sandboxedjs 0.1.81 → 0.1.85

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.
@@ -3882,7 +3882,7 @@ var require_acorn = __commonJS({
3882
3882
  }
3883
3883
  return i2 + 2;
3884
3884
  };
3885
- RegExpValidationState3.prototype.current = function current2(forceU) {
3885
+ RegExpValidationState3.prototype.current = function current3(forceU) {
3886
3886
  if (forceU === void 0) forceU = false;
3887
3887
  return this.at(this.pos, forceU);
3888
3888
  };
@@ -3907,8 +3907,8 @@ var require_acorn = __commonJS({
3907
3907
  var pos = this.pos;
3908
3908
  for (var i2 = 0, list2 = chs; i2 < list2.length; i2 += 1) {
3909
3909
  var ch = list2[i2];
3910
- var current2 = this.at(pos, forceU);
3911
- if (current2 === -1 || current2 !== ch) {
3910
+ var current3 = this.at(pos, forceU);
3911
+ if (current3 === -1 || current3 !== ch) {
3912
3912
  return false;
3913
3913
  }
3914
3914
  pos = this.nextIndex(pos, forceU);
@@ -8795,7 +8795,7 @@ var require_path_browserify = __commonJS({
8795
8795
  if (hasRoot && end === 1) return "//";
8796
8796
  return path.slice(0, end);
8797
8797
  },
8798
- basename: function basename(path, ext) {
8798
+ basename: function basename2(path, ext) {
8799
8799
  if (ext !== void 0 && typeof ext !== "string") throw new TypeError('"ext" argument must be a string');
8800
8800
  assertPath(path);
8801
8801
  var start = 0;
@@ -8849,7 +8849,7 @@ var require_path_browserify = __commonJS({
8849
8849
  return path.slice(start, end);
8850
8850
  }
8851
8851
  },
8852
- extname: function extname(path) {
8852
+ extname: function extname2(path) {
8853
8853
  assertPath(path);
8854
8854
  var startDot = -1;
8855
8855
  var startPart = 0;
@@ -9583,11 +9583,11 @@ var require_stream_writable = __commonJS({
9583
9583
  this.corkedRequestsFree = new CorkedRequest(this);
9584
9584
  }
9585
9585
  WritableState.prototype.getBuffer = function getBuffer() {
9586
- var current2 = this.bufferedRequest;
9586
+ var current3 = this.bufferedRequest;
9587
9587
  var out = [];
9588
- while (current2) {
9589
- out.push(current2);
9590
- current2 = current2.next;
9588
+ while (current3) {
9589
+ out.push(current3);
9590
+ current3 = current3.next;
9591
9591
  }
9592
9592
  return out;
9593
9593
  };
@@ -11188,12 +11188,12 @@ var require_stream_readable = __commonJS({
11188
11188
  if (!state.flowing) {
11189
11189
  debug("resume");
11190
11190
  state.flowing = !state.readableListening;
11191
- resume(this, state);
11191
+ resume2(this, state);
11192
11192
  }
11193
11193
  state.paused = false;
11194
11194
  return this;
11195
11195
  };
11196
- function resume(stream, state) {
11196
+ function resume2(stream, state) {
11197
11197
  if (!state.resumeScheduled) {
11198
11198
  state.resumeScheduled = true;
11199
11199
  process.nextTick(resume_, stream, state);
@@ -15513,6 +15513,18 @@ function dirname(p) {
15513
15513
  if (idx === 0) return "/";
15514
15514
  return norm.slice(0, idx);
15515
15515
  }
15516
+ function basename(p, ext) {
15517
+ const norm = stripTrailing(normalize(p));
15518
+ if (norm === "/") return "/";
15519
+ const idx = norm.lastIndexOf("/");
15520
+ let base2 = idx < 0 ? norm : norm.slice(idx + 1);
15521
+ return base2;
15522
+ }
15523
+ function extname(p) {
15524
+ const base2 = basename(p);
15525
+ const idx = base2.lastIndexOf(".");
15526
+ return idx <= 0 ? "" : base2.slice(idx);
15527
+ }
15516
15528
  function clean(p) {
15517
15529
  return stripTrailing(normalize(p));
15518
15530
  }
@@ -19157,8 +19169,8 @@ RegExpValidationState.prototype.eatChars = function eatChars(chs, forceU) {
19157
19169
  var pos = this.pos;
19158
19170
  for (var i = 0, list = chs; i < list.length; i += 1) {
19159
19171
  var ch = list[i];
19160
- var current2 = this.at(pos, forceU);
19161
- if (current2 === -1 || current2 !== ch) {
19172
+ var current3 = this.at(pos, forceU);
19173
+ if (current3 === -1 || current3 !== ch) {
19162
19174
  return false;
19163
19175
  }
19164
19176
  pos = this.nextIndex(pos, forceU);
@@ -21472,9 +21484,9 @@ ${applyEdits(source, edits)}` : applyEdits(source, edits),
21472
21484
  }
21473
21485
  }
21474
21486
  function lookup(name, scope) {
21475
- for (let current2 = scope; current2; current2 = current2.parent) {
21476
- if (current2.names.has(name)) {
21477
- return current2.parent === null ? importBindings.get(name) ?? null : null;
21487
+ for (let current3 = scope; current3; current3 = current3.parent) {
21488
+ if (current3.names.has(name)) {
21489
+ return current3.parent === null ? importBindings.get(name) ?? null : null;
21478
21490
  }
21479
21491
  }
21480
21492
  return null;
@@ -21507,7 +21519,7 @@ function containsImportExpression(node) {
21507
21519
  function containsImportMeta(node) {
21508
21520
  if (Array.isArray(node)) return node.some(containsImportMeta);
21509
21521
  if (!isNode(node)) return false;
21510
- if (node.type === "MetaProperty") return true;
21522
+ if (node.type === "MetaProperty" && node.meta?.name === "import") return true;
21511
21523
  for (const [key, value] of Object.entries(node)) {
21512
21524
  if (key === "type" || key === "start" || key === "end") continue;
21513
21525
  if (containsImportMeta(value)) return true;
@@ -21618,6 +21630,261 @@ var NOTHING = [];
21618
21630
  var PROPERTY = ["property", "key"];
21619
21631
  var LABEL = ["label"];
21620
21632
 
21633
+ // src/node/async-context-transform.ts
21634
+ var import_acorn_jsx2 = __toESM(require_acorn_jsx());
21635
+
21636
+ // src/node/async-context.ts
21637
+ var EMPTY = /* @__PURE__ */ new Map();
21638
+ var current2 = EMPTY;
21639
+ function capture() {
21640
+ return current2;
21641
+ }
21642
+ function restore(frame) {
21643
+ current2 = frame ?? EMPTY;
21644
+ }
21645
+ function resume(frame, value) {
21646
+ current2 = frame;
21647
+ return value;
21648
+ }
21649
+ function runInFrame(frame, fn) {
21650
+ const previous = current2;
21651
+ current2 = frame;
21652
+ try {
21653
+ return fn();
21654
+ } finally {
21655
+ current2 = previous;
21656
+ }
21657
+ }
21658
+ function bindToCurrent(fn) {
21659
+ const frame = current2;
21660
+ if (frame === EMPTY) {
21661
+ return function(...args) {
21662
+ return runInFrame(EMPTY, () => fn.apply(this, args));
21663
+ };
21664
+ }
21665
+ return function(...args) {
21666
+ return runInFrame(frame, () => fn.apply(this, args));
21667
+ };
21668
+ }
21669
+ function installPromiseContext(PromiseClass = Promise) {
21670
+ const proto = PromiseClass.prototype;
21671
+ if (proto.__sbxContextThen) return;
21672
+ const nativeThen = proto.then;
21673
+ Object.defineProperty(proto, "then", {
21674
+ configurable: true,
21675
+ writable: true,
21676
+ value: function then(onFulfilled, onRejected) {
21677
+ const frame = current2;
21678
+ const wrap2 = (handler) => typeof handler === "function" ? (value) => runInFrame(frame, () => handler(value)) : handler;
21679
+ return nativeThen.call(this, wrap2(onFulfilled), wrap2(onRejected));
21680
+ }
21681
+ });
21682
+ Object.defineProperty(proto, "__sbxContextThen", { value: true });
21683
+ }
21684
+ var AsyncLocalStorage = class {
21685
+ #enabled = true;
21686
+ getStore() {
21687
+ return current2.get(this);
21688
+ }
21689
+ run(store, callback, ...args) {
21690
+ const next = new Map(current2);
21691
+ next.set(this, store);
21692
+ this.#enabled = true;
21693
+ return runInFrame(next, () => callback(...args));
21694
+ }
21695
+ exit(callback, ...args) {
21696
+ if (!current2.has(this)) return callback(...args);
21697
+ const next = new Map(current2);
21698
+ next.delete(this);
21699
+ return runInFrame(next, () => callback(...args));
21700
+ }
21701
+ /** Replace the store for the rest of the current execution and its continuations. */
21702
+ enterWith(store) {
21703
+ const next = new Map(current2);
21704
+ next.set(this, store);
21705
+ current2 = next;
21706
+ this.#enabled = true;
21707
+ }
21708
+ disable() {
21709
+ if (!this.#enabled) return;
21710
+ this.#enabled = false;
21711
+ if (current2.has(this)) {
21712
+ const next = new Map(current2);
21713
+ next.delete(this);
21714
+ current2 = next;
21715
+ }
21716
+ }
21717
+ static bind(fn) {
21718
+ return bindToCurrent(fn);
21719
+ }
21720
+ static snapshot() {
21721
+ const frame = current2;
21722
+ return (fn, ...args) => runInFrame(frame, () => fn(...args));
21723
+ }
21724
+ };
21725
+ var AsyncResource = class _AsyncResource {
21726
+ #frame;
21727
+ type;
21728
+ constructor(type, _options) {
21729
+ this.type = type;
21730
+ this.#frame = current2;
21731
+ }
21732
+ runInAsyncScope(fn, thisArg, ...args) {
21733
+ return runInFrame(this.#frame, () => fn.apply(thisArg, args));
21734
+ }
21735
+ bind(fn, thisArg) {
21736
+ return ((...args) => this.runInAsyncScope(fn, thisArg, ...args));
21737
+ }
21738
+ emitDestroy() {
21739
+ return this;
21740
+ }
21741
+ asyncId() {
21742
+ return 1;
21743
+ }
21744
+ triggerAsyncId() {
21745
+ return 0;
21746
+ }
21747
+ static bind(fn, type = "bound-anonymous-fn", thisArg) {
21748
+ return new _AsyncResource(type).bind(fn, thisArg);
21749
+ }
21750
+ };
21751
+ var CONTEXT_HELPERS = {
21752
+ capture: "__sbxCapture",
21753
+ resume: "__sbxResume",
21754
+ restore: "__sbxRestore"
21755
+ };
21756
+
21757
+ // src/node/async-context-transform.ts
21758
+ var JSX_EXTENSION2 = /\.[jt]sx$/;
21759
+ var JsxParser2 = Parser.extend((0, import_acorn_jsx2.default)());
21760
+ var MAYBE_AWAIT = /\bawait\b/;
21761
+ var OPTIONS_MODULE = {
21762
+ ecmaVersion: "latest",
21763
+ sourceType: "module",
21764
+ allowAwaitOutsideFunction: true,
21765
+ allowHashBang: true,
21766
+ allowReturnOutsideFunction: true,
21767
+ allowImportExportEverywhere: true
21768
+ };
21769
+ var OPTIONS_SCRIPT = { ...OPTIONS_MODULE, sourceType: "script" };
21770
+ var { capture: CAPTURE, resume: RESUME, restore: RESTORE } = CONTEXT_HELPERS;
21771
+ function transformAsyncContext(source, filename = "module.js") {
21772
+ if (!MAYBE_AWAIT.test(source)) return null;
21773
+ const ast = parseEither(source, filename);
21774
+ if (!ast) return null;
21775
+ const edits = collectEdits(ast, source, filename);
21776
+ if (edits.length === 0) return null;
21777
+ return applyEdits2(source, edits);
21778
+ }
21779
+ function parseEither(source, filename) {
21780
+ const parser = JSX_EXTENSION2.test(filename) ? JsxParser2.parse.bind(JsxParser2) : parse3;
21781
+ for (const options of [OPTIONS_SCRIPT, OPTIONS_MODULE]) {
21782
+ try {
21783
+ return parser(source, options);
21784
+ } catch {
21785
+ }
21786
+ }
21787
+ return null;
21788
+ }
21789
+ var frameCounter = 0;
21790
+ function collectEdits(root, source, filename) {
21791
+ const edits = [];
21792
+ const visit = (node) => {
21793
+ if (Array.isArray(node)) {
21794
+ for (const item of node) visit(item);
21795
+ return;
21796
+ }
21797
+ if (!isNode2(node)) return;
21798
+ switch (node.type) {
21799
+ case "AwaitExpression": {
21800
+ edits.push({ start: node.start, end: node.start, text: `${RESUME}(${CAPTURE}(), ` });
21801
+ edits.push({ start: node.end, end: node.end, text: ")" });
21802
+ visit(node.argument);
21803
+ return;
21804
+ }
21805
+ case "TryStatement": {
21806
+ if (containsAwait(node.block) || containsAwait(node.handler) || containsAwait(node.finalizer)) {
21807
+ const frame = `__sbxFrame${frameCounter++}`;
21808
+ edits.push({ start: node.start, end: node.start, text: `{ const ${frame} = ${CAPTURE}(); ` });
21809
+ const handler = node.handler;
21810
+ if (handler) {
21811
+ const body = handler.body;
21812
+ edits.push({ start: body.start + 1, end: body.start + 1, text: ` ${RESTORE}(${frame});` });
21813
+ }
21814
+ const finalizer = node.finalizer;
21815
+ if (finalizer) {
21816
+ edits.push({ start: finalizer.start + 1, end: finalizer.start + 1, text: ` ${RESTORE}(${frame});` });
21817
+ }
21818
+ edits.push({ start: node.end, end: node.end, text: " }" });
21819
+ }
21820
+ visit(node.block);
21821
+ visit(node.handler);
21822
+ visit(node.finalizer);
21823
+ return;
21824
+ }
21825
+ case "ForOfStatement": {
21826
+ if (node.await === true) {
21827
+ const frame = `__sbxFrame${frameCounter++}`;
21828
+ const body = node.body;
21829
+ edits.push({ start: node.start, end: node.start, text: `{ const ${frame} = ${CAPTURE}(); ` });
21830
+ if (body.type === "BlockStatement") {
21831
+ edits.push({ start: body.start + 1, end: body.start + 1, text: ` ${RESTORE}(${frame});` });
21832
+ } else {
21833
+ edits.push({ start: body.start, end: body.start, text: `{ ${RESTORE}(${frame}); ` });
21834
+ edits.push({ start: body.end, end: body.end, text: " }" });
21835
+ }
21836
+ edits.push({ start: node.end, end: node.end, text: " }" });
21837
+ }
21838
+ visit(node.left);
21839
+ visit(node.right);
21840
+ visit(node.body);
21841
+ return;
21842
+ }
21843
+ case "CallExpression": {
21844
+ const callee = node.callee;
21845
+ const args = node.arguments;
21846
+ const first = args[0];
21847
+ if (callee.type === "Identifier" && callee.name === "eval" && first && first.type === "Literal" && typeof first.value === "string" && MAYBE_AWAIT.test(first.value)) {
21848
+ const inner = transformAsyncContext(first.value, filename);
21849
+ if (inner !== null) edits.push({ start: first.start, end: first.end, text: JSON.stringify(inner) });
21850
+ for (const argument of args.slice(1)) visit(argument);
21851
+ return;
21852
+ }
21853
+ break;
21854
+ }
21855
+ }
21856
+ for (const [key, value] of Object.entries(node)) {
21857
+ if (key === "type" || key === "start" || key === "end") continue;
21858
+ if (value && typeof value === "object") visit(value);
21859
+ }
21860
+ };
21861
+ visit(root);
21862
+ return edits;
21863
+ }
21864
+ function containsAwait(node) {
21865
+ if (Array.isArray(node)) return node.some(containsAwait);
21866
+ if (!isNode2(node)) return false;
21867
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
21868
+ return false;
21869
+ }
21870
+ if (node.type === "AwaitExpression") return true;
21871
+ if (node.type === "ForOfStatement" && node.await === true) return true;
21872
+ for (const [key, value] of Object.entries(node)) {
21873
+ if (key === "type" || key === "start" || key === "end") continue;
21874
+ if (value && typeof value === "object" && containsAwait(value)) return true;
21875
+ }
21876
+ return false;
21877
+ }
21878
+ function applyEdits2(source, edits) {
21879
+ const ordered = edits.map((edit, index) => ({ ...edit, index })).sort((a, b) => b.start - a.start || b.end - a.end || b.index - a.index);
21880
+ let out = source;
21881
+ for (const edit of ordered) out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
21882
+ return out;
21883
+ }
21884
+ function isNode2(value) {
21885
+ return typeof value === "object" && value !== null && typeof value.type === "string";
21886
+ }
21887
+
21621
21888
  // node_modules/resolve.exports/dist/index.mjs
21622
21889
  function e(e2, n2, r2) {
21623
21890
  throw new Error(r2 ? `No known conditions for "${n2}" specifier in "${e2}" package` : `Missing "${n2}" specifier in "${e2}" package`);
@@ -21686,6 +21953,62 @@ var CommonJsEngine = class {
21686
21953
  this.globals = { ...options.globals };
21687
21954
  this.aliases = { ...options.aliases };
21688
21955
  this.overrides = { ...options.overrides };
21956
+ const engine = this;
21957
+ this.moduleApi = function Module(id = "", parent = null) {
21958
+ Object.assign(this, { id, filename: id, exports: {}, loaded: false, parent, children: [] });
21959
+ };
21960
+ Object.assign(this.moduleApi, this.builtins.module);
21961
+ this.moduleApi.Module = this.moduleApi;
21962
+ this.moduleApi._extensions = {
21963
+ ".js": (module, filename) => this.evaluate(module, this.readText(filename)),
21964
+ ".json": (module, filename) => {
21965
+ module.exports = JSON.parse(this.readText(filename));
21966
+ },
21967
+ ".node": (_module, filename) => {
21968
+ throw dlopenFailed(filename);
21969
+ }
21970
+ };
21971
+ this.moduleApi._cache = new Proxy(/* @__PURE__ */ Object.create(null), {
21972
+ get: (_target, key) => typeof key === "string" ? this.cache.get(key) : void 0,
21973
+ set: (_target, key, value) => {
21974
+ this.cache.set(String(key), value);
21975
+ return true;
21976
+ },
21977
+ deleteProperty: (_target, key) => this.cache.delete(String(key)),
21978
+ ownKeys: () => [...this.cache.keys()],
21979
+ getOwnPropertyDescriptor: (_target, key) => this.cache.has(String(key)) ? { enumerable: true, configurable: true, writable: true, value: this.cache.get(String(key)) } : void 0
21980
+ });
21981
+ this.moduleApi._resolveFilename = (request, parent) => this.resolve(request, parent?.filename || join(this.cwd, "__entry__.js"));
21982
+ this.moduleApi._nodeModulePaths = (from) => {
21983
+ const directory = resolve(this.cwd, String(from));
21984
+ if (directory === "/") return ["/node_modules"];
21985
+ const parts = segments(directory);
21986
+ const paths = [];
21987
+ for (let index = parts.length; index > 0; index--) {
21988
+ if (parts[index - 1] === "node_modules") continue;
21989
+ paths.push(`/${[...parts.slice(0, index), "node_modules"].join("/")}`);
21990
+ }
21991
+ paths.push("/node_modules");
21992
+ return paths;
21993
+ };
21994
+ this.moduleApi._load = (request, parent) => this.makeRequire(parent ?? Object.assign(new this.moduleApi(join(this.cwd, "__entry__.js")), { filename: join(this.cwd, "__entry__.js") }))(request);
21995
+ this.moduleApi.prototype.require = function(request) {
21996
+ const filename = engine.moduleApi._resolveFilename(request, this);
21997
+ const builtin = engine.builtin(filename, this);
21998
+ if (builtin.found) return builtin.value;
21999
+ const target = engine.load(filename, this, false);
22000
+ if (target.pending) throw requireOfAsyncModule(request);
22001
+ return target.exports;
22002
+ };
22003
+ this.moduleApi.prototype._compile = function(source, filename) {
22004
+ this.filename = filename;
22005
+ engine.evaluate(this, source);
22006
+ };
22007
+ this.moduleApi.createRequire = (filename) => {
22008
+ const path = String(filename).startsWith("file:") ? pathFromFileUrl(String(filename)) : String(filename);
22009
+ if (!path.startsWith("/")) throw new TypeError("createRequire requires an absolute path or file URL");
22010
+ return this.makeRequire(Object.assign(new this.moduleApi(path), { filename: path }));
22011
+ };
21689
22012
  }
21690
22013
  volume;
21691
22014
  cache = /* @__PURE__ */ new Map();
@@ -21698,6 +22021,7 @@ var CommonJsEngine = class {
21698
22021
  /** `package.json` per directory; resolution reads them constantly. */
21699
22022
  manifests = /* @__PURE__ */ new Map();
21700
22023
  evaluationDepth = 0;
22024
+ moduleApi;
21701
22025
  /**
21702
22026
  * Is a module body running synchronously right now?
21703
22027
  *
@@ -21734,7 +22058,7 @@ var CommonJsEngine = class {
21734
22058
  specifier = pathFromFileUrl(specifier);
21735
22059
  }
21736
22060
  const builtin = this.builtin(specifier);
21737
- if (builtin.found) return specifier.replace(/^node:/, "");
22061
+ if (builtin.found) return specifier;
21738
22062
  if (specifier.startsWith("#")) {
21739
22063
  const found = this.resolveImports(specifier, importer, kind);
21740
22064
  if (found) return found;
@@ -21767,17 +22091,14 @@ var CommonJsEngine = class {
21767
22091
  parent,
21768
22092
  children: []
21769
22093
  };
22094
+ Object.setPrototypeOf(module, this.moduleApi.prototype);
21770
22095
  this.cache.set(filename, module);
21771
22096
  parent?.children.push(module);
21772
22097
  if (isMain) this.main = module;
21773
22098
  try {
21774
- if (filename.endsWith(".node")) {
21775
- throw dlopenFailed(filename);
21776
- } else if (filename.endsWith(".json")) {
21777
- module.exports = JSON.parse(this.readText(filename));
21778
- } else {
21779
- this.evaluate(module, this.readText(filename));
21780
- }
22099
+ const extension = extname(filename);
22100
+ const loader = this.moduleApi._extensions[extension] ?? this.moduleApi._extensions[".js"];
22101
+ loader(module, filename);
21781
22102
  module.loaded = true;
21782
22103
  return module;
21783
22104
  } catch (error) {
@@ -21789,7 +22110,8 @@ var CommonJsEngine = class {
21789
22110
  evaluate(module, source) {
21790
22111
  if (source.startsWith("#!")) source = source.replace(/^#![^\n]*(?:\n|$)/, "");
21791
22112
  const transformed = transformEsm(source, module.filename);
21792
- const body = transformed?.code ?? source;
22113
+ const esmBody = transformed?.code ?? source;
22114
+ const body = transformAsyncContext(esmBody, module.filename) ?? esmBody;
21793
22115
  const code = transformed?.topLevelAwait ? `return (async () => {
21794
22116
  ${body}
21795
22117
  })();` : body;
@@ -21797,7 +22119,10 @@ ${body}
21797
22119
  [HELPERS.import, (specifier) => this.importNamespace(specifier, module)],
21798
22120
  [HELPERS.dynamic, (specifier) => this.dynamicImport(specifier, module)],
21799
22121
  [HELPERS.exportAll, exportAll],
21800
- [HELPERS.meta, this.importMeta(module)]
22122
+ [HELPERS.meta, this.importMeta(module)],
22123
+ [CONTEXT_HELPERS.capture, capture],
22124
+ [CONTEXT_HELPERS.resume, resume],
22125
+ [CONTEXT_HELPERS.restore, restore]
21801
22126
  ];
21802
22127
  const bindings = transformed?.esm ? [[HELPERS.exports, module.exports], ...helpers] : [
21803
22128
  ["exports", module.exports],
@@ -21830,15 +22155,12 @@ ${code}
21830
22155
  /** The `require` a module sees, complete with `resolve`, `cache` and `main`. */
21831
22156
  makeRequire(module) {
21832
22157
  const localRequire = ((specifier) => {
21833
- const builtin = this.builtin(specifier, module);
21834
- if (builtin.found) return builtin.value;
21835
- const target = this.load(this.resolve(specifier, module.filename, "require"), module, false);
21836
- if (target.pending) throw requireOfAsyncModule(specifier);
21837
- return target.exports;
22158
+ return this.moduleApi.prototype.require.call(module, specifier);
21838
22159
  });
21839
- localRequire.resolve = (specifier) => this.resolve(specifier, module.filename, "require");
22160
+ localRequire.resolve = (specifier) => this.moduleApi._resolveFilename(specifier, module);
21840
22161
  Object.defineProperty(localRequire, "main", { get: () => this.main });
21841
- localRequire.cache = Object.fromEntries(this.cache);
22162
+ localRequire.cache = this.moduleApi._cache;
22163
+ localRequire.extensions = this.moduleApi._extensions;
21842
22164
  return localRequire;
21843
22165
  }
21844
22166
  /**
@@ -22013,12 +22335,7 @@ ${code}
22013
22335
  if (prefixOnly || !Object.prototype.hasOwnProperty.call(this.builtins, name)) {
22014
22336
  return Object.prototype.hasOwnProperty.call(this.overrides, specifier) ? { found: true, value: this.overrides[specifier] } : { found: false, value: void 0 };
22015
22337
  }
22016
- if (name === "module" && importer) {
22017
- return {
22018
- found: true,
22019
- value: { ...this.builtins.module, createRequire: () => this.makeRequire(importer) }
22020
- };
22021
- }
22338
+ if (name === "module") return { found: true, value: this.moduleApi };
22022
22339
  return { found: true, value: this.builtins[name] };
22023
22340
  }
22024
22341
  exists(path) {
@@ -22126,10 +22443,229 @@ function splitSpecifier(specifier) {
22126
22443
  return { name: parts.slice(0, size).join("/"), subpath: parts.slice(size).join("/") };
22127
22444
  }
22128
22445
 
22446
+ // src/node/diagnostics-channel.ts
22447
+ function createDiagnosticsChannel() {
22448
+ const channels = /* @__PURE__ */ new Map();
22449
+ class Channel {
22450
+ constructor(name) {
22451
+ this.name = name;
22452
+ }
22453
+ name;
22454
+ listeners = /* @__PURE__ */ new Set();
22455
+ get hasSubscribers() {
22456
+ return this.listeners.size > 0;
22457
+ }
22458
+ subscribe(fn) {
22459
+ if (typeof fn !== "function") throw new TypeError("subscriber must be a function");
22460
+ this.listeners.add(fn);
22461
+ }
22462
+ unsubscribe(fn) {
22463
+ return this.listeners.delete(fn);
22464
+ }
22465
+ publish(message) {
22466
+ for (const fn of [...this.listeners]) {
22467
+ try {
22468
+ fn(message, this.name);
22469
+ } catch (error) {
22470
+ queueMicrotask(() => {
22471
+ throw error;
22472
+ });
22473
+ }
22474
+ }
22475
+ }
22476
+ }
22477
+ const channel = (name) => {
22478
+ if (typeof name !== "string" && typeof name !== "symbol") throw new TypeError("channel name must be a string or symbol");
22479
+ let result = channels.get(name);
22480
+ if (!result) {
22481
+ result = new Channel(name);
22482
+ channels.set(name, result);
22483
+ }
22484
+ return result;
22485
+ };
22486
+ return {
22487
+ Channel,
22488
+ channel,
22489
+ hasSubscribers: (name) => channels.get(name)?.hasSubscribers ?? false,
22490
+ subscribe: (name, fn) => channel(name).subscribe(fn),
22491
+ unsubscribe: (name, fn) => channels.get(name)?.unsubscribe(fn) ?? false
22492
+ };
22493
+ }
22494
+
22495
+ // src/node/ipc-channel.ts
22496
+ var IPC_CHANNEL_ENV = "SANDBOXEDJS_IPC_CHANNEL";
22497
+ function newIpcChannelId() {
22498
+ const random = typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID() : Math.random().toString(36).slice(2);
22499
+ return `ipc-${random}`;
22500
+ }
22501
+
22502
+ // src/node/vm-module.ts
22503
+ var contexts = /* @__PURE__ */ new WeakSet();
22504
+ var globalEval = eval;
22505
+ var filenameOf = (options) => typeof options === "string" ? options : options?.filename;
22506
+ var withSourceUrl = (code, options) => {
22507
+ const filename = filenameOf(options);
22508
+ return filename ? `${code}
22509
+ //# sourceURL=${filename.replace(/\s/g, "%20")}` : code;
22510
+ };
22511
+ function runWithScope(code, sandbox, options) {
22512
+ const scope = new Proxy(sandbox, {
22513
+ /* The wrapper's own variables must resolve to the wrapper, never to the
22514
+ * context — otherwise `__sbx_vm_result__ = eval(…)` stores the completion
22515
+ * value on the sandbox and the function returns undefined. */
22516
+ has: (target, key) => !(typeof key === "string" && key.startsWith("__sbx_vm_")) && (key in target || !(key in globalThis)),
22517
+ get: (target, key) => {
22518
+ if (key === Symbol.unscopables) return void 0;
22519
+ if (key in target) return target[key];
22520
+ return globalThis[key];
22521
+ },
22522
+ set: (target, key, value) => {
22523
+ target[key] = value;
22524
+ return true;
22525
+ }
22526
+ });
22527
+ const declared = topLevelDeclarations(code);
22528
+ const evaluate = new Function(
22529
+ "__sbx_vm_scope__",
22530
+ "__sbx_vm_source__",
22531
+ "__sbx_vm_names__",
22532
+ "__sbx_vm_target__",
22533
+ "var __sbx_vm_result__; with (__sbx_vm_scope__) { __sbx_vm_result__ = eval(__sbx_vm_source__); }for (var __sbx_vm_i__ = 0; __sbx_vm_i__ < __sbx_vm_names__.length; __sbx_vm_i__++) { try { var __sbx_vm_value__ = eval(__sbx_vm_names__[__sbx_vm_i__]); if (__sbx_vm_value__ !== undefined || !(__sbx_vm_names__[__sbx_vm_i__] in __sbx_vm_target__)) __sbx_vm_target__[__sbx_vm_names__[__sbx_vm_i__]] = __sbx_vm_value__; } catch (e) {}}return __sbx_vm_result__;"
22534
+ );
22535
+ return evaluate(scope, withSourceUrl(code, options), declared, sandbox);
22536
+ }
22537
+ function topLevelDeclarations(code) {
22538
+ const names = /* @__PURE__ */ new Set();
22539
+ let depth = 0;
22540
+ for (let index = 0; index < code.length; index++) {
22541
+ const char = code[index];
22542
+ if (char === "/" && code[index + 1] === "/") {
22543
+ const end = code.indexOf("\n", index);
22544
+ index = end === -1 ? code.length : end;
22545
+ continue;
22546
+ }
22547
+ if (char === "/" && code[index + 1] === "*") {
22548
+ const end = code.indexOf("*/", index + 2);
22549
+ index = end === -1 ? code.length : end + 1;
22550
+ continue;
22551
+ }
22552
+ if (char === '"' || char === "'" || char === "`") {
22553
+ for (index++; index < code.length && code[index] !== char; index++) if (code[index] === "\\") index++;
22554
+ continue;
22555
+ }
22556
+ if (char === "{") {
22557
+ depth++;
22558
+ continue;
22559
+ }
22560
+ if (char === "}") {
22561
+ depth = Math.max(0, depth - 1);
22562
+ continue;
22563
+ }
22564
+ if (depth !== 0 || !/[A-Za-z_$]/.test(char) || index > 0 && /[\w$]/.test(code[index - 1])) continue;
22565
+ const rest = code.slice(index);
22566
+ const fn = /^(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/.exec(rest);
22567
+ if (fn) {
22568
+ names.add(fn[1]);
22569
+ continue;
22570
+ }
22571
+ const declaration = /^var\s+([^;]+)/.exec(rest);
22572
+ if (declaration) {
22573
+ for (const part of declaration[1].split(",")) {
22574
+ const name = /^\s*([A-Za-z_$][\w$]*)/.exec(part);
22575
+ if (name) names.add(name[1]);
22576
+ }
22577
+ }
22578
+ }
22579
+ return [...names];
22580
+ }
22581
+ function createContext(sandbox = {}) {
22582
+ contexts.add(sandbox);
22583
+ if (!("globalThis" in sandbox)) Object.defineProperty(sandbox, "globalThis", { value: sandbox, writable: true, configurable: true });
22584
+ return sandbox;
22585
+ }
22586
+ function isContext(value) {
22587
+ return typeof value === "object" && value !== null && contexts.has(value);
22588
+ }
22589
+ function runInThisContext(code, options) {
22590
+ return globalEval(withSourceUrl(String(code), options));
22591
+ }
22592
+ function runInContext(code, context, options) {
22593
+ if (!isContext(context)) {
22594
+ throw Object.assign(new TypeError('The "contextifiedObject" argument must be an vm.Context'), { code: "ERR_INVALID_ARG_TYPE" });
22595
+ }
22596
+ return runWithScope(String(code), context, options);
22597
+ }
22598
+ function runInNewContext(code, sandbox, options) {
22599
+ return runWithScope(String(code), createContext(sandbox ?? {}), options);
22600
+ }
22601
+ var Script = class {
22602
+ #code;
22603
+ #options;
22604
+ constructor(code, options = {}) {
22605
+ this.#code = String(code);
22606
+ this.#options = typeof options === "string" ? { filename: options } : { ...options };
22607
+ new Function(this.#code.replace(/^#!.*/, ""));
22608
+ }
22609
+ runInThisContext(options) {
22610
+ return runInThisContext(this.#code, { ...this.#options, ...options });
22611
+ }
22612
+ runInContext(context, options) {
22613
+ return runInContext(this.#code, context, { ...this.#options, ...options });
22614
+ }
22615
+ runInNewContext(sandbox, options) {
22616
+ return runInNewContext(this.#code, sandbox, { ...this.#options, ...options });
22617
+ }
22618
+ createCachedData() {
22619
+ return new Uint8Array();
22620
+ }
22621
+ };
22622
+ function compileFunction(code, params = [], options = {}) {
22623
+ const source = withSourceUrl(String(code), options.filename);
22624
+ if (options.parsingContext && isContext(options.parsingContext)) {
22625
+ return runWithScope(`(function (${params.join(", ")}) {
22626
+ ${source}
22627
+ })`, options.parsingContext, void 0);
22628
+ }
22629
+ return new Function(...params, source);
22630
+ }
22631
+ var vmModule = {
22632
+ Script,
22633
+ createContext,
22634
+ isContext,
22635
+ runInThisContext,
22636
+ runInContext,
22637
+ runInNewContext,
22638
+ compileFunction,
22639
+ constants: {
22640
+ USE_MAIN_CONTEXT_DEFAULT_LOADER: /* @__PURE__ */ Symbol("vm_dynamic_import_main_context_default"),
22641
+ DONT_CONTEXTIFY: /* @__PURE__ */ Symbol("vm_context_no_contextify")
22642
+ },
22643
+ measureMemory: async () => ({ total: { jsMemoryEstimate: 0, jsMemoryRange: [0, 0] } })
22644
+ };
22645
+ var vm_module_default = vmModule;
22646
+
22129
22647
  // src/node/buffer-module.ts
22130
22648
  var import_buffer = __toESM(require_buffer());
22131
22649
  var platformBuffer = globalThis.Buffer;
22132
- var Buffer2 = platformBuffer ?? addBase64UrlSupport(import_buffer.Buffer);
22650
+ addUint8ArraySupport(addBase64UrlSupport(import_buffer.Buffer));
22651
+ var Buffer2 = platformBuffer ?? import_buffer.Buffer;
22652
+ function addUint8ArraySupport(BufferClass) {
22653
+ const target = BufferClass;
22654
+ if (target.__sandboxedUint8Array) return BufferClass;
22655
+ Object.defineProperty(target, "__sandboxedUint8Array", { value: true });
22656
+ const asBuffer = (value) => value instanceof Uint8Array && !target.isBuffer(value) ? target.from(value.buffer, value.byteOffset, value.byteLength) : value;
22657
+ for (const method of ["indexOf", "lastIndexOf", "includes"]) {
22658
+ const original = target.prototype[method];
22659
+ target.prototype[method] = function(value, ...rest) {
22660
+ return original.call(this, asBuffer(value), ...rest);
22661
+ };
22662
+ }
22663
+ const equals = target.prototype.equals;
22664
+ target.prototype.equals = function(other) {
22665
+ return equals.call(this, asBuffer(other));
22666
+ };
22667
+ return BufferClass;
22668
+ }
22133
22669
  function addBase64UrlSupport(BufferClass) {
22134
22670
  const target = BufferClass;
22135
22671
  if (target.__sandboxedBase64Url) return BufferClass;
@@ -22160,90 +22696,330 @@ function normalizeEncoding(value) {
22160
22696
  // src/node/core-modules.ts
22161
22697
  var import_events4 = __toESM(require_events());
22162
22698
  var import_path_browserify = __toESM(require_path_browserify());
22163
- var import_stream_browserify4 = __toESM(require_stream_browserify());
22699
+ var import_stream_browserify5 = __toESM(require_stream_browserify());
22164
22700
 
22165
- // src/node/readable-from.ts
22166
- function createReadableFrom(Readable) {
22167
- return function from(source, options = {}) {
22168
- if (source && typeof source.pipe === "function") return source;
22169
- const iterator = source && typeof source[Symbol.asyncIterator] === "function" ? source[Symbol.asyncIterator]() : source && typeof source[Symbol.iterator] === "function" ? source[Symbol.iterator]() : (function* () {
22170
- yield source;
22171
- })();
22701
+ // src/node/stream-compat.ts
22702
+ var import_stream_browserify = __toESM(require_stream_browserify());
22703
+ function define2(proto, name, get) {
22704
+ if (Object.getOwnPropertyDescriptor(proto, name)) return;
22705
+ Object.defineProperty(proto, name, { configurable: true, enumerable: false, get });
22706
+ }
22707
+ var installed = false;
22708
+ function installWebStreamAdapters(stream) {
22709
+ const { Readable, Writable, Duplex } = stream;
22710
+ const toError = (reason) => reason instanceof Error ? reason : new Error(reason === void 0 ? "aborted" : String(reason));
22711
+ const readableToWeb = (source, options = {}) => {
22712
+ let onData;
22713
+ return new ReadableStream({
22714
+ start(controller) {
22715
+ const objectMode = Boolean(source?._readableState?.objectMode);
22716
+ onData = (chunk) => {
22717
+ const value = objectMode || !(chunk instanceof Uint8Array) && typeof chunk !== "string" ? chunk : typeof chunk === "string" ? new TextEncoder().encode(chunk) : new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
22718
+ controller.enqueue(value);
22719
+ if ((controller.desiredSize ?? 1) <= 0) source.pause();
22720
+ };
22721
+ source.on("data", onData);
22722
+ source.once("end", () => {
22723
+ try {
22724
+ controller.close();
22725
+ } catch {
22726
+ }
22727
+ });
22728
+ source.once("error", (error) => {
22729
+ try {
22730
+ controller.error(error);
22731
+ } catch {
22732
+ }
22733
+ });
22734
+ source.once("close", () => {
22735
+ if (!source.readableEnded && !source._readableState?.endEmitted) {
22736
+ try {
22737
+ controller.error(new Error("The stream was destroyed before it ended"));
22738
+ } catch {
22739
+ }
22740
+ }
22741
+ });
22742
+ },
22743
+ pull() {
22744
+ if (typeof source.isPaused === "function" && source.isPaused()) source.resume();
22745
+ },
22746
+ cancel(reason) {
22747
+ if (onData) source.off("data", onData);
22748
+ source.destroy(reason === void 0 ? void 0 : toError(reason));
22749
+ }
22750
+ }, options.strategy ?? { highWaterMark: 1 });
22751
+ };
22752
+ const readableFromWeb = (web, options = {}) => {
22753
+ const reader = web.getReader();
22172
22754
  let reading = false;
22173
- const stream = new Readable({
22755
+ const readable = new Readable({
22174
22756
  ...options,
22175
- objectMode: options.objectMode ?? false,
22176
22757
  read() {
22177
22758
  if (reading) return;
22178
22759
  reading = true;
22179
22760
  void (async () => {
22180
22761
  try {
22181
22762
  for (; ; ) {
22182
- const next = await iterator.next();
22183
- if (next.done) {
22184
- stream.push(null);
22763
+ const { done, value } = await reader.read();
22764
+ if (done) {
22765
+ readable.push(null);
22185
22766
  return;
22186
22767
  }
22187
- const value = next.value;
22188
- if (!stream.push(value === void 0 ? null : value)) return;
22768
+ const chunk = value instanceof Uint8Array && !options.objectMode ? Buffer2.from(value.buffer, value.byteOffset, value.byteLength) : value;
22769
+ if (!readable.push(chunk)) return;
22189
22770
  }
22190
22771
  } catch (error) {
22191
- stream.destroy(error);
22772
+ readable.destroy(toError(error));
22192
22773
  } finally {
22193
22774
  reading = false;
22194
22775
  }
22195
22776
  })();
22196
22777
  },
22197
22778
  destroy(error, callback) {
22198
- void (async () => {
22199
- try {
22200
- await iterator.return?.();
22201
- } catch {
22202
- }
22203
- callback(error);
22204
- })();
22779
+ reader.cancel(error ?? void 0).catch(() => {
22780
+ }).finally(() => callback(error));
22205
22781
  }
22206
22782
  });
22207
- return stream;
22783
+ return readable;
22208
22784
  };
22209
- }
22210
- function installReadableFrom(streamModule5) {
22211
- streamModule5.Readable.from = createReadableFrom(streamModule5.Readable);
22212
- }
22213
-
22214
- // src/node/env.ts
22215
- function parseEnv(text) {
22216
- if (typeof text !== "string") {
22217
- throw Object.assign(new TypeError('The "content" argument must be of type string'), { code: "ERR_INVALID_ARG_TYPE" });
22218
- }
22219
- const out = {};
22220
- const lines = text.split(/\r?\n/);
22221
- for (let index = 0; index < lines.length; index++) {
22222
- const raw = lines[index];
22223
- const match2 = /^[ \t]*(?:export[ \t]+)?([^=#]+?)[ \t]*=[ \t]*(.*)$/.exec(raw);
22224
- if (!match2) continue;
22225
- const name = match2[1];
22226
- let value = match2[2];
22227
- const quote2 = value[0];
22228
- if (quote2 === '"' || quote2 === "'" || quote2 === "`") {
22229
- const start = index;
22230
- const original = value;
22231
- value = value.slice(1);
22232
- while (true) {
22233
- const end = value.indexOf(quote2);
22234
- if (end >= 0) {
22235
- value = value.slice(0, end);
22236
- break;
22237
- }
22238
- if (++index >= lines.length) {
22239
- index = start;
22240
- value = original;
22241
- break;
22785
+ const writableToWeb = (sink) => new WritableStream({
22786
+ write(chunk) {
22787
+ return new Promise((resolve2, reject) => {
22788
+ const ok2 = sink.write(chunk, (error) => {
22789
+ if (error) reject(error);
22790
+ });
22791
+ if (ok2) resolve2();
22792
+ else {
22793
+ const onDrain = () => {
22794
+ sink.off("error", onError);
22795
+ resolve2();
22796
+ };
22797
+ const onError = (error) => {
22798
+ sink.off("drain", onDrain);
22799
+ reject(error);
22800
+ };
22801
+ sink.once("drain", onDrain);
22802
+ sink.once("error", onError);
22242
22803
  }
22243
- value += `
22244
- ${lines[index]}`;
22245
- }
22246
- if (quote2 === '"') value = value.replace(/\\n/g, "\n");
22804
+ });
22805
+ },
22806
+ close() {
22807
+ return new Promise((resolve2, reject) => {
22808
+ sink.once("error", reject);
22809
+ sink.end(() => resolve2());
22810
+ });
22811
+ },
22812
+ abort(reason) {
22813
+ sink.destroy(toError(reason));
22814
+ }
22815
+ });
22816
+ const writableFromWeb = (web, options = {}) => {
22817
+ const writer = web.getWriter();
22818
+ return new Writable({
22819
+ ...options,
22820
+ write(chunk, _encoding, callback) {
22821
+ writer.write(chunk).then(() => callback(), (error) => callback(toError(error)));
22822
+ },
22823
+ final(callback) {
22824
+ writer.close().then(() => callback(), (error) => callback(toError(error)));
22825
+ },
22826
+ destroy(error, callback) {
22827
+ (error ? writer.abort(error) : writer.close()).catch(() => {
22828
+ }).finally(() => callback(error));
22829
+ }
22830
+ });
22831
+ };
22832
+ const define3 = (target, name, value) => {
22833
+ if (typeof target[name] === "function") return;
22834
+ Object.defineProperty(target, name, { configurable: true, writable: true, value });
22835
+ };
22836
+ define3(Readable, "toWeb", readableToWeb);
22837
+ define3(Readable, "fromWeb", readableFromWeb);
22838
+ define3(Writable, "toWeb", writableToWeb);
22839
+ define3(Writable, "fromWeb", writableFromWeb);
22840
+ define3(Duplex, "toWeb", (duplex) => ({ readable: readableToWeb(duplex), writable: writableToWeb(duplex) }));
22841
+ define3(Duplex, "fromWeb", (pair, options = {}) => {
22842
+ const readable = readableFromWeb(pair.readable, options);
22843
+ const writable = writableFromWeb(pair.writable, options);
22844
+ const duplex = new Duplex({
22845
+ ...options,
22846
+ read() {
22847
+ readable.resume();
22848
+ },
22849
+ write(chunk, encoding, callback) {
22850
+ writable.write(chunk, encoding, callback);
22851
+ },
22852
+ final(callback) {
22853
+ writable.end(callback);
22854
+ }
22855
+ });
22856
+ readable.on("data", (chunk) => {
22857
+ if (!duplex.push(chunk)) readable.pause();
22858
+ });
22859
+ readable.once("end", () => duplex.push(null));
22860
+ readable.once("error", (error) => duplex.destroy(error));
22861
+ writable.once("error", (error) => duplex.destroy(error));
22862
+ return duplex;
22863
+ });
22864
+ }
22865
+ function installStreamCompat() {
22866
+ if (installed) return;
22867
+ installed = true;
22868
+ const stream = import_stream_browserify.default;
22869
+ const writable = (self2) => self2._writableState;
22870
+ const readable = (self2) => self2._readableState;
22871
+ for (const proto of [stream.Writable.prototype, stream.Duplex.prototype]) {
22872
+ define2(proto, "writableEnded", function() {
22873
+ return Boolean(writable(this)?.ending);
22874
+ });
22875
+ define2(proto, "writableFinished", function() {
22876
+ return Boolean(writable(this)?.finished);
22877
+ });
22878
+ define2(proto, "writableNeedDrain", function() {
22879
+ const state = writable(this);
22880
+ return Boolean(state && !state.destroyed && !state.ending && state.needDrain);
22881
+ });
22882
+ define2(proto, "writableCorked", function() {
22883
+ return Number(writable(this)?.corked ?? 0);
22884
+ });
22885
+ define2(proto, "writableObjectMode", function() {
22886
+ return Boolean(writable(this)?.objectMode);
22887
+ });
22888
+ define2(proto, "writableAborted", function() {
22889
+ const state = writable(this);
22890
+ return Boolean(state && state.destroyed && !state.finished);
22891
+ });
22892
+ }
22893
+ for (const proto of [stream.Readable.prototype, stream.Duplex.prototype]) {
22894
+ define2(proto, "readableEnded", function() {
22895
+ return Boolean(readable(this)?.endEmitted);
22896
+ });
22897
+ define2(proto, "readableAborted", function() {
22898
+ const state = readable(this);
22899
+ return Boolean(state && state.destroyed && !state.endEmitted);
22900
+ });
22901
+ define2(proto, "readableDidRead", function() {
22902
+ return Boolean(readable(this)?.dataEmitted ?? readable(this)?.readingMore);
22903
+ });
22904
+ }
22905
+ const writableProto = stream.Writable.prototype;
22906
+ const originalEnd = writableProto.end;
22907
+ const originalEmit = writableProto.emit;
22908
+ const inEnd = /* @__PURE__ */ new WeakSet();
22909
+ writableProto.end = function(...args) {
22910
+ inEnd.add(this);
22911
+ try {
22912
+ return originalEnd.apply(this, args);
22913
+ } finally {
22914
+ inEnd.delete(this);
22915
+ }
22916
+ };
22917
+ writableProto.emit = function(event, ...args) {
22918
+ if (event === "finish" && inEnd.has(this)) {
22919
+ const self2 = this;
22920
+ const later = globalThis.process?.nextTick;
22921
+ const deliver = () => {
22922
+ originalEmit.call(self2, event, ...args);
22923
+ };
22924
+ if (typeof later === "function") later(deliver);
22925
+ else queueMicrotask(deliver);
22926
+ return true;
22927
+ }
22928
+ return originalEmit.call(this, event, ...args);
22929
+ };
22930
+ installWebStreamAdapters(stream);
22931
+ for (const proto of [stream.Writable.prototype, stream.Readable.prototype, stream.Duplex.prototype]) {
22932
+ define2(proto, "closed", function() {
22933
+ return Boolean(writable(this)?.destroyed || readable(this)?.destroyed);
22934
+ });
22935
+ define2(proto, "errored", function() {
22936
+ return this.__sbxErrored ?? null;
22937
+ });
22938
+ }
22939
+ }
22940
+
22941
+ // src/node/readable-from.ts
22942
+ function createReadableFrom(Readable) {
22943
+ return function from(source, options = {}) {
22944
+ if (source && typeof source.pipe === "function") return source;
22945
+ const iterator = source && typeof source[Symbol.asyncIterator] === "function" ? source[Symbol.asyncIterator]() : source && typeof source[Symbol.iterator] === "function" ? source[Symbol.iterator]() : (function* () {
22946
+ yield source;
22947
+ })();
22948
+ let reading = false;
22949
+ const stream = new Readable({
22950
+ ...options,
22951
+ objectMode: options.objectMode ?? false,
22952
+ read() {
22953
+ if (reading) return;
22954
+ reading = true;
22955
+ void (async () => {
22956
+ try {
22957
+ for (; ; ) {
22958
+ const next = await iterator.next();
22959
+ if (next.done) {
22960
+ stream.push(null);
22961
+ return;
22962
+ }
22963
+ const value = next.value;
22964
+ if (!stream.push(value === void 0 ? null : value)) return;
22965
+ }
22966
+ } catch (error) {
22967
+ stream.destroy(error);
22968
+ } finally {
22969
+ reading = false;
22970
+ }
22971
+ })();
22972
+ },
22973
+ destroy(error, callback) {
22974
+ void (async () => {
22975
+ try {
22976
+ await iterator.return?.();
22977
+ } catch {
22978
+ }
22979
+ callback(error);
22980
+ })();
22981
+ }
22982
+ });
22983
+ return stream;
22984
+ };
22985
+ }
22986
+ function installReadableFrom(streamModule6) {
22987
+ streamModule6.Readable.from = createReadableFrom(streamModule6.Readable);
22988
+ }
22989
+
22990
+ // src/node/env.ts
22991
+ function parseEnv(text) {
22992
+ if (typeof text !== "string") {
22993
+ throw Object.assign(new TypeError('The "content" argument must be of type string'), { code: "ERR_INVALID_ARG_TYPE" });
22994
+ }
22995
+ const out = {};
22996
+ const lines = text.split(/\r?\n/);
22997
+ for (let index = 0; index < lines.length; index++) {
22998
+ const raw = lines[index];
22999
+ const match2 = /^[ \t]*(?:export[ \t]+)?([^=#]+?)[ \t]*=[ \t]*(.*)$/.exec(raw);
23000
+ if (!match2) continue;
23001
+ const name = match2[1];
23002
+ let value = match2[2];
23003
+ const quote2 = value[0];
23004
+ if (quote2 === '"' || quote2 === "'" || quote2 === "`") {
23005
+ const start = index;
23006
+ const original = value;
23007
+ value = value.slice(1);
23008
+ while (true) {
23009
+ const end = value.indexOf(quote2);
23010
+ if (end >= 0) {
23011
+ value = value.slice(0, end);
23012
+ break;
23013
+ }
23014
+ if (++index >= lines.length) {
23015
+ index = start;
23016
+ value = original;
23017
+ break;
23018
+ }
23019
+ value += `
23020
+ ${lines[index]}`;
23021
+ }
23022
+ if (quote2 === '"') value = value.replace(/\\n/g, "\n");
22247
23023
  } else {
22248
23024
  const comment = value.indexOf("#");
22249
23025
  if (comment >= 0) value = value.slice(0, comment);
@@ -22254,6 +23030,132 @@ ${lines[index]}`;
22254
23030
  return out;
22255
23031
  }
22256
23032
 
23033
+ // src/node/parse-args.ts
23034
+ function argError(code, message) {
23035
+ return Object.assign(new TypeError(message), { code });
23036
+ }
23037
+ function parseArgs(config = {}) {
23038
+ const args = config.args ?? globalThis.process?.argv?.slice(2) ?? [];
23039
+ const options = config.options ?? {};
23040
+ const strict = config.strict ?? true;
23041
+ const allowPositionals = config.allowPositionals ?? !strict;
23042
+ const allowNegative = config.allowNegative ?? false;
23043
+ const byShort = /* @__PURE__ */ new Map();
23044
+ for (const [name, option] of Object.entries(options)) {
23045
+ if (option.type !== "string" && option.type !== "boolean") {
23046
+ throw argError("ERR_INVALID_ARG_VALUE", `The property 'options.${name}.type' must be one of: 'string', 'boolean'`);
23047
+ }
23048
+ if (option.short !== void 0) {
23049
+ if (option.short.length !== 1) {
23050
+ throw argError("ERR_INVALID_ARG_VALUE", `The property 'options.${name}.short' must be a single character`);
23051
+ }
23052
+ byShort.set(option.short, name);
23053
+ }
23054
+ }
23055
+ const tokens = [];
23056
+ const takesValue = (name) => options[name]?.type === "string";
23057
+ for (let index = 0; index < args.length; index++) {
23058
+ const arg = args[index];
23059
+ if (arg === "--") {
23060
+ tokens.push({ kind: "option-terminator", index });
23061
+ for (let rest = index + 1; rest < args.length; rest++) tokens.push({ kind: "positional", index: rest, value: args[rest] });
23062
+ break;
23063
+ }
23064
+ if (arg.startsWith("--") && arg.length > 2) {
23065
+ const equals = arg.indexOf("=");
23066
+ if (equals !== -1) {
23067
+ tokens.push({ kind: "option", name: arg.slice(2, equals), rawName: arg.slice(0, equals), index, value: arg.slice(equals + 1), inlineValue: true });
23068
+ continue;
23069
+ }
23070
+ const name = arg.slice(2);
23071
+ if (takesValue(name) && index + 1 < args.length) {
23072
+ tokens.push({ kind: "option", name, rawName: arg, index, value: args[index + 1], inlineValue: false });
23073
+ index++;
23074
+ } else {
23075
+ tokens.push({ kind: "option", name, rawName: arg, index, value: void 0, inlineValue: void 0 });
23076
+ }
23077
+ continue;
23078
+ }
23079
+ if (arg.startsWith("-") && arg.length > 1) {
23080
+ for (let at2 = 1; at2 < arg.length; at2++) {
23081
+ const short = arg[at2];
23082
+ const name = byShort.get(short) ?? short;
23083
+ if (takesValue(name)) {
23084
+ if (at2 + 1 < arg.length) {
23085
+ tokens.push({ kind: "option", name, rawName: `-${short}`, index, value: arg.slice(at2 + 1), inlineValue: true });
23086
+ } else if (index + 1 < args.length) {
23087
+ tokens.push({ kind: "option", name, rawName: `-${short}`, index, value: args[index + 1], inlineValue: false });
23088
+ index++;
23089
+ } else {
23090
+ tokens.push({ kind: "option", name, rawName: `-${short}`, index, value: void 0, inlineValue: void 0 });
23091
+ }
23092
+ break;
23093
+ }
23094
+ tokens.push({ kind: "option", name, rawName: `-${short}`, index, value: void 0, inlineValue: void 0 });
23095
+ }
23096
+ continue;
23097
+ }
23098
+ tokens.push({ kind: "positional", index, value: arg });
23099
+ }
23100
+ const values = /* @__PURE__ */ Object.create(null);
23101
+ const positionals = [];
23102
+ const store = (name, value) => {
23103
+ if (options[name]?.multiple) {
23104
+ const list = values[name] ?? [];
23105
+ list.push(value);
23106
+ values[name] = list;
23107
+ } else {
23108
+ values[name] = value;
23109
+ }
23110
+ };
23111
+ for (const token of tokens) {
23112
+ if (token.kind === "option-terminator") continue;
23113
+ if (token.kind === "positional") {
23114
+ if (!allowPositionals) {
23115
+ throw argError("ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL", `Unexpected argument '${token.value}'. This command does not take positional arguments`);
23116
+ }
23117
+ positionals.push(token.value);
23118
+ continue;
23119
+ }
23120
+ let name = token.name;
23121
+ let negated = false;
23122
+ if (allowNegative && name.startsWith("no-") && token.rawName.startsWith("--") && options[name.slice(3)]?.type === "boolean") {
23123
+ name = name.slice(3);
23124
+ negated = true;
23125
+ }
23126
+ const option = options[name];
23127
+ if (!option) {
23128
+ if (strict) {
23129
+ throw argError(
23130
+ "ERR_PARSE_ARGS_UNKNOWN_OPTION",
23131
+ `Unknown option '${token.rawName}'${allowPositionals ? `. To specify a positional argument starting with a '-', place it at the end of the command after '--', as in '-- ${JSON.stringify(token.rawName)}'` : ""}`
23132
+ );
23133
+ }
23134
+ store(name, token.value ?? true);
23135
+ continue;
23136
+ }
23137
+ if (option.type === "string") {
23138
+ if (token.value === void 0) {
23139
+ if (strict) throw argError("ERR_PARSE_ARGS_INVALID_OPTION_VALUE", `Option '${token.rawName} <value>' argument missing`);
23140
+ store(name, true);
23141
+ continue;
23142
+ }
23143
+ store(name, token.value);
23144
+ } else {
23145
+ if (token.inlineValue && strict) {
23146
+ throw argError("ERR_PARSE_ARGS_INVALID_OPTION_VALUE", `Option '${token.rawName}' does not take an argument`);
23147
+ }
23148
+ store(name, !negated);
23149
+ }
23150
+ }
23151
+ for (const [name, option] of Object.entries(options)) {
23152
+ if (option.default !== void 0 && values[name] === void 0) {
23153
+ values[name] = Array.isArray(option.default) ? option.default.slice() : option.default;
23154
+ }
23155
+ }
23156
+ return config.tokens ? { values, positionals, tokens } : { values, positionals };
23157
+ }
23158
+
22257
23159
  // src/node/util-module.ts
22258
23160
  var customInspect = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
22259
23161
  var promisifyCustom = /* @__PURE__ */ Symbol.for("nodejs.util.promisify.custom");
@@ -22282,8 +23184,9 @@ function render(value, depth, seen, options) {
22282
23184
  if (value === null) return "null";
22283
23185
  const object = value;
22284
23186
  const custom = object[customInspect];
22285
- if (typeof custom === "function") {
22286
- return String(custom.call(object, depth, options));
23187
+ if (options.customInspect !== false && typeof custom === "function") {
23188
+ const result = custom.call(object, depth, options, inspect);
23189
+ if (result !== object) return typeof result === "string" ? result : render(result, depth, seen, options);
22287
23190
  }
22288
23191
  if (seen.has(object)) return "[Circular *1]";
22289
23192
  if (depth < 0) return Array.isArray(object) ? "[Array]" : "[Object]";
@@ -22618,6 +23521,7 @@ var legacy = {
22618
23521
  inspect.custom = customInspect;
22619
23522
  var utilModule = {
22620
23523
  parseEnv,
23524
+ parseArgs,
22621
23525
  format,
22622
23526
  formatWithOptions,
22623
23527
  inspect,
@@ -22721,12 +23625,12 @@ function matches(error, expected) {
22721
23625
  return String(error) === String(expected);
22722
23626
  }
22723
23627
  function throws(block, expected, message) {
22724
- const [error, threw] = capture(block);
23628
+ const [error, threw] = capture2(block);
22725
23629
  if (!threw) fail(void 0, expected, message ?? "Missing expected exception.", "throws");
22726
23630
  if (!matches(error, expected)) throw error;
22727
23631
  }
22728
23632
  function doesNotThrow(block, expected, message) {
22729
- const [error, threw] = capture(block);
23633
+ const [error, threw] = capture2(block);
22730
23634
  if (!threw) return;
22731
23635
  if (matches(error, expected)) {
22732
23636
  fail(error, expected, message ?? "Got unwanted exception.", "doesNotThrow");
@@ -22746,7 +23650,7 @@ async function doesNotReject(block, expected, message) {
22746
23650
  }
22747
23651
  throw error;
22748
23652
  }
22749
- function capture(block) {
23653
+ function capture2(block) {
22750
23654
  try {
22751
23655
  block();
22752
23656
  return [void 0, false];
@@ -22807,7 +23711,7 @@ var assert_module_default = assertModule;
22807
23711
  var import_browser = __toESM(require_browser2());
22808
23712
 
22809
23713
  // src/node/zlib-module.ts
22810
- var import_stream_browserify = __toESM(require_stream_browserify());
23714
+ var import_stream_browserify2 = __toESM(require_stream_browserify());
22811
23715
 
22812
23716
  // node_modules/pako/dist/pako.esm.mjs
22813
23717
  var Z_FIXED$1 = 4;
@@ -25023,10 +25927,12 @@ function gzip$1(input, options) {
25023
25927
  options.gzip = true;
25024
25928
  return deflate$1(input, options);
25025
25929
  }
25930
+ var Deflate_1$1 = Deflate$1;
25026
25931
  var deflate_2 = deflate$1;
25027
25932
  var deflateRaw_1$1 = deflateRaw$1;
25028
25933
  var gzip_1$1 = gzip$1;
25029
25934
  var deflate_1$1 = {
25935
+ Deflate: Deflate_1$1,
25030
25936
  deflate: deflate_2,
25031
25937
  deflateRaw: deflateRaw_1$1,
25032
25938
  gzip: gzip_1$1};
@@ -26989,29 +27895,37 @@ function inflateRaw$1(input, options) {
26989
27895
  options.raw = true;
26990
27896
  return inflate$1(input, options);
26991
27897
  }
27898
+ var Inflate_1$1 = Inflate$1;
26992
27899
  var inflate_2 = inflate$1;
26993
27900
  var inflateRaw_1$1 = inflateRaw$1;
26994
27901
  var ungzip$1 = inflate$1;
26995
27902
  var inflate_1$1 = {
27903
+ Inflate: Inflate_1$1,
26996
27904
  inflate: inflate_2,
26997
27905
  inflateRaw: inflateRaw_1$1,
26998
27906
  ungzip: ungzip$1};
26999
- var { deflate, deflateRaw, gzip } = deflate_1$1;
27000
- var { inflate, inflateRaw, ungzip } = inflate_1$1;
27907
+ var { Deflate, deflate, deflateRaw, gzip } = deflate_1$1;
27908
+ var { Inflate, inflate, inflateRaw, ungzip } = inflate_1$1;
27909
+ var Deflate_1 = Deflate;
27001
27910
  var deflate_1 = deflate;
27002
27911
  var deflateRaw_1 = deflateRaw;
27003
27912
  var gzip_1 = gzip;
27913
+ var Inflate_1 = Inflate;
27004
27914
  var inflate_1 = inflate;
27005
27915
  var inflateRaw_1 = inflateRaw;
27006
27916
  var ungzip_1 = ungzip;
27007
27917
 
27008
27918
  // src/node/zlib-module.ts
27919
+ var Z_NO_FLUSH2 = 0;
27920
+ var Z_SYNC_FLUSH2 = 2;
27921
+ var Z_FULL_FLUSH2 = 3;
27922
+ var Z_FINISH2 = 4;
27009
27923
  var bytes = (data2) => {
27010
27924
  if (typeof data2 === "string") return new Uint8Array(Buffer2.from(data2, "utf8"));
27011
27925
  if (data2 instanceof ArrayBuffer) return new Uint8Array(data2);
27012
27926
  return data2;
27013
27927
  };
27014
- function codec(name, run2) {
27928
+ function codec(run2) {
27015
27929
  const sync = (data2, options) => Buffer2.from(run2(bytes(data2), options));
27016
27930
  const async_ = (data2, options, callback) => {
27017
27931
  const done = typeof options === "function" ? options : callback;
@@ -27024,37 +27938,159 @@ function codec(name, run2) {
27024
27938
  }
27025
27939
  });
27026
27940
  };
27027
- const Stream = class extends import_stream_browserify.default.Transform {
27028
- chunks = [];
27029
- options;
27030
- constructor(options) {
27031
- super();
27032
- this.options = options;
27941
+ return { sync, async: async_ };
27942
+ }
27943
+ function createEngine(mode, options) {
27944
+ const windowBits = typeof options.windowBits === "number" ? options.windowBits : 15;
27945
+ const level = typeof options.level === "number" ? options.level : -1;
27946
+ const memLevel = typeof options.memLevel === "number" ? options.memLevel : 8;
27947
+ const strategy = typeof options.strategy === "number" ? options.strategy : 0;
27948
+ const deflateOptions = { level, memLevel, strategy, windowBits };
27949
+ switch (mode) {
27950
+ case "Deflate":
27951
+ return new Deflate_1(deflateOptions);
27952
+ case "Gzip":
27953
+ return new Deflate_1({ ...deflateOptions, gzip: true });
27954
+ case "DeflateRaw":
27955
+ return new Deflate_1({ ...deflateOptions, raw: true });
27956
+ case "Inflate":
27957
+ return new Inflate_1({ windowBits });
27958
+ case "InflateRaw":
27959
+ return new Inflate_1({ raw: true, windowBits });
27960
+ /* zlib's `windowBits + 16` means gzip only; `+ 32` detects gzip or zlib
27961
+ * from the header, which is exactly `Unzip`. */
27962
+ case "Gunzip":
27963
+ return new Inflate_1({ windowBits: windowBits + 16 });
27964
+ case "Unzip":
27965
+ return new Inflate_1({ windowBits: windowBits + 32 });
27966
+ }
27967
+ }
27968
+ function zlibError(engine) {
27969
+ const codes = { [-2]: "Z_STREAM_ERROR", [-3]: "Z_DATA_ERROR", [-4]: "Z_MEM_ERROR", [-5]: "Z_BUF_ERROR", 2: "Z_NEED_DICT" };
27970
+ return Object.assign(new Error(engine.msg || "zlib error"), { errno: engine.err, code: codes[engine.err] ?? "Z_DATA_ERROR" });
27971
+ }
27972
+ function zlibClass(mode) {
27973
+ const ZlibStream = class extends import_stream_browserify2.default.Transform {
27974
+ bytesWritten = 0;
27975
+ _handle;
27976
+ _engine;
27977
+ _settings;
27978
+ _output = [];
27979
+ _finished = false;
27980
+ constructor(options = {}) {
27981
+ super(options);
27982
+ this._settings = options;
27983
+ this._engine = this._attach(createEngine(mode, options));
27984
+ this._handle = { close: () => {
27985
+ this._handle = null;
27986
+ } };
27987
+ }
27988
+ _attach(engine) {
27989
+ engine.onData = (chunk) => this._output.push(chunk);
27990
+ engine.onEnd = (status) => {
27991
+ const state = engine;
27992
+ if (status !== 0) {
27993
+ state.err = status;
27994
+ state.msg = state.strm?.msg ?? state.msg;
27995
+ }
27996
+ };
27997
+ return engine;
27998
+ }
27999
+ /** Code one chunk now and hand back what it produced. */
28000
+ _processChunk(chunk, flushFlag = Z_NO_FLUSH2, callback) {
28001
+ const input = typeof chunk === "string" ? Buffer2.from(chunk) : chunk;
28002
+ try {
28003
+ const out = this._code(input, flushFlag);
28004
+ if (callback) queueMicrotask(() => callback(null, out));
28005
+ return out;
28006
+ } catch (error) {
28007
+ if (callback) {
28008
+ queueMicrotask(() => callback(error));
28009
+ return Buffer2.alloc(0);
28010
+ }
28011
+ throw error;
28012
+ }
28013
+ }
28014
+ _code(input, flushFlag) {
28015
+ if (this._finished) {
28016
+ return Buffer2.alloc(0);
28017
+ }
28018
+ this.bytesWritten += input.length;
28019
+ const engine = this._engine;
28020
+ if (input.length > 0 || flushFlag !== Z_NO_FLUSH2) {
28021
+ const mapped = flushFlag === Z_FINISH2 ? Z_FINISH2 : flushFlag === Z_FULL_FLUSH2 ? Z_FULL_FLUSH2 : flushFlag === Z_SYNC_FLUSH2 ? Z_SYNC_FLUSH2 : Z_NO_FLUSH2;
28022
+ engine.push(input, mapped);
28023
+ if (engine.err) throw zlibError(engine);
28024
+ }
28025
+ if (engine.ended || flushFlag === Z_FINISH2) this._finished = engine.ended === true || mode.startsWith("Deflate") || mode === "Gzip";
28026
+ const produced = this._output;
28027
+ this._output = [];
28028
+ return produced.length === 1 ? Buffer2.from(produced[0]) : Buffer2.concat(produced.map((part) => Buffer2.from(part)));
27033
28029
  }
27034
28030
  _transform(chunk, _encoding, next) {
27035
- this.chunks.push(Buffer2.from(chunk));
27036
- next();
28031
+ try {
28032
+ const out = this._code(chunk, typeof this._settings.flush === "number" ? this._settings.flush : Z_NO_FLUSH2);
28033
+ if (out.length) this.push(out);
28034
+ next();
28035
+ } catch (error) {
28036
+ next(error);
28037
+ }
27037
28038
  }
27038
28039
  _flush(next) {
27039
28040
  try {
27040
- this.push(sync(Buffer2.concat(this.chunks), this.options));
28041
+ const finish = typeof this._settings.finishFlush === "number" ? this._settings.finishFlush : Z_FINISH2;
28042
+ const out = this._code(new Uint8Array(0), finish);
28043
+ if (out.length) this.push(out);
27041
28044
  next();
27042
28045
  } catch (error) {
27043
28046
  next(error);
27044
28047
  }
27045
28048
  }
28049
+ /** `flush([kind], callback)`: emit what is pending without ending the stream. */
28050
+ flush(kind, callback) {
28051
+ const done = typeof kind === "function" ? kind : callback;
28052
+ const flag = typeof kind === "number" ? kind : Z_FULL_FLUSH2;
28053
+ try {
28054
+ const out = this._code(new Uint8Array(0), flag);
28055
+ if (out.length) this.push(out);
28056
+ } catch (error) {
28057
+ this.destroy(error);
28058
+ }
28059
+ if (done) queueMicrotask(done);
28060
+ }
28061
+ reset() {
28062
+ this._engine = this._attach(createEngine(mode, this._settings));
28063
+ this._output = [];
28064
+ this._finished = false;
28065
+ }
28066
+ params(level, strategy, callback) {
28067
+ this._settings.level = level;
28068
+ this._settings.strategy = strategy;
28069
+ if (callback) queueMicrotask(callback);
28070
+ }
28071
+ close(callback) {
28072
+ this._handle?.close();
28073
+ if (callback) this.once("close", callback);
28074
+ if (!this.destroyed) this.destroy();
28075
+ }
27046
28076
  };
27047
- Object.defineProperty(Stream, "name", { value: name });
27048
- return { sync, async: async_, Stream };
27049
- }
27050
- var gzipCodec = codec("Gzip", (input, options) => gzip_1(input, options));
27051
- var gunzipCodec = codec("Gunzip", (input) => ungzip_1(input));
27052
- var deflateCodec = codec("Deflate", (input, options) => deflate_1(input, options));
27053
- var inflateCodec = codec("Inflate", (input) => inflate_1(input));
27054
- var deflateRawCodec = codec("DeflateRaw", (input, options) => deflateRaw_1(input, options));
27055
- var inflateRawCodec = codec("InflateRaw", (input) => inflateRaw_1(input));
28077
+ Object.defineProperty(ZlibStream, "name", { value: mode });
28078
+ return ZlibStream;
28079
+ }
28080
+ var Gzip = zlibClass("Gzip");
28081
+ var Gunzip = zlibClass("Gunzip");
28082
+ var Deflate2 = zlibClass("Deflate");
28083
+ var Inflate2 = zlibClass("Inflate");
28084
+ var DeflateRaw = zlibClass("DeflateRaw");
28085
+ var InflateRaw = zlibClass("InflateRaw");
28086
+ var Unzip = zlibClass("Unzip");
28087
+ var gzipCodec = codec((input, options) => gzip_1(input, options));
28088
+ var gunzipCodec = codec((input) => ungzip_1(input));
28089
+ var deflateCodec = codec((input, options) => deflate_1(input, options));
28090
+ var inflateCodec = codec((input) => inflate_1(input));
28091
+ var deflateRawCodec = codec((input, options) => deflateRaw_1(input, options));
28092
+ var inflateRawCodec = codec((input) => inflateRaw_1(input));
27056
28093
  var unzipCodec = codec(
27057
- "Unzip",
27058
28094
  (input) => input[0] === 31 && input[1] === 139 ? ungzip_1(input) : inflate_1(input)
27059
28095
  );
27060
28096
  function brotliUnavailable(name) {
@@ -27065,27 +28101,34 @@ function brotliUnavailable(name) {
27065
28101
  throw error;
27066
28102
  }
27067
28103
  var zlibModule = {
28104
+ Gzip,
28105
+ Gunzip,
28106
+ Deflate: Deflate2,
28107
+ Inflate: Inflate2,
28108
+ DeflateRaw,
28109
+ InflateRaw,
28110
+ Unzip,
27068
28111
  gzipSync: gzipCodec.sync,
27069
28112
  gzip: gzipCodec.async,
27070
- createGzip: (o2) => new gzipCodec.Stream(o2),
28113
+ createGzip: (o2) => new Gzip(o2),
27071
28114
  gunzipSync: gunzipCodec.sync,
27072
28115
  gunzip: gunzipCodec.async,
27073
- createGunzip: (o2) => new gunzipCodec.Stream(o2),
28116
+ createGunzip: (o2) => new Gunzip(o2),
27074
28117
  deflateSync: deflateCodec.sync,
27075
28118
  deflate: deflateCodec.async,
27076
- createDeflate: (o2) => new deflateCodec.Stream(o2),
28119
+ createDeflate: (o2) => new Deflate2(o2),
27077
28120
  inflateSync: inflateCodec.sync,
27078
28121
  inflate: inflateCodec.async,
27079
- createInflate: (o2) => new inflateCodec.Stream(o2),
28122
+ createInflate: (o2) => new Inflate2(o2),
27080
28123
  deflateRawSync: deflateRawCodec.sync,
27081
28124
  deflateRaw: deflateRawCodec.async,
27082
- createDeflateRaw: (o2) => new deflateRawCodec.Stream(o2),
28125
+ createDeflateRaw: (o2) => new DeflateRaw(o2),
27083
28126
  inflateRawSync: inflateRawCodec.sync,
27084
28127
  inflateRaw: inflateRawCodec.async,
27085
- createInflateRaw: (o2) => new inflateRawCodec.Stream(o2),
28128
+ createInflateRaw: (o2) => new InflateRaw(o2),
27086
28129
  unzipSync: unzipCodec.sync,
27087
28130
  unzip: unzipCodec.async,
27088
- createUnzip: (o2) => new unzipCodec.Stream(o2),
28131
+ createUnzip: (o2) => new Unzip(o2),
27089
28132
  brotliCompressSync: () => brotliUnavailable("brotliCompressSync"),
27090
28133
  brotliDecompressSync: () => brotliUnavailable("brotliDecompressSync"),
27091
28134
  brotliCompress: () => brotliUnavailable("brotliCompress"),
@@ -27186,7 +28229,7 @@ var url_module_default = urlModule;
27186
28229
 
27187
28230
  // src/node/virtual-http.ts
27188
28231
  var import_events = __toESM(require_events());
27189
- var import_stream_browserify2 = __toESM(require_stream_browserify());
28232
+ var import_stream_browserify3 = __toESM(require_stream_browserify());
27190
28233
 
27191
28234
  // src/net/policy.ts
27192
28235
  function isLoopbackHostname(hostname) {
@@ -27260,7 +28303,8 @@ function policedWebSocket(Native, policy) {
27260
28303
  }
27261
28304
 
27262
28305
  // src/node/virtual-http.ts
27263
- var VirtualIncomingMessage = class extends import_stream_browserify2.default.Readable {
28306
+ installStreamCompat();
28307
+ var VirtualIncomingMessage = class extends import_stream_browserify3.default.Readable {
27264
28308
  method;
27265
28309
  url;
27266
28310
  headers;
@@ -27300,7 +28344,7 @@ var VirtualIncomingMessage = class extends import_stream_browserify2.default.Rea
27300
28344
  return this;
27301
28345
  }
27302
28346
  };
27303
- var VirtualServerResponse = class extends import_stream_browserify2.default.Writable {
28347
+ var VirtualServerResponse = class extends import_stream_browserify3.default.Writable {
27304
28348
  statusCode = 200;
27305
28349
  statusMessage = "OK";
27306
28350
  headersSent = false;
@@ -27326,16 +28370,38 @@ var VirtualServerResponse = class extends import_stream_browserify2.default.Writ
27326
28370
  }
27327
28371
  _final(callback) {
27328
28372
  this.headersSent = true;
28373
+ this.settle();
28374
+ this.once("finish", () => queueMicrotask(() => {
28375
+ if (!this.destroyed) this.destroy();
28376
+ }));
28377
+ callback();
28378
+ }
28379
+ /*
28380
+ * A destroyed response still answers.
28381
+ *
28382
+ * Node sends whatever was written and closes the socket; the caller sees a
28383
+ * response, however short. Here the caller is waiting on `completed`, which
28384
+ * only `_final` used to settle — so a response torn down before `end()`
28385
+ * (an aborted stream, `res.destroy(err)` from a web-stream pipe) left the
28386
+ * request unanswered forever while the server had already moved on.
28387
+ */
28388
+ _destroy(error, callback) {
28389
+ this.settle();
28390
+ callback(error);
28391
+ }
28392
+ settled = false;
28393
+ settle() {
28394
+ if (this.settled) return;
28395
+ this.settled = true;
27329
28396
  if (this.sendDate && !this.hasHeader("date")) this.setHeader("Date", (/* @__PURE__ */ new Date()).toUTCString());
27330
28397
  const headers = {};
27331
- for (const { name, value } of this.headers.values()) headers[name] = Array.isArray(value) ? value.join(", ") : value;
28398
+ for (const [key, { value }] of this.headers) headers[key] = Array.isArray(value) ? value.join(", ") : value;
27332
28399
  this.resolve({
27333
28400
  statusCode: this.statusCode,
27334
28401
  statusMessage: this.statusMessage || STATUS_CODES[this.statusCode] || "",
27335
28402
  headers,
27336
28403
  body: new Uint8Array(Buffer2.concat(this.chunks))
27337
28404
  });
27338
- callback();
27339
28405
  }
27340
28406
  setHeader(name, value) {
27341
28407
  validateHeaderName(name);
@@ -27344,9 +28410,9 @@ var VirtualServerResponse = class extends import_stream_browserify2.default.Writ
27344
28410
  return this;
27345
28411
  }
27346
28412
  appendHeader(name, value) {
27347
- const current2 = this.getHeader(name);
28413
+ const current3 = this.getHeader(name);
27348
28414
  const next = Array.isArray(value) ? [...value] : [String(value)];
27349
- return this.setHeader(name, current2 === void 0 ? next : [...Array.isArray(current2) ? current2 : [String(current2)], ...next]);
28415
+ return this.setHeader(name, current3 === void 0 ? next : [...Array.isArray(current3) ? current3 : [String(current3)], ...next]);
27350
28416
  }
27351
28417
  getHeader(name) {
27352
28418
  return this.headers.get(name.toLowerCase())?.value;
@@ -27374,6 +28440,25 @@ var VirtualServerResponse = class extends import_stream_browserify2.default.Writ
27374
28440
  flushHeaders() {
27375
28441
  this.headersSent = true;
27376
28442
  }
28443
+ /*
28444
+ * Node's `OutgoingMessage` internals that middleware reaches past the public
28445
+ * API for. `compression` — which Next's dev server wraps every response in —
28446
+ * calls `_implicitHeader()` from its own `write`/`end` to commit the status
28447
+ * line before the first byte, the way Node's `write` does internally.
28448
+ */
28449
+ _implicitHeader() {
28450
+ if (!this.headersSent) this.writeHead(this.statusCode);
28451
+ }
28452
+ get _header() {
28453
+ return this.headersSent ? `HTTP/1.1 ${this.statusCode} ${this.statusMessage}\r
28454
+ ` : null;
28455
+ }
28456
+ get finished() {
28457
+ return this.writableEnded;
28458
+ }
28459
+ chunkedEncoding = false;
28460
+ useChunkedEncodingByDefault = true;
28461
+ strictContentLength = false;
27377
28462
  writeContinue() {
27378
28463
  }
27379
28464
  writeProcessing() {
@@ -27385,7 +28470,7 @@ var VirtualServerResponse = class extends import_stream_browserify2.default.Writ
27385
28470
  return this;
27386
28471
  }
27387
28472
  };
27388
- var VirtualSocket = class extends import_stream_browserify2.default.Duplex {
28473
+ var VirtualSocket = class extends import_stream_browserify3.default.Duplex {
27389
28474
  remoteAddress = "127.0.0.1";
27390
28475
  remotePort = 0;
27391
28476
  localAddress = "127.0.0.1";
@@ -27590,7 +28675,7 @@ var VirtualHttpRouter = class {
27590
28675
  };
27591
28676
  }
27592
28677
  };
27593
- var VirtualClientResponse = class extends import_stream_browserify2.default.Readable {
28678
+ var VirtualClientResponse = class extends import_stream_browserify3.default.Readable {
27594
28679
  constructor(statusCode, statusMessage, headers, body) {
27595
28680
  super();
27596
28681
  this.statusCode = statusCode;
@@ -27657,7 +28742,7 @@ function resolveTarget(input, overrides, defaultProtocol) {
27657
28742
  function isLoopback(hostname) {
27658
28743
  return isLoopbackHostname(hostname);
27659
28744
  }
27660
- var VirtualClientRequest = class extends import_stream_browserify2.default.Writable {
28745
+ var VirtualClientRequest = class extends import_stream_browserify3.default.Writable {
27661
28746
  constructor(target, router, fetchImpl, trackRequest, loopback = void 0) {
27662
28747
  super();
27663
28748
  this.target = target;
@@ -27887,6 +28972,7 @@ function createVirtualFetch(router, options = {}) {
27887
28972
  const request = new Request(input, init);
27888
28973
  const url = new URL(request.url);
27889
28974
  const release = options.trackRequest?.();
28975
+ let handedOff = false;
27890
28976
  try {
27891
28977
  if (!isLoopback(url.hostname)) {
27892
28978
  if (!options.fetch) {
@@ -27894,7 +28980,10 @@ function createVirtualFetch(router, options = {}) {
27894
28980
  cause: Object.assign(new Error(`getaddrinfo ENOTFOUND ${url.hostname}`), { code: "ENOTFOUND" })
27895
28981
  });
27896
28982
  }
27897
- return await options.fetch(request);
28983
+ const response = await options.fetch(request);
28984
+ if (!release || !response.body) return response;
28985
+ handedOff = true;
28986
+ return releaseWhenConsumed(response, release);
27898
28987
  }
27899
28988
  const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
27900
28989
  const headers = {};
@@ -27934,9 +29023,43 @@ function createVirtualFetch(router, options = {}) {
27934
29023
  headers: responseHeaders
27935
29024
  });
27936
29025
  } finally {
27937
- release?.();
29026
+ if (!handedOff) release?.();
29027
+ }
29028
+ });
29029
+ }
29030
+ function releaseWhenConsumed(response, release) {
29031
+ let released = false;
29032
+ const once = () => {
29033
+ if (!released) {
29034
+ released = true;
29035
+ release();
29036
+ }
29037
+ };
29038
+ const reader = response.body.getReader();
29039
+ const body = new ReadableStream({
29040
+ async pull(controller) {
29041
+ try {
29042
+ const { done, value } = await reader.read();
29043
+ if (done) {
29044
+ controller.close();
29045
+ once();
29046
+ return;
29047
+ }
29048
+ controller.enqueue(value);
29049
+ } catch (error) {
29050
+ controller.error(error);
29051
+ once();
29052
+ }
29053
+ },
29054
+ cancel(reason) {
29055
+ once();
29056
+ return reader.cancel(reason);
27938
29057
  }
27939
29058
  });
29059
+ const wrapped = new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
29060
+ Object.defineProperty(wrapped, "url", { value: response.url });
29061
+ Object.defineProperty(wrapped, "redirected", { value: response.redirected });
29062
+ return wrapped;
27940
29063
  }
27941
29064
  function validateHeaderName(name) {
27942
29065
  if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(name)) throw Object.assign(new TypeError(`Header name must be a valid HTTP token [${name}]`), { code: "ERR_INVALID_HTTP_TOKEN" });
@@ -28031,12 +29154,12 @@ function invoke(host, fn, context, timeout) {
28031
29154
  function createMockTracker() {
28032
29155
  const restorers = [];
28033
29156
  const fn = (original = () => void 0, implementation = original) => {
28034
- let current2 = implementation;
29157
+ let current3 = implementation;
28035
29158
  const once = /* @__PURE__ */ new Map();
28036
29159
  const calls = [];
28037
29160
  const mocked = function(...args) {
28038
29161
  const index = calls.length;
28039
- const chosen = once.get(index) ?? current2;
29162
+ const chosen = once.get(index) ?? current3;
28040
29163
  once.delete(index);
28041
29164
  const call = { arguments: args, result: void 0, error: void 0, this: this };
28042
29165
  calls.push(call);
@@ -28056,13 +29179,13 @@ function createMockTracker() {
28056
29179
  calls.length = 0;
28057
29180
  },
28058
29181
  mockImplementation: (next) => {
28059
- current2 = next;
29182
+ current3 = next;
28060
29183
  },
28061
29184
  mockImplementationOnce: (next, onCall) => {
28062
29185
  once.set(onCall ?? calls.length, next);
28063
29186
  },
28064
29187
  restore: () => {
28065
- current2 = original;
29188
+ current3 = original;
28066
29189
  }
28067
29190
  }
28068
29191
  });
@@ -28075,21 +29198,21 @@ function createMockTracker() {
28075
29198
  }
28076
29199
  const mocked = fn(original, implementation ?? original);
28077
29200
  object[name] = mocked;
28078
- const restore = () => {
29201
+ const restore2 = () => {
28079
29202
  object[name] = original;
28080
29203
  };
28081
- mocked.mock.restore = restore;
28082
- restorers.push(restore);
29204
+ mocked.mock.restore = restore2;
29205
+ restorers.push(restore2);
28083
29206
  return mocked;
28084
29207
  };
28085
29208
  return {
28086
29209
  fn,
28087
29210
  method,
28088
29211
  reset: () => {
28089
- for (const restore of restorers.splice(0)) restore();
29212
+ for (const restore2 of restorers.splice(0)) restore2();
28090
29213
  },
28091
29214
  restoreAll: () => {
28092
- for (const restore of restorers.splice(0)) restore();
29215
+ for (const restore2 of restorers.splice(0)) restore2();
28093
29216
  }
28094
29217
  };
28095
29218
  }
@@ -29577,35 +30700,25 @@ var SyncChannelClient = class {
29577
30700
  waitWhile(state) {
29578
30701
  for (; ; ) {
29579
30702
  Atomics.wait(this.control, STATE, state, WAIT_SLICE_MS);
29580
- const current2 = Atomics.load(this.control, STATE);
29581
- if (current2 !== state) return current2;
30703
+ const current3 = Atomics.load(this.control, STATE);
30704
+ if (current3 !== state) return current3;
29582
30705
  }
29583
30706
  }
29584
30707
  };
29585
30708
 
29586
30709
  // src/node/child-process-module.ts
29587
30710
  var import_events2 = __toESM(require_events());
29588
- var import_stream_browserify3 = __toESM(require_stream_browserify());
30711
+ var import_stream_browserify4 = __toESM(require_stream_browserify());
29589
30712
  var ChildProcess = class extends import_events2.default {
29590
- stdout = new import_stream_browserify3.default.PassThrough();
29591
- stderr = new import_stream_browserify3.default.PassThrough();
29592
- stdin;
29593
- stdio;
29594
- pid;
29595
- exitCode = null;
29596
- signalCode = null;
29597
- killed = false;
29598
- spawnfile;
29599
- spawnargs;
29600
- handle;
29601
- settled = false;
29602
- constructor(handle, file, args) {
30713
+ constructor(handle, file, args, referenceChanged = () => {
30714
+ }, extraPipes = []) {
29603
30715
  super();
30716
+ this.referenceChanged = referenceChanged;
29604
30717
  this.handle = handle;
29605
30718
  this.pid = handle.pid;
29606
30719
  this.spawnfile = file;
29607
30720
  this.spawnargs = [file, ...args];
29608
- this.stdin = new import_stream_browserify3.default.Writable({
30721
+ this.stdin = new import_stream_browserify4.default.Writable({
29609
30722
  write: (chunk, _encoding, done) => {
29610
30723
  try {
29611
30724
  handle.sendStdin(typeof chunk === "string" ? chunk : Buffer2.from(chunk).toString("utf8"));
@@ -29622,43 +30735,144 @@ var ChildProcess = class extends import_events2.default {
29622
30735
  }
29623
30736
  });
29624
30737
  this.stdio = [this.stdin, this.stdout, this.stderr];
30738
+ for (const fd of extraPipes) this.stdio[fd] = this.extraPipe(fd);
30739
+ handle.on("fd", (event) => {
30740
+ const pipe = this.stdio[event.fd];
30741
+ pipe?.push(Buffer2.from(event.text));
30742
+ });
29625
30743
  handle.on("stdout", (text) => this.stdout.write(text));
29626
30744
  handle.on("stderr", (text) => this.stderr.write(text));
29627
30745
  handle.on("exit", (code) => this.finish(code));
29628
- handle.exec();
29629
- }
29630
- kill(signal = "SIGTERM") {
29631
- this.killed = true;
29632
- this.handle.kill(typeof signal === "number" ? "SIGTERM" : signal);
29633
- return true;
29634
- }
29635
- ref() {
29636
- return this;
29637
- }
29638
- unref() {
29639
- return this;
30746
+ referenceChanged(1);
30747
+ try {
30748
+ handle.exec();
30749
+ } catch (error) {
30750
+ this.unref();
30751
+ throw error;
30752
+ }
29640
30753
  }
29641
- disconnect() {
29642
- this.emit("disconnect");
30754
+ referenceChanged;
30755
+ stdout = new import_stream_browserify4.default.PassThrough();
30756
+ stderr = new import_stream_browserify4.default.PassThrough();
30757
+ stdin;
30758
+ stdio;
30759
+ pid;
30760
+ exitCode = null;
30761
+ signalCode = null;
30762
+ killed = false;
30763
+ spawnfile;
30764
+ spawnargs;
30765
+ handle;
30766
+ settled = false;
30767
+ referenced = true;
30768
+ /**
30769
+ * The parent's end of `stdio[fd] = "pipe"` for a descriptor above 2.
30770
+ *
30771
+ * One Duplex per descriptor, as Node gives: what the parent writes reaches
30772
+ * the child's `fd`, and what the child writes there is readable here. Chunks
30773
+ * are Buffers because the DevTools pipe is framed by NUL bytes and its reader
30774
+ * searches the chunk with `indexOf("\0")`.
30775
+ */
30776
+ extraPipe(fd) {
30777
+ const handle = this.handle;
30778
+ return new import_stream_browserify4.default.Duplex({
30779
+ read() {
30780
+ },
30781
+ write(chunk, _encoding, done) {
30782
+ try {
30783
+ handle.writeFd?.(fd, typeof chunk === "string" ? chunk : Buffer2.from(chunk).toString("utf8"));
30784
+ } catch {
30785
+ }
30786
+ done();
30787
+ },
30788
+ final(done) {
30789
+ try {
30790
+ handle.endFd?.(fd);
30791
+ } catch {
30792
+ }
30793
+ done();
30794
+ }
30795
+ });
29643
30796
  }
29644
- /** No IPC channel exists, and reporting that honestly beats a silent drop. */
29645
- send() {
29646
- return false;
30797
+ kill(signal = "SIGTERM") {
30798
+ this.killed = true;
30799
+ this.handle.kill(typeof signal === "number" ? "SIGTERM" : signal);
30800
+ return true;
30801
+ }
30802
+ ref() {
30803
+ if (!this.settled && !this.referenced) {
30804
+ this.referenced = true;
30805
+ this.referenceChanged(1);
30806
+ }
30807
+ return this;
30808
+ }
30809
+ unref() {
30810
+ if (this.referenced) {
30811
+ this.referenced = false;
30812
+ this.referenceChanged(-1);
30813
+ }
30814
+ return this;
30815
+ }
30816
+ channel;
30817
+ channelOpen = false;
30818
+ /** Open the parent's end of a `fork` channel. */
30819
+ attachChannel(transport, id) {
30820
+ this.channelOpen = true;
30821
+ this.channel = transport.attach(
30822
+ id,
30823
+ "parent",
30824
+ (message) => this.emit("message", message, void 0),
30825
+ () => this.channelClosed()
30826
+ );
29647
30827
  }
29648
30828
  get connected() {
29649
- return false;
30829
+ return this.channelOpen;
30830
+ }
30831
+ /** `send(message[, sendHandle][, options][, callback])`, as Node spells it. */
30832
+ send(message, ...rest) {
30833
+ const callback = rest.find((value) => typeof value === "function");
30834
+ if (!this.channel || !this.channelOpen) {
30835
+ const error = Object.assign(new Error("Channel closed"), { code: "ERR_IPC_CHANNEL_CLOSED" });
30836
+ if (callback) queueMicrotask(() => callback(error));
30837
+ else queueMicrotask(() => this.emit("error", error));
30838
+ return false;
30839
+ }
30840
+ this.channel.send(message);
30841
+ if (callback) queueMicrotask(() => callback(null));
30842
+ return true;
30843
+ }
30844
+ disconnect() {
30845
+ if (!this.channelOpen) return;
30846
+ this.channel?.disconnect();
30847
+ this.channelClosed();
30848
+ }
30849
+ channelClosed() {
30850
+ if (!this.channelOpen) return;
30851
+ this.channelOpen = false;
30852
+ this.emit("disconnect");
29650
30853
  }
29651
30854
  finish(code) {
29652
30855
  if (this.settled) return;
30856
+ this.channel?.disconnect();
30857
+ this.channelClosed();
30858
+ this.unref();
29653
30859
  this.settled = true;
29654
30860
  this.exitCode = code;
29655
30861
  this.stdout.end();
29656
30862
  this.stderr.end();
30863
+ for (const pipe of this.stdio.slice(3)) {
30864
+ if (!pipe) continue;
30865
+ pipe.once("end", () => pipe.destroy());
30866
+ pipe.push(null);
30867
+ if (!pipe.readableFlowing) queueMicrotask(() => {
30868
+ if (!pipe.readableFlowing) pipe.destroy();
30869
+ });
30870
+ }
29657
30871
  this.emit("exit", code, null);
29658
30872
  queueMicrotask(() => this.emit("close", code, null));
29659
30873
  }
29660
30874
  };
29661
- function createChildProcessModule(spawnChild, defaultCwd, syncSpawn, defaultEnv = () => ({})) {
30875
+ function createChildProcessModule(spawnChild, defaultCwd, syncSpawn, defaultEnv = () => ({}), lifecycle = {}) {
29662
30876
  const environmentFor = (options) => options.env ? { ...options.env } : defaultEnv();
29663
30877
  const throughShell = (command, options) => {
29664
30878
  const shell = typeof options.shell === "string" ? options.shell : "/bin/sh";
@@ -29669,16 +30883,27 @@ function createChildProcessModule(spawnChild, defaultCwd, syncSpawn, defaultEnv
29669
30883
  if (stdio === "ignore") return true;
29670
30884
  return Array.isArray(stdio) && stdio[0] === "ignore";
29671
30885
  };
30886
+ const wantsChannel = (options) => Array.isArray(options.stdio) && options.stdio.includes("ipc");
30887
+ const extraPipesOf = (options) => Array.isArray(options.stdio) ? options.stdio.flatMap((entry, fd) => fd > 2 && (entry === "pipe" || entry === "overlapped") ? [fd] : []) : [];
29672
30888
  const start = (file, args, options) => {
29673
30889
  const resolved = options.shell ? throughShell([file, ...args].join(" "), options) : { file, args };
30890
+ const channelId = wantsChannel(options) && lifecycle.ipc ? newIpcChannelId() : void 0;
30891
+ const extraPipes = extraPipesOf(options);
29674
30892
  const handle = spawnChild({
29675
30893
  command: resolved.file,
29676
30894
  args: resolved.args,
29677
30895
  cwd: options.cwd ?? defaultCwd(),
29678
- env: environmentFor(options),
29679
- ...stdinIgnored(options) ? { stdinIgnored: true } : {}
30896
+ env: channelId ? { ...environmentFor(options), [IPC_CHANNEL_ENV]: channelId } : environmentFor(options),
30897
+ ...options.stdio === "inherit" || Array.isArray(options.stdio) && options.stdio[0] === "inherit" ? { inheritStdio: true } : {},
30898
+ ...stdinIgnored(options) ? { stdinIgnored: true } : {},
30899
+ ...extraPipes.length ? { extraPipes } : {}
29680
30900
  });
29681
- return new ChildProcess(handle, resolved.file, resolved.args);
30901
+ const child = new ChildProcess(handle, resolved.file, resolved.args, lifecycle.referenceChanged, extraPipes);
30902
+ if (channelId && lifecycle.ipc) child.attachChannel(lifecycle.ipc, channelId);
30903
+ const inherited = (index) => options.stdio === "inherit" || Array.isArray(options.stdio) && options.stdio[index] === "inherit";
30904
+ if (inherited(1)) child.stdout.on("data", (chunk) => lifecycle.stdout?.(chunk.toString()));
30905
+ if (inherited(2)) child.stderr.on("data", (chunk) => lifecycle.stderr?.(chunk.toString()));
30906
+ return child;
29682
30907
  };
29683
30908
  const spawn = (file, args = [], options = {}) => {
29684
30909
  if (!Array.isArray(args)) return start(file, [], args);
@@ -29721,7 +30946,13 @@ ${err2.join("")}`),
29721
30946
  spawn,
29722
30947
  exec,
29723
30948
  execFile,
29724
- fork: (modulePath, args = [], options = {}) => spawn("node", [modulePath, ...args], options),
30949
+ fork: (modulePath, args = [], options = {}) => {
30950
+ const [list, opts] = Array.isArray(args) ? [args, options] : [[], args ?? {}];
30951
+ const stdio = Array.isArray(opts.stdio) ? opts.stdio : typeof opts.stdio === "string" ? [opts.stdio, opts.stdio, opts.stdio] : opts.silent ? ["pipe", "pipe", "pipe"] : ["inherit", "inherit", "inherit"];
30952
+ const withChannel = stdio.includes("ipc") ? stdio : [...stdio, "ipc"];
30953
+ const execArgv = (opts.execArgv ?? []).filter((flag) => !/^--(inspect|debug)/.test(flag));
30954
+ return start("node", [...execArgv, modulePath, ...list], { ...opts, shell: false, stdio: withChannel });
30955
+ },
29725
30956
  ...buildSyncFamily(syncSpawn, throughShell, defaultCwd, environmentFor),
29726
30957
  ChildProcess
29727
30958
  };
@@ -30253,7 +31484,8 @@ var KERNEL_RELEASE = "5.10.0";
30253
31484
  var KERNEL_VERSION = `Linux version ${KERNEL_RELEASE} (sandboxedjs@sandbox) (gcc version 12.2.0) #1 SMP PREEMPT_DYNAMIC`;
30254
31485
 
30255
31486
  // src/node/core-modules.ts
30256
- installReadableFrom(import_stream_browserify4.default);
31487
+ installStreamCompat();
31488
+ installReadableFrom(import_stream_browserify5.default);
30257
31489
  var Dirent = class {
30258
31490
  /** Node 20+ exposes the containing directory, and `fs.glob` consumers read it. */
30259
31491
  constructor(name, stat, parentPath = "") {
@@ -30394,6 +31626,9 @@ function createCoreModules(options) {
30394
31626
  argv: options.argv?.slice() ?? ["/usr/bin/node"],
30395
31627
  argv0: "node",
30396
31628
  execPath: "/usr/bin/node",
31629
+ /* `process/browser.js` has no `execArgv`; Node always has an array, and
31630
+ * CLIs that fork copy it (`[...process.execArgv]`). */
31631
+ execArgv: [],
30397
31632
  env,
30398
31633
  platform: "linux",
30399
31634
  arch: "x64",
@@ -30435,7 +31670,7 @@ function createCoreModules(options) {
30435
31670
  if (typeof fn !== "function") {
30436
31671
  throw Object.assign(new TypeError('The "callback" argument must be of type function'), { code: "ERR_INVALID_ARG_TYPE" });
30437
31672
  }
30438
- tickQueue.push([fn, args]);
31673
+ tickQueue.push([bindToCurrent(fn), args]);
30439
31674
  if (!tickDrainScheduled) {
30440
31675
  tickDrainScheduled = true;
30441
31676
  afterMicrotasks(runTicks);
@@ -30447,6 +31682,25 @@ function createCoreModules(options) {
30447
31682
  const implementation = import_events4.default.prototype[method];
30448
31683
  if (typeof implementation === "function") processObject[method] = implementation;
30449
31684
  }
31685
+ const hrtime = (previous) => {
31686
+ const now = performance.timeOrigin + performance.now();
31687
+ let seconds = Math.floor(now / 1e3);
31688
+ let nanoseconds = Math.floor(now % 1e3 * 1e6);
31689
+ if (previous) {
31690
+ seconds -= previous[0];
31691
+ nanoseconds -= previous[1];
31692
+ if (nanoseconds < 0) {
31693
+ seconds -= 1;
31694
+ nanoseconds += 1e9;
31695
+ }
31696
+ }
31697
+ return [seconds, nanoseconds];
31698
+ };
31699
+ hrtime.bigint = () => {
31700
+ const [seconds, nanoseconds] = hrtime();
31701
+ return BigInt(seconds) * 1000000000n + BigInt(nanoseconds);
31702
+ };
31703
+ processObject.hrtime = hrtime;
30450
31704
  const tty = options.tty === true;
30451
31705
  processObject.stdout = makeOutputStream(stdoutWrite, 1, tty);
30452
31706
  processObject.stderr = makeOutputStream(stderrWrite, 2, tty);
@@ -30488,15 +31742,16 @@ function createCoreModules(options) {
30488
31742
  }
30489
31743
  };
30490
31744
  const defer = (fn) => {
31745
+ const bound = bindToCurrent(fn);
30491
31746
  queueMicrotask(() => {
30492
31747
  try {
30493
- fn();
31748
+ bound();
30494
31749
  } catch (error) {
30495
31750
  reportUncaught(error);
30496
31751
  }
30497
31752
  });
30498
31753
  };
30499
- const stdin = options.interactiveStdin ? new import_stream_browserify4.default.PassThrough() : new import_stream_browserify4.default.Readable({ read() {
31754
+ const stdin = options.interactiveStdin ? new import_stream_browserify5.default.PassThrough() : new import_stream_browserify5.default.Readable({ read() {
30500
31755
  this.push(null);
30501
31756
  } });
30502
31757
  Object.assign(stdin, {
@@ -30531,6 +31786,7 @@ function createCoreModules(options) {
30531
31786
  const moduleBuiltin = {
30532
31787
  builtinModules: builtinNames.flatMap((name) => [name, `node:${name}`]),
30533
31788
  isBuiltin: (name) => builtinNames.includes(name.replace(/^node:/, "")),
31789
+ findSourceMap: () => void 0,
30534
31790
  createRequire: () => {
30535
31791
  throw new Error("createRequire is only available inside a loaded module");
30536
31792
  }
@@ -30553,18 +31809,98 @@ function createCoreModules(options) {
30553
31809
  };
30554
31810
  const http = options.http ? createHttpModule(options.http.router, options.http.owner, httpOptions, "http:") : createUnsupportedModule("http");
30555
31811
  const https = options.http ? createHttpModule(options.http.router, options.http.owner, httpOptions, "https:") : createUnsupportedModule("https");
30556
- const childProcess = options.spawnChild ? createChildProcessModule(options.spawnChild, () => cwd, options.syncSpawn, () => ({ ...processObject.env })) : createUnsupportedModule("child_process");
31812
+ let referencedChildren = 0;
31813
+ const childProcess = options.spawnChild ? createChildProcessModule(options.spawnChild, () => cwd, options.syncSpawn, () => ({ ...processObject.env }), {
31814
+ referenceChanged: (delta) => {
31815
+ referencedChildren += delta;
31816
+ },
31817
+ stdout: options.stdout,
31818
+ stderr: options.stderr,
31819
+ ...options.ipc ? { ipc: options.ipc } : {}
31820
+ }) : createUnsupportedModule("child_process");
31821
+ let channelReferenced = 0;
31822
+ const channelId = env[IPC_CHANNEL_ENV];
31823
+ if (channelId && options.ipc) {
31824
+ delete env[IPC_CHANNEL_ENV];
31825
+ let open = true;
31826
+ let referenced = true;
31827
+ channelReferenced = 1;
31828
+ const close = () => {
31829
+ if (!open) return;
31830
+ open = false;
31831
+ if (referenced) channelReferenced = 0;
31832
+ processObject.connected = false;
31833
+ delete processObject.send;
31834
+ try {
31835
+ processObject.emit("disconnect");
31836
+ } catch (error) {
31837
+ reportUncaught(error);
31838
+ }
31839
+ runTicks();
31840
+ };
31841
+ const endpoint = options.ipc.attach(
31842
+ channelId,
31843
+ "child",
31844
+ (message) => {
31845
+ try {
31846
+ processObject.emit("message", message, void 0);
31847
+ } catch (error) {
31848
+ reportUncaught(error);
31849
+ }
31850
+ runTicks();
31851
+ },
31852
+ close
31853
+ );
31854
+ processObject.connected = true;
31855
+ processObject.send = (message, ...rest) => {
31856
+ const callback = rest.find((value) => typeof value === "function");
31857
+ if (!open) {
31858
+ const error = Object.assign(new Error("Channel closed"), { code: "ERR_IPC_CHANNEL_CLOSED" });
31859
+ if (callback) defer(() => callback(error));
31860
+ else defer(() => {
31861
+ processObject.emit("error", error);
31862
+ });
31863
+ return false;
31864
+ }
31865
+ endpoint.send(message);
31866
+ if (callback) defer(() => callback(null));
31867
+ return true;
31868
+ };
31869
+ processObject.disconnect = () => {
31870
+ if (open) {
31871
+ endpoint.disconnect();
31872
+ close();
31873
+ }
31874
+ };
31875
+ processObject.channel = {
31876
+ ref() {
31877
+ if (open && !referenced) {
31878
+ referenced = true;
31879
+ channelReferenced = 1;
31880
+ }
31881
+ return this;
31882
+ },
31883
+ unref() {
31884
+ if (referenced) {
31885
+ referenced = false;
31886
+ channelReferenced = 0;
31887
+ }
31888
+ return this;
31889
+ }
31890
+ };
31891
+ }
30557
31892
  const readline = createReadlineModule(() => processObject.stdin, () => processObject.stdout);
30558
31893
  const dns = createDnsModule(defer);
30559
31894
  const builtins = {
30560
31895
  assert: assert_module_default,
30561
31896
  "assert/strict": assert_module_default.strict ?? assert_module_default,
30562
- buffer: { Buffer: Buffer2, SlowBuffer: Buffer2, INSPECT_MAX_BYTES: 50, kMaxLength: Buffer2.kMaxLength },
31897
+ buffer: createBufferBuiltin(),
30563
31898
  async_hooks: asyncHooks,
30564
31899
  child_process: childProcess,
30565
31900
  console: consoleObject,
30566
31901
  constants: fs.constants,
30567
31902
  crypto: createCryptoModule(),
31903
+ diagnostics_channel: createDiagnosticsChannel(),
30568
31904
  dns,
30569
31905
  "dns/promises": dns.promises,
30570
31906
  events: import_events4.default,
@@ -30582,12 +31918,31 @@ function createCoreModules(options) {
30582
31918
  querystring: import_querystring_es3.default,
30583
31919
  readline,
30584
31920
  "readline/promises": readline.promises,
30585
- stream: import_stream_browserify4.default,
31921
+ stream: import_stream_browserify5.default,
31922
+ "stream/web": Object.fromEntries([
31923
+ "ReadableStream",
31924
+ "ReadableStreamDefaultReader",
31925
+ "ReadableStreamBYOBReader",
31926
+ "ReadableStreamDefaultController",
31927
+ "ReadableByteStreamController",
31928
+ "ReadableStreamBYOBRequest",
31929
+ "WritableStream",
31930
+ "WritableStreamDefaultWriter",
31931
+ "WritableStreamDefaultController",
31932
+ "TransformStream",
31933
+ "TransformStreamDefaultController",
31934
+ "ByteLengthQueuingStrategy",
31935
+ "CountQueuingStrategy",
31936
+ "TextEncoderStream",
31937
+ "TextDecoderStream",
31938
+ "CompressionStream",
31939
+ "DecompressionStream"
31940
+ ].filter((name) => name in globalThis).map((name) => [name, globalThis[name]])),
30586
31941
  "stream/promises": createStreamPromises(),
30587
31942
  string_decoder: import_string_decoder.default,
30588
31943
  timers: { ...import_timers_browserify.default, ...timers.api },
30589
31944
  "timers/promises": createTimerPromises(timers.api),
30590
- tty: { isatty: () => false, ReadStream: import_stream_browserify4.default.Readable, WriteStream: import_stream_browserify4.default.Writable },
31945
+ tty: { isatty: () => false, ReadStream: import_stream_browserify5.default.Readable, WriteStream: import_stream_browserify5.default.Writable },
30591
31946
  url: url_module_default,
30592
31947
  util: util_module_default,
30593
31948
  "util/types": util_module_default.types ?? {},
@@ -30614,19 +31969,73 @@ function createCoreModules(options) {
30614
31969
  })
30615
31970
  };
30616
31971
  for (const name of stubNames) builtins[name] = createUnsupportedModule(name);
31972
+ builtins.worker_threads = {
31973
+ MessagePort: globalThis.MessagePort ?? class MessagePort {
31974
+ },
31975
+ markAsUncloneable: () => {
31976
+ },
31977
+ isMarkedAsUncloneable: () => false,
31978
+ markAsUntransferable: () => {
31979
+ },
31980
+ isMarkedAsUntransferable: () => false
31981
+ };
30617
31982
  builtins.net = createNetModule();
31983
+ builtins.vm = vm_module_default;
31984
+ builtins.inspector = createUnsupportedModule("inspector", {
31985
+ url: () => void 0,
31986
+ close: () => {
31987
+ },
31988
+ waitForDebugger: () => {
31989
+ throw Object.assign(new Error("Inspector is not active"), { code: "ERR_INSPECTOR_NOT_ACTIVE" });
31990
+ },
31991
+ console: consoleObject
31992
+ });
31993
+ builtins.v8 = createUnsupportedModule("v8", {
31994
+ getHeapStatistics: () => {
31995
+ const memory = performance.memory;
31996
+ const limit = memory?.jsHeapSizeLimit ?? 4 * 1024 ** 3;
31997
+ return {
31998
+ total_heap_size: memory?.totalJSHeapSize ?? 0,
31999
+ total_heap_size_executable: 0,
32000
+ total_physical_size: memory?.totalJSHeapSize ?? 0,
32001
+ total_available_size: limit - (memory?.usedJSHeapSize ?? 0),
32002
+ used_heap_size: memory?.usedJSHeapSize ?? 0,
32003
+ heap_size_limit: limit,
32004
+ malloced_memory: 0,
32005
+ peak_malloced_memory: 0,
32006
+ does_zap_garbage: 0,
32007
+ number_of_native_contexts: 1,
32008
+ number_of_detached_contexts: 0,
32009
+ total_global_handles_size: 0,
32010
+ used_global_handles_size: 0,
32011
+ external_memory: 0
32012
+ };
32013
+ },
32014
+ getHeapSpaceStatistics: () => [],
32015
+ getHeapCodeStatistics: () => ({ code_and_metadata_size: 0, bytecode_and_metadata_size: 0, external_script_source_size: 0, cpu_profiler_metadata_size: 0 }),
32016
+ cachedDataVersionTag: () => 0,
32017
+ setFlagsFromString: () => {
32018
+ },
32019
+ setHeapSnapshotNearHeapLimit: () => {
32020
+ },
32021
+ serialize: (value) => Buffer2.from(JSON.stringify(value) ?? "null"),
32022
+ deserialize: (buffer) => JSON.parse(Buffer2.from(buffer).toString("utf8"))
32023
+ });
30618
32024
  const globals = {
30619
32025
  Buffer: Buffer2,
30620
32026
  console: consoleObject,
30621
32027
  process: processObject,
30622
32028
  ...timers.api,
30623
- queueMicrotask: (fn) => queueMicrotask(() => {
30624
- try {
30625
- fn();
30626
- } catch (error) {
30627
- reportUncaught(error);
30628
- }
30629
- })
32029
+ queueMicrotask: (fn) => {
32030
+ const bound = bindToCurrent(fn);
32031
+ queueMicrotask(() => {
32032
+ try {
32033
+ bound();
32034
+ } catch (error) {
32035
+ reportUncaught(error);
32036
+ }
32037
+ });
32038
+ }
30630
32039
  };
30631
32040
  if (options.http) {
30632
32041
  globals.fetch = createVirtualFetch(options.http.router, {
@@ -30649,7 +32058,7 @@ function createCoreModules(options) {
30649
32058
  builtins,
30650
32059
  globals,
30651
32060
  process: processObject,
30652
- pendingHandles: timers.pending,
32061
+ pendingHandles: () => timers.pending() + referencedChildren + channelReferenced,
30653
32062
  pendingUnrefed: timers.pendingUnrefed,
30654
32063
  /** Client requests sent but not yet read to completion. */
30655
32064
  pendingRequests: () => inFlightRequests,
@@ -30671,7 +32080,7 @@ function createCoreModules(options) {
30671
32080
  },
30672
32081
  loopActivity: () => timers.scheduled() + requestsStarted,
30673
32082
  writeStdin: (data2) => {
30674
- if (options.interactiveStdin) stdin.write(data2);
32083
+ if (options.interactiveStdin) stdin.write(typeof data2 === "string" ? data2 : Buffer2.from(data2));
30675
32084
  },
30676
32085
  endStdin: () => {
30677
32086
  if (options.interactiveStdin) stdin.end();
@@ -30715,7 +32124,9 @@ var ASYNC_FS_METHODS = [
30715
32124
  "close",
30716
32125
  "read",
30717
32126
  "write",
30718
- "exists"
32127
+ "exists",
32128
+ "fsync",
32129
+ "fdatasync"
30719
32130
  ];
30720
32131
  function createPathModule(cwd) {
30721
32132
  const resolve2 = (...segments2) => import_path_browserify.default.resolve(cwd(), ...segments2);
@@ -30892,10 +32303,27 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
30892
32303
  },
30893
32304
  writeSync: (fd, data2, offset2, length, position) => {
30894
32305
  const file = requiredFd(fds, fd);
32306
+ if (typeof data2 === "string") {
32307
+ const stringPosition = typeof offset2 === "number" ? offset2 : null;
32308
+ const encoding = typeof length === "string" ? length : "utf8";
32309
+ data2 = Buffer2.from(data2, encoding);
32310
+ position = stringPosition;
32311
+ offset2 = 0;
32312
+ length = data2.length;
32313
+ }
30895
32314
  const input = bytes2(data2);
30896
- const chunk = typeof data2 === "string" ? input : input.subarray(offset2 ?? 0, (offset2 ?? 0) + (length ?? input.length));
32315
+ const chunk = input.subarray(offset2 ?? 0, (offset2 ?? 0) + (length ?? input.length));
32316
+ const size = volume.lstatSync(file.path).size;
32317
+ const append = file.flags.startsWith("a") || (position ?? file.position) >= size;
32318
+ if (append) {
32319
+ const at2 = file.flags.startsWith("a") ? size : position ?? file.position;
32320
+ if (at2 > size) volume.appendFileSync(file.path, new Uint8Array(at2 - size));
32321
+ volume.appendFileSync(file.path, chunk);
32322
+ if (position == null) file.position = at2 + chunk.length;
32323
+ return chunk.length;
32324
+ }
30897
32325
  const old = volume.readFileSync(file.path);
30898
- const start = file.flags.startsWith("a") ? old.length : position ?? file.position;
32326
+ const start = position ?? file.position;
30899
32327
  const next = new Uint8Array(Math.max(old.length, start + chunk.length));
30900
32328
  next.set(old);
30901
32329
  next.set(chunk, start);
@@ -30903,41 +32331,22 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
30903
32331
  if (position == null) file.position = start + chunk.length;
30904
32332
  return chunk.length;
30905
32333
  },
30906
- createReadStream: (path, options) => {
30907
- const target = abs(path);
30908
- const settings = typeof options === "string" ? { encoding: options } : options ?? {};
30909
- const whole = Buffer2.from(volume.readFileSync(resolveLinks(volume, target)));
30910
- const start = settings.start ?? 0;
30911
- const end = settings.end === void 0 ? whole.length : Math.min(settings.end + 1, whole.length);
30912
- const slice = whole.subarray(start, Math.max(start, end));
30913
- const stream = import_stream_browserify4.default.Readable.from([settings.encoding ? slice.toString(settings.encoding) : slice]);
30914
- Object.assign(stream, { path: target, bytesRead: slice.length, close: () => stream.destroy() });
30915
- defer(() => {
30916
- stream.emit("open", 0);
30917
- stream.emit("ready");
30918
- });
30919
- return stream;
30920
- },
30921
- createWriteStream: (path, options) => {
30922
- const target = abs(path);
30923
- let first = true;
30924
- return new import_stream_browserify4.default.Writable({ write(chunk, _encoding, done) {
30925
- try {
30926
- if (options?.flags?.startsWith("a") || !first) volume.appendFileSync(target, new Uint8Array(chunk));
30927
- else volume.writeFileSync(target, new Uint8Array(chunk));
30928
- first = false;
30929
- done();
30930
- } catch (error) {
30931
- done(error);
30932
- }
30933
- } });
30934
- },
32334
+ /* Looked up on `fs` at call time, so a package that replaces
32335
+ * `fs.ReadStream`/`fs.WriteStream` — graceful-fs does — is honoured. */
32336
+ createReadStream: (path, options) => new fs.ReadStream(path, options),
32337
+ createWriteStream: (path, options) => new fs.WriteStream(path, options),
30935
32338
  watch: () => new FsWatcher(),
30936
32339
  watchFile: () => {
30937
32340
  },
30938
32341
  unwatchFile: () => {
30939
32342
  }
30940
32343
  };
32344
+ fs.fsyncSync = (fd) => {
32345
+ requiredFd(fds, fd);
32346
+ };
32347
+ fs.fdatasyncSync = (fd) => {
32348
+ requiredFd(fds, fd);
32349
+ };
30941
32350
  fs.ftruncateSync = (fd, length) => fs.truncateSync(requiredFd(fds, fd).path, length);
30942
32351
  fs.fchmodSync = (fd, mode) => fs.chmodSync(requiredFd(fds, fd).path, mode);
30943
32352
  fs.fchownSync = (fd, uid, gid) => fs.chownSync(requiredFd(fds, fd).path, uid, gid);
@@ -30979,6 +32388,264 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
30979
32388
  };
30980
32389
  }
30981
32390
  fs.realpath.native = fs.realpath;
32391
+ const streamSettings = (options) => typeof options === "string" ? { encoding: options } : options ?? {};
32392
+ function WriteStream(path, options) {
32393
+ const self2 = this;
32394
+ if (!Object.prototype.isPrototypeOf.call(WriteStream.prototype, self2)) return new WriteStream(path, options);
32395
+ const settings = streamSettings(options);
32396
+ import_stream_browserify5.default.Writable.call(self2, { highWaterMark: settings.highWaterMark, emitClose: true });
32397
+ self2.path = abs(path);
32398
+ self2.flags = settings.flags ?? "w";
32399
+ self2.mode = settings.mode ?? 438;
32400
+ self2.fd = typeof settings.fd === "number" ? settings.fd : null;
32401
+ self2.bytesWritten = 0;
32402
+ self2.pending = true;
32403
+ self2._opened = self2.fd !== null;
32404
+ self2.once("open", () => {
32405
+ self2._opened = true;
32406
+ self2.pending = false;
32407
+ });
32408
+ self2.once("finish", () => {
32409
+ if (!self2.destroyed) self2.destroy();
32410
+ });
32411
+ if (self2.fd === null) self2.open();
32412
+ else defer(() => {
32413
+ self2.emit("open", self2.fd);
32414
+ self2.emit("ready");
32415
+ });
32416
+ }
32417
+ WriteStream.prototype = Object.create(import_stream_browserify5.default.Writable.prototype, {
32418
+ constructor: { value: WriteStream, writable: true, configurable: true }
32419
+ });
32420
+ WriteStream.prototype.open = function() {
32421
+ const self2 = this;
32422
+ try {
32423
+ if (String(self2.flags).startsWith("a")) {
32424
+ if (!fs.existsSync(self2.path)) volume.writeFileSync(self2.path, new Uint8Array());
32425
+ } else volume.writeFileSync(self2.path, new Uint8Array());
32426
+ } catch (error) {
32427
+ defer(() => self2.destroy(error));
32428
+ return;
32429
+ }
32430
+ defer(() => {
32431
+ self2.emit("open", 0);
32432
+ self2.emit("ready");
32433
+ });
32434
+ };
32435
+ WriteStream.prototype._write = function(chunk, encoding, done) {
32436
+ const self2 = this;
32437
+ const append = () => {
32438
+ try {
32439
+ const bytes3 = typeof chunk === "string" ? Buffer2.from(chunk, encoding) : chunk;
32440
+ volume.appendFileSync(self2.path, new Uint8Array(bytes3));
32441
+ self2.bytesWritten += bytes3.length;
32442
+ done();
32443
+ } catch (error) {
32444
+ done(error);
32445
+ }
32446
+ };
32447
+ if (self2._opened) append();
32448
+ else self2.once("open", append);
32449
+ };
32450
+ WriteStream.prototype.close = function(callback2) {
32451
+ const self2 = this;
32452
+ if (callback2) {
32453
+ if (self2.closed) defer(() => callback2(null));
32454
+ else {
32455
+ self2.once("close", () => callback2(null));
32456
+ self2.once("error", (error) => callback2(error));
32457
+ }
32458
+ }
32459
+ if (!self2.writableEnded) self2.end();
32460
+ else if (!self2.destroyed) self2.destroy();
32461
+ };
32462
+ function ReadStream(path, options) {
32463
+ const self2 = this;
32464
+ if (!Object.prototype.isPrototypeOf.call(ReadStream.prototype, self2)) return new ReadStream(path, options);
32465
+ const settings = streamSettings(options);
32466
+ import_stream_browserify5.default.Readable.call(self2, { highWaterMark: settings.highWaterMark, encoding: settings.encoding, emitClose: true });
32467
+ self2.path = abs(path);
32468
+ self2.flags = settings.flags ?? "r";
32469
+ self2.mode = settings.mode ?? 438;
32470
+ self2.fd = typeof settings.fd === "number" ? settings.fd : null;
32471
+ self2.start = settings.start;
32472
+ self2.end = settings.end;
32473
+ self2.bytesRead = 0;
32474
+ self2.pending = true;
32475
+ self2._delivered = false;
32476
+ self2.once("open", () => {
32477
+ self2.pending = false;
32478
+ });
32479
+ self2.once("end", () => {
32480
+ if (!self2.destroyed) self2.destroy();
32481
+ });
32482
+ if (self2.fd === null) self2.open();
32483
+ else defer(() => {
32484
+ self2.emit("open", self2.fd);
32485
+ self2.emit("ready");
32486
+ });
32487
+ }
32488
+ ReadStream.prototype = Object.create(import_stream_browserify5.default.Readable.prototype, {
32489
+ constructor: { value: ReadStream, writable: true, configurable: true }
32490
+ });
32491
+ ReadStream.prototype.open = function() {
32492
+ const self2 = this;
32493
+ defer(() => {
32494
+ self2.emit("open", 0);
32495
+ self2.emit("ready");
32496
+ });
32497
+ };
32498
+ ReadStream.prototype._read = function() {
32499
+ const self2 = this;
32500
+ if (self2._delivered) {
32501
+ self2.push(null);
32502
+ return;
32503
+ }
32504
+ self2._delivered = true;
32505
+ let whole;
32506
+ try {
32507
+ whole = Buffer2.from(volume.readFileSync(resolveLinks(volume, self2.path)));
32508
+ } catch (error) {
32509
+ self2.destroy(error);
32510
+ return;
32511
+ }
32512
+ const start = self2.start ?? 0;
32513
+ const end = self2.end === void 0 ? whole.length : Math.min(self2.end + 1, whole.length);
32514
+ const slice = whole.subarray(start, Math.max(start, end));
32515
+ self2.bytesRead = slice.length;
32516
+ if (slice.length) self2.push(slice);
32517
+ self2.push(null);
32518
+ };
32519
+ ReadStream.prototype.close = function(callback2) {
32520
+ const self2 = this;
32521
+ if (callback2) {
32522
+ if (self2.closed) defer(() => callback2(null));
32523
+ else self2.once("close", () => callback2(null));
32524
+ }
32525
+ if (!self2.destroyed) self2.destroy();
32526
+ };
32527
+ fs.WriteStream = WriteStream;
32528
+ fs.ReadStream = ReadStream;
32529
+ fs.FileWriteStream = WriteStream;
32530
+ fs.FileReadStream = ReadStream;
32531
+ class Dir {
32532
+ path;
32533
+ entries;
32534
+ closed = false;
32535
+ constructor(path) {
32536
+ this.path = path;
32537
+ this.entries = fs.readdirSync(path, { withFileTypes: true });
32538
+ }
32539
+ assertOpen() {
32540
+ if (this.closed) throw Object.assign(new Error("Directory handle was closed"), { code: "ERR_DIR_CLOSED" });
32541
+ }
32542
+ readSync() {
32543
+ this.assertOpen();
32544
+ return this.entries.shift() ?? null;
32545
+ }
32546
+ read(callback2) {
32547
+ if (callback2) {
32548
+ defer(() => {
32549
+ let entry;
32550
+ try {
32551
+ entry = this.readSync();
32552
+ } catch (error) {
32553
+ callback2(error, null);
32554
+ return;
32555
+ }
32556
+ callback2(null, entry);
32557
+ });
32558
+ return;
32559
+ }
32560
+ return Promise.resolve().then(() => this.readSync());
32561
+ }
32562
+ closeSync() {
32563
+ this.assertOpen();
32564
+ this.closed = true;
32565
+ }
32566
+ close(callback2) {
32567
+ if (callback2) {
32568
+ defer(() => {
32569
+ try {
32570
+ this.closeSync();
32571
+ } catch (error) {
32572
+ callback2(error);
32573
+ return;
32574
+ }
32575
+ callback2(null);
32576
+ });
32577
+ return;
32578
+ }
32579
+ return Promise.resolve().then(() => this.closeSync());
32580
+ }
32581
+ /* Iterating a `Dir` reads it to the end and then closes it, as in Node. */
32582
+ async *[Symbol.asyncIterator]() {
32583
+ try {
32584
+ for (let entry = this.readSync(); entry; entry = this.readSync()) yield entry;
32585
+ } finally {
32586
+ if (!this.closed) this.closeSync();
32587
+ }
32588
+ }
32589
+ *entriesSync() {
32590
+ try {
32591
+ for (let entry = this.readSync(); entry; entry = this.readSync()) yield entry;
32592
+ } finally {
32593
+ if (!this.closed) this.closeSync();
32594
+ }
32595
+ }
32596
+ }
32597
+ fs.Dir = Dir;
32598
+ fs.opendirSync = (path) => new Dir(abs(path));
32599
+ fs.opendir = (path, options, callback2) => {
32600
+ const done = typeof options === "function" ? options : callback2;
32601
+ if (typeof done !== "function") throw new TypeError("callback must be a function");
32602
+ defer(() => {
32603
+ let dir;
32604
+ try {
32605
+ dir = fs.opendirSync(path);
32606
+ } catch (error) {
32607
+ done(error);
32608
+ return;
32609
+ }
32610
+ done(null, dir);
32611
+ });
32612
+ };
32613
+ const runThenCall = (work, cb) => {
32614
+ defer(() => {
32615
+ let result;
32616
+ try {
32617
+ result = work();
32618
+ } catch (error) {
32619
+ cb(error);
32620
+ return;
32621
+ }
32622
+ cb(null, ...result);
32623
+ });
32624
+ };
32625
+ fs.read = (fd, ...rest) => {
32626
+ const cb = rest.pop();
32627
+ if (typeof cb !== "function") throw new TypeError("callback must be a function");
32628
+ let buffer;
32629
+ let offset2;
32630
+ let length;
32631
+ let position;
32632
+ if (ArrayBuffer.isView(rest[0])) {
32633
+ buffer = rest[0];
32634
+ if (rest[1] !== null && typeof rest[1] === "object") ({ offset: offset2, length, position } = rest[1]);
32635
+ else [offset2, length, position] = [rest[1], rest[2], rest[3]];
32636
+ } else {
32637
+ const options = rest[0] ?? {};
32638
+ buffer = options.buffer ?? Buffer2.alloc(16384);
32639
+ ({ offset: offset2, length, position } = options);
32640
+ }
32641
+ const start = offset2 ?? 0;
32642
+ runThenCall(() => [fs.readSync(fd, buffer, start, length ?? buffer.byteLength - start, position ?? null), buffer], cb);
32643
+ };
32644
+ fs.write = (fd, data2, ...rest) => {
32645
+ const cb = rest.pop();
32646
+ if (typeof cb !== "function") throw new TypeError("callback must be a function");
32647
+ runThenCall(() => [fs.writeSync(fd, data2, ...rest), data2], cb);
32648
+ };
30982
32649
  fs.exists = (path, cb) => {
30983
32650
  defer(() => cb(fs.existsSync(path)));
30984
32651
  };
@@ -30990,7 +32657,8 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
30990
32657
  /* The promise API hands back a FileHandle object rather than a numeric
30991
32658
  * descriptor, and callers use its methods instead of passing the number
30992
32659
  * to `fs.read`. */
30993
- open: async (path, flags = "r", mode) => makeFileHandle(fs, fs.openSync(path, flags, mode))
32660
+ open: async (path, flags = "r", mode) => makeFileHandle(fs, fs.openSync(path, flags, mode)),
32661
+ opendir: async (path) => fs.opendirSync(path)
30994
32662
  };
30995
32663
  return fs;
30996
32664
  }
@@ -30998,6 +32666,8 @@ function makeFileHandle(fs, fd) {
30998
32666
  return {
30999
32667
  fd,
31000
32668
  close: async () => fs.closeSync(fd),
32669
+ sync: async () => fs.fsyncSync(fd),
32670
+ datasync: async () => fs.fdatasyncSync(fd),
31001
32671
  stat: async () => fs.fstatSync(fd),
31002
32672
  truncate: async (length) => fs.ftruncateSync(fd, length),
31003
32673
  chmod: async (mode) => fs.fchmodSync(fd, mode),
@@ -31035,6 +32705,37 @@ function resolveLinks(volume, input) {
31035
32705
  }
31036
32706
  throw fsError("ELOOP", "realpath", input);
31037
32707
  }
32708
+ function createBufferBuiltin() {
32709
+ const MAX_LENGTH = typeof Buffer2.kMaxLength === "number" ? Buffer2.kMaxLength : 2 ** 32;
32710
+ const MAX_STRING_LENGTH = 2 ** 29 - 24;
32711
+ const textDecoder = typeof TextDecoder === "function" ? new TextDecoder("utf-8", { fatal: true }) : void 0;
32712
+ return {
32713
+ Buffer: Buffer2,
32714
+ SlowBuffer: Buffer2,
32715
+ INSPECT_MAX_BYTES: 50,
32716
+ kMaxLength: MAX_LENGTH,
32717
+ kStringMaxLength: MAX_STRING_LENGTH,
32718
+ constants: { MAX_LENGTH, MAX_STRING_LENGTH },
32719
+ ...typeof Blob === "function" ? { Blob } : {},
32720
+ ...typeof globalThis.File === "function" ? { File: globalThis.File } : {},
32721
+ atob: (data2) => globalThis.atob(String(data2)),
32722
+ btoa: (data2) => globalThis.btoa(String(data2)),
32723
+ isUtf8: (input) => {
32724
+ if (!textDecoder) return true;
32725
+ try {
32726
+ textDecoder.decode(input);
32727
+ return true;
32728
+ } catch {
32729
+ return false;
32730
+ }
32731
+ },
32732
+ isAscii: (input) => {
32733
+ const bytes2 = input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
32734
+ for (const byte of bytes2) if (byte > 127) return false;
32735
+ return true;
32736
+ }
32737
+ };
32738
+ }
31038
32739
  function requiredFd(fds, fd) {
31039
32740
  const file = fds.get(fd);
31040
32741
  if (!file) throw fsError("EBADF", "fd", String(fd));
@@ -31044,8 +32745,8 @@ function fsError(code, syscall, path) {
31044
32745
  return Object.assign(new Error(`${code}: ${syscall}, '${path}'`), { code, syscall, path });
31045
32746
  }
31046
32747
  function makeOutputStream(write, fd, isTTY = false) {
31047
- const stream = new import_stream_browserify4.default.Writable({ write(chunk, _encoding, done) {
31048
- write(Buffer2.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk));
32748
+ const stream = new import_stream_browserify5.default.Writable({ decodeStrings: false, write(chunk, _encoding, done) {
32749
+ write(Buffer2.isBuffer(chunk) ? new Uint8Array(chunk) : String(chunk));
31049
32750
  done();
31050
32751
  } });
31051
32752
  return Object.assign(stream, { fd, isTTY, columns: 80, rows: 24 });
@@ -31311,6 +33012,12 @@ function createTrackedTimers(onError = (error) => {
31311
33012
  }
31312
33013
  afterCallback();
31313
33014
  };
33015
+ const hostSetTimeout = globalThis.setTimeout.bind(globalThis);
33016
+ const hostClearTimeout = globalThis.clearTimeout.bind(globalThis);
33017
+ const hostSetInterval = globalThis.setInterval.bind(globalThis);
33018
+ const hostClearInterval = globalThis.clearInterval.bind(globalThis);
33019
+ const hostSetImmediate = typeof globalThis.setImmediate === "function" ? globalThis.setImmediate.bind(globalThis) : void 0;
33020
+ const hostClearImmediate = typeof globalThis.clearImmediate === "function" ? globalThis.clearImmediate.bind(globalThis) : hostClearTimeout;
31314
33021
  let scheduled = 0;
31315
33022
  const live = /* @__PURE__ */ new Set();
31316
33023
  const unrefed = /* @__PURE__ */ new Set();
@@ -31350,9 +33057,10 @@ function createTrackedTimers(onError = (error) => {
31350
33057
  live.delete(handle);
31351
33058
  unrefed.delete(handle);
31352
33059
  };
31353
- const setTimeoutTracked = (fn, delay, ...args) => {
33060
+ const setTimeoutTracked = (callback, delay, ...args) => {
33061
+ const fn = bindToCurrent(callback);
31354
33062
  let handle;
31355
- const native = setTimeout(
33063
+ const native = hostSetTimeout(
31356
33064
  (...inner) => {
31357
33065
  complete(handle);
31358
33066
  run2(fn, inner);
@@ -31363,10 +33071,13 @@ function createTrackedTimers(onError = (error) => {
31363
33071
  handle = track(native);
31364
33072
  return handle;
31365
33073
  };
31366
- const setIntervalTracked = (fn, delay, ...args) => track(setInterval((...inner) => run2(fn, inner), delay, ...args));
31367
- const hostSetImmediate = globalThis.setImmediate;
31368
- const setImmediateTracked = (fn, ...args) => {
31369
- if (!hostSetImmediate) return setTimeoutTracked(fn, 0, ...args);
33074
+ const setIntervalTracked = (callback, delay, ...args) => {
33075
+ const fn = bindToCurrent(callback);
33076
+ return track(hostSetInterval((...inner) => run2(fn, inner), delay, ...args));
33077
+ };
33078
+ const setImmediateTracked = (callback, ...args) => {
33079
+ if (!hostSetImmediate) return setTimeoutTracked(callback, 0, ...args);
33080
+ const fn = bindToCurrent(callback);
31370
33081
  let handle;
31371
33082
  const native = hostSetImmediate((...inner) => {
31372
33083
  complete(handle);
@@ -31395,15 +33106,15 @@ function createTrackedTimers(onError = (error) => {
31395
33106
  if (!state) continue;
31396
33107
  state.active = false;
31397
33108
  try {
31398
- clearTimeout(state.native);
33109
+ hostClearTimeout(state.native);
31399
33110
  } catch {
31400
33111
  }
31401
33112
  try {
31402
- clearInterval(state.native);
33113
+ hostClearInterval(state.native);
31403
33114
  } catch {
31404
33115
  }
31405
33116
  try {
31406
- (globalThis.clearImmediate ?? clearTimeout)(state.native);
33117
+ hostClearImmediate(state.native);
31407
33118
  } catch {
31408
33119
  }
31409
33120
  }
@@ -31415,9 +33126,9 @@ function createTrackedTimers(onError = (error) => {
31415
33126
  setTimeout: setTimeoutTracked,
31416
33127
  setInterval: setIntervalTracked,
31417
33128
  setImmediate: setImmediateTracked,
31418
- clearTimeout: (handle) => clear(handle, clearTimeout),
31419
- clearInterval: (handle) => clear(handle, clearInterval),
31420
- clearImmediate: (handle) => clear(handle, globalThis.clearImmediate ?? clearTimeout)
33129
+ clearTimeout: (handle) => clear(handle, hostClearTimeout),
33130
+ clearInterval: (handle) => clear(handle, hostClearInterval),
33131
+ clearImmediate: (handle) => clear(handle, hostClearImmediate)
31421
33132
  },
31422
33133
  pending: () => live.size,
31423
33134
  pendingUnrefed: () => unrefed.size,
@@ -31432,66 +33143,6 @@ function createTimerPromises(timers) {
31432
33143
  };
31433
33144
  }
31434
33145
  function createAsyncHooksModule() {
31435
- class AsyncResource {
31436
- constructor(type, _options) {
31437
- this.type = type;
31438
- }
31439
- type;
31440
- runInAsyncScope(fn, thisArg, ...args) {
31441
- return fn.apply(thisArg, args);
31442
- }
31443
- bind(fn, thisArg) {
31444
- return ((...args) => this.runInAsyncScope(fn, thisArg, ...args));
31445
- }
31446
- emitDestroy() {
31447
- return this;
31448
- }
31449
- asyncId() {
31450
- return 1;
31451
- }
31452
- triggerAsyncId() {
31453
- return 0;
31454
- }
31455
- static bind(fn, type = "bound-anonymous-fn", thisArg) {
31456
- return new AsyncResource(type).bind(fn, thisArg);
31457
- }
31458
- }
31459
- class AsyncLocalStorage {
31460
- value;
31461
- disable() {
31462
- this.value = void 0;
31463
- }
31464
- getStore() {
31465
- return this.value;
31466
- }
31467
- enterWith(store) {
31468
- this.value = store;
31469
- }
31470
- run(store, callback, ...args) {
31471
- const previous = this.value;
31472
- this.value = store;
31473
- try {
31474
- return callback(...args);
31475
- } finally {
31476
- this.value = previous;
31477
- }
31478
- }
31479
- exit(callback, ...args) {
31480
- const previous = this.value;
31481
- this.value = void 0;
31482
- try {
31483
- return callback(...args);
31484
- } finally {
31485
- this.value = previous;
31486
- }
31487
- }
31488
- static bind(fn) {
31489
- return fn;
31490
- }
31491
- static snapshot() {
31492
- return (fn, ...args) => fn(...args);
31493
- }
31494
- }
31495
33146
  return {
31496
33147
  AsyncResource,
31497
33148
  AsyncLocalStorage,
@@ -31509,10 +33160,10 @@ function createStreamPromises() {
31509
33160
  return {
31510
33161
  pipeline: (...streams) => new Promise((resolve2, reject) => {
31511
33162
  const callback = (error) => error ? reject(error) : resolve2();
31512
- import_stream_browserify4.default.pipeline(...streams, callback);
33163
+ import_stream_browserify5.default.pipeline(...streams, callback);
31513
33164
  }),
31514
33165
  finished: (stream) => new Promise((resolve2, reject) => {
31515
- import_stream_browserify4.default.finished(stream, (error) => error ? reject(error) : resolve2());
33166
+ import_stream_browserify5.default.finished(stream, (error) => error ? reject(error) : resolve2());
31516
33167
  })
31517
33168
  };
31518
33169
  }
@@ -31526,6 +33177,7 @@ function createUnsupportedModule(name, supported = {}) {
31526
33177
  const module = new Proxy(target, {
31527
33178
  get(object, key) {
31528
33179
  if (key === "default") return module;
33180
+ if (key === "__esModule" || typeof key === "symbol") return object[key];
31529
33181
  return key in object ? object[key] : unsupported;
31530
33182
  }
31531
33183
  });
@@ -31548,10 +33200,20 @@ function createNetModule() {
31548
33200
  const count = groups.reduce((total, half) => total + half.length, 0);
31549
33201
  return halves.length === 2 ? count <= 7 : count === 8;
31550
33202
  };
33203
+ let autoSelectFamily = true;
33204
+ let autoSelectFamilyAttemptTimeout = 250;
31551
33205
  return createUnsupportedModule("net", {
31552
33206
  isIPv4,
31553
33207
  isIPv6,
31554
- isIP: (value) => isIPv4(value) ? 4 : isIPv6(value) ? 6 : 0
33208
+ isIP: (value) => isIPv4(value) ? 4 : isIPv6(value) ? 6 : 0,
33209
+ getDefaultAutoSelectFamily: () => autoSelectFamily,
33210
+ setDefaultAutoSelectFamily: (value) => {
33211
+ autoSelectFamily = Boolean(value);
33212
+ },
33213
+ getDefaultAutoSelectFamilyAttemptTimeout: () => autoSelectFamilyAttemptTimeout,
33214
+ setDefaultAutoSelectFamilyAttemptTimeout: (value) => {
33215
+ autoSelectFamilyAttemptTimeout = Math.max(10, Number(value) || 250);
33216
+ }
31555
33217
  });
31556
33218
  }
31557
33219
  function parseTestSettings(raw) {
@@ -31591,7 +33253,7 @@ function formatUncaught(error) {
31591
33253
  Node.js v22.12.0
31592
33254
  `;
31593
33255
  }
31594
- var stubNames = ["cluster", "dgram", "diagnostics_channel", "domain", "http2", "inspector", "net", "tls", "v8", "vm", "worker_threads"];
33256
+ var stubNames = ["cluster", "dgram", "domain", "http2", "inspector", "net", "tls", "v8", "vm", "worker_threads"];
31595
33257
  var builtinNames = [
31596
33258
  "assert",
31597
33259
  "assert/strict",
@@ -31604,6 +33266,7 @@ var builtinNames = [
31604
33266
  "events",
31605
33267
  "fs",
31606
33268
  "fs/promises",
33269
+ "diagnostics_channel",
31607
33270
  "dns",
31608
33271
  "dns/promises",
31609
33272
  "http",
@@ -31619,6 +33282,7 @@ var builtinNames = [
31619
33282
  "readline",
31620
33283
  "readline/promises",
31621
33284
  "stream",
33285
+ "stream/web",
31622
33286
  "stream/promises",
31623
33287
  "string_decoder",
31624
33288
  "timers",
@@ -31767,10 +33431,10 @@ function spawnSyncOverChannel(channel, request) {
31767
33431
 
31768
33432
  // src/node/global-process.ts
31769
33433
  var import_browser2 = __toESM(require_browser2());
31770
- var installed = false;
33434
+ var installed2 = false;
31771
33435
  function ensureProcessGlobal() {
31772
- if (installed) return;
31773
- installed = true;
33436
+ if (installed2) return;
33437
+ installed2 = true;
31774
33438
  if (typeof globalThis.process !== "undefined") return;
31775
33439
  Object.defineProperty(globalThis, "process", {
31776
33440
  value: import_browser2.default,
@@ -31816,6 +33480,7 @@ async function main() {
31816
33480
  port.postMessage({ type: "sandboxedjs:ready" });
31817
33481
  }
31818
33482
  async function run(port, start) {
33483
+ installPromiseContext();
31819
33484
  const channel = new SyncChannelClient(start.buffers, () => port.postMessage({ type: "wake" }));
31820
33485
  const volume = new RemoteVolume(channel);
31821
33486
  const router = new VirtualHttpRouter();
@@ -31846,6 +33511,7 @@ async function run(port, start) {
31846
33511
  /* Asynchronous children are the host's business: it owns the process table
31847
33512
  * and the PATH. Both forms end up in the same place, one blocking. */
31848
33513
  spawnChild: (config) => hostChildProcess(port, config),
33514
+ ipc: hostIpcOverPort(port),
31849
33515
  syncSpawn: (request) => spawnSyncOverChannel(channel, request),
31850
33516
  ...start.stdinPath ? { stdinPath: start.stdinPath } : {},
31851
33517
  ...start.interactiveStdin ? { interactiveStdin: true } : {},
@@ -31879,7 +33545,7 @@ async function run(port, start) {
31879
33545
  };
31880
33546
  port.onMessage((message) => {
31881
33547
  if (message?.type === "wake") return;
31882
- if (message?.type === "stdin") core.writeStdin(String(message.data));
33548
+ if (message?.type === "stdin") core.writeStdin(message.data instanceof Uint8Array ? message.data : String(message.data));
31883
33549
  if (message?.type === "stdin-end") core.endStdin();
31884
33550
  if (message?.type === "kill") {
31885
33551
  core.cancelTimers();
@@ -31998,6 +33664,12 @@ function hostChildProcess(port, config) {
31998
33664
  endStdin() {
31999
33665
  port.postMessage({ type: "child-stdin-end", id });
32000
33666
  },
33667
+ writeFd(fd, data2) {
33668
+ port.postMessage({ type: "child-fd", id, fd, data: data2 });
33669
+ },
33670
+ endFd(fd) {
33671
+ port.postMessage({ type: "child-fd-end", id, fd });
33672
+ },
32001
33673
  kill(signal = "SIGTERM") {
32002
33674
  port.postMessage({ type: "child-kill", id, signal });
32003
33675
  }
@@ -32012,6 +33684,32 @@ function hostChildProcess(port, config) {
32012
33684
  });
32013
33685
  return handle;
32014
33686
  }
33687
+ function hostIpcOverPort(port) {
33688
+ const ends = /* @__PURE__ */ new Map();
33689
+ port.onMessage((message) => {
33690
+ if (message?.type !== "ipc-message" && message?.type !== "ipc-disconnect") return;
33691
+ const end = ends.get(`${message.side}:${message.id}`);
33692
+ if (!end) return;
33693
+ if (message.type === "ipc-message") end.message(message.value);
33694
+ else {
33695
+ ends.delete(`${message.side}:${message.id}`);
33696
+ end.disconnect();
33697
+ }
33698
+ });
33699
+ return {
33700
+ attach(id, side, onMessage, onDisconnect) {
33701
+ ends.set(`${side}:${id}`, { message: onMessage, disconnect: onDisconnect });
33702
+ port.postMessage({ type: "ipc-attach", id, side });
33703
+ return {
33704
+ send: (value) => port.postMessage({ type: "ipc-send", id, side, value: value === void 0 ? void 0 : JSON.parse(JSON.stringify(value)) }),
33705
+ disconnect: () => {
33706
+ ends.delete(`${side}:${id}`);
33707
+ port.postMessage({ type: "ipc-close", id, side });
33708
+ }
33709
+ };
33710
+ }
33711
+ };
33712
+ }
32015
33713
  function formatError(error) {
32016
33714
  if (error instanceof Error) return `${error.stack ?? `${error.name}: ${error.message}`}
32017
33715
  `;