@innovatorved/code-lab 0.5.0 → 0.6.0

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 (67) hide show
  1. package/ARCHITECTURE.md +3 -3
  2. package/CHANGELOG.md +15 -0
  3. package/README.md +3 -3
  4. package/dist/code-lab-sql.esm.js +1 -1
  5. package/dist/code-lab-sql.umd.js +2 -2
  6. package/dist/code-lab.css +32 -7273
  7. package/dist/code-lab.d.ts +1 -1
  8. package/dist/code-lab.esm.js +4669 -74678
  9. package/dist/code-lab.js +4655 -74665
  10. package/dist/code-lab.umd.js +4655 -74665
  11. package/dist/extensions/cpp.d.ts +2 -2
  12. package/dist/extensions/cpp.esm.js +1788 -14707
  13. package/dist/extensions/cpp.js +1788 -14707
  14. package/dist/extensions/guided-lab.esm.js +2938 -16127
  15. package/dist/extensions/guided-lab.js +2938 -16127
  16. package/dist/extensions/python.d.ts +2 -2
  17. package/dist/extensions/python.esm.js +1769 -14701
  18. package/dist/extensions/python.js +1769 -14701
  19. package/dist/index.d.ts +1 -1
  20. package/dist/preview-sw.js +4 -188
  21. package/dist/runtime.esm.js +109 -10284
  22. package/dist/runtime.js +107 -10284
  23. package/dist/schemas.d.ts +2 -2
  24. package/dist/schemas.esm.js +2938 -16127
  25. package/dist/schemas.js +2941 -16130
  26. package/dist/scm.d.ts +221 -20
  27. package/dist/shell.esm.js +811 -10002
  28. package/dist/shell.js +811 -10002
  29. package/dist/storage.d.ts +9 -0
  30. package/dist/terminal.esm.js +20 -1347
  31. package/dist/terminal.js +20 -1347
  32. package/dist/workbench/command-palette.d.ts +16 -1
  33. package/dist/workbench/diff-editor.d.ts +27 -1
  34. package/dist/workbench/icons.d.ts +6 -2
  35. package/dist/workbench/index.d.ts +32 -0
  36. package/dist/workbench/intellisense.d.ts +194 -0
  37. package/dist/workbench/xterm-adapter.d.ts +122 -0
  38. package/package.json +7 -1
  39. package/packages/commands/package.json +1 -1
  40. package/packages/core/package.json +1 -1
  41. package/packages/editor/package.json +1 -1
  42. package/packages/fs/package.json +1 -1
  43. package/packages/preview/package.json +1 -1
  44. package/packages/runtime/package.json +1 -1
  45. package/packages/settings/package.json +1 -1
  46. package/packages/sql/package.json +1 -1
  47. package/packages/terminal/package.json +1 -1
  48. package/packages/ui/package.json +1 -1
  49. package/packages/ui/src/settings-dialog.ts +36 -24
  50. package/packages/ui/src/themes.ts +89 -23
  51. package/src/code-lab.css +1345 -481
  52. package/src/extensions/cpp.ts +304 -38
  53. package/src/extensions/python.ts +342 -43
  54. package/src/index.ts +1 -1
  55. package/src/runtime.ts +272 -43
  56. package/src/schemas.ts +2 -2
  57. package/src/scm.ts +1467 -92
  58. package/src/shell.ts +1075 -93
  59. package/src/storage.ts +66 -3
  60. package/src/terminal.ts +148 -12
  61. package/src/workbench/command-palette.ts +289 -48
  62. package/src/workbench/diff-editor.ts +240 -78
  63. package/src/workbench/icons.ts +250 -53
  64. package/src/workbench/index.ts +7 -1
  65. package/src/workbench/intellisense.ts +1859 -0
  66. package/src/workbench/xterm-adapter.ts +1566 -0
  67. package/src/workbench.ts +1605 -236
package/src/shell.ts CHANGED
@@ -65,6 +65,17 @@
65
65
  return null;
66
66
  }
67
67
 
68
+ function getScmModule() {
69
+ if (typeof root !== 'undefined' && root && root.CodeLabScm) return root.CodeLabScm;
70
+ if (typeof globalThis !== 'undefined' && globalThis.CodeLabScm) return globalThis.CodeLabScm;
71
+ try {
72
+ if (typeof require !== 'undefined') return require('./scm.js');
73
+ } catch (err) {
74
+ _shellLogger.debug('Optional ./scm.js require skipped in shell.', err);
75
+ }
76
+ return null;
77
+ }
78
+
68
79
  function hasVirtualRuntime() {
69
80
  const rm = getRuntimeModule();
70
81
  return Boolean(rm && typeof rm.executeInVirtualRuntime === 'function');
@@ -78,6 +89,103 @@
78
89
  throw new Error('Virtual runtime engine is not available');
79
90
  }
80
91
 
92
+ async function executeJsInShellRuntime(runOpts, ctx) {
93
+ const rm = getRuntimeModule();
94
+ if (!rm || typeof rm.executeInVirtualRuntime !== 'function') {
95
+ throw new Error('Virtual runtime engine is not available');
96
+ }
97
+
98
+ let sourceCode = typeof runOpts.replCode === 'string' ? runOpts.replCode : '';
99
+ if (!sourceCode && typeof runOpts.entry === 'string' && ctx && ctx.vfs && typeof ctx.vfs.existsSync === 'function') {
100
+ try {
101
+ const absEntry = typeof ctx.resolvePath === 'function' ? ctx.resolvePath(runOpts.entry) : runOpts.entry;
102
+ const candidate = ctx.vfs.existsSync(absEntry) ? absEntry : (ctx.vfs.existsSync(runOpts.entry) ? runOpts.entry : '');
103
+ if (candidate) {
104
+ sourceCode = String(ctx.vfs.readFileSync(candidate, 'utf8') || '');
105
+ }
106
+ } catch (_err) {
107
+ void _err;
108
+ }
109
+ }
110
+
111
+ // Best-effort preload external npm packages if imported and not already in VFS node_modules
112
+ let preloadedNpmModules = runOpts.npmModules;
113
+ const BUILTIN_SPECS = new Set([
114
+ 'assert', 'buffer', 'child_process', 'cluster', 'console', 'constants', 'crypto', 'dgram',
115
+ 'diagnostics_channel', 'dns', 'domain', 'events', 'fs', 'http', 'http2', 'https', 'inspector',
116
+ 'module', 'net', 'os', 'path', 'perf_hooks', 'process', 'punycode', 'querystring', 'readline',
117
+ 'repl', 'sqlite', 'stream', 'string_decoder', 'sys', 'test', 'timers', 'tls', 'tty', 'url',
118
+ 'util', 'v8', 'vm', 'wasi', 'worker_threads', 'zlib'
119
+ ]);
120
+ let hasExternalPkg = false;
121
+ if (sourceCode && !(runOpts.isBackground || (ctx && ctx.isBackground))) {
122
+ const specRe = /(?:from\s+|require\s*\(\s*)['"]([^./'"]+)['"]/g;
123
+ let sm;
124
+ while ((sm = specRe.exec(sourceCode)) !== null) {
125
+ const spec = sm[1];
126
+ if (spec.startsWith('node:') || spec.startsWith('bun:')) continue;
127
+ const rootPkg = spec.startsWith('@') ? spec.split('/').slice(0, 2).join('/') : spec.split('/')[0];
128
+ if (!BUILTIN_SPECS.has(rootPkg)) {
129
+ hasExternalPkg = true;
130
+ break;
131
+ }
132
+ }
133
+ }
134
+ if (hasExternalPkg && typeof rm.preloadNpmPackages === 'function') {
135
+ try {
136
+ const loaded = await rm.preloadNpmPackages({ [runOpts.entry || 'eval.js']: sourceCode });
137
+ if (loaded && typeof loaded === 'object') {
138
+ preloadedNpmModules = Object.assign({}, loaded, preloadedNpmModules || {});
139
+ }
140
+ } catch (err) {
141
+ _shellLogger.debug('preloadNpmPackages skipped in shell:', err);
142
+ }
143
+ }
144
+
145
+ const onRequestStdin =
146
+ (ctx && typeof ctx.onRequestStdin === 'function' ? ctx.onRequestStdin : null) ||
147
+ (ctx && ctx.shell && ctx.shell.options && typeof ctx.shell.options.onRequestStdin === 'function'
148
+ ? ctx.shell.options.onRequestStdin
149
+ : undefined);
150
+
151
+ const portTable = ctx && ctx.shell ? ctx.shell.portTable : null;
152
+ const hasActivePortServers = Boolean(
153
+ portTable && typeof portTable.listServers === 'function' && portTable.listServers().length > 0
154
+ );
155
+ const needsPortTable = Boolean(
156
+ runOpts.isBackground ||
157
+ (ctx && ctx.isBackground) ||
158
+ hasActivePortServers ||
159
+ /(?:\bcreateServer\b|\.listen\s*\(|\bBun\.serve\b|\blocalhost\b|127\.0\.0\.1)/.test(sourceCode)
160
+ );
161
+
162
+ const resolvedInstanceId =
163
+ runOpts.instanceId ||
164
+ (ctx && ctx.shell && ctx.shell.options && ctx.shell.options.instanceId
165
+ ? ctx.shell.options.instanceId
166
+ : undefined);
167
+
168
+ const mergedOpts = {
169
+ ...runOpts,
170
+ ...(resolvedInstanceId ? { instanceId: resolvedInstanceId } : {}),
171
+ concurrent: true,
172
+ npmModules: preloadedNpmModules,
173
+ onRequestStdin
174
+ };
175
+
176
+ if (!needsPortTable && typeof Worker !== 'undefined' && typeof rm.executeInWorker === 'function') {
177
+ const workerOpts = { ...mergedOpts };
178
+ delete workerOpts.activePortTable;
179
+ delete workerOpts.portTable;
180
+ return rm.executeInWorker(workerOpts);
181
+ }
182
+
183
+ return rm.executeInVirtualRuntime({
184
+ ...mergedOpts,
185
+ activePortTable: portTable
186
+ });
187
+ }
188
+
81
189
  function createVirtualPortTable(...args) {
82
190
  const rm = getRuntimeModule();
83
191
  if (rm && typeof rm.createVirtualPortTable === 'function') {
@@ -121,12 +229,13 @@
121
229
 
122
230
  resolve(cwd, ...paths) {
123
231
  let resolved = cwd.startsWith('/') ? cwd : '/' + cwd;
232
+ const homeDir = PosixPath._homeDir || '/home/codelab';
124
233
  for (const p of paths) {
125
234
  if (!p) continue;
126
235
  if (p.startsWith('/')) {
127
236
  resolved = p;
128
237
  } else if (p === '~' || p.startsWith('~/')) {
129
- resolved = '/home/user' + p.slice(1);
238
+ resolved = homeDir + p.slice(1);
130
239
  } else {
131
240
  resolved = resolved.endsWith('/') ? resolved + p : resolved + '/' + p;
132
241
  }
@@ -1592,12 +1701,15 @@
1592
1701
  // =========================================================================
1593
1702
  function createFallbackVfs() {
1594
1703
  const files = new Map();
1595
- const dirs = new Set(['/', '/tmp', '/workspace', '/etc', '/home', '/home/user']);
1704
+ const dirs = new Set(['/', '/tmp', '/workspace', '/etc', '/home', '/home/user', '/home/codelab']);
1596
1705
  let _activeStdin = '';
1706
+ let _currentCwd = '/workspace';
1597
1707
 
1598
1708
  function norm(p) {
1599
1709
  const s = String(p);
1600
- return PosixPath.normalize(s.startsWith('/') ? s : '/workspace/' + s);
1710
+ if (s.startsWith('/')) return PosixPath.normalize(s);
1711
+ const base = _currentCwd && _currentCwd.startsWith('/') ? _currentCwd : '/workspace';
1712
+ return PosixPath.normalize(base.endsWith('/') ? base + s : base + '/' + s);
1601
1713
  }
1602
1714
 
1603
1715
  const emitter = {
@@ -1706,6 +1818,25 @@
1706
1818
  _setActiveStdin(text) {
1707
1819
  _activeStdin = text === null || text === undefined ? '' : String(text);
1708
1820
  },
1821
+ _setCwd(dir) {
1822
+ if (dir && typeof dir === 'string') {
1823
+ _currentCwd = PosixPath.normalize(dir);
1824
+ }
1825
+ },
1826
+ _getRawFileBytes(p) {
1827
+ const np = norm(p);
1828
+ const f = files.get(np);
1829
+ return f && f.rawBytes instanceof Uint8Array ? f.rawBytes : null;
1830
+ },
1831
+ _getAllRawFiles() {
1832
+ const out = {};
1833
+ for (const [k, f] of files.entries()) {
1834
+ if (f && f.rawBytes instanceof Uint8Array) {
1835
+ out[k] = f.rawBytes;
1836
+ }
1837
+ }
1838
+ return out;
1839
+ },
1709
1840
  writeFileSync(p, data) {
1710
1841
  const np = norm(p);
1711
1842
  const parent = PosixPath.dirname(np);
@@ -1830,7 +1961,16 @@
1830
1961
  const s = norm(src);
1831
1962
  const d = norm(dst);
1832
1963
  if (!files.has(s)) throw new Error(`ENOENT: no such file or directory, copy '${src}'`);
1833
- files.set(d, { data: files.get(s).data, mtimeMs: Date.now() });
1964
+ const srcEntry = files.get(s);
1965
+ const rawCopy = srcEntry.rawBytes instanceof Uint8Array
1966
+ ? new Uint8Array(srcEntry.rawBytes)
1967
+ : null;
1968
+ files.set(d, {
1969
+ data: srcEntry.data,
1970
+ rawBytes: rawCopy,
1971
+ mtimeMs: Date.now(),
1972
+ mode: srcEntry.mode !== undefined ? srcEntry.mode : 0o100644
1973
+ });
1834
1974
  }
1835
1975
  };
1836
1976
  }
@@ -1839,6 +1979,11 @@
1839
1979
  // 6. DIFF & LCS UTILITIES (For `diff -u` and `git diff`)
1840
1980
  // =========================================================================
1841
1981
  function computeUnifiedDiff(file1Name, file2Name, text1, text2) {
1982
+ const scm = getScmModule();
1983
+ if (scm && typeof scm.computeUnifiedHunkDiff === 'function') {
1984
+ const hunkDiff = scm.computeUnifiedHunkDiff(file1Name, file2Name, text1, text2, 3);
1985
+ return hunkDiff ? (hunkDiff.endsWith('\n') ? hunkDiff : hunkDiff + '\n') : '';
1986
+ }
1842
1987
  const lines1 = text1.length > 0 ? text1.split('\n') : [];
1843
1988
  const lines2 = text2.length > 0 ? text2.split('\n') : [];
1844
1989
 
@@ -1931,13 +2076,21 @@
1931
2076
  if (httpMatch) {
1932
2077
  owner = httpMatch[1];
1933
2078
  repo = httpMatch[2];
1934
- branch = httpMatch[4] || branch || null;
1935
- subpath = httpMatch[5] ? httpMatch[5].replace(/^\/+|\/+$/g, '') : null;
2079
+ const rawTail = httpMatch[4] ? (httpMatch[5] ? `${httpMatch[4]}/${httpMatch[5].replace(/^\/+|\/+$/g, '')}` : httpMatch[4]) : null;
2080
+ const slashBranchPrefix = rawTail && /^(?:feature|feat|fix|bugfix|hotfix|release|chore|refactor|docs|test|ci|depend|dependabot)\/[^/]+$/.test(rawTail);
2081
+ if (slashBranchPrefix && !branch) {
2082
+ branch = rawTail;
2083
+ subpath = null;
2084
+ } else {
2085
+ branch = httpMatch[4] || branch || null;
2086
+ subpath = httpMatch[5] ? httpMatch[5].replace(/^\/+|\/+$/g, '') : null;
2087
+ }
1936
2088
  return {
1937
2089
  owner,
1938
2090
  repo,
1939
2091
  branch,
1940
2092
  subpath,
2093
+ rawTreeTail: rawTail,
1941
2094
  fullName: `${owner}/${repo}`,
1942
2095
  httpsUrl: `https://github.com/${owner}/${repo}`,
1943
2096
  gitUrl: `https://github.com/${owner}/${repo}.git`,
@@ -2489,7 +2642,10 @@
2489
2642
 
2490
2643
  if (!repoNotFound) {
2491
2644
  const branchCandidates = requestedBranch
2492
- ? [requestedBranch]
2645
+ ? Array.from(new Set([
2646
+ requestedBranch,
2647
+ (!options.branch && parsed.rawTreeTail && parsed.rawTreeTail !== requestedBranch) ? parsed.rawTreeTail : null
2648
+ ].filter(Boolean)))
2493
2649
  : Array.from(new Set([resolvedBranch, 'main', 'master'].filter(Boolean)));
2494
2650
 
2495
2651
  for (const cand of branchCandidates) {
@@ -2502,6 +2658,9 @@
2502
2658
  const treeJson = await treeRes.json();
2503
2659
  if (treeJson && Array.isArray(treeJson.tree)) {
2504
2660
  resolvedBranch = cand;
2661
+ if (parsed.rawTreeTail && cand === parsed.rawTreeTail) {
2662
+ parsed.subpath = null;
2663
+ }
2505
2664
  rawTreeEntries = treeJson.tree
2506
2665
  .filter((item) => item && item.type === 'blob' && item.path)
2507
2666
  .map((item) => ({ path: item.path.replace(/^\/+/, ''), size: item.size || 0 }));
@@ -3100,7 +3259,15 @@
3100
3259
  depSpecs.push({ name: peer, range: peers[peer] || null });
3101
3260
  }
3102
3261
 
3103
- return { ok: true, version, entry, files, deps: depSpecs, pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null };
3262
+ return {
3263
+ ok: true,
3264
+ version,
3265
+ entry,
3266
+ files,
3267
+ deps: depSpecs,
3268
+ pkgBin: meta.bin || null,
3269
+ pkgExports: (meta.exports && typeof meta.exports === 'object') ? meta.exports : null
3270
+ };
3104
3271
  }
3105
3272
 
3106
3273
  function installTargetDirs(ctx, name) {
@@ -3129,6 +3296,7 @@
3129
3296
  }
3130
3297
  const modPkgPath = PosixPath.join(dir, 'package.json');
3131
3298
  const modPkg = { name, version: info.version || '1.0.0', main: './' + (info.entry || 'index.js') };
3299
+ if (info.pkgBin) modPkg.bin = info.pkgBin;
3132
3300
  if (info.pkgExports && typeof info.pkgExports === 'object') {
3133
3301
  const normalized = { '.': './' + (info.entry || 'index.js') };
3134
3302
  for (const key of Object.keys(info.pkgExports)) {
@@ -3140,6 +3308,27 @@
3140
3308
  }
3141
3309
  ctx.vfs.writeFileSync(modPkgPath, JSON.stringify(modPkg, null, 2) + '\n');
3142
3310
  if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', modPkgPath);
3311
+
3312
+ // Populate node_modules/.bin/<binName> shims when package declares `bin`
3313
+ if (info.pkgBin) {
3314
+ const nodeModulesRoot = dir.slice(0, dir.length - name.length - 1);
3315
+ const binDir = PosixPath.join(nodeModulesRoot, '.bin');
3316
+ ensureDirSync(ctx.vfs, binDir, ctx.emitMutation);
3317
+ const binEntries = typeof info.pkgBin === 'string'
3318
+ ? { [name.includes('/') ? name.split('/').pop() : name]: info.pkgBin }
3319
+ : (typeof info.pkgBin === 'object' ? info.pkgBin : {});
3320
+ for (const [binName, relBin] of Object.entries(binEntries)) {
3321
+ if (!binName || !relBin) continue;
3322
+ const targetScript = PosixPath.join(dir, String(relBin).replace(/^\.\//, ''));
3323
+ const shimPath = PosixPath.join(binDir, binName);
3324
+ const shimSource = `// Auto-generated bin shim for ${name}\nrequire(${JSON.stringify(targetScript)});\n`;
3325
+ ctx.vfs.writeFileSync(shimPath, shimSource);
3326
+ if (typeof ctx.vfs.chmodSync === 'function') {
3327
+ try { ctx.vfs.chmodSync(shimPath, 0o755); } catch (_err) { void _err; }
3328
+ }
3329
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', shimPath);
3330
+ }
3331
+ }
3143
3332
  }
3144
3333
  }
3145
3334
 
@@ -3348,7 +3537,27 @@
3348
3537
  }
3349
3538
  const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
3350
3539
  if (fallback) return fallback;
3351
- return await ctx.shell.execute(cmd, { cwd: ctx.cwd, env: ctx.env });
3540
+ const binPrefix = `${PosixPath.join(ctx.cwd || '/workspace', 'node_modules/.bin')}:/workspace/node_modules/.bin`;
3541
+ const scriptEnv = {
3542
+ ...ctx.env,
3543
+ PATH: ctx.env && ctx.env.PATH ? `${binPrefix}:${ctx.env.PATH}` : `${binPrefix}:/usr/local/bin:/usr/bin:/bin`
3544
+ };
3545
+ const subRes = await ctx.shell.execute(cmd, {
3546
+ cwd: ctx.cwd,
3547
+ env: scriptEnv,
3548
+ stdin: ctx.stdin,
3549
+ signal: ctx.signal,
3550
+ onStdout: ctx.onStdout,
3551
+ onStderr: ctx.onStderr,
3552
+ onRequestStdin: ctx.onRequestStdin || (ctx.shell && ctx.shell.options ? ctx.shell.options.onRequestStdin : undefined)
3553
+ });
3554
+ return {
3555
+ code: subRes.code !== undefined ? subRes.code : 0,
3556
+ stdout: subRes.stdout || '',
3557
+ stderr: subRes.stderr || '',
3558
+ alreadyStreamed: Boolean(ctx.onStdout),
3559
+ aborted: subRes.aborted
3560
+ };
3352
3561
  }
3353
3562
 
3354
3563
  // ---------------------------------------------------------------------------
@@ -3978,14 +4187,19 @@
3978
4187
  },
3979
4188
 
3980
4189
  async cd(args, ctx) {
4190
+ const homeDir = (ctx.env && ctx.env.HOME) || '/home/codelab';
4191
+ PosixPath._homeDir = homeDir;
3981
4192
  let target = args[0];
3982
4193
  if (!target || target === '~') {
3983
- target = ctx.env.HOME || '/workspace';
4194
+ target = homeDir;
3984
4195
  } else if (target === '-') {
3985
4196
  target = ctx.env.OLDPWD || ctx.cwd;
3986
4197
  }
3987
4198
 
3988
4199
  const resolved = ctx.resolvePath(target);
4200
+ if (resolved === homeDir && !ctx.vfs.existsSync(resolved) && typeof ctx.vfs.mkdirSync === 'function') {
4201
+ try { ctx.vfs.mkdirSync(resolved, { recursive: true }); } catch (_err) { void _err; }
4202
+ }
3989
4203
  if (!ctx.vfs.existsSync(resolved)) {
3990
4204
  return { code: 1, stdout: '', stderr: `cd: ${target}: No such file or directory\n` };
3991
4205
  }
@@ -4005,6 +4219,9 @@
4005
4219
  ctx.cwd = resolved;
4006
4220
  ctx.env.OLDPWD = oldPwd;
4007
4221
  ctx.env.PWD = resolved;
4222
+ if (ctx.vfs && typeof ctx.vfs._setCwd === 'function') {
4223
+ ctx.vfs._setCwd(resolved);
4224
+ }
4008
4225
  if (ctx.shell) {
4009
4226
  ctx.shell.cwd = resolved;
4010
4227
  ctx.shell.env.OLDPWD = oldPwd;
@@ -5902,7 +6119,7 @@
5902
6119
  return {
5903
6120
  code: 0,
5904
6121
  stdout:
5905
- 'usage: git <command> [<args>]\n\nCommon commands: init, clone, status, add, diff, commit, restore, reset, rm, branch, checkout, switch, remote, fetch, pull, log\n',
6122
+ 'usage: git <command> [<args>]\n\nCommon commands: init, clone, status, add, diff, commit, restore, reset, rm, branch, checkout, switch, merge, stash, tag, show, blame, remote, fetch, pull, push, log\n',
5906
6123
  stderr: ''
5907
6124
  };
5908
6125
  }
@@ -6128,11 +6345,39 @@
6128
6345
  }
6129
6346
 
6130
6347
  repoRoot = PosixPath.normalize(gitState.repoRoot || ctx.cwd);
6348
+ const scmMod = getScmModule();
6349
+
6350
+ const buildIgnoreChecker = (liveMap) => {
6351
+ const rawIgnore = liveMap && typeof liveMap['.gitignore'] === 'string'
6352
+ ? liveMap['.gitignore']
6353
+ : ((gitState.headSnapshot && typeof gitState.headSnapshot['.gitignore'] === 'string') ? gitState.headSnapshot['.gitignore'] : '');
6354
+ if (!rawIgnore) return () => false;
6355
+ if (scmMod && typeof scmMod.parseGitignoreRules === 'function' && typeof scmMod.isIgnoredByRules === 'function') {
6356
+ const rules = scmMod.parseGitignoreRules(rawIgnore);
6357
+ return (relPath) => scmMod.isIgnoredByRules(relPath, rules);
6358
+ }
6359
+ return () => false;
6360
+ };
6361
+
6362
+ const saveCurrentBranchTip = () => {
6363
+ if (scmMod && typeof scmMod.saveBranchTip === 'function') {
6364
+ scmMod.saveBranchTip(gitState);
6365
+ return;
6366
+ }
6367
+ if (!gitState.branchHeads || typeof gitState.branchHeads !== 'object') gitState.branchHeads = {};
6368
+ const curBranch = gitState.branch || 'main';
6369
+ gitState.branchHeads[curBranch] = {
6370
+ headCommit: gitState.headCommit || '',
6371
+ headSnapshot: Object.assign({}, gitState.headSnapshot || gitState.headFiles || {}),
6372
+ commits: Array.isArray(gitState.commits) ? gitState.commits.map((c) => Object.assign({}, c)) : []
6373
+ };
6374
+ };
6131
6375
 
6132
6376
  if (subcmd === 'status') {
6133
6377
  const isShort = args.includes('-s') || args.includes('--short') || args.includes('--porcelain');
6134
6378
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
6135
6379
  const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6380
+ const isIgnored = buildIgnoreChecker(liveFiles);
6136
6381
  pruneShellStagedMap(gitState, stagedMap, headFiles);
6137
6382
  const unbornHead = isUnbornShellHead(gitState);
6138
6383
 
@@ -6150,7 +6395,7 @@
6150
6395
  if (inHead) {
6151
6396
  stagedList.push({ status: 'deleted', code: 'D', path: relPath });
6152
6397
  }
6153
- if (inLive) {
6398
+ if (inLive && !isIgnored(relPath)) {
6154
6399
  untrackedList.push(relPath);
6155
6400
  }
6156
6401
  } else {
@@ -6179,7 +6424,9 @@
6179
6424
 
6180
6425
  for (const relPath of Object.keys(liveFiles).sort()) {
6181
6426
  if (!Object.prototype.hasOwnProperty.call(headFiles, relPath) && !stagedMap.has(relPath)) {
6182
- untrackedList.push(relPath);
6427
+ if (!isIgnored(relPath)) {
6428
+ untrackedList.push(relPath);
6429
+ }
6183
6430
  }
6184
6431
  }
6185
6432
 
@@ -6285,14 +6532,19 @@
6285
6532
 
6286
6533
  if (subcmd === 'add') {
6287
6534
  const targets = args.slice(1);
6535
+ const forceAdd = targets.includes('-f') || targets.includes('--force');
6288
6536
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
6289
6537
  const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6538
+ const isIgnored = forceAdd ? () => false : buildIgnoreChecker(liveFiles);
6290
6539
 
6291
- const stagePath = (relPath) => {
6540
+ const stagePath = (relPath, explicitTarget = false) => {
6292
6541
  const clean = normalizeGitRelPath(relPath, repoRoot);
6293
6542
  if (!clean) return;
6294
6543
  const inLive = Object.prototype.hasOwnProperty.call(liveFiles, clean);
6295
6544
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, clean);
6545
+ if (!inHead && !stagedMap.has(clean) && !explicitTarget && isIgnored(clean)) {
6546
+ return;
6547
+ }
6296
6548
  if (inLive) {
6297
6549
  applyShellStagedEntry(gitState, stagedMap, clean, liveFiles[clean], headFiles);
6298
6550
  } else if (inHead) {
@@ -6307,14 +6559,14 @@
6307
6559
  for (const relPath of Object.keys(liveFiles)) {
6308
6560
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
6309
6561
  if (!inHead && includeUntracked) {
6310
- stagePath(relPath);
6562
+ stagePath(relPath, false);
6311
6563
  } else if (inHead) {
6312
- stagePath(relPath);
6564
+ stagePath(relPath, false);
6313
6565
  }
6314
6566
  }
6315
6567
  for (const relPath of Object.keys(headFiles)) {
6316
6568
  if (!Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
6317
- stagePath(relPath);
6569
+ stagePath(relPath, false);
6318
6570
  }
6319
6571
  }
6320
6572
  for (const stagedKey of Array.from(stagedMap.keys())) {
@@ -6331,9 +6583,9 @@
6331
6583
  const rel = toRepoRel(f);
6332
6584
  if (!rel) continue;
6333
6585
  if (rel === '.') {
6334
- for (const k of Object.keys(liveFiles)) stagePath(k);
6586
+ for (const k of Object.keys(liveFiles)) stagePath(k, false);
6335
6587
  for (const k of Object.keys(headFiles)) {
6336
- if (!Object.prototype.hasOwnProperty.call(liveFiles, k)) stagePath(k);
6588
+ if (!Object.prototype.hasOwnProperty.call(liveFiles, k)) stagePath(k, false);
6337
6589
  }
6338
6590
  for (const stagedKey of Array.from(stagedMap.keys())) {
6339
6591
  if (
@@ -6353,9 +6605,16 @@
6353
6605
  ])
6354
6606
  );
6355
6607
  if (matchedSubfiles.length > 0) {
6356
- for (const k of matchedSubfiles) stagePath(k);
6608
+ for (const k of matchedSubfiles) stagePath(k, false);
6357
6609
  } else {
6358
- stagePath(rel);
6610
+ if (!Object.prototype.hasOwnProperty.call(headFiles, rel) && !stagedMap.has(rel) && isIgnored(rel)) {
6611
+ return {
6612
+ code: 1,
6613
+ stdout: '',
6614
+ stderr: `The following paths are ignored by one of your .gitignore files:\n${rel}\nhint: Use -f if you really want to add them.\n`
6615
+ };
6616
+ }
6617
+ stagePath(rel, true);
6359
6618
  }
6360
6619
  }
6361
6620
  }
@@ -6426,6 +6685,7 @@
6426
6685
  });
6427
6686
  gitState.headCommit = hash;
6428
6687
  stagedMap.clear();
6688
+ saveCurrentBranchTip();
6429
6689
  return {
6430
6690
  code: 0,
6431
6691
  stdout: `[${gitState.branch} ${hash}] ${msg}\n ${count} file${count === 1 ? '' : 's'} changed\n`,
@@ -6434,6 +6694,7 @@
6434
6694
  }
6435
6695
 
6436
6696
  if (subcmd === 'branch') {
6697
+ saveCurrentBranchTip();
6437
6698
  const dIdx = args.findIndex((a) => a === '-d' || a === '-D');
6438
6699
  if (dIdx !== -1 && dIdx + 1 < args.length) {
6439
6700
  const target = args[dIdx + 1];
@@ -6441,20 +6702,34 @@
6441
6702
  return { code: 1, stdout: '', stderr: `error: Cannot delete branch '${target}' checked out\n` };
6442
6703
  }
6443
6704
  gitState.branches.delete(target);
6705
+ if (gitState.branchHeads) delete gitState.branchHeads[target];
6444
6706
  return { code: 0, stdout: `Deleted branch ${target}.\n`, stderr: '' };
6445
6707
  }
6446
6708
  const mIdx = args.findIndex((a) => a === '-m' || a === '-M');
6447
6709
  if (mIdx !== -1 && mIdx + 1 < args.length) {
6710
+ const oldName = gitState.branch;
6448
6711
  const newName = args[mIdx + 1];
6449
- gitState.branches.delete(gitState.branch);
6712
+ gitState.branches.delete(oldName);
6450
6713
  gitState.branch = newName;
6451
6714
  gitState.branches.add(newName);
6715
+ if (gitState.branchHeads && gitState.branchHeads[oldName]) {
6716
+ gitState.branchHeads[newName] = gitState.branchHeads[oldName];
6717
+ delete gitState.branchHeads[oldName];
6718
+ }
6452
6719
  return { code: 0, stdout: '', stderr: '' };
6453
6720
  }
6454
6721
  const nonFlags = args.slice(1).filter((a) => !a.startsWith('-'));
6455
6722
  if (nonFlags.length > 0) {
6456
6723
  for (const bName of nonFlags) {
6457
6724
  gitState.branches.add(bName);
6725
+ if (!gitState.branchHeads) gitState.branchHeads = {};
6726
+ if (!gitState.branchHeads[bName]) {
6727
+ gitState.branchHeads[bName] = {
6728
+ headCommit: gitState.headCommit || '',
6729
+ headSnapshot: Object.assign({}, gitState.headSnapshot || gitState.headFiles || {}),
6730
+ commits: Array.isArray(gitState.commits) ? gitState.commits.map((c) => Object.assign({}, c)) : []
6731
+ };
6732
+ }
6458
6733
  }
6459
6734
  return { code: 0, stdout: '', stderr: '' };
6460
6735
  }
@@ -6471,11 +6746,18 @@
6471
6746
  }
6472
6747
 
6473
6748
  if (subcmd === 'checkout' || subcmd === 'switch') {
6749
+ const forceCheckout = args.includes('-f') || args.includes('--force');
6474
6750
  const bIdx = args.findIndex((a) => a === '-b' || a === '-B' || a === '-c' || a === '-C');
6475
6751
  if (bIdx !== -1 && bIdx + 1 < args.length) {
6476
6752
  const newBranch = args[bIdx + 1];
6753
+ saveCurrentBranchTip();
6477
6754
  gitState.branches.add(newBranch);
6478
6755
  gitState.branch = newBranch;
6756
+ saveCurrentBranchTip();
6757
+ const headPath = PosixPath.join(repoRoot, '.git/HEAD');
6758
+ if (ctx.vfs.existsSync(PosixPath.join(repoRoot, '.git'))) {
6759
+ ctx.vfs.writeFileSync(headPath, `ref: refs/heads/${newBranch}\n`);
6760
+ }
6479
6761
  return { code: 0, stdout: `Switched to a new branch '${newBranch}'\n`, stderr: '' };
6480
6762
  }
6481
6763
 
@@ -6485,6 +6767,18 @@
6485
6767
  }
6486
6768
 
6487
6769
  if (gitState.branches.has(target) && !args.includes('--')) {
6770
+ if (scmMod && typeof scmMod.checkoutBranch === 'function') {
6771
+ const chkRes = scmMod.checkoutBranch(ctx.shell, target, undefined, { force: forceCheckout });
6772
+ if (!chkRes.ok) {
6773
+ return { code: 1, stdout: '', stderr: (chkRes.error || `error: cannot checkout '${target}'`) + '\n' };
6774
+ }
6775
+ const headPath = PosixPath.join(repoRoot, '.git/HEAD');
6776
+ if (ctx.vfs.existsSync(PosixPath.join(repoRoot, '.git'))) {
6777
+ ctx.vfs.writeFileSync(headPath, `ref: refs/heads/${target}\n`);
6778
+ }
6779
+ return { code: 0, stdout: `Switched to branch '${target}'\n`, stderr: '' };
6780
+ }
6781
+ saveCurrentBranchTip();
6488
6782
  gitState.branch = target;
6489
6783
  return { code: 0, stdout: `Switched to branch '${target}'\n`, stderr: '' };
6490
6784
  }
@@ -6567,8 +6861,31 @@
6567
6861
 
6568
6862
  if (subcmd === 'reset') {
6569
6863
  const isHard = args.includes('--hard');
6570
- const fileArgs = args.slice(1).filter((a) => !a.startsWith('-') && a !== 'HEAD' && a !== '--');
6571
- if (fileArgs.length > 0) {
6864
+ const isSoft = args.includes('--soft');
6865
+ const mode = isHard ? 'hard' : (isSoft ? 'soft' : 'mixed');
6866
+ const rawPositional = args.slice(1).filter((a) => !a.startsWith('-') && a !== '--');
6867
+
6868
+ // Check if first positional arg is a commit ref (HEAD, HEAD~N, HEAD^, branch, tag, or commit hash)
6869
+ const firstArg = rawPositional[0];
6870
+ const isCommitRef = firstArg && (
6871
+ firstArg === 'HEAD' ||
6872
+ /^HEAD(?:~\d*|\^+)$/i.test(firstArg) ||
6873
+ (scmMod && typeof scmMod.resolveCommitRef === 'function' && scmMod.resolveCommitRef(gitState, firstArg) !== null)
6874
+ );
6875
+
6876
+ if (isCommitRef && rawPositional.length === 1 && firstArg !== 'HEAD' && scmMod && typeof scmMod.resetToRef === 'function') {
6877
+ const resetRes = scmMod.resetToRef(ctx.shell, firstArg, mode);
6878
+ if (!resetRes.ok) {
6879
+ return { code: 128, stdout: '', stderr: (resetRes.error || `fatal: ambiguous argument '${firstArg}'`) + '\n' };
6880
+ }
6881
+ const out = isHard && resetRes.commit
6882
+ ? `HEAD is now at ${resetRes.commit.hash} ${resetRes.commit.message}\n`
6883
+ : '';
6884
+ return { code: 0, stdout: out, stderr: '' };
6885
+ }
6886
+
6887
+ const fileArgs = rawPositional.filter((a) => a !== 'HEAD');
6888
+ if (fileArgs.length > 0 && !isHard && !isSoft) {
6572
6889
  for (const f of fileArgs) {
6573
6890
  const rel = toRepoRel(f);
6574
6891
  if (!rel) continue;
@@ -6587,7 +6904,10 @@
6587
6904
  }
6588
6905
  return { code: 0, stdout: '', stderr: '' };
6589
6906
  }
6590
- stagedMap.clear();
6907
+
6908
+ if (!isSoft) {
6909
+ stagedMap.clear();
6910
+ }
6591
6911
  if (isHard) {
6592
6912
  const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6593
6913
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
@@ -6609,6 +6929,7 @@
6609
6929
  ctx.emitMutation('change', abs);
6610
6930
  }
6611
6931
  }
6932
+ saveCurrentBranchTip();
6612
6933
  return { code: 0, stdout: '', stderr: '' };
6613
6934
  }
6614
6935
 
@@ -6761,6 +7082,144 @@
6761
7082
  }
6762
7083
  }
6763
7084
 
7085
+ if (subcmd === 'stash') {
7086
+ if (!Array.isArray(gitState.stashes)) gitState.stashes = [];
7087
+ const action = args[1] && !args[1].startsWith('-') ? args[1] : 'push';
7088
+ if (action === 'list') {
7089
+ const lines = gitState.stashes.map((s, idx) => `stash@{${idx}}: ${s.message}`);
7090
+ return { code: 0, stdout: lines.length ? lines.join('\n') + '\n' : '', stderr: '' };
7091
+ }
7092
+ if (action === 'clear') {
7093
+ gitState.stashes = [];
7094
+ return { code: 0, stdout: '', stderr: '' };
7095
+ }
7096
+ if (action === 'drop') {
7097
+ const idxMatch = (args[2] || 'stash@{0}').match(/(\d+)/);
7098
+ const idx = idxMatch ? parseInt(idxMatch[1], 10) : 0;
7099
+ if (idx < 0 || idx >= gitState.stashes.length) {
7100
+ return { code: 1, stdout: '', stderr: `error: stash@{${idx}} is not a valid reference\n` };
7101
+ }
7102
+ gitState.stashes.splice(idx, 1);
7103
+ return { code: 0, stdout: `Dropped stash@{${idx}}\n`, stderr: '' };
7104
+ }
7105
+ if (action === 'pop' || action === 'apply') {
7106
+ const idxMatch = (args[2] || 'stash@{0}').match(/(\d+)/);
7107
+ const idx = idxMatch ? parseInt(idxMatch[1], 10) : 0;
7108
+ if (scmMod && typeof scmMod.stashApply === 'function') {
7109
+ const res = scmMod.stashApply(ctx.shell, idx, action === 'pop');
7110
+ if (!res.ok) return { code: 1, stdout: '', stderr: (res.error || 'No stash entries found.') + '\n' };
7111
+ return { code: 0, stdout: `Restored working directory from stash@{${idx}}\n`, stderr: '' };
7112
+ }
7113
+ return { code: 1, stdout: '', stderr: 'No stash entries found.\n' };
7114
+ }
7115
+ if (action === 'push' || action === 'save') {
7116
+ let msg = undefined;
7117
+ const mIdx = args.findIndex((a) => a === '-m' || a === '--message');
7118
+ if (mIdx !== -1 && args[mIdx + 1]) msg = args[mIdx + 1];
7119
+ else if (action === 'save' && args[2]) msg = args.slice(2).join(' ');
7120
+ const includeUntracked = args.includes('-u') || args.includes('--include-untracked');
7121
+ if (scmMod && typeof scmMod.stashPush === 'function') {
7122
+ const res = scmMod.stashPush(ctx.shell, msg, includeUntracked);
7123
+ if (!res.ok) {
7124
+ return { code: 1, stdout: '', stderr: (res.label || 'not a git repository') + '\n' };
7125
+ }
7126
+ return { code: 0, stdout: (res.label || 'No local changes to save') + '\n', stderr: '' };
7127
+ }
7128
+ }
7129
+ return { code: 1, stdout: '', stderr: `git stash: unknown subcommand '${action}'\n` };
7130
+ }
7131
+
7132
+ if (subcmd === 'merge') {
7133
+ const noFf = args.includes('--no-ff');
7134
+ const sourceBranch = args.slice(1).find((a) => !a.startsWith('-'));
7135
+ if (!sourceBranch) {
7136
+ return { code: 1, stdout: '', stderr: 'fatal: No branch specified to merge.\n' };
7137
+ }
7138
+ if (scmMod && typeof scmMod.mergeBranch === 'function') {
7139
+ const res = scmMod.mergeBranch(ctx.shell, sourceBranch, undefined, { noFf });
7140
+ if (!res.ok && (!res.conflicts || res.conflicts.length === 0)) {
7141
+ return { code: 1, stdout: '', stderr: (res.error || `merge: ${sourceBranch} - not something we can merge`) + '\n' };
7142
+ }
7143
+ if (res.conflicts && res.conflicts.length > 0) {
7144
+ return {
7145
+ code: 1,
7146
+ stdout: res.conflicts.map((f) => `CONFLICT (content): Merge conflict in ${f}`).join('\n') + '\nAutomatic merge failed; fix conflicts and then commit the result.\n',
7147
+ stderr: ''
7148
+ };
7149
+ }
7150
+ if (res.fastForward && res.commit) {
7151
+ return { code: 0, stdout: `Updating ..${res.commit.hash}\nFast-forward\n`, stderr: '' };
7152
+ }
7153
+ if (res.commit) {
7154
+ return { code: 0, stdout: `Merge made by the 'ort' strategy.\n[${gitState.branch} ${res.commit.hash}] ${res.commit.message}\n`, stderr: '' };
7155
+ }
7156
+ return { code: 0, stdout: 'Already up to date.\n', stderr: '' };
7157
+ }
7158
+ return { code: 1, stdout: '', stderr: 'git merge: SCM module unavailable\n' };
7159
+ }
7160
+
7161
+ if (subcmd === 'tag') {
7162
+ if (!gitState.tags || typeof gitState.tags !== 'object') gitState.tags = {};
7163
+ if (args[1] === '-d' && args[2]) {
7164
+ if (!gitState.tags[args[2]]) {
7165
+ return { code: 1, stdout: '', stderr: `error: tag '${args[2]}' not found.\n` };
7166
+ }
7167
+ delete gitState.tags[args[2]];
7168
+ return { code: 0, stdout: `Deleted tag '${args[2]}'\n`, stderr: '' };
7169
+ }
7170
+ const tagName = args.slice(1).find((a) => !a.startsWith('-'));
7171
+ if (!tagName) {
7172
+ const list = Object.keys(gitState.tags).sort();
7173
+ return { code: 0, stdout: list.length ? list.join('\n') + '\n' : '', stderr: '' };
7174
+ }
7175
+ if (!gitState.headCommit) {
7176
+ return { code: 128, stdout: '', stderr: `fatal: Failed to resolve 'HEAD' as a valid ref.\n` };
7177
+ }
7178
+ gitState.tags[tagName] = gitState.headCommit;
7179
+ return { code: 0, stdout: '', stderr: '' };
7180
+ }
7181
+
7182
+ if (subcmd === 'show') {
7183
+ const ref = args.slice(1).find((a) => !a.startsWith('-')) || 'HEAD';
7184
+ if (scmMod && typeof scmMod.showCommit === 'function') {
7185
+ const out = scmMod.showCommit(gitState, ref);
7186
+ if (!out) return { code: 128, stdout: '', stderr: `fatal: bad object ${ref}\n` };
7187
+ return { code: 0, stdout: out, stderr: '' };
7188
+ }
7189
+ return { code: 128, stdout: '', stderr: `fatal: bad object ${ref}\n` };
7190
+ }
7191
+
7192
+ if (subcmd === 'blame') {
7193
+ const fileArg = args.slice(1).find((a) => !a.startsWith('-'));
7194
+ if (!fileArg) return { code: 128, stdout: '', stderr: 'usage: git blame <file>\n' };
7195
+ const rel = toRepoRel(fileArg);
7196
+ const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
7197
+ if (scmMod && typeof scmMod.blameFile === 'function') {
7198
+ const out = scmMod.blameFile(gitState, rel, liveFiles);
7199
+ if (!out && !Object.prototype.hasOwnProperty.call(liveFiles, rel)) {
7200
+ return { code: 128, stdout: '', stderr: `fatal: no such path '${fileArg}' in HEAD\n` };
7201
+ }
7202
+ return { code: 0, stdout: out, stderr: '' };
7203
+ }
7204
+ return { code: 128, stdout: '', stderr: `fatal: no such path '${fileArg}' in HEAD\n` };
7205
+ }
7206
+
7207
+ if (subcmd === 'push') {
7208
+ const remoteUrl = gitState.remoteUrl || (gitState.remotes && gitState.remotes.origin);
7209
+ if (!remoteUrl) {
7210
+ return {
7211
+ code: 128,
7212
+ stdout: '',
7213
+ stderr: 'fatal: No configured push destination.\nEither specify the URL from the command-line or configure a remote repository using\n\n git remote add <name> <url>\n'
7214
+ };
7215
+ }
7216
+ return {
7217
+ code: 128,
7218
+ stdout: '',
7219
+ stderr: `fatal: Authentication required to push to '${remoteUrl}' from browser sandbox.\n`
7220
+ };
7221
+ }
7222
+
6764
7223
  if (subcmd === 'log') {
6765
7224
  const oneline = args.includes('--oneline');
6766
7225
  let limit = gitState.commits.length;
@@ -6784,7 +7243,11 @@
6784
7243
  return { code: 0, stdout, stderr: '' };
6785
7244
  }
6786
7245
 
6787
- return { code: 0, stdout: `git: '${subcmd}' executed\n`, stderr: '' };
7246
+ return {
7247
+ code: 1,
7248
+ stdout: '',
7249
+ stderr: `git: '${subcmd}' is not a git command. See 'git --help'.\n`
7250
+ };
6788
7251
  },
6789
7252
 
6790
7253
  // -----------------------------------------------------------------------
@@ -6843,14 +7306,98 @@
6843
7306
  if (!hasVirtualRuntime()) {
6844
7307
  return { code: 1, stdout: '', stderr: 'node: Virtual runtime engine is not available\n' };
6845
7308
  }
6846
- if (args.length === 0 || args[0] === '-v' || args[0] === '--version') {
6847
- if (args[0] === '-v' || args[0] === '--version') return { code: 0, stdout: 'v22.0.0\n', stderr: '' };
7309
+ if (args[0] === '-v' || args[0] === '--version') {
7310
+ return { code: 0, stdout: 'v22.0.0\n', stderr: '' };
7311
+ }
7312
+ if (args.length === 0 || args[0] === '-i' || args[0] === '--interactive') {
7313
+ const onRequestStdin =
7314
+ (typeof ctx.onRequestStdin === 'function' ? ctx.onRequestStdin : null) ||
7315
+ (ctx.shell && ctx.shell.options && typeof ctx.shell.options.onRequestStdin === 'function'
7316
+ ? ctx.shell.options.onRequestStdin
7317
+ : null);
7318
+ if (ctx.stdin && !onRequestStdin) {
7319
+ const res = await executeJsInShellRuntime({
7320
+ mode: 'repl',
7321
+ replCode: ctx.stdin,
7322
+ printReplResult: true,
7323
+ stdin: '',
7324
+ env: ctx.env,
7325
+ cwd: ctx.cwd,
7326
+ vfs: ctx.vfs,
7327
+ pid: ctx.pid,
7328
+ isBackground: ctx.isBackground,
7329
+ onStdout: ctx.onStdout,
7330
+ onStderr: ctx.onStderr,
7331
+ signal: ctx.signal
7332
+ }, ctx);
7333
+ return { code: res.ok ? 0 : (res.exitCode || 1), stdout: res.stdout, stderr: res.stderr };
7334
+ }
7335
+ if (onRequestStdin && !ctx.stdin) {
7336
+ const banner = 'Welcome to Node.js v22.0.0.\nType ".help" for more information.\n';
7337
+ let fullOut = banner;
7338
+ let fullErr = '';
7339
+ if (ctx.onStdout) ctx.onStdout(banner);
7340
+ const replSessionId = 'node_repl_' + Date.now() + '_' + Math.random().toString(36).slice(2, 7);
7341
+ const rm = getRuntimeModule();
7342
+ try {
7343
+ while (!(ctx.signal && ctx.signal.aborted)) {
7344
+ const line = await onRequestStdin('> ');
7345
+ if (line === null || line === undefined) break;
7346
+ const trimmed = String(line).trim();
7347
+ if (trimmed === '.exit') break;
7348
+ if (trimmed === '.help') {
7349
+ const helpMsg =
7350
+ '.break Sometimes you get stuck, this gets you out\n' +
7351
+ '.clear Break, and also clear the local context\n' +
7352
+ '.exit Exit the REPL\n' +
7353
+ '.help Print this help message\n';
7354
+ fullOut += helpMsg;
7355
+ if (ctx.onStdout) ctx.onStdout(helpMsg);
7356
+ continue;
7357
+ }
7358
+ if (trimmed === '.clear' || trimmed === '.break') {
7359
+ if (trimmed === '.clear' && rm && typeof rm.clearReplSession === 'function') {
7360
+ rm.clearReplSession(replSessionId);
7361
+ }
7362
+ continue;
7363
+ }
7364
+ if (!trimmed) continue;
7365
+ const stepRes = await executeInVirtualRuntime({
7366
+ mode: 'repl',
7367
+ replSessionId,
7368
+ replCode: String(line),
7369
+ printReplResult: true,
7370
+ env: ctx.env,
7371
+ cwd: ctx.cwd,
7372
+ vfs: ctx.vfs,
7373
+ activePortTable: ctx.shell ? ctx.shell.portTable : null,
7374
+ pid: ctx.pid,
7375
+ onRequestStdin,
7376
+ onStdout: (t) => {
7377
+ fullOut += t;
7378
+ if (ctx.onStdout) ctx.onStdout(t);
7379
+ },
7380
+ onStderr: (t) => {
7381
+ fullErr += t;
7382
+ if (ctx.onStderr) ctx.onStderr(t);
7383
+ },
7384
+ signal: ctx.signal
7385
+ });
7386
+ void stepRes;
7387
+ }
7388
+ } finally {
7389
+ if (rm && typeof rm.clearReplSession === 'function') {
7390
+ rm.clearReplSession(replSessionId);
7391
+ }
7392
+ }
7393
+ return { code: 0, stdout: fullOut, stderr: fullErr, alreadyStreamed: true };
7394
+ }
6848
7395
  return { code: 0, stdout: 'Welcome to Node.js v22.0.0.\nType ".help" for more information.\n', stderr: '' };
6849
7396
  }
6850
7397
 
6851
7398
  if (args[0] === '-e' || args[0] === '--eval') {
6852
7399
  const code = args[1] || '';
6853
- const res = await executeInVirtualRuntime({
7400
+ const res = await executeJsInShellRuntime({
6854
7401
  mode: 'repl',
6855
7402
  replCode: code,
6856
7403
  printReplResult: false,
@@ -6858,19 +7405,18 @@
6858
7405
  env: ctx.env,
6859
7406
  cwd: ctx.cwd,
6860
7407
  vfs: ctx.vfs,
6861
- activePortTable: ctx.shell.portTable,
6862
7408
  pid: ctx.pid,
6863
7409
  isBackground: ctx.isBackground,
6864
7410
  onStdout: ctx.onStdout,
6865
7411
  onStderr: ctx.onStderr,
6866
7412
  signal: ctx.signal
6867
- });
7413
+ }, ctx);
6868
7414
  return { code: res.ok ? 0 : (res.exitCode || 1), stdout: res.stdout, stderr: res.stderr };
6869
7415
  }
6870
7416
 
6871
7417
  if (args[0] === '-p' || args[0] === '--print') {
6872
7418
  const code = args[1] || '';
6873
- const res = await executeInVirtualRuntime({
7419
+ const res = await executeJsInShellRuntime({
6874
7420
  mode: 'repl',
6875
7421
  replCode: code,
6876
7422
  printReplResult: true,
@@ -6878,13 +7424,12 @@
6878
7424
  env: ctx.env,
6879
7425
  cwd: ctx.cwd,
6880
7426
  vfs: ctx.vfs,
6881
- activePortTable: ctx.shell.portTable,
6882
7427
  pid: ctx.pid,
6883
7428
  isBackground: ctx.isBackground,
6884
7429
  onStdout: ctx.onStdout,
6885
7430
  onStderr: ctx.onStderr,
6886
7431
  signal: ctx.signal
6887
- });
7432
+ }, ctx);
6888
7433
  return { code: res.ok ? 0 : (res.exitCode || 1), stdout: res.stdout, stderr: res.stderr };
6889
7434
  }
6890
7435
 
@@ -6899,7 +7444,7 @@
6899
7444
  for (const item of ctx.vfs.readdirSync(dir)) {
6900
7445
  const full = PosixPath.join(dir, item);
6901
7446
  const st = ctx.vfs.statSync(full);
6902
- if (st.isDirectory() && item !== 'node_modules') {
7447
+ if (st.isDirectory() && item !== 'node_modules' && item !== '.git') {
6903
7448
  findTests(full);
6904
7449
  } else if (item.endsWith('.test.js') || item.endsWith('.test.ts') || item === 'test.js') {
6905
7450
  filesToRun.push(full);
@@ -6913,20 +7458,19 @@
6913
7458
  let combinedErr = '';
6914
7459
  let allOk = true;
6915
7460
  for (const f of filesToRun) {
6916
- const res = await executeInVirtualRuntime({
7461
+ const res = await executeJsInShellRuntime({
6917
7462
  mode: 'test',
6918
7463
  entry: f,
6919
7464
  stdin: ctx.stdin || '',
6920
7465
  env: ctx.env,
6921
7466
  cwd: ctx.cwd,
6922
7467
  vfs: ctx.vfs,
6923
- activePortTable: ctx.shell.portTable,
6924
7468
  pid: ctx.pid,
6925
7469
  isBackground: ctx.isBackground,
6926
7470
  onStdout: ctx.onStdout,
6927
7471
  onStderr: ctx.onStderr,
6928
7472
  signal: ctx.signal
6929
- });
7473
+ }, ctx);
6930
7474
  combinedOut += res.stdout;
6931
7475
  combinedErr += res.stderr;
6932
7476
  if (!res.ok) allOk = false;
@@ -6940,7 +7484,7 @@
6940
7484
  }
6941
7485
 
6942
7486
  const scriptArgs = args.slice(1);
6943
- const res = await executeInVirtualRuntime({
7487
+ const res = await executeJsInShellRuntime({
6944
7488
  mode: 'run',
6945
7489
  entry: scriptFile,
6946
7490
  argv: ['node', scriptFile, ...scriptArgs],
@@ -6948,13 +7492,12 @@
6948
7492
  env: ctx.env,
6949
7493
  cwd: ctx.cwd,
6950
7494
  vfs: ctx.vfs,
6951
- activePortTable: ctx.shell.portTable,
6952
7495
  pid: ctx.pid,
6953
7496
  isBackground: ctx.isBackground,
6954
7497
  onStdout: ctx.onStdout,
6955
7498
  onStderr: ctx.onStderr,
6956
7499
  signal: ctx.signal
6957
- });
7500
+ }, ctx);
6958
7501
  return { code: res.ok ? 0 : (res.exitCode || 1), stdout: res.stdout, stderr: res.stderr };
6959
7502
  },
6960
7503
 
@@ -7078,12 +7621,72 @@
7078
7621
  },
7079
7622
 
7080
7623
  async python3(args, ctx) {
7081
- if (args.length === 0) {
7624
+ if (args[0] === '--version' || args[0] === '-V') {
7082
7625
  return { code: 0, stdout: 'Python 3.12.8 (CPython WebAssembly via Pyodide)\n', stderr: '' };
7083
7626
  }
7084
7627
 
7085
- if (args[0] === '--version' || args[0] === '-V') {
7086
- return { code: 0, stdout: 'Python 3.12.8 (CPython WebAssembly via Pyodide)\n', stderr: '' };
7628
+ const pyCompiler =
7629
+ (ctx.shell && ctx.shell.options && ctx.shell.options.pythonCompiler) ||
7630
+ (typeof globalThis !== 'undefined' && globalThis.__codelabPythonCompiler) ||
7631
+ (typeof window !== 'undefined' && window.__codelabPythonCompiler);
7632
+
7633
+ const onRequestStdin =
7634
+ (typeof ctx.onRequestStdin === 'function' ? ctx.onRequestStdin : null) ||
7635
+ (ctx.shell && ctx.shell.options && typeof ctx.shell.options.onRequestStdin === 'function'
7636
+ ? ctx.shell.options.onRequestStdin
7637
+ : undefined);
7638
+
7639
+ if (args.length === 0 || args[0] === '-i') {
7640
+ if (!ctx.stdin && !onRequestStdin) {
7641
+ return { code: 0, stdout: 'Python 3.12.8 (CPython WebAssembly via Pyodide)\n', stderr: '' };
7642
+ }
7643
+ if (typeof pyCompiler !== 'function') {
7644
+ return {
7645
+ code: 1,
7646
+ stdout: '',
7647
+ stderr:
7648
+ 'python3: Python WebAssembly toolchain is not enabled. Enable pythonExtension from "@innovatorved/code-lab/extensions/python".\n'
7649
+ };
7650
+ }
7651
+ if (ctx.stdin && !onRequestStdin) {
7652
+ let outText = '';
7653
+ let errText = '';
7654
+ const res = await pyCompiler({
7655
+ source: ctx.stdin,
7656
+ stdin: '',
7657
+ env: ctx.env,
7658
+ cwd: ctx.cwd,
7659
+ vfs: ctx.vfs,
7660
+ signal: ctx.signal,
7661
+ onStdout: (t) => { outText += t; if (ctx.onStdout) ctx.onStdout(t); },
7662
+ onStderr: (t) => { errText += t; if (ctx.onStderr) ctx.onStderr(t); }
7663
+ });
7664
+ return { code: res && res.ok ? 0 : ((res && res.exitCode) || 1), stdout: outText, stderr: errText };
7665
+ }
7666
+ const banner = 'Python 3.12.8 (CPython WebAssembly via Pyodide)\nType "exit()" or Ctrl+D to exit.\n';
7667
+ let fullOut = banner;
7668
+ let fullErr = '';
7669
+ if (ctx.onStdout) ctx.onStdout(banner);
7670
+ while (!(ctx.signal && ctx.signal.aborted)) {
7671
+ const line = await onRequestStdin('>>> ');
7672
+ if (line === null || line === undefined) break;
7673
+ const trimmed = String(line).trim();
7674
+ if (trimmed === 'exit()' || trimmed === 'quit()') break;
7675
+ if (!trimmed) continue;
7676
+ await pyCompiler({
7677
+ source: String(line),
7678
+ repl: true,
7679
+ stdin: '',
7680
+ env: ctx.env,
7681
+ cwd: ctx.cwd,
7682
+ vfs: ctx.vfs,
7683
+ signal: ctx.signal,
7684
+ onRequestStdin,
7685
+ onStdout: (t) => { fullOut += t; if (ctx.onStdout) ctx.onStdout(t); },
7686
+ onStderr: (t) => { fullErr += t; if (ctx.onStderr) ctx.onStderr(t); }
7687
+ });
7688
+ }
7689
+ return { code: 0, stdout: fullOut, stderr: fullErr, alreadyStreamed: true };
7087
7690
  }
7088
7691
 
7089
7692
  let codeToRun = undefined;
@@ -7095,11 +7698,6 @@
7095
7698
  entryFile = ctx.resolvePath(args[0]);
7096
7699
  }
7097
7700
 
7098
- const pyCompiler =
7099
- (ctx.shell && ctx.shell.options && ctx.shell.options.pythonCompiler) ||
7100
- (typeof globalThis !== 'undefined' && globalThis.__codelabPythonCompiler) ||
7101
- (typeof window !== 'undefined' && window.__codelabPythonCompiler);
7102
-
7103
7701
  if (typeof pyCompiler !== 'function') {
7104
7702
  return {
7105
7703
  code: 1,
@@ -7118,6 +7716,8 @@
7118
7716
  env: ctx.env,
7119
7717
  cwd: ctx.cwd,
7120
7718
  vfs: ctx.vfs,
7719
+ signal: ctx.signal,
7720
+ onRequestStdin,
7121
7721
  onStdout: (t) => {
7122
7722
  outText += t;
7123
7723
  if (ctx.onStdout) ctx.onStdout(t);
@@ -7299,7 +7899,7 @@
7299
7899
 
7300
7900
  if (sub === '-e') {
7301
7901
  const code = args[1] || '';
7302
- const res = await executeInVirtualRuntime({
7902
+ const res = await executeJsInShellRuntime({
7303
7903
  mode: 'repl',
7304
7904
  replCode: code,
7305
7905
  printReplResult: false,
@@ -7307,13 +7907,12 @@
7307
7907
  env: ctx.env,
7308
7908
  cwd: ctx.cwd,
7309
7909
  vfs: ctx.vfs,
7310
- activePortTable: ctx.shell.portTable,
7311
7910
  pid: ctx.pid,
7312
7911
  isBackground: ctx.isBackground,
7313
7912
  onStdout: ctx.onStdout,
7314
7913
  onStderr: ctx.onStderr,
7315
7914
  signal: ctx.signal
7316
- });
7915
+ }, ctx);
7317
7916
  return { code: res.ok ? 0 : (res.exitCode || 1), stdout: res.stdout, stderr: res.stderr };
7318
7917
  }
7319
7918
 
@@ -7328,7 +7927,7 @@
7328
7927
  for (const item of ctx.vfs.readdirSync(dir)) {
7329
7928
  const full = PosixPath.join(dir, item);
7330
7929
  const st = ctx.vfs.statSync(full);
7331
- if (st.isDirectory() && item !== 'node_modules') {
7930
+ if (st.isDirectory() && item !== 'node_modules' && item !== '.git') {
7332
7931
  findTests(full);
7333
7932
  } else if (item.endsWith('.test.js') || item.endsWith('.test.ts')) {
7334
7933
  filesToRun.push(full);
@@ -7342,20 +7941,19 @@
7342
7941
  let combinedErr = '';
7343
7942
  let allOk = true;
7344
7943
  for (const f of filesToRun) {
7345
- const res = await executeInVirtualRuntime({
7944
+ const res = await executeJsInShellRuntime({
7346
7945
  mode: 'test',
7347
7946
  entry: f,
7348
7947
  stdin: ctx.stdin || '',
7349
7948
  env: ctx.env,
7350
7949
  cwd: ctx.cwd,
7351
7950
  vfs: ctx.vfs,
7352
- activePortTable: ctx.shell.portTable,
7353
7951
  pid: ctx.pid,
7354
7952
  isBackground: ctx.isBackground,
7355
7953
  onStdout: ctx.onStdout,
7356
7954
  onStderr: ctx.onStderr,
7357
7955
  signal: ctx.signal
7358
- });
7956
+ }, ctx);
7359
7957
  combinedOut += res.stdout;
7360
7958
  combinedErr += res.stderr;
7361
7959
  if (!res.ok) allOk = false;
@@ -7371,7 +7969,7 @@
7371
7969
  const resolved = ctx.resolvePath(target);
7372
7970
  if (ctx.vfs.existsSync(resolved)) {
7373
7971
  const scriptArgs = args.slice(2);
7374
- const res = await executeInVirtualRuntime({
7972
+ const res = await executeJsInShellRuntime({
7375
7973
  mode: 'run',
7376
7974
  entry: resolved,
7377
7975
  argv: ['bun', resolved, ...scriptArgs],
@@ -7379,13 +7977,12 @@
7379
7977
  env: ctx.env,
7380
7978
  cwd: ctx.cwd,
7381
7979
  vfs: ctx.vfs,
7382
- activePortTable: ctx.shell.portTable,
7383
7980
  pid: ctx.pid,
7384
7981
  isBackground: ctx.isBackground,
7385
7982
  onStdout: ctx.onStdout,
7386
7983
  onStderr: ctx.onStderr,
7387
7984
  signal: ctx.signal
7388
- });
7985
+ }, ctx);
7389
7986
  return { code: res.ok ? 0 : (res.exitCode || 1), stdout: res.stdout, stderr: res.stderr };
7390
7987
  }
7391
7988
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
@@ -7398,7 +7995,7 @@
7398
7995
  const resolved = ctx.resolvePath(sub);
7399
7996
  if (ctx.vfs.existsSync(resolved)) {
7400
7997
  const scriptArgs = args.slice(1);
7401
- const res = await executeInVirtualRuntime({
7998
+ const res = await executeJsInShellRuntime({
7402
7999
  mode: 'run',
7403
8000
  entry: resolved,
7404
8001
  argv: ['bun', resolved, ...scriptArgs],
@@ -7406,13 +8003,12 @@
7406
8003
  env: ctx.env,
7407
8004
  cwd: ctx.cwd,
7408
8005
  vfs: ctx.vfs,
7409
- activePortTable: ctx.shell.portTable,
7410
8006
  pid: ctx.pid,
7411
8007
  isBackground: ctx.isBackground,
7412
8008
  onStdout: ctx.onStdout,
7413
8009
  onStderr: ctx.onStderr,
7414
8010
  signal: ctx.signal
7415
- });
8011
+ }, ctx);
7416
8012
  return { code: res.ok ? 0 : (res.exitCode || 1), stdout: res.stdout, stderr: res.stderr };
7417
8013
  }
7418
8014
 
@@ -7429,6 +8025,16 @@
7429
8025
  return { code: 0, stdout: 'npm v10.2.0\n', stderr: '' };
7430
8026
  }
7431
8027
  const sub = args[0];
8028
+ if (sub === '--version' || sub === '-v' || sub === 'version') {
8029
+ return { code: 0, stdout: '10.2.0\n', stderr: '' };
8030
+ }
8031
+ if (sub === '--help' || sub === '-h' || sub === 'help') {
8032
+ return {
8033
+ code: 0,
8034
+ stdout: 'npm v10.2.0\nUsage: npm <command>\n\nCommands: init, install, uninstall, list, run, start, test\n',
8035
+ stderr: ''
8036
+ };
8037
+ }
7432
8038
 
7433
8039
  if (sub === 'init') {
7434
8040
  const pkgPath = PosixPath.join(ctx.cwd, 'package.json');
@@ -7485,6 +8091,10 @@
7485
8091
  return await runPackageScript('test', args.slice(1), ctx);
7486
8092
  }
7487
8093
 
8094
+ if (sub === 'start') {
8095
+ return await runPackageScript('start', args.slice(1), ctx);
8096
+ }
8097
+
7488
8098
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
7489
8099
  if (pkgData.scripts && pkgData.scripts[sub]) {
7490
8100
  return await runPackageScript(sub, args.slice(1), ctx);
@@ -7494,17 +8104,37 @@
7494
8104
  },
7495
8105
 
7496
8106
  async npx(args, ctx) {
7497
- if (args.length === 0) {
8107
+ const filtered = [];
8108
+ for (let i = 0; i < args.length; i++) {
8109
+ if (args[i] === '-y' || args[i] === '--yes' || args[i] === '--no-install') continue;
8110
+ filtered.push(args[i]);
8111
+ }
8112
+ if (filtered.length === 0) {
7498
8113
  return { code: 1, stdout: '', stderr: 'npx: missing command\n' };
7499
8114
  }
7500
- const cmd = args[0];
7501
- const cmdArgs = args.slice(1);
7502
- const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
7503
- if (ctx.vfs.existsSync(binPath)) {
7504
- return await ctx.commands.node([binPath, ...cmdArgs], ctx);
8115
+ const cmd = filtered[0];
8116
+ const cmdArgs = filtered.slice(1);
8117
+ const localBin = PosixPath.join(ctx.cwd || '/workspace', 'node_modules/.bin', cmd);
8118
+ const rootBin = PosixPath.join('/workspace/node_modules/.bin', cmd);
8119
+ const binPath = ctx.vfs.existsSync(localBin) ? localBin : (ctx.vfs.existsSync(rootBin) ? rootBin : null);
8120
+ if (binPath) {
8121
+ const shimSrc = String(ctx.vfs.readFileSync(binPath, 'utf8') || '');
8122
+ const execMatch = shimSrc.match(/exec\s+node\s+"([^"]+)"/);
8123
+ if (execMatch && execMatch[1]) {
8124
+ return await ctx.shell.commands.node([execMatch[1], ...cmdArgs], ctx);
8125
+ }
8126
+ return await ctx.shell.commands.node([binPath, ...cmdArgs], ctx);
7505
8127
  }
7506
8128
  const cmdStr = [cmd, ...cmdArgs].map(quoteShellArg).join(' ');
7507
- return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
8129
+ return await ctx.shell.execute(cmdStr, {
8130
+ cwd: ctx.cwd,
8131
+ env: ctx.env,
8132
+ stdin: ctx.stdin,
8133
+ signal: ctx.signal,
8134
+ onStdout: ctx.onStdout,
8135
+ onStderr: ctx.onStderr,
8136
+ onRequestStdin: ctx.onRequestStdin
8137
+ });
7508
8138
  },
7509
8139
 
7510
8140
  async bunx(args, ctx) {
@@ -7573,10 +8203,7 @@
7573
8203
  if (sub === 'exec') {
7574
8204
  const cmd = args[1];
7575
8205
  if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
7576
- const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
7577
- if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
7578
- const cmdStr = [cmd, ...args.slice(2)].map(quoteShellArg).join(' ');
7579
- return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
8206
+ return await this.npx([cmd, ...args.slice(2)], ctx);
7580
8207
  }
7581
8208
 
7582
8209
  if (sub === 'dlx') {
@@ -8099,7 +8726,13 @@
8099
8726
  sqlInput = String(ctx.stdin).trim();
8100
8727
  }
8101
8728
 
8102
- if (!sqlInput) {
8729
+ const onRequestStdin =
8730
+ (typeof ctx.onRequestStdin === 'function' ? ctx.onRequestStdin : null) ||
8731
+ (ctx.shell && ctx.shell.options && typeof ctx.shell.options.onRequestStdin === 'function'
8732
+ ? ctx.shell.options.onRequestStdin
8733
+ : null);
8734
+
8735
+ if (!sqlInput && !onRequestStdin) {
8103
8736
  return {
8104
8737
  code: 0,
8105
8738
  stdout: 'SQLite 3.45.0 (CodeLab VFS Engine)\nUsage: sqlite3 [-column] [-header] [-json] [dbfile] "SQL"\n',
@@ -8117,14 +8750,12 @@
8117
8750
  return { code: 1, stdout: '', stderr: 'sqlite3: SQLite engine not initialized in runtime\n' };
8118
8751
  }
8119
8752
 
8120
- try {
8121
- const SqliteDatabase = createDb(ctx.vfs, () => ctx.shell.cwd);
8122
- const db = new SqliteDatabase(dbFile);
8123
- const trimmed = sqlInput.trim();
8124
-
8753
+ const executeSqlBatch = (db, batchText) => {
8754
+ const trimmed = String(batchText || '').trim();
8755
+ if (!trimmed) return '';
8125
8756
  if (trimmed === '.tables') {
8126
8757
  const names = Array.from(db.tables.keys());
8127
- return { code: 0, stdout: names.length ? names.join(' ') + '\n' : '', stderr: '' };
8758
+ return names.length ? names.join(' ') + '\n' : '';
8128
8759
  }
8129
8760
  if (trimmed.startsWith('.schema')) {
8130
8761
  const lines = [];
@@ -8135,11 +8766,11 @@
8135
8766
  for (const idx of db.indexes.values()) {
8136
8767
  lines.push(`CREATE ${idx.unique ? 'UNIQUE ' : ''}INDEX ${idx.name} ON ${idx.table} (${idx.columns.join(', ')});`);
8137
8768
  }
8138
- return { code: 0, stdout: lines.join('\n') + (lines.length ? '\n' : ''), stderr: '' };
8769
+ return lines.join('\n') + (lines.length ? '\n' : '');
8139
8770
  }
8140
8771
  if (trimmed === '.indexes' || trimmed === '.indices') {
8141
8772
  const names = Array.from(db.indexes.keys());
8142
- return { code: 0, stdout: names.length ? names.join(' ') + '\n' : '', stderr: '' };
8773
+ return names.length ? names.join(' ') + '\n' : '';
8143
8774
  }
8144
8775
 
8145
8776
  const stmts = trimmed.split(';').map(s => s.trim()).filter(Boolean);
@@ -8170,10 +8801,281 @@
8170
8801
  }
8171
8802
  }
8172
8803
  }
8173
- return { code: 0, stdout: outputs.length ? outputs.join('\n') + '\n' : '', stderr: '' };
8804
+ return outputs.length ? outputs.join('\n') + '\n' : '';
8805
+ };
8806
+
8807
+ try {
8808
+ const SqliteDatabase = createDb(ctx.vfs, () => ctx.shell.cwd);
8809
+ const db = new SqliteDatabase(dbFile);
8810
+
8811
+ if (!sqlInput && onRequestStdin) {
8812
+ const banner = 'SQLite version 3.45.0 (CodeLab VFS Engine)\nEnter ".help" for usage hints, ".quit" to exit.\n';
8813
+ let fullOut = banner;
8814
+ let fullErr = '';
8815
+ if (ctx.onStdout) ctx.onStdout(banner);
8816
+ while (!(ctx.signal && ctx.signal.aborted)) {
8817
+ const line = await onRequestStdin('sqlite> ');
8818
+ if (line === null || line === undefined) break;
8819
+ const trimmedLine = String(line).trim();
8820
+ if (trimmedLine === '.quit' || trimmedLine === '.exit') break;
8821
+ if (trimmedLine === '.help') {
8822
+ const h = '.tables List names of tables\n.schema Show CREATE statements\n.indexes Show names of indexes\n.quit Exit this program\n';
8823
+ fullOut += h;
8824
+ if (ctx.onStdout) ctx.onStdout(h);
8825
+ continue;
8826
+ }
8827
+ if (!trimmedLine) continue;
8828
+ try {
8829
+ const stepOut = executeSqlBatch(db, trimmedLine);
8830
+ if (stepOut) {
8831
+ fullOut += stepOut;
8832
+ if (ctx.onStdout) ctx.onStdout(stepOut);
8833
+ }
8834
+ } catch (stepErr) {
8835
+ const errMsg = `Error: ${stepErr.message || String(stepErr)}\n`;
8836
+ fullErr += errMsg;
8837
+ if (ctx.onStderr) ctx.onStderr(errMsg);
8838
+ }
8839
+ }
8840
+ return { code: 0, stdout: fullOut, stderr: fullErr, alreadyStreamed: true };
8841
+ }
8842
+
8843
+ const out = executeSqlBatch(db, sqlInput);
8844
+ return { code: 0, stdout: out, stderr: '' };
8174
8845
  } catch (err) {
8175
8846
  return { code: 1, stdout: '', stderr: `Error: ${err.message || String(err)}\n` };
8176
8847
  }
8848
+ },
8849
+
8850
+ async read(args, ctx) {
8851
+ let prompt = '';
8852
+ let rawMode = false;
8853
+ const varNames = [];
8854
+ for (let i = 0; i < args.length; i++) {
8855
+ const a = args[i];
8856
+ if (a === '-r') {
8857
+ rawMode = true;
8858
+ } else if (a === '-p' && i + 1 < args.length) {
8859
+ prompt = String(args[++i]);
8860
+ } else if (a.startsWith('-') && a.length > 1) {
8861
+ if (a.includes('r')) rawMode = true;
8862
+ } else {
8863
+ varNames.push(a);
8864
+ }
8865
+ }
8866
+ if (varNames.length === 0) varNames.push('REPLY');
8867
+
8868
+ let line = null;
8869
+ if (ctx.stdin && String(ctx.stdin).length > 0) {
8870
+ const str = String(ctx.stdin);
8871
+ const nl = str.indexOf('\n');
8872
+ line = nl === -1 ? str : str.slice(0, nl);
8873
+ if (line.endsWith('\r')) line = line.slice(0, -1);
8874
+ } else {
8875
+ const onRequestStdin =
8876
+ (typeof ctx.onRequestStdin === 'function' ? ctx.onRequestStdin : null) ||
8877
+ (ctx.shell && ctx.shell.options && typeof ctx.shell.options.onRequestStdin === 'function'
8878
+ ? ctx.shell.options.onRequestStdin
8879
+ : null);
8880
+ if (onRequestStdin) {
8881
+ line = await onRequestStdin(prompt);
8882
+ }
8883
+ }
8884
+
8885
+ if (line === null || line === undefined) {
8886
+ return { code: 1, stdout: '', stderr: '' };
8887
+ }
8888
+
8889
+ let processed = String(line).replace(/\r?\n$/, '');
8890
+ if (!rawMode) {
8891
+ processed = processed.replace(/\\(.)/g, '$1');
8892
+ }
8893
+
8894
+ const ifs = ctx.env && ctx.env.IFS !== undefined ? String(ctx.env.IFS) : ' \t\n';
8895
+ if (varNames.length === 1) {
8896
+ const trimmed = ifs.includes(' ') ? processed.trim() : processed;
8897
+ ctx.env[varNames[0]] = trimmed;
8898
+ if (ctx.shell) ctx.shell.env[varNames[0]] = trimmed;
8899
+ } else {
8900
+ const sepRe = ifs.length > 0
8901
+ ? new RegExp('[' + ifs.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + ']+')
8902
+ : null;
8903
+ const parts = sepRe ? processed.trim().split(sepRe) : [processed];
8904
+ for (let idx = 0; idx < varNames.length; idx++) {
8905
+ const vName = varNames[idx];
8906
+ const val = idx === varNames.length - 1
8907
+ ? parts.slice(idx).join(' ')
8908
+ : (parts[idx] || '');
8909
+ ctx.env[vName] = val;
8910
+ if (ctx.shell) ctx.shell.env[vName] = val;
8911
+ }
8912
+ }
8913
+ return { code: 0, stdout: '', stderr: '' };
8914
+ },
8915
+
8916
+ async tsc(args, ctx) {
8917
+ if (args.includes('--version') || args.includes('-v')) {
8918
+ return { code: 0, stdout: 'Version 5.6.3\n', stderr: '' };
8919
+ }
8920
+ if (args.includes('--help') || args.includes('-h')) {
8921
+ return {
8922
+ code: 0,
8923
+ stdout:
8924
+ 'Version 5.6.3\nSyntax: tsc [options] [file...]\n\nOptions:\n' +
8925
+ ' --init Initializes a TypeScript project and creates a tsconfig.json file.\n' +
8926
+ ' --noEmit Do not emit outputs.\n' +
8927
+ ' --outDir <dir> Redirect output structure to the directory.\n' +
8928
+ ' -v, --version Print the compiler\'s version.\n',
8929
+ stderr: ''
8930
+ };
8931
+ }
8932
+ if (args.includes('--init')) {
8933
+ const tsconfigPath = PosixPath.join(ctx.cwd, 'tsconfig.json');
8934
+ if (!ctx.vfs.existsSync(tsconfigPath)) {
8935
+ ctx.vfs.writeFileSync(
8936
+ tsconfigPath,
8937
+ JSON.stringify(
8938
+ {
8939
+ compilerOptions: {
8940
+ target: 'ES2022',
8941
+ module: 'ESNext',
8942
+ moduleResolution: 'bundler',
8943
+ strict: true,
8944
+ esModuleInterop: true,
8945
+ skipLibCheck: true,
8946
+ jsx: 'react-jsx'
8947
+ }
8948
+ },
8949
+ null,
8950
+ 2
8951
+ ) + '\n'
8952
+ );
8953
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', tsconfigPath);
8954
+ }
8955
+ return { code: 0, stdout: 'Created a new tsconfig.json\n', stderr: '' };
8956
+ }
8957
+
8958
+ const noEmit = args.includes('--noEmit');
8959
+ let outDir = null;
8960
+ const explicitFiles = [];
8961
+ for (let i = 0; i < args.length; i++) {
8962
+ const a = args[i];
8963
+ if (a === '--outDir' && i + 1 < args.length) {
8964
+ outDir = ctx.resolvePath(args[++i]);
8965
+ } else if (a === '-p' || a === '--project') {
8966
+ i++;
8967
+ } else if (!a.startsWith('-')) {
8968
+ explicitFiles.push(ctx.resolvePath(a));
8969
+ }
8970
+ }
8971
+
8972
+ const files = [];
8973
+ if (explicitFiles.length > 0) {
8974
+ files.push(...explicitFiles);
8975
+ } else {
8976
+ const scanTs = (dir) => {
8977
+ if (!ctx.vfs.existsSync(dir)) return;
8978
+ for (const entry of ctx.vfs.readdirSync(dir)) {
8979
+ if (entry === 'node_modules' || entry === '.git' || entry === 'dist') continue;
8980
+ const full = PosixPath.join(dir, entry);
8981
+ const st = ctx.vfs.statSync(full);
8982
+ if (st.isDirectory()) scanTs(full);
8983
+ else if (/\.(ts|tsx)$/i.test(entry) && !entry.endsWith('.d.ts')) files.push(full);
8984
+ }
8985
+ };
8986
+ scanTs(ctx.cwd);
8987
+ }
8988
+
8989
+ let errOut = '';
8990
+ let exitCode = 0;
8991
+ for (const filePath of files) {
8992
+ if (!ctx.vfs.existsSync(filePath)) {
8993
+ errOut += `error TS6053: File '${filePath}' not found.\n`;
8994
+ exitCode = 2;
8995
+ continue;
8996
+ }
8997
+ const src = String(ctx.vfs.readFileSync(filePath, 'utf8') || '');
8998
+ try {
8999
+ const tsCompiler = typeof globalThis !== 'undefined' && globalThis.ts ? globalThis.ts : null;
9000
+ let jsOut = '';
9001
+ if (tsCompiler && typeof tsCompiler.transpileModule === 'function') {
9002
+ const tr = tsCompiler.transpileModule(src, {
9003
+ fileName: filePath,
9004
+ reportDiagnostics: true,
9005
+ compilerOptions: {
9006
+ target: tsCompiler.ScriptTarget ? tsCompiler.ScriptTarget.ES2022 : 9,
9007
+ module: tsCompiler.ModuleKind ? tsCompiler.ModuleKind.ESNext : 99
9008
+ }
9009
+ });
9010
+ if (Array.isArray(tr.diagnostics) && tr.diagnostics.length > 0) {
9011
+ for (const d of tr.diagnostics) {
9012
+ const msg = typeof d.messageText === 'string' ? d.messageText : (d.messageText && d.messageText.messageText) || 'Syntax error';
9013
+ errOut += `${PosixPath.relative(ctx.cwd, filePath)}(1,1): error TS${d.code || 1005}: ${msg}\n`;
9014
+ }
9015
+ exitCode = 2;
9016
+ continue;
9017
+ }
9018
+ jsOut = tr.outputText;
9019
+ } else {
9020
+ // Deterministic CSP-safe delimiter & unterminated string check before transpiling
9021
+ let inStr = null;
9022
+ let inLineComment = false;
9023
+ let inBlockComment = false;
9024
+ let braceBalance = 0;
9025
+ let parenBalance = 0;
9026
+ let lineNo = 1;
9027
+ for (let ci = 0; ci < src.length; ci++) {
9028
+ const ch = src[ci];
9029
+ const nxt = src[ci + 1];
9030
+ if (ch === '\n') {
9031
+ lineNo++;
9032
+ if (inStr === '"' || inStr === "'") {
9033
+ throw new Error(`Line ${lineNo - 1}: Unterminated string literal.`);
9034
+ }
9035
+ inLineComment = false;
9036
+ continue;
9037
+ }
9038
+ if (inLineComment) continue;
9039
+ if (inBlockComment) {
9040
+ if (ch === '*' && nxt === '/') { inBlockComment = false; ci++; }
9041
+ continue;
9042
+ }
9043
+ if (inStr) {
9044
+ if (ch === '\\') { ci++; continue; }
9045
+ if (ch === inStr) inStr = null;
9046
+ continue;
9047
+ }
9048
+ if (ch === '/' && nxt === '/') { inLineComment = true; ci++; continue; }
9049
+ if (ch === '/' && nxt === '*') { inBlockComment = true; ci++; continue; }
9050
+ if (ch === '"' || ch === "'" || ch === '`') { inStr = ch; continue; }
9051
+ if (ch === '{') braceBalance++;
9052
+ else if (ch === '}') braceBalance--;
9053
+ else if (ch === '(') parenBalance++;
9054
+ else if (ch === ')') parenBalance--;
9055
+ if (braceBalance < 0 || parenBalance < 0) {
9056
+ throw new Error(`Line ${lineNo}: Unexpected closing token '${ch}'.`);
9057
+ }
9058
+ }
9059
+ if (inStr) throw new Error(`Line ${lineNo}: Unterminated string literal.`);
9060
+ if (braceBalance !== 0 || parenBalance !== 0) {
9061
+ throw new Error(`Line ${lineNo}: Unexpected end of file (unclosed '${braceBalance !== 0 ? '{' : '('}').`);
9062
+ }
9063
+ jsOut = transpileTS(src, filePath);
9064
+ }
9065
+ if (!noEmit) {
9066
+ const rel = PosixPath.relative(ctx.cwd, filePath).replace(/\.(tsx|ts)$/i, '.js');
9067
+ const dest = outDir ? PosixPath.join(outDir, rel) : filePath.replace(/\.(tsx|ts)$/i, '.js');
9068
+ const destDir = PosixPath.dirname(dest);
9069
+ if (!ctx.vfs.existsSync(destDir)) ctx.vfs.mkdirSync(destDir, { recursive: true });
9070
+ ctx.vfs.writeFileSync(dest, jsOut);
9071
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', dest);
9072
+ }
9073
+ } catch (err) {
9074
+ errOut += `${PosixPath.relative(ctx.cwd, filePath)}(1,1): error TS1005: ${err.message || String(err)}\n`;
9075
+ exitCode = 2;
9076
+ }
9077
+ }
9078
+ return { code: exitCode, stdout: '', stderr: errOut };
8177
9079
  }
8178
9080
  };
8179
9081
 
@@ -8582,15 +9484,28 @@
8582
9484
  this.portTable = options.portTable || (typeof createVirtualPortTable === 'function' ? createVirtualPortTable() : null);
8583
9485
  this.vfs = options.vfs || createFallbackVfs();
8584
9486
  this.env = Object.assign({
8585
- PATH: '/usr/local/bin:/usr/bin:/bin',
9487
+ PATH: '/workspace/node_modules/.bin:/usr/local/bin:/usr/bin:/bin',
8586
9488
  PWD: '/workspace',
8587
- HOME: '/home/user',
9489
+ HOME: '/home/codelab',
8588
9490
  USER: 'codelab',
8589
9491
  SHELL: '/bin/sh',
8590
9492
  TERM: 'xterm-256color',
8591
9493
  '?': '0'
8592
9494
  }, options.env || {});
9495
+ PosixPath._homeDir = this.env.HOME || '/home/codelab';
8593
9496
  this.cwd = this.env.PWD || '/workspace';
9497
+ if (this.vfs && typeof this.vfs._setCwd === 'function') {
9498
+ this.vfs._setCwd(this.cwd);
9499
+ }
9500
+ if (
9501
+ this.vfs &&
9502
+ typeof this.vfs.mkdirSync === 'function' &&
9503
+ typeof this.vfs.existsSync === 'function' &&
9504
+ this.env.HOME &&
9505
+ !this.vfs.existsSync(this.env.HOME)
9506
+ ) {
9507
+ try { this.vfs.mkdirSync(this.env.HOME, { recursive: true }); } catch (_err) { void _err; }
9508
+ }
8594
9509
  if (options.files && typeof options.files === 'object') {
8595
9510
  for (const [k, v] of Object.entries(options.files)) {
8596
9511
  const abs = PosixPath.resolve(this.cwd, k);
@@ -8631,18 +9546,36 @@
8631
9546
  }
8632
9547
 
8633
9548
  resolvePath(p) {
9549
+ PosixPath._homeDir = (this.env && this.env.HOME) || '/home/codelab';
8634
9550
  if (!p) return this.cwd;
8635
9551
  return PosixPath.resolve(this.cwd, p);
8636
9552
  }
8637
9553
 
8638
- // True when `name` resolves to a shell function or coreutil (used by the
8639
- // workbench to route recognised commands straight to the shell instead of
8640
- // treating flag-looking input such as `node --version` as a JS expression).
9554
+ _resolvePathBinary(name) {
9555
+ if (!name || !this.vfs || typeof this.vfs.existsSync !== 'function') return null;
9556
+ const n = String(name);
9557
+ if (n.includes('/')) return null;
9558
+ const localBin = PosixPath.join(this.cwd || '/workspace', 'node_modules/.bin', n);
9559
+ if (this.vfs.existsSync(localBin)) return localBin;
9560
+ const pathDirs = String((this.env && this.env.PATH) || '/workspace/node_modules/.bin:/usr/local/bin:/usr/bin:/bin')
9561
+ .split(':')
9562
+ .filter(Boolean);
9563
+ for (const dir of pathDirs) {
9564
+ const candidate = PosixPath.join(dir, n);
9565
+ if (this.vfs.existsSync(candidate)) return candidate;
9566
+ }
9567
+ const rootBin = PosixPath.join('/workspace/node_modules/.bin', n);
9568
+ if (this.vfs.existsSync(rootBin)) return rootBin;
9569
+ return null;
9570
+ }
9571
+
9572
+ // True when `name` resolves to a shell function, coreutil, or PATH/.bin shim.
8641
9573
  hasCommand(name) {
8642
9574
  if (!name) return false;
8643
9575
  const n = String(name);
8644
9576
  if (this.functions && Object.prototype.hasOwnProperty.call(this.functions, n)) return true;
8645
- return !!this.commands && Object.prototype.hasOwnProperty.call(this.commands, n);
9577
+ if (this.commands && Object.prototype.hasOwnProperty.call(this.commands, n)) return true;
9578
+ return Boolean(this._resolvePathBinary(n));
8646
9579
  }
8647
9580
 
8648
9581
  _emitVfsMutation(type, absPath) {
@@ -9527,6 +10460,8 @@
9527
10460
  let currentStdin = context.stdin || '';
9528
10461
  let combinedStderr = '';
9529
10462
  let lastResult = { code: 0, stdout: '', stderr: '' };
10463
+ const isolateSubshells = commands.length > 1;
10464
+ const parentCwd = this.cwd;
9530
10465
 
9531
10466
  for (let i = 0; i < commands.length; i++) {
9532
10467
  if (context.signal && context.signal.aborted) {
@@ -9549,7 +10484,32 @@
9549
10484
  onStderr: context.onStderr
9550
10485
  };
9551
10486
 
9552
- const res = await this._executeAstNode(cmd, cmdContext);
10487
+ let res;
10488
+ if (isolateSubshells) {
10489
+ const stageEnv = Object.assign({}, this.env, context.env || {});
10490
+ const stageShell = new PosixShell({
10491
+ ...this.options,
10492
+ vfs: this.vfs,
10493
+ portTable: this.portTable,
10494
+ gitState: this.gitState,
10495
+ _initialBootRoot: this._initialBootRoot,
10496
+ _initialBootSnapshot: this._initialBootSnapshot,
10497
+ env: stageEnv
10498
+ });
10499
+ stageShell.cwd = context.cwd || parentCwd;
10500
+ stageShell.functions = Object.assign({}, this.functions || {});
10501
+ res = await stageShell._executeAstNode(cmd, {
10502
+ ...cmdContext,
10503
+ cwd: stageShell.cwd,
10504
+ env: Object.assign({}, stageEnv)
10505
+ });
10506
+ if (this.vfs && typeof this.vfs._setCwd === 'function') {
10507
+ this.vfs._setCwd(parentCwd);
10508
+ }
10509
+ } else {
10510
+ res = await this._executeAstNode(cmd, cmdContext);
10511
+ }
10512
+
9553
10513
  currentStdin = res.stdout || '';
9554
10514
  combinedStderr += (res.stderr || '');
9555
10515
  lastResult = res;
@@ -9738,6 +10698,9 @@
9738
10698
  resolvePath: (p) => this.resolvePath(p),
9739
10699
  emitMutation: (type, p) => this._emitVfsMutation(type, p),
9740
10700
  signal: context.signal,
10701
+ onRequestStdin:
10702
+ (typeof context.onRequestStdin === 'function' ? context.onRequestStdin : null) ||
10703
+ (this.options && typeof this.options.onRequestStdin === 'function' ? this.options.onRequestStdin : undefined),
9741
10704
  onStdout: (chunk) => {
9742
10705
  if (!chunk) return;
9743
10706
  streamedStdoutBytes += chunk.length;
@@ -9752,6 +10715,10 @@
9752
10715
 
9753
10716
  // 7. Command execution dispatch
9754
10717
  let res;
10718
+ const resolvedPathBin =
10719
+ !(this.functions && this.functions[cmdName]) && !this.commands[cmdName]
10720
+ ? this._resolvePathBinary(cmdName)
10721
+ : null;
9755
10722
  if (this.functions && this.functions[cmdName]) {
9756
10723
  const fnDef = this.functions[cmdName];
9757
10724
  const fnEnv = Object.assign({}, cmdEnv);
@@ -9767,13 +10734,21 @@
9767
10734
  };
9768
10735
  } else if (this.commands[cmdName]) {
9769
10736
  res = await this.commands[cmdName](args, cmdCtx);
9770
- if (cmdName === 'export' || cmdName === 'unset' || cmdName === 'cd') {
10737
+ if (cmdName === 'export' || cmdName === 'unset' || cmdName === 'cd' || cmdName === 'read') {
9771
10738
  for (const k of Object.keys(context.env)) {
9772
10739
  if (!(k in this.env)) delete context.env[k];
9773
10740
  }
9774
10741
  Object.assign(context.env, this.env);
9775
10742
  context.cwd = this.cwd;
9776
10743
  }
10744
+ } else if (resolvedPathBin) {
10745
+ const shimSrc = String(this.vfs.readFileSync(resolvedPathBin, 'utf8') || '');
10746
+ const execMatch = shimSrc.match(/exec\s+node\s+"([^"]+)"/);
10747
+ if (execMatch && execMatch[1]) {
10748
+ res = await this.commands.node([execMatch[1], ...args], cmdCtx);
10749
+ } else {
10750
+ res = await this.commands.node([resolvedPathBin, ...args], cmdCtx);
10751
+ }
9777
10752
  } else if (
9778
10753
  (cmdName.startsWith('./') || cmdName.startsWith('../') || cmdName.startsWith('/')) &&
9779
10754
  this.vfs.existsSync(this.resolvePath(cmdName))
@@ -9784,7 +10759,11 @@
9784
10759
  res = { code: 126, stdout: '', stderr: `shell: ${cmdName}: Is a directory\n` };
9785
10760
  } else if (hasVirtualRuntime()) {
9786
10761
  let rawData = null;
9787
- try { rawData = this.vfs.readFileSync(absBin); } catch (err) { _shellLogger.debug('Failed to read binary', err); }
10762
+ try {
10763
+ rawData = typeof this.vfs._getRawFileBytes === 'function'
10764
+ ? (this.vfs._getRawFileBytes(absBin) || this.vfs.readFileSync(absBin))
10765
+ : this.vfs.readFileSync(absBin);
10766
+ } catch (err) { _shellLogger.debug('Failed to read binary', err); }
9788
10767
  const isWasmMagic =
9789
10768
  (rawData instanceof Uint8Array &&
9790
10769
  rawData.length >= 4 &&
@@ -9793,17 +10772,20 @@
9793
10772
  rawData[2] === 0x73 &&
9794
10773
  rawData[3] === 0x6d) ||
9795
10774
  (typeof rawData === 'string' && rawData.startsWith('\0asm'));
9796
- const runRes = await executeInVirtualRuntime({
10775
+ const runFn = isWasmMagic ? executeInVirtualRuntime : (rOpts) => executeJsInShellRuntime(rOpts, cmdCtx);
10776
+ const runRes = await runFn({
9797
10777
  mode: 'run',
9798
10778
  entry: absBin,
9799
10779
  wasmBinary: isWasmMagic && rawData instanceof Uint8Array ? rawData : undefined,
9800
10780
  argv: [cmdName, ...args],
9801
10781
  stdin: effectiveStdin,
9802
10782
  env: cmdEnv,
10783
+ cwd: this.cwd,
9803
10784
  vfs: this.vfs,
9804
10785
  activePortTable: this.portTable,
9805
10786
  pid: cmdCtx.pid,
9806
10787
  isBackground: cmdCtx.isBackground,
10788
+ onRequestStdin: cmdCtx.onRequestStdin,
9807
10789
  onStdout: cmdCtx.onStdout,
9808
10790
  onStderr: cmdCtx.onStderr,
9809
10791
  signal: context.signal