@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/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();
@@ -4682,8 +4984,22 @@ function __initVirtualRuntime(rootScope) {
4682
4984
  }
4683
4985
 
4684
4986
  const _npmPackageCache = new Map();
4987
+ const _npmMetadataCache = new Map();
4988
+
4989
+ async function preloadNpmPackages(files = {}, secondArg = null, thirdArg = null) {
4990
+ // The 2nd/3rd arguments are overloaded for backwards compatibility:
4991
+ // preloadNpmPackages(files)
4992
+ // preloadNpmPackages(files, onProgress) // progress callback (used by the Workbench)
4993
+ // preloadNpmPackages(files, existingCache) // package-text cache (Map)
4994
+ // preloadNpmPackages(files, existingCache, onProgress)
4995
+ const isCacheLike = (v) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
4996
+ let onProgress = null;
4997
+ let existingCache = _npmPackageCache;
4998
+ if (typeof secondArg === 'function') onProgress = secondArg;
4999
+ else if (isCacheLike(secondArg)) existingCache = secondArg;
5000
+ if (typeof thirdArg === 'function') onProgress = onProgress || thirdArg;
5001
+ else if (isCacheLike(thirdArg)) existingCache = thirdArg;
4685
5002
 
4686
- async function preloadNpmPackages(files = {}, existingCache = _npmPackageCache) {
4687
5003
  const specs = new Set();
4688
5004
  const builtinSet = new Set([
4689
5005
  'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
@@ -4719,20 +5035,51 @@ function __initVirtualRuntime(rootScope) {
4719
5035
  while ((m = impRe.exec(content)) !== null) addSpec(m[1]);
4720
5036
  }
4721
5037
 
5038
+ // Follow declared dependencies transitively (best effort, bounded). Metadata
5039
+ // is memoised across calls so repeated preloads stay cheap.
5040
+ if (typeof fetch === 'function') {
5041
+ let pass = 0;
5042
+ while (pass < 6) {
5043
+ const pending = [];
5044
+ for (const pkg of specs) {
5045
+ if (!_npmMetadataCache.has(pkg)) pending.push(pkg);
5046
+ }
5047
+ if (pending.length === 0) break;
5048
+ pass++;
5049
+ await Promise.all(pending.map(async (pkg) => {
5050
+ let deps = [];
5051
+ try {
5052
+ const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}/package.json`);
5053
+ if (res && res.ok) {
5054
+ const meta = await res.json();
5055
+ deps = Object.keys((meta && meta.dependencies) || {});
5056
+ }
5057
+ } catch (_) {}
5058
+ _npmMetadataCache.set(pkg, deps);
5059
+ }));
5060
+ for (const pkg of pending) {
5061
+ for (const dep of (_npmMetadataCache.get(pkg) || [])) addSpec(dep);
5062
+ }
5063
+ }
5064
+ }
5065
+
4722
5066
  const loaded = {};
4723
5067
  for (const pkg of specs) {
4724
5068
  const nmKey = `node_modules/${pkg}/index.js`;
4725
5069
  if (files[nmKey] || files[`/workspace/${nmKey}`]) continue;
4726
- if (existingCache && existingCache.has(pkg)) {
5070
+ if (existingCache.has(pkg)) {
4727
5071
  loaded[pkg] = existingCache.get(pkg);
4728
5072
  continue;
4729
5073
  }
5074
+ if (typeof onProgress === 'function') {
5075
+ try { onProgress(pkg); } catch (_) {}
5076
+ }
4730
5077
  if (typeof fetch === 'function') {
4731
5078
  try {
4732
5079
  const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}`);
4733
5080
  if (res && res.ok) {
4734
5081
  const text = await res.text();
4735
- if (existingCache) existingCache.set(pkg, text);
5082
+ if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
4736
5083
  loaded[pkg] = text;
4737
5084
  }
4738
5085
  } catch (_) {}
@@ -7195,6 +7542,14 @@ function __initVirtualRuntime(rootScope) {
7195
7542
  };
7196
7543
  }
7197
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
+
7198
7553
  return {
7199
7554
  VirtualBuffer,
7200
7555
  VirtualCrypto,
@@ -7214,6 +7569,7 @@ function __initVirtualRuntime(rootScope) {
7214
7569
  createVirtualHttp,
7215
7570
  createVirtualNet,
7216
7571
  transpileTS,
7572
+ transpileForBrowser,
7217
7573
  preloadNpmPackages,
7218
7574
  createVirtualPortTable,
7219
7575
  executeInVirtualRuntime
@@ -9829,38 +10185,362 @@ if (typeof module !== 'undefined' && module.exports) {
9829
10185
  } catch (_) {}
9830
10186
  }
9831
10187
 
9832
- function installPackage(pkgSpec, ctx) {
9833
- const parts = pkgSpec.split('@').filter(Boolean);
9834
- const pkgName = pkgSpec.startsWith('@') ? '@' + parts[0] : parts[0];
9835
- const pkgVersion = parts[1] || '^1.0.0';
10188
+ // ---------------------------------------------------------------------------
10189
+ // Real npm package installation via the jsDelivr CDN
10190
+ // ---------------------------------------------------------------------------
10191
+ const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
10192
+
10193
+ // Minimal offline registry, used only when the CDN is unreachable so common
10194
+ // demos still resolve without network access.
10195
+ const OFFLINE_PACKAGE_FALLBACKS = {
10196
+ 'is-even': 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n',
10197
+ 'tiny-invariant': 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n',
10198
+ 'lodash': 'module.exports = { isArray: Array.isArray, isObject: function (v) { return v !== null && typeof v === "object"; } };\n',
10199
+ 'left-pad': 'module.exports = function leftPad(str, len, ch) { str = String(str); ch = (ch === undefined ? " " : String(ch)); while (str.length < len) str = ch + str; return str.slice(-len); };\n'
10200
+ };
9836
10201
 
9837
- const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
9838
- if (!pkgData.dependencies) pkgData.dependencies = {};
9839
- pkgData.dependencies[pkgName] = pkgVersion;
9840
- writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
10202
+ function packageCtxFetch(ctx) {
10203
+ if (ctx && ctx.shell && ctx.shell.options && typeof ctx.shell.options.fetchImpl === 'function') {
10204
+ return ctx.shell.options.fetchImpl;
10205
+ }
10206
+ if (typeof fetch === 'function') return fetch.bind(globalThis);
10207
+ return null;
10208
+ }
9841
10209
 
9842
- const targetDirs = ['/workspace/node_modules/' + pkgName];
9843
- const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', pkgName);
9844
- if (!targetDirs.includes(cwdTarget)) targetDirs.push(cwdTarget);
10210
+ function parsePackageSpec(spec) {
10211
+ const raw = String(spec || '').trim();
10212
+ if (!raw) return { name: '', range: null };
10213
+ if (raw.startsWith('@')) {
10214
+ const at = raw.indexOf('@', 1);
10215
+ if (at === -1) return { name: raw, range: null };
10216
+ return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
10217
+ }
10218
+ const at = raw.indexOf('@');
10219
+ if (at <= 0) return { name: raw, range: null };
10220
+ return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
10221
+ }
9845
10222
 
9846
- for (const modDir of targetDirs) {
9847
- ensureDirSync(ctx.vfs, modDir, ctx.emitMutation);
9848
- const modPkgPath = PosixPath.join(modDir, 'package.json');
9849
- const modIndexPath = PosixPath.join(modDir, 'index.js');
9850
- ctx.vfs.writeFileSync(modPkgPath, JSON.stringify({ name: pkgName, version: pkgVersion.replace(/^[\^~]/, ''), main: './index.js' }, null, 2) + '\n');
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
+
10236
+ function resolveEntryRelPath(pkgJson) {
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
+ }
10248
+ entry = String(entry).replace(/^[./]+/, '');
10249
+ return entry || 'index.js';
10250
+ }
10251
+
10252
+ function stripRelPath(rel) {
10253
+ return String(rel || '').replace(/^[./]+/, '');
10254
+ }
10255
+
10256
+ function extractRelativeSpecifiers(code) {
10257
+ const out = new Set();
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
+ }
10268
+ return Array.from(out);
10269
+ }
10270
+
10271
+ function normalizeRelPath(baseDir, rel) {
10272
+ const parts = String(baseDir || '').split('/').filter(Boolean);
10273
+ for (const seg of String(rel).split('/')) {
10274
+ if (!seg || seg === '.') continue;
10275
+ if (seg === '..') parts.pop();
10276
+ else parts.push(seg);
10277
+ }
10278
+ return parts.join('/');
10279
+ }
10280
+
10281
+ async function fetchTextFromCdn(fetchImpl, url) {
10282
+ try {
10283
+ const res = await fetchImpl(url);
10284
+ if (!res) return null;
10285
+ const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
10286
+ if (!ok) return null;
10287
+ if (typeof res.text === 'function') return await res.text();
10288
+ return String(res.body != null ? res.body : '');
10289
+ } catch (_) {
10290
+ return null;
10291
+ }
10292
+ }
10293
+
10294
+ async function resolvePackageMetadata(fetchImpl, name, range) {
10295
+ const urls = range
10296
+ ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
10297
+ : [`${CDN_NPM_BASE}/${name}/package.json`];
10298
+ for (const url of urls) {
10299
+ const text = await fetchTextFromCdn(fetchImpl, url);
10300
+ if (!text) continue;
10301
+ try {
10302
+ const parsed = JSON.parse(text);
10303
+ if (parsed && parsed.version) return parsed;
10304
+ } catch (_) {}
10305
+ }
10306
+ return null;
10307
+ }
10308
+
10309
+ // Download a package's entry module, its relative submodules and record its
10310
+ // declared dependencies so the caller can resolve them transitively.
10311
+ async function downloadPackageFiles(fetchImpl, name, range, seen) {
10312
+ const meta = await resolvePackageMetadata(fetchImpl, name, range);
10313
+ if (!meta) {
10314
+ const fallback = OFFLINE_PACKAGE_FALLBACKS[name];
10315
+ if (fallback) {
10316
+ const v = range ? range.replace(/^[\^~>=<\s]+/, '') || '1.0.0' : '1.0.0';
10317
+ return { ok: true, offline: true, version: v, entry: 'index.js', files: [{ rel: 'index.js', content: fallback }], deps: [] };
10318
+ }
10319
+ return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
10320
+ }
10321
+
10322
+ const version = meta.version;
10323
+ const key = `${name}@${version}`;
10324
+ if (seen.has(key)) {
10325
+ return { ok: true, deduped: true, version, entry: resolveEntryRelPath(meta), files: [], deps: [] };
10326
+ }
10327
+ seen.add(key);
10328
+
10329
+ const entry = resolveEntryRelPath(meta);
10330
+ const files = [];
10331
+ const visited = new Set();
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
+ }
10375
+ }
10376
+ }
10377
+ }
10378
+ // The declared entry may be missing on the CDN; fall back to index.js.
10379
+ if (!files.some(f => f.rel === entry)) {
10380
+ const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
10381
+ if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
10382
+ }
10383
+
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 };
10394
+ }
10395
+
10396
+ function installTargetDirs(ctx, name) {
10397
+ const dirs = ['/workspace/node_modules/' + name];
10398
+ const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', name);
10399
+ if (!dirs.includes(cwdTarget)) dirs.push(cwdTarget);
10400
+ return dirs;
10401
+ }
10402
+
10403
+ function writeInstalledPackageFiles(ctx, dirs, name, info) {
10404
+ for (const dir of dirs) {
10405
+ ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
10406
+ for (const f of info.files) {
10407
+ const full = PosixPath.join(dir, f.rel);
10408
+ ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
10409
+ ctx.vfs.writeFileSync(full, f.content);
10410
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
10411
+ }
10412
+ const modPkgPath = PosixPath.join(dir, 'package.json');
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
+ }
10423
+ ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
9851
10424
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
10425
+ }
10426
+ }
10427
+
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);
10432
+ const { name: pkgName, range } = parsePackageSpec(pkgSpec);
10433
+ if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
9852
10434
 
9853
- let code = 'module.exports = {};\n';
9854
- if (pkgName === 'is-even') {
9855
- code = 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n';
9856
- } else if (pkgName === 'tiny-invariant') {
9857
- code = 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n';
9858
- } else if (pkgName === 'lodash') {
9859
- code = 'module.exports = { isArray: Array.isArray, isObject: function(v) { return v !== null && typeof v === "object"; } };\n';
10435
+ const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
10436
+ const depField = isDev ? 'devDependencies' : 'dependencies';
10437
+ if (!pkgData[depField]) pkgData[depField] = {};
10438
+
10439
+ const fetchImpl = packageCtxFetch(ctx);
10440
+ const seen = (ctx.shell && ctx.shell._cdnSeen)
10441
+ ? ctx.shell._cdnSeen
10442
+ : (ctx.shell ? (ctx.shell._cdnSeen = new Set()) : new Set());
10443
+
10444
+ const queue = [{ name: pkgName, range, direct: true }];
10445
+ const requested = new Set([pkgName]);
10446
+ const installed = [];
10447
+ let warning = null;
10448
+ let directVersion = null;
10449
+
10450
+ while (queue.length > 0) {
10451
+ const item = queue.shift();
10452
+ const info = fetchImpl
10453
+ ? await downloadPackageFiles(fetchImpl, item.name, item.range, seen)
10454
+ : { ok: false, reason: `${item.name}: no fetch implementation available` };
10455
+
10456
+ if (!info.ok) {
10457
+ // Final fallback: an empty stub so offline demos still resolve the module.
10458
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, {
10459
+ version: '0.0.0', entry: 'index.js', files: [{ rel: 'index.js', content: 'module.exports = {};\n' }]
10460
+ });
10461
+ if (!warning) warning = info.reason;
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 });
10464
+ continue;
10465
+ }
10466
+
10467
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
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) });
10470
+ if (item.direct) directVersion = info.version || null;
10471
+
10472
+ for (const dep of (info.deps || [])) {
10473
+ const parsed = parsePackageSpec(dep);
10474
+ if (parsed.name && !requested.has(parsed.name)) {
10475
+ requested.add(parsed.name);
10476
+ queue.push({ name: parsed.name, range: null, direct: false });
10477
+ }
9860
10478
  }
9861
- ctx.vfs.writeFileSync(modIndexPath, code);
9862
- if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modIndexPath);
9863
10479
  }
10480
+
10481
+ pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
10482
+ writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
10483
+
10484
+ return { name: pkgName, ok: true, version: directVersion, installed, warning };
10485
+ }
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
+ };
9864
10544
  }
9865
10545
 
9866
10546
  function uninstallPackage(pkgName, ctx) {
@@ -9914,9 +10594,261 @@ if (typeof module !== 'undefined' && module.exports) {
9914
10594
  if (scriptArgs && scriptArgs.length > 0) {
9915
10595
  cmd += ' ' + scriptArgs.join(' ');
9916
10596
  }
10597
+ const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
10598
+ if (fallback) return fallback;
9917
10599
  return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
9918
10600
  }
9919
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
+
9920
10852
  function evaluatePosixTest(args, ctx) {
9921
10853
  const cleanArgs = [...args];
9922
10854
  if (cleanArgs.length > 0 && cleanArgs[cleanArgs.length - 1] === ']') {
@@ -12415,7 +13347,8 @@ if (typeof module !== 'undefined' && module.exports) {
12415
13347
  stdout += ' date, sleep, clear Date, delay, terminal screen control\n';
12416
13348
  stdout += ' history, ps, jobs, kill Process and job management\n';
12417
13349
  stdout += ' git [status diff log] Built-in version control\n';
12418
- 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';
12419
13352
  stdout += ' ports, curl Port table inspection & HTTP requests\n';
12420
13353
  return { code: 0, stdout, stderr: '' };
12421
13354
  },
@@ -12537,6 +13470,18 @@ if (typeof module !== 'undefined' && module.exports) {
12537
13470
 
12538
13471
  const sub = args[0];
12539
13472
 
13473
+ if (sub === '--version' || sub === '-v' || sub === '--revision') {
13474
+ return { code: 0, stdout: '1.1.20\n', stderr: '' };
13475
+ }
13476
+
13477
+ if (sub === '--help' || sub === '-h') {
13478
+ return {
13479
+ code: 0,
13480
+ stdout: 'Bun v1.1.20\nUsage: bun <command> [flags]\n\nCommands:\n run <file|script> Run a file or package script\n install, i, add Install dependencies\n remove, rm Remove dependencies\n test Run tests\n init Scaffold a new project\n -e <code> Evaluate JavaScript\n',
13481
+ stderr: ''
13482
+ };
13483
+ }
13484
+
12540
13485
  if (sub === 'init') {
12541
13486
  const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
12542
13487
  const dirName = PosixPath.basename(ctx.cwd) || 'app';
@@ -12586,12 +13531,27 @@ if (typeof module !== 'undefined' && module.exports) {
12586
13531
  return { code: 0, stdout: 'Done! A package.json file was created in ' + ctx.cwd + '\n', stderr: '' };
12587
13532
  }
12588
13533
 
12589
- if (sub === 'add') {
13534
+ if (sub === 'install' || sub === 'i' || sub === 'ci') {
12590
13535
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
12591
- for (const p of pkgs) {
12592
- installPackage(p, ctx);
13536
+ const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
13537
+ if (pkgs.length === 0) {
13538
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
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)' });
12593
13542
  }
12594
- return { code: 0, stdout: `saved ${pkgs.length} package(s)\n`, stderr: '' };
13543
+ return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
13544
+ }
13545
+
13546
+ if (sub === 'add') {
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)' });
12595
13555
  }
12596
13556
 
12597
13557
  if (sub === 'remove' || sub === 'rm') {
@@ -12751,18 +13711,14 @@ if (typeof module !== 'undefined' && module.exports) {
12751
13711
  }
12752
13712
 
12753
13713
  if (sub === 'i' || sub === 'install' || sub === 'add') {
12754
- 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');
12755
13716
  if (pkgs.length === 0) {
12756
13717
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
12757
- for (const p of Object.keys(pkgData.dependencies || {})) {
12758
- installPackage(p, ctx);
12759
- }
12760
- return { code: 0, stdout: 'up to date\n', stderr: '' };
13718
+ pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
13719
+ if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
12761
13720
  }
12762
- for (const p of pkgs) {
12763
- installPackage(p, ctx);
12764
- }
12765
- return { code: 0, stdout: `added ${pkgs.length} package(s) in 0.1s\n`, stderr: '' };
13721
+ return await runInstallTranscript(pkgs, ctx, { manager: 'npm', dev, header: 'npm install v10.2.0' });
12766
13722
  }
12767
13723
 
12768
13724
  if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
@@ -12814,6 +13770,123 @@ if (typeof module !== 'undefined' && module.exports) {
12814
13770
  return await this.npx(args, ctx);
12815
13771
  },
12816
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
+
12817
13890
  // -----------------------------------------------------------------------
12818
13891
  // Port Table & HTTP Inspection: ports, curl
12819
13892
  // -----------------------------------------------------------------------
@@ -12987,6 +14060,16 @@ if (typeof module !== 'undefined' && module.exports) {
12987
14060
  return PosixPath.resolve(this.cwd, p);
12988
14061
  }
12989
14062
 
14063
+ // True when `name` resolves to a shell function or coreutil (used by the
14064
+ // workbench to route recognised commands straight to the shell instead of
14065
+ // treating flag-looking input such as `node --version` as a JS expression).
14066
+ hasCommand(name) {
14067
+ if (!name) return false;
14068
+ const n = String(name);
14069
+ if (this.functions && Object.prototype.hasOwnProperty.call(this.functions, n)) return true;
14070
+ return !!this.commands && Object.prototype.hasOwnProperty.call(this.commands, n);
14071
+ }
14072
+
12990
14073
  _emitVfsMutation(type, absPath) {
12991
14074
  if (!this.vfs) return;
12992
14075
  const evt = { type, path: absPath, timestamp: Date.now() };
@@ -16758,6 +17841,9 @@ declare module 'bun:sqlite' {
16758
17841
  <span>${(this.hasGuidedLab && this.mode === 'guided') ? 'Verify Step' : 'Run Tests'}</span>
16759
17842
  <span class="codelab-btn__kbd">⌘↵</span>
16760
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>
16761
17847
  <span class="codelab-toolbar__sep" aria-hidden="true"></span>
16762
17848
  ${this.hasGuidedLab ? `
16763
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'}">
@@ -19090,6 +20176,55 @@ declare module 'bun:sqlite' {
19090
20176
  return this._previewLoadPromise || Promise.resolve();
19091
20177
  }
19092
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
+
19093
20228
  _previewGo(urlOrPath) {
19094
20229
  let url = String(urlOrPath || '').trim();
19095
20230
  if (!url) return Promise.resolve();
@@ -19260,7 +20395,15 @@ declare module 'bun:sqlite' {
19260
20395
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
19261
20396
  <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-same-origin allow-modals" title="Web Preview"></iframe>
19262
20397
  </div>
19263
- <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>`}
19264
20407
  </div>
19265
20408
  `;
19266
20409
  this._loadPreviewFrame();
@@ -20263,6 +21406,8 @@ declare module 'bun:sqlite' {
20263
21406
  } else if (action === 'open-web-preview') {
20264
21407
  const port = Number(actionBtn.dataset.port || actionBtn.dataset.clPort);
20265
21408
  if (port) this._openWebPreview(port);
21409
+ } else if (action === 'preview-app') {
21410
+ this.previewApp();
20266
21411
  } else if (action === 'dismiss-toast') {
20267
21412
  this._dismissPortToast(actionBtn.dataset.port);
20268
21413
  } else if (action === 'preview-back') {
@@ -21077,14 +22222,14 @@ declare module 'bun:sqlite' {
21077
22222
  </div>
21078
22223
  ${pkgs.length === 0 ? `
21079
22224
  <div style="padding:12px;border:1px solid var(--cl-border);border-radius:var(--cl-radius-sm);background:var(--cl-bg);color:var(--cl-fg-muted);font-size:12.5px;">
21080
- No external npm packages imported yet. Any <code>import ... from 'pkg'</code> or <code>require('pkg')</code> in your code is automatically resolved via <strong>esm.sh</strong> when you run or test.
22225
+ No external npm packages imported yet. Any <code>import ... from 'pkg'</code> or <code>require('pkg')</code> in your code is automatically resolved via <strong>jsDelivr</strong> when you run or test.
21081
22226
  </div>
21082
22227
  ` : `
21083
22228
  <div style="display:flex;flex-direction:column;gap:6px;">
21084
22229
  ${pkgs.map(p => `
21085
22230
  <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 12px;border:1px solid var(--cl-border);border-radius:var(--cl-radius-sm);background:var(--cl-bg);font-family:var(--cl-font-mono);font-size:12px;">
21086
22231
  <span style="color:var(--cl-fg);font-weight:600;">${escapeHtml(p.name)}</span>
21087
- <span style="color:var(--cl-accent);">${escapeHtml(p.version)} · esm.sh</span>
22232
+ <span style="color:var(--cl-accent);">${escapeHtml(p.version)} · jsDelivr</span>
21088
22233
  </div>
21089
22234
  `).join('')}
21090
22235
  </div>
@@ -21218,9 +22363,14 @@ declare module 'bun:sqlite' {
21218
22363
  if (detectedList.length > 0) {
21219
22364
  this._setRuntimeStatus('fetching', `Fetching ${detectedList.map(d => typeof d === 'string' ? d : d.name).join(', ')}...`);
21220
22365
  }
21221
- await root.CodeLabRuntime.preloadNpmPackages(payload.files, pkgName => {
21222
- this._setRuntimeStatus('fetching', `Fetching ${pkgName} from esm.sh...`);
22366
+ const preloaded = await root.CodeLabRuntime.preloadNpmPackages(payload.files, pkgName => {
22367
+ this._setRuntimeStatus('fetching', `Fetching ${pkgName} from jsDelivr CDN...`);
21223
22368
  });
22369
+ // Hand the fetched module sources to the runtime so the Web Worker
22370
+ // (which has an isolated module cache) can resolve them from node_modules.
22371
+ if (preloaded && typeof preloaded === 'object' && Object.keys(preloaded).length > 0) {
22372
+ payload.packages = Object.assign({}, preloaded, payload.packages || {});
22373
+ }
21224
22374
  }
21225
22375
  this._setRuntimeStatus('running', `Running ${payload.entry || payload.mode || 'script'}...`);
21226
22376
  let res;
@@ -21557,8 +22707,17 @@ declare module 'bun:sqlite' {
21557
22707
  return;
21558
22708
  }
21559
22709
 
21560
- const looksLikeJsExpr = /^(const|let|var|function|class|await|return|typeof|instanceof|new\s+|Math\.|JSON\.|Object\.|Array\.|Promise\.|console\.|process\.|Buffer\.|require\s*\(|import\s*\(|[0-9]+\s*[\+\-\*\/\%]|['"`\[{])/.test(trimmed)
21561
- || /^[a-zA-Z_$][\w$]*\s*(\.|===|!==|==|!=|<=|>=|\+=|-=|\*=|\(|\+\+|--)/.test(trimmed);
22710
+ const firstWord = (trimmed.split(/\s+/)[0] || '').replace(/^.*\//, '');
22711
+ const shellKnowsCommand = Boolean(
22712
+ firstWord &&
22713
+ this.shell &&
22714
+ typeof this.shell.hasCommand === 'function' &&
22715
+ this.shell.hasCommand(firstWord)
22716
+ );
22717
+ const looksLikeJsExpr = !shellKnowsCommand && (
22718
+ /^(const|let|var|function|class|await|return|typeof|instanceof|new\s+|Math\.|JSON\.|Object\.|Array\.|Promise\.|console\.|process\.|Buffer\.|require\s*\(|import\s*\(|[0-9]+\s*[\+\-\*\/\%]|['"`\[{])/.test(trimmed)
22719
+ || /^[a-zA-Z_$][\w$]*\s*(\.|===|!==|==|!=|<=|>=|\+=|-=|\*=|\(|\+\+|--)/.test(trimmed)
22720
+ );
21562
22721
 
21563
22722
  if (this.shell && typeof this.shell.execute === 'function' && !looksLikeJsExpr) {
21564
22723
  const abortCtrl = new AbortController();
@@ -22195,6 +23354,7 @@ declare module 'bun:sqlite' {
22195
23354
  cloneRepo(repoInput, opts) { return this._instance ? this._instance.cloneRepo(repoInput, opts) : Promise.reject(new Error('Workbench not mounted')); }
22196
23355
  runDemo() { return this._instance ? this._instance.runDemo() : Promise.resolve(); }
22197
23356
  runTests(filter) { return this._instance ? this._instance.runTests(filter) : Promise.resolve(); }
23357
+ previewApp() { return this._instance ? this._instance.previewApp() : Promise.resolve(null); }
22198
23358
  stopExecution() { if (this._instance) this._instance.stopExecution(); }
22199
23359
  reset() { if (this._instance) this._instance.reset(); }
22200
23360
  exportWorkspace(opts) { return this._instance ? this._instance.exportWorkspace(opts) : null; }