wasm-idle 1.1.2 → 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 (121) hide show
  1. package/README.md +134 -82
  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 +1 -1
  22. package/dist/playground/assetBridge.js +5 -2
  23. package/dist/playground/assets.d.ts +8 -0
  24. package/dist/playground/clang.d.ts +5 -1
  25. package/dist/playground/clang.js +61 -5
  26. package/dist/playground/compiledLldb.d.ts +41 -0
  27. package/dist/playground/compiledLldb.js +167 -0
  28. package/dist/playground/d.d.ts +4 -1
  29. package/dist/playground/d.js +78 -9
  30. package/dist/playground/debugDeadline.d.ts +12 -0
  31. package/dist/playground/debugDeadline.js +34 -0
  32. package/dist/playground/debugMailbox.d.ts +12 -0
  33. package/dist/playground/debugMailbox.js +77 -0
  34. package/dist/playground/go.js +9 -4
  35. package/dist/playground/goDebugInstrumentation.js +24 -44
  36. package/dist/playground/java-debug-FMHDKUN6.js +124 -0
  37. package/dist/playground/java-debug-notices.txt +492 -0
  38. package/dist/playground/java.d.ts +17 -1
  39. package/dist/playground/java.js +159 -3
  40. package/dist/playground/javaDebug.d.ts +62 -0
  41. package/dist/playground/javaDebug.js +305 -0
  42. package/dist/playground/javaDebugBridge.d.ts +6 -0
  43. package/dist/playground/javaDebugBridge.js +250 -0
  44. package/dist/playground/javaDebugSource.d.ts +9 -0
  45. package/dist/playground/javaDebugSource.js +4 -0
  46. package/dist/playground/javaRuntimeErrors.js +34 -1
  47. package/dist/playground/lean4Assets.d.ts +1 -25
  48. package/dist/playground/lean4Assets.js +2 -123
  49. package/dist/playground/lfortranAssets.d.ts +2 -2
  50. package/dist/playground/lldbSession.d.ts +23 -2
  51. package/dist/playground/lldbSession.js +278 -58
  52. package/dist/playground/lldbSourcePath.d.ts +2 -0
  53. package/dist/playground/lldbSourcePath.js +9 -0
  54. package/dist/playground/lua.d.ts +20 -1
  55. package/dist/playground/lua.js +190 -8
  56. package/dist/playground/luaDebug.d.ts +1 -0
  57. package/dist/playground/luaDebug.js +1 -0
  58. package/dist/playground/nim.d.ts +1 -0
  59. package/dist/playground/nim.js +8 -0
  60. package/dist/playground/objectivec.d.ts +7 -6
  61. package/dist/playground/objectivec.js +75 -9
  62. package/dist/playground/options.d.ts +10 -4
  63. package/dist/playground/python.d.ts +8 -1
  64. package/dist/playground/python.js +81 -6
  65. package/dist/playground/ruby.d.ts +10 -1
  66. package/dist/playground/ruby.js +66 -1
  67. package/dist/playground/rubyDebug.d.ts +21 -0
  68. package/dist/playground/rubyDebug.js +128 -0
  69. package/dist/playground/rust.d.ts +5 -1
  70. package/dist/playground/rust.js +128 -46
  71. package/dist/playground/sandbox.d.ts +8 -1
  72. package/dist/playground/staticWorkerRuntime.js +8 -2
  73. package/dist/playground/stdinBuffer.d.ts +1 -1
  74. package/dist/playground/stdinBuffer.js +19 -2
  75. package/dist/playground/tinygo.js +7 -0
  76. package/dist/playground/typescript.js +8 -0
  77. package/dist/playground/v.d.ts +3 -2
  78. package/dist/playground/v.js +66 -12
  79. package/dist/playground/wasmC3Version.d.ts +2 -2
  80. package/dist/playground/wasmC3Version.js +2 -2
  81. package/dist/playground/wasmLean4Version.d.ts +1 -110
  82. package/dist/playground/wasmLean4Version.js +2 -111
  83. package/dist/playground/wasmLfortranVersion.d.ts +2 -2
  84. package/dist/playground/wasmLfortranVersion.js +2 -2
  85. package/dist/playground/wasmLuaVersion.d.ts +1 -1
  86. package/dist/playground/wasmLuaVersion.js +1 -1
  87. package/dist/playground/wasmRustVersion.d.ts +26 -38
  88. package/dist/playground/wasmRustVersion.js +25 -40
  89. package/dist/playground/worker/clang.js +1 -1
  90. package/dist/playground/worker/cobol.js +1 -1
  91. package/dist/playground/worker/d.js +51 -2
  92. package/dist/playground/worker/fortran.js +1 -1
  93. package/dist/playground/worker/java.js +188 -35
  94. package/dist/playground/worker/javaDebugEvaluator.d.ts +16 -0
  95. package/dist/playground/worker/javaDebugEvaluator.js +44 -0
  96. package/dist/playground/worker/javaDebugRuntime.d.ts +24 -0
  97. package/dist/playground/worker/javaDebugRuntime.js +315 -0
  98. package/dist/playground/worker/javaOutput.d.ts +11 -0
  99. package/dist/playground/worker/javaOutput.js +54 -0
  100. package/dist/playground/worker/lua.js +13 -0
  101. package/dist/playground/worker/python.js +57 -22
  102. package/dist/playground/worker/ruby.js +13 -0
  103. package/dist/playground/worker/rubyDebugPreview.d.ts +2 -0
  104. package/dist/playground/worker/rubyDebugPreview.js +80 -0
  105. package/dist/playground/worker/rubyTracepoint.d.ts +16 -0
  106. package/dist/playground/worker/rubyTracepoint.js +162 -0
  107. package/dist/playground/worker/rust.js +4 -1
  108. package/dist/playground/worker/v.js +30 -5
  109. package/dist/playground/zig.js +4 -0
  110. package/package.json +55 -11
  111. package/dist/playground/container/ContainerExplorer.svelte +0 -307
  112. package/dist/playground/container/ContainerExplorer.svelte.d.ts +0 -14
  113. package/dist/playground/container/clang-runtime.js +0 -343
  114. package/dist/playground/container/client.d.ts +0 -15
  115. package/dist/playground/container/owner.worker.d.ts +0 -1
  116. package/dist/playground/container/owner.worker.js +0 -390
  117. package/dist/playground/container/release.d.ts +0 -31
  118. package/dist/playground/container/release.js +0 -612
  119. /package/dist/{playground/container → container}/explorer.js +0 -0
  120. /package/dist/{playground/container → container}/protocol.js +0 -0
  121. /package/dist/{playground/container → container}/workspace.js +0 -0
@@ -1,53 +1,48 @@
1
1
  import { acceptCompiledTeaVmModule, loadStreamingJavaCompiler } from './javaStreaming';
2
+ import { createJavaOutput } from './javaOutput';
2
3
  import { createJavaStdinBridge, prepareJavaRuntimeStdinInjection } from '../javaRuntimeStdin';
3
4
  import { resolveJavaSourceIdentity } from '../javaSource';
4
5
  import { prepareJavaExceptionBridge } from '../javaRuntimeErrors';
5
6
  import { waitForBufferedStdin } from '../stdinBuffer';
7
+ import { createJavaDebugBridge } from '../javaDebugBridge';
8
+ import { readDebugCommand } from '../debugMailbox';
9
+ import { createJavaDebugRuntime } from './javaDebugRuntime';
6
10
  import { configureWorkerRuntimeAssets, handleWorkerAssetMessage, loadWorkerRuntimeAsset } from './assets';
7
11
  let compilerLib = null;
8
12
  let compiler = null;
9
13
  let runtimeLoad = null;
10
14
  let exceptionDeobfuscator = null;
11
15
  let loadedBaseUrl = '';
12
- let stdoutBuffer = '';
13
- let stderrBuffer = '';
16
+ let output = null;
14
17
  let compiledCode = '';
15
18
  let compiledStdin = '';
16
19
  let compiledMainClass = '';
17
20
  let compiledExceptionFormatter = '';
18
21
  let compiledWasm = null;
22
+ let compiledModule = null;
23
+ let acceptsCompiledModule = false;
19
24
  let compiledDiagnostics = [];
20
25
  let compiledActivePath = '';
21
26
  let compiledWorkspaceFiles = [];
27
+ let compiledDebugEnabled = false;
28
+ let compiledDebugFiles = [];
29
+ // Only the isolated debugger evaluator opts in. Entries contain immutable compiled
30
+ // code, never instances/imports/heap state; every evaluation still loads a fresh instance.
31
+ const evaluationArtifacts = new Map();
32
+ const MAX_EVALUATION_ARTIFACTS = 8;
33
+ const MAX_EVALUATION_ARTIFACT_BYTES = 16 * 1024 * 1024;
34
+ let evaluationArtifactBytes = 0;
22
35
  let currentSourcePaths = new Set();
23
36
  const decoder = new TextDecoder();
24
37
  const toInt8Array = (bytes) => new Int8Array(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
25
- const flushStdout = () => {
26
- if (!stdoutBuffer)
27
- return;
28
- self.postMessage({ output: stdoutBuffer });
29
- stdoutBuffer = '';
30
- };
31
- const flushStderr = () => {
32
- if (!stderrBuffer)
33
- return;
34
- self.postMessage({ output: stderrBuffer });
35
- stderrBuffer = '';
36
- };
37
- const pushStdout = (charCode) => {
38
- stdoutBuffer += String.fromCharCode(charCode);
39
- if (charCode === 10)
40
- flushStdout();
41
- };
42
- const pushStderr = (charCode) => {
43
- stderrBuffer += String.fromCharCode(charCode);
44
- if (charCode === 10)
45
- flushStderr();
46
- };
38
+ const flushStdout = () => output?.flush();
39
+ const flushStderr = flushStdout;
40
+ const pushStdout = (charCode) => output?.write(charCode);
41
+ const pushStderr = pushStdout;
47
42
  self.addEventListener('message', async (event) => {
48
43
  if (handleWorkerAssetMessage(event.data))
49
44
  return;
50
- const { load, assets, buffer, code, prepare, args = [], stdin = '', hasExplicitStdin = false, activePath, workspaceFiles = [] } = event.data;
45
+ const { load, assets, buffer, code, prepare, debugMode, cacheEvaluationArtifacts, javaDebug, args = [], stdin = '', hasExplicitStdin = false, activePath, workspaceFiles = [] } = event.data;
51
46
  try {
52
47
  if (load) {
53
48
  const runtimeAssets = assets;
@@ -62,7 +57,9 @@ self.addEventListener('message', async (event) => {
62
57
  const [runtimeModule, compilerAsset] = await Promise.all([
63
58
  (async () => {
64
59
  let runtimeSource = decoder.decode((await loadWorkerRuntimeAsset('compiler.wasm-runtime.js')).bytes);
65
- if (streamCompiler)
60
+ // Custom runtime loaders retain their original byte-input contract.
61
+ acceptsCompiledModule = streamCompiler;
62
+ if (acceptsCompiledModule)
66
63
  runtimeSource = acceptCompiledTeaVmModule(runtimeSource);
67
64
  const runtimeUrl = URL.createObjectURL(new Blob([runtimeSource], {
68
65
  type: 'text/javascript;charset=utf-8'
@@ -111,9 +108,14 @@ self.addEventListener('message', async (event) => {
111
108
  compiledMainClass = '';
112
109
  compiledExceptionFormatter = '';
113
110
  compiledWasm = null;
111
+ compiledModule = null;
114
112
  compiledDiagnostics = [];
115
113
  compiledActivePath = '';
116
114
  compiledWorkspaceFiles = [];
115
+ compiledDebugEnabled = false;
116
+ compiledDebugFiles = [];
117
+ evaluationArtifacts.clear();
118
+ evaluationArtifactBytes = 0;
117
119
  currentSourcePaths = new Set();
118
120
  }
119
121
  self.postMessage({ load: true });
@@ -121,18 +123,30 @@ self.addEventListener('message', async (event) => {
121
123
  }
122
124
  if (!compiler || !runtimeLoad || !exceptionDeobfuscator)
123
125
  throw new Error('TeaVM compiler not loaded');
124
- stdoutBuffer = '';
125
- stderrBuffer = '';
126
+ output?.close();
127
+ output = createJavaOutput((text) => self.postMessage({ output: text }));
126
128
  const explicitStdin = hasExplicitStdin === true;
127
129
  const stdinInjection = prepareJavaRuntimeStdinInjection(code);
128
130
  const sourceIdentity = resolveJavaSourceIdentity(code);
129
131
  const sourcePath = typeof activePath === 'string' && activePath ? activePath : sourceIdentity.sourcePath;
130
132
  const sourceFileName = sourcePath.split('/').pop() || sourcePath;
131
133
  if (!Array.isArray(workspaceFiles) ||
132
- !workspaceFiles.every((file) => file && typeof file.path === 'string' && typeof file.content === 'string')) {
134
+ !workspaceFiles.every((file) => file &&
135
+ typeof file.path === 'string' &&
136
+ (typeof file.content === 'string' || file.content instanceof Uint8Array))) {
133
137
  throw new Error('Invalid Java workspace files');
134
138
  }
135
- const sourceFiles = workspaceFiles;
139
+ // Container files arrive as bytes; Java compiler inputs are strict UTF-8 source text.
140
+ const sourceDecoder = new TextDecoder('utf-8', { fatal: true });
141
+ const sourceFiles = workspaceFiles.map((file) => ({
142
+ path: file.path,
143
+ content: typeof file.content === 'string'
144
+ ? file.content
145
+ : sourceDecoder.decode(file.content)
146
+ }));
147
+ const debugEnabled = debugMode === 'trace';
148
+ if (debugMode && debugMode !== 'none' && !debugEnabled)
149
+ throw new Error('Java supports the trace debugger backend');
136
150
  const workspaceChanged = compiledActivePath !== sourcePath ||
137
151
  compiledWorkspaceFiles.length !== sourceFiles.length ||
138
152
  compiledWorkspaceFiles.some((file, index) => file.path !== sourceFiles[index]?.path ||
@@ -143,18 +157,76 @@ self.addEventListener('message', async (event) => {
143
157
  sourceFiles.some((file) => file.path === stdinInjection.helperSourcePath))) {
144
158
  throw new Error(`Java workspace conflicts with generated stdin helper: ${stdinInjection.helperSourcePath}`);
145
159
  }
160
+ const evaluationKey = cacheEvaluationArtifacts === true &&
161
+ acceptsCompiledModule &&
162
+ !debugEnabled &&
163
+ sourceFiles.length === 0
164
+ ? JSON.stringify([code, sourcePath, stdinInjection.stdinCacheKey])
165
+ : undefined;
166
+ const cachedEvaluation = evaluationKey ? evaluationArtifacts.get(evaluationKey) : undefined;
167
+ if (evaluationKey && cachedEvaluation) {
168
+ evaluationArtifacts.delete(evaluationKey);
169
+ evaluationArtifacts.set(evaluationKey, cachedEvaluation);
170
+ compiledCode = code;
171
+ compiledStdin = stdinInjection.stdinCacheKey;
172
+ compiledMainClass = cachedEvaluation.mainClass;
173
+ compiledExceptionFormatter = cachedEvaluation.formatter;
174
+ compiledWasm = cachedEvaluation.wasm;
175
+ compiledModule = cachedEvaluation.module;
176
+ compiledDiagnostics = cachedEvaluation.diagnostics;
177
+ compiledActivePath = sourcePath;
178
+ compiledWorkspaceFiles = [];
179
+ compiledDebugEnabled = false;
180
+ compiledDebugFiles = [];
181
+ }
146
182
  if (compiledCode !== code ||
183
+ compiledDebugEnabled !== debugEnabled ||
147
184
  compiledStdin !== stdinInjection.stdinCacheKey ||
148
- workspaceChanged ||
185
+ (!cachedEvaluation && workspaceChanged) ||
149
186
  !compiledWasm) {
150
187
  // A failed rebuild must never leave a previous artifact eligible for reuse.
151
188
  compiledWasm = null;
189
+ compiledModule = null;
152
190
  compiledDiagnostics = [];
191
+ compiledDebugFiles = [];
153
192
  const mainClass = sourceIdentity.mainClass;
154
193
  currentSourcePaths = new Set([sourcePath, ...sourceFiles.map((file) => file.path)].flatMap((path) => [
155
194
  path,
156
195
  path.split('/').pop() || path
157
196
  ]));
197
+ let mainSource = stdinInjection.transformedCode;
198
+ let otherSources = sourceFiles;
199
+ let debugBridge;
200
+ const debugFiles = [];
201
+ if (debugEnabled) {
202
+ const { instrumentJavaDebugSource } = await import('../javaDebugSource');
203
+ const originals = [{ path: sourcePath, content: code }, ...sourceFiles];
204
+ let nonce;
205
+ do {
206
+ nonce = crypto.randomUUID().replaceAll('-', '');
207
+ } while (originals.some((file) => file.content.includes(nonce) || file.path.includes(nonce)));
208
+ debugBridge = createJavaDebugBridge(`WasmIdleJavaDebug_${nonce}`, `wasm_idle_debug_${nonce}`);
209
+ const instrumented = [];
210
+ for (const file of originals) {
211
+ if (file.path !== sourcePath && !file.path.endsWith('.java')) {
212
+ instrumented.push(file);
213
+ continue;
214
+ }
215
+ const result = instrumentJavaDebugSource(file.content, file.path, debugBridge.qualifiedName);
216
+ const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(file.content)));
217
+ debugFiles.push({
218
+ path: file.path,
219
+ sourceContentSha256: [...hash]
220
+ .map((byte) => byte.toString(16).padStart(2, '0'))
221
+ .join(''),
222
+ lineCount: file.content.trimEnd().split(/\r\n|\r|\n/).length,
223
+ locations: result.locations
224
+ });
225
+ instrumented.push({ path: file.path, content: result.code });
226
+ }
227
+ mainSource = prepareJavaRuntimeStdinInjection(instrumented[0].content).transformedCode;
228
+ otherSources = instrumented.slice(1);
229
+ }
158
230
  const diagnosticLines = [];
159
231
  const diagnosticMessages = [];
160
232
  let compilingExceptionBridge = false;
@@ -199,10 +271,12 @@ self.addEventListener('message', async (event) => {
199
271
  compiler.clearInputClassFiles?.();
200
272
  compiler.clearOutputFiles?.();
201
273
  // TeaVM derives packages from source text but validates public types against the basename.
202
- compiler.addSourceFile(sourceFileName, stdinInjection.transformedCode);
203
- for (const file of sourceFiles) {
274
+ compiler.addSourceFile(sourceFileName, mainSource);
275
+ for (const file of otherSources) {
204
276
  compiler.addSourceFile(file.path.split('/').pop() || file.path, file.content);
205
277
  }
278
+ if (debugBridge)
279
+ compiler.addSourceFile(debugBridge.sourceFileName, debugBridge.source);
206
280
  if (stdinInjection.usesStdin &&
207
281
  stdinInjection.helperSourcePath &&
208
282
  stdinInjection.helperSource) {
@@ -259,14 +333,44 @@ self.addEventListener('message', async (event) => {
259
333
  if (!generateOk) {
260
334
  throw new Error(diagnosticLines.join('\n') || 'TeaVM WebAssembly generation failed');
261
335
  }
336
+ const nextWasm = new Uint8Array(compiler.getWebAssemblyOutputFile('app.wasm'));
337
+ const nextModule = acceptsCompiledModule
338
+ ? await WebAssembly.compile(nextWasm, { builtins: ['js-string'] })
339
+ : null;
262
340
  compiledCode = code;
263
341
  compiledStdin = stdinInjection.stdinCacheKey;
264
342
  compiledMainClass = mainClass;
265
343
  compiledExceptionFormatter = exceptionBridge.formatExport;
266
- compiledWasm = new Uint8Array(compiler.getWebAssemblyOutputFile('app.wasm'));
344
+ compiledWasm = nextWasm;
345
+ compiledModule = nextModule;
267
346
  compiledActivePath = sourcePath;
268
347
  compiledWorkspaceFiles = sourceFiles.map((file) => ({ ...file }));
348
+ compiledDebugEnabled = debugEnabled;
349
+ compiledDebugFiles = debugFiles;
269
350
  compiledDiagnostics = diagnosticMessages;
351
+ if (evaluationKey && nextModule) {
352
+ // Bound source, diagnostic and Wasm input bytes, not engine compiled-code RSS.
353
+ const bytes = nextWasm.byteLength +
354
+ evaluationKey.length * 2 +
355
+ JSON.stringify(diagnosticMessages).length * 2;
356
+ if (bytes <= MAX_EVALUATION_ARTIFACT_BYTES) {
357
+ while (evaluationArtifacts.size >= MAX_EVALUATION_ARTIFACTS ||
358
+ evaluationArtifactBytes + bytes > MAX_EVALUATION_ARTIFACT_BYTES) {
359
+ const oldest = evaluationArtifacts.keys().next().value;
360
+ evaluationArtifactBytes -= evaluationArtifacts.get(oldest).bytes;
361
+ evaluationArtifacts.delete(oldest);
362
+ }
363
+ evaluationArtifacts.set(evaluationKey, {
364
+ wasm: nextWasm,
365
+ module: nextModule,
366
+ mainClass,
367
+ formatter: exceptionBridge.formatExport,
368
+ diagnostics: diagnosticMessages,
369
+ bytes
370
+ });
371
+ evaluationArtifactBytes += bytes;
372
+ }
373
+ }
270
374
  }
271
375
  else {
272
376
  // Every operation has its own diagnostic sink, even when compilation is reused.
@@ -288,10 +392,43 @@ self.addEventListener('message', async (event) => {
288
392
  const previousWindow = workerGlobal.window;
289
393
  const hadStdinBridge = Object.prototype.hasOwnProperty.call(workerGlobal, 'wasmIdleJavaStdin');
290
394
  const previousStdinBridge = workerGlobal.wasmIdleJavaStdin;
395
+ const hadOutputBridge = Object.prototype.hasOwnProperty.call(workerGlobal, 'wasmIdleJavaOutput');
396
+ const previousOutputBridge = workerGlobal.wasmIdleJavaOutput;
397
+ const hadDebugBridge = Object.prototype.hasOwnProperty.call(workerGlobal, 'wasmIdleJavaDebug');
398
+ const previousDebugBridge = workerGlobal.wasmIdleJavaDebug;
399
+ const errorConstructor = Error;
400
+ const stackTraceLimit = Object.getOwnPropertyDescriptor(errorConstructor, 'stackTraceLimit');
291
401
  workerGlobal.window = workerGlobal;
292
402
  workerGlobal.wasmIdleJavaStdin = stdinBridge;
403
+ workerGlobal.wasmIdleJavaOutput = { flush: () => output?.flush() };
293
404
  try {
294
- const module = await runtimeLoad(compiledWasm, {
405
+ if (debugEnabled) {
406
+ if (!javaDebug)
407
+ throw new Error('Java debugger command transport is missing');
408
+ // V8 defaults to ten physical frames; retain full depth for recursive next/out.
409
+ if (typeof errorConstructor.stackTraceLimit === 'number')
410
+ errorConstructor.stackTraceLimit = Infinity;
411
+ workerGlobal.wasmIdleJavaDebug = createJavaDebugRuntime(compiledDebugFiles, {
412
+ activePath: sourcePath,
413
+ debugPath: javaDebug.sourcePath,
414
+ breakpoints: javaDebug.breakpoints ?? [],
415
+ sourceBreakpoints: javaDebug.sourceBreakpoints,
416
+ pauseOnEntry: javaDebug.pauseOnEntry !== false
417
+ }, (event, stopId) => {
418
+ if (event.type === 'pause') {
419
+ flushStdout();
420
+ flushStderr();
421
+ }
422
+ self.postMessage({ javaDebug: { event, stopId } });
423
+ }, (blocking) => {
424
+ // Synchronous Java loops prevent output timers from running. Keep
425
+ // elapsed batches visible while hooks poll, without flushing every hook.
426
+ if (!blocking)
427
+ output?.flushIfDue();
428
+ return readDebugCommand(javaDebug.buffer, blocking, () => self.postMessage({ javaDebug: { consumed: true } }), 'Java');
429
+ }, (response) => self.postMessage({ javaDebug: { response } }));
430
+ }
431
+ const module = await runtimeLoad(compiledModule ?? compiledWasm, {
295
432
  installImports(imports) {
296
433
  imports.teavmConsole.putcharStdout = pushStdout;
297
434
  imports.teavmConsole.putcharStderr = pushStderr;
@@ -333,6 +470,18 @@ self.addEventListener('message', async (event) => {
333
470
  }
334
471
  finally {
335
472
  stdinBridge.dispose();
473
+ if (hadOutputBridge)
474
+ workerGlobal.wasmIdleJavaOutput = previousOutputBridge;
475
+ else
476
+ delete workerGlobal.wasmIdleJavaOutput;
477
+ if (hadDebugBridge)
478
+ workerGlobal.wasmIdleJavaDebug = previousDebugBridge;
479
+ else
480
+ delete workerGlobal.wasmIdleJavaDebug;
481
+ if (stackTraceLimit)
482
+ Object.defineProperty(errorConstructor, 'stackTraceLimit', stackTraceLimit);
483
+ else
484
+ Reflect.deleteProperty(errorConstructor, 'stackTraceLimit');
336
485
  if (hadStdinBridge)
337
486
  workerGlobal.wasmIdleJavaStdin = previousStdinBridge;
338
487
  else
@@ -352,4 +501,8 @@ self.addEventListener('message', async (event) => {
352
501
  error: error instanceof Error ? error.message : String(error)
353
502
  });
354
503
  }
504
+ finally {
505
+ output?.close();
506
+ output = null;
507
+ }
355
508
  });
@@ -0,0 +1,16 @@
1
+ export interface JavaDebugEvaluationBinding {
2
+ name: string;
3
+ type: string;
4
+ /** Raw Java value text; char is a decimal UTF-16 code unit, String is unquoted. */
5
+ value: string | null;
6
+ unavailable?: string;
7
+ }
8
+ export interface JavaDebugEvaluationRequest {
9
+ expression: string;
10
+ bindings: readonly JavaDebugEvaluationBinding[];
11
+ }
12
+ /** A standalone program; no user classes, initializers or main method are copied into it. */
13
+ export declare function buildJavaDebugEvaluationProgram(request: JavaDebugEvaluationRequest): {
14
+ code: string;
15
+ args: string[];
16
+ };
@@ -0,0 +1,44 @@
1
+ // Third-party license texts: java-debug-notices.txt beside the shared parser.
2
+ import{a as m,b as y}from"../java-debug-FMHDKUN6.js";var N=new Set(["boolean","byte","short","char","int","long","float","double"]),j=new Set(["length","isEmpty","isBlank","charAt","codePointAt","codePointBefore","codePointCount","compareTo","compareToIgnoreCase","equals","equalsIgnoreCase","contains","startsWith","endsWith","indexOf","lastIndexOf","substring","subSequence","trim","strip","stripLeading","stripTrailing","concat","hashCode","toString","regionMatches"]),x=new Set(["substring","subSequence","trim","strip","stripLeading","stripTrailing","concat","toString","valueOf","toHexString","toOctalString","toBinaryString","toUnsignedString"]),T={Math:new Set(["abs","min","max","round","ceil","floor","sqrt","cbrt","pow","sin","cos","tan","asin","acos","atan","atan2","exp","expm1","log","log10","log1p","hypot","signum","copySign","scalb","ulp","nextUp","nextDown","nextAfter","toRadians","toDegrees","addExact","subtractExact","multiplyExact","toIntExact","floorDiv","floorMod","IEEEremainder"]),String:new Set(["valueOf"]),Integer:new Set(["parseInt","parseUnsignedInt","toString","toHexString","toOctalString","toBinaryString","toUnsignedString","compare","compareUnsigned","sum","min","max","bitCount","signum","numberOfLeadingZeros","numberOfTrailingZeros","reverse","reverseBytes","rotateLeft","rotateRight","highestOneBit","lowestOneBit","toUnsignedLong"]),Long:new Set(["parseLong","parseUnsignedLong","toString","toHexString","toOctalString","toBinaryString","toUnsignedString","compare","compareUnsigned","sum","min","max","bitCount","signum","numberOfLeadingZeros","numberOfTrailingZeros","reverse","reverseBytes","rotateLeft","rotateRight","highestOneBit","lowestOneBit"]),Double:new Set(["parseDouble","toString","isNaN","isInfinite","isFinite","compare","sum","min","max"]),Float:new Set(["parseFloat","toString","isNaN","isInfinite","isFinite","compare","sum","min","max"]),Boolean:new Set(["parseBoolean","toString","logicalAnd","logicalOr","logicalXor"]),Character:new Set(["isDigit","isLetter","isLetterOrDigit","isWhitespace","isUpperCase","isLowerCase","toUpperCase","toLowerCase","toTitleCase","getNumericValue","digit","toString"])},A={Math:new Set(["PI","E"]),Integer:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Long:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Short:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Byte:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Character:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Double:new Set(["MIN_VALUE","MIN_NORMAL","MAX_VALUE","NaN","POSITIVE_INFINITY","NEGATIVE_INFINITY"]),Float:new Set(["MIN_VALUE","MIN_NORMAL","MAX_VALUE","NaN","POSITIVE_INFINITY","NEGATIVE_INFINITY"])},b=m((t,i)=>(t.children[i]??[]).flatMap(s=>"children"in s?[s]:[]),"nodes"),L=m((t,i)=>(t.children[i]??[]).filter(s=>!("children"in s)),"tokens");function E(t){return Object.entries(t.children).flatMap(([i,s])=>s.flatMap(f=>"children"in f?E(f):i==="Identifier"?[f]:[])).sort((i,s)=>i.startOffset-s.startOffset)}m(E,"identifiers");function M(t,i){let s=new Set;if(/\\u+[0-9a-fA-F]{4}/.test(t))throw new Error("Java evaluation does not support Unicode preprocessing escapes.");let{cst:f,tokens:o}=y(t,"expression"),S=new Set(["PlusPlus","MinusMinus","New","This","Super","Arrow","DoubleColon","LSquare","LCurly","Class","Instanceof","At"]);if(o.some(a=>S.has(a.tokenType.name)))throw new Error("Java evaluation supports read-only scalar/String expressions; mutation, objects, arrays and closures are unsupported.");let d=new Map,h=m(a=>{if(d.has(a))return d.get(a);if(a.children.AssignmentOperator)throw new Error("Java evaluation does not allow assignment or mutation.");if(a.name==="conditionalExpression"&&a.children.QuestionMark)throw new Error("Java snapshot evaluation does not support conditional expressions because compile-time constant narrowing is unavailable.");if(a.name==="typeArguments")throw new Error("Java evaluation does not support generic or user-type expressions.");let e=Object.values(a.children).flat().flatMap(p=>"children"in p?[p]:[]).map(h),n=e.includes("string")?"string":e.includes("null")?"null":"scalar";if(a.name==="literal")n=a.children.StringLiteral||a.children.TextBlock?"string":a.children.Null?"null":"scalar";else if(a.name==="referenceTypeCastExpression"){if(E(b(a,"referenceType")[0]).map(v=>v.image).join(".")!=="java.lang.String")throw new Error("Java evaluation supports only primitive and fully qualified java.lang.String casts.");n="string"}else if(a.name==="primitiveCastExpression")n="scalar";else if(a.name==="primary"){let p=b(a,"primaryPrefix")[0],v=b(p,"fqnOrRefType")[0],g=b(a,"primarySuffix"),I=0;if(v){let r=E(v).map(c=>c.image),l=!!g[0]?.children.methodInvocationSuffix,u=i.get(r[0]);if(u){if(u.unavailable!==void 0)throw new Error(`Java evaluation cannot use ${u.name}: ${u.unavailable}`);if(!N.has(u.type)&&u.type!=="String"&&u.type!=="java.lang.String")throw new Error(`Java evaluation cannot use ${u.name} (${u.type}); inspect this target reference in Variables.`);if(s.add(u.name),n=N.has(u.type)?"scalar":"string",r.length!==1||l){if(r.length!==2||!l||n!=="string"||!j.has(r[1]))throw new Error("Java evaluation cannot call target methods or access target fields.");n=x.has(r[1])?"string":"scalar",I=1}}else{let c=r.slice(2);if(r[0]!=="java"||r[1]!=="lang"||c.length!==2||(l?!Object.hasOwn(T,c[0])||!T[c[0]].has(c[1]):!Object.hasOwn(A,c[0])||!A[c[0]].has(c[1])))throw new Error(`Java evaluation cannot resolve ${r.join(".")}; use scalar/String locals or fully qualified java.lang library calls/constants.`);n=l&&x.has(c[1])?"string":"scalar",I=l?1:0}}for(let r=I;r<g.length;r+=2){let l=L(g[r],"Identifier")[0]?.image;if(n!=="string"||!l||!j.has(l)||!g[r+1]?.children.methodInvocationSuffix)throw new Error("Java evaluation supports only approved String methods on expression results.");n=x.has(l)?"string":"scalar"}}else if(a.name==="binaryExpression"){let p=b(a,"unaryExpression").map(h),v=L(a,"BinaryOperator");for(let[g,I]of v.entries()){let r=[g,g+1].some(l=>p[l]==="null"&&v[l-1]?.image!=="+"&&v[l]?.image!=="+");if(["==","!="].includes(I.image)&&(p[g]==="string"||p[g+1]==="string")&&!r)throw new Error("Java snapshot evaluation cannot compare String reference identity; use equals() for String contents.")}v.some(g=>["==","!=","<",">","<=",">=","&&","||"].includes(g.image))&&(n="scalar")}return d.set(a,n),n},"visit");return h(f),s}m(M,"validateExpression");function $(t){if(typeof t.expression!="string"||!t.expression.trim()||new TextEncoder().encode(t.expression).length>4096)throw new Error("Java expressions must contain 1\u20134096 UTF-8 bytes.");if(!Array.isArray(t.bindings)||t.bindings.length>1024)throw new Error("Java evaluation supports at most 1024 local bindings.");let i=new Map;for(let e of t.bindings){if(!e||typeof e.name!="string"||typeof e.type!="string"||e.value!==null&&typeof e.value!="string"||e.unavailable!==void 0&&typeof e.unavailable!="string")throw new Error("Invalid Java evaluation binding.");let n=y(e.name,"expression");if(n.tokens.length!==1||E(n.cst)[0]?.image!==e.name||i.has(e.name)||/\\/.test(e.name))throw new Error(`Invalid or duplicate Java local name: ${e.name}`);i.set(e.name,{...e})}let s=M(t.expression,i),f=0,o="WasmIdleEval";for(;t.expression.includes(o)||[...i.keys()].some(e=>e.includes(o));)o=`WasmIdleEval_${++f}`;let S=`${o}_args`,d=[],h=[],a={byte:"java.lang.Byte.parseByte(value)",short:"java.lang.Short.parseShort(value)",int:"java.lang.Integer.parseInt(value)",long:"java.lang.Long.parseLong(value)",float:'value.equals("NaN") ? java.lang.Float.NaN : value.equals("Infinity") ? java.lang.Float.POSITIVE_INFINITY : value.equals("-Infinity") ? java.lang.Float.NEGATIVE_INFINITY : value.equals("-0.0") ? java.lang.Float.intBitsToFloat(java.lang.Integer.MIN_VALUE) : java.lang.Float.parseFloat(value)',double:'value.equals("NaN") ? java.lang.Double.NaN : value.equals("Infinity") ? java.lang.Double.POSITIVE_INFINITY : value.equals("-Infinity") ? java.lang.Double.NEGATIVE_INFINITY : value.equals("-0.0") ? java.lang.Double.longBitsToDouble(java.lang.Long.MIN_VALUE) : java.lang.Double.parseDouble(value)',boolean:"java.lang.Boolean.parseBoolean(value)",char:"(char) java.lang.Integer.parseInt(value)"},w=0;for(let e of i.values()){if(!s.has(e.name))continue;if(w+=new TextEncoder().encode(e.value??"").length,w>65536)throw new Error("Java evaluation binding values exceed 65536 UTF-8 bytes.");let n=d.length;if(N.has(e.type)){if(e.value===null||e.type==="char"&&(!/^\d{1,5}$/.test(e.value)||Number(e.value)>65535)||e.type==="boolean"&&!["true","false"].includes(e.value))throw new Error(`Invalid ${e.type} value for Java local ${e.name}.`);d.push(e.value),h.push(`final ${e.type} ${e.name} = ${o}_${e.type}(${S}[${n}]);`)}else(e.type==="String"||e.type==="java.lang.String")&&(d.push(e.value===null?"1":"0",e.value??""),h.push(`final java.lang.String ${e.name} = ${S}[${n}].equals("1") ? null : ${S}[${n+1}];`))}return{args:d,code:`public final class ${o} {
3
+ ${Object.entries(a).map(([e,n])=>` private static ${e} ${o}_${e}(java.lang.String value) { return ${n}; }`).join(`
4
+ `)}
5
+ ${String.raw` private static java.lang.String ${o}_quote(java.lang.String value) {
6
+ java.lang.StringBuilder result = new java.lang.StringBuilder("\"");
7
+ for (int i = 0; i < value.length(); i++) {
8
+ char ch = value.charAt(i);
9
+ switch (ch) {
10
+ case '"': result.append("\\\""); break;
11
+ case '\\': result.append("\\\\"); break;
12
+ case '\b': result.append("\\b"); break;
13
+ case '\f': result.append("\\f"); break;
14
+ case '\n': result.append("\\n"); break;
15
+ case '\r': result.append("\\r"); break;
16
+ case '\t': result.append("\\t"); break;
17
+ default:
18
+ if (ch < 32 || java.lang.Character.isSurrogate(ch)) {
19
+ java.lang.String hex = java.lang.Integer.toHexString(ch);
20
+ result.append("\\u");
21
+ for (int pad = hex.length(); pad < 4; pad++) result.append('0');
22
+ result.append(hex);
23
+ } else result.append(ch);
24
+ }
25
+ }
26
+ return result.append('"').toString();
27
+ }`}
28
+ private static void ${o}_print(java.lang.Object value) {
29
+ if (value != null && !(value instanceof java.lang.String) && !(value instanceof java.lang.Number)
30
+ && !(value instanceof java.lang.Boolean) && !(value instanceof java.lang.Character))
31
+ throw new java.lang.IllegalArgumentException("Java evaluation result is not a scalar or String.");
32
+ java.lang.String text = java.lang.String.valueOf(value);
33
+ if (value instanceof java.lang.String || value instanceof java.lang.Character) text = ${o}_quote(text);
34
+ if (text.length() > 16384) throw new java.lang.IllegalArgumentException("Java evaluation output exceeds 16384 characters.");
35
+ java.lang.System.out.print(text);
36
+ }
37
+ public static void main(java.lang.String[] ${S}) {
38
+ ${h.map(e=>` ${e}`).join(`
39
+ `)}
40
+ ${o}_print((${t.expression}
41
+ ));
42
+ }
43
+ }
44
+ `}}m($,"buildJavaDebugEvaluationProgram");export{$ as buildJavaDebugEvaluationProgram};
@@ -0,0 +1,24 @@
1
+ import type { DebugSessionEvent, DebugSourceBreakpoints } from '../options';
2
+ import type { JavaDebugLocation } from '../javaDebugSource';
3
+ export interface JavaDebugFile {
4
+ path: string;
5
+ sourceContentSha256: string;
6
+ lineCount: number;
7
+ locations: JavaDebugLocation[];
8
+ }
9
+ export declare function createJavaDebugRuntime(files: JavaDebugFile[], options: {
10
+ activePath: string;
11
+ debugPath?: string;
12
+ breakpoints: number[];
13
+ sourceBreakpoints?: DebugSourceBreakpoints[];
14
+ pauseOnEntry: boolean;
15
+ }, emit: (event: DebugSessionEvent, stopId?: number) => void, read: (blocking: boolean) => string | null, respond?: (response: {
16
+ id: number;
17
+ stopId: number;
18
+ value?: unknown;
19
+ error?: string;
20
+ }) => void): {
21
+ poll(source: string, line: number, _column: number): {} | null;
22
+ pause(source: string, line: number, column: number, serialized: string, rawDepth: number, serializedVariables?: string, totalVariables?: number): Record<string, unknown> | null;
23
+ reply(id: number, stopId: number, serialized: string | null, error: string | null): Record<string, unknown> | null;
24
+ };