@innovatorved/code-lab 0.1.7 → 0.1.8

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
@@ -45,12 +45,23 @@
45
45
  })(typeof globalThis !== 'undefined' ? globalThis : this, function (root) {
46
46
  'use strict';
47
47
 
48
+ const _shellLogger = (root && root.CodeLabLogger && typeof root.CodeLabLogger.createLogger === 'function')
49
+ ? root.CodeLabLogger.createLogger()
50
+ : {
51
+ debug() {},
52
+ info(...args) { if (typeof console !== 'undefined' && console.info) console.info('[code-lab]', ...args); },
53
+ warn(...args) { if (typeof console !== 'undefined' && console.warn) console.warn('[code-lab]', ...args); },
54
+ error(...args) { if (typeof console !== 'undefined' && console.error) console.error('[code-lab]', ...args); }
55
+ };
56
+
48
57
  function getRuntimeModule() {
49
58
  if (typeof root !== 'undefined' && root && root.CodeLabRuntime) return root.CodeLabRuntime;
50
59
  if (typeof globalThis !== 'undefined' && globalThis.CodeLabRuntime) return globalThis.CodeLabRuntime;
51
60
  try {
52
61
  if (typeof require !== 'undefined') return require('./runtime.js');
53
- } catch (_) {}
62
+ } catch (err) {
63
+ _shellLogger.debug('Optional ./runtime.js require skipped in shell.', err);
64
+ }
54
65
  return null;
55
66
  }
56
67
 
@@ -642,7 +653,9 @@
642
653
  if (typeof vfs.statSync === 'function') {
643
654
  isDir = vfs.statSync(full).isDirectory();
644
655
  }
645
- } catch (_) {}
656
+ } catch (err) {
657
+ _shellLogger.debug('Glob statSync failed.', full, err);
658
+ }
646
659
 
647
660
  if (isDir) {
648
661
  traverse(full, rel);
@@ -1964,7 +1977,9 @@
1964
1977
  : name;
1965
1978
  try {
1966
1979
  snap[rel] = String(vfs.readFileSync(full, 'utf8'));
1967
- } catch (_) {}
1980
+ } catch (err) {
1981
+ _shellLogger.debug('Skipped unreadable VFS file in snapshot.', full, err);
1982
+ }
1968
1983
  }
1969
1984
  }
1970
1985
  }
@@ -2068,8 +2083,9 @@
2068
2083
  }
2069
2084
  }
2070
2085
  }
2071
- } catch (_) {
2086
+ } catch (err) {
2072
2087
  // Network or rate limit error on api.github.com; proceed to Strategy B
2088
+ _shellLogger.debug('GitHub REST API tree fetch failed; falling back to jsDelivr.', err);
2073
2089
  }
2074
2090
 
2075
2091
  // Strategy B: jsDelivr Data API (Zero rate limits, fast global edge cache)
@@ -2096,7 +2112,9 @@
2096
2112
  }
2097
2113
  }
2098
2114
  }
2099
- } catch (_) {}
2115
+ } catch (err) {
2116
+ _shellLogger.debug('jsDelivr flat tree fetch failed.', err);
2117
+ }
2100
2118
  }
2101
2119
 
2102
2120
  if (repoNotFound || !rawTreeEntries) {
@@ -2244,7 +2262,9 @@
2244
2262
  }));
2245
2263
  }
2246
2264
  }
2247
- } catch (_) {}
2265
+ } catch (err) {
2266
+ _shellLogger.debug('Optional commit history fetch skipped.', err);
2267
+ }
2248
2268
 
2249
2269
  if (commits.length === 0) {
2250
2270
  commits = [
@@ -2310,7 +2330,9 @@
2310
2330
  try {
2311
2331
  const parsed = JSON.parse(vfs.readFileSync(p, 'utf8'));
2312
2332
  return { path: p, data: parsed };
2313
- } catch (_) {}
2333
+ } catch (err) {
2334
+ _shellLogger.warn(`Invalid JSON in ${p}; falling back to default package metadata.`, err);
2335
+ }
2314
2336
  }
2315
2337
  return { path: p, data: { name: 'app', dependencies: {}, devDependencies: {}, scripts: {} } };
2316
2338
  }
@@ -2351,13 +2373,20 @@
2351
2373
  vfs.rmdirSync(dirPath);
2352
2374
  }
2353
2375
  if (typeof emitMutation === 'function') emitMutation('delete', dirPath);
2354
- } catch (_) {}
2376
+ } catch (err) {
2377
+ _shellLogger.debug('removeDirRecursive failed.', dirPath, err);
2378
+ }
2355
2379
  }
2356
2380
 
2357
2381
  // ---------------------------------------------------------------------------
2358
2382
  // Real npm package installation via the jsDelivr CDN
2359
2383
  // ---------------------------------------------------------------------------
2360
2384
  const CDN_NPM_BASE = 'https://cdn.jsdelivr.net/npm';
2385
+ const CDN_NPM_BASES = [
2386
+ 'https://cdn.jsdelivr.net/npm',
2387
+ 'https://unpkg.com',
2388
+ 'https://esm.sh'
2389
+ ];
2361
2390
 
2362
2391
  // Minimal offline registry, used only when the CDN is unreachable so common
2363
2392
  // demos still resolve without network access.
@@ -2503,16 +2532,23 @@
2503
2532
  }
2504
2533
 
2505
2534
  async function resolvePackageMetadata(fetchImpl, name, range) {
2506
- const urls = range
2507
- ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
2508
- : [`${CDN_NPM_BASE}/${name}/package.json`];
2509
- for (const url of urls) {
2510
- const text = await fetchTextFromCdn(fetchImpl, url);
2511
- if (!text) continue;
2512
- try {
2513
- const parsed = JSON.parse(text);
2514
- if (parsed && parsed.version) return parsed;
2515
- } catch (_) {}
2535
+ for (const base of CDN_NPM_BASES) {
2536
+ const urls = range
2537
+ ? [`${base}/${name}@${range}/package.json`, `${base}/${name}/package.json`]
2538
+ : [`${base}/${name}/package.json`];
2539
+ for (const url of urls) {
2540
+ const text = await fetchTextFromCdn(fetchImpl, url);
2541
+ if (!text) continue;
2542
+ try {
2543
+ const parsed = JSON.parse(text);
2544
+ if (parsed && parsed.version) {
2545
+ parsed._resolvedCdnBase = base;
2546
+ return parsed;
2547
+ }
2548
+ } catch (err) {
2549
+ _shellLogger.debug('Invalid package.json metadata from CDN.', url, err);
2550
+ }
2551
+ }
2516
2552
  }
2517
2553
  return null;
2518
2554
  }
@@ -2530,6 +2566,7 @@
2530
2566
  return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
2531
2567
  }
2532
2568
 
2569
+ const activeCdnBase = meta._resolvedCdnBase || CDN_NPM_BASE;
2533
2570
  const version = meta.version;
2534
2571
  const key = `${name}@${version}`;
2535
2572
  if (seen.has(key)) {
@@ -2577,7 +2614,7 @@
2577
2614
  frontier = [];
2578
2615
  if (batch.length === 0) break;
2579
2616
  const texts = await Promise.all(
2580
- batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
2617
+ batch.map((rel) => fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/${rel}`))
2581
2618
  );
2582
2619
  for (let idx = 0; idx < batch.length; idx++) {
2583
2620
  const rel = batch[idx];
@@ -2601,7 +2638,7 @@
2601
2638
  }
2602
2639
  // The declared entry may be missing on the CDN; fall back to index.js.
2603
2640
  if (!files.some(f => f.rel === entry)) {
2604
- const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
2641
+ const idxText = await fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/index.js`);
2605
2642
  if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
2606
2643
  }
2607
2644
 
@@ -2648,7 +2685,9 @@
2648
2685
  // directory target would otherwise raise EISDIR).
2649
2686
  try {
2650
2687
  if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
2651
- } catch (_) {}
2688
+ } catch (err) {
2689
+ _shellLogger.debug('Package install statSync check skipped.', full, err);
2690
+ }
2652
2691
  ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
2653
2692
  ctx.vfs.writeFileSync(full, f.content);
2654
2693
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
@@ -2726,6 +2765,32 @@
2726
2765
  pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
2727
2766
  writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
2728
2767
 
2768
+ // Also maintain package-lock.json in the same directory for deterministic lockfile verification
2769
+ try {
2770
+ const lockPath = PosixPath.join(PosixPath.dirname(pkgPath), 'package-lock.json');
2771
+ let lockData = { name: pkgData.name || 'workspace', version: pkgData.version || '1.0.0', lockfileVersion: 3, packages: {} };
2772
+ if (ctx.vfs.existsSync(lockPath)) {
2773
+ const rawLock = String(ctx.vfs.readFileSync(lockPath, 'utf8') || '');
2774
+ const parsedLock = JSON.parse(rawLock);
2775
+ if (parsedLock && typeof parsedLock === 'object') {
2776
+ lockData = parsedLock;
2777
+ if (!lockData.packages || typeof lockData.packages !== 'object') lockData.packages = {};
2778
+ }
2779
+ }
2780
+ for (const inst of installed) {
2781
+ if (inst && inst.name) {
2782
+ lockData.packages[`node_modules/${inst.name}`] = {
2783
+ version: inst.version || '1.0.0',
2784
+ resolved: `${CDN_NPM_BASE}/${inst.name}@${inst.version || '1.0.0'}`
2785
+ };
2786
+ }
2787
+ }
2788
+ ctx.vfs.writeFileSync(lockPath, JSON.stringify(lockData, null, 2) + '\n');
2789
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('modify', lockPath);
2790
+ } catch (err) {
2791
+ _shellLogger.debug('Could not write package-lock.json during installPackage.', err);
2792
+ }
2793
+
2729
2794
  return { name: pkgName, ok: true, version: directVersion, installed, warning };
2730
2795
  }
2731
2796
 
@@ -2923,7 +2988,9 @@
2923
2988
  const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
2924
2989
  if (parsed && parsed.version) return parsed.version;
2925
2990
  }
2926
- } catch (_) {}
2991
+ } catch (err) {
2992
+ _shellLogger.debug('Could not read installed module package.json.', pkgName, err);
2993
+ }
2927
2994
  try {
2928
2995
  for (const dir of [rootDir, '/workspace']) {
2929
2996
  const pkgPath = PosixPath.join(dir, 'package.json');
@@ -2932,7 +2999,9 @@
2932
2999
  const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
2933
3000
  if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
2934
3001
  }
2935
- } catch (_) {}
3002
+ } catch (err) {
3003
+ _shellLogger.debug('Could not read workspace package.json for version resolution.', pkgName, err);
3004
+ }
2936
3005
  return 'latest';
2937
3006
  }
2938
3007
 
@@ -2970,7 +3039,7 @@
2970
3039
  if (dirFlag) {
2971
3040
  walk(full, depth + 1);
2972
3041
  } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
2973
- try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (_) {}
3042
+ try { scripts.push(vfs.readFileSync(full, 'utf8')); } catch (err) { _shellLogger.debug('Preview script read skipped.', full, err); }
2974
3043
  }
2975
3044
  }
2976
3045
  };
@@ -3017,7 +3086,7 @@
3017
3086
 
3018
3087
  const handler = async (request) => {
3019
3088
  let pathname = '/';
3020
- try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (_) {}
3089
+ try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
3021
3090
  const rel = pathname.replace(/^\/+/, '');
3022
3091
  let target = PosixPath.join(rootDir, rel);
3023
3092
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
@@ -3056,7 +3125,9 @@
3056
3125
  if (rm && typeof rm.transpileForBrowser === 'function') {
3057
3126
  body = rm.transpileForBrowser(body, target);
3058
3127
  }
3059
- } catch (_) {}
3128
+ } catch (err) {
3129
+ _shellLogger.warn(`Preview script transpilation failed for ${target}.`, err);
3130
+ }
3060
3131
  }
3061
3132
 
3062
3133
  return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
@@ -3064,7 +3135,7 @@
3064
3135
 
3065
3136
  const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
3066
3137
  return portTable.registerServer(port, {
3067
- server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
3138
+ server: { close() { try { portTable.unregisterServer(port); } catch (err) { _shellLogger.debug('Preview server unregister failed.', port, err); } } },
3068
3139
  fetch: handler,
3069
3140
  name: 'code-lab-serve',
3070
3141
  pid,
@@ -3177,7 +3248,9 @@
3177
3248
  let isDir = false;
3178
3249
  try {
3179
3250
  isDir = ctx.vfs.statSync(resolved).isDirectory();
3180
- } catch (_) {}
3251
+ } catch (err) {
3252
+ _shellLogger.debug('cd statSync failed.', resolved, err);
3253
+ }
3181
3254
 
3182
3255
  if (!isDir) {
3183
3256
  return { code: 1, stdout: '', stderr: `cd: ${target}: Not a directory\n` };
@@ -3277,7 +3350,9 @@
3277
3350
  isDirectory = st.isDirectory();
3278
3351
  size = st.size;
3279
3352
  mtimeMs = st.mtimeMs || Date.now();
3280
- } catch (_) {}
3353
+ } catch (err) {
3354
+ _shellLogger.debug('ls statSync skipped.', itemPath, err);
3355
+ }
3281
3356
  return { name, isDirectory, size, mtimeMs, absPath: itemPath };
3282
3357
  });
3283
3358
 
@@ -3697,7 +3772,9 @@
3697
3772
  if (st.isDirectory()) walk(full);
3698
3773
  else targets.push(full);
3699
3774
  }
3700
- } catch (_) {}
3775
+ } catch (err) {
3776
+ _shellLogger.debug('grep directory walk skipped.', dir, err);
3777
+ }
3701
3778
  }
3702
3779
  if (ctx.vfs.existsSync(absRoot)) {
3703
3780
  const st = ctx.vfs.statSync(absRoot);
@@ -3821,7 +3898,9 @@
3821
3898
  let isDir = false;
3822
3899
  try {
3823
3900
  isDir = ctx.vfs.statSync(full).isDirectory();
3824
- } catch (_) {}
3901
+ } catch (err) {
3902
+ _shellLogger.debug('find statSync skipped.', full, err);
3903
+ }
3825
3904
 
3826
3905
  const relPath = root === '.'
3827
3906
  ? './' + full.replace(absRoot.endsWith('/') ? absRoot : absRoot + '/', '')
@@ -3840,7 +3919,7 @@
3840
3919
  // Root itself check
3841
3920
  if (ctx.vfs.existsSync(absRoot)) {
3842
3921
  let isDir = false;
3843
- try { isDir = ctx.vfs.statSync(absRoot).isDirectory(); } catch (_) {}
3922
+ try { isDir = ctx.vfs.statSync(absRoot).isDirectory(); } catch (err) { _shellLogger.debug('find root statSync skipped.', absRoot, err); }
3844
3923
  if (!typeFilter || (typeFilter === 'd' && isDir) || (typeFilter === 'f' && !isDir)) {
3845
3924
  if (!nameRegex || nameRegex.test(PosixPath.basename(root))) {
3846
3925
  results.push(root);
@@ -4752,7 +4831,7 @@
4752
4831
  const isLast = i === entries.length - 1;
4753
4832
  const full = dirPath === '/' ? '/' + entry : dirPath + '/' + entry;
4754
4833
  let isDir = false;
4755
- try { isDir = ctx.vfs.statSync(full).isDirectory(); } catch (_) {}
4834
+ try { isDir = ctx.vfs.statSync(full).isDirectory(); } catch (err) { _shellLogger.debug('tree statSync skipped.', full, err); }
4756
4835
 
4757
4836
  stdout += `${prefix}${isLast ? '└── ' : '├── '}${entry}\n`;
4758
4837
 
@@ -4980,10 +5059,10 @@
4980
5059
  for (const s of ctx.shell.portTable.listServers()) {
4981
5060
  if (s.pid !== undefined && String(s.pid) === String(pid)) {
4982
5061
  if (s.server && typeof s.server.close === 'function') {
4983
- try { s.server.close(); } catch (_) {}
5062
+ try { s.server.close(); } catch (err) { _shellLogger.debug('kill server.close failed.', err); }
4984
5063
  }
4985
5064
  if (typeof s.stop === 'function') {
4986
- try { s.stop(); } catch (_) {}
5065
+ try { s.stop(); } catch (err) { _shellLogger.debug('kill server.stop failed.', err); }
4987
5066
  }
4988
5067
  ctx.shell.portTable.unregisterServer(s.port);
4989
5068
  killedPort = true;