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
@@ -0,0 +1,315 @@
1
+ export function createJavaDebugRuntime(files, options, emit, read, respond = () => { }) {
2
+ const sources = new Map(files.map((file) => [file.path, file]));
3
+ const sourcePrefix = options.debugPath?.endsWith(`/${options.activePath}`)
4
+ ? options.debugPath.slice(0, -options.activePath.length)
5
+ : '';
6
+ const displayPath = (path) => path === options.activePath ? options.debugPath || path : `${sourcePrefix}${path}`;
7
+ const breakpoints = new Map();
8
+ let mode = options.pauseOnEntry ? 'entry' : 'continue';
9
+ let targetDepth = 0;
10
+ let targetSource = '';
11
+ let targetLine = 0;
12
+ let targetColumn = 0;
13
+ let pauseRequested = false;
14
+ let stop = 0;
15
+ let pausedFrameId;
16
+ let pausedScope;
17
+ let pendingInspection;
18
+ const references = new Set();
19
+ const referenceBase = () => stop * 100_000 + 1;
20
+ const variablePage = (value) => {
21
+ if (!Array.isArray(value) || value.length > 1000)
22
+ throw new Error('Invalid Java variable response');
23
+ return value.map((item) => {
24
+ if (!item ||
25
+ typeof item.name !== 'string' ||
26
+ typeof item.value !== 'string' ||
27
+ typeof item.type !== 'string' ||
28
+ !Number.isSafeInteger(item.variablesReference) ||
29
+ item.variablesReference < 0 ||
30
+ item.variablesReference > 4096 ||
31
+ (item.indexedVariables !== undefined &&
32
+ (!Number.isSafeInteger(item.indexedVariables) || item.indexedVariables < 0)))
33
+ throw new Error('Invalid Java variable descriptor');
34
+ const reference = item.variablesReference
35
+ ? referenceBase() + item.variablesReference
36
+ : 0;
37
+ if (reference)
38
+ references.add(reference);
39
+ return {
40
+ name: item.name,
41
+ value: item.value,
42
+ type: item.type,
43
+ variablesReference: reference,
44
+ ...(item.indexedVariables !== undefined
45
+ ? { indexedVariables: item.indexedVariables }
46
+ : {})
47
+ };
48
+ });
49
+ };
50
+ const setBreakpoints = (sourcePath, lines) => {
51
+ if (!Array.isArray(lines) ||
52
+ lines.length > 1024 ||
53
+ lines.some((line) => !Number.isSafeInteger(line) || line < 1))
54
+ throw new Error('Invalid Java breakpoint lines');
55
+ const file = files.find((file) => displayPath(file.path) === sourcePath);
56
+ const executable = [
57
+ ...new Set(file?.locations.map((location) => location.line) ?? [])
58
+ ].sort((a, b) => a - b);
59
+ const resolved = [...new Set(lines)].map((requestedLine) => {
60
+ const line = executable.find((line) => line >= requestedLine);
61
+ return {
62
+ requestedLine,
63
+ line: line ?? requestedLine,
64
+ verified: line !== undefined,
65
+ ...(line === undefined
66
+ ? { message: 'No instrumented Java statement at or after this line' }
67
+ : {})
68
+ };
69
+ });
70
+ breakpoints.set(sourcePath, new Set(resolved.filter((item) => item.verified).map((item) => item.line)));
71
+ emit({
72
+ type: 'breakpoints',
73
+ sourcePath,
74
+ sourceContentSha256: file?.sourceContentSha256,
75
+ breakpoints: resolved
76
+ });
77
+ };
78
+ const command = (blocking) => {
79
+ const raw = read(blocking);
80
+ if (raw === null)
81
+ throw new Error('Java debugger stopped');
82
+ if (!raw)
83
+ return null;
84
+ return JSON.parse(raw);
85
+ };
86
+ const update = (item) => {
87
+ if (item.op === 'breakpoints')
88
+ setBreakpoints(item.sourcePath, item.lines);
89
+ else if (item.op === 'pause')
90
+ pauseRequested = true;
91
+ };
92
+ const requestError = (item, message) => {
93
+ if (Number.isSafeInteger(item.id) && item.id > 0 && Number.isSafeInteger(item.stopId))
94
+ respond({ id: item.id, stopId: item.stopId, error: message });
95
+ };
96
+ const readPaused = () => {
97
+ for (;;) {
98
+ const item = command(true);
99
+ if (!item)
100
+ continue;
101
+ if (item.op === 'control') {
102
+ if (!['continue', 'stepInto', 'nextLine', 'stepOut'].includes(item.command))
103
+ throw new Error('Invalid Java debugger control');
104
+ mode = item.command;
105
+ pausedFrameId = undefined;
106
+ pausedScope = undefined;
107
+ references.clear();
108
+ pendingInspection = undefined;
109
+ emit({ type: 'resume', command: mode });
110
+ return null;
111
+ }
112
+ if (item.op === 'breakpoints' || item.op === 'pause') {
113
+ update(item);
114
+ continue;
115
+ }
116
+ if (!Number.isSafeInteger(item.id) ||
117
+ item.id < 1 ||
118
+ item.id > 2_147_483_647 ||
119
+ item.stopId !== stop) {
120
+ requestError(item, 'Java inspection request belongs to an earlier stop');
121
+ continue;
122
+ }
123
+ if (item.op === 'scopes') {
124
+ respond({
125
+ id: item.id,
126
+ stopId: stop,
127
+ value: item.frameId === pausedFrameId && pausedScope ? [pausedScope] : []
128
+ });
129
+ continue;
130
+ }
131
+ if (item.op === 'context') {
132
+ if (item.frameId !== pausedFrameId) {
133
+ requestError(item, 'Java values are available only for the currently stopped frame');
134
+ continue;
135
+ }
136
+ pendingInspection = { id: item.id, stopId: stop, op: item.op };
137
+ return { op: item.op, id: item.id, stopId: stop };
138
+ }
139
+ if (item.op === 'variables') {
140
+ const { reference, start = 0, count = 50 } = item;
141
+ if (!references.has(reference) ||
142
+ !Number.isSafeInteger(start) ||
143
+ start < 0 ||
144
+ !Number.isSafeInteger(count) ||
145
+ count < 0 ||
146
+ count > 1000) {
147
+ requestError(item, 'Invalid or stale Java variable page');
148
+ continue;
149
+ }
150
+ pendingInspection = { id: item.id, stopId: stop, op: item.op };
151
+ return {
152
+ op: item.op,
153
+ id: item.id,
154
+ stopId: stop,
155
+ reference: reference - referenceBase(),
156
+ start,
157
+ count
158
+ };
159
+ }
160
+ requestError(item, 'Unsupported Java inspection request');
161
+ }
162
+ };
163
+ setBreakpoints(displayPath(options.activePath), options.breakpoints);
164
+ for (const source of options.sourceBreakpoints ?? [])
165
+ setBreakpoints(source.sourcePath, source.lines);
166
+ return {
167
+ poll(source, line, _column) {
168
+ if (!sources.has(source))
169
+ throw new Error('Unknown Java debugger source');
170
+ for (let item; (item = command(false));) {
171
+ if (item.op === 'breakpoints' || item.op === 'pause')
172
+ update(item);
173
+ else
174
+ requestError(item, 'Java inspection requires a paused frame');
175
+ }
176
+ return pauseRequested ||
177
+ mode !== 'continue' ||
178
+ breakpoints.get(displayPath(source))?.has(line)
179
+ ? {}
180
+ : null;
181
+ },
182
+ pause(source, line, column, serialized, rawDepth, serializedVariables = '[]', totalVariables = 0) {
183
+ if (serialized.length > 1_000_000 || !Number.isSafeInteger(rawDepth) || rawDepth < 1)
184
+ throw new Error('Invalid Java debugger stack');
185
+ const raw = JSON.parse(serialized);
186
+ if (!Array.isArray(raw) || raw.length > 64)
187
+ throw new Error('Invalid Java debugger stack');
188
+ const frames = [];
189
+ for (const frame of raw) {
190
+ if (!Array.isArray(frame) ||
191
+ frame.length !== 4 ||
192
+ typeof frame[0] !== 'string' ||
193
+ typeof frame[1] !== 'string' ||
194
+ typeof frame[2] !== 'string' ||
195
+ !Number.isSafeInteger(frame[3]))
196
+ continue;
197
+ const packagePath = frame[0]
198
+ .slice(0, Math.max(0, frame[0].lastIndexOf('.')))
199
+ .replaceAll('.', '/');
200
+ const relativePath = packagePath ? `${packagePath}/${frame[2]}` : frame[2];
201
+ const candidates = files.filter((file) => file.path.split('/').pop() === frame[2]);
202
+ const exact = candidates.filter((file) => file.path === relativePath || file.path.endsWith(`/${relativePath}`));
203
+ const file = exact.length === 1
204
+ ? exact[0]
205
+ : candidates.length === 1
206
+ ? candidates[0]
207
+ : undefined;
208
+ if (!file || frame[3] < 1 || frame[3] > file.lineCount)
209
+ continue;
210
+ frames.push({
211
+ functionName: `${frame[0]}.${frame[1]}`,
212
+ line: frame[3],
213
+ sourcePath: displayPath(file.path),
214
+ sourceContentSha256: file.sourceContentSha256
215
+ });
216
+ }
217
+ const top = frames[0];
218
+ if (!top || top.sourcePath !== displayPath(source))
219
+ throw new Error('The Java runtime could not provide the current source stack');
220
+ const breakpoint = breakpoints.get(displayPath(source))?.has(line) === true;
221
+ const progressed = source !== targetSource ||
222
+ line !== targetLine ||
223
+ rawDepth !== targetDepth ||
224
+ column === targetColumn;
225
+ const stepping = mode === 'entry' ||
226
+ (mode === 'stepInto' && progressed) ||
227
+ (mode === 'nextLine' && rawDepth <= targetDepth && progressed) ||
228
+ (mode === 'stepOut' && rawDepth < targetDepth);
229
+ if (!pauseRequested && !breakpoint && !stepping)
230
+ return null;
231
+ const reason = pauseRequested
232
+ ? 'pause'
233
+ : breakpoint
234
+ ? 'breakpoint'
235
+ : mode === 'entry'
236
+ ? 'entry'
237
+ : mode === 'stepInto'
238
+ ? 'step'
239
+ : mode === 'stepOut'
240
+ ? 'stepOut'
241
+ : 'nextLine';
242
+ pauseRequested = false;
243
+ stop++;
244
+ if (stop > 2_147_483_647 ||
245
+ serializedVariables.length > 1_000_000 ||
246
+ !Number.isSafeInteger(totalVariables) ||
247
+ totalVariables < 0 ||
248
+ totalVariables > 1024)
249
+ throw new Error('Invalid Java local snapshot');
250
+ references.clear();
251
+ pendingInspection = undefined;
252
+ const locals = variablePage(JSON.parse(serializedVariables));
253
+ frames.forEach((frame, index) => {
254
+ frame.id = stop * 100 + index + 1;
255
+ });
256
+ top.line = line;
257
+ top.column = column;
258
+ pausedFrameId = top.id;
259
+ pausedScope = {
260
+ name: 'Locals',
261
+ variablesReference: referenceBase(),
262
+ namedVariables: totalVariables,
263
+ expensive: false,
264
+ variables: locals
265
+ };
266
+ references.add(referenceBase());
267
+ targetDepth = rawDepth;
268
+ targetSource = source;
269
+ targetLine = line;
270
+ targetColumn = column;
271
+ emit({
272
+ type: 'pause',
273
+ reason,
274
+ line,
275
+ sourcePath: top.sourcePath,
276
+ sourceContentSha256: top.sourceContentSha256,
277
+ frameId: top.id,
278
+ threadId: 1,
279
+ locals,
280
+ scopes: [pausedScope],
281
+ callStack: frames,
282
+ capabilities: { readMemory: false, writeMemory: false, dataBreakpoints: false }
283
+ }, stop);
284
+ return readPaused();
285
+ },
286
+ reply(id, stopId, serialized, error) {
287
+ const inspection = pendingInspection;
288
+ if (!inspection || inspection.id !== id || inspection.stopId !== stopId || !pausedScope)
289
+ throw new Error('Java inspection reply belongs to an earlier request');
290
+ pendingInspection = undefined;
291
+ try {
292
+ if (error)
293
+ respond({ id, stopId, error });
294
+ else {
295
+ if (typeof serialized !== 'string' || serialized.length > 1_000_000)
296
+ throw new Error('Invalid Java inspection response');
297
+ const value = JSON.parse(serialized);
298
+ respond({
299
+ id,
300
+ stopId,
301
+ value: inspection.op === 'variables' ? variablePage(value) : value
302
+ });
303
+ }
304
+ }
305
+ catch (failure) {
306
+ respond({
307
+ id,
308
+ stopId,
309
+ error: failure instanceof Error ? failure.message : 'Unable to inspect Java values'
310
+ });
311
+ }
312
+ return readPaused();
313
+ }
314
+ };
315
+ }
@@ -0,0 +1,11 @@
1
+ /** Bound output while synchronous Wasm owns the worker, including newline-free output. */
2
+ export declare function createJavaOutput(emit: (text: string) => void, options?: {
3
+ maxChars?: number;
4
+ maxDelayMs?: number;
5
+ now?: () => number;
6
+ }): {
7
+ write(charCode: number): void;
8
+ flush: () => void;
9
+ flushIfDue(): void;
10
+ close(): void;
11
+ };
@@ -0,0 +1,54 @@
1
+ /** Bound output while synchronous Wasm owns the worker, including newline-free output. */
2
+ export function createJavaOutput(emit, options = {}) {
3
+ const maxChars = options.maxChars ?? 16384;
4
+ const maxDelayMs = options.maxDelayMs ?? 16;
5
+ const now = options.now ?? (() => performance.now());
6
+ if (!Number.isSafeInteger(maxChars) ||
7
+ maxChars < 2 ||
8
+ !Number.isFinite(maxDelayMs) ||
9
+ maxDelayMs < 0)
10
+ throw new RangeError('Invalid Java output batch limits');
11
+ let text = '';
12
+ let hasEmitted = false;
13
+ let lastFlush = now();
14
+ let timer;
15
+ let closed = false;
16
+ function flush() {
17
+ if (timer !== undefined)
18
+ clearTimeout(timer);
19
+ timer = undefined;
20
+ if (!text)
21
+ return;
22
+ const output = text;
23
+ text = '';
24
+ hasEmitted = true;
25
+ lastFlush = now();
26
+ emit(output);
27
+ }
28
+ return {
29
+ write(charCode) {
30
+ if (closed)
31
+ return;
32
+ // A high surrogate is held until the next code unit, so output accounting
33
+ // does not encode a valid pair as two replacement characters.
34
+ if (text.length >= maxChars - 1 && !(charCode >= 0xdc00 && charCode <= 0xdfff))
35
+ flush();
36
+ text += String.fromCharCode(charCode);
37
+ if (charCode >= 0xd800 && charCode <= 0xdbff)
38
+ return;
39
+ if (text.length >= maxChars || !hasEmitted || now() - lastFlush >= maxDelayMs)
40
+ flush();
41
+ else if (timer === undefined)
42
+ timer = setTimeout(flush, maxDelayMs);
43
+ },
44
+ flush,
45
+ flushIfDue() {
46
+ if (text && now() - lastFlush >= maxDelayMs)
47
+ flush();
48
+ },
49
+ close() {
50
+ flush();
51
+ closed = true;
52
+ }
53
+ };
54
+ }
@@ -1,4 +1,5 @@
1
1
  import { waitForBufferedStdin } from '../stdinBuffer';
2
+ import { readLuaDebugCommand } from '../luaDebug';
2
3
  import { buildFennelCompileChunk, buildFennelRunChunk, loadFennelCompilerSource, parseFennelDiagnostic, stripHostLuaTraceback } from '../fennelBootstrap';
3
4
  let stdinBufferLua = null;
4
5
  let moduleUrl = '';
@@ -138,8 +139,20 @@ self.onmessage = async (event) => {
138
139
  }
139
140
  const hasInitialStdin = typeof stdin === 'string';
140
141
  let initialStdin = hasInitialStdin ? stdin : null;
142
+ if (event.data.debug && fennelSource)
143
+ throw new Error('Fennel source debugging is not supported.');
141
144
  const execution = await runtime.executeBrowserLuaArtifact(compiledArtifact, {
142
145
  args,
146
+ ...(event.data.debug
147
+ ? {
148
+ debug: {
149
+ breakpoints: event.data.breakpoints ?? [],
150
+ pauseOnEntry: event.data.pauseOnEntry !== false,
151
+ readCommand: (blocking) => readLuaDebugCommand(event.data.debugBuffer, blocking, () => postMessage({ debugCommandConsumed: true })),
152
+ onEvent: (debugEvent) => postMessage({ luaDebug: debugEvent })
153
+ }
154
+ }
155
+ : {}),
143
156
  onReady: () => postMessage({
144
157
  progress: {
145
158
  kind: 'ready',
@@ -4,6 +4,7 @@ import { parsePythonPackageLock } from '../pythonPackageLock';
4
4
  import { WASM_APECODE_VERSION, WASM_APECODE_WHEELS } from '../wasmApecodeVersion';
5
5
  import { withCachedPyodideModule } from './runtimeModule';
6
6
  import { createPythonExecutionHelpers } from './pythonExecution';
7
+ import { compilePythonBytecode } from './pythonCompile';
7
8
  import { createPythonWorkspaceImports } from './pythonWorkspaceImports';
8
9
  import { createPythonWorkspaceFiles } from './pythonWorkspaceFiles';
9
10
  import { PYTHON_DEBUG_PREVIEW } from './pythonDebugPreview';
@@ -28,6 +29,7 @@ let installedApecodeVersion;
28
29
  let executionHelpers;
29
30
  let invalidateWorkspaceImports;
30
31
  let syncWorkspaceFiles;
32
+ let debugPauseSequence = 0;
31
33
  let installPythonFlushHooks;
32
34
  const PYTHON_EXTENSIONS = {
33
35
  hy: {
@@ -373,7 +375,9 @@ function normalizeWorkspacePath(path) {
373
375
  function writeWorkspaceFiles(files = [], syncPythonWorkspace = false) {
374
376
  const fs = pyodide.FS;
375
377
  if (syncPythonWorkspace) {
376
- const normalized = files.map((file) => ({ ...file, path: normalizeWorkspacePath(file.path) })).filter((file) => file.path);
378
+ const normalized = files
379
+ .map((file) => ({ ...file, path: normalizeWorkspacePath(file.path) }))
380
+ .filter((file) => file.path);
377
381
  invalidateWorkspaceImports ??= createPythonWorkspaceImports(pyodide);
378
382
  invalidateWorkspaceImports(normalized.map((file) => file.path));
379
383
  syncWorkspaceFiles ??= createPythonWorkspaceFiles(fs);
@@ -488,7 +492,7 @@ None
488
492
  self.onmessage = async (event) => {
489
493
  if (handleWorkerAssetMessage(event.data))
490
494
  return;
491
- const { code, buffer, debugBuffer, watchBuffer, watchResultBuffer, load, interrupt, assets, prepare, stdin, debug = false, breakpoints = [], pauseOnEntry = false, activePath, debugPath, workspaceFiles, language = 'python', extension } = event.data;
495
+ const { code, buffer, debugBuffer, watchBuffer, watchResultBuffer, load, interrupt, assets, compile, fileName, optimize, invalidationMode, timestamp, maxArtifactBytes, prepare, stdin, debug = false, breakpoints = [], pauseOnEntry = false, activePath, debugPath, workspaceFiles, language = 'python', extension } = event.data;
492
496
  const isHy = language === 'hy';
493
497
  const isAheui = language === 'aheui';
494
498
  const isApecode = language === 'apecode';
@@ -519,6 +523,28 @@ self.onmessage = async (event) => {
519
523
  self.postMessage({ error: e.message || 'Unknown error' });
520
524
  }
521
525
  }
526
+ else if (compile) {
527
+ try {
528
+ if (language !== 'python')
529
+ throw new Error('Bytecode compilation is supported only for Python');
530
+ await loadPyodide(baseUrl);
531
+ postProgress(10, 'Compiling Python bytecode');
532
+ const compiled = compilePythonBytecode(pyodide, code, fileName, optimize, maxArtifactBytes, {
533
+ invalidationMode,
534
+ timestamp
535
+ });
536
+ postProgress(100, 'Python bytecode ready');
537
+ self.postMessage({ compiled }, [compiled.data.buffer]);
538
+ }
539
+ catch (e) {
540
+ self.postMessage({
541
+ error: e.message || 'Unknown error',
542
+ ...(e.code === 'output-limit'
543
+ ? { outputLimit: { actual: e.actual, limit: e.limit } }
544
+ : {})
545
+ });
546
+ }
547
+ }
522
548
  else if (prepare) {
523
549
  preparedPackagesKey = undefined;
524
550
  try {
@@ -643,6 +669,7 @@ self.onmessage = async (event) => {
643
669
  const debugReadWatchName = `__wasm_idle_python_debug_watch_read_${ts}`;
644
670
  const debugWriteWatchName = `__wasm_idle_python_debug_watch_write_${ts}`;
645
671
  const debugReadBreakpointsName = `__wasm_idle_python_debug_breakpoints_${ts}`;
672
+ const debugBreakpointStateName = `__wasm_idle_python_debug_breakpoint_state_${ts}`;
646
673
  const executionReadyName = `__wasm_idle_python_execution_ready_${ts}`;
647
674
  let executionReadyReported = false;
648
675
  self[executionReadyName] = () => {
@@ -681,9 +708,19 @@ self.onmessage = async (event) => {
681
708
  line: Number(line),
682
709
  reason,
683
710
  locals,
684
- callStack
711
+ callStack,
712
+ scopes: [
713
+ {
714
+ name: 'Locals',
715
+ presentationHint: 'locals',
716
+ variablesReference: ++debugPauseSequence,
717
+ expensive: false,
718
+ variables: locals
719
+ }
720
+ ]
685
721
  }
686
722
  });
723
+ return debugPauseSequence;
687
724
  };
688
725
  self[debugWaitName] = () => {
689
726
  const sequence = Atomics.load(debugBufferPyodide, 0);
@@ -715,6 +752,13 @@ self.onmessage = async (event) => {
715
752
  }
716
753
  return JSON.stringify({ version, lines });
717
754
  };
755
+ // Preserve an atomic check on every traced line, but avoid a Python-to-JS
756
+ // function call/null conversion unless a new breakpoint snapshot exists.
757
+ self[debugBreakpointStateName] = {
758
+ get version() {
759
+ return Atomics.load(debugBufferPyodide, 2);
760
+ }
761
+ };
718
762
  const executionFilename = normalizeWorkspacePath(activePath || '') ||
719
763
  (isHy ? '__wasm_idle_user__.hy' : '__wasm_idle_user__.py');
720
764
  const debugFilename = normalizeWorkspacePath(debugPath || '') || executionFilename;
@@ -748,6 +792,7 @@ from js import ${executionReadyName} as __wasm_idle_execution_ready
748
792
  ${debug ? `from js import ${debugPauseName}, ${debugWaitName}` : ''}
749
793
  ${debug ? `from js import ${debugReadWatchName}, ${debugWriteWatchName}` : ''}
750
794
  ${debug ? `from js import ${debugReadBreakpointsName}` : ''}
795
+ ${debug ? `from js import ${debugBreakpointStateName} as __wasm_idle_debug_breakpoint_state` : ''}
751
796
 
752
797
  ${imageHook}
753
798
 
@@ -765,14 +810,14 @@ __wasm_idle_debug_breakpoints = set(${normalizedBreakpoints})
765
810
  __wasm_idle_debug_breakpoint_version = -1
766
811
  __wasm_idle_debug_pause_on_entry = ${pauseOnEntry ? 'True' : 'False'}
767
812
  __wasm_idle_debug_step_mode = None
768
- __wasm_idle_debug_resume_skip = None
769
813
  __wasm_idle_debug_next_depth = None
770
- __wasm_idle_debug_next_line = None
771
814
  __wasm_idle_debug_step_out_depth = None
772
815
 
773
816
  def __wasm_idle_debug_refresh_breakpoints():
774
817
  global __wasm_idle_debug_breakpoints
775
818
  global __wasm_idle_debug_breakpoint_version
819
+ if __wasm_idle_debug_breakpoint_state.version == __wasm_idle_debug_breakpoint_version:
820
+ return
776
821
  payload = ${debugReadBreakpointsName}(__wasm_idle_debug_breakpoint_version)
777
822
  # JavaScript null crosses Pyodide as JsNull rather than Python None.
778
823
  if not isinstance(payload, str):
@@ -795,13 +840,22 @@ def __wasm_idle_debug_depth(frame):
795
840
 
796
841
  ${PYTHON_DEBUG_PREVIEW}
797
842
 
798
- def __wasm_idle_debug_locals(frame):
843
+ def __wasm_idle_debug_locals(frame, start=0, count=50):
799
844
  locals_preview = []
845
+ index = 0
800
846
  for name, value in frame.f_locals.items():
801
847
  if name == "__builtins__" or name.startswith("__wasm_idle_") or name.startswith("."):
802
848
  continue
803
- locals_preview.append({"name": name, "value": __wasm_idle_debug_preview(value)})
804
- locals_preview.sort(key = lambda item: item["name"])
849
+ if index >= start:
850
+ preview = __wasm_idle_debug_preview(value)
851
+ if len(preview) > 200:
852
+ preview = preview[:197] + "..."
853
+ suffix = "… [" + str(index) + "]"
854
+ display_name = name if len(name) <= 256 else name[:256-len(suffix)] + suffix
855
+ locals_preview.append({"name": display_name, "value": preview})
856
+ if len(locals_preview) >= count:
857
+ break
858
+ index += 1
805
859
  return locals_preview
806
860
 
807
861
  def __wasm_idle_debug_stack(frame):
@@ -816,9 +870,7 @@ def __wasm_idle_debug_stack(frame):
816
870
  def __wasm_idle_debug_trace(frame, event, arg):
817
871
  global __wasm_idle_debug_pause_on_entry
818
872
  global __wasm_idle_debug_step_mode
819
- global __wasm_idle_debug_resume_skip
820
873
  global __wasm_idle_debug_next_depth
821
- global __wasm_idle_debug_next_line
822
874
  global __wasm_idle_debug_step_out_depth
823
875
 
824
876
  if frame.f_code.co_filename not in __wasm_idle_debug_source_filenames:
@@ -827,13 +879,11 @@ def __wasm_idle_debug_trace(frame, event, arg):
827
879
  return __wasm_idle_debug_trace
828
880
 
829
881
  __wasm_idle_debug_refresh_breakpoints()
830
- needs_depth = (__wasm_idle_debug_resume_skip is not None or __wasm_idle_debug_step_mode in ("next", "out"))
882
+ # Returning from a trace callback executes this event; a later event on the same
883
+ # line is another loop iteration, not a replay of the previous stop.
884
+ needs_depth = __wasm_idle_debug_step_mode in ("next", "out")
831
885
  depth = __wasm_idle_debug_depth(frame) if needs_depth else None
832
886
  line = frame.f_lineno
833
- if __wasm_idle_debug_resume_skip == (depth, line):
834
- return __wasm_idle_debug_trace
835
- if __wasm_idle_debug_resume_skip is not None:
836
- __wasm_idle_debug_resume_skip = None
837
887
 
838
888
  reason = None
839
889
  if __wasm_idle_debug_pause_on_entry:
@@ -842,7 +892,7 @@ def __wasm_idle_debug_trace(frame, event, arg):
842
892
  reason = "breakpoint"
843
893
  elif __wasm_idle_debug_step_mode == "step":
844
894
  reason = "step"
845
- elif __wasm_idle_debug_step_mode == "next" and __wasm_idle_debug_next_depth is not None and depth <= __wasm_idle_debug_next_depth and line != __wasm_idle_debug_next_line:
895
+ elif __wasm_idle_debug_step_mode == "next" and __wasm_idle_debug_next_depth is not None and depth <= __wasm_idle_debug_next_depth:
846
896
  reason = "nextLine"
847
897
  elif __wasm_idle_debug_step_mode == "out" and __wasm_idle_debug_step_out_depth is not None and depth <= __wasm_idle_debug_step_out_depth:
848
898
  reason = "stepOut"
@@ -855,16 +905,25 @@ def __wasm_idle_debug_trace(frame, event, arg):
855
905
  __wasm_idle_debug_pause_on_entry = False
856
906
  __wasm_idle_debug_step_mode = None
857
907
  __wasm_idle_debug_next_depth = None
858
- __wasm_idle_debug_next_line = None
859
908
  __wasm_idle_debug_step_out_depth = None
860
909
 
861
910
  sys.stdout.flush()
862
911
  sys.stderr.flush()
863
- ${debugPauseName}(line, reason, json.dumps(__wasm_idle_debug_locals(frame)), json.dumps(__wasm_idle_debug_stack(frame)))
912
+ pause_reference = ${debugPauseName}(line, reason, json.dumps(__wasm_idle_debug_locals(frame)), json.dumps(__wasm_idle_debug_stack(frame)))
864
913
  while True:
865
914
  command = ${debugWaitName}()
866
915
  if command < 0:
867
916
  raise KeyboardInterrupt()
917
+ if command == 6:
918
+ try:
919
+ request = json.loads(${debugReadWatchName}())
920
+ start = max(0, int(request.get("start", 0)))
921
+ count = max(1, min(50, int(request.get("count", 50))))
922
+ page = __wasm_idle_debug_locals(frame, start, count) if request.get("reference") == pause_reference else []
923
+ ${debugWriteWatchName}(json.dumps(page))
924
+ except Exception:
925
+ ${debugWriteWatchName}("[]")
926
+ continue
868
927
  if command != 5:
869
928
  break
870
929
  try:
@@ -873,13 +932,11 @@ def __wasm_idle_debug_trace(frame, event, arg):
873
932
  except Exception as error:
874
933
  result = "?" if error.__class__.__name__ == "NameError" else "error"
875
934
  ${debugWriteWatchName}(result)
876
- __wasm_idle_debug_resume_skip = (depth, line)
877
935
  if command == 2:
878
936
  __wasm_idle_debug_step_mode = "step"
879
937
  elif command == 3:
880
938
  __wasm_idle_debug_step_mode = "next"
881
939
  __wasm_idle_debug_next_depth = depth
882
- __wasm_idle_debug_next_line = line
883
940
  elif command == 4:
884
941
  __wasm_idle_debug_step_mode = "out"
885
942
  __wasm_idle_debug_step_out_depth = max(0, depth - 1)
@@ -955,9 +1012,7 @@ finally:
955
1012
  ${debug
956
1013
  ? `
957
1014
  __wasm_idle_debug_step_mode = None
958
- __wasm_idle_debug_resume_skip = None
959
1015
  __wasm_idle_debug_next_depth = None
960
- __wasm_idle_debug_next_line = None
961
1016
  __wasm_idle_debug_step_out_depth = None
962
1017
  `
963
1018
  : ''}
@@ -971,7 +1026,9 @@ finally:
971
1026
  try {
972
1027
  finishStdio();
973
1028
  }
974
- catch { /* Preserve the execution error. */ }
1029
+ catch {
1030
+ /* Preserve the execution error. */
1031
+ }
975
1032
  self.postMessage({ error: e.message || 'Unknown error' });
976
1033
  }
977
1034
  finally {
@@ -984,6 +1041,7 @@ finally:
984
1041
  delete self[debugReadWatchName];
985
1042
  delete self[debugWriteWatchName];
986
1043
  delete self[debugReadBreakpointsName];
1044
+ delete self[debugBreakpointStateName];
987
1045
  }
988
1046
  }
989
1047
  };
@@ -0,0 +1,4 @@
1
+ import type { PyodideInterface } from 'pyodide';
2
+ import { type PythonCompileOptions, type PythonCompileResult } from '../pythonCompileOptions';
3
+ /** Compile with CPython without executing source or resolving its imports. */
4
+ export declare function compilePythonBytecode(runtime: PyodideInterface, code: string, fileName: string, optimize: 0 | 1 | 2, maxArtifactBytes: number, options?: Pick<PythonCompileOptions, 'invalidationMode' | 'timestamp'>): PythonCompileResult;