@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/runtime.js
CHANGED
|
@@ -828,9 +828,78 @@ function __initVirtualRuntime(rootScope) {
|
|
|
828
828
|
crc = CRC32_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
|
|
829
829
|
}
|
|
830
830
|
return (crc ^ 0xffffffff) >>> 0;
|
|
831
|
+
},
|
|
832
|
+
// The full Node zlib constant surface. Packages such as axios read these at
|
|
833
|
+
// module-load time (e.g. `zlib.constants.Z_SYNC_FLUSH`) even when they never
|
|
834
|
+
// actually compress, so a missing table breaks the whole module graph.
|
|
835
|
+
constants: {
|
|
836
|
+
Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4,
|
|
837
|
+
Z_BLOCK: 5, Z_TREES: 6, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1,
|
|
838
|
+
Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_MEM_ERROR: -4, Z_BUF_ERROR: -5,
|
|
839
|
+
Z_VERSION_ERROR: -6, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9,
|
|
840
|
+
Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4,
|
|
841
|
+
Z_DEFAULT_STRATEGY: 0, ZLIB_VERNUM: 0x1310, DEFLATE: 1, INFLATE: 2, GZIP: 3,
|
|
842
|
+
GUNZIP: 4, DEFLATERAW: 5, INFLATERAW: 6, UNZIP: 7, BROTLI_DECODE: 8,
|
|
843
|
+
BROTLI_ENCODE: 9, Z_MIN_WINDOWBITS: 8, Z_MAX_WINDOWBITS: 15,
|
|
844
|
+
Z_DEFAULT_WINDOWBITS: 15, Z_MIN_CHUNK: 64, Z_MAX_CHUNK: Infinity,
|
|
845
|
+
Z_DEFAULT_CHUNK: 16384, Z_MIN_MEMLEVEL: 1, Z_MAX_MEMLEVEL: 9,
|
|
846
|
+
Z_DEFAULT_MEMLEVEL: 8, Z_MIN_LEVEL: -1, Z_MAX_LEVEL: 9, Z_DEFAULT_LEVEL: -1
|
|
831
847
|
}
|
|
832
848
|
};
|
|
833
849
|
|
|
850
|
+
// Compression: delegate to the host's real zlib when the runtime is embedded in
|
|
851
|
+
// Node (same process). In a pure browser worker there is no synchronous zlib, so
|
|
852
|
+
// the async APIs use CompressionStream/DecompressionStream and the *Sync variants
|
|
853
|
+
// throw a descriptive error instead of silently corrupting data.
|
|
854
|
+
(() => {
|
|
855
|
+
let hostZlib = null;
|
|
856
|
+
try { hostZlib = (typeof require === 'function') ? require('zlib') : null; } catch (_) { hostZlib = null; }
|
|
857
|
+
const names = [
|
|
858
|
+
'gzip', 'gunzip', 'deflate', 'inflate', 'deflateRaw', 'inflateRaw', 'unzip',
|
|
859
|
+
'gzipSync', 'gunzipSync', 'deflateSync', 'inflateSync', 'deflateRawSync', 'inflateRawSync', 'unzipSync',
|
|
860
|
+
'createGzip', 'createGunzip', 'createDeflate', 'createInflate', 'createDeflateRaw', 'createInflateRaw'
|
|
861
|
+
];
|
|
862
|
+
if (hostZlib) {
|
|
863
|
+
for (const n of names) {
|
|
864
|
+
if (typeof hostZlib[n] === 'function') VirtualZlib[n] = hostZlib[n].bind(hostZlib);
|
|
865
|
+
}
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
const asyncVariant = (format, kind) => (data, optsOrCb, maybeCb) => {
|
|
869
|
+
const cb = typeof optsOrCb === 'function' ? optsOrCb : (typeof maybeCb === 'function' ? maybeCb : null);
|
|
870
|
+
const p = (async () => {
|
|
871
|
+
if (typeof CompressionStream === 'undefined' || typeof DecompressionStream === 'undefined' || typeof Response === 'undefined') {
|
|
872
|
+
throw new Error('zlib.' + kind + ' is not supported in this environment');
|
|
873
|
+
}
|
|
874
|
+
const decompress = /^(gunzip|unzip|inflate)/.test(kind);
|
|
875
|
+
const stream = decompress ? new DecompressionStream(format) : new CompressionStream(format);
|
|
876
|
+
const writer = stream.writable.getWriter();
|
|
877
|
+
const input = data instanceof Uint8Array ? data : VirtualBuffer.from(data);
|
|
878
|
+
writer.write(input);
|
|
879
|
+
writer.close();
|
|
880
|
+
const ab = await new Response(stream.readable).arrayBuffer();
|
|
881
|
+
return VirtualBuffer.from(ab);
|
|
882
|
+
})();
|
|
883
|
+
if (cb) { p.then((out) => cb(null, out), (err) => cb(err)); return undefined; }
|
|
884
|
+
return p;
|
|
885
|
+
};
|
|
886
|
+
VirtualZlib.gzip = asyncVariant('gzip', 'gzip');
|
|
887
|
+
VirtualZlib.gunzip = asyncVariant('gzip', 'gunzip');
|
|
888
|
+
VirtualZlib.unzip = asyncVariant('gzip', 'unzip');
|
|
889
|
+
VirtualZlib.deflate = asyncVariant('deflate', 'deflate');
|
|
890
|
+
VirtualZlib.inflate = asyncVariant('deflate', 'inflate');
|
|
891
|
+
VirtualZlib.deflateRaw = asyncVariant('deflate-raw', 'deflateRaw');
|
|
892
|
+
VirtualZlib.inflateRaw = asyncVariant('deflate-raw', 'inflateRaw');
|
|
893
|
+
const unsupported = (kind) => () => { throw new Error('zlib.' + kind + ' is not supported in a browser worker (use the async API)'); };
|
|
894
|
+
VirtualZlib.gzipSync = unsupported('gzipSync');
|
|
895
|
+
VirtualZlib.gunzipSync = unsupported('gunzipSync');
|
|
896
|
+
VirtualZlib.deflateSync = unsupported('deflateSync');
|
|
897
|
+
VirtualZlib.inflateSync = unsupported('inflateSync');
|
|
898
|
+
VirtualZlib.deflateRawSync = unsupported('deflateRawSync');
|
|
899
|
+
VirtualZlib.inflateRawSync = unsupported('inflateRawSync');
|
|
900
|
+
VirtualZlib.unzipSync = unsupported('unzipSync');
|
|
901
|
+
})();
|
|
902
|
+
|
|
834
903
|
// =========================================================================
|
|
835
904
|
// 4. PATH & OS SHIMS
|
|
836
905
|
// =========================================================================
|
|
@@ -3973,14 +4042,316 @@ function __initVirtualRuntime(rootScope) {
|
|
|
3973
4042
|
};
|
|
3974
4043
|
}
|
|
3975
4044
|
|
|
4045
|
+
// =========================================================================
|
|
4046
|
+
// 7b. JSX / TSX SUPPORT
|
|
4047
|
+
// -------------------------------------------------------------------------
|
|
4048
|
+
// Rewrites JSX syntax into classic `createElement(...)` calls. This runs
|
|
4049
|
+
// BEFORE the string-masking pass so that JSX text (which routinely contains
|
|
4050
|
+
// quotes/apostrophes, e.g. <p>Don't</p>) is captured verbatim, while genuine
|
|
4051
|
+
// JS strings, comments and template literals are skipped untouched.
|
|
4052
|
+
// =========================================================================
|
|
4053
|
+
function detectJsxSyntax(source, filename) {
|
|
4054
|
+
if (/\.(jsx|tsx)$/i.test(filename || '')) return true;
|
|
4055
|
+
if (!source || source.indexOf('<') === -1) return false;
|
|
4056
|
+
if (/@jsx\b/.test(source)) return true;
|
|
4057
|
+
if (source.indexOf('<>') !== -1) return true;
|
|
4058
|
+
if (/<\/[A-Za-z]/.test(source)) return true;
|
|
4059
|
+
return false;
|
|
4060
|
+
}
|
|
4061
|
+
|
|
4062
|
+
function readJsxPragma(source) {
|
|
4063
|
+
let pragma = 'React.createElement';
|
|
4064
|
+
let frag = null;
|
|
4065
|
+
const m = /@jsx\s+([A-Za-z_$][\w$.]*)/.exec(source);
|
|
4066
|
+
if (m) pragma = m[1];
|
|
4067
|
+
const fm = /@jsxFrag\s+([A-Za-z_$][\w$.]*)/.exec(source);
|
|
4068
|
+
if (fm) frag = fm[1];
|
|
4069
|
+
if (!frag) frag = pragma === 'React.createElement' ? 'React.Fragment' : 'Fragment';
|
|
4070
|
+
return { pragma, frag };
|
|
4071
|
+
}
|
|
4072
|
+
|
|
4073
|
+
const JSX_WS_RE = /\s/;
|
|
4074
|
+
const JSX_NAME_START_RE = /[A-Za-z_$]/;
|
|
4075
|
+
const JSX_NAME_CHAR_RE = /[A-Za-z0-9_$:.\-]/;
|
|
4076
|
+
|
|
4077
|
+
function jsxThrow(message) {
|
|
4078
|
+
const err = new Error(message);
|
|
4079
|
+
err.jsxParse = true;
|
|
4080
|
+
throw err;
|
|
4081
|
+
}
|
|
4082
|
+
|
|
4083
|
+
// Returns the exclusive end index if a JS string / template / comment starts
|
|
4084
|
+
// at `i`, otherwise -1. Regexes are deliberately ignored.
|
|
4085
|
+
function jsxSkipJsLiteral(source, i) {
|
|
4086
|
+
const ch = source[i];
|
|
4087
|
+
const next = source[i + 1];
|
|
4088
|
+
const len = source.length;
|
|
4089
|
+
if (ch === '/' && next === '/') {
|
|
4090
|
+
const e = source.indexOf('\n', i);
|
|
4091
|
+
return e === -1 ? len : e;
|
|
4092
|
+
}
|
|
4093
|
+
if (ch === '/' && next === '*') {
|
|
4094
|
+
const e = source.indexOf('*/', i + 2);
|
|
4095
|
+
return e === -1 ? len : e + 2;
|
|
4096
|
+
}
|
|
4097
|
+
if (ch === '"' || ch === "'") {
|
|
4098
|
+
let j = i + 1;
|
|
4099
|
+
while (j < len) {
|
|
4100
|
+
const c = source[j];
|
|
4101
|
+
if (c === '\\') { j += 2; continue; }
|
|
4102
|
+
if (c === ch) { j++; break; }
|
|
4103
|
+
if (c === '\n') break;
|
|
4104
|
+
j++;
|
|
4105
|
+
}
|
|
4106
|
+
return j;
|
|
4107
|
+
}
|
|
4108
|
+
if (ch === '`') {
|
|
4109
|
+
let j = i + 1;
|
|
4110
|
+
let depth = 0;
|
|
4111
|
+
while (j < len) {
|
|
4112
|
+
const c = source[j];
|
|
4113
|
+
if (c === '\\') { j += 2; continue; }
|
|
4114
|
+
if (c === '$' && source[j + 1] === '{') { depth++; j += 2; continue; }
|
|
4115
|
+
if (c === '}' && depth > 0) { depth--; j++; continue; }
|
|
4116
|
+
if (c === '`' && depth === 0) { j++; break; }
|
|
4117
|
+
j++;
|
|
4118
|
+
}
|
|
4119
|
+
return j;
|
|
4120
|
+
}
|
|
4121
|
+
return -1;
|
|
4122
|
+
}
|
|
4123
|
+
|
|
4124
|
+
function jsxReadName(source, i) {
|
|
4125
|
+
if (!JSX_NAME_START_RE.test(source[i] || '')) jsxThrow('jsx: expected a tag name');
|
|
4126
|
+
let j = i;
|
|
4127
|
+
while (j < source.length && JSX_NAME_CHAR_RE.test(source[j])) j++;
|
|
4128
|
+
return { name: source.slice(i, j), next: j };
|
|
4129
|
+
}
|
|
4130
|
+
|
|
4131
|
+
function jsxSkipWs(source, i) {
|
|
4132
|
+
while (i < source.length && JSX_WS_RE.test(source[i])) i++;
|
|
4133
|
+
return i;
|
|
4134
|
+
}
|
|
4135
|
+
|
|
4136
|
+
function normalizeJsxText(raw) {
|
|
4137
|
+
if (!raw) return '';
|
|
4138
|
+
let t = raw.replace(/\r/g, '');
|
|
4139
|
+
if (t.indexOf('\n') !== -1) {
|
|
4140
|
+
t = t.split('\n').map((s) => s.replace(/[ \t]+/g, ' ').trim()).filter(Boolean).join(' ');
|
|
4141
|
+
} else if (!/\S/.test(t)) {
|
|
4142
|
+
return '';
|
|
4143
|
+
} else {
|
|
4144
|
+
t = t.replace(/[ \t]+/g, ' ');
|
|
4145
|
+
}
|
|
4146
|
+
return t ? JSON.stringify(t) : '';
|
|
4147
|
+
}
|
|
4148
|
+
|
|
4149
|
+
// Reads a balanced `{ ... }` expression container, skipping nested JSX and
|
|
4150
|
+
// JS literals. Returns the raw inner source (later re-transformed) plus the
|
|
4151
|
+
// index just past the closing brace.
|
|
4152
|
+
function jsxReadBraced(source, i, opts) {
|
|
4153
|
+
let depth = 0;
|
|
4154
|
+
let j = i;
|
|
4155
|
+
while (j < source.length) {
|
|
4156
|
+
const lit = jsxSkipJsLiteral(source, j);
|
|
4157
|
+
if (lit !== -1) { j = lit; continue; }
|
|
4158
|
+
const c = source[j];
|
|
4159
|
+
if (c === '{') { depth++; j++; continue; }
|
|
4160
|
+
if (c === '}') {
|
|
4161
|
+
depth--;
|
|
4162
|
+
j++;
|
|
4163
|
+
if (depth === 0) return { inner: source.slice(i + 1, j - 1), next: j };
|
|
4164
|
+
continue;
|
|
4165
|
+
}
|
|
4166
|
+
if (c === '<' && (JSX_NAME_START_RE.test(source[j + 1] || '') || source[j + 1] === '>')) {
|
|
4167
|
+
try {
|
|
4168
|
+
const el = jsxParseElement(source, j, opts);
|
|
4169
|
+
j = el.next;
|
|
4170
|
+
continue;
|
|
4171
|
+
} catch (e) {
|
|
4172
|
+
if (!e || !e.jsxParse) throw e;
|
|
4173
|
+
}
|
|
4174
|
+
}
|
|
4175
|
+
j++;
|
|
4176
|
+
}
|
|
4177
|
+
jsxThrow('jsx: unterminated expression container');
|
|
4178
|
+
}
|
|
4179
|
+
|
|
4180
|
+
function jsxParseElement(source, i, opts) {
|
|
4181
|
+
const o = opts || readJsxPragma(source);
|
|
4182
|
+
let j = i + 1;
|
|
4183
|
+
let isFragment = false;
|
|
4184
|
+
let typeExpr;
|
|
4185
|
+
if (source[j] === '>') {
|
|
4186
|
+
isFragment = true;
|
|
4187
|
+
typeExpr = o.frag;
|
|
4188
|
+
j++;
|
|
4189
|
+
} else {
|
|
4190
|
+
const nm = jsxReadName(source, j);
|
|
4191
|
+
j = nm.next;
|
|
4192
|
+
const raw = nm.name;
|
|
4193
|
+
const isReference = raw.indexOf('.') !== -1 || raw.indexOf(':') !== -1 || /^[A-Z_$]/.test(raw);
|
|
4194
|
+
if (isReference) {
|
|
4195
|
+
typeExpr = raw.replace(/:/g, '.');
|
|
4196
|
+
} else {
|
|
4197
|
+
typeExpr = JSON.stringify(raw);
|
|
4198
|
+
}
|
|
4199
|
+
}
|
|
4200
|
+
|
|
4201
|
+
const props = [];
|
|
4202
|
+
let selfClosing = false;
|
|
4203
|
+
if (!isFragment) {
|
|
4204
|
+
for (;;) {
|
|
4205
|
+
j = jsxSkipWs(source, j);
|
|
4206
|
+
if (j >= source.length) jsxThrow('jsx: unexpected end of input inside a tag');
|
|
4207
|
+
const c = source[j];
|
|
4208
|
+
if (c === '/') {
|
|
4209
|
+
if (source[j + 1] !== '>') jsxThrow('jsx: malformed self-closing tag');
|
|
4210
|
+
j += 2;
|
|
4211
|
+
selfClosing = true;
|
|
4212
|
+
break;
|
|
4213
|
+
}
|
|
4214
|
+
if (c === '>') { j++; break; }
|
|
4215
|
+
if (c === '{') {
|
|
4216
|
+
const br = jsxReadBraced(source, j, o);
|
|
4217
|
+
const inner = br.inner.trim();
|
|
4218
|
+
if (inner.slice(0, 3) !== '...') jsxThrow('jsx: only a spread {...} may appear where an attribute is expected');
|
|
4219
|
+
props.push({ spread: jsxTransform(inner.slice(3), o) });
|
|
4220
|
+
j = br.next;
|
|
4221
|
+
continue;
|
|
4222
|
+
}
|
|
4223
|
+
if (!JSX_NAME_START_RE.test(c)) jsxThrow('jsx: malformed attribute');
|
|
4224
|
+
const am = jsxReadName(source, j);
|
|
4225
|
+
const attrName = am.name;
|
|
4226
|
+
j = jsxSkipWs(source, am.next);
|
|
4227
|
+
let valueExpr = 'true';
|
|
4228
|
+
if (source[j] === '=') {
|
|
4229
|
+
j = jsxSkipWs(source, j + 1);
|
|
4230
|
+
const vc = source[j];
|
|
4231
|
+
if (vc === '"' || vc === "'") {
|
|
4232
|
+
let k = j + 1;
|
|
4233
|
+
while (k < source.length && source[k] !== vc) {
|
|
4234
|
+
if (source[k] === '\\') k++;
|
|
4235
|
+
k++;
|
|
4236
|
+
}
|
|
4237
|
+
if (k >= source.length) jsxThrow('jsx: unterminated attribute string');
|
|
4238
|
+
valueExpr = JSON.stringify(source.slice(j + 1, k));
|
|
4239
|
+
j = k + 1;
|
|
4240
|
+
} else if (vc === '{') {
|
|
4241
|
+
const br = jsxReadBraced(source, j, o);
|
|
4242
|
+
valueExpr = jsxTransform(br.inner, o) || 'undefined';
|
|
4243
|
+
j = br.next;
|
|
4244
|
+
} else if (vc === '<') {
|
|
4245
|
+
const el = jsxParseElement(source, j, o);
|
|
4246
|
+
valueExpr = el.code;
|
|
4247
|
+
j = el.next;
|
|
4248
|
+
} else {
|
|
4249
|
+
jsxThrow('jsx: unsupported attribute value');
|
|
4250
|
+
}
|
|
4251
|
+
}
|
|
4252
|
+
const propKey = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(attrName) ? attrName : JSON.stringify(attrName);
|
|
4253
|
+
props.push({ key: propKey, value: valueExpr });
|
|
4254
|
+
}
|
|
4255
|
+
}
|
|
4256
|
+
|
|
4257
|
+
const children = [];
|
|
4258
|
+
if (!selfClosing) {
|
|
4259
|
+
for (;;) {
|
|
4260
|
+
if (j >= source.length) jsxThrow('jsx: missing closing tag');
|
|
4261
|
+
const c = source[j];
|
|
4262
|
+
if (c === '<' && source[j + 1] === '/') {
|
|
4263
|
+
j = jsxSkipWs(source, j + 2);
|
|
4264
|
+
if (source[j] === '>') { j++; break; }
|
|
4265
|
+
const cm = jsxReadName(source, j);
|
|
4266
|
+
j = jsxSkipWs(source, cm.next);
|
|
4267
|
+
if (source[j] !== '>') jsxThrow('jsx: malformed closing tag');
|
|
4268
|
+
j++;
|
|
4269
|
+
break;
|
|
4270
|
+
}
|
|
4271
|
+
if (c === '<') {
|
|
4272
|
+
const el = jsxParseElement(source, j, o);
|
|
4273
|
+
children.push(el.code);
|
|
4274
|
+
j = el.next;
|
|
4275
|
+
continue;
|
|
4276
|
+
}
|
|
4277
|
+
if (c === '{') {
|
|
4278
|
+
const br = jsxReadBraced(source, j, o);
|
|
4279
|
+
const inner = jsxTransform(br.inner, o);
|
|
4280
|
+
if (inner && inner.trim()) children.push(inner);
|
|
4281
|
+
j = br.next;
|
|
4282
|
+
continue;
|
|
4283
|
+
}
|
|
4284
|
+
let k = j;
|
|
4285
|
+
while (k < source.length && source[k] !== '<' && source[k] !== '{') k++;
|
|
4286
|
+
const text = normalizeJsxText(source.slice(j, k));
|
|
4287
|
+
if (text) children.push(text);
|
|
4288
|
+
j = k;
|
|
4289
|
+
}
|
|
4290
|
+
}
|
|
4291
|
+
|
|
4292
|
+
let propsCode = 'null';
|
|
4293
|
+
if (props.length) {
|
|
4294
|
+
const parts = props.map((p) => (p.spread !== undefined ? '...(' + p.spread + ')' : p.key + ': ' + p.value));
|
|
4295
|
+
propsCode = '{ ' + parts.join(', ') + ' }';
|
|
4296
|
+
}
|
|
4297
|
+
|
|
4298
|
+
const args = [typeExpr, propsCode].concat(children);
|
|
4299
|
+
return { code: o.pragma + '(' + args.join(', ') + ')', next: j };
|
|
4300
|
+
}
|
|
4301
|
+
|
|
4302
|
+
function jsxTransform(source, opts) {
|
|
4303
|
+
const o = opts || readJsxPragma(source);
|
|
4304
|
+
let i = 0;
|
|
4305
|
+
let out = '';
|
|
4306
|
+
while (i < source.length) {
|
|
4307
|
+
const lit = jsxSkipJsLiteral(source, i);
|
|
4308
|
+
if (lit !== -1) { out += source.slice(i, lit); i = lit; continue; }
|
|
4309
|
+
const ch = source[i];
|
|
4310
|
+
if (ch === '<' && (JSX_NAME_START_RE.test(source[i + 1] || '') || source[i + 1] === '>')) {
|
|
4311
|
+
try {
|
|
4312
|
+
const el = jsxParseElement(source, i, o);
|
|
4313
|
+
out += el.code;
|
|
4314
|
+
i = el.next;
|
|
4315
|
+
continue;
|
|
4316
|
+
} catch (e) {
|
|
4317
|
+
if (!e || !e.jsxParse) throw e;
|
|
4318
|
+
}
|
|
4319
|
+
}
|
|
4320
|
+
out += ch;
|
|
4321
|
+
i++;
|
|
4322
|
+
}
|
|
4323
|
+
return out;
|
|
4324
|
+
}
|
|
4325
|
+
|
|
3976
4326
|
// =========================================================================
|
|
3977
4327
|
// 8. FAST TYPESCRIPT & ESM-TO-CJS TRANSPILER
|
|
3978
4328
|
// =========================================================================
|
|
3979
|
-
function transpileTS(source, filename = 'module.ts') {
|
|
4329
|
+
function transpileTS(source, filename = 'module.ts', opts = {}) {
|
|
4330
|
+
// `keepEsm` leaves `import`/`export` statements intact so the output can run
|
|
4331
|
+
// natively in a browser as an ES module (used by the built-in preview server).
|
|
4332
|
+
const keepEsm = Boolean(opts && opts.keepEsm);
|
|
3980
4333
|
const isTS = /\.(ts|tsx|mts|cts)$/i.test(filename)
|
|
3981
|
-
||
|
|
3982
|
-
const hasESM = /^\s*(import|export)\
|
|
3983
|
-
|
|
4334
|
+
|| /^[ \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);
|
|
4335
|
+
const hasESM = /^\s*(?:import|export)\b/m.test(source)
|
|
4336
|
+
|| /\bexport\s*\{/.test(source)
|
|
4337
|
+
|| /\bimport\s*\{/.test(source)
|
|
4338
|
+
|| /\bexport\s+default\b/.test(source);
|
|
4339
|
+
const hasJsx = detectJsxSyntax(source, filename);
|
|
4340
|
+
if (!isTS && !hasESM && !hasJsx) return source;
|
|
4341
|
+
|
|
4342
|
+
// JSX/TSX must be rewritten before masking so JSX text is kept verbatim.
|
|
4343
|
+
if (hasJsx) {
|
|
4344
|
+
const { pragma, frag } = readJsxPragma(source);
|
|
4345
|
+
const needsReact = pragma === 'React.createElement' && !/\bReact\b/.test(source);
|
|
4346
|
+
const transformed = jsxTransform(source, { pragma, frag });
|
|
4347
|
+
if (transformed !== source) {
|
|
4348
|
+
source = transformed;
|
|
4349
|
+
// The classic runtime needs a React binding available to the JSX output.
|
|
4350
|
+
if (needsReact) {
|
|
4351
|
+
source = (keepEsm ? 'import React from "react";\n' : 'const React = require("react");\n') + source;
|
|
4352
|
+
}
|
|
4353
|
+
}
|
|
4354
|
+
}
|
|
3984
4355
|
|
|
3985
4356
|
// Step 1: Mask strings, template literals, regex literals, and comments so transforms never corrupt literals
|
|
3986
4357
|
const placeholders = [];
|
|
@@ -4543,10 +4914,10 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4543
4914
|
} while (code !== prevCode);
|
|
4544
4915
|
}
|
|
4545
4916
|
|
|
4546
|
-
if (hasESM || isTS) {
|
|
4917
|
+
if ((hasESM || isTS) && !keepEsm) {
|
|
4547
4918
|
// Convert ES module imports (including multi-line `{ ... }`)
|
|
4548
|
-
code = code.replace(
|
|
4549
|
-
code = code.replace(
|
|
4919
|
+
code = code.replace(/\bimport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, 'const $1 = require($2);');
|
|
4920
|
+
code = code.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, defId, specifiers, mod) => {
|
|
4550
4921
|
const cleaned = specifiers
|
|
4551
4922
|
.split(',')
|
|
4552
4923
|
.map((s) => s.trim())
|
|
@@ -4557,7 +4928,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4557
4928
|
return `const ${defId} = (function(m){ return m && m.__esModule ? m.default : m; })(require(${mTrim}));` +
|
|
4558
4929
|
(cleaned ? ` const { ${cleaned} } = require(${mTrim});` : '');
|
|
4559
4930
|
});
|
|
4560
|
-
code = code.replace(
|
|
4931
|
+
code = code.replace(/\bimport\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, specifiers, mod) => {
|
|
4561
4932
|
const cleaned = specifiers
|
|
4562
4933
|
.split(',')
|
|
4563
4934
|
.map((s) => s.trim())
|
|
@@ -4566,42 +4937,48 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4566
4937
|
.join(', ');
|
|
4567
4938
|
return cleaned ? `const { ${cleaned} } = require(${mod.trim()});` : '';
|
|
4568
4939
|
});
|
|
4569
|
-
code = code.replace(
|
|
4570
|
-
|
|
4940
|
+
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));');
|
|
4941
|
+
// Dynamic `import("pkg")` — resolve through the CJS loader instead of the
|
|
4942
|
+
// host's dynamic import, which cannot see the virtual filesystem.
|
|
4943
|
+
code = code.replace(/\bimport\s*\(\s*(\x00__LIT_\d+__\x00)\s*\)/g, 'Promise.resolve().then(() => require($1))');
|
|
4944
|
+
// Side-effect import `import"pkg"` / `import "pkg"`. By this point the
|
|
4945
|
+
// specifier is literal-masked, and minified modules emit no whitespace
|
|
4946
|
+
// between `import` and the string, so `\s*` (not `\s+`) is required.
|
|
4947
|
+
code = code.replace(/\bimport\s*(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
|
|
4571
4948
|
|
|
4572
4949
|
// Convert ES module exports
|
|
4573
4950
|
const exportedNames = [];
|
|
4574
4951
|
let defaultExportName = null;
|
|
4575
4952
|
let hasEsmExport = false;
|
|
4576
4953
|
|
|
4577
|
-
code = code.replace(
|
|
4954
|
+
code = code.replace(/\bexport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, (_, ns, mod) => {
|
|
4578
4955
|
hasEsmExport = true;
|
|
4579
4956
|
return `exports.${ns} = require(${mod.trim()});`;
|
|
4580
4957
|
});
|
|
4581
|
-
code = code.replace(
|
|
4958
|
+
code = code.replace(/\bexport\s*\*\s*from\s*([^\n;]+);?/gm, (_, mod) => {
|
|
4582
4959
|
hasEsmExport = true;
|
|
4583
4960
|
return `Object.assign(exports, require(${mod.trim()}));`;
|
|
4584
4961
|
});
|
|
4585
|
-
code = code.replace(
|
|
4962
|
+
code = code.replace(/\bexport\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
|
|
4586
4963
|
hasEsmExport = true;
|
|
4587
4964
|
defaultExportName = name;
|
|
4588
4965
|
return `${kw} ${name}`;
|
|
4589
4966
|
});
|
|
4590
|
-
code = code.replace(
|
|
4967
|
+
code = code.replace(/\bexport\s+default\s+/gm, () => {
|
|
4591
4968
|
hasEsmExport = true;
|
|
4592
4969
|
return 'exports.default = ';
|
|
4593
4970
|
});
|
|
4594
|
-
code = code.replace(
|
|
4971
|
+
code = code.replace(/\bexport\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
|
|
4595
4972
|
hasEsmExport = true;
|
|
4596
4973
|
exportedNames.push(name);
|
|
4597
4974
|
return `${kw} ${name}`;
|
|
4598
4975
|
});
|
|
4599
|
-
code = code.replace(
|
|
4976
|
+
code = code.replace(/\bexport\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
|
|
4600
4977
|
hasEsmExport = true;
|
|
4601
4978
|
exportedNames.push(name);
|
|
4602
4979
|
return `${kw} ${name}`;
|
|
4603
4980
|
});
|
|
4604
|
-
code = code.replace(
|
|
4981
|
+
code = code.replace(/\bexport\s*\{([^}]+)\}\s*from\s*([^\n;]+);?/gm, (_, list, mod) => {
|
|
4605
4982
|
hasEsmExport = true;
|
|
4606
4983
|
const mTrim = mod.trim();
|
|
4607
4984
|
return list.split(',').map((item) => {
|
|
@@ -4613,7 +4990,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4613
4990
|
return `exports.${exported} = require(${mTrim}).${local};`;
|
|
4614
4991
|
}).join(' ');
|
|
4615
4992
|
});
|
|
4616
|
-
code = code.replace(
|
|
4993
|
+
code = code.replace(/\bexport\s*\{([^}]+)\}\s*;?/gm, (_, list) => {
|
|
4617
4994
|
hasEsmExport = true;
|
|
4618
4995
|
return list.split(',').map((item) => {
|
|
4619
4996
|
const trimmed = item.trim();
|
|
@@ -4700,8 +5077,12 @@ function __initVirtualRuntime(rootScope) {
|
|
|
4700
5077
|
const builtinSet = new Set([
|
|
4701
5078
|
'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
|
|
4702
5079
|
'dns', 'dns/promises', 'string_decoder', 'child_process', 'process',
|
|
4703
|
-
'assert', 'assert/strict', 'events', 'util', 'url', 'querystring',
|
|
4704
|
-
'stream', 'stream/promises', '
|
|
5080
|
+
'assert', 'assert/strict', 'events', 'util', 'util/types', 'url', 'querystring',
|
|
5081
|
+
'stream', 'stream/promises', 'stream/web', 'stream/consumers', 'test', 'perf_hooks',
|
|
5082
|
+
'timers', 'timers/promises', 'buffer', 'tty', 'tls', 'dgram', 'readline', 'readline/promises',
|
|
5083
|
+
'async_hooks', 'worker_threads', 'v8', 'vm', 'module', 'constants', 'domain',
|
|
5084
|
+
'diagnostics_channel', 'http2', 'cluster', 'repl', 'inspector', 'trace_events',
|
|
5085
|
+
'wasi', 'console',
|
|
4705
5086
|
'bun', 'bun:test', 'bun:sqlite'
|
|
4706
5087
|
]);
|
|
4707
5088
|
|
|
@@ -6611,6 +6992,285 @@ function __initVirtualRuntime(rootScope) {
|
|
|
6611
6992
|
})();
|
|
6612
6993
|
|
|
6613
6994
|
// Built-in Node module table
|
|
6995
|
+
// ── Additional Node builtin shims ────────────────────────────────────────
|
|
6996
|
+
// Widely-used packages require these at load time (e.g. `debug` requires
|
|
6997
|
+
// `tty`). Without an entry `require('tty')` throws MODULE_NOT_FOUND and the
|
|
6998
|
+
// whole app fails to start. Implementations are deliberately minimal but
|
|
6999
|
+
// shape-compatible; anything that genuinely cannot work in the sandbox
|
|
7000
|
+
// throws an explicit, descriptive error rather than silently misbehaving.
|
|
7001
|
+
const VirtualTty = {
|
|
7002
|
+
isatty() { return false; },
|
|
7003
|
+
ReadStream: class TtyReadStream extends EventEmitter {},
|
|
7004
|
+
WriteStream: class TtyWriteStream extends EventEmitter {
|
|
7005
|
+
constructor(fd) { super(); this.fd = fd; this.columns = 80; this.rows = 24; this.isTTY = false; }
|
|
7006
|
+
getColorDepth() { return 1; }
|
|
7007
|
+
hasColors() { return false; }
|
|
7008
|
+
cursorTo() { return true; }
|
|
7009
|
+
clearLine() { return true; }
|
|
7010
|
+
moveCursor() { return true; }
|
|
7011
|
+
}
|
|
7012
|
+
};
|
|
7013
|
+
|
|
7014
|
+
function makeReadlineInterface() {
|
|
7015
|
+
const iface = new EventEmitter();
|
|
7016
|
+
iface.terminal = false;
|
|
7017
|
+
iface.line = '';
|
|
7018
|
+
iface.cursor = 0;
|
|
7019
|
+
iface.question = (query, cb) => { if (typeof cb === 'function') queueMicrotask(() => cb('')); };
|
|
7020
|
+
iface.prompt = () => {};
|
|
7021
|
+
iface.setPrompt = () => {};
|
|
7022
|
+
iface.getPrompt = () => '';
|
|
7023
|
+
iface.write = () => {};
|
|
7024
|
+
iface.pause = () => iface;
|
|
7025
|
+
iface.resume = () => iface;
|
|
7026
|
+
iface.close = () => { queueMicrotask(() => iface.emit('close')); return iface; };
|
|
7027
|
+
iface[Symbol.asyncIterator] = async function* () {};
|
|
7028
|
+
return iface;
|
|
7029
|
+
}
|
|
7030
|
+
const VirtualReadline = {
|
|
7031
|
+
createInterface: makeReadlineInterface,
|
|
7032
|
+
Interface: class ReadlineInterface extends EventEmitter {},
|
|
7033
|
+
clearLine: () => true,
|
|
7034
|
+
clearScreenDown: () => true,
|
|
7035
|
+
cursorTo: () => true,
|
|
7036
|
+
moveCursor: () => true,
|
|
7037
|
+
emitKeypressEvents: () => {}
|
|
7038
|
+
};
|
|
7039
|
+
const VirtualReadlinePromises = {
|
|
7040
|
+
createInterface: () => {
|
|
7041
|
+
const iface = makeReadlineInterface();
|
|
7042
|
+
iface.question = () => Promise.resolve('');
|
|
7043
|
+
return iface;
|
|
7044
|
+
},
|
|
7045
|
+
Interface: class ReadlinePromisesInterface extends EventEmitter {}
|
|
7046
|
+
};
|
|
7047
|
+
|
|
7048
|
+
const VirtualAsyncHooks = {
|
|
7049
|
+
AsyncLocalStorage: class AsyncLocalStorage {
|
|
7050
|
+
constructor() { this._store = undefined; }
|
|
7051
|
+
getStore() { return this._store; }
|
|
7052
|
+
run(store, fn, ...args) {
|
|
7053
|
+
const prev = this._store;
|
|
7054
|
+
this._store = store;
|
|
7055
|
+
try { return fn(...args); } finally { this._store = prev; }
|
|
7056
|
+
}
|
|
7057
|
+
exit(fn, ...args) {
|
|
7058
|
+
const prev = this._store;
|
|
7059
|
+
this._store = undefined;
|
|
7060
|
+
try { return fn(...args); } finally { this._store = prev; }
|
|
7061
|
+
}
|
|
7062
|
+
enterWith(store) { this._store = store; }
|
|
7063
|
+
disable() { this._store = undefined; }
|
|
7064
|
+
},
|
|
7065
|
+
AsyncResource: class AsyncResource {
|
|
7066
|
+
constructor(type) { this.type = type || 'AsyncResource'; }
|
|
7067
|
+
runInAsyncScope(fn, thisArg, ...args) { return fn.apply(thisArg, args); }
|
|
7068
|
+
emitDestroy() { return this; }
|
|
7069
|
+
asyncId() { return 0; }
|
|
7070
|
+
triggerAsyncId() { return 0; }
|
|
7071
|
+
static bind(fn) { return fn; }
|
|
7072
|
+
},
|
|
7073
|
+
createHook() { return { enable() {}, disable() {} }; },
|
|
7074
|
+
executionAsyncId() { return 0; },
|
|
7075
|
+
triggerAsyncId() { return 0; },
|
|
7076
|
+
executionAsyncResource() { return null; }
|
|
7077
|
+
};
|
|
7078
|
+
|
|
7079
|
+
const VirtualWorkerThreads = {
|
|
7080
|
+
isMainThread: true,
|
|
7081
|
+
threadId: 0,
|
|
7082
|
+
parentPort: null,
|
|
7083
|
+
workerData: null,
|
|
7084
|
+
resourceLimits: {},
|
|
7085
|
+
SHARE_ENV: Symbol('nodejs.worker_threads.SHARE_ENV'),
|
|
7086
|
+
receiveMessageOnPort() { return undefined; },
|
|
7087
|
+
Worker: class Worker extends EventEmitter {
|
|
7088
|
+
constructor(filename) {
|
|
7089
|
+
super();
|
|
7090
|
+
this.threadId = -1;
|
|
7091
|
+
this.filename = filename;
|
|
7092
|
+
queueMicrotask(() => this.emit('error', new Error('worker_threads.Worker is not supported in the virtual runtime.')));
|
|
7093
|
+
}
|
|
7094
|
+
postMessage() {}
|
|
7095
|
+
terminate() { return Promise.resolve(0); }
|
|
7096
|
+
ref() { return this; }
|
|
7097
|
+
unref() { return this; }
|
|
7098
|
+
},
|
|
7099
|
+
MessageChannel: class MessageChannel {},
|
|
7100
|
+
MessagePort: class MessagePort extends EventEmitter {}
|
|
7101
|
+
};
|
|
7102
|
+
|
|
7103
|
+
const VirtualV8 = {
|
|
7104
|
+
serialize(value) { return VirtualBuffer.from(JSON.stringify(value === undefined ? null : value), 'utf8'); },
|
|
7105
|
+
deserialize(buf) { try { return JSON.parse(String(buf)); } catch (_) { return undefined; } },
|
|
7106
|
+
getHeapStatistics() {
|
|
7107
|
+
return {
|
|
7108
|
+
total_heap_size: 0, total_heap_size_executable: 0, total_physical_size: 0,
|
|
7109
|
+
total_available_size: 0, used_heap_size: 0, heap_size_limit: 0,
|
|
7110
|
+
malloced_memory: 0, peak_malloced_memory: 0, does_zap_garbage: 0,
|
|
7111
|
+
number_of_native_contexts: 1, number_of_detached_contexts: 0
|
|
7112
|
+
};
|
|
7113
|
+
},
|
|
7114
|
+
getHeapSpaceStatistics() { return []; },
|
|
7115
|
+
setFlagsFromString() {},
|
|
7116
|
+
cachedDataVersionTag() { return 0; },
|
|
7117
|
+
Serializer: class Serializer {
|
|
7118
|
+
constructor() { this._value = undefined; }
|
|
7119
|
+
writeHeader() {}
|
|
7120
|
+
writeValue(value) { this._value = value; }
|
|
7121
|
+
releaseBuffer() { return VirtualBuffer.from(JSON.stringify(this._value === undefined ? null : this._value), 'utf8'); }
|
|
7122
|
+
},
|
|
7123
|
+
Deserializer: class Deserializer {
|
|
7124
|
+
constructor(buffer) { this._buffer = buffer; }
|
|
7125
|
+
readHeader() { return true; }
|
|
7126
|
+
readValue() { try { return JSON.parse(String(this._buffer)); } catch (_) { return undefined; } }
|
|
7127
|
+
}
|
|
7128
|
+
};
|
|
7129
|
+
|
|
7130
|
+
const VirtualVm = {
|
|
7131
|
+
createContext(sandbox) { return sandbox && typeof sandbox === 'object' ? sandbox : {}; },
|
|
7132
|
+
isContext() { return false; },
|
|
7133
|
+
createScript() { throw new Error('vm code compilation is not supported in the virtual runtime.'); },
|
|
7134
|
+
runInContext() { throw new Error('vm.runInContext is not supported in the virtual runtime.'); },
|
|
7135
|
+
runInNewContext() { throw new Error('vm.runInNewContext is not supported in the virtual runtime.'); },
|
|
7136
|
+
runInThisContext() { throw new Error('vm.runInThisContext is not supported in the virtual runtime.'); },
|
|
7137
|
+
compileFunction() { throw new Error('vm.compileFunction is not supported in the virtual runtime.'); },
|
|
7138
|
+
Script: class Script {
|
|
7139
|
+
runInThisContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
|
|
7140
|
+
runInContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
|
|
7141
|
+
runInNewContext() { throw new Error('vm.Script is not supported in the virtual runtime.'); }
|
|
7142
|
+
}
|
|
7143
|
+
};
|
|
7144
|
+
|
|
7145
|
+
const VirtualDomain = {
|
|
7146
|
+
create() {
|
|
7147
|
+
const d = new EventEmitter();
|
|
7148
|
+
d.members = [];
|
|
7149
|
+
d.add = () => d;
|
|
7150
|
+
d.remove = () => d;
|
|
7151
|
+
d.bind = (fn) => fn;
|
|
7152
|
+
d.intercept = (fn) => fn;
|
|
7153
|
+
d.run = (fn, ...args) => fn(...args);
|
|
7154
|
+
d.dispose = () => d;
|
|
7155
|
+
return d;
|
|
7156
|
+
},
|
|
7157
|
+
createDomain() { return VirtualDomain.create(); }
|
|
7158
|
+
};
|
|
7159
|
+
|
|
7160
|
+
const VirtualDiagnosticsChannel = {
|
|
7161
|
+
_channels: new Map(),
|
|
7162
|
+
channel(name) {
|
|
7163
|
+
const key = String(name);
|
|
7164
|
+
if (!VirtualDiagnosticsChannel._channels.has(key)) {
|
|
7165
|
+
const ch = new EventEmitter();
|
|
7166
|
+
ch.name = key;
|
|
7167
|
+
ch.hasSubscribers = false;
|
|
7168
|
+
ch.subscribe = () => { ch.hasSubscribers = true; };
|
|
7169
|
+
ch.unsubscribe = () => { ch.hasSubscribers = false; };
|
|
7170
|
+
VirtualDiagnosticsChannel._channels.set(key, ch);
|
|
7171
|
+
}
|
|
7172
|
+
return VirtualDiagnosticsChannel._channels.get(key);
|
|
7173
|
+
},
|
|
7174
|
+
subscribe(name, cb) {
|
|
7175
|
+
const ch = VirtualDiagnosticsChannel.channel(name);
|
|
7176
|
+
ch.subscribe();
|
|
7177
|
+
if (typeof cb === 'function') ch.on('message', cb);
|
|
7178
|
+
},
|
|
7179
|
+
unsubscribe(name) { VirtualDiagnosticsChannel.channel(name).unsubscribe(); },
|
|
7180
|
+
Channel: class Channel extends EventEmitter {}
|
|
7181
|
+
};
|
|
7182
|
+
|
|
7183
|
+
const notSupported = (what) => () => { throw new Error(what + ' is not supported in the virtual runtime.'); };
|
|
7184
|
+
const VirtualTls = {
|
|
7185
|
+
DEFAULT_MIN_VERSION: 'TLSv1.2',
|
|
7186
|
+
DEFAULT_MAX_VERSION: 'TLSv1.3',
|
|
7187
|
+
rootCertificates: [],
|
|
7188
|
+
createSecureContext() { return { context: {} }; },
|
|
7189
|
+
SecureContext: class SecureContext {},
|
|
7190
|
+
TLSSocket: class TLSSocket extends EventEmitter {},
|
|
7191
|
+
Server: class TLSServer extends EventEmitter {},
|
|
7192
|
+
checkServerIdentity() { return undefined; },
|
|
7193
|
+
connect: notSupported('tls.connect'),
|
|
7194
|
+
createServer: notSupported('tls.createServer')
|
|
7195
|
+
};
|
|
7196
|
+
const VirtualDgram = {
|
|
7197
|
+
createSocket(type) {
|
|
7198
|
+
const sock = new EventEmitter();
|
|
7199
|
+
sock.type = type || 'udp4';
|
|
7200
|
+
sock.bind = (...args) => { const cb = args[args.length - 1]; if (typeof cb === 'function') queueMicrotask(cb); return sock; };
|
|
7201
|
+
sock.close = (cb) => { queueMicrotask(() => { sock.emit('close'); if (typeof cb === 'function') cb(); }); return sock; };
|
|
7202
|
+
sock.send = notSupported('dgram.send');
|
|
7203
|
+
sock.address = () => ({ address: '0.0.0.0', family: 'IPv4', port: 0 });
|
|
7204
|
+
sock.setBroadcast = () => sock;
|
|
7205
|
+
sock.setTTL = () => sock;
|
|
7206
|
+
sock.addMembership = () => {};
|
|
7207
|
+
sock.dropMembership = () => {};
|
|
7208
|
+
return sock;
|
|
7209
|
+
},
|
|
7210
|
+
Socket: class Socket extends EventEmitter {}
|
|
7211
|
+
};
|
|
7212
|
+
const VirtualHttp2 = {
|
|
7213
|
+
constants: { NGHTTP2_REFUSED_STREAM: 7, NGHTTP2_CANCEL: 8 },
|
|
7214
|
+
connect: notSupported('http2.connect'),
|
|
7215
|
+
createServer: notSupported('http2.createServer'),
|
|
7216
|
+
createSecureServer: notSupported('http2.createSecureServer')
|
|
7217
|
+
};
|
|
7218
|
+
const VirtualCluster = {
|
|
7219
|
+
isPrimary: true,
|
|
7220
|
+
isMaster: true,
|
|
7221
|
+
isWorker: false,
|
|
7222
|
+
workers: {},
|
|
7223
|
+
fork: notSupported('cluster.fork'),
|
|
7224
|
+
setupPrimary: notSupported('cluster.setupPrimary'),
|
|
7225
|
+
setupMaster: notSupported('cluster.setupMaster'),
|
|
7226
|
+
disconnect: () => {}
|
|
7227
|
+
};
|
|
7228
|
+
const VirtualRepl = { start: notSupported('repl.start') };
|
|
7229
|
+
const VirtualInspector = {
|
|
7230
|
+
open: () => null,
|
|
7231
|
+
close: () => {},
|
|
7232
|
+
url: () => '',
|
|
7233
|
+
Session: class Session { connect() {} disconnect() {} post() {} }
|
|
7234
|
+
};
|
|
7235
|
+
const VirtualTraceEvents = {
|
|
7236
|
+
createTracing: () => ({ enable() {}, disable() {} }),
|
|
7237
|
+
getEnabledCategories: () => ''
|
|
7238
|
+
};
|
|
7239
|
+
const VirtualWasi = {
|
|
7240
|
+
WASI: class WASI { constructor() { throw new Error('wasi is not supported in the virtual runtime.'); } }
|
|
7241
|
+
};
|
|
7242
|
+
|
|
7243
|
+
const VirtualStreamWeb = {
|
|
7244
|
+
ReadableStream: typeof ReadableStream !== 'undefined' ? ReadableStream : undefined,
|
|
7245
|
+
WritableStream: typeof WritableStream !== 'undefined' ? WritableStream : undefined,
|
|
7246
|
+
TransformStream: typeof TransformStream !== 'undefined' ? TransformStream : undefined
|
|
7247
|
+
};
|
|
7248
|
+
async function consumeStream(kind, stream) {
|
|
7249
|
+
const chunks = [];
|
|
7250
|
+
if (stream && typeof stream[Symbol.asyncIterator] === 'function') {
|
|
7251
|
+
for await (const chunk of stream) chunks.push(chunk);
|
|
7252
|
+
} else if (stream && typeof stream.on === 'function') {
|
|
7253
|
+
await new Promise((resolve, reject) => {
|
|
7254
|
+
stream.on('data', (c) => chunks.push(c));
|
|
7255
|
+
stream.on('end', resolve);
|
|
7256
|
+
stream.on('error', reject);
|
|
7257
|
+
});
|
|
7258
|
+
}
|
|
7259
|
+
const bufs = chunks.map((c) => (typeof c === 'string' ? VirtualBuffer.from(c) : VirtualBuffer.from(c)));
|
|
7260
|
+
const buf = VirtualBuffer.concat(bufs);
|
|
7261
|
+
if (kind === 'buffer') return buf;
|
|
7262
|
+
if (kind === 'arrayBuffer') return buf.buffer ? buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) : new ArrayBuffer(0);
|
|
7263
|
+
if (kind === 'text') return buf.toString('utf8');
|
|
7264
|
+
if (kind === 'json') return JSON.parse(buf.toString('utf8'));
|
|
7265
|
+
return buf;
|
|
7266
|
+
}
|
|
7267
|
+
const VirtualStreamConsumers = {
|
|
7268
|
+
text: (s) => consumeStream('text', s),
|
|
7269
|
+
json: (s) => consumeStream('json', s),
|
|
7270
|
+
buffer: (s) => consumeStream('buffer', s),
|
|
7271
|
+
arrayBuffer: (s) => consumeStream('arrayBuffer', s)
|
|
7272
|
+
};
|
|
7273
|
+
|
|
6614
7274
|
const builtinModules = {
|
|
6615
7275
|
fs: vfs,
|
|
6616
7276
|
'node:fs': vfs,
|
|
@@ -6671,9 +7331,59 @@ function __initVirtualRuntime(rootScope) {
|
|
|
6671
7331
|
bun: BunObj,
|
|
6672
7332
|
'node:bun': BunObj,
|
|
6673
7333
|
'bun:test': bunTestModule,
|
|
6674
|
-
'bun:sqlite': { Database: SqliteDatabase }
|
|
7334
|
+
'bun:sqlite': { Database: SqliteDatabase },
|
|
7335
|
+
tty: VirtualTty,
|
|
7336
|
+
tls: VirtualTls,
|
|
7337
|
+
dgram: VirtualDgram,
|
|
7338
|
+
readline: VirtualReadline,
|
|
7339
|
+
'readline/promises': VirtualReadlinePromises,
|
|
7340
|
+
async_hooks: VirtualAsyncHooks,
|
|
7341
|
+
worker_threads: VirtualWorkerThreads,
|
|
7342
|
+
v8: VirtualV8,
|
|
7343
|
+
vm: VirtualVm,
|
|
7344
|
+
domain: VirtualDomain,
|
|
7345
|
+
diagnostics_channel: VirtualDiagnosticsChannel,
|
|
7346
|
+
http2: VirtualHttp2,
|
|
7347
|
+
cluster: VirtualCluster,
|
|
7348
|
+
repl: VirtualRepl,
|
|
7349
|
+
inspector: VirtualInspector,
|
|
7350
|
+
trace_events: VirtualTraceEvents,
|
|
7351
|
+
wasi: VirtualWasi,
|
|
7352
|
+
constants: vfs.constants,
|
|
7353
|
+
'util/types': VirtualUtil.types,
|
|
7354
|
+
'stream/web': VirtualStreamWeb,
|
|
7355
|
+
'stream/consumers': VirtualStreamConsumers
|
|
6675
7356
|
};
|
|
6676
7357
|
|
|
7358
|
+
// Auto-alias every builtin under the `node:` prefix (node:tty, node:readline…)
|
|
7359
|
+
// so both spellings resolve identically without hand-maintaining two lists.
|
|
7360
|
+
for (const __builtinName of Object.keys(builtinModules)) {
|
|
7361
|
+
if (!__builtinName.startsWith('node:') && !__builtinName.startsWith('bun:')) {
|
|
7362
|
+
builtinModules['node:' + __builtinName] = builtinModules[__builtinName];
|
|
7363
|
+
}
|
|
7364
|
+
}
|
|
7365
|
+
|
|
7366
|
+
// `module` must reference the now-complete builtin table, so it is attached
|
|
7367
|
+
// after the object literal above.
|
|
7368
|
+
const VirtualModule = {
|
|
7369
|
+
builtinModules: Object.keys(builtinModules),
|
|
7370
|
+
Module: class Module {},
|
|
7371
|
+
isBuiltin(name) { return Object.prototype.hasOwnProperty.call(builtinModules, String(name)); },
|
|
7372
|
+
createRequire(from) {
|
|
7373
|
+
const base = typeof from === 'string' ? from : '/workspace';
|
|
7374
|
+
const dir = /\.(?:js|mjs|cjs|ts|json)$/.test(base) ? VirtualPath.dirname(base) : base;
|
|
7375
|
+
const req = (id) => {
|
|
7376
|
+
if (Object.prototype.hasOwnProperty.call(builtinModules, id)) return builtinModules[id];
|
|
7377
|
+
return loadModule(resolveModulePath(id, dir), false);
|
|
7378
|
+
};
|
|
7379
|
+
req.resolve = (id) => resolveModulePath(id, dir);
|
|
7380
|
+
req.cache = {};
|
|
7381
|
+
return req;
|
|
7382
|
+
}
|
|
7383
|
+
};
|
|
7384
|
+
builtinModules.module = VirtualModule;
|
|
7385
|
+
builtinModules['node:module'] = VirtualModule;
|
|
7386
|
+
|
|
6677
7387
|
const moduleCache = new Map();
|
|
6678
7388
|
let mainModule = null;
|
|
6679
7389
|
|
|
@@ -7238,6 +7948,14 @@ function __initVirtualRuntime(rootScope) {
|
|
|
7238
7948
|
};
|
|
7239
7949
|
}
|
|
7240
7950
|
|
|
7951
|
+
// Transpile a source file so it can run natively in a browser as an ES module:
|
|
7952
|
+
// JSX is compiled to the classic runtime (auto-importing React when needed) and
|
|
7953
|
+
// TypeScript annotations are stripped, but `import`/`export` are preserved so an
|
|
7954
|
+
// import map can resolve bare specifiers to CDN ESM builds.
|
|
7955
|
+
function transpileForBrowser(source, filename = 'module.js') {
|
|
7956
|
+
return transpileTS(source, filename, { keepEsm: true });
|
|
7957
|
+
}
|
|
7958
|
+
|
|
7241
7959
|
return {
|
|
7242
7960
|
VirtualBuffer,
|
|
7243
7961
|
VirtualCrypto,
|
|
@@ -7257,6 +7975,7 @@ function __initVirtualRuntime(rootScope) {
|
|
|
7257
7975
|
createVirtualHttp,
|
|
7258
7976
|
createVirtualNet,
|
|
7259
7977
|
transpileTS,
|
|
7978
|
+
transpileForBrowser,
|
|
7260
7979
|
preloadNpmPackages,
|
|
7261
7980
|
createVirtualPortTable,
|
|
7262
7981
|
executeInVirtualRuntime
|