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
@@ -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?.({
@@ -687,8 +747,9 @@ class Java {
687
747
  resolve(results);
688
748
  return;
689
749
  }
690
- if (error)
691
- failRun(error);
750
+ if (Object.hasOwn(event.data, 'error')) {
751
+ failRun(error === '' ? 'Java execution failed' : error);
752
+ }
692
753
  }
693
754
  catch (error) {
694
755
  failRun(error, true);
@@ -702,6 +763,17 @@ class Java {
702
763
  worker.postMessage({
703
764
  code,
704
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,
705
777
  buffer: this.buffer,
706
778
  args: programArgs,
707
779
  stdin: stdin ?? '',
@@ -716,6 +788,9 @@ class Java {
716
788
  }
717
789
  });
718
790
  return running.finally(() => {
791
+ runDebugSession?.dispose();
792
+ if (this.debugSession === runDebugSession)
793
+ this.debugSession = undefined;
719
794
  if (this.releaseOperation(activeOperation)) {
720
795
  this.finishExplicitStdin(activeOperation);
721
796
  this.exit = true;
@@ -737,6 +812,87 @@ class Java {
737
812
  this.workerSession.terminate(reason);
738
813
  this.cleanupOperation(operation);
739
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
+ }
740
896
  kill() {
741
897
  this.terminate();
742
898
  }
@@ -772,6 +928,7 @@ class Java {
772
928
  if (this.disposePromise)
773
929
  return this.disposePromise;
774
930
  this.disposed = true;
931
+ this.disposeEvaluationSandbox();
775
932
  this.disposePromise = Promise.resolve();
776
933
  const activeOperation = this.activeOperation;
777
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
+ };