@innovatorved/code-lab 0.3.1 → 0.3.2

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 (48) hide show
  1. package/ARCHITECTURE.md +4 -2
  2. package/CHANGELOG.md +25 -0
  3. package/README.md +15 -5
  4. package/dist/code-lab.css +52 -2
  5. package/dist/code-lab.d.ts +1 -1
  6. package/dist/code-lab.esm.js +1247 -377
  7. package/dist/code-lab.js +1246 -376
  8. package/dist/diagnostics.d.ts +5 -0
  9. package/dist/extensions/cpp.esm.js +51 -9
  10. package/dist/extensions/cpp.js +51 -9
  11. package/dist/extensions/python.esm.js +116 -103
  12. package/dist/extensions/python.js +116 -103
  13. package/dist/index.d.ts +1 -1
  14. package/dist/preview-sw.js +34 -17
  15. package/dist/runtime.esm.js +38 -31
  16. package/dist/runtime.js +38 -31
  17. package/dist/schemas.d.ts +1 -1
  18. package/dist/scm.d.ts +13 -2
  19. package/dist/search.d.ts +5 -1
  20. package/dist/shell.esm.js +72 -16
  21. package/dist/shell.js +72 -16
  22. package/dist/terminal.esm.js +183 -54
  23. package/dist/terminal.js +183 -54
  24. package/dist/workbench/index.d.ts +1 -1
  25. package/dist/workbench/styles.d.ts +1 -1
  26. package/dist/zip.d.ts +4 -3
  27. package/package.json +1 -1
  28. package/src/code-lab.css +52 -2
  29. package/src/csp.ts +7 -10
  30. package/src/diagnostics.ts +42 -3
  31. package/src/extensions/cpp.ts +47 -9
  32. package/src/extensions/python.ts +128 -116
  33. package/src/index.ts +1 -1
  34. package/src/preview-sw.js +25 -5
  35. package/src/runtime.ts +36 -29
  36. package/src/schemas.ts +1 -1
  37. package/src/scm.ts +106 -19
  38. package/src/search.ts +71 -27
  39. package/src/shell.ts +70 -14
  40. package/src/terminal.ts +181 -52
  41. package/src/workbench/diff-editor.ts +41 -13
  42. package/src/workbench/drawer.ts +17 -4
  43. package/src/workbench/guided-pane.ts +12 -2
  44. package/src/workbench/share.ts +37 -8
  45. package/src/workbench/styles.ts +2 -1
  46. package/src/workbench/toolbar.ts +15 -4
  47. package/src/workbench.ts +482 -79
  48. package/src/zip.ts +29 -7
package/dist/runtime.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.3.1 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.3.2 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
7
7
  * - First-Class Node.js and Bun Runtimes (Bun.serve, bun:test, bun:sqlite, Bun.*)
8
- * - Full POSIX Shell AST & 55+ UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
8
+ * - Full POSIX Shell AST & 71 UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
9
9
  * - Interactive PTY Terminal Emulator with inline prompt, Tab completion & ANSI colors
10
10
  * - Persistent HTTP/TCP Servers, CLI curl & Live Port/HTTP Preview
11
11
  * - Modular VS Code Workbench: File Tree, Tabs, Command Palette, Diff Viewer
@@ -1135,22 +1135,40 @@ function __initVirtualRuntime(rootScope) {
1135
1135
  // =========================================================================
1136
1136
  // 5. VIRTUAL IN-MEMORY POSIX FILESYSTEM (node:fs)
1137
1137
  // =========================================================================
1138
- function createVirtualFs(initialFiles = {}) {
1138
+ function createVirtualFs(initialFiles = {}, vfsOptions = {}) {
1139
1139
  const dirs = new Set(['/', '/tmp', '/workspace', '/home', '/home/user']);
1140
1140
  const files = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, ctimeMs, ino }
1141
1141
  const deletedInspectorCache = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, deletedAtMs }
1142
+ const MAX_DELETED_CACHE_ENTRIES = 50;
1143
+ const MAX_DELETED_CACHE_FILE_BYTES = 65536;
1144
+ const customCwdGetter = typeof vfsOptions === 'function'
1145
+ ? vfsOptions
1146
+ : (vfsOptions && typeof vfsOptions.cwdGetter === 'function' ? vfsOptions.cwdGetter : null);
1142
1147
  const fdTable = new Map(); // fd -> { inode, path, flags, pos, isDirectory }
1143
1148
  let nextFd = 10;
1144
1149
  let nextIno = 100;
1145
1150
  let mkdtempCounter = 1;
1146
1151
 
1152
+ function recordDeletedForInspector(p, data, mtimeMs) {
1153
+ if (!data || data.byteLength <= 0 || data.byteLength > MAX_DELETED_CACHE_FILE_BYTES) return;
1154
+ if (deletedInspectorCache.has(p)) {
1155
+ deletedInspectorCache.delete(p);
1156
+ } else if (deletedInspectorCache.size >= MAX_DELETED_CACHE_ENTRIES) {
1157
+ const oldestKey = deletedInspectorCache.keys().next().value;
1158
+ if (oldestKey !== undefined) deletedInspectorCache.delete(oldestKey);
1159
+ }
1160
+ deletedInspectorCache.set(p, { data: data.slice(), mtimeMs, deletedAtMs: Date.now() });
1161
+ }
1162
+
1147
1163
  function normPath(p) {
1148
1164
  if (typeof p !== 'string' || !p) {
1149
1165
  const err = new TypeError('path must be a non-empty string');
1150
1166
  err.code = 'ERR_INVALID_ARG_TYPE';
1151
1167
  throw err;
1152
1168
  }
1153
- const baseCwd = typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace';
1169
+ const baseCwd = typeof customCwdGetter === 'function'
1170
+ ? customCwdGetter()
1171
+ : (typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace');
1154
1172
  const abs = p.startsWith('/') ? VirtualPath.normalize(p) : VirtualPath.resolve(baseCwd, p);
1155
1173
  return abs.length > 1 && abs.endsWith('/') ? abs.slice(0, -1) : abs;
1156
1174
  }
@@ -1201,9 +1219,13 @@ function __initVirtualRuntime(rootScope) {
1201
1219
  for (const [relPath, content] of Object.entries(initialFiles)) {
1202
1220
  const cleanRel = relPath.startsWith('/') ? relPath.slice(1) : relPath;
1203
1221
  const isSystemPath = /^\/(workspace|usr|tmp|lib|include|etc|bin|dev)(\/|$)/.test(relPath);
1204
- const fullPath = isSystemPath
1222
+ let fullPath = isSystemPath
1205
1223
  ? normPath(relPath)
1206
1224
  : normPath(`/workspace/${cleanRel}`);
1225
+ if (!isSystemPath && fullPath !== '/workspace' && !fullPath.startsWith('/workspace/')) {
1226
+ const safeSub = cleanRel.split('/').filter((seg) => seg && seg !== '.' && seg !== '..').join('/');
1227
+ fullPath = normPath(`/workspace/${safeSub || 'file'}`);
1228
+ }
1207
1229
  ensureParentDirs(fullPath);
1208
1230
  const bytes = typeof content === 'string' ? utf8Encode(content) : new Uint8Array(content);
1209
1231
  files.set(fullPath, {
@@ -1383,13 +1405,6 @@ function __initVirtualRuntime(rootScope) {
1383
1405
  fsyncSync(fd) {
1384
1406
  const entry = fdTable.get(fd);
1385
1407
  if (!entry) throw fsError('EBADF', 'fsync', String(fd), 'bad file descriptor');
1386
- if (!entry.isDirectory && entry.inode) {
1387
- deletedInspectorCache.set(entry.path, {
1388
- data: entry.inode.data.slice(),
1389
- mtimeMs: entry.inode.mtimeMs,
1390
- deletedAtMs: null
1391
- });
1392
- }
1393
1408
  },
1394
1409
 
1395
1410
  fdatasyncSync(fd) {
@@ -1430,12 +1445,6 @@ function __initVirtualRuntime(rootScope) {
1430
1445
  inode.mtimeMs = Date.now();
1431
1446
  entry.pos = writePos + chunk.byteLength;
1432
1447
 
1433
- deletedInspectorCache.set(entry.path, {
1434
- data: inode.data.slice(),
1435
- mtimeMs: inode.mtimeMs,
1436
- deletedAtMs: null
1437
- });
1438
-
1439
1448
  return chunk.byteLength;
1440
1449
  },
1441
1450
 
@@ -1487,7 +1496,7 @@ function __initVirtualRuntime(rootScope) {
1487
1496
  inode.mode = 0o100000 | (Number(opts.mode) & 0o777);
1488
1497
  }
1489
1498
  }
1490
- deletedInspectorCache.set(np, { data: bytes.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1499
+ deletedInspectorCache.delete(np);
1491
1500
  },
1492
1501
 
1493
1502
  chmodSync(p, mode) {
@@ -1516,7 +1525,7 @@ function __initVirtualRuntime(rootScope) {
1516
1525
  combined.set(chunk, inode.data.byteLength);
1517
1526
  inode.data = combined;
1518
1527
  inode.mtimeMs = Date.now();
1519
- deletedInspectorCache.set(np, { data: combined.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1528
+ deletedInspectorCache.delete(np);
1520
1529
  },
1521
1530
 
1522
1531
  truncateSync(p, len = 0) {
@@ -1532,7 +1541,6 @@ function __initVirtualRuntime(rootScope) {
1532
1541
  inode.data = grown;
1533
1542
  }
1534
1543
  inode.mtimeMs = Date.now();
1535
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1536
1544
  },
1537
1545
 
1538
1546
  renameSync(oldP, newP) {
@@ -1593,16 +1601,14 @@ function __initVirtualRuntime(rootScope) {
1593
1601
  if (fdEntry.path === src) fdEntry.path = dst;
1594
1602
  }
1595
1603
  deletedInspectorCache.delete(src);
1596
- deletedInspectorCache.set(dst, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1604
+ deletedInspectorCache.delete(dst);
1597
1605
  },
1598
1606
 
1599
1607
  unlinkSync(p) {
1600
1608
  const np = normPath(p);
1601
1609
  const inode = files.get(np);
1602
1610
  if (!inode) throw fsError('ENOENT', 'unlink', p, 'no such file or directory');
1603
- if (inode.data.byteLength > 0) {
1604
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
1605
- }
1611
+ recordDeletedForInspector(np, inode.data, inode.mtimeMs);
1606
1612
  files.delete(np);
1607
1613
  },
1608
1614
 
@@ -1619,9 +1625,7 @@ function __initVirtualRuntime(rootScope) {
1619
1625
  for (const [fPath, inode] of Array.from(files.entries())) {
1620
1626
  if (fPath.startsWith(prefix)) {
1621
1627
  if (!recursive) throw fsError('ENOTEMPTY', 'rm', p, 'directory not empty');
1622
- if (inode.data.byteLength > 0) {
1623
- deletedInspectorCache.set(fPath, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
1624
- }
1628
+ recordDeletedForInspector(fPath, inode.data, inode.mtimeMs);
1625
1629
  files.delete(fPath);
1626
1630
  }
1627
1631
  }
@@ -3195,6 +3199,7 @@ function __initVirtualRuntime(rootScope) {
3195
3199
  responseHeaders: {},
3196
3200
  _t0: performance.now()
3197
3201
  };
3202
+ if (httpTrace.length >= 500) httpTrace.shift();
3198
3203
  httpTrace.push(traceEntry);
3199
3204
  this._traceEntry = traceEntry;
3200
3205
 
@@ -4186,6 +4191,7 @@ function __initVirtualRuntime(rootScope) {
4186
4191
  this._peer = serverSocket;
4187
4192
  this.connecting = false;
4188
4193
 
4194
+ if (sharedTrace.length >= 500) sharedTrace.shift();
4189
4195
  sharedTrace.push({
4190
4196
  protocol: 'TCP',
4191
4197
  event: 'connect',
@@ -6478,7 +6484,10 @@ function __initVirtualRuntime(rootScope) {
6478
6484
  const activePortTable = optPortTable || portTable || _defaultPortTable;
6479
6485
  resourceTracker.pid = pid;
6480
6486
 
6481
- const vfs = optVfs || createVirtualFs(files);
6487
+ let currentCwd = '/workspace';
6488
+ _activeCwdGetter = () => currentCwd;
6489
+
6490
+ const vfs = optVfs || createVirtualFs(files, { cwdGetter: () => currentCwd });
6482
6491
  if (optVfs && files && typeof files === 'object') {
6483
6492
  for (const [fPath, content] of Object.entries(files)) {
6484
6493
  const abs = fPath.startsWith('/') ? fPath : '/workspace/' + fPath;
@@ -6872,8 +6881,6 @@ function __initVirtualRuntime(rootScope) {
6872
6881
  hrtimeFn.bigint = () => BigInt(Math.round(performance.now() * 1e6));
6873
6882
 
6874
6883
  let syncExecDepth = 0;
6875
- let currentCwd = '/workspace';
6876
- _activeCwdGetter = () => currentCwd;
6877
6884
 
6878
6885
  const sandboxProcess = Object.assign(new EventEmitter(), {
6879
6886
  env: { NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' },
package/dist/schemas.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  /**
3
- * Zod Schemas and Inferred TypeScript Types for code-lab v0.2.0
3
+ * Zod Schemas and Inferred TypeScript Types for code-lab v0.3.2
4
4
  */
5
5
  export declare const GuidedStepSchema: z.ZodObject<{
6
6
  id: z.ZodString;
package/dist/scm.d.ts CHANGED
@@ -27,9 +27,17 @@ export interface GitState {
27
27
  branches?: string[];
28
28
  headCommit: string;
29
29
  headFiles: Record<string, string>;
30
- staged: Map<string, string | null>;
30
+ headSnapshot?: Record<string, string>;
31
+ staged: Map<string, string | null> | Set<string>;
31
32
  commits: GitCommitRecord[];
32
33
  }
34
+ export interface GitStatusEntry {
35
+ path: string;
36
+ status: GitFileChangeType;
37
+ staged: boolean;
38
+ index: string;
39
+ worktree: string;
40
+ }
33
41
  export interface GitStatusResult {
34
42
  branch: string;
35
43
  headCommit: string;
@@ -38,6 +46,7 @@ export interface GitStatusResult {
38
46
  deleted: GitFileStatus[];
39
47
  staged: GitFileStatus[];
40
48
  unstaged: GitFileStatus[];
49
+ entries: GitStatusEntry[];
41
50
  hasChanges: boolean;
42
51
  isClean: boolean;
43
52
  }
@@ -51,8 +60,10 @@ export declare function computeShortCommitHash(input: string): string;
51
60
  export declare function createGitState(initialFiles?: Record<string, string>, branch?: string): GitState;
52
61
  /**
53
62
  * Computes working-tree and staging-area Git status against `gitState`.
63
+ * Supports both `computeGitStatus(vfsFiles, repoRoot, gitState)` and
64
+ * `computeGitStatus(gitState, vfsFiles)` calling conventions.
54
65
  */
55
- export declare function computeGitStatus(vfsFiles: Record<string, string>, _repoRoot?: string, gitState?: GitState): GitStatusResult;
66
+ export declare function computeGitStatus(arg1: Record<string, string> | GitState, arg2?: string | Record<string, string>, gitState?: GitState): GitStatusResult;
56
67
  /**
57
68
  * Stages a file addition, modification, or deletion (`currentContent === null`).
58
69
  */
package/dist/search.d.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  */
10
10
  export interface SearchOptions {
11
11
  query?: string;
12
+ replacement?: string;
12
13
  caseSensitive?: boolean;
13
14
  wholeWord?: boolean;
14
15
  regex?: boolean;
@@ -50,8 +51,10 @@ export interface SearchResult extends Array<SearchMatchGroup> {
50
51
  }
51
52
  export interface ReplaceResult {
52
53
  updatedFiles: Record<string, string>;
54
+ files: Record<string, string>;
53
55
  replacedCount: number;
54
56
  filesAffected: string[];
57
+ filesModified: number;
55
58
  }
56
59
  /**
57
60
  * Escapes regex special characters in a literal string.
@@ -63,6 +66,7 @@ export declare function escapeRegex(text: string): string;
63
66
  export declare function normalizeSearchPath(filePath: string): string;
64
67
  /**
65
68
  * Matches a file path against a glob or literal substring filter.
69
+ * Supports comma-separated patterns (e.g. `*.ts, *.js`).
66
70
  */
67
71
  export declare function matchesGlob(filePath: string, pattern: string): boolean;
68
72
  /**
@@ -72,4 +76,4 @@ export declare function searchInFiles(files: Record<string, string>, queryOrOpti
72
76
  /**
73
77
  * Replaces occurrences of a query pattern across virtual workspace files.
74
78
  */
75
- export declare function replaceInFiles(files: Record<string, string>, arg2: string | SearchOptions, arg3: string, arg4?: SearchOptions | string[]): ReplaceResult;
79
+ export declare function replaceInFiles(files: Record<string, string>, arg2: string | SearchOptions, arg3?: string, arg4?: SearchOptions | string[]): ReplaceResult;
package/dist/shell.esm.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.3.1 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.3.2 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
7
7
  * - First-Class Node.js and Bun Runtimes (Bun.serve, bun:test, bun:sqlite, Bun.*)
8
- * - Full POSIX Shell AST & 55+ UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
8
+ * - Full POSIX Shell AST & 71 UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
9
9
  * - Interactive PTY Terminal Emulator with inline prompt, Tab completion & ANSI colors
10
10
  * - Persistent HTTP/TCP Servers, CLI curl & Live Port/HTTP Preview
11
11
  * - Modular VS Code Workbench: File Tree, Tabs, Command Palette, Diff Viewer
@@ -3021,6 +3021,13 @@ var CodeLabLogger = (() => {
3021
3021
  return out;
3022
3022
  }
3023
3023
 
3024
+ function quoteShellArg(arg) {
3025
+ const s = String(arg ?? '');
3026
+ if (s.length === 0) return "''";
3027
+ if (!/[\s"'\\$&|;<>()`!*?~#]/.test(s)) return s;
3028
+ return "'" + s.replace(/'/g, "'\\''") + "'";
3029
+ }
3030
+
3024
3031
  async function runPackageScript(scriptName, scriptArgs, ctx) {
3025
3032
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
3026
3033
  if (!pkgData.scripts || !pkgData.scripts[scriptName]) {
@@ -3028,7 +3035,7 @@ var CodeLabLogger = (() => {
3028
3035
  }
3029
3036
  let cmd = pkgData.scripts[scriptName];
3030
3037
  if (scriptArgs && scriptArgs.length > 0) {
3031
- cmd += ' ' + scriptArgs.join(' ');
3038
+ cmd += ' ' + scriptArgs.map(quoteShellArg).join(' ');
3032
3039
  }
3033
3040
  const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
3034
3041
  if (fallback) return fallback;
@@ -3281,6 +3288,11 @@ var CodeLabLogger = (() => {
3281
3288
  const isFile = (p) => exists(p) && !isDir(p);
3282
3289
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
3283
3290
 
3291
+ const isWithinRoot = (p) => {
3292
+ const rootPrefix = rootDir === '/' ? '/' : rootDir + '/';
3293
+ return p === rootDir || p.startsWith(rootPrefix);
3294
+ };
3295
+
3284
3296
  const resolveLocalTarget = (baseDir, rawSpec) => {
3285
3297
  if (!rawSpec || typeof rawSpec !== 'string') return null;
3286
3298
  const clean = rawSpec.split(/[?#]/)[0].trim();
@@ -3288,6 +3300,7 @@ var CodeLabLogger = (() => {
3288
3300
  const candidateBase = clean.startsWith('/')
3289
3301
  ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
3290
3302
  : PosixPath.join(baseDir, clean);
3303
+ if (!isWithinRoot(candidateBase)) return null;
3291
3304
  if (isFile(candidateBase)) return candidateBase;
3292
3305
  const cands = [
3293
3306
  candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
@@ -3296,7 +3309,7 @@ var CodeLabLogger = (() => {
3296
3309
  PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
3297
3310
  ];
3298
3311
  for (const c of cands) {
3299
- if (isFile(c)) return c;
3312
+ if (isWithinRoot(c) && isFile(c)) return c;
3300
3313
  }
3301
3314
  return null;
3302
3315
  };
@@ -3425,7 +3438,7 @@ var CodeLabLogger = (() => {
3425
3438
  if (/@import\s+['"]tailwindcss['"]/i.test(cssContent)) {
3426
3439
  needsTailwindBrowser = true;
3427
3440
  }
3428
- const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget));
3441
+ const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget)).replace(/<\/style/gi, '<\\/style');
3429
3442
  return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${resolvedCss}\n</style>`;
3430
3443
  });
3431
3444
 
@@ -3437,7 +3450,7 @@ var CodeLabLogger = (() => {
3437
3450
  if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
3438
3451
  const rawScript = readText(scriptTarget);
3439
3452
  if (rawScript === null) return fullTag;
3440
- const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
3453
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget).replace(/<\/script/gi, '<\\/script');
3441
3454
  const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget) || /^\s*(?:import|export)\b/m.test(rawScript);
3442
3455
  const typeAttr = isMod ? ' type="module"' : '';
3443
3456
  return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
@@ -3460,6 +3473,12 @@ var CodeLabLogger = (() => {
3460
3473
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
3461
3474
  const rel = pathname.replace(/^\/+/, '');
3462
3475
  let target = PosixPath.join(rootDir, rel);
3476
+ if (!isWithinRoot(target)) {
3477
+ return new Response(
3478
+ '<!doctype html><meta charset="utf-8"><title>403</title><h1>403 Forbidden</h1>',
3479
+ { status: 403, headers: { 'content-type': 'text/html; charset=utf-8' } }
3480
+ );
3481
+ }
3463
3482
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
3464
3483
 
3465
3484
  if (!rel || pathname.endsWith('/') || isDir(target)) {
@@ -3484,8 +3503,13 @@ var CodeLabLogger = (() => {
3484
3503
  target = (!exists(rootIdx) && exists(pubIdx)) ? pubIdx : rootIdx; // SPA fallback
3485
3504
  }
3486
3505
  if (!exists(target)) {
3506
+ const safePath = String(pathname)
3507
+ .replace(/&/g, '&amp;')
3508
+ .replace(/</g, '&lt;')
3509
+ .replace(/>/g, '&gt;')
3510
+ .replace(/"/g, '&quot;');
3487
3511
  return new Response(
3488
- `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
3512
+ `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${safePath}</p>`,
3489
3513
  { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
3490
3514
  );
3491
3515
  }
@@ -5636,13 +5660,17 @@ var CodeLabLogger = (() => {
5636
5660
 
5637
5661
  const count = Math.max(1, result.filesWritten);
5638
5662
  const kb = Math.max(0.1, result.totalBytes / 1024).toFixed(1);
5663
+ if (!enumeratedEmitted) {
5664
+ streamLine(`remote: Enumerating objects: ${count}, done.\n`);
5665
+ streamLine(`remote: Counting objects: 100% (${count}/${count}), done.\n`);
5666
+ }
5639
5667
  streamLine(`Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`);
5640
5668
  const stdout =
5641
5669
  `Cloning into '${dirDisplayName}'...\n` +
5642
5670
  `remote: Enumerating objects: ${count}, done.\n` +
5643
5671
  `remote: Counting objects: 100% (${count}/${count}), done.\n` +
5644
5672
  `Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`;
5645
- return { code: 0, stdout, stderr: '' };
5673
+ return { code: 0, stdout, stderr: '', alreadyStreamed: canStream };
5646
5674
  } catch (err) {
5647
5675
  if (ctx.signal && ctx.signal.aborted) {
5648
5676
  return { code: 130, stdout: '', stderr: '', aborted: true };
@@ -6705,7 +6733,8 @@ var CodeLabLogger = (() => {
6705
6733
  if (ctx.vfs.existsSync(binPath)) {
6706
6734
  return await ctx.commands.node([binPath, ...cmdArgs], ctx);
6707
6735
  }
6708
- return await ctx.shell.execute(cmd + (cmdArgs.length ? ' ' + cmdArgs.join(' ') : ''));
6736
+ const cmdStr = [cmd, ...cmdArgs].map(quoteShellArg).join(' ');
6737
+ return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
6709
6738
  },
6710
6739
 
6711
6740
  async bunx(args, ctx) {
@@ -6776,7 +6805,8 @@ var CodeLabLogger = (() => {
6776
6805
  if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
6777
6806
  const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
6778
6807
  if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
6779
- return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
6808
+ const cmdStr = [cmd, ...args.slice(2)].map(quoteShellArg).join(' ');
6809
+ return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
6780
6810
  }
6781
6811
 
6782
6812
  if (sub === 'dlx') {
@@ -7959,18 +7989,27 @@ var CodeLabLogger = (() => {
7959
7989
  if (item.background) {
7960
7990
  const pid = this.nextPid++;
7961
7991
  const jobId = this.nextJobId++;
7992
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
7962
7993
  const job = {
7963
7994
  id: jobId,
7964
7995
  pid,
7965
7996
  command: trimmed,
7966
7997
  status: 'Running',
7967
- startTime: Date.now()
7998
+ startTime: Date.now(),
7999
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
7968
8000
  };
7969
8001
  this.jobs.set(jobId, job);
7970
8002
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
7971
8003
 
7972
- // Run in background promise
7973
- this._executeAstNode(item.node, { ...execOptions, env: Object.assign({}, this.env, currentEnv), cwd: this.cwd, pid, isBackground: true })
8004
+ // Run in background promise with its own independent AbortSignal
8005
+ this._executeAstNode(item.node, {
8006
+ ...execOptions,
8007
+ signal: jobAbortCtrl ? jobAbortCtrl.signal : undefined,
8008
+ env: Object.assign({}, this.env, currentEnv),
8009
+ cwd: this.cwd,
8010
+ pid,
8011
+ isBackground: true
8012
+ })
7974
8013
  .then(res => {
7975
8014
  if (job.status !== 'Terminated') {
7976
8015
  job.status = 'Done';
@@ -8124,17 +8163,24 @@ var CodeLabLogger = (() => {
8124
8163
  if (item.background) {
8125
8164
  const pid = this.nextPid++;
8126
8165
  const jobId = this.nextJobId++;
8166
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
8127
8167
  const job = {
8128
8168
  id: jobId,
8129
8169
  pid,
8130
8170
  command: 'background',
8131
8171
  status: 'Running',
8132
- startTime: Date.now()
8172
+ startTime: Date.now(),
8173
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
8133
8174
  };
8134
8175
  this.jobs.set(jobId, job);
8135
8176
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
8136
8177
 
8137
- this._executeAstNode(item.node, { ...context, pid, isBackground: true })
8178
+ this._executeAstNode(item.node, {
8179
+ ...context,
8180
+ signal: jobAbortCtrl ? jobAbortCtrl.signal : undefined,
8181
+ pid,
8182
+ isBackground: true
8183
+ })
8138
8184
  .then(res => {
8139
8185
  if (job.status !== 'Terminated') {
8140
8186
  job.status = 'Done';
@@ -8250,7 +8296,11 @@ var CodeLabLogger = (() => {
8250
8296
  wordItems.push(...(innerCtx.positionalArgs || []));
8251
8297
  }
8252
8298
 
8299
+ let loopIter = 0;
8253
8300
  for (const val of wordItems) {
8301
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
8302
+ await new Promise((r) => setTimeout(r, 0));
8303
+ }
8254
8304
  if (innerCtx.signal && innerCtx.signal.aborted) {
8255
8305
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
8256
8306
  }
@@ -8295,7 +8345,11 @@ var CodeLabLogger = (() => {
8295
8345
  let combinedStderr = '';
8296
8346
  let lastCode = 0;
8297
8347
 
8348
+ let loopIter = 0;
8298
8349
  while (true) {
8350
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
8351
+ await new Promise((r) => setTimeout(r, 0));
8352
+ }
8299
8353
  if (innerCtx.signal && innerCtx.signal.aborted) {
8300
8354
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
8301
8355
  }
@@ -8762,7 +8816,9 @@ var CodeLabLogger = (() => {
8762
8816
 
8763
8817
  // Route any remaining unstreamed output
8764
8818
  if (res.stdout) {
8765
- if (streamedStdoutBytes > 0) {
8819
+ if (res.alreadyStreamed) {
8820
+ stdoutOut = res.stdout;
8821
+ } else if (streamedStdoutBytes > 0) {
8766
8822
  if (res.stdout.length > streamedStdoutBytes) {
8767
8823
  routeOutput(fd1, res.stdout.slice(streamedStdoutBytes), true);
8768
8824
  }