wasm-idle 1.3.0 → 1.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 (89) hide show
  1. package/README.md +183 -147
  2. package/dist/container/clang-runtime.js +32 -8
  3. package/dist/container/runtime-adapter.d.ts +2 -0
  4. package/dist/container/runtime-adapter.js +37 -8
  5. package/dist/playground/assetBridge.js +10 -8
  6. package/dist/playground/assets.d.ts +4 -0
  7. package/dist/playground/assets.js +9 -4
  8. package/dist/playground/c3.js +1 -1
  9. package/dist/playground/compiledLldb.d.ts +2 -0
  10. package/dist/playground/compiledLldb.js +37 -2
  11. package/dist/playground/d.d.ts +1 -0
  12. package/dist/playground/d.js +18 -8
  13. package/dist/playground/index.d.ts +1 -1
  14. package/dist/playground/index.js +7 -0
  15. package/dist/playground/{java-debug-HUZVAK4F.js → java-debug-64JGCLTC.js} +1 -1
  16. package/dist/playground/java-debug-notices.txt +26 -1
  17. package/dist/playground/java.js +3 -2
  18. package/dist/playground/javaDebugBridge.js +42 -7
  19. package/dist/playground/javaDebugSource.js +4 -4
  20. package/dist/playground/javaMain.d.ts +3 -0
  21. package/dist/playground/javaMain.js +2 -0
  22. package/dist/playground/javaRuntimeErrors.d.ts +2 -1
  23. package/dist/playground/javaRuntimeErrors.js +9 -2
  24. package/dist/playground/javaSource.d.ts +1 -1
  25. package/dist/playground/javaSource.js +7 -2
  26. package/dist/playground/lldbSession.d.ts +1 -0
  27. package/dist/playground/lldbSession.js +15 -2
  28. package/dist/playground/objectivec.js +2 -1
  29. package/dist/playground/options.d.ts +1 -1
  30. package/dist/playground/pythonCompileOptions.d.ts +7 -4
  31. package/dist/playground/pythonCompileOptions.js +2 -2
  32. package/dist/playground/scala.d.ts +34 -0
  33. package/dist/playground/scala.js +397 -0
  34. package/dist/playground/scalaAssets.d.ts +16 -0
  35. package/dist/playground/scalaAssets.js +51 -0
  36. package/dist/playground/scalaDiagnostics.d.ts +3 -0
  37. package/dist/playground/scalaDiagnostics.js +29 -0
  38. package/dist/playground/staticWorkerRuntime.d.ts +2 -0
  39. package/dist/playground/staticWorkerRuntime.js +85 -11
  40. package/dist/playground/tinygo.js +21 -8
  41. package/dist/playground/tinygoExecutableGraph.js +1 -1
  42. package/dist/playground/v.d.ts +1 -0
  43. package/dist/playground/v.js +17 -7
  44. package/dist/playground/wasmC3Version.d.ts +8 -8
  45. package/dist/playground/wasmC3Version.js +8 -8
  46. package/dist/playground/wasmDotnetVersion.d.ts +1 -1
  47. package/dist/playground/wasmDotnetVersion.js +1 -1
  48. package/dist/playground/wasmGoVersion.d.ts +1 -1
  49. package/dist/playground/wasmGoVersion.js +1 -1
  50. package/dist/playground/wasmLispVersion.d.ts +5 -0
  51. package/dist/playground/wasmLispVersion.js +5 -0
  52. package/dist/playground/wasmOcamlVersion.d.ts +4 -4
  53. package/dist/playground/wasmOcamlVersion.js +3 -3
  54. package/dist/playground/wasmTinyGoVersion.d.ts +57 -57
  55. package/dist/playground/wasmTinyGoVersion.js +57 -57
  56. package/dist/playground/wasmZigVersion.d.ts +7 -7
  57. package/dist/playground/wasmZigVersion.js +7 -7
  58. package/dist/playground/worker/java.js +18 -4
  59. package/dist/playground/worker/javaDebugEvaluator.js +2 -2
  60. package/dist/playground/worker/javaDebugRuntime.js +8 -1
  61. package/dist/playground/worker/javaStreaming.js +4 -2
  62. package/dist/playground/worker/ocaml.js +11 -10
  63. package/dist/playground/worker/python.js +21 -164
  64. package/dist/playground/worker/pythonCompile.js +5 -0
  65. package/dist/playground/worker/pythonDebug.d.ts +20 -0
  66. package/dist/playground/worker/pythonDebug.js +205 -0
  67. package/dist/playground/worker/scala/UPSTREAM-LICENSE.txt +201 -0
  68. package/dist/playground/worker/scala/UPSTREAM-NOTICE.txt +108 -0
  69. package/dist/playground/worker/scala/asset-bootstrap.d.ts +6 -0
  70. package/dist/playground/worker/scala/asset-bootstrap.js +58 -0
  71. package/dist/playground/worker/scala/asset-receipts.d.ts +7 -0
  72. package/dist/playground/worker/scala/asset-receipts.js +58 -0
  73. package/dist/playground/worker/scala/compiler.worker.d.ts +1 -0
  74. package/dist/playground/worker/scala/compiler.worker.js +204 -0
  75. package/dist/playground/worker/scala/execution.worker.d.ts +1 -0
  76. package/dist/playground/worker/scala/execution.worker.js +89 -0
  77. package/dist/playground/worker/scala/memory-fs.d.ts +29 -0
  78. package/dist/playground/worker/scala/memory-fs.js +333 -0
  79. package/dist/playground/worker/scala/runner.d.ts +1 -0
  80. package/dist/playground/worker/scala/runner.js +36 -0
  81. package/dist/playground/worker/zig.d.ts +2 -1
  82. package/dist/playground/worker/zig.js +212 -86
  83. package/dist/playground/worker/zigDebug.d.ts +39 -0
  84. package/dist/playground/worker/zigDebug.js +156 -0
  85. package/dist/playground/zig.d.ts +27 -4
  86. package/dist/playground/zig.js +266 -23
  87. package/dist/playground/zigDebugValues.d.ts +20 -0
  88. package/dist/playground/zigDebugValues.js +248 -0
  89. package/package.json +17 -10
@@ -1,7 +1,12 @@
1
- import { type CompilerDiagnostic, type SandboxExecutionOptions } from './options';
1
+ import { type CompilerDiagnostic, type DebugCommand, type DebugSessionEvent, type SandboxExecutionOptions } from './options';
2
2
  import { type PlaygroundRuntimeAssets } from './assets';
3
3
  import type { Sandbox, SandboxProgress } from './sandbox';
4
- declare class Zig implements Sandbox {
4
+ import { CompiledLldbSandbox } from './compiledLldb';
5
+ declare class Zig extends CompiledLldbSandbox implements Sandbox {
6
+ protected lldbEntryFunction: string;
7
+ readonly defaultExecutionLimits: Readonly<{
8
+ maxAssetBytes: number;
9
+ }>;
5
10
  output: any;
6
11
  worker?: Worker;
7
12
  buffer: import("./sharedBuffer").WasmIdleSharedBuffer;
@@ -17,6 +22,12 @@ declare class Zig implements Sandbox {
17
22
  waitingForInput: boolean;
18
23
  pendingEof: boolean;
19
24
  private activeOperation;
25
+ private loadedRuntimeAssets;
26
+ private loadedIntegrity?;
27
+ private debugTimeout?;
28
+ private debugDisposal?;
29
+ private zigDebugValues?;
30
+ private zigDebugSession?;
20
31
  private disposed;
21
32
  private disposePromise;
22
33
  private readonly disposeCancellation;
@@ -36,11 +47,23 @@ declare class Zig implements Sandbox {
36
47
  write(input: string): void;
37
48
  eof(): void;
38
49
  private flushPendingInput;
39
- run(code: string, prepare: boolean, _log?: boolean, _prog?: SandboxProgress, args?: string[], options?: SandboxExecutionOptions): Promise<boolean | string>;
50
+ run(code: string, prepare: boolean, log?: boolean, progress?: SandboxProgress, args?: string[], options?: SandboxExecutionOptions): Promise<boolean | string>;
51
+ private runLoaded;
40
52
  private cancelOperation;
53
+ private finishCancellation;
41
54
  kill(): void;
42
- terminate(reason?: unknown): void;
55
+ terminate(reason?: unknown): Promise<void> | undefined;
43
56
  clear(): Promise<void>;
44
57
  dispose(): Promise<void>;
58
+ private retireDebugger;
59
+ protected onLldbEvent(event: DebugSessionEvent): void;
60
+ debugVariables(reference: number, start?: number, count?: number): Promise<import("@wasm-idle/core").DebugVariable[]>;
61
+ debugCommand(command: DebugCommand): Promise<void> | undefined;
62
+ debugScopes(frameId: number): Promise<import("@wasm-idle/core").DebugScope[]>;
63
+ debugWriteMemory(reference: string, offset: number, data: Uint8Array, allowPartial?: boolean): Promise<{
64
+ offset?: number;
65
+ bytesWritten: number;
66
+ } | null>;
67
+ private bindDebugTimeout;
45
68
  }
46
69
  export default Zig;
@@ -1,17 +1,22 @@
1
1
  import { resolveSandboxExecutionArgs } from './options';
2
- import { resolveZigCompilerUrl, resolveZigStdlibUrl } from './assets';
2
+ import { resolveZigCompilerUrl, resolveZigStdlibUrl, resolveRuntimeAssetConfig } from './assets';
3
3
  import { snapshotZigExecutionAssetReceipts } from './zigAssets';
4
4
  import { WASM_ZIG_ASSET_RECEIPTS } from './wasmZigVersion';
5
5
  import { BusyError, CancelledError, DEFAULT_WORKSPACE_LIMITS, DiagnosticLimitError, OutputLimitError, RuntimeConfigurationError, TimeoutError, resolveExecutionLimits, resolveRuntimeAssetCacheOptions, validateExecutionWorkspace } from '@wasm-idle/core';
6
6
  import { flushBufferedEof, flushQueuedStdin, resetBufferedStdin } from './stdinBuffer';
7
- import { createWasmIdleSharedBuffer } from './sharedBuffer';
7
+ import { createWasmIdleSharedBuffer, requireSharedArrayBuffer } from './sharedBuffer';
8
+ import { CompiledLldbSandbox } from './compiledLldb';
9
+ import { ZigDebugValues } from './zigDebugValues';
8
10
  import { WorkerSession } from './workerSession';
9
11
  import { reportWorkerInputReady, reportWorkerProgress } from './workerProgress';
10
12
  const OUTPUT_ENCODER = new TextEncoder();
11
13
  const abortReason = (signal, phase) => signal.reason !== undefined
12
14
  ? signal.reason
13
15
  : new DOMException(phase === 'startup' ? 'Zig runtime startup aborted' : 'Zig execution aborted', 'AbortError');
14
- class Zig {
16
+ class Zig extends CompiledLldbSandbox {
17
+ lldbEntryFunction = 'main.main';
18
+ // The public binding must preserve this runtime's full lib/ archive budget.
19
+ defaultExecutionLimits = Object.freeze({ maxAssetBytes: 256 * 1024 * 1024 });
15
20
  output = null;
16
21
  worker = null;
17
22
  buffer = createWasmIdleSharedBuffer(1024);
@@ -27,6 +32,12 @@ class Zig {
27
32
  waitingForInput = false;
28
33
  pendingEof = false;
29
34
  activeOperation = null;
35
+ loadedRuntimeAssets = '';
36
+ loadedIntegrity;
37
+ debugTimeout;
38
+ debugDisposal;
39
+ zigDebugValues;
40
+ zigDebugSession;
30
41
  disposed = false;
31
42
  disposePromise = null;
32
43
  disposeCancellation = new CancelledError('Zig sandbox disposed', {
@@ -184,10 +195,11 @@ class Zig {
184
195
  if (!this.isOperationActive(operation))
185
196
  return;
186
197
  let timeout;
187
- operation.cleanups.push(() => {
198
+ const cancel = () => {
188
199
  if (timeout !== undefined)
189
200
  clearTimeout(timeout);
190
- });
201
+ };
202
+ operation.cleanups.push(cancel);
191
203
  try {
192
204
  timeout = setTimeout(() => {
193
205
  if (!this.isOperationActive(operation))
@@ -205,6 +217,7 @@ class Zig {
205
217
  catch (error) {
206
218
  this.cancelOperation(operation, error);
207
219
  }
220
+ return cancel;
208
221
  }
209
222
  resetExplicitStdinState() {
210
223
  this.pendingInput = [];
@@ -240,7 +253,10 @@ class Zig {
240
253
  if (!this.isOperationActive(activeOperation) || signal?.aborted) {
241
254
  return Promise.reject(this.releaseBeforeSession(activeOperation, 'Zig runtime startup cancelled'));
242
255
  }
243
- limits = resolveExecutionLimits(options.limits);
256
+ limits = resolveExecutionLimits({
257
+ ...this.defaultExecutionLimits,
258
+ ...options.limits
259
+ });
244
260
  if (!this.isOperationActive(activeOperation) || signal?.aborted) {
245
261
  return Promise.reject(this.releaseBeforeSession(activeOperation, 'Zig runtime startup cancelled'));
246
262
  }
@@ -256,6 +272,7 @@ class Zig {
256
272
  const resolveLoad = () => {
257
273
  if (!this.releaseOperation(activeOperation))
258
274
  return;
275
+ this.loadedRuntimeAssets = runtimeAssets;
259
276
  resolve();
260
277
  this.cleanupOperation(activeOperation);
261
278
  };
@@ -266,6 +283,8 @@ class Zig {
266
283
  this.cleanupOperation(activeOperation);
267
284
  };
268
285
  try {
286
+ if (this.debugDisposal)
287
+ await this.debugDisposal;
269
288
  if (!this.isOperationActive(activeOperation))
270
289
  return;
271
290
  this.pendingInput = [];
@@ -322,6 +341,7 @@ class Zig {
322
341
  this.compilerUrl = nextCompilerUrl;
323
342
  this.stdlibUrl = nextStdlibUrl;
324
343
  this.assetKey = nextAssetKey;
344
+ this.loadedIntegrity = nextIntegrity;
325
345
  if (needsWorkerReset && this.worker) {
326
346
  this.workerSession.reset();
327
347
  }
@@ -403,6 +423,10 @@ class Zig {
403
423
  write(input) {
404
424
  if (this.disposed)
405
425
  return;
426
+ if (this.lldbSession) {
427
+ void this.lldbSession.write(input);
428
+ return;
429
+ }
406
430
  this.pendingInput.push(input);
407
431
  this.pendingEof = false;
408
432
  this.flushPendingInput();
@@ -410,6 +434,10 @@ class Zig {
410
434
  eof() {
411
435
  if (this.disposed)
412
436
  return;
437
+ if (this.lldbSession) {
438
+ void this.lldbSession.eof();
439
+ return;
440
+ }
413
441
  this.pendingEof = true;
414
442
  this.flushPendingInput();
415
443
  }
@@ -426,7 +454,24 @@ class Zig {
426
454
  this.waitingForInput = false;
427
455
  }
428
456
  }
429
- run(code, prepare, _log = true, _prog, args = [], options = {}) {
457
+ async run(code, prepare, log = true, progress, args = [], options = {}) {
458
+ // LLDB owns a separate Worker; reload the pinned compiler after its predecessor retires.
459
+ // load() reserves a cancellable operation before waiting for debugger disposal.
460
+ if (!this.worker && this.loadedIntegrity && !this.disposed) {
461
+ this.requireOperationIdle();
462
+ const assets = this.loadedRuntimeAssets;
463
+ await this.load({
464
+ ...(typeof assets === 'string' ? { rootUrl: assets } : assets),
465
+ zig: {
466
+ compilerUrl: this.compilerUrl,
467
+ stdlibUrl: this.stdlibUrl,
468
+ integrity: this.loadedIntegrity
469
+ }
470
+ }, '', log, [], options, progress);
471
+ }
472
+ return this.runLoaded(code, prepare, log, progress, args, options);
473
+ }
474
+ runLoaded(code, prepare, _log = true, _prog, args = [], options = {}) {
430
475
  let activeOperation;
431
476
  try {
432
477
  activeOperation = this.beginOperation('execute');
@@ -446,6 +491,8 @@ class Zig {
446
491
  let targetTriple;
447
492
  let workspace;
448
493
  let stdin;
494
+ let debugMode;
495
+ let debugClang;
449
496
  try {
450
497
  signal = options.signal;
451
498
  unbindPreSessionAbort = this.bindPreSessionAbort(activeOperation, signal);
@@ -453,11 +500,12 @@ class Zig {
453
500
  return Promise.reject(this.releaseBeforeSession(activeOperation, 'Zig execution cancelled'));
454
501
  }
455
502
  ({ compileArgs, programArgs } = resolveSandboxExecutionArgs('ZIG', args, options));
456
- const debugMode = options.debugMode ?? (options.debug ? 'trace' : 'none');
457
- if (debugMode !== 'none') {
458
- throw new RuntimeConfigurationError('Zig source debugging is unavailable: the current Wasm compiler does not emit DWARF.');
503
+ const requestedDebugMode = options.debugMode ?? (options.debug ? 'lldb' : 'none');
504
+ if (requestedDebugMode !== 'none' && requestedDebugMode !== 'lldb') {
505
+ throw new RuntimeConfigurationError('Zig debugging requires debugMode: lldb.');
459
506
  }
460
- limits = resolveExecutionLimits(options.limits);
507
+ debugMode = requestedDebugMode;
508
+ limits = resolveExecutionLimits({ ...this.defaultExecutionLimits, ...options.limits });
461
509
  const workspaceFiles = options.workspaceFiles ?? [];
462
510
  const activePath = options.activePath ?? 'main.zig';
463
511
  const workspaceLimits = options.workspaceLimits;
@@ -466,7 +514,27 @@ class Zig {
466
514
  maxFileBytes: Math.min(workspaceLimits?.maxFileBytes ?? DEFAULT_WORKSPACE_LIMITS.maxFileBytes, limits.maxWorkspaceBytes),
467
515
  maxTotalBytes: Math.min(workspaceLimits?.maxTotalBytes ?? DEFAULT_WORKSPACE_LIMITS.maxTotalBytes, limits.maxWorkspaceBytes)
468
516
  });
469
- targetTriple = options.zigTargetTriple || 'wasm64-wasi';
517
+ targetTriple = options.zigTargetTriple || 'wasm32-wasi';
518
+ if (debugMode === 'lldb') {
519
+ requireSharedArrayBuffer('Zig debugging');
520
+ if (targetTriple !== 'wasm32-wasi') {
521
+ throw new RuntimeConfigurationError('Zig LLDB debugging requires wasm32-wasi.');
522
+ }
523
+ debugClang = resolveRuntimeAssetConfig('clang', this.loadedRuntimeAssets, typeof window !== 'undefined' ? window.location.href : '');
524
+ if (!this.isOperationActive(activeOperation)) {
525
+ return Promise.reject(this.releaseBeforeSession(activeOperation, 'Zig execution cancelled'));
526
+ }
527
+ if (debugClang.useAssetBridge && debugClang.loader) {
528
+ throw new RuntimeConfigurationError('Zig debugging requires URL-based Clang assets.');
529
+ }
530
+ this.configureLldb(this.loadedRuntimeAssets, options);
531
+ const entryPath = workspace.activePath || 'main.zig';
532
+ this.prepareLldb(options, entryPath);
533
+ this.lldbEntryFunction = `${entryPath
534
+ .split('/')
535
+ .pop()
536
+ .replace(/\.zig$/, '')}.main`;
537
+ }
470
538
  stdin = options.stdin;
471
539
  if (!this.isOperationActive(activeOperation) || signal?.aborted) {
472
540
  return Promise.reject(this.releaseBeforeSession(activeOperation, 'Zig execution cancelled'));
@@ -490,19 +558,20 @@ class Zig {
490
558
  let diagnosticCount = 0;
491
559
  let outputBytes = 0;
492
560
  const operation = this.workerSession.beginRun(worker, reject);
493
- const timeoutMs = Math.min(2_147_483_647, limits.compileTimeoutMs + limits.runTimeoutMs);
494
- this.bindOperationTimeout(activeOperation, timeoutMs);
561
+ const timeoutMs = Math.min(2_147_483_647, limits.compileTimeoutMs + (debugMode === 'lldb' ? 0 : limits.runTimeoutMs));
562
+ const cancelCompileTimeout = this.bindOperationTimeout(activeOperation, timeoutMs);
495
563
  this.bindAbortSignal(activeOperation, signal);
496
564
  if (!this.isOperationActive(activeOperation))
497
565
  return;
498
566
  let handler;
567
+ let handedOff = false;
499
568
  const ownsRun = () => this.isOperationActive(activeOperation) &&
500
- this.worker === worker &&
501
- worker.onmessage === handler &&
569
+ (handedOff || (this.worker === worker && worker.onmessage === handler)) &&
502
570
  _uid === this.uid;
503
571
  const claimRun = () => {
504
572
  if (!ownsRun())
505
573
  return false;
574
+ this.lldbPending = false;
506
575
  this.finishExplicitStdin(activeOperation);
507
576
  this.elapse = Date.now() - this.begin;
508
577
  this.exit = true;
@@ -532,10 +601,47 @@ class Zig {
532
601
  reject(error);
533
602
  };
534
603
  handler = (event) => {
535
- if (!ownsRun())
604
+ if (handedOff || !ownsRun())
536
605
  return;
537
606
  try {
538
- const { output, results, error, buffer, diagnostic, progress } = event.data;
607
+ const { output, results, error, buffer, diagnostic, progress, lldbArtifact } = event.data;
608
+ if (lldbArtifact) {
609
+ if (debugMode !== 'lldb' || prepare || handedOff) {
610
+ throw new RuntimeConfigurationError('Unexpected Zig debugger artifact.');
611
+ }
612
+ cancelCompileTimeout?.();
613
+ handedOff = true;
614
+ this.bindDebugTimeout(activeOperation, limits.runTimeoutMs);
615
+ const completion = this.startLldb(lldbArtifact, options, programArgs, this.pendingInput, this.pendingEof, (text) => {
616
+ if (!ownsRun())
617
+ return;
618
+ const actual = outputBytes + OUTPUT_ENCODER.encode(text).byteLength;
619
+ if (actual > limits.maxOutputBytes) {
620
+ failRun(new OutputLimitError(`Zig output exceeded ${limits.maxOutputBytes} bytes`, {
621
+ actual,
622
+ limit: limits.maxOutputBytes,
623
+ phase: 'execute',
624
+ runtimeId: 'ZIG'
625
+ }), true);
626
+ return;
627
+ }
628
+ outputBytes = actual;
629
+ try {
630
+ this.output?.(text);
631
+ }
632
+ catch (error) {
633
+ failRun(error, true);
634
+ }
635
+ });
636
+ this.pendingEof = false;
637
+ if (this.workerSession.release(worker))
638
+ delete this.worker;
639
+ void completion.then((result) => {
640
+ if (claimRun())
641
+ resolve(result);
642
+ }, (error) => failRun(error));
643
+ return;
644
+ }
539
645
  if (buffer && !hasExplicitStdin) {
540
646
  this.waitingForInput = true;
541
647
  if (!prepare) {
@@ -610,6 +716,14 @@ class Zig {
610
716
  activePath: workspace.activePath,
611
717
  workspaceFiles: workspace.workspaceFiles,
612
718
  targetTriple,
719
+ debugMode,
720
+ ...(debugClang
721
+ ? {
722
+ debugClangPath: debugClang.baseUrl,
723
+ debugClangIntegrity: debugClang.integrity,
724
+ maxWasmMemoryBytes: limits.maxWasmMemoryBytes
725
+ }
726
+ : {}),
613
727
  log: _log
614
728
  });
615
729
  }
@@ -630,13 +744,20 @@ class Zig {
630
744
  return;
631
745
  operation.cancelled = true;
632
746
  operation.cancellationReason = reason;
633
- this.activeOperation = null;
747
+ // Fence reentrant stop listeners before notifying them, retaining ownership
748
+ // until the debugger retirement barrier has been registered.
749
+ this.retireDebugger();
750
+ this.finishCancellation(operation);
751
+ }
752
+ finishCancellation(operation) {
753
+ if (!this.releaseOperation(operation))
754
+ return;
634
755
  this.uid += 1;
635
756
  this.finishExplicitStdin(operation);
636
757
  this.waitingForInput = false;
637
758
  this.pendingEof = false;
638
759
  this.exit = true;
639
- this.workerSession.terminate(reason);
760
+ this.workerSession.terminate(operation.cancellationReason);
640
761
  this.cleanupOperation(operation);
641
762
  }
642
763
  kill() {
@@ -648,13 +769,15 @@ class Zig {
648
769
  const activeOperation = this.activeOperation;
649
770
  if (activeOperation) {
650
771
  this.cancelOperation(activeOperation, reason);
651
- return;
772
+ return this.debugDisposal;
652
773
  }
774
+ this.retireDebugger();
653
775
  this.waitingForInput = false;
654
776
  this.pendingEof = false;
655
777
  this.uid += 1;
656
778
  this.workerSession.terminate(reason);
657
779
  this.exit = true;
780
+ return this.debugDisposal;
658
781
  }
659
782
  async clear() {
660
783
  if (this.disposed)
@@ -674,17 +797,27 @@ class Zig {
674
797
  if (this.disposePromise)
675
798
  return this.disposePromise;
676
799
  this.disposed = true;
677
- this.disposePromise = Promise.resolve();
800
+ this.disposePromise = Promise.resolve().then(async () => {
801
+ await this.debugDisposal;
802
+ });
678
803
  const activeOperation = this.activeOperation;
804
+ if (activeOperation && !activeOperation.cancelled) {
805
+ activeOperation.cancelled = true;
806
+ activeOperation.cancellationReason = this.disposeCancellation;
807
+ }
808
+ this.retireDebugger();
679
809
  delete this.worker;
680
810
  this.compilerUrl = '';
681
811
  this.stdlibUrl = '';
682
812
  this.assetKey = '';
813
+ this.loadedRuntimeAssets = '';
814
+ this.loadedIntegrity = undefined;
815
+ this.ondebug = undefined;
683
816
  this.output = null;
684
817
  this.oncompilerdiagnostic = undefined;
685
818
  this.resetExplicitStdinState();
686
819
  if (activeOperation) {
687
- this.cancelOperation(activeOperation, this.disposeCancellation);
820
+ this.finishCancellation(activeOperation);
688
821
  }
689
822
  else {
690
823
  this.uid += 1;
@@ -693,5 +826,115 @@ class Zig {
693
826
  }
694
827
  return this.disposePromise;
695
828
  }
829
+ retireDebugger() {
830
+ this.zigDebugValues?.invalidate();
831
+ try {
832
+ const disconnecting = this.stopLldb();
833
+ if (!disconnecting)
834
+ return;
835
+ // Shutdown may outlive cancellation; keep the exact caller reason and wait
836
+ // for target Workers to retire before disposal or a replacement execution.
837
+ const cleanup = Promise.resolve(disconnecting).catch(() => undefined);
838
+ this.debugDisposal = Promise.all([this.debugDisposal, cleanup]).then(() => undefined);
839
+ }
840
+ catch {
841
+ // Cleanup must not replace the caller's cancellation or disposal outcome.
842
+ }
843
+ }
844
+ onLldbEvent(event) {
845
+ if (event.type === 'pause' || event.type === 'resume' || event.type === 'stop')
846
+ this.zigDebugValues?.invalidate();
847
+ if (event.type === 'stop') {
848
+ this.zigDebugValues = undefined;
849
+ this.zigDebugSession = undefined;
850
+ try {
851
+ super.onLldbEvent(event);
852
+ }
853
+ catch {
854
+ // Stop listeners cannot replace target completion or cancellation.
855
+ }
856
+ return;
857
+ }
858
+ const operation = this.activeOperation;
859
+ if (!operation || !this.isOperationActive(operation))
860
+ return;
861
+ try {
862
+ if (event.type === 'pause')
863
+ this.debugTimeout?.pause();
864
+ else if (event.type === 'resume')
865
+ this.debugTimeout?.resume();
866
+ super.onLldbEvent(event);
867
+ }
868
+ catch (error) {
869
+ this.cancelOperation(operation, error);
870
+ }
871
+ }
872
+ debugVariables(reference, start, count) {
873
+ if (!this.lldbSession)
874
+ return Promise.resolve([]);
875
+ if (this.zigDebugSession !== this.lldbSession) {
876
+ this.zigDebugValues?.invalidate();
877
+ this.zigDebugSession = this.lldbSession;
878
+ this.zigDebugValues = new ZigDebugValues(this.lldbSession);
879
+ }
880
+ return this.zigDebugValues.variables(reference, start, count);
881
+ }
882
+ debugCommand(command) {
883
+ this.zigDebugValues?.invalidate();
884
+ return super.debugCommand(command);
885
+ }
886
+ debugScopes(frameId) {
887
+ this.zigDebugValues?.invalidate();
888
+ return super.debugScopes(frameId);
889
+ }
890
+ async debugWriteMemory(reference, offset, data, allowPartial = false) {
891
+ const session = this.lldbSession;
892
+ this.zigDebugValues?.invalidateValues();
893
+ try {
894
+ return await super.debugWriteMemory(reference, offset, data, allowPartial);
895
+ }
896
+ finally {
897
+ if (this.lldbSession === session)
898
+ this.zigDebugValues?.invalidateValues();
899
+ }
900
+ }
901
+ bindDebugTimeout(operation, timeoutMs) {
902
+ let remaining = timeoutMs;
903
+ let started = Date.now();
904
+ let timer;
905
+ let paused = true;
906
+ const clear = () => {
907
+ if (timer !== undefined)
908
+ clearTimeout(timer);
909
+ timer = undefined;
910
+ };
911
+ const control = {
912
+ pause: () => {
913
+ if (paused)
914
+ return;
915
+ remaining = Math.max(0, remaining - Math.max(0, Date.now() - started));
916
+ paused = true;
917
+ clear();
918
+ },
919
+ resume: () => {
920
+ if (!paused || !this.isOperationActive(operation))
921
+ return;
922
+ paused = false;
923
+ started = Date.now();
924
+ timer = setTimeout(() => this.cancelOperation(operation, new TimeoutError(`Zig execution timed out after ${timeoutMs} ms`, {
925
+ phase: 'execute',
926
+ runtimeId: 'ZIG',
927
+ timeoutMs
928
+ })), Math.min(2_147_483_647, remaining));
929
+ }
930
+ };
931
+ this.debugTimeout = control;
932
+ operation.cleanups.push(() => {
933
+ clear();
934
+ if (this.debugTimeout === control)
935
+ this.debugTimeout = undefined;
936
+ });
937
+ control.resume();
938
+ }
696
939
  }
697
940
  export default Zig;
@@ -0,0 +1,20 @@
1
+ import type { DebugVariable } from '@wasm-idle/core';
2
+ import type { LldbSandboxSession } from './lldbSession';
3
+ type Backend = Pick<LldbSandboxSession, 'variables' | 'readMemory'>;
4
+ /** Pinned Zig DWARF layouts only. No expressions or user code are evaluated. */
5
+ export declare class ZigDebugValues {
6
+ private readonly backend;
7
+ private epoch;
8
+ private readonly children;
9
+ private readonly layouts;
10
+ constructor(backend: Backend);
11
+ invalidate(): void;
12
+ /** A memory write preserves DAP handles in this stop, but not their values. */
13
+ invalidateValues(): void;
14
+ variables(reference: number, start?: number, count?: number): Promise<DebugVariable[]>;
15
+ private describe;
16
+ private format;
17
+ private readBytes;
18
+ private expand;
19
+ }
20
+ export {};