@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
@@ -5068,68 +5068,73 @@ assert_false = ASSERT_FALSE
5068
5068
  if (this.pyodide) return this.pyodide;
5069
5069
  if (this._loadingPromise) return this._loadingPromise;
5070
5070
  this._loadingPromise = (async () => {
5071
- this._emitProgress({
5072
- stage: "downloading",
5073
- percent: 10,
5074
- message: "Initializing CPython 3.12 WebAssembly (Pyodide)..."
5075
- });
5076
- if (typeof window !== "undefined") {
5077
- const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
5078
- if (!window.loadPyodide) {
5079
- await new Promise((resolve, reject) => {
5080
- const script = document.createElement("script");
5081
- script.src = `${cdn.replace(/\/+$/, "")}/pyodide.js`;
5082
- script.onload = () => resolve();
5083
- script.onerror = () => reject(new Error(`Failed to load pyodide.js from ${script.src}`));
5084
- document.head.appendChild(script);
5085
- });
5086
- }
5071
+ try {
5087
5072
  this._emitProgress({
5088
- stage: "extracting",
5089
- percent: 50,
5090
- message: "Bootstrapping Python runtime environment..."
5073
+ stage: "downloading",
5074
+ percent: 10,
5075
+ message: "Initializing CPython 3.12 WebAssembly (Pyodide)..."
5091
5076
  });
5092
- const loadPyodideFn = window.loadPyodide;
5093
- this.pyodide = await loadPyodideFn({
5094
- indexURL: cdn
5095
- });
5096
- } else {
5097
- this.pyodide = {
5098
- FS: {
5099
- files: /* @__PURE__ */ new Map(),
5100
- writeFile(p, content) {
5101
- this.files.set(p, typeof content === "string" ? content : String(content));
5102
- },
5103
- readFile(p, opts) {
5104
- return this.files.get(p) || "";
5105
- },
5106
- unlink(p) {
5107
- this.files.delete(p);
5077
+ if (typeof window !== "undefined") {
5078
+ const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
5079
+ if (!window.loadPyodide) {
5080
+ await new Promise((resolve, reject) => {
5081
+ const script = document.createElement("script");
5082
+ script.src = `${cdn.replace(/\/+$/, "")}/pyodide.js`;
5083
+ script.onload = () => resolve();
5084
+ script.onerror = () => reject(new Error(`Failed to load pyodide.js from ${script.src}`));
5085
+ document.head.appendChild(script);
5086
+ });
5087
+ }
5088
+ this._emitProgress({
5089
+ stage: "extracting",
5090
+ percent: 50,
5091
+ message: "Bootstrapping Python runtime environment..."
5092
+ });
5093
+ const loadPyodideFn = window.loadPyodide;
5094
+ this.pyodide = await loadPyodideFn({
5095
+ indexURL: cdn
5096
+ });
5097
+ } else {
5098
+ this.pyodide = {
5099
+ FS: {
5100
+ files: /* @__PURE__ */ new Map(),
5101
+ writeFile(p, content) {
5102
+ this.files.set(p, typeof content === "string" ? content : String(content));
5103
+ },
5104
+ readFile(p, opts) {
5105
+ return this.files.get(p) || "";
5106
+ },
5107
+ unlink(p) {
5108
+ this.files.delete(p);
5109
+ },
5110
+ mkdirTree(_p) {
5111
+ }
5108
5112
  },
5109
- mkdirTree(_p) {
5113
+ runPythonAsync: async (code) => {
5114
+ return `Execution mock: ${code.slice(0, 30)}`;
5110
5115
  }
5111
- },
5112
- runPythonAsync: async (code) => {
5113
- return `Execution mock: ${code.slice(0, 30)}`;
5114
- }
5115
- };
5116
- }
5117
- if (this.options.preloadPackages && Array.isArray(this.options.preloadPackages)) {
5118
- for (const pkg of this.options.preloadPackages) {
5119
- try {
5120
- if (typeof this.pyodide.loadPackage === "function") {
5121
- await this.pyodide.loadPackage(pkg);
5116
+ };
5117
+ }
5118
+ if (this.options.preloadPackages && Array.isArray(this.options.preloadPackages)) {
5119
+ for (const pkg of this.options.preloadPackages) {
5120
+ try {
5121
+ if (typeof this.pyodide.loadPackage === "function") {
5122
+ await this.pyodide.loadPackage(pkg);
5123
+ }
5124
+ } catch (err) {
5122
5125
  }
5123
- } catch (err) {
5124
5126
  }
5125
5127
  }
5128
+ this._emitProgress({
5129
+ stage: "ready",
5130
+ percent: 100,
5131
+ message: "Python 3.12 WebAssembly Toolchain Ready"
5132
+ });
5133
+ return this.pyodide;
5134
+ } catch (err) {
5135
+ this._loadingPromise = null;
5136
+ throw err;
5126
5137
  }
5127
- this._emitProgress({
5128
- stage: "ready",
5129
- percent: 100,
5130
- message: "Python 3.12 WebAssembly Toolchain Ready"
5131
- });
5132
- return this.pyodide;
5133
5138
  })();
5134
5139
  return this._loadingPromise;
5135
5140
  }
@@ -5173,18 +5178,34 @@ assert_false = ASSERT_FALSE
5173
5178
  };
5174
5179
  const pyodide = await this.ensureLoaded();
5175
5180
  if (req.vfs && pyodide.FS) {
5176
- try {
5177
- const vfsEntries = req.vfs.readdirSync("/workspace", { recursive: true });
5178
- for (const entry of vfsEntries) {
5179
- const fullPath = `/workspace/${entry}`;
5180
- if (!req.vfs.statSync(fullPath).isDirectory()) {
5181
- const content = req.vfs.readFileSync(fullPath, "utf8");
5182
- pyodide.FS.mkdirTree("/workspace");
5183
- pyodide.FS.writeFile(fullPath, content);
5181
+ const syncVfsDir = (dirPath) => {
5182
+ try {
5183
+ if (typeof pyodide.FS.mkdirTree === "function") {
5184
+ pyodide.FS.mkdirTree(dirPath);
5184
5185
  }
5186
+ const entries = req.vfs.readdirSync(dirPath);
5187
+ for (const entry of entries) {
5188
+ if (!entry || entry === "." || entry === "..") continue;
5189
+ const fullPath = `${dirPath === "/" ? "" : dirPath}/${entry}`;
5190
+ try {
5191
+ const st = req.vfs.statSync(fullPath);
5192
+ if (st && typeof st.isDirectory === "function" && st.isDirectory()) {
5193
+ syncVfsDir(fullPath);
5194
+ } else {
5195
+ const parentDir = fullPath.slice(0, fullPath.lastIndexOf("/")) || "/workspace";
5196
+ if (typeof pyodide.FS.mkdirTree === "function") {
5197
+ pyodide.FS.mkdirTree(parentDir);
5198
+ }
5199
+ const content = req.vfs.readFileSync(fullPath, "utf8");
5200
+ pyodide.FS.writeFile(fullPath, content);
5201
+ }
5202
+ } catch (err) {
5203
+ }
5204
+ }
5205
+ } catch (err) {
5185
5206
  }
5186
- } catch (err) {
5187
- }
5207
+ };
5208
+ syncVfsDir("/workspace");
5188
5209
  }
5189
5210
  if (pyodide.FS) {
5190
5211
  try {
@@ -5230,45 +5251,19 @@ assert_false = ASSERT_FALSE
5230
5251
  }
5231
5252
  });
5232
5253
  }
5233
- const rawLines = codeToRun.split("\n");
5234
- const futureImports = [];
5235
- const bodyLines = [];
5236
- let inDocstring = false;
5237
- let docChar = "";
5238
- for (const l of rawLines) {
5239
- const t = l.trim();
5240
- if (!inDocstring && (t.startsWith('"""') || t.startsWith("'''"))) {
5241
- if (t.length > 3 && (t.endsWith('"""') || t.endsWith("'''"))) {
5242
- bodyLines.push(l);
5243
- continue;
5244
- }
5245
- inDocstring = true;
5246
- docChar = t.slice(0, 3);
5247
- bodyLines.push(l);
5248
- continue;
5249
- }
5250
- if (inDocstring) {
5251
- if (t.endsWith(docChar)) inDocstring = false;
5252
- bodyLines.push(l);
5253
- continue;
5254
- }
5255
- if (/^from\s+__future__\s+import\s+/.test(t)) {
5256
- futureImports.push(t);
5257
- } else {
5258
- bodyLines.push(l);
5259
- }
5260
- }
5254
+ const fileLabel = JSON.stringify(req.entry || "<exec>");
5255
+ const encodedCode = JSON.stringify(codeToRun);
5261
5256
  const runnerWrapper = `
5262
- ${futureImports.join("\n")}
5263
5257
  import sys, tracemalloc
5264
5258
  if '/usr/lib/python' not in sys.path:
5265
5259
  sys.path.insert(0, '/usr/lib/python')
5266
5260
  if '/workspace' not in sys.path:
5267
5261
  sys.path.insert(0, '/workspace')
5268
5262
 
5263
+ _cl_user_code = ${encodedCode}
5269
5264
  tracemalloc.start()
5270
5265
  try:
5271
- ${bodyLines.map((l) => " " + l).join("\n")}
5266
+ exec(compile(_cl_user_code, ${fileLabel}, 'exec'), globals())
5272
5267
  finally:
5273
5268
  _, _peak = tracemalloc.get_traced_memory()
5274
5269
  tracemalloc.stop()
@@ -5311,20 +5306,38 @@ finally:
5311
5306
  }
5312
5307
  }
5313
5308
  if (req.vfs && pyodide.FS && typeof pyodide.FS.readdir === "function") {
5314
- try {
5315
- const files = pyodide.FS.readdir("/workspace");
5316
- for (const f of files) {
5317
- if (f !== "." && f !== "..") {
5318
- const p = `/workspace/${f}`;
5309
+ const syncBackPyodideDir = (dirPath) => {
5310
+ try {
5311
+ const entries = pyodide.FS.readdir(dirPath);
5312
+ for (const f of entries) {
5313
+ if (!f || f === "." || f === "..") continue;
5314
+ const p = `${dirPath}/${f}`;
5319
5315
  try {
5320
- const content = pyodide.FS.readFile(p, { encoding: "utf8" });
5321
- req.vfs.writeFileSync(p, content);
5316
+ let isDir = false;
5317
+ if (typeof pyodide.FS.stat === "function" && typeof pyodide.FS.isDir === "function") {
5318
+ const st = pyodide.FS.stat(p);
5319
+ isDir = Boolean(pyodide.FS.isDir(st.mode));
5320
+ }
5321
+ if (isDir) {
5322
+ if (typeof req.vfs.mkdirSync === "function" && !req.vfs.existsSync(p)) {
5323
+ req.vfs.mkdirSync(p, { recursive: true });
5324
+ }
5325
+ syncBackPyodideDir(p);
5326
+ } else {
5327
+ const parentDir = p.slice(0, p.lastIndexOf("/")) || "/workspace";
5328
+ if (typeof req.vfs.mkdirSync === "function" && !req.vfs.existsSync(parentDir)) {
5329
+ req.vfs.mkdirSync(parentDir, { recursive: true });
5330
+ }
5331
+ const content = pyodide.FS.readFile(p, { encoding: "utf8" });
5332
+ req.vfs.writeFileSync(p, content);
5333
+ }
5322
5334
  } catch (err) {
5323
5335
  }
5324
5336
  }
5337
+ } catch (err) {
5325
5338
  }
5326
- } catch (err) {
5327
- }
5339
+ };
5340
+ syncBackPyodideDir("/workspace");
5328
5341
  }
5329
5342
  const durationMs = performance.now() - start;
5330
5343
  return {
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @innovatorved/code-lab v0.3.1
2
+ * @innovatorved/code-lab v0.3.2
3
3
  * Browser-native IDE, POSIX Shell, Web Worker Node.js/Bun Runtime, WASI C++20 Toolchain, Python 3.12 WebAssembly, and Git Engine.
4
4
  */
5
5
  export * from './schemas';
@@ -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
@@ -160,7 +160,12 @@ var CodeLabCsp = (() => {
160
160
  directive("worker-src", [self, "blob:"].concat(sourcesFor(mode, allow, "workerSrc"))),
161
161
  directive("frame-src", withData("frameSrc")),
162
162
  directive("form-action", [self]),
163
- directive("frame-ancestors", [options.frameAncestors || "'self'"])
163
+ directive("frame-ancestors", (() => {
164
+ const rawFa = typeof options.frameAncestors === "string" ? options.frameAncestors.trim() : "";
165
+ if (!rawFa) return ["'self'"];
166
+ const tokens = cleanSources(rawFa.split(/\s+/));
167
+ return tokens.length > 0 ? tokens : ["'self'"];
168
+ })())
164
169
  ].join("; ");
165
170
  }
166
171
  function describePreviewNetwork(config) {
@@ -198,15 +203,6 @@ var CodeLabCsp = (() => {
198
203
  };
199
204
  }
200
205
  function shim(name) {
201
- var blocked = false;
202
- try {
203
- var existing = window[name];
204
- if (existing) { existing.getItem('__codelab_probe__'); return; }
205
- } catch (err) {
206
- // Expected on an opaque origin: the accessor itself throws.
207
- blocked = Boolean(err);
208
- }
209
- void blocked;
210
206
  try {
211
207
  Object.defineProperty(window, name, { configurable: true, value: memoryStorage() });
212
208
  } catch (err) {
@@ -366,6 +362,7 @@ var CodeLabCsp = (() => {
366
362
  }
367
363
 
368
364
  window.addEventListener('message', function (event) {
365
+ if (event && event.source && event.source !== window.parent) return;
369
366
  var data = event && event.data;
370
367
  if (!data || typeof data !== 'object') return;
371
368
  if (data.type === 'codelab:preview-fetch-res' && data.reqId) {
@@ -578,6 +575,8 @@ self.addEventListener('activate', (event) => {
578
575
  self.addEventListener('message', (event) => {
579
576
  const data = event && event.data;
580
577
  if (!data || data.type !== 'codelab:config') return;
578
+ // Reject configuration attempts originating from preview tabs/frames themselves.
579
+ if (event.source && event.source.url && /\/__preview\//.test(event.source.url)) return;
581
580
  const csp = typeof data.csp === 'string' ? data.csp.trim() : '';
582
581
  if (!csp || csp.length > MAX_CONFIG_LENGTH) return;
583
582
  configuredCsp = csp;
@@ -600,10 +599,15 @@ function parsePreviewPath(pathname) {
600
599
  return { port: Number(match[1]), path: match[2] || '/' };
601
600
  }
602
601
 
602
+ function escapeMetaAttr(val) {
603
+ return String(val || '').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
604
+ }
605
+
603
606
  function previewErrorResponse(status, title, message) {
604
607
  const csp = previewPolicy();
608
+ const safeCsp = escapeMetaAttr(csp);
605
609
  const body = `<!doctype html><meta charset="utf-8">` +
606
- `<meta http-equiv="Content-Security-Policy" content="${csp}">` +
610
+ `<meta http-equiv="Content-Security-Policy" content="${safeCsp}">` +
607
611
  `<title>${title}</title>` +
608
612
  `<body style="font-family:system-ui,-apple-system,sans-serif;padding:32px;color:#666;background:#0a0a0a">` +
609
613
  `<h1 style="color:#e5e5e5;font-size:18px">${title}</h1><p>${message}</p></body>`;
@@ -620,14 +624,15 @@ function previewErrorResponse(status, title, message) {
620
624
  /** Inject the policy, a base URL and the sandbox shims into an HTML response. */
621
625
  function injectPreviewHead(html, port) {
622
626
  const csp = previewPolicy();
627
+ const safeCsp = escapeMetaAttr(csp);
623
628
  const shims = previewShims();
624
629
  const tags = [];
625
630
  const hasCsp = /<meta[^>]+http-equiv=["']?content-security-policy/i.test(html);
626
631
  const hasBase = /<base\b/i.test(html);
627
632
  const hasShims = html.indexOf('data-codelab-preview-shims') !== -1;
628
633
 
629
- if (!hasCsp) tags.push(`<meta http-equiv="Content-Security-Policy" content="${csp}">`);
630
- if (!hasBase) tags.push(`<base href="${PREVIEW_PREFIX}${port}/">`);
634
+ if (!hasCsp) tags.push(`<meta http-equiv="Content-Security-Policy" content="${safeCsp}">`);
635
+ if (!hasBase) tags.push(`<base href="${PREVIEW_PREFIX}${Number(port) || 3000}/">`);
631
636
  if (!hasShims && shims) tags.push(shims);
632
637
  if (tags.length === 0) return html;
633
638
 
@@ -643,7 +648,8 @@ function injectPreviewHead(html, port) {
643
648
 
644
649
  async function proxyVirtualRequest(event, port, targetPath) {
645
650
  const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
646
- if (!clients || !clients.length) {
651
+ const workbenchClients = (clients || []).filter((c) => !c.url || !/\/__preview\//.test(c.url));
652
+ if (!workbenchClients.length) {
647
653
  return previewErrorResponse(
648
654
  503,
649
655
  'No active CodeLab workbench',
@@ -651,7 +657,7 @@ async function proxyVirtualRequest(event, port, targetPath) {
651
657
  );
652
658
  }
653
659
 
654
- const client = clients[0];
660
+ const client = workbenchClients[0];
655
661
  const channel = new MessageChannel();
656
662
  const request = event.request;
657
663
  const method = request.method || 'GET';
@@ -707,6 +713,17 @@ async function proxyVirtualRequest(event, port, targetPath) {
707
713
  const responseHeaders = new Headers((response && response.headers) || {});
708
714
  const contentType = responseHeaders.get('content-type') || '';
709
715
 
716
+ // Decode Uint8Array / ArrayBuffer HTML bodies so head injection always applies.
717
+ if (/text\/html/i.test(contentType) && responseBody && typeof responseBody !== 'string') {
718
+ try {
719
+ if (responseBody instanceof ArrayBuffer || ArrayBuffer.isView(responseBody)) {
720
+ responseBody = new TextDecoder('utf-8').decode(responseBody);
721
+ }
722
+ } catch (err) {
723
+ console.warn('[code-lab] preview-sw: failed to decode HTML buffer', err);
724
+ }
725
+ }
726
+
710
727
  // Inject the policy and a <base> so relative asset URLs in HTML responses
711
728
  // resolve under the `/__preview/:port/` namespace rather than the host root.
712
729
  if (/text\/html/i.test(contentType) && typeof responseBody === 'string') {
@@ -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
@@ -1134,22 +1134,40 @@ function __initVirtualRuntime(rootScope) {
1134
1134
  // =========================================================================
1135
1135
  // 5. VIRTUAL IN-MEMORY POSIX FILESYSTEM (node:fs)
1136
1136
  // =========================================================================
1137
- function createVirtualFs(initialFiles = {}) {
1137
+ function createVirtualFs(initialFiles = {}, vfsOptions = {}) {
1138
1138
  const dirs = new Set(['/', '/tmp', '/workspace', '/home', '/home/user']);
1139
1139
  const files = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, ctimeMs, ino }
1140
1140
  const deletedInspectorCache = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, deletedAtMs }
1141
+ const MAX_DELETED_CACHE_ENTRIES = 50;
1142
+ const MAX_DELETED_CACHE_FILE_BYTES = 65536;
1143
+ const customCwdGetter = typeof vfsOptions === 'function'
1144
+ ? vfsOptions
1145
+ : (vfsOptions && typeof vfsOptions.cwdGetter === 'function' ? vfsOptions.cwdGetter : null);
1141
1146
  const fdTable = new Map(); // fd -> { inode, path, flags, pos, isDirectory }
1142
1147
  let nextFd = 10;
1143
1148
  let nextIno = 100;
1144
1149
  let mkdtempCounter = 1;
1145
1150
 
1151
+ function recordDeletedForInspector(p, data, mtimeMs) {
1152
+ if (!data || data.byteLength <= 0 || data.byteLength > MAX_DELETED_CACHE_FILE_BYTES) return;
1153
+ if (deletedInspectorCache.has(p)) {
1154
+ deletedInspectorCache.delete(p);
1155
+ } else if (deletedInspectorCache.size >= MAX_DELETED_CACHE_ENTRIES) {
1156
+ const oldestKey = deletedInspectorCache.keys().next().value;
1157
+ if (oldestKey !== undefined) deletedInspectorCache.delete(oldestKey);
1158
+ }
1159
+ deletedInspectorCache.set(p, { data: data.slice(), mtimeMs, deletedAtMs: Date.now() });
1160
+ }
1161
+
1146
1162
  function normPath(p) {
1147
1163
  if (typeof p !== 'string' || !p) {
1148
1164
  const err = new TypeError('path must be a non-empty string');
1149
1165
  err.code = 'ERR_INVALID_ARG_TYPE';
1150
1166
  throw err;
1151
1167
  }
1152
- const baseCwd = typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace';
1168
+ const baseCwd = typeof customCwdGetter === 'function'
1169
+ ? customCwdGetter()
1170
+ : (typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace');
1153
1171
  const abs = p.startsWith('/') ? VirtualPath.normalize(p) : VirtualPath.resolve(baseCwd, p);
1154
1172
  return abs.length > 1 && abs.endsWith('/') ? abs.slice(0, -1) : abs;
1155
1173
  }
@@ -1200,9 +1218,13 @@ function __initVirtualRuntime(rootScope) {
1200
1218
  for (const [relPath, content] of Object.entries(initialFiles)) {
1201
1219
  const cleanRel = relPath.startsWith('/') ? relPath.slice(1) : relPath;
1202
1220
  const isSystemPath = /^\/(workspace|usr|tmp|lib|include|etc|bin|dev)(\/|$)/.test(relPath);
1203
- const fullPath = isSystemPath
1221
+ let fullPath = isSystemPath
1204
1222
  ? normPath(relPath)
1205
1223
  : normPath(`/workspace/${cleanRel}`);
1224
+ if (!isSystemPath && fullPath !== '/workspace' && !fullPath.startsWith('/workspace/')) {
1225
+ const safeSub = cleanRel.split('/').filter((seg) => seg && seg !== '.' && seg !== '..').join('/');
1226
+ fullPath = normPath(`/workspace/${safeSub || 'file'}`);
1227
+ }
1206
1228
  ensureParentDirs(fullPath);
1207
1229
  const bytes = typeof content === 'string' ? utf8Encode(content) : new Uint8Array(content);
1208
1230
  files.set(fullPath, {
@@ -1382,13 +1404,6 @@ function __initVirtualRuntime(rootScope) {
1382
1404
  fsyncSync(fd) {
1383
1405
  const entry = fdTable.get(fd);
1384
1406
  if (!entry) throw fsError('EBADF', 'fsync', String(fd), 'bad file descriptor');
1385
- if (!entry.isDirectory && entry.inode) {
1386
- deletedInspectorCache.set(entry.path, {
1387
- data: entry.inode.data.slice(),
1388
- mtimeMs: entry.inode.mtimeMs,
1389
- deletedAtMs: null
1390
- });
1391
- }
1392
1407
  },
1393
1408
 
1394
1409
  fdatasyncSync(fd) {
@@ -1429,12 +1444,6 @@ function __initVirtualRuntime(rootScope) {
1429
1444
  inode.mtimeMs = Date.now();
1430
1445
  entry.pos = writePos + chunk.byteLength;
1431
1446
 
1432
- deletedInspectorCache.set(entry.path, {
1433
- data: inode.data.slice(),
1434
- mtimeMs: inode.mtimeMs,
1435
- deletedAtMs: null
1436
- });
1437
-
1438
1447
  return chunk.byteLength;
1439
1448
  },
1440
1449
 
@@ -1486,7 +1495,7 @@ function __initVirtualRuntime(rootScope) {
1486
1495
  inode.mode = 0o100000 | (Number(opts.mode) & 0o777);
1487
1496
  }
1488
1497
  }
1489
- deletedInspectorCache.set(np, { data: bytes.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1498
+ deletedInspectorCache.delete(np);
1490
1499
  },
1491
1500
 
1492
1501
  chmodSync(p, mode) {
@@ -1515,7 +1524,7 @@ function __initVirtualRuntime(rootScope) {
1515
1524
  combined.set(chunk, inode.data.byteLength);
1516
1525
  inode.data = combined;
1517
1526
  inode.mtimeMs = Date.now();
1518
- deletedInspectorCache.set(np, { data: combined.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1527
+ deletedInspectorCache.delete(np);
1519
1528
  },
1520
1529
 
1521
1530
  truncateSync(p, len = 0) {
@@ -1531,7 +1540,6 @@ function __initVirtualRuntime(rootScope) {
1531
1540
  inode.data = grown;
1532
1541
  }
1533
1542
  inode.mtimeMs = Date.now();
1534
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1535
1543
  },
1536
1544
 
1537
1545
  renameSync(oldP, newP) {
@@ -1592,16 +1600,14 @@ function __initVirtualRuntime(rootScope) {
1592
1600
  if (fdEntry.path === src) fdEntry.path = dst;
1593
1601
  }
1594
1602
  deletedInspectorCache.delete(src);
1595
- deletedInspectorCache.set(dst, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1603
+ deletedInspectorCache.delete(dst);
1596
1604
  },
1597
1605
 
1598
1606
  unlinkSync(p) {
1599
1607
  const np = normPath(p);
1600
1608
  const inode = files.get(np);
1601
1609
  if (!inode) throw fsError('ENOENT', 'unlink', p, 'no such file or directory');
1602
- if (inode.data.byteLength > 0) {
1603
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
1604
- }
1610
+ recordDeletedForInspector(np, inode.data, inode.mtimeMs);
1605
1611
  files.delete(np);
1606
1612
  },
1607
1613
 
@@ -1618,9 +1624,7 @@ function __initVirtualRuntime(rootScope) {
1618
1624
  for (const [fPath, inode] of Array.from(files.entries())) {
1619
1625
  if (fPath.startsWith(prefix)) {
1620
1626
  if (!recursive) throw fsError('ENOTEMPTY', 'rm', p, 'directory not empty');
1621
- if (inode.data.byteLength > 0) {
1622
- deletedInspectorCache.set(fPath, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
1623
- }
1627
+ recordDeletedForInspector(fPath, inode.data, inode.mtimeMs);
1624
1628
  files.delete(fPath);
1625
1629
  }
1626
1630
  }
@@ -3194,6 +3198,7 @@ function __initVirtualRuntime(rootScope) {
3194
3198
  responseHeaders: {},
3195
3199
  _t0: performance.now()
3196
3200
  };
3201
+ if (httpTrace.length >= 500) httpTrace.shift();
3197
3202
  httpTrace.push(traceEntry);
3198
3203
  this._traceEntry = traceEntry;
3199
3204
 
@@ -4185,6 +4190,7 @@ function __initVirtualRuntime(rootScope) {
4185
4190
  this._peer = serverSocket;
4186
4191
  this.connecting = false;
4187
4192
 
4193
+ if (sharedTrace.length >= 500) sharedTrace.shift();
4188
4194
  sharedTrace.push({
4189
4195
  protocol: 'TCP',
4190
4196
  event: 'connect',
@@ -6477,7 +6483,10 @@ function __initVirtualRuntime(rootScope) {
6477
6483
  const activePortTable = optPortTable || portTable || _defaultPortTable;
6478
6484
  resourceTracker.pid = pid;
6479
6485
 
6480
- const vfs = optVfs || createVirtualFs(files);
6486
+ let currentCwd = '/workspace';
6487
+ _activeCwdGetter = () => currentCwd;
6488
+
6489
+ const vfs = optVfs || createVirtualFs(files, { cwdGetter: () => currentCwd });
6481
6490
  if (optVfs && files && typeof files === 'object') {
6482
6491
  for (const [fPath, content] of Object.entries(files)) {
6483
6492
  const abs = fPath.startsWith('/') ? fPath : '/workspace/' + fPath;
@@ -6871,8 +6880,6 @@ function __initVirtualRuntime(rootScope) {
6871
6880
  hrtimeFn.bigint = () => BigInt(Math.round(performance.now() * 1e6));
6872
6881
 
6873
6882
  let syncExecDepth = 0;
6874
- let currentCwd = '/workspace';
6875
- _activeCwdGetter = () => currentCwd;
6876
6883
 
6877
6884
  const sandboxProcess = Object.assign(new EventEmitter(), {
6878
6885
  env: { NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' },