@innovatorved/code-lab 0.1.6 → 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.
Files changed (51) hide show
  1. package/ARCHITECTURE.md +34 -16
  2. package/README.md +17 -7
  3. package/dist/code-lab.css +26 -0
  4. package/dist/code-lab.d.ts +271 -1
  5. package/dist/code-lab.esm.js +2909 -166
  6. package/dist/code-lab.js +2869 -164
  7. package/dist/csp.d.ts +86 -0
  8. package/dist/diagnostics.d.ts +43 -0
  9. package/dist/extensions/guided-lab.esm.js +66 -0
  10. package/dist/extensions/guided-lab.js +66 -0
  11. package/dist/html.d.ts +24 -0
  12. package/dist/index.d.ts +9 -1
  13. package/dist/logger.d.ts +60 -0
  14. package/dist/preview-sw.js +425 -11
  15. package/dist/runtime.d.ts +6 -27
  16. package/dist/runtime.esm.js +171 -31
  17. package/dist/runtime.js +171 -31
  18. package/dist/schemas.d.ts +366 -25
  19. package/dist/schemas.esm.js +73 -0
  20. package/dist/schemas.js +73 -0
  21. package/dist/scm.d.ts +77 -0
  22. package/dist/search.d.ts +75 -0
  23. package/dist/shell.d.ts +18 -47
  24. package/dist/shell.esm.js +236 -37
  25. package/dist/shell.js +236 -37
  26. package/dist/storage.d.ts +57 -0
  27. package/dist/terminal.d.ts +11 -87
  28. package/dist/terminal.esm.js +124 -7
  29. package/dist/terminal.js +124 -7
  30. package/dist/zip.d.ts +42 -0
  31. package/package.json +11 -3
  32. package/src/code-lab.css +26 -0
  33. package/src/csp.ts +396 -0
  34. package/src/diagnostics.ts +116 -0
  35. package/src/html.ts +88 -0
  36. package/src/index.ts +39 -1
  37. package/src/logger.ts +139 -0
  38. package/src/preview-sw.js +97 -11
  39. package/src/runtime.ts +132 -105
  40. package/src/schemas.ts +94 -1
  41. package/src/scm.ts +268 -0
  42. package/src/search.ts +389 -0
  43. package/src/shell.ts +410 -369
  44. package/src/storage.ts +377 -0
  45. package/src/terminal.ts +898 -918
  46. package/src/workbench.ts +926 -89
  47. package/src/zip.ts +326 -0
  48. package/src/runtime.js +0 -8229
  49. package/src/shell.js +0 -7257
  50. package/src/terminal.js +0 -1046
  51. package/src/workbench.js +0 -7353
package/src/shell.ts CHANGED
@@ -1,65 +1,67 @@
1
1
  // @ts-nocheck
2
- 'use strict';
3
2
  /**
4
- * @innovatorved/code-lab - POSIX Shell Engine & UNIX Coreutils (TypeScript)
3
+ * @innovatorved/code-lab - POSIX Shell Engine & UNIX Coreutils
5
4
  *
6
5
  * Full-fidelity, CSP-safe POSIX shell AST interpreter and 35+ standard UNIX
7
6
  * coreutils operating directly on the in-memory virtual filesystem (VFS).
8
7
  *
8
+ * Capabilities:
9
+ * - Deterministic lexer and AST parser (zero dynamic eval, zero new Function)
10
+ * - Pipelines (cmd1 | cmd2 | cmd3) with streaming stdin/stdout chaining
11
+ * - Output redirection (>, >>, 1>, 2>, 2>&1, 1>&2, &>)
12
+ * - Input redirection (<, 0<)
13
+ * - Logical operators (&&, ||, ;)
14
+ * - Background job execution (cmd &) with job table & PID tracking
15
+ * - Variable expansion ($VAR, ${VAR}, ${VAR:-def}, $?, $PWD, $HOME, $USER)
16
+ * - Command substitution ($(cmd), `cmd`)
17
+ * - Glob expansion (*.js, src/**\/*.ts, [0-9]*.txt) against VFS
18
+ * - 40+ UNIX coreutils (ls, cd, pwd, cat, head, tail, grep, find, wc, sort, uniq,
19
+ * sed, awk, cut, tr, diff, tree, cp, mv, rm, mkdir, touch, chmod, stat, echo,
20
+ * printf, env, export, unset, which, whoami, uname, date, sleep, true, false,
21
+ * clear, history, ps, jobs, kill, git, help, dirname, basename, seq, tee)
22
+ * - Bidirectional VFS mutation bridge (touch, mkdir, rm, mv, cp, echo >, sed -i)
23
+ *
9
24
  * (C) 2026 InnovatorVed / CodeLab. MIT License.
10
25
  */
11
26
 
12
- import type { CloneProgressEvent, CloneProgressPhase, GitHubCloneOptions } from './schemas.js';
13
-
14
- export type { CloneProgressEvent, CloneProgressPhase, GitHubCloneOptions };
15
-
16
- export interface CloneResult {
17
- owner: string;
18
- repo: string;
19
- branch: string;
20
- url: string;
21
- targetDir: string;
22
- count: number;
23
- fileCount: number;
24
- filesWritten: number;
25
- totalBytes: number;
26
- commits: Array<{ hash: string; author: string; date: string; message: string }>;
27
- headSnapshot: Record<string, string>;
28
- }
29
-
30
- export interface ShellExecResult {
31
- code: number;
32
- exitCode?: number;
33
- ok?: boolean;
34
- stdout: string;
35
- stderr: string;
36
- controlFlow?: { type: string; count?: number; code?: number };
37
- aborted?: boolean;
38
- }
39
-
40
- export interface ShellExecOptions {
41
- cwd?: string;
42
- env?: Record<string, string>;
43
- vfs?: any;
44
- portTable?: any;
45
- onStdout?: (chunk: string) => void;
46
- onStderr?: (chunk: string) => void;
47
- stdin?: string;
48
- fetchImpl?: any;
49
- onProgress?: (event: CloneProgressEvent) => void;
50
- signal?: AbortSignal;
51
- }
52
-
53
- function __initShellModule(root: any) {
54
-
27
+ (function (root, factory) {
28
+ const exports = factory(root);
29
+ if (root) {
30
+ root.CodeLabShell = exports;
31
+ root.createPosixShell = exports.createPosixShell;
32
+ root.PosixShell = exports.PosixShell;
33
+ root.parseShellCommand = exports.parseShellCommand;
34
+ root.tokenizeShell = exports.tokenizeShell;
35
+ root.COREUTILS = exports.COREUTILS;
36
+ root.createVirtualPortTable = exports.createVirtualPortTable;
37
+ root.parseGitHubRepoUrl = exports.parseGitHubRepoUrl;
38
+ root.cloneGitHubRepository = exports.cloneGitHubRepository;
39
+ }
40
+ if (typeof module !== 'undefined' && module.exports) {
41
+ module.exports = exports;
42
+ } else if (typeof define === 'function' && define.amd) {
43
+ define([], function () { return exports; });
44
+ }
45
+ })(typeof globalThis !== 'undefined' ? globalThis : this, function (root) {
55
46
  'use strict';
56
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
+
57
57
  function getRuntimeModule() {
58
58
  if (typeof root !== 'undefined' && root && root.CodeLabRuntime) return root.CodeLabRuntime;
59
59
  if (typeof globalThis !== 'undefined' && globalThis.CodeLabRuntime) return globalThis.CodeLabRuntime;
60
60
  try {
61
- if (typeof require !== 'undefined') { try { return require('./runtime.js'); } catch (_) {} try { return require('./runtime'); } catch (_) {} try { return require('../dist/runtime.js'); } catch (_) {} }
62
- } catch (_) {}
61
+ if (typeof require !== 'undefined') return require('./runtime.js');
62
+ } catch (err) {
63
+ _shellLogger.debug('Optional ./runtime.js require skipped in shell.', err);
64
+ }
63
65
  return null;
64
66
  }
65
67
 
@@ -651,7 +653,9 @@ function __initShellModule(root: any) {
651
653
  if (typeof vfs.statSync === 'function') {
652
654
  isDir = vfs.statSync(full).isDirectory();
653
655
  }
654
- } catch (_) {}
656
+ } catch (err) {
657
+ _shellLogger.debug('Glob statSync failed.', full, err);
658
+ }
655
659
 
656
660
  if (isDir) {
657
661
  traverse(full, rel);
@@ -1973,7 +1977,9 @@ function __initShellModule(root: any) {
1973
1977
  : name;
1974
1978
  try {
1975
1979
  snap[rel] = String(vfs.readFileSync(full, 'utf8'));
1976
- } catch (_) {}
1980
+ } catch (err) {
1981
+ _shellLogger.debug('Skipped unreadable VFS file in snapshot.', full, err);
1982
+ }
1977
1983
  }
1978
1984
  }
1979
1985
  }
@@ -1995,325 +2001,307 @@ function __initShellModule(root: any) {
1995
2001
  return 10 + depth * 0.1;
1996
2002
  }
1997
2003
 
1998
- async function cloneGitHubRepository(repoInput, vfs, options = {}) {
2004
+ async function _cloneGitHubRepository(repoInput, vfs, options = {}) {
1999
2005
  const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
2006
+ if (onProgress) {
2007
+ onProgress({ phase: 'connecting', message: `Connecting to repository '${repoInput}'...` });
2008
+ }
2009
+ const parsed = parseGitHubRepoUrl(repoInput);
2010
+ if (!parsed) {
2011
+ throw new Error(`fatal: repository '${repoInput}' does not exist or is not a valid GitHub repository URL`);
2012
+ }
2013
+ if (!vfs) {
2014
+ throw new Error('fatal: virtual filesystem (vfs) is required to clone repository');
2015
+ }
2000
2016
 
2001
- try {
2002
- if (onProgress) {
2003
- onProgress({
2004
- phase: 'connecting',
2005
- message: `Connecting to repository '${repoInput}'...`
2006
- });
2007
- }
2017
+ const fetchFn = options.fetchImpl || (typeof fetch === 'function' ? fetch.bind(globalThis) : null);
2018
+ if (!fetchFn) {
2019
+ throw new Error('fatal: global fetch API is unavailable in this environment');
2020
+ }
2008
2021
 
2009
- const parsed = parseGitHubRepoUrl(repoInput);
2010
- if (!parsed) {
2011
- throw new Error(`fatal: repository '${repoInput}' does not exist or is not a valid GitHub repository URL`);
2012
- }
2013
- if (!vfs) {
2014
- throw new Error('fatal: virtual filesystem (vfs) is required to clone repository');
2015
- }
2022
+ const targetDir = PosixPath.normalize(options.targetDir || '/workspace');
2023
+ const maxFiles = options.maxFiles || 250;
2024
+ const maxFileSize = options.maxFileSize || 512 * 1024;
2025
+ const requestedBranch = options.branch || parsed.branch || null;
2026
+ const { owner, repo } = parsed;
2016
2027
 
2017
- const fetchFn = options.fetchImpl || (typeof fetch === 'function' ? fetch.bind(globalThis) : null);
2018
- if (!fetchFn) {
2019
- throw new Error('fatal: global fetch API is unavailable in this environment');
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;
2020
2034
  }
2035
+ };
2036
+ throwIfAborted();
2021
2037
 
2022
- const targetDir = PosixPath.normalize(options.targetDir || '/workspace');
2023
- const maxFiles = options.maxFiles || 250;
2024
- const maxFileSize = options.maxFileSize || 512 * 1024;
2025
- const requestedBranch = options.branch || parsed.branch || null;
2026
- const { owner, repo } = parsed;
2038
+ let resolvedBranch = requestedBranch;
2039
+ let rawTreeEntries = null;
2040
+ let repoNotFound = false;
2027
2041
 
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();
2042
+ if (onProgress) {
2043
+ onProgress({ phase: 'metadata', message: `Fetching repository metadata for ${owner}/${repo}...` });
2044
+ }
2037
2045
 
2038
- if (onProgress) {
2039
- onProgress({
2040
- phase: 'metadata',
2041
- message: `Fetching repository metadata for ${owner}/${repo}...`
2046
+ // Strategy A: GitHub REST API (with automatic fallback if rate-limited)
2047
+ try {
2048
+ if (!resolvedBranch) {
2049
+ const metaRes = await fetchFn(`https://api.github.com/repos/${owner}/${repo}`, {
2050
+ headers: { Accept: 'application/vnd.github.v3+json' },
2051
+ signal
2042
2052
  });
2043
- }
2044
-
2045
- let resolvedBranch = requestedBranch;
2046
- let rawTreeEntries = null;
2047
- let repoNotFound = false;
2048
-
2049
- // Strategy A: GitHub REST API (with automatic fallback if rate-limited)
2050
- try {
2051
- if (!resolvedBranch) {
2052
- const metaRes = await fetchFn(`https://api.github.com/repos/${owner}/${repo}`, {
2053
- headers: { Accept: 'application/vnd.github.v3+json' },
2054
- signal
2055
- });
2056
- if (metaRes.status === 404) {
2057
- repoNotFound = true;
2058
- } else if (metaRes.ok) {
2059
- const metaJson = await metaRes.json();
2060
- if (metaJson && metaJson.default_branch) {
2061
- resolvedBranch = metaJson.default_branch;
2062
- }
2063
- }
2064
- }
2065
-
2066
- if (!repoNotFound) {
2067
- const branchCandidates = requestedBranch
2068
- ? [requestedBranch]
2069
- : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
2070
-
2071
- for (const cand of branchCandidates) {
2072
- throwIfAborted();
2073
- const treeRes = await fetchFn(
2074
- `https://api.github.com/repos/${owner}/${repo}/git/trees/${encodeURIComponent(cand)}?recursive=1`,
2075
- { headers: { Accept: 'application/vnd.github.v3+json' }, signal }
2076
- );
2077
- if (treeRes.ok) {
2078
- const treeJson = await treeRes.json();
2079
- if (treeJson && Array.isArray(treeJson.tree)) {
2080
- resolvedBranch = cand;
2081
- rawTreeEntries = treeJson.tree
2082
- .filter((item) => item && item.type === 'blob' && item.path)
2083
- .map((item) => ({ path: item.path.replace(/^\/+/, ''), size: item.size || 0 }));
2084
- break;
2085
- }
2053
+ if (metaRes.status === 404) {
2054
+ repoNotFound = true;
2055
+ } else if (metaRes.ok) {
2056
+ const metaJson = await metaRes.json();
2057
+ if (metaJson && metaJson.default_branch) {
2058
+ resolvedBranch = metaJson.default_branch;
2059
+ }
2060
+ }
2061
+ }
2062
+
2063
+ if (!repoNotFound) {
2064
+ const branchCandidates = requestedBranch
2065
+ ? [requestedBranch]
2066
+ : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
2067
+
2068
+ for (const cand of branchCandidates) {
2069
+ throwIfAborted();
2070
+ const treeRes = await fetchFn(
2071
+ `https://api.github.com/repos/${owner}/${repo}/git/trees/${encodeURIComponent(cand)}?recursive=1`,
2072
+ { headers: { Accept: 'application/vnd.github.v3+json' }, signal }
2073
+ );
2074
+ if (treeRes.ok) {
2075
+ const treeJson = await treeRes.json();
2076
+ if (treeJson && Array.isArray(treeJson.tree)) {
2077
+ resolvedBranch = cand;
2078
+ rawTreeEntries = treeJson.tree
2079
+ .filter((item) => item && item.type === 'blob' && item.path)
2080
+ .map((item) => ({ path: item.path.replace(/^\/+/, ''), size: item.size || 0 }));
2081
+ break;
2086
2082
  }
2087
2083
  }
2088
2084
  }
2089
- } catch (_) {
2090
- // Network or rate limit error on api.github.com; proceed to Strategy B
2091
2085
  }
2086
+ } catch (err) {
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);
2089
+ }
2092
2090
 
2093
- // Strategy B: jsDelivr Data API (Zero rate limits, fast global edge cache)
2094
- if (!rawTreeEntries && !repoNotFound) {
2095
- try {
2096
- const branchCandidates = requestedBranch
2097
- ? [requestedBranch]
2098
- : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
2099
-
2100
- for (const cand of branchCandidates) {
2101
- throwIfAborted();
2102
- const flatRes = await fetchFn(
2103
- `https://data.jsdelivr.com/v1/package/gh/${owner}/${repo}@${encodeURIComponent(cand)}/flat`,
2104
- { signal }
2105
- );
2106
- if (flatRes && flatRes.ok) {
2107
- const flatJson = await flatRes.json();
2108
- if (flatJson && Array.isArray(flatJson.files) && flatJson.files.length > 0) {
2109
- resolvedBranch = cand;
2110
- rawTreeEntries = flatJson.files
2111
- .filter((f) => f && f.name)
2112
- .map((f) => ({ path: f.name.replace(/^\/+/, ''), size: f.size || 0 }));
2113
- break;
2114
- }
2091
+ // Strategy B: jsDelivr Data API (Zero rate limits, fast global edge cache)
2092
+ if (!rawTreeEntries && !repoNotFound) {
2093
+ try {
2094
+ const branchCandidates = requestedBranch
2095
+ ? [requestedBranch]
2096
+ : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
2097
+
2098
+ for (const cand of branchCandidates) {
2099
+ throwIfAborted();
2100
+ const flatRes = await fetchFn(
2101
+ `https://data.jsdelivr.com/v1/package/gh/${owner}/${repo}@${encodeURIComponent(cand)}/flat`,
2102
+ { signal }
2103
+ );
2104
+ if (flatRes && flatRes.ok) {
2105
+ const flatJson = await flatRes.json();
2106
+ if (flatJson && Array.isArray(flatJson.files) && flatJson.files.length > 0) {
2107
+ resolvedBranch = cand;
2108
+ rawTreeEntries = flatJson.files
2109
+ .filter((f) => f && f.name)
2110
+ .map((f) => ({ path: f.name.replace(/^\/+/, ''), size: f.size || 0 }));
2111
+ break;
2115
2112
  }
2116
2113
  }
2117
- } catch (_) {}
2114
+ }
2115
+ } catch (err) {
2116
+ _shellLogger.debug('jsDelivr flat tree fetch failed.', err);
2118
2117
  }
2118
+ }
2119
2119
 
2120
- if (repoNotFound || !rawTreeEntries) {
2121
- throw new Error(`fatal: repository '${parsed.url}' not found or could not be fetched`);
2122
- }
2120
+ if (repoNotFound || !rawTreeEntries) {
2121
+ throw new Error(`fatal: repository '${parsed.url}' not found or could not be fetched`);
2122
+ }
2123
2123
 
2124
- // Filter subpath if specified (e.g. /tree/main/examples)
2125
- const subPrefix = parsed.subpath ? parsed.subpath.replace(/^\/+|\/+$/g, '') + '/' : null;
2126
- const filtered = [];
2127
- for (const item of rawTreeEntries) {
2128
- let destPath = item.path;
2129
- if (subPrefix) {
2130
- if (item.path === parsed.subpath) {
2131
- destPath = PosixPath.basename(item.path);
2132
- } else if (item.path.startsWith(subPrefix)) {
2133
- destPath = item.path.slice(subPrefix.length);
2134
- } else {
2135
- continue;
2136
- }
2137
- }
2138
- if (!destPath || destPath.startsWith('.git/') || destPath.includes('/node_modules/') || destPath.startsWith('node_modules/')) {
2139
- continue;
2140
- }
2141
- if (BINARY_OR_HEAVY_EXT_RE.test(destPath)) {
2142
- continue;
2143
- }
2144
- if (item.size && item.size > maxFileSize) {
2124
+ // Filter subpath if specified (e.g. /tree/main/examples)
2125
+ const subPrefix = parsed.subpath ? parsed.subpath.replace(/^\/+|\/+$/g, '') + '/' : null;
2126
+ const filtered = [];
2127
+ for (const item of rawTreeEntries) {
2128
+ let destPath = item.path;
2129
+ if (subPrefix) {
2130
+ if (item.path === parsed.subpath) {
2131
+ destPath = PosixPath.basename(item.path);
2132
+ } else if (item.path.startsWith(subPrefix)) {
2133
+ destPath = item.path.slice(subPrefix.length);
2134
+ } else {
2145
2135
  continue;
2146
2136
  }
2147
- filtered.push({
2148
- repoPath: item.path,
2149
- destPath,
2150
- size: item.size || 0,
2151
- priority: scoreRepoFilePriority(destPath)
2152
- });
2153
2137
  }
2138
+ if (!destPath || destPath.startsWith('.git/') || destPath.includes('/node_modules/') || destPath.startsWith('node_modules/')) {
2139
+ continue;
2140
+ }
2141
+ if (BINARY_OR_HEAVY_EXT_RE.test(destPath)) {
2142
+ continue;
2143
+ }
2144
+ if (item.size && item.size > maxFileSize) {
2145
+ continue;
2146
+ }
2147
+ filtered.push({
2148
+ repoPath: item.path,
2149
+ destPath,
2150
+ size: item.size || 0,
2151
+ priority: scoreRepoFilePriority(destPath)
2152
+ });
2153
+ }
2154
2154
 
2155
- filtered.sort((a, b) => a.priority - b.priority || a.destPath.localeCompare(b.destPath));
2156
- const selectedFiles = filtered.slice(0, maxFiles);
2157
- const totalToDownload = selectedFiles.length;
2155
+ filtered.sort((a, b) => a.priority - b.priority || a.destPath.localeCompare(b.destPath));
2156
+ const selectedFiles = filtered.slice(0, maxFiles);
2157
+ const totalToDownload = selectedFiles.length;
2158
2158
 
2159
- if (onProgress) {
2160
- onProgress({
2161
- phase: 'downloading',
2162
- message: `Downloading files (0/${totalToDownload})...`,
2163
- loaded: 0,
2164
- total: totalToDownload
2165
- });
2166
- }
2159
+ if (onProgress) {
2160
+ onProgress({ phase: 'downloading', message: `Downloading files (0/${totalToDownload})...`, loaded: 0, total: totalToDownload });
2161
+ }
2167
2162
 
2168
- if (!vfs.existsSync(targetDir)) {
2169
- vfs.mkdirSync(targetDir, { recursive: true });
2170
- }
2163
+ if (!vfs.existsSync(targetDir)) {
2164
+ vfs.mkdirSync(targetDir, { recursive: true });
2165
+ }
2171
2166
 
2172
- const headSnapshot = {};
2173
- let filesWritten = 0;
2174
- let totalBytes = 0;
2175
- const BATCH_SIZE = 12;
2167
+ const headSnapshot = {};
2168
+ let filesWritten = 0;
2169
+ let totalBytes = 0;
2170
+ const BATCH_SIZE = 12;
2176
2171
 
2177
- for (let i = 0; i < selectedFiles.length; i += BATCH_SIZE) {
2178
- throwIfAborted();
2179
- const batch = selectedFiles.slice(i, i + BATCH_SIZE);
2180
- await Promise.all(
2181
- batch.map(async (entry) => {
2182
- throwIfAborted();
2183
- const encodedPath = entry.repoPath.split('/').map(encodeURIComponent).join('/');
2184
- const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
2185
- const cdnUrl = `https://cdn.jsdelivr.net/gh/${owner}/${repo}@${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
2172
+ for (let i = 0; i < selectedFiles.length; i += BATCH_SIZE) {
2173
+ throwIfAborted();
2174
+ const batch = selectedFiles.slice(i, i + BATCH_SIZE);
2175
+ await Promise.all(
2176
+ batch.map(async (entry) => {
2177
+ throwIfAborted();
2178
+ const encodedPath = entry.repoPath.split('/').map(encodeURIComponent).join('/');
2179
+ const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
2180
+ const cdnUrl = `https://cdn.jsdelivr.net/gh/${owner}/${repo}@${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
2181
+
2182
+ let text = null;
2183
+ try {
2184
+ const r1 = await fetchFn(rawUrl, { signal });
2185
+ if (r1 && r1.ok) {
2186
+ text = await r1.text();
2187
+ }
2188
+ } catch (_) {
2189
+ if (signal && signal.aborted) throw _;
2190
+ }
2186
2191
 
2187
- let text = null;
2192
+ if (text === null) {
2188
2193
  try {
2189
- const r1 = await fetchFn(rawUrl, { signal });
2190
- if (r1 && r1.ok) {
2191
- text = await r1.text();
2194
+ const r2 = await fetchFn(cdnUrl, { signal });
2195
+ if (r2 && r2.ok) {
2196
+ text = await r2.text();
2192
2197
  }
2193
2198
  } catch (_) {
2194
2199
  if (signal && signal.aborted) throw _;
2195
2200
  }
2201
+ }
2196
2202
 
2197
- if (text === null) {
2198
- try {
2199
- const r2 = await fetchFn(cdnUrl, { signal });
2200
- if (r2 && r2.ok) {
2201
- text = await r2.text();
2202
- }
2203
- } catch (_) {
2204
- if (signal && signal.aborted) throw _;
2205
- }
2203
+ if (text !== null && text.length <= maxFileSize) {
2204
+ const absPath = PosixPath.join(targetDir, entry.destPath);
2205
+ const parentDir = PosixPath.dirname(absPath);
2206
+ if (!vfs.existsSync(parentDir)) {
2207
+ vfs.mkdirSync(parentDir, { recursive: true });
2206
2208
  }
2207
-
2208
- if (text !== null && text.length <= maxFileSize) {
2209
- const absPath = PosixPath.join(targetDir, entry.destPath);
2210
- const parentDir = PosixPath.dirname(absPath);
2211
- if (!vfs.existsSync(parentDir)) {
2212
- vfs.mkdirSync(parentDir, { recursive: true });
2213
- }
2214
- vfs.writeFileSync(absPath, text);
2215
- headSnapshot[entry.destPath] = text;
2216
- filesWritten++;
2217
- totalBytes += text.length;
2218
-
2219
- if (onProgress) {
2220
- onProgress({
2221
- phase: 'downloading',
2222
- message: `Downloading files (${filesWritten}/${totalToDownload}): ${entry.destPath}`,
2223
- loaded: filesWritten,
2224
- total: totalToDownload
2225
- });
2226
- }
2227
-
2228
- if (typeof options.onFile === 'function') {
2229
- options.onFile(absPath, text, entry.destPath);
2230
- }
2209
+ vfs.writeFileSync(absPath, text);
2210
+ headSnapshot[entry.destPath] = text;
2211
+ filesWritten++;
2212
+ totalBytes += text.length;
2213
+ if (onProgress) {
2214
+ onProgress({ phase: 'downloading', message: `Downloading files (${filesWritten}/${totalToDownload}): ${entry.destPath}`, loaded: filesWritten, total: totalToDownload });
2231
2215
  }
2232
- })
2233
- );
2234
- }
2216
+ if (typeof options.onFile === 'function') {
2217
+ options.onFile(absPath, text, entry.destPath);
2218
+ }
2219
+ }
2220
+ })
2221
+ );
2222
+ }
2235
2223
 
2236
- throwIfAborted();
2224
+ throwIfAborted();
2237
2225
 
2238
- if (onProgress) {
2239
- onProgress({
2240
- phase: 'mounting',
2241
- message: `Mounting files and writing Git metadata into ${targetDir}...`,
2242
- loaded: filesWritten,
2243
- total: totalToDownload
2244
- });
2245
- }
2226
+ if (onProgress) {
2227
+ onProgress({ phase: 'mounting', message: `Mounting files and writing Git metadata into ${targetDir}...`, loaded: filesWritten, total: totalToDownload });
2228
+ }
2246
2229
 
2247
- // Write .git metadata inside targetDir
2248
- const gitDir = PosixPath.join(targetDir, '.git');
2249
- if (!vfs.existsSync(gitDir)) {
2250
- vfs.mkdirSync(gitDir, { recursive: true });
2251
- }
2252
- vfs.writeFileSync(PosixPath.join(gitDir, 'HEAD'), `ref: refs/heads/${resolvedBranch}\n`);
2253
- vfs.writeFileSync(
2254
- PosixPath.join(gitDir, 'config'),
2255
- `[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n[remote "origin"]\n\turl = ${parsed.url}\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n[branch "${resolvedBranch}"]\n\tremote = origin\n\tmerge = refs/heads/${resolvedBranch}\n`
2230
+ // Write .git metadata inside targetDir
2231
+ const gitDir = PosixPath.join(targetDir, '.git');
2232
+ if (!vfs.existsSync(gitDir)) {
2233
+ vfs.mkdirSync(gitDir, { recursive: true });
2234
+ }
2235
+ vfs.writeFileSync(PosixPath.join(gitDir, 'HEAD'), `ref: refs/heads/${resolvedBranch}\n`);
2236
+ vfs.writeFileSync(
2237
+ PosixPath.join(gitDir, 'config'),
2238
+ `[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n[remote "origin"]\n\turl = ${parsed.url}\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n[branch "${resolvedBranch}"]\n\tremote = origin\n\tmerge = refs/heads/${resolvedBranch}\n`
2239
+ );
2240
+
2241
+ // Fetch recent commits (best-effort)
2242
+ let commits = [];
2243
+ try {
2244
+ const commitsRes = await fetchFn(
2245
+ `https://api.github.com/repos/${owner}/${repo}/commits?sha=${encodeURIComponent(resolvedBranch)}&per_page=10`,
2246
+ { headers: { Accept: 'application/vnd.github.v3+json' }, signal }
2256
2247
  );
2257
-
2258
- // Fetch recent commits (best-effort)
2259
- let commits = [];
2260
- try {
2261
- const commitsRes = await fetchFn(
2262
- `https://api.github.com/repos/${owner}/${repo}/commits?sha=${encodeURIComponent(resolvedBranch)}&per_page=10`,
2263
- { headers: { Accept: 'application/vnd.github.v3+json' }, signal }
2264
- );
2265
- if (commitsRes && commitsRes.ok) {
2266
- const commitsJson = await commitsRes.json();
2267
- if (Array.isArray(commitsJson) && commitsJson.length > 0) {
2268
- commits = commitsJson.map((c) => ({
2269
- hash: String(c.sha || 'a1b2c3d').slice(0, 7),
2270
- author:
2271
- c.commit && c.commit.author
2272
- ? `${c.commit.author.name || owner} <${c.commit.author.email || `${owner}@users.noreply.github.com`}>`
2273
- : `${owner} <${owner}@users.noreply.github.com>`,
2274
- date:
2275
- c.commit && c.commit.author && c.commit.author.date
2276
- ? new Date(c.commit.author.date).toUTCString()
2277
- : new Date().toUTCString(),
2278
- message: c.commit && c.commit.message ? String(c.commit.message).split('\n')[0] : 'Commit'
2279
- }));
2280
- }
2281
- }
2282
- } catch (_) {}
2283
-
2284
- if (commits.length === 0) {
2285
- commits = [
2286
- {
2287
- hash: 'a1b2c3d',
2288
- author: `${owner} <${owner}@users.noreply.github.com>`,
2289
- date: new Date().toUTCString(),
2290
- message: `Clone ${owner}/${repo} (${resolvedBranch})`
2291
- }
2292
- ];
2248
+ if (commitsRes && commitsRes.ok) {
2249
+ const commitsJson = await commitsRes.json();
2250
+ if (Array.isArray(commitsJson) && commitsJson.length > 0) {
2251
+ commits = commitsJson.map((c) => ({
2252
+ hash: String(c.sha || 'a1b2c3d').slice(0, 7),
2253
+ author:
2254
+ c.commit && c.commit.author
2255
+ ? `${c.commit.author.name || owner} <${c.commit.author.email || `${owner}@users.noreply.github.com`}>`
2256
+ : `${owner} <${owner}@users.noreply.github.com>`,
2257
+ date:
2258
+ c.commit && c.commit.author && c.commit.author.date
2259
+ ? new Date(c.commit.author.date).toUTCString()
2260
+ : new Date().toUTCString(),
2261
+ message: c.commit && c.commit.message ? String(c.commit.message).split('\n')[0] : 'Commit'
2262
+ }));
2263
+ }
2293
2264
  }
2265
+ } catch (err) {
2266
+ _shellLogger.debug('Optional commit history fetch skipped.', err);
2267
+ }
2294
2268
 
2295
- if (onProgress) {
2296
- onProgress({
2297
- phase: 'ready',
2298
- message: `Repository cloned successfully (${filesWritten} files).`,
2299
- loaded: filesWritten,
2300
- total: totalToDownload
2301
- });
2302
- }
2269
+ if (commits.length === 0) {
2270
+ commits = [
2271
+ {
2272
+ hash: 'a1b2c3d',
2273
+ author: `${owner} <${owner}@users.noreply.github.com>`,
2274
+ date: new Date().toUTCString(),
2275
+ message: `Clone ${owner}/${repo} (${resolvedBranch})`
2276
+ }
2277
+ ];
2278
+ }
2303
2279
 
2304
- return {
2305
- owner,
2306
- repo,
2307
- branch: resolvedBranch,
2308
- url: parsed.url,
2309
- targetDir,
2310
- count: filesWritten,
2311
- fileCount: filesWritten,
2312
- filesWritten,
2313
- totalBytes,
2314
- commits,
2315
- headSnapshot
2316
- };
2280
+ if (onProgress) {
2281
+ onProgress({ phase: 'ready', message: `Repository cloned successfully (${filesWritten} files).`, loaded: filesWritten, total: totalToDownload });
2282
+ }
2283
+
2284
+ return {
2285
+ owner,
2286
+ repo,
2287
+ branch: resolvedBranch,
2288
+ url: parsed.url,
2289
+ targetDir,
2290
+ count: filesWritten,
2291
+ fileCount: filesWritten,
2292
+ filesWritten,
2293
+ totalBytes,
2294
+ commits,
2295
+ headSnapshot
2296
+ };
2297
+ }
2298
+
2299
+ // Public wrapper: guarantee an `error` progress event when the clone fails
2300
+ // for any reason (invalid URL, missing vfs, fetch rejection, abort, ...).
2301
+ async function cloneGitHubRepository(repoInput, vfs, options = {}) {
2302
+ const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
2303
+ try {
2304
+ return await _cloneGitHubRepository(repoInput, vfs, options);
2317
2305
  } catch (err) {
2318
2306
  if (onProgress) {
2319
2307
  onProgress({
@@ -2342,7 +2330,9 @@ function __initShellModule(root: any) {
2342
2330
  try {
2343
2331
  const parsed = JSON.parse(vfs.readFileSync(p, 'utf8'));
2344
2332
  return { path: p, data: parsed };
2345
- } catch (_) {}
2333
+ } catch (err) {
2334
+ _shellLogger.warn(`Invalid JSON in ${p}; falling back to default package metadata.`, err);
2335
+ }
2346
2336
  }
2347
2337
  return { path: p, data: { name: 'app', dependencies: {}, devDependencies: {}, scripts: {} } };
2348
2338
  }
@@ -2383,13 +2373,20 @@ function __initShellModule(root: any) {
2383
2373
  vfs.rmdirSync(dirPath);
2384
2374
  }
2385
2375
  if (typeof emitMutation === 'function') emitMutation('delete', dirPath);
2386
- } catch (_) {}
2376
+ } catch (err) {
2377
+ _shellLogger.debug('removeDirRecursive failed.', dirPath, err);
2378
+ }
2387
2379
  }
2388
2380
 
2389
2381
  // ---------------------------------------------------------------------------
2390
2382
  // Real npm package installation via the jsDelivr CDN
2391
2383
  // ---------------------------------------------------------------------------
2392
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
+ ];
2393
2390
 
2394
2391
  // Minimal offline registry, used only when the CDN is unreachable so common
2395
2392
  // demos still resolve without network access.
@@ -2535,16 +2532,23 @@ function __initShellModule(root: any) {
2535
2532
  }
2536
2533
 
2537
2534
  async function resolvePackageMetadata(fetchImpl, name, range) {
2538
- const urls = range
2539
- ? [`${CDN_NPM_BASE}/${name}@${range}/package.json`, `${CDN_NPM_BASE}/${name}/package.json`]
2540
- : [`${CDN_NPM_BASE}/${name}/package.json`];
2541
- for (const url of urls) {
2542
- const text = await fetchTextFromCdn(fetchImpl, url);
2543
- if (!text) continue;
2544
- try {
2545
- const parsed = JSON.parse(text);
2546
- if (parsed && parsed.version) return parsed;
2547
- } 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
+ }
2548
2552
  }
2549
2553
  return null;
2550
2554
  }
@@ -2562,6 +2566,7 @@ function __initShellModule(root: any) {
2562
2566
  return { ok: false, reason: `${name}: package metadata not found on the registry (offline?)` };
2563
2567
  }
2564
2568
 
2569
+ const activeCdnBase = meta._resolvedCdnBase || CDN_NPM_BASE;
2565
2570
  const version = meta.version;
2566
2571
  const key = `${name}@${version}`;
2567
2572
  if (seen.has(key)) {
@@ -2609,7 +2614,7 @@ function __initShellModule(root: any) {
2609
2614
  frontier = [];
2610
2615
  if (batch.length === 0) break;
2611
2616
  const texts = await Promise.all(
2612
- batch.map((rel) => fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/${rel}`))
2617
+ batch.map((rel) => fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/${rel}`))
2613
2618
  );
2614
2619
  for (let idx = 0; idx < batch.length; idx++) {
2615
2620
  const rel = batch[idx];
@@ -2633,7 +2638,7 @@ function __initShellModule(root: any) {
2633
2638
  }
2634
2639
  // The declared entry may be missing on the CDN; fall back to index.js.
2635
2640
  if (!files.some(f => f.rel === entry)) {
2636
- const idxText = await fetchTextFromCdn(fetchImpl, `${CDN_NPM_BASE}/${name}@${version}/index.js`);
2641
+ const idxText = await fetchTextFromCdn(fetchImpl, `${activeCdnBase}/${name}@${version}/index.js`);
2637
2642
  if (idxText !== null) files.push({ rel: 'index.js', content: idxText });
2638
2643
  }
2639
2644
 
@@ -2643,16 +2648,16 @@ function __initShellModule(root: any) {
2643
2648
  // parent actually asked for — e.g. chalk@4 needs ansi-styles@^4, which itself
2644
2649
  // needs color-convert. Resolving transitive names as "latest" silently breaks
2645
2650
  // the tree (ansi-styles@6 has no deps at all).
2646
- const depSpecs: Array<{ name: string; range: string | null }> = [];
2647
- const depSeen = new Set<string>();
2648
- const declared = (meta.dependencies || {}) as Record<string, string>;
2651
+ const depSpecs = [];
2652
+ const depSeen = new Set();
2653
+ const declared = meta.dependencies || {};
2649
2654
  for (const depName of Object.keys(declared)) {
2650
2655
  if (depSeen.has(depName)) continue;
2651
2656
  depSeen.add(depName);
2652
2657
  depSpecs.push({ name: depName, range: declared[depName] || null });
2653
2658
  }
2654
2659
  const peerMeta = meta.peerDependenciesMeta || {};
2655
- const peers = (meta.peerDependencies || {}) as Record<string, string>;
2660
+ const peers = meta.peerDependencies || {};
2656
2661
  for (const peer of Object.keys(peers)) {
2657
2662
  if (peerMeta[peer] && peerMeta[peer].optional) continue;
2658
2663
  if (depSeen.has(peer)) continue;
@@ -2680,7 +2685,9 @@ function __initShellModule(root: any) {
2680
2685
  // directory target would otherwise raise EISDIR).
2681
2686
  try {
2682
2687
  if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
2683
- } catch (_) {}
2688
+ } catch (err) {
2689
+ _shellLogger.debug('Package install statSync check skipped.', full, err);
2690
+ }
2684
2691
  ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
2685
2692
  ctx.vfs.writeFileSync(full, f.content);
2686
2693
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
@@ -2758,6 +2765,32 @@ function __initShellModule(root: any) {
2758
2765
  pkgData[depField][pkgName] = range || (directVersion ? `^${directVersion}` : (pkgData[depField][pkgName] || 'latest'));
2759
2766
  writePackageJson(ctx.vfs, pkgPath, pkgData, ctx.emitMutation);
2760
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
+
2761
2794
  return { name: pkgName, ok: true, version: directVersion, installed, warning };
2762
2795
  }
2763
2796
 
@@ -2955,7 +2988,9 @@ function __initShellModule(root: any) {
2955
2988
  const parsed = JSON.parse(vfs.readFileSync(modPkg, 'utf8'));
2956
2989
  if (parsed && parsed.version) return parsed.version;
2957
2990
  }
2958
- } catch (_) {}
2991
+ } catch (err) {
2992
+ _shellLogger.debug('Could not read installed module package.json.', pkgName, err);
2993
+ }
2959
2994
  try {
2960
2995
  for (const dir of [rootDir, '/workspace']) {
2961
2996
  const pkgPath = PosixPath.join(dir, 'package.json');
@@ -2964,7 +2999,9 @@ function __initShellModule(root: any) {
2964
2999
  const deps = Object.assign({}, parsed.dependencies || {}, parsed.devDependencies || {}, parsed.peerDependencies || {});
2965
3000
  if (deps[pkgName]) return normalizeVersionRange(deps[pkgName]);
2966
3001
  }
2967
- } catch (_) {}
3002
+ } catch (err) {
3003
+ _shellLogger.debug('Could not read workspace package.json for version resolution.', pkgName, err);
3004
+ }
2968
3005
  return 'latest';
2969
3006
  }
2970
3007
 
@@ -3002,7 +3039,7 @@ function __initShellModule(root: any) {
3002
3039
  if (dirFlag) {
3003
3040
  walk(full, depth + 1);
3004
3041
  } else if (isPreviewScriptPath(name) && scripts.length < maxFiles) {
3005
- 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); }
3006
3043
  }
3007
3044
  }
3008
3045
  };
@@ -3049,7 +3086,7 @@ function __initShellModule(root: any) {
3049
3086
 
3050
3087
  const handler = async (request) => {
3051
3088
  let pathname = '/';
3052
- 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); }
3053
3090
  const rel = pathname.replace(/^\/+/, '');
3054
3091
  let target = PosixPath.join(rootDir, rel);
3055
3092
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
@@ -3088,7 +3125,9 @@ function __initShellModule(root: any) {
3088
3125
  if (rm && typeof rm.transpileForBrowser === 'function') {
3089
3126
  body = rm.transpileForBrowser(body, target);
3090
3127
  }
3091
- } catch (_) {}
3128
+ } catch (err) {
3129
+ _shellLogger.warn(`Preview script transpilation failed for ${target}.`, err);
3130
+ }
3092
3131
  }
3093
3132
 
3094
3133
  return new Response(body, { status: 200, headers: { 'content-type': previewMimeFor(target) } });
@@ -3096,7 +3135,7 @@ function __initShellModule(root: any) {
3096
3135
 
3097
3136
  const pid = (ctx.shell && typeof ctx.shell.nextPid === 'number') ? ctx.shell.nextPid++ : (ctx.pid || 1000);
3098
3137
  return portTable.registerServer(port, {
3099
- server: { close() { try { portTable.unregisterServer(port); } catch (_) {} } },
3138
+ server: { close() { try { portTable.unregisterServer(port); } catch (err) { _shellLogger.debug('Preview server unregister failed.', port, err); } } },
3100
3139
  fetch: handler,
3101
3140
  name: 'code-lab-serve',
3102
3141
  pid,
@@ -3209,7 +3248,9 @@ function __initShellModule(root: any) {
3209
3248
  let isDir = false;
3210
3249
  try {
3211
3250
  isDir = ctx.vfs.statSync(resolved).isDirectory();
3212
- } catch (_) {}
3251
+ } catch (err) {
3252
+ _shellLogger.debug('cd statSync failed.', resolved, err);
3253
+ }
3213
3254
 
3214
3255
  if (!isDir) {
3215
3256
  return { code: 1, stdout: '', stderr: `cd: ${target}: Not a directory\n` };
@@ -3309,7 +3350,9 @@ function __initShellModule(root: any) {
3309
3350
  isDirectory = st.isDirectory();
3310
3351
  size = st.size;
3311
3352
  mtimeMs = st.mtimeMs || Date.now();
3312
- } catch (_) {}
3353
+ } catch (err) {
3354
+ _shellLogger.debug('ls statSync skipped.', itemPath, err);
3355
+ }
3313
3356
  return { name, isDirectory, size, mtimeMs, absPath: itemPath };
3314
3357
  });
3315
3358
 
@@ -3729,7 +3772,9 @@ function __initShellModule(root: any) {
3729
3772
  if (st.isDirectory()) walk(full);
3730
3773
  else targets.push(full);
3731
3774
  }
3732
- } catch (_) {}
3775
+ } catch (err) {
3776
+ _shellLogger.debug('grep directory walk skipped.', dir, err);
3777
+ }
3733
3778
  }
3734
3779
  if (ctx.vfs.existsSync(absRoot)) {
3735
3780
  const st = ctx.vfs.statSync(absRoot);
@@ -3853,7 +3898,9 @@ function __initShellModule(root: any) {
3853
3898
  let isDir = false;
3854
3899
  try {
3855
3900
  isDir = ctx.vfs.statSync(full).isDirectory();
3856
- } catch (_) {}
3901
+ } catch (err) {
3902
+ _shellLogger.debug('find statSync skipped.', full, err);
3903
+ }
3857
3904
 
3858
3905
  const relPath = root === '.'
3859
3906
  ? './' + full.replace(absRoot.endsWith('/') ? absRoot : absRoot + '/', '')
@@ -3872,7 +3919,7 @@ function __initShellModule(root: any) {
3872
3919
  // Root itself check
3873
3920
  if (ctx.vfs.existsSync(absRoot)) {
3874
3921
  let isDir = false;
3875
- 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); }
3876
3923
  if (!typeFilter || (typeFilter === 'd' && isDir) || (typeFilter === 'f' && !isDir)) {
3877
3924
  if (!nameRegex || nameRegex.test(PosixPath.basename(root))) {
3878
3925
  results.push(root);
@@ -4784,7 +4831,7 @@ function __initShellModule(root: any) {
4784
4831
  const isLast = i === entries.length - 1;
4785
4832
  const full = dirPath === '/' ? '/' + entry : dirPath + '/' + entry;
4786
4833
  let isDir = false;
4787
- 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); }
4788
4835
 
4789
4836
  stdout += `${prefix}${isLast ? '└── ' : '├── '}${entry}\n`;
4790
4837
 
@@ -5012,10 +5059,10 @@ function __initShellModule(root: any) {
5012
5059
  for (const s of ctx.shell.portTable.listServers()) {
5013
5060
  if (s.pid !== undefined && String(s.pid) === String(pid)) {
5014
5061
  if (s.server && typeof s.server.close === 'function') {
5015
- try { s.server.close(); } catch (_) {}
5062
+ try { s.server.close(); } catch (err) { _shellLogger.debug('kill server.close failed.', err); }
5016
5063
  }
5017
5064
  if (typeof s.stop === 'function') {
5018
- try { s.stop(); } catch (_) {}
5065
+ try { s.stop(); } catch (err) { _shellLogger.debug('kill server.stop failed.', err); }
5019
5066
  }
5020
5067
  ctx.shell.portTable.unregisterServer(s.port);
5021
5068
  killedPort = true;
@@ -7304,17 +7351,11 @@ function __initShellModule(root: any) {
7304
7351
  parseGitHubRepoUrl,
7305
7352
  cloneGitHubRepository
7306
7353
  };
7354
+ });
7307
7355
 
7308
- }
7309
-
7310
- const _hostShell: any = __initShellModule(typeof globalThis !== 'undefined' ? globalThis : this);
7311
-
7312
- if (typeof globalThis !== 'undefined') {
7313
- (globalThis as any).CodeLabShell = _hostShell;
7314
- }
7315
- if (typeof module !== 'undefined' && module.exports) {
7316
- module.exports = _hostShell;
7317
- }
7356
+ // ── TypeScript module surface (stripped from browser bundles) ──────────────
7357
+ const _hostShell: any = (typeof globalThis !== 'undefined' ? (globalThis as any).CodeLabShell : undefined)
7358
+ || (typeof module !== 'undefined' && module.exports ? module.exports : {});
7318
7359
 
7319
7360
  export const createPosixShell: (options?: any) => any = _hostShell.createPosixShell;
7320
7361
  export const parseShellCommand: (cmd: string) => any = _hostShell.parseShellCommand;
@@ -7325,7 +7366,7 @@ export const PosixPath: any = _hostShell.PosixPath;
7325
7366
  export const expandGlob: (pattern: string, vfs: any, cwd?: string) => string[] = _hostShell.expandGlob;
7326
7367
  export const createVirtualPortTable: () => any = _hostShell.createVirtualPortTable;
7327
7368
  export const parseGitHubRepoUrl: (input: string) => any = _hostShell.parseGitHubRepoUrl;
7328
- export const cloneGitHubRepository: (repoInput: string, vfs: any, options?: GitHubCloneOptions) => Promise<CloneResult> = _hostShell.cloneGitHubRepository;
7369
+ export const cloneGitHubRepository: (repoInput: string, vfs: any, options?: any) => Promise<any> = _hostShell.cloneGitHubRepository;
7329
7370
  export const CodeLabShell: any = _hostShell;
7330
7371
 
7331
7372
  export default _hostShell;