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