sv 0.17.0 → 1.0.0-next.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.
@@ -1,6 +1,8 @@
1
1
  import { createRequire } from "node:module";
2
- import { AGENTS, COMMANDS, KIT3_TSCONFIG, KIT3_TSCONFIG_DEFAULT, Walker, coerceVersion, color, constructCommand, createPrinter, dedent, defineEnv, detect, downloadJson, fileExists, isKit3, isVersionUnsupportedBelow, js, libSubpathImports, loadFile, loadPackageJson, minVersion, parse, pnpm, resolveCommand, resolveCommandArray, resolveLibPrefix, sanitizeName, saveFile, svelte, svelteConfig, transforms } from "@sveltejs/sv-utils";
2
+ import { AGENTS, COMMANDS, Walker, coerceVersion, color, constructCommand, createPrinter, dedent, defineEnv, detect, downloadJson, fileExists, isKit3, isVersionUnsupportedBelow, js, loadFile, loadPackageJson, minVersion, minimizeDiff, parse, pnpm, resolveCommand, resolveCommandArray, resolveLibPrefix, sanitizeName, saveFile, svelte, svelteConfig, transforms } from "@sveltejs/sv-utils";
3
+ import * as fs$1 from "node:fs";
3
4
  import fs, { closeSync, existsSync, openSync, readSync, statSync } from "node:fs";
5
+ import * as path$1 from "node:path";
4
6
  import path, { basename, delimiter, dirname, isAbsolute, join, normalize, resolve } from "node:path";
5
7
  import { promisify, stripVTControlCharacters, styleText } from "node:util";
6
8
  import V, { cwd, stdin, stdout } from "node:process";
@@ -10,10 +12,11 @@ import { ReadStream } from "node:tty";
10
12
  import { fileURLToPath } from "node:url";
11
13
  import childProcess, { exec, spawn, spawnSync } from "node:child_process";
12
14
  import { pipeline } from "node:stream/promises";
13
- import { PassThrough } from "node:stream";
15
+ import { PassThrough, Writable } from "node:stream";
14
16
  import { EventEmitter } from "node:events";
15
17
  import crypto from "node:crypto";
16
- import { platform } from "node:os";
18
+ import * as fsp from "node:fs/promises";
19
+ import { cpus, platform } from "node:os";
17
20
  import { createGunzip } from "node:zlib";
18
21
  //#region \0rolldown/runtime.js
19
22
  var __create = Object.create;
@@ -39,18 +42,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
39
42
  }) : target, mod));
40
43
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
41
44
  //#endregion
42
- //#region src/core/deprecated.ts
43
- const warned = /* @__PURE__ */ new Set();
44
- /** Emit a one-time deprecation warning. */
45
- function svDeprecated(message) {
46
- if (warned.has(message)) return;
47
- warned.add(message);
48
- console.warn();
49
- console.warn(` ${color.dim("[sv] Deprecated:")} ${message}`);
50
- console.warn(` Still works. ${color.warning("Warn add-on's author about it.")}`);
51
- console.warn();
52
- }
53
- //#endregion
54
45
  //#region ../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/utils.js
55
46
  const getCodePointsLength = (() => {
56
47
  const SURROGATE_PAIR_RE = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
@@ -1348,7 +1339,7 @@ ${i ? styleText("cyan", x$1) : ""}
1348
1339
  //#endregion
1349
1340
  //#region package.json
1350
1341
  var name = "sv";
1351
- var version = "0.17.0";
1342
+ var version = "1.0.0-next.0";
1352
1343
  //#endregion
1353
1344
  //#region src/core/errors.ts
1354
1345
  var UnsupportedError = class extends Error {
@@ -1565,6 +1556,27 @@ const filePaths = {
1565
1556
  viteConfig: "vite.config.js",
1566
1557
  viteConfigTS: "vite.config.ts"
1567
1558
  };
1559
+ async function runAndValidateVerifications(verifications) {
1560
+ const fails = [];
1561
+ for (const verification of verifications) {
1562
+ const { message, success } = await verification.run();
1563
+ if (!success) fails.push({
1564
+ name: verification.name,
1565
+ message
1566
+ });
1567
+ }
1568
+ if (fails.length > 0) {
1569
+ Ce(`- ${fails.map(({ name, message }) => color.warning(`${name} (${message})`)).join("\n- ")}`, "Verifications not met", { format: (line) => line });
1570
+ const force = await le({
1571
+ message: "Verifications failed. Do you wish to continue?",
1572
+ initialValue: false
1573
+ });
1574
+ if (R$2(force) || !force) {
1575
+ ge("Operation cancelled.");
1576
+ V.exit(1);
1577
+ }
1578
+ }
1579
+ }
1568
1580
  //#endregion
1569
1581
  //#region src/create/utils.ts
1570
1582
  function mkdirp(dir) {
@@ -5382,6 +5394,26 @@ function boolean(message$1) {
5382
5394
  };
5383
5395
  }
5384
5396
  /* @__NO_SIDE_EFFECTS__ */
5397
+ function literal(literal_, message$1) {
5398
+ return {
5399
+ kind: "schema",
5400
+ type: "literal",
5401
+ reference: literal,
5402
+ expects: /* @__PURE__ */ _stringify(literal_),
5403
+ async: false,
5404
+ literal: literal_,
5405
+ message: message$1,
5406
+ get "~standard"() {
5407
+ return /* @__PURE__ */ _getStandardProps(this);
5408
+ },
5409
+ "~run"(dataset, config$1) {
5410
+ if (dataset.value === this.literal) dataset.typed = true;
5411
+ else _addIssue(this, "type", dataset, config$1);
5412
+ return dataset;
5413
+ }
5414
+ };
5415
+ }
5416
+ /* @__NO_SIDE_EFFECTS__ */
5385
5417
  function optional(wrapped, default_) {
5386
5418
  return {
5387
5419
  kind: "schema",
@@ -5938,7 +5970,7 @@ var ai_tools_default = defineAddon({
5938
5970
  const { mcpOptions, agentPath, agentLink, configPath, skillsPath, agentsPath, agentExtension, schema, customData, extraFiles } = client;
5939
5971
  if (!filesAdded.includes(agentPath)) sv.file(agentPath, (content) => {
5940
5972
  if (content) {
5941
- filesExistingAlready.push(agentPath);
5973
+ if (!filesExistingAlready.includes(agentPath)) filesExistingAlready.push(agentPath);
5942
5974
  return false;
5943
5975
  }
5944
5976
  filesAdded.push(agentPath);
@@ -6154,8 +6186,8 @@ var better_auth_default = defineAddon({
6154
6186
  const hasDemo = demoPassword || demoGithub;
6155
6187
  let drizzleDialect;
6156
6188
  let d1 = false;
6157
- sv.devDependency("auth", "^1.6.23");
6158
- sv.devDependency("better-auth", "^1.6.23");
6189
+ sv.devDependency("auth", "^1.6.24");
6190
+ sv.devDependency("better-auth", "^1.6.24");
6159
6191
  sv.file(`drizzle.config.${language}`, transforms.script(({ ast }) => {
6160
6192
  const isProp = (name, node) => node.key.type === "Identifier" && node.key.name === name;
6161
6193
  Walker.walk(ast, null, { Property(node) {
@@ -6628,9 +6660,14 @@ var drizzle_default = defineAddon({
6628
6660
  group: "client",
6629
6661
  default: "libsql",
6630
6662
  options: [
6663
+ {
6664
+ value: "node-sqlite",
6665
+ label: "node:sqlite",
6666
+ hint: "built-in to Node.js and Deno"
6667
+ },
6631
6668
  {
6632
6669
  value: "better-sqlite3",
6633
- hint: "for traditional Node environments"
6670
+ hint: "for server environments"
6634
6671
  },
6635
6672
  {
6636
6673
  value: "libsql",
@@ -6906,6 +6943,17 @@ var drizzle_default = defineAddon({
6906
6943
  clientExpression = js.common.parseExpression(`createClient({ url: ${dbUrl}, authToken: ${dbToken} })`);
6907
6944
  } else clientExpression = js.common.parseExpression(`createClient({ url: ${dbUrl} })`);
6908
6945
  }
6946
+ if (options.sqlite === "node-sqlite") {
6947
+ js.imports.addNamed(ast, {
6948
+ from: "node:sqlite",
6949
+ imports: ["DatabaseSync"]
6950
+ });
6951
+ js.imports.addNamed(ast, {
6952
+ from: "drizzle-orm/node-sqlite",
6953
+ imports: ["drizzle"]
6954
+ });
6955
+ clientExpression = js.common.parseExpression(`new DatabaseSync(${dbUrl})`);
6956
+ }
6909
6957
  if (options.mysql === "mysql2" || options.mysql === "planetscale") {
6910
6958
  js.imports.addDefault(ast, {
6911
6959
  from: "mysql2/promise",
@@ -7008,7 +7056,11 @@ const generateEnv = (opts, isExample) => transforms.text(({ content, text }) =>
7008
7056
  let value;
7009
7057
  const comment = ["Drizzle"];
7010
7058
  if (opts.docker) value = `"${opts.database === "mysql" ? "mysql" : "postgres"}://root:mysecretpassword@localhost:${PORTS[opts.database]}/local"`;
7011
- else if (opts.sqlite === "better-sqlite3" || opts.sqlite === "libsql") value = opts.sqlite === "libsql" ? "file:local.db" : "local.db";
7059
+ else if ([
7060
+ "better-sqlite3",
7061
+ "libsql",
7062
+ "node-sqlite"
7063
+ ].includes(opts.sqlite)) value = opts.sqlite === "libsql" ? "file:local.db" : "local.db";
7012
7064
  else if (opts.sqlite === "turso") if (isExample) {
7013
7065
  value = "\"libsql://db-name-user.turso.io\"";
7014
7066
  comment.push("Replace with your DB credentials!", {
@@ -7189,50 +7241,16 @@ const FEATURES = {
7189
7241
  path: "compilerOptions.experimental.async"
7190
7242
  },
7191
7243
  remoteFunctions: { label: "remote functions" },
7192
- explicitEnvironmentVariables: {
7193
- label: "explicit environment variables",
7194
- hint: "kit ^2 only",
7195
- inNext: false
7196
- },
7197
- handleRenderingErrors: {
7198
- label: "rendering error boundaries",
7199
- hint: "kit ^2 only",
7200
- inNext: false
7201
- },
7202
7244
  forkPreloads: {
7203
7245
  label: "forked preloading",
7204
7246
  off: true
7205
7247
  }
7206
7248
  };
7207
- const SOURCE_EXTENSIONS = [
7208
- ".svelte",
7209
- ".svelte.ts",
7210
- ".svelte.js",
7211
- ".ts",
7212
- ".js",
7213
- ".svx",
7214
- ".md"
7215
- ];
7216
- const KIT3_PEERS = {
7217
- vite: "^8.0.0",
7218
- "@sveltejs/vite-plugin-svelte": "^7.0.0",
7219
- svelte: "^5.48.0",
7220
- typescript: "^6.0.0"
7221
- };
7222
7249
  var experimental_default = defineAddon({
7223
7250
  id: "experimental",
7224
7251
  shortDescription: "svelte & kit experimental features",
7225
7252
  homepage: "https://svelte.dev/docs/kit/configuration#experimental",
7226
- options: defineAddonOptions().add("versions", {
7227
- question: "Which packages should use their `next` (pre-release) version?",
7228
- type: "multiselect",
7229
- default: ["kit"],
7230
- options: [{
7231
- value: "kit",
7232
- label: "@sveltejs/kit@next"
7233
- }],
7234
- required: false
7235
- }).add("features", {
7253
+ options: defineAddonOptions().add("features", {
7236
7254
  question: "Which experimental features do you want to enable?",
7237
7255
  type: "multiselect",
7238
7256
  default: Object.entries(FEATURES).filter(([, f]) => !f.off).map(([value]) => value),
@@ -7243,44 +7261,10 @@ var experimental_default = defineAddon({
7243
7261
  })),
7244
7262
  required: false
7245
7263
  }).build(),
7246
- setup: ({ runsAfter }) => runsAfter("sveltekitAdapter"),
7247
- run: ({ sv, cwd, options, language, directory, dependencyVersion }) => {
7248
- const kitNext = options.versions.includes("kit");
7249
- if (kitNext) {
7250
- sv.devDependency("@sveltejs/kit", "next");
7251
- for (const [pkg, range] of Object.entries(KIT3_PEERS)) {
7252
- if (pkg === "typescript" && language !== "ts") continue;
7253
- const current = dependencyVersion(pkg);
7254
- if (current && isVersionUnsupportedBelow(current, range)) sv.devDependency(pkg, range);
7255
- }
7256
- const { data: pkg } = loadPackageJson(cwd);
7257
- const deps = {
7258
- ...pkg.devDependencies,
7259
- ...pkg.dependencies
7260
- };
7261
- for (const name of Object.keys(deps)) if (name.startsWith("@sveltejs/adapter-")) sv.devDependency(name, "next");
7262
- }
7263
- if (kitNext) {
7264
- for (const name of ["tsconfig.json", "jsconfig.json"]) {
7265
- if (!fileExists(cwd, name)) continue;
7266
- sv.file(name, transforms.json(({ data }) => {
7267
- data.extends = KIT3_TSCONFIG;
7268
- data.include ??= [directory.src];
7269
- for (const [key, value] of Object.entries(data.compilerOptions ?? {})) if (KIT3_TSCONFIG_DEFAULT[key] === value) delete data.compilerOptions[key];
7270
- }));
7271
- }
7272
- sv.file("package.json", transforms.json(({ data }) => {
7273
- data.imports = {
7274
- ...libSubpathImports(directory.lib),
7275
- ...data.imports
7276
- };
7277
- }));
7278
- for (const relative of sourceFiles(cwd, directory.src)) sv.file(relative, (content) => content.includes("$lib") ? content.replaceAll("$lib", "#lib") : false);
7279
- }
7264
+ run: ({ sv, cwd, options }) => {
7280
7265
  const config = {};
7281
7266
  for (const [name, f] of Object.entries(FEATURES)) {
7282
7267
  if (!options.features.includes(name)) continue;
7283
- if (kitNext && f.inNext === false) continue;
7284
7268
  const keys = (f.path ?? `experimental.${name}`).split(".");
7285
7269
  let target = config;
7286
7270
  for (const key of keys.slice(0, -1)) target = target[key] ??= {};
@@ -7292,12 +7276,6 @@ var experimental_default = defineAddon({
7292
7276
  }, ({ override }) => override(config));
7293
7277
  }
7294
7278
  });
7295
- /** Workspace-relative source files under `src`, for the `$lib` -> `#lib` rewrite. */
7296
- function sourceFiles(cwd, src) {
7297
- const root = path.resolve(cwd, src);
7298
- if (!fs.existsSync(root)) return [];
7299
- return fs.readdirSync(root, { recursive: true }).map((entry) => path.join(src, entry)).filter((relative) => SOURCE_EXTENSIONS.some((ext) => relative.endsWith(ext)) && fs.statSync(path.resolve(cwd, relative)).isFile());
7300
- }
7301
7279
  //#endregion
7302
7280
  //#region src/addons/mdsvex.ts
7303
7281
  var mdsvex_default = defineAddon({
@@ -7425,8 +7403,7 @@ var paraglide_default = defineAddon({
7425
7403
  language,
7426
7404
  newHandleName: "handleParaglide",
7427
7405
  handleContent: `({ event, resolve }) => paraglideMiddleware(event.request, ({ request, locale }) => {
7428
- event.request = request;
7429
- return resolve(event, {
7406
+ return resolve({ ...event, request }, {
7430
7407
  transformPageChunk: ({ html }) => html.replace('%paraglide.lang%', locale).replace('%paraglide.dir%', getTextDirection(locale))
7431
7408
  });
7432
7409
  });`,
@@ -8093,2711 +8070,1048 @@ function getAddonDetails(id) {
8093
8070
  return details;
8094
8071
  }
8095
8072
  //#endregion
8096
- //#region ../../node_modules/.pnpm/events-universal@1.0.1/node_modules/events-universal/default.js
8097
- var require_default = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8098
- module.exports = __require("events");
8099
- }));
8100
- //#endregion
8101
- //#region ../../node_modules/.pnpm/fast-fifo@1.3.2/node_modules/fast-fifo/fixed-size.js
8102
- var require_fixed_size = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8103
- module.exports = class FixedFIFO {
8104
- constructor(hwm) {
8105
- if (!(hwm > 0) || (hwm - 1 & hwm) !== 0) throw new Error("Max size for a FixedFIFO should be a power of two");
8106
- this.buffer = new Array(hwm);
8107
- this.mask = hwm - 1;
8108
- this.top = 0;
8109
- this.btm = 0;
8110
- this.next = null;
8111
- }
8112
- clear() {
8113
- this.top = this.btm = 0;
8114
- this.next = null;
8115
- this.buffer.fill(void 0);
8116
- }
8117
- push(data) {
8118
- if (this.buffer[this.top] !== void 0) return false;
8119
- this.buffer[this.top] = data;
8120
- this.top = this.top + 1 & this.mask;
8121
- return true;
8122
- }
8123
- shift() {
8124
- const last = this.buffer[this.btm];
8125
- if (last === void 0) return void 0;
8126
- this.buffer[this.btm] = void 0;
8127
- this.btm = this.btm + 1 & this.mask;
8128
- return last;
8129
- }
8130
- peek() {
8131
- return this.buffer[this.btm];
8132
- }
8133
- isEmpty() {
8134
- return this.buffer[this.btm] === void 0;
8073
+ //#region ../../node_modules/.pnpm/modern-tar@0.7.7/node_modules/modern-tar/dist/packer-BtsuoKCV.js
8074
+ const FILE = "file";
8075
+ const LINK = "link";
8076
+ const SYMLINK = "symlink";
8077
+ const DIRECTORY = "directory";
8078
+ const FLAGTYPE = {
8079
+ "0": FILE,
8080
+ "1": LINK,
8081
+ "2": SYMLINK,
8082
+ "3": "character-device",
8083
+ "4": "block-device",
8084
+ "5": DIRECTORY,
8085
+ "6": "fifo",
8086
+ x: "pax-header",
8087
+ g: "pax-global-header",
8088
+ L: "gnu-long-name",
8089
+ K: "gnu-long-link-name"
8090
+ };
8091
+ const EMPTY = /* @__PURE__ */ new Uint8Array(0);
8092
+ new TextEncoder();
8093
+ const decoder = new TextDecoder();
8094
+ function readString(view, offset, size) {
8095
+ const end = view.indexOf(0, offset);
8096
+ const sliceEnd = end === -1 || end > offset + size ? offset + size : end;
8097
+ return decoder.decode(view.subarray(offset, sliceEnd));
8098
+ }
8099
+ function readOctal(view, offset, size) {
8100
+ let value = 0;
8101
+ const end = offset + size;
8102
+ for (let i = offset; i < end; i++) {
8103
+ const charCode = view[i];
8104
+ if (charCode === 0) break;
8105
+ if (charCode === 32) continue;
8106
+ value = value * 8 + (charCode - 48);
8107
+ }
8108
+ return value;
8109
+ }
8110
+ function readNumeric(view, offset, size) {
8111
+ if (view[offset] & 128) {
8112
+ let result = 0;
8113
+ result = view[offset] & 127;
8114
+ for (let i = 1; i < size; i++) result = result * 256 + view[offset + i];
8115
+ if (!Number.isSafeInteger(result)) throw new Error("TAR number too large");
8116
+ return result;
8117
+ }
8118
+ return readOctal(view, offset, size);
8119
+ }
8120
+ const isBodyless = (header) => header.type === "directory" || header.type === "symlink" || header.type === "link" || header.type === "character-device" || header.type === "block-device" || header.type === "fifo";
8121
+ const stripPath = (p, n) => {
8122
+ const parts = p.split("/").filter(Boolean);
8123
+ return n >= parts.length ? "" : parts.slice(n).join("/");
8124
+ };
8125
+ function transformHeader(header, options) {
8126
+ const { strip, filter, map } = options;
8127
+ if (!strip && !filter && !map) return header;
8128
+ const h = { ...header };
8129
+ if (strip && strip > 0) {
8130
+ const newName = stripPath(h.name, strip);
8131
+ if (!newName) return null;
8132
+ h.name = h.type === "directory" && !newName.endsWith("/") ? `${newName}/` : newName;
8133
+ if (h.linkname) {
8134
+ const isAbsolute = h.linkname.startsWith("/");
8135
+ if (isAbsolute || h.type === "link") {
8136
+ const stripped = stripPath(h.linkname, strip);
8137
+ h.linkname = isAbsolute ? `/${stripped}` || "/" : stripped;
8138
+ }
8139
+ }
8140
+ }
8141
+ if (filter?.(h) === false) return null;
8142
+ const result = map ? map(h) : h;
8143
+ if (result && (!result.name || !result.name.trim() || result.name === "." || result.name === "/")) return null;
8144
+ return result;
8145
+ }
8146
+ const INITIAL_CAPACITY = 256;
8147
+ function createChunkQueue() {
8148
+ let chunks = new Array(INITIAL_CAPACITY);
8149
+ let capacityMask = chunks.length - 1;
8150
+ let head = 0;
8151
+ let tail = 0;
8152
+ let totalAvailable = 0;
8153
+ const consumeFromHead = (count) => {
8154
+ const chunk = chunks[head];
8155
+ if (count === chunk.length) {
8156
+ chunks[head] = EMPTY;
8157
+ head = head + 1 & capacityMask;
8158
+ } else chunks[head] = chunk.subarray(count);
8159
+ totalAvailable -= count;
8160
+ if (totalAvailable === 0 && chunks.length > INITIAL_CAPACITY) {
8161
+ chunks = new Array(INITIAL_CAPACITY);
8162
+ capacityMask = INITIAL_CAPACITY - 1;
8163
+ head = 0;
8164
+ tail = 0;
8135
8165
  }
8136
8166
  };
8137
- }));
8138
- //#endregion
8139
- //#region ../../node_modules/.pnpm/fast-fifo@1.3.2/node_modules/fast-fifo/index.js
8140
- var require_fast_fifo = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8141
- const FixedFIFO = require_fixed_size();
8142
- module.exports = class FastFIFO {
8143
- constructor(hwm) {
8144
- this.hwm = hwm || 16;
8145
- this.head = new FixedFIFO(this.hwm);
8146
- this.tail = this.head;
8147
- this.length = 0;
8167
+ function pull(bytes, callback) {
8168
+ if (callback) {
8169
+ let fed = 0;
8170
+ let remaining = Math.min(bytes, totalAvailable);
8171
+ while (remaining > 0) {
8172
+ const chunk = chunks[head];
8173
+ const toFeed = Math.min(remaining, chunk.length);
8174
+ const segment = toFeed === chunk.length ? chunk : chunk.subarray(0, toFeed);
8175
+ consumeFromHead(toFeed);
8176
+ remaining -= toFeed;
8177
+ fed += toFeed;
8178
+ if (!callback(segment)) break;
8179
+ }
8180
+ return fed;
8181
+ }
8182
+ if (totalAvailable < bytes) return null;
8183
+ if (bytes === 0) return EMPTY;
8184
+ const firstChunk = chunks[head];
8185
+ if (firstChunk.length >= bytes) {
8186
+ const view = firstChunk.length === bytes ? firstChunk : firstChunk.subarray(0, bytes);
8187
+ consumeFromHead(bytes);
8188
+ return view;
8189
+ }
8190
+ const result = new Uint8Array(bytes);
8191
+ let copied = 0;
8192
+ let remaining = bytes;
8193
+ while (remaining > 0) {
8194
+ const chunk = chunks[head];
8195
+ const toCopy = Math.min(remaining, chunk.length);
8196
+ result.set(toCopy === chunk.length ? chunk : chunk.subarray(0, toCopy), copied);
8197
+ copied += toCopy;
8198
+ remaining -= toCopy;
8199
+ consumeFromHead(toCopy);
8148
8200
  }
8149
- clear() {
8150
- this.head = this.tail;
8151
- this.head.clear();
8152
- this.length = 0;
8153
- }
8154
- push(val) {
8155
- this.length++;
8156
- if (!this.head.push(val)) {
8157
- const prev = this.head;
8158
- this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);
8159
- this.head.push(val);
8201
+ return result;
8202
+ }
8203
+ return {
8204
+ push: (chunk) => {
8205
+ if (chunk.length === 0) return;
8206
+ let nextTail = tail + 1 & capacityMask;
8207
+ if (nextTail === head) {
8208
+ const oldLen = chunks.length;
8209
+ const newLen = oldLen * 2;
8210
+ const newChunks = new Array(newLen);
8211
+ const count = tail - head + oldLen & oldLen - 1;
8212
+ if (head < tail) for (let i = 0; i < count; i++) newChunks[i] = chunks[head + i];
8213
+ else if (count > 0) {
8214
+ const firstPart = oldLen - head;
8215
+ for (let i = 0; i < firstPart; i++) newChunks[i] = chunks[head + i];
8216
+ for (let i = 0; i < tail; i++) newChunks[firstPart + i] = chunks[i];
8217
+ }
8218
+ chunks = newChunks;
8219
+ capacityMask = newLen - 1;
8220
+ head = 0;
8221
+ tail = count;
8222
+ nextTail = tail + 1 & capacityMask;
8223
+ }
8224
+ chunks[tail] = chunk;
8225
+ tail = nextTail;
8226
+ totalAvailable += chunk.length;
8227
+ },
8228
+ available: () => totalAvailable,
8229
+ peek: (bytes) => {
8230
+ if (totalAvailable < bytes) return null;
8231
+ if (bytes === 0) return EMPTY;
8232
+ const firstChunk = chunks[head];
8233
+ if (firstChunk.length >= bytes) return firstChunk.length === bytes ? firstChunk : firstChunk.subarray(0, bytes);
8234
+ const result = new Uint8Array(bytes);
8235
+ let copied = 0;
8236
+ let index = head;
8237
+ while (copied < bytes) {
8238
+ const chunk = chunks[index];
8239
+ const toCopy = Math.min(bytes - copied, chunk.length);
8240
+ if (toCopy === chunk.length) result.set(chunk, copied);
8241
+ else result.set(chunk.subarray(0, toCopy), copied);
8242
+ copied += toCopy;
8243
+ index = index + 1 & capacityMask;
8160
8244
  }
8161
- }
8162
- shift() {
8163
- if (this.length !== 0) this.length--;
8164
- const val = this.tail.shift();
8165
- if (val === void 0 && this.tail.next) {
8166
- const next = this.tail.next;
8167
- this.tail.next = null;
8168
- this.tail = next;
8169
- return this.tail.shift();
8245
+ return result;
8246
+ },
8247
+ discard: (bytes) => {
8248
+ if (bytes > totalAvailable) throw new Error("Too many bytes consumed");
8249
+ if (bytes === 0) return;
8250
+ let remaining = bytes;
8251
+ while (remaining > 0) {
8252
+ const chunk = chunks[head];
8253
+ const toConsume = Math.min(remaining, chunk.length);
8254
+ consumeFromHead(toConsume);
8255
+ remaining -= toConsume;
8170
8256
  }
8171
- return val;
8172
- }
8173
- peek() {
8174
- const val = this.tail.peek();
8175
- if (val === void 0 && this.tail.next) return this.tail.next.peek();
8176
- return val;
8177
- }
8178
- isEmpty() {
8179
- return this.length === 0;
8180
- }
8181
- };
8182
- }));
8183
- //#endregion
8184
- //#region ../../node_modules/.pnpm/b4a@1.8.1/node_modules/b4a/index.js
8185
- var require_b4a = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8186
- function isBuffer(value) {
8187
- return Buffer.isBuffer(value) || value instanceof Uint8Array;
8188
- }
8189
- function isEncoding(encoding) {
8190
- return Buffer.isEncoding(encoding);
8191
- }
8192
- function alloc(size, fill, encoding) {
8193
- return Buffer.alloc(size, fill, encoding);
8194
- }
8195
- function allocUnsafe(size) {
8196
- return Buffer.allocUnsafe(size);
8197
- }
8198
- function allocUnsafeSlow(size) {
8199
- return Buffer.allocUnsafeSlow(size);
8200
- }
8201
- function byteLength(string, encoding) {
8202
- return Buffer.byteLength(string, encoding);
8203
- }
8204
- function compare(a, b) {
8205
- return Buffer.compare(a, b);
8206
- }
8207
- function concat(buffers, totalLength) {
8208
- return Buffer.concat(buffers, totalLength);
8209
- }
8210
- function copy(source, target, targetStart, start, end) {
8211
- return toBuffer(source).copy(target, targetStart, start, end);
8212
- }
8213
- function equals(a, b) {
8214
- return toBuffer(a).equals(b);
8215
- }
8216
- function fill(buffer, value, offset, end, encoding) {
8217
- return toBuffer(buffer).fill(value, offset, end, encoding);
8218
- }
8219
- function from(value, encodingOrOffset, length) {
8220
- return Buffer.from(value, encodingOrOffset, length);
8221
- }
8222
- function includes(buffer, value, byteOffset, encoding) {
8223
- return toBuffer(buffer).includes(value, byteOffset, encoding);
8224
- }
8225
- function indexOf(buffer, value, byfeOffset, encoding) {
8226
- return toBuffer(buffer).indexOf(value, byfeOffset, encoding);
8227
- }
8228
- function lastIndexOf(buffer, value, byteOffset, encoding) {
8229
- return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding);
8230
- }
8231
- function swap16(buffer) {
8232
- return toBuffer(buffer).swap16();
8233
- }
8234
- function swap32(buffer) {
8235
- return toBuffer(buffer).swap32();
8236
- }
8237
- function swap64(buffer) {
8238
- return toBuffer(buffer).swap64();
8239
- }
8240
- function toBuffer(buffer) {
8241
- if (Buffer.isBuffer(buffer)) return buffer;
8242
- return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
8243
- }
8244
- function toString(buffer, encoding, start, end) {
8245
- return toBuffer(buffer).toString(encoding, start, end);
8246
- }
8247
- function write(buffer, string, offset, length, encoding) {
8248
- return toBuffer(buffer).write(string, offset, length, encoding);
8249
- }
8250
- function readDoubleBE(buffer, offset) {
8251
- return toBuffer(buffer).readDoubleBE(offset);
8252
- }
8253
- function readDoubleLE(buffer, offset) {
8254
- return toBuffer(buffer).readDoubleLE(offset);
8255
- }
8256
- function readFloatBE(buffer, offset) {
8257
- return toBuffer(buffer).readFloatBE(offset);
8258
- }
8259
- function readFloatLE(buffer, offset) {
8260
- return toBuffer(buffer).readFloatLE(offset);
8261
- }
8262
- function readInt32BE(buffer, offset) {
8263
- return toBuffer(buffer).readInt32BE(offset);
8264
- }
8265
- function readInt32LE(buffer, offset) {
8266
- return toBuffer(buffer).readInt32LE(offset);
8267
- }
8268
- function readUInt32BE(buffer, offset) {
8269
- return toBuffer(buffer).readUInt32BE(offset);
8270
- }
8271
- function readUInt32LE(buffer, offset) {
8272
- return toBuffer(buffer).readUInt32LE(offset);
8273
- }
8274
- function writeDoubleBE(buffer, value, offset) {
8275
- return toBuffer(buffer).writeDoubleBE(value, offset);
8276
- }
8277
- function writeDoubleLE(buffer, value, offset) {
8278
- return toBuffer(buffer).writeDoubleLE(value, offset);
8279
- }
8280
- function writeFloatBE(buffer, value, offset) {
8281
- return toBuffer(buffer).writeFloatBE(value, offset);
8282
- }
8283
- function writeFloatLE(buffer, value, offset) {
8284
- return toBuffer(buffer).writeFloatLE(value, offset);
8285
- }
8286
- function writeInt32BE(buffer, value, offset) {
8287
- return toBuffer(buffer).writeInt32BE(value, offset);
8288
- }
8289
- function writeInt32LE(buffer, value, offset) {
8290
- return toBuffer(buffer).writeInt32LE(value, offset);
8291
- }
8292
- function writeUInt32BE(buffer, value, offset) {
8293
- return toBuffer(buffer).writeUInt32BE(value, offset);
8294
- }
8295
- function writeUInt32LE(buffer, value, offset) {
8296
- return toBuffer(buffer).writeUInt32LE(value, offset);
8297
- }
8298
- module.exports = {
8299
- isBuffer,
8300
- isEncoding,
8301
- alloc,
8302
- allocUnsafe,
8303
- allocUnsafeSlow,
8304
- byteLength,
8305
- compare,
8306
- concat,
8307
- copy,
8308
- equals,
8309
- fill,
8310
- from,
8311
- includes,
8312
- indexOf,
8313
- lastIndexOf,
8314
- swap16,
8315
- swap32,
8316
- swap64,
8317
- toBuffer,
8318
- toString,
8319
- write,
8320
- readDoubleBE,
8321
- readDoubleLE,
8322
- readFloatBE,
8323
- readFloatLE,
8324
- readInt32BE,
8325
- readInt32LE,
8326
- readUInt32BE,
8327
- readUInt32LE,
8328
- writeDoubleBE,
8329
- writeDoubleLE,
8330
- writeFloatBE,
8331
- writeFloatLE,
8332
- writeInt32BE,
8333
- writeInt32LE,
8334
- writeUInt32BE,
8335
- writeUInt32LE
8257
+ },
8258
+ pull
8336
8259
  };
8337
- }));
8338
- //#endregion
8339
- //#region ../../node_modules/.pnpm/text-decoder@1.2.7/node_modules/text-decoder/lib/pass-through-decoder.js
8340
- var require_pass_through_decoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8341
- const b4a = require_b4a();
8342
- module.exports = class PassThroughDecoder {
8343
- constructor(encoding) {
8344
- this.encoding = encoding;
8345
- }
8346
- get remaining() {
8347
- return 0;
8348
- }
8349
- decode(data) {
8350
- return b4a.toString(data, this.encoding);
8351
- }
8352
- flush() {
8353
- return "";
8354
- }
8260
+ }
8261
+ const CHECKSUM_SPACE = 32;
8262
+ function validateChecksum(block) {
8263
+ const stored = readOctal(block, 148, 8);
8264
+ let sum = 0;
8265
+ for (let i = 0; i < block.length; i++) if (i >= 148 && i < 156) sum += CHECKSUM_SPACE;
8266
+ else sum += block[i];
8267
+ return stored === sum;
8268
+ }
8269
+ function parseUstarHeader(block, strict) {
8270
+ if (strict && !validateChecksum(block)) throw new Error("Invalid tar header checksum.");
8271
+ const typeflag = readString(block, 156, 1);
8272
+ const header = {
8273
+ name: readString(block, 0, 100),
8274
+ mode: readOctal(block, 100, 8),
8275
+ uid: readNumeric(block, 108, 8),
8276
+ gid: readNumeric(block, 116, 8),
8277
+ size: readNumeric(block, 124, 12),
8278
+ mtime: /* @__PURE__ */ new Date(readNumeric(block, 136, 12) * 1e3),
8279
+ type: FLAGTYPE[typeflag] || "file",
8280
+ linkname: readString(block, 157, 100)
8355
8281
  };
8356
- }));
8357
- //#endregion
8358
- //#region ../../node_modules/.pnpm/text-decoder@1.2.7/node_modules/text-decoder/lib/utf8-decoder.js
8359
- var require_utf8_decoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8360
- const b4a = require_b4a();
8361
- /**
8362
- * https://encoding.spec.whatwg.org/#utf-8-decoder
8363
- */
8364
- module.exports = class UTF8Decoder {
8365
- constructor() {
8366
- this._reset();
8367
- }
8368
- get remaining() {
8369
- return this.bytesSeen;
8370
- }
8371
- decode(data) {
8372
- if (data.byteLength === 0) return "";
8373
- if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
8374
- this.bytesSeen = trailingBytesSeen(data);
8375
- return b4a.toString(data, "utf8");
8376
- }
8377
- let result = "";
8378
- let start = 0;
8379
- if (this.bytesNeeded > 0) {
8380
- while (start < data.byteLength) {
8381
- const byte = data[start];
8382
- if (byte < this.lowerBoundary || byte > this.upperBoundary) {
8383
- result += "�";
8384
- this._reset();
8385
- break;
8386
- }
8387
- this.lowerBoundary = 128;
8388
- this.upperBoundary = 191;
8389
- this.codePoint = this.codePoint << 6 | byte & 63;
8390
- this.bytesSeen++;
8391
- start++;
8392
- if (this.bytesSeen === this.bytesNeeded) {
8393
- result += String.fromCodePoint(this.codePoint);
8394
- this._reset();
8395
- break;
8282
+ const magic = readString(block, 257, 6);
8283
+ if (magic.trim() === "ustar") {
8284
+ header.uname = readString(block, 265, 32);
8285
+ header.gname = readString(block, 297, 32);
8286
+ }
8287
+ if (magic === "ustar") header.prefix = readString(block, 345, 155);
8288
+ return header;
8289
+ }
8290
+ const PAX_MAPPING = {
8291
+ path: ["name", (v) => v],
8292
+ linkpath: ["linkname", (v) => v],
8293
+ size: ["size", (v) => /^\d+$/.test(v) && Number.isSafeInteger(+v) ? +v : NaN],
8294
+ mtime: ["mtime", parseFloat],
8295
+ uid: ["uid", (v) => parseInt(v, 10)],
8296
+ gid: ["gid", (v) => parseInt(v, 10)],
8297
+ uname: ["uname", (v) => v],
8298
+ gname: ["gname", (v) => v]
8299
+ };
8300
+ function parsePax(buffer) {
8301
+ const overrides = Object.create(null);
8302
+ const pax = Object.create(null);
8303
+ let isPax = false;
8304
+ let offset = 0;
8305
+ while (offset < buffer.length) {
8306
+ const spaceIndex = buffer.indexOf(32, offset);
8307
+ if (spaceIndex === -1) break;
8308
+ const length = parseInt(decoder.decode(buffer.subarray(offset, spaceIndex)), 10);
8309
+ if (!(length > 0)) break;
8310
+ const recordEnd = offset + length;
8311
+ const recordStr = decoder.decode(buffer.subarray(spaceIndex + 1, recordEnd - 1));
8312
+ const equalsIndex = recordStr.indexOf("=");
8313
+ if (equalsIndex > 0) {
8314
+ const key = recordStr.slice(0, equalsIndex);
8315
+ const value = recordStr.slice(equalsIndex + 1);
8316
+ pax[key] = value;
8317
+ isPax = true;
8318
+ if (Object.hasOwn(PAX_MAPPING, key)) {
8319
+ const [targetKey, parser] = PAX_MAPPING[key];
8320
+ const parsedValue = parser(value);
8321
+ if (typeof parsedValue === "string" || !Number.isNaN(parsedValue)) overrides[targetKey] = parsedValue;
8322
+ }
8323
+ }
8324
+ offset = recordEnd;
8325
+ }
8326
+ if (isPax) overrides.pax = pax;
8327
+ return overrides;
8328
+ }
8329
+ function applyOverrides(header, overrides) {
8330
+ if (overrides.name !== void 0) header.name = overrides.name;
8331
+ if (overrides.linkname !== void 0) header.linkname = overrides.linkname;
8332
+ if (overrides.size !== void 0) header.size = overrides.size;
8333
+ if (overrides.mtime !== void 0) header.mtime = /* @__PURE__ */ new Date(overrides.mtime * 1e3);
8334
+ if (overrides.uid !== void 0) header.uid = overrides.uid;
8335
+ if (overrides.gid !== void 0) header.gid = overrides.gid;
8336
+ if (overrides.uname !== void 0) header.uname = overrides.uname;
8337
+ if (overrides.gname !== void 0) header.gname = overrides.gname;
8338
+ if (overrides.pax) header.pax = Object.assign({}, header.pax ?? {}, overrides.pax);
8339
+ }
8340
+ function getMetaParser(type) {
8341
+ switch (type) {
8342
+ case "pax-global-header":
8343
+ case "pax-header": return parsePax;
8344
+ case "gnu-long-name": return (data) => ({ name: readString(data, 0, data.length) });
8345
+ case "gnu-long-link-name": return (data) => ({ linkname: readString(data, 0, data.length) });
8346
+ default: return;
8347
+ }
8348
+ }
8349
+ const STATE_HEADER = 0;
8350
+ const STATE_BODY = 1;
8351
+ const MAX_META_SIZE = 8 * 1024 * 1024;
8352
+ const truncateErr = /* @__PURE__ */ new Error("Tar archive is truncated.");
8353
+ function createUnpacker(options = {}) {
8354
+ const strict = options.strict ?? false;
8355
+ const { available, peek, push, discard, pull } = createChunkQueue();
8356
+ let state = STATE_HEADER;
8357
+ let ended = false;
8358
+ let done = false;
8359
+ let eof = false;
8360
+ let currentEntry = null;
8361
+ const paxGlobals = {};
8362
+ let nextEntryOverrides = {};
8363
+ const unpacker = {
8364
+ isEntryActive: () => state === STATE_BODY,
8365
+ isBodyComplete: () => !currentEntry || currentEntry.remaining === 0,
8366
+ canFinish: () => !currentEntry || available() >= currentEntry.remaining + currentEntry.padding,
8367
+ bodyBytes: () => currentEntry && currentEntry.remaining > 0 ? Math.min(currentEntry.remaining, available()) : 0,
8368
+ write(chunk) {
8369
+ if (ended) throw new Error("Archive already ended.");
8370
+ push(chunk);
8371
+ },
8372
+ end() {
8373
+ ended = true;
8374
+ },
8375
+ readHeader() {
8376
+ if (state !== STATE_HEADER) throw new Error("Cannot read header while an entry is active");
8377
+ if (done) return void 0;
8378
+ while (!done) {
8379
+ if (available() < 512) {
8380
+ if (ended) {
8381
+ if (available() > 0 && strict) throw truncateErr;
8382
+ done = true;
8383
+ return;
8396
8384
  }
8385
+ return null;
8397
8386
  }
8398
- if (this.bytesNeeded > 0) return result;
8399
- }
8400
- const trailing = trailingIncomplete(data, start);
8401
- const end = data.byteLength - trailing;
8402
- if (end > start) result += b4a.toString(data, "utf8", start, end);
8403
- for (let i = end; i < data.byteLength; i++) {
8404
- const byte = data[i];
8405
- if (this.bytesNeeded === 0) {
8406
- if (byte <= 127) {
8407
- this.bytesSeen = 0;
8408
- result += String.fromCharCode(byte);
8409
- } else if (byte >= 194 && byte <= 223) {
8410
- this.bytesNeeded = 2;
8411
- this.bytesSeen = 1;
8412
- this.codePoint = byte & 31;
8413
- } else if (byte >= 224 && byte <= 239) {
8414
- if (byte === 224) this.lowerBoundary = 160;
8415
- else if (byte === 237) this.upperBoundary = 159;
8416
- this.bytesNeeded = 3;
8417
- this.bytesSeen = 1;
8418
- this.codePoint = byte & 15;
8419
- } else if (byte >= 240 && byte <= 244) {
8420
- if (byte === 240) this.lowerBoundary = 144;
8421
- else if (byte === 244) this.upperBoundary = 143;
8422
- this.bytesNeeded = 4;
8423
- this.bytesSeen = 1;
8424
- this.codePoint = byte & 7;
8425
- } else {
8426
- this.bytesSeen = 1;
8427
- result += "�";
8387
+ const headerBlock = peek(512);
8388
+ if (isZeroBlock(headerBlock)) {
8389
+ if (available() < 512 * 2) {
8390
+ if (ended) {
8391
+ if (strict) throw truncateErr;
8392
+ done = true;
8393
+ return;
8394
+ }
8395
+ return null;
8396
+ }
8397
+ if (isZeroBlock(peek(512 * 2).subarray(512))) {
8398
+ discard(512 * 2);
8399
+ done = true;
8400
+ eof = true;
8401
+ return;
8428
8402
  }
8403
+ if (strict) throw new Error("Invalid tar header.");
8404
+ discard(512);
8429
8405
  continue;
8430
8406
  }
8431
- if (byte < this.lowerBoundary || byte > this.upperBoundary) {
8432
- result += "�";
8433
- i--;
8434
- this._reset();
8407
+ let internalHeader;
8408
+ try {
8409
+ internalHeader = parseUstarHeader(headerBlock, strict);
8410
+ } catch (err) {
8411
+ if (strict) throw err;
8412
+ discard(512);
8435
8413
  continue;
8436
8414
  }
8437
- this.lowerBoundary = 128;
8438
- this.upperBoundary = 191;
8439
- this.codePoint = this.codePoint << 6 | byte & 63;
8440
- this.bytesSeen++;
8441
- if (this.bytesSeen === this.bytesNeeded) {
8442
- result += String.fromCodePoint(this.codePoint);
8443
- this._reset();
8415
+ const metaParser = getMetaParser(internalHeader.type);
8416
+ if (metaParser) {
8417
+ if (internalHeader.size > MAX_META_SIZE) throw new Error("Tar metadata entry exceeds maximum size.");
8418
+ const paddedSize = internalHeader.size + (-internalHeader.size & 511);
8419
+ if (available() < 512 + paddedSize) {
8420
+ if (ended && strict) throw truncateErr;
8421
+ return null;
8422
+ }
8423
+ discard(512);
8424
+ const overrides = metaParser(pull(paddedSize).subarray(0, internalHeader.size));
8425
+ if (nextEntryOverrides.pax) nextEntryOverrides = {};
8426
+ const target = internalHeader.type === "pax-global-header" ? paxGlobals : nextEntryOverrides;
8427
+ for (const key in overrides) target[key] = overrides[key];
8428
+ continue;
8429
+ }
8430
+ discard(512);
8431
+ const header = internalHeader;
8432
+ if (internalHeader.prefix) header.name = `${internalHeader.prefix}/${header.name}`;
8433
+ applyOverrides(header, paxGlobals);
8434
+ applyOverrides(header, nextEntryOverrides);
8435
+ let archiveSize = header.size;
8436
+ if (isBodyless(header)) {
8437
+ archiveSize = 0;
8438
+ header.size = 0;
8439
+ } else if (header.name.endsWith("/") && header.type === "file") {
8440
+ header.type = DIRECTORY;
8441
+ header.size = 0;
8442
+ }
8443
+ nextEntryOverrides = {};
8444
+ currentEntry = {
8445
+ header,
8446
+ remaining: archiveSize,
8447
+ padding: -archiveSize & 511
8448
+ };
8449
+ state = STATE_BODY;
8450
+ return header;
8451
+ }
8452
+ },
8453
+ streamBody(callback) {
8454
+ if (state !== STATE_BODY || !currentEntry || currentEntry.remaining === 0) return 0;
8455
+ const bytesToFeed = Math.min(currentEntry.remaining, available());
8456
+ if (bytesToFeed === 0) return 0;
8457
+ const fed = pull(bytesToFeed, callback);
8458
+ currentEntry.remaining -= fed;
8459
+ return fed;
8460
+ },
8461
+ skipPadding() {
8462
+ if (state !== STATE_BODY || !currentEntry) return true;
8463
+ if (currentEntry.remaining > 0) throw new Error("Body not fully consumed");
8464
+ if (available() < currentEntry.padding) return false;
8465
+ discard(currentEntry.padding);
8466
+ currentEntry = null;
8467
+ state = STATE_HEADER;
8468
+ return true;
8469
+ },
8470
+ skipEntry() {
8471
+ if (state !== STATE_BODY || !currentEntry) return true;
8472
+ const toDiscard = Math.min(currentEntry.remaining, available());
8473
+ if (toDiscard > 0) {
8474
+ discard(toDiscard);
8475
+ currentEntry.remaining -= toDiscard;
8476
+ }
8477
+ if (currentEntry.remaining > 0) return false;
8478
+ return unpacker.skipPadding();
8479
+ },
8480
+ validateEOF() {
8481
+ if (strict) {
8482
+ if (!eof) throw truncateErr;
8483
+ if (available() > 0) {
8484
+ if (pull(available()).some((byte) => byte !== 0)) throw new Error("Invalid EOF.");
8444
8485
  }
8445
8486
  }
8446
- return result;
8447
- }
8448
- flush() {
8449
- const result = this.bytesNeeded > 0 ? "�" : "";
8450
- this._reset();
8451
- return result;
8452
- }
8453
- _reset() {
8454
- this.codePoint = 0;
8455
- this.bytesNeeded = 0;
8456
- this.bytesSeen = 0;
8457
- this.lowerBoundary = 128;
8458
- this.upperBoundary = 191;
8459
8487
  }
8460
8488
  };
8461
- function trailingIncomplete(data, start) {
8462
- const len = data.byteLength;
8463
- if (len <= start) return 0;
8464
- const limit = Math.max(start, len - 4);
8465
- let i = len - 1;
8466
- while (i > limit && (data[i] & 192) === 128) i--;
8467
- if (i < start) return 0;
8468
- const byte = data[i];
8469
- let needed;
8470
- if (byte <= 127) return 0;
8471
- if (byte >= 194 && byte <= 223) needed = 2;
8472
- else if (byte >= 224 && byte <= 239) needed = 3;
8473
- else if (byte >= 240 && byte <= 244) needed = 4;
8474
- else return 0;
8475
- const available = len - i;
8476
- return available < needed ? available : 0;
8477
- }
8478
- function trailingBytesSeen(data) {
8479
- const len = data.byteLength;
8480
- if (len === 0) return 0;
8481
- const last = data[len - 1];
8482
- if (last <= 127) return 0;
8483
- if ((last & 192) !== 128) return 1;
8484
- const limit = Math.max(0, len - 4);
8485
- let i = len - 2;
8486
- while (i >= limit && (data[i] & 192) === 128) i--;
8487
- if (i < 0) return 1;
8488
- const first = data[i];
8489
- let needed;
8490
- if (first >= 194 && first <= 223) needed = 2;
8491
- else if (first >= 224 && first <= 239) needed = 3;
8492
- else if (first >= 240 && first <= 244) needed = 4;
8493
- else return 1;
8494
- if (len - i !== needed) return 1;
8495
- if (needed >= 3) {
8496
- const second = data[i + 1];
8497
- if (first === 224 && second < 160) return 1;
8498
- if (first === 237 && second > 159) return 1;
8499
- if (first === 240 && second < 144) return 1;
8500
- if (first === 244 && second > 143) return 1;
8501
- }
8502
- return 0;
8503
- }
8504
- }));
8489
+ return unpacker;
8490
+ }
8491
+ function isZeroBlock(block) {
8492
+ if (block.byteOffset % 8 === 0) {
8493
+ const view = new BigUint64Array(block.buffer, block.byteOffset, block.length / 8);
8494
+ for (let i = 0; i < view.length; i++) if (view[i] !== 0n) return false;
8495
+ return true;
8496
+ }
8497
+ for (let i = 0; i < block.length; i++) if (block[i] !== 0) return false;
8498
+ return true;
8499
+ }
8505
8500
  //#endregion
8506
- //#region ../../node_modules/.pnpm/text-decoder@1.2.7/node_modules/text-decoder/index.js
8507
- var require_text_decoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8508
- const PassThroughDecoder = require_pass_through_decoder();
8509
- const UTF8Decoder = require_utf8_decoder();
8510
- module.exports = class TextDecoder {
8511
- constructor(encoding = "utf8") {
8512
- this.encoding = normalizeEncoding(encoding);
8513
- switch (this.encoding) {
8514
- case "utf8":
8515
- this.decoder = new UTF8Decoder();
8516
- break;
8517
- case "utf16le":
8518
- case "base64": throw new Error("Unsupported encoding: " + this.encoding);
8519
- default: this.decoder = new PassThroughDecoder(this.encoding);
8520
- }
8521
- }
8522
- get remaining() {
8523
- return this.decoder.remaining;
8524
- }
8525
- push(data) {
8526
- if (typeof data === "string") return data;
8527
- return this.decoder.decode(data);
8528
- }
8529
- write(data) {
8530
- return this.push(data);
8501
+ //#region ../../node_modules/.pnpm/modern-tar@0.7.7/node_modules/modern-tar/dist/fs/index.js
8502
+ function validateBounds(targetPath, destDir, errorMessage) {
8503
+ const target = path$1.resolve(targetPath);
8504
+ const dest = path$1.resolve(destDir);
8505
+ if (target !== dest && !target.startsWith(dest + path$1.sep)) throw new Error(errorMessage);
8506
+ }
8507
+ const win32Reserved = {
8508
+ ":": "",
8509
+ "<": "",
8510
+ ">": "",
8511
+ "|": "",
8512
+ "?": "",
8513
+ "*": "",
8514
+ "\"": ""
8515
+ };
8516
+ function normalizeName(name) {
8517
+ const path = name.replace(/\\/g, "/");
8518
+ if (path.split("/").includes("..") || /^[a-zA-Z]:\.\./.test(path)) throw new Error(`${name} points outside extraction directory`);
8519
+ let relative = path;
8520
+ if (/^[a-zA-Z]:/.test(relative)) relative = relative.replace(/^[a-zA-Z]:[/\\]?/, "");
8521
+ else if (relative.startsWith("/")) relative = relative.replace(/^\/+/, "");
8522
+ if (process.platform === "win32") return relative.replace(/[<>:"|?*]/g, (char) => win32Reserved[char]);
8523
+ return relative;
8524
+ }
8525
+ const normalizeHeaderName = (s) => normalizeName(s.replace(/\/+$/, ""));
8526
+ const createOperationQueue = (concurrency) => {
8527
+ let active = 0;
8528
+ const tasks = [];
8529
+ let head = 0;
8530
+ let idle = null;
8531
+ let resolveIdle = null;
8532
+ const ensureIdle = () => idle ??= new Promise((resolve) => resolveIdle = resolve);
8533
+ const flush = () => {
8534
+ while (active < concurrency && head < tasks.length) {
8535
+ const task = tasks[head++];
8536
+ active++;
8537
+ task().finally(() => {
8538
+ active--;
8539
+ flush();
8540
+ });
8531
8541
  }
8532
- end(data) {
8533
- let result = "";
8534
- if (data) result = this.push(data);
8535
- result += this.decoder.flush();
8536
- return result;
8542
+ if (head === tasks.length) {
8543
+ tasks.length = 0;
8544
+ head = 0;
8545
+ if (active === 0 && resolveIdle) {
8546
+ resolveIdle();
8547
+ idle = null;
8548
+ resolveIdle = null;
8549
+ }
8537
8550
  }
8538
8551
  };
8539
- function normalizeEncoding(encoding) {
8540
- encoding = encoding.toLowerCase();
8541
- switch (encoding) {
8542
- case "utf8":
8543
- case "utf-8": return "utf8";
8544
- case "ucs2":
8545
- case "ucs-2":
8546
- case "utf16le":
8547
- case "utf-16le": return "utf16le";
8548
- case "latin1":
8549
- case "binary": return "latin1";
8550
- case "base64":
8551
- case "ascii":
8552
- case "hex": return encoding;
8553
- default: throw new Error("Unknown encoding: " + encoding);
8554
- }
8555
- }
8556
- }));
8557
- //#endregion
8558
- //#region ../../node_modules/.pnpm/streamx@2.26.0/node_modules/streamx/lib/errors.js
8559
- var require_errors = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8560
- module.exports = class StreamError extends Error {
8561
- constructor(msg, code, fn = StreamError) {
8562
- super(msg);
8563
- this.code = code;
8564
- if (Error.captureStackTrace) Error.captureStackTrace(this, fn);
8552
+ return {
8553
+ add(op) {
8554
+ const wasIdle = active === 0 && head === tasks.length;
8555
+ return new Promise((resolve, reject) => {
8556
+ tasks.push(() => Promise.resolve().then(op).then(resolve, reject));
8557
+ if (wasIdle) ensureIdle();
8558
+ flush();
8559
+ });
8560
+ },
8561
+ onIdle() {
8562
+ return active === 0 && head === tasks.length ? Promise.resolve() : ensureIdle();
8565
8563
  }
8566
- static isStreamDestroyed(err) {
8567
- return err && err.code === "STREAM_DESTROYED";
8564
+ };
8565
+ };
8566
+ const BATCH_BYTES = 256 * 1024;
8567
+ 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;
8568
+ const STATE_OPENING = 1;
8569
+ const STATE_OPEN = 2;
8570
+ const STATE_CLOSED = 3;
8571
+ const STATE_FAILED = 4;
8572
+ const DRAINED_PROMISE = Promise.resolve();
8573
+ function createFileSink(path, { mode = 438, mtime } = {}) {
8574
+ let state = STATE_OPENING;
8575
+ let flushing = false;
8576
+ let fd = null;
8577
+ let queue = [];
8578
+ let spare = [];
8579
+ let bytes = 0;
8580
+ let storedError = null;
8581
+ let endPromise = null;
8582
+ let endResolve = null;
8583
+ let endReject = null;
8584
+ const waitResolves = [];
8585
+ const waitRejects = [];
8586
+ const settleWaiters = () => {
8587
+ if (waitResolves.length === 0) return;
8588
+ for (let i = 0; i < waitResolves.length; i++) waitResolves[i]();
8589
+ waitResolves.length = 0;
8590
+ waitRejects.length = 0;
8591
+ };
8592
+ const failWaiters = (error) => {
8593
+ if (waitRejects.length === 0) return;
8594
+ for (let i = 0; i < waitRejects.length; i++) waitRejects[i](error);
8595
+ waitRejects.length = 0;
8596
+ waitResolves.length = 0;
8597
+ };
8598
+ const resetBuffers = () => {
8599
+ bytes = 0;
8600
+ queue.length = 0;
8601
+ spare.length = 0;
8602
+ };
8603
+ const finish = () => {
8604
+ state = STATE_CLOSED;
8605
+ endResolve?.();
8606
+ settleWaiters();
8607
+ };
8608
+ const swapQueues = () => {
8609
+ const current = queue;
8610
+ queue = spare;
8611
+ spare = current;
8612
+ queue.length = 0;
8613
+ return current;
8614
+ };
8615
+ const fail = (error) => {
8616
+ if (storedError) return;
8617
+ storedError = error;
8618
+ state = STATE_FAILED;
8619
+ resetBuffers();
8620
+ flushing = false;
8621
+ const fdToClose = fd;
8622
+ fd = null;
8623
+ if (fdToClose !== null) fs$1.ftruncate(fdToClose, 0, () => fs$1.close(fdToClose));
8624
+ endReject?.(error);
8625
+ failWaiters(error);
8626
+ };
8627
+ const close = () => {
8628
+ if (fd === null) {
8629
+ finish();
8630
+ return;
8568
8631
  }
8569
- static isPrematureClose(err) {
8570
- return err && err.code === "PREMATURE_CLOSE";
8632
+ const fdToClose = fd;
8633
+ fd = null;
8634
+ if (mtime) fs$1.futimes(fdToClose, mtime, mtime, (err) => {
8635
+ if (err) return fail(err);
8636
+ fs$1.close(fdToClose, (closeErr) => {
8637
+ if (closeErr) fail(closeErr);
8638
+ else finish();
8639
+ });
8640
+ });
8641
+ else fs$1.close(fdToClose, (err) => {
8642
+ if (err) fail(err);
8643
+ else finish();
8644
+ });
8645
+ };
8646
+ const flush = () => {
8647
+ if (flushing || queue.length === 0 || state !== STATE_OPEN) return;
8648
+ flushing = true;
8649
+ const bufs = swapQueues();
8650
+ const onDone = (err, written = 0) => {
8651
+ if (err) return fail(err);
8652
+ flushing = false;
8653
+ bytes -= written;
8654
+ spare.length = 0;
8655
+ if (bytes < BATCH_BYTES) settleWaiters();
8656
+ if (queue.length > 0) flush();
8657
+ else if (endResolve) close();
8658
+ };
8659
+ if (bufs.length === 1) {
8660
+ const buf = bufs[0];
8661
+ fs$1.write(fd, buf, 0, buf.length, null, onDone);
8662
+ } else fs$1.writev(fd, bufs, onDone);
8663
+ };
8664
+ const onOpen = (err, openFd) => {
8665
+ if (err) return fail(err);
8666
+ if (state === STATE_CLOSED || state === STATE_FAILED) {
8667
+ fs$1.close(openFd);
8668
+ return;
8571
8669
  }
8572
- static isAborted(err) {
8573
- return err && err.code === "ABORTED";
8670
+ fd = openFd;
8671
+ state = STATE_OPEN;
8672
+ if (endResolve) if (queue.length > 0) flush();
8673
+ else close();
8674
+ else if (bytes >= BATCH_BYTES && !flushing) flush();
8675
+ else settleWaiters();
8676
+ };
8677
+ const write = (chunk) => {
8678
+ if (storedError || state >= STATE_CLOSED || endResolve) return false;
8679
+ const buf = Buffer.isBuffer(chunk) ? chunk : chunk instanceof Uint8Array ? Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) : Buffer.from(chunk);
8680
+ if (buf.length === 0) return bytes < BATCH_BYTES;
8681
+ queue.push(buf);
8682
+ bytes += buf.length;
8683
+ if (state === STATE_OPEN && !flushing && bytes >= BATCH_BYTES) flush();
8684
+ return bytes < BATCH_BYTES;
8685
+ };
8686
+ const waitDrain = () => {
8687
+ if (state === STATE_OPENING || state === STATE_OPEN && bytes >= BATCH_BYTES) return new Promise((resolve, reject) => {
8688
+ waitResolves.push(resolve);
8689
+ waitRejects.push(reject);
8690
+ });
8691
+ return DRAINED_PROMISE;
8692
+ };
8693
+ const end = () => {
8694
+ if (state >= STATE_CLOSED) return DRAINED_PROMISE;
8695
+ if (storedError) return Promise.reject(storedError);
8696
+ if (endPromise) return endPromise;
8697
+ endPromise = new Promise((resolve, reject) => {
8698
+ endResolve = resolve;
8699
+ endReject = reject;
8700
+ if (state === STATE_OPEN && !flushing) if (queue.length > 0) flush();
8701
+ else close();
8702
+ });
8703
+ return endPromise;
8704
+ };
8705
+ const destroy = (error) => {
8706
+ if (error) {
8707
+ fail(error);
8708
+ return;
8574
8709
  }
8575
- get name() {
8576
- return "StreamError";
8710
+ if (state >= STATE_CLOSED || storedError) return;
8711
+ resetBuffers();
8712
+ flushing = false;
8713
+ if (fd !== null) {
8714
+ const fdToClose = fd;
8715
+ fd = null;
8716
+ fs$1.close(fdToClose);
8577
8717
  }
8578
- static STREAM_DESTROYED() {
8579
- return new StreamError("Stream was destroyed", "STREAM_DESTROYED", StreamError.STREAM_DESTROYED);
8718
+ finish();
8719
+ };
8720
+ fs$1.open(path, CREATE_FLAGS, mode, (err, openFd) => {
8721
+ if (!err || err.code !== "EEXIST") return onOpen(err, openFd);
8722
+ fs$1.rm(path, { force: true }, (rmErr) => {
8723
+ if (rmErr) return fail(rmErr);
8724
+ fs$1.open(path, CREATE_FLAGS, mode, onOpen);
8725
+ });
8726
+ });
8727
+ return {
8728
+ write,
8729
+ end,
8730
+ destroy,
8731
+ waitDrain
8732
+ };
8733
+ }
8734
+ const createCache = () => {
8735
+ const m = /* @__PURE__ */ new Map();
8736
+ return {
8737
+ get(k) {
8738
+ const v = m.get(k);
8739
+ if (m.delete(k)) m.set(k, v);
8740
+ return v;
8741
+ },
8742
+ set(k, v) {
8743
+ if (m.set(k, v).size > 1e4) m.delete(m.keys().next().value);
8744
+ },
8745
+ clear() {
8746
+ m.clear();
8580
8747
  }
8581
- static PREMATURE_CLOSE() {
8582
- return new StreamError("Premature close", "PREMATURE_CLOSE", StreamError.PREMATURE_CLOSE);
8748
+ };
8749
+ };
8750
+ const ENOENT = "ENOENT";
8751
+ const MAX_SYMLINKS = 64;
8752
+ const linkSep = process.platform === "win32" ? /[/\\]/ : "/";
8753
+ const linkParts = (linkname) => linkname.split(linkSep).filter((part) => part && part !== ".");
8754
+ const createPathCache = (destDirPath, options, opQueue, concurrency) => {
8755
+ const { maxDepth = 1024, dmode } = options;
8756
+ const dirPromises = createCache();
8757
+ const pathConflicts = /* @__PURE__ */ new Map();
8758
+ const deferredLinks = [];
8759
+ let symlinks;
8760
+ const realDirCache = createCache();
8761
+ const initializeDestDir = async (destDirPath) => {
8762
+ const symbolic = path$1.resolve(destDirPath);
8763
+ try {
8764
+ await fsp.mkdir(symbolic, { recursive: true });
8765
+ } catch (err) {
8766
+ if (err.code === ENOENT) {
8767
+ const parentDir = path$1.dirname(symbolic);
8768
+ if (parentDir === symbolic) throw err;
8769
+ await fsp.mkdir(parentDir, { recursive: true });
8770
+ await fsp.mkdir(symbolic, { recursive: true });
8771
+ } else throw err;
8583
8772
  }
8584
- static ABORTED() {
8585
- return new StreamError("Stream aborted", "ABORTED", StreamError.ABORTED);
8773
+ try {
8774
+ return {
8775
+ symbolic,
8776
+ real: await fsp.realpath(symbolic)
8777
+ };
8778
+ } catch (err) {
8779
+ if (err.code === ENOENT) return {
8780
+ symbolic,
8781
+ real: symbolic
8782
+ };
8783
+ throw err;
8586
8784
  }
8587
8785
  };
8588
- }));
8589
- //#endregion
8590
- //#region ../../node_modules/.pnpm/streamx@2.26.0/node_modules/streamx/index.js
8591
- var require_streamx = /* @__PURE__ */ __commonJSMin(((exports, module) => {
8592
- const { EventEmitter } = require_default();
8593
- const FIFO = require_fast_fifo();
8594
- const TextDecoder = require_text_decoder();
8595
- const StreamError = require_errors();
8596
- const qmt = typeof queueMicrotask === "undefined" ? (fn) => global.process.nextTick(fn) : queueMicrotask;
8597
- const OPENING = 1;
8598
- const PREDESTROYING = 2;
8599
- const DESTROYING = 4;
8600
- const DESTROYED = 8;
8601
- const NOT_OPENING = 536870910;
8602
- const NOT_PREDESTROYING = 536870909;
8603
- const READ_UPDATING = 32;
8604
- const READ_PRIMARY = 64;
8605
- const READ_QUEUED = 128;
8606
- const READ_RESUMED = 256;
8607
- const READ_PIPE_DRAINED = 512;
8608
- const READ_ENDING = 1024;
8609
- const READ_EMIT_DATA = 2048;
8610
- const READ_EMIT_READABLE = 4096;
8611
- const READ_EMITTED_READABLE = 8192;
8612
- const READ_DONE = 16384;
8613
- const READ_NEXT_TICK = 32768;
8614
- const READ_READ_AHEAD = 131072;
8615
- const READ_FLOWING = 768;
8616
- const READ_ACTIVE_AND_NEEDS_PUSH = 65552;
8617
- const READ_PRIMARY_AND_ACTIVE = 80;
8618
- const READ_EMIT_READABLE_AND_QUEUED = 4224;
8619
- const READ_RESUMED_READ_AHEAD = 131328;
8620
- const READ_NOT_ACTIVE = 536870895;
8621
- const READ_NON_PRIMARY_AND_PUSHED = 536805311;
8622
- const READ_PUSHED = 536805375;
8623
- const READ_PAUSED = 536870655;
8624
- const READ_NOT_QUEUED = 536862591;
8625
- const READ_NOT_ENDING = 536869887;
8626
- const READ_PIPE_NOT_DRAINED = 536870143;
8627
- const READ_NOT_NEXT_TICK = 536838143;
8628
- const READ_NOT_UPDATING = 536870879;
8629
- const READ_NO_READ_AHEAD = 536739839;
8630
- const READ_PAUSED_NO_READ_AHEAD = 536739583;
8631
- const WRITE_ACTIVE = 1 << 18;
8632
- const WRITE_UPDATING = 2 << 18;
8633
- const WRITE_PRIMARY = 4 << 18;
8634
- const WRITE_QUEUED = 8 << 18;
8635
- const WRITE_UNDRAINED = 16 << 18;
8636
- const WRITE_DONE = 32 << 18;
8637
- const WRITE_EMIT_DRAIN = 64 << 18;
8638
- const WRITE_NEXT_TICK = 128 << 18;
8639
- const WRITE_WRITING = 256 << 18;
8640
- const WRITE_FINISHING = 512 << 18;
8641
- const WRITE_CORKED = 1024 << 18;
8642
- const WRITE_NOT_ACTIVE = 469499903;
8643
- const WRITE_NON_PRIMARY = 535822335;
8644
- const WRITE_NOT_FINISHING = 402391039;
8645
- const WRITE_DRAINED = 532676607;
8646
- const WRITE_NOT_QUEUED = 534773759;
8647
- const WRITE_NOT_NEXT_TICK = 503316479;
8648
- const WRITE_NOT_UPDATING = 536346623;
8649
- const WRITE_NOT_CORKED = 268435455;
8650
- const ACTIVE = 262160;
8651
- const NOT_ACTIVE = 536608751;
8652
- const DONE = 8404992;
8653
- const DESTROY_STATUS = 14;
8654
- const OPEN_STATUS = 15;
8655
- const AUTO_DESTROY = 8405006;
8656
- const NON_PRIMARY = 535822271;
8657
- const ACTIVE_OR_TICKING = 33587200;
8658
- const IS_OPENING = 33587215;
8659
- const READ_PRIMARY_STATUS = 17423;
8660
- const READ_STATUS = 16527;
8661
- const READ_ENDING_STATUS = 1167;
8662
- const READ_READABLE_STATUS = 12431;
8663
- const SHOULD_NOT_READ = 214047;
8664
- const READ_BACKPRESSURE_STATUS = 17422;
8665
- const READ_UPDATE_SYNC_STATUS = 32879;
8666
- const READ_NEXT_TICK_OR_OPENING = 32769;
8667
- const WRITE_PRIMARY_STATUS = 142606351;
8668
- const WRITE_QUEUED_AND_UNDRAINED = 6291456;
8669
- const WRITE_QUEUED_AND_ACTIVE = 2359296;
8670
- const WRITE_DRAIN_STATUS = 6553615;
8671
- const WRITE_STATUS = 270794767;
8672
- const WRITE_PRIMARY_AND_ACTIVE = 1310720;
8673
- const WRITE_ACTIVE_AND_WRITING = 67371008;
8674
- const WRITE_FINISHING_STATUS = 144965647;
8675
- const WRITE_BACKPRESSURE_STATUS = 146800654;
8676
- const WRITE_UPDATE_SYNC_STATUS = 35127311;
8677
- const WRITE_DROP_DATA = 142606350;
8678
- const asyncIterator = Symbol.asyncIterator || Symbol("asyncIterator");
8679
- var WritableState = class {
8680
- constructor(stream, { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}) {
8681
- this.stream = stream;
8682
- this.queue = new FIFO();
8683
- this.highWaterMark = highWaterMark;
8684
- this.buffered = 0;
8685
- this.error = null;
8686
- this.pipeline = null;
8687
- this.drains = null;
8688
- this.byteLength = byteLengthWritable || byteLength || defaultByteLength;
8689
- this.map = mapWritable || map;
8690
- this.afterWrite = afterWrite.bind(this);
8691
- this.afterUpdateNextTick = updateWriteNT.bind(this);
8692
- }
8693
- get ending() {
8694
- return (this.stream._duplexState & WRITE_FINISHING) !== 0;
8695
- }
8696
- get ended() {
8697
- return (this.stream._duplexState & WRITE_DONE) !== 0;
8698
- }
8699
- push(data) {
8700
- if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false;
8701
- if (this.map !== null) data = this.map(data);
8702
- this.buffered += this.byteLength(data);
8703
- this.queue.push(data);
8704
- if (this.buffered < this.highWaterMark) {
8705
- this.stream._duplexState |= WRITE_QUEUED;
8706
- return true;
8707
- }
8708
- this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED;
8709
- return false;
8786
+ const destDirPromise = initializeDestDir(destDirPath);
8787
+ destDirPromise.catch(() => {});
8788
+ const getRealDir = async (dirPath, errorMessage) => {
8789
+ const destDir = await destDirPromise;
8790
+ if (dirPath === destDir.symbolic) return destDir.real;
8791
+ let promise = realDirCache.get(dirPath);
8792
+ if (!promise) {
8793
+ promise = fsp.realpath(dirPath).then((realPath) => {
8794
+ validateBounds(realPath, destDir.real, errorMessage);
8795
+ return realPath;
8796
+ });
8797
+ realDirCache.set(dirPath, promise);
8710
8798
  }
8711
- shift() {
8712
- const data = this.queue.shift();
8713
- this.buffered -= this.byteLength(data);
8714
- if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED;
8715
- return data;
8716
- }
8717
- end(data) {
8718
- if (typeof data === "function") this.stream.once("finish", data);
8719
- else if (data !== void 0 && data !== null) this.push(data);
8720
- this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY;
8721
- }
8722
- autoBatch(data, cb) {
8723
- const buffer = [];
8724
- const stream = this.stream;
8725
- buffer.push(data);
8726
- while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) buffer.push(stream._writableState.shift());
8727
- if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null);
8728
- stream._writev(buffer, cb);
8729
- }
8730
- update() {
8731
- const stream = this.stream;
8732
- stream._duplexState |= WRITE_UPDATING;
8733
- do {
8734
- while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
8735
- const data = this.shift();
8736
- stream._duplexState |= WRITE_ACTIVE_AND_WRITING;
8737
- stream._write(data, this.afterWrite);
8799
+ return promise;
8800
+ };
8801
+ const prepareDirectory = async (dirPath, mode) => {
8802
+ let promise = dirPromises.get(dirPath);
8803
+ if (promise) return promise;
8804
+ promise = (async () => {
8805
+ if (dirPath === (await destDirPromise).symbolic) return;
8806
+ await prepareDirectory(path$1.dirname(dirPath));
8807
+ try {
8808
+ const stat = await fsp.lstat(dirPath);
8809
+ if (stat.isDirectory()) return;
8810
+ if (stat.isSymbolicLink()) try {
8811
+ const realPath = await getRealDir(dirPath, `Symlink "${dirPath}" points outside the extraction directory.`);
8812
+ if ((await fsp.stat(realPath)).isDirectory()) return;
8813
+ } catch (err) {
8814
+ if (err.code === ENOENT) throw new Error(`Symlink "${dirPath}" points outside the extraction directory.`);
8815
+ throw err;
8738
8816
  }
8739
- if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
8740
- } while (this.continueUpdate() === true);
8741
- stream._duplexState &= WRITE_NOT_UPDATING;
8742
- }
8743
- updateNonPrimary() {
8744
- const stream = this.stream;
8745
- if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
8746
- stream._duplexState = stream._duplexState | WRITE_ACTIVE;
8747
- stream._final(afterFinal.bind(this));
8748
- return;
8749
- }
8750
- if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
8751
- if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
8752
- stream._duplexState |= ACTIVE;
8753
- stream._destroy(afterDestroy.bind(this));
8817
+ throw new Error(`"${dirPath}" is not a valid directory component.`);
8818
+ } catch (err) {
8819
+ if (err.code === ENOENT) {
8820
+ await fsp.mkdir(dirPath, { mode: mode ?? options.dmode });
8821
+ return;
8754
8822
  }
8755
- return;
8756
- }
8757
- if ((stream._duplexState & IS_OPENING) === OPENING) {
8758
- stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
8759
- stream._open(afterOpen.bind(this));
8823
+ throw err;
8760
8824
  }
8761
- }
8762
- continueUpdate() {
8763
- if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false;
8764
- this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
8765
- return true;
8766
- }
8767
- updateCallback() {
8768
- if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update();
8769
- else this.updateNextTick();
8770
- }
8771
- updateNextTick() {
8772
- if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return;
8773
- this.stream._duplexState |= WRITE_NEXT_TICK;
8774
- if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick);
8775
- }
8825
+ })();
8826
+ dirPromises.set(dirPath, promise);
8827
+ return promise;
8776
8828
  };
8777
- var ReadableState = class {
8778
- constructor(stream, { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}) {
8779
- this.stream = stream;
8780
- this.queue = new FIFO();
8781
- this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark;
8782
- this.buffered = 0;
8783
- this.readAhead = highWaterMark > 0;
8784
- this.error = null;
8785
- this.pipeline = null;
8786
- this.byteLength = byteLengthReadable || byteLength || defaultByteLength;
8787
- this.map = mapReadable || map;
8788
- this.pipeTo = null;
8789
- this.afterRead = afterRead.bind(this);
8790
- this.afterUpdateNextTick = updateReadNT.bind(this);
8791
- }
8792
- get ending() {
8793
- return (this.stream._duplexState & READ_ENDING) !== 0;
8794
- }
8795
- get ended() {
8796
- return (this.stream._duplexState & READ_DONE) !== 0;
8797
- }
8798
- pipe(pipeTo, cb) {
8799
- if (this.pipeTo !== null) throw new Error("Can only pipe to one destination");
8800
- if (typeof cb !== "function") cb = null;
8801
- this.stream._duplexState |= READ_PIPE_DRAINED;
8802
- this.pipeTo = pipeTo;
8803
- this.pipeline = new Pipeline(this.stream, pipeTo, cb);
8804
- if (cb) this.stream.on("error", noop);
8805
- if (isStreamx(pipeTo)) {
8806
- pipeTo._writableState.pipeline = this.pipeline;
8807
- if (cb) pipeTo.on("error", noop);
8808
- pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
8809
- } else {
8810
- const onerror = this.pipeline.done.bind(this.pipeline, pipeTo);
8811
- const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null);
8812
- pipeTo.on("error", onerror);
8813
- pipeTo.on("close", onclose);
8814
- pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
8815
- }
8816
- pipeTo.on("drain", afterDrain.bind(this));
8817
- this.stream.emit("piping", pipeTo);
8818
- pipeTo.emit("pipe", this.stream);
8819
- }
8820
- push(data) {
8821
- const stream = this.stream;
8822
- if (data === null) {
8823
- this.highWaterMark = 0;
8824
- stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED;
8825
- return false;
8829
+ return {
8830
+ async ready() {
8831
+ await destDirPromise;
8832
+ },
8833
+ async preparePath(header) {
8834
+ const { name, linkname, type, mode, mtime } = header;
8835
+ const normalizedName = normalizeHeaderName(name);
8836
+ const destDir = await destDirPromise;
8837
+ const outPath = path$1.join(destDir.symbolic, normalizedName);
8838
+ if (maxDepth !== Infinity) {
8839
+ let depth = 1;
8840
+ for (const char of normalizedName) if (char === "/" && ++depth > maxDepth) throw new Error("Tar exceeds max specified depth.");
8841
+ }
8842
+ const prevOp = pathConflicts.get(normalizedName);
8843
+ if (prevOp) {
8844
+ if (prevOp === "directory" && type !== "directory" || prevOp !== "directory" && type === "directory") throw new Error(`Path conflict ${type} over existing ${prevOp} at "${name}"`);
8845
+ return;
8826
8846
  }
8827
- if (this.map !== null) {
8828
- data = this.map(data);
8829
- if (data === null) {
8830
- stream._duplexState &= READ_PUSHED;
8831
- return this.buffered < this.highWaterMark;
8847
+ const parentDir = path$1.dirname(outPath);
8848
+ switch (type) {
8849
+ case DIRECTORY: {
8850
+ pathConflicts.set(normalizedName, DIRECTORY);
8851
+ const safeMode = mode ? mode & 511 : void 0;
8852
+ await prepareDirectory(outPath, dmode ?? safeMode);
8853
+ if (mtime) await fsp.lutimes(outPath, mtime, mtime).catch(() => {});
8854
+ return;
8832
8855
  }
8833
- }
8834
- this.buffered += this.byteLength(data);
8835
- this.queue.push(data);
8836
- stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED;
8837
- return this.buffered < this.highWaterMark;
8838
- }
8839
- shift() {
8840
- const data = this.queue.shift();
8841
- this.buffered -= this.byteLength(data);
8842
- if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED;
8843
- return data;
8844
- }
8845
- unshift(data) {
8846
- const pending = [this.map !== null ? this.map(data) : data];
8847
- while (this.buffered > 0) pending.push(this.shift());
8848
- for (let i = 0; i < pending.length - 1; i++) {
8849
- const data = pending[i];
8850
- this.buffered += this.byteLength(data);
8851
- this.queue.push(data);
8852
- }
8853
- this.push(pending[pending.length - 1]);
8854
- }
8855
- read() {
8856
- const stream = this.stream;
8857
- if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
8858
- const data = this.shift();
8859
- if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED;
8860
- if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data);
8861
- return data;
8862
- }
8863
- if (this.readAhead === false) {
8864
- stream._duplexState |= READ_READ_AHEAD;
8865
- this.updateNextTick();
8866
- }
8867
- return null;
8868
- }
8869
- drain() {
8870
- const stream = this.stream;
8871
- while ((stream._duplexState & READ_STATUS) === READ_QUEUED && (stream._duplexState & READ_FLOWING) !== 0) {
8872
- const data = this.shift();
8873
- if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED;
8874
- if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data);
8875
- }
8876
- }
8877
- update() {
8878
- const stream = this.stream;
8879
- stream._duplexState |= READ_UPDATING;
8880
- do {
8881
- this.drain();
8882
- while (this.buffered < this.highWaterMark && (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD) {
8883
- stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH;
8884
- stream._read(this.afterRead);
8885
- this.drain();
8886
- }
8887
- if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
8888
- stream._duplexState |= READ_EMITTED_READABLE;
8889
- stream.emit("readable");
8890
- }
8891
- if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
8892
- } while (this.continueUpdate() === true);
8893
- stream._duplexState &= READ_NOT_UPDATING;
8894
- }
8895
- updateNonPrimary() {
8896
- const stream = this.stream;
8897
- if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
8898
- stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING;
8899
- stream.emit("end");
8900
- if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING;
8901
- if (this.pipeTo !== null) this.pipeTo.end();
8902
- }
8903
- if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
8904
- if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
8905
- stream._duplexState |= ACTIVE;
8906
- stream._destroy(afterDestroy.bind(this));
8907
- }
8908
- return;
8909
- }
8910
- if ((stream._duplexState & IS_OPENING) === OPENING) {
8911
- stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
8912
- stream._open(afterOpen.bind(this));
8913
- }
8914
- }
8915
- continueUpdate() {
8916
- if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false;
8917
- this.stream._duplexState &= READ_NOT_NEXT_TICK;
8918
- return true;
8919
- }
8920
- updateCallback() {
8921
- if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update();
8922
- else this.updateNextTick();
8923
- }
8924
- updateNextTickIfOpen() {
8925
- if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return;
8926
- this.stream._duplexState |= READ_NEXT_TICK;
8927
- if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick);
8928
- }
8929
- updateNextTick() {
8930
- if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return;
8931
- this.stream._duplexState |= READ_NEXT_TICK;
8932
- if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick);
8933
- }
8934
- };
8935
- var TransformState = class {
8936
- constructor(stream) {
8937
- this.data = null;
8938
- this.afterTransform = afterTransform.bind(stream);
8939
- this.afterFinal = null;
8940
- }
8941
- };
8942
- var Pipeline = class {
8943
- constructor(src, dst, cb) {
8944
- this.from = src;
8945
- this.to = dst;
8946
- this.afterPipe = cb;
8947
- this.error = null;
8948
- this.pipeToFinished = false;
8949
- }
8950
- finished() {
8951
- this.pipeToFinished = true;
8952
- }
8953
- done(stream, err) {
8954
- if (err) this.error = err;
8955
- if (stream === this.to) {
8956
- this.to = null;
8957
- if (this.from !== null) {
8958
- if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) this.from.destroy(this.error || /* @__PURE__ */ new Error("Writable stream closed prematurely"));
8856
+ case FILE:
8857
+ pathConflicts.set(normalizedName, FILE);
8858
+ await prepareDirectory(parentDir);
8859
+ return path$1.join(await getRealDir(parentDir, `File "${name}" points outside the extraction directory.`), path$1.basename(outPath));
8860
+ case SYMLINK: {
8861
+ pathConflicts.set(normalizedName, SYMLINK);
8862
+ if (!linkname) return;
8863
+ validateBounds(path$1.resolve(parentDir, linkname), destDir.symbolic, `Symlink "${linkname}" points outside the extraction directory.`);
8864
+ await prepareDirectory(parentDir);
8865
+ const realParentDir = await fsp.realpath(parentDir);
8866
+ validateBounds(realParentDir, destDir.real, "Symlink parent changed.");
8867
+ validateBounds(path$1.resolve(realParentDir, linkname), destDir.real, `Symlink "${linkname}" points outside the extraction directory.`);
8868
+ const realOutPath = path$1.join(realParentDir, path$1.basename(outPath));
8869
+ try {
8870
+ await fsp.symlink(linkname, realOutPath);
8871
+ } catch (err) {
8872
+ if (err.code !== "EEXIST") throw err;
8873
+ await fsp.rm(realOutPath, { force: true });
8874
+ if (await fsp.realpath(parentDir) !== realParentDir) throw new Error("Symlink parent changed.");
8875
+ await fsp.symlink(linkname, realOutPath);
8876
+ }
8877
+ (symlinks ??= []).push([normalizedName, linkname]);
8878
+ dirPromises.clear();
8879
+ realDirCache.clear();
8880
+ if (mtime) await fsp.lutimes(outPath, mtime, mtime).catch(() => {});
8959
8881
  return;
8960
8882
  }
8961
- }
8962
- if (stream === this.from) {
8963
- this.from = null;
8964
- if (this.to !== null) {
8965
- if ((stream._duplexState & READ_DONE) === 0) this.to.destroy(this.error || /* @__PURE__ */ new Error("Readable stream closed before ending"));
8883
+ case LINK: {
8884
+ pathConflicts.set(normalizedName, LINK);
8885
+ if (!linkname) return;
8886
+ if (path$1.isAbsolute(linkname)) throw new Error(`Hardlink "${linkname}" points outside the extraction directory.`);
8887
+ const linkTarget = path$1.join(destDir.symbolic, linkname);
8888
+ validateBounds(linkTarget, destDir.symbolic, `Hardlink "${linkname}" points outside the extraction directory.`);
8889
+ await prepareDirectory(parentDir);
8890
+ if (linkTarget !== outPath) deferredLinks.push({
8891
+ linkTarget,
8892
+ outPath
8893
+ });
8966
8894
  return;
8967
8895
  }
8896
+ default: return;
8968
8897
  }
8969
- if (this.afterPipe !== null) this.afterPipe(this.error);
8970
- this.to = this.from = this.afterPipe = null;
8971
- }
8972
- };
8973
- function afterDrain() {
8974
- this.stream._duplexState |= READ_PIPE_DRAINED;
8975
- this.updateCallback();
8976
- }
8977
- function afterFinal(err) {
8978
- const stream = this.stream;
8979
- if (err) stream.destroy(err);
8980
- if ((stream._duplexState & DESTROY_STATUS) === 0) {
8981
- stream._duplexState |= WRITE_DONE;
8982
- stream.emit("finish");
8983
- }
8984
- if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING;
8985
- stream._duplexState &= WRITE_NOT_FINISHING;
8986
- if ((stream._duplexState & WRITE_UPDATING) === 0) this.update();
8987
- else this.updateNextTick();
8988
- }
8989
- function afterDestroy(err) {
8990
- const stream = this.stream;
8991
- if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error;
8992
- if (err) stream.emit("error", err);
8993
- stream._duplexState |= DESTROYED;
8994
- stream.emit("close");
8995
- const rs = stream._readableState;
8996
- const ws = stream._writableState;
8997
- if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err);
8998
- if (ws !== null) {
8999
- while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false);
9000
- if (ws.pipeline !== null) ws.pipeline.done(stream, err);
9001
- }
9002
- }
9003
- function afterWrite(err) {
9004
- const stream = this.stream;
9005
- if (err) stream.destroy(err);
9006
- stream._duplexState &= WRITE_NOT_ACTIVE;
9007
- if (this.drains !== null) tickDrains(this.drains);
9008
- if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
9009
- stream._duplexState &= WRITE_DRAINED;
9010
- if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) stream.emit("drain");
9011
- }
9012
- this.updateCallback();
9013
- }
9014
- function afterRead(err) {
9015
- if (err) this.stream.destroy(err);
9016
- this.stream._duplexState &= READ_NOT_ACTIVE;
9017
- if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) this.stream._duplexState &= READ_NO_READ_AHEAD;
9018
- this.updateCallback();
9019
- }
9020
- function updateReadNT() {
9021
- if ((this.stream._duplexState & READ_UPDATING) === 0) {
9022
- this.stream._duplexState &= READ_NOT_NEXT_TICK;
9023
- this.update();
9024
- }
9025
- }
9026
- function updateWriteNT() {
9027
- if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
9028
- this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
9029
- this.update();
9030
- }
9031
- }
9032
- function tickDrains(drains) {
9033
- for (let i = 0; i < drains.length; i++) if (--drains[i].writes === 0) {
9034
- drains.shift().resolve(true);
9035
- i--;
9036
- }
9037
- }
9038
- function afterOpen(err) {
9039
- const stream = this.stream;
9040
- if (err) stream.destroy(err);
9041
- if ((stream._duplexState & DESTROYING) === 0) {
9042
- if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY;
9043
- if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY;
9044
- stream.emit("open");
9045
- }
9046
- stream._duplexState &= NOT_ACTIVE;
9047
- if (stream._writableState !== null) stream._writableState.updateCallback();
9048
- if (stream._readableState !== null) stream._readableState.updateCallback();
9049
- }
9050
- function afterTransform(err, data) {
9051
- if (data !== void 0 && data !== null) this.push(data);
9052
- this._writableState.afterWrite(err);
9053
- }
9054
- function newListener(name) {
9055
- if (this._readableState !== null) {
9056
- if (name === "data") {
9057
- this._duplexState |= 133376;
9058
- this._readableState.updateNextTick();
9059
- }
9060
- if (name === "readable") {
9061
- this._duplexState |= READ_EMIT_READABLE;
9062
- this._readableState.updateNextTick();
9063
- }
9064
- }
9065
- if (this._writableState !== null) {
9066
- if (name === "drain") {
9067
- this._duplexState |= WRITE_EMIT_DRAIN;
9068
- this._writableState.updateNextTick();
9069
- }
9070
- }
9071
- }
9072
- var Stream = class extends EventEmitter {
9073
- constructor(opts) {
9074
- super();
9075
- this._duplexState = 0;
9076
- this._readableState = null;
9077
- this._writableState = null;
9078
- if (opts) {
9079
- if (opts.open) this._open = opts.open;
9080
- if (opts.destroy) this._destroy = opts.destroy;
9081
- if (opts.predestroy) this._predestroy = opts.predestroy;
9082
- if (opts.signal) opts.signal.addEventListener("abort", abort.bind(this));
9083
- }
9084
- this.on("newListener", newListener);
9085
- }
9086
- _open(cb) {
9087
- cb(null);
9088
- }
9089
- _destroy(cb) {
9090
- cb(null);
9091
- }
9092
- _predestroy() {}
9093
- get readable() {
9094
- return this._readableState !== null ? true : void 0;
9095
- }
9096
- get writable() {
9097
- return this._writableState !== null ? true : void 0;
9098
- }
9099
- get destroyed() {
9100
- return (this._duplexState & DESTROYED) !== 0;
9101
- }
9102
- get destroying() {
9103
- return (this._duplexState & DESTROY_STATUS) !== 0;
9104
- }
9105
- destroy(err) {
9106
- if ((this._duplexState & DESTROY_STATUS) === 0) {
9107
- if (!err) err = StreamError.STREAM_DESTROYED();
9108
- this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY;
9109
- if (this._readableState !== null) {
9110
- this._readableState.highWaterMark = 0;
9111
- this._readableState.error = err;
9112
- }
9113
- if (this._writableState !== null) {
9114
- this._writableState.highWaterMark = 0;
9115
- this._writableState.error = err;
9116
- }
9117
- this._duplexState |= PREDESTROYING;
9118
- this._predestroy();
9119
- this._duplexState &= NOT_PREDESTROYING;
9120
- if (this._readableState !== null) this._readableState.updateNextTick();
9121
- if (this._writableState !== null) this._writableState.updateNextTick();
9122
- }
9123
- }
9124
- };
9125
- var Readable = class Readable extends Stream {
9126
- constructor(opts) {
9127
- super(opts);
9128
- this._duplexState |= 8519681;
9129
- this._readableState = new ReadableState(this, opts);
9130
- if (opts) {
9131
- if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD;
9132
- if (opts.read) this._read = opts.read;
9133
- if (opts.eagerOpen) this._readableState.updateNextTick();
9134
- if (opts.encoding) this.setEncoding(opts.encoding);
9135
- }
9136
- }
9137
- static deferred(fn, opts) {
9138
- const out = new PassThrough(opts);
9139
- fn().then((src) => {
9140
- if (src === null) return out.end();
9141
- if (out.destroying) return;
9142
- pipeline(src, out, noop);
9143
- }).catch((err) => out.destroy(err));
9144
- return out;
9145
- }
9146
- setEncoding(encoding) {
9147
- const dec = new TextDecoder(encoding);
9148
- const map = this._readableState.map || echo;
9149
- this._readableState.map = mapOrSkip;
9150
- return this;
9151
- function mapOrSkip(data) {
9152
- const next = dec.push(data);
9153
- return next === "" && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next);
9154
- }
9155
- }
9156
- _read(cb) {
9157
- cb(null);
9158
- }
9159
- pipe(dest, cb) {
9160
- this._readableState.updateNextTick();
9161
- this._readableState.pipe(dest, cb);
9162
- return dest;
9163
- }
9164
- read() {
9165
- this._readableState.updateNextTick();
9166
- return this._readableState.read();
9167
- }
9168
- push(data) {
9169
- this._readableState.updateNextTickIfOpen();
9170
- return this._readableState.push(data);
9171
- }
9172
- unshift(data) {
9173
- this._readableState.updateNextTickIfOpen();
9174
- return this._readableState.unshift(data);
9175
- }
9176
- resume() {
9177
- this._duplexState |= READ_RESUMED_READ_AHEAD;
9178
- this._readableState.updateNextTick();
9179
- return this;
9180
- }
9181
- pause() {
9182
- this._duplexState &= this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED;
9183
- return this;
9184
- }
9185
- static _fromAsyncIterator(ite, opts) {
9186
- let destroy;
9187
- const rs = new Readable({
9188
- ...opts,
9189
- read(cb) {
9190
- ite.next().then(push).then(cb.bind(null, null)).catch(cb);
9191
- },
9192
- predestroy() {
9193
- destroy = ite.return();
9194
- },
9195
- destroy(cb) {
9196
- if (!destroy) return cb(null);
9197
- destroy.then(cb.bind(null, null)).catch(cb);
9198
- }
9199
- });
9200
- return rs;
9201
- function push(data) {
9202
- if (data.done) rs.push(null);
9203
- else rs.push(data.value);
9204
- }
9205
- }
9206
- static from(data, opts) {
9207
- if (isReadStreamx(data)) return data;
9208
- if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts);
9209
- if (!Array.isArray(data)) data = data === void 0 ? [] : [data];
9210
- let i = 0;
9211
- return new Readable({
9212
- ...opts,
9213
- read(cb) {
9214
- this.push(i === data.length ? null : data[i++]);
9215
- cb(null);
9216
- }
9217
- });
9218
- }
9219
- static isBackpressured(rs) {
9220
- return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark;
9221
- }
9222
- static isPaused(rs) {
9223
- return (rs._duplexState & READ_RESUMED) === 0;
9224
- }
9225
- [asyncIterator]() {
9226
- const stream = this;
9227
- let error = null;
9228
- let promiseResolve = null;
9229
- let promiseReject = null;
9230
- this.on("error", (err) => {
9231
- error = err;
9232
- });
9233
- this.on("readable", onreadable);
9234
- this.on("close", onclose);
9235
- return {
9236
- [asyncIterator]() {
9237
- return this;
9238
- },
9239
- next() {
9240
- return new Promise(function(resolve, reject) {
9241
- promiseResolve = resolve;
9242
- promiseReject = reject;
9243
- const data = stream.read();
9244
- if (data !== null) ondata(data);
9245
- else if ((stream._duplexState & DESTROYED) !== 0) ondata(null);
9246
- });
9247
- },
9248
- return() {
9249
- return destroy(null);
9250
- },
9251
- throw(err) {
9252
- return destroy(err);
9253
- }
8898
+ },
8899
+ async checkSymlinks() {
8900
+ if (!symlinks) return;
8901
+ const { symbolic: dest, real } = await destDirPromise;
8902
+ const realPrefix = real + path$1.sep;
8903
+ const root = path$1.parse(real).root;
8904
+ const depth = linkParts(real.slice(root.length)).length;
8905
+ const targetParts = (linkname, resolvedParts, message) => {
8906
+ if (!path$1.isAbsolute(linkname)) return linkParts(linkname);
8907
+ validateBounds(linkname, real, message);
8908
+ resolvedParts.length = 0;
8909
+ const parts = linkParts(linkname.slice(root.length));
8910
+ parts.splice(0, depth);
8911
+ return parts;
9254
8912
  };
9255
- function onreadable() {
9256
- if (promiseResolve !== null) ondata(stream.read());
9257
- }
9258
- function onclose() {
9259
- if (promiseResolve !== null) ondata(null);
9260
- }
9261
- function ondata(data) {
9262
- if (promiseReject === null) return;
9263
- if (error) promiseReject(error);
9264
- else if (data === null && (stream._duplexState & READ_DONE) === 0) promiseReject(StreamError.STREAM_DESTROYED());
9265
- else promiseResolve({
9266
- value: data,
9267
- done: data === null
9268
- });
9269
- promiseReject = promiseResolve = null;
9270
- }
9271
- function destroy(err) {
9272
- stream.destroy(err);
9273
- return new Promise((resolve, reject) => {
9274
- if (stream._duplexState & DESTROYED) return resolve({
9275
- value: void 0,
9276
- done: true
9277
- });
9278
- stream.once("close", function() {
9279
- if (err) reject(err);
9280
- else resolve({
9281
- value: void 0,
9282
- done: true
9283
- });
9284
- });
9285
- });
9286
- }
9287
- }
9288
- };
9289
- var Writable = class extends Stream {
9290
- constructor(opts) {
9291
- super(opts);
9292
- this._duplexState |= 16385;
9293
- this._writableState = new WritableState(this, opts);
9294
- if (opts) {
9295
- if (opts.writev) this._writev = opts.writev;
9296
- if (opts.write) this._write = opts.write;
9297
- if (opts.final) this._final = opts.final;
9298
- if (opts.eagerOpen) this._writableState.updateNextTick();
9299
- }
9300
- }
9301
- cork() {
9302
- this._duplexState |= WRITE_CORKED;
9303
- }
9304
- uncork() {
9305
- this._duplexState &= WRITE_NOT_CORKED;
9306
- this._writableState.updateNextTick();
9307
- }
9308
- _writev(batch, cb) {
9309
- cb(null);
9310
- }
9311
- _write(data, cb) {
9312
- this._writableState.autoBatch(data, cb);
9313
- }
9314
- _final(cb) {
9315
- cb(null);
9316
- }
9317
- static isBackpressured(ws) {
9318
- return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0;
9319
- }
9320
- static drained(ws) {
9321
- if (ws.destroyed) return Promise.resolve(false);
9322
- const state = ws._writableState;
9323
- const writes = (isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length) + (ws._duplexState & WRITE_WRITING ? 1 : 0);
9324
- if (writes === 0) return Promise.resolve(true);
9325
- if (state.drains === null) state.drains = [];
9326
- return new Promise((resolve) => {
9327
- state.drains.push({
9328
- writes,
9329
- resolve
9330
- });
9331
- });
9332
- }
9333
- write(data) {
9334
- this._writableState.updateNextTick();
9335
- return this._writableState.push(data);
9336
- }
9337
- end(data) {
9338
- this._writableState.updateNextTick();
9339
- this._writableState.end(data);
9340
- return this;
9341
- }
9342
- };
9343
- var Duplex = class extends Readable {
9344
- constructor(opts) {
9345
- super(opts);
9346
- this._duplexState = OPENING | this._duplexState & READ_READ_AHEAD;
9347
- this._writableState = new WritableState(this, opts);
9348
- if (opts) {
9349
- if (opts.writev) this._writev = opts.writev;
9350
- if (opts.write) this._write = opts.write;
9351
- if (opts.final) this._final = opts.final;
9352
- }
9353
- }
9354
- cork() {
9355
- this._duplexState |= WRITE_CORKED;
9356
- }
9357
- uncork() {
9358
- this._duplexState &= WRITE_NOT_CORKED;
9359
- this._writableState.updateNextTick();
9360
- }
9361
- _writev(batch, cb) {
9362
- cb(null);
9363
- }
9364
- _write(data, cb) {
9365
- this._writableState.autoBatch(data, cb);
9366
- }
9367
- _final(cb) {
9368
- cb(null);
9369
- }
9370
- write(data) {
9371
- this._writableState.updateNextTick();
9372
- return this._writableState.push(data);
9373
- }
9374
- end(data) {
9375
- this._writableState.updateNextTick();
9376
- this._writableState.end(data);
9377
- return this;
9378
- }
9379
- };
9380
- var Transform = class extends Duplex {
9381
- constructor(opts) {
9382
- super(opts);
9383
- this._transformState = new TransformState(this);
9384
- if (opts) {
9385
- if (opts.transform) this._transform = opts.transform;
9386
- if (opts.flush) this._flush = opts.flush;
9387
- }
9388
- }
9389
- _write(data, cb) {
9390
- if (this._readableState.buffered >= this._readableState.highWaterMark) this._transformState.data = data;
9391
- else this._transform(data, this._transformState.afterTransform);
9392
- }
9393
- _read(cb) {
9394
- if (this._transformState.data !== null) {
9395
- const data = this._transformState.data;
9396
- this._transformState.data = null;
9397
- cb(null);
9398
- this._transform(data, this._transformState.afterTransform);
9399
- } else cb(null);
9400
- }
9401
- destroy(err) {
9402
- super.destroy(err);
9403
- if (this._transformState.data !== null) {
9404
- this._transformState.data = null;
9405
- this._transformState.afterTransform();
9406
- }
9407
- }
9408
- _transform(data, cb) {
9409
- cb(null, data);
9410
- }
9411
- _flush(cb) {
9412
- cb(null);
9413
- }
9414
- _final(cb) {
9415
- this._transformState.afterFinal = cb;
9416
- this._flush(transformAfterFlush.bind(this));
9417
- }
9418
- };
9419
- var PassThrough = class extends Transform {};
9420
- function transformAfterFlush(err, data) {
9421
- const cb = this._transformState.afterFinal;
9422
- if (err) return cb(err);
9423
- if (data !== null && data !== void 0) this.push(data);
9424
- this.push(null);
9425
- cb(null);
9426
- }
9427
- function pipelinePromise(...streams) {
9428
- return new Promise((resolve, reject) => {
9429
- return pipeline(...streams, (err) => {
9430
- if (err) return reject(err);
9431
- resolve();
9432
- });
9433
- });
9434
- }
9435
- function pipeline(stream, ...streams) {
9436
- const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams];
9437
- const done = all.length && typeof all[all.length - 1] === "function" ? all.pop() : null;
9438
- if (all.length < 2) throw new Error("Pipeline requires at least 2 streams");
9439
- let src = all[0];
9440
- let dest = null;
9441
- let error = null;
9442
- for (let i = 1; i < all.length; i++) {
9443
- dest = all[i];
9444
- if (isStreamx(src)) src.pipe(dest, onerror);
9445
- else {
9446
- errorHandle(src, true, i > 1, onerror);
9447
- src.pipe(dest);
9448
- }
9449
- src = dest;
9450
- }
9451
- if (done) {
9452
- let fin = false;
9453
- const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy);
9454
- dest.on("error", (err) => {
9455
- if (error === null) error = err;
9456
- });
9457
- dest.on("finish", () => {
9458
- fin = true;
9459
- if (!autoDestroy) done(error);
9460
- });
9461
- if (autoDestroy) dest.on("close", () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())));
9462
- }
9463
- return dest;
9464
- function errorHandle(s, rd, wr, onerror) {
9465
- s.on("error", onerror);
9466
- s.on("close", onclose);
9467
- function onclose() {
9468
- if (rd && s._readableState && !s._readableState.ended) return onerror(StreamError.PREMATURE_CLOSE());
9469
- if (wr && s._writableState && !s._writableState.ended) return onerror(StreamError.PREMATURE_CLOSE());
9470
- }
9471
- }
9472
- function onerror(err) {
9473
- if (!err || error) return;
9474
- error = err;
9475
- for (const s of all) s.destroy(err);
9476
- }
9477
- }
9478
- function echo(s) {
9479
- return s;
9480
- }
9481
- function isStream(stream) {
9482
- return !!stream._readableState || !!stream._writableState;
9483
- }
9484
- function isStreamx(stream) {
9485
- return typeof stream._duplexState === "number" && isStream(stream);
9486
- }
9487
- function isEnding(stream) {
9488
- return !!stream._readableState && stream._readableState.ending;
9489
- }
9490
- function isEnded(stream) {
9491
- return !!stream._readableState && stream._readableState.ended;
9492
- }
9493
- function isFinishing(stream) {
9494
- return !!stream._writableState && stream._writableState.ending;
9495
- }
9496
- function isFinished(stream) {
9497
- return !!stream._writableState && stream._writableState.ended;
9498
- }
9499
- function getStreamError(stream, opts = {}) {
9500
- const err = stream._readableState && stream._readableState.error || stream._writableState && stream._writableState.error;
9501
- return !opts.all && StreamError.isStreamDestroyed(err) ? null : err;
9502
- }
9503
- function isReadStreamx(stream) {
9504
- return isStreamx(stream) && stream.readable;
9505
- }
9506
- function isDisturbed(stream) {
9507
- return (stream._duplexState & OPENING) !== OPENING || (stream._duplexState & DESTROYING) === DESTROYING || (stream._duplexState & ACTIVE_OR_TICKING) !== 0;
9508
- }
9509
- function isTypedArray(data) {
9510
- return typeof data === "object" && data !== null && typeof data.byteLength === "number";
9511
- }
9512
- function defaultByteLength(data) {
9513
- return isTypedArray(data) ? data.byteLength : 1024;
9514
- }
9515
- function noop() {}
9516
- function abort() {
9517
- this.destroy(StreamError.ABORTED());
9518
- }
9519
- function isWritev(s) {
9520
- return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev;
9521
- }
9522
- module.exports = {
9523
- pipeline,
9524
- pipelinePromise,
9525
- isStream,
9526
- isStreamx,
9527
- isEnding,
9528
- isEnded,
9529
- isFinishing,
9530
- isFinished,
9531
- isDisturbed,
9532
- getStreamError,
9533
- Stream,
9534
- Writable,
9535
- Readable,
9536
- Duplex,
9537
- Transform,
9538
- PassThrough
9539
- };
9540
- }));
9541
- //#endregion
9542
- //#region ../../node_modules/.pnpm/tar-stream@3.2.0/node_modules/tar-stream/headers.js
9543
- var require_headers = /* @__PURE__ */ __commonJSMin(((exports) => {
9544
- const b4a = require_b4a();
9545
- const ZEROS = "0000000000000000000";
9546
- const SEVENS = "7777777777777777777";
9547
- const ZERO_OFFSET = "0".charCodeAt(0);
9548
- const USTAR_MAGIC = b4a.from([
9549
- 117,
9550
- 115,
9551
- 116,
9552
- 97,
9553
- 114,
9554
- 0
9555
- ]);
9556
- const USTAR_VER = b4a.from([ZERO_OFFSET, ZERO_OFFSET]);
9557
- const GNU_MAGIC = b4a.from([
9558
- 117,
9559
- 115,
9560
- 116,
9561
- 97,
9562
- 114,
9563
- 32
9564
- ]);
9565
- const GNU_VER = b4a.from([32, 0]);
9566
- const MASK = 4095;
9567
- const MAGIC_OFFSET = 257;
9568
- const VERSION_OFFSET = 263;
9569
- exports.decodeLongPath = function decodeLongPath(buf, encoding) {
9570
- return decodeStr(buf, 0, buf.length, encoding);
9571
- };
9572
- exports.encodePax = function encodePax(opts) {
9573
- let result = "";
9574
- if (opts.name) result += addLength(" path=" + opts.name + "\n");
9575
- if (opts.linkname) result += addLength(" linkpath=" + opts.linkname + "\n");
9576
- const pax = opts.pax;
9577
- if (pax) for (const key in pax) result += addLength(" " + key + "=" + pax[key] + "\n");
9578
- return b4a.from(result);
9579
- };
9580
- exports.decodePax = function decodePax(buf) {
9581
- const result = {};
9582
- while (buf.length) {
9583
- let i = 0;
9584
- while (i < buf.length && buf[i] !== 32) i++;
9585
- const len = parseInt(b4a.toString(buf.subarray(0, i)), 10);
9586
- if (!len) return result;
9587
- const b = b4a.toString(buf.subarray(i + 1, len - 1));
9588
- const keyIndex = b.indexOf("=");
9589
- if (keyIndex === -1) return result;
9590
- result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1);
9591
- buf = buf.subarray(len);
9592
- }
9593
- return result;
9594
- };
9595
- exports.encode = function encode(opts) {
9596
- const buf = b4a.alloc(512);
9597
- let name = opts.name;
9598
- let prefix = "";
9599
- if (opts.typeflag === 5 && name[name.length - 1] !== "/") name += "/";
9600
- if (b4a.byteLength(name) !== name.length) return null;
9601
- while (b4a.byteLength(name) > 100) {
9602
- const i = name.indexOf("/");
9603
- if (i === -1) return null;
9604
- prefix += prefix ? "/" + name.slice(0, i) : name.slice(0, i);
9605
- name = name.slice(i + 1);
9606
- }
9607
- if (b4a.byteLength(name) > 100 || b4a.byteLength(prefix) > 155) return null;
9608
- if (opts.linkname && b4a.byteLength(opts.linkname) > 100) return null;
9609
- b4a.write(buf, name);
9610
- b4a.write(buf, encodeOct(opts.mode & MASK, 6), 100);
9611
- b4a.write(buf, encodeOct(opts.uid, 6), 108);
9612
- b4a.write(buf, encodeOct(opts.gid, 6), 116);
9613
- encodeSize(opts.size, buf, 124);
9614
- b4a.write(buf, encodeOct(opts.mtime.getTime() / 1e3 | 0, 11), 136);
9615
- buf[156] = ZERO_OFFSET + toTypeflag(opts.type);
9616
- if (opts.linkname) b4a.write(buf, opts.linkname, 157);
9617
- b4a.copy(USTAR_MAGIC, buf, MAGIC_OFFSET);
9618
- b4a.copy(USTAR_VER, buf, VERSION_OFFSET);
9619
- if (opts.uname) b4a.write(buf, opts.uname, 265);
9620
- if (opts.gname) b4a.write(buf, opts.gname, 297);
9621
- b4a.write(buf, encodeOct(opts.devmajor || 0, 6), 329);
9622
- b4a.write(buf, encodeOct(opts.devminor || 0, 6), 337);
9623
- if (prefix) b4a.write(buf, prefix, 345);
9624
- b4a.write(buf, encodeOct(cksum(buf), 6), 148);
9625
- return buf;
9626
- };
9627
- exports.decode = function decode(buf, filenameEncoding, allowUnknownFormat) {
9628
- let typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET;
9629
- let name = decodeStr(buf, 0, 100, filenameEncoding);
9630
- const mode = decodeOct(buf, 100, 8);
9631
- const uid = decodeOct(buf, 108, 8);
9632
- const gid = decodeOct(buf, 116, 8);
9633
- const size = decodeOct(buf, 124, 12);
9634
- const mtime = decodeOct(buf, 136, 12);
9635
- const type = toType(typeflag);
9636
- const linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding);
9637
- const uname = decodeStr(buf, 265, 32);
9638
- const gname = decodeStr(buf, 297, 32);
9639
- const devmajor = decodeOct(buf, 329, 8);
9640
- const devminor = decodeOct(buf, 337, 8);
9641
- const c = cksum(buf);
9642
- if (c === 256) return null;
9643
- if (c !== decodeOct(buf, 148, 8)) throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");
9644
- if (isUSTAR(buf)) {
9645
- if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + "/" + name;
9646
- } else if (isGNU(buf)) {} else if (!allowUnknownFormat) throw new Error("Invalid tar header: unknown format.");
9647
- if (typeflag === 0 && name && name[name.length - 1] === "/") typeflag = 5;
9648
- return {
9649
- name,
9650
- mode,
9651
- uid,
9652
- gid,
9653
- size,
9654
- byteOffset: 0,
9655
- mtime: /* @__PURE__ */ new Date(1e3 * mtime),
9656
- type,
9657
- linkname,
9658
- uname,
9659
- gname,
9660
- devmajor,
9661
- devminor,
9662
- pax: null
9663
- };
9664
- };
9665
- function isUSTAR(buf) {
9666
- return b4a.equals(USTAR_MAGIC, buf.subarray(MAGIC_OFFSET, 263));
9667
- }
9668
- function isGNU(buf) {
9669
- return b4a.equals(GNU_MAGIC, buf.subarray(MAGIC_OFFSET, 263)) && b4a.equals(GNU_VER, buf.subarray(VERSION_OFFSET, 265));
9670
- }
9671
- function clamp(index, len, defaultValue) {
9672
- if (typeof index !== "number") return defaultValue;
9673
- index = ~~index;
9674
- if (index >= len) return len;
9675
- if (index >= 0) return index;
9676
- index += len;
9677
- if (index >= 0) return index;
9678
- return 0;
9679
- }
9680
- function toType(flag) {
9681
- switch (flag) {
9682
- case 0: return "file";
9683
- case 1: return "link";
9684
- case 2: return "symlink";
9685
- case 3: return "character-device";
9686
- case 4: return "block-device";
9687
- case 5: return "directory";
9688
- case 6: return "fifo";
9689
- case 7: return "contiguous-file";
9690
- case 72: return "pax-header";
9691
- case 55: return "pax-global-header";
9692
- case 27: return "gnu-long-link-path";
9693
- case 28:
9694
- case 30: return "gnu-long-path";
9695
- }
9696
- return null;
9697
- }
9698
- function toTypeflag(flag) {
9699
- switch (flag) {
9700
- case "file": return 0;
9701
- case "link": return 1;
9702
- case "symlink": return 2;
9703
- case "character-device": return 3;
9704
- case "block-device": return 4;
9705
- case "directory": return 5;
9706
- case "fifo": return 6;
9707
- case "contiguous-file": return 7;
9708
- case "pax-header": return 72;
9709
- }
9710
- return 0;
9711
- }
9712
- function indexOf(block, num, offset, end) {
9713
- for (; offset < end; offset++) if (block[offset] === num) return offset;
9714
- return end;
9715
- }
9716
- function cksum(block) {
9717
- let sum = 256;
9718
- for (let i = 0; i < 148; i++) sum += block[i];
9719
- for (let j = 156; j < 512; j++) sum += block[j];
9720
- return sum;
9721
- }
9722
- function encodeOct(val, n) {
9723
- val = val.toString(8);
9724
- if (val.length > n) return SEVENS.slice(0, n) + " ";
9725
- return ZEROS.slice(0, n - val.length) + val + " ";
9726
- }
9727
- function encodeSizeBin(num, buf, off) {
9728
- buf[off] = 128;
9729
- for (let i = 11; i > 0; i--) {
9730
- buf[off + i] = num & 255;
9731
- num = Math.floor(num / 256);
9732
- }
9733
- }
9734
- function encodeSize(num, buf, off) {
9735
- if (num.toString(8).length > 11) encodeSizeBin(num, buf, off);
9736
- else b4a.write(buf, encodeOct(num, 11), off);
9737
- }
9738
- function parse256(buf) {
9739
- let positive;
9740
- if (buf[0] === 128) positive = true;
9741
- else if (buf[0] === 255) positive = false;
9742
- else return null;
9743
- const tuple = [];
9744
- let i;
9745
- for (i = buf.length - 1; i > 0; i--) {
9746
- const byte = buf[i];
9747
- if (positive) tuple.push(byte);
9748
- else tuple.push(255 - byte);
9749
- }
9750
- let sum = 0;
9751
- const l = tuple.length;
9752
- for (i = 0; i < l; i++) sum += tuple[i] * Math.pow(256, i);
9753
- return positive ? sum : -1 * sum;
9754
- }
9755
- function decodeOct(val, offset, length) {
9756
- val = val.subarray(offset, offset + length);
9757
- offset = 0;
9758
- if (val[offset] & 128) return parse256(val);
9759
- else {
9760
- while (offset < val.length && val[offset] === 32) offset++;
9761
- const end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length);
9762
- while (offset < end && val[offset] === 0) offset++;
9763
- if (end === offset) return 0;
9764
- return parseInt(b4a.toString(val.subarray(offset, end)), 8);
9765
- }
9766
- }
9767
- function decodeStr(val, offset, length, encoding) {
9768
- return b4a.toString(val.subarray(offset, indexOf(val, 0, offset, offset + length)), encoding);
9769
- }
9770
- function addLength(str) {
9771
- const len = b4a.byteLength(str);
9772
- let digits = Math.floor(Math.log(len) / Math.log(10)) + 1;
9773
- if (len + digits >= Math.pow(10, digits)) digits++;
9774
- return len + digits + str;
9775
- }
9776
- }));
9777
- //#endregion
9778
- //#region ../../node_modules/.pnpm/tar-stream@3.2.0/node_modules/tar-stream/extract.js
9779
- var require_extract = /* @__PURE__ */ __commonJSMin(((exports, module) => {
9780
- const { Writable, Readable, getStreamError } = require_streamx();
9781
- const FIFO = require_fast_fifo();
9782
- const b4a = require_b4a();
9783
- const headers = require_headers();
9784
- const EMPTY = b4a.alloc(0);
9785
- const MAX_HEADER_SIZE = 4 * 1024 * 1024;
9786
- var BufferList = class {
9787
- constructor() {
9788
- this.buffered = 0;
9789
- this.shifted = 0;
9790
- this.queue = new FIFO();
9791
- this._offset = 0;
9792
- }
9793
- push(buffer) {
9794
- this.buffered += buffer.byteLength;
9795
- this.queue.push(buffer);
9796
- }
9797
- shiftFirst(size) {
9798
- return this.buffered === 0 ? null : this._next(size);
9799
- }
9800
- shift(size) {
9801
- if (size > this.buffered) return null;
9802
- if (size === 0) return EMPTY;
9803
- let chunk = this._next(size);
9804
- if (size === chunk.byteLength) return chunk;
9805
- const chunks = [chunk];
9806
- while ((size -= chunk.byteLength) > 0) {
9807
- chunk = this._next(size);
9808
- chunks.push(chunk);
9809
- }
9810
- return b4a.concat(chunks);
9811
- }
9812
- _next(size) {
9813
- const buf = this.queue.peek();
9814
- const rem = buf.byteLength - this._offset;
9815
- if (size >= rem) {
9816
- const sub = this._offset ? buf.subarray(this._offset, buf.byteLength) : buf;
9817
- this.queue.shift();
9818
- this._offset = 0;
9819
- this.buffered -= rem;
9820
- this.shifted += rem;
9821
- return sub;
9822
- }
9823
- this.buffered -= size;
9824
- this.shifted += size;
9825
- return buf.subarray(this._offset, this._offset += size);
9826
- }
9827
- };
9828
- var Source = class extends Readable {
9829
- constructor(self, header, offset) {
9830
- super();
9831
- this.header = header;
9832
- this.offset = offset;
9833
- this._parent = self;
9834
- }
9835
- _read(cb) {
9836
- if (this.header.size === 0) this.push(null);
9837
- if (this._parent._stream === this) this._parent._update();
9838
- cb(null);
9839
- }
9840
- _predestroy() {
9841
- this._parent.destroy(getStreamError(this));
9842
- }
9843
- _detach() {
9844
- if (this._parent._stream === this) {
9845
- this._parent._stream = null;
9846
- this._parent._missing = overflow(this.header.size);
9847
- this._parent._update();
9848
- }
9849
- }
9850
- _destroy(cb) {
9851
- this._detach();
9852
- cb(null);
9853
- }
9854
- };
9855
- var Extract = class extends Writable {
9856
- constructor(opts) {
9857
- super(opts);
9858
- if (!opts) opts = {};
9859
- this._buffer = new BufferList();
9860
- this._offset = 0;
9861
- this._header = null;
9862
- this._stream = null;
9863
- this._missing = 0;
9864
- this._longHeader = false;
9865
- this._callback = noop;
9866
- this._locked = false;
9867
- this._finished = false;
9868
- this._pax = null;
9869
- this._paxGlobal = null;
9870
- this._gnuLongPath = null;
9871
- this._gnuLongLinkPath = null;
9872
- this._filenameEncoding = opts.filenameEncoding || "utf-8";
9873
- this._allowUnknownFormat = !!opts.allowUnknownFormat;
9874
- this._unlockBound = this._unlock.bind(this);
9875
- }
9876
- _unlock(err) {
9877
- this._locked = false;
9878
- if (err) {
9879
- this.destroy(err);
9880
- this._continueWrite(err);
9881
- return;
9882
- }
9883
- this._update();
9884
- }
9885
- _consumeHeader() {
9886
- if (this._locked) return false;
9887
- this._offset = this._buffer.shifted;
9888
- try {
9889
- this._header = headers.decode(this._buffer.shift(512), this._filenameEncoding, this._allowUnknownFormat);
9890
- } catch (err) {
9891
- this._continueWrite(err);
9892
- return false;
9893
- }
9894
- if (!this._header) return true;
9895
- this._header.byteOffset = this._buffer.shifted;
9896
- switch (this._header.type) {
9897
- case "gnu-long-path":
9898
- case "gnu-long-link-path":
9899
- case "pax-global-header":
9900
- case "pax-header":
9901
- this._longHeader = true;
9902
- this._missing = this._header.size;
9903
- if (this._missing > MAX_HEADER_SIZE) {
9904
- this._continueWrite(/* @__PURE__ */ new Error("Header exceeds max size"));
9905
- return false;
9906
- }
9907
- return true;
9908
- }
9909
- this._locked = true;
9910
- this._applyLongHeaders();
9911
- if (!(this._header.size >= 0)) {
9912
- this._continueWrite(/* @__PURE__ */ new Error("Invalid header"));
9913
- return false;
9914
- }
9915
- if (this._header.size === 0 || this._header.type === "directory") {
9916
- this.emit("entry", this._header, this._createStream(), this._unlockBound);
9917
- return true;
9918
- }
9919
- this._stream = this._createStream();
9920
- this._missing = this._header.size;
9921
- this.emit("entry", this._header, this._stream, this._unlockBound);
9922
- return true;
9923
- }
9924
- _applyLongHeaders() {
9925
- if (this._gnuLongPath) {
9926
- this._header.name = this._gnuLongPath;
9927
- this._gnuLongPath = null;
9928
- }
9929
- if (this._gnuLongLinkPath) {
9930
- this._header.linkname = this._gnuLongLinkPath;
9931
- this._gnuLongLinkPath = null;
9932
- }
9933
- if (this._pax) {
9934
- if (this._pax.path) this._header.name = this._pax.path;
9935
- if (this._pax.linkpath) this._header.linkname = this._pax.linkpath;
9936
- if (this._pax.size) this._header.size = parseInt(this._pax.size, 10);
9937
- this._header.pax = this._pax;
9938
- this._pax = null;
9939
- }
9940
- }
9941
- _decodeLongHeader(buf) {
9942
- switch (this._header.type) {
9943
- case "gnu-long-path":
9944
- this._gnuLongPath = headers.decodeLongPath(buf, this._filenameEncoding);
9945
- break;
9946
- case "gnu-long-link-path":
9947
- this._gnuLongLinkPath = headers.decodeLongPath(buf, this._filenameEncoding);
9948
- break;
9949
- case "pax-global-header":
9950
- this._paxGlobal = headers.decodePax(buf);
9951
- break;
9952
- case "pax-header":
9953
- this._pax = this._paxGlobal === null ? headers.decodePax(buf) : Object.assign({}, this._paxGlobal, headers.decodePax(buf));
9954
- break;
9955
- }
9956
- }
9957
- _consumeLongHeader() {
9958
- this._longHeader = false;
9959
- this._missing = overflow(this._header.size);
9960
- const buf = this._buffer.shift(this._header.size);
9961
- try {
9962
- this._decodeLongHeader(buf);
9963
- } catch (err) {
9964
- this._continueWrite(err);
9965
- return false;
9966
- }
9967
- return true;
9968
- }
9969
- _consumeStream() {
9970
- const buf = this._buffer.shiftFirst(this._missing);
9971
- if (buf === null) return false;
9972
- this._missing -= buf.byteLength;
9973
- const drained = this._stream.push(buf);
9974
- if (this._missing === 0) {
9975
- this._stream.push(null);
9976
- if (drained) this._stream._detach();
9977
- return drained && this._locked === false;
9978
- }
9979
- return drained;
9980
- }
9981
- _createStream() {
9982
- return new Source(this, this._header, this._offset);
9983
- }
9984
- _update() {
9985
- while (this._buffer.buffered > 0 && !this.destroying) {
9986
- if (this._missing > 0) {
9987
- if (this._stream !== null) {
9988
- if (this._consumeStream() === false) return;
9989
- continue;
8913
+ const getSymlinkError = async ([name, storedLinkname]) => {
8914
+ const outPath = path$1.join(dest, name);
8915
+ try {
8916
+ try {
8917
+ const resolved = await fsp.realpath(outPath);
8918
+ if (resolved !== real && !resolved.startsWith(realPrefix)) throw new Error(`Symlink "${storedLinkname}" points outside the extraction directory.`);
8919
+ return;
8920
+ } catch (err) {
8921
+ if (err.code !== ENOENT) throw err;
9990
8922
  }
9991
- if (this._longHeader === true) {
9992
- if (this._missing > this._buffer.buffered) break;
9993
- if (this._consumeLongHeader() === false) return false;
9994
- continue;
8923
+ if (!(await fsp.lstat(outPath)).isSymbolicLink()) return;
8924
+ const linkname = await fsp.readlink(outPath);
8925
+ const message = `Symlink "${linkname}" points outside the extraction directory.`;
8926
+ const realParent = await fsp.realpath(path$1.dirname(outPath));
8927
+ validateBounds(realParent, real, message);
8928
+ const resolvedParts = linkParts(path$1.relative(real, realParent));
8929
+ const pendingParts = targetParts(linkname, resolvedParts, message);
8930
+ let followedSymlinks = 0;
8931
+ for (let i = 0; i < pendingParts.length; i++) {
8932
+ const part = pendingParts[i];
8933
+ if (part === "..") {
8934
+ if (!resolvedParts.length) throw new Error(message);
8935
+ resolvedParts.pop();
8936
+ continue;
8937
+ }
8938
+ resolvedParts.push(part);
8939
+ const nextPath = path$1.join(real, ...resolvedParts);
8940
+ let nextStat;
8941
+ try {
8942
+ nextStat = await fsp.lstat(nextPath);
8943
+ } catch (err) {
8944
+ if (err.code === ENOENT) continue;
8945
+ throw err;
8946
+ }
8947
+ if (!nextStat.isSymbolicLink()) continue;
8948
+ if (++followedSymlinks > MAX_SYMLINKS) throw new Error(message);
8949
+ const nextLink = await fsp.readlink(nextPath);
8950
+ resolvedParts.pop();
8951
+ pendingParts.splice(i + 1, 0, ...targetParts(nextLink, resolvedParts, message));
9995
8952
  }
9996
- const ignore = this._buffer.shiftFirst(this._missing);
9997
- if (ignore !== null) this._missing -= ignore.byteLength;
9998
- continue;
9999
- }
10000
- if (this._buffer.buffered < 512) break;
10001
- if (this._stream !== null || this._consumeHeader() === false) return;
10002
- }
10003
- this._continueWrite(null);
10004
- }
10005
- _continueWrite(err) {
10006
- const cb = this._callback;
10007
- this._callback = noop;
10008
- cb(err);
10009
- }
10010
- _write(data, cb) {
10011
- this._callback = cb;
10012
- this._buffer.push(data);
10013
- this._update();
10014
- }
10015
- _final(cb) {
10016
- this._finished = this._missing === 0 && this._buffer.buffered === 0;
10017
- cb(this._finished ? null : /* @__PURE__ */ new Error("Unexpected end of data"));
10018
- }
10019
- _predestroy() {
10020
- this._continueWrite(null);
10021
- }
10022
- _destroy(cb) {
10023
- if (this._stream) this._stream.destroy(getStreamError(this));
10024
- cb(null);
10025
- }
10026
- [Symbol.asyncIterator]() {
10027
- let error = null;
10028
- let promiseResolve = null;
10029
- let promiseReject = null;
10030
- let entryStream = null;
10031
- let entryCallback = null;
10032
- const extract = this;
10033
- this.on("entry", onentry);
10034
- this.on("error", (err) => {
10035
- error = err;
10036
- });
10037
- this.on("close", onclose);
10038
- return {
10039
- [Symbol.asyncIterator]() {
10040
- return this;
10041
- },
10042
- next() {
10043
- return new Promise(onnext);
10044
- },
10045
- return() {
10046
- return destroy(null);
10047
- },
10048
- throw(err) {
10049
- return destroy(err);
8953
+ } catch (err) {
8954
+ if (err.code !== ENOENT) return err;
10050
8955
  }
10051
8956
  };
10052
- function consumeCallback(err) {
10053
- if (!entryCallback) return;
10054
- const cb = entryCallback;
10055
- entryCallback = null;
10056
- cb(err);
10057
- }
10058
- function onnext(resolve, reject) {
10059
- if (error) return reject(error);
10060
- if (entryStream) {
10061
- resolve({
10062
- value: entryStream,
10063
- done: false
10064
- });
10065
- entryStream = null;
10066
- return;
8957
+ for (let start = 0; start < symlinks.length; start += concurrency) {
8958
+ const batch = symlinks.slice(start, start + concurrency);
8959
+ const errors = await Promise.all(batch.map((symlink) => opQueue.add(() => getSymlinkError(symlink))));
8960
+ for (const [i, error] of errors.entries()) {
8961
+ if (error === void 0) continue;
8962
+ await fsp.rm(path$1.join(dest, batch[i][0]), { force: true });
8963
+ throw error;
10067
8964
  }
10068
- promiseResolve = resolve;
10069
- promiseReject = reject;
10070
- consumeCallback(null);
10071
- if (extract._finished && promiseResolve) {
10072
- promiseResolve({
10073
- value: void 0,
10074
- done: true
10075
- });
10076
- promiseResolve = promiseReject = null;
10077
- }
10078
- }
10079
- function onentry(header, stream, callback) {
10080
- entryCallback = callback;
10081
- stream.on("error", noop);
10082
- if (promiseResolve) {
10083
- promiseResolve({
10084
- value: stream,
10085
- done: false
10086
- });
10087
- promiseResolve = promiseReject = null;
10088
- } else entryStream = stream;
10089
- }
10090
- function onclose() {
10091
- consumeCallback(error);
10092
- if (!promiseResolve) return;
10093
- if (error) promiseReject(error);
10094
- else promiseResolve({
10095
- value: void 0,
10096
- done: true
10097
- });
10098
- promiseResolve = promiseReject = null;
10099
8965
  }
10100
- function destroy(err) {
10101
- extract.destroy(err);
10102
- consumeCallback(err);
10103
- return new Promise((resolve, reject) => {
10104
- if (extract.destroyed) return resolve({
10105
- value: void 0,
10106
- done: true
10107
- });
10108
- extract.once("close", function() {
10109
- if (err) reject(err);
10110
- else resolve({
10111
- value: void 0,
10112
- done: true
10113
- });
10114
- });
10115
- });
10116
- }
10117
- }
10118
- };
10119
- module.exports = function extract(opts) {
10120
- return new Extract(opts);
10121
- };
10122
- function noop() {}
10123
- function overflow(size) {
10124
- size &= 511;
10125
- return size && 512 - size;
10126
- }
10127
- }));
10128
- //#endregion
10129
- //#region ../../node_modules/.pnpm/tar-stream@3.2.0/node_modules/tar-stream/constants.js
10130
- var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
10131
- const constants = {
10132
- S_IFMT: 61440,
10133
- S_IFDIR: 16384,
10134
- S_IFCHR: 8192,
10135
- S_IFBLK: 24576,
10136
- S_IFIFO: 4096,
10137
- S_IFLNK: 40960
10138
- };
10139
- try {
10140
- module.exports = __require("fs").constants || constants;
10141
- } catch {
10142
- module.exports = constants;
10143
- }
10144
- }));
10145
- //#endregion
10146
- //#region ../../node_modules/.pnpm/tar-stream@3.2.0/node_modules/tar-stream/pack.js
10147
- var require_pack = /* @__PURE__ */ __commonJSMin(((exports, module) => {
10148
- const { Readable, Writable, getStreamError } = require_streamx();
10149
- const b4a = require_b4a();
10150
- const constants = require_constants();
10151
- const headers = require_headers();
10152
- const DMODE = 493;
10153
- const FMODE = 420;
10154
- const END_OF_TAR = b4a.alloc(1024);
10155
- var Sink = class extends Writable {
10156
- constructor(pack, header, callback) {
10157
- super({
10158
- mapWritable,
10159
- eagerOpen: true
10160
- });
10161
- this.written = 0;
10162
- this.header = header;
10163
- this._callback = callback;
10164
- this._linkname = null;
10165
- this._isLinkname = header.type === "symlink" && !header.linkname;
10166
- this._isVoid = header.type !== "file" && header.type !== "contiguous-file";
10167
- this._finished = false;
10168
- this._pack = pack;
10169
- this._openCallback = null;
10170
- if (this._pack._stream === null) this._pack._stream = this;
10171
- else this._pack._pending.push(this);
10172
- }
10173
- _open(cb) {
10174
- this._openCallback = cb;
10175
- if (this._pack._stream === this) this._continueOpen();
10176
- }
10177
- _continuePack(err) {
10178
- if (this._callback === null) return;
10179
- const callback = this._callback;
10180
- this._callback = null;
10181
- callback(err);
10182
- }
10183
- _continueOpen() {
10184
- if (this._pack._stream === null) this._pack._stream = this;
10185
- const cb = this._openCallback;
10186
- this._openCallback = null;
10187
- if (cb === null) return;
10188
- if (this._pack.destroying) return cb(/* @__PURE__ */ new Error("pack stream destroyed"));
10189
- if (this._pack._finalized) return cb(/* @__PURE__ */ new Error("pack stream is already finalized"));
10190
- this._pack._stream = this;
10191
- if (!this._isLinkname) this._pack._encode(this.header);
10192
- if (this._isVoid) {
10193
- this._finish();
10194
- this._continuePack(null);
10195
- }
10196
- cb(null);
10197
- }
10198
- _write(data, cb) {
10199
- if (this._isLinkname) {
10200
- this._linkname = this._linkname ? b4a.concat([this._linkname, data]) : data;
10201
- return cb(null);
10202
- }
10203
- if (this._isVoid) {
10204
- if (data.byteLength > 0) return cb(/* @__PURE__ */ new Error("No body allowed for this entry"));
10205
- return cb();
10206
- }
10207
- this.written += data.byteLength;
10208
- if (this._pack.push(data)) return cb();
10209
- this._pack._drain = cb;
10210
- }
10211
- _finish() {
10212
- if (this._finished) return;
10213
- this._finished = true;
10214
- if (this._isLinkname) {
10215
- this.header.linkname = this._linkname ? b4a.toString(this._linkname, "utf-8") : "";
10216
- this._pack._encode(this.header);
10217
- }
10218
- overflow(this._pack, this.header.size);
10219
- this._pack._done(this);
10220
- }
10221
- _final(cb) {
10222
- if (this.written !== this.header.size) return cb(/* @__PURE__ */ new Error("Size mismatch"));
10223
- this._finish();
10224
- cb(null);
10225
- }
10226
- _getError() {
10227
- return getStreamError(this) || /* @__PURE__ */ new Error("tar entry destroyed");
10228
- }
10229
- _predestroy() {
10230
- this._pack.destroy(this._getError());
10231
- }
10232
- _destroy(cb) {
10233
- this._pack._done(this);
10234
- this._continuePack(this._finished ? null : this._getError());
10235
- cb();
10236
- }
10237
- };
10238
- var Pack = class extends Readable {
10239
- constructor(opts) {
10240
- super(opts);
10241
- this._drain = noop;
10242
- this._finalized = false;
10243
- this._finalizing = false;
10244
- this._pending = [];
10245
- this._stream = null;
10246
- }
10247
- entry(header, buffer, callback) {
10248
- if (this._finalized || this.destroying) throw new Error("already finalized or destroyed");
10249
- if (typeof buffer === "function") {
10250
- callback = buffer;
10251
- buffer = null;
10252
- }
10253
- if (!callback) callback = noop;
10254
- if (!header.size || header.type === "symlink") header.size = 0;
10255
- if (!header.type) header.type = modeToType(header.mode);
10256
- if (!header.mode) header.mode = header.type === "directory" ? DMODE : FMODE;
10257
- if (!header.uid) header.uid = 0;
10258
- if (!header.gid) header.gid = 0;
10259
- if (!header.mtime) header.mtime = /* @__PURE__ */ new Date();
10260
- if (typeof buffer === "string") buffer = b4a.from(buffer);
10261
- const sink = new Sink(this, header, callback);
10262
- if (b4a.isBuffer(buffer)) {
10263
- header.size = buffer.byteLength;
10264
- sink.write(buffer);
10265
- sink.end();
10266
- return sink;
10267
- }
10268
- if (sink._isVoid) return sink;
10269
- return sink;
10270
- }
10271
- finalize() {
10272
- if (this._stream || this._pending.length > 0) {
10273
- this._finalizing = true;
10274
- return;
10275
- }
10276
- if (this._finalized) return;
10277
- this._finalized = true;
10278
- this.push(END_OF_TAR);
10279
- this.push(null);
10280
- }
10281
- _done(stream) {
10282
- if (stream !== this._stream) return;
10283
- this._stream = null;
10284
- if (this._finalizing) this.finalize();
10285
- if (this._pending.length) this._pending.shift()._continueOpen();
10286
- }
10287
- _encode(header) {
10288
- if (!header.pax) {
10289
- const buf = headers.encode(header);
10290
- if (buf) {
10291
- this.push(buf);
10292
- return;
8966
+ },
8967
+ async applyLinks() {
8968
+ const destRoot = (await destDirPromise).real;
8969
+ for (const { linkTarget, outPath } of deferredLinks) try {
8970
+ const realTargetDir = await fsp.realpath(path$1.dirname(linkTarget));
8971
+ validateBounds(realTargetDir, destRoot, `Hardlink "${linkTarget}" points outside the extraction directory.`);
8972
+ const realTarget = path$1.join(realTargetDir, path$1.basename(linkTarget));
8973
+ const [targetResult, outDirResult] = await Promise.allSettled([opQueue.add(() => fsp.lstat(realTarget)), opQueue.add(() => fsp.realpath(path$1.dirname(outPath)))]);
8974
+ if (targetResult.status === "rejected") throw targetResult.reason;
8975
+ const targetStat = targetResult.value;
8976
+ if (targetStat.isSymbolicLink()) throw new Error(`Hardlink "${linkTarget}" is a symlink.`);
8977
+ if (outDirResult.status === "rejected") throw outDirResult.reason;
8978
+ const realOutDir = outDirResult.value;
8979
+ validateBounds(realOutDir, destRoot, `Hardlink "${outPath}" points outside the extraction directory.`);
8980
+ const realOutPath = path$1.join(realOutDir, path$1.basename(outPath));
8981
+ try {
8982
+ await fsp.link(realTarget, realOutPath);
8983
+ } catch (err) {
8984
+ const code = err.code;
8985
+ if (code !== "EEXIST" && code !== ENOENT) throw err;
8986
+ try {
8987
+ const outStat = await fsp.lstat(realOutPath);
8988
+ if (outStat.dev === targetStat.dev && outStat.ino === targetStat.ino) continue;
8989
+ await fsp.rm(realOutPath, { force: true });
8990
+ } catch (err) {
8991
+ if (err.code !== ENOENT) throw err;
8992
+ }
8993
+ await fsp.link(realTarget, realOutPath);
10293
8994
  }
8995
+ const linkStat = await fsp.lstat(realOutPath);
8996
+ if (linkStat.dev !== targetStat.dev || linkStat.ino !== targetStat.ino) {
8997
+ await fsp.rm(realOutPath, { force: true });
8998
+ throw new Error(`Hardlink target "${linkTarget}" changed during creation for link at "${outPath}".`);
8999
+ }
9000
+ } catch (err) {
9001
+ if (err.code === ENOENT) throw new Error(`Hardlink target "${linkTarget}" does not exist for link at "${outPath}".`);
9002
+ throw err;
10294
9003
  }
10295
- this._encodePax(header);
10296
- }
10297
- _encodePax(header) {
10298
- const paxHeader = headers.encodePax({
10299
- name: header.name,
10300
- linkname: header.linkname,
10301
- pax: header.pax
10302
- });
10303
- const newHeader = {
10304
- name: "PaxHeader",
10305
- mode: header.mode,
10306
- uid: header.uid,
10307
- gid: header.gid,
10308
- size: paxHeader.byteLength,
10309
- mtime: header.mtime,
10310
- type: "pax-header",
10311
- linkname: header.linkname && "PaxHeader",
10312
- uname: header.uname,
10313
- gname: header.gname,
10314
- devmajor: header.devmajor,
10315
- devminor: header.devminor
10316
- };
10317
- this.push(headers.encode(newHeader));
10318
- this.push(paxHeader);
10319
- overflow(this, paxHeader.byteLength);
10320
- newHeader.size = header.size;
10321
- newHeader.type = header.type;
10322
- this.push(headers.encode(newHeader));
10323
- }
10324
- _doDrain() {
10325
- const drain = this._drain;
10326
- this._drain = noop;
10327
- drain();
10328
- }
10329
- _predestroy() {
10330
- const err = getStreamError(this);
10331
- if (this._stream) this._stream.destroy(err);
10332
- while (this._pending.length) {
10333
- const stream = this._pending.shift();
10334
- stream.destroy(err);
10335
- stream._continueOpen();
10336
- }
10337
- this._doDrain();
10338
- }
10339
- _read(cb) {
10340
- this._doDrain();
10341
- cb();
10342
- }
10343
- };
10344
- module.exports = function pack(opts) {
10345
- return new Pack(opts);
10346
- };
10347
- function modeToType(mode) {
10348
- switch (mode & constants.S_IFMT) {
10349
- case constants.S_IFBLK: return "block-device";
10350
- case constants.S_IFCHR: return "character-device";
10351
- case constants.S_IFDIR: return "directory";
10352
- case constants.S_IFIFO: return "fifo";
10353
- case constants.S_IFLNK: return "symlink";
10354
- }
10355
- return "file";
10356
- }
10357
- function noop() {}
10358
- function overflow(self, size) {
10359
- size &= 511;
10360
- if (size) self.push(END_OF_TAR.subarray(0, 512 - size));
10361
- }
10362
- function mapWritable(buf) {
10363
- return b4a.isBuffer(buf) ? buf : b4a.from(buf);
10364
- }
10365
- }));
10366
- //#endregion
10367
- //#region ../../node_modules/.pnpm/tar-stream@3.2.0/node_modules/tar-stream/index.js
10368
- var require_tar_stream = /* @__PURE__ */ __commonJSMin(((exports) => {
10369
- exports.extract = require_extract();
10370
- exports.pack = require_pack();
10371
- }));
10372
- //#endregion
10373
- //#region ../../node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js
10374
- var require_wrappy = /* @__PURE__ */ __commonJSMin(((exports, module) => {
10375
- module.exports = wrappy;
10376
- function wrappy(fn, cb) {
10377
- if (fn && cb) return wrappy(fn)(cb);
10378
- if (typeof fn !== "function") throw new TypeError("need wrapper function");
10379
- Object.keys(fn).forEach(function(k) {
10380
- wrapper[k] = fn[k];
10381
- });
10382
- return wrapper;
10383
- function wrapper() {
10384
- var args = new Array(arguments.length);
10385
- for (var i = 0; i < args.length; i++) args[i] = arguments[i];
10386
- var ret = fn.apply(this, args);
10387
- var cb = args[args.length - 1];
10388
- if (typeof ret === "function" && ret !== cb) Object.keys(cb).forEach(function(k) {
10389
- ret[k] = cb[k];
10390
- });
10391
- return ret;
10392
9004
  }
10393
- }
10394
- }));
10395
- //#endregion
10396
- //#region ../../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js
10397
- var require_once = /* @__PURE__ */ __commonJSMin(((exports, module) => {
10398
- var wrappy = require_wrappy();
10399
- module.exports = wrappy(once);
10400
- module.exports.strict = wrappy(onceStrict);
10401
- once.proto = once(function() {
10402
- Object.defineProperty(Function.prototype, "once", {
10403
- value: function() {
10404
- return once(this);
10405
- },
10406
- configurable: true
10407
- });
10408
- Object.defineProperty(Function.prototype, "onceStrict", {
10409
- value: function() {
10410
- return onceStrict(this);
10411
- },
10412
- configurable: true
10413
- });
10414
- });
10415
- function once(fn) {
10416
- var f = function() {
10417
- if (f.called) return f.value;
10418
- f.called = true;
10419
- return f.value = fn.apply(this, arguments);
10420
- };
10421
- f.called = false;
10422
- return f;
10423
- }
10424
- function onceStrict(fn) {
10425
- var f = function() {
10426
- if (f.called) throw new Error(f.onceError);
10427
- f.called = true;
10428
- return f.value = fn.apply(this, arguments);
10429
- };
10430
- f.onceError = (fn.name || "Function wrapped with `once`") + " shouldn't be called more than once";
10431
- f.called = false;
10432
- return f;
10433
- }
10434
- }));
10435
- //#endregion
10436
- //#region ../../node_modules/.pnpm/end-of-stream@1.4.5/node_modules/end-of-stream/index.js
10437
- var require_end_of_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
10438
- var once = require_once();
10439
- var noop = function() {};
10440
- var qnt = global.Bare ? queueMicrotask : process.nextTick.bind(process);
10441
- var isRequest = function(stream) {
10442
- return stream.setHeader && typeof stream.abort === "function";
10443
- };
10444
- var isChildProcess = function(stream) {
10445
- return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3;
10446
9005
  };
10447
- var eos = function(stream, opts, callback) {
10448
- if (typeof opts === "function") return eos(stream, null, opts);
10449
- if (!opts) opts = {};
10450
- callback = once(callback || noop);
10451
- var ws = stream._writableState;
10452
- var rs = stream._readableState;
10453
- var readable = opts.readable || opts.readable !== false && stream.readable;
10454
- var writable = opts.writable || opts.writable !== false && stream.writable;
10455
- var cancelled = false;
10456
- var onlegacyfinish = function() {
10457
- if (!stream.writable) onfinish();
10458
- };
10459
- var onfinish = function() {
10460
- writable = false;
10461
- if (!readable) callback.call(stream);
10462
- };
10463
- var onend = function() {
10464
- readable = false;
10465
- if (!writable) callback.call(stream);
10466
- };
10467
- var onexit = function(exitCode) {
10468
- callback.call(stream, exitCode ? /* @__PURE__ */ new Error("exited with error code: " + exitCode) : null);
10469
- };
10470
- var onerror = function(err) {
10471
- callback.call(stream, err);
10472
- };
10473
- var onclose = function() {
10474
- qnt(onclosenexttick);
10475
- };
10476
- var onclosenexttick = function() {
10477
- if (cancelled) return;
10478
- if (readable && !(rs && rs.ended && !rs.destroyed)) return callback.call(stream, /* @__PURE__ */ new Error("premature close"));
10479
- if (writable && !(ws && ws.ended && !ws.destroyed)) return callback.call(stream, /* @__PURE__ */ new Error("premature close"));
10480
- };
10481
- var onrequest = function() {
10482
- stream.req.on("finish", onfinish);
10483
- };
10484
- if (isRequest(stream)) {
10485
- stream.on("complete", onfinish);
10486
- stream.on("abort", onclose);
10487
- if (stream.req) onrequest();
10488
- else stream.on("request", onrequest);
10489
- } else if (writable && !ws) {
10490
- stream.on("end", onlegacyfinish);
10491
- stream.on("close", onlegacyfinish);
10492
- }
10493
- if (isChildProcess(stream)) stream.on("exit", onexit);
10494
- stream.on("end", onend);
10495
- stream.on("finish", onfinish);
10496
- if (opts.error !== false) stream.on("error", onerror);
10497
- stream.on("close", onclose);
10498
- return function() {
10499
- cancelled = true;
10500
- stream.removeListener("complete", onfinish);
10501
- stream.removeListener("abort", onclose);
10502
- stream.removeListener("request", onrequest);
10503
- if (stream.req) stream.req.removeListener("finish", onfinish);
10504
- stream.removeListener("end", onlegacyfinish);
10505
- stream.removeListener("close", onlegacyfinish);
10506
- stream.removeListener("finish", onfinish);
10507
- stream.removeListener("exit", onexit);
10508
- stream.removeListener("end", onend);
10509
- stream.removeListener("error", onerror);
10510
- stream.removeListener("close", onclose);
10511
- };
10512
- };
10513
- module.exports = eos;
10514
- }));
10515
- //#endregion
10516
- //#region ../../node_modules/.pnpm/pump@3.0.4/node_modules/pump/index.js
10517
- var require_pump = /* @__PURE__ */ __commonJSMin(((exports, module) => {
10518
- var once = require_once();
10519
- var eos = require_end_of_stream();
10520
- var fs;
10521
- try {
10522
- fs = __require("fs");
10523
- } catch (e) {}
10524
- var noop = function() {};
10525
- var ancient = typeof process === "undefined" ? false : /^v?\.0/.test(process.version);
10526
- var isFn = function(fn) {
10527
- return typeof fn === "function";
10528
- };
10529
- var isFS = function(stream) {
10530
- if (!ancient) return false;
10531
- if (!fs) return false;
10532
- return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close);
10533
- };
10534
- var isRequest = function(stream) {
10535
- return stream.setHeader && isFn(stream.abort);
10536
- };
10537
- var destroyer = function(stream, reading, writing, callback) {
10538
- callback = once(callback);
10539
- var closed = false;
10540
- stream.on("close", function() {
10541
- closed = true;
10542
- });
10543
- eos(stream, {
10544
- readable: reading,
10545
- writable: writing
10546
- }, function(err) {
10547
- if (err) return callback(err);
10548
- closed = true;
10549
- callback();
10550
- });
10551
- var destroyed = false;
10552
- return function(err) {
10553
- if (closed) return;
10554
- if (destroyed) return;
10555
- destroyed = true;
10556
- if (isFS(stream)) return stream.close(noop);
10557
- if (isRequest(stream)) return stream.abort();
10558
- if (isFn(stream.destroy)) return stream.destroy();
10559
- callback(err || /* @__PURE__ */ new Error("stream was destroyed"));
10560
- };
10561
- };
10562
- var call = function(fn) {
10563
- fn();
10564
- };
10565
- var pipe = function(from, to) {
10566
- return from.pipe(to);
10567
- };
10568
- var pump = function() {
10569
- var streams = Array.prototype.slice.call(arguments);
10570
- var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop;
10571
- if (Array.isArray(streams[0])) streams = streams[0];
10572
- if (streams.length < 2) throw new Error("pump requires two streams per minimum");
10573
- var error;
10574
- var destroys = streams.map(function(stream, i) {
10575
- var reading = i < streams.length - 1;
10576
- return destroyer(stream, reading, i > 0, function(err) {
10577
- if (!error) error = err;
10578
- if (err) destroys.forEach(call);
10579
- if (reading) return;
10580
- destroys.forEach(call);
10581
- callback(error);
10582
- });
10583
- });
10584
- return streams.reduce(pipe);
9006
+ };
9007
+ function unpackTar(directoryPath, options = {}) {
9008
+ const unpacker = createUnpacker(options);
9009
+ const concurrency = options.concurrency || cpus().length || 8;
9010
+ const opQueue = createOperationQueue(concurrency);
9011
+ const pathCache = createPathCache(directoryPath, options, opQueue, concurrency);
9012
+ let currentFileStream = null;
9013
+ let currentWriteCallback = null;
9014
+ let queuedError = null;
9015
+ const onQueuedError = (err) => {
9016
+ queuedError ??= err;
9017
+ if (!writable.destroyed) writable.destroy(err);
10585
9018
  };
10586
- module.exports = pump;
10587
- }));
10588
- //#endregion
10589
- //#region src/core/fetch-packages.ts
10590
- var import_tar_fs = (/* @__PURE__ */ __commonJSMin(((exports) => {
10591
- const tar = require_tar_stream();
10592
- const pump = require_pump();
10593
- const fs$1 = __require("fs");
10594
- const path$1 = __require("path");
10595
- const win32 = (global.Bare ? global.Bare.platform : process.platform) === "win32";
10596
- function head(list) {
10597
- return list.length ? list[list.length - 1] : null;
10598
- }
10599
- function processGetuid() {
10600
- return !global.Bare && process.getuid ? process.getuid() : -1;
10601
- }
10602
- function processUmask() {
10603
- return !global.Bare && process.umask ? process.umask() : 0;
10604
- }
10605
- exports.extract = function extract(cwd, opts) {
10606
- if (!cwd) cwd = ".";
10607
- if (!opts) opts = {};
10608
- cwd = path$1.resolve(cwd);
10609
- const xfs = opts.fs || fs$1;
10610
- const ignore = opts.ignore || opts.filter || noop;
10611
- const mapStream = opts.mapStream || echo;
10612
- const own = opts.chown !== false && !win32 && processGetuid() === 0;
10613
- const extract = opts.extract || tar.extract();
10614
- const stack = [];
10615
- const now = /* @__PURE__ */ new Date();
10616
- const umask = typeof opts.umask === "number" ? ~opts.umask : ~processUmask();
10617
- const strict = opts.strict !== false;
10618
- const validateSymLinks = opts.validateSymlinks !== false;
10619
- let map = opts.map || noop;
10620
- let dmode = typeof opts.dmode === "number" ? opts.dmode : 0;
10621
- let fmode = typeof opts.fmode === "number" ? opts.fmode : 0;
10622
- if (opts.strip) map = strip(map, opts.strip);
10623
- if (opts.readable) {
10624
- dmode |= parseInt(555, 8);
10625
- fmode |= parseInt(444, 8);
10626
- }
10627
- if (opts.writable) {
10628
- dmode |= parseInt(333, 8);
10629
- fmode |= parseInt(222, 8);
10630
- }
10631
- extract.on("entry", onentry);
10632
- if (opts.finish) extract.on("finish", opts.finish);
10633
- return extract;
10634
- function onentry(header, stream, next) {
10635
- header = map(header) || header;
10636
- header.name = normalize(header.name);
10637
- const name = path$1.join(cwd, path$1.join("/", header.name));
10638
- if (ignore(name, header)) {
10639
- stream.resume();
10640
- return next();
10641
- }
10642
- const dir = path$1.join(name, ".") === path$1.join(cwd, ".") ? cwd : path$1.dirname(name);
10643
- validate(xfs, dir, path$1.join(cwd, "."), function(err, valid) {
10644
- if (err) return next(err);
10645
- if (!valid) return next(/* @__PURE__ */ new Error(dir + " is not a valid path"));
10646
- if (header.type === "directory") {
10647
- stack.push([name, header.mtime]);
10648
- return mkdirfix(name, {
10649
- fs: xfs,
10650
- own,
10651
- uid: header.uid,
10652
- gid: header.gid,
10653
- mode: header.mode
10654
- }, stat);
9019
+ const writable = new Writable({
9020
+ async write(chunk, _, cb) {
9021
+ const pendingFileOpens = [];
9022
+ let writeError;
9023
+ try {
9024
+ unpacker.write(chunk);
9025
+ if (unpacker.isEntryActive()) {
9026
+ if (currentFileStream && currentWriteCallback) {
9027
+ let needsDrain = false;
9028
+ const writeCallback = currentWriteCallback;
9029
+ while (!unpacker.isBodyComplete()) {
9030
+ needsDrain = false;
9031
+ if (unpacker.streamBody(writeCallback) === 0) if (needsDrain) await currentFileStream.waitDrain();
9032
+ else return;
9033
+ }
9034
+ while (!unpacker.skipPadding()) return;
9035
+ const streamToClose = currentFileStream;
9036
+ if (streamToClose) opQueue.add(() => streamToClose.end()).catch(onQueuedError);
9037
+ currentFileStream = null;
9038
+ currentWriteCallback = null;
9039
+ } else if (!unpacker.skipEntry()) return;
10655
9040
  }
10656
- mkdirfix(dir, {
10657
- fs: xfs,
10658
- own,
10659
- uid: header.uid,
10660
- gid: header.gid,
10661
- mode: 493
10662
- }, function(err) {
10663
- if (err) return next(err);
10664
- switch (header.type) {
10665
- case "file": return onfile();
10666
- case "link": return onlink();
10667
- case "symlink": return onsymlink();
9041
+ while (true) {
9042
+ const header = unpacker.readHeader();
9043
+ if (header === void 0 || header === null) return;
9044
+ const transformedHeader = transformHeader(header, options);
9045
+ if (!transformedHeader) {
9046
+ if (!unpacker.skipEntry()) return;
9047
+ continue;
10668
9048
  }
10669
- if (strict) return next(/* @__PURE__ */ new Error("unsupported type for " + name + " (" + header.type + ")"));
10670
- stream.resume();
10671
- next();
10672
- });
10673
- });
10674
- function stat(err) {
10675
- if (err) return next(err);
10676
- utimes(name, header, function(err) {
10677
- if (err) return next(err);
10678
- if (win32) return next();
10679
- chperm(name, header, next);
10680
- });
10681
- }
10682
- function onsymlink() {
10683
- if (win32) return next();
10684
- xfs.unlink(name, function() {
10685
- const dst = path$1.resolve(path$1.dirname(name), header.linkname);
10686
- if (!inCwd(dst) && validateSymLinks) return next(/* @__PURE__ */ new Error(name + " is not a valid symlink"));
10687
- validateNotSymlink(xfs, dst, path$1.join(cwd, "."), function(err, valid) {
10688
- if (err) return next(err);
10689
- if (!valid && validateSymLinks) return next(/* @__PURE__ */ new Error(name + " is not a valid symlink"));
10690
- xfs.symlink(header.linkname, name, stat);
10691
- });
10692
- });
10693
- }
10694
- function onlink() {
10695
- if (win32) return next();
10696
- xfs.unlink(name, function() {
10697
- const link = path$1.join(cwd, path$1.join("/", header.linkname));
10698
- xfs.realpath(link, function(err, dst) {
10699
- if (err || !inCwd(dst)) return next(/* @__PURE__ */ new Error(name + " is not a valid hardlink"));
10700
- xfs.link(dst, name, function(err) {
10701
- if (err && err.code === "EPERM" && opts.hardlinkAsFilesFallback) {
10702
- stream = xfs.createReadStream(dst);
10703
- return onfile();
10704
- }
10705
- stat(err);
9049
+ const outPath = await opQueue.add(() => pathCache.preparePath(transformedHeader));
9050
+ if (outPath) {
9051
+ const safeMode = transformedHeader.mode ? transformedHeader.mode & 511 : void 0;
9052
+ const fileStream = createFileSink(outPath, {
9053
+ mode: options.fmode ?? safeMode,
9054
+ mtime: transformedHeader.mtime ?? void 0
10706
9055
  });
10707
- });
10708
- });
10709
- }
10710
- function inCwd(dst) {
10711
- return dst === cwd || dst.startsWith(cwd + path$1.sep);
10712
- }
10713
- function onfile() {
10714
- const ws = xfs.createWriteStream(name);
10715
- const rs = mapStream(stream, header);
10716
- ws.on("error", function(err) {
10717
- rs.destroy(err);
10718
- });
10719
- pump(rs, ws, function(err) {
10720
- if (err) return next(err);
10721
- ws.on("close", stat);
10722
- });
9056
+ pendingFileOpens.push(fileStream.waitDrain().catch((error) => error));
9057
+ let needsDrain = false;
9058
+ const writeCallback = (chunk) => {
9059
+ const writeOk = fileStream.write(chunk);
9060
+ if (!writeOk) needsDrain = true;
9061
+ return writeOk;
9062
+ };
9063
+ while (!unpacker.isBodyComplete()) {
9064
+ needsDrain = false;
9065
+ if (unpacker.streamBody(writeCallback) === 0) if (needsDrain) await fileStream.waitDrain();
9066
+ else {
9067
+ currentFileStream = fileStream;
9068
+ currentWriteCallback = writeCallback;
9069
+ return;
9070
+ }
9071
+ }
9072
+ while (!unpacker.skipPadding()) {
9073
+ currentFileStream = fileStream;
9074
+ currentWriteCallback = writeCallback;
9075
+ return;
9076
+ }
9077
+ opQueue.add(() => fileStream.end()).catch(onQueuedError);
9078
+ } else if (!unpacker.skipEntry()) return;
9079
+ }
9080
+ } catch (err) {
9081
+ writeError = err;
9082
+ } finally {
9083
+ cb((pendingFileOpens.length ? (await Promise.all(pendingFileOpens)).find((error) => error) : void 0) ?? writeError);
10723
9084
  }
10724
- }
10725
- function utimesParent(name, cb) {
10726
- let top;
10727
- while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop();
10728
- if (!top) return cb();
10729
- xfs.utimes(top[0], now, top[1], cb);
10730
- }
10731
- function utimes(name, header, cb) {
10732
- if (opts.utimes === false) return cb();
10733
- if (header.type === "directory") return xfs.utimes(name, now, header.mtime, cb);
10734
- if (header.type === "symlink") return utimesParent(name, cb);
10735
- xfs.utimes(name, now, header.mtime, function(err) {
10736
- if (err) return cb(err);
10737
- utimesParent(name, cb);
10738
- });
10739
- }
10740
- function chperm(name, header, cb) {
10741
- const link = header.type === "symlink";
10742
- const chmod = link ? xfs.lchmod : xfs.chmod;
10743
- const chown = link ? xfs.lchown : xfs.chown;
10744
- if (!chmod) return cb();
10745
- const mode = (header.mode | (header.type === "directory" ? dmode : fmode)) & umask;
10746
- if (chown && own) chown.call(xfs, name, header.uid, header.gid, onchown);
10747
- else onchown(null);
10748
- function onchown(err) {
10749
- if (err) return cb(err);
10750
- if (!chmod) return cb();
10751
- chmod.call(xfs, name, mode, cb);
9085
+ },
9086
+ async final(cb) {
9087
+ try {
9088
+ unpacker.end();
9089
+ unpacker.validateEOF();
9090
+ await pathCache.ready();
9091
+ await opQueue.onIdle();
9092
+ if (queuedError) throw queuedError;
9093
+ await pathCache.checkSymlinks();
9094
+ await pathCache.applyLinks();
9095
+ cb();
9096
+ } catch (err) {
9097
+ cb(err);
10752
9098
  }
10753
- }
10754
- function mkdirfix(name, opts, cb) {
10755
- xfs.stat(name, function(err) {
10756
- if (!err) return cb(null);
10757
- if (err.code !== "ENOENT") return cb(err);
10758
- xfs.mkdir(name, {
10759
- mode: opts.mode,
10760
- recursive: true
10761
- }, function(err, made) {
10762
- if (err) return cb(err);
10763
- chperm(name, opts, cb);
10764
- });
10765
- });
10766
- }
10767
- };
10768
- function validateNotSymlink(fs, name, root, cb) {
10769
- if (name === root) return cb(null, true);
10770
- if (!name.startsWith(root + path$1.sep)) return cb(null, false);
10771
- fs.lstat(name, function(err, st) {
10772
- if (err && err.code !== "ENOENT" && err.code !== "EPERM") return cb(err);
10773
- if (err || !st.isSymbolicLink()) return validateNotSymlink(fs, path$1.join(name, ".."), root, cb);
10774
- cb(null, false);
10775
- });
10776
- }
10777
- function validate(fs, name, root, cb) {
10778
- if (name === root) return cb(null, true);
10779
- fs.lstat(name, function(err, st) {
10780
- if (err && err.code !== "ENOENT" && err.code !== "EPERM") return cb(err);
10781
- if (err || st.isDirectory()) return validate(fs, path$1.join(name, ".."), root, cb);
10782
- cb(null, false);
10783
- });
10784
- }
10785
- function noop() {}
10786
- function echo(name) {
10787
- return name;
10788
- }
10789
- function normalize(name) {
10790
- return win32 ? name.replace(/\\/g, "/").replace(/[:?<>|]/g, "_") : name;
10791
- }
10792
- function strip(map, level) {
10793
- return function(header) {
10794
- header.name = header.name.split("/").slice(level).join("/");
10795
- const linkname = header.linkname;
10796
- if (linkname && (header.type === "link" || path$1.isAbsolute(linkname))) header.linkname = linkname.split("/").slice(level).join("/");
10797
- return map(header);
10798
- };
10799
- }
10800
- })))();
9099
+ },
9100
+ destroy(error, callback) {
9101
+ (async () => {
9102
+ if (currentFileStream) {
9103
+ currentFileStream.destroy(error ?? void 0);
9104
+ currentFileStream = null;
9105
+ currentWriteCallback = null;
9106
+ }
9107
+ await opQueue.onIdle();
9108
+ })().then(() => callback(error ?? null), (e) => callback(error ?? (e instanceof Error ? e : /* @__PURE__ */ new Error("Stream destroyed"))));
9109
+ }
9110
+ });
9111
+ return writable;
9112
+ }
9113
+ //#endregion
9114
+ //#region src/core/fetch-packages.ts
10801
9115
  const NODE_MODULES = fileURLToPath(new URL("../../node_modules", import.meta.url));
10802
9116
  function verifyPackage(addonPkg, specifier) {
10803
9117
  const peerDeps = { ...addonPkg.peerDependencies };
@@ -10847,10 +9161,7 @@ async function downloadPackage(options) {
10847
9161
  const tarballUrl = pkg.dist.tarball;
10848
9162
  const data = await fetch(tarballUrl);
10849
9163
  if (!data.body) throw new Error(`Unexpected response: '${tarballUrl}' responded with no body`);
10850
- await pipeline(data.body, createGunzip(), (0, import_tar_fs.extract)(NODE_MODULES, { map: (header) => {
10851
- header.name = header.name.replace("package", pkg.name);
10852
- return header;
10853
- } }));
9164
+ await pipeline(data.body, createGunzip(), unpackTar(path.join(NODE_MODULES, pkg.name), { strip: 1 }));
10854
9165
  return await importAddonCode(pkg.name, pkg.version);
10855
9166
  }
10856
9167
  async function importAddonCode(pkgName, pkgVersion) {
@@ -10894,48 +9205,6 @@ async function getPackageJSON(ref) {
10894
9205
  };
10895
9206
  }
10896
9207
  //#endregion
10897
- //#region src/core/formatFiles.ts
10898
- async function formatFiles(options) {
10899
- if (options.filesToFormat.length === 0) return;
10900
- const { start, stop } = vt();
10901
- start("Formatting modified files");
10902
- const args = [
10903
- "--write",
10904
- "--ignore-unknown",
10905
- ...options.filesToFormat
10906
- ];
10907
- let result = await run("prettier", args, options.cwd);
10908
- if (result.notFound) {
10909
- const cmd = resolveCommand(options.packageManager, "execute-local", ["prettier", ...args]);
10910
- result = await run(cmd.command, cmd.args, options.cwd);
10911
- }
10912
- if (result.error !== void 0) {
10913
- stop("Failed to format files");
10914
- R$1.error(result.error);
10915
- return;
10916
- }
10917
- stop("Successfully formatted modified files");
10918
- }
10919
- async function run(command, args, cwd) {
10920
- try {
10921
- await z(command, args, {
10922
- nodeOptions: {
10923
- cwd,
10924
- stdio: "pipe"
10925
- },
10926
- throwOnError: true
10927
- });
10928
- return {};
10929
- } catch (e) {
10930
- if (e?.code === "ENOENT") return {
10931
- notFound: true,
10932
- error: `${command} not found`
10933
- };
10934
- const output = e?.output;
10935
- return { error: [output?.stderr, output?.stdout].filter(Boolean).join("\n").trim() || (e instanceof Error ? e.message : "unknown error") };
10936
- }
10937
- }
10938
- //#endregion
10939
9208
  //#region src/core/package-manager.ts
10940
9209
  const AGENT_NAMES = AGENTS.filter((agent) => !agent.includes("@"));
10941
9210
  const installOption = new Option("--install <package-manager>", "installs dependencies with a specified package manager").choices(AGENT_NAMES);
@@ -10943,7 +9212,7 @@ async function packageManagerPrompt(cwd) {
10943
9212
  const agent = (await detect({ cwd }))?.name ?? getUserAgent();
10944
9213
  if (!V.stdout.isTTY) return agent;
10945
9214
  const pm = await Ee({
10946
- message: "Which package manager do you want to install dependencies with?",
9215
+ message: "Detected package managers. Which one should we use to install dependencies?",
10947
9216
  options: [{
10948
9217
  label: "None",
10949
9218
  value: void 0
@@ -11034,91 +9303,16 @@ function addPnpmAllowBuilds(cwd, packageManager, ...packages) {
11034
9303
  const filePath = found ?? path.join(cwd, "pnpm-workspace.yaml");
11035
9304
  const content = found ? fs.readFileSync(found, "utf-8") : "";
11036
9305
  const newContent = pnpm.allowBuilds(...packages)(content);
11037
- if (newContent !== content) fs.writeFileSync(filePath, newContent, "utf-8");
11038
- }
11039
- //#endregion
11040
- //#region src/core/verifiers.ts
11041
- function verifyCleanWorkingDirectory(cwd, gitCheck) {
11042
- const verifications = [];
11043
- if (gitCheck) verifications.push({
11044
- name: "clean working directory",
11045
- run: async () => {
11046
- try {
11047
- const { stdout } = await promisify(exec)("git status --short", { cwd });
11048
- if (stdout) return {
11049
- success: false,
11050
- message: "Uncommited changes found"
11051
- };
11052
- return {
11053
- success: true,
11054
- message: void 0
11055
- };
11056
- } catch {
11057
- return {
11058
- success: true,
11059
- message: "Not a git repository"
11060
- };
11061
- }
11062
- }
11063
- });
11064
- return verifications;
11065
- }
11066
- function verifyUnsupportedAddons(addons, setupResults) {
11067
- const verifications = [];
11068
- verifications.push({
11069
- name: "unsupported add-ons",
11070
- run: () => {
11071
- const reasons = addons.flatMap((a) => setupResults[a.id].unsupported.map((reason) => ({
11072
- id: a.id,
11073
- reason
11074
- })));
11075
- if (reasons.length === 0) return {
11076
- success: true,
11077
- message: void 0
11078
- };
11079
- throw new UnsupportedError(reasons);
11080
- }
11081
- });
11082
- return verifications;
9306
+ if (newContent && newContent !== content) fs.writeFileSync(filePath, newContent, "utf-8");
11083
9307
  }
11084
9308
  //#endregion
11085
9309
  //#region src/core/workspace.ts
11086
- const deprecatedFiles = {
11087
- prettierignore: ".prettierignore",
11088
- prettierrc: ".prettierrc",
11089
- eslintConfig: "eslint.config.js",
11090
- vscodeSettings: ".vscode/settings.json",
11091
- vscodeExtensions: ".vscode/extensions.json"
11092
- };
11093
- /**
11094
- * Adds deprecated file properties as non-enumerable getters so they don't trigger on spread
11095
- * Once we remove these deprecatedFiles, we can get rid of addDeprecatedFileProperties
11096
- */
11097
- function addDeprecatedFileProperties(file, svelteConfig) {
11098
- for (const [key, value] of Object.entries(deprecatedFiles)) Object.defineProperty(file, key, {
11099
- get() {
11100
- svDeprecated(`use the string \`"${value}"\` instead of \`file.${key}\``);
11101
- return value;
11102
- },
11103
- enumerable: false
11104
- });
11105
- Object.defineProperty(file, "svelteConfig", {
11106
- get() {
11107
- svDeprecated("use `svelteConfig` from `@sveltejs/sv-utils` instead of `file.svelteConfig` (the config may live in `vite.config.{js,ts}`)");
11108
- return svelteConfig;
11109
- },
11110
- enumerable: false
11111
- });
11112
- return file;
11113
- }
11114
9310
  async function createWorkspace({ cwd, packageManager, override }) {
11115
9311
  const resolvedCwd = path.resolve(cwd);
11116
9312
  const typeConfig = any([filePaths.jsconfig, filePaths.tsconfig], { cwd });
11117
9313
  const typescript = typeConfig?.endsWith(filePaths.tsconfig) ?? false;
11118
9314
  const viteConfigPath = path.join(resolvedCwd, filePaths.viteConfigTS);
11119
9315
  const viteConfig = fs.existsSync(viteConfigPath) ? filePaths.viteConfigTS : filePaths.viteConfig;
11120
- const svelteConfigPath = path.join(resolvedCwd, filePaths.svelteConfigTS);
11121
- const svelteConfig = fs.existsSync(svelteConfigPath) ? filePaths.svelteConfigTS : filePaths.svelteConfig;
11122
9316
  let dependencies = {};
11123
9317
  if (override?.dependencies) dependencies = override.dependencies;
11124
9318
  else {
@@ -11155,7 +9349,7 @@ async function createWorkspace({ cwd, packageManager, override }) {
11155
9349
  cwd: resolvedCwd,
11156
9350
  packageManager: packageManager ?? await detectPackageManager(cwd),
11157
9351
  language: typescript ? "ts" : "js",
11158
- file: addDeprecatedFileProperties({
9352
+ file: {
11159
9353
  viteConfig,
11160
9354
  typeConfig,
11161
9355
  stylesheet,
@@ -11173,7 +9367,7 @@ async function createWorkspace({ cwd, packageManager, override }) {
11173
9367
  if (resolvedCwd.includes(".test-output") && !found.includes(".test-output")) return filename;
11174
9368
  return path.relative(resolvedCwd, found);
11175
9369
  }
11176
- }, svelteConfig),
9370
+ },
11177
9371
  isKit,
11178
9372
  directory,
11179
9373
  dependencyVersion: (pkg) => dependencies[pkg]
@@ -11230,6 +9424,129 @@ function parseKitOptions(cwd) {
11230
9424
  };
11231
9425
  }
11232
9426
  //#endregion
9427
+ //#region src/core/formatFiles.ts
9428
+ async function formatFiles(options) {
9429
+ if (options.filesToFormat.length === 0) return;
9430
+ if (options.strategy === "project-script-then-files-only") {
9431
+ const script = findFormatScript(options.cwd);
9432
+ if (script) {
9433
+ const packageManager = await detectPackageManager(script.dir);
9434
+ const cmd = resolveCommand(packageManager, "run", [script.name]);
9435
+ await withSpinner(`Running ${packageManager} run ${script.name}`, () => run(cmd.command, cmd.args, script.dir));
9436
+ return;
9437
+ }
9438
+ }
9439
+ const args = [
9440
+ "--write",
9441
+ "--ignore-unknown",
9442
+ ...options.filesToFormat
9443
+ ];
9444
+ await withSpinner("Formatting modified files", async () => {
9445
+ let result = await run("prettier", args, options.cwd);
9446
+ if (result.notFound) {
9447
+ const cmd = resolveCommand(options.packageManager, "execute-local", ["prettier", ...args]);
9448
+ result = await run(cmd.command, cmd.args, options.cwd);
9449
+ }
9450
+ return result;
9451
+ });
9452
+ }
9453
+ /** Nearest dir from `cwd` up to the workspace root with a `format` or `fmt` package.json script. */
9454
+ function findFormatScript(cwd) {
9455
+ const workspaceRoot = findWorkspaceRoot(cwd);
9456
+ let directory = path.resolve(cwd);
9457
+ const { root } = path.parse(directory);
9458
+ while (directory && directory.length >= workspaceRoot.length) {
9459
+ if (fs.existsSync(path.join(directory, "package.json"))) {
9460
+ const { data } = loadPackageJson(directory);
9461
+ if (data.scripts?.format) return {
9462
+ dir: directory,
9463
+ name: "format"
9464
+ };
9465
+ if (data.scripts?.fmt) return {
9466
+ dir: directory,
9467
+ name: "fmt"
9468
+ };
9469
+ }
9470
+ if (directory === root) break;
9471
+ directory = path.dirname(directory);
9472
+ }
9473
+ }
9474
+ async function withSpinner(startMsg, task) {
9475
+ const { start, stop } = vt();
9476
+ start(startMsg);
9477
+ const { error } = await task();
9478
+ if (error !== void 0) {
9479
+ stop("Failed to format files");
9480
+ R$1.error(error);
9481
+ return;
9482
+ }
9483
+ stop("Successfully formatted files");
9484
+ }
9485
+ async function run(command, args, cwd) {
9486
+ try {
9487
+ await z(command, args, {
9488
+ nodeOptions: {
9489
+ cwd,
9490
+ stdio: "pipe"
9491
+ },
9492
+ throwOnError: true
9493
+ });
9494
+ return {};
9495
+ } catch (e) {
9496
+ if (e?.code === "ENOENT") return {
9497
+ notFound: true,
9498
+ error: `${command} not found`
9499
+ };
9500
+ const output = e?.output;
9501
+ return { error: [output?.stderr, output?.stdout].filter(Boolean).join("\n").trim() || (e instanceof Error ? e.message : "unknown error") };
9502
+ }
9503
+ }
9504
+ //#endregion
9505
+ //#region src/core/verifiers.ts
9506
+ function verifyCleanWorkingDirectory(cwd, gitCheck) {
9507
+ const verifications = [];
9508
+ if (gitCheck) verifications.push({
9509
+ name: "clean working directory",
9510
+ run: async () => {
9511
+ try {
9512
+ const { stdout } = await promisify(exec)("git status --short", { cwd });
9513
+ if (stdout) return {
9514
+ success: false,
9515
+ message: "Uncommited changes found"
9516
+ };
9517
+ return {
9518
+ success: true,
9519
+ message: void 0
9520
+ };
9521
+ } catch {
9522
+ return {
9523
+ success: true,
9524
+ message: "Not a git repository"
9525
+ };
9526
+ }
9527
+ }
9528
+ });
9529
+ return verifications;
9530
+ }
9531
+ function verifyUnsupportedAddons(addons, setupResults) {
9532
+ const verifications = [];
9533
+ verifications.push({
9534
+ name: "unsupported add-ons",
9535
+ run: () => {
9536
+ const reasons = addons.flatMap((a) => setupResults[a.id].unsupported.map((reason) => ({
9537
+ id: a.id,
9538
+ reason
9539
+ })));
9540
+ if (reasons.length === 0) return {
9541
+ success: true,
9542
+ message: void 0
9543
+ };
9544
+ throw new UnsupportedError(reasons);
9545
+ }
9546
+ });
9547
+ return verifications;
9548
+ }
9549
+ //#endregion
11233
9550
  //#region src/create/playground.ts
11234
9551
  function validatePlaygroundUrl(link) {
11235
9552
  try {
@@ -11280,6 +9597,7 @@ function detectPlaygroundDependencies(files) {
11280
9597
  const packages = /* @__PURE__ */ new Map();
11281
9598
  const excludedPrefixes = [
11282
9599
  "$",
9600
+ "#",
11283
9601
  "node:",
11284
9602
  "svelte",
11285
9603
  "@sveltejs/"
@@ -11358,11 +9676,11 @@ function setupPlaygroundProject(url, playground, cwd, installDependencies) {
11358
9676
  svelte.ensureScript(ast);
11359
9677
  js.imports.addDefault(ast.instance.content, {
11360
9678
  as: "App",
11361
- from: `$lib/playground/${mainFile.name}`
9679
+ from: `#lib/playground/${mainFile.name}`
11362
9680
  });
11363
9681
  js.imports.addDefault(ast.instance.content, {
11364
9682
  as: "PlaygroundLayout",
11365
- from: `$lib/PlaygroundLayout.svelte`
9683
+ from: `#lib/PlaygroundLayout.svelte`
11366
9684
  });
11367
9685
  svelte.addFragment(ast, `<PlaygroundLayout>
11368
9686
  <App />
@@ -11654,7 +9972,8 @@ async function createProject(cwd, options) {
11654
9972
  if (depsInstalled) await formatFiles({
11655
9973
  packageManager,
11656
9974
  cwd: projectPath,
11657
- filesToFormat: addOnSuccessfulAddons.some((addon) => addon.addon.id === "prettier") ? ["."] : addOnFilesToFormat
9975
+ filesToFormat: addOnSuccessfulAddons.some((addon) => addon.addon.id === "prettier") ? ["."] : addOnFilesToFormat,
9976
+ strategy: "files-only"
11658
9977
  });
11659
9978
  }
11660
9979
  return {
@@ -11708,8 +10027,7 @@ async function createVirtualWorkspace({ cwd, template, type }) {
11708
10027
  language: type === "typescript" ? "ts" : "js",
11709
10028
  file: {
11710
10029
  ...tentativeWorkspace.file,
11711
- viteConfig: type === "typescript" ? filePaths.viteConfigTS : filePaths.viteConfig,
11712
- svelteConfig: filePaths.svelteConfig
10030
+ viteConfig: type === "typescript" ? filePaths.viteConfigTS : filePaths.viteConfig
11713
10031
  }
11714
10032
  };
11715
10033
  }
@@ -12024,26 +10342,7 @@ async function promptAddonQuestions({ options, loadedAddons, workspace }) {
12024
10342
  }
12025
10343
  }
12026
10344
  const addonDefinitions = addons.map((a) => a.addon);
12027
- const verifications = [...verifyCleanWorkingDirectory(options.cwd, options.gitCheck), ...verifyUnsupportedAddons(addonDefinitions, setupResults)];
12028
- const fails = [];
12029
- for (const verification of verifications) {
12030
- const { message, success } = await verification.run();
12031
- if (!success) fails.push({
12032
- name: verification.name,
12033
- message
12034
- });
12035
- }
12036
- if (fails.length > 0) {
12037
- Ce(`- ${fails.map(({ name, message }) => color.warning(`${name} (${message})`)).join("\n- ")}`, "Verifications not met", { format: (line) => line });
12038
- const force = await le({
12039
- message: "Verifications failed. Do you wish to continue?",
12040
- initialValue: false
12041
- });
12042
- if (R$2(force) || !force) {
12043
- ge("Operation cancelled.");
12044
- V.exit(1);
12045
- }
12046
- }
10345
+ await runAndValidateVerifications([...verifyCleanWorkingDirectory(options.cwd, options.gitCheck), ...verifyUnsupportedAddons(addonDefinitions, setupResults)]);
12047
10346
  for (const loaded of addons) {
12048
10347
  const addon = loaded.addon;
12049
10348
  const addonId = addon.id;
@@ -12157,7 +10456,8 @@ async function runAddonsApply({ answers, options, loadedAddons, setupResults, wo
12157
10456
  if (depsInstalled) await formatFiles({
12158
10457
  packageManager,
12159
10458
  cwd: options.cwd,
12160
- filesToFormat
10459
+ filesToFormat,
10460
+ strategy: "files-only"
12161
10461
  });
12162
10462
  }
12163
10463
  const nextSteps = getNextSteps(successfulAddons, workspace, answers, setupResults);
@@ -12351,20 +10651,24 @@ function alphabetizeRecord(obj) {
12351
10651
  for (const [key, value] of Object.entries(obj).sort(([a], [b]) => a.localeCompare(b))) ordered[key] = value;
12352
10652
  return ordered;
12353
10653
  }
12354
- function updatePackages(dependencies, cwd) {
12355
- const { source } = loadPackageJson(cwd);
12356
- const { data, generateCode } = parse.json(source);
12357
- for (const dependency of dependencies) if (dependency.dev) {
12358
- data.devDependencies ??= {};
12359
- data.devDependencies[dependency.pkg] = dependency.version;
12360
- } else {
12361
- data.dependencies ??= {};
12362
- data.dependencies[dependency.pkg] = dependency.version;
12363
- }
12364
- if (data.dependencies) data.dependencies = alphabetizeRecord(data.dependencies);
12365
- if (data.devDependencies) data.devDependencies = alphabetizeRecord(data.devDependencies);
12366
- saveFile(cwd, filePaths.packageJson, generateCode());
12367
- return filePaths.packageJson;
10654
+ function updatePackages(dependencies, sv) {
10655
+ if (dependencies.length === 0) return;
10656
+ const pkgPath = filePaths.packageJson;
10657
+ sv.file(pkgPath, transforms.json(({ content, data }) => {
10658
+ if (!content) throw new Error(`Invalid workspace: missing '${pkgPath}'`);
10659
+ let modified = false;
10660
+ for (const { dev, pkg, version } of dependencies) {
10661
+ const dependency = dev ? "devDependencies" : "dependencies";
10662
+ data[dependency] ??= {};
10663
+ if (data[dependency][pkg] !== version) {
10664
+ modified = true;
10665
+ data[dependency][pkg] = version;
10666
+ }
10667
+ }
10668
+ if (!modified) return false;
10669
+ if (data.dependencies) data.dependencies = alphabetizeRecord(data.dependencies);
10670
+ if (data.devDependencies) data.devDependencies = alphabetizeRecord(data.devDependencies);
10671
+ }));
12368
10672
  }
12369
10673
  async function add({ addons, cwd, options, packageManager = "npm" }) {
12370
10674
  const workspace = await createWorkspace({
@@ -12453,31 +10757,88 @@ async function setupAddons(loadedAddons, workspace) {
12453
10757
  return setupResults;
12454
10758
  }
12455
10759
  async function runAddon({ addon, loaded, multiple, workspace, workspaceOptions }) {
12456
- const files = /* @__PURE__ */ new Set();
10760
+ let modifiedFiles = /* @__PURE__ */ new Set();
12457
10761
  const options = { ...workspaceOptions };
12458
10762
  for (const [id, question] of Object.entries(addon.options)) if (question.condition?.(options) !== false) options[id] ??= question.default;
10763
+ const { sv, finalize } = prepareSvApi(workspace, { executeOutputPrefix: multiple ? `${addon.id}: ` : "" });
10764
+ const cancels = [];
10765
+ try {
10766
+ await addon.run({
10767
+ cancel: (reason) => {
10768
+ cancels.push(reason);
10769
+ },
10770
+ ...workspace,
10771
+ options,
10772
+ sv
10773
+ });
10774
+ } catch (err) {
10775
+ const msg = err instanceof Error ? err.message : String(err);
10776
+ throw new Error(`Add-on '${addon.id}' failed during run: ${msg}\n\n${getErrorHint(loaded.reference.source)}`, { cause: err });
10777
+ }
10778
+ if (cancels.length === 0) ({modifiedFiles} = finalize());
10779
+ return {
10780
+ files: Array.from(modifiedFiles),
10781
+ cancels
10782
+ };
10783
+ }
10784
+ function editFile(file, edit, workspace, modifiedFiles, unmodifiedFiles, options, include) {
10785
+ try {
10786
+ const exists = fileExists(workspace.cwd, file);
10787
+ if (exists && !fs.statSync(path.resolve(workspace.cwd, file)).isFile()) return;
10788
+ const content = exists ? loadFile(workspace.cwd, file) : "";
10789
+ if (include === void 0 ? false : !include(content)) return;
10790
+ const editedContent = edit(content);
10791
+ if (editedContent === "" || editedContent === false) return;
10792
+ if (options.filesFilter && !path.matchesGlob(file, options.filesFilter)) {
10793
+ unmodifiedFiles.add(file);
10794
+ return;
10795
+ }
10796
+ const diffMinimizedEditedContent = minimizeDiff(content, editedContent);
10797
+ file = saveFile(workspace.cwd, file, diffMinimizedEditedContent, options.saveFileInfix);
10798
+ modifiedFiles.add(file);
10799
+ } catch (e) {
10800
+ if (e instanceof Error) e.message = `Unable to process '${file}'. Reason: ${e.message}`;
10801
+ throw e;
10802
+ }
10803
+ }
10804
+ function prepareSvApi(workspace, options = {
10805
+ filesFilter: void 0,
10806
+ executeOutputPrefix: void 0,
10807
+ saveFileInfix: void 0,
10808
+ additionalExcludes: void 0
10809
+ }) {
12459
10810
  const dependencies = [];
10811
+ const modifiedFiles = /* @__PURE__ */ new Set();
10812
+ const unmodifiedFiles = /* @__PURE__ */ new Set();
12460
10813
  const sv = {
12461
10814
  file: (path, edit) => {
12462
- try {
12463
- const content = fileExists(workspace.cwd, path) ? loadFile(workspace.cwd, path) : "";
12464
- const editedContent = edit(content);
12465
- if (editedContent === "" || editedContent === false) return content;
12466
- saveFile(workspace.cwd, path, editedContent);
12467
- files.add(path);
12468
- } catch (e) {
12469
- if (e instanceof Error) {
12470
- e.message = `Unable to process '${path}'. Reason: ${e.message}`;
12471
- throw e;
12472
- }
12473
- throw e;
10815
+ editFile(path, edit, workspace, modifiedFiles, unmodifiedFiles, options);
10816
+ },
10817
+ files: (opts, edit) => {
10818
+ const { include, exclude } = opts;
10819
+ const globbedFiles = fs.globSync(include, {
10820
+ cwd: workspace.cwd,
10821
+ exclude: [
10822
+ "node_modules/**",
10823
+ "**/node_modules/**",
10824
+ ".*/**",
10825
+ "**/.*/**",
10826
+ "build/**",
10827
+ "dist/**",
10828
+ ...options.additionalExcludes ?? [],
10829
+ ...exclude ?? []
10830
+ ]
10831
+ });
10832
+ for (const file of globbedFiles) {
10833
+ if (options.filesFilter && !path.matchesGlob(file, options.filesFilter)) continue;
10834
+ const singleFileEdit = (content) => edit(content, file);
10835
+ editFile(file, singleFileEdit, workspace, modifiedFiles, unmodifiedFiles, options, opts.where);
12474
10836
  }
12475
10837
  },
12476
10838
  execute: async (commandArgs, stdio) => {
12477
10839
  const { command, args } = resolveCommand(workspace.packageManager, "execute", commandArgs);
12478
- const addonPrefix = multiple ? `${addon.id}: ` : "";
12479
10840
  const executedCommand = [command, ...args].join(" ");
12480
- if (!TESTING) R$1.step(`${addonPrefix}Running external command ${color.optional(`(${executedCommand})`)}`);
10841
+ if (!TESTING) R$1.step(`${options?.executeOutputPrefix}Running external command ${color.optional(`(${executedCommand})`)}`);
12481
10842
  if (workspace.packageManager === "npm") args.unshift("--yes");
12482
10843
  try {
12483
10844
  await z(command, args, {
@@ -12504,34 +10865,17 @@ async function runAddon({ addon, loaded, multiple, workspace, workspaceOptions }
12504
10865
  version,
12505
10866
  dev: true
12506
10867
  });
12507
- },
12508
- /** @deprecated use `pnpm.allowBuilds` from `@sveltejs/sv-utils` instead */
12509
- pnpmBuildDependency: (pkg) => {
12510
- svDeprecated("use `pnpm.allowBuilds` from `@sveltejs/sv-utils` instead of `sv.pnpmBuildDependency`");
12511
- addPnpmAllowBuilds(workspace.cwd, workspace.packageManager, pkg);
12512
10868
  }
12513
10869
  };
12514
- const cancels = [];
12515
- try {
12516
- await addon.run({
12517
- cancel: (reason) => {
12518
- cancels.push(reason);
12519
- },
12520
- ...workspace,
12521
- options,
12522
- sv
12523
- });
12524
- } catch (err) {
12525
- const msg = err instanceof Error ? err.message : String(err);
12526
- throw new Error(`Add-on '${addon.id}' failed during run: ${msg}\n\n${getErrorHint(loaded.reference.source)}`, { cause: err });
12527
- }
12528
- if (cancels.length === 0) {
12529
- const pkgPath = updatePackages(dependencies, workspace.cwd);
12530
- files.add(pkgPath);
12531
- }
12532
10870
  return {
12533
- files: Array.from(files),
12534
- cancels
10871
+ sv,
10872
+ finalize: () => {
10873
+ updatePackages(dependencies, sv);
10874
+ return {
10875
+ modifiedFiles,
10876
+ unmodifiedFiles
10877
+ };
10878
+ }
12535
10879
  };
12536
10880
  }
12537
10881
  /**
@@ -12560,4 +10904,4 @@ function orderAddons(addons, setupResults) {
12560
10904
  return ordered;
12561
10905
  }
12562
10906
  //#endregion
12563
- export { __toESM as S, name as _, detectPackageManager as a, __commonJSMin as b, defineAddonOptions as c, Command as d, R as f, helpConfig as g, forwardExitCode as h, addPnpmAllowBuilds as i, from as l, create$1 as m, add$1 as n, officialAddons$1 as o, z as p, create as r, defineAddon as s, add as t, program as u, version as v, __require as x, svDeprecated as y };
10907
+ export { Command as A, name as B, pipe as C, union as D, transform as E, forwardExitCode as F, ge as G, Ce as H, helpConfig as I, we as J, le as K, normalizePosix as L, z as M, create$1 as N, from as O, errorAndExit as P, __toESM as Q, runAndValidateVerifications as R, picklist as S, string as T, Ee as U, version as V, R$1 as W, __commonJSMin as X, R$2 as Y, __require as Z, array as _, verifyCleanWorkingDirectory as a, optional as b, AGENT_NAMES as c, installDependencies as d, installOption as f, defineAddonOptions as g, defineAddon as h, create as i, R as j, program as k, addPnpmAllowBuilds as l, officialAddons$1 as m, prepareSvApi as n, formatFiles as o, packageManagerPrompt as p, vt as q, add$1 as r, createWorkspace as s, add as t, detectPackageManager as u, boolean as v, strictObject as w, parse$1 as x, literal as y, runCommand as z };