@innovatorved/code-lab 0.1.3 → 0.1.5

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/dist/runtime.js CHANGED
@@ -3973,14 +3973,316 @@ function __initVirtualRuntime(rootScope) {
3973
3973
  };
3974
3974
  }
3975
3975
 
3976
+ // =========================================================================
3977
+ // 7b. JSX / TSX SUPPORT
3978
+ // -------------------------------------------------------------------------
3979
+ // Rewrites JSX syntax into classic `createElement(...)` calls. This runs
3980
+ // BEFORE the string-masking pass so that JSX text (which routinely contains
3981
+ // quotes/apostrophes, e.g. <p>Don't</p>) is captured verbatim, while genuine
3982
+ // JS strings, comments and template literals are skipped untouched.
3983
+ // =========================================================================
3984
+ function detectJsxSyntax(source, filename) {
3985
+ if (/\.(jsx|tsx)$/i.test(filename || '')) return true;
3986
+ if (!source || source.indexOf('<') === -1) return false;
3987
+ if (/@jsx\b/.test(source)) return true;
3988
+ if (source.indexOf('<>') !== -1) return true;
3989
+ if (/<\/[A-Za-z]/.test(source)) return true;
3990
+ return false;
3991
+ }
3992
+
3993
+ function readJsxPragma(source) {
3994
+ let pragma = 'React.createElement';
3995
+ let frag = null;
3996
+ const m = /@jsx\s+([A-Za-z_$][\w$.]*)/.exec(source);
3997
+ if (m) pragma = m[1];
3998
+ const fm = /@jsxFrag\s+([A-Za-z_$][\w$.]*)/.exec(source);
3999
+ if (fm) frag = fm[1];
4000
+ if (!frag) frag = pragma === 'React.createElement' ? 'React.Fragment' : 'Fragment';
4001
+ return { pragma, frag };
4002
+ }
4003
+
4004
+ const JSX_WS_RE = /\s/;
4005
+ const JSX_NAME_START_RE = /[A-Za-z_$]/;
4006
+ const JSX_NAME_CHAR_RE = /[A-Za-z0-9_$:.\-]/;
4007
+
4008
+ function jsxThrow(message) {
4009
+ const err = new Error(message);
4010
+ err.jsxParse = true;
4011
+ throw err;
4012
+ }
4013
+
4014
+ // Returns the exclusive end index if a JS string / template / comment starts
4015
+ // at `i`, otherwise -1. Regexes are deliberately ignored.
4016
+ function jsxSkipJsLiteral(source, i) {
4017
+ const ch = source[i];
4018
+ const next = source[i + 1];
4019
+ const len = source.length;
4020
+ if (ch === '/' && next === '/') {
4021
+ const e = source.indexOf('\n', i);
4022
+ return e === -1 ? len : e;
4023
+ }
4024
+ if (ch === '/' && next === '*') {
4025
+ const e = source.indexOf('*/', i + 2);
4026
+ return e === -1 ? len : e + 2;
4027
+ }
4028
+ if (ch === '"' || ch === "'") {
4029
+ let j = i + 1;
4030
+ while (j < len) {
4031
+ const c = source[j];
4032
+ if (c === '\\') { j += 2; continue; }
4033
+ if (c === ch) { j++; break; }
4034
+ if (c === '\n') break;
4035
+ j++;
4036
+ }
4037
+ return j;
4038
+ }
4039
+ if (ch === '`') {
4040
+ let j = i + 1;
4041
+ let depth = 0;
4042
+ while (j < len) {
4043
+ const c = source[j];
4044
+ if (c === '\\') { j += 2; continue; }
4045
+ if (c === '$' && source[j + 1] === '{') { depth++; j += 2; continue; }
4046
+ if (c === '}' && depth > 0) { depth--; j++; continue; }
4047
+ if (c === '`' && depth === 0) { j++; break; }
4048
+ j++;
4049
+ }
4050
+ return j;
4051
+ }
4052
+ return -1;
4053
+ }
4054
+
4055
+ function jsxReadName(source, i) {
4056
+ if (!JSX_NAME_START_RE.test(source[i] || '')) jsxThrow('jsx: expected a tag name');
4057
+ let j = i;
4058
+ while (j < source.length && JSX_NAME_CHAR_RE.test(source[j])) j++;
4059
+ return { name: source.slice(i, j), next: j };
4060
+ }
4061
+
4062
+ function jsxSkipWs(source, i) {
4063
+ while (i < source.length && JSX_WS_RE.test(source[i])) i++;
4064
+ return i;
4065
+ }
4066
+
4067
+ function normalizeJsxText(raw) {
4068
+ if (!raw) return '';
4069
+ let t = raw.replace(/\r/g, '');
4070
+ if (t.indexOf('\n') !== -1) {
4071
+ t = t.split('\n').map((s) => s.replace(/[ \t]+/g, ' ').trim()).filter(Boolean).join(' ');
4072
+ } else if (!/\S/.test(t)) {
4073
+ return '';
4074
+ } else {
4075
+ t = t.replace(/[ \t]+/g, ' ');
4076
+ }
4077
+ return t ? JSON.stringify(t) : '';
4078
+ }
4079
+
4080
+ // Reads a balanced `{ ... }` expression container, skipping nested JSX and
4081
+ // JS literals. Returns the raw inner source (later re-transformed) plus the
4082
+ // index just past the closing brace.
4083
+ function jsxReadBraced(source, i, opts) {
4084
+ let depth = 0;
4085
+ let j = i;
4086
+ while (j < source.length) {
4087
+ const lit = jsxSkipJsLiteral(source, j);
4088
+ if (lit !== -1) { j = lit; continue; }
4089
+ const c = source[j];
4090
+ if (c === '{') { depth++; j++; continue; }
4091
+ if (c === '}') {
4092
+ depth--;
4093
+ j++;
4094
+ if (depth === 0) return { inner: source.slice(i + 1, j - 1), next: j };
4095
+ continue;
4096
+ }
4097
+ if (c === '<' && (JSX_NAME_START_RE.test(source[j + 1] || '') || source[j + 1] === '>')) {
4098
+ try {
4099
+ const el = jsxParseElement(source, j, opts);
4100
+ j = el.next;
4101
+ continue;
4102
+ } catch (e) {
4103
+ if (!e || !e.jsxParse) throw e;
4104
+ }
4105
+ }
4106
+ j++;
4107
+ }
4108
+ jsxThrow('jsx: unterminated expression container');
4109
+ }
4110
+
4111
+ function jsxParseElement(source, i, opts) {
4112
+ const o = opts || readJsxPragma(source);
4113
+ let j = i + 1;
4114
+ let isFragment = false;
4115
+ let typeExpr;
4116
+ if (source[j] === '>') {
4117
+ isFragment = true;
4118
+ typeExpr = o.frag;
4119
+ j++;
4120
+ } else {
4121
+ const nm = jsxReadName(source, j);
4122
+ j = nm.next;
4123
+ const raw = nm.name;
4124
+ const isReference = raw.indexOf('.') !== -1 || raw.indexOf(':') !== -1 || /^[A-Z_$]/.test(raw);
4125
+ if (isReference) {
4126
+ typeExpr = raw.replace(/:/g, '.');
4127
+ } else {
4128
+ typeExpr = JSON.stringify(raw);
4129
+ }
4130
+ }
4131
+
4132
+ const props = [];
4133
+ let selfClosing = false;
4134
+ if (!isFragment) {
4135
+ for (;;) {
4136
+ j = jsxSkipWs(source, j);
4137
+ if (j >= source.length) jsxThrow('jsx: unexpected end of input inside a tag');
4138
+ const c = source[j];
4139
+ if (c === '/') {
4140
+ if (source[j + 1] !== '>') jsxThrow('jsx: malformed self-closing tag');
4141
+ j += 2;
4142
+ selfClosing = true;
4143
+ break;
4144
+ }
4145
+ if (c === '>') { j++; break; }
4146
+ if (c === '{') {
4147
+ const br = jsxReadBraced(source, j, o);
4148
+ const inner = br.inner.trim();
4149
+ if (inner.slice(0, 3) !== '...') jsxThrow('jsx: only a spread {...} may appear where an attribute is expected');
4150
+ props.push({ spread: jsxTransform(inner.slice(3), o) });
4151
+ j = br.next;
4152
+ continue;
4153
+ }
4154
+ if (!JSX_NAME_START_RE.test(c)) jsxThrow('jsx: malformed attribute');
4155
+ const am = jsxReadName(source, j);
4156
+ const attrName = am.name;
4157
+ j = jsxSkipWs(source, am.next);
4158
+ let valueExpr = 'true';
4159
+ if (source[j] === '=') {
4160
+ j = jsxSkipWs(source, j + 1);
4161
+ const vc = source[j];
4162
+ if (vc === '"' || vc === "'") {
4163
+ let k = j + 1;
4164
+ while (k < source.length && source[k] !== vc) {
4165
+ if (source[k] === '\\') k++;
4166
+ k++;
4167
+ }
4168
+ if (k >= source.length) jsxThrow('jsx: unterminated attribute string');
4169
+ valueExpr = JSON.stringify(source.slice(j + 1, k));
4170
+ j = k + 1;
4171
+ } else if (vc === '{') {
4172
+ const br = jsxReadBraced(source, j, o);
4173
+ valueExpr = jsxTransform(br.inner, o) || 'undefined';
4174
+ j = br.next;
4175
+ } else if (vc === '<') {
4176
+ const el = jsxParseElement(source, j, o);
4177
+ valueExpr = el.code;
4178
+ j = el.next;
4179
+ } else {
4180
+ jsxThrow('jsx: unsupported attribute value');
4181
+ }
4182
+ }
4183
+ const propKey = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(attrName) ? attrName : JSON.stringify(attrName);
4184
+ props.push({ key: propKey, value: valueExpr });
4185
+ }
4186
+ }
4187
+
4188
+ const children = [];
4189
+ if (!selfClosing) {
4190
+ for (;;) {
4191
+ if (j >= source.length) jsxThrow('jsx: missing closing tag');
4192
+ const c = source[j];
4193
+ if (c === '<' && source[j + 1] === '/') {
4194
+ j = jsxSkipWs(source, j + 2);
4195
+ if (source[j] === '>') { j++; break; }
4196
+ const cm = jsxReadName(source, j);
4197
+ j = jsxSkipWs(source, cm.next);
4198
+ if (source[j] !== '>') jsxThrow('jsx: malformed closing tag');
4199
+ j++;
4200
+ break;
4201
+ }
4202
+ if (c === '<') {
4203
+ const el = jsxParseElement(source, j, o);
4204
+ children.push(el.code);
4205
+ j = el.next;
4206
+ continue;
4207
+ }
4208
+ if (c === '{') {
4209
+ const br = jsxReadBraced(source, j, o);
4210
+ const inner = jsxTransform(br.inner, o);
4211
+ if (inner && inner.trim()) children.push(inner);
4212
+ j = br.next;
4213
+ continue;
4214
+ }
4215
+ let k = j;
4216
+ while (k < source.length && source[k] !== '<' && source[k] !== '{') k++;
4217
+ const text = normalizeJsxText(source.slice(j, k));
4218
+ if (text) children.push(text);
4219
+ j = k;
4220
+ }
4221
+ }
4222
+
4223
+ let propsCode = 'null';
4224
+ if (props.length) {
4225
+ const parts = props.map((p) => (p.spread !== undefined ? '...(' + p.spread + ')' : p.key + ': ' + p.value));
4226
+ propsCode = '{ ' + parts.join(', ') + ' }';
4227
+ }
4228
+
4229
+ const args = [typeExpr, propsCode].concat(children);
4230
+ return { code: o.pragma + '(' + args.join(', ') + ')', next: j };
4231
+ }
4232
+
4233
+ function jsxTransform(source, opts) {
4234
+ const o = opts || readJsxPragma(source);
4235
+ let i = 0;
4236
+ let out = '';
4237
+ while (i < source.length) {
4238
+ const lit = jsxSkipJsLiteral(source, i);
4239
+ if (lit !== -1) { out += source.slice(i, lit); i = lit; continue; }
4240
+ const ch = source[i];
4241
+ if (ch === '<' && (JSX_NAME_START_RE.test(source[i + 1] || '') || source[i + 1] === '>')) {
4242
+ try {
4243
+ const el = jsxParseElement(source, i, o);
4244
+ out += el.code;
4245
+ i = el.next;
4246
+ continue;
4247
+ } catch (e) {
4248
+ if (!e || !e.jsxParse) throw e;
4249
+ }
4250
+ }
4251
+ out += ch;
4252
+ i++;
4253
+ }
4254
+ return out;
4255
+ }
4256
+
3976
4257
  // =========================================================================
3977
4258
  // 8. FAST TYPESCRIPT & ESM-TO-CJS TRANSPILER
3978
4259
  // =========================================================================
3979
- function transpileTS(source, filename = 'module.ts') {
4260
+ function transpileTS(source, filename = 'module.ts', opts = {}) {
4261
+ // `keepEsm` leaves `import`/`export` statements intact so the output can run
4262
+ // natively in a browser as an ES module (used by the built-in preview server).
4263
+ const keepEsm = Boolean(opts && opts.keepEsm);
3980
4264
  const isTS = /\.(ts|tsx|mts|cts)$/i.test(filename)
3981
- || /\b(interface\s+[A-Za-z_$]|type\s+[A-Za-z_$][A-Za-z0-9_$]*\s*(?:<[^>]*>)?\s*=|enum\s+[A-Za-z_$]|abstract\s+class\s+|declare\s+(?:const|let|var|function|class|type|interface)\b|public\s+|private\s+|protected\s+|readonly\s+|satisfies\s+[A-Za-z_${]|\bas\s+(?:const|unknown|any|[A-Za-z_${]))/m.test(source);
3982
- const hasESM = /^\s*(import|export)\s+/m.test(source);
3983
- if (!isTS && !hasESM) return source;
4265
+ || /^[ \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);
4266
+ const hasESM = /^\s*(?:import|export)\b/m.test(source)
4267
+ || /\bexport\s*\{/.test(source)
4268
+ || /\bimport\s*\{/.test(source)
4269
+ || /\bexport\s+default\b/.test(source);
4270
+ const hasJsx = detectJsxSyntax(source, filename);
4271
+ if (!isTS && !hasESM && !hasJsx) return source;
4272
+
4273
+ // JSX/TSX must be rewritten before masking so JSX text is kept verbatim.
4274
+ if (hasJsx) {
4275
+ const { pragma, frag } = readJsxPragma(source);
4276
+ const needsReact = pragma === 'React.createElement' && !/\bReact\b/.test(source);
4277
+ const transformed = jsxTransform(source, { pragma, frag });
4278
+ if (transformed !== source) {
4279
+ source = transformed;
4280
+ // The classic runtime needs a React binding available to the JSX output.
4281
+ if (needsReact) {
4282
+ source = (keepEsm ? 'import React from "react";\n' : 'const React = require("react");\n') + source;
4283
+ }
4284
+ }
4285
+ }
3984
4286
 
3985
4287
  // Step 1: Mask strings, template literals, regex literals, and comments so transforms never corrupt literals
3986
4288
  const placeholders = [];
@@ -4543,10 +4845,10 @@ function __initVirtualRuntime(rootScope) {
4543
4845
  } while (code !== prevCode);
4544
4846
  }
4545
4847
 
4546
- if (hasESM || isTS) {
4848
+ if ((hasESM || isTS) && !keepEsm) {
4547
4849
  // Convert ES module imports (including multi-line `{ ... }`)
4548
- code = code.replace(/^\s*import\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, 'const $1 = require($2);');
4549
- code = code.replace(/^\s*import\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*\{([\s\S]*?)\}\s+from\s+([^\n;]+);?/gm, (_, defId, specifiers, mod) => {
4850
+ code = code.replace(/\bimport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, 'const $1 = require($2);');
4851
+ 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
4852
  const cleaned = specifiers
4551
4853
  .split(',')
4552
4854
  .map((s) => s.trim())
@@ -4557,7 +4859,7 @@ function __initVirtualRuntime(rootScope) {
4557
4859
  return `const ${defId} = (function(m){ return m && m.__esModule ? m.default : m; })(require(${mTrim}));` +
4558
4860
  (cleaned ? ` const { ${cleaned} } = require(${mTrim});` : '');
4559
4861
  });
4560
- code = code.replace(/^\s*import\s+\{([\s\S]*?)\}\s+from\s+([^\n;]+);?/gm, (_, specifiers, mod) => {
4862
+ code = code.replace(/\bimport\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, specifiers, mod) => {
4561
4863
  const cleaned = specifiers
4562
4864
  .split(',')
4563
4865
  .map((s) => s.trim())
@@ -4566,42 +4868,42 @@ function __initVirtualRuntime(rootScope) {
4566
4868
  .join(', ');
4567
4869
  return cleaned ? `const { ${cleaned} } = require(${mod.trim()});` : '';
4568
4870
  });
4569
- code = code.replace(/^\s*import\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));');
4570
- code = code.replace(/^\s*import\s+(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
4871
+ 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));');
4872
+ code = code.replace(/\bimport\s+(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
4571
4873
 
4572
4874
  // Convert ES module exports
4573
4875
  const exportedNames = [];
4574
4876
  let defaultExportName = null;
4575
4877
  let hasEsmExport = false;
4576
4878
 
4577
- code = code.replace(/^\s*export\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, (_, ns, mod) => {
4879
+ code = code.replace(/\bexport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, (_, ns, mod) => {
4578
4880
  hasEsmExport = true;
4579
4881
  return `exports.${ns} = require(${mod.trim()});`;
4580
4882
  });
4581
- code = code.replace(/^\s*export\s+\*\s+from\s+([^\n;]+);?/gm, (_, mod) => {
4883
+ code = code.replace(/\bexport\s*\*\s*from\s*([^\n;]+);?/gm, (_, mod) => {
4582
4884
  hasEsmExport = true;
4583
4885
  return `Object.assign(exports, require(${mod.trim()}));`;
4584
4886
  });
4585
- code = code.replace(/^\s*export\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4887
+ code = code.replace(/\bexport\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4586
4888
  hasEsmExport = true;
4587
4889
  defaultExportName = name;
4588
4890
  return `${kw} ${name}`;
4589
4891
  });
4590
- code = code.replace(/^\s*export\s+default\s+/gm, () => {
4892
+ code = code.replace(/\bexport\s+default\s+/gm, () => {
4591
4893
  hasEsmExport = true;
4592
4894
  return 'exports.default = ';
4593
4895
  });
4594
- code = code.replace(/^\s*export\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4896
+ code = code.replace(/\bexport\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4595
4897
  hasEsmExport = true;
4596
4898
  exportedNames.push(name);
4597
4899
  return `${kw} ${name}`;
4598
4900
  });
4599
- code = code.replace(/^\s*export\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4901
+ code = code.replace(/\bexport\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4600
4902
  hasEsmExport = true;
4601
4903
  exportedNames.push(name);
4602
4904
  return `${kw} ${name}`;
4603
4905
  });
4604
- code = code.replace(/^\s*export\s+\{([^}]+)\}\s+from\s+([^\n;]+);?/gm, (_, list, mod) => {
4906
+ code = code.replace(/\bexport\s*\{([^}]+)\}\s*from\s*([^\n;]+);?/gm, (_, list, mod) => {
4605
4907
  hasEsmExport = true;
4606
4908
  const mTrim = mod.trim();
4607
4909
  return list.split(',').map((item) => {
@@ -4613,7 +4915,7 @@ function __initVirtualRuntime(rootScope) {
4613
4915
  return `exports.${exported} = require(${mTrim}).${local};`;
4614
4916
  }).join(' ');
4615
4917
  });
4616
- code = code.replace(/^\s*export\s+\{([^}]+)\}\s*;?/gm, (_, list) => {
4918
+ code = code.replace(/\bexport\s*\{([^}]+)\}\s*;?/gm, (_, list) => {
4617
4919
  hasEsmExport = true;
4618
4920
  return list.split(',').map((item) => {
4619
4921
  const trimmed = item.trim();
@@ -4680,8 +4982,22 @@ function __initVirtualRuntime(rootScope) {
4680
4982
  }
4681
4983
 
4682
4984
  const _npmPackageCache = new Map();
4985
+ const _npmMetadataCache = new Map();
4986
+
4987
+ async function preloadNpmPackages(files = {}, secondArg = null, thirdArg = null) {
4988
+ // The 2nd/3rd arguments are overloaded for backwards compatibility:
4989
+ // preloadNpmPackages(files)
4990
+ // preloadNpmPackages(files, onProgress) // progress callback (used by the Workbench)
4991
+ // preloadNpmPackages(files, existingCache) // package-text cache (Map)
4992
+ // preloadNpmPackages(files, existingCache, onProgress)
4993
+ const isCacheLike = (v) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
4994
+ let onProgress = null;
4995
+ let existingCache = _npmPackageCache;
4996
+ if (typeof secondArg === 'function') onProgress = secondArg;
4997
+ else if (isCacheLike(secondArg)) existingCache = secondArg;
4998
+ if (typeof thirdArg === 'function') onProgress = onProgress || thirdArg;
4999
+ else if (isCacheLike(thirdArg)) existingCache = thirdArg;
4683
5000
 
4684
- async function preloadNpmPackages(files = {}, existingCache = _npmPackageCache) {
4685
5001
  const specs = new Set();
4686
5002
  const builtinSet = new Set([
4687
5003
  'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
@@ -4717,20 +5033,51 @@ function __initVirtualRuntime(rootScope) {
4717
5033
  while ((m = impRe.exec(content)) !== null) addSpec(m[1]);
4718
5034
  }
4719
5035
 
5036
+ // Follow declared dependencies transitively (best effort, bounded). Metadata
5037
+ // is memoised across calls so repeated preloads stay cheap.
5038
+ if (typeof fetch === 'function') {
5039
+ let pass = 0;
5040
+ while (pass < 6) {
5041
+ const pending = [];
5042
+ for (const pkg of specs) {
5043
+ if (!_npmMetadataCache.has(pkg)) pending.push(pkg);
5044
+ }
5045
+ if (pending.length === 0) break;
5046
+ pass++;
5047
+ await Promise.all(pending.map(async (pkg) => {
5048
+ let deps = [];
5049
+ try {
5050
+ const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}/package.json`);
5051
+ if (res && res.ok) {
5052
+ const meta = await res.json();
5053
+ deps = Object.keys((meta && meta.dependencies) || {});
5054
+ }
5055
+ } catch (_) {}
5056
+ _npmMetadataCache.set(pkg, deps);
5057
+ }));
5058
+ for (const pkg of pending) {
5059
+ for (const dep of (_npmMetadataCache.get(pkg) || [])) addSpec(dep);
5060
+ }
5061
+ }
5062
+ }
5063
+
4720
5064
  const loaded = {};
4721
5065
  for (const pkg of specs) {
4722
5066
  const nmKey = `node_modules/${pkg}/index.js`;
4723
5067
  if (files[nmKey] || files[`/workspace/${nmKey}`]) continue;
4724
- if (existingCache && existingCache.has(pkg)) {
5068
+ if (existingCache.has(pkg)) {
4725
5069
  loaded[pkg] = existingCache.get(pkg);
4726
5070
  continue;
4727
5071
  }
5072
+ if (typeof onProgress === 'function') {
5073
+ try { onProgress(pkg); } catch (_) {}
5074
+ }
4728
5075
  if (typeof fetch === 'function') {
4729
5076
  try {
4730
5077
  const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}`);
4731
5078
  if (res && res.ok) {
4732
5079
  const text = await res.text();
4733
- if (existingCache) existingCache.set(pkg, text);
5080
+ if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
4734
5081
  loaded[pkg] = text;
4735
5082
  }
4736
5083
  } catch (_) {}
@@ -7193,6 +7540,14 @@ function __initVirtualRuntime(rootScope) {
7193
7540
  };
7194
7541
  }
7195
7542
 
7543
+ // Transpile a source file so it can run natively in a browser as an ES module:
7544
+ // JSX is compiled to the classic runtime (auto-importing React when needed) and
7545
+ // TypeScript annotations are stripped, but `import`/`export` are preserved so an
7546
+ // import map can resolve bare specifiers to CDN ESM builds.
7547
+ function transpileForBrowser(source, filename = 'module.js') {
7548
+ return transpileTS(source, filename, { keepEsm: true });
7549
+ }
7550
+
7196
7551
  return {
7197
7552
  VirtualBuffer,
7198
7553
  VirtualCrypto,
@@ -7212,6 +7567,7 @@ function __initVirtualRuntime(rootScope) {
7212
7567
  createVirtualHttp,
7213
7568
  createVirtualNet,
7214
7569
  transpileTS,
7570
+ transpileForBrowser,
7215
7571
  preloadNpmPackages,
7216
7572
  createVirtualPortTable,
7217
7573
  executeInVirtualRuntime