@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
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.3.1 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.4.0 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
7
7
  * - First-Class Node.js and Bun Runtimes (Bun.serve, bun:test, bun:sqlite, Bun.*)
8
- * - Full POSIX Shell AST & 55+ UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
8
+ * - Full POSIX Shell AST & 71 UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
9
9
  * - Interactive PTY Terminal Emulator with inline prompt, Tab completion & ANSI colors
10
10
  * - Persistent HTTP/TCP Servers, CLI curl & Live Port/HTTP Preview
11
11
  * - Modular VS Code Workbench: File Tree, Tabs, Command Palette, Diff Viewer
@@ -86,6 +86,7 @@ var CodeLabLogger = (() => {
86
86
  } catch (err) {
87
87
  sinkError = err;
88
88
  }
89
+ void sinkError;
89
90
  }
90
91
  const consoleObj = typeof console !== "undefined" ? console : null;
91
92
  const fn = consoleObj ? consoleObj[level] : null;
@@ -1134,22 +1135,40 @@ function __initVirtualRuntime(rootScope) {
1134
1135
  // =========================================================================
1135
1136
  // 5. VIRTUAL IN-MEMORY POSIX FILESYSTEM (node:fs)
1136
1137
  // =========================================================================
1137
- function createVirtualFs(initialFiles = {}) {
1138
+ function createVirtualFs(initialFiles = {}, vfsOptions = {}) {
1138
1139
  const dirs = new Set(['/', '/tmp', '/workspace', '/home', '/home/user']);
1139
1140
  const files = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, ctimeMs, ino }
1140
1141
  const deletedInspectorCache = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, deletedAtMs }
1142
+ const MAX_DELETED_CACHE_ENTRIES = 50;
1143
+ const MAX_DELETED_CACHE_FILE_BYTES = 65536;
1144
+ const customCwdGetter = typeof vfsOptions === 'function'
1145
+ ? vfsOptions
1146
+ : (vfsOptions && typeof vfsOptions.cwdGetter === 'function' ? vfsOptions.cwdGetter : null);
1141
1147
  const fdTable = new Map(); // fd -> { inode, path, flags, pos, isDirectory }
1142
1148
  let nextFd = 10;
1143
1149
  let nextIno = 100;
1144
1150
  let mkdtempCounter = 1;
1145
1151
 
1152
+ function recordDeletedForInspector(p, data, mtimeMs) {
1153
+ if (!data || data.byteLength <= 0 || data.byteLength > MAX_DELETED_CACHE_FILE_BYTES) return;
1154
+ if (deletedInspectorCache.has(p)) {
1155
+ deletedInspectorCache.delete(p);
1156
+ } else if (deletedInspectorCache.size >= MAX_DELETED_CACHE_ENTRIES) {
1157
+ const oldestKey = deletedInspectorCache.keys().next().value;
1158
+ if (oldestKey !== undefined) deletedInspectorCache.delete(oldestKey);
1159
+ }
1160
+ deletedInspectorCache.set(p, { data: data.slice(), mtimeMs, deletedAtMs: Date.now() });
1161
+ }
1162
+
1146
1163
  function normPath(p) {
1147
1164
  if (typeof p !== 'string' || !p) {
1148
1165
  const err = new TypeError('path must be a non-empty string');
1149
1166
  err.code = 'ERR_INVALID_ARG_TYPE';
1150
1167
  throw err;
1151
1168
  }
1152
- const baseCwd = typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace';
1169
+ const baseCwd = typeof customCwdGetter === 'function'
1170
+ ? customCwdGetter()
1171
+ : (typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace');
1153
1172
  const abs = p.startsWith('/') ? VirtualPath.normalize(p) : VirtualPath.resolve(baseCwd, p);
1154
1173
  return abs.length > 1 && abs.endsWith('/') ? abs.slice(0, -1) : abs;
1155
1174
  }
@@ -1200,9 +1219,13 @@ function __initVirtualRuntime(rootScope) {
1200
1219
  for (const [relPath, content] of Object.entries(initialFiles)) {
1201
1220
  const cleanRel = relPath.startsWith('/') ? relPath.slice(1) : relPath;
1202
1221
  const isSystemPath = /^\/(workspace|usr|tmp|lib|include|etc|bin|dev)(\/|$)/.test(relPath);
1203
- const fullPath = isSystemPath
1222
+ let fullPath = isSystemPath
1204
1223
  ? normPath(relPath)
1205
1224
  : normPath(`/workspace/${cleanRel}`);
1225
+ if (!isSystemPath && fullPath !== '/workspace' && !fullPath.startsWith('/workspace/')) {
1226
+ const safeSub = cleanRel.split('/').filter((seg) => seg && seg !== '.' && seg !== '..').join('/');
1227
+ fullPath = normPath(`/workspace/${safeSub || 'file'}`);
1228
+ }
1206
1229
  ensureParentDirs(fullPath);
1207
1230
  const bytes = typeof content === 'string' ? utf8Encode(content) : new Uint8Array(content);
1208
1231
  files.set(fullPath, {
@@ -1215,7 +1238,13 @@ function __initVirtualRuntime(rootScope) {
1215
1238
  });
1216
1239
  }
1217
1240
 
1241
+ let _activeStdin = '';
1242
+
1218
1243
  const fsShim = {
1244
+ _setActiveStdin(text) {
1245
+ _activeStdin = text !== undefined && text !== null ? String(text) : '';
1246
+ },
1247
+
1219
1248
  existsSync(p) {
1220
1249
  try {
1221
1250
  const np = normPath(p);
@@ -1382,13 +1411,6 @@ function __initVirtualRuntime(rootScope) {
1382
1411
  fsyncSync(fd) {
1383
1412
  const entry = fdTable.get(fd);
1384
1413
  if (!entry) throw fsError('EBADF', 'fsync', String(fd), 'bad file descriptor');
1385
- if (!entry.isDirectory && entry.inode) {
1386
- deletedInspectorCache.set(entry.path, {
1387
- data: entry.inode.data.slice(),
1388
- mtimeMs: entry.inode.mtimeMs,
1389
- deletedAtMs: null
1390
- });
1391
- }
1392
1414
  },
1393
1415
 
1394
1416
  fdatasyncSync(fd) {
@@ -1429,12 +1451,6 @@ function __initVirtualRuntime(rootScope) {
1429
1451
  inode.mtimeMs = Date.now();
1430
1452
  entry.pos = writePos + chunk.byteLength;
1431
1453
 
1432
- deletedInspectorCache.set(entry.path, {
1433
- data: inode.data.slice(),
1434
- mtimeMs: inode.mtimeMs,
1435
- deletedAtMs: null
1436
- });
1437
-
1438
1454
  return chunk.byteLength;
1439
1455
  },
1440
1456
 
@@ -1453,6 +1469,11 @@ function __initVirtualRuntime(rootScope) {
1453
1469
  },
1454
1470
 
1455
1471
  readFileSync(p, opts) {
1472
+ if (p === 0 || p === '/dev/stdin') {
1473
+ const stdinBuf = VirtualBuffer.from(String(_activeStdin || ''), 'utf8');
1474
+ const encoding = typeof opts === 'string' ? opts : (opts && opts.encoding);
1475
+ return encoding ? stdinBuf.toString(encoding) : stdinBuf;
1476
+ }
1456
1477
  const np = normPath(p);
1457
1478
  if (dirs.has(np)) throw fsError('EISDIR', 'read', p, 'illegal operation on a directory');
1458
1479
  const inode = files.get(np);
@@ -1486,7 +1507,7 @@ function __initVirtualRuntime(rootScope) {
1486
1507
  inode.mode = 0o100000 | (Number(opts.mode) & 0o777);
1487
1508
  }
1488
1509
  }
1489
- deletedInspectorCache.set(np, { data: bytes.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1510
+ deletedInspectorCache.delete(np);
1490
1511
  },
1491
1512
 
1492
1513
  chmodSync(p, mode) {
@@ -1515,7 +1536,7 @@ function __initVirtualRuntime(rootScope) {
1515
1536
  combined.set(chunk, inode.data.byteLength);
1516
1537
  inode.data = combined;
1517
1538
  inode.mtimeMs = Date.now();
1518
- deletedInspectorCache.set(np, { data: combined.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1539
+ deletedInspectorCache.delete(np);
1519
1540
  },
1520
1541
 
1521
1542
  truncateSync(p, len = 0) {
@@ -1531,7 +1552,6 @@ function __initVirtualRuntime(rootScope) {
1531
1552
  inode.data = grown;
1532
1553
  }
1533
1554
  inode.mtimeMs = Date.now();
1534
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1535
1555
  },
1536
1556
 
1537
1557
  renameSync(oldP, newP) {
@@ -1592,16 +1612,14 @@ function __initVirtualRuntime(rootScope) {
1592
1612
  if (fdEntry.path === src) fdEntry.path = dst;
1593
1613
  }
1594
1614
  deletedInspectorCache.delete(src);
1595
- deletedInspectorCache.set(dst, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
1615
+ deletedInspectorCache.delete(dst);
1596
1616
  },
1597
1617
 
1598
1618
  unlinkSync(p) {
1599
1619
  const np = normPath(p);
1600
1620
  const inode = files.get(np);
1601
1621
  if (!inode) throw fsError('ENOENT', 'unlink', p, 'no such file or directory');
1602
- if (inode.data.byteLength > 0) {
1603
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
1604
- }
1622
+ recordDeletedForInspector(np, inode.data, inode.mtimeMs);
1605
1623
  files.delete(np);
1606
1624
  },
1607
1625
 
@@ -1618,9 +1636,7 @@ function __initVirtualRuntime(rootScope) {
1618
1636
  for (const [fPath, inode] of Array.from(files.entries())) {
1619
1637
  if (fPath.startsWith(prefix)) {
1620
1638
  if (!recursive) throw fsError('ENOTEMPTY', 'rm', p, 'directory not empty');
1621
- if (inode.data.byteLength > 0) {
1622
- deletedInspectorCache.set(fPath, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
1623
- }
1639
+ recordDeletedForInspector(fPath, inode.data, inode.mtimeMs);
1624
1640
  files.delete(fPath);
1625
1641
  }
1626
1642
  }
@@ -1817,6 +1833,10 @@ function __initVirtualRuntime(rootScope) {
1817
1833
 
1818
1834
  items.sort((a, b) => a.path.localeCompare(b.path));
1819
1835
  return items;
1836
+ },
1837
+
1838
+ _listOpenFds() {
1839
+ return Array.from(fdTable.keys());
1820
1840
  }
1821
1841
  };
1822
1842
 
@@ -1971,6 +1991,13 @@ function __initVirtualRuntime(rootScope) {
1971
1991
  };
1972
1992
 
1973
1993
  fsShim.promises = fsPromises;
1994
+ fsShim._exportRawState = () => {
1995
+ const clonedFiles = new Map();
1996
+ for (const [k, v] of files.entries()) {
1997
+ clonedFiles.set(k, v.data instanceof Uint8Array ? v.data.slice() : new Uint8Array(v.data || 0));
1998
+ }
1999
+ return { files: clonedFiles, dirs: new Set(dirs) };
2000
+ };
1974
2001
 
1975
2002
  return fsShim;
1976
2003
  }
@@ -3194,6 +3221,7 @@ function __initVirtualRuntime(rootScope) {
3194
3221
  responseHeaders: {},
3195
3222
  _t0: performance.now()
3196
3223
  };
3224
+ if (httpTrace.length >= 500) httpTrace.shift();
3197
3225
  httpTrace.push(traceEntry);
3198
3226
  this._traceEntry = traceEntry;
3199
3227
 
@@ -4185,6 +4213,7 @@ function __initVirtualRuntime(rootScope) {
4185
4213
  this._peer = serverSocket;
4186
4214
  this.connecting = false;
4187
4215
 
4216
+ if (sharedTrace.length >= 500) sharedTrace.shift();
4188
4217
  sharedTrace.push({
4189
4218
  protocol: 'TCP',
4190
4219
  event: 'connect',
@@ -4699,13 +4728,17 @@ function __initVirtualRuntime(rootScope) {
4699
4728
  function transpileTS(source, filename = 'module.ts', opts = {}) {
4700
4729
  // `keepEsm` leaves `import`/`export` statements intact so the output can run
4701
4730
  // natively in a browser as an ES module (used by the built-in preview server).
4702
- const keepEsm = Boolean(opts && opts.keepEsm);
4703
- const isTS = /\.(ts|tsx|mts|cts)$/i.test(filename)
4731
+ const keepEsm = Boolean(opts && (opts.keepEsm || opts.expressionOnly));
4732
+ const expressionOnly = Boolean(opts && opts.expressionOnly);
4733
+ const isTS = expressionOnly
4734
+ || /\.(ts|tsx|mts|cts)$/i.test(filename)
4704
4735
  || /^[ \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);
4705
- const hasESM = /^\s*(?:import|export)\b/m.test(source)
4736
+ const hasESM = !expressionOnly && (
4737
+ /^\s*(?:import|export)\b/m.test(source)
4706
4738
  || /\bexport\s*\{/.test(source)
4707
4739
  || /\bimport\s*\{/.test(source)
4708
- || /\bexport\s+default\b/.test(source);
4740
+ || /\bexport\s+default\b/.test(source)
4741
+ );
4709
4742
  const hasJsx = detectJsxSyntax(source, filename);
4710
4743
  if (!isTS && !hasESM && !hasJsx) return source;
4711
4744
 
@@ -4713,7 +4746,7 @@ function __initVirtualRuntime(rootScope) {
4713
4746
  if (hasJsx) {
4714
4747
  const { pragma, frag } = readJsxPragma(source);
4715
4748
  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);
4716
- const needsReact = pragma === 'React.createElement' && (keepEsm ? !hasReactBinding : !/\bReact\b/.test(source));
4749
+ const needsReact = !expressionOnly && pragma === 'React.createElement' && (keepEsm ? !hasReactBinding : !/\bReact\b/.test(source));
4717
4750
  const transformed = jsxTransform(source, { pragma, frag });
4718
4751
  if (transformed !== source) {
4719
4752
  source = transformed;
@@ -4801,18 +4834,80 @@ function __initVirtualRuntime(rootScope) {
4801
4834
  i = j;
4802
4835
  continue;
4803
4836
  }
4804
- // Template literal
4837
+ // Template literal (recursively transpile TypeScript inside ${...} expressions)
4805
4838
  if (ch === '`') {
4806
4839
  let j = i + 1;
4807
- let depth = 0;
4840
+ let rebuilt = '`';
4808
4841
  while (j < len) {
4809
- if (source[j] === '\\') { j += 2; continue; }
4810
- if (source[j] === '$' && source[j + 1] === '{') { depth++; j += 2; continue; }
4811
- if (source[j] === '}' && depth > 0) { depth--; j++; continue; }
4812
- if (source[j] === '`' && depth === 0) { j++; break; }
4842
+ if (source[j] === '\\') {
4843
+ rebuilt += source.slice(j, j + 2);
4844
+ j += 2;
4845
+ continue;
4846
+ }
4847
+ if (source[j] === '`' ) {
4848
+ rebuilt += '`';
4849
+ j++;
4850
+ break;
4851
+ }
4852
+ if (source[j] === '$' && source[j + 1] === '{') {
4853
+ j += 2;
4854
+ const exprStart = j;
4855
+ let braceDepth = 1;
4856
+ while (j < len && braceDepth > 0) {
4857
+ const ec = source[j];
4858
+ const en = source[j + 1];
4859
+ if (ec === '/' && en === '/') {
4860
+ j += 2;
4861
+ while (j < len && source[j] !== '\n') j++;
4862
+ continue;
4863
+ }
4864
+ if (ec === '/' && en === '*') {
4865
+ j += 2;
4866
+ while (j < len && !(source[j] === '*' && source[j + 1] === '/')) j++;
4867
+ j += 2;
4868
+ continue;
4869
+ }
4870
+ if (ec === "'" || ec === '"') {
4871
+ const q = ec;
4872
+ j++;
4873
+ while (j < len && source[j] !== q && source[j] !== '\n') {
4874
+ if (source[j] === '\\') j += 2;
4875
+ else j++;
4876
+ }
4877
+ if (j < len && source[j] === q) j++;
4878
+ continue;
4879
+ }
4880
+ if (ec === '`') {
4881
+ j++;
4882
+ let nestedDepth = 0;
4883
+ while (j < len) {
4884
+ if (source[j] === '\\') { j += 2; continue; }
4885
+ if (source[j] === '$' && source[j + 1] === '{') { nestedDepth++; j += 2; continue; }
4886
+ if (source[j] === '}' && nestedDepth > 0) { nestedDepth--; j++; continue; }
4887
+ if (source[j] === '`' && nestedDepth === 0) { j++; break; }
4888
+ j++;
4889
+ }
4890
+ continue;
4891
+ }
4892
+ if (ec === '{') braceDepth++;
4893
+ else if (ec === '}') {
4894
+ braceDepth--;
4895
+ if (braceDepth === 0) break;
4896
+ }
4897
+ j++;
4898
+ }
4899
+ const rawExpr = source.slice(exprStart, j);
4900
+ const transpiledExpr = isTS
4901
+ ? transpileTS(rawExpr, filename, { expressionOnly: true })
4902
+ : rawExpr;
4903
+ rebuilt += '${' + transpiledExpr + '}';
4904
+ if (j < len && source[j] === '}') j++;
4905
+ continue;
4906
+ }
4907
+ rebuilt += source[j];
4813
4908
  j++;
4814
4909
  }
4815
- code += mask(source.slice(i, j));
4910
+ code += mask(rebuilt);
4816
4911
  i = j;
4817
4912
  continue;
4818
4913
  }
@@ -5186,8 +5281,8 @@ function __initVirtualRuntime(rootScope) {
5186
5281
  };
5187
5282
  code = stripReturnTypes(code);
5188
5283
 
5189
- // Strip parameter type annotations inside `(...)` (supports multi-line parameter lists and default value `()` calls)
5190
- code = code.replace(/\(((?:[^()]|\([^()]*\))*)\)/g, (full, inner) => {
5284
+ // Strip parameter type annotations inside `(...)` from innermost parens outward so nested callbacks work
5285
+ const stripParensParamTypes = (full, inner) => {
5191
5286
  if (!inner.includes(':')) return full;
5192
5287
  if (inner.includes('?') && !/[A-Za-z0-9_$}\]]\s*\?\s*:/.test(inner)) return full;
5193
5288
  if (/[{}]/.test(inner) && !/\}\s*\??\s*:/.test(inner) && !/:\s*[A-Za-z_$][A-Za-z0-9_$.<>[\]|&\s]*\{/.test(inner)) {
@@ -5201,7 +5296,12 @@ function __initVirtualRuntime(rootScope) {
5201
5296
  const parts = splitTopLevel(inner, ',');
5202
5297
  const cleaned = parts.map((part) => cleanSingleParam(part));
5203
5298
  return `(${cleaned.join(',')})`;
5204
- });
5299
+ };
5300
+ do {
5301
+ prevCode = code;
5302
+ code = code.replace(/\(([^()]*)\)/g, stripParensParamTypes);
5303
+ } while (code !== prevCode);
5304
+ code = code.replace(/\(((?:[^()]|\([^()]*\))*)\)/g, stripParensParamTypes);
5205
5305
 
5206
5306
  // Strip variable type annotations: `const x: Type =`, `let y: Type =`
5207
5307
  code = code.replace(/\b(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*:\s*[^=;\n]+(?<![=!<>])=(?![=>])/g, '$1 $2 =');
@@ -5332,7 +5432,31 @@ function __initVirtualRuntime(rootScope) {
5332
5432
  hasEsmExport = true;
5333
5433
  return `Object.assign(exports, require(${mod.trim()}));`;
5334
5434
  });
5335
- code = code.replace(/\bexport\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
5435
+ const collectBindingIds = (pattern) => {
5436
+ const ids = [];
5437
+ const inner = pattern.trim().replace(/^[\[{]|[\]}]$/g, '');
5438
+ const isObj = pattern.trim().startsWith('{');
5439
+ for (const rawPart of splitTopLevel(inner, ',')) {
5440
+ let part = rawPart.trim();
5441
+ if (!part) continue;
5442
+ if (part.startsWith('...')) {
5443
+ part = part.slice(3).trim();
5444
+ } else if (isObj && part.includes(':')) {
5445
+ const colonIdx = part.indexOf(':');
5446
+ part = part.slice(colonIdx + 1).trim();
5447
+ }
5448
+ const eqIdx = part.indexOf('=');
5449
+ if (eqIdx !== -1) part = part.slice(0, eqIdx).trim();
5450
+ if ((part.startsWith('{') && part.endsWith('}')) || (part.startsWith('[') && part.endsWith(']'))) {
5451
+ ids.push(...collectBindingIds(part));
5452
+ } else if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(part)) {
5453
+ ids.push(part);
5454
+ }
5455
+ }
5456
+ return ids;
5457
+ };
5458
+
5459
+ 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) => {
5336
5460
  hasEsmExport = true;
5337
5461
  defaultExportName = name;
5338
5462
  return `${kw} ${name}`;
@@ -5341,11 +5465,16 @@ function __initVirtualRuntime(rootScope) {
5341
5465
  hasEsmExport = true;
5342
5466
  return 'exports.default = ';
5343
5467
  });
5344
- code = code.replace(/\bexport\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
5468
+ 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) => {
5345
5469
  hasEsmExport = true;
5346
5470
  exportedNames.push(name);
5347
5471
  return `${kw} ${name}`;
5348
5472
  });
5473
+ code = code.replace(/\bexport\s+(const|let|var)\s+(\{[^;=\n]+\}|\[[^;=\n]+\])\s*=/gm, (_, kw, pat) => {
5474
+ hasEsmExport = true;
5475
+ exportedNames.push(...collectBindingIds(pat));
5476
+ return `${kw} ${pat} =`;
5477
+ });
5349
5478
  code = code.replace(/\bexport\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
5350
5479
  hasEsmExport = true;
5351
5480
  exportedNames.push(name);
@@ -6477,7 +6606,16 @@ function __initVirtualRuntime(rootScope) {
6477
6606
  const activePortTable = optPortTable || portTable || _defaultPortTable;
6478
6607
  resourceTracker.pid = pid;
6479
6608
 
6480
- const vfs = optVfs || createVirtualFs(files);
6609
+ const prevCwdGetter = _activeCwdGetter;
6610
+ let currentCwd = (typeof options.cwd === 'string' && options.cwd.trim())
6611
+ ? VirtualPath.resolve('/workspace', options.cwd.trim())
6612
+ : '/workspace';
6613
+ _activeCwdGetter = () => currentCwd;
6614
+
6615
+ const vfs = optVfs || createVirtualFs(files, { cwdGetter: () => currentCwd });
6616
+ const initialOpenFds = typeof vfs._listOpenFds === 'function'
6617
+ ? new Set(vfs._listOpenFds())
6618
+ : null;
6481
6619
  if (optVfs && files && typeof files === 'object') {
6482
6620
  for (const [fPath, content] of Object.entries(files)) {
6483
6621
  const abs = fPath.startsWith('/') ? fPath : '/workspace/' + fPath;
@@ -6490,6 +6628,9 @@ function __initVirtualRuntime(rootScope) {
6490
6628
  }
6491
6629
  }
6492
6630
  }
6631
+ if (typeof vfs._setActiveStdin === 'function') {
6632
+ vfs._setActiveStdin(options && options.stdin ? String(options.stdin) : '');
6633
+ }
6493
6634
  const vhttp = createVirtualHttp(resourceTracker, activePortTable);
6494
6635
  const vnet = createVirtualNet(resourceTracker, vhttp.getTrace());
6495
6636
 
@@ -6512,6 +6653,10 @@ function __initVirtualRuntime(rootScope) {
6512
6653
  }
6513
6654
  }
6514
6655
 
6656
+ const initialVfsState = (options && options._captureVfsDiff && typeof vfs._exportRawState === 'function')
6657
+ ? vfs._exportRawState()
6658
+ : null;
6659
+
6515
6660
  // Custom timer wrappers supporting .unref() / .ref() and active handle tracking
6516
6661
  function makeTimerHandle(rawId, isInterval) {
6517
6662
  const handle = {
@@ -6871,11 +7016,9 @@ function __initVirtualRuntime(rootScope) {
6871
7016
  hrtimeFn.bigint = () => BigInt(Math.round(performance.now() * 1e6));
6872
7017
 
6873
7018
  let syncExecDepth = 0;
6874
- let currentCwd = '/workspace';
6875
- _activeCwdGetter = () => currentCwd;
6876
7019
 
6877
7020
  const sandboxProcess = Object.assign(new EventEmitter(), {
6878
- env: { NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' },
7021
+ env: Object.assign({ NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' }, options.env || {}),
6879
7022
  argv: argv || ['node', entry.startsWith('/') ? entry : `/workspace/${entry}`],
6880
7023
  argv0: 'node',
6881
7024
  execArgv: [],
@@ -6955,6 +7098,9 @@ function __initVirtualRuntime(rootScope) {
6955
7098
  }
6956
7099
 
6957
7100
  // Immediately cancel all active timers and immediates
7101
+ if (typeof vfs._setActiveStdin === 'function') {
7102
+ vfs._setActiveStdin('');
7103
+ }
6958
7104
  for (const rawId of resourceTracker.allTimers) {
6959
7105
  clearTimeout(rawId);
6960
7106
  clearInterval(rawId);
@@ -8870,6 +9016,9 @@ function __initVirtualRuntime(rootScope) {
8870
9016
  hasExited = true;
8871
9017
  try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime exit listener failed', err); }
8872
9018
  }
9019
+ if (typeof vfs._setActiveStdin === 'function') {
9020
+ vfs._setActiveStdin('');
9021
+ }
8873
9022
  for (const rawId of resourceTracker.allTimers) {
8874
9023
  clearTimeout(rawId);
8875
9024
  clearInterval(rawId);
@@ -8886,12 +9035,56 @@ function __initVirtualRuntime(rootScope) {
8886
9035
  if (!isBackground) {
8887
9036
  vhttp.closeAllServers();
8888
9037
  vnet.closeAllServers();
9038
+ if (initialOpenFds && typeof vfs._listOpenFds === 'function' && typeof vfs.closeSync === 'function') {
9039
+ for (const fd of vfs._listOpenFds()) {
9040
+ if (!initialOpenFds.has(fd)) {
9041
+ try { vfs.closeSync(fd); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime closeSync leak cleanup failed', { fd, err }); }
9042
+ }
9043
+ }
9044
+ }
8889
9045
  }
9046
+ _activeCwdGetter = prevCwdGetter;
8890
9047
  }
8891
9048
 
8892
9049
  const failedTests = testResults.filter((t) => !t.passed).length;
8893
9050
  if (failedTests > 0 && exitCode === 0) exitCode = 1;
8894
9051
 
9052
+ let vfsChanges = undefined;
9053
+ if (initialVfsState && typeof vfs._exportRawState === 'function') {
9054
+ const finalVfsState = vfs._exportRawState();
9055
+ const modifiedFiles = {};
9056
+ const deletedFiles = [];
9057
+ const createdDirs = [];
9058
+ const isNodeModulesPath = (p) => p === '/workspace/node_modules' || p.startsWith('/workspace/node_modules/');
9059
+ const bytesEqual = (a, b) => {
9060
+ if (!a || !b || a.byteLength !== b.byteLength) return false;
9061
+ for (let i = 0; i < a.byteLength; i++) {
9062
+ if (a[i] !== b[i]) return false;
9063
+ }
9064
+ return true;
9065
+ };
9066
+
9067
+ for (const d of finalVfsState.dirs) {
9068
+ if (!initialVfsState.dirs.has(d) && !isNodeModulesPath(d)) {
9069
+ createdDirs.push(d);
9070
+ }
9071
+ }
9072
+ for (const [fPath, data] of finalVfsState.files.entries()) {
9073
+ if (isNodeModulesPath(fPath)) continue;
9074
+ const prev = initialVfsState.files.get(fPath);
9075
+ if (!prev || !bytesEqual(prev, data)) {
9076
+ modifiedFiles[fPath] = data;
9077
+ }
9078
+ }
9079
+ for (const fPath of initialVfsState.files.keys()) {
9080
+ if (isNodeModulesPath(fPath)) continue;
9081
+ if (!finalVfsState.files.has(fPath)) {
9082
+ deletedFiles.push(fPath);
9083
+ }
9084
+ }
9085
+ vfsChanges = { modifiedFiles, deletedFiles, createdDirs };
9086
+ }
9087
+
8895
9088
  return {
8896
9089
  ok: exitCode === 0,
8897
9090
  exitCode,
@@ -8907,6 +9100,7 @@ function __initVirtualRuntime(rootScope) {
8907
9100
  failed: failedTests
8908
9101
  },
8909
9102
  fsSnapshot: typeof vfs.getSnapshot === 'function' ? vfs.getSnapshot() : [],
9103
+ ...(vfsChanges ? { vfsChanges } : {}),
8910
9104
  httpTrace: [...vhttp.getTrace(), ...vnet.getTrace()],
8911
9105
  replValue: replValue !== undefined ? formatConsoleArg(replValue) : undefined
8912
9106
  };
@@ -9295,14 +9489,70 @@ function __initVirtualRuntime(rootScope) {
9295
9489
 
9296
9490
  exec(sql) {
9297
9491
  const cleaned = stripSqlComments(sql);
9298
- const statements = cleaned.split(';').map((s) => s.trim()).filter(Boolean);
9492
+ const statements = [];
9493
+ let cur = '';
9494
+ let i = 0;
9495
+ while (i < cleaned.length) {
9496
+ const ch = cleaned[i];
9497
+ if (ch === "'" || ch === '"') {
9498
+ const quote = ch;
9499
+ cur += ch;
9500
+ i++;
9501
+ while (i < cleaned.length) {
9502
+ if (cleaned[i] === quote && cleaned[i + 1] === quote) {
9503
+ cur += quote + quote;
9504
+ i += 2;
9505
+ continue;
9506
+ }
9507
+ if (cleaned[i] === '\\' && quote === '"') {
9508
+ cur += cleaned.slice(i, i + 2);
9509
+ i += 2;
9510
+ continue;
9511
+ }
9512
+ cur += cleaned[i];
9513
+ if (cleaned[i] === quote) {
9514
+ i++;
9515
+ break;
9516
+ }
9517
+ i++;
9518
+ }
9519
+ continue;
9520
+ }
9521
+ if (ch === ';') {
9522
+ const trimmed = cur.trim();
9523
+ if (trimmed) statements.push(trimmed);
9524
+ cur = '';
9525
+ i++;
9526
+ continue;
9527
+ }
9528
+ cur += ch;
9529
+ i++;
9530
+ }
9531
+ if (cur.trim()) statements.push(cur.trim());
9299
9532
  for (const s of statements) {
9300
9533
  this.run(s);
9301
9534
  }
9302
9535
  }
9303
9536
 
9304
9537
  transaction(fn) {
9305
- return (...args) => fn(...args);
9538
+ const db = this;
9539
+ return (...args) => {
9540
+ const snapshot = new Map();
9541
+ for (const [tblName, tbl] of db.tables.entries()) {
9542
+ snapshot.set(tblName, {
9543
+ columns: tbl.columns.map((c) => Object.assign({}, c)),
9544
+ rows: tbl.rows.map((r) => Object.assign({}, r)),
9545
+ autoInc: tbl.autoInc
9546
+ });
9547
+ }
9548
+ try {
9549
+ return fn(...args);
9550
+ } catch (err) {
9551
+ db.tables = snapshot;
9552
+ db._persistToVfs();
9553
+ throw err;
9554
+ }
9555
+ };
9306
9556
  }
9307
9557
 
9308
9558
  close() {
@@ -9591,9 +9841,11 @@ function __workerMessageLoop(workerScope) {
9591
9841
  const msg = event.data || {};
9592
9842
  const { requestId, type, payload = {} } = msg;
9593
9843
  if (type !== 'execute') return;
9844
+ workerScope.postMessage({ requestId, type: 'started' });
9594
9845
  try {
9595
9846
  const result = await runtime.executeInVirtualRuntime({
9596
9847
  ...payload,
9848
+ _captureVfsDiff: true,
9597
9849
  onStdout(text) {
9598
9850
  workerScope.postMessage({ requestId, type: 'stdout', text });
9599
9851
  },
@@ -9645,7 +9897,10 @@ function _ensureWorkerUrl() {
9645
9897
  }
9646
9898
 
9647
9899
  function _ensureWarmWorker() {
9648
- if (_warmWorker) return _warmWorker;
9900
+ if (_warmWorker && typeof Worker === 'function' && _warmWorker instanceof Worker) {
9901
+ return _warmWorker;
9902
+ }
9903
+ if (_warmWorker) _destroyWarmWorker();
9649
9904
  _warmWorker = new Worker(_ensureWorkerUrl());
9650
9905
  return _warmWorker;
9651
9906
  }
@@ -9658,6 +9913,14 @@ function _destroyWarmWorker() {
9658
9913
  _warmWorkerBusy = false;
9659
9914
  }
9660
9915
 
9916
+ _hostRuntime.destroyWorkerPool = function destroyWorkerPool() {
9917
+ _destroyWarmWorker();
9918
+ if (_cachedWorkerUrl && typeof URL !== 'undefined' && typeof URL.revokeObjectURL === 'function') {
9919
+ try { URL.revokeObjectURL(_cachedWorkerUrl); } catch (err) { _hostLogger.debug('revokeObjectURL failed', err); }
9920
+ }
9921
+ _cachedWorkerUrl = null;
9922
+ };
9923
+
9661
9924
  _hostRuntime.cancelWorkerExecution = function cancelWorkerExecution(reason = 'Execution cancelled', instanceId) {
9662
9925
  let cancelledAny = false;
9663
9926
  for (const [jobId, job] of Array.from(_activeWorkerJobs.entries())) {
@@ -9670,11 +9933,118 @@ _hostRuntime.cancelWorkerExecution = function cancelWorkerExecution(reason = 'Ex
9670
9933
  return cancelledAny;
9671
9934
  };
9672
9935
 
9936
+ function _extractWorkerFilesFromVfs(vfs) {
9937
+ const extracted = {};
9938
+ if (!vfs || typeof vfs !== 'object') return extracted;
9939
+ try {
9940
+ if (typeof vfs._exportRawState === 'function') {
9941
+ const st = vfs._exportRawState();
9942
+ for (const [absPath, bytes] of st.files.entries()) {
9943
+ extracted[absPath] = bytes;
9944
+ }
9945
+ return extracted;
9946
+ }
9947
+ if (vfs.files instanceof Map) {
9948
+ for (const [absPath, entry] of vfs.files.entries()) {
9949
+ if (!entry) continue;
9950
+ const data = entry.data !== undefined ? entry.data : entry;
9951
+ if (typeof data === 'string') {
9952
+ extracted[absPath] = data;
9953
+ } else if (data instanceof Uint8Array) {
9954
+ extracted[absPath] = data.slice();
9955
+ } else if (ArrayBuffer.isView(data)) {
9956
+ extracted[absPath] = new Uint8Array(data.buffer, data.byteOffset, data.byteLength).slice();
9957
+ }
9958
+ }
9959
+ return extracted;
9960
+ }
9961
+ if (typeof vfs.readdirSync === 'function' && typeof vfs.readFileSync === 'function') {
9962
+ const walk = (dir) => {
9963
+ let entries = [];
9964
+ try { entries = vfs.readdirSync(dir); } catch (_) { return; }
9965
+ for (const name of entries) {
9966
+ const full = dir === '/' ? '/' + name : dir + '/' + name;
9967
+ let isDir = false;
9968
+ try { isDir = vfs.statSync(full).isDirectory(); } catch (_) { isDir = false; }
9969
+ if (isDir) walk(full);
9970
+ else {
9971
+ try {
9972
+ const raw = vfs.readFileSync(full);
9973
+ extracted[full] = raw instanceof Uint8Array
9974
+ ? raw.slice()
9975
+ : (typeof raw === 'string' ? raw : String(raw ?? ''));
9976
+ } catch (err) {
9977
+ _hostLogger.debug('_extractWorkerFilesFromVfs: skip unreadable entry', full, err);
9978
+ }
9979
+ }
9980
+ }
9981
+ };
9982
+ walk('/workspace');
9983
+ walk('/tmp');
9984
+ }
9985
+ } catch (err) {
9986
+ _hostLogger.debug('_extractWorkerFilesFromVfs failed', err);
9987
+ }
9988
+ return extracted;
9989
+ }
9990
+
9991
+ function _applyWorkerVfsChanges(vfs, vfsChanges) {
9992
+ if (!vfs || !vfsChanges || typeof vfsChanges !== 'object') return;
9993
+ const { createdDirs = [], modifiedFiles = {}, deletedFiles = [] } = vfsChanges;
9994
+ try {
9995
+ if (Array.isArray(createdDirs) && typeof vfs.mkdirSync === 'function') {
9996
+ for (const dir of createdDirs) {
9997
+ try {
9998
+ vfs.mkdirSync(dir, { recursive: true });
9999
+ } catch (err) {
10000
+ _hostLogger.debug('_applyWorkerVfsChanges: mkdirSync failed', dir, err);
10001
+ }
10002
+ }
10003
+ }
10004
+ if (modifiedFiles && typeof modifiedFiles === 'object') {
10005
+ for (const [absPath, rawBytes] of Object.entries(modifiedFiles)) {
10006
+ const slashIdx = absPath.lastIndexOf('/');
10007
+ if (slashIdx > 0 && typeof vfs.mkdirSync === 'function') {
10008
+ try {
10009
+ vfs.mkdirSync(absPath.slice(0, slashIdx), { recursive: true });
10010
+ } catch (err) {
10011
+ _hostLogger.debug('_applyWorkerVfsChanges: parent mkdirSync failed', absPath, err);
10012
+ }
10013
+ }
10014
+ const payload = rawBytes instanceof Uint8Array
10015
+ ? rawBytes
10016
+ : (ArrayBuffer.isView(rawBytes)
10017
+ ? new Uint8Array(rawBytes.buffer, rawBytes.byteOffset, rawBytes.byteLength)
10018
+ : rawBytes);
10019
+ if (typeof vfs.writeFileSync === 'function') {
10020
+ vfs.writeFileSync(absPath, payload);
10021
+ } else if (typeof vfs.writeFile === 'function') {
10022
+ vfs.writeFile(absPath, payload);
10023
+ }
10024
+ }
10025
+ }
10026
+ if (Array.isArray(deletedFiles)) {
10027
+ for (const absPath of deletedFiles) {
10028
+ try {
10029
+ if (typeof vfs.unlinkSync === 'function') vfs.unlinkSync(absPath);
10030
+ else if (typeof vfs.rmSync === 'function') vfs.rmSync(absPath, { force: true });
10031
+ } catch (err) {
10032
+ _hostLogger.debug('_applyWorkerVfsChanges: delete failed', absPath, err);
10033
+ }
10034
+ }
10035
+ }
10036
+ } catch (err) {
10037
+ _hostLogger.debug('_applyWorkerVfsChanges failed', err);
10038
+ }
10039
+ }
10040
+
9673
10041
  _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9674
10042
  const isNonJs =
9675
10043
  Boolean(options.wasmBinary) ||
9676
10044
  Boolean(options.cppCompiler) ||
9677
10045
  Boolean(options.pythonCompiler) ||
10046
+ Boolean(options.activePortTable) ||
10047
+ Boolean(options.portTable) ||
9678
10048
  (typeof options.entry === 'string' && /\.(cpp|cc|cxx|wasm|py)$/i.test(options.entry));
9679
10049
  if (
9680
10050
  isNonJs ||
@@ -9694,6 +10064,10 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9694
10064
  _hostRuntime.cancelWorkerExecution('Execution cancelled by new run', instanceId);
9695
10065
  }
9696
10066
 
10067
+ const mergedFiles = options.vfs
10068
+ ? Object.assign(_extractWorkerFilesFromVfs(options.vfs), options.files || {})
10069
+ : options.files;
10070
+
9697
10071
  return new Promise((resolve) => {
9698
10072
  let worker;
9699
10073
  let isWarmWorker = false;
@@ -9712,9 +10086,23 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9712
10086
  return;
9713
10087
  }
9714
10088
 
10089
+ const startTime = typeof performance !== 'undefined' ? performance.now() : Date.now();
9715
10090
  const timeoutMs = options.timeoutMs || 15000;
9716
10091
  let settled = false;
10092
+ let userCodeStarted = false;
9717
10093
  let abortListener = null;
10094
+ const streamedStdoutChunks = [];
10095
+ const streamedStderrChunks = [];
10096
+ const streamedTestResults = [];
10097
+
10098
+ const buildTestSummary = () => {
10099
+ const failed = streamedTestResults.filter((t) => !t.passed).length;
10100
+ return {
10101
+ total: streamedTestResults.length,
10102
+ passed: streamedTestResults.length - failed,
10103
+ failed
10104
+ };
10105
+ };
9718
10106
 
9719
10107
  function releaseWorker(terminateWorker) {
9720
10108
  if (options.signal && abortListener) {
@@ -9741,14 +10129,16 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9741
10129
  if (settled) return;
9742
10130
  settled = true;
9743
10131
  releaseWorker(true);
10132
+ const timeoutMsg = `Execution timed out after ${timeoutMs}ms (infinite loop or hung timer terminated).\n`;
9744
10133
  resolve({
9745
10134
  ok: false,
9746
10135
  timedOut: true,
9747
10136
  exitCode: 124,
9748
10137
  durationMs: timeoutMs,
9749
- stdout: '',
9750
- stderr: `Execution timed out after ${timeoutMs}ms (infinite loop or hung timer terminated).\n`,
9751
- testResults: [],
10138
+ stdout: streamedStdoutChunks.join(''),
10139
+ stderr: streamedStderrChunks.join('') + timeoutMsg,
10140
+ testResults: streamedTestResults.slice(),
10141
+ testSummary: buildTestSummary(),
9752
10142
  fsSnapshot: [],
9753
10143
  httpTrace: [],
9754
10144
  error: { message: `Execution timed out after ${timeoutMs}ms` }
@@ -9763,14 +10153,16 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9763
10153
  settled = true;
9764
10154
  clearTimeout(timer);
9765
10155
  releaseWorker(true);
10156
+ const elapsed = Math.max(0, (typeof performance !== 'undefined' ? performance.now() : Date.now()) - startTime);
9766
10157
  resolve({
9767
10158
  ok: false,
9768
10159
  cancelled: true,
9769
10160
  exitCode: 130,
9770
- durationMs: 0,
9771
- stdout: '',
9772
- stderr: `${reason}\n`,
9773
- testResults: [],
10161
+ durationMs: elapsed,
10162
+ stdout: streamedStdoutChunks.join(''),
10163
+ stderr: streamedStderrChunks.join('') + `${reason}\n`,
10164
+ testResults: streamedTestResults.slice(),
10165
+ testSummary: buildTestSummary(),
9774
10166
  fsSnapshot: [],
9775
10167
  httpTrace: [],
9776
10168
  error: { message: reason }
@@ -9794,16 +10186,27 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9794
10186
  worker.onmessage = (event) => {
9795
10187
  const msg = event.data || {};
9796
10188
  if (msg.requestId !== requestId) return;
9797
- if (msg.type === 'stdout' && typeof options.onStdout === 'function') {
9798
- options.onStdout(msg.text);
9799
- } else if (msg.type === 'stderr' && typeof options.onStderr === 'function') {
9800
- options.onStderr(msg.text);
9801
- } else if (msg.type === 'test-result' && typeof options.onTestResult === 'function') {
9802
- options.onTestResult(msg.testResult);
10189
+ if (msg.type === 'started') {
10190
+ userCodeStarted = true;
10191
+ } else if (msg.type === 'stdout') {
10192
+ userCodeStarted = true;
10193
+ if (typeof msg.text === 'string') streamedStdoutChunks.push(msg.text);
10194
+ if (typeof options.onStdout === 'function') options.onStdout(msg.text);
10195
+ } else if (msg.type === 'stderr') {
10196
+ userCodeStarted = true;
10197
+ if (typeof msg.text === 'string') streamedStderrChunks.push(msg.text);
10198
+ if (typeof options.onStderr === 'function') options.onStderr(msg.text);
10199
+ } else if (msg.type === 'test-result') {
10200
+ userCodeStarted = true;
10201
+ if (msg.testResult) streamedTestResults.push(msg.testResult);
10202
+ if (typeof options.onTestResult === 'function') options.onTestResult(msg.testResult);
9803
10203
  } else if (msg.type === 'complete') {
9804
10204
  if (settled) return;
9805
10205
  settled = true;
9806
10206
  clearTimeout(timer);
10207
+ if (options.vfs && msg.result && msg.result.vfsChanges) {
10208
+ _applyWorkerVfsChanges(options.vfs, msg.result.vfsChanges);
10209
+ }
9807
10210
  // Release `_warmWorker` for instant reuse, or terminate ephemeral concurrent worker
9808
10211
  releaseWorker(false);
9809
10212
  resolve(msg.result);
@@ -9812,13 +10215,16 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9812
10215
  settled = true;
9813
10216
  clearTimeout(timer);
9814
10217
  releaseWorker(false);
10218
+ const elapsed = Math.max(0, (typeof performance !== 'undefined' ? performance.now() : Date.now()) - startTime);
10219
+ const errLine = (msg.error?.stack || msg.error?.message || 'Worker execution error') + '\n';
9815
10220
  resolve({
9816
10221
  ok: false,
9817
10222
  exitCode: 1,
9818
- durationMs: 0,
9819
- stdout: '',
9820
- stderr: (msg.error?.stack || msg.error?.message || 'Worker execution error') + '\n',
9821
- testResults: [],
10223
+ durationMs: elapsed,
10224
+ stdout: streamedStdoutChunks.join(''),
10225
+ stderr: streamedStderrChunks.join('') + errLine,
10226
+ testResults: streamedTestResults.slice(),
10227
+ testSummary: buildTestSummary(),
9822
10228
  fsSnapshot: [],
9823
10229
  httpTrace: [],
9824
10230
  error: { message: msg.error?.message || 'Worker execution error', stack: msg.error?.stack }
@@ -9826,19 +10232,40 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9826
10232
  }
9827
10233
  };
9828
10234
 
9829
- worker.onerror = () => {
10235
+ worker.onerror = (errEvent) => {
9830
10236
  if (settled) return;
9831
10237
  settled = true;
9832
10238
  clearTimeout(timer);
9833
10239
  releaseWorker(true);
9834
- resolve(_hostRuntime.executeInVirtualRuntime(options));
10240
+ // Only fall back to in-process execution if the host blocked Blob Worker startup
10241
+ // BEFORE user code ever started. Never re-run crashed user code on the main thread.
10242
+ if (!userCodeStarted && options.allowMainThreadFallback !== false) {
10243
+ resolve(_hostRuntime.executeInVirtualRuntime(options));
10244
+ return;
10245
+ }
10246
+ const elapsed = Math.max(0, (typeof performance !== 'undefined' ? performance.now() : Date.now()) - startTime);
10247
+ const errMsg = (errEvent && errEvent.message)
10248
+ ? String(errEvent.message)
10249
+ : 'Uncaught fatal error in Web Worker execution';
10250
+ resolve({
10251
+ ok: false,
10252
+ exitCode: 1,
10253
+ durationMs: elapsed,
10254
+ stdout: streamedStdoutChunks.join(''),
10255
+ stderr: streamedStderrChunks.join('') + errMsg + '\n',
10256
+ testResults: streamedTestResults.slice(),
10257
+ testSummary: buildTestSummary(),
10258
+ fsSnapshot: [],
10259
+ httpTrace: [],
10260
+ error: { message: errMsg }
10261
+ });
9835
10262
  };
9836
10263
 
9837
10264
  worker.postMessage({
9838
10265
  requestId,
9839
10266
  type: 'execute',
9840
10267
  payload: {
9841
- files: options.files,
10268
+ files: mergedFiles,
9842
10269
  entry: options.entry,
9843
10270
  mode: options.mode,
9844
10271
  replCode: options.replCode,
@@ -9854,7 +10281,8 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9854
10281
  printReplResult: options.printReplResult,
9855
10282
  stdin: options.stdin,
9856
10283
  wasmBinary: options.wasmBinary,
9857
- env: options.env
10284
+ env: options.env,
10285
+ cwd: options.cwd
9858
10286
  }
9859
10287
  });
9860
10288
  });
@@ -9904,6 +10332,7 @@ const createSqliteDatabase = CodeLabRuntime.createSqliteDatabase;
9904
10332
  const executeInVirtualRuntime = CodeLabRuntime.executeInVirtualRuntime;
9905
10333
  const createWorkerRuntimeSource = CodeLabRuntime.createWorkerRuntimeSource;
9906
10334
  const cancelWorkerExecution = CodeLabRuntime.cancelWorkerExecution;
10335
+ const destroyWorkerPool = CodeLabRuntime.destroyWorkerPool;
9907
10336
  const executeInWorker = CodeLabRuntime.executeInWorker;
9908
10337
 
9909
10338
  export {
@@ -9936,6 +10365,7 @@ export {
9936
10365
  executeInVirtualRuntime,
9937
10366
  createWorkerRuntimeSource,
9938
10367
  cancelWorkerExecution,
10368
+ destroyWorkerPool,
9939
10369
  executeInWorker
9940
10370
  };
9941
10371
  export default CodeLabRuntime;