@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/dist/shell.js
CHANGED
|
@@ -2355,38 +2355,362 @@
|
|
|
2355
2355
|
} catch (_) {}
|
|
2356
2356
|
}
|
|
2357
2357
|
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2358
|
+
// ---------------------------------------------------------------------------
|
|
2359
|
+
// Real npm package installation via the jsDelivr CDN
|
|
2360
|
+
// ---------------------------------------------------------------------------
|
|
2361
|
+
const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
|
|
2362
|
+
|
|
2363
|
+
// Minimal offline registry, used only when the CDN is unreachable so common
|
|
2364
|
+
// demos still resolve without network access.
|
|
2365
|
+
const OFFLINE_PACKAGE_FALLBACKS = {
|
|
2366
|
+
'is-even': 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n',
|
|
2367
|
+
'tiny-invariant': 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n',
|
|
2368
|
+
'lodash': 'module.exports = { isArray: Array.isArray, isObject: function (v) { return v !== null && typeof v === "object"; } };\n',
|
|
2369
|
+
'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'
|
|
2370
|
+
};
|
|
2362
2371
|
|
|
2363
|
-
|
|
2364
|
-
if (
|
|
2365
|
-
|
|
2366
|
-
|
|
2372
|
+
function packageCtxFetch(ctx) {
|
|
2373
|
+
if (ctx && ctx.shell && ctx.shell.options && typeof ctx.shell.options.fetchImpl === 'function') {
|
|
2374
|
+
return ctx.shell.options.fetchImpl;
|
|
2375
|
+
}
|
|
2376
|
+
if (typeof fetch === 'function') return fetch.bind(globalThis);
|
|
2377
|
+
return null;
|
|
2378
|
+
}
|
|
2367
2379
|
|
|
2368
|
-
|
|
2369
|
-
const
|
|
2370
|
-
if (!
|
|
2380
|
+
function parsePackageSpec(spec) {
|
|
2381
|
+
const raw = String(spec || '').trim();
|
|
2382
|
+
if (!raw) return { name: '', range: null };
|
|
2383
|
+
if (raw.startsWith('@')) {
|
|
2384
|
+
const at = raw.indexOf('@', 1);
|
|
2385
|
+
if (at === -1) return { name: raw, range: null };
|
|
2386
|
+
return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
|
|
2387
|
+
}
|
|
2388
|
+
const at = raw.indexOf('@');
|
|
2389
|
+
if (at <= 0) return { name: raw, range: null };
|
|
2390
|
+
return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
|
|
2391
|
+
}
|
|
2371
2392
|
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2393
|
+
function pickConditionalEntry(value) {
|
|
2394
|
+
if (typeof value === 'string') return value;
|
|
2395
|
+
if (!value || typeof value !== 'object') return null;
|
|
2396
|
+
// This runtime executes CommonJS, so it prefers CJS-friendly conditions.
|
|
2397
|
+
for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
|
|
2398
|
+
if (value[key] !== undefined) {
|
|
2399
|
+
const picked = pickConditionalEntry(value[key]);
|
|
2400
|
+
if (picked) return picked;
|
|
2401
|
+
}
|
|
2402
|
+
}
|
|
2403
|
+
return null;
|
|
2404
|
+
}
|
|
2405
|
+
|
|
2406
|
+
function resolveEntryRelPath(pkgJson) {
|
|
2407
|
+
let entry = null;
|
|
2408
|
+
const exp = pkgJson && pkgJson.exports;
|
|
2409
|
+
if (typeof exp === 'string') {
|
|
2410
|
+
entry = exp;
|
|
2411
|
+
} else if (exp && typeof exp === 'object' && exp['.'] !== undefined) {
|
|
2412
|
+
entry = pickConditionalEntry(exp['.']);
|
|
2413
|
+
}
|
|
2414
|
+
if (!entry) {
|
|
2415
|
+
entry = pkgJson.main || pkgJson.module ||
|
|
2416
|
+
(typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
|
|
2417
|
+
}
|
|
2418
|
+
entry = String(entry).replace(/^[./]+/, '');
|
|
2419
|
+
return entry || 'index.js';
|
|
2420
|
+
}
|
|
2421
|
+
|
|
2422
|
+
function stripRelPath(rel) {
|
|
2423
|
+
return String(rel || '').replace(/^[./]+/, '');
|
|
2424
|
+
}
|
|
2425
|
+
|
|
2426
|
+
function extractRelativeSpecifiers(code) {
|
|
2427
|
+
const out = new Set();
|
|
2428
|
+
const patterns = [
|
|
2429
|
+
/\bfrom\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2430
|
+
/\brequire\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2431
|
+
/\bimport\s*\(\s*['"](\.{1,2}\/[^'"]+)['"]/g,
|
|
2432
|
+
/\bimport\s*['"](\.{1,2}\/[^'"]+)['"]/g
|
|
2433
|
+
];
|
|
2434
|
+
for (const re of patterns) {
|
|
2435
|
+
let m;
|
|
2436
|
+
while ((m = re.exec(code)) !== null) out.add(m[1]);
|
|
2437
|
+
}
|
|
2438
|
+
return Array.from(out);
|
|
2439
|
+
}
|
|
2440
|
+
|
|
2441
|
+
function normalizeRelPath(baseDir, rel) {
|
|
2442
|
+
const parts = String(baseDir || '').split('/').filter(Boolean);
|
|
2443
|
+
for (const seg of String(rel).split('/')) {
|
|
2444
|
+
if (!seg || seg === '.') continue;
|
|
2445
|
+
if (seg === '..') parts.pop();
|
|
2446
|
+
else parts.push(seg);
|
|
2447
|
+
}
|
|
2448
|
+
return parts.join('/');
|
|
2449
|
+
}
|
|
2450
|
+
|
|
2451
|
+
async function fetchTextFromCdn(fetchImpl, url) {
|
|
2452
|
+
try {
|
|
2453
|
+
const res = await fetchImpl(url);
|
|
2454
|
+
if (!res) return null;
|
|
2455
|
+
const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
|
|
2456
|
+
if (!ok) return null;
|
|
2457
|
+
if (typeof res.text === 'function') return await res.text();
|
|
2458
|
+
return String(res.body != null ? res.body : '');
|
|
2459
|
+
} catch (_) {
|
|
2460
|
+
return null;
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
|
|
2464
|
+
async function resolvePackageMetadata(fetchImpl, name, range) {
|
|
2465
|
+
const urls = range
|
|
2466
|
+
? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
|
|
2467
|
+
: [`${CDN_NPM_BASE}/${name}/package.json`];
|
|
2468
|
+
for (const url of urls) {
|
|
2469
|
+
const text = await fetchTextFromCdn(fetchImpl, url);
|
|
2470
|
+
if (!text) continue;
|
|
2471
|
+
try {
|
|
2472
|
+
const parsed = JSON.parse(text);
|
|
2473
|
+
if (parsed && parsed.version) return parsed;
|
|
2474
|
+
} catch (_) {}
|
|
2475
|
+
}
|
|
2476
|
+
return null;
|
|
2477
|
+
}
|
|
2478
|
+
|
|
2479
|
+
// Download a package's entry module, its relative submodules and record its
|
|
2480
|
+
// declared dependencies so the caller can resolve them transitively.
|
|
2481
|
+
async function downloadPackageFiles(fetchImpl, name, range, seen) {
|
|
2482
|
+
const meta = await resolvePackageMetadata(fetchImpl, name, range);
|
|
2483
|
+
if (!meta) {
|
|
2484
|
+
const fallback = OFFLINE_PACKAGE_FALLBACKS[name];
|
|
2485
|
+
if (fallback) {
|
|
2486
|
+
const v = range ? range.replace(/^[\^~>=<\s]+/, '') || '1.0.0' : '1.0.0';
|
|
2487
|
+
return { ok: true, offline: true, version: v, entry: 'index.js', files: [{ rel: 'index.js', content: fallback }], deps: [] };
|
|
2488
|
+
}
|
|
2489
|
+
return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
|
|
2490
|
+
}
|
|
2491
|
+
|
|
2492
|
+
const version = meta.version;
|
|
2493
|
+
const key = `${name}@${version}`;
|
|
2494
|
+
if (seen.has(key)) {
|
|
2495
|
+
return { ok: true, deduped: true, version, entry: resolveEntryRelPath(meta), files: [], deps: [] };
|
|
2496
|
+
}
|
|
2497
|
+
seen.add(key);
|
|
2498
|
+
|
|
2499
|
+
const entry = resolveEntryRelPath(meta);
|
|
2500
|
+
const files = [];
|
|
2501
|
+
const visited = new Set();
|
|
2502
|
+
// Seed with the package entry plus any declared `exports` subpaths, so a
|
|
2503
|
+
// later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
|
|
2504
|
+
const seed = [entry, `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`];
|
|
2505
|
+
const expMap = meta.exports;
|
|
2506
|
+
if (expMap && typeof expMap === 'object') {
|
|
2507
|
+
let subCount = 0;
|
|
2508
|
+
for (const key of Object.keys(expMap)) {
|
|
2509
|
+
if (key === '.' || key.slice(0, 2) !== './' || subCount >= 25) continue;
|
|
2510
|
+
const target = pickConditionalEntry(expMap[key]);
|
|
2511
|
+
if (target) { seed.push(target); subCount++; }
|
|
2512
|
+
}
|
|
2513
|
+
}
|
|
2514
|
+
let frontier = seed;
|
|
2515
|
+
while (frontier.length > 0) {
|
|
2516
|
+
const batch = [];
|
|
2517
|
+
for (const raw of frontier) {
|
|
2518
|
+
const rel = stripRelPath(raw);
|
|
2519
|
+
if (!rel || visited.has(rel)) continue;
|
|
2520
|
+
visited.add(rel);
|
|
2521
|
+
batch.push(rel);
|
|
2522
|
+
}
|
|
2523
|
+
frontier = [];
|
|
2524
|
+
if (batch.length === 0) break;
|
|
2525
|
+
const texts = await Promise.all(
|
|
2526
|
+
batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
|
|
2527
|
+
);
|
|
2528
|
+
for (let idx = 0; idx < batch.length; idx++) {
|
|
2529
|
+
const rel = batch[idx];
|
|
2530
|
+
const text = texts[idx];
|
|
2531
|
+
if (text === null) continue;
|
|
2532
|
+
files.push({ rel, content: text });
|
|
2533
|
+
const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
|
|
2534
|
+
for (const spec of extractRelativeSpecifiers(text)) {
|
|
2535
|
+
const target = normalizeRelPath(baseDir, spec);
|
|
2536
|
+
// Only guess extensions when the specifier omits one; non-existent
|
|
2537
|
+
// candidates 404 harmlessly.
|
|
2538
|
+
const cands = /\.[a-z0-9]+$/i.test(target)
|
|
2539
|
+
? [target]
|
|
2540
|
+
: [target, `${target}.js`, `${target}.json`, `${target}.mjs`, `${target}.cjs`, `${target}/index.js`];
|
|
2541
|
+
for (const cand of cands) {
|
|
2542
|
+
const c = stripRelPath(cand);
|
|
2543
|
+
if (c && !visited.has(c)) frontier.push(cand);
|
|
2544
|
+
}
|
|
2545
|
+
}
|
|
2546
|
+
}
|
|
2547
|
+
}
|
|
2548
|
+
// The declared entry may be missing on the CDN; fall back to index.js.
|
|
2549
|
+
if (!files.some(f => f.rel === entry)) {
|
|
2550
|
+
const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
|
|
2551
|
+
if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
|
|
2552
|
+
}
|
|
2553
|
+
|
|
2554
|
+
// Declared dependencies plus non-optional peer dependencies (npm v7+ style),
|
|
2555
|
+
// so e.g. `npm install react-dom` also pulls in `react`.
|
|
2556
|
+
const depNames = Object.keys(meta.dependencies || {});
|
|
2557
|
+
const peerMeta = meta.peerDependenciesMeta || {};
|
|
2558
|
+
for (const peer of Object.keys(meta.peerDependencies || {})) {
|
|
2559
|
+
if (peerMeta[peer] && peerMeta[peer].optional) continue;
|
|
2560
|
+
if (depNames.indexOf(peer) === -1) depNames.push(peer);
|
|
2561
|
+
}
|
|
2562
|
+
|
|
2563
|
+
return { ok: true, version, entry, files, deps: depNames, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
|
|
2564
|
+
}
|
|
2565
|
+
|
|
2566
|
+
function installTargetDirs(ctx, name) {
|
|
2567
|
+
const dirs = ['/workspace/node_modules/' + name];
|
|
2568
|
+
const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', name);
|
|
2569
|
+
if (!dirs.includes(cwdTarget)) dirs.push(cwdTarget);
|
|
2570
|
+
return dirs;
|
|
2571
|
+
}
|
|
2572
|
+
|
|
2573
|
+
function writeInstalledPackageFiles(ctx, dirs, name, info) {
|
|
2574
|
+
for (const dir of dirs) {
|
|
2575
|
+
ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
|
|
2576
|
+
for (const f of info.files) {
|
|
2577
|
+
const full = PosixPath.join(dir, f.rel);
|
|
2578
|
+
ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
|
|
2579
|
+
ctx.vfs.writeFileSync(full, f.content);
|
|
2580
|
+
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
|
|
2581
|
+
}
|
|
2582
|
+
const modPkgPath = PosixPath.join(dir, 'package.json');
|
|
2583
|
+
const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
|
|
2584
|
+
if (info.pkgExports && typeof info.pkgExports === 'object') {
|
|
2585
|
+
const normalized = { '.': './' + (info.entry || 'index.js') };
|
|
2586
|
+
for (const key of Object.keys(info.pkgExports)) {
|
|
2587
|
+
if (key === '.' || key.indexOf('*') !== -1) continue;
|
|
2588
|
+
const target = pickConditionalEntry(info.pkgExports[key]);
|
|
2589
|
+
if (target) normalized[key] = target.charAt(0) === '.' ? target : './' + target;
|
|
2590
|
+
}
|
|
2591
|
+
modPkg.exports = normalized;
|
|
2592
|
+
}
|
|
2593
|
+
ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
|
|
2377
2594
|
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
|
|
2595
|
+
}
|
|
2596
|
+
}
|
|
2597
|
+
|
|
2598
|
+
async function installPackage(pkgSpec, ctx, onLine, opts) {
|
|
2599
|
+
const options = (onLine && typeof onLine === 'object') ? onLine : (opts || {});
|
|
2600
|
+
const lineCb = (typeof onLine === 'function') ? onLine : (typeof options.onLine === 'function' ? options.onLine : null);
|
|
2601
|
+
const isDev = Boolean(options.dev);
|
|
2602
|
+
const { name: pkgName, range } = parsePackageSpec(pkgSpec);
|
|
2603
|
+
if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
|
|
2378
2604
|
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2605
|
+
const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
2606
|
+
const depField = isDev ? 'devDependencies' : 'dependencies';
|
|
2607
|
+
if (!pkgData[depField]) pkgData[depField] = {};
|
|
2608
|
+
|
|
2609
|
+
const fetchImpl = packageCtxFetch(ctx);
|
|
2610
|
+
const seen = (ctx.shell && ctx.shell._cdnSeen)
|
|
2611
|
+
? ctx.shell._cdnSeen
|
|
2612
|
+
: (ctx.shell ? (ctx.shell._cdnSeen = new Set()) : new Set());
|
|
2613
|
+
|
|
2614
|
+
const queue = [{ name: pkgName, range, direct: true }];
|
|
2615
|
+
const requested = new Set([pkgName]);
|
|
2616
|
+
const installed = [];
|
|
2617
|
+
let warning = null;
|
|
2618
|
+
let directVersion = null;
|
|
2619
|
+
|
|
2620
|
+
while (queue.length > 0) {
|
|
2621
|
+
const item = queue.shift();
|
|
2622
|
+
const info = fetchImpl
|
|
2623
|
+
? await downloadPackageFiles(fetchImpl, item.name, item.range, seen)
|
|
2624
|
+
: { ok: false, reason: `${item.name}: no fetch implementation available` };
|
|
2625
|
+
|
|
2626
|
+
if (!info.ok) {
|
|
2627
|
+
// Final fallback: an empty stub so offline demos still resolve the module.
|
|
2628
|
+
writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, {
|
|
2629
|
+
version: '0.0.0', entry: 'index.js', files: [{ rel: 'index.js', content: 'module.exports = {};\n' }]
|
|
2630
|
+
});
|
|
2631
|
+
if (!warning) warning = info.reason;
|
|
2632
|
+
installed.push({ name: item.name, version: '0.0.0' });
|
|
2633
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: '0.0.0', offline: true });
|
|
2634
|
+
continue;
|
|
2635
|
+
}
|
|
2636
|
+
|
|
2637
|
+
writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
|
|
2638
|
+
installed.push({ name: item.name, version: info.version || '1.0.0' });
|
|
2639
|
+
if (typeof lineCb === 'function') lineCb({ name: item.name, version: info.version || '1.0.0', deduped: Boolean(info.deduped) });
|
|
2640
|
+
if (item.direct) directVersion = info.version || null;
|
|
2641
|
+
|
|
2642
|
+
for (const dep of (info.deps || [])) {
|
|
2643
|
+
const parsed = parsePackageSpec(dep);
|
|
2644
|
+
if (parsed.name && !requested.has(parsed.name)) {
|
|
2645
|
+
requested.add(parsed.name);
|
|
2646
|
+
queue.push({ name: parsed.name, range: null, direct: false });
|
|
2647
|
+
}
|
|
2386
2648
|
}
|
|
2387
|
-
ctx.vfs.writeFileSync(modIndexPath, code);
|
|
2388
|
-
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modIndexPath);
|
|
2389
2649
|
}
|
|
2650
|
+
|
|
2651
|
+
pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
|
|
2652
|
+
writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
|
|
2653
|
+
|
|
2654
|
+
return { name: pkgName, ok: true, version: directVersion, installed, warning };
|
|
2655
|
+
}
|
|
2656
|
+
|
|
2657
|
+
// Build a live install log: each line is streamed to the terminal as it
|
|
2658
|
+
// happens (when possible) and accumulated so the command can also return it.
|
|
2659
|
+
function createInstallEmitter(ctx, sink) {
|
|
2660
|
+
const stream = (ctx && typeof ctx.onStdout === 'function') ? ctx.onStdout : null;
|
|
2661
|
+
return function emit(text) {
|
|
2662
|
+
if (!text) return;
|
|
2663
|
+
sink.push(text);
|
|
2664
|
+
if (stream) stream(text);
|
|
2665
|
+
};
|
|
2666
|
+
}
|
|
2667
|
+
|
|
2668
|
+
function formatInstallLine(info) {
|
|
2669
|
+
if (!info || !info.name) return '';
|
|
2670
|
+
const suffix = info.offline ? ' (offline fallback)' : (info.deduped ? ' (deduped)' : '');
|
|
2671
|
+
return ` + ${info.name}@${info.version || '1.0.0'}${suffix}\n`;
|
|
2672
|
+
}
|
|
2673
|
+
|
|
2674
|
+
function countInstalledPackages(results) {
|
|
2675
|
+
const seen = new Set();
|
|
2676
|
+
for (const r of results) {
|
|
2677
|
+
if (!r) continue;
|
|
2678
|
+
if (r.name) seen.add(r.name);
|
|
2679
|
+
for (const p of (r.installed || [])) { if (p && p.name) seen.add(p.name); }
|
|
2680
|
+
}
|
|
2681
|
+
return seen.size;
|
|
2682
|
+
}
|
|
2683
|
+
|
|
2684
|
+
// Resolve + install a list of specs while printing a realistic transcript,
|
|
2685
|
+
// so `npm install` / `bun add` look like the real tools instead of a terse
|
|
2686
|
+
// "saved N package(s)".
|
|
2687
|
+
async function runInstallTranscript(pkgs, ctx, opts) {
|
|
2688
|
+
const options = opts || {};
|
|
2689
|
+
const manager = options.manager || 'bun';
|
|
2690
|
+
const header = options.header || (manager === 'npm' ? 'npm install v10.2.0' : 'bun add v1.1.20 (1.1.20)');
|
|
2691
|
+
const out = [];
|
|
2692
|
+
const emit = createInstallEmitter(ctx, out);
|
|
2693
|
+
const started = Date.now();
|
|
2694
|
+
emit(`${header}\n\nResolving dependencies...\n`);
|
|
2695
|
+
const results = [];
|
|
2696
|
+
for (const p of pkgs) {
|
|
2697
|
+
results.push(await installPackage(p, ctx, { onLine: (info) => emit(formatInstallLine(info)), dev: Boolean(options.dev) }));
|
|
2698
|
+
}
|
|
2699
|
+
const warning = results.map(r => r && r.warning).filter(Boolean)[0];
|
|
2700
|
+
const count = countInstalledPackages(results);
|
|
2701
|
+
const ms = Date.now() - started;
|
|
2702
|
+
if (manager === 'npm') {
|
|
2703
|
+
emit(`\nadded ${count} package(s) in ${ms}ms\n`);
|
|
2704
|
+
} else if (manager === 'pnpm') {
|
|
2705
|
+
emit(`\nPackages: +${count}\n${'+'.repeat(Math.min(count, 40))}\nDone in ${ms}ms using pnpm v9.0.0\n`);
|
|
2706
|
+
} else {
|
|
2707
|
+
emit(`Saved lockfile\n\n${count} package(s) installed [${ms}ms]\n`);
|
|
2708
|
+
}
|
|
2709
|
+
return {
|
|
2710
|
+
code: 0,
|
|
2711
|
+
stdout: out.join(''),
|
|
2712
|
+
stderr: warning ? `${manager === 'npm' ? 'npm warn' : manager === 'pnpm' ? 'pnpm warn' : 'bun warn'} ${warning}\n` : ''
|
|
2713
|
+
};
|
|
2390
2714
|
}
|
|
2391
2715
|
|
|
2392
2716
|
function uninstallPackage(pkgName, ctx) {
|
|
@@ -2440,9 +2764,261 @@
|
|
|
2440
2764
|
if (scriptArgs && scriptArgs.length > 0) {
|
|
2441
2765
|
cmd += ' ' + scriptArgs.join(' ');
|
|
2442
2766
|
}
|
|
2767
|
+
const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
|
|
2768
|
+
if (fallback) return fallback;
|
|
2443
2769
|
return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
|
|
2444
2770
|
}
|
|
2445
2771
|
|
|
2772
|
+
// ---------------------------------------------------------------------------
|
|
2773
|
+
// Built-in static preview server (`serve` / `npm run dev` fallback).
|
|
2774
|
+
//
|
|
2775
|
+
// Serves the virtual filesystem over a virtual port so the in-browser Web
|
|
2776
|
+
// Preview can render a project. `.ts/.tsx/.jsx` sources are transpiled to
|
|
2777
|
+
// browser-native ESM on the fly, and bare specifiers are resolved to jsDelivr
|
|
2778
|
+
// `+esm` builds through an injected import map — no bundler required.
|
|
2779
|
+
// ---------------------------------------------------------------------------
|
|
2780
|
+
|
|
2781
|
+
const CDN_ESM_BASE = 'https://cdn.jsdelivr.net/npm';
|
|
2782
|
+
|
|
2783
|
+
const PREVIEW_MIME = {
|
|
2784
|
+
'.html': 'text/html; charset=utf-8',
|
|
2785
|
+
'.htm': 'text/html; charset=utf-8',
|
|
2786
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
2787
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
2788
|
+
'.cjs': 'text/javascript; charset=utf-8',
|
|
2789
|
+
'.jsx': 'text/javascript; charset=utf-8',
|
|
2790
|
+
'.ts': 'text/javascript; charset=utf-8',
|
|
2791
|
+
'.tsx': 'text/javascript; charset=utf-8',
|
|
2792
|
+
'.css': 'text/css; charset=utf-8',
|
|
2793
|
+
'.json': 'application/json; charset=utf-8',
|
|
2794
|
+
'.map': 'application/json; charset=utf-8',
|
|
2795
|
+
'.svg': 'image/svg+xml',
|
|
2796
|
+
'.png': 'image/png',
|
|
2797
|
+
'.jpg': 'image/jpeg',
|
|
2798
|
+
'.jpeg': 'image/jpeg',
|
|
2799
|
+
'.gif': 'image/gif',
|
|
2800
|
+
'.webp': 'image/webp',
|
|
2801
|
+
'.ico': 'image/x-icon',
|
|
2802
|
+
'.txt': 'text/plain; charset=utf-8'
|
|
2803
|
+
};
|
|
2804
|
+
|
|
2805
|
+
function previewMimeFor(p) {
|
|
2806
|
+
const lower = String(p).toLowerCase();
|
|
2807
|
+
const dot = lower.lastIndexOf('.');
|
|
2808
|
+
if (dot === -1) return 'application/octet-stream';
|
|
2809
|
+
return PREVIEW_MIME[lower.slice(dot)] || 'application/octet-stream';
|
|
2810
|
+
}
|
|
2811
|
+
|
|
2812
|
+
function isPreviewScriptPath(p) {
|
|
2813
|
+
return /\.(?:[cm]?jsx?|tsx?)$/i.test(p) && !/\.d\.ts$/i.test(p);
|
|
2814
|
+
}
|
|
2815
|
+
|
|
2816
|
+
// Collect bare (non-relative) module specifiers referenced by a source file.
|
|
2817
|
+
function extractBareSpecifiers(code) {
|
|
2818
|
+
const out = new Set();
|
|
2819
|
+
const patterns = [
|
|
2820
|
+
/\bfrom\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2821
|
+
/\brequire\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2822
|
+
/\bimport\s*\(\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g,
|
|
2823
|
+
/\bimport\s*['"]((?:@[^'"/]+\/)?[^'"./][^'"]*)['"]/g
|
|
2824
|
+
];
|
|
2825
|
+
for (const re of patterns) {
|
|
2826
|
+
let m;
|
|
2827
|
+
while ((m = re.exec(code)) !== null) {
|
|
2828
|
+
const spec = m[1];
|
|
2829
|
+
if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.includes(':')) continue;
|
|
2830
|
+
out.add(spec);
|
|
2831
|
+
}
|
|
2832
|
+
}
|
|
2833
|
+
return Array.from(out);
|
|
2834
|
+
}
|
|
2835
|
+
|
|
2836
|
+
function normalizeVersionRange(range) {
|
|
2837
|
+
if (!range || typeof range !== 'string') return 'latest';
|
|
2838
|
+
const v = range.trim();
|
|
2839
|
+
if (!v || v === '*' || /^(?:latest|next|beta|canary)$/.test(v)) return 'latest';
|
|
2840
|
+
if (/^(?:file|link|workspace|portal|git|https?):/.test(v)) return 'latest';
|
|
2841
|
+
return v.replace(/\s+/g, '').replace(/^[v=\s]+/, '') || 'latest';
|
|
2842
|
+
}
|
|
2843
|
+
|
|
2844
|
+
function resolveBareVersion(vfs, rootDir, pkgName) {
|
|
2845
|
+
try {
|
|
2846
|
+
const modPkg = PosixPath.join(rootDir, 'node_modules', pkgName, 'package.json');
|
|
2847
|
+
if (vfs.existsSync(modPkg)) {
|
|
2848
|
+
const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
|
|
2849
|
+
if (parsed && parsed.version) return parsed.version;
|
|
2850
|
+
}
|
|
2851
|
+
} catch (_) {}
|
|
2852
|
+
try {
|
|
2853
|
+
for (const dir of [rootDir, '/workspace']) {
|
|
2854
|
+
const pkgPath = PosixPath.join(dir, 'package.json');
|
|
2855
|
+
if (!vfs.existsSync(pkgPath)) continue;
|
|
2856
|
+
const parsed = JSON.parse(vfs.readFileSync(pkgPath, 'utf8'));
|
|
2857
|
+
const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
|
|
2858
|
+
if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
|
|
2859
|
+
}
|
|
2860
|
+
} catch (_) {}
|
|
2861
|
+
return 'latest';
|
|
2862
|
+
}
|
|
2863
|
+
|
|
2864
|
+
function cdnEsmUrl(pkgName, version, subpath) {
|
|
2865
|
+
const base = `${CDN_ESM_BASE}/${pkgName}@${version}`;
|
|
2866
|
+
const sub = subpath ? '/' + String(subpath).replace(/^\/+|\/+$/g, '') : '';
|
|
2867
|
+
return `${base}${sub}/+esm`;
|
|
2868
|
+
}
|
|
2869
|
+
|
|
2870
|
+
function buildPreviewImportMap(vfs, rootDir, specifiers) {
|
|
2871
|
+
const imports = {};
|
|
2872
|
+
for (const spec of specifiers) {
|
|
2873
|
+
const parts = String(spec).split('/');
|
|
2874
|
+
const pkgName = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
|
|
2875
|
+
if (!pkgName) continue;
|
|
2876
|
+
const subpath = spec.slice(pkgName.length).replace(/^\/+/, '');
|
|
2877
|
+
const version = resolveBareVersion(vfs, rootDir, pkgName);
|
|
2878
|
+
imports[spec] = cdnEsmUrl(pkgName, version, subpath || undefined);
|
|
2879
|
+
}
|
|
2880
|
+
return imports;
|
|
2881
|
+
}
|
|
2882
|
+
|
|
2883
|
+
function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
|
|
2884
|
+
const scripts = [];
|
|
2885
|
+
const walk = (dir, depth) => {
|
|
2886
|
+
if (depth > 8 || scripts.length >= maxFiles) return;
|
|
2887
|
+
let entries = [];
|
|
2888
|
+
try { entries = vfs.readdirSync(dir); } catch (_) { return; }
|
|
2889
|
+
for (const name of entries) {
|
|
2890
|
+
if (name === 'node_modules' || name.startsWith('.')) continue;
|
|
2891
|
+
const full = PosixPath.join(dir, name);
|
|
2892
|
+
let st;
|
|
2893
|
+
try { st = vfs.statSync(full); } catch (_) { continue; }
|
|
2894
|
+
const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
|
|
2895
|
+
if (dirFlag) {
|
|
2896
|
+
walk(full, depth + 1);
|
|
2897
|
+
} else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
|
|
2898
|
+
try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
|
|
2899
|
+
}
|
|
2900
|
+
}
|
|
2901
|
+
};
|
|
2902
|
+
walk(rootDir, 0);
|
|
2903
|
+
return scripts;
|
|
2904
|
+
}
|
|
2905
|
+
|
|
2906
|
+
function injectPreviewExtras(html, importMap) {
|
|
2907
|
+
let out = html;
|
|
2908
|
+
const importMapTag = `<script type="importmap">\n${JSON.stringify({ imports: importMap }, null, 2)}\n</script>`;
|
|
2909
|
+
if (/<head[^>]*>/i.test(out)) {
|
|
2910
|
+
out = out.replace(/<head[^>]*>/i, (m) => `${m}\n ${importMapTag}`);
|
|
2911
|
+
} else {
|
|
2912
|
+
out = importMapTag + '\n' + out;
|
|
2913
|
+
}
|
|
2914
|
+
const shim = '<script>window.__CODELAB_PREVIEW__ = true;</script>';
|
|
2915
|
+
if (/<\/body>/i.test(out)) out = out.replace(/<\/body>/i, `${shim}\n</body>`);
|
|
2916
|
+
else out = out + '\n' + shim;
|
|
2917
|
+
return out;
|
|
2918
|
+
}
|
|
2919
|
+
|
|
2920
|
+
function registerPreviewServer(ctx, rootDir, preferredPort) {
|
|
2921
|
+
const portTable = ctx.shell && ctx.shell.portTable;
|
|
2922
|
+
if (!portTable || typeof portTable.registerServer !== 'function') return null;
|
|
2923
|
+
|
|
2924
|
+
let port = Number(preferredPort) || 3000;
|
|
2925
|
+
const taken = new Set((typeof portTable.listServers === 'function' ? portTable.listServers() : []).map((s) => Number(s.port)));
|
|
2926
|
+
while (taken.has(port)) port++;
|
|
2927
|
+
|
|
2928
|
+
const specifiers = new Set();
|
|
2929
|
+
for (const content of collectPreviewScripts(ctx.vfs, rootDir)) {
|
|
2930
|
+
for (const s of extractBareSpecifiers(content)) specifiers.add(s);
|
|
2931
|
+
}
|
|
2932
|
+
const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
|
|
2933
|
+
|
|
2934
|
+
const exists = (p) => { try { return ctx.vfs.existsSync(p); } catch (_) { return false; } };
|
|
2935
|
+
const isDir = (p) => {
|
|
2936
|
+
try {
|
|
2937
|
+
const st = ctx.vfs.statSync(p);
|
|
2938
|
+
return Boolean(st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory));
|
|
2939
|
+
} catch (_) { return false; }
|
|
2940
|
+
};
|
|
2941
|
+
const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
|
|
2942
|
+
|
|
2943
|
+
const handler = async (request) => {
|
|
2944
|
+
let pathname = '/';
|
|
2945
|
+
try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
|
|
2946
|
+
const rel = pathname.replace(/^\/+/, '');
|
|
2947
|
+
let target = PosixPath.join(rootDir, rel);
|
|
2948
|
+
const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
|
|
2949
|
+
|
|
2950
|
+
if (!rel || pathname.endsWith('/') || isDir(target)) {
|
|
2951
|
+
target = PosixPath.join(target, 'index.html');
|
|
2952
|
+
}
|
|
2953
|
+
if (!exists(target) && !hasExt) {
|
|
2954
|
+
// Resolve extensionless module specifiers (e.g. `./components/Counter`)
|
|
2955
|
+
// the way a bundler / dev server would.
|
|
2956
|
+
const cands = [
|
|
2957
|
+
target + '.tsx', target + '.ts', target + '.jsx', target + '.js',
|
|
2958
|
+
target + '.mjs', target + '.cjs',
|
|
2959
|
+
PosixPath.join(target, 'index.tsx'), PosixPath.join(target, 'index.ts'),
|
|
2960
|
+
PosixPath.join(target, 'index.jsx'), PosixPath.join(target, 'index.js')
|
|
2961
|
+
];
|
|
2962
|
+
for (const c of cands) { if (exists(c)) { target = c; break; } }
|
|
2963
|
+
}
|
|
2964
|
+
if (!exists(target) && !hasExt) {
|
|
2965
|
+
target = PosixPath.join(rootDir, 'index.html'); // SPA fallback
|
|
2966
|
+
}
|
|
2967
|
+
if (!exists(target)) {
|
|
2968
|
+
return new Response(
|
|
2969
|
+
`<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
|
|
2970
|
+
{ status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
|
|
2971
|
+
);
|
|
2972
|
+
}
|
|
2973
|
+
|
|
2974
|
+
let body = readText(target);
|
|
2975
|
+
if (body === null) body = '';
|
|
2976
|
+
if (/\.html?$/i.test(target)) {
|
|
2977
|
+
body = injectPreviewExtras(body, importMap);
|
|
2978
|
+
} else if (isPreviewScriptPath(target)) {
|
|
2979
|
+
try {
|
|
2980
|
+
const rm = getRuntimeModule();
|
|
2981
|
+
if (rm && typeof rm.transpileForBrowser === 'function') {
|
|
2982
|
+
body = rm.transpileForBrowser(body, target);
|
|
2983
|
+
}
|
|
2984
|
+
} catch (_) {}
|
|
2985
|
+
}
|
|
2986
|
+
|
|
2987
|
+
return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
|
|
2988
|
+
};
|
|
2989
|
+
|
|
2990
|
+
const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
|
|
2991
|
+
return portTable.registerServer(port, {
|
|
2992
|
+
server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
|
|
2993
|
+
fetch: handler,
|
|
2994
|
+
name: 'code-lab-serve',
|
|
2995
|
+
pid,
|
|
2996
|
+
root: rootDir
|
|
2997
|
+
});
|
|
2998
|
+
}
|
|
2999
|
+
|
|
3000
|
+
// Common dev-server commands that cannot run inside the virtual runtime are
|
|
3001
|
+
// transparently redirected to the built-in preview server.
|
|
3002
|
+
const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
|
|
3003
|
+
|
|
3004
|
+
function tryDevScriptFallback(scriptName, cmd, ctx) {
|
|
3005
|
+
if (!PREVIEW_TOOL_RE.test(cmd)) return null;
|
|
3006
|
+
// Only fall back when the referenced tool is not actually installed.
|
|
3007
|
+
const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
|
|
3008
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
|
|
3009
|
+
if (ctx.vfs.existsSync(binPath)) return null;
|
|
3010
|
+
const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
|
|
3011
|
+
const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
|
|
3012
|
+
const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
|
|
3013
|
+
const entry = registerPreviewServer(ctx, ctx.cwd, port);
|
|
3014
|
+
if (!entry) return null;
|
|
3015
|
+
return {
|
|
3016
|
+
code: 0,
|
|
3017
|
+
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`,
|
|
3018
|
+
stderr: ''
|
|
3019
|
+
};
|
|
3020
|
+
}
|
|
3021
|
+
|
|
2446
3022
|
function evaluatePosixTest(args, ctx) {
|
|
2447
3023
|
const cleanArgs = [...args];
|
|
2448
3024
|
if (cleanArgs.length > 0 && cleanArgs[cleanArgs.length - 1] === ']') {
|
|
@@ -4941,7 +5517,8 @@
|
|
|
4941
5517
|
stdout += ' date, sleep, clear Date, delay, terminal screen control\n';
|
|
4942
5518
|
stdout += ' history, ps, jobs, kill Process and job management\n';
|
|
4943
5519
|
stdout += ' git [status diff log] Built-in version control\n';
|
|
4944
|
-
stdout += ' node, bun, npm, npx, bunx CLI runtime and package shims\n';
|
|
5520
|
+
stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
|
|
5521
|
+
stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
|
|
4945
5522
|
stdout += ' ports, curl Port table inspection & HTTP requests\n';
|
|
4946
5523
|
return { code: 0, stdout, stderr: '' };
|
|
4947
5524
|
},
|
|
@@ -5063,6 +5640,18 @@
|
|
|
5063
5640
|
|
|
5064
5641
|
const sub = args[0];
|
|
5065
5642
|
|
|
5643
|
+
if (sub === '--version' || sub === '-v' || sub === '--revision') {
|
|
5644
|
+
return { code: 0, stdout: '1.1.20\n', stderr: '' };
|
|
5645
|
+
}
|
|
5646
|
+
|
|
5647
|
+
if (sub === '--help' || sub === '-h') {
|
|
5648
|
+
return {
|
|
5649
|
+
code: 0,
|
|
5650
|
+
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',
|
|
5651
|
+
stderr: ''
|
|
5652
|
+
};
|
|
5653
|
+
}
|
|
5654
|
+
|
|
5066
5655
|
if (sub === 'init') {
|
|
5067
5656
|
const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
|
|
5068
5657
|
const dirName = PosixPath.basename(ctx.cwd) || 'app';
|
|
@@ -5112,12 +5701,27 @@
|
|
|
5112
5701
|
return { code: 0, stdout: 'Done! A package.json file was created in ' + ctx.cwd + '\n', stderr: '' };
|
|
5113
5702
|
}
|
|
5114
5703
|
|
|
5115
|
-
if (sub === '
|
|
5704
|
+
if (sub === 'install' || sub === 'i' || sub === 'ci') {
|
|
5116
5705
|
const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5117
|
-
|
|
5118
|
-
|
|
5706
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
5707
|
+
if (pkgs.length === 0) {
|
|
5708
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5709
|
+
const deps = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
5710
|
+
if (deps.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5711
|
+
return await runInstallTranscript(deps, ctx, { manager: 'bun', header: 'bun install v1.1.20 (1.1.20)' });
|
|
5119
5712
|
}
|
|
5120
|
-
return {
|
|
5713
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
5714
|
+
}
|
|
5715
|
+
|
|
5716
|
+
if (sub === 'add') {
|
|
5717
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5718
|
+
const dev = args.some(a => a === '-D' || a === '--dev' || a === '--save-dev' || a === '-d');
|
|
5719
|
+
if (pkgs.length === 0) {
|
|
5720
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5721
|
+
pkgs = Object.keys(pkgData.dependencies || {});
|
|
5722
|
+
}
|
|
5723
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5724
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'bun', dev, header: 'bun add v1.1.20 (1.1.20)' });
|
|
5121
5725
|
}
|
|
5122
5726
|
|
|
5123
5727
|
if (sub === 'remove' || sub === 'rm') {
|
|
@@ -5277,18 +5881,14 @@
|
|
|
5277
5881
|
}
|
|
5278
5882
|
|
|
5279
5883
|
if (sub === 'i' || sub === 'install' || sub === 'add') {
|
|
5280
|
-
|
|
5884
|
+
let pkgs = args.slice(1).filter(a => !a.startsWith('-'));
|
|
5885
|
+
const dev = args.some(a => a === '-D' || a === '--save-dev' || a === '--dev');
|
|
5281
5886
|
if (pkgs.length === 0) {
|
|
5282
5887
|
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5283
|
-
|
|
5284
|
-
|
|
5285
|
-
}
|
|
5286
|
-
return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5888
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
5889
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'up to date\n', stderr: '' };
|
|
5287
5890
|
}
|
|
5288
|
-
|
|
5289
|
-
installPackage(p, ctx);
|
|
5290
|
-
}
|
|
5291
|
-
return { code: 0, stdout: `added ${pkgs.length} package(s) in 0.1s\n`, stderr: '' };
|
|
5891
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'npm', dev, header: 'npm install v10.2.0' });
|
|
5292
5892
|
}
|
|
5293
5893
|
|
|
5294
5894
|
if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
|
|
@@ -5340,6 +5940,123 @@
|
|
|
5340
5940
|
return await this.npx(args, ctx);
|
|
5341
5941
|
},
|
|
5342
5942
|
|
|
5943
|
+
async pnpm(args, ctx) {
|
|
5944
|
+
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
|
5945
|
+
return {
|
|
5946
|
+
code: 0,
|
|
5947
|
+
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',
|
|
5948
|
+
stderr: ''
|
|
5949
|
+
};
|
|
5950
|
+
}
|
|
5951
|
+
const sub = args[0];
|
|
5952
|
+
if (sub === '--version' || sub === '-v') {
|
|
5953
|
+
return { code: 0, stdout: '9.0.0\n', stderr: '' };
|
|
5954
|
+
}
|
|
5955
|
+
const dev = args.some((a) => a === '-D' || a === '--save-dev' || a === '--dev' || a === '-d');
|
|
5956
|
+
|
|
5957
|
+
if (sub === 'init') {
|
|
5958
|
+
const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
|
|
5959
|
+
if (!ctx.vfs.existsSync(pkgPath)) {
|
|
5960
|
+
ctx.vfs.writeFileSync(pkgPath, JSON.stringify({
|
|
5961
|
+
name: PosixPath.basename(ctx.cwd) || 'app',
|
|
5962
|
+
version: '1.0.0',
|
|
5963
|
+
main: 'index.js',
|
|
5964
|
+
scripts: { test: 'echo "Error: no test specified" && exit 1' }
|
|
5965
|
+
}, null, 2) + '\n');
|
|
5966
|
+
if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', pkgPath);
|
|
5967
|
+
}
|
|
5968
|
+
return { code: 0, stdout: 'Wrote to ' + pkgPath + '\n', stderr: '' };
|
|
5969
|
+
}
|
|
5970
|
+
|
|
5971
|
+
if (sub === 'install' || sub === 'i' || sub === 'add') {
|
|
5972
|
+
let pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
5973
|
+
if (pkgs.length === 0) {
|
|
5974
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
5975
|
+
pkgs = Object.keys(Object.assign({}, pkgData.dependencies || {}, pkgData.devDependencies || {}));
|
|
5976
|
+
if (pkgs.length === 0) return { code: 0, stdout: 'Already up to date\n', stderr: '' };
|
|
5977
|
+
}
|
|
5978
|
+
const verb = (sub === 'add') ? 'add' : 'install';
|
|
5979
|
+
return await runInstallTranscript(pkgs, ctx, { manager: 'pnpm', dev, header: `pnpm ${verb} v9.0.0` });
|
|
5980
|
+
}
|
|
5981
|
+
|
|
5982
|
+
if (sub === 'remove' || sub === 'rm' || sub === 'uninstall') {
|
|
5983
|
+
const pkgs = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
5984
|
+
for (const p of pkgs) uninstallPackage(p, ctx);
|
|
5985
|
+
return { code: 0, stdout: `removed ${pkgs.length} package(s)\n`, stderr: '' };
|
|
5986
|
+
}
|
|
5987
|
+
|
|
5988
|
+
if (sub === 'list' || sub === 'ls') {
|
|
5989
|
+
return { code: 0, stdout: listDependencies(ctx), stderr: '' };
|
|
5990
|
+
}
|
|
5991
|
+
|
|
5992
|
+
if (sub === 'run' || sub === 'run-script') {
|
|
5993
|
+
const scriptName = args[1];
|
|
5994
|
+
if (!scriptName) return { code: 1, stdout: '', stderr: 'pnpm: missing script name\n' };
|
|
5995
|
+
return await runPackageScript(scriptName, args.slice(2), ctx);
|
|
5996
|
+
}
|
|
5997
|
+
|
|
5998
|
+
if (sub === 'test') {
|
|
5999
|
+
return await runPackageScript('test', args.slice(1), ctx);
|
|
6000
|
+
}
|
|
6001
|
+
|
|
6002
|
+
if (sub === 'exec') {
|
|
6003
|
+
const cmd = args[1];
|
|
6004
|
+
if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
|
|
6005
|
+
const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
|
|
6006
|
+
if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
|
|
6007
|
+
return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
|
|
6008
|
+
}
|
|
6009
|
+
|
|
6010
|
+
if (sub === 'dlx') {
|
|
6011
|
+
return await this.npx(args.slice(1), ctx);
|
|
6012
|
+
}
|
|
6013
|
+
|
|
6014
|
+
const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
|
|
6015
|
+
if (pkgData.scripts && pkgData.scripts[sub]) {
|
|
6016
|
+
return await runPackageScript(sub, args.slice(1), ctx);
|
|
6017
|
+
}
|
|
6018
|
+
|
|
6019
|
+
return { code: 1, stdout: '', stderr: `ERR_PNPM_RECURSIVE_EXEC_FIRST_FAIL Unknown command: "${sub}"\n` };
|
|
6020
|
+
},
|
|
6021
|
+
|
|
6022
|
+
async serve(args, ctx) {
|
|
6023
|
+
if (args[0] === '--help' || args[0] === '-h') {
|
|
6024
|
+
return {
|
|
6025
|
+
code: 0,
|
|
6026
|
+
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',
|
|
6027
|
+
stderr: ''
|
|
6028
|
+
};
|
|
6029
|
+
}
|
|
6030
|
+
const rootArg = (() => {
|
|
6031
|
+
const positionals = [];
|
|
6032
|
+
for (let i = 0; i < args.length; i++) {
|
|
6033
|
+
const a = args[i];
|
|
6034
|
+
if (a === '--port' || a === '-p') { i++; continue; }
|
|
6035
|
+
if (a.startsWith('-')) continue;
|
|
6036
|
+
positionals.push(a);
|
|
6037
|
+
}
|
|
6038
|
+
return positionals[0];
|
|
6039
|
+
})();
|
|
6040
|
+
let port = 3000;
|
|
6041
|
+
for (let i = 0; i < args.length; i++) {
|
|
6042
|
+
if ((args[i] === '--port' || args[i] === '-p') && args[i + 1]) { port = Number(args[i + 1]) || port; i++; }
|
|
6043
|
+
else if (args[i].startsWith('--port=')) port = Number(args[i].split('=')[1]) || port;
|
|
6044
|
+
}
|
|
6045
|
+
const rootDir = ctx.resolvePath(rootArg || '.');
|
|
6046
|
+
if (!ctx.vfs.existsSync(rootDir)) {
|
|
6047
|
+
return { code: 1, stdout: '', stderr: `serve: ${rootArg}: No such file or directory\n` };
|
|
6048
|
+
}
|
|
6049
|
+
const entry = registerPreviewServer(ctx, rootDir, port);
|
|
6050
|
+
if (!entry) {
|
|
6051
|
+
return { code: 1, stdout: '', stderr: 'serve: no virtual port table available\n' };
|
|
6052
|
+
}
|
|
6053
|
+
return {
|
|
6054
|
+
code: 0,
|
|
6055
|
+
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`,
|
|
6056
|
+
stderr: ''
|
|
6057
|
+
};
|
|
6058
|
+
},
|
|
6059
|
+
|
|
5343
6060
|
// -----------------------------------------------------------------------
|
|
5344
6061
|
// Port Table & HTTP Inspection: ports, curl
|
|
5345
6062
|
// -----------------------------------------------------------------------
|
|
@@ -5513,6 +6230,16 @@
|
|
|
5513
6230
|
return PosixPath.resolve(this.cwd, p);
|
|
5514
6231
|
}
|
|
5515
6232
|
|
|
6233
|
+
// True when `name` resolves to a shell function or coreutil (used by the
|
|
6234
|
+
// workbench to route recognised commands straight to the shell instead of
|
|
6235
|
+
// treating flag-looking input such as `node --version` as a JS expression).
|
|
6236
|
+
hasCommand(name) {
|
|
6237
|
+
if (!name) return false;
|
|
6238
|
+
const n = String(name);
|
|
6239
|
+
if (this.functions && Object.prototype.hasOwnProperty.call(this.functions, n)) return true;
|
|
6240
|
+
return !!this.commands && Object.prototype.hasOwnProperty.call(this.commands, n);
|
|
6241
|
+
}
|
|
6242
|
+
|
|
5516
6243
|
_emitVfsMutation(type, absPath) {
|
|
5517
6244
|
if (!this.vfs) return;
|
|
5518
6245
|
const evt = { type, path: absPath, timestamp: Date.now() };
|