@innovatorved/code-lab 0.1.3 → 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/dist/code-lab.js CHANGED
@@ -4682,8 +4682,22 @@ function __initVirtualRuntime(rootScope) {
4682
4682
  }
4683
4683
 
4684
4684
  const _npmPackageCache = new Map();
4685
+ const _npmMetadataCache = new Map();
4686
+
4687
+ async function preloadNpmPackages(files = {}, secondArg = null, thirdArg = null) {
4688
+ // The 2nd/3rd arguments are overloaded for backwards compatibility:
4689
+ // preloadNpmPackages(files)
4690
+ // preloadNpmPackages(files, onProgress) // progress callback (used by the Workbench)
4691
+ // preloadNpmPackages(files, existingCache) // package-text cache (Map)
4692
+ // preloadNpmPackages(files, existingCache, onProgress)
4693
+ const isCacheLike = (v) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
4694
+ let onProgress = null;
4695
+ let existingCache = _npmPackageCache;
4696
+ if (typeof secondArg === 'function') onProgress = secondArg;
4697
+ else if (isCacheLike(secondArg)) existingCache = secondArg;
4698
+ if (typeof thirdArg === 'function') onProgress = onProgress || thirdArg;
4699
+ else if (isCacheLike(thirdArg)) existingCache = thirdArg;
4685
4700
 
4686
- async function preloadNpmPackages(files = {}, existingCache = _npmPackageCache) {
4687
4701
  const specs = new Set();
4688
4702
  const builtinSet = new Set([
4689
4703
  'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
@@ -4719,20 +4733,51 @@ function __initVirtualRuntime(rootScope) {
4719
4733
  while ((m = impRe.exec(content)) !== null) addSpec(m[1]);
4720
4734
  }
4721
4735
 
4736
+ // Follow declared dependencies transitively (best effort, bounded). Metadata
4737
+ // is memoised across calls so repeated preloads stay cheap.
4738
+ if (typeof fetch === 'function') {
4739
+ let pass = 0;
4740
+ while (pass < 6) {
4741
+ const pending = [];
4742
+ for (const pkg of specs) {
4743
+ if (!_npmMetadataCache.has(pkg)) pending.push(pkg);
4744
+ }
4745
+ if (pending.length === 0) break;
4746
+ pass++;
4747
+ await Promise.all(pending.map(async (pkg) => {
4748
+ let deps = [];
4749
+ try {
4750
+ const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}/package.json`);
4751
+ if (res && res.ok) {
4752
+ const meta = await res.json();
4753
+ deps = Object.keys((meta && meta.dependencies) || {});
4754
+ }
4755
+ } catch (_) {}
4756
+ _npmMetadataCache.set(pkg, deps);
4757
+ }));
4758
+ for (const pkg of pending) {
4759
+ for (const dep of (_npmMetadataCache.get(pkg) || [])) addSpec(dep);
4760
+ }
4761
+ }
4762
+ }
4763
+
4722
4764
  const loaded = {};
4723
4765
  for (const pkg of specs) {
4724
4766
  const nmKey = `node_modules/${pkg}/index.js`;
4725
4767
  if (files[nmKey] || files[`/workspace/${nmKey}`]) continue;
4726
- if (existingCache && existingCache.has(pkg)) {
4768
+ if (existingCache.has(pkg)) {
4727
4769
  loaded[pkg] = existingCache.get(pkg);
4728
4770
  continue;
4729
4771
  }
4772
+ if (typeof onProgress === 'function') {
4773
+ try { onProgress(pkg); } catch (_) {}
4774
+ }
4730
4775
  if (typeof fetch === 'function') {
4731
4776
  try {
4732
4777
  const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}`);
4733
4778
  if (res && res.ok) {
4734
4779
  const text = await res.text();
4735
- if (existingCache) existingCache.set(pkg, text);
4780
+ if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
4736
4781
  loaded[pkg] = text;
4737
4782
  }
4738
4783
  } catch (_) {}
@@ -9829,38 +9874,221 @@ if (typeof module !== 'undefined' && module.exports) {
9829
9874
  } catch (_) {}
9830
9875
  }
9831
9876
 
9832
- function installPackage(pkgSpec, ctx) {
9833
- const parts = pkgSpec.split('@').filter(Boolean);
9834
- const pkgName = pkgSpec.startsWith('@') ? '@' + parts[0] : parts[0];
9835
- const pkgVersion = parts[1] || '^1.0.0';
9877
+ // ---------------------------------------------------------------------------
9878
+ // Real npm package installation via the jsDelivr CDN
9879
+ // ---------------------------------------------------------------------------
9880
+ const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
9881
+
9882
+ // Minimal offline registry, used only when the CDN is unreachable so common
9883
+ // demos still resolve without network access.
9884
+ const OFFLINE_PACKAGE_FALLBACKS = {
9885
+ 'is-even': 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n',
9886
+ 'tiny-invariant': 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n',
9887
+ 'lodash': 'module.exports = { isArray: Array.isArray, isObject: function (v) { return v !== null && typeof v === "object"; } };\n',
9888
+ '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'
9889
+ };
9890
+
9891
+ function packageCtxFetch(ctx) {
9892
+ if (ctx && ctx.shell && ctx.shell.options && typeof ctx.shell.options.fetchImpl === 'function') {
9893
+ return ctx.shell.options.fetchImpl;
9894
+ }
9895
+ if (typeof fetch === 'function') return fetch.bind(globalThis);
9896
+ return null;
9897
+ }
9898
+
9899
+ function parsePackageSpec(spec) {
9900
+ const raw = String(spec || '').trim();
9901
+ if (!raw) return { name: '', range: null };
9902
+ if (raw.startsWith('@')) {
9903
+ const at = raw.indexOf('@', 1);
9904
+ if (at === -1) return { name: raw, range: null };
9905
+ return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
9906
+ }
9907
+ const at = raw.indexOf('@');
9908
+ if (at <= 0) return { name: raw, range: null };
9909
+ return { name: raw.slice(0, at), range: raw.slice(at + 1) || null };
9910
+ }
9911
+
9912
+ function resolveEntryRelPath(pkgJson) {
9913
+ let entry = pkgJson.main || pkgJson.module ||
9914
+ (typeof pkgJson.browser === 'string' ? pkgJson.browser : '') || 'index.js';
9915
+ entry = String(entry).replace(/^[./]+/, '');
9916
+ return entry || 'index.js';
9917
+ }
9918
+
9919
+ function stripRelPath(rel) {
9920
+ return String(rel || '').replace(/^[./]+/, '');
9921
+ }
9922
+
9923
+ function extractRelativeSpecifiers(code) {
9924
+ const out = new Set();
9925
+ const re = /(?:\brequire\s*\(\s*|\bimport\s+[\s\S]{0,120}?\bfrom\s*|\bimport\s*\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g;
9926
+ let m;
9927
+ while ((m = re.exec(code)) !== null) out.add(m[1]);
9928
+ return Array.from(out);
9929
+ }
9930
+
9931
+ function normalizeRelPath(baseDir, rel) {
9932
+ const parts = String(baseDir || '').split('/').filter(Boolean);
9933
+ for (const seg of String(rel).split('/')) {
9934
+ if (!seg || seg === '.') continue;
9935
+ if (seg === '..') parts.pop();
9936
+ else parts.push(seg);
9937
+ }
9938
+ return parts.join('/');
9939
+ }
9940
+
9941
+ async function fetchTextFromCdn(fetchImpl, url) {
9942
+ try {
9943
+ const res = await fetchImpl(url);
9944
+ if (!res) return null;
9945
+ const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
9946
+ if (!ok) return null;
9947
+ if (typeof res.text === 'function') return await res.text();
9948
+ return String(res.body != null ? res.body : '');
9949
+ } catch (_) {
9950
+ return null;
9951
+ }
9952
+ }
9953
+
9954
+ async function resolvePackageMetadata(fetchImpl, name, range) {
9955
+ const urls = range
9956
+ ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
9957
+ : [`${CDN_NPM_BASE}/${name}/package.json`];
9958
+ for (const url of urls) {
9959
+ const text = await fetchTextFromCdn(fetchImpl, url);
9960
+ if (!text) continue;
9961
+ try {
9962
+ const parsed = JSON.parse(text);
9963
+ if (parsed && parsed.version) return parsed;
9964
+ } catch (_) {}
9965
+ }
9966
+ return null;
9967
+ }
9968
+
9969
+ // Download a package's entry module, its relative submodules and record its
9970
+ // declared dependencies so the caller can resolve them transitively.
9971
+ async function downloadPackageFiles(fetchImpl, name, range, seen) {
9972
+ const meta = await resolvePackageMetadata(fetchImpl, name, range);
9973
+ if (!meta) {
9974
+ const fallback = OFFLINE_PACKAGE_FALLBACKS[name];
9975
+ if (fallback) {
9976
+ const v = range ? range.replace(/^[\^~>=<\s]+/, '') || '1.0.0' : '1.0.0';
9977
+ return { ok: true, offline: true, version: v, entry: 'index.js', files: [{ rel: 'index.js', content: fallback }], deps: [] };
9978
+ }
9979
+ return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
9980
+ }
9981
+
9982
+ const version = meta.version;
9983
+ const key = `${name}@${version}`;
9984
+ if (seen.has(key)) {
9985
+ return { ok: true, deduped: true, version, entry: resolveEntryRelPath(meta), files: [], deps: [] };
9986
+ }
9987
+ seen.add(key);
9988
+
9989
+ const entry = resolveEntryRelPath(meta);
9990
+ const files = [];
9991
+ const visited = new Set();
9992
+ const queue = [entry];
9993
+ while (queue.length > 0) {
9994
+ const rel = stripRelPath(queue.shift());
9995
+ if (!rel || visited.has(rel)) continue;
9996
+ visited.add(rel);
9997
+ const text = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`);
9998
+ if (text === null) continue;
9999
+ files.push({ rel, content: text });
10000
+ const baseDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
10001
+ for (const spec of extractRelativeSpecifiers(text)) {
10002
+ const target = normalizeRelPath(baseDir, spec);
10003
+ for (const cand of [target, `${target}.js`, `${target}.json`, `${target}/index.js`]) {
10004
+ const c = stripRelPath(cand);
10005
+ if (c && !visited.has(c)) { queue.push(cand); break; }
10006
+ }
10007
+ }
10008
+ }
10009
+ // The declared entry may be missing on the CDN; fall back to index.js.
10010
+ if (!files.some(f => f.rel === entry)) {
10011
+ const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
10012
+ if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
10013
+ }
10014
+
10015
+ return { ok: true, version, entry, files, deps: Object.keys(meta.dependencies || {}) };
10016
+ }
10017
+
10018
+ function installTargetDirs(ctx, name) {
10019
+ const dirs = ['/workspace/node_modules/' + name];
10020
+ const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', name);
10021
+ if (!dirs.includes(cwdTarget)) dirs.push(cwdTarget);
10022
+ return dirs;
10023
+ }
10024
+
10025
+ function writeInstalledPackageFiles(ctx, dirs, name, info) {
10026
+ for (const dir of dirs) {
10027
+ ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
10028
+ for (const f of info.files) {
10029
+ const full = PosixPath.join(dir, f.rel);
10030
+ ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
10031
+ ctx.vfs.writeFileSync(full, f.content);
10032
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
10033
+ }
10034
+ const modPkgPath = PosixPath.join(dir, 'package.json');
10035
+ const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
10036
+ ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
10037
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
10038
+ }
10039
+ }
10040
+
10041
+ async function installPackage(pkgSpec, ctx) {
10042
+ const { name: pkgName, range } = parsePackageSpec(pkgSpec);
10043
+ if (!pkgName) return { name: null, ok: false, installed: [], warning: null };
9836
10044
 
9837
10045
  const { path: pkgPath, data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
9838
10046
  if (!pkgData.dependencies) pkgData.dependencies = {};
9839
- pkgData.dependencies[pkgName] = pkgVersion;
9840
- writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
9841
10047
 
9842
- const targetDirs = ['/workspace/node_modules/' + pkgName];
9843
- const cwdTarget = PosixPath.join(ctx.cwd || '/workspace', 'node_modules', pkgName);
9844
- if (!targetDirs.includes(cwdTarget)) targetDirs.push(cwdTarget);
10048
+ const fetchImpl = packageCtxFetch(ctx);
10049
+ const seen = (ctx.shell && ctx.shell._cdnSeen)
10050
+ ? ctx.shell._cdnSeen
10051
+ : (ctx.shell ? (ctx.shell._cdnSeen = new Set()) : new Set());
10052
+
10053
+ const queue = [{ name: pkgName, range, direct: true }];
10054
+ const requested = new Set([pkgName]);
10055
+ const installed = [];
10056
+ let warning = null;
10057
+ let directVersion = null;
10058
+
10059
+ while (queue.length > 0) {
10060
+ const item = queue.shift();
10061
+ const info = fetchImpl
10062
+ ? await downloadPackageFiles(fetchImpl, item.name, item.range, seen)
10063
+ : { ok: false, reason: `${item.name}: no fetch implementation available` };
10064
+
10065
+ if (!info.ok) {
10066
+ // Final fallback: an empty stub so offline demos still resolve the module.
10067
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, {
10068
+ version: '0.0.0', entry: 'index.js', files: [{ rel: 'index.js', content: 'module.exports = {};\n' }]
10069
+ });
10070
+ if (!warning) warning = info.reason;
10071
+ installed.push({ name: item.name, version: '0.0.0' });
10072
+ continue;
10073
+ }
9845
10074
 
9846
- for (const modDir of targetDirs) {
9847
- ensureDirSync(ctx.vfs, modDir, ctx.emitMutation);
9848
- const modPkgPath = PosixPath.join(modDir, 'package.json');
9849
- const modIndexPath = PosixPath.join(modDir, 'index.js');
9850
- ctx.vfs.writeFileSync(modPkgPath, JSON.stringify({ name: pkgName, version: pkgVersion.replace(/^[\^~]/, ''), main: './index.js' }, null, 2) + '\n');
9851
- if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
10075
+ writeInstalledPackageFiles(ctx, installTargetDirs(ctx, item.name), item.name, info);
10076
+ installed.push({ name: item.name, version: info.version || '1.0.0' });
10077
+ if (item.direct) directVersion = info.version || null;
9852
10078
 
9853
- let code = 'module.exports = {};\n';
9854
- if (pkgName === 'is-even') {
9855
- code = 'module.exports = function isEven(n) { return (Number(n) % 2) === 0; };\n';
9856
- } else if (pkgName === 'tiny-invariant') {
9857
- code = 'module.exports = function invariant(condition, message) { if (!condition) throw new Error(message || "Invariant failed"); };\n';
9858
- } else if (pkgName === 'lodash') {
9859
- code = 'module.exports = { isArray: Array.isArray, isObject: function(v) { return v !== null && typeof v === "object"; } };\n';
10079
+ for (const dep of (info.deps || [])) {
10080
+ const parsed = parsePackageSpec(dep);
10081
+ if (parsed.name && !requested.has(parsed.name)) {
10082
+ requested.add(parsed.name);
10083
+ queue.push({ name: parsed.name, range: null, direct: false });
10084
+ }
9860
10085
  }
9861
- ctx.vfs.writeFileSync(modIndexPath, code);
9862
- if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modIndexPath);
9863
10086
  }
10087
+
10088
+ pkgData.dependencies[pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData.dependencies[pkgName] || 'latest'));
10089
+ writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
10090
+
10091
+ return { name: pkgName, ok: true, version: directVersion, installed, warning };
9864
10092
  }
9865
10093
 
9866
10094
  function uninstallPackage(pkgName, ctx) {
@@ -12537,6 +12765,18 @@ if (typeof module !== 'undefined' && module.exports) {
12537
12765
 
12538
12766
  const sub = args[0];
12539
12767
 
12768
+ if (sub === '--version' || sub === '-v' || sub === '--revision') {
12769
+ return { code: 0, stdout: '1.1.20\n', stderr: '' };
12770
+ }
12771
+
12772
+ if (sub === '--help' || sub === '-h') {
12773
+ return {
12774
+ code: 0,
12775
+ 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',
12776
+ stderr: ''
12777
+ };
12778
+ }
12779
+
12540
12780
  if (sub === 'init') {
12541
12781
  const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
12542
12782
  const dirName = PosixPath.basename(ctx.cwd) || 'app';
@@ -12586,12 +12826,28 @@ if (typeof module !== 'undefined' && module.exports) {
12586
12826
  return { code: 0, stdout: 'Done! A package.json file was created in ' + ctx.cwd + '\n', stderr: '' };
12587
12827
  }
12588
12828
 
12589
- if (sub === 'add') {
12829
+ if (sub === 'install' || sub === 'i' || sub === 'ci') {
12590
12830
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
12591
- for (const p of pkgs) {
12592
- installPackage(p, ctx);
12831
+ if (pkgs.length === 0) {
12832
+ const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
12833
+ const deps = Object.keys(pkgData.dependencies || {});
12834
+ const results = [];
12835
+ for (const p of deps) results.push(await installPackage(p, ctx));
12836
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
12837
+ return { code: 0, stdout: deps.length === 0 ? 'up to date\n' : `installed ${deps.length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
12593
12838
  }
12594
- return { code: 0, stdout: `saved ${pkgs.length} package(s)\n`, stderr: '' };
12839
+ const results = [];
12840
+ for (const p of pkgs) results.push(await installPackage(p, ctx));
12841
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
12842
+ return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
12843
+ }
12844
+
12845
+ if (sub === 'add') {
12846
+ const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
12847
+ const results = [];
12848
+ for (const p of pkgs) results.push(await installPackage(p, ctx));
12849
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
12850
+ return { code: 0, stdout: `saved ${results.filter(r => r && r.name).length} package(s)\n`, stderr: warning ? `bun warn ${warning}\n` : '' };
12595
12851
  }
12596
12852
 
12597
12853
  if (sub === 'remove' || sub === 'rm') {
@@ -12754,15 +13010,19 @@ if (typeof module !== 'undefined' && module.exports) {
12754
13010
  const pkgs = args.slice(1).filter(a => !a.startsWith('-'));
12755
13011
  if (pkgs.length === 0) {
12756
13012
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
13013
+ const results = [];
12757
13014
  for (const p of Object.keys(pkgData.dependencies || {})) {
12758
- installPackage(p, ctx);
13015
+ results.push(await installPackage(p, ctx));
12759
13016
  }
12760
- return { code: 0, stdout: 'up to date\n', stderr: '' };
13017
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
13018
+ return { code: 0, stdout: 'up to date\n', stderr: warning ? `npm warn ${warning}\n` : '' };
12761
13019
  }
13020
+ const results = [];
12762
13021
  for (const p of pkgs) {
12763
- installPackage(p, ctx);
13022
+ results.push(await installPackage(p, ctx));
12764
13023
  }
12765
- return { code: 0, stdout: `added ${pkgs.length} package(s) in 0.1s\n`, stderr: '' };
13024
+ const warning = results.map(r => r && r.warning).filter(Boolean)[0];
13025
+ return { code: 0, stdout: `added ${results.filter(r => r && r.name).length} package(s) in 0.1s\n`, stderr: warning ? `npm warn ${warning}\n` : '' };
12766
13026
  }
12767
13027
 
12768
13028
  if (sub === 'uninstall' || sub === 'remove' || sub === 'rm') {
@@ -12987,6 +13247,16 @@ if (typeof module !== 'undefined' && module.exports) {
12987
13247
  return PosixPath.resolve(this.cwd, p);
12988
13248
  }
12989
13249
 
13250
+ // True when `name` resolves to a shell function or coreutil (used by the
13251
+ // workbench to route recognised commands straight to the shell instead of
13252
+ // treating flag-looking input such as `node --version` as a JS expression).
13253
+ hasCommand(name) {
13254
+ if (!name) return false;
13255
+ const n = String(name);
13256
+ if (this.functions && Object.prototype.hasOwnProperty.call(this.functions, n)) return true;
13257
+ return !!this.commands && Object.prototype.hasOwnProperty.call(this.commands, n);
13258
+ }
13259
+
12990
13260
  _emitVfsMutation(type, absPath) {
12991
13261
  if (!this.vfs) return;
12992
13262
  const evt = { type, path: absPath, timestamp: Date.now() };
@@ -21077,14 +21347,14 @@ declare module 'bun:sqlite' {
21077
21347
  </div>
21078
21348
  ${pkgs.length === 0 ? `
21079
21349
  <div style="padding:12px;border:1px solid var(--cl-border);border-radius:var(--cl-radius-sm);background:var(--cl-bg);color:var(--cl-fg-muted);font-size:12.5px;">
21080
- No external npm packages imported yet. Any <code>import ... from 'pkg'</code> or <code>require('pkg')</code> in your code is automatically resolved via <strong>esm.sh</strong> when you run or test.
21350
+ No external npm packages imported yet. Any <code>import ... from 'pkg'</code> or <code>require('pkg')</code> in your code is automatically resolved via <strong>jsDelivr</strong> when you run or test.
21081
21351
  </div>
21082
21352
  ` : `
21083
21353
  <div style="display:flex;flex-direction:column;gap:6px;">
21084
21354
  ${pkgs.map(p => `
21085
21355
  <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 12px;border:1px solid var(--cl-border);border-radius:var(--cl-radius-sm);background:var(--cl-bg);font-family:var(--cl-font-mono);font-size:12px;">
21086
21356
  <span style="color:var(--cl-fg);font-weight:600;">${escapeHtml(p.name)}</span>
21087
- <span style="color:var(--cl-accent);">${escapeHtml(p.version)} · esm.sh</span>
21357
+ <span style="color:var(--cl-accent);">${escapeHtml(p.version)} · jsDelivr</span>
21088
21358
  </div>
21089
21359
  `).join('')}
21090
21360
  </div>
@@ -21218,9 +21488,14 @@ declare module 'bun:sqlite' {
21218
21488
  if (detectedList.length > 0) {
21219
21489
  this._setRuntimeStatus('fetching', `Fetching ${detectedList.map(d => typeof d === 'string' ? d : d.name).join(', ')}...`);
21220
21490
  }
21221
- await root.CodeLabRuntime.preloadNpmPackages(payload.files, pkgName => {
21222
- this._setRuntimeStatus('fetching', `Fetching ${pkgName} from esm.sh...`);
21491
+ const preloaded = await root.CodeLabRuntime.preloadNpmPackages(payload.files, pkgName => {
21492
+ this._setRuntimeStatus('fetching', `Fetching ${pkgName} from jsDelivr CDN...`);
21223
21493
  });
21494
+ // Hand the fetched module sources to the runtime so the Web Worker
21495
+ // (which has an isolated module cache) can resolve them from node_modules.
21496
+ if (preloaded && typeof preloaded === 'object' && Object.keys(preloaded).length > 0) {
21497
+ payload.packages = Object.assign({}, preloaded, payload.packages || {});
21498
+ }
21224
21499
  }
21225
21500
  this._setRuntimeStatus('running', `Running ${payload.entry || payload.mode || 'script'}...`);
21226
21501
  let res;
@@ -21557,8 +21832,17 @@ declare module 'bun:sqlite' {
21557
21832
  return;
21558
21833
  }
21559
21834
 
21560
- const looksLikeJsExpr = /^(const|let|var|function|class|await|return|typeof|instanceof|new\s+|Math\.|JSON\.|Object\.|Array\.|Promise\.|console\.|process\.|Buffer\.|require\s*\(|import\s*\(|[0-9]+\s*[\+\-\*\/\%]|['"`\[{])/.test(trimmed)
21561
- || /^[a-zA-Z_$][\w$]*\s*(\.|===|!==|==|!=|<=|>=|\+=|-=|\*=|\(|\+\+|--)/.test(trimmed);
21835
+ const firstWord = (trimmed.split(/\s+/)[0] || '').replace(/^.*\//, '');
21836
+ const shellKnowsCommand = Boolean(
21837
+ firstWord &&
21838
+ this.shell &&
21839
+ typeof this.shell.hasCommand === 'function' &&
21840
+ this.shell.hasCommand(firstWord)
21841
+ );
21842
+ const looksLikeJsExpr = !shellKnowsCommand && (
21843
+ /^(const|let|var|function|class|await|return|typeof|instanceof|new\s+|Math\.|JSON\.|Object\.|Array\.|Promise\.|console\.|process\.|Buffer\.|require\s*\(|import\s*\(|[0-9]+\s*[\+\-\*\/\%]|['"`\[{])/.test(trimmed)
21844
+ || /^[a-zA-Z_$][\w$]*\s*(\.|===|!==|==|!=|<=|>=|\+=|-=|\*=|\(|\+\+|--)/.test(trimmed)
21845
+ );
21562
21846
 
21563
21847
  if (this.shell && typeof this.shell.execute === 'function' && !looksLikeJsExpr) {
21564
21848
  const abortCtrl = new AbortController();
package/dist/runtime.d.ts CHANGED
@@ -39,7 +39,7 @@ export declare const createVirtualFs: (options?: any) => any;
39
39
  export declare const createVirtualHttp: (portTable?: any, vfs?: any) => any;
40
40
  export declare const createVirtualNet: (portTable?: any) => any;
41
41
  export declare const transpileTS: (code: string, filename?: string) => string;
42
- export declare const preloadNpmPackages: (packages?: Record<string, any>) => void;
42
+ export declare const preloadNpmPackages: (files?: Record<string, any>, onProgressOrCache?: ((pkg: string) => void) | Map<string, string>, onProgress?: (pkg: string) => void) => Promise<Record<string, string>>;
43
43
  export declare const createVirtualPortTable: () => any;
44
44
  export declare const executeInVirtualRuntime: (options?: any) => Promise<RuntimeExecutionResult>;
45
45
  export declare const createWorkerRuntimeSource: () => string;
@@ -4679,8 +4679,22 @@ function __initVirtualRuntime(rootScope) {
4679
4679
  }
4680
4680
 
4681
4681
  const _npmPackageCache = new Map();
4682
+ const _npmMetadataCache = new Map();
4683
+
4684
+ async function preloadNpmPackages(files = {}, secondArg = null, thirdArg = null) {
4685
+ // The 2nd/3rd arguments are overloaded for backwards compatibility:
4686
+ // preloadNpmPackages(files)
4687
+ // preloadNpmPackages(files, onProgress) // progress callback (used by the Workbench)
4688
+ // preloadNpmPackages(files, existingCache) // package-text cache (Map)
4689
+ // preloadNpmPackages(files, existingCache, onProgress)
4690
+ const isCacheLike = (v) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
4691
+ let onProgress = null;
4692
+ let existingCache = _npmPackageCache;
4693
+ if (typeof secondArg === 'function') onProgress = secondArg;
4694
+ else if (isCacheLike(secondArg)) existingCache = secondArg;
4695
+ if (typeof thirdArg === 'function') onProgress = onProgress || thirdArg;
4696
+ else if (isCacheLike(thirdArg)) existingCache = thirdArg;
4682
4697
 
4683
- async function preloadNpmPackages(files = {}, existingCache = _npmPackageCache) {
4684
4698
  const specs = new Set();
4685
4699
  const builtinSet = new Set([
4686
4700
  'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
@@ -4716,20 +4730,51 @@ function __initVirtualRuntime(rootScope) {
4716
4730
  while ((m = impRe.exec(content)) !== null) addSpec(m[1]);
4717
4731
  }
4718
4732
 
4733
+ // Follow declared dependencies transitively (best effort, bounded). Metadata
4734
+ // is memoised across calls so repeated preloads stay cheap.
4735
+ if (typeof fetch === 'function') {
4736
+ let pass = 0;
4737
+ while (pass < 6) {
4738
+ const pending = [];
4739
+ for (const pkg of specs) {
4740
+ if (!_npmMetadataCache.has(pkg)) pending.push(pkg);
4741
+ }
4742
+ if (pending.length === 0) break;
4743
+ pass++;
4744
+ await Promise.all(pending.map(async (pkg) => {
4745
+ let deps = [];
4746
+ try {
4747
+ const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}/package.json`);
4748
+ if (res && res.ok) {
4749
+ const meta = await res.json();
4750
+ deps = Object.keys((meta && meta.dependencies) || {});
4751
+ }
4752
+ } catch (_) {}
4753
+ _npmMetadataCache.set(pkg, deps);
4754
+ }));
4755
+ for (const pkg of pending) {
4756
+ for (const dep of (_npmMetadataCache.get(pkg) || [])) addSpec(dep);
4757
+ }
4758
+ }
4759
+ }
4760
+
4719
4761
  const loaded = {};
4720
4762
  for (const pkg of specs) {
4721
4763
  const nmKey = `node_modules/${pkg}/index.js`;
4722
4764
  if (files[nmKey] || files[`/workspace/${nmKey}`]) continue;
4723
- if (existingCache && existingCache.has(pkg)) {
4765
+ if (existingCache.has(pkg)) {
4724
4766
  loaded[pkg] = existingCache.get(pkg);
4725
4767
  continue;
4726
4768
  }
4769
+ if (typeof onProgress === 'function') {
4770
+ try { onProgress(pkg); } catch (_) {}
4771
+ }
4727
4772
  if (typeof fetch === 'function') {
4728
4773
  try {
4729
4774
  const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}`);
4730
4775
  if (res && res.ok) {
4731
4776
  const text = await res.text();
4732
- if (existingCache) existingCache.set(pkg, text);
4777
+ if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
4733
4778
  loaded[pkg] = text;
4734
4779
  }
4735
4780
  } catch (_) {}
package/dist/runtime.js CHANGED
@@ -4680,8 +4680,22 @@ function __initVirtualRuntime(rootScope) {
4680
4680
  }
4681
4681
 
4682
4682
  const _npmPackageCache = new Map();
4683
+ const _npmMetadataCache = new Map();
4684
+
4685
+ async function preloadNpmPackages(files = {}, secondArg = null, thirdArg = null) {
4686
+ // The 2nd/3rd arguments are overloaded for backwards compatibility:
4687
+ // preloadNpmPackages(files)
4688
+ // preloadNpmPackages(files, onProgress) // progress callback (used by the Workbench)
4689
+ // preloadNpmPackages(files, existingCache) // package-text cache (Map)
4690
+ // preloadNpmPackages(files, existingCache, onProgress)
4691
+ const isCacheLike = (v) => !!v && typeof v !== 'function' && typeof v.has === 'function' && typeof v.get === 'function';
4692
+ let onProgress = null;
4693
+ let existingCache = _npmPackageCache;
4694
+ if (typeof secondArg === 'function') onProgress = secondArg;
4695
+ else if (isCacheLike(secondArg)) existingCache = secondArg;
4696
+ if (typeof thirdArg === 'function') onProgress = onProgress || thirdArg;
4697
+ else if (isCacheLike(thirdArg)) existingCache = thirdArg;
4683
4698
 
4684
- async function preloadNpmPackages(files = {}, existingCache = _npmPackageCache) {
4685
4699
  const specs = new Set();
4686
4700
  const builtinSet = new Set([
4687
4701
  'fs', 'fs/promises', 'path', 'os', 'crypto', 'zlib', 'http', 'https', 'net',
@@ -4717,20 +4731,51 @@ function __initVirtualRuntime(rootScope) {
4717
4731
  while ((m = impRe.exec(content)) !== null) addSpec(m[1]);
4718
4732
  }
4719
4733
 
4734
+ // Follow declared dependencies transitively (best effort, bounded). Metadata
4735
+ // is memoised across calls so repeated preloads stay cheap.
4736
+ if (typeof fetch === 'function') {
4737
+ let pass = 0;
4738
+ while (pass < 6) {
4739
+ const pending = [];
4740
+ for (const pkg of specs) {
4741
+ if (!_npmMetadataCache.has(pkg)) pending.push(pkg);
4742
+ }
4743
+ if (pending.length === 0) break;
4744
+ pass++;
4745
+ await Promise.all(pending.map(async (pkg) => {
4746
+ let deps = [];
4747
+ try {
4748
+ const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}/package.json`);
4749
+ if (res && res.ok) {
4750
+ const meta = await res.json();
4751
+ deps = Object.keys((meta && meta.dependencies) || {});
4752
+ }
4753
+ } catch (_) {}
4754
+ _npmMetadataCache.set(pkg, deps);
4755
+ }));
4756
+ for (const pkg of pending) {
4757
+ for (const dep of (_npmMetadataCache.get(pkg) || [])) addSpec(dep);
4758
+ }
4759
+ }
4760
+ }
4761
+
4720
4762
  const loaded = {};
4721
4763
  for (const pkg of specs) {
4722
4764
  const nmKey = `node_modules/${pkg}/index.js`;
4723
4765
  if (files[nmKey] || files[`/workspace/${nmKey}`]) continue;
4724
- if (existingCache && existingCache.has(pkg)) {
4766
+ if (existingCache.has(pkg)) {
4725
4767
  loaded[pkg] = existingCache.get(pkg);
4726
4768
  continue;
4727
4769
  }
4770
+ if (typeof onProgress === 'function') {
4771
+ try { onProgress(pkg); } catch (_) {}
4772
+ }
4728
4773
  if (typeof fetch === 'function') {
4729
4774
  try {
4730
4775
  const res = await fetch(`https://cdn.jsdelivr.net/npm/${pkg}`);
4731
4776
  if (res && res.ok) {
4732
4777
  const text = await res.text();
4733
- if (existingCache) existingCache.set(pkg, text);
4778
+ if (typeof existingCache.set === 'function') existingCache.set(pkg, text);
4734
4779
  loaded[pkg] = text;
4735
4780
  }
4736
4781
  } catch (_) {}