@innovatorved/code-lab 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/shell.js CHANGED
@@ -2371,9 +2371,31 @@
2371
2371
  return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
2372
2372
  }
2373
2373
 
2374
+ function pickConditionalEntry(value) {
2375
+ if (typeof value === 'string') return value;
2376
+ if (!value || typeof value !== 'object') return null;
2377
+ // This runtime executes CommonJS, so it prefers CJS-friendly conditions.
2378
+ for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
2379
+ if (value[key] !== undefined) {
2380
+ const picked = pickConditionalEntry(value[key]);
2381
+ if (picked) return picked;
2382
+ }
2383
+ }
2384
+ return null;
2385
+ }
2386
+
2374
2387
  function resolveEntryRelPath(pkgJson) {
2375
- let entry = pkgJson.main || pkgJson.module ||
2376
- (typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
2388
+ let entry = null;
2389
+ const exp = pkgJson && pkgJson.exports;
2390
+ if (typeof exp === 'string') {
2391
+ entry = exp;
2392
+ } else if (exp && typeof exp === 'object' && exp['.'] !== undefined) {
2393
+ entry = pickConditionalEntry(exp['.']);
2394
+ }
2395
+ if (!entry) {
2396
+ entry = pkgJson.main || pkgJson.module ||
2397
+ (typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
2398
+ }
2377
2399
  entry = String(entry).replace(/^[./]+/, '');
2378
2400
  return entry || 'index.js';
2379
2401
  }
@@ -2384,9 +2406,16 @@
2384
2406
 
2385
2407
  function extractRelativeSpecifiers(code) {
2386
2408
  const out = new Set();
2387
- const re = /(?:\brequire\s*\(\s*|\bimport\s+[\s\S]{0,120}?\bfrom\s*|\bimport\s*\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g;
2388
- let m;
2389
- while ((m = re.exec(code)) !== null) out.add(m[1]);
2409
+ const patterns = [
2410
+ /\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,
2411
+ /\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
2412
+ /\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
2413
+ /\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g
2414
+ ];
2415
+ for (const re of patterns) {
2416
+ let m;
2417
+ while ((m = re.exec(code)) !== null) out.add(m[1]);
2418
+ }
2390
2419
  return Array.from(out);
2391
2420
  }
2392
2421
 
@@ -2451,20 +2480,49 @@
2451
2480
  const entry = resolveEntryRelPath(meta);
2452
2481
  const files = [];
2453
2482
  const visited = new Set();
2454
- const queue = [entry];
2455
- while (queue.length > 0) {
2456
- const rel = stripRelPath(queue.shift());
2457
- if (!rel || visited.has(rel)) continue;
2458
- visited.add(rel);
2459
- const text = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`);
2460
- if (text === null) continue;
2461
- files.push({ rel, content: text });
2462
- const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
2463
- for (const spec of extractRelativeSpecifiers(text)) {
2464
- const target = normalizeRelPath(baseDir, spec);
2465
- for (const cand of [target, `${target}.js`, `${target}.json`, `${target}/index.js`]) {
2466
- const c = stripRelPath(cand);
2467
- if (c && !visited.has(c)) { queue.push(cand); break; }
2483
+ // Seed with the package entry plus any declared `exports` subpaths, so a
2484
+ // later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
2485
+ const seed = [entry, `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`];
2486
+ const expMap = meta.exports;
2487
+ if (expMap && typeof expMap === 'object') {
2488
+ let subCount = 0;
2489
+ for (const key of Object.keys(expMap)) {
2490
+ if (key === '.' || key.slice(0, 2) !== './' || subCount >= 25) continue;
2491
+ const target = pickConditionalEntry(expMap[key]);
2492
+ if (target) { seed.push(target); subCount++; }
2493
+ }
2494
+ }
2495
+ let frontier = seed;
2496
+ while (frontier.length > 0) {
2497
+ const batch = [];
2498
+ for (const raw of frontier) {
2499
+ const rel = stripRelPath(raw);
2500
+ if (!rel || visited.has(rel)) continue;
2501
+ visited.add(rel);
2502
+ batch.push(rel);
2503
+ }
2504
+ frontier = [];
2505
+ if (batch.length === 0) break;
2506
+ const texts = await Promise.all(
2507
+ batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
2508
+ );
2509
+ for (let idx = 0; idx < batch.length; idx++) {
2510
+ const rel = batch[idx];
2511
+ const text = texts[idx];
2512
+ if (text === null) continue;
2513
+ files.push({ rel, content: text });
2514
+ const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
2515
+ for (const spec of extractRelativeSpecifiers(text)) {
2516
+ const target = normalizeRelPath(baseDir, spec);
2517
+ // Only guess extensions when the specifier omits one; non-existent
2518
+ // candidates 404 harmlessly.
2519
+ const cands = /\.[a-z0-9]+$/i.test(target)
2520
+ ? [target]
2521
+ : [target, `${target}.js`, `${target}.json`, `${target}.mjs`, `${target}.cjs`, `${target}/index.js`];
2522
+ for (const cand of cands) {
2523
+ const c = stripRelPath(cand);
2524
+ if (c && !visited.has(c)) frontier.push(cand);
2525
+ }
2468
2526
  }
2469
2527
  }
2470
2528
  }
@@ -2474,7 +2532,16 @@
2474
2532
  if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
2475
2533
  }
2476
2534
 
2477
- return { ok: true, version, entry, files, deps: Object.keys(meta.dependencies || {}) };
2535
+ // Declared dependencies plus non-optional peer dependencies (npm v7+ style),
2536
+ // so e.g. `npm install react-dom` also pulls in `react`.
2537
+ const depNames = Object.keys(meta.dependencies || {});
2538
+ const peerMeta = meta.peerDependenciesMeta || {};
2539
+ for (const peer of Object.keys(meta.peerDependencies || {})) {
2540
+ if (peerMeta[peer] && peerMeta[peer].optional) continue;
2541
+ if (depNames.indexOf(peer) === -1) depNames.push(peer);
2542
+ }
2543
+
2544
+ return { ok: true, version, entry, files, deps: depNames, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
2478
2545
  }
2479
2546
 
2480
2547
  function installTargetDirs(ctx, name) {
@@ -2495,17 +2562,30 @@
2495
2562
  }
2496
2563
  const modPkgPath = PosixPath.join(dir, 'package.json');
2497
2564
  const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
2565
+ if (info.pkgExports && typeof info.pkgExports === 'object') {
2566
+ const normalized = { '.': './' + (info.entry || 'index.js') };
2567
+ for (const key of Object.keys(info.pkgExports)) {
2568
+ if (key === '.' || key.indexOf('*') !== -1) continue;
2569
+ const target = pickConditionalEntry(info.pkgExports[key]);
2570
+ if (target) normalized[key] = target.charAt(0) === '.' ? target : './' + target;
2571
+ }
2572
+ modPkg.exports = normalized;
2573
+ }
2498
2574
  ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
2499
2575
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
2500
2576
  }
2501
2577
  }
2502
2578
 
2503
- async function installPackage(pkgSpec, ctx) {
2579
+ async function installPackage(pkgSpec, ctx, onLine, opts) {
2580
+ const options = (onLine && typeof onLine === 'object') ? onLine : (opts || {});
2581
+ const lineCb = (typeof onLine === 'function') ? onLine : (typeof options.onLine === 'function' ? options.onLine : null);
2582
+ const isDev = Boolean(options.dev);
2504
2583
  const { name: pkgName, range } = parsePackageSpec(pkgSpec);
2505
2584
  if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
2506
2585
 
2507
2586
  const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
2508
- if (!pkgData.dependencies) pkgData.dependencies = {};
2587
+ const depField = isDev ? 'devDependencies' : 'dependencies';
2588
+ if (!pkgData[depField]) pkgData[depField] = {};
2509
2589
 
2510
2590
  const fetchImpl = packageCtxFetch(ctx);
2511
2591
  const seen = (ctx.shell && ctx.shell._cdnSeen)
@@ -2531,11 +2611,13 @@
2531
2611
  });
2532
2612
  if (!warning) warning = info.reason;
2533
2613
  installed.push({ name: item.name, version: '0.0.0' });
2614
+ if (typeof lineCb === 'function') lineCb({ name: item.name, version: '0.0.0', offline: true });
2534
2615
  continue;
2535
2616
  }
2536
2617
 
2537
2618
  writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
2538
2619
  installed.push({ name: item.name, version: info.version || '1.0.0' });
2620
+ if (typeof lineCb === 'function') lineCb({ name: item.name, version: info.version || '1.0.0', deduped: Boolean(info.deduped) });
2539
2621
  if (item.direct) directVersion = info.version || null;
2540
2622
 
2541
2623
  for (const dep of (info.deps || [])) {
@@ -2547,12 +2629,71 @@
2547
2629
  }
2548
2630
  }
2549
2631
 
2550
- pkgData.dependencies[pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData.dependencies[pkgName] || 'latest'));
2632
+ pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
2551
2633
  writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
2552
2634
 
2553
2635
  return { name: pkgName, ok: true, version: directVersion, installed, warning };
2554
2636
  }
2555
2637
 
2638
+ // Build a live install log: each line is streamed to the terminal as it
2639
+ // happens (when possible) and accumulated so the command can also return it.
2640
+ function createInstallEmitter(ctx, sink) {
2641
+ const stream = (ctx && typeof ctx.onStdout === 'function') ? ctx.onStdout : null;
2642
+ return function emit(text) {
2643
+ if (!text) return;
2644
+ sink.push(text);
2645
+ if (stream) stream(text);
2646
+ };
2647
+ }
2648
+
2649
+ function formatInstallLine(info) {
2650
+ if (!info || !info.name) return '';
2651
+ const suffix = info.offline ? ' (offline fallback)' : (info.deduped ? ' (deduped)' : '');
2652
+ return ` + ${info.name}@${info.version || '1.0.0'}${suffix}\n`;
2653
+ }
2654
+
2655
+ function countInstalledPackages(results) {
2656
+ const seen = new Set();
2657
+ for (const r of results) {
2658
+ if (!r) continue;
2659
+ if (r.name) seen.add(r.name);
2660
+ for (const p of (r.installed || [])) { if (p && p.name) seen.add(p.name); }
2661
+ }
2662
+ return seen.size;
2663
+ }
2664
+
2665
+ // Resolve + install a list of specs while printing a realistic transcript,
2666
+ // so `npm install` / `bun add` look like the real tools instead of a terse
2667
+ // "saved N package(s)".
2668
+ async function runInstallTranscript(pkgs, ctx, opts) {
2669
+ const options = opts || {};
2670
+ const manager = options.manager || 'bun';
2671
+ const header = options.header || (manager === 'npm' ? 'npm install v10.2.0' : 'bun add v1.1.20 (1.1.20)');
2672
+ const out = [];
2673
+ const emit = createInstallEmitter(ctx, out);
2674
+ const started = Date.now();
2675
+ emit(`${header}\n\nResolving dependencies...\n`);
2676
+ const results = [];
2677
+ for (const p of pkgs) {
2678
+ results.push(await installPackage(p, ctx, { onLine: (info) => emit(formatInstallLine(info)), dev: Boolean(options.dev) }));
2679
+ }
2680
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
2681
+ const count = countInstalledPackages(results);
2682
+ const ms = Date.now() - started;
2683
+ if (manager === 'npm') {
2684
+ emit(`\nadded ${count} package(s) in ${ms}ms\n`);
2685
+ } else if (manager === 'pnpm') {
2686
+ emit(`\nPackages: +${count}\n${'+'.repeat(Math.min(count, 40))}\nDone in ${ms}ms using pnpm v9.0.0\n`);
2687
+ } else {
2688
+ emit(`Saved lockfile\n\n${count} package(s) installed [${ms}ms]\n`);
2689
+ }
2690
+ return {
2691
+ code: 0,
2692
+ stdout: out.join(''),
2693
+ stderr: warning ? `${manager === 'npm' ? 'npm warn' : manager === 'pnpm' ? 'pnpm warn' : 'bun warn'} ${warning}\n` : ''
2694
+ };
2695
+ }
2696
+
2556
2697
  function uninstallPackage(pkgName, ctx) {
2557
2698
  const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
2558
2699
  let changed = false;
@@ -2604,9 +2745,261 @@
2604
2745
  if (scriptArgs && scriptArgs.length > 0) {
2605
2746
  cmd += ' ' + scriptArgs.join(' ');
2606
2747
  }
2748
+ const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
2749
+ if (fallback) return fallback;
2607
2750
  return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
2608
2751
  }
2609
2752
 
2753
+ // ---------------------------------------------------------------------------
2754
+ // Built-in static preview server (`serve` / `npm run dev` fallback).
2755
+ //
2756
+ // Serves the virtual filesystem over a virtual port so the in-browser Web
2757
+ // Preview can render a project. `.ts/.tsx/.jsx` sources are transpiled to
2758
+ // browser-native ESM on the fly, and bare specifiers are resolved to jsDelivr
2759
+ // `+esm` builds through an injected import map — no bundler required.
2760
+ // ---------------------------------------------------------------------------
2761
+
2762
+ const CDN_ESM_BASE = 'https://cdn.jsdelivr.net/npm';
2763
+
2764
+ const PREVIEW_MIME = {
2765
+ '.html': 'text/html; charset=utf-8',
2766
+ '.htm': 'text/html; charset=utf-8',
2767
+ '.js': 'text/javascript; charset=utf-8',
2768
+ '.mjs': 'text/javascript; charset=utf-8',
2769
+ '.cjs': 'text/javascript; charset=utf-8',
2770
+ '.jsx': 'text/javascript; charset=utf-8',
2771
+ '.ts': 'text/javascript; charset=utf-8',
2772
+ '.tsx': 'text/javascript; charset=utf-8',
2773
+ '.css': 'text/css; charset=utf-8',
2774
+ '.json': 'application/json; charset=utf-8',
2775
+ '.map': 'application/json; charset=utf-8',
2776
+ '.svg': 'image/svg+xml',
2777
+ '.png': 'image/png',
2778
+ '.jpg': 'image/jpeg',
2779
+ '.jpeg': 'image/jpeg',
2780
+ '.gif': 'image/gif',
2781
+ '.webp': 'image/webp',
2782
+ '.ico': 'image/x-icon',
2783
+ '.txt': 'text/plain; charset=utf-8'
2784
+ };
2785
+
2786
+ function previewMimeFor(p) {
2787
+ const lower = String(p).toLowerCase();
2788
+ const dot = lower.lastIndexOf('.');
2789
+ if (dot === -1) return 'application/octet-stream';
2790
+ return PREVIEW_MIME[lower.slice(dot)] || 'application/octet-stream';
2791
+ }
2792
+
2793
+ function isPreviewScriptPath(p) {
2794
+ return /\.(?:[cm]?jsx?|tsx?)$/i.test(p) && !/\.d\.ts$/i.test(p);
2795
+ }
2796
+
2797
+ // Collect bare (non-relative) module specifiers referenced by a source file.
2798
+ function extractBareSpecifiers(code) {
2799
+ const out = new Set();
2800
+ const patterns = [
2801
+ /\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
2802
+ /\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
2803
+ /\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
2804
+ /\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g
2805
+ ];
2806
+ for (const re of patterns) {
2807
+ let m;
2808
+ while ((m = re.exec(code)) !== null) {
2809
+ const spec = m[1];
2810
+ if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.includes(':')) continue;
2811
+ out.add(spec);
2812
+ }
2813
+ }
2814
+ return Array.from(out);
2815
+ }
2816
+
2817
+ function normalizeVersionRange(range) {
2818
+ if (!range || typeof range !== 'string') return 'latest';
2819
+ const v = range.trim();
2820
+ if (!v || v === '*' || /^(?:latest|next|beta|canary)$/.test(v)) return 'latest';
2821
+ if (/^(?:file|link|workspace|portal|git|https?):/.test(v)) return 'latest';
2822
+ return v.replace(/\s+/g, '').replace(/^[v=\s]+/, '') || 'latest';
2823
+ }
2824
+
2825
+ function resolveBareVersion(vfs, rootDir, pkgName) {
2826
+ try {
2827
+ const modPkg = PosixPath.join(rootDir, 'node_modules', pkgName, 'package.json');
2828
+ if (vfs.existsSync(modPkg)) {
2829
+ const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
2830
+ if (parsed && parsed.version) return parsed.version;
2831
+ }
2832
+ } catch (_) {}
2833
+ try {
2834
+ for (const dir of [rootDir, '/workspace']) {
2835
+ const pkgPath = PosixPath.join(dir, 'package.json');
2836
+ if (!vfs.existsSync(pkgPath)) continue;
2837
+ const parsed = JSON.parse(vfs.readFileSync(pkgPath, 'utf8'));
2838
+ const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
2839
+ if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
2840
+ }
2841
+ } catch (_) {}
2842
+ return 'latest';
2843
+ }
2844
+
2845
+ function cdnEsmUrl(pkgName, version, subpath) {
2846
+ const base = `${CDN_ESM_BASE}/${pkgName}@${version}`;
2847
+ const sub = subpath ? '/' + String(subpath).replace(/^\/+|\/+$/g, '') : '';
2848
+ return `${base}${sub}/+esm`;
2849
+ }
2850
+
2851
+ function buildPreviewImportMap(vfs, rootDir, specifiers) {
2852
+ const imports = {};
2853
+ for (const spec of specifiers) {
2854
+ const parts = String(spec).split('/');
2855
+ const pkgName = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
2856
+ if (!pkgName) continue;
2857
+ const subpath = spec.slice(pkgName.length).replace(/^\/+/, '');
2858
+ const version = resolveBareVersion(vfs, rootDir, pkgName);
2859
+ imports[spec] = cdnEsmUrl(pkgName, version, subpath || undefined);
2860
+ }
2861
+ return imports;
2862
+ }
2863
+
2864
+ function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
2865
+ const scripts = [];
2866
+ const walk = (dir, depth) => {
2867
+ if (depth > 8 || scripts.length >= maxFiles) return;
2868
+ let entries = [];
2869
+ try { entries = vfs.readdirSync(dir); } catch (_) { return; }
2870
+ for (const name of entries) {
2871
+ if (name === 'node_modules' || name.startsWith('.')) continue;
2872
+ const full = PosixPath.join(dir, name);
2873
+ let st;
2874
+ try { st = vfs.statSync(full); } catch (_) { continue; }
2875
+ const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
2876
+ if (dirFlag) {
2877
+ walk(full, depth + 1);
2878
+ } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
2879
+ try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
2880
+ }
2881
+ }
2882
+ };
2883
+ walk(rootDir, 0);
2884
+ return scripts;
2885
+ }
2886
+
2887
+ function injectPreviewExtras(html, importMap) {
2888
+ let out = html;
2889
+ const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
2890
+ if (/<head[^>]*>/i.test(out)) {
2891
+ out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
2892
+ } else {
2893
+ out = importMapTag + '\n' + out;
2894
+ }
2895
+ const shim = '<script>window.__CODELAB_PREVIEW__ = true;</script>';
2896
+ if (/<\/body>/i.test(out)) out = out.replace(/<\/body>/i, `${shim}\n</body>`);
2897
+ else out = out + '\n' + shim;
2898
+ return out;
2899
+ }
2900
+
2901
+ function registerPreviewServer(ctx, rootDir, preferredPort) {
2902
+ const portTable = ctx.shell && ctx.shell.portTable;
2903
+ if (!portTable || typeof portTable.registerServer !== 'function') return null;
2904
+
2905
+ let port = Number(preferredPort) || 3000;
2906
+ const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
2907
+ while (taken.has(port)) port++;
2908
+
2909
+ const specifiers = new Set();
2910
+ for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
2911
+ for (const s of extractBareSpecifiers(content)) specifiers.add(s);
2912
+ }
2913
+ const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
2914
+
2915
+ const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
2916
+ const isDir = (p) => {
2917
+ try {
2918
+ const st = ctx.vfs.statSync(p);
2919
+ return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
2920
+ } catch (_) { return false; }
2921
+ };
2922
+ const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
2923
+
2924
+ const handler = async (request) => {
2925
+ let pathname = '/';
2926
+ try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
2927
+ const rel = pathname.replace(/^\/+/, '');
2928
+ let target = PosixPath.join(rootDir, rel);
2929
+ const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
2930
+
2931
+ if (!rel || pathname.endsWith('/') || isDir(target)) {
2932
+ target = PosixPath.join(target, 'index.html');
2933
+ }
2934
+ if (!exists(target) && !hasExt) {
2935
+ // Resolve extensionless module specifiers (e.g. `./components/Counter`)
2936
+ // the way a bundler / dev server would.
2937
+ const cands = [
2938
+ target + '.tsx', target + '.ts', target + '.jsx', target + '.js',
2939
+ target + '.mjs', target + '.cjs',
2940
+ PosixPath.join(target, 'index.tsx'), PosixPath.join(target, 'index.ts'),
2941
+ PosixPath.join(target, 'index.jsx'), PosixPath.join(target, 'index.js')
2942
+ ];
2943
+ for (const c of cands) { if (exists(c)) { target = c; break; } }
2944
+ }
2945
+ if (!exists(target) && !hasExt) {
2946
+ target = PosixPath.join(rootDir, 'index.html'); // SPA fallback
2947
+ }
2948
+ if (!exists(target)) {
2949
+ return new Response(
2950
+ `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
2951
+ { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
2952
+ );
2953
+ }
2954
+
2955
+ let body = readText(target);
2956
+ if (body === null) body = '';
2957
+ if (/\.html?$/i.test(target)) {
2958
+ body = injectPreviewExtras(body, importMap);
2959
+ } else if (isPreviewScriptPath(target)) {
2960
+ try {
2961
+ const rm = getRuntimeModule();
2962
+ if (rm && typeof rm.transpileForBrowser === 'function') {
2963
+ body = rm.transpileForBrowser(body, target);
2964
+ }
2965
+ } catch (_) {}
2966
+ }
2967
+
2968
+ return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
2969
+ };
2970
+
2971
+ const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
2972
+ return portTable.registerServer(port, {
2973
+ server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
2974
+ fetch: handler,
2975
+ name: 'code-lab-serve',
2976
+ pid,
2977
+ root: rootDir
2978
+ });
2979
+ }
2980
+
2981
+ // Common dev-server commands that cannot run inside the virtual runtime are
2982
+ // transparently redirected to the built-in preview server.
2983
+ const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
2984
+
2985
+ function tryDevScriptFallback(scriptName, cmd, ctx) {
2986
+ if (!PREVIEW_TOOL_RE.test(cmd)) return null;
2987
+ // Only fall back when the referenced tool is not actually installed.
2988
+ const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
2989
+ const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
2990
+ if (ctx.vfs.existsSync(binPath)) return null;
2991
+ const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
2992
+ const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
2993
+ const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
2994
+ const entry = registerPreviewServer(ctx, ctx.cwd, port);
2995
+ if (!entry) return null;
2996
+ return {
2997
+ code: 0,
2998
+ 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`,
2999
+ stderr: ''
3000
+ };
3001
+ }
3002
+
2610
3003
  function evaluatePosixTest(args, ctx) {
2611
3004
  const cleanArgs = [...args];
2612
3005
  if (cleanArgs.length > 0 && cleanArgs[cleanArgs.length - 1] === ']') {
@@ -5105,7 +5498,8 @@
5105
5498
  stdout += ' date, sleep, clear Date, delay, terminal screen control\n';
5106
5499
  stdout += ' history, ps, jobs, kill Process and job management\n';
5107
5500
  stdout += ' git [status diff log] Built-in version control\n';
5108
- stdout += ' node, bun, npm, npx, bunx CLI runtime and package shims\n';
5501
+ stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
5502
+ stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
5109
5503
  stdout += ' ports, curl Port table inspection & HTTP requests\n';
5110
5504
  return { code: 0, stdout, stderr: '' };
5111
5505
  },
@@ -5290,26 +5684,25 @@
5290
5684
 
5291
5685
  if (sub === 'install' || sub === 'i' || sub === 'ci') {
5292
5686
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5687
+ const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
5293
5688
  if (pkgs.length === 0) {
5294
5689
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5295
- const deps = Object.keys(pkgData.dependencies || {});
5296
- const results = [];
5297
- for (const p of deps) results.push(await installPackage(p, ctx));
5298
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5299
- return { code: 0, stdout: deps.length === 0 ? 'up to date\n' : `installed ${deps.length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5690
+ const deps = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
5691
+ if (deps.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
5692
+ return await runInstallTranscript(deps, ctx, { manager: 'bun', header: 'bun install v1.1.20 (1.1.20)' });
5300
5693
  }
5301
- const results = [];
5302
- for (const p of pkgs) results.push(await installPackage(p, ctx));
5303
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5304
- return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5694
+ return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
5305
5695
  }
5306
5696
 
5307
5697
  if (sub === 'add') {
5308
- const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5309
- const results = [];
5310
- for (const p of pkgs) results.push(await installPackage(p, ctx));
5311
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5312
- return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5698
+ let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5699
+ const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
5700
+ if (pkgs.length === 0) {
5701
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5702
+ pkgs = Object.keys(pkgData.dependencies || {});
5703
+ }
5704
+ if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
5705
+ return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
5313
5706
  }
5314
5707
 
5315
5708
  if (sub === 'remove' || sub === 'rm') {
@@ -5469,22 +5862,14 @@
5469
5862
  }
5470
5863
 
5471
5864
  if (sub === 'i' || sub === 'install' || sub === 'add') {
5472
- const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5865
+ let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5866
+ const dev = args.some(a => a === '-D' || a === '--save-dev' || a === '--dev');
5473
5867
  if (pkgs.length === 0) {
5474
5868
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5475
- const results = [];
5476
- for (const p of Object.keys(pkgData.dependencies || {})) {
5477
- results.push(await installPackage(p, ctx));
5478
- }
5479
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5480
- return { code: 0, stdout: 'up to date\n', stderr: warning ? `npm warn ${warning}\n` : '' };
5869
+ pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
5870
+ if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
5481
5871
  }
5482
- const results = [];
5483
- for (const p of pkgs) {
5484
- results.push(await installPackage(p, ctx));
5485
- }
5486
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5487
- return { code: 0, stdout: `added ${results.filter(r => r && r.name).length} package(s) in 0.1s\n`, stderr: warning ? `npm warn ${warning}\n` : '' };
5872
+ return await runInstallTranscript(pkgs, ctx, { manager: 'npm', dev, header: 'npm install v10.2.0' });
5488
5873
  }
5489
5874
 
5490
5875
  if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
@@ -5536,6 +5921,123 @@
5536
5921
  return await this.npx(args, ctx);
5537
5922
  },
5538
5923
 
5924
+ async pnpm(args, ctx) {
5925
+ if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
5926
+ return {
5927
+ code: 0,
5928
+ 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',
5929
+ stderr: ''
5930
+ };
5931
+ }
5932
+ const sub = args[0];
5933
+ if (sub === '--version' || sub === '-v') {
5934
+ return { code: 0, stdout: '9.0.0\n', stderr: '' };
5935
+ }
5936
+ const dev = args.some((a) => a === '-D' || a === '--save-dev' || a === '--dev' || a === '-d');
5937
+
5938
+ if (sub === 'init') {
5939
+ const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
5940
+ if (!ctx.vfs.existsSync(pkgPath)) {
5941
+ ctx.vfs.writeFileSync(pkgPath, JSON.stringify({
5942
+ name: PosixPath.basename(ctx.cwd) || 'app',
5943
+ version: '1.0.0',
5944
+ main: 'index.js',
5945
+ scripts: { test: 'echo "Error: no test specified" && exit 1' }
5946
+ }, null, 2) + '\n');
5947
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', pkgPath);
5948
+ }
5949
+ return { code: 0, stdout: 'Wrote to ' + pkgPath + '\n', stderr: '' };
5950
+ }
5951
+
5952
+ if (sub === 'install' || sub === 'i' || sub === 'add') {
5953
+ let pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
5954
+ if (pkgs.length === 0) {
5955
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5956
+ pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
5957
+ if (pkgs.length === 0) return { code: 0, stdout: 'Already up to date\n', stderr: '' };
5958
+ }
5959
+ const verb = (sub === 'add') ? 'add' : 'install';
5960
+ return await runInstallTranscript(pkgs, ctx, { manager: 'pnpm', dev, header: `pnpm ${verb} v9.0.0` });
5961
+ }
5962
+
5963
+ if (sub === 'remove' || sub === 'rm' || sub === 'uninstall') {
5964
+ const pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
5965
+ for (const p of pkgs) uninstallPackage(p, ctx);
5966
+ return { code: 0, stdout: `removed ${pkgs.length} package(s)\n`, stderr: '' };
5967
+ }
5968
+
5969
+ if (sub === 'list' || sub === 'ls') {
5970
+ return { code: 0, stdout: listDependencies(ctx), stderr: '' };
5971
+ }
5972
+
5973
+ if (sub === 'run' || sub === 'run-script') {
5974
+ const scriptName = args[1];
5975
+ if (!scriptName) return { code: 1, stdout: '', stderr: 'pnpm: missing script name\n' };
5976
+ return await runPackageScript(scriptName, args.slice(2), ctx);
5977
+ }
5978
+
5979
+ if (sub === 'test') {
5980
+ return await runPackageScript('test', args.slice(1), ctx);
5981
+ }
5982
+
5983
+ if (sub === 'exec') {
5984
+ const cmd = args[1];
5985
+ if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
5986
+ const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
5987
+ if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
5988
+ return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
5989
+ }
5990
+
5991
+ if (sub === 'dlx') {
5992
+ return await this.npx(args.slice(1), ctx);
5993
+ }
5994
+
5995
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5996
+ if (pkgData.scripts && pkgData.scripts[sub]) {
5997
+ return await runPackageScript(sub, args.slice(1), ctx);
5998
+ }
5999
+
6000
+ return { code: 1, stdout: '', stderr: `ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Unknown command: "${sub}"\n` };
6001
+ },
6002
+
6003
+ async serve(args, ctx) {
6004
+ if (args[0] === '--help' || args[0] === '-h') {
6005
+ return {
6006
+ code: 0,
6007
+ 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',
6008
+ stderr: ''
6009
+ };
6010
+ }
6011
+ const rootArg = (() => {
6012
+ const positionals = [];
6013
+ for (let i = 0; i < args.length; i++) {
6014
+ const a = args[i];
6015
+ if (a === '--port' || a === '-p') { i++; continue; }
6016
+ if (a.startsWith('-')) continue;
6017
+ positionals.push(a);
6018
+ }
6019
+ return positionals[0];
6020
+ })();
6021
+ let port = 3000;
6022
+ for (let i = 0; i < args.length; i++) {
6023
+ if ((args[i] === '--port' || args[i] === '-p') && args[i + 1]) { port = Number(args[i + 1]) || port; i++; }
6024
+ else if (args[i].startsWith('--port=')) port = Number(args[i].split('=')[1]) || port;
6025
+ }
6026
+ const rootDir = ctx.resolvePath(rootArg || '.');
6027
+ if (!ctx.vfs.existsSync(rootDir)) {
6028
+ return { code: 1, stdout: '', stderr: `serve: ${rootArg}: No such file or directory\n` };
6029
+ }
6030
+ const entry = registerPreviewServer(ctx, rootDir, port);
6031
+ if (!entry) {
6032
+ return { code: 1, stdout: '', stderr: 'serve: no virtual port table available\n' };
6033
+ }
6034
+ return {
6035
+ code: 0,
6036
+ 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`,
6037
+ stderr: ''
6038
+ };
6039
+ },
6040
+
5539
6041
  // -----------------------------------------------------------------------
5540
6042
  // Port Table & HTTP Inspection: ports, curl
5541
6043
  // -----------------------------------------------------------------------