single-file-core 1.1.78 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4955 @@
1
+ const { Array, Object, String, Number, BigInt, Math, Date, Map, Set, Response, URL, Error, Uint8Array, Uint16Array, Uint32Array, DataView, Blob, Promise, TextEncoder, TextDecoder, document, crypto, btoa, TransformStream, ReadableStream, WritableStream, CompressionStream, DecompressionStream, navigator, Worker } = globalThis;
2
+
3
+ /*
4
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice,
10
+ this list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright
13
+ notice, this list of conditions and the following disclaimer in
14
+ the documentation and/or other materials provided with the distribution.
15
+
16
+ 3. The names of the authors may not be used to endorse or promote products
17
+ derived from this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
20
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
21
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
22
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
23
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
25
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
28
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
+ */
30
+
31
+ const MAX_32_BITS = 0xffffffff;
32
+ const MAX_16_BITS = 0xffff;
33
+ const COMPRESSION_METHOD_DEFLATE = 0x08;
34
+ const COMPRESSION_METHOD_STORE = 0x00;
35
+ const COMPRESSION_METHOD_AES = 0x63;
36
+
37
+ const LOCAL_FILE_HEADER_SIGNATURE = 0x04034b50;
38
+ const SPLIT_ZIP_FILE_SIGNATURE = 0x08074b50;
39
+ const DATA_DESCRIPTOR_RECORD_SIGNATURE = SPLIT_ZIP_FILE_SIGNATURE;
40
+ const CENTRAL_FILE_HEADER_SIGNATURE = 0x02014b50;
41
+ const END_OF_CENTRAL_DIR_SIGNATURE = 0x06054b50;
42
+ const ZIP64_END_OF_CENTRAL_DIR_SIGNATURE = 0x06064b50;
43
+ const ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE = 0x07064b50;
44
+ const END_OF_CENTRAL_DIR_LENGTH = 22;
45
+ const ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH = 20;
46
+ const ZIP64_END_OF_CENTRAL_DIR_LENGTH = 56;
47
+ const ZIP64_END_OF_CENTRAL_DIR_TOTAL_LENGTH = END_OF_CENTRAL_DIR_LENGTH + ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH + ZIP64_END_OF_CENTRAL_DIR_LENGTH;
48
+
49
+ const EXTRAFIELD_TYPE_ZIP64 = 0x0001;
50
+ const EXTRAFIELD_TYPE_AES = 0x9901;
51
+ const EXTRAFIELD_TYPE_NTFS = 0x000a;
52
+ const EXTRAFIELD_TYPE_NTFS_TAG1 = 0x0001;
53
+ const EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP = 0x5455;
54
+ const EXTRAFIELD_TYPE_UNICODE_PATH = 0x7075;
55
+ const EXTRAFIELD_TYPE_UNICODE_COMMENT = 0x6375;
56
+ const EXTRAFIELD_TYPE_USDZ = 0x1986;
57
+
58
+ const BITFLAG_ENCRYPTED = 0x01;
59
+ const BITFLAG_LEVEL = 0x06;
60
+ const BITFLAG_DATA_DESCRIPTOR = 0x0008;
61
+ const BITFLAG_LANG_ENCODING_FLAG = 0x0800;
62
+ const FILE_ATTR_MSDOS_DIR_MASK = 0x10;
63
+
64
+ const VERSION_DEFLATE = 0x14;
65
+ const VERSION_ZIP64 = 0x2D;
66
+ const VERSION_AES = 0x33;
67
+
68
+ const DIRECTORY_SIGNATURE = "/";
69
+
70
+ const MAX_DATE = new Date(2107, 11, 31);
71
+ const MIN_DATE = new Date(1980, 0, 1);
72
+
73
+ const UNDEFINED_VALUE = undefined;
74
+ const UNDEFINED_TYPE$1 = "undefined";
75
+ const FUNCTION_TYPE$1 = "function";
76
+
77
+ /*
78
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
79
+
80
+ Redistribution and use in source and binary forms, with or without
81
+ modification, are permitted provided that the following conditions are met:
82
+
83
+ 1. Redistributions of source code must retain the above copyright notice,
84
+ this list of conditions and the following disclaimer.
85
+
86
+ 2. Redistributions in binary form must reproduce the above copyright
87
+ notice, this list of conditions and the following disclaimer in
88
+ the documentation and/or other materials provided with the distribution.
89
+
90
+ 3. The names of the authors may not be used to endorse or promote products
91
+ derived from this software without specific prior written permission.
92
+
93
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
94
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
95
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
96
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
97
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
98
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
99
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
100
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
101
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
102
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
103
+ */
104
+
105
+ class StreamAdapter {
106
+
107
+ constructor(Codec) {
108
+ return class extends TransformStream {
109
+ constructor(_format, options) {
110
+ const codec = new Codec(options);
111
+ super({
112
+ transform(chunk, controller) {
113
+ controller.enqueue(codec.append(chunk));
114
+ },
115
+ flush(controller) {
116
+ const chunk = codec.flush();
117
+ if (chunk) {
118
+ controller.enqueue(chunk);
119
+ }
120
+ }
121
+ });
122
+ }
123
+ };
124
+ }
125
+ }
126
+
127
+ /*
128
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
129
+
130
+ Redistribution and use in source and binary forms, with or without
131
+ modification, are permitted provided that the following conditions are met:
132
+
133
+ 1. Redistributions of source code must retain the above copyright notice,
134
+ this list of conditions and the following disclaimer.
135
+
136
+ 2. Redistributions in binary form must reproduce the above copyright
137
+ notice, this list of conditions and the following disclaimer in
138
+ the documentation and/or other materials provided with the distribution.
139
+
140
+ 3. The names of the authors may not be used to endorse or promote products
141
+ derived from this software without specific prior written permission.
142
+
143
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
144
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
145
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
146
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
147
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
148
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
149
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
150
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
151
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
152
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
153
+ */
154
+
155
+ const MINIMUM_CHUNK_SIZE = 64;
156
+ let maxWorkers = 2;
157
+ try {
158
+ if (typeof navigator != UNDEFINED_TYPE$1 && navigator.hardwareConcurrency) {
159
+ maxWorkers = navigator.hardwareConcurrency;
160
+ }
161
+ } catch (_error) {
162
+ // ignored
163
+ }
164
+ const DEFAULT_CONFIGURATION = {
165
+ chunkSize: 512 * 1024,
166
+ maxWorkers,
167
+ terminateWorkerTimeout: 5000,
168
+ useWebWorkers: true,
169
+ useCompressionStream: true,
170
+ workerScripts: UNDEFINED_VALUE,
171
+ CompressionStreamNative: typeof CompressionStream != UNDEFINED_TYPE$1 && CompressionStream,
172
+ DecompressionStreamNative: typeof DecompressionStream != UNDEFINED_TYPE$1 && DecompressionStream
173
+ };
174
+
175
+ const config = Object.assign({}, DEFAULT_CONFIGURATION);
176
+
177
+ function getConfiguration() {
178
+ return config;
179
+ }
180
+
181
+ function getChunkSize(config) {
182
+ return Math.max(config.chunkSize, MINIMUM_CHUNK_SIZE);
183
+ }
184
+
185
+ function configure(configuration) {
186
+ const {
187
+ baseURL,
188
+ chunkSize,
189
+ maxWorkers,
190
+ terminateWorkerTimeout,
191
+ useCompressionStream,
192
+ useWebWorkers,
193
+ Deflate,
194
+ Inflate,
195
+ CompressionStream,
196
+ DecompressionStream,
197
+ workerScripts
198
+ } = configuration;
199
+ setIfDefined("baseURL", baseURL);
200
+ setIfDefined("chunkSize", chunkSize);
201
+ setIfDefined("maxWorkers", maxWorkers);
202
+ setIfDefined("terminateWorkerTimeout", terminateWorkerTimeout);
203
+ setIfDefined("useCompressionStream", useCompressionStream);
204
+ setIfDefined("useWebWorkers", useWebWorkers);
205
+ if (Deflate) {
206
+ config.CompressionStream = new StreamAdapter(Deflate);
207
+ }
208
+ if (Inflate) {
209
+ config.DecompressionStream = new StreamAdapter(Inflate);
210
+ }
211
+ setIfDefined("CompressionStream", CompressionStream);
212
+ setIfDefined("DecompressionStream", DecompressionStream);
213
+ if (workerScripts !== UNDEFINED_VALUE) {
214
+ const { deflate, inflate } = workerScripts;
215
+ if (deflate || inflate) {
216
+ if (!config.workerScripts) {
217
+ config.workerScripts = {};
218
+ }
219
+ }
220
+ if (deflate) {
221
+ if (!Array.isArray(deflate)) {
222
+ throw new Error("workerScripts.deflate must be an array");
223
+ }
224
+ config.workerScripts.deflate = deflate;
225
+ }
226
+ if (inflate) {
227
+ if (!Array.isArray(inflate)) {
228
+ throw new Error("workerScripts.inflate must be an array");
229
+ }
230
+ config.workerScripts.inflate = inflate;
231
+ }
232
+ }
233
+ }
234
+
235
+ function setIfDefined(propertyName, propertyValue) {
236
+ if (propertyValue !== UNDEFINED_VALUE) {
237
+ config[propertyName] = propertyValue;
238
+ }
239
+ }
240
+
241
+ function e(e){const t=()=>URL.createObjectURL(new Blob(['const{Array:e,Object:t,Number:n,Math:r,Error:s,Uint8Array:a,Uint16Array:i,Uint32Array:o,Int32Array:l,Map:c,DataView:h,Promise:f,TextEncoder:u,crypto:p,postMessage:d,TransformStream:g,ReadableStream:w,WritableStream:v,CompressionStream:y,DecompressionStream:b}=self;class m{constructor(e){return class extends g{constructor(t,n){const r=new e(n);super({transform(e,t){t.enqueue(r.append(e))},flush(e){const t=r.flush();t&&e.enqueue(t)}})}}}}const _=[];for(let e=0;256>e;e++){let t=e;for(let e=0;8>e;e++)1&t?t=t>>>1^3988292384:t>>>=1;_[e]=t}class k{constructor(e){this.crc=e||-1}append(e){let t=0|this.crc;for(let n=0,r=0|e.length;r>n;n++)t=t>>>8^_[255&(t^e[n])];this.crc=t}get(){return~this.crc}}class S extends g{constructor(){let e;const t=new k;super({transform(e,n){t.append(e),n.enqueue(e)},flush(){const n=new a(4);new h(n.buffer).setUint32(0,t.get()),e.value=n}}),e=this}}const z={concat(e,t){if(0===e.length||0===t.length)return e.concat(t);const n=e[e.length-1],r=z.getPartial(n);return 32===r?e.concat(t):z._shiftRight(t,r,0|n,e.slice(0,e.length-1))},bitLength(e){const t=e.length;if(0===t)return 0;const n=e[t-1];return 32*(t-1)+z.getPartial(n)},clamp(e,t){if(32*e.length<t)return e;const n=(e=e.slice(0,r.ceil(t/32))).length;return t&=31,n>0&&t&&(e[n-1]=z.partial(t,e[n-1]&2147483648>>t-1,1)),e},partial:(e,t,n)=>32===e?t:(n?0|t:t<<32-e)+1099511627776*e,getPartial:e=>r.round(e/1099511627776)||32,_shiftRight(e,t,n,r){for(void 0===r&&(r=[]);t>=32;t-=32)r.push(n),n=0;if(0===t)return r.concat(e);for(let s=0;s<e.length;s++)r.push(n|e[s]>>>t),n=e[s]<<32-t;const s=e.length?e[e.length-1]:0,a=z.getPartial(s);return r.push(z.partial(t+a&31,t+a>32?n:r.pop(),1)),r}},D={bytes:{fromBits(e){const t=z.bitLength(e)/8,n=new a(t);let r;for(let s=0;t>s;s++)0==(3&s)&&(r=e[s/4]),n[s]=r>>>24,r<<=8;return n},toBits(e){const t=[];let n,r=0;for(n=0;n<e.length;n++)r=r<<8|e[n],3==(3&n)&&(t.push(r),r=0);return 3&n&&t.push(z.partial(8*(3&n),r)),t}}},C=class{constructor(e){const t=this;t.blockSize=512,t._init=[1732584193,4023233417,2562383102,271733878,3285377520],t._key=[1518500249,1859775393,2400959708,3395469782],e?(t._h=e._h.slice(0),t._buffer=e._buffer.slice(0),t._length=e._length):t.reset()}reset(){const e=this;return e._h=e._init.slice(0),e._buffer=[],e._length=0,e}update(e){const t=this;"string"==typeof e&&(e=D.utf8String.toBits(e));const n=t._buffer=z.concat(t._buffer,e),r=t._length,a=t._length=r+z.bitLength(e);if(a>9007199254740991)throw new s("Cannot hash more than 2^53 - 1 bits");const i=new o(n);let l=0;for(let e=t.blockSize+r-(t.blockSize+r&t.blockSize-1);a>=e;e+=t.blockSize)t._block(i.subarray(16*l,16*(l+1))),l+=1;return n.splice(0,16*l),t}finalize(){const e=this;let t=e._buffer;const n=e._h;t=z.concat(t,[z.partial(1,1)]);for(let e=t.length+2;15&e;e++)t.push(0);for(t.push(r.floor(e._length/4294967296)),t.push(0|e._length);t.length;)e._block(t.splice(0,16));return e.reset(),n}_f(e,t,n,r){return e>19?e>39?e>59?e>79?void 0:t^n^r:t&n|t&r|n&r:t^n^r:t&n|~t&r}_S(e,t){return t<<e|t>>>32-e}_block(t){const n=this,s=n._h,a=e(80);for(let e=0;16>e;e++)a[e]=t[e];let i=s[0],o=s[1],l=s[2],c=s[3],h=s[4];for(let e=0;79>=e;e++){16>e||(a[e]=n._S(1,a[e-3]^a[e-8]^a[e-14]^a[e-16]));const t=n._S(5,i)+n._f(e,o,l,c)+h+a[e]+n._key[r.floor(e/20)]|0;h=c,c=l,l=n._S(30,o),o=i,i=t}s[0]=s[0]+i|0,s[1]=s[1]+o|0,s[2]=s[2]+l|0,s[3]=s[3]+c|0,s[4]=s[4]+h|0}},I={getRandomValues(e){const t=new o(e.buffer),n=e=>{let t=987654321;const n=4294967295;return()=>(t=36969*(65535&t)+(t>>16)&n,(((t<<16)+(e=18e3*(65535&e)+(e>>16)&n)&n)/4294967296+.5)*(r.random()>.5?1:-1))};for(let s,a=0;a<e.length;a+=4){const e=n(4294967296*(s||r.random()));s=987654071*e(),t[a/4]=4294967296*e()|0}return e}},x={importKey:e=>new x.hmacSha1(D.bytes.toBits(e)),pbkdf2(e,t,n,r){if(n=n||1e4,0>r||0>n)throw new s("invalid params to pbkdf2");const a=1+(r>>5)<<2;let i,o,l,c,f;const u=new ArrayBuffer(a),p=new h(u);let d=0;const g=z;for(t=D.bytes.toBits(t),f=1;(a||1)>d;f++){for(i=o=e.encrypt(g.concat(t,[f])),l=1;n>l;l++)for(o=e.encrypt(o),c=0;c<o.length;c++)i[c]^=o[c];for(l=0;(a||1)>d&&l<i.length;l++)p.setInt32(d,i[l]),d+=4}return u.slice(0,r/8)},hmacSha1:class{constructor(e){const t=this,n=t._hash=C,r=[[],[]];t._baseHash=[new n,new n];const s=t._baseHash[0].blockSize/32;e.length>s&&(e=(new n).update(e).finalize());for(let t=0;s>t;t++)r[0][t]=909522486^e[t],r[1][t]=1549556828^e[t];t._baseHash[0].update(r[0]),t._baseHash[1].update(r[1]),t._resultHash=new n(t._baseHash[0])}reset(){const e=this;e._resultHash=new e._hash(e._baseHash[0]),e._updated=!1}update(e){this._updated=!0,this._resultHash.update(e)}digest(){const e=this,t=e._resultHash.finalize(),n=new e._hash(e._baseHash[1]).update(t).finalize();return e.reset(),n}encrypt(e){if(this._updated)throw new s("encrypt on already updated hmac called!");return this.update(e),this.digest(e)}}},A=void 0!==p&&"function"==typeof p.getRandomValues,T="Invalid password",R="Invalid signature",H="zipjs-abort-check-password";function q(e){return A?p.getRandomValues(e):I.getRandomValues(e)}const B=16,K={name:"PBKDF2"},V=t.assign({hash:{name:"HMAC"}},K),P=t.assign({iterations:1e3,hash:{name:"SHA-1"}},K),E=["deriveBits"],U=[8,12,16],W=[16,24,32],M=10,N=[0,0,0,0],O="undefined",F="function",L=typeof p!=O,j=L&&p.subtle,G=L&&typeof j!=O,X=D.bytes,J=class{constructor(e){const t=this;t._tables=[[[],[],[],[],[]],[[],[],[],[],[]]],t._tables[0][0][0]||t._precompute();const n=t._tables[0][4],r=t._tables[1],a=e.length;let i,o,l,c=1;if(4!==a&&6!==a&&8!==a)throw new s("invalid aes key size");for(t._key=[o=e.slice(0),l=[]],i=a;4*a+28>i;i++){let e=o[i-1];(i%a==0||8===a&&i%a==4)&&(e=n[e>>>24]<<24^n[e>>16&255]<<16^n[e>>8&255]<<8^n[255&e],i%a==0&&(e=e<<8^e>>>24^c<<24,c=c<<1^283*(c>>7))),o[i]=o[i-a]^e}for(let e=0;i;e++,i--){const t=o[3&e?i:i-4];l[e]=4>=i||4>e?t:r[0][n[t>>>24]]^r[1][n[t>>16&255]]^r[2][n[t>>8&255]]^r[3][n[255&t]]}}encrypt(e){return this._crypt(e,0)}decrypt(e){return this._crypt(e,1)}_precompute(){const e=this._tables[0],t=this._tables[1],n=e[4],r=t[4],s=[],a=[];let i,o,l,c;for(let e=0;256>e;e++)a[(s[e]=e<<1^283*(e>>7))^e]=e;for(let h=i=0;!n[h];h^=o||1,i=a[i]||1){let a=i^i<<1^i<<2^i<<3^i<<4;a=a>>8^255&a^99,n[h]=a,r[a]=h,c=s[l=s[o=s[h]]];let f=16843009*c^65537*l^257*o^16843008*h,u=257*s[a]^16843008*a;for(let n=0;4>n;n++)e[n][h]=u=u<<24^u>>>8,t[n][a]=f=f<<24^f>>>8}for(let n=0;5>n;n++)e[n]=e[n].slice(0),t[n]=t[n].slice(0)}_crypt(e,t){if(4!==e.length)throw new s("invalid aes block size");const n=this._key[t],r=n.length/4-2,a=[0,0,0,0],i=this._tables[t],o=i[0],l=i[1],c=i[2],h=i[3],f=i[4];let u,p,d,g=e[0]^n[0],w=e[t?3:1]^n[1],v=e[2]^n[2],y=e[t?1:3]^n[3],b=4;for(let e=0;r>e;e++)u=o[g>>>24]^l[w>>16&255]^c[v>>8&255]^h[255&y]^n[b],p=o[w>>>24]^l[v>>16&255]^c[y>>8&255]^h[255&g]^n[b+1],d=o[v>>>24]^l[y>>16&255]^c[g>>8&255]^h[255&w]^n[b+2],y=o[y>>>24]^l[g>>16&255]^c[w>>8&255]^h[255&v]^n[b+3],b+=4,g=u,w=p,v=d;for(let e=0;4>e;e++)a[t?3&-e:e]=f[g>>>24]<<24^f[w>>16&255]<<16^f[v>>8&255]<<8^f[255&y]^n[b++],u=g,g=w,w=v,v=y,y=u;return a}},Q=class{constructor(e,t){this._prf=e,this._initIv=t,this._iv=t}reset(){this._iv=this._initIv}update(e){return this.calculate(this._prf,e,this._iv)}incWord(e){if(255==(e>>24&255)){let t=e>>16&255,n=e>>8&255,r=255&e;255===t?(t=0,255===n?(n=0,255===r?r=0:++r):++n):++t,e=0,e+=t<<16,e+=n<<8,e+=r}else e+=1<<24;return e}incCounter(e){0===(e[0]=this.incWord(e[0]))&&(e[1]=this.incWord(e[1]))}calculate(e,t,n){let r;if(!(r=t.length))return[];const s=z.bitLength(t);for(let s=0;r>s;s+=4){this.incCounter(n);const r=e.encrypt(n);t[s]^=r[0],t[s+1]^=r[1],t[s+2]^=r[2],t[s+3]^=r[3]}return z.clamp(t,s)}},Y=x.hmacSha1;let Z=L&&G&&typeof j.importKey==F,$=L&&G&&typeof j.deriveBits==F;class ee extends g{constructor({password:e,signed:n,encryptionStrength:r,checkPasswordOnly:i}){super({start(){t.assign(this,{ready:new f((e=>this.resolveReady=e)),password:e,signed:n,strength:r-1,pending:new a})},async transform(e,t){const n=this,{password:r,strength:o,resolveReady:l,ready:c}=n;r?(await(async(e,t,n,r)=>{const a=await re(e,t,n,ae(r,0,U[t])),i=ae(r,U[t]);if(a[0]!=i[0]||a[1]!=i[1])throw new s(T)})(n,o,r,ae(e,0,U[o]+2)),e=ae(e,U[o]+2),i?t.error(new s(H)):l()):await c;const h=new a(e.length-M-(e.length-M)%B);t.enqueue(ne(n,e,h,0,M,!0))},async flush(e){const{signed:t,ctr:n,hmac:r,pending:i,ready:o}=this;await o;const l=ae(i,0,i.length-M),c=ae(i,i.length-M);let h=new a;if(l.length){const e=oe(X,l);r.update(e);const t=n.update(e);h=ie(X,t)}if(t){const e=ae(ie(X,r.digest()),0,M);for(let t=0;M>t;t++)if(e[t]!=c[t])throw new s(R)}e.enqueue(h)}})}}class te extends g{constructor({password:e,encryptionStrength:n}){let r;super({start(){t.assign(this,{ready:new f((e=>this.resolveReady=e)),password:e,strength:n-1,pending:new a})},async transform(e,t){const n=this,{password:r,strength:s,resolveReady:i,ready:o}=n;let l=new a;r?(l=await(async(e,t,n)=>{const r=q(new a(U[t]));return se(r,await re(e,t,n,r))})(n,s,r),i()):await o;const c=new a(l.length+e.length-e.length%B);c.set(l,0),t.enqueue(ne(n,e,c,l.length,0))},async flush(e){const{ctr:t,hmac:n,pending:s,ready:i}=this;await i;let o=new a;if(s.length){const e=t.update(oe(X,s));n.update(e),o=ie(X,e)}r.signature=ie(X,n.digest()).slice(0,M),e.enqueue(se(o,r.signature))}}),r=this}}function ne(e,t,n,r,s,i){const{ctr:o,hmac:l,pending:c}=e,h=t.length-s;let f;for(c.length&&(t=se(c,t),n=((e,t)=>{if(t&&t>e.length){const n=e;(e=new a(t)).set(n,0)}return e})(n,h-h%B)),f=0;h-B>=f;f+=B){const e=oe(X,ae(t,f,f+B));i&&l.update(e);const s=o.update(e);i||l.update(s),n.set(ie(X,s),f+r)}return e.pending=ae(t,f),n}async function re(n,r,s,i){n.password=null;const o=(e=>{if(void 0===u){const t=new a((e=unescape(encodeURIComponent(e))).length);for(let n=0;n<t.length;n++)t[n]=e.charCodeAt(n);return t}return(new u).encode(e)})(s),l=await(async(e,t,n,r,s)=>{if(!Z)return x.importKey(t);try{return await j.importKey("raw",t,n,!1,s)}catch(e){return Z=!1,x.importKey(t)}})(0,o,V,0,E),c=await(async(e,t,n)=>{if(!$)return x.pbkdf2(t,e.salt,P.iterations,n);try{return await j.deriveBits(e,t,n)}catch(r){return $=!1,x.pbkdf2(t,e.salt,P.iterations,n)}})(t.assign({salt:i},P),l,8*(2*W[r]+2)),h=new a(c),f=oe(X,ae(h,0,W[r])),p=oe(X,ae(h,W[r],2*W[r])),d=ae(h,2*W[r]);return t.assign(n,{keys:{key:f,authentication:p,passwordVerification:d},ctr:new Q(new J(f),e.from(N)),hmac:new Y(p)}),d}function se(e,t){let n=e;return e.length+t.length&&(n=new a(e.length+t.length),n.set(e,0),n.set(t,e.length)),n}function ae(e,t,n){return e.subarray(t,n)}function ie(e,t){return e.fromBits(t)}function oe(e,t){return e.toBits(t)}class le extends g{constructor({password:e,passwordVerification:n,checkPasswordOnly:r}){super({start(){t.assign(this,{password:e,passwordVerification:n}),ue(this,e)},transform(e,t){const n=this;if(n.password){const t=he(n,e.subarray(0,12));if(n.password=null,t[11]!=n.passwordVerification)throw new s(T);e=e.subarray(12)}r?t.error(new s(H)):t.enqueue(he(n,e))}})}}class ce extends g{constructor({password:e,passwordVerification:n}){super({start(){t.assign(this,{password:e,passwordVerification:n}),ue(this,e)},transform(e,t){const n=this;let r,s;if(n.password){n.password=null;const t=q(new a(12));t[11]=n.passwordVerification,r=new a(e.length+t.length),r.set(fe(n,t),0),s=12}else r=new a(e.length),s=0;r.set(fe(n,e),s),t.enqueue(r)}})}}function he(e,t){const n=new a(t.length);for(let r=0;r<t.length;r++)n[r]=de(e)^t[r],pe(e,n[r]);return n}function fe(e,t){const n=new a(t.length);for(let r=0;r<t.length;r++)n[r]=de(e)^t[r],pe(e,t[r]);return n}function ue(e,n){const r=[305419896,591751049,878082192];t.assign(e,{keys:r,crcKey0:new k(r[0]),crcKey2:new k(r[2])});for(let t=0;t<n.length;t++)pe(e,n.charCodeAt(t))}function pe(e,t){let[n,s,a]=e.keys;e.crcKey0.append([t]),n=~e.crcKey0.get(),s=we(r.imul(we(s+ge(n)),134775813)+1),e.crcKey2.append([s>>>24]),a=~e.crcKey2.get(),e.keys=[n,s,a]}function de(e){const t=2|e.keys[2];return ge(r.imul(t,1^t)>>>8)}function ge(e){return 255&e}function we(e){return 4294967295&e}const ve="deflate-raw";class ye extends g{constructor(e,{chunkSize:t,CompressionStream:n,CompressionStreamNative:r}){super({});const{compressed:s,encrypted:a,useCompressionStream:i,zipCrypto:o,signed:l,level:c}=e,f=this;let u,p,d=me(super.readable);a&&!o||!l||(u=new S,d=Se(d,u)),s&&(d=ke(d,i,{level:c,chunkSize:t},r,n)),a&&(o?d=Se(d,new ce(e)):(p=new te(e),d=Se(d,p))),_e(f,d,(()=>{let e;a&&!o&&(e=p.signature),a&&!o||!l||(e=new h(u.value.buffer).getUint32(0)),f.signature=e}))}}class be extends g{constructor(e,{chunkSize:t,DecompressionStream:n,DecompressionStreamNative:r}){super({});const{zipCrypto:a,encrypted:i,signed:o,signature:l,compressed:c,useCompressionStream:f}=e;let u,p,d=me(super.readable);i&&(a?d=Se(d,new le(e)):(p=new ee(e),d=Se(d,p))),c&&(d=ke(d,f,{chunkSize:t},r,n)),i&&!a||!o||(u=new S,d=Se(d,u)),_e(this,d,(()=>{if((!i||a)&&o){const e=new h(u.value.buffer);if(l!=e.getUint32(0,!1))throw new s(R)}}))}}function me(e){return Se(e,new g({transform(e,t){e&&e.length&&t.enqueue(e)}}))}function _e(e,n,r){n=Se(n,new g({flush:r})),t.defineProperty(e,"readable",{get:()=>n})}function ke(e,t,n,r,s){try{e=Se(e,new(t&&r?r:s)(ve,n))}catch(r){if(!t)throw r;e=Se(e,new s(ve,n))}return e}function Se(e,t){return e.pipeThrough(t)}const ze="data";class De extends g{constructor(e,n){super({});const r=this,{codecType:s}=e;let a;s.startsWith("deflate")?a=ye:s.startsWith("inflate")&&(a=be);let i=0;const o=new a(e,n),l=super.readable,c=new g({transform(e,t){e&&e.length&&(i+=e.length,t.enqueue(e))},flush(){const{signature:e}=o;t.assign(r,{signature:e,size:i})}});t.defineProperty(r,"readable",{get:()=>l.pipeThrough(o).pipeThrough(c)})}}const Ce=new c,Ie=new c;let xe=0;async function Ae(e){try{const{options:t,scripts:r,config:s}=e;r&&r.length&&importScripts.apply(void 0,r),self.initCodec&&self.initCodec(),s.CompressionStreamNative=self.CompressionStream,s.DecompressionStreamNative=self.DecompressionStream,self.Deflate&&(s.CompressionStream=new m(self.Deflate)),self.Inflate&&(s.DecompressionStream=new m(self.Inflate));const a={highWaterMark:1,size:()=>s.chunkSize},i=e.readable||new w({async pull(e){const t=new f((e=>Ce.set(xe,e)));Te({type:"pull",messageId:xe}),xe=(xe+1)%n.MAX_SAFE_INTEGER;const{value:r,done:s}=await t;e.enqueue(r),s&&e.close()}},a),o=e.writable||new v({async write(e){let t;const r=new f((e=>t=e));Ie.set(xe,t),Te({type:ze,value:e,messageId:xe}),xe=(xe+1)%n.MAX_SAFE_INTEGER,await r}},a),l=new De(t,s);await i.pipeThrough(l).pipeTo(o,{preventClose:!0,preventAbort:!0});try{await o.getWriter().close()}catch(e){}const{signature:c,size:h}=l;Te({type:"close",result:{signature:c,size:h}})}catch(e){Re(e)}}function Te(e){let{value:t}=e;if(t)if(t.length)try{t=new a(t),e.value=t.buffer,d(e,[e.value])}catch(t){d(e)}else d(e);else d(e)}function Re(e=new s("Unknown error")){const{message:t,stack:n,code:r,name:a}=e;d({error:{message:t,stack:n,code:r,name:a}})}addEventListener("message",(({data:e})=>{const{type:t,messageId:n,value:r,done:s}=e;try{if("start"==t&&Ae(e),t==ze){const e=Ce.get(n);Ce.delete(n),e({value:new a(r),done:s})}if("ack"==t){const e=Ie.get(n);Ie.delete(n),e()}}catch(e){Re(e)}}));var He=a,qe=i,Be=l,Ke=new He([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ve=new He([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Pe=new He([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ee=(e,t)=>{for(var n=new qe(31),r=0;31>r;++r)n[r]=t+=1<<e[r-1];var s=new Be(n[30]);for(r=1;30>r;++r)for(var a=n[r];a<n[r+1];++a)s[a]=a-n[r]<<5|r;return{b:n,r:s}},Ue=Ee(Ke,2),We=Ue.b,Me=Ue.r;We[28]=258,Me[258]=28;for(var Ne=Ee(Ve,0),Oe=Ne.b,Fe=Ne.r,Le=new qe(32768),je=0;32768>je;++je){var Ge=(43690&je)>>1|(21845&je)<<1;Ge=(61680&(Ge=(52428&Ge)>>2|(13107&Ge)<<2))>>4|(3855&Ge)<<4,Le[je]=((65280&Ge)>>8|(255&Ge)<<8)>>1}var Xe=(e,t,n)=>{for(var r=e.length,s=0,a=new qe(t);r>s;++s)e[s]&&++a[e[s]-1];var i,o=new qe(t);for(s=1;t>s;++s)o[s]=o[s-1]+a[s-1]<<1;if(n){i=new qe(1<<t);var l=15-t;for(s=0;r>s;++s)if(e[s])for(var c=s<<4|e[s],h=t-e[s],f=o[e[s]-1]++<<h,u=f|(1<<h)-1;u>=f;++f)i[Le[f]>>l]=c}else for(i=new qe(r),s=0;r>s;++s)e[s]&&(i[s]=Le[o[e[s]-1]++]>>15-e[s]);return i},Je=new He(288);for(je=0;144>je;++je)Je[je]=8;for(je=144;256>je;++je)Je[je]=9;for(je=256;280>je;++je)Je[je]=7;for(je=280;288>je;++je)Je[je]=8;var Qe=new He(32);for(je=0;32>je;++je)Qe[je]=5;var Ye=Xe(Je,9,0),Ze=Xe(Je,9,1),$e=Xe(Qe,5,0),et=Xe(Qe,5,1),tt=e=>{for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},nt=(e,t,n)=>{var r=t/8|0;return(e[r]|e[r+1]<<8)>>(7&t)&n},rt=(e,t)=>{var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},st=e=>(e+7)/8|0,at=(e,t,n)=>{(null==t||0>t)&&(t=0),(null==n||n>e.length)&&(n=e.length);var r=new He(n-t);return r.set(e.subarray(t,n)),r},it=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ot=(e,t,n)=>{var r=new s(t||it[e]);if(r.code=e,s.captureStackTrace&&s.captureStackTrace(r,ot),!n)throw r;return r},lt=(e,t,n)=>{n<<=7&t;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},ct=(e,t,n)=>{n<<=7&t;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8,e[r+2]|=n>>16},ht=(e,t)=>{for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var s=n.length,a=n.slice();if(!s)return{t:vt,l:0};if(1==s){var i=new He(n[0].s+1);return i[n[0].s]=1,{t:i,l:1}}n.sort(((e,t)=>e.f-t.f)),n.push({s:-1,f:25001});var o=n[0],l=n[1],c=0,h=1,f=2;for(n[0]={s:-1,f:o.f+l.f,l:o,r:l};h!=s-1;)o=n[n[c].f<n[f].f?c++:f++],l=n[c!=h&&n[c].f<n[f].f?c++:f++],n[h++]={s:-1,f:o.f+l.f,l:o,r:l};var u=a[0].s;for(r=1;s>r;++r)a[r].s>u&&(u=a[r].s);var p=new qe(u+1),d=ft(n[h-1],p,0);if(d>t){r=0;var g=0,w=d-t,v=1<<w;for(a.sort(((e,t)=>p[t.s]-p[e.s]||e.f-t.f));s>r;++r){var y=a[r].s;if(p[y]<=t)break;g+=v-(1<<d-p[y]),p[y]=t}for(g>>=w;g>0;){var b=a[r].s;p[b]<t?g-=1<<t-p[b]++-1:++r}for(;r>=0&&g;--r){var m=a[r].s;p[m]==t&&(--p[m],++g)}d=t}return{t:new He(p),l:d}},ft=(e,t,n)=>-1==e.s?r.max(ft(e.l,t,n+1),ft(e.r,t,n+1)):t[e.s]=n,ut=e=>{for(var t=e.length;t&&!e[--t];);for(var n=new qe(++t),r=0,s=e[0],a=1,i=e=>{n[r++]=e},o=1;t>=o;++o)if(e[o]==s&&o!=t)++a;else{if(!s&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(s),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(s);a=1,s=e[o]}return{c:n.subarray(0,r),n:t}},pt=(e,t)=>{for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},dt=(e,t,n)=>{var r=n.length,s=st(t+2);e[s]=255&r,e[s+1]=r>>8,e[s+2]=255^e[s],e[s+3]=255^e[s+1];for(var a=0;r>a;++a)e[s+a+4]=n[a];return 8*(s+4+r)},gt=(e,t,n,r,s,a,i,o,l,c,h)=>{lt(t,h++,n),++s[256];for(var f=ht(s,15),u=f.t,p=f.l,d=ht(a,15),g=d.t,w=d.l,v=ut(u),y=v.c,b=v.n,m=ut(g),_=m.c,k=m.n,S=new qe(19),z=0;z<y.length;++z)++S[31&y[z]];for(z=0;z<_.length;++z)++S[31&_[z]];for(var D=ht(S,7),C=D.t,I=D.l,x=19;x>4&&!C[Pe[x-1]];--x);var A,T,R,H,q=c+5<<3,B=pt(s,Je)+pt(a,Qe)+i,K=pt(s,u)+pt(a,g)+i+14+3*x+pt(S,C)+2*S[16]+3*S[17]+7*S[18];if(l>=0&&B>=q&&K>=q)return dt(t,h,e.subarray(l,l+c));if(lt(t,h,1+(B>K)),h+=2,B>K){A=Xe(u,p,0),T=u,R=Xe(g,w,0),H=g;var V=Xe(C,I,0);for(lt(t,h,b-257),lt(t,h+5,k-1),lt(t,h+10,x-4),h+=14,z=0;x>z;++z)lt(t,h+3*z,C[Pe[z]]);h+=3*x;for(var P=[y,_],E=0;2>E;++E){var U=P[E];for(z=0;z<U.length;++z){var W=31&U[z];lt(t,h,V[W]),h+=C[W],W>15&&(lt(t,h,U[z]>>5&127),h+=U[z]>>12)}}}else A=Ye,T=Je,R=$e,H=Qe;for(z=0;o>z;++z){var M=r[z];if(M>255){ct(t,h,A[257+(W=M>>18&31)]),h+=T[W+257],W>7&&(lt(t,h,M>>23&31),h+=Ke[W]);var N=31&M;ct(t,h,R[N]),h+=H[N],N>3&&(ct(t,h,M>>5&8191),h+=Ve[N])}else ct(t,h,A[M]),h+=T[M]}return ct(t,h,A[256]),h+T[256]},wt=new Be([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),vt=new He(0),yt=function(){function e(e,t){if("function"==typeof e&&(t=e,e={}),this.ondata=t,this.o=e||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new He(98304),this.o.dictionary){var n=this.o.dictionary.subarray(-32768);this.b.set(n,32768-n.length),this.s.i=32768-n.length}}return e.prototype.p=function(e,t){this.ondata(((e,t,n,s,a)=>{if(!a&&(a={l:1},t.dictionary)){var i=t.dictionary.subarray(-32768),o=new He(i.length+e.length);o.set(i),o.set(e,i.length),e=o,a.w=i.length}return((e,t,n,s,a,i)=>{var o=i.z||e.length,l=new He(0+o+5*(1+r.ceil(o/7e3))+0),c=l.subarray(0,l.length-0),h=i.l,f=7&(i.r||0);if(t){f&&(c[0]=i.r>>3);for(var u=wt[t-1],p=u>>13,d=8191&u,g=(1<<n)-1,w=i.p||new qe(32768),v=i.h||new qe(g+1),y=r.ceil(n/3),b=2*y,m=t=>(e[t]^e[t+1]<<y^e[t+2]<<b)&g,_=new Be(25e3),k=new qe(288),S=new qe(32),z=0,D=0,C=i.i||0,I=0,x=i.w||0,A=0;o>C+2;++C){var T=m(C),R=32767&C,H=v[T];if(w[R]=H,v[T]=R,C>=x){var q=o-C;if((z>7e3||I>24576)&&(q>423||!h)){f=gt(e,c,0,_,k,S,D,I,A,C-A,f),I=z=D=0,A=C;for(var B=0;286>B;++B)k[B]=0;for(B=0;30>B;++B)S[B]=0}var K=2,V=0,P=d,E=R-H&32767;if(q>2&&T==m(C-E))for(var U=r.min(p,q)-1,W=r.min(32767,C),M=r.min(258,q);W>=E&&--P&&R!=H;){if(e[C+K]==e[C+K-E]){for(var N=0;M>N&&e[C+N]==e[C+N-E];++N);if(N>K){if(K=N,V=E,N>U)break;var O=r.min(E,N-2),F=0;for(B=0;O>B;++B){var L=C-E+B&32767,j=L-w[L]&32767;j>F&&(F=j,H=L)}}}E+=(R=H)-(H=w[R])&32767}if(V){_[I++]=268435456|Me[K]<<18|Fe[V];var G=31&Me[K],X=31&Fe[V];D+=Ke[G]+Ve[X],++k[257+G],++S[X],x=C+K,++z}else _[I++]=e[C],++k[e[C]]}}for(C=r.max(C,x);o>C;++C)_[I++]=e[C],++k[e[C]];f=gt(e,c,h,_,k,S,D,I,A,C-A,f),h||(i.r=7&f|c[f/8|0]<<3,f-=7,i.h=v,i.p=w,i.i=C,i.w=x)}else{for(C=i.w||0;o+h>C;C+=65535){var J=C+65535;o>J||(c[f/8|0]=h,J=o),f=dt(c,f+1,e.subarray(C,J))}i.i=o}return at(l,0,0+st(f)+0)})(e,null==t.level?6:t.level,null==t.mem?r.ceil(1.5*r.max(8,r.min(13,r.log(e.length)))):12+t.mem,0,0,a)})(e,this.o,0,0,this.s),t)},e.prototype.push=function(e,t){this.ondata||ot(5),this.s.l&&ot(4);var n=e.length+this.s.z;if(n>this.b.length){if(n>2*this.b.length-32768){var r=new He(-32768&n);r.set(this.b.subarray(0,this.s.z)),this.b=r}var s=this.b.length-this.s.z;s&&(this.b.set(e.subarray(0,s),this.s.z),this.s.z=this.b.length,this.p(this.b,!1)),this.b.set(this.b.subarray(-32768)),this.b.set(e.subarray(s),32768),this.s.z=e.length-s+32768,this.s.i=32766,this.s.w=32768}else this.b.set(e,this.s.z),this.s.z+=e.length;this.s.l=1&t,(this.s.z>this.s.w+8191||t)&&(this.p(this.b,t||!1),this.s.w=this.s.i,this.s.i-=2)},e}(),bt=function(){function e(e,t){"function"==typeof e&&(t=e,e={}),this.ondata=t;var n=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:n?n.length:0},this.o=new He(32768),this.p=new He(0),n&&this.o.set(n)}return e.prototype.e=function(e){if(this.ondata||ot(5),this.d&&ot(4),this.p.length){if(e.length){var t=new He(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}}else this.p=e},e.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,n=((e,t,n)=>{var s=e.length;if(!s||t.f&&!t.l)return n||new He(0);var a=!n||2!=t.i,i=t.i;n||(n=new He(3*s));var o=e=>{var t=n.length;if(e>t){var s=new He(r.max(2*t,e));s.set(n),n=s}},l=t.f||0,c=t.p||0,h=t.b||0,f=t.l,u=t.d,p=t.m,d=t.n,g=8*s;do{if(!f){l=nt(e,c,1);var w=nt(e,c+1,3);if(c+=3,!w){var v=e[(x=st(c)+4)-4]|e[x-3]<<8,y=x+v;if(y>s){i&&ot(0);break}a&&o(h+v),n.set(e.subarray(x,y),h),t.b=h+=v,t.p=c=8*y,t.f=l;continue}if(1==w)f=Ze,u=et,p=9,d=5;else if(2==w){var b=nt(e,c,31)+257,m=nt(e,c+10,15)+4,_=b+nt(e,c+5,31)+1;c+=14;for(var k=new He(_),S=new He(19),z=0;m>z;++z)S[Pe[z]]=nt(e,c+3*z,7);c+=3*m;var D=tt(S),C=(1<<D)-1,I=Xe(S,D,1);for(z=0;_>z;){var x,A=I[nt(e,c,C)];if(c+=15&A,16>(x=A>>4))k[z++]=x;else{var T=0,R=0;for(16==x?(R=3+nt(e,c,3),c+=2,T=k[z-1]):17==x?(R=3+nt(e,c,7),c+=3):18==x&&(R=11+nt(e,c,127),c+=7);R--;)k[z++]=T}}var H=k.subarray(0,b),q=k.subarray(b);p=tt(H),d=tt(q),f=Xe(H,p,1),u=Xe(q,d,1)}else ot(1);if(c>g){i&&ot(0);break}}a&&o(h+131072);for(var B=(1<<p)-1,K=(1<<d)-1,V=c;;V=c){var P=(T=f[rt(e,c)&B])>>4;if((c+=15&T)>g){i&&ot(0);break}if(T||ot(2),256>P)n[h++]=P;else{if(256==P){V=c,f=null;break}var E=P-254;if(P>264){var U=Ke[z=P-257];E=nt(e,c,(1<<U)-1)+We[z],c+=U}var W=u[rt(e,c)&K],M=W>>4;if(W||ot(3),c+=15&W,q=Oe[M],M>3&&(U=Ve[M],q+=rt(e,c)&(1<<U)-1,c+=U),c>g){i&&ot(0);break}a&&o(h+131072);var N=h+E;if(q>h){var O=0-q,F=r.min(q,N);for(0>O+h&&ot(3);F>h;++h)n[h]=undefined[O+h]}for(;N>h;h+=4)n[h]=n[h-q],n[h+1]=n[h+1-q],n[h+2]=n[h+2-q],n[h+3]=n[h+3-q];h=N}}t.l=f,t.p=V,t.b=h,t.f=l,f&&(l=1,t.m=p,t.d=u,t.n=d)}while(!l);return h==n.length?n:at(n,0,h)})(this.p,this.s,this.o);this.ondata(at(n,t,this.s.b),this.d),this.o=at(n,this.s.b-32768),this.s.b=this.o.length,this.p=at(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}(),mt="undefined"!=typeof TextDecoder&&new TextDecoder;try{mt.decode(vt,{stream:!0})}catch(e){}function _t(e,n,r){return class{constructor(s){const i=this;var o,l;o=s,l="level",("function"==typeof t.hasOwn?t.hasOwn(o,l):o.hasOwnProperty(l))&&void 0===s.level&&delete s.level,i.codec=new e(t.assign({},n,s)),r(i.codec,(e=>{if(i.pendingData){const t=i.pendingData;i.pendingData=new a(t.length+e.length);const{pendingData:n}=i;n.set(t,0),n.set(e,t.length)}else i.pendingData=new a(e)}))}append(e){return this.codec.push(e),s(this)}flush(){return this.codec.push(new a,!0),s(this)}};function s(e){if(e.pendingData){const t=e.pendingData;return e.pendingData=null,t}return new a}}const{Deflate:kt,Inflate:St}=((e,t={},n)=>({Deflate:_t(e.Deflate,t.deflate,n),Inflate:_t(e.Inflate,t.inflate,n)}))({Deflate:yt,Inflate:bt},void 0,((e,t)=>e.ondata=t));self.initCodec=()=>{self.Deflate=kt,self.Inflate=St};\n'],{type:"text/javascript"}));e({workerScripts:{inflate:[t],deflate:[t]}});}
242
+
243
+ /*
244
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
245
+
246
+ Redistribution and use in source and binary forms, with or without
247
+ modification, are permitted provided that the following conditions are met:
248
+
249
+ 1. Redistributions of source code must retain the above copyright notice,
250
+ this list of conditions and the following disclaimer.
251
+
252
+ 2. Redistributions in binary form must reproduce the above copyright
253
+ notice, this list of conditions and the following disclaimer in
254
+ the documentation and/or other materials provided with the distribution.
255
+
256
+ 3. The names of the authors may not be used to endorse or promote products
257
+ derived from this software without specific prior written permission.
258
+
259
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
260
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
261
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
262
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
263
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
264
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
265
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
266
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
267
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
268
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
269
+ */
270
+
271
+ function getMimeType() {
272
+ return "application/octet-stream";
273
+ }
274
+
275
+ function initShimAsyncCodec(library, options = {}, registerDataHandler) {
276
+ return {
277
+ Deflate: createCodecClass(library.Deflate, options.deflate, registerDataHandler),
278
+ Inflate: createCodecClass(library.Inflate, options.inflate, registerDataHandler)
279
+ };
280
+ }
281
+
282
+ function objectHasOwn(object, propertyName) {
283
+ // eslint-disable-next-line no-prototype-builtins
284
+ return typeof Object.hasOwn === "function" ? Object.hasOwn(object, propertyName) : object.hasOwnProperty(propertyName);
285
+ }
286
+
287
+ function createCodecClass(constructor, constructorOptions, registerDataHandler) {
288
+ return class {
289
+
290
+ constructor(options) {
291
+ const codecAdapter = this;
292
+ const onData = data => {
293
+ if (codecAdapter.pendingData) {
294
+ const previousPendingData = codecAdapter.pendingData;
295
+ codecAdapter.pendingData = new Uint8Array(previousPendingData.length + data.length);
296
+ const { pendingData } = codecAdapter;
297
+ pendingData.set(previousPendingData, 0);
298
+ pendingData.set(data, previousPendingData.length);
299
+ } else {
300
+ codecAdapter.pendingData = new Uint8Array(data);
301
+ }
302
+ };
303
+ if (objectHasOwn(options, "level") && options.level === undefined) {
304
+ delete options.level;
305
+ }
306
+ codecAdapter.codec = new constructor(Object.assign({}, constructorOptions, options));
307
+ registerDataHandler(codecAdapter.codec, onData);
308
+ }
309
+ append(data) {
310
+ this.codec.push(data);
311
+ return getResponse(this);
312
+ }
313
+ flush() {
314
+ this.codec.push(new Uint8Array(), true);
315
+ return getResponse(this);
316
+ }
317
+ };
318
+
319
+ function getResponse(codec) {
320
+ if (codec.pendingData) {
321
+ const output = codec.pendingData;
322
+ codec.pendingData = null;
323
+ return output;
324
+ } else {
325
+ return new Uint8Array();
326
+ }
327
+ }
328
+ }
329
+
330
+ /*
331
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
332
+
333
+ Redistribution and use in source and binary forms, with or without
334
+ modification, are permitted provided that the following conditions are met:
335
+
336
+ 1. Redistributions of source code must retain the above copyright notice,
337
+ this list of conditions and the following disclaimer.
338
+
339
+ 2. Redistributions in binary form must reproduce the above copyright
340
+ notice, this list of conditions and the following disclaimer in
341
+ the documentation and/or other materials provided with the distribution.
342
+
343
+ 3. The names of the authors may not be used to endorse or promote products
344
+ derived from this software without specific prior written permission.
345
+
346
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
347
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
348
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
349
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
350
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
351
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
352
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
353
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
354
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
355
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
356
+ */
357
+
358
+ const table = [];
359
+ for (let i = 0; i < 256; i++) {
360
+ let t = i;
361
+ for (let j = 0; j < 8; j++) {
362
+ if (t & 1) {
363
+ t = (t >>> 1) ^ 0xEDB88320;
364
+ } else {
365
+ t = t >>> 1;
366
+ }
367
+ }
368
+ table[i] = t;
369
+ }
370
+
371
+ class Crc32 {
372
+
373
+ constructor(crc) {
374
+ this.crc = crc || -1;
375
+ }
376
+
377
+ append(data) {
378
+ let crc = this.crc | 0;
379
+ for (let offset = 0, length = data.length | 0; offset < length; offset++) {
380
+ crc = (crc >>> 8) ^ table[(crc ^ data[offset]) & 0xFF];
381
+ }
382
+ this.crc = crc;
383
+ }
384
+
385
+ get() {
386
+ return ~this.crc;
387
+ }
388
+ }
389
+
390
+ /*
391
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
392
+
393
+ Redistribution and use in source and binary forms, with or without
394
+ modification, are permitted provided that the following conditions are met:
395
+
396
+ 1. Redistributions of source code must retain the above copyright notice,
397
+ this list of conditions and the following disclaimer.
398
+
399
+ 2. Redistributions in binary form must reproduce the above copyright
400
+ notice, this list of conditions and the following disclaimer in
401
+ the documentation and/or other materials provided with the distribution.
402
+
403
+ 3. The names of the authors may not be used to endorse or promote products
404
+ derived from this software without specific prior written permission.
405
+
406
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
407
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
408
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
409
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
410
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
411
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
412
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
413
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
414
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
415
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
416
+ */
417
+
418
+ class Crc32Stream extends TransformStream {
419
+
420
+ constructor() {
421
+ let stream;
422
+ const crc32 = new Crc32();
423
+ super({
424
+ transform(chunk, controller) {
425
+ crc32.append(chunk);
426
+ controller.enqueue(chunk);
427
+ },
428
+ flush() {
429
+ const value = new Uint8Array(4);
430
+ const dataView = new DataView(value.buffer);
431
+ dataView.setUint32(0, crc32.get());
432
+ stream.value = value;
433
+ }
434
+ });
435
+ stream = this;
436
+ }
437
+ }
438
+
439
+ /*
440
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
441
+
442
+ Redistribution and use in source and binary forms, with or without
443
+ modification, are permitted provided that the following conditions are met:
444
+
445
+ 1. Redistributions of source code must retain the above copyright notice,
446
+ this list of conditions and the following disclaimer.
447
+
448
+ 2. Redistributions in binary form must reproduce the above copyright
449
+ notice, this list of conditions and the following disclaimer in
450
+ the documentation and/or other materials provided with the distribution.
451
+
452
+ 3. The names of the authors may not be used to endorse or promote products
453
+ derived from this software without specific prior written permission.
454
+
455
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
456
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
457
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
458
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
459
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
460
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
461
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
462
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
463
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
464
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
465
+ */
466
+
467
+ function encodeText(value) {
468
+ if (typeof TextEncoder == "undefined") {
469
+ value = unescape(encodeURIComponent(value));
470
+ const result = new Uint8Array(value.length);
471
+ for (let i = 0; i < result.length; i++) {
472
+ result[i] = value.charCodeAt(i);
473
+ }
474
+ return result;
475
+ } else {
476
+ return new TextEncoder().encode(value);
477
+ }
478
+ }
479
+
480
+ // Derived from https://github.com/xqdoo00o/jszip/blob/master/lib/sjcl.js and https://github.com/bitwiseshiftleft/sjcl
481
+
482
+ // deno-lint-ignore-file no-this-alias
483
+
484
+ /*
485
+ * SJCL is open. You can use, modify and redistribute it under a BSD
486
+ * license or under the GNU GPL, version 2.0.
487
+ */
488
+
489
+ /** @fileOverview Javascript cryptography implementation.
490
+ *
491
+ * Crush to remove comments, shorten variable names and
492
+ * generally reduce transmission size.
493
+ *
494
+ * @author Emily Stark
495
+ * @author Mike Hamburg
496
+ * @author Dan Boneh
497
+ */
498
+
499
+ /*jslint indent: 2, bitwise: false, nomen: false, plusplus: false, white: false, regexp: false */
500
+
501
+ /** @fileOverview Arrays of bits, encoded as arrays of Numbers.
502
+ *
503
+ * @author Emily Stark
504
+ * @author Mike Hamburg
505
+ * @author Dan Boneh
506
+ */
507
+
508
+ /**
509
+ * Arrays of bits, encoded as arrays of Numbers.
510
+ * @namespace
511
+ * @description
512
+ * <p>
513
+ * These objects are the currency accepted by SJCL's crypto functions.
514
+ * </p>
515
+ *
516
+ * <p>
517
+ * Most of our crypto primitives operate on arrays of 4-byte words internally,
518
+ * but many of them can take arguments that are not a multiple of 4 bytes.
519
+ * This library encodes arrays of bits (whose size need not be a multiple of 8
520
+ * bits) as arrays of 32-bit words. The bits are packed, big-endian, into an
521
+ * array of words, 32 bits at a time. Since the words are double-precision
522
+ * floating point numbers, they fit some extra data. We use this (in a private,
523
+ * possibly-changing manner) to encode the number of bits actually present
524
+ * in the last word of the array.
525
+ * </p>
526
+ *
527
+ * <p>
528
+ * Because bitwise ops clear this out-of-band data, these arrays can be passed
529
+ * to ciphers like AES which want arrays of words.
530
+ * </p>
531
+ */
532
+ const bitArray = {
533
+ /**
534
+ * Concatenate two bit arrays.
535
+ * @param {bitArray} a1 The first array.
536
+ * @param {bitArray} a2 The second array.
537
+ * @return {bitArray} The concatenation of a1 and a2.
538
+ */
539
+ concat(a1, a2) {
540
+ if (a1.length === 0 || a2.length === 0) {
541
+ return a1.concat(a2);
542
+ }
543
+
544
+ const last = a1[a1.length - 1], shift = bitArray.getPartial(last);
545
+ if (shift === 32) {
546
+ return a1.concat(a2);
547
+ } else {
548
+ return bitArray._shiftRight(a2, shift, last | 0, a1.slice(0, a1.length - 1));
549
+ }
550
+ },
551
+
552
+ /**
553
+ * Find the length of an array of bits.
554
+ * @param {bitArray} a The array.
555
+ * @return {Number} The length of a, in bits.
556
+ */
557
+ bitLength(a) {
558
+ const l = a.length;
559
+ if (l === 0) {
560
+ return 0;
561
+ }
562
+ const x = a[l - 1];
563
+ return (l - 1) * 32 + bitArray.getPartial(x);
564
+ },
565
+
566
+ /**
567
+ * Truncate an array.
568
+ * @param {bitArray} a The array.
569
+ * @param {Number} len The length to truncate to, in bits.
570
+ * @return {bitArray} A new array, truncated to len bits.
571
+ */
572
+ clamp(a, len) {
573
+ if (a.length * 32 < len) {
574
+ return a;
575
+ }
576
+ a = a.slice(0, Math.ceil(len / 32));
577
+ const l = a.length;
578
+ len = len & 31;
579
+ if (l > 0 && len) {
580
+ a[l - 1] = bitArray.partial(len, a[l - 1] & 0x80000000 >> (len - 1), 1);
581
+ }
582
+ return a;
583
+ },
584
+
585
+ /**
586
+ * Make a partial word for a bit array.
587
+ * @param {Number} len The number of bits in the word.
588
+ * @param {Number} x The bits.
589
+ * @param {Number} [_end=0] Pass 1 if x has already been shifted to the high side.
590
+ * @return {Number} The partial word.
591
+ */
592
+ partial(len, x, _end) {
593
+ if (len === 32) {
594
+ return x;
595
+ }
596
+ return (_end ? x | 0 : x << (32 - len)) + len * 0x10000000000;
597
+ },
598
+
599
+ /**
600
+ * Get the number of bits used by a partial word.
601
+ * @param {Number} x The partial word.
602
+ * @return {Number} The number of bits used by the partial word.
603
+ */
604
+ getPartial(x) {
605
+ return Math.round(x / 0x10000000000) || 32;
606
+ },
607
+
608
+ /** Shift an array right.
609
+ * @param {bitArray} a The array to shift.
610
+ * @param {Number} shift The number of bits to shift.
611
+ * @param {Number} [carry=0] A byte to carry in
612
+ * @param {bitArray} [out=[]] An array to prepend to the output.
613
+ * @private
614
+ */
615
+ _shiftRight(a, shift, carry, out) {
616
+ if (out === undefined) {
617
+ out = [];
618
+ }
619
+
620
+ for (; shift >= 32; shift -= 32) {
621
+ out.push(carry);
622
+ carry = 0;
623
+ }
624
+ if (shift === 0) {
625
+ return out.concat(a);
626
+ }
627
+
628
+ for (let i = 0; i < a.length; i++) {
629
+ out.push(carry | a[i] >>> shift);
630
+ carry = a[i] << (32 - shift);
631
+ }
632
+ const last2 = a.length ? a[a.length - 1] : 0;
633
+ const shift2 = bitArray.getPartial(last2);
634
+ out.push(bitArray.partial(shift + shift2 & 31, (shift + shift2 > 32) ? carry : out.pop(), 1));
635
+ return out;
636
+ }
637
+ };
638
+
639
+ /** @fileOverview Bit array codec implementations.
640
+ *
641
+ * @author Emily Stark
642
+ * @author Mike Hamburg
643
+ * @author Dan Boneh
644
+ */
645
+
646
+ /**
647
+ * Arrays of bytes
648
+ * @namespace
649
+ */
650
+ const codec = {
651
+ bytes: {
652
+ /** Convert from a bitArray to an array of bytes. */
653
+ fromBits(arr) {
654
+ const bl = bitArray.bitLength(arr);
655
+ const byteLength = bl / 8;
656
+ const out = new Uint8Array(byteLength);
657
+ let tmp;
658
+ for (let i = 0; i < byteLength; i++) {
659
+ if ((i & 3) === 0) {
660
+ tmp = arr[i / 4];
661
+ }
662
+ out[i] = tmp >>> 24;
663
+ tmp <<= 8;
664
+ }
665
+ return out;
666
+ },
667
+ /** Convert from an array of bytes to a bitArray. */
668
+ toBits(bytes) {
669
+ const out = [];
670
+ let i;
671
+ let tmp = 0;
672
+ for (i = 0; i < bytes.length; i++) {
673
+ tmp = tmp << 8 | bytes[i];
674
+ if ((i & 3) === 3) {
675
+ out.push(tmp);
676
+ tmp = 0;
677
+ }
678
+ }
679
+ if (i & 3) {
680
+ out.push(bitArray.partial(8 * (i & 3), tmp));
681
+ }
682
+ return out;
683
+ }
684
+ }
685
+ };
686
+
687
+ const hash = {};
688
+
689
+ /**
690
+ * Context for a SHA-1 operation in progress.
691
+ * @constructor
692
+ */
693
+ hash.sha1 = class {
694
+ constructor(hash) {
695
+ const sha1 = this;
696
+ /**
697
+ * The hash's block size, in bits.
698
+ * @constant
699
+ */
700
+ sha1.blockSize = 512;
701
+ /**
702
+ * The SHA-1 initialization vector.
703
+ * @private
704
+ */
705
+ sha1._init = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
706
+ /**
707
+ * The SHA-1 hash key.
708
+ * @private
709
+ */
710
+ sha1._key = [0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6];
711
+ if (hash) {
712
+ sha1._h = hash._h.slice(0);
713
+ sha1._buffer = hash._buffer.slice(0);
714
+ sha1._length = hash._length;
715
+ } else {
716
+ sha1.reset();
717
+ }
718
+ }
719
+
720
+ /**
721
+ * Reset the hash state.
722
+ * @return this
723
+ */
724
+ reset() {
725
+ const sha1 = this;
726
+ sha1._h = sha1._init.slice(0);
727
+ sha1._buffer = [];
728
+ sha1._length = 0;
729
+ return sha1;
730
+ }
731
+
732
+ /**
733
+ * Input several words to the hash.
734
+ * @param {bitArray|String} data the data to hash.
735
+ * @return this
736
+ */
737
+ update(data) {
738
+ const sha1 = this;
739
+ if (typeof data === "string") {
740
+ data = codec.utf8String.toBits(data);
741
+ }
742
+ const b = sha1._buffer = bitArray.concat(sha1._buffer, data);
743
+ const ol = sha1._length;
744
+ const nl = sha1._length = ol + bitArray.bitLength(data);
745
+ if (nl > 9007199254740991) {
746
+ throw new Error("Cannot hash more than 2^53 - 1 bits");
747
+ }
748
+ const c = new Uint32Array(b);
749
+ let j = 0;
750
+ for (let i = sha1.blockSize + ol - ((sha1.blockSize + ol) & (sha1.blockSize - 1)); i <= nl;
751
+ i += sha1.blockSize) {
752
+ sha1._block(c.subarray(16 * j, 16 * (j + 1)));
753
+ j += 1;
754
+ }
755
+ b.splice(0, 16 * j);
756
+ return sha1;
757
+ }
758
+
759
+ /**
760
+ * Complete hashing and output the hash value.
761
+ * @return {bitArray} The hash value, an array of 5 big-endian words. TODO
762
+ */
763
+ finalize() {
764
+ const sha1 = this;
765
+ let b = sha1._buffer;
766
+ const h = sha1._h;
767
+
768
+ // Round out and push the buffer
769
+ b = bitArray.concat(b, [bitArray.partial(1, 1)]);
770
+ // Round out the buffer to a multiple of 16 words, less the 2 length words.
771
+ for (let i = b.length + 2; i & 15; i++) {
772
+ b.push(0);
773
+ }
774
+
775
+ // append the length
776
+ b.push(Math.floor(sha1._length / 0x100000000));
777
+ b.push(sha1._length | 0);
778
+
779
+ while (b.length) {
780
+ sha1._block(b.splice(0, 16));
781
+ }
782
+
783
+ sha1.reset();
784
+ return h;
785
+ }
786
+
787
+ /**
788
+ * The SHA-1 logical functions f(0), f(1), ..., f(79).
789
+ * @private
790
+ */
791
+ _f(t, b, c, d) {
792
+ if (t <= 19) {
793
+ return (b & c) | (~b & d);
794
+ } else if (t <= 39) {
795
+ return b ^ c ^ d;
796
+ } else if (t <= 59) {
797
+ return (b & c) | (b & d) | (c & d);
798
+ } else if (t <= 79) {
799
+ return b ^ c ^ d;
800
+ }
801
+ }
802
+
803
+ /**
804
+ * Circular left-shift operator.
805
+ * @private
806
+ */
807
+ _S(n, x) {
808
+ return (x << n) | (x >>> 32 - n);
809
+ }
810
+
811
+ /**
812
+ * Perform one cycle of SHA-1.
813
+ * @param {Uint32Array|bitArray} words one block of words.
814
+ * @private
815
+ */
816
+ _block(words) {
817
+ const sha1 = this;
818
+ const h = sha1._h;
819
+ // When words is passed to _block, it has 16 elements. SHA1 _block
820
+ // function extends words with new elements (at the end there are 80 elements).
821
+ // The problem is that if we use Uint32Array instead of Array,
822
+ // the length of Uint32Array cannot be changed. Thus, we replace words with a
823
+ // normal Array here.
824
+ const w = Array(80); // do not use Uint32Array here as the instantiation is slower
825
+ for (let j = 0; j < 16; j++) {
826
+ w[j] = words[j];
827
+ }
828
+
829
+ let a = h[0];
830
+ let b = h[1];
831
+ let c = h[2];
832
+ let d = h[3];
833
+ let e = h[4];
834
+
835
+ for (let t = 0; t <= 79; t++) {
836
+ if (t >= 16) {
837
+ w[t] = sha1._S(1, w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16]);
838
+ }
839
+ const tmp = (sha1._S(5, a) + sha1._f(t, b, c, d) + e + w[t] +
840
+ sha1._key[Math.floor(t / 20)]) | 0;
841
+ e = d;
842
+ d = c;
843
+ c = sha1._S(30, b);
844
+ b = a;
845
+ a = tmp;
846
+ }
847
+
848
+ h[0] = (h[0] + a) | 0;
849
+ h[1] = (h[1] + b) | 0;
850
+ h[2] = (h[2] + c) | 0;
851
+ h[3] = (h[3] + d) | 0;
852
+ h[4] = (h[4] + e) | 0;
853
+ }
854
+ };
855
+
856
+ /** @fileOverview Low-level AES implementation.
857
+ *
858
+ * This file contains a low-level implementation of AES, optimized for
859
+ * size and for efficiency on several browsers. It is based on
860
+ * OpenSSL's aes_core.c, a public-domain implementation by Vincent
861
+ * Rijmen, Antoon Bosselaers and Paulo Barreto.
862
+ *
863
+ * An older version of this implementation is available in the public
864
+ * domain, but this one is (c) Emily Stark, Mike Hamburg, Dan Boneh,
865
+ * Stanford University 2008-2010 and BSD-licensed for liability
866
+ * reasons.
867
+ *
868
+ * @author Emily Stark
869
+ * @author Mike Hamburg
870
+ * @author Dan Boneh
871
+ */
872
+
873
+ const cipher = {};
874
+
875
+ /**
876
+ * Schedule out an AES key for both encryption and decryption. This
877
+ * is a low-level class. Use a cipher mode to do bulk encryption.
878
+ *
879
+ * @constructor
880
+ * @param {Array} key The key as an array of 4, 6 or 8 words.
881
+ */
882
+ cipher.aes = class {
883
+ constructor(key) {
884
+ /**
885
+ * The expanded S-box and inverse S-box tables. These will be computed
886
+ * on the client so that we don't have to send them down the wire.
887
+ *
888
+ * There are two tables, _tables[0] is for encryption and
889
+ * _tables[1] is for decryption.
890
+ *
891
+ * The first 4 sub-tables are the expanded S-box with MixColumns. The
892
+ * last (_tables[01][4]) is the S-box itself.
893
+ *
894
+ * @private
895
+ */
896
+ const aes = this;
897
+ aes._tables = [[[], [], [], [], []], [[], [], [], [], []]];
898
+
899
+ if (!aes._tables[0][0][0]) {
900
+ aes._precompute();
901
+ }
902
+
903
+ const sbox = aes._tables[0][4];
904
+ const decTable = aes._tables[1];
905
+ const keyLen = key.length;
906
+
907
+ let i, encKey, decKey, rcon = 1;
908
+
909
+ if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
910
+ throw new Error("invalid aes key size");
911
+ }
912
+
913
+ aes._key = [encKey = key.slice(0), decKey = []];
914
+
915
+ // schedule encryption keys
916
+ for (i = keyLen; i < 4 * keyLen + 28; i++) {
917
+ let tmp = encKey[i - 1];
918
+
919
+ // apply sbox
920
+ if (i % keyLen === 0 || (keyLen === 8 && i % keyLen === 4)) {
921
+ tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255];
922
+
923
+ // shift rows and add rcon
924
+ if (i % keyLen === 0) {
925
+ tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
926
+ rcon = rcon << 1 ^ (rcon >> 7) * 283;
927
+ }
928
+ }
929
+
930
+ encKey[i] = encKey[i - keyLen] ^ tmp;
931
+ }
932
+
933
+ // schedule decryption keys
934
+ for (let j = 0; i; j++, i--) {
935
+ const tmp = encKey[j & 3 ? i : i - 4];
936
+ if (i <= 4 || j < 4) {
937
+ decKey[j] = tmp;
938
+ } else {
939
+ decKey[j] = decTable[0][sbox[tmp >>> 24]] ^
940
+ decTable[1][sbox[tmp >> 16 & 255]] ^
941
+ decTable[2][sbox[tmp >> 8 & 255]] ^
942
+ decTable[3][sbox[tmp & 255]];
943
+ }
944
+ }
945
+ }
946
+ // public
947
+ /* Something like this might appear here eventually
948
+ name: "AES",
949
+ blockSize: 4,
950
+ keySizes: [4,6,8],
951
+ */
952
+
953
+ /**
954
+ * Encrypt an array of 4 big-endian words.
955
+ * @param {Array} data The plaintext.
956
+ * @return {Array} The ciphertext.
957
+ */
958
+ encrypt(data) {
959
+ return this._crypt(data, 0);
960
+ }
961
+
962
+ /**
963
+ * Decrypt an array of 4 big-endian words.
964
+ * @param {Array} data The ciphertext.
965
+ * @return {Array} The plaintext.
966
+ */
967
+ decrypt(data) {
968
+ return this._crypt(data, 1);
969
+ }
970
+
971
+ /**
972
+ * Expand the S-box tables.
973
+ *
974
+ * @private
975
+ */
976
+ _precompute() {
977
+ const encTable = this._tables[0];
978
+ const decTable = this._tables[1];
979
+ const sbox = encTable[4];
980
+ const sboxInv = decTable[4];
981
+ const d = [];
982
+ const th = [];
983
+ let xInv, x2, x4, x8;
984
+
985
+ // Compute double and third tables
986
+ for (let i = 0; i < 256; i++) {
987
+ th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
988
+ }
989
+
990
+ for (let x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
991
+ // Compute sbox
992
+ let s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
993
+ s = s >> 8 ^ s & 255 ^ 99;
994
+ sbox[x] = s;
995
+ sboxInv[s] = x;
996
+
997
+ // Compute MixColumns
998
+ x8 = d[x4 = d[x2 = d[x]]];
999
+ let tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
1000
+ let tEnc = d[s] * 0x101 ^ s * 0x1010100;
1001
+
1002
+ for (let i = 0; i < 4; i++) {
1003
+ encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
1004
+ decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
1005
+ }
1006
+ }
1007
+
1008
+ // Compactify. Considerable speedup on Firefox.
1009
+ for (let i = 0; i < 5; i++) {
1010
+ encTable[i] = encTable[i].slice(0);
1011
+ decTable[i] = decTable[i].slice(0);
1012
+ }
1013
+ }
1014
+
1015
+ /**
1016
+ * Encryption and decryption core.
1017
+ * @param {Array} input Four words to be encrypted or decrypted.
1018
+ * @param dir The direction, 0 for encrypt and 1 for decrypt.
1019
+ * @return {Array} The four encrypted or decrypted words.
1020
+ * @private
1021
+ */
1022
+ _crypt(input, dir) {
1023
+ if (input.length !== 4) {
1024
+ throw new Error("invalid aes block size");
1025
+ }
1026
+
1027
+ const key = this._key[dir];
1028
+
1029
+ const nInnerRounds = key.length / 4 - 2;
1030
+ const out = [0, 0, 0, 0];
1031
+ const table = this._tables[dir];
1032
+
1033
+ // load up the tables
1034
+ const t0 = table[0];
1035
+ const t1 = table[1];
1036
+ const t2 = table[2];
1037
+ const t3 = table[3];
1038
+ const sbox = table[4];
1039
+
1040
+ // state variables a,b,c,d are loaded with pre-whitened data
1041
+ let a = input[0] ^ key[0];
1042
+ let b = input[dir ? 3 : 1] ^ key[1];
1043
+ let c = input[2] ^ key[2];
1044
+ let d = input[dir ? 1 : 3] ^ key[3];
1045
+ let kIndex = 4;
1046
+ let a2, b2, c2;
1047
+
1048
+ // Inner rounds. Cribbed from OpenSSL.
1049
+ for (let i = 0; i < nInnerRounds; i++) {
1050
+ a2 = t0[a >>> 24] ^ t1[b >> 16 & 255] ^ t2[c >> 8 & 255] ^ t3[d & 255] ^ key[kIndex];
1051
+ b2 = t0[b >>> 24] ^ t1[c >> 16 & 255] ^ t2[d >> 8 & 255] ^ t3[a & 255] ^ key[kIndex + 1];
1052
+ c2 = t0[c >>> 24] ^ t1[d >> 16 & 255] ^ t2[a >> 8 & 255] ^ t3[b & 255] ^ key[kIndex + 2];
1053
+ d = t0[d >>> 24] ^ t1[a >> 16 & 255] ^ t2[b >> 8 & 255] ^ t3[c & 255] ^ key[kIndex + 3];
1054
+ kIndex += 4;
1055
+ a = a2; b = b2; c = c2;
1056
+ }
1057
+
1058
+ // Last round.
1059
+ for (let i = 0; i < 4; i++) {
1060
+ out[dir ? 3 & -i : i] =
1061
+ sbox[a >>> 24] << 24 ^
1062
+ sbox[b >> 16 & 255] << 16 ^
1063
+ sbox[c >> 8 & 255] << 8 ^
1064
+ sbox[d & 255] ^
1065
+ key[kIndex++];
1066
+ a2 = a; a = b; b = c; c = d; d = a2;
1067
+ }
1068
+
1069
+ return out;
1070
+ }
1071
+ };
1072
+
1073
+ /**
1074
+ * Random values
1075
+ * @namespace
1076
+ */
1077
+ const random = {
1078
+ /**
1079
+ * Generate random words with pure js, cryptographically not as strong & safe as native implementation.
1080
+ * @param {TypedArray} typedArray The array to fill.
1081
+ * @return {TypedArray} The random values.
1082
+ */
1083
+ getRandomValues(typedArray) {
1084
+ const words = new Uint32Array(typedArray.buffer);
1085
+ const r = (m_w) => {
1086
+ let m_z = 0x3ade68b1;
1087
+ const mask = 0xffffffff;
1088
+ return function () {
1089
+ m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
1090
+ m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
1091
+ const result = ((((m_z << 0x10) + m_w) & mask) / 0x100000000) + .5;
1092
+ return result * (Math.random() > .5 ? 1 : -1);
1093
+ };
1094
+ };
1095
+ for (let i = 0, rcache; i < typedArray.length; i += 4) {
1096
+ const _r = r((rcache || Math.random()) * 0x100000000);
1097
+ rcache = _r() * 0x3ade67b7;
1098
+ words[i / 4] = (_r() * 0x100000000) | 0;
1099
+ }
1100
+ return typedArray;
1101
+ }
1102
+ };
1103
+
1104
+ /** @fileOverview CTR mode implementation.
1105
+ *
1106
+ * Special thanks to Roy Nicholson for pointing out a bug in our
1107
+ * implementation.
1108
+ *
1109
+ * @author Emily Stark
1110
+ * @author Mike Hamburg
1111
+ * @author Dan Boneh
1112
+ */
1113
+
1114
+ /** Brian Gladman's CTR Mode.
1115
+ * @constructor
1116
+ * @param {Object} _prf The aes instance to generate key.
1117
+ * @param {bitArray} _iv The iv for ctr mode, it must be 128 bits.
1118
+ */
1119
+
1120
+ const mode = {};
1121
+
1122
+ /**
1123
+ * Brian Gladman's CTR Mode.
1124
+ * @namespace
1125
+ */
1126
+ mode.ctrGladman = class {
1127
+ constructor(prf, iv) {
1128
+ this._prf = prf;
1129
+ this._initIv = iv;
1130
+ this._iv = iv;
1131
+ }
1132
+
1133
+ reset() {
1134
+ this._iv = this._initIv;
1135
+ }
1136
+
1137
+ /** Input some data to calculate.
1138
+ * @param {bitArray} data the data to process, it must be intergral multiple of 128 bits unless it's the last.
1139
+ */
1140
+ update(data) {
1141
+ return this.calculate(this._prf, data, this._iv);
1142
+ }
1143
+
1144
+ incWord(word) {
1145
+ if (((word >> 24) & 0xff) === 0xff) { //overflow
1146
+ let b1 = (word >> 16) & 0xff;
1147
+ let b2 = (word >> 8) & 0xff;
1148
+ let b3 = word & 0xff;
1149
+
1150
+ if (b1 === 0xff) { // overflow b1
1151
+ b1 = 0;
1152
+ if (b2 === 0xff) {
1153
+ b2 = 0;
1154
+ if (b3 === 0xff) {
1155
+ b3 = 0;
1156
+ } else {
1157
+ ++b3;
1158
+ }
1159
+ } else {
1160
+ ++b2;
1161
+ }
1162
+ } else {
1163
+ ++b1;
1164
+ }
1165
+
1166
+ word = 0;
1167
+ word += (b1 << 16);
1168
+ word += (b2 << 8);
1169
+ word += b3;
1170
+ } else {
1171
+ word += (0x01 << 24);
1172
+ }
1173
+ return word;
1174
+ }
1175
+
1176
+ incCounter(counter) {
1177
+ if ((counter[0] = this.incWord(counter[0])) === 0) {
1178
+ // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
1179
+ counter[1] = this.incWord(counter[1]);
1180
+ }
1181
+ }
1182
+
1183
+ calculate(prf, data, iv) {
1184
+ let l;
1185
+ if (!(l = data.length)) {
1186
+ return [];
1187
+ }
1188
+ const bl = bitArray.bitLength(data);
1189
+ for (let i = 0; i < l; i += 4) {
1190
+ this.incCounter(iv);
1191
+ const e = prf.encrypt(iv);
1192
+ data[i] ^= e[0];
1193
+ data[i + 1] ^= e[1];
1194
+ data[i + 2] ^= e[2];
1195
+ data[i + 3] ^= e[3];
1196
+ }
1197
+ return bitArray.clamp(data, bl);
1198
+ }
1199
+ };
1200
+
1201
+ const misc = {
1202
+ importKey(password) {
1203
+ return new misc.hmacSha1(codec.bytes.toBits(password));
1204
+ },
1205
+ pbkdf2(prf, salt, count, length) {
1206
+ count = count || 10000;
1207
+ if (length < 0 || count < 0) {
1208
+ throw new Error("invalid params to pbkdf2");
1209
+ }
1210
+ const byteLength = ((length >> 5) + 1) << 2;
1211
+ let u, ui, i, j, k;
1212
+ const arrayBuffer = new ArrayBuffer(byteLength);
1213
+ const out = new DataView(arrayBuffer);
1214
+ let outLength = 0;
1215
+ const b = bitArray;
1216
+ salt = codec.bytes.toBits(salt);
1217
+ for (k = 1; outLength < (byteLength || 1); k++) {
1218
+ u = ui = prf.encrypt(b.concat(salt, [k]));
1219
+ for (i = 1; i < count; i++) {
1220
+ ui = prf.encrypt(ui);
1221
+ for (j = 0; j < ui.length; j++) {
1222
+ u[j] ^= ui[j];
1223
+ }
1224
+ }
1225
+ for (i = 0; outLength < (byteLength || 1) && i < u.length; i++) {
1226
+ out.setInt32(outLength, u[i]);
1227
+ outLength += 4;
1228
+ }
1229
+ }
1230
+ return arrayBuffer.slice(0, length / 8);
1231
+ }
1232
+ };
1233
+
1234
+ /** @fileOverview HMAC implementation.
1235
+ *
1236
+ * @author Emily Stark
1237
+ * @author Mike Hamburg
1238
+ * @author Dan Boneh
1239
+ */
1240
+
1241
+ /** HMAC with the specified hash function.
1242
+ * @constructor
1243
+ * @param {bitArray} key the key for HMAC.
1244
+ * @param {Object} [Hash=hash.sha1] The hash function to use.
1245
+ */
1246
+ misc.hmacSha1 = class {
1247
+
1248
+ constructor(key) {
1249
+ const hmac = this;
1250
+ const Hash = hmac._hash = hash.sha1;
1251
+ const exKey = [[], []];
1252
+ hmac._baseHash = [new Hash(), new Hash()];
1253
+ const bs = hmac._baseHash[0].blockSize / 32;
1254
+
1255
+ if (key.length > bs) {
1256
+ key = new Hash().update(key).finalize();
1257
+ }
1258
+
1259
+ for (let i = 0; i < bs; i++) {
1260
+ exKey[0][i] = key[i] ^ 0x36363636;
1261
+ exKey[1][i] = key[i] ^ 0x5C5C5C5C;
1262
+ }
1263
+
1264
+ hmac._baseHash[0].update(exKey[0]);
1265
+ hmac._baseHash[1].update(exKey[1]);
1266
+ hmac._resultHash = new Hash(hmac._baseHash[0]);
1267
+ }
1268
+ reset() {
1269
+ const hmac = this;
1270
+ hmac._resultHash = new hmac._hash(hmac._baseHash[0]);
1271
+ hmac._updated = false;
1272
+ }
1273
+
1274
+ update(data) {
1275
+ const hmac = this;
1276
+ hmac._updated = true;
1277
+ hmac._resultHash.update(data);
1278
+ }
1279
+
1280
+ digest() {
1281
+ const hmac = this;
1282
+ const w = hmac._resultHash.finalize();
1283
+ const result = new (hmac._hash)(hmac._baseHash[1]).update(w).finalize();
1284
+
1285
+ hmac.reset();
1286
+
1287
+ return result;
1288
+ }
1289
+
1290
+ encrypt(data) {
1291
+ if (!this._updated) {
1292
+ this.update(data);
1293
+ return this.digest(data);
1294
+ } else {
1295
+ throw new Error("encrypt on already updated hmac called!");
1296
+ }
1297
+ }
1298
+ };
1299
+
1300
+ /*
1301
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
1302
+
1303
+ Redistribution and use in source and binary forms, with or without
1304
+ modification, are permitted provided that the following conditions are met:
1305
+
1306
+ 1. Redistributions of source code must retain the above copyright notice,
1307
+ this list of conditions and the following disclaimer.
1308
+
1309
+ 2. Redistributions in binary form must reproduce the above copyright
1310
+ notice, this list of conditions and the following disclaimer in
1311
+ the documentation and/or other materials provided with the distribution.
1312
+
1313
+ 3. The names of the authors may not be used to endorse or promote products
1314
+ derived from this software without specific prior written permission.
1315
+
1316
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
1317
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
1318
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
1319
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
1320
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1321
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
1322
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
1323
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
1324
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
1325
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1326
+ */
1327
+
1328
+ const GET_RANDOM_VALUES_SUPPORTED = typeof crypto != "undefined" && typeof crypto.getRandomValues == "function";
1329
+
1330
+ const ERR_INVALID_PASSWORD = "Invalid password";
1331
+ const ERR_INVALID_SIGNATURE = "Invalid signature";
1332
+ const ERR_ABORT_CHECK_PASSWORD = "zipjs-abort-check-password";
1333
+
1334
+ function getRandomValues(array) {
1335
+ if (GET_RANDOM_VALUES_SUPPORTED) {
1336
+ return crypto.getRandomValues(array);
1337
+ } else {
1338
+ return random.getRandomValues(array);
1339
+ }
1340
+ }
1341
+
1342
+ /*
1343
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
1344
+
1345
+ Redistribution and use in source and binary forms, with or without
1346
+ modification, are permitted provided that the following conditions are met:
1347
+
1348
+ 1. Redistributions of source code must retain the above copyright notice,
1349
+ this list of conditions and the following disclaimer.
1350
+
1351
+ 2. Redistributions in binary form must reproduce the above copyright
1352
+ notice, this list of conditions and the following disclaimer in
1353
+ the documentation and/or other materials provided with the distribution.
1354
+
1355
+ 3. The names of the authors may not be used to endorse or promote products
1356
+ derived from this software without specific prior written permission.
1357
+
1358
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
1359
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
1360
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
1361
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
1362
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1363
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
1364
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
1365
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
1366
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
1367
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1368
+ */
1369
+
1370
+ const BLOCK_LENGTH = 16;
1371
+ const RAW_FORMAT = "raw";
1372
+ const PBKDF2_ALGORITHM = { name: "PBKDF2" };
1373
+ const HASH_ALGORITHM = { name: "HMAC" };
1374
+ const HASH_FUNCTION = "SHA-1";
1375
+ const BASE_KEY_ALGORITHM = Object.assign({ hash: HASH_ALGORITHM }, PBKDF2_ALGORITHM);
1376
+ const DERIVED_BITS_ALGORITHM = Object.assign({ iterations: 1000, hash: { name: HASH_FUNCTION } }, PBKDF2_ALGORITHM);
1377
+ const DERIVED_BITS_USAGE = ["deriveBits"];
1378
+ const SALT_LENGTH = [8, 12, 16];
1379
+ const KEY_LENGTH = [16, 24, 32];
1380
+ const SIGNATURE_LENGTH = 10;
1381
+ const COUNTER_DEFAULT_VALUE = [0, 0, 0, 0];
1382
+ const UNDEFINED_TYPE = "undefined";
1383
+ const FUNCTION_TYPE = "function";
1384
+ // deno-lint-ignore valid-typeof
1385
+ const CRYPTO_API_SUPPORTED = typeof crypto != UNDEFINED_TYPE;
1386
+ const subtle = CRYPTO_API_SUPPORTED && crypto.subtle;
1387
+ const SUBTLE_API_SUPPORTED = CRYPTO_API_SUPPORTED && typeof subtle != UNDEFINED_TYPE;
1388
+ const codecBytes = codec.bytes;
1389
+ const Aes = cipher.aes;
1390
+ const CtrGladman = mode.ctrGladman;
1391
+ const HmacSha1 = misc.hmacSha1;
1392
+
1393
+ let IMPORT_KEY_SUPPORTED = CRYPTO_API_SUPPORTED && SUBTLE_API_SUPPORTED && typeof subtle.importKey == FUNCTION_TYPE;
1394
+ let DERIVE_BITS_SUPPORTED = CRYPTO_API_SUPPORTED && SUBTLE_API_SUPPORTED && typeof subtle.deriveBits == FUNCTION_TYPE;
1395
+
1396
+ class AESDecryptionStream extends TransformStream {
1397
+
1398
+ constructor({ password, signed, encryptionStrength, checkPasswordOnly }) {
1399
+ super({
1400
+ start() {
1401
+ Object.assign(this, {
1402
+ ready: new Promise(resolve => this.resolveReady = resolve),
1403
+ password,
1404
+ signed,
1405
+ strength: encryptionStrength - 1,
1406
+ pending: new Uint8Array()
1407
+ });
1408
+ },
1409
+ async transform(chunk, controller) {
1410
+ const aesCrypto = this;
1411
+ const {
1412
+ password,
1413
+ strength,
1414
+ resolveReady,
1415
+ ready
1416
+ } = aesCrypto;
1417
+ if (password) {
1418
+ await createDecryptionKeys(aesCrypto, strength, password, subarray(chunk, 0, SALT_LENGTH[strength] + 2));
1419
+ chunk = subarray(chunk, SALT_LENGTH[strength] + 2);
1420
+ if (checkPasswordOnly) {
1421
+ controller.error(new Error(ERR_ABORT_CHECK_PASSWORD));
1422
+ } else {
1423
+ resolveReady();
1424
+ }
1425
+ } else {
1426
+ await ready;
1427
+ }
1428
+ const output = new Uint8Array(chunk.length - SIGNATURE_LENGTH - ((chunk.length - SIGNATURE_LENGTH) % BLOCK_LENGTH));
1429
+ controller.enqueue(append(aesCrypto, chunk, output, 0, SIGNATURE_LENGTH, true));
1430
+ },
1431
+ async flush(controller) {
1432
+ const {
1433
+ signed,
1434
+ ctr,
1435
+ hmac,
1436
+ pending,
1437
+ ready
1438
+ } = this;
1439
+ await ready;
1440
+ const chunkToDecrypt = subarray(pending, 0, pending.length - SIGNATURE_LENGTH);
1441
+ const originalSignature = subarray(pending, pending.length - SIGNATURE_LENGTH);
1442
+ let decryptedChunkArray = new Uint8Array();
1443
+ if (chunkToDecrypt.length) {
1444
+ const encryptedChunk = toBits(codecBytes, chunkToDecrypt);
1445
+ hmac.update(encryptedChunk);
1446
+ const decryptedChunk = ctr.update(encryptedChunk);
1447
+ decryptedChunkArray = fromBits(codecBytes, decryptedChunk);
1448
+ }
1449
+ if (signed) {
1450
+ const signature = subarray(fromBits(codecBytes, hmac.digest()), 0, SIGNATURE_LENGTH);
1451
+ for (let indexSignature = 0; indexSignature < SIGNATURE_LENGTH; indexSignature++) {
1452
+ if (signature[indexSignature] != originalSignature[indexSignature]) {
1453
+ throw new Error(ERR_INVALID_SIGNATURE);
1454
+ }
1455
+ }
1456
+ }
1457
+ controller.enqueue(decryptedChunkArray);
1458
+ }
1459
+ });
1460
+ }
1461
+ }
1462
+
1463
+ class AESEncryptionStream extends TransformStream {
1464
+
1465
+ constructor({ password, encryptionStrength }) {
1466
+ // deno-lint-ignore prefer-const
1467
+ let stream;
1468
+ super({
1469
+ start() {
1470
+ Object.assign(this, {
1471
+ ready: new Promise(resolve => this.resolveReady = resolve),
1472
+ password,
1473
+ strength: encryptionStrength - 1,
1474
+ pending: new Uint8Array()
1475
+ });
1476
+ },
1477
+ async transform(chunk, controller) {
1478
+ const aesCrypto = this;
1479
+ const {
1480
+ password,
1481
+ strength,
1482
+ resolveReady,
1483
+ ready
1484
+ } = aesCrypto;
1485
+ let preamble = new Uint8Array();
1486
+ if (password) {
1487
+ preamble = await createEncryptionKeys(aesCrypto, strength, password);
1488
+ resolveReady();
1489
+ } else {
1490
+ await ready;
1491
+ }
1492
+ const output = new Uint8Array(preamble.length + chunk.length - (chunk.length % BLOCK_LENGTH));
1493
+ output.set(preamble, 0);
1494
+ controller.enqueue(append(aesCrypto, chunk, output, preamble.length, 0));
1495
+ },
1496
+ async flush(controller) {
1497
+ const {
1498
+ ctr,
1499
+ hmac,
1500
+ pending,
1501
+ ready
1502
+ } = this;
1503
+ await ready;
1504
+ let encryptedChunkArray = new Uint8Array();
1505
+ if (pending.length) {
1506
+ const encryptedChunk = ctr.update(toBits(codecBytes, pending));
1507
+ hmac.update(encryptedChunk);
1508
+ encryptedChunkArray = fromBits(codecBytes, encryptedChunk);
1509
+ }
1510
+ stream.signature = fromBits(codecBytes, hmac.digest()).slice(0, SIGNATURE_LENGTH);
1511
+ controller.enqueue(concat(encryptedChunkArray, stream.signature));
1512
+ }
1513
+ });
1514
+ stream = this;
1515
+ }
1516
+ }
1517
+
1518
+ function append(aesCrypto, input, output, paddingStart, paddingEnd, verifySignature) {
1519
+ const {
1520
+ ctr,
1521
+ hmac,
1522
+ pending
1523
+ } = aesCrypto;
1524
+ const inputLength = input.length - paddingEnd;
1525
+ if (pending.length) {
1526
+ input = concat(pending, input);
1527
+ output = expand(output, inputLength - (inputLength % BLOCK_LENGTH));
1528
+ }
1529
+ let offset;
1530
+ for (offset = 0; offset <= inputLength - BLOCK_LENGTH; offset += BLOCK_LENGTH) {
1531
+ const inputChunk = toBits(codecBytes, subarray(input, offset, offset + BLOCK_LENGTH));
1532
+ if (verifySignature) {
1533
+ hmac.update(inputChunk);
1534
+ }
1535
+ const outputChunk = ctr.update(inputChunk);
1536
+ if (!verifySignature) {
1537
+ hmac.update(outputChunk);
1538
+ }
1539
+ output.set(fromBits(codecBytes, outputChunk), offset + paddingStart);
1540
+ }
1541
+ aesCrypto.pending = subarray(input, offset);
1542
+ return output;
1543
+ }
1544
+
1545
+ async function createDecryptionKeys(decrypt, strength, password, preamble) {
1546
+ const passwordVerificationKey = await createKeys$1(decrypt, strength, password, subarray(preamble, 0, SALT_LENGTH[strength]));
1547
+ const passwordVerification = subarray(preamble, SALT_LENGTH[strength]);
1548
+ if (passwordVerificationKey[0] != passwordVerification[0] || passwordVerificationKey[1] != passwordVerification[1]) {
1549
+ throw new Error(ERR_INVALID_PASSWORD);
1550
+ }
1551
+ }
1552
+
1553
+ async function createEncryptionKeys(encrypt, strength, password) {
1554
+ const salt = getRandomValues(new Uint8Array(SALT_LENGTH[strength]));
1555
+ const passwordVerification = await createKeys$1(encrypt, strength, password, salt);
1556
+ return concat(salt, passwordVerification);
1557
+ }
1558
+
1559
+ async function createKeys$1(aesCrypto, strength, password, salt) {
1560
+ aesCrypto.password = null;
1561
+ const encodedPassword = encodeText(password);
1562
+ const baseKey = await importKey(RAW_FORMAT, encodedPassword, BASE_KEY_ALGORITHM, false, DERIVED_BITS_USAGE);
1563
+ const derivedBits = await deriveBits(Object.assign({ salt }, DERIVED_BITS_ALGORITHM), baseKey, 8 * ((KEY_LENGTH[strength] * 2) + 2));
1564
+ const compositeKey = new Uint8Array(derivedBits);
1565
+ const key = toBits(codecBytes, subarray(compositeKey, 0, KEY_LENGTH[strength]));
1566
+ const authentication = toBits(codecBytes, subarray(compositeKey, KEY_LENGTH[strength], KEY_LENGTH[strength] * 2));
1567
+ const passwordVerification = subarray(compositeKey, KEY_LENGTH[strength] * 2);
1568
+ Object.assign(aesCrypto, {
1569
+ keys: {
1570
+ key,
1571
+ authentication,
1572
+ passwordVerification
1573
+ },
1574
+ ctr: new CtrGladman(new Aes(key), Array.from(COUNTER_DEFAULT_VALUE)),
1575
+ hmac: new HmacSha1(authentication)
1576
+ });
1577
+ return passwordVerification;
1578
+ }
1579
+
1580
+ async function importKey(format, password, algorithm, extractable, keyUsages) {
1581
+ if (IMPORT_KEY_SUPPORTED) {
1582
+ try {
1583
+ return await subtle.importKey(format, password, algorithm, extractable, keyUsages);
1584
+ } catch (_error) {
1585
+ IMPORT_KEY_SUPPORTED = false;
1586
+ return misc.importKey(password);
1587
+ }
1588
+ } else {
1589
+ return misc.importKey(password);
1590
+ }
1591
+ }
1592
+
1593
+ async function deriveBits(algorithm, baseKey, length) {
1594
+ if (DERIVE_BITS_SUPPORTED) {
1595
+ try {
1596
+ return await subtle.deriveBits(algorithm, baseKey, length);
1597
+ } catch (_error) {
1598
+ DERIVE_BITS_SUPPORTED = false;
1599
+ return misc.pbkdf2(baseKey, algorithm.salt, DERIVED_BITS_ALGORITHM.iterations, length);
1600
+ }
1601
+ } else {
1602
+ return misc.pbkdf2(baseKey, algorithm.salt, DERIVED_BITS_ALGORITHM.iterations, length);
1603
+ }
1604
+ }
1605
+
1606
+ function concat(leftArray, rightArray) {
1607
+ let array = leftArray;
1608
+ if (leftArray.length + rightArray.length) {
1609
+ array = new Uint8Array(leftArray.length + rightArray.length);
1610
+ array.set(leftArray, 0);
1611
+ array.set(rightArray, leftArray.length);
1612
+ }
1613
+ return array;
1614
+ }
1615
+
1616
+ function expand(inputArray, length) {
1617
+ if (length && length > inputArray.length) {
1618
+ const array = inputArray;
1619
+ inputArray = new Uint8Array(length);
1620
+ inputArray.set(array, 0);
1621
+ }
1622
+ return inputArray;
1623
+ }
1624
+
1625
+ function subarray(array, begin, end) {
1626
+ return array.subarray(begin, end);
1627
+ }
1628
+
1629
+ function fromBits(codecBytes, chunk) {
1630
+ return codecBytes.fromBits(chunk);
1631
+ }
1632
+ function toBits(codecBytes, chunk) {
1633
+ return codecBytes.toBits(chunk);
1634
+ }
1635
+
1636
+ /*
1637
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
1638
+
1639
+ Redistribution and use in source and binary forms, with or without
1640
+ modification, are permitted provided that the following conditions are met:
1641
+
1642
+ 1. Redistributions of source code must retain the above copyright notice,
1643
+ this list of conditions and the following disclaimer.
1644
+
1645
+ 2. Redistributions in binary form must reproduce the above copyright
1646
+ notice, this list of conditions and the following disclaimer in
1647
+ the documentation and/or other materials provided with the distribution.
1648
+
1649
+ 3. The names of the authors may not be used to endorse or promote products
1650
+ derived from this software without specific prior written permission.
1651
+
1652
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
1653
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
1654
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
1655
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
1656
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1657
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
1658
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
1659
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
1660
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
1661
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1662
+ */
1663
+
1664
+ const HEADER_LENGTH = 12;
1665
+
1666
+ class ZipCryptoDecryptionStream extends TransformStream {
1667
+
1668
+ constructor({ password, passwordVerification, checkPasswordOnly }) {
1669
+ super({
1670
+ start() {
1671
+ Object.assign(this, {
1672
+ password,
1673
+ passwordVerification
1674
+ });
1675
+ createKeys(this, password);
1676
+ },
1677
+ transform(chunk, controller) {
1678
+ const zipCrypto = this;
1679
+ if (zipCrypto.password) {
1680
+ const decryptedHeader = decrypt(zipCrypto, chunk.subarray(0, HEADER_LENGTH));
1681
+ zipCrypto.password = null;
1682
+ if (decryptedHeader[HEADER_LENGTH - 1] != zipCrypto.passwordVerification) {
1683
+ throw new Error(ERR_INVALID_PASSWORD);
1684
+ }
1685
+ chunk = chunk.subarray(HEADER_LENGTH);
1686
+ }
1687
+ if (checkPasswordOnly) {
1688
+ controller.error(new Error(ERR_ABORT_CHECK_PASSWORD));
1689
+ } else {
1690
+ controller.enqueue(decrypt(zipCrypto, chunk));
1691
+ }
1692
+ }
1693
+ });
1694
+ }
1695
+ }
1696
+
1697
+ class ZipCryptoEncryptionStream extends TransformStream {
1698
+
1699
+ constructor({ password, passwordVerification }) {
1700
+ super({
1701
+ start() {
1702
+ Object.assign(this, {
1703
+ password,
1704
+ passwordVerification
1705
+ });
1706
+ createKeys(this, password);
1707
+ },
1708
+ transform(chunk, controller) {
1709
+ const zipCrypto = this;
1710
+ let output;
1711
+ let offset;
1712
+ if (zipCrypto.password) {
1713
+ zipCrypto.password = null;
1714
+ const header = getRandomValues(new Uint8Array(HEADER_LENGTH));
1715
+ header[HEADER_LENGTH - 1] = zipCrypto.passwordVerification;
1716
+ output = new Uint8Array(chunk.length + header.length);
1717
+ output.set(encrypt(zipCrypto, header), 0);
1718
+ offset = HEADER_LENGTH;
1719
+ } else {
1720
+ output = new Uint8Array(chunk.length);
1721
+ offset = 0;
1722
+ }
1723
+ output.set(encrypt(zipCrypto, chunk), offset);
1724
+ controller.enqueue(output);
1725
+ }
1726
+ });
1727
+ }
1728
+ }
1729
+
1730
+ function decrypt(target, input) {
1731
+ const output = new Uint8Array(input.length);
1732
+ for (let index = 0; index < input.length; index++) {
1733
+ output[index] = getByte(target) ^ input[index];
1734
+ updateKeys(target, output[index]);
1735
+ }
1736
+ return output;
1737
+ }
1738
+
1739
+ function encrypt(target, input) {
1740
+ const output = new Uint8Array(input.length);
1741
+ for (let index = 0; index < input.length; index++) {
1742
+ output[index] = getByte(target) ^ input[index];
1743
+ updateKeys(target, input[index]);
1744
+ }
1745
+ return output;
1746
+ }
1747
+
1748
+ function createKeys(target, password) {
1749
+ const keys = [0x12345678, 0x23456789, 0x34567890];
1750
+ Object.assign(target, {
1751
+ keys,
1752
+ crcKey0: new Crc32(keys[0]),
1753
+ crcKey2: new Crc32(keys[2]),
1754
+ });
1755
+ for (let index = 0; index < password.length; index++) {
1756
+ updateKeys(target, password.charCodeAt(index));
1757
+ }
1758
+ }
1759
+
1760
+ function updateKeys(target, byte) {
1761
+ let [key0, key1, key2] = target.keys;
1762
+ target.crcKey0.append([byte]);
1763
+ key0 = ~target.crcKey0.get();
1764
+ key1 = getInt32(Math.imul(getInt32(key1 + getInt8(key0)), 134775813) + 1);
1765
+ target.crcKey2.append([key1 >>> 24]);
1766
+ key2 = ~target.crcKey2.get();
1767
+ target.keys = [key0, key1, key2];
1768
+ }
1769
+
1770
+ function getByte(target) {
1771
+ const temp = target.keys[2] | 2;
1772
+ return getInt8(Math.imul(temp, (temp ^ 1)) >>> 8);
1773
+ }
1774
+
1775
+ function getInt8(number) {
1776
+ return number & 0xFF;
1777
+ }
1778
+
1779
+ function getInt32(number) {
1780
+ return number & 0xFFFFFFFF;
1781
+ }
1782
+
1783
+ /*
1784
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
1785
+
1786
+ Redistribution and use in source and binary forms, with or without
1787
+ modification, are permitted provided that the following conditions are met:
1788
+
1789
+ 1. Redistributions of source code must retain the above copyright notice,
1790
+ this list of conditions and the following disclaimer.
1791
+
1792
+ 2. Redistributions in binary form must reproduce the above copyright
1793
+ notice, this list of conditions and the following disclaimer in
1794
+ the documentation and/or other materials provided with the distribution.
1795
+
1796
+ 3. The names of the authors may not be used to endorse or promote products
1797
+ derived from this software without specific prior written permission.
1798
+
1799
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
1800
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
1801
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
1802
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
1803
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1804
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
1805
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
1806
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
1807
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
1808
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1809
+ */
1810
+
1811
+ const COMPRESSION_FORMAT = "deflate-raw";
1812
+
1813
+ class DeflateStream extends TransformStream {
1814
+
1815
+ constructor(options, { chunkSize, CompressionStream, CompressionStreamNative }) {
1816
+ super({});
1817
+ const { compressed, encrypted, useCompressionStream, zipCrypto, signed, level } = options;
1818
+ const stream = this;
1819
+ let crc32Stream, encryptionStream;
1820
+ let readable = filterEmptyChunks(super.readable);
1821
+ if ((!encrypted || zipCrypto) && signed) {
1822
+ crc32Stream = new Crc32Stream();
1823
+ readable = pipeThrough(readable, crc32Stream);
1824
+ }
1825
+ if (compressed) {
1826
+ readable = pipeThroughCommpressionStream(readable, useCompressionStream, { level, chunkSize }, CompressionStreamNative, CompressionStream);
1827
+ }
1828
+ if (encrypted) {
1829
+ if (zipCrypto) {
1830
+ readable = pipeThrough(readable, new ZipCryptoEncryptionStream(options));
1831
+ } else {
1832
+ encryptionStream = new AESEncryptionStream(options);
1833
+ readable = pipeThrough(readable, encryptionStream);
1834
+ }
1835
+ }
1836
+ setReadable(stream, readable, () => {
1837
+ let signature;
1838
+ if (encrypted && !zipCrypto) {
1839
+ signature = encryptionStream.signature;
1840
+ }
1841
+ if ((!encrypted || zipCrypto) && signed) {
1842
+ signature = new DataView(crc32Stream.value.buffer).getUint32(0);
1843
+ }
1844
+ stream.signature = signature;
1845
+ });
1846
+ }
1847
+ }
1848
+
1849
+ class InflateStream extends TransformStream {
1850
+
1851
+ constructor(options, { chunkSize, DecompressionStream, DecompressionStreamNative }) {
1852
+ super({});
1853
+ const { zipCrypto, encrypted, signed, signature, compressed, useCompressionStream } = options;
1854
+ let crc32Stream, decryptionStream;
1855
+ let readable = filterEmptyChunks(super.readable);
1856
+ if (encrypted) {
1857
+ if (zipCrypto) {
1858
+ readable = pipeThrough(readable, new ZipCryptoDecryptionStream(options));
1859
+ } else {
1860
+ decryptionStream = new AESDecryptionStream(options);
1861
+ readable = pipeThrough(readable, decryptionStream);
1862
+ }
1863
+ }
1864
+ if (compressed) {
1865
+ readable = pipeThroughCommpressionStream(readable, useCompressionStream, { chunkSize }, DecompressionStreamNative, DecompressionStream);
1866
+ }
1867
+ if ((!encrypted || zipCrypto) && signed) {
1868
+ crc32Stream = new Crc32Stream();
1869
+ readable = pipeThrough(readable, crc32Stream);
1870
+ }
1871
+ setReadable(this, readable, () => {
1872
+ if ((!encrypted || zipCrypto) && signed) {
1873
+ const dataViewSignature = new DataView(crc32Stream.value.buffer);
1874
+ if (signature != dataViewSignature.getUint32(0, false)) {
1875
+ throw new Error(ERR_INVALID_SIGNATURE);
1876
+ }
1877
+ }
1878
+ });
1879
+ }
1880
+ }
1881
+
1882
+ function filterEmptyChunks(readable) {
1883
+ return pipeThrough(readable, new TransformStream({
1884
+ transform(chunk, controller) {
1885
+ if (chunk && chunk.length) {
1886
+ controller.enqueue(chunk);
1887
+ }
1888
+ }
1889
+ }));
1890
+ }
1891
+
1892
+ function setReadable(stream, readable, flush) {
1893
+ readable = pipeThrough(readable, new TransformStream({ flush }));
1894
+ Object.defineProperty(stream, "readable", {
1895
+ get() {
1896
+ return readable;
1897
+ }
1898
+ });
1899
+ }
1900
+
1901
+ function pipeThroughCommpressionStream(readable, useCompressionStream, options, CodecStreamNative, CodecStream) {
1902
+ try {
1903
+ const CompressionStream = useCompressionStream && CodecStreamNative ? CodecStreamNative : CodecStream;
1904
+ readable = pipeThrough(readable, new CompressionStream(COMPRESSION_FORMAT, options));
1905
+ } catch (error) {
1906
+ if (useCompressionStream) {
1907
+ readable = pipeThrough(readable, new CodecStream(COMPRESSION_FORMAT, options));
1908
+ } else {
1909
+ throw error;
1910
+ }
1911
+ }
1912
+ return readable;
1913
+ }
1914
+
1915
+ function pipeThrough(readable, transformStream) {
1916
+ return readable.pipeThrough(transformStream);
1917
+ }
1918
+
1919
+ /*
1920
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
1921
+
1922
+ Redistribution and use in source and binary forms, with or without
1923
+ modification, are permitted provided that the following conditions are met:
1924
+
1925
+ 1. Redistributions of source code must retain the above copyright notice,
1926
+ this list of conditions and the following disclaimer.
1927
+
1928
+ 2. Redistributions in binary form must reproduce the above copyright
1929
+ notice, this list of conditions and the following disclaimer in
1930
+ the documentation and/or other materials provided with the distribution.
1931
+
1932
+ 3. The names of the authors may not be used to endorse or promote products
1933
+ derived from this software without specific prior written permission.
1934
+
1935
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
1936
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
1937
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
1938
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
1939
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1940
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
1941
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
1942
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
1943
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
1944
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1945
+ */
1946
+
1947
+ const MESSAGE_EVENT_TYPE = "message";
1948
+ const MESSAGE_START = "start";
1949
+ const MESSAGE_PULL = "pull";
1950
+ const MESSAGE_DATA = "data";
1951
+ const MESSAGE_ACK_DATA = "ack";
1952
+ const MESSAGE_CLOSE = "close";
1953
+ const CODEC_DEFLATE = "deflate";
1954
+ const CODEC_INFLATE = "inflate";
1955
+
1956
+ class CodecStream extends TransformStream {
1957
+
1958
+ constructor(options, config) {
1959
+ super({});
1960
+ const codec = this;
1961
+ const { codecType } = options;
1962
+ let Stream;
1963
+ if (codecType.startsWith(CODEC_DEFLATE)) {
1964
+ Stream = DeflateStream;
1965
+ } else if (codecType.startsWith(CODEC_INFLATE)) {
1966
+ Stream = InflateStream;
1967
+ }
1968
+ let size = 0;
1969
+ const stream = new Stream(options, config);
1970
+ const readable = super.readable;
1971
+ const transformStream = new TransformStream({
1972
+ transform(chunk, controller) {
1973
+ if (chunk && chunk.length) {
1974
+ size += chunk.length;
1975
+ controller.enqueue(chunk);
1976
+ }
1977
+ },
1978
+ flush() {
1979
+ const { signature } = stream;
1980
+ Object.assign(codec, {
1981
+ signature,
1982
+ size
1983
+ });
1984
+ }
1985
+ });
1986
+ Object.defineProperty(codec, "readable", {
1987
+ get() {
1988
+ return readable.pipeThrough(stream).pipeThrough(transformStream);
1989
+ }
1990
+ });
1991
+ }
1992
+ }
1993
+
1994
+ /*
1995
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
1996
+
1997
+ Redistribution and use in source and binary forms, with or without
1998
+ modification, are permitted provided that the following conditions are met:
1999
+
2000
+ 1. Redistributions of source code must retain the above copyright notice,
2001
+ this list of conditions and the following disclaimer.
2002
+
2003
+ 2. Redistributions in binary form must reproduce the above copyright
2004
+ notice, this list of conditions and the following disclaimer in
2005
+ the documentation and/or other materials provided with the distribution.
2006
+
2007
+ 3. The names of the authors may not be used to endorse or promote products
2008
+ derived from this software without specific prior written permission.
2009
+
2010
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
2011
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
2012
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
2013
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
2014
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2015
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
2016
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
2017
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
2018
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
2019
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2020
+ */
2021
+
2022
+ // deno-lint-ignore valid-typeof
2023
+ const WEB_WORKERS_SUPPORTED = typeof Worker != UNDEFINED_TYPE$1;
2024
+
2025
+ class CodecWorker {
2026
+
2027
+ constructor(workerData, { readable, writable }, { options, config, streamOptions, useWebWorkers, transferStreams, scripts }, onTaskFinished) {
2028
+ const { signal } = streamOptions;
2029
+ Object.assign(workerData, {
2030
+ busy: true,
2031
+ readable: readable.pipeThrough(new ProgressWatcherStream(readable, streamOptions, config), { signal }),
2032
+ writable,
2033
+ options: Object.assign({}, options),
2034
+ scripts,
2035
+ transferStreams,
2036
+ terminate() {
2037
+ const { worker, busy } = workerData;
2038
+ if (worker && !busy) {
2039
+ worker.terminate();
2040
+ workerData.interface = null;
2041
+ }
2042
+ },
2043
+ onTaskFinished() {
2044
+ workerData.busy = false;
2045
+ onTaskFinished(workerData);
2046
+ }
2047
+ });
2048
+ return (useWebWorkers && WEB_WORKERS_SUPPORTED ? createWebWorkerInterface : createWorkerInterface)(workerData, config);
2049
+ }
2050
+ }
2051
+
2052
+ class ProgressWatcherStream extends TransformStream {
2053
+
2054
+ constructor(readableSource, { onstart, onprogress, size, onend }, { chunkSize }) {
2055
+ let chunkOffset = 0;
2056
+ super({
2057
+ start() {
2058
+ if (onstart) {
2059
+ callHandler(onstart, size);
2060
+ }
2061
+ },
2062
+ async transform(chunk, controller) {
2063
+ chunkOffset += chunk.length;
2064
+ if (onprogress) {
2065
+ await callHandler(onprogress, chunkOffset, size);
2066
+ }
2067
+ controller.enqueue(chunk);
2068
+ },
2069
+ flush() {
2070
+ readableSource.size = chunkOffset;
2071
+ if (onend) {
2072
+ callHandler(onend, chunkOffset);
2073
+ }
2074
+ }
2075
+ }, { highWaterMark: 1, size: () => chunkSize });
2076
+ }
2077
+ }
2078
+
2079
+ async function callHandler(handler, ...parameters) {
2080
+ try {
2081
+ await handler(...parameters);
2082
+ } catch (_error) {
2083
+ // ignored
2084
+ }
2085
+ }
2086
+
2087
+ function createWorkerInterface(workerData, config) {
2088
+ return {
2089
+ run: () => runWorker$1(workerData, config)
2090
+ };
2091
+ }
2092
+
2093
+ function createWebWorkerInterface(workerData, { baseURL, chunkSize }) {
2094
+ if (!workerData.interface) {
2095
+ Object.assign(workerData, {
2096
+ worker: getWebWorker(workerData.scripts[0], baseURL, workerData),
2097
+ interface: {
2098
+ run: () => runWebWorker(workerData, { chunkSize })
2099
+ }
2100
+ });
2101
+ }
2102
+ return workerData.interface;
2103
+ }
2104
+
2105
+ async function runWorker$1({ options, readable, writable, onTaskFinished }, config) {
2106
+ const codecStream = new CodecStream(options, config);
2107
+ try {
2108
+ await readable.pipeThrough(codecStream).pipeTo(writable, { preventClose: true, preventAbort: true });
2109
+ const {
2110
+ signature,
2111
+ size
2112
+ } = codecStream;
2113
+ return {
2114
+ signature,
2115
+ size
2116
+ };
2117
+ } finally {
2118
+ onTaskFinished();
2119
+ }
2120
+ }
2121
+
2122
+ async function runWebWorker(workerData, config) {
2123
+ let resolveResult, rejectResult;
2124
+ const result = new Promise((resolve, reject) => {
2125
+ resolveResult = resolve;
2126
+ rejectResult = reject;
2127
+ });
2128
+ Object.assign(workerData, {
2129
+ reader: null,
2130
+ writer: null,
2131
+ resolveResult,
2132
+ rejectResult,
2133
+ result
2134
+ });
2135
+ const { readable, options, scripts } = workerData;
2136
+ const { writable, closed } = watchClosedStream(workerData.writable);
2137
+ const streamsTransferred = sendMessage({
2138
+ type: MESSAGE_START,
2139
+ scripts: scripts.slice(1),
2140
+ options,
2141
+ config,
2142
+ readable,
2143
+ writable
2144
+ }, workerData);
2145
+ if (!streamsTransferred) {
2146
+ Object.assign(workerData, {
2147
+ reader: readable.getReader(),
2148
+ writer: writable.getWriter()
2149
+ });
2150
+ }
2151
+ const resultValue = await result;
2152
+ try {
2153
+ await writable.getWriter().close();
2154
+ } catch (_error) {
2155
+ // ignored
2156
+ }
2157
+ await closed;
2158
+ return resultValue;
2159
+ }
2160
+
2161
+ function watchClosedStream(writableSource) {
2162
+ const writer = writableSource.getWriter();
2163
+ let resolveStreamClosed;
2164
+ const closed = new Promise(resolve => resolveStreamClosed = resolve);
2165
+ const writable = new WritableStream({
2166
+ async write(chunk) {
2167
+ await writer.ready;
2168
+ await writer.write(chunk);
2169
+ },
2170
+ close() {
2171
+ writer.releaseLock();
2172
+ resolveStreamClosed();
2173
+ },
2174
+ abort(reason) {
2175
+ return writer.abort(reason);
2176
+ }
2177
+ });
2178
+ return { writable, closed };
2179
+ }
2180
+
2181
+ let classicWorkersSupported = true;
2182
+ let transferStreamsSupported = true;
2183
+
2184
+ function getWebWorker(url, baseURL, workerData) {
2185
+ const workerOptions = { type: "module" };
2186
+ let scriptUrl, worker;
2187
+ // deno-lint-ignore valid-typeof
2188
+ if (typeof url == FUNCTION_TYPE$1) {
2189
+ url = url();
2190
+ }
2191
+ try {
2192
+ scriptUrl = new URL(url, baseURL);
2193
+ } catch (_error) {
2194
+ scriptUrl = url;
2195
+ }
2196
+ if (classicWorkersSupported) {
2197
+ try {
2198
+ worker = new Worker(scriptUrl);
2199
+ } catch (_error) {
2200
+ classicWorkersSupported = false;
2201
+ worker = new Worker(scriptUrl, workerOptions);
2202
+ }
2203
+ } else {
2204
+ worker = new Worker(scriptUrl, workerOptions);
2205
+ }
2206
+ worker.addEventListener(MESSAGE_EVENT_TYPE, event => onMessage(event, workerData));
2207
+ return worker;
2208
+ }
2209
+
2210
+ function sendMessage(message, { worker, writer, onTaskFinished, transferStreams }) {
2211
+ try {
2212
+ let { value, readable, writable } = message;
2213
+ const transferables = [];
2214
+ if (value) {
2215
+ message.value = value.buffer;
2216
+ transferables.push(message.value);
2217
+ }
2218
+ if (transferStreams && transferStreamsSupported) {
2219
+ if (readable) {
2220
+ transferables.push(readable);
2221
+ }
2222
+ if (writable) {
2223
+ transferables.push(writable);
2224
+ }
2225
+ } else {
2226
+ message.readable = message.writable = null;
2227
+ }
2228
+ if (transferables.length) {
2229
+ try {
2230
+ worker.postMessage(message, transferables);
2231
+ return true;
2232
+ } catch (_error) {
2233
+ transferStreamsSupported = false;
2234
+ message.readable = message.writable = null;
2235
+ worker.postMessage(message);
2236
+ }
2237
+ } else {
2238
+ worker.postMessage(message);
2239
+ }
2240
+ } catch (error) {
2241
+ if (writer) {
2242
+ writer.releaseLock();
2243
+ }
2244
+ onTaskFinished();
2245
+ throw error;
2246
+ }
2247
+ }
2248
+
2249
+ async function onMessage({ data }, workerData) {
2250
+ const { type, value, messageId, result, error } = data;
2251
+ const { reader, writer, resolveResult, rejectResult, onTaskFinished } = workerData;
2252
+ try {
2253
+ if (error) {
2254
+ const { message, stack, code, name } = error;
2255
+ const responseError = new Error(message);
2256
+ Object.assign(responseError, { stack, code, name });
2257
+ close(responseError);
2258
+ } else {
2259
+ if (type == MESSAGE_PULL) {
2260
+ const { value, done } = await reader.read();
2261
+ sendMessage({ type: MESSAGE_DATA, value, done, messageId }, workerData);
2262
+ }
2263
+ if (type == MESSAGE_DATA) {
2264
+ await writer.ready;
2265
+ await writer.write(new Uint8Array(value));
2266
+ sendMessage({ type: MESSAGE_ACK_DATA, messageId }, workerData);
2267
+ }
2268
+ if (type == MESSAGE_CLOSE) {
2269
+ close(null, result);
2270
+ }
2271
+ }
2272
+ } catch (error) {
2273
+ close(error);
2274
+ }
2275
+
2276
+ function close(error, result) {
2277
+ if (error) {
2278
+ rejectResult(error);
2279
+ } else {
2280
+ resolveResult(result);
2281
+ }
2282
+ if (writer) {
2283
+ writer.releaseLock();
2284
+ }
2285
+ onTaskFinished();
2286
+ }
2287
+ }
2288
+
2289
+ /*
2290
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
2291
+
2292
+ Redistribution and use in source and binary forms, with or without
2293
+ modification, are permitted provided that the following conditions are met:
2294
+
2295
+ 1. Redistributions of source code must retain the above copyright notice,
2296
+ this list of conditions and the following disclaimer.
2297
+
2298
+ 2. Redistributions in binary form must reproduce the above copyright
2299
+ notice, this list of conditions and the following disclaimer in
2300
+ the documentation and/or other materials provided with the distribution.
2301
+
2302
+ 3. The names of the authors may not be used to endorse or promote products
2303
+ derived from this software without specific prior written permission.
2304
+
2305
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
2306
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
2307
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
2308
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
2309
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2310
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
2311
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
2312
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
2313
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
2314
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2315
+ */
2316
+
2317
+ let pool = [];
2318
+ const pendingRequests = [];
2319
+
2320
+ let indexWorker = 0;
2321
+
2322
+ async function runWorker(stream, workerOptions) {
2323
+ const { options, config } = workerOptions;
2324
+ const { transferStreams, useWebWorkers, useCompressionStream, codecType, compressed, signed, encrypted } = options;
2325
+ const { workerScripts, maxWorkers, terminateWorkerTimeout } = config;
2326
+ workerOptions.transferStreams = transferStreams || transferStreams === UNDEFINED_VALUE;
2327
+ const streamCopy = !compressed && !signed && !encrypted && !workerOptions.transferStreams;
2328
+ workerOptions.useWebWorkers = !streamCopy && (useWebWorkers || (useWebWorkers === UNDEFINED_VALUE && config.useWebWorkers));
2329
+ workerOptions.scripts = workerOptions.useWebWorkers && workerScripts ? workerScripts[codecType] : [];
2330
+ options.useCompressionStream = useCompressionStream || (useCompressionStream === UNDEFINED_VALUE && config.useCompressionStream);
2331
+ let worker;
2332
+ const workerData = pool.find(workerData => !workerData.busy);
2333
+ if (workerData) {
2334
+ clearTerminateTimeout(workerData);
2335
+ worker = new CodecWorker(workerData, stream, workerOptions, onTaskFinished);
2336
+ } else if (pool.length < maxWorkers) {
2337
+ const workerData = { indexWorker };
2338
+ indexWorker++;
2339
+ pool.push(workerData);
2340
+ worker = new CodecWorker(workerData, stream, workerOptions, onTaskFinished);
2341
+ } else {
2342
+ worker = await new Promise(resolve => pendingRequests.push({ resolve, stream, workerOptions }));
2343
+ }
2344
+ return worker.run();
2345
+
2346
+ function onTaskFinished(workerData) {
2347
+ if (pendingRequests.length) {
2348
+ const [{ resolve, stream, workerOptions }] = pendingRequests.splice(0, 1);
2349
+ resolve(new CodecWorker(workerData, stream, workerOptions, onTaskFinished));
2350
+ } else if (workerData.worker) {
2351
+ clearTerminateTimeout(workerData);
2352
+ if (Number.isFinite(terminateWorkerTimeout) && terminateWorkerTimeout >= 0) {
2353
+ workerData.terminateTimeout = setTimeout(() => {
2354
+ pool = pool.filter(data => data != workerData);
2355
+ workerData.terminate();
2356
+ }, terminateWorkerTimeout);
2357
+ }
2358
+ } else {
2359
+ pool = pool.filter(data => data != workerData);
2360
+ }
2361
+ }
2362
+ }
2363
+
2364
+ function clearTerminateTimeout(workerData) {
2365
+ const { terminateTimeout } = workerData;
2366
+ if (terminateTimeout) {
2367
+ clearTimeout(terminateTimeout);
2368
+ workerData.terminateTimeout = null;
2369
+ }
2370
+ }
2371
+
2372
+ function terminateWorkers() {
2373
+ pool.forEach(workerData => {
2374
+ clearTerminateTimeout(workerData);
2375
+ workerData.terminate();
2376
+ });
2377
+ }
2378
+
2379
+ /*
2380
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
2381
+
2382
+ Redistribution and use in source and binary forms, with or without
2383
+ modification, are permitted provided that the following conditions are met:
2384
+
2385
+ 1. Redistributions of source code must retain the above copyright notice,
2386
+ this list of conditions and the following disclaimer.
2387
+
2388
+ 2. Redistributions in binary form must reproduce the above copyright
2389
+ notice, this list of conditions and the following disclaimer in
2390
+ the documentation and/or other materials provided with the distribution.
2391
+
2392
+ 3. The names of the authors may not be used to endorse or promote products
2393
+ derived from this software without specific prior written permission.
2394
+
2395
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
2396
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
2397
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
2398
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
2399
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2400
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
2401
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
2402
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
2403
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
2404
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2405
+ */
2406
+
2407
+ const ERR_HTTP_STATUS = "HTTP error ";
2408
+ const ERR_HTTP_RANGE = "HTTP Range not supported";
2409
+ const ERR_ITERATOR_COMPLETED_TOO_SOON = "Writer iterator completed too soon";
2410
+
2411
+ const CONTENT_TYPE_TEXT_PLAIN = "text/plain";
2412
+ const HTTP_HEADER_CONTENT_LENGTH = "Content-Length";
2413
+ const HTTP_HEADER_CONTENT_RANGE = "Content-Range";
2414
+ const HTTP_HEADER_ACCEPT_RANGES = "Accept-Ranges";
2415
+ const HTTP_HEADER_RANGE = "Range";
2416
+ const HTTP_HEADER_CONTENT_TYPE = "Content-Type";
2417
+ const HTTP_METHOD_HEAD = "HEAD";
2418
+ const HTTP_METHOD_GET = "GET";
2419
+ const HTTP_RANGE_UNIT = "bytes";
2420
+ const DEFAULT_CHUNK_SIZE = 64 * 1024;
2421
+
2422
+ const PROPERTY_NAME_WRITABLE = "writable";
2423
+
2424
+ class Stream {
2425
+
2426
+ constructor() {
2427
+ this.size = 0;
2428
+ }
2429
+
2430
+ init() {
2431
+ this.initialized = true;
2432
+ }
2433
+ }
2434
+
2435
+ class Reader extends Stream {
2436
+
2437
+ get readable() {
2438
+ const reader = this;
2439
+ const { chunkSize = DEFAULT_CHUNK_SIZE } = reader;
2440
+ const readable = new ReadableStream({
2441
+ start() {
2442
+ this.chunkOffset = 0;
2443
+ },
2444
+ async pull(controller) {
2445
+ const { offset = 0, size, diskNumberStart } = readable;
2446
+ const { chunkOffset } = this;
2447
+ controller.enqueue(await readUint8Array(reader, offset + chunkOffset, Math.min(chunkSize, size - chunkOffset), diskNumberStart));
2448
+ if (chunkOffset + chunkSize > size) {
2449
+ controller.close();
2450
+ } else {
2451
+ this.chunkOffset += chunkSize;
2452
+ }
2453
+ }
2454
+ });
2455
+ return readable;
2456
+ }
2457
+ }
2458
+
2459
+ class Writer extends Stream {
2460
+
2461
+ constructor() {
2462
+ super();
2463
+ const writer = this;
2464
+ const writable = new WritableStream({
2465
+ write(chunk) {
2466
+ return writer.writeUint8Array(chunk);
2467
+ }
2468
+ });
2469
+ Object.defineProperty(writer, PROPERTY_NAME_WRITABLE, {
2470
+ get() {
2471
+ return writable;
2472
+ }
2473
+ });
2474
+ }
2475
+
2476
+ writeUint8Array() {
2477
+ // abstract
2478
+ }
2479
+ }
2480
+
2481
+ class Data64URIReader extends Reader {
2482
+
2483
+ constructor(dataURI) {
2484
+ super();
2485
+ let dataEnd = dataURI.length;
2486
+ while (dataURI.charAt(dataEnd - 1) == "=") {
2487
+ dataEnd--;
2488
+ }
2489
+ const dataStart = dataURI.indexOf(",") + 1;
2490
+ Object.assign(this, {
2491
+ dataURI,
2492
+ dataStart,
2493
+ size: Math.floor((dataEnd - dataStart) * 0.75)
2494
+ });
2495
+ }
2496
+
2497
+ readUint8Array(offset, length) {
2498
+ const {
2499
+ dataStart,
2500
+ dataURI
2501
+ } = this;
2502
+ const dataArray = new Uint8Array(length);
2503
+ const start = Math.floor(offset / 3) * 4;
2504
+ const bytes = atob(dataURI.substring(start + dataStart, Math.ceil((offset + length) / 3) * 4 + dataStart));
2505
+ const delta = offset - Math.floor(start / 4) * 3;
2506
+ for (let indexByte = delta; indexByte < delta + length; indexByte++) {
2507
+ dataArray[indexByte - delta] = bytes.charCodeAt(indexByte);
2508
+ }
2509
+ return dataArray;
2510
+ }
2511
+ }
2512
+
2513
+ class Data64URIWriter extends Writer {
2514
+
2515
+ constructor(contentType) {
2516
+ super();
2517
+ Object.assign(this, {
2518
+ data: "data:" + (contentType || "") + ";base64,",
2519
+ pending: []
2520
+ });
2521
+ }
2522
+
2523
+ writeUint8Array(array) {
2524
+ const writer = this;
2525
+ let indexArray = 0;
2526
+ let dataString = writer.pending;
2527
+ const delta = writer.pending.length;
2528
+ writer.pending = "";
2529
+ for (indexArray = 0; indexArray < (Math.floor((delta + array.length) / 3) * 3) - delta; indexArray++) {
2530
+ dataString += String.fromCharCode(array[indexArray]);
2531
+ }
2532
+ for (; indexArray < array.length; indexArray++) {
2533
+ writer.pending += String.fromCharCode(array[indexArray]);
2534
+ }
2535
+ if (dataString.length > 2) {
2536
+ writer.data += btoa(dataString);
2537
+ } else {
2538
+ writer.pending = dataString;
2539
+ }
2540
+ }
2541
+
2542
+ getData() {
2543
+ return this.data + btoa(this.pending);
2544
+ }
2545
+ }
2546
+
2547
+ class BlobReader extends Reader {
2548
+
2549
+ constructor(blob) {
2550
+ super();
2551
+ Object.assign(this, {
2552
+ blob,
2553
+ size: blob.size
2554
+ });
2555
+ }
2556
+
2557
+ async readUint8Array(offset, length) {
2558
+ const reader = this;
2559
+ const offsetEnd = offset + length;
2560
+ const blob = offset || offsetEnd < reader.size ? reader.blob.slice(offset, offsetEnd) : reader.blob;
2561
+ let arrayBuffer = await blob.arrayBuffer();
2562
+ if (arrayBuffer.byteLength > length) {
2563
+ arrayBuffer = arrayBuffer.slice(offset, offsetEnd);
2564
+ }
2565
+ return new Uint8Array(arrayBuffer);
2566
+ }
2567
+ }
2568
+
2569
+ class BlobWriter extends Stream {
2570
+
2571
+ constructor(contentType) {
2572
+ super();
2573
+ const writer = this;
2574
+ const transformStream = new TransformStream();
2575
+ const headers = [];
2576
+ if (contentType) {
2577
+ headers.push([HTTP_HEADER_CONTENT_TYPE, contentType]);
2578
+ }
2579
+ Object.defineProperty(writer, PROPERTY_NAME_WRITABLE, {
2580
+ get() {
2581
+ return transformStream.writable;
2582
+ }
2583
+ });
2584
+ writer.blob = new Response(transformStream.readable, { headers }).blob();
2585
+ }
2586
+
2587
+ getData() {
2588
+ return this.blob;
2589
+ }
2590
+ }
2591
+
2592
+ class TextReader extends BlobReader {
2593
+
2594
+ constructor(text) {
2595
+ super(new Blob([text], { type: CONTENT_TYPE_TEXT_PLAIN }));
2596
+ }
2597
+ }
2598
+
2599
+ class TextWriter extends BlobWriter {
2600
+
2601
+ constructor(encoding) {
2602
+ super(encoding);
2603
+ Object.assign(this, {
2604
+ encoding,
2605
+ utf8: !encoding || encoding.toLowerCase() == "utf-8"
2606
+ });
2607
+ }
2608
+
2609
+ async getData() {
2610
+ const {
2611
+ encoding,
2612
+ utf8
2613
+ } = this;
2614
+ const blob = await super.getData();
2615
+ if (blob.text && utf8) {
2616
+ return blob.text();
2617
+ } else {
2618
+ const reader = new FileReader();
2619
+ return new Promise((resolve, reject) => {
2620
+ Object.assign(reader, {
2621
+ onload: ({ target }) => resolve(target.result),
2622
+ onerror: () => reject(reader.error)
2623
+ });
2624
+ reader.readAsText(blob, encoding);
2625
+ });
2626
+ }
2627
+ }
2628
+ }
2629
+
2630
+ class FetchReader extends Reader {
2631
+
2632
+ constructor(url, options) {
2633
+ super();
2634
+ createHtpReader(this, url, options);
2635
+ }
2636
+
2637
+ async init() {
2638
+ await initHttpReader(this, sendFetchRequest, getFetchRequestData);
2639
+ super.init();
2640
+ }
2641
+
2642
+ readUint8Array(index, length) {
2643
+ return readUint8ArrayHttpReader(this, index, length, sendFetchRequest, getFetchRequestData);
2644
+ }
2645
+ }
2646
+
2647
+ class XHRReader extends Reader {
2648
+
2649
+ constructor(url, options) {
2650
+ super();
2651
+ createHtpReader(this, url, options);
2652
+ }
2653
+
2654
+ async init() {
2655
+ await initHttpReader(this, sendXMLHttpRequest, getXMLHttpRequestData);
2656
+ super.init();
2657
+ }
2658
+
2659
+ readUint8Array(index, length) {
2660
+ return readUint8ArrayHttpReader(this, index, length, sendXMLHttpRequest, getXMLHttpRequestData);
2661
+ }
2662
+ }
2663
+
2664
+ function createHtpReader(httpReader, url, options) {
2665
+ const {
2666
+ preventHeadRequest,
2667
+ useRangeHeader,
2668
+ forceRangeRequests
2669
+ } = options;
2670
+ options = Object.assign({}, options);
2671
+ delete options.preventHeadRequest;
2672
+ delete options.useRangeHeader;
2673
+ delete options.forceRangeRequests;
2674
+ delete options.useXHR;
2675
+ Object.assign(httpReader, {
2676
+ url,
2677
+ options,
2678
+ preventHeadRequest,
2679
+ useRangeHeader,
2680
+ forceRangeRequests
2681
+ });
2682
+ }
2683
+
2684
+ async function initHttpReader(httpReader, sendRequest, getRequestData) {
2685
+ const {
2686
+ url,
2687
+ useRangeHeader,
2688
+ forceRangeRequests
2689
+ } = httpReader;
2690
+ if (isHttpFamily(url) && (useRangeHeader || forceRangeRequests)) {
2691
+ const { headers } = await sendRequest(HTTP_METHOD_GET, httpReader, getRangeHeaders(httpReader));
2692
+ if (!forceRangeRequests && headers.get(HTTP_HEADER_ACCEPT_RANGES) != HTTP_RANGE_UNIT) {
2693
+ throw new Error(ERR_HTTP_RANGE);
2694
+ } else {
2695
+ let contentSize;
2696
+ const contentRangeHeader = headers.get(HTTP_HEADER_CONTENT_RANGE);
2697
+ if (contentRangeHeader) {
2698
+ const splitHeader = contentRangeHeader.trim().split(/\s*\/\s*/);
2699
+ if (splitHeader.length) {
2700
+ const headerValue = splitHeader[1];
2701
+ if (headerValue && headerValue != "*") {
2702
+ contentSize = Number(headerValue);
2703
+ }
2704
+ }
2705
+ }
2706
+ if (contentSize === UNDEFINED_VALUE) {
2707
+ await getContentLength(httpReader, sendRequest, getRequestData);
2708
+ } else {
2709
+ httpReader.size = contentSize;
2710
+ }
2711
+ }
2712
+ } else {
2713
+ await getContentLength(httpReader, sendRequest, getRequestData);
2714
+ }
2715
+ }
2716
+
2717
+ async function readUint8ArrayHttpReader(httpReader, index, length, sendRequest, getRequestData) {
2718
+ const {
2719
+ useRangeHeader,
2720
+ forceRangeRequests,
2721
+ options
2722
+ } = httpReader;
2723
+ if (useRangeHeader || forceRangeRequests) {
2724
+ const response = await sendRequest(HTTP_METHOD_GET, httpReader, getRangeHeaders(httpReader, index, length));
2725
+ if (response.status != 206) {
2726
+ throw new Error(ERR_HTTP_RANGE);
2727
+ }
2728
+ return new Uint8Array(await response.arrayBuffer());
2729
+ } else {
2730
+ const { data } = httpReader;
2731
+ if (!data) {
2732
+ await getRequestData(httpReader, options);
2733
+ }
2734
+ return new Uint8Array(httpReader.data.subarray(index, index + length));
2735
+ }
2736
+ }
2737
+
2738
+ function getRangeHeaders(httpReader, index = 0, length = 1) {
2739
+ return Object.assign({}, getHeaders(httpReader), { [HTTP_HEADER_RANGE]: HTTP_RANGE_UNIT + "=" + index + "-" + (index + length - 1) });
2740
+ }
2741
+
2742
+ function getHeaders({ options }) {
2743
+ const { headers } = options;
2744
+ if (headers) {
2745
+ if (Symbol.iterator in headers) {
2746
+ return Object.fromEntries(headers);
2747
+ } else {
2748
+ return headers;
2749
+ }
2750
+ }
2751
+ }
2752
+
2753
+ async function getFetchRequestData(httpReader) {
2754
+ await getRequestData(httpReader, sendFetchRequest);
2755
+ }
2756
+
2757
+ async function getXMLHttpRequestData(httpReader) {
2758
+ await getRequestData(httpReader, sendXMLHttpRequest);
2759
+ }
2760
+
2761
+ async function getRequestData(httpReader, sendRequest) {
2762
+ const response = await sendRequest(HTTP_METHOD_GET, httpReader, getHeaders(httpReader));
2763
+ httpReader.data = new Uint8Array(await response.arrayBuffer());
2764
+ if (!httpReader.size) {
2765
+ httpReader.size = httpReader.data.length;
2766
+ }
2767
+ }
2768
+
2769
+ async function getContentLength(httpReader, sendRequest, getRequestData) {
2770
+ if (httpReader.preventHeadRequest) {
2771
+ await getRequestData(httpReader, httpReader.options);
2772
+ } else {
2773
+ const response = await sendRequest(HTTP_METHOD_HEAD, httpReader, getHeaders(httpReader));
2774
+ const contentLength = response.headers.get(HTTP_HEADER_CONTENT_LENGTH);
2775
+ if (contentLength) {
2776
+ httpReader.size = Number(contentLength);
2777
+ } else {
2778
+ await getRequestData(httpReader, httpReader.options);
2779
+ }
2780
+ }
2781
+ }
2782
+
2783
+ async function sendFetchRequest(method, { options, url }, headers) {
2784
+ const response = await fetch(url, Object.assign({}, options, { method, headers }));
2785
+ if (response.status < 400) {
2786
+ return response;
2787
+ } else {
2788
+ throw response.status == 416 ? new Error(ERR_HTTP_RANGE) : new Error(ERR_HTTP_STATUS + (response.statusText || response.status));
2789
+ }
2790
+ }
2791
+
2792
+ function sendXMLHttpRequest(method, { url }, headers) {
2793
+ return new Promise((resolve, reject) => {
2794
+ const request = new XMLHttpRequest();
2795
+ request.addEventListener("load", () => {
2796
+ if (request.status < 400) {
2797
+ const headers = [];
2798
+ request.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(header => {
2799
+ const splitHeader = header.trim().split(/\s*:\s*/);
2800
+ splitHeader[0] = splitHeader[0].trim().replace(/^[a-z]|-[a-z]/g, value => value.toUpperCase());
2801
+ headers.push(splitHeader);
2802
+ });
2803
+ resolve({
2804
+ status: request.status,
2805
+ arrayBuffer: () => request.response,
2806
+ headers: new Map(headers)
2807
+ });
2808
+ } else {
2809
+ reject(request.status == 416 ? new Error(ERR_HTTP_RANGE) : new Error(ERR_HTTP_STATUS + (request.statusText || request.status)));
2810
+ }
2811
+ }, false);
2812
+ request.addEventListener("error", event => reject(event.detail ? event.detail.error : new Error("Network error")), false);
2813
+ request.open(method, url);
2814
+ if (headers) {
2815
+ for (const entry of Object.entries(headers)) {
2816
+ request.setRequestHeader(entry[0], entry[1]);
2817
+ }
2818
+ }
2819
+ request.responseType = "arraybuffer";
2820
+ request.send();
2821
+ });
2822
+ }
2823
+
2824
+ class HttpReader extends Reader {
2825
+
2826
+ constructor(url, options = {}) {
2827
+ super();
2828
+ Object.assign(this, {
2829
+ url,
2830
+ reader: options.useXHR ? new XHRReader(url, options) : new FetchReader(url, options)
2831
+ });
2832
+ }
2833
+
2834
+ set size(value) {
2835
+ // ignored
2836
+ }
2837
+
2838
+ get size() {
2839
+ return this.reader.size;
2840
+ }
2841
+
2842
+ async init() {
2843
+ await this.reader.init();
2844
+ super.init();
2845
+ }
2846
+
2847
+ readUint8Array(index, length) {
2848
+ return this.reader.readUint8Array(index, length);
2849
+ }
2850
+ }
2851
+
2852
+ class HttpRangeReader extends HttpReader {
2853
+
2854
+ constructor(url, options = {}) {
2855
+ options.useRangeHeader = true;
2856
+ super(url, options);
2857
+ }
2858
+ }
2859
+
2860
+
2861
+ class Uint8ArrayReader extends Reader {
2862
+
2863
+ constructor(array) {
2864
+ super();
2865
+ Object.assign(this, {
2866
+ array,
2867
+ size: array.length
2868
+ });
2869
+ }
2870
+
2871
+ readUint8Array(index, length) {
2872
+ return this.array.slice(index, index + length);
2873
+ }
2874
+ }
2875
+
2876
+ class Uint8ArrayWriter extends Writer {
2877
+
2878
+ init(initSize = 0) {
2879
+ Object.assign(this, {
2880
+ offset: 0,
2881
+ array: new Uint8Array(initSize)
2882
+ });
2883
+ super.init();
2884
+ }
2885
+
2886
+ writeUint8Array(array) {
2887
+ const writer = this;
2888
+ if (writer.offset + array.length > writer.array.length) {
2889
+ const previousArray = writer.array;
2890
+ writer.array = new Uint8Array(previousArray.length + array.length);
2891
+ writer.array.set(previousArray);
2892
+ }
2893
+ writer.array.set(array, writer.offset);
2894
+ writer.offset += array.length;
2895
+ }
2896
+
2897
+ getData() {
2898
+ return this.array;
2899
+ }
2900
+ }
2901
+
2902
+ class SplitDataReader extends Reader {
2903
+
2904
+ constructor(readers) {
2905
+ super();
2906
+ this.readers = readers;
2907
+ }
2908
+
2909
+ async init() {
2910
+ const reader = this;
2911
+ const { readers } = reader;
2912
+ reader.lastDiskNumber = 0;
2913
+ reader.lastDiskOffset = 0;
2914
+ await Promise.all(readers.map(async (diskReader, indexDiskReader) => {
2915
+ await diskReader.init();
2916
+ if (indexDiskReader != readers.length - 1) {
2917
+ reader.lastDiskOffset += diskReader.size;
2918
+ }
2919
+ reader.size += diskReader.size;
2920
+ }));
2921
+ super.init();
2922
+ }
2923
+
2924
+ async readUint8Array(offset, length, diskNumber = 0) {
2925
+ const reader = this;
2926
+ const { readers } = this;
2927
+ let result;
2928
+ let currentDiskNumber = diskNumber;
2929
+ if (currentDiskNumber == -1) {
2930
+ currentDiskNumber = readers.length - 1;
2931
+ }
2932
+ let currentReaderOffset = offset;
2933
+ while (currentReaderOffset >= readers[currentDiskNumber].size) {
2934
+ currentReaderOffset -= readers[currentDiskNumber].size;
2935
+ currentDiskNumber++;
2936
+ }
2937
+ const currentReader = readers[currentDiskNumber];
2938
+ const currentReaderSize = currentReader.size;
2939
+ if (currentReaderOffset + length <= currentReaderSize) {
2940
+ result = await readUint8Array(currentReader, currentReaderOffset, length);
2941
+ } else {
2942
+ const chunkLength = currentReaderSize - currentReaderOffset;
2943
+ result = new Uint8Array(length);
2944
+ result.set(await readUint8Array(currentReader, currentReaderOffset, chunkLength));
2945
+ result.set(await reader.readUint8Array(offset + chunkLength, length - chunkLength, diskNumber), chunkLength);
2946
+ }
2947
+ reader.lastDiskNumber = Math.max(currentDiskNumber, reader.lastDiskNumber);
2948
+ return result;
2949
+ }
2950
+ }
2951
+
2952
+ class SplitDataWriter extends Stream {
2953
+
2954
+ constructor(writerGenerator, maxSize = 4294967295) {
2955
+ super();
2956
+ const zipWriter = this;
2957
+ Object.assign(zipWriter, {
2958
+ diskNumber: 0,
2959
+ diskOffset: 0,
2960
+ size: 0,
2961
+ maxSize,
2962
+ availableSize: maxSize
2963
+ });
2964
+ let diskSourceWriter, diskWritable, diskWriter;
2965
+ const writable = new WritableStream({
2966
+ async write(chunk) {
2967
+ const { availableSize } = zipWriter;
2968
+ if (!diskWriter) {
2969
+ const { value, done } = await writerGenerator.next();
2970
+ if (done && !value) {
2971
+ throw new Error(ERR_ITERATOR_COMPLETED_TOO_SOON);
2972
+ } else {
2973
+ diskSourceWriter = value;
2974
+ diskSourceWriter.size = 0;
2975
+ if (diskSourceWriter.maxSize) {
2976
+ zipWriter.maxSize = diskSourceWriter.maxSize;
2977
+ }
2978
+ zipWriter.availableSize = zipWriter.maxSize;
2979
+ await initStream(diskSourceWriter);
2980
+ diskWritable = value.writable;
2981
+ diskWriter = diskWritable.getWriter();
2982
+ }
2983
+ await this.write(chunk);
2984
+ } else if (chunk.length >= availableSize) {
2985
+ await writeChunk(chunk.slice(0, availableSize));
2986
+ await closeDisk();
2987
+ zipWriter.diskOffset += diskSourceWriter.size;
2988
+ zipWriter.diskNumber++;
2989
+ diskWriter = null;
2990
+ await this.write(chunk.slice(availableSize));
2991
+ } else {
2992
+ await writeChunk(chunk);
2993
+ }
2994
+ },
2995
+ async close() {
2996
+ await diskWriter.ready;
2997
+ await closeDisk();
2998
+ }
2999
+ });
3000
+ Object.defineProperty(zipWriter, PROPERTY_NAME_WRITABLE, {
3001
+ get() {
3002
+ return writable;
3003
+ }
3004
+ });
3005
+
3006
+ async function writeChunk(chunk) {
3007
+ const chunkLength = chunk.length;
3008
+ if (chunkLength) {
3009
+ await diskWriter.ready;
3010
+ await diskWriter.write(chunk);
3011
+ diskSourceWriter.size += chunkLength;
3012
+ zipWriter.size += chunkLength;
3013
+ zipWriter.availableSize -= chunkLength;
3014
+ }
3015
+ }
3016
+
3017
+ async function closeDisk() {
3018
+ diskWritable.size = diskSourceWriter.size;
3019
+ await diskWriter.close();
3020
+ }
3021
+ }
3022
+ }
3023
+
3024
+ function isHttpFamily(url) {
3025
+ const { baseURL } = getConfiguration();
3026
+ const { protocol } = new URL(url, baseURL);
3027
+ return protocol == "http:" || protocol == "https:";
3028
+ }
3029
+
3030
+ async function initStream(stream, initSize) {
3031
+ if (stream.init && !stream.initialized) {
3032
+ await stream.init(initSize);
3033
+ }
3034
+ }
3035
+
3036
+ function initReader(reader) {
3037
+ if (Array.isArray(reader)) {
3038
+ reader = new SplitDataReader(reader);
3039
+ }
3040
+ if (reader instanceof ReadableStream) {
3041
+ reader = {
3042
+ readable: reader
3043
+ };
3044
+ }
3045
+ return reader;
3046
+ }
3047
+
3048
+ function initWriter(writer) {
3049
+ if (writer.writable === UNDEFINED_VALUE && typeof writer.next == FUNCTION_TYPE$1) {
3050
+ writer = new SplitDataWriter(writer);
3051
+ }
3052
+ if (writer instanceof WritableStream) {
3053
+ writer = {
3054
+ writable: writer
3055
+ };
3056
+ }
3057
+ const { writable } = writer;
3058
+ if (writable.size === UNDEFINED_VALUE) {
3059
+ writable.size = 0;
3060
+ }
3061
+ const splitZipFile = writer instanceof SplitDataWriter;
3062
+ if (!splitZipFile) {
3063
+ Object.assign(writer, {
3064
+ diskNumber: 0,
3065
+ diskOffset: 0,
3066
+ availableSize: Infinity,
3067
+ maxSize: Infinity
3068
+ });
3069
+ }
3070
+ return writer;
3071
+ }
3072
+
3073
+ function readUint8Array(reader, offset, size, diskNumber) {
3074
+ return reader.readUint8Array(offset, size, diskNumber);
3075
+ }
3076
+
3077
+ const SplitZipReader = SplitDataReader;
3078
+ const SplitZipWriter = SplitDataWriter;
3079
+
3080
+ /*
3081
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
3082
+
3083
+ Redistribution and use in source and binary forms, with or without
3084
+ modification, are permitted provided that the following conditions are met:
3085
+
3086
+ 1. Redistributions of source code must retain the above copyright notice,
3087
+ this list of conditions and the following disclaimer.
3088
+
3089
+ 2. Redistributions in binary form must reproduce the above copyright
3090
+ notice, this list of conditions and the following disclaimer in
3091
+ the documentation and/or other materials provided with the distribution.
3092
+
3093
+ 3. The names of the authors may not be used to endorse or promote products
3094
+ derived from this software without specific prior written permission.
3095
+
3096
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
3097
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
3098
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
3099
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
3100
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3101
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
3102
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
3103
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
3104
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
3105
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3106
+ */
3107
+
3108
+ /* global TextDecoder */
3109
+
3110
+ const CP437 = "\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ".split("");
3111
+ const VALID_CP437 = CP437.length == 256;
3112
+
3113
+ function decodeCP437(stringValue) {
3114
+ if (VALID_CP437) {
3115
+ let result = "";
3116
+ for (let indexCharacter = 0; indexCharacter < stringValue.length; indexCharacter++) {
3117
+ result += CP437[stringValue[indexCharacter]];
3118
+ }
3119
+ return result;
3120
+ } else {
3121
+ return new TextDecoder().decode(stringValue);
3122
+ }
3123
+ }
3124
+
3125
+ /*
3126
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
3127
+
3128
+ Redistribution and use in source and binary forms, with or without
3129
+ modification, are permitted provided that the following conditions are met:
3130
+
3131
+ 1. Redistributions of source code must retain the above copyright notice,
3132
+ this list of conditions and the following disclaimer.
3133
+
3134
+ 2. Redistributions in binary form must reproduce the above copyright
3135
+ notice, this list of conditions and the following disclaimer in
3136
+ the documentation and/or other materials provided with the distribution.
3137
+
3138
+ 3. The names of the authors may not be used to endorse or promote products
3139
+ derived from this software without specific prior written permission.
3140
+
3141
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
3142
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
3143
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
3144
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
3145
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3146
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
3147
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
3148
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
3149
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
3150
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3151
+ */
3152
+
3153
+ function decodeText(value, encoding) {
3154
+ if (encoding && encoding.trim().toLowerCase() == "cp437") {
3155
+ return decodeCP437(value);
3156
+ } else {
3157
+ return new TextDecoder(encoding).decode(value);
3158
+ }
3159
+ }
3160
+
3161
+ /*
3162
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
3163
+
3164
+ Redistribution and use in source and binary forms, with or without
3165
+ modification, are permitted provided that the following conditions are met:
3166
+
3167
+ 1. Redistributions of source code must retain the above copyright notice,
3168
+ this list of conditions and the following disclaimer.
3169
+
3170
+ 2. Redistributions in binary form must reproduce the above copyright
3171
+ notice, this list of conditions and the following disclaimer in
3172
+ the documentation and/or other materials provided with the distribution.
3173
+
3174
+ 3. The names of the authors may not be used to endorse or promote products
3175
+ derived from this software without specific prior written permission.
3176
+
3177
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
3178
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
3179
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
3180
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
3181
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3182
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
3183
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
3184
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
3185
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
3186
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3187
+ */
3188
+
3189
+ const PROPERTY_NAME_FILENAME = "filename";
3190
+ const PROPERTY_NAME_RAW_FILENAME = "rawFilename";
3191
+ const PROPERTY_NAME_COMMENT = "comment";
3192
+ const PROPERTY_NAME_RAW_COMMENT = "rawComment";
3193
+ const PROPERTY_NAME_UNCOMPPRESSED_SIZE = "uncompressedSize";
3194
+ const PROPERTY_NAME_COMPPRESSED_SIZE = "compressedSize";
3195
+ const PROPERTY_NAME_OFFSET = "offset";
3196
+ const PROPERTY_NAME_DISK_NUMBER_START = "diskNumberStart";
3197
+ const PROPERTY_NAME_LAST_MODIFICATION_DATE = "lastModDate";
3198
+ const PROPERTY_NAME_RAW_LAST_MODIFICATION_DATE = "rawLastModDate";
3199
+ const PROPERTY_NAME_LAST_ACCESS_DATE = "lastAccessDate";
3200
+ const PROPERTY_NAME_RAW_LAST_ACCESS_DATE = "rawLastAccessDate";
3201
+ const PROPERTY_NAME_CREATION_DATE = "creationDate";
3202
+ const PROPERTY_NAME_RAW_CREATION_DATE = "rawCreationDate";
3203
+ const PROPERTY_NAME_INTERNAL_FILE_ATTRIBUTE = "internalFileAttribute";
3204
+ const PROPERTY_NAME_EXTERNAL_FILE_ATTRIBUTE = "externalFileAttribute";
3205
+ const PROPERTY_NAME_MS_DOS_COMPATIBLE = "msDosCompatible";
3206
+ const PROPERTY_NAME_ZIP64 = "zip64";
3207
+
3208
+ const PROPERTY_NAMES = [
3209
+ PROPERTY_NAME_FILENAME, PROPERTY_NAME_RAW_FILENAME, PROPERTY_NAME_COMPPRESSED_SIZE, PROPERTY_NAME_UNCOMPPRESSED_SIZE,
3210
+ PROPERTY_NAME_LAST_MODIFICATION_DATE, PROPERTY_NAME_RAW_LAST_MODIFICATION_DATE, PROPERTY_NAME_COMMENT, PROPERTY_NAME_RAW_COMMENT,
3211
+ PROPERTY_NAME_LAST_ACCESS_DATE, PROPERTY_NAME_CREATION_DATE, PROPERTY_NAME_OFFSET, PROPERTY_NAME_DISK_NUMBER_START,
3212
+ PROPERTY_NAME_DISK_NUMBER_START, PROPERTY_NAME_INTERNAL_FILE_ATTRIBUTE, PROPERTY_NAME_EXTERNAL_FILE_ATTRIBUTE,
3213
+ PROPERTY_NAME_MS_DOS_COMPATIBLE, PROPERTY_NAME_ZIP64,
3214
+ "directory", "bitFlag", "encrypted", "signature", "filenameUTF8", "commentUTF8", "compressionMethod", "version", "versionMadeBy",
3215
+ "extraField", "rawExtraField", "extraFieldZip64", "extraFieldUnicodePath", "extraFieldUnicodeComment", "extraFieldAES", "extraFieldNTFS",
3216
+ "extraFieldExtendedTimestamp"];
3217
+
3218
+ class Entry {
3219
+
3220
+ constructor(data) {
3221
+ PROPERTY_NAMES.forEach(name => this[name] = data[name]);
3222
+ }
3223
+
3224
+ }
3225
+
3226
+ /*
3227
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
3228
+
3229
+ Redistribution and use in source and binary forms, with or without
3230
+ modification, are permitted provided that the following conditions are met:
3231
+
3232
+ 1. Redistributions of source code must retain the above copyright notice,
3233
+ this list of conditions and the following disclaimer.
3234
+
3235
+ 2. Redistributions in binary form must reproduce the above copyright
3236
+ notice, this list of conditions and the following disclaimer in
3237
+ the documentation and/or other materials provided with the distribution.
3238
+
3239
+ 3. The names of the authors may not be used to endorse or promote products
3240
+ derived from this software without specific prior written permission.
3241
+
3242
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
3243
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
3244
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
3245
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
3246
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3247
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
3248
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
3249
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
3250
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
3251
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3252
+ */
3253
+
3254
+ const ERR_BAD_FORMAT = "File format is not recognized";
3255
+ const ERR_EOCDR_NOT_FOUND = "End of central directory not found";
3256
+ const ERR_EOCDR_ZIP64_NOT_FOUND = "End of Zip64 central directory not found";
3257
+ const ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND = "End of Zip64 central directory locator not found";
3258
+ const ERR_CENTRAL_DIRECTORY_NOT_FOUND = "Central directory header not found";
3259
+ const ERR_LOCAL_FILE_HEADER_NOT_FOUND = "Local file header not found";
3260
+ const ERR_EXTRAFIELD_ZIP64_NOT_FOUND = "Zip64 extra field not found";
3261
+ const ERR_ENCRYPTED = "File contains encrypted entry";
3262
+ const ERR_UNSUPPORTED_ENCRYPTION = "Encryption method not supported";
3263
+ const ERR_UNSUPPORTED_COMPRESSION = "Compression method not supported";
3264
+ const ERR_SPLIT_ZIP_FILE = "Split zip file";
3265
+ const CHARSET_UTF8 = "utf-8";
3266
+ const CHARSET_CP437 = "cp437";
3267
+ const ZIP64_PROPERTIES = [
3268
+ [PROPERTY_NAME_UNCOMPPRESSED_SIZE, MAX_32_BITS],
3269
+ [PROPERTY_NAME_COMPPRESSED_SIZE, MAX_32_BITS],
3270
+ [PROPERTY_NAME_OFFSET, MAX_32_BITS],
3271
+ [PROPERTY_NAME_DISK_NUMBER_START, MAX_16_BITS]
3272
+ ];
3273
+ const ZIP64_EXTRACTION = {
3274
+ [MAX_16_BITS]: {
3275
+ getValue: getUint32,
3276
+ bytes: 4
3277
+ },
3278
+ [MAX_32_BITS]: {
3279
+ getValue: getBigUint64,
3280
+ bytes: 8
3281
+ }
3282
+ };
3283
+
3284
+ class ZipReader {
3285
+
3286
+ constructor(reader, options = {}) {
3287
+ Object.assign(this, {
3288
+ reader: initReader(reader),
3289
+ options,
3290
+ config: getConfiguration()
3291
+ });
3292
+ }
3293
+
3294
+ async* getEntriesGenerator(options = {}) {
3295
+ const zipReader = this;
3296
+ let { reader } = zipReader;
3297
+ const { config } = zipReader;
3298
+ await initStream(reader);
3299
+ if (reader.size === UNDEFINED_VALUE || !reader.readUint8Array) {
3300
+ reader = new BlobReader(await new Response(reader.readable).blob());
3301
+ await initStream(reader);
3302
+ }
3303
+ if (reader.size < END_OF_CENTRAL_DIR_LENGTH) {
3304
+ throw new Error(ERR_BAD_FORMAT);
3305
+ }
3306
+ reader.chunkSize = getChunkSize(config);
3307
+ const endOfDirectoryInfo = await seekSignature(reader, END_OF_CENTRAL_DIR_SIGNATURE, reader.size, END_OF_CENTRAL_DIR_LENGTH, MAX_16_BITS * 16);
3308
+ if (!endOfDirectoryInfo) {
3309
+ const signatureArray = await readUint8Array(reader, 0, 4);
3310
+ const signatureView = getDataView$1(signatureArray);
3311
+ if (getUint32(signatureView) == SPLIT_ZIP_FILE_SIGNATURE) {
3312
+ throw new Error(ERR_SPLIT_ZIP_FILE);
3313
+ } else {
3314
+ throw new Error(ERR_EOCDR_NOT_FOUND);
3315
+ }
3316
+ }
3317
+ const endOfDirectoryView = getDataView$1(endOfDirectoryInfo);
3318
+ let directoryDataLength = getUint32(endOfDirectoryView, 12);
3319
+ let directoryDataOffset = getUint32(endOfDirectoryView, 16);
3320
+ const commentOffset = endOfDirectoryInfo.offset;
3321
+ const commentLength = getUint16(endOfDirectoryView, 20);
3322
+ const appendedDataOffset = commentOffset + END_OF_CENTRAL_DIR_LENGTH + commentLength;
3323
+ let lastDiskNumber = getUint16(endOfDirectoryView, 4);
3324
+ const expectedLastDiskNumber = reader.lastDiskNumber || 0;
3325
+ let diskNumber = getUint16(endOfDirectoryView, 6);
3326
+ let filesLength = getUint16(endOfDirectoryView, 8);
3327
+ let prependedDataLength = 0;
3328
+ let startOffset = 0;
3329
+ if (directoryDataOffset == MAX_32_BITS || directoryDataLength == MAX_32_BITS || filesLength == MAX_16_BITS || diskNumber == MAX_16_BITS) {
3330
+ const endOfDirectoryLocatorArray = await readUint8Array(reader, endOfDirectoryInfo.offset - ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH, ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH);
3331
+ const endOfDirectoryLocatorView = getDataView$1(endOfDirectoryLocatorArray);
3332
+ if (getUint32(endOfDirectoryLocatorView, 0) != ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE) {
3333
+ throw new Error(ERR_EOCDR_ZIP64_NOT_FOUND);
3334
+ }
3335
+ directoryDataOffset = getBigUint64(endOfDirectoryLocatorView, 8);
3336
+ let endOfDirectoryArray = await readUint8Array(reader, directoryDataOffset, ZIP64_END_OF_CENTRAL_DIR_LENGTH, -1);
3337
+ let endOfDirectoryView = getDataView$1(endOfDirectoryArray);
3338
+ const expectedDirectoryDataOffset = endOfDirectoryInfo.offset - ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH - ZIP64_END_OF_CENTRAL_DIR_LENGTH;
3339
+ if (getUint32(endOfDirectoryView, 0) != ZIP64_END_OF_CENTRAL_DIR_SIGNATURE && directoryDataOffset != expectedDirectoryDataOffset) {
3340
+ const originalDirectoryDataOffset = directoryDataOffset;
3341
+ directoryDataOffset = expectedDirectoryDataOffset;
3342
+ prependedDataLength = directoryDataOffset - originalDirectoryDataOffset;
3343
+ endOfDirectoryArray = await readUint8Array(reader, directoryDataOffset, ZIP64_END_OF_CENTRAL_DIR_LENGTH, -1);
3344
+ endOfDirectoryView = getDataView$1(endOfDirectoryArray);
3345
+ }
3346
+ if (getUint32(endOfDirectoryView, 0) != ZIP64_END_OF_CENTRAL_DIR_SIGNATURE) {
3347
+ throw new Error(ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND);
3348
+ }
3349
+ if (lastDiskNumber == MAX_16_BITS) {
3350
+ lastDiskNumber = getUint32(endOfDirectoryView, 16);
3351
+ }
3352
+ if (diskNumber == MAX_16_BITS) {
3353
+ diskNumber = getUint32(endOfDirectoryView, 20);
3354
+ }
3355
+ if (filesLength == MAX_16_BITS) {
3356
+ filesLength = getBigUint64(endOfDirectoryView, 32);
3357
+ }
3358
+ if (directoryDataLength == MAX_32_BITS) {
3359
+ directoryDataLength = getBigUint64(endOfDirectoryView, 40);
3360
+ }
3361
+ directoryDataOffset -= directoryDataLength;
3362
+ }
3363
+ if (expectedLastDiskNumber != lastDiskNumber) {
3364
+ throw new Error(ERR_SPLIT_ZIP_FILE);
3365
+ }
3366
+ if (directoryDataOffset < 0 || directoryDataOffset >= reader.size) {
3367
+ throw new Error(ERR_BAD_FORMAT);
3368
+ }
3369
+ let offset = 0;
3370
+ let directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength, diskNumber);
3371
+ let directoryView = getDataView$1(directoryArray);
3372
+ if (directoryDataLength) {
3373
+ const expectedDirectoryDataOffset = endOfDirectoryInfo.offset - directoryDataLength;
3374
+ if (getUint32(directoryView, offset) != CENTRAL_FILE_HEADER_SIGNATURE && directoryDataOffset != expectedDirectoryDataOffset) {
3375
+ const originalDirectoryDataOffset = directoryDataOffset;
3376
+ directoryDataOffset = expectedDirectoryDataOffset;
3377
+ prependedDataLength = directoryDataOffset - originalDirectoryDataOffset;
3378
+ directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength, diskNumber);
3379
+ directoryView = getDataView$1(directoryArray);
3380
+ }
3381
+ }
3382
+ const expectedDirectoryDataLength = endOfDirectoryInfo.offset - directoryDataOffset - (reader.lastDiskOffset || 0);
3383
+ if (directoryDataLength != expectedDirectoryDataLength && expectedDirectoryDataLength >= 0) {
3384
+ directoryDataLength = expectedDirectoryDataLength;
3385
+ directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength, diskNumber);
3386
+ directoryView = getDataView$1(directoryArray);
3387
+ }
3388
+ if (directoryDataOffset < 0 || directoryDataOffset >= reader.size) {
3389
+ throw new Error(ERR_BAD_FORMAT);
3390
+ }
3391
+ const filenameEncoding = getOptionValue$1(zipReader, options, "filenameEncoding");
3392
+ const commentEncoding = getOptionValue$1(zipReader, options, "commentEncoding");
3393
+ for (let indexFile = 0; indexFile < filesLength; indexFile++) {
3394
+ const fileEntry = new ZipEntry(reader, config, zipReader.options);
3395
+ if (getUint32(directoryView, offset) != CENTRAL_FILE_HEADER_SIGNATURE) {
3396
+ throw new Error(ERR_CENTRAL_DIRECTORY_NOT_FOUND);
3397
+ }
3398
+ readCommonHeader(fileEntry, directoryView, offset + 6);
3399
+ const languageEncodingFlag = Boolean(fileEntry.bitFlag.languageEncodingFlag);
3400
+ const filenameOffset = offset + 46;
3401
+ const extraFieldOffset = filenameOffset + fileEntry.filenameLength;
3402
+ const commentOffset = extraFieldOffset + fileEntry.extraFieldLength;
3403
+ const versionMadeBy = getUint16(directoryView, offset + 4);
3404
+ const msDosCompatible = (versionMadeBy & 0) == 0;
3405
+ const rawFilename = directoryArray.subarray(filenameOffset, extraFieldOffset);
3406
+ const commentLength = getUint16(directoryView, offset + 32);
3407
+ const endOffset = commentOffset + commentLength;
3408
+ const rawComment = directoryArray.subarray(commentOffset, endOffset);
3409
+ const filenameUTF8 = languageEncodingFlag;
3410
+ const commentUTF8 = languageEncodingFlag;
3411
+ const directory = msDosCompatible && ((getUint8(directoryView, offset + 38) & FILE_ATTR_MSDOS_DIR_MASK) == FILE_ATTR_MSDOS_DIR_MASK);
3412
+ const offsetFileEntry = getUint32(directoryView, offset + 42) + prependedDataLength;
3413
+ Object.assign(fileEntry, {
3414
+ versionMadeBy,
3415
+ msDosCompatible,
3416
+ compressedSize: 0,
3417
+ uncompressedSize: 0,
3418
+ commentLength,
3419
+ directory,
3420
+ offset: offsetFileEntry,
3421
+ diskNumberStart: getUint16(directoryView, offset + 34),
3422
+ internalFileAttribute: getUint16(directoryView, offset + 36),
3423
+ externalFileAttribute: getUint32(directoryView, offset + 38),
3424
+ rawFilename,
3425
+ filenameUTF8,
3426
+ commentUTF8,
3427
+ rawExtraField: directoryArray.subarray(extraFieldOffset, commentOffset)
3428
+ });
3429
+ const [filename, comment] = await Promise.all([
3430
+ decodeText(rawFilename, filenameUTF8 ? CHARSET_UTF8 : filenameEncoding || CHARSET_CP437),
3431
+ decodeText(rawComment, commentUTF8 ? CHARSET_UTF8 : commentEncoding || CHARSET_CP437)
3432
+ ]);
3433
+ Object.assign(fileEntry, {
3434
+ rawComment,
3435
+ filename,
3436
+ comment,
3437
+ directory: directory || filename.endsWith(DIRECTORY_SIGNATURE)
3438
+ });
3439
+ startOffset = Math.max(offsetFileEntry, startOffset);
3440
+ await readCommonFooter(fileEntry, fileEntry, directoryView, offset + 6);
3441
+ const entry = new Entry(fileEntry);
3442
+ entry.getData = (writer, options) => fileEntry.getData(writer, entry, options);
3443
+ offset = endOffset;
3444
+ const { onprogress } = options;
3445
+ if (onprogress) {
3446
+ try {
3447
+ await onprogress(indexFile + 1, filesLength, new Entry(fileEntry));
3448
+ } catch (_error) {
3449
+ // ignored
3450
+ }
3451
+ }
3452
+ yield entry;
3453
+ }
3454
+ const extractPrependedData = getOptionValue$1(zipReader, options, "extractPrependedData");
3455
+ const extractAppendedData = getOptionValue$1(zipReader, options, "extractAppendedData");
3456
+ if (extractPrependedData) {
3457
+ zipReader.prependedData = startOffset > 0 ? await readUint8Array(reader, 0, startOffset) : new Uint8Array();
3458
+ }
3459
+ zipReader.comment = commentLength ? await readUint8Array(reader, commentOffset + END_OF_CENTRAL_DIR_LENGTH, commentLength) : new Uint8Array();
3460
+ if (extractAppendedData) {
3461
+ zipReader.appendedData = appendedDataOffset < reader.size ? await readUint8Array(reader, appendedDataOffset, reader.size - appendedDataOffset) : new Uint8Array();
3462
+ }
3463
+ return true;
3464
+ }
3465
+
3466
+ async getEntries(options = {}) {
3467
+ const entries = [];
3468
+ for await (const entry of this.getEntriesGenerator(options)) {
3469
+ entries.push(entry);
3470
+ }
3471
+ return entries;
3472
+ }
3473
+
3474
+ async close() {
3475
+ }
3476
+ }
3477
+
3478
+ class ZipEntry {
3479
+
3480
+ constructor(reader, config, options) {
3481
+ Object.assign(this, {
3482
+ reader,
3483
+ config,
3484
+ options
3485
+ });
3486
+ }
3487
+
3488
+ async getData(writer, fileEntry, options = {}) {
3489
+ const zipEntry = this;
3490
+ const {
3491
+ reader,
3492
+ offset,
3493
+ diskNumberStart,
3494
+ extraFieldAES,
3495
+ compressionMethod,
3496
+ config,
3497
+ bitFlag,
3498
+ signature,
3499
+ rawLastModDate,
3500
+ uncompressedSize,
3501
+ compressedSize
3502
+ } = zipEntry;
3503
+ const localDirectory = fileEntry.localDirectory = {};
3504
+ const dataArray = await readUint8Array(reader, offset, 30, diskNumberStart);
3505
+ const dataView = getDataView$1(dataArray);
3506
+ let password = getOptionValue$1(zipEntry, options, "password");
3507
+ password = password && password.length && password;
3508
+ if (extraFieldAES) {
3509
+ if (extraFieldAES.originalCompressionMethod != COMPRESSION_METHOD_AES) {
3510
+ throw new Error(ERR_UNSUPPORTED_COMPRESSION);
3511
+ }
3512
+ }
3513
+ if (compressionMethod != COMPRESSION_METHOD_STORE && compressionMethod != COMPRESSION_METHOD_DEFLATE) {
3514
+ throw new Error(ERR_UNSUPPORTED_COMPRESSION);
3515
+ }
3516
+ if (getUint32(dataView, 0) != LOCAL_FILE_HEADER_SIGNATURE) {
3517
+ throw new Error(ERR_LOCAL_FILE_HEADER_NOT_FOUND);
3518
+ }
3519
+ readCommonHeader(localDirectory, dataView, 4);
3520
+ localDirectory.rawExtraField = localDirectory.extraFieldLength ?
3521
+ await readUint8Array(reader, offset + 30 + localDirectory.filenameLength, localDirectory.extraFieldLength, diskNumberStart) :
3522
+ new Uint8Array();
3523
+ await readCommonFooter(zipEntry, localDirectory, dataView, 4, true);
3524
+ Object.assign(fileEntry, {
3525
+ lastAccessDate: localDirectory.lastAccessDate,
3526
+ creationDate: localDirectory.creationDate
3527
+ });
3528
+ const encrypted = zipEntry.encrypted && localDirectory.encrypted;
3529
+ const zipCrypto = encrypted && !extraFieldAES;
3530
+ if (encrypted) {
3531
+ if (!zipCrypto && extraFieldAES.strength === UNDEFINED_VALUE) {
3532
+ throw new Error(ERR_UNSUPPORTED_ENCRYPTION);
3533
+ } else if (!password) {
3534
+ throw new Error(ERR_ENCRYPTED);
3535
+ }
3536
+ }
3537
+ const dataOffset = offset + 30 + localDirectory.filenameLength + localDirectory.extraFieldLength;
3538
+ const size = compressedSize;
3539
+ const readable = reader.readable;
3540
+ Object.assign(readable, {
3541
+ diskNumberStart,
3542
+ offset: dataOffset,
3543
+ size
3544
+ });
3545
+ const signal = getOptionValue$1(zipEntry, options, "signal");
3546
+ const checkPasswordOnly = getOptionValue$1(zipEntry, options, "checkPasswordOnly");
3547
+ if (checkPasswordOnly) {
3548
+ writer = new WritableStream();
3549
+ }
3550
+ writer = initWriter(writer);
3551
+ await initStream(writer, uncompressedSize);
3552
+ const { writable } = writer;
3553
+ const { onstart, onprogress, onend } = options;
3554
+ const workerOptions = {
3555
+ options: {
3556
+ codecType: CODEC_INFLATE,
3557
+ password,
3558
+ zipCrypto,
3559
+ encryptionStrength: extraFieldAES && extraFieldAES.strength,
3560
+ signed: getOptionValue$1(zipEntry, options, "checkSignature"),
3561
+ passwordVerification: zipCrypto && (bitFlag.dataDescriptor ? ((rawLastModDate >>> 8) & 0xFF) : ((signature >>> 24) & 0xFF)),
3562
+ signature,
3563
+ compressed: compressionMethod != 0,
3564
+ encrypted,
3565
+ useWebWorkers: getOptionValue$1(zipEntry, options, "useWebWorkers"),
3566
+ useCompressionStream: getOptionValue$1(zipEntry, options, "useCompressionStream"),
3567
+ transferStreams: getOptionValue$1(zipEntry, options, "transferStreams"),
3568
+ checkPasswordOnly
3569
+ },
3570
+ config,
3571
+ streamOptions: { signal, size, onstart, onprogress, onend }
3572
+ };
3573
+ let outputSize = 0;
3574
+ try {
3575
+ ({ outputSize } = (await runWorker({ readable, writable }, workerOptions)));
3576
+ } catch (error) {
3577
+ if (!checkPasswordOnly || error.message != ERR_ABORT_CHECK_PASSWORD) {
3578
+ throw error;
3579
+ }
3580
+ } finally {
3581
+ const preventClose = getOptionValue$1(zipEntry, options, "preventClose");
3582
+ writable.size += outputSize;
3583
+ if (!preventClose && !writable.locked) {
3584
+ await writable.getWriter().close();
3585
+ }
3586
+ }
3587
+ return checkPasswordOnly ? undefined : writer.getData ? writer.getData() : writable;
3588
+ }
3589
+ }
3590
+
3591
+ function readCommonHeader(directory, dataView, offset) {
3592
+ const rawBitFlag = directory.rawBitFlag = getUint16(dataView, offset + 2);
3593
+ const encrypted = (rawBitFlag & BITFLAG_ENCRYPTED) == BITFLAG_ENCRYPTED;
3594
+ const rawLastModDate = getUint32(dataView, offset + 6);
3595
+ Object.assign(directory, {
3596
+ encrypted,
3597
+ version: getUint16(dataView, offset),
3598
+ bitFlag: {
3599
+ level: (rawBitFlag & BITFLAG_LEVEL) >> 1,
3600
+ dataDescriptor: (rawBitFlag & BITFLAG_DATA_DESCRIPTOR) == BITFLAG_DATA_DESCRIPTOR,
3601
+ languageEncodingFlag: (rawBitFlag & BITFLAG_LANG_ENCODING_FLAG) == BITFLAG_LANG_ENCODING_FLAG
3602
+ },
3603
+ rawLastModDate,
3604
+ lastModDate: getDate(rawLastModDate),
3605
+ filenameLength: getUint16(dataView, offset + 22),
3606
+ extraFieldLength: getUint16(dataView, offset + 24)
3607
+ });
3608
+ }
3609
+
3610
+ async function readCommonFooter(fileEntry, directory, dataView, offset, localDirectory) {
3611
+ const { rawExtraField } = directory;
3612
+ const extraField = directory.extraField = new Map();
3613
+ const rawExtraFieldView = getDataView$1(new Uint8Array(rawExtraField));
3614
+ let offsetExtraField = 0;
3615
+ try {
3616
+ while (offsetExtraField < rawExtraField.length) {
3617
+ const type = getUint16(rawExtraFieldView, offsetExtraField);
3618
+ const size = getUint16(rawExtraFieldView, offsetExtraField + 2);
3619
+ extraField.set(type, {
3620
+ type,
3621
+ data: rawExtraField.slice(offsetExtraField + 4, offsetExtraField + 4 + size)
3622
+ });
3623
+ offsetExtraField += 4 + size;
3624
+ }
3625
+ } catch (_error) {
3626
+ // ignored
3627
+ }
3628
+ const compressionMethod = getUint16(dataView, offset + 4);
3629
+ Object.assign(directory, {
3630
+ signature: getUint32(dataView, offset + 10),
3631
+ uncompressedSize: getUint32(dataView, offset + 18),
3632
+ compressedSize: getUint32(dataView, offset + 14)
3633
+ });
3634
+ const extraFieldZip64 = extraField.get(EXTRAFIELD_TYPE_ZIP64);
3635
+ if (extraFieldZip64) {
3636
+ readExtraFieldZip64(extraFieldZip64, directory);
3637
+ directory.extraFieldZip64 = extraFieldZip64;
3638
+ }
3639
+ const extraFieldUnicodePath = extraField.get(EXTRAFIELD_TYPE_UNICODE_PATH);
3640
+ if (extraFieldUnicodePath) {
3641
+ await readExtraFieldUnicode(extraFieldUnicodePath, PROPERTY_NAME_FILENAME, PROPERTY_NAME_RAW_FILENAME, directory, fileEntry);
3642
+ directory.extraFieldUnicodePath = extraFieldUnicodePath;
3643
+ }
3644
+ const extraFieldUnicodeComment = extraField.get(EXTRAFIELD_TYPE_UNICODE_COMMENT);
3645
+ if (extraFieldUnicodeComment) {
3646
+ await readExtraFieldUnicode(extraFieldUnicodeComment, PROPERTY_NAME_COMMENT, PROPERTY_NAME_RAW_COMMENT, directory, fileEntry);
3647
+ directory.extraFieldUnicodeComment = extraFieldUnicodeComment;
3648
+ }
3649
+ const extraFieldAES = extraField.get(EXTRAFIELD_TYPE_AES);
3650
+ if (extraFieldAES) {
3651
+ readExtraFieldAES(extraFieldAES, directory, compressionMethod);
3652
+ directory.extraFieldAES = extraFieldAES;
3653
+ } else {
3654
+ directory.compressionMethod = compressionMethod;
3655
+ }
3656
+ const extraFieldNTFS = extraField.get(EXTRAFIELD_TYPE_NTFS);
3657
+ if (extraFieldNTFS) {
3658
+ readExtraFieldNTFS(extraFieldNTFS, directory);
3659
+ directory.extraFieldNTFS = extraFieldNTFS;
3660
+ }
3661
+ const extraFieldExtendedTimestamp = extraField.get(EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
3662
+ if (extraFieldExtendedTimestamp) {
3663
+ readExtraFieldExtendedTimestamp(extraFieldExtendedTimestamp, directory, localDirectory);
3664
+ directory.extraFieldExtendedTimestamp = extraFieldExtendedTimestamp;
3665
+ }
3666
+ const extraFieldUSDZ = extraField.get(EXTRAFIELD_TYPE_USDZ);
3667
+ if (extraFieldUSDZ) {
3668
+ directory.extraFieldUSDZ = extraFieldUSDZ;
3669
+ }
3670
+ }
3671
+
3672
+ function readExtraFieldZip64(extraFieldZip64, directory) {
3673
+ directory.zip64 = true;
3674
+ const extraFieldView = getDataView$1(extraFieldZip64.data);
3675
+ const missingProperties = ZIP64_PROPERTIES.filter(([propertyName, max]) => directory[propertyName] == max);
3676
+ for (let indexMissingProperty = 0, offset = 0; indexMissingProperty < missingProperties.length; indexMissingProperty++) {
3677
+ const [propertyName, max] = missingProperties[indexMissingProperty];
3678
+ if (directory[propertyName] == max) {
3679
+ const extraction = ZIP64_EXTRACTION[max];
3680
+ directory[propertyName] = extraFieldZip64[propertyName] = extraction.getValue(extraFieldView, offset);
3681
+ offset += extraction.bytes;
3682
+ } else if (extraFieldZip64[propertyName]) {
3683
+ throw new Error(ERR_EXTRAFIELD_ZIP64_NOT_FOUND);
3684
+ }
3685
+ }
3686
+ }
3687
+
3688
+ async function readExtraFieldUnicode(extraFieldUnicode, propertyName, rawPropertyName, directory, fileEntry) {
3689
+ const extraFieldView = getDataView$1(extraFieldUnicode.data);
3690
+ const crc32 = new Crc32();
3691
+ crc32.append(fileEntry[rawPropertyName]);
3692
+ const dataViewSignature = getDataView$1(new Uint8Array(4));
3693
+ dataViewSignature.setUint32(0, crc32.get(), true);
3694
+ const signature = getUint32(extraFieldView, 1);
3695
+ Object.assign(extraFieldUnicode, {
3696
+ version: getUint8(extraFieldView, 0),
3697
+ [propertyName]: decodeText(extraFieldUnicode.data.subarray(5)),
3698
+ valid: !fileEntry.bitFlag.languageEncodingFlag && signature == getUint32(dataViewSignature, 0)
3699
+ });
3700
+ if (extraFieldUnicode.valid) {
3701
+ directory[propertyName] = extraFieldUnicode[propertyName];
3702
+ directory[propertyName + "UTF8"] = true;
3703
+ }
3704
+ }
3705
+
3706
+ function readExtraFieldAES(extraFieldAES, directory, compressionMethod) {
3707
+ const extraFieldView = getDataView$1(extraFieldAES.data);
3708
+ const strength = getUint8(extraFieldView, 4);
3709
+ Object.assign(extraFieldAES, {
3710
+ vendorVersion: getUint8(extraFieldView, 0),
3711
+ vendorId: getUint8(extraFieldView, 2),
3712
+ strength,
3713
+ originalCompressionMethod: compressionMethod,
3714
+ compressionMethod: getUint16(extraFieldView, 5)
3715
+ });
3716
+ directory.compressionMethod = extraFieldAES.compressionMethod;
3717
+ }
3718
+
3719
+ function readExtraFieldNTFS(extraFieldNTFS, directory) {
3720
+ const extraFieldView = getDataView$1(extraFieldNTFS.data);
3721
+ let offsetExtraField = 4;
3722
+ let tag1Data;
3723
+ try {
3724
+ while (offsetExtraField < extraFieldNTFS.data.length && !tag1Data) {
3725
+ const tagValue = getUint16(extraFieldView, offsetExtraField);
3726
+ const attributeSize = getUint16(extraFieldView, offsetExtraField + 2);
3727
+ if (tagValue == EXTRAFIELD_TYPE_NTFS_TAG1) {
3728
+ tag1Data = extraFieldNTFS.data.slice(offsetExtraField + 4, offsetExtraField + 4 + attributeSize);
3729
+ }
3730
+ offsetExtraField += 4 + attributeSize;
3731
+ }
3732
+ } catch (_error) {
3733
+ // ignored
3734
+ }
3735
+ try {
3736
+ if (tag1Data && tag1Data.length == 24) {
3737
+ const tag1View = getDataView$1(tag1Data);
3738
+ const rawLastModDate = tag1View.getBigUint64(0, true);
3739
+ const rawLastAccessDate = tag1View.getBigUint64(8, true);
3740
+ const rawCreationDate = tag1View.getBigUint64(16, true);
3741
+ Object.assign(extraFieldNTFS, {
3742
+ rawLastModDate,
3743
+ rawLastAccessDate,
3744
+ rawCreationDate
3745
+ });
3746
+ const lastModDate = getDateNTFS(rawLastModDate);
3747
+ const lastAccessDate = getDateNTFS(rawLastAccessDate);
3748
+ const creationDate = getDateNTFS(rawCreationDate);
3749
+ const extraFieldData = { lastModDate, lastAccessDate, creationDate };
3750
+ Object.assign(extraFieldNTFS, extraFieldData);
3751
+ Object.assign(directory, extraFieldData);
3752
+ }
3753
+ } catch (_error) {
3754
+ // ignored
3755
+ }
3756
+ }
3757
+
3758
+ function readExtraFieldExtendedTimestamp(extraFieldExtendedTimestamp, directory, localDirectory) {
3759
+ const extraFieldView = getDataView$1(extraFieldExtendedTimestamp.data);
3760
+ const flags = getUint8(extraFieldView, 0);
3761
+ const timeProperties = [];
3762
+ const timeRawProperties = [];
3763
+ if (localDirectory) {
3764
+ if ((flags & 0x1) == 0x1) {
3765
+ timeProperties.push(PROPERTY_NAME_LAST_MODIFICATION_DATE);
3766
+ timeRawProperties.push(PROPERTY_NAME_RAW_LAST_MODIFICATION_DATE);
3767
+ }
3768
+ if ((flags & 0x2) == 0x2) {
3769
+ timeProperties.push(PROPERTY_NAME_LAST_ACCESS_DATE);
3770
+ timeRawProperties.push(PROPERTY_NAME_RAW_LAST_ACCESS_DATE);
3771
+ }
3772
+ if ((flags & 0x4) == 0x4) {
3773
+ timeProperties.push(PROPERTY_NAME_CREATION_DATE);
3774
+ timeRawProperties.push(PROPERTY_NAME_RAW_CREATION_DATE);
3775
+ }
3776
+ } else if (extraFieldExtendedTimestamp.data.length >= 5) {
3777
+ timeProperties.push(PROPERTY_NAME_LAST_MODIFICATION_DATE);
3778
+ timeRawProperties.push(PROPERTY_NAME_RAW_LAST_MODIFICATION_DATE);
3779
+ }
3780
+ let offset = 1;
3781
+ timeProperties.forEach((propertyName, indexProperty) => {
3782
+ if (extraFieldExtendedTimestamp.data.length >= offset + 4) {
3783
+ const time = getUint32(extraFieldView, offset);
3784
+ directory[propertyName] = extraFieldExtendedTimestamp[propertyName] = new Date(time * 1000);
3785
+ const rawPropertyName = timeRawProperties[indexProperty];
3786
+ extraFieldExtendedTimestamp[rawPropertyName] = time;
3787
+ }
3788
+ offset += 4;
3789
+ });
3790
+ }
3791
+
3792
+ async function seekSignature(reader, signature, startOffset, minimumBytes, maximumLength) {
3793
+ const signatureArray = new Uint8Array(4);
3794
+ const signatureView = getDataView$1(signatureArray);
3795
+ setUint32$1(signatureView, 0, signature);
3796
+ const maximumBytes = minimumBytes + maximumLength;
3797
+ return (await seek(minimumBytes)) || await seek(Math.min(maximumBytes, startOffset));
3798
+
3799
+ async function seek(length) {
3800
+ const offset = startOffset - length;
3801
+ const bytes = await readUint8Array(reader, offset, length);
3802
+ for (let indexByte = bytes.length - minimumBytes; indexByte >= 0; indexByte--) {
3803
+ if (bytes[indexByte] == signatureArray[0] && bytes[indexByte + 1] == signatureArray[1] &&
3804
+ bytes[indexByte + 2] == signatureArray[2] && bytes[indexByte + 3] == signatureArray[3]) {
3805
+ return {
3806
+ offset: offset + indexByte,
3807
+ buffer: bytes.slice(indexByte, indexByte + minimumBytes).buffer
3808
+ };
3809
+ }
3810
+ }
3811
+ }
3812
+ }
3813
+
3814
+ function getOptionValue$1(zipReader, options, name) {
3815
+ return options[name] === UNDEFINED_VALUE ? zipReader.options[name] : options[name];
3816
+ }
3817
+
3818
+ function getDate(timeRaw) {
3819
+ const date = (timeRaw & 0xffff0000) >> 16, time = timeRaw & 0x0000ffff;
3820
+ try {
3821
+ return new Date(1980 + ((date & 0xFE00) >> 9), ((date & 0x01E0) >> 5) - 1, date & 0x001F, (time & 0xF800) >> 11, (time & 0x07E0) >> 5, (time & 0x001F) * 2, 0);
3822
+ } catch (_error) {
3823
+ // ignored
3824
+ }
3825
+ }
3826
+
3827
+ function getDateNTFS(timeRaw) {
3828
+ return new Date((Number((timeRaw / BigInt(10000)) - BigInt(11644473600000))));
3829
+ }
3830
+
3831
+ function getUint8(view, offset) {
3832
+ return view.getUint8(offset);
3833
+ }
3834
+
3835
+ function getUint16(view, offset) {
3836
+ return view.getUint16(offset, true);
3837
+ }
3838
+
3839
+ function getUint32(view, offset) {
3840
+ return view.getUint32(offset, true);
3841
+ }
3842
+
3843
+ function getBigUint64(view, offset) {
3844
+ return Number(view.getBigUint64(offset, true));
3845
+ }
3846
+
3847
+ function setUint32$1(view, offset, value) {
3848
+ view.setUint32(offset, value, true);
3849
+ }
3850
+
3851
+ function getDataView$1(array) {
3852
+ return new DataView(array.buffer);
3853
+ }
3854
+
3855
+ /*
3856
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
3857
+
3858
+ Redistribution and use in source and binary forms, with or without
3859
+ modification, are permitted provided that the following conditions are met:
3860
+
3861
+ 1. Redistributions of source code must retain the above copyright notice,
3862
+ this list of conditions and the following disclaimer.
3863
+
3864
+ 2. Redistributions in binary form must reproduce the above copyright
3865
+ notice, this list of conditions and the following disclaimer in
3866
+ the documentation and/or other materials provided with the distribution.
3867
+
3868
+ 3. The names of the authors may not be used to endorse or promote products
3869
+ derived from this software without specific prior written permission.
3870
+
3871
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
3872
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
3873
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
3874
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
3875
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3876
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
3877
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
3878
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
3879
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
3880
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3881
+ */
3882
+
3883
+ const ERR_DUPLICATED_NAME = "File already exists";
3884
+ const ERR_INVALID_COMMENT = "Zip file comment exceeds 64KB";
3885
+ const ERR_INVALID_ENTRY_COMMENT = "File entry comment exceeds 64KB";
3886
+ const ERR_INVALID_ENTRY_NAME = "File entry name exceeds 64KB";
3887
+ const ERR_INVALID_VERSION = "Version exceeds 65535";
3888
+ const ERR_INVALID_ENCRYPTION_STRENGTH = "The strength must equal 1, 2, or 3";
3889
+ const ERR_INVALID_EXTRAFIELD_TYPE = "Extra field type exceeds 65535";
3890
+ const ERR_INVALID_EXTRAFIELD_DATA = "Extra field data exceeds 64KB";
3891
+ const ERR_UNSUPPORTED_FORMAT = "Zip64 is not supported (make sure 'keepOrder' is set to 'true')";
3892
+
3893
+ const EXTRAFIELD_DATA_AES = new Uint8Array([0x07, 0x00, 0x02, 0x00, 0x41, 0x45, 0x03, 0x00, 0x00]);
3894
+
3895
+ let workers = 0;
3896
+ const pendingEntries = [];
3897
+
3898
+ class ZipWriter {
3899
+
3900
+ constructor(writer, options = {}) {
3901
+ writer = initWriter(writer);
3902
+ Object.assign(this, {
3903
+ writer,
3904
+ addSplitZipSignature: writer instanceof SplitDataWriter,
3905
+ options,
3906
+ config: getConfiguration(),
3907
+ files: new Map(),
3908
+ filenames: new Set(),
3909
+ offset: writer.writable.size,
3910
+ pendingEntriesSize: 0,
3911
+ pendingAddFileCalls: new Set(),
3912
+ bufferedWrites: 0
3913
+ });
3914
+ }
3915
+
3916
+ async add(name = "", reader, options = {}) {
3917
+ const zipWriter = this;
3918
+ const {
3919
+ pendingAddFileCalls,
3920
+ config
3921
+ } = zipWriter;
3922
+ if (workers < config.maxWorkers) {
3923
+ workers++;
3924
+ } else {
3925
+ await new Promise(resolve => pendingEntries.push(resolve));
3926
+ }
3927
+ let promiseAddFile;
3928
+ try {
3929
+ name = name.trim();
3930
+ if (zipWriter.filenames.has(name)) {
3931
+ throw new Error(ERR_DUPLICATED_NAME);
3932
+ }
3933
+ zipWriter.filenames.add(name);
3934
+ promiseAddFile = addFile(zipWriter, name, reader, options);
3935
+ pendingAddFileCalls.add(promiseAddFile);
3936
+ return await promiseAddFile;
3937
+ } catch (error) {
3938
+ zipWriter.filenames.delete(name);
3939
+ throw error;
3940
+ } finally {
3941
+ pendingAddFileCalls.delete(promiseAddFile);
3942
+ const pendingEntry = pendingEntries.shift();
3943
+ if (pendingEntry) {
3944
+ pendingEntry();
3945
+ } else {
3946
+ workers--;
3947
+ }
3948
+ }
3949
+ }
3950
+
3951
+ async close(comment = new Uint8Array(), options = {}) {
3952
+ const zipWriter = this;
3953
+ const { pendingAddFileCalls, writer } = this;
3954
+ const { writable } = writer;
3955
+ while (pendingAddFileCalls.size) {
3956
+ await Promise.all(Array.from(pendingAddFileCalls));
3957
+ }
3958
+ await closeFile(this, comment, options);
3959
+ const preventClose = getOptionValue(zipWriter, options, "preventClose");
3960
+ if (!preventClose) {
3961
+ await writable.getWriter().close();
3962
+ }
3963
+ return writer.getData ? writer.getData() : writable;
3964
+ }
3965
+ }
3966
+
3967
+ async function addFile(zipWriter, name, reader, options) {
3968
+ name = name.trim();
3969
+ if (options.directory && (!name.endsWith(DIRECTORY_SIGNATURE))) {
3970
+ name += DIRECTORY_SIGNATURE;
3971
+ } else {
3972
+ options.directory = name.endsWith(DIRECTORY_SIGNATURE);
3973
+ }
3974
+ const rawFilename = encodeText(name);
3975
+ if (getLength(rawFilename) > MAX_16_BITS) {
3976
+ throw new Error(ERR_INVALID_ENTRY_NAME);
3977
+ }
3978
+ const comment = options.comment || "";
3979
+ const rawComment = encodeText(comment);
3980
+ if (getLength(rawComment) > MAX_16_BITS) {
3981
+ throw new Error(ERR_INVALID_ENTRY_COMMENT);
3982
+ }
3983
+ const version = getOptionValue(zipWriter, options, "version", VERSION_DEFLATE);
3984
+ if (version > MAX_16_BITS) {
3985
+ throw new Error(ERR_INVALID_VERSION);
3986
+ }
3987
+ const versionMadeBy = getOptionValue(zipWriter, options, "versionMadeBy", 20);
3988
+ if (versionMadeBy > MAX_16_BITS) {
3989
+ throw new Error(ERR_INVALID_VERSION);
3990
+ }
3991
+ const lastModDate = getOptionValue(zipWriter, options, PROPERTY_NAME_LAST_MODIFICATION_DATE, new Date());
3992
+ const lastAccessDate = getOptionValue(zipWriter, options, PROPERTY_NAME_LAST_ACCESS_DATE);
3993
+ const creationDate = getOptionValue(zipWriter, options, PROPERTY_NAME_CREATION_DATE);
3994
+ const msDosCompatible = getOptionValue(zipWriter, options, PROPERTY_NAME_MS_DOS_COMPATIBLE, true);
3995
+ const internalFileAttribute = getOptionValue(zipWriter, options, PROPERTY_NAME_INTERNAL_FILE_ATTRIBUTE, 0);
3996
+ const externalFileAttribute = getOptionValue(zipWriter, options, PROPERTY_NAME_EXTERNAL_FILE_ATTRIBUTE, 0);
3997
+ const password = getOptionValue(zipWriter, options, "password");
3998
+ const encryptionStrength = getOptionValue(zipWriter, options, "encryptionStrength", 3);
3999
+ const zipCrypto = getOptionValue(zipWriter, options, "zipCrypto");
4000
+ const extendedTimestamp = getOptionValue(zipWriter, options, "extendedTimestamp", true);
4001
+ const keepOrder = getOptionValue(zipWriter, options, "keepOrder", true);
4002
+ const level = getOptionValue(zipWriter, options, "level");
4003
+ const useWebWorkers = getOptionValue(zipWriter, options, "useWebWorkers");
4004
+ const bufferedWrite = getOptionValue(zipWriter, options, "bufferedWrite");
4005
+ const dataDescriptorSignature = getOptionValue(zipWriter, options, "dataDescriptorSignature", false);
4006
+ const signal = getOptionValue(zipWriter, options, "signal");
4007
+ const useCompressionStream = getOptionValue(zipWriter, options, "useCompressionStream");
4008
+ let dataDescriptor = getOptionValue(zipWriter, options, "dataDescriptor", true);
4009
+ let zip64 = getOptionValue(zipWriter, options, PROPERTY_NAME_ZIP64);
4010
+ if (password !== UNDEFINED_VALUE && encryptionStrength !== UNDEFINED_VALUE && (encryptionStrength < 1 || encryptionStrength > 3)) {
4011
+ throw new Error(ERR_INVALID_ENCRYPTION_STRENGTH);
4012
+ }
4013
+ let rawExtraField = new Uint8Array();
4014
+ const { extraField } = options;
4015
+ if (extraField) {
4016
+ let extraFieldSize = 0;
4017
+ let offset = 0;
4018
+ extraField.forEach(data => extraFieldSize += 4 + getLength(data));
4019
+ rawExtraField = new Uint8Array(extraFieldSize);
4020
+ extraField.forEach((data, type) => {
4021
+ if (type > MAX_16_BITS) {
4022
+ throw new Error(ERR_INVALID_EXTRAFIELD_TYPE);
4023
+ }
4024
+ if (getLength(data) > MAX_16_BITS) {
4025
+ throw new Error(ERR_INVALID_EXTRAFIELD_DATA);
4026
+ }
4027
+ arraySet(rawExtraField, new Uint16Array([type]), offset);
4028
+ arraySet(rawExtraField, new Uint16Array([getLength(data)]), offset + 2);
4029
+ arraySet(rawExtraField, data, offset + 4);
4030
+ offset += 4 + getLength(data);
4031
+ });
4032
+ }
4033
+ let maximumCompressedSize = 0;
4034
+ let maximumEntrySize = 0;
4035
+ let uncompressedSize = 0;
4036
+ const zip64Enabled = zip64 === true;
4037
+ if (reader) {
4038
+ reader = initReader(reader);
4039
+ await initStream(reader);
4040
+ if (reader.size === UNDEFINED_VALUE) {
4041
+ dataDescriptor = true;
4042
+ if (zip64 || zip64 === UNDEFINED_VALUE) {
4043
+ zip64 = true;
4044
+ uncompressedSize = maximumCompressedSize = MAX_32_BITS;
4045
+ }
4046
+ } else {
4047
+ uncompressedSize = reader.size;
4048
+ maximumCompressedSize = getMaximumCompressedSize(uncompressedSize);
4049
+ }
4050
+ }
4051
+ const { diskOffset, diskNumber, maxSize } = zipWriter.writer;
4052
+ const zip64UncompressedSize = zip64Enabled || uncompressedSize >= MAX_32_BITS;
4053
+ const zip64CompressedSize = zip64Enabled || maximumCompressedSize >= MAX_32_BITS;
4054
+ const zip64Offset = zip64Enabled || zipWriter.offset + zipWriter.pendingEntriesSize - diskOffset >= MAX_32_BITS;
4055
+ const supportZip64SplitFile = getOptionValue(zipWriter, options, "supportZip64SplitFile", true);
4056
+ const zip64DiskNumberStart = (supportZip64SplitFile && zip64Enabled) || diskNumber + Math.ceil(zipWriter.pendingEntriesSize / maxSize) >= MAX_16_BITS;
4057
+ if (zip64Offset || zip64UncompressedSize || zip64CompressedSize || zip64DiskNumberStart) {
4058
+ if (zip64 === false || !keepOrder) {
4059
+ throw new Error(ERR_UNSUPPORTED_FORMAT);
4060
+ } else {
4061
+ zip64 = true;
4062
+ }
4063
+ }
4064
+ zip64 = zip64 || false;
4065
+ options = Object.assign({}, options, {
4066
+ rawFilename,
4067
+ rawComment,
4068
+ version,
4069
+ versionMadeBy,
4070
+ lastModDate,
4071
+ lastAccessDate,
4072
+ creationDate,
4073
+ rawExtraField,
4074
+ zip64,
4075
+ zip64UncompressedSize,
4076
+ zip64CompressedSize,
4077
+ zip64Offset,
4078
+ zip64DiskNumberStart,
4079
+ password,
4080
+ level,
4081
+ useWebWorkers,
4082
+ encryptionStrength,
4083
+ extendedTimestamp,
4084
+ zipCrypto,
4085
+ bufferedWrite,
4086
+ keepOrder,
4087
+ dataDescriptor,
4088
+ dataDescriptorSignature,
4089
+ signal,
4090
+ msDosCompatible,
4091
+ internalFileAttribute,
4092
+ externalFileAttribute,
4093
+ useCompressionStream
4094
+ });
4095
+ const headerInfo = getHeaderInfo(options);
4096
+ const dataDescriptorInfo = getDataDescriptorInfo(options);
4097
+ const metadataSize = getLength(headerInfo.localHeaderArray, dataDescriptorInfo.dataDescriptorArray);
4098
+ maximumEntrySize = metadataSize + maximumCompressedSize;
4099
+ if (zipWriter.options.usdz) {
4100
+ maximumEntrySize += maximumEntrySize + 64;
4101
+ }
4102
+ zipWriter.pendingEntriesSize += maximumEntrySize;
4103
+ let fileEntry;
4104
+ try {
4105
+ fileEntry = await getFileEntry(zipWriter, name, reader, { headerInfo, dataDescriptorInfo, metadataSize }, options);
4106
+ } finally {
4107
+ zipWriter.pendingEntriesSize -= maximumEntrySize;
4108
+ }
4109
+ Object.assign(fileEntry, { name, comment, extraField });
4110
+ return new Entry(fileEntry);
4111
+ }
4112
+
4113
+ async function getFileEntry(zipWriter, name, reader, entryInfo, options) {
4114
+ const {
4115
+ files,
4116
+ writer
4117
+ } = zipWriter;
4118
+ const {
4119
+ keepOrder,
4120
+ dataDescriptor,
4121
+ signal
4122
+ } = options;
4123
+ const {
4124
+ headerInfo
4125
+ } = entryInfo;
4126
+ const { usdz } = zipWriter.options;
4127
+ const previousFileEntry = Array.from(files.values()).pop();
4128
+ let fileEntry = {};
4129
+ let bufferedWrite;
4130
+ let releaseLockWriter;
4131
+ let releaseLockCurrentFileEntry;
4132
+ let writingBufferedEntryData;
4133
+ let writingEntryData;
4134
+ let fileWriter;
4135
+ files.set(name, fileEntry);
4136
+ try {
4137
+ let lockPreviousFileEntry;
4138
+ if (keepOrder) {
4139
+ lockPreviousFileEntry = previousFileEntry && previousFileEntry.lock;
4140
+ requestLockCurrentFileEntry();
4141
+ }
4142
+ if ((options.bufferedWrite || zipWriter.writerLocked || (zipWriter.bufferedWrites && keepOrder) || !dataDescriptor) && !usdz) {
4143
+ fileWriter = new BlobWriter();
4144
+ fileWriter.writable.size = 0;
4145
+ bufferedWrite = true;
4146
+ zipWriter.bufferedWrites++;
4147
+ await initStream(writer);
4148
+ } else {
4149
+ fileWriter = writer;
4150
+ await requestLockWriter();
4151
+ }
4152
+ await initStream(fileWriter);
4153
+ const { writable } = writer;
4154
+ let { diskOffset } = writer;
4155
+ if (zipWriter.addSplitZipSignature) {
4156
+ delete zipWriter.addSplitZipSignature;
4157
+ const signatureArray = new Uint8Array(4);
4158
+ const signatureArrayView = getDataView(signatureArray);
4159
+ setUint32(signatureArrayView, 0, SPLIT_ZIP_FILE_SIGNATURE);
4160
+ await writeData(writable, signatureArray);
4161
+ zipWriter.offset += 4;
4162
+ }
4163
+ if (!bufferedWrite) {
4164
+ await lockPreviousFileEntry;
4165
+ await skipDiskIfNeeded(writable);
4166
+ }
4167
+ const { diskNumber } = writer;
4168
+ writingEntryData = true;
4169
+ fileEntry.diskNumberStart = diskNumber;
4170
+ if (usdz) {
4171
+ appendExtraFieldUSDZ(entryInfo, zipWriter.offset - diskOffset);
4172
+ }
4173
+ fileEntry = await createFileEntry(reader, fileWriter, fileEntry, entryInfo, zipWriter.config, options);
4174
+ writingEntryData = false;
4175
+ files.set(name, fileEntry);
4176
+ fileEntry.filename = name;
4177
+ if (bufferedWrite) {
4178
+ await fileWriter.writable.getWriter().close();
4179
+ let blob = await fileWriter.getData();
4180
+ await lockPreviousFileEntry;
4181
+ await requestLockWriter();
4182
+ writingBufferedEntryData = true;
4183
+ if (!dataDescriptor) {
4184
+ blob = await writeExtraHeaderInfo(fileEntry, blob, writable, options);
4185
+ }
4186
+ await skipDiskIfNeeded(writable);
4187
+ fileEntry.diskNumberStart = writer.diskNumber;
4188
+ diskOffset = writer.diskOffset;
4189
+ await blob.stream().pipeTo(writable, { preventClose: true, preventAbort: true, signal });
4190
+ writable.size += blob.size;
4191
+ writingBufferedEntryData = false;
4192
+ }
4193
+ fileEntry.offset = zipWriter.offset - diskOffset;
4194
+ if (fileEntry.zip64) {
4195
+ setZip64ExtraInfo(fileEntry, options);
4196
+ } else if (fileEntry.offset >= MAX_32_BITS) {
4197
+ throw new Error(ERR_UNSUPPORTED_FORMAT);
4198
+ }
4199
+ zipWriter.offset += fileEntry.length;
4200
+ return fileEntry;
4201
+ } catch (error) {
4202
+ if ((bufferedWrite && writingBufferedEntryData) || (!bufferedWrite && writingEntryData)) {
4203
+ zipWriter.hasCorruptedEntries = true;
4204
+ if (error) {
4205
+ try {
4206
+ error.corruptedEntry = true;
4207
+ } catch (_error) {
4208
+ // ignored
4209
+ }
4210
+ }
4211
+ if (bufferedWrite) {
4212
+ zipWriter.offset += fileWriter.writable.size;
4213
+ } else {
4214
+ zipWriter.offset = fileWriter.writable.size;
4215
+ }
4216
+ }
4217
+ files.delete(name);
4218
+ throw error;
4219
+ } finally {
4220
+ if (bufferedWrite) {
4221
+ zipWriter.bufferedWrites--;
4222
+ }
4223
+ if (releaseLockCurrentFileEntry) {
4224
+ releaseLockCurrentFileEntry();
4225
+ }
4226
+ if (releaseLockWriter) {
4227
+ releaseLockWriter();
4228
+ }
4229
+ }
4230
+
4231
+ function requestLockCurrentFileEntry() {
4232
+ fileEntry.lock = new Promise(resolve => releaseLockCurrentFileEntry = resolve);
4233
+ }
4234
+
4235
+ async function requestLockWriter() {
4236
+ zipWriter.writerLocked = true;
4237
+ const { lockWriter } = zipWriter;
4238
+ zipWriter.lockWriter = new Promise(resolve => releaseLockWriter = () => {
4239
+ zipWriter.writerLocked = false;
4240
+ resolve();
4241
+ });
4242
+ await lockWriter;
4243
+ }
4244
+
4245
+ async function skipDiskIfNeeded(writable) {
4246
+ if (headerInfo.localHeaderArray.length > writer.availableSize) {
4247
+ writer.availableSize = 0;
4248
+ await writeData(writable, new Uint8Array());
4249
+ }
4250
+ }
4251
+ }
4252
+
4253
+ async function createFileEntry(reader, writer, { diskNumberStart, lock }, entryInfo, config, options) {
4254
+ const {
4255
+ headerInfo,
4256
+ dataDescriptorInfo,
4257
+ metadataSize
4258
+ } = entryInfo;
4259
+ const {
4260
+ localHeaderArray,
4261
+ headerArray,
4262
+ lastModDate,
4263
+ rawLastModDate,
4264
+ encrypted,
4265
+ compressed,
4266
+ version,
4267
+ compressionMethod,
4268
+ rawExtraFieldExtendedTimestamp,
4269
+ extraFieldExtendedTimestampFlag,
4270
+ rawExtraFieldNTFS,
4271
+ rawExtraFieldAES
4272
+ } = headerInfo;
4273
+ const { dataDescriptorArray } = dataDescriptorInfo;
4274
+ const {
4275
+ rawFilename,
4276
+ lastAccessDate,
4277
+ creationDate,
4278
+ password,
4279
+ level,
4280
+ zip64,
4281
+ zip64UncompressedSize,
4282
+ zip64CompressedSize,
4283
+ zip64Offset,
4284
+ zip64DiskNumberStart,
4285
+ zipCrypto,
4286
+ dataDescriptor,
4287
+ directory,
4288
+ versionMadeBy,
4289
+ rawComment,
4290
+ rawExtraField,
4291
+ useWebWorkers,
4292
+ onstart,
4293
+ onprogress,
4294
+ onend,
4295
+ signal,
4296
+ encryptionStrength,
4297
+ extendedTimestamp,
4298
+ msDosCompatible,
4299
+ internalFileAttribute,
4300
+ externalFileAttribute,
4301
+ useCompressionStream
4302
+ } = options;
4303
+ const fileEntry = {
4304
+ lock,
4305
+ versionMadeBy,
4306
+ zip64,
4307
+ directory: Boolean(directory),
4308
+ filenameUTF8: true,
4309
+ rawFilename,
4310
+ commentUTF8: true,
4311
+ rawComment,
4312
+ rawExtraFieldExtendedTimestamp,
4313
+ rawExtraFieldNTFS,
4314
+ rawExtraFieldAES,
4315
+ rawExtraField,
4316
+ extendedTimestamp,
4317
+ msDosCompatible,
4318
+ internalFileAttribute,
4319
+ externalFileAttribute,
4320
+ diskNumberStart
4321
+ };
4322
+ let compressedSize = 0;
4323
+ let uncompressedSize = 0;
4324
+ let signature;
4325
+ const { writable } = writer;
4326
+ if (reader) {
4327
+ reader.chunkSize = getChunkSize(config);
4328
+ await writeData(writable, localHeaderArray);
4329
+ const readable = reader.readable;
4330
+ const size = readable.size = reader.size;
4331
+ const workerOptions = {
4332
+ options: {
4333
+ codecType: CODEC_DEFLATE,
4334
+ level,
4335
+ password,
4336
+ encryptionStrength,
4337
+ zipCrypto: encrypted && zipCrypto,
4338
+ passwordVerification: encrypted && zipCrypto && (rawLastModDate >> 8) & 0xFF,
4339
+ signed: true,
4340
+ compressed,
4341
+ encrypted,
4342
+ useWebWorkers,
4343
+ useCompressionStream,
4344
+ transferStreams: false
4345
+ },
4346
+ config,
4347
+ streamOptions: { signal, size, onstart, onprogress, onend }
4348
+ };
4349
+ const result = await runWorker({ readable, writable }, workerOptions);
4350
+ writable.size += result.size;
4351
+ signature = result.signature;
4352
+ uncompressedSize = reader.size = readable.size;
4353
+ compressedSize = result.size;
4354
+ } else {
4355
+ await writeData(writable, localHeaderArray);
4356
+ }
4357
+ let rawExtraFieldZip64;
4358
+ if (zip64) {
4359
+ let rawExtraFieldZip64Length = 4;
4360
+ if (zip64UncompressedSize) {
4361
+ rawExtraFieldZip64Length += 8;
4362
+ }
4363
+ if (zip64CompressedSize) {
4364
+ rawExtraFieldZip64Length += 8;
4365
+ }
4366
+ if (zip64Offset) {
4367
+ rawExtraFieldZip64Length += 8;
4368
+ }
4369
+ if (zip64DiskNumberStart) {
4370
+ rawExtraFieldZip64Length += 4;
4371
+ }
4372
+ rawExtraFieldZip64 = new Uint8Array(rawExtraFieldZip64Length);
4373
+ } else {
4374
+ rawExtraFieldZip64 = new Uint8Array();
4375
+ }
4376
+ setEntryInfo({
4377
+ signature,
4378
+ rawExtraFieldZip64,
4379
+ compressedSize,
4380
+ uncompressedSize,
4381
+ headerInfo,
4382
+ dataDescriptorInfo
4383
+ }, options);
4384
+ if (dataDescriptor) {
4385
+ await writeData(writable, dataDescriptorArray);
4386
+ }
4387
+ Object.assign(fileEntry, {
4388
+ uncompressedSize,
4389
+ compressedSize,
4390
+ lastModDate,
4391
+ rawLastModDate,
4392
+ creationDate,
4393
+ lastAccessDate,
4394
+ encrypted,
4395
+ length: metadataSize + compressedSize,
4396
+ compressionMethod,
4397
+ version,
4398
+ headerArray,
4399
+ signature,
4400
+ rawExtraFieldZip64,
4401
+ extraFieldExtendedTimestampFlag,
4402
+ zip64UncompressedSize,
4403
+ zip64CompressedSize,
4404
+ zip64Offset,
4405
+ zip64DiskNumberStart
4406
+ });
4407
+ return fileEntry;
4408
+ }
4409
+
4410
+ function getHeaderInfo(options) {
4411
+ const {
4412
+ rawFilename,
4413
+ lastModDate,
4414
+ lastAccessDate,
4415
+ creationDate,
4416
+ password,
4417
+ level,
4418
+ zip64,
4419
+ zipCrypto,
4420
+ dataDescriptor,
4421
+ directory,
4422
+ rawExtraField,
4423
+ encryptionStrength,
4424
+ extendedTimestamp
4425
+ } = options;
4426
+ const compressed = level !== 0 && !directory;
4427
+ const encrypted = Boolean(password && getLength(password));
4428
+ let version = options.version;
4429
+ let rawExtraFieldAES;
4430
+ if (encrypted && !zipCrypto) {
4431
+ rawExtraFieldAES = new Uint8Array(getLength(EXTRAFIELD_DATA_AES) + 2);
4432
+ const extraFieldAESView = getDataView(rawExtraFieldAES);
4433
+ setUint16(extraFieldAESView, 0, EXTRAFIELD_TYPE_AES);
4434
+ arraySet(rawExtraFieldAES, EXTRAFIELD_DATA_AES, 2);
4435
+ setUint8(extraFieldAESView, 8, encryptionStrength);
4436
+ } else {
4437
+ rawExtraFieldAES = new Uint8Array();
4438
+ }
4439
+ let rawExtraFieldNTFS;
4440
+ let rawExtraFieldExtendedTimestamp;
4441
+ let extraFieldExtendedTimestampFlag;
4442
+ if (extendedTimestamp) {
4443
+ rawExtraFieldExtendedTimestamp = new Uint8Array(9 + (lastAccessDate ? 4 : 0) + (creationDate ? 4 : 0));
4444
+ const extraFieldExtendedTimestampView = getDataView(rawExtraFieldExtendedTimestamp);
4445
+ setUint16(extraFieldExtendedTimestampView, 0, EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
4446
+ setUint16(extraFieldExtendedTimestampView, 2, getLength(rawExtraFieldExtendedTimestamp) - 4);
4447
+ extraFieldExtendedTimestampFlag = 0x1 + (lastAccessDate ? 0x2 : 0) + (creationDate ? 0x4 : 0);
4448
+ setUint8(extraFieldExtendedTimestampView, 4, extraFieldExtendedTimestampFlag);
4449
+ let offset = 5;
4450
+ setUint32(extraFieldExtendedTimestampView, offset, Math.floor(lastModDate.getTime() / 1000));
4451
+ offset += 4;
4452
+ if (lastAccessDate) {
4453
+ setUint32(extraFieldExtendedTimestampView, offset, Math.floor(lastAccessDate.getTime() / 1000));
4454
+ offset += 4;
4455
+ }
4456
+ if (creationDate) {
4457
+ setUint32(extraFieldExtendedTimestampView, offset, Math.floor(creationDate.getTime() / 1000));
4458
+ }
4459
+ try {
4460
+ rawExtraFieldNTFS = new Uint8Array(36);
4461
+ const extraFieldNTFSView = getDataView(rawExtraFieldNTFS);
4462
+ const lastModTimeNTFS = getTimeNTFS(lastModDate);
4463
+ setUint16(extraFieldNTFSView, 0, EXTRAFIELD_TYPE_NTFS);
4464
+ setUint16(extraFieldNTFSView, 2, 32);
4465
+ setUint16(extraFieldNTFSView, 8, EXTRAFIELD_TYPE_NTFS_TAG1);
4466
+ setUint16(extraFieldNTFSView, 10, 24);
4467
+ setBigUint64(extraFieldNTFSView, 12, lastModTimeNTFS);
4468
+ setBigUint64(extraFieldNTFSView, 20, getTimeNTFS(lastAccessDate) || lastModTimeNTFS);
4469
+ setBigUint64(extraFieldNTFSView, 28, getTimeNTFS(creationDate) || lastModTimeNTFS);
4470
+ } catch (_error) {
4471
+ rawExtraFieldNTFS = new Uint8Array();
4472
+ }
4473
+ } else {
4474
+ rawExtraFieldNTFS = rawExtraFieldExtendedTimestamp = new Uint8Array();
4475
+ }
4476
+ let bitFlag = BITFLAG_LANG_ENCODING_FLAG;
4477
+ if (dataDescriptor) {
4478
+ bitFlag = bitFlag | BITFLAG_DATA_DESCRIPTOR;
4479
+ }
4480
+ let compressionMethod = COMPRESSION_METHOD_STORE;
4481
+ if (compressed) {
4482
+ compressionMethod = COMPRESSION_METHOD_DEFLATE;
4483
+ }
4484
+ if (zip64) {
4485
+ version = version > VERSION_ZIP64 ? version : VERSION_ZIP64;
4486
+ }
4487
+ if (encrypted) {
4488
+ bitFlag = bitFlag | BITFLAG_ENCRYPTED;
4489
+ if (!zipCrypto) {
4490
+ version = version > VERSION_AES ? version : VERSION_AES;
4491
+ compressionMethod = COMPRESSION_METHOD_AES;
4492
+ if (compressed) {
4493
+ rawExtraFieldAES[9] = COMPRESSION_METHOD_DEFLATE;
4494
+ }
4495
+ }
4496
+ }
4497
+ const headerArray = new Uint8Array(26);
4498
+ const headerView = getDataView(headerArray);
4499
+ setUint16(headerView, 0, version);
4500
+ setUint16(headerView, 2, bitFlag);
4501
+ setUint16(headerView, 4, compressionMethod);
4502
+ const dateArray = new Uint32Array(1);
4503
+ const dateView = getDataView(dateArray);
4504
+ let lastModDateMsDos;
4505
+ if (lastModDate < MIN_DATE) {
4506
+ lastModDateMsDos = MIN_DATE;
4507
+ } else if (lastModDate > MAX_DATE) {
4508
+ lastModDateMsDos = MAX_DATE;
4509
+ } else {
4510
+ lastModDateMsDos = lastModDate;
4511
+ }
4512
+ setUint16(dateView, 0, (((lastModDateMsDos.getHours() << 6) | lastModDateMsDos.getMinutes()) << 5) | lastModDateMsDos.getSeconds() / 2);
4513
+ setUint16(dateView, 2, ((((lastModDateMsDos.getFullYear() - 1980) << 4) | (lastModDateMsDos.getMonth() + 1)) << 5) | lastModDateMsDos.getDate());
4514
+ const rawLastModDate = dateArray[0];
4515
+ setUint32(headerView, 6, rawLastModDate);
4516
+ setUint16(headerView, 22, getLength(rawFilename));
4517
+ const extraFieldLength = getLength(rawExtraFieldAES, rawExtraFieldExtendedTimestamp, rawExtraFieldNTFS, rawExtraField);
4518
+ setUint16(headerView, 24, extraFieldLength);
4519
+ const localHeaderArray = new Uint8Array(30 + getLength(rawFilename) + extraFieldLength);
4520
+ const localHeaderView = getDataView(localHeaderArray);
4521
+ setUint32(localHeaderView, 0, LOCAL_FILE_HEADER_SIGNATURE);
4522
+ arraySet(localHeaderArray, headerArray, 4);
4523
+ arraySet(localHeaderArray, rawFilename, 30);
4524
+ arraySet(localHeaderArray, rawExtraFieldAES, 30 + getLength(rawFilename));
4525
+ arraySet(localHeaderArray, rawExtraFieldExtendedTimestamp, 30 + getLength(rawFilename, rawExtraFieldAES));
4526
+ arraySet(localHeaderArray, rawExtraFieldNTFS, 30 + getLength(rawFilename, rawExtraFieldAES, rawExtraFieldExtendedTimestamp));
4527
+ arraySet(localHeaderArray, rawExtraField, 30 + getLength(rawFilename, rawExtraFieldAES, rawExtraFieldExtendedTimestamp, rawExtraFieldNTFS));
4528
+ return {
4529
+ localHeaderArray,
4530
+ headerArray,
4531
+ headerView,
4532
+ lastModDate,
4533
+ rawLastModDate,
4534
+ encrypted,
4535
+ compressed,
4536
+ version,
4537
+ compressionMethod,
4538
+ extraFieldExtendedTimestampFlag,
4539
+ rawExtraFieldExtendedTimestamp,
4540
+ rawExtraFieldNTFS,
4541
+ rawExtraFieldAES,
4542
+ extraFieldLength
4543
+ };
4544
+ }
4545
+
4546
+ function appendExtraFieldUSDZ(entryInfo, zipWriterOffset) {
4547
+ const { headerInfo } = entryInfo;
4548
+ let { localHeaderArray, extraFieldLength } = headerInfo;
4549
+ let localHeaderArrayView = getDataView(localHeaderArray);
4550
+ let extraBytesLength = 64 - ((zipWriterOffset + localHeaderArray.length) % 64);
4551
+ if (extraBytesLength < 4) {
4552
+ extraBytesLength += 64;
4553
+ }
4554
+ const rawExtraFieldUSDZ = new Uint8Array(extraBytesLength);
4555
+ const extraFieldUSDZView = getDataView(rawExtraFieldUSDZ);
4556
+ setUint16(extraFieldUSDZView, 0, EXTRAFIELD_TYPE_USDZ);
4557
+ setUint16(extraFieldUSDZView, 2, extraBytesLength - 2);
4558
+ const previousLocalHeaderArray = localHeaderArray;
4559
+ headerInfo.localHeaderArray = localHeaderArray = new Uint8Array(previousLocalHeaderArray.length + extraBytesLength);
4560
+ arraySet(localHeaderArray, previousLocalHeaderArray);
4561
+ arraySet(localHeaderArray, rawExtraFieldUSDZ, previousLocalHeaderArray.length);
4562
+ localHeaderArrayView = getDataView(localHeaderArray);
4563
+ setUint16(localHeaderArrayView, 28, extraFieldLength + extraBytesLength);
4564
+ entryInfo.metadataSize += extraBytesLength;
4565
+ }
4566
+
4567
+ function getDataDescriptorInfo(options) {
4568
+ const {
4569
+ zip64,
4570
+ dataDescriptor,
4571
+ dataDescriptorSignature
4572
+ } = options;
4573
+ let dataDescriptorArray = new Uint8Array();
4574
+ let dataDescriptorView, dataDescriptorOffset = 0;
4575
+ if (dataDescriptor) {
4576
+ dataDescriptorArray = new Uint8Array(zip64 ? (dataDescriptorSignature ? 24 : 20) : (dataDescriptorSignature ? 16 : 12));
4577
+ dataDescriptorView = getDataView(dataDescriptorArray);
4578
+ if (dataDescriptorSignature) {
4579
+ dataDescriptorOffset = 4;
4580
+ setUint32(dataDescriptorView, 0, DATA_DESCRIPTOR_RECORD_SIGNATURE);
4581
+ }
4582
+ }
4583
+ return {
4584
+ dataDescriptorArray,
4585
+ dataDescriptorView,
4586
+ dataDescriptorOffset
4587
+ };
4588
+ }
4589
+
4590
+ function setEntryInfo(entryInfo, options) {
4591
+ const {
4592
+ signature,
4593
+ rawExtraFieldZip64,
4594
+ compressedSize,
4595
+ uncompressedSize,
4596
+ headerInfo,
4597
+ dataDescriptorInfo
4598
+ } = entryInfo;
4599
+ const {
4600
+ headerView,
4601
+ encrypted
4602
+ } = headerInfo;
4603
+ const {
4604
+ dataDescriptorView,
4605
+ dataDescriptorOffset
4606
+ } = dataDescriptorInfo;
4607
+ const {
4608
+ zip64,
4609
+ zip64UncompressedSize,
4610
+ zip64CompressedSize,
4611
+ zipCrypto,
4612
+ dataDescriptor
4613
+ } = options;
4614
+ if ((!encrypted || zipCrypto) && signature !== UNDEFINED_VALUE) {
4615
+ setUint32(headerView, 10, signature);
4616
+ if (dataDescriptor) {
4617
+ setUint32(dataDescriptorView, dataDescriptorOffset, signature);
4618
+ }
4619
+ }
4620
+ if (zip64) {
4621
+ const rawExtraFieldZip64View = getDataView(rawExtraFieldZip64);
4622
+ setUint16(rawExtraFieldZip64View, 0, EXTRAFIELD_TYPE_ZIP64);
4623
+ setUint16(rawExtraFieldZip64View, 2, rawExtraFieldZip64.length - 4);
4624
+ let rawExtraFieldZip64Offset = 4;
4625
+ if (zip64UncompressedSize) {
4626
+ setUint32(headerView, 18, MAX_32_BITS);
4627
+ setBigUint64(rawExtraFieldZip64View, rawExtraFieldZip64Offset, BigInt(uncompressedSize));
4628
+ rawExtraFieldZip64Offset += 8;
4629
+ }
4630
+ if (zip64CompressedSize) {
4631
+ setUint32(headerView, 14, MAX_32_BITS);
4632
+ setBigUint64(rawExtraFieldZip64View, rawExtraFieldZip64Offset, BigInt(compressedSize));
4633
+ }
4634
+ if (dataDescriptor) {
4635
+ setBigUint64(dataDescriptorView, dataDescriptorOffset + 4, BigInt(compressedSize));
4636
+ setBigUint64(dataDescriptorView, dataDescriptorOffset + 12, BigInt(uncompressedSize));
4637
+ }
4638
+ } else {
4639
+ setUint32(headerView, 14, compressedSize);
4640
+ setUint32(headerView, 18, uncompressedSize);
4641
+ if (dataDescriptor) {
4642
+ setUint32(dataDescriptorView, dataDescriptorOffset + 4, compressedSize);
4643
+ setUint32(dataDescriptorView, dataDescriptorOffset + 8, uncompressedSize);
4644
+ }
4645
+ }
4646
+ }
4647
+
4648
+ async function writeExtraHeaderInfo(fileEntry, entryData, writable, { zipCrypto }) {
4649
+ let arrayBuffer;
4650
+ arrayBuffer = await entryData.slice(0, 26).arrayBuffer();
4651
+ if (arrayBuffer.byteLength != 26) {
4652
+ arrayBuffer = arrayBuffer.slice(0, 26);
4653
+ }
4654
+ const arrayBufferView = new DataView(arrayBuffer);
4655
+ if (!fileEntry.encrypted || zipCrypto) {
4656
+ setUint32(arrayBufferView, 14, fileEntry.signature);
4657
+ }
4658
+ if (fileEntry.zip64) {
4659
+ setUint32(arrayBufferView, 18, MAX_32_BITS);
4660
+ setUint32(arrayBufferView, 22, MAX_32_BITS);
4661
+ } else {
4662
+ setUint32(arrayBufferView, 18, fileEntry.compressedSize);
4663
+ setUint32(arrayBufferView, 22, fileEntry.uncompressedSize);
4664
+ }
4665
+ await writeData(writable, new Uint8Array(arrayBuffer));
4666
+ return entryData.slice(arrayBuffer.byteLength);
4667
+ }
4668
+
4669
+ function setZip64ExtraInfo(fileEntry, options) {
4670
+ const { rawExtraFieldZip64, offset, diskNumberStart } = fileEntry;
4671
+ const { zip64UncompressedSize, zip64CompressedSize, zip64Offset, zip64DiskNumberStart } = options;
4672
+ const rawExtraFieldZip64View = getDataView(rawExtraFieldZip64);
4673
+ let rawExtraFieldZip64Offset = 4;
4674
+ if (zip64UncompressedSize) {
4675
+ rawExtraFieldZip64Offset += 8;
4676
+ }
4677
+ if (zip64CompressedSize) {
4678
+ rawExtraFieldZip64Offset += 8;
4679
+ }
4680
+ if (zip64Offset) {
4681
+ setBigUint64(rawExtraFieldZip64View, rawExtraFieldZip64Offset, BigInt(offset));
4682
+ rawExtraFieldZip64Offset += 8;
4683
+ }
4684
+ if (zip64DiskNumberStart) {
4685
+ setUint32(rawExtraFieldZip64View, rawExtraFieldZip64Offset, diskNumberStart);
4686
+ }
4687
+ }
4688
+
4689
+ async function closeFile(zipWriter, comment, options) {
4690
+ const { files, writer } = zipWriter;
4691
+ const { diskOffset, writable } = writer;
4692
+ let { diskNumber } = writer;
4693
+ let offset = 0;
4694
+ let directoryDataLength = 0;
4695
+ let directoryOffset = zipWriter.offset - diskOffset;
4696
+ let filesLength = files.size;
4697
+ for (const [, fileEntry] of files) {
4698
+ const {
4699
+ rawFilename,
4700
+ rawExtraFieldZip64,
4701
+ rawExtraFieldAES,
4702
+ rawComment,
4703
+ rawExtraFieldNTFS,
4704
+ rawExtraField,
4705
+ extendedTimestamp,
4706
+ extraFieldExtendedTimestampFlag,
4707
+ lastModDate
4708
+ } = fileEntry;
4709
+ let rawExtraFieldTimestamp;
4710
+ if (extendedTimestamp) {
4711
+ rawExtraFieldTimestamp = new Uint8Array(9);
4712
+ const extraFieldExtendedTimestampView = getDataView(rawExtraFieldTimestamp);
4713
+ setUint16(extraFieldExtendedTimestampView, 0, EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
4714
+ setUint16(extraFieldExtendedTimestampView, 2, 5);
4715
+ setUint8(extraFieldExtendedTimestampView, 4, extraFieldExtendedTimestampFlag);
4716
+ setUint32(extraFieldExtendedTimestampView, 5, Math.floor(lastModDate.getTime() / 1000));
4717
+ } else {
4718
+ rawExtraFieldTimestamp = new Uint8Array();
4719
+ }
4720
+ fileEntry.rawExtraFieldCDExtendedTimestamp = rawExtraFieldTimestamp;
4721
+ directoryDataLength += 46 +
4722
+ getLength(
4723
+ rawFilename,
4724
+ rawComment,
4725
+ rawExtraFieldZip64,
4726
+ rawExtraFieldAES,
4727
+ rawExtraFieldNTFS,
4728
+ rawExtraFieldTimestamp,
4729
+ rawExtraField);
4730
+ }
4731
+ const directoryArray = new Uint8Array(directoryDataLength);
4732
+ const directoryView = getDataView(directoryArray);
4733
+ await initStream(writer);
4734
+ let directoryDiskOffset = 0;
4735
+ for (const [indexFileEntry, fileEntry] of Array.from(files.values()).entries()) {
4736
+ const {
4737
+ offset: fileEntryOffset,
4738
+ rawFilename,
4739
+ rawExtraFieldZip64,
4740
+ rawExtraFieldAES,
4741
+ rawExtraFieldCDExtendedTimestamp,
4742
+ rawExtraFieldNTFS,
4743
+ rawExtraField,
4744
+ rawComment,
4745
+ versionMadeBy,
4746
+ headerArray,
4747
+ directory,
4748
+ zip64,
4749
+ zip64UncompressedSize,
4750
+ zip64CompressedSize,
4751
+ zip64DiskNumberStart,
4752
+ zip64Offset,
4753
+ msDosCompatible,
4754
+ internalFileAttribute,
4755
+ externalFileAttribute,
4756
+ diskNumberStart,
4757
+ uncompressedSize,
4758
+ compressedSize
4759
+ } = fileEntry;
4760
+ const extraFieldLength = getLength(rawExtraFieldZip64, rawExtraFieldAES, rawExtraFieldCDExtendedTimestamp, rawExtraFieldNTFS, rawExtraField);
4761
+ setUint32(directoryView, offset, CENTRAL_FILE_HEADER_SIGNATURE);
4762
+ setUint16(directoryView, offset + 4, versionMadeBy);
4763
+ const headerView = getDataView(headerArray);
4764
+ if (!zip64UncompressedSize) {
4765
+ setUint32(headerView, 18, uncompressedSize);
4766
+ }
4767
+ if (!zip64CompressedSize) {
4768
+ setUint32(headerView, 14, compressedSize);
4769
+ }
4770
+ arraySet(directoryArray, headerArray, offset + 6);
4771
+ setUint16(directoryView, offset + 30, extraFieldLength);
4772
+ setUint16(directoryView, offset + 32, getLength(rawComment));
4773
+ setUint16(directoryView, offset + 34, zip64 && zip64DiskNumberStart ? MAX_16_BITS : diskNumberStart);
4774
+ setUint16(directoryView, offset + 36, internalFileAttribute);
4775
+ if (externalFileAttribute) {
4776
+ setUint32(directoryView, offset + 38, externalFileAttribute);
4777
+ } else if (directory && msDosCompatible) {
4778
+ setUint8(directoryView, offset + 38, FILE_ATTR_MSDOS_DIR_MASK);
4779
+ }
4780
+ setUint32(directoryView, offset + 42, zip64 && zip64Offset ? MAX_32_BITS : fileEntryOffset);
4781
+ arraySet(directoryArray, rawFilename, offset + 46);
4782
+ arraySet(directoryArray, rawExtraFieldZip64, offset + 46 + getLength(rawFilename));
4783
+ arraySet(directoryArray, rawExtraFieldAES, offset + 46 + getLength(rawFilename, rawExtraFieldZip64));
4784
+ arraySet(directoryArray, rawExtraFieldCDExtendedTimestamp, offset + 46 + getLength(rawFilename, rawExtraFieldZip64, rawExtraFieldAES));
4785
+ arraySet(directoryArray, rawExtraFieldNTFS, offset + 46 + getLength(rawFilename, rawExtraFieldZip64, rawExtraFieldAES, rawExtraFieldCDExtendedTimestamp));
4786
+ arraySet(directoryArray, rawExtraField, offset + 46 + getLength(rawFilename, rawExtraFieldZip64, rawExtraFieldAES, rawExtraFieldCDExtendedTimestamp, rawExtraFieldNTFS));
4787
+ arraySet(directoryArray, rawComment, offset + 46 + getLength(rawFilename) + extraFieldLength);
4788
+ const directoryEntryLength = 46 + getLength(rawFilename, rawComment) + extraFieldLength;
4789
+ if (offset - directoryDiskOffset > writer.availableSize) {
4790
+ writer.availableSize = 0;
4791
+ await writeData(writable, directoryArray.slice(directoryDiskOffset, offset));
4792
+ directoryDiskOffset = offset;
4793
+ }
4794
+ offset += directoryEntryLength;
4795
+ if (options.onprogress) {
4796
+ try {
4797
+ await options.onprogress(indexFileEntry + 1, files.size, new Entry(fileEntry));
4798
+ } catch (_error) {
4799
+ // ignored
4800
+ }
4801
+ }
4802
+ }
4803
+ await writeData(writable, directoryDiskOffset ? directoryArray.slice(directoryDiskOffset) : directoryArray);
4804
+ let lastDiskNumber = writer.diskNumber;
4805
+ const { availableSize } = writer;
4806
+ if (availableSize < END_OF_CENTRAL_DIR_LENGTH) {
4807
+ lastDiskNumber++;
4808
+ }
4809
+ let zip64 = getOptionValue(zipWriter, options, "zip64");
4810
+ if (directoryOffset >= MAX_32_BITS || directoryDataLength >= MAX_32_BITS || filesLength >= MAX_16_BITS || lastDiskNumber >= MAX_16_BITS) {
4811
+ if (zip64 === false) {
4812
+ throw new Error(ERR_UNSUPPORTED_FORMAT);
4813
+ } else {
4814
+ zip64 = true;
4815
+ }
4816
+ }
4817
+ const endOfdirectoryArray = new Uint8Array(zip64 ? ZIP64_END_OF_CENTRAL_DIR_TOTAL_LENGTH : END_OF_CENTRAL_DIR_LENGTH);
4818
+ const endOfdirectoryView = getDataView(endOfdirectoryArray);
4819
+ offset = 0;
4820
+ if (zip64) {
4821
+ setUint32(endOfdirectoryView, 0, ZIP64_END_OF_CENTRAL_DIR_SIGNATURE);
4822
+ setBigUint64(endOfdirectoryView, 4, BigInt(44));
4823
+ setUint16(endOfdirectoryView, 12, 45);
4824
+ setUint16(endOfdirectoryView, 14, 45);
4825
+ setUint32(endOfdirectoryView, 16, lastDiskNumber);
4826
+ setUint32(endOfdirectoryView, 20, diskNumber);
4827
+ setBigUint64(endOfdirectoryView, 24, BigInt(filesLength));
4828
+ setBigUint64(endOfdirectoryView, 32, BigInt(filesLength));
4829
+ setBigUint64(endOfdirectoryView, 40, BigInt(directoryDataLength));
4830
+ setBigUint64(endOfdirectoryView, 48, BigInt(directoryOffset));
4831
+ setUint32(endOfdirectoryView, 56, ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE);
4832
+ setBigUint64(endOfdirectoryView, 64, BigInt(directoryOffset) + BigInt(directoryDataLength));
4833
+ setUint32(endOfdirectoryView, 72, lastDiskNumber + 1);
4834
+ const supportZip64SplitFile = getOptionValue(zipWriter, options, "supportZip64SplitFile", true);
4835
+ if (supportZip64SplitFile) {
4836
+ lastDiskNumber = MAX_16_BITS;
4837
+ diskNumber = MAX_16_BITS;
4838
+ }
4839
+ filesLength = MAX_16_BITS;
4840
+ directoryOffset = MAX_32_BITS;
4841
+ directoryDataLength = MAX_32_BITS;
4842
+ offset += ZIP64_END_OF_CENTRAL_DIR_LENGTH + ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH;
4843
+ }
4844
+ setUint32(endOfdirectoryView, offset, END_OF_CENTRAL_DIR_SIGNATURE);
4845
+ setUint16(endOfdirectoryView, offset + 4, lastDiskNumber);
4846
+ setUint16(endOfdirectoryView, offset + 6, diskNumber);
4847
+ setUint16(endOfdirectoryView, offset + 8, filesLength);
4848
+ setUint16(endOfdirectoryView, offset + 10, filesLength);
4849
+ setUint32(endOfdirectoryView, offset + 12, directoryDataLength);
4850
+ setUint32(endOfdirectoryView, offset + 16, directoryOffset);
4851
+ const commentLength = getLength(comment);
4852
+ if (commentLength) {
4853
+ if (commentLength <= MAX_16_BITS) {
4854
+ setUint16(endOfdirectoryView, offset + 20, commentLength);
4855
+ } else {
4856
+ throw new Error(ERR_INVALID_COMMENT);
4857
+ }
4858
+ }
4859
+ await writeData(writable, endOfdirectoryArray);
4860
+ if (commentLength) {
4861
+ await writeData(writable, comment);
4862
+ }
4863
+ }
4864
+
4865
+ async function writeData(writable, array) {
4866
+ const streamWriter = writable.getWriter();
4867
+ await streamWriter.ready;
4868
+ writable.size += getLength(array);
4869
+ await streamWriter.write(array);
4870
+ streamWriter.releaseLock();
4871
+ }
4872
+
4873
+ function getTimeNTFS(date) {
4874
+ if (date) {
4875
+ return ((BigInt(date.getTime()) + BigInt(11644473600000)) * BigInt(10000));
4876
+ }
4877
+ }
4878
+
4879
+ function getOptionValue(zipWriter, options, name, defaultValue) {
4880
+ const result = options[name] === UNDEFINED_VALUE ? zipWriter.options[name] : options[name];
4881
+ return result === UNDEFINED_VALUE ? defaultValue : result;
4882
+ }
4883
+
4884
+ function getMaximumCompressedSize(uncompressedSize) {
4885
+ return uncompressedSize + (5 * (Math.floor(uncompressedSize / 16383) + 1));
4886
+ }
4887
+
4888
+ function setUint8(view, offset, value) {
4889
+ view.setUint8(offset, value);
4890
+ }
4891
+
4892
+ function setUint16(view, offset, value) {
4893
+ view.setUint16(offset, value, true);
4894
+ }
4895
+
4896
+ function setUint32(view, offset, value) {
4897
+ view.setUint32(offset, value, true);
4898
+ }
4899
+
4900
+ function setBigUint64(view, offset, value) {
4901
+ view.setBigUint64(offset, value, true);
4902
+ }
4903
+
4904
+ function arraySet(array, typedArray, offset) {
4905
+ array.set(typedArray, offset);
4906
+ }
4907
+
4908
+ function getDataView(array) {
4909
+ return new DataView(array.buffer);
4910
+ }
4911
+
4912
+ function getLength(...arrayLikes) {
4913
+ let result = 0;
4914
+ arrayLikes.forEach(arrayLike => arrayLike && (result += arrayLike.length));
4915
+ return result;
4916
+ }
4917
+
4918
+ /*
4919
+ Copyright (c) 2022 Gildas Lormeau. All rights reserved.
4920
+
4921
+ Redistribution and use in source and binary forms, with or without
4922
+ modification, are permitted provided that the following conditions are met:
4923
+
4924
+ 1. Redistributions of source code must retain the above copyright notice,
4925
+ this list of conditions and the following disclaimer.
4926
+
4927
+ 2. Redistributions in binary form must reproduce the above copyright
4928
+ notice, this list of conditions and the following disclaimer in
4929
+ the documentation and/or other materials provided with the distribution.
4930
+
4931
+ 3. The names of the authors may not be used to endorse or promote products
4932
+ derived from this software without specific prior written permission.
4933
+
4934
+ THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
4935
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
4936
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
4937
+ INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
4938
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
4939
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
4940
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
4941
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
4942
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
4943
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4944
+ */
4945
+
4946
+ let baseURL;
4947
+ try {
4948
+ baseURL = import.meta.url;
4949
+ } catch (_error) {
4950
+ // ignored
4951
+ }
4952
+ configure({ baseURL });
4953
+ e(configure);
4954
+
4955
+ export { BlobReader, BlobWriter, Data64URIReader, Data64URIWriter, ERR_BAD_FORMAT, ERR_CENTRAL_DIRECTORY_NOT_FOUND, ERR_DUPLICATED_NAME, ERR_ENCRYPTED, ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND, ERR_EOCDR_NOT_FOUND, ERR_EOCDR_ZIP64_NOT_FOUND, ERR_EXTRAFIELD_ZIP64_NOT_FOUND, ERR_HTTP_RANGE, ERR_INVALID_COMMENT, ERR_INVALID_ENCRYPTION_STRENGTH, ERR_INVALID_ENTRY_COMMENT, ERR_INVALID_ENTRY_NAME, ERR_INVALID_EXTRAFIELD_DATA, ERR_INVALID_EXTRAFIELD_TYPE, ERR_INVALID_PASSWORD, ERR_INVALID_SIGNATURE, ERR_INVALID_VERSION, ERR_ITERATOR_COMPLETED_TOO_SOON, ERR_LOCAL_FILE_HEADER_NOT_FOUND, ERR_SPLIT_ZIP_FILE, ERR_UNSUPPORTED_COMPRESSION, ERR_UNSUPPORTED_ENCRYPTION, ERR_UNSUPPORTED_FORMAT, HttpRangeReader, HttpReader, Reader, SplitDataReader, SplitDataWriter, SplitZipReader, SplitZipWriter, TextReader, TextWriter, Uint8ArrayReader, Uint8ArrayWriter, Writer, ZipReader, ZipWriter, configure, getMimeType, initReader, initShimAsyncCodec, initStream, initWriter, readUint8Array, terminateWorkers };