@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/ARCHITECTURE.md +1 -1
- package/README.md +1 -1
- package/dist/code-lab.d.ts +3 -1
- package/dist/code-lab.esm.js +811 -74
- package/dist/code-lab.js +801 -73
- package/dist/extensions/guided-lab.esm.js +3 -0
- package/dist/extensions/guided-lab.js +3 -0
- package/dist/index.d.ts +1 -1
- package/dist/preview-sw.js +56 -8
- package/dist/runtime.d.ts +7 -27
- package/dist/runtime.esm.js +458 -16
- package/dist/runtime.js +415 -5
- package/dist/schemas.d.ts +10 -1
- package/dist/schemas.esm.js +4194 -0
- package/dist/schemas.js +4210 -0
- package/dist/shell.d.ts +18 -47
- package/dist/shell.esm.js +139 -29
- package/dist/shell.js +139 -29
- package/dist/terminal.d.ts +11 -87
- package/dist/terminal.esm.js +10 -2
- package/dist/terminal.js +3 -1
- package/package.json +12 -5
- package/src/index.ts +1 -1
- package/src/preview-sw.js +56 -8
- package/src/runtime.ts +478 -79
- package/src/schemas.ts +4 -1
- package/src/shell.ts +412 -359
- package/src/terminal.ts +885 -919
- package/src/workbench.ts +244 -40
- package/src/runtime.js +0 -7821
- package/src/shell.js +0 -7166
- package/src/terminal.js +0 -1046
- package/src/workbench.js +0 -7353
package/dist/code-lab.esm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* ============================================================
|
|
3
|
-
* @innovatorved/code-lab
|
|
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
|
|
@@ -18,6 +18,7 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
|
|
|
18
18
|
|
|
19
19
|
// --- Module 1: Runtime Engine ---
|
|
20
20
|
(function () {
|
|
21
|
+
// @ts-nocheck
|
|
21
22
|
'use strict';
|
|
22
23
|
if (typeof globalThis !== 'undefined' && typeof globalThis.Bun === 'undefined') {
|
|
23
24
|
globalThis.Bun = { version: '1.1.20' };
|
|
@@ -829,9 +830,78 @@ function __initVirtualRuntime(rootScope) {
|
|
|
829
830
|
crc = CRC32_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
|
|
830
831
|
}
|
|
831
832
|
return (crc ^ 0xffffffff) >>> 0;
|
|
833
|
+
},
|
|
834
|
+
// The full Node zlib constant surface. Packages such as axios read these at
|
|
835
|
+
// module-load time (e.g. `zlib.constants.Z_SYNC_FLUSH`) even when they never
|
|
836
|
+
// actually compress, so a missing table breaks the whole module graph.
|
|
837
|
+
constants: {
|
|
838
|
+
Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4,
|
|
839
|
+
Z_BLOCK: 5, Z_TREES: 6, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1,
|
|
840
|
+
Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_MEM_ERROR: -4, Z_BUF_ERROR: -5,
|
|
841
|
+
Z_VERSION_ERROR: -6, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9,
|
|
842
|
+
Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4,
|
|
843
|
+
Z_DEFAULT_STRATEGY: 0, ZLIB_VERNUM: 0x1310, DEFLATE: 1, INFLATE: 2, GZIP: 3,
|
|
844
|
+
GUNZIP: 4, DEFLATERAW: 5, INFLATERAW: 6, UNZIP: 7, BROTLI_DECODE: 8,
|
|
845
|
+
BROTLI_ENCODE: 9, Z_MIN_WINDOWBITS: 8, Z_MAX_WINDOWBITS: 15,
|
|
846
|
+
Z_DEFAULT_WINDOWBITS: 15, Z_MIN_CHUNK: 64, Z_MAX_CHUNK: Infinity,
|
|
847
|
+
Z_DEFAULT_CHUNK: 16384, Z_MIN_MEMLEVEL: 1, Z_MAX_MEMLEVEL: 9,
|
|
848
|
+
Z_DEFAULT_MEMLEVEL: 8, Z_MIN_LEVEL: -1, Z_MAX_LEVEL: 9, Z_DEFAULT_LEVEL: -1
|
|
832
849
|
}
|
|
833
850
|
};
|
|
834
851
|
|
|
852
|
+
// Compression: delegate to the host's real zlib when the runtime is embedded in
|
|
853
|
+
// Node (same process). In a pure browser worker there is no synchronous zlib, so
|
|
854
|
+
// the async APIs use CompressionStream/DecompressionStream and the *Sync variants
|
|
855
|
+
// throw a descriptive error instead of silently corrupting data.
|
|
856
|
+
(() => {
|
|
857
|
+
let hostZlib = null;
|
|
858
|
+
try { hostZlib = (typeof require === 'function') ? require('zlib') : null; } catch (_) { hostZlib = null; }
|
|
859
|
+
const names = [
|
|
860
|
+
'gzip', 'gunzip', 'deflate', 'inflate', 'deflateRaw', 'inflateRaw', 'unzip',
|
|
861
|
+
'gzipSync', 'gunzipSync', 'deflateSync', 'inflateSync', 'deflateRawSync', 'inflateRawSync', 'unzipSync',
|
|
862
|
+
'createGzip', 'createGunzip', 'createDeflate', 'createInflate', 'createDeflateRaw', 'createInflateRaw'
|
|
863
|
+
];
|
|
864
|
+
if (hostZlib) {
|
|
865
|
+
for (const n of names) {
|
|
866
|
+
if (typeof hostZlib[n] === 'function') VirtualZlib[n] = hostZlib[n].bind(hostZlib);
|
|
867
|
+
}
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
const asyncVariant = (format, kind) => (data, optsOrCb, maybeCb) => {
|
|
871
|
+
const cb = typeof optsOrCb === 'function' ? optsOrCb : (typeof maybeCb === 'function' ? maybeCb : null);
|
|
872
|
+
const p = (async () => {
|
|
873
|
+
if (typeof CompressionStream === 'undefined' || typeof DecompressionStream === 'undefined' || typeof Response === 'undefined') {
|
|
874
|
+
throw new Error('zlib.' + kind + ' is not supported in this environment');
|
|
875
|
+
}
|
|
876
|
+
const decompress = /^(gunzip|unzip|inflate)/.test(kind);
|
|
877
|
+
const stream = decompress ? new DecompressionStream(format) : new CompressionStream(format);
|
|
878
|
+
const writer = stream.writable.getWriter();
|
|
879
|
+
const input = data instanceof Uint8Array ? data : VirtualBuffer.from(data);
|
|
880
|
+
writer.write(input);
|
|
881
|
+
writer.close();
|
|
882
|
+
const ab = await new Response(stream.readable).arrayBuffer();
|
|
883
|
+
return VirtualBuffer.from(ab);
|
|
884
|
+
})();
|
|
885
|
+
if (cb) { p.then((out) => cb(null, out), (err) => cb(err)); return undefined; }
|
|
886
|
+
return p;
|
|
887
|
+
};
|
|
888
|
+
VirtualZlib.gzip = asyncVariant('gzip', 'gzip');
|
|
889
|
+
VirtualZlib.gunzip = asyncVariant('gzip', 'gunzip');
|
|
890
|
+
VirtualZlib.unzip = asyncVariant('gzip', 'unzip');
|
|
891
|
+
VirtualZlib.deflate = asyncVariant('deflate', 'deflate');
|
|
892
|
+
VirtualZlib.inflate = asyncVariant('deflate', 'inflate');
|
|
893
|
+
VirtualZlib.deflateRaw = asyncVariant('deflate-raw', 'deflateRaw');
|
|
894
|
+
VirtualZlib.inflateRaw = asyncVariant('deflate-raw', 'inflateRaw');
|
|
895
|
+
const unsupported = (kind) => () => { throw new Error('zlib.' + kind + ' is not supported in a browser worker (use the async API)'); };
|
|
896
|
+
VirtualZlib.gzipSync = unsupported('gzipSync');
|
|
897
|
+
VirtualZlib.gunzipSync = unsupported('gunzipSync');
|
|
898
|
+
VirtualZlib.deflateSync = unsupported('deflateSync');
|
|
899
|
+
VirtualZlib.inflateSync = unsupported('inflateSync');
|
|
900
|
+
VirtualZlib.deflateRawSync = unsupported('deflateRawSync');
|
|
901
|
+
VirtualZlib.inflateRawSync = unsupported('inflateRawSync');
|
|
902
|
+
VirtualZlib.unzipSync = unsupported('unzipSync');
|
|
903
|
+
})();
|
|
904
|
+
|
|
835
905
|
// =========================================================================
|
|
836
906
|
// 4. PATH & OS SHIMS
|
|
837
907
|
// =========================================================================
|
|
@@ -4870,7 +4940,13 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4870
4940
|
return cleaned ? `const { ${cleaned} } = require(${mod.trim()});` : '';
|
|
4871
4941
|
});
|
|
4872
4942
|
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));');
|
|
4873
|
-
|
|
4943
|
+
// Dynamic `import("pkg")` — resolve through the CJS loader instead of the
|
|
4944
|
+
// host's dynamic import, which cannot see the virtual filesystem.
|
|
4945
|
+
code = code.replace(/\bimport\s*\(\s*(\x00__LIT_\d+__\x00)\s*\)/g, 'Promise.resolve().then(() => require($1))');
|
|
4946
|
+
// Side-effect import `import"pkg"` / `import "pkg"`. By this point the
|
|
4947
|
+
// specifier is literal-masked, and minified modules emit no whitespace
|
|
4948
|
+
// between `import` and the string, so `\s*` (not `\s+`) is required.
|
|
4949
|
+
code = code.replace(/\bimport\s*(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
|
|
4874
4950
|
|
|
4875
4951
|
// Convert ES module exports
|
|
4876
4952
|
const exportedNames = [];
|
|
@@ -5003,8 +5079,12 @@ function __initVirtualRuntime(rootScope) {
|
|
|
5003
5079
|
const builtinSet = new Set([
|
|
5004
5080
|
'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
|
|
5005
5081
|
'dns', 'dns/promises', 'string_decoder', 'child_process', 'process',
|
|
5006
|
-
'assert', 'assert/strict', 'events', 'util', 'url', 'querystring',
|
|
5007
|
-
'stream', 'stream/promises', '
|
|
5082
|
+
'assert', 'assert/strict', 'events', 'util', 'util/types', 'url', 'querystring',
|
|
5083
|
+
'stream', 'stream/promises', 'stream/web', 'stream/consumers', 'test', 'perf_hooks',
|
|
5084
|
+
'timers', 'timers/promises', 'buffer', 'tty', 'tls', 'dgram', 'readline', 'readline/promises',
|
|
5085
|
+
'async_hooks', 'worker_threads', 'v8', 'vm', 'module', 'constants', 'domain',
|
|
5086
|
+
'diagnostics_channel', 'http2', 'cluster', 'repl', 'inspector', 'trace_events',
|
|
5087
|
+
'wasi', 'console',
|
|
5008
5088
|
'bun', 'bun:test', 'bun:sqlite'
|
|
5009
5089
|
]);
|
|
5010
5090
|
|
|
@@ -6914,6 +6994,285 @@ function __initVirtualRuntime(rootScope) {
|
|
|
6914
6994
|
})();
|
|
6915
6995
|
|
|
6916
6996
|
// Built-in Node module table
|
|
6997
|
+
// ── Additional Node builtin shims ────────────────────────────────────────
|
|
6998
|
+
// Widely-used packages require these at load time (e.g. `debug` requires
|
|
6999
|
+
// `tty`). Without an entry `require('tty')` throws MODULE_NOT_FOUND and the
|
|
7000
|
+
// whole app fails to start. Implementations are deliberately minimal but
|
|
7001
|
+
// shape-compatible; anything that genuinely cannot work in the sandbox
|
|
7002
|
+
// throws an explicit, descriptive error rather than silently misbehaving.
|
|
7003
|
+
const VirtualTty = {
|
|
7004
|
+
isatty() { return false; },
|
|
7005
|
+
ReadStream: class TtyReadStream extends EventEmitter {},
|
|
7006
|
+
WriteStream: class TtyWriteStream extends EventEmitter {
|
|
7007
|
+
constructor(fd) { super(); this.fd = fd; this.columns = 80; this.rows = 24; this.isTTY = false; }
|
|
7008
|
+
getColorDepth() { return 1; }
|
|
7009
|
+
hasColors() { return false; }
|
|
7010
|
+
cursorTo() { return true; }
|
|
7011
|
+
clearLine() { return true; }
|
|
7012
|
+
moveCursor() { return true; }
|
|
7013
|
+
}
|
|
7014
|
+
};
|
|
7015
|
+
|
|
7016
|
+
function makeReadlineInterface() {
|
|
7017
|
+
const iface = new EventEmitter();
|
|
7018
|
+
iface.terminal = false;
|
|
7019
|
+
iface.line = '';
|
|
7020
|
+
iface.cursor = 0;
|
|
7021
|
+
iface.question = (query, cb) => { if (typeof cb === 'function') queueMicrotask(() => cb('')); };
|
|
7022
|
+
iface.prompt = () => {};
|
|
7023
|
+
iface.setPrompt = () => {};
|
|
7024
|
+
iface.getPrompt = () => '';
|
|
7025
|
+
iface.write = () => {};
|
|
7026
|
+
iface.pause = () => iface;
|
|
7027
|
+
iface.resume = () => iface;
|
|
7028
|
+
iface.close = () => { queueMicrotask(() => iface.emit('close')); return iface; };
|
|
7029
|
+
iface[Symbol.asyncIterator] = async function* () {};
|
|
7030
|
+
return iface;
|
|
7031
|
+
}
|
|
7032
|
+
const VirtualReadline = {
|
|
7033
|
+
createInterface: makeReadlineInterface,
|
|
7034
|
+
Interface: class ReadlineInterface extends EventEmitter {},
|
|
7035
|
+
clearLine: () => true,
|
|
7036
|
+
clearScreenDown: () => true,
|
|
7037
|
+
cursorTo: () => true,
|
|
7038
|
+
moveCursor: () => true,
|
|
7039
|
+
emitKeypressEvents: () => {}
|
|
7040
|
+
};
|
|
7041
|
+
const VirtualReadlinePromises = {
|
|
7042
|
+
createInterface: () => {
|
|
7043
|
+
const iface = makeReadlineInterface();
|
|
7044
|
+
iface.question = () => Promise.resolve('');
|
|
7045
|
+
return iface;
|
|
7046
|
+
},
|
|
7047
|
+
Interface: class ReadlinePromisesInterface extends EventEmitter {}
|
|
7048
|
+
};
|
|
7049
|
+
|
|
7050
|
+
const VirtualAsyncHooks = {
|
|
7051
|
+
AsyncLocalStorage: class AsyncLocalStorage {
|
|
7052
|
+
constructor() { this._store = undefined; }
|
|
7053
|
+
getStore() { return this._store; }
|
|
7054
|
+
run(store, fn, ...args) {
|
|
7055
|
+
const prev = this._store;
|
|
7056
|
+
this._store = store;
|
|
7057
|
+
try { return fn(...args); } finally { this._store = prev; }
|
|
7058
|
+
}
|
|
7059
|
+
exit(fn, ...args) {
|
|
7060
|
+
const prev = this._store;
|
|
7061
|
+
this._store = undefined;
|
|
7062
|
+
try { return fn(...args); } finally { this._store = prev; }
|
|
7063
|
+
}
|
|
7064
|
+
enterWith(store) { this._store = store; }
|
|
7065
|
+
disable() { this._store = undefined; }
|
|
7066
|
+
},
|
|
7067
|
+
AsyncResource: class AsyncResource {
|
|
7068
|
+
constructor(type) { this.type = type || 'AsyncResource'; }
|
|
7069
|
+
runInAsyncScope(fn, thisArg, ...args) { return fn.apply(thisArg, args); }
|
|
7070
|
+
emitDestroy() { return this; }
|
|
7071
|
+
asyncId() { return 0; }
|
|
7072
|
+
triggerAsyncId() { return 0; }
|
|
7073
|
+
static bind(fn) { return fn; }
|
|
7074
|
+
},
|
|
7075
|
+
createHook() { return { enable() {}, disable() {} }; },
|
|
7076
|
+
executionAsyncId() { return 0; },
|
|
7077
|
+
triggerAsyncId() { return 0; },
|
|
7078
|
+
executionAsyncResource() { return null; }
|
|
7079
|
+
};
|
|
7080
|
+
|
|
7081
|
+
const VirtualWorkerThreads = {
|
|
7082
|
+
isMainThread: true,
|
|
7083
|
+
threadId: 0,
|
|
7084
|
+
parentPort: null,
|
|
7085
|
+
workerData: null,
|
|
7086
|
+
resourceLimits: {},
|
|
7087
|
+
SHARE_ENV: Symbol('nodejs.worker_threads.SHARE_ENV'),
|
|
7088
|
+
receiveMessageOnPort() { return undefined; },
|
|
7089
|
+
Worker: class Worker extends EventEmitter {
|
|
7090
|
+
constructor(filename) {
|
|
7091
|
+
super();
|
|
7092
|
+
this.threadId = -1;
|
|
7093
|
+
this.filename = filename;
|
|
7094
|
+
queueMicrotask(() => this.emit('error', new Error('worker_threads.Worker is not supported in the virtual runtime.')));
|
|
7095
|
+
}
|
|
7096
|
+
postMessage() {}
|
|
7097
|
+
terminate() { return Promise.resolve(0); }
|
|
7098
|
+
ref() { return this; }
|
|
7099
|
+
unref() { return this; }
|
|
7100
|
+
},
|
|
7101
|
+
MessageChannel: class MessageChannel {},
|
|
7102
|
+
MessagePort: class MessagePort extends EventEmitter {}
|
|
7103
|
+
};
|
|
7104
|
+
|
|
7105
|
+
const VirtualV8 = {
|
|
7106
|
+
serialize(value) { return VirtualBuffer.from(JSON.stringify(value === undefined ? null : value), 'utf8'); },
|
|
7107
|
+
deserialize(buf) { try { return JSON.parse(String(buf)); } catch (_) { return undefined; } },
|
|
7108
|
+
getHeapStatistics() {
|
|
7109
|
+
return {
|
|
7110
|
+
total_heap_size: 0, total_heap_size_executable: 0, total_physical_size: 0,
|
|
7111
|
+
total_available_size: 0, used_heap_size: 0, heap_size_limit: 0,
|
|
7112
|
+
malloced_memory: 0, peak_malloced_memory: 0, does_zap_garbage: 0,
|
|
7113
|
+
number_of_native_contexts: 1, number_of_detached_contexts: 0
|
|
7114
|
+
};
|
|
7115
|
+
},
|
|
7116
|
+
getHeapSpaceStatistics() { return []; },
|
|
7117
|
+
setFlagsFromString() {},
|
|
7118
|
+
cachedDataVersionTag() { return 0; },
|
|
7119
|
+
Serializer: class Serializer {
|
|
7120
|
+
constructor() { this._value = undefined; }
|
|
7121
|
+
writeHeader() {}
|
|
7122
|
+
writeValue(value) { this._value = value; }
|
|
7123
|
+
releaseBuffer() { return VirtualBuffer.from(JSON.stringify(this._value === undefined ? null : this._value), 'utf8'); }
|
|
7124
|
+
},
|
|
7125
|
+
Deserializer: class Deserializer {
|
|
7126
|
+
constructor(buffer) { this._buffer = buffer; }
|
|
7127
|
+
readHeader() { return true; }
|
|
7128
|
+
readValue() { try { return JSON.parse(String(this._buffer)); } catch (_) { return undefined; } }
|
|
7129
|
+
}
|
|
7130
|
+
};
|
|
7131
|
+
|
|
7132
|
+
const VirtualVm = {
|
|
7133
|
+
createContext(sandbox) { return sandbox && typeof sandbox === 'object' ? sandbox : {}; },
|
|
7134
|
+
isContext() { return false; },
|
|
7135
|
+
createScript() { throw new Error('vm code compilation is not supported in the virtual runtime.'); },
|
|
7136
|
+
runInContext() { throw new Error('vm.runInContext is not supported in the virtual runtime.'); },
|
|
7137
|
+
runInNewContext() { throw new Error('vm.runInNewContext is not supported in the virtual runtime.'); },
|
|
7138
|
+
runInThisContext() { throw new Error('vm.runInThisContext is not supported in the virtual runtime.'); },
|
|
7139
|
+
compileFunction() { throw new Error('vm.compileFunction is not supported in the virtual runtime.'); },
|
|
7140
|
+
Script: class Script {
|
|
7141
|
+
runInThisContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
|
|
7142
|
+
runInContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
|
|
7143
|
+
runInNewContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
|
|
7144
|
+
}
|
|
7145
|
+
};
|
|
7146
|
+
|
|
7147
|
+
const VirtualDomain = {
|
|
7148
|
+
create() {
|
|
7149
|
+
const d = new EventEmitter();
|
|
7150
|
+
d.members = [];
|
|
7151
|
+
d.add = () => d;
|
|
7152
|
+
d.remove = () => d;
|
|
7153
|
+
d.bind = (fn) => fn;
|
|
7154
|
+
d.intercept = (fn) => fn;
|
|
7155
|
+
d.run = (fn, ...args) => fn(...args);
|
|
7156
|
+
d.dispose = () => d;
|
|
7157
|
+
return d;
|
|
7158
|
+
},
|
|
7159
|
+
createDomain() { return VirtualDomain.create(); }
|
|
7160
|
+
};
|
|
7161
|
+
|
|
7162
|
+
const VirtualDiagnosticsChannel = {
|
|
7163
|
+
_channels: new Map(),
|
|
7164
|
+
channel(name) {
|
|
7165
|
+
const key = String(name);
|
|
7166
|
+
if (!VirtualDiagnosticsChannel._channels.has(key)) {
|
|
7167
|
+
const ch = new EventEmitter();
|
|
7168
|
+
ch.name = key;
|
|
7169
|
+
ch.hasSubscribers = false;
|
|
7170
|
+
ch.subscribe = () => { ch.hasSubscribers = true; };
|
|
7171
|
+
ch.unsubscribe = () => { ch.hasSubscribers = false; };
|
|
7172
|
+
VirtualDiagnosticsChannel._channels.set(key, ch);
|
|
7173
|
+
}
|
|
7174
|
+
return VirtualDiagnosticsChannel._channels.get(key);
|
|
7175
|
+
},
|
|
7176
|
+
subscribe(name, cb) {
|
|
7177
|
+
const ch = VirtualDiagnosticsChannel.channel(name);
|
|
7178
|
+
ch.subscribe();
|
|
7179
|
+
if (typeof cb === 'function') ch.on('message', cb);
|
|
7180
|
+
},
|
|
7181
|
+
unsubscribe(name) { VirtualDiagnosticsChannel.channel(name).unsubscribe(); },
|
|
7182
|
+
Channel: class Channel extends EventEmitter {}
|
|
7183
|
+
};
|
|
7184
|
+
|
|
7185
|
+
const notSupported = (what) => () => { throw new Error(what + ' is not supported in the virtual runtime.'); };
|
|
7186
|
+
const VirtualTls = {
|
|
7187
|
+
DEFAULT_MIN_VERSION: 'TLSv1.2',
|
|
7188
|
+
DEFAULT_MAX_VERSION: 'TLSv1.3',
|
|
7189
|
+
rootCertificates: [],
|
|
7190
|
+
createSecureContext() { return { context: {} }; },
|
|
7191
|
+
SecureContext: class SecureContext {},
|
|
7192
|
+
TLSSocket: class TLSSocket extends EventEmitter {},
|
|
7193
|
+
Server: class TLSServer extends EventEmitter {},
|
|
7194
|
+
checkServerIdentity() { return undefined; },
|
|
7195
|
+
connect: notSupported('tls.connect'),
|
|
7196
|
+
createServer: notSupported('tls.createServer')
|
|
7197
|
+
};
|
|
7198
|
+
const VirtualDgram = {
|
|
7199
|
+
createSocket(type) {
|
|
7200
|
+
const sock = new EventEmitter();
|
|
7201
|
+
sock.type = type || 'udp4';
|
|
7202
|
+
sock.bind = (...args) => { const cb = args[args.length - 1]; if (typeof cb === 'function') queueMicrotask(cb); return sock; };
|
|
7203
|
+
sock.close = (cb) => { queueMicrotask(() => { sock.emit('close'); if (typeof cb === 'function') cb(); }); return sock; };
|
|
7204
|
+
sock.send = notSupported('dgram.send');
|
|
7205
|
+
sock.address = () => ({ address: '0.0.0.0', family: 'IPv4', port: 0 });
|
|
7206
|
+
sock.setBroadcast = () => sock;
|
|
7207
|
+
sock.setTTL = () => sock;
|
|
7208
|
+
sock.addMembership = () => {};
|
|
7209
|
+
sock.dropMembership = () => {};
|
|
7210
|
+
return sock;
|
|
7211
|
+
},
|
|
7212
|
+
Socket: class Socket extends EventEmitter {}
|
|
7213
|
+
};
|
|
7214
|
+
const VirtualHttp2 = {
|
|
7215
|
+
constants: { NGHTTP2_REFUSED_STREAM: 7, NGHTTP2_CANCEL: 8 },
|
|
7216
|
+
connect: notSupported('http2.connect'),
|
|
7217
|
+
createServer: notSupported('http2.createServer'),
|
|
7218
|
+
createSecureServer: notSupported('http2.createSecureServer')
|
|
7219
|
+
};
|
|
7220
|
+
const VirtualCluster = {
|
|
7221
|
+
isPrimary: true,
|
|
7222
|
+
isMaster: true,
|
|
7223
|
+
isWorker: false,
|
|
7224
|
+
workers: {},
|
|
7225
|
+
fork: notSupported('cluster.fork'),
|
|
7226
|
+
setupPrimary: notSupported('cluster.setupPrimary'),
|
|
7227
|
+
setupMaster: notSupported('cluster.setupMaster'),
|
|
7228
|
+
disconnect: () => {}
|
|
7229
|
+
};
|
|
7230
|
+
const VirtualRepl = { start: notSupported('repl.start') };
|
|
7231
|
+
const VirtualInspector = {
|
|
7232
|
+
open: () => null,
|
|
7233
|
+
close: () => {},
|
|
7234
|
+
url: () => '',
|
|
7235
|
+
Session: class Session { connect() {} disconnect() {} post() {} }
|
|
7236
|
+
};
|
|
7237
|
+
const VirtualTraceEvents = {
|
|
7238
|
+
createTracing: () => ({ enable() {}, disable() {} }),
|
|
7239
|
+
getEnabledCategories: () => ''
|
|
7240
|
+
};
|
|
7241
|
+
const VirtualWasi = {
|
|
7242
|
+
WASI: class WASI { constructor() { throw new Error('wasi is not supported in the virtual runtime.'); } }
|
|
7243
|
+
};
|
|
7244
|
+
|
|
7245
|
+
const VirtualStreamWeb = {
|
|
7246
|
+
ReadableStream: typeof ReadableStream !== 'undefined' ? ReadableStream : undefined,
|
|
7247
|
+
WritableStream: typeof WritableStream !== 'undefined' ? WritableStream : undefined,
|
|
7248
|
+
TransformStream: typeof TransformStream !== 'undefined' ? TransformStream : undefined
|
|
7249
|
+
};
|
|
7250
|
+
async function consumeStream(kind, stream) {
|
|
7251
|
+
const chunks = [];
|
|
7252
|
+
if (stream && typeof stream[Symbol.asyncIterator] === 'function') {
|
|
7253
|
+
for await (const chunk of stream) chunks.push(chunk);
|
|
7254
|
+
} else if (stream && typeof stream.on === 'function') {
|
|
7255
|
+
await new Promise((resolve, reject) => {
|
|
7256
|
+
stream.on('data', (c) => chunks.push(c));
|
|
7257
|
+
stream.on('end', resolve);
|
|
7258
|
+
stream.on('error', reject);
|
|
7259
|
+
});
|
|
7260
|
+
}
|
|
7261
|
+
const bufs = chunks.map((c) => (typeof c === 'string' ? VirtualBuffer.from(c) : VirtualBuffer.from(c)));
|
|
7262
|
+
const buf = VirtualBuffer.concat(bufs);
|
|
7263
|
+
if (kind === 'buffer') return buf;
|
|
7264
|
+
if (kind === 'arrayBuffer') return buf.buffer ? buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) : new ArrayBuffer(0);
|
|
7265
|
+
if (kind === 'text') return buf.toString('utf8');
|
|
7266
|
+
if (kind === 'json') return JSON.parse(buf.toString('utf8'));
|
|
7267
|
+
return buf;
|
|
7268
|
+
}
|
|
7269
|
+
const VirtualStreamConsumers = {
|
|
7270
|
+
text: (s) => consumeStream('text', s),
|
|
7271
|
+
json: (s) => consumeStream('json', s),
|
|
7272
|
+
buffer: (s) => consumeStream('buffer', s),
|
|
7273
|
+
arrayBuffer: (s) => consumeStream('arrayBuffer', s)
|
|
7274
|
+
};
|
|
7275
|
+
|
|
6917
7276
|
const builtinModules = {
|
|
6918
7277
|
fs: vfs,
|
|
6919
7278
|
'node:fs': vfs,
|
|
@@ -6974,9 +7333,59 @@ function __initVirtualRuntime(rootScope) {
|
|
|
6974
7333
|
bun: BunObj,
|
|
6975
7334
|
'node:bun': BunObj,
|
|
6976
7335
|
'bun:test': bunTestModule,
|
|
6977
|
-
'bun:sqlite': { Database: SqliteDatabase }
|
|
7336
|
+
'bun:sqlite': { Database: SqliteDatabase },
|
|
7337
|
+
tty: VirtualTty,
|
|
7338
|
+
tls: VirtualTls,
|
|
7339
|
+
dgram: VirtualDgram,
|
|
7340
|
+
readline: VirtualReadline,
|
|
7341
|
+
'readline/promises': VirtualReadlinePromises,
|
|
7342
|
+
async_hooks: VirtualAsyncHooks,
|
|
7343
|
+
worker_threads: VirtualWorkerThreads,
|
|
7344
|
+
v8: VirtualV8,
|
|
7345
|
+
vm: VirtualVm,
|
|
7346
|
+
domain: VirtualDomain,
|
|
7347
|
+
diagnostics_channel: VirtualDiagnosticsChannel,
|
|
7348
|
+
http2: VirtualHttp2,
|
|
7349
|
+
cluster: VirtualCluster,
|
|
7350
|
+
repl: VirtualRepl,
|
|
7351
|
+
inspector: VirtualInspector,
|
|
7352
|
+
trace_events: VirtualTraceEvents,
|
|
7353
|
+
wasi: VirtualWasi,
|
|
7354
|
+
constants: vfs.constants,
|
|
7355
|
+
'util/types': VirtualUtil.types,
|
|
7356
|
+
'stream/web': VirtualStreamWeb,
|
|
7357
|
+
'stream/consumers': VirtualStreamConsumers
|
|
6978
7358
|
};
|
|
6979
7359
|
|
|
7360
|
+
// Auto-alias every builtin under the `node:` prefix (node:tty, node:readline…)
|
|
7361
|
+
// so both spellings resolve identically without hand-maintaining two lists.
|
|
7362
|
+
for (const __builtinName of Object.keys(builtinModules)) {
|
|
7363
|
+
if (!__builtinName.startsWith('node:') && !__builtinName.startsWith('bun:')) {
|
|
7364
|
+
builtinModules['node:' + __builtinName] = builtinModules[__builtinName];
|
|
7365
|
+
}
|
|
7366
|
+
}
|
|
7367
|
+
|
|
7368
|
+
// `module` must reference the now-complete builtin table, so it is attached
|
|
7369
|
+
// after the object literal above.
|
|
7370
|
+
const VirtualModule = {
|
|
7371
|
+
builtinModules: Object.keys(builtinModules),
|
|
7372
|
+
Module: class Module {},
|
|
7373
|
+
isBuiltin(name) { return Object.prototype.hasOwnProperty.call(builtinModules, String(name)); },
|
|
7374
|
+
createRequire(from) {
|
|
7375
|
+
const base = typeof from === 'string' ? from : '/workspace';
|
|
7376
|
+
const dir = /\.(?:js|mjs|cjs|ts|json)$/.test(base) ? VirtualPath.dirname(base) : base;
|
|
7377
|
+
const req = (id) => {
|
|
7378
|
+
if (Object.prototype.hasOwnProperty.call(builtinModules, id)) return builtinModules[id];
|
|
7379
|
+
return loadModule(resolveModulePath(id, dir), false);
|
|
7380
|
+
};
|
|
7381
|
+
req.resolve = (id) => resolveModulePath(id, dir);
|
|
7382
|
+
req.cache = {};
|
|
7383
|
+
return req;
|
|
7384
|
+
}
|
|
7385
|
+
};
|
|
7386
|
+
builtinModules.module = VirtualModule;
|
|
7387
|
+
builtinModules['node:module'] = VirtualModule;
|
|
7388
|
+
|
|
6980
7389
|
const moduleCache = new Map();
|
|
6981
7390
|
let mainModule = null;
|
|
6982
7391
|
|
|
@@ -7840,10 +8249,12 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
7840
8249
|
}
|
|
7841
8250
|
|
|
7842
8251
|
|
|
8252
|
+
|
|
7843
8253
|
})();
|
|
7844
8254
|
|
|
7845
8255
|
// --- Module 2: POSIX Shell & Coreutils ---
|
|
7846
8256
|
(function () {
|
|
8257
|
+
// @ts-nocheck
|
|
7847
8258
|
/**
|
|
7848
8259
|
* @innovatorved/code-lab - POSIX Shell Engine & UNIX Coreutils
|
|
7849
8260
|
*
|
|
@@ -9831,7 +10242,7 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
9831
10242
|
return 10 + depth * 0.1;
|
|
9832
10243
|
}
|
|
9833
10244
|
|
|
9834
|
-
async function
|
|
10245
|
+
async function _cloneGitHubRepository(repoInput, vfs, options = {}) {
|
|
9835
10246
|
const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
|
|
9836
10247
|
if (onProgress) {
|
|
9837
10248
|
onProgress({ phase: 'connecting', message: `Connecting to repository '${repoInput}'...` });
|
|
@@ -10121,6 +10532,23 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10121
10532
|
};
|
|
10122
10533
|
}
|
|
10123
10534
|
|
|
10535
|
+
// Public wrapper: guarantee an `error` progress event when the clone fails
|
|
10536
|
+
// for any reason (invalid URL, missing vfs, fetch rejection, abort, ...).
|
|
10537
|
+
async function cloneGitHubRepository(repoInput, vfs, options = {}) {
|
|
10538
|
+
const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
|
|
10539
|
+
try {
|
|
10540
|
+
return await _cloneGitHubRepository(repoInput, vfs, options);
|
|
10541
|
+
} catch (err) {
|
|
10542
|
+
if (onProgress) {
|
|
10543
|
+
onProgress({
|
|
10544
|
+
phase: 'error',
|
|
10545
|
+
message: err && err.message ? err.message : String(err)
|
|
10546
|
+
});
|
|
10547
|
+
}
|
|
10548
|
+
throw err;
|
|
10549
|
+
}
|
|
10550
|
+
}
|
|
10551
|
+
|
|
10124
10552
|
// =========================================================================
|
|
10125
10553
|
// Package Management Helpers (npm / bun virtual modules & scripts)
|
|
10126
10554
|
// =========================================================================
|
|
@@ -10219,6 +10647,15 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10219
10647
|
|
|
10220
10648
|
function pickConditionalEntry(value) {
|
|
10221
10649
|
if (typeof value === 'string') return value;
|
|
10650
|
+
// `exports` subpaths may be an array of fallbacks, e.g.
|
|
10651
|
+
// `"./shams": [{ "types": "...", "default": "./shams.js" }, "./shams.js"]`.
|
|
10652
|
+
if (Array.isArray(value)) {
|
|
10653
|
+
for (const item of value) {
|
|
10654
|
+
const picked = pickConditionalEntry(item);
|
|
10655
|
+
if (picked) return picked;
|
|
10656
|
+
}
|
|
10657
|
+
return null;
|
|
10658
|
+
}
|
|
10222
10659
|
if (!value || typeof value !== 'object') return null;
|
|
10223
10660
|
// This runtime executes CommonJS, so it prefers CJS-friendly conditions.
|
|
10224
10661
|
for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
|
|
@@ -10275,17 +10712,50 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10275
10712
|
return parts.join('/');
|
|
10276
10713
|
}
|
|
10277
10714
|
|
|
10715
|
+
// Small promise-based delay. Used only for CDN retry backoff; falls back to an
|
|
10716
|
+
// immediate resolve if `setTimeout` is unavailable in the host.
|
|
10717
|
+
function cdnBackoff(ms) {
|
|
10718
|
+
return new Promise((resolve) => {
|
|
10719
|
+
if (typeof setTimeout === 'function') setTimeout(resolve, ms);
|
|
10720
|
+
else resolve();
|
|
10721
|
+
});
|
|
10722
|
+
}
|
|
10723
|
+
|
|
10278
10724
|
async function fetchTextFromCdn(fetchImpl, url) {
|
|
10279
|
-
|
|
10280
|
-
|
|
10281
|
-
|
|
10282
|
-
|
|
10283
|
-
|
|
10284
|
-
|
|
10285
|
-
|
|
10286
|
-
|
|
10287
|
-
|
|
10725
|
+
// A single flaky jsDelivr response used to silently produce an *incomplete*
|
|
10726
|
+
// install (the module graph then failed at require-time). Retry transient
|
|
10727
|
+
// failures (network error, 429/408, 5xx) but treat 4xx as final.
|
|
10728
|
+
const maxAttempts = 3;
|
|
10729
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
10730
|
+
try {
|
|
10731
|
+
const res = await fetchImpl(url);
|
|
10732
|
+
if (!res) {
|
|
10733
|
+
if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
|
|
10734
|
+
return null;
|
|
10735
|
+
}
|
|
10736
|
+
const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
|
|
10737
|
+
if (!ok) {
|
|
10738
|
+
const transient = res.status >= 500 || res.status === 429 || res.status === 408;
|
|
10739
|
+
if (transient && attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
|
|
10740
|
+
return null;
|
|
10741
|
+
}
|
|
10742
|
+
// jsDelivr answers a *directory* path (e.g. `/pkg@1/libcjs/`) with HTTP 200
|
|
10743
|
+
// and an HTML directory listing. Storing that as a module both corrupts the
|
|
10744
|
+
// package and later collides with the real directory (EISDIR).
|
|
10745
|
+
const contentType = (res.headers && typeof res.headers.get === 'function')
|
|
10746
|
+
? (res.headers.get('content-type') || '')
|
|
10747
|
+
: '';
|
|
10748
|
+
const isHtmlUrl = /\.html?(?:[?#]|$)/i.test(url);
|
|
10749
|
+
if (/text\/html/i.test(contentType) && !isHtmlUrl) return null;
|
|
10750
|
+
const text = typeof res.text === 'function' ? await res.text() : String(res.body != null ? res.body : '');
|
|
10751
|
+
if (!isHtmlUrl && /^\s*(?:<!doctype\s+html|<html[\s>]|<head[\s>])/i.test(text)) return null;
|
|
10752
|
+
return text;
|
|
10753
|
+
} catch (_) {
|
|
10754
|
+
if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
|
|
10755
|
+
return null;
|
|
10756
|
+
}
|
|
10288
10757
|
}
|
|
10758
|
+
return null;
|
|
10289
10759
|
}
|
|
10290
10760
|
|
|
10291
10761
|
async function resolvePackageMetadata(fetchImpl, name, range) {
|
|
@@ -10328,14 +10798,25 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10328
10798
|
const visited = new Set();
|
|
10329
10799
|
// Seed with the package entry plus any declared `exports` subpaths, so a
|
|
10330
10800
|
// later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
|
|
10331
|
-
|
|
10801
|
+
// A `main` may point at a *directory* (e.g. chalk: `"main": "source"`); Node
|
|
10802
|
+
// resolves that to `<dir>/index.<ext>`, so those candidates must be seeded
|
|
10803
|
+
// too or the package installs with only its manifest.
|
|
10804
|
+
const seed = [
|
|
10805
|
+
entry,
|
|
10806
|
+
`${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`,
|
|
10807
|
+
`${entry}/index.js`, `${entry}/index.json`, `${entry}/index.mjs`, `${entry}/index.cjs`
|
|
10808
|
+
];
|
|
10332
10809
|
const expMap = meta.exports;
|
|
10333
10810
|
if (expMap && typeof expMap === 'object') {
|
|
10334
|
-
|
|
10811
|
+
// Seed *every* declared subpath. A low cap silently dropped the tail of
|
|
10812
|
+
// packages that list each file in `exports` (lit-html has 29 keys, so
|
|
10813
|
+
// `lit-html/is-server.js` was never fetched and `require` failed later).
|
|
10814
|
+
// Wildcard keys (`./*`) need no seeding — their files are reached through
|
|
10815
|
+
// the relative-require closure or fetched on demand.
|
|
10335
10816
|
for (const key of Object.keys(expMap)) {
|
|
10336
|
-
if (key === '.' || key.slice(0, 2) !== './' ||
|
|
10817
|
+
if (key === '.' || key.slice(0, 2) !== './' || key.includes('*')) continue;
|
|
10337
10818
|
const target = pickConditionalEntry(expMap[key]);
|
|
10338
|
-
if (target)
|
|
10819
|
+
if (target) seed.push(target);
|
|
10339
10820
|
}
|
|
10340
10821
|
}
|
|
10341
10822
|
let frontier = seed;
|
|
@@ -10343,7 +10824,9 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10343
10824
|
const batch = [];
|
|
10344
10825
|
for (const raw of frontier) {
|
|
10345
10826
|
const rel = stripRelPath(raw);
|
|
10346
|
-
|
|
10827
|
+
// Directory targets (e.g. `exports["./lib/"] === "./libcjs/"`) must never
|
|
10828
|
+
// be fetched as files — that is what produced the EISDIR crash.
|
|
10829
|
+
if (!rel || rel.endsWith('/') || visited.has(rel)) continue;
|
|
10347
10830
|
visited.add(rel);
|
|
10348
10831
|
batch.push(rel);
|
|
10349
10832
|
}
|
|
@@ -10379,15 +10862,29 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10379
10862
|
}
|
|
10380
10863
|
|
|
10381
10864
|
// Declared dependencies plus non-optional peer dependencies (npm v7+ style),
|
|
10382
|
-
// so e.g. `npm install react-dom` also pulls in `react`.
|
|
10383
|
-
|
|
10865
|
+
// so e.g. `npm install react-dom` also pulls in `react`. The *ranges* are
|
|
10866
|
+
// preserved (not just the names) so transitives resolve to the version the
|
|
10867
|
+
// parent actually asked for — e.g. chalk@4 needs ansi-styles@^4, which itself
|
|
10868
|
+
// needs color-convert. Resolving transitive names as "latest" silently breaks
|
|
10869
|
+
// the tree (ansi-styles@6 has no deps at all).
|
|
10870
|
+
const depSpecs = [];
|
|
10871
|
+
const depSeen = new Set();
|
|
10872
|
+
const declared = meta.dependencies || {};
|
|
10873
|
+
for (const depName of Object.keys(declared)) {
|
|
10874
|
+
if (depSeen.has(depName)) continue;
|
|
10875
|
+
depSeen.add(depName);
|
|
10876
|
+
depSpecs.push({ name: depName, range: declared[depName] || null });
|
|
10877
|
+
}
|
|
10384
10878
|
const peerMeta = meta.peerDependenciesMeta || {};
|
|
10385
|
-
|
|
10879
|
+
const peers = meta.peerDependencies || {};
|
|
10880
|
+
for (const peer of Object.keys(peers)) {
|
|
10386
10881
|
if (peerMeta[peer] && peerMeta[peer].optional) continue;
|
|
10387
|
-
if (
|
|
10882
|
+
if (depSeen.has(peer)) continue;
|
|
10883
|
+
depSeen.add(peer);
|
|
10884
|
+
depSpecs.push({ name: peer, range: peers[peer] || null });
|
|
10388
10885
|
}
|
|
10389
10886
|
|
|
10390
|
-
return { ok: true, version, entry, files, deps:
|
|
10887
|
+
return { ok: true, version, entry, files, deps: depSpecs, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
|
|
10391
10888
|
}
|
|
10392
10889
|
|
|
10393
10890
|
function installTargetDirs(ctx, name) {
|
|
@@ -10401,7 +10898,13 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10401
10898
|
for (const dir of dirs) {
|
|
10402
10899
|
ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
|
|
10403
10900
|
for (const f of info.files) {
|
|
10901
|
+
if (!f || !f.rel || f.rel.endsWith('/')) continue;
|
|
10404
10902
|
const full = PosixPath.join(dir, f.rel);
|
|
10903
|
+
// Never overwrite a directory with a file body (defensive: a stray
|
|
10904
|
+
// directory target would otherwise raise EISDIR).
|
|
10905
|
+
try {
|
|
10906
|
+
if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
|
|
10907
|
+
} catch (_) {}
|
|
10405
10908
|
ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
|
|
10406
10909
|
ctx.vfs.writeFileSync(full, f.content);
|
|
10407
10910
|
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
|
|
@@ -10467,10 +10970,11 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10467
10970
|
if (item.direct) directVersion = info.version || null;
|
|
10468
10971
|
|
|
10469
10972
|
for (const dep of (info.deps || [])) {
|
|
10470
|
-
const
|
|
10471
|
-
|
|
10472
|
-
|
|
10473
|
-
|
|
10973
|
+
const depName = (dep && typeof dep === 'object') ? dep.name : parsePackageSpec(dep).name;
|
|
10974
|
+
const depRange = (dep && typeof dep === 'object') ? dep.range : parsePackageSpec(dep).range;
|
|
10975
|
+
if (depName && !requested.has(depName)) {
|
|
10976
|
+
requested.add(depName);
|
|
10977
|
+
queue.push({ name: depName, range: depRange || null, direct: false });
|
|
10474
10978
|
}
|
|
10475
10979
|
}
|
|
10476
10980
|
}
|
|
@@ -10827,21 +11331,29 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10827
11331
|
// Common dev-server commands that cannot run inside the virtual runtime are
|
|
10828
11332
|
// transparently redirected to the built-in preview server.
|
|
10829
11333
|
const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
|
|
11334
|
+
// The same tools, when typed directly at the prompt (`ng serve`, `vite`).
|
|
11335
|
+
// `serve` is omitted: it is a first-class builtin shell command.
|
|
11336
|
+
const DIRECT_DEV_TOOL_RE = /^(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|http-server)$/;
|
|
10830
11337
|
|
|
10831
|
-
function tryDevScriptFallback(scriptName, cmd, ctx) {
|
|
11338
|
+
function tryDevScriptFallback(scriptName, cmd, ctx, opts) {
|
|
10832
11339
|
if (!PREVIEW_TOOL_RE.test(cmd)) return null;
|
|
10833
11340
|
// Only fall back when the referenced tool is not actually installed.
|
|
10834
11341
|
const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
|
|
11342
|
+
const force = Boolean(opts && opts.force);
|
|
10835
11343
|
const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
|
|
10836
|
-
if (ctx.vfs.existsSync(binPath)) return null;
|
|
11344
|
+
if (!force && ctx.vfs.existsSync(binPath)) return null;
|
|
10837
11345
|
const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
|
|
10838
11346
|
const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
|
|
10839
11347
|
const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
|
|
10840
|
-
const
|
|
11348
|
+
const rootDir = typeof ctx.resolvePath === 'function' ? ctx.resolvePath('.') : (ctx.cwd || '/workspace');
|
|
11349
|
+
const entry = registerPreviewServer(ctx, rootDir, port);
|
|
10841
11350
|
if (!entry) return null;
|
|
11351
|
+
const note = force
|
|
11352
|
+
? `${bin} is a native dev server and cannot execute inside this virtual runtime — using the CodeLab preview server instead.`
|
|
11353
|
+
: `${bin} is not available in this virtual runtime — using the CodeLab preview server instead.`;
|
|
10842
11354
|
return {
|
|
10843
11355
|
code: 0,
|
|
10844
|
-
stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${
|
|
11356
|
+
stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${note}\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
|
|
10845
11357
|
stderr: ''
|
|
10846
11358
|
};
|
|
10847
11359
|
}
|
|
@@ -14940,6 +15452,13 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
14940
15452
|
Object.assign(context.env, this.env);
|
|
14941
15453
|
context.cwd = this.cwd;
|
|
14942
15454
|
}
|
|
15455
|
+
} else if (DIRECT_DEV_TOOL_RE.test(cmdName)) {
|
|
15456
|
+
// A native dev server (vite/ng/astro/…) typed directly. It cannot run in
|
|
15457
|
+
// this runtime — whether or not it was installed — so route it to the
|
|
15458
|
+
// built-in preview server rather than reporting a misleading "command
|
|
15459
|
+
// not found".
|
|
15460
|
+
const fb = tryDevScriptFallback(cmdName, [cmdName, ...args].join(' '), cmdCtx, { force: true });
|
|
15461
|
+
res = fb || { code: 127, stdout: '', stderr: `shell: ${cmdName}: command not found\n` };
|
|
14943
15462
|
} else if (typeof this.options.onProcessSpawn === 'function') {
|
|
14944
15463
|
const spawned = await this.options.onProcessSpawn(cmdName, args, {
|
|
14945
15464
|
cwd: this.cwd,
|
|
@@ -15011,10 +15530,12 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
15011
15530
|
};
|
|
15012
15531
|
});
|
|
15013
15532
|
|
|
15533
|
+
|
|
15014
15534
|
})();
|
|
15015
15535
|
|
|
15016
15536
|
// --- Module 3: PTY Terminal Engine ---
|
|
15017
15537
|
(function () {
|
|
15538
|
+
// @ts-nocheck
|
|
15018
15539
|
/**
|
|
15019
15540
|
* @innovatorved/code-lab - Pure-JS PTY Terminal Emulator Component
|
|
15020
15541
|
*
|
|
@@ -16062,10 +16583,12 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
16062
16583
|
};
|
|
16063
16584
|
});
|
|
16064
16585
|
|
|
16586
|
+
|
|
16065
16587
|
})();
|
|
16066
16588
|
|
|
16067
16589
|
// --- Module 4: IDE Workbench & Web Component ---
|
|
16068
16590
|
(function () {
|
|
16591
|
+
// @ts-nocheck
|
|
16069
16592
|
/* ═══════════════════════════════════════════════════════════════════════════
|
|
16070
16593
|
@innovatorved/code-lab — Interactive Monaco IDE Workbench & Guided Lab UI
|
|
16071
16594
|
Supports <code-lab> Custom Element + window.CodeLab.mount() API
|
|
@@ -16109,6 +16632,10 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
16109
16632
|
const MONACO_BASE = 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs';
|
|
16110
16633
|
const STORAGE_PREFIX = 'sd-codelab-v1:';
|
|
16111
16634
|
|
|
16635
|
+
// The bundler rewrites this literal from package.json at build time. Keeping
|
|
16636
|
+
// the fallback in sync lets tests require src/workbench.js directly.
|
|
16637
|
+
const CODELAB_VERSION = '0.1.7';
|
|
16638
|
+
|
|
16112
16639
|
// Ambient TypeScript declarations for Node.js built-ins inside Monaco
|
|
16113
16640
|
const NODE_AMBIENT_DTS = `
|
|
16114
16641
|
declare var require: (id: string) => any;
|
|
@@ -16445,6 +16972,33 @@ declare module 'bun:sqlite' {
|
|
|
16445
16972
|
.replace(/'/g, ''');
|
|
16446
16973
|
}
|
|
16447
16974
|
|
|
16975
|
+
// Schemes that may appear in a rendered href. Everything else
|
|
16976
|
+
// (javascript:, data:, vbscript:, blob:, file:, ...) becomes a dead link.
|
|
16977
|
+
const SAFE_LINK_SCHEMES = new Set(['http', 'https', 'mailto']);
|
|
16978
|
+
|
|
16979
|
+
function sanitizeUrl(raw) {
|
|
16980
|
+
if (raw === null || raw === undefined) return '#';
|
|
16981
|
+
const trimmed = String(raw).trim();
|
|
16982
|
+
if (!trimmed) return '#';
|
|
16983
|
+
|
|
16984
|
+
// Browsers ignore C0 controls and zero-width characters while resolving a
|
|
16985
|
+
// scheme, so `java\nscript:` and `java\u200Bscript:` still execute. Strip
|
|
16986
|
+
// them before deciding what the scheme is, but return the original value
|
|
16987
|
+
// when it is safe.
|
|
16988
|
+
const normalized = trimmed.replace(/[\u0000-\u0020\u007F\u200B-\u200D\uFEFF]/g, '');
|
|
16989
|
+
const schemeMatch = normalized.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);
|
|
16990
|
+
|
|
16991
|
+
if (!schemeMatch) {
|
|
16992
|
+
// No scheme: a fragment, an absolute path, or a relative path.
|
|
16993
|
+
// Backslashes are treated as slashes by the URL parser and can turn a
|
|
16994
|
+
// "relative" URL into a protocol-relative one, so reject those.
|
|
16995
|
+
if (/^[\\/]{2}/.test(normalized) && !normalized.startsWith('/')) return '#';
|
|
16996
|
+
return trimmed;
|
|
16997
|
+
}
|
|
16998
|
+
|
|
16999
|
+
return SAFE_LINK_SCHEMES.has(schemeMatch[1].toLowerCase()) ? trimmed : '#';
|
|
17000
|
+
}
|
|
17001
|
+
|
|
16448
17002
|
function formatErrorText(err) {
|
|
16449
17003
|
if (!err) return '';
|
|
16450
17004
|
if (typeof err === 'string') return err;
|
|
@@ -16638,14 +17192,9 @@ declare module 'bun:sqlite' {
|
|
|
16638
17192
|
|
|
16639
17193
|
// Markdown Links: [label](url "title") or [label](url)
|
|
16640
17194
|
text = text.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
|
|
16641
|
-
const cleanUrl = url
|
|
17195
|
+
const cleanUrl = sanitizeUrl(url);
|
|
16642
17196
|
const titleAttr = title ? ` title="${escapeHtml(title)}"` : '';
|
|
16643
|
-
return `<a href="${escapeHtml(cleanUrl)}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${label}</a>`;
|
|
16644
|
-
});
|
|
16645
|
-
|
|
16646
|
-
// Autolinks: <https://...>
|
|
16647
|
-
text = text.replace(/<(https?:\/\/[^>]+)>/g, (_, url) => {
|
|
16648
|
-
return `<a href="${escapeHtml(url)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`;
|
|
17197
|
+
return `<a href="${escapeHtml(cleanUrl)}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${escapeHtml(label)}</a>`;
|
|
16649
17198
|
});
|
|
16650
17199
|
|
|
16651
17200
|
// Strikethrough: ~~del~~
|
|
@@ -16840,8 +17389,9 @@ declare module 'bun:sqlite' {
|
|
|
16840
17389
|
// Normalize CRLF to LF
|
|
16841
17390
|
text = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
|
16842
17391
|
|
|
16843
|
-
//
|
|
16844
|
-
|
|
17392
|
+
// NUL delimits internal placeholders. Strip author-supplied NULs so
|
|
17393
|
+
// markdown cannot forge a code-block or autolink placeholder.
|
|
17394
|
+
text = text.replace(/\u0000/g, '');
|
|
16845
17395
|
|
|
16846
17396
|
// Phase 1: Fenced Code Block Extraction
|
|
16847
17397
|
const codeBlocks = [];
|
|
@@ -16864,6 +17414,25 @@ declare module 'bun:sqlite' {
|
|
|
16864
17414
|
return `\x00INLINECODE_${idx}\x00`;
|
|
16865
17415
|
});
|
|
16866
17416
|
|
|
17417
|
+
// Phase 2b: Autolinks are the only inline construct that uses angle
|
|
17418
|
+
// brackets. Extract them before raw HTML is neutralized, then restore the
|
|
17419
|
+
// anchors in Phase 7.
|
|
17420
|
+
const autolinks = [];
|
|
17421
|
+
text = text.replace(/<(https?:\/\/[^>\s]+)>/g, (_, url) => {
|
|
17422
|
+
const idx = autolinks.length;
|
|
17423
|
+
const safe = sanitizeUrl(url);
|
|
17424
|
+
autolinks.push(
|
|
17425
|
+
`<a href="${escapeHtml(safe)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`
|
|
17426
|
+
);
|
|
17427
|
+
return `\x00AUTOLINK_${idx}\x00`;
|
|
17428
|
+
});
|
|
17429
|
+
|
|
17430
|
+
// Phase 2c: Neutralize all remaining raw HTML. Every tag needs a `<`, so
|
|
17431
|
+
// escaping that one character turns any author-supplied markup into text
|
|
17432
|
+
// without disturbing `>` blockquote syntax. From here on, every real tag
|
|
17433
|
+
// in the output is generated by this renderer.
|
|
17434
|
+
text = text.replace(/</g, '<');
|
|
17435
|
+
|
|
16867
17436
|
// Phase 3: GitHub Callout Alerts & Blockquotes
|
|
16868
17437
|
const calloutBlocks = [];
|
|
16869
17438
|
text = text.replace(/(?:^[ \t]*>.*(?:\n|$))+/gm, (match) => {
|
|
@@ -16941,7 +17510,8 @@ declare module 'bun:sqlite' {
|
|
|
16941
17510
|
.replace(/\x00TABLE_(\d+)\x00/g, (_, i) => tableBlocks[Number(i)] || '')
|
|
16942
17511
|
.replace(/\x00CALLOUT_(\d+)\x00/g, (_, i) => calloutBlocks[Number(i)] || '')
|
|
16943
17512
|
.replace(/\x00CODEBLOCK_(\d+)\x00/g, (_, i) => codeBlocks[Number(i)] || '')
|
|
16944
|
-
.replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '')
|
|
17513
|
+
.replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '')
|
|
17514
|
+
.replace(/\x00AUTOLINK_(\d+)\x00/g, (_, i) => autolinks[Number(i)] || '');
|
|
16945
17515
|
|
|
16946
17516
|
return finalHtml;
|
|
16947
17517
|
}
|
|
@@ -17151,24 +17721,102 @@ declare module 'bun:sqlite' {
|
|
|
17151
17721
|
let _workbenchInstanceCounter = 0;
|
|
17152
17722
|
const _fallbackStorage = new Map();
|
|
17153
17723
|
|
|
17154
|
-
|
|
17724
|
+
// CSP for preview HTML assembled in the srcdoc fallback. Mirrors PREVIEW_CSP
|
|
17725
|
+
// in src/preview-sw.js — keep both copies in sync.
|
|
17726
|
+
const PREVIEW_CSP = [
|
|
17727
|
+
"default-src 'self' data: blob:",
|
|
17728
|
+
"base-uri 'self'",
|
|
17729
|
+
"object-src 'none'",
|
|
17730
|
+
"script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:",
|
|
17731
|
+
"style-src 'self' 'unsafe-inline'",
|
|
17732
|
+
"img-src 'self' data: blob:",
|
|
17733
|
+
"font-src 'self' data:",
|
|
17734
|
+
"connect-src 'self' data: blob:",
|
|
17735
|
+
"media-src 'self' data: blob:",
|
|
17736
|
+
"worker-src 'self' blob:",
|
|
17737
|
+
"frame-src 'self' data: blob:",
|
|
17738
|
+
"form-action 'self'",
|
|
17739
|
+
"frame-ancestors 'self'"
|
|
17740
|
+
].join('; ');
|
|
17741
|
+
|
|
17742
|
+
function normalizePreviewOrigin(raw) {
|
|
17743
|
+
if (raw === null || raw === undefined || raw === '') return null;
|
|
17744
|
+
try {
|
|
17745
|
+
const parsed = new URL(String(raw));
|
|
17746
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
|
|
17747
|
+
return parsed.origin;
|
|
17748
|
+
} catch (_) {
|
|
17749
|
+
return null;
|
|
17750
|
+
}
|
|
17751
|
+
}
|
|
17752
|
+
|
|
17753
|
+
const LOG_PREFIX = '[code-lab]';
|
|
17754
|
+
|
|
17755
|
+
// Small leveled logger. Hosts can pass `options.logger` to route diagnostics
|
|
17756
|
+
// into their own telemetry; `options.debug` enables verbose output. Errors
|
|
17757
|
+
// are never silently discarded.
|
|
17758
|
+
function createLogger(options = {}) {
|
|
17759
|
+
const sink = options.logger;
|
|
17760
|
+
const debugEnabled = options.debug === true;
|
|
17761
|
+
|
|
17762
|
+
const write = (level, args) => {
|
|
17763
|
+
if (level === 'debug' && !debugEnabled) return;
|
|
17764
|
+
if (sink && typeof sink[level] === 'function') {
|
|
17765
|
+
try {
|
|
17766
|
+
sink[level](...args);
|
|
17767
|
+
return;
|
|
17768
|
+
} catch (_) {
|
|
17769
|
+
// A broken host logger must not break the IDE; fall through.
|
|
17770
|
+
}
|
|
17771
|
+
}
|
|
17772
|
+
const fn = typeof console !== 'undefined' ? console[level] : null;
|
|
17773
|
+
if (typeof fn === 'function') fn(LOG_PREFIX, ...args);
|
|
17774
|
+
};
|
|
17775
|
+
|
|
17776
|
+
return {
|
|
17777
|
+
debug: (...args) => write('debug', args),
|
|
17778
|
+
info: (...args) => write('info', args),
|
|
17779
|
+
warn: (...args) => write('warn', args),
|
|
17780
|
+
error: (...args) => write('error', args)
|
|
17781
|
+
};
|
|
17782
|
+
}
|
|
17783
|
+
|
|
17784
|
+
const DEFAULT_LOGGER = createLogger();
|
|
17785
|
+
|
|
17786
|
+
function safeStorageGet(key, logger = DEFAULT_LOGGER) {
|
|
17155
17787
|
try {
|
|
17156
17788
|
if (typeof localStorage !== 'undefined' && localStorage !== null) {
|
|
17157
|
-
|
|
17789
|
+
const value = localStorage.getItem(key);
|
|
17790
|
+
if (value !== null && value !== undefined) return value;
|
|
17158
17791
|
}
|
|
17159
|
-
} catch (
|
|
17792
|
+
} catch (err) {
|
|
17793
|
+
logger.warn(
|
|
17794
|
+
`localStorage.getItem("${key}") failed; using in-memory state.`,
|
|
17795
|
+
err && err.message ? err.message : err
|
|
17796
|
+
);
|
|
17797
|
+
}
|
|
17160
17798
|
return _fallbackStorage.has(key) ? _fallbackStorage.get(key) : null;
|
|
17161
17799
|
}
|
|
17162
17800
|
|
|
17163
|
-
function safeStorageSet(key, value) {
|
|
17801
|
+
function safeStorageSet(key, value, logger = DEFAULT_LOGGER) {
|
|
17164
17802
|
const str = String(value);
|
|
17165
17803
|
try {
|
|
17166
17804
|
if (typeof localStorage !== 'undefined' && localStorage !== null) {
|
|
17167
17805
|
localStorage.setItem(key, str);
|
|
17168
|
-
return;
|
|
17806
|
+
return true;
|
|
17169
17807
|
}
|
|
17170
|
-
} catch (
|
|
17808
|
+
} catch (err) {
|
|
17809
|
+
if (!safeStorageSet._warnedKeys) safeStorageSet._warnedKeys = new Set();
|
|
17810
|
+
if (!safeStorageSet._warnedKeys.has(key)) {
|
|
17811
|
+
safeStorageSet._warnedKeys.add(key);
|
|
17812
|
+
logger.warn(
|
|
17813
|
+
`localStorage.setItem("${key}") failed; keeping state in memory for this session.`,
|
|
17814
|
+
err && err.message ? err.message : err
|
|
17815
|
+
);
|
|
17816
|
+
}
|
|
17817
|
+
}
|
|
17171
17818
|
_fallbackStorage.set(key, str);
|
|
17819
|
+
return false;
|
|
17172
17820
|
}
|
|
17173
17821
|
|
|
17174
17822
|
// ── CodeLabWorkbench Instance Class ──────────────────────────────────────
|
|
@@ -17179,12 +17827,22 @@ declare module 'bun:sqlite' {
|
|
|
17179
17827
|
throw new Error('CodeLabWorkbench requires a valid DOM container element.');
|
|
17180
17828
|
}
|
|
17181
17829
|
this.options = options || {};
|
|
17830
|
+
this.logger = createLogger({ logger: options.logger, debug: options.debug });
|
|
17831
|
+
this._persistenceFailureReported = false;
|
|
17182
17832
|
this.instanceId = options.instanceId || (`cl-${++_workbenchInstanceCounter}`);
|
|
17183
17833
|
this.labId = options.id || options.labId || options.buildId || 'custom-lab';
|
|
17184
17834
|
this.title = options.title || this.labId;
|
|
17185
17835
|
this.summary = options.summary || '';
|
|
17186
17836
|
this.monacoUrl = options.monacoUrl || MONACO_BASE;
|
|
17187
17837
|
this.themeOption = options.theme || 'auto'; // 'dark' | 'light' | 'auto'
|
|
17838
|
+
this.previewOrigin = normalizePreviewOrigin(options.previewOrigin);
|
|
17839
|
+
this._previewIsolationWarned = false;
|
|
17840
|
+
if (options.previewOrigin && !this.previewOrigin) {
|
|
17841
|
+
this.logger.warn(
|
|
17842
|
+
'Ignoring invalid `previewOrigin`; expected an absolute http(s) origin ' +
|
|
17843
|
+
'such as "https://preview.example.com".'
|
|
17844
|
+
);
|
|
17845
|
+
}
|
|
17188
17846
|
this.explicitEntry = options.entry || null;
|
|
17189
17847
|
this.explicitTestEntry = options.testEntry || options.testFile || null;
|
|
17190
17848
|
this.backLabel = options.backLabel || 'Back to Build Guide';
|
|
@@ -17522,7 +18180,7 @@ declare module 'bun:sqlite' {
|
|
|
17522
18180
|
const handlers = this._eventListeners.get(key);
|
|
17523
18181
|
if (handlers) {
|
|
17524
18182
|
for (const fn of Array.from(handlers)) {
|
|
17525
|
-
try { fn(detail); } catch (
|
|
18183
|
+
try { fn(detail); } catch (err) { this.logger.error(`Listener for "${key}" threw.`, err); }
|
|
17526
18184
|
}
|
|
17527
18185
|
}
|
|
17528
18186
|
}
|
|
@@ -17556,13 +18214,26 @@ declare module 'bun:sqlite' {
|
|
|
17556
18214
|
return {};
|
|
17557
18215
|
}
|
|
17558
18216
|
try {
|
|
17559
|
-
const raw = safeStorageGet(this._storageKey()) || safeStorageGet('sd_codelab_' + this.labId);
|
|
18217
|
+
const raw = safeStorageGet(this._storageKey(), this.logger) || safeStorageGet('sd_codelab_' + this.labId, this.logger);
|
|
17560
18218
|
return raw ? JSON.parse(raw) : {};
|
|
17561
|
-
} catch {
|
|
18219
|
+
} catch (err) {
|
|
18220
|
+
this.logger.warn(
|
|
18221
|
+
`Ignoring unreadable saved state for "${this.labId}".`,
|
|
18222
|
+
err && err.message ? err.message : err
|
|
18223
|
+
);
|
|
17562
18224
|
return {};
|
|
17563
18225
|
}
|
|
17564
18226
|
}
|
|
17565
18227
|
|
|
18228
|
+
_reportPersistenceFailure() {
|
|
18229
|
+
if (this._persistenceFailureReported) return;
|
|
18230
|
+
this._persistenceFailureReported = true;
|
|
18231
|
+
this.logger.warn(
|
|
18232
|
+
'Workbench state could not be persisted; changes are kept in memory. Export your workspace to keep them.'
|
|
18233
|
+
);
|
|
18234
|
+
this._emitEvent('persistence-error', { labId: this.labId });
|
|
18235
|
+
}
|
|
18236
|
+
|
|
17566
18237
|
_saveState() {
|
|
17567
18238
|
try {
|
|
17568
18239
|
const key = `${this.mode}:${this.lang}`;
|
|
@@ -17587,11 +18258,20 @@ declare module 'bun:sqlite' {
|
|
|
17587
18258
|
return;
|
|
17588
18259
|
}
|
|
17589
18260
|
const serialized = JSON.stringify(state);
|
|
17590
|
-
|
|
17591
|
-
|
|
17592
|
-
|
|
17593
|
-
|
|
17594
|
-
|
|
18261
|
+
const persisted = [
|
|
18262
|
+
safeStorageSet(this._storageKey(), serialized, this.logger),
|
|
18263
|
+
// Sync with host app sidebar & build overview progress trackers
|
|
18264
|
+
safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger),
|
|
18265
|
+
safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger)
|
|
18266
|
+
];
|
|
18267
|
+
if (persisted.includes(false)) this._reportPersistenceFailure();
|
|
18268
|
+
} catch (err) {
|
|
18269
|
+
this.logger.error(
|
|
18270
|
+
'Failed to save workbench state.',
|
|
18271
|
+
err && err.message ? err.message : err
|
|
18272
|
+
);
|
|
18273
|
+
this._reportPersistenceFailure();
|
|
18274
|
+
}
|
|
17595
18275
|
}
|
|
17596
18276
|
|
|
17597
18277
|
_detectPackages() {
|
|
@@ -20156,8 +20836,44 @@ declare module 'bun:sqlite' {
|
|
|
20156
20836
|
return `http://127.0.0.1:${port}${path}`;
|
|
20157
20837
|
}
|
|
20158
20838
|
|
|
20839
|
+
_previewFrameUrl(port, pathAndQuery = '/') {
|
|
20840
|
+
const p = Number(port) || 3000;
|
|
20841
|
+
const rawPath = pathAndQuery || '/';
|
|
20842
|
+
const path = rawPath.startsWith('/') ? rawPath : '/' + rawPath;
|
|
20843
|
+
const base = this.previewOrigin || '';
|
|
20844
|
+
return `${base}/__preview/${p}${path}`;
|
|
20845
|
+
}
|
|
20846
|
+
|
|
20847
|
+
_warnPreviewIsolation() {
|
|
20848
|
+
if (this.previewOrigin || this._previewIsolationWarned) return;
|
|
20849
|
+
this._previewIsolationWarned = true;
|
|
20850
|
+
if (typeof console !== 'undefined' && typeof console.warn === 'function') {
|
|
20851
|
+
console.warn(
|
|
20852
|
+
'[code-lab] Web Preview runs on the host origin and can read host storage. ' +
|
|
20853
|
+
'Pass `previewOrigin: "https://preview.example.com"` to isolate untrusted previews.'
|
|
20854
|
+
);
|
|
20855
|
+
}
|
|
20856
|
+
}
|
|
20857
|
+
|
|
20858
|
+
_injectPreviewCsp(html, port) {
|
|
20859
|
+
if (typeof html !== 'string' || !html) return html;
|
|
20860
|
+
if (/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) return html;
|
|
20861
|
+
|
|
20862
|
+
const tags = `<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}">` +
|
|
20863
|
+
(/<base\b/i.test(html) ? '' : `<base href="/__preview/${Number(port) || 3000}/">`);
|
|
20864
|
+
|
|
20865
|
+
if (/<head\b[^>]*>/i.test(html)) {
|
|
20866
|
+
return html.replace(/<head\b[^>]*>/i, (match) => match + tags);
|
|
20867
|
+
}
|
|
20868
|
+
if (/<html\b[^>]*>/i.test(html)) {
|
|
20869
|
+
return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${tags}</head>`);
|
|
20870
|
+
}
|
|
20871
|
+
return `<head>${tags}</head>${html}`;
|
|
20872
|
+
}
|
|
20873
|
+
|
|
20159
20874
|
_openWebPreview(port, path = '/') {
|
|
20160
20875
|
const p = Number(port) || this._firstListeningPort() || 3000;
|
|
20876
|
+
this._warnPreviewIsolation();
|
|
20161
20877
|
this.previewState.port = p;
|
|
20162
20878
|
this.previewState.path = path || '/';
|
|
20163
20879
|
this.previewState.url = `http://127.0.0.1:${p}${this.previewState.path}`;
|
|
@@ -20336,10 +21052,10 @@ declare module 'bun:sqlite' {
|
|
|
20336
21052
|
|
|
20337
21053
|
_popoutPreview() {
|
|
20338
21054
|
const url = this._previewUrl();
|
|
20339
|
-
let popout = '/
|
|
21055
|
+
let popout = this._previewFrameUrl(this.previewState.port || 3000, '/');
|
|
20340
21056
|
try {
|
|
20341
21057
|
const u = new URL(url);
|
|
20342
|
-
popout =
|
|
21058
|
+
popout = this._previewFrameUrl(u.port, `${u.pathname}${u.search || ''}`);
|
|
20343
21059
|
} catch (_) {}
|
|
20344
21060
|
if (typeof window !== 'undefined' && typeof window.open === 'function') {
|
|
20345
21061
|
try { window.open(popout, '_blank', 'noopener'); } catch (_) {}
|
|
@@ -20349,6 +21065,7 @@ declare module 'bun:sqlite' {
|
|
|
20349
21065
|
|
|
20350
21066
|
_renderWebPreview(bodyEl) {
|
|
20351
21067
|
if (!bodyEl) return;
|
|
21068
|
+
this._warnPreviewIsolation();
|
|
20352
21069
|
const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this._previewSwReady}`;
|
|
20353
21070
|
if (bodyEl.querySelector && bodyEl.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
|
|
20354
21071
|
this._renderWebPreviewControls();
|
|
@@ -20386,7 +21103,7 @@ declare module 'bun:sqlite' {
|
|
|
20386
21103
|
<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>
|
|
20387
21104
|
</div>
|
|
20388
21105
|
<div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
|
|
20389
|
-
<iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-same-origin allow-modals" title="Web Preview"></iframe>
|
|
21106
|
+
<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>
|
|
20390
21107
|
</div>
|
|
20391
21108
|
${servers.length
|
|
20392
21109
|
? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
|
|
@@ -20423,7 +21140,7 @@ declare module 'bun:sqlite' {
|
|
|
20423
21140
|
try {
|
|
20424
21141
|
const u = new URL(fullUrl);
|
|
20425
21142
|
if (typeof iframe.removeAttribute === 'function') iframe.removeAttribute('srcdoc');
|
|
20426
|
-
iframe.setAttribute('src',
|
|
21143
|
+
iframe.setAttribute('src', this._previewFrameUrl(u.port, u.pathname + (u.search || '')));
|
|
20427
21144
|
this.previewState.loading = false;
|
|
20428
21145
|
return Promise.resolve();
|
|
20429
21146
|
} catch (_) {}
|
|
@@ -20435,8 +21152,8 @@ declare module 'bun:sqlite' {
|
|
|
20435
21152
|
.then((res) => {
|
|
20436
21153
|
let body = res.body || '';
|
|
20437
21154
|
const contentType = res.headers['content-type'] || res.headers['Content-Type'] || '';
|
|
20438
|
-
if (/text\/html/i.test(contentType)
|
|
20439
|
-
body =
|
|
21155
|
+
if (/text\/html/i.test(contentType)) {
|
|
21156
|
+
body = this._injectPreviewCsp(body, port);
|
|
20440
21157
|
}
|
|
20441
21158
|
this.previewState.srcdoc = body;
|
|
20442
21159
|
this.previewState.loading = false;
|
|
@@ -20448,7 +21165,7 @@ declare module 'bun:sqlite' {
|
|
|
20448
21165
|
this.previewState.loading = false;
|
|
20449
21166
|
this.previewState.error = String((err && err.message) || err);
|
|
20450
21167
|
const msg = `<body style="font-family:system-ui;padding:24px;color:#888"><h2>Preview unavailable</h2><p>${escapeHtml(this.previewState.error)}</p></body>`;
|
|
20451
|
-
iframe.setAttribute('srcdoc', msg);
|
|
21168
|
+
iframe.setAttribute('srcdoc', this._injectPreviewCsp(msg, port));
|
|
20452
21169
|
});
|
|
20453
21170
|
}
|
|
20454
21171
|
|
|
@@ -20803,7 +21520,7 @@ declare module 'bun:sqlite' {
|
|
|
20803
21520
|
|
|
20804
21521
|
_notifyCodeChange(filename, code) {
|
|
20805
21522
|
if (this.onCodeChange) {
|
|
20806
|
-
try { this.onCodeChange(filename, code); } catch (
|
|
21523
|
+
try { this.onCodeChange(filename, code); } catch (err) { this.logger.error('onCodeChange callback threw.', err); }
|
|
20807
21524
|
}
|
|
20808
21525
|
const detail = { labId: this.labId, filename, path: filename, code, content: code };
|
|
20809
21526
|
this._emitEvent('codelab:change', detail);
|
|
@@ -22442,7 +23159,7 @@ declare module 'bun:sqlite' {
|
|
|
22442
23159
|
}
|
|
22443
23160
|
|
|
22444
23161
|
if (this.onRun) {
|
|
22445
|
-
try { this.onRun(res); } catch (
|
|
23162
|
+
try { this.onRun(res); } catch (err) { this.logger.error('onRun callback threw.', err); }
|
|
22446
23163
|
}
|
|
22447
23164
|
this._emitEvent('codelab:run', { labId: this.labId, mode: 'run', entry, result: res });
|
|
22448
23165
|
} catch (err) {
|
|
@@ -22517,10 +23234,10 @@ declare module 'bun:sqlite' {
|
|
|
22517
23234
|
}
|
|
22518
23235
|
|
|
22519
23236
|
if (this.onTestResult) {
|
|
22520
|
-
try { this.onTestResult(res); } catch (
|
|
23237
|
+
try { this.onTestResult(res); } catch (err) { this.logger.error('onTestResult callback threw.', err); }
|
|
22521
23238
|
}
|
|
22522
23239
|
if (this.onRun) {
|
|
22523
|
-
try { this.onRun(res); } catch (
|
|
23240
|
+
try { this.onRun(res); } catch (err) { this.logger.error('onRun callback threw.', err); }
|
|
22524
23241
|
}
|
|
22525
23242
|
this._emitEvent('codelab:run', { labId: this.labId, mode: 'test', entry, result: res });
|
|
22526
23243
|
|
|
@@ -22534,7 +23251,7 @@ declare module 'bun:sqlite' {
|
|
|
22534
23251
|
this.completedSteps.add(step.id);
|
|
22535
23252
|
newlyCompleted = true;
|
|
22536
23253
|
if (this.onStepComplete) {
|
|
22537
|
-
try { this.onStepComplete(step, sIdx); } catch (
|
|
23254
|
+
try { this.onStepComplete(step, sIdx); } catch (err) { this.logger.error('onStepComplete callback threw.', err); }
|
|
22538
23255
|
}
|
|
22539
23256
|
const stepDetail = {
|
|
22540
23257
|
labId: this.labId,
|
|
@@ -22553,7 +23270,7 @@ declare module 'bun:sqlite' {
|
|
|
22553
23270
|
this._saveState();
|
|
22554
23271
|
if (this.steps.length > 0 && this.completedSteps.size >= this.steps.length) {
|
|
22555
23272
|
if (this.onLabComplete) {
|
|
22556
|
-
try { this.onLabComplete(this.labId); } catch (
|
|
23273
|
+
try { this.onLabComplete(this.labId); } catch (err) { this.logger.error('onLabComplete callback threw.', err); }
|
|
22557
23274
|
}
|
|
22558
23275
|
this._emitEvent('codelab:lab-complete', {
|
|
22559
23276
|
labId: this.labId,
|
|
@@ -22858,7 +23575,12 @@ declare module 'bun:sqlite' {
|
|
|
22858
23575
|
a.click();
|
|
22859
23576
|
setTimeout(() => URL.revokeObjectURL(url), 500);
|
|
22860
23577
|
}
|
|
22861
|
-
} catch (
|
|
23578
|
+
} catch (err) {
|
|
23579
|
+
this.logger.error(
|
|
23580
|
+
`Failed to start download for "${filename}".`,
|
|
23581
|
+
err && err.message ? err.message : err
|
|
23582
|
+
);
|
|
23583
|
+
}
|
|
22862
23584
|
return content;
|
|
22863
23585
|
}
|
|
22864
23586
|
|
|
@@ -22886,7 +23608,12 @@ declare module 'bun:sqlite' {
|
|
|
22886
23608
|
a.click();
|
|
22887
23609
|
setTimeout(() => URL.revokeObjectURL(url), 500);
|
|
22888
23610
|
}
|
|
22889
|
-
} catch (
|
|
23611
|
+
} catch (err) {
|
|
23612
|
+
this.logger.error(
|
|
23613
|
+
'Failed to download workspace export.',
|
|
23614
|
+
err && err.message ? err.message : err
|
|
23615
|
+
);
|
|
23616
|
+
}
|
|
22890
23617
|
}
|
|
22891
23618
|
return snapshot;
|
|
22892
23619
|
}
|
|
@@ -23382,7 +24109,7 @@ declare module 'bun:sqlite' {
|
|
|
23382
24109
|
}
|
|
23383
24110
|
|
|
23384
24111
|
const CodeLabSDK = {
|
|
23385
|
-
version:
|
|
24112
|
+
version: CODELAB_VERSION,
|
|
23386
24113
|
Workbench: CodeLabWorkbench,
|
|
23387
24114
|
CodeLabWorkbench,
|
|
23388
24115
|
CodeLabElement: CodeLabElementClass,
|
|
@@ -23434,6 +24161,7 @@ const executeInWorker = CodeLabRuntime.executeInWorker;
|
|
|
23434
24161
|
const cancelWorkerExecution = CodeLabRuntime.cancelWorkerExecution;
|
|
23435
24162
|
const preloadNpmPackages = CodeLabRuntime.preloadNpmPackages;
|
|
23436
24163
|
const transpileTS = CodeLabRuntime.transpileTS;
|
|
24164
|
+
const transpileForBrowser = CodeLabRuntime.transpileForBrowser;
|
|
23437
24165
|
const createVirtualFs = CodeLabRuntime.createVirtualFs;
|
|
23438
24166
|
const createVirtualHttp = CodeLabRuntime.createVirtualHttp;
|
|
23439
24167
|
const createVirtualNet = CodeLabRuntime.createVirtualNet;
|
|
@@ -23448,7 +24176,11 @@ const PTYTerminalEngine = CodeLabTerminal ? CodeLabTerminal.PTYTerminalEngine :
|
|
|
23448
24176
|
const mount = CodeLab ? CodeLab.mount : null;
|
|
23449
24177
|
const create = CodeLab ? CodeLab.create : null;
|
|
23450
24178
|
const unmount = CodeLab ? CodeLab.unmount : null;
|
|
23451
|
-
const version = CodeLab ? CodeLab.version : '1.
|
|
24179
|
+
const version = CodeLab ? CodeLab.version : '0.1.7';
|
|
24180
|
+
const renderMarkdown = CodeLab ? CodeLab.renderMarkdown : null;
|
|
24181
|
+
const renderSimpleMarkdown = CodeLab ? CodeLab.renderSimpleMarkdown : null;
|
|
24182
|
+
const cloneRepo = CodeLab ? CodeLab.cloneRepo : null;
|
|
24183
|
+
const extensions = CodeLab ? CodeLab.extensions : null;
|
|
23452
24184
|
|
|
23453
24185
|
export {
|
|
23454
24186
|
CodeLab,
|
|
@@ -23465,6 +24197,10 @@ export {
|
|
|
23465
24197
|
create,
|
|
23466
24198
|
unmount,
|
|
23467
24199
|
version,
|
|
24200
|
+
renderMarkdown,
|
|
24201
|
+
renderSimpleMarkdown,
|
|
24202
|
+
cloneRepo,
|
|
24203
|
+
extensions,
|
|
23468
24204
|
createPosixShell,
|
|
23469
24205
|
cloneGitHubRepository,
|
|
23470
24206
|
parseGitHubRepoUrl,
|
|
@@ -23476,6 +24212,7 @@ export {
|
|
|
23476
24212
|
cancelWorkerExecution,
|
|
23477
24213
|
preloadNpmPackages,
|
|
23478
24214
|
transpileTS,
|
|
24215
|
+
transpileForBrowser,
|
|
23479
24216
|
createVirtualFs,
|
|
23480
24217
|
createVirtualHttp,
|
|
23481
24218
|
createVirtualNet,
|