@innovatorved/code-lab 0.1.3 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +2 -1
- package/README.md +4 -2
- package/dist/code-lab.css +49 -0
- package/dist/code-lab.d.ts +2 -1
- package/dist/code-lab.esm.js +1227 -67
- package/dist/code-lab.js +1227 -67
- package/dist/runtime.d.ts +1 -1
- package/dist/runtime.esm.js +377 -21
- package/dist/runtime.js +377 -21
- package/dist/shell.esm.js +766 -39
- package/dist/shell.js +766 -39
- package/package.json +6 -2
- package/src/code-lab.css +49 -0
- package/src/runtime.js +377 -21
- package/src/runtime.ts +382 -22
- package/src/shell.js +766 -39
- package/src/shell.ts +766 -39
- package/src/workbench.js +84 -7
- package/src/workbench.ts +84 -7
package/src/shell.ts
CHANGED
|
@@ -2386,38 +2386,362 @@ function __initShellModule(root: any) {
|
|
|
2386
2386
|
} catch (_) {}
|
|
2387
2387
|
}
|
|
2388
2388
|
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2389
|
+
// ---------------------------------------------------------------------------
|
|
2390
|
+
// Real npm package installation via the jsDelivr CDN
|
|
2391
|
+
// ---------------------------------------------------------------------------
|
|
2392
|
+
const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
|
|
2393
|
+
|
|
2394
|
+
// Minimal offline registry, used only when the CDN is unreachable so common
|
|
2395
|
+
// demos still resolve without network access.
|
|
2396
|
+
const OFFLINE_PACKAGE_FALLBACKS = {
|
|
2397
|
+
'is-even': 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n',
|
|
2398
|
+
'tiny-invariant': 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n',
|
|
2399
|
+
'lodash': 'module.exports = { isArray: Array.isArray, isObject: function (v) { return v !== null && typeof v === "object"; } };\n',
|
|
2400
|
+
'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'
|
|
2401
|
+
};
|
|
2393
2402
|
|
|
2394
|
-
|
|
2395
|
-
if (
|
|
2396
|
-
|
|
2397
|
-
|
|
2403
|
+
function packageCtxFetch(ctx) {
|
|
2404
|
+
if (ctx && ctx.shell && ctx.shell.options && typeof ctx.shell.options.fetchImpl === 'function') {
|
|
2405
|
+
return ctx.shell.options.fetchImpl;
|
|
2406
|
+
}
|
|
2407
|
+
if (typeof fetch === 'function') return fetch.bind(globalThis);
|
|
2408
|
+
return null;
|
|
2409
|
+
}
|
|
2398
2410
|
|
|
2399
|
-
|
|
2400
|
-
const
|
|
2401
|
-
if (!
|
|
2411
|
+
function parsePackageSpec(spec) {
|
|
2412
|
+
const raw = String(spec || '').trim();
|
|
2413
|
+
if (!raw) return { name: '', range: null };
|
|
2414
|
+
if (raw.startsWith('@')) {
|
|
2415
|
+
const at = raw.indexOf('@', 1);
|
|
2416
|
+
if (at === -1) return { name: raw, range: null };
|
|
2417
|
+
return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
|
|
2418
|
+
}
|
|
2419
|
+
const at = raw.indexOf('@');
|
|
2420
|
+
if (at <= 0) return { name: raw, range: null };
|
|
2421
|
+
return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
|
|
2422
|
+
}
|
|
2402
2423
|
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2424
|
+
function pickConditionalEntry(value) {
|
|
2425
|
+
if (typeof value === 'string') return value;
|
|
2426
|
+
if (!value || typeof value !== 'object') return null;
|
|
2427
|
+
// This runtime executes CommonJS, so it prefers CJS-friendly conditions.
|
|
2428
|
+
for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
|
|
2429
|
+
if (value[key] !== undefined) {
|
|
2430
|
+
const picked = pickConditionalEntry(value[key]);
|
|
2431
|
+
if (picked) return picked;
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
2434
|
+
return null;
|
|
2435
|
+
}
|
|
2436
|
+
|
|
2437
|
+
function resolveEntryRelPath(pkgJson) {
|
|
2438
|
+
let entry = null;
|
|
2439
|
+
const exp = pkgJson && pkgJson.exports;
|
|
2440
|
+
if (typeof exp === 'string') {
|
|
2441
|
+
entry = exp;
|
|
2442
|
+
} else if (exp && typeof exp === 'object' && exp['.'] !== undefined) {
|
|
2443
|
+
entry = pickConditionalEntry(exp['.']);
|
|
2444
|
+
}
|
|
2445
|
+
if (!entry) {
|
|
2446
|
+
entry = pkgJson.main || pkgJson.module ||
|
|
2447
|
+
(typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
|
|
2448
|
+
}
|
|
2449
|
+
entry = String(entry).replace(/^[./]+/, '');
|
|
2450
|
+
return entry || 'index.js';
|
|
2451
|
+
}
|
|
2452
|
+
|
|
2453
|
+
function stripRelPath(rel) {
|
|
2454
|
+
return String(rel || '').replace(/^[./]+/, '');
|
|
2455
|
+
}
|
|
2456
|
+
|
|
2457
|
+
function extractRelativeSpecifiers(code) {
|
|
2458
|
+
const out = new Set();
|
|
2459
|
+
const patterns = [
|
|
2460
|
+
/\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2461
|
+
/\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2462
|
+
/\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2463
|
+
/\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g
|
|
2464
|
+
];
|
|
2465
|
+
for (const re of patterns) {
|
|
2466
|
+
let m;
|
|
2467
|
+
while ((m = re.exec(code)) !== null) out.add(m[1]);
|
|
2468
|
+
}
|
|
2469
|
+
return Array.from(out);
|
|
2470
|
+
}
|
|
2471
|
+
|
|
2472
|
+
function normalizeRelPath(baseDir, rel) {
|
|
2473
|
+
const parts = String(baseDir || '').split('/').filter(Boolean);
|
|
2474
|
+
for (const seg of String(rel).split('/')) {
|
|
2475
|
+
if (!seg || seg === '.') continue;
|
|
2476
|
+
if (seg === '..') parts.pop();
|
|
2477
|
+
else parts.push(seg);
|
|
2478
|
+
}
|
|
2479
|
+
return parts.join('/');
|
|
2480
|
+
}
|
|
2481
|
+
|
|
2482
|
+
async function fetchTextFromCdn(fetchImpl, url) {
|
|
2483
|
+
try {
|
|
2484
|
+
const res = await fetchImpl(url);
|
|
2485
|
+
if (!res) return null;
|
|
2486
|
+
const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
|
|
2487
|
+
if (!ok) return null;
|
|
2488
|
+
if (typeof res.text === 'function') return await res.text();
|
|
2489
|
+
return String(res.body != null ? res.body : '');
|
|
2490
|
+
} catch (_) {
|
|
2491
|
+
return null;
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
|
|
2495
|
+
async function resolvePackageMetadata(fetchImpl, name, range) {
|
|
2496
|
+
const urls = range
|
|
2497
|
+
? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
|
|
2498
|
+
: [`${CDN_NPM_BASE}/${name}/package.json`];
|
|
2499
|
+
for (const url of urls) {
|
|
2500
|
+
const text = await fetchTextFromCdn(fetchImpl, url);
|
|
2501
|
+
if (!text) continue;
|
|
2502
|
+
try {
|
|
2503
|
+
const parsed = JSON.parse(text);
|
|
2504
|
+
if (parsed && parsed.version) return parsed;
|
|
2505
|
+
} catch (_) {}
|
|
2506
|
+
}
|
|
2507
|
+
return null;
|
|
2508
|
+
}
|
|
2509
|
+
|
|
2510
|
+
// Download a package's entry module, its relative submodules and record its
|
|
2511
|
+
// declared dependencies so the caller can resolve them transitively.
|
|
2512
|
+
async function downloadPackageFiles(fetchImpl, name, range, seen) {
|
|
2513
|
+
const meta = await resolvePackageMetadata(fetchImpl, name, range);
|
|
2514
|
+
if (!meta) {
|
|
2515
|
+
const fallback = OFFLINE_PACKAGE_FALLBACKS[name];
|
|
2516
|
+
if (fallback) {
|
|
2517
|
+
const v = range ? range.replace(/^[\^~>=<\s]+/, '') || '1.0.0' : '1.0.0';
|
|
2518
|
+
return { ok: true, offline: true, version: v, entry: 'index.js', files: [{ rel: 'index.js', content: fallback }], deps: [] };
|
|
2519
|
+
}
|
|
2520
|
+
return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
|
|
2521
|
+
}
|
|
2522
|
+
|
|
2523
|
+
const version = meta.version;
|
|
2524
|
+
const key = `${name}@${version}`;
|
|
2525
|
+
if (seen.has(key)) {
|
|
2526
|
+
return { ok: true, deduped: true, version, entry: resolveEntryRelPath(meta), files: [], deps: [] };
|
|
2527
|
+
}
|
|
2528
|
+
seen.add(key);
|
|
2529
|
+
|
|
2530
|
+
const entry = resolveEntryRelPath(meta);
|
|
2531
|
+
const files = [];
|
|
2532
|
+
const visited = new Set();
|
|
2533
|
+
// Seed with the package entry plus any declared `exports` subpaths, so a
|
|
2534
|
+
// later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
|
|
2535
|
+
const seed = [entry, `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`];
|
|
2536
|
+
const expMap = meta.exports;
|
|
2537
|
+
if (expMap && typeof expMap === 'object') {
|
|
2538
|
+
let subCount = 0;
|
|
2539
|
+
for (const key of Object.keys(expMap)) {
|
|
2540
|
+
if (key === '.' || key.slice(0, 2) !== './' || subCount >= 25) continue;
|
|
2541
|
+
const target = pickConditionalEntry(expMap[key]);
|
|
2542
|
+
if (target) { seed.push(target); subCount++; }
|
|
2543
|
+
}
|
|
2544
|
+
}
|
|
2545
|
+
let frontier = seed;
|
|
2546
|
+
while (frontier.length > 0) {
|
|
2547
|
+
const batch = [];
|
|
2548
|
+
for (const raw of frontier) {
|
|
2549
|
+
const rel = stripRelPath(raw);
|
|
2550
|
+
if (!rel || visited.has(rel)) continue;
|
|
2551
|
+
visited.add(rel);
|
|
2552
|
+
batch.push(rel);
|
|
2553
|
+
}
|
|
2554
|
+
frontier = [];
|
|
2555
|
+
if (batch.length === 0) break;
|
|
2556
|
+
const texts = await Promise.all(
|
|
2557
|
+
batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
|
|
2558
|
+
);
|
|
2559
|
+
for (let idx = 0; idx < batch.length; idx++) {
|
|
2560
|
+
const rel = batch[idx];
|
|
2561
|
+
const text = texts[idx];
|
|
2562
|
+
if (text === null) continue;
|
|
2563
|
+
files.push({ rel, content: text });
|
|
2564
|
+
const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
|
|
2565
|
+
for (const spec of extractRelativeSpecifiers(text)) {
|
|
2566
|
+
const target = normalizeRelPath(baseDir, spec);
|
|
2567
|
+
// Only guess extensions when the specifier omits one; non-existent
|
|
2568
|
+
// candidates 404 harmlessly.
|
|
2569
|
+
const cands = /\.[a-z0-9]+$/i.test(target)
|
|
2570
|
+
? [target]
|
|
2571
|
+
: [target, `${target}.js`, `${target}.json`, `${target}.mjs`, `${target}.cjs`, `${target}/index.js`];
|
|
2572
|
+
for (const cand of cands) {
|
|
2573
|
+
const c = stripRelPath(cand);
|
|
2574
|
+
if (c && !visited.has(c)) frontier.push(cand);
|
|
2575
|
+
}
|
|
2576
|
+
}
|
|
2577
|
+
}
|
|
2578
|
+
}
|
|
2579
|
+
// The declared entry may be missing on the CDN; fall back to index.js.
|
|
2580
|
+
if (!files.some(f => f.rel === entry)) {
|
|
2581
|
+
const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
|
|
2582
|
+
if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
|
|
2583
|
+
}
|
|
2584
|
+
|
|
2585
|
+
// Declared dependencies plus non-optional peer dependencies (npm v7+ style),
|
|
2586
|
+
// so e.g. `npm install react-dom` also pulls in `react`.
|
|
2587
|
+
const depNames = Object.keys(meta.dependencies || {});
|
|
2588
|
+
const peerMeta = meta.peerDependenciesMeta || {};
|
|
2589
|
+
for (const peer of Object.keys(meta.peerDependencies || {})) {
|
|
2590
|
+
if (peerMeta[peer] && peerMeta[peer].optional) continue;
|
|
2591
|
+
if (depNames.indexOf(peer) === -1) depNames.push(peer);
|
|
2592
|
+
}
|
|
2593
|
+
|
|
2594
|
+
return { ok: true, version, entry, files, deps: depNames, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
|
|
2595
|
+
}
|
|
2596
|
+
|
|
2597
|
+
function installTargetDirs(ctx, name) {
|
|
2598
|
+
const dirs = ['/workspace/node_modules/' + name];
|
|
2599
|
+
const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', name);
|
|
2600
|
+
if (!dirs.includes(cwdTarget)) dirs.push(cwdTarget);
|
|
2601
|
+
return dirs;
|
|
2602
|
+
}
|
|
2603
|
+
|
|
2604
|
+
function writeInstalledPackageFiles(ctx, dirs, name, info) {
|
|
2605
|
+
for (const dir of dirs) {
|
|
2606
|
+
ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
|
|
2607
|
+
for (const f of info.files) {
|
|
2608
|
+
const full = PosixPath.join(dir, f.rel);
|
|
2609
|
+
ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
|
|
2610
|
+
ctx.vfs.writeFileSync(full, f.content);
|
|
2611
|
+
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
|
|
2612
|
+
}
|
|
2613
|
+
const modPkgPath = PosixPath.join(dir, 'package.json');
|
|
2614
|
+
const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
|
|
2615
|
+
if (info.pkgExports && typeof info.pkgExports === 'object') {
|
|
2616
|
+
const normalized = { '.': './' + (info.entry || 'index.js') };
|
|
2617
|
+
for (const key of Object.keys(info.pkgExports)) {
|
|
2618
|
+
if (key === '.' || key.indexOf('*') !== -1) continue;
|
|
2619
|
+
const target = pickConditionalEntry(info.pkgExports[key]);
|
|
2620
|
+
if (target) normalized[key] = target.charAt(0) === '.' ? target : './' + target;
|
|
2621
|
+
}
|
|
2622
|
+
modPkg.exports = normalized;
|
|
2623
|
+
}
|
|
2624
|
+
ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
|
|
2408
2625
|
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
|
|
2626
|
+
}
|
|
2627
|
+
}
|
|
2409
2628
|
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2629
|
+
async function installPackage(pkgSpec, ctx, onLine, opts) {
|
|
2630
|
+
const options = (onLine && typeof onLine === 'object') ? onLine : (opts || {});
|
|
2631
|
+
const lineCb = (typeof onLine === 'function') ? onLine : (typeof options.onLine === 'function' ? options.onLine : null);
|
|
2632
|
+
const isDev = Boolean(options.dev);
|
|
2633
|
+
const { name: pkgName, range } = parsePackageSpec(pkgSpec);
|
|
2634
|
+
if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
|
|
2635
|
+
|
|
2636
|
+
const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
2637
|
+
const depField = isDev ? 'devDependencies' : 'dependencies';
|
|
2638
|
+
if (!pkgData[depField]) pkgData[depField] = {};
|
|
2639
|
+
|
|
2640
|
+
const fetchImpl = packageCtxFetch(ctx);
|
|
2641
|
+
const seen = (ctx.shell && ctx.shell._cdnSeen)
|
|
2642
|
+
? ctx.shell._cdnSeen
|
|
2643
|
+
: (ctx.shell ? (ctx.shell._cdnSeen = new Set()) : new Set());
|
|
2644
|
+
|
|
2645
|
+
const queue = [{ name: pkgName, range, direct: true }];
|
|
2646
|
+
const requested = new Set([pkgName]);
|
|
2647
|
+
const installed = [];
|
|
2648
|
+
let warning = null;
|
|
2649
|
+
let directVersion = null;
|
|
2650
|
+
|
|
2651
|
+
while (queue.length > 0) {
|
|
2652
|
+
const item = queue.shift();
|
|
2653
|
+
const info = fetchImpl
|
|
2654
|
+
? await downloadPackageFiles(fetchImpl, item.name, item.range, seen)
|
|
2655
|
+
: { ok: false, reason: `${item.name}: no fetch implementation available` };
|
|
2656
|
+
|
|
2657
|
+
if (!info.ok) {
|
|
2658
|
+
// Final fallback: an empty stub so offline demos still resolve the module.
|
|
2659
|
+
writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, {
|
|
2660
|
+
version: '0.0.0', entry: 'index.js', files: [{ rel: 'index.js', content: 'module.exports = {};\n' }]
|
|
2661
|
+
});
|
|
2662
|
+
if (!warning) warning = info.reason;
|
|
2663
|
+
installed.push({ name: item.name, version: '0.0.0' });
|
|
2664
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: '0.0.0', offline: true });
|
|
2665
|
+
continue;
|
|
2666
|
+
}
|
|
2667
|
+
|
|
2668
|
+
writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
|
|
2669
|
+
installed.push({ name: item.name, version: info.version || '1.0.0' });
|
|
2670
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: info.version || '1.0.0', deduped: Boolean(info.deduped) });
|
|
2671
|
+
if (item.direct) directVersion = info.version || null;
|
|
2672
|
+
|
|
2673
|
+
for (const dep of (info.deps || [])) {
|
|
2674
|
+
const parsed = parsePackageSpec(dep);
|
|
2675
|
+
if (parsed.name && !requested.has(parsed.name)) {
|
|
2676
|
+
requested.add(parsed.name);
|
|
2677
|
+
queue.push({ name: parsed.name, range: null, direct: false });
|
|
2678
|
+
}
|
|
2417
2679
|
}
|
|
2418
|
-
ctx.vfs.writeFileSync(modIndexPath, code);
|
|
2419
|
-
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modIndexPath);
|
|
2420
2680
|
}
|
|
2681
|
+
|
|
2682
|
+
pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
|
|
2683
|
+
writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
|
|
2684
|
+
|
|
2685
|
+
return { name: pkgName, ok: true, version: directVersion, installed, warning };
|
|
2686
|
+
}
|
|
2687
|
+
|
|
2688
|
+
// Build a live install log: each line is streamed to the terminal as it
|
|
2689
|
+
// happens (when possible) and accumulated so the command can also return it.
|
|
2690
|
+
function createInstallEmitter(ctx, sink) {
|
|
2691
|
+
const stream = (ctx && typeof ctx.onStdout === 'function') ? ctx.onStdout : null;
|
|
2692
|
+
return function emit(text) {
|
|
2693
|
+
if (!text) return;
|
|
2694
|
+
sink.push(text);
|
|
2695
|
+
if (stream) stream(text);
|
|
2696
|
+
};
|
|
2697
|
+
}
|
|
2698
|
+
|
|
2699
|
+
function formatInstallLine(info) {
|
|
2700
|
+
if (!info || !info.name) return '';
|
|
2701
|
+
const suffix = info.offline ? ' (offline fallback)' : (info.deduped ? ' (deduped)' : '');
|
|
2702
|
+
return ` + ${info.name}@${info.version || '1.0.0'}${suffix}\n`;
|
|
2703
|
+
}
|
|
2704
|
+
|
|
2705
|
+
function countInstalledPackages(results) {
|
|
2706
|
+
const seen = new Set();
|
|
2707
|
+
for (const r of results) {
|
|
2708
|
+
if (!r) continue;
|
|
2709
|
+
if (r.name) seen.add(r.name);
|
|
2710
|
+
for (const p of (r.installed || [])) { if (p && p.name) seen.add(p.name); }
|
|
2711
|
+
}
|
|
2712
|
+
return seen.size;
|
|
2713
|
+
}
|
|
2714
|
+
|
|
2715
|
+
// Resolve + install a list of specs while printing a realistic transcript,
|
|
2716
|
+
// so `npm install` / `bun add` look like the real tools instead of a terse
|
|
2717
|
+
// "saved N package(s)".
|
|
2718
|
+
async function runInstallTranscript(pkgs, ctx, opts) {
|
|
2719
|
+
const options = opts || {};
|
|
2720
|
+
const manager = options.manager || 'bun';
|
|
2721
|
+
const header = options.header || (manager === 'npm' ? 'npm install v10.2.0' : 'bun add v1.1.20 (1.1.20)');
|
|
2722
|
+
const out = [];
|
|
2723
|
+
const emit = createInstallEmitter(ctx, out);
|
|
2724
|
+
const started = Date.now();
|
|
2725
|
+
emit(`${header}\n\nResolving dependencies...\n`);
|
|
2726
|
+
const results = [];
|
|
2727
|
+
for (const p of pkgs) {
|
|
2728
|
+
results.push(await installPackage(p, ctx, { onLine: (info) => emit(formatInstallLine(info)), dev: Boolean(options.dev) }));
|
|
2729
|
+
}
|
|
2730
|
+
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
2731
|
+
const count = countInstalledPackages(results);
|
|
2732
|
+
const ms = Date.now() - started;
|
|
2733
|
+
if (manager === 'npm') {
|
|
2734
|
+
emit(`\nadded ${count} package(s) in ${ms}ms\n`);
|
|
2735
|
+
} else if (manager === 'pnpm') {
|
|
2736
|
+
emit(`\nPackages: +${count}\n${'+'.repeat(Math.min(count, 40))}\nDone in ${ms}ms using pnpm v9.0.0\n`);
|
|
2737
|
+
} else {
|
|
2738
|
+
emit(`Saved lockfile\n\n${count} package(s) installed [${ms}ms]\n`);
|
|
2739
|
+
}
|
|
2740
|
+
return {
|
|
2741
|
+
code: 0,
|
|
2742
|
+
stdout: out.join(''),
|
|
2743
|
+
stderr: warning ? `${manager === 'npm' ? 'npm warn' : manager === 'pnpm' ? 'pnpm warn' : 'bun warn'} ${warning}\n` : ''
|
|
2744
|
+
};
|
|
2421
2745
|
}
|
|
2422
2746
|
|
|
2423
2747
|
function uninstallPackage(pkgName, ctx) {
|
|
@@ -2471,9 +2795,261 @@ function __initShellModule(root: any) {
|
|
|
2471
2795
|
if (scriptArgs && scriptArgs.length > 0) {
|
|
2472
2796
|
cmd += ' ' + scriptArgs.join(' ');
|
|
2473
2797
|
}
|
|
2798
|
+
const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
|
|
2799
|
+
if (fallback) return fallback;
|
|
2474
2800
|
return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
|
|
2475
2801
|
}
|
|
2476
2802
|
|
|
2803
|
+
// ---------------------------------------------------------------------------
|
|
2804
|
+
// Built-in static preview server (`serve` / `npm run dev` fallback).
|
|
2805
|
+
//
|
|
2806
|
+
// Serves the virtual filesystem over a virtual port so the in-browser Web
|
|
2807
|
+
// Preview can render a project. `.ts/.tsx/.jsx` sources are transpiled to
|
|
2808
|
+
// browser-native ESM on the fly, and bare specifiers are resolved to jsDelivr
|
|
2809
|
+
// `+esm` builds through an injected import map — no bundler required.
|
|
2810
|
+
// ---------------------------------------------------------------------------
|
|
2811
|
+
|
|
2812
|
+
const CDN_ESM_BASE = 'https://cdn.jsdelivr.net/npm';
|
|
2813
|
+
|
|
2814
|
+
const PREVIEW_MIME = {
|
|
2815
|
+
'.html': 'text/html; charset=utf-8',
|
|
2816
|
+
'.htm': 'text/html; charset=utf-8',
|
|
2817
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
2818
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
2819
|
+
'.cjs': 'text/javascript; charset=utf-8',
|
|
2820
|
+
'.jsx': 'text/javascript; charset=utf-8',
|
|
2821
|
+
'.ts': 'text/javascript; charset=utf-8',
|
|
2822
|
+
'.tsx': 'text/javascript; charset=utf-8',
|
|
2823
|
+
'.css': 'text/css; charset=utf-8',
|
|
2824
|
+
'.json': 'application/json; charset=utf-8',
|
|
2825
|
+
'.map': 'application/json; charset=utf-8',
|
|
2826
|
+
'.svg': 'image/svg+xml',
|
|
2827
|
+
'.png': 'image/png',
|
|
2828
|
+
'.jpg': 'image/jpeg',
|
|
2829
|
+
'.jpeg': 'image/jpeg',
|
|
2830
|
+
'.gif': 'image/gif',
|
|
2831
|
+
'.webp': 'image/webp',
|
|
2832
|
+
'.ico': 'image/x-icon',
|
|
2833
|
+
'.txt': 'text/plain; charset=utf-8'
|
|
2834
|
+
};
|
|
2835
|
+
|
|
2836
|
+
function previewMimeFor(p) {
|
|
2837
|
+
const lower = String(p).toLowerCase();
|
|
2838
|
+
const dot = lower.lastIndexOf('.');
|
|
2839
|
+
if (dot === -1) return 'application/octet-stream';
|
|
2840
|
+
return PREVIEW_MIME[lower.slice(dot)] || 'application/octet-stream';
|
|
2841
|
+
}
|
|
2842
|
+
|
|
2843
|
+
function isPreviewScriptPath(p) {
|
|
2844
|
+
return /\.(?:[cm]?jsx?|tsx?)$/i.test(p) && !/\.d\.ts$/i.test(p);
|
|
2845
|
+
}
|
|
2846
|
+
|
|
2847
|
+
// Collect bare (non-relative) module specifiers referenced by a source file.
|
|
2848
|
+
function extractBareSpecifiers(code) {
|
|
2849
|
+
const out = new Set();
|
|
2850
|
+
const patterns = [
|
|
2851
|
+
/\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2852
|
+
/\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2853
|
+
/\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2854
|
+
/\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g
|
|
2855
|
+
];
|
|
2856
|
+
for (const re of patterns) {
|
|
2857
|
+
let m;
|
|
2858
|
+
while ((m = re.exec(code)) !== null) {
|
|
2859
|
+
const spec = m[1];
|
|
2860
|
+
if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.includes(':')) continue;
|
|
2861
|
+
out.add(spec);
|
|
2862
|
+
}
|
|
2863
|
+
}
|
|
2864
|
+
return Array.from(out);
|
|
2865
|
+
}
|
|
2866
|
+
|
|
2867
|
+
function normalizeVersionRange(range) {
|
|
2868
|
+
if (!range || typeof range !== 'string') return 'latest';
|
|
2869
|
+
const v = range.trim();
|
|
2870
|
+
if (!v || v === '*' || /^(?:latest|next|beta|canary)$/.test(v)) return 'latest';
|
|
2871
|
+
if (/^(?:file|link|workspace|portal|git|https?):/.test(v)) return 'latest';
|
|
2872
|
+
return v.replace(/\s+/g, '').replace(/^[v=\s]+/, '') || 'latest';
|
|
2873
|
+
}
|
|
2874
|
+
|
|
2875
|
+
function resolveBareVersion(vfs, rootDir, pkgName) {
|
|
2876
|
+
try {
|
|
2877
|
+
const modPkg = PosixPath.join(rootDir, 'node_modules', pkgName, 'package.json');
|
|
2878
|
+
if (vfs.existsSync(modPkg)) {
|
|
2879
|
+
const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
|
|
2880
|
+
if (parsed && parsed.version) return parsed.version;
|
|
2881
|
+
}
|
|
2882
|
+
} catch (_) {}
|
|
2883
|
+
try {
|
|
2884
|
+
for (const dir of [rootDir, '/workspace']) {
|
|
2885
|
+
const pkgPath = PosixPath.join(dir, 'package.json');
|
|
2886
|
+
if (!vfs.existsSync(pkgPath)) continue;
|
|
2887
|
+
const parsed = JSON.parse(vfs.readFileSync(pkgPath, 'utf8'));
|
|
2888
|
+
const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
|
|
2889
|
+
if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
|
|
2890
|
+
}
|
|
2891
|
+
} catch (_) {}
|
|
2892
|
+
return 'latest';
|
|
2893
|
+
}
|
|
2894
|
+
|
|
2895
|
+
function cdnEsmUrl(pkgName, version, subpath) {
|
|
2896
|
+
const base = `${CDN_ESM_BASE}/${pkgName}@${version}`;
|
|
2897
|
+
const sub = subpath ? '/' + String(subpath).replace(/^\/+|\/+$/g, '') : '';
|
|
2898
|
+
return `${base}${sub}/+esm`;
|
|
2899
|
+
}
|
|
2900
|
+
|
|
2901
|
+
function buildPreviewImportMap(vfs, rootDir, specifiers) {
|
|
2902
|
+
const imports = {};
|
|
2903
|
+
for (const spec of specifiers) {
|
|
2904
|
+
const parts = String(spec).split('/');
|
|
2905
|
+
const pkgName = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
|
|
2906
|
+
if (!pkgName) continue;
|
|
2907
|
+
const subpath = spec.slice(pkgName.length).replace(/^\/+/, '');
|
|
2908
|
+
const version = resolveBareVersion(vfs, rootDir, pkgName);
|
|
2909
|
+
imports[spec] = cdnEsmUrl(pkgName, version, subpath || undefined);
|
|
2910
|
+
}
|
|
2911
|
+
return imports;
|
|
2912
|
+
}
|
|
2913
|
+
|
|
2914
|
+
function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
|
|
2915
|
+
const scripts = [];
|
|
2916
|
+
const walk = (dir, depth) => {
|
|
2917
|
+
if (depth > 8 || scripts.length >= maxFiles) return;
|
|
2918
|
+
let entries = [];
|
|
2919
|
+
try { entries = vfs.readdirSync(dir); } catch (_) { return; }
|
|
2920
|
+
for (const name of entries) {
|
|
2921
|
+
if (name === 'node_modules' || name.startsWith('.')) continue;
|
|
2922
|
+
const full = PosixPath.join(dir, name);
|
|
2923
|
+
let st;
|
|
2924
|
+
try { st = vfs.statSync(full); } catch (_) { continue; }
|
|
2925
|
+
const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
|
|
2926
|
+
if (dirFlag) {
|
|
2927
|
+
walk(full, depth + 1);
|
|
2928
|
+
} else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
|
|
2929
|
+
try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
|
|
2930
|
+
}
|
|
2931
|
+
}
|
|
2932
|
+
};
|
|
2933
|
+
walk(rootDir, 0);
|
|
2934
|
+
return scripts;
|
|
2935
|
+
}
|
|
2936
|
+
|
|
2937
|
+
function injectPreviewExtras(html, importMap) {
|
|
2938
|
+
let out = html;
|
|
2939
|
+
const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
|
|
2940
|
+
if (/<head[^>]*>/i.test(out)) {
|
|
2941
|
+
out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
|
|
2942
|
+
} else {
|
|
2943
|
+
out = importMapTag + '\n' + out;
|
|
2944
|
+
}
|
|
2945
|
+
const shim = '<script>window.__CODELAB_PREVIEW__ = true;</script>';
|
|
2946
|
+
if (/<\/body>/i.test(out)) out = out.replace(/<\/body>/i, `${shim}\n</body>`);
|
|
2947
|
+
else out = out + '\n' + shim;
|
|
2948
|
+
return out;
|
|
2949
|
+
}
|
|
2950
|
+
|
|
2951
|
+
function registerPreviewServer(ctx, rootDir, preferredPort) {
|
|
2952
|
+
const portTable = ctx.shell && ctx.shell.portTable;
|
|
2953
|
+
if (!portTable || typeof portTable.registerServer !== 'function') return null;
|
|
2954
|
+
|
|
2955
|
+
let port = Number(preferredPort) || 3000;
|
|
2956
|
+
const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
|
|
2957
|
+
while (taken.has(port)) port++;
|
|
2958
|
+
|
|
2959
|
+
const specifiers = new Set();
|
|
2960
|
+
for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
|
|
2961
|
+
for (const s of extractBareSpecifiers(content)) specifiers.add(s);
|
|
2962
|
+
}
|
|
2963
|
+
const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
|
|
2964
|
+
|
|
2965
|
+
const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
|
|
2966
|
+
const isDir = (p) => {
|
|
2967
|
+
try {
|
|
2968
|
+
const st = ctx.vfs.statSync(p);
|
|
2969
|
+
return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
|
|
2970
|
+
} catch (_) { return false; }
|
|
2971
|
+
};
|
|
2972
|
+
const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
|
|
2973
|
+
|
|
2974
|
+
const handler = async (request) => {
|
|
2975
|
+
let pathname = '/';
|
|
2976
|
+
try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
|
|
2977
|
+
const rel = pathname.replace(/^\/+/, '');
|
|
2978
|
+
let target = PosixPath.join(rootDir, rel);
|
|
2979
|
+
const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
|
|
2980
|
+
|
|
2981
|
+
if (!rel || pathname.endsWith('/') || isDir(target)) {
|
|
2982
|
+
target = PosixPath.join(target, 'index.html');
|
|
2983
|
+
}
|
|
2984
|
+
if (!exists(target) && !hasExt) {
|
|
2985
|
+
// Resolve extensionless module specifiers (e.g. `./components/Counter`)
|
|
2986
|
+
// the way a bundler / dev server would.
|
|
2987
|
+
const cands = [
|
|
2988
|
+
target + '.tsx', target + '.ts', target + '.jsx', target + '.js',
|
|
2989
|
+
target + '.mjs', target + '.cjs',
|
|
2990
|
+
PosixPath.join(target, 'index.tsx'), PosixPath.join(target, 'index.ts'),
|
|
2991
|
+
PosixPath.join(target, 'index.jsx'), PosixPath.join(target, 'index.js')
|
|
2992
|
+
];
|
|
2993
|
+
for (const c of cands) { if (exists(c)) { target = c; break; } }
|
|
2994
|
+
}
|
|
2995
|
+
if (!exists(target) && !hasExt) {
|
|
2996
|
+
target = PosixPath.join(rootDir, 'index.html'); // SPA fallback
|
|
2997
|
+
}
|
|
2998
|
+
if (!exists(target)) {
|
|
2999
|
+
return new Response(
|
|
3000
|
+
`<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
|
|
3001
|
+
{ status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
|
|
3002
|
+
);
|
|
3003
|
+
}
|
|
3004
|
+
|
|
3005
|
+
let body = readText(target);
|
|
3006
|
+
if (body === null) body = '';
|
|
3007
|
+
if (/\.html?$/i.test(target)) {
|
|
3008
|
+
body = injectPreviewExtras(body, importMap);
|
|
3009
|
+
} else if (isPreviewScriptPath(target)) {
|
|
3010
|
+
try {
|
|
3011
|
+
const rm = getRuntimeModule();
|
|
3012
|
+
if (rm && typeof rm.transpileForBrowser === 'function') {
|
|
3013
|
+
body = rm.transpileForBrowser(body, target);
|
|
3014
|
+
}
|
|
3015
|
+
} catch (_) {}
|
|
3016
|
+
}
|
|
3017
|
+
|
|
3018
|
+
return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
|
|
3019
|
+
};
|
|
3020
|
+
|
|
3021
|
+
const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
|
|
3022
|
+
return portTable.registerServer(port, {
|
|
3023
|
+
server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
|
|
3024
|
+
fetch: handler,
|
|
3025
|
+
name: 'code-lab-serve',
|
|
3026
|
+
pid,
|
|
3027
|
+
root: rootDir
|
|
3028
|
+
});
|
|
3029
|
+
}
|
|
3030
|
+
|
|
3031
|
+
// Common dev-server commands that cannot run inside the virtual runtime are
|
|
3032
|
+
// transparently redirected to the built-in preview server.
|
|
3033
|
+
const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
|
|
3034
|
+
|
|
3035
|
+
function tryDevScriptFallback(scriptName, cmd, ctx) {
|
|
3036
|
+
if (!PREVIEW_TOOL_RE.test(cmd)) return null;
|
|
3037
|
+
// Only fall back when the referenced tool is not actually installed.
|
|
3038
|
+
const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
|
|
3039
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
|
|
3040
|
+
if (ctx.vfs.existsSync(binPath)) return null;
|
|
3041
|
+
const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
|
|
3042
|
+
const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
|
|
3043
|
+
const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
|
|
3044
|
+
const entry = registerPreviewServer(ctx, ctx.cwd, port);
|
|
3045
|
+
if (!entry) return null;
|
|
3046
|
+
return {
|
|
3047
|
+
code: 0,
|
|
3048
|
+
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`,
|
|
3049
|
+
stderr: ''
|
|
3050
|
+
};
|
|
3051
|
+
}
|
|
3052
|
+
|
|
2477
3053
|
function evaluatePosixTest(args, ctx) {
|
|
2478
3054
|
const cleanArgs = [...args];
|
|
2479
3055
|
if (cleanArgs.length > 0 && cleanArgs[cleanArgs.length - 1] === ']') {
|
|
@@ -4972,7 +5548,8 @@ function __initShellModule(root: any) {
|
|
|
4972
5548
|
stdout += ' date, sleep, clear Date, delay, terminal screen control\n';
|
|
4973
5549
|
stdout += ' history, ps, jobs, kill Process and job management\n';
|
|
4974
5550
|
stdout += ' git [status diff log] Built-in version control\n';
|
|
4975
|
-
stdout += ' node, bun, npm, npx, bunx CLI runtime and package shims\n';
|
|
5551
|
+
stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
|
|
5552
|
+
stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
|
|
4976
5553
|
stdout += ' ports, curl Port table inspection & HTTP requests\n';
|
|
4977
5554
|
return { code: 0, stdout, stderr: '' };
|
|
4978
5555
|
},
|
|
@@ -5094,6 +5671,18 @@ function __initShellModule(root: any) {
|
|
|
5094
5671
|
|
|
5095
5672
|
const sub = args[0];
|
|
5096
5673
|
|
|
5674
|
+
if (sub === '--version' || sub === '-v' || sub === '--revision') {
|
|
5675
|
+
return { code: 0, stdout: '1.1.20\n', stderr: '' };
|
|
5676
|
+
}
|
|
5677
|
+
|
|
5678
|
+
if (sub === '--help' || sub === '-h') {
|
|
5679
|
+
return {
|
|
5680
|
+
code: 0,
|
|
5681
|
+
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',
|
|
5682
|
+
stderr: ''
|
|
5683
|
+
};
|
|
5684
|
+
}
|
|
5685
|
+
|
|
5097
5686
|
if (sub === 'init') {
|
|
5098
5687
|
const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
|
|
5099
5688
|
const dirName = PosixPath.basename(ctx.cwd) || 'app';
|
|
@@ -5143,12 +5732,27 @@ function __initShellModule(root: any) {
|
|
|
5143
5732
|
return { code: 0, stdout: 'Done! A package.json file was created in ' + ctx.cwd + '\n', stderr: '' };
|
|
5144
5733
|
}
|
|
5145
5734
|
|
|
5146
|
-
if (sub === '
|
|
5735
|
+
if (sub === 'install' || sub === 'i' || sub === 'ci') {
|
|
5147
5736
|
const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5148
|
-
|
|
5149
|
-
|
|
5737
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
5738
|
+
if (pkgs.length === 0) {
|
|
5739
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5740
|
+
const deps = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
5741
|
+
if (deps.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5742
|
+
return await runInstallTranscript(deps, ctx, { manager: 'bun', header: 'bun install v1.1.20 (1.1.20)' });
|
|
5150
5743
|
}
|
|
5151
|
-
return {
|
|
5744
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
5745
|
+
}
|
|
5746
|
+
|
|
5747
|
+
if (sub === 'add') {
|
|
5748
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5749
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
5750
|
+
if (pkgs.length === 0) {
|
|
5751
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5752
|
+
pkgs = Object.keys(pkgData.dependencies || {});
|
|
5753
|
+
}
|
|
5754
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5755
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
5152
5756
|
}
|
|
5153
5757
|
|
|
5154
5758
|
if (sub === 'remove' || sub === 'rm') {
|
|
@@ -5308,18 +5912,14 @@ function __initShellModule(root: any) {
|
|
|
5308
5912
|
}
|
|
5309
5913
|
|
|
5310
5914
|
if (sub === 'i' || sub === 'install' || sub === 'add') {
|
|
5311
|
-
|
|
5915
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5916
|
+
const dev = args.some(a => a === '-D' || a === '--save-dev' || a === '--dev');
|
|
5312
5917
|
if (pkgs.length === 0) {
|
|
5313
5918
|
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5314
|
-
|
|
5315
|
-
|
|
5316
|
-
}
|
|
5317
|
-
return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5318
|
-
}
|
|
5319
|
-
for (const p of pkgs) {
|
|
5320
|
-
installPackage(p, ctx);
|
|
5919
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
5920
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5321
5921
|
}
|
|
5322
|
-
return
|
|
5922
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'npm', dev, header: 'npm install v10.2.0' });
|
|
5323
5923
|
}
|
|
5324
5924
|
|
|
5325
5925
|
if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
|
|
@@ -5371,6 +5971,123 @@ function __initShellModule(root: any) {
|
|
|
5371
5971
|
return await this.npx(args, ctx);
|
|
5372
5972
|
},
|
|
5373
5973
|
|
|
5974
|
+
async pnpm(args, ctx) {
|
|
5975
|
+
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
|
5976
|
+
return {
|
|
5977
|
+
code: 0,
|
|
5978
|
+
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',
|
|
5979
|
+
stderr: ''
|
|
5980
|
+
};
|
|
5981
|
+
}
|
|
5982
|
+
const sub = args[0];
|
|
5983
|
+
if (sub === '--version' || sub === '-v') {
|
|
5984
|
+
return { code: 0, stdout: '9.0.0\n', stderr: '' };
|
|
5985
|
+
}
|
|
5986
|
+
const dev = args.some((a) => a === '-D' || a === '--save-dev' || a === '--dev' || a === '-d');
|
|
5987
|
+
|
|
5988
|
+
if (sub === 'init') {
|
|
5989
|
+
const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
|
|
5990
|
+
if (!ctx.vfs.existsSync(pkgPath)) {
|
|
5991
|
+
ctx.vfs.writeFileSync(pkgPath, JSON.stringify({
|
|
5992
|
+
name: PosixPath.basename(ctx.cwd) || 'app',
|
|
5993
|
+
version: '1.0.0',
|
|
5994
|
+
main: 'index.js',
|
|
5995
|
+
scripts: { test: 'echo "Error: no test specified" && exit 1' }
|
|
5996
|
+
}, null, 2) + '\n');
|
|
5997
|
+
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', pkgPath);
|
|
5998
|
+
}
|
|
5999
|
+
return { code: 0, stdout: 'Wrote to ' + pkgPath + '\n', stderr: '' };
|
|
6000
|
+
}
|
|
6001
|
+
|
|
6002
|
+
if (sub === 'install' || sub === 'i' || sub === 'add') {
|
|
6003
|
+
let pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
6004
|
+
if (pkgs.length === 0) {
|
|
6005
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
6006
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
6007
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'Already up to date\n', stderr: '' };
|
|
6008
|
+
}
|
|
6009
|
+
const verb = (sub === 'add') ? 'add' : 'install';
|
|
6010
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'pnpm', dev, header: `pnpm ${verb} v9.0.0` });
|
|
6011
|
+
}
|
|
6012
|
+
|
|
6013
|
+
if (sub === 'remove' || sub === 'rm' || sub === 'uninstall') {
|
|
6014
|
+
const pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
6015
|
+
for (const p of pkgs) uninstallPackage(p, ctx);
|
|
6016
|
+
return { code: 0, stdout: `removed ${pkgs.length} package(s)\n`, stderr: '' };
|
|
6017
|
+
}
|
|
6018
|
+
|
|
6019
|
+
if (sub === 'list' || sub === 'ls') {
|
|
6020
|
+
return { code: 0, stdout: listDependencies(ctx), stderr: '' };
|
|
6021
|
+
}
|
|
6022
|
+
|
|
6023
|
+
if (sub === 'run' || sub === 'run-script') {
|
|
6024
|
+
const scriptName = args[1];
|
|
6025
|
+
if (!scriptName) return { code: 1, stdout: '', stderr: 'pnpm: missing script name\n' };
|
|
6026
|
+
return await runPackageScript(scriptName, args.slice(2), ctx);
|
|
6027
|
+
}
|
|
6028
|
+
|
|
6029
|
+
if (sub === 'test') {
|
|
6030
|
+
return await runPackageScript('test', args.slice(1), ctx);
|
|
6031
|
+
}
|
|
6032
|
+
|
|
6033
|
+
if (sub === 'exec') {
|
|
6034
|
+
const cmd = args[1];
|
|
6035
|
+
if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
|
|
6036
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
|
|
6037
|
+
if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
|
|
6038
|
+
return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
|
|
6039
|
+
}
|
|
6040
|
+
|
|
6041
|
+
if (sub === 'dlx') {
|
|
6042
|
+
return await this.npx(args.slice(1), ctx);
|
|
6043
|
+
}
|
|
6044
|
+
|
|
6045
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
6046
|
+
if (pkgData.scripts && pkgData.scripts[sub]) {
|
|
6047
|
+
return await runPackageScript(sub, args.slice(1), ctx);
|
|
6048
|
+
}
|
|
6049
|
+
|
|
6050
|
+
return { code: 1, stdout: '', stderr: `ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Unknown command: "${sub}"\n` };
|
|
6051
|
+
},
|
|
6052
|
+
|
|
6053
|
+
async serve(args, ctx) {
|
|
6054
|
+
if (args[0] === '--help' || args[0] === '-h') {
|
|
6055
|
+
return {
|
|
6056
|
+
code: 0,
|
|
6057
|
+
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',
|
|
6058
|
+
stderr: ''
|
|
6059
|
+
};
|
|
6060
|
+
}
|
|
6061
|
+
const rootArg = (() => {
|
|
6062
|
+
const positionals = [];
|
|
6063
|
+
for (let i = 0; i < args.length; i++) {
|
|
6064
|
+
const a = args[i];
|
|
6065
|
+
if (a === '--port' || a === '-p') { i++; continue; }
|
|
6066
|
+
if (a.startsWith('-')) continue;
|
|
6067
|
+
positionals.push(a);
|
|
6068
|
+
}
|
|
6069
|
+
return positionals[0];
|
|
6070
|
+
})();
|
|
6071
|
+
let port = 3000;
|
|
6072
|
+
for (let i = 0; i < args.length; i++) {
|
|
6073
|
+
if ((args[i] === '--port' || args[i] === '-p') && args[i + 1]) { port = Number(args[i + 1]) || port; i++; }
|
|
6074
|
+
else if (args[i].startsWith('--port=')) port = Number(args[i].split('=')[1]) || port;
|
|
6075
|
+
}
|
|
6076
|
+
const rootDir = ctx.resolvePath(rootArg || '.');
|
|
6077
|
+
if (!ctx.vfs.existsSync(rootDir)) {
|
|
6078
|
+
return { code: 1, stdout: '', stderr: `serve: ${rootArg}: No such file or directory\n` };
|
|
6079
|
+
}
|
|
6080
|
+
const entry = registerPreviewServer(ctx, rootDir, port);
|
|
6081
|
+
if (!entry) {
|
|
6082
|
+
return { code: 1, stdout: '', stderr: 'serve: no virtual port table available\n' };
|
|
6083
|
+
}
|
|
6084
|
+
return {
|
|
6085
|
+
code: 0,
|
|
6086
|
+
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`,
|
|
6087
|
+
stderr: ''
|
|
6088
|
+
};
|
|
6089
|
+
},
|
|
6090
|
+
|
|
5374
6091
|
// -----------------------------------------------------------------------
|
|
5375
6092
|
// Port Table & HTTP Inspection: ports, curl
|
|
5376
6093
|
// -----------------------------------------------------------------------
|
|
@@ -5544,6 +6261,16 @@ function __initShellModule(root: any) {
|
|
|
5544
6261
|
return PosixPath.resolve(this.cwd, p);
|
|
5545
6262
|
}
|
|
5546
6263
|
|
|
6264
|
+
// True when `name` resolves to a shell function or coreutil (used by the
|
|
6265
|
+
// workbench to route recognised commands straight to the shell instead of
|
|
6266
|
+
// treating flag-looking input such as `node --version` as a JS expression).
|
|
6267
|
+
hasCommand(name) {
|
|
6268
|
+
if (!name) return false;
|
|
6269
|
+
const n = String(name);
|
|
6270
|
+
if (this.functions && Object.prototype.hasOwnProperty.call(this.functions, n)) return true;
|
|
6271
|
+
return !!this.commands && Object.prototype.hasOwnProperty.call(this.commands, n);
|
|
6272
|
+
}
|
|
6273
|
+
|
|
5547
6274
|
_emitVfsMutation(type, absPath) {
|
|
5548
6275
|
if (!this.vfs) return;
|
|
5549
6276
|
const evt = { type, path: absPath, timestamp: Date.now() };
|