@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
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, {
@@ -1096,7 +1118,13 @@ function __initVirtualRuntime(rootScope) {
1096
1118
  });
1097
1119
  }
1098
1120
 
1121
+ let _activeStdin = '';
1122
+
1099
1123
  const fsShim = {
1124
+ _setActiveStdin(text) {
1125
+ _activeStdin = text !== undefined && text !== null ? String(text) : '';
1126
+ },
1127
+
1100
1128
  existsSync(p) {
1101
1129
  try {
1102
1130
  const np = normPath(p);
@@ -1263,13 +1291,6 @@ function __initVirtualRuntime(rootScope) {
1263
1291
  fsyncSync(fd) {
1264
1292
  const entry = fdTable.get(fd);
1265
1293
  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
1294
  },
1274
1295
 
1275
1296
  fdatasyncSync(fd) {
@@ -1310,12 +1331,6 @@ function __initVirtualRuntime(rootScope) {
1310
1331
  inode.mtimeMs = Date.now();
1311
1332
  entry.pos = writePos + chunk.byteLength;
1312
1333
 
1313
- deletedInspectorCache.set(entry.path, {
1314
- data: inode.data.slice(),
1315
- mtimeMs: inode.mtimeMs,
1316
- deletedAtMs: null
1317
- });
1318
-
1319
1334
  return chunk.byteLength;
1320
1335
  },
1321
1336
 
@@ -1334,6 +1349,11 @@ function __initVirtualRuntime(rootScope) {
1334
1349
  },
1335
1350
 
1336
1351
  readFileSync(p, opts) {
1352
+ if (p === 0 || p === '/dev/stdin') {
1353
+ const stdinBuf = VirtualBuffer.from(String(_activeStdin || ''), 'utf8');
1354
+ const encoding = typeof opts === 'string' ? opts : (opts && opts.encoding);
1355
+ return encoding ? stdinBuf.toString(encoding) : stdinBuf;
1356
+ }
1337
1357
  const np = normPath(p);
1338
1358
  if (dirs.has(np)) throw fsError('EISDIR', 'read', p, 'illegal operation on a directory');
1339
1359
  const inode = files.get(np);
@@ -1367,7 +1387,7 @@ function __initVirtualRuntime(rootScope) {
1367
1387
  inode.mode = 0o100000 | (Number(opts.mode) & 0o777);
1368
1388
  }
1369
1389
  }
1370
- deletedInspectorCache.set(np, { data: bytes.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1390
+ deletedInspectorCache.delete(np);
1371
1391
  },
1372
1392
 
1373
1393
  chmodSync(p, mode) {
@@ -1396,7 +1416,7 @@ function __initVirtualRuntime(rootScope) {
1396
1416
  combined.set(chunk, inode.data.byteLength);
1397
1417
  inode.data = combined;
1398
1418
  inode.mtimeMs = Date.now();
1399
- deletedInspectorCache.set(np, { data: combined.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1419
+ deletedInspectorCache.delete(np);
1400
1420
  },
1401
1421
 
1402
1422
  truncateSync(p, len = 0) {
@@ -1412,7 +1432,6 @@ function __initVirtualRuntime(rootScope) {
1412
1432
  inode.data = grown;
1413
1433
  }
1414
1434
  inode.mtimeMs = Date.now();
1415
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1416
1435
  },
1417
1436
 
1418
1437
  renameSync(oldP, newP) {
@@ -1473,16 +1492,14 @@ function __initVirtualRuntime(rootScope) {
1473
1492
  if (fdEntry.path === src) fdEntry.path = dst;
1474
1493
  }
1475
1494
  deletedInspectorCache.delete(src);
1476
- deletedInspectorCache.set(dst, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1495
+ deletedInspectorCache.delete(dst);
1477
1496
  },
1478
1497
 
1479
1498
  unlinkSync(p) {
1480
1499
  const np = normPath(p);
1481
1500
  const inode = files.get(np);
1482
1501
  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
- }
1502
+ recordDeletedForInspector(np, inode.data, inode.mtimeMs);
1486
1503
  files.delete(np);
1487
1504
  },
1488
1505
 
@@ -1499,9 +1516,7 @@ function __initVirtualRuntime(rootScope) {
1499
1516
  for (const [fPath, inode] of Array.from(files.entries())) {
1500
1517
  if (fPath.startsWith(prefix)) {
1501
1518
  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
- }
1519
+ recordDeletedForInspector(fPath, inode.data, inode.mtimeMs);
1505
1520
  files.delete(fPath);
1506
1521
  }
1507
1522
  }
@@ -1698,6 +1713,10 @@ function __initVirtualRuntime(rootScope) {
1698
1713
 
1699
1714
  items.sort((a, b) => a.path.localeCompare(b.path));
1700
1715
  return items;
1716
+ },
1717
+
1718
+ _listOpenFds() {
1719
+ return Array.from(fdTable.keys());
1701
1720
  }
1702
1721
  };
1703
1722
 
@@ -1852,6 +1871,13 @@ function __initVirtualRuntime(rootScope) {
1852
1871
  };
1853
1872
 
1854
1873
  fsShim.promises = fsPromises;
1874
+ fsShim._exportRawState = () => {
1875
+ const clonedFiles = new Map();
1876
+ for (const [k, v] of files.entries()) {
1877
+ clonedFiles.set(k, v.data instanceof Uint8Array ? v.data.slice() : new Uint8Array(v.data || 0));
1878
+ }
1879
+ return { files: clonedFiles, dirs: new Set(dirs) };
1880
+ };
1855
1881
 
1856
1882
  return fsShim;
1857
1883
  }
@@ -3075,6 +3101,7 @@ function __initVirtualRuntime(rootScope) {
3075
3101
  responseHeaders: {},
3076
3102
  _t0: performance.now()
3077
3103
  };
3104
+ if (httpTrace.length >= 500) httpTrace.shift();
3078
3105
  httpTrace.push(traceEntry);
3079
3106
  this._traceEntry = traceEntry;
3080
3107
 
@@ -4066,6 +4093,7 @@ function __initVirtualRuntime(rootScope) {
4066
4093
  this._peer = serverSocket;
4067
4094
  this.connecting = false;
4068
4095
 
4096
+ if (sharedTrace.length >= 500) sharedTrace.shift();
4069
4097
  sharedTrace.push({
4070
4098
  protocol: 'TCP',
4071
4099
  event: 'connect',
@@ -4580,13 +4608,17 @@ function __initVirtualRuntime(rootScope) {
4580
4608
  function transpileTS(source, filename = 'module.ts', opts = {}) {
4581
4609
  // `keepEsm` leaves `import`/`export` statements intact so the output can run
4582
4610
  // natively in a browser as an ES module (used by the built-in preview server).
4583
- const keepEsm = Boolean(opts && opts.keepEsm);
4584
- const isTS = /\.(ts|tsx|mts|cts)$/i.test(filename)
4611
+ const keepEsm = Boolean(opts && (opts.keepEsm || opts.expressionOnly));
4612
+ const expressionOnly = Boolean(opts && opts.expressionOnly);
4613
+ const isTS = expressionOnly
4614
+ || /\.(ts|tsx|mts|cts)$/i.test(filename)
4585
4615
  || /^[ \t]*(?:export\s+)?(?:abstract\s+class\s+[A-Za-z_$]|declare\s+(?:const|let|var|function|class|namespace|module|global)\b|interface\s+[A-Za-z_$][A-Za-z0-9_$]*|type\s+[A-Za-z_$][A-Za-z0-9_$]*\s*(?:<[^>]*>)?\s*=|enum\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{|namespace\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{)/m.test(source);
4586
- const hasESM = /^\s*(?:import|export)\b/m.test(source)
4616
+ const hasESM = !expressionOnly && (
4617
+ /^\s*(?:import|export)\b/m.test(source)
4587
4618
  || /\bexport\s*\{/.test(source)
4588
4619
  || /\bimport\s*\{/.test(source)
4589
- || /\bexport\s+default\b/.test(source);
4620
+ || /\bexport\s+default\b/.test(source)
4621
+ );
4590
4622
  const hasJsx = detectJsxSyntax(source, filename);
4591
4623
  if (!isTS && !hasESM && !hasJsx) return source;
4592
4624
 
@@ -4594,7 +4626,7 @@ function __initVirtualRuntime(rootScope) {
4594
4626
  if (hasJsx) {
4595
4627
  const { pragma, frag } = readJsxPragma(source);
4596
4628
  const hasReactBinding = /\bimport\s+(?!type\b)(?:\*\s+as\s+React\b|React\b)|(?:\bconst|\blet|\bvar|\bfunction|\bclass)\s+React\b|\bReact\s*=/.test(source);
4597
- const needsReact = pragma === 'React.createElement' && (keepEsm ? !hasReactBinding : !/\bReact\b/.test(source));
4629
+ const needsReact = !expressionOnly && pragma === 'React.createElement' && (keepEsm ? !hasReactBinding : !/\bReact\b/.test(source));
4598
4630
  const transformed = jsxTransform(source, { pragma, frag });
4599
4631
  if (transformed !== source) {
4600
4632
  source = transformed;
@@ -4682,18 +4714,80 @@ function __initVirtualRuntime(rootScope) {
4682
4714
  i = j;
4683
4715
  continue;
4684
4716
  }
4685
- // Template literal
4717
+ // Template literal (recursively transpile TypeScript inside ${...} expressions)
4686
4718
  if (ch === '`') {
4687
4719
  let j = i + 1;
4688
- let depth = 0;
4720
+ let rebuilt = '`';
4689
4721
  while (j < len) {
4690
- if (source[j] === '\\') { j += 2; continue; }
4691
- if (source[j] === '$' && source[j + 1] === '{') { depth++; j += 2; continue; }
4692
- if (source[j] === '}' && depth > 0) { depth--; j++; continue; }
4693
- if (source[j] === '`' && depth === 0) { j++; break; }
4722
+ if (source[j] === '\\') {
4723
+ rebuilt += source.slice(j, j + 2);
4724
+ j += 2;
4725
+ continue;
4726
+ }
4727
+ if (source[j] === '`' ) {
4728
+ rebuilt += '`';
4729
+ j++;
4730
+ break;
4731
+ }
4732
+ if (source[j] === '$' && source[j + 1] === '{') {
4733
+ j += 2;
4734
+ const exprStart = j;
4735
+ let braceDepth = 1;
4736
+ while (j < len && braceDepth > 0) {
4737
+ const ec = source[j];
4738
+ const en = source[j + 1];
4739
+ if (ec === '/' && en === '/') {
4740
+ j += 2;
4741
+ while (j < len && source[j] !== '\n') j++;
4742
+ continue;
4743
+ }
4744
+ if (ec === '/' && en === '*') {
4745
+ j += 2;
4746
+ while (j < len && !(source[j] === '*' && source[j + 1] === '/')) j++;
4747
+ j += 2;
4748
+ continue;
4749
+ }
4750
+ if (ec === "'" || ec === '"') {
4751
+ const q = ec;
4752
+ j++;
4753
+ while (j < len && source[j] !== q && source[j] !== '\n') {
4754
+ if (source[j] === '\\') j += 2;
4755
+ else j++;
4756
+ }
4757
+ if (j < len && source[j] === q) j++;
4758
+ continue;
4759
+ }
4760
+ if (ec === '`') {
4761
+ j++;
4762
+ let nestedDepth = 0;
4763
+ while (j < len) {
4764
+ if (source[j] === '\\') { j += 2; continue; }
4765
+ if (source[j] === '$' && source[j + 1] === '{') { nestedDepth++; j += 2; continue; }
4766
+ if (source[j] === '}' && nestedDepth > 0) { nestedDepth--; j++; continue; }
4767
+ if (source[j] === '`' && nestedDepth === 0) { j++; break; }
4768
+ j++;
4769
+ }
4770
+ continue;
4771
+ }
4772
+ if (ec === '{') braceDepth++;
4773
+ else if (ec === '}') {
4774
+ braceDepth--;
4775
+ if (braceDepth === 0) break;
4776
+ }
4777
+ j++;
4778
+ }
4779
+ const rawExpr = source.slice(exprStart, j);
4780
+ const transpiledExpr = isTS
4781
+ ? transpileTS(rawExpr, filename, { expressionOnly: true })
4782
+ : rawExpr;
4783
+ rebuilt += '${' + transpiledExpr + '}';
4784
+ if (j < len && source[j] === '}') j++;
4785
+ continue;
4786
+ }
4787
+ rebuilt += source[j];
4694
4788
  j++;
4695
4789
  }
4696
- code += mask(source.slice(i, j));
4790
+ code += mask(rebuilt);
4697
4791
  i = j;
4698
4792
  continue;
4699
4793
  }
@@ -5067,8 +5161,8 @@ function __initVirtualRuntime(rootScope) {
5067
5161
  };
5068
5162
  code = stripReturnTypes(code);
5069
5163
 
5070
- // Strip parameter type annotations inside `(...)` (supports multi-line parameter lists and default value `()` calls)
5071
- code = code.replace(/\(((?:[^()]|\([^()]*\))*)\)/g, (full, inner) => {
5164
+ // Strip parameter type annotations inside `(...)` from innermost parens outward so nested callbacks work
5165
+ const stripParensParamTypes = (full, inner) => {
5072
5166
  if (!inner.includes(':')) return full;
5073
5167
  if (inner.includes('?') && !/[A-Za-z0-9_$}\]]\s*\?\s*:/.test(inner)) return full;
5074
5168
  if (/[{}]/.test(inner) && !/\}\s*\??\s*:/.test(inner) && !/:\s*[A-Za-z_$][A-Za-z0-9_$.<>[\]|&\s]*\{/.test(inner)) {
@@ -5082,7 +5176,12 @@ function __initVirtualRuntime(rootScope) {
5082
5176
  const parts = splitTopLevel(inner, ',');
5083
5177
  const cleaned = parts.map((part) => cleanSingleParam(part));
5084
5178
  return `(${cleaned.join(',')})`;
5085
- });
5179
+ };
5180
+ do {
5181
+ prevCode = code;
5182
+ code = code.replace(/\(([^()]*)\)/g, stripParensParamTypes);
5183
+ } while (code !== prevCode);
5184
+ code = code.replace(/\(((?:[^()]|\([^()]*\))*)\)/g, stripParensParamTypes);
5086
5185
 
5087
5186
  // Strip variable type annotations: `const x: Type =`, `let y: Type =`
5088
5187
  code = code.replace(/\b(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*:\s*[^=;\n]+(?<![=!<>])=(?![=>])/g, '$1 $2 =');
@@ -5213,7 +5312,31 @@ function __initVirtualRuntime(rootScope) {
5213
5312
  hasEsmExport = true;
5214
5313
  return `Object.assign(exports, require(${mod.trim()}));`;
5215
5314
  });
5216
- code = code.replace(/\bexport\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
5315
+ const collectBindingIds = (pattern) => {
5316
+ const ids = [];
5317
+ const inner = pattern.trim().replace(/^[\[{]|[\]}]$/g, '');
5318
+ const isObj = pattern.trim().startsWith('{');
5319
+ for (const rawPart of splitTopLevel(inner, ',')) {
5320
+ let part = rawPart.trim();
5321
+ if (!part) continue;
5322
+ if (part.startsWith('...')) {
5323
+ part = part.slice(3).trim();
5324
+ } else if (isObj && part.includes(':')) {
5325
+ const colonIdx = part.indexOf(':');
5326
+ part = part.slice(colonIdx + 1).trim();
5327
+ }
5328
+ const eqIdx = part.indexOf('=');
5329
+ if (eqIdx !== -1) part = part.slice(0, eqIdx).trim();
5330
+ if ((part.startsWith('{') && part.endsWith('}')) || (part.startsWith('[') && part.endsWith(']'))) {
5331
+ ids.push(...collectBindingIds(part));
5332
+ } else if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(part)) {
5333
+ ids.push(part);
5334
+ }
5335
+ }
5336
+ return ids;
5337
+ };
5338
+
5339
+ code = code.replace(/\bexport\s+default\s+(async\s+function\s*\*|function\s*\*|async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
5217
5340
  hasEsmExport = true;
5218
5341
  defaultExportName = name;
5219
5342
  return `${kw} ${name}`;
@@ -5222,11 +5345,16 @@ function __initVirtualRuntime(rootScope) {
5222
5345
  hasEsmExport = true;
5223
5346
  return 'exports.default = ';
5224
5347
  });
5225
- code = code.replace(/\bexport\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
5348
+ code = code.replace(/\bexport\s+(async\s+function\s*\*|function\s*\*|async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
5226
5349
  hasEsmExport = true;
5227
5350
  exportedNames.push(name);
5228
5351
  return `${kw} ${name}`;
5229
5352
  });
5353
+ code = code.replace(/\bexport\s+(const|let|var)\s+(\{[^;=\n]+\}|\[[^;=\n]+\])\s*=/gm, (_, kw, pat) => {
5354
+ hasEsmExport = true;
5355
+ exportedNames.push(...collectBindingIds(pat));
5356
+ return `${kw} ${pat} =`;
5357
+ });
5230
5358
  code = code.replace(/\bexport\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
5231
5359
  hasEsmExport = true;
5232
5360
  exportedNames.push(name);
@@ -6358,7 +6486,16 @@ function __initVirtualRuntime(rootScope) {
6358
6486
  const activePortTable = optPortTable || portTable || _defaultPortTable;
6359
6487
  resourceTracker.pid = pid;
6360
6488
 
6361
- const vfs = optVfs || createVirtualFs(files);
6489
+ const prevCwdGetter = _activeCwdGetter;
6490
+ let currentCwd = (typeof options.cwd === 'string' && options.cwd.trim())
6491
+ ? VirtualPath.resolve('/workspace', options.cwd.trim())
6492
+ : '/workspace';
6493
+ _activeCwdGetter = () => currentCwd;
6494
+
6495
+ const vfs = optVfs || createVirtualFs(files, { cwdGetter: () => currentCwd });
6496
+ const initialOpenFds = typeof vfs._listOpenFds === 'function'
6497
+ ? new Set(vfs._listOpenFds())
6498
+ : null;
6362
6499
  if (optVfs && files && typeof files === 'object') {
6363
6500
  for (const [fPath, content] of Object.entries(files)) {
6364
6501
  const abs = fPath.startsWith('/') ? fPath : '/workspace/' + fPath;
@@ -6371,6 +6508,9 @@ function __initVirtualRuntime(rootScope) {
6371
6508
  }
6372
6509
  }
6373
6510
  }
6511
+ if (typeof vfs._setActiveStdin === 'function') {
6512
+ vfs._setActiveStdin(options && options.stdin ? String(options.stdin) : '');
6513
+ }
6374
6514
  const vhttp = createVirtualHttp(resourceTracker, activePortTable);
6375
6515
  const vnet = createVirtualNet(resourceTracker, vhttp.getTrace());
6376
6516
 
@@ -6393,6 +6533,10 @@ function __initVirtualRuntime(rootScope) {
6393
6533
  }
6394
6534
  }
6395
6535
 
6536
+ const initialVfsState = (options && options._captureVfsDiff && typeof vfs._exportRawState === 'function')
6537
+ ? vfs._exportRawState()
6538
+ : null;
6539
+
6396
6540
  // Custom timer wrappers supporting .unref() / .ref() and active handle tracking
6397
6541
  function makeTimerHandle(rawId, isInterval) {
6398
6542
  const handle = {
@@ -6752,11 +6896,9 @@ function __initVirtualRuntime(rootScope) {
6752
6896
  hrtimeFn.bigint = () => BigInt(Math.round(performance.now() * 1e6));
6753
6897
 
6754
6898
  let syncExecDepth = 0;
6755
- let currentCwd = '/workspace';
6756
- _activeCwdGetter = () => currentCwd;
6757
6899
 
6758
6900
  const sandboxProcess = Object.assign(new EventEmitter(), {
6759
- env: { NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' },
6901
+ env: Object.assign({ NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' }, options.env || {}),
6760
6902
  argv: argv || ['node', entry.startsWith('/') ? entry : `/workspace/${entry}`],
6761
6903
  argv0: 'node',
6762
6904
  execArgv: [],
@@ -6836,6 +6978,9 @@ function __initVirtualRuntime(rootScope) {
6836
6978
  }
6837
6979
 
6838
6980
  // Immediately cancel all active timers and immediates
6981
+ if (typeof vfs._setActiveStdin === 'function') {
6982
+ vfs._setActiveStdin('');
6983
+ }
6839
6984
  for (const rawId of resourceTracker.allTimers) {
6840
6985
  clearTimeout(rawId);
6841
6986
  clearInterval(rawId);
@@ -8751,6 +8896,9 @@ function __initVirtualRuntime(rootScope) {
8751
8896
  hasExited = true;
8752
8897
  try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime exit listener failed', err); }
8753
8898
  }
8899
+ if (typeof vfs._setActiveStdin === 'function') {
8900
+ vfs._setActiveStdin('');
8901
+ }
8754
8902
  for (const rawId of resourceTracker.allTimers) {
8755
8903
  clearTimeout(rawId);
8756
8904
  clearInterval(rawId);
@@ -8767,12 +8915,56 @@ function __initVirtualRuntime(rootScope) {
8767
8915
  if (!isBackground) {
8768
8916
  vhttp.closeAllServers();
8769
8917
  vnet.closeAllServers();
8918
+ if (initialOpenFds && typeof vfs._listOpenFds === 'function' && typeof vfs.closeSync === 'function') {
8919
+ for (const fd of vfs._listOpenFds()) {
8920
+ if (!initialOpenFds.has(fd)) {
8921
+ try { vfs.closeSync(fd); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime closeSync leak cleanup failed', { fd, err }); }
8922
+ }
8923
+ }
8924
+ }
8770
8925
  }
8926
+ _activeCwdGetter = prevCwdGetter;
8771
8927
  }
8772
8928
 
8773
8929
  const failedTests = testResults.filter((t) => !t.passed).length;
8774
8930
  if (failedTests > 0 && exitCode === 0) exitCode = 1;
8775
8931
 
8932
+ let vfsChanges = undefined;
8933
+ if (initialVfsState && typeof vfs._exportRawState === 'function') {
8934
+ const finalVfsState = vfs._exportRawState();
8935
+ const modifiedFiles = {};
8936
+ const deletedFiles = [];
8937
+ const createdDirs = [];
8938
+ const isNodeModulesPath = (p) => p === '/workspace/node_modules' || p.startsWith('/workspace/node_modules/');
8939
+ const bytesEqual = (a, b) => {
8940
+ if (!a || !b || a.byteLength !== b.byteLength) return false;
8941
+ for (let i = 0; i < a.byteLength; i++) {
8942
+ if (a[i] !== b[i]) return false;
8943
+ }
8944
+ return true;
8945
+ };
8946
+
8947
+ for (const d of finalVfsState.dirs) {
8948
+ if (!initialVfsState.dirs.has(d) && !isNodeModulesPath(d)) {
8949
+ createdDirs.push(d);
8950
+ }
8951
+ }
8952
+ for (const [fPath, data] of finalVfsState.files.entries()) {
8953
+ if (isNodeModulesPath(fPath)) continue;
8954
+ const prev = initialVfsState.files.get(fPath);
8955
+ if (!prev || !bytesEqual(prev, data)) {
8956
+ modifiedFiles[fPath] = data;
8957
+ }
8958
+ }
8959
+ for (const fPath of initialVfsState.files.keys()) {
8960
+ if (isNodeModulesPath(fPath)) continue;
8961
+ if (!finalVfsState.files.has(fPath)) {
8962
+ deletedFiles.push(fPath);
8963
+ }
8964
+ }
8965
+ vfsChanges = { modifiedFiles, deletedFiles, createdDirs };
8966
+ }
8967
+
8776
8968
  return {
8777
8969
  ok: exitCode === 0,
8778
8970
  exitCode,
@@ -8788,6 +8980,7 @@ function __initVirtualRuntime(rootScope) {
8788
8980
  failed: failedTests
8789
8981
  },
8790
8982
  fsSnapshot: typeof vfs.getSnapshot === 'function' ? vfs.getSnapshot() : [],
8983
+ ...(vfsChanges ? { vfsChanges } : {}),
8791
8984
  httpTrace: [...vhttp.getTrace(), ...vnet.getTrace()],
8792
8985
  replValue: replValue !== undefined ? formatConsoleArg(replValue) : undefined
8793
8986
  };
@@ -9176,14 +9369,70 @@ function __initVirtualRuntime(rootScope) {
9176
9369
 
9177
9370
  exec(sql) {
9178
9371
  const cleaned = stripSqlComments(sql);
9179
- const statements = cleaned.split(';').map((s) => s.trim()).filter(Boolean);
9372
+ const statements = [];
9373
+ let cur = '';
9374
+ let i = 0;
9375
+ while (i < cleaned.length) {
9376
+ const ch = cleaned[i];
9377
+ if (ch === "'" || ch === '"') {
9378
+ const quote = ch;
9379
+ cur += ch;
9380
+ i++;
9381
+ while (i < cleaned.length) {
9382
+ if (cleaned[i] === quote && cleaned[i + 1] === quote) {
9383
+ cur += quote + quote;
9384
+ i += 2;
9385
+ continue;
9386
+ }
9387
+ if (cleaned[i] === '\\' && quote === '"') {
9388
+ cur += cleaned.slice(i, i + 2);
9389
+ i += 2;
9390
+ continue;
9391
+ }
9392
+ cur += cleaned[i];
9393
+ if (cleaned[i] === quote) {
9394
+ i++;
9395
+ break;
9396
+ }
9397
+ i++;
9398
+ }
9399
+ continue;
9400
+ }
9401
+ if (ch === ';') {
9402
+ const trimmed = cur.trim();
9403
+ if (trimmed) statements.push(trimmed);
9404
+ cur = '';
9405
+ i++;
9406
+ continue;
9407
+ }
9408
+ cur += ch;
9409
+ i++;
9410
+ }
9411
+ if (cur.trim()) statements.push(cur.trim());
9180
9412
  for (const s of statements) {
9181
9413
  this.run(s);
9182
9414
  }
9183
9415
  }
9184
9416
 
9185
9417
  transaction(fn) {
9186
- return (...args) => fn(...args);
9418
+ const db = this;
9419
+ return (...args) => {
9420
+ const snapshot = new Map();
9421
+ for (const [tblName, tbl] of db.tables.entries()) {
9422
+ snapshot.set(tblName, {
9423
+ columns: tbl.columns.map((c) => Object.assign({}, c)),
9424
+ rows: tbl.rows.map((r) => Object.assign({}, r)),
9425
+ autoInc: tbl.autoInc
9426
+ });
9427
+ }
9428
+ try {
9429
+ return fn(...args);
9430
+ } catch (err) {
9431
+ db.tables = snapshot;
9432
+ db._persistToVfs();
9433
+ throw err;
9434
+ }
9435
+ };
9187
9436
  }
9188
9437
 
9189
9438
  close() {
@@ -9472,9 +9721,11 @@ function __workerMessageLoop(workerScope) {
9472
9721
  const msg = event.data || {};
9473
9722
  const { requestId, type, payload = {} } = msg;
9474
9723
  if (type !== 'execute') return;
9724
+ workerScope.postMessage({ requestId, type: 'started' });
9475
9725
  try {
9476
9726
  const result = await runtime.executeInVirtualRuntime({
9477
9727
  ...payload,
9728
+ _captureVfsDiff: true,
9478
9729
  onStdout(text) {
9479
9730
  workerScope.postMessage({ requestId, type: 'stdout', text });
9480
9731
  },
@@ -9526,7 +9777,10 @@ function _ensureWorkerUrl() {
9526
9777
  }
9527
9778
 
9528
9779
  function _ensureWarmWorker() {
9529
- if (_warmWorker) return _warmWorker;
9780
+ if (_warmWorker && typeof Worker === 'function' && _warmWorker instanceof Worker) {
9781
+ return _warmWorker;
9782
+ }
9783
+ if (_warmWorker) _destroyWarmWorker();
9530
9784
  _warmWorker = new Worker(_ensureWorkerUrl());
9531
9785
  return _warmWorker;
9532
9786
  }
@@ -9539,6 +9793,14 @@ function _destroyWarmWorker() {
9539
9793
  _warmWorkerBusy = false;
9540
9794
  }
9541
9795
 
9796
+ _hostRuntime.destroyWorkerPool = function destroyWorkerPool() {
9797
+ _destroyWarmWorker();
9798
+ if (_cachedWorkerUrl && typeof URL !== 'undefined' && typeof URL.revokeObjectURL === 'function') {
9799
+ try { URL.revokeObjectURL(_cachedWorkerUrl); } catch (err) { _hostLogger.debug('revokeObjectURL failed', err); }
9800
+ }
9801
+ _cachedWorkerUrl = null;
9802
+ };
9803
+
9542
9804
  _hostRuntime.cancelWorkerExecution = function cancelWorkerExecution(reason = 'Execution cancelled', instanceId) {
9543
9805
  let cancelledAny = false;
9544
9806
  for (const [jobId, job] of Array.from(_activeWorkerJobs.entries())) {
@@ -9551,11 +9813,118 @@ _hostRuntime.cancelWorkerExecution = function cancelWorkerExecution(reason = 'Ex
9551
9813
  return cancelledAny;
9552
9814
  };
9553
9815
 
9816
+ function _extractWorkerFilesFromVfs(vfs) {
9817
+ const extracted = {};
9818
+ if (!vfs || typeof vfs !== 'object') return extracted;
9819
+ try {
9820
+ if (typeof vfs._exportRawState === 'function') {
9821
+ const st = vfs._exportRawState();
9822
+ for (const [absPath, bytes] of st.files.entries()) {
9823
+ extracted[absPath] = bytes;
9824
+ }
9825
+ return extracted;
9826
+ }
9827
+ if (vfs.files instanceof Map) {
9828
+ for (const [absPath, entry] of vfs.files.entries()) {
9829
+ if (!entry) continue;
9830
+ const data = entry.data !== undefined ? entry.data : entry;
9831
+ if (typeof data === 'string') {
9832
+ extracted[absPath] = data;
9833
+ } else if (data instanceof Uint8Array) {
9834
+ extracted[absPath] = data.slice();
9835
+ } else if (ArrayBuffer.isView(data)) {
9836
+ extracted[absPath] = new Uint8Array(data.buffer, data.byteOffset, data.byteLength).slice();
9837
+ }
9838
+ }
9839
+ return extracted;
9840
+ }
9841
+ if (typeof vfs.readdirSync === 'function' && typeof vfs.readFileSync === 'function') {
9842
+ const walk = (dir) => {
9843
+ let entries = [];
9844
+ try { entries = vfs.readdirSync(dir); } catch (_) { return; }
9845
+ for (const name of entries) {
9846
+ const full = dir === '/' ? '/' + name : dir + '/' + name;
9847
+ let isDir = false;
9848
+ try { isDir = vfs.statSync(full).isDirectory(); } catch (_) { isDir = false; }
9849
+ if (isDir) walk(full);
9850
+ else {
9851
+ try {
9852
+ const raw = vfs.readFileSync(full);
9853
+ extracted[full] = raw instanceof Uint8Array
9854
+ ? raw.slice()
9855
+ : (typeof raw === 'string' ? raw : String(raw ?? ''));
9856
+ } catch (err) {
9857
+ _hostLogger.debug('_extractWorkerFilesFromVfs: skip unreadable entry', full, err);
9858
+ }
9859
+ }
9860
+ }
9861
+ };
9862
+ walk('/workspace');
9863
+ walk('/tmp');
9864
+ }
9865
+ } catch (err) {
9866
+ _hostLogger.debug('_extractWorkerFilesFromVfs failed', err);
9867
+ }
9868
+ return extracted;
9869
+ }
9870
+
9871
+ function _applyWorkerVfsChanges(vfs, vfsChanges) {
9872
+ if (!vfs || !vfsChanges || typeof vfsChanges !== 'object') return;
9873
+ const { createdDirs = [], modifiedFiles = {}, deletedFiles = [] } = vfsChanges;
9874
+ try {
9875
+ if (Array.isArray(createdDirs) && typeof vfs.mkdirSync === 'function') {
9876
+ for (const dir of createdDirs) {
9877
+ try {
9878
+ vfs.mkdirSync(dir, { recursive: true });
9879
+ } catch (err) {
9880
+ _hostLogger.debug('_applyWorkerVfsChanges: mkdirSync failed', dir, err);
9881
+ }
9882
+ }
9883
+ }
9884
+ if (modifiedFiles && typeof modifiedFiles === 'object') {
9885
+ for (const [absPath, rawBytes] of Object.entries(modifiedFiles)) {
9886
+ const slashIdx = absPath.lastIndexOf('/');
9887
+ if (slashIdx > 0 && typeof vfs.mkdirSync === 'function') {
9888
+ try {
9889
+ vfs.mkdirSync(absPath.slice(0, slashIdx), { recursive: true });
9890
+ } catch (err) {
9891
+ _hostLogger.debug('_applyWorkerVfsChanges: parent mkdirSync failed', absPath, err);
9892
+ }
9893
+ }
9894
+ const payload = rawBytes instanceof Uint8Array
9895
+ ? rawBytes
9896
+ : (ArrayBuffer.isView(rawBytes)
9897
+ ? new Uint8Array(rawBytes.buffer, rawBytes.byteOffset, rawBytes.byteLength)
9898
+ : rawBytes);
9899
+ if (typeof vfs.writeFileSync === 'function') {
9900
+ vfs.writeFileSync(absPath, payload);
9901
+ } else if (typeof vfs.writeFile === 'function') {
9902
+ vfs.writeFile(absPath, payload);
9903
+ }
9904
+ }
9905
+ }
9906
+ if (Array.isArray(deletedFiles)) {
9907
+ for (const absPath of deletedFiles) {
9908
+ try {
9909
+ if (typeof vfs.unlinkSync === 'function') vfs.unlinkSync(absPath);
9910
+ else if (typeof vfs.rmSync === 'function') vfs.rmSync(absPath, { force: true });
9911
+ } catch (err) {
9912
+ _hostLogger.debug('_applyWorkerVfsChanges: delete failed', absPath, err);
9913
+ }
9914
+ }
9915
+ }
9916
+ } catch (err) {
9917
+ _hostLogger.debug('_applyWorkerVfsChanges failed', err);
9918
+ }
9919
+ }
9920
+
9554
9921
  _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9555
9922
  const isNonJs =
9556
9923
  Boolean(options.wasmBinary) ||
9557
9924
  Boolean(options.cppCompiler) ||
9558
9925
  Boolean(options.pythonCompiler) ||
9926
+ Boolean(options.activePortTable) ||
9927
+ Boolean(options.portTable) ||
9559
9928
  (typeof options.entry === 'string' && /\.(cpp|cc|cxx|wasm|py)$/i.test(options.entry));
9560
9929
  if (
9561
9930
  isNonJs ||
@@ -9575,6 +9944,10 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9575
9944
  _hostRuntime.cancelWorkerExecution('Execution cancelled by new run', instanceId);
9576
9945
  }
9577
9946
 
9947
+ const mergedFiles = options.vfs
9948
+ ? Object.assign(_extractWorkerFilesFromVfs(options.vfs), options.files || {})
9949
+ : options.files;
9950
+
9578
9951
  return new Promise((resolve) => {
9579
9952
  let worker;
9580
9953
  let isWarmWorker = false;
@@ -9593,9 +9966,23 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9593
9966
  return;
9594
9967
  }
9595
9968
 
9969
+ const startTime = typeof performance !== 'undefined' ? performance.now() : Date.now();
9596
9970
  const timeoutMs = options.timeoutMs || 15000;
9597
9971
  let settled = false;
9972
+ let userCodeStarted = false;
9598
9973
  let abortListener = null;
9974
+ const streamedStdoutChunks = [];
9975
+ const streamedStderrChunks = [];
9976
+ const streamedTestResults = [];
9977
+
9978
+ const buildTestSummary = () => {
9979
+ const failed = streamedTestResults.filter((t) => !t.passed).length;
9980
+ return {
9981
+ total: streamedTestResults.length,
9982
+ passed: streamedTestResults.length - failed,
9983
+ failed
9984
+ };
9985
+ };
9599
9986
 
9600
9987
  function releaseWorker(terminateWorker) {
9601
9988
  if (options.signal && abortListener) {
@@ -9622,14 +10009,16 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9622
10009
  if (settled) return;
9623
10010
  settled = true;
9624
10011
  releaseWorker(true);
10012
+ const timeoutMsg = `Execution timed out after ${timeoutMs}ms (infinite loop or hung timer terminated).\n`;
9625
10013
  resolve({
9626
10014
  ok: false,
9627
10015
  timedOut: true,
9628
10016
  exitCode: 124,
9629
10017
  durationMs: timeoutMs,
9630
- stdout: '',
9631
- stderr: `Execution timed out after ${timeoutMs}ms (infinite loop or hung timer terminated).\n`,
9632
- testResults: [],
10018
+ stdout: streamedStdoutChunks.join(''),
10019
+ stderr: streamedStderrChunks.join('') + timeoutMsg,
10020
+ testResults: streamedTestResults.slice(),
10021
+ testSummary: buildTestSummary(),
9633
10022
  fsSnapshot: [],
9634
10023
  httpTrace: [],
9635
10024
  error: { message: `Execution timed out after ${timeoutMs}ms` }
@@ -9644,14 +10033,16 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9644
10033
  settled = true;
9645
10034
  clearTimeout(timer);
9646
10035
  releaseWorker(true);
10036
+ const elapsed = Math.max(0, (typeof performance !== 'undefined' ? performance.now() : Date.now()) - startTime);
9647
10037
  resolve({
9648
10038
  ok: false,
9649
10039
  cancelled: true,
9650
10040
  exitCode: 130,
9651
- durationMs: 0,
9652
- stdout: '',
9653
- stderr: `${reason}\n`,
9654
- testResults: [],
10041
+ durationMs: elapsed,
10042
+ stdout: streamedStdoutChunks.join(''),
10043
+ stderr: streamedStderrChunks.join('') + `${reason}\n`,
10044
+ testResults: streamedTestResults.slice(),
10045
+ testSummary: buildTestSummary(),
9655
10046
  fsSnapshot: [],
9656
10047
  httpTrace: [],
9657
10048
  error: { message: reason }
@@ -9675,16 +10066,27 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9675
10066
  worker.onmessage = (event) => {
9676
10067
  const msg = event.data || {};
9677
10068
  if (msg.requestId !== requestId) return;
9678
- if (msg.type === 'stdout' && typeof options.onStdout === 'function') {
9679
- options.onStdout(msg.text);
9680
- } else if (msg.type === 'stderr' && typeof options.onStderr === 'function') {
9681
- options.onStderr(msg.text);
9682
- } else if (msg.type === 'test-result' && typeof options.onTestResult === 'function') {
9683
- options.onTestResult(msg.testResult);
10069
+ if (msg.type === 'started') {
10070
+ userCodeStarted = true;
10071
+ } else if (msg.type === 'stdout') {
10072
+ userCodeStarted = true;
10073
+ if (typeof msg.text === 'string') streamedStdoutChunks.push(msg.text);
10074
+ if (typeof options.onStdout === 'function') options.onStdout(msg.text);
10075
+ } else if (msg.type === 'stderr') {
10076
+ userCodeStarted = true;
10077
+ if (typeof msg.text === 'string') streamedStderrChunks.push(msg.text);
10078
+ if (typeof options.onStderr === 'function') options.onStderr(msg.text);
10079
+ } else if (msg.type === 'test-result') {
10080
+ userCodeStarted = true;
10081
+ if (msg.testResult) streamedTestResults.push(msg.testResult);
10082
+ if (typeof options.onTestResult === 'function') options.onTestResult(msg.testResult);
9684
10083
  } else if (msg.type === 'complete') {
9685
10084
  if (settled) return;
9686
10085
  settled = true;
9687
10086
  clearTimeout(timer);
10087
+ if (options.vfs && msg.result && msg.result.vfsChanges) {
10088
+ _applyWorkerVfsChanges(options.vfs, msg.result.vfsChanges);
10089
+ }
9688
10090
  // Release `_warmWorker` for instant reuse, or terminate ephemeral concurrent worker
9689
10091
  releaseWorker(false);
9690
10092
  resolve(msg.result);
@@ -9693,13 +10095,16 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9693
10095
  settled = true;
9694
10096
  clearTimeout(timer);
9695
10097
  releaseWorker(false);
10098
+ const elapsed = Math.max(0, (typeof performance !== 'undefined' ? performance.now() : Date.now()) - startTime);
10099
+ const errLine = (msg.error?.stack || msg.error?.message || 'Worker execution error') + '\n';
9696
10100
  resolve({
9697
10101
  ok: false,
9698
10102
  exitCode: 1,
9699
- durationMs: 0,
9700
- stdout: '',
9701
- stderr: (msg.error?.stack || msg.error?.message || 'Worker execution error') + '\n',
9702
- testResults: [],
10103
+ durationMs: elapsed,
10104
+ stdout: streamedStdoutChunks.join(''),
10105
+ stderr: streamedStderrChunks.join('') + errLine,
10106
+ testResults: streamedTestResults.slice(),
10107
+ testSummary: buildTestSummary(),
9703
10108
  fsSnapshot: [],
9704
10109
  httpTrace: [],
9705
10110
  error: { message: msg.error?.message || 'Worker execution error', stack: msg.error?.stack }
@@ -9707,19 +10112,40 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9707
10112
  }
9708
10113
  };
9709
10114
 
9710
- worker.onerror = () => {
10115
+ worker.onerror = (errEvent) => {
9711
10116
  if (settled) return;
9712
10117
  settled = true;
9713
10118
  clearTimeout(timer);
9714
10119
  releaseWorker(true);
9715
- resolve(_hostRuntime.executeInVirtualRuntime(options));
10120
+ // Only fall back to in-process execution if the host blocked Blob Worker startup
10121
+ // BEFORE user code ever started. Never re-run crashed user code on the main thread.
10122
+ if (!userCodeStarted && options.allowMainThreadFallback !== false) {
10123
+ resolve(_hostRuntime.executeInVirtualRuntime(options));
10124
+ return;
10125
+ }
10126
+ const elapsed = Math.max(0, (typeof performance !== 'undefined' ? performance.now() : Date.now()) - startTime);
10127
+ const errMsg = (errEvent && errEvent.message)
10128
+ ? String(errEvent.message)
10129
+ : 'Uncaught fatal error in Web Worker execution';
10130
+ resolve({
10131
+ ok: false,
10132
+ exitCode: 1,
10133
+ durationMs: elapsed,
10134
+ stdout: streamedStdoutChunks.join(''),
10135
+ stderr: streamedStderrChunks.join('') + errMsg + '\n',
10136
+ testResults: streamedTestResults.slice(),
10137
+ testSummary: buildTestSummary(),
10138
+ fsSnapshot: [],
10139
+ httpTrace: [],
10140
+ error: { message: errMsg }
10141
+ });
9716
10142
  };
9717
10143
 
9718
10144
  worker.postMessage({
9719
10145
  requestId,
9720
10146
  type: 'execute',
9721
10147
  payload: {
9722
- files: options.files,
10148
+ files: mergedFiles,
9723
10149
  entry: options.entry,
9724
10150
  mode: options.mode,
9725
10151
  replCode: options.replCode,
@@ -9735,7 +10161,8 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9735
10161
  printReplResult: options.printReplResult,
9736
10162
  stdin: options.stdin,
9737
10163
  wasmBinary: options.wasmBinary,
9738
- env: options.env
10164
+ env: options.env,
10165
+ cwd: options.cwd
9739
10166
  }
9740
10167
  });
9741
10168
  });
@@ -9775,9 +10202,9 @@ export const VirtualStream: any = _runtimeApi.VirtualStream;
9775
10202
  export const VirtualStreamPromises: any = _runtimeApi.VirtualStreamPromises;
9776
10203
  export const VirtualStringDecoder: any = _runtimeApi.VirtualStringDecoder;
9777
10204
  export const VirtualDns: any = _runtimeApi.VirtualDns;
9778
- export const createVirtualFs: (options?: any) => any = _runtimeApi.createVirtualFs;
9779
- export const createVirtualHttp: (portTable?: any, vfs?: any) => any = _runtimeApi.createVirtualHttp;
9780
- export const createVirtualNet: (portTable?: any) => any = _runtimeApi.createVirtualNet;
10205
+ export const createVirtualFs: (files?: any, options?: any) => any = _runtimeApi.createVirtualFs;
10206
+ export const createVirtualHttp: (resourceTracker?: any, portTable?: any) => any = _runtimeApi.createVirtualHttp;
10207
+ export const createVirtualNet: (resourceTracker?: any, httpTrace?: any) => any = _runtimeApi.createVirtualNet;
9781
10208
  export const createSqliteDatabase: (vfs?: any, getCwd?: () => string) => any = _runtimeApi.createSqliteDatabase;
9782
10209
  export const transpileTS: (code: string, filename?: string) => string = _runtimeApi.transpileTS;
9783
10210
  export const transpileForBrowser: (source: string, filename?: string) => string = _runtimeApi.transpileForBrowser;