wasm-idle 1.1.0 → 1.2.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 (197) hide show
  1. package/README.md +267 -112
  2. package/dist/container/bash-profile.d.ts +80 -0
  3. package/dist/container/bash-profile.js +328 -0
  4. package/dist/container/binding.d.ts +39 -0
  5. package/dist/container/binding.js +331 -0
  6. package/dist/container/clang-runtime.d.ts +42 -0
  7. package/dist/container/clang-runtime.js +561 -0
  8. package/dist/container/client.d.ts +14 -0
  9. package/dist/container/client.js +185 -0
  10. package/dist/container/explorer.d.ts +31 -0
  11. package/dist/container/explorer.js +112 -0
  12. package/dist/container/index.d.ts +11 -0
  13. package/dist/container/index.js +11 -0
  14. package/dist/container/owner-worker.d.ts +19 -0
  15. package/dist/container/owner-worker.js +464 -0
  16. package/dist/container/protocol.d.ts +84 -0
  17. package/dist/container/protocol.js +28 -0
  18. package/dist/container/runtime-adapter.d.ts +75 -0
  19. package/dist/container/runtime-adapter.js +537 -0
  20. package/dist/container/shell-control.d.ts +49 -0
  21. package/dist/container/shell-control.js +360 -0
  22. package/dist/container/workspace.d.ts +12 -0
  23. package/dist/container/workspace.js +29 -0
  24. package/dist/index.d.ts +1 -1
  25. package/dist/playground/assetBridge.js +111 -33
  26. package/dist/playground/assets.d.ts +10 -2
  27. package/dist/playground/c3.js +22 -0
  28. package/dist/playground/c3Memory.d.ts +19 -0
  29. package/dist/playground/c3Memory.js +117 -0
  30. package/dist/playground/cachedClang.js +143 -34
  31. package/dist/playground/clang.d.ts +5 -1
  32. package/dist/playground/clang.js +61 -5
  33. package/dist/playground/clangAssetIntegrity.js +6 -6
  34. package/dist/playground/clangWorkerProtocol.d.ts +12 -1
  35. package/dist/playground/cobol.d.ts +3 -0
  36. package/dist/playground/cobol.js +10 -1
  37. package/dist/playground/commonlispAssets.d.ts +2 -2
  38. package/dist/playground/compiledArtifactCache.d.ts +3 -1
  39. package/dist/playground/compiledArtifactCache.js +31 -5
  40. package/dist/playground/compiledLldb.d.ts +41 -0
  41. package/dist/playground/compiledLldb.js +167 -0
  42. package/dist/playground/d.d.ts +10 -2
  43. package/dist/playground/d.js +161 -14
  44. package/dist/playground/debugDeadline.d.ts +12 -0
  45. package/dist/playground/debugDeadline.js +34 -0
  46. package/dist/playground/debugMailbox.d.ts +12 -0
  47. package/dist/playground/debugMailbox.js +77 -0
  48. package/dist/playground/dotnet.js +6 -8
  49. package/dist/playground/fortran.d.ts +3 -0
  50. package/dist/playground/fortran.js +10 -1
  51. package/dist/playground/go.js +23 -7
  52. package/dist/playground/goDebugInstrumentation.js +207 -97
  53. package/dist/playground/java-debug-FMHDKUN6.js +124 -0
  54. package/dist/playground/java-debug-notices.txt +492 -0
  55. package/dist/playground/java.d.ts +17 -1
  56. package/dist/playground/java.js +162 -5
  57. package/dist/playground/javaDebug.d.ts +62 -0
  58. package/dist/playground/javaDebug.js +305 -0
  59. package/dist/playground/javaDebugBridge.d.ts +6 -0
  60. package/dist/playground/javaDebugBridge.js +250 -0
  61. package/dist/playground/javaDebugSource.d.ts +9 -0
  62. package/dist/playground/javaDebugSource.js +4 -0
  63. package/dist/playground/javaRuntimeErrors.d.ts +9 -0
  64. package/dist/playground/javaRuntimeErrors.js +93 -0
  65. package/dist/playground/lean4Assets.d.ts +1 -25
  66. package/dist/playground/lean4Assets.js +2 -123
  67. package/dist/playground/lfortran.js +10 -0
  68. package/dist/playground/lfortranAssets.d.ts +2 -2
  69. package/dist/playground/lldbSession.d.ts +23 -2
  70. package/dist/playground/lldbSession.js +278 -58
  71. package/dist/playground/lldbSourcePath.d.ts +2 -0
  72. package/dist/playground/lldbSourcePath.js +9 -0
  73. package/dist/playground/lua.d.ts +20 -1
  74. package/dist/playground/lua.js +190 -8
  75. package/dist/playground/luaDebug.d.ts +1 -0
  76. package/dist/playground/luaDebug.js +1 -0
  77. package/dist/playground/nim.d.ts +1 -0
  78. package/dist/playground/nim.js +30 -0
  79. package/dist/playground/objectivec.d.ts +10 -6
  80. package/dist/playground/objectivec.js +85 -10
  81. package/dist/playground/options.d.ts +12 -4
  82. package/dist/playground/python.d.ts +8 -1
  83. package/dist/playground/python.js +89 -6
  84. package/dist/playground/ruby.d.ts +10 -1
  85. package/dist/playground/ruby.js +66 -1
  86. package/dist/playground/rubyDebug.d.ts +21 -0
  87. package/dist/playground/rubyDebug.js +128 -0
  88. package/dist/playground/runtimeAssetCache.d.ts +1 -32
  89. package/dist/playground/runtimeAssetCache.js +1 -193
  90. package/dist/playground/runtimeSession.d.ts +2 -2
  91. package/dist/playground/runtimeSession.js +11 -11
  92. package/dist/playground/rust.d.ts +10 -0
  93. package/dist/playground/rust.js +230 -51
  94. package/dist/playground/sandbox.d.ts +8 -1
  95. package/dist/playground/staticStdinRing.d.ts +2 -1
  96. package/dist/playground/staticStdinRing.js +21 -10
  97. package/dist/playground/staticWorkerRuntime.d.ts +15 -1
  98. package/dist/playground/staticWorkerRuntime.js +127 -19
  99. package/dist/playground/stdinBuffer.d.ts +1 -1
  100. package/dist/playground/stdinBuffer.js +19 -2
  101. package/dist/playground/tinygo.d.ts +3 -0
  102. package/dist/playground/tinygo.js +88 -6
  103. package/dist/playground/typescript.js +8 -0
  104. package/dist/playground/v.d.ts +6 -2
  105. package/dist/playground/v.js +76 -13
  106. package/dist/playground/wasmAwkVersion.d.ts +13 -13
  107. package/dist/playground/wasmAwkVersion.js +4 -4
  108. package/dist/playground/wasmBqnVersion.d.ts +2 -2
  109. package/dist/playground/wasmBqnVersion.js +2 -2
  110. package/dist/playground/wasmC3Version.d.ts +2 -2
  111. package/dist/playground/wasmC3Version.js +2 -2
  112. package/dist/playground/wasmClojureScriptVersion.d.ts +2 -2
  113. package/dist/playground/wasmClojureScriptVersion.js +2 -2
  114. package/dist/playground/wasmCommonLispVersion.d.ts +2 -2
  115. package/dist/playground/wasmCommonLispVersion.js +2 -2
  116. package/dist/playground/wasmDIntegrity.d.ts +5 -5
  117. package/dist/playground/wasmDIntegrity.js +5 -5
  118. package/dist/playground/wasmDVersion.d.ts +16 -1
  119. package/dist/playground/wasmDVersion.js +16 -1
  120. package/dist/playground/wasmDebugVersion.d.ts +1 -1
  121. package/dist/playground/wasmDebugVersion.js +1 -1
  122. package/dist/playground/wasmForthVersion.d.ts +2 -2
  123. package/dist/playground/wasmForthVersion.js +2 -2
  124. package/dist/playground/wasmGleamVersion.d.ts +2 -2
  125. package/dist/playground/wasmGleamVersion.js +2 -2
  126. package/dist/playground/wasmGrainVersion.d.ts +2 -2
  127. package/dist/playground/wasmGrainVersion.js +2 -2
  128. package/dist/playground/wasmJVersion.d.ts +2 -2
  129. package/dist/playground/wasmJVersion.js +2 -2
  130. package/dist/playground/wasmJanetVersion.js +2 -2
  131. package/dist/playground/wasmJuliaVersion.js +2 -2
  132. package/dist/playground/wasmLean4Version.d.ts +1 -110
  133. package/dist/playground/wasmLean4Version.js +2 -111
  134. package/dist/playground/wasmLfortranVersion.d.ts +2 -2
  135. package/dist/playground/wasmLfortranVersion.js +2 -2
  136. package/dist/playground/wasmLuaVersion.d.ts +1 -1
  137. package/dist/playground/wasmLuaVersion.js +1 -1
  138. package/dist/playground/wasmNimVersion.d.ts +9 -9
  139. package/dist/playground/wasmNimVersion.js +6 -6
  140. package/dist/playground/wasmOcamlVersion.d.ts +2 -2
  141. package/dist/playground/wasmOcamlVersion.js +1 -1
  142. package/dist/playground/wasmPascalVersion.js +2 -2
  143. package/dist/playground/wasmPerlVersion.js +2 -2
  144. package/dist/playground/wasmPrologVersion.d.ts +2 -2
  145. package/dist/playground/wasmPrologVersion.js +2 -2
  146. package/dist/playground/wasmReScriptVersion.d.ts +2 -2
  147. package/dist/playground/wasmReScriptVersion.js +2 -2
  148. package/dist/playground/wasmRustVersion.d.ts +26 -38
  149. package/dist/playground/wasmRustVersion.js +25 -40
  150. package/dist/playground/wasmTclVersion.d.ts +4 -4
  151. package/dist/playground/wasmTclVersion.js +2 -2
  152. package/dist/playground/wasmTinyGoVersion.d.ts +14 -14
  153. package/dist/playground/wasmTinyGoVersion.js +14 -14
  154. package/dist/playground/wasmTypeScriptVersion.d.ts +5 -5
  155. package/dist/playground/wasmTypeScriptVersion.js +5 -5
  156. package/dist/playground/worker/cachedClangCompile.js +52 -4
  157. package/dist/playground/worker/cachedClangExecute.js +6 -5
  158. package/dist/playground/worker/clang.js +33 -11
  159. package/dist/playground/worker/cobol.js +3 -3
  160. package/dist/playground/worker/d.js +63 -7
  161. package/dist/playground/worker/fortran.js +3 -3
  162. package/dist/playground/worker/go.js +16 -5
  163. package/dist/playground/worker/haskell.js +10 -7
  164. package/dist/playground/worker/java.js +263 -45
  165. package/dist/playground/worker/javaDebugEvaluator.d.ts +16 -0
  166. package/dist/playground/worker/javaDebugEvaluator.js +44 -0
  167. package/dist/playground/worker/javaDebugRuntime.d.ts +24 -0
  168. package/dist/playground/worker/javaDebugRuntime.js +315 -0
  169. package/dist/playground/worker/javaOutput.d.ts +11 -0
  170. package/dist/playground/worker/javaOutput.js +54 -0
  171. package/dist/playground/worker/lua.js +15 -3
  172. package/dist/playground/worker/php.js +15 -9
  173. package/dist/playground/worker/python.js +102 -30
  174. package/dist/playground/worker/pythonExecution.js +17 -1
  175. package/dist/playground/worker/pythonWorkspaceFiles.d.ts +6 -0
  176. package/dist/playground/worker/pythonWorkspaceFiles.js +26 -0
  177. package/dist/playground/worker/pythonWorkspaceImports.d.ts +4 -0
  178. package/dist/playground/worker/pythonWorkspaceImports.js +129 -0
  179. package/dist/playground/worker/r.js +13 -6
  180. package/dist/playground/worker/ruby.js +13 -0
  181. package/dist/playground/worker/rubyDebugPreview.d.ts +2 -0
  182. package/dist/playground/worker/rubyDebugPreview.js +80 -0
  183. package/dist/playground/worker/rubyTracepoint.d.ts +16 -0
  184. package/dist/playground/worker/rubyTracepoint.js +162 -0
  185. package/dist/playground/worker/rust.js +38 -3
  186. package/dist/playground/worker/sqlite.js +4 -3
  187. package/dist/playground/worker/tinygo.js +11 -3
  188. package/dist/playground/worker/typescript.js +2 -3
  189. package/dist/playground/worker/v.js +32 -7
  190. package/dist/playground/worker/wat.js +2 -3
  191. package/dist/playground/worker/zig.js +20 -6
  192. package/dist/playground/workerSession.d.ts +1 -28
  193. package/dist/playground/workerSession.js +1 -164
  194. package/dist/playground/zig.js +4 -0
  195. package/package.json +66 -15
  196. package/dist/playground/worker/python.runtime.cases.d.ts +0 -1
  197. package/dist/playground/worker/python.runtime.cases.js +0 -374
@@ -1,4 +1,4 @@
1
- import { AssetNotFoundError, AssetTooLargeError, BusyError, CancelledError, DEFAULT_WORKSPACE_LIMITS, DiagnosticLimitError, OutputLimitError, ProtocolError, RuntimeConfigurationError, RuntimeExecutionError, RuntimeProgressController, RuntimeWorkerLifetimeController, TimeoutError, WorkerStartupError, isWasmIdleError, resolveExecutionLimits, resolveRuntimeAssetCacheOptions, readPersistentRuntimeAsset, writePersistentRuntimeAsset, validateExecutionWorkspace, verifyRuntimeAssetIntegrity } from '@wasm-idle/core';
1
+ import { AssetNotFoundError, AssetTooLargeError, BusyError, CancelledError, DEFAULT_WORKSPACE_LIMITS, DiagnosticLimitError, OutputLimitError, ProtocolError, RuntimeConfigurationError, RuntimeExecutionError, RuntimeProgressController, RuntimeWorkerLifetimeController, TimeoutError, WorkerStartupError, isWasmIdleError, resolveExecutionLimits, resolveRuntimeAssetCacheOptions, readPersistentRuntimeAsset, writePersistentRuntimeAsset, validateExecutionWorkspace, verifyRuntimeAssetIntegrity, createRuntimeWasmModuleService } from '@wasm-idle/core';
2
2
  import { resolveSandboxExecutionArgs } from './options';
3
3
  import { StaticStdinRingHost } from './staticStdinRing';
4
4
  import { deserializeStaticRuntimePreflightError, isStaticRuntimePreflightSerializedError, inspectStaticRuntimePreflightBytes } from './staticRuntimePreflightProtocol';
@@ -54,6 +54,8 @@ export class StaticWorkerRuntimeSandbox {
54
54
  workerRuntimePreflightMaxAssetBytes = new WeakMap();
55
55
  workersWithCachedRuntimePreflight = new WeakSet();
56
56
  workerStartMaxAssetBytes = null;
57
+ runtimeAssetCache;
58
+ workerCompilerModuleServices = new WeakMap();
57
59
  constructor(config) {
58
60
  this.config = config;
59
61
  const workerLifetime = config.workerLifetime ?? { mode: 'per-run' };
@@ -78,6 +80,77 @@ export class StaticWorkerRuntimeSandbox {
78
80
  disposeWorker: (worker) => this.retireManagedWorker(worker)
79
81
  });
80
82
  }
83
+ /** The application owns this cache; worker or sandbox disposal never disposes it. */
84
+ setRuntimeAssetCache(cache) {
85
+ if (cache === this.runtimeAssetCache)
86
+ return;
87
+ if (this.disposed ||
88
+ this.worker ||
89
+ this.workerStartPromise ||
90
+ this.activeRun ||
91
+ this.startingRunId) {
92
+ throw new RuntimeConfigurationError(`Cannot replace an active ${this.config.displayName} compiler cache`, { runtimeId: this.config.languageId, phase: 'startup' });
93
+ }
94
+ this.runtimeAssetCache = cache;
95
+ }
96
+ createCompilerModulePorts(worker, activeRun, limits) {
97
+ const cache = this.runtimeAssetCache;
98
+ const factory = this.config.compilerModules;
99
+ if (!cache || !factory)
100
+ return undefined;
101
+ const urls = this.resolvedRuntimeUrls;
102
+ if (!urls)
103
+ throw new RuntimeConfigurationError('Compiler module profile is unavailable');
104
+ const identity = JSON.stringify([
105
+ 'static-runtime-compiler-v1',
106
+ this.config.languageId,
107
+ urls.baseUrl,
108
+ urls.workerUrl,
109
+ urls.manifestFingerprint,
110
+ urls.preflightKey,
111
+ urls.workerReceipt
112
+ ]);
113
+ const descriptors = Object.entries(factory(urls, limits));
114
+ if (this.disposed ||
115
+ this.activeRun !== activeRun ||
116
+ this.worker !== worker ||
117
+ descriptors.length === 0 ||
118
+ descriptors.length > 64) {
119
+ throw new RuntimeConfigurationError('Compiler module profile is invalid or expired');
120
+ }
121
+ const ports = {};
122
+ const services = [];
123
+ this.workerCompilerModuleServices.set(worker, services);
124
+ activeRun.compilerModuleWorker = worker;
125
+ for (const [name, descriptor] of descriptors) {
126
+ if (!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/u.test(name)) {
127
+ throw new RuntimeConfigurationError('Compiler module name is invalid');
128
+ }
129
+ const service = createRuntimeWasmModuleService({
130
+ cache,
131
+ receipt: descriptor.receipt,
132
+ identity: JSON.stringify([identity, name]),
133
+ compileKey: descriptor.compileKey,
134
+ maxAssetBytes: limits.maxAssetBytes,
135
+ compile: descriptor.compile
136
+ });
137
+ services.push(service);
138
+ ports[name] = service.port;
139
+ }
140
+ return Object.freeze(ports);
141
+ }
142
+ closeCompilerModuleServices(worker) {
143
+ const services = this.workerCompilerModuleServices.get(worker);
144
+ this.workerCompilerModuleServices.delete(worker);
145
+ for (const service of services ?? []) {
146
+ try {
147
+ service.close();
148
+ }
149
+ catch {
150
+ // All subscriptions must be retired even if another endpoint cleanup fails.
151
+ }
152
+ }
153
+ }
81
154
  usesOwnedRuntimePreflight() {
82
155
  return (this.config.runtimePreflightDelivery === 'transfer-owned' ||
83
156
  this.config.runtimePreflightDelivery === 'transfer-owned-worker-cache');
@@ -94,7 +167,15 @@ export class StaticWorkerRuntimeSandbox {
94
167
  ? (this.workerStartMaxAssetBytes ?? undefined)
95
168
  : undefined;
96
169
  if (currentLimit !== undefined && maxAssetBytes < currentLimit) {
97
- this.disposeWorker(new CancelledError(`${this.config.displayName} worker reset for a lower runtime asset limit`, { phase: 'asset', runtimeId: this.config.languageId }));
170
+ const reason = new CancelledError(`${this.config.displayName} worker reset for a lower runtime asset limit`, { phase: 'asset', runtimeId: this.config.languageId });
171
+ // A run cannot settle once its worker is detached, so the reset ends it like an abort.
172
+ if (this.activeRun) {
173
+ this.rejectStdinWaiters(reason);
174
+ this.rejectRun(this.activeRun.id, reason);
175
+ }
176
+ else {
177
+ this.disposeWorker(reason);
178
+ }
98
179
  }
99
180
  }
100
181
  getDisposeReason() {
@@ -148,7 +229,7 @@ export class StaticWorkerRuntimeSandbox {
148
229
  this.validateWorkspace(code, options, controls.limits);
149
230
  this.assertOperationNotDisposed();
150
231
  const progressSink = this.selectProgress(progress);
151
- const currentUrl = typeof window !== 'undefined' ? window.location.href : '';
232
+ const currentUrl = globalThis.location?.href ?? '';
152
233
  const urls = this.config.resolveRuntimeAssets(runtimeAssets, currentUrl);
153
234
  this.assertOperationNotDisposed();
154
235
  this.persistentCache = persistentCache;
@@ -222,6 +303,9 @@ export class StaticWorkerRuntimeSandbox {
222
303
  return;
223
304
  const activeRun = this.activeRun;
224
305
  if (activeRun?.stdinRing) {
306
+ // The terminal keeps accepting input after EOF; late input must not fail the run.
307
+ if (activeRun.stdinRingClosed)
308
+ return;
225
309
  try {
226
310
  activeRun.stdinRing.enqueue(input);
227
311
  }
@@ -237,6 +321,7 @@ export class StaticWorkerRuntimeSandbox {
237
321
  return;
238
322
  const activeRun = this.activeRun;
239
323
  if (activeRun?.stdinRing) {
324
+ activeRun.stdinRingClosed = true;
240
325
  try {
241
326
  activeRun.stdinRing.close();
242
327
  }
@@ -283,18 +368,19 @@ export class StaticWorkerRuntimeSandbox {
283
368
  }
284
369
  if (!this.pendingEof) {
285
370
  this.reportRunReady(activeRun, 'waiting-input', 'stdin-request', `${this.config.displayName} runtime ready for input`);
286
- if (this.activeRun !== activeRun) {
287
- throw new CancelledError(`${this.config.displayName} run terminated`, {
288
- phase: 'execute',
289
- runtimeId: this.config.languageId
290
- });
291
- }
292
371
  }
293
- while (!this.pendingEof) {
372
+ // A waiter woken after its run settled must not consume the next run's input.
373
+ while (this.activeRun === activeRun && !this.pendingEof) {
294
374
  await new Promise((resolve, reject) => {
295
375
  this.stdinWaiters.push({ resolve, reject });
296
376
  });
297
377
  }
378
+ if (this.activeRun !== activeRun) {
379
+ throw new CancelledError(`${this.config.displayName} run terminated`, {
380
+ phase: 'execute',
381
+ runtimeId: this.config.languageId
382
+ });
383
+ }
298
384
  const stdin = this.pendingInput.join('');
299
385
  this.clearPendingStdin();
300
386
  return { stdin, stdinEof: true };
@@ -387,10 +473,7 @@ export class StaticWorkerRuntimeSandbox {
387
473
  }
388
474
  let workerRequestUrl;
389
475
  try {
390
- workerRequestUrl =
391
- typeof window === 'undefined'
392
- ? new URL(this.workerUrl)
393
- : new URL(this.workerUrl, window.location.href);
476
+ workerRequestUrl = new URL(this.workerUrl, globalThis.location?.href);
394
477
  }
395
478
  catch {
396
479
  throw new RuntimeConfigurationError(`${this.config.displayName} worker script URL is invalid`, { runtimeId: this.config.languageId });
@@ -1423,14 +1506,18 @@ self.postMessage = (message, transferOrOptions) => {
1423
1506
  return;
1424
1507
  this.elapse = Date.now() - this.begin;
1425
1508
  this.exit = true;
1509
+ this.rejectStdinWaiters(new CancelledError(`${this.config.displayName} run ended`, {
1510
+ phase: 'execute',
1511
+ runtimeId: this.config.languageId
1512
+ }));
1426
1513
  this.clearPendingStdin();
1427
1514
  this.releaseWorkerLease(true);
1428
1515
  this.cleanupRun(activeRun);
1429
1516
  activeRun.resolve(result);
1430
1517
  }
1431
1518
  rejectRun(id, reason) {
1432
- const activeRun = this.claimRun(id);
1433
- if (!activeRun)
1519
+ const activeRun = this.activeRun;
1520
+ if (!activeRun || activeRun.id !== id)
1434
1521
  return;
1435
1522
  try {
1436
1523
  this.reportRunSettled(activeRun, reason instanceof TimeoutError
@@ -1442,8 +1529,15 @@ self.postMessage = (message, transferOrOptions) => {
1442
1529
  catch {
1443
1530
  // Progress observers must not prevent a failed run from releasing its worker.
1444
1531
  }
1532
+ // Keep the run reserved through its observer, as on success. If that observer
1533
+ // terminates and replaces the run, only the replacement may clean up its state.
1534
+ if (this.activeRun !== activeRun)
1535
+ return;
1536
+ if (this.claimRun(id) !== activeRun)
1537
+ return;
1445
1538
  this.elapse = Date.now() - this.begin;
1446
1539
  this.exit = true;
1540
+ this.rejectStdinWaiters(reason);
1447
1541
  this.clearPendingStdin();
1448
1542
  this.startupReject?.(reason);
1449
1543
  this.disposeWorker();
@@ -1459,6 +1553,10 @@ self.postMessage = (message, transferOrOptions) => {
1459
1553
  return activeRun;
1460
1554
  }
1461
1555
  cleanupRun(activeRun) {
1556
+ if (activeRun.compilerModuleWorker) {
1557
+ this.closeCompilerModuleServices(activeRun.compilerModuleWorker);
1558
+ activeRun.compilerModuleWorker = undefined;
1559
+ }
1462
1560
  try {
1463
1561
  activeRun.cleanup();
1464
1562
  }
@@ -1517,6 +1615,7 @@ self.postMessage = (message, transferOrOptions) => {
1517
1615
  state.transferables = null;
1518
1616
  }
1519
1617
  detachAndTerminateWorker(worker) {
1618
+ this.closeCompilerModuleServices(worker);
1520
1619
  this.retireRuntimePreflight(this.workerRuntimePreflight.get(worker));
1521
1620
  this.workerRuntimePreflight.delete(worker);
1522
1621
  this.workerRuntimePreflightMaxAssetBytes.delete(worker);
@@ -1681,6 +1780,7 @@ self.postMessage = (message, transferOrOptions) => {
1681
1780
  this.exit = false;
1682
1781
  return new Promise((resolve, reject) => {
1683
1782
  let stdinRing;
1783
+ let stdinRingClosed = false;
1684
1784
  if (this.stdinMode === 'streaming') {
1685
1785
  try {
1686
1786
  const maxBufferedBytes = Math.min(128 * 1024, controls.limits.maxWorkspaceBytes);
@@ -1698,6 +1798,7 @@ self.postMessage = (message, transferOrOptions) => {
1698
1798
  stdinRing.enqueue(initialInput);
1699
1799
  if (initialEof)
1700
1800
  stdinRing.close();
1801
+ stdinRingClosed = initialEof;
1701
1802
  }
1702
1803
  catch (error) {
1703
1804
  try {
@@ -1722,7 +1823,6 @@ self.postMessage = (message, transferOrOptions) => {
1722
1823
  phase: 'execute',
1723
1824
  runtimeId: this.config.languageId
1724
1825
  });
1725
- this.rejectStdinWaiters(error);
1726
1826
  this.rejectRun(id, error);
1727
1827
  };
1728
1828
  const cleanup = () => {
@@ -1741,7 +1841,7 @@ self.postMessage = (message, transferOrOptions) => {
1741
1841
  resolve,
1742
1842
  reject,
1743
1843
  settledReported: false,
1744
- ...(stdinRing ? { stdinRing } : {})
1844
+ ...(stdinRing ? { stdinRing, stdinRingClosed } : {})
1745
1845
  };
1746
1846
  this.activeReject = reject;
1747
1847
  this.startingRunId = null;
@@ -1830,6 +1930,7 @@ self.postMessage = (message, transferOrOptions) => {
1830
1930
  ownedDeliveryStateByTicket.has(storedRuntimePreflight)) {
1831
1931
  throw new RuntimeConfigurationError(`${this.config.displayName} structured-clone runtime preflight cannot dispatch an owned delivery ticket.`, { phase: 'protocol', runtimeId: this.config.languageId });
1832
1932
  }
1933
+ const runtimeWasmModulePorts = this.createCompilerModulePorts(worker, activeRun, controls.limits);
1833
1934
  const message = {
1834
1935
  run: true,
1835
1936
  runId: id,
@@ -1837,6 +1938,7 @@ self.postMessage = (message, transferOrOptions) => {
1837
1938
  manifestUrl: this.manifestUrl,
1838
1939
  manifestFingerprint: this.manifestFingerprint,
1839
1940
  ...(runtimePreflight === undefined ? {} : { runtimePreflight }),
1941
+ ...(runtimeWasmModulePorts ? { runtimeWasmModulePorts } : {}),
1840
1942
  maxAssetBytes: controls.limits.maxAssetBytes,
1841
1943
  ...(this.config.includeExecutionLimits
1842
1944
  ? { limits: controls.limits }
@@ -1852,7 +1954,13 @@ self.postMessage = (message, transferOrOptions) => {
1852
1954
  workspaceFiles: workspace.workspaceFiles,
1853
1955
  log: _log
1854
1956
  };
1855
- if (transferList)
1957
+ if (runtimeWasmModulePorts) {
1958
+ worker.postMessage(message, [
1959
+ ...(transferList ?? []),
1960
+ ...Object.values(runtimeWasmModulePorts)
1961
+ ]);
1962
+ }
1963
+ else if (transferList)
1856
1964
  worker.postMessage(message, transferList);
1857
1965
  else
1858
1966
  worker.postMessage(message);
@@ -2,7 +2,7 @@ type StdinBuffer = ArrayBufferLike | Int32Array;
2
2
  export declare const flushQueuedStdin: (queue: string[], buffer: StdinBuffer) => boolean;
3
3
  export declare const readBufferedStdin: (buffer: StdinBuffer) => string | null;
4
4
  export declare const bufferedSequence: (buffer: StdinBuffer) => number;
5
- export declare const waitForBufferedSequenceChange: (buffer: StdinBuffer, sequence: number, timeoutMs?: number) => Promise<string | null>;
5
+ export declare const waitForBufferedSequenceChange: (buffer: StdinBuffer, sequence: number, timeoutMs?: number, signal?: AbortSignal) => Promise<string | null>;
6
6
  export declare const flushBufferedEof: (buffer: StdinBuffer) => void;
7
7
  export declare const waitForBufferedStdin: (buffer: Int32Array | null | undefined, requestInput: () => void) => string | null;
8
8
  export declare const resetBufferedStdin: (buffer: StdinBuffer) => void;
@@ -47,18 +47,35 @@ export const readBufferedStdin = (buffer) => {
47
47
  return decoder.decode(payload.slice(0, length));
48
48
  };
49
49
  export const bufferedSequence = (buffer) => Atomics.load(controlViewOf(buffer), SEQUENCE_INDEX);
50
- export const waitForBufferedSequenceChange = (buffer, sequence, timeoutMs = 5000) => new Promise((resolve, reject) => {
50
+ export const waitForBufferedSequenceChange = (buffer, sequence, timeoutMs = 5000, signal) => new Promise((resolve, reject) => {
51
51
  const startedAt = Date.now();
52
+ let timer;
53
+ const cleanup = () => {
54
+ if (timer !== undefined)
55
+ clearTimeout(timer);
56
+ signal?.removeEventListener('abort', abort);
57
+ };
58
+ const abort = () => {
59
+ cleanup();
60
+ reject(signal?.reason ?? new Error('Buffered wait aborted'));
61
+ };
62
+ if (signal?.aborted) {
63
+ abort();
64
+ return;
65
+ }
66
+ signal?.addEventListener('abort', abort, { once: true });
52
67
  const poll = () => {
53
68
  if (bufferedSequence(buffer) !== sequence) {
69
+ cleanup();
54
70
  resolve(readBufferedStdin(buffer));
55
71
  return;
56
72
  }
57
73
  if (Date.now() - startedAt >= timeoutMs) {
74
+ cleanup();
58
75
  reject(new Error('Timed out waiting for buffered value'));
59
76
  return;
60
77
  }
61
- setTimeout(poll, 10);
78
+ timer = setTimeout(poll, 10);
62
79
  };
63
80
  poll();
64
81
  });
@@ -2,6 +2,7 @@ import { type PlaygroundRuntimeAssets, type RuntimeAssetIntegrityEntry, type Tin
2
2
  import { type LoadedTinyGoExecutableGraph } from './tinygoExecutableGraph';
3
3
  import type { CompilerDiagnostic, SandboxExecutionOptions, TinyGoTarget } from './options';
4
4
  import type { Sandbox, SandboxProgress } from './sandbox';
5
+ import { type RuntimeAssetCache } from '@wasm-idle/core';
5
6
  type TinyGoRuntimeHooks = {
6
7
  boot(): Promise<void>;
7
8
  plan(): Promise<unknown>;
@@ -72,10 +73,12 @@ declare class TinyGo implements Sandbox {
72
73
  private runtimeProgressOwner;
73
74
  private activeOperation;
74
75
  private disposed;
76
+ private runtimeAssetCache;
75
77
  private disposePromise;
76
78
  private readonly disposeCancellation;
77
79
  private readonly workerSession;
78
80
  private disposedConfigurationError;
81
+ setRuntimeAssetCache(cache: RuntimeAssetCache): void;
79
82
  load(runtimeAssets?: string | PlaygroundRuntimeAssets, _code?: string, _log?: boolean, _args?: string[], options?: SandboxExecutionOptions, progress?: SandboxProgress): Promise<void>;
80
83
  private beginOperation;
81
84
  private completeOperation;
@@ -5,7 +5,7 @@ import { flushBufferedEof, flushQueuedStdin, resetBufferedStdin } from './stdinB
5
5
  import { createWasmIdleSharedBuffer } from './sharedBuffer';
6
6
  import { WorkerSession } from './workerSession';
7
7
  import { reportWorkerProgress } from './workerProgress';
8
- import { BusyError, CancelledError, DEFAULT_EXECUTION_LIMITS, DEFAULT_WORKSPACE_LIMITS, DiagnosticLimitError, OutputLimitError, RuntimeConfigurationError, TimeoutError, WorkspaceValidationError, resolveExecutionLimits, resolveRuntimeAssetCacheOptions, fetchPinnedRuntimeAsset, validateExecutionWorkspace } from '@wasm-idle/core';
8
+ import { BusyError, CancelledError, DEFAULT_EXECUTION_LIMITS, DEFAULT_WORKSPACE_LIMITS, DiagnosticLimitError, OutputLimitError, RuntimeConfigurationError, TimeoutError, WorkspaceValidationError, resolveExecutionLimits, resolveRuntimeAssetCacheOptions, createRuntimeWasmModuleService, fetchPinnedRuntimeAsset, validateExecutionWorkspace } from '@wasm-idle/core';
9
9
  const ACTIVITY_PREFIX_PATTERN = /^\[\d{2}:\d{2}:\d{2}\]\s?/gm;
10
10
  const MAX_TIMER_DELAY_MS = 2_147_483_647;
11
11
  const TINYGO_BROWSER_COMPILER_DEFAULT_MAX_WASM_MEMORY_BYTES = 2 * 1024 * 1024 * 1024;
@@ -96,6 +96,7 @@ class TinyGo {
96
96
  runtimeProgressOwner = null;
97
97
  activeOperation = null;
98
98
  disposed = false;
99
+ runtimeAssetCache;
99
100
  disposePromise = null;
100
101
  disposeCancellation = new CancelledError('TinyGo sandbox disposed', {
101
102
  phase: 'dispose',
@@ -117,6 +118,20 @@ class TinyGo {
117
118
  runtimeId: 'TINYGO'
118
119
  });
119
120
  }
121
+ setRuntimeAssetCache(cache) {
122
+ if (cache === this.runtimeAssetCache)
123
+ return;
124
+ if (this.disposed)
125
+ throw this.disposedConfigurationError();
126
+ if (this.worker ||
127
+ this.runtime ||
128
+ this.runtimePromise ||
129
+ this.loadPromise ||
130
+ this.activeOperation) {
131
+ throw new RuntimeConfigurationError('Cannot replace TinyGo runtime asset cache after startup has begun', { runtimeId: 'TINYGO', phase: 'startup' });
132
+ }
133
+ this.runtimeAssetCache = cache;
134
+ }
120
135
  load(runtimeAssets = '', _code = '', _log = true, _args = [], options = {}, progress) {
121
136
  return this.executeOperation('startup', options, async (operation) => {
122
137
  const persistentCache = resolveRuntimeAssetCacheOptions(typeof runtimeAssets === 'object' ? runtimeAssets.persistentCache : undefined, options.persistentCache);
@@ -793,6 +808,16 @@ class TinyGo {
793
808
  let assetsPromise = null;
794
809
  const loadUpstreamAssets = runtimeModule.loadTinyGoUpstreamToolchainAssets;
795
810
  const compileUpstream = runtimeModule.compileTinyGoInDisposableWorker;
811
+ const moduleCache = this.runtimeAssetCache;
812
+ const moduleIdentity = moduleCache
813
+ ? JSON.stringify([
814
+ moduleUrl,
815
+ runtimeProfile.profileId,
816
+ runtimeProfile.manifestFingerprint,
817
+ this.executableGraphFingerprint,
818
+ moduleCache.identity(assetLoader)
819
+ ])
820
+ : '';
796
821
  const appendLog = (line) => {
797
822
  activityLog += `[${new Date().toTimeString().slice(0, 8)}] ${line}\n`;
798
823
  commonOptions.onLogAppended({ line });
@@ -844,11 +869,61 @@ class TinyGo {
844
869
  compileFiles['go.mod'] =
845
870
  'module wasm-idle.local/main\n\ngo 1.24.0\n';
846
871
  }
847
- const result = await compileUpstream(assets, { workspaceFiles: compileFiles, package: '.' }, {
848
- signal: controller.signal,
849
- maxWasmMemoryBytes: wasmMemoryLimit,
850
- onPhase: (phase) => appendLog(`upstream TinyGo phase: ${phase}`)
851
- });
872
+ const compileMemoryLimit = wasmMemoryLimit;
873
+ const services = [];
874
+ let result;
875
+ try {
876
+ let modulePorts;
877
+ if (moduleCache) {
878
+ const capMemory = runtimeModule.capTinyGoWasmMemory;
879
+ if (typeof capMemory !== 'function') {
880
+ throw new RuntimeConfigurationError('TinyGo runtime must provide its reviewed memory-cap transformation', { runtimeId: 'TINYGO', phase: 'compile' });
881
+ }
882
+ modulePorts = {};
883
+ for (const [kind, assetPath, label] of [
884
+ [
885
+ 'compiler',
886
+ 'tools/upstream/tinygo-compiler.wasm',
887
+ 'upstream TinyGo compiler'
888
+ ],
889
+ [
890
+ 'packageGraph',
891
+ 'tools/upstream/tinygo-package-graph.wasm',
892
+ 'upstream Go package-graph provider'
893
+ ],
894
+ ['lld', 'tools/upstream/lld.wasm', 'raw WASI LLD']
895
+ ]) {
896
+ const pinned = runtimeProfile.assetReceipts[assetPath];
897
+ const bytes = pinned?.uncompressedBytes ?? pinned?.bytes;
898
+ const sha256 = pinned?.uncompressedSha256 ?? pinned?.sha256;
899
+ if (typeof bytes !== 'number' ||
900
+ typeof sha256 !== 'string') {
901
+ throw new RuntimeConfigurationError(`TinyGo ${kind} module requires a complete pinned logical receipt`, { runtimeId: 'TINYGO', phase: 'asset' });
902
+ }
903
+ const service = createRuntimeWasmModuleService({
904
+ cache: moduleCache,
905
+ receipt: { bytes, sha256 },
906
+ identity: `${moduleIdentity}:${kind}`,
907
+ compileKey: `tinygo-wasi-memory-cap-v1:${compileMemoryLimit}`,
908
+ maxAssetBytes: assetLimit,
909
+ signal: controller.signal,
910
+ compile: (bytes) => WebAssembly.compile(capMemory(bytes, compileMemoryLimit, label))
911
+ });
912
+ services.push(service);
913
+ modulePorts[kind] = service.port;
914
+ }
915
+ }
916
+ result = await compileUpstream(assets, { workspaceFiles: compileFiles, package: '.' }, {
917
+ signal: controller.signal,
918
+ maxWasmMemoryBytes: compileMemoryLimit,
919
+ ...(modulePorts ? { modulePorts } : {}),
920
+ onPhase: (phase) => appendLog(`upstream TinyGo phase: ${phase}`)
921
+ });
922
+ }
923
+ finally {
924
+ for (const service of services)
925
+ service.close();
926
+ }
852
927
  artifact = {
853
928
  path: '/work/program.wasm',
854
929
  bytes: Uint8Array.from(result.wasm),
@@ -1206,6 +1281,13 @@ class TinyGo {
1206
1281
  if (typeof code !== 'string') {
1207
1282
  throw new TypeError('TinyGo source code must be a string');
1208
1283
  }
1284
+ const configuredDebugMode = options.debugMode;
1285
+ this.assertOperation(operation);
1286
+ const debugMode = configuredDebugMode ?? (options.debug ? 'trace' : 'none');
1287
+ this.assertOperation(operation);
1288
+ if (debugMode !== 'none') {
1289
+ throw new RuntimeConfigurationError('TinyGo debugging is unavailable: the current compiler protocol does not provide a debug runtime closure.');
1290
+ }
1209
1291
  const configuredTarget = options.tinygoTarget;
1210
1292
  this.assertOperation(operation);
1211
1293
  const target = configuredTarget ?? 'wasip1';
@@ -563,6 +563,14 @@ class TypeScriptSandbox {
563
563
  this.requireOperationActive(activeOperation);
564
564
  unbindPreSessionAbort = this.bindPreSessionAbort(activeOperation, signal);
565
565
  this.requireOperationActive(activeOperation);
566
+ const debugMode = options.debugMode;
567
+ this.requireOperationActive(activeOperation);
568
+ const debug = options.debug;
569
+ this.requireOperationActive(activeOperation);
570
+ const resolvedDebugMode = debugMode ?? (debug ? 'trace' : 'none');
571
+ if (resolvedDebugMode !== 'none') {
572
+ throw new RuntimeConfigurationError(`${this.languageLabel} source debugging is unavailable in this browser runtime.`, { runtimeId: this.language, phase: 'execute' });
573
+ }
566
574
  const configuredProgramArgs = options.programArgs;
567
575
  this.requireOperationActive(activeOperation);
568
576
  const sourceProgramArgs = configuredProgramArgs ?? args;
@@ -1,10 +1,12 @@
1
1
  import { WorkerAssetBridge } from './assetBridge';
2
+ import { CompiledLldbSandbox } from './compiledLldb';
3
+ import type { RuntimeAssetCache } from './runtimeAssetCache';
2
4
  import { type PlaygroundRuntimeAssets } from './assets';
3
5
  import type { SandboxExecutionOptions } from './options';
4
6
  import type { Sandbox, SandboxProgress } from './sandbox';
5
- declare class VLang implements Sandbox {
7
+ declare class VLang extends CompiledLldbSandbox implements Sandbox {
8
+ protected lldbEntryFunction: string;
6
9
  language: string;
7
- output?: (data: string) => void;
8
10
  worker?: Worker;
9
11
  buffer: import("./sharedBuffer").WasmIdleSharedBuffer;
10
12
  pendingInput: string[];
@@ -18,10 +20,12 @@ declare class VLang implements Sandbox {
18
20
  assetBridge: WorkerAssetBridge | null;
19
21
  activeVBaseUrl: string;
20
22
  private activeOperation;
23
+ private runtimeAssetCache?;
21
24
  private disposed;
22
25
  private disposePromise;
23
26
  private readonly disposeCancellation;
24
27
  private readonly workerSession;
28
+ setRuntimeAssetCache(cache: RuntimeAssetCache): void;
25
29
  private beginOperation;
26
30
  private isOperationActive;
27
31
  private releaseOperation;