@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
@@ -791,77 +791,82 @@ export class PythonToolchainManager {
791
791
  if (this._loadingPromise) return this._loadingPromise;
792
792
 
793
793
  this._loadingPromise = (async () => {
794
- this._emitProgress({
795
- stage: 'downloading',
796
- percent: 10,
797
- message: 'Initializing CPython 3.12 WebAssembly (Pyodide)...'
798
- });
799
-
800
- // Browser environment: load pyodide.js from CDN
801
- if (typeof window !== 'undefined') {
802
- const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
803
- if (!(window as any).loadPyodide) {
804
- await new Promise<void>((resolve, reject) => {
805
- const script = document.createElement('script');
806
- script.src = `${cdn.replace(/\/+$/, '')}/pyodide.js`;
807
- script.onload = () => resolve();
808
- script.onerror = () => reject(new Error(`Failed to load pyodide.js from ${script.src}`));
809
- document.head.appendChild(script);
810
- });
811
- }
812
-
794
+ try {
813
795
  this._emitProgress({
814
- stage: 'extracting',
815
- percent: 50,
816
- message: 'Bootstrapping Python runtime environment...'
796
+ stage: 'downloading',
797
+ percent: 10,
798
+ message: 'Initializing CPython 3.12 WebAssembly (Pyodide)...'
817
799
  });
818
800
 
819
- const loadPyodideFn = (window as any).loadPyodide;
820
- this.pyodide = await loadPyodideFn({
821
- indexURL: cdn
822
- });
823
- } else {
824
- // Node / Bun headless mock toolchain for hermetic offline test runs
825
- this.pyodide = {
826
- FS: {
827
- files: new Map<string, string>(),
828
- writeFile(p: string, content: any) {
829
- this.files.set(p, typeof content === 'string' ? content : String(content));
830
- },
831
- readFile(p: string, opts?: any) {
832
- return this.files.get(p) || '';
833
- },
834
- unlink(p: string) {
835
- this.files.delete(p);
836
- },
837
- mkdirTree(_p: string) {}
838
- },
839
- runPythonAsync: async (code: string) => {
840
- return `Execution mock: ${code.slice(0, 30)}`;
801
+ // Browser environment: load pyodide.js from CDN
802
+ if (typeof window !== 'undefined') {
803
+ const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
804
+ if (!(window as any).loadPyodide) {
805
+ await new Promise<void>((resolve, reject) => {
806
+ const script = document.createElement('script');
807
+ script.src = `${cdn.replace(/\/+$/, '')}/pyodide.js`;
808
+ script.onload = () => resolve();
809
+ script.onerror = () => reject(new Error(`Failed to load pyodide.js from ${script.src}`));
810
+ document.head.appendChild(script);
811
+ });
841
812
  }
842
- };
843
- }
844
813
 
845
- // Preload specified packages if any
846
- if (this.options.preloadPackages && Array.isArray(this.options.preloadPackages)) {
847
- for (const pkg of this.options.preloadPackages) {
848
- try {
849
- if (typeof this.pyodide.loadPackage === 'function') {
850
- await this.pyodide.loadPackage(pkg);
814
+ this._emitProgress({
815
+ stage: 'extracting',
816
+ percent: 50,
817
+ message: 'Bootstrapping Python runtime environment...'
818
+ });
819
+
820
+ const loadPyodideFn = (window as any).loadPyodide;
821
+ this.pyodide = await loadPyodideFn({
822
+ indexURL: cdn
823
+ });
824
+ } else {
825
+ // Node / Bun headless mock toolchain for hermetic offline test runs
826
+ this.pyodide = {
827
+ FS: {
828
+ files: new Map<string, string>(),
829
+ writeFile(p: string, content: any) {
830
+ this.files.set(p, typeof content === 'string' ? content : String(content));
831
+ },
832
+ readFile(p: string, opts?: any) {
833
+ return this.files.get(p) || '';
834
+ },
835
+ unlink(p: string) {
836
+ this.files.delete(p);
837
+ },
838
+ mkdirTree(_p: string) {}
839
+ },
840
+ runPythonAsync: async (code: string) => {
841
+ return `Execution mock: ${code.slice(0, 30)}`;
842
+ }
843
+ };
844
+ }
845
+
846
+ // Preload specified packages if any
847
+ if (this.options.preloadPackages && Array.isArray(this.options.preloadPackages)) {
848
+ for (const pkg of this.options.preloadPackages) {
849
+ try {
850
+ if (typeof this.pyodide.loadPackage === 'function') {
851
+ await this.pyodide.loadPackage(pkg);
852
+ }
853
+ } catch (err) {
854
+ void err;
851
855
  }
852
- } catch (err) {
853
- void err;
854
856
  }
855
857
  }
856
- }
857
858
 
858
- this._emitProgress({
859
- stage: 'ready',
860
- percent: 100,
861
- message: 'Python 3.12 WebAssembly Toolchain Ready'
862
- });
859
+ this._emitProgress({
860
+ stage: 'ready',
861
+ percent: 100,
862
+ message: 'Python 3.12 WebAssembly Toolchain Ready'
863
+ });
863
864
 
864
- return this.pyodide;
865
+ return this.pyodide;
866
+ } catch (err) {
867
+ this._loadingPromise = null;
868
+ throw err;
869
+ }
865
870
  })();
866
871
 
867
872
  return this._loadingPromise;
@@ -919,21 +924,38 @@ export class PythonToolchainManager {
919
924
 
920
925
  const pyodide = await this.ensureLoaded();
921
926
 
922
- // 1. Sync VFS files into Pyodide FS
927
+ // 1. Sync VFS files into Pyodide FS (recursively traversing subdirectories)
923
928
  if (req.vfs && pyodide.FS) {
924
- try {
925
- const vfsEntries = req.vfs.readdirSync('/workspace', { recursive: true });
926
- for (const entry of vfsEntries) {
927
- const fullPath = `/workspace/${entry}`;
928
- if (!req.vfs.statSync(fullPath).isDirectory()) {
929
- const content = req.vfs.readFileSync(fullPath, 'utf8');
930
- pyodide.FS.mkdirTree('/workspace');
931
- pyodide.FS.writeFile(fullPath, content);
929
+ const syncVfsDir = (dirPath: string) => {
930
+ try {
931
+ if (typeof pyodide.FS.mkdirTree === 'function') {
932
+ pyodide.FS.mkdirTree(dirPath);
933
+ }
934
+ const entries = req.vfs.readdirSync(dirPath);
935
+ for (const entry of entries) {
936
+ if (!entry || entry === '.' || entry === '..') continue;
937
+ const fullPath = `${dirPath === '/' ? '' : dirPath}/${entry}`;
938
+ try {
939
+ const st = req.vfs.statSync(fullPath);
940
+ if (st && typeof st.isDirectory === 'function' && st.isDirectory()) {
941
+ syncVfsDir(fullPath);
942
+ } else {
943
+ const parentDir = fullPath.slice(0, fullPath.lastIndexOf('/')) || '/workspace';
944
+ if (typeof pyodide.FS.mkdirTree === 'function') {
945
+ pyodide.FS.mkdirTree(parentDir);
946
+ }
947
+ const content = req.vfs.readFileSync(fullPath, 'utf8');
948
+ pyodide.FS.writeFile(fullPath, content);
949
+ }
950
+ } catch (err) {
951
+ void err;
952
+ }
932
953
  }
954
+ } catch (err) {
955
+ void err;
933
956
  }
934
- } catch (err) {
935
- void err;
936
- }
957
+ };
958
+ syncVfsDir('/workspace');
937
959
  }
938
960
 
939
961
  // Seed builtin /usr/lib/python modules
@@ -986,47 +1008,19 @@ export class PythonToolchainManager {
986
1008
  });
987
1009
  }
988
1010
 
989
- const rawLines = codeToRun.split('\n');
990
- const futureImports: string[] = [];
991
- const bodyLines: string[] = [];
992
- let inDocstring = false;
993
- let docChar = '';
994
-
995
- for (const l of rawLines) {
996
- const t = l.trim();
997
- if (!inDocstring && (t.startsWith('"""') || t.startsWith("'''"))) {
998
- if (t.length > 3 && (t.endsWith('"""') || t.endsWith("'''"))) {
999
- bodyLines.push(l);
1000
- continue;
1001
- }
1002
- inDocstring = true;
1003
- docChar = t.slice(0, 3);
1004
- bodyLines.push(l);
1005
- continue;
1006
- }
1007
- if (inDocstring) {
1008
- if (t.endsWith(docChar)) inDocstring = false;
1009
- bodyLines.push(l);
1010
- continue;
1011
- }
1012
- if (/^from\s+__future__\s+import\s+/.test(t)) {
1013
- futureImports.push(t);
1014
- } else {
1015
- bodyLines.push(l);
1016
- }
1017
- }
1018
-
1011
+ const fileLabel = JSON.stringify(req.entry || '<exec>');
1012
+ const encodedCode = JSON.stringify(codeToRun);
1019
1013
  const runnerWrapper = `
1020
- ${futureImports.join('\n')}
1021
1014
  import sys, tracemalloc
1022
1015
  if '/usr/lib/python' not in sys.path:
1023
1016
  sys.path.insert(0, '/usr/lib/python')
1024
1017
  if '/workspace' not in sys.path:
1025
1018
  sys.path.insert(0, '/workspace')
1026
1019
 
1020
+ _cl_user_code = ${encodedCode}
1027
1021
  tracemalloc.start()
1028
1022
  try:
1029
- ${bodyLines.map((l) => ' ' + l).join('\n')}
1023
+ exec(compile(_cl_user_code, ${fileLabel}, 'exec'), globals())
1030
1024
  finally:
1031
1025
  _, _peak = tracemalloc.get_traced_memory()
1032
1026
  tracemalloc.stop()
@@ -1069,24 +1063,42 @@ finally:
1069
1063
  }
1070
1064
  }
1071
1065
 
1072
- // 2. Sync back files from Pyodide FS into VFS
1066
+ // 2. Sync back files from Pyodide FS into VFS (recursively traversing subdirectories)
1073
1067
  if (req.vfs && pyodide.FS && typeof pyodide.FS.readdir === 'function') {
1074
- try {
1075
- const files = pyodide.FS.readdir('/workspace');
1076
- for (const f of files) {
1077
- if (f !== '.' && f !== '..') {
1078
- const p = `/workspace/${f}`;
1068
+ const syncBackPyodideDir = (dirPath: string) => {
1069
+ try {
1070
+ const entries = pyodide.FS.readdir(dirPath);
1071
+ for (const f of entries) {
1072
+ if (!f || f === '.' || f === '..') continue;
1073
+ const p = `${dirPath}/${f}`;
1079
1074
  try {
1080
- const content = pyodide.FS.readFile(p, { encoding: 'utf8' });
1081
- req.vfs.writeFileSync(p, content);
1075
+ let isDir = false;
1076
+ if (typeof pyodide.FS.stat === 'function' && typeof pyodide.FS.isDir === 'function') {
1077
+ const st = pyodide.FS.stat(p);
1078
+ isDir = Boolean(pyodide.FS.isDir(st.mode));
1079
+ }
1080
+ if (isDir) {
1081
+ if (typeof req.vfs.mkdirSync === 'function' && !req.vfs.existsSync(p)) {
1082
+ req.vfs.mkdirSync(p, { recursive: true });
1083
+ }
1084
+ syncBackPyodideDir(p);
1085
+ } else {
1086
+ const parentDir = p.slice(0, p.lastIndexOf('/')) || '/workspace';
1087
+ if (typeof req.vfs.mkdirSync === 'function' && !req.vfs.existsSync(parentDir)) {
1088
+ req.vfs.mkdirSync(parentDir, { recursive: true });
1089
+ }
1090
+ const content = pyodide.FS.readFile(p, { encoding: 'utf8' });
1091
+ req.vfs.writeFileSync(p, content);
1092
+ }
1082
1093
  } catch (err) {
1083
1094
  void err;
1084
1095
  }
1085
1096
  }
1097
+ } catch (err) {
1098
+ void err;
1086
1099
  }
1087
- } catch (err) {
1088
- void err;
1089
- }
1100
+ };
1101
+ syncBackPyodideDir('/workspace');
1090
1102
  }
1091
1103
 
1092
1104
  const durationMs = performance.now() - start;
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @innovatorved/code-lab v0.3.0
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
 
package/src/preview-sw.js CHANGED
@@ -58,6 +58,8 @@ self.addEventListener('activate', (event) => {
58
58
  self.addEventListener('message', (event) => {
59
59
  const data = event && event.data;
60
60
  if (!data || data.type !== 'codelab:config') return;
61
+ // Reject configuration attempts originating from preview tabs/frames themselves.
62
+ if (event.source && event.source.url && /\/__preview\//.test(event.source.url)) return;
61
63
  const csp = typeof data.csp === 'string' ? data.csp.trim() : '';
62
64
  if (!csp || csp.length > MAX_CONFIG_LENGTH) return;
63
65
  configuredCsp = csp;
@@ -80,10 +82,15 @@ function parsePreviewPath(pathname) {
80
82
  return { port: Number(match[1]), path: match[2] || '/' };
81
83
  }
82
84
 
85
+ function escapeMetaAttr(val) {
86
+ return String(val || '').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
87
+ }
88
+
83
89
  function previewErrorResponse(status, title, message) {
84
90
  const csp = previewPolicy();
91
+ const safeCsp = escapeMetaAttr(csp);
85
92
  const body = `<!doctype html><meta charset="utf-8">` +
86
- `<meta http-equiv="Content-Security-Policy" content="${csp}">` +
93
+ `<meta http-equiv="Content-Security-Policy" content="${safeCsp}">` +
87
94
  `<title>${title}</title>` +
88
95
  `<body style="font-family:system-ui,-apple-system,sans-serif;padding:32px;color:#666;background:#0a0a0a">` +
89
96
  `<h1 style="color:#e5e5e5;font-size:18px">${title}</h1><p>${message}</p></body>`;
@@ -100,14 +107,15 @@ function previewErrorResponse(status, title, message) {
100
107
  /** Inject the policy, a base URL and the sandbox shims into an HTML response. */
101
108
  function injectPreviewHead(html, port) {
102
109
  const csp = previewPolicy();
110
+ const safeCsp = escapeMetaAttr(csp);
103
111
  const shims = previewShims();
104
112
  const tags = [];
105
113
  const hasCsp = /<meta[^>]+http-equiv=["']?content-security-policy/i.test(html);
106
114
  const hasBase = /<base\b/i.test(html);
107
115
  const hasShims = html.indexOf('data-codelab-preview-shims') !== -1;
108
116
 
109
- if (!hasCsp) tags.push(`<meta http-equiv="Content-Security-Policy" content="${csp}">`);
110
- if (!hasBase) tags.push(`<base href="${PREVIEW_PREFIX}${port}/">`);
117
+ if (!hasCsp) tags.push(`<meta http-equiv="Content-Security-Policy" content="${safeCsp}">`);
118
+ if (!hasBase) tags.push(`<base href="${PREVIEW_PREFIX}${Number(port) || 3000}/">`);
111
119
  if (!hasShims && shims) tags.push(shims);
112
120
  if (tags.length === 0) return html;
113
121
 
@@ -123,7 +131,8 @@ function injectPreviewHead(html, port) {
123
131
 
124
132
  async function proxyVirtualRequest(event, port, targetPath) {
125
133
  const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
126
- if (!clients || !clients.length) {
134
+ const workbenchClients = (clients || []).filter((c) => !c.url || !/\/__preview\//.test(c.url));
135
+ if (!workbenchClients.length) {
127
136
  return previewErrorResponse(
128
137
  503,
129
138
  'No active CodeLab workbench',
@@ -131,7 +140,7 @@ async function proxyVirtualRequest(event, port, targetPath) {
131
140
  );
132
141
  }
133
142
 
134
- const client = clients[0];
143
+ const client = workbenchClients[0];
135
144
  const channel = new MessageChannel();
136
145
  const request = event.request;
137
146
  const method = request.method || 'GET';
@@ -187,6 +196,17 @@ async function proxyVirtualRequest(event, port, targetPath) {
187
196
  const responseHeaders = new Headers((response && response.headers) || {});
188
197
  const contentType = responseHeaders.get('content-type') || '';
189
198
 
199
+ // Decode Uint8Array / ArrayBuffer HTML bodies so head injection always applies.
200
+ if (/text\/html/i.test(contentType) && responseBody && typeof responseBody !== 'string') {
201
+ try {
202
+ if (responseBody instanceof ArrayBuffer || ArrayBuffer.isView(responseBody)) {
203
+ responseBody = new TextDecoder('utf-8').decode(responseBody);
204
+ }
205
+ } catch (err) {
206
+ console.warn('[code-lab] preview-sw: failed to decode HTML buffer', err);
207
+ }
208
+ }
209
+
190
210
  // Inject the policy and a <base> so relative asset URLs in HTML responses
191
211
  // resolve under the `/__preview/:port/` namespace rather than the host root.
192
212
  if (/text\/html/i.test(contentType) && typeof responseBody === 'string') {
package/src/runtime.ts CHANGED
@@ -1015,22 +1015,40 @@ function __initVirtualRuntime(rootScope) {
1015
1015
  // =========================================================================
1016
1016
  // 5. VIRTUAL IN-MEMORY POSIX FILESYSTEM (node:fs)
1017
1017
  // =========================================================================
1018
- function createVirtualFs(initialFiles = {}) {
1018
+ function createVirtualFs(initialFiles = {}, vfsOptions = {}) {
1019
1019
  const dirs = new Set(['/', '/tmp', '/workspace', '/home', '/home/user']);
1020
1020
  const files = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, ctimeMs, ino }
1021
1021
  const deletedInspectorCache = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, deletedAtMs }
1022
+ const MAX_DELETED_CACHE_ENTRIES = 50;
1023
+ const MAX_DELETED_CACHE_FILE_BYTES = 65536;
1024
+ const customCwdGetter = typeof vfsOptions === 'function'
1025
+ ? vfsOptions
1026
+ : (vfsOptions && typeof vfsOptions.cwdGetter === 'function' ? vfsOptions.cwdGetter : null);
1022
1027
  const fdTable = new Map(); // fd -> { inode, path, flags, pos, isDirectory }
1023
1028
  let nextFd = 10;
1024
1029
  let nextIno = 100;
1025
1030
  let mkdtempCounter = 1;
1026
1031
 
1032
+ function recordDeletedForInspector(p, data, mtimeMs) {
1033
+ if (!data || data.byteLength <= 0 || data.byteLength > MAX_DELETED_CACHE_FILE_BYTES) return;
1034
+ if (deletedInspectorCache.has(p)) {
1035
+ deletedInspectorCache.delete(p);
1036
+ } else if (deletedInspectorCache.size >= MAX_DELETED_CACHE_ENTRIES) {
1037
+ const oldestKey = deletedInspectorCache.keys().next().value;
1038
+ if (oldestKey !== undefined) deletedInspectorCache.delete(oldestKey);
1039
+ }
1040
+ deletedInspectorCache.set(p, { data: data.slice(), mtimeMs, deletedAtMs: Date.now() });
1041
+ }
1042
+
1027
1043
  function normPath(p) {
1028
1044
  if (typeof p !== 'string' || !p) {
1029
1045
  const err = new TypeError('path must be a non-empty string');
1030
1046
  err.code = 'ERR_INVALID_ARG_TYPE';
1031
1047
  throw err;
1032
1048
  }
1033
- const baseCwd = typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace';
1049
+ const baseCwd = typeof customCwdGetter === 'function'
1050
+ ? customCwdGetter()
1051
+ : (typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace');
1034
1052
  const abs = p.startsWith('/') ? VirtualPath.normalize(p) : VirtualPath.resolve(baseCwd, p);
1035
1053
  return abs.length > 1 && abs.endsWith('/') ? abs.slice(0, -1) : abs;
1036
1054
  }
@@ -1081,9 +1099,13 @@ function __initVirtualRuntime(rootScope) {
1081
1099
  for (const [relPath, content] of Object.entries(initialFiles)) {
1082
1100
  const cleanRel = relPath.startsWith('/') ? relPath.slice(1) : relPath;
1083
1101
  const isSystemPath = /^\/(workspace|usr|tmp|lib|include|etc|bin|dev)(\/|$)/.test(relPath);
1084
- const fullPath = isSystemPath
1102
+ let fullPath = isSystemPath
1085
1103
  ? normPath(relPath)
1086
1104
  : normPath(`/workspace/${cleanRel}`);
1105
+ if (!isSystemPath && fullPath !== '/workspace' && !fullPath.startsWith('/workspace/')) {
1106
+ const safeSub = cleanRel.split('/').filter((seg) => seg && seg !== '.' && seg !== '..').join('/');
1107
+ fullPath = normPath(`/workspace/${safeSub || 'file'}`);
1108
+ }
1087
1109
  ensureParentDirs(fullPath);
1088
1110
  const bytes = typeof content === 'string' ? utf8Encode(content) : new Uint8Array(content);
1089
1111
  files.set(fullPath, {
@@ -1263,13 +1285,6 @@ function __initVirtualRuntime(rootScope) {
1263
1285
  fsyncSync(fd) {
1264
1286
  const entry = fdTable.get(fd);
1265
1287
  if (!entry) throw fsError('EBADF', 'fsync', String(fd), 'bad file descriptor');
1266
- if (!entry.isDirectory && entry.inode) {
1267
- deletedInspectorCache.set(entry.path, {
1268
- data: entry.inode.data.slice(),
1269
- mtimeMs: entry.inode.mtimeMs,
1270
- deletedAtMs: null
1271
- });
1272
- }
1273
1288
  },
1274
1289
 
1275
1290
  fdatasyncSync(fd) {
@@ -1310,12 +1325,6 @@ function __initVirtualRuntime(rootScope) {
1310
1325
  inode.mtimeMs = Date.now();
1311
1326
  entry.pos = writePos + chunk.byteLength;
1312
1327
 
1313
- deletedInspectorCache.set(entry.path, {
1314
- data: inode.data.slice(),
1315
- mtimeMs: inode.mtimeMs,
1316
- deletedAtMs: null
1317
- });
1318
-
1319
1328
  return chunk.byteLength;
1320
1329
  },
1321
1330
 
@@ -1367,7 +1376,7 @@ function __initVirtualRuntime(rootScope) {
1367
1376
  inode.mode = 0o100000 | (Number(opts.mode) & 0o777);
1368
1377
  }
1369
1378
  }
1370
- deletedInspectorCache.set(np, { data: bytes.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1379
+ deletedInspectorCache.delete(np);
1371
1380
  },
1372
1381
 
1373
1382
  chmodSync(p, mode) {
@@ -1396,7 +1405,7 @@ function __initVirtualRuntime(rootScope) {
1396
1405
  combined.set(chunk, inode.data.byteLength);
1397
1406
  inode.data = combined;
1398
1407
  inode.mtimeMs = Date.now();
1399
- deletedInspectorCache.set(np, { data: combined.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1408
+ deletedInspectorCache.delete(np);
1400
1409
  },
1401
1410
 
1402
1411
  truncateSync(p, len = 0) {
@@ -1412,7 +1421,6 @@ function __initVirtualRuntime(rootScope) {
1412
1421
  inode.data = grown;
1413
1422
  }
1414
1423
  inode.mtimeMs = Date.now();
1415
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1416
1424
  },
1417
1425
 
1418
1426
  renameSync(oldP, newP) {
@@ -1473,16 +1481,14 @@ function __initVirtualRuntime(rootScope) {
1473
1481
  if (fdEntry.path === src) fdEntry.path = dst;
1474
1482
  }
1475
1483
  deletedInspectorCache.delete(src);
1476
- deletedInspectorCache.set(dst, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1484
+ deletedInspectorCache.delete(dst);
1477
1485
  },
1478
1486
 
1479
1487
  unlinkSync(p) {
1480
1488
  const np = normPath(p);
1481
1489
  const inode = files.get(np);
1482
1490
  if (!inode) throw fsError('ENOENT', 'unlink', p, 'no such file or directory');
1483
- if (inode.data.byteLength > 0) {
1484
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
1485
- }
1491
+ recordDeletedForInspector(np, inode.data, inode.mtimeMs);
1486
1492
  files.delete(np);
1487
1493
  },
1488
1494
 
@@ -1499,9 +1505,7 @@ function __initVirtualRuntime(rootScope) {
1499
1505
  for (const [fPath, inode] of Array.from(files.entries())) {
1500
1506
  if (fPath.startsWith(prefix)) {
1501
1507
  if (!recursive) throw fsError('ENOTEMPTY', 'rm', p, 'directory not empty');
1502
- if (inode.data.byteLength > 0) {
1503
- deletedInspectorCache.set(fPath, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
1504
- }
1508
+ recordDeletedForInspector(fPath, inode.data, inode.mtimeMs);
1505
1509
  files.delete(fPath);
1506
1510
  }
1507
1511
  }
@@ -3075,6 +3079,7 @@ function __initVirtualRuntime(rootScope) {
3075
3079
  responseHeaders: {},
3076
3080
  _t0: performance.now()
3077
3081
  };
3082
+ if (httpTrace.length >= 500) httpTrace.shift();
3078
3083
  httpTrace.push(traceEntry);
3079
3084
  this._traceEntry = traceEntry;
3080
3085
 
@@ -4066,6 +4071,7 @@ function __initVirtualRuntime(rootScope) {
4066
4071
  this._peer = serverSocket;
4067
4072
  this.connecting = false;
4068
4073
 
4074
+ if (sharedTrace.length >= 500) sharedTrace.shift();
4069
4075
  sharedTrace.push({
4070
4076
  protocol: 'TCP',
4071
4077
  event: 'connect',
@@ -6358,7 +6364,10 @@ function __initVirtualRuntime(rootScope) {
6358
6364
  const activePortTable = optPortTable || portTable || _defaultPortTable;
6359
6365
  resourceTracker.pid = pid;
6360
6366
 
6361
- const vfs = optVfs || createVirtualFs(files);
6367
+ let currentCwd = '/workspace';
6368
+ _activeCwdGetter = () => currentCwd;
6369
+
6370
+ const vfs = optVfs || createVirtualFs(files, { cwdGetter: () => currentCwd });
6362
6371
  if (optVfs && files && typeof files === 'object') {
6363
6372
  for (const [fPath, content] of Object.entries(files)) {
6364
6373
  const abs = fPath.startsWith('/') ? fPath : '/workspace/' + fPath;
@@ -6752,8 +6761,6 @@ function __initVirtualRuntime(rootScope) {
6752
6761
  hrtimeFn.bigint = () => BigInt(Math.round(performance.now() * 1e6));
6753
6762
 
6754
6763
  let syncExecDepth = 0;
6755
- let currentCwd = '/workspace';
6756
- _activeCwdGetter = () => currentCwd;
6757
6764
 
6758
6765
  const sandboxProcess = Object.assign(new EventEmitter(), {
6759
6766
  env: { NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' },
package/src/schemas.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
 
3
3
  /**
4
- * Zod Schemas and Inferred TypeScript Types for code-lab v0.2.0
4
+ * Zod Schemas and Inferred TypeScript Types for code-lab v0.3.2
5
5
  */
6
6
 
7
7
  // ── 1. Guided Step ──────────────────────────────────────────────────────────
@@ -67,7 +67,7 @@ export const GuidedLabExtensionOptionsSchema = z.object({
67
67
  export type GuidedLabExtensionOptions = z.infer<typeof GuidedLabExtensionOptionsSchema>;
68
68
 
69
69
  export const CppToolchainProgressSchema = z.object({
70
- stage: z.enum(['downloading', 'caching', 'extracting', 'compiling', 'linking', 'ready']),
70
+ stage: z.enum(['downloading', 'caching', 'extracting', 'compiling', 'linking', 'ready', 'error']),
71
71
  loadedBytes: z.number().optional(),
72
72
  totalBytes: z.number().optional(),
73
73
  percent: z.number().optional(),