@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/dist/code-lab.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v2.0.0 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.1.7 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
@@ -19,6 +19,7 @@
19
19
 
20
20
  // --- Module 1: Runtime Engine ---
21
21
  (function () {
22
+ // @ts-nocheck
22
23
  'use strict';
23
24
  if (typeof globalThis !== 'undefined' && typeof globalThis.Bun === 'undefined') {
24
25
  globalThis.Bun = { version: '1.1.20' };
@@ -830,9 +831,78 @@ function __initVirtualRuntime(rootScope) {
830
831
  crc = CRC32_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
831
832
  }
832
833
  return (crc ^ 0xffffffff) >>> 0;
834
+ },
835
+ // The full Node zlib constant surface. Packages such as axios read these at
836
+ // module-load time (e.g. `zlib.constants.Z_SYNC_FLUSH`) even when they never
837
+ // actually compress, so a missing table breaks the whole module graph.
838
+ constants: {
839
+ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4,
840
+ Z_BLOCK: 5, Z_TREES: 6, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1,
841
+ Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_MEM_ERROR: -4, Z_BUF_ERROR: -5,
842
+ Z_VERSION_ERROR: -6, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9,
843
+ Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4,
844
+ Z_DEFAULT_STRATEGY: 0, ZLIB_VERNUM: 0x1310, DEFLATE: 1, INFLATE: 2, GZIP: 3,
845
+ GUNZIP: 4, DEFLATERAW: 5, INFLATERAW: 6, UNZIP: 7, BROTLI_DECODE: 8,
846
+ BROTLI_ENCODE: 9, Z_MIN_WINDOWBITS: 8, Z_MAX_WINDOWBITS: 15,
847
+ Z_DEFAULT_WINDOWBITS: 15, Z_MIN_CHUNK: 64, Z_MAX_CHUNK: Infinity,
848
+ Z_DEFAULT_CHUNK: 16384, Z_MIN_MEMLEVEL: 1, Z_MAX_MEMLEVEL: 9,
849
+ Z_DEFAULT_MEMLEVEL: 8, Z_MIN_LEVEL: -1, Z_MAX_LEVEL: 9, Z_DEFAULT_LEVEL: -1
833
850
  }
834
851
  };
835
852
 
853
+ // Compression: delegate to the host's real zlib when the runtime is embedded in
854
+ // Node (same process). In a pure browser worker there is no synchronous zlib, so
855
+ // the async APIs use CompressionStream/DecompressionStream and the *Sync variants
856
+ // throw a descriptive error instead of silently corrupting data.
857
+ (() => {
858
+ let hostZlib = null;
859
+ try { hostZlib = (typeof require === 'function') ? require('zlib') : null; } catch (_) { hostZlib = null; }
860
+ const names = [
861
+ 'gzip', 'gunzip', 'deflate', 'inflate', 'deflateRaw', 'inflateRaw', 'unzip',
862
+ 'gzipSync', 'gunzipSync', 'deflateSync', 'inflateSync', 'deflateRawSync', 'inflateRawSync', 'unzipSync',
863
+ 'createGzip', 'createGunzip', 'createDeflate', 'createInflate', 'createDeflateRaw', 'createInflateRaw'
864
+ ];
865
+ if (hostZlib) {
866
+ for (const n of names) {
867
+ if (typeof hostZlib[n] === 'function') VirtualZlib[n] = hostZlib[n].bind(hostZlib);
868
+ }
869
+ return;
870
+ }
871
+ const asyncVariant = (format, kind) => (data, optsOrCb, maybeCb) => {
872
+ const cb = typeof optsOrCb === 'function' ? optsOrCb : (typeof maybeCb === 'function' ? maybeCb : null);
873
+ const p = (async () => {
874
+ if (typeof CompressionStream === 'undefined' || typeof DecompressionStream === 'undefined' || typeof Response === 'undefined') {
875
+ throw new Error('zlib.' + kind + ' is not supported in this environment');
876
+ }
877
+ const decompress = /^(gunzip|unzip|inflate)/.test(kind);
878
+ const stream = decompress ? new DecompressionStream(format) : new CompressionStream(format);
879
+ const writer = stream.writable.getWriter();
880
+ const input = data instanceof Uint8Array ? data : VirtualBuffer.from(data);
881
+ writer.write(input);
882
+ writer.close();
883
+ const ab = await new Response(stream.readable).arrayBuffer();
884
+ return VirtualBuffer.from(ab);
885
+ })();
886
+ if (cb) { p.then((out) => cb(null, out), (err) => cb(err)); return undefined; }
887
+ return p;
888
+ };
889
+ VirtualZlib.gzip = asyncVariant('gzip', 'gzip');
890
+ VirtualZlib.gunzip = asyncVariant('gzip', 'gunzip');
891
+ VirtualZlib.unzip = asyncVariant('gzip', 'unzip');
892
+ VirtualZlib.deflate = asyncVariant('deflate', 'deflate');
893
+ VirtualZlib.inflate = asyncVariant('deflate', 'inflate');
894
+ VirtualZlib.deflateRaw = asyncVariant('deflate-raw', 'deflateRaw');
895
+ VirtualZlib.inflateRaw = asyncVariant('deflate-raw', 'inflateRaw');
896
+ const unsupported = (kind) => () => { throw new Error('zlib.' + kind + ' is not supported in a browser worker (use the async API)'); };
897
+ VirtualZlib.gzipSync = unsupported('gzipSync');
898
+ VirtualZlib.gunzipSync = unsupported('gunzipSync');
899
+ VirtualZlib.deflateSync = unsupported('deflateSync');
900
+ VirtualZlib.inflateSync = unsupported('inflateSync');
901
+ VirtualZlib.deflateRawSync = unsupported('deflateRawSync');
902
+ VirtualZlib.inflateRawSync = unsupported('inflateRawSync');
903
+ VirtualZlib.unzipSync = unsupported('unzipSync');
904
+ })();
905
+
836
906
  // =========================================================================
837
907
  // 4. PATH & OS SHIMS
838
908
  // =========================================================================
@@ -4871,7 +4941,13 @@ function __initVirtualRuntime(rootScope) {
4871
4941
  return cleaned ? `const { ${cleaned} } = require(${mod.trim()});` : '';
4872
4942
  });
4873
4943
  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));');
4874
- code = code.replace(/\bimport\s+(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
4944
+ // Dynamic `import("pkg")` — resolve through the CJS loader instead of the
4945
+ // host's dynamic import, which cannot see the virtual filesystem.
4946
+ code = code.replace(/\bimport\s*\(\s*(\x00__LIT_\d+__\x00)\s*\)/g, 'Promise.resolve().then(() => require($1))');
4947
+ // Side-effect import `import"pkg"` / `import "pkg"`. By this point the
4948
+ // specifier is literal-masked, and minified modules emit no whitespace
4949
+ // between `import` and the string, so `\s*` (not `\s+`) is required.
4950
+ code = code.replace(/\bimport\s*(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
4875
4951
 
4876
4952
  // Convert ES module exports
4877
4953
  const exportedNames = [];
@@ -5004,8 +5080,12 @@ function __initVirtualRuntime(rootScope) {
5004
5080
  const builtinSet = new Set([
5005
5081
  'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
5006
5082
  'dns', 'dns/promises', 'string_decoder', 'child_process', 'process',
5007
- 'assert', 'assert/strict', 'events', 'util', 'url', 'querystring',
5008
- 'stream', 'stream/promises', 'test', 'perf_hooks', 'timers', 'timers/promises', 'buffer',
5083
+ 'assert', 'assert/strict', 'events', 'util', 'util/types', 'url', 'querystring',
5084
+ 'stream', 'stream/promises', 'stream/web', 'stream/consumers', 'test', 'perf_hooks',
5085
+ 'timers', 'timers/promises', 'buffer', 'tty', 'tls', 'dgram', 'readline', 'readline/promises',
5086
+ 'async_hooks', 'worker_threads', 'v8', 'vm', 'module', 'constants', 'domain',
5087
+ 'diagnostics_channel', 'http2', 'cluster', 'repl', 'inspector', 'trace_events',
5088
+ 'wasi', 'console',
5009
5089
  'bun', 'bun:test', 'bun:sqlite'
5010
5090
  ]);
5011
5091
 
@@ -6915,6 +6995,285 @@ function __initVirtualRuntime(rootScope) {
6915
6995
  })();
6916
6996
 
6917
6997
  // Built-in Node module table
6998
+ // ── Additional Node builtin shims ────────────────────────────────────────
6999
+ // Widely-used packages require these at load time (e.g. `debug` requires
7000
+ // `tty`). Without an entry `require('tty')` throws MODULE_NOT_FOUND and the
7001
+ // whole app fails to start. Implementations are deliberately minimal but
7002
+ // shape-compatible; anything that genuinely cannot work in the sandbox
7003
+ // throws an explicit, descriptive error rather than silently misbehaving.
7004
+ const VirtualTty = {
7005
+ isatty() { return false; },
7006
+ ReadStream: class TtyReadStream extends EventEmitter {},
7007
+ WriteStream: class TtyWriteStream extends EventEmitter {
7008
+ constructor(fd) { super(); this.fd = fd; this.columns = 80; this.rows = 24; this.isTTY = false; }
7009
+ getColorDepth() { return 1; }
7010
+ hasColors() { return false; }
7011
+ cursorTo() { return true; }
7012
+ clearLine() { return true; }
7013
+ moveCursor() { return true; }
7014
+ }
7015
+ };
7016
+
7017
+ function makeReadlineInterface() {
7018
+ const iface = new EventEmitter();
7019
+ iface.terminal = false;
7020
+ iface.line = '';
7021
+ iface.cursor = 0;
7022
+ iface.question = (query, cb) => { if (typeof cb === 'function') queueMicrotask(() => cb('')); };
7023
+ iface.prompt = () => {};
7024
+ iface.setPrompt = () => {};
7025
+ iface.getPrompt = () => '';
7026
+ iface.write = () => {};
7027
+ iface.pause = () => iface;
7028
+ iface.resume = () => iface;
7029
+ iface.close = () => { queueMicrotask(() => iface.emit('close')); return iface; };
7030
+ iface[Symbol.asyncIterator] = async function* () {};
7031
+ return iface;
7032
+ }
7033
+ const VirtualReadline = {
7034
+ createInterface: makeReadlineInterface,
7035
+ Interface: class ReadlineInterface extends EventEmitter {},
7036
+ clearLine: () => true,
7037
+ clearScreenDown: () => true,
7038
+ cursorTo: () => true,
7039
+ moveCursor: () => true,
7040
+ emitKeypressEvents: () => {}
7041
+ };
7042
+ const VirtualReadlinePromises = {
7043
+ createInterface: () => {
7044
+ const iface = makeReadlineInterface();
7045
+ iface.question = () => Promise.resolve('');
7046
+ return iface;
7047
+ },
7048
+ Interface: class ReadlinePromisesInterface extends EventEmitter {}
7049
+ };
7050
+
7051
+ const VirtualAsyncHooks = {
7052
+ AsyncLocalStorage: class AsyncLocalStorage {
7053
+ constructor() { this._store = undefined; }
7054
+ getStore() { return this._store; }
7055
+ run(store, fn, ...args) {
7056
+ const prev = this._store;
7057
+ this._store = store;
7058
+ try { return fn(...args); } finally { this._store = prev; }
7059
+ }
7060
+ exit(fn, ...args) {
7061
+ const prev = this._store;
7062
+ this._store = undefined;
7063
+ try { return fn(...args); } finally { this._store = prev; }
7064
+ }
7065
+ enterWith(store) { this._store = store; }
7066
+ disable() { this._store = undefined; }
7067
+ },
7068
+ AsyncResource: class AsyncResource {
7069
+ constructor(type) { this.type = type || 'AsyncResource'; }
7070
+ runInAsyncScope(fn, thisArg, ...args) { return fn.apply(thisArg, args); }
7071
+ emitDestroy() { return this; }
7072
+ asyncId() { return 0; }
7073
+ triggerAsyncId() { return 0; }
7074
+ static bind(fn) { return fn; }
7075
+ },
7076
+ createHook() { return { enable() {}, disable() {} }; },
7077
+ executionAsyncId() { return 0; },
7078
+ triggerAsyncId() { return 0; },
7079
+ executionAsyncResource() { return null; }
7080
+ };
7081
+
7082
+ const VirtualWorkerThreads = {
7083
+ isMainThread: true,
7084
+ threadId: 0,
7085
+ parentPort: null,
7086
+ workerData: null,
7087
+ resourceLimits: {},
7088
+ SHARE_ENV: Symbol('nodejs.worker_threads.SHARE_ENV'),
7089
+ receiveMessageOnPort() { return undefined; },
7090
+ Worker: class Worker extends EventEmitter {
7091
+ constructor(filename) {
7092
+ super();
7093
+ this.threadId = -1;
7094
+ this.filename = filename;
7095
+ queueMicrotask(() => this.emit('error', new Error('worker_threads.Worker is not supported in the virtual runtime.')));
7096
+ }
7097
+ postMessage() {}
7098
+ terminate() { return Promise.resolve(0); }
7099
+ ref() { return this; }
7100
+ unref() { return this; }
7101
+ },
7102
+ MessageChannel: class MessageChannel {},
7103
+ MessagePort: class MessagePort extends EventEmitter {}
7104
+ };
7105
+
7106
+ const VirtualV8 = {
7107
+ serialize(value) { return VirtualBuffer.from(JSON.stringify(value === undefined ? null : value), 'utf8'); },
7108
+ deserialize(buf) { try { return JSON.parse(String(buf)); } catch (_) { return undefined; } },
7109
+ getHeapStatistics() {
7110
+ return {
7111
+ total_heap_size: 0, total_heap_size_executable: 0, total_physical_size: 0,
7112
+ total_available_size: 0, used_heap_size: 0, heap_size_limit: 0,
7113
+ malloced_memory: 0, peak_malloced_memory: 0, does_zap_garbage: 0,
7114
+ number_of_native_contexts: 1, number_of_detached_contexts: 0
7115
+ };
7116
+ },
7117
+ getHeapSpaceStatistics() { return []; },
7118
+ setFlagsFromString() {},
7119
+ cachedDataVersionTag() { return 0; },
7120
+ Serializer: class Serializer {
7121
+ constructor() { this._value = undefined; }
7122
+ writeHeader() {}
7123
+ writeValue(value) { this._value = value; }
7124
+ releaseBuffer() { return VirtualBuffer.from(JSON.stringify(this._value === undefined ? null : this._value), 'utf8'); }
7125
+ },
7126
+ Deserializer: class Deserializer {
7127
+ constructor(buffer) { this._buffer = buffer; }
7128
+ readHeader() { return true; }
7129
+ readValue() { try { return JSON.parse(String(this._buffer)); } catch (_) { return undefined; } }
7130
+ }
7131
+ };
7132
+
7133
+ const VirtualVm = {
7134
+ createContext(sandbox) { return sandbox && typeof sandbox === 'object' ? sandbox : {}; },
7135
+ isContext() { return false; },
7136
+ createScript() { throw new Error('vm code compilation is not supported in the virtual runtime.'); },
7137
+ runInContext() { throw new Error('vm.runInContext is not supported in the virtual runtime.'); },
7138
+ runInNewContext() { throw new Error('vm.runInNewContext is not supported in the virtual runtime.'); },
7139
+ runInThisContext() { throw new Error('vm.runInThisContext is not supported in the virtual runtime.'); },
7140
+ compileFunction() { throw new Error('vm.compileFunction is not supported in the virtual runtime.'); },
7141
+ Script: class Script {
7142
+ runInThisContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
7143
+ runInContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
7144
+ runInNewContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
7145
+ }
7146
+ };
7147
+
7148
+ const VirtualDomain = {
7149
+ create() {
7150
+ const d = new EventEmitter();
7151
+ d.members = [];
7152
+ d.add = () => d;
7153
+ d.remove = () => d;
7154
+ d.bind = (fn) => fn;
7155
+ d.intercept = (fn) => fn;
7156
+ d.run = (fn, ...args) => fn(...args);
7157
+ d.dispose = () => d;
7158
+ return d;
7159
+ },
7160
+ createDomain() { return VirtualDomain.create(); }
7161
+ };
7162
+
7163
+ const VirtualDiagnosticsChannel = {
7164
+ _channels: new Map(),
7165
+ channel(name) {
7166
+ const key = String(name);
7167
+ if (!VirtualDiagnosticsChannel._channels.has(key)) {
7168
+ const ch = new EventEmitter();
7169
+ ch.name = key;
7170
+ ch.hasSubscribers = false;
7171
+ ch.subscribe = () => { ch.hasSubscribers = true; };
7172
+ ch.unsubscribe = () => { ch.hasSubscribers = false; };
7173
+ VirtualDiagnosticsChannel._channels.set(key, ch);
7174
+ }
7175
+ return VirtualDiagnosticsChannel._channels.get(key);
7176
+ },
7177
+ subscribe(name, cb) {
7178
+ const ch = VirtualDiagnosticsChannel.channel(name);
7179
+ ch.subscribe();
7180
+ if (typeof cb === 'function') ch.on('message', cb);
7181
+ },
7182
+ unsubscribe(name) { VirtualDiagnosticsChannel.channel(name).unsubscribe(); },
7183
+ Channel: class Channel extends EventEmitter {}
7184
+ };
7185
+
7186
+ const notSupported = (what) => () => { throw new Error(what + ' is not supported in the virtual runtime.'); };
7187
+ const VirtualTls = {
7188
+ DEFAULT_MIN_VERSION: 'TLSv1.2',
7189
+ DEFAULT_MAX_VERSION: 'TLSv1.3',
7190
+ rootCertificates: [],
7191
+ createSecureContext() { return { context: {} }; },
7192
+ SecureContext: class SecureContext {},
7193
+ TLSSocket: class TLSSocket extends EventEmitter {},
7194
+ Server: class TLSServer extends EventEmitter {},
7195
+ checkServerIdentity() { return undefined; },
7196
+ connect: notSupported('tls.connect'),
7197
+ createServer: notSupported('tls.createServer')
7198
+ };
7199
+ const VirtualDgram = {
7200
+ createSocket(type) {
7201
+ const sock = new EventEmitter();
7202
+ sock.type = type || 'udp4';
7203
+ sock.bind = (...args) => { const cb = args[args.length - 1]; if (typeof cb === 'function') queueMicrotask(cb); return sock; };
7204
+ sock.close = (cb) => { queueMicrotask(() => { sock.emit('close'); if (typeof cb === 'function') cb(); }); return sock; };
7205
+ sock.send = notSupported('dgram.send');
7206
+ sock.address = () => ({ address: '0.0.0.0', family: 'IPv4', port: 0 });
7207
+ sock.setBroadcast = () => sock;
7208
+ sock.setTTL = () => sock;
7209
+ sock.addMembership = () => {};
7210
+ sock.dropMembership = () => {};
7211
+ return sock;
7212
+ },
7213
+ Socket: class Socket extends EventEmitter {}
7214
+ };
7215
+ const VirtualHttp2 = {
7216
+ constants: { NGHTTP2_REFUSED_STREAM: 7, NGHTTP2_CANCEL: 8 },
7217
+ connect: notSupported('http2.connect'),
7218
+ createServer: notSupported('http2.createServer'),
7219
+ createSecureServer: notSupported('http2.createSecureServer')
7220
+ };
7221
+ const VirtualCluster = {
7222
+ isPrimary: true,
7223
+ isMaster: true,
7224
+ isWorker: false,
7225
+ workers: {},
7226
+ fork: notSupported('cluster.fork'),
7227
+ setupPrimary: notSupported('cluster.setupPrimary'),
7228
+ setupMaster: notSupported('cluster.setupMaster'),
7229
+ disconnect: () => {}
7230
+ };
7231
+ const VirtualRepl = { start: notSupported('repl.start') };
7232
+ const VirtualInspector = {
7233
+ open: () => null,
7234
+ close: () => {},
7235
+ url: () => '',
7236
+ Session: class Session { connect() {} disconnect() {} post() {} }
7237
+ };
7238
+ const VirtualTraceEvents = {
7239
+ createTracing: () => ({ enable() {}, disable() {} }),
7240
+ getEnabledCategories: () => ''
7241
+ };
7242
+ const VirtualWasi = {
7243
+ WASI: class WASI { constructor() { throw new Error('wasi is not supported in the virtual runtime.'); } }
7244
+ };
7245
+
7246
+ const VirtualStreamWeb = {
7247
+ ReadableStream: typeof ReadableStream !== 'undefined' ? ReadableStream : undefined,
7248
+ WritableStream: typeof WritableStream !== 'undefined' ? WritableStream : undefined,
7249
+ TransformStream: typeof TransformStream !== 'undefined' ? TransformStream : undefined
7250
+ };
7251
+ async function consumeStream(kind, stream) {
7252
+ const chunks = [];
7253
+ if (stream && typeof stream[Symbol.asyncIterator] === 'function') {
7254
+ for await (const chunk of stream) chunks.push(chunk);
7255
+ } else if (stream && typeof stream.on === 'function') {
7256
+ await new Promise((resolve, reject) => {
7257
+ stream.on('data', (c) => chunks.push(c));
7258
+ stream.on('end', resolve);
7259
+ stream.on('error', reject);
7260
+ });
7261
+ }
7262
+ const bufs = chunks.map((c) => (typeof c === 'string' ? VirtualBuffer.from(c) : VirtualBuffer.from(c)));
7263
+ const buf = VirtualBuffer.concat(bufs);
7264
+ if (kind === 'buffer') return buf;
7265
+ if (kind === 'arrayBuffer') return buf.buffer ? buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) : new ArrayBuffer(0);
7266
+ if (kind === 'text') return buf.toString('utf8');
7267
+ if (kind === 'json') return JSON.parse(buf.toString('utf8'));
7268
+ return buf;
7269
+ }
7270
+ const VirtualStreamConsumers = {
7271
+ text: (s) => consumeStream('text', s),
7272
+ json: (s) => consumeStream('json', s),
7273
+ buffer: (s) => consumeStream('buffer', s),
7274
+ arrayBuffer: (s) => consumeStream('arrayBuffer', s)
7275
+ };
7276
+
6918
7277
  const builtinModules = {
6919
7278
  fs: vfs,
6920
7279
  'node:fs': vfs,
@@ -6975,9 +7334,59 @@ function __initVirtualRuntime(rootScope) {
6975
7334
  bun: BunObj,
6976
7335
  'node:bun': BunObj,
6977
7336
  'bun:test': bunTestModule,
6978
- 'bun:sqlite': { Database: SqliteDatabase }
7337
+ 'bun:sqlite': { Database: SqliteDatabase },
7338
+ tty: VirtualTty,
7339
+ tls: VirtualTls,
7340
+ dgram: VirtualDgram,
7341
+ readline: VirtualReadline,
7342
+ 'readline/promises': VirtualReadlinePromises,
7343
+ async_hooks: VirtualAsyncHooks,
7344
+ worker_threads: VirtualWorkerThreads,
7345
+ v8: VirtualV8,
7346
+ vm: VirtualVm,
7347
+ domain: VirtualDomain,
7348
+ diagnostics_channel: VirtualDiagnosticsChannel,
7349
+ http2: VirtualHttp2,
7350
+ cluster: VirtualCluster,
7351
+ repl: VirtualRepl,
7352
+ inspector: VirtualInspector,
7353
+ trace_events: VirtualTraceEvents,
7354
+ wasi: VirtualWasi,
7355
+ constants: vfs.constants,
7356
+ 'util/types': VirtualUtil.types,
7357
+ 'stream/web': VirtualStreamWeb,
7358
+ 'stream/consumers': VirtualStreamConsumers
6979
7359
  };
6980
7360
 
7361
+ // Auto-alias every builtin under the `node:` prefix (node:tty, node:readline…)
7362
+ // so both spellings resolve identically without hand-maintaining two lists.
7363
+ for (const __builtinName of Object.keys(builtinModules)) {
7364
+ if (!__builtinName.startsWith('node:') && !__builtinName.startsWith('bun:')) {
7365
+ builtinModules['node:' + __builtinName] = builtinModules[__builtinName];
7366
+ }
7367
+ }
7368
+
7369
+ // `module` must reference the now-complete builtin table, so it is attached
7370
+ // after the object literal above.
7371
+ const VirtualModule = {
7372
+ builtinModules: Object.keys(builtinModules),
7373
+ Module: class Module {},
7374
+ isBuiltin(name) { return Object.prototype.hasOwnProperty.call(builtinModules, String(name)); },
7375
+ createRequire(from) {
7376
+ const base = typeof from === 'string' ? from : '/workspace';
7377
+ const dir = /\.(?:js|mjs|cjs|ts|json)$/.test(base) ? VirtualPath.dirname(base) : base;
7378
+ const req = (id) => {
7379
+ if (Object.prototype.hasOwnProperty.call(builtinModules, id)) return builtinModules[id];
7380
+ return loadModule(resolveModulePath(id, dir), false);
7381
+ };
7382
+ req.resolve = (id) => resolveModulePath(id, dir);
7383
+ req.cache = {};
7384
+ return req;
7385
+ }
7386
+ };
7387
+ builtinModules.module = VirtualModule;
7388
+ builtinModules['node:module'] = VirtualModule;
7389
+
6981
7390
  const moduleCache = new Map();
6982
7391
  let mainModule = null;
6983
7392
 
@@ -7841,12 +8250,14 @@ if (typeof module !== 'undefined' && module.exports) {
7841
8250
  }
7842
8251
 
7843
8252
 
8253
+
7844
8254
  })();
7845
8255
 
7846
8256
  const CodeLabRuntime = root.CodeLabRuntime;
7847
8257
 
7848
8258
  // --- Module 2: POSIX Shell & Coreutils ---
7849
8259
  (function () {
8260
+ // @ts-nocheck
7850
8261
  /**
7851
8262
  * @innovatorved/code-lab - POSIX Shell Engine & UNIX Coreutils
7852
8263
  *
@@ -9834,7 +10245,7 @@ if (typeof module !== 'undefined' && module.exports) {
9834
10245
  return 10 + depth * 0.1;
9835
10246
  }
9836
10247
 
9837
- async function cloneGitHubRepository(repoInput, vfs, options = {}) {
10248
+ async function _cloneGitHubRepository(repoInput, vfs, options = {}) {
9838
10249
  const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
9839
10250
  if (onProgress) {
9840
10251
  onProgress({ phase: 'connecting', message: `Connecting to repository '${repoInput}'...` });
@@ -10124,6 +10535,23 @@ if (typeof module !== 'undefined' && module.exports) {
10124
10535
  };
10125
10536
  }
10126
10537
 
10538
+ // Public wrapper: guarantee an `error` progress event when the clone fails
10539
+ // for any reason (invalid URL, missing vfs, fetch rejection, abort, ...).
10540
+ async function cloneGitHubRepository(repoInput, vfs, options = {}) {
10541
+ const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
10542
+ try {
10543
+ return await _cloneGitHubRepository(repoInput, vfs, options);
10544
+ } catch (err) {
10545
+ if (onProgress) {
10546
+ onProgress({
10547
+ phase: 'error',
10548
+ message: err && err.message ? err.message : String(err)
10549
+ });
10550
+ }
10551
+ throw err;
10552
+ }
10553
+ }
10554
+
10127
10555
  // =========================================================================
10128
10556
  // Package Management Helpers (npm / bun virtual modules & scripts)
10129
10557
  // =========================================================================
@@ -10222,6 +10650,15 @@ if (typeof module !== 'undefined' && module.exports) {
10222
10650
 
10223
10651
  function pickConditionalEntry(value) {
10224
10652
  if (typeof value === 'string') return value;
10653
+ // `exports` subpaths may be an array of fallbacks, e.g.
10654
+ // `"./shams": [{ "types": "...", "default": "./shams.js" }, "./shams.js"]`.
10655
+ if (Array.isArray(value)) {
10656
+ for (const item of value) {
10657
+ const picked = pickConditionalEntry(item);
10658
+ if (picked) return picked;
10659
+ }
10660
+ return null;
10661
+ }
10225
10662
  if (!value || typeof value !== 'object') return null;
10226
10663
  // This runtime executes CommonJS, so it prefers CJS-friendly conditions.
10227
10664
  for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
@@ -10278,17 +10715,50 @@ if (typeof module !== 'undefined' && module.exports) {
10278
10715
  return parts.join('/');
10279
10716
  }
10280
10717
 
10718
+ // Small promise-based delay. Used only for CDN retry backoff; falls back to an
10719
+ // immediate resolve if `setTimeout` is unavailable in the host.
10720
+ function cdnBackoff(ms) {
10721
+ return new Promise((resolve) => {
10722
+ if (typeof setTimeout === 'function') setTimeout(resolve, ms);
10723
+ else resolve();
10724
+ });
10725
+ }
10726
+
10281
10727
  async function fetchTextFromCdn(fetchImpl, url) {
10282
- try {
10283
- const res = await fetchImpl(url);
10284
- if (!res) return null;
10285
- const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
10286
- if (!ok) return null;
10287
- if (typeof res.text === 'function') return await res.text();
10288
- return String(res.body != null ? res.body : '');
10289
- } catch (_) {
10290
- return null;
10728
+ // A single flaky jsDelivr response used to silently produce an *incomplete*
10729
+ // install (the module graph then failed at require-time). Retry transient
10730
+ // failures (network error, 429/408, 5xx) but treat 4xx as final.
10731
+ const maxAttempts = 3;
10732
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
10733
+ try {
10734
+ const res = await fetchImpl(url);
10735
+ if (!res) {
10736
+ if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
10737
+ return null;
10738
+ }
10739
+ const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
10740
+ if (!ok) {
10741
+ const transient = res.status >= 500 || res.status === 429 || res.status === 408;
10742
+ if (transient && attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
10743
+ return null;
10744
+ }
10745
+ // jsDelivr answers a *directory* path (e.g. `/pkg@1/libcjs/`) with HTTP 200
10746
+ // and an HTML directory listing. Storing that as a module both corrupts the
10747
+ // package and later collides with the real directory (EISDIR).
10748
+ const contentType = (res.headers && typeof res.headers.get === 'function')
10749
+ ? (res.headers.get('content-type') || '')
10750
+ : '';
10751
+ const isHtmlUrl = /\.html?(?:[?#]|$)/i.test(url);
10752
+ if (/text\/html/i.test(contentType) && !isHtmlUrl) return null;
10753
+ const text = typeof res.text === 'function' ? await res.text() : String(res.body != null ? res.body : '');
10754
+ if (!isHtmlUrl && /^\s*(?:<!doctype\s+html|<html[\s>]|<head[\s>])/i.test(text)) return null;
10755
+ return text;
10756
+ } catch (_) {
10757
+ if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
10758
+ return null;
10759
+ }
10291
10760
  }
10761
+ return null;
10292
10762
  }
10293
10763
 
10294
10764
  async function resolvePackageMetadata(fetchImpl, name, range) {
@@ -10331,14 +10801,25 @@ if (typeof module !== 'undefined' && module.exports) {
10331
10801
  const visited = new Set();
10332
10802
  // Seed with the package entry plus any declared `exports` subpaths, so a
10333
10803
  // later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
10334
- const seed = [entry, `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`];
10804
+ // A `main` may point at a *directory* (e.g. chalk: `"main": "source"`); Node
10805
+ // resolves that to `<dir>/index.<ext>`, so those candidates must be seeded
10806
+ // too or the package installs with only its manifest.
10807
+ const seed = [
10808
+ entry,
10809
+ `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`,
10810
+ `${entry}/index.js`, `${entry}/index.json`, `${entry}/index.mjs`, `${entry}/index.cjs`
10811
+ ];
10335
10812
  const expMap = meta.exports;
10336
10813
  if (expMap && typeof expMap === 'object') {
10337
- let subCount = 0;
10814
+ // Seed *every* declared subpath. A low cap silently dropped the tail of
10815
+ // packages that list each file in `exports` (lit-html has 29 keys, so
10816
+ // `lit-html/is-server.js` was never fetched and `require` failed later).
10817
+ // Wildcard keys (`./*`) need no seeding — their files are reached through
10818
+ // the relative-require closure or fetched on demand.
10338
10819
  for (const key of Object.keys(expMap)) {
10339
- if (key === '.' || key.slice(0, 2) !== './' || subCount >= 25) continue;
10820
+ if (key === '.' || key.slice(0, 2) !== './' || key.includes('*')) continue;
10340
10821
  const target = pickConditionalEntry(expMap[key]);
10341
- if (target) { seed.push(target); subCount++; }
10822
+ if (target) seed.push(target);
10342
10823
  }
10343
10824
  }
10344
10825
  let frontier = seed;
@@ -10346,7 +10827,9 @@ if (typeof module !== 'undefined' && module.exports) {
10346
10827
  const batch = [];
10347
10828
  for (const raw of frontier) {
10348
10829
  const rel = stripRelPath(raw);
10349
- if (!rel || visited.has(rel)) continue;
10830
+ // Directory targets (e.g. `exports["./lib/"] === "./libcjs/"`) must never
10831
+ // be fetched as files — that is what produced the EISDIR crash.
10832
+ if (!rel || rel.endsWith('/') || visited.has(rel)) continue;
10350
10833
  visited.add(rel);
10351
10834
  batch.push(rel);
10352
10835
  }
@@ -10382,15 +10865,29 @@ if (typeof module !== 'undefined' && module.exports) {
10382
10865
  }
10383
10866
 
10384
10867
  // Declared dependencies plus non-optional peer dependencies (npm v7+ style),
10385
- // so e.g. `npm install react-dom` also pulls in `react`.
10386
- const depNames = Object.keys(meta.dependencies || {});
10868
+ // so e.g. `npm install react-dom` also pulls in `react`. The *ranges* are
10869
+ // preserved (not just the names) so transitives resolve to the version the
10870
+ // parent actually asked for — e.g. chalk@4 needs ansi-styles@^4, which itself
10871
+ // needs color-convert. Resolving transitive names as "latest" silently breaks
10872
+ // the tree (ansi-styles@6 has no deps at all).
10873
+ const depSpecs = [];
10874
+ const depSeen = new Set();
10875
+ const declared = meta.dependencies || {};
10876
+ for (const depName of Object.keys(declared)) {
10877
+ if (depSeen.has(depName)) continue;
10878
+ depSeen.add(depName);
10879
+ depSpecs.push({ name: depName, range: declared[depName] || null });
10880
+ }
10387
10881
  const peerMeta = meta.peerDependenciesMeta || {};
10388
- for (const peer of Object.keys(meta.peerDependencies || {})) {
10882
+ const peers = meta.peerDependencies || {};
10883
+ for (const peer of Object.keys(peers)) {
10389
10884
  if (peerMeta[peer] && peerMeta[peer].optional) continue;
10390
- if (depNames.indexOf(peer) === -1) depNames.push(peer);
10885
+ if (depSeen.has(peer)) continue;
10886
+ depSeen.add(peer);
10887
+ depSpecs.push({ name: peer, range: peers[peer] || null });
10391
10888
  }
10392
10889
 
10393
- return { ok: true, version, entry, files, deps: depNames, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
10890
+ return { ok: true, version, entry, files, deps: depSpecs, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
10394
10891
  }
10395
10892
 
10396
10893
  function installTargetDirs(ctx, name) {
@@ -10404,7 +10901,13 @@ if (typeof module !== 'undefined' && module.exports) {
10404
10901
  for (const dir of dirs) {
10405
10902
  ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
10406
10903
  for (const f of info.files) {
10904
+ if (!f || !f.rel || f.rel.endsWith('/')) continue;
10407
10905
  const full = PosixPath.join(dir, f.rel);
10906
+ // Never overwrite a directory with a file body (defensive: a stray
10907
+ // directory target would otherwise raise EISDIR).
10908
+ try {
10909
+ if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
10910
+ } catch (_) {}
10408
10911
  ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
10409
10912
  ctx.vfs.writeFileSync(full, f.content);
10410
10913
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
@@ -10470,10 +10973,11 @@ if (typeof module !== 'undefined' && module.exports) {
10470
10973
  if (item.direct) directVersion = info.version || null;
10471
10974
 
10472
10975
  for (const dep of (info.deps || [])) {
10473
- const parsed = parsePackageSpec(dep);
10474
- if (parsed.name && !requested.has(parsed.name)) {
10475
- requested.add(parsed.name);
10476
- queue.push({ name: parsed.name, range: null, direct: false });
10976
+ const depName = (dep && typeof dep === 'object') ? dep.name : parsePackageSpec(dep).name;
10977
+ const depRange = (dep && typeof dep === 'object') ? dep.range : parsePackageSpec(dep).range;
10978
+ if (depName && !requested.has(depName)) {
10979
+ requested.add(depName);
10980
+ queue.push({ name: depName, range: depRange || null, direct: false });
10477
10981
  }
10478
10982
  }
10479
10983
  }
@@ -10830,21 +11334,29 @@ if (typeof module !== 'undefined' && module.exports) {
10830
11334
  // Common dev-server commands that cannot run inside the virtual runtime are
10831
11335
  // transparently redirected to the built-in preview server.
10832
11336
  const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
11337
+ // The same tools, when typed directly at the prompt (`ng serve`, `vite`).
11338
+ // `serve` is omitted: it is a first-class builtin shell command.
11339
+ const DIRECT_DEV_TOOL_RE = /^(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|http-server)$/;
10833
11340
 
10834
- function tryDevScriptFallback(scriptName, cmd, ctx) {
11341
+ function tryDevScriptFallback(scriptName, cmd, ctx, opts) {
10835
11342
  if (!PREVIEW_TOOL_RE.test(cmd)) return null;
10836
11343
  // Only fall back when the referenced tool is not actually installed.
10837
11344
  const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
11345
+ const force = Boolean(opts && opts.force);
10838
11346
  const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
10839
- if (ctx.vfs.existsSync(binPath)) return null;
11347
+ if (!force && ctx.vfs.existsSync(binPath)) return null;
10840
11348
  const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
10841
11349
  const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
10842
11350
  const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
10843
- const entry = registerPreviewServer(ctx, ctx.cwd, port);
11351
+ const rootDir = typeof ctx.resolvePath === 'function' ? ctx.resolvePath('.') : (ctx.cwd || '/workspace');
11352
+ const entry = registerPreviewServer(ctx, rootDir, port);
10844
11353
  if (!entry) return null;
11354
+ const note = force
11355
+ ? `${bin} is a native dev server and cannot execute inside this virtual runtime — using the CodeLab preview server instead.`
11356
+ : `${bin} is not available in this virtual runtime — using the CodeLab preview server instead.`;
10845
11357
  return {
10846
11358
  code: 0,
10847
- stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${bin} is not available in this virtual runtime — using the CodeLab preview server instead.\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
11359
+ stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${note}\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
10848
11360
  stderr: ''
10849
11361
  };
10850
11362
  }
@@ -14943,6 +15455,13 @@ if (typeof module !== 'undefined' && module.exports) {
14943
15455
  Object.assign(context.env, this.env);
14944
15456
  context.cwd = this.cwd;
14945
15457
  }
15458
+ } else if (DIRECT_DEV_TOOL_RE.test(cmdName)) {
15459
+ // A native dev server (vite/ng/astro/…) typed directly. It cannot run in
15460
+ // this runtime — whether or not it was installed — so route it to the
15461
+ // built-in preview server rather than reporting a misleading "command
15462
+ // not found".
15463
+ const fb = tryDevScriptFallback(cmdName, [cmdName, ...args].join(' '), cmdCtx, { force: true });
15464
+ res = fb || { code: 127, stdout: '', stderr: `shell: ${cmdName}: command not found\n` };
14946
15465
  } else if (typeof this.options.onProcessSpawn === 'function') {
14947
15466
  const spawned = await this.options.onProcessSpawn(cmdName, args, {
14948
15467
  cwd: this.cwd,
@@ -15014,12 +15533,14 @@ if (typeof module !== 'undefined' && module.exports) {
15014
15533
  };
15015
15534
  });
15016
15535
 
15536
+
15017
15537
  })();
15018
15538
 
15019
15539
  const CodeLabShell = root.CodeLabShell;
15020
15540
 
15021
15541
  // --- Module 3: PTY Terminal Engine ---
15022
15542
  (function () {
15543
+ // @ts-nocheck
15023
15544
  /**
15024
15545
  * @innovatorved/code-lab - Pure-JS PTY Terminal Emulator Component
15025
15546
  *
@@ -16067,12 +16588,14 @@ if (typeof module !== 'undefined' && module.exports) {
16067
16588
  };
16068
16589
  });
16069
16590
 
16591
+
16070
16592
  })();
16071
16593
 
16072
16594
  const CodeLabTerminal = root.CodeLabTerminal;
16073
16595
 
16074
16596
  // --- Module 4: IDE Workbench & Web Component ---
16075
16597
  (function () {
16598
+ // @ts-nocheck
16076
16599
  /* ═══════════════════════════════════════════════════════════════════════════
16077
16600
  @innovatorved/code-lab — Interactive Monaco IDE Workbench & Guided Lab UI
16078
16601
  Supports <code-lab> Custom Element + window.CodeLab.mount() API
@@ -16116,6 +16639,10 @@ if (typeof module !== 'undefined' && module.exports) {
16116
16639
  const MONACO_BASE = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs';
16117
16640
  const STORAGE_PREFIX = 'sd-codelab-v1:';
16118
16641
 
16642
+ // The bundler rewrites this literal from package.json at build time. Keeping
16643
+ // the fallback in sync lets tests require src/workbench.js directly.
16644
+ const CODELAB_VERSION = '0.1.7';
16645
+
16119
16646
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
16120
16647
  const NODE_AMBIENT_DTS = `
16121
16648
  declare var require: (id: string) => any;
@@ -16452,6 +16979,33 @@ declare module 'bun:sqlite' {
16452
16979
  .replace(/'/g, '&#39;');
16453
16980
  }
16454
16981
 
16982
+ // Schemes that may appear in a rendered href. Everything else
16983
+ // (javascript:, data:, vbscript:, blob:, file:, ...) becomes a dead link.
16984
+ const SAFE_LINK_SCHEMES = new Set(['http', 'https', 'mailto']);
16985
+
16986
+ function sanitizeUrl(raw) {
16987
+ if (raw === null || raw === undefined) return '#';
16988
+ const trimmed = String(raw).trim();
16989
+ if (!trimmed) return '#';
16990
+
16991
+ // Browsers ignore C0 controls and zero-width characters while resolving a
16992
+ // scheme, so `java\nscript:` and `java\u200Bscript:` still execute. Strip
16993
+ // them before deciding what the scheme is, but return the original value
16994
+ // when it is safe.
16995
+ const normalized = trimmed.replace(/[\u0000-\u0020\u007F\u200B-\u200D\uFEFF]/g, '');
16996
+ const schemeMatch = normalized.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);
16997
+
16998
+ if (!schemeMatch) {
16999
+ // No scheme: a fragment, an absolute path, or a relative path.
17000
+ // Backslashes are treated as slashes by the URL parser and can turn a
17001
+ // "relative" URL into a protocol-relative one, so reject those.
17002
+ if (/^[\\/]{2}/.test(normalized) && !normalized.startsWith('/')) return '#';
17003
+ return trimmed;
17004
+ }
17005
+
17006
+ return SAFE_LINK_SCHEMES.has(schemeMatch[1].toLowerCase()) ? trimmed : '#';
17007
+ }
17008
+
16455
17009
  function formatErrorText(err) {
16456
17010
  if (!err) return '';
16457
17011
  if (typeof err === 'string') return err;
@@ -16645,14 +17199,9 @@ declare module 'bun:sqlite' {
16645
17199
 
16646
17200
  // Markdown Links: [label](url "title") or [label](url)
16647
17201
  text = text.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
16648
- const cleanUrl = url.trim();
17202
+ const cleanUrl = sanitizeUrl(url);
16649
17203
  const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
16650
- return `<a href="${escapeHtml(cleanUrl)}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${label}</a>`;
16651
- });
16652
-
16653
- // Autolinks: <https://...>
16654
- text = text.replace(/<(https?:\/\/[^>]+)>/g, (_, url) => {
16655
- return `<a href="${escapeHtml(url)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`;
17204
+ return `<a href="${escapeHtml(cleanUrl)}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${escapeHtml(label)}</a>`;
16656
17205
  });
16657
17206
 
16658
17207
  // Strikethrough: ~~del~~
@@ -16847,8 +17396,9 @@ declare module 'bun:sqlite' {
16847
17396
  // Normalize CRLF to LF
16848
17397
  text = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
16849
17398
 
16850
- // Prevent raw custom elements from executing within markdown previews
16851
- text = text.replace(/<\/?code-lab(\s[^>]*)?>/gi, (m) => escapeHtml(m));
17399
+ // NUL delimits internal placeholders. Strip author-supplied NULs so
17400
+ // markdown cannot forge a code-block or autolink placeholder.
17401
+ text = text.replace(/\u0000/g, '');
16852
17402
 
16853
17403
  // Phase 1: Fenced Code Block Extraction
16854
17404
  const codeBlocks = [];
@@ -16871,6 +17421,25 @@ declare module 'bun:sqlite' {
16871
17421
  return `\x00INLINECODE_${idx}\x00`;
16872
17422
  });
16873
17423
 
17424
+ // Phase 2b: Autolinks are the only inline construct that uses angle
17425
+ // brackets. Extract them before raw HTML is neutralized, then restore the
17426
+ // anchors in Phase 7.
17427
+ const autolinks = [];
17428
+ text = text.replace(/<(https?:\/\/[^>\s]+)>/g, (_, url) => {
17429
+ const idx = autolinks.length;
17430
+ const safe = sanitizeUrl(url);
17431
+ autolinks.push(
17432
+ `<a href="${escapeHtml(safe)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`
17433
+ );
17434
+ return `\x00AUTOLINK_${idx}\x00`;
17435
+ });
17436
+
17437
+ // Phase 2c: Neutralize all remaining raw HTML. Every tag needs a `<`, so
17438
+ // escaping that one character turns any author-supplied markup into text
17439
+ // without disturbing `>` blockquote syntax. From here on, every real tag
17440
+ // in the output is generated by this renderer.
17441
+ text = text.replace(/</g, '&lt;');
17442
+
16874
17443
  // Phase 3: GitHub Callout Alerts & Blockquotes
16875
17444
  const calloutBlocks = [];
16876
17445
  text = text.replace(/(?:^[ \t]*>.*(?:\n|$))+/gm, (match) => {
@@ -16948,7 +17517,8 @@ declare module 'bun:sqlite' {
16948
17517
  .replace(/\x00TABLE_(\d+)\x00/g, (_, i) => tableBlocks[Number(i)] || '')
16949
17518
  .replace(/\x00CALLOUT_(\d+)\x00/g, (_, i) => calloutBlocks[Number(i)] || '')
16950
17519
  .replace(/\x00CODEBLOCK_(\d+)\x00/g, (_, i) => codeBlocks[Number(i)] || '')
16951
- .replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '');
17520
+ .replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '')
17521
+ .replace(/\x00AUTOLINK_(\d+)\x00/g, (_, i) => autolinks[Number(i)] || '');
16952
17522
 
16953
17523
  return finalHtml;
16954
17524
  }
@@ -17158,24 +17728,102 @@ declare module 'bun:sqlite' {
17158
17728
  let _workbenchInstanceCounter = 0;
17159
17729
  const _fallbackStorage = new Map();
17160
17730
 
17161
- function safeStorageGet(key) {
17731
+ // CSP for preview HTML assembled in the srcdoc fallback. Mirrors PREVIEW_CSP
17732
+ // in src/preview-sw.js — keep both copies in sync.
17733
+ const PREVIEW_CSP = [
17734
+ "default-src 'self' data: blob:",
17735
+ "base-uri 'self'",
17736
+ "object-src 'none'",
17737
+ "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:",
17738
+ "style-src 'self' 'unsafe-inline'",
17739
+ "img-src 'self' data: blob:",
17740
+ "font-src 'self' data:",
17741
+ "connect-src 'self' data: blob:",
17742
+ "media-src 'self' data: blob:",
17743
+ "worker-src 'self' blob:",
17744
+ "frame-src 'self' data: blob:",
17745
+ "form-action 'self'",
17746
+ "frame-ancestors 'self'"
17747
+ ].join('; ');
17748
+
17749
+ function normalizePreviewOrigin(raw) {
17750
+ if (raw === null || raw === undefined || raw === '') return null;
17751
+ try {
17752
+ const parsed = new URL(String(raw));
17753
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
17754
+ return parsed.origin;
17755
+ } catch (_) {
17756
+ return null;
17757
+ }
17758
+ }
17759
+
17760
+ const LOG_PREFIX = '[code-lab]';
17761
+
17762
+ // Small leveled logger. Hosts can pass `options.logger` to route diagnostics
17763
+ // into their own telemetry; `options.debug` enables verbose output. Errors
17764
+ // are never silently discarded.
17765
+ function createLogger(options = {}) {
17766
+ const sink = options.logger;
17767
+ const debugEnabled = options.debug === true;
17768
+
17769
+ const write = (level, args) => {
17770
+ if (level === 'debug' && !debugEnabled) return;
17771
+ if (sink && typeof sink[level] === 'function') {
17772
+ try {
17773
+ sink[level](...args);
17774
+ return;
17775
+ } catch (_) {
17776
+ // A broken host logger must not break the IDE; fall through.
17777
+ }
17778
+ }
17779
+ const fn = typeof console !== 'undefined' ? console[level] : null;
17780
+ if (typeof fn === 'function') fn(LOG_PREFIX, ...args);
17781
+ };
17782
+
17783
+ return {
17784
+ debug: (...args) => write('debug', args),
17785
+ info: (...args) => write('info', args),
17786
+ warn: (...args) => write('warn', args),
17787
+ error: (...args) => write('error', args)
17788
+ };
17789
+ }
17790
+
17791
+ const DEFAULT_LOGGER = createLogger();
17792
+
17793
+ function safeStorageGet(key, logger = DEFAULT_LOGGER) {
17162
17794
  try {
17163
17795
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
17164
- return localStorage.getItem(key);
17796
+ const value = localStorage.getItem(key);
17797
+ if (value !== null && value !== undefined) return value;
17165
17798
  }
17166
- } catch (_) {}
17799
+ } catch (err) {
17800
+ logger.warn(
17801
+ `localStorage.getItem("${key}") failed; using in-memory state.`,
17802
+ err && err.message ? err.message : err
17803
+ );
17804
+ }
17167
17805
  return _fallbackStorage.has(key) ? _fallbackStorage.get(key) : null;
17168
17806
  }
17169
17807
 
17170
- function safeStorageSet(key, value) {
17808
+ function safeStorageSet(key, value, logger = DEFAULT_LOGGER) {
17171
17809
  const str = String(value);
17172
17810
  try {
17173
17811
  if (typeof localStorage !== 'undefined' && localStorage !== null) {
17174
17812
  localStorage.setItem(key, str);
17175
- return;
17813
+ return true;
17176
17814
  }
17177
- } catch (_) {}
17815
+ } catch (err) {
17816
+ if (!safeStorageSet._warnedKeys) safeStorageSet._warnedKeys = new Set();
17817
+ if (!safeStorageSet._warnedKeys.has(key)) {
17818
+ safeStorageSet._warnedKeys.add(key);
17819
+ logger.warn(
17820
+ `localStorage.setItem("${key}") failed; keeping state in memory for this session.`,
17821
+ err && err.message ? err.message : err
17822
+ );
17823
+ }
17824
+ }
17178
17825
  _fallbackStorage.set(key, str);
17826
+ return false;
17179
17827
  }
17180
17828
 
17181
17829
  // ── CodeLabWorkbench Instance Class ──────────────────────────────────────
@@ -17186,12 +17834,22 @@ declare module 'bun:sqlite' {
17186
17834
  throw new Error('CodeLabWorkbench requires a valid DOM container element.');
17187
17835
  }
17188
17836
  this.options = options || {};
17837
+ this.logger = createLogger({ logger: options.logger, debug: options.debug });
17838
+ this._persistenceFailureReported = false;
17189
17839
  this.instanceId = options.instanceId || (`cl-${++_workbenchInstanceCounter}`);
17190
17840
  this.labId = options.id || options.labId || options.buildId || 'custom-lab';
17191
17841
  this.title = options.title || this.labId;
17192
17842
  this.summary = options.summary || '';
17193
17843
  this.monacoUrl = options.monacoUrl || MONACO_BASE;
17194
17844
  this.themeOption = options.theme || 'auto'; // 'dark' | 'light' | 'auto'
17845
+ this.previewOrigin = normalizePreviewOrigin(options.previewOrigin);
17846
+ this._previewIsolationWarned = false;
17847
+ if (options.previewOrigin && !this.previewOrigin) {
17848
+ this.logger.warn(
17849
+ 'Ignoring invalid `previewOrigin`; expected an absolute http(s) origin ' +
17850
+ 'such as "https://preview.example.com".'
17851
+ );
17852
+ }
17195
17853
  this.explicitEntry = options.entry || null;
17196
17854
  this.explicitTestEntry = options.testEntry || options.testFile || null;
17197
17855
  this.backLabel = options.backLabel || 'Back to Build Guide';
@@ -17529,7 +18187,7 @@ declare module 'bun:sqlite' {
17529
18187
  const handlers = this._eventListeners.get(key);
17530
18188
  if (handlers) {
17531
18189
  for (const fn of Array.from(handlers)) {
17532
- try { fn(detail); } catch (_) {}
18190
+ try { fn(detail); } catch (err) { this.logger.error(`Listener for "${key}" threw.`, err); }
17533
18191
  }
17534
18192
  }
17535
18193
  }
@@ -17563,13 +18221,26 @@ declare module 'bun:sqlite' {
17563
18221
  return {};
17564
18222
  }
17565
18223
  try {
17566
- const raw = safeStorageGet(this._storageKey()) || safeStorageGet('sd_codelab_' + this.labId);
18224
+ const raw = safeStorageGet(this._storageKey(), this.logger) || safeStorageGet('sd_codelab_' + this.labId, this.logger);
17567
18225
  return raw ? JSON.parse(raw) : {};
17568
- } catch {
18226
+ } catch (err) {
18227
+ this.logger.warn(
18228
+ `Ignoring unreadable saved state for "${this.labId}".`,
18229
+ err && err.message ? err.message : err
18230
+ );
17569
18231
  return {};
17570
18232
  }
17571
18233
  }
17572
18234
 
18235
+ _reportPersistenceFailure() {
18236
+ if (this._persistenceFailureReported) return;
18237
+ this._persistenceFailureReported = true;
18238
+ this.logger.warn(
18239
+ 'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.'
18240
+ );
18241
+ this._emitEvent('persistence-error', { labId: this.labId });
18242
+ }
18243
+
17573
18244
  _saveState() {
17574
18245
  try {
17575
18246
  const key = `${this.mode}:${this.lang}`;
@@ -17594,11 +18265,20 @@ declare module 'bun:sqlite' {
17594
18265
  return;
17595
18266
  }
17596
18267
  const serialized = JSON.stringify(state);
17597
- safeStorageSet(this._storageKey(), serialized);
17598
- // Sync with host app sidebar & build overview progress trackers
17599
- safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr));
17600
- safeStorageSet('sd_codelab_' + this.labId, serialized);
17601
- } catch {}
18268
+ const persisted = [
18269
+ safeStorageSet(this._storageKey(), serialized, this.logger),
18270
+ // Sync with host app sidebar & build overview progress trackers
18271
+ safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger),
18272
+ safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger)
18273
+ ];
18274
+ if (persisted.includes(false)) this._reportPersistenceFailure();
18275
+ } catch (err) {
18276
+ this.logger.error(
18277
+ 'Failed to save workbench state.',
18278
+ err && err.message ? err.message : err
18279
+ );
18280
+ this._reportPersistenceFailure();
18281
+ }
17602
18282
  }
17603
18283
 
17604
18284
  _detectPackages() {
@@ -20163,8 +20843,44 @@ declare module 'bun:sqlite' {
20163
20843
  return `http://127.0.0.1:${port}${path}`;
20164
20844
  }
20165
20845
 
20846
+ _previewFrameUrl(port, pathAndQuery = '/') {
20847
+ const p = Number(port) || 3000;
20848
+ const rawPath = pathAndQuery || '/';
20849
+ const path = rawPath.startsWith('/') ? rawPath : '/' + rawPath;
20850
+ const base = this.previewOrigin || '';
20851
+ return `${base}/__preview/${p}${path}`;
20852
+ }
20853
+
20854
+ _warnPreviewIsolation() {
20855
+ if (this.previewOrigin || this._previewIsolationWarned) return;
20856
+ this._previewIsolationWarned = true;
20857
+ if (typeof console !== 'undefined' && typeof console.warn === 'function') {
20858
+ console.warn(
20859
+ '[code-lab] Web Preview runs on the host origin and can read host storage. ' +
20860
+ 'Pass `previewOrigin: "https://preview.example.com"` to isolate untrusted previews.'
20861
+ );
20862
+ }
20863
+ }
20864
+
20865
+ _injectPreviewCsp(html, port) {
20866
+ if (typeof html !== 'string' || !html) return html;
20867
+ if (/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) return html;
20868
+
20869
+ const tags = `<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}">` +
20870
+ (/<base\b/i.test(html) ? '' : `<base href="/__preview/${Number(port) || 3000}/">`);
20871
+
20872
+ if (/<head\b[^>]*>/i.test(html)) {
20873
+ return html.replace(/<head\b[^>]*>/i, (match) => match + tags);
20874
+ }
20875
+ if (/<html\b[^>]*>/i.test(html)) {
20876
+ return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${tags}</head>`);
20877
+ }
20878
+ return `<head>${tags}</head>${html}`;
20879
+ }
20880
+
20166
20881
  _openWebPreview(port, path = '/') {
20167
20882
  const p = Number(port) || this._firstListeningPort() || 3000;
20883
+ this._warnPreviewIsolation();
20168
20884
  this.previewState.port = p;
20169
20885
  this.previewState.path = path || '/';
20170
20886
  this.previewState.url = `http://127.0.0.1:${p}${this.previewState.path}`;
@@ -20343,10 +21059,10 @@ declare module 'bun:sqlite' {
20343
21059
 
20344
21060
  _popoutPreview() {
20345
21061
  const url = this._previewUrl();
20346
- let popout = '/__preview/';
21062
+ let popout = this._previewFrameUrl(this.previewState.port || 3000, '/');
20347
21063
  try {
20348
21064
  const u = new URL(url);
20349
- popout = `/__preview/${u.port}${u.pathname}${u.search || ''}`;
21065
+ popout = this._previewFrameUrl(u.port, `${u.pathname}${u.search || ''}`);
20350
21066
  } catch (_) {}
20351
21067
  if (typeof window !== 'undefined' && typeof window.open === 'function') {
20352
21068
  try { window.open(popout, '_blank', 'noopener'); } catch (_) {}
@@ -20356,6 +21072,7 @@ declare module 'bun:sqlite' {
20356
21072
 
20357
21073
  _renderWebPreview(bodyEl) {
20358
21074
  if (!bodyEl) return;
21075
+ this._warnPreviewIsolation();
20359
21076
  const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this._previewSwReady}`;
20360
21077
  if (bodyEl.querySelector && bodyEl.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
20361
21078
  this._renderWebPreviewControls();
@@ -20393,7 +21110,7 @@ declare module 'bun:sqlite' {
20393
21110
  <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-popout" title="Open in a new browser tab">${CL_ICONS.externalLink || '↗'} <span>Pop Out</span></button>
20394
21111
  </div>
20395
21112
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
20396
- <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-same-origin allow-modals" title="Web Preview"></iframe>
21113
+ <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-same-origin allow-modals" allow="camera 'none'; microphone 'none'; geolocation 'none'; payment 'none'; usb 'none'" referrerpolicy="same-origin" title="Web Preview"></iframe>
20397
21114
  </div>
20398
21115
  ${servers.length
20399
21116
  ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
@@ -20430,7 +21147,7 @@ declare module 'bun:sqlite' {
20430
21147
  try {
20431
21148
  const u = new URL(fullUrl);
20432
21149
  if (typeof iframe.removeAttribute === 'function') iframe.removeAttribute('srcdoc');
20433
- iframe.setAttribute('src', `/__preview/${u.port}${u.pathname}${u.search || ''}`);
21150
+ iframe.setAttribute('src', this._previewFrameUrl(u.port, u.pathname + (u.search || '')));
20434
21151
  this.previewState.loading = false;
20435
21152
  return Promise.resolve();
20436
21153
  } catch (_) {}
@@ -20442,8 +21159,8 @@ declare module 'bun:sqlite' {
20442
21159
  .then((res) => {
20443
21160
  let body = res.body || '';
20444
21161
  const contentType = res.headers['content-type'] || res.headers['Content-Type'] || '';
20445
- if (/text\/html/i.test(contentType) && /<head\b/i.test(body) && !/<base\b/i.test(body)) {
20446
- body = body.replace(/<head\b[^>]*>/i, (m) => `${m}<base href="/__preview/${port}/">`);
21162
+ if (/text\/html/i.test(contentType)) {
21163
+ body = this._injectPreviewCsp(body, port);
20447
21164
  }
20448
21165
  this.previewState.srcdoc = body;
20449
21166
  this.previewState.loading = false;
@@ -20455,7 +21172,7 @@ declare module 'bun:sqlite' {
20455
21172
  this.previewState.loading = false;
20456
21173
  this.previewState.error = String((err && err.message) || err);
20457
21174
  const msg = `<body style="font-family:system-ui;padding:24px;color:#888"><h2>Preview unavailable</h2><p>${escapeHtml(this.previewState.error)}</p></body>`;
20458
- iframe.setAttribute('srcdoc', msg);
21175
+ iframe.setAttribute('srcdoc', this._injectPreviewCsp(msg, port));
20459
21176
  });
20460
21177
  }
20461
21178
 
@@ -20810,7 +21527,7 @@ declare module 'bun:sqlite' {
20810
21527
 
20811
21528
  _notifyCodeChange(filename, code) {
20812
21529
  if (this.onCodeChange) {
20813
- try { this.onCodeChange(filename, code); } catch (_) {}
21530
+ try { this.onCodeChange(filename, code); } catch (err) { this.logger.error('onCodeChange callback threw.', err); }
20814
21531
  }
20815
21532
  const detail = { labId: this.labId, filename, path: filename, code, content: code };
20816
21533
  this._emitEvent('codelab:change', detail);
@@ -22449,7 +23166,7 @@ declare module 'bun:sqlite' {
22449
23166
  }
22450
23167
 
22451
23168
  if (this.onRun) {
22452
- try { this.onRun(res); } catch (_) {}
23169
+ try { this.onRun(res); } catch (err) { this.logger.error('onRun callback threw.', err); }
22453
23170
  }
22454
23171
  this._emitEvent('codelab:run', { labId: this.labId, mode: 'run', entry, result: res });
22455
23172
  } catch (err) {
@@ -22524,10 +23241,10 @@ declare module 'bun:sqlite' {
22524
23241
  }
22525
23242
 
22526
23243
  if (this.onTestResult) {
22527
- try { this.onTestResult(res); } catch (_) {}
23244
+ try { this.onTestResult(res); } catch (err) { this.logger.error('onTestResult callback threw.', err); }
22528
23245
  }
22529
23246
  if (this.onRun) {
22530
- try { this.onRun(res); } catch (_) {}
23247
+ try { this.onRun(res); } catch (err) { this.logger.error('onRun callback threw.', err); }
22531
23248
  }
22532
23249
  this._emitEvent('codelab:run', { labId: this.labId, mode: 'test', entry, result: res });
22533
23250
 
@@ -22541,7 +23258,7 @@ declare module 'bun:sqlite' {
22541
23258
  this.completedSteps.add(step.id);
22542
23259
  newlyCompleted = true;
22543
23260
  if (this.onStepComplete) {
22544
- try { this.onStepComplete(step, sIdx); } catch (_) {}
23261
+ try { this.onStepComplete(step, sIdx); } catch (err) { this.logger.error('onStepComplete callback threw.', err); }
22545
23262
  }
22546
23263
  const stepDetail = {
22547
23264
  labId: this.labId,
@@ -22560,7 +23277,7 @@ declare module 'bun:sqlite' {
22560
23277
  this._saveState();
22561
23278
  if (this.steps.length > 0 && this.completedSteps.size >= this.steps.length) {
22562
23279
  if (this.onLabComplete) {
22563
- try { this.onLabComplete(this.labId); } catch (_) {}
23280
+ try { this.onLabComplete(this.labId); } catch (err) { this.logger.error('onLabComplete callback threw.', err); }
22564
23281
  }
22565
23282
  this._emitEvent('codelab:lab-complete', {
22566
23283
  labId: this.labId,
@@ -22865,7 +23582,12 @@ declare module 'bun:sqlite' {
22865
23582
  a.click();
22866
23583
  setTimeout(() => URL.revokeObjectURL(url), 500);
22867
23584
  }
22868
- } catch (_) {}
23585
+ } catch (err) {
23586
+ this.logger.error(
23587
+ `Failed to start download for "${filename}".`,
23588
+ err && err.message ? err.message : err
23589
+ );
23590
+ }
22869
23591
  return content;
22870
23592
  }
22871
23593
 
@@ -22893,7 +23615,12 @@ declare module 'bun:sqlite' {
22893
23615
  a.click();
22894
23616
  setTimeout(() => URL.revokeObjectURL(url), 500);
22895
23617
  }
22896
- } catch (_) {}
23618
+ } catch (err) {
23619
+ this.logger.error(
23620
+ 'Failed to download workspace export.',
23621
+ err && err.message ? err.message : err
23622
+ );
23623
+ }
22897
23624
  }
22898
23625
  return snapshot;
22899
23626
  }
@@ -23389,7 +24116,7 @@ declare module 'bun:sqlite' {
23389
24116
  }
23390
24117
 
23391
24118
  const CodeLabSDK = {
23392
- version: '2.0.0',
24119
+ version: CODELAB_VERSION,
23393
24120
  Workbench: CodeLabWorkbench,
23394
24121
  CodeLabWorkbench,
23395
24122
  CodeLabElement: CodeLabElementClass,
@@ -23453,6 +24180,7 @@ declare module 'bun:sqlite' {
23453
24180
  cancelWorkerExecution: CodeLabRuntime.cancelWorkerExecution,
23454
24181
  preloadNpmPackages: CodeLabRuntime.preloadNpmPackages,
23455
24182
  transpileTS: CodeLabRuntime.transpileTS,
24183
+ transpileForBrowser: CodeLabRuntime.transpileForBrowser,
23456
24184
  createVirtualFs: CodeLabRuntime.createVirtualFs,
23457
24185
  createVirtualHttp: CodeLabRuntime.createVirtualHttp,
23458
24186
  createVirtualNet: CodeLabRuntime.createVirtualNet,