@innovatorved/code-lab 0.1.4 → 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/src/runtime.ts CHANGED
@@ -3955,14 +3955,316 @@ function __initVirtualRuntime(rootScope) {
3955
3955
  };
3956
3956
  }
3957
3957
 
3958
+ // =========================================================================
3959
+ // 7b. JSX / TSX SUPPORT
3960
+ // -------------------------------------------------------------------------
3961
+ // Rewrites JSX syntax into classic `createElement(...)` calls. This runs
3962
+ // BEFORE the string-masking pass so that JSX text (which routinely contains
3963
+ // quotes/apostrophes, e.g. <p>Don't</p>) is captured verbatim, while genuine
3964
+ // JS strings, comments and template literals are skipped untouched.
3965
+ // =========================================================================
3966
+ function detectJsxSyntax(source, filename) {
3967
+ if (/\.(jsx|tsx)$/i.test(filename || '')) return true;
3968
+ if (!source || source.indexOf('<') === -1) return false;
3969
+ if (/@jsx\b/.test(source)) return true;
3970
+ if (source.indexOf('<>') !== -1) return true;
3971
+ if (/<\/[A-Za-z]/.test(source)) return true;
3972
+ return false;
3973
+ }
3974
+
3975
+ function readJsxPragma(source) {
3976
+ let pragma = 'React.createElement';
3977
+ let frag = null;
3978
+ const m = /@jsx\s+([A-Za-z_$][\w$.]*)/.exec(source);
3979
+ if (m) pragma = m[1];
3980
+ const fm = /@jsxFrag\s+([A-Za-z_$][\w$.]*)/.exec(source);
3981
+ if (fm) frag = fm[1];
3982
+ if (!frag) frag = pragma === 'React.createElement' ? 'React.Fragment' : 'Fragment';
3983
+ return { pragma, frag };
3984
+ }
3985
+
3986
+ const JSX_WS_RE = /\s/;
3987
+ const JSX_NAME_START_RE = /[A-Za-z_$]/;
3988
+ const JSX_NAME_CHAR_RE = /[A-Za-z0-9_$:.\-]/;
3989
+
3990
+ function jsxThrow(message) {
3991
+ const err = new Error(message);
3992
+ err.jsxParse = true;
3993
+ throw err;
3994
+ }
3995
+
3996
+ // Returns the exclusive end index if a JS string / template / comment starts
3997
+ // at `i`, otherwise -1. Regexes are deliberately ignored.
3998
+ function jsxSkipJsLiteral(source, i) {
3999
+ const ch = source[i];
4000
+ const next = source[i + 1];
4001
+ const len = source.length;
4002
+ if (ch === '/' && next === '/') {
4003
+ const e = source.indexOf('\n', i);
4004
+ return e === -1 ? len : e;
4005
+ }
4006
+ if (ch === '/' && next === '*') {
4007
+ const e = source.indexOf('*/', i + 2);
4008
+ return e === -1 ? len : e + 2;
4009
+ }
4010
+ if (ch === '"' || ch === "'") {
4011
+ let j = i + 1;
4012
+ while (j < len) {
4013
+ const c = source[j];
4014
+ if (c === '\\') { j += 2; continue; }
4015
+ if (c === ch) { j++; break; }
4016
+ if (c === '\n') break;
4017
+ j++;
4018
+ }
4019
+ return j;
4020
+ }
4021
+ if (ch === '`') {
4022
+ let j = i + 1;
4023
+ let depth = 0;
4024
+ while (j < len) {
4025
+ const c = source[j];
4026
+ if (c === '\\') { j += 2; continue; }
4027
+ if (c === '$' && source[j + 1] === '{') { depth++; j += 2; continue; }
4028
+ if (c === '}' && depth > 0) { depth--; j++; continue; }
4029
+ if (c === '`' && depth === 0) { j++; break; }
4030
+ j++;
4031
+ }
4032
+ return j;
4033
+ }
4034
+ return -1;
4035
+ }
4036
+
4037
+ function jsxReadName(source, i) {
4038
+ if (!JSX_NAME_START_RE.test(source[i] || '')) jsxThrow('jsx: expected a tag name');
4039
+ let j = i;
4040
+ while (j < source.length && JSX_NAME_CHAR_RE.test(source[j])) j++;
4041
+ return { name: source.slice(i, j), next: j };
4042
+ }
4043
+
4044
+ function jsxSkipWs(source, i) {
4045
+ while (i < source.length && JSX_WS_RE.test(source[i])) i++;
4046
+ return i;
4047
+ }
4048
+
4049
+ function normalizeJsxText(raw) {
4050
+ if (!raw) return '';
4051
+ let t = raw.replace(/\r/g, '');
4052
+ if (t.indexOf('\n') !== -1) {
4053
+ t = t.split('\n').map((s) => s.replace(/[ \t]+/g, ' ').trim()).filter(Boolean).join(' ');
4054
+ } else if (!/\S/.test(t)) {
4055
+ return '';
4056
+ } else {
4057
+ t = t.replace(/[ \t]+/g, ' ');
4058
+ }
4059
+ return t ? JSON.stringify(t) : '';
4060
+ }
4061
+
4062
+ // Reads a balanced `{ ... }` expression container, skipping nested JSX and
4063
+ // JS literals. Returns the raw inner source (later re-transformed) plus the
4064
+ // index just past the closing brace.
4065
+ function jsxReadBraced(source, i, opts) {
4066
+ let depth = 0;
4067
+ let j = i;
4068
+ while (j < source.length) {
4069
+ const lit = jsxSkipJsLiteral(source, j);
4070
+ if (lit !== -1) { j = lit; continue; }
4071
+ const c = source[j];
4072
+ if (c === '{') { depth++; j++; continue; }
4073
+ if (c === '}') {
4074
+ depth--;
4075
+ j++;
4076
+ if (depth === 0) return { inner: source.slice(i + 1, j - 1), next: j };
4077
+ continue;
4078
+ }
4079
+ if (c === '<' && (JSX_NAME_START_RE.test(source[j + 1] || '') || source[j + 1] === '>')) {
4080
+ try {
4081
+ const el = jsxParseElement(source, j, opts);
4082
+ j = el.next;
4083
+ continue;
4084
+ } catch (e) {
4085
+ if (!e || !e.jsxParse) throw e;
4086
+ }
4087
+ }
4088
+ j++;
4089
+ }
4090
+ jsxThrow('jsx: unterminated expression container');
4091
+ }
4092
+
4093
+ function jsxParseElement(source, i, opts) {
4094
+ const o = opts || readJsxPragma(source);
4095
+ let j = i + 1;
4096
+ let isFragment = false;
4097
+ let typeExpr;
4098
+ if (source[j] === '>') {
4099
+ isFragment = true;
4100
+ typeExpr = o.frag;
4101
+ j++;
4102
+ } else {
4103
+ const nm = jsxReadName(source, j);
4104
+ j = nm.next;
4105
+ const raw = nm.name;
4106
+ const isReference = raw.indexOf('.') !== -1 || raw.indexOf(':') !== -1 || /^[A-Z_$]/.test(raw);
4107
+ if (isReference) {
4108
+ typeExpr = raw.replace(/:/g, '.');
4109
+ } else {
4110
+ typeExpr = JSON.stringify(raw);
4111
+ }
4112
+ }
4113
+
4114
+ const props = [];
4115
+ let selfClosing = false;
4116
+ if (!isFragment) {
4117
+ for (;;) {
4118
+ j = jsxSkipWs(source, j);
4119
+ if (j >= source.length) jsxThrow('jsx: unexpected end of input inside a tag');
4120
+ const c = source[j];
4121
+ if (c === '/') {
4122
+ if (source[j + 1] !== '>') jsxThrow('jsx: malformed self-closing tag');
4123
+ j += 2;
4124
+ selfClosing = true;
4125
+ break;
4126
+ }
4127
+ if (c === '>') { j++; break; }
4128
+ if (c === '{') {
4129
+ const br = jsxReadBraced(source, j, o);
4130
+ const inner = br.inner.trim();
4131
+ if (inner.slice(0, 3) !== '...') jsxThrow('jsx: only a spread {...} may appear where an attribute is expected');
4132
+ props.push({ spread: jsxTransform(inner.slice(3), o) });
4133
+ j = br.next;
4134
+ continue;
4135
+ }
4136
+ if (!JSX_NAME_START_RE.test(c)) jsxThrow('jsx: malformed attribute');
4137
+ const am = jsxReadName(source, j);
4138
+ const attrName = am.name;
4139
+ j = jsxSkipWs(source, am.next);
4140
+ let valueExpr = 'true';
4141
+ if (source[j] === '=') {
4142
+ j = jsxSkipWs(source, j + 1);
4143
+ const vc = source[j];
4144
+ if (vc === '"' || vc === "'") {
4145
+ let k = j + 1;
4146
+ while (k < source.length && source[k] !== vc) {
4147
+ if (source[k] === '\\') k++;
4148
+ k++;
4149
+ }
4150
+ if (k >= source.length) jsxThrow('jsx: unterminated attribute string');
4151
+ valueExpr = JSON.stringify(source.slice(j + 1, k));
4152
+ j = k + 1;
4153
+ } else if (vc === '{') {
4154
+ const br = jsxReadBraced(source, j, o);
4155
+ valueExpr = jsxTransform(br.inner, o) || 'undefined';
4156
+ j = br.next;
4157
+ } else if (vc === '<') {
4158
+ const el = jsxParseElement(source, j, o);
4159
+ valueExpr = el.code;
4160
+ j = el.next;
4161
+ } else {
4162
+ jsxThrow('jsx: unsupported attribute value');
4163
+ }
4164
+ }
4165
+ const propKey = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(attrName) ? attrName : JSON.stringify(attrName);
4166
+ props.push({ key: propKey, value: valueExpr });
4167
+ }
4168
+ }
4169
+
4170
+ const children = [];
4171
+ if (!selfClosing) {
4172
+ for (;;) {
4173
+ if (j >= source.length) jsxThrow('jsx: missing closing tag');
4174
+ const c = source[j];
4175
+ if (c === '<' && source[j + 1] === '/') {
4176
+ j = jsxSkipWs(source, j + 2);
4177
+ if (source[j] === '>') { j++; break; }
4178
+ const cm = jsxReadName(source, j);
4179
+ j = jsxSkipWs(source, cm.next);
4180
+ if (source[j] !== '>') jsxThrow('jsx: malformed closing tag');
4181
+ j++;
4182
+ break;
4183
+ }
4184
+ if (c === '<') {
4185
+ const el = jsxParseElement(source, j, o);
4186
+ children.push(el.code);
4187
+ j = el.next;
4188
+ continue;
4189
+ }
4190
+ if (c === '{') {
4191
+ const br = jsxReadBraced(source, j, o);
4192
+ const inner = jsxTransform(br.inner, o);
4193
+ if (inner && inner.trim()) children.push(inner);
4194
+ j = br.next;
4195
+ continue;
4196
+ }
4197
+ let k = j;
4198
+ while (k < source.length && source[k] !== '<' && source[k] !== '{') k++;
4199
+ const text = normalizeJsxText(source.slice(j, k));
4200
+ if (text) children.push(text);
4201
+ j = k;
4202
+ }
4203
+ }
4204
+
4205
+ let propsCode = 'null';
4206
+ if (props.length) {
4207
+ const parts = props.map((p) => (p.spread !== undefined ? '...(' + p.spread + ')' : p.key + ': ' + p.value));
4208
+ propsCode = '{ ' + parts.join(', ') + ' }';
4209
+ }
4210
+
4211
+ const args = [typeExpr, propsCode].concat(children);
4212
+ return { code: o.pragma + '(' + args.join(', ') + ')', next: j };
4213
+ }
4214
+
4215
+ function jsxTransform(source, opts) {
4216
+ const o = opts || readJsxPragma(source);
4217
+ let i = 0;
4218
+ let out = '';
4219
+ while (i < source.length) {
4220
+ const lit = jsxSkipJsLiteral(source, i);
4221
+ if (lit !== -1) { out += source.slice(i, lit); i = lit; continue; }
4222
+ const ch = source[i];
4223
+ if (ch === '<' && (JSX_NAME_START_RE.test(source[i + 1] || '') || source[i + 1] === '>')) {
4224
+ try {
4225
+ const el = jsxParseElement(source, i, o);
4226
+ out += el.code;
4227
+ i = el.next;
4228
+ continue;
4229
+ } catch (e) {
4230
+ if (!e || !e.jsxParse) throw e;
4231
+ }
4232
+ }
4233
+ out += ch;
4234
+ i++;
4235
+ }
4236
+ return out;
4237
+ }
4238
+
3958
4239
  // =========================================================================
3959
4240
  // 8. FAST TYPESCRIPT & ESM-TO-CJS TRANSPILER
3960
4241
  // =========================================================================
3961
- function transpileTS(source, filename = 'module.ts') {
4242
+ function transpileTS(source, filename = 'module.ts', opts = {}) {
4243
+ // `keepEsm` leaves `import`/`export` statements intact so the output can run
4244
+ // natively in a browser as an ES module (used by the built-in preview server).
4245
+ const keepEsm = Boolean(opts && opts.keepEsm);
3962
4246
  const isTS = /\.(ts|tsx|mts|cts)$/i.test(filename)
3963
- || /\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);
3964
- const hasESM = /^\s*(import|export)\s+/m.test(source);
3965
- if (!isTS && !hasESM) return source;
4247
+ || /^[ \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);
4248
+ const hasESM = /^\s*(?:import|export)\b/m.test(source)
4249
+ || /\bexport\s*\{/.test(source)
4250
+ || /\bimport\s*\{/.test(source)
4251
+ || /\bexport\s+default\b/.test(source);
4252
+ const hasJsx = detectJsxSyntax(source, filename);
4253
+ if (!isTS && !hasESM && !hasJsx) return source;
4254
+
4255
+ // JSX/TSX must be rewritten before masking so JSX text is kept verbatim.
4256
+ if (hasJsx) {
4257
+ const { pragma, frag } = readJsxPragma(source);
4258
+ const needsReact = pragma === 'React.createElement' && !/\bReact\b/.test(source);
4259
+ const transformed = jsxTransform(source, { pragma, frag });
4260
+ if (transformed !== source) {
4261
+ source = transformed;
4262
+ // The classic runtime needs a React binding available to the JSX output.
4263
+ if (needsReact) {
4264
+ source = (keepEsm ? 'import React from "react";\n' : 'const React = require("react");\n') + source;
4265
+ }
4266
+ }
4267
+ }
3966
4268
 
3967
4269
  // Step 1: Mask strings, template literals, regex literals, and comments so transforms never corrupt literals
3968
4270
  const placeholders = [];
@@ -4525,10 +4827,10 @@ function __initVirtualRuntime(rootScope) {
4525
4827
  } while (code !== prevCode);
4526
4828
  }
4527
4829
 
4528
- if (hasESM || isTS) {
4830
+ if ((hasESM || isTS) && !keepEsm) {
4529
4831
  // Convert ES module imports (including multi-line `{ ... }`)
4530
- 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);');
4531
- 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) => {
4832
+ code = code.replace(/\bimport\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, 'const $1 = require($2);');
4833
+ 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
4834
  const cleaned = specifiers
4533
4835
  .split(',')
4534
4836
  .map((s) => s.trim())
@@ -4539,7 +4841,7 @@ function __initVirtualRuntime(rootScope) {
4539
4841
  return `const ${defId} = (function(m){ return m && m.__esModule ? m.default : m; })(require(${mTrim}));` +
4540
4842
  (cleaned ? ` const { ${cleaned} } = require(${mTrim});` : '');
4541
4843
  });
4542
- code = code.replace(/^\s*import\s+\{([\s\S]*?)\}\s+from\s+([^\n;]+);?/gm, (_, specifiers, mod) => {
4844
+ code = code.replace(/\bimport\s+\{([\s\S]*?)\}\s+from\s+([^\n;]+);?/gm, (_, specifiers, mod) => {
4543
4845
  const cleaned = specifiers
4544
4846
  .split(',')
4545
4847
  .map((s) => s.trim())
@@ -4548,42 +4850,42 @@ function __initVirtualRuntime(rootScope) {
4548
4850
  .join(', ');
4549
4851
  return cleaned ? `const { ${cleaned} } = require(${mod.trim()});` : '';
4550
4852
  });
4551
- 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));');
4552
- code = code.replace(/^\s*import\s+(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
4853
+ 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));');
4854
+ code = code.replace(/\bimport\s+(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
4553
4855
 
4554
4856
  // Convert ES module exports
4555
4857
  const exportedNames = [];
4556
4858
  let defaultExportName = null;
4557
4859
  let hasEsmExport = false;
4558
4860
 
4559
- code = code.replace(/^\s*export\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, (_, ns, mod) => {
4861
+ code = code.replace(/\bexport\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, (_, ns, mod) => {
4560
4862
  hasEsmExport = true;
4561
4863
  return `exports.${ns} = require(${mod.trim()});`;
4562
4864
  });
4563
- code = code.replace(/^\s*export\s+\*\s+from\s+([^\n;]+);?/gm, (_, mod) => {
4865
+ code = code.replace(/\bexport\s+\*\s+from\s+([^\n;]+);?/gm, (_, mod) => {
4564
4866
  hasEsmExport = true;
4565
4867
  return `Object.assign(exports, require(${mod.trim()}));`;
4566
4868
  });
4567
- code = code.replace(/^\s*export\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4869
+ code = code.replace(/\bexport\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4568
4870
  hasEsmExport = true;
4569
4871
  defaultExportName = name;
4570
4872
  return `${kw} ${name}`;
4571
4873
  });
4572
- code = code.replace(/^\s*export\s+default\s+/gm, () => {
4874
+ code = code.replace(/\bexport\s+default\s+/gm, () => {
4573
4875
  hasEsmExport = true;
4574
4876
  return 'exports.default = ';
4575
4877
  });
4576
- code = code.replace(/^\s*export\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4878
+ code = code.replace(/\bexport\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4577
4879
  hasEsmExport = true;
4578
4880
  exportedNames.push(name);
4579
4881
  return `${kw} ${name}`;
4580
4882
  });
4581
- code = code.replace(/^\s*export\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4883
+ code = code.replace(/\bexport\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4582
4884
  hasEsmExport = true;
4583
4885
  exportedNames.push(name);
4584
4886
  return `${kw} ${name}`;
4585
4887
  });
4586
- code = code.replace(/^\s*export\s+\{([^}]+)\}\s+from\s+([^\n;]+);?/gm, (_, list, mod) => {
4888
+ code = code.replace(/\bexport\s+\{([^}]+)\}\s+from\s+([^\n;]+);?/gm, (_, list, mod) => {
4587
4889
  hasEsmExport = true;
4588
4890
  const mTrim = mod.trim();
4589
4891
  return list.split(',').map((item) => {
@@ -4595,7 +4897,7 @@ function __initVirtualRuntime(rootScope) {
4595
4897
  return `exports.${exported} = require(${mTrim}).${local};`;
4596
4898
  }).join(' ');
4597
4899
  });
4598
- code = code.replace(/^\s*export\s+\{([^}]+)\}\s*;?/gm, (_, list) => {
4900
+ code = code.replace(/\bexport\s+\{([^}]+)\}\s*;?/gm, (_, list) => {
4599
4901
  hasEsmExport = true;
4600
4902
  return list.split(',').map((item) => {
4601
4903
  const trimmed = item.trim();
@@ -7220,6 +7522,14 @@ function __initVirtualRuntime(rootScope) {
7220
7522
  };
7221
7523
  }
7222
7524
 
7525
+ // Transpile a source file so it can run natively in a browser as an ES module:
7526
+ // JSX is compiled to the classic runtime (auto-importing React when needed) and
7527
+ // TypeScript annotations are stripped, but `import`/`export` are preserved so an
7528
+ // import map can resolve bare specifiers to CDN ESM builds.
7529
+ function transpileForBrowser(source, filename = 'module.js') {
7530
+ return transpileTS(source, filename, { keepEsm: true });
7531
+ }
7532
+
7223
7533
  return {
7224
7534
  VirtualBuffer,
7225
7535
  VirtualCrypto,
@@ -7239,6 +7549,7 @@ function __initVirtualRuntime(rootScope) {
7239
7549
  createVirtualHttp,
7240
7550
  createVirtualNet,
7241
7551
  transpileTS,
7552
+ transpileForBrowser,
7242
7553
  preloadNpmPackages,
7243
7554
  createVirtualPortTable,
7244
7555
  executeInVirtualRuntime