sandboxedjs 0.2.22 → 0.2.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.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { Inflate as Inflate$1, Deflate as Deflate$1, inflateRaw, ungzip, gzip as gzip$1, deflate as deflate$1, inflate as inflate$1, deflateRaw } from 'pako';
2
2
  import { sha256, sha224 } from '@noble/hashes/sha256';
3
- import { Parser as Parser$1, parse as parse$1 } from 'acorn';
4
- import jsx from 'acorn-jsx';
5
- import { transform } from 'sucrase';
6
3
  import { Buffer as Buffer$1 } from 'buffer/index.js';
7
4
  import { sha512, sha384 } from '@noble/hashes/sha512';
8
5
  import { sha1 } from '@noble/hashes/sha1';
9
6
  import { valid, maxSatisfying } from 'semver';
7
+ import { Parser as Parser$1, parse as parse$1 } from 'acorn';
8
+ import jsx from 'acorn-jsx';
9
+ import { transform } from 'sucrase';
10
10
  import EventEmitter4 from 'events/events.js';
11
11
  import { exports as exports$1, imports } from 'resolve.exports';
12
12
  import pathModule from 'path-browserify';
@@ -4130,9 +4130,9 @@ async function randomUuid() {
4130
4130
  const { randomUUID } = await nodeCrypto();
4131
4131
  return randomUUID();
4132
4132
  }
4133
- function toHex(bytes2) {
4133
+ function toHex(bytes3) {
4134
4134
  let out = "";
4135
- for (const byte of bytes2) out += byte.toString(16).padStart(2, "0");
4135
+ for (const byte of bytes3) out += byte.toString(16).padStart(2, "0");
4136
4136
  return out;
4137
4137
  }
4138
4138
  function md5Hex(input) {
@@ -4870,12 +4870,12 @@ var Vfs = class {
4870
4870
  writeFile(abs, data, opts = {}) {
4871
4871
  const cred = opts.privileged ? void 0 : opts.cred;
4872
4872
  const real = this.resolvePath(abs, { cred });
4873
- const bytes2 = typeof data === "string" ? encoder.encode(data) : data;
4873
+ const bytes3 = typeof data === "string" ? encoder.encode(data) : data;
4874
4874
  const virt = this.lookupVirtual(real);
4875
4875
  if (virt) {
4876
4876
  if (!virt.write) throw new SysError("EACCES", "write", real);
4877
4877
  this.require(this.statFromVirtual(real, virt), W_OK, cred, "open", real);
4878
- virt.write(bytes2, opts.append ?? false);
4878
+ virt.write(bytes3, opts.append ?? false);
4879
4879
  return;
4880
4880
  }
4881
4881
  if (this.isUnderProvider(real)) throw new SysError("ENOENT", "open", real);
@@ -4890,8 +4890,8 @@ var Vfs = class {
4890
4890
  this.require(pst, W_OK | X_OK, cred, "open", real);
4891
4891
  }
4892
4892
  try {
4893
- if (opts.append && existing) this.volume.appendFileSync(real, bytes2);
4894
- else this.volume.writeFileSync(real, bytes2);
4893
+ if (opts.append && existing) this.volume.appendFileSync(real, bytes3);
4894
+ else this.volume.writeFileSync(real, bytes3);
4895
4895
  } catch (e) {
4896
4896
  throw toSysError(e, "open", real);
4897
4897
  }
@@ -5143,7 +5143,7 @@ var Vfs = class {
5143
5143
  usage(abs = "/") {
5144
5144
  let files = 0;
5145
5145
  let dirs = 0;
5146
- let bytes2 = 0;
5146
+ let bytes3 = 0;
5147
5147
  for (const p of this.walk(abs)) {
5148
5148
  let st = null;
5149
5149
  try {
@@ -5154,10 +5154,10 @@ var Vfs = class {
5154
5154
  if (st.isDirectory()) dirs++;
5155
5155
  else {
5156
5156
  files++;
5157
- bytes2 += st.size;
5157
+ bytes3 += st.size;
5158
5158
  }
5159
5159
  }
5160
- return { files, dirs, bytes: bytes2 };
5160
+ return { files, dirs, bytes: bytes3 };
5161
5161
  }
5162
5162
  };
5163
5163
 
@@ -5241,10 +5241,10 @@ var Pipe = class _Pipe {
5241
5241
  write(data) {
5242
5242
  if (this.readerClosed) throw new SysError("EPIPE", "write");
5243
5243
  if (this.writerClosed) return;
5244
- const bytes2 = this.icrnl && !this.raw ? translateCarriageReturns(toBytes(data)) : toBytes(data);
5245
- if (bytes2.length === 0) return;
5246
- this.chunks.push(bytes2);
5247
- this.buffered += bytes2.length;
5244
+ const bytes3 = this.icrnl && !this.raw ? translateCarriageReturns(toBytes(data)) : toBytes(data);
5245
+ if (bytes3.length === 0) return;
5246
+ this.chunks.push(bytes3);
5247
+ this.buffered += bytes3.length;
5248
5248
  this.wake();
5249
5249
  }
5250
5250
  end() {
@@ -5334,15 +5334,15 @@ var Pipe = class _Pipe {
5334
5334
  return p;
5335
5335
  }
5336
5336
  };
5337
- function translateCarriageReturns(bytes2) {
5338
- if (!bytes2.includes(CR)) return bytes2;
5339
- const out = new Uint8Array(bytes2.length);
5337
+ function translateCarriageReturns(bytes3) {
5338
+ if (!bytes3.includes(CR)) return bytes3;
5339
+ const out = new Uint8Array(bytes3.length);
5340
5340
  let length = 0;
5341
- for (let index = 0; index < bytes2.length; index += 1) {
5342
- const byte = bytes2[index];
5341
+ for (let index = 0; index < bytes3.length; index += 1) {
5342
+ const byte = bytes3[index];
5343
5343
  if (byte === CR) {
5344
5344
  out[length++] = LF;
5345
- if (bytes2[index + 1] === LF) index += 1;
5345
+ if (bytes3[index + 1] === LF) index += 1;
5346
5346
  } else {
5347
5347
  out[length++] = byte;
5348
5348
  }
@@ -5388,11 +5388,11 @@ var BufferSink = class {
5388
5388
  }
5389
5389
  write(data) {
5390
5390
  if (this._closed) return;
5391
- const bytes2 = toBytes(data);
5392
- if (bytes2.length === 0) return;
5393
- this.chunks.push(bytes2);
5394
- this.total += bytes2.length;
5395
- this.onWrite?.(bytes2);
5391
+ const bytes3 = toBytes(data);
5392
+ if (bytes3.length === 0) return;
5393
+ this.chunks.push(bytes3);
5394
+ this.total += bytes3.length;
5395
+ this.onWrite?.(bytes3);
5396
5396
  }
5397
5397
  end() {
5398
5398
  this._closed = true;
@@ -6281,8 +6281,8 @@ var SIZEOF_FDSTAT = 24;
6281
6281
  var SIZEOF_DIRENT = 24;
6282
6282
  var SIZEOF_SUBSCRIPTION = 48;
6283
6283
  var SIZEOF_EVENT = 32;
6284
- function isWasmBinary(bytes2) {
6285
- return bytes2.length >= 4 && bytes2[0] === 0 && bytes2[1] === 97 && bytes2[2] === 115 && bytes2[3] === 109;
6284
+ function isWasmBinary(bytes3) {
6285
+ return bytes3.length >= 4 && bytes3[0] === 0 && bytes3[1] === 97 && bytes3[2] === 115 && bytes3[3] === 109;
6286
6286
  }
6287
6287
 
6288
6288
  // src/wasi/host.ts
@@ -7072,8 +7072,8 @@ function defaultSleep(milliseconds) {
7072
7072
  // src/wasi/run.ts
7073
7073
  var compiled = /* @__PURE__ */ new Map();
7074
7074
  var MAX_CACHED_MODULES = 32;
7075
- async function runWasi(ctx, bytes2, options = {}) {
7076
- if (!isWasmBinary(bytes2)) {
7075
+ async function runWasi(ctx, bytes3, options = {}) {
7076
+ if (!isWasmBinary(bytes3)) {
7077
7077
  ctx.warn("cannot execute binary file: not a WebAssembly module");
7078
7078
  return EXIT_NOT_EXECUTABLE;
7079
7079
  }
@@ -7097,7 +7097,7 @@ async function runWasi(ctx, bytes2, options = {}) {
7097
7097
  });
7098
7098
  let instance;
7099
7099
  try {
7100
- const module = await compile(bytes2);
7100
+ const module = await compile(bytes3);
7101
7101
  instance = await WebAssembly.instantiate(module, {
7102
7102
  ...options.imports,
7103
7103
  wasi_snapshot_preview1: host2.wasiImport,
@@ -7133,15 +7133,15 @@ async function runWasi(ctx, bytes2, options = {}) {
7133
7133
  }
7134
7134
  }
7135
7135
  }
7136
- async function compile(bytes2) {
7137
- const key = await digest(bytes2);
7136
+ async function compile(bytes3) {
7137
+ const key = await digest(bytes3);
7138
7138
  const hit = compiled.get(key);
7139
7139
  if (hit) {
7140
7140
  compiled.delete(key);
7141
7141
  compiled.set(key, hit);
7142
7142
  return hit;
7143
7143
  }
7144
- const module = await WebAssembly.compile(sliceForWasm(bytes2));
7144
+ const module = await WebAssembly.compile(sliceForWasm(bytes3));
7145
7145
  compiled.set(key, module);
7146
7146
  if (compiled.size > MAX_CACHED_MODULES) {
7147
7147
  const oldest = compiled.keys().next().value;
@@ -7149,12 +7149,12 @@ async function compile(bytes2) {
7149
7149
  }
7150
7150
  return module;
7151
7151
  }
7152
- async function digest(bytes2) {
7153
- const hash = await crypto.subtle.digest("SHA-256", sliceForWasm(bytes2));
7152
+ async function digest(bytes3) {
7153
+ const hash = await crypto.subtle.digest("SHA-256", sliceForWasm(bytes3));
7154
7154
  return Array.from(new Uint8Array(hash, 0, 16), (byte) => byte.toString(16).padStart(2, "0")).join("");
7155
7155
  }
7156
- function sliceForWasm(bytes2) {
7157
- return bytes2.buffer.slice(bytes2.byteOffset, bytes2.byteOffset + bytes2.byteLength);
7156
+ function sliceForWasm(bytes3) {
7157
+ return bytes3.buffer.slice(bytes3.byteOffset, bytes3.byteOffset + bytes3.byteLength);
7158
7158
  }
7159
7159
  async function primeStdin(ctx) {
7160
7160
  let pending = new Uint8Array(0);
@@ -7186,19 +7186,19 @@ function describeStartupFailure(error) {
7186
7186
  }
7187
7187
 
7188
7188
  // src/compat/execution.ts
7189
- function binaryDigest(bytes2) {
7190
- return Array.from(sha256(bytes2), (b) => b.toString(16).padStart(2, "0")).join("");
7189
+ function binaryDigest(bytes3) {
7190
+ return Array.from(sha256(bytes3), (b) => b.toString(16).padStart(2, "0")).join("");
7191
7191
  }
7192
- function isElfBinary(bytes2) {
7193
- return bytes2[0] === 127 && bytes2[1] === 69 && bytes2[2] === 76 && bytes2[3] === 70;
7192
+ function isElfBinary(bytes3) {
7193
+ return bytes3[0] === 127 && bytes3[1] === 69 && bytes3[2] === 76 && bytes3[3] === 70;
7194
7194
  }
7195
- function inspectElf(bytes2) {
7196
- if (!isElfBinary(bytes2) || ![1, 2].includes(bytes2[4]) || ![1, 2].includes(bytes2[5]) || bytes2[6] !== 1 || bytes2.length < (bytes2[4] === 2 ? 64 : 52)) throw new Error("invalid or truncated ELF header");
7197
- const littleEndian = bytes2[5] === 1;
7198
- const machine = new DataView(bytes2.buffer, bytes2.byteOffset, bytes2.byteLength).getUint16(18, littleEndian);
7195
+ function inspectElf(bytes3) {
7196
+ if (!isElfBinary(bytes3) || ![1, 2].includes(bytes3[4]) || ![1, 2].includes(bytes3[5]) || bytes3[6] !== 1 || bytes3.length < (bytes3[4] === 2 ? 64 : 52)) throw new Error("invalid or truncated ELF header");
7197
+ const littleEndian = bytes3[5] === 1;
7198
+ const machine = new DataView(bytes3.buffer, bytes3.byteOffset, bytes3.byteLength).getUint16(18, littleEndian);
7199
7199
  return {
7200
7200
  format: "elf",
7201
- bits: bytes2[4] === 2 ? 64 : 32,
7201
+ bits: bytes3[4] === 2 ? 64 : 32,
7202
7202
  machine,
7203
7203
  littleEndian,
7204
7204
  architecture: { 3: "x86", 62: "x86_64", 40: "arm", 183: "aarch64", 243: "riscv" }[machine] ?? `machine-${machine}`
@@ -7225,14 +7225,14 @@ var BinaryExecutionRegistry = class {
7225
7225
  return this.backends.map(({ id, tier }) => ({ id, tier }));
7226
7226
  }
7227
7227
  async run(ctx, path) {
7228
- const bytes2 = ctx.vfs.readFile(path, ctx.cred);
7228
+ const bytes3 = ctx.vfs.readFile(path, ctx.cred);
7229
7229
  let info2;
7230
7230
  try {
7231
- info2 = inspectElf(bytes2);
7231
+ info2 = inspectElf(bytes3);
7232
7232
  } catch (error) {
7233
7233
  return ctx.fail(String(error), 126);
7234
7234
  }
7235
- const request = { path, bytes: bytes2, info: info2, sha256: binaryDigest(bytes2) };
7235
+ const request = { path, bytes: bytes3, info: info2, sha256: binaryDigest(bytes3) };
7236
7236
  const reasons = [];
7237
7237
  const backends = [...this.backends];
7238
7238
  for (const tier of ["compatibility", "translation", "emulation"]) {
@@ -7255,10 +7255,10 @@ var BinaryExecutionRegistry = class {
7255
7255
  }
7256
7256
  };
7257
7257
  function checkedWasm(artifact) {
7258
- const bytes2 = artifact.bytes.slice();
7259
- if (!/^[a-f0-9]{64}$/i.test(artifact.sha256) || binaryDigest(bytes2) !== artifact.sha256.toLowerCase()) throw new Error("Wasm artifact integrity mismatch");
7260
- if (!WebAssembly.validate(bytes2)) throw new Error("invalid WebAssembly artifact");
7261
- return bytes2;
7258
+ const bytes3 = artifact.bytes.slice();
7259
+ if (!/^[a-f0-9]{64}$/i.test(artifact.sha256) || binaryDigest(bytes3) !== artifact.sha256.toLowerCase()) throw new Error("Wasm artifact integrity mismatch");
7260
+ if (!WebAssembly.validate(bytes3)) throw new Error("invalid WebAssembly artifact");
7261
+ return bytes3;
7262
7262
  }
7263
7263
  function installWasmCommands(kernel, artifacts) {
7264
7264
  const names = /* @__PURE__ */ new Set();
@@ -7267,7 +7267,7 @@ function installWasmCommands(kernel, artifacts) {
7267
7267
  names.add(artifact.name);
7268
7268
  return { name: artifact.name, bytes: checkedWasm(artifact) };
7269
7269
  });
7270
- for (const { name, bytes: bytes2 } of checked) kernel.installCommand({ name, run: (ctx) => runWasi(ctx, bytes2) });
7270
+ for (const { name, bytes: bytes3 } of checked) kernel.installCommand({ name, run: (ctx) => runWasi(ctx, bytes3) });
7271
7271
  }
7272
7272
  function createWasmCompatibilityBackend(id, entries) {
7273
7273
  const ports = new Map(entries.map((entry) => {
@@ -7275,8 +7275,8 @@ function createWasmCompatibilityBackend(id, entries) {
7275
7275
  return [entry.elfSha256.toLowerCase(), checkedWasm(entry.wasm)];
7276
7276
  }));
7277
7277
  return { id, tier: "compatibility", prepare(request) {
7278
- const bytes2 = ports.get(request.sha256);
7279
- return bytes2 ? { supported: true, program: { run: (ctx) => runWasi(ctx, bytes2, { argv: [request.path, ...ctx.args] }) } } : { supported: false, reason: "no port for this binary digest" };
7278
+ const bytes3 = ports.get(request.sha256);
7279
+ return bytes3 ? { supported: true, program: { run: (ctx) => runWasi(ctx, bytes3, { argv: [request.path, ...ctx.args] }) } } : { supported: false, reason: "no port for this binary digest" };
7280
7280
  } };
7281
7281
  }
7282
7282
  function createTranslationBackend(translator, maxCacheBytes = 32 * 1024 * 1024) {
@@ -7285,32 +7285,32 @@ function createTranslationBackend(translator, maxCacheBytes = 32 * 1024 * 1024)
7285
7285
  let size = 0;
7286
7286
  return { id: translator.id, tier: "translation", async prepare(request, signal) {
7287
7287
  if (!translator.supports(request.info)) return { supported: false, reason: "unsupported ELF architecture" };
7288
- let bytes2 = cache.get(request.sha256);
7289
- if (bytes2) {
7288
+ let bytes3 = cache.get(request.sha256);
7289
+ if (bytes3) {
7290
7290
  cache.delete(request.sha256);
7291
- cache.set(request.sha256, bytes2);
7291
+ cache.set(request.sha256, bytes3);
7292
7292
  } else {
7293
7293
  const output = await translator.translate(request, signal);
7294
7294
  if (signal.aborted) return { supported: false, reason: "cancelled" };
7295
7295
  if (!output) return { supported: false, reason: "translator declined this program" };
7296
- bytes2 = output.slice();
7297
- if (!WebAssembly.validate(bytes2.slice())) throw new Error(`${translator.id}: invalid translator output`);
7298
- if (bytes2.byteLength <= maxCacheBytes) {
7296
+ bytes3 = output.slice();
7297
+ if (!WebAssembly.validate(bytes3.slice())) throw new Error(`${translator.id}: invalid translator output`);
7298
+ if (bytes3.byteLength <= maxCacheBytes) {
7299
7299
  const previous = cache.get(request.sha256);
7300
7300
  if (previous) {
7301
7301
  size -= previous.byteLength;
7302
7302
  cache.delete(request.sha256);
7303
7303
  }
7304
- while (size + bytes2.byteLength > maxCacheBytes && cache.size) {
7304
+ while (size + bytes3.byteLength > maxCacheBytes && cache.size) {
7305
7305
  const key = cache.keys().next().value;
7306
7306
  size -= cache.get(key).byteLength;
7307
7307
  cache.delete(key);
7308
7308
  }
7309
- cache.set(request.sha256, bytes2);
7310
- size += bytes2.byteLength;
7309
+ cache.set(request.sha256, bytes3);
7310
+ size += bytes3.byteLength;
7311
7311
  }
7312
7312
  }
7313
- const artifact = bytes2;
7313
+ const artifact = bytes3;
7314
7314
  return { supported: true, program: { run: (ctx) => runWasi(ctx, artifact, { argv: [request.path, ...ctx.args] }) } };
7315
7315
  } };
7316
7316
  }
@@ -8359,18 +8359,18 @@ function createSysProvider(kernel) {
8359
8359
  }
8360
8360
 
8361
8361
  // src/net/proxy-fetch.ts
8362
- function toBase64(bytes2) {
8362
+ function toBase64(bytes3) {
8363
8363
  let text2 = "";
8364
- for (let at = 0; at < bytes2.length; at += 32768) {
8365
- text2 += String.fromCharCode(...bytes2.subarray(at, at + 32768));
8364
+ for (let at = 0; at < bytes3.length; at += 32768) {
8365
+ text2 += String.fromCharCode(...bytes3.subarray(at, at + 32768));
8366
8366
  }
8367
8367
  return btoa(text2);
8368
8368
  }
8369
8369
  function fromBase64(text2) {
8370
8370
  const binary = atob(text2);
8371
- const bytes2 = new Uint8Array(binary.length);
8372
- for (let at = 0; at < binary.length; at += 1) bytes2[at] = binary.charCodeAt(at);
8373
- return bytes2;
8371
+ const bytes3 = new Uint8Array(binary.length);
8372
+ for (let at = 0; at < binary.length; at += 1) bytes3[at] = binary.charCodeAt(at);
8373
+ return bytes3;
8374
8374
  }
8375
8375
  async function proxyExchange(proxy, request, fetchImpl = fetch) {
8376
8376
  let answer;
@@ -8457,6 +8457,93 @@ async function discoverEgress(fetchImpl = fetch) {
8457
8457
  return await found;
8458
8458
  }
8459
8459
 
8460
+ // src/net/secrets.ts
8461
+ var PLACEHOLDER = /\{\{secret:([A-Za-z_][A-Za-z0-9_]*)\}\}/g;
8462
+ var REDACTED = "[sealed]";
8463
+ var SecretRefused = class extends Error {
8464
+ code = "EACCES";
8465
+ };
8466
+ function hostBound(secret, hostname) {
8467
+ return secret.hosts.some((host2) => hostname === host2 || hostname.endsWith(`.${host2}`));
8468
+ }
8469
+ function mentionsSecret(text2) {
8470
+ PLACEHOLDER.lastIndex = 0;
8471
+ return PLACEHOLDER.test(text2);
8472
+ }
8473
+ function substituteSecrets(text2, hostname, secrets) {
8474
+ return text2.replace(PLACEHOLDER, (_match, name) => {
8475
+ const secret = Object.prototype.hasOwnProperty.call(secrets, name) ? secrets[name] : void 0;
8476
+ if (!secret) {
8477
+ throw new SecretRefused(`no sealed secret named ${name} is configured for this container`);
8478
+ }
8479
+ if (!hostBound(secret, hostname)) {
8480
+ throw new SecretRefused(
8481
+ `the sealed secret ${name} is not bound to ${hostname}; it may only be sent to ${secret.hosts.join(", ") || "no host"}`
8482
+ );
8483
+ }
8484
+ return secret.value;
8485
+ });
8486
+ }
8487
+ function sealRequest(request, secrets) {
8488
+ const url = new URL(request.url);
8489
+ if (mentionsSecret(decodeURIComponent(url.href))) {
8490
+ throw new SecretRefused("a sealed secret can only be used in a request header, not in the URL");
8491
+ }
8492
+ const used = [];
8493
+ let headers = null;
8494
+ request.headers.forEach((value, name) => {
8495
+ if (!mentionsSecret(value)) return;
8496
+ headers ??= new Headers(request.headers);
8497
+ headers.set(name, substituteSecrets(value, url.hostname, secrets));
8498
+ PLACEHOLDER.lastIndex = 0;
8499
+ for (const match2 of value.matchAll(PLACEHOLDER)) used.push(match2[1]);
8500
+ });
8501
+ return headers ? { request: new Request(request, { headers }), used } : { request, used };
8502
+ }
8503
+ function redactResponse(response, secrets) {
8504
+ const values = Object.values(secrets).map((secret) => secret.value).filter((value) => value.length > 0);
8505
+ if (values.length === 0) return response;
8506
+ const headers = new Headers();
8507
+ response.headers.forEach((value, name) => headers.set(name, redactText(value, values)));
8508
+ const init = { status: response.status, statusText: response.statusText, headers };
8509
+ if (!response.body) return new Response(null, init);
8510
+ headers.delete("content-length");
8511
+ return new Response(response.body.pipeThrough(redactingStream(values)), init);
8512
+ }
8513
+ function redactText(text2, values) {
8514
+ let out = text2;
8515
+ for (const value of values) out = out.split(value).join(REDACTED);
8516
+ return out;
8517
+ }
8518
+ function redactingStream(values) {
8519
+ const needles = values.map((value) => latin1(new TextEncoder().encode(value)));
8520
+ const hold = Math.max(...needles.map((needle) => needle.length)) - 1;
8521
+ let pending = "";
8522
+ return new TransformStream({
8523
+ transform(chunk, controller) {
8524
+ pending = redactText(pending + latin1(chunk), needles);
8525
+ if (pending.length <= hold) return;
8526
+ controller.enqueue(bytes(pending.slice(0, pending.length - hold)));
8527
+ pending = pending.slice(pending.length - hold);
8528
+ },
8529
+ flush(controller) {
8530
+ if (pending) controller.enqueue(bytes(redactText(pending, needles)));
8531
+ }
8532
+ });
8533
+ }
8534
+ function latin1(chunk) {
8535
+ let out = "";
8536
+ for (let at = 0; at < chunk.length; at += 32768) {
8537
+ out += String.fromCharCode(...chunk.subarray(at, at + 32768));
8538
+ }
8539
+ return out;
8540
+ }
8541
+ function bytes(text2) {
8542
+ const out = new Uint8Array(text2.length);
8543
+ for (let index = 0; index < text2.length; index += 1) out[index] = text2.charCodeAt(index);
8544
+ return out;
8545
+ }
8546
+
8460
8547
  // src/net/policy.ts
8461
8548
  function isLoopbackHostname(hostname) {
8462
8549
  const host2 = hostname.replace(/^\[|\]$/g, "").toLowerCase();
@@ -8494,6 +8581,24 @@ function requestUrl(input) {
8494
8581
  return input.url;
8495
8582
  }
8496
8583
  function policedFetch(policy, fetchImpl) {
8584
+ const secrets = policy.secrets && Object.keys(policy.secrets).length > 0 ? policy.secrets : null;
8585
+ if (!secrets) return policedPlainFetch(policy, fetchImpl);
8586
+ const plain = policedPlainFetch(policy, fetchImpl);
8587
+ return (async (input, init) => {
8588
+ const url = requestUrl(input);
8589
+ if (!outboundAllowed(policy, url)) {
8590
+ throw Object.assign(new TypeError("fetch failed"), { cause: outboundBlockedError(url) });
8591
+ }
8592
+ let sealed;
8593
+ try {
8594
+ sealed = sealRequest(new Request(input, init), secrets).request;
8595
+ } catch (error) {
8596
+ throw Object.assign(new TypeError("fetch failed"), { cause: error });
8597
+ }
8598
+ return redactResponse(await plain(sealed), secrets);
8599
+ });
8600
+ }
8601
+ function policedPlainFetch(policy, fetchImpl) {
8497
8602
  return (async (input, init) => {
8498
8603
  const url = requestUrl(input);
8499
8604
  if (!outboundAllowed(policy, url)) {
@@ -8730,22 +8835,22 @@ var NetworkStack = class {
8730
8835
  `;
8731
8836
  return out;
8732
8837
  }
8733
- countTx(bytes2, iface = "eth0") {
8838
+ countTx(bytes3, iface = "eth0") {
8734
8839
  const i = this.interface(iface);
8735
8840
  if (!i) return;
8736
- i.txBytes += bytes2;
8737
- i.txPackets += Math.max(1, Math.ceil(bytes2 / 1400));
8841
+ i.txBytes += bytes3;
8842
+ i.txPackets += Math.max(1, Math.ceil(bytes3 / 1400));
8738
8843
  }
8739
- countRx(bytes2, iface = "eth0") {
8844
+ countRx(bytes3, iface = "eth0") {
8740
8845
  const i = this.interface(iface);
8741
8846
  if (!i) return;
8742
- i.rxBytes += bytes2;
8743
- i.rxPackets += Math.max(1, Math.ceil(bytes2 / 1400));
8847
+ i.rxBytes += bytes3;
8848
+ i.rxPackets += Math.max(1, Math.ceil(bytes3 / 1400));
8744
8849
  }
8745
8850
  };
8746
8851
  function randomMac() {
8747
- const bytes2 = [2, 66, 172, 17, 0, 2];
8748
- return bytes2.map((b) => b.toString(16).padStart(2, "0")).join(":");
8852
+ const bytes3 = [2, 66, 172, 17, 0, 2];
8853
+ return bytes3.map((b) => b.toString(16).padStart(2, "0")).join(":");
8749
8854
  }
8750
8855
  function hexIp(ip2) {
8751
8856
  return ip2.split(".").reverse().map((o) => Number(o).toString(16).padStart(2, "0").toUpperCase()).join("");
@@ -9190,15 +9295,15 @@ var Parser = class {
9190
9295
  if (this.isWord("-p")) this.next();
9191
9296
  }
9192
9297
  }
9193
- const commands12 = [this.parseCommand()];
9298
+ const commands13 = [this.parseCommand()];
9194
9299
  const stderrToo = [];
9195
9300
  while (this.isOp("|") || this.isOp("|&")) {
9196
9301
  stderrToo.push(this.next().value === "|&");
9197
9302
  this.skipNewlines();
9198
- commands12.push(this.parseCommand());
9303
+ commands13.push(this.parseCommand());
9199
9304
  }
9200
- if (commands12.length === 1 && !negated && !timed) return commands12[0];
9201
- return { type: "pipeline", commands: commands12, negated, stderrToo, timed };
9305
+ if (commands13.length === 1 && !negated && !timed) return commands13[0];
9306
+ return { type: "pipeline", commands: commands13, negated, stderrToo, timed };
9202
9307
  }
9203
9308
  // ── commands ─────────────────────────────────────────────────────────────
9204
9309
  parseCommand() {
@@ -10818,8 +10923,8 @@ var decoder4 = new TextDecoder();
10818
10923
  async function readInputs(ctx, operands, opts = {}) {
10819
10924
  const stdinName = opts.stdinName ?? "-";
10820
10925
  if (operands.length === 0) {
10821
- const bytes2 = await ctx.stdin.readAll();
10822
- return { sources: [{ name: stdinName, bytes: bytes2 }], ok: true };
10926
+ const bytes3 = await ctx.stdin.readAll();
10927
+ return { sources: [{ name: stdinName, bytes: bytes3 }], ok: true };
10823
10928
  }
10824
10929
  const sources = [];
10825
10930
  let ok2 = true;
@@ -10844,8 +10949,8 @@ async function readInputs(ctx, operands, opts = {}) {
10844
10949
  }
10845
10950
  return { sources, ok: ok2 };
10846
10951
  }
10847
- function splitLines(bytes2) {
10848
- const text2 = decoder4.decode(bytes2);
10952
+ function splitLines(bytes3) {
10953
+ const text2 = decoder4.decode(bytes3);
10849
10954
  if (text2 === "") return { lines: [], trailingNewline: true };
10850
10955
  const trailingNewline = text2.endsWith("\n");
10851
10956
  const body = trailingNewline ? text2.slice(0, -1) : text2;
@@ -10857,11 +10962,11 @@ function joinLines(lines, trailingNewline = true) {
10857
10962
  }
10858
10963
  var SI_UNITS = ["", "k", "M", "G", "T", "P", "E"];
10859
10964
  var IEC_UNITS = ["", "K", "M", "G", "T", "P", "E"];
10860
- function humanSize(bytes2, opts = {}) {
10965
+ function humanSize(bytes3, opts = {}) {
10861
10966
  const base2 = opts.si ? 1e3 : 1024;
10862
10967
  const units = opts.si ? SI_UNITS : IEC_UNITS;
10863
- if (bytes2 < base2) return String(bytes2);
10864
- let value = bytes2;
10968
+ if (bytes3 < base2) return String(bytes3);
10969
+ let value = bytes3;
10865
10970
  let unit = 0;
10866
10971
  while (value >= base2 && unit < units.length - 1) {
10867
10972
  value /= base2;
@@ -11151,7 +11256,7 @@ var cat = defineCommand({
11151
11256
  let lineNumber = 1;
11152
11257
  let lastWasBlank = false;
11153
11258
  for (const operand of operands) {
11154
- let bytes2;
11259
+ let bytes3;
11155
11260
  if (operand === "-") {
11156
11261
  if (plain) {
11157
11262
  for (; ; ) {
@@ -11162,7 +11267,7 @@ var cat = defineCommand({
11162
11267
  }
11163
11268
  continue;
11164
11269
  }
11165
- bytes2 = await ctx.stdin.readAll();
11270
+ bytes3 = await ctx.stdin.readAll();
11166
11271
  } else {
11167
11272
  try {
11168
11273
  const abs = ctx.path(operand);
@@ -11172,17 +11277,17 @@ var cat = defineCommand({
11172
11277
  status = 1;
11173
11278
  continue;
11174
11279
  }
11175
- bytes2 = ctx.vfs.readFile(abs, ctx.cred);
11280
+ bytes3 = ctx.vfs.readFile(abs, ctx.cred);
11176
11281
  } catch (e) {
11177
11282
  status = ctx.reportError(e, operand);
11178
11283
  continue;
11179
11284
  }
11180
11285
  }
11181
11286
  if (plain) {
11182
- ctx.write(bytes2);
11287
+ ctx.write(bytes3);
11183
11288
  continue;
11184
11289
  }
11185
- const text2 = new TextDecoder().decode(bytes2);
11290
+ const text2 = new TextDecoder().decode(bytes3);
11186
11291
  const hadTrailing = text2.endsWith("\n");
11187
11292
  const parts = (hadTrailing ? text2.slice(0, -1) : text2).split("\n");
11188
11293
  for (const raw of parts) {
@@ -12036,15 +12141,15 @@ function describeFile(ctx, abs, st, mime) {
12036
12141
  }
12037
12142
  if (st.isCharacterDevice()) return mime ? "inode/chardevice" : "character special";
12038
12143
  if (st.size === 0) return mime ? "inode/x-empty" : "empty";
12039
- const bytes2 = ctx.vfs.readFile(abs, ctx.cred).subarray(0, 512);
12040
- const magic = [...bytes2.subarray(0, 4)];
12144
+ const bytes3 = ctx.vfs.readFile(abs, ctx.cred).subarray(0, 512);
12145
+ const magic = [...bytes3.subarray(0, 4)];
12041
12146
  if (magic[0] === 127 && magic[1] === 69 && magic[2] === 76 && magic[3] === 70) {
12042
12147
  return mime ? "application/x-executable" : "ELF 64-bit LSB executable, x86-64";
12043
12148
  }
12044
12149
  if (magic[0] === 31 && magic[1] === 139) return mime ? "application/gzip" : "gzip compressed data";
12045
12150
  if (magic[0] === 80 && magic[1] === 75) return mime ? "application/zip" : "Zip archive data";
12046
12151
  if (magic[0] === 137 && magic[1] === 80) return mime ? "image/png" : "PNG image data";
12047
- const text2 = new TextDecoder().decode(bytes2);
12152
+ const text2 = new TextDecoder().decode(bytes3);
12048
12153
  const printable = [...text2].every((c) => c === "\n" || c === " " || c === "\r" || c >= " " && c <= "~" || c.charCodeAt(0) > 127);
12049
12154
  if (!printable) return mime ? "application/octet-stream" : "data";
12050
12155
  if (text2.startsWith("#!")) {
@@ -12947,6 +13052,523 @@ var commands3 = [
12947
13052
  clear,
12948
13053
  sync
12949
13054
  ];
13055
+ var platformBuffer = globalThis.Buffer;
13056
+ addUint8ArraySupport(addBase64UrlSupport(Buffer$1));
13057
+ var Buffer2 = platformBuffer ?? Buffer$1;
13058
+ function addUint8ArraySupport(BufferClass) {
13059
+ const target = BufferClass;
13060
+ if (target.__sandboxedUint8Array) return BufferClass;
13061
+ Object.defineProperty(target, "__sandboxedUint8Array", { value: true });
13062
+ const asBuffer = (value) => value instanceof Uint8Array && !target.isBuffer(value) ? target.from(value.buffer, value.byteOffset, value.byteLength) : value;
13063
+ for (const method of ["indexOf", "lastIndexOf", "includes"]) {
13064
+ const original = target.prototype[method];
13065
+ target.prototype[method] = function(value, ...rest) {
13066
+ return original.call(this, asBuffer(value), ...rest);
13067
+ };
13068
+ }
13069
+ const equals = target.prototype.equals;
13070
+ target.prototype.equals = function(other) {
13071
+ return equals.call(this, asBuffer(other));
13072
+ };
13073
+ return BufferClass;
13074
+ }
13075
+ function addBase64UrlSupport(BufferClass) {
13076
+ const target = BufferClass;
13077
+ if (target.__sandboxedBase64Url) return BufferClass;
13078
+ Object.defineProperty(target, "__sandboxedBase64Url", { value: true });
13079
+ const from = target.from.bind(target);
13080
+ target.from = (value, encodingOrOffset, length) => from(value, normalizeEncoding(encodingOrOffset), length);
13081
+ const byteLength = target.byteLength.bind(target);
13082
+ target.byteLength = (value, encoding) => byteLength(value, normalizeEncoding(encoding));
13083
+ const isEncoding = target.isEncoding?.bind(target);
13084
+ if (isEncoding) target.isEncoding = (encoding) => encoding.toLowerCase() === "base64url" || isEncoding(encoding);
13085
+ const toString = target.prototype.toString;
13086
+ target.prototype.toString = function(encoding, start2, end) {
13087
+ if (encoding?.toLowerCase() !== "base64url") return toString.call(this, encoding, start2, end);
13088
+ return toString.call(this, "base64", start2, end).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
13089
+ };
13090
+ const write = target.prototype.write;
13091
+ target.prototype.write = function(...args) {
13092
+ const index = typeof args[1] === "string" ? 1 : typeof args[2] === "string" ? 2 : 3;
13093
+ if (typeof args[index] === "string") args[index] = normalizeEncoding(args[index]);
13094
+ return write.apply(this, args);
13095
+ };
13096
+ return BufferClass;
13097
+ }
13098
+ function normalizeEncoding(value) {
13099
+ return typeof value === "string" && value.toLowerCase() === "base64url" ? "base64" : value;
13100
+ }
13101
+
13102
+ // src/pkg/clean-installer.ts
13103
+ init_path();
13104
+
13105
+ // src/browser/playwright-browsers.ts
13106
+ init_path();
13107
+ var PLAYWRIGHT_REGISTRY = "/root/.cache/ms-playwright";
13108
+ var LAYOUTS = {
13109
+ "chromium": ["chrome-linux64", "chrome"],
13110
+ "chromium-headless-shell": ["chrome-headless-shell-linux64", "chrome-headless-shell"]
13111
+ };
13112
+ function virtualBrowserFiles(browsersJson) {
13113
+ let manifest;
13114
+ try {
13115
+ manifest = JSON.parse(browsersJson);
13116
+ } catch {
13117
+ return [];
13118
+ }
13119
+ const encoder9 = new TextEncoder();
13120
+ const files = [];
13121
+ for (const browser of manifest.browsers ?? []) {
13122
+ const layout = LAYOUTS[browser.name];
13123
+ if (!layout) continue;
13124
+ const dir3 = join(PLAYWRIGHT_REGISTRY, `${browser.name.replace(/-/g, "_")}-${browser.revision}`);
13125
+ files.push({ path: join(dir3, ...layout), data: encoder9.encode(`#!${BUILTIN_INTERPRETER} chrome
13126
+ `), mode: 493 });
13127
+ files.push({ path: join(dir3, "INSTALLATION_COMPLETE"), data: new Uint8Array() });
13128
+ }
13129
+ return files;
13130
+ }
13131
+ function mkdirp(volume, path) {
13132
+ let current2 = "";
13133
+ for (const part of segments(path)) {
13134
+ current2 += `/${part}`;
13135
+ try {
13136
+ volume.mkdirSync(current2, { mode: 493 });
13137
+ } catch (error) {
13138
+ if (error.code !== "EEXIST") throw error;
13139
+ }
13140
+ }
13141
+ }
13142
+ function installVirtualPlaywrightBrowsers(volume, packageDir) {
13143
+ let text2;
13144
+ try {
13145
+ text2 = new TextDecoder().decode(volume.readFileSync(join(packageDir, "browsers.json")));
13146
+ } catch {
13147
+ return [];
13148
+ }
13149
+ const written = [];
13150
+ for (const file3 of virtualBrowserFiles(text2)) {
13151
+ mkdirp(volume, dirname(file3.path));
13152
+ volume.writeFileSync(file3.path, file3.data);
13153
+ if (file3.mode !== void 0) {
13154
+ volume.chmodSync(file3.path, file3.mode);
13155
+ written.push(file3.path);
13156
+ }
13157
+ }
13158
+ return written;
13159
+ }
13160
+
13161
+ // src/pkg/clean-installer.ts
13162
+ var RUNTIME_PACKAGE_FALLBACKS = {
13163
+ esbuild: "esbuild-wasm",
13164
+ rollup: "@rollup/wasm-node"
13165
+ };
13166
+ var CleanPackageInstaller = class _CleanPackageInstaller {
13167
+ constructor(volume, options = {}) {
13168
+ this.volume = volume;
13169
+ this.options = options;
13170
+ this.registry = (options.registry ?? "https://registry.npmjs.org").replace(/\/$/, "");
13171
+ this.fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
13172
+ }
13173
+ volume;
13174
+ options;
13175
+ registry;
13176
+ fetcher;
13177
+ metadata = /* @__PURE__ */ new Map();
13178
+ tarballs = /* @__PURE__ */ new Map();
13179
+ /** Single-version manifests, for the fields the packument omits. */
13180
+ details = /* @__PURE__ */ new Map();
13181
+ forCwd(cwd) {
13182
+ const installer = new _CleanPackageInstaller(this.volume, { ...this.options, cwd });
13183
+ installer.metadata = this.metadata;
13184
+ installer.tarballs = this.tarballs;
13185
+ installer.details = this.details;
13186
+ return installer;
13187
+ }
13188
+ async install(name, version = "latest", options = {}) {
13189
+ const cwd = this.options.cwd ?? "/";
13190
+ const manifest = await this.installAt(name, version || "latest", join(cwd, "node_modules"), options, /* @__PURE__ */ new Set());
13191
+ if (options.persist !== false) this.persist(cwd, name, version, options.persistDev === true);
13192
+ return manifest;
13193
+ }
13194
+ async installFromManifest(path, options = {}) {
13195
+ const project = this.readJson(path);
13196
+ const cwd = dirname(path);
13197
+ const dependencies = {
13198
+ ...project.dependencies ?? {},
13199
+ ...options.withDevDeps === false ? {} : project.devDependencies ?? {}
13200
+ };
13201
+ await this.prefetch(dependencies);
13202
+ for (const [name, range] of Object.entries(dependencies)) {
13203
+ await this.installAt(name, range, join(cwd, "node_modules"), options, /* @__PURE__ */ new Set());
13204
+ }
13205
+ }
13206
+ async installAt(name, range, modulesRoot, options, ancestry) {
13207
+ const metadata = await this.getMetadata(name);
13208
+ const version = resolveVersion(metadata, range);
13209
+ const manifest = metadata.versions[version];
13210
+ if (!manifest) throw new Error(`No matching version found for ${name}@${range}`);
13211
+ const identity = `${name}@${version}`;
13212
+ if (!supportsPlatform(manifest)) throw new IncompatiblePlatform(identity, "");
13213
+ if (manifest.os?.length || manifest.cpu?.length) {
13214
+ const detail = await this.platformDetail(name, version);
13215
+ if (!platformListAllows(detail.libc, PLATFORM.libc)) {
13216
+ throw new IncompatiblePlatform(identity, ` (needs ${detail.libc?.join(", ")})`);
13217
+ }
13218
+ if (detail.main?.endsWith(".node")) {
13219
+ throw new IncompatiblePlatform(identity, " (native addon; this runtime cannot dlopen)");
13220
+ }
13221
+ }
13222
+ const target = join(modulesRoot, name);
13223
+ const installed3 = this.tryReadJson(join(target, "package.json"));
13224
+ if (ancestry.has(identity)) return manifest;
13225
+ if (installed3?.version !== version) {
13226
+ options.onProgress?.(`Fetching ${identity}`);
13227
+ const archive = await this.getTarball(manifest.dist.tarball);
13228
+ verifyIntegrity(archive, manifest.dist.integrity, manifest.dist.shasum, identity);
13229
+ this.removeIfPresent(target);
13230
+ mkdirp2(this.volume, target);
13231
+ extractNpmTarball(this.volume, archive, target);
13232
+ options.onProgress?.(`Installed ${identity}`);
13233
+ }
13234
+ this.createBinLinks(manifest, target, modulesRoot);
13235
+ if (name === "playwright-core") {
13236
+ for (const executable of installVirtualPlaywrightBrowsers(this.volume, target)) {
13237
+ options.onProgress?.(`Linked ${executable} to the virtual browser`);
13238
+ }
13239
+ }
13240
+ const nextAncestry = new Set(ancestry).add(identity);
13241
+ const fallback = RUNTIME_PACKAGE_FALLBACKS[name];
13242
+ if (fallback && fallback !== name) {
13243
+ await this.installAt(fallback, version, modulesRoot, options, nextAncestry);
13244
+ }
13245
+ const childRoot = join(target, "node_modules");
13246
+ const required = Object.fromEntries(Object.entries(manifest.dependencies ?? {}).filter(([name2]) => !(name2 in (manifest.optionalDependencies ?? {}))));
13247
+ await this.prefetch(required);
13248
+ for (const [dependency, dependencyRange] of Object.entries(required)) {
13249
+ await this.installAt(dependency, dependencyRange, childRoot, options, nextAncestry);
13250
+ }
13251
+ for (const [dependency, dependencyRange] of Object.entries(manifest.optionalDependencies ?? {})) {
13252
+ try {
13253
+ await this.installAt(dependency, dependencyRange, childRoot, options, nextAncestry);
13254
+ } catch (error) {
13255
+ if (error instanceof IncompatiblePlatform) continue;
13256
+ options.onProgress?.(`Skipped optional ${dependency}: ${error instanceof Error ? error.message : String(error)}`);
13257
+ }
13258
+ }
13259
+ return manifest;
13260
+ }
13261
+ /**
13262
+ * The `libc` and `main` fields, which the abbreviated packument leaves out.
13263
+ *
13264
+ * Fetched per version rather than as a full packument: the single-version
13265
+ * document is a few kilobytes, while the full one for a popular package runs
13266
+ * to megabytes. Only packages that already declare `os` or `cpu` ask for it,
13267
+ * so an ordinary install of pure-JavaScript dependencies makes no extra
13268
+ * requests at all — it is the prebuilt binaries, a handful per project, that
13269
+ * need the answer.
13270
+ *
13271
+ * A failure here is not fatal. Being unable to read `libc` puts the check
13272
+ * back where it was before this existed, which is worth strictly less than
13273
+ * being right and strictly more than refusing to install.
13274
+ */
13275
+ async platformDetail(name, version) {
13276
+ const key = `${name}@${version}`;
13277
+ let request = this.details.get(key);
13278
+ if (!request) {
13279
+ request = (async () => {
13280
+ try {
13281
+ const encoded = name.startsWith("@") ? name.replace("/", "%2F") : encodeURIComponent(name);
13282
+ const response = await this.fetcher(`${this.registry}/${encoded}/${version}`);
13283
+ if (!response.ok) return {};
13284
+ return await response.json();
13285
+ } catch {
13286
+ return {};
13287
+ }
13288
+ })();
13289
+ this.details.set(key, request);
13290
+ }
13291
+ return request;
13292
+ }
13293
+ /** Overlap up to six sibling downloads; filesystem writes remain ordered. */
13294
+ async prefetch(dependencies) {
13295
+ const entries = Object.entries(dependencies);
13296
+ let next = 0;
13297
+ await Promise.all(Array.from({ length: Math.min(6, entries.length) }, async () => {
13298
+ while (next < entries.length) {
13299
+ const [name, range] = entries[next++];
13300
+ try {
13301
+ const metadata = await this.getMetadata(name);
13302
+ const manifest = metadata.versions[resolveVersion(metadata, range)];
13303
+ if (!manifest.os?.length && !manifest.cpu?.length && supportsPlatform(manifest)) {
13304
+ await this.getTarball(manifest.dist.tarball);
13305
+ }
13306
+ } catch {
13307
+ }
13308
+ }
13309
+ }));
13310
+ }
13311
+ async getMetadata(name) {
13312
+ let request = this.metadata.get(name);
13313
+ if (!request) {
13314
+ request = (async () => {
13315
+ const encoded = name.startsWith("@") ? name.replace("/", "%2F") : encodeURIComponent(name);
13316
+ const response = await this.fetcher(`${this.registry}/${encoded}`, {
13317
+ headers: { Accept: "application/vnd.npm.install-v1+json" }
13318
+ });
13319
+ if (!response.ok) throw new Error(`registry returned ${response.status} for ${name}`);
13320
+ return await response.json();
13321
+ })();
13322
+ this.metadata.set(name, request);
13323
+ void request.catch(() => {
13324
+ this.metadata.delete(name);
13325
+ });
13326
+ }
13327
+ return request;
13328
+ }
13329
+ async getTarball(url) {
13330
+ let request = this.tarballs.get(url);
13331
+ if (!request) {
13332
+ request = (async () => {
13333
+ const response = await this.fetcher(url);
13334
+ if (!response.ok) throw new Error(`tarball returned ${response.status}: ${url}`);
13335
+ return new Uint8Array(await response.arrayBuffer());
13336
+ })();
13337
+ this.tarballs.set(url, request);
13338
+ void request.catch(() => {
13339
+ this.tarballs.delete(url);
13340
+ });
13341
+ }
13342
+ return request;
13343
+ }
13344
+ createBinLinks(manifest, target, modulesRoot) {
13345
+ if (!manifest.bin) return;
13346
+ const bins = typeof manifest.bin === "string" ? { [unscoped(manifest.name)]: manifest.bin } : manifest.bin;
13347
+ const binDir = join(modulesRoot, ".bin");
13348
+ mkdirp2(this.volume, binDir);
13349
+ for (const [name, path] of Object.entries(bins)) {
13350
+ const link = join(binDir, name);
13351
+ this.removeIfPresent(link);
13352
+ this.volume.symlinkSync(relative(binDir, join(target, path)), link);
13353
+ }
13354
+ }
13355
+ persist(cwd, name, range, dev) {
13356
+ const path = join(cwd, "package.json");
13357
+ const manifest = this.tryReadJson(path) ?? {};
13358
+ const key = dev ? "devDependencies" : "dependencies";
13359
+ manifest[key] = { ...manifest[key] ?? {}, [name]: range === "latest" ? "*" : range };
13360
+ this.volume.writeFileSync(path, JSON.stringify(manifest, null, 2) + "\n");
13361
+ }
13362
+ removeIfPresent(path) {
13363
+ let stat2;
13364
+ try {
13365
+ stat2 = this.volume.lstatSync(path);
13366
+ } catch {
13367
+ return;
13368
+ }
13369
+ if (!stat2.isDirectory()) return this.volume.unlinkSync(path);
13370
+ for (const name of this.volume.readdirSync(path)) this.removeIfPresent(join(path, name));
13371
+ this.volume.rmdirSync(path);
13372
+ }
13373
+ readJson(path) {
13374
+ return JSON.parse(new TextDecoder().decode(this.volume.readFileSync(path)));
13375
+ }
13376
+ tryReadJson(path) {
13377
+ try {
13378
+ return this.readJson(path);
13379
+ } catch {
13380
+ return null;
13381
+ }
13382
+ }
13383
+ };
13384
+ var PLATFORM = { os: "linux", cpu: "x64", libc: "glibc" };
13385
+ var IncompatiblePlatform = class extends Error {
13386
+ constructor(identity, detail) {
13387
+ super(`${identity} is not compatible with ${PLATFORM.os}/${PLATFORM.cpu}/${PLATFORM.libc}${detail}`);
13388
+ this.name = "IncompatiblePlatform";
13389
+ }
13390
+ };
13391
+ function supportsPlatform(manifest) {
13392
+ return platformListAllows(manifest.os, PLATFORM.os) && platformListAllows(manifest.cpu, PLATFORM.cpu) && platformListAllows(manifest.libc, PLATFORM.libc);
13393
+ }
13394
+ function platformListAllows(values, current2) {
13395
+ if (!values?.length) return true;
13396
+ if (values.includes(`!${current2}`)) return false;
13397
+ const positive = values.filter((value) => !value.startsWith("!"));
13398
+ return positive.length === 0 || positive.includes(current2) || positive.includes("any");
13399
+ }
13400
+ function resolveVersion(metadata, range) {
13401
+ const tag2 = metadata["dist-tags"]?.[range];
13402
+ if (tag2) return tag2;
13403
+ if (valid(range) && metadata.versions[range]) return range;
13404
+ const found2 = maxSatisfying(Object.keys(metadata.versions), range === "latest" ? "*" : range, { includePrerelease: false });
13405
+ if (!found2) throw new Error(`No matching version found for ${metadata.name}@${range}`);
13406
+ return found2;
13407
+ }
13408
+ function verifyIntegrity(data, integrity, shasum, identity) {
13409
+ if (integrity) {
13410
+ const choices = integrity.trim().split(/\s+/);
13411
+ for (const choice of choices) {
13412
+ const dash = choice.indexOf("-");
13413
+ const algorithm = choice.slice(0, dash);
13414
+ const expected = choice.slice(dash + 1).replace(/\?.*$/, "");
13415
+ const digest2 = algorithm === "sha512" ? sha512(data) : algorithm === "sha256" ? sha256(data) : null;
13416
+ if (digest2 && Buffer2.from(digest2).toString("base64") === expected) return;
13417
+ }
13418
+ throw new Error(`Integrity check failed for ${identity}`);
13419
+ }
13420
+ if (shasum && Buffer2.from(sha1(data)).toString("hex") === shasum) return;
13421
+ if (shasum) throw new Error(`Legacy checksum check failed for ${identity}`);
13422
+ }
13423
+ function extractNpmTarball(volume, compressed, destination) {
13424
+ const tar2 = ungzip(compressed);
13425
+ let offset = 0;
13426
+ let longPath = null;
13427
+ let paxPath = null;
13428
+ while (offset + 512 <= tar2.length) {
13429
+ const header = tar2.subarray(offset, offset + 512);
13430
+ if (header.every((byte) => byte === 0)) break;
13431
+ const size = octal(header, 124, 12);
13432
+ const type = String.fromCharCode(header[156] || 48);
13433
+ const prefix = text(header, 345, 155);
13434
+ let name = longPath ?? paxPath ?? [prefix, text(header, 0, 100)].filter(Boolean).join("/");
13435
+ longPath = null;
13436
+ paxPath = null;
13437
+ const data = tar2.subarray(offset + 512, offset + 512 + size);
13438
+ offset += 512 + Math.ceil(size / 512) * 512;
13439
+ if (type === "L") {
13440
+ longPath = new TextDecoder().decode(data).replace(/\0.*$/, "").trim();
13441
+ continue;
13442
+ }
13443
+ if (type === "x" || type === "g") {
13444
+ paxPath = parsePax(data).path ?? null;
13445
+ continue;
13446
+ }
13447
+ name = stripPackageRoot(name);
13448
+ if (!name) continue;
13449
+ const target = safeTarget(destination, name);
13450
+ const mode = octal(header, 100, 8) || 420;
13451
+ if (type === "5") {
13452
+ mkdirp2(volume, target, mode);
13453
+ } else if (type === "2") {
13454
+ mkdirp2(volume, dirname(target));
13455
+ volume.symlinkSync(text(header, 157, 100), target);
13456
+ } else if (type === "1") {
13457
+ mkdirp2(volume, dirname(target));
13458
+ volume.linkSync(safeTarget(destination, stripPackageRoot(text(header, 157, 100))), target);
13459
+ } else if (type === "0" || type === "\0" || type === "7") {
13460
+ mkdirp2(volume, dirname(target));
13461
+ volume.writeFileSync(target, data.slice());
13462
+ volume.chmodSync(target, mode);
13463
+ }
13464
+ }
13465
+ }
13466
+ function mkdirp2(volume, path, mode = 493) {
13467
+ let current2 = "";
13468
+ for (const part of segments(path)) {
13469
+ current2 += `/${part}`;
13470
+ try {
13471
+ volume.mkdirSync(current2, { mode });
13472
+ } catch (error) {
13473
+ if (error.code !== "EEXIST") throw error;
13474
+ if (!volume.lstatSync(current2).isDirectory()) throw error;
13475
+ }
13476
+ }
13477
+ }
13478
+ function safeTarget(destination, name) {
13479
+ const clean2 = clean(`/${name}`).slice(1);
13480
+ if (!clean2 || clean2 === ".." || clean2.startsWith("../") || name.startsWith("/")) throw new Error(`Unsafe path in package: ${name}`);
13481
+ return join(destination, clean2);
13482
+ }
13483
+ function stripPackageRoot(name) {
13484
+ const clean2 = name.replace(/^\.\//, "").replace(/\/$/, "");
13485
+ const slash = clean2.indexOf("/");
13486
+ return slash === -1 ? "" : clean2.slice(slash + 1);
13487
+ }
13488
+ function text(bytes3, start2, length) {
13489
+ return new TextDecoder().decode(bytes3.subarray(start2, start2 + length)).replace(/\0.*$/, "").trim();
13490
+ }
13491
+ function octal(bytes3, start2, length) {
13492
+ return parseInt(text(bytes3, start2, length).replace(/^0+/, "") || "0", 8);
13493
+ }
13494
+ function parsePax(data) {
13495
+ const value = new TextDecoder().decode(data);
13496
+ const result = {};
13497
+ let offset = 0;
13498
+ while (offset < value.length) {
13499
+ const space = value.indexOf(" ", offset);
13500
+ if (space < 0) break;
13501
+ const length = Number(value.slice(offset, space));
13502
+ if (!Number.isFinite(length) || length <= 0) break;
13503
+ const record2 = value.slice(space + 1, offset + length - 1);
13504
+ const equal2 = record2.indexOf("=");
13505
+ if (equal2 > 0) result[record2.slice(0, equal2)] = record2.slice(equal2 + 1);
13506
+ offset += length;
13507
+ }
13508
+ return result;
13509
+ }
13510
+ function unscoped(name) {
13511
+ return name.startsWith("@") ? name.slice(name.indexOf("/") + 1) : name;
13512
+ }
13513
+
13514
+ // src/bin/capabilities.ts
13515
+ function report(ctx) {
13516
+ const commands13 = ctx.kernel.commands.names();
13517
+ const has = (name) => commands13.includes(name);
13518
+ return {
13519
+ schemaVersion: 1,
13520
+ runtime: "sandboxedjs",
13521
+ platform: { os: "linux", arch: "x64", libc: "glibc" },
13522
+ filesystem: { writable: true, root: "/", persistence: "container-lifetime", hostAccess: false },
13523
+ shell: { posix: true, pipelines: true, redirection: true, backgroundProcesses: true },
13524
+ languages: { node: has("node"), python: has("python3"), wasmWasi: has("wasi") },
13525
+ packages: {
13526
+ npm: has("npm"),
13527
+ pip: has("pip"),
13528
+ applicationRegistry: has("pm"),
13529
+ nativeAddons: false,
13530
+ fallbacks: RUNTIME_PACKAGE_FALLBACKS
13531
+ },
13532
+ network: {
13533
+ virtualServers: true,
13534
+ loopback: true,
13535
+ outbound: ctx.kernel.net.policy.allowOutbound,
13536
+ allowedHosts: ctx.kernel.net.policy.allowedHosts,
13537
+ proxy: ctx.kernel.net.proxy !== null,
13538
+ listeningPorts: ctx.kernel.net.listening().map(({ port, proto, program }) => ({ port, proto, program }))
13539
+ },
13540
+ interfaces: {
13541
+ desktopGui: false,
13542
+ hostFilesystem: false,
13543
+ systemPackageManager: false,
13544
+ docker: false
13545
+ },
13546
+ commands: commands13
13547
+ };
13548
+ }
13549
+ var sandboxedjsCapabilities = defineCommand({
13550
+ name: "sandboxedjs-capabilities",
13551
+ aliases: ["sbx-capabilities"],
13552
+ path: "/usr/bin/sandboxedjs-capabilities",
13553
+ summary: "report the runtime capabilities available to tools and agents",
13554
+ usage: "sandboxedjs-capabilities [--json]",
13555
+ run(ctx) {
13556
+ const result = report(ctx);
13557
+ if (ctx.args.includes("--json")) {
13558
+ ctx.line(JSON.stringify(result, null, 2));
13559
+ return 0;
13560
+ }
13561
+ ctx.line("SandboxedJS runtime capabilities");
13562
+ ctx.line(` commands: ${result.commands.length}`);
13563
+ ctx.line(` languages: ${Object.entries(result.languages).filter(([, enabled]) => enabled).map(([name]) => name).join(", ")}`);
13564
+ ctx.line(` outbound network: ${result.network.outbound ? "enabled" : "disabled"}`);
13565
+ ctx.line(` writable filesystem: ${result.filesystem.root} (${result.filesystem.persistence})`);
13566
+ ctx.line(` package fallbacks: ${Object.entries(result.packages.fallbacks).map(([from, to]) => `${from} -> ${to}`).join(", ") || "none"}`);
13567
+ ctx.line("Run with --json for the complete machine-readable inventory.");
13568
+ return 0;
13569
+ }
13570
+ });
13571
+ var commands4 = [sandboxedjsCapabilities];
12950
13572
 
12951
13573
  // src/bin/sed.ts
12952
13574
  var SedParseError = class extends Error {
@@ -15389,8 +16011,8 @@ async function runAwk(ctx) {
15389
16011
  continue;
15390
16012
  }
15391
16013
  try {
15392
- const bytes2 = ctx.vfs.readFile(ctx.path(operand), ctx.cred);
15393
- inputs.push({ name: operand, lines: splitLines(bytes2).lines });
16014
+ const bytes3 = ctx.vfs.readFile(ctx.path(operand), ctx.cred);
16015
+ inputs.push({ name: operand, lines: splitLines(bytes3).lines });
15394
16016
  } catch (e) {
15395
16017
  ctx.reportError(e, operand);
15396
16018
  return 2;
@@ -15533,12 +16155,12 @@ async function followFiles(ctx, paths, intervalMs) {
15533
16155
  if (ctx.signal.aborted) break;
15534
16156
  for (const path of paths) {
15535
16157
  try {
15536
- const bytes2 = ctx.vfs.readFile(ctx.path(path), ctx.cred);
16158
+ const bytes3 = ctx.vfs.readFile(ctx.path(path), ctx.cred);
15537
16159
  const previous = offsets.get(path) ?? 0;
15538
- if (bytes2.length > previous) {
15539
- ctx.write(bytes2.subarray(previous));
15540
- offsets.set(path, bytes2.length);
15541
- } else if (bytes2.length < previous) {
16160
+ if (bytes3.length > previous) {
16161
+ ctx.write(bytes3.subarray(previous));
16162
+ offsets.set(path, bytes3.length);
16163
+ } else if (bytes3.length < previous) {
15542
16164
  offsets.set(path, 0);
15543
16165
  }
15544
16166
  } catch {
@@ -15921,14 +16543,14 @@ var tee = defineCommand({
15921
16543
  { short: "a", long: "append" },
15922
16544
  { short: "i", long: "ignore-interrupts" }
15923
16545
  ]);
15924
- const bytes2 = await ctx.stdin.readAll();
15925
- ctx.write(bytes2);
16546
+ const bytes3 = await ctx.stdin.readAll();
16547
+ ctx.write(bytes3);
15926
16548
  let status = 0;
15927
16549
  for (const target of args.positional) {
15928
16550
  try {
15929
16551
  const abs = ctx.path(target);
15930
- if (args.has("append")) ctx.vfs.appendFile(abs, bytes2, { cred: ctx.cred });
15931
- else ctx.vfs.writeFile(abs, bytes2, { cred: ctx.cred });
16552
+ if (args.has("append")) ctx.vfs.appendFile(abs, bytes3, { cred: ctx.cred });
16553
+ else ctx.vfs.writeFile(abs, bytes3, { cred: ctx.cred });
15932
16554
  } catch (e) {
15933
16555
  status = ctx.reportError(e, target);
15934
16556
  }
@@ -16241,16 +16863,16 @@ var split = defineCommand({
16241
16863
  const [input, prefixRaw] = args.positional;
16242
16864
  const prefix = prefixRaw ?? "x";
16243
16865
  const { sources, ok: ok2 } = await readInputs(ctx, input ? [input] : []);
16244
- const bytes2 = sources[0]?.bytes ?? new Uint8Array(0);
16866
+ const bytes3 = sources[0]?.bytes ?? new Uint8Array(0);
16245
16867
  const suffixLength = args.num("suffix-length", 2);
16246
16868
  const chunks = [];
16247
16869
  const byteSpec = args.str("bytes");
16248
16870
  if (byteSpec !== void 0) {
16249
16871
  const size = parseSize(byteSpec) ?? 1024;
16250
- for (let i = 0; i < bytes2.length; i += size) chunks.push(bytes2.subarray(i, i + size));
16872
+ for (let i = 0; i < bytes3.length; i += size) chunks.push(bytes3.subarray(i, i + size));
16251
16873
  } else {
16252
16874
  const perChunk = args.num("lines", 1e3);
16253
- const { lines } = splitLines(bytes2);
16875
+ const { lines } = splitLines(bytes3);
16254
16876
  for (let i = 0; i < lines.length; i += perChunk) {
16255
16877
  chunks.push(new TextEncoder().encode(joinLines(lines.slice(i, i + perChunk), true)));
16256
16878
  }
@@ -16314,7 +16936,7 @@ var awk = defineCommand({
16314
16936
  usage: "awk [-F fs] [-v var=value] 'program' [FILE]...",
16315
16937
  run: runAwk
16316
16938
  });
16317
- var commands4 = [
16939
+ var commands5 = [
16318
16940
  head,
16319
16941
  tail,
16320
16942
  wc,
@@ -16460,19 +17082,19 @@ var grep = defineCommand({
16460
17082
  let anyMatch = false;
16461
17083
  let status = 1;
16462
17084
  for (const target of targets) {
16463
- let bytes2;
17085
+ let bytes3;
16464
17086
  if (target === "-") {
16465
- bytes2 = await ctx.stdin.readAll();
17087
+ bytes3 = await ctx.stdin.readAll();
16466
17088
  } else {
16467
17089
  try {
16468
- bytes2 = ctx.vfs.readFile(ctx.path(target), ctx.cred);
17090
+ bytes3 = ctx.vfs.readFile(ctx.path(target), ctx.cred);
16469
17091
  } catch (e) {
16470
17092
  if (!args.has("no-messages")) ctx.reportError(e, target);
16471
17093
  status = 2;
16472
17094
  continue;
16473
17095
  }
16474
17096
  }
16475
- const { lines } = splitLines(bytes2);
17097
+ const { lines } = splitLines(bytes3);
16476
17098
  const matched = [];
16477
17099
  let count = 0;
16478
17100
  for (let i = 0; i < lines.length && count < maxCount; i++) {
@@ -17045,7 +17667,7 @@ var cmp = defineCommand({
17045
17667
  return 0;
17046
17668
  }
17047
17669
  });
17048
- var commands5 = [grep, find, xargs, diff, cmp];
17670
+ var commands6 = [grep, find, xargs, diff, cmp];
17049
17671
 
17050
17672
  // src/bin/archive.ts
17051
17673
  init_mode();
@@ -17055,8 +17677,8 @@ var BLOCK = 512;
17055
17677
  var encoder5 = new TextEncoder();
17056
17678
  var decoder7 = new TextDecoder();
17057
17679
  function writeString(block, offset, value, length) {
17058
- const bytes2 = encoder5.encode(value);
17059
- for (let i = 0; i < length; i++) block[offset + i] = i < bytes2.length ? bytes2[i] : 0;
17680
+ const bytes3 = encoder5.encode(value);
17681
+ for (let i = 0; i < length; i++) block[offset + i] = i < bytes3.length ? bytes3[i] : 0;
17060
17682
  }
17061
17683
  function writeOctal(block, offset, value, length) {
17062
17684
  const text2 = value.toString(8).padStart(length - 1, "0");
@@ -17207,23 +17829,23 @@ var tar = defineCommand({
17207
17829
  if (args.has("verbose")) ctx.line(name);
17208
17830
  };
17209
17831
  for (const operand of args.positional) add(resolve(baseDir, operand), operand);
17210
- let bytes3 = createTar(entries2);
17211
- if (compressed) bytes3 = await gzip(bytes3);
17212
- if (archive === void 0 || archive === "-") ctx.write(bytes3);
17213
- else ctx.vfs.writeFile(ctx.path(archive), bytes3, { cred: ctx.cred, mode: 420 });
17832
+ let bytes4 = createTar(entries2);
17833
+ if (compressed) bytes4 = await gzip(bytes4);
17834
+ if (archive === void 0 || archive === "-") ctx.write(bytes4);
17835
+ else ctx.vfs.writeFile(ctx.path(archive), bytes4, { cred: ctx.cred, mode: 420 });
17214
17836
  return 0;
17215
17837
  }
17216
- let bytes2;
17217
- if (archive === void 0 || archive === "-") bytes2 = await ctx.stdin.readAll();
17838
+ let bytes3;
17839
+ if (archive === void 0 || archive === "-") bytes3 = await ctx.stdin.readAll();
17218
17840
  else {
17219
17841
  try {
17220
- bytes2 = ctx.vfs.readFile(ctx.path(archive), ctx.cred);
17842
+ bytes3 = ctx.vfs.readFile(ctx.path(archive), ctx.cred);
17221
17843
  } catch (e) {
17222
17844
  return ctx.reportError(e, archive);
17223
17845
  }
17224
17846
  }
17225
- if (bytes2[0] === 31 && bytes2[1] === 139) bytes2 = await gunzip(bytes2);
17226
- const entries = readTar(bytes2);
17847
+ if (bytes3[0] === 31 && bytes3[1] === 139) bytes3 = await gunzip(bytes3);
17848
+ const entries = readTar(bytes3);
17227
17849
  const strip = args.num("strip-components", 0);
17228
17850
  if (args.has("list")) {
17229
17851
  for (const entry of entries) {
@@ -17360,7 +17982,7 @@ var zlibCompress = defineCommand({
17360
17982
  });
17361
17983
  }
17362
17984
  });
17363
- var commands6 = [tar, gzip2, gunzip2, zcat, zlibCompress];
17985
+ var commands7 = [tar, gzip2, gunzip2, zcat, zlibCompress];
17364
17986
 
17365
17987
  // src/bin/hash.ts
17366
17988
  init_binary();
@@ -17402,8 +18024,8 @@ async function checkSums(ctx, algorithm, files, quiet) {
17402
18024
  checked++;
17403
18025
  const [, expected, name] = m;
17404
18026
  try {
17405
- const bytes2 = ctx.vfs.readFile(ctx.path(name), ctx.cred);
17406
- const actual = await digestHex(algorithm, bytes2);
18027
+ const bytes3 = ctx.vfs.readFile(ctx.path(name), ctx.cred);
18028
+ const actual = await digestHex(algorithm, bytes3);
17407
18029
  if (actual === expected.toLowerCase()) {
17408
18030
  if (!quiet) ctx.line(`${name}: OK`);
17409
18031
  } else {
@@ -17568,7 +18190,7 @@ var mktemp = defineCommand({
17568
18190
  return 0;
17569
18191
  }
17570
18192
  });
17571
- var commands7 = [
18193
+ var commands8 = [
17572
18194
  md5sum,
17573
18195
  sha1sum,
17574
18196
  sha224sum,
@@ -18044,7 +18666,7 @@ var host = defineCommand({
18044
18666
  return 0;
18045
18667
  }
18046
18668
  });
18047
- var commands8 = [curl, wget, ping, ip, ifconfig, ss, netstat, nc, host];
18669
+ var commands9 = [curl, wget, ping, ip, ifconfig, ss, netstat, nc, host];
18048
18670
 
18049
18671
  // src/bin/admin.ts
18050
18672
  init_mode();
@@ -18481,7 +19103,7 @@ sys ${fmt2(Math.floor(ms * 0.2))}
18481
19103
  return code;
18482
19104
  }
18483
19105
  });
18484
- var commands9 = [
19106
+ var commands10 = [
18485
19107
  suCmd,
18486
19108
  sudo,
18487
19109
  useradd,
@@ -18657,7 +19279,7 @@ var helpCmd = defineCommand({
18657
19279
  return 0;
18658
19280
  }
18659
19281
  });
18660
- var commands10 = [man, whatis, apropos, less, helpCmd];
19282
+ var commands11 = [man, whatis, apropos, less, helpCmd];
18661
19283
 
18662
19284
  // src/bin/clipboard.ts
18663
19285
  init_path();
@@ -18672,12 +19294,12 @@ function readSelection(ctx, selection) {
18672
19294
  return new Uint8Array();
18673
19295
  }
18674
19296
  }
18675
- function writeSelection(ctx, selection, bytes2) {
19297
+ function writeSelection(ctx, selection, bytes3) {
18676
19298
  try {
18677
19299
  ctx.vfs.mkdir(CLIPBOARD_DIR, { recursive: true, mode: 511 });
18678
19300
  } catch {
18679
19301
  }
18680
- ctx.vfs.writeFile(selectionPath(selection), bytes2, { privileged: true, mode: 438 });
19302
+ ctx.vfs.writeFile(selectionPath(selection), bytes3, { privileged: true, mode: 438 });
18681
19303
  }
18682
19304
  var xsel = defineCommand({
18683
19305
  name: "xsel",
@@ -18779,8 +19401,8 @@ var wlCopy = defineCommand({
18779
19401
  async run(ctx) {
18780
19402
  const selection = ctx.args.includes("--primary") || ctx.args.includes("-p") ? "primary" : "clipboard";
18781
19403
  const operands = ctx.args.filter((arg) => !arg.startsWith("-"));
18782
- const bytes2 = operands.length ? new TextEncoder().encode(operands.join(" ")) : await ctx.stdin.readAll();
18783
- writeSelection(ctx, selection, bytes2);
19404
+ const bytes3 = operands.length ? new TextEncoder().encode(operands.join(" ")) : await ctx.stdin.readAll();
19405
+ writeSelection(ctx, selection, bytes3);
18784
19406
  return 0;
18785
19407
  }
18786
19408
  });
@@ -18790,13 +19412,13 @@ var wlPaste = defineCommand({
18790
19412
  usage: "wl-paste [--primary] [-n]",
18791
19413
  run(ctx) {
18792
19414
  const selection = ctx.args.includes("--primary") || ctx.args.includes("-p") ? "primary" : "clipboard";
18793
- const bytes2 = readSelection(ctx, selection);
18794
- ctx.write(bytes2);
19415
+ const bytes3 = readSelection(ctx, selection);
19416
+ ctx.write(bytes3);
18795
19417
  if (!ctx.args.includes("-n") && !ctx.args.includes("--no-newline")) ctx.write("\n");
18796
19418
  return 0;
18797
19419
  }
18798
19420
  });
18799
- var commands11 = [xsel, xclip, pbcopy, pbpaste, wlCopy, wlPaste];
19421
+ var commands12 = [xsel, xclip, pbcopy, pbpaste, wlCopy, wlPaste];
18800
19422
 
18801
19423
  // src/node/node.ts
18802
19424
  init_path();
@@ -19387,10 +20009,10 @@ async function execute(ctx, invocation) {
19387
20009
  }
19388
20010
  async function captureStdin(ctx) {
19389
20011
  if (ctx.stdin.isTTY || ctx.stdin.interactive) return null;
19390
- const bytes2 = await ctx.stdin.readAll();
19391
- if (bytes2.length === 0) return null;
20012
+ const bytes3 = await ctx.stdin.readAll();
20013
+ if (bytes3.length === 0) return null;
19392
20014
  const path = tempPath("stdin", ctx.proc.pid, ".dat");
19393
- ctx.vfs.writeFile(path, bytes2, { privileged: true, mode: 384 });
20015
+ ctx.vfs.writeFile(path, bytes3, { privileged: true, mode: 384 });
19394
20016
  return path;
19395
20017
  }
19396
20018
  var node = defineCommand({
@@ -21092,7 +21714,7 @@ var wheels_default = {
21092
21714
 
21093
21715
  // package.json
21094
21716
  var package_default = {
21095
- version: "0.2.22"};
21717
+ version: "0.2.23"};
21096
21718
 
21097
21719
  // src/python/extension-abi.ts
21098
21720
  var EXTENSION_ABI = {
@@ -21943,9 +22565,9 @@ var Reader = class {
21943
22565
  at = 0;
21944
22566
  view;
21945
22567
  bytes;
21946
- constructor(bytes2) {
21947
- this.bytes = bytes2;
21948
- this.view = new DataView(bytes2.buffer, bytes2.byteOffset, bytes2.byteLength);
22568
+ constructor(bytes3) {
22569
+ this.bytes = bytes3;
22570
+ this.view = new DataView(bytes3.buffer, bytes3.byteOffset, bytes3.byteLength);
21949
22571
  }
21950
22572
  need(count) {
21951
22573
  if (this.at + count > this.bytes.length) throw new ProtocolError("payload underrun");
@@ -22031,9 +22653,9 @@ var ByteQueue = class {
22031
22653
  chunks = [];
22032
22654
  length = 0;
22033
22655
  waiters = /* @__PURE__ */ new Set();
22034
- push(bytes2) {
22035
- if (bytes2.length === 0) return;
22036
- const copy = bytes2.slice();
22656
+ push(bytes3) {
22657
+ if (bytes3.length === 0) return;
22658
+ const copy = bytes3.slice();
22037
22659
  this.chunks.push(copy);
22038
22660
  this.length += copy.length;
22039
22661
  this.wake();
@@ -22093,10 +22715,10 @@ var VirtualTcpConnection = class {
22093
22715
  if (this.eof) return new Uint8Array();
22094
22716
  throw new PosixError(Errno.EAGAIN, "socket read would block");
22095
22717
  }
22096
- write(bytes2) {
22718
+ write(bytes3) {
22097
22719
  if (!this.writable) throw new PosixError(this.closed || this.writeClosed ? Errno.EPIPE : Errno.ECONNRESET);
22098
- this.peer.incoming.push(bytes2);
22099
- return bytes2.length;
22720
+ this.peer.incoming.push(bytes3);
22721
+ return bytes3.length;
22100
22722
  }
22101
22723
  async waitForChange() {
22102
22724
  if (this.readable || this.closed) return;
@@ -22379,9 +23001,9 @@ var SO_ERROR = 4;
22379
23001
  var SO_TYPE = 3;
22380
23002
  var SOCK_STREAM = 1;
22381
23003
  function int32(value) {
22382
- const bytes2 = new Uint8Array(4);
22383
- new DataView(bytes2.buffer).setInt32(0, value, true);
22384
- return bytes2;
23004
+ const bytes3 = new Uint8Array(4);
23005
+ new DataView(bytes3.buffer).setInt32(0, value, true);
23006
+ return bytes3;
22385
23007
  }
22386
23008
  function isLoopback(address) {
22387
23009
  if (address === "" || address === "localhost" || address === "0.0.0.0") return true;
@@ -22772,9 +23394,9 @@ function createHostAbiServer(proc) {
22772
23394
  /* ---------------------------------------------------------- entropy */
22773
23395
  case Op.getrandom: {
22774
23396
  const length = Math.min(r.u32(), 65536);
22775
- const bytes2 = new Uint8Array(length);
22776
- crypto.getRandomValues(bytes2);
22777
- return { status: length, payload: bytes2 };
23397
+ const bytes3 = new Uint8Array(length);
23398
+ crypto.getRandomValues(bytes3);
23399
+ return { status: length, payload: bytes3 };
22778
23400
  }
22779
23401
  /* ----------------------------------------------------------- sockets */
22780
23402
  case Op.socket: {
@@ -23260,9 +23882,9 @@ var FIRST_EGRESS_PORT = 48e3;
23260
23882
  var MAX_HEADER_BYTES = 64 * 1024;
23261
23883
  var MAX_BODY_BYTES = 32 * 1024 * 1024;
23262
23884
  var CRLF = "\r\n";
23263
- function indexOfDoubleCrlf(bytes2) {
23264
- for (let i = 3; i < bytes2.length; i++) {
23265
- if (bytes2[i] === 10 && bytes2[i - 1] === 13 && bytes2[i - 2] === 10 && bytes2[i - 3] === 13) return i + 1;
23885
+ function indexOfDoubleCrlf(bytes3) {
23886
+ for (let i = 3; i < bytes3.length; i++) {
23887
+ if (bytes3[i] === 10 && bytes3[i - 1] === 13 && bytes3[i - 2] === 10 && bytes3[i - 3] === 13) return i + 1;
23266
23888
  }
23267
23889
  return -1;
23268
23890
  }
@@ -23527,62 +24149,6 @@ function splitOnce(text2, separator) {
23527
24149
  return at < 0 ? [text2] : [text2.slice(0, at), text2.slice(at + 1)];
23528
24150
  }
23529
24151
 
23530
- // src/browser/playwright-browsers.ts
23531
- init_path();
23532
- var PLAYWRIGHT_REGISTRY = "/root/.cache/ms-playwright";
23533
- var LAYOUTS = {
23534
- "chromium": ["chrome-linux64", "chrome"],
23535
- "chromium-headless-shell": ["chrome-headless-shell-linux64", "chrome-headless-shell"]
23536
- };
23537
- function virtualBrowserFiles(browsersJson) {
23538
- let manifest;
23539
- try {
23540
- manifest = JSON.parse(browsersJson);
23541
- } catch {
23542
- return [];
23543
- }
23544
- const encoder9 = new TextEncoder();
23545
- const files = [];
23546
- for (const browser of manifest.browsers ?? []) {
23547
- const layout = LAYOUTS[browser.name];
23548
- if (!layout) continue;
23549
- const dir3 = join(PLAYWRIGHT_REGISTRY, `${browser.name.replace(/-/g, "_")}-${browser.revision}`);
23550
- files.push({ path: join(dir3, ...layout), data: encoder9.encode(`#!${BUILTIN_INTERPRETER} chrome
23551
- `), mode: 493 });
23552
- files.push({ path: join(dir3, "INSTALLATION_COMPLETE"), data: new Uint8Array() });
23553
- }
23554
- return files;
23555
- }
23556
- function mkdirp(volume, path) {
23557
- let current2 = "";
23558
- for (const part of segments(path)) {
23559
- current2 += `/${part}`;
23560
- try {
23561
- volume.mkdirSync(current2, { mode: 493 });
23562
- } catch (error) {
23563
- if (error.code !== "EEXIST") throw error;
23564
- }
23565
- }
23566
- }
23567
- function installVirtualPlaywrightBrowsers(volume, packageDir) {
23568
- let text2;
23569
- try {
23570
- text2 = new TextDecoder().decode(volume.readFileSync(join(packageDir, "browsers.json")));
23571
- } catch {
23572
- return [];
23573
- }
23574
- const written = [];
23575
- for (const file3 of virtualBrowserFiles(text2)) {
23576
- mkdirp(volume, dirname(file3.path));
23577
- volume.writeFileSync(file3.path, file3.data);
23578
- if (file3.mode !== void 0) {
23579
- volume.chmodSync(file3.path, file3.mode);
23580
- written.push(file3.path);
23581
- }
23582
- }
23583
- return written;
23584
- }
23585
-
23586
24152
  // src/python/substitutions.ts
23587
24153
  var SUBSTITUTED_WHEELS = {
23588
24154
  playwright: /-py3-none-manylinux1_x86_64\.whl$/
@@ -24149,27 +24715,27 @@ async function installRequirements(options) {
24149
24715
  continue;
24150
24716
  }
24151
24717
  options.progress.downloading(distribution.name, distribution.version);
24152
- const bytes2 = await download(options.client, distribution);
24153
- const files = stageWheel(readZip(bytes2));
24718
+ const bytes3 = await download(options.client, distribution);
24719
+ const files = stageWheel(readZip(bytes3));
24154
24720
  staged.push(...distribution.kind === "substituted" ? substituteFiles(distribution.name, files, SITE_PACKAGES) : files);
24155
24721
  installed3.push({ name: distribution.name, version: distribution.version });
24156
24722
  }
24157
24723
  commit(options.vfs, options.cred, staged);
24158
24724
  return { installed: installed3, skipped: solved.skipped };
24159
24725
  }
24160
- function requireArchive(distribution, bytes2) {
24161
- if (bytes2.length > 1 && bytes2[0] === 80 && bytes2[1] === 75) return;
24162
- const opening = new TextDecoder().decode(bytes2.subarray(0, 80)).replace(/\s+/g, " ").trim();
24726
+ function requireArchive(distribution, bytes3) {
24727
+ if (bytes3.length > 1 && bytes3[0] === 80 && bytes3[1] === 75) return;
24728
+ const opening = new TextDecoder().decode(bytes3.subarray(0, 80)).replace(/\s+/g, " ").trim();
24163
24729
  const looksLikeMarkup = /^<!doctype|^<html/i.test(opening);
24164
24730
  throw new Error(
24165
- `${distribution.filename} did not arrive as a wheel from ${distribution.url}: ` + (looksLikeMarkup ? "the server answered with an HTML page, which usually means the wheel is not published at that address and the server returned its index page instead" : `expected a zip archive, got ${bytes2.length} bytes beginning ${JSON.stringify(opening)}`)
24731
+ `${distribution.filename} did not arrive as a wheel from ${distribution.url}: ` + (looksLikeMarkup ? "the server answered with an HTML page, which usually means the wheel is not published at that address and the server returned its index page instead" : `expected a zip archive, got ${bytes3.length} bytes beginning ${JSON.stringify(opening)}`)
24166
24732
  );
24167
24733
  }
24168
24734
  async function download(client, distribution) {
24169
- const bytes2 = await client.bytes(distribution.url, { timeoutMs: 12e4 });
24170
- requireArchive(distribution, bytes2);
24171
- const mismatch = digestMismatch(distribution, bytes2);
24172
- if (!mismatch) return bytes2;
24735
+ const bytes3 = await client.bytes(distribution.url, { timeoutMs: 12e4 });
24736
+ requireArchive(distribution, bytes3);
24737
+ const mismatch = digestMismatch(distribution, bytes3);
24738
+ if (!mismatch) return bytes3;
24173
24739
  const fresh = await refetch(client, distribution);
24174
24740
  if (fresh && !digestMismatch(distribution, fresh)) {
24175
24741
  requireArchive(distribution, fresh);
@@ -24182,22 +24748,22 @@ async function download(client, distribution) {
24182
24748
  async function refetch(client, distribution) {
24183
24749
  const separator = distribution.url.includes("?") ? "&" : "?";
24184
24750
  try {
24185
- const bytes2 = await client.bytes(
24751
+ const bytes3 = await client.bytes(
24186
24752
  `${distribution.url}${separator}sha256=${distribution.sha256}`,
24187
24753
  { timeoutMs: 6e4 }
24188
24754
  );
24189
- return bytes2.length > 1 && bytes2[0] === 80 && bytes2[1] === 75 ? bytes2 : null;
24755
+ return bytes3.length > 1 && bytes3[0] === 80 && bytes3[1] === 75 ? bytes3 : null;
24190
24756
  } catch {
24191
24757
  return null;
24192
24758
  }
24193
24759
  }
24194
- function digestMismatch(distribution, bytes2) {
24760
+ function digestMismatch(distribution, bytes3) {
24195
24761
  if (!distribution.sha256) {
24196
24762
  throw new Error(
24197
24763
  `${distribution.filename} was published without a sha256 digest, so it cannot be verified`
24198
24764
  );
24199
24765
  }
24200
- const actual = [...sha256(bytes2)].map((b) => b.toString(16).padStart(2, "0")).join("");
24766
+ const actual = [...sha256(bytes3)].map((b) => b.toString(16).padStart(2, "0")).join("");
24201
24767
  if (actual === distribution.sha256) return null;
24202
24768
  return `${distribution.filename} failed verification: the index published sha256 ${distribution.sha256} but the download hashes to ${actual}.`;
24203
24769
  }
@@ -24327,9 +24893,9 @@ function outputFor(description, fallback) {
24327
24893
  return {
24328
24894
  write(data) {
24329
24895
  if (broken) return;
24330
- const bytes2 = typeof data === "string" ? new TextEncoder().encode(data) : data;
24331
- if (bytes2.length === 0) return;
24332
- queue.push(bytes2.slice());
24896
+ const bytes3 = typeof data === "string" ? new TextEncoder().encode(data) : data;
24897
+ if (bytes3.length === 0) return;
24898
+ queue.push(bytes3.slice());
24333
24899
  if (!active) done = pump();
24334
24900
  },
24335
24901
  end() {
@@ -25694,9 +26260,9 @@ environments. A package with no usable wheel is an error, never a silent skip.`,
25694
26260
  )];
25695
26261
  if (embedded) {
25696
26262
  const binary = atob(embedded);
25697
- const bytes2 = new Uint8Array(binary.length);
25698
- for (let i = 0; i < binary.length; i += 1) bytes2[i] = binary.charCodeAt(i);
25699
- return await read(new Response(bytes2));
26263
+ const bytes3 = new Uint8Array(binary.length);
26264
+ for (let i = 0; i < binary.length; i += 1) bytes3[i] = binary.charCodeAt(i);
26265
+ return await read(new Response(bytes3));
25700
26266
  }
25701
26267
  if (url.startsWith("sbx-wheel:")) {
25702
26268
  const filename = decodeURIComponent(url.slice("sbx-wheel:".length).replace(/^\/+/, ""));
@@ -25765,7 +26331,7 @@ environments. A package with no usable wheel is an error, never a silent skip.`,
25765
26331
  let attemptsLeft = 12;
25766
26332
  for (; ; ) {
25767
26333
  try {
25768
- const report = await installRequirements({
26334
+ const report2 = await installRequirements({
25769
26335
  index,
25770
26336
  client,
25771
26337
  vfs: ctx.vfs,
@@ -25786,11 +26352,11 @@ environments. A package with no usable wheel is an error, never a silent skip.`,
25786
26352
  }
25787
26353
  }
25788
26354
  });
25789
- for (const skipped of report.skipped) {
26355
+ for (const skipped of report2.skipped) {
25790
26356
  ctx.line(` Skipping ${skipped.name} (marker: ${skipped.marker})`);
25791
26357
  }
25792
26358
  ctx.line(
25793
- `Successfully installed ${report.installed.map((p) => `${p.name}-${p.version}`).join(" ")}`
26359
+ `Successfully installed ${report2.installed.map((p) => `${p.name}-${p.version}`).join(" ")}`
25794
26360
  );
25795
26361
  return 0;
25796
26362
  } catch (error) {
@@ -26176,11 +26742,11 @@ async function loadFactory() {
26176
26742
  function getCompiled() {
26177
26743
  compiled2 ??= (async () => {
26178
26744
  const { factory, wasm } = await loadFactory();
26179
- const bytes2 = wasm.buffer.slice(
26745
+ const bytes3 = wasm.buffer.slice(
26180
26746
  wasm.byteOffset,
26181
26747
  wasm.byteOffset + wasm.byteLength
26182
26748
  );
26183
- return { factory, module: await WebAssembly.compile(bytes2) };
26749
+ return { factory, module: await WebAssembly.compile(bytes3) };
26184
26750
  })();
26185
26751
  void compiled2.catch(() => compiled2 = null);
26186
26752
  return compiled2;
@@ -26328,18 +26894,18 @@ than a packet path, and socket calls report ENOTSUP.`,
26328
26894
  }
26329
26895
  if (module === void 0) return ctx.reportError(new UsageError("a module is required"));
26330
26896
  const abs = ctx.path(module);
26331
- let bytes2;
26897
+ let bytes3;
26332
26898
  try {
26333
- bytes2 = ctx.vfs.readFile(abs, ctx.cred);
26899
+ bytes3 = ctx.vfs.readFile(abs, ctx.cred);
26334
26900
  } catch (error) {
26335
26901
  ctx.reportError(error, abs);
26336
26902
  return EXIT_NOT_FOUND;
26337
26903
  }
26338
- if (!isWasmBinary(bytes2)) {
26904
+ if (!isWasmBinary(bytes3)) {
26339
26905
  return ctx.fail(`${abs}: not a WebAssembly module`, 126);
26340
26906
  }
26341
26907
  Object.assign(ctx.env, env2);
26342
- return await runWasi(ctx, bytes2, {
26908
+ return await runWasi(ctx, bytes3, {
26343
26909
  /* argv[0] is the path as the user wrote it, not the resolved one: a
26344
26910
  * program printing its own usage should echo what was typed. */
26345
26911
  argv: [module, ...rest],
@@ -26350,398 +26916,6 @@ than a packet path, and socket calls report ENOTSUP.`,
26350
26916
  function wasiCommands() {
26351
26917
  return [wasi];
26352
26918
  }
26353
- var platformBuffer = globalThis.Buffer;
26354
- addUint8ArraySupport(addBase64UrlSupport(Buffer$1));
26355
- var Buffer2 = platformBuffer ?? Buffer$1;
26356
- function addUint8ArraySupport(BufferClass) {
26357
- const target = BufferClass;
26358
- if (target.__sandboxedUint8Array) return BufferClass;
26359
- Object.defineProperty(target, "__sandboxedUint8Array", { value: true });
26360
- const asBuffer = (value) => value instanceof Uint8Array && !target.isBuffer(value) ? target.from(value.buffer, value.byteOffset, value.byteLength) : value;
26361
- for (const method of ["indexOf", "lastIndexOf", "includes"]) {
26362
- const original = target.prototype[method];
26363
- target.prototype[method] = function(value, ...rest) {
26364
- return original.call(this, asBuffer(value), ...rest);
26365
- };
26366
- }
26367
- const equals = target.prototype.equals;
26368
- target.prototype.equals = function(other) {
26369
- return equals.call(this, asBuffer(other));
26370
- };
26371
- return BufferClass;
26372
- }
26373
- function addBase64UrlSupport(BufferClass) {
26374
- const target = BufferClass;
26375
- if (target.__sandboxedBase64Url) return BufferClass;
26376
- Object.defineProperty(target, "__sandboxedBase64Url", { value: true });
26377
- const from = target.from.bind(target);
26378
- target.from = (value, encodingOrOffset, length) => from(value, normalizeEncoding(encodingOrOffset), length);
26379
- const byteLength = target.byteLength.bind(target);
26380
- target.byteLength = (value, encoding) => byteLength(value, normalizeEncoding(encoding));
26381
- const isEncoding = target.isEncoding?.bind(target);
26382
- if (isEncoding) target.isEncoding = (encoding) => encoding.toLowerCase() === "base64url" || isEncoding(encoding);
26383
- const toString = target.prototype.toString;
26384
- target.prototype.toString = function(encoding, start2, end) {
26385
- if (encoding?.toLowerCase() !== "base64url") return toString.call(this, encoding, start2, end);
26386
- return toString.call(this, "base64", start2, end).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
26387
- };
26388
- const write = target.prototype.write;
26389
- target.prototype.write = function(...args) {
26390
- const index = typeof args[1] === "string" ? 1 : typeof args[2] === "string" ? 2 : 3;
26391
- if (typeof args[index] === "string") args[index] = normalizeEncoding(args[index]);
26392
- return write.apply(this, args);
26393
- };
26394
- return BufferClass;
26395
- }
26396
- function normalizeEncoding(value) {
26397
- return typeof value === "string" && value.toLowerCase() === "base64url" ? "base64" : value;
26398
- }
26399
-
26400
- // src/pkg/clean-installer.ts
26401
- init_path();
26402
- var CleanPackageInstaller = class _CleanPackageInstaller {
26403
- constructor(volume, options = {}) {
26404
- this.volume = volume;
26405
- this.options = options;
26406
- this.registry = (options.registry ?? "https://registry.npmjs.org").replace(/\/$/, "");
26407
- this.fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
26408
- }
26409
- volume;
26410
- options;
26411
- registry;
26412
- fetcher;
26413
- metadata = /* @__PURE__ */ new Map();
26414
- tarballs = /* @__PURE__ */ new Map();
26415
- /** Single-version manifests, for the fields the packument omits. */
26416
- details = /* @__PURE__ */ new Map();
26417
- forCwd(cwd) {
26418
- const installer = new _CleanPackageInstaller(this.volume, { ...this.options, cwd });
26419
- installer.metadata = this.metadata;
26420
- installer.tarballs = this.tarballs;
26421
- installer.details = this.details;
26422
- return installer;
26423
- }
26424
- async install(name, version = "latest", options = {}) {
26425
- const cwd = this.options.cwd ?? "/";
26426
- const manifest = await this.installAt(name, version || "latest", join(cwd, "node_modules"), options, /* @__PURE__ */ new Set());
26427
- if (options.persist !== false) this.persist(cwd, name, version, options.persistDev === true);
26428
- return manifest;
26429
- }
26430
- async installFromManifest(path, options = {}) {
26431
- const project = this.readJson(path);
26432
- const cwd = dirname(path);
26433
- const dependencies = {
26434
- ...project.dependencies ?? {},
26435
- ...options.withDevDeps === false ? {} : project.devDependencies ?? {}
26436
- };
26437
- await this.prefetch(dependencies);
26438
- for (const [name, range] of Object.entries(dependencies)) {
26439
- await this.installAt(name, range, join(cwd, "node_modules"), options, /* @__PURE__ */ new Set());
26440
- }
26441
- }
26442
- async installAt(name, range, modulesRoot, options, ancestry) {
26443
- const metadata = await this.getMetadata(name);
26444
- const version = resolveVersion(metadata, range);
26445
- const manifest = metadata.versions[version];
26446
- if (!manifest) throw new Error(`No matching version found for ${name}@${range}`);
26447
- const identity = `${name}@${version}`;
26448
- if (!supportsPlatform(manifest)) throw new IncompatiblePlatform(identity, "");
26449
- if (manifest.os?.length || manifest.cpu?.length) {
26450
- const detail = await this.platformDetail(name, version);
26451
- if (!platformListAllows(detail.libc, PLATFORM.libc)) {
26452
- throw new IncompatiblePlatform(identity, ` (needs ${detail.libc?.join(", ")})`);
26453
- }
26454
- if (detail.main?.endsWith(".node")) {
26455
- throw new IncompatiblePlatform(identity, " (native addon; this runtime cannot dlopen)");
26456
- }
26457
- }
26458
- const target = join(modulesRoot, name);
26459
- const installed3 = this.tryReadJson(join(target, "package.json"));
26460
- if (ancestry.has(identity)) return manifest;
26461
- if (installed3?.version !== version) {
26462
- options.onProgress?.(`Fetching ${identity}`);
26463
- const archive = await this.getTarball(manifest.dist.tarball);
26464
- verifyIntegrity(archive, manifest.dist.integrity, manifest.dist.shasum, identity);
26465
- this.removeIfPresent(target);
26466
- mkdirp2(this.volume, target);
26467
- extractNpmTarball(this.volume, archive, target);
26468
- options.onProgress?.(`Installed ${identity}`);
26469
- }
26470
- this.createBinLinks(manifest, target, modulesRoot);
26471
- if (name === "playwright-core") {
26472
- for (const executable of installVirtualPlaywrightBrowsers(this.volume, target)) {
26473
- options.onProgress?.(`Linked ${executable} to the virtual browser`);
26474
- }
26475
- }
26476
- const nextAncestry = new Set(ancestry).add(identity);
26477
- const childRoot = join(target, "node_modules");
26478
- const required = Object.fromEntries(Object.entries(manifest.dependencies ?? {}).filter(([name2]) => !(name2 in (manifest.optionalDependencies ?? {}))));
26479
- await this.prefetch(required);
26480
- for (const [dependency, dependencyRange] of Object.entries(required)) {
26481
- await this.installAt(dependency, dependencyRange, childRoot, options, nextAncestry);
26482
- }
26483
- for (const [dependency, dependencyRange] of Object.entries(manifest.optionalDependencies ?? {})) {
26484
- try {
26485
- await this.installAt(dependency, dependencyRange, childRoot, options, nextAncestry);
26486
- } catch (error) {
26487
- if (error instanceof IncompatiblePlatform) continue;
26488
- options.onProgress?.(`Skipped optional ${dependency}: ${error instanceof Error ? error.message : String(error)}`);
26489
- }
26490
- }
26491
- return manifest;
26492
- }
26493
- /**
26494
- * The `libc` and `main` fields, which the abbreviated packument leaves out.
26495
- *
26496
- * Fetched per version rather than as a full packument: the single-version
26497
- * document is a few kilobytes, while the full one for a popular package runs
26498
- * to megabytes. Only packages that already declare `os` or `cpu` ask for it,
26499
- * so an ordinary install of pure-JavaScript dependencies makes no extra
26500
- * requests at all — it is the prebuilt binaries, a handful per project, that
26501
- * need the answer.
26502
- *
26503
- * A failure here is not fatal. Being unable to read `libc` puts the check
26504
- * back where it was before this existed, which is worth strictly less than
26505
- * being right and strictly more than refusing to install.
26506
- */
26507
- async platformDetail(name, version) {
26508
- const key = `${name}@${version}`;
26509
- let request = this.details.get(key);
26510
- if (!request) {
26511
- request = (async () => {
26512
- try {
26513
- const encoded = name.startsWith("@") ? name.replace("/", "%2F") : encodeURIComponent(name);
26514
- const response = await this.fetcher(`${this.registry}/${encoded}/${version}`);
26515
- if (!response.ok) return {};
26516
- return await response.json();
26517
- } catch {
26518
- return {};
26519
- }
26520
- })();
26521
- this.details.set(key, request);
26522
- }
26523
- return request;
26524
- }
26525
- /** Overlap up to six sibling downloads; filesystem writes remain ordered. */
26526
- async prefetch(dependencies) {
26527
- const entries = Object.entries(dependencies);
26528
- let next = 0;
26529
- await Promise.all(Array.from({ length: Math.min(6, entries.length) }, async () => {
26530
- while (next < entries.length) {
26531
- const [name, range] = entries[next++];
26532
- try {
26533
- const metadata = await this.getMetadata(name);
26534
- const manifest = metadata.versions[resolveVersion(metadata, range)];
26535
- if (!manifest.os?.length && !manifest.cpu?.length && supportsPlatform(manifest)) {
26536
- await this.getTarball(manifest.dist.tarball);
26537
- }
26538
- } catch {
26539
- }
26540
- }
26541
- }));
26542
- }
26543
- async getMetadata(name) {
26544
- let request = this.metadata.get(name);
26545
- if (!request) {
26546
- request = (async () => {
26547
- const encoded = name.startsWith("@") ? name.replace("/", "%2F") : encodeURIComponent(name);
26548
- const response = await this.fetcher(`${this.registry}/${encoded}`, {
26549
- headers: { Accept: "application/vnd.npm.install-v1+json" }
26550
- });
26551
- if (!response.ok) throw new Error(`registry returned ${response.status} for ${name}`);
26552
- return await response.json();
26553
- })();
26554
- this.metadata.set(name, request);
26555
- void request.catch(() => {
26556
- this.metadata.delete(name);
26557
- });
26558
- }
26559
- return request;
26560
- }
26561
- async getTarball(url) {
26562
- let request = this.tarballs.get(url);
26563
- if (!request) {
26564
- request = (async () => {
26565
- const response = await this.fetcher(url);
26566
- if (!response.ok) throw new Error(`tarball returned ${response.status}: ${url}`);
26567
- return new Uint8Array(await response.arrayBuffer());
26568
- })();
26569
- this.tarballs.set(url, request);
26570
- void request.catch(() => {
26571
- this.tarballs.delete(url);
26572
- });
26573
- }
26574
- return request;
26575
- }
26576
- createBinLinks(manifest, target, modulesRoot) {
26577
- if (!manifest.bin) return;
26578
- const bins = typeof manifest.bin === "string" ? { [unscoped(manifest.name)]: manifest.bin } : manifest.bin;
26579
- const binDir = join(modulesRoot, ".bin");
26580
- mkdirp2(this.volume, binDir);
26581
- for (const [name, path] of Object.entries(bins)) {
26582
- const link = join(binDir, name);
26583
- this.removeIfPresent(link);
26584
- this.volume.symlinkSync(relative(binDir, join(target, path)), link);
26585
- }
26586
- }
26587
- persist(cwd, name, range, dev) {
26588
- const path = join(cwd, "package.json");
26589
- const manifest = this.tryReadJson(path) ?? {};
26590
- const key = dev ? "devDependencies" : "dependencies";
26591
- manifest[key] = { ...manifest[key] ?? {}, [name]: range === "latest" ? "*" : range };
26592
- this.volume.writeFileSync(path, JSON.stringify(manifest, null, 2) + "\n");
26593
- }
26594
- removeIfPresent(path) {
26595
- let stat2;
26596
- try {
26597
- stat2 = this.volume.lstatSync(path);
26598
- } catch {
26599
- return;
26600
- }
26601
- if (!stat2.isDirectory()) return this.volume.unlinkSync(path);
26602
- for (const name of this.volume.readdirSync(path)) this.removeIfPresent(join(path, name));
26603
- this.volume.rmdirSync(path);
26604
- }
26605
- readJson(path) {
26606
- return JSON.parse(new TextDecoder().decode(this.volume.readFileSync(path)));
26607
- }
26608
- tryReadJson(path) {
26609
- try {
26610
- return this.readJson(path);
26611
- } catch {
26612
- return null;
26613
- }
26614
- }
26615
- };
26616
- var PLATFORM = { os: "linux", cpu: "x64", libc: "glibc" };
26617
- var IncompatiblePlatform = class extends Error {
26618
- constructor(identity, detail) {
26619
- super(`${identity} is not compatible with ${PLATFORM.os}/${PLATFORM.cpu}/${PLATFORM.libc}${detail}`);
26620
- this.name = "IncompatiblePlatform";
26621
- }
26622
- };
26623
- function supportsPlatform(manifest) {
26624
- return platformListAllows(manifest.os, PLATFORM.os) && platformListAllows(manifest.cpu, PLATFORM.cpu) && platformListAllows(manifest.libc, PLATFORM.libc);
26625
- }
26626
- function platformListAllows(values, current2) {
26627
- if (!values?.length) return true;
26628
- if (values.includes(`!${current2}`)) return false;
26629
- const positive = values.filter((value) => !value.startsWith("!"));
26630
- return positive.length === 0 || positive.includes(current2) || positive.includes("any");
26631
- }
26632
- function resolveVersion(metadata, range) {
26633
- const tag2 = metadata["dist-tags"]?.[range];
26634
- if (tag2) return tag2;
26635
- if (valid(range) && metadata.versions[range]) return range;
26636
- const found2 = maxSatisfying(Object.keys(metadata.versions), range === "latest" ? "*" : range, { includePrerelease: false });
26637
- if (!found2) throw new Error(`No matching version found for ${metadata.name}@${range}`);
26638
- return found2;
26639
- }
26640
- function verifyIntegrity(data, integrity, shasum, identity) {
26641
- if (integrity) {
26642
- const choices = integrity.trim().split(/\s+/);
26643
- for (const choice of choices) {
26644
- const dash = choice.indexOf("-");
26645
- const algorithm = choice.slice(0, dash);
26646
- const expected = choice.slice(dash + 1).replace(/\?.*$/, "");
26647
- const digest2 = algorithm === "sha512" ? sha512(data) : algorithm === "sha256" ? sha256(data) : null;
26648
- if (digest2 && Buffer2.from(digest2).toString("base64") === expected) return;
26649
- }
26650
- throw new Error(`Integrity check failed for ${identity}`);
26651
- }
26652
- if (shasum && Buffer2.from(sha1(data)).toString("hex") === shasum) return;
26653
- if (shasum) throw new Error(`Legacy checksum check failed for ${identity}`);
26654
- }
26655
- function extractNpmTarball(volume, compressed, destination) {
26656
- const tar2 = ungzip(compressed);
26657
- let offset = 0;
26658
- let longPath = null;
26659
- let paxPath = null;
26660
- while (offset + 512 <= tar2.length) {
26661
- const header = tar2.subarray(offset, offset + 512);
26662
- if (header.every((byte) => byte === 0)) break;
26663
- const size = octal(header, 124, 12);
26664
- const type = String.fromCharCode(header[156] || 48);
26665
- const prefix = text(header, 345, 155);
26666
- let name = longPath ?? paxPath ?? [prefix, text(header, 0, 100)].filter(Boolean).join("/");
26667
- longPath = null;
26668
- paxPath = null;
26669
- const data = tar2.subarray(offset + 512, offset + 512 + size);
26670
- offset += 512 + Math.ceil(size / 512) * 512;
26671
- if (type === "L") {
26672
- longPath = new TextDecoder().decode(data).replace(/\0.*$/, "").trim();
26673
- continue;
26674
- }
26675
- if (type === "x" || type === "g") {
26676
- paxPath = parsePax(data).path ?? null;
26677
- continue;
26678
- }
26679
- name = stripPackageRoot(name);
26680
- if (!name) continue;
26681
- const target = safeTarget(destination, name);
26682
- const mode = octal(header, 100, 8) || 420;
26683
- if (type === "5") {
26684
- mkdirp2(volume, target, mode);
26685
- } else if (type === "2") {
26686
- mkdirp2(volume, dirname(target));
26687
- volume.symlinkSync(text(header, 157, 100), target);
26688
- } else if (type === "1") {
26689
- mkdirp2(volume, dirname(target));
26690
- volume.linkSync(safeTarget(destination, stripPackageRoot(text(header, 157, 100))), target);
26691
- } else if (type === "0" || type === "\0" || type === "7") {
26692
- mkdirp2(volume, dirname(target));
26693
- volume.writeFileSync(target, data.slice());
26694
- volume.chmodSync(target, mode);
26695
- }
26696
- }
26697
- }
26698
- function mkdirp2(volume, path, mode = 493) {
26699
- let current2 = "";
26700
- for (const part of segments(path)) {
26701
- current2 += `/${part}`;
26702
- try {
26703
- volume.mkdirSync(current2, { mode });
26704
- } catch (error) {
26705
- if (error.code !== "EEXIST") throw error;
26706
- if (!volume.lstatSync(current2).isDirectory()) throw error;
26707
- }
26708
- }
26709
- }
26710
- function safeTarget(destination, name) {
26711
- const clean2 = clean(`/${name}`).slice(1);
26712
- if (!clean2 || clean2 === ".." || clean2.startsWith("../") || name.startsWith("/")) throw new Error(`Unsafe path in package: ${name}`);
26713
- return join(destination, clean2);
26714
- }
26715
- function stripPackageRoot(name) {
26716
- const clean2 = name.replace(/^\.\//, "").replace(/\/$/, "");
26717
- const slash = clean2.indexOf("/");
26718
- return slash === -1 ? "" : clean2.slice(slash + 1);
26719
- }
26720
- function text(bytes2, start2, length) {
26721
- return new TextDecoder().decode(bytes2.subarray(start2, start2 + length)).replace(/\0.*$/, "").trim();
26722
- }
26723
- function octal(bytes2, start2, length) {
26724
- return parseInt(text(bytes2, start2, length).replace(/^0+/, "") || "0", 8);
26725
- }
26726
- function parsePax(data) {
26727
- const value = new TextDecoder().decode(data);
26728
- const result = {};
26729
- let offset = 0;
26730
- while (offset < value.length) {
26731
- const space = value.indexOf(" ", offset);
26732
- if (space < 0) break;
26733
- const length = Number(value.slice(offset, space));
26734
- if (!Number.isFinite(length) || length <= 0) break;
26735
- const record2 = value.slice(space + 1, offset + length - 1);
26736
- const equal2 = record2.indexOf("=");
26737
- if (equal2 > 0) result[record2.slice(0, equal2)] = record2.slice(equal2 + 1);
26738
- offset += length;
26739
- }
26740
- return result;
26741
- }
26742
- function unscoped(name) {
26743
- return name.startsWith("@") ? name.slice(name.indexOf("/") + 1) : name;
26744
- }
26745
26919
  var DECLARES_EXPORTS = /(?:^|[\s;{)])(?:var|let|const|function|class)\s+exports\b/;
26746
26920
  var NAME = "exports";
26747
26921
  function renameShadowedExports(source) {
@@ -28454,8 +28628,8 @@ var VireoEngine = class _VireoEngine {
28454
28628
  const app = installedVireo(ctx);
28455
28629
  if (!app?.browserEngine) return null;
28456
28630
  const manifest = app.browserEngine;
28457
- const bytes2 = ctx.vfs.readFile(`${app.root}/${manifest.wasm}`, ctx.cred);
28458
- const loaded = await WebAssembly.instantiate(bytes2, {});
28631
+ const bytes3 = ctx.vfs.readFile(`${app.root}/${manifest.wasm}`, ctx.cred);
28632
+ const loaded = await WebAssembly.instantiate(bytes3, {});
28459
28633
  const instance = loaded instanceof WebAssembly.Instance ? loaded : loaded.instance;
28460
28634
  const wasm = instance.exports;
28461
28635
  for (const name of ["memory", "vireo_alloc", "vireo_load_html", "vireo_snapshot_pointer", "vireo_snapshot_length", "vireo_free_document"]) {
@@ -28479,11 +28653,11 @@ var VireoEngine = class _VireoEngine {
28479
28653
  this.wasm.vireo_free_document(handle);
28480
28654
  }
28481
28655
  }
28482
- copy(bytes2) {
28483
- if (!bytes2.length) return 0;
28484
- const pointer = this.wasm.vireo_alloc(bytes2.length);
28656
+ copy(bytes3) {
28657
+ if (!bytes3.length) return 0;
28658
+ const pointer = this.wasm.vireo_alloc(bytes3.length);
28485
28659
  if (!pointer) throw new Error("Vireo ran out of memory");
28486
- new Uint8Array(this.wasm.memory.buffer, pointer, bytes2.length).set(bytes2);
28660
+ new Uint8Array(this.wasm.memory.buffer, pointer, bytes3.length).set(bytes3);
28487
28661
  return pointer;
28488
28662
  }
28489
28663
  };
@@ -28669,8 +28843,8 @@ var SIGNATURE_PATH = "META/signature.json";
28669
28843
  var TRUSTED_KEYS_PATH = "/etc/pm/trusted-keys.json";
28670
28844
  var PackageError = class extends Error {
28671
28845
  };
28672
- async function openPackage(bytes2, trusted) {
28673
- const entries = readZip(bytes2);
28846
+ async function openPackage(bytes3, trusted) {
28847
+ const entries = readZip(bytes3);
28674
28848
  const byName = new Map(entries.map((entry) => [entry.name, entry]));
28675
28849
  const manifestEntry = byName.get(MANIFEST_PATH);
28676
28850
  if (!manifestEntry) {
@@ -28713,10 +28887,10 @@ async function openPackage(bytes2, trusted) {
28713
28887
  const trustedBy = trusted.find((key) => key.publicKey === signature.publicKey) ?? null;
28714
28888
  return { manifest, signature, entries, trustedBy };
28715
28889
  }
28716
- function parseManifest(bytes2) {
28890
+ function parseManifest(bytes3) {
28717
28891
  let parsed;
28718
28892
  try {
28719
- parsed = JSON.parse(new TextDecoder().decode(bytes2));
28893
+ parsed = JSON.parse(new TextDecoder().decode(bytes3));
28720
28894
  } catch (error) {
28721
28895
  throw new PackageError(`${MANIFEST_PATH} is not JSON: ${error.message}`);
28722
28896
  }
@@ -28732,10 +28906,10 @@ function parseManifest(bytes2) {
28732
28906
  }
28733
28907
  return manifest;
28734
28908
  }
28735
- function parseSignature(bytes2) {
28909
+ function parseSignature(bytes3) {
28736
28910
  let parsed;
28737
28911
  try {
28738
- parsed = JSON.parse(new TextDecoder().decode(bytes2));
28912
+ parsed = JSON.parse(new TextDecoder().decode(bytes3));
28739
28913
  } catch (error) {
28740
28914
  throw new PackageError(`${SIGNATURE_PATH} is not JSON: ${error.message}`);
28741
28915
  }
@@ -28783,16 +28957,16 @@ async function verifySignature(manifestBytes, signature) {
28783
28957
  intoBuffer(manifestBytes)
28784
28958
  );
28785
28959
  }
28786
- function intoBuffer(bytes2) {
28787
- return bytes2.slice().buffer;
28960
+ function intoBuffer(bytes3) {
28961
+ return bytes3.slice().buffer;
28788
28962
  }
28789
28963
  function base64ToBytes(text2) {
28790
28964
  const binary = atob(text2);
28791
- const bytes2 = new Uint8Array(binary.length);
28965
+ const bytes3 = new Uint8Array(binary.length);
28792
28966
  for (let index = 0; index < binary.length; index += 1) {
28793
- bytes2[index] = binary.charCodeAt(index);
28967
+ bytes3[index] = binary.charCodeAt(index);
28794
28968
  }
28795
- return bytes2;
28969
+ return bytes3;
28796
28970
  }
28797
28971
  async function fingerprint(publicKey) {
28798
28972
  const digest2 = await digestHex("sha256", base64ToBytes(publicKey));
@@ -29165,8 +29339,8 @@ function listInstalled2(ctx) {
29165
29339
  return 0;
29166
29340
  }
29167
29341
  for (const app of apps.slice().sort((a, b) => a.name.localeCompare(b.name))) {
29168
- const commands12 = app.installedBins.length > 0 ? ` (${app.installedBins.join(", ")})` : "";
29169
- ctx.line(`${app.name} ${app.version}${commands12}`);
29342
+ const commands13 = app.installedBins.length > 0 ? ` (${app.installedBins.join(", ")})` : "";
29343
+ ctx.line(`${app.name} ${app.version}${commands13}`);
29170
29344
  }
29171
29345
  return 0;
29172
29346
  }
@@ -29275,6 +29449,7 @@ function allCommands() {
29275
29449
  ...commands9,
29276
29450
  ...commands10,
29277
29451
  ...commands11,
29452
+ ...commands12,
29278
29453
  ...nodeCommands(),
29279
29454
  ...pythonCommands(),
29280
29455
  ...ffmpegCommands(),
@@ -29319,8 +29494,8 @@ var ContainerFs = class {
29319
29494
  return this.kernel.vfs;
29320
29495
  }
29321
29496
  async readFile(path, encoding) {
29322
- const bytes2 = this.vfs.readFile(clean(path));
29323
- return encoding ? new TextDecoder().decode(bytes2) : bytes2;
29497
+ const bytes3 = this.vfs.readFile(clean(path));
29498
+ return encoding ? new TextDecoder().decode(bytes3) : bytes3;
29324
29499
  }
29325
29500
  async writeFile(path, data, opts = {}) {
29326
29501
  const abs = clean(path);
@@ -29646,9 +29821,9 @@ var KernelChildProcess = class {
29646
29821
  this.exitCode = code;
29647
29822
  this.emit("exit", code);
29648
29823
  }
29649
- append(stream, text2) {
29824
+ append(stream, value, text2 = typeof value === "string" ? value : new TextDecoder().decode(value)) {
29650
29825
  this[stream] += text2;
29651
- this.emit(stream, text2);
29826
+ this.emit(stream, value);
29652
29827
  }
29653
29828
  };
29654
29829
  var ChildOutput = class {
@@ -29667,7 +29842,7 @@ var ChildOutput = class {
29667
29842
  write(data) {
29668
29843
  if (this.closedState) return;
29669
29844
  const text2 = typeof data === "string" ? data : this.decoder.decode(data, { stream: true });
29670
- if (text2) this.child.append(this.stream, text2);
29845
+ if (text2 || data instanceof Uint8Array) this.child.append(this.stream, data, text2);
29671
29846
  }
29672
29847
  end() {
29673
29848
  if (this.closedState) return;
@@ -31725,13 +31900,13 @@ var Z_NO_FLUSH = 0;
31725
31900
  var Z_SYNC_FLUSH = 2;
31726
31901
  var Z_FULL_FLUSH = 3;
31727
31902
  var Z_FINISH = 4;
31728
- var bytes = (data) => {
31903
+ var bytes2 = (data) => {
31729
31904
  if (typeof data === "string") return new Uint8Array(Buffer2.from(data, "utf8"));
31730
31905
  if (data instanceof ArrayBuffer) return new Uint8Array(data);
31731
31906
  return data;
31732
31907
  };
31733
31908
  function codec(run3) {
31734
- const sync2 = (data, options) => Buffer2.from(run3(bytes(data), options));
31909
+ const sync2 = (data, options) => Buffer2.from(run3(bytes2(data), options));
31735
31910
  const async_ = (data, options, callback) => {
31736
31911
  const done = typeof options === "function" ? options : callback;
31737
31912
  const settings = typeof options === "function" ? void 0 : options;
@@ -32081,6 +32256,8 @@ var VirtualServerResponse = class extends streamModule5.Writable {
32081
32256
  completed;
32082
32257
  constructor(request) {
32083
32258
  super();
32259
+ this.on("error", () => {
32260
+ });
32084
32261
  this.req = request;
32085
32262
  this.completed = new Promise((resolve3) => {
32086
32263
  this.resolve = resolve3;
@@ -32210,9 +32387,9 @@ var VirtualSocket = class extends streamModule5.Duplex {
32210
32387
  _read() {
32211
32388
  }
32212
32389
  _write(chunk, encoding, callback) {
32213
- const bytes2 = Buffer2.isBuffer(chunk) ? chunk : Buffer2.from(chunk, encoding);
32390
+ const bytes3 = Buffer2.isBuffer(chunk) ? chunk : Buffer2.from(chunk, encoding);
32214
32391
  try {
32215
- this.peer?.data(new Uint8Array(bytes2));
32392
+ this.peer?.data(new Uint8Array(bytes3));
32216
32393
  callback();
32217
32394
  } catch (error) {
32218
32395
  callback(error);
@@ -32236,9 +32413,9 @@ var VirtualSocket = class extends streamModule5.Duplex {
32236
32413
  this.peer = null;
32237
32414
  }
32238
32415
  /** Bytes arriving from the far end. */
32239
- deliver(bytes2) {
32416
+ deliver(bytes3) {
32240
32417
  if (this.destroyed || this.hungUp) return;
32241
- this.push(Buffer2.from(bytes2));
32418
+ this.push(Buffer2.from(bytes3));
32242
32419
  }
32243
32420
  /** The far end went away; let the server's stream end cleanly. */
32244
32421
  peerClosed() {
@@ -32393,7 +32570,7 @@ var VirtualHttpRouter = class {
32393
32570
  request.socket = socket;
32394
32571
  item.server.emit("upgrade", request, socket, Buffer2.alloc(0));
32395
32572
  return {
32396
- send: (bytes2) => socket.deliver(bytes2),
32573
+ send: (bytes3) => socket.deliver(bytes3),
32397
32574
  close: () => socket.peerClosed()
32398
32575
  };
32399
32576
  }
@@ -32619,9 +32796,9 @@ var VirtualClientRequest = class extends streamModule5.Writable {
32619
32796
  }
32620
32797
  const result = remote ?? await this.router.request(this.target.port, init);
32621
32798
  const body_ = result.body;
32622
- const bytes2 = typeof body_ === "string" ? new TextEncoder().encode(body_) : body_ instanceof ArrayBuffer ? new Uint8Array(body_) : body_ ?? new Uint8Array();
32799
+ const bytes3 = typeof body_ === "string" ? new TextEncoder().encode(body_) : body_ instanceof ArrayBuffer ? new Uint8Array(body_) : body_ ?? new Uint8Array();
32623
32800
  const status = result.statusCode ?? 200;
32624
- return new VirtualClientResponse(status, result.statusMessage ?? STATUS_CODES[status] ?? "", lowercaseHeaders(result.headers), bytes2);
32801
+ return new VirtualClientResponse(status, result.statusMessage ?? STATUS_CODES[status] ?? "", lowercaseHeaders(result.headers), bytes3);
32625
32802
  }
32626
32803
  async viaFetch(body) {
32627
32804
  const fetchImpl = this.fetchImpl ?? globalThis.fetch;
@@ -32645,8 +32822,8 @@ var VirtualClientRequest = class extends streamModule5.Writable {
32645
32822
  response.headers.forEach((value, key) => {
32646
32823
  received[key.toLowerCase()] = value;
32647
32824
  });
32648
- const bytes2 = new Uint8Array(await response.arrayBuffer());
32649
- return new VirtualClientResponse(response.status, response.statusText, received, bytes2);
32825
+ const bytes3 = new Uint8Array(await response.arrayBuffer());
32826
+ return new VirtualClientResponse(response.status, response.statusText, received, bytes3);
32650
32827
  }
32651
32828
  };
32652
32829
  function lowercaseHeaders(headers) {
@@ -32738,9 +32915,9 @@ function createVirtualFetch(router, options = {}) {
32738
32915
  for (const part of Array.isArray(value) ? value : [value]) responseHeaders.append(name, String(part));
32739
32916
  }
32740
32917
  const raw = result.body;
32741
- const bytes2 = typeof raw === "string" ? new TextEncoder().encode(raw) : raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw ?? new Uint8Array();
32918
+ const bytes3 = typeof raw === "string" ? new TextEncoder().encode(raw) : raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw ?? new Uint8Array();
32742
32919
  const nullBody = status === 204 || status === 205 || status === 304 || request.method === "HEAD";
32743
- return new Response(nullBody ? null : new Uint8Array(bytes2), {
32920
+ return new Response(nullBody ? null : new Uint8Array(bytes3), {
32744
32921
  status,
32745
32922
  statusText: result.statusMessage ?? STATUS_CODES[status] ?? "",
32746
32923
  headers: responseHeaders
@@ -32986,7 +33163,7 @@ function createTestModule(host2) {
32986
33163
  });
32987
33164
  };
32988
33165
  const hasOnly = (node2) => Boolean(node2.options.only) || node2.kind === "suite" && node2.children.some(hasOnly);
32989
- const report = (depth, outcome, name, started, detail) => {
33166
+ const report2 = (depth, outcome, name, started, detail) => {
32990
33167
  if (tap()) {
32991
33168
  tapIndex += 1;
32992
33169
  const ok2 = outcome === "fail" ? "not ok" : "ok";
@@ -33033,13 +33210,13 @@ ${indent(detail, 4)}
33033
33210
  if (runOnly && !options.only) return true;
33034
33211
  if (options.skip) {
33035
33212
  record2("skip", display);
33036
- report(depth, "skip", name, started);
33213
+ report2(depth, "skip", name, started);
33037
33214
  return true;
33038
33215
  }
33039
33216
  if (!fn) {
33040
33217
  const outcome = options.todo ? "todo" : "skip";
33041
33218
  record2(outcome, display);
33042
- report(depth, outcome, name, started);
33219
+ report2(depth, outcome, name, started);
33043
33220
  return true;
33044
33221
  }
33045
33222
  const controller = new AbortController();
@@ -33103,21 +33280,21 @@ ${indent(detail, 4)}
33103
33280
  }
33104
33281
  if (skipped) {
33105
33282
  record2("skip", display);
33106
- report(depth, "skip", name, started);
33283
+ report2(depth, "skip", name, started);
33107
33284
  return true;
33108
33285
  }
33109
33286
  if (error !== void 0) {
33110
33287
  if (todo) {
33111
33288
  record2("todo", display);
33112
- report(depth, "todo", name, started);
33289
+ report2(depth, "todo", name, started);
33113
33290
  return true;
33114
33291
  }
33115
33292
  record2("fail", display, error);
33116
- report(depth, "fail", name, started, errorText(error));
33293
+ report2(depth, "fail", name, started, errorText(error));
33117
33294
  return false;
33118
33295
  }
33119
33296
  record2(todo ? "todo" : "pass", display);
33120
- report(depth, todo ? "todo" : "pass", name, started);
33297
+ report2(depth, todo ? "todo" : "pass", name, started);
33121
33298
  return true;
33122
33299
  };
33123
33300
  const runSuite = async (suite, depth, runOnly) => {
@@ -33132,7 +33309,7 @@ ${indent(detail, 4)}
33132
33309
  `);
33133
33310
  if (suite.options.skip) {
33134
33311
  for (const child of suite.children) if (child.kind === "test") record2("skip", fullName(child));
33135
- report(depth, "skip", suite.name, started);
33312
+ report2(depth, "skip", suite.name, started);
33136
33313
  return true;
33137
33314
  }
33138
33315
  }
@@ -33144,10 +33321,10 @@ ${indent(detail, 4)}
33144
33321
  for (const child of suite.children) {
33145
33322
  if (child.kind === "test") {
33146
33323
  record2("cancelled", fullName(child), error);
33147
- report(depth + (isRoot ? 0 : 1), "cancelled", child.name, started, errorText(error));
33324
+ report2(depth + (isRoot ? 0 : 1), "cancelled", child.name, started, errorText(error));
33148
33325
  }
33149
33326
  }
33150
- if (!isRoot) report(depth, "fail", suite.name, started);
33327
+ if (!isRoot) report2(depth, "fail", suite.name, started);
33151
33328
  return false;
33152
33329
  }
33153
33330
  const only = runOnly || settings().only === true && suite.children.some(hasOnly);
@@ -33527,7 +33704,7 @@ var ChildProcess = class extends EventEmitter4 {
33527
33704
  this.stdin = new streamModule5.Writable({
33528
33705
  write: (chunk, _encoding, done) => {
33529
33706
  try {
33530
- handle.sendStdin(typeof chunk === "string" ? chunk : Buffer2.from(chunk).toString("utf8"));
33707
+ handle.sendStdin(typeof chunk === "string" ? chunk : new Uint8Array(chunk));
33531
33708
  } catch {
33532
33709
  }
33533
33710
  done();
@@ -33546,8 +33723,8 @@ var ChildProcess = class extends EventEmitter4 {
33546
33723
  const pipe = this.stdio[event.fd];
33547
33724
  pipe?.push(Buffer2.from(event.text));
33548
33725
  });
33549
- handle.on("stdout", (text2) => this.stdout.write(text2));
33550
- handle.on("stderr", (text2) => this.stderr.write(text2));
33726
+ handle.on("stdout", (value) => this.stdout.write(typeof value === "string" ? value : Buffer2.from(value)));
33727
+ handle.on("stderr", (value) => this.stderr.write(typeof value === "string" ? value : Buffer2.from(value)));
33551
33728
  handle.on("exit", (code) => this.finish(code));
33552
33729
  referenceChanged(1);
33553
33730
  try {
@@ -34534,7 +34711,7 @@ function createCoreModules(options) {
34534
34711
  });
34535
34712
  processObject.stdin = stdin;
34536
34713
  Reflect.deleteProperty(processObject, "browser");
34537
- const fs = createFsModule(volume, () => cwd, options.stdinPath, defer);
34714
+ const fs = createFsModule(volume, () => cwd, options.stdinPath, defer, stdin);
34538
34715
  processObject.loadEnvFile = (path2 = ".env") => {
34539
34716
  const parsed = parseEnv(fs.readFileSync(path2, "utf8"));
34540
34717
  for (const [key, value] of Object.entries(parsed)) {
@@ -34906,7 +35083,7 @@ function createPathModule(cwd) {
34906
35083
  path.default = path;
34907
35084
  return path;
34908
35085
  }
34909
- function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
35086
+ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask, stdin) {
34910
35087
  const fds = /* @__PURE__ */ new Map();
34911
35088
  let nextFd = 3;
34912
35089
  if (stdinPath) fds.set(0, { path: stdinPath, position: 0, flags: "r" });
@@ -34917,7 +35094,7 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
34917
35094
  if (typeof value !== "string") throw new TypeError("path must be a string, Buffer, or URL");
34918
35095
  return value.startsWith("/") ? clean(value) : resolve(cwd(), value);
34919
35096
  };
34920
- const bytes2 = (data, encoding) => {
35097
+ const bytes3 = (data, encoding) => {
34921
35098
  if (typeof data === "string") return new Uint8Array(Buffer2.from(data, encoding));
34922
35099
  if (Buffer2.isBuffer(data) || data instanceof Uint8Array) return new Uint8Array(data);
34923
35100
  if (data instanceof ArrayBuffer) return new Uint8Array(data);
@@ -34979,12 +35156,12 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
34979
35156
  readFileSync: (path, options) => read(path, typeof options === "object" && options ? options.encoding : options),
34980
35157
  writeFileSync: (path, data, options) => {
34981
35158
  const encoding = typeof options === "object" && options ? options.encoding : options === "buffer" ? void 0 : options ?? void 0;
34982
- volume.writeFileSync(abs(path), bytes2(data, encoding ?? void 0));
35159
+ volume.writeFileSync(abs(path), bytes3(data, encoding ?? void 0));
34983
35160
  if (typeof options === "object" && options?.mode !== void 0) volume.chmodSync(abs(path), options.mode);
34984
35161
  },
34985
35162
  appendFileSync: (path, data, options) => {
34986
35163
  const encoding = typeof options === "object" && options ? options.encoding : options === "buffer" ? void 0 : options ?? void 0;
34987
- volume.appendFileSync(abs(path), bytes2(data, encoding ?? void 0));
35164
+ volume.appendFileSync(abs(path), bytes3(data, encoding ?? void 0));
34988
35165
  },
34989
35166
  existsSync: (path) => {
34990
35167
  try {
@@ -35075,7 +35252,7 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
35075
35252
  offset = 0;
35076
35253
  length = data.length;
35077
35254
  }
35078
- const input = bytes2(data);
35255
+ const input = bytes3(data);
35079
35256
  const chunk = input.subarray(offset ?? 0, (offset ?? 0) + (length ?? input.length));
35080
35257
  const size = volume.lstatSync(file3.path).size;
35081
35258
  const append = file3.flags.startsWith("a") || (position ?? file3.position) >= size;
@@ -35200,9 +35377,9 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
35200
35377
  const self = this;
35201
35378
  const append = () => {
35202
35379
  try {
35203
- const bytes3 = typeof chunk === "string" ? Buffer2.from(chunk, encoding) : chunk;
35204
- volume.appendFileSync(self.path, new Uint8Array(bytes3));
35205
- self.bytesWritten += bytes3.length;
35380
+ const bytes4 = typeof chunk === "string" ? Buffer2.from(chunk, encoding) : chunk;
35381
+ volume.appendFileSync(self.path, new Uint8Array(bytes4));
35382
+ self.bytesWritten += bytes4.length;
35206
35383
  done();
35207
35384
  } catch (error) {
35208
35385
  done(error);
@@ -35403,6 +35580,57 @@ function createFsModule(volume, cwd, stdinPath, defer = queueMicrotask) {
35403
35580
  ({ offset, length, position } = options);
35404
35581
  }
35405
35582
  const start2 = offset ?? 0;
35583
+ if (fd === 0 && stdin) {
35584
+ const requested = length ?? buffer.byteLength - start2;
35585
+ const finish = (chunk) => {
35586
+ const source = Buffer2.isBuffer(chunk) ? chunk : Buffer2.from(chunk);
35587
+ const count = Math.min(requested, source.byteLength);
35588
+ buffer.set(source.subarray(0, count), start2);
35589
+ if (count < source.byteLength && typeof stdin.unshift === "function") {
35590
+ stdin.unshift(source.subarray(count));
35591
+ }
35592
+ cb(null, count, buffer);
35593
+ };
35594
+ const available2 = stdin.read();
35595
+ if (available2 !== null) {
35596
+ defer(() => finish(available2));
35597
+ return;
35598
+ }
35599
+ if (stdin.readableEnded || stdin.destroyed) {
35600
+ defer(() => cb(null, 0, buffer));
35601
+ return;
35602
+ }
35603
+ let settled = false;
35604
+ const cleanup = () => {
35605
+ stdin.removeListener("readable", onReadable);
35606
+ stdin.removeListener("end", onEnd);
35607
+ stdin.removeListener("error", onError);
35608
+ };
35609
+ const onReadable = () => {
35610
+ if (settled) return;
35611
+ const chunk = stdin.read();
35612
+ if (chunk === null) return;
35613
+ settled = true;
35614
+ cleanup();
35615
+ finish(chunk);
35616
+ };
35617
+ const onEnd = () => {
35618
+ if (settled) return;
35619
+ settled = true;
35620
+ cleanup();
35621
+ cb(null, 0, buffer);
35622
+ };
35623
+ const onError = (error) => {
35624
+ if (settled) return;
35625
+ settled = true;
35626
+ cleanup();
35627
+ cb(error);
35628
+ };
35629
+ stdin.on("readable", onReadable);
35630
+ stdin.once("end", onEnd);
35631
+ stdin.once("error", onError);
35632
+ return;
35633
+ }
35406
35634
  runThenCall(() => [fs.readSync(fd, buffer, start2, length ?? buffer.byteLength - start2, position ?? null), buffer], cb);
35407
35635
  };
35408
35636
  fs.write = (fd, data, ...rest) => {
@@ -35494,8 +35722,8 @@ function createBufferBuiltin() {
35494
35722
  }
35495
35723
  },
35496
35724
  isAscii: (input) => {
35497
- const bytes2 = input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
35498
- for (const byte of bytes2) if (byte > 127) return false;
35725
+ const bytes3 = input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
35726
+ for (const byte of bytes3) if (byte > 127) return false;
35499
35727
  return true;
35500
35728
  }
35501
35729
  };
@@ -36134,37 +36362,37 @@ var MemoryVolume = class {
36134
36362
  writeFileSync(path, data) {
36135
36363
  const key = this.key(path);
36136
36364
  this.requireParent(key, "open");
36137
- const bytes2 = typeof data === "string" ? encoder7.encode(data) : data.slice();
36365
+ const bytes3 = typeof data === "string" ? encoder7.encode(data) : data.slice();
36138
36366
  const current2 = this.entries.get(key);
36139
36367
  if (current2?.kind === "directory") throw new VolumeError("EISDIR", "open", key);
36140
36368
  if (current2?.kind === "symlink") throw new VolumeError("EINVAL", "open", key);
36141
36369
  if (current2) {
36142
- current2.data = bytes2;
36370
+ current2.data = bytes3;
36143
36371
  this.touchChanged(current2, true);
36144
36372
  } else {
36145
- this.entries.set(key, this.inode("file", 438, bytes2));
36373
+ this.entries.set(key, this.inode("file", 438, bytes3));
36146
36374
  }
36147
36375
  }
36148
36376
  appendFileSync(path, data) {
36149
36377
  const key = this.key(path);
36150
- const bytes2 = typeof data === "string" ? encoder7.encode(data) : data;
36378
+ const bytes3 = typeof data === "string" ? encoder7.encode(data) : data;
36151
36379
  const current2 = this.entries.get(key);
36152
- if (!current2) return this.writeFileSync(key, bytes2);
36380
+ if (!current2) return this.writeFileSync(key, bytes3);
36153
36381
  if (current2.kind !== "file") throw new VolumeError(current2.kind === "directory" ? "EISDIR" : "EINVAL", "open", key);
36154
36382
  const length = current2.data.length;
36155
- const needed = length + bytes2.length;
36383
+ const needed = length + bytes3.length;
36156
36384
  const backing = current2.data.buffer;
36157
36385
  const ownsTail = current2.data.byteOffset === 0 && backing instanceof ArrayBuffer && backing.byteLength >= needed && appendCapacity.get(current2) === backing;
36158
36386
  if (ownsTail) {
36159
36387
  const grown = new Uint8Array(backing, 0, needed);
36160
- grown.set(bytes2, length);
36388
+ grown.set(bytes3, length);
36161
36389
  current2.data = grown;
36162
36390
  } else {
36163
36391
  const capacity = Math.max(needed, length * 2, 64 * 1024);
36164
36392
  const buffer = new ArrayBuffer(capacity);
36165
36393
  const grown = new Uint8Array(buffer, 0, needed);
36166
36394
  grown.set(current2.data);
36167
- grown.set(bytes2, length);
36395
+ grown.set(bytes3, length);
36168
36396
  current2.data = grown;
36169
36397
  appendCapacity.set(current2, buffer);
36170
36398
  }
@@ -36737,9 +36965,9 @@ var MirroringVolume = class {
36737
36965
  } catch {
36738
36966
  }
36739
36967
  try {
36740
- const bytes2 = mirror.readFileSync(source);
36968
+ const bytes3 = mirror.readFileSync(source);
36741
36969
  this.ensureDirectory(dirname(destination));
36742
- this.inner.writeFileSync(destination, bytes2);
36970
+ this.inner.writeFileSync(destination, bytes3);
36743
36971
  } catch {
36744
36972
  }
36745
36973
  };
@@ -37121,9 +37349,9 @@ var OutboundTcp = class {
37121
37349
  const bridge = new VirtualTcpConnection({ address, port }, { address: local.address, port: local.port });
37122
37350
  guest.pairWith(bridge);
37123
37351
  bridge.pairWith(guest);
37124
- host2.onData((bytes2) => {
37352
+ host2.onData((bytes3) => {
37125
37353
  try {
37126
- bridge.write(bytes2);
37354
+ bridge.write(bytes3);
37127
37355
  } catch {
37128
37356
  host2.close();
37129
37357
  }
@@ -37178,9 +37406,9 @@ function createNodeTcpDialer() {
37178
37406
  let onClose = null;
37179
37407
  let closed = false;
37180
37408
  socket.on("data", (chunk) => {
37181
- const bytes2 = new Uint8Array(chunk);
37182
- if (onData) onData(bytes2);
37183
- else pending.push(bytes2);
37409
+ const bytes3 = new Uint8Array(chunk);
37410
+ if (onData) onData(bytes3);
37411
+ else pending.push(bytes3);
37184
37412
  });
37185
37413
  const finish = () => {
37186
37414
  if (closed) return;
@@ -37199,8 +37427,8 @@ function createNodeTcpDialer() {
37199
37427
  socket.on("connect", () => {
37200
37428
  socket.setNoDelay(true);
37201
37429
  resolve3({
37202
- write(bytes2) {
37203
- socket.write(bytes2);
37430
+ write(bytes3) {
37431
+ socket.write(bytes3);
37204
37432
  },
37205
37433
  end() {
37206
37434
  socket.end();
@@ -37252,8 +37480,7 @@ function translate(error, host2, port) {
37252
37480
 
37253
37481
  // src/worker/local-runtime-pod.ts
37254
37482
  var WASM_ALIASES = {
37255
- esbuild: "esbuild-wasm",
37256
- rollup: "@rollup/wasm-node"
37483
+ ...RUNTIME_PACKAGE_FALLBACKS
37257
37484
  };
37258
37485
  var ProcessExit = class extends Error {
37259
37486
  constructor(code) {
@@ -37413,7 +37640,7 @@ var PodChildProcess = class {
37413
37640
  /* The child is launched asynchronously, but a parent may write and close
37414
37641
  * its input synchronously right after spawning. Holding both until the
37415
37642
  * child exists is what keeps `echo hi | child` from losing the `hi`. */
37416
- pendingInput = "";
37643
+ pendingInput = [];
37417
37644
  inputEnded = false;
37418
37645
  on(event, listener) {
37419
37646
  let set = this.listeners.get(event);
@@ -37437,15 +37664,13 @@ var PodChildProcess = class {
37437
37664
  (child) => {
37438
37665
  this.child = child;
37439
37666
  if (this.cancelled) child.kill();
37440
- if (this.pendingInput !== "") {
37441
- child.write(this.pendingInput);
37442
- this.pendingInput = "";
37443
- }
37667
+ for (const chunk of this.pendingInput.splice(0)) child.write(chunk);
37444
37668
  if (this.inputEnded) child.endInput?.();
37445
- child.on("output", (chunk) => {
37669
+ const outputEvent = child.rawOutput ? "raw-output" : "output";
37670
+ child.on(outputEvent, (chunk) => {
37446
37671
  const text2 = typeof chunk === "string" ? chunk : this.outText.decode(chunk, { stream: true });
37447
37672
  this.stdout += text2;
37448
- this.emit("stdout", text2);
37673
+ this.emit("stdout", chunk);
37449
37674
  });
37450
37675
  child.on("error", (chunk) => {
37451
37676
  const text2 = typeof chunk === "string" ? chunk : this.errText.decode(chunk, { stream: true });
@@ -37467,7 +37692,7 @@ var PodChildProcess = class {
37467
37692
  }
37468
37693
  sendStdin(data) {
37469
37694
  if (this.child) this.child.write(data);
37470
- else this.pendingInput += data;
37695
+ else this.pendingInput.push(data);
37471
37696
  }
37472
37697
  /** Signal EOF, so a child reading stdin to the end can finish. */
37473
37698
  endStdin() {
@@ -37827,14 +38052,14 @@ ${headers.join("\r\n")}\r
37827
38052
  `);
37828
38053
  connection.write(request);
37829
38054
  if (body.length) connection.write(body);
37830
- const bytes2 = [];
38055
+ const bytes3 = [];
37831
38056
  let combined = new Uint8Array();
37832
38057
  for (; ; ) {
37833
38058
  try {
37834
38059
  const chunk = connection.read(64 * 1024);
37835
38060
  if (chunk.length === 0) break;
37836
- bytes2.push(chunk);
37837
- combined = joinBytes(bytes2);
38061
+ bytes3.push(chunk);
38062
+ combined = joinBytes(bytes3);
37838
38063
  const headerEnd = findBytes(combined, new Uint8Array([13, 10, 13, 10]));
37839
38064
  if (headerEnd < 0) continue;
37840
38065
  const headerText = new TextDecoder().decode(combined.subarray(0, headerEnd));
@@ -37900,11 +38125,11 @@ function findBytes(haystack, needle) {
37900
38125
  }
37901
38126
  return -1;
37902
38127
  }
37903
- function parseHttpResponse(bytes2) {
38128
+ function parseHttpResponse(bytes3) {
37904
38129
  const marker = new Uint8Array([13, 10, 13, 10]);
37905
- const headerEnd = findBytes(bytes2, marker);
38130
+ const headerEnd = findBytes(bytes3, marker);
37906
38131
  if (headerEnd < 0) throw new Error("Python server returned an incomplete HTTP response");
37907
- const text2 = new TextDecoder().decode(bytes2.subarray(0, headerEnd));
38132
+ const text2 = new TextDecoder().decode(bytes3.subarray(0, headerEnd));
37908
38133
  const lines = text2.split("\r\n");
37909
38134
  const status = /HTTP\/\d\.\d\s+(\d+)(?:\s+(.*))?/.exec(lines.shift() ?? "");
37910
38135
  if (!status) throw new Error("Python server returned an invalid HTTP status line");
@@ -37913,7 +38138,7 @@ function parseHttpResponse(bytes2) {
37913
38138
  const separator = line.indexOf(":");
37914
38139
  if (separator > 0) headers[line.slice(0, separator).toLowerCase()] = line.slice(separator + 1).trim();
37915
38140
  }
37916
- let body = bytes2.slice(headerEnd + marker.length);
38141
+ let body = bytes3.slice(headerEnd + marker.length);
37917
38142
  if (CHUNKED.test(headers["transfer-encoding"] ?? "")) {
37918
38143
  body = decodeChunked(body).body;
37919
38144
  delete headers["transfer-encoding"];
@@ -37927,19 +38152,19 @@ function parseHttpResponse(bytes2) {
37927
38152
  };
37928
38153
  }
37929
38154
  var CHUNKED = /^(?:transfer-encoding:.*)?\bchunked\b/im;
37930
- function decodeChunked(bytes2) {
38155
+ function decodeChunked(bytes3) {
37931
38156
  const parts = [];
37932
38157
  const crlf = new Uint8Array([13, 10]);
37933
38158
  for (let at = 0; ; ) {
37934
- const lineEnd = findBytes(bytes2.subarray(at), crlf);
38159
+ const lineEnd = findBytes(bytes3.subarray(at), crlf);
37935
38160
  if (lineEnd < 0) return { body: joinBytes(parts), complete: false };
37936
- const header = new TextDecoder().decode(bytes2.subarray(at, at + lineEnd)).split(";")[0].trim();
38161
+ const header = new TextDecoder().decode(bytes3.subarray(at, at + lineEnd)).split(";")[0].trim();
37937
38162
  const size = /^[0-9a-f]+$/i.test(header) ? Number.parseInt(header, 16) : Number.NaN;
37938
38163
  if (!Number.isInteger(size)) throw new Error("Python server returned an invalid chunked response");
37939
38164
  at += lineEnd + crlf.length;
37940
38165
  if (size === 0) return { body: joinBytes(parts), complete: true };
37941
- if (at + size + crlf.length > bytes2.length) return { body: joinBytes(parts), complete: false };
37942
- parts.push(bytes2.subarray(at, at + size));
38166
+ if (at + size + crlf.length > bytes3.length) return { body: joinBytes(parts), complete: false };
38167
+ parts.push(bytes3.subarray(at, at + size));
37943
38168
  at += size + crlf.length;
37944
38169
  }
37945
38170
  }
@@ -38122,7 +38347,7 @@ var WorkerProcess = class extends EventEmitter4 {
38122
38347
  */
38123
38348
  write(data) {
38124
38349
  if (this.inheritedInput) {
38125
- this.inheritedInput.sendStdin(typeof data === "string" ? data : new TextDecoder().decode(data));
38350
+ this.inheritedInput.sendStdin(data);
38126
38351
  return;
38127
38352
  }
38128
38353
  if (this.started) this.worker.postMessage({ type: "stdin", data });
@@ -38286,7 +38511,9 @@ var WorkerRuntimePod = class _WorkerRuntimePod extends LocalRuntimePod {
38286
38511
  this.startChild(worker, children, message, ownedChildren);
38287
38512
  return;
38288
38513
  case "child-stdin":
38289
- children.get(message.id)?.sendStdin?.(String(message.data));
38514
+ children.get(message.id)?.sendStdin?.(
38515
+ message.data instanceof Uint8Array ? message.data : String(message.data)
38516
+ );
38290
38517
  return;
38291
38518
  case "child-stdin-end":
38292
38519
  children.get(message.id)?.endStdin?.();
@@ -38328,20 +38555,22 @@ var WorkerRuntimePod = class _WorkerRuntimePod extends LocalRuntimePod {
38328
38555
  return;
38329
38556
  }
38330
38557
  });
38331
- worker.postMessage({
38332
- type: "start",
38333
- buffers,
38334
- script,
38335
- cwd,
38336
- env: env2,
38337
- argv: Array.isArray(options.argv) ? options.argv : ["/usr/bin/node", script, ...args.slice(1)],
38338
- aliases: this.aliases,
38339
- ...typeof options.stdinPath === "string" ? { stdinPath: options.stdinPath } : {},
38340
- ...options.interactiveStdin ? { interactiveStdin: true } : {},
38341
- ...options.tty ? { tty: true } : {},
38342
- ...this.networkPolicy ? { network: this.networkPolicy } : {}
38343
- });
38344
- process2.begin();
38558
+ setTimeout(() => {
38559
+ worker.postMessage({
38560
+ type: "start",
38561
+ buffers,
38562
+ script,
38563
+ cwd,
38564
+ env: env2,
38565
+ argv: Array.isArray(options.argv) ? options.argv : ["/usr/bin/node", script, ...args.slice(1)],
38566
+ aliases: this.aliases,
38567
+ ...typeof options.stdinPath === "string" ? { stdinPath: options.stdinPath } : {},
38568
+ ...options.interactiveStdin ? { interactiveStdin: true } : {},
38569
+ ...options.tty ? { tty: true } : {},
38570
+ ...this.networkPolicy ? { network: this.networkPolicy } : {}
38571
+ });
38572
+ process2.begin();
38573
+ }, 0);
38345
38574
  return process2;
38346
38575
  }
38347
38576
  /** Start an asynchronous child on the host's behalf and relay its events. */
@@ -38379,16 +38608,20 @@ var WorkerRuntimePod = class _WorkerRuntimePod extends LocalRuntimePod {
38379
38608
  handle.on("exit", () => owned.delete(handle));
38380
38609
  let stdout = "";
38381
38610
  let stderr = "";
38611
+ const stdoutDecoder = new TextDecoder();
38612
+ const stderrDecoder = new TextDecoder();
38382
38613
  const live = request.inheritStdio ? streamTo : null;
38383
38614
  const restoreInput = live?.inheritInput(handle);
38384
38615
  if (restoreInput) handle.on("exit", restoreInput);
38385
- handle.on("stdout", (text2) => {
38616
+ handle.on("stdout", (value) => {
38617
+ const text2 = typeof value === "string" ? value : stdoutDecoder.decode(value, { stream: true });
38386
38618
  stdout += text2;
38387
- live?.output(text2);
38619
+ live?.output(value);
38388
38620
  });
38389
- handle.on("stderr", (text2) => {
38621
+ handle.on("stderr", (value) => {
38622
+ const text2 = typeof value === "string" ? value : stderrDecoder.decode(value, { stream: true });
38390
38623
  stderr += text2;
38391
- live?.error(text2);
38624
+ live?.error(value);
38392
38625
  });
38393
38626
  handle.on("exit", (code) => resolve3({ status: code, stdout, stderr, signal: null }));
38394
38627
  handle.exec();
@@ -38459,8 +38692,8 @@ var WorkerRuntimePod = class _WorkerRuntimePod extends LocalRuntimePod {
38459
38692
  const id = this.nextRequestId++;
38460
38693
  this.upgraded.set(id, socket);
38461
38694
  socket.on("data", (chunk) => {
38462
- const bytes2 = new Uint8Array(chunk);
38463
- worker.postMessage({ type: "ws-data", id, data: bytes2 });
38695
+ const bytes3 = new Uint8Array(chunk);
38696
+ worker.postMessage({ type: "ws-data", id, data: bytes3 });
38464
38697
  });
38465
38698
  const drop = () => {
38466
38699
  if (!this.upgraded.delete(id)) return;
@@ -38600,7 +38833,8 @@ var Container = class _Container {
38600
38833
  const network = {
38601
38834
  allowOutbound: opts.network?.allowOutbound ?? false,
38602
38835
  allowedHosts: opts.network?.allowedHosts ?? null,
38603
- ...opts.network?.proxy ? { proxy: opts.network.proxy } : {}
38836
+ ...opts.network?.proxy ? { proxy: opts.network.proxy } : {},
38837
+ ...opts.network?.secrets ? { secrets: opts.network.secrets } : {}
38604
38838
  };
38605
38839
  const podOptions = {
38606
38840
  workdir: opts.cwd ?? "/",
@@ -38916,17 +39150,17 @@ var Container = class _Container {
38916
39150
  body: init.body ?? null
38917
39151
  });
38918
39152
  const bodyRaw = res.body;
38919
- const bytes2 = bodyRaw instanceof Uint8Array ? bodyRaw : (
39153
+ const bytes3 = bodyRaw instanceof Uint8Array ? bodyRaw : (
38920
39154
  // The binary dispatcher answers with an ArrayBuffer.
38921
39155
  bodyRaw instanceof ArrayBuffer ? new Uint8Array(bodyRaw) : typeof bodyRaw === "string" ? new TextEncoder().encode(bodyRaw) : new Uint8Array(0)
38922
39156
  );
38923
- const body = typeof bodyRaw === "string" ? bodyRaw : new TextDecoder().decode(bytes2);
39157
+ const body = typeof bodyRaw === "string" ? bodyRaw : new TextDecoder().decode(bytes3);
38924
39158
  return {
38925
39159
  status: res.statusCode ?? 200,
38926
39160
  statusText: res.statusMessage ?? "",
38927
39161
  headers: res.headers ?? {},
38928
39162
  body,
38929
- bytes: bytes2,
39163
+ bytes: bytes3,
38930
39164
  json() {
38931
39165
  return JSON.parse(body);
38932
39166
  }
@@ -39559,7 +39793,7 @@ function serveContainerOn(port, box) {
39559
39793
  headers: request.headers,
39560
39794
  ...request.body ? { body: new Uint8Array(request.body) } : {}
39561
39795
  });
39562
- const bytes2 = response.bytes.slice();
39796
+ const bytes3 = response.bytes.slice();
39563
39797
  port.postMessage(
39564
39798
  {
39565
39799
  id: request.id,
@@ -39567,10 +39801,10 @@ function serveContainerOn(port, box) {
39567
39801
  status: response.status,
39568
39802
  statusText: response.statusText,
39569
39803
  headers: response.headers,
39570
- body: bytes2.buffer
39804
+ body: bytes3.buffer
39571
39805
  }
39572
39806
  },
39573
- [bytes2.buffer]
39807
+ [bytes3.buffer]
39574
39808
  );
39575
39809
  } catch (error) {
39576
39810
  const message = new TextEncoder().encode(error instanceof Error ? error.message : String(error));
@@ -39656,8 +39890,8 @@ async function createPreview(box, options = {}) {
39656
39890
  Number(data.port),
39657
39891
  { method: "GET", path: data.path ?? "/", headers: data.headers ?? {} },
39658
39892
  {
39659
- data: (bytes2) => {
39660
- const carrier = bytes2.slice().buffer;
39893
+ data: (bytes3) => {
39894
+ const carrier = bytes3.slice().buffer;
39661
39895
  reply({ type: WS_DATA, id, data: carrier }, [carrier]);
39662
39896
  },
39663
39897
  close: () => {
@@ -39739,8 +39973,8 @@ function gitFilesystem(ctx) {
39739
39973
  const encoding = (opts) => typeof opts === "string" ? opts : opts?.encoding;
39740
39974
  return { promises: {
39741
39975
  async readFile(path, opts) {
39742
- const bytes2 = Buffer2.from(ctx.vfs.readFile(ctx.path(path), ctx.cred));
39743
- return encoding(opts) ? bytes2.toString(encoding(opts)) : bytes2;
39976
+ const bytes3 = Buffer2.from(ctx.vfs.readFile(ctx.path(path), ctx.cred));
39977
+ return encoding(opts) ? bytes3.toString(encoding(opts)) : bytes3;
39744
39978
  },
39745
39979
  async writeFile(path, data, opts) {
39746
39980
  ctx.vfs.writeFile(ctx.path(path), data, { cred: ctx.cred, mode: opts?.mode });
@@ -39932,8 +40166,8 @@ var signed = (value) => {
39932
40166
  }
39933
40167
  };
39934
40168
  var str = (s) => {
39935
- const bytes2 = [...new TextEncoder().encode(s)];
39936
- return [...leb(bytes2.length), ...bytes2];
40169
+ const bytes3 = [...new TextEncoder().encode(s)];
40170
+ return [...leb(bytes3.length), ...bytes3];
39937
40171
  };
39938
40172
  var section = (id, data) => [id, ...leb(data.length), ...data];
39939
40173
  function compileInstruction({ op, next }) {