@innovatorved/code-lab 0.1.5 → 0.1.7

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/src/runtime.ts CHANGED
@@ -810,9 +810,78 @@ function __initVirtualRuntime(rootScope) {
810
810
  crc = CRC32_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
811
811
  }
812
812
  return (crc ^ 0xffffffff) >>> 0;
813
+ },
814
+ // The full Node zlib constant surface. Packages such as axios read these at
815
+ // module-load time (e.g. `zlib.constants.Z_SYNC_FLUSH`) even when they never
816
+ // actually compress, so a missing table breaks the whole module graph.
817
+ constants: {
818
+ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4,
819
+ Z_BLOCK: 5, Z_TREES: 6, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1,
820
+ Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_MEM_ERROR: -4, Z_BUF_ERROR: -5,
821
+ Z_VERSION_ERROR: -6, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9,
822
+ Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4,
823
+ Z_DEFAULT_STRATEGY: 0, ZLIB_VERNUM: 0x1310, DEFLATE: 1, INFLATE: 2, GZIP: 3,
824
+ GUNZIP: 4, DEFLATERAW: 5, INFLATERAW: 6, UNZIP: 7, BROTLI_DECODE: 8,
825
+ BROTLI_ENCODE: 9, Z_MIN_WINDOWBITS: 8, Z_MAX_WINDOWBITS: 15,
826
+ Z_DEFAULT_WINDOWBITS: 15, Z_MIN_CHUNK: 64, Z_MAX_CHUNK: Infinity,
827
+ Z_DEFAULT_CHUNK: 16384, Z_MIN_MEMLEVEL: 1, Z_MAX_MEMLEVEL: 9,
828
+ Z_DEFAULT_MEMLEVEL: 8, Z_MIN_LEVEL: -1, Z_MAX_LEVEL: 9, Z_DEFAULT_LEVEL: -1
813
829
  }
814
830
  };
815
831
 
832
+ // Compression: delegate to the host's real zlib when the runtime is embedded in
833
+ // Node (same process). In a pure browser worker there is no synchronous zlib, so
834
+ // the async APIs use CompressionStream/DecompressionStream and the *Sync variants
835
+ // throw a descriptive error instead of silently corrupting data.
836
+ (() => {
837
+ let hostZlib = null;
838
+ try { hostZlib = (typeof require === 'function') ? require('zlib') : null; } catch (_) { hostZlib = null; }
839
+ const names = [
840
+ 'gzip', 'gunzip', 'deflate', 'inflate', 'deflateRaw', 'inflateRaw', 'unzip',
841
+ 'gzipSync', 'gunzipSync', 'deflateSync', 'inflateSync', 'deflateRawSync', 'inflateRawSync', 'unzipSync',
842
+ 'createGzip', 'createGunzip', 'createDeflate', 'createInflate', 'createDeflateRaw', 'createInflateRaw'
843
+ ];
844
+ if (hostZlib) {
845
+ for (const n of names) {
846
+ if (typeof hostZlib[n] === 'function') VirtualZlib[n] = hostZlib[n].bind(hostZlib);
847
+ }
848
+ return;
849
+ }
850
+ const asyncVariant = (format, kind) => (data, optsOrCb, maybeCb) => {
851
+ const cb = typeof optsOrCb === 'function' ? optsOrCb : (typeof maybeCb === 'function' ? maybeCb : null);
852
+ const p = (async () => {
853
+ if (typeof CompressionStream === 'undefined' || typeof DecompressionStream === 'undefined' || typeof Response === 'undefined') {
854
+ throw new Error('zlib.' + kind + ' is not supported in this environment');
855
+ }
856
+ const decompress = /^(gunzip|unzip|inflate)/.test(kind);
857
+ const stream = decompress ? new DecompressionStream(format) : new CompressionStream(format);
858
+ const writer = stream.writable.getWriter();
859
+ const input = data instanceof Uint8Array ? data : VirtualBuffer.from(data);
860
+ writer.write(input);
861
+ writer.close();
862
+ const ab = await new Response(stream.readable).arrayBuffer();
863
+ return VirtualBuffer.from(ab);
864
+ })();
865
+ if (cb) { p.then((out) => cb(null, out), (err) => cb(err)); return undefined; }
866
+ return p;
867
+ };
868
+ VirtualZlib.gzip = asyncVariant('gzip', 'gzip');
869
+ VirtualZlib.gunzip = asyncVariant('gzip', 'gunzip');
870
+ VirtualZlib.unzip = asyncVariant('gzip', 'unzip');
871
+ VirtualZlib.deflate = asyncVariant('deflate', 'deflate');
872
+ VirtualZlib.inflate = asyncVariant('deflate', 'inflate');
873
+ VirtualZlib.deflateRaw = asyncVariant('deflate-raw', 'deflateRaw');
874
+ VirtualZlib.inflateRaw = asyncVariant('deflate-raw', 'inflateRaw');
875
+ const unsupported = (kind) => () => { throw new Error('zlib.' + kind + ' is not supported in a browser worker (use the async API)'); };
876
+ VirtualZlib.gzipSync = unsupported('gzipSync');
877
+ VirtualZlib.gunzipSync = unsupported('gunzipSync');
878
+ VirtualZlib.deflateSync = unsupported('deflateSync');
879
+ VirtualZlib.inflateSync = unsupported('inflateSync');
880
+ VirtualZlib.deflateRawSync = unsupported('deflateRawSync');
881
+ VirtualZlib.inflateRawSync = unsupported('inflateRawSync');
882
+ VirtualZlib.unzipSync = unsupported('unzipSync');
883
+ })();
884
+
816
885
  // =========================================================================
817
886
  // 4. PATH & OS SHIMS
818
887
  // =========================================================================
@@ -4829,8 +4898,8 @@ function __initVirtualRuntime(rootScope) {
4829
4898
 
4830
4899
  if ((hasESM || isTS) && !keepEsm) {
4831
4900
  // Convert ES module imports (including multi-line `{ ... }`)
4832
- code = code.replace(/\bimport\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, 'const $1 = require($2);');
4833
- code = code.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*\{([\s\S]*?)\}\s+from\s+([^\n;]+);?/gm, (_, defId, specifiers, mod) => {
4901
+ code = code.replace(/\bimport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, 'const $1 = require($2);');
4902
+ code = code.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, defId, specifiers, mod) => {
4834
4903
  const cleaned = specifiers
4835
4904
  .split(',')
4836
4905
  .map((s) => s.trim())
@@ -4841,7 +4910,7 @@ function __initVirtualRuntime(rootScope) {
4841
4910
  return `const ${defId} = (function(m){ return m && m.__esModule ? m.default : m; })(require(${mTrim}));` +
4842
4911
  (cleaned ? ` const { ${cleaned} } = require(${mTrim});` : '');
4843
4912
  });
4844
- code = code.replace(/\bimport\s+\{([\s\S]*?)\}\s+from\s+([^\n;]+);?/gm, (_, specifiers, mod) => {
4913
+ code = code.replace(/\bimport\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, specifiers, mod) => {
4845
4914
  const cleaned = specifiers
4846
4915
  .split(',')
4847
4916
  .map((s) => s.trim())
@@ -4851,18 +4920,24 @@ function __initVirtualRuntime(rootScope) {
4851
4920
  return cleaned ? `const { ${cleaned} } = require(${mod.trim()});` : '';
4852
4921
  });
4853
4922
  code = code.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, 'const $1 = (function(m){ return m && m.__esModule ? m.default : m; })(require($2));');
4854
- code = code.replace(/\bimport\s+(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
4923
+ // Dynamic `import("pkg")` — resolve through the CJS loader instead of the
4924
+ // host's dynamic import, which cannot see the virtual filesystem.
4925
+ code = code.replace(/\bimport\s*\(\s*(\x00__LIT_\d+__\x00)\s*\)/g, 'Promise.resolve().then(() => require($1))');
4926
+ // Side-effect import `import"pkg"` / `import "pkg"`. By this point the
4927
+ // specifier is literal-masked, and minified modules emit no whitespace
4928
+ // between `import` and the string, so `\s*` (not `\s+`) is required.
4929
+ code = code.replace(/\bimport\s*(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
4855
4930
 
4856
4931
  // Convert ES module exports
4857
4932
  const exportedNames = [];
4858
4933
  let defaultExportName = null;
4859
4934
  let hasEsmExport = false;
4860
4935
 
4861
- code = code.replace(/\bexport\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, (_, ns, mod) => {
4936
+ code = code.replace(/\bexport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, (_, ns, mod) => {
4862
4937
  hasEsmExport = true;
4863
4938
  return `exports.${ns} = require(${mod.trim()});`;
4864
4939
  });
4865
- code = code.replace(/\bexport\s+\*\s+from\s+([^\n;]+);?/gm, (_, mod) => {
4940
+ code = code.replace(/\bexport\s*\*\s*from\s*([^\n;]+);?/gm, (_, mod) => {
4866
4941
  hasEsmExport = true;
4867
4942
  return `Object.assign(exports, require(${mod.trim()}));`;
4868
4943
  });
@@ -4885,7 +4960,7 @@ function __initVirtualRuntime(rootScope) {
4885
4960
  exportedNames.push(name);
4886
4961
  return `${kw} ${name}`;
4887
4962
  });
4888
- code = code.replace(/\bexport\s+\{([^}]+)\}\s+from\s+([^\n;]+);?/gm, (_, list, mod) => {
4963
+ code = code.replace(/\bexport\s*\{([^}]+)\}\s*from\s*([^\n;]+);?/gm, (_, list, mod) => {
4889
4964
  hasEsmExport = true;
4890
4965
  const mTrim = mod.trim();
4891
4966
  return list.split(',').map((item) => {
@@ -4897,7 +4972,7 @@ function __initVirtualRuntime(rootScope) {
4897
4972
  return `exports.${exported} = require(${mTrim}).${local};`;
4898
4973
  }).join(' ');
4899
4974
  });
4900
- code = code.replace(/\bexport\s+\{([^}]+)\}\s*;?/gm, (_, list) => {
4975
+ code = code.replace(/\bexport\s*\{([^}]+)\}\s*;?/gm, (_, list) => {
4901
4976
  hasEsmExport = true;
4902
4977
  return list.split(',').map((item) => {
4903
4978
  const trimmed = item.trim();
@@ -4972,9 +5047,9 @@ function __initVirtualRuntime(rootScope) {
4972
5047
  // preloadNpmPackages(files, onProgress) // progress callback (used by the Workbench)
4973
5048
  // preloadNpmPackages(files, existingCache) // package-text cache (Map)
4974
5049
  // preloadNpmPackages(files, existingCache, onProgress)
4975
- const isCacheLike = (v: any) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
4976
- let onProgress: any = null;
4977
- let existingCache: any = _npmPackageCache;
5050
+ const isCacheLike = (v) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
5051
+ let onProgress = null;
5052
+ let existingCache = _npmPackageCache;
4978
5053
  if (typeof secondArg === 'function') onProgress = secondArg;
4979
5054
  else if (isCacheLike(secondArg)) existingCache = secondArg;
4980
5055
  if (typeof thirdArg === 'function') onProgress = onProgress || thirdArg;
@@ -4984,8 +5059,12 @@ function __initVirtualRuntime(rootScope) {
4984
5059
  const builtinSet = new Set([
4985
5060
  'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
4986
5061
  'dns', 'dns/promises', 'string_decoder', 'child_process', 'process',
4987
- 'assert', 'assert/strict', 'events', 'util', 'url', 'querystring',
4988
- 'stream', 'stream/promises', 'test', 'perf_hooks', 'timers', 'timers/promises', 'buffer',
5062
+ 'assert', 'assert/strict', 'events', 'util', 'util/types', 'url', 'querystring',
5063
+ 'stream', 'stream/promises', 'stream/web', 'stream/consumers', 'test', 'perf_hooks',
5064
+ 'timers', 'timers/promises', 'buffer', 'tty', 'tls', 'dgram', 'readline', 'readline/promises',
5065
+ 'async_hooks', 'worker_threads', 'v8', 'vm', 'module', 'constants', 'domain',
5066
+ 'diagnostics_channel', 'http2', 'cluster', 'repl', 'inspector', 'trace_events',
5067
+ 'wasi', 'console',
4989
5068
  'bun', 'bun:test', 'bun:sqlite'
4990
5069
  ]);
4991
5070
 
@@ -5020,14 +5099,14 @@ function __initVirtualRuntime(rootScope) {
5020
5099
  if (typeof fetch === 'function') {
5021
5100
  let pass = 0;
5022
5101
  while (pass < 6) {
5023
- const pending: string[] = [];
5102
+ const pending = [];
5024
5103
  for (const pkg of specs) {
5025
- if (!_npmMetadataCache.has(pkg)) pending.push(pkg as string);
5104
+ if (!_npmMetadataCache.has(pkg)) pending.push(pkg);
5026
5105
  }
5027
5106
  if (pending.length === 0) break;
5028
5107
  pass++;
5029
5108
  await Promise.all(pending.map(async (pkg) => {
5030
- let deps: string[] = [];
5109
+ let deps = [];
5031
5110
  try {
5032
5111
  const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}/package.json`);
5033
5112
  if (res && res.ok) {
@@ -6895,6 +6974,285 @@ function __initVirtualRuntime(rootScope) {
6895
6974
  })();
6896
6975
 
6897
6976
  // Built-in Node module table
6977
+ // ── Additional Node builtin shims ────────────────────────────────────────
6978
+ // Widely-used packages require these at load time (e.g. `debug` requires
6979
+ // `tty`). Without an entry `require('tty')` throws MODULE_NOT_FOUND and the
6980
+ // whole app fails to start. Implementations are deliberately minimal but
6981
+ // shape-compatible; anything that genuinely cannot work in the sandbox
6982
+ // throws an explicit, descriptive error rather than silently misbehaving.
6983
+ const VirtualTty = {
6984
+ isatty() { return false; },
6985
+ ReadStream: class TtyReadStream extends EventEmitter {},
6986
+ WriteStream: class TtyWriteStream extends EventEmitter {
6987
+ constructor(fd) { super(); this.fd = fd; this.columns = 80; this.rows = 24; this.isTTY = false; }
6988
+ getColorDepth() { return 1; }
6989
+ hasColors() { return false; }
6990
+ cursorTo() { return true; }
6991
+ clearLine() { return true; }
6992
+ moveCursor() { return true; }
6993
+ }
6994
+ };
6995
+
6996
+ function makeReadlineInterface() {
6997
+ const iface = new EventEmitter();
6998
+ iface.terminal = false;
6999
+ iface.line = '';
7000
+ iface.cursor = 0;
7001
+ iface.question = (query, cb) => { if (typeof cb === 'function') queueMicrotask(() => cb('')); };
7002
+ iface.prompt = () => {};
7003
+ iface.setPrompt = () => {};
7004
+ iface.getPrompt = () => '';
7005
+ iface.write = () => {};
7006
+ iface.pause = () => iface;
7007
+ iface.resume = () => iface;
7008
+ iface.close = () => { queueMicrotask(() => iface.emit('close')); return iface; };
7009
+ iface[Symbol.asyncIterator] = async function* () {};
7010
+ return iface;
7011
+ }
7012
+ const VirtualReadline = {
7013
+ createInterface: makeReadlineInterface,
7014
+ Interface: class ReadlineInterface extends EventEmitter {},
7015
+ clearLine: () => true,
7016
+ clearScreenDown: () => true,
7017
+ cursorTo: () => true,
7018
+ moveCursor: () => true,
7019
+ emitKeypressEvents: () => {}
7020
+ };
7021
+ const VirtualReadlinePromises = {
7022
+ createInterface: () => {
7023
+ const iface = makeReadlineInterface();
7024
+ iface.question = () => Promise.resolve('');
7025
+ return iface;
7026
+ },
7027
+ Interface: class ReadlinePromisesInterface extends EventEmitter {}
7028
+ };
7029
+
7030
+ const VirtualAsyncHooks = {
7031
+ AsyncLocalStorage: class AsyncLocalStorage {
7032
+ constructor() { this._store = undefined; }
7033
+ getStore() { return this._store; }
7034
+ run(store, fn, ...args) {
7035
+ const prev = this._store;
7036
+ this._store = store;
7037
+ try { return fn(...args); } finally { this._store = prev; }
7038
+ }
7039
+ exit(fn, ...args) {
7040
+ const prev = this._store;
7041
+ this._store = undefined;
7042
+ try { return fn(...args); } finally { this._store = prev; }
7043
+ }
7044
+ enterWith(store) { this._store = store; }
7045
+ disable() { this._store = undefined; }
7046
+ },
7047
+ AsyncResource: class AsyncResource {
7048
+ constructor(type) { this.type = type || 'AsyncResource'; }
7049
+ runInAsyncScope(fn, thisArg, ...args) { return fn.apply(thisArg, args); }
7050
+ emitDestroy() { return this; }
7051
+ asyncId() { return 0; }
7052
+ triggerAsyncId() { return 0; }
7053
+ static bind(fn) { return fn; }
7054
+ },
7055
+ createHook() { return { enable() {}, disable() {} }; },
7056
+ executionAsyncId() { return 0; },
7057
+ triggerAsyncId() { return 0; },
7058
+ executionAsyncResource() { return null; }
7059
+ };
7060
+
7061
+ const VirtualWorkerThreads = {
7062
+ isMainThread: true,
7063
+ threadId: 0,
7064
+ parentPort: null,
7065
+ workerData: null,
7066
+ resourceLimits: {},
7067
+ SHARE_ENV: Symbol('nodejs.worker_threads.SHARE_ENV'),
7068
+ receiveMessageOnPort() { return undefined; },
7069
+ Worker: class Worker extends EventEmitter {
7070
+ constructor(filename) {
7071
+ super();
7072
+ this.threadId = -1;
7073
+ this.filename = filename;
7074
+ queueMicrotask(() => this.emit('error', new Error('worker_threads.Worker is not supported in the virtual runtime.')));
7075
+ }
7076
+ postMessage() {}
7077
+ terminate() { return Promise.resolve(0); }
7078
+ ref() { return this; }
7079
+ unref() { return this; }
7080
+ },
7081
+ MessageChannel: class MessageChannel {},
7082
+ MessagePort: class MessagePort extends EventEmitter {}
7083
+ };
7084
+
7085
+ const VirtualV8 = {
7086
+ serialize(value) { return VirtualBuffer.from(JSON.stringify(value === undefined ? null : value), 'utf8'); },
7087
+ deserialize(buf) { try { return JSON.parse(String(buf)); } catch (_) { return undefined; } },
7088
+ getHeapStatistics() {
7089
+ return {
7090
+ total_heap_size: 0, total_heap_size_executable: 0, total_physical_size: 0,
7091
+ total_available_size: 0, used_heap_size: 0, heap_size_limit: 0,
7092
+ malloced_memory: 0, peak_malloced_memory: 0, does_zap_garbage: 0,
7093
+ number_of_native_contexts: 1, number_of_detached_contexts: 0
7094
+ };
7095
+ },
7096
+ getHeapSpaceStatistics() { return []; },
7097
+ setFlagsFromString() {},
7098
+ cachedDataVersionTag() { return 0; },
7099
+ Serializer: class Serializer {
7100
+ constructor() { this._value = undefined; }
7101
+ writeHeader() {}
7102
+ writeValue(value) { this._value = value; }
7103
+ releaseBuffer() { return VirtualBuffer.from(JSON.stringify(this._value === undefined ? null : this._value), 'utf8'); }
7104
+ },
7105
+ Deserializer: class Deserializer {
7106
+ constructor(buffer) { this._buffer = buffer; }
7107
+ readHeader() { return true; }
7108
+ readValue() { try { return JSON.parse(String(this._buffer)); } catch (_) { return undefined; } }
7109
+ }
7110
+ };
7111
+
7112
+ const VirtualVm = {
7113
+ createContext(sandbox) { return sandbox && typeof sandbox === 'object' ? sandbox : {}; },
7114
+ isContext() { return false; },
7115
+ createScript() { throw new Error('vm code compilation is not supported in the virtual runtime.'); },
7116
+ runInContext() { throw new Error('vm.runInContext is not supported in the virtual runtime.'); },
7117
+ runInNewContext() { throw new Error('vm.runInNewContext is not supported in the virtual runtime.'); },
7118
+ runInThisContext() { throw new Error('vm.runInThisContext is not supported in the virtual runtime.'); },
7119
+ compileFunction() { throw new Error('vm.compileFunction is not supported in the virtual runtime.'); },
7120
+ Script: class Script {
7121
+ runInThisContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
7122
+ runInContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
7123
+ runInNewContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
7124
+ }
7125
+ };
7126
+
7127
+ const VirtualDomain = {
7128
+ create() {
7129
+ const d = new EventEmitter();
7130
+ d.members = [];
7131
+ d.add = () => d;
7132
+ d.remove = () => d;
7133
+ d.bind = (fn) => fn;
7134
+ d.intercept = (fn) => fn;
7135
+ d.run = (fn, ...args) => fn(...args);
7136
+ d.dispose = () => d;
7137
+ return d;
7138
+ },
7139
+ createDomain() { return VirtualDomain.create(); }
7140
+ };
7141
+
7142
+ const VirtualDiagnosticsChannel = {
7143
+ _channels: new Map(),
7144
+ channel(name) {
7145
+ const key = String(name);
7146
+ if (!VirtualDiagnosticsChannel._channels.has(key)) {
7147
+ const ch = new EventEmitter();
7148
+ ch.name = key;
7149
+ ch.hasSubscribers = false;
7150
+ ch.subscribe = () => { ch.hasSubscribers = true; };
7151
+ ch.unsubscribe = () => { ch.hasSubscribers = false; };
7152
+ VirtualDiagnosticsChannel._channels.set(key, ch);
7153
+ }
7154
+ return VirtualDiagnosticsChannel._channels.get(key);
7155
+ },
7156
+ subscribe(name, cb) {
7157
+ const ch = VirtualDiagnosticsChannel.channel(name);
7158
+ ch.subscribe();
7159
+ if (typeof cb === 'function') ch.on('message', cb);
7160
+ },
7161
+ unsubscribe(name) { VirtualDiagnosticsChannel.channel(name).unsubscribe(); },
7162
+ Channel: class Channel extends EventEmitter {}
7163
+ };
7164
+
7165
+ const notSupported = (what) => () => { throw new Error(what + ' is not supported in the virtual runtime.'); };
7166
+ const VirtualTls = {
7167
+ DEFAULT_MIN_VERSION: 'TLSv1.2',
7168
+ DEFAULT_MAX_VERSION: 'TLSv1.3',
7169
+ rootCertificates: [],
7170
+ createSecureContext() { return { context: {} }; },
7171
+ SecureContext: class SecureContext {},
7172
+ TLSSocket: class TLSSocket extends EventEmitter {},
7173
+ Server: class TLSServer extends EventEmitter {},
7174
+ checkServerIdentity() { return undefined; },
7175
+ connect: notSupported('tls.connect'),
7176
+ createServer: notSupported('tls.createServer')
7177
+ };
7178
+ const VirtualDgram = {
7179
+ createSocket(type) {
7180
+ const sock = new EventEmitter();
7181
+ sock.type = type || 'udp4';
7182
+ sock.bind = (...args) => { const cb = args[args.length - 1]; if (typeof cb === 'function') queueMicrotask(cb); return sock; };
7183
+ sock.close = (cb) => { queueMicrotask(() => { sock.emit('close'); if (typeof cb === 'function') cb(); }); return sock; };
7184
+ sock.send = notSupported('dgram.send');
7185
+ sock.address = () => ({ address: '0.0.0.0', family: 'IPv4', port: 0 });
7186
+ sock.setBroadcast = () => sock;
7187
+ sock.setTTL = () => sock;
7188
+ sock.addMembership = () => {};
7189
+ sock.dropMembership = () => {};
7190
+ return sock;
7191
+ },
7192
+ Socket: class Socket extends EventEmitter {}
7193
+ };
7194
+ const VirtualHttp2 = {
7195
+ constants: { NGHTTP2_REFUSED_STREAM: 7, NGHTTP2_CANCEL: 8 },
7196
+ connect: notSupported('http2.connect'),
7197
+ createServer: notSupported('http2.createServer'),
7198
+ createSecureServer: notSupported('http2.createSecureServer')
7199
+ };
7200
+ const VirtualCluster = {
7201
+ isPrimary: true,
7202
+ isMaster: true,
7203
+ isWorker: false,
7204
+ workers: {},
7205
+ fork: notSupported('cluster.fork'),
7206
+ setupPrimary: notSupported('cluster.setupPrimary'),
7207
+ setupMaster: notSupported('cluster.setupMaster'),
7208
+ disconnect: () => {}
7209
+ };
7210
+ const VirtualRepl = { start: notSupported('repl.start') };
7211
+ const VirtualInspector = {
7212
+ open: () => null,
7213
+ close: () => {},
7214
+ url: () => '',
7215
+ Session: class Session { connect() {} disconnect() {} post() {} }
7216
+ };
7217
+ const VirtualTraceEvents = {
7218
+ createTracing: () => ({ enable() {}, disable() {} }),
7219
+ getEnabledCategories: () => ''
7220
+ };
7221
+ const VirtualWasi = {
7222
+ WASI: class WASI { constructor() { throw new Error('wasi is not supported in the virtual runtime.'); } }
7223
+ };
7224
+
7225
+ const VirtualStreamWeb = {
7226
+ ReadableStream: typeof ReadableStream !== 'undefined' ? ReadableStream : undefined,
7227
+ WritableStream: typeof WritableStream !== 'undefined' ? WritableStream : undefined,
7228
+ TransformStream: typeof TransformStream !== 'undefined' ? TransformStream : undefined
7229
+ };
7230
+ async function consumeStream(kind, stream) {
7231
+ const chunks = [];
7232
+ if (stream && typeof stream[Symbol.asyncIterator] === 'function') {
7233
+ for await (const chunk of stream) chunks.push(chunk);
7234
+ } else if (stream && typeof stream.on === 'function') {
7235
+ await new Promise((resolve, reject) => {
7236
+ stream.on('data', (c) => chunks.push(c));
7237
+ stream.on('end', resolve);
7238
+ stream.on('error', reject);
7239
+ });
7240
+ }
7241
+ const bufs = chunks.map((c) => (typeof c === 'string' ? VirtualBuffer.from(c) : VirtualBuffer.from(c)));
7242
+ const buf = VirtualBuffer.concat(bufs);
7243
+ if (kind === 'buffer') return buf;
7244
+ if (kind === 'arrayBuffer') return buf.buffer ? buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) : new ArrayBuffer(0);
7245
+ if (kind === 'text') return buf.toString('utf8');
7246
+ if (kind === 'json') return JSON.parse(buf.toString('utf8'));
7247
+ return buf;
7248
+ }
7249
+ const VirtualStreamConsumers = {
7250
+ text: (s) => consumeStream('text', s),
7251
+ json: (s) => consumeStream('json', s),
7252
+ buffer: (s) => consumeStream('buffer', s),
7253
+ arrayBuffer: (s) => consumeStream('arrayBuffer', s)
7254
+ };
7255
+
6898
7256
  const builtinModules = {
6899
7257
  fs: vfs,
6900
7258
  'node:fs': vfs,
@@ -6955,9 +7313,59 @@ function __initVirtualRuntime(rootScope) {
6955
7313
  bun: BunObj,
6956
7314
  'node:bun': BunObj,
6957
7315
  'bun:test': bunTestModule,
6958
- 'bun:sqlite': { Database: SqliteDatabase }
7316
+ 'bun:sqlite': { Database: SqliteDatabase },
7317
+ tty: VirtualTty,
7318
+ tls: VirtualTls,
7319
+ dgram: VirtualDgram,
7320
+ readline: VirtualReadline,
7321
+ 'readline/promises': VirtualReadlinePromises,
7322
+ async_hooks: VirtualAsyncHooks,
7323
+ worker_threads: VirtualWorkerThreads,
7324
+ v8: VirtualV8,
7325
+ vm: VirtualVm,
7326
+ domain: VirtualDomain,
7327
+ diagnostics_channel: VirtualDiagnosticsChannel,
7328
+ http2: VirtualHttp2,
7329
+ cluster: VirtualCluster,
7330
+ repl: VirtualRepl,
7331
+ inspector: VirtualInspector,
7332
+ trace_events: VirtualTraceEvents,
7333
+ wasi: VirtualWasi,
7334
+ constants: vfs.constants,
7335
+ 'util/types': VirtualUtil.types,
7336
+ 'stream/web': VirtualStreamWeb,
7337
+ 'stream/consumers': VirtualStreamConsumers
6959
7338
  };
6960
7339
 
7340
+ // Auto-alias every builtin under the `node:` prefix (node:tty, node:readline…)
7341
+ // so both spellings resolve identically without hand-maintaining two lists.
7342
+ for (const __builtinName of Object.keys(builtinModules)) {
7343
+ if (!__builtinName.startsWith('node:') && !__builtinName.startsWith('bun:')) {
7344
+ builtinModules['node:' + __builtinName] = builtinModules[__builtinName];
7345
+ }
7346
+ }
7347
+
7348
+ // `module` must reference the now-complete builtin table, so it is attached
7349
+ // after the object literal above.
7350
+ const VirtualModule = {
7351
+ builtinModules: Object.keys(builtinModules),
7352
+ Module: class Module {},
7353
+ isBuiltin(name) { return Object.prototype.hasOwnProperty.call(builtinModules, String(name)); },
7354
+ createRequire(from) {
7355
+ const base = typeof from === 'string' ? from : '/workspace';
7356
+ const dir = /\.(?:js|mjs|cjs|ts|json)$/.test(base) ? VirtualPath.dirname(base) : base;
7357
+ const req = (id) => {
7358
+ if (Object.prototype.hasOwnProperty.call(builtinModules, id)) return builtinModules[id];
7359
+ return loadModule(resolveModulePath(id, dir), false);
7360
+ };
7361
+ req.resolve = (id) => resolveModulePath(id, dir);
7362
+ req.cache = {};
7363
+ return req;
7364
+ }
7365
+ };
7366
+ builtinModules.module = VirtualModule;
7367
+ builtinModules['node:module'] = VirtualModule;
7368
+
6961
7369
  const moduleCache = new Map();
6962
7370
  let mainModule = null;
6963
7371
 
@@ -7294,20 +7702,20 @@ function __initVirtualRuntime(rootScope) {
7294
7702
  }
7295
7703
  }
7296
7704
 
7297
- function raceWithAbort<T = any>(promise: Promise<T>): Promise<T | undefined> {
7298
- if (!promise || typeof (promise as any).then !== 'function') {
7299
- return Promise.resolve(promise as any);
7705
+ function raceWithAbort(promise) {
7706
+ if (!promise || typeof promise.then !== 'function') {
7707
+ return Promise.resolve(promise);
7300
7708
  }
7301
7709
  if (hasExited || isSigintAborted || Boolean(signal && signal.aborted)) {
7302
7710
  if (!hasExited) handleSigint();
7303
- return Promise.resolve(undefined);
7711
+ return Promise.resolve();
7304
7712
  }
7305
7713
 
7306
7714
  // Absorb late rejections after abort to avoid unhandled promise rejection warnings
7307
- (promise as any).catch(() => {});
7715
+ promise.catch(() => {});
7308
7716
 
7309
- return new Promise<T | undefined>((resolve, reject) => {
7310
- let timer: any = null;
7717
+ return new Promise((resolve, reject) => {
7718
+ let timer = null;
7311
7719
  let settled = false;
7312
7720
 
7313
7721
  const cleanup = () => {
@@ -7327,7 +7735,7 @@ function __initVirtualRuntime(rootScope) {
7327
7735
  const onAbort = () => {
7328
7736
  cleanup();
7329
7737
  handleSigint();
7330
- resolve(undefined);
7738
+ resolve();
7331
7739
  };
7332
7740
 
7333
7741
  if (signal) {
@@ -7342,7 +7750,7 @@ function __initVirtualRuntime(rootScope) {
7342
7750
  if (remainingMs > 0 && Number.isFinite(remainingMs)) {
7343
7751
  timer = setTimeout(() => {
7344
7752
  cleanup();
7345
- resolve(undefined);
7753
+ resolve();
7346
7754
  }, remainingMs);
7347
7755
  if (timer && typeof timer.unref === 'function') {
7348
7756
  timer.unref();
@@ -7350,11 +7758,11 @@ function __initVirtualRuntime(rootScope) {
7350
7758
  }
7351
7759
 
7352
7760
  promise.then(
7353
- (val: any) => {
7761
+ (val) => {
7354
7762
  cleanup();
7355
7763
  resolve(val);
7356
7764
  },
7357
- (err: any) => {
7765
+ (err) => {
7358
7766
  cleanup();
7359
7767
  reject(err);
7360
7768
  }
@@ -7587,11 +7995,12 @@ function __workerMessageLoop(workerScope) {
7587
7995
  };
7588
7996
  }
7589
7997
 
7590
- const _hostRuntime: any = __initVirtualRuntime(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global));
7591
-
7592
- _hostRuntime.createWorkerRuntimeSource = function createWorkerRuntimeSource() {
7998
+ function createWorkerRuntimeSource() {
7593
7999
  return `'use strict';\nself.__virtualRuntime = (${__initVirtualRuntime.toString()})(self);\n(${__workerMessageLoop.toString()})(self);\n`;
7594
- };
8000
+ }
8001
+
8002
+ const _hostRuntime = __initVirtualRuntime(typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : global));
8003
+ _hostRuntime.createWorkerRuntimeSource = createWorkerRuntimeSource;
7595
8004
 
7596
8005
  let _cachedWorkerUrl = null;
7597
8006
  let _warmWorker = null;
@@ -7600,7 +8009,7 @@ const _activeWorkerJobs = new Map();
7600
8009
 
7601
8010
  function _ensureWorkerUrl() {
7602
8011
  if (!_cachedWorkerUrl) {
7603
- const blob = new Blob([_hostRuntime.createWorkerRuntimeSource()], { type: 'application/javascript' });
8012
+ const blob = new Blob([createWorkerRuntimeSource()], { type: 'application/javascript' });
7604
8013
  _cachedWorkerUrl = URL.createObjectURL(blob);
7605
8014
  }
7606
8015
  return _cachedWorkerUrl;
@@ -7820,53 +8229,43 @@ if (typeof module !== 'undefined' && module.exports) {
7820
8229
  }
7821
8230
 
7822
8231
 
7823
- export interface RuntimeExecutionResult {
7824
- ok: boolean;
7825
- exitCode: number;
7826
- durationMs: number;
7827
- stdout: string;
7828
- stderr: string;
7829
- testResults: any[];
7830
- fsSnapshot: any[];
7831
- httpTrace: any[];
7832
- error?: { message: string; stack?: string };
7833
- outputTruncated?: boolean;
7834
- replValue?: any;
7835
- cancelled?: boolean;
7836
- testSummary?: {
7837
- total: number;
7838
- passed: number;
7839
- failed: number;
7840
- };
7841
- }
7842
-
7843
- export const VirtualBuffer: any = _hostRuntime.VirtualBuffer;
7844
- export const VirtualCrypto: any = _hostRuntime.VirtualCrypto;
7845
- export const VirtualZlib: any = _hostRuntime.VirtualZlib;
7846
- export const VirtualPath: any = _hostRuntime.VirtualPath;
7847
- export const VirtualOs: any = _hostRuntime.VirtualOs;
7848
- export const VirtualAssert: any = _hostRuntime.VirtualAssert;
7849
- export const EventEmitter: any = _hostRuntime.EventEmitter;
7850
- export const VirtualUtil: any = _hostRuntime.VirtualUtil;
7851
- export const VirtualUrl: any = _hostRuntime.VirtualUrl;
7852
- export const VirtualQuerystring: any = _hostRuntime.VirtualQuerystring;
7853
- export const VirtualStream: any = _hostRuntime.VirtualStream;
7854
- export const VirtualStreamPromises: any = _hostRuntime.VirtualStreamPromises;
7855
- export const VirtualStringDecoder: any = _hostRuntime.VirtualStringDecoder;
7856
- export const VirtualDns: any = _hostRuntime.VirtualDns;
7857
- export const createVirtualFs: (options?: any) => any = _hostRuntime.createVirtualFs;
7858
- export const createVirtualHttp: (portTable?: any, vfs?: any) => any = _hostRuntime.createVirtualHttp;
7859
- export const createVirtualNet: (portTable?: any) => any = _hostRuntime.createVirtualNet;
7860
- export const transpileTS: (code: string, filename?: string) => string = _hostRuntime.transpileTS;
8232
+ // ── TypeScript module surface (stripped from browser bundles) ──────────────
8233
+ // The implementation above is a UMD script that attaches itself to the global
8234
+ // object. These aliases give TypeScript consumers named exports without
8235
+ // duplicating the implementation. tools/bundle.js removes this footer before
8236
+ // concatenating the script into the browser bundle.
8237
+ const _runtimeApi: any = (typeof globalThis !== 'undefined' ? (globalThis as any).CodeLabRuntime : undefined)
8238
+ || (typeof module !== 'undefined' && module.exports ? module.exports : {});
8239
+
8240
+ export const VirtualBuffer: any = _runtimeApi.VirtualBuffer;
8241
+ export const VirtualCrypto: any = _runtimeApi.VirtualCrypto;
8242
+ export const VirtualZlib: any = _runtimeApi.VirtualZlib;
8243
+ export const VirtualPath: any = _runtimeApi.VirtualPath;
8244
+ export const VirtualOs: any = _runtimeApi.VirtualOs;
8245
+ export const VirtualAssert: any = _runtimeApi.VirtualAssert;
8246
+ export const EventEmitter: any = _runtimeApi.EventEmitter;
8247
+ export const VirtualUtil: any = _runtimeApi.VirtualUtil;
8248
+ export const VirtualUrl: any = _runtimeApi.VirtualUrl;
8249
+ export const VirtualQuerystring: any = _runtimeApi.VirtualQuerystring;
8250
+ export const VirtualStream: any = _runtimeApi.VirtualStream;
8251
+ export const VirtualStreamPromises: any = _runtimeApi.VirtualStreamPromises;
8252
+ export const VirtualStringDecoder: any = _runtimeApi.VirtualStringDecoder;
8253
+ export const VirtualDns: any = _runtimeApi.VirtualDns;
8254
+ export const createVirtualFs: (options?: any) => any = _runtimeApi.createVirtualFs;
8255
+ export const createVirtualHttp: (portTable?: any, vfs?: any) => any = _runtimeApi.createVirtualHttp;
8256
+ export const createVirtualNet: (portTable?: any) => any = _runtimeApi.createVirtualNet;
8257
+ export const transpileTS: (code: string, filename?: string) => string = _runtimeApi.transpileTS;
8258
+ export const transpileForBrowser: (source: string, filename?: string) => string = _runtimeApi.transpileForBrowser;
7861
8259
  export const preloadNpmPackages: (
7862
8260
  files?: Record<string, any>,
7863
8261
  onProgressOrCache?: ((pkg: string) => void) | Map<string, string>,
7864
8262
  onProgress?: (pkg: string) => void
7865
- ) => Promise<Record<string, string>> = _hostRuntime.preloadNpmPackages;
7866
- export const createVirtualPortTable: () => any = _hostRuntime.createVirtualPortTable;
7867
- export const executeInVirtualRuntime: (options?: any) => Promise<RuntimeExecutionResult> = _hostRuntime.executeInVirtualRuntime;
7868
- export const createWorkerRuntimeSource: () => string = _hostRuntime.createWorkerRuntimeSource;
7869
- export const cancelWorkerExecution: (reason?: string, instanceId?: string) => boolean = _hostRuntime.cancelWorkerExecution;
7870
- export const executeInWorker: (options?: any) => Promise<RuntimeExecutionResult> = _hostRuntime.executeInWorker;
7871
-
7872
- export default _hostRuntime;
8263
+ ) => Promise<Record<string, string>> = _runtimeApi.preloadNpmPackages;
8264
+ export const createVirtualPortTable: () => any = _runtimeApi.createVirtualPortTable;
8265
+ export const executeInVirtualRuntime: (options?: any) => Promise<any> = _runtimeApi.executeInVirtualRuntime;
8266
+ const createWorkerRuntimeSourceExport: () => string = _runtimeApi.createWorkerRuntimeSource;
8267
+ export { createWorkerRuntimeSourceExport as createWorkerRuntimeSource };
8268
+ export const cancelWorkerExecution: (reason?: string, instanceId?: string) => boolean = _runtimeApi.cancelWorkerExecution;
8269
+ export const executeInWorker: (options?: any) => Promise<any> = _runtimeApi.executeInWorker;
8270
+
8271
+ export default _runtimeApi;