@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/dist/code-lab.js CHANGED
@@ -3975,14 +3975,316 @@ function __initVirtualRuntime(rootScope) {
3975
3975
  };
3976
3976
  }
3977
3977
 
3978
+ // =========================================================================
3979
+ // 7b. JSX / TSX SUPPORT
3980
+ // -------------------------------------------------------------------------
3981
+ // Rewrites JSX syntax into classic `createElement(...)` calls. This runs
3982
+ // BEFORE the string-masking pass so that JSX text (which routinely contains
3983
+ // quotes/apostrophes, e.g. <p>Don't</p>) is captured verbatim, while genuine
3984
+ // JS strings, comments and template literals are skipped untouched.
3985
+ // =========================================================================
3986
+ function detectJsxSyntax(source, filename) {
3987
+ if (/\.(jsx|tsx)$/i.test(filename || '')) return true;
3988
+ if (!source || source.indexOf('<') === -1) return false;
3989
+ if (/@jsx\b/.test(source)) return true;
3990
+ if (source.indexOf('<>') !== -1) return true;
3991
+ if (/<\/[A-Za-z]/.test(source)) return true;
3992
+ return false;
3993
+ }
3994
+
3995
+ function readJsxPragma(source) {
3996
+ let pragma = 'React.createElement';
3997
+ let frag = null;
3998
+ const m = /@jsx\s+([A-Za-z_$][\w$.]*)/.exec(source);
3999
+ if (m) pragma = m[1];
4000
+ const fm = /@jsxFrag\s+([A-Za-z_$][\w$.]*)/.exec(source);
4001
+ if (fm) frag = fm[1];
4002
+ if (!frag) frag = pragma === 'React.createElement' ? 'React.Fragment' : 'Fragment';
4003
+ return { pragma, frag };
4004
+ }
4005
+
4006
+ const JSX_WS_RE = /\s/;
4007
+ const JSX_NAME_START_RE = /[A-Za-z_$]/;
4008
+ const JSX_NAME_CHAR_RE = /[A-Za-z0-9_$:.\-]/;
4009
+
4010
+ function jsxThrow(message) {
4011
+ const err = new Error(message);
4012
+ err.jsxParse = true;
4013
+ throw err;
4014
+ }
4015
+
4016
+ // Returns the exclusive end index if a JS string / template / comment starts
4017
+ // at `i`, otherwise -1. Regexes are deliberately ignored.
4018
+ function jsxSkipJsLiteral(source, i) {
4019
+ const ch = source[i];
4020
+ const next = source[i + 1];
4021
+ const len = source.length;
4022
+ if (ch === '/' && next === '/') {
4023
+ const e = source.indexOf('\n', i);
4024
+ return e === -1 ? len : e;
4025
+ }
4026
+ if (ch === '/' && next === '*') {
4027
+ const e = source.indexOf('*/', i + 2);
4028
+ return e === -1 ? len : e + 2;
4029
+ }
4030
+ if (ch === '"' || ch === "'") {
4031
+ let j = i + 1;
4032
+ while (j < len) {
4033
+ const c = source[j];
4034
+ if (c === '\\') { j += 2; continue; }
4035
+ if (c === ch) { j++; break; }
4036
+ if (c === '\n') break;
4037
+ j++;
4038
+ }
4039
+ return j;
4040
+ }
4041
+ if (ch === '`') {
4042
+ let j = i + 1;
4043
+ let depth = 0;
4044
+ while (j < len) {
4045
+ const c = source[j];
4046
+ if (c === '\\') { j += 2; continue; }
4047
+ if (c === '$' && source[j + 1] === '{') { depth++; j += 2; continue; }
4048
+ if (c === '}' && depth > 0) { depth--; j++; continue; }
4049
+ if (c === '`' && depth === 0) { j++; break; }
4050
+ j++;
4051
+ }
4052
+ return j;
4053
+ }
4054
+ return -1;
4055
+ }
4056
+
4057
+ function jsxReadName(source, i) {
4058
+ if (!JSX_NAME_START_RE.test(source[i] || '')) jsxThrow('jsx: expected a tag name');
4059
+ let j = i;
4060
+ while (j < source.length && JSX_NAME_CHAR_RE.test(source[j])) j++;
4061
+ return { name: source.slice(i, j), next: j };
4062
+ }
4063
+
4064
+ function jsxSkipWs(source, i) {
4065
+ while (i < source.length && JSX_WS_RE.test(source[i])) i++;
4066
+ return i;
4067
+ }
4068
+
4069
+ function normalizeJsxText(raw) {
4070
+ if (!raw) return '';
4071
+ let t = raw.replace(/\r/g, '');
4072
+ if (t.indexOf('\n') !== -1) {
4073
+ t = t.split('\n').map((s) => s.replace(/[ \t]+/g, ' ').trim()).filter(Boolean).join(' ');
4074
+ } else if (!/\S/.test(t)) {
4075
+ return '';
4076
+ } else {
4077
+ t = t.replace(/[ \t]+/g, ' ');
4078
+ }
4079
+ return t ? JSON.stringify(t) : '';
4080
+ }
4081
+
4082
+ // Reads a balanced `{ ... }` expression container, skipping nested JSX and
4083
+ // JS literals. Returns the raw inner source (later re-transformed) plus the
4084
+ // index just past the closing brace.
4085
+ function jsxReadBraced(source, i, opts) {
4086
+ let depth = 0;
4087
+ let j = i;
4088
+ while (j < source.length) {
4089
+ const lit = jsxSkipJsLiteral(source, j);
4090
+ if (lit !== -1) { j = lit; continue; }
4091
+ const c = source[j];
4092
+ if (c === '{') { depth++; j++; continue; }
4093
+ if (c === '}') {
4094
+ depth--;
4095
+ j++;
4096
+ if (depth === 0) return { inner: source.slice(i + 1, j - 1), next: j };
4097
+ continue;
4098
+ }
4099
+ if (c === '<' && (JSX_NAME_START_RE.test(source[j + 1] || '') || source[j + 1] === '>')) {
4100
+ try {
4101
+ const el = jsxParseElement(source, j, opts);
4102
+ j = el.next;
4103
+ continue;
4104
+ } catch (e) {
4105
+ if (!e || !e.jsxParse) throw e;
4106
+ }
4107
+ }
4108
+ j++;
4109
+ }
4110
+ jsxThrow('jsx: unterminated expression container');
4111
+ }
4112
+
4113
+ function jsxParseElement(source, i, opts) {
4114
+ const o = opts || readJsxPragma(source);
4115
+ let j = i + 1;
4116
+ let isFragment = false;
4117
+ let typeExpr;
4118
+ if (source[j] === '>') {
4119
+ isFragment = true;
4120
+ typeExpr = o.frag;
4121
+ j++;
4122
+ } else {
4123
+ const nm = jsxReadName(source, j);
4124
+ j = nm.next;
4125
+ const raw = nm.name;
4126
+ const isReference = raw.indexOf('.') !== -1 || raw.indexOf(':') !== -1 || /^[A-Z_$]/.test(raw);
4127
+ if (isReference) {
4128
+ typeExpr = raw.replace(/:/g, '.');
4129
+ } else {
4130
+ typeExpr = JSON.stringify(raw);
4131
+ }
4132
+ }
4133
+
4134
+ const props = [];
4135
+ let selfClosing = false;
4136
+ if (!isFragment) {
4137
+ for (;;) {
4138
+ j = jsxSkipWs(source, j);
4139
+ if (j >= source.length) jsxThrow('jsx: unexpected end of input inside a tag');
4140
+ const c = source[j];
4141
+ if (c === '/') {
4142
+ if (source[j + 1] !== '>') jsxThrow('jsx: malformed self-closing tag');
4143
+ j += 2;
4144
+ selfClosing = true;
4145
+ break;
4146
+ }
4147
+ if (c === '>') { j++; break; }
4148
+ if (c === '{') {
4149
+ const br = jsxReadBraced(source, j, o);
4150
+ const inner = br.inner.trim();
4151
+ if (inner.slice(0, 3) !== '...') jsxThrow('jsx: only a spread {...} may appear where an attribute is expected');
4152
+ props.push({ spread: jsxTransform(inner.slice(3), o) });
4153
+ j = br.next;
4154
+ continue;
4155
+ }
4156
+ if (!JSX_NAME_START_RE.test(c)) jsxThrow('jsx: malformed attribute');
4157
+ const am = jsxReadName(source, j);
4158
+ const attrName = am.name;
4159
+ j = jsxSkipWs(source, am.next);
4160
+ let valueExpr = 'true';
4161
+ if (source[j] === '=') {
4162
+ j = jsxSkipWs(source, j + 1);
4163
+ const vc = source[j];
4164
+ if (vc === '"' || vc === "'") {
4165
+ let k = j + 1;
4166
+ while (k < source.length && source[k] !== vc) {
4167
+ if (source[k] === '\\') k++;
4168
+ k++;
4169
+ }
4170
+ if (k >= source.length) jsxThrow('jsx: unterminated attribute string');
4171
+ valueExpr = JSON.stringify(source.slice(j + 1, k));
4172
+ j = k + 1;
4173
+ } else if (vc === '{') {
4174
+ const br = jsxReadBraced(source, j, o);
4175
+ valueExpr = jsxTransform(br.inner, o) || 'undefined';
4176
+ j = br.next;
4177
+ } else if (vc === '<') {
4178
+ const el = jsxParseElement(source, j, o);
4179
+ valueExpr = el.code;
4180
+ j = el.next;
4181
+ } else {
4182
+ jsxThrow('jsx: unsupported attribute value');
4183
+ }
4184
+ }
4185
+ const propKey = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(attrName) ? attrName : JSON.stringify(attrName);
4186
+ props.push({ key: propKey, value: valueExpr });
4187
+ }
4188
+ }
4189
+
4190
+ const children = [];
4191
+ if (!selfClosing) {
4192
+ for (;;) {
4193
+ if (j >= source.length) jsxThrow('jsx: missing closing tag');
4194
+ const c = source[j];
4195
+ if (c === '<' && source[j + 1] === '/') {
4196
+ j = jsxSkipWs(source, j + 2);
4197
+ if (source[j] === '>') { j++; break; }
4198
+ const cm = jsxReadName(source, j);
4199
+ j = jsxSkipWs(source, cm.next);
4200
+ if (source[j] !== '>') jsxThrow('jsx: malformed closing tag');
4201
+ j++;
4202
+ break;
4203
+ }
4204
+ if (c === '<') {
4205
+ const el = jsxParseElement(source, j, o);
4206
+ children.push(el.code);
4207
+ j = el.next;
4208
+ continue;
4209
+ }
4210
+ if (c === '{') {
4211
+ const br = jsxReadBraced(source, j, o);
4212
+ const inner = jsxTransform(br.inner, o);
4213
+ if (inner && inner.trim()) children.push(inner);
4214
+ j = br.next;
4215
+ continue;
4216
+ }
4217
+ let k = j;
4218
+ while (k < source.length && source[k] !== '<' && source[k] !== '{') k++;
4219
+ const text = normalizeJsxText(source.slice(j, k));
4220
+ if (text) children.push(text);
4221
+ j = k;
4222
+ }
4223
+ }
4224
+
4225
+ let propsCode = 'null';
4226
+ if (props.length) {
4227
+ const parts = props.map((p) => (p.spread !== undefined ? '...(' + p.spread + ')' : p.key + ': ' + p.value));
4228
+ propsCode = '{ ' + parts.join(', ') + ' }';
4229
+ }
4230
+
4231
+ const args = [typeExpr, propsCode].concat(children);
4232
+ return { code: o.pragma + '(' + args.join(', ') + ')', next: j };
4233
+ }
4234
+
4235
+ function jsxTransform(source, opts) {
4236
+ const o = opts || readJsxPragma(source);
4237
+ let i = 0;
4238
+ let out = '';
4239
+ while (i < source.length) {
4240
+ const lit = jsxSkipJsLiteral(source, i);
4241
+ if (lit !== -1) { out += source.slice(i, lit); i = lit; continue; }
4242
+ const ch = source[i];
4243
+ if (ch === '<' && (JSX_NAME_START_RE.test(source[i + 1] || '') || source[i + 1] === '>')) {
4244
+ try {
4245
+ const el = jsxParseElement(source, i, o);
4246
+ out += el.code;
4247
+ i = el.next;
4248
+ continue;
4249
+ } catch (e) {
4250
+ if (!e || !e.jsxParse) throw e;
4251
+ }
4252
+ }
4253
+ out += ch;
4254
+ i++;
4255
+ }
4256
+ return out;
4257
+ }
4258
+
3978
4259
  // =========================================================================
3979
4260
  // 8. FAST TYPESCRIPT & ESM-TO-CJS TRANSPILER
3980
4261
  // =========================================================================
3981
- function transpileTS(source, filename = 'module.ts') {
4262
+ function transpileTS(source, filename = 'module.ts', opts = {}) {
4263
+ // `keepEsm` leaves `import`/`export` statements intact so the output can run
4264
+ // natively in a browser as an ES module (used by the built-in preview server).
4265
+ const keepEsm = Boolean(opts && opts.keepEsm);
3982
4266
  const isTS = /\.(ts|tsx|mts|cts)$/i.test(filename)
3983
- || /\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);
3984
- const hasESM = /^\s*(import|export)\s+/m.test(source);
3985
- if (!isTS && !hasESM) return source;
4267
+ || /^[ \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);
4268
+ const hasESM = /^\s*(?:import|export)\b/m.test(source)
4269
+ || /\bexport\s*\{/.test(source)
4270
+ || /\bimport\s*\{/.test(source)
4271
+ || /\bexport\s+default\b/.test(source);
4272
+ const hasJsx = detectJsxSyntax(source, filename);
4273
+ if (!isTS && !hasESM && !hasJsx) return source;
4274
+
4275
+ // JSX/TSX must be rewritten before masking so JSX text is kept verbatim.
4276
+ if (hasJsx) {
4277
+ const { pragma, frag } = readJsxPragma(source);
4278
+ const needsReact = pragma === 'React.createElement' && !/\bReact\b/.test(source);
4279
+ const transformed = jsxTransform(source, { pragma, frag });
4280
+ if (transformed !== source) {
4281
+ source = transformed;
4282
+ // The classic runtime needs a React binding available to the JSX output.
4283
+ if (needsReact) {
4284
+ source = (keepEsm ? 'import React from "react";\n' : 'const React = require("react");\n') + source;
4285
+ }
4286
+ }
4287
+ }
3986
4288
 
3987
4289
  // Step 1: Mask strings, template literals, regex literals, and comments so transforms never corrupt literals
3988
4290
  const placeholders = [];
@@ -4545,10 +4847,10 @@ function __initVirtualRuntime(rootScope) {
4545
4847
  } while (code !== prevCode);
4546
4848
  }
4547
4849
 
4548
- if (hasESM || isTS) {
4850
+ if ((hasESM || isTS) && !keepEsm) {
4549
4851
  // Convert ES module imports (including multi-line `{ ... }`)
4550
- 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);');
4551
- 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) => {
4852
+ code = code.replace(/\bimport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, 'const $1 = require($2);');
4853
+ code = code.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, defId, specifiers, mod) => {
4552
4854
  const cleaned = specifiers
4553
4855
  .split(',')
4554
4856
  .map((s) => s.trim())
@@ -4559,7 +4861,7 @@ function __initVirtualRuntime(rootScope) {
4559
4861
  return `const ${defId} = (function(m){ return m && m.__esModule ? m.default : m; })(require(${mTrim}));` +
4560
4862
  (cleaned ? ` const { ${cleaned} } = require(${mTrim});` : '');
4561
4863
  });
4562
- code = code.replace(/^\s*import\s+\{([\s\S]*?)\}\s+from\s+([^\n;]+);?/gm, (_, specifiers, mod) => {
4864
+ code = code.replace(/\bimport\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, specifiers, mod) => {
4563
4865
  const cleaned = specifiers
4564
4866
  .split(',')
4565
4867
  .map((s) => s.trim())
@@ -4568,42 +4870,42 @@ function __initVirtualRuntime(rootScope) {
4568
4870
  .join(', ');
4569
4871
  return cleaned ? `const { ${cleaned} } = require(${mod.trim()});` : '';
4570
4872
  });
4571
- 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));');
4572
- code = code.replace(/^\s*import\s+(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
4873
+ 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));');
4874
+ code = code.replace(/\bimport\s+(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
4573
4875
 
4574
4876
  // Convert ES module exports
4575
4877
  const exportedNames = [];
4576
4878
  let defaultExportName = null;
4577
4879
  let hasEsmExport = false;
4578
4880
 
4579
- code = code.replace(/^\s*export\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, (_, ns, mod) => {
4881
+ code = code.replace(/\bexport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, (_, ns, mod) => {
4580
4882
  hasEsmExport = true;
4581
4883
  return `exports.${ns} = require(${mod.trim()});`;
4582
4884
  });
4583
- code = code.replace(/^\s*export\s+\*\s+from\s+([^\n;]+);?/gm, (_, mod) => {
4885
+ code = code.replace(/\bexport\s*\*\s*from\s*([^\n;]+);?/gm, (_, mod) => {
4584
4886
  hasEsmExport = true;
4585
4887
  return `Object.assign(exports, require(${mod.trim()}));`;
4586
4888
  });
4587
- code = code.replace(/^\s*export\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4889
+ code = code.replace(/\bexport\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4588
4890
  hasEsmExport = true;
4589
4891
  defaultExportName = name;
4590
4892
  return `${kw} ${name}`;
4591
4893
  });
4592
- code = code.replace(/^\s*export\s+default\s+/gm, () => {
4894
+ code = code.replace(/\bexport\s+default\s+/gm, () => {
4593
4895
  hasEsmExport = true;
4594
4896
  return 'exports.default = ';
4595
4897
  });
4596
- code = code.replace(/^\s*export\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4898
+ code = code.replace(/\bexport\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4597
4899
  hasEsmExport = true;
4598
4900
  exportedNames.push(name);
4599
4901
  return `${kw} ${name}`;
4600
4902
  });
4601
- code = code.replace(/^\s*export\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4903
+ code = code.replace(/\bexport\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4602
4904
  hasEsmExport = true;
4603
4905
  exportedNames.push(name);
4604
4906
  return `${kw} ${name}`;
4605
4907
  });
4606
- code = code.replace(/^\s*export\s+\{([^}]+)\}\s+from\s+([^\n;]+);?/gm, (_, list, mod) => {
4908
+ code = code.replace(/\bexport\s*\{([^}]+)\}\s*from\s*([^\n;]+);?/gm, (_, list, mod) => {
4607
4909
  hasEsmExport = true;
4608
4910
  const mTrim = mod.trim();
4609
4911
  return list.split(',').map((item) => {
@@ -4615,7 +4917,7 @@ function __initVirtualRuntime(rootScope) {
4615
4917
  return `exports.${exported} = require(${mTrim}).${local};`;
4616
4918
  }).join(' ');
4617
4919
  });
4618
- code = code.replace(/^\s*export\s+\{([^}]+)\}\s*;?/gm, (_, list) => {
4920
+ code = code.replace(/\bexport\s*\{([^}]+)\}\s*;?/gm, (_, list) => {
4619
4921
  hasEsmExport = true;
4620
4922
  return list.split(',').map((item) => {
4621
4923
  const trimmed = item.trim();
@@ -7240,6 +7542,14 @@ function __initVirtualRuntime(rootScope) {
7240
7542
  };
7241
7543
  }
7242
7544
 
7545
+ // Transpile a source file so it can run natively in a browser as an ES module:
7546
+ // JSX is compiled to the classic runtime (auto-importing React when needed) and
7547
+ // TypeScript annotations are stripped, but `import`/`export` are preserved so an
7548
+ // import map can resolve bare specifiers to CDN ESM builds.
7549
+ function transpileForBrowser(source, filename = 'module.js') {
7550
+ return transpileTS(source, filename, { keepEsm: true });
7551
+ }
7552
+
7243
7553
  return {
7244
7554
  VirtualBuffer,
7245
7555
  VirtualCrypto,
@@ -7259,6 +7569,7 @@ function __initVirtualRuntime(rootScope) {
7259
7569
  createVirtualHttp,
7260
7570
  createVirtualNet,
7261
7571
  transpileTS,
7572
+ transpileForBrowser,
7262
7573
  preloadNpmPackages,
7263
7574
  createVirtualPortTable,
7264
7575
  executeInVirtualRuntime
@@ -9909,9 +10220,31 @@ if (typeof module !== 'undefined' && module.exports) {
9909
10220
  return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
9910
10221
  }
9911
10222
 
10223
+ function pickConditionalEntry(value) {
10224
+ if (typeof value === 'string') return value;
10225
+ if (!value || typeof value !== 'object') return null;
10226
+ // This runtime executes CommonJS, so it prefers CJS-friendly conditions.
10227
+ for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
10228
+ if (value[key] !== undefined) {
10229
+ const picked = pickConditionalEntry(value[key]);
10230
+ if (picked) return picked;
10231
+ }
10232
+ }
10233
+ return null;
10234
+ }
10235
+
9912
10236
  function resolveEntryRelPath(pkgJson) {
9913
- let entry = pkgJson.main || pkgJson.module ||
9914
- (typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
10237
+ let entry = null;
10238
+ const exp = pkgJson && pkgJson.exports;
10239
+ if (typeof exp === 'string') {
10240
+ entry = exp;
10241
+ } else if (exp && typeof exp === 'object' && exp['.'] !== undefined) {
10242
+ entry = pickConditionalEntry(exp['.']);
10243
+ }
10244
+ if (!entry) {
10245
+ entry = pkgJson.main || pkgJson.module ||
10246
+ (typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
10247
+ }
9915
10248
  entry = String(entry).replace(/^[./]+/, '');
9916
10249
  return entry || 'index.js';
9917
10250
  }
@@ -9922,9 +10255,16 @@ if (typeof module !== 'undefined' && module.exports) {
9922
10255
 
9923
10256
  function extractRelativeSpecifiers(code) {
9924
10257
  const out = new Set();
9925
- const re = /(?:\brequire\s*\(\s*|\bimport\s+[\s\S]{0,120}?\bfrom\s*|\bimport\s*\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g;
9926
- let m;
9927
- while ((m = re.exec(code)) !== null) out.add(m[1]);
10258
+ const patterns = [
10259
+ /\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,
10260
+ /\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
10261
+ /\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
10262
+ /\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g
10263
+ ];
10264
+ for (const re of patterns) {
10265
+ let m;
10266
+ while ((m = re.exec(code)) !== null) out.add(m[1]);
10267
+ }
9928
10268
  return Array.from(out);
9929
10269
  }
9930
10270
 
@@ -9989,20 +10329,49 @@ if (typeof module !== 'undefined' && module.exports) {
9989
10329
  const entry = resolveEntryRelPath(meta);
9990
10330
  const files = [];
9991
10331
  const visited = new Set();
9992
- const queue = [entry];
9993
- while (queue.length > 0) {
9994
- const rel = stripRelPath(queue.shift());
9995
- if (!rel || visited.has(rel)) continue;
9996
- visited.add(rel);
9997
- const text = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`);
9998
- if (text === null) continue;
9999
- files.push({ rel, content: text });
10000
- const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
10001
- for (const spec of extractRelativeSpecifiers(text)) {
10002
- const target = normalizeRelPath(baseDir, spec);
10003
- for (const cand of [target, `${target}.js`, `${target}.json`, `${target}/index.js`]) {
10004
- const c = stripRelPath(cand);
10005
- if (c && !visited.has(c)) { queue.push(cand); break; }
10332
+ // Seed with the package entry plus any declared `exports` subpaths, so a
10333
+ // later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
10334
+ const seed = [entry, `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`];
10335
+ const expMap = meta.exports;
10336
+ if (expMap && typeof expMap === 'object') {
10337
+ let subCount = 0;
10338
+ for (const key of Object.keys(expMap)) {
10339
+ if (key === '.' || key.slice(0, 2) !== './' || subCount >= 25) continue;
10340
+ const target = pickConditionalEntry(expMap[key]);
10341
+ if (target) { seed.push(target); subCount++; }
10342
+ }
10343
+ }
10344
+ let frontier = seed;
10345
+ while (frontier.length > 0) {
10346
+ const batch = [];
10347
+ for (const raw of frontier) {
10348
+ const rel = stripRelPath(raw);
10349
+ if (!rel || visited.has(rel)) continue;
10350
+ visited.add(rel);
10351
+ batch.push(rel);
10352
+ }
10353
+ frontier = [];
10354
+ if (batch.length === 0) break;
10355
+ const texts = await Promise.all(
10356
+ batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
10357
+ );
10358
+ for (let idx = 0; idx < batch.length; idx++) {
10359
+ const rel = batch[idx];
10360
+ const text = texts[idx];
10361
+ if (text === null) continue;
10362
+ files.push({ rel, content: text });
10363
+ const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
10364
+ for (const spec of extractRelativeSpecifiers(text)) {
10365
+ const target = normalizeRelPath(baseDir, spec);
10366
+ // Only guess extensions when the specifier omits one; non-existent
10367
+ // candidates 404 harmlessly.
10368
+ const cands = /\.[a-z0-9]+$/i.test(target)
10369
+ ? [target]
10370
+ : [target, `${target}.js`, `${target}.json`, `${target}.mjs`, `${target}.cjs`, `${target}/index.js`];
10371
+ for (const cand of cands) {
10372
+ const c = stripRelPath(cand);
10373
+ if (c && !visited.has(c)) frontier.push(cand);
10374
+ }
10006
10375
  }
10007
10376
  }
10008
10377
  }
@@ -10012,7 +10381,16 @@ if (typeof module !== 'undefined' && module.exports) {
10012
10381
  if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
10013
10382
  }
10014
10383
 
10015
- return { ok: true, version, entry, files, deps: Object.keys(meta.dependencies || {}) };
10384
+ // Declared dependencies plus non-optional peer dependencies (npm v7+ style),
10385
+ // so e.g. `npm install react-dom` also pulls in `react`.
10386
+ const depNames = Object.keys(meta.dependencies || {});
10387
+ const peerMeta = meta.peerDependenciesMeta || {};
10388
+ for (const peer of Object.keys(meta.peerDependencies || {})) {
10389
+ if (peerMeta[peer] && peerMeta[peer].optional) continue;
10390
+ if (depNames.indexOf(peer) === -1) depNames.push(peer);
10391
+ }
10392
+
10393
+ return { ok: true, version, entry, files, deps: depNames, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
10016
10394
  }
10017
10395
 
10018
10396
  function installTargetDirs(ctx, name) {
@@ -10033,17 +10411,30 @@ if (typeof module !== 'undefined' && module.exports) {
10033
10411
  }
10034
10412
  const modPkgPath = PosixPath.join(dir, 'package.json');
10035
10413
  const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
10414
+ if (info.pkgExports && typeof info.pkgExports === 'object') {
10415
+ const normalized = { '.': './' + (info.entry || 'index.js') };
10416
+ for (const key of Object.keys(info.pkgExports)) {
10417
+ if (key === '.' || key.indexOf('*') !== -1) continue;
10418
+ const target = pickConditionalEntry(info.pkgExports[key]);
10419
+ if (target) normalized[key] = target.charAt(0) === '.' ? target : './' + target;
10420
+ }
10421
+ modPkg.exports = normalized;
10422
+ }
10036
10423
  ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
10037
10424
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
10038
10425
  }
10039
10426
  }
10040
10427
 
10041
- async function installPackage(pkgSpec, ctx) {
10428
+ async function installPackage(pkgSpec, ctx, onLine, opts) {
10429
+ const options = (onLine && typeof onLine === 'object') ? onLine : (opts || {});
10430
+ const lineCb = (typeof onLine === 'function') ? onLine : (typeof options.onLine === 'function' ? options.onLine : null);
10431
+ const isDev = Boolean(options.dev);
10042
10432
  const { name: pkgName, range } = parsePackageSpec(pkgSpec);
10043
10433
  if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
10044
10434
 
10045
10435
  const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
10046
- if (!pkgData.dependencies) pkgData.dependencies = {};
10436
+ const depField = isDev ? 'devDependencies' : 'dependencies';
10437
+ if (!pkgData[depField]) pkgData[depField] = {};
10047
10438
 
10048
10439
  const fetchImpl = packageCtxFetch(ctx);
10049
10440
  const seen = (ctx.shell && ctx.shell._cdnSeen)
@@ -10069,11 +10460,13 @@ if (typeof module !== 'undefined' && module.exports) {
10069
10460
  });
10070
10461
  if (!warning) warning = info.reason;
10071
10462
  installed.push({ name: item.name, version: '0.0.0' });
10463
+ if (typeof lineCb === 'function') lineCb({ name: item.name, version: '0.0.0', offline: true });
10072
10464
  continue;
10073
10465
  }
10074
10466
 
10075
10467
  writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
10076
10468
  installed.push({ name: item.name, version: info.version || '1.0.0' });
10469
+ if (typeof lineCb === 'function') lineCb({ name: item.name, version: info.version || '1.0.0', deduped: Boolean(info.deduped) });
10077
10470
  if (item.direct) directVersion = info.version || null;
10078
10471
 
10079
10472
  for (const dep of (info.deps || [])) {
@@ -10085,12 +10478,71 @@ if (typeof module !== 'undefined' && module.exports) {
10085
10478
  }
10086
10479
  }
10087
10480
 
10088
- pkgData.dependencies[pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData.dependencies[pkgName] || 'latest'));
10481
+ pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
10089
10482
  writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
10090
10483
 
10091
10484
  return { name: pkgName, ok: true, version: directVersion, installed, warning };
10092
10485
  }
10093
10486
 
10487
+ // Build a live install log: each line is streamed to the terminal as it
10488
+ // happens (when possible) and accumulated so the command can also return it.
10489
+ function createInstallEmitter(ctx, sink) {
10490
+ const stream = (ctx && typeof ctx.onStdout === 'function') ? ctx.onStdout : null;
10491
+ return function emit(text) {
10492
+ if (!text) return;
10493
+ sink.push(text);
10494
+ if (stream) stream(text);
10495
+ };
10496
+ }
10497
+
10498
+ function formatInstallLine(info) {
10499
+ if (!info || !info.name) return '';
10500
+ const suffix = info.offline ? ' (offline fallback)' : (info.deduped ? ' (deduped)' : '');
10501
+ return ` + ${info.name}@${info.version || '1.0.0'}${suffix}\n`;
10502
+ }
10503
+
10504
+ function countInstalledPackages(results) {
10505
+ const seen = new Set();
10506
+ for (const r of results) {
10507
+ if (!r) continue;
10508
+ if (r.name) seen.add(r.name);
10509
+ for (const p of (r.installed || [])) { if (p && p.name) seen.add(p.name); }
10510
+ }
10511
+ return seen.size;
10512
+ }
10513
+
10514
+ // Resolve + install a list of specs while printing a realistic transcript,
10515
+ // so `npm install` / `bun add` look like the real tools instead of a terse
10516
+ // "saved N package(s)".
10517
+ async function runInstallTranscript(pkgs, ctx, opts) {
10518
+ const options = opts || {};
10519
+ const manager = options.manager || 'bun';
10520
+ const header = options.header || (manager === 'npm' ? 'npm install v10.2.0' : 'bun add v1.1.20 (1.1.20)');
10521
+ const out = [];
10522
+ const emit = createInstallEmitter(ctx, out);
10523
+ const started = Date.now();
10524
+ emit(`${header}\n\nResolving dependencies...\n`);
10525
+ const results = [];
10526
+ for (const p of pkgs) {
10527
+ results.push(await installPackage(p, ctx, { onLine: (info) => emit(formatInstallLine(info)), dev: Boolean(options.dev) }));
10528
+ }
10529
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
10530
+ const count = countInstalledPackages(results);
10531
+ const ms = Date.now() - started;
10532
+ if (manager === 'npm') {
10533
+ emit(`\nadded ${count} package(s) in ${ms}ms\n`);
10534
+ } else if (manager === 'pnpm') {
10535
+ emit(`\nPackages: +${count}\n${'+'.repeat(Math.min(count, 40))}\nDone in ${ms}ms using pnpm v9.0.0\n`);
10536
+ } else {
10537
+ emit(`Saved lockfile\n\n${count} package(s) installed [${ms}ms]\n`);
10538
+ }
10539
+ return {
10540
+ code: 0,
10541
+ stdout: out.join(''),
10542
+ stderr: warning ? `${manager === 'npm' ? 'npm warn' : manager === 'pnpm' ? 'pnpm warn' : 'bun warn'} ${warning}\n` : ''
10543
+ };
10544
+ }
10545
+
10094
10546
  function uninstallPackage(pkgName, ctx) {
10095
10547
  const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
10096
10548
  let changed = false;
@@ -10142,9 +10594,261 @@ if (typeof module !== 'undefined' && module.exports) {
10142
10594
  if (scriptArgs && scriptArgs.length > 0) {
10143
10595
  cmd += ' ' + scriptArgs.join(' ');
10144
10596
  }
10597
+ const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
10598
+ if (fallback) return fallback;
10145
10599
  return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
10146
10600
  }
10147
10601
 
10602
+ // ---------------------------------------------------------------------------
10603
+ // Built-in static preview server (`serve` / `npm run dev` fallback).
10604
+ //
10605
+ // Serves the virtual filesystem over a virtual port so the in-browser Web
10606
+ // Preview can render a project. `.ts/.tsx/.jsx` sources are transpiled to
10607
+ // browser-native ESM on the fly, and bare specifiers are resolved to jsDelivr
10608
+ // `+esm` builds through an injected import map — no bundler required.
10609
+ // ---------------------------------------------------------------------------
10610
+
10611
+ const CDN_ESM_BASE = 'https://cdn.jsdelivr.net/npm';
10612
+
10613
+ const PREVIEW_MIME = {
10614
+ '.html': 'text/html; charset=utf-8',
10615
+ '.htm': 'text/html; charset=utf-8',
10616
+ '.js': 'text/javascript; charset=utf-8',
10617
+ '.mjs': 'text/javascript; charset=utf-8',
10618
+ '.cjs': 'text/javascript; charset=utf-8',
10619
+ '.jsx': 'text/javascript; charset=utf-8',
10620
+ '.ts': 'text/javascript; charset=utf-8',
10621
+ '.tsx': 'text/javascript; charset=utf-8',
10622
+ '.css': 'text/css; charset=utf-8',
10623
+ '.json': 'application/json; charset=utf-8',
10624
+ '.map': 'application/json; charset=utf-8',
10625
+ '.svg': 'image/svg+xml',
10626
+ '.png': 'image/png',
10627
+ '.jpg': 'image/jpeg',
10628
+ '.jpeg': 'image/jpeg',
10629
+ '.gif': 'image/gif',
10630
+ '.webp': 'image/webp',
10631
+ '.ico': 'image/x-icon',
10632
+ '.txt': 'text/plain; charset=utf-8'
10633
+ };
10634
+
10635
+ function previewMimeFor(p) {
10636
+ const lower = String(p).toLowerCase();
10637
+ const dot = lower.lastIndexOf('.');
10638
+ if (dot === -1) return 'application/octet-stream';
10639
+ return PREVIEW_MIME[lower.slice(dot)] || 'application/octet-stream';
10640
+ }
10641
+
10642
+ function isPreviewScriptPath(p) {
10643
+ return /\.(?:[cm]?jsx?|tsx?)$/i.test(p) && !/\.d\.ts$/i.test(p);
10644
+ }
10645
+
10646
+ // Collect bare (non-relative) module specifiers referenced by a source file.
10647
+ function extractBareSpecifiers(code) {
10648
+ const out = new Set();
10649
+ const patterns = [
10650
+ /\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
10651
+ /\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
10652
+ /\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
10653
+ /\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g
10654
+ ];
10655
+ for (const re of patterns) {
10656
+ let m;
10657
+ while ((m = re.exec(code)) !== null) {
10658
+ const spec = m[1];
10659
+ if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.includes(':')) continue;
10660
+ out.add(spec);
10661
+ }
10662
+ }
10663
+ return Array.from(out);
10664
+ }
10665
+
10666
+ function normalizeVersionRange(range) {
10667
+ if (!range || typeof range !== 'string') return 'latest';
10668
+ const v = range.trim();
10669
+ if (!v || v === '*' || /^(?:latest|next|beta|canary)$/.test(v)) return 'latest';
10670
+ if (/^(?:file|link|workspace|portal|git|https?):/.test(v)) return 'latest';
10671
+ return v.replace(/\s+/g, '').replace(/^[v=\s]+/, '') || 'latest';
10672
+ }
10673
+
10674
+ function resolveBareVersion(vfs, rootDir, pkgName) {
10675
+ try {
10676
+ const modPkg = PosixPath.join(rootDir, 'node_modules', pkgName, 'package.json');
10677
+ if (vfs.existsSync(modPkg)) {
10678
+ const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
10679
+ if (parsed && parsed.version) return parsed.version;
10680
+ }
10681
+ } catch (_) {}
10682
+ try {
10683
+ for (const dir of [rootDir, '/workspace']) {
10684
+ const pkgPath = PosixPath.join(dir, 'package.json');
10685
+ if (!vfs.existsSync(pkgPath)) continue;
10686
+ const parsed = JSON.parse(vfs.readFileSync(pkgPath, 'utf8'));
10687
+ const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
10688
+ if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
10689
+ }
10690
+ } catch (_) {}
10691
+ return 'latest';
10692
+ }
10693
+
10694
+ function cdnEsmUrl(pkgName, version, subpath) {
10695
+ const base = `${CDN_ESM_BASE}/${pkgName}@${version}`;
10696
+ const sub = subpath ? '/' + String(subpath).replace(/^\/+|\/+$/g, '') : '';
10697
+ return `${base}${sub}/+esm`;
10698
+ }
10699
+
10700
+ function buildPreviewImportMap(vfs, rootDir, specifiers) {
10701
+ const imports = {};
10702
+ for (const spec of specifiers) {
10703
+ const parts = String(spec).split('/');
10704
+ const pkgName = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
10705
+ if (!pkgName) continue;
10706
+ const subpath = spec.slice(pkgName.length).replace(/^\/+/, '');
10707
+ const version = resolveBareVersion(vfs, rootDir, pkgName);
10708
+ imports[spec] = cdnEsmUrl(pkgName, version, subpath || undefined);
10709
+ }
10710
+ return imports;
10711
+ }
10712
+
10713
+ function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
10714
+ const scripts = [];
10715
+ const walk = (dir, depth) => {
10716
+ if (depth > 8 || scripts.length >= maxFiles) return;
10717
+ let entries = [];
10718
+ try { entries = vfs.readdirSync(dir); } catch (_) { return; }
10719
+ for (const name of entries) {
10720
+ if (name === 'node_modules' || name.startsWith('.')) continue;
10721
+ const full = PosixPath.join(dir, name);
10722
+ let st;
10723
+ try { st = vfs.statSync(full); } catch (_) { continue; }
10724
+ const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
10725
+ if (dirFlag) {
10726
+ walk(full, depth + 1);
10727
+ } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
10728
+ try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
10729
+ }
10730
+ }
10731
+ };
10732
+ walk(rootDir, 0);
10733
+ return scripts;
10734
+ }
10735
+
10736
+ function injectPreviewExtras(html, importMap) {
10737
+ let out = html;
10738
+ const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
10739
+ if (/<head[^>]*>/i.test(out)) {
10740
+ out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
10741
+ } else {
10742
+ out = importMapTag + '\n' + out;
10743
+ }
10744
+ const shim = '<script>window.__CODELAB_PREVIEW__ = true;</script>';
10745
+ if (/<\/body>/i.test(out)) out = out.replace(/<\/body>/i, `${shim}\n</body>`);
10746
+ else out = out + '\n' + shim;
10747
+ return out;
10748
+ }
10749
+
10750
+ function registerPreviewServer(ctx, rootDir, preferredPort) {
10751
+ const portTable = ctx.shell && ctx.shell.portTable;
10752
+ if (!portTable || typeof portTable.registerServer !== 'function') return null;
10753
+
10754
+ let port = Number(preferredPort) || 3000;
10755
+ const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
10756
+ while (taken.has(port)) port++;
10757
+
10758
+ const specifiers = new Set();
10759
+ for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
10760
+ for (const s of extractBareSpecifiers(content)) specifiers.add(s);
10761
+ }
10762
+ const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
10763
+
10764
+ const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
10765
+ const isDir = (p) => {
10766
+ try {
10767
+ const st = ctx.vfs.statSync(p);
10768
+ return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
10769
+ } catch (_) { return false; }
10770
+ };
10771
+ const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
10772
+
10773
+ const handler = async (request) => {
10774
+ let pathname = '/';
10775
+ try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
10776
+ const rel = pathname.replace(/^\/+/, '');
10777
+ let target = PosixPath.join(rootDir, rel);
10778
+ const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
10779
+
10780
+ if (!rel || pathname.endsWith('/') || isDir(target)) {
10781
+ target = PosixPath.join(target, 'index.html');
10782
+ }
10783
+ if (!exists(target) && !hasExt) {
10784
+ // Resolve extensionless module specifiers (e.g. `./components/Counter`)
10785
+ // the way a bundler / dev server would.
10786
+ const cands = [
10787
+ target + '.tsx', target + '.ts', target + '.jsx', target + '.js',
10788
+ target + '.mjs', target + '.cjs',
10789
+ PosixPath.join(target, 'index.tsx'), PosixPath.join(target, 'index.ts'),
10790
+ PosixPath.join(target, 'index.jsx'), PosixPath.join(target, 'index.js')
10791
+ ];
10792
+ for (const c of cands) { if (exists(c)) { target = c; break; } }
10793
+ }
10794
+ if (!exists(target) && !hasExt) {
10795
+ target = PosixPath.join(rootDir, 'index.html'); // SPA fallback
10796
+ }
10797
+ if (!exists(target)) {
10798
+ return new Response(
10799
+ `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
10800
+ { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
10801
+ );
10802
+ }
10803
+
10804
+ let body = readText(target);
10805
+ if (body === null) body = '';
10806
+ if (/\.html?$/i.test(target)) {
10807
+ body = injectPreviewExtras(body, importMap);
10808
+ } else if (isPreviewScriptPath(target)) {
10809
+ try {
10810
+ const rm = getRuntimeModule();
10811
+ if (rm && typeof rm.transpileForBrowser === 'function') {
10812
+ body = rm.transpileForBrowser(body, target);
10813
+ }
10814
+ } catch (_) {}
10815
+ }
10816
+
10817
+ return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
10818
+ };
10819
+
10820
+ const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
10821
+ return portTable.registerServer(port, {
10822
+ server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
10823
+ fetch: handler,
10824
+ name: 'code-lab-serve',
10825
+ pid,
10826
+ root: rootDir
10827
+ });
10828
+ }
10829
+
10830
+ // Common dev-server commands that cannot run inside the virtual runtime are
10831
+ // transparently redirected to the built-in preview server.
10832
+ const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
10833
+
10834
+ function tryDevScriptFallback(scriptName, cmd, ctx) {
10835
+ if (!PREVIEW_TOOL_RE.test(cmd)) return null;
10836
+ // Only fall back when the referenced tool is not actually installed.
10837
+ const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
10838
+ const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
10839
+ if (ctx.vfs.existsSync(binPath)) return null;
10840
+ const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
10841
+ const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
10842
+ const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
10843
+ const entry = registerPreviewServer(ctx, ctx.cwd, port);
10844
+ if (!entry) return null;
10845
+ return {
10846
+ code: 0,
10847
+ stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${bin} is not available in this virtual runtime — using the CodeLab preview server instead.\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
10848
+ stderr: ''
10849
+ };
10850
+ }
10851
+
10148
10852
  function evaluatePosixTest(args, ctx) {
10149
10853
  const cleanArgs = [...args];
10150
10854
  if (cleanArgs.length > 0 && cleanArgs[cleanArgs.length - 1] === ']') {
@@ -12643,7 +13347,8 @@ if (typeof module !== 'undefined' && module.exports) {
12643
13347
  stdout += ' date, sleep, clear Date, delay, terminal screen control\n';
12644
13348
  stdout += ' history, ps, jobs, kill Process and job management\n';
12645
13349
  stdout += ' git [status diff log] Built-in version control\n';
12646
- stdout += ' node, bun, npm, npx, bunx CLI runtime and package shims\n';
13350
+ stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
13351
+ stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
12647
13352
  stdout += ' ports, curl Port table inspection & HTTP requests\n';
12648
13353
  return { code: 0, stdout, stderr: '' };
12649
13354
  },
@@ -12828,26 +13533,25 @@ if (typeof module !== 'undefined' && module.exports) {
12828
13533
 
12829
13534
  if (sub === 'install' || sub === 'i' || sub === 'ci') {
12830
13535
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
13536
+ const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
12831
13537
  if (pkgs.length === 0) {
12832
13538
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
12833
- const deps = Object.keys(pkgData.dependencies || {});
12834
- const results = [];
12835
- for (const p of deps) results.push(await installPackage(p, ctx));
12836
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
12837
- return { code: 0, stdout: deps.length === 0 ? 'up to date\n' : `installed ${deps.length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
13539
+ const deps = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
13540
+ if (deps.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
13541
+ return await runInstallTranscript(deps, ctx, { manager: 'bun', header: 'bun install v1.1.20 (1.1.20)' });
12838
13542
  }
12839
- const results = [];
12840
- for (const p of pkgs) results.push(await installPackage(p, ctx));
12841
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
12842
- return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
13543
+ return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
12843
13544
  }
12844
13545
 
12845
13546
  if (sub === 'add') {
12846
- const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
12847
- const results = [];
12848
- for (const p of pkgs) results.push(await installPackage(p, ctx));
12849
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
12850
- return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
13547
+ let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
13548
+ const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
13549
+ if (pkgs.length === 0) {
13550
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
13551
+ pkgs = Object.keys(pkgData.dependencies || {});
13552
+ }
13553
+ if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
13554
+ return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
12851
13555
  }
12852
13556
 
12853
13557
  if (sub === 'remove' || sub === 'rm') {
@@ -13007,22 +13711,14 @@ if (typeof module !== 'undefined' && module.exports) {
13007
13711
  }
13008
13712
 
13009
13713
  if (sub === 'i' || sub === 'install' || sub === 'add') {
13010
- const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
13714
+ let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
13715
+ const dev = args.some(a => a === '-D' || a === '--save-dev' || a === '--dev');
13011
13716
  if (pkgs.length === 0) {
13012
13717
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
13013
- const results = [];
13014
- for (const p of Object.keys(pkgData.dependencies || {})) {
13015
- results.push(await installPackage(p, ctx));
13016
- }
13017
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
13018
- return { code: 0, stdout: 'up to date\n', stderr: warning ? `npm warn ${warning}\n` : '' };
13718
+ pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
13719
+ if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
13019
13720
  }
13020
- const results = [];
13021
- for (const p of pkgs) {
13022
- results.push(await installPackage(p, ctx));
13023
- }
13024
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
13025
- return { code: 0, stdout: `added ${results.filter(r => r && r.name).length} package(s) in 0.1s\n`, stderr: warning ? `npm warn ${warning}\n` : '' };
13721
+ return await runInstallTranscript(pkgs, ctx, { manager: 'npm', dev, header: 'npm install v10.2.0' });
13026
13722
  }
13027
13723
 
13028
13724
  if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
@@ -13074,6 +13770,123 @@ if (typeof module !== 'undefined' && module.exports) {
13074
13770
  return await this.npx(args, ctx);
13075
13771
  },
13076
13772
 
13773
+ async pnpm(args, ctx) {
13774
+ if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
13775
+ return {
13776
+ code: 0,
13777
+ stdout: 'pnpm v9.0.0\nUsage: pnpm <command>\n\nCommands:\n install, i Install all dependencies\n add <pkg> Add a dependency (-D for dev)\n remove, rm Remove a dependency\n list, ls List dependencies\n run <script> Run a package script\n exec <cmd> Run a command from node_modules/.bin\n dlx <pkg> Fetch and run a package\n --version, -v Print the version\n',
13778
+ stderr: ''
13779
+ };
13780
+ }
13781
+ const sub = args[0];
13782
+ if (sub === '--version' || sub === '-v') {
13783
+ return { code: 0, stdout: '9.0.0\n', stderr: '' };
13784
+ }
13785
+ const dev = args.some((a) => a === '-D' || a === '--save-dev' || a === '--dev' || a === '-d');
13786
+
13787
+ if (sub === 'init') {
13788
+ const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
13789
+ if (!ctx.vfs.existsSync(pkgPath)) {
13790
+ ctx.vfs.writeFileSync(pkgPath, JSON.stringify({
13791
+ name: PosixPath.basename(ctx.cwd) || 'app',
13792
+ version: '1.0.0',
13793
+ main: 'index.js',
13794
+ scripts: { test: 'echo "Error: no test specified" && exit 1' }
13795
+ }, null, 2) + '\n');
13796
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', pkgPath);
13797
+ }
13798
+ return { code: 0, stdout: 'Wrote to ' + pkgPath + '\n', stderr: '' };
13799
+ }
13800
+
13801
+ if (sub === 'install' || sub === 'i' || sub === 'add') {
13802
+ let pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
13803
+ if (pkgs.length === 0) {
13804
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
13805
+ pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
13806
+ if (pkgs.length === 0) return { code: 0, stdout: 'Already up to date\n', stderr: '' };
13807
+ }
13808
+ const verb = (sub === 'add') ? 'add' : 'install';
13809
+ return await runInstallTranscript(pkgs, ctx, { manager: 'pnpm', dev, header: `pnpm ${verb} v9.0.0` });
13810
+ }
13811
+
13812
+ if (sub === 'remove' || sub === 'rm' || sub === 'uninstall') {
13813
+ const pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
13814
+ for (const p of pkgs) uninstallPackage(p, ctx);
13815
+ return { code: 0, stdout: `removed ${pkgs.length} package(s)\n`, stderr: '' };
13816
+ }
13817
+
13818
+ if (sub === 'list' || sub === 'ls') {
13819
+ return { code: 0, stdout: listDependencies(ctx), stderr: '' };
13820
+ }
13821
+
13822
+ if (sub === 'run' || sub === 'run-script') {
13823
+ const scriptName = args[1];
13824
+ if (!scriptName) return { code: 1, stdout: '', stderr: 'pnpm: missing script name\n' };
13825
+ return await runPackageScript(scriptName, args.slice(2), ctx);
13826
+ }
13827
+
13828
+ if (sub === 'test') {
13829
+ return await runPackageScript('test', args.slice(1), ctx);
13830
+ }
13831
+
13832
+ if (sub === 'exec') {
13833
+ const cmd = args[1];
13834
+ if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
13835
+ const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
13836
+ if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
13837
+ return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
13838
+ }
13839
+
13840
+ if (sub === 'dlx') {
13841
+ return await this.npx(args.slice(1), ctx);
13842
+ }
13843
+
13844
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
13845
+ if (pkgData.scripts && pkgData.scripts[sub]) {
13846
+ return await runPackageScript(sub, args.slice(1), ctx);
13847
+ }
13848
+
13849
+ return { code: 1, stdout: '', stderr: `ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Unknown command: "${sub}"\n` };
13850
+ },
13851
+
13852
+ async serve(args, ctx) {
13853
+ if (args[0] === '--help' || args[0] === '-h') {
13854
+ return {
13855
+ code: 0,
13856
+ stdout: 'Usage: serve [dir] [--port <n>]\n\n Starts the built-in CodeLab preview server on the virtual port table.\n HTML/CSS/JS are served statically, .ts/.tsx/.jsx are transpiled to\n browser-native ESM on the fly, and bare imports resolve to jsDelivr ESM.\n\n Open the Web Preview drawer (or http://127.0.0.1:<port>/) to view it.\n',
13857
+ stderr: ''
13858
+ };
13859
+ }
13860
+ const rootArg = (() => {
13861
+ const positionals = [];
13862
+ for (let i = 0; i < args.length; i++) {
13863
+ const a = args[i];
13864
+ if (a === '--port' || a === '-p') { i++; continue; }
13865
+ if (a.startsWith('-')) continue;
13866
+ positionals.push(a);
13867
+ }
13868
+ return positionals[0];
13869
+ })();
13870
+ let port = 3000;
13871
+ for (let i = 0; i < args.length; i++) {
13872
+ if ((args[i] === '--port' || args[i] === '-p') && args[i + 1]) { port = Number(args[i + 1]) || port; i++; }
13873
+ else if (args[i].startsWith('--port=')) port = Number(args[i].split('=')[1]) || port;
13874
+ }
13875
+ const rootDir = ctx.resolvePath(rootArg || '.');
13876
+ if (!ctx.vfs.existsSync(rootDir)) {
13877
+ return { code: 1, stdout: '', stderr: `serve: ${rootArg}: No such file or directory\n` };
13878
+ }
13879
+ const entry = registerPreviewServer(ctx, rootDir, port);
13880
+ if (!entry) {
13881
+ return { code: 1, stdout: '', stderr: 'serve: no virtual port table available\n' };
13882
+ }
13883
+ return {
13884
+ code: 0,
13885
+ stdout: `\n ⚡ CodeLab preview server\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n ➜ Root: ${rootDir}\n ➜ Preview: open the Web Preview drawer for port ${entry.port}\n\n`,
13886
+ stderr: ''
13887
+ };
13888
+ },
13889
+
13077
13890
  // -----------------------------------------------------------------------
13078
13891
  // Port Table & HTTP Inspection: ports, curl
13079
13892
  // -----------------------------------------------------------------------
@@ -17028,6 +17841,9 @@ declare module 'bun:sqlite' {
17028
17841
  <span>${(this.hasGuidedLab && this.mode === 'guided') ? 'Verify Step' : 'Run Tests'}</span>
17029
17842
  <span class="codelab-btn__kbd">⌘↵</span>
17030
17843
  </button>
17844
+ <button type="button" class="codelab-btn codelab-btn--icon" id="cl-preview-app-btn" data-cl-action="preview-app" title="Run &amp; Preview in Browser (built-in dev server)" aria-label="Run and Preview in Browser">
17845
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
17846
+ </button>
17031
17847
  <span class="codelab-toolbar__sep" aria-hidden="true"></span>
17032
17848
  ${this.hasGuidedLab ? `
17033
17849
  <button type="button" class="codelab-btn codelab-btn--icon ${isGuideCollapsed ? '' : 'active'}" id="cl-toggle-guide-btn" data-cl-action="toggle-guide" title="Toggle Guide Panel" aria-label="Toggle Guide Panel" aria-pressed="${isGuideCollapsed ? 'false' : 'true'}">
@@ -19360,6 +20176,55 @@ declare module 'bun:sqlite' {
19360
20176
  return this._previewLoadPromise || Promise.resolve();
19361
20177
  }
19362
20178
 
20179
+ // One-click "run the app in a browser": if nothing is listening yet, start the
20180
+ // built-in preview server (which transpiles TS/JSX to browser-native ESM and
20181
+ // resolves bare imports via jsDelivr) and then open the Web Preview.
20182
+ async previewApp() {
20183
+ const existing = this._firstListeningPort();
20184
+ if (existing) {
20185
+ this._openWebPreview(existing);
20186
+ return existing;
20187
+ }
20188
+
20189
+ const htmlCandidates = ['public/index.html', 'index.html', 'site/index.html', 'src/index.html'];
20190
+ if (!htmlCandidates.some((f) => this.files && this.files[f])) {
20191
+ this.drawerTab = 'terminal';
20192
+ this.terminalLogs.push({
20193
+ type: 'system',
20194
+ text: '\nNo index.html found. Add an `index.html` (or run `serve <dir>` in the terminal) to preview your app.'
20195
+ });
20196
+ this._renderDrawerBody();
20197
+ return null;
20198
+ }
20199
+
20200
+ const rootDir = (this.files['public/index.html']) ? '/workspace/public'
20201
+ : (this.files['site/index.html']) ? '/workspace/site'
20202
+ : '/workspace';
20203
+
20204
+ if (!this.shell || typeof this.shell.execute !== 'function') return null;
20205
+ this._syncFilesToShellVfs();
20206
+ this.shell.cwd = this.cwd || '/workspace';
20207
+ this.drawerTab = 'terminal';
20208
+ this.terminalLogs.push({ type: 'system', text: `\n$ serve ${rootDir}` });
20209
+ this._renderDrawerBody();
20210
+
20211
+ try {
20212
+ const res = await this.shell.execute(`serve ${rootDir}`, {});
20213
+ if (res && res.stdout) this.terminalLogs.push({ type: 'stdout', text: res.stdout.replace(/\n$/, '') });
20214
+ if (res && res.stderr) this.terminalLogs.push({ type: 'stderr', text: res.stderr.replace(/\n$/, '') });
20215
+ } catch (err) {
20216
+ this.terminalLogs.push({ type: 'stderr', text: String((err && err.message) || err) });
20217
+ }
20218
+ this._renderDrawerBody();
20219
+
20220
+ const port = this._firstListeningPort();
20221
+ if (port) {
20222
+ this._openWebPreview(port);
20223
+ return port;
20224
+ }
20225
+ return null;
20226
+ }
20227
+
19363
20228
  _previewGo(urlOrPath) {
19364
20229
  let url = String(urlOrPath || '').trim();
19365
20230
  if (!url) return Promise.resolve();
@@ -19530,7 +20395,15 @@ declare module 'bun:sqlite' {
19530
20395
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
19531
20396
  <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-same-origin allow-modals" title="Web Preview"></iframe>
19532
20397
  </div>
19533
- <div class="codelab-preview-hint">${servers.length ? 'Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.' : 'No listening ports detected. Run a server (e.g. <code>node server.js &amp;</code>) to bind a virtual port.'}</div>
20398
+ ${servers.length
20399
+ ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
20400
+ : `<div class="codelab-preview-empty">
20401
+ <div class="codelab-preview-empty__icon">${CL_ICONS.globe || '🌐'}</div>
20402
+ <div class="codelab-preview-empty__title">No server running</div>
20403
+ <div class="codelab-preview-empty__text">Start the built-in preview server to render your <code>index.html</code>. TypeScript, TSX and JSX are transpiled for the browser automatically &mdash; no bundler required.</div>
20404
+ <button type="button" class="codelab-btn codelab-btn--primary codelab-btn--sm" data-cl-action="preview-app">${CL_ICONS.play || '▶'} <span>Run &amp; Preview</span></button>
20405
+ <div class="codelab-preview-empty__hint">or run <code>serve</code> in the terminal</div>
20406
+ </div>`}
19534
20407
  </div>
19535
20408
  `;
19536
20409
  this._loadPreviewFrame();
@@ -20533,6 +21406,8 @@ declare module 'bun:sqlite' {
20533
21406
  } else if (action === 'open-web-preview') {
20534
21407
  const port = Number(actionBtn.dataset.port || actionBtn.dataset.clPort);
20535
21408
  if (port) this._openWebPreview(port);
21409
+ } else if (action === 'preview-app') {
21410
+ this.previewApp();
20536
21411
  } else if (action === 'dismiss-toast') {
20537
21412
  this._dismissPortToast(actionBtn.dataset.port);
20538
21413
  } else if (action === 'preview-back') {
@@ -22479,6 +23354,7 @@ declare module 'bun:sqlite' {
22479
23354
  cloneRepo(repoInput, opts) { return this._instance ? this._instance.cloneRepo(repoInput, opts) : Promise.reject(new Error('Workbench not mounted')); }
22480
23355
  runDemo() { return this._instance ? this._instance.runDemo() : Promise.resolve(); }
22481
23356
  runTests(filter) { return this._instance ? this._instance.runTests(filter) : Promise.resolve(); }
23357
+ previewApp() { return this._instance ? this._instance.previewApp() : Promise.resolve(null); }
22482
23358
  stopExecution() { if (this._instance) this._instance.stopExecution(); }
22483
23359
  reset() { if (this._instance) this._instance.reset(); }
22484
23360
  exportWorkspace(opts) { return this._instance ? this._instance.exportWorkspace(opts) : null; }