@innovatorved/code-lab 0.3.0 → 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 (57) hide show
  1. package/ARCHITECTURE.md +4 -2
  2. package/CHANGELOG.md +38 -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 +1533 -396
  7. package/dist/code-lab.js +1532 -395
  8. package/dist/diagnostics.d.ts +5 -0
  9. package/dist/extensions/cpp.d.ts +8 -0
  10. package/dist/extensions/cpp.esm.js +333 -10
  11. package/dist/extensions/cpp.js +333 -10
  12. package/dist/extensions/guided-lab.esm.js +1 -1
  13. package/dist/extensions/guided-lab.js +1 -1
  14. package/dist/extensions/python.esm.js +117 -104
  15. package/dist/extensions/python.js +117 -104
  16. package/dist/index.d.ts +1 -1
  17. package/dist/preview-sw.js +34 -17
  18. package/dist/runtime.esm.js +38 -31
  19. package/dist/runtime.js +38 -31
  20. package/dist/schemas.d.ts +4 -4
  21. package/dist/schemas.esm.js +1 -1
  22. package/dist/schemas.js +1 -1
  23. package/dist/scm.d.ts +13 -2
  24. package/dist/search.d.ts +5 -1
  25. package/dist/shell.esm.js +72 -16
  26. package/dist/shell.js +72 -16
  27. package/dist/terminal.esm.js +183 -54
  28. package/dist/terminal.js +183 -54
  29. package/dist/workbench/index.d.ts +1 -1
  30. package/dist/workbench/styles.d.ts +1 -1
  31. package/dist/zip.d.ts +4 -3
  32. package/package.json +1 -1
  33. package/src/code-lab.css +52 -2
  34. package/src/csp.ts +7 -10
  35. package/src/diagnostics.ts +42 -3
  36. package/src/extensions/cpp.ts +303 -9
  37. package/src/extensions/python.ts +128 -116
  38. package/src/index.ts +1 -1
  39. package/src/preview-sw.js +25 -5
  40. package/src/runtime.ts +36 -29
  41. package/src/schemas.ts +2 -2
  42. package/src/scm.ts +106 -19
  43. package/src/search.ts +71 -27
  44. package/src/shell.ts +70 -14
  45. package/src/terminal.ts +181 -52
  46. package/src/workbench/diff-editor.ts +41 -13
  47. package/src/workbench/drawer.ts +17 -8
  48. package/src/workbench/guided-pane.ts +12 -2
  49. package/src/workbench/share.ts +37 -8
  50. package/src/workbench/styles.ts +2 -1
  51. package/src/workbench/toolbar.ts +15 -4
  52. package/src/workbench.ts +484 -91
  53. package/src/zip.ts +29 -7
  54. package/dist/runtime/module-loader.d.ts +0 -11
  55. package/dist/runtime/vfs.d.ts +0 -31
  56. package/dist/runtime/wasi-host.d.ts +0 -33
  57. package/dist/shell/lexer-parser.d.ts +0 -26
package/dist/shell.esm.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.3.0 — 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
  }
package/dist/shell.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.3.0 — 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
@@ -3022,6 +3022,13 @@ var CodeLabLogger = (() => {
3022
3022
  return out;
3023
3023
  }
3024
3024
 
3025
+ function quoteShellArg(arg) {
3026
+ const s = String(arg ?? '');
3027
+ if (s.length === 0) return "''";
3028
+ if (!/[\s"'\\$&|;<>()`!*?~#]/.test(s)) return s;
3029
+ return "'" + s.replace(/'/g, "'\\''") + "'";
3030
+ }
3031
+
3025
3032
  async function runPackageScript(scriptName, scriptArgs, ctx) {
3026
3033
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
3027
3034
  if (!pkgData.scripts || !pkgData.scripts[scriptName]) {
@@ -3029,7 +3036,7 @@ var CodeLabLogger = (() => {
3029
3036
  }
3030
3037
  let cmd = pkgData.scripts[scriptName];
3031
3038
  if (scriptArgs && scriptArgs.length > 0) {
3032
- cmd += ' ' + scriptArgs.join(' ');
3039
+ cmd += ' ' + scriptArgs.map(quoteShellArg).join(' ');
3033
3040
  }
3034
3041
  const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
3035
3042
  if (fallback) return fallback;
@@ -3282,6 +3289,11 @@ var CodeLabLogger = (() => {
3282
3289
  const isFile = (p) => exists(p) && !isDir(p);
3283
3290
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
3284
3291
 
3292
+ const isWithinRoot = (p) => {
3293
+ const rootPrefix = rootDir === '/' ? '/' : rootDir + '/';
3294
+ return p === rootDir || p.startsWith(rootPrefix);
3295
+ };
3296
+
3285
3297
  const resolveLocalTarget = (baseDir, rawSpec) => {
3286
3298
  if (!rawSpec || typeof rawSpec !== 'string') return null;
3287
3299
  const clean = rawSpec.split(/[?#]/)[0].trim();
@@ -3289,6 +3301,7 @@ var CodeLabLogger = (() => {
3289
3301
  const candidateBase = clean.startsWith('/')
3290
3302
  ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
3291
3303
  : PosixPath.join(baseDir, clean);
3304
+ if (!isWithinRoot(candidateBase)) return null;
3292
3305
  if (isFile(candidateBase)) return candidateBase;
3293
3306
  const cands = [
3294
3307
  candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
@@ -3297,7 +3310,7 @@ var CodeLabLogger = (() => {
3297
3310
  PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
3298
3311
  ];
3299
3312
  for (const c of cands) {
3300
- if (isFile(c)) return c;
3313
+ if (isWithinRoot(c) && isFile(c)) return c;
3301
3314
  }
3302
3315
  return null;
3303
3316
  };
@@ -3426,7 +3439,7 @@ var CodeLabLogger = (() => {
3426
3439
  if (/@import\s+['"]tailwindcss['"]/i.test(cssContent)) {
3427
3440
  needsTailwindBrowser = true;
3428
3441
  }
3429
- const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget));
3442
+ const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget)).replace(/<\/style/gi, '<\\/style');
3430
3443
  return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${resolvedCss}\n</style>`;
3431
3444
  });
3432
3445
 
@@ -3438,7 +3451,7 @@ var CodeLabLogger = (() => {
3438
3451
  if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
3439
3452
  const rawScript = readText(scriptTarget);
3440
3453
  if (rawScript === null) return fullTag;
3441
- const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
3454
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget).replace(/<\/script/gi, '<\\/script');
3442
3455
  const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget) || /^\s*(?:import|export)\b/m.test(rawScript);
3443
3456
  const typeAttr = isMod ? ' type="module"' : '';
3444
3457
  return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
@@ -3461,6 +3474,12 @@ var CodeLabLogger = (() => {
3461
3474
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
3462
3475
  const rel = pathname.replace(/^\/+/, '');
3463
3476
  let target = PosixPath.join(rootDir, rel);
3477
+ if (!isWithinRoot(target)) {
3478
+ return new Response(
3479
+ '<!doctype html><meta charset="utf-8"><title>403</title><h1>403 Forbidden</h1>',
3480
+ { status: 403, headers: { 'content-type': 'text/html; charset=utf-8' } }
3481
+ );
3482
+ }
3464
3483
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
3465
3484
 
3466
3485
  if (!rel || pathname.endsWith('/') || isDir(target)) {
@@ -3485,8 +3504,13 @@ var CodeLabLogger = (() => {
3485
3504
  target = (!exists(rootIdx) && exists(pubIdx)) ? pubIdx : rootIdx; // SPA fallback
3486
3505
  }
3487
3506
  if (!exists(target)) {
3507
+ const safePath = String(pathname)
3508
+ .replace(/&/g, '&amp;')
3509
+ .replace(/</g, '&lt;')
3510
+ .replace(/>/g, '&gt;')
3511
+ .replace(/"/g, '&quot;');
3488
3512
  return new Response(
3489
- `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
3513
+ `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${safePath}</p>`,
3490
3514
  { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
3491
3515
  );
3492
3516
  }
@@ -5637,13 +5661,17 @@ var CodeLabLogger = (() => {
5637
5661
 
5638
5662
  const count = Math.max(1, result.filesWritten);
5639
5663
  const kb = Math.max(0.1, result.totalBytes / 1024).toFixed(1);
5664
+ if (!enumeratedEmitted) {
5665
+ streamLine(`remote: Enumerating objects: ${count}, done.\n`);
5666
+ streamLine(`remote: Counting objects: 100% (${count}/${count}), done.\n`);
5667
+ }
5640
5668
  streamLine(`Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`);
5641
5669
  const stdout =
5642
5670
  `Cloning into '${dirDisplayName}'...\n` +
5643
5671
  `remote: Enumerating objects: ${count}, done.\n` +
5644
5672
  `remote: Counting objects: 100% (${count}/${count}), done.\n` +
5645
5673
  `Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`;
5646
- return { code: 0, stdout, stderr: '' };
5674
+ return { code: 0, stdout, stderr: '', alreadyStreamed: canStream };
5647
5675
  } catch (err) {
5648
5676
  if (ctx.signal && ctx.signal.aborted) {
5649
5677
  return { code: 130, stdout: '', stderr: '', aborted: true };
@@ -6706,7 +6734,8 @@ var CodeLabLogger = (() => {
6706
6734
  if (ctx.vfs.existsSync(binPath)) {
6707
6735
  return await ctx.commands.node([binPath, ...cmdArgs], ctx);
6708
6736
  }
6709
- return await ctx.shell.execute(cmd + (cmdArgs.length ? ' ' + cmdArgs.join(' ') : ''));
6737
+ const cmdStr = [cmd, ...cmdArgs].map(quoteShellArg).join(' ');
6738
+ return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
6710
6739
  },
6711
6740
 
6712
6741
  async bunx(args, ctx) {
@@ -6777,7 +6806,8 @@ var CodeLabLogger = (() => {
6777
6806
  if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
6778
6807
  const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
6779
6808
  if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
6780
- return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
6809
+ const cmdStr = [cmd, ...args.slice(2)].map(quoteShellArg).join(' ');
6810
+ return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
6781
6811
  }
6782
6812
 
6783
6813
  if (sub === 'dlx') {
@@ -7960,18 +7990,27 @@ var CodeLabLogger = (() => {
7960
7990
  if (item.background) {
7961
7991
  const pid = this.nextPid++;
7962
7992
  const jobId = this.nextJobId++;
7993
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
7963
7994
  const job = {
7964
7995
  id: jobId,
7965
7996
  pid,
7966
7997
  command: trimmed,
7967
7998
  status: 'Running',
7968
- startTime: Date.now()
7999
+ startTime: Date.now(),
8000
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
7969
8001
  };
7970
8002
  this.jobs.set(jobId, job);
7971
8003
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
7972
8004
 
7973
- // Run in background promise
7974
- this._executeAstNode(item.node, { ...execOptions, env: Object.assign({}, this.env, currentEnv), cwd: this.cwd, pid, isBackground: true })
8005
+ // Run in background promise with its own independent AbortSignal
8006
+ this._executeAstNode(item.node, {
8007
+ ...execOptions,
8008
+ signal: jobAbortCtrl ? jobAbortCtrl.signal : undefined,
8009
+ env: Object.assign({}, this.env, currentEnv),
8010
+ cwd: this.cwd,
8011
+ pid,
8012
+ isBackground: true
8013
+ })
7975
8014
  .then(res => {
7976
8015
  if (job.status !== 'Terminated') {
7977
8016
  job.status = 'Done';
@@ -8125,17 +8164,24 @@ var CodeLabLogger = (() => {
8125
8164
  if (item.background) {
8126
8165
  const pid = this.nextPid++;
8127
8166
  const jobId = this.nextJobId++;
8167
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
8128
8168
  const job = {
8129
8169
  id: jobId,
8130
8170
  pid,
8131
8171
  command: 'background',
8132
8172
  status: 'Running',
8133
- startTime: Date.now()
8173
+ startTime: Date.now(),
8174
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
8134
8175
  };
8135
8176
  this.jobs.set(jobId, job);
8136
8177
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
8137
8178
 
8138
- this._executeAstNode(item.node, { ...context, pid, isBackground: true })
8179
+ this._executeAstNode(item.node, {
8180
+ ...context,
8181
+ signal: jobAbortCtrl ? jobAbortCtrl.signal : undefined,
8182
+ pid,
8183
+ isBackground: true
8184
+ })
8139
8185
  .then(res => {
8140
8186
  if (job.status !== 'Terminated') {
8141
8187
  job.status = 'Done';
@@ -8251,7 +8297,11 @@ var CodeLabLogger = (() => {
8251
8297
  wordItems.push(...(innerCtx.positionalArgs || []));
8252
8298
  }
8253
8299
 
8300
+ let loopIter = 0;
8254
8301
  for (const val of wordItems) {
8302
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
8303
+ await new Promise((r) => setTimeout(r, 0));
8304
+ }
8255
8305
  if (innerCtx.signal && innerCtx.signal.aborted) {
8256
8306
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
8257
8307
  }
@@ -8296,7 +8346,11 @@ var CodeLabLogger = (() => {
8296
8346
  let combinedStderr = '';
8297
8347
  let lastCode = 0;
8298
8348
 
8349
+ let loopIter = 0;
8299
8350
  while (true) {
8351
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
8352
+ await new Promise((r) => setTimeout(r, 0));
8353
+ }
8300
8354
  if (innerCtx.signal && innerCtx.signal.aborted) {
8301
8355
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
8302
8356
  }
@@ -8763,7 +8817,9 @@ var CodeLabLogger = (() => {
8763
8817
 
8764
8818
  // Route any remaining unstreamed output
8765
8819
  if (res.stdout) {
8766
- if (streamedStdoutBytes > 0) {
8820
+ if (res.alreadyStreamed) {
8821
+ stdoutOut = res.stdout;
8822
+ } else if (streamedStdoutBytes > 0) {
8767
8823
  if (res.stdout.length > streamedStdoutBytes) {
8768
8824
  routeOutput(fd1, res.stdout.slice(streamedStdoutBytes), true);
8769
8825
  }