sandboxedjs 0.1.81 → 0.1.83

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.
package/dist/index.js CHANGED
@@ -20221,7 +20221,7 @@ var wheels_default = {
20221
20221
 
20222
20222
  // package.json
20223
20223
  var package_default = {
20224
- version: "0.1.81"};
20224
+ version: "0.1.83"};
20225
20225
 
20226
20226
  // src/python/config.ts
20227
20227
  function runtimeModuleUrl() {
@@ -25199,7 +25199,21 @@ function makeNpmAlias(name, path) {
25199
25199
  exec: ["exec", ...rest],
25200
25200
  list: ["ls", ...rest],
25201
25201
  why: ["ls", ...rest],
25202
- dlx: ["exec", ...rest]
25202
+ dlx: ["exec", ...rest],
25203
+ /* Verbs of the package manager itself, never script names. Tools ask
25204
+ * them in passing — Next resolves its download registry with
25205
+ * `yarn config get registry` whenever yarn is on PATH — and running
25206
+ * them as scripts failed with "could not read package.json". */
25207
+ config: ["config", ...rest],
25208
+ cache: ["cache", ...rest],
25209
+ root: ["root", ...rest],
25210
+ prefix: ["prefix", ...rest],
25211
+ ping: ["ping", ...rest],
25212
+ whoami: ["whoami", ...rest],
25213
+ init: ["init", ...rest],
25214
+ create: ["create", ...rest],
25215
+ uninstall: ["uninstall", ...rest],
25216
+ rm: ["uninstall", ...rest]
25203
25217
  };
25204
25218
  if (subcommand === void 0) return npm.run({ ...ctx, args: ["install"], argv: [name, "install"] });
25205
25219
  if (subcommand === "-v" || subcommand === "--version") {
@@ -25811,6 +25825,49 @@ var CommonJsEngine = class {
25811
25825
  this.globals = { ...options.globals };
25812
25826
  this.aliases = { ...options.aliases };
25813
25827
  this.overrides = { ...options.overrides };
25828
+ const engine = this;
25829
+ this.moduleApi = function Module(id = "", parent = null) {
25830
+ Object.assign(this, { id, filename: id, exports: {}, loaded: false, parent, children: [] });
25831
+ };
25832
+ Object.assign(this.moduleApi, this.builtins.module);
25833
+ this.moduleApi.Module = this.moduleApi;
25834
+ this.moduleApi._extensions = {
25835
+ ".js": (module, filename) => this.evaluate(module, this.readText(filename)),
25836
+ ".json": (module, filename) => {
25837
+ module.exports = JSON.parse(this.readText(filename));
25838
+ },
25839
+ ".node": (_module, filename) => {
25840
+ throw dlopenFailed(filename);
25841
+ }
25842
+ };
25843
+ this.moduleApi._cache = new Proxy(/* @__PURE__ */ Object.create(null), {
25844
+ get: (_target, key) => typeof key === "string" ? this.cache.get(key) : void 0,
25845
+ set: (_target, key, value) => {
25846
+ this.cache.set(String(key), value);
25847
+ return true;
25848
+ },
25849
+ deleteProperty: (_target, key) => this.cache.delete(String(key)),
25850
+ ownKeys: () => [...this.cache.keys()],
25851
+ getOwnPropertyDescriptor: (_target, key) => this.cache.has(String(key)) ? { enumerable: true, configurable: true, writable: true, value: this.cache.get(String(key)) } : void 0
25852
+ });
25853
+ this.moduleApi._resolveFilename = (request, parent) => this.resolve(request, parent?.filename || join(this.cwd, "__entry__.js"));
25854
+ this.moduleApi.prototype.require = function(request) {
25855
+ const filename = engine.moduleApi._resolveFilename(request, this);
25856
+ const builtin = engine.builtin(filename, this);
25857
+ if (builtin.found) return builtin.value;
25858
+ const target = engine.load(filename, this, false);
25859
+ if (target.pending) throw requireOfAsyncModule(request);
25860
+ return target.exports;
25861
+ };
25862
+ this.moduleApi.prototype._compile = function(source, filename) {
25863
+ this.filename = filename;
25864
+ engine.evaluate(this, source);
25865
+ };
25866
+ this.moduleApi.createRequire = (filename) => {
25867
+ const path = String(filename).startsWith("file:") ? pathFromFileUrl(String(filename)) : String(filename);
25868
+ if (!path.startsWith("/")) throw new TypeError("createRequire requires an absolute path or file URL");
25869
+ return this.makeRequire(Object.assign(new this.moduleApi(path), { filename: path }));
25870
+ };
25814
25871
  }
25815
25872
  volume;
25816
25873
  cache = /* @__PURE__ */ new Map();
@@ -25823,6 +25880,7 @@ var CommonJsEngine = class {
25823
25880
  /** `package.json` per directory; resolution reads them constantly. */
25824
25881
  manifests = /* @__PURE__ */ new Map();
25825
25882
  evaluationDepth = 0;
25883
+ moduleApi;
25826
25884
  /**
25827
25885
  * Is a module body running synchronously right now?
25828
25886
  *
@@ -25859,7 +25917,7 @@ var CommonJsEngine = class {
25859
25917
  specifier = pathFromFileUrl(specifier);
25860
25918
  }
25861
25919
  const builtin = this.builtin(specifier);
25862
- if (builtin.found) return specifier.replace(/^node:/, "");
25920
+ if (builtin.found) return specifier;
25863
25921
  if (specifier.startsWith("#")) {
25864
25922
  const found = this.resolveImports(specifier, importer, kind);
25865
25923
  if (found) return found;
@@ -25892,17 +25950,14 @@ var CommonJsEngine = class {
25892
25950
  parent,
25893
25951
  children: []
25894
25952
  };
25953
+ Object.setPrototypeOf(module, this.moduleApi.prototype);
25895
25954
  this.cache.set(filename, module);
25896
25955
  parent?.children.push(module);
25897
25956
  if (isMain) this.main = module;
25898
25957
  try {
25899
- if (filename.endsWith(".node")) {
25900
- throw dlopenFailed(filename);
25901
- } else if (filename.endsWith(".json")) {
25902
- module.exports = JSON.parse(this.readText(filename));
25903
- } else {
25904
- this.evaluate(module, this.readText(filename));
25905
- }
25958
+ const extension = extname(filename);
25959
+ const loader = this.moduleApi._extensions[extension] ?? this.moduleApi._extensions[".js"];
25960
+ loader(module, filename);
25906
25961
  module.loaded = true;
25907
25962
  return module;
25908
25963
  } catch (error) {
@@ -25955,15 +26010,12 @@ ${code}
25955
26010
  /** The `require` a module sees, complete with `resolve`, `cache` and `main`. */
25956
26011
  makeRequire(module) {
25957
26012
  const localRequire = ((specifier) => {
25958
- const builtin = this.builtin(specifier, module);
25959
- if (builtin.found) return builtin.value;
25960
- const target = this.load(this.resolve(specifier, module.filename, "require"), module, false);
25961
- if (target.pending) throw requireOfAsyncModule(specifier);
25962
- return target.exports;
26013
+ return this.moduleApi.prototype.require.call(module, specifier);
25963
26014
  });
25964
- localRequire.resolve = (specifier) => this.resolve(specifier, module.filename, "require");
26015
+ localRequire.resolve = (specifier) => this.moduleApi._resolveFilename(specifier, module);
25965
26016
  Object.defineProperty(localRequire, "main", { get: () => this.main });
25966
- localRequire.cache = Object.fromEntries(this.cache);
26017
+ localRequire.cache = this.moduleApi._cache;
26018
+ localRequire.extensions = this.moduleApi._extensions;
25967
26019
  return localRequire;
25968
26020
  }
25969
26021
  /**
@@ -26138,12 +26190,7 @@ ${code}
26138
26190
  if (prefixOnly || !Object.prototype.hasOwnProperty.call(this.builtins, name)) {
26139
26191
  return Object.prototype.hasOwnProperty.call(this.overrides, specifier) ? { found: true, value: this.overrides[specifier] } : { found: false, value: void 0 };
26140
26192
  }
26141
- if (name === "module" && importer) {
26142
- return {
26143
- found: true,
26144
- value: { ...this.builtins.module, createRequire: () => this.makeRequire(importer) }
26145
- };
26146
- }
26193
+ if (name === "module") return { found: true, value: this.moduleApi };
26147
26194
  return { found: true, value: this.builtins[name] };
26148
26195
  }
26149
26196
  exists(path) {
@@ -26251,6 +26298,108 @@ function splitSpecifier(specifier) {
26251
26298
  return { name: parts.slice(0, size).join("/"), subpath: parts.slice(size).join("/") };
26252
26299
  }
26253
26300
 
26301
+ // src/node/diagnostics-channel.ts
26302
+ function createDiagnosticsChannel() {
26303
+ const channels2 = /* @__PURE__ */ new Map();
26304
+ class Channel {
26305
+ constructor(name) {
26306
+ this.name = name;
26307
+ }
26308
+ name;
26309
+ listeners = /* @__PURE__ */ new Set();
26310
+ get hasSubscribers() {
26311
+ return this.listeners.size > 0;
26312
+ }
26313
+ subscribe(fn) {
26314
+ if (typeof fn !== "function") throw new TypeError("subscriber must be a function");
26315
+ this.listeners.add(fn);
26316
+ }
26317
+ unsubscribe(fn) {
26318
+ return this.listeners.delete(fn);
26319
+ }
26320
+ publish(message) {
26321
+ for (const fn of [...this.listeners]) {
26322
+ try {
26323
+ fn(message, this.name);
26324
+ } catch (error) {
26325
+ queueMicrotask(() => {
26326
+ throw error;
26327
+ });
26328
+ }
26329
+ }
26330
+ }
26331
+ }
26332
+ const channel = (name) => {
26333
+ if (typeof name !== "string" && typeof name !== "symbol") throw new TypeError("channel name must be a string or symbol");
26334
+ let result = channels2.get(name);
26335
+ if (!result) {
26336
+ result = new Channel(name);
26337
+ channels2.set(name, result);
26338
+ }
26339
+ return result;
26340
+ };
26341
+ return {
26342
+ Channel,
26343
+ channel,
26344
+ hasSubscribers: (name) => channels2.get(name)?.hasSubscribers ?? false,
26345
+ subscribe: (name, fn) => channel(name).subscribe(fn),
26346
+ unsubscribe: (name, fn) => channels2.get(name)?.unsubscribe(fn) ?? false
26347
+ };
26348
+ }
26349
+
26350
+ // src/node/ipc-channel.ts
26351
+ var IPC_CHANNEL_ENV = "SANDBOXEDJS_IPC_CHANNEL";
26352
+ var channels = /* @__PURE__ */ new Map();
26353
+ var closedChannels = /* @__PURE__ */ new Set();
26354
+ function newIpcChannelId() {
26355
+ const random = typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID() : Math.random().toString(36).slice(2);
26356
+ return `ipc-${random}`;
26357
+ }
26358
+ var hostIpcTransport = {
26359
+ attach(id, side, onMessage, onDisconnect) {
26360
+ let channel = channels.get(id);
26361
+ if (!channel && !closedChannels.has(id)) {
26362
+ channel = { parent: { backlog: [] }, child: { backlog: [] }, closed: false };
26363
+ channels.set(id, channel);
26364
+ }
26365
+ if (!channel || channel.closed) {
26366
+ queueMicrotask(onDisconnect);
26367
+ return { send: () => {
26368
+ }, disconnect: () => {
26369
+ } };
26370
+ }
26371
+ const own = channel[side];
26372
+ const other = channel[side === "parent" ? "child" : "parent"];
26373
+ own.deliver = onMessage;
26374
+ own.disconnected = onDisconnect;
26375
+ for (const message of own.backlog.splice(0)) queueMicrotask(() => onMessage(message));
26376
+ return {
26377
+ send(message) {
26378
+ if (channel.closed) return;
26379
+ const copy = message === void 0 ? void 0 : JSON.parse(JSON.stringify(message));
26380
+ if (other.deliver) {
26381
+ const deliver = other.deliver;
26382
+ setTimeout(() => {
26383
+ if (!channel.closed) deliver(copy);
26384
+ }, 0);
26385
+ } else {
26386
+ other.backlog.push(copy);
26387
+ }
26388
+ },
26389
+ disconnect() {
26390
+ if (channel.closed) return;
26391
+ channel.closed = true;
26392
+ channels.delete(id);
26393
+ closedChannels.add(id);
26394
+ for (const end of [channel.parent, channel.child]) {
26395
+ const notify = end.disconnected;
26396
+ if (notify) setTimeout(notify, 0);
26397
+ }
26398
+ }
26399
+ };
26400
+ }
26401
+ };
26402
+
26254
26403
  // src/node/readable-from.ts
26255
26404
  function createReadableFrom(Readable) {
26256
26405
  return function from(source, options = {}) {
@@ -26300,6 +26449,132 @@ function installReadableFrom(streamModule5) {
26300
26449
  streamModule5.Readable.from = createReadableFrom(streamModule5.Readable);
26301
26450
  }
26302
26451
 
26452
+ // src/node/parse-args.ts
26453
+ function argError(code, message) {
26454
+ return Object.assign(new TypeError(message), { code });
26455
+ }
26456
+ function parseArgs2(config2 = {}) {
26457
+ const args = config2.args ?? globalThis.process?.argv?.slice(2) ?? [];
26458
+ const options = config2.options ?? {};
26459
+ const strict = config2.strict ?? true;
26460
+ const allowPositionals = config2.allowPositionals ?? !strict;
26461
+ const allowNegative = config2.allowNegative ?? false;
26462
+ const byShort = /* @__PURE__ */ new Map();
26463
+ for (const [name, option] of Object.entries(options)) {
26464
+ if (option.type !== "string" && option.type !== "boolean") {
26465
+ throw argError("ERR_INVALID_ARG_VALUE", `The property 'options.${name}.type' must be one of: 'string', 'boolean'`);
26466
+ }
26467
+ if (option.short !== void 0) {
26468
+ if (option.short.length !== 1) {
26469
+ throw argError("ERR_INVALID_ARG_VALUE", `The property 'options.${name}.short' must be a single character`);
26470
+ }
26471
+ byShort.set(option.short, name);
26472
+ }
26473
+ }
26474
+ const tokens = [];
26475
+ const takesValue = (name) => options[name]?.type === "string";
26476
+ for (let index = 0; index < args.length; index++) {
26477
+ const arg = args[index];
26478
+ if (arg === "--") {
26479
+ tokens.push({ kind: "option-terminator", index });
26480
+ for (let rest = index + 1; rest < args.length; rest++) tokens.push({ kind: "positional", index: rest, value: args[rest] });
26481
+ break;
26482
+ }
26483
+ if (arg.startsWith("--") && arg.length > 2) {
26484
+ const equals = arg.indexOf("=");
26485
+ if (equals !== -1) {
26486
+ tokens.push({ kind: "option", name: arg.slice(2, equals), rawName: arg.slice(0, equals), index, value: arg.slice(equals + 1), inlineValue: true });
26487
+ continue;
26488
+ }
26489
+ const name = arg.slice(2);
26490
+ if (takesValue(name) && index + 1 < args.length) {
26491
+ tokens.push({ kind: "option", name, rawName: arg, index, value: args[index + 1], inlineValue: false });
26492
+ index++;
26493
+ } else {
26494
+ tokens.push({ kind: "option", name, rawName: arg, index, value: void 0, inlineValue: void 0 });
26495
+ }
26496
+ continue;
26497
+ }
26498
+ if (arg.startsWith("-") && arg.length > 1) {
26499
+ for (let at = 1; at < arg.length; at++) {
26500
+ const short = arg[at];
26501
+ const name = byShort.get(short) ?? short;
26502
+ if (takesValue(name)) {
26503
+ if (at + 1 < arg.length) {
26504
+ tokens.push({ kind: "option", name, rawName: `-${short}`, index, value: arg.slice(at + 1), inlineValue: true });
26505
+ } else if (index + 1 < args.length) {
26506
+ tokens.push({ kind: "option", name, rawName: `-${short}`, index, value: args[index + 1], inlineValue: false });
26507
+ index++;
26508
+ } else {
26509
+ tokens.push({ kind: "option", name, rawName: `-${short}`, index, value: void 0, inlineValue: void 0 });
26510
+ }
26511
+ break;
26512
+ }
26513
+ tokens.push({ kind: "option", name, rawName: `-${short}`, index, value: void 0, inlineValue: void 0 });
26514
+ }
26515
+ continue;
26516
+ }
26517
+ tokens.push({ kind: "positional", index, value: arg });
26518
+ }
26519
+ const values = /* @__PURE__ */ Object.create(null);
26520
+ const positionals = [];
26521
+ const store = (name, value) => {
26522
+ if (options[name]?.multiple) {
26523
+ const list = values[name] ?? [];
26524
+ list.push(value);
26525
+ values[name] = list;
26526
+ } else {
26527
+ values[name] = value;
26528
+ }
26529
+ };
26530
+ for (const token of tokens) {
26531
+ if (token.kind === "option-terminator") continue;
26532
+ if (token.kind === "positional") {
26533
+ if (!allowPositionals) {
26534
+ throw argError("ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL", `Unexpected argument '${token.value}'. This command does not take positional arguments`);
26535
+ }
26536
+ positionals.push(token.value);
26537
+ continue;
26538
+ }
26539
+ let name = token.name;
26540
+ let negated = false;
26541
+ if (allowNegative && name.startsWith("no-") && token.rawName.startsWith("--") && options[name.slice(3)]?.type === "boolean") {
26542
+ name = name.slice(3);
26543
+ negated = true;
26544
+ }
26545
+ const option = options[name];
26546
+ if (!option) {
26547
+ if (strict) {
26548
+ throw argError(
26549
+ "ERR_PARSE_ARGS_UNKNOWN_OPTION",
26550
+ `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)}'` : ""}`
26551
+ );
26552
+ }
26553
+ store(name, token.value ?? true);
26554
+ continue;
26555
+ }
26556
+ if (option.type === "string") {
26557
+ if (token.value === void 0) {
26558
+ if (strict) throw argError("ERR_PARSE_ARGS_INVALID_OPTION_VALUE", `Option '${token.rawName} <value>' argument missing`);
26559
+ store(name, true);
26560
+ continue;
26561
+ }
26562
+ store(name, token.value);
26563
+ } else {
26564
+ if (token.inlineValue && strict) {
26565
+ throw argError("ERR_PARSE_ARGS_INVALID_OPTION_VALUE", `Option '${token.rawName}' does not take an argument`);
26566
+ }
26567
+ store(name, !negated);
26568
+ }
26569
+ }
26570
+ for (const [name, option] of Object.entries(options)) {
26571
+ if (option.default !== void 0 && values[name] === void 0) {
26572
+ values[name] = Array.isArray(option.default) ? option.default.slice() : option.default;
26573
+ }
26574
+ }
26575
+ return config2.tokens ? { values, positionals, tokens } : { values, positionals };
26576
+ }
26577
+
26303
26578
  // src/node/util-module.ts
26304
26579
  var customInspect = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
26305
26580
  var promisifyCustom = /* @__PURE__ */ Symbol.for("nodejs.util.promisify.custom");
@@ -26328,8 +26603,9 @@ function render(value, depth, seen, options) {
26328
26603
  if (value === null) return "null";
26329
26604
  const object = value;
26330
26605
  const custom = object[customInspect];
26331
- if (typeof custom === "function") {
26332
- return String(custom.call(object, depth, options));
26606
+ if (options.customInspect !== false && typeof custom === "function") {
26607
+ const result = custom.call(object, depth, options, inspect);
26608
+ if (result !== object) return typeof result === "string" ? result : render(result, depth, seen, options);
26333
26609
  }
26334
26610
  if (seen.has(object)) return "[Circular *1]";
26335
26611
  if (depth < 0) return Array.isArray(object) ? "[Array]" : "[Object]";
@@ -26664,6 +26940,7 @@ var legacy = {
26664
26940
  inspect.custom = customInspect;
26665
26941
  var utilModule = {
26666
26942
  parseEnv,
26943
+ parseArgs: parseArgs2,
26667
26944
  format,
26668
26945
  formatWithOptions,
26669
26946
  inspect,
@@ -28430,20 +28707,10 @@ function concat6(parts) {
28430
28707
  return joined;
28431
28708
  }
28432
28709
  var ChildProcess = class extends EventEmitter4 {
28433
- stdout = new streamModule4.PassThrough();
28434
- stderr = new streamModule4.PassThrough();
28435
- stdin;
28436
- stdio;
28437
- pid;
28438
- exitCode = null;
28439
- signalCode = null;
28440
- killed = false;
28441
- spawnfile;
28442
- spawnargs;
28443
- handle;
28444
- settled = false;
28445
- constructor(handle, file3, args) {
28710
+ constructor(handle, file3, args, referenceChanged = () => {
28711
+ }) {
28446
28712
  super();
28713
+ this.referenceChanged = referenceChanged;
28447
28714
  this.handle = handle;
28448
28715
  this.pid = handle.pid;
28449
28716
  this.spawnfile = file3;
@@ -28468,31 +28735,90 @@ var ChildProcess = class extends EventEmitter4 {
28468
28735
  handle.on("stdout", (text2) => this.stdout.write(text2));
28469
28736
  handle.on("stderr", (text2) => this.stderr.write(text2));
28470
28737
  handle.on("exit", (code) => this.finish(code));
28471
- handle.exec();
28738
+ referenceChanged(1);
28739
+ try {
28740
+ handle.exec();
28741
+ } catch (error) {
28742
+ this.unref();
28743
+ throw error;
28744
+ }
28472
28745
  }
28746
+ referenceChanged;
28747
+ stdout = new streamModule4.PassThrough();
28748
+ stderr = new streamModule4.PassThrough();
28749
+ stdin;
28750
+ stdio;
28751
+ pid;
28752
+ exitCode = null;
28753
+ signalCode = null;
28754
+ killed = false;
28755
+ spawnfile;
28756
+ spawnargs;
28757
+ handle;
28758
+ settled = false;
28759
+ referenced = true;
28473
28760
  kill(signal = "SIGTERM") {
28474
28761
  this.killed = true;
28475
28762
  this.handle.kill(typeof signal === "number" ? "SIGTERM" : signal);
28476
28763
  return true;
28477
28764
  }
28478
28765
  ref() {
28766
+ if (!this.settled && !this.referenced) {
28767
+ this.referenced = true;
28768
+ this.referenceChanged(1);
28769
+ }
28479
28770
  return this;
28480
28771
  }
28481
28772
  unref() {
28773
+ if (this.referenced) {
28774
+ this.referenced = false;
28775
+ this.referenceChanged(-1);
28776
+ }
28482
28777
  return this;
28483
28778
  }
28484
- disconnect() {
28485
- this.emit("disconnect");
28486
- }
28487
- /** No IPC channel exists, and reporting that honestly beats a silent drop. */
28488
- send() {
28489
- return false;
28779
+ channel;
28780
+ channelOpen = false;
28781
+ /** Open the parent's end of a `fork` channel. */
28782
+ attachChannel(transport, id) {
28783
+ this.channelOpen = true;
28784
+ this.channel = transport.attach(
28785
+ id,
28786
+ "parent",
28787
+ (message) => this.emit("message", message, void 0),
28788
+ () => this.channelClosed()
28789
+ );
28490
28790
  }
28491
28791
  get connected() {
28492
- return false;
28792
+ return this.channelOpen;
28793
+ }
28794
+ /** `send(message[, sendHandle][, options][, callback])`, as Node spells it. */
28795
+ send(message, ...rest) {
28796
+ const callback = rest.find((value) => typeof value === "function");
28797
+ if (!this.channel || !this.channelOpen) {
28798
+ const error = Object.assign(new Error("Channel closed"), { code: "ERR_IPC_CHANNEL_CLOSED" });
28799
+ if (callback) queueMicrotask(() => callback(error));
28800
+ else queueMicrotask(() => this.emit("error", error));
28801
+ return false;
28802
+ }
28803
+ this.channel.send(message);
28804
+ if (callback) queueMicrotask(() => callback(null));
28805
+ return true;
28806
+ }
28807
+ disconnect() {
28808
+ if (!this.channelOpen) return;
28809
+ this.channel?.disconnect();
28810
+ this.channelClosed();
28811
+ }
28812
+ channelClosed() {
28813
+ if (!this.channelOpen) return;
28814
+ this.channelOpen = false;
28815
+ this.emit("disconnect");
28493
28816
  }
28494
28817
  finish(code) {
28495
28818
  if (this.settled) return;
28819
+ this.channel?.disconnect();
28820
+ this.channelClosed();
28821
+ this.unref();
28496
28822
  this.settled = true;
28497
28823
  this.exitCode = code;
28498
28824
  this.stdout.end();
@@ -28501,7 +28827,7 @@ var ChildProcess = class extends EventEmitter4 {
28501
28827
  queueMicrotask(() => this.emit("close", code, null));
28502
28828
  }
28503
28829
  };
28504
- function createChildProcessModule(spawnChild, defaultCwd, syncSpawn, defaultEnv = () => ({})) {
28830
+ function createChildProcessModule(spawnChild, defaultCwd, syncSpawn, defaultEnv = () => ({}), lifecycle = {}) {
28505
28831
  const environmentFor = (options) => options.env ? { ...options.env } : defaultEnv();
28506
28832
  const throughShell = (command, options) => {
28507
28833
  const shell = typeof options.shell === "string" ? options.shell : "/bin/sh";
@@ -28512,16 +28838,24 @@ function createChildProcessModule(spawnChild, defaultCwd, syncSpawn, defaultEnv
28512
28838
  if (stdio === "ignore") return true;
28513
28839
  return Array.isArray(stdio) && stdio[0] === "ignore";
28514
28840
  };
28841
+ const wantsChannel = (options) => Array.isArray(options.stdio) && options.stdio.includes("ipc");
28515
28842
  const start2 = (file3, args, options) => {
28516
28843
  const resolved = options.shell ? throughShell([file3, ...args].join(" "), options) : { file: file3, args };
28844
+ const channelId = wantsChannel(options) && lifecycle.ipc ? newIpcChannelId() : void 0;
28517
28845
  const handle = spawnChild({
28518
28846
  command: resolved.file,
28519
28847
  args: resolved.args,
28520
28848
  cwd: options.cwd ?? defaultCwd(),
28521
- env: environmentFor(options),
28849
+ env: channelId ? { ...environmentFor(options), [IPC_CHANNEL_ENV]: channelId } : environmentFor(options),
28850
+ ...options.stdio === "inherit" || Array.isArray(options.stdio) && options.stdio[0] === "inherit" ? { inheritStdio: true } : {},
28522
28851
  ...stdinIgnored(options) ? { stdinIgnored: true } : {}
28523
28852
  });
28524
- return new ChildProcess(handle, resolved.file, resolved.args);
28853
+ const child = new ChildProcess(handle, resolved.file, resolved.args, lifecycle.referenceChanged);
28854
+ if (channelId && lifecycle.ipc) child.attachChannel(lifecycle.ipc, channelId);
28855
+ const inherited = (index) => options.stdio === "inherit" || Array.isArray(options.stdio) && options.stdio[index] === "inherit";
28856
+ if (inherited(1)) child.stdout.on("data", (chunk) => lifecycle.stdout?.(chunk.toString()));
28857
+ if (inherited(2)) child.stderr.on("data", (chunk) => lifecycle.stderr?.(chunk.toString()));
28858
+ return child;
28525
28859
  };
28526
28860
  const spawn = (file3, args = [], options = {}) => {
28527
28861
  if (!Array.isArray(args)) return start2(file3, [], args);
@@ -28564,7 +28898,13 @@ ${err.join("")}`),
28564
28898
  spawn,
28565
28899
  exec,
28566
28900
  execFile,
28567
- fork: (modulePath, args = [], options = {}) => spawn("node", [modulePath, ...args], options),
28901
+ fork: (modulePath, args = [], options = {}) => {
28902
+ const [list, opts] = Array.isArray(args) ? [args, options] : [[], args ?? {}];
28903
+ 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"];
28904
+ const withChannel = stdio.includes("ipc") ? stdio : [...stdio, "ipc"];
28905
+ const execArgv = (opts.execArgv ?? []).filter((flag) => !/^--(inspect|debug)/.test(flag));
28906
+ return start2("node", [...execArgv, modulePath, ...list], { ...opts, shell: false, stdio: withChannel });
28907
+ },
28568
28908
  ...buildSyncFamily(syncSpawn, throughShell, defaultCwd, environmentFor),
28569
28909
  ChildProcess
28570
28910
  };
@@ -29195,6 +29535,9 @@ function createCoreModules(options) {
29195
29535
  argv: options.argv?.slice() ?? ["/usr/bin/node"],
29196
29536
  argv0: "node",
29197
29537
  execPath: "/usr/bin/node",
29538
+ /* `process/browser.js` has no `execArgv`; Node always has an array, and
29539
+ * CLIs that fork copy it (`[...process.execArgv]`). */
29540
+ execArgv: [],
29198
29541
  env: env2,
29199
29542
  platform: "linux",
29200
29543
  arch: "x64",
@@ -29248,6 +29591,25 @@ function createCoreModules(options) {
29248
29591
  const implementation = EventEmitter4.prototype[method];
29249
29592
  if (typeof implementation === "function") processObject[method] = implementation;
29250
29593
  }
29594
+ const hrtime = (previous) => {
29595
+ const now = performance.timeOrigin + performance.now();
29596
+ let seconds = Math.floor(now / 1e3);
29597
+ let nanoseconds = Math.floor(now % 1e3 * 1e6);
29598
+ if (previous) {
29599
+ seconds -= previous[0];
29600
+ nanoseconds -= previous[1];
29601
+ if (nanoseconds < 0) {
29602
+ seconds -= 1;
29603
+ nanoseconds += 1e9;
29604
+ }
29605
+ }
29606
+ return [seconds, nanoseconds];
29607
+ };
29608
+ hrtime.bigint = () => {
29609
+ const [seconds, nanoseconds] = hrtime();
29610
+ return BigInt(seconds) * 1000000000n + BigInt(nanoseconds);
29611
+ };
29612
+ processObject.hrtime = hrtime;
29251
29613
  const tty = options.tty === true;
29252
29614
  processObject.stdout = makeOutputStream(stdoutWrite, 1, tty);
29253
29615
  processObject.stderr = makeOutputStream(stderrWrite, 2, tty);
@@ -29332,6 +29694,7 @@ function createCoreModules(options) {
29332
29694
  const moduleBuiltin = {
29333
29695
  builtinModules: builtinNames2.flatMap((name) => [name, `node:${name}`]),
29334
29696
  isBuiltin: (name) => builtinNames2.includes(name.replace(/^node:/, "")),
29697
+ findSourceMap: () => void 0,
29335
29698
  createRequire: () => {
29336
29699
  throw new Error("createRequire is only available inside a loaded module");
29337
29700
  }
@@ -29354,7 +29717,86 @@ function createCoreModules(options) {
29354
29717
  };
29355
29718
  const http = options.http ? createHttpModule(options.http.router, options.http.owner, httpOptions, "http:") : createUnsupportedModule("http");
29356
29719
  const https = options.http ? createHttpModule(options.http.router, options.http.owner, httpOptions, "https:") : createUnsupportedModule("https");
29357
- const childProcess = options.spawnChild ? createChildProcessModule(options.spawnChild, () => cwd, options.syncSpawn, () => ({ ...processObject.env })) : createUnsupportedModule("child_process");
29720
+ let referencedChildren = 0;
29721
+ const childProcess = options.spawnChild ? createChildProcessModule(options.spawnChild, () => cwd, options.syncSpawn, () => ({ ...processObject.env }), {
29722
+ referenceChanged: (delta) => {
29723
+ referencedChildren += delta;
29724
+ },
29725
+ stdout: options.stdout,
29726
+ stderr: options.stderr,
29727
+ ...options.ipc ? { ipc: options.ipc } : {}
29728
+ }) : createUnsupportedModule("child_process");
29729
+ let channelReferenced = 0;
29730
+ const channelId = env2[IPC_CHANNEL_ENV];
29731
+ if (channelId && options.ipc) {
29732
+ delete env2[IPC_CHANNEL_ENV];
29733
+ let open = true;
29734
+ let referenced = true;
29735
+ channelReferenced = 1;
29736
+ const close = () => {
29737
+ if (!open) return;
29738
+ open = false;
29739
+ if (referenced) channelReferenced = 0;
29740
+ processObject.connected = false;
29741
+ delete processObject.send;
29742
+ try {
29743
+ processObject.emit("disconnect");
29744
+ } catch (error) {
29745
+ reportUncaught(error);
29746
+ }
29747
+ runTicks();
29748
+ };
29749
+ const endpoint = options.ipc.attach(
29750
+ channelId,
29751
+ "child",
29752
+ (message) => {
29753
+ try {
29754
+ processObject.emit("message", message, void 0);
29755
+ } catch (error) {
29756
+ reportUncaught(error);
29757
+ }
29758
+ runTicks();
29759
+ },
29760
+ close
29761
+ );
29762
+ processObject.connected = true;
29763
+ processObject.send = (message, ...rest) => {
29764
+ const callback = rest.find((value) => typeof value === "function");
29765
+ if (!open) {
29766
+ const error = Object.assign(new Error("Channel closed"), { code: "ERR_IPC_CHANNEL_CLOSED" });
29767
+ if (callback) defer(() => callback(error));
29768
+ else defer(() => {
29769
+ processObject.emit("error", error);
29770
+ });
29771
+ return false;
29772
+ }
29773
+ endpoint.send(message);
29774
+ if (callback) defer(() => callback(null));
29775
+ return true;
29776
+ };
29777
+ processObject.disconnect = () => {
29778
+ if (open) {
29779
+ endpoint.disconnect();
29780
+ close();
29781
+ }
29782
+ };
29783
+ processObject.channel = {
29784
+ ref() {
29785
+ if (open && !referenced) {
29786
+ referenced = true;
29787
+ channelReferenced = 1;
29788
+ }
29789
+ return this;
29790
+ },
29791
+ unref() {
29792
+ if (referenced) {
29793
+ referenced = false;
29794
+ channelReferenced = 0;
29795
+ }
29796
+ return this;
29797
+ }
29798
+ };
29799
+ }
29358
29800
  const readline = createReadlineModule(() => processObject.stdin, () => processObject.stdout);
29359
29801
  const dns = createDnsModule(defer);
29360
29802
  const builtins = {
@@ -29366,6 +29808,7 @@ function createCoreModules(options) {
29366
29808
  console: consoleObject,
29367
29809
  constants: fs.constants,
29368
29810
  crypto: createCryptoModule(),
29811
+ diagnostics_channel: createDiagnosticsChannel(),
29369
29812
  dns,
29370
29813
  "dns/promises": dns.promises,
29371
29814
  events: EventEmitter4,
@@ -29384,6 +29827,25 @@ function createCoreModules(options) {
29384
29827
  readline,
29385
29828
  "readline/promises": readline.promises,
29386
29829
  stream: streamModule4,
29830
+ "stream/web": Object.fromEntries([
29831
+ "ReadableStream",
29832
+ "ReadableStreamDefaultReader",
29833
+ "ReadableStreamBYOBReader",
29834
+ "ReadableStreamDefaultController",
29835
+ "ReadableByteStreamController",
29836
+ "ReadableStreamBYOBRequest",
29837
+ "WritableStream",
29838
+ "WritableStreamDefaultWriter",
29839
+ "WritableStreamDefaultController",
29840
+ "TransformStream",
29841
+ "TransformStreamDefaultController",
29842
+ "ByteLengthQueuingStrategy",
29843
+ "CountQueuingStrategy",
29844
+ "TextEncoderStream",
29845
+ "TextDecoderStream",
29846
+ "CompressionStream",
29847
+ "DecompressionStream"
29848
+ ].filter((name) => name in globalThis).map((name) => [name, globalThis[name]])),
29387
29849
  "stream/promises": createStreamPromises(),
29388
29850
  string_decoder: stringDecoderModule,
29389
29851
  timers: { ...timersModule, ...timers.api },
@@ -29415,7 +29877,57 @@ function createCoreModules(options) {
29415
29877
  })
29416
29878
  };
29417
29879
  for (const name of stubNames) builtins[name] = createUnsupportedModule(name);
29880
+ builtins.worker_threads = {
29881
+ MessagePort: globalThis.MessagePort ?? class MessagePort {
29882
+ },
29883
+ markAsUncloneable: () => {
29884
+ },
29885
+ isMarkedAsUncloneable: () => false,
29886
+ markAsUntransferable: () => {
29887
+ },
29888
+ isMarkedAsUntransferable: () => false
29889
+ };
29418
29890
  builtins.net = createNetModule();
29891
+ builtins.inspector = createUnsupportedModule("inspector", {
29892
+ url: () => void 0,
29893
+ close: () => {
29894
+ },
29895
+ waitForDebugger: () => {
29896
+ throw Object.assign(new Error("Inspector is not active"), { code: "ERR_INSPECTOR_NOT_ACTIVE" });
29897
+ },
29898
+ console: consoleObject
29899
+ });
29900
+ builtins.v8 = createUnsupportedModule("v8", {
29901
+ getHeapStatistics: () => {
29902
+ const memory = performance.memory;
29903
+ const limit = memory?.jsHeapSizeLimit ?? 4 * 1024 ** 3;
29904
+ return {
29905
+ total_heap_size: memory?.totalJSHeapSize ?? 0,
29906
+ total_heap_size_executable: 0,
29907
+ total_physical_size: memory?.totalJSHeapSize ?? 0,
29908
+ total_available_size: limit - (memory?.usedJSHeapSize ?? 0),
29909
+ used_heap_size: memory?.usedJSHeapSize ?? 0,
29910
+ heap_size_limit: limit,
29911
+ malloced_memory: 0,
29912
+ peak_malloced_memory: 0,
29913
+ does_zap_garbage: 0,
29914
+ number_of_native_contexts: 1,
29915
+ number_of_detached_contexts: 0,
29916
+ total_global_handles_size: 0,
29917
+ used_global_handles_size: 0,
29918
+ external_memory: 0
29919
+ };
29920
+ },
29921
+ getHeapSpaceStatistics: () => [],
29922
+ getHeapCodeStatistics: () => ({ code_and_metadata_size: 0, bytecode_and_metadata_size: 0, external_script_source_size: 0, cpu_profiler_metadata_size: 0 }),
29923
+ cachedDataVersionTag: () => 0,
29924
+ setFlagsFromString: () => {
29925
+ },
29926
+ setHeapSnapshotNearHeapLimit: () => {
29927
+ },
29928
+ serialize: (value) => Buffer2.from(JSON.stringify(value) ?? "null"),
29929
+ deserialize: (buffer) => JSON.parse(Buffer2.from(buffer).toString("utf8"))
29930
+ });
29419
29931
  const globals = {
29420
29932
  Buffer: Buffer2,
29421
29933
  console: consoleObject,
@@ -29450,7 +29962,7 @@ function createCoreModules(options) {
29450
29962
  builtins,
29451
29963
  globals,
29452
29964
  process: processObject,
29453
- pendingHandles: timers.pending,
29965
+ pendingHandles: () => timers.pending() + referencedChildren + channelReferenced,
29454
29966
  pendingUnrefed: timers.pendingUnrefed,
29455
29967
  /** Client requests sent but not yet read to completion. */
29456
29968
  pendingRequests: () => inFlightRequests,
@@ -29516,7 +30028,9 @@ var ASYNC_FS_METHODS = [
29516
30028
  "close",
29517
30029
  "read",
29518
30030
  "write",
29519
- "exists"
30031
+ "exists",
30032
+ "fsync",
30033
+ "fdatasync"
29520
30034
  ];
29521
30035
  function createPathModule(cwd) {
29522
30036
  const resolve3 = (...segments2) => pathModule.resolve(cwd(), ...segments2);
@@ -29739,6 +30253,12 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
29739
30253
  unwatchFile: () => {
29740
30254
  }
29741
30255
  };
30256
+ fs.fsyncSync = (fd) => {
30257
+ requiredFd(fds, fd);
30258
+ };
30259
+ fs.fdatasyncSync = (fd) => {
30260
+ requiredFd(fds, fd);
30261
+ };
29742
30262
  fs.ftruncateSync = (fd, length) => fs.truncateSync(requiredFd(fds, fd).path, length);
29743
30263
  fs.fchmodSync = (fd, mode) => fs.chmodSync(requiredFd(fds, fd).path, mode);
29744
30264
  fs.fchownSync = (fd, uid, gid) => fs.chownSync(requiredFd(fds, fd).path, uid, gid);
@@ -29799,6 +30319,8 @@ function makeFileHandle(fs, fd) {
29799
30319
  return {
29800
30320
  fd,
29801
30321
  close: async () => fs.closeSync(fd),
30322
+ sync: async () => fs.fsyncSync(fd),
30323
+ datasync: async () => fs.fdatasyncSync(fd),
29802
30324
  stat: async () => fs.fstatSync(fd),
29803
30325
  truncate: async (length) => fs.ftruncateSync(fd, length),
29804
30326
  chmod: async (mode) => fs.fchmodSync(fd, mode),
@@ -30392,7 +30914,7 @@ function formatUncaught(error) {
30392
30914
  Node.js v22.12.0
30393
30915
  `;
30394
30916
  }
30395
- var stubNames = ["cluster", "dgram", "diagnostics_channel", "domain", "http2", "inspector", "net", "tls", "v8", "vm", "worker_threads"];
30917
+ var stubNames = ["cluster", "dgram", "domain", "http2", "inspector", "net", "tls", "v8", "vm", "worker_threads"];
30396
30918
  var builtinNames2 = [
30397
30919
  "assert",
30398
30920
  "assert/strict",
@@ -30405,6 +30927,7 @@ var builtinNames2 = [
30405
30927
  "events",
30406
30928
  "fs",
30407
30929
  "fs/promises",
30930
+ "diagnostics_channel",
30408
30931
  "dns",
30409
30932
  "dns/promises",
30410
30933
  "http",
@@ -30420,6 +30943,7 @@ var builtinNames2 = [
30420
30943
  "readline",
30421
30944
  "readline/promises",
30422
30945
  "stream",
30946
+ "stream/web",
30423
30947
  "stream/promises",
30424
30948
  "string_decoder",
30425
30949
  "timers",
@@ -31808,6 +32332,7 @@ var LocalRuntimePod = class _LocalRuntimePod {
31808
32332
  ...this.networkPolicy ? { policy: this.networkPolicy } : {}
31809
32333
  },
31810
32334
  spawnChild: (config2) => this.processManager.spawn(config2),
32335
+ ipc: hostIpcTransport,
31811
32336
  ...typeof options.stdinPath === "string" ? { stdinPath: options.stdinPath } : {},
31812
32337
  ...options.interactiveStdin ? { interactiveStdin: true } : {},
31813
32338
  ...options.tty ? { tty: true } : {},
@@ -32301,9 +32826,12 @@ var WorkerRuntimePod = class _WorkerRuntimePod extends LocalRuntimePod {
32301
32826
  const entry = { worker, server };
32302
32827
  this.live.add(entry);
32303
32828
  const ownedChildren = /* @__PURE__ */ new Set();
32829
+ const channelEnds = /* @__PURE__ */ new Map();
32304
32830
  const process2 = new WorkerProcess(worker, () => {
32305
32831
  for (const child of ownedChildren) child.kill("SIGTERM");
32306
32832
  ownedChildren.clear();
32833
+ for (const end of channelEnds.values()) end.disconnect();
32834
+ channelEnds.clear();
32307
32835
  this.live.delete(entry);
32308
32836
  server.close();
32309
32837
  this.closeProxies(owner);
@@ -32368,6 +32896,30 @@ var WorkerRuntimePod = class _WorkerRuntimePod extends LocalRuntimePod {
32368
32896
  case "child-kill":
32369
32897
  children.get(message.id)?.kill(String(message.signal));
32370
32898
  return;
32899
+ case "ipc-attach": {
32900
+ const key = `${message.side}:${message.id}`;
32901
+ if (channelEnds.has(key)) return;
32902
+ channelEnds.set(key, hostIpcTransport.attach(
32903
+ String(message.id),
32904
+ message.side === "child" ? "child" : "parent",
32905
+ (value) => worker.postMessage({ type: "ipc-message", id: message.id, side: message.side, value }),
32906
+ () => {
32907
+ channelEnds.delete(key);
32908
+ worker.postMessage({ type: "ipc-disconnect", id: message.id, side: message.side });
32909
+ }
32910
+ ));
32911
+ return;
32912
+ }
32913
+ case "ipc-send":
32914
+ channelEnds.get(`${message.side}:${message.id}`)?.send(message.value);
32915
+ return;
32916
+ case "ipc-close": {
32917
+ const key = `${message.side}:${message.id}`;
32918
+ const end = channelEnds.get(key);
32919
+ channelEnds.delete(key);
32920
+ end?.disconnect();
32921
+ return;
32922
+ }
32371
32923
  default:
32372
32924
  return;
32373
32925
  }