@loaders.gl/archives 0.0.0-stage → 5.0.0-alpha.13

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.
Files changed (167) hide show
  1. package/README.md +4 -2
  2. package/dist/dist.dev.js +5101 -0
  3. package/dist/dist.min.js +9 -0
  4. package/dist/index.cjs +2982 -0
  5. package/dist/index.cjs.map +6 -0
  6. package/dist/index.d.ts +11 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +11 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/tar/index.cjs +576 -0
  11. package/dist/tar/index.cjs.map +6 -0
  12. package/dist/tar/index.d.ts +8 -0
  13. package/dist/tar/index.d.ts.map +1 -0
  14. package/dist/tar/index.js +9 -0
  15. package/dist/tar/index.js.map +1 -0
  16. package/dist/tar/lib/header.d.ts +9 -0
  17. package/dist/tar/lib/header.d.ts.map +1 -0
  18. package/dist/tar/lib/header.js +76 -0
  19. package/dist/tar/lib/header.js.map +1 -0
  20. package/dist/tar/lib/tar.d.ts +29 -0
  21. package/dist/tar/lib/tar.d.ts.map +1 -0
  22. package/dist/tar/lib/tar.js +136 -0
  23. package/dist/tar/lib/tar.js.map +1 -0
  24. package/dist/tar/lib/types.d.ts +48 -0
  25. package/dist/tar/lib/types.d.ts.map +1 -0
  26. package/dist/tar/lib/types.js +5 -0
  27. package/dist/tar/lib/types.js.map +1 -0
  28. package/dist/tar/lib/utils.d.ts +23 -0
  29. package/dist/tar/lib/utils.d.ts.map +1 -0
  30. package/dist/tar/lib/utils.js +52 -0
  31. package/dist/tar/lib/utils.js.map +1 -0
  32. package/dist/tar/tar-archive.d.ts +4 -0
  33. package/dist/tar/tar-archive.d.ts.map +1 -0
  34. package/dist/tar/tar-archive.js +97 -0
  35. package/dist/tar/tar-archive.js.map +1 -0
  36. package/dist/tar/tar-builder.d.ts +28 -0
  37. package/dist/tar/tar-builder.d.ts.map +1 -0
  38. package/dist/tar/tar-builder.js +38 -0
  39. package/dist/tar/tar-builder.js.map +1 -0
  40. package/dist/tar/tar-format.d.ts +12 -0
  41. package/dist/tar/tar-format.d.ts.map +1 -0
  42. package/dist/tar/tar-format.js +15 -0
  43. package/dist/tar/tar-format.js.map +1 -0
  44. package/dist/tar/tar-loader-types.d.ts +15 -0
  45. package/dist/tar/tar-loader-types.d.ts.map +1 -0
  46. package/dist/tar/tar-loader-types.js +20 -0
  47. package/dist/tar/tar-loader-types.js.map +1 -0
  48. package/dist/tar/tar-loader.cjs +285 -0
  49. package/dist/tar/tar-loader.cjs.map +6 -0
  50. package/dist/tar/tar-loader.d.ts +3 -0
  51. package/dist/tar/tar-loader.d.ts.map +1 -0
  52. package/dist/tar/tar-loader.js +12 -0
  53. package/dist/tar/tar-loader.js.map +1 -0
  54. package/dist/tar/tar-writer.cjs +114 -0
  55. package/dist/tar/tar-writer.cjs.map +6 -0
  56. package/dist/tar/tar-writer.d.ts +20 -0
  57. package/dist/tar/tar-writer.d.ts.map +1 -0
  58. package/dist/tar/tar-writer.js +94 -0
  59. package/dist/tar/tar-writer.js.map +1 -0
  60. package/dist/zip/filesystems/IndexedArchive.d.ts +40 -0
  61. package/dist/zip/filesystems/IndexedArchive.d.ts.map +1 -0
  62. package/dist/zip/filesystems/IndexedArchive.js +99 -0
  63. package/dist/zip/filesystems/IndexedArchive.js.map +1 -0
  64. package/dist/zip/filesystems/zip-filesystem.d.ts +53 -0
  65. package/dist/zip/filesystems/zip-filesystem.d.ts.map +1 -0
  66. package/dist/zip/filesystems/zip-filesystem.js +231 -0
  67. package/dist/zip/filesystems/zip-filesystem.js.map +1 -0
  68. package/dist/zip/hash-file-utility.d.ts +20 -0
  69. package/dist/zip/hash-file-utility.d.ts.map +1 -0
  70. package/dist/zip/hash-file-utility.js +83 -0
  71. package/dist/zip/hash-file-utility.js.map +1 -0
  72. package/dist/zip/index.cjs +4614 -0
  73. package/dist/zip/index.cjs.map +6 -0
  74. package/dist/zip/index.d.ts +18 -0
  75. package/dist/zip/index.d.ts.map +1 -0
  76. package/dist/zip/index.js +14 -0
  77. package/dist/zip/index.js.map +1 -0
  78. package/dist/zip/indexed-zip-writer.cjs +1211 -0
  79. package/dist/zip/indexed-zip-writer.cjs.map +6 -0
  80. package/dist/zip/indexed-zip-writer.d.ts +46 -0
  81. package/dist/zip/indexed-zip-writer.d.ts.map +1 -0
  82. package/dist/zip/indexed-zip-writer.js +229 -0
  83. package/dist/zip/indexed-zip-writer.js.map +1 -0
  84. package/dist/zip/lib/zip-composition.d.ts +37 -0
  85. package/dist/zip/lib/zip-composition.d.ts.map +1 -0
  86. package/dist/zip/lib/zip-composition.js +157 -0
  87. package/dist/zip/lib/zip-composition.js.map +1 -0
  88. package/dist/zip/lib/zip-entry-metadata.d.ts +34 -0
  89. package/dist/zip/lib/zip-entry-metadata.d.ts.map +1 -0
  90. package/dist/zip/lib/zip-entry-metadata.js +132 -0
  91. package/dist/zip/lib/zip-entry-metadata.js.map +1 -0
  92. package/dist/zip/lib/zip-serialization.d.ts +36 -0
  93. package/dist/zip/lib/zip-serialization.d.ts.map +1 -0
  94. package/dist/zip/lib/zip-serialization.js +148 -0
  95. package/dist/zip/lib/zip-serialization.js.map +1 -0
  96. package/dist/zip/lib/zip64-extra-field.d.ts +20 -0
  97. package/dist/zip/lib/zip64-extra-field.d.ts.map +1 -0
  98. package/dist/zip/lib/zip64-extra-field.js +53 -0
  99. package/dist/zip/lib/zip64-extra-field.js.map +1 -0
  100. package/dist/zip/zip-archive-types.d.ts +56 -0
  101. package/dist/zip/zip-archive-types.d.ts.map +1 -0
  102. package/dist/zip/zip-archive-types.js +5 -0
  103. package/dist/zip/zip-archive-types.js.map +1 -0
  104. package/dist/zip/zip-archive.d.ts +101 -0
  105. package/dist/zip/zip-archive.d.ts.map +1 -0
  106. package/dist/zip/zip-archive.js +593 -0
  107. package/dist/zip/zip-archive.js.map +1 -0
  108. package/dist/zip/zip-encode-types.d.ts +41 -0
  109. package/dist/zip/zip-encode-types.d.ts.map +1 -0
  110. package/dist/zip/zip-encode-types.js +5 -0
  111. package/dist/zip/zip-encode-types.js.map +1 -0
  112. package/dist/zip/zip-encode.cjs +1154 -0
  113. package/dist/zip/zip-encode.cjs.map +6 -0
  114. package/dist/zip/zip-encode.d.ts +15 -0
  115. package/dist/zip/zip-encode.d.ts.map +1 -0
  116. package/dist/zip/zip-encode.js +312 -0
  117. package/dist/zip/zip-encode.js.map +1 -0
  118. package/dist/zip/zip-format.d.ts +14 -0
  119. package/dist/zip/zip-format.d.ts.map +1 -0
  120. package/dist/zip/zip-format.js +17 -0
  121. package/dist/zip/zip-format.js.map +1 -0
  122. package/dist/zip/zip-loader-types.d.ts +15 -0
  123. package/dist/zip/zip-loader-types.d.ts.map +1 -0
  124. package/dist/zip/zip-loader-types.js +20 -0
  125. package/dist/zip/zip-loader-types.js.map +1 -0
  126. package/dist/zip/zip-loader.cjs +2681 -0
  127. package/dist/zip/zip-loader.cjs.map +6 -0
  128. package/dist/zip/zip-loader.d.ts +3 -0
  129. package/dist/zip/zip-loader.d.ts.map +1 -0
  130. package/dist/zip/zip-loader.js +38 -0
  131. package/dist/zip/zip-loader.js.map +1 -0
  132. package/dist/zip/zip-writer.cjs +1208 -0
  133. package/dist/zip/zip-writer.cjs.map +6 -0
  134. package/dist/zip/zip-writer.d.ts +40 -0
  135. package/dist/zip/zip-writer.d.ts.map +1 -0
  136. package/dist/zip/zip-writer.js +48 -0
  137. package/dist/zip/zip-writer.js.map +1 -0
  138. package/package.json +88 -4
  139. package/src/index.ts +14 -0
  140. package/src/tar/index.ts +11 -0
  141. package/src/tar/lib/header.ts +82 -0
  142. package/src/tar/lib/tar.ts +160 -0
  143. package/src/tar/lib/types.ts +51 -0
  144. package/src/tar/lib/utils.ts +55 -0
  145. package/src/tar/tar-archive.ts +98 -0
  146. package/src/tar/tar-builder.ts +47 -0
  147. package/src/tar/tar-format.ts +17 -0
  148. package/src/tar/tar-loader-types.ts +36 -0
  149. package/src/tar/tar-loader.ts +17 -0
  150. package/src/tar/tar-writer.ts +102 -0
  151. package/src/zip/filesystems/IndexedArchive.ts +110 -0
  152. package/src/zip/filesystems/zip-filesystem.ts +244 -0
  153. package/src/zip/hash-file-utility.ts +109 -0
  154. package/src/zip/index.ts +38 -0
  155. package/src/zip/indexed-zip-writer.ts +345 -0
  156. package/src/zip/lib/zip-composition.ts +243 -0
  157. package/src/zip/lib/zip-entry-metadata.ts +157 -0
  158. package/src/zip/lib/zip-serialization.ts +206 -0
  159. package/src/zip/lib/zip64-extra-field.ts +84 -0
  160. package/src/zip/zip-archive-types.ts +64 -0
  161. package/src/zip/zip-archive.ts +733 -0
  162. package/src/zip/zip-encode-types.ts +53 -0
  163. package/src/zip/zip-encode.ts +370 -0
  164. package/src/zip/zip-format.ts +19 -0
  165. package/src/zip/zip-loader-types.ts +36 -0
  166. package/src/zip/zip-loader.ts +43 -0
  167. package/src/zip/zip-writer.ts +73 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,2982 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res, err) => function __init() {
9
+ if (err) throw err[0];
10
+ try {
11
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
+ } catch (e) {
13
+ throw err = [e], e;
14
+ }
15
+ };
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
+ // If the importer is in node compatibility mode or this is not an ESM
30
+ // file that has been converted to a CommonJS file using a Babel-
31
+ // compatible transform (i.e. "__esModule" has not been set), then set
32
+ // "default" to the CommonJS "module.exports" for node compatibility.
33
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
+ mod
35
+ ));
36
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
+
38
+ // src/zip/zip-format.ts
39
+ var ZipFormat2;
40
+ var init_zip_format = __esm({
41
+ "src/zip/zip-format.ts"() {
42
+ "use strict";
43
+ ZipFormat2 = {
44
+ name: "Zip Archive",
45
+ id: "zip",
46
+ module: "archives",
47
+ encoding: "zip",
48
+ format: "zip",
49
+ extensions: ["zip"],
50
+ mimeTypes: ["application/zip"],
51
+ category: "archive",
52
+ binary: true,
53
+ tests: ["PK"]
54
+ };
55
+ }
56
+ });
57
+
58
+ // src/zip/zip-loader-types.ts
59
+ var VERSION, ZipLoader;
60
+ var init_zip_loader_types = __esm({
61
+ "src/zip/zip-loader-types.ts"() {
62
+ "use strict";
63
+ init_zip_format();
64
+ VERSION = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
65
+ ZipLoader = {
66
+ ...ZipFormat2,
67
+ version: VERSION,
68
+ dataType: null,
69
+ batchType: null,
70
+ options: { zip: { maxTotalDecodedBytes: 64n * 1024n * 1024n } },
71
+ /** Loads the parser implementation through its installed package subpath. */
72
+ async preload() {
73
+ const { ZipLoaderWithParser: ZipLoaderWithParser2 } = await Promise.resolve().then(() => (init_zip_loader(), zip_loader_exports));
74
+ return ZipLoaderWithParser2;
75
+ }
76
+ };
77
+ }
78
+ });
79
+
80
+ // ../core/src/loader-utils/lib/module-utils/js-module-utils.ts
81
+ function registerJSModules(modules) {
82
+ globalThis.loaders ||= {};
83
+ globalThis.loaders.modules ||= {};
84
+ Object.assign(globalThis.loaders.modules, modules);
85
+ }
86
+ var init_js_module_utils = __esm({
87
+ "../core/src/loader-utils/lib/module-utils/js-module-utils.ts"() {
88
+ "use strict";
89
+ }
90
+ });
91
+
92
+ // ../core/src/loader-utils/lib/binary-utils/array-buffer-utils.ts
93
+ function concatenateArrayBuffers(...sources) {
94
+ return concatenateArrayBuffersFromArray(sources);
95
+ }
96
+ function concatenateArrayBuffersFromArray(sources) {
97
+ const sourceArrays = sources.map(
98
+ (source2) => source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2
99
+ );
100
+ const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);
101
+ const result = new Uint8Array(byteLength);
102
+ let offset = 0;
103
+ for (const sourceArray of sourceArrays) {
104
+ result.set(sourceArray, offset);
105
+ offset += sourceArray.byteLength;
106
+ }
107
+ return result.buffer;
108
+ }
109
+ var init_array_buffer_utils = __esm({
110
+ "../core/src/loader-utils/lib/binary-utils/array-buffer-utils.ts"() {
111
+ "use strict";
112
+ }
113
+ });
114
+
115
+ // ../core/src/loader-utils/lib/iterators/async-iteration.ts
116
+ async function concatenateArrayBuffersAsync(asyncIterator) {
117
+ const arrayBuffers = [];
118
+ for await (const chunk of asyncIterator) {
119
+ arrayBuffers.push(copyToArrayBuffer(chunk));
120
+ }
121
+ return concatenateArrayBuffers(...arrayBuffers);
122
+ }
123
+ function copyToArrayBuffer(chunk) {
124
+ if (chunk instanceof ArrayBuffer) {
125
+ return chunk;
126
+ }
127
+ if (ArrayBuffer.isView(chunk)) {
128
+ const { buffer, byteOffset, byteLength } = chunk;
129
+ return copyFromBuffer(buffer, byteOffset, byteLength);
130
+ }
131
+ return copyFromBuffer(chunk);
132
+ }
133
+ function copyFromBuffer(buffer, byteOffset = 0, byteLength = buffer.byteLength - byteOffset) {
134
+ const view = new Uint8Array(buffer, byteOffset, byteLength);
135
+ const copy = new Uint8Array(view.length);
136
+ copy.set(view);
137
+ return copy.buffer;
138
+ }
139
+ var init_async_iteration = __esm({
140
+ "../core/src/loader-utils/lib/iterators/async-iteration.ts"() {
141
+ "use strict";
142
+ init_array_buffer_utils();
143
+ }
144
+ });
145
+
146
+ // ../core/src/loader-utils/lib/files/blob-file.ts
147
+ var BlobFile;
148
+ var init_blob_file = __esm({
149
+ "../core/src/loader-utils/lib/files/blob-file.ts"() {
150
+ "use strict";
151
+ BlobFile = class {
152
+ handle;
153
+ size;
154
+ bigsize;
155
+ url;
156
+ constructor(blob) {
157
+ this.handle = blob instanceof ArrayBuffer ? new Blob([blob]) : blob;
158
+ this.size = blob instanceof ArrayBuffer ? blob.byteLength : blob.size;
159
+ this.bigsize = BigInt(this.size);
160
+ this.url = blob instanceof File ? blob.name : "";
161
+ }
162
+ async close() {
163
+ }
164
+ async stat() {
165
+ return {
166
+ size: this.handle.size,
167
+ bigsize: BigInt(this.handle.size),
168
+ isDirectory: false
169
+ };
170
+ }
171
+ async read(start, length, signal) {
172
+ if (signal == null ? void 0 : signal.aborted) {
173
+ throw new Error("Request aborted");
174
+ }
175
+ const arrayBuffer = await this.handle.slice(Number(start), Number(start) + Number(length)).arrayBuffer();
176
+ if (signal == null ? void 0 : signal.aborted) {
177
+ throw new Error("Request aborted");
178
+ }
179
+ return arrayBuffer;
180
+ }
181
+ };
182
+ }
183
+ });
184
+
185
+ // ../core/src/loader-utils/index.ts
186
+ var init_loader_utils = __esm({
187
+ "../core/src/loader-utils/index.ts"() {
188
+ "use strict";
189
+ init_js_module_utils();
190
+ init_async_iteration();
191
+ init_blob_file();
192
+ }
193
+ });
194
+
195
+ // ../compression/src/lib/compression.ts
196
+ var CompressionTransform, Compressor, Decompressor;
197
+ var init_compression = __esm({
198
+ "../compression/src/lib/compression.ts"() {
199
+ "use strict";
200
+ init_loader_utils();
201
+ CompressionTransform = class {
202
+ /** Preloads any dynamic libraries. May enable sync functions */
203
+ async preload(modules = {}) {
204
+ registerJSModules(modules);
205
+ return void 0;
206
+ }
207
+ // HELPERS
208
+ concatenate(asyncIterator) {
209
+ return concatenateArrayBuffersAsync(asyncIterator);
210
+ }
211
+ improveError(error) {
212
+ if (!error.message.includes(this.name)) {
213
+ error.message = `${this.name} ${error.message}`;
214
+ }
215
+ return error;
216
+ }
217
+ };
218
+ Compressor = class extends CompressionTransform {
219
+ constructor(options) {
220
+ super();
221
+ this.compressBatches = this.compressBatches.bind(this);
222
+ }
223
+ /** Asynchronously compresses data. */
224
+ async compress(input) {
225
+ await this.preload();
226
+ return this.compressSync(input);
227
+ }
228
+ /** Synchronously compresses data. */
229
+ compressSync(input) {
230
+ throw new Error(`${this.name}: sync compression not supported`);
231
+ }
232
+ /** Compresses batches. */
233
+ async *compressBatches(asyncIterator) {
234
+ const input = await this.concatenate(asyncIterator);
235
+ yield this.compress(input);
236
+ }
237
+ };
238
+ Decompressor = class extends CompressionTransform {
239
+ constructor(options) {
240
+ super();
241
+ this.decompressBatches = this.decompressBatches.bind(this);
242
+ }
243
+ /** Asynchronously decompresses data. */
244
+ async decompress(input, size) {
245
+ await this.preload();
246
+ return this.decompressSync(input, size);
247
+ }
248
+ /** Synchronously decompresses data. */
249
+ decompressSync(input, size) {
250
+ throw new Error(`${this.name}: sync decompression not supported`);
251
+ }
252
+ /** Decompresses batches. */
253
+ async *decompressBatches(asyncIterator) {
254
+ const input = await this.concatenate(asyncIterator);
255
+ yield this.decompress(input);
256
+ }
257
+ };
258
+ }
259
+ });
260
+
261
+ // ../compression/src/lib/compress-utils-compression.ts
262
+ async function* transformBatches(stream, inputBatches, maximumOutputByteLength = Number.POSITIVE_INFINITY) {
263
+ let outputByteLength = 0;
264
+ try {
265
+ for await (const input of inputBatches) {
266
+ const output2 = stream.write(new Uint8Array(input));
267
+ if (output2.byteLength > maximumOutputByteLength - outputByteLength)
268
+ throw new RangeError("Decompressed output exceeds maxOutputByteLength");
269
+ outputByteLength += output2.byteLength;
270
+ if (output2.byteLength > 0) yield copyArrayBuffer(output2);
271
+ }
272
+ const output = stream.finish();
273
+ if (output.byteLength > maximumOutputByteLength - outputByteLength)
274
+ throw new RangeError("Decompressed output exceeds maxOutputByteLength");
275
+ if (output.byteLength > 0) yield copyArrayBuffer(output);
276
+ } finally {
277
+ stream.destroy();
278
+ }
279
+ }
280
+ function copyArrayBuffer(bytes) {
281
+ return bytes.slice().buffer;
282
+ }
283
+ function getDecompressOptions(options, size) {
284
+ const decodeOptions = {
285
+ ...options.compressUtils,
286
+ ...size === void 0 ? {} : { expectedSize: size }
287
+ };
288
+ const capacity = decodeOptions.expectedSize;
289
+ const maximum = getMaximumOutputByteLength(options);
290
+ if (capacity !== void 0 && (!Number.isSafeInteger(capacity) || capacity < 0 || capacity > maximum)) {
291
+ throw new RangeError("expectedSize exceeds the configured output capacity limit");
292
+ }
293
+ return decodeOptions;
294
+ }
295
+ function getMaximumOutputByteLength(options) {
296
+ const maximum = options.maxOutputByteLength ?? 512 * 1024 * 1024;
297
+ if (!Number.isSafeInteger(maximum) || maximum < 0 || maximum > 2147483647)
298
+ throw new RangeError("Invalid maxOutputByteLength");
299
+ return maximum;
300
+ }
301
+ function copyDecompressedOutput(bytes, options) {
302
+ if (bytes.byteLength > getMaximumOutputByteLength(options))
303
+ throw new RangeError("Decompressed output exceeds maxOutputByteLength");
304
+ return copyArrayBuffer(bytes);
305
+ }
306
+ var CompressUtilsCompressor, CompressUtilsDecompressor;
307
+ var init_compress_utils_compression = __esm({
308
+ "../compression/src/lib/compress-utils-compression.ts"() {
309
+ "use strict";
310
+ init_compression();
311
+ CompressUtilsCompressor = class extends Compressor {
312
+ name;
313
+ extensions;
314
+ contentEncodings;
315
+ isSupported = true;
316
+ options;
317
+ loadModule;
318
+ /** Module initialized for synchronous operations. */
319
+ module = null;
320
+ /** Shared import and WASM initialization for concurrent callers. */
321
+ modulePromise = null;
322
+ /** Creates a format-specific compress-utils encoder. */
323
+ constructor(metadata3, loadModule, options = {}) {
324
+ super(options);
325
+ this.name = metadata3.name;
326
+ this.extensions = metadata3.extensions || [];
327
+ this.contentEncodings = metadata3.contentEncodings || [];
328
+ this.loadModule = loadModule;
329
+ this.options = options;
330
+ }
331
+ /** Imports and initializes the codec without loading the opposite direction. */
332
+ async preload(modules = {}) {
333
+ await super.preload(modules);
334
+ this.modulePromise ||= this.loadModule().then(async (module2) => {
335
+ var _a;
336
+ await ((_a = module2.preload) == null ? void 0 : _a.call(module2));
337
+ this.module = module2;
338
+ });
339
+ try {
340
+ await this.modulePromise;
341
+ } catch (error) {
342
+ this.modulePromise = null;
343
+ throw error;
344
+ }
345
+ }
346
+ /** Runs synchronously after preload has initialized the WASM codec. */
347
+ compressSync(input) {
348
+ var _a;
349
+ if (!((_a = this.module) == null ? void 0 : _a.compressSync))
350
+ throw new Error(`${this.name}: call preload() before compressSync()`);
351
+ return copyArrayBuffer(
352
+ this.module.compressSync(new Uint8Array(input), this.options.compressUtils)
353
+ );
354
+ }
355
+ /** Compresses one buffer with the selected compress-utils encoder. */
356
+ async compress(input) {
357
+ await this.preload();
358
+ const module2 = this.module;
359
+ const output = await module2.compress(new Uint8Array(input), this.options.compressUtils);
360
+ return copyArrayBuffer(output);
361
+ }
362
+ /** Incrementally compresses input batches with compress-utils. */
363
+ async *compressBatches(inputBatches) {
364
+ await this.preload();
365
+ const module2 = this.module;
366
+ if (!module2.createCompressStream) {
367
+ yield await this.compress(await this.concatenate(inputBatches));
368
+ return;
369
+ }
370
+ const stream = await module2.createCompressStream(this.options.compressUtils);
371
+ yield* transformBatches(stream, inputBatches);
372
+ }
373
+ };
374
+ CompressUtilsDecompressor = class extends Decompressor {
375
+ name;
376
+ extensions;
377
+ contentEncodings;
378
+ isSupported = true;
379
+ options;
380
+ loadModule;
381
+ /** Module initialized for synchronous operations. */
382
+ module = null;
383
+ /** Shared import and WASM initialization for concurrent callers. */
384
+ modulePromise = null;
385
+ /** Creates a format-specific compress-utils decoder. */
386
+ constructor(metadata3, loadModule, options = {}) {
387
+ super(options);
388
+ this.name = metadata3.name;
389
+ this.extensions = metadata3.extensions || [];
390
+ this.contentEncodings = metadata3.contentEncodings || [];
391
+ this.loadModule = loadModule;
392
+ this.options = options;
393
+ }
394
+ /** Imports and initializes the codec without loading the opposite direction. */
395
+ async preload(modules = {}) {
396
+ await super.preload(modules);
397
+ this.modulePromise ||= this.loadModule().then(async (module2) => {
398
+ var _a;
399
+ await ((_a = module2.preload) == null ? void 0 : _a.call(module2));
400
+ this.module = module2;
401
+ });
402
+ try {
403
+ await this.modulePromise;
404
+ } catch (error) {
405
+ this.modulePromise = null;
406
+ throw error;
407
+ }
408
+ }
409
+ /** Runs synchronously after preload has initialized the WASM codec. */
410
+ decompressSync(input, size) {
411
+ var _a;
412
+ if (!((_a = this.module) == null ? void 0 : _a.decompressSync))
413
+ throw new Error(`${this.name}: call preload() before decompressSync()`);
414
+ return copyDecompressedOutput(
415
+ this.module.decompressSync(new Uint8Array(input), getDecompressOptions(this.options, size)),
416
+ this.options
417
+ );
418
+ }
419
+ /** Decompresses one buffer with the selected compress-utils decoder. */
420
+ async decompress(input, size) {
421
+ const decodeOptions = getDecompressOptions(this.options, size);
422
+ await this.preload();
423
+ const module2 = this.module;
424
+ const output = await module2.decompress(new Uint8Array(input), decodeOptions);
425
+ return copyDecompressedOutput(output, this.options);
426
+ }
427
+ /** Incrementally decompresses input batches with compress-utils. */
428
+ async *decompressBatches(inputBatches) {
429
+ await this.preload();
430
+ const module2 = this.module;
431
+ if (!module2.createDecompressStream) {
432
+ yield await this.decompress(await this.concatenate(inputBatches));
433
+ return;
434
+ }
435
+ const maximum = getMaximumOutputByteLength(this.options);
436
+ const stream = await module2.createDecompressStream();
437
+ yield* transformBatches(stream, inputBatches, maximum);
438
+ }
439
+ };
440
+ }
441
+ });
442
+
443
+ // ../compression/src/deflate-decompressor-compress-utils.ts
444
+ var DeflateCompressUtilsDecompressor;
445
+ var init_deflate_decompressor_compress_utils = __esm({
446
+ "../compression/src/deflate-decompressor-compress-utils.ts"() {
447
+ "use strict";
448
+ init_compress_utils_compression();
449
+ DeflateCompressUtilsDecompressor = class extends CompressUtilsDecompressor {
450
+ constructor(options = {}) {
451
+ super(
452
+ { name: "deflate", contentEncodings: ["deflate"] },
453
+ () => options.raw ? import("compress-utils/deflate/decompress") : import("compress-utils/zlib/decompress"),
454
+ options
455
+ );
456
+ }
457
+ };
458
+ }
459
+ });
460
+
461
+ // ../compression/src/lib/decompression-stream.ts
462
+ async function decompressWithNativeDecompressionStream(input, format2) {
463
+ const outputBatches = decompressBatchesWithNativeDecompressionStream([input], format2);
464
+ return outputBatches ? await concatenateNativeDecompressionBatches(outputBatches) : null;
465
+ }
466
+ function decompressBatchesWithNativeDecompressionStream(inputBatches, format2) {
467
+ const decompressionStream = createNativeDecompressionStream(format2);
468
+ return decompressionStream ? transformBatchesWithNativeDecompressionStream(inputBatches, decompressionStream) : null;
469
+ }
470
+ function createNativeDecompressionStream(format2) {
471
+ var _a, _b;
472
+ if (typeof globalThis.DecompressionStream === "undefined") {
473
+ return null;
474
+ }
475
+ if (((_b = (_a = globalThis.process) == null ? void 0 : _a.release) == null ? void 0 : _b.name) === "node" && typeof globalThis.Buffer === "undefined") {
476
+ return null;
477
+ }
478
+ try {
479
+ const DecompressionStreamConstructor = globalThis.DecompressionStream;
480
+ return new DecompressionStreamConstructor(format2);
481
+ } catch (error) {
482
+ if (error instanceof TypeError || (error == null ? void 0 : error.name) === "TypeError") {
483
+ return null;
484
+ }
485
+ throw error;
486
+ }
487
+ }
488
+ async function* transformBatchesWithNativeDecompressionStream(inputBatches, decompressionStream) {
489
+ const writer = decompressionStream.writable.getWriter();
490
+ const reader = decompressionStream.readable.getReader();
491
+ const writePromise = writeBatchesToNativeDecompressionStream(inputBatches, writer);
492
+ writePromise.catch(() => {
493
+ });
494
+ let outputCompleted = false;
495
+ try {
496
+ while (true) {
497
+ const { done, value } = await reader.read();
498
+ if (done) {
499
+ outputCompleted = true;
500
+ break;
501
+ }
502
+ yield copyExactArrayBuffer(value);
503
+ }
504
+ await writePromise;
505
+ } finally {
506
+ if (!outputCompleted) {
507
+ await reader.cancel().catch(() => {
508
+ });
509
+ await writer.abort().catch(() => {
510
+ });
511
+ await writePromise.catch(() => {
512
+ });
513
+ }
514
+ reader.releaseLock();
515
+ }
516
+ }
517
+ async function concatenateNativeDecompressionBatches(outputBatches) {
518
+ const batches = [];
519
+ let byteLength = 0;
520
+ for await (const outputBatch of outputBatches) {
521
+ const bytes = new Uint8Array(outputBatch);
522
+ batches.push(bytes);
523
+ byteLength += bytes.byteLength;
524
+ }
525
+ const output = new Uint8Array(byteLength);
526
+ let byteOffset = 0;
527
+ for (const batch of batches) {
528
+ output.set(batch, byteOffset);
529
+ byteOffset += batch.byteLength;
530
+ }
531
+ return output.buffer;
532
+ }
533
+ function copyExactArrayBuffer(value) {
534
+ return new Uint8Array(value).buffer;
535
+ }
536
+ async function writeBatchesToNativeDecompressionStream(inputBatches, writer) {
537
+ try {
538
+ for await (const inputBatch of inputBatches) {
539
+ await writer.write(new Uint8Array(inputBatch));
540
+ }
541
+ await writer.close();
542
+ } catch (error) {
543
+ await writer.abort(error).catch(() => {
544
+ });
545
+ throw error;
546
+ }
547
+ }
548
+ var init_decompression_stream = __esm({
549
+ "../compression/src/lib/decompression-stream.ts"() {
550
+ "use strict";
551
+ }
552
+ });
553
+
554
+ // ../compression/src/deflate-decompressor.ts
555
+ var DeflateDecompressor;
556
+ var init_deflate_decompressor = __esm({
557
+ "../compression/src/deflate-decompressor.ts"() {
558
+ "use strict";
559
+ init_deflate_decompressor_compress_utils();
560
+ init_decompression_stream();
561
+ DeflateDecompressor = class extends DeflateCompressUtilsDecompressor {
562
+ /** Decompresses with native streams when available, otherwise lazily initializes WASM. */
563
+ async decompress(input, size) {
564
+ if (this.options.useNative !== false) {
565
+ const output = await decompressWithNativeDecompressionStream(
566
+ input,
567
+ this.options.raw ? "deflate-raw" : "deflate"
568
+ );
569
+ if (output) return output;
570
+ }
571
+ return super.decompress(input, size);
572
+ }
573
+ /** Streams native batches when available, otherwise uses the WASM stream. */
574
+ async *decompressBatches(inputBatches) {
575
+ if (this.options.useNative !== false) {
576
+ const output = decompressBatchesWithNativeDecompressionStream(
577
+ inputBatches,
578
+ this.options.raw ? "deflate-raw" : "deflate"
579
+ );
580
+ if (output) {
581
+ yield* output;
582
+ return;
583
+ }
584
+ }
585
+ yield* super.decompressBatches(inputBatches);
586
+ }
587
+ };
588
+ }
589
+ });
590
+
591
+ // ../crypto/src/lib/hash.ts
592
+ var Hash;
593
+ var init_hash = __esm({
594
+ "../crypto/src/lib/hash.ts"() {
595
+ "use strict";
596
+ init_loader_utils();
597
+ Hash = class {
598
+ constructor(options = {}) {
599
+ this.hashBatches = this.hashBatches.bind(this);
600
+ }
601
+ async preload() {
602
+ return;
603
+ }
604
+ async *hashBatches(asyncIterator, encoding = "base64") {
605
+ var _a, _b;
606
+ const arrayBuffers = [];
607
+ for await (const arrayBuffer of asyncIterator) {
608
+ arrayBuffers.push(arrayBuffer);
609
+ yield arrayBuffer;
610
+ }
611
+ const output = await this.concatenate(arrayBuffers);
612
+ const hash = await this.hash(output, encoding);
613
+ (_b = (_a = this.options.crypto) == null ? void 0 : _a.onEnd) == null ? void 0 : _b.call(_a, { hash });
614
+ }
615
+ // HELPERS
616
+ async concatenate(asyncIterator) {
617
+ return await concatenateArrayBuffersAsync(asyncIterator);
618
+ }
619
+ };
620
+ }
621
+ });
622
+
623
+ // ../crypto/src/lib/algorithms/crc32.ts
624
+ function getCRC32Table() {
625
+ return CRC32TAB;
626
+ }
627
+ var CRC32, CRC32TAB;
628
+ var init_crc32 = __esm({
629
+ "../crypto/src/lib/algorithms/crc32.ts"() {
630
+ "use strict";
631
+ CRC32 = class {
632
+ crc;
633
+ constructor() {
634
+ this.crc = ~0;
635
+ }
636
+ update(arrayBuffer) {
637
+ const CRC32_TABLE = getCRC32Table();
638
+ const byteArray = new Uint8Array(arrayBuffer);
639
+ for (let i = 0; i < byteArray.byteLength; i++) {
640
+ this.crc = this.crc >>> 8 ^ CRC32_TABLE[(this.crc ^ byteArray[i]) & 255];
641
+ }
642
+ return this;
643
+ }
644
+ finalize() {
645
+ this.crc = (this.crc ^ -1) >>> 0;
646
+ return this.crc;
647
+ }
648
+ };
649
+ CRC32TAB = Uint32Array.of(
650
+ 0,
651
+ 1996959894,
652
+ 3993919788,
653
+ 2567524794,
654
+ 124634137,
655
+ 1886057615,
656
+ 3915621685,
657
+ 2657392035,
658
+ 249268274,
659
+ 2044508324,
660
+ 3772115230,
661
+ 2547177864,
662
+ 162941995,
663
+ 2125561021,
664
+ 3887607047,
665
+ 2428444049,
666
+ 498536548,
667
+ 1789927666,
668
+ 4089016648,
669
+ 2227061214,
670
+ 450548861,
671
+ 1843258603,
672
+ 4107580753,
673
+ 2211677639,
674
+ 325883990,
675
+ 1684777152,
676
+ 4251122042,
677
+ 2321926636,
678
+ 335633487,
679
+ 1661365465,
680
+ 4195302755,
681
+ 2366115317,
682
+ 997073096,
683
+ 1281953886,
684
+ 3579855332,
685
+ 2724688242,
686
+ 1006888145,
687
+ 1258607687,
688
+ 3524101629,
689
+ 2768942443,
690
+ 901097722,
691
+ 1119000684,
692
+ 3686517206,
693
+ 2898065728,
694
+ 853044451,
695
+ 1172266101,
696
+ 3705015759,
697
+ 2882616665,
698
+ 651767980,
699
+ 1373503546,
700
+ 3369554304,
701
+ 3218104598,
702
+ 565507253,
703
+ 1454621731,
704
+ 3485111705,
705
+ 3099436303,
706
+ 671266974,
707
+ 1594198024,
708
+ 3322730930,
709
+ 2970347812,
710
+ 795835527,
711
+ 1483230225,
712
+ 3244367275,
713
+ 3060149565,
714
+ 1994146192,
715
+ 31158534,
716
+ 2563907772,
717
+ 4023717930,
718
+ 1907459465,
719
+ 112637215,
720
+ 2680153253,
721
+ 3904427059,
722
+ 2013776290,
723
+ 251722036,
724
+ 2517215374,
725
+ 3775830040,
726
+ 2137656763,
727
+ 141376813,
728
+ 2439277719,
729
+ 3865271297,
730
+ 1802195444,
731
+ 476864866,
732
+ 2238001368,
733
+ 4066508878,
734
+ 1812370925,
735
+ 453092731,
736
+ 2181625025,
737
+ 4111451223,
738
+ 1706088902,
739
+ 314042704,
740
+ 2344532202,
741
+ 4240017532,
742
+ 1658658271,
743
+ 366619977,
744
+ 2362670323,
745
+ 4224994405,
746
+ 1303535960,
747
+ 984961486,
748
+ 2747007092,
749
+ 3569037538,
750
+ 1256170817,
751
+ 1037604311,
752
+ 2765210733,
753
+ 3554079995,
754
+ 1131014506,
755
+ 879679996,
756
+ 2909243462,
757
+ 3663771856,
758
+ 1141124467,
759
+ 855842277,
760
+ 2852801631,
761
+ 3708648649,
762
+ 1342533948,
763
+ 654459306,
764
+ 3188396048,
765
+ 3373015174,
766
+ 1466479909,
767
+ 544179635,
768
+ 3110523913,
769
+ 3462522015,
770
+ 1591671054,
771
+ 702138776,
772
+ 2966460450,
773
+ 3352799412,
774
+ 1504918807,
775
+ 783551873,
776
+ 3082640443,
777
+ 3233442989,
778
+ 3988292384,
779
+ 2596254646,
780
+ 62317068,
781
+ 1957810842,
782
+ 3939845945,
783
+ 2647816111,
784
+ 81470997,
785
+ 1943803523,
786
+ 3814918930,
787
+ 2489596804,
788
+ 225274430,
789
+ 2053790376,
790
+ 3826175755,
791
+ 2466906013,
792
+ 167816743,
793
+ 2097651377,
794
+ 4027552580,
795
+ 2265490386,
796
+ 503444072,
797
+ 1762050814,
798
+ 4150417245,
799
+ 2154129355,
800
+ 426522225,
801
+ 1852507879,
802
+ 4275313526,
803
+ 2312317920,
804
+ 282753626,
805
+ 1742555852,
806
+ 4189708143,
807
+ 2394877945,
808
+ 397917763,
809
+ 1622183637,
810
+ 3604390888,
811
+ 2714866558,
812
+ 953729732,
813
+ 1340076626,
814
+ 3518719985,
815
+ 2797360999,
816
+ 1068828381,
817
+ 1219638859,
818
+ 3624741850,
819
+ 2936675148,
820
+ 906185462,
821
+ 1090812512,
822
+ 3747672003,
823
+ 2825379669,
824
+ 829329135,
825
+ 1181335161,
826
+ 3412177804,
827
+ 3160834842,
828
+ 628085408,
829
+ 1382605366,
830
+ 3423369109,
831
+ 3138078467,
832
+ 570562233,
833
+ 1426400815,
834
+ 3317316542,
835
+ 2998733608,
836
+ 733239954,
837
+ 1555261956,
838
+ 3268935591,
839
+ 3050360625,
840
+ 752459403,
841
+ 1541320221,
842
+ 2607071920,
843
+ 3965973030,
844
+ 1969922972,
845
+ 40735498,
846
+ 2617837225,
847
+ 3943577151,
848
+ 1913087877,
849
+ 83908371,
850
+ 2512341634,
851
+ 3803740692,
852
+ 2075208622,
853
+ 213261112,
854
+ 2463272603,
855
+ 3855990285,
856
+ 2094854071,
857
+ 198958881,
858
+ 2262029012,
859
+ 4057260610,
860
+ 1759359992,
861
+ 534414190,
862
+ 2176718541,
863
+ 4139329115,
864
+ 1873836001,
865
+ 414664567,
866
+ 2282248934,
867
+ 4279200368,
868
+ 1711684554,
869
+ 285281116,
870
+ 2405801727,
871
+ 4167216745,
872
+ 1634467795,
873
+ 376229701,
874
+ 2685067896,
875
+ 3608007406,
876
+ 1308918612,
877
+ 956543938,
878
+ 2808555105,
879
+ 3495958263,
880
+ 1231636301,
881
+ 1047427035,
882
+ 2932959818,
883
+ 3654703836,
884
+ 1088359270,
885
+ 936918e3,
886
+ 2847714899,
887
+ 3736837829,
888
+ 1202900863,
889
+ 817233897,
890
+ 3183342108,
891
+ 3401237130,
892
+ 1404277552,
893
+ 615818150,
894
+ 3134207493,
895
+ 3453421203,
896
+ 1423857449,
897
+ 601450431,
898
+ 3009837614,
899
+ 3294710456,
900
+ 1567103746,
901
+ 711928724,
902
+ 3020668471,
903
+ 3272380065,
904
+ 1510334235,
905
+ 755167117
906
+ );
907
+ }
908
+ });
909
+
910
+ // ../crypto/src/lib/utils/base64-utils.ts
911
+ function asciiToBase64(string) {
912
+ string = `${string}`;
913
+ for (let i = 0; i < string.length; i++) {
914
+ if (string.charCodeAt(i) > 255) {
915
+ return null;
916
+ }
917
+ }
918
+ let out = "";
919
+ for (let i = 0; i < string.length; i += 3) {
920
+ const groupsOfSix = [void 0, void 0, void 0, void 0];
921
+ groupsOfSix[0] = string.charCodeAt(i) >> 2;
922
+ groupsOfSix[1] = (string.charCodeAt(i) & 3) << 4;
923
+ if (string.length > i + 1) {
924
+ groupsOfSix[1] |= string.charCodeAt(i + 1) >> 4;
925
+ groupsOfSix[2] = (string.charCodeAt(i + 1) & 15) << 2;
926
+ }
927
+ if (string.length > i + 2) {
928
+ groupsOfSix[2] |= string.charCodeAt(i + 2) >> 6;
929
+ groupsOfSix[3] = string.charCodeAt(i + 2) & 63;
930
+ }
931
+ for (let j = 0; j < groupsOfSix.length; j++) {
932
+ if (typeof groupsOfSix[j] === "undefined") {
933
+ out += "=";
934
+ } else {
935
+ out += btoaLookup(groupsOfSix[j]);
936
+ }
937
+ }
938
+ }
939
+ return out;
940
+ }
941
+ function btoaLookup(idx) {
942
+ if (idx < 26) {
943
+ return String.fromCharCode(idx + "A".charCodeAt(0));
944
+ }
945
+ if (idx < 52) {
946
+ return String.fromCharCode(idx - 26 + "a".charCodeAt(0));
947
+ }
948
+ if (idx < 62) {
949
+ return String.fromCharCode(idx - 52 + "0".charCodeAt(0));
950
+ }
951
+ if (idx === 62) {
952
+ return "+";
953
+ }
954
+ if (idx === 63) {
955
+ return "/";
956
+ }
957
+ return void 0;
958
+ }
959
+ var init_base64_utils = __esm({
960
+ "../crypto/src/lib/utils/base64-utils.ts"() {
961
+ "use strict";
962
+ }
963
+ });
964
+
965
+ // ../crypto/src/lib/utils/digest-utils.ts
966
+ function encodeNumber(number, encoding) {
967
+ switch (encoding) {
968
+ case "hex":
969
+ return convertNumberToHex(number);
970
+ case "base64":
971
+ return convertHexToBase64(convertNumberToHex(number));
972
+ default:
973
+ throw new Error(encoding);
974
+ }
975
+ }
976
+ function convertHexToBase64(hexstring) {
977
+ if (hexstring.length % 2 !== 0) {
978
+ hexstring = `0${hexstring}`;
979
+ }
980
+ const matches = hexstring.match(/\w{2}/g) || [];
981
+ const string = matches.map((a) => String.fromCharCode(parseInt(a, 16))).join("");
982
+ return asciiToBase64(string) || "";
983
+ }
984
+ function convertNumberToHex(cipher) {
985
+ const hexString = cipher.toString(16);
986
+ return hexString === "0" ? `0${hexString}` : hexString;
987
+ }
988
+ var init_digest_utils = __esm({
989
+ "../crypto/src/lib/utils/digest-utils.ts"() {
990
+ "use strict";
991
+ init_base64_utils();
992
+ }
993
+ });
994
+
995
+ // ../crypto/src/lib/crc32-hash.ts
996
+ var CRC32Hash;
997
+ var init_crc32_hash = __esm({
998
+ "../crypto/src/lib/crc32-hash.ts"() {
999
+ "use strict";
1000
+ init_hash();
1001
+ init_crc32();
1002
+ init_digest_utils();
1003
+ CRC32Hash = class extends Hash {
1004
+ name = "crc32";
1005
+ options;
1006
+ constructor(options = {}) {
1007
+ super();
1008
+ this.options = { crypto: {}, ...options };
1009
+ this.hashBatches = this.hashBatches.bind(this);
1010
+ }
1011
+ /**
1012
+ * Atomic hash calculation
1013
+ * @returns base64 encoded hash
1014
+ */
1015
+ async hash(input, encoding) {
1016
+ return this.hashSync(input, encoding);
1017
+ }
1018
+ hashSync(input, encoding) {
1019
+ const hash = new CRC32();
1020
+ hash.update(input);
1021
+ const digest = hash.finalize();
1022
+ return encodeNumber(digest, encoding);
1023
+ }
1024
+ async *hashBatches(asyncIterator, encoding = "base64") {
1025
+ var _a, _b;
1026
+ const hash = new CRC32();
1027
+ for await (const chunk of asyncIterator) {
1028
+ hash.update(chunk);
1029
+ yield chunk;
1030
+ }
1031
+ const digest = hash.finalize();
1032
+ (_b = (_a = this.options.crypto) == null ? void 0 : _a.onEnd) == null ? void 0 : _b.call(_a, { hash: encodeNumber(digest, encoding) });
1033
+ }
1034
+ };
1035
+ }
1036
+ });
1037
+
1038
+ // ../crypto/src/index.ts
1039
+ var init_src = __esm({
1040
+ "../crypto/src/index.ts"() {
1041
+ "use strict";
1042
+ init_crc32_hash();
1043
+ }
1044
+ });
1045
+
1046
+ // src/zip/lib/zip64-extra-field.ts
1047
+ function parseZip64ExtraField(extraField, expectedFields) {
1048
+ const values = {};
1049
+ if (expectedFields.length === 0) {
1050
+ return values;
1051
+ }
1052
+ const expectedPayloadLength = expectedFields.reduce(
1053
+ (totalByteLength, field) => totalByteLength + field.byteLength,
1054
+ 0
1055
+ );
1056
+ let recordOffset = 0;
1057
+ while (recordOffset < extraField.byteLength) {
1058
+ if (recordOffset + 4 > extraField.byteLength) {
1059
+ throw new Error(
1060
+ "Invalid ZIP archive: truncated extra-field record header while reading ZIP64 data"
1061
+ );
1062
+ }
1063
+ const headerId = extraField.getUint16(recordOffset, true);
1064
+ const payloadLength = extraField.getUint16(recordOffset + 2, true);
1065
+ const payloadOffset = recordOffset + 4;
1066
+ const nextRecordOffset = payloadOffset + payloadLength;
1067
+ if (nextRecordOffset > extraField.byteLength) {
1068
+ throw new Error(
1069
+ "Invalid ZIP archive: truncated extra-field record payload while reading ZIP64 data"
1070
+ );
1071
+ }
1072
+ if (headerId === ZIP64_EXTRA_FIELD_ID) {
1073
+ if (payloadLength !== expectedPayloadLength) {
1074
+ throw new Error(
1075
+ "Invalid ZIP archive: ZIP64 extended information has an unexpected payload size"
1076
+ );
1077
+ }
1078
+ let fieldOffset = payloadOffset;
1079
+ for (const field of expectedFields) {
1080
+ values[field.name] = field.byteLength === 8 ? extraField.getBigUint64(fieldOffset, true) : BigInt(extraField.getUint32(fieldOffset, true));
1081
+ fieldOffset += field.byteLength;
1082
+ }
1083
+ return values;
1084
+ }
1085
+ recordOffset = nextRecordOffset;
1086
+ }
1087
+ throw new Error("Invalid ZIP archive: required ZIP64 extended information is missing");
1088
+ }
1089
+ var ZIP64_EXTRA_FIELD_ID;
1090
+ var init_zip64_extra_field = __esm({
1091
+ "src/zip/lib/zip64-extra-field.ts"() {
1092
+ "use strict";
1093
+ ZIP64_EXTRA_FIELD_ID = 1;
1094
+ }
1095
+ });
1096
+
1097
+ // src/zip/lib/zip-entry-metadata.ts
1098
+ function decodeZipHeader(bytes, central) {
1099
+ const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1100
+ const fixedBytes = central ? 46 : 30;
1101
+ if (bytes.byteLength < fixedBytes || header.getUint32(0, true) !== (central ? 33639248 : 67324752))
1102
+ throw new Error("Invalid ZIP archive: missing entry header");
1103
+ const nameLength = header.getUint16(central ? 28 : 26, true);
1104
+ const extraLength = header.getUint16(central ? 30 : 28, true);
1105
+ const commentLength = central ? header.getUint16(32, true) : 0;
1106
+ if (bytes.byteLength !== fixedBytes + nameLength + extraLength + commentLength)
1107
+ throw new Error("Invalid ZIP archive: truncated entry metadata");
1108
+ const flags = header.getUint16(central ? 8 : 6, true);
1109
+ const method = header.getUint16(central ? 10 : 8, true);
1110
+ if (flags & (1 | 64 | 8192)) throw new Error("Unsupported ZIP encryption");
1111
+ if (flags & ~(8 | 2048 | (method === 8 ? 6 : 0))) throw new Error("Unsupported ZIP flags");
1112
+ if (method !== 0 && method !== 8)
1113
+ throw new Error(`Unsupported ZIP compression method: ${method}`);
1114
+ let compressedSize = BigInt(header.getUint32(central ? 20 : 18, true));
1115
+ let size = BigInt(header.getUint32(central ? 24 : 22, true));
1116
+ let localHeaderOffset = central ? BigInt(header.getUint32(42, true)) : 0n;
1117
+ let disk = central ? BigInt(header.getUint16(34, true)) : 0n;
1118
+ let zip64 = compressedSize === 0xffffffffn || size === 0xffffffffn;
1119
+ const fields = [];
1120
+ if (central) {
1121
+ if (size === 0xffffffffn) fields.push({ name: "size", byteLength: 8 });
1122
+ if (compressedSize === 0xffffffffn) fields.push({ name: "compressedSize", byteLength: 8 });
1123
+ if (localHeaderOffset === 0xffffffffn) fields.push({ name: "localHeaderOffset", byteLength: 8 });
1124
+ if (disk === 0xffffn) fields.push({ name: "disk", byteLength: 4 });
1125
+ } else if (zip64)
1126
+ fields.push({ name: "size", byteLength: 8 }, { name: "compressedSize", byteLength: 8 });
1127
+ const extraBytes = bytes.subarray(fixedBytes + nameLength, fixedBytes + nameLength + extraLength);
1128
+ const extra = new DataView(extraBytes.buffer, extraBytes.byteOffset, extraBytes.byteLength);
1129
+ const extraValues = parseZip64ExtraField(extra, fields);
1130
+ if (size === 0xffffffffn) size = extraValues.size;
1131
+ if (compressedSize === 0xffffffffn) compressedSize = extraValues.compressedSize;
1132
+ if (localHeaderOffset === 0xffffffffn) localHeaderOffset = extraValues.localHeaderOffset;
1133
+ if (disk === 0xffffn) disk = extraValues.disk;
1134
+ if (disk !== 0n) throw new Error("Unsupported split ZIP archive");
1135
+ const nameBytes = bytes.subarray(fixedBytes, fixedBytes + nameLength);
1136
+ let path = decodeZipText(nameBytes, Boolean(flags & 2048));
1137
+ const commentBytes = bytes.subarray(fixedBytes + nameLength + extraLength);
1138
+ let comment = decodeZipText(commentBytes, Boolean(flags & 2048));
1139
+ for (let offset = 0; offset < extra.byteLength; ) {
1140
+ if (offset + 4 > extra.byteLength)
1141
+ throw new Error("Invalid ZIP archive: truncated extra field");
1142
+ const identifier = extra.getUint16(offset, true);
1143
+ const length = extra.getUint16(offset + 2, true);
1144
+ if (offset + 4 + length > extra.byteLength)
1145
+ throw new Error("Invalid ZIP archive: truncated extra field");
1146
+ if (!central && flags & 8 && identifier === 1) {
1147
+ if (length >= 16) zip64 = true;
1148
+ }
1149
+ if (identifier === 28789 || identifier === 25461) {
1150
+ const original = identifier === 28789 ? nameBytes : commentBytes;
1151
+ if (length < 5) throw new Error("Invalid ZIP archive: truncated Unicode extra field");
1152
+ if (extra.getUint8(offset + 4) === 1 && extra.getUint32(offset + 5, true) === calculateZipChecksum(original)) {
1153
+ const text = decodeZipText(extraBytes.subarray(offset + 9, offset + 4 + length), true);
1154
+ if (identifier === 28789) path = text;
1155
+ else comment = text;
1156
+ }
1157
+ }
1158
+ offset += 4 + length;
1159
+ }
1160
+ validateZipPath(path);
1161
+ return {
1162
+ path,
1163
+ nameBytes,
1164
+ flags,
1165
+ method,
1166
+ crc32: header.getUint32(central ? 16 : 14, true),
1167
+ compressedSize,
1168
+ size,
1169
+ localHeaderOffset,
1170
+ comment,
1171
+ zip64
1172
+ };
1173
+ }
1174
+ function decodeZipText(bytes, utf8) {
1175
+ if (utf8) return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
1176
+ return Array.from(
1177
+ bytes,
1178
+ (value) => value < 128 ? String.fromCharCode(value) : CP437_HIGH[value - 128]
1179
+ ).join("");
1180
+ }
1181
+ function validateZipPath(path) {
1182
+ const segments = path.endsWith("/") ? path.slice(0, -1).split("/") : path.split("/");
1183
+ if (!path || path.includes("\\") || path.includes("\0") || /^[A-Za-z]:/.test(path) || segments.some((segment) => !segment || segment === "." || segment === ".."))
1184
+ throw new Error("Invalid ZIP archive: noncanonical relative path");
1185
+ }
1186
+ function calculateZipChecksum(bytes) {
1187
+ return Number.parseInt(new CRC32Hash().hashSync(bytes.slice().buffer, "hex"), 16);
1188
+ }
1189
+ function encodeUtf8Text(value) {
1190
+ const bytes = new TextEncoder().encode(value);
1191
+ if (new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes) !== value)
1192
+ throw new TypeError("ZIP names and entry comments must be well-formed Unicode");
1193
+ return bytes;
1194
+ }
1195
+ var CP437_HIGH;
1196
+ var init_zip_entry_metadata = __esm({
1197
+ "src/zip/lib/zip-entry-metadata.ts"() {
1198
+ "use strict";
1199
+ init_src();
1200
+ init_zip64_extra_field();
1201
+ CP437_HIGH = "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0";
1202
+ }
1203
+ });
1204
+
1205
+ // src/zip/lib/zip-serialization.ts
1206
+ function encodeZipLocalHeader(entry) {
1207
+ validateHeaderEntry(entry);
1208
+ const bytes = new Uint8Array(30 + entry.nameBytes.length + (entry.zip64 ? 20 : 0));
1209
+ const view = new DataView(bytes.buffer);
1210
+ view.setUint32(0, 67324752, true);
1211
+ view.setUint16(4, getZipVersion(entry), true);
1212
+ view.setUint16(6, entry.flags, true);
1213
+ view.setUint16(8, entry.method, true);
1214
+ view.setUint32(10, encodeZipTimestamp(entry.date), true);
1215
+ const descriptor = Boolean(entry.flags & 8);
1216
+ view.setUint32(14, descriptor ? 0 : entry.crc32, true);
1217
+ view.setUint32(
1218
+ 18,
1219
+ entry.zip64 ? Number(ZIP32_SENTINEL) : descriptor ? 0 : Number(entry.compressedSize),
1220
+ true
1221
+ );
1222
+ view.setUint32(
1223
+ 22,
1224
+ entry.zip64 ? Number(ZIP32_SENTINEL) : descriptor ? 0 : Number(entry.size),
1225
+ true
1226
+ );
1227
+ view.setUint16(26, entry.nameBytes.length, true);
1228
+ view.setUint16(28, entry.zip64 ? 20 : 0, true);
1229
+ bytes.set(entry.nameBytes, 30);
1230
+ if (entry.zip64) {
1231
+ const extraOffset = 30 + entry.nameBytes.length;
1232
+ view.setUint16(extraOffset, 1, true);
1233
+ view.setUint16(extraOffset + 2, 16, true);
1234
+ view.setBigUint64(extraOffset + 4, descriptor ? 0n : entry.size, true);
1235
+ view.setBigUint64(extraOffset + 12, descriptor ? 0n : entry.compressedSize, true);
1236
+ }
1237
+ return bytes;
1238
+ }
1239
+ function encodeZipCentralHeader(entry) {
1240
+ validateHeaderEntry(entry);
1241
+ const comment = entry.commentBytes ?? new Uint8Array();
1242
+ const extraBytes = entry.zip64 ? 28 : 0;
1243
+ const bytes = new Uint8Array(46 + entry.nameBytes.length + extraBytes + comment.length);
1244
+ const view = new DataView(bytes.buffer);
1245
+ view.setUint32(0, 33639248, true);
1246
+ view.setUint16(4, entry.zip64 ? 45 : 20, true);
1247
+ view.setUint16(6, getZipVersion(entry), true);
1248
+ view.setUint16(8, entry.flags, true);
1249
+ view.setUint16(10, entry.method, true);
1250
+ view.setUint32(12, encodeZipTimestamp(entry.date), true);
1251
+ view.setUint32(16, entry.crc32, true);
1252
+ view.setUint32(20, entry.zip64 ? Number(ZIP32_SENTINEL) : Number(entry.compressedSize), true);
1253
+ view.setUint32(24, entry.zip64 ? Number(ZIP32_SENTINEL) : Number(entry.size), true);
1254
+ view.setUint16(28, entry.nameBytes.length, true);
1255
+ view.setUint16(30, extraBytes, true);
1256
+ view.setUint16(32, comment.length, true);
1257
+ view.setUint32(38, entry.directory ? 16 : 0, true);
1258
+ view.setUint32(42, entry.zip64 ? Number(ZIP32_SENTINEL) : Number(entry.localHeaderOffset), true);
1259
+ bytes.set(entry.nameBytes, 46);
1260
+ if (entry.zip64) {
1261
+ const extraOffset = 46 + entry.nameBytes.length;
1262
+ view.setUint16(extraOffset, 1, true);
1263
+ view.setUint16(extraOffset + 2, 24, true);
1264
+ view.setBigUint64(extraOffset + 4, entry.size, true);
1265
+ view.setBigUint64(extraOffset + 12, entry.compressedSize, true);
1266
+ view.setBigUint64(extraOffset + 20, entry.localHeaderOffset, true);
1267
+ }
1268
+ bytes.set(comment, 46 + entry.nameBytes.length + extraBytes);
1269
+ return bytes;
1270
+ }
1271
+ function encodeZipEndRecords(count, directorySize, directoryOffset, zip64, comment = new Uint8Array()) {
1272
+ for (const value of [count, directorySize, directoryOffset, directoryOffset + directorySize])
1273
+ validateUint64(value);
1274
+ if (comment.length > 65535) throw new RangeError("ZIP archive comment exceeds 65535 bytes");
1275
+ if (!zip64 && (count > 0xffffn || directorySize >= ZIP32_SENTINEL || directoryOffset >= ZIP32_SENTINEL))
1276
+ throw new RangeError("ZIP32 end record capacity exceeded");
1277
+ const bytes = new Uint8Array((zip64 ? 98 : 22) + comment.length);
1278
+ const view = new DataView(bytes.buffer);
1279
+ if (zip64) {
1280
+ view.setUint32(0, 101075792, true);
1281
+ view.setBigUint64(4, 44n, true);
1282
+ view.setUint16(12, 45, true);
1283
+ view.setUint16(14, 45, true);
1284
+ view.setBigUint64(24, count, true);
1285
+ view.setBigUint64(32, count, true);
1286
+ view.setBigUint64(40, directorySize, true);
1287
+ view.setBigUint64(48, directoryOffset, true);
1288
+ view.setUint32(56, 117853008, true);
1289
+ view.setBigUint64(64, directoryOffset + directorySize, true);
1290
+ view.setUint32(72, 1, true);
1291
+ }
1292
+ const endOffset = zip64 ? 76 : 0;
1293
+ view.setUint32(endOffset, 101010256, true);
1294
+ view.setUint16(endOffset + 8, zip64 ? 65535 : Number(count), true);
1295
+ view.setUint16(endOffset + 10, zip64 ? 65535 : Number(count), true);
1296
+ view.setUint32(endOffset + 12, zip64 ? Number(ZIP32_SENTINEL) : Number(directorySize), true);
1297
+ view.setUint32(endOffset + 16, zip64 ? Number(ZIP32_SENTINEL) : Number(directoryOffset), true);
1298
+ view.setUint16(endOffset + 20, comment.length, true);
1299
+ bytes.set(comment, endOffset + 22);
1300
+ return bytes;
1301
+ }
1302
+ function encodeZipTimestamp(date) {
1303
+ if (!(date instanceof Date) || !Number.isFinite(date.getTime()) || date.getUTCFullYear() < 1980 || date.getUTCFullYear() > 2107)
1304
+ throw new RangeError("ZIP timestamp must be a valid UTC date in 1980\u20132107");
1305
+ const time = date.getUTCHours() << 11 | date.getUTCMinutes() << 5 | Math.floor(date.getUTCSeconds() / 2);
1306
+ const day = date.getUTCFullYear() - 1980 << 9 | date.getUTCMonth() + 1 << 5 | date.getUTCDate();
1307
+ return (day << 16 | time) >>> 0;
1308
+ }
1309
+ function getZipVersion(entry) {
1310
+ return entry.zip64 ? 45 : entry.method === 8 || entry.flags & 8 ? 20 : 10;
1311
+ }
1312
+ function validateHeaderEntry(entry) {
1313
+ var _a;
1314
+ if (!entry.nameBytes.length || entry.nameBytes.length > 65535 || (((_a = entry.commentBytes) == null ? void 0 : _a.length) ?? 0) > 65535)
1315
+ throw new RangeError("ZIP name/comment exceeds header capacity");
1316
+ for (const value of [entry.size, entry.compressedSize, entry.localHeaderOffset])
1317
+ validateUint64(value);
1318
+ if (!entry.zip64 && [entry.size, entry.compressedSize, entry.localHeaderOffset].some(
1319
+ (value) => value >= ZIP32_SENTINEL
1320
+ ))
1321
+ throw new RangeError("ZIP32 entry capacity exceeded");
1322
+ }
1323
+ function validateUint64(value) {
1324
+ if (typeof value !== "bigint" || value < 0n || value > 0xffffffffffffffffn)
1325
+ throw new RangeError("ZIP64 unsigned integer capacity exceeded");
1326
+ }
1327
+ var ZIP32_SENTINEL;
1328
+ var init_zip_serialization = __esm({
1329
+ "src/zip/lib/zip-serialization.ts"() {
1330
+ "use strict";
1331
+ ZIP32_SENTINEL = 0xffffffffn;
1332
+ }
1333
+ });
1334
+
1335
+ // src/zip/zip-archive.ts
1336
+ async function openZipArchive(input, options = {}) {
1337
+ return await ZipArchive.open(input, options);
1338
+ }
1339
+ function normalizeZipInput(input) {
1340
+ if (input instanceof ArrayBuffer) return new BlobFile(input);
1341
+ if (ArrayBuffer.isView(input))
1342
+ return new BlobFile(
1343
+ new Blob([new Uint8Array(input.buffer, input.byteOffset, input.byteLength).slice()])
1344
+ );
1345
+ if (input instanceof Blob) return new BlobFile(input);
1346
+ return input;
1347
+ }
1348
+ function minimumBigInt(left, right) {
1349
+ return left < right ? left : right;
1350
+ }
1351
+ var DEFAULT_OPTIONS, ZipArchive;
1352
+ var init_zip_archive = __esm({
1353
+ "src/zip/zip-archive.ts"() {
1354
+ "use strict";
1355
+ init_loader_utils();
1356
+ init_deflate_decompressor();
1357
+ init_src();
1358
+ init_zip_entry_metadata();
1359
+ init_zip_serialization();
1360
+ DEFAULT_OPTIONS = {
1361
+ maxArchiveBytes: 1024n ** 4n,
1362
+ maxDirectoryBytes: 32 * 1024 * 1024,
1363
+ maxEntries: 1e5,
1364
+ maxReadBytes: 1024 * 1024,
1365
+ maxCompressedBytes: 64n * 1024n * 1024n,
1366
+ maxDecodedBytes: 64n * 1024n * 1024n,
1367
+ chunkBytes: 64 * 1024
1368
+ };
1369
+ ZipArchive = class _ZipArchive {
1370
+ /** Archive byte length, without losing ZIP64 precision. */
1371
+ size;
1372
+ /** Archive comment, decoded using legacy ZIP CP437. */
1373
+ comment;
1374
+ /** Shared file limits captured at open time. */
1375
+ limits;
1376
+ /** Owned random-access transport. */
1377
+ file;
1378
+ /** File lifetime, including in-flight operations. */
1379
+ controller = new AbortController();
1380
+ /** Initialization/caller cancellation combined with close. */
1381
+ signal;
1382
+ /** Validated directory boundary. */
1383
+ directory;
1384
+ /** A single directory-index promise shared by concurrent lookups. */
1385
+ directoryPromise;
1386
+ /** Local-header validation shared by repeated path reads. */
1387
+ entriesByOffset = /* @__PURE__ */ new Map();
1388
+ /** Central-validated named lookups share their local-header work. */
1389
+ entriesByPath = /* @__PURE__ */ new Map();
1390
+ /** Next local-header boundary for central-validated, nonoverlapping payloads. */
1391
+ nextOffsets = /* @__PURE__ */ new Map();
1392
+ /** Only entries issued by this archive can be used for reads. */
1393
+ issuedEntries = /* @__PURE__ */ new WeakSet();
1394
+ /** Idempotent file cleanup, including open failure. */
1395
+ closePromise;
1396
+ /** Captures the owned transport and validates independent limits. */
1397
+ constructor(file, size, options) {
1398
+ this.file = file;
1399
+ this.size = size;
1400
+ this.comment = "";
1401
+ this.limits = {
1402
+ maxArchiveBytes: options.maxArchiveBytes ?? DEFAULT_OPTIONS.maxArchiveBytes,
1403
+ maxDirectoryBytes: options.maxDirectoryBytes ?? DEFAULT_OPTIONS.maxDirectoryBytes,
1404
+ maxEntries: options.maxEntries ?? DEFAULT_OPTIONS.maxEntries,
1405
+ maxReadBytes: options.maxReadBytes ?? DEFAULT_OPTIONS.maxReadBytes,
1406
+ maxCompressedBytes: options.maxCompressedBytes ?? DEFAULT_OPTIONS.maxCompressedBytes,
1407
+ maxDecodedBytes: options.maxDecodedBytes ?? DEFAULT_OPTIONS.maxDecodedBytes,
1408
+ chunkBytes: options.chunkBytes ?? DEFAULT_OPTIONS.chunkBytes
1409
+ };
1410
+ for (const [name, value] of Object.entries(this.limits)) {
1411
+ const bigintLimit = ["maxArchiveBytes", "maxCompressedBytes", "maxDecodedBytes"].includes(
1412
+ name
1413
+ );
1414
+ if (bigintLimit ? typeof value !== "bigint" || value < 0n : typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)
1415
+ throw new RangeError(`Invalid ZIP ${name} limit`);
1416
+ }
1417
+ this.signal = options.signal ? AbortSignal.any([this.controller.signal, options.signal]) : this.controller.signal;
1418
+ }
1419
+ /** Initializes directory bounds without scanning entries or reading their payloads. */
1420
+ static async open(input, options = {}) {
1421
+ var _a;
1422
+ const file = normalizeZipInput(input);
1423
+ let archive;
1424
+ try {
1425
+ const advertisedSize = file.bigsize;
1426
+ const status = advertisedSize === void 0 || advertisedSize === 0n ? await ((_a = file.stat) == null ? void 0 : _a.call(file)) : void 0;
1427
+ const reportedBigsize = (status == null ? void 0 : status.bigsize) ?? file.bigsize;
1428
+ const size = reportedBigsize !== void 0 && reportedBigsize !== 0n ? reportedBigsize : BigInt((status == null ? void 0 : status.size) || file.size);
1429
+ archive = new _ZipArchive(file, size, options);
1430
+ archive.signal.throwIfAborted();
1431
+ if (size < 22n || size > archive.limits.maxArchiveBytes)
1432
+ throw new RangeError("ZIP archive size limit or minimum header size");
1433
+ archive.directory = await archive.readDirectoryLocation();
1434
+ Object.defineProperty(archive, "comment", { value: archive.directory.comment });
1435
+ return archive;
1436
+ } catch (error) {
1437
+ if (archive) await archive.close();
1438
+ else await file.close();
1439
+ throw error;
1440
+ }
1441
+ }
1442
+ /**
1443
+ * Appends one STORE entry through validated container metadata and the native serializer.
1444
+ * Internal composition operation: callers own the writable file and discard it on write failure.
1445
+ * Existing payload offsets, central metadata and archive comments are retained.
1446
+ */
1447
+ static async appendEntry(file, path, data, options = {}) {
1448
+ const archive = await _ZipArchive.open(file, options);
1449
+ try {
1450
+ validateZipPath(path);
1451
+ if (archive.directory.offset > BigInt(Number.MAX_SAFE_INTEGER))
1452
+ throw new RangeError("ZIP append transport offset exceeds safe integer range");
1453
+ if (await archive.getEntry(path)) throw new Error("ZIP entry already exists");
1454
+ for await (const _entry of archive.entries()) {
1455
+ }
1456
+ const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
1457
+ if (path.endsWith("/") && bytes.length)
1458
+ throw new Error("ZIP directory payload must be empty");
1459
+ const entry = {
1460
+ nameBytes: encodeUtf8Text(path),
1461
+ date: /* @__PURE__ */ new Date("1980-01-01T00:00:00Z"),
1462
+ flags: 2048,
1463
+ method: 0,
1464
+ crc32: 0,
1465
+ size: BigInt(bytes.length),
1466
+ compressedSize: BigInt(bytes.length),
1467
+ localHeaderOffset: archive.directory.offset,
1468
+ zip64: archive.directory.offset >= 0xffffffffn || bytes.length >= 4294967295
1469
+ };
1470
+ let local = encodeZipLocalHeader(entry);
1471
+ let central = encodeZipCentralHeader(entry);
1472
+ const directoryBytes = archive.directory.size + BigInt(central.length);
1473
+ const directoryOffset = archive.directory.offset + BigInt(local.length + bytes.length);
1474
+ const count = archive.directory.count + 1n;
1475
+ const comment = new Uint8Array(
1476
+ await archive.readExact(
1477
+ archive.size - BigInt(archive.comment.length),
1478
+ archive.comment.length
1479
+ )
1480
+ );
1481
+ const footer = encodeZipEndRecords(
1482
+ count,
1483
+ directoryBytes,
1484
+ directoryOffset,
1485
+ directoryOffset + directoryBytes > 0x7fffffffn || count >= 0xffffn,
1486
+ comment
1487
+ );
1488
+ if (count > BigInt(archive.limits.maxEntries) || directoryBytes > BigInt(archive.limits.maxDirectoryBytes) || directoryOffset + directoryBytes + BigInt(footer.length) > archive.limits.maxArchiveBytes)
1489
+ throw new RangeError("ZIP append metadata/archive limit exceeded");
1490
+ entry.crc32 = calculateZipChecksum(bytes);
1491
+ local = encodeZipLocalHeader(entry);
1492
+ central = encodeZipCentralHeader(entry);
1493
+ const directory = new Uint8Array(
1494
+ await archive.readExact(archive.directory.offset, Number(archive.directory.size))
1495
+ );
1496
+ archive.signal.throwIfAborted();
1497
+ await file.truncate(Number(archive.directory.offset));
1498
+ for (const chunk of [local, bytes, directory, central, footer]) {
1499
+ archive.signal.throwIfAborted();
1500
+ await file.append(chunk);
1501
+ }
1502
+ archive.signal.throwIfAborted();
1503
+ } finally {
1504
+ await archive.close();
1505
+ }
1506
+ }
1507
+ /** Enumerates validated entries in central-directory order; metadata is indexed once. */
1508
+ async *entries() {
1509
+ for (const path of (await this.getDirectory()).keys()) yield await this.getEntry(path);
1510
+ }
1511
+ /**
1512
+ * Reads the final central entry using at most one maximum-sized header from the directory tail.
1513
+ * Ambiguous header signatures in comments fall back to the cached directory. This supports
1514
+ * final-index discovery without scanning a large directory in the normal indexed profile.
1515
+ */
1516
+ async getLastEntry() {
1517
+ this.signal.throwIfAborted();
1518
+ if (!this.directory.count) return void 0;
1519
+ const length = Number(minimumBigInt(this.directory.size, 46n + 3n * 65535n));
1520
+ const bytes = new Uint8Array(
1521
+ await this.readExact(this.directory.offset + this.directory.size - BigInt(length), length)
1522
+ );
1523
+ const view = new DataView(bytes.buffer);
1524
+ const positions = [];
1525
+ for (let position = 0; position + 46 <= length; position++) {
1526
+ if (view.getUint32(position, true) !== 33639248) continue;
1527
+ const end = position + 46 + view.getUint16(position + 28, true) + view.getUint16(position + 30, true) + view.getUint16(position + 32, true);
1528
+ if (end === length) positions.push(position);
1529
+ }
1530
+ if (positions.length !== 1) {
1531
+ const headers = [...(await this.getDirectory()).values()];
1532
+ return await this.getEntry(headers[headers.length - 1].path);
1533
+ }
1534
+ const metadata3 = decodeZipHeader(bytes.subarray(positions[0]), true);
1535
+ return await this.getValidatedEntry(metadata3.localHeaderOffset, metadata3);
1536
+ }
1537
+ /** Looks up a canonical path; returns undefined when the entry is absent. */
1538
+ async getEntry(path) {
1539
+ this.signal.throwIfAborted();
1540
+ const metadata3 = (await this.getDirectory()).get(path);
1541
+ if (!metadata3) return void 0;
1542
+ let promise = this.entriesByPath.get(path);
1543
+ if (!promise) {
1544
+ promise = this.getValidatedEntry(metadata3.localHeaderOffset, metadata3).catch((error) => {
1545
+ this.entriesByPath.delete(path);
1546
+ throw error;
1547
+ });
1548
+ this.entriesByPath.set(path, promise);
1549
+ }
1550
+ return await promise;
1551
+ }
1552
+ /**
1553
+ * Validates a populated local header at an index-provided offset without a directory scan.
1554
+ * Descriptor entries fall back to the shared directory because their local sizes may be zero.
1555
+ * Direct access validates local layout/bounds; central consistency requires named lookup.
1556
+ */
1557
+ async getEntryAt(localHeaderOffset) {
1558
+ this.signal.throwIfAborted();
1559
+ const existing = this.entriesByOffset.get(localHeaderOffset);
1560
+ if (existing) return await existing;
1561
+ const metadata3 = await this.readLocalHeader(localHeaderOffset);
1562
+ if (metadata3.header.flags & 8) {
1563
+ for (const header of (await this.getDirectory()).values())
1564
+ if (header.localHeaderOffset === localHeaderOffset)
1565
+ return await this.getEntry(header.path);
1566
+ throw new Error("Invalid ZIP archive: indexed offset missing from directory");
1567
+ }
1568
+ return await this.getValidatedEntry(localHeaderOffset, void 0, metadata3);
1569
+ }
1570
+ /** Reads one complete entry and verifies its decoded size and CRC-32. */
1571
+ async read(entryOrPath, options = {}) {
1572
+ const signal = this.getReadSignal(options);
1573
+ signal.throwIfAborted();
1574
+ const entry = await this.resolveEntry(entryOrPath);
1575
+ signal.throwIfAborted();
1576
+ this.checkEntryBudget(entry);
1577
+ if (entry.size > BigInt(Number.MAX_SAFE_INTEGER))
1578
+ throw new RangeError("ZIP allocation is not safely representable");
1579
+ const output = new Uint8Array(Number(entry.size));
1580
+ let offset = 0;
1581
+ for await (const chunk of this.readInBatches(entry, options)) {
1582
+ output.set(chunk, offset);
1583
+ offset += chunk.byteLength;
1584
+ }
1585
+ return output.buffer;
1586
+ }
1587
+ /** Streams decoded chunks with backpressure; consuming through completion verifies CRC-32. */
1588
+ async *readInBatches(entryOrPath, options = {}) {
1589
+ const signal = this.getReadSignal(options);
1590
+ signal.throwIfAborted();
1591
+ const entry = await this.resolveEntry(entryOrPath);
1592
+ signal.throwIfAborted();
1593
+ this.checkEntryBudget(entry);
1594
+ let decodedBytes = 0n;
1595
+ let checksum = 0;
1596
+ const hash = new CRC32Hash({
1597
+ crypto: {
1598
+ onEnd: (result) => {
1599
+ checksum = Number.parseInt(result.hash, 16);
1600
+ }
1601
+ }
1602
+ });
1603
+ const compressed = this.readPayloadChunks(entry, signal);
1604
+ const decoded = entry.compression === "store" ? compressed : new DeflateDecompressor({ raw: true }).decompressBatches(compressed);
1605
+ for await (const chunk of hash.hashBatches(decoded, "hex")) {
1606
+ signal.throwIfAborted();
1607
+ decodedBytes += BigInt(chunk.byteLength);
1608
+ if (decodedBytes > entry.size || decodedBytes > this.limits.maxDecodedBytes)
1609
+ throw new RangeError("ZIP decoded entry size limit exceeded");
1610
+ yield new Uint8Array(chunk);
1611
+ }
1612
+ signal.throwIfAborted();
1613
+ if (decodedBytes !== entry.size) throw new Error("Invalid ZIP archive: decoded size mismatch");
1614
+ if (checksum !== entry.crc32) throw new Error("Invalid ZIP archive: CRC-32 mismatch");
1615
+ }
1616
+ /** Reads only a STORE byte range. Partial reads cannot verify a whole-entry CRC. */
1617
+ async readRange(entryOrPath, options) {
1618
+ const signal = this.getReadSignal(options);
1619
+ signal.throwIfAborted();
1620
+ const entry = await this.resolveEntry(entryOrPath);
1621
+ if (entry.compression !== "store") throw new Error("ZIP ranges require STORE entries");
1622
+ if (options.start < 0n || options.end < options.start || options.end > entry.size || options.end - options.start > BigInt(this.limits.maxReadBytes))
1623
+ throw new RangeError("ZIP byte-range limit exceeded");
1624
+ return await this.readExact(
1625
+ entry.dataOffset + options.start,
1626
+ Number(options.end - options.start),
1627
+ signal
1628
+ );
1629
+ }
1630
+ /** Cancels reads and closes the owned transport exactly once; all subsequent reads reject. */
1631
+ close() {
1632
+ this.controller.abort(new Error("ZIP archive is closed"));
1633
+ this.closePromise ||= this.file.close();
1634
+ return this.closePromise;
1635
+ }
1636
+ /** Resolves a named entry or rejects metadata not issued by this archive. */
1637
+ async resolveEntry(entryOrPath) {
1638
+ this.signal.throwIfAborted();
1639
+ const entry = typeof entryOrPath === "string" ? await this.getEntry(entryOrPath) : entryOrPath;
1640
+ if (!entry || !this.issuedEntries.has(entry))
1641
+ throw new Error("ZIP entry not found or belongs to another archive");
1642
+ return entry;
1643
+ }
1644
+ /** Combines per-read cancellation with the owned lifetime. */
1645
+ getReadSignal(options) {
1646
+ return options.signal ? AbortSignal.any([this.signal, options.signal]) : this.signal;
1647
+ }
1648
+ /** Checks whole-entry consumption before allocation or decompression. */
1649
+ checkEntryBudget(entry) {
1650
+ if (entry.size > this.limits.maxDecodedBytes || entry.compressedSize > this.limits.maxCompressedBytes)
1651
+ throw new RangeError("ZIP entry compressed/decoded byte limit exceeded");
1652
+ }
1653
+ /** Yields compressed bytes without retaining a complete entry. */
1654
+ async *readPayloadChunks(entry, signal) {
1655
+ const chunkBytes = Math.min(this.limits.chunkBytes, this.limits.maxReadBytes);
1656
+ for (let offset = 0n; offset < entry.compressedSize; offset += BigInt(chunkBytes)) {
1657
+ const length = Number(minimumBigInt(BigInt(chunkBytes), entry.compressedSize - offset));
1658
+ yield await this.readExact(entry.dataOffset + offset, length, signal);
1659
+ }
1660
+ }
1661
+ /** Performs exact, bounded physical reads and rejects truncated transports. */
1662
+ async readExact(offset, length, signal = this.signal) {
1663
+ signal.throwIfAborted();
1664
+ if (offset < 0n || !Number.isSafeInteger(length) || length < 0 || offset + BigInt(length) > this.size)
1665
+ throw new Error("Invalid ZIP archive: read outside file");
1666
+ const output = new Uint8Array(length);
1667
+ for (let copied = 0; copied < length; ) {
1668
+ const readBytes = Math.min(length - copied, this.limits.maxReadBytes);
1669
+ const bytes = await this.file.read(offset + BigInt(copied), readBytes, signal);
1670
+ signal.throwIfAborted();
1671
+ if (bytes.byteLength !== readBytes)
1672
+ throw new Error("Invalid ZIP archive: truncated file read");
1673
+ output.set(new Uint8Array(bytes), copied);
1674
+ copied += readBytes;
1675
+ }
1676
+ return output.buffer;
1677
+ }
1678
+ /** Finds an EOCD whose complete comment ends at EOF, not a signature embedded in the comment. */
1679
+ async readDirectoryLocation() {
1680
+ const magic = new DataView(await this.readExact(0n, 4)).getUint32(0, true);
1681
+ if (magic !== 67324752 && magic !== 101010256 && magic !== 101075792)
1682
+ throw new Error("Unsupported ZIP prefix or archive format");
1683
+ const tailLength = Number(minimumBigInt(this.size, 65557n));
1684
+ const tailStart = this.size - BigInt(tailLength);
1685
+ const tail = new DataView(await this.readExact(tailStart, tailLength));
1686
+ let position = -1;
1687
+ for (let candidate = tailLength - 22; candidate >= 0; candidate--) {
1688
+ if (tail.getUint32(candidate, true) !== 101010256 || candidate + 22 + tail.getUint16(candidate + 20, true) !== tailLength)
1689
+ continue;
1690
+ if (position < 0) position = candidate;
1691
+ const emptyDirectoryAtEnd = tail.getUint32(candidate + 12, true) === 0 && BigInt(tail.getUint32(candidate + 16, true)) === tailStart + BigInt(candidate);
1692
+ if (tail.getUint16(candidate + 10, true) !== 0 || emptyDirectoryAtEnd || magic === 101075792) {
1693
+ position = candidate;
1694
+ break;
1695
+ }
1696
+ }
1697
+ if (position < 0) throw new Error("Invalid ZIP archive: end record not found");
1698
+ const disk = tail.getUint16(position + 4, true);
1699
+ const directoryDisk = tail.getUint16(position + 6, true);
1700
+ if (disk !== 0 && disk !== 65535 || directoryDisk !== 0 && directoryDisk !== 65535)
1701
+ throw new Error("Unsupported split ZIP archive");
1702
+ const onDisk = BigInt(tail.getUint16(position + 8, true));
1703
+ let count = BigInt(tail.getUint16(position + 10, true));
1704
+ let size = BigInt(tail.getUint32(position + 12, true));
1705
+ let offset = BigInt(tail.getUint32(position + 16, true));
1706
+ let footerOffset = tailStart + BigInt(position);
1707
+ let zip64 = false;
1708
+ if (footerOffset >= 20n) {
1709
+ const locator = new DataView(await this.readExact(footerOffset - 20n, 20));
1710
+ const locatorInsideDirectory = size !== 0xffffffffn && offset !== 0xffffffffn && offset + size > footerOffset - 20n;
1711
+ if (locator.getUint32(0, true) === 117853008 && !locatorInsideDirectory) {
1712
+ zip64 = true;
1713
+ if (locator.getUint32(4, true) || locator.getUint32(16, true) !== 1)
1714
+ throw new Error("Unsupported split ZIP64 archive");
1715
+ const zip64Offset = locator.getBigUint64(8, true);
1716
+ const record = new DataView(await this.readExact(zip64Offset, 56));
1717
+ if (record.getUint32(0, true) !== 101075792 || record.getBigUint64(4, true) < 44n || zip64Offset + 12n + record.getBigUint64(4, true) !== footerOffset - 20n || record.getUint32(16, true) || record.getUint32(20, true) || record.getBigUint64(24, true) !== record.getBigUint64(32, true))
1718
+ throw new Error("Invalid ZIP64 end record");
1719
+ const zip64Count = record.getBigUint64(32, true);
1720
+ const zip64Size = record.getBigUint64(40, true);
1721
+ const zip64DirectoryOffset = record.getBigUint64(48, true);
1722
+ if (onDisk !== 0xffffn && onDisk !== zip64Count || count !== 0xffffn && count !== zip64Count || size !== 0xffffffffn && size !== zip64Size || offset !== 0xffffffffn && offset !== zip64DirectoryOffset)
1723
+ throw new Error("Invalid ZIP64 legacy end values");
1724
+ count = zip64Count;
1725
+ size = zip64Size;
1726
+ offset = zip64DirectoryOffset;
1727
+ footerOffset = zip64Offset;
1728
+ } else if (size === 0xffffffffn || offset === 0xffffffffn)
1729
+ throw new Error("Invalid ZIP archive: ZIP64 locator missing");
1730
+ } else if (size === 0xffffffffn || offset === 0xffffffffn)
1731
+ throw new Error("Invalid ZIP archive: ZIP64 locator missing");
1732
+ if (!zip64) {
1733
+ if (disk === 65535 || directoryDisk === 65535)
1734
+ throw new Error("Invalid ZIP archive: ZIP64 locator missing");
1735
+ if (onDisk !== count) throw new Error("Invalid ZIP archive: inconsistent entry counts");
1736
+ }
1737
+ if (count > BigInt(this.limits.maxEntries) || size > BigInt(this.limits.maxDirectoryBytes))
1738
+ throw new RangeError("ZIP directory entry/byte limit exceeded");
1739
+ if (offset + size > footerOffset || size < count * 46n || count === 0n !== (size === 0n))
1740
+ throw new Error("Invalid ZIP archive: directory outside bounds");
1741
+ if (count && new DataView(await this.readExact(offset, 4)).getUint32(0, true) !== 33639248)
1742
+ throw new Error("Invalid ZIP archive: directory signature missing");
1743
+ const comment = decodeZipText(new Uint8Array(tail.buffer, position + 22), false);
1744
+ return { count, size, offset, comment };
1745
+ }
1746
+ /** Indexes central metadata once, without eagerly reading every local header. */
1747
+ getDirectory() {
1748
+ this.signal.throwIfAborted();
1749
+ this.directoryPromise ||= this.readDirectory().catch((error) => {
1750
+ this.directoryPromise = void 0;
1751
+ this.nextOffsets.clear();
1752
+ throw error;
1753
+ });
1754
+ return this.directoryPromise;
1755
+ }
1756
+ /** Parses exact directory records, including comments and Unicode/ZIP64 extras. */
1757
+ async readDirectory() {
1758
+ const bytes = new Uint8Array(
1759
+ await this.readExact(this.directory.offset, Number(this.directory.size))
1760
+ );
1761
+ const view = new DataView(bytes.buffer);
1762
+ const entries = /* @__PURE__ */ new Map();
1763
+ const offsets = /* @__PURE__ */ new Set();
1764
+ let position = 0;
1765
+ for (let index = 0n; index < this.directory.count; index++) {
1766
+ if (position + 46 > bytes.byteLength)
1767
+ throw new Error("Invalid ZIP archive: truncated directory");
1768
+ const length = 46 + view.getUint16(position + 28, true) + view.getUint16(position + 30, true) + view.getUint16(position + 32, true);
1769
+ const header = decodeZipHeader(bytes.subarray(position, position + length), true);
1770
+ if (header.localHeaderOffset + 30n > this.directory.offset)
1771
+ throw new Error("Invalid ZIP archive: local header outside data region");
1772
+ if (entries.has(header.path) || offsets.has(header.localHeaderOffset))
1773
+ throw new Error("Invalid ZIP archive: duplicate path or local-header offset");
1774
+ entries.set(header.path, header);
1775
+ offsets.add(header.localHeaderOffset);
1776
+ position += length;
1777
+ }
1778
+ const sortedOffsets = [...offsets].sort(
1779
+ (left, right) => left < right ? -1 : left > right ? 1 : 0
1780
+ );
1781
+ sortedOffsets.forEach(
1782
+ (offset, index) => this.nextOffsets.set(offset, sortedOffsets[index + 1] ?? this.directory.offset)
1783
+ );
1784
+ if (position !== bytes.byteLength)
1785
+ throw new Error("Invalid ZIP archive: directory length mismatch");
1786
+ return entries;
1787
+ }
1788
+ /** Reads local metadata without inspecting unrelated payloads. */
1789
+ async readLocalHeader(offset) {
1790
+ if (offset < 0n || offset + 30n > this.directory.offset)
1791
+ throw new Error("Invalid ZIP archive: local header outside data region");
1792
+ const fixed = new DataView(await this.readExact(offset, 30));
1793
+ const length = 30 + fixed.getUint16(26, true) + fixed.getUint16(28, true);
1794
+ if (offset + BigInt(length) > this.directory.offset)
1795
+ throw new Error("Invalid ZIP archive: local metadata overlaps directory");
1796
+ const bytes = new Uint8Array(length);
1797
+ bytes.set(new Uint8Array(fixed.buffer));
1798
+ bytes.set(new Uint8Array(await this.readExact(offset + 30n, length - 30)), 30);
1799
+ const header = decodeZipHeader(bytes, false);
1800
+ return { header, dataOffset: offset + BigInt(length) };
1801
+ }
1802
+ /** Shares local validation; a later named lookup additionally verifies central metadata. */
1803
+ async getValidatedEntry(offset, central, localMetadata) {
1804
+ if (central) return await this.validateEntry(offset, central);
1805
+ let entry = this.entriesByOffset.get(offset);
1806
+ if (!entry) {
1807
+ entry = this.validateEntry(offset, void 0, localMetadata).catch((error) => {
1808
+ this.entriesByOffset.delete(offset);
1809
+ throw error;
1810
+ });
1811
+ this.entriesByOffset.set(offset, entry);
1812
+ }
1813
+ return await entry;
1814
+ }
1815
+ /** Validates local/central identity, payload bounds and signed or unsigned descriptors. */
1816
+ async validateEntry(offset, central, localMetadata) {
1817
+ const { header: local, dataOffset } = localMetadata ?? await this.readLocalHeader(offset);
1818
+ const metadata3 = central || local;
1819
+ const descriptor = Boolean(local.flags & 8);
1820
+ if (central && (central.flags !== local.flags || central.method !== local.method || central.nameBytes.length !== local.nameBytes.length || central.nameBytes.some((value, index) => value !== local.nameBytes[index]) || !descriptor && (central.crc32 !== local.crc32 || central.size !== local.size || central.compressedSize !== local.compressedSize)))
1821
+ throw new Error("Invalid ZIP archive: local/central metadata mismatch");
1822
+ if (metadata3.method === 0 && metadata3.size !== metadata3.compressedSize)
1823
+ throw new Error("Invalid ZIP archive: STORE sizes mismatch");
1824
+ if (central && descriptor && (local.crc32 !== 0 && local.crc32 !== central.crc32 || local.size !== 0n && local.size !== central.size || local.compressedSize !== 0n && local.compressedSize !== central.compressedSize))
1825
+ throw new Error("Invalid ZIP archive: descriptor local/central metadata mismatch");
1826
+ const payloadEnd = dataOffset + metadata3.compressedSize;
1827
+ const entryEnd = central ? this.nextOffsets.get(offset) ?? this.directory.offset : this.directory.offset;
1828
+ if (payloadEnd > entryEnd) throw new Error("Invalid ZIP archive: payload overlaps directory");
1829
+ if (descriptor)
1830
+ await this.validateDescriptor(
1831
+ payloadEnd,
1832
+ metadata3,
1833
+ local.zip64 || Boolean(central == null ? void 0 : central.zip64),
1834
+ entryEnd
1835
+ );
1836
+ const entry = Object.freeze({
1837
+ path: metadata3.path,
1838
+ directory: metadata3.path.endsWith("/"),
1839
+ compression: metadata3.method === 0 ? "store" : "deflate",
1840
+ size: metadata3.size,
1841
+ compressedSize: metadata3.compressedSize,
1842
+ crc32: metadata3.crc32,
1843
+ localHeaderOffset: offset,
1844
+ dataOffset,
1845
+ comment: (central == null ? void 0 : central.comment) || ""
1846
+ });
1847
+ this.issuedEntries.add(entry);
1848
+ return entry;
1849
+ }
1850
+ /** Resolves the optional descriptor signature using the expected CRC and sizes. */
1851
+ async validateDescriptor(offset, metadata3, zip64, entryEnd) {
1852
+ const length = Number(minimumBigInt(24n, entryEnd - offset));
1853
+ const bytes = new DataView(await this.readExact(offset, length));
1854
+ for (const wide of zip64 ? [true, false] : [false, true]) {
1855
+ if (!wide && (metadata3.size > 0xffffffffn || metadata3.compressedSize > 0xffffffffn)) continue;
1856
+ const descriptorLength = wide ? 20 : 12;
1857
+ for (const prefix of [4, 0]) {
1858
+ if (length < prefix + descriptorLength || prefix && bytes.getUint32(0, true) !== 134695760)
1859
+ continue;
1860
+ const compressed = wide ? bytes.getBigUint64(prefix + 4, true) : BigInt(bytes.getUint32(prefix + 4, true));
1861
+ const decoded = wide ? bytes.getBigUint64(prefix + 12, true) : BigInt(bytes.getUint32(prefix + 8, true));
1862
+ if (bytes.getUint32(prefix, true) === metadata3.crc32 && compressed === metadata3.compressedSize && decoded === metadata3.size)
1863
+ return;
1864
+ }
1865
+ }
1866
+ throw new Error("Invalid ZIP archive: data descriptor mismatch");
1867
+ }
1868
+ };
1869
+ }
1870
+ });
1871
+
1872
+ // src/zip/zip-loader.ts
1873
+ var zip_loader_exports = {};
1874
+ __export(zip_loader_exports, {
1875
+ ZipLoaderWithParser: () => ZipLoaderWithParser
1876
+ });
1877
+ async function parseZip(input, options = {}) {
1878
+ var _a;
1879
+ const maximum = ((_a = options.zip) == null ? void 0 : _a.maxTotalDecodedBytes) ?? ZipLoader.options.zip.maxTotalDecodedBytes;
1880
+ if (typeof maximum !== "bigint" || maximum < 0n)
1881
+ throw new RangeError("Invalid ZIP total decoded-byte limit");
1882
+ const archive = await openZipArchive(input, options.zip);
1883
+ try {
1884
+ const entries = [];
1885
+ let totalBytes = 0n;
1886
+ for await (const entry of archive.entries()) {
1887
+ if (entry.directory) continue;
1888
+ totalBytes += entry.size;
1889
+ if (totalBytes > maximum) throw new RangeError("ZIP total decoded-byte limit exceeded");
1890
+ entries.push(entry);
1891
+ }
1892
+ const files = /* @__PURE__ */ Object.create(null);
1893
+ for (const entry of entries) files[entry.path] = await archive.read(entry);
1894
+ return files;
1895
+ } finally {
1896
+ await archive.close();
1897
+ }
1898
+ }
1899
+ var _preload, metadata, ZipLoaderWithParser;
1900
+ var init_zip_loader = __esm({
1901
+ "src/zip/zip-loader.ts"() {
1902
+ "use strict";
1903
+ init_zip_loader_types();
1904
+ init_zip_archive();
1905
+ ({ preload: _preload, ...metadata } = ZipLoader);
1906
+ ZipLoaderWithParser = {
1907
+ ...metadata,
1908
+ parse: parseZip
1909
+ };
1910
+ }
1911
+ });
1912
+
1913
+ // src/tar/tar-format.ts
1914
+ var TarFormat2;
1915
+ var init_tar_format = __esm({
1916
+ "src/tar/tar-format.ts"() {
1917
+ "use strict";
1918
+ TarFormat2 = {
1919
+ name: "TAR Archive",
1920
+ id: "tar",
1921
+ module: "archives",
1922
+ format: "tar",
1923
+ extensions: ["tar"],
1924
+ mimeTypes: ["application/x-tar"],
1925
+ category: "archive",
1926
+ binary: true
1927
+ };
1928
+ }
1929
+ });
1930
+
1931
+ // src/tar/tar-loader-types.ts
1932
+ var VERSION4, TarLoader;
1933
+ var init_tar_loader_types = __esm({
1934
+ "src/tar/tar-loader-types.ts"() {
1935
+ "use strict";
1936
+ init_tar_format();
1937
+ VERSION4 = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
1938
+ TarLoader = {
1939
+ ...TarFormat2,
1940
+ version: VERSION4,
1941
+ dataType: null,
1942
+ batchType: null,
1943
+ options: { tar: { maxEntries: 1e5, maxTotalDecodedBytes: 64 * 1024 * 1024 } },
1944
+ /** Loads the parser through the installed package subpath. */
1945
+ async preload() {
1946
+ const { TarLoaderWithParser: TarLoaderWithParser2 } = await Promise.resolve().then(() => (init_tar_loader(), tar_loader_exports));
1947
+ return TarLoaderWithParser2;
1948
+ }
1949
+ };
1950
+ }
1951
+ });
1952
+
1953
+ // src/tar/tar-archive.ts
1954
+ function readString(bytes) {
1955
+ const end = bytes.indexOf(0);
1956
+ return decoder.decode(end === -1 ? bytes : bytes.subarray(0, end));
1957
+ }
1958
+ function readOctal(bytes) {
1959
+ const value = readString(bytes).trim();
1960
+ if (!value || !/^[0-7]+$/.test(value)) throw new Error("Invalid TAR numeric field");
1961
+ const number = Number.parseInt(value, 8);
1962
+ if (!Number.isSafeInteger(number)) throw new RangeError("TAR numeric field exceeds safe range");
1963
+ return number;
1964
+ }
1965
+ function normalizePath(path, directory) {
1966
+ if (!path || path.startsWith("/") || path.includes("\\") || path.includes("\0") || /^[A-Za-z]:/.test(path)) {
1967
+ throw new Error(`Unsafe TAR path: ${path}`);
1968
+ }
1969
+ const components = path.split("/").filter((part) => part && part !== ".");
1970
+ if (components.includes("..")) throw new Error(`Unsafe TAR path: ${path}`);
1971
+ if (/^[A-Za-z]:/.test(components[0] ?? "")) throw new Error(`Unsafe TAR path: ${path}`);
1972
+ if (!components.length) {
1973
+ if (directory) return null;
1974
+ throw new Error(`Unsafe TAR path: ${path}`);
1975
+ }
1976
+ return components.join("/");
1977
+ }
1978
+ function readTarArchive(input, options = {}) {
1979
+ var _a, _b;
1980
+ const bytes = input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
1981
+ const maxEntries = ((_a = options.tar) == null ? void 0 : _a.maxEntries) ?? 1e5;
1982
+ const maxBytes = ((_b = options.tar) == null ? void 0 : _b.maxTotalDecodedBytes) ?? 64 * 1024 * 1024;
1983
+ if (!Number.isSafeInteger(maxEntries) || maxEntries < 0 || !Number.isSafeInteger(maxBytes) || maxBytes < 0) {
1984
+ throw new RangeError("Invalid TAR limits");
1985
+ }
1986
+ const files = /* @__PURE__ */ Object.create(null);
1987
+ let offset = 0;
1988
+ let entries = 0;
1989
+ let totalBytes = 0;
1990
+ while (offset + BLOCK_SIZE <= bytes.length) {
1991
+ const header = bytes.subarray(offset, offset + BLOCK_SIZE);
1992
+ if (header.every((byte) => byte === 0)) return files;
1993
+ const storedChecksum = readOctal(header.subarray(148, 156));
1994
+ let checksum = 0;
1995
+ for (let index = 0; index < BLOCK_SIZE; index++) {
1996
+ checksum += index >= 148 && index < 156 ? 32 : header[index];
1997
+ }
1998
+ if (checksum !== storedChecksum) throw new Error("Invalid TAR header checksum");
1999
+ if (++entries > maxEntries) throw new RangeError("TAR entry limit exceeded");
2000
+ const name = readString(header.subarray(0, 100));
2001
+ const prefix = readString(header.subarray(345, 500));
2002
+ const type = header[156];
2003
+ const path = normalizePath(prefix ? `${prefix}/${name}` : name, type === 53);
2004
+ const size = readOctal(header.subarray(124, 136));
2005
+ const dataOffset = offset + BLOCK_SIZE;
2006
+ if (size > bytes.length - dataOffset) throw new Error("Truncated TAR entry");
2007
+ if (type === 0 || type === 48) {
2008
+ totalBytes += size;
2009
+ if (totalBytes > maxBytes) throw new RangeError("TAR decoded-byte limit exceeded");
2010
+ if (path === null) throw new Error("Invalid TAR file path");
2011
+ if (Object.hasOwn(files, path)) throw new Error(`Duplicate TAR path: ${path}`);
2012
+ files[path] = bytes.slice(dataOffset, dataOffset + size).buffer;
2013
+ } else if (type !== 53) {
2014
+ throw new Error(`Unsupported TAR entry type: ${String.fromCharCode(type)}`);
2015
+ }
2016
+ offset = dataOffset + Math.ceil(size / BLOCK_SIZE) * BLOCK_SIZE;
2017
+ }
2018
+ throw new Error("Truncated TAR archive");
2019
+ }
2020
+ var BLOCK_SIZE, decoder;
2021
+ var init_tar_archive = __esm({
2022
+ "src/tar/tar-archive.ts"() {
2023
+ "use strict";
2024
+ BLOCK_SIZE = 512;
2025
+ decoder = new TextDecoder();
2026
+ }
2027
+ });
2028
+
2029
+ // src/tar/tar-loader.ts
2030
+ var tar_loader_exports = {};
2031
+ __export(tar_loader_exports, {
2032
+ TarLoaderWithParser: () => TarLoaderWithParser
2033
+ });
2034
+ var _preload2, metadata2, TarLoaderWithParser;
2035
+ var init_tar_loader = __esm({
2036
+ "src/tar/tar-loader.ts"() {
2037
+ "use strict";
2038
+ init_tar_loader_types();
2039
+ init_tar_archive();
2040
+ ({ preload: _preload2, ...metadata2 } = TarLoader);
2041
+ TarLoaderWithParser = {
2042
+ ...metadata2,
2043
+ parse: async (input, options) => readTarArchive(input, options)
2044
+ };
2045
+ }
2046
+ });
2047
+
2048
+ // dist/index.js
2049
+ var index_exports = {};
2050
+ __export(index_exports, {
2051
+ TarBuilder: () => TarBuilder,
2052
+ TarFormat: () => TarFormat,
2053
+ TarLoader: () => TarLoader2,
2054
+ TarWriter: () => TarWriter,
2055
+ ZipFormat: () => ZipFormat,
2056
+ ZipLoader: () => ZipLoader2,
2057
+ ZipWriter: () => ZipWriter
2058
+ });
2059
+ module.exports = __toCommonJS(index_exports);
2060
+
2061
+ // dist/zip/zip-format.js
2062
+ var ZipFormat = {
2063
+ name: "Zip Archive",
2064
+ id: "zip",
2065
+ module: "archives",
2066
+ encoding: "zip",
2067
+ format: "zip",
2068
+ extensions: ["zip"],
2069
+ mimeTypes: ["application/zip"],
2070
+ category: "archive",
2071
+ binary: true,
2072
+ tests: ["PK"]
2073
+ };
2074
+
2075
+ // dist/zip/zip-loader-types.js
2076
+ var VERSION2 = true ? "5.0.0-alpha.13" : "latest";
2077
+ var ZipLoader2 = {
2078
+ ...ZipFormat,
2079
+ version: VERSION2,
2080
+ dataType: null,
2081
+ batchType: null,
2082
+ options: { zip: { maxTotalDecodedBytes: 64n * 1024n * 1024n } },
2083
+ /** Loads the parser implementation through its installed package subpath. */
2084
+ async preload() {
2085
+ const { ZipLoaderWithParser: ZipLoaderWithParser2 } = await Promise.resolve().then(() => (init_zip_loader(), zip_loader_exports));
2086
+ return ZipLoaderWithParser2;
2087
+ }
2088
+ };
2089
+
2090
+ // ../compression/src/deflate-compressor-compress-utils.ts
2091
+ init_compress_utils_compression();
2092
+ var DeflateCompressUtilsCompressor = class extends CompressUtilsCompressor {
2093
+ constructor(options = {}) {
2094
+ super(
2095
+ { name: "deflate", contentEncodings: ["deflate"] },
2096
+ () => options.raw ? import("compress-utils/deflate/compress") : import("compress-utils/zlib/compress"),
2097
+ options
2098
+ );
2099
+ }
2100
+ };
2101
+
2102
+ // ../compression/src/lib/compression-stream.ts
2103
+ async function compressWithNativeCompressionStream(input, format2) {
2104
+ const outputBatches = compressBatchesWithNativeCompressionStream([input], format2);
2105
+ return outputBatches ? await concatenateBatches(outputBatches) : null;
2106
+ }
2107
+ function compressBatchesWithNativeCompressionStream(inputBatches, format2) {
2108
+ const compressionStream = createNativeCompressionStream(format2);
2109
+ return compressionStream ? transformBatches2(inputBatches, compressionStream) : null;
2110
+ }
2111
+ function createNativeCompressionStream(format2) {
2112
+ if (typeof globalThis.CompressionStream === "undefined") {
2113
+ return null;
2114
+ }
2115
+ try {
2116
+ const CompressionStreamConstructor = globalThis.CompressionStream;
2117
+ return new CompressionStreamConstructor(format2);
2118
+ } catch (error) {
2119
+ if (error instanceof TypeError || (error == null ? void 0 : error.name) === "TypeError") {
2120
+ return null;
2121
+ }
2122
+ throw error;
2123
+ }
2124
+ }
2125
+ async function* transformBatches2(inputBatches, compressionStream) {
2126
+ const writer = compressionStream.writable.getWriter();
2127
+ const reader = compressionStream.readable.getReader();
2128
+ const writePromise = writeBatches(inputBatches, writer);
2129
+ writePromise.catch(() => {
2130
+ });
2131
+ let outputCompleted = false;
2132
+ try {
2133
+ while (true) {
2134
+ const { done, value } = await reader.read();
2135
+ if (done) {
2136
+ outputCompleted = true;
2137
+ break;
2138
+ }
2139
+ yield new Uint8Array(value).buffer;
2140
+ }
2141
+ await writePromise;
2142
+ } finally {
2143
+ if (!outputCompleted) {
2144
+ await reader.cancel().catch(() => {
2145
+ });
2146
+ await writer.abort().catch(() => {
2147
+ });
2148
+ await writePromise.catch(() => {
2149
+ });
2150
+ }
2151
+ reader.releaseLock();
2152
+ }
2153
+ }
2154
+ async function writeBatches(inputBatches, writer) {
2155
+ try {
2156
+ for await (const inputBatch of inputBatches) {
2157
+ await writer.write(new Uint8Array(inputBatch));
2158
+ }
2159
+ await writer.close();
2160
+ } catch (error) {
2161
+ await writer.abort(error).catch(() => {
2162
+ });
2163
+ throw error;
2164
+ }
2165
+ }
2166
+ async function concatenateBatches(batches) {
2167
+ const output = [];
2168
+ let byteLength = 0;
2169
+ for await (const batch of batches) {
2170
+ const bytes = new Uint8Array(batch);
2171
+ output.push(bytes);
2172
+ byteLength += bytes.byteLength;
2173
+ }
2174
+ const result = new Uint8Array(byteLength);
2175
+ let offset = 0;
2176
+ for (const batch of output) {
2177
+ result.set(batch, offset);
2178
+ offset += batch.byteLength;
2179
+ }
2180
+ return result.buffer;
2181
+ }
2182
+
2183
+ // ../compression/src/deflate-compressor.ts
2184
+ var DeflateCompressor = class extends DeflateCompressUtilsCompressor {
2185
+ /** Compresses with native streams when available, otherwise lazily initializes WASM. */
2186
+ async compress(input) {
2187
+ if (this.options.useNative !== false && !this.options.raw) {
2188
+ const output = await compressWithNativeCompressionStream(input, "deflate");
2189
+ if (output) return output;
2190
+ }
2191
+ return super.compress(input);
2192
+ }
2193
+ /** Streams native batches when available, otherwise uses the WASM stream. */
2194
+ async *compressBatches(inputBatches) {
2195
+ if (this.options.useNative !== false && !this.options.raw) {
2196
+ const output = compressBatchesWithNativeCompressionStream(inputBatches, "deflate");
2197
+ if (output) {
2198
+ yield* output;
2199
+ return;
2200
+ }
2201
+ }
2202
+ yield* super.compressBatches(inputBatches);
2203
+ }
2204
+ };
2205
+
2206
+ // dist/zip/zip-encode.js
2207
+ init_src();
2208
+
2209
+ // dist/zip/lib/zip-entry-metadata.js
2210
+ var CP437_HIGH2 = "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0";
2211
+ function decodeZipText2(bytes, utf8) {
2212
+ if (utf8)
2213
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
2214
+ return Array.from(bytes, (value) => value < 128 ? String.fromCharCode(value) : CP437_HIGH2[value - 128]).join("");
2215
+ }
2216
+ function validateZipPath2(path) {
2217
+ const segments = path.endsWith("/") ? path.slice(0, -1).split("/") : path.split("/");
2218
+ if (!path || path.includes("\\") || path.includes("\0") || /^[A-Za-z]:/.test(path) || segments.some((segment) => !segment || segment === "." || segment === ".."))
2219
+ throw new Error("Invalid ZIP archive: noncanonical relative path");
2220
+ }
2221
+ function encodeUtf8Text2(value) {
2222
+ const bytes = new TextEncoder().encode(value);
2223
+ if (new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes) !== value)
2224
+ throw new TypeError("ZIP names and entry comments must be well-formed Unicode");
2225
+ return bytes;
2226
+ }
2227
+
2228
+ // dist/zip/lib/zip-serialization.js
2229
+ var ZIP32_SENTINEL2 = 0xffffffffn;
2230
+ function encodeZipLocalHeader2(entry) {
2231
+ validateHeaderEntry2(entry);
2232
+ const bytes = new Uint8Array(30 + entry.nameBytes.length + (entry.zip64 ? 20 : 0));
2233
+ const view = new DataView(bytes.buffer);
2234
+ view.setUint32(0, 67324752, true);
2235
+ view.setUint16(4, getZipVersion2(entry), true);
2236
+ view.setUint16(6, entry.flags, true);
2237
+ view.setUint16(8, entry.method, true);
2238
+ view.setUint32(10, encodeZipTimestamp2(entry.date), true);
2239
+ const descriptor = Boolean(entry.flags & 8);
2240
+ view.setUint32(14, descriptor ? 0 : entry.crc32, true);
2241
+ view.setUint32(18, entry.zip64 ? Number(ZIP32_SENTINEL2) : descriptor ? 0 : Number(entry.compressedSize), true);
2242
+ view.setUint32(22, entry.zip64 ? Number(ZIP32_SENTINEL2) : descriptor ? 0 : Number(entry.size), true);
2243
+ view.setUint16(26, entry.nameBytes.length, true);
2244
+ view.setUint16(28, entry.zip64 ? 20 : 0, true);
2245
+ bytes.set(entry.nameBytes, 30);
2246
+ if (entry.zip64) {
2247
+ const extraOffset = 30 + entry.nameBytes.length;
2248
+ view.setUint16(extraOffset, 1, true);
2249
+ view.setUint16(extraOffset + 2, 16, true);
2250
+ view.setBigUint64(extraOffset + 4, descriptor ? 0n : entry.size, true);
2251
+ view.setBigUint64(extraOffset + 12, descriptor ? 0n : entry.compressedSize, true);
2252
+ }
2253
+ return bytes;
2254
+ }
2255
+ function encodeZipCentralHeader2(entry) {
2256
+ validateHeaderEntry2(entry);
2257
+ const comment = entry.commentBytes ?? new Uint8Array();
2258
+ const extraBytes = entry.zip64 ? 28 : 0;
2259
+ const bytes = new Uint8Array(46 + entry.nameBytes.length + extraBytes + comment.length);
2260
+ const view = new DataView(bytes.buffer);
2261
+ view.setUint32(0, 33639248, true);
2262
+ view.setUint16(4, entry.zip64 ? 45 : 20, true);
2263
+ view.setUint16(6, getZipVersion2(entry), true);
2264
+ view.setUint16(8, entry.flags, true);
2265
+ view.setUint16(10, entry.method, true);
2266
+ view.setUint32(12, encodeZipTimestamp2(entry.date), true);
2267
+ view.setUint32(16, entry.crc32, true);
2268
+ view.setUint32(20, entry.zip64 ? Number(ZIP32_SENTINEL2) : Number(entry.compressedSize), true);
2269
+ view.setUint32(24, entry.zip64 ? Number(ZIP32_SENTINEL2) : Number(entry.size), true);
2270
+ view.setUint16(28, entry.nameBytes.length, true);
2271
+ view.setUint16(30, extraBytes, true);
2272
+ view.setUint16(32, comment.length, true);
2273
+ view.setUint32(38, entry.directory ? 16 : 0, true);
2274
+ view.setUint32(42, entry.zip64 ? Number(ZIP32_SENTINEL2) : Number(entry.localHeaderOffset), true);
2275
+ bytes.set(entry.nameBytes, 46);
2276
+ if (entry.zip64) {
2277
+ const extraOffset = 46 + entry.nameBytes.length;
2278
+ view.setUint16(extraOffset, 1, true);
2279
+ view.setUint16(extraOffset + 2, 24, true);
2280
+ view.setBigUint64(extraOffset + 4, entry.size, true);
2281
+ view.setBigUint64(extraOffset + 12, entry.compressedSize, true);
2282
+ view.setBigUint64(extraOffset + 20, entry.localHeaderOffset, true);
2283
+ }
2284
+ bytes.set(comment, 46 + entry.nameBytes.length + extraBytes);
2285
+ return bytes;
2286
+ }
2287
+ function encodeZipDescriptor(entry) {
2288
+ validateHeaderEntry2(entry);
2289
+ const bytes = new Uint8Array(entry.zip64 ? 24 : 16);
2290
+ const view = new DataView(bytes.buffer);
2291
+ view.setUint32(0, 134695760, true);
2292
+ view.setUint32(4, entry.crc32, true);
2293
+ if (entry.zip64) {
2294
+ view.setBigUint64(8, entry.compressedSize, true);
2295
+ view.setBigUint64(16, entry.size, true);
2296
+ } else {
2297
+ view.setUint32(8, Number(entry.compressedSize), true);
2298
+ view.setUint32(12, Number(entry.size), true);
2299
+ }
2300
+ return bytes;
2301
+ }
2302
+ function encodeZipEndRecords2(count, directorySize, directoryOffset, zip64, comment = new Uint8Array()) {
2303
+ for (const value of [count, directorySize, directoryOffset, directoryOffset + directorySize])
2304
+ validateUint642(value);
2305
+ if (comment.length > 65535)
2306
+ throw new RangeError("ZIP archive comment exceeds 65535 bytes");
2307
+ if (!zip64 && (count > 0xffffn || directorySize >= ZIP32_SENTINEL2 || directoryOffset >= ZIP32_SENTINEL2))
2308
+ throw new RangeError("ZIP32 end record capacity exceeded");
2309
+ const bytes = new Uint8Array((zip64 ? 98 : 22) + comment.length);
2310
+ const view = new DataView(bytes.buffer);
2311
+ if (zip64) {
2312
+ view.setUint32(0, 101075792, true);
2313
+ view.setBigUint64(4, 44n, true);
2314
+ view.setUint16(12, 45, true);
2315
+ view.setUint16(14, 45, true);
2316
+ view.setBigUint64(24, count, true);
2317
+ view.setBigUint64(32, count, true);
2318
+ view.setBigUint64(40, directorySize, true);
2319
+ view.setBigUint64(48, directoryOffset, true);
2320
+ view.setUint32(56, 117853008, true);
2321
+ view.setBigUint64(64, directoryOffset + directorySize, true);
2322
+ view.setUint32(72, 1, true);
2323
+ }
2324
+ const endOffset = zip64 ? 76 : 0;
2325
+ view.setUint32(endOffset, 101010256, true);
2326
+ view.setUint16(endOffset + 8, zip64 ? 65535 : Number(count), true);
2327
+ view.setUint16(endOffset + 10, zip64 ? 65535 : Number(count), true);
2328
+ view.setUint32(endOffset + 12, zip64 ? Number(ZIP32_SENTINEL2) : Number(directorySize), true);
2329
+ view.setUint32(endOffset + 16, zip64 ? Number(ZIP32_SENTINEL2) : Number(directoryOffset), true);
2330
+ view.setUint16(endOffset + 20, comment.length, true);
2331
+ bytes.set(comment, endOffset + 22);
2332
+ return bytes;
2333
+ }
2334
+ function encodeZipTimestamp2(date) {
2335
+ if (!(date instanceof Date) || !Number.isFinite(date.getTime()) || date.getUTCFullYear() < 1980 || date.getUTCFullYear() > 2107)
2336
+ throw new RangeError("ZIP timestamp must be a valid UTC date in 1980\u20132107");
2337
+ const time = date.getUTCHours() << 11 | date.getUTCMinutes() << 5 | Math.floor(date.getUTCSeconds() / 2);
2338
+ const day = date.getUTCFullYear() - 1980 << 9 | date.getUTCMonth() + 1 << 5 | date.getUTCDate();
2339
+ return (day << 16 | time) >>> 0;
2340
+ }
2341
+ function getZipVersion2(entry) {
2342
+ return entry.zip64 ? 45 : entry.method === 8 || entry.flags & 8 ? 20 : 10;
2343
+ }
2344
+ function validateHeaderEntry2(entry) {
2345
+ var _a;
2346
+ if (!entry.nameBytes.length || entry.nameBytes.length > 65535 || (((_a = entry.commentBytes) == null ? void 0 : _a.length) ?? 0) > 65535)
2347
+ throw new RangeError("ZIP name/comment exceeds header capacity");
2348
+ for (const value of [entry.size, entry.compressedSize, entry.localHeaderOffset])
2349
+ validateUint642(value);
2350
+ if (!entry.zip64 && [entry.size, entry.compressedSize, entry.localHeaderOffset].some((value) => value >= ZIP32_SENTINEL2))
2351
+ throw new RangeError("ZIP32 entry capacity exceeded");
2352
+ }
2353
+ function validateUint642(value) {
2354
+ if (typeof value !== "bigint" || value < 0n || value > 0xffffffffffffffffn)
2355
+ throw new RangeError("ZIP64 unsigned integer capacity exceeded");
2356
+ }
2357
+
2358
+ // dist/zip/zip-encode.js
2359
+ var DEFAULT_OPTIONS2 = {
2360
+ compression: "store",
2361
+ zip64: "auto",
2362
+ maxArchiveBytes: 1024n ** 4n,
2363
+ maxEntryBytes: 1024n ** 4n,
2364
+ maxDirectoryBytes: 32 * 1024 * 1024,
2365
+ maxEntries: 1e5,
2366
+ chunkBytes: 64 * 1024
2367
+ };
2368
+ async function encodeZip(files, options = {}) {
2369
+ const chunks = [];
2370
+ let size = 0;
2371
+ for await (const chunk of encodeZipInBatches(files, options)) {
2372
+ if (size + chunk.length > 4294967295)
2373
+ throw new RangeError("ZIP buffer capacity exceeded; use encodeZipInBatches");
2374
+ chunks.push(chunk);
2375
+ size += chunk.length;
2376
+ }
2377
+ const output = new Uint8Array(size);
2378
+ let offset = 0;
2379
+ for (const chunk of chunks) {
2380
+ output.set(chunk, offset);
2381
+ offset += chunk.length;
2382
+ }
2383
+ return output.buffer;
2384
+ }
2385
+ async function* encodeZipInBatches(files, options = {}) {
2386
+ const settings = {
2387
+ compression: options.compression ?? DEFAULT_OPTIONS2.compression,
2388
+ zip64: options.zip64 ?? DEFAULT_OPTIONS2.zip64,
2389
+ maxArchiveBytes: options.maxArchiveBytes ?? DEFAULT_OPTIONS2.maxArchiveBytes,
2390
+ maxEntryBytes: options.maxEntryBytes ?? DEFAULT_OPTIONS2.maxEntryBytes,
2391
+ maxDirectoryBytes: options.maxDirectoryBytes ?? DEFAULT_OPTIONS2.maxDirectoryBytes,
2392
+ maxEntries: options.maxEntries ?? DEFAULT_OPTIONS2.maxEntries,
2393
+ chunkBytes: options.chunkBytes ?? DEFAULT_OPTIONS2.chunkBytes
2394
+ };
2395
+ validateSettings(settings);
2396
+ const signal = options.signal;
2397
+ signal == null ? void 0 : signal.throwIfAborted();
2398
+ const comment = encodeArchiveComment(options.comment ?? "");
2399
+ const date = options.date ?? /* @__PURE__ */ new Date("1980-01-01T00:00:00Z");
2400
+ encodeZipTimestamp2(date);
2401
+ const paths = Object.keys(files).sort();
2402
+ if (paths.length > settings.maxEntries)
2403
+ throw new RangeError("ZIP entry count limit exceeded");
2404
+ if (settings.zip64 === "never" && paths.length > 65535)
2405
+ throw new RangeError("ZIP32 entry count capacity exceeded");
2406
+ let minimumDirectoryBytes = 0;
2407
+ const entries = paths.map((path) => {
2408
+ var _a;
2409
+ validateZipPath2(path);
2410
+ const value = files[path];
2411
+ const entry = value && typeof value === "object" && "data" in value ? value : { data: value };
2412
+ const size = getSourceSize(entry.data);
2413
+ const directory2 = path.endsWith("/");
2414
+ const compression = entry.compression ?? settings.compression;
2415
+ if (compression !== "store" && compression !== "deflate")
2416
+ throw new TypeError("Unsupported ZIP compression");
2417
+ if (size !== void 0 && (size > settings.maxEntryBytes || directory2 && size !== 0n))
2418
+ throw new RangeError("ZIP entry byte limit or nonempty directory");
2419
+ if (path.length > 65535 || (((_a = entry.comment) == null ? void 0 : _a.length) ?? 0) > 65535)
2420
+ throw new RangeError("ZIP name/comment exceeds header capacity");
2421
+ if (entry.comment !== void 0 && typeof entry.comment !== "string")
2422
+ throw new TypeError("ZIP entry comment must be a string");
2423
+ const nameBytes = encodeUtf8Text2(path);
2424
+ const commentBytes = encodeUtf8Text2(entry.comment ?? "");
2425
+ encodeZipTimestamp2(entry.date ?? date);
2426
+ const timestamp = new Date((entry.date ?? date).getTime());
2427
+ const zip642 = settings.zip64 === "always" || settings.zip64 === "auto" && (size === void 0 || size >= 0xffffffffn || !directory2 && compression === "deflate");
2428
+ const header = {
2429
+ nameBytes,
2430
+ commentBytes,
2431
+ date: timestamp,
2432
+ method: directory2 || compression === "store" ? 0 : 8,
2433
+ flags: 2056,
2434
+ crc32: 0,
2435
+ size: size ?? 0n,
2436
+ compressedSize: 0n,
2437
+ localHeaderOffset: 0n,
2438
+ zip64: zip642,
2439
+ directory: directory2
2440
+ };
2441
+ encodeZipCentralHeader2(header);
2442
+ minimumDirectoryBytes += 46 + nameBytes.length + commentBytes.length + (zip642 ? 28 : 0);
2443
+ if (minimumDirectoryBytes > settings.maxDirectoryBytes)
2444
+ throw new RangeError("ZIP directory byte limit exceeded");
2445
+ return { source: entry.data, size, header };
2446
+ });
2447
+ let outputBytes = 0n;
2448
+ let directoryBytes = 0;
2449
+ let usedZip64 = settings.zip64 === "always";
2450
+ const directory = [];
2451
+ function* emit(bytes) {
2452
+ for (let offset = 0; offset < bytes.length; offset += settings.chunkBytes) {
2453
+ signal == null ? void 0 : signal.throwIfAborted();
2454
+ const chunk = bytes.slice(offset, offset + settings.chunkBytes);
2455
+ if (outputBytes + BigInt(chunk.length) > settings.maxArchiveBytes)
2456
+ throw new RangeError("ZIP archive output byte limit exceeded");
2457
+ outputBytes += BigInt(chunk.length);
2458
+ yield chunk;
2459
+ signal == null ? void 0 : signal.throwIfAborted();
2460
+ }
2461
+ }
2462
+ for (const entry of entries) {
2463
+ signal == null ? void 0 : signal.throwIfAborted();
2464
+ const zip642 = entry.header.zip64 || settings.zip64 === "auto" && outputBytes >= 0xffffffffn;
2465
+ const header = { ...entry.header, localHeaderOffset: outputBytes, zip64: zip642 };
2466
+ usedZip64 ||= zip642;
2467
+ yield* emit(encodeZipLocalHeader2(header));
2468
+ let size = 0n;
2469
+ let compressedSize = 0n;
2470
+ let checksum = 0;
2471
+ async function* measuredInput() {
2472
+ for await (const block of readSource(entry.source, settings.chunkBytes, signal)) {
2473
+ size += BigInt(block.byteLength);
2474
+ if (size > settings.maxEntryBytes || header.directory && size !== 0n)
2475
+ throw new RangeError("ZIP entry byte limit or nonempty directory");
2476
+ if (!zip642 && size >= 0xffffffffn)
2477
+ throw new RangeError("ZIP32 entry capacity exceeded");
2478
+ yield block;
2479
+ }
2480
+ if (entry.size !== void 0 && size !== entry.size)
2481
+ throw new TypeError("ZIP source size changed during encoding");
2482
+ }
2483
+ const hash = new CRC32Hash({
2484
+ crypto: {
2485
+ /** Captures the CRC after all decoded input bytes have been consumed. */
2486
+ onEnd: (result) => {
2487
+ checksum = Number.parseInt(result.hash, 16);
2488
+ }
2489
+ }
2490
+ });
2491
+ const input = hash.hashBatches(measuredInput(), "hex");
2492
+ const payload = header.method === 8 ? new DeflateCompressor({ raw: true }).compressBatches(input) : input;
2493
+ for await (const block of payload) {
2494
+ signal == null ? void 0 : signal.throwIfAborted();
2495
+ compressedSize += BigInt(block.byteLength);
2496
+ if (!zip642 && compressedSize >= 0xffffffffn)
2497
+ throw new RangeError("ZIP32 compressed entry capacity exceeded");
2498
+ yield* emit(new Uint8Array(block));
2499
+ }
2500
+ const finalHeader = { ...header, size, compressedSize, crc32: checksum };
2501
+ yield* emit(encodeZipDescriptor(finalHeader));
2502
+ const centralHeader = encodeZipCentralHeader2(finalHeader);
2503
+ directoryBytes += centralHeader.length;
2504
+ if (directoryBytes > settings.maxDirectoryBytes)
2505
+ throw new RangeError("ZIP directory byte limit exceeded");
2506
+ directory.push(centralHeader);
2507
+ }
2508
+ const directoryOffset = outputBytes;
2509
+ const zip64 = usedZip64 || settings.zip64 === "auto" && (paths.length >= 65535 || directoryBytes >= 4294967295 || directoryOffset >= 0xffffffffn);
2510
+ const footer = encodeZipEndRecords2(BigInt(paths.length), BigInt(directoryBytes), directoryOffset, zip64, comment);
2511
+ for (const header of directory)
2512
+ yield* emit(header);
2513
+ yield* emit(footer);
2514
+ }
2515
+ function validateSettings(settings) {
2516
+ if (settings.compression !== "store" && settings.compression !== "deflate")
2517
+ throw new TypeError("Unsupported ZIP compression");
2518
+ if (!["auto", "always", "never"].includes(settings.zip64))
2519
+ throw new TypeError("Invalid ZIP64 policy");
2520
+ for (const [name, value] of Object.entries(settings)) {
2521
+ if (name === "compression" || name === "zip64")
2522
+ continue;
2523
+ const bigintLimit = name === "maxArchiveBytes" || name === "maxEntryBytes";
2524
+ if (bigintLimit ? typeof value !== "bigint" || value < 0n : typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)
2525
+ throw new RangeError(`Invalid ZIP ${name} limit`);
2526
+ }
2527
+ }
2528
+ function getSourceSize(source) {
2529
+ if (source instanceof ArrayBuffer || ArrayBuffer.isView(source))
2530
+ return BigInt(source.byteLength);
2531
+ if (source instanceof Blob)
2532
+ return BigInt(Object.getOwnPropertyDescriptor(Blob.prototype, "size").get.call(source));
2533
+ if (!source || typeof source !== "object" || !(source instanceof ReadableStream) && !(Symbol.asyncIterator in source) && !(Symbol.iterator in source))
2534
+ throw new TypeError("ZIP source must be bytes, a Blob or a byte stream");
2535
+ return void 0;
2536
+ }
2537
+ async function* readSource(source, chunkBytes, signal) {
2538
+ if (source instanceof Blob) {
2539
+ const size = Number(getSourceSize(source));
2540
+ for (let offset = 0; offset < size; offset += chunkBytes) {
2541
+ signal == null ? void 0 : signal.throwIfAborted();
2542
+ const blob = Blob.prototype.slice.call(source, offset, Math.min(size, offset + chunkBytes));
2543
+ const block = await awaitWithSignal(Blob.prototype.arrayBuffer.call(blob), signal);
2544
+ signal == null ? void 0 : signal.throwIfAborted();
2545
+ if (block.byteLength !== Math.min(chunkBytes, size - offset))
2546
+ throw new TypeError("ZIP Blob returned a truncated block");
2547
+ yield block;
2548
+ }
2549
+ return;
2550
+ }
2551
+ if (source instanceof ArrayBuffer || ArrayBuffer.isView(source)) {
2552
+ yield* splitByteChunk(source, chunkBytes, signal);
2553
+ return;
2554
+ }
2555
+ const reader = source instanceof ReadableStream ? source.getReader() : void 0;
2556
+ const iterator = reader ? void 0 : Symbol.asyncIterator in source ? source[Symbol.asyncIterator]() : source[Symbol.iterator]();
2557
+ let done = false;
2558
+ try {
2559
+ while (!done) {
2560
+ signal == null ? void 0 : signal.throwIfAborted();
2561
+ const result = await awaitWithSignal(reader ? reader.read() : Promise.resolve(iterator.next()), signal);
2562
+ done = Boolean(result.done);
2563
+ if (!done)
2564
+ yield* splitByteChunk(result.value, chunkBytes, signal);
2565
+ }
2566
+ } finally {
2567
+ if (reader) {
2568
+ if (!done)
2569
+ void reader.cancel(signal == null ? void 0 : signal.reason).catch(() => {
2570
+ });
2571
+ reader.releaseLock();
2572
+ } else if (!done && (iterator == null ? void 0 : iterator.return)) {
2573
+ void Promise.resolve().then(() => iterator.return()).catch(() => {
2574
+ });
2575
+ }
2576
+ }
2577
+ }
2578
+ function* splitByteChunk(chunk, chunkBytes, signal) {
2579
+ if (!(chunk instanceof ArrayBuffer) && !ArrayBuffer.isView(chunk))
2580
+ throw new TypeError("ZIP stream chunks must be binary");
2581
+ const bytes = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
2582
+ const length = bytes.length;
2583
+ for (let offset = 0; offset < length; offset += chunkBytes) {
2584
+ signal == null ? void 0 : signal.throwIfAborted();
2585
+ if (bytes.byteLength !== length)
2586
+ throw new TypeError("ZIP source size changed during encoding");
2587
+ yield bytes.slice(offset, offset + chunkBytes).buffer;
2588
+ }
2589
+ }
2590
+ function awaitWithSignal(promise, signal) {
2591
+ if (!signal)
2592
+ return promise;
2593
+ return new Promise((resolve, reject) => {
2594
+ const finish = (settle) => {
2595
+ signal.removeEventListener("abort", abort);
2596
+ settle();
2597
+ };
2598
+ const abort = () => finish(() => reject(signal.reason));
2599
+ signal.addEventListener("abort", abort, { once: true });
2600
+ promise.then((value) => finish(() => resolve(value)), (error) => finish(() => reject(error)));
2601
+ if (signal.aborted)
2602
+ abort();
2603
+ });
2604
+ }
2605
+ function encodeArchiveComment(comment) {
2606
+ if (typeof comment !== "string")
2607
+ throw new TypeError("ZIP archive comment must be a string");
2608
+ const codepoints = [...comment];
2609
+ if (codepoints.length > 65535)
2610
+ throw new RangeError("ZIP archive comment exceeds 65535 bytes");
2611
+ const alphabet = decodeZipText2(Uint8Array.from({ length: 256 }, (_, index) => index), false);
2612
+ const bytes = new Uint8Array(codepoints.length);
2613
+ codepoints.forEach((character, index) => {
2614
+ const position = alphabet.indexOf(character);
2615
+ if (position < 0)
2616
+ throw new TypeError("ZIP archive comment is not representable in CP437");
2617
+ bytes[index] = position;
2618
+ });
2619
+ return bytes;
2620
+ }
2621
+
2622
+ // dist/zip/zip-writer.js
2623
+ var VERSION3 = true ? "5.0.0-alpha.13" : "latest";
2624
+ var ZipWriter = {
2625
+ ...ZipFormat,
2626
+ version: VERSION3,
2627
+ options: { zip: { createFolders: false } },
2628
+ encode: encodeZipFiles
2629
+ };
2630
+ async function encodeZipFiles(input, options = {}) {
2631
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2632
+ (_b = (_a = options.zip) == null ? void 0 : _a.signal) == null ? void 0 : _b.throwIfAborted();
2633
+ if ("jszip" in options)
2634
+ throw new TypeError("jszip options were removed; use typed zip options");
2635
+ const files = /* @__PURE__ */ Object.create(null);
2636
+ const maximum = ((_c = options.zip) == null ? void 0 : _c.maxEntries) ?? 1e5;
2637
+ if (!Number.isSafeInteger(maximum) || maximum < 1)
2638
+ throw new RangeError("Invalid ZIP entry limit");
2639
+ let count = 0;
2640
+ const addFile = (path, data) => {
2641
+ if (!Object.hasOwn(files, path) && ++count > maximum)
2642
+ throw new RangeError("ZIP entry limit exceeded");
2643
+ files[path] = data;
2644
+ };
2645
+ for (const [path, data] of Object.entries(input)) {
2646
+ if (path.endsWith("/") || ((_d = options.zip) == null ? void 0 : _d.createFolders)) {
2647
+ let offset = path.indexOf("/");
2648
+ while (offset !== -1) {
2649
+ const directory = path.slice(0, offset + 1);
2650
+ if (!Object.hasOwn(input, directory))
2651
+ addFile(directory, new Uint8Array(0));
2652
+ offset = path.indexOf("/", offset + 1);
2653
+ }
2654
+ }
2655
+ addFile(path, typeof data === "string" ? new TextEncoder().encode(data) : data);
2656
+ }
2657
+ (_f = (_e = options.zip) == null ? void 0 : _e.onUpdate) == null ? void 0 : _f.call(_e, { percent: 0 });
2658
+ const bytes = await encodeZip(files, options.zip);
2659
+ (_h = (_g = options.zip) == null ? void 0 : _g.onUpdate) == null ? void 0 : _h.call(_g, { percent: 100 });
2660
+ return bytes;
2661
+ }
2662
+
2663
+ // dist/tar/tar-format.js
2664
+ var TarFormat = {
2665
+ name: "TAR Archive",
2666
+ id: "tar",
2667
+ module: "archives",
2668
+ format: "tar",
2669
+ extensions: ["tar"],
2670
+ mimeTypes: ["application/x-tar"],
2671
+ category: "archive",
2672
+ binary: true
2673
+ };
2674
+
2675
+ // dist/tar/tar-loader-types.js
2676
+ var VERSION5 = true ? "5.0.0-alpha.13" : "latest";
2677
+ var TarLoader2 = {
2678
+ ...TarFormat,
2679
+ version: VERSION5,
2680
+ dataType: null,
2681
+ batchType: null,
2682
+ options: { tar: { maxEntries: 1e5, maxTotalDecodedBytes: 64 * 1024 * 1024 } },
2683
+ /** Loads the parser through the installed package subpath. */
2684
+ async preload() {
2685
+ const { TarLoaderWithParser: TarLoaderWithParser2 } = await Promise.resolve().then(() => (init_tar_loader(), tar_loader_exports));
2686
+ return TarLoaderWithParser2;
2687
+ }
2688
+ };
2689
+
2690
+ // dist/tar/tar-writer.js
2691
+ var VERSION6 = true ? "5.0.0-alpha.13" : "latest";
2692
+ var BLOCK_SIZE2 = 512;
2693
+ var encoder = new TextEncoder();
2694
+ function writeOctal(header, offset, width, value) {
2695
+ const digits = value.toString(8);
2696
+ if (!Number.isSafeInteger(value) || value < 0 || digits.length > width - 1) {
2697
+ throw new RangeError("TAR numeric field exceeds header capacity");
2698
+ }
2699
+ header.set(encoder.encode(digits.padStart(width - 1, "0")), offset);
2700
+ header[offset + width - 1] = 0;
2701
+ }
2702
+ function splitPath(path) {
2703
+ const components = path.split("/").filter((part) => part && part !== ".");
2704
+ if (!path || path.startsWith("/") || path.includes("\\") || path.includes("\0") || /^[A-Za-z]:/.test(components[0] ?? "") || components.includes("..")) {
2705
+ throw new Error(`Unsafe TAR path: ${path}`);
2706
+ }
2707
+ const bytes = encoder.encode(path);
2708
+ if (bytes.length <= 100)
2709
+ return { name: bytes, prefix: new Uint8Array(0) };
2710
+ for (let index = path.lastIndexOf("/"); index > 0; index = path.lastIndexOf("/", index - 1)) {
2711
+ const prefix = encoder.encode(path.slice(0, index));
2712
+ const name = encoder.encode(path.slice(index + 1));
2713
+ if (prefix.length <= 155 && name.length > 0 && name.length <= 100)
2714
+ return { name, prefix };
2715
+ }
2716
+ throw new RangeError(`TAR path exceeds ustar header capacity: ${path}`);
2717
+ }
2718
+ async function encodeTar(files) {
2719
+ const entries = Object.keys(files).sort().map((path) => [path, files[path]]);
2720
+ const prepared = entries.map(([path, value]) => {
2721
+ const directory = path.endsWith("/");
2722
+ const bytes = typeof value === "string" ? encoder.encode(value) : value instanceof Uint8Array ? value : new Uint8Array(value);
2723
+ if (directory && bytes.length)
2724
+ throw new Error(`TAR directory has file data: ${path}`);
2725
+ return { path, directory, bytes, ...splitPath(path) };
2726
+ });
2727
+ let length = BLOCK_SIZE2 * 2;
2728
+ for (const entry of prepared) {
2729
+ length += BLOCK_SIZE2 + Math.ceil(entry.bytes.length / BLOCK_SIZE2) * BLOCK_SIZE2;
2730
+ if (!Number.isSafeInteger(length))
2731
+ throw new RangeError("TAR archive exceeds safe size");
2732
+ }
2733
+ const archive = new Uint8Array(length);
2734
+ let offset = 0;
2735
+ for (const entry of prepared) {
2736
+ const header = archive.subarray(offset, offset + BLOCK_SIZE2);
2737
+ header.set(entry.name, 0);
2738
+ writeOctal(header, 100, 8, entry.directory ? 493 : 420);
2739
+ writeOctal(header, 108, 8, 0);
2740
+ writeOctal(header, 116, 8, 0);
2741
+ writeOctal(header, 124, 12, entry.bytes.length);
2742
+ writeOctal(header, 136, 12, 0);
2743
+ header.fill(32, 148, 156);
2744
+ header[156] = entry.directory ? 53 : 48;
2745
+ header.set(encoder.encode("ustar\0"), 257);
2746
+ header.set(encoder.encode("00"), 263);
2747
+ header.set(entry.prefix, 345);
2748
+ let checksum = 0;
2749
+ for (const byte of header)
2750
+ checksum += byte;
2751
+ header.set(encoder.encode(checksum.toString(8).padStart(6, "0") + "\0 "), 148);
2752
+ offset += BLOCK_SIZE2;
2753
+ archive.set(entry.bytes, offset);
2754
+ offset += Math.ceil(entry.bytes.length / BLOCK_SIZE2) * BLOCK_SIZE2;
2755
+ }
2756
+ return archive.buffer;
2757
+ }
2758
+ var TarWriter = {
2759
+ ...TarFormat,
2760
+ version: VERSION6,
2761
+ options: {},
2762
+ encode: async (files, _options) => encodeTar(files)
2763
+ };
2764
+
2765
+ // dist/tar/lib/utils.js
2766
+ function clean(length) {
2767
+ let i;
2768
+ const buffer = new Uint8Array(length);
2769
+ for (i = 0; i < length; i += 1) {
2770
+ buffer[i] = 0;
2771
+ }
2772
+ return buffer;
2773
+ }
2774
+ function pad(num, bytes, base) {
2775
+ const numStr = num.toString(base || 8);
2776
+ return "000000000000".substr(numStr.length + 12 - bytes) + numStr;
2777
+ }
2778
+ function stringToUint8(input, out, offset) {
2779
+ let i;
2780
+ let length;
2781
+ out = out || clean(input.length);
2782
+ offset = offset || 0;
2783
+ for (i = 0, length = input.length; i < length; i += 1) {
2784
+ out[offset] = input.charCodeAt(i);
2785
+ offset += 1;
2786
+ }
2787
+ return out;
2788
+ }
2789
+
2790
+ // dist/tar/lib/header.js
2791
+ var structure = {
2792
+ fileName: 100,
2793
+ fileMode: 8,
2794
+ uid: 8,
2795
+ gid: 8,
2796
+ fileSize: 12,
2797
+ mtime: 12,
2798
+ checksum: 8,
2799
+ type: 1,
2800
+ linkName: 100,
2801
+ ustar: 8,
2802
+ owner: 32,
2803
+ group: 32,
2804
+ majorNumber: 8,
2805
+ minorNumber: 8,
2806
+ filenamePrefix: 155,
2807
+ padding: 12
2808
+ };
2809
+ function format(data, cb) {
2810
+ const buffer = clean(512);
2811
+ let offset = 0;
2812
+ Object.entries(structure).forEach(([field, length]) => {
2813
+ const str = data[field] || "";
2814
+ let i;
2815
+ let fieldLength;
2816
+ for (i = 0, fieldLength = str.length; i < fieldLength; i += 1) {
2817
+ buffer[offset] = str.charCodeAt(i);
2818
+ offset += 1;
2819
+ }
2820
+ offset += length - i;
2821
+ });
2822
+ if (typeof cb === "function") {
2823
+ return cb(buffer, offset);
2824
+ }
2825
+ return buffer;
2826
+ }
2827
+
2828
+ // dist/tar/lib/tar.js
2829
+ var blockSize;
2830
+ var headerLength;
2831
+ var inputLength;
2832
+ var recordSize = 512;
2833
+ var Tar = class {
2834
+ written;
2835
+ out;
2836
+ blocks = [];
2837
+ length;
2838
+ /**
2839
+ * @param [recordsPerBlock]
2840
+ */
2841
+ constructor(recordsPerBlock) {
2842
+ this.written = 0;
2843
+ blockSize = (recordsPerBlock || 20) * recordSize;
2844
+ this.out = clean(blockSize);
2845
+ this.blocks = [];
2846
+ this.length = 0;
2847
+ this.save = this.save.bind(this);
2848
+ this.clear = this.clear.bind(this);
2849
+ this.append = this.append.bind(this);
2850
+ }
2851
+ /**
2852
+ * Append a file to the tar archive
2853
+ * @param filepath
2854
+ * @param input
2855
+ * @param [opts]
2856
+ */
2857
+ // eslint-disable-next-line complexity
2858
+ append(filepath, input, opts) {
2859
+ let checksum;
2860
+ if (typeof input === "string") {
2861
+ input = stringToUint8(input);
2862
+ } else if (input.constructor && input.constructor !== Uint8Array.prototype.constructor) {
2863
+ const errorInputMatch = /function\s*([$A-Za-z_][0-9A-Za-z_]*)\s*\(/.exec(input.constructor.toString());
2864
+ const errorInput = errorInputMatch && errorInputMatch[1];
2865
+ const errorMessage = `Invalid input type. You gave me: ${errorInput}`;
2866
+ throw errorMessage;
2867
+ }
2868
+ opts = opts || {};
2869
+ const mode = opts.mode || parseInt("777", 8) & 4095;
2870
+ const mtime = opts.mtime || Math.floor(Number(/* @__PURE__ */ new Date()) / 1e3);
2871
+ const uid = opts.uid || 0;
2872
+ const gid = opts.gid || 0;
2873
+ const data = {
2874
+ fileName: filepath,
2875
+ fileMode: pad(mode, 7),
2876
+ uid: pad(uid, 7),
2877
+ gid: pad(gid, 7),
2878
+ fileSize: pad(input.length, 11),
2879
+ mtime: pad(mtime, 11),
2880
+ checksum: " ",
2881
+ // 0 = just a file
2882
+ type: "0",
2883
+ ustar: "ustar ",
2884
+ owner: opts.owner || "",
2885
+ group: opts.group || ""
2886
+ };
2887
+ checksum = 0;
2888
+ Object.keys(data).forEach((key) => {
2889
+ let i;
2890
+ const value = data[key];
2891
+ let length;
2892
+ for (i = 0, length = value.length; i < length; i += 1) {
2893
+ checksum += value.charCodeAt(i);
2894
+ }
2895
+ });
2896
+ data.checksum = `${pad(checksum, 6)}\0 `;
2897
+ const headerArr = format(data);
2898
+ headerLength = Math.ceil(headerArr.length / recordSize) * recordSize;
2899
+ inputLength = Math.ceil(input.length / recordSize) * recordSize;
2900
+ this.blocks.push({
2901
+ header: headerArr,
2902
+ input,
2903
+ headerLength,
2904
+ inputLength
2905
+ });
2906
+ }
2907
+ /**
2908
+ * Compiling data to a Blob object
2909
+ * @returns {Blob}
2910
+ */
2911
+ save() {
2912
+ const buffers = [];
2913
+ const chunks = new Array();
2914
+ let length = 0;
2915
+ const max = Math.pow(2, 20);
2916
+ let chunk = new Array();
2917
+ this.blocks.forEach((b = []) => {
2918
+ if (length + b.headerLength + b.inputLength > max) {
2919
+ chunks.push({ blocks: chunk, length });
2920
+ chunk = [];
2921
+ length = 0;
2922
+ }
2923
+ chunk.push(b);
2924
+ length += b.headerLength + b.inputLength;
2925
+ });
2926
+ chunks.push({ blocks: chunk, length });
2927
+ chunks.forEach((c = []) => {
2928
+ const buffer = new Uint8Array(c.length);
2929
+ let written = 0;
2930
+ c.blocks.forEach((b = []) => {
2931
+ buffer.set(b.header, written);
2932
+ written += b.headerLength;
2933
+ buffer.set(b.input, written);
2934
+ written += b.inputLength;
2935
+ });
2936
+ buffers.push(buffer);
2937
+ });
2938
+ buffers.push(new Uint8Array(2 * recordSize));
2939
+ return new Blob(buffers, { type: "octet/stream" });
2940
+ }
2941
+ /**
2942
+ * Clear the data by its blocksize
2943
+ */
2944
+ clear() {
2945
+ this.written = 0;
2946
+ this.out = clean(blockSize);
2947
+ }
2948
+ };
2949
+ var tar_default = Tar;
2950
+
2951
+ // dist/tar/tar-builder.js
2952
+ var TAR_BUILDER_OPTIONS = {
2953
+ recordsPerBlock: 20
2954
+ };
2955
+ var TarBuilder = class _TarBuilder {
2956
+ static get properties() {
2957
+ return {
2958
+ id: "tar",
2959
+ name: "TAR",
2960
+ extensions: ["tar"],
2961
+ mimeTypes: ["application/x-tar"],
2962
+ builder: _TarBuilder,
2963
+ options: TAR_BUILDER_OPTIONS
2964
+ };
2965
+ }
2966
+ options;
2967
+ tape;
2968
+ count = 0;
2969
+ constructor(options) {
2970
+ this.options = { ...TAR_BUILDER_OPTIONS, ...options };
2971
+ this.tape = new tar_default(this.options.recordsPerBlock);
2972
+ }
2973
+ /** Adds a file to the archive. */
2974
+ addFile(filename, buffer) {
2975
+ this.tape.append(filename, new Uint8Array(buffer));
2976
+ this.count++;
2977
+ }
2978
+ async build() {
2979
+ return new Response(this.tape.save()).arrayBuffer();
2980
+ }
2981
+ };
2982
+ //# sourceMappingURL=index.cjs.map