@innovatorved/code-lab 0.1.4 → 0.1.6
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 +2 -1
- package/README.md +4 -2
- package/dist/code-lab.css +49 -0
- package/dist/code-lab.d.ts +3 -1
- package/dist/code-lab.esm.js +1472 -87
- package/dist/code-lab.js +1462 -86
- package/dist/runtime.d.ts +1 -0
- package/dist/runtime.esm.js +783 -32
- package/dist/runtime.js +740 -21
- package/dist/schemas.esm.js +4191 -0
- package/dist/schemas.js +4207 -0
- package/dist/shell.esm.js +657 -64
- package/dist/shell.js +657 -64
- package/dist/terminal.esm.js +7 -1
- package/package.json +9 -4
- package/src/code-lab.css +49 -0
- package/src/runtime.js +740 -21
- package/src/runtime.ts +741 -21
- package/src/shell.js +657 -64
- package/src/shell.ts +657 -64
- package/src/workbench.js +64 -1
- package/src/workbench.ts +64 -1
package/dist/code-lab.esm.js
CHANGED
|
@@ -829,9 +829,78 @@ function __initVirtualRuntime(rootScope) {
|
|
|
829
829
|
crc = CRC32_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
|
|
830
830
|
}
|
|
831
831
|
return (crc ^ 0xffffffff) >>> 0;
|
|
832
|
+
},
|
|
833
|
+
// The full Node zlib constant surface. Packages such as axios read these at
|
|
834
|
+
// module-load time (e.g. `zlib.constants.Z_SYNC_FLUSH`) even when they never
|
|
835
|
+
// actually compress, so a missing table breaks the whole module graph.
|
|
836
|
+
constants: {
|
|
837
|
+
Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4,
|
|
838
|
+
Z_BLOCK: 5, Z_TREES: 6, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1,
|
|
839
|
+
Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_MEM_ERROR: -4, Z_BUF_ERROR: -5,
|
|
840
|
+
Z_VERSION_ERROR: -6, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9,
|
|
841
|
+
Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4,
|
|
842
|
+
Z_DEFAULT_STRATEGY: 0, ZLIB_VERNUM: 0x1310, DEFLATE: 1, INFLATE: 2, GZIP: 3,
|
|
843
|
+
GUNZIP: 4, DEFLATERAW: 5, INFLATERAW: 6, UNZIP: 7, BROTLI_DECODE: 8,
|
|
844
|
+
BROTLI_ENCODE: 9, Z_MIN_WINDOWBITS: 8, Z_MAX_WINDOWBITS: 15,
|
|
845
|
+
Z_DEFAULT_WINDOWBITS: 15, Z_MIN_CHUNK: 64, Z_MAX_CHUNK: Infinity,
|
|
846
|
+
Z_DEFAULT_CHUNK: 16384, Z_MIN_MEMLEVEL: 1, Z_MAX_MEMLEVEL: 9,
|
|
847
|
+
Z_DEFAULT_MEMLEVEL: 8, Z_MIN_LEVEL: -1, Z_MAX_LEVEL: 9, Z_DEFAULT_LEVEL: -1
|
|
832
848
|
}
|
|
833
849
|
};
|
|
834
850
|
|
|
851
|
+
// Compression: delegate to the host's real zlib when the runtime is embedded in
|
|
852
|
+
// Node (same process). In a pure browser worker there is no synchronous zlib, so
|
|
853
|
+
// the async APIs use CompressionStream/DecompressionStream and the *Sync variants
|
|
854
|
+
// throw a descriptive error instead of silently corrupting data.
|
|
855
|
+
(() => {
|
|
856
|
+
let hostZlib = null;
|
|
857
|
+
try { hostZlib = (typeof require === 'function') ? require('zlib') : null; } catch (_) { hostZlib = null; }
|
|
858
|
+
const names = [
|
|
859
|
+
'gzip', 'gunzip', 'deflate', 'inflate', 'deflateRaw', 'inflateRaw', 'unzip',
|
|
860
|
+
'gzipSync', 'gunzipSync', 'deflateSync', 'inflateSync', 'deflateRawSync', 'inflateRawSync', 'unzipSync',
|
|
861
|
+
'createGzip', 'createGunzip', 'createDeflate', 'createInflate', 'createDeflateRaw', 'createInflateRaw'
|
|
862
|
+
];
|
|
863
|
+
if (hostZlib) {
|
|
864
|
+
for (const n of names) {
|
|
865
|
+
if (typeof hostZlib[n] === 'function') VirtualZlib[n] = hostZlib[n].bind(hostZlib);
|
|
866
|
+
}
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
const asyncVariant = (format, kind) => (data, optsOrCb, maybeCb) => {
|
|
870
|
+
const cb = typeof optsOrCb === 'function' ? optsOrCb : (typeof maybeCb === 'function' ? maybeCb : null);
|
|
871
|
+
const p = (async () => {
|
|
872
|
+
if (typeof CompressionStream === 'undefined' || typeof DecompressionStream === 'undefined' || typeof Response === 'undefined') {
|
|
873
|
+
throw new Error('zlib.' + kind + ' is not supported in this environment');
|
|
874
|
+
}
|
|
875
|
+
const decompress = /^(gunzip|unzip|inflate)/.test(kind);
|
|
876
|
+
const stream = decompress ? new DecompressionStream(format) : new CompressionStream(format);
|
|
877
|
+
const writer = stream.writable.getWriter();
|
|
878
|
+
const input = data instanceof Uint8Array ? data : VirtualBuffer.from(data);
|
|
879
|
+
writer.write(input);
|
|
880
|
+
writer.close();
|
|
881
|
+
const ab = await new Response(stream.readable).arrayBuffer();
|
|
882
|
+
return VirtualBuffer.from(ab);
|
|
883
|
+
})();
|
|
884
|
+
if (cb) { p.then((out) => cb(null, out), (err) => cb(err)); return undefined; }
|
|
885
|
+
return p;
|
|
886
|
+
};
|
|
887
|
+
VirtualZlib.gzip = asyncVariant('gzip', 'gzip');
|
|
888
|
+
VirtualZlib.gunzip = asyncVariant('gzip', 'gunzip');
|
|
889
|
+
VirtualZlib.unzip = asyncVariant('gzip', 'unzip');
|
|
890
|
+
VirtualZlib.deflate = asyncVariant('deflate', 'deflate');
|
|
891
|
+
VirtualZlib.inflate = asyncVariant('deflate', 'inflate');
|
|
892
|
+
VirtualZlib.deflateRaw = asyncVariant('deflate-raw', 'deflateRaw');
|
|
893
|
+
VirtualZlib.inflateRaw = asyncVariant('deflate-raw', 'inflateRaw');
|
|
894
|
+
const unsupported = (kind) => () => { throw new Error('zlib.' + kind + ' is not supported in a browser worker (use the async API)'); };
|
|
895
|
+
VirtualZlib.gzipSync = unsupported('gzipSync');
|
|
896
|
+
VirtualZlib.gunzipSync = unsupported('gunzipSync');
|
|
897
|
+
VirtualZlib.deflateSync = unsupported('deflateSync');
|
|
898
|
+
VirtualZlib.inflateSync = unsupported('inflateSync');
|
|
899
|
+
VirtualZlib.deflateRawSync = unsupported('deflateRawSync');
|
|
900
|
+
VirtualZlib.inflateRawSync = unsupported('inflateRawSync');
|
|
901
|
+
VirtualZlib.unzipSync = unsupported('unzipSync');
|
|
902
|
+
})();
|
|
903
|
+
|
|
835
904
|
// =========================================================================
|
|
836
905
|
// 4. PATH & OS SHIMS
|
|
837
906
|
// =========================================================================
|
|
@@ -3974,14 +4043,316 @@ function __initVirtualRuntime(rootScope) {
|
|
|
3974
4043
|
};
|
|
3975
4044
|
}
|
|
3976
4045
|
|
|
4046
|
+
// =========================================================================
|
|
4047
|
+
// 7b. JSX / TSX SUPPORT
|
|
4048
|
+
// -------------------------------------------------------------------------
|
|
4049
|
+
// Rewrites JSX syntax into classic `createElement(...)` calls. This runs
|
|
4050
|
+
// BEFORE the string-masking pass so that JSX text (which routinely contains
|
|
4051
|
+
// quotes/apostrophes, e.g. <p>Don't</p>) is captured verbatim, while genuine
|
|
4052
|
+
// JS strings, comments and template literals are skipped untouched.
|
|
4053
|
+
// =========================================================================
|
|
4054
|
+
function detectJsxSyntax(source, filename) {
|
|
4055
|
+
if (/\.(jsx|tsx)$/i.test(filename || '')) return true;
|
|
4056
|
+
if (!source || source.indexOf('<') === -1) return false;
|
|
4057
|
+
if (/@jsx\b/.test(source)) return true;
|
|
4058
|
+
if (source.indexOf('<>') !== -1) return true;
|
|
4059
|
+
if (/<\/[A-Za-z]/.test(source)) return true;
|
|
4060
|
+
return false;
|
|
4061
|
+
}
|
|
4062
|
+
|
|
4063
|
+
function readJsxPragma(source) {
|
|
4064
|
+
let pragma = 'React.createElement';
|
|
4065
|
+
let frag = null;
|
|
4066
|
+
const m = /@jsx\s+([A-Za-z_$][\w$.]*)/.exec(source);
|
|
4067
|
+
if (m) pragma = m[1];
|
|
4068
|
+
const fm = /@jsxFrag\s+([A-Za-z_$][\w$.]*)/.exec(source);
|
|
4069
|
+
if (fm) frag = fm[1];
|
|
4070
|
+
if (!frag) frag = pragma === 'React.createElement' ? 'React.Fragment' : 'Fragment';
|
|
4071
|
+
return { pragma, frag };
|
|
4072
|
+
}
|
|
4073
|
+
|
|
4074
|
+
const JSX_WS_RE = /\s/;
|
|
4075
|
+
const JSX_NAME_START_RE = /[A-Za-z_$]/;
|
|
4076
|
+
const JSX_NAME_CHAR_RE = /[A-Za-z0-9_$:.\-]/;
|
|
4077
|
+
|
|
4078
|
+
function jsxThrow(message) {
|
|
4079
|
+
const err = new Error(message);
|
|
4080
|
+
err.jsxParse = true;
|
|
4081
|
+
throw err;
|
|
4082
|
+
}
|
|
4083
|
+
|
|
4084
|
+
// Returns the exclusive end index if a JS string / template / comment starts
|
|
4085
|
+
// at `i`, otherwise -1. Regexes are deliberately ignored.
|
|
4086
|
+
function jsxSkipJsLiteral(source, i) {
|
|
4087
|
+
const ch = source[i];
|
|
4088
|
+
const next = source[i + 1];
|
|
4089
|
+
const len = source.length;
|
|
4090
|
+
if (ch === '/' && next === '/') {
|
|
4091
|
+
const e = source.indexOf('\n', i);
|
|
4092
|
+
return e === -1 ? len : e;
|
|
4093
|
+
}
|
|
4094
|
+
if (ch === '/' && next === '*') {
|
|
4095
|
+
const e = source.indexOf('*/', i + 2);
|
|
4096
|
+
return e === -1 ? len : e + 2;
|
|
4097
|
+
}
|
|
4098
|
+
if (ch === '"' || ch === "'") {
|
|
4099
|
+
let j = i + 1;
|
|
4100
|
+
while (j < len) {
|
|
4101
|
+
const c = source[j];
|
|
4102
|
+
if (c === '\\') { j += 2; continue; }
|
|
4103
|
+
if (c === ch) { j++; break; }
|
|
4104
|
+
if (c === '\n') break;
|
|
4105
|
+
j++;
|
|
4106
|
+
}
|
|
4107
|
+
return j;
|
|
4108
|
+
}
|
|
4109
|
+
if (ch === '`') {
|
|
4110
|
+
let j = i + 1;
|
|
4111
|
+
let depth = 0;
|
|
4112
|
+
while (j < len) {
|
|
4113
|
+
const c = source[j];
|
|
4114
|
+
if (c === '\\') { j += 2; continue; }
|
|
4115
|
+
if (c === '$' && source[j + 1] === '{') { depth++; j += 2; continue; }
|
|
4116
|
+
if (c === '}' && depth > 0) { depth--; j++; continue; }
|
|
4117
|
+
if (c === '`' && depth === 0) { j++; break; }
|
|
4118
|
+
j++;
|
|
4119
|
+
}
|
|
4120
|
+
return j;
|
|
4121
|
+
}
|
|
4122
|
+
return -1;
|
|
4123
|
+
}
|
|
4124
|
+
|
|
4125
|
+
function jsxReadName(source, i) {
|
|
4126
|
+
if (!JSX_NAME_START_RE.test(source[i] || '')) jsxThrow('jsx: expected a tag name');
|
|
4127
|
+
let j = i;
|
|
4128
|
+
while (j < source.length && JSX_NAME_CHAR_RE.test(source[j])) j++;
|
|
4129
|
+
return { name: source.slice(i, j), next: j };
|
|
4130
|
+
}
|
|
4131
|
+
|
|
4132
|
+
function jsxSkipWs(source, i) {
|
|
4133
|
+
while (i < source.length && JSX_WS_RE.test(source[i])) i++;
|
|
4134
|
+
return i;
|
|
4135
|
+
}
|
|
4136
|
+
|
|
4137
|
+
function normalizeJsxText(raw) {
|
|
4138
|
+
if (!raw) return '';
|
|
4139
|
+
let t = raw.replace(/\r/g, '');
|
|
4140
|
+
if (t.indexOf('\n') !== -1) {
|
|
4141
|
+
t = t.split('\n').map((s) => s.replace(/[ \t]+/g, ' ').trim()).filter(Boolean).join(' ');
|
|
4142
|
+
} else if (!/\S/.test(t)) {
|
|
4143
|
+
return '';
|
|
4144
|
+
} else {
|
|
4145
|
+
t = t.replace(/[ \t]+/g, ' ');
|
|
4146
|
+
}
|
|
4147
|
+
return t ? JSON.stringify(t) : '';
|
|
4148
|
+
}
|
|
4149
|
+
|
|
4150
|
+
// Reads a balanced `{ ... }` expression container, skipping nested JSX and
|
|
4151
|
+
// JS literals. Returns the raw inner source (later re-transformed) plus the
|
|
4152
|
+
// index just past the closing brace.
|
|
4153
|
+
function jsxReadBraced(source, i, opts) {
|
|
4154
|
+
let depth = 0;
|
|
4155
|
+
let j = i;
|
|
4156
|
+
while (j < source.length) {
|
|
4157
|
+
const lit = jsxSkipJsLiteral(source, j);
|
|
4158
|
+
if (lit !== -1) { j = lit; continue; }
|
|
4159
|
+
const c = source[j];
|
|
4160
|
+
if (c === '{') { depth++; j++; continue; }
|
|
4161
|
+
if (c === '}') {
|
|
4162
|
+
depth--;
|
|
4163
|
+
j++;
|
|
4164
|
+
if (depth === 0) return { inner: source.slice(i + 1, j - 1), next: j };
|
|
4165
|
+
continue;
|
|
4166
|
+
}
|
|
4167
|
+
if (c === '<' && (JSX_NAME_START_RE.test(source[j + 1] || '') || source[j + 1] === '>')) {
|
|
4168
|
+
try {
|
|
4169
|
+
const el = jsxParseElement(source, j, opts);
|
|
4170
|
+
j = el.next;
|
|
4171
|
+
continue;
|
|
4172
|
+
} catch (e) {
|
|
4173
|
+
if (!e || !e.jsxParse) throw e;
|
|
4174
|
+
}
|
|
4175
|
+
}
|
|
4176
|
+
j++;
|
|
4177
|
+
}
|
|
4178
|
+
jsxThrow('jsx: unterminated expression container');
|
|
4179
|
+
}
|
|
4180
|
+
|
|
4181
|
+
function jsxParseElement(source, i, opts) {
|
|
4182
|
+
const o = opts || readJsxPragma(source);
|
|
4183
|
+
let j = i + 1;
|
|
4184
|
+
let isFragment = false;
|
|
4185
|
+
let typeExpr;
|
|
4186
|
+
if (source[j] === '>') {
|
|
4187
|
+
isFragment = true;
|
|
4188
|
+
typeExpr = o.frag;
|
|
4189
|
+
j++;
|
|
4190
|
+
} else {
|
|
4191
|
+
const nm = jsxReadName(source, j);
|
|
4192
|
+
j = nm.next;
|
|
4193
|
+
const raw = nm.name;
|
|
4194
|
+
const isReference = raw.indexOf('.') !== -1 || raw.indexOf(':') !== -1 || /^[A-Z_$]/.test(raw);
|
|
4195
|
+
if (isReference) {
|
|
4196
|
+
typeExpr = raw.replace(/:/g, '.');
|
|
4197
|
+
} else {
|
|
4198
|
+
typeExpr = JSON.stringify(raw);
|
|
4199
|
+
}
|
|
4200
|
+
}
|
|
4201
|
+
|
|
4202
|
+
const props = [];
|
|
4203
|
+
let selfClosing = false;
|
|
4204
|
+
if (!isFragment) {
|
|
4205
|
+
for (;;) {
|
|
4206
|
+
j = jsxSkipWs(source, j);
|
|
4207
|
+
if (j >= source.length) jsxThrow('jsx: unexpected end of input inside a tag');
|
|
4208
|
+
const c = source[j];
|
|
4209
|
+
if (c === '/') {
|
|
4210
|
+
if (source[j + 1] !== '>') jsxThrow('jsx: malformed self-closing tag');
|
|
4211
|
+
j += 2;
|
|
4212
|
+
selfClosing = true;
|
|
4213
|
+
break;
|
|
4214
|
+
}
|
|
4215
|
+
if (c === '>') { j++; break; }
|
|
4216
|
+
if (c === '{') {
|
|
4217
|
+
const br = jsxReadBraced(source, j, o);
|
|
4218
|
+
const inner = br.inner.trim();
|
|
4219
|
+
if (inner.slice(0, 3) !== '...') jsxThrow('jsx: only a spread {...} may appear where an attribute is expected');
|
|
4220
|
+
props.push({ spread: jsxTransform(inner.slice(3), o) });
|
|
4221
|
+
j = br.next;
|
|
4222
|
+
continue;
|
|
4223
|
+
}
|
|
4224
|
+
if (!JSX_NAME_START_RE.test(c)) jsxThrow('jsx: malformed attribute');
|
|
4225
|
+
const am = jsxReadName(source, j);
|
|
4226
|
+
const attrName = am.name;
|
|
4227
|
+
j = jsxSkipWs(source, am.next);
|
|
4228
|
+
let valueExpr = 'true';
|
|
4229
|
+
if (source[j] === '=') {
|
|
4230
|
+
j = jsxSkipWs(source, j + 1);
|
|
4231
|
+
const vc = source[j];
|
|
4232
|
+
if (vc === '"' || vc === "'") {
|
|
4233
|
+
let k = j + 1;
|
|
4234
|
+
while (k < source.length && source[k] !== vc) {
|
|
4235
|
+
if (source[k] === '\\') k++;
|
|
4236
|
+
k++;
|
|
4237
|
+
}
|
|
4238
|
+
if (k >= source.length) jsxThrow('jsx: unterminated attribute string');
|
|
4239
|
+
valueExpr = JSON.stringify(source.slice(j + 1, k));
|
|
4240
|
+
j = k + 1;
|
|
4241
|
+
} else if (vc === '{') {
|
|
4242
|
+
const br = jsxReadBraced(source, j, o);
|
|
4243
|
+
valueExpr = jsxTransform(br.inner, o) || 'undefined';
|
|
4244
|
+
j = br.next;
|
|
4245
|
+
} else if (vc === '<') {
|
|
4246
|
+
const el = jsxParseElement(source, j, o);
|
|
4247
|
+
valueExpr = el.code;
|
|
4248
|
+
j = el.next;
|
|
4249
|
+
} else {
|
|
4250
|
+
jsxThrow('jsx: unsupported attribute value');
|
|
4251
|
+
}
|
|
4252
|
+
}
|
|
4253
|
+
const propKey = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(attrName) ? attrName : JSON.stringify(attrName);
|
|
4254
|
+
props.push({ key: propKey, value: valueExpr });
|
|
4255
|
+
}
|
|
4256
|
+
}
|
|
4257
|
+
|
|
4258
|
+
const children = [];
|
|
4259
|
+
if (!selfClosing) {
|
|
4260
|
+
for (;;) {
|
|
4261
|
+
if (j >= source.length) jsxThrow('jsx: missing closing tag');
|
|
4262
|
+
const c = source[j];
|
|
4263
|
+
if (c === '<' && source[j + 1] === '/') {
|
|
4264
|
+
j = jsxSkipWs(source, j + 2);
|
|
4265
|
+
if (source[j] === '>') { j++; break; }
|
|
4266
|
+
const cm = jsxReadName(source, j);
|
|
4267
|
+
j = jsxSkipWs(source, cm.next);
|
|
4268
|
+
if (source[j] !== '>') jsxThrow('jsx: malformed closing tag');
|
|
4269
|
+
j++;
|
|
4270
|
+
break;
|
|
4271
|
+
}
|
|
4272
|
+
if (c === '<') {
|
|
4273
|
+
const el = jsxParseElement(source, j, o);
|
|
4274
|
+
children.push(el.code);
|
|
4275
|
+
j = el.next;
|
|
4276
|
+
continue;
|
|
4277
|
+
}
|
|
4278
|
+
if (c === '{') {
|
|
4279
|
+
const br = jsxReadBraced(source, j, o);
|
|
4280
|
+
const inner = jsxTransform(br.inner, o);
|
|
4281
|
+
if (inner && inner.trim()) children.push(inner);
|
|
4282
|
+
j = br.next;
|
|
4283
|
+
continue;
|
|
4284
|
+
}
|
|
4285
|
+
let k = j;
|
|
4286
|
+
while (k < source.length && source[k] !== '<' && source[k] !== '{') k++;
|
|
4287
|
+
const text = normalizeJsxText(source.slice(j, k));
|
|
4288
|
+
if (text) children.push(text);
|
|
4289
|
+
j = k;
|
|
4290
|
+
}
|
|
4291
|
+
}
|
|
4292
|
+
|
|
4293
|
+
let propsCode = 'null';
|
|
4294
|
+
if (props.length) {
|
|
4295
|
+
const parts = props.map((p) => (p.spread !== undefined ? '...(' + p.spread + ')' : p.key + ': ' + p.value));
|
|
4296
|
+
propsCode = '{ ' + parts.join(', ') + ' }';
|
|
4297
|
+
}
|
|
4298
|
+
|
|
4299
|
+
const args = [typeExpr, propsCode].concat(children);
|
|
4300
|
+
return { code: o.pragma + '(' + args.join(', ') + ')', next: j };
|
|
4301
|
+
}
|
|
4302
|
+
|
|
4303
|
+
function jsxTransform(source, opts) {
|
|
4304
|
+
const o = opts || readJsxPragma(source);
|
|
4305
|
+
let i = 0;
|
|
4306
|
+
let out = '';
|
|
4307
|
+
while (i < source.length) {
|
|
4308
|
+
const lit = jsxSkipJsLiteral(source, i);
|
|
4309
|
+
if (lit !== -1) { out += source.slice(i, lit); i = lit; continue; }
|
|
4310
|
+
const ch = source[i];
|
|
4311
|
+
if (ch === '<' && (JSX_NAME_START_RE.test(source[i + 1] || '') || source[i + 1] === '>')) {
|
|
4312
|
+
try {
|
|
4313
|
+
const el = jsxParseElement(source, i, o);
|
|
4314
|
+
out += el.code;
|
|
4315
|
+
i = el.next;
|
|
4316
|
+
continue;
|
|
4317
|
+
} catch (e) {
|
|
4318
|
+
if (!e || !e.jsxParse) throw e;
|
|
4319
|
+
}
|
|
4320
|
+
}
|
|
4321
|
+
out += ch;
|
|
4322
|
+
i++;
|
|
4323
|
+
}
|
|
4324
|
+
return out;
|
|
4325
|
+
}
|
|
4326
|
+
|
|
3977
4327
|
// =========================================================================
|
|
3978
4328
|
// 8. FAST TYPESCRIPT & ESM-TO-CJS TRANSPILER
|
|
3979
4329
|
// =========================================================================
|
|
3980
|
-
function transpileTS(source, filename = 'module.ts') {
|
|
4330
|
+
function transpileTS(source, filename = 'module.ts', opts = {}) {
|
|
4331
|
+
// `keepEsm` leaves `import`/`export` statements intact so the output can run
|
|
4332
|
+
// natively in a browser as an ES module (used by the built-in preview server).
|
|
4333
|
+
const keepEsm = Boolean(opts && opts.keepEsm);
|
|
3981
4334
|
const isTS = /\.(ts|tsx|mts|cts)$/i.test(filename)
|
|
3982
|
-
||
|
|
3983
|
-
const hasESM = /^\s*(import|export)\
|
|
3984
|
-
|
|
4335
|
+
|| /^[ \t]*(?:export\s+)?(?:abstract\s+class\s+[A-Za-z_$]|declare\s+(?:const|let|var|function|class|namespace|module|global)\b|interface\s+[A-Za-z_$][A-Za-z0-9_$]*|type\s+[A-Za-z_$][A-Za-z0-9_$]*\s*(?:<[^>]*>)?\s*=|enum\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{|namespace\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{)/m.test(source);
|
|
4336
|
+
const hasESM = /^\s*(?:import|export)\b/m.test(source)
|
|
4337
|
+
|| /\bexport\s*\{/.test(source)
|
|
4338
|
+
|| /\bimport\s*\{/.test(source)
|
|
4339
|
+
|| /\bexport\s+default\b/.test(source);
|
|
4340
|
+
const hasJsx = detectJsxSyntax(source, filename);
|
|
4341
|
+
if (!isTS && !hasESM && !hasJsx) return source;
|
|
4342
|
+
|
|
4343
|
+
// JSX/TSX must be rewritten before masking so JSX text is kept verbatim.
|
|
4344
|
+
if (hasJsx) {
|
|
4345
|
+
const { pragma, frag } = readJsxPragma(source);
|
|
4346
|
+
const needsReact = pragma === 'React.createElement' && !/\bReact\b/.test(source);
|
|
4347
|
+
const transformed = jsxTransform(source, { pragma, frag });
|
|
4348
|
+
if (transformed !== source) {
|
|
4349
|
+
source = transformed;
|
|
4350
|
+
// The classic runtime needs a React binding available to the JSX output.
|
|
4351
|
+
if (needsReact) {
|
|
4352
|
+
source = (keepEsm ? 'import React from "react";\n' : 'const React = require("react");\n') + source;
|
|
4353
|
+
}
|
|
4354
|
+
}
|
|
4355
|
+
}
|
|
3985
4356
|
|
|
3986
4357
|
// Step 1: Mask strings, template literals, regex literals, and comments so transforms never corrupt literals
|
|
3987
4358
|
const placeholders = [];
|
|
@@ -4544,10 +4915,10 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4544
4915
|
} while (code !== prevCode);
|
|
4545
4916
|
}
|
|
4546
4917
|
|
|
4547
|
-
if (hasESM || isTS) {
|
|
4918
|
+
if ((hasESM || isTS) && !keepEsm) {
|
|
4548
4919
|
// Convert ES module imports (including multi-line `{ ... }`)
|
|
4549
|
-
code = code.replace(
|
|
4550
|
-
code = code.replace(
|
|
4920
|
+
code = code.replace(/\bimport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, 'const $1 = require($2);');
|
|
4921
|
+
code = code.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, defId, specifiers, mod) => {
|
|
4551
4922
|
const cleaned = specifiers
|
|
4552
4923
|
.split(',')
|
|
4553
4924
|
.map((s) => s.trim())
|
|
@@ -4558,7 +4929,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4558
4929
|
return `const ${defId} = (function(m){ return m && m.__esModule ? m.default : m; })(require(${mTrim}));` +
|
|
4559
4930
|
(cleaned ? ` const { ${cleaned} } = require(${mTrim});` : '');
|
|
4560
4931
|
});
|
|
4561
|
-
code = code.replace(
|
|
4932
|
+
code = code.replace(/\bimport\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, specifiers, mod) => {
|
|
4562
4933
|
const cleaned = specifiers
|
|
4563
4934
|
.split(',')
|
|
4564
4935
|
.map((s) => s.trim())
|
|
@@ -4567,42 +4938,48 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4567
4938
|
.join(', ');
|
|
4568
4939
|
return cleaned ? `const { ${cleaned} } = require(${mod.trim()});` : '';
|
|
4569
4940
|
});
|
|
4570
|
-
code = code.replace(
|
|
4571
|
-
|
|
4941
|
+
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));');
|
|
4942
|
+
// Dynamic `import("pkg")` — resolve through the CJS loader instead of the
|
|
4943
|
+
// host's dynamic import, which cannot see the virtual filesystem.
|
|
4944
|
+
code = code.replace(/\bimport\s*\(\s*(\x00__LIT_\d+__\x00)\s*\)/g, 'Promise.resolve().then(() => require($1))');
|
|
4945
|
+
// Side-effect import `import"pkg"` / `import "pkg"`. By this point the
|
|
4946
|
+
// specifier is literal-masked, and minified modules emit no whitespace
|
|
4947
|
+
// between `import` and the string, so `\s*` (not `\s+`) is required.
|
|
4948
|
+
code = code.replace(/\bimport\s*(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
|
|
4572
4949
|
|
|
4573
4950
|
// Convert ES module exports
|
|
4574
4951
|
const exportedNames = [];
|
|
4575
4952
|
let defaultExportName = null;
|
|
4576
4953
|
let hasEsmExport = false;
|
|
4577
4954
|
|
|
4578
|
-
code = code.replace(
|
|
4955
|
+
code = code.replace(/\bexport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, (_, ns, mod) => {
|
|
4579
4956
|
hasEsmExport = true;
|
|
4580
4957
|
return `exports.${ns} = require(${mod.trim()});`;
|
|
4581
4958
|
});
|
|
4582
|
-
code = code.replace(
|
|
4959
|
+
code = code.replace(/\bexport\s*\*\s*from\s*([^\n;]+);?/gm, (_, mod) => {
|
|
4583
4960
|
hasEsmExport = true;
|
|
4584
4961
|
return `Object.assign(exports, require(${mod.trim()}));`;
|
|
4585
4962
|
});
|
|
4586
|
-
code = code.replace(
|
|
4963
|
+
code = code.replace(/\bexport\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
|
|
4587
4964
|
hasEsmExport = true;
|
|
4588
4965
|
defaultExportName = name;
|
|
4589
4966
|
return `${kw} ${name}`;
|
|
4590
4967
|
});
|
|
4591
|
-
code = code.replace(
|
|
4968
|
+
code = code.replace(/\bexport\s+default\s+/gm, () => {
|
|
4592
4969
|
hasEsmExport = true;
|
|
4593
4970
|
return 'exports.default = ';
|
|
4594
4971
|
});
|
|
4595
|
-
code = code.replace(
|
|
4972
|
+
code = code.replace(/\bexport\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
|
|
4596
4973
|
hasEsmExport = true;
|
|
4597
4974
|
exportedNames.push(name);
|
|
4598
4975
|
return `${kw} ${name}`;
|
|
4599
4976
|
});
|
|
4600
|
-
code = code.replace(
|
|
4977
|
+
code = code.replace(/\bexport\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
|
|
4601
4978
|
hasEsmExport = true;
|
|
4602
4979
|
exportedNames.push(name);
|
|
4603
4980
|
return `${kw} ${name}`;
|
|
4604
4981
|
});
|
|
4605
|
-
code = code.replace(
|
|
4982
|
+
code = code.replace(/\bexport\s*\{([^}]+)\}\s*from\s*([^\n;]+);?/gm, (_, list, mod) => {
|
|
4606
4983
|
hasEsmExport = true;
|
|
4607
4984
|
const mTrim = mod.trim();
|
|
4608
4985
|
return list.split(',').map((item) => {
|
|
@@ -4614,7 +4991,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4614
4991
|
return `exports.${exported} = require(${mTrim}).${local};`;
|
|
4615
4992
|
}).join(' ');
|
|
4616
4993
|
});
|
|
4617
|
-
code = code.replace(
|
|
4994
|
+
code = code.replace(/\bexport\s*\{([^}]+)\}\s*;?/gm, (_, list) => {
|
|
4618
4995
|
hasEsmExport = true;
|
|
4619
4996
|
return list.split(',').map((item) => {
|
|
4620
4997
|
const trimmed = item.trim();
|
|
@@ -4701,8 +5078,12 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4701
5078
|
const builtinSet = new Set([
|
|
4702
5079
|
'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
|
|
4703
5080
|
'dns', 'dns/promises', 'string_decoder', 'child_process', 'process',
|
|
4704
|
-
'assert', 'assert/strict', 'events', 'util', 'url', 'querystring',
|
|
4705
|
-
'stream', 'stream/promises', '
|
|
5081
|
+
'assert', 'assert/strict', 'events', 'util', 'util/types', 'url', 'querystring',
|
|
5082
|
+
'stream', 'stream/promises', 'stream/web', 'stream/consumers', 'test', 'perf_hooks',
|
|
5083
|
+
'timers', 'timers/promises', 'buffer', 'tty', 'tls', 'dgram', 'readline', 'readline/promises',
|
|
5084
|
+
'async_hooks', 'worker_threads', 'v8', 'vm', 'module', 'constants', 'domain',
|
|
5085
|
+
'diagnostics_channel', 'http2', 'cluster', 'repl', 'inspector', 'trace_events',
|
|
5086
|
+
'wasi', 'console',
|
|
4706
5087
|
'bun', 'bun:test', 'bun:sqlite'
|
|
4707
5088
|
]);
|
|
4708
5089
|
|
|
@@ -6612,6 +6993,285 @@ function __initVirtualRuntime(rootScope) {
|
|
|
6612
6993
|
})();
|
|
6613
6994
|
|
|
6614
6995
|
// Built-in Node module table
|
|
6996
|
+
// ── Additional Node builtin shims ────────────────────────────────────────
|
|
6997
|
+
// Widely-used packages require these at load time (e.g. `debug` requires
|
|
6998
|
+
// `tty`). Without an entry `require('tty')` throws MODULE_NOT_FOUND and the
|
|
6999
|
+
// whole app fails to start. Implementations are deliberately minimal but
|
|
7000
|
+
// shape-compatible; anything that genuinely cannot work in the sandbox
|
|
7001
|
+
// throws an explicit, descriptive error rather than silently misbehaving.
|
|
7002
|
+
const VirtualTty = {
|
|
7003
|
+
isatty() { return false; },
|
|
7004
|
+
ReadStream: class TtyReadStream extends EventEmitter {},
|
|
7005
|
+
WriteStream: class TtyWriteStream extends EventEmitter {
|
|
7006
|
+
constructor(fd) { super(); this.fd = fd; this.columns = 80; this.rows = 24; this.isTTY = false; }
|
|
7007
|
+
getColorDepth() { return 1; }
|
|
7008
|
+
hasColors() { return false; }
|
|
7009
|
+
cursorTo() { return true; }
|
|
7010
|
+
clearLine() { return true; }
|
|
7011
|
+
moveCursor() { return true; }
|
|
7012
|
+
}
|
|
7013
|
+
};
|
|
7014
|
+
|
|
7015
|
+
function makeReadlineInterface() {
|
|
7016
|
+
const iface = new EventEmitter();
|
|
7017
|
+
iface.terminal = false;
|
|
7018
|
+
iface.line = '';
|
|
7019
|
+
iface.cursor = 0;
|
|
7020
|
+
iface.question = (query, cb) => { if (typeof cb === 'function') queueMicrotask(() => cb('')); };
|
|
7021
|
+
iface.prompt = () => {};
|
|
7022
|
+
iface.setPrompt = () => {};
|
|
7023
|
+
iface.getPrompt = () => '';
|
|
7024
|
+
iface.write = () => {};
|
|
7025
|
+
iface.pause = () => iface;
|
|
7026
|
+
iface.resume = () => iface;
|
|
7027
|
+
iface.close = () => { queueMicrotask(() => iface.emit('close')); return iface; };
|
|
7028
|
+
iface[Symbol.asyncIterator] = async function* () {};
|
|
7029
|
+
return iface;
|
|
7030
|
+
}
|
|
7031
|
+
const VirtualReadline = {
|
|
7032
|
+
createInterface: makeReadlineInterface,
|
|
7033
|
+
Interface: class ReadlineInterface extends EventEmitter {},
|
|
7034
|
+
clearLine: () => true,
|
|
7035
|
+
clearScreenDown: () => true,
|
|
7036
|
+
cursorTo: () => true,
|
|
7037
|
+
moveCursor: () => true,
|
|
7038
|
+
emitKeypressEvents: () => {}
|
|
7039
|
+
};
|
|
7040
|
+
const VirtualReadlinePromises = {
|
|
7041
|
+
createInterface: () => {
|
|
7042
|
+
const iface = makeReadlineInterface();
|
|
7043
|
+
iface.question = () => Promise.resolve('');
|
|
7044
|
+
return iface;
|
|
7045
|
+
},
|
|
7046
|
+
Interface: class ReadlinePromisesInterface extends EventEmitter {}
|
|
7047
|
+
};
|
|
7048
|
+
|
|
7049
|
+
const VirtualAsyncHooks = {
|
|
7050
|
+
AsyncLocalStorage: class AsyncLocalStorage {
|
|
7051
|
+
constructor() { this._store = undefined; }
|
|
7052
|
+
getStore() { return this._store; }
|
|
7053
|
+
run(store, fn, ...args) {
|
|
7054
|
+
const prev = this._store;
|
|
7055
|
+
this._store = store;
|
|
7056
|
+
try { return fn(...args); } finally { this._store = prev; }
|
|
7057
|
+
}
|
|
7058
|
+
exit(fn, ...args) {
|
|
7059
|
+
const prev = this._store;
|
|
7060
|
+
this._store = undefined;
|
|
7061
|
+
try { return fn(...args); } finally { this._store = prev; }
|
|
7062
|
+
}
|
|
7063
|
+
enterWith(store) { this._store = store; }
|
|
7064
|
+
disable() { this._store = undefined; }
|
|
7065
|
+
},
|
|
7066
|
+
AsyncResource: class AsyncResource {
|
|
7067
|
+
constructor(type) { this.type = type || 'AsyncResource'; }
|
|
7068
|
+
runInAsyncScope(fn, thisArg, ...args) { return fn.apply(thisArg, args); }
|
|
7069
|
+
emitDestroy() { return this; }
|
|
7070
|
+
asyncId() { return 0; }
|
|
7071
|
+
triggerAsyncId() { return 0; }
|
|
7072
|
+
static bind(fn) { return fn; }
|
|
7073
|
+
},
|
|
7074
|
+
createHook() { return { enable() {}, disable() {} }; },
|
|
7075
|
+
executionAsyncId() { return 0; },
|
|
7076
|
+
triggerAsyncId() { return 0; },
|
|
7077
|
+
executionAsyncResource() { return null; }
|
|
7078
|
+
};
|
|
7079
|
+
|
|
7080
|
+
const VirtualWorkerThreads = {
|
|
7081
|
+
isMainThread: true,
|
|
7082
|
+
threadId: 0,
|
|
7083
|
+
parentPort: null,
|
|
7084
|
+
workerData: null,
|
|
7085
|
+
resourceLimits: {},
|
|
7086
|
+
SHARE_ENV: Symbol('nodejs.worker_threads.SHARE_ENV'),
|
|
7087
|
+
receiveMessageOnPort() { return undefined; },
|
|
7088
|
+
Worker: class Worker extends EventEmitter {
|
|
7089
|
+
constructor(filename) {
|
|
7090
|
+
super();
|
|
7091
|
+
this.threadId = -1;
|
|
7092
|
+
this.filename = filename;
|
|
7093
|
+
queueMicrotask(() => this.emit('error', new Error('worker_threads.Worker is not supported in the virtual runtime.')));
|
|
7094
|
+
}
|
|
7095
|
+
postMessage() {}
|
|
7096
|
+
terminate() { return Promise.resolve(0); }
|
|
7097
|
+
ref() { return this; }
|
|
7098
|
+
unref() { return this; }
|
|
7099
|
+
},
|
|
7100
|
+
MessageChannel: class MessageChannel {},
|
|
7101
|
+
MessagePort: class MessagePort extends EventEmitter {}
|
|
7102
|
+
};
|
|
7103
|
+
|
|
7104
|
+
const VirtualV8 = {
|
|
7105
|
+
serialize(value) { return VirtualBuffer.from(JSON.stringify(value === undefined ? null : value), 'utf8'); },
|
|
7106
|
+
deserialize(buf) { try { return JSON.parse(String(buf)); } catch (_) { return undefined; } },
|
|
7107
|
+
getHeapStatistics() {
|
|
7108
|
+
return {
|
|
7109
|
+
total_heap_size: 0, total_heap_size_executable: 0, total_physical_size: 0,
|
|
7110
|
+
total_available_size: 0, used_heap_size: 0, heap_size_limit: 0,
|
|
7111
|
+
malloced_memory: 0, peak_malloced_memory: 0, does_zap_garbage: 0,
|
|
7112
|
+
number_of_native_contexts: 1, number_of_detached_contexts: 0
|
|
7113
|
+
};
|
|
7114
|
+
},
|
|
7115
|
+
getHeapSpaceStatistics() { return []; },
|
|
7116
|
+
setFlagsFromString() {},
|
|
7117
|
+
cachedDataVersionTag() { return 0; },
|
|
7118
|
+
Serializer: class Serializer {
|
|
7119
|
+
constructor() { this._value = undefined; }
|
|
7120
|
+
writeHeader() {}
|
|
7121
|
+
writeValue(value) { this._value = value; }
|
|
7122
|
+
releaseBuffer() { return VirtualBuffer.from(JSON.stringify(this._value === undefined ? null : this._value), 'utf8'); }
|
|
7123
|
+
},
|
|
7124
|
+
Deserializer: class Deserializer {
|
|
7125
|
+
constructor(buffer) { this._buffer = buffer; }
|
|
7126
|
+
readHeader() { return true; }
|
|
7127
|
+
readValue() { try { return JSON.parse(String(this._buffer)); } catch (_) { return undefined; } }
|
|
7128
|
+
}
|
|
7129
|
+
};
|
|
7130
|
+
|
|
7131
|
+
const VirtualVm = {
|
|
7132
|
+
createContext(sandbox) { return sandbox && typeof sandbox === 'object' ? sandbox : {}; },
|
|
7133
|
+
isContext() { return false; },
|
|
7134
|
+
createScript() { throw new Error('vm code compilation is not supported in the virtual runtime.'); },
|
|
7135
|
+
runInContext() { throw new Error('vm.runInContext is not supported in the virtual runtime.'); },
|
|
7136
|
+
runInNewContext() { throw new Error('vm.runInNewContext is not supported in the virtual runtime.'); },
|
|
7137
|
+
runInThisContext() { throw new Error('vm.runInThisContext is not supported in the virtual runtime.'); },
|
|
7138
|
+
compileFunction() { throw new Error('vm.compileFunction is not supported in the virtual runtime.'); },
|
|
7139
|
+
Script: class Script {
|
|
7140
|
+
runInThisContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
|
|
7141
|
+
runInContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
|
|
7142
|
+
runInNewContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
|
|
7143
|
+
}
|
|
7144
|
+
};
|
|
7145
|
+
|
|
7146
|
+
const VirtualDomain = {
|
|
7147
|
+
create() {
|
|
7148
|
+
const d = new EventEmitter();
|
|
7149
|
+
d.members = [];
|
|
7150
|
+
d.add = () => d;
|
|
7151
|
+
d.remove = () => d;
|
|
7152
|
+
d.bind = (fn) => fn;
|
|
7153
|
+
d.intercept = (fn) => fn;
|
|
7154
|
+
d.run = (fn, ...args) => fn(...args);
|
|
7155
|
+
d.dispose = () => d;
|
|
7156
|
+
return d;
|
|
7157
|
+
},
|
|
7158
|
+
createDomain() { return VirtualDomain.create(); }
|
|
7159
|
+
};
|
|
7160
|
+
|
|
7161
|
+
const VirtualDiagnosticsChannel = {
|
|
7162
|
+
_channels: new Map(),
|
|
7163
|
+
channel(name) {
|
|
7164
|
+
const key = String(name);
|
|
7165
|
+
if (!VirtualDiagnosticsChannel._channels.has(key)) {
|
|
7166
|
+
const ch = new EventEmitter();
|
|
7167
|
+
ch.name = key;
|
|
7168
|
+
ch.hasSubscribers = false;
|
|
7169
|
+
ch.subscribe = () => { ch.hasSubscribers = true; };
|
|
7170
|
+
ch.unsubscribe = () => { ch.hasSubscribers = false; };
|
|
7171
|
+
VirtualDiagnosticsChannel._channels.set(key, ch);
|
|
7172
|
+
}
|
|
7173
|
+
return VirtualDiagnosticsChannel._channels.get(key);
|
|
7174
|
+
},
|
|
7175
|
+
subscribe(name, cb) {
|
|
7176
|
+
const ch = VirtualDiagnosticsChannel.channel(name);
|
|
7177
|
+
ch.subscribe();
|
|
7178
|
+
if (typeof cb === 'function') ch.on('message', cb);
|
|
7179
|
+
},
|
|
7180
|
+
unsubscribe(name) { VirtualDiagnosticsChannel.channel(name).unsubscribe(); },
|
|
7181
|
+
Channel: class Channel extends EventEmitter {}
|
|
7182
|
+
};
|
|
7183
|
+
|
|
7184
|
+
const notSupported = (what) => () => { throw new Error(what + ' is not supported in the virtual runtime.'); };
|
|
7185
|
+
const VirtualTls = {
|
|
7186
|
+
DEFAULT_MIN_VERSION: 'TLSv1.2',
|
|
7187
|
+
DEFAULT_MAX_VERSION: 'TLSv1.3',
|
|
7188
|
+
rootCertificates: [],
|
|
7189
|
+
createSecureContext() { return { context: {} }; },
|
|
7190
|
+
SecureContext: class SecureContext {},
|
|
7191
|
+
TLSSocket: class TLSSocket extends EventEmitter {},
|
|
7192
|
+
Server: class TLSServer extends EventEmitter {},
|
|
7193
|
+
checkServerIdentity() { return undefined; },
|
|
7194
|
+
connect: notSupported('tls.connect'),
|
|
7195
|
+
createServer: notSupported('tls.createServer')
|
|
7196
|
+
};
|
|
7197
|
+
const VirtualDgram = {
|
|
7198
|
+
createSocket(type) {
|
|
7199
|
+
const sock = new EventEmitter();
|
|
7200
|
+
sock.type = type || 'udp4';
|
|
7201
|
+
sock.bind = (...args) => { const cb = args[args.length - 1]; if (typeof cb === 'function') queueMicrotask(cb); return sock; };
|
|
7202
|
+
sock.close = (cb) => { queueMicrotask(() => { sock.emit('close'); if (typeof cb === 'function') cb(); }); return sock; };
|
|
7203
|
+
sock.send = notSupported('dgram.send');
|
|
7204
|
+
sock.address = () => ({ address: '0.0.0.0', family: 'IPv4', port: 0 });
|
|
7205
|
+
sock.setBroadcast = () => sock;
|
|
7206
|
+
sock.setTTL = () => sock;
|
|
7207
|
+
sock.addMembership = () => {};
|
|
7208
|
+
sock.dropMembership = () => {};
|
|
7209
|
+
return sock;
|
|
7210
|
+
},
|
|
7211
|
+
Socket: class Socket extends EventEmitter {}
|
|
7212
|
+
};
|
|
7213
|
+
const VirtualHttp2 = {
|
|
7214
|
+
constants: { NGHTTP2_REFUSED_STREAM: 7, NGHTTP2_CANCEL: 8 },
|
|
7215
|
+
connect: notSupported('http2.connect'),
|
|
7216
|
+
createServer: notSupported('http2.createServer'),
|
|
7217
|
+
createSecureServer: notSupported('http2.createSecureServer')
|
|
7218
|
+
};
|
|
7219
|
+
const VirtualCluster = {
|
|
7220
|
+
isPrimary: true,
|
|
7221
|
+
isMaster: true,
|
|
7222
|
+
isWorker: false,
|
|
7223
|
+
workers: {},
|
|
7224
|
+
fork: notSupported('cluster.fork'),
|
|
7225
|
+
setupPrimary: notSupported('cluster.setupPrimary'),
|
|
7226
|
+
setupMaster: notSupported('cluster.setupMaster'),
|
|
7227
|
+
disconnect: () => {}
|
|
7228
|
+
};
|
|
7229
|
+
const VirtualRepl = { start: notSupported('repl.start') };
|
|
7230
|
+
const VirtualInspector = {
|
|
7231
|
+
open: () => null,
|
|
7232
|
+
close: () => {},
|
|
7233
|
+
url: () => '',
|
|
7234
|
+
Session: class Session { connect() {} disconnect() {} post() {} }
|
|
7235
|
+
};
|
|
7236
|
+
const VirtualTraceEvents = {
|
|
7237
|
+
createTracing: () => ({ enable() {}, disable() {} }),
|
|
7238
|
+
getEnabledCategories: () => ''
|
|
7239
|
+
};
|
|
7240
|
+
const VirtualWasi = {
|
|
7241
|
+
WASI: class WASI { constructor() { throw new Error('wasi is not supported in the virtual runtime.'); } }
|
|
7242
|
+
};
|
|
7243
|
+
|
|
7244
|
+
const VirtualStreamWeb = {
|
|
7245
|
+
ReadableStream: typeof ReadableStream !== 'undefined' ? ReadableStream : undefined,
|
|
7246
|
+
WritableStream: typeof WritableStream !== 'undefined' ? WritableStream : undefined,
|
|
7247
|
+
TransformStream: typeof TransformStream !== 'undefined' ? TransformStream : undefined
|
|
7248
|
+
};
|
|
7249
|
+
async function consumeStream(kind, stream) {
|
|
7250
|
+
const chunks = [];
|
|
7251
|
+
if (stream && typeof stream[Symbol.asyncIterator] === 'function') {
|
|
7252
|
+
for await (const chunk of stream) chunks.push(chunk);
|
|
7253
|
+
} else if (stream && typeof stream.on === 'function') {
|
|
7254
|
+
await new Promise((resolve, reject) => {
|
|
7255
|
+
stream.on('data', (c) => chunks.push(c));
|
|
7256
|
+
stream.on('end', resolve);
|
|
7257
|
+
stream.on('error', reject);
|
|
7258
|
+
});
|
|
7259
|
+
}
|
|
7260
|
+
const bufs = chunks.map((c) => (typeof c === 'string' ? VirtualBuffer.from(c) : VirtualBuffer.from(c)));
|
|
7261
|
+
const buf = VirtualBuffer.concat(bufs);
|
|
7262
|
+
if (kind === 'buffer') return buf;
|
|
7263
|
+
if (kind === 'arrayBuffer') return buf.buffer ? buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) : new ArrayBuffer(0);
|
|
7264
|
+
if (kind === 'text') return buf.toString('utf8');
|
|
7265
|
+
if (kind === 'json') return JSON.parse(buf.toString('utf8'));
|
|
7266
|
+
return buf;
|
|
7267
|
+
}
|
|
7268
|
+
const VirtualStreamConsumers = {
|
|
7269
|
+
text: (s) => consumeStream('text', s),
|
|
7270
|
+
json: (s) => consumeStream('json', s),
|
|
7271
|
+
buffer: (s) => consumeStream('buffer', s),
|
|
7272
|
+
arrayBuffer: (s) => consumeStream('arrayBuffer', s)
|
|
7273
|
+
};
|
|
7274
|
+
|
|
6615
7275
|
const builtinModules = {
|
|
6616
7276
|
fs: vfs,
|
|
6617
7277
|
'node:fs': vfs,
|
|
@@ -6672,9 +7332,59 @@ function __initVirtualRuntime(rootScope) {
|
|
|
6672
7332
|
bun: BunObj,
|
|
6673
7333
|
'node:bun': BunObj,
|
|
6674
7334
|
'bun:test': bunTestModule,
|
|
6675
|
-
'bun:sqlite': { Database: SqliteDatabase }
|
|
7335
|
+
'bun:sqlite': { Database: SqliteDatabase },
|
|
7336
|
+
tty: VirtualTty,
|
|
7337
|
+
tls: VirtualTls,
|
|
7338
|
+
dgram: VirtualDgram,
|
|
7339
|
+
readline: VirtualReadline,
|
|
7340
|
+
'readline/promises': VirtualReadlinePromises,
|
|
7341
|
+
async_hooks: VirtualAsyncHooks,
|
|
7342
|
+
worker_threads: VirtualWorkerThreads,
|
|
7343
|
+
v8: VirtualV8,
|
|
7344
|
+
vm: VirtualVm,
|
|
7345
|
+
domain: VirtualDomain,
|
|
7346
|
+
diagnostics_channel: VirtualDiagnosticsChannel,
|
|
7347
|
+
http2: VirtualHttp2,
|
|
7348
|
+
cluster: VirtualCluster,
|
|
7349
|
+
repl: VirtualRepl,
|
|
7350
|
+
inspector: VirtualInspector,
|
|
7351
|
+
trace_events: VirtualTraceEvents,
|
|
7352
|
+
wasi: VirtualWasi,
|
|
7353
|
+
constants: vfs.constants,
|
|
7354
|
+
'util/types': VirtualUtil.types,
|
|
7355
|
+
'stream/web': VirtualStreamWeb,
|
|
7356
|
+
'stream/consumers': VirtualStreamConsumers
|
|
6676
7357
|
};
|
|
6677
7358
|
|
|
7359
|
+
// Auto-alias every builtin under the `node:` prefix (node:tty, node:readline…)
|
|
7360
|
+
// so both spellings resolve identically without hand-maintaining two lists.
|
|
7361
|
+
for (const __builtinName of Object.keys(builtinModules)) {
|
|
7362
|
+
if (!__builtinName.startsWith('node:') && !__builtinName.startsWith('bun:')) {
|
|
7363
|
+
builtinModules['node:' + __builtinName] = builtinModules[__builtinName];
|
|
7364
|
+
}
|
|
7365
|
+
}
|
|
7366
|
+
|
|
7367
|
+
// `module` must reference the now-complete builtin table, so it is attached
|
|
7368
|
+
// after the object literal above.
|
|
7369
|
+
const VirtualModule = {
|
|
7370
|
+
builtinModules: Object.keys(builtinModules),
|
|
7371
|
+
Module: class Module {},
|
|
7372
|
+
isBuiltin(name) { return Object.prototype.hasOwnProperty.call(builtinModules, String(name)); },
|
|
7373
|
+
createRequire(from) {
|
|
7374
|
+
const base = typeof from === 'string' ? from : '/workspace';
|
|
7375
|
+
const dir = /\.(?:js|mjs|cjs|ts|json)$/.test(base) ? VirtualPath.dirname(base) : base;
|
|
7376
|
+
const req = (id) => {
|
|
7377
|
+
if (Object.prototype.hasOwnProperty.call(builtinModules, id)) return builtinModules[id];
|
|
7378
|
+
return loadModule(resolveModulePath(id, dir), false);
|
|
7379
|
+
};
|
|
7380
|
+
req.resolve = (id) => resolveModulePath(id, dir);
|
|
7381
|
+
req.cache = {};
|
|
7382
|
+
return req;
|
|
7383
|
+
}
|
|
7384
|
+
};
|
|
7385
|
+
builtinModules.module = VirtualModule;
|
|
7386
|
+
builtinModules['node:module'] = VirtualModule;
|
|
7387
|
+
|
|
6678
7388
|
const moduleCache = new Map();
|
|
6679
7389
|
let mainModule = null;
|
|
6680
7390
|
|
|
@@ -7239,6 +7949,14 @@ function __initVirtualRuntime(rootScope) {
|
|
|
7239
7949
|
};
|
|
7240
7950
|
}
|
|
7241
7951
|
|
|
7952
|
+
// Transpile a source file so it can run natively in a browser as an ES module:
|
|
7953
|
+
// JSX is compiled to the classic runtime (auto-importing React when needed) and
|
|
7954
|
+
// TypeScript annotations are stripped, but `import`/`export` are preserved so an
|
|
7955
|
+
// import map can resolve bare specifiers to CDN ESM builds.
|
|
7956
|
+
function transpileForBrowser(source, filename = 'module.js') {
|
|
7957
|
+
return transpileTS(source, filename, { keepEsm: true });
|
|
7958
|
+
}
|
|
7959
|
+
|
|
7242
7960
|
return {
|
|
7243
7961
|
VirtualBuffer,
|
|
7244
7962
|
VirtualCrypto,
|
|
@@ -7258,6 +7976,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
7258
7976
|
createVirtualHttp,
|
|
7259
7977
|
createVirtualNet,
|
|
7260
7978
|
transpileTS,
|
|
7979
|
+
transpileForBrowser,
|
|
7261
7980
|
preloadNpmPackages,
|
|
7262
7981
|
createVirtualPortTable,
|
|
7263
7982
|
executeInVirtualRuntime
|
|
@@ -9906,9 +10625,40 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
9906
10625
|
return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
|
|
9907
10626
|
}
|
|
9908
10627
|
|
|
10628
|
+
function pickConditionalEntry(value) {
|
|
10629
|
+
if (typeof value === 'string') return value;
|
|
10630
|
+
// `exports` subpaths may be an array of fallbacks, e.g.
|
|
10631
|
+
// `"./shams": [{ "types": "...", "default": "./shams.js" }, "./shams.js"]`.
|
|
10632
|
+
if (Array.isArray(value)) {
|
|
10633
|
+
for (const item of value) {
|
|
10634
|
+
const picked = pickConditionalEntry(item);
|
|
10635
|
+
if (picked) return picked;
|
|
10636
|
+
}
|
|
10637
|
+
return null;
|
|
10638
|
+
}
|
|
10639
|
+
if (!value || typeof value !== 'object') return null;
|
|
10640
|
+
// This runtime executes CommonJS, so it prefers CJS-friendly conditions.
|
|
10641
|
+
for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
|
|
10642
|
+
if (value[key] !== undefined) {
|
|
10643
|
+
const picked = pickConditionalEntry(value[key]);
|
|
10644
|
+
if (picked) return picked;
|
|
10645
|
+
}
|
|
10646
|
+
}
|
|
10647
|
+
return null;
|
|
10648
|
+
}
|
|
10649
|
+
|
|
9909
10650
|
function resolveEntryRelPath(pkgJson) {
|
|
9910
|
-
let entry =
|
|
9911
|
-
|
|
10651
|
+
let entry = null;
|
|
10652
|
+
const exp = pkgJson && pkgJson.exports;
|
|
10653
|
+
if (typeof exp === 'string') {
|
|
10654
|
+
entry = exp;
|
|
10655
|
+
} else if (exp && typeof exp === 'object' && exp['.'] !== undefined) {
|
|
10656
|
+
entry = pickConditionalEntry(exp['.']);
|
|
10657
|
+
}
|
|
10658
|
+
if (!entry) {
|
|
10659
|
+
entry = pkgJson.main || pkgJson.module ||
|
|
10660
|
+
(typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
|
|
10661
|
+
}
|
|
9912
10662
|
entry = String(entry).replace(/^[./]+/, '');
|
|
9913
10663
|
return entry || 'index.js';
|
|
9914
10664
|
}
|
|
@@ -9919,9 +10669,16 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
9919
10669
|
|
|
9920
10670
|
function extractRelativeSpecifiers(code) {
|
|
9921
10671
|
const out = new Set();
|
|
9922
|
-
const
|
|
9923
|
-
|
|
9924
|
-
|
|
10672
|
+
const patterns = [
|
|
10673
|
+
/\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
10674
|
+
/\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
10675
|
+
/\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
10676
|
+
/\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g
|
|
10677
|
+
];
|
|
10678
|
+
for (const re of patterns) {
|
|
10679
|
+
let m;
|
|
10680
|
+
while ((m = re.exec(code)) !== null) out.add(m[1]);
|
|
10681
|
+
}
|
|
9925
10682
|
return Array.from(out);
|
|
9926
10683
|
}
|
|
9927
10684
|
|
|
@@ -9935,17 +10692,50 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
9935
10692
|
return parts.join('/');
|
|
9936
10693
|
}
|
|
9937
10694
|
|
|
10695
|
+
// Small promise-based delay. Used only for CDN retry backoff; falls back to an
|
|
10696
|
+
// immediate resolve if `setTimeout` is unavailable in the host.
|
|
10697
|
+
function cdnBackoff(ms) {
|
|
10698
|
+
return new Promise((resolve) => {
|
|
10699
|
+
if (typeof setTimeout === 'function') setTimeout(resolve, ms);
|
|
10700
|
+
else resolve();
|
|
10701
|
+
});
|
|
10702
|
+
}
|
|
10703
|
+
|
|
9938
10704
|
async function fetchTextFromCdn(fetchImpl, url) {
|
|
9939
|
-
|
|
9940
|
-
|
|
9941
|
-
|
|
9942
|
-
|
|
9943
|
-
|
|
9944
|
-
|
|
9945
|
-
|
|
9946
|
-
|
|
9947
|
-
|
|
10705
|
+
// A single flaky jsDelivr response used to silently produce an *incomplete*
|
|
10706
|
+
// install (the module graph then failed at require-time). Retry transient
|
|
10707
|
+
// failures (network error, 429/408, 5xx) but treat 4xx as final.
|
|
10708
|
+
const maxAttempts = 3;
|
|
10709
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
10710
|
+
try {
|
|
10711
|
+
const res = await fetchImpl(url);
|
|
10712
|
+
if (!res) {
|
|
10713
|
+
if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
|
|
10714
|
+
return null;
|
|
10715
|
+
}
|
|
10716
|
+
const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
|
|
10717
|
+
if (!ok) {
|
|
10718
|
+
const transient = res.status >= 500 || res.status === 429 || res.status === 408;
|
|
10719
|
+
if (transient && attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
|
|
10720
|
+
return null;
|
|
10721
|
+
}
|
|
10722
|
+
// jsDelivr answers a *directory* path (e.g. `/pkg@1/libcjs/`) with HTTP 200
|
|
10723
|
+
// and an HTML directory listing. Storing that as a module both corrupts the
|
|
10724
|
+
// package and later collides with the real directory (EISDIR).
|
|
10725
|
+
const contentType = (res.headers && typeof res.headers.get === 'function')
|
|
10726
|
+
? (res.headers.get('content-type') || '')
|
|
10727
|
+
: '';
|
|
10728
|
+
const isHtmlUrl = /\.html?(?:[?#]|$)/i.test(url);
|
|
10729
|
+
if (/text\/html/i.test(contentType) && !isHtmlUrl) return null;
|
|
10730
|
+
const text = typeof res.text === 'function' ? await res.text() : String(res.body != null ? res.body : '');
|
|
10731
|
+
if (!isHtmlUrl && /^\s*(?:<!doctype\s+html|<html[\s>]|<head[\s>])/i.test(text)) return null;
|
|
10732
|
+
return text;
|
|
10733
|
+
} catch (_) {
|
|
10734
|
+
if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
|
|
10735
|
+
return null;
|
|
10736
|
+
}
|
|
9948
10737
|
}
|
|
10738
|
+
return null;
|
|
9949
10739
|
}
|
|
9950
10740
|
|
|
9951
10741
|
async function resolvePackageMetadata(fetchImpl, name, range) {
|
|
@@ -9986,20 +10776,62 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
9986
10776
|
const entry = resolveEntryRelPath(meta);
|
|
9987
10777
|
const files = [];
|
|
9988
10778
|
const visited = new Set();
|
|
9989
|
-
|
|
9990
|
-
|
|
9991
|
-
|
|
9992
|
-
|
|
9993
|
-
|
|
9994
|
-
|
|
9995
|
-
|
|
9996
|
-
|
|
9997
|
-
|
|
9998
|
-
|
|
9999
|
-
|
|
10000
|
-
|
|
10001
|
-
|
|
10002
|
-
|
|
10779
|
+
// Seed with the package entry plus any declared `exports` subpaths, so a
|
|
10780
|
+
// later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
|
|
10781
|
+
// A `main` may point at a *directory* (e.g. chalk: `"main": "source"`); Node
|
|
10782
|
+
// resolves that to `<dir>/index.<ext>`, so those candidates must be seeded
|
|
10783
|
+
// too or the package installs with only its manifest.
|
|
10784
|
+
const seed = [
|
|
10785
|
+
entry,
|
|
10786
|
+
`${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`,
|
|
10787
|
+
`${entry}/index.js`, `${entry}/index.json`, `${entry}/index.mjs`, `${entry}/index.cjs`
|
|
10788
|
+
];
|
|
10789
|
+
const expMap = meta.exports;
|
|
10790
|
+
if (expMap && typeof expMap === 'object') {
|
|
10791
|
+
// Seed *every* declared subpath. A low cap silently dropped the tail of
|
|
10792
|
+
// packages that list each file in `exports` (lit-html has 29 keys, so
|
|
10793
|
+
// `lit-html/is-server.js` was never fetched and `require` failed later).
|
|
10794
|
+
// Wildcard keys (`./*`) need no seeding — their files are reached through
|
|
10795
|
+
// the relative-require closure or fetched on demand.
|
|
10796
|
+
for (const key of Object.keys(expMap)) {
|
|
10797
|
+
if (key === '.' || key.slice(0, 2) !== './' || key.includes('*')) continue;
|
|
10798
|
+
const target = pickConditionalEntry(expMap[key]);
|
|
10799
|
+
if (target) seed.push(target);
|
|
10800
|
+
}
|
|
10801
|
+
}
|
|
10802
|
+
let frontier = seed;
|
|
10803
|
+
while (frontier.length > 0) {
|
|
10804
|
+
const batch = [];
|
|
10805
|
+
for (const raw of frontier) {
|
|
10806
|
+
const rel = stripRelPath(raw);
|
|
10807
|
+
// Directory targets (e.g. `exports["./lib/"] === "./libcjs/"`) must never
|
|
10808
|
+
// be fetched as files — that is what produced the EISDIR crash.
|
|
10809
|
+
if (!rel || rel.endsWith('/') || visited.has(rel)) continue;
|
|
10810
|
+
visited.add(rel);
|
|
10811
|
+
batch.push(rel);
|
|
10812
|
+
}
|
|
10813
|
+
frontier = [];
|
|
10814
|
+
if (batch.length === 0) break;
|
|
10815
|
+
const texts = await Promise.all(
|
|
10816
|
+
batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
|
|
10817
|
+
);
|
|
10818
|
+
for (let idx = 0; idx < batch.length; idx++) {
|
|
10819
|
+
const rel = batch[idx];
|
|
10820
|
+
const text = texts[idx];
|
|
10821
|
+
if (text === null) continue;
|
|
10822
|
+
files.push({ rel, content: text });
|
|
10823
|
+
const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
|
|
10824
|
+
for (const spec of extractRelativeSpecifiers(text)) {
|
|
10825
|
+
const target = normalizeRelPath(baseDir, spec);
|
|
10826
|
+
// Only guess extensions when the specifier omits one; non-existent
|
|
10827
|
+
// candidates 404 harmlessly.
|
|
10828
|
+
const cands = /\.[a-z0-9]+$/i.test(target)
|
|
10829
|
+
? [target]
|
|
10830
|
+
: [target, `${target}.js`, `${target}.json`, `${target}.mjs`, `${target}.cjs`, `${target}/index.js`];
|
|
10831
|
+
for (const cand of cands) {
|
|
10832
|
+
const c = stripRelPath(cand);
|
|
10833
|
+
if (c && !visited.has(c)) frontier.push(cand);
|
|
10834
|
+
}
|
|
10003
10835
|
}
|
|
10004
10836
|
}
|
|
10005
10837
|
}
|
|
@@ -10009,7 +10841,30 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10009
10841
|
if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
|
|
10010
10842
|
}
|
|
10011
10843
|
|
|
10012
|
-
|
|
10844
|
+
// Declared dependencies plus non-optional peer dependencies (npm v7+ style),
|
|
10845
|
+
// so e.g. `npm install react-dom` also pulls in `react`. The *ranges* are
|
|
10846
|
+
// preserved (not just the names) so transitives resolve to the version the
|
|
10847
|
+
// parent actually asked for — e.g. chalk@4 needs ansi-styles@^4, which itself
|
|
10848
|
+
// needs color-convert. Resolving transitive names as "latest" silently breaks
|
|
10849
|
+
// the tree (ansi-styles@6 has no deps at all).
|
|
10850
|
+
const depSpecs = [];
|
|
10851
|
+
const depSeen = new Set();
|
|
10852
|
+
const declared = meta.dependencies || {};
|
|
10853
|
+
for (const depName of Object.keys(declared)) {
|
|
10854
|
+
if (depSeen.has(depName)) continue;
|
|
10855
|
+
depSeen.add(depName);
|
|
10856
|
+
depSpecs.push({ name: depName, range: declared[depName] || null });
|
|
10857
|
+
}
|
|
10858
|
+
const peerMeta = meta.peerDependenciesMeta || {};
|
|
10859
|
+
const peers = meta.peerDependencies || {};
|
|
10860
|
+
for (const peer of Object.keys(peers)) {
|
|
10861
|
+
if (peerMeta[peer] && peerMeta[peer].optional) continue;
|
|
10862
|
+
if (depSeen.has(peer)) continue;
|
|
10863
|
+
depSeen.add(peer);
|
|
10864
|
+
depSpecs.push({ name: peer, range: peers[peer] || null });
|
|
10865
|
+
}
|
|
10866
|
+
|
|
10867
|
+
return { ok: true, version, entry, files, deps: depSpecs, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
|
|
10013
10868
|
}
|
|
10014
10869
|
|
|
10015
10870
|
function installTargetDirs(ctx, name) {
|
|
@@ -10023,24 +10878,43 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10023
10878
|
for (const dir of dirs) {
|
|
10024
10879
|
ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
|
|
10025
10880
|
for (const f of info.files) {
|
|
10881
|
+
if (!f || !f.rel || f.rel.endsWith('/')) continue;
|
|
10026
10882
|
const full = PosixPath.join(dir, f.rel);
|
|
10883
|
+
// Never overwrite a directory with a file body (defensive: a stray
|
|
10884
|
+
// directory target would otherwise raise EISDIR).
|
|
10885
|
+
try {
|
|
10886
|
+
if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
|
|
10887
|
+
} catch (_) {}
|
|
10027
10888
|
ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
|
|
10028
10889
|
ctx.vfs.writeFileSync(full, f.content);
|
|
10029
10890
|
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
|
|
10030
10891
|
}
|
|
10031
10892
|
const modPkgPath = PosixPath.join(dir, 'package.json');
|
|
10032
10893
|
const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
|
|
10894
|
+
if (info.pkgExports && typeof info.pkgExports === 'object') {
|
|
10895
|
+
const normalized = { '.': './' + (info.entry || 'index.js') };
|
|
10896
|
+
for (const key of Object.keys(info.pkgExports)) {
|
|
10897
|
+
if (key === '.' || key.indexOf('*') !== -1) continue;
|
|
10898
|
+
const target = pickConditionalEntry(info.pkgExports[key]);
|
|
10899
|
+
if (target) normalized[key] = target.charAt(0) === '.' ? target : './' + target;
|
|
10900
|
+
}
|
|
10901
|
+
modPkg.exports = normalized;
|
|
10902
|
+
}
|
|
10033
10903
|
ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
|
|
10034
10904
|
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
|
|
10035
10905
|
}
|
|
10036
10906
|
}
|
|
10037
10907
|
|
|
10038
|
-
async function installPackage(pkgSpec, ctx) {
|
|
10908
|
+
async function installPackage(pkgSpec, ctx, onLine, opts) {
|
|
10909
|
+
const options = (onLine && typeof onLine === 'object') ? onLine : (opts || {});
|
|
10910
|
+
const lineCb = (typeof onLine === 'function') ? onLine : (typeof options.onLine === 'function' ? options.onLine : null);
|
|
10911
|
+
const isDev = Boolean(options.dev);
|
|
10039
10912
|
const { name: pkgName, range } = parsePackageSpec(pkgSpec);
|
|
10040
10913
|
if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
|
|
10041
10914
|
|
|
10042
10915
|
const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
10043
|
-
|
|
10916
|
+
const depField = isDev ? 'devDependencies' : 'dependencies';
|
|
10917
|
+
if (!pkgData[depField]) pkgData[depField] = {};
|
|
10044
10918
|
|
|
10045
10919
|
const fetchImpl = packageCtxFetch(ctx);
|
|
10046
10920
|
const seen = (ctx.shell && ctx.shell._cdnSeen)
|
|
@@ -10066,28 +10940,90 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10066
10940
|
});
|
|
10067
10941
|
if (!warning) warning = info.reason;
|
|
10068
10942
|
installed.push({ name: item.name, version: '0.0.0' });
|
|
10943
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: '0.0.0', offline: true });
|
|
10069
10944
|
continue;
|
|
10070
10945
|
}
|
|
10071
10946
|
|
|
10072
10947
|
writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
|
|
10073
10948
|
installed.push({ name: item.name, version: info.version || '1.0.0' });
|
|
10949
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: info.version || '1.0.0', deduped: Boolean(info.deduped) });
|
|
10074
10950
|
if (item.direct) directVersion = info.version || null;
|
|
10075
10951
|
|
|
10076
10952
|
for (const dep of (info.deps || [])) {
|
|
10077
|
-
const
|
|
10078
|
-
|
|
10079
|
-
|
|
10080
|
-
|
|
10953
|
+
const depName = (dep && typeof dep === 'object') ? dep.name : parsePackageSpec(dep).name;
|
|
10954
|
+
const depRange = (dep && typeof dep === 'object') ? dep.range : parsePackageSpec(dep).range;
|
|
10955
|
+
if (depName && !requested.has(depName)) {
|
|
10956
|
+
requested.add(depName);
|
|
10957
|
+
queue.push({ name: depName, range: depRange || null, direct: false });
|
|
10081
10958
|
}
|
|
10082
10959
|
}
|
|
10083
10960
|
}
|
|
10084
10961
|
|
|
10085
|
-
pkgData
|
|
10962
|
+
pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
|
|
10086
10963
|
writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
|
|
10087
10964
|
|
|
10088
10965
|
return { name: pkgName, ok: true, version: directVersion, installed, warning };
|
|
10089
10966
|
}
|
|
10090
10967
|
|
|
10968
|
+
// Build a live install log: each line is streamed to the terminal as it
|
|
10969
|
+
// happens (when possible) and accumulated so the command can also return it.
|
|
10970
|
+
function createInstallEmitter(ctx, sink) {
|
|
10971
|
+
const stream = (ctx && typeof ctx.onStdout === 'function') ? ctx.onStdout : null;
|
|
10972
|
+
return function emit(text) {
|
|
10973
|
+
if (!text) return;
|
|
10974
|
+
sink.push(text);
|
|
10975
|
+
if (stream) stream(text);
|
|
10976
|
+
};
|
|
10977
|
+
}
|
|
10978
|
+
|
|
10979
|
+
function formatInstallLine(info) {
|
|
10980
|
+
if (!info || !info.name) return '';
|
|
10981
|
+
const suffix = info.offline ? ' (offline fallback)' : (info.deduped ? ' (deduped)' : '');
|
|
10982
|
+
return ` + ${info.name}@${info.version || '1.0.0'}${suffix}\n`;
|
|
10983
|
+
}
|
|
10984
|
+
|
|
10985
|
+
function countInstalledPackages(results) {
|
|
10986
|
+
const seen = new Set();
|
|
10987
|
+
for (const r of results) {
|
|
10988
|
+
if (!r) continue;
|
|
10989
|
+
if (r.name) seen.add(r.name);
|
|
10990
|
+
for (const p of (r.installed || [])) { if (p && p.name) seen.add(p.name); }
|
|
10991
|
+
}
|
|
10992
|
+
return seen.size;
|
|
10993
|
+
}
|
|
10994
|
+
|
|
10995
|
+
// Resolve + install a list of specs while printing a realistic transcript,
|
|
10996
|
+
// so `npm install` / `bun add` look like the real tools instead of a terse
|
|
10997
|
+
// "saved N package(s)".
|
|
10998
|
+
async function runInstallTranscript(pkgs, ctx, opts) {
|
|
10999
|
+
const options = opts || {};
|
|
11000
|
+
const manager = options.manager || 'bun';
|
|
11001
|
+
const header = options.header || (manager === 'npm' ? 'npm install v10.2.0' : 'bun add v1.1.20 (1.1.20)');
|
|
11002
|
+
const out = [];
|
|
11003
|
+
const emit = createInstallEmitter(ctx, out);
|
|
11004
|
+
const started = Date.now();
|
|
11005
|
+
emit(`${header}\n\nResolving dependencies...\n`);
|
|
11006
|
+
const results = [];
|
|
11007
|
+
for (const p of pkgs) {
|
|
11008
|
+
results.push(await installPackage(p, ctx, { onLine: (info) => emit(formatInstallLine(info)), dev: Boolean(options.dev) }));
|
|
11009
|
+
}
|
|
11010
|
+
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
11011
|
+
const count = countInstalledPackages(results);
|
|
11012
|
+
const ms = Date.now() - started;
|
|
11013
|
+
if (manager === 'npm') {
|
|
11014
|
+
emit(`\nadded ${count} package(s) in ${ms}ms\n`);
|
|
11015
|
+
} else if (manager === 'pnpm') {
|
|
11016
|
+
emit(`\nPackages: +${count}\n${'+'.repeat(Math.min(count, 40))}\nDone in ${ms}ms using pnpm v9.0.0\n`);
|
|
11017
|
+
} else {
|
|
11018
|
+
emit(`Saved lockfile\n\n${count} package(s) installed [${ms}ms]\n`);
|
|
11019
|
+
}
|
|
11020
|
+
return {
|
|
11021
|
+
code: 0,
|
|
11022
|
+
stdout: out.join(''),
|
|
11023
|
+
stderr: warning ? `${manager === 'npm' ? 'npm warn' : manager === 'pnpm' ? 'pnpm warn' : 'bun warn'} ${warning}\n` : ''
|
|
11024
|
+
};
|
|
11025
|
+
}
|
|
11026
|
+
|
|
10091
11027
|
function uninstallPackage(pkgName, ctx) {
|
|
10092
11028
|
const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
10093
11029
|
let changed = false;
|
|
@@ -10139,9 +11075,269 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
10139
11075
|
if (scriptArgs && scriptArgs.length > 0) {
|
|
10140
11076
|
cmd += ' ' + scriptArgs.join(' ');
|
|
10141
11077
|
}
|
|
11078
|
+
const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
|
|
11079
|
+
if (fallback) return fallback;
|
|
10142
11080
|
return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
|
|
10143
11081
|
}
|
|
10144
11082
|
|
|
11083
|
+
// ---------------------------------------------------------------------------
|
|
11084
|
+
// Built-in static preview server (`serve` / `npm run dev` fallback).
|
|
11085
|
+
//
|
|
11086
|
+
// Serves the virtual filesystem over a virtual port so the in-browser Web
|
|
11087
|
+
// Preview can render a project. `.ts/.tsx/.jsx` sources are transpiled to
|
|
11088
|
+
// browser-native ESM on the fly, and bare specifiers are resolved to jsDelivr
|
|
11089
|
+
// `+esm` builds through an injected import map — no bundler required.
|
|
11090
|
+
// ---------------------------------------------------------------------------
|
|
11091
|
+
|
|
11092
|
+
const CDN_ESM_BASE = 'https://cdn.jsdelivr.net/npm';
|
|
11093
|
+
|
|
11094
|
+
const PREVIEW_MIME = {
|
|
11095
|
+
'.html': 'text/html; charset=utf-8',
|
|
11096
|
+
'.htm': 'text/html; charset=utf-8',
|
|
11097
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
11098
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
11099
|
+
'.cjs': 'text/javascript; charset=utf-8',
|
|
11100
|
+
'.jsx': 'text/javascript; charset=utf-8',
|
|
11101
|
+
'.ts': 'text/javascript; charset=utf-8',
|
|
11102
|
+
'.tsx': 'text/javascript; charset=utf-8',
|
|
11103
|
+
'.css': 'text/css; charset=utf-8',
|
|
11104
|
+
'.json': 'application/json; charset=utf-8',
|
|
11105
|
+
'.map': 'application/json; charset=utf-8',
|
|
11106
|
+
'.svg': 'image/svg+xml',
|
|
11107
|
+
'.png': 'image/png',
|
|
11108
|
+
'.jpg': 'image/jpeg',
|
|
11109
|
+
'.jpeg': 'image/jpeg',
|
|
11110
|
+
'.gif': 'image/gif',
|
|
11111
|
+
'.webp': 'image/webp',
|
|
11112
|
+
'.ico': 'image/x-icon',
|
|
11113
|
+
'.txt': 'text/plain; charset=utf-8'
|
|
11114
|
+
};
|
|
11115
|
+
|
|
11116
|
+
function previewMimeFor(p) {
|
|
11117
|
+
const lower = String(p).toLowerCase();
|
|
11118
|
+
const dot = lower.lastIndexOf('.');
|
|
11119
|
+
if (dot === -1) return 'application/octet-stream';
|
|
11120
|
+
return PREVIEW_MIME[lower.slice(dot)] || 'application/octet-stream';
|
|
11121
|
+
}
|
|
11122
|
+
|
|
11123
|
+
function isPreviewScriptPath(p) {
|
|
11124
|
+
return /\.(?:[cm]?jsx?|tsx?)$/i.test(p) && !/\.d\.ts$/i.test(p);
|
|
11125
|
+
}
|
|
11126
|
+
|
|
11127
|
+
// Collect bare (non-relative) module specifiers referenced by a source file.
|
|
11128
|
+
function extractBareSpecifiers(code) {
|
|
11129
|
+
const out = new Set();
|
|
11130
|
+
const patterns = [
|
|
11131
|
+
/\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
11132
|
+
/\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
11133
|
+
/\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
11134
|
+
/\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g
|
|
11135
|
+
];
|
|
11136
|
+
for (const re of patterns) {
|
|
11137
|
+
let m;
|
|
11138
|
+
while ((m = re.exec(code)) !== null) {
|
|
11139
|
+
const spec = m[1];
|
|
11140
|
+
if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.includes(':')) continue;
|
|
11141
|
+
out.add(spec);
|
|
11142
|
+
}
|
|
11143
|
+
}
|
|
11144
|
+
return Array.from(out);
|
|
11145
|
+
}
|
|
11146
|
+
|
|
11147
|
+
function normalizeVersionRange(range) {
|
|
11148
|
+
if (!range || typeof range !== 'string') return 'latest';
|
|
11149
|
+
const v = range.trim();
|
|
11150
|
+
if (!v || v === '*' || /^(?:latest|next|beta|canary)$/.test(v)) return 'latest';
|
|
11151
|
+
if (/^(?:file|link|workspace|portal|git|https?):/.test(v)) return 'latest';
|
|
11152
|
+
return v.replace(/\s+/g, '').replace(/^[v=\s]+/, '') || 'latest';
|
|
11153
|
+
}
|
|
11154
|
+
|
|
11155
|
+
function resolveBareVersion(vfs, rootDir, pkgName) {
|
|
11156
|
+
try {
|
|
11157
|
+
const modPkg = PosixPath.join(rootDir, 'node_modules', pkgName, 'package.json');
|
|
11158
|
+
if (vfs.existsSync(modPkg)) {
|
|
11159
|
+
const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
|
|
11160
|
+
if (parsed && parsed.version) return parsed.version;
|
|
11161
|
+
}
|
|
11162
|
+
} catch (_) {}
|
|
11163
|
+
try {
|
|
11164
|
+
for (const dir of [rootDir, '/workspace']) {
|
|
11165
|
+
const pkgPath = PosixPath.join(dir, 'package.json');
|
|
11166
|
+
if (!vfs.existsSync(pkgPath)) continue;
|
|
11167
|
+
const parsed = JSON.parse(vfs.readFileSync(pkgPath, 'utf8'));
|
|
11168
|
+
const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
|
|
11169
|
+
if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
|
|
11170
|
+
}
|
|
11171
|
+
} catch (_) {}
|
|
11172
|
+
return 'latest';
|
|
11173
|
+
}
|
|
11174
|
+
|
|
11175
|
+
function cdnEsmUrl(pkgName, version, subpath) {
|
|
11176
|
+
const base = `${CDN_ESM_BASE}/${pkgName}@${version}`;
|
|
11177
|
+
const sub = subpath ? '/' + String(subpath).replace(/^\/+|\/+$/g, '') : '';
|
|
11178
|
+
return `${base}${sub}/+esm`;
|
|
11179
|
+
}
|
|
11180
|
+
|
|
11181
|
+
function buildPreviewImportMap(vfs, rootDir, specifiers) {
|
|
11182
|
+
const imports = {};
|
|
11183
|
+
for (const spec of specifiers) {
|
|
11184
|
+
const parts = String(spec).split('/');
|
|
11185
|
+
const pkgName = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
|
|
11186
|
+
if (!pkgName) continue;
|
|
11187
|
+
const subpath = spec.slice(pkgName.length).replace(/^\/+/, '');
|
|
11188
|
+
const version = resolveBareVersion(vfs, rootDir, pkgName);
|
|
11189
|
+
imports[spec] = cdnEsmUrl(pkgName, version, subpath || undefined);
|
|
11190
|
+
}
|
|
11191
|
+
return imports;
|
|
11192
|
+
}
|
|
11193
|
+
|
|
11194
|
+
function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
|
|
11195
|
+
const scripts = [];
|
|
11196
|
+
const walk = (dir, depth) => {
|
|
11197
|
+
if (depth > 8 || scripts.length >= maxFiles) return;
|
|
11198
|
+
let entries = [];
|
|
11199
|
+
try { entries = vfs.readdirSync(dir); } catch (_) { return; }
|
|
11200
|
+
for (const name of entries) {
|
|
11201
|
+
if (name === 'node_modules' || name.startsWith('.')) continue;
|
|
11202
|
+
const full = PosixPath.join(dir, name);
|
|
11203
|
+
let st;
|
|
11204
|
+
try { st = vfs.statSync(full); } catch (_) { continue; }
|
|
11205
|
+
const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
|
|
11206
|
+
if (dirFlag) {
|
|
11207
|
+
walk(full, depth + 1);
|
|
11208
|
+
} else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
|
|
11209
|
+
try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
|
|
11210
|
+
}
|
|
11211
|
+
}
|
|
11212
|
+
};
|
|
11213
|
+
walk(rootDir, 0);
|
|
11214
|
+
return scripts;
|
|
11215
|
+
}
|
|
11216
|
+
|
|
11217
|
+
function injectPreviewExtras(html, importMap) {
|
|
11218
|
+
let out = html;
|
|
11219
|
+
const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
|
|
11220
|
+
if (/<head[^>]*>/i.test(out)) {
|
|
11221
|
+
out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
|
|
11222
|
+
} else {
|
|
11223
|
+
out = importMapTag + '\n' + out;
|
|
11224
|
+
}
|
|
11225
|
+
const shim = '<script>window.__CODELAB_PREVIEW__ = true;</script>';
|
|
11226
|
+
if (/<\/body>/i.test(out)) out = out.replace(/<\/body>/i, `${shim}\n</body>`);
|
|
11227
|
+
else out = out + '\n' + shim;
|
|
11228
|
+
return out;
|
|
11229
|
+
}
|
|
11230
|
+
|
|
11231
|
+
function registerPreviewServer(ctx, rootDir, preferredPort) {
|
|
11232
|
+
const portTable = ctx.shell && ctx.shell.portTable;
|
|
11233
|
+
if (!portTable || typeof portTable.registerServer !== 'function') return null;
|
|
11234
|
+
|
|
11235
|
+
let port = Number(preferredPort) || 3000;
|
|
11236
|
+
const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
|
|
11237
|
+
while (taken.has(port)) port++;
|
|
11238
|
+
|
|
11239
|
+
const specifiers = new Set();
|
|
11240
|
+
for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
|
|
11241
|
+
for (const s of extractBareSpecifiers(content)) specifiers.add(s);
|
|
11242
|
+
}
|
|
11243
|
+
const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
|
|
11244
|
+
|
|
11245
|
+
const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
|
|
11246
|
+
const isDir = (p) => {
|
|
11247
|
+
try {
|
|
11248
|
+
const st = ctx.vfs.statSync(p);
|
|
11249
|
+
return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
|
|
11250
|
+
} catch (_) { return false; }
|
|
11251
|
+
};
|
|
11252
|
+
const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
|
|
11253
|
+
|
|
11254
|
+
const handler = async (request) => {
|
|
11255
|
+
let pathname = '/';
|
|
11256
|
+
try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
|
|
11257
|
+
const rel = pathname.replace(/^\/+/, '');
|
|
11258
|
+
let target = PosixPath.join(rootDir, rel);
|
|
11259
|
+
const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
|
|
11260
|
+
|
|
11261
|
+
if (!rel || pathname.endsWith('/') || isDir(target)) {
|
|
11262
|
+
target = PosixPath.join(target, 'index.html');
|
|
11263
|
+
}
|
|
11264
|
+
if (!exists(target) && !hasExt) {
|
|
11265
|
+
// Resolve extensionless module specifiers (e.g. `./components/Counter`)
|
|
11266
|
+
// the way a bundler / dev server would.
|
|
11267
|
+
const cands = [
|
|
11268
|
+
target + '.tsx', target + '.ts', target + '.jsx', target + '.js',
|
|
11269
|
+
target + '.mjs', target + '.cjs',
|
|
11270
|
+
PosixPath.join(target, 'index.tsx'), PosixPath.join(target, 'index.ts'),
|
|
11271
|
+
PosixPath.join(target, 'index.jsx'), PosixPath.join(target, 'index.js')
|
|
11272
|
+
];
|
|
11273
|
+
for (const c of cands) { if (exists(c)) { target = c; break; } }
|
|
11274
|
+
}
|
|
11275
|
+
if (!exists(target) && !hasExt) {
|
|
11276
|
+
target = PosixPath.join(rootDir, 'index.html'); // SPA fallback
|
|
11277
|
+
}
|
|
11278
|
+
if (!exists(target)) {
|
|
11279
|
+
return new Response(
|
|
11280
|
+
`<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
|
|
11281
|
+
{ status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
|
|
11282
|
+
);
|
|
11283
|
+
}
|
|
11284
|
+
|
|
11285
|
+
let body = readText(target);
|
|
11286
|
+
if (body === null) body = '';
|
|
11287
|
+
if (/\.html?$/i.test(target)) {
|
|
11288
|
+
body = injectPreviewExtras(body, importMap);
|
|
11289
|
+
} else if (isPreviewScriptPath(target)) {
|
|
11290
|
+
try {
|
|
11291
|
+
const rm = getRuntimeModule();
|
|
11292
|
+
if (rm && typeof rm.transpileForBrowser === 'function') {
|
|
11293
|
+
body = rm.transpileForBrowser(body, target);
|
|
11294
|
+
}
|
|
11295
|
+
} catch (_) {}
|
|
11296
|
+
}
|
|
11297
|
+
|
|
11298
|
+
return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
|
|
11299
|
+
};
|
|
11300
|
+
|
|
11301
|
+
const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
|
|
11302
|
+
return portTable.registerServer(port, {
|
|
11303
|
+
server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
|
|
11304
|
+
fetch: handler,
|
|
11305
|
+
name: 'code-lab-serve',
|
|
11306
|
+
pid,
|
|
11307
|
+
root: rootDir
|
|
11308
|
+
});
|
|
11309
|
+
}
|
|
11310
|
+
|
|
11311
|
+
// Common dev-server commands that cannot run inside the virtual runtime are
|
|
11312
|
+
// transparently redirected to the built-in preview server.
|
|
11313
|
+
const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
|
|
11314
|
+
// The same tools, when typed directly at the prompt (`ng serve`, `vite`).
|
|
11315
|
+
// `serve` is omitted: it is a first-class builtin shell command.
|
|
11316
|
+
const DIRECT_DEV_TOOL_RE = /^(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|http-server)$/;
|
|
11317
|
+
|
|
11318
|
+
function tryDevScriptFallback(scriptName, cmd, ctx, opts) {
|
|
11319
|
+
if (!PREVIEW_TOOL_RE.test(cmd)) return null;
|
|
11320
|
+
// Only fall back when the referenced tool is not actually installed.
|
|
11321
|
+
const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
|
|
11322
|
+
const force = Boolean(opts && opts.force);
|
|
11323
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
|
|
11324
|
+
if (!force && ctx.vfs.existsSync(binPath)) return null;
|
|
11325
|
+
const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
|
|
11326
|
+
const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
|
|
11327
|
+
const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
|
|
11328
|
+
const rootDir = typeof ctx.resolvePath === 'function' ? ctx.resolvePath('.') : (ctx.cwd || '/workspace');
|
|
11329
|
+
const entry = registerPreviewServer(ctx, rootDir, port);
|
|
11330
|
+
if (!entry) return null;
|
|
11331
|
+
const note = force
|
|
11332
|
+
? `${bin} is a native dev server and cannot execute inside this virtual runtime — using the CodeLab preview server instead.`
|
|
11333
|
+
: `${bin} is not available in this virtual runtime — using the CodeLab preview server instead.`;
|
|
11334
|
+
return {
|
|
11335
|
+
code: 0,
|
|
11336
|
+
stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${note}\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
|
|
11337
|
+
stderr: ''
|
|
11338
|
+
};
|
|
11339
|
+
}
|
|
11340
|
+
|
|
10145
11341
|
function evaluatePosixTest(args, ctx) {
|
|
10146
11342
|
const cleanArgs = [...args];
|
|
10147
11343
|
if (cleanArgs.length > 0 && cleanArgs[cleanArgs.length - 1] === ']') {
|
|
@@ -12640,7 +13836,8 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
12640
13836
|
stdout += ' date, sleep, clear Date, delay, terminal screen control\n';
|
|
12641
13837
|
stdout += ' history, ps, jobs, kill Process and job management\n';
|
|
12642
13838
|
stdout += ' git [status diff log] Built-in version control\n';
|
|
12643
|
-
stdout += ' node, bun, npm, npx, bunx CLI runtime and package shims\n';
|
|
13839
|
+
stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
|
|
13840
|
+
stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
|
|
12644
13841
|
stdout += ' ports, curl Port table inspection & HTTP requests\n';
|
|
12645
13842
|
return { code: 0, stdout, stderr: '' };
|
|
12646
13843
|
},
|
|
@@ -12825,26 +14022,25 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
12825
14022
|
|
|
12826
14023
|
if (sub === 'install' || sub === 'i' || sub === 'ci') {
|
|
12827
14024
|
const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
14025
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
12828
14026
|
if (pkgs.length === 0) {
|
|
12829
14027
|
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
12830
|
-
const deps = Object.keys(pkgData.dependencies || {});
|
|
12831
|
-
|
|
12832
|
-
|
|
12833
|
-
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
12834
|
-
return { code: 0, stdout: deps.length === 0 ? 'up to date\n' : `installed ${deps.length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
|
|
14028
|
+
const deps = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
14029
|
+
if (deps.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
14030
|
+
return await runInstallTranscript(deps, ctx, { manager: 'bun', header: 'bun install v1.1.20 (1.1.20)' });
|
|
12835
14031
|
}
|
|
12836
|
-
|
|
12837
|
-
for (const p of pkgs) results.push(await installPackage(p, ctx));
|
|
12838
|
-
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
12839
|
-
return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
|
|
14032
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
12840
14033
|
}
|
|
12841
14034
|
|
|
12842
14035
|
if (sub === 'add') {
|
|
12843
|
-
|
|
12844
|
-
const
|
|
12845
|
-
|
|
12846
|
-
|
|
12847
|
-
|
|
14036
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
14037
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
14038
|
+
if (pkgs.length === 0) {
|
|
14039
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
14040
|
+
pkgs = Object.keys(pkgData.dependencies || {});
|
|
14041
|
+
}
|
|
14042
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
14043
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
12848
14044
|
}
|
|
12849
14045
|
|
|
12850
14046
|
if (sub === 'remove' || sub === 'rm') {
|
|
@@ -13004,22 +14200,14 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
13004
14200
|
}
|
|
13005
14201
|
|
|
13006
14202
|
if (sub === 'i' || sub === 'install' || sub === 'add') {
|
|
13007
|
-
|
|
14203
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
14204
|
+
const dev = args.some(a => a === '-D' || a === '--save-dev' || a === '--dev');
|
|
13008
14205
|
if (pkgs.length === 0) {
|
|
13009
14206
|
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
13010
|
-
|
|
13011
|
-
|
|
13012
|
-
results.push(await installPackage(p, ctx));
|
|
13013
|
-
}
|
|
13014
|
-
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
13015
|
-
return { code: 0, stdout: 'up to date\n', stderr: warning ? `npm warn ${warning}\n` : '' };
|
|
14207
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
14208
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
13016
14209
|
}
|
|
13017
|
-
|
|
13018
|
-
for (const p of pkgs) {
|
|
13019
|
-
results.push(await installPackage(p, ctx));
|
|
13020
|
-
}
|
|
13021
|
-
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
13022
|
-
return { code: 0, stdout: `added ${results.filter(r => r && r.name).length} package(s) in 0.1s\n`, stderr: warning ? `npm warn ${warning}\n` : '' };
|
|
14210
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'npm', dev, header: 'npm install v10.2.0' });
|
|
13023
14211
|
}
|
|
13024
14212
|
|
|
13025
14213
|
if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
|
|
@@ -13071,6 +14259,123 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
13071
14259
|
return await this.npx(args, ctx);
|
|
13072
14260
|
},
|
|
13073
14261
|
|
|
14262
|
+
async pnpm(args, ctx) {
|
|
14263
|
+
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
|
14264
|
+
return {
|
|
14265
|
+
code: 0,
|
|
14266
|
+
stdout: 'pnpm v9.0.0\nUsage: pnpm <command>\n\nCommands:\n install, i Install all dependencies\n add <pkg> Add a dependency (-D for dev)\n remove, rm Remove a dependency\n list, ls List dependencies\n run <script> Run a package script\n exec <cmd> Run a command from node_modules/.bin\n dlx <pkg> Fetch and run a package\n --version, -v Print the version\n',
|
|
14267
|
+
stderr: ''
|
|
14268
|
+
};
|
|
14269
|
+
}
|
|
14270
|
+
const sub = args[0];
|
|
14271
|
+
if (sub === '--version' || sub === '-v') {
|
|
14272
|
+
return { code: 0, stdout: '9.0.0\n', stderr: '' };
|
|
14273
|
+
}
|
|
14274
|
+
const dev = args.some((a) => a === '-D' || a === '--save-dev' || a === '--dev' || a === '-d');
|
|
14275
|
+
|
|
14276
|
+
if (sub === 'init') {
|
|
14277
|
+
const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
|
|
14278
|
+
if (!ctx.vfs.existsSync(pkgPath)) {
|
|
14279
|
+
ctx.vfs.writeFileSync(pkgPath, JSON.stringify({
|
|
14280
|
+
name: PosixPath.basename(ctx.cwd) || 'app',
|
|
14281
|
+
version: '1.0.0',
|
|
14282
|
+
main: 'index.js',
|
|
14283
|
+
scripts: { test: 'echo "Error: no test specified" && exit 1' }
|
|
14284
|
+
}, null, 2) + '\n');
|
|
14285
|
+
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', pkgPath);
|
|
14286
|
+
}
|
|
14287
|
+
return { code: 0, stdout: 'Wrote to ' + pkgPath + '\n', stderr: '' };
|
|
14288
|
+
}
|
|
14289
|
+
|
|
14290
|
+
if (sub === 'install' || sub === 'i' || sub === 'add') {
|
|
14291
|
+
let pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
14292
|
+
if (pkgs.length === 0) {
|
|
14293
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
14294
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
14295
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'Already up to date\n', stderr: '' };
|
|
14296
|
+
}
|
|
14297
|
+
const verb = (sub === 'add') ? 'add' : 'install';
|
|
14298
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'pnpm', dev, header: `pnpm ${verb} v9.0.0` });
|
|
14299
|
+
}
|
|
14300
|
+
|
|
14301
|
+
if (sub === 'remove' || sub === 'rm' || sub === 'uninstall') {
|
|
14302
|
+
const pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
14303
|
+
for (const p of pkgs) uninstallPackage(p, ctx);
|
|
14304
|
+
return { code: 0, stdout: `removed ${pkgs.length} package(s)\n`, stderr: '' };
|
|
14305
|
+
}
|
|
14306
|
+
|
|
14307
|
+
if (sub === 'list' || sub === 'ls') {
|
|
14308
|
+
return { code: 0, stdout: listDependencies(ctx), stderr: '' };
|
|
14309
|
+
}
|
|
14310
|
+
|
|
14311
|
+
if (sub === 'run' || sub === 'run-script') {
|
|
14312
|
+
const scriptName = args[1];
|
|
14313
|
+
if (!scriptName) return { code: 1, stdout: '', stderr: 'pnpm: missing script name\n' };
|
|
14314
|
+
return await runPackageScript(scriptName, args.slice(2), ctx);
|
|
14315
|
+
}
|
|
14316
|
+
|
|
14317
|
+
if (sub === 'test') {
|
|
14318
|
+
return await runPackageScript('test', args.slice(1), ctx);
|
|
14319
|
+
}
|
|
14320
|
+
|
|
14321
|
+
if (sub === 'exec') {
|
|
14322
|
+
const cmd = args[1];
|
|
14323
|
+
if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
|
|
14324
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
|
|
14325
|
+
if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
|
|
14326
|
+
return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
|
|
14327
|
+
}
|
|
14328
|
+
|
|
14329
|
+
if (sub === 'dlx') {
|
|
14330
|
+
return await this.npx(args.slice(1), ctx);
|
|
14331
|
+
}
|
|
14332
|
+
|
|
14333
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
14334
|
+
if (pkgData.scripts && pkgData.scripts[sub]) {
|
|
14335
|
+
return await runPackageScript(sub, args.slice(1), ctx);
|
|
14336
|
+
}
|
|
14337
|
+
|
|
14338
|
+
return { code: 1, stdout: '', stderr: `ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Unknown command: "${sub}"\n` };
|
|
14339
|
+
},
|
|
14340
|
+
|
|
14341
|
+
async serve(args, ctx) {
|
|
14342
|
+
if (args[0] === '--help' || args[0] === '-h') {
|
|
14343
|
+
return {
|
|
14344
|
+
code: 0,
|
|
14345
|
+
stdout: 'Usage: serve [dir] [--port <n>]\n\n Starts the built-in CodeLab preview server on the virtual port table.\n HTML/CSS/JS are served statically, .ts/.tsx/.jsx are transpiled to\n browser-native ESM on the fly, and bare imports resolve to jsDelivr ESM.\n\n Open the Web Preview drawer (or http://127.0.0.1:<port>/) to view it.\n',
|
|
14346
|
+
stderr: ''
|
|
14347
|
+
};
|
|
14348
|
+
}
|
|
14349
|
+
const rootArg = (() => {
|
|
14350
|
+
const positionals = [];
|
|
14351
|
+
for (let i = 0; i < args.length; i++) {
|
|
14352
|
+
const a = args[i];
|
|
14353
|
+
if (a === '--port' || a === '-p') { i++; continue; }
|
|
14354
|
+
if (a.startsWith('-')) continue;
|
|
14355
|
+
positionals.push(a);
|
|
14356
|
+
}
|
|
14357
|
+
return positionals[0];
|
|
14358
|
+
})();
|
|
14359
|
+
let port = 3000;
|
|
14360
|
+
for (let i = 0; i < args.length; i++) {
|
|
14361
|
+
if ((args[i] === '--port' || args[i] === '-p') && args[i + 1]) { port = Number(args[i + 1]) || port; i++; }
|
|
14362
|
+
else if (args[i].startsWith('--port=')) port = Number(args[i].split('=')[1]) || port;
|
|
14363
|
+
}
|
|
14364
|
+
const rootDir = ctx.resolvePath(rootArg || '.');
|
|
14365
|
+
if (!ctx.vfs.existsSync(rootDir)) {
|
|
14366
|
+
return { code: 1, stdout: '', stderr: `serve: ${rootArg}: No such file or directory\n` };
|
|
14367
|
+
}
|
|
14368
|
+
const entry = registerPreviewServer(ctx, rootDir, port);
|
|
14369
|
+
if (!entry) {
|
|
14370
|
+
return { code: 1, stdout: '', stderr: 'serve: no virtual port table available\n' };
|
|
14371
|
+
}
|
|
14372
|
+
return {
|
|
14373
|
+
code: 0,
|
|
14374
|
+
stdout: `\n ⚡ CodeLab preview server\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n ➜ Root: ${rootDir}\n ➜ Preview: open the Web Preview drawer for port ${entry.port}\n\n`,
|
|
14375
|
+
stderr: ''
|
|
14376
|
+
};
|
|
14377
|
+
},
|
|
14378
|
+
|
|
13074
14379
|
// -----------------------------------------------------------------------
|
|
13075
14380
|
// Port Table & HTTP Inspection: ports, curl
|
|
13076
14381
|
// -----------------------------------------------------------------------
|
|
@@ -14127,6 +15432,13 @@ if (typeof module !== 'undefined' && module.exports) {
|
|
|
14127
15432
|
Object.assign(context.env, this.env);
|
|
14128
15433
|
context.cwd = this.cwd;
|
|
14129
15434
|
}
|
|
15435
|
+
} else if (DIRECT_DEV_TOOL_RE.test(cmdName)) {
|
|
15436
|
+
// A native dev server (vite/ng/astro/…) typed directly. It cannot run in
|
|
15437
|
+
// this runtime — whether or not it was installed — so route it to the
|
|
15438
|
+
// built-in preview server rather than reporting a misleading "command
|
|
15439
|
+
// not found".
|
|
15440
|
+
const fb = tryDevScriptFallback(cmdName, [cmdName, ...args].join(' '), cmdCtx, { force: true });
|
|
15441
|
+
res = fb || { code: 127, stdout: '', stderr: `shell: ${cmdName}: command not found\n` };
|
|
14130
15442
|
} else if (typeof this.options.onProcessSpawn === 'function') {
|
|
14131
15443
|
const spawned = await this.options.onProcessSpawn(cmdName, args, {
|
|
14132
15444
|
cwd: this.cwd,
|
|
@@ -17021,6 +18333,9 @@ declare module 'bun:sqlite' {
|
|
|
17021
18333
|
<span>${(this.hasGuidedLab && this.mode === 'guided') ? 'Verify Step' : 'Run Tests'}</span>
|
|
17022
18334
|
<span class="codelab-btn__kbd">⌘↵</span>
|
|
17023
18335
|
</button>
|
|
18336
|
+
<button type="button" class="codelab-btn codelab-btn--icon" id="cl-preview-app-btn" data-cl-action="preview-app" title="Run & Preview in Browser (built-in dev server)" aria-label="Run and Preview in Browser">
|
|
18337
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
|
|
18338
|
+
</button>
|
|
17024
18339
|
<span class="codelab-toolbar__sep" aria-hidden="true"></span>
|
|
17025
18340
|
${this.hasGuidedLab ? `
|
|
17026
18341
|
<button type="button" class="codelab-btn codelab-btn--icon ${isGuideCollapsed ? '' : 'active'}" id="cl-toggle-guide-btn" data-cl-action="toggle-guide" title="Toggle Guide Panel" aria-label="Toggle Guide Panel" aria-pressed="${isGuideCollapsed ? 'false' : 'true'}">
|
|
@@ -19353,6 +20668,55 @@ declare module 'bun:sqlite' {
|
|
|
19353
20668
|
return this._previewLoadPromise || Promise.resolve();
|
|
19354
20669
|
}
|
|
19355
20670
|
|
|
20671
|
+
// One-click "run the app in a browser": if nothing is listening yet, start the
|
|
20672
|
+
// built-in preview server (which transpiles TS/JSX to browser-native ESM and
|
|
20673
|
+
// resolves bare imports via jsDelivr) and then open the Web Preview.
|
|
20674
|
+
async previewApp() {
|
|
20675
|
+
const existing = this._firstListeningPort();
|
|
20676
|
+
if (existing) {
|
|
20677
|
+
this._openWebPreview(existing);
|
|
20678
|
+
return existing;
|
|
20679
|
+
}
|
|
20680
|
+
|
|
20681
|
+
const htmlCandidates = ['public/index.html', 'index.html', 'site/index.html', 'src/index.html'];
|
|
20682
|
+
if (!htmlCandidates.some((f) => this.files && this.files[f])) {
|
|
20683
|
+
this.drawerTab = 'terminal';
|
|
20684
|
+
this.terminalLogs.push({
|
|
20685
|
+
type: 'system',
|
|
20686
|
+
text: '\nNo index.html found. Add an `index.html` (or run `serve <dir>` in the terminal) to preview your app.'
|
|
20687
|
+
});
|
|
20688
|
+
this._renderDrawerBody();
|
|
20689
|
+
return null;
|
|
20690
|
+
}
|
|
20691
|
+
|
|
20692
|
+
const rootDir = (this.files['public/index.html']) ? '/workspace/public'
|
|
20693
|
+
: (this.files['site/index.html']) ? '/workspace/site'
|
|
20694
|
+
: '/workspace';
|
|
20695
|
+
|
|
20696
|
+
if (!this.shell || typeof this.shell.execute !== 'function') return null;
|
|
20697
|
+
this._syncFilesToShellVfs();
|
|
20698
|
+
this.shell.cwd = this.cwd || '/workspace';
|
|
20699
|
+
this.drawerTab = 'terminal';
|
|
20700
|
+
this.terminalLogs.push({ type: 'system', text: `\n$ serve ${rootDir}` });
|
|
20701
|
+
this._renderDrawerBody();
|
|
20702
|
+
|
|
20703
|
+
try {
|
|
20704
|
+
const res = await this.shell.execute(`serve ${rootDir}`, {});
|
|
20705
|
+
if (res && res.stdout) this.terminalLogs.push({ type: 'stdout', text: res.stdout.replace(/\n$/, '') });
|
|
20706
|
+
if (res && res.stderr) this.terminalLogs.push({ type: 'stderr', text: res.stderr.replace(/\n$/, '') });
|
|
20707
|
+
} catch (err) {
|
|
20708
|
+
this.terminalLogs.push({ type: 'stderr', text: String((err && err.message) || err) });
|
|
20709
|
+
}
|
|
20710
|
+
this._renderDrawerBody();
|
|
20711
|
+
|
|
20712
|
+
const port = this._firstListeningPort();
|
|
20713
|
+
if (port) {
|
|
20714
|
+
this._openWebPreview(port);
|
|
20715
|
+
return port;
|
|
20716
|
+
}
|
|
20717
|
+
return null;
|
|
20718
|
+
}
|
|
20719
|
+
|
|
19356
20720
|
_previewGo(urlOrPath) {
|
|
19357
20721
|
let url = String(urlOrPath || '').trim();
|
|
19358
20722
|
if (!url) return Promise.resolve();
|
|
@@ -19523,7 +20887,15 @@ declare module 'bun:sqlite' {
|
|
|
19523
20887
|
<div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
|
|
19524
20888
|
<iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-same-origin allow-modals" title="Web Preview"></iframe>
|
|
19525
20889
|
</div>
|
|
19526
|
-
|
|
20890
|
+
${servers.length
|
|
20891
|
+
? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
|
|
20892
|
+
: `<div class="codelab-preview-empty">
|
|
20893
|
+
<div class="codelab-preview-empty__icon">${CL_ICONS.globe || '🌐'}</div>
|
|
20894
|
+
<div class="codelab-preview-empty__title">No server running</div>
|
|
20895
|
+
<div class="codelab-preview-empty__text">Start the built-in preview server to render your <code>index.html</code>. TypeScript, TSX and JSX are transpiled for the browser automatically — no bundler required.</div>
|
|
20896
|
+
<button type="button" class="codelab-btn codelab-btn--primary codelab-btn--sm" data-cl-action="preview-app">${CL_ICONS.play || '▶'} <span>Run & Preview</span></button>
|
|
20897
|
+
<div class="codelab-preview-empty__hint">or run <code>serve</code> in the terminal</div>
|
|
20898
|
+
</div>`}
|
|
19527
20899
|
</div>
|
|
19528
20900
|
`;
|
|
19529
20901
|
this._loadPreviewFrame();
|
|
@@ -20526,6 +21898,8 @@ declare module 'bun:sqlite' {
|
|
|
20526
21898
|
} else if (action === 'open-web-preview') {
|
|
20527
21899
|
const port = Number(actionBtn.dataset.port || actionBtn.dataset.clPort);
|
|
20528
21900
|
if (port) this._openWebPreview(port);
|
|
21901
|
+
} else if (action === 'preview-app') {
|
|
21902
|
+
this.previewApp();
|
|
20529
21903
|
} else if (action === 'dismiss-toast') {
|
|
20530
21904
|
this._dismissPortToast(actionBtn.dataset.port);
|
|
20531
21905
|
} else if (action === 'preview-back') {
|
|
@@ -22472,6 +23846,7 @@ declare module 'bun:sqlite' {
|
|
|
22472
23846
|
cloneRepo(repoInput, opts) { return this._instance ? this._instance.cloneRepo(repoInput, opts) : Promise.reject(new Error('Workbench not mounted')); }
|
|
22473
23847
|
runDemo() { return this._instance ? this._instance.runDemo() : Promise.resolve(); }
|
|
22474
23848
|
runTests(filter) { return this._instance ? this._instance.runTests(filter) : Promise.resolve(); }
|
|
23849
|
+
previewApp() { return this._instance ? this._instance.previewApp() : Promise.resolve(null); }
|
|
22475
23850
|
stopExecution() { if (this._instance) this._instance.stopExecution(); }
|
|
22476
23851
|
reset() { if (this._instance) this._instance.reset(); }
|
|
22477
23852
|
exportWorkspace(opts) { return this._instance ? this._instance.exportWorkspace(opts) : null; }
|
|
@@ -22558,6 +23933,7 @@ const executeInWorker = CodeLabRuntime.executeInWorker;
|
|
|
22558
23933
|
const cancelWorkerExecution = CodeLabRuntime.cancelWorkerExecution;
|
|
22559
23934
|
const preloadNpmPackages = CodeLabRuntime.preloadNpmPackages;
|
|
22560
23935
|
const transpileTS = CodeLabRuntime.transpileTS;
|
|
23936
|
+
const transpileForBrowser = CodeLabRuntime.transpileForBrowser;
|
|
22561
23937
|
const createVirtualFs = CodeLabRuntime.createVirtualFs;
|
|
22562
23938
|
const createVirtualHttp = CodeLabRuntime.createVirtualHttp;
|
|
22563
23939
|
const createVirtualNet = CodeLabRuntime.createVirtualNet;
|
|
@@ -22572,7 +23948,11 @@ const PTYTerminalEngine = CodeLabTerminal ? CodeLabTerminal.PTYTerminalEngine :
|
|
|
22572
23948
|
const mount = CodeLab ? CodeLab.mount : null;
|
|
22573
23949
|
const create = CodeLab ? CodeLab.create : null;
|
|
22574
23950
|
const unmount = CodeLab ? CodeLab.unmount : null;
|
|
22575
|
-
const version = CodeLab ? CodeLab.version : '
|
|
23951
|
+
const version = CodeLab ? CodeLab.version : '2.0.0';
|
|
23952
|
+
const renderMarkdown = CodeLab ? CodeLab.renderMarkdown : null;
|
|
23953
|
+
const renderSimpleMarkdown = CodeLab ? CodeLab.renderSimpleMarkdown : null;
|
|
23954
|
+
const cloneRepo = CodeLab ? CodeLab.cloneRepo : null;
|
|
23955
|
+
const extensions = CodeLab ? CodeLab.extensions : null;
|
|
22576
23956
|
|
|
22577
23957
|
export {
|
|
22578
23958
|
CodeLab,
|
|
@@ -22589,6 +23969,10 @@ export {
|
|
|
22589
23969
|
create,
|
|
22590
23970
|
unmount,
|
|
22591
23971
|
version,
|
|
23972
|
+
renderMarkdown,
|
|
23973
|
+
renderSimpleMarkdown,
|
|
23974
|
+
cloneRepo,
|
|
23975
|
+
extensions,
|
|
22592
23976
|
createPosixShell,
|
|
22593
23977
|
cloneGitHubRepository,
|
|
22594
23978
|
parseGitHubRepoUrl,
|
|
@@ -22600,6 +23984,7 @@ export {
|
|
|
22600
23984
|
cancelWorkerExecution,
|
|
22601
23985
|
preloadNpmPackages,
|
|
22602
23986
|
transpileTS,
|
|
23987
|
+
transpileForBrowser,
|
|
22603
23988
|
createVirtualFs,
|
|
22604
23989
|
createVirtualHttp,
|
|
22605
23990
|
createVirtualNet,
|