wasm-idle 1.1.2 → 1.3.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 (136) hide show
  1. package/README.md +211 -91
  2. package/dist/container/bash-profile.d.ts +80 -0
  3. package/dist/container/bash-profile.js +328 -0
  4. package/dist/{playground/container → container}/binding.d.ts +21 -8
  5. package/dist/{playground/container → container}/binding.js +109 -25
  6. package/dist/{playground/container → container}/clang-runtime.d.ts +11 -7
  7. package/dist/container/clang-runtime.js +561 -0
  8. package/dist/container/client.d.ts +14 -0
  9. package/dist/{playground/container → container}/client.js +2 -6
  10. package/dist/{playground/container → container}/explorer.d.ts +1 -1
  11. package/dist/container/index.d.ts +11 -0
  12. package/dist/container/index.js +11 -0
  13. package/dist/container/owner-worker.d.ts +19 -0
  14. package/dist/container/owner-worker.js +464 -0
  15. package/dist/{playground/container → container}/protocol.d.ts +12 -1
  16. package/dist/{playground/container → container}/runtime-adapter.d.ts +13 -11
  17. package/dist/{playground/container → container}/runtime-adapter.js +104 -41
  18. package/dist/{playground/container → container}/shell-control.d.ts +2 -2
  19. package/dist/{playground/container → container}/shell-control.js +93 -36
  20. package/dist/{playground/container → container}/workspace.d.ts +5 -1
  21. package/dist/index.d.ts +2 -1
  22. package/dist/index.js +1 -0
  23. package/dist/playground/assetBridge.js +5 -2
  24. package/dist/playground/assets.d.ts +8 -0
  25. package/dist/playground/clang.d.ts +5 -1
  26. package/dist/playground/clang.js +61 -5
  27. package/dist/playground/compiledLldb.d.ts +41 -0
  28. package/dist/playground/compiledLldb.js +167 -0
  29. package/dist/playground/d.d.ts +4 -1
  30. package/dist/playground/d.js +78 -9
  31. package/dist/playground/debugDeadline.d.ts +12 -0
  32. package/dist/playground/debugDeadline.js +34 -0
  33. package/dist/playground/debugMailbox.d.ts +12 -0
  34. package/dist/playground/debugMailbox.js +77 -0
  35. package/dist/playground/go.js +9 -4
  36. package/dist/playground/goDebugInstrumentation.js +24 -44
  37. package/dist/playground/java-debug-HUZVAK4F.js +124 -0
  38. package/dist/playground/java-debug-notices.txt +492 -0
  39. package/dist/playground/java.d.ts +17 -1
  40. package/dist/playground/java.js +159 -3
  41. package/dist/playground/javaDebug.d.ts +62 -0
  42. package/dist/playground/javaDebug.js +305 -0
  43. package/dist/playground/javaDebugBridge.d.ts +6 -0
  44. package/dist/playground/javaDebugBridge.js +250 -0
  45. package/dist/playground/javaDebugSource.d.ts +9 -0
  46. package/dist/playground/javaDebugSource.js +4 -0
  47. package/dist/playground/javaRuntimeErrors.js +34 -1
  48. package/dist/playground/lean4Assets.d.ts +1 -25
  49. package/dist/playground/lean4Assets.js +2 -123
  50. package/dist/playground/lfortranAssets.d.ts +2 -2
  51. package/dist/playground/lldbSession.d.ts +24 -2
  52. package/dist/playground/lldbSession.js +322 -59
  53. package/dist/playground/lldbSourcePath.d.ts +2 -0
  54. package/dist/playground/lldbSourcePath.js +9 -0
  55. package/dist/playground/lua.d.ts +20 -1
  56. package/dist/playground/lua.js +190 -8
  57. package/dist/playground/luaDebug.d.ts +1 -0
  58. package/dist/playground/luaDebug.js +1 -0
  59. package/dist/playground/nim.d.ts +1 -0
  60. package/dist/playground/nim.js +8 -0
  61. package/dist/playground/objectivec.d.ts +7 -6
  62. package/dist/playground/objectivec.js +75 -9
  63. package/dist/playground/options.d.ts +10 -4
  64. package/dist/playground/python.d.ts +11 -1
  65. package/dist/playground/python.js +203 -8
  66. package/dist/playground/pythonCompileOptions.d.ts +49 -0
  67. package/dist/playground/pythonCompileOptions.js +40 -0
  68. package/dist/playground/ruby.d.ts +10 -1
  69. package/dist/playground/ruby.js +66 -1
  70. package/dist/playground/rubyDebug.d.ts +21 -0
  71. package/dist/playground/rubyDebug.js +128 -0
  72. package/dist/playground/rust.d.ts +5 -1
  73. package/dist/playground/rust.js +128 -46
  74. package/dist/playground/sandbox.d.ts +8 -1
  75. package/dist/playground/staticRuntimeModuleVersion.d.ts +1 -1
  76. package/dist/playground/staticRuntimeModuleVersion.js +1 -1
  77. package/dist/playground/staticWorkerRuntime.js +8 -2
  78. package/dist/playground/stdinBuffer.d.ts +1 -1
  79. package/dist/playground/stdinBuffer.js +19 -2
  80. package/dist/playground/tinygo.js +7 -0
  81. package/dist/playground/typescript.js +8 -0
  82. package/dist/playground/v.d.ts +3 -2
  83. package/dist/playground/v.js +66 -12
  84. package/dist/playground/wasmC3Version.d.ts +2 -2
  85. package/dist/playground/wasmC3Version.js +2 -2
  86. package/dist/playground/wasmDebugVersion.d.ts +1 -1
  87. package/dist/playground/wasmDebugVersion.js +1 -1
  88. package/dist/playground/wasmLean4Version.d.ts +1 -110
  89. package/dist/playground/wasmLean4Version.js +2 -111
  90. package/dist/playground/wasmLfortranVersion.d.ts +2 -2
  91. package/dist/playground/wasmLfortranVersion.js +2 -2
  92. package/dist/playground/wasmLuaVersion.d.ts +1 -1
  93. package/dist/playground/wasmLuaVersion.js +1 -1
  94. package/dist/playground/wasmPrologVersion.d.ts +17 -17
  95. package/dist/playground/wasmPrologVersion.js +16 -16
  96. package/dist/playground/wasmRustVersion.d.ts +26 -38
  97. package/dist/playground/wasmRustVersion.js +25 -40
  98. package/dist/playground/wasmTypeScriptVersion.d.ts +3 -3
  99. package/dist/playground/wasmTypeScriptVersion.js +3 -3
  100. package/dist/playground/worker/clang.js +1 -1
  101. package/dist/playground/worker/cobol.js +1 -1
  102. package/dist/playground/worker/d.js +51 -2
  103. package/dist/playground/worker/fortran.js +1 -1
  104. package/dist/playground/worker/java.js +188 -35
  105. package/dist/playground/worker/javaDebugEvaluator.d.ts +16 -0
  106. package/dist/playground/worker/javaDebugEvaluator.js +44 -0
  107. package/dist/playground/worker/javaDebugRuntime.d.ts +24 -0
  108. package/dist/playground/worker/javaDebugRuntime.js +315 -0
  109. package/dist/playground/worker/javaOutput.d.ts +11 -0
  110. package/dist/playground/worker/javaOutput.js +54 -0
  111. package/dist/playground/worker/lua.js +13 -0
  112. package/dist/playground/worker/python.js +81 -23
  113. package/dist/playground/worker/pythonCompile.d.ts +4 -0
  114. package/dist/playground/worker/pythonCompile.js +122 -0
  115. package/dist/playground/worker/ruby.js +13 -0
  116. package/dist/playground/worker/rubyDebugPreview.d.ts +2 -0
  117. package/dist/playground/worker/rubyDebugPreview.js +80 -0
  118. package/dist/playground/worker/rubyTracepoint.d.ts +16 -0
  119. package/dist/playground/worker/rubyTracepoint.js +162 -0
  120. package/dist/playground/worker/rust.js +4 -1
  121. package/dist/playground/worker/v.js +30 -5
  122. package/dist/playground/zig.js +4 -0
  123. package/dist/pythonCompiler.d.ts +8 -0
  124. package/dist/pythonCompiler.js +52 -0
  125. package/package.json +76 -28
  126. package/dist/playground/container/ContainerExplorer.svelte +0 -307
  127. package/dist/playground/container/ContainerExplorer.svelte.d.ts +0 -14
  128. package/dist/playground/container/clang-runtime.js +0 -343
  129. package/dist/playground/container/client.d.ts +0 -15
  130. package/dist/playground/container/owner.worker.d.ts +0 -1
  131. package/dist/playground/container/owner.worker.js +0 -390
  132. package/dist/playground/container/release.d.ts +0 -31
  133. package/dist/playground/container/release.js +0 -612
  134. /package/dist/{playground/container → container}/explorer.js +0 -0
  135. /package/dist/{playground/container → container}/protocol.js +0 -0
  136. /package/dist/{playground/container → container}/workspace.js +0 -0
@@ -4,9 +4,11 @@ import { resolveRuntimeAssetConfig } from './assets';
4
4
  import { AssetTooLargeError, BusyError, CancelledError, DEFAULT_WORKSPACE_LIMITS, DiagnosticLimitError, OutputLimitError, RuntimeConfigurationError, TEAVM_RUNTIME_ASSET_NAMES, TEAVM_RUNTIME_ASSET_RECEIPTS, TimeoutError, resolveExecutionLimits, validateExecutionWorkspace } from '@wasm-idle/core';
5
5
  import { resolveJavaSourceIdentity } from './javaSource';
6
6
  import { flushBufferedEof, flushQueuedStdin, resetBufferedStdin } from './stdinBuffer';
7
- import { createWasmIdleSharedBuffer } from './sharedBuffer';
7
+ import { createWasmIdleSharedBuffer, requireSharedArrayBuffer } from './sharedBuffer';
8
8
  import { WorkerSession } from './workerSession';
9
9
  import { reportWorkerProgress } from './workerProgress';
10
+ import { JavaDebugSession } from './javaDebug';
11
+ import { DebugDeadline } from './debugDeadline';
10
12
  const OUTPUT_ENCODER = new TextEncoder();
11
13
  const abortReason = (signal, phase) => signal.reason !== undefined
12
14
  ? signal.reason
@@ -22,6 +24,13 @@ class Java {
22
24
  exit = true;
23
25
  baseUrl = '';
24
26
  oncompilerdiagnostic;
27
+ ondebug;
28
+ debugSession;
29
+ evaluationAssets;
30
+ evaluationLimits;
31
+ evaluationSandbox;
32
+ cacheEvaluationArtifacts = false;
33
+ evaluationQueue = Promise.resolve();
25
34
  waitingForInput = false;
26
35
  pendingEof = false;
27
36
  assetBridge = null;
@@ -392,6 +401,16 @@ class Java {
392
401
  }
393
402
  }
394
403
  this.baseUrl = assetConfig.baseUrl;
404
+ this.evaluationAssets = {
405
+ java: {
406
+ baseUrl: assetConfig.baseUrl,
407
+ loader: assetConfig.loader,
408
+ integrity: assetConfig.integrity,
409
+ allowedBaseUrls: assetConfig.allowedBaseUrls,
410
+ persistentCache: assetConfig.persistentCache
411
+ }
412
+ };
413
+ this.evaluationLimits = limits;
395
414
  const needsWorkerReset = !this.worker ||
396
415
  !this.assetBridge ||
397
416
  !this.assetBridge.matches(assetConfig, limits.maxAssetBytes);
@@ -539,6 +558,7 @@ class Java {
539
558
  let limits;
540
559
  let workspace;
541
560
  let stdin;
561
+ let debugMode;
542
562
  try {
543
563
  signal = options.signal;
544
564
  unbindPreSessionAbort = this.bindPreSessionAbort(activeOperation, signal);
@@ -566,6 +586,13 @@ class Java {
566
586
  maxTotalBytes: Math.min(workspaceLimits.maxTotalBytes ?? DEFAULT_WORKSPACE_LIMITS.maxTotalBytes, limits.maxWorkspaceBytes)
567
587
  });
568
588
  stdin = options.stdin;
589
+ const requestedDebugMode = options.debugMode ?? (options.debug ? 'trace' : 'none');
590
+ if (requestedDebugMode !== 'none' && requestedDebugMode !== 'trace') {
591
+ throw new Error(`Unsupported Java debugger backend: ${requestedDebugMode}`);
592
+ }
593
+ debugMode = requestedDebugMode;
594
+ if (debugMode === 'trace' && !prepare)
595
+ requireSharedArrayBuffer('Java debugging');
569
596
  const persistentCache = options.persistentCache;
570
597
  if (!this.isOperationActive(activeOperation) || signal?.aborted) {
571
598
  return Promise.reject(this.releaseBeforeSession(activeOperation, 'Java execution cancelled'));
@@ -585,13 +612,42 @@ class Java {
585
612
  this.resetExplicitStdinState();
586
613
  }
587
614
  this.exit = false;
615
+ let runDebugSession;
616
+ let debugDeadline;
588
617
  const running = new Promise((resolve, reject) => {
589
618
  const _uid = ++this.uid;
590
619
  let diagnosticCount = 0;
591
620
  let outputBytes = 0;
592
621
  const operation = this.workerSession.beginRun(worker, reject);
593
622
  const timeoutMs = Math.min(2_147_483_647, limits.compileTimeoutMs + limits.runTimeoutMs);
594
- this.bindOperationTimeout(activeOperation, timeoutMs);
623
+ if (debugMode === 'trace' && !prepare) {
624
+ debugDeadline = new DebugDeadline(timeoutMs, () => this.cancelOperation(activeOperation, new TimeoutError(`Java execution timed out after ${timeoutMs} ms`, {
625
+ phase: 'execute',
626
+ runtimeId: 'JAVA',
627
+ timeoutMs
628
+ })));
629
+ activeOperation.cleanups.push(() => debugDeadline?.dispose());
630
+ const session = new JavaDebugSession(options.debugPath || `/workspace/${workspace.activePath}`, (event) => {
631
+ if (event.type === 'pause')
632
+ debugDeadline?.pause();
633
+ else if (event.type === 'resume')
634
+ debugDeadline?.resume();
635
+ if (this.debugSession === session &&
636
+ (this.isOperationActive(activeOperation) || event.type === 'stop'))
637
+ this.ondebug?.(event);
638
+ }, {
639
+ evaluate: (expression, context, signal) => this.evaluateSnapshot(expression, context, signal, activeOperation)
640
+ });
641
+ this.debugSession = runDebugSession = session;
642
+ activeOperation.cleanups.push(() => {
643
+ session.dispose();
644
+ this.disposeEvaluationSandbox();
645
+ if (this.debugSession === session)
646
+ this.debugSession = undefined;
647
+ });
648
+ }
649
+ else
650
+ this.bindOperationTimeout(activeOperation, timeoutMs);
595
651
  this.bindAbortSignal(activeOperation, signal);
596
652
  if (!this.isOperationActive(activeOperation))
597
653
  return;
@@ -631,7 +687,11 @@ class Java {
631
687
  return;
632
688
  if (!ownsRun())
633
689
  return;
634
- const { output, results, error, buffer, diagnostic, progress } = event.data;
690
+ const { output, results, error, buffer, diagnostic, progress, javaDebug } = event.data;
691
+ if (javaDebug && runDebugSession) {
692
+ runDebugSession.handle(javaDebug);
693
+ return;
694
+ }
635
695
  if (buffer && !hasExplicitStdin) {
636
696
  if (!prepare) {
637
697
  _prog?.report?.({
@@ -703,6 +763,17 @@ class Java {
703
763
  worker.postMessage({
704
764
  code,
705
765
  prepare,
766
+ debugMode,
767
+ cacheEvaluationArtifacts: this.cacheEvaluationArtifacts,
768
+ javaDebug: runDebugSession
769
+ ? {
770
+ buffer: runDebugSession.mailbox.buffer,
771
+ sourcePath: options.debugPath || `/workspace/${workspace.activePath}`,
772
+ breakpoints: options.breakpoints || [],
773
+ sourceBreakpoints: options.sourceBreakpoints,
774
+ pauseOnEntry: options.pauseOnEntry !== false
775
+ }
776
+ : undefined,
706
777
  buffer: this.buffer,
707
778
  args: programArgs,
708
779
  stdin: stdin ?? '',
@@ -717,6 +788,9 @@ class Java {
717
788
  }
718
789
  });
719
790
  return running.finally(() => {
791
+ runDebugSession?.dispose();
792
+ if (this.debugSession === runDebugSession)
793
+ this.debugSession = undefined;
720
794
  if (this.releaseOperation(activeOperation)) {
721
795
  this.finishExplicitStdin(activeOperation);
722
796
  this.exit = true;
@@ -738,6 +812,87 @@ class Java {
738
812
  this.workerSession.terminate(reason);
739
813
  this.cleanupOperation(operation);
740
814
  }
815
+ debugCommand(command) {
816
+ return this.debugSession?.command(command);
817
+ }
818
+ debugPause() {
819
+ return this.debugSession?.pause();
820
+ }
821
+ setBreakpoints(lines, sourcePath) {
822
+ return this.debugSession?.setBreakpoints(lines, sourcePath);
823
+ }
824
+ async debugEvaluate(expression) {
825
+ if (!this.debugSession)
826
+ throw new Error('Java expression evaluation is unavailable without a paused debugger');
827
+ return this.debugSession.evaluate(expression);
828
+ }
829
+ async debugVariables(reference, start, count) {
830
+ return this.debugSession?.variables(reference, start, count) ?? [];
831
+ }
832
+ async debugScopes(frameId) {
833
+ return this.debugSession?.scopes(frameId) ?? [];
834
+ }
835
+ async debugFrameScopes(frameId) {
836
+ return this.debugSession?.scopes(frameId, false) ?? [];
837
+ }
838
+ evaluateSnapshot(expression, context, signal, operation) {
839
+ const evaluate = async () => {
840
+ signal.throwIfAborted();
841
+ if (!this.isOperationActive(operation) ||
842
+ !this.evaluationAssets ||
843
+ !this.evaluationLimits)
844
+ throw new Error('Java evaluation requires an active paused debugger');
845
+ const { buildJavaDebugEvaluationProgram } = await import('./worker/javaDebugEvaluator');
846
+ signal.throwIfAborted();
847
+ const program = buildJavaDebugEvaluationProgram({
848
+ expression,
849
+ bindings: context.bindings
850
+ });
851
+ const sandbox = (this.evaluationSandbox ??= new Java());
852
+ sandbox.cacheEvaluationArtifacts = true;
853
+ const abort = () => {
854
+ if (this.evaluationSandbox === sandbox)
855
+ this.evaluationSandbox = undefined;
856
+ void sandbox.dispose();
857
+ };
858
+ signal.addEventListener('abort', abort, { once: true });
859
+ let output = '';
860
+ sandbox.output = (chunk) => {
861
+ output += chunk;
862
+ };
863
+ const limits = {
864
+ ...this.evaluationLimits,
865
+ compileTimeoutMs: Math.min(this.evaluationLimits.compileTimeoutMs, 30_000),
866
+ runTimeoutMs: Math.min(this.evaluationLimits.runTimeoutMs, 10_000),
867
+ maxOutputBytes: Math.min(this.evaluationLimits.maxOutputBytes, 65_536)
868
+ };
869
+ try {
870
+ await sandbox.load(this.evaluationAssets, '', false, [], { signal, limits });
871
+ signal.throwIfAborted();
872
+ await sandbox.run(program.code, false, false, undefined, program.args, {
873
+ signal,
874
+ limits,
875
+ stdin: '',
876
+ debugMode: 'none'
877
+ });
878
+ signal.throwIfAborted();
879
+ return output;
880
+ }
881
+ finally {
882
+ signal.removeEventListener('abort', abort);
883
+ sandbox.output = undefined;
884
+ }
885
+ };
886
+ const result = this.evaluationQueue.then(evaluate);
887
+ this.evaluationQueue = result.then(() => { }, () => { });
888
+ return result;
889
+ }
890
+ disposeEvaluationSandbox() {
891
+ const sandbox = this.evaluationSandbox;
892
+ this.evaluationSandbox = undefined;
893
+ if (sandbox)
894
+ void sandbox.dispose();
895
+ }
741
896
  kill() {
742
897
  this.terminate();
743
898
  }
@@ -773,6 +928,7 @@ class Java {
773
928
  if (this.disposePromise)
774
929
  return this.disposePromise;
775
930
  this.disposed = true;
931
+ this.disposeEvaluationSandbox();
776
932
  this.disposePromise = Promise.resolve();
777
933
  const activeOperation = this.activeOperation;
778
934
  const assetBridge = this.assetBridge;
@@ -0,0 +1,62 @@
1
+ import { DebugCommandMailbox } from './debugMailbox';
2
+ import type { DebugCommand, DebugScope, DebugSessionEvent, DebugVariable } from './options';
3
+ export interface JavaDebugEvaluationContext {
4
+ bindings: Array<{
5
+ name: string;
6
+ type: string;
7
+ value: string | null;
8
+ unavailable?: string;
9
+ }>;
10
+ }
11
+ export interface JavaDebugSessionOptions {
12
+ evaluate?: (expression: string, context: JavaDebugEvaluationContext, signal: AbortSignal) => Promise<string>;
13
+ requestTimeoutMs?: number;
14
+ evaluationTimeoutMs?: number;
15
+ }
16
+ interface JavaDebugMessage {
17
+ consumed?: boolean;
18
+ event?: DebugSessionEvent;
19
+ stopId?: number;
20
+ response?: {
21
+ id: number;
22
+ stopId: number;
23
+ value?: unknown;
24
+ error?: string;
25
+ };
26
+ }
27
+ export declare class JavaDebugSession {
28
+ private readonly sourcePath;
29
+ private readonly emit;
30
+ private readonly options;
31
+ readonly mailbox: DebugCommandMailbox;
32
+ private closed;
33
+ private stopId?;
34
+ private frameId?;
35
+ private generation;
36
+ private selectionVersion;
37
+ private selectingFrame;
38
+ private frames;
39
+ private references;
40
+ private nextRequest;
41
+ private pending;
42
+ private evaluations;
43
+ private readonly requestTimeoutMs;
44
+ private readonly evaluationTimeoutMs;
45
+ constructor(sourcePath: string, emit: (event: DebugSessionEvent) => void, options?: JavaDebugSessionOptions);
46
+ handle(message: JavaDebugMessage): void;
47
+ command(command: DebugCommand): void;
48
+ pause(): void;
49
+ setBreakpoints(lines: number[], sourcePath?: string): void;
50
+ scopes(frameId: number, select?: boolean): Promise<DebugScope[]>;
51
+ variables(reference: number, start?: number, count?: number): Promise<DebugVariable[]>;
52
+ evaluate(expression: string): Promise<string>;
53
+ private assertPaused;
54
+ private assertCurrent;
55
+ private request;
56
+ private validateVariables;
57
+ private rememberVariables;
58
+ private cancelEvaluations;
59
+ private invalidate;
60
+ dispose(): void;
61
+ }
62
+ export {};
@@ -0,0 +1,305 @@
1
+ import { DebugCommandMailbox } from './debugMailbox';
2
+ const MAX_PENDING_REQUESTS = 64;
3
+ const MAX_VARIABLE_PAGE = 1000;
4
+ const validId = (value) => Number.isSafeInteger(value) && Number(value) > 0;
5
+ function timeout(value, fallback) {
6
+ const milliseconds = value ?? fallback;
7
+ if (!Number.isSafeInteger(milliseconds) || milliseconds < 1 || milliseconds > 2_147_483_647)
8
+ throw new RangeError('Invalid Java debugger request timeout');
9
+ return milliseconds;
10
+ }
11
+ export class JavaDebugSession {
12
+ sourcePath;
13
+ emit;
14
+ options;
15
+ mailbox = new DebugCommandMailbox('Java');
16
+ closed = false;
17
+ stopId;
18
+ frameId;
19
+ generation = 0;
20
+ selectionVersion = 0;
21
+ selectingFrame = false;
22
+ frames = new Set();
23
+ references = new Set();
24
+ nextRequest = 0;
25
+ pending = new Map();
26
+ evaluations = new Set();
27
+ requestTimeoutMs;
28
+ evaluationTimeoutMs;
29
+ constructor(sourcePath, emit, options = {}) {
30
+ this.sourcePath = sourcePath;
31
+ this.emit = emit;
32
+ this.options = options;
33
+ this.requestTimeoutMs = timeout(options.requestTimeoutMs, 10_000);
34
+ this.evaluationTimeoutMs = timeout(options.evaluationTimeoutMs, 45_000);
35
+ }
36
+ handle(message) {
37
+ if (this.closed)
38
+ return;
39
+ if (message.consumed)
40
+ this.mailbox.flush();
41
+ if (message.response) {
42
+ const response = message.response;
43
+ const pending = this.pending.get(response.id);
44
+ if (pending && pending.stopId === response.stopId && response.stopId === this.stopId) {
45
+ this.pending.delete(response.id);
46
+ pending.cleanup();
47
+ if (typeof response.error === 'string')
48
+ pending.reject(new Error(response.error));
49
+ else
50
+ pending.resolve(response.value);
51
+ }
52
+ }
53
+ const event = message.event;
54
+ if (!event)
55
+ return;
56
+ if (event.type === 'stop') {
57
+ this.dispose();
58
+ return;
59
+ }
60
+ if (event.type === 'pause') {
61
+ this.invalidate(new Error('Java debugger values became stale after a new pause'));
62
+ // Older producers can still deliver events and accept controls, but do not
63
+ // expose unversioned values through the request protocol.
64
+ this.stopId = validId(message.stopId) ? message.stopId : undefined;
65
+ for (const frame of event.callStack) {
66
+ if (validId(frame.id))
67
+ this.frames.add(frame.id);
68
+ }
69
+ if (validId(event.frameId)) {
70
+ this.frames.add(event.frameId);
71
+ this.frameId = event.frameId;
72
+ }
73
+ for (const scope of event.scopes ?? []) {
74
+ if (validId(scope.variablesReference))
75
+ this.references.add(scope.variablesReference);
76
+ this.rememberVariables(scope.variables);
77
+ }
78
+ this.rememberVariables(event.locals);
79
+ }
80
+ else if (event.type === 'resume') {
81
+ this.invalidate(new Error('Java debugger values became stale after resume'));
82
+ }
83
+ this.emit(event);
84
+ }
85
+ command(command) {
86
+ this.mailbox.send(JSON.stringify({ op: 'control', command }));
87
+ this.invalidate(new Error('Java debugger values became stale after a control command'));
88
+ }
89
+ pause() {
90
+ this.mailbox.send(JSON.stringify({ op: 'pause' }));
91
+ }
92
+ setBreakpoints(lines, sourcePath = this.sourcePath) {
93
+ if (lines.length > 1024 || lines.some((line) => !Number.isSafeInteger(line) || line < 1))
94
+ throw new RangeError('Invalid Java breakpoint lines');
95
+ this.mailbox.send(JSON.stringify({ op: 'breakpoints', lines, sourcePath }));
96
+ }
97
+ async scopes(frameId, select = true) {
98
+ this.assertPaused();
99
+ if (!validId(frameId) || !this.frames.has(frameId))
100
+ throw new Error('Unknown or stale Java frame');
101
+ const generation = this.generation;
102
+ const selection = select ? ++this.selectionVersion : this.selectionVersion;
103
+ if (select) {
104
+ this.selectingFrame = true;
105
+ this.cancelEvaluations(new Error('Java evaluation became stale after frame selection'));
106
+ }
107
+ try {
108
+ const value = await this.request('scopes', { frameId });
109
+ this.assertCurrent(generation);
110
+ if (select && selection !== this.selectionVersion)
111
+ throw new Error('Java frame selection became stale');
112
+ if (!Array.isArray(value) || value.length > 64)
113
+ throw new Error('Invalid Java debugger scopes response');
114
+ for (const scope of value) {
115
+ if (!scope ||
116
+ typeof scope.name !== 'string' ||
117
+ !validId(scope.variablesReference) ||
118
+ typeof scope.expensive !== 'boolean')
119
+ throw new Error('Invalid Java debugger scope');
120
+ this.validateVariables(scope.variables);
121
+ }
122
+ for (const scope of value) {
123
+ this.references.add(scope.variablesReference);
124
+ this.rememberVariables(scope.variables);
125
+ }
126
+ if (select)
127
+ this.frameId = frameId;
128
+ return value;
129
+ }
130
+ finally {
131
+ if (select && selection === this.selectionVersion)
132
+ this.selectingFrame = false;
133
+ }
134
+ }
135
+ async variables(reference, start = 0, count = 50) {
136
+ this.assertPaused();
137
+ if (!validId(reference) || !this.references.has(reference))
138
+ throw new Error('Unknown or stale Java variable reference');
139
+ if (!Number.isSafeInteger(start) ||
140
+ start < 0 ||
141
+ !Number.isSafeInteger(count) ||
142
+ count < 0 ||
143
+ count > MAX_VARIABLE_PAGE)
144
+ throw new RangeError('Invalid Java variable page');
145
+ const generation = this.generation;
146
+ const value = await this.request('variables', { reference, start, count });
147
+ this.assertCurrent(generation);
148
+ this.validateVariables(value);
149
+ if (value.length > count)
150
+ throw new Error('Java variable response exceeded its requested page');
151
+ this.rememberVariables(value);
152
+ return value;
153
+ }
154
+ async evaluate(expression) {
155
+ if (typeof expression !== 'string' || expression.length > 4096)
156
+ throw new RangeError('Java expression exceeds 4096 characters');
157
+ const evaluate = this.options.evaluate;
158
+ if (!evaluate)
159
+ throw new Error('Java expression evaluation is unavailable');
160
+ this.assertPaused();
161
+ if (this.selectingFrame || this.frameId === undefined)
162
+ throw new Error('Java evaluation requires a selected paused frame');
163
+ if (this.evaluations.size + this.pending.size >= MAX_PENDING_REQUESTS)
164
+ throw new Error('Java debugger request queue is full');
165
+ const frameId = this.frameId;
166
+ const generation = this.generation;
167
+ const controller = new AbortController();
168
+ return await new Promise((resolve, reject) => {
169
+ const finish = (error, value) => {
170
+ if (!this.evaluations.delete(operation))
171
+ return;
172
+ clearTimeout(timer);
173
+ if (error) {
174
+ controller.abort(error);
175
+ reject(error);
176
+ }
177
+ else
178
+ resolve(value);
179
+ };
180
+ const operation = { cancel: (error) => finish(error) };
181
+ const timer = setTimeout(() => finish(new Error('Java evaluation timed out')), this.evaluationTimeoutMs);
182
+ this.evaluations.add(operation);
183
+ void this.request('context', { frameId }, controller.signal)
184
+ .then((value) => {
185
+ this.assertCurrent(generation);
186
+ controller.signal.throwIfAborted();
187
+ const context = value;
188
+ if (!context ||
189
+ !Array.isArray(context.bindings) ||
190
+ context.bindings.length > 1024 ||
191
+ context.bindings.some((binding) => !binding ||
192
+ typeof binding.name !== 'string' ||
193
+ typeof binding.type !== 'string' ||
194
+ (binding.value !== null && typeof binding.value !== 'string') ||
195
+ (binding.unavailable !== undefined &&
196
+ typeof binding.unavailable !== 'string')))
197
+ throw new Error('Invalid Java evaluation context');
198
+ return evaluate(expression, { bindings: context.bindings.map((binding) => ({ ...binding })) }, controller.signal);
199
+ })
200
+ .then((value) => {
201
+ if (typeof value !== 'string')
202
+ finish(new Error('Invalid Java evaluation result'));
203
+ else
204
+ finish(undefined, value);
205
+ }, (error) => finish(error instanceof Error ? error : new Error(String(error))));
206
+ });
207
+ }
208
+ assertPaused() {
209
+ if (this.closed)
210
+ throw new Error('Java debugger stopped');
211
+ if (this.stopId === undefined)
212
+ throw new Error('Java debugger request requires a paused snapshot');
213
+ }
214
+ assertCurrent(generation) {
215
+ this.assertPaused();
216
+ if (this.generation !== generation)
217
+ throw new Error('Java debugger response became stale');
218
+ }
219
+ request(op, arguments_, signal) {
220
+ this.assertPaused();
221
+ if (signal?.aborted)
222
+ return Promise.reject(signal.reason);
223
+ if (this.pending.size >= MAX_PENDING_REQUESTS)
224
+ return Promise.reject(new Error('Java debugger request queue is full'));
225
+ const stopId = this.stopId;
226
+ const id = ++this.nextRequest;
227
+ return new Promise((resolve, reject) => {
228
+ const finish = (error) => {
229
+ const pending = this.pending.get(id);
230
+ if (!pending)
231
+ return;
232
+ this.pending.delete(id);
233
+ pending.cleanup();
234
+ reject(error);
235
+ };
236
+ const aborted = () => finish(signal?.reason ?? new Error('Java debugger request cancelled'));
237
+ const timer = setTimeout(() => finish(new Error('Java debugger request timed out')), this.requestTimeoutMs);
238
+ this.pending.set(id, {
239
+ stopId,
240
+ resolve,
241
+ reject,
242
+ cleanup() {
243
+ clearTimeout(timer);
244
+ signal?.removeEventListener('abort', aborted);
245
+ }
246
+ });
247
+ signal?.addEventListener('abort', aborted, { once: true });
248
+ try {
249
+ this.mailbox.send(JSON.stringify({ op, id, stopId, ...arguments_ }));
250
+ }
251
+ catch (error) {
252
+ finish(error instanceof Error ? error : new Error(String(error)));
253
+ }
254
+ });
255
+ }
256
+ validateVariables(value) {
257
+ if (!Array.isArray(value) ||
258
+ value.length > MAX_VARIABLE_PAGE ||
259
+ value.some((variable) => !variable ||
260
+ typeof variable.name !== 'string' ||
261
+ typeof variable.value !== 'string' ||
262
+ (variable.variablesReference !== undefined &&
263
+ variable.variablesReference !== 0 &&
264
+ !validId(variable.variablesReference))))
265
+ throw new Error('Invalid Java debugger variables response');
266
+ }
267
+ rememberVariables(variables) {
268
+ for (const variable of variables) {
269
+ if (validId(variable.variablesReference))
270
+ this.references.add(variable.variablesReference);
271
+ }
272
+ }
273
+ cancelEvaluations(error) {
274
+ for (const evaluation of this.evaluations)
275
+ evaluation.cancel(error);
276
+ }
277
+ invalidate(error) {
278
+ this.generation++;
279
+ this.selectionVersion++;
280
+ this.selectingFrame = false;
281
+ this.stopId = undefined;
282
+ this.frameId = undefined;
283
+ this.frames.clear();
284
+ this.references.clear();
285
+ this.cancelEvaluations(error);
286
+ for (const pending of this.pending.values()) {
287
+ pending.cleanup();
288
+ pending.reject(error);
289
+ }
290
+ this.pending.clear();
291
+ }
292
+ dispose() {
293
+ if (this.closed)
294
+ return;
295
+ this.closed = true;
296
+ this.mailbox.close();
297
+ this.invalidate(new Error('Java debugger stopped'));
298
+ try {
299
+ this.emit({ type: 'stop' });
300
+ }
301
+ catch {
302
+ /* Mandatory cleanup precedes caller notifications. */
303
+ }
304
+ }
305
+ }
@@ -0,0 +1,6 @@
1
+ /** Values stay in the real Java VM while a stopped hook services inspection requests. */
2
+ export declare function createJavaDebugBridge(className: string, packageName?: string): {
3
+ qualifiedName: string;
4
+ sourceFileName: string;
5
+ source: string;
6
+ };