@innovatorved/code-lab 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/shell.ts CHANGED
@@ -2025,6 +2025,16 @@ function __initShellModule(root: any) {
2025
2025
  const requestedBranch = options.branch || parsed.branch || null;
2026
2026
  const { owner, repo } = parsed;
2027
2027
 
2028
+ const signal = options.signal || null;
2029
+ const throwIfAborted = () => {
2030
+ if (signal && signal.aborted) {
2031
+ const abortErr = new Error('fatal: clone cancelled (SIGINT)');
2032
+ abortErr.name = 'AbortError';
2033
+ throw abortErr;
2034
+ }
2035
+ };
2036
+ throwIfAborted();
2037
+
2028
2038
  if (onProgress) {
2029
2039
  onProgress({
2030
2040
  phase: 'metadata',
@@ -2040,7 +2050,8 @@ function __initShellModule(root: any) {
2040
2050
  try {
2041
2051
  if (!resolvedBranch) {
2042
2052
  const metaRes = await fetchFn(`https://api.github.com/repos/${owner}/${repo}`, {
2043
- headers: { Accept: 'application/vnd.github.v3+json' }
2053
+ headers: { Accept: 'application/vnd.github.v3+json' },
2054
+ signal
2044
2055
  });
2045
2056
  if (metaRes.status === 404) {
2046
2057
  repoNotFound = true;
@@ -2058,9 +2069,10 @@ function __initShellModule(root: any) {
2058
2069
  : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
2059
2070
 
2060
2071
  for (const cand of branchCandidates) {
2072
+ throwIfAborted();
2061
2073
  const treeRes = await fetchFn(
2062
2074
  `https://api.github.com/repos/${owner}/${repo}/git/trees/${encodeURIComponent(cand)}?recursive=1`,
2063
- { headers: { Accept: 'application/vnd.github.v3+json' } }
2075
+ { headers: { Accept: 'application/vnd.github.v3+json' }, signal }
2064
2076
  );
2065
2077
  if (treeRes.ok) {
2066
2078
  const treeJson = await treeRes.json();
@@ -2086,8 +2098,10 @@ function __initShellModule(root: any) {
2086
2098
  : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
2087
2099
 
2088
2100
  for (const cand of branchCandidates) {
2101
+ throwIfAborted();
2089
2102
  const flatRes = await fetchFn(
2090
- `https://data.jsdelivr.com/v1/package/gh/${owner}/${repo}@${encodeURIComponent(cand)}/flat`
2103
+ `https://data.jsdelivr.com/v1/package/gh/${owner}/${repo}@${encodeURIComponent(cand)}/flat`,
2104
+ { signal }
2091
2105
  );
2092
2106
  if (flatRes && flatRes.ok) {
2093
2107
  const flatJson = await flatRes.json();
@@ -2161,28 +2175,34 @@ function __initShellModule(root: any) {
2161
2175
  const BATCH_SIZE = 12;
2162
2176
 
2163
2177
  for (let i = 0; i < selectedFiles.length; i += BATCH_SIZE) {
2178
+ throwIfAborted();
2164
2179
  const batch = selectedFiles.slice(i, i + BATCH_SIZE);
2165
2180
  await Promise.all(
2166
2181
  batch.map(async (entry) => {
2182
+ throwIfAborted();
2167
2183
  const encodedPath = entry.repoPath.split('/').map(encodeURIComponent).join('/');
2168
2184
  const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
2169
2185
  const cdnUrl = `https://cdn.jsdelivr.net/gh/${owner}/${repo}@${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
2170
2186
 
2171
2187
  let text = null;
2172
2188
  try {
2173
- const r1 = await fetchFn(rawUrl);
2189
+ const r1 = await fetchFn(rawUrl, { signal });
2174
2190
  if (r1 && r1.ok) {
2175
2191
  text = await r1.text();
2176
2192
  }
2177
- } catch (_) {}
2193
+ } catch (_) {
2194
+ if (signal && signal.aborted) throw _;
2195
+ }
2178
2196
 
2179
2197
  if (text === null) {
2180
2198
  try {
2181
- const r2 = await fetchFn(cdnUrl);
2199
+ const r2 = await fetchFn(cdnUrl, { signal });
2182
2200
  if (r2 && r2.ok) {
2183
2201
  text = await r2.text();
2184
2202
  }
2185
- } catch (_) {}
2203
+ } catch (_) {
2204
+ if (signal && signal.aborted) throw _;
2205
+ }
2186
2206
  }
2187
2207
 
2188
2208
  if (text !== null && text.length <= maxFileSize) {
@@ -2213,6 +2233,8 @@ function __initShellModule(root: any) {
2213
2233
  );
2214
2234
  }
2215
2235
 
2236
+ throwIfAborted();
2237
+
2216
2238
  if (onProgress) {
2217
2239
  onProgress({
2218
2240
  phase: 'mounting',
@@ -2238,7 +2260,7 @@ function __initShellModule(root: any) {
2238
2260
  try {
2239
2261
  const commitsRes = await fetchFn(
2240
2262
  `https://api.github.com/repos/${owner}/${repo}/commits?sha=${encodeURIComponent(resolvedBranch)}&per_page=10`,
2241
- { headers: { Accept: 'application/vnd.github.v3+json' } }
2263
+ { headers: { Accept: 'application/vnd.github.v3+json' }, signal }
2242
2264
  );
2243
2265
  if (commitsRes && commitsRes.ok) {
2244
2266
  const commitsJson = await commitsRes.json();
@@ -2364,38 +2386,221 @@ function __initShellModule(root: any) {
2364
2386
  } catch (_) {}
2365
2387
  }
2366
2388
 
2367
- function installPackage(pkgSpec, ctx) {
2368
- const parts = pkgSpec.split('@').filter(Boolean);
2369
- const pkgName = pkgSpec.startsWith('@') ? '@' + parts[0] : parts[0];
2370
- const pkgVersion = parts[1] || '^1.0.0';
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
+ };
2402
+
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
+ }
2410
+
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
+ }
2423
+
2424
+ function resolveEntryRelPath(pkgJson) {
2425
+ let entry = pkgJson.main || pkgJson.module ||
2426
+ (typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
2427
+ entry = String(entry).replace(/^[./]+/, '');
2428
+ return entry || 'index.js';
2429
+ }
2430
+
2431
+ function stripRelPath(rel) {
2432
+ return String(rel || '').replace(/^[./]+/, '');
2433
+ }
2434
+
2435
+ function extractRelativeSpecifiers(code) {
2436
+ const out = new Set();
2437
+ const re = /(?:\brequire\s*\(\s*|\bimport\s+[\s\S]{0,120}?\bfrom\s*|\bimport\s*\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g;
2438
+ let m;
2439
+ while ((m = re.exec(code)) !== null) out.add(m[1]);
2440
+ return Array.from(out);
2441
+ }
2442
+
2443
+ function normalizeRelPath(baseDir, rel) {
2444
+ const parts = String(baseDir || '').split('/').filter(Boolean);
2445
+ for (const seg of String(rel).split('/')) {
2446
+ if (!seg || seg === '.') continue;
2447
+ if (seg === '..') parts.pop();
2448
+ else parts.push(seg);
2449
+ }
2450
+ return parts.join('/');
2451
+ }
2452
+
2453
+ async function fetchTextFromCdn(fetchImpl, url) {
2454
+ try {
2455
+ const res = await fetchImpl(url);
2456
+ if (!res) return null;
2457
+ const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
2458
+ if (!ok) return null;
2459
+ if (typeof res.text === 'function') return await res.text();
2460
+ return String(res.body != null ? res.body : '');
2461
+ } catch (_) {
2462
+ return null;
2463
+ }
2464
+ }
2465
+
2466
+ async function resolvePackageMetadata(fetchImpl, name, range) {
2467
+ const urls = range
2468
+ ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
2469
+ : [`${CDN_NPM_BASE}/${name}/package.json`];
2470
+ for (const url of urls) {
2471
+ const text = await fetchTextFromCdn(fetchImpl, url);
2472
+ if (!text) continue;
2473
+ try {
2474
+ const parsed = JSON.parse(text);
2475
+ if (parsed && parsed.version) return parsed;
2476
+ } catch (_) {}
2477
+ }
2478
+ return null;
2479
+ }
2480
+
2481
+ // Download a package's entry module, its relative submodules and record its
2482
+ // declared dependencies so the caller can resolve them transitively.
2483
+ async function downloadPackageFiles(fetchImpl, name, range, seen) {
2484
+ const meta = await resolvePackageMetadata(fetchImpl, name, range);
2485
+ if (!meta) {
2486
+ const fallback = OFFLINE_PACKAGE_FALLBACKS[name];
2487
+ if (fallback) {
2488
+ const v = range ? range.replace(/^[\^~>=<\s]+/, '') || '1.0.0' : '1.0.0';
2489
+ return { ok: true, offline: true, version: v, entry: 'index.js', files: [{ rel: 'index.js', content: fallback }], deps: [] };
2490
+ }
2491
+ return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
2492
+ }
2493
+
2494
+ const version = meta.version;
2495
+ const key = `${name}@${version}`;
2496
+ if (seen.has(key)) {
2497
+ return { ok: true, deduped: true, version, entry: resolveEntryRelPath(meta), files: [], deps: [] };
2498
+ }
2499
+ seen.add(key);
2500
+
2501
+ const entry = resolveEntryRelPath(meta);
2502
+ const files = [];
2503
+ const visited = new Set();
2504
+ const queue = [entry];
2505
+ while (queue.length > 0) {
2506
+ const rel = stripRelPath(queue.shift());
2507
+ if (!rel || visited.has(rel)) continue;
2508
+ visited.add(rel);
2509
+ const text = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`);
2510
+ if (text === null) continue;
2511
+ files.push({ rel, content: text });
2512
+ const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
2513
+ for (const spec of extractRelativeSpecifiers(text)) {
2514
+ const target = normalizeRelPath(baseDir, spec);
2515
+ for (const cand of [target, `${target}.js`, `${target}.json`, `${target}/index.js`]) {
2516
+ const c = stripRelPath(cand);
2517
+ if (c && !visited.has(c)) { queue.push(cand); break; }
2518
+ }
2519
+ }
2520
+ }
2521
+ // The declared entry may be missing on the CDN; fall back to index.js.
2522
+ if (!files.some(f => f.rel === entry)) {
2523
+ const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
2524
+ if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
2525
+ }
2526
+
2527
+ return { ok: true, version, entry, files, deps: Object.keys(meta.dependencies || {}) };
2528
+ }
2529
+
2530
+ function installTargetDirs(ctx, name) {
2531
+ const dirs = ['/workspace/node_modules/' + name];
2532
+ const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', name);
2533
+ if (!dirs.includes(cwdTarget)) dirs.push(cwdTarget);
2534
+ return dirs;
2535
+ }
2536
+
2537
+ function writeInstalledPackageFiles(ctx, dirs, name, info) {
2538
+ for (const dir of dirs) {
2539
+ ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
2540
+ for (const f of info.files) {
2541
+ const full = PosixPath.join(dir, f.rel);
2542
+ ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
2543
+ ctx.vfs.writeFileSync(full, f.content);
2544
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
2545
+ }
2546
+ const modPkgPath = PosixPath.join(dir, 'package.json');
2547
+ const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
2548
+ ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
2549
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
2550
+ }
2551
+ }
2552
+
2553
+ async function installPackage(pkgSpec, ctx) {
2554
+ const { name: pkgName, range } = parsePackageSpec(pkgSpec);
2555
+ if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
2371
2556
 
2372
2557
  const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
2373
2558
  if (!pkgData.dependencies) pkgData.dependencies = {};
2374
- pkgData.dependencies[pkgName] = pkgVersion;
2375
- writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
2376
2559
 
2377
- const targetDirs = ['/workspace/node_modules/' + pkgName];
2378
- const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', pkgName);
2379
- if (!targetDirs.includes(cwdTarget)) targetDirs.push(cwdTarget);
2560
+ const fetchImpl = packageCtxFetch(ctx);
2561
+ const seen = (ctx.shell && ctx.shell._cdnSeen)
2562
+ ? ctx.shell._cdnSeen
2563
+ : (ctx.shell ? (ctx.shell._cdnSeen = new Set()) : new Set());
2564
+
2565
+ const queue = [{ name: pkgName, range, direct: true }];
2566
+ const requested = new Set([pkgName]);
2567
+ const installed = [];
2568
+ let warning = null;
2569
+ let directVersion = null;
2570
+
2571
+ while (queue.length > 0) {
2572
+ const item = queue.shift();
2573
+ const info = fetchImpl
2574
+ ? await downloadPackageFiles(fetchImpl, item.name, item.range, seen)
2575
+ : { ok: false, reason: `${item.name}: no fetch implementation available` };
2576
+
2577
+ if (!info.ok) {
2578
+ // Final fallback: an empty stub so offline demos still resolve the module.
2579
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, {
2580
+ version: '0.0.0', entry: 'index.js', files: [{ rel: 'index.js', content: 'module.exports = {};\n' }]
2581
+ });
2582
+ if (!warning) warning = info.reason;
2583
+ installed.push({ name: item.name, version: '0.0.0' });
2584
+ continue;
2585
+ }
2380
2586
 
2381
- for (const modDir of targetDirs) {
2382
- ensureDirSync(ctx.vfs, modDir, ctx.emitMutation);
2383
- const modPkgPath = PosixPath.join(modDir, 'package.json');
2384
- const modIndexPath = PosixPath.join(modDir, 'index.js');
2385
- ctx.vfs.writeFileSync(modPkgPath, JSON.stringify({ name: pkgName, version: pkgVersion.replace(/^[\^~]/, ''), main: './index.js' }, null, 2) + '\n');
2386
- if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
2587
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
2588
+ installed.push({ name: item.name, version: info.version || '1.0.0' });
2589
+ if (item.direct) directVersion = info.version || null;
2387
2590
 
2388
- let code = 'module.exports = {};\n';
2389
- if (pkgName === 'is-even') {
2390
- code = 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n';
2391
- } else if (pkgName === 'tiny-invariant') {
2392
- code = 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n';
2393
- } else if (pkgName === 'lodash') {
2394
- code = 'module.exports = { isArray: Array.isArray, isObject: function(v) { return v !== null && typeof v === "object"; } };\n';
2591
+ for (const dep of (info.deps || [])) {
2592
+ const parsed = parsePackageSpec(dep);
2593
+ if (parsed.name && !requested.has(parsed.name)) {
2594
+ requested.add(parsed.name);
2595
+ queue.push({ name: parsed.name, range: null, direct: false });
2596
+ }
2395
2597
  }
2396
- ctx.vfs.writeFileSync(modIndexPath, code);
2397
- if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modIndexPath);
2398
2598
  }
2599
+
2600
+ pkgData.dependencies[pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData.dependencies[pkgName] || 'latest'));
2601
+ writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
2602
+
2603
+ return { name: pkgName, ok: true, version: directVersion, installed, warning };
2399
2604
  }
2400
2605
 
2401
2606
  function uninstallPackage(pkgName, ctx) {
@@ -4499,6 +4704,7 @@ function __initShellModule(root: any) {
4499
4704
  targetDir,
4500
4705
  branch: branchOpt,
4501
4706
  fetchImpl: ctx.shell && ctx.shell.options ? ctx.shell.options.fetchImpl : undefined,
4707
+ signal: ctx.signal,
4502
4708
  onFile: (absPath) => ctx.emitMutation('create', absPath),
4503
4709
  onProgress: (ev) => {
4504
4710
  if (!ev) return;
@@ -4539,6 +4745,9 @@ function __initShellModule(root: any) {
4539
4745
  `Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`;
4540
4746
  return { code: 0, stdout, stderr: '' };
4541
4747
  } catch (err) {
4748
+ if (ctx.signal && ctx.signal.aborted) {
4749
+ return { code: 130, stdout: '', stderr: '', aborted: true };
4750
+ }
4542
4751
  const msg = err && err.message ? err.message : String(err);
4543
4752
  if (canStream) streamLine(msg.endsWith('\n') ? msg : msg + '\n');
4544
4753
  return { code: 128, stdout: '', stderr: (msg.endsWith('\n') ? msg : msg + '\n') };
@@ -4866,6 +5075,7 @@ function __initShellModule(root: any) {
4866
5075
  targetDir: repoRoot,
4867
5076
  branch: gitState.branch,
4868
5077
  fetchImpl: ctx.shell && ctx.shell.options ? ctx.shell.options.fetchImpl : undefined,
5078
+ signal: ctx.signal,
4869
5079
  onFile: (absPath) => ctx.emitMutation('change', absPath)
4870
5080
  });
4871
5081
  gitState.headSnapshot = Object.assign({}, result.headSnapshot);
@@ -4875,6 +5085,9 @@ function __initShellModule(root: any) {
4875
5085
  stderr: ''
4876
5086
  };
4877
5087
  } catch (err) {
5088
+ if (ctx.signal && ctx.signal.aborted) {
5089
+ return { code: 130, stdout: '', stderr: '', aborted: true };
5090
+ }
4878
5091
  const msg = err && err.message ? err.message : String(err);
4879
5092
  return { code: 1, stdout: '', stderr: (msg.endsWith('\n') ? msg : msg + '\n') };
4880
5093
  }
@@ -5064,6 +5277,18 @@ function __initShellModule(root: any) {
5064
5277
 
5065
5278
  const sub = args[0];
5066
5279
 
5280
+ if (sub === '--version' || sub === '-v' || sub === '--revision') {
5281
+ return { code: 0, stdout: '1.1.20\n', stderr: '' };
5282
+ }
5283
+
5284
+ if (sub === '--help' || sub === '-h') {
5285
+ return {
5286
+ code: 0,
5287
+ 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',
5288
+ stderr: ''
5289
+ };
5290
+ }
5291
+
5067
5292
  if (sub === 'init') {
5068
5293
  const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
5069
5294
  const dirName = PosixPath.basename(ctx.cwd) || 'app';
@@ -5113,12 +5338,28 @@ function __initShellModule(root: any) {
5113
5338
  return { code: 0, stdout: 'Done! A package.json file was created in ' + ctx.cwd + '\n', stderr: '' };
5114
5339
  }
5115
5340
 
5116
- if (sub === 'add') {
5341
+ if (sub === 'install' || sub === 'i' || sub === 'ci') {
5117
5342
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5118
- for (const p of pkgs) {
5119
- installPackage(p, ctx);
5343
+ if (pkgs.length === 0) {
5344
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5345
+ const deps = Object.keys(pkgData.dependencies || {});
5346
+ const results = [];
5347
+ for (const p of deps) results.push(await installPackage(p, ctx));
5348
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5349
+ return { code: 0, stdout: deps.length === 0 ? 'up to date\n' : `installed ${deps.length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5120
5350
  }
5121
- return { code: 0, stdout: `saved ${pkgs.length} package(s)\n`, stderr: '' };
5351
+ const results = [];
5352
+ for (const p of pkgs) results.push(await installPackage(p, ctx));
5353
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5354
+ return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5355
+ }
5356
+
5357
+ if (sub === 'add') {
5358
+ const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5359
+ const results = [];
5360
+ for (const p of pkgs) results.push(await installPackage(p, ctx));
5361
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5362
+ return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
5122
5363
  }
5123
5364
 
5124
5365
  if (sub === 'remove' || sub === 'rm') {
@@ -5281,15 +5522,19 @@ function __initShellModule(root: any) {
5281
5522
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
5282
5523
  if (pkgs.length === 0) {
5283
5524
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
5525
+ const results = [];
5284
5526
  for (const p of Object.keys(pkgData.dependencies || {})) {
5285
- installPackage(p, ctx);
5527
+ results.push(await installPackage(p, ctx));
5286
5528
  }
5287
- return { code: 0, stdout: 'up to date\n', stderr: '' };
5529
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5530
+ return { code: 0, stdout: 'up to date\n', stderr: warning ? `npm warn ${warning}\n` : '' };
5288
5531
  }
5532
+ const results = [];
5289
5533
  for (const p of pkgs) {
5290
- installPackage(p, ctx);
5534
+ results.push(await installPackage(p, ctx));
5291
5535
  }
5292
- return { code: 0, stdout: `added ${pkgs.length} package(s) in 0.1s\n`, stderr: '' };
5536
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
5537
+ return { code: 0, stdout: `added ${results.filter(r => r && r.name).length} package(s) in 0.1s\n`, stderr: warning ? `npm warn ${warning}\n` : '' };
5293
5538
  }
5294
5539
 
5295
5540
  if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
@@ -5514,6 +5759,16 @@ function __initShellModule(root: any) {
5514
5759
  return PosixPath.resolve(this.cwd, p);
5515
5760
  }
5516
5761
 
5762
+ // True when `name` resolves to a shell function or coreutil (used by the
5763
+ // workbench to route recognised commands straight to the shell instead of
5764
+ // treating flag-looking input such as `node --version` as a JS expression).
5765
+ hasCommand(name) {
5766
+ if (!name) return false;
5767
+ const n = String(name);
5768
+ if (this.functions && Object.prototype.hasOwnProperty.call(this.functions, n)) return true;
5769
+ return !!this.commands && Object.prototype.hasOwnProperty.call(this.commands, n);
5770
+ }
5771
+
5517
5772
  _emitVfsMutation(type, absPath) {
5518
5773
  if (!this.vfs) return;
5519
5774
  const evt = { type, path: absPath, timestamp: Date.now() };