@innovatorved/code-lab 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/ARCHITECTURE.md +8 -4
  2. package/CHANGELOG.md +45 -0
  3. package/README.md +70 -158
  4. package/dist/apps/web/src/index.d.ts +34 -0
  5. package/dist/code-lab-sql.css +482 -0
  6. package/dist/code-lab-sql.d.ts +179 -0
  7. package/dist/code-lab-sql.esm.js +542 -0
  8. package/dist/code-lab-sql.umd.js +531 -0
  9. package/dist/code-lab.css +298 -2
  10. package/dist/code-lab.d.ts +110 -15
  11. package/dist/code-lab.esm.js +35284 -18253
  12. package/dist/code-lab.js +40434 -23431
  13. package/dist/code-lab.umd.js +65502 -0
  14. package/dist/diagnostics.d.ts +5 -0
  15. package/dist/extensions/cpp.esm.js +19532 -3772
  16. package/dist/extensions/cpp.js +19529 -3769
  17. package/dist/extensions/guided-lab.esm.js +19401 -3725
  18. package/dist/extensions/guided-lab.js +19400 -3724
  19. package/dist/extensions/python.d.ts +1 -0
  20. package/dist/extensions/python.esm.js +19666 -3843
  21. package/dist/extensions/python.js +19668 -3845
  22. package/dist/extensions/umbrella.d.ts +5 -0
  23. package/dist/index.d.ts +1 -1
  24. package/dist/modular-kernel.d.ts +11 -0
  25. package/dist/packages/commands/src/index.d.ts +96 -0
  26. package/dist/packages/core/src/di.d.ts +36 -0
  27. package/dist/packages/core/src/disposable.d.ts +27 -0
  28. package/dist/packages/core/src/errors.d.ts +69 -0
  29. package/dist/packages/core/src/events.d.ts +38 -0
  30. package/dist/packages/core/src/index.d.ts +6 -0
  31. package/dist/packages/core/src/path.d.ts +14 -0
  32. package/dist/packages/core/src/registry.d.ts +23 -0
  33. package/dist/packages/editor/src/index.d.ts +118 -0
  34. package/dist/packages/fs/src/backends.d.ts +37 -0
  35. package/dist/packages/fs/src/index.d.ts +3 -0
  36. package/dist/packages/fs/src/types.d.ts +40 -0
  37. package/dist/packages/fs/src/vfs-service.d.ts +33 -0
  38. package/dist/packages/preview/src/index.d.ts +34 -0
  39. package/dist/packages/runtime/src/index.d.ts +47 -0
  40. package/dist/packages/settings/src/builtin-schemas.d.ts +15 -0
  41. package/dist/packages/settings/src/configuration-service.d.ts +100 -0
  42. package/dist/packages/settings/src/index.d.ts +4 -0
  43. package/dist/packages/settings/src/jsonc.d.ts +20 -0
  44. package/dist/packages/settings/src/schema.d.ts +28 -0
  45. package/dist/packages/sql/src/completions.d.ts +8 -0
  46. package/dist/packages/sql/src/diagnostics.d.ts +2 -0
  47. package/dist/packages/sql/src/formatter.d.ts +2 -0
  48. package/dist/packages/sql/src/index.d.ts +7 -0
  49. package/dist/packages/sql/src/sql-editor.d.ts +2 -0
  50. package/dist/packages/sql/src/styles.d.ts +2 -0
  51. package/dist/packages/sql/src/tokenizer.d.ts +13 -0
  52. package/dist/packages/sql/src/types.d.ts +130 -0
  53. package/dist/packages/terminal/src/index.d.ts +54 -0
  54. package/dist/packages/ui/src/index.d.ts +4 -0
  55. package/dist/packages/ui/src/observability.d.ts +22 -0
  56. package/dist/packages/ui/src/plugin-registry.d.ts +89 -0
  57. package/dist/packages/ui/src/settings-dialog.d.ts +25 -0
  58. package/dist/packages/ui/src/themes.d.ts +35 -0
  59. package/dist/preview-sw.js +82 -24
  60. package/dist/runtime.d.ts +3 -3
  61. package/dist/runtime.esm.js +503 -73
  62. package/dist/runtime.js +501 -73
  63. package/dist/schemas.d.ts +234 -814
  64. package/dist/schemas.esm.js +19401 -3725
  65. package/dist/schemas.js +19404 -3728
  66. package/dist/scm.d.ts +13 -2
  67. package/dist/search.d.ts +5 -1
  68. package/dist/shell.d.ts +1 -1
  69. package/dist/shell.esm.js +435 -54
  70. package/dist/shell.js +435 -54
  71. package/dist/terminal.esm.js +242 -54
  72. package/dist/terminal.js +242 -54
  73. package/dist/workbench/diff-editor.d.ts +1 -0
  74. package/dist/workbench/index.d.ts +1 -1
  75. package/dist/workbench/styles.d.ts +1 -1
  76. package/dist/zip.d.ts +4 -3
  77. package/package.json +37 -8
  78. package/packages/commands/README.md +7 -0
  79. package/packages/commands/package.json +16 -0
  80. package/packages/commands/src/index.ts +467 -0
  81. package/packages/commands/tsconfig.json +22 -0
  82. package/packages/core/README.md +12 -0
  83. package/packages/core/package.json +13 -0
  84. package/packages/core/src/di.ts +147 -0
  85. package/packages/core/src/disposable.ts +112 -0
  86. package/packages/core/src/errors.ts +205 -0
  87. package/packages/core/src/events.ts +157 -0
  88. package/packages/core/src/index.ts +49 -0
  89. package/packages/core/src/path.ts +118 -0
  90. package/packages/core/src/registry.ts +61 -0
  91. package/packages/core/tsconfig.json +19 -0
  92. package/packages/editor/README.md +9 -0
  93. package/packages/editor/package.json +18 -0
  94. package/packages/editor/src/index.ts +344 -0
  95. package/packages/editor/tsconfig.json +24 -0
  96. package/packages/fs/README.md +7 -0
  97. package/packages/fs/package.json +16 -0
  98. package/packages/fs/src/backends.ts +301 -0
  99. package/packages/fs/src/index.ts +18 -0
  100. package/packages/fs/src/types.ts +44 -0
  101. package/packages/fs/src/vfs-service.ts +257 -0
  102. package/packages/fs/tsconfig.json +22 -0
  103. package/packages/preview/README.md +3 -0
  104. package/packages/preview/package.json +16 -0
  105. package/packages/preview/src/index.ts +125 -0
  106. package/packages/preview/tsconfig.json +22 -0
  107. package/packages/runtime/README.md +3 -0
  108. package/packages/runtime/package.json +17 -0
  109. package/packages/runtime/src/index.ts +134 -0
  110. package/packages/runtime/tsconfig.json +23 -0
  111. package/packages/settings/README.md +7 -0
  112. package/packages/settings/package.json +16 -0
  113. package/packages/settings/src/builtin-schemas.ts +235 -0
  114. package/packages/settings/src/configuration-service.ts +543 -0
  115. package/packages/settings/src/index.ts +37 -0
  116. package/packages/settings/src/jsonc.ts +189 -0
  117. package/packages/settings/src/schema.ts +164 -0
  118. package/packages/settings/tsconfig.json +22 -0
  119. package/packages/sql/README.md +12 -0
  120. package/packages/sql/package.json +13 -0
  121. package/packages/sql/src/completions.ts +359 -0
  122. package/packages/sql/src/diagnostics.ts +200 -0
  123. package/packages/sql/src/formatter.ts +271 -0
  124. package/packages/sql/src/index.ts +54 -0
  125. package/packages/sql/src/sql-editor.ts +802 -0
  126. package/packages/sql/src/styles.ts +501 -0
  127. package/packages/sql/src/tokenizer.ts +457 -0
  128. package/packages/sql/src/types.ts +148 -0
  129. package/packages/sql/tsconfig.json +19 -0
  130. package/packages/terminal/README.md +3 -0
  131. package/packages/terminal/package.json +16 -0
  132. package/packages/terminal/src/index.ts +183 -0
  133. package/packages/terminal/tsconfig.json +22 -0
  134. package/packages/ui/README.md +8 -0
  135. package/packages/ui/package.json +18 -0
  136. package/packages/ui/src/index.ts +36 -0
  137. package/packages/ui/src/observability.ts +175 -0
  138. package/packages/ui/src/plugin-registry.ts +274 -0
  139. package/packages/ui/src/settings-dialog.ts +293 -0
  140. package/packages/ui/src/themes.ts +174 -0
  141. package/packages/ui/tsconfig.json +24 -0
  142. package/src/code-lab.css +298 -2
  143. package/src/csp.ts +7 -10
  144. package/src/diagnostics.ts +42 -3
  145. package/src/extensions/cpp.ts +105 -24
  146. package/src/extensions/python.ts +260 -116
  147. package/src/extensions/umbrella.ts +5 -0
  148. package/src/index.ts +1 -1
  149. package/src/modular-kernel.ts +11 -0
  150. package/src/preview-sw.js +73 -12
  151. package/src/runtime.ts +501 -74
  152. package/src/schemas.ts +62 -62
  153. package/src/scm.ts +106 -19
  154. package/src/search.ts +71 -27
  155. package/src/shell.ts +433 -53
  156. package/src/terminal.ts +239 -52
  157. package/src/workbench/diff-editor.ts +106 -18
  158. package/src/workbench/drawer.ts +17 -4
  159. package/src/workbench/guided-pane.ts +12 -2
  160. package/src/workbench/icons.ts +5 -2
  161. package/src/workbench/share.ts +37 -8
  162. package/src/workbench/styles.ts +2 -1
  163. package/src/workbench/toolbar.ts +15 -4
  164. package/src/workbench.ts +2877 -284
  165. package/src/zip.ts +29 -7
  166. package/dist/runtime/index.d.ts +0 -4
  167. package/dist/shell/coreutils/compilers-cli.d.ts +0 -24
  168. package/dist/shell/index.d.ts +0 -4
  169. package/src/runtime/index.ts +0 -5
  170. package/src/shell/coreutils/compilers-cli.ts +0 -103
  171. package/src/shell/index.ts +0 -5
@@ -341,12 +341,16 @@ async function getCachedAsset(key: string): Promise<Uint8Array | null> {
341
341
  const db = await openToolchainIdb();
342
342
  if (!db) return null;
343
343
  return new Promise((resolve) => {
344
+ const closeDb = () => {
345
+ try { db.close(); } catch (err) { void err; }
346
+ };
344
347
  try {
345
348
  const tx = db.transaction(IDB_STORE, 'readonly');
346
349
  const store = tx.objectStore(IDB_STORE);
347
350
  const req = store.get(key);
348
351
  req.onsuccess = () => {
349
352
  const val = req.result;
353
+ closeDb();
350
354
  if (val instanceof Uint8Array) {
351
355
  memoryAssetCache.set(key, val);
352
356
  resolve(val);
@@ -358,8 +362,12 @@ async function getCachedAsset(key: string): Promise<Uint8Array | null> {
358
362
  resolve(null);
359
363
  }
360
364
  };
361
- req.onerror = () => resolve(null);
365
+ req.onerror = () => {
366
+ closeDb();
367
+ resolve(null);
368
+ };
362
369
  } catch (err) {
370
+ closeDb();
363
371
  if (err) resolve(null);
364
372
  }
365
373
  });
@@ -370,13 +378,23 @@ async function setCachedAsset(key: string, data: Uint8Array): Promise<void> {
370
378
  const db = await openToolchainIdb();
371
379
  if (!db) return;
372
380
  return new Promise((resolve) => {
381
+ const closeDb = () => {
382
+ try { db.close(); } catch (err) { void err; }
383
+ };
373
384
  try {
374
385
  const tx = db.transaction(IDB_STORE, 'readwrite');
375
386
  const store = tx.objectStore(IDB_STORE);
376
387
  store.put(data, key);
377
- tx.oncomplete = () => resolve();
378
- tx.onerror = () => resolve();
388
+ tx.oncomplete = () => {
389
+ closeDb();
390
+ resolve();
391
+ };
392
+ tx.onerror = () => {
393
+ closeDb();
394
+ resolve();
395
+ };
379
396
  } catch (err) {
397
+ closeDb();
380
398
  if (err) resolve();
381
399
  }
382
400
  });
@@ -404,17 +422,21 @@ export function extractTarToVfs(tarBytes: Uint8Array, vfs: any, baseDir = '/'):
404
422
  continue;
405
423
  }
406
424
  const sizeOctal = readString(offset + 124, 12);
407
- const size = parseInt(sizeOctal || '0', 8) || 0;
425
+ const size = Math.max(0, parseInt(sizeOctal || '0', 8) || 0);
408
426
  const typeFlag = tarBytes[offset + 156];
409
427
  const prefix = readString(offset + 345, 155);
410
428
  const fullName = prefix ? `${prefix}/${name}` : name;
411
- const cleanRel = fullName.replace(/^\.?\/+/, '');
412
- const targetPath = baseDir === '/' ? `/${cleanRel}` : `${baseDir.replace(/\/+$/, '')}/${cleanRel}`;
429
+ const rawRel = fullName.replace(/^\.?\/+/, '');
430
+ const rawSegments = rawRel.split('/').filter(Boolean);
431
+ const hasDotDot = rawSegments.some((seg) => seg === '..');
432
+ const cleanRel = hasDotDot ? '' : rawSegments.filter((seg) => seg !== '.').join('/');
433
+ const cleanBase = baseDir === '/' ? '' : baseDir.replace(/\/+$/, '');
434
+ const targetPath = `${cleanBase}/${cleanRel}`;
413
435
 
414
436
  const dataStart = offset + 512;
415
- const dataEnd = dataStart + size;
437
+ const dataEnd = Math.min(tarBytes.length, dataStart + size);
416
438
 
417
- if (cleanRel) {
439
+ if (cleanRel && !hasDotDot) {
418
440
  if (typeFlag === 53 || fullName.endsWith('/')) {
419
441
  // Directory ('5')
420
442
  if (!vfs.existsSync(targetPath)) {
@@ -838,6 +860,8 @@ export class CppToolchainManager {
838
860
  );
839
861
  }
840
862
 
863
+ this.nativeToolchainUnavailable = false;
864
+ this.loadError = null;
841
865
  this._emitProgress({
842
866
  stage: 'ready',
843
867
  loadedBytes:
@@ -951,10 +975,24 @@ export class CppToolchainManager {
951
975
  message: `Compiling ${sourceFiles.map((s) => s.split('/').pop()).join(', ')} with Clang (${std}, ${optLevel})...`
952
976
  });
953
977
 
978
+ const buildDir = `/tmp/build_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
979
+ if (!vfs.existsSync(buildDir)) {
980
+ vfs.mkdirSync(buildDir, { recursive: true });
981
+ }
982
+ const cleanupBuildDir = () => {
983
+ try {
984
+ if (typeof vfs.rmSync === 'function') {
985
+ vfs.rmSync(buildDir, { recursive: true, force: true });
986
+ }
987
+ } catch (err) {
988
+ void err;
989
+ }
990
+ };
991
+
954
992
  const objectFiles: string[] = [];
955
993
  for (let i = 0; i < sourceFiles.length; i++) {
956
994
  const srcPath = sourceFiles[i];
957
- const objPath = `/tmp/obj_${i}.o`;
995
+ const objPath = `${buildDir}/obj_${i}.o`;
958
996
  objectFiles.push(objPath);
959
997
 
960
998
  const clangArgs = [
@@ -992,6 +1030,7 @@ export class CppToolchainManager {
992
1030
  });
993
1031
 
994
1032
  if (compileStep.exitCode !== 0) {
1033
+ cleanupBuildDir();
995
1034
  return {
996
1035
  ok: false,
997
1036
  exitCode: compileStep.exitCode,
@@ -1034,6 +1073,7 @@ export class CppToolchainManager {
1034
1073
  onStdout: handleOut,
1035
1074
  onStderr: handleErr
1036
1075
  });
1076
+ cleanupBuildDir();
1037
1077
 
1038
1078
  if (linkStep.exitCode !== 0 || !vfs.existsSync(outputPath)) {
1039
1079
  return {
@@ -1087,23 +1127,63 @@ export class CppToolchainManager {
1087
1127
  if (req.onStderr) req.onStderr(t);
1088
1128
  };
1089
1129
 
1090
- let allValid = true;
1091
- for (const src of sourceFiles) {
1092
- const code = vfs.readFileSync(src, 'utf8');
1093
- const lines = code.split(/\r?\n/);
1130
+ const fallbackReason = this.loadError && this.loadError.message
1131
+ ? this.loadError.message
1132
+ : 'WASI Clang/LLD binaries not loaded';
1133
+ handleErr(`clang++: warning: native WASI toolchain unavailable (${fallbackReason}); using limited offline C++ fallback.\n`);
1134
+
1135
+ const scanBalancedDelimiters = (code: string): { braceCount: number; parenCount: number } => {
1094
1136
  let braceCount = 0;
1095
1137
  let parenCount = 0;
1096
- for (let i = 0; i < lines.length; i++) {
1097
- const line = lines[i];
1098
- const trimmed = line.trim();
1099
- if (trimmed.startsWith('//') || trimmed.startsWith('/*')) continue;
1100
- for (const ch of line) {
1101
- if (ch === '{') braceCount++;
1102
- else if (ch === '}') braceCount--;
1103
- else if (ch === '(') parenCount++;
1104
- else if (ch === ')') parenCount--;
1138
+ let i = 0;
1139
+ const len = code.length;
1140
+ while (i < len) {
1141
+ const ch = code[i];
1142
+ const next = code[i + 1];
1143
+ if (ch === '/' && next === '/') {
1144
+ i += 2;
1145
+ while (i < len && code[i] !== '\n') i++;
1146
+ continue;
1147
+ }
1148
+ if (ch === '/' && next === '*') {
1149
+ i += 2;
1150
+ while (i < len && !(code[i] === '*' && code[i + 1] === '/')) i++;
1151
+ i += 2;
1152
+ continue;
1153
+ }
1154
+ if (ch === 'R' && next === '"') {
1155
+ const openParen = code.indexOf('(', i + 2);
1156
+ if (openParen !== -1) {
1157
+ const delim = code.slice(i + 2, openParen);
1158
+ const closeSeq = `)${delim}"`;
1159
+ const closeIdx = code.indexOf(closeSeq, openParen + 1);
1160
+ i = closeIdx !== -1 ? closeIdx + closeSeq.length : len;
1161
+ continue;
1162
+ }
1105
1163
  }
1164
+ if (ch === '"' || ch === "'") {
1165
+ const quote = ch;
1166
+ i++;
1167
+ while (i < len && code[i] !== quote) {
1168
+ if (code[i] === '\\') i += 2;
1169
+ else i++;
1170
+ }
1171
+ i++;
1172
+ continue;
1173
+ }
1174
+ if (ch === '{') braceCount++;
1175
+ else if (ch === '}') braceCount--;
1176
+ else if (ch === '(') parenCount++;
1177
+ else if (ch === ')') parenCount--;
1178
+ i++;
1106
1179
  }
1180
+ return { braceCount, parenCount };
1181
+ };
1182
+
1183
+ let allValid = true;
1184
+ for (const src of sourceFiles) {
1185
+ const code = vfs.readFileSync(src, 'utf8');
1186
+ const { braceCount, parenCount } = scanBalancedDelimiters(code);
1107
1187
  if (braceCount !== 0 || parenCount !== 0) {
1108
1188
  const err = `clang++: error: syntax error in '${src}': unmatched ${braceCount !== 0 ? 'curly braces' : 'parentheses'}\n`;
1109
1189
  handleErr(err);
@@ -1969,8 +2049,9 @@ export function installCppExtension(workbench: any, options: ExtendedCppExtensio
1969
2049
  for (const d of diags) {
1970
2050
  workbench._diagnosticsStore.add(d);
1971
2051
  }
1972
- if (typeof window !== 'undefined' && (window as any).monaco && workbench.editor) {
1973
- const model = workbench.editor.getModel();
2052
+ if (typeof window !== 'undefined' && (window as any).monaco) {
2053
+ const model = (workbench.models && typeof workbench.models.get === 'function' && workbench.models.get(file))
2054
+ || (workbench.activeFile === file && workbench.editor ? workbench.editor.getModel() : null);
1974
2055
  if (model) {
1975
2056
  const markers = diags.map((d) => ({
1976
2057
  startLineNumber: d.line,
@@ -194,6 +194,13 @@ def ASSERT_NE(actual: Any, expected: Any, msg: str = None):
194
194
  def CODELAB_TEST_EXIT_CODE() -> int:
195
195
  return 0 if _FAILED_COUNT == 0 else 1
196
196
 
197
+ def _reset_codelab_test() -> None:
198
+ global _SUITE_NAME, _PASSED_COUNT, _FAILED_COUNT, _TOTAL_COUNT
199
+ _SUITE_NAME = "Default Test Suite"
200
+ _PASSED_COUNT = 0
201
+ _FAILED_COUNT = 0
202
+ _TOTAL_COUNT = 0
203
+
197
204
  from contextlib import contextmanager
198
205
 
199
206
  @contextmanager
@@ -786,82 +793,159 @@ export class PythonToolchainManager {
786
793
  }
787
794
  }
788
795
 
796
+ private static _scriptPromises = new Map<string, Promise<void>>();
797
+
789
798
  public async ensureLoaded(): Promise<any> {
790
799
  if (this.pyodide) return this.pyodide;
791
800
  if (this._loadingPromise) return this._loadingPromise;
792
801
 
793
802
  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
-
803
+ try {
813
804
  this._emitProgress({
814
- stage: 'extracting',
815
- percent: 50,
816
- message: 'Bootstrapping Python runtime environment...'
805
+ stage: 'downloading',
806
+ percent: 10,
807
+ message: 'Initializing CPython 3.12 WebAssembly (Pyodide)...'
817
808
  });
818
809
 
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)}`;
810
+ // Browser environment: load pyodide.js from CDN (deduplicated across concurrent instances)
811
+ if (typeof window !== 'undefined' && typeof document !== 'undefined' && !(this.options as any).headlessMock) {
812
+ const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
813
+ const scriptUrl = `${cdn.replace(/\/+$/, '')}/pyodide.js`;
814
+ if (!(window as any).loadPyodide) {
815
+ let scriptPromise = PythonToolchainManager._scriptPromises.get(scriptUrl);
816
+ if (!scriptPromise) {
817
+ scriptPromise = new Promise<void>((resolve, reject) => {
818
+ const existing = typeof document.querySelector === 'function'
819
+ ? document.querySelector(`script[data-codelab-pyodide="${scriptUrl}"]`) as HTMLScriptElement | null
820
+ : null;
821
+ if (existing && (window as any).loadPyodide) {
822
+ resolve();
823
+ return;
824
+ }
825
+ const script = document.createElement('script');
826
+ script.src = scriptUrl;
827
+ script.setAttribute('data-codelab-pyodide', scriptUrl);
828
+ script.onload = () => resolve();
829
+ script.onerror = () => {
830
+ PythonToolchainManager._scriptPromises.delete(scriptUrl);
831
+ reject(new Error(`Failed to load pyodide.js from ${scriptUrl}`));
832
+ };
833
+ document.head.appendChild(script);
834
+ });
835
+ PythonToolchainManager._scriptPromises.set(scriptUrl, scriptPromise);
836
+ }
837
+ await scriptPromise;
841
838
  }
842
- };
843
- }
844
839
 
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);
840
+ this._emitProgress({
841
+ stage: 'extracting',
842
+ percent: 50,
843
+ message: 'Bootstrapping Python runtime environment...'
844
+ });
845
+
846
+ const loadPyodideFn = (window as any).loadPyodide;
847
+ this.pyodide = await loadPyodideFn({
848
+ indexURL: cdn
849
+ });
850
+ } else {
851
+ // Node / Bun headless mock toolchain for hermetic offline test runs (binary-safe)
852
+ const dirs = new Set<string>(['/', '/workspace', '/usr', '/usr/lib', '/usr/lib/python']);
853
+ const files = new Map<string, Uint8Array>();
854
+ const encoder = new TextEncoder();
855
+ const decoder = new TextDecoder('utf-8', { fatal: false });
856
+ const ensureDirs = (p: string) => {
857
+ const parts = p.split('/').filter(Boolean);
858
+ let cur = '';
859
+ for (const seg of parts) {
860
+ cur += '/' + seg;
861
+ dirs.add(cur);
862
+ }
863
+ };
864
+ this.pyodide = {
865
+ FS: {
866
+ files,
867
+ dirs,
868
+ mkdirTree(p: string) {
869
+ ensureDirs(p);
870
+ },
871
+ writeFile(p: string, content: any) {
872
+ const slashIdx = p.lastIndexOf('/');
873
+ if (slashIdx > 0) ensureDirs(p.slice(0, slashIdx));
874
+ if (content instanceof Uint8Array) {
875
+ files.set(p, content.slice());
876
+ } else if (ArrayBuffer.isView(content)) {
877
+ files.set(p, new Uint8Array(content.buffer, content.byteOffset, content.byteLength).slice());
878
+ } else {
879
+ files.set(p, encoder.encode(typeof content === 'string' ? content : String(content ?? '')));
880
+ }
881
+ },
882
+ readFile(p: string, opts?: any) {
883
+ const raw = files.get(p);
884
+ if (!raw) return opts && opts.encoding === 'utf8' ? '' : new Uint8Array(0);
885
+ if (opts && opts.encoding === 'utf8') {
886
+ return decoder.decode(raw);
887
+ }
888
+ return raw.slice();
889
+ },
890
+ unlink(p: string) {
891
+ files.delete(p);
892
+ },
893
+ readdir(dirPath: string) {
894
+ const prefix = dirPath === '/' ? '/' : dirPath.replace(/\/+$/, '') + '/';
895
+ const children = new Set<string>(['.', '..']);
896
+ for (const d of dirs) {
897
+ if (d.startsWith(prefix)) {
898
+ const rest = d.slice(prefix.length);
899
+ if (rest && !rest.includes('/')) children.add(rest);
900
+ }
901
+ }
902
+ for (const f of files.keys()) {
903
+ if (f.startsWith(prefix)) {
904
+ const rest = f.slice(prefix.length);
905
+ if (rest && !rest.includes('/')) children.add(rest);
906
+ }
907
+ }
908
+ return Array.from(children);
909
+ },
910
+ stat(p: string) {
911
+ if (dirs.has(p)) return { mode: 0o040755 };
912
+ if (files.has(p)) return { mode: 0o100644 };
913
+ throw new Error(`ENOENT: ${p}`);
914
+ },
915
+ isDir(mode: number) {
916
+ return (mode & 0o170000) === 0o040000;
917
+ }
918
+ },
919
+ runPythonAsync: async (code: string) => {
920
+ return `Execution mock: ${code.slice(0, 30)}`;
921
+ }
922
+ };
923
+ }
924
+
925
+ // Preload specified packages if any
926
+ if (this.options.preloadPackages && Array.isArray(this.options.preloadPackages)) {
927
+ for (const pkg of this.options.preloadPackages) {
928
+ try {
929
+ if (typeof this.pyodide.loadPackage === 'function') {
930
+ await this.pyodide.loadPackage(pkg);
931
+ }
932
+ } catch (err) {
933
+ void err;
851
934
  }
852
- } catch (err) {
853
- void err;
854
935
  }
855
936
  }
856
- }
857
937
 
858
- this._emitProgress({
859
- stage: 'ready',
860
- percent: 100,
861
- message: 'Python 3.12 WebAssembly Toolchain Ready'
862
- });
938
+ this._emitProgress({
939
+ stage: 'ready',
940
+ percent: 100,
941
+ message: 'Python 3.12 WebAssembly Toolchain Ready'
942
+ });
863
943
 
864
- return this.pyodide;
944
+ return this.pyodide;
945
+ } catch (err) {
946
+ this._loadingPromise = null;
947
+ throw err;
948
+ }
865
949
  })();
866
950
 
867
951
  return this._loadingPromise;
@@ -919,20 +1003,72 @@ export class PythonToolchainManager {
919
1003
 
920
1004
  const pyodide = await this.ensureLoaded();
921
1005
 
922
- // 1. Sync VFS files into Pyodide FS
1006
+ // 1. Sync VFS files into Pyodide FS (binary-safe + prune files deleted in VFS)
1007
+ const vfsSnapshotFiles = new Set<string>();
923
1008
  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);
1009
+ const syncVfsDir = (dirPath: string) => {
1010
+ try {
1011
+ if (typeof pyodide.FS.mkdirTree === 'function') {
1012
+ pyodide.FS.mkdirTree(dirPath);
1013
+ }
1014
+ const entries = req.vfs.readdirSync(dirPath);
1015
+ for (const entry of entries) {
1016
+ if (!entry || entry === '.' || entry === '..') continue;
1017
+ const fullPath = `${dirPath === '/' ? '' : dirPath}/${entry}`;
1018
+ try {
1019
+ const st = req.vfs.statSync(fullPath);
1020
+ if (st && typeof st.isDirectory === 'function' && st.isDirectory()) {
1021
+ syncVfsDir(fullPath);
1022
+ } else {
1023
+ const parentDir = fullPath.slice(0, fullPath.lastIndexOf('/')) || '/workspace';
1024
+ if (typeof pyodide.FS.mkdirTree === 'function') {
1025
+ pyodide.FS.mkdirTree(parentDir);
1026
+ }
1027
+ const rawContent = req.vfs.readFileSync(fullPath);
1028
+ pyodide.FS.writeFile(fullPath, rawContent);
1029
+ vfsSnapshotFiles.add(fullPath);
1030
+ }
1031
+ } catch (err) {
1032
+ void err;
1033
+ }
932
1034
  }
1035
+ } catch (err) {
1036
+ void err;
933
1037
  }
934
- } catch (err) {
935
- void err;
1038
+ };
1039
+ syncVfsDir('/workspace');
1040
+
1041
+ // Prune stale files in Pyodide FS that no longer exist in VFS before execution
1042
+ if (typeof pyodide.FS.readdir === 'function' && typeof pyodide.FS.unlink === 'function') {
1043
+ const pruneStalePyodideFiles = (dirPath: string) => {
1044
+ try {
1045
+ const pyEntries = pyodide.FS.readdir(dirPath);
1046
+ for (const f of pyEntries) {
1047
+ if (!f || f === '.' || f === '..') continue;
1048
+ const p = `${dirPath}/${f}`;
1049
+ let isDir = false;
1050
+ if (typeof pyodide.FS.stat === 'function' && typeof pyodide.FS.isDir === 'function') {
1051
+ try {
1052
+ isDir = Boolean(pyodide.FS.isDir(pyodide.FS.stat(p).mode));
1053
+ } catch (err) {
1054
+ void err;
1055
+ }
1056
+ }
1057
+ if (isDir) {
1058
+ pruneStalePyodideFiles(p);
1059
+ } else if (!vfsSnapshotFiles.has(p)) {
1060
+ try {
1061
+ pyodide.FS.unlink(p);
1062
+ } catch (err) {
1063
+ void err;
1064
+ }
1065
+ }
1066
+ }
1067
+ } catch (err) {
1068
+ void err;
1069
+ }
1070
+ };
1071
+ pruneStalePyodideFiles('/workspace');
936
1072
  }
937
1073
  }
938
1074
 
@@ -986,47 +1122,22 @@ export class PythonToolchainManager {
986
1122
  });
987
1123
  }
988
1124
 
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
-
1125
+ const fileLabel = JSON.stringify(req.entry || '<exec>');
1126
+ const encodedCode = JSON.stringify(codeToRun);
1019
1127
  const runnerWrapper = `
1020
- ${futureImports.join('\n')}
1021
1128
  import sys, tracemalloc
1022
1129
  if '/usr/lib/python' not in sys.path:
1023
1130
  sys.path.insert(0, '/usr/lib/python')
1024
1131
  if '/workspace' not in sys.path:
1025
1132
  sys.path.insert(0, '/workspace')
1133
+ if 'codelab_test' in sys.modules and hasattr(sys.modules['codelab_test'], '_reset_codelab_test'):
1134
+ sys.modules['codelab_test']._reset_codelab_test()
1026
1135
 
1136
+ _cl_user_code = ${encodedCode}
1137
+ _cl_ns = {'__name__': '__main__', '__file__': ${fileLabel}, '__builtins__': __builtins__}
1027
1138
  tracemalloc.start()
1028
1139
  try:
1029
- ${bodyLines.map((l) => ' ' + l).join('\n')}
1140
+ exec(compile(_cl_user_code, ${fileLabel}, 'exec'), _cl_ns)
1030
1141
  finally:
1031
1142
  _, _peak = tracemalloc.get_traced_memory()
1032
1143
  tracemalloc.stop()
@@ -1069,23 +1180,55 @@ finally:
1069
1180
  }
1070
1181
  }
1071
1182
 
1072
- // 2. Sync back files from Pyodide FS into VFS
1183
+ // 2. Sync back files from Pyodide FS into VFS (binary-safe + propagate Python deletions)
1073
1184
  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}`;
1185
+ const pyFilesAfter = new Set<string>();
1186
+ const syncBackPyodideDir = (dirPath: string) => {
1187
+ try {
1188
+ const entries = pyodide.FS.readdir(dirPath);
1189
+ for (const f of entries) {
1190
+ if (!f || f === '.' || f === '..') continue;
1191
+ const p = `${dirPath}/${f}`;
1192
+ try {
1193
+ let isDir = false;
1194
+ if (typeof pyodide.FS.stat === 'function' && typeof pyodide.FS.isDir === 'function') {
1195
+ const st = pyodide.FS.stat(p);
1196
+ isDir = Boolean(pyodide.FS.isDir(st.mode));
1197
+ }
1198
+ if (isDir) {
1199
+ if (typeof req.vfs.mkdirSync === 'function' && !req.vfs.existsSync(p)) {
1200
+ req.vfs.mkdirSync(p, { recursive: true });
1201
+ }
1202
+ syncBackPyodideDir(p);
1203
+ } else {
1204
+ const parentDir = p.slice(0, p.lastIndexOf('/')) || '/workspace';
1205
+ if (typeof req.vfs.mkdirSync === 'function' && !req.vfs.existsSync(parentDir)) {
1206
+ req.vfs.mkdirSync(parentDir, { recursive: true });
1207
+ }
1208
+ const rawBytes = pyodide.FS.readFile(p);
1209
+ req.vfs.writeFileSync(p, rawBytes);
1210
+ pyFilesAfter.add(p);
1211
+ }
1212
+ } catch (err) {
1213
+ void err;
1214
+ }
1215
+ }
1216
+ } catch (err) {
1217
+ void err;
1218
+ }
1219
+ };
1220
+ syncBackPyodideDir('/workspace');
1221
+
1222
+ if (typeof req.vfs.unlinkSync === 'function') {
1223
+ for (const existedBefore of vfsSnapshotFiles) {
1224
+ if (!pyFilesAfter.has(existedBefore)) {
1079
1225
  try {
1080
- const content = pyodide.FS.readFile(p, { encoding: 'utf8' });
1081
- req.vfs.writeFileSync(p, content);
1226
+ req.vfs.unlinkSync(existedBefore);
1082
1227
  } catch (err) {
1083
1228
  void err;
1084
1229
  }
1085
1230
  }
1086
1231
  }
1087
- } catch (err) {
1088
- void err;
1089
1232
  }
1090
1233
  }
1091
1234
 
@@ -1217,8 +1360,9 @@ function installPythonExtension(workbench: any, options: ExtendedPythonExtension
1217
1360
  for (const d of diags) {
1218
1361
  workbench._diagnosticsStore.add(d);
1219
1362
  }
1220
- if (typeof window !== 'undefined' && (window as any).monaco && workbench.editor) {
1221
- const model = workbench.editor.getModel();
1363
+ if (typeof window !== 'undefined' && (window as any).monaco) {
1364
+ const model = (workbench.models && typeof workbench.models.get === 'function' && workbench.models.get(file))
1365
+ || (workbench.activeFile === file && workbench.editor ? workbench.editor.getModel() : null);
1222
1366
  if (model) {
1223
1367
  const markers = diags.map((d) => ({
1224
1368
  startLineNumber: d.line,
@@ -0,0 +1,5 @@
1
+ export { guidedLabExtension } from './guided-lab';
2
+ export { javascriptExtension } from './javascript';
3
+ export { typescriptExtension } from './typescript';
4
+ export { cppExtension } from './cpp';
5
+ export { pythonExtension } from './python';