@botharness/core 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1100 @@
1
+ import * as fs$1 from "node:fs";
2
+ import * as path from "node:path";
3
+ import { cpus } from "node:os";
4
+ import * as fsp from "node:fs/promises";
5
+ import { Writable } from "node:stream";
6
+ //#region node_modules/.pnpm/modern-tar@0.8.5/node_modules/modern-tar/dist/packer-kJPaRbFA.js
7
+ const FILE = "file";
8
+ const LINK = "link";
9
+ const SYMLINK = "symlink";
10
+ const DIRECTORY = "directory";
11
+ const FLAGTYPE = {
12
+ "0": FILE,
13
+ "1": LINK,
14
+ "2": SYMLINK,
15
+ "3": "character-device",
16
+ "4": "block-device",
17
+ "5": DIRECTORY,
18
+ "6": "fifo",
19
+ x: "pax-header",
20
+ g: "pax-global-header",
21
+ L: "gnu-long-name",
22
+ K: "gnu-long-link-name"
23
+ };
24
+ const EMPTY = /* @__PURE__ */ new Uint8Array(0);
25
+ new TextEncoder();
26
+ const decoder = new TextDecoder();
27
+ function readString(view, offset, size) {
28
+ if (view[offset] === 0) return "";
29
+ const end = view.indexOf(0, offset);
30
+ const sliceEnd = end === -1 || end > offset + size ? offset + size : end;
31
+ return decoder.decode(view.subarray(offset, sliceEnd));
32
+ }
33
+ function readOctal(view, offset, size) {
34
+ let value = 0;
35
+ const end = offset + size;
36
+ for (let i = offset; i < end; i++) {
37
+ const charCode = view[i];
38
+ if (charCode === 0) break;
39
+ if (charCode === 32) continue;
40
+ value = value * 8 + (charCode - 48);
41
+ }
42
+ return value;
43
+ }
44
+ function readNumeric(view, offset, size) {
45
+ if (view[offset] & 128) {
46
+ let result = 0;
47
+ result = view[offset] & 127;
48
+ for (let i = 1; i < size; i++) result = result * 256 + view[offset + i];
49
+ if (!Number.isSafeInteger(result)) throw new Error("TAR number too large");
50
+ return result;
51
+ }
52
+ return readOctal(view, offset, size);
53
+ }
54
+ const isBodyless = (header) => header.type === "directory" || header.type === "symlink" || header.type === "link" || header.type === "character-device" || header.type === "block-device" || header.type === "fifo";
55
+ const stripPath = (p, n) => {
56
+ const parts = p.split("/").filter(Boolean);
57
+ return n >= parts.length ? "" : parts.slice(n).join("/");
58
+ };
59
+ function transformHeader(header, options) {
60
+ const { strip, filter, map } = options;
61
+ if (!strip && !filter && !map) return header;
62
+ const h = { ...header };
63
+ if (strip && strip > 0) {
64
+ const newName = stripPath(h.name, strip);
65
+ if (!newName) return null;
66
+ h.name = h.type === "directory" && !newName.endsWith("/") ? `${newName}/` : newName;
67
+ if (h.linkname) {
68
+ const isAbsolute = h.linkname.startsWith("/");
69
+ if (isAbsolute || h.type === "link") {
70
+ const stripped = stripPath(h.linkname, strip);
71
+ h.linkname = isAbsolute ? `/${stripped}` || "/" : stripped;
72
+ }
73
+ }
74
+ }
75
+ if (filter?.(h) === false) return null;
76
+ const result = map ? map(h) : h;
77
+ if (result && (!result.name?.trim() || result.name === "." || result.name === "/")) return null;
78
+ return result;
79
+ }
80
+ const INITIAL_CAPACITY = 256;
81
+ function createChunkQueue() {
82
+ let chunks = new Array(INITIAL_CAPACITY);
83
+ let capacityMask = chunks.length - 1;
84
+ let head = 0;
85
+ let tail = 0;
86
+ let totalAvailable = 0;
87
+ const consumeFromHead = (count) => {
88
+ const chunk = chunks[head];
89
+ if (count === chunk.length) {
90
+ chunks[head] = EMPTY;
91
+ head = head + 1 & capacityMask;
92
+ } else chunks[head] = chunk.subarray(count);
93
+ totalAvailable -= count;
94
+ if (totalAvailable === 0 && chunks.length > INITIAL_CAPACITY) {
95
+ chunks = new Array(INITIAL_CAPACITY);
96
+ capacityMask = 255;
97
+ head = 0;
98
+ tail = 0;
99
+ }
100
+ };
101
+ function pull(bytes, callback) {
102
+ if (callback) {
103
+ let fed = 0;
104
+ let remaining = Math.min(bytes, totalAvailable);
105
+ while (remaining > 0) {
106
+ const chunk = chunks[head];
107
+ const toFeed = Math.min(remaining, chunk.length);
108
+ const segment = toFeed === chunk.length ? chunk : chunk.subarray(0, toFeed);
109
+ consumeFromHead(toFeed);
110
+ remaining -= toFeed;
111
+ fed += toFeed;
112
+ if (!callback(segment)) break;
113
+ }
114
+ return fed;
115
+ }
116
+ if (totalAvailable < bytes) return null;
117
+ if (bytes === 0) return EMPTY;
118
+ const firstChunk = chunks[head];
119
+ if (firstChunk.length >= bytes) {
120
+ const view = firstChunk.length === bytes ? firstChunk : firstChunk.subarray(0, bytes);
121
+ consumeFromHead(bytes);
122
+ return view;
123
+ }
124
+ const result = new Uint8Array(bytes);
125
+ let copied = 0;
126
+ let remaining = bytes;
127
+ while (remaining > 0) {
128
+ const chunk = chunks[head];
129
+ const toCopy = Math.min(remaining, chunk.length);
130
+ result.set(toCopy === chunk.length ? chunk : chunk.subarray(0, toCopy), copied);
131
+ copied += toCopy;
132
+ remaining -= toCopy;
133
+ consumeFromHead(toCopy);
134
+ }
135
+ return result;
136
+ }
137
+ return {
138
+ push: (chunk) => {
139
+ if (chunk.length === 0) return;
140
+ let nextTail = tail + 1 & capacityMask;
141
+ if (nextTail === head) {
142
+ const oldLen = chunks.length;
143
+ const newLen = oldLen * 2;
144
+ const newChunks = new Array(newLen);
145
+ const count = tail - head + oldLen & oldLen - 1;
146
+ if (head < tail) for (let i = 0; i < count; i++) newChunks[i] = chunks[head + i];
147
+ else {
148
+ const firstPart = oldLen - head;
149
+ for (let i = 0; i < firstPart; i++) newChunks[i] = chunks[head + i];
150
+ for (let i = 0; i < tail; i++) newChunks[firstPart + i] = chunks[i];
151
+ }
152
+ chunks = newChunks;
153
+ capacityMask = newLen - 1;
154
+ head = 0;
155
+ tail = count;
156
+ nextTail = tail + 1 & capacityMask;
157
+ }
158
+ chunks[tail] = chunk;
159
+ tail = nextTail;
160
+ totalAvailable += chunk.length;
161
+ },
162
+ available: () => totalAvailable,
163
+ peek: (bytes) => {
164
+ if (totalAvailable < bytes) return null;
165
+ if (bytes === 0) return EMPTY;
166
+ const firstChunk = chunks[head];
167
+ if (firstChunk.length >= bytes) return firstChunk.length === bytes ? firstChunk : firstChunk.subarray(0, bytes);
168
+ const result = new Uint8Array(bytes);
169
+ let copied = 0;
170
+ let index = head;
171
+ while (copied < bytes) {
172
+ const chunk = chunks[index];
173
+ const toCopy = Math.min(bytes - copied, chunk.length);
174
+ if (toCopy === chunk.length) result.set(chunk, copied);
175
+ else result.set(chunk.subarray(0, toCopy), copied);
176
+ copied += toCopy;
177
+ index = index + 1 & capacityMask;
178
+ }
179
+ return result;
180
+ },
181
+ discard: (bytes) => {
182
+ if (bytes > totalAvailable) throw new Error("Too many bytes consumed");
183
+ if (bytes === 0) return;
184
+ let remaining = bytes;
185
+ while (remaining > 0) {
186
+ const chunk = chunks[head];
187
+ const toConsume = Math.min(remaining, chunk.length);
188
+ consumeFromHead(toConsume);
189
+ remaining -= toConsume;
190
+ }
191
+ },
192
+ pull
193
+ };
194
+ }
195
+ const CHECKSUM_SPACE = 32;
196
+ function validateChecksum(block) {
197
+ const stored = readOctal(block, 148, 8);
198
+ let sum = 0;
199
+ for (let i = 0; i < block.length; i++) if (i >= 148 && i < 156) sum += CHECKSUM_SPACE;
200
+ else sum += block[i];
201
+ return stored === sum;
202
+ }
203
+ function parseUstarHeader(block, strict) {
204
+ if (strict && !validateChecksum(block)) throw new Error("Invalid tar header checksum.");
205
+ const typeflag = readString(block, 156, 1);
206
+ const header = {
207
+ name: readString(block, 0, 100),
208
+ mode: readOctal(block, 100, 8),
209
+ uid: readNumeric(block, 108, 8),
210
+ gid: readNumeric(block, 116, 8),
211
+ size: readNumeric(block, 124, 12),
212
+ mtime: /* @__PURE__ */ new Date(readNumeric(block, 136, 12) * 1e3),
213
+ type: FLAGTYPE[typeflag] || "file",
214
+ linkname: readString(block, 157, 100)
215
+ };
216
+ const magic = readString(block, 257, 6);
217
+ if (magic.trim() === "ustar") {
218
+ header.uname = readString(block, 265, 32);
219
+ header.gname = readString(block, 297, 32);
220
+ }
221
+ if (magic === "ustar") header.prefix = readString(block, 345, 155);
222
+ return header;
223
+ }
224
+ const PAX_MAPPING = {
225
+ path: ["name", (v) => v],
226
+ linkpath: ["linkname", (v) => v],
227
+ size: ["size", (v) => /^\d+$/.test(v) && Number.isSafeInteger(+v) ? +v : NaN],
228
+ mtime: ["mtime", parseFloat],
229
+ uid: ["uid", (v) => parseInt(v, 10)],
230
+ gid: ["gid", (v) => parseInt(v, 10)],
231
+ uname: ["uname", (v) => v],
232
+ gname: ["gname", (v) => v]
233
+ };
234
+ function parsePax(buffer) {
235
+ const overrides = Object.create(null);
236
+ const pax = Object.create(null);
237
+ let isPax = false;
238
+ let offset = 0;
239
+ while (offset < buffer.length) {
240
+ const spaceIndex = buffer.indexOf(32, offset);
241
+ if (spaceIndex === -1) break;
242
+ const length = parseInt(decoder.decode(buffer.subarray(offset, spaceIndex)), 10);
243
+ if (!(length > 0)) break;
244
+ const recordEnd = offset + length;
245
+ const recordStr = decoder.decode(buffer.subarray(spaceIndex + 1, recordEnd - 1));
246
+ const equalsIndex = recordStr.indexOf("=");
247
+ if (equalsIndex > 0) {
248
+ const key = recordStr.slice(0, equalsIndex);
249
+ const value = recordStr.slice(equalsIndex + 1);
250
+ pax[key] = value;
251
+ isPax = true;
252
+ if (Object.hasOwn(PAX_MAPPING, key)) {
253
+ const [targetKey, parser] = PAX_MAPPING[key];
254
+ const parsedValue = parser(value);
255
+ if (typeof parsedValue === "string" || !Number.isNaN(parsedValue)) overrides[targetKey] = parsedValue;
256
+ }
257
+ }
258
+ offset = recordEnd;
259
+ }
260
+ if (isPax) overrides.pax = pax;
261
+ return overrides;
262
+ }
263
+ function applyOverrides(header, overrides) {
264
+ if (overrides.name !== void 0) header.name = overrides.name;
265
+ if (overrides.linkname !== void 0) header.linkname = overrides.linkname;
266
+ if (overrides.size !== void 0) header.size = overrides.size;
267
+ if (overrides.mtime !== void 0) header.mtime = /* @__PURE__ */ new Date(overrides.mtime * 1e3);
268
+ if (overrides.uid !== void 0) header.uid = overrides.uid;
269
+ if (overrides.gid !== void 0) header.gid = overrides.gid;
270
+ if (overrides.uname !== void 0) header.uname = overrides.uname;
271
+ if (overrides.gname !== void 0) header.gname = overrides.gname;
272
+ if (overrides.pax) header.pax = Object.assign({}, header.pax ?? {}, overrides.pax);
273
+ }
274
+ function getMetaParser(type) {
275
+ switch (type) {
276
+ case "pax-global-header":
277
+ case "pax-header": return parsePax;
278
+ case "gnu-long-name": return (data) => ({ name: readString(data, 0, data.length) });
279
+ case "gnu-long-link-name": return (data) => ({ linkname: readString(data, 0, data.length) });
280
+ default: return;
281
+ }
282
+ }
283
+ const STATE_HEADER = 0;
284
+ const STATE_BODY = 1;
285
+ const MAX_META_SIZE = 8388608;
286
+ const truncateErr = /* @__PURE__ */ new Error("Tar archive is truncated.");
287
+ function createUnpacker(options = {}) {
288
+ const strict = options.strict ?? false;
289
+ const { available, peek, push, discard, pull } = createChunkQueue();
290
+ let state = STATE_HEADER;
291
+ let ended = false;
292
+ let done = false;
293
+ let eof = false;
294
+ let currentEntry = null;
295
+ const paxGlobals = {};
296
+ let nextEntryOverrides = {};
297
+ const unpacker = {
298
+ isEntryActive: () => state === STATE_BODY,
299
+ isBodyComplete: () => !currentEntry || currentEntry.remaining === 0,
300
+ canFinish: () => !currentEntry || available() >= currentEntry.remaining + currentEntry.padding,
301
+ bodyBytes: () => currentEntry && currentEntry.remaining > 0 ? Math.min(currentEntry.remaining, available()) : 0,
302
+ available,
303
+ write(chunk) {
304
+ if (ended) throw new Error("Archive already ended.");
305
+ push(chunk);
306
+ },
307
+ end() {
308
+ ended = true;
309
+ },
310
+ readHeader() {
311
+ if (state !== STATE_HEADER) throw new Error("Cannot read header while an entry is active");
312
+ if (done) return void 0;
313
+ while (!done) {
314
+ if (available() < 512) {
315
+ if (ended) {
316
+ if (available() > 0 && strict) throw truncateErr;
317
+ done = true;
318
+ return;
319
+ }
320
+ return null;
321
+ }
322
+ const headerBlock = peek(512);
323
+ if (isZeroBlock(headerBlock)) {
324
+ if (available() < 1024) {
325
+ if (ended) {
326
+ if (strict) throw truncateErr;
327
+ done = true;
328
+ return;
329
+ }
330
+ return null;
331
+ }
332
+ if (isZeroBlock(peek(1024).subarray(512))) {
333
+ discard(1024);
334
+ done = true;
335
+ eof = true;
336
+ return;
337
+ }
338
+ if (strict) throw new Error("Invalid tar header.");
339
+ discard(512);
340
+ continue;
341
+ }
342
+ let internalHeader;
343
+ try {
344
+ internalHeader = parseUstarHeader(headerBlock, strict);
345
+ } catch (err) {
346
+ if (strict) throw err;
347
+ discard(512);
348
+ continue;
349
+ }
350
+ const metaParser = getMetaParser(internalHeader.type);
351
+ if (metaParser) {
352
+ if (internalHeader.size > MAX_META_SIZE) throw new Error("Tar metadata entry exceeds maximum size.");
353
+ const paddedSize = internalHeader.size + (-internalHeader.size & 511);
354
+ if (available() < 512 + paddedSize) {
355
+ if (ended && strict) throw truncateErr;
356
+ return null;
357
+ }
358
+ discard(512);
359
+ const overrides = metaParser(pull(paddedSize).subarray(0, internalHeader.size));
360
+ if (nextEntryOverrides.pax) nextEntryOverrides = {};
361
+ const target = internalHeader.type === "pax-global-header" ? paxGlobals : nextEntryOverrides;
362
+ for (const key in overrides) target[key] = overrides[key];
363
+ continue;
364
+ }
365
+ discard(512);
366
+ const header = internalHeader;
367
+ if (internalHeader.prefix) header.name = `${internalHeader.prefix}/${header.name}`;
368
+ applyOverrides(header, paxGlobals);
369
+ applyOverrides(header, nextEntryOverrides);
370
+ let archiveSize = header.size;
371
+ if (isBodyless(header)) {
372
+ archiveSize = 0;
373
+ header.size = 0;
374
+ } else if (header.name.endsWith("/") && header.type === "file") {
375
+ header.type = DIRECTORY;
376
+ header.size = 0;
377
+ }
378
+ nextEntryOverrides = {};
379
+ currentEntry = {
380
+ header,
381
+ remaining: archiveSize,
382
+ padding: -archiveSize & 511
383
+ };
384
+ state = STATE_BODY;
385
+ return header;
386
+ }
387
+ },
388
+ streamBody(callback) {
389
+ if (state !== STATE_BODY || !currentEntry || currentEntry.remaining === 0) return 0;
390
+ const bytesToFeed = Math.min(currentEntry.remaining, available());
391
+ if (bytesToFeed === 0) return 0;
392
+ const fed = pull(bytesToFeed, callback);
393
+ currentEntry.remaining -= fed;
394
+ return fed;
395
+ },
396
+ skipPadding() {
397
+ if (state !== STATE_BODY || !currentEntry) return true;
398
+ if (currentEntry.remaining > 0) throw new Error("Body not fully consumed");
399
+ if (available() < currentEntry.padding) return false;
400
+ discard(currentEntry.padding);
401
+ currentEntry = null;
402
+ state = STATE_HEADER;
403
+ return true;
404
+ },
405
+ skipEntry() {
406
+ if (state !== STATE_BODY || !currentEntry) return true;
407
+ const toDiscard = Math.min(currentEntry.remaining, available());
408
+ if (toDiscard > 0) {
409
+ discard(toDiscard);
410
+ currentEntry.remaining -= toDiscard;
411
+ }
412
+ if (currentEntry.remaining > 0) return false;
413
+ return unpacker.skipPadding();
414
+ },
415
+ validateEOF() {
416
+ if (strict) {
417
+ if (!eof) throw truncateErr;
418
+ if (available() > 0) {
419
+ if (pull(available()).some((byte) => byte !== 0)) throw new Error("Invalid EOF.");
420
+ }
421
+ }
422
+ }
423
+ };
424
+ return unpacker;
425
+ }
426
+ function isZeroBlock(block) {
427
+ if (block[0] !== 0) return false;
428
+ if (block.byteOffset % 8 === 0) {
429
+ const view = new BigUint64Array(block.buffer, block.byteOffset, block.length / 8);
430
+ for (let i = 0; i < view.length; i++) if (view[i] !== 0n) return false;
431
+ return true;
432
+ }
433
+ for (let i = 0; i < block.length; i++) if (block[i] !== 0) return false;
434
+ return true;
435
+ }
436
+ //#endregion
437
+ //#region node_modules/.pnpm/modern-tar@0.8.5/node_modules/modern-tar/dist/fs/index.js
438
+ function validateBounds(targetPath, destDir, errorMessage) {
439
+ const target = path.resolve(targetPath);
440
+ const dest = path.resolve(destDir);
441
+ if (target !== dest && !target.startsWith(dest + path.sep)) throw new Error(errorMessage);
442
+ }
443
+ const win32Reserved = {
444
+ ":": "",
445
+ "<": "",
446
+ ">": "",
447
+ "|": "",
448
+ "?": "",
449
+ "*": "",
450
+ "\"": ""
451
+ };
452
+ const pathAlias = /\/\/|(?:^|\/)\.(?:\/|$)/;
453
+ function normalizeName(name) {
454
+ const path = name.replace(/\\/g, "/");
455
+ if (path.split("/").includes("..") || /^[a-zA-Z]:\.\./.test(path)) throw new Error(`${name} points outside extraction directory`);
456
+ let relative = path;
457
+ if (/^[a-zA-Z]:/.test(relative)) relative = relative.replace(/^[a-zA-Z]:[/\\]?/, "");
458
+ else if (relative.startsWith("/")) relative = relative.replace(/^\/+/, "");
459
+ if (process.platform === "win32") return relative.replace(/[<>:"|?*]/g, (char) => win32Reserved[char]);
460
+ return relative;
461
+ }
462
+ const normalizeHeaderName = (s) => {
463
+ const name = normalizeName(s.replace(/[\\/]+$/, ""));
464
+ return pathAlias.test(name) ? path.posix.normalize(name) : name;
465
+ };
466
+ const createOperationQueue = (concurrency) => {
467
+ let active = 0;
468
+ const tasks = [];
469
+ let head = 0;
470
+ let idle = null;
471
+ let resolveIdle = null;
472
+ const ensureIdle = () => idle ??= new Promise((resolve) => resolveIdle = resolve);
473
+ const flush = () => {
474
+ while (active < concurrency && head < tasks.length) {
475
+ const task = tasks[head++];
476
+ active++;
477
+ task().finally(() => {
478
+ active--;
479
+ flush();
480
+ });
481
+ }
482
+ if (head === tasks.length) {
483
+ tasks.length = 0;
484
+ head = 0;
485
+ if (active === 0 && resolveIdle) {
486
+ resolveIdle();
487
+ idle = null;
488
+ resolveIdle = null;
489
+ }
490
+ }
491
+ };
492
+ return {
493
+ add(op) {
494
+ const wasIdle = active === 0 && head === tasks.length;
495
+ return new Promise((resolve, reject) => {
496
+ tasks.push(() => Promise.resolve().then(op).then(resolve, reject));
497
+ if (wasIdle) ensureIdle();
498
+ flush();
499
+ });
500
+ },
501
+ onIdle() {
502
+ return active === 0 && head === tasks.length ? Promise.resolve() : ensureIdle();
503
+ }
504
+ };
505
+ };
506
+ const BATCH_BYTES = 262144;
507
+ const BUFFER_LIMIT = 8388608;
508
+ const MAX_WRITE_VECTORS = 1024;
509
+ const CREATE_FLAGS = fs$1.constants.O_WRONLY | fs$1.constants.O_CREAT | fs$1.constants.O_TRUNC | (fs$1.constants.O_NOFOLLOW ?? 0) | fs$1.constants.O_EXCL;
510
+ const STATE_OPENING = 1;
511
+ const STATE_OPEN = 2;
512
+ const STATE_CLOSED = 3;
513
+ const STATE_FAILED = 4;
514
+ const DRAINED_PROMISE = Promise.resolve();
515
+ const discardFile = (fd) => fs$1.ftruncate(fd, 0, () => fs$1.close(fd));
516
+ function createFileSink(path, { mode = 438, mtime } = {}, onError) {
517
+ let state = STATE_OPENING;
518
+ let flushing = false;
519
+ let fd = null;
520
+ let queue = [];
521
+ let spare = [];
522
+ let bytes = 0;
523
+ let storedError = null;
524
+ let failedFd = null;
525
+ let endPromise = null;
526
+ let endResolve = null;
527
+ let endReject = null;
528
+ let drainPromise = null;
529
+ let drainResolve = null;
530
+ let drainReject = null;
531
+ const settleDrain = (error) => {
532
+ if (!drainPromise) return;
533
+ const resolve = drainResolve;
534
+ const reject = drainReject;
535
+ drainPromise = null;
536
+ drainResolve = null;
537
+ drainReject = null;
538
+ if (error) reject?.(error);
539
+ else resolve?.();
540
+ };
541
+ const resetBuffers = () => {
542
+ bytes = 0;
543
+ queue.length = 0;
544
+ spare.length = 0;
545
+ };
546
+ const finish = () => {
547
+ if (state === STATE_FAILED) return;
548
+ state = STATE_CLOSED;
549
+ endResolve?.();
550
+ settleDrain();
551
+ };
552
+ const fail = (error) => {
553
+ if (storedError) return;
554
+ storedError = error;
555
+ state = STATE_FAILED;
556
+ const writePending = flushing;
557
+ resetBuffers();
558
+ const fdToClose = fd;
559
+ fd = null;
560
+ if (fdToClose !== null) if (writePending) failedFd = fdToClose;
561
+ else discardFile(fdToClose);
562
+ flushing = false;
563
+ if (endReject) endReject(error);
564
+ else onError?.(error);
565
+ settleDrain(error);
566
+ };
567
+ const close = () => {
568
+ if (fd === null) {
569
+ finish();
570
+ return;
571
+ }
572
+ const fdToClose = fd;
573
+ fd = null;
574
+ if (mtime) fs$1.futimes(fdToClose, mtime, mtime, (err) => {
575
+ if (state !== STATE_OPEN) {
576
+ fs$1.close(fdToClose);
577
+ return;
578
+ }
579
+ if (err) {
580
+ fs$1.close(fdToClose, () => fail(err));
581
+ return;
582
+ }
583
+ fs$1.close(fdToClose, (closeErr) => {
584
+ if (state !== STATE_OPEN) return;
585
+ if (closeErr) fail(closeErr);
586
+ else finish();
587
+ });
588
+ });
589
+ else fs$1.close(fdToClose, (err) => {
590
+ if (state !== STATE_OPEN) return;
591
+ if (err) fail(err);
592
+ else finish();
593
+ });
594
+ };
595
+ const flush = () => {
596
+ if (flushing || queue.length === 0 || state !== STATE_OPEN) return;
597
+ flushing = true;
598
+ let bufs = queue;
599
+ queue = spare;
600
+ spare = bufs;
601
+ queue.length = 0;
602
+ let pendingBytes = bytes;
603
+ const onDone = (err, written = 0) => {
604
+ if (state !== STATE_OPEN) {
605
+ if (failedFd !== null) {
606
+ const fdToClose = failedFd;
607
+ failedFd = null;
608
+ discardFile(fdToClose);
609
+ }
610
+ return;
611
+ }
612
+ if (err) {
613
+ flushing = false;
614
+ fail(err);
615
+ return;
616
+ }
617
+ if (written <= 0 || written > pendingBytes) {
618
+ flushing = false;
619
+ fail(/* @__PURE__ */ new Error("File write made no progress."));
620
+ return;
621
+ }
622
+ bytes -= written;
623
+ pendingBytes -= written;
624
+ if (pendingBytes > 0) {
625
+ let skipped = written;
626
+ let index = 0;
627
+ while (skipped >= bufs[index].length) skipped -= bufs[index++].length;
628
+ bufs = bufs.slice(index);
629
+ if (skipped > 0) bufs[0] = bufs[0].subarray(skipped);
630
+ if (bufs.length === 1) {
631
+ const buf = bufs[0];
632
+ fs$1.write(fd, buf, 0, buf.length, null, onDone);
633
+ } else fs$1.writev(fd, bufs, onDone);
634
+ return;
635
+ }
636
+ flushing = false;
637
+ spare.length = 0;
638
+ if (bytes < BUFFER_LIMIT) settleDrain();
639
+ if (queue.length > 0) flush();
640
+ else if (endResolve) close();
641
+ };
642
+ if (bufs.length === 1) {
643
+ const buf = bufs[0];
644
+ fs$1.write(fd, buf, 0, buf.length, null, onDone);
645
+ } else fs$1.writev(fd, bufs, onDone);
646
+ };
647
+ const onOpen = (err, openFd) => {
648
+ if (err) return fail(err);
649
+ if (state >= STATE_CLOSED) {
650
+ fs$1.close(openFd);
651
+ return;
652
+ }
653
+ fd = openFd;
654
+ state = STATE_OPEN;
655
+ if (endResolve) if (queue.length > 0) flush();
656
+ else close();
657
+ else if (bytes >= BATCH_BYTES || queue.length >= MAX_WRITE_VECTORS) flush();
658
+ else settleDrain();
659
+ };
660
+ const write = (chunk) => {
661
+ if (state >= STATE_CLOSED || endResolve) return false;
662
+ queue.push(chunk);
663
+ bytes += chunk.length;
664
+ if (state === STATE_OPEN && !flushing && (bytes >= BATCH_BYTES || queue.length >= MAX_WRITE_VECTORS)) flush();
665
+ return bytes < BUFFER_LIMIT && queue.length < MAX_WRITE_VECTORS;
666
+ };
667
+ const waitDrain = () => {
668
+ if (storedError) return Promise.reject(storedError);
669
+ if (state === STATE_OPENING || state === STATE_OPEN && (bytes >= BUFFER_LIMIT || queue.length >= MAX_WRITE_VECTORS)) return drainPromise ??= new Promise((resolve, reject) => {
670
+ drainResolve = resolve;
671
+ drainReject = reject;
672
+ });
673
+ return DRAINED_PROMISE;
674
+ };
675
+ const end = () => {
676
+ if (storedError) return Promise.reject(storedError);
677
+ if (state >= STATE_CLOSED) return DRAINED_PROMISE;
678
+ if (endPromise) return endPromise;
679
+ endPromise = new Promise((resolve, reject) => {
680
+ endResolve = resolve;
681
+ endReject = reject;
682
+ if (state === STATE_OPEN && !flushing) if (queue.length > 0) flush();
683
+ else close();
684
+ });
685
+ return endPromise;
686
+ };
687
+ const destroy = (error) => {
688
+ if (error) {
689
+ fail(error);
690
+ return;
691
+ }
692
+ if (state >= STATE_CLOSED) return;
693
+ resetBuffers();
694
+ flushing = false;
695
+ if (fd !== null) {
696
+ const fdToClose = fd;
697
+ fd = null;
698
+ fs$1.close(fdToClose);
699
+ }
700
+ finish();
701
+ };
702
+ fs$1.open(path, CREATE_FLAGS, mode, (err, openFd) => {
703
+ if (err?.code !== "EEXIST") return onOpen(err, openFd);
704
+ if (state !== STATE_OPENING) return;
705
+ fs$1.rm(path, { force: true }, (rmErr) => {
706
+ if (rmErr) return fail(rmErr);
707
+ if (state !== STATE_OPENING) return;
708
+ fs$1.open(path, CREATE_FLAGS, mode, onOpen);
709
+ });
710
+ });
711
+ return {
712
+ write,
713
+ end,
714
+ destroy,
715
+ waitDrain
716
+ };
717
+ }
718
+ const createCache = () => {
719
+ const m = /* @__PURE__ */ new Map();
720
+ return {
721
+ get(k) {
722
+ const v = m.get(k);
723
+ if (m.delete(k)) m.set(k, v);
724
+ return v;
725
+ },
726
+ set(k, v) {
727
+ if (m.set(k, v).size > 1e4) m.delete(m.keys().next().value);
728
+ },
729
+ clear() {
730
+ m.clear();
731
+ }
732
+ };
733
+ };
734
+ const ENOENT = "ENOENT";
735
+ const MAX_SYMLINKS = 64;
736
+ const linkSep = process.platform === "win32" ? /[/\\]/ : "/";
737
+ const linkParts = (linkname) => linkname.split(linkSep).filter((part) => part && part !== ".");
738
+ const createPathCache = (destDirPath, options, opQueue, concurrency) => {
739
+ const { maxDepth = 1024, dmode } = options;
740
+ const dirPromises = createCache();
741
+ const pathConflicts = /* @__PURE__ */ new Map();
742
+ const deferredLinks = [];
743
+ let symlinks;
744
+ const realDirCache = createCache();
745
+ const initializeDestDir = async (destDirPath) => {
746
+ const symbolic = path.resolve(destDirPath);
747
+ try {
748
+ await fsp.mkdir(symbolic, { recursive: true });
749
+ } catch (err) {
750
+ if (err.code === ENOENT) {
751
+ const parentDir = path.dirname(symbolic);
752
+ if (parentDir === symbolic) throw err;
753
+ await fsp.mkdir(parentDir, { recursive: true });
754
+ await fsp.mkdir(symbolic, { recursive: true });
755
+ } else throw err;
756
+ }
757
+ try {
758
+ return {
759
+ symbolic,
760
+ real: await fsp.realpath(symbolic)
761
+ };
762
+ } catch (err) {
763
+ if (err.code === ENOENT) return {
764
+ symbolic,
765
+ real: symbolic
766
+ };
767
+ throw err;
768
+ }
769
+ };
770
+ const destDirPromise = initializeDestDir(destDirPath);
771
+ destDirPromise.catch(() => {});
772
+ const getRealDir = async (dirPath, errorMessage) => {
773
+ const destDir = await destDirPromise;
774
+ if (dirPath === destDir.symbolic) return destDir.real;
775
+ let promise = realDirCache.get(dirPath);
776
+ if (!promise) {
777
+ promise = fsp.realpath(dirPath).then((realPath) => {
778
+ validateBounds(realPath, destDir.real, errorMessage);
779
+ return realPath;
780
+ });
781
+ realDirCache.set(dirPath, promise);
782
+ }
783
+ return promise;
784
+ };
785
+ const prepareDirectory = async (dirPath, mode) => {
786
+ let promise = dirPromises.get(dirPath);
787
+ if (promise) return promise;
788
+ promise = (async () => {
789
+ if (dirPath === (await destDirPromise).symbolic) return;
790
+ await prepareDirectory(path.dirname(dirPath));
791
+ try {
792
+ const stat = await fsp.lstat(dirPath);
793
+ if (stat.isDirectory()) return;
794
+ if (stat.isSymbolicLink()) try {
795
+ const realPath = await getRealDir(dirPath, `Symlink "${dirPath}" points outside the extraction directory.`);
796
+ if ((await fsp.stat(realPath)).isDirectory()) return;
797
+ } catch (err) {
798
+ if (err.code === ENOENT) throw new Error(`Symlink "${dirPath}" points outside the extraction directory.`);
799
+ throw err;
800
+ }
801
+ throw new Error(`"${dirPath}" is not a valid directory component.`);
802
+ } catch (err) {
803
+ if (err.code === ENOENT) {
804
+ await fsp.mkdir(dirPath, { mode: mode ?? options.dmode });
805
+ return;
806
+ }
807
+ throw err;
808
+ }
809
+ })();
810
+ dirPromises.set(dirPath, promise);
811
+ return promise;
812
+ };
813
+ return {
814
+ async ready() {
815
+ await destDirPromise;
816
+ },
817
+ async preparePath(header) {
818
+ const { name, linkname, type, mode, mtime } = header;
819
+ const normalizedName = normalizeHeaderName(name);
820
+ const destDir = await destDirPromise;
821
+ const outPath = path.join(destDir.symbolic, normalizedName);
822
+ if (maxDepth !== Infinity) {
823
+ let depth = 1;
824
+ for (const char of normalizedName) if (char === "/" && ++depth > maxDepth) throw new Error("Tar exceeds max specified depth.");
825
+ }
826
+ const prevOp = pathConflicts.get(normalizedName);
827
+ if (prevOp) {
828
+ if (prevOp === "directory" && type !== "directory" || prevOp !== "directory" && type === "directory") throw new Error(`Path conflict ${type} over existing ${prevOp} at "${name}"`);
829
+ return;
830
+ }
831
+ const parentDir = path.dirname(outPath);
832
+ switch (type) {
833
+ case DIRECTORY: {
834
+ pathConflicts.set(normalizedName, DIRECTORY);
835
+ const safeMode = mode === void 0 ? void 0 : mode & 511;
836
+ await prepareDirectory(outPath, dmode ?? safeMode);
837
+ if (mtime) await fsp.lutimes(outPath, mtime, mtime).catch(() => {});
838
+ return;
839
+ }
840
+ case FILE:
841
+ pathConflicts.set(normalizedName, FILE);
842
+ await prepareDirectory(parentDir);
843
+ return path.join(await getRealDir(parentDir, `File "${name}" points outside the extraction directory.`), path.basename(outPath));
844
+ case SYMLINK: {
845
+ pathConflicts.set(normalizedName, SYMLINK);
846
+ if (!linkname) return;
847
+ validateBounds(path.resolve(parentDir, linkname), destDir.symbolic, `Symlink "${linkname}" points outside the extraction directory.`);
848
+ await prepareDirectory(parentDir);
849
+ const realParentDir = await fsp.realpath(parentDir);
850
+ validateBounds(realParentDir, destDir.real, "Symlink parent changed.");
851
+ validateBounds(path.resolve(realParentDir, linkname), destDir.real, `Symlink "${linkname}" points outside the extraction directory.`);
852
+ const realOutPath = path.join(realParentDir, path.basename(outPath));
853
+ try {
854
+ await fsp.symlink(linkname, realOutPath);
855
+ } catch (err) {
856
+ if (err.code !== "EEXIST") throw err;
857
+ await fsp.rm(realOutPath, { force: true });
858
+ if (await fsp.realpath(parentDir) !== realParentDir) throw new Error("Symlink parent changed.");
859
+ await fsp.symlink(linkname, realOutPath);
860
+ }
861
+ (symlinks ??= []).push([normalizedName, linkname]);
862
+ dirPromises.clear();
863
+ realDirCache.clear();
864
+ if (mtime) await fsp.lutimes(outPath, mtime, mtime).catch(() => {});
865
+ return;
866
+ }
867
+ case LINK: {
868
+ pathConflicts.set(normalizedName, LINK);
869
+ if (!linkname) return;
870
+ if (path.isAbsolute(linkname)) throw new Error(`Hardlink "${linkname}" points outside the extraction directory.`);
871
+ const linkTarget = path.join(destDir.symbolic, linkname);
872
+ validateBounds(linkTarget, destDir.symbolic, `Hardlink "${linkname}" points outside the extraction directory.`);
873
+ await prepareDirectory(parentDir);
874
+ if (linkTarget !== outPath) deferredLinks.push({
875
+ linkTarget,
876
+ outPath
877
+ });
878
+ return;
879
+ }
880
+ default: return;
881
+ }
882
+ },
883
+ async checkSymlinks() {
884
+ if (!symlinks) return;
885
+ const { symbolic: dest, real } = await destDirPromise;
886
+ const realPrefix = real + path.sep;
887
+ const root = path.parse(real).root;
888
+ const depth = linkParts(real.slice(root.length)).length;
889
+ const targetParts = (linkname, resolvedParts, message) => {
890
+ if (!path.isAbsolute(linkname)) return linkParts(linkname);
891
+ validateBounds(linkname, real, message);
892
+ resolvedParts.length = 0;
893
+ const parts = linkParts(linkname.slice(root.length));
894
+ parts.splice(0, depth);
895
+ return parts;
896
+ };
897
+ const getSymlinkError = async ([name, storedLinkname]) => {
898
+ const outPath = path.join(dest, name);
899
+ try {
900
+ try {
901
+ const resolved = await fsp.realpath(outPath);
902
+ if (resolved !== real && !resolved.startsWith(realPrefix)) throw new Error(`Symlink "${storedLinkname}" points outside the extraction directory.`);
903
+ return;
904
+ } catch (err) {
905
+ if (err.code !== ENOENT) throw err;
906
+ }
907
+ if (!(await fsp.lstat(outPath)).isSymbolicLink()) return;
908
+ const linkname = await fsp.readlink(outPath);
909
+ const message = `Symlink "${linkname}" points outside the extraction directory.`;
910
+ const realParent = await fsp.realpath(path.dirname(outPath));
911
+ validateBounds(realParent, real, message);
912
+ const resolvedParts = linkParts(path.relative(real, realParent));
913
+ const pendingParts = targetParts(linkname, resolvedParts, message);
914
+ let followedSymlinks = 0;
915
+ for (let i = 0; i < pendingParts.length; i++) {
916
+ const part = pendingParts[i];
917
+ if (part === "..") {
918
+ if (!resolvedParts.length) throw new Error(message);
919
+ resolvedParts.pop();
920
+ continue;
921
+ }
922
+ resolvedParts.push(part);
923
+ const nextPath = path.join(real, ...resolvedParts);
924
+ let nextStat;
925
+ try {
926
+ nextStat = await fsp.lstat(nextPath);
927
+ } catch (err) {
928
+ if (err.code === ENOENT) continue;
929
+ throw err;
930
+ }
931
+ if (!nextStat.isSymbolicLink()) continue;
932
+ if (++followedSymlinks > MAX_SYMLINKS) throw new Error(message);
933
+ const nextLink = await fsp.readlink(nextPath);
934
+ resolvedParts.pop();
935
+ pendingParts.splice(i + 1, 0, ...targetParts(nextLink, resolvedParts, message));
936
+ }
937
+ } catch (err) {
938
+ if (err.code !== ENOENT) return err;
939
+ }
940
+ };
941
+ for (let start = 0; start < symlinks.length; start += concurrency) {
942
+ const batch = symlinks.slice(start, start + concurrency);
943
+ const errors = await Promise.all(batch.map((symlink) => opQueue.add(() => getSymlinkError(symlink))));
944
+ for (const [i, error] of errors.entries()) {
945
+ if (error === void 0) continue;
946
+ await fsp.rm(path.join(dest, batch[i][0]), { force: true });
947
+ throw error;
948
+ }
949
+ }
950
+ },
951
+ async applyLinks() {
952
+ const destRoot = (await destDirPromise).real;
953
+ for (const { linkTarget, outPath } of deferredLinks) try {
954
+ const realTargetDir = await fsp.realpath(path.dirname(linkTarget));
955
+ validateBounds(realTargetDir, destRoot, `Hardlink "${linkTarget}" points outside the extraction directory.`);
956
+ const realTarget = path.join(realTargetDir, path.basename(linkTarget));
957
+ const [targetResult, outDirResult] = await Promise.allSettled([opQueue.add(() => fsp.lstat(realTarget)), opQueue.add(() => fsp.realpath(path.dirname(outPath)))]);
958
+ if (targetResult.status === "rejected") throw targetResult.reason;
959
+ const targetStat = targetResult.value;
960
+ if (targetStat.isSymbolicLink()) throw new Error(`Hardlink "${linkTarget}" is a symlink.`);
961
+ if (outDirResult.status === "rejected") throw outDirResult.reason;
962
+ const realOutDir = outDirResult.value;
963
+ validateBounds(realOutDir, destRoot, `Hardlink "${outPath}" points outside the extraction directory.`);
964
+ const realOutPath = path.join(realOutDir, path.basename(outPath));
965
+ try {
966
+ await fsp.link(realTarget, realOutPath);
967
+ } catch (err) {
968
+ const code = err.code;
969
+ if (code !== "EEXIST" && code !== ENOENT) throw err;
970
+ try {
971
+ const outStat = await fsp.lstat(realOutPath);
972
+ if (outStat.dev === targetStat.dev && outStat.ino === targetStat.ino) continue;
973
+ await fsp.rm(realOutPath, { force: true });
974
+ } catch (err) {
975
+ if (err.code !== ENOENT) throw err;
976
+ }
977
+ await fsp.link(realTarget, realOutPath);
978
+ }
979
+ const linkStat = await fsp.lstat(realOutPath);
980
+ if (linkStat.dev !== targetStat.dev || linkStat.ino !== targetStat.ino) {
981
+ await fsp.rm(realOutPath, { force: true });
982
+ throw new Error(`Hardlink target "${linkTarget}" changed during creation for link at "${outPath}".`);
983
+ }
984
+ } catch (err) {
985
+ if (err.code === ENOENT) throw new Error(`Hardlink target "${linkTarget}" does not exist for link at "${outPath}".`);
986
+ throw err;
987
+ }
988
+ }
989
+ };
990
+ };
991
+ function unpackTar(directoryPath, options = {}) {
992
+ const unpacker = createUnpacker(options);
993
+ const concurrency = options.concurrency || cpus().length || 8;
994
+ const opQueue = createOperationQueue(concurrency);
995
+ let cancelError;
996
+ const pathCache = createPathCache(directoryPath, options, opQueue, concurrency);
997
+ let currentFileStream = null;
998
+ const fileStreams = /* @__PURE__ */ new Set();
999
+ let needsDrain = false;
1000
+ const writeCurrent = (chunk) => {
1001
+ const writeOk = currentFileStream.write(chunk);
1002
+ if (!writeOk) needsDrain = true;
1003
+ return writeOk;
1004
+ };
1005
+ const onFileError = (err) => {
1006
+ if (!writable.destroyed) writable.destroy(err);
1007
+ };
1008
+ const closeCurrent = () => {
1009
+ const stream = currentFileStream;
1010
+ currentFileStream = null;
1011
+ opQueue.add(() => stream.end()).then(() => fileStreams.delete(stream), (err) => {
1012
+ fileStreams.delete(stream);
1013
+ onFileError(err);
1014
+ });
1015
+ };
1016
+ const writable = new Writable({
1017
+ async write(chunk, _, cb) {
1018
+ let pendingFileOpens;
1019
+ let writeError;
1020
+ try {
1021
+ unpacker.write(chunk);
1022
+ if (unpacker.isEntryActive()) {
1023
+ if (currentFileStream) {
1024
+ while (!unpacker.isBodyComplete()) {
1025
+ needsDrain = false;
1026
+ const fed = unpacker.streamBody(writeCurrent);
1027
+ if (needsDrain) await currentFileStream.waitDrain();
1028
+ else if (fed === 0) return;
1029
+ }
1030
+ if (!unpacker.skipPadding()) return;
1031
+ closeCurrent();
1032
+ } else if (!unpacker.skipEntry()) return;
1033
+ }
1034
+ while (true) {
1035
+ const header = unpacker.readHeader();
1036
+ if (header === void 0 || header === null) return;
1037
+ const transformedHeader = transformHeader(header, options);
1038
+ if (!transformedHeader) {
1039
+ if (!unpacker.skipEntry()) return;
1040
+ continue;
1041
+ }
1042
+ const outPath = await opQueue.add(() => pathCache.preparePath(transformedHeader));
1043
+ if (cancelError) throw cancelError;
1044
+ if (outPath) {
1045
+ const safeMode = transformedHeader.mode === void 0 ? void 0 : transformedHeader.mode & 511;
1046
+ currentFileStream = createFileSink(outPath, {
1047
+ mode: options.fmode ?? safeMode,
1048
+ mtime: transformedHeader.mtime ?? void 0
1049
+ }, onFileError);
1050
+ fileStreams.add(currentFileStream);
1051
+ (pendingFileOpens ??= []).push(currentFileStream.waitDrain().catch((error) => error));
1052
+ while (!unpacker.isBodyComplete()) {
1053
+ needsDrain = false;
1054
+ const fed = unpacker.streamBody(writeCurrent);
1055
+ if (needsDrain) await currentFileStream.waitDrain();
1056
+ else if (fed === 0) return;
1057
+ }
1058
+ if (!unpacker.skipPadding()) return;
1059
+ closeCurrent();
1060
+ } else if (!unpacker.skipEntry()) return;
1061
+ }
1062
+ } catch (err) {
1063
+ writeError = err;
1064
+ } finally {
1065
+ const openError = pendingFileOpens ? (await Promise.all(pendingFileOpens)).find((error) => error) : void 0;
1066
+ cb(cancelError ?? openError ?? writeError);
1067
+ }
1068
+ },
1069
+ async final(cb) {
1070
+ try {
1071
+ unpacker.end();
1072
+ unpacker.validateEOF();
1073
+ if (currentFileStream) closeCurrent();
1074
+ await pathCache.ready();
1075
+ await opQueue.onIdle();
1076
+ if (cancelError) throw cancelError;
1077
+ await pathCache.checkSymlinks();
1078
+ await pathCache.applyLinks();
1079
+ cb();
1080
+ } catch (err) {
1081
+ cb(err);
1082
+ }
1083
+ },
1084
+ destroy(error, callback) {
1085
+ const hasWork = fileStreams.size > 0 || writable.writableLength > 0 || writable.writableEnded && !writable.writableFinished;
1086
+ if (!error && !hasWork) {
1087
+ callback(null);
1088
+ return;
1089
+ }
1090
+ cancelError = error ?? AbortSignal.abort().reason;
1091
+ for (const stream of fileStreams) stream.destroy(cancelError);
1092
+ fileStreams.clear();
1093
+ currentFileStream = null;
1094
+ callback(cancelError);
1095
+ }
1096
+ });
1097
+ return writable;
1098
+ }
1099
+ //#endregion
1100
+ export { unpackTar };