@innovatorved/code-lab 0.1.5 → 0.1.7

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
@@ -1,64 +1,55 @@
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
 
57
48
  function getRuntimeModule() {
58
49
  if (typeof root !== 'undefined' && root && root.CodeLabRuntime) return root.CodeLabRuntime;
59
50
  if (typeof globalThis !== 'undefined' && globalThis.CodeLabRuntime) return globalThis.CodeLabRuntime;
60
51
  try {
61
- if (typeof require !== 'undefined') { try { return require('./runtime.js'); } catch (_) {} try { return require('./runtime'); } catch (_) {} try { return require('../dist/runtime.js'); } catch (_) {} }
52
+ if (typeof require !== 'undefined') return require('./runtime.js');
62
53
  } catch (_) {}
63
54
  return null;
64
55
  }
@@ -1995,325 +1986,302 @@ function __initShellModule(root: any) {
1995
1986
  return 10 + depth * 0.1;
1996
1987
  }
1997
1988
 
1998
- async function cloneGitHubRepository(repoInput, vfs, options = {}) {
1989
+ async function _cloneGitHubRepository(repoInput, vfs, options = {}) {
1999
1990
  const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
1991
+ if (onProgress) {
1992
+ onProgress({ phase: 'connecting', message: `Connecting to repository '${repoInput}'...` });
1993
+ }
1994
+ const parsed = parseGitHubRepoUrl(repoInput);
1995
+ if (!parsed) {
1996
+ throw new Error(`fatal: repository '${repoInput}' does not exist or is not a valid GitHub repository URL`);
1997
+ }
1998
+ if (!vfs) {
1999
+ throw new Error('fatal: virtual filesystem (vfs) is required to clone repository');
2000
+ }
2000
2001
 
2001
- try {
2002
- if (onProgress) {
2003
- onProgress({
2004
- phase: 'connecting',
2005
- message: `Connecting to repository '${repoInput}'...`
2006
- });
2007
- }
2002
+ const fetchFn = options.fetchImpl || (typeof fetch === 'function' ? fetch.bind(globalThis) : null);
2003
+ if (!fetchFn) {
2004
+ throw new Error('fatal: global fetch API is unavailable in this environment');
2005
+ }
2008
2006
 
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
- }
2007
+ const targetDir = PosixPath.normalize(options.targetDir || '/workspace');
2008
+ const maxFiles = options.maxFiles || 250;
2009
+ const maxFileSize = options.maxFileSize || 512 * 1024;
2010
+ const requestedBranch = options.branch || parsed.branch || null;
2011
+ const { owner, repo } = parsed;
2016
2012
 
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');
2013
+ const signal = options.signal || null;
2014
+ const throwIfAborted = () => {
2015
+ if (signal && signal.aborted) {
2016
+ const abortErr = new Error('fatal: clone cancelled (SIGINT)');
2017
+ abortErr.name = 'AbortError';
2018
+ throw abortErr;
2020
2019
  }
2020
+ };
2021
+ throwIfAborted();
2021
2022
 
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;
2023
+ let resolvedBranch = requestedBranch;
2024
+ let rawTreeEntries = null;
2025
+ let repoNotFound = false;
2027
2026
 
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();
2027
+ if (onProgress) {
2028
+ onProgress({ phase: 'metadata', message: `Fetching repository metadata for ${owner}/${repo}...` });
2029
+ }
2037
2030
 
2038
- if (onProgress) {
2039
- onProgress({
2040
- phase: 'metadata',
2041
- message: `Fetching repository metadata for ${owner}/${repo}...`
2031
+ // Strategy A: GitHub REST API (with automatic fallback if rate-limited)
2032
+ try {
2033
+ if (!resolvedBranch) {
2034
+ const metaRes = await fetchFn(`https://api.github.com/repos/${owner}/${repo}`, {
2035
+ headers: { Accept: 'application/vnd.github.v3+json' },
2036
+ signal
2042
2037
  });
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
- }
2038
+ if (metaRes.status === 404) {
2039
+ repoNotFound = true;
2040
+ } else if (metaRes.ok) {
2041
+ const metaJson = await metaRes.json();
2042
+ if (metaJson && metaJson.default_branch) {
2043
+ resolvedBranch = metaJson.default_branch;
2044
+ }
2045
+ }
2046
+ }
2047
+
2048
+ if (!repoNotFound) {
2049
+ const branchCandidates = requestedBranch
2050
+ ? [requestedBranch]
2051
+ : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
2052
+
2053
+ for (const cand of branchCandidates) {
2054
+ throwIfAborted();
2055
+ const treeRes = await fetchFn(
2056
+ `https://api.github.com/repos/${owner}/${repo}/git/trees/${encodeURIComponent(cand)}?recursive=1`,
2057
+ { headers: { Accept: 'application/vnd.github.v3+json' }, signal }
2058
+ );
2059
+ if (treeRes.ok) {
2060
+ const treeJson = await treeRes.json();
2061
+ if (treeJson && Array.isArray(treeJson.tree)) {
2062
+ resolvedBranch = cand;
2063
+ rawTreeEntries = treeJson.tree
2064
+ .filter((item) => item && item.type === 'blob' && item.path)
2065
+ .map((item) => ({ path: item.path.replace(/^\/+/, ''), size: item.size || 0 }));
2066
+ break;
2086
2067
  }
2087
2068
  }
2088
2069
  }
2089
- } catch (_) {
2090
- // Network or rate limit error on api.github.com; proceed to Strategy B
2091
2070
  }
2071
+ } catch (_) {
2072
+ // Network or rate limit error on api.github.com; proceed to Strategy B
2073
+ }
2092
2074
 
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
- }
2075
+ // Strategy B: jsDelivr Data API (Zero rate limits, fast global edge cache)
2076
+ if (!rawTreeEntries && !repoNotFound) {
2077
+ try {
2078
+ const branchCandidates = requestedBranch
2079
+ ? [requestedBranch]
2080
+ : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
2081
+
2082
+ for (const cand of branchCandidates) {
2083
+ throwIfAborted();
2084
+ const flatRes = await fetchFn(
2085
+ `https://data.jsdelivr.com/v1/package/gh/${owner}/${repo}@${encodeURIComponent(cand)}/flat`,
2086
+ { signal }
2087
+ );
2088
+ if (flatRes && flatRes.ok) {
2089
+ const flatJson = await flatRes.json();
2090
+ if (flatJson && Array.isArray(flatJson.files) && flatJson.files.length > 0) {
2091
+ resolvedBranch = cand;
2092
+ rawTreeEntries = flatJson.files
2093
+ .filter((f) => f && f.name)
2094
+ .map((f) => ({ path: f.name.replace(/^\/+/, ''), size: f.size || 0 }));
2095
+ break;
2115
2096
  }
2116
2097
  }
2117
- } catch (_) {}
2118
- }
2098
+ }
2099
+ } catch (_) {}
2100
+ }
2119
2101
 
2120
- if (repoNotFound || !rawTreeEntries) {
2121
- throw new Error(`fatal: repository '${parsed.url}' not found or could not be fetched`);
2122
- }
2102
+ if (repoNotFound || !rawTreeEntries) {
2103
+ throw new Error(`fatal: repository '${parsed.url}' not found or could not be fetched`);
2104
+ }
2123
2105
 
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) {
2106
+ // Filter subpath if specified (e.g. /tree/main/examples)
2107
+ const subPrefix = parsed.subpath ? parsed.subpath.replace(/^\/+|\/+$/g, '') + '/' : null;
2108
+ const filtered = [];
2109
+ for (const item of rawTreeEntries) {
2110
+ let destPath = item.path;
2111
+ if (subPrefix) {
2112
+ if (item.path === parsed.subpath) {
2113
+ destPath = PosixPath.basename(item.path);
2114
+ } else if (item.path.startsWith(subPrefix)) {
2115
+ destPath = item.path.slice(subPrefix.length);
2116
+ } else {
2145
2117
  continue;
2146
2118
  }
2147
- filtered.push({
2148
- repoPath: item.path,
2149
- destPath,
2150
- size: item.size || 0,
2151
- priority: scoreRepoFilePriority(destPath)
2152
- });
2153
2119
  }
2120
+ if (!destPath || destPath.startsWith('.git/') || destPath.includes('/node_modules/') || destPath.startsWith('node_modules/')) {
2121
+ continue;
2122
+ }
2123
+ if (BINARY_OR_HEAVY_EXT_RE.test(destPath)) {
2124
+ continue;
2125
+ }
2126
+ if (item.size && item.size > maxFileSize) {
2127
+ continue;
2128
+ }
2129
+ filtered.push({
2130
+ repoPath: item.path,
2131
+ destPath,
2132
+ size: item.size || 0,
2133
+ priority: scoreRepoFilePriority(destPath)
2134
+ });
2135
+ }
2154
2136
 
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;
2137
+ filtered.sort((a, b) => a.priority - b.priority || a.destPath.localeCompare(b.destPath));
2138
+ const selectedFiles = filtered.slice(0, maxFiles);
2139
+ const totalToDownload = selectedFiles.length;
2158
2140
 
2159
- if (onProgress) {
2160
- onProgress({
2161
- phase: 'downloading',
2162
- message: `Downloading files (0/${totalToDownload})...`,
2163
- loaded: 0,
2164
- total: totalToDownload
2165
- });
2166
- }
2141
+ if (onProgress) {
2142
+ onProgress({ phase: 'downloading', message: `Downloading files (0/${totalToDownload})...`, loaded: 0, total: totalToDownload });
2143
+ }
2167
2144
 
2168
- if (!vfs.existsSync(targetDir)) {
2169
- vfs.mkdirSync(targetDir, { recursive: true });
2170
- }
2145
+ if (!vfs.existsSync(targetDir)) {
2146
+ vfs.mkdirSync(targetDir, { recursive: true });
2147
+ }
2171
2148
 
2172
- const headSnapshot = {};
2173
- let filesWritten = 0;
2174
- let totalBytes = 0;
2175
- const BATCH_SIZE = 12;
2149
+ const headSnapshot = {};
2150
+ let filesWritten = 0;
2151
+ let totalBytes = 0;
2152
+ const BATCH_SIZE = 12;
2176
2153
 
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}`;
2154
+ for (let i = 0; i < selectedFiles.length; i += BATCH_SIZE) {
2155
+ throwIfAborted();
2156
+ const batch = selectedFiles.slice(i, i + BATCH_SIZE);
2157
+ await Promise.all(
2158
+ batch.map(async (entry) => {
2159
+ throwIfAborted();
2160
+ const encodedPath = entry.repoPath.split('/').map(encodeURIComponent).join('/');
2161
+ const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
2162
+ const cdnUrl = `https://cdn.jsdelivr.net/gh/${owner}/${repo}@${encodeURIComponent(resolvedBranch)}/${encodedPath}`;
2163
+
2164
+ let text = null;
2165
+ try {
2166
+ const r1 = await fetchFn(rawUrl, { signal });
2167
+ if (r1 && r1.ok) {
2168
+ text = await r1.text();
2169
+ }
2170
+ } catch (_) {
2171
+ if (signal && signal.aborted) throw _;
2172
+ }
2186
2173
 
2187
- let text = null;
2174
+ if (text === null) {
2188
2175
  try {
2189
- const r1 = await fetchFn(rawUrl, { signal });
2190
- if (r1 && r1.ok) {
2191
- text = await r1.text();
2176
+ const r2 = await fetchFn(cdnUrl, { signal });
2177
+ if (r2 && r2.ok) {
2178
+ text = await r2.text();
2192
2179
  }
2193
2180
  } catch (_) {
2194
2181
  if (signal && signal.aborted) throw _;
2195
2182
  }
2183
+ }
2196
2184
 
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
- }
2185
+ if (text !== null && text.length <= maxFileSize) {
2186
+ const absPath = PosixPath.join(targetDir, entry.destPath);
2187
+ const parentDir = PosixPath.dirname(absPath);
2188
+ if (!vfs.existsSync(parentDir)) {
2189
+ vfs.mkdirSync(parentDir, { recursive: true });
2206
2190
  }
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
- }
2191
+ vfs.writeFileSync(absPath, text);
2192
+ headSnapshot[entry.destPath] = text;
2193
+ filesWritten++;
2194
+ totalBytes += text.length;
2195
+ if (onProgress) {
2196
+ onProgress({ phase: 'downloading', message: `Downloading files (${filesWritten}/${totalToDownload}): ${entry.destPath}`, loaded: filesWritten, total: totalToDownload });
2231
2197
  }
2232
- })
2233
- );
2234
- }
2198
+ if (typeof options.onFile === 'function') {
2199
+ options.onFile(absPath, text, entry.destPath);
2200
+ }
2201
+ }
2202
+ })
2203
+ );
2204
+ }
2235
2205
 
2236
- throwIfAborted();
2206
+ throwIfAborted();
2237
2207
 
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
- }
2208
+ if (onProgress) {
2209
+ onProgress({ phase: 'mounting', message: `Mounting files and writing Git metadata into ${targetDir}...`, loaded: filesWritten, total: totalToDownload });
2210
+ }
2246
2211
 
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`
2212
+ // Write .git metadata inside targetDir
2213
+ const gitDir = PosixPath.join(targetDir, '.git');
2214
+ if (!vfs.existsSync(gitDir)) {
2215
+ vfs.mkdirSync(gitDir, { recursive: true });
2216
+ }
2217
+ vfs.writeFileSync(PosixPath.join(gitDir, 'HEAD'), `ref: refs/heads/${resolvedBranch}\n`);
2218
+ vfs.writeFileSync(
2219
+ PosixPath.join(gitDir, 'config'),
2220
+ `[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`
2221
+ );
2222
+
2223
+ // Fetch recent commits (best-effort)
2224
+ let commits = [];
2225
+ try {
2226
+ const commitsRes = await fetchFn(
2227
+ `https://api.github.com/repos/${owner}/${repo}/commits?sha=${encodeURIComponent(resolvedBranch)}&per_page=10`,
2228
+ { headers: { Accept: 'application/vnd.github.v3+json' }, signal }
2256
2229
  );
2230
+ if (commitsRes && commitsRes.ok) {
2231
+ const commitsJson = await commitsRes.json();
2232
+ if (Array.isArray(commitsJson) && commitsJson.length > 0) {
2233
+ commits = commitsJson.map((c) => ({
2234
+ hash: String(c.sha || 'a1b2c3d').slice(0, 7),
2235
+ author:
2236
+ c.commit && c.commit.author
2237
+ ? `${c.commit.author.name || owner} <${c.commit.author.email || `${owner}@users.noreply.github.com`}>`
2238
+ : `${owner} <${owner}@users.noreply.github.com>`,
2239
+ date:
2240
+ c.commit && c.commit.author && c.commit.author.date
2241
+ ? new Date(c.commit.author.date).toUTCString()
2242
+ : new Date().toUTCString(),
2243
+ message: c.commit && c.commit.message ? String(c.commit.message).split('\n')[0] : 'Commit'
2244
+ }));
2245
+ }
2246
+ }
2247
+ } catch (_) {}
2257
2248
 
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
- }
2249
+ if (commits.length === 0) {
2250
+ commits = [
2251
+ {
2252
+ hash: 'a1b2c3d',
2253
+ author: `${owner} <${owner}@users.noreply.github.com>`,
2254
+ date: new Date().toUTCString(),
2255
+ message: `Clone ${owner}/${repo} (${resolvedBranch})`
2281
2256
  }
2282
- } catch (_) {}
2257
+ ];
2258
+ }
2283
2259
 
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
- ];
2293
- }
2260
+ if (onProgress) {
2261
+ onProgress({ phase: 'ready', message: `Repository cloned successfully (${filesWritten} files).`, loaded: filesWritten, total: totalToDownload });
2262
+ }
2294
2263
 
2295
- if (onProgress) {
2296
- onProgress({
2297
- phase: 'ready',
2298
- message: `Repository cloned successfully (${filesWritten} files).`,
2299
- loaded: filesWritten,
2300
- total: totalToDownload
2301
- });
2302
- }
2264
+ return {
2265
+ owner,
2266
+ repo,
2267
+ branch: resolvedBranch,
2268
+ url: parsed.url,
2269
+ targetDir,
2270
+ count: filesWritten,
2271
+ fileCount: filesWritten,
2272
+ filesWritten,
2273
+ totalBytes,
2274
+ commits,
2275
+ headSnapshot
2276
+ };
2277
+ }
2303
2278
 
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
- };
2279
+ // Public wrapper: guarantee an `error` progress event when the clone fails
2280
+ // for any reason (invalid URL, missing vfs, fetch rejection, abort, ...).
2281
+ async function cloneGitHubRepository(repoInput, vfs, options = {}) {
2282
+ const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
2283
+ try {
2284
+ return await _cloneGitHubRepository(repoInput, vfs, options);
2317
2285
  } catch (err) {
2318
2286
  if (onProgress) {
2319
2287
  onProgress({
@@ -2423,6 +2391,15 @@ function __initShellModule(root: any) {
2423
2391
 
2424
2392
  function pickConditionalEntry(value) {
2425
2393
  if (typeof value === 'string') return value;
2394
+ // `exports` subpaths may be an array of fallbacks, e.g.
2395
+ // `"./shams": [{ "types": "...", "default": "./shams.js" }, "./shams.js"]`.
2396
+ if (Array.isArray(value)) {
2397
+ for (const item of value) {
2398
+ const picked = pickConditionalEntry(item);
2399
+ if (picked) return picked;
2400
+ }
2401
+ return null;
2402
+ }
2426
2403
  if (!value || typeof value !== 'object') return null;
2427
2404
  // This runtime executes CommonJS, so it prefers CJS-friendly conditions.
2428
2405
  for (const key of ['require', 'node', 'default', 'browser', 'import', 'module']) {
@@ -2479,17 +2456,50 @@ function __initShellModule(root: any) {
2479
2456
  return parts.join('/');
2480
2457
  }
2481
2458
 
2459
+ // Small promise-based delay. Used only for CDN retry backoff; falls back to an
2460
+ // immediate resolve if `setTimeout` is unavailable in the host.
2461
+ function cdnBackoff(ms) {
2462
+ return new Promise((resolve) => {
2463
+ if (typeof setTimeout === 'function') setTimeout(resolve, ms);
2464
+ else resolve();
2465
+ });
2466
+ }
2467
+
2482
2468
  async function fetchTextFromCdn(fetchImpl, url) {
2483
- try {
2484
- const res = await fetchImpl(url);
2485
- if (!res) return null;
2486
- const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
2487
- if (!ok) return null;
2488
- if (typeof res.text === 'function') return await res.text();
2489
- return String(res.body != null ? res.body : '');
2490
- } catch (_) {
2491
- return null;
2469
+ // A single flaky jsDelivr response used to silently produce an *incomplete*
2470
+ // install (the module graph then failed at require-time). Retry transient
2471
+ // failures (network error, 429/408, 5xx) but treat 4xx as final.
2472
+ const maxAttempts = 3;
2473
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2474
+ try {
2475
+ const res = await fetchImpl(url);
2476
+ if (!res) {
2477
+ if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
2478
+ return null;
2479
+ }
2480
+ const ok = (res.ok === true) || res.status === 200 || res.status === undefined;
2481
+ if (!ok) {
2482
+ const transient = res.status >= 500 || res.status === 429 || res.status === 408;
2483
+ if (transient && attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
2484
+ return null;
2485
+ }
2486
+ // jsDelivr answers a *directory* path (e.g. `/pkg@1/libcjs/`) with HTTP 200
2487
+ // and an HTML directory listing. Storing that as a module both corrupts the
2488
+ // package and later collides with the real directory (EISDIR).
2489
+ const contentType = (res.headers && typeof res.headers.get === 'function')
2490
+ ? (res.headers.get('content-type') || '')
2491
+ : '';
2492
+ const isHtmlUrl = /\.html?(?:[?#]|$)/i.test(url);
2493
+ if (/text\/html/i.test(contentType) && !isHtmlUrl) return null;
2494
+ const text = typeof res.text === 'function' ? await res.text() : String(res.body != null ? res.body : '');
2495
+ if (!isHtmlUrl && /^\s*(?:<!doctype\s+html|<html[\s>]|<head[\s>])/i.test(text)) return null;
2496
+ return text;
2497
+ } catch (_) {
2498
+ if (attempt < maxAttempts) { await cdnBackoff(attempt * 150); continue; }
2499
+ return null;
2500
+ }
2492
2501
  }
2502
+ return null;
2493
2503
  }
2494
2504
 
2495
2505
  async function resolvePackageMetadata(fetchImpl, name, range) {
@@ -2532,14 +2542,25 @@ function __initShellModule(root: any) {
2532
2542
  const visited = new Set();
2533
2543
  // Seed with the package entry plus any declared `exports` subpaths, so a
2534
2544
  // later `require('pkg/subpath')` (e.g. `entities/decode`) resolves offline.
2535
- const seed = [entry, `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`];
2545
+ // A `main` may point at a *directory* (e.g. chalk: `"main": "source"`); Node
2546
+ // resolves that to `<dir>/index.<ext>`, so those candidates must be seeded
2547
+ // too or the package installs with only its manifest.
2548
+ const seed = [
2549
+ entry,
2550
+ `${entry}.js`, `${entry}.json`, `${entry}.mjs`, `${entry}.cjs`,
2551
+ `${entry}/index.js`, `${entry}/index.json`, `${entry}/index.mjs`, `${entry}/index.cjs`
2552
+ ];
2536
2553
  const expMap = meta.exports;
2537
2554
  if (expMap && typeof expMap === 'object') {
2538
- let subCount = 0;
2555
+ // Seed *every* declared subpath. A low cap silently dropped the tail of
2556
+ // packages that list each file in `exports` (lit-html has 29 keys, so
2557
+ // `lit-html/is-server.js` was never fetched and `require` failed later).
2558
+ // Wildcard keys (`./*`) need no seeding — their files are reached through
2559
+ // the relative-require closure or fetched on demand.
2539
2560
  for (const key of Object.keys(expMap)) {
2540
- if (key === '.' || key.slice(0, 2) !== './' || subCount >= 25) continue;
2561
+ if (key === '.' || key.slice(0, 2) !== './' || key.includes('*')) continue;
2541
2562
  const target = pickConditionalEntry(expMap[key]);
2542
- if (target) { seed.push(target); subCount++; }
2563
+ if (target) seed.push(target);
2543
2564
  }
2544
2565
  }
2545
2566
  let frontier = seed;
@@ -2547,7 +2568,9 @@ function __initShellModule(root: any) {
2547
2568
  const batch = [];
2548
2569
  for (const raw of frontier) {
2549
2570
  const rel = stripRelPath(raw);
2550
- if (!rel || visited.has(rel)) continue;
2571
+ // Directory targets (e.g. `exports["./lib/"] === "./libcjs/"`) must never
2572
+ // be fetched as files — that is what produced the EISDIR crash.
2573
+ if (!rel || rel.endsWith('/') || visited.has(rel)) continue;
2551
2574
  visited.add(rel);
2552
2575
  batch.push(rel);
2553
2576
  }
@@ -2583,15 +2606,29 @@ function __initShellModule(root: any) {
2583
2606
  }
2584
2607
 
2585
2608
  // Declared dependencies plus non-optional peer dependencies (npm v7+ style),
2586
- // so e.g. `npm install react-dom` also pulls in `react`.
2587
- const depNames = Object.keys(meta.dependencies || {});
2609
+ // so e.g. `npm install react-dom` also pulls in `react`. The *ranges* are
2610
+ // preserved (not just the names) so transitives resolve to the version the
2611
+ // parent actually asked for — e.g. chalk@4 needs ansi-styles@^4, which itself
2612
+ // needs color-convert. Resolving transitive names as "latest" silently breaks
2613
+ // the tree (ansi-styles@6 has no deps at all).
2614
+ const depSpecs = [];
2615
+ const depSeen = new Set();
2616
+ const declared = meta.dependencies || {};
2617
+ for (const depName of Object.keys(declared)) {
2618
+ if (depSeen.has(depName)) continue;
2619
+ depSeen.add(depName);
2620
+ depSpecs.push({ name: depName, range: declared[depName] || null });
2621
+ }
2588
2622
  const peerMeta = meta.peerDependenciesMeta || {};
2589
- for (const peer of Object.keys(meta.peerDependencies || {})) {
2623
+ const peers = meta.peerDependencies || {};
2624
+ for (const peer of Object.keys(peers)) {
2590
2625
  if (peerMeta[peer] && peerMeta[peer].optional) continue;
2591
- if (depNames.indexOf(peer) === -1) depNames.push(peer);
2626
+ if (depSeen.has(peer)) continue;
2627
+ depSeen.add(peer);
2628
+ depSpecs.push({ name: peer, range: peers[peer] || null });
2592
2629
  }
2593
2630
 
2594
- return { ok: true, version, entry, files, deps: depNames, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
2631
+ return { ok: true, version, entry, files, deps: depSpecs, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
2595
2632
  }
2596
2633
 
2597
2634
  function installTargetDirs(ctx, name) {
@@ -2605,7 +2642,13 @@ function __initShellModule(root: any) {
2605
2642
  for (const dir of dirs) {
2606
2643
  ensureDirSync(ctx.vfs, dir, ctx.emitMutation);
2607
2644
  for (const f of info.files) {
2645
+ if (!f || !f.rel || f.rel.endsWith('/')) continue;
2608
2646
  const full = PosixPath.join(dir, f.rel);
2647
+ // Never overwrite a directory with a file body (defensive: a stray
2648
+ // directory target would otherwise raise EISDIR).
2649
+ try {
2650
+ if (ctx.vfs.existsSync(full) && ctx.vfs.statSync(full).isDirectory()) continue;
2651
+ } catch (_) {}
2609
2652
  ensureDirSync(ctx.vfs, PosixPath.dirname(full), ctx.emitMutation);
2610
2653
  ctx.vfs.writeFileSync(full, f.content);
2611
2654
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', full);
@@ -2671,10 +2714,11 @@ function __initShellModule(root: any) {
2671
2714
  if (item.direct) directVersion = info.version || null;
2672
2715
 
2673
2716
  for (const dep of (info.deps || [])) {
2674
- const parsed = parsePackageSpec(dep);
2675
- if (parsed.name && !requested.has(parsed.name)) {
2676
- requested.add(parsed.name);
2677
- queue.push({ name: parsed.name, range: null, direct: false });
2717
+ const depName = (dep && typeof dep === 'object') ? dep.name : parsePackageSpec(dep).name;
2718
+ const depRange = (dep && typeof dep === 'object') ? dep.range : parsePackageSpec(dep).range;
2719
+ if (depName && !requested.has(depName)) {
2720
+ requested.add(depName);
2721
+ queue.push({ name: depName, range: depRange || null, direct: false });
2678
2722
  }
2679
2723
  }
2680
2724
  }
@@ -3031,21 +3075,29 @@ function __initShellModule(root: any) {
3031
3075
  // Common dev-server commands that cannot run inside the virtual runtime are
3032
3076
  // transparently redirected to the built-in preview server.
3033
3077
  const PREVIEW_TOOL_RE = /\b(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|serve|http-server)\b/;
3078
+ // The same tools, when typed directly at the prompt (`ng serve`, `vite`).
3079
+ // `serve` is omitted: it is a first-class builtin shell command.
3080
+ const DIRECT_DEV_TOOL_RE = /^(vite|ng|astro|next|webpack|parcel|esbuild|snowpack|react-scripts|http-server)$/;
3034
3081
 
3035
- function tryDevScriptFallback(scriptName, cmd, ctx) {
3082
+ function tryDevScriptFallback(scriptName, cmd, ctx, opts) {
3036
3083
  if (!PREVIEW_TOOL_RE.test(cmd)) return null;
3037
3084
  // Only fall back when the referenced tool is not actually installed.
3038
3085
  const bin = (cmd.match(PREVIEW_TOOL_RE) || [])[1];
3086
+ const force = Boolean(opts && opts.force);
3039
3087
  const binPath = PosixPath.join('/workspace/node_modules/.bin', bin);
3040
- if (ctx.vfs.existsSync(binPath)) return null;
3088
+ if (!force && ctx.vfs.existsSync(binPath)) return null;
3041
3089
  const portMatch = cmd.match(/--port(?:=|\s+)(\d+)/);
3042
3090
  const defaultPorts = { ng: 4200, vite: 5173, astro: 4321, next: 3000 };
3043
3091
  const port = portMatch ? Number(portMatch[1]) : (defaultPorts[bin] || 3000);
3044
- const entry = registerPreviewServer(ctx, ctx.cwd, port);
3092
+ const rootDir = typeof ctx.resolvePath === 'function' ? ctx.resolvePath('.') : (ctx.cwd || '/workspace');
3093
+ const entry = registerPreviewServer(ctx, rootDir, port);
3045
3094
  if (!entry) return null;
3095
+ const note = force
3096
+ ? `${bin} is a native dev server and cannot execute inside this virtual runtime — using the CodeLab preview server instead.`
3097
+ : `${bin} is not available in this virtual runtime — using the CodeLab preview server instead.`;
3046
3098
  return {
3047
3099
  code: 0,
3048
- stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${bin} is not available in this virtual runtime — using the CodeLab preview server instead.\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
3100
+ stdout: `\n> ${scriptName}\n> ${cmd}\n\n ${note}\n\n ➜ Local: http://127.0.0.1:${entry.port}/\n\n`,
3049
3101
  stderr: ''
3050
3102
  };
3051
3103
  }
@@ -7144,6 +7196,13 @@ function __initShellModule(root: any) {
7144
7196
  Object.assign(context.env, this.env);
7145
7197
  context.cwd = this.cwd;
7146
7198
  }
7199
+ } else if (DIRECT_DEV_TOOL_RE.test(cmdName)) {
7200
+ // A native dev server (vite/ng/astro/…) typed directly. It cannot run in
7201
+ // this runtime — whether or not it was installed — so route it to the
7202
+ // built-in preview server rather than reporting a misleading "command
7203
+ // not found".
7204
+ const fb = tryDevScriptFallback(cmdName, [cmdName, ...args].join(' '), cmdCtx, { force: true });
7205
+ res = fb || { code: 127, stdout: '', stderr: `shell: ${cmdName}: command not found\n` };
7147
7206
  } else if (typeof this.options.onProcessSpawn === 'function') {
7148
7207
  const spawned = await this.options.onProcessSpawn(cmdName, args, {
7149
7208
  cwd: this.cwd,
@@ -7213,17 +7272,11 @@ function __initShellModule(root: any) {
7213
7272
  parseGitHubRepoUrl,
7214
7273
  cloneGitHubRepository
7215
7274
  };
7275
+ });
7216
7276
 
7217
- }
7218
-
7219
- const _hostShell: any = __initShellModule(typeof globalThis !== 'undefined' ? globalThis : this);
7220
-
7221
- if (typeof globalThis !== 'undefined') {
7222
- (globalThis as any).CodeLabShell = _hostShell;
7223
- }
7224
- if (typeof module !== 'undefined' && module.exports) {
7225
- module.exports = _hostShell;
7226
- }
7277
+ // ── TypeScript module surface (stripped from browser bundles) ──────────────
7278
+ const _hostShell: any = (typeof globalThis !== 'undefined' ? (globalThis as any).CodeLabShell : undefined)
7279
+ || (typeof module !== 'undefined' && module.exports ? module.exports : {});
7227
7280
 
7228
7281
  export const createPosixShell: (options?: any) => any = _hostShell.createPosixShell;
7229
7282
  export const parseShellCommand: (cmd: string) => any = _hostShell.parseShellCommand;
@@ -7234,7 +7287,7 @@ export const PosixPath: any = _hostShell.PosixPath;
7234
7287
  export const expandGlob: (pattern: string, vfs: any, cwd?: string) => string[] = _hostShell.expandGlob;
7235
7288
  export const createVirtualPortTable: () => any = _hostShell.createVirtualPortTable;
7236
7289
  export const parseGitHubRepoUrl: (input: string) => any = _hostShell.parseGitHubRepoUrl;
7237
- export const cloneGitHubRepository: (repoInput: string, vfs: any, options?: GitHubCloneOptions) => Promise<CloneResult> = _hostShell.cloneGitHubRepository;
7290
+ export const cloneGitHubRepository: (repoInput: string, vfs: any, options?: any) => Promise<any> = _hostShell.cloneGitHubRepository;
7238
7291
  export const CodeLabShell: any = _hostShell;
7239
7292
 
7240
7293
  export default _hostShell;