sandboxedjs 0.1.21 → 0.1.23

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.cjs CHANGED
@@ -4,8 +4,44 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var nodepod = require('@scelar/nodepod');
6
6
  var acorn = require('acorn');
7
+ var EventEmitter3 = require('events');
8
+ var jsx = require('acorn-jsx');
9
+ var resolve_exports = require('resolve.exports');
10
+ var buffer = require('buffer');
11
+ var pathModule = require('path-browserify');
12
+ var streamModule3 = require('stream-browserify');
13
+ var utilModule = require('util');
14
+ var assertModule = require('assert');
15
+ var processShim = require('process');
16
+ var zlibModule = require('browserify-zlib');
17
+ var querystringModule = require('querystring-es3');
18
+ var stringDecoderModule = require('string_decoder');
19
+ var timersModule = require('timers-browserify');
20
+ var urlModule = require('url');
21
+ var legacy = require('@noble/hashes/legacy');
22
+ var sha256 = require('@noble/hashes/sha256');
23
+ var sha512 = require('@noble/hashes/sha512');
24
+ var hmac = require('@noble/hashes/hmac');
25
+ var pako = require('pako');
26
+ var sha1 = require('@noble/hashes/sha1');
27
+ var semver = require('semver');
7
28
 
8
29
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
30
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
31
+
32
+ var EventEmitter3__default = /*#__PURE__*/_interopDefault(EventEmitter3);
33
+ var jsx__default = /*#__PURE__*/_interopDefault(jsx);
34
+ var pathModule__default = /*#__PURE__*/_interopDefault(pathModule);
35
+ var streamModule3__default = /*#__PURE__*/_interopDefault(streamModule3);
36
+ var utilModule__default = /*#__PURE__*/_interopDefault(utilModule);
37
+ var assertModule__default = /*#__PURE__*/_interopDefault(assertModule);
38
+ var processShim__default = /*#__PURE__*/_interopDefault(processShim);
39
+ var zlibModule__default = /*#__PURE__*/_interopDefault(zlibModule);
40
+ var querystringModule__default = /*#__PURE__*/_interopDefault(querystringModule);
41
+ var stringDecoderModule__default = /*#__PURE__*/_interopDefault(stringDecoderModule);
42
+ var timersModule__default = /*#__PURE__*/_interopDefault(timersModule);
43
+ var urlModule__default = /*#__PURE__*/_interopDefault(urlModule);
44
+
9
45
  var __defProp = Object.defineProperty;
10
46
  var __getOwnPropNames = Object.getOwnPropertyNames;
11
47
  var __esm = (fn, res) => function __init() {
@@ -1070,16 +1106,16 @@ function tokenize(src) {
1070
1106
  out.push({ kind: "eof", value: "" });
1071
1107
  return out;
1072
1108
  }
1073
- function parseInBase(text, base) {
1109
+ function parseInBase(text2, base) {
1074
1110
  let value = 0;
1075
- for (const ch of text) {
1111
+ for (const ch of text2) {
1076
1112
  let digit;
1077
1113
  if (base <= 36) {
1078
1114
  digit = DIGITS.toLowerCase().indexOf(ch.toLowerCase());
1079
1115
  } else {
1080
1116
  digit = DIGITS.indexOf(ch);
1081
1117
  }
1082
- if (digit < 0 || digit >= base) throw new exports.ArithError(`value too great for base (error token is "${text}")`);
1118
+ if (digit < 0 || digit >= base) throw new exports.ArithError(`value too great for base (error token is "${text2}")`);
1083
1119
  value = value * base + digit;
1084
1120
  }
1085
1121
  return value;
@@ -1415,8 +1451,8 @@ function ifsOf(ctx) {
1415
1451
  const raw = ctx.vars.get("IFS");
1416
1452
  return raw === void 0 ? IFS_DEFAULT : raw;
1417
1453
  }
1418
- function escapeGlob(text) {
1419
- return text.replace(/[*?[\]\\]/g, "\\$&");
1454
+ function escapeGlob(text2) {
1455
+ return text2.replace(/[*?[\]\\]/g, "\\$&");
1420
1456
  }
1421
1457
  function braceExpand(word) {
1422
1458
  const open = findUnquotedBrace(word);
@@ -1572,12 +1608,12 @@ async function expandFragments(word, ctx, opts = {}) {
1572
1608
  literalGlob = true;
1573
1609
  }
1574
1610
  };
1575
- const pushLiteral = (text, globActive) => {
1611
+ const pushLiteral = (text2, globActive) => {
1576
1612
  if (globActive !== literalGlob) {
1577
1613
  flushLiteral();
1578
1614
  literalGlob = globActive;
1579
1615
  }
1580
- literal += text;
1616
+ literal += text2;
1581
1617
  };
1582
1618
  while (i < word.length) {
1583
1619
  const c = word[i];
@@ -1924,8 +1960,8 @@ async function expandBracedParameter(body, ctx, quoted) {
1924
1960
  }
1925
1961
  return valueFragments(name, ctx, quoted);
1926
1962
  }
1927
- function frag(text, quoted) {
1928
- return { text, split: !quoted, glob: false };
1963
+ function frag(text2, quoted) {
1964
+ return { text: text2, split: !quoted, glob: false };
1929
1965
  }
1930
1966
  function stripAffix(value, pattern, op, ctx) {
1931
1967
  const opts = { pathname: false, dot: true, extglob: ctx.extglob !== false };
@@ -2021,26 +2057,26 @@ function splitOnUnquotedColon(spec) {
2021
2057
  out.push(current);
2022
2058
  return out;
2023
2059
  }
2024
- function findUnescaped(text, ch) {
2025
- for (let i = 0; i < text.length; i++) {
2026
- if (text[i] === "\\") {
2060
+ function findUnescaped(text2, ch) {
2061
+ for (let i = 0; i < text2.length; i++) {
2062
+ if (text2[i] === "\\") {
2027
2063
  i++;
2028
2064
  continue;
2029
2065
  }
2030
- if (text[i] === ch) return i;
2066
+ if (text2[i] === ch) return i;
2031
2067
  }
2032
2068
  return -1;
2033
2069
  }
2034
- function matchParen(text, open) {
2070
+ function matchParen(text2, open) {
2035
2071
  let depth = 0;
2036
- for (let i = open; i < text.length; i++) {
2037
- const c = text[i];
2072
+ for (let i = open; i < text2.length; i++) {
2073
+ const c = text2[i];
2038
2074
  if (c === "\\") {
2039
2075
  i++;
2040
2076
  continue;
2041
2077
  }
2042
2078
  if (c === "'") {
2043
- const end = text.indexOf("'", i + 1);
2079
+ const end = text2.indexOf("'", i + 1);
2044
2080
  if (end < 0) return -1;
2045
2081
  i = end;
2046
2082
  continue;
@@ -2053,10 +2089,10 @@ function matchParen(text, open) {
2053
2089
  }
2054
2090
  return -1;
2055
2091
  }
2056
- function matchDoubleParen(text, open) {
2092
+ function matchDoubleParen(text2, open) {
2057
2093
  let depth = 0;
2058
- for (let i = open; i < text.length; i++) {
2059
- const c = text[i];
2094
+ for (let i = open; i < text2.length; i++) {
2095
+ const c = text2[i];
2060
2096
  if (c === "\\") {
2061
2097
  i++;
2062
2098
  continue;
@@ -2069,21 +2105,21 @@ function matchDoubleParen(text, open) {
2069
2105
  }
2070
2106
  return -1;
2071
2107
  }
2072
- function findBacktick(text, from) {
2073
- for (let i = from + 1; i < text.length; i++) {
2074
- if (text[i] === "\\") {
2108
+ function findBacktick(text2, from) {
2109
+ for (let i = from + 1; i < text2.length; i++) {
2110
+ if (text2[i] === "\\") {
2075
2111
  i++;
2076
2112
  continue;
2077
2113
  }
2078
- if (text[i] === "`") return i;
2114
+ if (text2[i] === "`") return i;
2079
2115
  }
2080
- return text.length;
2116
+ return text2.length;
2081
2117
  }
2082
- function unescapeBacktick(text) {
2083
- return text.replace(/\\([`$\\])/g, "$1");
2118
+ function unescapeBacktick(text2) {
2119
+ return text2.replace(/\\([`$\\])/g, "$1");
2084
2120
  }
2085
- function stripTrailingNewlines(text) {
2086
- return text.replace(/\n+$/, "");
2121
+ function stripTrailingNewlines(text2) {
2122
+ return text2.replace(/\n+$/, "");
2087
2123
  }
2088
2124
  function fieldSplit(fragments, ifs) {
2089
2125
  if (fragments.length === 0) return [];
@@ -2106,9 +2142,9 @@ function fieldSplit(fragments, ifs) {
2106
2142
  }
2107
2143
  let buffer = "";
2108
2144
  let i = 0;
2109
- const text = fragment.text;
2110
- while (i < text.length) {
2111
- const c = text[i];
2145
+ const text2 = fragment.text;
2146
+ while (i < text2.length) {
2147
+ const c = text2[i];
2112
2148
  if (whitespace.includes(c) || others.includes(c)) {
2113
2149
  if (buffer !== "" || current.length > 0) {
2114
2150
  if (buffer !== "") current.push({ ...fragment, text: buffer });
@@ -2118,8 +2154,8 @@ function fieldSplit(fragments, ifs) {
2118
2154
  }
2119
2155
  let consumedNonWs = others.includes(c);
2120
2156
  i++;
2121
- while (i < text.length) {
2122
- const d = text[i];
2157
+ while (i < text2.length) {
2158
+ const d = text2[i];
2123
2159
  if (whitespace.includes(d)) {
2124
2160
  i++;
2125
2161
  continue;
@@ -2807,13 +2843,13 @@ function builtinEcho({ argv, io }) {
2807
2843
  }
2808
2844
  args = args.slice(1);
2809
2845
  }
2810
- let text = args.join(" ");
2846
+ let text2 = args.join(" ");
2811
2847
  if (interpret) {
2812
- const decoded = decodeEscapes(text, { stopAtC: true });
2813
- text = decoded.text;
2848
+ const decoded = decodeEscapes(text2, { stopAtC: true });
2849
+ text2 = decoded.text;
2814
2850
  if (decoded.stopped) newline = false;
2815
2851
  }
2816
- io.stdout.write(newline ? text + "\n" : text);
2852
+ io.stdout.write(newline ? text2 + "\n" : text2);
2817
2853
  return 0;
2818
2854
  }
2819
2855
  function builtinPrintf({ argv, io }) {
@@ -2830,9 +2866,9 @@ function builtinPrintf({ argv, io }) {
2830
2866
  return 2;
2831
2867
  }
2832
2868
  try {
2833
- const text = formatPrintf(format, args.slice(start + 1));
2869
+ const text2 = formatPrintf(format, args.slice(start + 1));
2834
2870
  if (varName) return 0;
2835
- io.stdout.write(text);
2871
+ io.stdout.write(text2);
2836
2872
  return 0;
2837
2873
  } catch (e) {
2838
2874
  io.stderr.write(`printf: ${e instanceof PrintfError ? e.message : String(e)}
@@ -2915,9 +2951,9 @@ async function builtinSource({ shell, argv, io }) {
2915
2951
  const found = shell.kernel.which(target, shell.cwd, shell.vars.environment(), shell.cred);
2916
2952
  if (found) path = found;
2917
2953
  }
2918
- let text;
2954
+ let text2;
2919
2955
  try {
2920
- text = shell.kernel.vfs.readText(path, shell.cred);
2956
+ text2 = shell.kernel.vfs.readText(path, shell.cred);
2921
2957
  } catch {
2922
2958
  io.stderr.write(`${argv[0]}: ${target}: No such file or directory
2923
2959
  `);
@@ -2926,7 +2962,7 @@ async function builtinSource({ shell, argv, io }) {
2926
2962
  const savedPositional = shell.positional;
2927
2963
  if (argv.length > 2) shell.positional = argv.slice(2);
2928
2964
  try {
2929
- return await shell.execute(text, io);
2965
+ return await shell.execute(text2, io);
2930
2966
  } finally {
2931
2967
  shell.positional = savedPositional;
2932
2968
  }
@@ -4228,9 +4264,9 @@ var init_ffmpeg_core = __esm({
4228
4264
  }
4229
4265
  var wasmMemory;
4230
4266
  var ABORT = false;
4231
- function assert(condition, text) {
4267
+ function assert(condition, text2) {
4232
4268
  if (!condition) {
4233
- abort(text);
4269
+ abort(text2);
4234
4270
  }
4235
4271
  }
4236
4272
  var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAP64, HEAPF64;
@@ -6721,8 +6757,8 @@ var init_ffmpeg_core = __esm({
6721
6757
  };
6722
6758
  function handleMessage(data) {
6723
6759
  if (typeof data == "string") {
6724
- var encoder6 = new TextEncoder();
6725
- data = encoder6.encode(data);
6760
+ var encoder7 = new TextEncoder();
6761
+ data = encoder7.encode(data);
6726
6762
  } else {
6727
6763
  assert(data.byteLength !== void 0);
6728
6764
  if (data.byteLength == 0) {
@@ -8805,15 +8841,15 @@ async function buildPatchedWorker() {
8805
8841
  function ensureEsbuild() {`)
8806
8842
  ].join("\n");
8807
8843
  const fingerprint = crypto2.createHash("sha256").update(`${source.length}:${wasmStat.size}:${patched.length}`).digest("hex").slice(0, 16);
8808
- const cached = path.join(os.tmpdir(), `sandboxedjs-worker-${fingerprint}.js`);
8844
+ const cached2 = path.join(os.tmpdir(), `sandboxedjs-worker-${fingerprint}.js`);
8809
8845
  try {
8810
- await fs.access(cached);
8846
+ await fs.access(cached2);
8811
8847
  } catch {
8812
- const staging = `${cached}.${process.pid}.tmp`;
8848
+ const staging = `${cached2}.${process.pid}.tmp`;
8813
8849
  await fs.writeFile(staging, patched, "utf8");
8814
- await fs.rename(staging, cached);
8850
+ await fs.rename(staging, cached2);
8815
8851
  }
8816
- return cached;
8852
+ return cached2;
8817
8853
  }
8818
8854
  var INIT_HELPER = `let __sandboxedjsWasmUrl = null;
8819
8855
  async function __sandboxedjsEsbuildInit(wasmPath, wasmUrl) {
@@ -10398,16 +10434,16 @@ function createContext(init) {
10398
10434
  path(p) {
10399
10435
  return resolve(cwd, p);
10400
10436
  },
10401
- write(text) {
10437
+ write(text2) {
10402
10438
  try {
10403
- stdout.write(text);
10439
+ stdout.write(text2);
10404
10440
  } catch (e) {
10405
10441
  if (isSysError(e) && e.code === "EPIPE") proc.deliver("SIGPIPE");
10406
10442
  else throw e;
10407
10443
  }
10408
10444
  },
10409
- line(text = "") {
10410
- ctx.write(encoder3.encode(text + "\n"));
10445
+ line(text2 = "") {
10446
+ ctx.write(encoder3.encode(text2 + "\n"));
10411
10447
  },
10412
10448
  warn(message) {
10413
10449
  try {
@@ -11284,8 +11320,8 @@ function createProcProvider(kernel) {
11284
11320
  loadavg: () => textFile(() => {
11285
11321
  const running = kernel.procs.list().filter((p) => p.state === "R").length;
11286
11322
  const total = kernel.procs.list().length;
11287
- const load = (running / kernel.cpus).toFixed(2);
11288
- return `${load} ${load} ${load} ${running}/${total} ${kernel.procs.list().length + 1}
11323
+ const load2 = (running / kernel.cpus).toFixed(2);
11324
+ return `${load2} ${load2} ${load2} ${running}/${total} ${kernel.procs.list().length + 1}
11289
11325
  `;
11290
11326
  }),
11291
11327
  meminfo: () => textFile(() => {
@@ -11541,13 +11577,13 @@ var NetworkStack = class {
11541
11577
  /** Resolve through `/etc/hosts`; returns null when the name is not local. */
11542
11578
  resolve(host2) {
11543
11579
  if (/^\d+\.\d+\.\d+\.\d+$/.test(host2)) return host2;
11544
- let text = "";
11580
+ let text2 = "";
11545
11581
  try {
11546
- text = this.vfs.readText("/etc/hosts");
11582
+ text2 = this.vfs.readText("/etc/hosts");
11547
11583
  } catch {
11548
11584
  return null;
11549
11585
  }
11550
- for (const line of text.split("\n")) {
11586
+ for (const line of text2.split("\n")) {
11551
11587
  const clean2 = line.split("#")[0].trim();
11552
11588
  if (clean2 === "") continue;
11553
11589
  const [addr, ...names] = clean2.split(/\s+/);
@@ -11906,9 +11942,9 @@ var Lexer = class _Lexer {
11906
11942
  }
11907
11943
  }
11908
11944
  if (i >= this.src.length) throw new IncompleteInputError(`unexpected EOF while looking for matching \`${close}'`, start);
11909
- const text = prefix + this.src.slice(openIdx, i + 1);
11945
+ const text2 = prefix + this.src.slice(openIdx, i + 1);
11910
11946
  this.pos = i + 1;
11911
- return text;
11947
+ return text2;
11912
11948
  }
11913
11949
  skipDoubleQuoted(from) {
11914
11950
  for (let i = from + 1; i < this.src.length; i++) {
@@ -12748,8 +12784,8 @@ var Shell = class _Shell {
12748
12784
  async makeProcessSubstitution(command, direction) {
12749
12785
  const path = `/tmp/.sbx-procsub-${this.proc.pid}-${this.tempFileCounter++}`;
12750
12786
  if (direction === "in") {
12751
- const text = await this.captureSubshell(command);
12752
- this.kernel.vfs.writeFile(path, text, { cred: this.cred, mode: 384 });
12787
+ const text2 = await this.captureSubshell(command);
12788
+ this.kernel.vfs.writeFile(path, text2, { cred: this.cred, mode: 384 });
12753
12789
  } else {
12754
12790
  this.kernel.vfs.writeFile(path, "", { cred: this.cred, mode: 384 });
12755
12791
  }
@@ -13530,12 +13566,12 @@ sys ${fmt2(Math.floor(ms * 0.2))}
13530
13566
  return finished;
13531
13567
  }
13532
13568
  };
13533
- function splitAliasWords(text) {
13569
+ function splitAliasWords(text2) {
13534
13570
  const out = [];
13535
13571
  let current = "";
13536
13572
  let quote2 = null;
13537
- for (let i = 0; i < text.length; i++) {
13538
- const c = text[i];
13573
+ for (let i = 0; i < text2.length; i++) {
13574
+ const c = text2[i];
13539
13575
  if (quote2) {
13540
13576
  if (c === quote2) quote2 = null;
13541
13577
  else current += c;
@@ -13723,10 +13759,10 @@ async function readInputs(ctx, operands, opts = {}) {
13723
13759
  return { sources, ok };
13724
13760
  }
13725
13761
  function splitLines(bytes) {
13726
- const text = decoder3.decode(bytes);
13727
- if (text === "") return { lines: [], trailingNewline: true };
13728
- const trailingNewline = text.endsWith("\n");
13729
- const body = trailingNewline ? text.slice(0, -1) : text;
13762
+ const text2 = decoder3.decode(bytes);
13763
+ if (text2 === "") return { lines: [], trailingNewline: true };
13764
+ const trailingNewline = text2.endsWith("\n");
13765
+ const body = trailingNewline ? text2.slice(0, -1) : text2;
13730
13766
  return { lines: body.split("\n"), trailingNewline };
13731
13767
  }
13732
13768
  function joinLines(lines, trailingNewline = true) {
@@ -13782,9 +13818,9 @@ function columnize(items, width, gap = 2) {
13782
13818
  }
13783
13819
  return out;
13784
13820
  }
13785
- function displayWidth(text) {
13821
+ function displayWidth(text2) {
13786
13822
  let width = 0;
13787
- for (const ch of text) {
13823
+ for (const ch of text2) {
13788
13824
  const code = ch.codePointAt(0);
13789
13825
  if (code >= 4352 && (code <= 4447 || code >= 11904 && code <= 42191 || code >= 44032 && code <= 55203 || code >= 63744 && code <= 64255 || code >= 65072 && code <= 65135 || code >= 65280 && code <= 65376 || code >= 65504 && code <= 65510)) {
13790
13826
  width += 2;
@@ -14060,9 +14096,9 @@ var cat = defineCommand({
14060
14096
  ctx.write(bytes);
14061
14097
  continue;
14062
14098
  }
14063
- const text = new TextDecoder().decode(bytes);
14064
- const hadTrailing = text.endsWith("\n");
14065
- const parts = (hadTrailing ? text.slice(0, -1) : text).split("\n");
14099
+ const text2 = new TextDecoder().decode(bytes);
14100
+ const hadTrailing = text2.endsWith("\n");
14101
+ const parts = (hadTrailing ? text2.slice(0, -1) : text2).split("\n");
14066
14102
  for (const raw of parts) {
14067
14103
  if (args.has("squeeze-blank")) {
14068
14104
  if (raw === "" && lastWasBlank) continue;
@@ -14922,11 +14958,11 @@ function describeFile(ctx, abs, st, mime) {
14922
14958
  if (magic[0] === 31 && magic[1] === 139) return mime ? "application/gzip" : "gzip compressed data";
14923
14959
  if (magic[0] === 80 && magic[1] === 75) return mime ? "application/zip" : "Zip archive data";
14924
14960
  if (magic[0] === 137 && magic[1] === 80) return mime ? "image/png" : "PNG image data";
14925
- const text = new TextDecoder().decode(bytes);
14926
- const printable = [...text].every((c) => c === "\n" || c === " " || c === "\r" || c >= " " && c <= "~" || c.charCodeAt(0) > 127);
14961
+ const text2 = new TextDecoder().decode(bytes);
14962
+ const printable = [...text2].every((c) => c === "\n" || c === " " || c === "\r" || c >= " " && c <= "~" || c.charCodeAt(0) > 127);
14927
14963
  if (!printable) return mime ? "application/octet-stream" : "data";
14928
- if (text.startsWith("#!")) {
14929
- const interp = text.slice(2, text.indexOf("\n")).trim();
14964
+ if (text2.startsWith("#!")) {
14965
+ const interp = text2.slice(2, text2.indexOf("\n")).trim();
14930
14966
  return mime ? "text/x-shellscript" : `a ${interp} script, ASCII text executable`;
14931
14967
  }
14932
14968
  const ext = extname(abs);
@@ -14979,13 +15015,13 @@ var echo = defineCommand({
14979
15015
  }
14980
15016
  args = args.slice(1);
14981
15017
  }
14982
- let text = args.join(" ");
15018
+ let text2 = args.join(" ");
14983
15019
  if (interpret) {
14984
- const decoded = decodeEscapes(text, { stopAtC: true });
14985
- text = decoded.text;
15020
+ const decoded = decodeEscapes(text2, { stopAtC: true });
15021
+ text2 = decoded.text;
14986
15022
  if (decoded.stopped) newline = false;
14987
15023
  }
14988
- ctx.write(newline ? text + "\n" : text);
15024
+ ctx.write(newline ? text2 + "\n" : text2);
14989
15025
  return 0;
14990
15026
  }
14991
15027
  });
@@ -15056,8 +15092,8 @@ var yesCmd = defineCommand({
15056
15092
  path: "/usr/bin/yes",
15057
15093
  summary: "output a string repeatedly until killed",
15058
15094
  async run(ctx) {
15059
- const text = (ctx.args.length ? ctx.args.join(" ") : "y") + "\n";
15060
- const block = text.repeat(512);
15095
+ const text2 = (ctx.args.length ? ctx.args.join(" ") : "y") + "\n";
15096
+ const block = text2.repeat(512);
15061
15097
  for (let i = 0; i < 1e5 && !ctx.signal.aborted && !ctx.stdout.closed; i++) {
15062
15098
  ctx.write(block);
15063
15099
  await new Promise((r) => setTimeout(r, 0));
@@ -15099,8 +15135,8 @@ var seq = defineCommand({
15099
15135
  if (increment > 0) for (let v = first; v <= last + 1e-9; v += increment) values.push(v);
15100
15136
  else for (let v = first; v >= last - 1e-9; v += increment) values.push(v);
15101
15137
  const rendered = values.map((v) => {
15102
- const text = Number.isInteger(v) ? String(v) : String(Number(v.toFixed(10)));
15103
- return format ? formatPrintf(format, [String(v)]) : text;
15138
+ const text2 = Number.isInteger(v) ? String(v) : String(Number(v.toFixed(10)));
15139
+ return format ? formatPrintf(format, [String(v)]) : text2;
15104
15140
  });
15105
15141
  const width = args.has("equal-width") ? Math.max(0, ...rendered.map((r) => r.length)) : 0;
15106
15142
  const out = rendered.map((r) => width ? r.padStart(width, "0") : r);
@@ -16086,8 +16122,8 @@ var ScriptParser = class {
16086
16122
  return { type: "y", range, from: [...unescape(from)], to: [...unescape(to)] };
16087
16123
  }
16088
16124
  };
16089
- function unescape(text) {
16090
- return text.replace(/\\(.)/g, (_, c) => ({ n: "\n", t: " ", r: "\r", "\\": "\\" })[c] ?? c);
16125
+ function unescape(text2) {
16126
+ return text2.replace(/\\(.)/g, (_, c) => ({ n: "\n", t: " ", r: "\r", "\\": "\\" })[c] ?? c);
16091
16127
  }
16092
16128
  function toJsRegex(pattern, extended) {
16093
16129
  let out = "";
@@ -16193,15 +16229,15 @@ var BRACKET_CLASSES = {
16193
16229
  xdigit: "0-9A-Fa-f",
16194
16230
  word: "A-Za-z0-9_"
16195
16231
  };
16196
- function translateBracket(text) {
16197
- return text.replace(/\[:([a-z]+):\]/g, (_, name) => BRACKET_CLASSES[name] ?? "");
16232
+ function translateBracket(text2) {
16233
+ return text2.replace(/\[:([a-z]+):\]/g, (_, name) => BRACKET_CLASSES[name] ?? "");
16198
16234
  }
16199
16235
  function applyReplacement(replacement, match) {
16200
16236
  let out = "";
16201
16237
  let caseMode = null;
16202
16238
  let oneShot = null;
16203
- const emit = (text) => {
16204
- let value = text;
16239
+ const emit = (text2) => {
16240
+ let value = text2;
16205
16241
  if (oneShot && value.length > 0) {
16206
16242
  value = (oneShot === "u" ? value[0].toUpperCase() : value[0].toLowerCase()) + value.slice(1);
16207
16243
  oneShot = null;
@@ -16331,20 +16367,20 @@ async function runSed(ctx) {
16331
16367
  flushAppends(state);
16332
16368
  if (state.quit !== null) break;
16333
16369
  }
16334
- const text = joinLines(state.output, trailingNewline || state.output.length > 0);
16370
+ const text2 = joinLines(state.output, trailingNewline || state.output.length > 0);
16335
16371
  if (inPlace && source.name !== "-" && source.name !== "standard input") {
16336
16372
  const abs = ctx.path(source.name);
16337
16373
  if (suffix) ctx.vfs.writeFile(ctx.path(source.name + suffix), source.bytes, { cred: ctx.cred });
16338
- ctx.vfs.writeFile(abs, text, { cred: ctx.cred });
16374
+ ctx.vfs.writeFile(abs, text2, { cred: ctx.cred });
16339
16375
  } else {
16340
- ctx.write(text);
16376
+ ctx.write(text2);
16341
16377
  }
16342
16378
  if (state.quit !== null && state.quit !== 0) status = state.quit;
16343
16379
  }
16344
16380
  return status;
16345
16381
  }
16346
16382
  function flushAppends(state) {
16347
- for (const text of state.appendQueue) state.output.push(text);
16383
+ for (const text2 of state.appendQueue) state.output.push(text2);
16348
16384
  state.appendQueue = [];
16349
16385
  }
16350
16386
  function resetRanges(program) {
@@ -16530,8 +16566,8 @@ function substitute2(input, regex, replacement, global, occurrence) {
16530
16566
  out += input.slice(last);
16531
16567
  return { text: out, changed };
16532
16568
  }
16533
- function escapeForL(text) {
16534
- return [...text].map((ch) => {
16569
+ function escapeForL(text2) {
16570
+ return [...text2].map((ch) => {
16535
16571
  const code = ch.charCodeAt(0);
16536
16572
  if (ch === "\\") return "\\\\";
16537
16573
  if (ch === " ") return "\\t";
@@ -16743,10 +16779,10 @@ function tokenize2(src) {
16743
16779
  i += 2;
16744
16780
  continue;
16745
16781
  }
16746
- const octal = /^[0-7]{1,3}/.exec(src.slice(i + 1));
16747
- if (octal) {
16748
- value += String.fromCharCode(parseInt(octal[0], 8));
16749
- i += 1 + octal[0].length;
16782
+ const octal2 = /^[0-7]{1,3}/.exec(src.slice(i + 1));
16783
+ if (octal2) {
16784
+ value += String.fromCharCode(parseInt(octal2[0], 8));
16785
+ i += 1 + octal2[0].length;
16750
16786
  continue;
16751
16787
  }
16752
16788
  value += next;
@@ -17498,9 +17534,9 @@ var Interpreter = class {
17498
17534
  return this.numToStr(v.num, this.toStrRaw(this.globals.get("OFMT")));
17499
17535
  }
17500
17536
  // ── output ────────────────────────────────────────────────────────────────
17501
- emit(text, redirect) {
17537
+ emit(text2, redirect) {
17502
17538
  if (!redirect) {
17503
- this.pendingOutput += text;
17539
+ this.pendingOutput += text2;
17504
17540
  if (this.pendingOutput.length > 8192) this.flush();
17505
17541
  return;
17506
17542
  }
@@ -17510,7 +17546,7 @@ var Interpreter = class {
17510
17546
  target = this.openOutput(name, redirect.op);
17511
17547
  this.outputs.set(name, target);
17512
17548
  }
17513
- target.write(text);
17549
+ target.write(text2);
17514
17550
  }
17515
17551
  flush() {
17516
17552
  if (this.pendingOutput !== "") {
@@ -17524,8 +17560,8 @@ var Interpreter = class {
17524
17560
  const ctx = this.ctx;
17525
17561
  const self2 = this;
17526
17562
  return {
17527
- write: (text) => {
17528
- buffer += text;
17563
+ write: (text2) => {
17564
+ buffer += text2;
17529
17565
  },
17530
17566
  close: () => {
17531
17567
  self2.flush();
@@ -17543,18 +17579,18 @@ var Interpreter = class {
17543
17579
  };
17544
17580
  }
17545
17581
  if (name === "/dev/stdout" || name === "-") {
17546
- return { write: (text) => this.ctx.write(text), close: () => {
17582
+ return { write: (text2) => this.ctx.write(text2), close: () => {
17547
17583
  } };
17548
17584
  }
17549
17585
  if (name === "/dev/stderr") {
17550
- return { write: (text) => this.ctx.stderr.write(text), close: () => {
17586
+ return { write: (text2) => this.ctx.stderr.write(text2), close: () => {
17551
17587
  } };
17552
17588
  }
17553
17589
  const abs = this.ctx.path(name);
17554
17590
  if (op === ">") this.ctx.vfs.writeFile(abs, "", { cred: this.ctx.cred });
17555
17591
  else if (!this.ctx.vfs.lexists(abs)) this.ctx.vfs.writeFile(abs, "", { cred: this.ctx.cred });
17556
17592
  return {
17557
- write: (text) => this.ctx.vfs.appendFile(abs, text, { cred: this.ctx.cred }),
17593
+ write: (text2) => this.ctx.vfs.appendFile(abs, text2, { cred: this.ctx.cred }),
17558
17594
  close: () => {
17559
17595
  }
17560
17596
  };
@@ -17916,8 +17952,8 @@ var Interpreter = class {
17916
17952
  let handle = this.inputs.get(name);
17917
17953
  if (!handle) {
17918
17954
  try {
17919
- const text = this.ctx.vfs.readText(this.ctx.path(name), this.ctx.cred);
17920
- handle = { lines: splitLines(new TextEncoder().encode(text)).lines, index: 0 };
17955
+ const text2 = this.ctx.vfs.readText(this.ctx.path(name), this.ctx.cred);
17956
+ handle = { lines: splitLines(new TextEncoder().encode(text2)).lines, index: 0 };
17921
17957
  } catch {
17922
17958
  return Value.fromNumber(-1);
17923
17959
  }
@@ -17956,8 +17992,8 @@ var Interpreter = class {
17956
17992
  case "print": {
17957
17993
  const ofs = this.toStr(this.getVar("OFS"));
17958
17994
  const ors = this.toStr(this.getVar("ORS"));
17959
- const text = stmt.args.length === 0 ? this.toStr(this.getField(0)) : stmt.args.map((a) => this.outputStr(this.evaluate(a))).join(ofs);
17960
- this.emit(text + ors, stmt.redirect);
17995
+ const text2 = stmt.args.length === 0 ? this.toStr(this.getField(0)) : stmt.args.map((a) => this.outputStr(this.evaluate(a))).join(ofs);
17996
+ this.emit(text2 + ors, stmt.redirect);
17961
17997
  return;
17962
17998
  }
17963
17999
  case "printf": {
@@ -18442,13 +18478,13 @@ var wc = defineCommand({
18442
18478
  const totals = { lines: 0, words: 0, bytes: 0, chars: 0, maxLine: 0 };
18443
18479
  const rows = [];
18444
18480
  for (const source of sources) {
18445
- const text = decoder4.decode(source.bytes);
18481
+ const text2 = decoder4.decode(source.bytes);
18446
18482
  const counts = {
18447
- lines: (text.match(/\n/g) ?? []).length,
18448
- words: text.split(/\s+/).filter((w) => w !== "").length,
18483
+ lines: (text2.match(/\n/g) ?? []).length,
18484
+ words: text2.split(/\s+/).filter((w) => w !== "").length,
18449
18485
  bytes: source.bytes.length,
18450
- chars: [...text].length,
18451
- maxLine: Math.max(0, ...text.split("\n").map((l) => displayWidth(l)))
18486
+ chars: [...text2].length,
18487
+ maxLine: Math.max(0, ...text2.split("\n").map((l) => displayWidth(l)))
18452
18488
  };
18453
18489
  totals.lines += counts.lines;
18454
18490
  totals.words += counts.words;
@@ -18515,15 +18551,15 @@ var sort = defineCommand({
18515
18551
  const slice = fields.slice(start, end === void 0 ? void 0 : end);
18516
18552
  return slice.join(separator ?? " ");
18517
18553
  };
18518
- const normalize2 = (line) => {
18554
+ const normalize3 = (line) => {
18519
18555
  let value = keys.length ? fieldOf(line, keys[0]) : line;
18520
18556
  if (args.has("ignore-leading-blanks")) value = value.replace(/^\s+/, "");
18521
18557
  if (args.has("ignore-case")) value = value.toLowerCase();
18522
18558
  return value;
18523
18559
  };
18524
18560
  const compare = (a, b) => {
18525
- const x = normalize2(a);
18526
- const y = normalize2(b);
18561
+ const x = normalize3(a);
18562
+ const y = normalize3(b);
18527
18563
  if (args.has("numeric-sort") || args.has("general-numeric-sort")) {
18528
18564
  const nx = parseFloat(x) || 0;
18529
18565
  const ny = parseFloat(y) || 0;
@@ -18614,9 +18650,9 @@ var uniq = defineCommand({
18614
18650
  }
18615
18651
  out.push(args.has("count") ? `${String(group.count).padStart(7)} ${group.line}` : group.line);
18616
18652
  }
18617
- const text = joinLines(out, true);
18618
- if (output) ctx.vfs.writeFile(ctx.path(output), text, { cred: ctx.cred });
18619
- else ctx.write(text);
18653
+ const text2 = joinLines(out, true);
18654
+ if (output) ctx.vfs.writeFile(ctx.path(output), text2, { cred: ctx.cred });
18655
+ else ctx.write(text2);
18620
18656
  return ok ? 0 : 1;
18621
18657
  }
18622
18658
  });
@@ -18726,11 +18762,11 @@ var tr = defineCommand({
18726
18762
  if (set1Raw === void 0) return ctx.fail("missing operand", 1);
18727
18763
  const set1 = expandSet(set1Raw);
18728
18764
  const set2 = set2Raw === void 0 ? [] : expandSet(set2Raw);
18729
- const text = decoder4.decode(await ctx.stdin.readAll());
18765
+ const text2 = decoder4.decode(await ctx.stdin.readAll());
18730
18766
  const inSet1 = (ch) => args.has("complement") ? !set1.includes(ch) : set1.includes(ch);
18731
18767
  let out = "";
18732
18768
  let lastEmitted = "";
18733
- for (const ch of text) {
18769
+ for (const ch of text2) {
18734
18770
  if (args.has("delete") && inSet1(ch)) continue;
18735
18771
  let mapped = ch;
18736
18772
  if (!args.has("delete") && set2.length && inSet1(ch)) {
@@ -19401,12 +19437,12 @@ var grep = defineCommand({
19401
19437
  }
19402
19438
  continue;
19403
19439
  }
19404
- let text = lines[i];
19440
+ let text2 = lines[i];
19405
19441
  if (useColor && isMatchLine && !args.has("invert-match")) {
19406
19442
  regex.lastIndex = 0;
19407
- text = text.replace(regex, (m) => `\x1B[1;31m${m}\x1B[0m`);
19443
+ text2 = text2.replace(regex, (m) => `\x1B[1;31m${m}\x1B[0m`);
19408
19444
  }
19409
- ctx.line(prefix + text);
19445
+ ctx.line(prefix + text2);
19410
19446
  lastPrinted = i;
19411
19447
  }
19412
19448
  }
@@ -19414,8 +19450,8 @@ var grep = defineCommand({
19414
19450
  return anyMatch ? status === 2 ? 2 : 0 : status === 2 ? 2 : 1;
19415
19451
  }
19416
19452
  });
19417
- function escapeLiteral(text) {
19418
- return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
19453
+ function escapeLiteral(text2) {
19454
+ return text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
19419
19455
  }
19420
19456
  var find = defineCommand({
19421
19457
  name: "find",
@@ -19764,7 +19800,7 @@ var diff = defineCommand({
19764
19800
  if (a === void 0 || b === void 0) return ctx.fail("missing operand", 2);
19765
19801
  const { sources, ok } = await readInputs(ctx, [a, b]);
19766
19802
  if (!ok || sources.length < 2) return 2;
19767
- const normalize2 = (line) => {
19803
+ const normalize3 = (line) => {
19768
19804
  let value = line;
19769
19805
  if (args.has("ignore-all-space")) value = value.replace(/\s+/g, "");
19770
19806
  else if (args.has("ignore-space-change")) value = value.replace(/\s+/g, " ").trim();
@@ -19773,7 +19809,7 @@ var diff = defineCommand({
19773
19809
  };
19774
19810
  const left = splitLines(sources[0].bytes).lines;
19775
19811
  const right = splitLines(sources[1].bytes).lines;
19776
- const script = diffLines(left.map(normalize2), right.map(normalize2));
19812
+ const script = diffLines(left.map(normalize3), right.map(normalize3));
19777
19813
  if (script.length === 0) return 0;
19778
19814
  if (args.has("brief")) {
19779
19815
  ctx.line(`Files ${a} and ${b} differ`);
@@ -19936,8 +19972,8 @@ function writeString(block, offset, value, length) {
19936
19972
  for (let i = 0; i < length; i++) block[offset + i] = i < bytes.length ? bytes[i] : 0;
19937
19973
  }
19938
19974
  function writeOctal(block, offset, value, length) {
19939
- const text = value.toString(8).padStart(length - 1, "0");
19940
- writeString(block, offset, text, length);
19975
+ const text2 = value.toString(8).padStart(length - 1, "0");
19976
+ writeString(block, offset, text2, length);
19941
19977
  }
19942
19978
  function readString(block, offset, length) {
19943
19979
  let end = offset;
@@ -19945,8 +19981,8 @@ function readString(block, offset, length) {
19945
19981
  return decoder6.decode(block.subarray(offset, end));
19946
19982
  }
19947
19983
  function readOctal(block, offset, length) {
19948
- const text = readString(block, offset, length).trim();
19949
- return text === "" ? 0 : parseInt(text, 8) || 0;
19984
+ const text2 = readString(block, offset, length).trim();
19985
+ return text2 === "" ? 0 : parseInt(text2, 8) || 0;
19950
19986
  }
19951
19987
  function createTar(entries) {
19952
19988
  const blocks = [];
@@ -20341,9 +20377,9 @@ var base64Cmd = defineCommand({
20341
20377
  const { sources, ok } = await readInputs(ctx, args.positional);
20342
20378
  for (const source of sources) {
20343
20379
  if (args.has("decode")) {
20344
- const text = new TextDecoder().decode(source.bytes).replace(/\s+/g, "");
20380
+ const text2 = new TextDecoder().decode(source.bytes).replace(/\s+/g, "");
20345
20381
  try {
20346
- ctx.write(new Uint8Array(Buffer.from(text, "base64")));
20382
+ ctx.write(new Uint8Array(Buffer.from(text2, "base64")));
20347
20383
  } catch {
20348
20384
  return ctx.fail("invalid input");
20349
20385
  }
@@ -20370,11 +20406,11 @@ var base32Cmd = defineCommand({
20370
20406
  const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
20371
20407
  for (const source of sources) {
20372
20408
  if (args.has("decode")) {
20373
- const text = new TextDecoder().decode(source.bytes).replace(/[\s=]/g, "").toUpperCase();
20409
+ const text2 = new TextDecoder().decode(source.bytes).replace(/[\s=]/g, "").toUpperCase();
20374
20410
  const out2 = [];
20375
20411
  let bits2 = 0;
20376
20412
  let value2 = 0;
20377
- for (const ch of text) {
20413
+ for (const ch of text2) {
20378
20414
  const idx = ALPHABET.indexOf(ch);
20379
20415
  if (idx < 0) continue;
20380
20416
  value2 = value2 << 5 | idx;
@@ -21417,8 +21453,8 @@ var man = defineCommand({
21417
21453
  return 0;
21418
21454
  }
21419
21455
  });
21420
- function capitalize(text) {
21421
- return text.length ? text[0].toUpperCase() + text.slice(1) : text;
21456
+ function capitalize(text2) {
21457
+ return text2.length ? text2[0].toUpperCase() + text2.slice(1) : text2;
21422
21458
  }
21423
21459
  var whatis = defineCommand({
21424
21460
  name: "whatis",
@@ -21583,7 +21619,8 @@ async function execute(ctx, invocation) {
21583
21619
  try {
21584
21620
  const proc = await pod.spawn("node", [invocation.script], {
21585
21621
  cwd: ctx.cwd,
21586
- env: { ...ctx.env, PWD: ctx.cwd }
21622
+ env: { ...ctx.env, PWD: ctx.cwd },
21623
+ argv: ["/usr/bin/node", invocation.argvPath ?? invocation.script, ...invocation.argv]
21587
21624
  });
21588
21625
  proc.on("output", (chunk) => {
21589
21626
  try {
@@ -21762,7 +21799,7 @@ Error: Cannot find module '${ctx.path(scriptArg)}'
21762
21799
  mode: 384
21763
21800
  });
21764
21801
  temps.push(sibling);
21765
- return await execute(ctx, { script: sibling, argv: scriptArgs, temps });
21802
+ return await execute(ctx, { script: sibling, argvPath: script, argv: scriptArgs, temps });
21766
21803
  } catch {
21767
21804
  return await execute(ctx, { script, argv: scriptArgs, temps });
21768
21805
  }
@@ -22163,6 +22200,8 @@ var RESERVED_FOR_INTERPRETER = /* @__PURE__ */ new Set(["lib", "dev", "proc"]);
22163
22200
  var pyodideModule = null;
22164
22201
  var indexUrl;
22165
22202
  var moduleUrl;
22203
+ var DEFAULT_BROWSER_INDEX_URL = "https://cdn.jsdelivr.net/pyodide/v0.28.3/full/";
22204
+ var isNode2 = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
22166
22205
  function configureCPython(options = {}) {
22167
22206
  if (options.indexURL !== void 0) indexUrl = options.indexURL;
22168
22207
  if (options.moduleURL !== void 0) {
@@ -22172,19 +22211,27 @@ function configureCPython(options = {}) {
22172
22211
  }
22173
22212
  function importPyodide() {
22174
22213
  if (!pyodideModule) {
22175
- const specifier = moduleUrl ?? ["py", "odide"].join("");
22176
- pyodideModule = import(
22177
- /* @vite-ignore */
22178
- /* webpackIgnore: true */
22179
- specifier
22180
- );
22214
+ if (moduleUrl) {
22215
+ pyodideModule = import(
22216
+ /* @vite-ignore */
22217
+ /* webpackIgnore: true */
22218
+ moduleUrl
22219
+ );
22220
+ } else if (isNode2) {
22221
+ pyodideModule = nodeOnlyModule("pyodide");
22222
+ } else {
22223
+ pyodideModule = import(
22224
+ /* @vite-ignore */
22225
+ /* webpackIgnore: true */
22226
+ `${DEFAULT_BROWSER_INDEX_URL}pyodide.mjs`
22227
+ );
22228
+ }
22181
22229
  }
22182
22230
  return pyodideModule;
22183
22231
  }
22184
- var isNode2 = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
22185
22232
  async function resolveIndexUrl() {
22186
22233
  if (indexUrl) return indexUrl;
22187
- if (!isNode2) return void 0;
22234
+ if (!isNode2) return DEFAULT_BROWSER_INDEX_URL;
22188
22235
  try {
22189
22236
  const { createRequire } = await nodeBuiltin("module");
22190
22237
  const path = await nodeBuiltin("path");
@@ -22309,8 +22356,8 @@ function reportError(ctx, error) {
22309
22356
  ctx.stderr.write("KeyboardInterrupt\n");
22310
22357
  return 130;
22311
22358
  }
22312
- const text = message.replace(/^PythonError:\s*/, "");
22313
- ctx.stderr.write(text.endsWith("\n") ? text : `${text}
22359
+ const text2 = message.replace(/^PythonError:\s*/, "");
22360
+ ctx.stderr.write(text2.endsWith("\n") ? text2 : `${text2}
22314
22361
  `);
22315
22362
  return 1;
22316
22363
  }
@@ -22335,7 +22382,7 @@ async function runCPythonProgram(ctx, source, argv, scriptDir, stdinText) {
22335
22382
  });
22336
22383
  } catch {
22337
22384
  }
22338
- const encoder6 = new TextEncoder();
22385
+ const encoder7 = new TextEncoder();
22339
22386
  const decoder7 = new TextDecoder();
22340
22387
  py.setStdout({
22341
22388
  write: (buffer) => {
@@ -22350,7 +22397,7 @@ async function runCPythonProgram(ctx, source, argv, scriptDir, stdinText) {
22350
22397
  }
22351
22398
  });
22352
22399
  if (stdinText !== null) {
22353
- const bytes = encoder6.encode(stdinText);
22400
+ const bytes = encoder7.encode(stdinText);
22354
22401
  let offset = 0;
22355
22402
  py.setStdin({
22356
22403
  read: (buffer) => {
@@ -22723,8 +22770,8 @@ function renameShadowedExports(source) {
22723
22770
  const replacement = freshName(source);
22724
22771
  let out = source;
22725
22772
  for (const target of [...targets].sort((a, b) => b.start - a.start)) {
22726
- const text = target.shorthand ? `${NAME}: ${replacement}` : replacement;
22727
- out = out.slice(0, target.start) + text + out.slice(target.end);
22773
+ const text2 = target.shorthand ? `${NAME}: ${replacement}` : replacement;
22774
+ out = out.slice(0, target.start) + text2 + out.slice(target.end);
22728
22775
  }
22729
22776
  return out;
22730
22777
  function visit(node2, scope) {
@@ -22943,11 +22990,11 @@ function splitPackageSpec(spec) {
22943
22990
  return { name: spec.slice(0, at), version: spec.slice(at + 1) };
22944
22991
  }
22945
22992
  async function installPackages(ctx, specs, opts) {
22946
- const installer = opts.cwd === "/" ? ctx.kernel.pod.packages : new nodepod.DependencyInstaller(ctx.vfs.volume, { cwd: opts.cwd });
22993
+ const installer = opts.cwd === "/" ? ctx.kernel.pod.packages : ctx.kernel.pod.packages.forCwd?.(opts.cwd) ?? new nodepod.DependencyInstaller(ctx.vfs.volume, { cwd: opts.cwd });
22947
22994
  const onProgress = (message) => {
22948
22995
  if (!opts.quiet) ctx.stderr.write(message.endsWith("\n") ? message : message + "\n");
22949
22996
  };
22950
- const note = (text) => opts.quiet ? ctx.stderr.write(text + "\n") : ctx.line(text);
22997
+ const note = (text2) => opts.quiet ? ctx.stderr.write(text2 + "\n") : ctx.line(text2);
22951
22998
  if (!ctx.kernel.net.options.allowOutbound) {
22952
22999
  ctx.warn("npm error code ENOTFOUND");
22953
23000
  ctx.warn("npm error network request to https://registry.npmjs.org failed");
@@ -23002,7 +23049,13 @@ var npm = defineCommand({
23002
23049
  case "version":
23003
23050
  ctx.line(NPM_VERSION);
23004
23051
  return 0;
23052
+ /* `npm create vite@latest` and `npm init vite` are the same command, and
23053
+ * both are `npx` against a conventionally-named package. Only a bare
23054
+ * `npm init` with no initializer writes a package.json. */
23055
+ case "create":
23056
+ return await runInitializer(ctx, rest);
23005
23057
  case "init": {
23058
+ if (rest[0] && !rest[0].startsWith("-")) return await runInitializer(ctx, rest);
23006
23059
  const existing = readManifest(ctx, ctx.cwd);
23007
23060
  if (existing && !rest.includes("-f") && !rest.includes("--force")) {
23008
23061
  ctx.warn("package.json already exists");
@@ -23184,9 +23237,9 @@ function normalizeBinDirectories(ctx, root) {
23184
23237
  const st = ctx.vfs.lstat(path);
23185
23238
  if (st.isDirectory()) continue;
23186
23239
  if (!st.isSymbolicLink()) {
23187
- const text = ctx.vfs.readText(path, ctx.cred);
23188
- if (!text.startsWith("#!")) {
23189
- ctx.vfs.writeFile(path, "#!/bin/sh\n" + text, { privileged: true, mode: 493 });
23240
+ const text2 = ctx.vfs.readText(path, ctx.cred);
23241
+ if (!text2.startsWith("#!")) {
23242
+ ctx.vfs.writeFile(path, "#!/bin/sh\n" + text2, { privileged: true, mode: 493 });
23190
23243
  }
23191
23244
  }
23192
23245
  ctx.vfs.chmod(path, 493, ctx.cred);
@@ -23252,6 +23305,26 @@ function findLocalBin(ctx, name) {
23252
23305
  }
23253
23306
  return null;
23254
23307
  }
23308
+ async function runInitializer(ctx, args) {
23309
+ const [spec, ...rest] = args;
23310
+ const { name, version } = splitPackageSpec(spec);
23311
+ const suffix = version ? `@${version}` : "";
23312
+ let packageName;
23313
+ if (!name.startsWith("@")) {
23314
+ packageName = `create-${name}`;
23315
+ } else if (name.includes("/")) {
23316
+ const [scope, unscoped2] = name.split("/");
23317
+ packageName = `${scope}/create-${unscoped2}`;
23318
+ } else {
23319
+ packageName = `${name}/create`;
23320
+ }
23321
+ const forwarded = rest.filter((argument) => argument !== "--");
23322
+ return await npx.run({
23323
+ ...ctx,
23324
+ args: ["-y", "--package", `${packageName}${suffix}`, basename(packageName), ...forwarded],
23325
+ argv: ["npx", ...forwarded]
23326
+ });
23327
+ }
23255
23328
  var npx = defineCommand({
23256
23329
  name: "npx",
23257
23330
  path: "/usr/bin/npx",
@@ -23696,16 +23769,16 @@ var Session = class {
23696
23769
  const combined = [];
23697
23770
  const decoder7 = new TextDecoder();
23698
23771
  const stdout = new BufferSink((chunk) => {
23699
- const text = decoder7.decode(chunk, { stream: true });
23700
- combined.push(text);
23701
- opts.onStdout?.(text);
23702
- this.hooks.onStdout?.(text);
23772
+ const text2 = decoder7.decode(chunk, { stream: true });
23773
+ combined.push(text2);
23774
+ opts.onStdout?.(text2);
23775
+ this.hooks.onStdout?.(text2);
23703
23776
  });
23704
23777
  const stderr = new BufferSink((chunk) => {
23705
- const text = decoder7.decode(chunk, { stream: true });
23706
- combined.push(text);
23707
- opts.onStderr?.(text);
23708
- this.hooks.onStderr?.(text);
23778
+ const text2 = decoder7.decode(chunk, { stream: true });
23779
+ combined.push(text2);
23780
+ opts.onStderr?.(text2);
23781
+ this.hooks.onStderr?.(text2);
23709
23782
  });
23710
23783
  if (opts.tty) {
23711
23784
  stdout.isTTY = true;
@@ -23841,9 +23914,9 @@ var KernelChildProcess = class {
23841
23914
  this.exitCode = code;
23842
23915
  this.emit("exit", code);
23843
23916
  }
23844
- append(stream, text) {
23845
- this[stream] += text;
23846
- this.emit(stream, text);
23917
+ append(stream, text2) {
23918
+ this[stream] += text2;
23919
+ this.emit(stream, text2);
23847
23920
  }
23848
23921
  };
23849
23922
  var ChildOutput = class {
@@ -23861,8 +23934,8 @@ var ChildOutput = class {
23861
23934
  }
23862
23935
  write(data) {
23863
23936
  if (this.closedState) return;
23864
- const text = typeof data === "string" ? data : this.decoder.decode(data, { stream: true });
23865
- if (text) this.child.append(this.stream, text);
23937
+ const text2 = typeof data === "string" ? data : this.decoder.decode(data, { stream: true });
23938
+ if (text2) this.child.append(this.stream, text2);
23866
23939
  }
23867
23940
  end() {
23868
23941
  if (this.closedState) return;
@@ -23888,6 +23961,3286 @@ function installNodeChildProcessBridge(pod, kernel, cred) {
23888
23961
  };
23889
23962
  }
23890
23963
 
23964
+ // src/runtime/commonjs-engine.ts
23965
+ init_path();
23966
+ var HELPERS = {
23967
+ /** Import a specifier and return an ES-module-shaped namespace. */
23968
+ import: "__sbxImport",
23969
+ /** `import(...)`, returning a promise of a namespace. */
23970
+ dynamic: "__sbxDynamicImport",
23971
+ /** `export * from` — copy live bindings onto `exports`. */
23972
+ exportAll: "__sbxExportAll",
23973
+ /** `import.meta`. */
23974
+ meta: "__sbxMeta",
23975
+ /**
23976
+ * The exports object, under a name of the engine's choosing.
23977
+ *
23978
+ * An ES module is free to declare its own top-level `exports`, `require` or
23979
+ * `__dirname` — they are ordinary identifiers there, and real packages use
23980
+ * all three (`const require = createRequire(import.meta.url)` is close to
23981
+ * idiomatic). Naming the wrapper's binding something no source would write
23982
+ * removes that entire class of collision instead of patching it up after a
23983
+ * `SyntaxError`.
23984
+ */
23985
+ exports: "__sbxExports"
23986
+ };
23987
+ var DEFAULT_LOCAL = "__sbxDefault";
23988
+ var MAYBE_ESM = /(^|[\s;}(])(?:import|export)(?:[\s({[*"']|$)|\bimport\s*\.\s*meta\b/;
23989
+ function looksLikeEsm(source) {
23990
+ return MAYBE_ESM.test(source);
23991
+ }
23992
+ function transformEsm(source, filename = "module.js") {
23993
+ if (!looksLikeEsm(source)) return null;
23994
+ let ast;
23995
+ try {
23996
+ ast = parseModule(source, filename);
23997
+ } catch {
23998
+ return null;
23999
+ }
24000
+ const body = ast.body;
24001
+ const hasModuleSyntax = body.some(
24002
+ (node2) => node2.type.startsWith("Import") || node2.type.startsWith("Export")
24003
+ );
24004
+ const usesImportMeta = !hasModuleSyntax && containsImportMeta(ast);
24005
+ const esm = hasModuleSyntax || usesImportMeta;
24006
+ if (!esm && !containsImportExpression(ast)) return null;
24007
+ const edits = [];
24008
+ const prelude = [];
24009
+ const importBindings = /* @__PURE__ */ new Map();
24010
+ const exportGetters = /* @__PURE__ */ new Map();
24011
+ let namespaceCount = 0;
24012
+ const namespaceFor = (specifier) => {
24013
+ const id = `__sbxNs${namespaceCount++}`;
24014
+ prelude.push(`var ${id} = ${HELPERS.import}(${JSON.stringify(specifier)});`);
24015
+ return id;
24016
+ };
24017
+ for (const node2 of body) {
24018
+ if (node2.type === "ImportDeclaration") collectImport(node2);
24019
+ }
24020
+ for (const node2 of body) {
24021
+ switch (node2.type) {
24022
+ case "ExportNamedDeclaration":
24023
+ collectNamedExport(node2);
24024
+ break;
24025
+ case "ExportDefaultDeclaration":
24026
+ collectDefaultExport(node2);
24027
+ break;
24028
+ case "ExportAllDeclaration":
24029
+ collectExportAll(node2);
24030
+ break;
24031
+ }
24032
+ }
24033
+ rewriteReferences();
24034
+ const header = esm ? [
24035
+ `Object.defineProperty(${HELPERS.exports}, "__esModule", { value: true });`,
24036
+ ...prelude,
24037
+ ...[...exportGetters].map(
24038
+ ([name, expression]) => `Object.defineProperty(${HELPERS.exports}, ${JSON.stringify(name)}, { enumerable: true, configurable: true, get: function () { return ${expression}; } });`
24039
+ )
24040
+ ].join("\n") : "";
24041
+ return {
24042
+ code: header ? `${header}
24043
+ ${applyEdits(source, edits)}` : applyEdits(source, edits),
24044
+ esm,
24045
+ topLevelAwait: hasTopLevelAwait(ast)
24046
+ };
24047
+ function collectImport(node2) {
24048
+ const specifier = node2.source.value;
24049
+ const specifiers = node2.specifiers ?? [];
24050
+ const id = namespaceFor(specifier);
24051
+ for (const entry of specifiers) {
24052
+ const local = entry.local.name ?? "";
24053
+ if (entry.type === "ImportDefaultSpecifier") {
24054
+ importBindings.set(local, `${id}.default`);
24055
+ } else if (entry.type === "ImportNamespaceSpecifier") {
24056
+ importBindings.set(local, id);
24057
+ } else {
24058
+ const imported = entry.imported;
24059
+ const name = imported.type === "Identifier" ? imported.name : imported.value;
24060
+ importBindings.set(local, `${id}[${JSON.stringify(name)}]`);
24061
+ }
24062
+ }
24063
+ drop(node2);
24064
+ }
24065
+ function collectNamedExport(node2) {
24066
+ const declaration = node2.declaration;
24067
+ if (declaration) {
24068
+ for (const name of declaredNames(declaration)) exportGetters.set(name, name);
24069
+ edits.push({ start: node2.start, end: declaration.start, text: "" });
24070
+ return;
24071
+ }
24072
+ const source_ = node2.source;
24073
+ const id = source_ ? namespaceFor(source_.value) : null;
24074
+ for (const entry of node2.specifiers ?? []) {
24075
+ const local = nameOf(entry.local);
24076
+ const exported = nameOf(entry.exported);
24077
+ const read = id ? `${id}[${JSON.stringify(local)}]` : importBindings.get(local) ?? local;
24078
+ exportGetters.set(exported, read);
24079
+ }
24080
+ drop(node2);
24081
+ }
24082
+ function collectDefaultExport(node2) {
24083
+ const declaration = node2.declaration;
24084
+ const isDeclaration = declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration";
24085
+ if (isDeclaration) {
24086
+ const named = declaration.id;
24087
+ if (named) {
24088
+ exportGetters.set("default", named.name);
24089
+ edits.push({ start: node2.start, end: declaration.start, text: "" });
24090
+ return;
24091
+ }
24092
+ const keyword = declaration.type === "FunctionDeclaration" ? "function" : "class";
24093
+ const keywordEnd = source.indexOf(keyword, declaration.start) + keyword.length;
24094
+ exportGetters.set("default", DEFAULT_LOCAL);
24095
+ edits.push({ start: node2.start, end: declaration.start, text: "" });
24096
+ edits.push({ start: keywordEnd, end: keywordEnd, text: ` ${DEFAULT_LOCAL}` });
24097
+ return;
24098
+ }
24099
+ exportGetters.set("default", DEFAULT_LOCAL);
24100
+ edits.push({ start: node2.start, end: declaration.start, text: `var ${DEFAULT_LOCAL} = ` });
24101
+ edits.push({ start: node2.end, end: node2.end, text: ";" });
24102
+ }
24103
+ function collectExportAll(node2) {
24104
+ const id = namespaceFor(node2.source.value);
24105
+ const exported = node2.exported;
24106
+ if (exported) exportGetters.set(nameOf(exported), id);
24107
+ else prelude.push(`${HELPERS.exportAll}(${HELPERS.exports}, ${id});`);
24108
+ drop(node2);
24109
+ }
24110
+ function drop(node2) {
24111
+ edits.push({ start: node2.start, end: node2.end, text: "" });
24112
+ }
24113
+ function rewriteReferences() {
24114
+ const programScope = { names: new Set(importBindings.keys()), parent: null };
24115
+ visit(ast, programScope, true);
24116
+ function visit(node2, scope, isProgram = false) {
24117
+ let childScope = scope;
24118
+ let skip = NOTHING2;
24119
+ switch (node2.type) {
24120
+ case "ImportDeclaration":
24121
+ case "ExportAllDeclaration":
24122
+ return;
24123
+ case "ExportNamedDeclaration":
24124
+ if (!node2.declaration) return;
24125
+ break;
24126
+ case "FunctionDeclaration":
24127
+ case "FunctionExpression":
24128
+ case "ArrowFunctionExpression": {
24129
+ const names = /* @__PURE__ */ new Set();
24130
+ for (const param of node2.params ?? []) collectPattern2(param, names);
24131
+ const id = node2.id;
24132
+ if (id && node2.type === "FunctionExpression") names.add(id.name);
24133
+ const fnBody = node2.body;
24134
+ if (fnBody?.type === "BlockStatement") {
24135
+ for (const name of hoistedNames2(fnBody.body)) names.add(name);
24136
+ }
24137
+ childScope = { names, parent: scope };
24138
+ break;
24139
+ }
24140
+ case "CatchClause": {
24141
+ const names = /* @__PURE__ */ new Set();
24142
+ if (node2.param) collectPattern2(node2.param, names);
24143
+ childScope = { names, parent: scope };
24144
+ break;
24145
+ }
24146
+ case "ClassExpression": {
24147
+ const id = node2.id;
24148
+ if (id) childScope = { names: /* @__PURE__ */ new Set([id.name]), parent: scope };
24149
+ break;
24150
+ }
24151
+ case "BlockStatement":
24152
+ case "StaticBlock":
24153
+ if (!isProgram) {
24154
+ childScope = { names: blockNames2(node2.body), parent: scope };
24155
+ }
24156
+ break;
24157
+ case "ForStatement":
24158
+ case "ForInStatement":
24159
+ case "ForOfStatement": {
24160
+ const head2 = node2.init ?? node2.left;
24161
+ if (head2?.type === "VariableDeclaration" && head2.kind !== "var") {
24162
+ const names = /* @__PURE__ */ new Set();
24163
+ for (const declarator of head2.declarations) {
24164
+ collectPattern2(declarator.id, names);
24165
+ }
24166
+ childScope = { names, parent: scope };
24167
+ }
24168
+ break;
24169
+ }
24170
+ case "MetaProperty":
24171
+ edits.push({ start: node2.start, end: node2.end, text: HELPERS.meta });
24172
+ return;
24173
+ case "ImportExpression": {
24174
+ const argument = node2.source;
24175
+ edits.push({ start: node2.start, end: argument.start, text: `${HELPERS.dynamic}(` });
24176
+ visit(argument, childScope);
24177
+ edits.push({ start: argument.end, end: node2.end, text: ")" });
24178
+ return;
24179
+ }
24180
+ case "Identifier": {
24181
+ const replacement = lookup(node2.name, scope);
24182
+ if (replacement) edits.push({ start: node2.start, end: node2.end, text: replacement });
24183
+ return;
24184
+ }
24185
+ case "MemberExpression":
24186
+ case "MethodDefinition":
24187
+ case "PropertyDefinition":
24188
+ skip = node2.computed ? NOTHING2 : PROPERTY2;
24189
+ break;
24190
+ case "Property": {
24191
+ if (node2.computed) break;
24192
+ if (node2.shorthand) {
24193
+ const value = node2.value;
24194
+ if (value.type === "Identifier") {
24195
+ const replacement = lookup(value.name, scope);
24196
+ if (replacement) {
24197
+ edits.push({ start: value.start, end: value.end, text: `${value.name}: ${replacement}` });
24198
+ return;
24199
+ }
24200
+ }
24201
+ break;
24202
+ }
24203
+ skip = PROPERTY2;
24204
+ break;
24205
+ }
24206
+ case "LabeledStatement":
24207
+ case "BreakStatement":
24208
+ case "ContinueStatement":
24209
+ skip = LABEL2;
24210
+ break;
24211
+ }
24212
+ for (const [key, value] of Object.entries(node2)) {
24213
+ if (key === "type" || key === "start" || key === "end" || skip.includes(key)) continue;
24214
+ if (Array.isArray(value)) {
24215
+ for (const item of value) if (isNode4(item)) visit(item, childScope);
24216
+ } else if (isNode4(value)) {
24217
+ visit(value, childScope);
24218
+ }
24219
+ }
24220
+ }
24221
+ function lookup(name, scope) {
24222
+ for (let current = scope; current; current = current.parent) {
24223
+ if (current.names.has(name)) {
24224
+ return current.parent === null ? importBindings.get(name) ?? null : null;
24225
+ }
24226
+ }
24227
+ return null;
24228
+ }
24229
+ }
24230
+ }
24231
+ var JSX_EXTENSION = /\.[jt]sx$/;
24232
+ var JsxParser = acorn.Parser.extend(jsx__default.default());
24233
+ var PARSE_OPTIONS = {
24234
+ ecmaVersion: "latest",
24235
+ sourceType: "module",
24236
+ allowAwaitOutsideFunction: true,
24237
+ allowHashBang: true,
24238
+ allowReturnOutsideFunction: true
24239
+ };
24240
+ function parseModule(source, filename) {
24241
+ const parser = JSX_EXTENSION.test(filename) ? JsxParser.parse.bind(JsxParser) : acorn.parse;
24242
+ return parser(source, PARSE_OPTIONS);
24243
+ }
24244
+ function containsImportExpression(node2) {
24245
+ if (Array.isArray(node2)) return node2.some(containsImportExpression);
24246
+ if (!isNode4(node2)) return false;
24247
+ if (node2.type === "ImportExpression") return true;
24248
+ for (const [key, value] of Object.entries(node2)) {
24249
+ if (key === "type" || key === "start" || key === "end") continue;
24250
+ if (containsImportExpression(value)) return true;
24251
+ }
24252
+ return false;
24253
+ }
24254
+ function containsImportMeta(node2) {
24255
+ if (Array.isArray(node2)) return node2.some(containsImportMeta);
24256
+ if (!isNode4(node2)) return false;
24257
+ if (node2.type === "MetaProperty") return true;
24258
+ for (const [key, value] of Object.entries(node2)) {
24259
+ if (key === "type" || key === "start" || key === "end") continue;
24260
+ if (containsImportMeta(value)) return true;
24261
+ }
24262
+ return false;
24263
+ }
24264
+ function hasTopLevelAwait(node2) {
24265
+ if (Array.isArray(node2)) return node2.some(hasTopLevelAwait);
24266
+ if (!isNode4(node2)) return false;
24267
+ if (node2.type === "FunctionDeclaration" || node2.type === "FunctionExpression" || node2.type === "ArrowFunctionExpression") {
24268
+ return false;
24269
+ }
24270
+ if (node2.type === "AwaitExpression") return true;
24271
+ if (node2.type === "ForOfStatement" && node2.await === true) return true;
24272
+ for (const [key, value] of Object.entries(node2)) {
24273
+ if (key === "type" || key === "start" || key === "end") continue;
24274
+ if (hasTopLevelAwait(value)) return true;
24275
+ }
24276
+ return false;
24277
+ }
24278
+ function declaredNames(declaration) {
24279
+ const names = /* @__PURE__ */ new Set();
24280
+ if (declaration.type === "VariableDeclaration") {
24281
+ for (const declarator of declaration.declarations) {
24282
+ collectPattern2(declarator.id, names);
24283
+ }
24284
+ } else if (isNode4(declaration.id)) {
24285
+ names.add(declaration.id.name);
24286
+ }
24287
+ return [...names];
24288
+ }
24289
+ function nameOf(node2) {
24290
+ return node2.type === "Identifier" ? node2.name : node2.value;
24291
+ }
24292
+ function hoistedNames2(body) {
24293
+ const names = blockNames2(body);
24294
+ collectVars2(body, names);
24295
+ return names;
24296
+ }
24297
+ function blockNames2(body) {
24298
+ const names = /* @__PURE__ */ new Set();
24299
+ for (const node2 of body ?? []) {
24300
+ if (node2.type === "VariableDeclaration" && node2.kind !== "var") {
24301
+ for (const declarator of node2.declarations) {
24302
+ collectPattern2(declarator.id, names);
24303
+ }
24304
+ } else if ((node2.type === "ClassDeclaration" || node2.type === "FunctionDeclaration") && isNode4(node2.id)) {
24305
+ names.add(node2.id.name);
24306
+ }
24307
+ }
24308
+ return names;
24309
+ }
24310
+ function collectVars2(nodes, names) {
24311
+ if (Array.isArray(nodes)) {
24312
+ for (const item of nodes) collectVars2(item, names);
24313
+ return;
24314
+ }
24315
+ if (!isNode4(nodes)) return;
24316
+ const node2 = nodes;
24317
+ if (node2.type === "FunctionDeclaration" || node2.type === "FunctionExpression" || node2.type === "ArrowFunctionExpression") {
24318
+ if (isNode4(node2.id)) names.add(node2.id.name);
24319
+ return;
24320
+ }
24321
+ if (node2.type === "VariableDeclaration" && node2.kind === "var") {
24322
+ for (const declarator of node2.declarations) {
24323
+ collectPattern2(declarator.id, names);
24324
+ }
24325
+ }
24326
+ for (const [key, value] of Object.entries(node2)) {
24327
+ if (key === "type" || key === "start" || key === "end") continue;
24328
+ collectVars2(value, names);
24329
+ }
24330
+ }
24331
+ function collectPattern2(node2, names) {
24332
+ if (!isNode4(node2)) return;
24333
+ switch (node2.type) {
24334
+ case "Identifier":
24335
+ names.add(node2.name);
24336
+ return;
24337
+ case "ObjectPattern":
24338
+ for (const property of node2.properties) {
24339
+ collectPattern2(property.value ?? property.argument, names);
24340
+ }
24341
+ return;
24342
+ case "ArrayPattern":
24343
+ for (const element of node2.elements) collectPattern2(element, names);
24344
+ return;
24345
+ case "AssignmentPattern":
24346
+ collectPattern2(node2.left, names);
24347
+ return;
24348
+ case "RestElement":
24349
+ collectPattern2(node2.argument, names);
24350
+ return;
24351
+ default:
24352
+ return;
24353
+ }
24354
+ }
24355
+ function applyEdits(source, edits) {
24356
+ const ordered = [...edits].sort((a, b) => b.start - a.start || b.end - a.end);
24357
+ let out = source;
24358
+ for (const edit of ordered) out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
24359
+ return out;
24360
+ }
24361
+ function isNode4(value) {
24362
+ return typeof value === "object" && value !== null && typeof value.type === "string";
24363
+ }
24364
+ var NOTHING2 = [];
24365
+ var PROPERTY2 = ["property", "key"];
24366
+ var LABEL2 = ["label"];
24367
+ var EXTENSIONS = [".js", ".mjs", ".cjs", ".json", ".node"];
24368
+ var CONDITION_SETS = {
24369
+ import: [["node", "import", "module", "default"], ["node", "require", "default"], ["default"]],
24370
+ require: [["node", "require", "default"], ["node", "import", "module", "default"], ["default"]]
24371
+ };
24372
+ var ENTRY_FIELDS = {
24373
+ import: ["module", "main"],
24374
+ require: ["main", "module"]
24375
+ };
24376
+ var CommonJsEngine = class {
24377
+ constructor(volume, options = {}) {
24378
+ this.volume = volume;
24379
+ this.cwd = options.cwd ?? "/";
24380
+ this.builtins = { ...options.builtins };
24381
+ this.globals = { ...options.globals };
24382
+ this.aliases = { ...options.aliases };
24383
+ this.overrides = { ...options.overrides };
24384
+ }
24385
+ volume;
24386
+ cache = /* @__PURE__ */ new Map();
24387
+ builtins;
24388
+ globals;
24389
+ aliases;
24390
+ overrides;
24391
+ cwd;
24392
+ main = null;
24393
+ /** `package.json` per directory; resolution reads them constantly. */
24394
+ manifests = /* @__PURE__ */ new Map();
24395
+ /**
24396
+ * Evaluate an entry point.
24397
+ *
24398
+ * Returns the module's exports, or a promise for them when the entry is an
24399
+ * ES module with a top-level `await` — the caller has to await that before
24400
+ * treating the program as finished.
24401
+ */
24402
+ run(entry) {
24403
+ const operand = entry.startsWith("/") || entry.startsWith("./") || entry.startsWith("../") ? entry : `./${entry}`;
24404
+ const filename = this.resolve(operand, join(this.cwd, "__entry__.js"));
24405
+ const module = this.load(filename, null, true);
24406
+ return module.pending ? module.pending.then(() => module.exports) : module.exports;
24407
+ }
24408
+ require(specifier, importer = join(this.cwd, "__entry__.js")) {
24409
+ const builtin = this.builtin(specifier);
24410
+ if (builtin.found) return builtin.value;
24411
+ const target = this.load(this.resolve(specifier, importer), this.cache.get(importer) ?? null, false);
24412
+ if (target.pending) throw requireOfAsyncModule(specifier);
24413
+ return target.exports;
24414
+ }
24415
+ resolve(specifier, importer, kind = "require") {
24416
+ const builtin = this.builtin(specifier);
24417
+ if (builtin.found) return specifier.replace(/^node:/, "");
24418
+ if (specifier.startsWith("#")) {
24419
+ const found = this.resolveImports(specifier, importer, kind);
24420
+ if (found) return found;
24421
+ throw this.moduleNotFound(specifier, importer);
24422
+ }
24423
+ const baseDir = dirname(importer);
24424
+ if (specifier.startsWith("/") || specifier.startsWith("./") || specifier.startsWith("../")) {
24425
+ const resolved = specifier.startsWith("/") ? clean(specifier) : resolve(baseDir, specifier);
24426
+ const found = this.resolvePath(resolved, kind);
24427
+ if (found) return found;
24428
+ } else {
24429
+ const aliased = this.aliasFor(specifier);
24430
+ if (aliased) {
24431
+ const substituted = this.resolvePackage(aliased, baseDir, kind);
24432
+ if (substituted) return substituted;
24433
+ }
24434
+ const found = this.resolvePackage(specifier, baseDir, kind);
24435
+ if (found) return found;
24436
+ }
24437
+ throw this.moduleNotFound(specifier, importer);
24438
+ }
24439
+ load(filename, parent, isMain) {
24440
+ const cached2 = this.cache.get(filename);
24441
+ if (cached2) return cached2;
24442
+ const module = {
24443
+ id: isMain ? "." : filename,
24444
+ filename,
24445
+ exports: {},
24446
+ loaded: false,
24447
+ parent,
24448
+ children: []
24449
+ };
24450
+ this.cache.set(filename, module);
24451
+ parent?.children.push(module);
24452
+ if (isMain) this.main = module;
24453
+ try {
24454
+ if (filename.endsWith(".node")) {
24455
+ throw dlopenFailed(filename);
24456
+ } else if (filename.endsWith(".json")) {
24457
+ module.exports = JSON.parse(this.readText(filename));
24458
+ } else {
24459
+ this.evaluate(module, this.readText(filename));
24460
+ }
24461
+ module.loaded = true;
24462
+ return module;
24463
+ } catch (error) {
24464
+ this.cache.delete(filename);
24465
+ if (isMain) this.main = null;
24466
+ throw error;
24467
+ }
24468
+ }
24469
+ evaluate(module, source) {
24470
+ if (source.startsWith("#!")) source = source.replace(/^#![^\n]*(?:\n|$)/, "");
24471
+ const transformed = transformEsm(source, module.filename);
24472
+ const body = transformed?.code ?? source;
24473
+ const code = transformed?.topLevelAwait ? `return (async () => {
24474
+ ${body}
24475
+ })();` : body;
24476
+ const helpers = [
24477
+ [HELPERS.import, (specifier) => this.importNamespace(specifier, module)],
24478
+ [HELPERS.dynamic, (specifier) => this.dynamicImport(specifier, module)],
24479
+ [HELPERS.exportAll, exportAll],
24480
+ [HELPERS.meta, this.importMeta(module)]
24481
+ ];
24482
+ const bindings = transformed?.esm ? [[HELPERS.exports, module.exports], ...helpers] : [
24483
+ ["exports", module.exports],
24484
+ ["require", this.makeRequire(module)],
24485
+ ["module", module],
24486
+ ["__filename", module.filename],
24487
+ ["__dirname", dirname(module.filename)],
24488
+ ...helpers
24489
+ ];
24490
+ const globalNames = Object.keys(this.globals);
24491
+ const factory = new Function(
24492
+ "__sbxGlobals",
24493
+ `"use strict";
24494
+ ` + (globalNames.length ? `const { ${globalNames.join(", ")} } = __sbxGlobals;
24495
+ ` : "") + `return function (${bindings.map(([name]) => name).join(", ")}) {
24496
+ ${code}
24497
+ };
24498
+ //# sourceURL=sandboxedjs:${module.filename}`
24499
+ )(this.globals);
24500
+ const result = factory(...bindings.map(([, value]) => value));
24501
+ if (transformed?.topLevelAwait) module.pending = Promise.resolve(result).then(() => {
24502
+ });
24503
+ }
24504
+ /** The `require` a module sees, complete with `resolve`, `cache` and `main`. */
24505
+ makeRequire(module) {
24506
+ const localRequire = ((specifier) => {
24507
+ const builtin = this.builtin(specifier, module);
24508
+ if (builtin.found) return builtin.value;
24509
+ const target = this.load(this.resolve(specifier, module.filename, "require"), module, false);
24510
+ if (target.pending) throw requireOfAsyncModule(specifier);
24511
+ return target.exports;
24512
+ });
24513
+ localRequire.resolve = (specifier) => this.resolve(specifier, module.filename, "require");
24514
+ Object.defineProperty(localRequire, "main", { get: () => this.main });
24515
+ localRequire.cache = Object.fromEntries(this.cache);
24516
+ return localRequire;
24517
+ }
24518
+ /**
24519
+ * Load `specifier` and present it as an ES module namespace.
24520
+ *
24521
+ * A static `import` is synchronous here, exactly as the CommonJS `require`
24522
+ * it compiles down to. That is the one place this engine knowingly differs
24523
+ * from Node's real ESM semantics, and it is the trade that lets both module
24524
+ * systems share a single cache and resolver.
24525
+ */
24526
+ importNamespace(specifier, importer) {
24527
+ const builtin = this.builtin(specifier, importer);
24528
+ if (builtin.found) return namespaceOf(builtin.value);
24529
+ const target = this.load(this.resolve(specifier, importer.filename, "import"), importer, false);
24530
+ if (target.pending) throw requireOfAsyncModule(specifier);
24531
+ return namespaceOf(target.exports);
24532
+ }
24533
+ /** `import(...)`: the same load, but able to await a top-level `await`. */
24534
+ async dynamicImport(specifier, importer) {
24535
+ const builtin = this.builtin(specifier, importer);
24536
+ if (builtin.found) return namespaceOf(builtin.value);
24537
+ const target = this.load(this.resolve(specifier, importer.filename, "import"), importer, false);
24538
+ if (target.pending) await target.pending;
24539
+ return namespaceOf(target.exports);
24540
+ }
24541
+ /** `import.meta` for a module. */
24542
+ importMeta(module) {
24543
+ return {
24544
+ url: fileUrl(module.filename),
24545
+ filename: module.filename,
24546
+ dirname: dirname(module.filename),
24547
+ resolve: (specifier) => fileUrl(this.resolve(specifier, module.filename, "import"))
24548
+ };
24549
+ }
24550
+ /**
24551
+ * The substituted specifier for `specifier`, or null when none applies.
24552
+ *
24553
+ * An alias names a package, so a subpath rides along: aliasing `rollup` also
24554
+ * redirects `rollup/dist/native.js` into the substitute.
24555
+ */
24556
+ aliasFor(specifier) {
24557
+ const { name, subpath } = splitSpecifier(specifier);
24558
+ const target = this.aliases[name];
24559
+ if (!target) return null;
24560
+ return subpath ? `${target}/${subpath}` : target;
24561
+ }
24562
+ /**
24563
+ * Resolve a bare specifier (`pkg`, `@scope/pkg`, `pkg/sub`) by walking
24564
+ * `node_modules` up from the importer, exactly as Node does.
24565
+ */
24566
+ resolvePackage(specifier, from, kind) {
24567
+ const { name, subpath } = splitSpecifier(specifier);
24568
+ for (let dir3 = from; ; dir3 = dirname(dir3)) {
24569
+ const root = join(dir3, "node_modules", name);
24570
+ if (this.isDirectory(root)) {
24571
+ const resolved = this.resolveInPackage(root, subpath, kind);
24572
+ if (resolved) return resolved;
24573
+ }
24574
+ if (dir3 === "/") return null;
24575
+ }
24576
+ }
24577
+ /**
24578
+ * Resolve `subpath` ("" for the package root) inside an installed package.
24579
+ *
24580
+ * An `exports` map, when present, is authoritative: Node refuses paths it
24581
+ * does not name, and packages rely on that to keep their internals private.
24582
+ * Only a package without one falls back to `main`/`module` and to treating
24583
+ * the subpath as a plain file path.
24584
+ */
24585
+ resolveInPackage(root, subpath, kind) {
24586
+ const manifest = this.readManifest(root);
24587
+ const entry = subpath ? `./${subpath}` : ".";
24588
+ if (manifest?.exports !== void 0) {
24589
+ for (const conditions of CONDITION_SETS[kind]) {
24590
+ let targets;
24591
+ try {
24592
+ targets = resolve_exports.exports(manifest, entry, { conditions, unsafe: true });
24593
+ } catch {
24594
+ continue;
24595
+ }
24596
+ for (const target of targets ?? []) {
24597
+ const found = this.resolvePath(resolve(root, target), kind);
24598
+ if (found) return found;
24599
+ }
24600
+ }
24601
+ return null;
24602
+ }
24603
+ if (subpath) return this.resolvePath(join(root, subpath), kind);
24604
+ for (const field of ENTRY_FIELDS[kind]) {
24605
+ const value = manifest?.[field];
24606
+ if (typeof value === "string") {
24607
+ const found = this.resolvePath(resolve(root, value), kind);
24608
+ if (found) return found;
24609
+ }
24610
+ }
24611
+ return this.resolveIndex(root);
24612
+ }
24613
+ /**
24614
+ * Resolve a `#private` specifier through the importing package's `imports`
24615
+ * map, which is scoped to the nearest enclosing package rather than to
24616
+ * `node_modules`.
24617
+ */
24618
+ resolveImports(specifier, from, kind) {
24619
+ const root = this.packageRoot(from);
24620
+ if (!root) return null;
24621
+ const manifest = this.readManifest(root);
24622
+ if (!manifest?.imports) return null;
24623
+ for (const conditions of CONDITION_SETS[kind]) {
24624
+ let targets;
24625
+ try {
24626
+ targets = resolve_exports.imports(manifest, specifier, { conditions, unsafe: true });
24627
+ } catch {
24628
+ continue;
24629
+ }
24630
+ for (const target of targets ?? []) {
24631
+ const found = target.startsWith(".") ? this.resolvePath(resolve(root, target), kind) : this.resolvePackage(target, root, kind);
24632
+ if (found) return found;
24633
+ }
24634
+ }
24635
+ return null;
24636
+ }
24637
+ /** Resolve a path to a file, trying Node's extension and index fallbacks. */
24638
+ resolvePath(path, kind = "require") {
24639
+ if (this.isFile(path)) return path;
24640
+ for (const extension of EXTENSIONS) {
24641
+ const candidate = `${path}${extension}`;
24642
+ if (this.isFile(candidate)) return candidate;
24643
+ }
24644
+ if (!this.isDirectory(path)) return null;
24645
+ const manifest = this.readManifest(path);
24646
+ for (const field of ENTRY_FIELDS[kind]) {
24647
+ const value = manifest?.[field];
24648
+ if (typeof value !== "string") continue;
24649
+ const target = resolve(path, value);
24650
+ if (this.isFile(target)) return target;
24651
+ for (const extension of EXTENSIONS) {
24652
+ if (this.isFile(`${target}${extension}`)) return `${target}${extension}`;
24653
+ }
24654
+ const nested = this.resolveIndex(target);
24655
+ if (nested) return nested;
24656
+ }
24657
+ return this.resolveIndex(path);
24658
+ }
24659
+ resolveIndex(dir3) {
24660
+ for (const extension of EXTENSIONS) {
24661
+ const candidate = join(dir3, `index${extension}`);
24662
+ if (this.isFile(candidate)) return candidate;
24663
+ }
24664
+ return null;
24665
+ }
24666
+ /** The nearest ancestor directory holding a `package.json`. */
24667
+ packageRoot(from) {
24668
+ for (let dir3 = dirname(from); ; dir3 = dirname(dir3)) {
24669
+ if (this.isFile(join(dir3, "package.json"))) return dir3;
24670
+ if (dir3 === "/") return null;
24671
+ }
24672
+ }
24673
+ readManifest(root) {
24674
+ const cached2 = this.manifests.get(root);
24675
+ if (cached2 !== void 0) return cached2;
24676
+ let manifest = null;
24677
+ try {
24678
+ manifest = JSON.parse(this.readText(join(root, "package.json")));
24679
+ } catch {
24680
+ }
24681
+ this.manifests.set(root, manifest);
24682
+ return manifest;
24683
+ }
24684
+ builtin(specifier, importer) {
24685
+ const name = specifier.replace(/^node:/, "");
24686
+ if (!Object.prototype.hasOwnProperty.call(this.builtins, name)) {
24687
+ return Object.prototype.hasOwnProperty.call(this.overrides, specifier) ? { found: true, value: this.overrides[specifier] } : { found: false, value: void 0 };
24688
+ }
24689
+ if (name === "module" && importer) {
24690
+ return {
24691
+ found: true,
24692
+ value: { ...this.builtins.module, createRequire: () => this.makeRequire(importer) }
24693
+ };
24694
+ }
24695
+ return { found: true, value: this.builtins[name] };
24696
+ }
24697
+ exists(path) {
24698
+ try {
24699
+ this.volume.lstatSync(path);
24700
+ return true;
24701
+ } catch {
24702
+ return false;
24703
+ }
24704
+ }
24705
+ isFile(path) {
24706
+ try {
24707
+ return this.volume.lstatSync(path).isFile();
24708
+ } catch {
24709
+ return false;
24710
+ }
24711
+ }
24712
+ isDirectory(path) {
24713
+ try {
24714
+ return this.volume.lstatSync(path).isDirectory();
24715
+ } catch {
24716
+ return false;
24717
+ }
24718
+ }
24719
+ readText(path) {
24720
+ return new TextDecoder().decode(this.volume.readFileSync(path));
24721
+ }
24722
+ moduleNotFound(specifier, importer) {
24723
+ const error = new Error(`Cannot find module '${specifier}'
24724
+ Require stack:
24725
+ - ${importer}`);
24726
+ error.code = "MODULE_NOT_FOUND";
24727
+ return error;
24728
+ }
24729
+ };
24730
+ var namespaces = /* @__PURE__ */ new WeakMap();
24731
+ function namespaceOf(exports) {
24732
+ if (exports === null || typeof exports !== "object" && typeof exports !== "function") {
24733
+ return { default: exports, __esModule: true };
24734
+ }
24735
+ const target = exports;
24736
+ if (target.__esModule) return target;
24737
+ const cached2 = namespaces.get(target);
24738
+ if (cached2) return cached2;
24739
+ const namespace = {};
24740
+ for (const key of ownKeys(target)) {
24741
+ if (key === "default" || key === "__esModule") continue;
24742
+ Object.defineProperty(namespace, key, {
24743
+ enumerable: true,
24744
+ configurable: true,
24745
+ get: () => target[key]
24746
+ });
24747
+ }
24748
+ Object.defineProperty(namespace, "default", { enumerable: true, configurable: true, value: target });
24749
+ Object.defineProperty(namespace, "__esModule", { value: true });
24750
+ namespaces.set(target, namespace);
24751
+ return namespace;
24752
+ }
24753
+ function exportAll(exports, namespace) {
24754
+ if (namespace === null || typeof namespace !== "object") return;
24755
+ const source = namespace;
24756
+ for (const key of ownKeys(source)) {
24757
+ if (key === "default" || key === "__esModule") continue;
24758
+ if (Object.prototype.hasOwnProperty.call(exports, key)) continue;
24759
+ Object.defineProperty(exports, key, {
24760
+ enumerable: true,
24761
+ configurable: true,
24762
+ get: () => source[key]
24763
+ });
24764
+ }
24765
+ }
24766
+ function ownKeys(target) {
24767
+ const keys = [];
24768
+ for (const key of Object.getOwnPropertyNames(target)) {
24769
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
24770
+ if (descriptor?.enumerable) keys.push(key);
24771
+ }
24772
+ return keys;
24773
+ }
24774
+ function fileUrl(path) {
24775
+ return `file://${path.split("/").map(encodeURIComponent).join("/")}`;
24776
+ }
24777
+ function dlopenFailed(filename) {
24778
+ const error = new Error(
24779
+ `Cannot load '${filename}': it is a compiled native addon, which the sandboxed runtime cannot execute. A pure-JavaScript or WebAssembly build of the package is needed instead.`
24780
+ );
24781
+ error.code = "ERR_DLOPEN_FAILED";
24782
+ return error;
24783
+ }
24784
+ function requireOfAsyncModule(specifier) {
24785
+ const error = new Error(
24786
+ `require() cannot load ES module '${specifier}': it uses top-level await. Use import() instead.`
24787
+ );
24788
+ error.code = "ERR_REQUIRE_ASYNC_MODULE";
24789
+ return error;
24790
+ }
24791
+ function splitSpecifier(specifier) {
24792
+ const parts = specifier.split("/");
24793
+ const size = specifier.startsWith("@") ? 2 : 1;
24794
+ return { name: parts.slice(0, size).join("/"), subpath: parts.slice(size).join("/") };
24795
+ }
24796
+
24797
+ // src/runtime/core-modules.ts
24798
+ init_path();
24799
+ var VirtualIncomingMessage = class extends streamModule3__default.default.Readable {
24800
+ method;
24801
+ url;
24802
+ headers;
24803
+ rawHeaders;
24804
+ httpVersion = "1.1";
24805
+ httpVersionMajor = 1;
24806
+ httpVersionMinor = 1;
24807
+ complete = true;
24808
+ socket = socketStub();
24809
+ connection = this.socket;
24810
+ constructor(init) {
24811
+ super();
24812
+ this.method = (init.method ?? "GET").toUpperCase();
24813
+ this.url = init.path ?? "/";
24814
+ const body = init.body == null ? new Uint8Array() : typeof init.body === "string" ? new TextEncoder().encode(init.body) : init.body instanceof ArrayBuffer ? new Uint8Array(init.body) : init.body;
24815
+ this.headers = Object.fromEntries(Object.entries(init.headers ?? {}).map(([key, value]) => [key.toLowerCase(), value]));
24816
+ if (body.length && this.headers["content-length"] === void 0 && this.headers["transfer-encoding"] === void 0) {
24817
+ this.headers["content-length"] = String(body.length);
24818
+ }
24819
+ this.rawHeaders = Object.entries(this.headers).flatMap(([key, value]) => [key, value]);
24820
+ if (body.length) this.push(buffer.Buffer.from(body));
24821
+ this.push(null);
24822
+ }
24823
+ _read() {
24824
+ }
24825
+ setTimeout(_milliseconds, callback) {
24826
+ if (callback) this.once("timeout", callback);
24827
+ return this;
24828
+ }
24829
+ };
24830
+ var VirtualServerResponse = class extends streamModule3__default.default.Writable {
24831
+ statusCode = 200;
24832
+ statusMessage = "OK";
24833
+ headersSent = false;
24834
+ sendDate = true;
24835
+ req;
24836
+ socket = socketStub();
24837
+ connection = this.socket;
24838
+ headers = /* @__PURE__ */ new Map();
24839
+ chunks = [];
24840
+ resolve;
24841
+ completed;
24842
+ constructor(request) {
24843
+ super();
24844
+ this.req = request;
24845
+ this.completed = new Promise((resolve2) => {
24846
+ this.resolve = resolve2;
24847
+ });
24848
+ }
24849
+ _write(chunk, encoding, callback) {
24850
+ this.headersSent = true;
24851
+ this.chunks.push(buffer.Buffer.isBuffer(chunk) ? chunk : buffer.Buffer.from(chunk, encoding));
24852
+ callback();
24853
+ }
24854
+ _final(callback) {
24855
+ this.headersSent = true;
24856
+ if (this.sendDate && !this.hasHeader("date")) this.setHeader("Date", (/* @__PURE__ */ new Date()).toUTCString());
24857
+ const headers = {};
24858
+ for (const { name, value } of this.headers.values()) headers[name] = Array.isArray(value) ? value.join(", ") : value;
24859
+ this.resolve({
24860
+ statusCode: this.statusCode,
24861
+ statusMessage: this.statusMessage || STATUS_CODES[this.statusCode] || "",
24862
+ headers,
24863
+ body: new Uint8Array(buffer.Buffer.concat(this.chunks))
24864
+ });
24865
+ callback();
24866
+ }
24867
+ setHeader(name, value) {
24868
+ validateHeaderName(name);
24869
+ validateHeaderValue(name, value);
24870
+ this.headers.set(name.toLowerCase(), { name, value: Array.isArray(value) ? [...value].map(String) : String(value) });
24871
+ return this;
24872
+ }
24873
+ appendHeader(name, value) {
24874
+ const current = this.getHeader(name);
24875
+ const next = Array.isArray(value) ? [...value] : [String(value)];
24876
+ return this.setHeader(name, current === void 0 ? next : [...Array.isArray(current) ? current : [String(current)], ...next]);
24877
+ }
24878
+ getHeader(name) {
24879
+ return this.headers.get(name.toLowerCase())?.value;
24880
+ }
24881
+ getHeaders() {
24882
+ return Object.fromEntries([...this.headers].map(([key, entry]) => [key, entry.value]));
24883
+ }
24884
+ getHeaderNames() {
24885
+ return [...this.headers.keys()];
24886
+ }
24887
+ hasHeader(name) {
24888
+ return this.headers.has(name.toLowerCase());
24889
+ }
24890
+ removeHeader(name) {
24891
+ this.headers.delete(name.toLowerCase());
24892
+ }
24893
+ writeHead(statusCode, statusMessage, headers) {
24894
+ this.statusCode = statusCode;
24895
+ if (typeof statusMessage === "string") this.statusMessage = statusMessage;
24896
+ const values = (typeof statusMessage === "object" ? statusMessage : headers) ?? {};
24897
+ for (const [name, value] of Object.entries(values)) if (value !== void 0) this.setHeader(name, value);
24898
+ this.headersSent = true;
24899
+ return this;
24900
+ }
24901
+ flushHeaders() {
24902
+ this.headersSent = true;
24903
+ }
24904
+ writeContinue() {
24905
+ }
24906
+ writeProcessing() {
24907
+ }
24908
+ addTrailers(_headers) {
24909
+ }
24910
+ setTimeout(_milliseconds, callback) {
24911
+ if (callback) this.once("timeout", callback);
24912
+ return this;
24913
+ }
24914
+ };
24915
+ var VirtualHttpServer = class extends EventEmitter3__default.default {
24916
+ constructor(router, owner, listener) {
24917
+ super();
24918
+ this.router = router;
24919
+ this.owner = owner;
24920
+ if (listener) this.on("request", listener);
24921
+ }
24922
+ router;
24923
+ owner;
24924
+ listening = false;
24925
+ portValue = null;
24926
+ listen(...args) {
24927
+ const callback = typeof args.at(-1) === "function" ? args.pop() : void 0;
24928
+ const first = args[0];
24929
+ const port = typeof first === "object" ? Number(first.port) : Number(first);
24930
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw Object.assign(new RangeError(`Invalid port: ${port}`), { code: "ERR_SOCKET_BAD_PORT" });
24931
+ this.router.register(port, this, this.owner);
24932
+ this.portValue = port;
24933
+ this.listening = true;
24934
+ queueMicrotask(() => {
24935
+ this.emit("listening");
24936
+ callback?.();
24937
+ });
24938
+ return this;
24939
+ }
24940
+ close(callback) {
24941
+ if (this.portValue !== null) this.router.unregister(this.portValue, this);
24942
+ this.portValue = null;
24943
+ this.listening = false;
24944
+ queueMicrotask(() => {
24945
+ this.emit("close");
24946
+ callback?.();
24947
+ });
24948
+ return this;
24949
+ }
24950
+ address() {
24951
+ return this.portValue === null ? null : { address: "0.0.0.0", family: "IPv4", port: this.portValue };
24952
+ }
24953
+ ref() {
24954
+ return this;
24955
+ }
24956
+ unref() {
24957
+ return this;
24958
+ }
24959
+ setTimeout(_milliseconds, callback) {
24960
+ if (callback) this.on("timeout", callback);
24961
+ return this;
24962
+ }
24963
+ };
24964
+ var VirtualHttpRouter = class {
24965
+ servers = /* @__PURE__ */ new Map();
24966
+ register(port, server, owner) {
24967
+ if (this.servers.has(port)) throw Object.assign(new Error(`listen EADDRINUSE: address already in use 0.0.0.0:${port}`), { code: "EADDRINUSE", port });
24968
+ this.servers.set(port, { server, owner });
24969
+ }
24970
+ unregister(port, server) {
24971
+ if (this.servers.get(port)?.server === server) this.servers.delete(port);
24972
+ }
24973
+ activePorts(owner) {
24974
+ return [...this.servers].filter(([, item]) => owner === void 0 || item.owner === owner).map(([port]) => port).sort((a, b) => a - b);
24975
+ }
24976
+ closeOwner(owner) {
24977
+ for (const { server, owner: value } of [...this.servers.values()]) if (value === owner) server.close();
24978
+ }
24979
+ closeAll() {
24980
+ for (const { server } of [...this.servers.values()]) server.close();
24981
+ }
24982
+ async request(port, init = {}) {
24983
+ const item = this.servers.get(port);
24984
+ if (!item) return { statusCode: 503, statusMessage: "Service Unavailable", headers: {}, body: "No server is listening" };
24985
+ const request = new VirtualIncomingMessage(init);
24986
+ const response = new VirtualServerResponse(request);
24987
+ try {
24988
+ item.server.emit("request", request, response);
24989
+ return await response.completed;
24990
+ } catch (error) {
24991
+ if (!response.writableEnded) response.end(error instanceof Error ? error.message : String(error));
24992
+ return { statusCode: 500, statusMessage: "Internal Server Error", headers: {}, body: error instanceof Error ? error.message : String(error) };
24993
+ }
24994
+ }
24995
+ };
24996
+ function createHttpModule(router, owner) {
24997
+ const createServer = (listener) => new VirtualHttpServer(router, owner, listener);
24998
+ const module = {
24999
+ createServer,
25000
+ Server: VirtualHttpServer,
25001
+ ServerResponse: VirtualServerResponse,
25002
+ IncomingMessage: VirtualIncomingMessage,
25003
+ METHODS,
25004
+ STATUS_CODES,
25005
+ maxHeaderSize: 16 * 1024,
25006
+ validateHeaderName,
25007
+ validateHeaderValue,
25008
+ globalAgent: { keepAlive: true },
25009
+ Agent: class Agent {
25010
+ }
25011
+ };
25012
+ return { ...module, request: unsupportedClient, get: unsupportedClient };
25013
+ }
25014
+ function unsupportedClient() {
25015
+ throw Object.assign(new Error("http client requests are not implemented yet"), { code: "ERR_NOT_IMPLEMENTED" });
25016
+ }
25017
+ function validateHeaderName(name) {
25018
+ 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" });
25019
+ }
25020
+ function validateHeaderValue(name, value) {
25021
+ if (value === void 0 || /[\0\r\n]/.test(String(value))) throw Object.assign(new TypeError(`Invalid value for header "${name}"`), { code: "ERR_INVALID_CHAR" });
25022
+ }
25023
+ function socketStub() {
25024
+ return { remoteAddress: "127.0.0.1", remotePort: 0, localAddress: "127.0.0.1", localPort: 0, encrypted: false, writable: true, readable: true, setTimeout() {
25025
+ }, setNoDelay() {
25026
+ }, setKeepAlive() {
25027
+ }, ref() {
25028
+ return this;
25029
+ }, unref() {
25030
+ return this;
25031
+ }, destroy() {
25032
+ } };
25033
+ }
25034
+ var METHODS = ["ACL", "BIND", "CHECKOUT", "CONNECT", "COPY", "DELETE", "GET", "HEAD", "LINK", "LOCK", "M-SEARCH", "MERGE", "MKACTIVITY", "MKCALENDAR", "MKCOL", "MOVE", "NOTIFY", "OPTIONS", "PATCH", "POST", "PROPFIND", "PROPPATCH", "PURGE", "PUT", "REBIND", "REPORT", "SEARCH", "SOURCE", "SUBSCRIBE", "TRACE", "UNBIND", "UNLINK", "UNLOCK", "UNSUBSCRIBE"];
25035
+ var STATUS_CODES = { 100: "Continue", 200: "OK", 201: "Created", 202: "Accepted", 204: "No Content", 206: "Partial Content", 301: "Moved Permanently", 302: "Found", 304: "Not Modified", 307: "Temporary Redirect", 308: "Permanent Redirect", 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 409: "Conflict", 413: "Payload Too Large", 415: "Unsupported Media Type", 422: "Unprocessable Entity", 429: "Too Many Requests", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable" };
25036
+ var hashes = { md5: legacy.md5, sha1: legacy.sha1, "sha-1": legacy.sha1, sha224: sha256.sha224, "sha-224": sha256.sha224, sha256: sha256.sha256, "sha-256": sha256.sha256, sha384: sha512.sha384, "sha-384": sha512.sha384, sha512: sha512.sha512, "sha-512": sha512.sha512 };
25037
+ function createCryptoModule() {
25038
+ const cryptoObject = globalThis.crypto;
25039
+ return {
25040
+ createHash(algorithm) {
25041
+ const hash = hashFor(algorithm).create();
25042
+ const api = {
25043
+ update(data, encoding) {
25044
+ hash.update(toBytes2(data, encoding));
25045
+ return api;
25046
+ },
25047
+ digest(encoding) {
25048
+ const value = buffer.Buffer.from(hash.digest());
25049
+ return encoding ? value.toString(encoding) : value;
25050
+ },
25051
+ copy() {
25052
+ throw new Error("Hash.copy is not implemented");
25053
+ }
25054
+ };
25055
+ return api;
25056
+ },
25057
+ createHmac(algorithm, key) {
25058
+ const hash = hashFor(algorithm);
25059
+ const state = hmac.hmac.create(hash, toBytes2(key));
25060
+ const api = {
25061
+ update(data, encoding) {
25062
+ state.update(toBytes2(data, encoding));
25063
+ return api;
25064
+ },
25065
+ digest(encoding) {
25066
+ const value = buffer.Buffer.from(state.digest());
25067
+ return encoding ? value.toString(encoding) : value;
25068
+ }
25069
+ };
25070
+ return api;
25071
+ },
25072
+ randomBytes(size, callback) {
25073
+ const value = buffer.Buffer.alloc(size);
25074
+ cryptoObject.getRandomValues(value);
25075
+ if (callback) {
25076
+ queueMicrotask(() => callback(null, value));
25077
+ return;
25078
+ }
25079
+ return value;
25080
+ },
25081
+ randomFillSync(target, offset = 0, size = target.length - offset) {
25082
+ cryptoObject.getRandomValues(target.subarray(offset, offset + size));
25083
+ return target;
25084
+ },
25085
+ randomUUID: () => cryptoObject.randomUUID(),
25086
+ /* Node re-exports the Web Crypto entry points on the `crypto` module
25087
+ * itself, and tools use whichever spelling they prefer — Vite's config
25088
+ * hashing reaches for `getRandomValues` on the default import. */
25089
+ getRandomValues: (target) => cryptoObject.getRandomValues(target),
25090
+ randomInt(min, max) {
25091
+ const [low, high] = max === void 0 ? [0, min] : [min, max];
25092
+ const span = high - low;
25093
+ if (!(span > 0)) throw new RangeError('The value of "max" is out of range');
25094
+ const value = new Uint32Array(1);
25095
+ cryptoObject.getRandomValues(value);
25096
+ return low + value[0] % span;
25097
+ },
25098
+ randomFill(target, offset = 0, size, callback) {
25099
+ const done = [offset, size, callback].find((value) => typeof value === "function");
25100
+ const start = typeof offset === "number" ? offset : 0;
25101
+ const length = typeof size === "number" ? size : target.length - start;
25102
+ cryptoObject.getRandomValues(target.subarray(start, start + length));
25103
+ queueMicrotask(() => done?.(null, target));
25104
+ },
25105
+ hash(algorithm, data, encoding = "hex") {
25106
+ const digest = buffer.Buffer.from(hashFor(algorithm)(toBytes2(data)));
25107
+ return encoding === "buffer" ? digest : digest.toString(encoding);
25108
+ },
25109
+ timingSafeEqual(a, b) {
25110
+ if (a.length !== b.length) throw new RangeError("Input buffers must have the same byte length");
25111
+ let difference = 0;
25112
+ for (let index = 0; index < a.length; index++) difference |= a[index] ^ b[index];
25113
+ return difference === 0;
25114
+ },
25115
+ getHashes: () => ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"],
25116
+ webcrypto: cryptoObject,
25117
+ subtle: cryptoObject.subtle,
25118
+ constants: {}
25119
+ };
25120
+ }
25121
+ function hashFor(algorithm) {
25122
+ const hash = hashes[algorithm.toLowerCase()];
25123
+ if (!hash) throw Object.assign(new Error(`Digest method not supported: ${algorithm}`), { code: "ERR_OSSL_EVP_UNSUPPORTED" });
25124
+ return hash;
25125
+ }
25126
+ function toBytes2(data, encoding) {
25127
+ return typeof data === "string" ? buffer.Buffer.from(data, encoding) : data;
25128
+ }
25129
+ var ChildProcess = class extends EventEmitter3__default.default {
25130
+ stdout = new streamModule3__default.default.PassThrough();
25131
+ stderr = new streamModule3__default.default.PassThrough();
25132
+ stdin;
25133
+ stdio;
25134
+ pid;
25135
+ exitCode = null;
25136
+ signalCode = null;
25137
+ killed = false;
25138
+ spawnfile;
25139
+ spawnargs;
25140
+ handle;
25141
+ settled = false;
25142
+ constructor(handle, file3, args) {
25143
+ super();
25144
+ this.handle = handle;
25145
+ this.pid = handle.pid;
25146
+ this.spawnfile = file3;
25147
+ this.spawnargs = [file3, ...args];
25148
+ this.stdin = new streamModule3__default.default.Writable({
25149
+ write: (chunk, _encoding, done) => {
25150
+ try {
25151
+ handle.sendStdin(typeof chunk === "string" ? chunk : buffer.Buffer.from(chunk).toString("utf8"));
25152
+ } catch {
25153
+ }
25154
+ done();
25155
+ }
25156
+ });
25157
+ this.stdio = [this.stdin, this.stdout, this.stderr];
25158
+ handle.on("stdout", (text2) => this.stdout.write(text2));
25159
+ handle.on("stderr", (text2) => this.stderr.write(text2));
25160
+ handle.on("exit", (code) => this.finish(code));
25161
+ handle.exec();
25162
+ }
25163
+ kill(signal = "SIGTERM") {
25164
+ this.killed = true;
25165
+ this.handle.kill(typeof signal === "number" ? "SIGTERM" : signal);
25166
+ return true;
25167
+ }
25168
+ ref() {
25169
+ return this;
25170
+ }
25171
+ unref() {
25172
+ return this;
25173
+ }
25174
+ disconnect() {
25175
+ this.emit("disconnect");
25176
+ }
25177
+ /** No IPC channel exists, and reporting that honestly beats a silent drop. */
25178
+ send() {
25179
+ return false;
25180
+ }
25181
+ get connected() {
25182
+ return false;
25183
+ }
25184
+ finish(code) {
25185
+ if (this.settled) return;
25186
+ this.settled = true;
25187
+ this.exitCode = code;
25188
+ this.stdout.end();
25189
+ this.stderr.end();
25190
+ this.emit("exit", code, null);
25191
+ queueMicrotask(() => this.emit("close", code, null));
25192
+ }
25193
+ };
25194
+ function createChildProcessModule(spawnChild, defaultCwd) {
25195
+ const throughShell = (command, options) => {
25196
+ const shell = typeof options.shell === "string" ? options.shell : "/bin/sh";
25197
+ return { file: shell, args: ["-c", command] };
25198
+ };
25199
+ const start = (file3, args, options) => {
25200
+ const resolved = options.shell ? throughShell([file3, ...args].join(" "), options) : { file: file3, args };
25201
+ const handle = spawnChild({
25202
+ command: resolved.file,
25203
+ args: resolved.args,
25204
+ cwd: options.cwd ?? defaultCwd(),
25205
+ ...options.env ? { env: options.env } : {}
25206
+ });
25207
+ return new ChildProcess(handle, resolved.file, resolved.args);
25208
+ };
25209
+ const spawn = (file3, args = [], options = {}) => {
25210
+ if (!Array.isArray(args)) return start(file3, [], args);
25211
+ return start(file3, args, options);
25212
+ };
25213
+ const collect = (child, options, callback) => {
25214
+ if (!callback) return child;
25215
+ const out = [];
25216
+ const err = [];
25217
+ child.stdout.on("data", (chunk) => out.push(String(chunk)));
25218
+ child.stderr.on("data", (chunk) => err.push(String(chunk)));
25219
+ child.on("close", (code) => {
25220
+ const asBuffer = options.encoding === "buffer";
25221
+ const stdout = asBuffer ? buffer.Buffer.from(out.join("")) : out.join("");
25222
+ const stderr = asBuffer ? buffer.Buffer.from(err.join("")) : err.join("");
25223
+ if (code === 0) {
25224
+ callback(null, stdout, stderr);
25225
+ return;
25226
+ }
25227
+ const error = Object.assign(
25228
+ new Error(`Command failed: ${child.spawnargs.join(" ")}
25229
+ ${err.join("")}`),
25230
+ { code, killed: child.killed, cmd: child.spawnargs.join(" ") }
25231
+ );
25232
+ callback(error, stdout, stderr);
25233
+ });
25234
+ return child;
25235
+ };
25236
+ const exec = (command, options = {}, callback) => {
25237
+ const [opts, cb] = normalize2(options, callback);
25238
+ const { file: file3, args } = throughShell(command, opts);
25239
+ return collect(start(file3, args, { ...opts, shell: false }), opts, cb);
25240
+ };
25241
+ const execFile = (file3, args = [], options = {}, callback) => {
25242
+ const list = Array.isArray(args) ? args : [];
25243
+ const [opts, cb] = Array.isArray(args) ? normalize2(options, callback) : normalize2(args, options);
25244
+ return collect(start(file3, list, opts), opts, cb);
25245
+ };
25246
+ return {
25247
+ spawn,
25248
+ exec,
25249
+ execFile,
25250
+ fork: (modulePath, args = [], options = {}) => spawn("node", [modulePath, ...args], options),
25251
+ execSync: unavailable("execSync"),
25252
+ execFileSync: unavailable("execFileSync"),
25253
+ spawnSync: unavailable("spawnSync"),
25254
+ ChildProcess
25255
+ };
25256
+ }
25257
+ function normalize2(options, callback) {
25258
+ if (typeof options === "function") return [{}, options];
25259
+ return [options ?? {}, callback];
25260
+ }
25261
+ function unavailable(name) {
25262
+ return () => {
25263
+ const error = new Error(
25264
+ `child_process.${name} is not supported in the sandboxed runtime: it would have to block the JavaScript thread. Use the asynchronous form instead.`
25265
+ );
25266
+ error.code = "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM";
25267
+ throw error;
25268
+ };
25269
+ }
25270
+
25271
+ // src/runtime/core-modules.ts
25272
+ init_signals();
25273
+ var Dirent = class {
25274
+ /** Node 20+ exposes the containing directory, and `fs.glob` consumers read it. */
25275
+ constructor(name, stat2, parentPath = "") {
25276
+ this.name = name;
25277
+ this.stat = stat2;
25278
+ this.parentPath = parentPath;
25279
+ }
25280
+ name;
25281
+ stat;
25282
+ parentPath;
25283
+ get path() {
25284
+ return this.parentPath;
25285
+ }
25286
+ isFile() {
25287
+ return this.stat.isFile();
25288
+ }
25289
+ isDirectory() {
25290
+ return this.stat.isDirectory();
25291
+ }
25292
+ isSymbolicLink() {
25293
+ return this.stat.isSymbolicLink();
25294
+ }
25295
+ isBlockDevice() {
25296
+ return false;
25297
+ }
25298
+ isCharacterDevice() {
25299
+ return false;
25300
+ }
25301
+ isFIFO() {
25302
+ return false;
25303
+ }
25304
+ isSocket() {
25305
+ return false;
25306
+ }
25307
+ };
25308
+ var Stats2 = class {
25309
+ constructor(inner) {
25310
+ this.inner = inner;
25311
+ }
25312
+ inner;
25313
+ dev = 1;
25314
+ rdev = 0;
25315
+ blksize = 4096;
25316
+ get mode() {
25317
+ const type = this.inner.isDirectory() ? S_IFDIR2 : this.inner.isSymbolicLink() ? S_IFLNK2 : S_IFREG2;
25318
+ return (this.inner.mode & S_IFMT2) !== 0 ? this.inner.mode : this.inner.mode | type;
25319
+ }
25320
+ get size() {
25321
+ return this.inner.size;
25322
+ }
25323
+ get uid() {
25324
+ return this.inner.uid;
25325
+ }
25326
+ get gid() {
25327
+ return this.inner.gid;
25328
+ }
25329
+ get ino() {
25330
+ return this.inner.ino;
25331
+ }
25332
+ get nlink() {
25333
+ return this.inner.nlink;
25334
+ }
25335
+ get blocks() {
25336
+ return Math.ceil(this.inner.size / 512);
25337
+ }
25338
+ get atimeMs() {
25339
+ return this.inner.atimeMs;
25340
+ }
25341
+ get mtimeMs() {
25342
+ return this.inner.mtimeMs;
25343
+ }
25344
+ get ctimeMs() {
25345
+ return this.inner.ctimeMs;
25346
+ }
25347
+ get birthtimeMs() {
25348
+ return this.inner.birthtimeMs;
25349
+ }
25350
+ get atime() {
25351
+ return new Date(this.inner.atimeMs);
25352
+ }
25353
+ get mtime() {
25354
+ return new Date(this.inner.mtimeMs);
25355
+ }
25356
+ get ctime() {
25357
+ return new Date(this.inner.ctimeMs);
25358
+ }
25359
+ get birthtime() {
25360
+ return new Date(this.inner.birthtimeMs);
25361
+ }
25362
+ isFile() {
25363
+ return this.inner.isFile();
25364
+ }
25365
+ isDirectory() {
25366
+ return this.inner.isDirectory();
25367
+ }
25368
+ isSymbolicLink() {
25369
+ return this.inner.isSymbolicLink();
25370
+ }
25371
+ isBlockDevice() {
25372
+ return false;
25373
+ }
25374
+ isCharacterDevice() {
25375
+ return false;
25376
+ }
25377
+ isFIFO() {
25378
+ return false;
25379
+ }
25380
+ isSocket() {
25381
+ return false;
25382
+ }
25383
+ };
25384
+ var S_IFMT2 = 61440;
25385
+ var S_IFREG2 = 32768;
25386
+ var S_IFDIR2 = 16384;
25387
+ var S_IFLNK2 = 40960;
25388
+ var FsWatcher = class extends EventEmitter3__default.default {
25389
+ close() {
25390
+ this.removeAllListeners();
25391
+ }
25392
+ ref() {
25393
+ return this;
25394
+ }
25395
+ unref() {
25396
+ return this;
25397
+ }
25398
+ };
25399
+ function createCoreModules(options) {
25400
+ const volume = options.volume;
25401
+ let cwd = clean(options.cwd ?? "/");
25402
+ let exitCode = 0;
25403
+ const env2 = { ...options.env };
25404
+ const stdoutWrite = options.stdout ?? (() => {
25405
+ });
25406
+ const stderrWrite = options.stderr ?? (() => {
25407
+ });
25408
+ const timers = createTrackedTimers();
25409
+ const processObject = Object.assign(new EventEmitter3__default.default(), processShim__default.default, {
25410
+ argv: options.argv?.slice() ?? ["/usr/bin/node"],
25411
+ argv0: "node",
25412
+ execPath: "/usr/bin/node",
25413
+ env: env2,
25414
+ platform: "linux",
25415
+ arch: "x64",
25416
+ version: "v22.12.0",
25417
+ versions: { ...processShim__default.default.versions, node: "22.12.0" },
25418
+ pid: 100,
25419
+ ppid: 1,
25420
+ title: "node",
25421
+ exitCode,
25422
+ cwd: () => cwd,
25423
+ chdir: (path2) => {
25424
+ const next = resolve(cwd, path2);
25425
+ const stat2 = volume.lstatSync(resolveLinks(volume, next));
25426
+ if (!stat2.isDirectory()) throw fsError("ENOTDIR", "chdir", next);
25427
+ cwd = next;
25428
+ },
25429
+ umask: (_mask) => 18,
25430
+ getuid: () => 0,
25431
+ geteuid: () => 0,
25432
+ getgid: () => 0,
25433
+ getegid: () => 0,
25434
+ getgroups: () => [0],
25435
+ uptime: () => performance.now() / 1e3,
25436
+ memoryUsage: () => ({ rss: 0, heapTotal: 0, heapUsed: 0, external: 0, arrayBuffers: 0 }),
25437
+ cpuUsage: () => ({ user: 0, system: 0 }),
25438
+ exit: (code = 0) => {
25439
+ exitCode = code;
25440
+ processObject.exitCode = code;
25441
+ options.onExit?.(code);
25442
+ },
25443
+ kill: () => true
25444
+ });
25445
+ processObject.stdout = makeOutputStream(stdoutWrite, 1);
25446
+ processObject.stderr = makeOutputStream(stderrWrite, 2);
25447
+ processObject.stdin = new streamModule3__default.default.Readable({ read() {
25448
+ this.push(null);
25449
+ } });
25450
+ Object.assign(processObject.stdin, { fd: 0, isTTY: false, setRawMode() {
25451
+ return this;
25452
+ } });
25453
+ const fs = createFsModule(volume, () => cwd);
25454
+ const path = createPathModule(() => cwd);
25455
+ const consoleObject = new Console(stdoutWrite, stderrWrite);
25456
+ const os = createOsModule();
25457
+ const asyncHooks = createAsyncHooksModule();
25458
+ const moduleBuiltin = {
25459
+ builtinModules: builtinNames2.flatMap((name) => [name, `node:${name}`]),
25460
+ isBuiltin: (name) => builtinNames2.includes(name.replace(/^node:/, "")),
25461
+ createRequire: () => {
25462
+ throw new Error("createRequire is only available inside a loaded module");
25463
+ }
25464
+ };
25465
+ const http = options.http ? createHttpModule(options.http.router, options.http.owner) : createUnsupportedModule("http");
25466
+ const childProcess = options.spawnChild ? createChildProcessModule(options.spawnChild, () => cwd) : createUnsupportedModule("child_process");
25467
+ const readline2 = createReadlineModule(() => processObject.stdin);
25468
+ const dns = createDnsModule();
25469
+ const builtins = {
25470
+ assert: assertModule__default.default,
25471
+ "assert/strict": assertModule__default.default.strict ?? assertModule__default.default,
25472
+ buffer: { Buffer: buffer.Buffer, SlowBuffer: buffer.Buffer, INSPECT_MAX_BYTES: 50, kMaxLength: buffer.Buffer.kMaxLength },
25473
+ async_hooks: asyncHooks,
25474
+ child_process: childProcess,
25475
+ console: consoleObject,
25476
+ constants: fs.constants,
25477
+ crypto: createCryptoModule(),
25478
+ dns,
25479
+ "dns/promises": dns.promises,
25480
+ events: EventEmitter3__default.default,
25481
+ fs,
25482
+ "fs/promises": fs.promises,
25483
+ module: moduleBuiltin,
25484
+ http,
25485
+ https: http,
25486
+ os,
25487
+ path,
25488
+ "path/posix": path,
25489
+ perf_hooks: { performance, PerformanceObserver: globalThis.PerformanceObserver },
25490
+ process: processObject,
25491
+ punycode: urlModule__default.default.punycode ?? {},
25492
+ querystring: querystringModule__default.default,
25493
+ readline: readline2,
25494
+ "readline/promises": readline2.promises,
25495
+ stream: streamModule3__default.default,
25496
+ "stream/promises": createStreamPromises(),
25497
+ string_decoder: stringDecoderModule__default.default,
25498
+ timers: { ...timersModule__default.default, ...timers.api },
25499
+ "timers/promises": createTimerPromises(),
25500
+ tty: { isatty: () => false, ReadStream: streamModule3__default.default.Readable, WriteStream: streamModule3__default.default.Writable },
25501
+ url: urlModule__default.default,
25502
+ util: utilModule__default.default,
25503
+ "util/types": utilModule__default.default.types ?? {},
25504
+ zlib: zlibModule__default.default
25505
+ };
25506
+ for (const name of stubNames) builtins[name] = createUnsupportedModule(name);
25507
+ const globals = {
25508
+ Buffer: buffer.Buffer,
25509
+ console: consoleObject,
25510
+ process: processObject,
25511
+ ...timers.api
25512
+ };
25513
+ const globalOverlay = new Proxy(globalThis, {
25514
+ get: (target, key) => typeof key === "string" && key in globals ? globals[key] : key === "global" || key === "globalThis" ? globalOverlay : Reflect.get(target, key),
25515
+ has: (target, key) => typeof key === "string" && key in globals || Reflect.has(target, key)
25516
+ });
25517
+ globals.global = globalOverlay;
25518
+ globals.globalThis = globalOverlay;
25519
+ return { builtins, globals, process: processObject, pendingHandles: timers.pending };
25520
+ }
25521
+ var ASYNC_FS_METHODS = [
25522
+ "readFile",
25523
+ "writeFile",
25524
+ "appendFile",
25525
+ "stat",
25526
+ "lstat",
25527
+ "fstat",
25528
+ "readdir",
25529
+ "mkdir",
25530
+ "mkdtemp",
25531
+ "rm",
25532
+ "rmdir",
25533
+ "unlink",
25534
+ "rename",
25535
+ "readlink",
25536
+ "symlink",
25537
+ "link",
25538
+ "realpath",
25539
+ "truncate",
25540
+ "ftruncate",
25541
+ "chmod",
25542
+ "lchmod",
25543
+ "fchmod",
25544
+ "chown",
25545
+ "lchown",
25546
+ "fchown",
25547
+ "utimes",
25548
+ "lutimes",
25549
+ "futimes",
25550
+ "access",
25551
+ "copyFile",
25552
+ "cp",
25553
+ "open",
25554
+ "close",
25555
+ "read",
25556
+ "write",
25557
+ "exists"
25558
+ ];
25559
+ function createPathModule(cwd) {
25560
+ const resolve2 = (...segments2) => pathModule__default.default.resolve(cwd(), ...segments2);
25561
+ const path = {
25562
+ ...pathModule__default.default,
25563
+ resolve: resolve2,
25564
+ /* `relative` resolves both operands, and the implementation would do so
25565
+ * against the host cwd, so they are resolved here first. */
25566
+ relative: (from, to) => pathModule__default.default.relative(resolve2(from), resolve2(to))
25567
+ };
25568
+ path.posix = path;
25569
+ path.win32 = pathModule__default.default.win32 ?? path;
25570
+ path.default = path;
25571
+ return path;
25572
+ }
25573
+ function createFsModule(volume, cwd) {
25574
+ const fds = /* @__PURE__ */ new Map();
25575
+ let nextFd = 3;
25576
+ const abs = (value) => {
25577
+ if (value instanceof URL) value = value.pathname;
25578
+ if (buffer.Buffer.isBuffer(value) || value instanceof Uint8Array) value = new TextDecoder().decode(value);
25579
+ if (typeof value !== "string") throw new TypeError("path must be a string, Buffer, or URL");
25580
+ return value.startsWith("/") ? clean(value) : resolve(cwd(), value);
25581
+ };
25582
+ const bytes = (data, encoding) => {
25583
+ if (typeof data === "string") return new Uint8Array(buffer.Buffer.from(data, encoding));
25584
+ if (buffer.Buffer.isBuffer(data) || data instanceof Uint8Array) return new Uint8Array(data);
25585
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
25586
+ throw new TypeError("data must be a string or byte array");
25587
+ };
25588
+ const read = (path, encoding) => {
25589
+ const data = buffer.Buffer.from(volume.readFileSync(resolveLinks(volume, abs(path))));
25590
+ return encoding && encoding !== "buffer" ? data.toString(encoding) : data;
25591
+ };
25592
+ const mkdirRecursive = (path, mode) => {
25593
+ let cursor = "";
25594
+ for (const part of segments(path)) {
25595
+ cursor += `/${part}`;
25596
+ try {
25597
+ if (!volume.lstatSync(cursor).isDirectory()) throw fsError("ENOTDIR", "mkdir", cursor);
25598
+ } catch (error) {
25599
+ if (error.code !== "ENOENT") throw error;
25600
+ volume.mkdirSync(cursor, { mode });
25601
+ }
25602
+ }
25603
+ };
25604
+ const rmRecursive = (path) => {
25605
+ const stat2 = volume.lstatSync(path);
25606
+ if (!stat2.isDirectory()) return volume.unlinkSync(path);
25607
+ for (const name of volume.readdirSync(path)) rmRecursive(join(path, name));
25608
+ volume.rmdirSync(path);
25609
+ };
25610
+ const callback = (operation, cb) => {
25611
+ queueMicrotask(() => {
25612
+ try {
25613
+ cb(null, operation());
25614
+ } catch (error) {
25615
+ cb(error);
25616
+ }
25617
+ });
25618
+ };
25619
+ const fs = {
25620
+ constants: {
25621
+ F_OK: 0,
25622
+ R_OK: 4,
25623
+ W_OK: 2,
25624
+ X_OK: 1,
25625
+ O_RDONLY: 0,
25626
+ O_WRONLY: 1,
25627
+ O_RDWR: 2,
25628
+ O_CREAT: 64,
25629
+ O_EXCL: 128,
25630
+ O_TRUNC: 512,
25631
+ O_APPEND: 1024,
25632
+ COPYFILE_EXCL: 1
25633
+ },
25634
+ Dirent,
25635
+ readFileSync: (path, options) => read(path, typeof options === "object" && options ? options.encoding : options),
25636
+ writeFileSync: (path, data, options) => {
25637
+ const encoding = typeof options === "object" && options ? options.encoding : options === "buffer" ? void 0 : options ?? void 0;
25638
+ volume.writeFileSync(abs(path), bytes(data, encoding ?? void 0));
25639
+ if (typeof options === "object" && options?.mode !== void 0) volume.chmodSync(abs(path), options.mode);
25640
+ },
25641
+ appendFileSync: (path, data, options) => {
25642
+ const encoding = typeof options === "object" && options ? options.encoding : options === "buffer" ? void 0 : options ?? void 0;
25643
+ volume.appendFileSync(abs(path), bytes(data, encoding ?? void 0));
25644
+ },
25645
+ existsSync: (path) => {
25646
+ try {
25647
+ volume.lstatSync(abs(path));
25648
+ return true;
25649
+ } catch {
25650
+ return false;
25651
+ }
25652
+ },
25653
+ statSync: (path) => new Stats2(volume.lstatSync(resolveLinks(volume, abs(path)))),
25654
+ lstatSync: (path) => new Stats2(volume.lstatSync(abs(path))),
25655
+ readdirSync: (path, options) => {
25656
+ const dir3 = resolveLinks(volume, abs(path));
25657
+ const names = volume.readdirSync(dir3);
25658
+ if (typeof options === "object" && options?.withFileTypes) {
25659
+ return names.map((name) => new Dirent(name, new Stats2(volume.lstatSync(join(dir3, name))), dir3));
25660
+ }
25661
+ if ((typeof options === "string" ? options : options?.encoding) === "buffer") return names.map((name) => buffer.Buffer.from(name));
25662
+ return names;
25663
+ },
25664
+ mkdirSync: (path, options) => {
25665
+ const target = abs(path);
25666
+ const mode = typeof options === "number" ? options : options?.mode ?? 511;
25667
+ if (typeof options === "object" && options?.recursive) return mkdirRecursive(target, mode);
25668
+ return volume.mkdirSync(target, { mode });
25669
+ },
25670
+ rmdirSync: (path, options) => options?.recursive ? rmRecursive(abs(path)) : volume.rmdirSync(abs(path)),
25671
+ rmSync: (path, options) => {
25672
+ try {
25673
+ options?.recursive ? rmRecursive(abs(path)) : volume.unlinkSync(abs(path));
25674
+ } catch (error) {
25675
+ if (!options?.force) throw error;
25676
+ }
25677
+ },
25678
+ unlinkSync: (path) => volume.unlinkSync(abs(path)),
25679
+ renameSync: (from, to) => volume.renameSync(abs(from), abs(to)),
25680
+ readlinkSync: (path, encoding) => {
25681
+ const value = volume.readlinkSync(abs(path));
25682
+ return encoding === "buffer" ? buffer.Buffer.from(value) : value;
25683
+ },
25684
+ symlinkSync: (target, path) => volume.symlinkSync(target, abs(path)),
25685
+ linkSync: (from, to) => volume.linkSync(abs(from), abs(to)),
25686
+ realpathSync: (path) => resolveLinks(volume, abs(path)),
25687
+ truncateSync: (path, length = 0) => volume.truncateSync(abs(path), length),
25688
+ chmodSync: (path, mode) => volume.chmodSync(resolveLinks(volume, abs(path)), mode),
25689
+ chownSync: (path, uid, gid) => volume.chownSync(resolveLinks(volume, abs(path)), uid, gid),
25690
+ utimesSync: (path, atime, mtime) => volume.utimesSync(resolveLinks(volume, abs(path)), new Date(atime), new Date(mtime)),
25691
+ accessSync: (path) => {
25692
+ volume.lstatSync(resolveLinks(volume, abs(path)));
25693
+ },
25694
+ copyFileSync: (from, to, flags = 0) => {
25695
+ const target = abs(to);
25696
+ if (flags && fs.existsSync(target)) throw fsError("EEXIST", "copyfile", target);
25697
+ volume.writeFileSync(target, volume.readFileSync(resolveLinks(volume, abs(from))));
25698
+ },
25699
+ openSync: (path, flags) => {
25700
+ const target = abs(path);
25701
+ const textFlags = typeof flags === "number" ? flags === 0 ? "r" : "r+" : flags;
25702
+ if (/[wa]/.test(textFlags) && !fs.existsSync(target)) volume.writeFileSync(target, new Uint8Array());
25703
+ if (textFlags.startsWith("w")) volume.truncateSync(target, 0);
25704
+ else volume.lstatSync(resolveLinks(volume, target));
25705
+ const fd = nextFd++;
25706
+ fds.set(fd, { path: target, position: textFlags.startsWith("a") ? volume.lstatSync(target).size : 0, flags: textFlags });
25707
+ return fd;
25708
+ },
25709
+ closeSync: (fd) => {
25710
+ if (!fds.delete(fd)) throw fsError("EBADF", "close", String(fd));
25711
+ },
25712
+ /** Used by the promise API's FileHandle to reach whole-file operations. */
25713
+ __pathForFd: (fd) => requiredFd(fds, fd).path,
25714
+ fstatSync: (fd) => new Stats2(volume.lstatSync(resolveLinks(volume, requiredFd(fds, fd).path))),
25715
+ readSync: (fd, target, offset, length, position) => {
25716
+ const file3 = requiredFd(fds, fd);
25717
+ const source = volume.readFileSync(resolveLinks(volume, file3.path));
25718
+ const start = position ?? file3.position;
25719
+ const count = Math.max(0, Math.min(length, source.length - start));
25720
+ target.set(source.subarray(start, start + count), offset);
25721
+ if (position == null) file3.position += count;
25722
+ return count;
25723
+ },
25724
+ writeSync: (fd, data, offset, length, position) => {
25725
+ const file3 = requiredFd(fds, fd);
25726
+ const input = bytes(data);
25727
+ const chunk = typeof data === "string" ? input : input.subarray(offset ?? 0, (offset ?? 0) + (length ?? input.length));
25728
+ const old = volume.readFileSync(file3.path);
25729
+ const start = file3.flags.startsWith("a") ? old.length : position ?? file3.position;
25730
+ const next = new Uint8Array(Math.max(old.length, start + chunk.length));
25731
+ next.set(old);
25732
+ next.set(chunk, start);
25733
+ volume.writeFileSync(file3.path, next);
25734
+ if (position == null) file3.position = start + chunk.length;
25735
+ return chunk.length;
25736
+ },
25737
+ createReadStream: (path) => {
25738
+ const data = buffer.Buffer.from(volume.readFileSync(resolveLinks(volume, abs(path))));
25739
+ return streamModule3__default.default.Readable.from([data]);
25740
+ },
25741
+ createWriteStream: (path, options) => {
25742
+ const target = abs(path);
25743
+ let first = true;
25744
+ return new streamModule3__default.default.Writable({ write(chunk, _encoding, done) {
25745
+ try {
25746
+ if (options?.flags?.startsWith("a") || !first) volume.appendFileSync(target, new Uint8Array(chunk));
25747
+ else volume.writeFileSync(target, new Uint8Array(chunk));
25748
+ first = false;
25749
+ done();
25750
+ } catch (error) {
25751
+ done(error);
25752
+ }
25753
+ } });
25754
+ },
25755
+ watch: () => new FsWatcher(),
25756
+ watchFile: () => {
25757
+ },
25758
+ unwatchFile: () => {
25759
+ }
25760
+ };
25761
+ fs.ftruncateSync = (fd, length) => fs.truncateSync(requiredFd(fds, fd).path, length);
25762
+ fs.fchmodSync = (fd, mode) => fs.chmodSync(requiredFd(fds, fd).path, mode);
25763
+ fs.fchownSync = (fd, uid, gid) => fs.chownSync(requiredFd(fds, fd).path, uid, gid);
25764
+ fs.futimesSync = (fd, atime, mtime) => fs.utimesSync(requiredFd(fds, fd).path, atime, mtime);
25765
+ fs.lchmodSync = (path, mode) => volume.lchmodSync(abs(path), mode);
25766
+ fs.lchownSync = (path, uid, gid) => volume.lchownSync(abs(path), uid, gid);
25767
+ fs.lutimesSync = (path, atime, mtime) => fs.utimesSync(path, atime, mtime);
25768
+ fs.realpathSync.native = fs.realpathSync;
25769
+ fs.mkdtempSync = (prefix) => {
25770
+ const target = `${String(prefix)}${Math.random().toString(36).slice(2, 8)}`;
25771
+ volume.mkdirSync(resolve(cwd(), target), { mode: 448 });
25772
+ return target;
25773
+ };
25774
+ fs.cpSync = (from, to, options) => {
25775
+ const copy = (source, destination) => {
25776
+ const stat2 = volume.lstatSync(source);
25777
+ if (stat2.isDirectory()) {
25778
+ if (!options?.recursive) throw fsError("EISDIR", "cp", source);
25779
+ mkdirRecursive(destination, stat2.mode);
25780
+ for (const name of volume.readdirSync(source)) {
25781
+ copy(join(source, name), join(destination, name));
25782
+ }
25783
+ return;
25784
+ }
25785
+ if (stat2.isSymbolicLink()) {
25786
+ volume.symlinkSync(volume.readlinkSync(source), destination);
25787
+ return;
25788
+ }
25789
+ volume.writeFileSync(destination, volume.readFileSync(source));
25790
+ };
25791
+ copy(abs(from), abs(to));
25792
+ };
25793
+ for (const name of ASYNC_FS_METHODS) {
25794
+ if (name === "exists") continue;
25795
+ fs[name] = (...args) => {
25796
+ const cb = args.pop();
25797
+ if (typeof cb !== "function") throw new TypeError("callback must be a function");
25798
+ callback(() => fs[`${name}Sync`](...args), cb);
25799
+ };
25800
+ }
25801
+ fs.realpath.native = fs.realpath;
25802
+ fs.exists = (path, cb) => {
25803
+ queueMicrotask(() => cb(fs.existsSync(path)));
25804
+ };
25805
+ fs.promises = {
25806
+ ...Object.fromEntries(
25807
+ ASYNC_FS_METHODS.filter((name) => name !== "exists" && name !== "open").map((name) => [name, (...args) => Promise.resolve().then(() => fs[`${name}Sync`](...args))])
25808
+ ),
25809
+ constants: fs.constants,
25810
+ /* The promise API hands back a FileHandle object rather than a numeric
25811
+ * descriptor, and callers use its methods instead of passing the number
25812
+ * to `fs.read`. */
25813
+ open: async (path, flags = "r", mode) => makeFileHandle(fs, fs.openSync(path, flags, mode))
25814
+ };
25815
+ return fs;
25816
+ }
25817
+ function makeFileHandle(fs, fd) {
25818
+ return {
25819
+ fd,
25820
+ close: async () => fs.closeSync(fd),
25821
+ stat: async () => fs.fstatSync(fd),
25822
+ truncate: async (length) => fs.ftruncateSync(fd, length),
25823
+ chmod: async (mode) => fs.fchmodSync(fd, mode),
25824
+ chown: async (uid, gid) => fs.fchownSync(fd, uid, gid),
25825
+ utimes: async (atime, mtime) => fs.futimesSync(fd, atime, mtime),
25826
+ read: async (buffer, offset = 0, length = buffer.length, position) => ({
25827
+ bytesRead: fs.readSync(fd, buffer, offset, length, position),
25828
+ buffer
25829
+ }),
25830
+ write: async (data, offset, length, position) => ({
25831
+ bytesWritten: fs.writeSync(fd, data, offset, length, position),
25832
+ buffer: data
25833
+ }),
25834
+ readFile: async (options) => fs.readFileSync(fs.__pathForFd(fd), options),
25835
+ writeFile: async (data, options) => fs.writeFileSync(fs.__pathForFd(fd), data, options)
25836
+ };
25837
+ }
25838
+ function resolveLinks(volume, input) {
25839
+ let path = clean(input);
25840
+ for (let hops = 0; hops < 40; hops++) {
25841
+ const parts = segments(path);
25842
+ let cursor = "";
25843
+ let followed = false;
25844
+ for (let index = 0; index < parts.length; index++) {
25845
+ cursor += `/${parts[index]}`;
25846
+ const stat2 = volume.lstatSync(cursor);
25847
+ if (!stat2.isSymbolicLink()) continue;
25848
+ const target = volume.readlinkSync(cursor);
25849
+ const rest = parts.slice(index + 1).join("/");
25850
+ path = resolve(dirname(cursor), target, rest);
25851
+ followed = true;
25852
+ break;
25853
+ }
25854
+ if (!followed) return path || "/";
25855
+ }
25856
+ throw fsError("ELOOP", "realpath", input);
25857
+ }
25858
+ function requiredFd(fds, fd) {
25859
+ const file3 = fds.get(fd);
25860
+ if (!file3) throw fsError("EBADF", "fd", String(fd));
25861
+ return file3;
25862
+ }
25863
+ function fsError(code, syscall, path) {
25864
+ return Object.assign(new Error(`${code}: ${syscall}, '${path}'`), { code, syscall, path });
25865
+ }
25866
+ function makeOutputStream(write, fd) {
25867
+ const stream = new streamModule3__default.default.Writable({ write(chunk, _encoding, done) {
25868
+ write(buffer.Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk));
25869
+ done();
25870
+ } });
25871
+ return Object.assign(stream, { fd, isTTY: false, columns: 80, rows: 24 });
25872
+ }
25873
+ var Console = class {
25874
+ constructor(out, err) {
25875
+ this.out = out;
25876
+ this.err = err;
25877
+ }
25878
+ out;
25879
+ err;
25880
+ log = (...args) => {
25881
+ this.out(utilModule__default.default.format(...args) + "\n");
25882
+ };
25883
+ info = (...args) => {
25884
+ this.log(...args);
25885
+ };
25886
+ debug = (...args) => {
25887
+ this.log(...args);
25888
+ };
25889
+ warn = (...args) => {
25890
+ this.err(utilModule__default.default.format(...args) + "\n");
25891
+ };
25892
+ error = (...args) => {
25893
+ this.warn(...args);
25894
+ };
25895
+ dir = (value, options) => {
25896
+ this.out(utilModule__default.default.inspect(value, options) + "\n");
25897
+ };
25898
+ trace = (...args) => {
25899
+ this.err(`Trace: ${utilModule__default.default.format(...args)}
25900
+ `);
25901
+ };
25902
+ assert = (value, ...args) => {
25903
+ if (!value) this.err(`Assertion failed: ${utilModule__default.default.format(...args)}
25904
+ `);
25905
+ };
25906
+ group = (...args) => {
25907
+ if (args.length) this.log(...args);
25908
+ };
25909
+ groupEnd = () => {
25910
+ };
25911
+ table = (value) => {
25912
+ this.dir(value);
25913
+ };
25914
+ count = () => {
25915
+ };
25916
+ countReset = () => {
25917
+ };
25918
+ time = (_label = "default") => {
25919
+ };
25920
+ timeEnd = (_label = "default") => {
25921
+ };
25922
+ timeLog = (_label = "default") => {
25923
+ };
25924
+ };
25925
+ function createReadlineModule(stdin) {
25926
+ class Interface extends EventEmitter3__default.default {
25927
+ constructor(input) {
25928
+ super();
25929
+ this.input = input;
25930
+ input?.on?.("data", (chunk) => {
25931
+ for (const line of String(chunk).split("\n")) this.lines.push(line);
25932
+ while (this.lines.length > 1) this.emit("line", this.lines.shift());
25933
+ });
25934
+ input?.on?.("end", () => this.close());
25935
+ }
25936
+ input;
25937
+ closed = false;
25938
+ lines = [];
25939
+ question(_query, callback) {
25940
+ const answer = this.lines.shift() ?? "";
25941
+ if (callback) {
25942
+ queueMicrotask(() => callback(answer));
25943
+ return;
25944
+ }
25945
+ return Promise.resolve(answer);
25946
+ }
25947
+ prompt() {
25948
+ }
25949
+ setPrompt() {
25950
+ }
25951
+ pause() {
25952
+ return this;
25953
+ }
25954
+ resume() {
25955
+ return this;
25956
+ }
25957
+ write() {
25958
+ }
25959
+ close() {
25960
+ if (this.closed) return;
25961
+ this.closed = true;
25962
+ this.emit("close");
25963
+ }
25964
+ async *[Symbol.asyncIterator]() {
25965
+ while (this.lines.length) yield this.lines.shift();
25966
+ }
25967
+ }
25968
+ const createInterface = (options) => new Interface(options?.input ?? (Array.isArray(options) ? options[0] : stdin()));
25969
+ const noop = () => {
25970
+ };
25971
+ const base = {
25972
+ Interface,
25973
+ createInterface,
25974
+ clearLine: noop,
25975
+ clearScreenDown: noop,
25976
+ cursorTo: noop,
25977
+ moveCursor: noop,
25978
+ emitKeypressEvents: noop
25979
+ };
25980
+ return { ...base, promises: { ...base, Interface, createInterface } };
25981
+ }
25982
+ function createDnsModule() {
25983
+ const LOOPBACK = {
25984
+ localhost: { address: "127.0.0.1", family: 4 },
25985
+ "127.0.0.1": { address: "127.0.0.1", family: 4 },
25986
+ "0.0.0.0": { address: "0.0.0.0", family: 4 },
25987
+ "::1": { address: "::1", family: 6 }
25988
+ };
25989
+ const lookupSync = (hostname) => {
25990
+ const entry = LOOPBACK[hostname];
25991
+ if (entry) return entry;
25992
+ const error = new Error(`getaddrinfo ENOTFOUND ${hostname}`);
25993
+ error.code = "ENOTFOUND";
25994
+ error.errno = -3008;
25995
+ error.syscall = "getaddrinfo";
25996
+ error.hostname = hostname;
25997
+ throw error;
25998
+ };
25999
+ const lookup = (hostname, options, callback) => {
26000
+ const done = typeof options === "function" ? options : callback;
26001
+ const all = typeof options === "object" && options !== null && options.all;
26002
+ queueMicrotask(() => {
26003
+ try {
26004
+ const entry = lookupSync(hostname);
26005
+ done?.(null, all ? [entry] : entry.address, entry.family);
26006
+ } catch (error) {
26007
+ done?.(error);
26008
+ }
26009
+ });
26010
+ };
26011
+ const notFound = (hostname) => Promise.reject(lookupThrow(hostname));
26012
+ const lookupThrow = (hostname) => {
26013
+ try {
26014
+ lookupSync(hostname);
26015
+ return null;
26016
+ } catch (error) {
26017
+ return error;
26018
+ }
26019
+ };
26020
+ const promises = {
26021
+ lookup: async (hostname, options) => {
26022
+ const entry = lookupSync(hostname);
26023
+ return options?.all ? [entry] : entry;
26024
+ },
26025
+ resolve4: async (hostname) => [lookupSync(hostname).address],
26026
+ resolve6: async (hostname) => [lookupSync(hostname).address],
26027
+ reverse: async (address) => address === "127.0.0.1" ? ["localhost"] : notFound(address)
26028
+ };
26029
+ return {
26030
+ lookup,
26031
+ promises,
26032
+ Resolver: class Resolver {
26033
+ },
26034
+ getServers: () => [],
26035
+ setServers: () => {
26036
+ },
26037
+ ADDRCONFIG: 1024,
26038
+ V4MAPPED: 8,
26039
+ ALL: 16,
26040
+ NODATA: "ENODATA",
26041
+ NOTFOUND: "ENOTFOUND"
26042
+ };
26043
+ }
26044
+ function createOsModule() {
26045
+ return {
26046
+ EOL: "\n",
26047
+ devNull: "/dev/null",
26048
+ type: () => "Linux",
26049
+ platform: () => "linux",
26050
+ release: () => "5.10.0-sandboxedjs",
26051
+ version: () => "#1 SMP SandboxedJS",
26052
+ arch: () => "x64",
26053
+ endianness: () => "LE",
26054
+ hostname: () => "sandbox",
26055
+ homedir: () => "/root",
26056
+ tmpdir: () => "/tmp",
26057
+ userInfo: () => ({ uid: 0, gid: 0, username: "root", homedir: "/root", shell: "/bin/sh" }),
26058
+ cpus: () => [{ model: "SandboxedJS Virtual CPU", speed: 1e3, times: { user: 0, nice: 0, sys: 0, idle: 0, irq: 0 } }],
26059
+ totalmem: () => 2 * 1024 ** 3,
26060
+ freemem: () => 1024 ** 3,
26061
+ uptime: () => performance.now() / 1e3,
26062
+ loadavg: () => [0, 0, 0],
26063
+ networkInterfaces: () => ({}),
26064
+ machine: () => "x86_64",
26065
+ availableParallelism: () => 4,
26066
+ /* `os.constants.signals` is not decoration: the `human-signals` package
26067
+ * that `execa` pulls in enumerates it at load time, so every tool built on
26068
+ * execa fails to even import without it. */
26069
+ constants: {
26070
+ signals: exports.SIGNALS,
26071
+ errno: ERRNO_CONSTANTS,
26072
+ priority: {
26073
+ PRIORITY_LOW: 19,
26074
+ PRIORITY_BELOW_NORMAL: 10,
26075
+ PRIORITY_NORMAL: 0,
26076
+ PRIORITY_ABOVE_NORMAL: -7,
26077
+ PRIORITY_HIGH: -14,
26078
+ PRIORITY_HIGHEST: -20
26079
+ }
26080
+ }
26081
+ };
26082
+ }
26083
+ var ERRNO_CONSTANTS = {
26084
+ E2BIG: 7,
26085
+ EACCES: 13,
26086
+ EADDRINUSE: 98,
26087
+ EADDRNOTAVAIL: 99,
26088
+ EAFNOSUPPORT: 97,
26089
+ EAGAIN: 11,
26090
+ EALREADY: 114,
26091
+ EBADF: 9,
26092
+ EBADMSG: 74,
26093
+ EBUSY: 16,
26094
+ ECANCELED: 125,
26095
+ ECHILD: 10,
26096
+ ECONNABORTED: 103,
26097
+ ECONNREFUSED: 111,
26098
+ ECONNRESET: 104,
26099
+ EDEADLK: 35,
26100
+ EDESTADDRREQ: 89,
26101
+ EDOM: 33,
26102
+ EDQUOT: 122,
26103
+ EEXIST: 17,
26104
+ EFAULT: 14,
26105
+ EFBIG: 27,
26106
+ EHOSTUNREACH: 113,
26107
+ EIDRM: 43,
26108
+ EILSEQ: 84,
26109
+ EINPROGRESS: 115,
26110
+ EINTR: 4,
26111
+ EINVAL: 22,
26112
+ EIO: 5,
26113
+ EISCONN: 106,
26114
+ EISDIR: 21,
26115
+ ELOOP: 40,
26116
+ EMFILE: 24,
26117
+ EMLINK: 31,
26118
+ EMSGSIZE: 90,
26119
+ EMULTIHOP: 72,
26120
+ ENAMETOOLONG: 36,
26121
+ ENETDOWN: 100,
26122
+ ENETRESET: 102,
26123
+ ENETUNREACH: 101,
26124
+ ENFILE: 23,
26125
+ ENOBUFS: 105,
26126
+ ENODATA: 61,
26127
+ ENODEV: 19,
26128
+ ENOENT: 2,
26129
+ ENOEXEC: 8,
26130
+ ENOLCK: 37,
26131
+ ENOLINK: 67,
26132
+ ENOMEM: 12,
26133
+ ENOMSG: 42,
26134
+ ENOPROTOOPT: 92,
26135
+ ENOSPC: 28,
26136
+ ENOSR: 63,
26137
+ ENOSTR: 60,
26138
+ ENOSYS: 38,
26139
+ ENOTCONN: 107,
26140
+ ENOTDIR: 20,
26141
+ ENOTEMPTY: 39,
26142
+ ENOTSOCK: 88,
26143
+ ENOTSUP: 95,
26144
+ ENOTTY: 25,
26145
+ ENXIO: 6,
26146
+ EOPNOTSUPP: 95,
26147
+ EOVERFLOW: 75,
26148
+ EPERM: 1,
26149
+ EPIPE: 32,
26150
+ EPROTO: 71,
26151
+ EPROTONOSUPPORT: 93,
26152
+ EPROTOTYPE: 91,
26153
+ ERANGE: 34,
26154
+ EROFS: 30,
26155
+ ESPIPE: 29,
26156
+ ESRCH: 3,
26157
+ ESTALE: 116,
26158
+ ETIME: 62,
26159
+ ETIMEDOUT: 110,
26160
+ ETXTBSY: 26,
26161
+ EWOULDBLOCK: 11,
26162
+ EXDEV: 18
26163
+ };
26164
+ function createTrackedTimers() {
26165
+ const live = /* @__PURE__ */ new Set();
26166
+ const track = (handle, repeating) => {
26167
+ live.add(handle);
26168
+ return handle;
26169
+ };
26170
+ const setTimeoutTracked = (fn, delay, ...args) => {
26171
+ const handle = setTimeout(
26172
+ (...inner) => {
26173
+ live.delete(handle);
26174
+ fn(...inner);
26175
+ },
26176
+ delay,
26177
+ ...args
26178
+ );
26179
+ live.add(handle);
26180
+ return handle;
26181
+ };
26182
+ const setIntervalTracked = (fn, delay, ...args) => track(setInterval(fn, delay, ...args));
26183
+ const hostSetImmediate = globalThis.setImmediate;
26184
+ const setImmediateTracked = (fn, ...args) => {
26185
+ const handle = hostSetImmediate ? hostSetImmediate((...inner) => {
26186
+ live.delete(handle);
26187
+ fn(...inner);
26188
+ }, ...args) : setTimeoutTracked(fn, 0, ...args);
26189
+ live.add(handle);
26190
+ return handle;
26191
+ };
26192
+ const clear2 = (handle, native) => {
26193
+ live.delete(handle);
26194
+ native(handle);
26195
+ };
26196
+ return {
26197
+ api: {
26198
+ setTimeout: setTimeoutTracked,
26199
+ setInterval: setIntervalTracked,
26200
+ setImmediate: setImmediateTracked,
26201
+ clearTimeout: (handle) => clear2(handle, clearTimeout),
26202
+ clearInterval: (handle) => clear2(handle, clearInterval),
26203
+ clearImmediate: (handle) => clear2(handle, globalThis.clearImmediate ?? clearTimeout)
26204
+ },
26205
+ pending: () => live.size
26206
+ };
26207
+ }
26208
+ function createTimerPromises() {
26209
+ return {
26210
+ setTimeout: (delay, value) => new Promise((resolve2) => setTimeout(resolve2, delay, value)),
26211
+ setImmediate: (value) => new Promise((resolve2) => setTimeout(resolve2, 0, value))
26212
+ };
26213
+ }
26214
+ function createAsyncHooksModule() {
26215
+ class AsyncResource {
26216
+ constructor(type, _options) {
26217
+ this.type = type;
26218
+ }
26219
+ type;
26220
+ runInAsyncScope(fn, thisArg, ...args) {
26221
+ return fn.apply(thisArg, args);
26222
+ }
26223
+ bind(fn, thisArg) {
26224
+ return ((...args) => this.runInAsyncScope(fn, thisArg, ...args));
26225
+ }
26226
+ emitDestroy() {
26227
+ return this;
26228
+ }
26229
+ asyncId() {
26230
+ return 1;
26231
+ }
26232
+ triggerAsyncId() {
26233
+ return 0;
26234
+ }
26235
+ static bind(fn, type = "bound-anonymous-fn", thisArg) {
26236
+ return new AsyncResource(type).bind(fn, thisArg);
26237
+ }
26238
+ }
26239
+ class AsyncLocalStorage {
26240
+ value;
26241
+ disable() {
26242
+ this.value = void 0;
26243
+ }
26244
+ getStore() {
26245
+ return this.value;
26246
+ }
26247
+ enterWith(store) {
26248
+ this.value = store;
26249
+ }
26250
+ run(store, callback, ...args) {
26251
+ const previous = this.value;
26252
+ this.value = store;
26253
+ try {
26254
+ return callback(...args);
26255
+ } finally {
26256
+ this.value = previous;
26257
+ }
26258
+ }
26259
+ exit(callback, ...args) {
26260
+ const previous = this.value;
26261
+ this.value = void 0;
26262
+ try {
26263
+ return callback(...args);
26264
+ } finally {
26265
+ this.value = previous;
26266
+ }
26267
+ }
26268
+ static bind(fn) {
26269
+ return fn;
26270
+ }
26271
+ static snapshot() {
26272
+ return (fn, ...args) => fn(...args);
26273
+ }
26274
+ }
26275
+ return {
26276
+ AsyncResource,
26277
+ AsyncLocalStorage,
26278
+ executionAsyncId: () => 1,
26279
+ triggerAsyncId: () => 0,
26280
+ executionAsyncResource: () => ({}),
26281
+ createHook: () => ({ enable() {
26282
+ return this;
26283
+ }, disable() {
26284
+ return this;
26285
+ } })
26286
+ };
26287
+ }
26288
+ function createStreamPromises() {
26289
+ return {
26290
+ pipeline: (...streams) => new Promise((resolve2, reject) => {
26291
+ const callback = (error) => error ? reject(error) : resolve2();
26292
+ streamModule3__default.default.pipeline(...streams, callback);
26293
+ }),
26294
+ finished: (stream) => new Promise((resolve2, reject) => {
26295
+ streamModule3__default.default.finished(stream, (error) => error ? reject(error) : resolve2());
26296
+ })
26297
+ };
26298
+ }
26299
+ function createUnsupportedModule(name) {
26300
+ const unsupported = () => {
26301
+ const error = new Error(`${name} is unavailable in the browser runtime`);
26302
+ error.code = "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM";
26303
+ throw error;
26304
+ };
26305
+ return new Proxy({ unsupported }, { get(target, key) {
26306
+ return key in target ? target[key] : unsupported;
26307
+ } });
26308
+ }
26309
+ var stubNames = ["cluster", "dgram", "diagnostics_channel", "domain", "http2", "inspector", "net", "tls", "v8", "vm", "worker_threads"];
26310
+ var builtinNames2 = [
26311
+ "assert",
26312
+ "assert/strict",
26313
+ "async_hooks",
26314
+ "buffer",
26315
+ "child_process",
26316
+ "console",
26317
+ "constants",
26318
+ "crypto",
26319
+ "events",
26320
+ "fs",
26321
+ "fs/promises",
26322
+ "dns",
26323
+ "dns/promises",
26324
+ "http",
26325
+ "https",
26326
+ "module",
26327
+ "os",
26328
+ "path",
26329
+ "path/posix",
26330
+ "perf_hooks",
26331
+ "process",
26332
+ "punycode",
26333
+ "querystring",
26334
+ "readline",
26335
+ "readline/promises",
26336
+ "stream",
26337
+ "stream/promises",
26338
+ "string_decoder",
26339
+ "timers",
26340
+ "timers/promises",
26341
+ "tty",
26342
+ "url",
26343
+ "util",
26344
+ "util/types",
26345
+ "zlib",
26346
+ ...stubNames
26347
+ ];
26348
+
26349
+ // src/runtime/memory-volume.ts
26350
+ init_path();
26351
+ var VolumeError = class extends Error {
26352
+ constructor(code, operation, path) {
26353
+ super(`${code}: ${operation}, '${path}'`);
26354
+ this.code = code;
26355
+ this.name = "VolumeError";
26356
+ }
26357
+ code;
26358
+ };
26359
+ var MemoryStat = class {
26360
+ constructor(inode) {
26361
+ this.inode = inode;
26362
+ }
26363
+ inode;
26364
+ get mode() {
26365
+ return this.inode.mode;
26366
+ }
26367
+ get size() {
26368
+ return this.inode.kind === "file" ? this.inode.data.length : this.inode.kind === "symlink" ? new TextEncoder().encode(this.inode.target).length : 0;
26369
+ }
26370
+ get uid() {
26371
+ return this.inode.uid;
26372
+ }
26373
+ get gid() {
26374
+ return this.inode.gid;
26375
+ }
26376
+ get ino() {
26377
+ return this.inode.ino;
26378
+ }
26379
+ get nlink() {
26380
+ return this.inode.nlink;
26381
+ }
26382
+ get atimeMs() {
26383
+ return this.inode.atimeMs;
26384
+ }
26385
+ get mtimeMs() {
26386
+ return this.inode.mtimeMs;
26387
+ }
26388
+ get ctimeMs() {
26389
+ return this.inode.ctimeMs;
26390
+ }
26391
+ get birthtimeMs() {
26392
+ return this.inode.birthtimeMs;
26393
+ }
26394
+ isFile() {
26395
+ return this.inode.kind === "file";
26396
+ }
26397
+ isDirectory() {
26398
+ return this.inode.kind === "directory";
26399
+ }
26400
+ isSymbolicLink() {
26401
+ return this.inode.kind === "symlink";
26402
+ }
26403
+ };
26404
+ var encoder6 = new TextEncoder();
26405
+ var MemoryVolume = class {
26406
+ entries = /* @__PURE__ */ new Map();
26407
+ nextIno = 2;
26408
+ constructor() {
26409
+ this.entries.set("/", this.inode("directory", 493));
26410
+ }
26411
+ readFileSync(path) {
26412
+ const key = this.key(path);
26413
+ const node2 = this.required(key, "open");
26414
+ if (node2.kind === "directory") throw new VolumeError("EISDIR", "read", key);
26415
+ if (node2.kind !== "file") throw new VolumeError("EINVAL", "read", key);
26416
+ node2.atimeMs = Date.now();
26417
+ return node2.data.slice();
26418
+ }
26419
+ writeFileSync(path, data) {
26420
+ const key = this.key(path);
26421
+ this.requireParent(key, "open");
26422
+ const bytes = typeof data === "string" ? encoder6.encode(data) : data.slice();
26423
+ const current = this.entries.get(key);
26424
+ if (current?.kind === "directory") throw new VolumeError("EISDIR", "open", key);
26425
+ if (current?.kind === "symlink") throw new VolumeError("EINVAL", "open", key);
26426
+ if (current) {
26427
+ current.data = bytes;
26428
+ this.touchChanged(current, true);
26429
+ } else {
26430
+ this.entries.set(key, this.inode("file", 438, bytes));
26431
+ }
26432
+ }
26433
+ appendFileSync(path, data) {
26434
+ const key = this.key(path);
26435
+ const bytes = typeof data === "string" ? encoder6.encode(data) : data;
26436
+ const current = this.entries.get(key);
26437
+ if (!current) return this.writeFileSync(key, bytes);
26438
+ if (current.kind !== "file") throw new VolumeError(current.kind === "directory" ? "EISDIR" : "EINVAL", "open", key);
26439
+ const next = new Uint8Array(current.data.length + bytes.length);
26440
+ next.set(current.data);
26441
+ next.set(bytes, current.data.length);
26442
+ current.data = next;
26443
+ this.touchChanged(current, true);
26444
+ }
26445
+ readdirSync(path) {
26446
+ const key = this.key(path);
26447
+ const node2 = this.required(key, "scandir");
26448
+ if (node2.kind !== "directory") throw new VolumeError("ENOTDIR", "scandir", key);
26449
+ const prefix = key === "/" ? "/" : `${key}/`;
26450
+ const names = /* @__PURE__ */ new Set();
26451
+ for (const candidate of this.entries.keys()) {
26452
+ if (!candidate.startsWith(prefix) || candidate === key) continue;
26453
+ const rest = candidate.slice(prefix.length);
26454
+ if (rest && !rest.includes("/")) names.add(rest);
26455
+ }
26456
+ node2.atimeMs = Date.now();
26457
+ return [...names].sort();
26458
+ }
26459
+ lstatSync(path) {
26460
+ return new MemoryStat(this.required(this.key(path), "lstat"));
26461
+ }
26462
+ readlinkSync(path) {
26463
+ const key = this.key(path);
26464
+ const node2 = this.required(key, "readlink");
26465
+ if (node2.kind !== "symlink") throw new VolumeError("EINVAL", "readlink", key);
26466
+ return node2.target;
26467
+ }
26468
+ mkdirSync(path, options = {}) {
26469
+ const key = this.key(path);
26470
+ if (this.entries.has(key)) throw new VolumeError("EEXIST", "mkdir", key);
26471
+ this.requireParent(key, "mkdir");
26472
+ this.entries.set(key, this.inode("directory", options.mode ?? 511));
26473
+ }
26474
+ rmdirSync(path) {
26475
+ const key = this.key(path);
26476
+ if (key === "/") throw new VolumeError("EBUSY", "rmdir", key);
26477
+ const node2 = this.required(key, "rmdir");
26478
+ if (node2.kind !== "directory") throw new VolumeError("ENOTDIR", "rmdir", key);
26479
+ const prefix = `${key}/`;
26480
+ if ([...this.entries.keys()].some((candidate) => candidate.startsWith(prefix))) {
26481
+ throw new VolumeError("ENOTEMPTY", "rmdir", key);
26482
+ }
26483
+ this.entries.delete(key);
26484
+ }
26485
+ unlinkSync(path) {
26486
+ const key = this.key(path);
26487
+ const node2 = this.required(key, "unlink");
26488
+ if (node2.kind === "directory") throw new VolumeError("EISDIR", "unlink", key);
26489
+ this.entries.delete(key);
26490
+ node2.nlink--;
26491
+ node2.ctimeMs = Date.now();
26492
+ }
26493
+ renameSync(from, to) {
26494
+ const source = this.key(from);
26495
+ const dest = this.key(to);
26496
+ const node2 = this.required(source, "rename");
26497
+ this.requireParent(dest, "rename");
26498
+ if (source === "/") throw new VolumeError("EBUSY", "rename", source);
26499
+ if (dest.startsWith(`${source}/`)) throw new VolumeError("EINVAL", "rename", source);
26500
+ const existing = this.entries.get(dest);
26501
+ if (existing?.kind === "directory" && this.readdirSync(dest).length > 0) {
26502
+ throw new VolumeError("ENOTEMPTY", "rename", dest);
26503
+ }
26504
+ if (existing) {
26505
+ this.entries.delete(dest);
26506
+ existing.nlink--;
26507
+ }
26508
+ const moved = [...this.entries.entries()].filter(([path]) => path === source || path.startsWith(`${source}/`)).sort(([a], [b]) => a.length - b.length);
26509
+ for (const [path] of moved) this.entries.delete(path);
26510
+ for (const [path, value] of moved) {
26511
+ this.entries.set(dest + path.slice(source.length), value);
26512
+ value.ctimeMs = Date.now();
26513
+ }
26514
+ node2.ctimeMs = Date.now();
26515
+ }
26516
+ symlinkSync(target, path) {
26517
+ const key = this.key(path);
26518
+ if (this.entries.has(key)) throw new VolumeError("EEXIST", "symlink", key);
26519
+ this.requireParent(key, "symlink");
26520
+ const node2 = this.inode("symlink", 511);
26521
+ node2.target = target;
26522
+ this.entries.set(key, node2);
26523
+ }
26524
+ linkSync(existing, path) {
26525
+ const source = this.key(existing);
26526
+ const dest = this.key(path);
26527
+ const node2 = this.required(source, "link");
26528
+ if (node2.kind === "directory") throw new VolumeError("EPERM", "link", source);
26529
+ if (this.entries.has(dest)) throw new VolumeError("EEXIST", "link", dest);
26530
+ this.requireParent(dest, "link");
26531
+ node2.nlink++;
26532
+ node2.ctimeMs = Date.now();
26533
+ this.entries.set(dest, node2);
26534
+ }
26535
+ truncateSync(path, length = 0) {
26536
+ const key = this.key(path);
26537
+ const node2 = this.required(key, "truncate");
26538
+ if (node2.kind !== "file") throw new VolumeError(node2.kind === "directory" ? "EISDIR" : "EINVAL", "truncate", key);
26539
+ const data = new Uint8Array(length);
26540
+ data.set(node2.data.subarray(0, length));
26541
+ node2.data = data;
26542
+ this.touchChanged(node2, true);
26543
+ }
26544
+ chmodSync(path, mode) {
26545
+ this.setMode(path, mode);
26546
+ }
26547
+ lchmodSync(path, mode) {
26548
+ this.setMode(path, mode);
26549
+ }
26550
+ chownSync(path, uid, gid) {
26551
+ this.setOwner(path, uid, gid);
26552
+ }
26553
+ lchownSync(path, uid, gid) {
26554
+ this.setOwner(path, uid, gid);
26555
+ }
26556
+ utimesSync(path, atime, mtime) {
26557
+ const node2 = this.required(this.key(path), "utimes");
26558
+ node2.atimeMs = atime.getTime();
26559
+ node2.mtimeMs = mtime.getTime();
26560
+ node2.ctimeMs = Date.now();
26561
+ }
26562
+ getStats() {
26563
+ const seen = /* @__PURE__ */ new Set();
26564
+ let totalBytes = 0;
26565
+ let fileCount = 0;
26566
+ let directoryCount = 0;
26567
+ for (const node2 of this.entries.values()) {
26568
+ if (seen.has(node2.ino)) continue;
26569
+ seen.add(node2.ino);
26570
+ if (node2.kind === "directory") directoryCount++;
26571
+ else {
26572
+ fileCount++;
26573
+ totalBytes += node2.kind === "file" ? node2.data.length : encoder6.encode(node2.target).length;
26574
+ }
26575
+ }
26576
+ return { totalBytes, fileCount, directoryCount, dirCount: directoryCount };
26577
+ }
26578
+ snapshot() {
26579
+ return [...this.entries.entries()].map(([path, node2]) => ({ path, ...node2, data: [...node2.data] }));
26580
+ }
26581
+ restore(snapshot) {
26582
+ const inodes = /* @__PURE__ */ new Map();
26583
+ const entries = /* @__PURE__ */ new Map();
26584
+ for (const item of snapshot) {
26585
+ let inode = inodes.get(item.ino);
26586
+ if (!inode) {
26587
+ inode = { ...item, data: new Uint8Array(item.data) };
26588
+ inodes.set(item.ino, inode);
26589
+ }
26590
+ entries.set(this.key(item.path), inode);
26591
+ }
26592
+ if (!entries.has("/")) throw new VolumeError("EINVAL", "restore", "/");
26593
+ this.entries.clear();
26594
+ for (const [path, inode] of entries) this.entries.set(path, inode);
26595
+ this.nextIno = Math.max(1, ...inodes.keys()) + 1;
26596
+ }
26597
+ /** Serializable representation used by RuntimePod snapshots. */
26598
+ export() {
26599
+ return [...this.entries.entries()].map(([path, node2]) => ({
26600
+ path,
26601
+ kind: node2.kind,
26602
+ mode: node2.mode,
26603
+ uid: node2.uid,
26604
+ gid: node2.gid,
26605
+ ...node2.kind === "file" ? { data: [...node2.data] } : {},
26606
+ ...node2.kind === "symlink" ? { target: node2.target } : {}
26607
+ }));
26608
+ }
26609
+ setMode(path, mode) {
26610
+ const node2 = this.required(this.key(path), "chmod");
26611
+ node2.mode = mode & 4095;
26612
+ node2.ctimeMs = Date.now();
26613
+ }
26614
+ setOwner(path, uid, gid) {
26615
+ const node2 = this.required(this.key(path), "chown");
26616
+ node2.uid = uid;
26617
+ node2.gid = gid;
26618
+ node2.ctimeMs = Date.now();
26619
+ }
26620
+ key(path) {
26621
+ const clean2 = clean(path);
26622
+ if (!isAbsolute(clean2)) throw new VolumeError("EINVAL", "path", path);
26623
+ return clean2;
26624
+ }
26625
+ required(path, operation) {
26626
+ const node2 = this.entries.get(path);
26627
+ if (!node2) throw new VolumeError("ENOENT", operation, path);
26628
+ return node2;
26629
+ }
26630
+ requireParent(path, operation) {
26631
+ const parent = this.required(dirname(path), operation);
26632
+ if (parent.kind !== "directory") throw new VolumeError("ENOTDIR", operation, path);
26633
+ return parent;
26634
+ }
26635
+ inode(kind, mode, data = new Uint8Array(0)) {
26636
+ const now = Date.now();
26637
+ return {
26638
+ ino: kind === "directory" && this.entries.size === 0 ? 1 : this.nextIno++,
26639
+ kind,
26640
+ mode: mode & 4095,
26641
+ uid: 0,
26642
+ gid: 0,
26643
+ nlink: 1,
26644
+ data,
26645
+ target: "",
26646
+ atimeMs: now,
26647
+ mtimeMs: now,
26648
+ ctimeMs: now,
26649
+ birthtimeMs: now
26650
+ };
26651
+ }
26652
+ touchChanged(node2, modified) {
26653
+ const now = Date.now();
26654
+ node2.ctimeMs = now;
26655
+ if (modified) node2.mtimeMs = now;
26656
+ }
26657
+ };
26658
+
26659
+ // src/pkg/clean-installer.ts
26660
+ init_path();
26661
+ var CleanPackageInstaller = class _CleanPackageInstaller {
26662
+ constructor(volume, options = {}) {
26663
+ this.volume = volume;
26664
+ this.options = options;
26665
+ this.registry = (options.registry ?? "https://registry.npmjs.org").replace(/\/$/, "");
26666
+ this.fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
26667
+ }
26668
+ volume;
26669
+ options;
26670
+ registry;
26671
+ fetcher;
26672
+ metadata = /* @__PURE__ */ new Map();
26673
+ tarballs = /* @__PURE__ */ new Map();
26674
+ forCwd(cwd) {
26675
+ return new _CleanPackageInstaller(this.volume, { ...this.options, cwd });
26676
+ }
26677
+ async install(name, version = "latest", options = {}) {
26678
+ const cwd = this.options.cwd ?? "/";
26679
+ const manifest = await this.installAt(name, version || "latest", join(cwd, "node_modules"), options, /* @__PURE__ */ new Set());
26680
+ if (options.persist !== false) this.persist(cwd, name, version, options.persistDev === true);
26681
+ return manifest;
26682
+ }
26683
+ async installFromManifest(path, options = {}) {
26684
+ const project = this.readJson(path);
26685
+ const cwd = dirname(path);
26686
+ const dependencies = {
26687
+ ...project.dependencies ?? {},
26688
+ ...options.withDevDeps === false ? {} : project.devDependencies ?? {}
26689
+ };
26690
+ for (const [name, range] of Object.entries(dependencies)) {
26691
+ await this.installAt(name, range, join(cwd, "node_modules"), options, /* @__PURE__ */ new Set());
26692
+ }
26693
+ }
26694
+ async installAt(name, range, modulesRoot, options, ancestry) {
26695
+ const metadata = await this.getMetadata(name);
26696
+ const version = resolveVersion(metadata, range);
26697
+ const manifest = metadata.versions[version];
26698
+ if (!manifest) throw new Error(`No matching version found for ${name}@${range}`);
26699
+ const identity = `${name}@${version}`;
26700
+ const target = join(modulesRoot, name);
26701
+ const installed2 = this.tryReadJson(join(target, "package.json"));
26702
+ if (installed2?.version === version) return installed2;
26703
+ if (ancestry.has(identity)) return manifest;
26704
+ options.onProgress?.(`Fetching ${identity}`);
26705
+ const archive = await this.getTarball(manifest.dist.tarball);
26706
+ verifyIntegrity(archive, manifest.dist.integrity, manifest.dist.shasum, identity);
26707
+ this.removeIfPresent(target);
26708
+ mkdirp(this.volume, target);
26709
+ extractNpmTarball(this.volume, archive, target);
26710
+ options.onProgress?.(`Installed ${identity}`);
26711
+ this.createBinLinks(manifest, target, modulesRoot);
26712
+ const nextAncestry = new Set(ancestry).add(identity);
26713
+ const childRoot = join(target, "node_modules");
26714
+ for (const [dependency, dependencyRange] of Object.entries(manifest.dependencies ?? {})) {
26715
+ await this.installAt(dependency, dependencyRange, childRoot, options, nextAncestry);
26716
+ }
26717
+ for (const [dependency, dependencyRange] of Object.entries(manifest.optionalDependencies ?? {})) {
26718
+ try {
26719
+ await this.installAt(dependency, dependencyRange, childRoot, options, nextAncestry);
26720
+ } catch (error) {
26721
+ options.onProgress?.(`Skipped optional ${dependency}: ${error instanceof Error ? error.message : String(error)}`);
26722
+ }
26723
+ }
26724
+ return manifest;
26725
+ }
26726
+ async getMetadata(name) {
26727
+ let request = this.metadata.get(name);
26728
+ if (!request) {
26729
+ request = (async () => {
26730
+ const encoded = name.startsWith("@") ? name.replace("/", "%2F") : encodeURIComponent(name);
26731
+ const response = await this.fetcher(`${this.registry}/${encoded}`, {
26732
+ headers: { Accept: "application/vnd.npm.install-v1+json" }
26733
+ });
26734
+ if (!response.ok) throw new Error(`registry returned ${response.status} for ${name}`);
26735
+ return await response.json();
26736
+ })();
26737
+ this.metadata.set(name, request);
26738
+ }
26739
+ return request;
26740
+ }
26741
+ async getTarball(url) {
26742
+ let request = this.tarballs.get(url);
26743
+ if (!request) {
26744
+ request = (async () => {
26745
+ const response = await this.fetcher(url);
26746
+ if (!response.ok) throw new Error(`tarball returned ${response.status}: ${url}`);
26747
+ return new Uint8Array(await response.arrayBuffer());
26748
+ })();
26749
+ this.tarballs.set(url, request);
26750
+ }
26751
+ return request;
26752
+ }
26753
+ createBinLinks(manifest, target, modulesRoot) {
26754
+ if (!manifest.bin) return;
26755
+ const bins = typeof manifest.bin === "string" ? { [unscoped(manifest.name)]: manifest.bin } : manifest.bin;
26756
+ const binDir = join(modulesRoot, ".bin");
26757
+ mkdirp(this.volume, binDir);
26758
+ for (const [name, path] of Object.entries(bins)) {
26759
+ const link = join(binDir, name);
26760
+ this.removeIfPresent(link);
26761
+ this.volume.symlinkSync(relative(binDir, join(target, path)), link);
26762
+ }
26763
+ }
26764
+ persist(cwd, name, range, dev) {
26765
+ const path = join(cwd, "package.json");
26766
+ const manifest = this.tryReadJson(path) ?? {};
26767
+ const key = dev ? "devDependencies" : "dependencies";
26768
+ manifest[key] = { ...manifest[key] ?? {}, [name]: range === "latest" ? "*" : range };
26769
+ this.volume.writeFileSync(path, JSON.stringify(manifest, null, 2) + "\n");
26770
+ }
26771
+ removeIfPresent(path) {
26772
+ let stat2;
26773
+ try {
26774
+ stat2 = this.volume.lstatSync(path);
26775
+ } catch {
26776
+ return;
26777
+ }
26778
+ if (!stat2.isDirectory()) return this.volume.unlinkSync(path);
26779
+ for (const name of this.volume.readdirSync(path)) this.removeIfPresent(join(path, name));
26780
+ this.volume.rmdirSync(path);
26781
+ }
26782
+ readJson(path) {
26783
+ return JSON.parse(new TextDecoder().decode(this.volume.readFileSync(path)));
26784
+ }
26785
+ tryReadJson(path) {
26786
+ try {
26787
+ return this.readJson(path);
26788
+ } catch {
26789
+ return null;
26790
+ }
26791
+ }
26792
+ };
26793
+ function resolveVersion(metadata, range) {
26794
+ const tag = metadata["dist-tags"]?.[range];
26795
+ if (tag) return tag;
26796
+ if (semver.valid(range) && metadata.versions[range]) return range;
26797
+ const found = semver.maxSatisfying(Object.keys(metadata.versions), range === "latest" ? "*" : range, { includePrerelease: false });
26798
+ if (!found) throw new Error(`No matching version found for ${metadata.name}@${range}`);
26799
+ return found;
26800
+ }
26801
+ function verifyIntegrity(data, integrity, shasum, identity) {
26802
+ if (integrity) {
26803
+ const choices = integrity.trim().split(/\s+/);
26804
+ for (const choice of choices) {
26805
+ const dash = choice.indexOf("-");
26806
+ const algorithm = choice.slice(0, dash);
26807
+ const expected = choice.slice(dash + 1).replace(/\?.*$/, "");
26808
+ const digest = algorithm === "sha512" ? sha512.sha512(data) : algorithm === "sha256" ? sha256.sha256(data) : null;
26809
+ if (digest && buffer.Buffer.from(digest).toString("base64") === expected) return;
26810
+ }
26811
+ throw new Error(`Integrity check failed for ${identity}`);
26812
+ }
26813
+ if (shasum && buffer.Buffer.from(sha1.sha1(data)).toString("hex") === shasum) return;
26814
+ if (shasum) throw new Error(`Legacy checksum check failed for ${identity}`);
26815
+ }
26816
+ function extractNpmTarball(volume, compressed, destination) {
26817
+ const tar2 = pako.ungzip(compressed);
26818
+ let offset = 0;
26819
+ let longPath = null;
26820
+ let paxPath = null;
26821
+ while (offset + 512 <= tar2.length) {
26822
+ const header = tar2.subarray(offset, offset + 512);
26823
+ if (header.every((byte) => byte === 0)) break;
26824
+ const size = octal(header, 124, 12);
26825
+ const type = String.fromCharCode(header[156] || 48);
26826
+ const prefix = text(header, 345, 155);
26827
+ let name = longPath ?? paxPath ?? [prefix, text(header, 0, 100)].filter(Boolean).join("/");
26828
+ longPath = null;
26829
+ paxPath = null;
26830
+ const data = tar2.subarray(offset + 512, offset + 512 + size);
26831
+ offset += 512 + Math.ceil(size / 512) * 512;
26832
+ if (type === "L") {
26833
+ longPath = new TextDecoder().decode(data).replace(/\0.*$/, "").trim();
26834
+ continue;
26835
+ }
26836
+ if (type === "x" || type === "g") {
26837
+ paxPath = parsePax(data).path ?? null;
26838
+ continue;
26839
+ }
26840
+ name = stripPackageRoot(name);
26841
+ if (!name) continue;
26842
+ const target = safeTarget(destination, name);
26843
+ const mode = octal(header, 100, 8) || 420;
26844
+ if (type === "5") {
26845
+ mkdirp(volume, target, mode);
26846
+ } else if (type === "2") {
26847
+ mkdirp(volume, dirname(target));
26848
+ volume.symlinkSync(text(header, 157, 100), target);
26849
+ } else if (type === "1") {
26850
+ mkdirp(volume, dirname(target));
26851
+ volume.linkSync(safeTarget(destination, stripPackageRoot(text(header, 157, 100))), target);
26852
+ } else if (type === "0" || type === "\0" || type === "7") {
26853
+ mkdirp(volume, dirname(target));
26854
+ volume.writeFileSync(target, data.slice());
26855
+ volume.chmodSync(target, mode);
26856
+ }
26857
+ }
26858
+ }
26859
+ function mkdirp(volume, path, mode = 493) {
26860
+ let current = "";
26861
+ for (const part of segments(path)) {
26862
+ current += `/${part}`;
26863
+ try {
26864
+ volume.mkdirSync(current, { mode });
26865
+ } catch (error) {
26866
+ if (error.code !== "EEXIST") throw error;
26867
+ if (!volume.lstatSync(current).isDirectory()) throw error;
26868
+ }
26869
+ }
26870
+ }
26871
+ function safeTarget(destination, name) {
26872
+ const clean2 = clean(`/${name}`).slice(1);
26873
+ if (!clean2 || clean2 === ".." || clean2.startsWith("../") || name.startsWith("/")) throw new Error(`Unsafe path in package: ${name}`);
26874
+ return join(destination, clean2);
26875
+ }
26876
+ function stripPackageRoot(name) {
26877
+ return name.replace(/^\.\//, "").replace(/^package\//, "").replace(/\/$/, "");
26878
+ }
26879
+ function text(bytes, start, length) {
26880
+ return new TextDecoder().decode(bytes.subarray(start, start + length)).replace(/\0.*$/, "").trim();
26881
+ }
26882
+ function octal(bytes, start, length) {
26883
+ return parseInt(text(bytes, start, length).replace(/^0+/, "") || "0", 8);
26884
+ }
26885
+ function parsePax(data) {
26886
+ const value = new TextDecoder().decode(data);
26887
+ const result = {};
26888
+ let offset = 0;
26889
+ while (offset < value.length) {
26890
+ const space = value.indexOf(" ", offset);
26891
+ if (space < 0) break;
26892
+ const length = Number(value.slice(offset, space));
26893
+ if (!Number.isFinite(length) || length <= 0) break;
26894
+ const record = value.slice(space + 1, offset + length - 1);
26895
+ const equal = record.indexOf("=");
26896
+ if (equal > 0) result[record.slice(0, equal)] = record.slice(equal + 1);
26897
+ offset += length;
26898
+ }
26899
+ return result;
26900
+ }
26901
+ function unscoped(name) {
26902
+ return name.startsWith("@") ? name.slice(name.indexOf("/") + 1) : name;
26903
+ }
26904
+
26905
+ // src/runtime/host-esbuild.ts
26906
+ var cached = null;
26907
+ function loadHostEsbuild() {
26908
+ cached ??= load().catch((error) => {
26909
+ if (typeof process !== "undefined" && process.env?.SANDBOXEDJS_DEBUG) {
26910
+ console.error("[sandboxedjs] host esbuild unavailable:", error);
26911
+ }
26912
+ return null;
26913
+ });
26914
+ return cached;
26915
+ }
26916
+ async function load() {
26917
+ if (typeof process === "undefined" || process.versions?.node == null) return null;
26918
+ for (const specifier of ["esbuild-wasm", "esbuild"]) {
26919
+ try {
26920
+ const esbuild = await nodeOnlyModule(specifier);
26921
+ const api = esbuild.default ?? esbuild;
26922
+ if (specifier === "esbuild-wasm") await api.initialize({});
26923
+ return api;
26924
+ } catch {
26925
+ }
26926
+ }
26927
+ return null;
26928
+ }
26929
+
26930
+ // src/runtime/local-runtime-pod.ts
26931
+ var WASM_ALIASES = {
26932
+ esbuild: "esbuild-wasm",
26933
+ rollup: "@rollup/wasm-node"
26934
+ };
26935
+ var ProcessExit = class extends Error {
26936
+ constructor(code) {
26937
+ super(`process exited with code ${code}`);
26938
+ this.code = code;
26939
+ }
26940
+ code;
26941
+ };
26942
+ var LocalProcess = class extends EventEmitter3__default.default {
26943
+ constructor(task) {
26944
+ super();
26945
+ this.task = task;
26946
+ super.on("error", () => {
26947
+ });
26948
+ this.completion = new Promise((resolve2) => {
26949
+ this.resolveCompletion = resolve2;
26950
+ });
26951
+ setTimeout(() => void this.start(), 0);
26952
+ }
26953
+ task;
26954
+ completion;
26955
+ resolveCompletion;
26956
+ settled = false;
26957
+ killed = false;
26958
+ out = [];
26959
+ err = [];
26960
+ resolveKilled;
26961
+ killedPromise = new Promise((resolve2) => {
26962
+ this.resolveKilled = resolve2;
26963
+ });
26964
+ on(event, listener) {
26965
+ return super.on(event, listener);
26966
+ }
26967
+ output(text2) {
26968
+ this.out.push(text2);
26969
+ this.emit("output", text2);
26970
+ }
26971
+ error(text2) {
26972
+ this.err.push(text2);
26973
+ this.emit("error", text2);
26974
+ }
26975
+ write(_data) {
26976
+ }
26977
+ kill(_signal = "SIGTERM") {
26978
+ this.killed = true;
26979
+ this.resolveKilled();
26980
+ }
26981
+ waitForKill() {
26982
+ return this.killedPromise;
26983
+ }
26984
+ /** End the process now, for an asynchronous `process.exit`. */
26985
+ exitNow(code) {
26986
+ this.finish(code);
26987
+ this.resolveKilled();
26988
+ }
26989
+ async start() {
26990
+ if (this.killed) {
26991
+ this.finish(137);
26992
+ return;
26993
+ }
26994
+ try {
26995
+ this.finish(await this.task(this));
26996
+ } catch (error) {
26997
+ if (error instanceof ProcessExit) this.finish(error.code);
26998
+ else {
26999
+ this.error(formatError(error));
27000
+ this.finish(1);
27001
+ }
27002
+ }
27003
+ }
27004
+ finish(exitCode) {
27005
+ if (this.settled) return;
27006
+ this.settled = true;
27007
+ const result = { exitCode, stdout: this.out.join(""), stderr: this.err.join("") };
27008
+ this.emit("exit", exitCode);
27009
+ this.resolveCompletion(result);
27010
+ }
27011
+ };
27012
+ var PodChildProcess = class {
27013
+ constructor(pid, config, launch) {
27014
+ this.pid = pid;
27015
+ this.config = config;
27016
+ this.launch = launch;
27017
+ }
27018
+ pid;
27019
+ config;
27020
+ launch;
27021
+ state = "starting";
27022
+ exitCode;
27023
+ stdout = "";
27024
+ stderr = "";
27025
+ listeners = /* @__PURE__ */ new Map();
27026
+ started = false;
27027
+ cancelled = false;
27028
+ child;
27029
+ on(event, listener) {
27030
+ let set = this.listeners.get(event);
27031
+ if (!set) this.listeners.set(event, set = /* @__PURE__ */ new Set());
27032
+ set.add(listener);
27033
+ return this;
27034
+ }
27035
+ emit(event, ...args) {
27036
+ for (const listener of this.listeners.get(event) ?? []) listener(...args);
27037
+ }
27038
+ exec() {
27039
+ if (this.started) return;
27040
+ this.started = true;
27041
+ queueMicrotask(() => {
27042
+ if (this.cancelled) {
27043
+ this.finish(143);
27044
+ return;
27045
+ }
27046
+ this.state = "running";
27047
+ void this.launch(this.config).then(
27048
+ (child) => {
27049
+ this.child = child;
27050
+ if (this.cancelled) child.kill();
27051
+ child.on("output", (text2) => {
27052
+ this.stdout += text2;
27053
+ this.emit("stdout", text2);
27054
+ });
27055
+ child.on("error", (text2) => {
27056
+ this.stderr += text2;
27057
+ this.emit("stderr", text2);
27058
+ });
27059
+ void child.completion.then((result) => this.finish(result.exitCode));
27060
+ },
27061
+ (error) => {
27062
+ const text2 = error instanceof Error ? `${error.message}
27063
+ ` : `${String(error)}
27064
+ `;
27065
+ this.stderr += text2;
27066
+ this.emit("stderr", text2);
27067
+ this.finish(127);
27068
+ }
27069
+ );
27070
+ });
27071
+ }
27072
+ sendStdin(data) {
27073
+ this.child?.write(data);
27074
+ }
27075
+ kill(signal = "SIGTERM") {
27076
+ if (this.child) this.child.kill(signal);
27077
+ else this.cancelled = true;
27078
+ }
27079
+ finish(code) {
27080
+ if (this.state === "exited") return;
27081
+ this.state = "exited";
27082
+ this.exitCode = code;
27083
+ this.emit("exit", code);
27084
+ }
27085
+ };
27086
+ var nextChildPid = 805306368;
27087
+ var LocalRuntimePod = class _LocalRuntimePod {
27088
+ volume = new MemoryVolume();
27089
+ packages;
27090
+ instanceId = `sbx-${Math.random().toString(36).slice(2)}`;
27091
+ router = new VirtualHttpRouter();
27092
+ proxy = { activePorts: (_instanceId) => this.router.activePorts() };
27093
+ /**
27094
+ * Mutable on purpose: a container replaces `spawn` so that children resolve
27095
+ * against the kernel's PATH. Left alone, it runs `node` and reports anything
27096
+ * else as not found, which is the correct answer for a bare pod.
27097
+ */
27098
+ processManager = {
27099
+ spawn: (config) => new PodChildProcess(
27100
+ nextChildPid++,
27101
+ config,
27102
+ (child) => this.spawn(child.command, child.args ?? [], {
27103
+ ...child.cwd ? { cwd: child.cwd } : {},
27104
+ ...child.env ? { env: child.env } : {}
27105
+ })
27106
+ )
27107
+ };
27108
+ disposed = false;
27109
+ workdir;
27110
+ env;
27111
+ aliases;
27112
+ modules;
27113
+ constructor(options) {
27114
+ this.workdir = options.workdir ?? "/";
27115
+ this.env = { ...options.env };
27116
+ this.aliases = { ...WASM_ALIASES, ...options.aliases };
27117
+ this.modules = { ...options.modules };
27118
+ this.packages = new CleanPackageInstaller(this.volume, {
27119
+ cwd: this.workdir,
27120
+ ...options.registry ? { registry: options.registry } : {},
27121
+ ...options.fetch ? { fetch: options.fetch } : {}
27122
+ });
27123
+ this.seed(options.files ?? {});
27124
+ }
27125
+ static async boot(options = {}) {
27126
+ const pod = new _LocalRuntimePod(options);
27127
+ if (options.hostEsbuild !== false && !pod.modules.esbuild) {
27128
+ const esbuild = await loadHostEsbuild();
27129
+ if (esbuild) pod.modules.esbuild = esbuild;
27130
+ }
27131
+ return pod;
27132
+ }
27133
+ async spawn(command, args = [], options = {}) {
27134
+ this.assertActive();
27135
+ if (command !== "node" && command !== "nodejs") throw commandError(command);
27136
+ const script = args[0];
27137
+ if (!script) throw new Error("node: a script path is required");
27138
+ const cwd = typeof options.cwd === "string" ? options.cwd : this.workdir;
27139
+ const env2 = { ...this.env, ...isRecord(options.env) ? options.env : {} };
27140
+ const owner = `${this.instanceId}:${Math.random().toString(36).slice(2)}`;
27141
+ return new LocalProcess(async (proc) => {
27142
+ let requestedExit = 0;
27143
+ let evaluating = true;
27144
+ const core = createCoreModules({
27145
+ volume: this.volume,
27146
+ cwd,
27147
+ env: env2,
27148
+ argv: Array.isArray(options.argv) ? options.argv : ["/usr/bin/node", script, ...args.slice(1)],
27149
+ stdout: (text2) => proc.output(text2),
27150
+ stderr: (text2) => proc.error(text2),
27151
+ onExit: (code) => {
27152
+ requestedExit = code;
27153
+ if (evaluating) throw new ProcessExit(code);
27154
+ proc.exitNow(code);
27155
+ },
27156
+ http: { router: this.router, owner },
27157
+ spawnChild: (config) => this.processManager.spawn(config)
27158
+ });
27159
+ const engine = new CommonJsEngine(this.volume, {
27160
+ cwd,
27161
+ builtins: core.builtins,
27162
+ globals: core.globals,
27163
+ aliases: this.aliases,
27164
+ overrides: this.modules
27165
+ });
27166
+ try {
27167
+ try {
27168
+ await engine.run(script);
27169
+ } finally {
27170
+ evaluating = false;
27171
+ }
27172
+ await this.settle(owner, core.pendingHandles);
27173
+ if (this.router.activePorts(owner).length) {
27174
+ await proc.waitForKill();
27175
+ return 137;
27176
+ }
27177
+ return requestedExit;
27178
+ } finally {
27179
+ this.router.closeOwner(owner);
27180
+ }
27181
+ });
27182
+ }
27183
+ /**
27184
+ * Wait until the process has either started serving or genuinely run out of
27185
+ * work.
27186
+ *
27187
+ * Timers are the observable half of the event loop, so a process with none
27188
+ * outstanding and no port open has finished — and, being the common case for
27189
+ * a plain script, is settled without waiting at all.
27190
+ */
27191
+ async settle(owner, pendingHandles) {
27192
+ while (!this.router.activePorts(owner).length && pendingHandles() > 0) {
27193
+ await new Promise((resolve2) => setTimeout(resolve2, 5));
27194
+ }
27195
+ }
27196
+ async request(_port, _init = {}) {
27197
+ return this.router.request(_port, _init);
27198
+ }
27199
+ snapshot() {
27200
+ this.assertActive();
27201
+ return this.volume.snapshot();
27202
+ }
27203
+ async restore(snapshot) {
27204
+ this.assertActive();
27205
+ if (!Array.isArray(snapshot)) throw new TypeError("invalid runtime snapshot");
27206
+ this.volume.restore(snapshot);
27207
+ }
27208
+ teardown() {
27209
+ this.disposed = true;
27210
+ this.router.closeAll();
27211
+ }
27212
+ seed(files) {
27213
+ for (const [path, data] of Object.entries(files)) {
27214
+ const parts = path.split("/").filter(Boolean);
27215
+ let parent = "";
27216
+ for (const part of parts.slice(0, -1)) {
27217
+ parent += `/${part}`;
27218
+ try {
27219
+ this.volume.mkdirSync(parent);
27220
+ } catch (error) {
27221
+ if (error.code !== "EEXIST") throw error;
27222
+ }
27223
+ }
27224
+ this.volume.writeFileSync(path, data);
27225
+ }
27226
+ }
27227
+ assertActive() {
27228
+ if (this.disposed) throw new Error("runtime has been disposed");
27229
+ }
27230
+ };
27231
+ function commandError(command) {
27232
+ return Object.assign(new Error(`${command}: command not found`), { code: "ENOENT" });
27233
+ }
27234
+ function formatError(error) {
27235
+ if (error instanceof Error) return `${error.stack ?? `${error.name}: ${error.message}`}
27236
+ `;
27237
+ return `${String(error)}
27238
+ `;
27239
+ }
27240
+ function isRecord(value) {
27241
+ return typeof value === "object" && value !== null && !Array.isArray(value);
27242
+ }
27243
+
23891
27244
  // src/container/container.ts
23892
27245
  var Container = class _Container {
23893
27246
  kernel;
@@ -23932,8 +27285,8 @@ var Container = class _Container {
23932
27285
  // ── boot ──────────────────────────────────────────────────────────────────
23933
27286
  static async create(opts = {}) {
23934
27287
  if (opts.python) configurePython(opts.python);
23935
- if (!opts.pod && isNodeRuntime()) await installEsbuildRuntime();
23936
- const pod = opts.pod ?? (isNodeRuntime() ? await bootHeadlessPod(opts) : await bootBrowserPod(opts));
27288
+ if (!opts.pod && opts.runtime !== "sandboxedjs" && isNodeRuntime()) await installEsbuildRuntime();
27289
+ const pod = opts.pod ?? (opts.runtime === "sandboxedjs" ? await LocalRuntimePod.boot({ workdir: opts.cwd ?? "/", env: opts.env ?? {} }) : isNodeRuntime() ? await bootHeadlessPod(opts) : await bootBrowserPod(opts));
23937
27290
  const kernel = new Kernel({
23938
27291
  pod,
23939
27292
  hostname: opts.hostname ?? "sandbox",
@@ -24177,16 +27530,16 @@ var Container = class _Container {
24177
27530
  const combined = [];
24178
27531
  const decoder7 = new TextDecoder();
24179
27532
  const stdout = new BufferSink((chunk) => {
24180
- const text = decoder7.decode(chunk, { stream: true });
24181
- combined.push(text);
24182
- opts.onStdout?.(text);
24183
- this.hooks.onStdout?.(text);
27533
+ const text2 = decoder7.decode(chunk, { stream: true });
27534
+ combined.push(text2);
27535
+ opts.onStdout?.(text2);
27536
+ this.hooks.onStdout?.(text2);
24184
27537
  });
24185
27538
  const stderr = new BufferSink((chunk) => {
24186
- const text = decoder7.decode(chunk, { stream: true });
24187
- combined.push(text);
24188
- opts.onStderr?.(text);
24189
- this.hooks.onStderr?.(text);
27539
+ const text2 = decoder7.decode(chunk, { stream: true });
27540
+ combined.push(text2);
27541
+ opts.onStderr?.(text2);
27542
+ this.hooks.onStderr?.(text2);
24190
27543
  });
24191
27544
  if (opts.tty) {
24192
27545
  stdout.isTTY = true;
@@ -24447,8 +27800,8 @@ var Terminal = class {
24447
27800
  return this.closed;
24448
27801
  }
24449
27802
  // ── rendering ─────────────────────────────────────────────────────────────
24450
- write(text) {
24451
- this.opts.write(text);
27803
+ write(text2) {
27804
+ this.opts.write(text2);
24452
27805
  }
24453
27806
  promptText() {
24454
27807
  if (this.opts.prompt) return this.opts.prompt(this.session);
@@ -24715,7 +28068,7 @@ var Terminal = class {
24715
28068
  stdin.isTTY = true;
24716
28069
  stdin.interactive = true;
24717
28070
  this.currentStdin = stdin;
24718
- const sink = new CallbackSink((text) => this.write(text.replace(/(?<!\r)\n/g, "\r\n")), {
28071
+ const sink = new CallbackSink((text2) => this.write(text2.replace(/(?<!\r)\n/g, "\r\n")), {
24719
28072
  isTTY: true,
24720
28073
  columns: this.columns,
24721
28074
  rows: this.rows
@@ -24826,7 +28179,9 @@ var src_default = createContainer;
24826
28179
 
24827
28180
  exports.BufferSink = BufferSink;
24828
28181
  exports.CallbackSink = CallbackSink;
28182
+ exports.CleanPackageInstaller = CleanPackageInstaller;
24829
28183
  exports.CommandRegistry = CommandRegistry;
28184
+ exports.CommonJsEngine = CommonJsEngine;
24830
28185
  exports.Container = Container;
24831
28186
  exports.ContainerFs = ContainerFs;
24832
28187
  exports.FileInput = FileInput;
@@ -24835,6 +28190,8 @@ exports.IncompleteInputError = IncompleteInputError;
24835
28190
  exports.KERNEL_NAME = KERNEL_NAME;
24836
28191
  exports.KERNEL_RELEASE = KERNEL_RELEASE;
24837
28192
  exports.Kernel = Kernel;
28193
+ exports.LocalRuntimePod = LocalRuntimePod;
28194
+ exports.MemoryVolume = MemoryVolume;
24838
28195
  exports.NODE_VERSION = NODE_VERSION;
24839
28196
  exports.NPM_VERSION = NPM_VERSION;
24840
28197
  exports.NetworkStack = NetworkStack;
@@ -24856,6 +28213,11 @@ exports.TeeOutput = TeeOutput;
24856
28213
  exports.Terminal = Terminal;
24857
28214
  exports.UserDatabase = UserDatabase;
24858
28215
  exports.Vfs = Vfs;
28216
+ exports.VirtualHttpRouter = VirtualHttpRouter;
28217
+ exports.VirtualHttpServer = VirtualHttpServer;
28218
+ exports.VirtualIncomingMessage = VirtualIncomingMessage;
28219
+ exports.VirtualServerResponse = VirtualServerResponse;
28220
+ exports.WASM_ALIASES = WASM_ALIASES;
24859
28221
  exports.allCommands = allCommands;
24860
28222
  exports.applyChmod = applyChmod;
24861
28223
  exports.braceExpand = braceExpand;
@@ -24864,8 +28226,10 @@ exports.builtinNames = builtinNames;
24864
28226
  exports.captureStdio = captureStdio;
24865
28227
  exports.configureCPython = configureCPython;
24866
28228
  exports.configurePython = configurePython;
28229
+ exports.createChildProcessModule = createChildProcessModule;
24867
28230
  exports.createContainer = createContainer;
24868
28231
  exports.createContext = createContext;
28232
+ exports.createCoreModules = createCoreModules;
24869
28233
  exports.default = src_default;
24870
28234
  exports.defineCommand = defineCommand;
24871
28235
  exports.evalArith = evalArith;
@@ -24873,6 +28237,7 @@ exports.exitCodeForSignal = exitCodeForSignal;
24873
28237
  exports.expandPrompt = expandPrompt;
24874
28238
  exports.expandWord = expandWord;
24875
28239
  exports.expandWords = expandWords;
28240
+ exports.extractNpmTarball = extractNpmTarball;
24876
28241
  exports.fnmatch = fnmatch;
24877
28242
  exports.formatMode = formatMode;
24878
28243
  exports.getBuiltin = getBuiltin;
@@ -24884,6 +28249,7 @@ exports.isBuiltinName = isBuiltinName;
24884
28249
  exports.isCPythonAvailable = isCPythonAvailable;
24885
28250
  exports.isPythonAvailable = isPythonAvailable;
24886
28251
  exports.isSysError = isSysError;
28252
+ exports.looksLikeEsm = looksLikeEsm;
24887
28253
  exports.makeCred = makeCred;
24888
28254
  exports.normalizeSignal = normalizeSignal;
24889
28255
  exports.octalMode = octalMode;
@@ -24893,6 +28259,7 @@ exports.posixPath = path_exports;
24893
28259
  exports.resetPidCounter = resetPidCounter;
24894
28260
  exports.shellQuote = shellQuote;
24895
28261
  exports.strerror = strerror;
28262
+ exports.transformEsm = transformEsm;
24896
28263
  exports.unameInfo = unameInfo;
24897
28264
  //# sourceMappingURL=index.cjs.map
24898
28265
  //# sourceMappingURL=index.cjs.map