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,6 +1,5 @@
1
- import { normalizeLanguageId, normalizeWorkspacePath, validateWorkspaceFiles } from '@wasm-idle/core';
1
+ import { assertDebugBreakpointSupport, normalizeDebugSourceBreakpoints, normalizeLanguageId, normalizeWorkspacePath, validateWorkspaceFiles } from '@wasm-idle/core';
2
2
  import { ContainerError } from '@wasm-idle/container';
3
- import { createPlaygroundBinding } from '../index';
4
3
  const COMMAND = 'website-playground-engine';
5
4
  const ADAPTER = 'website-playground-host-v1';
6
5
  const encoder = new TextEncoder();
@@ -17,7 +16,7 @@ const defaultSource = (language) => ({
17
16
  TYPESCRIPT: 'main.ts'
18
17
  })[language] ?? 'main.txt';
19
18
  /** Existing real engines keep their private runtime FS; their source snapshot is the common VFS. */
20
- export class WebsiteRuntimeAdapter {
19
+ export class ContainerRuntimeAdapter {
21
20
  settings;
22
21
  adapter;
23
22
  commands = {
@@ -28,6 +27,7 @@ export class WebsiteRuntimeAdapter {
28
27
  #sessions = new Map();
29
28
  #jobs = new Map();
30
29
  #published = new Map();
30
+ #workspaceReads = new Map();
31
31
  #nextJob = 0;
32
32
  #disposed = false;
33
33
  constructor(settings) {
@@ -132,12 +132,15 @@ export class WebsiteRuntimeAdapter {
132
132
  throw new Error('Container not attached');
133
133
  return this.#container.fs;
134
134
  }
135
- directory(language) {
135
+ directoryPath(language) {
136
136
  if (typeof language !== 'string' ||
137
137
  !/^[A-Z][A-Z0-9_]{0,63}$/u.test(language) ||
138
138
  !normalizeLanguageId(language))
139
139
  throw new TypeError('Unsupported workspace language');
140
- const path = `/workspace/${language}`;
140
+ return `/workspace/${language}`;
141
+ }
142
+ directory(language) {
143
+ const path = this.directoryPath(language);
141
144
  this.fs.mkdir(path, { recursive: true });
142
145
  return path;
143
146
  }
@@ -147,7 +150,7 @@ export class WebsiteRuntimeAdapter {
147
150
  let session = this.#sessions.get(language);
148
151
  if (session)
149
152
  return session;
150
- const binding = (this.settings.createBinding ?? createPlaygroundBinding)(this.settings.runtimeAssets);
153
+ const binding = this.settings.createBinding(this.settings.runtimeAssets);
151
154
  session = {
152
155
  binding,
153
156
  sandbox: undefined,
@@ -176,8 +179,8 @@ export class WebsiteRuntimeAdapter {
176
179
  this.#sessions.set(language, session);
177
180
  return session;
178
181
  }
179
- syncWorkspace(language, files, expectedBaseFiles) {
180
- const path = this.directory(language);
182
+ syncWorkspace(language, files, expectedBaseFiles, project) {
183
+ const path = this.directoryPath(language);
181
184
  const validated = validateWorkspaceFiles(files, {
182
185
  maxFiles: 2048,
183
186
  maxFileBytes: 16 * 1024 * 1024,
@@ -185,6 +188,32 @@ export class WebsiteRuntimeAdapter {
185
188
  caseSensitive: true
186
189
  });
187
190
  const next = new Set(validated.map((file) => file.path));
191
+ let publishedNext = next;
192
+ if (project !== undefined) {
193
+ if (expectedBaseFiles === undefined || !Array.isArray(project) || project.length > 2048)
194
+ throw new TypeError('Invalid workspace delta metadata');
195
+ // Keep whole-project path/count/size admission without sending unchanged bodies.
196
+ const paths = validateWorkspaceFiles(project.map((file) => ({ path: file.path, content: '' })), { maxFiles: 2048, caseSensitive: true });
197
+ const sizes = new Map();
198
+ let total = 0;
199
+ for (let index = 0; index < paths.length; index++) {
200
+ const size = project[index].bytes;
201
+ if (!Number.isSafeInteger(size) || size < 0 || size > 16 * 1024 * 1024)
202
+ throw new TypeError('Invalid workspace file size');
203
+ total += size;
204
+ sizes.set(paths[index].path, size);
205
+ }
206
+ if (total > 64 * 1024 * 1024)
207
+ throw new TypeError('Workspace exceeds total size limit');
208
+ for (const file of validated) {
209
+ const size = typeof file.content === 'string'
210
+ ? encoder.encode(file.content).length
211
+ : file.content.length;
212
+ if (sizes.get(file.path) !== size)
213
+ throw new TypeError('Workspace delta size mismatch');
214
+ }
215
+ publishedNext = new Set(sizes.keys());
216
+ }
188
217
  const asBytes = (content) => typeof content === 'string' ? encoder.encode(content) : content;
189
218
  const equal = (left, right) => left === undefined || right === undefined
190
219
  ? left === right
@@ -210,49 +239,64 @@ export class WebsiteRuntimeAdapter {
210
239
  }).map((file) => [file.path, asBytes(file.content)]));
211
240
  const previousPaths = base?.keys() ?? this.#published.get(language) ?? [];
212
241
  const deletions = [...previousPaths].filter((previous) => !next.has(previous));
242
+ if (project && deletions.some((name) => publishedNext.has(name)))
243
+ throw new TypeError('Deleted workspace file remains in project metadata');
213
244
  // Compare all touched files before publishing even the first edit. Shell-created
214
245
  // paths outside the editor's baseline are retained unless explicitly supplied.
215
246
  if (base) {
216
247
  for (const file of validated) {
217
- const before = base.get(file.path), after = asBytes(file.content), present = current(file.path);
218
- if (!equal(before, after) && !equal(present, before) && !equal(present, after))
248
+ const before = base.get(file.path), after = asBytes(file.content);
249
+ if (equal(before, after))
250
+ continue;
251
+ const present = current(file.path);
252
+ if (!equal(present, before) && !equal(present, after))
219
253
  throw new ContainerError('FILESYSTEM_CONFLICT', `Workspace changed while editing ${file.path}`);
220
254
  }
221
255
  for (const file of deletions)
222
256
  if (current(file) !== undefined && !equal(current(file), base.get(file)))
223
257
  throw new ContainerError('FILESYSTEM_CONFLICT', `Workspace changed before deleting ${file}`);
224
258
  }
225
- for (const previous of deletions) {
226
- try {
227
- this.fs.unlink(previous, { root: path, cwd: path });
228
- }
229
- catch (error) {
230
- if (error.code !== 'ENOENT')
231
- throw error;
232
- }
233
- }
234
- for (const file of validated) {
235
- // An unchanged editor buffer must not overwrite a newer shell revision.
236
- if (base?.has(file.path) && equal(base.get(file.path), asBytes(file.content)))
237
- continue;
238
- const parent = file.path.split('/').slice(0, -1).join('/');
239
- if (parent)
240
- this.fs.mkdir(parent, { recursive: true, root: path, cwd: path });
241
- const bytes = typeof file.content === 'string' ? encoder.encode(file.content) : file.content;
242
- let previous;
243
- try {
244
- previous = this.fs.readFile(file.path, { root: path, cwd: path });
245
- }
246
- catch (error) {
247
- if (error.code !== 'ENOENT')
248
- throw error;
259
+ this.fs.applyFileChanges({
260
+ remove: deletions,
261
+ write: validated
262
+ // Unchanged editor buffers must not overwrite newer shell revisions.
263
+ .filter((file) => !base?.has(file.path) ||
264
+ !equal(base.get(file.path), asBytes(file.content)))
265
+ .map((file) => ({ path: file.path, bytes: asBytes(file.content) }))
266
+ }, { root: path, cwd: path, createRoot: true });
267
+ this.#published.set(language, publishedNext);
268
+ }
269
+ readWorkspaceDelta(language, since) {
270
+ const root = this.directory(language);
271
+ const previous = this.#workspaceReads.get(language);
272
+ const reset = !previous || since !== previous.revision;
273
+ const versions = new Map();
274
+ const files = [];
275
+ const visit = (path) => {
276
+ for (const name of this.fs.readdir(path || '.', { root, cwd: root })) {
277
+ const relative = path ? `${path}/${name}` : name;
278
+ const options = { root, cwd: root };
279
+ const stat = this.fs.lstat(relative, options);
280
+ if (stat.type === 'directory')
281
+ visit(relative);
282
+ else if (stat.type === 'file') {
283
+ const version = this.fs.captureFileVersion(relative, options);
284
+ versions.set(relative, version);
285
+ if (reset || previous?.versions.get(relative) !== version)
286
+ files.push({
287
+ path: relative,
288
+ content: this.fs.readFile(relative, options)
289
+ });
290
+ }
249
291
  }
250
- if (previous?.length === bytes.length &&
251
- previous.every((byte, index) => byte === bytes[index]))
252
- continue;
253
- this.fs.writeFile(file.path, bytes, { root: path, cwd: path });
254
- }
255
- this.#published.set(language, next);
292
+ };
293
+ visit('');
294
+ const deleted = reset
295
+ ? []
296
+ : [...previous.versions.keys()].filter((path) => !versions.has(path));
297
+ const revision = (previous?.revision ?? 0) + 1;
298
+ this.#workspaceReads.set(language, { revision, versions });
299
+ return { revision, reset, files, deleted };
256
300
  }
257
301
  readWorkspace(language) {
258
302
  const root = this.directory(language), files = [];
@@ -434,7 +478,10 @@ export class WebsiteRuntimeAdapter {
434
478
  'debugCommand',
435
479
  'debugPause',
436
480
  'setBreakpoints',
481
+ 'setSourceBreakpoints',
437
482
  'debugEvaluate',
483
+ 'debugEvaluateValue',
484
+ 'debugSetSteppingOptions',
438
485
  'debugVariables',
439
486
  'debugScopes',
440
487
  'debugFrameScopes',
@@ -446,11 +493,25 @@ export class WebsiteRuntimeAdapter {
446
493
  ]);
447
494
  if (!allowed.has(method))
448
495
  throw new TypeError('Unknown debugger method');
496
+ const specifications = method === 'setSourceBreakpoints'
497
+ ? normalizeDebugSourceBreakpoints(args[0])
498
+ : undefined;
499
+ const sourcePath = specifications ? args[1] : undefined;
500
+ if (sourcePath !== undefined && typeof sourcePath !== 'string')
501
+ throw new TypeError('Invalid debugger source path');
449
502
  const sandbox = await this.session(language).sandbox;
450
503
  const handler = sandbox[method];
504
+ if (specifications &&
505
+ typeof handler !== 'function' &&
506
+ typeof sandbox.setBreakpoints === 'function') {
507
+ assertDebugBreakpointSupport(specifications, {});
508
+ return await sandbox.setBreakpoints(specifications
509
+ .filter((value) => value.enabled !== false)
510
+ .map((value) => value.line), sourcePath);
511
+ }
451
512
  if (typeof handler !== 'function')
452
513
  throw new Error(`The ${language} runtime does not support ${method}`);
453
- return await handler.apply(sandbox, args);
514
+ return await handler.apply(sandbox, specifications ? [specifications, sourcePath] : args);
454
515
  }
455
516
  inspect() {
456
517
  return [...this.#jobs.values()].map((job) => ({
@@ -470,5 +531,7 @@ export class WebsiteRuntimeAdapter {
470
531
  }));
471
532
  this.#sessions.clear();
472
533
  this.#jobs.clear();
534
+ this.#workspaceReads.clear();
473
535
  }
474
536
  }
537
+ export { ContainerRuntimeAdapter as WebsiteRuntimeAdapter };
@@ -15,7 +15,7 @@ export interface ShellControlInspection {
15
15
  readonly appliedGeneration: number;
16
16
  readonly error: string | null;
17
17
  }
18
- interface ShellControlOptions {
18
+ export interface ShellControlOptions {
19
19
  languages: readonly string[];
20
20
  initialDirectory?: string;
21
21
  onChange?: (inspection: ShellControlInspection) => void;
@@ -42,8 +42,8 @@ export declare function createShellControl(options: ShellControlOptions): Readon
42
42
  }>;
43
43
  }>;
44
44
  requestDirectory(language: string): Promise<void>;
45
+ requestPrompt(action: "suspend" | "resume", signal?: AbortSignal): Promise<void>;
45
46
  onInvocation(invocation: HostCommandInvocation): number | undefined;
46
47
  inspect: () => ShellControlInspection;
47
48
  dispose(): void;
48
49
  }>;
49
- export {};
@@ -33,15 +33,29 @@ function rcfile(session, languages) {
33
33
  ' builtin exec {__wic_fd}<&-',
34
34
  ' return 0',
35
35
  ' fi',
36
- ' [[ "$__wic_version" == 1 && "$__wic_session" == "$__wic_expected_session" && -z "$__wic_extra" ]] || return 0',
36
+ ' [[ "$__wic_session" == "$__wic_expected_session" && -z "$__wic_extra" ]] || return 0',
37
37
  ' [[ "$__wic_generation" =~ ^[1-9][0-9]{0,9}$ ]] || return 0',
38
38
  ` (( __wic_generation <= ${MAX_GENERATION} && __wic_generation > \${__wasm_idle_control_generation:-0} )) || return 0`,
39
+ ' if [[ "$__wic_version" == 2 ]]; then',
40
+ ' case "$__wic_language" in suspend|resume) ;; *) return 0 ;; esac',
41
+ ' __wasm_idle_control_generation=$__wic_generation',
42
+ // Output belongs to the actual shell, while its editing buffer remains untouched.
43
+ ' builtin printf "\\r\\n"',
44
+ ` if '${SHELL_CONTROL_ROUTE}' 2 "$__wic_session" "$__wic_generation" "$__wic_language" ok; then :; else :; fi`,
45
+ // The pinned native hook decodes PS1 and redraws the preserved Readline buffer.
46
+ ' [[ "$__wic_language" == resume ]] && return 124',
47
+ ' return 0',
48
+ ' fi',
49
+ ' [[ "$__wic_version" == 1 ]] || return 0',
39
50
  ` case "$__wic_language" in ${languages.join('|')}) ;; *) return 0 ;; esac`,
40
51
  ' __wasm_idle_control_generation=$__wic_generation',
41
52
  ' __wic_oldpwd=$PWD',
42
53
  ' if builtin cd -P -- "/workspace/$__wic_language"; then',
43
54
  ` if '${SHELL_CONTROL_ROUTE}' 1 "$__wic_session" "$__wic_generation" "$__wic_language" ok; then :; else :; fi`,
44
- ' [[ "$__wic_oldpwd" != "$PWD" ]] && return 124',
55
+ ' if [[ "$__wic_oldpwd" != "$PWD" ]]; then',
56
+ ' builtin printf "\\r\\n"',
57
+ ' return 124',
58
+ ' fi',
45
59
  ' else',
46
60
  ` if '${SHELL_CONTROL_ROUTE}' 1 "$__wic_session" "$__wic_generation" "$__wic_language" failed; then :; else :; fi`,
47
61
  ' fi',
@@ -124,33 +138,37 @@ export function createShellControl(options) {
124
138
  if (disposed ||
125
139
  !filesystem ||
126
140
  args.length !== 5 ||
127
- args[0] !== '1' ||
141
+ !['1', '2'].includes(args[0]) ||
128
142
  args[1] !== session ||
129
143
  !/^[1-9][0-9]{0,9}$/.test(args[2]) ||
130
- !allowed.has(args[3]) ||
144
+ !(args[0] === '1' ? allowed.has(args[3]) : ['suspend', 'resume'].includes(args[3])) ||
131
145
  !['ok', 'failed'].includes(args[4]) ||
132
146
  !canonicalDirectory(actualCwd))
133
147
  return 126;
134
- const received = Number(args[2]), language = args[3], verdict = args[4];
135
- if (verdict === 'ok' && actualCwd !== `/workspace/${language}`)
148
+ const version = args[0], received = Number(args[2]), target = args[3], verdict = args[4];
149
+ if (version === '1' && verdict === 'ok' && actualCwd !== `/workspace/${target}`)
136
150
  return 126;
137
151
  if (received > MAX_GENERATION || received > generation)
138
152
  return 126;
139
153
  if (received < generation)
140
154
  return 0; // A superseded completion cannot publish the new request.
141
155
  if (!pending)
142
- return lastAcknowledgement?.generation === received &&
143
- lastAcknowledgement.language === language &&
156
+ return lastAcknowledgement?.version === version &&
157
+ lastAcknowledgement.generation === received &&
158
+ lastAcknowledgement.target === target &&
144
159
  lastAcknowledgement.cwd === actualCwd &&
145
160
  lastAcknowledgement.verdict === verdict
146
161
  ? 0
147
162
  : 126;
148
- if (pending.language !== language || (verdict === 'ok' && actualCwd !== pending.cwd))
163
+ if (pending.version !== version ||
164
+ pending.target !== target ||
165
+ (pending.cwd && verdict === 'ok' && actualCwd !== pending.cwd))
149
166
  return 126;
150
167
  const completed = pending;
151
168
  pending = undefined;
169
+ completed.removeAbort?.();
152
170
  cwd = actualCwd;
153
- lastAcknowledgement = { generation: received, language, cwd: actualCwd, verdict };
171
+ lastAcknowledgement = { version, generation: received, target, cwd: actualCwd, verdict };
154
172
  if (verdict === 'ok') {
155
173
  appliedGeneration = received;
156
174
  error = null;
@@ -163,6 +181,64 @@ export function createShellControl(options) {
163
181
  changed();
164
182
  return 0;
165
183
  };
184
+ const request = (version, target, signal) => {
185
+ try {
186
+ const fs = currentFilesystem();
187
+ signal?.throwIfAborted();
188
+ if (version === '1' ? !allowed.has(target) : !['suspend', 'resume'].includes(target))
189
+ throw new Error('Unknown shell control target');
190
+ if (pending?.version === version && pending.target === target)
191
+ return pending.promise;
192
+ if (generation === MAX_GENERATION)
193
+ throw new Error('Shell control generation exhausted');
194
+ const targetCwd = version === '1' ? `/workspace/${target}` : undefined, nextGeneration = generation + 1;
195
+ if (targetCwd)
196
+ ensureDirectory(fs, targetCwd);
197
+ writeRequest(fs, `${version} ${session} ${nextGeneration} ${target}\n`);
198
+ pending?.removeAbort?.();
199
+ pending?.reject(abortError('Shell control request was superseded'));
200
+ let resolve, reject;
201
+ const promise = new Promise((yes, no) => {
202
+ resolve = yes;
203
+ reject = no;
204
+ });
205
+ const next = {
206
+ version,
207
+ target,
208
+ cwd: targetCwd,
209
+ promise,
210
+ resolve,
211
+ reject
212
+ };
213
+ pending = next;
214
+ generation = nextGeneration;
215
+ error = null;
216
+ if (signal) {
217
+ const abort = () => {
218
+ if (pending !== next)
219
+ return;
220
+ pending = undefined;
221
+ next.removeAbort?.();
222
+ // A foreground command must not receive control on its eventual return.
223
+ try {
224
+ writeRequest(fs, `1 ${session} 0 -\n`);
225
+ }
226
+ catch {
227
+ /* Preserve the cancellation if the guest has removed its mailbox. */
228
+ }
229
+ reject(signal.reason ?? abortError('Shell control request was cancelled'));
230
+ changed();
231
+ };
232
+ signal.addEventListener('abort', abort, { once: true });
233
+ next.removeAbort = () => signal.removeEventListener('abort', abort);
234
+ }
235
+ changed();
236
+ return promise;
237
+ }
238
+ catch (reason) {
239
+ return Promise.reject(reason);
240
+ }
241
+ };
166
242
  const adapter = {
167
243
  id: ADAPTER,
168
244
  filesystem: 'live',
@@ -246,32 +322,12 @@ export function createShellControl(options) {
246
322
  return configuration;
247
323
  },
248
324
  requestDirectory(language) {
249
- try {
250
- const fs = currentFilesystem();
251
- if (!allowed.has(language))
252
- throw new Error('Unknown shell project directory');
253
- if (pending?.language === language)
254
- return pending.promise;
255
- if (generation === MAX_GENERATION)
256
- throw new Error('Shell directory generation exhausted');
257
- const target = `/workspace/${language}`, nextGeneration = generation + 1;
258
- ensureDirectory(fs, target);
259
- writeRequest(fs, `1 ${session} ${nextGeneration} ${language}\n`);
260
- pending?.reject(abortError('Shell directory request was superseded'));
261
- let resolve, reject;
262
- const promise = new Promise((yes, no) => {
263
- resolve = yes;
264
- reject = no;
265
- });
266
- pending = { language, cwd: target, promise, resolve, reject };
267
- generation = nextGeneration;
268
- error = null;
269
- changed();
270
- return promise;
271
- }
272
- catch (reason) {
273
- return Promise.reject(reason);
274
- }
325
+ if (!allowed.has(language))
326
+ return Promise.reject(new Error('Unknown shell project directory'));
327
+ return request('1', language);
328
+ },
329
+ requestPrompt(action, signal) {
330
+ return request('2', action, signal);
275
331
  },
276
332
  onInvocation(invocation) {
277
333
  return invocation.path === SHELL_CONTROL_ROUTE
@@ -283,6 +339,7 @@ export function createShellControl(options) {
283
339
  if (disposed)
284
340
  return;
285
341
  disposed = true;
342
+ pending?.removeAbort?.();
286
343
  pending?.reject(abortError('Shell directory control was disposed'));
287
344
  pending = undefined;
288
345
  if (filesystem) {
@@ -1,4 +1,8 @@
1
- import type { WorkspaceFile } from '../../../routes/workspaceCodec';
1
+ export interface WorkspaceFile {
2
+ path: string;
3
+ content: string;
4
+ encoding?: 'utf-8' | 'data-url';
5
+ }
2
6
  /** Reconcile independent terminal edits without discarding an unpublished editor revision. */
3
7
  export declare function mergeContainerWorkspace(local: readonly WorkspaceFile[], baseline: readonly WorkspaceFile[], remote: readonly WorkspaceFile[], options?: {
4
8
  acceptRemoteConflicts?: boolean;
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ export { createRuntimeSession } from './playground/runtimeSession';
5
5
  export { configureRuntimeAssetCache, createRuntimeAssetCacheBackend, fetchPinnedRuntimeAsset, prefetchRuntimeAssets, resolveRuntimeAssetLockEntry, type PrefetchRuntimeAssetsOptions, type PrefetchRuntimeAssetsResult, type RuntimeAssetCacheStats, type RuntimeAssetCacheBackend, type RuntimeAssetCacheBackendIdentity, type PinnedRuntimeAssetRequest, getRuntimeAssetCacheOptions, getRuntimeAssetCacheStats, clearRuntimeAssetCache, pruneRuntimeAssetCache, requestRuntimeAssetCachePersistence, type RuntimeAssetCacheOptions } from '@wasm-idle/core';
6
6
  export type { PlaygroundRuntimeSession } from './playground/runtimeSession';
7
7
  export { isSharedArrayBufferAvailable, requireSharedArrayBuffer } from './playground/sharedBuffer';
8
- export type { DebugCommand, DebugFrame, DebugSessionEvent, DebugVariable, TerminalControl } from '@wasm-idle/core';
8
+ export type { DebugCommand, DebugEvaluateOptions, DebugEvaluateResult, DebugSourceBreakpoint, DebugSourceBreakpoints, DebugSteppingOptions, DebugSessionCapabilities, DebugVariablePresentationHint, DebugFrame, DebugSessionEvent, DebugVariable, TerminalControl } from '@wasm-idle/core';
9
9
  export type { CompilerDiagnostic, SandboxExecutionOptions } from './playground/options';
10
10
  export type { PlaygroundRuntimeAssets, RuntimeAssetConfig, RuntimeAssetLoadRequest, RuntimeAssetLoader, RuntimeAssetLoaderResult } from './playground/assets';
11
11
  export type { BoundSandbox, PlaygroundBinding, PlaygroundTerminalProps, SandboxProgress, SandboxRuntimeAssets } from './playground/sandbox';
@@ -1,5 +1,5 @@
1
1
  import { RUNTIME_LOAD_ASSETS } from './assets';
2
- import { ProtocolError, verifyRuntimeAssetIntegrity, verifyRuntimeAssetPair, readPersistentRuntimeAsset, writePersistentRuntimeAsset, resolveRuntimeAssetLockEntry, resolveRuntimeAssetCacheOptions } from '@wasm-idle/core';
2
+ import { ProtocolError, compilePythonRuntimeModule, verifyRuntimeAssetIntegrity, verifyRuntimeAssetPair, readPersistentRuntimeAsset, writePersistentRuntimeAsset, resolveRuntimeAssetLockEntry, resolveRuntimeAssetCacheOptions } from '@wasm-idle/core';
3
3
  import { decompressGzip } from '@wasm-idle/llvm-core';
4
4
  import { readPythonPackageAssets } from './pythonPackageLock';
5
5
  import { BUNDLED_CLANG_LANGUAGE_SYSROOT_PROFILES } from './clangAssetIntegrity';
@@ -660,7 +660,10 @@ export class WorkerAssetBridge {
660
660
  else {
661
661
  const loaded = await loadBytes(signal, (event) => report(event, `${event.kind}:${event.asset}`));
662
662
  bytes = loaded.bytes.byteLength;
663
- module = await WebAssembly.compile(Uint8Array.from(loaded.bytes));
663
+ module =
664
+ this.runtime === 'python' && request.asset === 'pyodide.asm.wasm'
665
+ ? await compilePythonRuntimeModule(loaded.bytes)
666
+ : await WebAssembly.compile(Uint8Array.from(loaded.bytes));
664
667
  }
665
668
  if (signal.aborted)
666
669
  throw runtimeAssetAbortReason(signal);
@@ -550,6 +550,14 @@ export interface PhpRuntimeAssetConfig {
550
550
  moduleUrl?: string;
551
551
  }
552
552
  export interface PlaygroundRuntimeAssets extends RuntimeAssetKeySource {
553
+ javaLsp?: {
554
+ baseUrl?: string;
555
+ assets?: readonly {
556
+ readonly path: 'javacs-runtime.mjs' | 'javacs.wasm' | 'jdk-platform.zip';
557
+ readonly bytes: number;
558
+ readonly sha256: string;
559
+ }[];
560
+ };
553
561
  python?: RuntimeAssetConfig;
554
562
  java?: RuntimeAssetConfig;
555
563
  clang?: RuntimeAssetConfig;
@@ -1,4 +1,4 @@
1
- import type { DebugCommand, DebugDataBreakpoint, DebugDataBreakpointInfoArguments, DebugSessionEvent, SandboxExecutionOptions } from './options';
1
+ import type { DebugCommand, DebugEvaluateOptions, DebugSourceBreakpoint, DebugSteppingOptions, DebugDataBreakpoint, DebugDataBreakpointInfoArguments, DebugSessionEvent, SandboxExecutionOptions } from './options';
2
2
  import { WorkerAssetBridge } from './assetBridge';
3
3
  import { RuntimeAssetCache } from './runtimeAssetCache';
4
4
  import { type PlaygroundRuntimeAssets, type RuntimeAssetIntegrityEntry } from './assets';
@@ -35,6 +35,7 @@ declare class Clang implements Sandbox {
35
35
  private disposal?;
36
36
  private debugMode;
37
37
  private readonly lldbBreakpoints;
38
+ private readonly lldbBreakpointSpecifications;
38
39
  private debugEvaluationQueue;
39
40
  private precompiledHeader?;
40
41
  private precompiledHeaderSent?;
@@ -51,6 +52,9 @@ declare class Clang implements Sandbox {
51
52
  debugCommand(command: DebugCommand): Promise<void> | undefined;
52
53
  debugPause(): Promise<void> | undefined;
53
54
  setBreakpoints(lines: number[], sourcePath?: string): Promise<void> | undefined;
55
+ setSourceBreakpoints(breakpoints: DebugSourceBreakpoint[], sourcePath?: string): Promise<void>;
56
+ debugSetSteppingOptions(options: DebugSteppingOptions): Promise<void>;
57
+ debugEvaluateValue(expression: string, options?: DebugEvaluateOptions): Promise<import("@wasm-idle/core").DebugEvaluateResult>;
54
58
  debugEvaluate(expression: string): Promise<string>;
55
59
  debugVariables(variablesReference: number, start?: number, count?: number): Promise<import("@wasm-idle/core").DebugVariable[]>;
56
60
  debugScopes(frameId: number): Promise<import("@wasm-idle/core").DebugScope[]>;
@@ -4,7 +4,7 @@ import { RuntimeAssetCache } from './runtimeAssetCache';
4
4
  import { resolveDebugRuntimeUrls, resolveRuntimeAssetConfig } from './assets';
5
5
  import { LldbSandboxSession } from './lldbSession';
6
6
  import { normalizeDwarfWorkspacePath } from '@wasm-idle/llvm-core/clang';
7
- import { resolveExecutionLimits } from '@wasm-idle/core';
7
+ import { resolveExecutionLimits, normalizeDebugSourceBreakpoints, mergeDebugBreakpointLines, assertDebugBreakpointSupport } from '@wasm-idle/core';
8
8
  import { resolveSandboxExecutionArgs } from './options';
9
9
  import { bufferedSequence, flushBufferedEof, flushQueuedStdin, resetBufferedStdin, waitForBufferedSequenceChange } from './stdinBuffer';
10
10
  import { createWasmIdleSharedBuffer, requireSharedArrayBuffer } from './sharedBuffer';
@@ -47,6 +47,7 @@ class Clang {
47
47
  disposal;
48
48
  debugMode = 'none';
49
49
  lldbBreakpoints = new Map();
50
+ lldbBreakpointSpecifications = new Map();
50
51
  debugEvaluationQueue = Promise.resolve();
51
52
  // A helper worker builds the precompiled <bits/stdc++.h> so the warm worker stays free for
52
53
  // runs. The header is sent once to each warm worker, which keeps it for later compiles.
@@ -198,6 +199,9 @@ class Clang {
198
199
  if (this.disposed)
199
200
  return Promise.reject(new Error('Clang runtime has been disposed'));
200
201
  const debugMode = options.debugMode || (options.debug ? 'trace' : 'none');
202
+ if (debugMode !== 'none' && debugMode !== 'trace' && debugMode !== 'lldb') {
203
+ return Promise.reject(new Error(`${this.language} does not support ${debugMode} debugging.`));
204
+ }
201
205
  this.debugMode = debugMode;
202
206
  if (debugMode !== 'none')
203
207
  requireSharedArrayBuffer(`${this.language} debugging`);
@@ -213,14 +217,33 @@ class Clang {
213
217
  const { compileArgs, programArgs } = resolveSandboxExecutionArgs(this.language, args, options);
214
218
  const sourcePath = normalizeLldbSourcePath(options.debugPath || options.activePath, this.language === 'C' ? 'main.c' : 'main.cc');
215
219
  this.lldbBreakpoints.clear();
220
+ this.lldbBreakpointSpecifications.clear();
216
221
  if (debugMode === 'lldb') {
217
222
  for (const sourceBreakpoints of options.sourceBreakpoints || []) {
218
- this.setBreakpoints(sourceBreakpoints.lines, sourceBreakpoints.sourcePath);
223
+ if (sourceBreakpoints.breakpoints) {
224
+ const values = normalizeDebugSourceBreakpoints(sourceBreakpoints.breakpoints);
225
+ const path = normalizeLldbSourcePath(sourceBreakpoints.sourcePath, sourcePath.replace(/^\/workspace\//u, ''));
226
+ this.lldbBreakpointSpecifications.set(path, values);
227
+ this.lldbBreakpoints.set(path, values
228
+ .filter((value) => value.enabled !== false)
229
+ .map((value) => value.line));
230
+ }
231
+ else
232
+ this.setBreakpoints(sourceBreakpoints.lines, sourceBreakpoints.sourcePath);
219
233
  }
220
- this.setBreakpoints([...(options.breakpoints || [])], sourcePath);
234
+ if (!this.lldbBreakpointSpecifications.has(sourcePath))
235
+ this.setBreakpoints([...(options.breakpoints || [])], sourcePath);
221
236
  }
222
237
  else {
223
- this.setBreakpoints([...(options.breakpoints || [])], sourcePath);
238
+ for (const source of options.sourceBreakpoints || [])
239
+ if (source.breakpoints)
240
+ assertDebugBreakpointSupport(normalizeDebugSourceBreakpoints(source.breakpoints), {});
241
+ const source = options.sourceBreakpoints?.find((entry) => normalizeLldbSourcePath(entry.sourcePath, sourcePath.replace(/^\/workspace\//u, '')) === sourcePath);
242
+ this.setBreakpoints(source?.breakpoints
243
+ ? source.breakpoints
244
+ .filter((value) => value.enabled !== false)
245
+ .map((value) => value.line)
246
+ : [...(options.breakpoints || [])], sourcePath);
224
247
  }
225
248
  const interrupt = new Uint8Array(this.interruptBuffer), _uid = ++this.uid;
226
249
  const handler = (event) => {
@@ -256,9 +279,15 @@ class Clang {
256
279
  breakpoints: [...(options.breakpoints || [])],
257
280
  sourceBreakpoints: Array.from(this.lldbBreakpoints, ([sourcePath, lines]) => ({
258
281
  sourcePath,
259
- lines: [...lines]
282
+ lines: [...lines],
283
+ ...(this.lldbBreakpointSpecifications.has(sourcePath)
284
+ ? {
285
+ breakpoints: normalizeDebugSourceBreakpoints(this.lldbBreakpointSpecifications.get(sourcePath))
286
+ }
287
+ : {})
260
288
  })),
261
289
  pauseOnEntry: !!options.pauseOnEntry,
290
+ debugSteppingOptions: options.debugSteppingOptions,
262
291
  pauseAtMain: true,
263
292
  programArgs,
264
293
  stdin: options.stdin,
@@ -386,6 +415,8 @@ class Clang {
386
415
  return this.lldbSession.setBreakpoints(lines, resolvedSourcePath);
387
416
  }
388
417
  if (this.debugMode === 'lldb') {
418
+ if (this.lldbBreakpointSpecifications.has(resolvedSourcePath))
419
+ return this.setSourceBreakpoints(mergeDebugBreakpointLines(this.lldbBreakpointSpecifications.get(resolvedSourcePath), lines), resolvedSourcePath);
389
420
  this.lldbBreakpoints.set(resolvedSourcePath, [...lines]);
390
421
  return;
391
422
  }
@@ -399,6 +430,31 @@ class Clang {
399
430
  Atomics.store(control, 3, next.length);
400
431
  Atomics.add(control, 2, 1);
401
432
  }
433
+ async setSourceBreakpoints(breakpoints, sourcePath) {
434
+ const values = normalizeDebugSourceBreakpoints(breakpoints);
435
+ const path = normalizeLldbSourcePath(sourcePath, this.language === 'C' ? 'main.c' : 'main.cc');
436
+ if (this.lldbSession)
437
+ return this.lldbSession.setSourceBreakpoints(values, path);
438
+ if (this.debugMode === 'lldb') {
439
+ this.lldbBreakpointSpecifications.set(path, values);
440
+ this.lldbBreakpoints.set(path, values.filter((value) => value.enabled !== false).map((value) => value.line));
441
+ return;
442
+ }
443
+ assertDebugBreakpointSupport(values, {});
444
+ this.setBreakpoints(values.filter((value) => value.enabled !== false).map((value) => value.line), sourcePath);
445
+ }
446
+ async debugSetSteppingOptions(options) {
447
+ if (!this.lldbSession)
448
+ throw new Error('Stepping options require an LLDB session.');
449
+ await this.lldbSession.setSteppingOptions(options);
450
+ }
451
+ async debugEvaluateValue(expression, options) {
452
+ if (this.lldbSession)
453
+ return this.lldbSession.evaluateValue(expression, options);
454
+ if (options?.frameId !== undefined || options?.context === 'hover')
455
+ return { result: '?', variablesReference: 0 };
456
+ return { result: await this.debugEvaluate(expression), variablesReference: 0 };
457
+ }
402
458
  debugEvaluate(expression) {
403
459
  if (this.lldbSession)
404
460
  return this.lldbSession.evaluate(expression);