@innovatorved/code-lab 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/shell.esm.js CHANGED
@@ -2389,9 +2389,40 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2389
2389
  return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
2390
2390
  }
2391
2391
 
2392
+ function pickConditionalEntry(value) {
2393
+ if (typeof value === 'string') return value;
2394
+ // `exports` subpaths may be an array of fallbacks, e.g.
2395
+ // `"./shams": [{ "types": "...", "default": "./shams.js" }, "./shams.js"]`.
2396
+ if (Array.isArray(value)) {
2397
+ for (const item of value) {
2398
+ const picked = pickConditionalEntry(item);
2399
+ if (picked) return picked;
2400
+ }
2401
+ return null;
2402
+ }
2403
+ if (!value || typeof value !== 'object') return null;
2404
+ // This runtime executes CommonJS, so it prefers CJS-friendly conditions.
2405
+ for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
2406
+ if (value[key] !== undefined) {
2407
+ const picked = pickConditionalEntry(value[key]);
2408
+ if (picked) return picked;
2409
+ }
2410
+ }
2411
+ return null;
2412
+ }
2413
+
2392
2414
  function resolveEntryRelPath(pkgJson) {
2393
- let entry = pkgJson.main || pkgJson.module ||
2394
- (typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
2415
+ let entry = null;
2416
+ const exp = pkgJson && pkgJson.exports;
2417
+ if (typeof exp === 'string') {
2418
+ entry = exp;
2419
+ } else if (exp && typeof exp === 'object' && exp['.'] !== undefined) {
2420
+ entry = pickConditionalEntry(exp['.']);
2421
+ }
2422
+ if (!entry) {
2423
+ entry = pkgJson.main || pkgJson.module ||
2424
+ (typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
2425
+ }
2395
2426
  entry = String(entry).replace(/^[./]+/, '');
2396
2427
  return entry || 'index.js';
2397
2428
  }
@@ -2402,9 +2433,16 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2402
2433
 
2403
2434
  function extractRelativeSpecifiers(code) {
2404
2435
  const out = new Set();
2405
- const re = /(?:\brequire\s*\(\s*|\bimport\s+[\s\S]{0,120}?\bfrom\s*|\bimport\s*\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g;
2406
- let m;
2407
- while ((m = re.exec(code)) !== null) out.add(m[1]);
2436
+ const patterns = [
2437
+ /\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,
2438
+ /\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
2439
+ /\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
2440
+ /\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g
2441
+ ];
2442
+ for (const re of patterns) {
2443
+ let m;
2444
+ while ((m = re.exec(code)) !== null) out.add(m[1]);
2445
+ }
2408
2446
  return Array.from(out);
2409
2447
  }
2410
2448
 
@@ -2418,17 +2456,50 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2418
2456
  return parts.join('/');
2419
2457
  }
2420
2458
 
2459
+ // Small promise-based delay. Used only for CDN retry backoff; falls back to an
2460
+ // immediate resolve if `setTimeout` is unavailable in the host.
2461
+ function cdnBackoff(ms) {
2462
+ return new Promise((resolve) => {
2463
+ if (typeof setTimeout === 'function') setTimeout(resolve, ms);
2464
+ else resolve();
2465
+ });
2466
+ }
2467
+
2421
2468
  async function fetchTextFromCdn(fetchImpl, url) {
2422
- try {
2423
- const res = await fetchImpl(url);
2424
- if (!res) return null;
2425
- const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
2426
- if (!ok) return null;
2427
- if (typeof res.text === 'function') return await res.text();
2428
- return String(res.body != null ? res.body : '');
2429
- } catch (_) {
2430
- return null;
2469
+ // A single flaky jsDelivr response used to silently produce an *incomplete*
2470
+ // install (the module graph then failed at require-time). Retry transient
2471
+ // failures (network error, 429/408, 5xx) but treat 4xx as final.
2472
+ const maxAttempts = 3;
2473
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2474
+ try {
2475
+ const res = await fetchImpl(url);
2476
+ if (!res) {
2477
+ if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
2478
+ return null;
2479
+ }
2480
+ const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
2481
+ if (!ok) {
2482
+ const transient = res.status >= 500 || res.status === 429 || res.status === 408;
2483
+ if (transient && attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
2484
+ return null;
2485
+ }
2486
+ // jsDelivr answers a *directory* path (e.g. `/pkg@1/libcjs/`) with HTTP 200
2487
+ // and an HTML directory listing. Storing that as a module both corrupts the
2488
+ // package and later collides with the real directory (EISDIR).
2489
+ const contentType = (res.headers && typeof res.headers.get === 'function')
2490
+ ? (res.headers.get('content-type') || '')
2491
+ : '';
2492
+ const isHtmlUrl = /\.html?(?:[?#]|$)/i.test(url);
2493
+ if (/text\/html/i.test(contentType) && !isHtmlUrl) return null;
2494
+ const text = typeof res.text === 'function' ? await res.text() : String(res.body != null ? res.body : '');
2495
+ if (!isHtmlUrl && /^\s*(?:<!doctype\s+html|<html[\s>]|<head[\s>])/i.test(text)) return null;
2496
+ return text;
2497
+ } catch (_) {
2498
+ if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
2499
+ return null;
2500
+ }
2431
2501
  }
2502
+ return null;
2432
2503
  }
2433
2504
 
2434
2505
  async function resolvePackageMetadata(fetchImpl, name, range) {
@@ -2469,20 +2540,62 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2469
2540
  const entry = resolveEntryRelPath(meta);
2470
2541
  const files = [];
2471
2542
  const visited = new Set();
2472
- const queue = [entry];
2473
- while (queue.length > 0) {
2474
- const rel = stripRelPath(queue.shift());
2475
- if (!rel || visited.has(rel)) continue;
2476
- visited.add(rel);
2477
- const text = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`);
2478
- if (text === null) continue;
2479
- files.push({ rel, content: text });
2480
- const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
2481
- for (const spec of extractRelativeSpecifiers(text)) {
2482
- const target = normalizeRelPath(baseDir, spec);
2483
- for (const cand of [target, `${target}.js`, `${target}.json`, `${target}/index.js`]) {
2484
- const c = stripRelPath(cand);
2485
- if (c && !visited.has(c)) { queue.push(cand); break; }
2543
+ // Seed with the package entry plus any declared `exports` subpaths, so a
2544
+ // later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
2545
+ // A `main` may point at a *directory* (e.g. chalk: `"main": "source"`); Node
2546
+ // resolves that to `<dir>/index.<ext>`, so those candidates must be seeded
2547
+ // too or the package installs with only its manifest.
2548
+ const seed = [
2549
+ entry,
2550
+ `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`,
2551
+ `${entry}/index.js`, `${entry}/index.json`, `${entry}/index.mjs`, `${entry}/index.cjs`
2552
+ ];
2553
+ const expMap = meta.exports;
2554
+ if (expMap && typeof expMap === 'object') {
2555
+ // Seed *every* declared subpath. A low cap silently dropped the tail of
2556
+ // packages that list each file in `exports` (lit-html has 29 keys, so
2557
+ // `lit-html/is-server.js` was never fetched and `require` failed later).
2558
+ // Wildcard keys (`./*`) need no seeding — their files are reached through
2559
+ // the relative-require closure or fetched on demand.
2560
+ for (const key of Object.keys(expMap)) {
2561
+ if (key === '.' || key.slice(0, 2) !== './' || key.includes('*')) continue;
2562
+ const target = pickConditionalEntry(expMap[key]);
2563
+ if (target) seed.push(target);
2564
+ }
2565
+ }
2566
+ let frontier = seed;
2567
+ while (frontier.length > 0) {
2568
+ const batch = [];
2569
+ for (const raw of frontier) {
2570
+ const rel = stripRelPath(raw);
2571
+ // Directory targets (e.g. `exports["./lib/"] === "./libcjs/"`) must never
2572
+ // be fetched as files — that is what produced the EISDIR crash.
2573
+ if (!rel || rel.endsWith('/') || visited.has(rel)) continue;
2574
+ visited.add(rel);
2575
+ batch.push(rel);
2576
+ }
2577
+ frontier = [];
2578
+ if (batch.length === 0) break;
2579
+ const texts = await Promise.all(
2580
+ batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
2581
+ );
2582
+ for (let idx = 0; idx < batch.length; idx++) {
2583
+ const rel = batch[idx];
2584
+ const text = texts[idx];
2585
+ if (text === null) continue;
2586
+ files.push({ rel, content: text });
2587
+ const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
2588
+ for (const spec of extractRelativeSpecifiers(text)) {
2589
+ const target = normalizeRelPath(baseDir, spec);
2590
+ // Only guess extensions when the specifier omits one; non-existent
2591
+ // candidates 404 harmlessly.
2592
+ const cands = /\.[a-z0-9]+$/i.test(target)
2593
+ ? [target]
2594
+ : [target, `${target}.js`, `${target}.json`, `${target}.mjs`, `${target}.cjs`, `${target}/index.js`];
2595
+ for (const cand of cands) {
2596
+ const c = stripRelPath(cand);
2597
+ if (c && !visited.has(c)) frontier.push(cand);
2598
+ }
2486
2599
  }
2487
2600
  }
2488
2601
  }
@@ -2492,7 +2605,30 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2492
2605
  if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
2493
2606
  }
2494
2607
 
2495
- return { ok: true, version, entry, files, deps: Object.keys(meta.dependencies || {}) };
2608
+ // Declared dependencies plus non-optional peer dependencies (npm v7+ style),
2609
+ // so e.g. `npm install react-dom` also pulls in `react`. The *ranges* are
2610
+ // preserved (not just the names) so transitives resolve to the version the
2611
+ // parent actually asked for — e.g. chalk@4 needs ansi-styles@^4, which itself
2612
+ // needs color-convert. Resolving transitive names as "latest" silently breaks
2613
+ // the tree (ansi-styles@6 has no deps at all).
2614
+ const depSpecs = [];
2615
+ const depSeen = new Set();
2616
+ const declared = meta.dependencies || {};
2617
+ for (const depName of Object.keys(declared)) {
2618
+ if (depSeen.has(depName)) continue;
2619
+ depSeen.add(depName);
2620
+ depSpecs.push({ name: depName, range: declared[depName] || null });
2621
+ }
2622
+ const peerMeta = meta.peerDependenciesMeta || {};
2623
+ const peers = meta.peerDependencies || {};
2624
+ for (const peer of Object.keys(peers)) {
2625
+ if (peerMeta[peer] && peerMeta[peer].optional) continue;
2626
+ if (depSeen.has(peer)) continue;
2627
+ depSeen.add(peer);
2628
+ depSpecs.push({ name: peer, range: peers[peer] || null });
2629
+ }
2630
+
2631
+ return { ok: true, version, entry, files, deps: depSpecs, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
2496
2632
  }
2497
2633
 
2498
2634
  function installTargetDirs(ctx, name) {
@@ -2506,24 +2642,43 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2506
2642
  for (const dir of dirs) {
2507
2643
  ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
2508
2644
  for (const f of info.files) {
2645
+ if (!f || !f.rel || f.rel.endsWith('/')) continue;
2509
2646
  const full = PosixPath.join(dir, f.rel);
2647
+ // Never overwrite a directory with a file body (defensive: a stray
2648
+ // directory target would otherwise raise EISDIR).
2649
+ try {
2650
+ if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
2651
+ } catch (_) {}
2510
2652
  ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
2511
2653
  ctx.vfs.writeFileSync(full, f.content);
2512
2654
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
2513
2655
  }
2514
2656
  const modPkgPath = PosixPath.join(dir, 'package.json');
2515
2657
  const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
2658
+ if (info.pkgExports && typeof info.pkgExports === 'object') {
2659
+ const normalized = { '.': './' + (info.entry || 'index.js') };
2660
+ for (const key of Object.keys(info.pkgExports)) {
2661
+ if (key === '.' || key.indexOf('*') !== -1) continue;
2662
+ const target = pickConditionalEntry(info.pkgExports[key]);
2663
+ if (target) normalized[key] = target.charAt(0) === '.' ? target : './' + target;
2664
+ }
2665
+ modPkg.exports = normalized;
2666
+ }
2516
2667
  ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
2517
2668
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
2518
2669
  }
2519
2670
  }
2520
2671
 
2521
- async function installPackage(pkgSpec, ctx) {
2672
+ async function installPackage(pkgSpec, ctx, onLine, opts) {
2673
+ const options = (onLine && typeof onLine === 'object') ? onLine : (opts || {});
2674
+ const lineCb = (typeof onLine === 'function') ? onLine : (typeof options.onLine === 'function' ? options.onLine : null);
2675
+ const isDev = Boolean(options.dev);
2522
2676
  const { name: pkgName, range } = parsePackageSpec(pkgSpec);
2523
2677
  if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
2524
2678
 
2525
2679
  const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
2526
- if (!pkgData.dependencies) pkgData.dependencies = {};
2680
+ const depField = isDev ? 'devDependencies' : 'dependencies';
2681
+ if (!pkgData[depField]) pkgData[depField] = {};
2527
2682
 
2528
2683
  const fetchImpl = packageCtxFetch(ctx);
2529
2684
  const seen = (ctx.shell && ctx.shell._cdnSeen)
@@ -2549,28 +2704,90 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2549
2704
  });
2550
2705
  if (!warning) warning = info.reason;
2551
2706
  installed.push({ name: item.name, version: '0.0.0' });
2707
+ if (typeof lineCb === 'function') lineCb({ name: item.name, version: '0.0.0', offline: true });
2552
2708
  continue;
2553
2709
  }
2554
2710
 
2555
2711
  writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
2556
2712
  installed.push({ name: item.name, version: info.version || '1.0.0' });
2713
+ if (typeof lineCb === 'function') lineCb({ name: item.name, version: info.version || '1.0.0', deduped: Boolean(info.deduped) });
2557
2714
  if (item.direct) directVersion = info.version || null;
2558
2715
 
2559
2716
  for (const dep of (info.deps || [])) {
2560
- const parsed = parsePackageSpec(dep);
2561
- if (parsed.name && !requested.has(parsed.name)) {
2562
- requested.add(parsed.name);
2563
- queue.push({ name: parsed.name, range: null, direct: false });
2717
+ const depName = (dep && typeof dep === 'object') ? dep.name : parsePackageSpec(dep).name;
2718
+ const depRange = (dep && typeof dep === 'object') ? dep.range : parsePackageSpec(dep).range;
2719
+ if (depName && !requested.has(depName)) {
2720
+ requested.add(depName);
2721
+ queue.push({ name: depName, range: depRange || null, direct: false });
2564
2722
  }
2565
2723
  }
2566
2724
  }
2567
2725
 
2568
- pkgData.dependencies[pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData.dependencies[pkgName] || 'latest'));
2726
+ pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
2569
2727
  writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
2570
2728
 
2571
2729
  return { name: pkgName, ok: true, version: directVersion, installed, warning };
2572
2730
  }
2573
2731
 
2732
+ // Build a live install log: each line is streamed to the terminal as it
2733
+ // happens (when possible) and accumulated so the command can also return it.
2734
+ function createInstallEmitter(ctx, sink) {
2735
+ const stream = (ctx && typeof ctx.onStdout === 'function') ? ctx.onStdout : null;
2736
+ return function emit(text) {
2737
+ if (!text) return;
2738
+ sink.push(text);
2739
+ if (stream) stream(text);
2740
+ };
2741
+ }
2742
+
2743
+ function formatInstallLine(info) {
2744
+ if (!info || !info.name) return '';
2745
+ const suffix = info.offline ? ' (offline fallback)' : (info.deduped ? ' (deduped)' : '');
2746
+ return ` + ${info.name}@${info.version || '1.0.0'}${suffix}\n`;
2747
+ }
2748
+
2749
+ function countInstalledPackages(results) {
2750
+ const seen = new Set();
2751
+ for (const r of results) {
2752
+ if (!r) continue;
2753
+ if (r.name) seen.add(r.name);
2754
+ for (const p of (r.installed || [])) { if (p && p.name) seen.add(p.name); }
2755
+ }
2756
+ return seen.size;
2757
+ }
2758
+
2759
+ // Resolve + install a list of specs while printing a realistic transcript,
2760
+ // so `npm install` / `bun add` look like the real tools instead of a terse
2761
+ // "saved N package(s)".
2762
+ async function runInstallTranscript(pkgs, ctx, opts) {
2763
+ const options = opts || {};
2764
+ const manager = options.manager || 'bun';
2765
+ const header = options.header || (manager === 'npm' ? 'npm install v10.2.0' : 'bun add v1.1.20 (1.1.20)');
2766
+ const out = [];
2767
+ const emit = createInstallEmitter(ctx, out);
2768
+ const started = Date.now();
2769
+ emit(`${header}\n\nResolving dependencies...\n`);
2770
+ const results = [];
2771
+ for (const p of pkgs) {
2772
+ results.push(await installPackage(p, ctx, { onLine: (info) => emit(formatInstallLine(info)), dev: Boolean(options.dev) }));
2773
+ }
2774
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
2775
+ const count = countInstalledPackages(results);
2776
+ const ms = Date.now() - started;
2777
+ if (manager === 'npm') {
2778
+ emit(`\nadded ${count} package(s) in ${ms}ms\n`);
2779
+ } else if (manager === 'pnpm') {
2780
+ emit(`\nPackages: +${count}\n${'+'.repeat(Math.min(count, 40))}\nDone in ${ms}ms using pnpm v9.0.0\n`);
2781
+ } else {
2782
+ emit(`Saved lockfile\n\n${count} package(s) installed [${ms}ms]\n`);
2783
+ }
2784
+ return {
2785
+ code: 0,
2786
+ stdout: out.join(''),
2787
+ stderr: warning ? `${manager === 'npm' ? 'npm warn' : manager === 'pnpm' ? 'pnpm warn' : 'bun warn'} ${warning}\n` : ''
2788
+ };
2789
+ }
2790
+
2574
2791
  function uninstallPackage(pkgName, ctx) {
2575
2792
  const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
2576
2793
  let changed = false;
@@ -2622,9 +2839,269 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
2622
2839
  if (scriptArgs && scriptArgs.length > 0) {
2623
2840
  cmd += ' ' + scriptArgs.join(' ');
2624
2841
  }
2842
+ const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
2843
+ if (fallback) return fallback;
2625
2844
  return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
2626
2845
  }
2627
2846
 
2847
+ // ---------------------------------------------------------------------------
2848
+ // Built-in static preview server (`serve` / `npm run dev` fallback).
2849
+ //
2850
+ // Serves the virtual filesystem over a virtual port so the in-browser Web
2851
+ // Preview can render a project. `.ts/.tsx/.jsx` sources are transpiled to
2852
+ // browser-native ESM on the fly, and bare specifiers are resolved to jsDelivr
2853
+ // `+esm` builds through an injected import map — no bundler required.
2854
+ // ---------------------------------------------------------------------------
2855
+
2856
+ const CDN_ESM_BASE = 'https://cdn.jsdelivr.net/npm';
2857
+
2858
+ const PREVIEW_MIME = {
2859
+ '.html': 'text/html; charset=utf-8',
2860
+ '.htm': 'text/html; charset=utf-8',
2861
+ '.js': 'text/javascript; charset=utf-8',
2862
+ '.mjs': 'text/javascript; charset=utf-8',
2863
+ '.cjs': 'text/javascript; charset=utf-8',
2864
+ '.jsx': 'text/javascript; charset=utf-8',
2865
+ '.ts': 'text/javascript; charset=utf-8',
2866
+ '.tsx': 'text/javascript; charset=utf-8',
2867
+ '.css': 'text/css; charset=utf-8',
2868
+ '.json': 'application/json; charset=utf-8',
2869
+ '.map': 'application/json; charset=utf-8',
2870
+ '.svg': 'image/svg+xml',
2871
+ '.png': 'image/png',
2872
+ '.jpg': 'image/jpeg',
2873
+ '.jpeg': 'image/jpeg',
2874
+ '.gif': 'image/gif',
2875
+ '.webp': 'image/webp',
2876
+ '.ico': 'image/x-icon',
2877
+ '.txt': 'text/plain; charset=utf-8'
2878
+ };
2879
+
2880
+ function previewMimeFor(p) {
2881
+ const lower = String(p).toLowerCase();
2882
+ const dot = lower.lastIndexOf('.');
2883
+ if (dot === -1) return 'application/octet-stream';
2884
+ return PREVIEW_MIME[lower.slice(dot)] || 'application/octet-stream';
2885
+ }
2886
+
2887
+ function isPreviewScriptPath(p) {
2888
+ return /\.(?:[cm]?jsx?|tsx?)$/i.test(p) && !/\.d\.ts$/i.test(p);
2889
+ }
2890
+
2891
+ // Collect bare (non-relative) module specifiers referenced by a source file.
2892
+ function extractBareSpecifiers(code) {
2893
+ const out = new Set();
2894
+ const patterns = [
2895
+ /\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
2896
+ /\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
2897
+ /\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
2898
+ /\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g
2899
+ ];
2900
+ for (const re of patterns) {
2901
+ let m;
2902
+ while ((m = re.exec(code)) !== null) {
2903
+ const spec = m[1];
2904
+ if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.includes(':')) continue;
2905
+ out.add(spec);
2906
+ }
2907
+ }
2908
+ return Array.from(out);
2909
+ }
2910
+
2911
+ function normalizeVersionRange(range) {
2912
+ if (!range || typeof range !== 'string') return 'latest';
2913
+ const v = range.trim();
2914
+ if (!v || v === '*' || /^(?:latest|next|beta|canary)$/.test(v)) return 'latest';
2915
+ if (/^(?:file|link|workspace|portal|git|https?):/.test(v)) return 'latest';
2916
+ return v.replace(/\s+/g, '').replace(/^[v=\s]+/, '') || 'latest';
2917
+ }
2918
+
2919
+ function resolveBareVersion(vfs, rootDir, pkgName) {
2920
+ try {
2921
+ const modPkg = PosixPath.join(rootDir, 'node_modules', pkgName, 'package.json');
2922
+ if (vfs.existsSync(modPkg)) {
2923
+ const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
2924
+ if (parsed && parsed.version) return parsed.version;
2925
+ }
2926
+ } catch (_) {}
2927
+ try {
2928
+ for (const dir of [rootDir, '/workspace']) {
2929
+ const pkgPath = PosixPath.join(dir, 'package.json');
2930
+ if (!vfs.existsSync(pkgPath)) continue;
2931
+ const parsed = JSON.parse(vfs.readFileSync(pkgPath, 'utf8'));
2932
+ const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
2933
+ if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
2934
+ }
2935
+ } catch (_) {}
2936
+ return 'latest';
2937
+ }
2938
+
2939
+ function cdnEsmUrl(pkgName, version, subpath) {
2940
+ const base = `${CDN_ESM_BASE}/${pkgName}@${version}`;
2941
+ const sub = subpath ? '/' + String(subpath).replace(/^\/+|\/+$/g, '') : '';
2942
+ return `${base}${sub}/+esm`;
2943
+ }
2944
+
2945
+ function buildPreviewImportMap(vfs, rootDir, specifiers) {
2946
+ const imports = {};
2947
+ for (const spec of specifiers) {
2948
+ const parts = String(spec).split('/');
2949
+ const pkgName = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
2950
+ if (!pkgName) continue;
2951
+ const subpath = spec.slice(pkgName.length).replace(/^\/+/, '');
2952
+ const version = resolveBareVersion(vfs, rootDir, pkgName);
2953
+ imports[spec] = cdnEsmUrl(pkgName, version, subpath || undefined);
2954
+ }
2955
+ return imports;
2956
+ }
2957
+
2958
+ function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
2959
+ const scripts = [];
2960
+ const walk = (dir, depth) => {
2961
+ if (depth > 8 || scripts.length >= maxFiles) return;
2962
+ let entries = [];
2963
+ try { entries = vfs.readdirSync(dir); } catch (_) { return; }
2964
+ for (const name of entries) {
2965
+ if (name === 'node_modules' || name.startsWith('.')) continue;
2966
+ const full = PosixPath.join(dir, name);
2967
+ let st;
2968
+ try { st = vfs.statSync(full); } catch (_) { continue; }
2969
+ const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
2970
+ if (dirFlag) {
2971
+ walk(full, depth + 1);
2972
+ } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
2973
+ try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
2974
+ }
2975
+ }
2976
+ };
2977
+ walk(rootDir, 0);
2978
+ return scripts;
2979
+ }
2980
+
2981
+ function injectPreviewExtras(html, importMap) {
2982
+ let out = html;
2983
+ const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
2984
+ if (/<head[^>]*>/i.test(out)) {
2985
+ out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
2986
+ } else {
2987
+ out = importMapTag + '\n' + out;
2988
+ }
2989
+ const shim = '<script>window.__CODELAB_PREVIEW__ = true;</script>';
2990
+ if (/<\/body>/i.test(out)) out = out.replace(/<\/body>/i, `${shim}\n</body>`);
2991
+ else out = out + '\n' + shim;
2992
+ return out;
2993
+ }
2994
+
2995
+ function registerPreviewServer(ctx, rootDir, preferredPort) {
2996
+ const portTable = ctx.shell && ctx.shell.portTable;
2997
+ if (!portTable || typeof portTable.registerServer !== 'function') return null;
2998
+
2999
+ let port = Number(preferredPort) || 3000;
3000
+ const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
3001
+ while (taken.has(port)) port++;
3002
+
3003
+ const specifiers = new Set();
3004
+ for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
3005
+ for (const s of extractBareSpecifiers(content)) specifiers.add(s);
3006
+ }
3007
+ const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
3008
+
3009
+ const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
3010
+ const isDir = (p) => {
3011
+ try {
3012
+ const st = ctx.vfs.statSync(p);
3013
+ return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
3014
+ } catch (_) { return false; }
3015
+ };
3016
+ const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
3017
+
3018
+ const handler = async (request) => {
3019
+ let pathname = '/';
3020
+ try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
3021
+ const rel = pathname.replace(/^\/+/, '');
3022
+ let target = PosixPath.join(rootDir, rel);
3023
+ const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
3024
+
3025
+ if (!rel || pathname.endsWith('/') || isDir(target)) {
3026
+ target = PosixPath.join(target, 'index.html');
3027
+ }
3028
+ if (!exists(target) && !hasExt) {
3029
+ // Resolve extensionless module specifiers (e.g. `./components/Counter`)
3030
+ // the way a bundler / dev server would.
3031
+ const cands = [
3032
+ target + '.tsx', target + '.ts', target + '.jsx', target + '.js',
3033
+ target + '.mjs', target + '.cjs',
3034
+ PosixPath.join(target, 'index.tsx'), PosixPath.join(target, 'index.ts'),
3035
+ PosixPath.join(target, 'index.jsx'), PosixPath.join(target, 'index.js')
3036
+ ];
3037
+ for (const c of cands) { if (exists(c)) { target = c; break; } }
3038
+ }
3039
+ if (!exists(target) && !hasExt) {
3040
+ target = PosixPath.join(rootDir, 'index.html'); // SPA fallback
3041
+ }
3042
+ if (!exists(target)) {
3043
+ return new Response(
3044
+ `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
3045
+ { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
3046
+ );
3047
+ }
3048
+
3049
+ let body = readText(target);
3050
+ if (body === null) body = '';
3051
+ if (/\.html?$/i.test(target)) {
3052
+ body = injectPreviewExtras(body, importMap);
3053
+ } else if (isPreviewScriptPath(target)) {
3054
+ try {
3055
+ const rm = getRuntimeModule();
3056
+ if (rm && typeof rm.transpileForBrowser === 'function') {
3057
+ body = rm.transpileForBrowser(body, target);
3058
+ }
3059
+ } catch (_) {}
3060
+ }
3061
+
3062
+ return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
3063
+ };
3064
+
3065
+ const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
3066
+ return portTable.registerServer(port, {
3067
+ server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
3068
+ fetch: handler,
3069
+ name: 'code-lab-serve',
3070
+ pid,
3071
+ root: rootDir
3072
+ });
3073
+ }
3074
+
3075
+ // Common dev-server commands that cannot run inside the virtual runtime are
3076
+ // transparently redirected to the built-in preview server.
3077
+ const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
3078
+ // The same tools, when typed directly at the prompt (`ng serve`, `vite`).
3079
+ // `serve` is omitted: it is a first-class builtin shell command.
3080
+ const DIRECT_DEV_TOOL_RE = /^(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|http-server)$/;
3081
+
3082
+ function tryDevScriptFallback(scriptName, cmd, ctx, opts) {
3083
+ if (!PREVIEW_TOOL_RE.test(cmd)) return null;
3084
+ // Only fall back when the referenced tool is not actually installed.
3085
+ const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
3086
+ const force = Boolean(opts && opts.force);
3087
+ const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
3088
+ if (!force && ctx.vfs.existsSync(binPath)) return null;
3089
+ const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
3090
+ const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
3091
+ const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
3092
+ const rootDir = typeof ctx.resolvePath === 'function' ? ctx.resolvePath('.') : (ctx.cwd || '/workspace');
3093
+ const entry = registerPreviewServer(ctx, rootDir, port);
3094
+ if (!entry) return null;
3095
+ const note = force
3096
+ ? `${bin} is a native dev server and cannot execute inside this virtual runtime — using the CodeLab preview server instead.`
3097
+ : `${bin} is not available in this virtual runtime — using the CodeLab preview server instead.`;
3098
+ return {
3099
+ code: 0,
3100
+ stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${note}\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
3101
+ stderr: ''
3102
+ };
3103
+ }
3104
+
2628
3105
  function evaluatePosixTest(args, ctx) {
2629
3106
  const cleanArgs = [...args];
2630
3107
  if (cleanArgs.length > 0 && cleanArgs[cleanArgs.length - 1] === ']') {
@@ -5123,7 +5600,8 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5123
5600
  stdout += ' date, sleep, clear Date, delay, terminal screen control\n';
5124
5601
  stdout += ' history, ps, jobs, kill Process and job management\n';
5125
5602
  stdout += ' git [status diff log] Built-in version control\n';
5126
- stdout += ' node, bun, npm, npx, bunx CLI runtime and package shims\n';
5603
+ stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
5604
+ stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
5127
5605
  stdout += ' ports, curl Port table inspection & HTTP requests\n';
5128
5606
  return { code: 0, stdout, stderr: '' };
5129
5607
  },
@@ -5308,26 +5786,25 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5308
5786
 
5309
5787
  if (sub === 'install' || sub === 'i' || sub === 'ci') {
5310
5788
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5789
+ const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
5311
5790
  if (pkgs.length === 0) {
5312
5791
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5313
- const deps = Object.keys(pkgData.dependencies || {});
5314
- const results = [];
5315
- for (const p of deps) results.push(await installPackage(p, ctx));
5316
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5317
- return { code: 0, stdout: deps.length === 0 ? 'up to date\n' : `installed ${deps.length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5792
+ const deps = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
5793
+ if (deps.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
5794
+ return await runInstallTranscript(deps, ctx, { manager: 'bun', header: 'bun install v1.1.20 (1.1.20)' });
5318
5795
  }
5319
- const results = [];
5320
- for (const p of pkgs) results.push(await installPackage(p, ctx));
5321
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5322
- return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5796
+ return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
5323
5797
  }
5324
5798
 
5325
5799
  if (sub === 'add') {
5326
- const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5327
- const results = [];
5328
- for (const p of pkgs) results.push(await installPackage(p, ctx));
5329
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5330
- return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5800
+ let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5801
+ const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
5802
+ if (pkgs.length === 0) {
5803
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5804
+ pkgs = Object.keys(pkgData.dependencies || {});
5805
+ }
5806
+ if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
5807
+ return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
5331
5808
  }
5332
5809
 
5333
5810
  if (sub === 'remove' || sub === 'rm') {
@@ -5487,22 +5964,14 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5487
5964
  }
5488
5965
 
5489
5966
  if (sub === 'i' || sub === 'install' || sub === 'add') {
5490
- const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5967
+ let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5968
+ const dev = args.some(a => a === '-D' || a === '--save-dev' || a === '--dev');
5491
5969
  if (pkgs.length === 0) {
5492
5970
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5493
- const results = [];
5494
- for (const p of Object.keys(pkgData.dependencies || {})) {
5495
- results.push(await installPackage(p, ctx));
5496
- }
5497
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5498
- return { code: 0, stdout: 'up to date\n', stderr: warning ? `npm warn ${warning}\n` : '' };
5499
- }
5500
- const results = [];
5501
- for (const p of pkgs) {
5502
- results.push(await installPackage(p, ctx));
5971
+ pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
5972
+ if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
5503
5973
  }
5504
- const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5505
- return { code: 0, stdout: `added ${results.filter(r => r && r.name).length} package(s) in 0.1s\n`, stderr: warning ? `npm warn ${warning}\n` : '' };
5974
+ return await runInstallTranscript(pkgs, ctx, { manager: 'npm', dev, header: 'npm install v10.2.0' });
5506
5975
  }
5507
5976
 
5508
5977
  if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
@@ -5554,6 +6023,123 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
5554
6023
  return await this.npx(args, ctx);
5555
6024
  },
5556
6025
 
6026
+ async pnpm(args, ctx) {
6027
+ if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
6028
+ return {
6029
+ code: 0,
6030
+ 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',
6031
+ stderr: ''
6032
+ };
6033
+ }
6034
+ const sub = args[0];
6035
+ if (sub === '--version' || sub === '-v') {
6036
+ return { code: 0, stdout: '9.0.0\n', stderr: '' };
6037
+ }
6038
+ const dev = args.some((a) => a === '-D' || a === '--save-dev' || a === '--dev' || a === '-d');
6039
+
6040
+ if (sub === 'init') {
6041
+ const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
6042
+ if (!ctx.vfs.existsSync(pkgPath)) {
6043
+ ctx.vfs.writeFileSync(pkgPath, JSON.stringify({
6044
+ name: PosixPath.basename(ctx.cwd) || 'app',
6045
+ version: '1.0.0',
6046
+ main: 'index.js',
6047
+ scripts: { test: 'echo "Error: no test specified" && exit 1' }
6048
+ }, null, 2) + '\n');
6049
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', pkgPath);
6050
+ }
6051
+ return { code: 0, stdout: 'Wrote to ' + pkgPath + '\n', stderr: '' };
6052
+ }
6053
+
6054
+ if (sub === 'install' || sub === 'i' || sub === 'add') {
6055
+ let pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
6056
+ if (pkgs.length === 0) {
6057
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
6058
+ pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
6059
+ if (pkgs.length === 0) return { code: 0, stdout: 'Already up to date\n', stderr: '' };
6060
+ }
6061
+ const verb = (sub === 'add') ? 'add' : 'install';
6062
+ return await runInstallTranscript(pkgs, ctx, { manager: 'pnpm', dev, header: `pnpm ${verb} v9.0.0` });
6063
+ }
6064
+
6065
+ if (sub === 'remove' || sub === 'rm' || sub === 'uninstall') {
6066
+ const pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
6067
+ for (const p of pkgs) uninstallPackage(p, ctx);
6068
+ return { code: 0, stdout: `removed ${pkgs.length} package(s)\n`, stderr: '' };
6069
+ }
6070
+
6071
+ if (sub === 'list' || sub === 'ls') {
6072
+ return { code: 0, stdout: listDependencies(ctx), stderr: '' };
6073
+ }
6074
+
6075
+ if (sub === 'run' || sub === 'run-script') {
6076
+ const scriptName = args[1];
6077
+ if (!scriptName) return { code: 1, stdout: '', stderr: 'pnpm: missing script name\n' };
6078
+ return await runPackageScript(scriptName, args.slice(2), ctx);
6079
+ }
6080
+
6081
+ if (sub === 'test') {
6082
+ return await runPackageScript('test', args.slice(1), ctx);
6083
+ }
6084
+
6085
+ if (sub === 'exec') {
6086
+ const cmd = args[1];
6087
+ if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
6088
+ const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
6089
+ if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
6090
+ return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
6091
+ }
6092
+
6093
+ if (sub === 'dlx') {
6094
+ return await this.npx(args.slice(1), ctx);
6095
+ }
6096
+
6097
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
6098
+ if (pkgData.scripts && pkgData.scripts[sub]) {
6099
+ return await runPackageScript(sub, args.slice(1), ctx);
6100
+ }
6101
+
6102
+ return { code: 1, stdout: '', stderr: `ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Unknown command: "${sub}"\n` };
6103
+ },
6104
+
6105
+ async serve(args, ctx) {
6106
+ if (args[0] === '--help' || args[0] === '-h') {
6107
+ return {
6108
+ code: 0,
6109
+ 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',
6110
+ stderr: ''
6111
+ };
6112
+ }
6113
+ const rootArg = (() => {
6114
+ const positionals = [];
6115
+ for (let i = 0; i < args.length; i++) {
6116
+ const a = args[i];
6117
+ if (a === '--port' || a === '-p') { i++; continue; }
6118
+ if (a.startsWith('-')) continue;
6119
+ positionals.push(a);
6120
+ }
6121
+ return positionals[0];
6122
+ })();
6123
+ let port = 3000;
6124
+ for (let i = 0; i < args.length; i++) {
6125
+ if ((args[i] === '--port' || args[i] === '-p') && args[i + 1]) { port = Number(args[i + 1]) || port; i++; }
6126
+ else if (args[i].startsWith('--port=')) port = Number(args[i].split('=')[1]) || port;
6127
+ }
6128
+ const rootDir = ctx.resolvePath(rootArg || '.');
6129
+ if (!ctx.vfs.existsSync(rootDir)) {
6130
+ return { code: 1, stdout: '', stderr: `serve: ${rootArg}: No such file or directory\n` };
6131
+ }
6132
+ const entry = registerPreviewServer(ctx, rootDir, port);
6133
+ if (!entry) {
6134
+ return { code: 1, stdout: '', stderr: 'serve: no virtual port table available\n' };
6135
+ }
6136
+ return {
6137
+ code: 0,
6138
+ 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`,
6139
+ stderr: ''
6140
+ };
6141
+ },
6142
+
5557
6143
  // -----------------------------------------------------------------------
5558
6144
  // Port Table & HTTP Inspection: ports, curl
5559
6145
  // -----------------------------------------------------------------------
@@ -6610,6 +7196,13 @@ const _root = typeof globalThis !== 'undefined' ? globalThis : typeof window !==
6610
7196
  Object.assign(context.env, this.env);
6611
7197
  context.cwd = this.cwd;
6612
7198
  }
7199
+ } else if (DIRECT_DEV_TOOL_RE.test(cmdName)) {
7200
+ // A native dev server (vite/ng/astro/…) typed directly. It cannot run in
7201
+ // this runtime — whether or not it was installed — so route it to the
7202
+ // built-in preview server rather than reporting a misleading "command
7203
+ // not found".
7204
+ const fb = tryDevScriptFallback(cmdName, [cmdName, ...args].join(' '), cmdCtx, { force: true });
7205
+ res = fb || { code: 127, stdout: '', stderr: `shell: ${cmdName}: command not found\n` };
6613
7206
  } else if (typeof this.options.onProcessSpawn === 'function') {
6614
7207
  const spawned = await this.options.onProcessSpawn(cmdName, args, {
6615
7208
  cwd: this.cwd,