@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.
@@ -3974,14 +3974,316 @@ function __initVirtualRuntime(rootScope) {
3974
3974
  };
3975
3975
  }
3976
3976
 
3977
+ // =========================================================================
3978
+ // 7b. JSX / TSX SUPPORT
3979
+ // -------------------------------------------------------------------------
3980
+ // Rewrites JSX syntax into classic `createElement(...)` calls. This runs
3981
+ // BEFORE the string-masking pass so that JSX text (which routinely contains
3982
+ // quotes/apostrophes, e.g. <p>Don't</p>) is captured verbatim, while genuine
3983
+ // JS strings, comments and template literals are skipped untouched.
3984
+ // =========================================================================
3985
+ function detectJsxSyntax(source, filename) {
3986
+ if (/\.(jsx|tsx)$/i.test(filename || '')) return true;
3987
+ if (!source || source.indexOf('<') === -1) return false;
3988
+ if (/@jsx\b/.test(source)) return true;
3989
+ if (source.indexOf('<>') !== -1) return true;
3990
+ if (/<\/[A-Za-z]/.test(source)) return true;
3991
+ return false;
3992
+ }
3993
+
3994
+ function readJsxPragma(source) {
3995
+ let pragma = 'React.createElement';
3996
+ let frag = null;
3997
+ const m = /@jsx\s+([A-Za-z_$][\w$.]*)/.exec(source);
3998
+ if (m) pragma = m[1];
3999
+ const fm = /@jsxFrag\s+([A-Za-z_$][\w$.]*)/.exec(source);
4000
+ if (fm) frag = fm[1];
4001
+ if (!frag) frag = pragma === 'React.createElement' ? 'React.Fragment' : 'Fragment';
4002
+ return { pragma, frag };
4003
+ }
4004
+
4005
+ const JSX_WS_RE = /\s/;
4006
+ const JSX_NAME_START_RE = /[A-Za-z_$]/;
4007
+ const JSX_NAME_CHAR_RE = /[A-Za-z0-9_$:.\-]/;
4008
+
4009
+ function jsxThrow(message) {
4010
+ const err = new Error(message);
4011
+ err.jsxParse = true;
4012
+ throw err;
4013
+ }
4014
+
4015
+ // Returns the exclusive end index if a JS string / template / comment starts
4016
+ // at `i`, otherwise -1. Regexes are deliberately ignored.
4017
+ function jsxSkipJsLiteral(source, i) {
4018
+ const ch = source[i];
4019
+ const next = source[i + 1];
4020
+ const len = source.length;
4021
+ if (ch === '/' && next === '/') {
4022
+ const e = source.indexOf('\n', i);
4023
+ return e === -1 ? len : e;
4024
+ }
4025
+ if (ch === '/' && next === '*') {
4026
+ const e = source.indexOf('*/', i + 2);
4027
+ return e === -1 ? len : e + 2;
4028
+ }
4029
+ if (ch === '"' || ch === "'") {
4030
+ let j = i + 1;
4031
+ while (j < len) {
4032
+ const c = source[j];
4033
+ if (c === '\\') { j += 2; continue; }
4034
+ if (c === ch) { j++; break; }
4035
+ if (c === '\n') break;
4036
+ j++;
4037
+ }
4038
+ return j;
4039
+ }
4040
+ if (ch === '`') {
4041
+ let j = i + 1;
4042
+ let depth = 0;
4043
+ while (j < len) {
4044
+ const c = source[j];
4045
+ if (c === '\\') { j += 2; continue; }
4046
+ if (c === '$' && source[j + 1] === '{') { depth++; j += 2; continue; }
4047
+ if (c === '}' && depth > 0) { depth--; j++; continue; }
4048
+ if (c === '`' && depth === 0) { j++; break; }
4049
+ j++;
4050
+ }
4051
+ return j;
4052
+ }
4053
+ return -1;
4054
+ }
4055
+
4056
+ function jsxReadName(source, i) {
4057
+ if (!JSX_NAME_START_RE.test(source[i] || '')) jsxThrow('jsx: expected a tag name');
4058
+ let j = i;
4059
+ while (j < source.length && JSX_NAME_CHAR_RE.test(source[j])) j++;
4060
+ return { name: source.slice(i, j), next: j };
4061
+ }
4062
+
4063
+ function jsxSkipWs(source, i) {
4064
+ while (i < source.length && JSX_WS_RE.test(source[i])) i++;
4065
+ return i;
4066
+ }
4067
+
4068
+ function normalizeJsxText(raw) {
4069
+ if (!raw) return '';
4070
+ let t = raw.replace(/\r/g, '');
4071
+ if (t.indexOf('\n') !== -1) {
4072
+ t = t.split('\n').map((s) => s.replace(/[ \t]+/g, ' ').trim()).filter(Boolean).join(' ');
4073
+ } else if (!/\S/.test(t)) {
4074
+ return '';
4075
+ } else {
4076
+ t = t.replace(/[ \t]+/g, ' ');
4077
+ }
4078
+ return t ? JSON.stringify(t) : '';
4079
+ }
4080
+
4081
+ // Reads a balanced `{ ... }` expression container, skipping nested JSX and
4082
+ // JS literals. Returns the raw inner source (later re-transformed) plus the
4083
+ // index just past the closing brace.
4084
+ function jsxReadBraced(source, i, opts) {
4085
+ let depth = 0;
4086
+ let j = i;
4087
+ while (j < source.length) {
4088
+ const lit = jsxSkipJsLiteral(source, j);
4089
+ if (lit !== -1) { j = lit; continue; }
4090
+ const c = source[j];
4091
+ if (c === '{') { depth++; j++; continue; }
4092
+ if (c === '}') {
4093
+ depth--;
4094
+ j++;
4095
+ if (depth === 0) return { inner: source.slice(i + 1, j - 1), next: j };
4096
+ continue;
4097
+ }
4098
+ if (c === '<' && (JSX_NAME_START_RE.test(source[j + 1] || '') || source[j + 1] === '>')) {
4099
+ try {
4100
+ const el = jsxParseElement(source, j, opts);
4101
+ j = el.next;
4102
+ continue;
4103
+ } catch (e) {
4104
+ if (!e || !e.jsxParse) throw e;
4105
+ }
4106
+ }
4107
+ j++;
4108
+ }
4109
+ jsxThrow('jsx: unterminated expression container');
4110
+ }
4111
+
4112
+ function jsxParseElement(source, i, opts) {
4113
+ const o = opts || readJsxPragma(source);
4114
+ let j = i + 1;
4115
+ let isFragment = false;
4116
+ let typeExpr;
4117
+ if (source[j] === '>') {
4118
+ isFragment = true;
4119
+ typeExpr = o.frag;
4120
+ j++;
4121
+ } else {
4122
+ const nm = jsxReadName(source, j);
4123
+ j = nm.next;
4124
+ const raw = nm.name;
4125
+ const isReference = raw.indexOf('.') !== -1 || raw.indexOf(':') !== -1 || /^[A-Z_$]/.test(raw);
4126
+ if (isReference) {
4127
+ typeExpr = raw.replace(/:/g, '.');
4128
+ } else {
4129
+ typeExpr = JSON.stringify(raw);
4130
+ }
4131
+ }
4132
+
4133
+ const props = [];
4134
+ let selfClosing = false;
4135
+ if (!isFragment) {
4136
+ for (;;) {
4137
+ j = jsxSkipWs(source, j);
4138
+ if (j >= source.length) jsxThrow('jsx: unexpected end of input inside a tag');
4139
+ const c = source[j];
4140
+ if (c === '/') {
4141
+ if (source[j + 1] !== '>') jsxThrow('jsx: malformed self-closing tag');
4142
+ j += 2;
4143
+ selfClosing = true;
4144
+ break;
4145
+ }
4146
+ if (c === '>') { j++; break; }
4147
+ if (c === '{') {
4148
+ const br = jsxReadBraced(source, j, o);
4149
+ const inner = br.inner.trim();
4150
+ if (inner.slice(0, 3) !== '...') jsxThrow('jsx: only a spread {...} may appear where an attribute is expected');
4151
+ props.push({ spread: jsxTransform(inner.slice(3), o) });
4152
+ j = br.next;
4153
+ continue;
4154
+ }
4155
+ if (!JSX_NAME_START_RE.test(c)) jsxThrow('jsx: malformed attribute');
4156
+ const am = jsxReadName(source, j);
4157
+ const attrName = am.name;
4158
+ j = jsxSkipWs(source, am.next);
4159
+ let valueExpr = 'true';
4160
+ if (source[j] === '=') {
4161
+ j = jsxSkipWs(source, j + 1);
4162
+ const vc = source[j];
4163
+ if (vc === '"' || vc === "'") {
4164
+ let k = j + 1;
4165
+ while (k < source.length && source[k] !== vc) {
4166
+ if (source[k] === '\\') k++;
4167
+ k++;
4168
+ }
4169
+ if (k >= source.length) jsxThrow('jsx: unterminated attribute string');
4170
+ valueExpr = JSON.stringify(source.slice(j + 1, k));
4171
+ j = k + 1;
4172
+ } else if (vc === '{') {
4173
+ const br = jsxReadBraced(source, j, o);
4174
+ valueExpr = jsxTransform(br.inner, o) || 'undefined';
4175
+ j = br.next;
4176
+ } else if (vc === '<') {
4177
+ const el = jsxParseElement(source, j, o);
4178
+ valueExpr = el.code;
4179
+ j = el.next;
4180
+ } else {
4181
+ jsxThrow('jsx: unsupported attribute value');
4182
+ }
4183
+ }
4184
+ const propKey = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(attrName) ? attrName : JSON.stringify(attrName);
4185
+ props.push({ key: propKey, value: valueExpr });
4186
+ }
4187
+ }
4188
+
4189
+ const children = [];
4190
+ if (!selfClosing) {
4191
+ for (;;) {
4192
+ if (j >= source.length) jsxThrow('jsx: missing closing tag');
4193
+ const c = source[j];
4194
+ if (c === '<' && source[j + 1] === '/') {
4195
+ j = jsxSkipWs(source, j + 2);
4196
+ if (source[j] === '>') { j++; break; }
4197
+ const cm = jsxReadName(source, j);
4198
+ j = jsxSkipWs(source, cm.next);
4199
+ if (source[j] !== '>') jsxThrow('jsx: malformed closing tag');
4200
+ j++;
4201
+ break;
4202
+ }
4203
+ if (c === '<') {
4204
+ const el = jsxParseElement(source, j, o);
4205
+ children.push(el.code);
4206
+ j = el.next;
4207
+ continue;
4208
+ }
4209
+ if (c === '{') {
4210
+ const br = jsxReadBraced(source, j, o);
4211
+ const inner = jsxTransform(br.inner, o);
4212
+ if (inner && inner.trim()) children.push(inner);
4213
+ j = br.next;
4214
+ continue;
4215
+ }
4216
+ let k = j;
4217
+ while (k < source.length && source[k] !== '<' && source[k] !== '{') k++;
4218
+ const text = normalizeJsxText(source.slice(j, k));
4219
+ if (text) children.push(text);
4220
+ j = k;
4221
+ }
4222
+ }
4223
+
4224
+ let propsCode = 'null';
4225
+ if (props.length) {
4226
+ const parts = props.map((p) => (p.spread !== undefined ? '...(' + p.spread + ')' : p.key + ': ' + p.value));
4227
+ propsCode = '{ ' + parts.join(', ') + ' }';
4228
+ }
4229
+
4230
+ const args = [typeExpr, propsCode].concat(children);
4231
+ return { code: o.pragma + '(' + args.join(', ') + ')', next: j };
4232
+ }
4233
+
4234
+ function jsxTransform(source, opts) {
4235
+ const o = opts || readJsxPragma(source);
4236
+ let i = 0;
4237
+ let out = '';
4238
+ while (i < source.length) {
4239
+ const lit = jsxSkipJsLiteral(source, i);
4240
+ if (lit !== -1) { out += source.slice(i, lit); i = lit; continue; }
4241
+ const ch = source[i];
4242
+ if (ch === '<' && (JSX_NAME_START_RE.test(source[i + 1] || '') || source[i + 1] === '>')) {
4243
+ try {
4244
+ const el = jsxParseElement(source, i, o);
4245
+ out += el.code;
4246
+ i = el.next;
4247
+ continue;
4248
+ } catch (e) {
4249
+ if (!e || !e.jsxParse) throw e;
4250
+ }
4251
+ }
4252
+ out += ch;
4253
+ i++;
4254
+ }
4255
+ return out;
4256
+ }
4257
+
3977
4258
  // =========================================================================
3978
4259
  // 8. FAST TYPESCRIPT & ESM-TO-CJS TRANSPILER
3979
4260
  // =========================================================================
3980
- function transpileTS(source, filename = 'module.ts') {
4261
+ function transpileTS(source, filename = 'module.ts', opts = {}) {
4262
+ // `keepEsm` leaves `import`/`export` statements intact so the output can run
4263
+ // natively in a browser as an ES module (used by the built-in preview server).
4264
+ const keepEsm = Boolean(opts && opts.keepEsm);
3981
4265
  const isTS = /\.(ts|tsx|mts|cts)$/i.test(filename)
3982
- || /\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);
3983
- const hasESM = /^\s*(import|export)\s+/m.test(source);
3984
- if (!isTS && !hasESM) return source;
4266
+ || /^[ \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);
4267
+ const hasESM = /^\s*(?:import|export)\b/m.test(source)
4268
+ || /\bexport\s*\{/.test(source)
4269
+ || /\bimport\s*\{/.test(source)
4270
+ || /\bexport\s+default\b/.test(source);
4271
+ const hasJsx = detectJsxSyntax(source, filename);
4272
+ if (!isTS && !hasESM && !hasJsx) return source;
4273
+
4274
+ // JSX/TSX must be rewritten before masking so JSX text is kept verbatim.
4275
+ if (hasJsx) {
4276
+ const { pragma, frag } = readJsxPragma(source);
4277
+ const needsReact = pragma === 'React.createElement' && !/\bReact\b/.test(source);
4278
+ const transformed = jsxTransform(source, { pragma, frag });
4279
+ if (transformed !== source) {
4280
+ source = transformed;
4281
+ // The classic runtime needs a React binding available to the JSX output.
4282
+ if (needsReact) {
4283
+ source = (keepEsm ? 'import React from "react";\n' : 'const React = require("react");\n') + source;
4284
+ }
4285
+ }
4286
+ }
3985
4287
 
3986
4288
  // Step 1: Mask strings, template literals, regex literals, and comments so transforms never corrupt literals
3987
4289
  const placeholders = [];
@@ -4544,10 +4846,10 @@ function __initVirtualRuntime(rootScope) {
4544
4846
  } while (code !== prevCode);
4545
4847
  }
4546
4848
 
4547
- if (hasESM || isTS) {
4849
+ if ((hasESM || isTS) && !keepEsm) {
4548
4850
  // Convert ES module imports (including multi-line `{ ... }`)
4549
- 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);');
4550
- 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) => {
4851
+ code = code.replace(/\bimport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, 'const $1 = require($2);');
4852
+ code = code.replace(/\bimport\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, defId, specifiers, mod) => {
4551
4853
  const cleaned = specifiers
4552
4854
  .split(',')
4553
4855
  .map((s) => s.trim())
@@ -4558,7 +4860,7 @@ function __initVirtualRuntime(rootScope) {
4558
4860
  return `const ${defId} = (function(m){ return m && m.__esModule ? m.default : m; })(require(${mTrim}));` +
4559
4861
  (cleaned ? ` const { ${cleaned} } = require(${mTrim});` : '');
4560
4862
  });
4561
- code = code.replace(/^\s*import\s+\{([\s\S]*?)\}\s+from\s+([^\n;]+);?/gm, (_, specifiers, mod) => {
4863
+ code = code.replace(/\bimport\s*\{([\s\S]*?)\}\s*from\s*([^\n;]+);?/gm, (_, specifiers, mod) => {
4562
4864
  const cleaned = specifiers
4563
4865
  .split(',')
4564
4866
  .map((s) => s.trim())
@@ -4567,42 +4869,42 @@ function __initVirtualRuntime(rootScope) {
4567
4869
  .join(', ');
4568
4870
  return cleaned ? `const { ${cleaned} } = require(${mod.trim()});` : '';
4569
4871
  });
4570
- 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));');
4571
- code = code.replace(/^\s*import\s+(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
4872
+ 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));');
4873
+ code = code.replace(/\bimport\s+(\x00__LIT_\d+__\x00)\s*;?/gm, 'require($1);');
4572
4874
 
4573
4875
  // Convert ES module exports
4574
4876
  const exportedNames = [];
4575
4877
  let defaultExportName = null;
4576
4878
  let hasEsmExport = false;
4577
4879
 
4578
- code = code.replace(/^\s*export\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+([^\n;]+);?/gm, (_, ns, mod) => {
4880
+ code = code.replace(/\bexport\s*\*\s*as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*from\s*([^\n;]+);?/gm, (_, ns, mod) => {
4579
4881
  hasEsmExport = true;
4580
4882
  return `exports.${ns} = require(${mod.trim()});`;
4581
4883
  });
4582
- code = code.replace(/^\s*export\s+\*\s+from\s+([^\n;]+);?/gm, (_, mod) => {
4884
+ code = code.replace(/\bexport\s*\*\s*from\s*([^\n;]+);?/gm, (_, mod) => {
4583
4885
  hasEsmExport = true;
4584
4886
  return `Object.assign(exports, require(${mod.trim()}));`;
4585
4887
  });
4586
- code = code.replace(/^\s*export\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4888
+ code = code.replace(/\bexport\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4587
4889
  hasEsmExport = true;
4588
4890
  defaultExportName = name;
4589
4891
  return `${kw} ${name}`;
4590
4892
  });
4591
- code = code.replace(/^\s*export\s+default\s+/gm, () => {
4893
+ code = code.replace(/\bexport\s+default\s+/gm, () => {
4592
4894
  hasEsmExport = true;
4593
4895
  return 'exports.default = ';
4594
4896
  });
4595
- code = code.replace(/^\s*export\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4897
+ code = code.replace(/\bexport\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4596
4898
  hasEsmExport = true;
4597
4899
  exportedNames.push(name);
4598
4900
  return `${kw} ${name}`;
4599
4901
  });
4600
- code = code.replace(/^\s*export\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4902
+ code = code.replace(/\bexport\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
4601
4903
  hasEsmExport = true;
4602
4904
  exportedNames.push(name);
4603
4905
  return `${kw} ${name}`;
4604
4906
  });
4605
- code = code.replace(/^\s*export\s+\{([^}]+)\}\s+from\s+([^\n;]+);?/gm, (_, list, mod) => {
4907
+ code = code.replace(/\bexport\s*\{([^}]+)\}\s*from\s*([^\n;]+);?/gm, (_, list, mod) => {
4606
4908
  hasEsmExport = true;
4607
4909
  const mTrim = mod.trim();
4608
4910
  return list.split(',').map((item) => {
@@ -4614,7 +4916,7 @@ function __initVirtualRuntime(rootScope) {
4614
4916
  return `exports.${exported} = require(${mTrim}).${local};`;
4615
4917
  }).join(' ');
4616
4918
  });
4617
- code = code.replace(/^\s*export\s+\{([^}]+)\}\s*;?/gm, (_, list) => {
4919
+ code = code.replace(/\bexport\s*\{([^}]+)\}\s*;?/gm, (_, list) => {
4618
4920
  hasEsmExport = true;
4619
4921
  return list.split(',').map((item) => {
4620
4922
  const trimmed = item.trim();
@@ -4681,8 +4983,22 @@ function __initVirtualRuntime(rootScope) {
4681
4983
  }
4682
4984
 
4683
4985
  const _npmPackageCache = new Map();
4986
+ const _npmMetadataCache = new Map();
4987
+
4988
+ async function preloadNpmPackages(files = {}, secondArg = null, thirdArg = null) {
4989
+ // The 2nd/3rd arguments are overloaded for backwards compatibility:
4990
+ // preloadNpmPackages(files)
4991
+ // preloadNpmPackages(files, onProgress) // progress callback (used by the Workbench)
4992
+ // preloadNpmPackages(files, existingCache) // package-text cache (Map)
4993
+ // preloadNpmPackages(files, existingCache, onProgress)
4994
+ const isCacheLike = (v) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
4995
+ let onProgress = null;
4996
+ let existingCache = _npmPackageCache;
4997
+ if (typeof secondArg === 'function') onProgress = secondArg;
4998
+ else if (isCacheLike(secondArg)) existingCache = secondArg;
4999
+ if (typeof thirdArg === 'function') onProgress = onProgress || thirdArg;
5000
+ else if (isCacheLike(thirdArg)) existingCache = thirdArg;
4684
5001
 
4685
- async function preloadNpmPackages(files = {}, existingCache = _npmPackageCache) {
4686
5002
  const specs = new Set();
4687
5003
  const builtinSet = new Set([
4688
5004
  'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
@@ -4718,20 +5034,51 @@ function __initVirtualRuntime(rootScope) {
4718
5034
  while ((m = impRe.exec(content)) !== null) addSpec(m[1]);
4719
5035
  }
4720
5036
 
5037
+ // Follow declared dependencies transitively (best effort, bounded). Metadata
5038
+ // is memoised across calls so repeated preloads stay cheap.
5039
+ if (typeof fetch === 'function') {
5040
+ let pass = 0;
5041
+ while (pass < 6) {
5042
+ const pending = [];
5043
+ for (const pkg of specs) {
5044
+ if (!_npmMetadataCache.has(pkg)) pending.push(pkg);
5045
+ }
5046
+ if (pending.length === 0) break;
5047
+ pass++;
5048
+ await Promise.all(pending.map(async (pkg) => {
5049
+ let deps = [];
5050
+ try {
5051
+ const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}/package.json`);
5052
+ if (res && res.ok) {
5053
+ const meta = await res.json();
5054
+ deps = Object.keys((meta && meta.dependencies) || {});
5055
+ }
5056
+ } catch (_) {}
5057
+ _npmMetadataCache.set(pkg, deps);
5058
+ }));
5059
+ for (const pkg of pending) {
5060
+ for (const dep of (_npmMetadataCache.get(pkg) || [])) addSpec(dep);
5061
+ }
5062
+ }
5063
+ }
5064
+
4721
5065
  const loaded = {};
4722
5066
  for (const pkg of specs) {
4723
5067
  const nmKey = `node_modules/${pkg}/index.js`;
4724
5068
  if (files[nmKey] || files[`/workspace/${nmKey}`]) continue;
4725
- if (existingCache && existingCache.has(pkg)) {
5069
+ if (existingCache.has(pkg)) {
4726
5070
  loaded[pkg] = existingCache.get(pkg);
4727
5071
  continue;
4728
5072
  }
5073
+ if (typeof onProgress === 'function') {
5074
+ try { onProgress(pkg); } catch (_) {}
5075
+ }
4729
5076
  if (typeof fetch === 'function') {
4730
5077
  try {
4731
5078
  const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}`);
4732
5079
  if (res && res.ok) {
4733
5080
  const text = await res.text();
4734
- if (existingCache) existingCache.set(pkg, text);
5081
+ if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
4735
5082
  loaded[pkg] = text;
4736
5083
  }
4737
5084
  } catch (_) {}
@@ -7194,6 +7541,14 @@ function __initVirtualRuntime(rootScope) {
7194
7541
  };
7195
7542
  }
7196
7543
 
7544
+ // Transpile a source file so it can run natively in a browser as an ES module:
7545
+ // JSX is compiled to the classic runtime (auto-importing React when needed) and
7546
+ // TypeScript annotations are stripped, but `import`/`export` are preserved so an
7547
+ // import map can resolve bare specifiers to CDN ESM builds.
7548
+ function transpileForBrowser(source, filename = 'module.js') {
7549
+ return transpileTS(source, filename, { keepEsm: true });
7550
+ }
7551
+
7197
7552
  return {
7198
7553
  VirtualBuffer,
7199
7554
  VirtualCrypto,
@@ -7213,6 +7568,7 @@ function __initVirtualRuntime(rootScope) {
7213
7568
  createVirtualHttp,
7214
7569
  createVirtualNet,
7215
7570
  transpileTS,
7571
+ transpileForBrowser,
7216
7572
  preloadNpmPackages,
7217
7573
  createVirtualPortTable,
7218
7574
  executeInVirtualRuntime
@@ -9826,38 +10182,362 @@ if (typeof module !== 'undefined' && module.exports) {
9826
10182
  } catch (_) {}
9827
10183
  }
9828
10184
 
9829
- function installPackage(pkgSpec, ctx) {
9830
- const parts = pkgSpec.split('@').filter(Boolean);
9831
- const pkgName = pkgSpec.startsWith('@') ? '@' + parts[0] : parts[0];
9832
- const pkgVersion = parts[1] || '^1.0.0';
10185
+ // ---------------------------------------------------------------------------
10186
+ // Real npm package installation via the jsDelivr CDN
10187
+ // ---------------------------------------------------------------------------
10188
+ const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
10189
+
10190
+ // Minimal offline registry, used only when the CDN is unreachable so common
10191
+ // demos still resolve without network access.
10192
+ const OFFLINE_PACKAGE_FALLBACKS = {
10193
+ 'is-even': 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n',
10194
+ 'tiny-invariant': 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n',
10195
+ 'lodash': 'module.exports = { isArray: Array.isArray, isObject: function (v) { return v !== null && typeof v === "object"; } };\n',
10196
+ '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'
10197
+ };
9833
10198
 
9834
- const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
9835
- if (!pkgData.dependencies) pkgData.dependencies = {};
9836
- pkgData.dependencies[pkgName] = pkgVersion;
9837
- writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
10199
+ function packageCtxFetch(ctx) {
10200
+ if (ctx && ctx.shell && ctx.shell.options && typeof ctx.shell.options.fetchImpl === 'function') {
10201
+ return ctx.shell.options.fetchImpl;
10202
+ }
10203
+ if (typeof fetch === 'function') return fetch.bind(globalThis);
10204
+ return null;
10205
+ }
9838
10206
 
9839
- const targetDirs = ['/workspace/node_modules/' + pkgName];
9840
- const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', pkgName);
9841
- if (!targetDirs.includes(cwdTarget)) targetDirs.push(cwdTarget);
10207
+ function parsePackageSpec(spec) {
10208
+ const raw = String(spec || '').trim();
10209
+ if (!raw) return { name: '', range: null };
10210
+ if (raw.startsWith('@')) {
10211
+ const at = raw.indexOf('@', 1);
10212
+ if (at === -1) return { name: raw, range: null };
10213
+ return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
10214
+ }
10215
+ const at = raw.indexOf('@');
10216
+ if (at <= 0) return { name: raw, range: null };
10217
+ return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
10218
+ }
9842
10219
 
9843
- for (const modDir of targetDirs) {
9844
- ensureDirSync(ctx.vfs, modDir, ctx.emitMutation);
9845
- const modPkgPath = PosixPath.join(modDir, 'package.json');
9846
- const modIndexPath = PosixPath.join(modDir, 'index.js');
9847
- ctx.vfs.writeFileSync(modPkgPath, JSON.stringify({ name: pkgName, version: pkgVersion.replace(/^[\^~]/, ''), main: './index.js' }, null, 2) + '\n');
10220
+ function pickConditionalEntry(value) {
10221
+ if (typeof value === 'string') return value;
10222
+ if (!value || typeof value !== 'object') return null;
10223
+ // This runtime executes CommonJS, so it prefers CJS-friendly conditions.
10224
+ for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
10225
+ if (value[key] !== undefined) {
10226
+ const picked = pickConditionalEntry(value[key]);
10227
+ if (picked) return picked;
10228
+ }
10229
+ }
10230
+ return null;
10231
+ }
10232
+
10233
+ function resolveEntryRelPath(pkgJson) {
10234
+ let entry = null;
10235
+ const exp = pkgJson && pkgJson.exports;
10236
+ if (typeof exp === 'string') {
10237
+ entry = exp;
10238
+ } else if (exp && typeof exp === 'object' && exp['.'] !== undefined) {
10239
+ entry = pickConditionalEntry(exp['.']);
10240
+ }
10241
+ if (!entry) {
10242
+ entry = pkgJson.main || pkgJson.module ||
10243
+ (typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
10244
+ }
10245
+ entry = String(entry).replace(/^[./]+/, '');
10246
+ return entry || 'index.js';
10247
+ }
10248
+
10249
+ function stripRelPath(rel) {
10250
+ return String(rel || '').replace(/^[./]+/, '');
10251
+ }
10252
+
10253
+ function extractRelativeSpecifiers(code) {
10254
+ const out = new Set();
10255
+ const patterns = [
10256
+ /\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,
10257
+ /\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
10258
+ /\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
10259
+ /\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g
10260
+ ];
10261
+ for (const re of patterns) {
10262
+ let m;
10263
+ while ((m = re.exec(code)) !== null) out.add(m[1]);
10264
+ }
10265
+ return Array.from(out);
10266
+ }
10267
+
10268
+ function normalizeRelPath(baseDir, rel) {
10269
+ const parts = String(baseDir || '').split('/').filter(Boolean);
10270
+ for (const seg of String(rel).split('/')) {
10271
+ if (!seg || seg === '.') continue;
10272
+ if (seg === '..') parts.pop();
10273
+ else parts.push(seg);
10274
+ }
10275
+ return parts.join('/');
10276
+ }
10277
+
10278
+ async function fetchTextFromCdn(fetchImpl, url) {
10279
+ try {
10280
+ const res = await fetchImpl(url);
10281
+ if (!res) return null;
10282
+ const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
10283
+ if (!ok) return null;
10284
+ if (typeof res.text === 'function') return await res.text();
10285
+ return String(res.body != null ? res.body : '');
10286
+ } catch (_) {
10287
+ return null;
10288
+ }
10289
+ }
10290
+
10291
+ async function resolvePackageMetadata(fetchImpl, name, range) {
10292
+ const urls = range
10293
+ ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
10294
+ : [`${CDN_NPM_BASE}/${name}/package.json`];
10295
+ for (const url of urls) {
10296
+ const text = await fetchTextFromCdn(fetchImpl, url);
10297
+ if (!text) continue;
10298
+ try {
10299
+ const parsed = JSON.parse(text);
10300
+ if (parsed && parsed.version) return parsed;
10301
+ } catch (_) {}
10302
+ }
10303
+ return null;
10304
+ }
10305
+
10306
+ // Download a package's entry module, its relative submodules and record its
10307
+ // declared dependencies so the caller can resolve them transitively.
10308
+ async function downloadPackageFiles(fetchImpl, name, range, seen) {
10309
+ const meta = await resolvePackageMetadata(fetchImpl, name, range);
10310
+ if (!meta) {
10311
+ const fallback = OFFLINE_PACKAGE_FALLBACKS[name];
10312
+ if (fallback) {
10313
+ const v = range ? range.replace(/^[\^~>=<\s]+/, '') || '1.0.0' : '1.0.0';
10314
+ return { ok: true, offline: true, version: v, entry: 'index.js', files: [{ rel: 'index.js', content: fallback }], deps: [] };
10315
+ }
10316
+ return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
10317
+ }
10318
+
10319
+ const version = meta.version;
10320
+ const key = `${name}@${version}`;
10321
+ if (seen.has(key)) {
10322
+ return { ok: true, deduped: true, version, entry: resolveEntryRelPath(meta), files: [], deps: [] };
10323
+ }
10324
+ seen.add(key);
10325
+
10326
+ const entry = resolveEntryRelPath(meta);
10327
+ const files = [];
10328
+ const visited = new Set();
10329
+ // Seed with the package entry plus any declared `exports` subpaths, so a
10330
+ // later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
10331
+ const seed = [entry, `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`];
10332
+ const expMap = meta.exports;
10333
+ if (expMap && typeof expMap === 'object') {
10334
+ let subCount = 0;
10335
+ for (const key of Object.keys(expMap)) {
10336
+ if (key === '.' || key.slice(0, 2) !== './' || subCount >= 25) continue;
10337
+ const target = pickConditionalEntry(expMap[key]);
10338
+ if (target) { seed.push(target); subCount++; }
10339
+ }
10340
+ }
10341
+ let frontier = seed;
10342
+ while (frontier.length > 0) {
10343
+ const batch = [];
10344
+ for (const raw of frontier) {
10345
+ const rel = stripRelPath(raw);
10346
+ if (!rel || visited.has(rel)) continue;
10347
+ visited.add(rel);
10348
+ batch.push(rel);
10349
+ }
10350
+ frontier = [];
10351
+ if (batch.length === 0) break;
10352
+ const texts = await Promise.all(
10353
+ batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
10354
+ );
10355
+ for (let idx = 0; idx < batch.length; idx++) {
10356
+ const rel = batch[idx];
10357
+ const text = texts[idx];
10358
+ if (text === null) continue;
10359
+ files.push({ rel, content: text });
10360
+ const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
10361
+ for (const spec of extractRelativeSpecifiers(text)) {
10362
+ const target = normalizeRelPath(baseDir, spec);
10363
+ // Only guess extensions when the specifier omits one; non-existent
10364
+ // candidates 404 harmlessly.
10365
+ const cands = /\.[a-z0-9]+$/i.test(target)
10366
+ ? [target]
10367
+ : [target, `${target}.js`, `${target}.json`, `${target}.mjs`, `${target}.cjs`, `${target}/index.js`];
10368
+ for (const cand of cands) {
10369
+ const c = stripRelPath(cand);
10370
+ if (c && !visited.has(c)) frontier.push(cand);
10371
+ }
10372
+ }
10373
+ }
10374
+ }
10375
+ // The declared entry may be missing on the CDN; fall back to index.js.
10376
+ if (!files.some(f => f.rel === entry)) {
10377
+ const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
10378
+ if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
10379
+ }
10380
+
10381
+ // Declared dependencies plus non-optional peer dependencies (npm v7+ style),
10382
+ // so e.g. `npm install react-dom` also pulls in `react`.
10383
+ const depNames = Object.keys(meta.dependencies || {});
10384
+ const peerMeta = meta.peerDependenciesMeta || {};
10385
+ for (const peer of Object.keys(meta.peerDependencies || {})) {
10386
+ if (peerMeta[peer] && peerMeta[peer].optional) continue;
10387
+ if (depNames.indexOf(peer) === -1) depNames.push(peer);
10388
+ }
10389
+
10390
+ return { ok: true, version, entry, files, deps: depNames, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
10391
+ }
10392
+
10393
+ function installTargetDirs(ctx, name) {
10394
+ const dirs = ['/workspace/node_modules/' + name];
10395
+ const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', name);
10396
+ if (!dirs.includes(cwdTarget)) dirs.push(cwdTarget);
10397
+ return dirs;
10398
+ }
10399
+
10400
+ function writeInstalledPackageFiles(ctx, dirs, name, info) {
10401
+ for (const dir of dirs) {
10402
+ ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
10403
+ for (const f of info.files) {
10404
+ const full = PosixPath.join(dir, f.rel);
10405
+ ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
10406
+ ctx.vfs.writeFileSync(full, f.content);
10407
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
10408
+ }
10409
+ const modPkgPath = PosixPath.join(dir, 'package.json');
10410
+ const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
10411
+ if (info.pkgExports && typeof info.pkgExports === 'object') {
10412
+ const normalized = { '.': './' + (info.entry || 'index.js') };
10413
+ for (const key of Object.keys(info.pkgExports)) {
10414
+ if (key === '.' || key.indexOf('*') !== -1) continue;
10415
+ const target = pickConditionalEntry(info.pkgExports[key]);
10416
+ if (target) normalized[key] = target.charAt(0) === '.' ? target : './' + target;
10417
+ }
10418
+ modPkg.exports = normalized;
10419
+ }
10420
+ ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
9848
10421
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
10422
+ }
10423
+ }
10424
+
10425
+ async function installPackage(pkgSpec, ctx, onLine, opts) {
10426
+ const options = (onLine && typeof onLine === 'object') ? onLine : (opts || {});
10427
+ const lineCb = (typeof onLine === 'function') ? onLine : (typeof options.onLine === 'function' ? options.onLine : null);
10428
+ const isDev = Boolean(options.dev);
10429
+ const { name: pkgName, range } = parsePackageSpec(pkgSpec);
10430
+ if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
9849
10431
 
9850
- let code = 'module.exports = {};\n';
9851
- if (pkgName === 'is-even') {
9852
- code = 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n';
9853
- } else if (pkgName === 'tiny-invariant') {
9854
- code = 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n';
9855
- } else if (pkgName === 'lodash') {
9856
- code = 'module.exports = { isArray: Array.isArray, isObject: function(v) { return v !== null && typeof v === "object"; } };\n';
10432
+ const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
10433
+ const depField = isDev ? 'devDependencies' : 'dependencies';
10434
+ if (!pkgData[depField]) pkgData[depField] = {};
10435
+
10436
+ const fetchImpl = packageCtxFetch(ctx);
10437
+ const seen = (ctx.shell && ctx.shell._cdnSeen)
10438
+ ? ctx.shell._cdnSeen
10439
+ : (ctx.shell ? (ctx.shell._cdnSeen = new Set()) : new Set());
10440
+
10441
+ const queue = [{ name: pkgName, range, direct: true }];
10442
+ const requested = new Set([pkgName]);
10443
+ const installed = [];
10444
+ let warning = null;
10445
+ let directVersion = null;
10446
+
10447
+ while (queue.length > 0) {
10448
+ const item = queue.shift();
10449
+ const info = fetchImpl
10450
+ ? await downloadPackageFiles(fetchImpl, item.name, item.range, seen)
10451
+ : { ok: false, reason: `${item.name}: no fetch implementation available` };
10452
+
10453
+ if (!info.ok) {
10454
+ // Final fallback: an empty stub so offline demos still resolve the module.
10455
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, {
10456
+ version: '0.0.0', entry: 'index.js', files: [{ rel: 'index.js', content: 'module.exports = {};\n' }]
10457
+ });
10458
+ if (!warning) warning = info.reason;
10459
+ installed.push({ name: item.name, version: '0.0.0' });
10460
+ if (typeof lineCb === 'function') lineCb({ name: item.name, version: '0.0.0', offline: true });
10461
+ continue;
10462
+ }
10463
+
10464
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
10465
+ installed.push({ name: item.name, version: info.version || '1.0.0' });
10466
+ if (typeof lineCb === 'function') lineCb({ name: item.name, version: info.version || '1.0.0', deduped: Boolean(info.deduped) });
10467
+ if (item.direct) directVersion = info.version || null;
10468
+
10469
+ for (const dep of (info.deps || [])) {
10470
+ const parsed = parsePackageSpec(dep);
10471
+ if (parsed.name && !requested.has(parsed.name)) {
10472
+ requested.add(parsed.name);
10473
+ queue.push({ name: parsed.name, range: null, direct: false });
10474
+ }
9857
10475
  }
9858
- ctx.vfs.writeFileSync(modIndexPath, code);
9859
- if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modIndexPath);
9860
10476
  }
10477
+
10478
+ pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
10479
+ writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
10480
+
10481
+ return { name: pkgName, ok: true, version: directVersion, installed, warning };
10482
+ }
10483
+
10484
+ // Build a live install log: each line is streamed to the terminal as it
10485
+ // happens (when possible) and accumulated so the command can also return it.
10486
+ function createInstallEmitter(ctx, sink) {
10487
+ const stream = (ctx && typeof ctx.onStdout === 'function') ? ctx.onStdout : null;
10488
+ return function emit(text) {
10489
+ if (!text) return;
10490
+ sink.push(text);
10491
+ if (stream) stream(text);
10492
+ };
10493
+ }
10494
+
10495
+ function formatInstallLine(info) {
10496
+ if (!info || !info.name) return '';
10497
+ const suffix = info.offline ? ' (offline fallback)' : (info.deduped ? ' (deduped)' : '');
10498
+ return ` + ${info.name}@${info.version || '1.0.0'}${suffix}\n`;
10499
+ }
10500
+
10501
+ function countInstalledPackages(results) {
10502
+ const seen = new Set();
10503
+ for (const r of results) {
10504
+ if (!r) continue;
10505
+ if (r.name) seen.add(r.name);
10506
+ for (const p of (r.installed || [])) { if (p && p.name) seen.add(p.name); }
10507
+ }
10508
+ return seen.size;
10509
+ }
10510
+
10511
+ // Resolve + install a list of specs while printing a realistic transcript,
10512
+ // so `npm install` / `bun add` look like the real tools instead of a terse
10513
+ // "saved N package(s)".
10514
+ async function runInstallTranscript(pkgs, ctx, opts) {
10515
+ const options = opts || {};
10516
+ const manager = options.manager || 'bun';
10517
+ const header = options.header || (manager === 'npm' ? 'npm install v10.2.0' : 'bun add v1.1.20 (1.1.20)');
10518
+ const out = [];
10519
+ const emit = createInstallEmitter(ctx, out);
10520
+ const started = Date.now();
10521
+ emit(`${header}\n\nResolving dependencies...\n`);
10522
+ const results = [];
10523
+ for (const p of pkgs) {
10524
+ results.push(await installPackage(p, ctx, { onLine: (info) => emit(formatInstallLine(info)), dev: Boolean(options.dev) }));
10525
+ }
10526
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
10527
+ const count = countInstalledPackages(results);
10528
+ const ms = Date.now() - started;
10529
+ if (manager === 'npm') {
10530
+ emit(`\nadded ${count} package(s) in ${ms}ms\n`);
10531
+ } else if (manager === 'pnpm') {
10532
+ emit(`\nPackages: +${count}\n${'+'.repeat(Math.min(count, 40))}\nDone in ${ms}ms using pnpm v9.0.0\n`);
10533
+ } else {
10534
+ emit(`Saved lockfile\n\n${count} package(s) installed [${ms}ms]\n`);
10535
+ }
10536
+ return {
10537
+ code: 0,
10538
+ stdout: out.join(''),
10539
+ stderr: warning ? `${manager === 'npm' ? 'npm warn' : manager === 'pnpm' ? 'pnpm warn' : 'bun warn'} ${warning}\n` : ''
10540
+ };
9861
10541
  }
9862
10542
 
9863
10543
  function uninstallPackage(pkgName, ctx) {
@@ -9911,9 +10591,261 @@ if (typeof module !== 'undefined' && module.exports) {
9911
10591
  if (scriptArgs && scriptArgs.length > 0) {
9912
10592
  cmd += ' ' + scriptArgs.join(' ');
9913
10593
  }
10594
+ const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
10595
+ if (fallback) return fallback;
9914
10596
  return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
9915
10597
  }
9916
10598
 
10599
+ // ---------------------------------------------------------------------------
10600
+ // Built-in static preview server (`serve` / `npm run dev` fallback).
10601
+ //
10602
+ // Serves the virtual filesystem over a virtual port so the in-browser Web
10603
+ // Preview can render a project. `.ts/.tsx/.jsx` sources are transpiled to
10604
+ // browser-native ESM on the fly, and bare specifiers are resolved to jsDelivr
10605
+ // `+esm` builds through an injected import map — no bundler required.
10606
+ // ---------------------------------------------------------------------------
10607
+
10608
+ const CDN_ESM_BASE = 'https://cdn.jsdelivr.net/npm';
10609
+
10610
+ const PREVIEW_MIME = {
10611
+ '.html': 'text/html; charset=utf-8',
10612
+ '.htm': 'text/html; charset=utf-8',
10613
+ '.js': 'text/javascript; charset=utf-8',
10614
+ '.mjs': 'text/javascript; charset=utf-8',
10615
+ '.cjs': 'text/javascript; charset=utf-8',
10616
+ '.jsx': 'text/javascript; charset=utf-8',
10617
+ '.ts': 'text/javascript; charset=utf-8',
10618
+ '.tsx': 'text/javascript; charset=utf-8',
10619
+ '.css': 'text/css; charset=utf-8',
10620
+ '.json': 'application/json; charset=utf-8',
10621
+ '.map': 'application/json; charset=utf-8',
10622
+ '.svg': 'image/svg+xml',
10623
+ '.png': 'image/png',
10624
+ '.jpg': 'image/jpeg',
10625
+ '.jpeg': 'image/jpeg',
10626
+ '.gif': 'image/gif',
10627
+ '.webp': 'image/webp',
10628
+ '.ico': 'image/x-icon',
10629
+ '.txt': 'text/plain; charset=utf-8'
10630
+ };
10631
+
10632
+ function previewMimeFor(p) {
10633
+ const lower = String(p).toLowerCase();
10634
+ const dot = lower.lastIndexOf('.');
10635
+ if (dot === -1) return 'application/octet-stream';
10636
+ return PREVIEW_MIME[lower.slice(dot)] || 'application/octet-stream';
10637
+ }
10638
+
10639
+ function isPreviewScriptPath(p) {
10640
+ return /\.(?:[cm]?jsx?|tsx?)$/i.test(p) && !/\.d\.ts$/i.test(p);
10641
+ }
10642
+
10643
+ // Collect bare (non-relative) module specifiers referenced by a source file.
10644
+ function extractBareSpecifiers(code) {
10645
+ const out = new Set();
10646
+ const patterns = [
10647
+ /\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
10648
+ /\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
10649
+ /\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
10650
+ /\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g
10651
+ ];
10652
+ for (const re of patterns) {
10653
+ let m;
10654
+ while ((m = re.exec(code)) !== null) {
10655
+ const spec = m[1];
10656
+ if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.includes(':')) continue;
10657
+ out.add(spec);
10658
+ }
10659
+ }
10660
+ return Array.from(out);
10661
+ }
10662
+
10663
+ function normalizeVersionRange(range) {
10664
+ if (!range || typeof range !== 'string') return 'latest';
10665
+ const v = range.trim();
10666
+ if (!v || v === '*' || /^(?:latest|next|beta|canary)$/.test(v)) return 'latest';
10667
+ if (/^(?:file|link|workspace|portal|git|https?):/.test(v)) return 'latest';
10668
+ return v.replace(/\s+/g, '').replace(/^[v=\s]+/, '') || 'latest';
10669
+ }
10670
+
10671
+ function resolveBareVersion(vfs, rootDir, pkgName) {
10672
+ try {
10673
+ const modPkg = PosixPath.join(rootDir, 'node_modules', pkgName, 'package.json');
10674
+ if (vfs.existsSync(modPkg)) {
10675
+ const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
10676
+ if (parsed && parsed.version) return parsed.version;
10677
+ }
10678
+ } catch (_) {}
10679
+ try {
10680
+ for (const dir of [rootDir, '/workspace']) {
10681
+ const pkgPath = PosixPath.join(dir, 'package.json');
10682
+ if (!vfs.existsSync(pkgPath)) continue;
10683
+ const parsed = JSON.parse(vfs.readFileSync(pkgPath, 'utf8'));
10684
+ const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
10685
+ if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
10686
+ }
10687
+ } catch (_) {}
10688
+ return 'latest';
10689
+ }
10690
+
10691
+ function cdnEsmUrl(pkgName, version, subpath) {
10692
+ const base = `${CDN_ESM_BASE}/${pkgName}@${version}`;
10693
+ const sub = subpath ? '/' + String(subpath).replace(/^\/+|\/+$/g, '') : '';
10694
+ return `${base}${sub}/+esm`;
10695
+ }
10696
+
10697
+ function buildPreviewImportMap(vfs, rootDir, specifiers) {
10698
+ const imports = {};
10699
+ for (const spec of specifiers) {
10700
+ const parts = String(spec).split('/');
10701
+ const pkgName = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
10702
+ if (!pkgName) continue;
10703
+ const subpath = spec.slice(pkgName.length).replace(/^\/+/, '');
10704
+ const version = resolveBareVersion(vfs, rootDir, pkgName);
10705
+ imports[spec] = cdnEsmUrl(pkgName, version, subpath || undefined);
10706
+ }
10707
+ return imports;
10708
+ }
10709
+
10710
+ function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
10711
+ const scripts = [];
10712
+ const walk = (dir, depth) => {
10713
+ if (depth > 8 || scripts.length >= maxFiles) return;
10714
+ let entries = [];
10715
+ try { entries = vfs.readdirSync(dir); } catch (_) { return; }
10716
+ for (const name of entries) {
10717
+ if (name === 'node_modules' || name.startsWith('.')) continue;
10718
+ const full = PosixPath.join(dir, name);
10719
+ let st;
10720
+ try { st = vfs.statSync(full); } catch (_) { continue; }
10721
+ const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
10722
+ if (dirFlag) {
10723
+ walk(full, depth + 1);
10724
+ } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
10725
+ try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
10726
+ }
10727
+ }
10728
+ };
10729
+ walk(rootDir, 0);
10730
+ return scripts;
10731
+ }
10732
+
10733
+ function injectPreviewExtras(html, importMap) {
10734
+ let out = html;
10735
+ const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
10736
+ if (/<head[^>]*>/i.test(out)) {
10737
+ out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
10738
+ } else {
10739
+ out = importMapTag + '\n' + out;
10740
+ }
10741
+ const shim = '<script>window.__CODELAB_PREVIEW__ = true;</script>';
10742
+ if (/<\/body>/i.test(out)) out = out.replace(/<\/body>/i, `${shim}\n</body>`);
10743
+ else out = out + '\n' + shim;
10744
+ return out;
10745
+ }
10746
+
10747
+ function registerPreviewServer(ctx, rootDir, preferredPort) {
10748
+ const portTable = ctx.shell && ctx.shell.portTable;
10749
+ if (!portTable || typeof portTable.registerServer !== 'function') return null;
10750
+
10751
+ let port = Number(preferredPort) || 3000;
10752
+ const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
10753
+ while (taken.has(port)) port++;
10754
+
10755
+ const specifiers = new Set();
10756
+ for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
10757
+ for (const s of extractBareSpecifiers(content)) specifiers.add(s);
10758
+ }
10759
+ const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
10760
+
10761
+ const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
10762
+ const isDir = (p) => {
10763
+ try {
10764
+ const st = ctx.vfs.statSync(p);
10765
+ return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
10766
+ } catch (_) { return false; }
10767
+ };
10768
+ const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
10769
+
10770
+ const handler = async (request) => {
10771
+ let pathname = '/';
10772
+ try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
10773
+ const rel = pathname.replace(/^\/+/, '');
10774
+ let target = PosixPath.join(rootDir, rel);
10775
+ const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
10776
+
10777
+ if (!rel || pathname.endsWith('/') || isDir(target)) {
10778
+ target = PosixPath.join(target, 'index.html');
10779
+ }
10780
+ if (!exists(target) && !hasExt) {
10781
+ // Resolve extensionless module specifiers (e.g. `./components/Counter`)
10782
+ // the way a bundler / dev server would.
10783
+ const cands = [
10784
+ target + '.tsx', target + '.ts', target + '.jsx', target + '.js',
10785
+ target + '.mjs', target + '.cjs',
10786
+ PosixPath.join(target, 'index.tsx'), PosixPath.join(target, 'index.ts'),
10787
+ PosixPath.join(target, 'index.jsx'), PosixPath.join(target, 'index.js')
10788
+ ];
10789
+ for (const c of cands) { if (exists(c)) { target = c; break; } }
10790
+ }
10791
+ if (!exists(target) && !hasExt) {
10792
+ target = PosixPath.join(rootDir, 'index.html'); // SPA fallback
10793
+ }
10794
+ if (!exists(target)) {
10795
+ return new Response(
10796
+ `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
10797
+ { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
10798
+ );
10799
+ }
10800
+
10801
+ let body = readText(target);
10802
+ if (body === null) body = '';
10803
+ if (/\.html?$/i.test(target)) {
10804
+ body = injectPreviewExtras(body, importMap);
10805
+ } else if (isPreviewScriptPath(target)) {
10806
+ try {
10807
+ const rm = getRuntimeModule();
10808
+ if (rm && typeof rm.transpileForBrowser === 'function') {
10809
+ body = rm.transpileForBrowser(body, target);
10810
+ }
10811
+ } catch (_) {}
10812
+ }
10813
+
10814
+ return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
10815
+ };
10816
+
10817
+ const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
10818
+ return portTable.registerServer(port, {
10819
+ server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
10820
+ fetch: handler,
10821
+ name: 'code-lab-serve',
10822
+ pid,
10823
+ root: rootDir
10824
+ });
10825
+ }
10826
+
10827
+ // Common dev-server commands that cannot run inside the virtual runtime are
10828
+ // transparently redirected to the built-in preview server.
10829
+ const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
10830
+
10831
+ function tryDevScriptFallback(scriptName, cmd, ctx) {
10832
+ if (!PREVIEW_TOOL_RE.test(cmd)) return null;
10833
+ // Only fall back when the referenced tool is not actually installed.
10834
+ const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
10835
+ const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
10836
+ if (ctx.vfs.existsSync(binPath)) return null;
10837
+ const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
10838
+ const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
10839
+ const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
10840
+ const entry = registerPreviewServer(ctx, ctx.cwd, port);
10841
+ if (!entry) return null;
10842
+ return {
10843
+ code: 0,
10844
+ 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`,
10845
+ stderr: ''
10846
+ };
10847
+ }
10848
+
9917
10849
  function evaluatePosixTest(args, ctx) {
9918
10850
  const cleanArgs = [...args];
9919
10851
  if (cleanArgs.length > 0 && cleanArgs[cleanArgs.length - 1] === ']') {
@@ -12412,7 +13344,8 @@ if (typeof module !== 'undefined' && module.exports) {
12412
13344
  stdout += ' date, sleep, clear Date, delay, terminal screen control\n';
12413
13345
  stdout += ' history, ps, jobs, kill Process and job management\n';
12414
13346
  stdout += ' git [status diff log] Built-in version control\n';
12415
- stdout += ' node, bun, npm, npx, bunx CLI runtime and package shims\n';
13347
+ stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
13348
+ stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
12416
13349
  stdout += ' ports, curl Port table inspection & HTTP requests\n';
12417
13350
  return { code: 0, stdout, stderr: '' };
12418
13351
  },
@@ -12534,6 +13467,18 @@ if (typeof module !== 'undefined' && module.exports) {
12534
13467
 
12535
13468
  const sub = args[0];
12536
13469
 
13470
+ if (sub === '--version' || sub === '-v' || sub === '--revision') {
13471
+ return { code: 0, stdout: '1.1.20\n', stderr: '' };
13472
+ }
13473
+
13474
+ if (sub === '--help' || sub === '-h') {
13475
+ return {
13476
+ code: 0,
13477
+ 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',
13478
+ stderr: ''
13479
+ };
13480
+ }
13481
+
12537
13482
  if (sub === 'init') {
12538
13483
  const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
12539
13484
  const dirName = PosixPath.basename(ctx.cwd) || 'app';
@@ -12583,12 +13528,27 @@ if (typeof module !== 'undefined' && module.exports) {
12583
13528
  return { code: 0, stdout: 'Done! A package.json file was created in ' + ctx.cwd + '\n', stderr: '' };
12584
13529
  }
12585
13530
 
12586
- if (sub === 'add') {
13531
+ if (sub === 'install' || sub === 'i' || sub === 'ci') {
12587
13532
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
12588
- for (const p of pkgs) {
12589
- installPackage(p, ctx);
13533
+ const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
13534
+ if (pkgs.length === 0) {
13535
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
13536
+ const deps = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
13537
+ if (deps.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
13538
+ return await runInstallTranscript(deps, ctx, { manager: 'bun', header: 'bun install v1.1.20 (1.1.20)' });
12590
13539
  }
12591
- return { code: 0, stdout: `saved ${pkgs.length} package(s)\n`, stderr: '' };
13540
+ return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
13541
+ }
13542
+
13543
+ if (sub === 'add') {
13544
+ let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
13545
+ const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
13546
+ if (pkgs.length === 0) {
13547
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
13548
+ pkgs = Object.keys(pkgData.dependencies || {});
13549
+ }
13550
+ if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
13551
+ return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
12592
13552
  }
12593
13553
 
12594
13554
  if (sub === 'remove' || sub === 'rm') {
@@ -12748,18 +13708,14 @@ if (typeof module !== 'undefined' && module.exports) {
12748
13708
  }
12749
13709
 
12750
13710
  if (sub === 'i' || sub === 'install' || sub === 'add') {
12751
- const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
13711
+ let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
13712
+ const dev = args.some(a => a === '-D' || a === '--save-dev' || a === '--dev');
12752
13713
  if (pkgs.length === 0) {
12753
13714
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
12754
- for (const p of Object.keys(pkgData.dependencies || {})) {
12755
- installPackage(p, ctx);
12756
- }
12757
- return { code: 0, stdout: 'up to date\n', stderr: '' };
13715
+ pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
13716
+ if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
12758
13717
  }
12759
- for (const p of pkgs) {
12760
- installPackage(p, ctx);
12761
- }
12762
- return { code: 0, stdout: `added ${pkgs.length} package(s) in 0.1s\n`, stderr: '' };
13718
+ return await runInstallTranscript(pkgs, ctx, { manager: 'npm', dev, header: 'npm install v10.2.0' });
12763
13719
  }
12764
13720
 
12765
13721
  if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
@@ -12811,6 +13767,123 @@ if (typeof module !== 'undefined' && module.exports) {
12811
13767
  return await this.npx(args, ctx);
12812
13768
  },
12813
13769
 
13770
+ async pnpm(args, ctx) {
13771
+ if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
13772
+ return {
13773
+ code: 0,
13774
+ 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',
13775
+ stderr: ''
13776
+ };
13777
+ }
13778
+ const sub = args[0];
13779
+ if (sub === '--version' || sub === '-v') {
13780
+ return { code: 0, stdout: '9.0.0\n', stderr: '' };
13781
+ }
13782
+ const dev = args.some((a) => a === '-D' || a === '--save-dev' || a === '--dev' || a === '-d');
13783
+
13784
+ if (sub === 'init') {
13785
+ const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
13786
+ if (!ctx.vfs.existsSync(pkgPath)) {
13787
+ ctx.vfs.writeFileSync(pkgPath, JSON.stringify({
13788
+ name: PosixPath.basename(ctx.cwd) || 'app',
13789
+ version: '1.0.0',
13790
+ main: 'index.js',
13791
+ scripts: { test: 'echo "Error: no test specified" && exit 1' }
13792
+ }, null, 2) + '\n');
13793
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', pkgPath);
13794
+ }
13795
+ return { code: 0, stdout: 'Wrote to ' + pkgPath + '\n', stderr: '' };
13796
+ }
13797
+
13798
+ if (sub === 'install' || sub === 'i' || sub === 'add') {
13799
+ let pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
13800
+ if (pkgs.length === 0) {
13801
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
13802
+ pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
13803
+ if (pkgs.length === 0) return { code: 0, stdout: 'Already up to date\n', stderr: '' };
13804
+ }
13805
+ const verb = (sub === 'add') ? 'add' : 'install';
13806
+ return await runInstallTranscript(pkgs, ctx, { manager: 'pnpm', dev, header: `pnpm ${verb} v9.0.0` });
13807
+ }
13808
+
13809
+ if (sub === 'remove' || sub === 'rm' || sub === 'uninstall') {
13810
+ const pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
13811
+ for (const p of pkgs) uninstallPackage(p, ctx);
13812
+ return { code: 0, stdout: `removed ${pkgs.length} package(s)\n`, stderr: '' };
13813
+ }
13814
+
13815
+ if (sub === 'list' || sub === 'ls') {
13816
+ return { code: 0, stdout: listDependencies(ctx), stderr: '' };
13817
+ }
13818
+
13819
+ if (sub === 'run' || sub === 'run-script') {
13820
+ const scriptName = args[1];
13821
+ if (!scriptName) return { code: 1, stdout: '', stderr: 'pnpm: missing script name\n' };
13822
+ return await runPackageScript(scriptName, args.slice(2), ctx);
13823
+ }
13824
+
13825
+ if (sub === 'test') {
13826
+ return await runPackageScript('test', args.slice(1), ctx);
13827
+ }
13828
+
13829
+ if (sub === 'exec') {
13830
+ const cmd = args[1];
13831
+ if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
13832
+ const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
13833
+ if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
13834
+ return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
13835
+ }
13836
+
13837
+ if (sub === 'dlx') {
13838
+ return await this.npx(args.slice(1), ctx);
13839
+ }
13840
+
13841
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
13842
+ if (pkgData.scripts && pkgData.scripts[sub]) {
13843
+ return await runPackageScript(sub, args.slice(1), ctx);
13844
+ }
13845
+
13846
+ return { code: 1, stdout: '', stderr: `ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Unknown command: "${sub}"\n` };
13847
+ },
13848
+
13849
+ async serve(args, ctx) {
13850
+ if (args[0] === '--help' || args[0] === '-h') {
13851
+ return {
13852
+ code: 0,
13853
+ 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',
13854
+ stderr: ''
13855
+ };
13856
+ }
13857
+ const rootArg = (() => {
13858
+ const positionals = [];
13859
+ for (let i = 0; i < args.length; i++) {
13860
+ const a = args[i];
13861
+ if (a === '--port' || a === '-p') { i++; continue; }
13862
+ if (a.startsWith('-')) continue;
13863
+ positionals.push(a);
13864
+ }
13865
+ return positionals[0];
13866
+ })();
13867
+ let port = 3000;
13868
+ for (let i = 0; i < args.length; i++) {
13869
+ if ((args[i] === '--port' || args[i] === '-p') && args[i + 1]) { port = Number(args[i + 1]) || port; i++; }
13870
+ else if (args[i].startsWith('--port=')) port = Number(args[i].split('=')[1]) || port;
13871
+ }
13872
+ const rootDir = ctx.resolvePath(rootArg || '.');
13873
+ if (!ctx.vfs.existsSync(rootDir)) {
13874
+ return { code: 1, stdout: '', stderr: `serve: ${rootArg}: No such file or directory\n` };
13875
+ }
13876
+ const entry = registerPreviewServer(ctx, rootDir, port);
13877
+ if (!entry) {
13878
+ return { code: 1, stdout: '', stderr: 'serve: no virtual port table available\n' };
13879
+ }
13880
+ return {
13881
+ code: 0,
13882
+ 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`,
13883
+ stderr: ''
13884
+ };
13885
+ },
13886
+
12814
13887
  // -----------------------------------------------------------------------
12815
13888
  // Port Table & HTTP Inspection: ports, curl
12816
13889
  // -----------------------------------------------------------------------
@@ -12984,6 +14057,16 @@ if (typeof module !== 'undefined' && module.exports) {
12984
14057
  return PosixPath.resolve(this.cwd, p);
12985
14058
  }
12986
14059
 
14060
+ // True when `name` resolves to a shell function or coreutil (used by the
14061
+ // workbench to route recognised commands straight to the shell instead of
14062
+ // treating flag-looking input such as `node --version` as a JS expression).
14063
+ hasCommand(name) {
14064
+ if (!name) return false;
14065
+ const n = String(name);
14066
+ if (this.functions && Object.prototype.hasOwnProperty.call(this.functions, n)) return true;
14067
+ return !!this.commands && Object.prototype.hasOwnProperty.call(this.commands, n);
14068
+ }
14069
+
12987
14070
  _emitVfsMutation(type, absPath) {
12988
14071
  if (!this.vfs) return;
12989
14072
  const evt = { type, path: absPath, timestamp: Date.now() };
@@ -16751,6 +17834,9 @@ declare module 'bun:sqlite' {
16751
17834
  <span>${(this.hasGuidedLab && this.mode === 'guided') ? 'Verify Step' : 'Run Tests'}</span>
16752
17835
  <span class="codelab-btn__kbd">⌘↵</span>
16753
17836
  </button>
17837
+ <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">
17838
+ <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>
17839
+ </button>
16754
17840
  <span class="codelab-toolbar__sep" aria-hidden="true"></span>
16755
17841
  ${this.hasGuidedLab ? `
16756
17842
  <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'}">
@@ -19083,6 +20169,55 @@ declare module 'bun:sqlite' {
19083
20169
  return this._previewLoadPromise || Promise.resolve();
19084
20170
  }
19085
20171
 
20172
+ // One-click "run the app in a browser": if nothing is listening yet, start the
20173
+ // built-in preview server (which transpiles TS/JSX to browser-native ESM and
20174
+ // resolves bare imports via jsDelivr) and then open the Web Preview.
20175
+ async previewApp() {
20176
+ const existing = this._firstListeningPort();
20177
+ if (existing) {
20178
+ this._openWebPreview(existing);
20179
+ return existing;
20180
+ }
20181
+
20182
+ const htmlCandidates = ['public/index.html', 'index.html', 'site/index.html', 'src/index.html'];
20183
+ if (!htmlCandidates.some((f) => this.files && this.files[f])) {
20184
+ this.drawerTab = 'terminal';
20185
+ this.terminalLogs.push({
20186
+ type: 'system',
20187
+ text: '\nNo index.html found. Add an `index.html` (or run `serve <dir>` in the terminal) to preview your app.'
20188
+ });
20189
+ this._renderDrawerBody();
20190
+ return null;
20191
+ }
20192
+
20193
+ const rootDir = (this.files['public/index.html']) ? '/workspace/public'
20194
+ : (this.files['site/index.html']) ? '/workspace/site'
20195
+ : '/workspace';
20196
+
20197
+ if (!this.shell || typeof this.shell.execute !== 'function') return null;
20198
+ this._syncFilesToShellVfs();
20199
+ this.shell.cwd = this.cwd || '/workspace';
20200
+ this.drawerTab = 'terminal';
20201
+ this.terminalLogs.push({ type: 'system', text: `\n$ serve ${rootDir}` });
20202
+ this._renderDrawerBody();
20203
+
20204
+ try {
20205
+ const res = await this.shell.execute(`serve ${rootDir}`, {});
20206
+ if (res && res.stdout) this.terminalLogs.push({ type: 'stdout', text: res.stdout.replace(/\n$/, '') });
20207
+ if (res && res.stderr) this.terminalLogs.push({ type: 'stderr', text: res.stderr.replace(/\n$/, '') });
20208
+ } catch (err) {
20209
+ this.terminalLogs.push({ type: 'stderr', text: String((err && err.message) || err) });
20210
+ }
20211
+ this._renderDrawerBody();
20212
+
20213
+ const port = this._firstListeningPort();
20214
+ if (port) {
20215
+ this._openWebPreview(port);
20216
+ return port;
20217
+ }
20218
+ return null;
20219
+ }
20220
+
19086
20221
  _previewGo(urlOrPath) {
19087
20222
  let url = String(urlOrPath || '').trim();
19088
20223
  if (!url) return Promise.resolve();
@@ -19253,7 +20388,15 @@ declare module 'bun:sqlite' {
19253
20388
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
19254
20389
  <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-same-origin allow-modals" title="Web Preview"></iframe>
19255
20390
  </div>
19256
- <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>
20391
+ ${servers.length
20392
+ ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
20393
+ : `<div class="codelab-preview-empty">
20394
+ <div class="codelab-preview-empty__icon">${CL_ICONS.globe || '🌐'}</div>
20395
+ <div class="codelab-preview-empty__title">No server running</div>
20396
+ <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>
20397
+ <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>
20398
+ <div class="codelab-preview-empty__hint">or run <code>serve</code> in the terminal</div>
20399
+ </div>`}
19257
20400
  </div>
19258
20401
  `;
19259
20402
  this._loadPreviewFrame();
@@ -20256,6 +21399,8 @@ declare module 'bun:sqlite' {
20256
21399
  } else if (action === 'open-web-preview') {
20257
21400
  const port = Number(actionBtn.dataset.port || actionBtn.dataset.clPort);
20258
21401
  if (port) this._openWebPreview(port);
21402
+ } else if (action === 'preview-app') {
21403
+ this.previewApp();
20259
21404
  } else if (action === 'dismiss-toast') {
20260
21405
  this._dismissPortToast(actionBtn.dataset.port);
20261
21406
  } else if (action === 'preview-back') {
@@ -21070,14 +22215,14 @@ declare module 'bun:sqlite' {
21070
22215
  </div>
21071
22216
  ${pkgs.length === 0 ? `
21072
22217
  <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;">
21073
- 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.
22218
+ 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.
21074
22219
  </div>
21075
22220
  ` : `
21076
22221
  <div style="display:flex;flex-direction:column;gap:6px;">
21077
22222
  ${pkgs.map(p => `
21078
22223
  <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;">
21079
22224
  <span style="color:var(--cl-fg);font-weight:600;">${escapeHtml(p.name)}</span>
21080
- <span style="color:var(--cl-accent);">${escapeHtml(p.version)} · esm.sh</span>
22225
+ <span style="color:var(--cl-accent);">${escapeHtml(p.version)} · jsDelivr</span>
21081
22226
  </div>
21082
22227
  `).join('')}
21083
22228
  </div>
@@ -21211,9 +22356,14 @@ declare module 'bun:sqlite' {
21211
22356
  if (detectedList.length > 0) {
21212
22357
  this._setRuntimeStatus('fetching', `Fetching ${detectedList.map(d => typeof d === 'string' ? d : d.name).join(', ')}...`);
21213
22358
  }
21214
- await root.CodeLabRuntime.preloadNpmPackages(payload.files, pkgName => {
21215
- this._setRuntimeStatus('fetching', `Fetching ${pkgName} from esm.sh...`);
22359
+ const preloaded = await root.CodeLabRuntime.preloadNpmPackages(payload.files, pkgName => {
22360
+ this._setRuntimeStatus('fetching', `Fetching ${pkgName} from jsDelivr CDN...`);
21216
22361
  });
22362
+ // Hand the fetched module sources to the runtime so the Web Worker
22363
+ // (which has an isolated module cache) can resolve them from node_modules.
22364
+ if (preloaded && typeof preloaded === 'object' && Object.keys(preloaded).length > 0) {
22365
+ payload.packages = Object.assign({}, preloaded, payload.packages || {});
22366
+ }
21217
22367
  }
21218
22368
  this._setRuntimeStatus('running', `Running ${payload.entry || payload.mode || 'script'}...`);
21219
22369
  let res;
@@ -21550,8 +22700,17 @@ declare module 'bun:sqlite' {
21550
22700
  return;
21551
22701
  }
21552
22702
 
21553
- 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)
21554
- || /^[a-zA-Z_$][\w$]*\s*(\.|===|!==|==|!=|<=|>=|\+=|-=|\*=|\(|\+\+|--)/.test(trimmed);
22703
+ const firstWord = (trimmed.split(/\s+/)[0] || '').replace(/^.*\//, '');
22704
+ const shellKnowsCommand = Boolean(
22705
+ firstWord &&
22706
+ this.shell &&
22707
+ typeof this.shell.hasCommand === 'function' &&
22708
+ this.shell.hasCommand(firstWord)
22709
+ );
22710
+ const looksLikeJsExpr = !shellKnowsCommand && (
22711
+ /^(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)
22712
+ || /^[a-zA-Z_$][\w$]*\s*(\.|===|!==|==|!=|<=|>=|\+=|-=|\*=|\(|\+\+|--)/.test(trimmed)
22713
+ );
21555
22714
 
21556
22715
  if (this.shell && typeof this.shell.execute === 'function' && !looksLikeJsExpr) {
21557
22716
  const abortCtrl = new AbortController();
@@ -22188,6 +23347,7 @@ declare module 'bun:sqlite' {
22188
23347
  cloneRepo(repoInput, opts) { return this._instance ? this._instance.cloneRepo(repoInput, opts) : Promise.reject(new Error('Workbench not mounted')); }
22189
23348
  runDemo() { return this._instance ? this._instance.runDemo() : Promise.resolve(); }
22190
23349
  runTests(filter) { return this._instance ? this._instance.runTests(filter) : Promise.resolve(); }
23350
+ previewApp() { return this._instance ? this._instance.previewApp() : Promise.resolve(null); }
22191
23351
  stopExecution() { if (this._instance) this._instance.stopExecution(); }
22192
23352
  reset() { if (this._instance) this._instance.reset(); }
22193
23353
  exportWorkspace(opts) { return this._instance ? this._instance.exportWorkspace(opts) : null; }