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