-
Notifications
You must be signed in to change notification settings - Fork 2
/
untar.js
108 lines (92 loc) · 2.63 KB
/
untar.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/* globals Blob: false, Promise: false, console: false, Worker: false, ProgressivePromise: false */
const basePath = import.meta.url.replace(/[^\/]*$/, '');
var workerScriptUri = basePath + 'untar-worker.js'; // Included at compile time
var global = window || this;
var URL = global.URL || global.webkitURL;
/**
Returns a ProgressivePromise.
*/
function untar(arrayBuffer) {
if (!(arrayBuffer instanceof ArrayBuffer)) {
throw new TypeError("arrayBuffer is not an instance of ArrayBuffer.");
}
if (!global.Worker) {
throw new Error("Worker implementation is not available in this environment.");
}
return new ProgressivePromise(async function(resolve, reject, progress) {
const _readBlob = async (src, text) => {
const res = await fetch(src);
return await res.blob();
};
var worker = new Worker(URL.createObjectURL(await _readBlob(workerScriptUri)));
var files = [];
worker.onerror = function(err) {
reject(err);
};
worker.onmessage = function(message) {
message = message.data;
switch (message.type) {
case "log":
console[message.data.level]("Worker: " + message.data.msg);
break;
case "extract":
var file = decorateExtractedFile(message.data);
files.push(file);
progress(file);
break;
case "complete":
worker.terminate();
resolve(files);
break;
case "error":
//console.log("error message");
worker.terminate();
reject(new Error(message.data.message));
break;
default:
worker.terminate();
reject(new Error("Unknown message from worker: " + message.type));
break;
}
};
//console.info("Sending arraybuffer to worker for extraction.");
worker.postMessage({ type: "extract", buffer: arrayBuffer }, [arrayBuffer]);
});
}
window.untar = untar;
var decoratedFileProps = {
blob: {
get: function() {
return this._blob || (this._blob = new Blob([this.buffer]));
}
},
getBlobUrl: {
value: function() {
return this._blobUrl || (this._blobUrl = URL.createObjectURL(this.blob));
}
},
readAsString: {
value: function() {
var buffer = this.buffer;
var charCount = buffer.byteLength;
var charSize = 1;
var byteCount = charCount * charSize;
var bufferView = new DataView(buffer);
var charCodes = [];
for (var i = 0; i < charCount; ++i) {
var charCode = bufferView.getUint8(i * charSize, true);
charCodes.push(charCode);
}
return (this._string = String.fromCharCode.apply(null, charCodes));
}
},
readAsJSON: {
value: function() {
return JSON.parse(this.readAsString());
}
}
};
function decorateExtractedFile(file) {
Object.defineProperties(file, decoratedFileProps);
return file;
}