@volter/tabnode 0.5.24 → 0.5.26

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/__sw__.js CHANGED
@@ -43,7 +43,8 @@ function openHost(id, channel) {
43
43
  };
44
44
  hosts.set(id, host);
45
45
  latestHost = host;
46
- void pruneClients();
46
+ // Clients that are gone are forgotten; a prune that fails forgets nothing.
47
+ void pruneClients().catch(() => {});
47
48
  return host;
48
49
  }
49
50
 
@@ -544,7 +545,7 @@ async function blobWorkerContext(client, requestUrl) {
544
545
  if (owners.some(owner => owner.context.port !== owners[0].context.port || owner.host !== owners[0].host)) throw new Error('Ambiguous virtual blob owner');
545
546
  rootedClients.set(client.id, owners[0].context.port);
546
547
  if (owners[0].host) clientHosts.set(client.id, owners[0].host.id);
547
- if (rootedClients.size > 256) pruneClients();
548
+ if (rootedClients.size > 256) void pruneClients().catch(() => {});
548
549
  return owners[0].context;
549
550
  })();
550
551
  pendingBlobContexts.set(client.id, pending);
@@ -617,7 +618,7 @@ async function askForInit() {
617
618
  function handleRootedRequest(event, port, path) {
618
619
  if (event.resultingClientId) {
619
620
  rootedClients.set(event.resultingClientId, port);
620
- if (rootedClients.size > 256) pruneClients();
621
+ if (rootedClients.size > 256) void pruneClients().catch(() => {});
621
622
  }
622
623
  return handleVirtualRequest(event.request, port, path, true);
623
624
  }
@@ -21146,17 +21146,10 @@ var implementation$1 = function bind2(that) {
21146
21146
  var implementation = implementation$1;
21147
21147
  var functionBind = Function.prototype.bind || implementation;
21148
21148
  var functionCall = Function.prototype.call;
21149
- var functionApply;
21150
- var hasRequiredFunctionApply;
21151
- function requireFunctionApply() {
21152
- if (hasRequiredFunctionApply) return functionApply;
21153
- hasRequiredFunctionApply = 1;
21154
- functionApply = Function.prototype.apply;
21155
- return functionApply;
21156
- }
21149
+ var functionApply = Function.prototype.apply;
21157
21150
  var reflectApply = typeof Reflect !== "undefined" && Reflect && Reflect.apply;
21158
21151
  var bind$2 = functionBind;
21159
- var $apply$1 = requireFunctionApply();
21152
+ var $apply$1 = functionApply;
21160
21153
  var $call$2 = functionCall;
21161
21154
  var $reflectApply = reflectApply;
21162
21155
  var actualApply = $reflectApply || bind$2.call($call$2, $apply$1);
@@ -21276,7 +21269,7 @@ var hasSymbols = requireHasSymbols()();
21276
21269
  var getProto = requireGetProto();
21277
21270
  var $ObjectGPO = requireObject_getPrototypeOf();
21278
21271
  var $ReflectGPO = requireReflect_getPrototypeOf();
21279
- var $apply = requireFunctionApply();
21272
+ var $apply = functionApply;
21280
21273
  var $call = functionCall;
21281
21274
  var needsEval = {};
21282
21275
  var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined$1 : getProto(Uint8Array);
@@ -21917,7 +21910,7 @@ function requireApplyBind() {
21917
21910
  if (hasRequiredApplyBind) return applyBind;
21918
21911
  hasRequiredApplyBind = 1;
21919
21912
  var bind3 = functionBind;
21920
- var $apply2 = requireFunctionApply();
21913
+ var $apply2 = functionApply;
21921
21914
  var actualApply$1 = actualApply;
21922
21915
  applyBind = function applyBind2() {
21923
21916
  return actualApply$1(bind3, $apply2, arguments);
@@ -22528,9 +22521,9 @@ Sha256$1.prototype._hash = function() {
22528
22521
  H.writeInt32BE(this._h, 28);
22529
22522
  return H;
22530
22523
  };
22531
- var sha256 = Sha256$1;
22524
+ var sha256$1 = Sha256$1;
22532
22525
  var inherits$2 = inherits_browserExports;
22533
- var Sha256 = sha256;
22526
+ var Sha256 = sha256$1;
22534
22527
  var Hash$2 = hash$1;
22535
22528
  var Buffer$3 = safeBufferExports.Buffer;
22536
22529
  var W$3 = new Array(64);
@@ -22956,7 +22949,7 @@ var sha384 = Sha384;
22956
22949
  module.exports.sha = sha;
22957
22950
  module.exports.sha1 = sha1;
22958
22951
  module.exports.sha224 = sha224;
22959
- module.exports.sha256 = sha256;
22952
+ module.exports.sha256 = sha256$1;
22960
22953
  module.exports.sha384 = sha384;
22961
22954
  module.exports.sha512 = sha512;
22962
22955
  })(sha_js);
@@ -23010,9 +23003,27 @@ function clean(...arrays) {
23010
23003
  function createView(arr) {
23011
23004
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
23012
23005
  }
23006
+ function rotr(word, shift) {
23007
+ return word << 32 - shift | word >>> shift;
23008
+ }
23013
23009
  function rotl(word, shift) {
23014
23010
  return word << shift | word >>> 32 - shift >>> 0;
23015
23011
  }
23012
+ const hasHexBuiltin = /* @__PURE__ */ (() => (
23013
+ // @ts-ignore
23014
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
23015
+ ))();
23016
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i10) => i10.toString(16).padStart(2, "0"));
23017
+ function bytesToHex(bytes2) {
23018
+ abytes(bytes2);
23019
+ if (hasHexBuiltin)
23020
+ return bytes2.toHex();
23021
+ let hex = "";
23022
+ for (let i10 = 0; i10 < bytes2.length; i10++) {
23023
+ hex += hexes[bytes2[i10]];
23024
+ }
23025
+ return hex;
23026
+ }
23016
23027
  function checkOpts(defaults2, opts, title = "opts") {
23017
23028
  aobject(defaults2, "defaults");
23018
23029
  if (opts !== void 0)
@@ -23033,9 +23044,17 @@ function createHasher(hashCons, info = {}) {
23033
23044
  Object.assign(hashC, info);
23034
23045
  return Object.freeze(hashC);
23035
23046
  }
23047
+ const oidNist = (suffix) => ({
23048
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
23049
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
23050
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
23051
+ });
23036
23052
  function Chi(a, b, c) {
23037
23053
  return a & b ^ ~a & c;
23038
23054
  }
23055
+ function Maj(a, b, c) {
23056
+ return a & b ^ a & c ^ b & c;
23057
+ }
23039
23058
  class HashMD {
23040
23059
  constructor(blockLen, outputLen, padOffset, isLE) {
23041
23060
  __publicField(this, "blockLen");
@@ -23131,6 +23150,16 @@ class HashMD {
23131
23150
  return this._cloneInto();
23132
23151
  }
23133
23152
  }
23153
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
23154
+ 1779033703,
23155
+ 3144134277,
23156
+ 1013904242,
23157
+ 2773480762,
23158
+ 1359893119,
23159
+ 2600822924,
23160
+ 528734635,
23161
+ 1541459225
23162
+ ]);
23134
23163
  const SHA1_IV = /* @__PURE__ */ Uint32Array.from([
23135
23164
  1732584193,
23136
23165
  4023233417,
@@ -32110,6 +32139,169 @@ function simpleHash(str) {
32110
32139
  }
32111
32140
  return hash2.toString(36);
32112
32141
  }
32142
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
32143
+ 1116352408,
32144
+ 1899447441,
32145
+ 3049323471,
32146
+ 3921009573,
32147
+ 961987163,
32148
+ 1508970993,
32149
+ 2453635748,
32150
+ 2870763221,
32151
+ 3624381080,
32152
+ 310598401,
32153
+ 607225278,
32154
+ 1426881987,
32155
+ 1925078388,
32156
+ 2162078206,
32157
+ 2614888103,
32158
+ 3248222580,
32159
+ 3835390401,
32160
+ 4022224774,
32161
+ 264347078,
32162
+ 604807628,
32163
+ 770255983,
32164
+ 1249150122,
32165
+ 1555081692,
32166
+ 1996064986,
32167
+ 2554220882,
32168
+ 2821834349,
32169
+ 2952996808,
32170
+ 3210313671,
32171
+ 3336571891,
32172
+ 3584528711,
32173
+ 113926993,
32174
+ 338241895,
32175
+ 666307205,
32176
+ 773529912,
32177
+ 1294757372,
32178
+ 1396182291,
32179
+ 1695183700,
32180
+ 1986661051,
32181
+ 2177026350,
32182
+ 2456956037,
32183
+ 2730485921,
32184
+ 2820302411,
32185
+ 3259730800,
32186
+ 3345764771,
32187
+ 3516065817,
32188
+ 3600352804,
32189
+ 4094571909,
32190
+ 275423344,
32191
+ 430227734,
32192
+ 506948616,
32193
+ 659060556,
32194
+ 883997877,
32195
+ 958139571,
32196
+ 1322822218,
32197
+ 1537002063,
32198
+ 1747873779,
32199
+ 1955562222,
32200
+ 2024104815,
32201
+ 2227730452,
32202
+ 2361852424,
32203
+ 2428436474,
32204
+ 2756734187,
32205
+ 3204031479,
32206
+ 3329325298
32207
+ ]);
32208
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
32209
+ class SHA2_32B extends HashMD {
32210
+ constructor(outputLen, IV) {
32211
+ super(64, outputLen, 8, false);
32212
+ // We cannot use array here since array allows indexing by variable
32213
+ // which means optimizer/compiler cannot use registers.
32214
+ // Numeric initializers matter: starting the fields as `undefined` changes
32215
+ // V8's field representation and makes sha256 3x slower (measured).
32216
+ __publicField(this, "A", 0);
32217
+ __publicField(this, "B", 0);
32218
+ __publicField(this, "C", 0);
32219
+ __publicField(this, "D", 0);
32220
+ __publicField(this, "E", 0);
32221
+ __publicField(this, "F", 0);
32222
+ __publicField(this, "G", 0);
32223
+ __publicField(this, "H", 0);
32224
+ this.A = IV[0] | 0;
32225
+ this.B = IV[1] | 0;
32226
+ this.C = IV[2] | 0;
32227
+ this.D = IV[3] | 0;
32228
+ this.E = IV[4] | 0;
32229
+ this.F = IV[5] | 0;
32230
+ this.G = IV[6] | 0;
32231
+ this.H = IV[7] | 0;
32232
+ }
32233
+ get() {
32234
+ const { A: A10, B, C, D: D10, E: E7, F, G: G10, H } = this;
32235
+ return [A10, B, C, D10, E7, F, G10, H];
32236
+ }
32237
+ // prettier-ignore
32238
+ set(A10, B, C, D10, E7, F, G10, H) {
32239
+ this.A = A10 | 0;
32240
+ this.B = B | 0;
32241
+ this.C = C | 0;
32242
+ this.D = D10 | 0;
32243
+ this.E = E7 | 0;
32244
+ this.F = F | 0;
32245
+ this.G = G10 | 0;
32246
+ this.H = H | 0;
32247
+ }
32248
+ _cloneInto(to2) {
32249
+ (to2 || (to2 = new this.constructor())).set(...this.get());
32250
+ return this._cloneIntoMeta(to2);
32251
+ }
32252
+ process(view, offset2) {
32253
+ for (let i10 = 0; i10 < 16; i10++, offset2 += 4)
32254
+ SHA256_W[i10] = view.getUint32(offset2, false);
32255
+ for (let i10 = 16; i10 < 64; i10++) {
32256
+ const W15 = SHA256_W[i10 - 15];
32257
+ const W22 = SHA256_W[i10 - 2];
32258
+ const s02 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
32259
+ const s12 = rotr(W22, 17) ^ rotr(W22, 19) ^ W22 >>> 10;
32260
+ SHA256_W[i10] = s12 + SHA256_W[i10 - 7] + s02 + SHA256_W[i10 - 16] | 0;
32261
+ }
32262
+ let { A: A10, B, C, D: D10, E: E7, F, G: G10, H } = this;
32263
+ for (let i10 = 0; i10 < 64; i10++) {
32264
+ const sigma12 = rotr(E7, 6) ^ rotr(E7, 11) ^ rotr(E7, 25);
32265
+ const T12 = H + sigma12 + Chi(E7, F, G10) + SHA256_K[i10] + SHA256_W[i10] | 0;
32266
+ const sigma02 = rotr(A10, 2) ^ rotr(A10, 13) ^ rotr(A10, 22);
32267
+ const T22 = sigma02 + Maj(A10, B, C) | 0;
32268
+ H = G10;
32269
+ G10 = F;
32270
+ F = E7;
32271
+ E7 = D10 + T12 | 0;
32272
+ D10 = C;
32273
+ C = B;
32274
+ B = A10;
32275
+ A10 = T12 + T22 | 0;
32276
+ }
32277
+ A10 = A10 + this.A | 0;
32278
+ B = B + this.B | 0;
32279
+ C = C + this.C | 0;
32280
+ D10 = D10 + this.D | 0;
32281
+ E7 = E7 + this.E | 0;
32282
+ F = F + this.F | 0;
32283
+ G10 = G10 + this.G | 0;
32284
+ H = H + this.H | 0;
32285
+ this.set(A10, B, C, D10, E7, F, G10, H);
32286
+ }
32287
+ roundClean() {
32288
+ clean(SHA256_W);
32289
+ }
32290
+ destroy() {
32291
+ this.destroyed = true;
32292
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
32293
+ clean(this.buffer);
32294
+ }
32295
+ }
32296
+ class _SHA256 extends SHA2_32B {
32297
+ constructor() {
32298
+ super(32, SHA256_IV);
32299
+ }
32300
+ }
32301
+ const sha256 = /* @__PURE__ */ createHasher(
32302
+ () => new _SHA256(),
32303
+ /* @__PURE__ */ oidNist(1)
32304
+ );
32113
32305
  const fsModule = lazyModule("fs");
32114
32306
  lazyModule("internal/fs/promises");
32115
32307
  function fsModuleFor(process2) {
@@ -78302,6 +78494,30 @@ Object.defineProperty(globalThis, "__substrateEvalSource", {
78302
78494
  configurable: true,
78303
78495
  value: (source) => typeof source === "string" ? __substrateRewriteDynamicImportsInScript(source) : source
78304
78496
  });
78497
+ function __substratePrepareBody(rawCode, resolvedPath, format2, process2) {
78498
+ let code2 = rawCode;
78499
+ if (code2.startsWith("#!")) {
78500
+ code2 = code2.slice(code2.indexOf("\n") + 1);
78501
+ }
78502
+ code2 = __substrateModuleTypes(code2, resolvedPath, format2, process2);
78503
+ const __commonjs = format2 === "commonjs" || format2 === "commonjs-typescript" ? true : format2 === "module" || format2 === "module-typescript" ? false : resolvedPath.endsWith(".cjs") || resolvedPath.endsWith(".cts");
78504
+ if (!__commonjs) {
78505
+ const lowered = transformEsmToCjs(code2, resolvedPath);
78506
+ code2 = lowered === code2 ? code2 : `${__substrateModuleMarker}"use strict";${lowered}`;
78507
+ } else {
78508
+ code2 = transformDynamicImportsRegex(code2);
78509
+ }
78510
+ return code2;
78511
+ }
78512
+ const PREPARED_MODULES_DIR = "/.tabnode/prepared";
78513
+ const PREPARED_MODULES_FORMAT = "tabnode-prepared-1";
78514
+ function preparedModuleKey(rawCode, resolvedPath) {
78515
+ var _a3;
78516
+ const extension = (_a3 = /\.(js|cjs|mjs)$/u.exec(resolvedPath)) == null ? void 0 : _a3[1];
78517
+ if (!extension) return void 0;
78518
+ const kind = extension === "cjs" ? "cjs" : "js";
78519
+ return bytesToHex(sha256(new TextEncoder().encode(`${PREPARED_MODULES_FORMAT}|${kind}|${rawCode}`)));
78520
+ }
78305
78521
  function transformEsmToCjs(code2, filename) {
78306
78522
  const maybeEsm = __substrateHasEsmSyntax(code2);
78307
78523
  if (!maybeEsm) return __substrateRewriteDynamicImportsInScript(code2);
@@ -79340,6 +79556,14 @@ function createRequire(vfs2, fsShim, process2, currentDir, moduleCache, options,
79340
79556
  }
79341
79557
  const rawCode = source === void 0 || source === null ? defaultSource() : String(source);
79342
79558
  const dirname$1 = resolvedPath.startsWith("data:") ? currentDir : dirname(resolvedPath);
79559
+ if (format2 === void 0 && !transformsTypes(process2) && vfs2.existsSync(PREPARED_MODULES_DIR)) {
79560
+ const key = preparedModuleKey(rawCode, resolvedPath);
79561
+ const prepared = key ? `${PREPARED_MODULES_DIR}/${key}` : void 0;
79562
+ if (prepared && vfs2.existsSync(prepared)) {
79563
+ runModuleBody(module, vfs2.readFileSync(prepared, "utf8"), resolvedPath, dirname$1, true);
79564
+ return module;
79565
+ }
79566
+ }
79343
79567
  runModuleBody(module, prepareModuleCode(rawCode, resolvedPath, format2), resolvedPath, dirname$1);
79344
79568
  return module;
79345
79569
  };
@@ -79347,23 +79571,12 @@ function createRequire(vfs2, fsShim, process2, currentDir, moduleCache, options,
79347
79571
  const codeCacheKey = `${resolvedPath}|${format2 ?? ""}|${transformsTypes(process2) ? "transform-types|" : ""}${simpleHash(rawCode)}`;
79348
79572
  let code2 = processedCodeCache == null ? void 0 : processedCodeCache.get(codeCacheKey);
79349
79573
  if (!code2) {
79350
- code2 = rawCode;
79351
- if (code2.startsWith("#!")) {
79352
- code2 = code2.slice(code2.indexOf("\n") + 1);
79353
- }
79354
- code2 = __substrateModuleTypes(code2, resolvedPath, format2, process2);
79355
- const __commonjs = format2 === "commonjs" || format2 === "commonjs-typescript" ? true : format2 === "module" || format2 === "module-typescript" ? false : resolvedPath.endsWith(".cjs") || resolvedPath.endsWith(".cts");
79356
- if (!__commonjs) {
79357
- const lowered = transformEsmToCjs(code2, resolvedPath);
79358
- code2 = lowered === code2 ? code2 : `${__substrateModuleMarker}"use strict";${lowered}`;
79359
- } else {
79360
- code2 = transformDynamicImportsRegex(code2);
79361
- }
79574
+ code2 = __substratePrepareBody(rawCode, resolvedPath, format2, process2);
79362
79575
  processedCodeCache == null ? void 0 : processedCodeCache.set(codeCacheKey, code2);
79363
79576
  }
79364
79577
  return code2;
79365
79578
  };
79366
- const runModuleBody = (module, prepared, resolvedPath, dirname2) => {
79579
+ const runModuleBody = (module, prepared, resolvedPath, dirname2, scoped = false) => {
79367
79580
  let code2 = prepared;
79368
79581
  const moduleRequire = createRequire(
79369
79582
  vfs2,
@@ -79380,7 +79593,7 @@ function createRequire(vfs2, fsShim, process2, currentDir, moduleCache, options,
79380
79593
  try {
79381
79594
  const importMetaUrl = resolvedPath.startsWith("data:") ? resolvedPath : "file://" + resolvedPath;
79382
79595
  const strictBody = code2.startsWith(__substrateModuleMarker);
79383
- code2 = __substrateScopeGlobalCalls(code2);
79596
+ if (!scoped) code2 = __substrateScopeGlobalCalls(code2);
79384
79597
  const wrappedCode = `(function($exports, $require, $module, $filename, $dirname, $process, $console, $importMeta, $dynamicImport, __substrateGuestGlobal, __substrateGuestConstructor) { var exports = $exports; var require = $require; var module = $module; var __filename = $filename; var __dirname = $dirname; var process = $process; var console = $console; var import_meta = $importMeta; var __dynamicImport = $dynamicImport; var document = void 0, window = void 0, location = void 0, self = void 0; var globalThis = __substrateGuestGlobal($process); var global = globalThis; var Buffer = globalThis.Buffer; var queueMicrotask = globalThis.queueMicrotask, atob = globalThis.atob, btoa = globalThis.btoa, structuredClone = globalThis.structuredClone, setTimeout = globalThis.setTimeout, clearTimeout = globalThis.clearTimeout, setInterval = globalThis.setInterval, clearInterval = globalThis.clearInterval; globalThis.process = $process; global.process = $process; with ({ __proto__: null, get navigator() { return globalThis.navigator; }, set navigator(value) { globalThis.navigator = value; }, get Navigator() { return globalThis.Navigator; }, set Navigator(value) { globalThis.Navigator = value; }, get Promise() { return globalThis.Promise; }, set Promise(value) { globalThis.Promise = value; }, get fetch() { return globalThis.fetch; }, set fetch(value) { globalThis.fetch = value; } }) { return (function() {${code2}
79385
79598
  }).call(${strictBody ? "void 0" : "$module.exports"}); }
79386
79599
  })${__substrateSourceURL(resolvedPath)}`;
package/dist/index.d.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  export { restoreHostGlobals, guestRealmInstalled } from './host-globals';
11
11
  export { VirtualFS } from './virtual-fs';
12
12
  export type { FSNode, MountedTree, Stats, FSWatcher, WatchListener, WatchEventType } from './virtual-fs';
13
- export { Runtime, execute } from './runtime';
13
+ export { Runtime, execute, prepareModuleForImage, preparedModuleKey, PREPARED_MODULES_DIR } from './runtime';
14
14
  export type { Module, RuntimeOptions, RequireFunction } from './runtime';
15
15
  export { createRuntime, WorkerRuntime } from './create-runtime';
16
16
  export type { IRuntime, IExecuteResult, CreateRuntimeOptions, IRuntimeOptions, VFSSnapshot } from './runtime-interface';
package/dist/index.mjs CHANGED
@@ -22704,9 +22704,9 @@ Sha256$1.prototype._hash = function() {
22704
22704
  H.writeInt32BE(this._h, 28);
22705
22705
  return H;
22706
22706
  };
22707
- var sha256 = Sha256$1;
22707
+ var sha256$1 = Sha256$1;
22708
22708
  var inherits$2 = inherits_browserExports;
22709
- var Sha256 = sha256;
22709
+ var Sha256 = sha256$1;
22710
22710
  var Hash$2 = hash$1;
22711
22711
  var Buffer$3 = safeBufferExports.Buffer;
22712
22712
  var W$2 = new Array(64);
@@ -23132,7 +23132,7 @@ var sha384 = Sha384;
23132
23132
  module.exports.sha = sha;
23133
23133
  module.exports.sha1 = sha1;
23134
23134
  module.exports.sha224 = sha224;
23135
- module.exports.sha256 = sha256;
23135
+ module.exports.sha256 = sha256$1;
23136
23136
  module.exports.sha384 = sha384;
23137
23137
  module.exports.sha512 = sha512;
23138
23138
  })(sha_js);
@@ -23186,9 +23186,27 @@ function clean(...arrays) {
23186
23186
  function createView(arr) {
23187
23187
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
23188
23188
  }
23189
+ function rotr(word, shift) {
23190
+ return word << 32 - shift | word >>> shift;
23191
+ }
23189
23192
  function rotl(word, shift) {
23190
23193
  return word << shift | word >>> 32 - shift >>> 0;
23191
23194
  }
23195
+ const hasHexBuiltin = /* @__PURE__ */ (() => (
23196
+ // @ts-ignore
23197
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
23198
+ ))();
23199
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i2) => i2.toString(16).padStart(2, "0"));
23200
+ function bytesToHex(bytes2) {
23201
+ abytes(bytes2);
23202
+ if (hasHexBuiltin)
23203
+ return bytes2.toHex();
23204
+ let hex = "";
23205
+ for (let i2 = 0; i2 < bytes2.length; i2++) {
23206
+ hex += hexes[bytes2[i2]];
23207
+ }
23208
+ return hex;
23209
+ }
23192
23210
  function checkOpts(defaults, opts, title = "opts") {
23193
23211
  aobject(defaults, "defaults");
23194
23212
  if (opts !== void 0)
@@ -23209,9 +23227,17 @@ function createHasher(hashCons, info = {}) {
23209
23227
  Object.assign(hashC, info);
23210
23228
  return Object.freeze(hashC);
23211
23229
  }
23230
+ const oidNist = (suffix) => ({
23231
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
23232
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
23233
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
23234
+ });
23212
23235
  function Chi(a, b, c) {
23213
23236
  return a & b ^ ~a & c;
23214
23237
  }
23238
+ function Maj(a, b, c) {
23239
+ return a & b ^ a & c ^ b & c;
23240
+ }
23215
23241
  class HashMD {
23216
23242
  constructor(blockLen, outputLen, padOffset, isLE) {
23217
23243
  __publicField(this, "blockLen");
@@ -23307,6 +23333,16 @@ class HashMD {
23307
23333
  return this._cloneInto();
23308
23334
  }
23309
23335
  }
23336
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
23337
+ 1779033703,
23338
+ 3144134277,
23339
+ 1013904242,
23340
+ 2773480762,
23341
+ 1359893119,
23342
+ 2600822924,
23343
+ 528734635,
23344
+ 1541459225
23345
+ ]);
23310
23346
  const SHA1_IV = /* @__PURE__ */ Uint32Array.from([
23311
23347
  1732584193,
23312
23348
  4023233417,
@@ -32350,6 +32386,169 @@ function simpleHash(str) {
32350
32386
  }
32351
32387
  return hash2.toString(36);
32352
32388
  }
32389
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
32390
+ 1116352408,
32391
+ 1899447441,
32392
+ 3049323471,
32393
+ 3921009573,
32394
+ 961987163,
32395
+ 1508970993,
32396
+ 2453635748,
32397
+ 2870763221,
32398
+ 3624381080,
32399
+ 310598401,
32400
+ 607225278,
32401
+ 1426881987,
32402
+ 1925078388,
32403
+ 2162078206,
32404
+ 2614888103,
32405
+ 3248222580,
32406
+ 3835390401,
32407
+ 4022224774,
32408
+ 264347078,
32409
+ 604807628,
32410
+ 770255983,
32411
+ 1249150122,
32412
+ 1555081692,
32413
+ 1996064986,
32414
+ 2554220882,
32415
+ 2821834349,
32416
+ 2952996808,
32417
+ 3210313671,
32418
+ 3336571891,
32419
+ 3584528711,
32420
+ 113926993,
32421
+ 338241895,
32422
+ 666307205,
32423
+ 773529912,
32424
+ 1294757372,
32425
+ 1396182291,
32426
+ 1695183700,
32427
+ 1986661051,
32428
+ 2177026350,
32429
+ 2456956037,
32430
+ 2730485921,
32431
+ 2820302411,
32432
+ 3259730800,
32433
+ 3345764771,
32434
+ 3516065817,
32435
+ 3600352804,
32436
+ 4094571909,
32437
+ 275423344,
32438
+ 430227734,
32439
+ 506948616,
32440
+ 659060556,
32441
+ 883997877,
32442
+ 958139571,
32443
+ 1322822218,
32444
+ 1537002063,
32445
+ 1747873779,
32446
+ 1955562222,
32447
+ 2024104815,
32448
+ 2227730452,
32449
+ 2361852424,
32450
+ 2428436474,
32451
+ 2756734187,
32452
+ 3204031479,
32453
+ 3329325298
32454
+ ]);
32455
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
32456
+ class SHA2_32B extends HashMD {
32457
+ constructor(outputLen, IV) {
32458
+ super(64, outputLen, 8, false);
32459
+ // We cannot use array here since array allows indexing by variable
32460
+ // which means optimizer/compiler cannot use registers.
32461
+ // Numeric initializers matter: starting the fields as `undefined` changes
32462
+ // V8's field representation and makes sha256 3x slower (measured).
32463
+ __publicField(this, "A", 0);
32464
+ __publicField(this, "B", 0);
32465
+ __publicField(this, "C", 0);
32466
+ __publicField(this, "D", 0);
32467
+ __publicField(this, "E", 0);
32468
+ __publicField(this, "F", 0);
32469
+ __publicField(this, "G", 0);
32470
+ __publicField(this, "H", 0);
32471
+ this.A = IV[0] | 0;
32472
+ this.B = IV[1] | 0;
32473
+ this.C = IV[2] | 0;
32474
+ this.D = IV[3] | 0;
32475
+ this.E = IV[4] | 0;
32476
+ this.F = IV[5] | 0;
32477
+ this.G = IV[6] | 0;
32478
+ this.H = IV[7] | 0;
32479
+ }
32480
+ get() {
32481
+ const { A, B, C, D, E, F, G, H } = this;
32482
+ return [A, B, C, D, E, F, G, H];
32483
+ }
32484
+ // prettier-ignore
32485
+ set(A, B, C, D, E, F, G, H) {
32486
+ this.A = A | 0;
32487
+ this.B = B | 0;
32488
+ this.C = C | 0;
32489
+ this.D = D | 0;
32490
+ this.E = E | 0;
32491
+ this.F = F | 0;
32492
+ this.G = G | 0;
32493
+ this.H = H | 0;
32494
+ }
32495
+ _cloneInto(to) {
32496
+ (to || (to = new this.constructor())).set(...this.get());
32497
+ return this._cloneIntoMeta(to);
32498
+ }
32499
+ process(view, offset2) {
32500
+ for (let i2 = 0; i2 < 16; i2++, offset2 += 4)
32501
+ SHA256_W[i2] = view.getUint32(offset2, false);
32502
+ for (let i2 = 16; i2 < 64; i2++) {
32503
+ const W15 = SHA256_W[i2 - 15];
32504
+ const W2 = SHA256_W[i2 - 2];
32505
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
32506
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
32507
+ SHA256_W[i2] = s1 + SHA256_W[i2 - 7] + s0 + SHA256_W[i2 - 16] | 0;
32508
+ }
32509
+ let { A, B, C, D, E, F, G, H } = this;
32510
+ for (let i2 = 0; i2 < 64; i2++) {
32511
+ const sigma12 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
32512
+ const T1 = H + sigma12 + Chi(E, F, G) + SHA256_K[i2] + SHA256_W[i2] | 0;
32513
+ const sigma02 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
32514
+ const T2 = sigma02 + Maj(A, B, C) | 0;
32515
+ H = G;
32516
+ G = F;
32517
+ F = E;
32518
+ E = D + T1 | 0;
32519
+ D = C;
32520
+ C = B;
32521
+ B = A;
32522
+ A = T1 + T2 | 0;
32523
+ }
32524
+ A = A + this.A | 0;
32525
+ B = B + this.B | 0;
32526
+ C = C + this.C | 0;
32527
+ D = D + this.D | 0;
32528
+ E = E + this.E | 0;
32529
+ F = F + this.F | 0;
32530
+ G = G + this.G | 0;
32531
+ H = H + this.H | 0;
32532
+ this.set(A, B, C, D, E, F, G, H);
32533
+ }
32534
+ roundClean() {
32535
+ clean(SHA256_W);
32536
+ }
32537
+ destroy() {
32538
+ this.destroyed = true;
32539
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
32540
+ clean(this.buffer);
32541
+ }
32542
+ }
32543
+ class _SHA256 extends SHA2_32B {
32544
+ constructor() {
32545
+ super(32, SHA256_IV);
32546
+ }
32547
+ }
32548
+ const sha256 = /* @__PURE__ */ createHasher(
32549
+ () => new _SHA256(),
32550
+ /* @__PURE__ */ oidNist(1)
32551
+ );
32353
32552
  const fsModule = lazyModule("fs");
32354
32553
  lazyModule("internal/fs/promises");
32355
32554
  function fsModuleFor(process2) {
@@ -37988,6 +38187,33 @@ Object.defineProperty(globalThis, "__substrateEvalSource", {
37988
38187
  configurable: true,
37989
38188
  value: (source) => typeof source === "string" ? __substrateRewriteDynamicImportsInScript(source) : source
37990
38189
  });
38190
+ function __substratePrepareBody(rawCode, resolvedPath, format2, process2) {
38191
+ let code2 = rawCode;
38192
+ if (code2.startsWith("#!")) {
38193
+ code2 = code2.slice(code2.indexOf("\n") + 1);
38194
+ }
38195
+ code2 = __substrateModuleTypes(code2, resolvedPath, format2, process2);
38196
+ const __commonjs = format2 === "commonjs" || format2 === "commonjs-typescript" ? true : format2 === "module" || format2 === "module-typescript" ? false : resolvedPath.endsWith(".cjs") || resolvedPath.endsWith(".cts");
38197
+ if (!__commonjs) {
38198
+ const lowered = transformEsmToCjs(code2, resolvedPath);
38199
+ code2 = lowered === code2 ? code2 : `${__substrateModuleMarker}"use strict";${lowered}`;
38200
+ } else {
38201
+ code2 = transformDynamicImportsRegex(code2);
38202
+ }
38203
+ return code2;
38204
+ }
38205
+ const PREPARED_MODULES_DIR = "/.tabnode/prepared";
38206
+ const PREPARED_MODULES_FORMAT = "tabnode-prepared-1";
38207
+ function preparedModuleKey(rawCode, resolvedPath) {
38208
+ var _a2;
38209
+ const extension = (_a2 = /\.(js|cjs|mjs)$/u.exec(resolvedPath)) == null ? void 0 : _a2[1];
38210
+ if (!extension) return void 0;
38211
+ const kind = extension === "cjs" ? "cjs" : "js";
38212
+ return bytesToHex(sha256(new TextEncoder().encode(`${PREPARED_MODULES_FORMAT}|${kind}|${rawCode}`)));
38213
+ }
38214
+ function prepareModuleForImage(rawCode, resolvedPath) {
38215
+ return __substrateScopeGlobalCalls(__substratePrepareBody(rawCode, resolvedPath, void 0, { execArgv: [], env: {} }));
38216
+ }
37991
38217
  function transformEsmToCjs(code2, filename) {
37992
38218
  const maybeEsm = __substrateHasEsmSyntax(code2);
37993
38219
  if (!maybeEsm) return __substrateRewriteDynamicImportsInScript(code2);
@@ -39026,6 +39252,14 @@ function createRequire(vfs2, fsShim, process2, currentDir, moduleCache, options,
39026
39252
  }
39027
39253
  const rawCode = source === void 0 || source === null ? defaultSource() : String(source);
39028
39254
  const dirname$1 = resolvedPath.startsWith("data:") ? currentDir : dirname(resolvedPath);
39255
+ if (format2 === void 0 && !transformsTypes(process2) && vfs2.existsSync(PREPARED_MODULES_DIR)) {
39256
+ const key = preparedModuleKey(rawCode, resolvedPath);
39257
+ const prepared = key ? `${PREPARED_MODULES_DIR}/${key}` : void 0;
39258
+ if (prepared && vfs2.existsSync(prepared)) {
39259
+ runModuleBody(module, vfs2.readFileSync(prepared, "utf8"), resolvedPath, dirname$1, true);
39260
+ return module;
39261
+ }
39262
+ }
39029
39263
  runModuleBody(module, prepareModuleCode(rawCode, resolvedPath, format2), resolvedPath, dirname$1);
39030
39264
  return module;
39031
39265
  };
@@ -39033,23 +39267,12 @@ function createRequire(vfs2, fsShim, process2, currentDir, moduleCache, options,
39033
39267
  const codeCacheKey = `${resolvedPath}|${format2 ?? ""}|${transformsTypes(process2) ? "transform-types|" : ""}${simpleHash(rawCode)}`;
39034
39268
  let code2 = processedCodeCache == null ? void 0 : processedCodeCache.get(codeCacheKey);
39035
39269
  if (!code2) {
39036
- code2 = rawCode;
39037
- if (code2.startsWith("#!")) {
39038
- code2 = code2.slice(code2.indexOf("\n") + 1);
39039
- }
39040
- code2 = __substrateModuleTypes(code2, resolvedPath, format2, process2);
39041
- const __commonjs = format2 === "commonjs" || format2 === "commonjs-typescript" ? true : format2 === "module" || format2 === "module-typescript" ? false : resolvedPath.endsWith(".cjs") || resolvedPath.endsWith(".cts");
39042
- if (!__commonjs) {
39043
- const lowered = transformEsmToCjs(code2, resolvedPath);
39044
- code2 = lowered === code2 ? code2 : `${__substrateModuleMarker}"use strict";${lowered}`;
39045
- } else {
39046
- code2 = transformDynamicImportsRegex(code2);
39047
- }
39270
+ code2 = __substratePrepareBody(rawCode, resolvedPath, format2, process2);
39048
39271
  processedCodeCache == null ? void 0 : processedCodeCache.set(codeCacheKey, code2);
39049
39272
  }
39050
39273
  return code2;
39051
39274
  };
39052
- const runModuleBody = (module, prepared, resolvedPath, dirname2) => {
39275
+ const runModuleBody = (module, prepared, resolvedPath, dirname2, scoped = false) => {
39053
39276
  let code2 = prepared;
39054
39277
  const moduleRequire = createRequire(
39055
39278
  vfs2,
@@ -39066,7 +39289,7 @@ function createRequire(vfs2, fsShim, process2, currentDir, moduleCache, options,
39066
39289
  try {
39067
39290
  const importMetaUrl = resolvedPath.startsWith("data:") ? resolvedPath : "file://" + resolvedPath;
39068
39291
  const strictBody = code2.startsWith(__substrateModuleMarker);
39069
- code2 = __substrateScopeGlobalCalls(code2);
39292
+ if (!scoped) code2 = __substrateScopeGlobalCalls(code2);
39070
39293
  const wrappedCode = `(function($exports, $require, $module, $filename, $dirname, $process, $console, $importMeta, $dynamicImport, __substrateGuestGlobal, __substrateGuestConstructor) { var exports = $exports; var require = $require; var module = $module; var __filename = $filename; var __dirname = $dirname; var process = $process; var console = $console; var import_meta = $importMeta; var __dynamicImport = $dynamicImport; var document = void 0, window = void 0, location = void 0, self = void 0; var globalThis = __substrateGuestGlobal($process); var global = globalThis; var Buffer = globalThis.Buffer; var queueMicrotask = globalThis.queueMicrotask, atob = globalThis.atob, btoa = globalThis.btoa, structuredClone = globalThis.structuredClone, setTimeout = globalThis.setTimeout, clearTimeout = globalThis.clearTimeout, setInterval = globalThis.setInterval, clearInterval = globalThis.clearInterval; globalThis.process = $process; global.process = $process; with ({ __proto__: null, get navigator() { return globalThis.navigator; }, set navigator(value) { globalThis.navigator = value; }, get Navigator() { return globalThis.Navigator; }, set Navigator(value) { globalThis.Navigator = value; }, get Promise() { return globalThis.Promise; }, set Promise(value) { globalThis.Promise = value; }, get fetch() { return globalThis.fetch; }, set fetch(value) { globalThis.fetch = value; } }) { return (function() {${code2}
39071
39294
  }).call(${strictBody ? "void 0" : "$module.exports"}); }
39072
39295
  })${__substrateSourceURL(resolvedPath)}`;
@@ -39925,7 +40148,7 @@ class WorkerRuntime {
39925
40148
  this.worker = new Worker(
39926
40149
  new URL(
39927
40150
  /* @vite-ignore */
39928
- "/assets/runtime-worker-Bw5ePWPu.js",
40151
+ "/assets/runtime-worker-VIeZbbDr.js",
39929
40152
  import.meta.url
39930
40153
  ),
39931
40154
  { type: "module" }
@@ -42842,6 +43065,7 @@ function createContainer(options) {
42842
43065
  }
42843
43066
  export {
42844
43067
  NativeStreamScope,
43068
+ PREPARED_MODULES_DIR,
42845
43069
  PackageManager,
42846
43070
  Runtime,
42847
43071
  ServerBridge,
@@ -42877,6 +43101,8 @@ export {
42877
43101
  ownerProcessTable,
42878
43102
  path,
42879
43103
  perfHooksShim as perf_hooks,
43104
+ prepareModuleForImage,
43105
+ preparedModuleKey,
42880
43106
  processByPid,
42881
43107
  requestHasStaticBody,
42882
43108
  resetServerBridge,
package/dist/runtime.d.ts CHANGED
@@ -8,6 +8,19 @@ import { VirtualFS } from './virtual-fs';
8
8
  import type { IExecuteResult } from './runtime-interface';
9
9
  import { Process } from './shims/process';
10
10
  export { pendingGuestTimers, stopGuestTimers } from './guest-timers';
11
+ /**
12
+ * Module bodies prepared where the image is built. Parsing a package's files
13
+ * for the passes above is most of a `require` in a tab: 36 of 45 s for
14
+ * playwright-core's, measured in a tab, against 0.9 s under Node on the same
15
+ * machine. The image carries each body under the hash of the file it was made
16
+ * from, in this directory of the tab's filesystem, and the loader takes it in
17
+ * place of the passes when the file it read hashes to one.
18
+ */
19
+ export declare const PREPARED_MODULES_DIR = "/.tabnode/prepared";
20
+ /** The name a prepared body goes under: the hash of the file as read, and how it is compiled. Undefined for a file no body is prepared for. */
21
+ export declare function preparedModuleKey(rawCode: string, resolvedPath: string): string | undefined;
22
+ /** The body the loader would compile for this file, with no load hooks and no type stripping: what the image carries. */
23
+ export declare function prepareModuleForImage(rawCode: string, resolvedPath: string): string;
11
24
  export declare function __substratePendingOf(value: unknown): Promise<void> | undefined;
12
25
  export interface Module {
13
26
  id: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@volter/tabnode",
3
- "version": "0.5.24",
3
+ "version": "0.5.26",
4
4
  "description": "Node's own library, in a browser tab.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/index.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  export { restoreHostGlobals, guestRealmInstalled } from './host-globals';
15
15
  export { VirtualFS } from './virtual-fs';
16
16
  export type { FSNode, MountedTree, Stats, FSWatcher, WatchListener, WatchEventType } from './virtual-fs';
17
- export { Runtime, execute } from './runtime';
17
+ export { Runtime, execute, prepareModuleForImage, preparedModuleKey, PREPARED_MODULES_DIR } from './runtime';
18
18
  export type { Module, RuntimeOptions, RequireFunction } from './runtime';
19
19
  export { createRuntime, WorkerRuntime } from './create-runtime';
20
20
  export type { IRuntime, IExecuteResult, CreateRuntimeOptions, IRuntimeOptions, VFSSnapshot } from './runtime-interface';
package/src/runtime.ts CHANGED
@@ -12,6 +12,8 @@ import { forGuestRealm, installGuestRealm, takeFromHost, defineOnHost, heldWork
12
12
  import type { IRuntime, IExecuteResult, IRuntimeOptions } from './runtime-interface';
13
13
  import type { PackageJson } from './types/package-json';
14
14
  import { simpleHash } from './utils/hash';
15
+ import { sha256 } from '@noble/hashes/sha2.js';
16
+ import { bytesToHex } from '@noble/hashes/utils.js';
15
17
  import { uint8ToBase64, uint8ToHex } from './utils/binary-encoding';
16
18
  import { createFsShim, FsShim } from './shims/fs';
17
19
  import * as pathShim from './shims/path';
@@ -423,6 +425,66 @@ Object.defineProperty(globalThis, "__substrateEvalSource", {
423
425
  configurable: true,
424
426
  value: (source: unknown): unknown => typeof source === "string" ? __substrateRewriteDynamicImportsInScript(source) : source,
425
427
  });
428
+ /** A file's source made a body: shebang stripped, types stripped, ESM lowered, dynamic imports rewritten. */
429
+ function __substratePrepareBody(rawCode: string, resolvedPath: string, format: string | undefined, process: unknown): string {
430
+ let code = rawCode;
431
+
432
+ // Strip shebang line if present (e.g. #!/usr/bin/env node)
433
+ if (code.startsWith('#!')) {
434
+ code = code.slice(code.indexOf('\n') + 1);
435
+ }
436
+
437
+ code = __substrateModuleTypes(code, resolvedPath, format, process);
438
+
439
+ // Transform ESM to CJS if needed (for .mjs files or ESM that wasn't pre-transformed)
440
+ // transformEsmToCjs uses AST to handle import/export, import.meta, and dynamic imports
441
+ // It also handles already-CJS files safely (AST finds no ESM nodes → no-op)
442
+ const __commonjs = format === 'commonjs' || format === 'commonjs-typescript'
443
+ ? true
444
+ : format === 'module' || format === 'module-typescript'
445
+ ? false
446
+ : resolvedPath.endsWith('.cjs') || resolvedPath.endsWith('.cts');
447
+ if (!__commonjs) {
448
+ // An ES module is strict wherever it runs; the mark says so to the
449
+ // compile below, which is otherwise sloppy as a CommonJS body is.
450
+ // The directive shares the body's first line, as Node's one-line
451
+ // wrapper does, so a frame of an ES module counts the file's own lines;
452
+ // on a line of its own it put every frame one line below the file's.
453
+ const lowered = transformEsmToCjs(code, resolvedPath);
454
+ code = lowered === code ? code : `${__substrateModuleMarker}"use strict";${lowered}`;
455
+ } else {
456
+ // A `.cjs` module skips the ESM transform, and with it the rewrite of
457
+ // `import(...)` to the engine's dynamic import, so its
458
+ // `import("fs/promises")` reached the browser's own import and failed on
459
+ // the bare specifier. The dynamic-import rewrite applies to `.cjs` too.
460
+ code = transformDynamicImportsRegex(code);
461
+ }
462
+
463
+ return code;
464
+ }
465
+
466
+ /**
467
+ * Module bodies prepared where the image is built. Parsing a package's files
468
+ * for the passes above is most of a `require` in a tab: 36 of 45 s for
469
+ * playwright-core's, measured in a tab, against 0.9 s under Node on the same
470
+ * machine. The image carries each body under the hash of the file it was made
471
+ * from, in this directory of the tab's filesystem, and the loader takes it in
472
+ * place of the passes when the file it read hashes to one.
473
+ */
474
+ export const PREPARED_MODULES_DIR = '/.tabnode/prepared';
475
+ const PREPARED_MODULES_FORMAT = 'tabnode-prepared-1';
476
+ /** The name a prepared body goes under: the hash of the file as read, and how it is compiled. Undefined for a file no body is prepared for. */
477
+ export function preparedModuleKey(rawCode: string, resolvedPath: string): string | undefined {
478
+ const extension = /\.(js|cjs|mjs)$/u.exec(resolvedPath)?.[1];
479
+ if (!extension) return undefined;
480
+ const kind = extension === 'cjs' ? 'cjs' : 'js';
481
+ return bytesToHex(sha256(new TextEncoder().encode(`${PREPARED_MODULES_FORMAT}|${kind}|${rawCode}`)));
482
+ }
483
+ /** The body the loader would compile for this file, with no load hooks and no type stripping: what the image carries. */
484
+ export function prepareModuleForImage(rawCode: string, resolvedPath: string): string {
485
+ return __substrateScopeGlobalCalls(__substratePrepareBody(rawCode, resolvedPath, undefined, { execArgv: [], env: {} }));
486
+ }
487
+
426
488
  function transformEsmToCjs(code: string, filename: string): string {
427
489
  // Quick check: does the code have any ESM-like patterns?
428
490
  const maybeEsm = __substrateHasEsmSyntax(code);
@@ -1789,6 +1851,14 @@ function createRequire(
1789
1851
  const rawCode = source === undefined || source === null ? defaultSource() : String(source);
1790
1852
  const dirname = resolvedPath.startsWith('data:') ? currentDir : pathShim.dirname(resolvedPath);
1791
1853
 
1854
+ if (format === undefined && !transformsTypes(process as { execArgv?: string[]; env?: Record<string, string> }) && vfs.existsSync(PREPARED_MODULES_DIR)) {
1855
+ const key = preparedModuleKey(rawCode, resolvedPath);
1856
+ const prepared = key ? `${PREPARED_MODULES_DIR}/${key}` : undefined;
1857
+ if (prepared && vfs.existsSync(prepared)) {
1858
+ runModuleBody(module, vfs.readFileSync(prepared, 'utf8'), resolvedPath, dirname, true);
1859
+ return module;
1860
+ }
1861
+ }
1792
1862
  runModuleBody(module, prepareModuleCode(rawCode, resolvedPath, format), resolvedPath, dirname);
1793
1863
  return module;
1794
1864
  };
@@ -1808,45 +1878,10 @@ function createRequire(
1808
1878
  // Use a simple hash of the content for cache key to handle content changes
1809
1879
  const codeCacheKey = `${resolvedPath}|${format ?? ''}|${transformsTypes(process as { execArgv?: string[]; env?: Record<string, string> }) ? 'transform-types|' : ''}${simpleHash(rawCode)}`;
1810
1880
  let code = processedCodeCache?.get(codeCacheKey);
1811
-
1812
1881
  if (!code) {
1813
- code = rawCode;
1814
-
1815
- // Strip shebang line if present (e.g. #!/usr/bin/env node)
1816
- if (code.startsWith('#!')) {
1817
- code = code.slice(code.indexOf('\n') + 1);
1818
- }
1819
-
1820
- code = __substrateModuleTypes(code, resolvedPath, format, process);
1821
-
1822
- // Transform ESM to CJS if needed (for .mjs files or ESM that wasn't pre-transformed)
1823
- // transformEsmToCjs uses AST to handle import/export, import.meta, and dynamic imports
1824
- // It also handles already-CJS files safely (AST finds no ESM nodes → no-op)
1825
- const __commonjs = format === 'commonjs' || format === 'commonjs-typescript'
1826
- ? true
1827
- : format === 'module' || format === 'module-typescript'
1828
- ? false
1829
- : resolvedPath.endsWith('.cjs') || resolvedPath.endsWith('.cts');
1830
- if (!__commonjs) {
1831
- // An ES module is strict wherever it runs; the mark says so to the
1832
- // compile below, which is otherwise sloppy as a CommonJS body is.
1833
- // The directive shares the body's first line, as Node's one-line
1834
- // wrapper does, so a frame of an ES module counts the file's own lines;
1835
- // on a line of its own it put every frame one line below the file's.
1836
- const lowered = transformEsmToCjs(code, resolvedPath);
1837
- code = lowered === code ? code : `${__substrateModuleMarker}"use strict";${lowered}`;
1838
- } else {
1839
- // A `.cjs` module skips the ESM transform, and with it the rewrite of
1840
- // `import(...)` to the engine's dynamic import, so its
1841
- // `import("fs/promises")` reached the browser's own import and failed on
1842
- // the bare specifier. The dynamic-import rewrite applies to `.cjs` too.
1843
- code = transformDynamicImportsRegex(code);
1844
- }
1845
-
1846
- // Cache the processed code
1882
+ code = __substratePrepareBody(rawCode, resolvedPath, format, process);
1847
1883
  processedCodeCache?.set(codeCacheKey, code);
1848
1884
  }
1849
-
1850
1885
  return code;
1851
1886
  };
1852
1887
 
@@ -1858,7 +1893,7 @@ function createRequire(
1858
1893
  * hands the result to it; the engine's own pipeline is what makes the
1859
1894
  * body Node-shaped here.
1860
1895
  */
1861
- const runModuleBody = (module: Module, prepared: string, resolvedPath: string, dirname: string): void => {
1896
+ const runModuleBody = (module: Module, prepared: string, resolvedPath: string, dirname: string, scoped = false): void => {
1862
1897
  let code = prepared;
1863
1898
  // Create require for this module
1864
1899
  const moduleRequire = createRequire(
@@ -1884,7 +1919,7 @@ function createRequire(
1884
1919
  try {
1885
1920
  const importMetaUrl = resolvedPath.startsWith('data:') ? resolvedPath : 'file://' + resolvedPath;
1886
1921
  const strictBody = code.startsWith(__substrateModuleMarker);
1887
- code = __substrateScopeGlobalCalls(code);
1922
+ if (!scoped) code = __substrateScopeGlobalCalls(code);
1888
1923
  // The wrapper is one line and the body begins on it, as Node's
1889
1924
  // `Module.wrap` is one line, so a module's line N is line N of the
1890
1925
  // script V8 compiles and a stack names the module's own lines. The