@innovatorved/code-lab 0.3.2 → 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 (155) hide show
  1. package/ARCHITECTURE.md +5 -3
  2. package/CHANGELOG.md +20 -0
  3. package/README.md +70 -168
  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 +246 -0
  10. package/dist/code-lab.d.ts +110 -15
  11. package/dist/code-lab.esm.js +34265 -18104
  12. package/dist/code-lab.js +33186 -17053
  13. package/dist/code-lab.umd.js +65502 -0
  14. package/dist/extensions/cpp.esm.js +19478 -3760
  15. package/dist/extensions/cpp.js +19475 -3757
  16. package/dist/extensions/guided-lab.esm.js +19401 -3725
  17. package/dist/extensions/guided-lab.js +19400 -3724
  18. package/dist/extensions/python.d.ts +1 -0
  19. package/dist/extensions/python.esm.js +19576 -3766
  20. package/dist/extensions/python.js +19576 -3766
  21. package/dist/extensions/umbrella.d.ts +5 -0
  22. package/dist/index.d.ts +1 -1
  23. package/dist/modular-kernel.d.ts +11 -0
  24. package/dist/packages/commands/src/index.d.ts +96 -0
  25. package/dist/packages/core/src/di.d.ts +36 -0
  26. package/dist/packages/core/src/disposable.d.ts +27 -0
  27. package/dist/packages/core/src/errors.d.ts +69 -0
  28. package/dist/packages/core/src/events.d.ts +38 -0
  29. package/dist/packages/core/src/index.d.ts +6 -0
  30. package/dist/packages/core/src/path.d.ts +14 -0
  31. package/dist/packages/core/src/registry.d.ts +23 -0
  32. package/dist/packages/editor/src/index.d.ts +118 -0
  33. package/dist/packages/fs/src/backends.d.ts +37 -0
  34. package/dist/packages/fs/src/index.d.ts +3 -0
  35. package/dist/packages/fs/src/types.d.ts +40 -0
  36. package/dist/packages/fs/src/vfs-service.d.ts +33 -0
  37. package/dist/packages/preview/src/index.d.ts +34 -0
  38. package/dist/packages/runtime/src/index.d.ts +47 -0
  39. package/dist/packages/settings/src/builtin-schemas.d.ts +15 -0
  40. package/dist/packages/settings/src/configuration-service.d.ts +100 -0
  41. package/dist/packages/settings/src/index.d.ts +4 -0
  42. package/dist/packages/settings/src/jsonc.d.ts +20 -0
  43. package/dist/packages/settings/src/schema.d.ts +28 -0
  44. package/dist/packages/sql/src/completions.d.ts +8 -0
  45. package/dist/packages/sql/src/diagnostics.d.ts +2 -0
  46. package/dist/packages/sql/src/formatter.d.ts +2 -0
  47. package/dist/packages/sql/src/index.d.ts +7 -0
  48. package/dist/packages/sql/src/sql-editor.d.ts +2 -0
  49. package/dist/packages/sql/src/styles.d.ts +2 -0
  50. package/dist/packages/sql/src/tokenizer.d.ts +13 -0
  51. package/dist/packages/sql/src/types.d.ts +130 -0
  52. package/dist/packages/terminal/src/index.d.ts +54 -0
  53. package/dist/packages/ui/src/index.d.ts +4 -0
  54. package/dist/packages/ui/src/observability.d.ts +22 -0
  55. package/dist/packages/ui/src/plugin-registry.d.ts +89 -0
  56. package/dist/packages/ui/src/settings-dialog.d.ts +25 -0
  57. package/dist/packages/ui/src/themes.d.ts +35 -0
  58. package/dist/preview-sw.js +53 -12
  59. package/dist/runtime.d.ts +3 -3
  60. package/dist/runtime.esm.js +467 -44
  61. package/dist/runtime.js +465 -44
  62. package/dist/schemas.d.ts +234 -814
  63. package/dist/schemas.esm.js +19401 -3725
  64. package/dist/schemas.js +19404 -3728
  65. package/dist/shell.d.ts +1 -1
  66. package/dist/shell.esm.js +364 -39
  67. package/dist/shell.js +364 -39
  68. package/dist/terminal.esm.js +62 -3
  69. package/dist/terminal.js +62 -3
  70. package/dist/workbench/diff-editor.d.ts +1 -0
  71. package/package.json +37 -8
  72. package/packages/commands/README.md +7 -0
  73. package/packages/commands/package.json +16 -0
  74. package/packages/commands/src/index.ts +467 -0
  75. package/packages/commands/tsconfig.json +22 -0
  76. package/packages/core/README.md +12 -0
  77. package/packages/core/package.json +13 -0
  78. package/packages/core/src/di.ts +147 -0
  79. package/packages/core/src/disposable.ts +112 -0
  80. package/packages/core/src/errors.ts +205 -0
  81. package/packages/core/src/events.ts +157 -0
  82. package/packages/core/src/index.ts +49 -0
  83. package/packages/core/src/path.ts +118 -0
  84. package/packages/core/src/registry.ts +61 -0
  85. package/packages/core/tsconfig.json +19 -0
  86. package/packages/editor/README.md +9 -0
  87. package/packages/editor/package.json +18 -0
  88. package/packages/editor/src/index.ts +344 -0
  89. package/packages/editor/tsconfig.json +24 -0
  90. package/packages/fs/README.md +7 -0
  91. package/packages/fs/package.json +16 -0
  92. package/packages/fs/src/backends.ts +301 -0
  93. package/packages/fs/src/index.ts +18 -0
  94. package/packages/fs/src/types.ts +44 -0
  95. package/packages/fs/src/vfs-service.ts +257 -0
  96. package/packages/fs/tsconfig.json +22 -0
  97. package/packages/preview/README.md +3 -0
  98. package/packages/preview/package.json +16 -0
  99. package/packages/preview/src/index.ts +125 -0
  100. package/packages/preview/tsconfig.json +22 -0
  101. package/packages/runtime/README.md +3 -0
  102. package/packages/runtime/package.json +17 -0
  103. package/packages/runtime/src/index.ts +134 -0
  104. package/packages/runtime/tsconfig.json +23 -0
  105. package/packages/settings/README.md +7 -0
  106. package/packages/settings/package.json +16 -0
  107. package/packages/settings/src/builtin-schemas.ts +235 -0
  108. package/packages/settings/src/configuration-service.ts +543 -0
  109. package/packages/settings/src/index.ts +37 -0
  110. package/packages/settings/src/jsonc.ts +189 -0
  111. package/packages/settings/src/schema.ts +164 -0
  112. package/packages/settings/tsconfig.json +22 -0
  113. package/packages/sql/README.md +12 -0
  114. package/packages/sql/package.json +13 -0
  115. package/packages/sql/src/completions.ts +359 -0
  116. package/packages/sql/src/diagnostics.ts +200 -0
  117. package/packages/sql/src/formatter.ts +271 -0
  118. package/packages/sql/src/index.ts +54 -0
  119. package/packages/sql/src/sql-editor.ts +802 -0
  120. package/packages/sql/src/styles.ts +501 -0
  121. package/packages/sql/src/tokenizer.ts +457 -0
  122. package/packages/sql/src/types.ts +148 -0
  123. package/packages/sql/tsconfig.json +19 -0
  124. package/packages/terminal/README.md +3 -0
  125. package/packages/terminal/package.json +16 -0
  126. package/packages/terminal/src/index.ts +183 -0
  127. package/packages/terminal/tsconfig.json +22 -0
  128. package/packages/ui/README.md +8 -0
  129. package/packages/ui/package.json +18 -0
  130. package/packages/ui/src/index.ts +36 -0
  131. package/packages/ui/src/observability.ts +175 -0
  132. package/packages/ui/src/plugin-registry.ts +274 -0
  133. package/packages/ui/src/settings-dialog.ts +293 -0
  134. package/packages/ui/src/themes.ts +174 -0
  135. package/packages/ui/tsconfig.json +24 -0
  136. package/src/code-lab.css +246 -0
  137. package/src/extensions/cpp.ts +58 -15
  138. package/src/extensions/python.ts +156 -24
  139. package/src/extensions/umbrella.ts +5 -0
  140. package/src/index.ts +1 -1
  141. package/src/modular-kernel.ts +11 -0
  142. package/src/preview-sw.js +52 -11
  143. package/src/runtime.ts +466 -46
  144. package/src/schemas.ts +62 -62
  145. package/src/shell.ts +363 -39
  146. package/src/terminal.ts +60 -2
  147. package/src/workbench/diff-editor.ts +66 -6
  148. package/src/workbench/icons.ts +5 -2
  149. package/src/workbench.ts +2410 -220
  150. package/dist/runtime/index.d.ts +0 -4
  151. package/dist/shell/coreutils/compilers-cli.d.ts +0 -24
  152. package/dist/shell/index.d.ts +0 -4
  153. package/src/runtime/index.ts +0 -5
  154. package/src/shell/coreutils/compilers-cli.ts +0 -103
  155. package/src/shell/index.ts +0 -5
package/dist/runtime.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.3.2 — 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
@@ -87,6 +87,7 @@ var CodeLabLogger = (() => {
87
87
  } catch (err) {
88
88
  sinkError = err;
89
89
  }
90
+ void sinkError;
90
91
  }
91
92
  const consoleObj = typeof console !== "undefined" ? console : null;
92
93
  const fn = consoleObj ? consoleObj[level] : null;
@@ -1238,7 +1239,13 @@ function __initVirtualRuntime(rootScope) {
1238
1239
  });
1239
1240
  }
1240
1241
 
1242
+ let _activeStdin = '';
1243
+
1241
1244
  const fsShim = {
1245
+ _setActiveStdin(text) {
1246
+ _activeStdin = text !== undefined && text !== null ? String(text) : '';
1247
+ },
1248
+
1242
1249
  existsSync(p) {
1243
1250
  try {
1244
1251
  const np = normPath(p);
@@ -1463,6 +1470,11 @@ function __initVirtualRuntime(rootScope) {
1463
1470
  },
1464
1471
 
1465
1472
  readFileSync(p, opts) {
1473
+ if (p === 0 || p === '/dev/stdin') {
1474
+ const stdinBuf = VirtualBuffer.from(String(_activeStdin || ''), 'utf8');
1475
+ const encoding = typeof opts === 'string' ? opts : (opts && opts.encoding);
1476
+ return encoding ? stdinBuf.toString(encoding) : stdinBuf;
1477
+ }
1466
1478
  const np = normPath(p);
1467
1479
  if (dirs.has(np)) throw fsError('EISDIR', 'read', p, 'illegal operation on a directory');
1468
1480
  const inode = files.get(np);
@@ -1822,6 +1834,10 @@ function __initVirtualRuntime(rootScope) {
1822
1834
 
1823
1835
  items.sort((a, b) => a.path.localeCompare(b.path));
1824
1836
  return items;
1837
+ },
1838
+
1839
+ _listOpenFds() {
1840
+ return Array.from(fdTable.keys());
1825
1841
  }
1826
1842
  };
1827
1843
 
@@ -1976,6 +1992,13 @@ function __initVirtualRuntime(rootScope) {
1976
1992
  };
1977
1993
 
1978
1994
  fsShim.promises = fsPromises;
1995
+ fsShim._exportRawState = () => {
1996
+ const clonedFiles = new Map();
1997
+ for (const [k, v] of files.entries()) {
1998
+ clonedFiles.set(k, v.data instanceof Uint8Array ? v.data.slice() : new Uint8Array(v.data || 0));
1999
+ }
2000
+ return { files: clonedFiles, dirs: new Set(dirs) };
2001
+ };
1979
2002
 
1980
2003
  return fsShim;
1981
2004
  }
@@ -4706,13 +4729,17 @@ function __initVirtualRuntime(rootScope) {
4706
4729
  function transpileTS(source, filename = 'module.ts', opts = {}) {
4707
4730
  // `keepEsm` leaves `import`/`export` statements intact so the output can run
4708
4731
  // natively in a browser as an ES module (used by the built-in preview server).
4709
- const keepEsm = Boolean(opts && opts.keepEsm);
4710
- const isTS = /\.(ts|tsx|mts|cts)$/i.test(filename)
4732
+ const keepEsm = Boolean(opts && (opts.keepEsm || opts.expressionOnly));
4733
+ const expressionOnly = Boolean(opts && opts.expressionOnly);
4734
+ const isTS = expressionOnly
4735
+ || /\.(ts|tsx|mts|cts)$/i.test(filename)
4711
4736
  || /^[ \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);
4712
- const hasESM = /^\s*(?:import|export)\b/m.test(source)
4737
+ const hasESM = !expressionOnly && (
4738
+ /^\s*(?:import|export)\b/m.test(source)
4713
4739
  || /\bexport\s*\{/.test(source)
4714
4740
  || /\bimport\s*\{/.test(source)
4715
- || /\bexport\s+default\b/.test(source);
4741
+ || /\bexport\s+default\b/.test(source)
4742
+ );
4716
4743
  const hasJsx = detectJsxSyntax(source, filename);
4717
4744
  if (!isTS && !hasESM && !hasJsx) return source;
4718
4745
 
@@ -4720,7 +4747,7 @@ function __initVirtualRuntime(rootScope) {
4720
4747
  if (hasJsx) {
4721
4748
  const { pragma, frag } = readJsxPragma(source);
4722
4749
  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);
4723
- const needsReact = pragma === 'React.createElement' && (keepEsm ? !hasReactBinding : !/\bReact\b/.test(source));
4750
+ const needsReact = !expressionOnly && pragma === 'React.createElement' && (keepEsm ? !hasReactBinding : !/\bReact\b/.test(source));
4724
4751
  const transformed = jsxTransform(source, { pragma, frag });
4725
4752
  if (transformed !== source) {
4726
4753
  source = transformed;
@@ -4808,18 +4835,80 @@ function __initVirtualRuntime(rootScope) {
4808
4835
  i = j;
4809
4836
  continue;
4810
4837
  }
4811
- // Template literal
4838
+ // Template literal (recursively transpile TypeScript inside ${...} expressions)
4812
4839
  if (ch === '`') {
4813
4840
  let j = i + 1;
4814
- let depth = 0;
4841
+ let rebuilt = '`';
4815
4842
  while (j < len) {
4816
- if (source[j] === '\\') { j += 2; continue; }
4817
- if (source[j] === '$' && source[j + 1] === '{') { depth++; j += 2; continue; }
4818
- if (source[j] === '}' && depth > 0) { depth--; j++; continue; }
4819
- if (source[j] === '`' && depth === 0) { j++; break; }
4843
+ if (source[j] === '\\') {
4844
+ rebuilt += source.slice(j, j + 2);
4845
+ j += 2;
4846
+ continue;
4847
+ }
4848
+ if (source[j] === '`' ) {
4849
+ rebuilt += '`';
4850
+ j++;
4851
+ break;
4852
+ }
4853
+ if (source[j] === '$' && source[j + 1] === '{') {
4854
+ j += 2;
4855
+ const exprStart = j;
4856
+ let braceDepth = 1;
4857
+ while (j < len && braceDepth > 0) {
4858
+ const ec = source[j];
4859
+ const en = source[j + 1];
4860
+ if (ec === '/' && en === '/') {
4861
+ j += 2;
4862
+ while (j < len && source[j] !== '\n') j++;
4863
+ continue;
4864
+ }
4865
+ if (ec === '/' && en === '*') {
4866
+ j += 2;
4867
+ while (j < len && !(source[j] === '*' && source[j + 1] === '/')) j++;
4868
+ j += 2;
4869
+ continue;
4870
+ }
4871
+ if (ec === "'" || ec === '"') {
4872
+ const q = ec;
4873
+ j++;
4874
+ while (j < len && source[j] !== q && source[j] !== '\n') {
4875
+ if (source[j] === '\\') j += 2;
4876
+ else j++;
4877
+ }
4878
+ if (j < len && source[j] === q) j++;
4879
+ continue;
4880
+ }
4881
+ if (ec === '`') {
4882
+ j++;
4883
+ let nestedDepth = 0;
4884
+ while (j < len) {
4885
+ if (source[j] === '\\') { j += 2; continue; }
4886
+ if (source[j] === '$' && source[j + 1] === '{') { nestedDepth++; j += 2; continue; }
4887
+ if (source[j] === '}' && nestedDepth > 0) { nestedDepth--; j++; continue; }
4888
+ if (source[j] === '`' && nestedDepth === 0) { j++; break; }
4889
+ j++;
4890
+ }
4891
+ continue;
4892
+ }
4893
+ if (ec === '{') braceDepth++;
4894
+ else if (ec === '}') {
4895
+ braceDepth--;
4896
+ if (braceDepth === 0) break;
4897
+ }
4898
+ j++;
4899
+ }
4900
+ const rawExpr = source.slice(exprStart, j);
4901
+ const transpiledExpr = isTS
4902
+ ? transpileTS(rawExpr, filename, { expressionOnly: true })
4903
+ : rawExpr;
4904
+ rebuilt += '${' + transpiledExpr + '}';
4905
+ if (j < len && source[j] === '}') j++;
4906
+ continue;
4907
+ }
4908
+ rebuilt += source[j];
4820
4909
  j++;
4821
4910
  }
4822
- code += mask(source.slice(i, j));
4911
+ code += mask(rebuilt);
4823
4912
  i = j;
4824
4913
  continue;
4825
4914
  }
@@ -5193,8 +5282,8 @@ function __initVirtualRuntime(rootScope) {
5193
5282
  };
5194
5283
  code = stripReturnTypes(code);
5195
5284
 
5196
- // Strip parameter type annotations inside `(...)` (supports multi-line parameter lists and default value `()` calls)
5197
- code = code.replace(/\(((?:[^()]|\([^()]*\))*)\)/g, (full, inner) => {
5285
+ // Strip parameter type annotations inside `(...)` from innermost parens outward so nested callbacks work
5286
+ const stripParensParamTypes = (full, inner) => {
5198
5287
  if (!inner.includes(':')) return full;
5199
5288
  if (inner.includes('?') && !/[A-Za-z0-9_$}\]]\s*\?\s*:/.test(inner)) return full;
5200
5289
  if (/[{}]/.test(inner) && !/\}\s*\??\s*:/.test(inner) && !/:\s*[A-Za-z_$][A-Za-z0-9_$.<>[\]|&\s]*\{/.test(inner)) {
@@ -5208,7 +5297,12 @@ function __initVirtualRuntime(rootScope) {
5208
5297
  const parts = splitTopLevel(inner, ',');
5209
5298
  const cleaned = parts.map((part) => cleanSingleParam(part));
5210
5299
  return `(${cleaned.join(',')})`;
5211
- });
5300
+ };
5301
+ do {
5302
+ prevCode = code;
5303
+ code = code.replace(/\(([^()]*)\)/g, stripParensParamTypes);
5304
+ } while (code !== prevCode);
5305
+ code = code.replace(/\(((?:[^()]|\([^()]*\))*)\)/g, stripParensParamTypes);
5212
5306
 
5213
5307
  // Strip variable type annotations: `const x: Type =`, `let y: Type =`
5214
5308
  code = code.replace(/\b(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*:\s*[^=;\n]+(?<![=!<>])=(?![=>])/g, '$1 $2 =');
@@ -5339,7 +5433,31 @@ function __initVirtualRuntime(rootScope) {
5339
5433
  hasEsmExport = true;
5340
5434
  return `Object.assign(exports, require(${mod.trim()}));`;
5341
5435
  });
5342
- code = code.replace(/\bexport\s+default\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
5436
+ const collectBindingIds = (pattern) => {
5437
+ const ids = [];
5438
+ const inner = pattern.trim().replace(/^[\[{]|[\]}]$/g, '');
5439
+ const isObj = pattern.trim().startsWith('{');
5440
+ for (const rawPart of splitTopLevel(inner, ',')) {
5441
+ let part = rawPart.trim();
5442
+ if (!part) continue;
5443
+ if (part.startsWith('...')) {
5444
+ part = part.slice(3).trim();
5445
+ } else if (isObj && part.includes(':')) {
5446
+ const colonIdx = part.indexOf(':');
5447
+ part = part.slice(colonIdx + 1).trim();
5448
+ }
5449
+ const eqIdx = part.indexOf('=');
5450
+ if (eqIdx !== -1) part = part.slice(0, eqIdx).trim();
5451
+ if ((part.startsWith('{') && part.endsWith('}')) || (part.startsWith('[') && part.endsWith(']'))) {
5452
+ ids.push(...collectBindingIds(part));
5453
+ } else if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(part)) {
5454
+ ids.push(part);
5455
+ }
5456
+ }
5457
+ return ids;
5458
+ };
5459
+
5460
+ 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) => {
5343
5461
  hasEsmExport = true;
5344
5462
  defaultExportName = name;
5345
5463
  return `${kw} ${name}`;
@@ -5348,11 +5466,16 @@ function __initVirtualRuntime(rootScope) {
5348
5466
  hasEsmExport = true;
5349
5467
  return 'exports.default = ';
5350
5468
  });
5351
- code = code.replace(/\bexport\s+(async\s+function|function|class)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
5469
+ 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) => {
5352
5470
  hasEsmExport = true;
5353
5471
  exportedNames.push(name);
5354
5472
  return `${kw} ${name}`;
5355
5473
  });
5474
+ code = code.replace(/\bexport\s+(const|let|var)\s+(\{[^;=\n]+\}|\[[^;=\n]+\])\s*=/gm, (_, kw, pat) => {
5475
+ hasEsmExport = true;
5476
+ exportedNames.push(...collectBindingIds(pat));
5477
+ return `${kw} ${pat} =`;
5478
+ });
5356
5479
  code = code.replace(/\bexport\s+(const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/gm, (_, kw, name) => {
5357
5480
  hasEsmExport = true;
5358
5481
  exportedNames.push(name);
@@ -6484,10 +6607,16 @@ function __initVirtualRuntime(rootScope) {
6484
6607
  const activePortTable = optPortTable || portTable || _defaultPortTable;
6485
6608
  resourceTracker.pid = pid;
6486
6609
 
6487
- let currentCwd = '/workspace';
6610
+ const prevCwdGetter = _activeCwdGetter;
6611
+ let currentCwd = (typeof options.cwd === 'string' && options.cwd.trim())
6612
+ ? VirtualPath.resolve('/workspace', options.cwd.trim())
6613
+ : '/workspace';
6488
6614
  _activeCwdGetter = () => currentCwd;
6489
6615
 
6490
6616
  const vfs = optVfs || createVirtualFs(files, { cwdGetter: () => currentCwd });
6617
+ const initialOpenFds = typeof vfs._listOpenFds === 'function'
6618
+ ? new Set(vfs._listOpenFds())
6619
+ : null;
6491
6620
  if (optVfs && files && typeof files === 'object') {
6492
6621
  for (const [fPath, content] of Object.entries(files)) {
6493
6622
  const abs = fPath.startsWith('/') ? fPath : '/workspace/' + fPath;
@@ -6500,6 +6629,9 @@ function __initVirtualRuntime(rootScope) {
6500
6629
  }
6501
6630
  }
6502
6631
  }
6632
+ if (typeof vfs._setActiveStdin === 'function') {
6633
+ vfs._setActiveStdin(options && options.stdin ? String(options.stdin) : '');
6634
+ }
6503
6635
  const vhttp = createVirtualHttp(resourceTracker, activePortTable);
6504
6636
  const vnet = createVirtualNet(resourceTracker, vhttp.getTrace());
6505
6637
 
@@ -6522,6 +6654,10 @@ function __initVirtualRuntime(rootScope) {
6522
6654
  }
6523
6655
  }
6524
6656
 
6657
+ const initialVfsState = (options && options._captureVfsDiff && typeof vfs._exportRawState === 'function')
6658
+ ? vfs._exportRawState()
6659
+ : null;
6660
+
6525
6661
  // Custom timer wrappers supporting .unref() / .ref() and active handle tracking
6526
6662
  function makeTimerHandle(rawId, isInterval) {
6527
6663
  const handle = {
@@ -6883,7 +7019,7 @@ function __initVirtualRuntime(rootScope) {
6883
7019
  let syncExecDepth = 0;
6884
7020
 
6885
7021
  const sandboxProcess = Object.assign(new EventEmitter(), {
6886
- env: { NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' },
7022
+ env: Object.assign({ NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' }, options.env || {}),
6887
7023
  argv: argv || ['node', entry.startsWith('/') ? entry : `/workspace/${entry}`],
6888
7024
  argv0: 'node',
6889
7025
  execArgv: [],
@@ -6963,6 +7099,9 @@ function __initVirtualRuntime(rootScope) {
6963
7099
  }
6964
7100
 
6965
7101
  // Immediately cancel all active timers and immediates
7102
+ if (typeof vfs._setActiveStdin === 'function') {
7103
+ vfs._setActiveStdin('');
7104
+ }
6966
7105
  for (const rawId of resourceTracker.allTimers) {
6967
7106
  clearTimeout(rawId);
6968
7107
  clearInterval(rawId);
@@ -8878,6 +9017,9 @@ function __initVirtualRuntime(rootScope) {
8878
9017
  hasExited = true;
8879
9018
  try { sandboxProcess.emit('exit', exitCode); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime exit listener failed', err); }
8880
9019
  }
9020
+ if (typeof vfs._setActiveStdin === 'function') {
9021
+ vfs._setActiveStdin('');
9022
+ }
8881
9023
  for (const rawId of resourceTracker.allTimers) {
8882
9024
  clearTimeout(rawId);
8883
9025
  clearInterval(rawId);
@@ -8894,12 +9036,56 @@ function __initVirtualRuntime(rootScope) {
8894
9036
  if (!isBackground) {
8895
9037
  vhttp.closeAllServers();
8896
9038
  vnet.closeAllServers();
9039
+ if (initialOpenFds && typeof vfs._listOpenFds === 'function' && typeof vfs.closeSync === 'function') {
9040
+ for (const fd of vfs._listOpenFds()) {
9041
+ if (!initialOpenFds.has(fd)) {
9042
+ try { vfs.closeSync(fd); } catch (err) { _runtimeLogger.debug('executeInVirtualRuntime closeSync leak cleanup failed', { fd, err }); }
9043
+ }
9044
+ }
9045
+ }
8897
9046
  }
9047
+ _activeCwdGetter = prevCwdGetter;
8898
9048
  }
8899
9049
 
8900
9050
  const failedTests = testResults.filter((t) => !t.passed).length;
8901
9051
  if (failedTests > 0 && exitCode === 0) exitCode = 1;
8902
9052
 
9053
+ let vfsChanges = undefined;
9054
+ if (initialVfsState && typeof vfs._exportRawState === 'function') {
9055
+ const finalVfsState = vfs._exportRawState();
9056
+ const modifiedFiles = {};
9057
+ const deletedFiles = [];
9058
+ const createdDirs = [];
9059
+ const isNodeModulesPath = (p) => p === '/workspace/node_modules' || p.startsWith('/workspace/node_modules/');
9060
+ const bytesEqual = (a, b) => {
9061
+ if (!a || !b || a.byteLength !== b.byteLength) return false;
9062
+ for (let i = 0; i < a.byteLength; i++) {
9063
+ if (a[i] !== b[i]) return false;
9064
+ }
9065
+ return true;
9066
+ };
9067
+
9068
+ for (const d of finalVfsState.dirs) {
9069
+ if (!initialVfsState.dirs.has(d) && !isNodeModulesPath(d)) {
9070
+ createdDirs.push(d);
9071
+ }
9072
+ }
9073
+ for (const [fPath, data] of finalVfsState.files.entries()) {
9074
+ if (isNodeModulesPath(fPath)) continue;
9075
+ const prev = initialVfsState.files.get(fPath);
9076
+ if (!prev || !bytesEqual(prev, data)) {
9077
+ modifiedFiles[fPath] = data;
9078
+ }
9079
+ }
9080
+ for (const fPath of initialVfsState.files.keys()) {
9081
+ if (isNodeModulesPath(fPath)) continue;
9082
+ if (!finalVfsState.files.has(fPath)) {
9083
+ deletedFiles.push(fPath);
9084
+ }
9085
+ }
9086
+ vfsChanges = { modifiedFiles, deletedFiles, createdDirs };
9087
+ }
9088
+
8903
9089
  return {
8904
9090
  ok: exitCode === 0,
8905
9091
  exitCode,
@@ -8915,6 +9101,7 @@ function __initVirtualRuntime(rootScope) {
8915
9101
  failed: failedTests
8916
9102
  },
8917
9103
  fsSnapshot: typeof vfs.getSnapshot === 'function' ? vfs.getSnapshot() : [],
9104
+ ...(vfsChanges ? { vfsChanges } : {}),
8918
9105
  httpTrace: [...vhttp.getTrace(), ...vnet.getTrace()],
8919
9106
  replValue: replValue !== undefined ? formatConsoleArg(replValue) : undefined
8920
9107
  };
@@ -9303,14 +9490,70 @@ function __initVirtualRuntime(rootScope) {
9303
9490
 
9304
9491
  exec(sql) {
9305
9492
  const cleaned = stripSqlComments(sql);
9306
- const statements = cleaned.split(';').map((s) => s.trim()).filter(Boolean);
9493
+ const statements = [];
9494
+ let cur = '';
9495
+ let i = 0;
9496
+ while (i < cleaned.length) {
9497
+ const ch = cleaned[i];
9498
+ if (ch === "'" || ch === '"') {
9499
+ const quote = ch;
9500
+ cur += ch;
9501
+ i++;
9502
+ while (i < cleaned.length) {
9503
+ if (cleaned[i] === quote && cleaned[i + 1] === quote) {
9504
+ cur += quote + quote;
9505
+ i += 2;
9506
+ continue;
9507
+ }
9508
+ if (cleaned[i] === '\\' && quote === '"') {
9509
+ cur += cleaned.slice(i, i + 2);
9510
+ i += 2;
9511
+ continue;
9512
+ }
9513
+ cur += cleaned[i];
9514
+ if (cleaned[i] === quote) {
9515
+ i++;
9516
+ break;
9517
+ }
9518
+ i++;
9519
+ }
9520
+ continue;
9521
+ }
9522
+ if (ch === ';') {
9523
+ const trimmed = cur.trim();
9524
+ if (trimmed) statements.push(trimmed);
9525
+ cur = '';
9526
+ i++;
9527
+ continue;
9528
+ }
9529
+ cur += ch;
9530
+ i++;
9531
+ }
9532
+ if (cur.trim()) statements.push(cur.trim());
9307
9533
  for (const s of statements) {
9308
9534
  this.run(s);
9309
9535
  }
9310
9536
  }
9311
9537
 
9312
9538
  transaction(fn) {
9313
- return (...args) => fn(...args);
9539
+ const db = this;
9540
+ return (...args) => {
9541
+ const snapshot = new Map();
9542
+ for (const [tblName, tbl] of db.tables.entries()) {
9543
+ snapshot.set(tblName, {
9544
+ columns: tbl.columns.map((c) => Object.assign({}, c)),
9545
+ rows: tbl.rows.map((r) => Object.assign({}, r)),
9546
+ autoInc: tbl.autoInc
9547
+ });
9548
+ }
9549
+ try {
9550
+ return fn(...args);
9551
+ } catch (err) {
9552
+ db.tables = snapshot;
9553
+ db._persistToVfs();
9554
+ throw err;
9555
+ }
9556
+ };
9314
9557
  }
9315
9558
 
9316
9559
  close() {
@@ -9599,9 +9842,11 @@ function __workerMessageLoop(workerScope) {
9599
9842
  const msg = event.data || {};
9600
9843
  const { requestId, type, payload = {} } = msg;
9601
9844
  if (type !== 'execute') return;
9845
+ workerScope.postMessage({ requestId, type: 'started' });
9602
9846
  try {
9603
9847
  const result = await runtime.executeInVirtualRuntime({
9604
9848
  ...payload,
9849
+ _captureVfsDiff: true,
9605
9850
  onStdout(text) {
9606
9851
  workerScope.postMessage({ requestId, type: 'stdout', text });
9607
9852
  },
@@ -9653,7 +9898,10 @@ function _ensureWorkerUrl() {
9653
9898
  }
9654
9899
 
9655
9900
  function _ensureWarmWorker() {
9656
- if (_warmWorker) return _warmWorker;
9901
+ if (_warmWorker && typeof Worker === 'function' && _warmWorker instanceof Worker) {
9902
+ return _warmWorker;
9903
+ }
9904
+ if (_warmWorker) _destroyWarmWorker();
9657
9905
  _warmWorker = new Worker(_ensureWorkerUrl());
9658
9906
  return _warmWorker;
9659
9907
  }
@@ -9666,6 +9914,14 @@ function _destroyWarmWorker() {
9666
9914
  _warmWorkerBusy = false;
9667
9915
  }
9668
9916
 
9917
+ _hostRuntime.destroyWorkerPool = function destroyWorkerPool() {
9918
+ _destroyWarmWorker();
9919
+ if (_cachedWorkerUrl && typeof URL !== 'undefined' && typeof URL.revokeObjectURL === 'function') {
9920
+ try { URL.revokeObjectURL(_cachedWorkerUrl); } catch (err) { _hostLogger.debug('revokeObjectURL failed', err); }
9921
+ }
9922
+ _cachedWorkerUrl = null;
9923
+ };
9924
+
9669
9925
  _hostRuntime.cancelWorkerExecution = function cancelWorkerExecution(reason = 'Execution cancelled', instanceId) {
9670
9926
  let cancelledAny = false;
9671
9927
  for (const [jobId, job] of Array.from(_activeWorkerJobs.entries())) {
@@ -9678,11 +9934,118 @@ _hostRuntime.cancelWorkerExecution = function cancelWorkerExecution(reason = 'Ex
9678
9934
  return cancelledAny;
9679
9935
  };
9680
9936
 
9937
+ function _extractWorkerFilesFromVfs(vfs) {
9938
+ const extracted = {};
9939
+ if (!vfs || typeof vfs !== 'object') return extracted;
9940
+ try {
9941
+ if (typeof vfs._exportRawState === 'function') {
9942
+ const st = vfs._exportRawState();
9943
+ for (const [absPath, bytes] of st.files.entries()) {
9944
+ extracted[absPath] = bytes;
9945
+ }
9946
+ return extracted;
9947
+ }
9948
+ if (vfs.files instanceof Map) {
9949
+ for (const [absPath, entry] of vfs.files.entries()) {
9950
+ if (!entry) continue;
9951
+ const data = entry.data !== undefined ? entry.data : entry;
9952
+ if (typeof data === 'string') {
9953
+ extracted[absPath] = data;
9954
+ } else if (data instanceof Uint8Array) {
9955
+ extracted[absPath] = data.slice();
9956
+ } else if (ArrayBuffer.isView(data)) {
9957
+ extracted[absPath] = new Uint8Array(data.buffer, data.byteOffset, data.byteLength).slice();
9958
+ }
9959
+ }
9960
+ return extracted;
9961
+ }
9962
+ if (typeof vfs.readdirSync === 'function' && typeof vfs.readFileSync === 'function') {
9963
+ const walk = (dir) => {
9964
+ let entries = [];
9965
+ try { entries = vfs.readdirSync(dir); } catch (_) { return; }
9966
+ for (const name of entries) {
9967
+ const full = dir === '/' ? '/' + name : dir + '/' + name;
9968
+ let isDir = false;
9969
+ try { isDir = vfs.statSync(full).isDirectory(); } catch (_) { isDir = false; }
9970
+ if (isDir) walk(full);
9971
+ else {
9972
+ try {
9973
+ const raw = vfs.readFileSync(full);
9974
+ extracted[full] = raw instanceof Uint8Array
9975
+ ? raw.slice()
9976
+ : (typeof raw === 'string' ? raw : String(raw ?? ''));
9977
+ } catch (err) {
9978
+ _hostLogger.debug('_extractWorkerFilesFromVfs: skip unreadable entry', full, err);
9979
+ }
9980
+ }
9981
+ }
9982
+ };
9983
+ walk('/workspace');
9984
+ walk('/tmp');
9985
+ }
9986
+ } catch (err) {
9987
+ _hostLogger.debug('_extractWorkerFilesFromVfs failed', err);
9988
+ }
9989
+ return extracted;
9990
+ }
9991
+
9992
+ function _applyWorkerVfsChanges(vfs, vfsChanges) {
9993
+ if (!vfs || !vfsChanges || typeof vfsChanges !== 'object') return;
9994
+ const { createdDirs = [], modifiedFiles = {}, deletedFiles = [] } = vfsChanges;
9995
+ try {
9996
+ if (Array.isArray(createdDirs) && typeof vfs.mkdirSync === 'function') {
9997
+ for (const dir of createdDirs) {
9998
+ try {
9999
+ vfs.mkdirSync(dir, { recursive: true });
10000
+ } catch (err) {
10001
+ _hostLogger.debug('_applyWorkerVfsChanges: mkdirSync failed', dir, err);
10002
+ }
10003
+ }
10004
+ }
10005
+ if (modifiedFiles && typeof modifiedFiles === 'object') {
10006
+ for (const [absPath, rawBytes] of Object.entries(modifiedFiles)) {
10007
+ const slashIdx = absPath.lastIndexOf('/');
10008
+ if (slashIdx > 0 && typeof vfs.mkdirSync === 'function') {
10009
+ try {
10010
+ vfs.mkdirSync(absPath.slice(0, slashIdx), { recursive: true });
10011
+ } catch (err) {
10012
+ _hostLogger.debug('_applyWorkerVfsChanges: parent mkdirSync failed', absPath, err);
10013
+ }
10014
+ }
10015
+ const payload = rawBytes instanceof Uint8Array
10016
+ ? rawBytes
10017
+ : (ArrayBuffer.isView(rawBytes)
10018
+ ? new Uint8Array(rawBytes.buffer, rawBytes.byteOffset, rawBytes.byteLength)
10019
+ : rawBytes);
10020
+ if (typeof vfs.writeFileSync === 'function') {
10021
+ vfs.writeFileSync(absPath, payload);
10022
+ } else if (typeof vfs.writeFile === 'function') {
10023
+ vfs.writeFile(absPath, payload);
10024
+ }
10025
+ }
10026
+ }
10027
+ if (Array.isArray(deletedFiles)) {
10028
+ for (const absPath of deletedFiles) {
10029
+ try {
10030
+ if (typeof vfs.unlinkSync === 'function') vfs.unlinkSync(absPath);
10031
+ else if (typeof vfs.rmSync === 'function') vfs.rmSync(absPath, { force: true });
10032
+ } catch (err) {
10033
+ _hostLogger.debug('_applyWorkerVfsChanges: delete failed', absPath, err);
10034
+ }
10035
+ }
10036
+ }
10037
+ } catch (err) {
10038
+ _hostLogger.debug('_applyWorkerVfsChanges failed', err);
10039
+ }
10040
+ }
10041
+
9681
10042
  _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9682
10043
  const isNonJs =
9683
10044
  Boolean(options.wasmBinary) ||
9684
10045
  Boolean(options.cppCompiler) ||
9685
10046
  Boolean(options.pythonCompiler) ||
10047
+ Boolean(options.activePortTable) ||
10048
+ Boolean(options.portTable) ||
9686
10049
  (typeof options.entry === 'string' && /\.(cpp|cc|cxx|wasm|py)$/i.test(options.entry));
9687
10050
  if (
9688
10051
  isNonJs ||
@@ -9702,6 +10065,10 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9702
10065
  _hostRuntime.cancelWorkerExecution('Execution cancelled by new run', instanceId);
9703
10066
  }
9704
10067
 
10068
+ const mergedFiles = options.vfs
10069
+ ? Object.assign(_extractWorkerFilesFromVfs(options.vfs), options.files || {})
10070
+ : options.files;
10071
+
9705
10072
  return new Promise((resolve) => {
9706
10073
  let worker;
9707
10074
  let isWarmWorker = false;
@@ -9720,9 +10087,23 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9720
10087
  return;
9721
10088
  }
9722
10089
 
10090
+ const startTime = typeof performance !== 'undefined' ? performance.now() : Date.now();
9723
10091
  const timeoutMs = options.timeoutMs || 15000;
9724
10092
  let settled = false;
10093
+ let userCodeStarted = false;
9725
10094
  let abortListener = null;
10095
+ const streamedStdoutChunks = [];
10096
+ const streamedStderrChunks = [];
10097
+ const streamedTestResults = [];
10098
+
10099
+ const buildTestSummary = () => {
10100
+ const failed = streamedTestResults.filter((t) => !t.passed).length;
10101
+ return {
10102
+ total: streamedTestResults.length,
10103
+ passed: streamedTestResults.length - failed,
10104
+ failed
10105
+ };
10106
+ };
9726
10107
 
9727
10108
  function releaseWorker(terminateWorker) {
9728
10109
  if (options.signal && abortListener) {
@@ -9749,14 +10130,16 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9749
10130
  if (settled) return;
9750
10131
  settled = true;
9751
10132
  releaseWorker(true);
10133
+ const timeoutMsg = `Execution timed out after ${timeoutMs}ms (infinite loop or hung timer terminated).\n`;
9752
10134
  resolve({
9753
10135
  ok: false,
9754
10136
  timedOut: true,
9755
10137
  exitCode: 124,
9756
10138
  durationMs: timeoutMs,
9757
- stdout: '',
9758
- stderr: `Execution timed out after ${timeoutMs}ms (infinite loop or hung timer terminated).\n`,
9759
- testResults: [],
10139
+ stdout: streamedStdoutChunks.join(''),
10140
+ stderr: streamedStderrChunks.join('') + timeoutMsg,
10141
+ testResults: streamedTestResults.slice(),
10142
+ testSummary: buildTestSummary(),
9760
10143
  fsSnapshot: [],
9761
10144
  httpTrace: [],
9762
10145
  error: { message: `Execution timed out after ${timeoutMs}ms` }
@@ -9771,14 +10154,16 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9771
10154
  settled = true;
9772
10155
  clearTimeout(timer);
9773
10156
  releaseWorker(true);
10157
+ const elapsed = Math.max(0, (typeof performance !== 'undefined' ? performance.now() : Date.now()) - startTime);
9774
10158
  resolve({
9775
10159
  ok: false,
9776
10160
  cancelled: true,
9777
10161
  exitCode: 130,
9778
- durationMs: 0,
9779
- stdout: '',
9780
- stderr: `${reason}\n`,
9781
- testResults: [],
10162
+ durationMs: elapsed,
10163
+ stdout: streamedStdoutChunks.join(''),
10164
+ stderr: streamedStderrChunks.join('') + `${reason}\n`,
10165
+ testResults: streamedTestResults.slice(),
10166
+ testSummary: buildTestSummary(),
9782
10167
  fsSnapshot: [],
9783
10168
  httpTrace: [],
9784
10169
  error: { message: reason }
@@ -9802,16 +10187,27 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9802
10187
  worker.onmessage = (event) => {
9803
10188
  const msg = event.data || {};
9804
10189
  if (msg.requestId !== requestId) return;
9805
- if (msg.type === 'stdout' && typeof options.onStdout === 'function') {
9806
- options.onStdout(msg.text);
9807
- } else if (msg.type === 'stderr' && typeof options.onStderr === 'function') {
9808
- options.onStderr(msg.text);
9809
- } else if (msg.type === 'test-result' && typeof options.onTestResult === 'function') {
9810
- options.onTestResult(msg.testResult);
10190
+ if (msg.type === 'started') {
10191
+ userCodeStarted = true;
10192
+ } else if (msg.type === 'stdout') {
10193
+ userCodeStarted = true;
10194
+ if (typeof msg.text === 'string') streamedStdoutChunks.push(msg.text);
10195
+ if (typeof options.onStdout === 'function') options.onStdout(msg.text);
10196
+ } else if (msg.type === 'stderr') {
10197
+ userCodeStarted = true;
10198
+ if (typeof msg.text === 'string') streamedStderrChunks.push(msg.text);
10199
+ if (typeof options.onStderr === 'function') options.onStderr(msg.text);
10200
+ } else if (msg.type === 'test-result') {
10201
+ userCodeStarted = true;
10202
+ if (msg.testResult) streamedTestResults.push(msg.testResult);
10203
+ if (typeof options.onTestResult === 'function') options.onTestResult(msg.testResult);
9811
10204
  } else if (msg.type === 'complete') {
9812
10205
  if (settled) return;
9813
10206
  settled = true;
9814
10207
  clearTimeout(timer);
10208
+ if (options.vfs && msg.result && msg.result.vfsChanges) {
10209
+ _applyWorkerVfsChanges(options.vfs, msg.result.vfsChanges);
10210
+ }
9815
10211
  // Release `_warmWorker` for instant reuse, or terminate ephemeral concurrent worker
9816
10212
  releaseWorker(false);
9817
10213
  resolve(msg.result);
@@ -9820,13 +10216,16 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9820
10216
  settled = true;
9821
10217
  clearTimeout(timer);
9822
10218
  releaseWorker(false);
10219
+ const elapsed = Math.max(0, (typeof performance !== 'undefined' ? performance.now() : Date.now()) - startTime);
10220
+ const errLine = (msg.error?.stack || msg.error?.message || 'Worker execution error') + '\n';
9823
10221
  resolve({
9824
10222
  ok: false,
9825
10223
  exitCode: 1,
9826
- durationMs: 0,
9827
- stdout: '',
9828
- stderr: (msg.error?.stack || msg.error?.message || 'Worker execution error') + '\n',
9829
- testResults: [],
10224
+ durationMs: elapsed,
10225
+ stdout: streamedStdoutChunks.join(''),
10226
+ stderr: streamedStderrChunks.join('') + errLine,
10227
+ testResults: streamedTestResults.slice(),
10228
+ testSummary: buildTestSummary(),
9830
10229
  fsSnapshot: [],
9831
10230
  httpTrace: [],
9832
10231
  error: { message: msg.error?.message || 'Worker execution error', stack: msg.error?.stack }
@@ -9834,19 +10233,40 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9834
10233
  }
9835
10234
  };
9836
10235
 
9837
- worker.onerror = () => {
10236
+ worker.onerror = (errEvent) => {
9838
10237
  if (settled) return;
9839
10238
  settled = true;
9840
10239
  clearTimeout(timer);
9841
10240
  releaseWorker(true);
9842
- resolve(_hostRuntime.executeInVirtualRuntime(options));
10241
+ // Only fall back to in-process execution if the host blocked Blob Worker startup
10242
+ // BEFORE user code ever started. Never re-run crashed user code on the main thread.
10243
+ if (!userCodeStarted && options.allowMainThreadFallback !== false) {
10244
+ resolve(_hostRuntime.executeInVirtualRuntime(options));
10245
+ return;
10246
+ }
10247
+ const elapsed = Math.max(0, (typeof performance !== 'undefined' ? performance.now() : Date.now()) - startTime);
10248
+ const errMsg = (errEvent && errEvent.message)
10249
+ ? String(errEvent.message)
10250
+ : 'Uncaught fatal error in Web Worker execution';
10251
+ resolve({
10252
+ ok: false,
10253
+ exitCode: 1,
10254
+ durationMs: elapsed,
10255
+ stdout: streamedStdoutChunks.join(''),
10256
+ stderr: streamedStderrChunks.join('') + errMsg + '\n',
10257
+ testResults: streamedTestResults.slice(),
10258
+ testSummary: buildTestSummary(),
10259
+ fsSnapshot: [],
10260
+ httpTrace: [],
10261
+ error: { message: errMsg }
10262
+ });
9843
10263
  };
9844
10264
 
9845
10265
  worker.postMessage({
9846
10266
  requestId,
9847
10267
  type: 'execute',
9848
10268
  payload: {
9849
- files: options.files,
10269
+ files: mergedFiles,
9850
10270
  entry: options.entry,
9851
10271
  mode: options.mode,
9852
10272
  replCode: options.replCode,
@@ -9862,7 +10282,8 @@ _hostRuntime.executeInWorker = async function executeInWorker(options = {}) {
9862
10282
  printReplResult: options.printReplResult,
9863
10283
  stdin: options.stdin,
9864
10284
  wasmBinary: options.wasmBinary,
9865
- env: options.env
10285
+ env: options.env,
10286
+ cwd: options.cwd
9866
10287
  }
9867
10288
  });
9868
10289
  });