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
@@ -0,0 +1,328 @@
1
+ import { createContainer, createContainerPackageManager, createVerifiedAssetLoader, validateDistribution, extractTarPackage } from '@wasm-idle/container';
2
+ import { createClangAdapter } from '@wasm-idle/container/adapters/clang';
3
+ import { createLiveClangAdapter } from '@wasm-idle/container/adapters/clang-live';
4
+ import { createLiveWasiAdapter } from '@wasm-idle/container/adapters/wasi-live';
5
+ import { clangSimdDriverArgs, installClangSimdHeaders } from '@wasm-idle/llvm-core/core/clang-simd';
6
+ import { createWasixShellSession, installWasixWorkerGroup } from '@wasm-idle/container/adapters/wasix';
7
+ export const BASH_BIN = '/usr/local/bin';
8
+ export const BASH_SYSROOT = '/usr/share/wasm-sysroot';
9
+ export const C_SYSROOT = '/usr/share/wasm-sysroot-c';
10
+ const TOOLCHAIN = '/opt/toolchains/llvm';
11
+ /** Expose the verified legacy sysroot through the canonical driver's automatic search paths. */
12
+ export function withCanonicalWasiPaths(entries) {
13
+ const additions = [];
14
+ for (const parent of ['include', 'lib']) {
15
+ if (entries.some((entry) => entry.path === `${parent}/wasm32-wasi` && entry.type === 'directory') &&
16
+ !entries.some((entry) => entry.path === `${parent}/wasm32-wasip1`))
17
+ additions.push({
18
+ path: `${parent}/wasm32-wasip1`,
19
+ type: 'symlink',
20
+ mode: 0o777,
21
+ target: 'wasm32-wasi'
22
+ });
23
+ }
24
+ const directory = 'lib/clang/22/lib/wasm32-unknown-wasip1';
25
+ const path = `${directory}/libclang_rt.builtins.a`;
26
+ if (!entries.some((entry) => entry.path === path) &&
27
+ entries.some((entry) => entry.path === 'lib/clang/22/lib/wasi/libclang_rt.builtins-wasm32.a' &&
28
+ entry.type === 'file')) {
29
+ if (!entries.some((entry) => entry.path === directory))
30
+ additions.push({ path: directory, type: 'directory', mode: 0o755 });
31
+ additions.push({
32
+ path,
33
+ type: 'symlink',
34
+ mode: 0o777,
35
+ target: '../wasi/libclang_rt.builtins-wasm32.a'
36
+ });
37
+ }
38
+ return additions.length ? [...entries, ...additions] : entries;
39
+ }
40
+ const digest = async (bytes) => Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', Uint8Array.from(bytes))), (value) => value.toString(16).padStart(2, '0')).join('');
41
+ /** Compose verified USTAR layers without changing retained header or file bytes. */
42
+ export function composeSysrootLayers(base, cxx) {
43
+ for (const layer of [base, cxx]) {
44
+ if (!(layer instanceof Uint8Array) ||
45
+ layer.length < 1024 ||
46
+ layer.length % 512 ||
47
+ layer.subarray(-1024).some((byte) => byte !== 0))
48
+ throw new Error('Invalid sysroot layer terminator');
49
+ }
50
+ const length = base.length + cxx.length - 1024;
51
+ if (length > 128 * 1024 * 1024)
52
+ throw new Error('Composed sysroot exceeds its archive budget');
53
+ const archive = new Uint8Array(length);
54
+ archive.set(base.subarray(0, -1024));
55
+ archive.set(cxx.subarray(0, -1024), base.length - 1024);
56
+ return archive;
57
+ }
58
+ /** A shared Bash/Clang owner. Importing this module does not load any runtime assets. */
59
+ export async function createBashProfile({ config, sdk, workspace, fetch: fetcher, onRecord, onInvocation, adapters = [], commands = {}, workerGroup, shellCommands = [], shellRoutes = {} }) {
60
+ const filesystem = config.clangFilesystem === undefined ? 'snapshot' : config.clangFilesystem;
61
+ if (filesystem !== 'snapshot' && filesystem !== 'live')
62
+ throw new TypeError('clangFilesystem must be snapshot or live');
63
+ const adapterId = filesystem === 'live' ? 'llvm-clang-tool-host-live-v1' : 'llvm-clang-tool-host-v1';
64
+ const layers = config.sysrootLayers;
65
+ if ((config.sysrootProfile !== undefined &&
66
+ !['full', 'c-base-v1'].includes(config.sysrootProfile)) ||
67
+ Boolean(layers) !== (config.sysrootProfile === 'c-base-v1'))
68
+ throw new Error('Explicit C base profile and pinned layers must be configured together');
69
+ if (layers &&
70
+ (layers.schemaVersion !== 1 ||
71
+ layers.basePackage !== 'llvm-sysroot-c' ||
72
+ layers.cxxPackage !== 'llvm-sysroot-cxx' ||
73
+ !/^[a-f0-9]{64}$/.test(layers.full?.sha256) ||
74
+ !Number.isSafeInteger(layers.full?.bytes) ||
75
+ layers.full.bytes < 1024 ||
76
+ layers.full.bytes > 128 * 1024 * 1024))
77
+ throw new Error('Invalid pinned sysroot layer configuration');
78
+ const distribution = await validateDistribution({
79
+ bytes: new TextEncoder().encode(config.manifest),
80
+ expectedSha256: config.manifestSha256,
81
+ adapterIds: ['wasi-preview1-live', adapterId],
82
+ allowedAssetURLs: config.assetURLs
83
+ });
84
+ const cache = Object.freeze({
85
+ enabled: true,
86
+ namespace: config.cacheNamespace,
87
+ version: config.manifestSha256,
88
+ storageReserveBytes: 0
89
+ });
90
+ const assetOptions = {
91
+ distribution,
92
+ fetch: fetcher,
93
+ persistentCache: cache,
94
+ maxCachedBytes: 192 * 1024 * 1024
95
+ };
96
+ const manager = createContainerPackageManager({
97
+ ...assetOptions,
98
+ capabilities: ['wasi-preview1', 'llvm-tool-host-exec-v1']
99
+ });
100
+ const shellAssets = createVerifiedAssetLoader({
101
+ ...assetOptions,
102
+ maxCachedBytes: 64 * 1024 * 1024
103
+ });
104
+ let workers;
105
+ let container;
106
+ let compiler;
107
+ try {
108
+ workers = workerGroup ?? installWasixWorkerGroup({ maxWorkers: config.maxWorkers ?? 32 });
109
+ compiler = (filesystem === 'live' ? createLiveClangAdapter : createClangAdapter)({
110
+ clangSha256: config.clangSha256,
111
+ linkerSha256: config.linkerSha256,
112
+ linkerPath: `${TOOLCHAIN}/bin/wasm-ld`,
113
+ compilerPaths: [`${TOOLCHAIN}/bin/llvm`],
114
+ ...(filesystem === 'live'
115
+ ? { moduleServices: config.clangModuleServices === true }
116
+ : {}),
117
+ executableOutputProfile: 'wasi-preview1-process',
118
+ workerFactory: () => new Worker(config.clangWorkerUrl, { type: 'module' })
119
+ });
120
+ container = createContainer({
121
+ workspace,
122
+ packages: manager,
123
+ commands,
124
+ maxBytes: workspace?.fs.maxBytes ?? 256 * 1024 * 1024,
125
+ adapters: [
126
+ ...adapters,
127
+ createLiveWasiAdapter({
128
+ maxBlockedIoMs: 120000,
129
+ workerFactory: () => new Worker(config.liveWorkerUrl, { type: 'module' })
130
+ }),
131
+ compiler
132
+ ],
133
+ artifactAdapter: 'wasi-preview1-live',
134
+ maxMemoryBytes: 2 ** 32,
135
+ maxProcesses: 8
136
+ });
137
+ }
138
+ catch (error) {
139
+ compiler?.clearModuleCache?.();
140
+ await workers?.dispose();
141
+ await manager.dispose();
142
+ await shellAssets.dispose();
143
+ throw error;
144
+ }
145
+ const routes = {
146
+ ...Object.fromEntries(shellCommands.map((name) => [`${BASH_BIN}/${name}`, { command: name }])),
147
+ [`${BASH_BIN}/clang`]: {
148
+ command: 'clang',
149
+ // Prepared release manifests may predate the current SIMD defaults.
150
+ args: clangSimdDriverArgs(BASH_SYSROOT),
151
+ stdio: filesystem === 'live' ? 'delegated' : 'forwarded'
152
+ },
153
+ [`${BASH_BIN}/wasm-run`]: { command: 'wasm-run' },
154
+ ...shellRoutes
155
+ };
156
+ const sysroots = new Map();
157
+ let session;
158
+ let starting;
159
+ let disposal;
160
+ const stop = new AbortController();
161
+ const prepareSysroot = async (requestedProfile, signal) => {
162
+ if (requestedProfile !== 'c' && requestedProfile !== 'full')
163
+ throw new Error('Unknown Clang sysroot profile');
164
+ const profile = !layers || requestedProfile === 'full' || sysroots.has('full') ? 'full' : 'c';
165
+ const root = profile === 'c' ? C_SYSROOT : BASH_SYSROOT;
166
+ const args = [
167
+ ...(profile === 'c'
168
+ ? [`--sysroot=${C_SYSROOT}`, `-resource-dir=${C_SYSROOT}/lib/clang/22`]
169
+ : []),
170
+ ...clangSimdDriverArgs(root)
171
+ ];
172
+ if (sysroots.has(profile))
173
+ return args;
174
+ // Each consumer owns its signal; the verified asset loader shares only fetches.
175
+ const prepared = await manager.prepare('llvm', { signal });
176
+ let archive;
177
+ if (layers) {
178
+ const base = await manager.prepare(layers.basePackage, { signal });
179
+ archive = base.packages
180
+ .find((pkg) => pkg.id === layers.basePackage)
181
+ ?.files.find((file) => file.path === 'sysroot.tar')?.bytes;
182
+ if (!archive)
183
+ throw new Error('Pinned LLVM profile has no base sysroot archive');
184
+ if (profile === 'full') {
185
+ const cxx = await manager.prepare(layers.cxxPackage, { signal });
186
+ const delta = cxx.packages
187
+ .find((pkg) => pkg.id === layers.cxxPackage)
188
+ ?.files.find((file) => file.path === 'sysroot.tar')?.bytes;
189
+ if (!delta)
190
+ throw new Error('Pinned LLVM profile has no C++ sysroot archive');
191
+ archive = composeSysrootLayers(archive, delta);
192
+ }
193
+ }
194
+ else
195
+ archive = prepared.packages
196
+ .find((pkg) => pkg.id === 'llvm')
197
+ ?.files.find((file) => file.path === 'sysroot.tar')?.bytes;
198
+ if (!archive)
199
+ throw new Error('Pinned LLVM profile has no sysroot archive');
200
+ const sha256 = await digest(archive);
201
+ signal.throwIfAborted();
202
+ if (layers &&
203
+ profile === 'full' &&
204
+ (archive.length !== layers.full.bytes || sha256 !== layers.full.sha256))
205
+ throw new Error('Composed sysroot does not match its pinned identity');
206
+ const entries = extractTarPackage(archive);
207
+ const metadata = {
208
+ sha256,
209
+ entries: entries.length,
210
+ files: entries.filter((file) => file.type === 'file').length
211
+ };
212
+ signal.throwIfAborted();
213
+ if (!sysroots.has(profile)) {
214
+ // The archive identity describes upstream bytes. Add the trusted application's
215
+ // SIMD headers only after verification, leaving its Clang resource headers intact.
216
+ const mounted = new Map(entries.map((entry) => [entry.path, entry]));
217
+ installClangSimdHeaders({
218
+ mkdirTree(path) {
219
+ let parent = '';
220
+ for (const part of path.slice(1).split('/')) {
221
+ parent = parent ? `${parent}/${part}` : part;
222
+ const existing = mounted.get(parent);
223
+ if (existing && existing.type !== 'directory')
224
+ throw new Error('SIMD header directory conflicts with the pinned sysroot');
225
+ if (!existing)
226
+ mounted.set(parent, { path: parent, type: 'directory', mode: 0o555 });
227
+ }
228
+ },
229
+ writeFile(path, data) {
230
+ const relative = path.slice(1);
231
+ if (mounted.has(relative))
232
+ throw new Error('SIMD header conflicts with the pinned sysroot');
233
+ mounted.set(relative, { path: relative, type: 'file', mode: 0o444, data });
234
+ }
235
+ });
236
+ container.fs.mountReadonly(root, withCanonicalWasiPaths([...mounted.values()]));
237
+ sysroots.set(profile, metadata);
238
+ }
239
+ return args;
240
+ };
241
+ const prepareCommand = async (invocation, signal) => {
242
+ onInvocation?.(invocation);
243
+ if (invocation.path === `${BASH_BIN}/clang`)
244
+ await prepareSysroot('full', signal);
245
+ };
246
+ return Object.freeze({
247
+ container,
248
+ manager,
249
+ shellAssets,
250
+ workers,
251
+ cache,
252
+ clangFilesystem: filesystem,
253
+ sysrootProfile: layers ? 'c-base-v1' : 'full',
254
+ inspectSysroot: (profile = 'full') => sysroots.get(profile) ?? null,
255
+ prepareCommand,
256
+ prepareClang(profile, signal) {
257
+ onInvocation?.({
258
+ path: `${BASH_BIN}/clang`,
259
+ argv: ['clang'],
260
+ env: [],
261
+ cwd: '/workspace',
262
+ stdin: null,
263
+ stdout: null,
264
+ stderr: null
265
+ });
266
+ return prepareSysroot(profile, signal);
267
+ },
268
+ startShell(options = {}, signal) {
269
+ if (starting || stop.signal.aborted)
270
+ return Promise.reject(new Error('The dedicated Bash owner has already started or retired'));
271
+ starting = createWasixShellSession({
272
+ container,
273
+ sdk,
274
+ workers,
275
+ assets: shellAssets,
276
+ sdkAsset: config.sdkAsset ?? { packageId: 'shell', assetId: 'sdk' },
277
+ shellAsset: config.shellAsset ?? { packageId: 'shell', assetId: 'bash' },
278
+ shellWasmSha256: config.bashWasmSha256,
279
+ sdkUrl: config.sdkUrl,
280
+ workerUrl: config.sdkWorkerUrl,
281
+ memory: config.memory,
282
+ routes,
283
+ mounts: options.mounts,
284
+ moduleDirectories: ['/workspace'],
285
+ timeoutMs: config.commandTimeoutMs,
286
+ args: options.args ?? ['--noprofile', '--norc'],
287
+ cwd: options.cwd ?? '/workspace',
288
+ env: {
289
+ PATH: `${BASH_BIN}:/usr/bin:/bin`,
290
+ HOME: '/workspace',
291
+ LANG: 'C',
292
+ ...options.env
293
+ },
294
+ signal: signal ? AbortSignal.any([signal, stop.signal]) : stop.signal,
295
+ prepareCommand,
296
+ onRecord
297
+ }).then((value) => {
298
+ session = value;
299
+ return value;
300
+ });
301
+ return starting;
302
+ },
303
+ dispose() {
304
+ return (disposal ??= (async () => {
305
+ stop.abort();
306
+ const errors = [];
307
+ for (const cleanup of [
308
+ () => workers.dispose(),
309
+ () => session?.dispose(),
310
+ () => container.dispose(),
311
+ () => compiler?.clearModuleCache?.(),
312
+ () => manager.dispose(),
313
+ () => shellAssets.dispose()
314
+ ]) {
315
+ try {
316
+ await cleanup();
317
+ }
318
+ catch (error) {
319
+ errors.push(error);
320
+ }
321
+ }
322
+ await starting?.catch(() => { });
323
+ if (errors.length)
324
+ throw new AggregateError(errors, 'Bash profile cleanup failed');
325
+ })());
326
+ }
327
+ });
328
+ }
@@ -1,19 +1,33 @@
1
- import type { PlaygroundBinding, SandboxRuntimeAssets } from '../sandbox';
2
- import type { TerminalShellBinding } from '@wasm-idle/terminal';
1
+ import type { PlaygroundBinding, SandboxRuntimeAssets } from '../playground/sandbox.js';
3
2
  import type { WorkspaceFile as ContainerWorkspaceFile } from '@wasm-idle/core';
4
- import { type ContainerWorkerClient } from './client';
5
- import type { ContainerWorkerEvent, ContainerWorkspaceEntry } from './protocol';
6
- type BindingOptions = {
3
+ import { type ContainerWorkerClient, type ContainerOwnerWorker } from './client.js';
4
+ import type { ContainerWorkerEvent, ContainerWorkspaceEntry } from './protocol.js';
5
+ export type ContainerPlaygroundBindingOptions = {
7
6
  applicationRootURL: string;
8
7
  workspaceId: string;
9
8
  getLanguage?: () => string;
9
+ /** The app bundles this worker entry; no worker is created until first use. */
10
+ workerFactory?: () => ContainerOwnerWorker;
10
11
  /** Deterministic transport contract tests only. */
11
12
  clientFactory?: () => ContainerWorkerClient;
12
13
  };
14
+ /** Structurally compatible with terminal UIs without depending on their components. */
15
+ export interface ContainerShellBinding {
16
+ connect(onOutput: (text: string) => void, onError?: (error: unknown) => void): Promise<void>;
17
+ write(text: string): Promise<void>;
18
+ eof(): Promise<void>;
19
+ interrupt(): Promise<void>;
20
+ dispose(): Promise<void>;
21
+ }
13
22
  export interface ContainerPlaygroundBinding extends PlaygroundBinding {
14
- readonly shell: TerminalShellBinding;
23
+ readonly shell: ContainerShellBinding;
24
+ dispose(): Promise<void>;
15
25
  inspect(): Promise<unknown>;
16
26
  setShellDirectory(language: string): Promise<void>;
27
+ /** Claim the shared display at Bash's real primary prompt without consuming its input. */
28
+ beginTerminalExecution(): Promise<void>;
29
+ /** Redraw the actual Bash prompt after the Terminal has written its execution footer. */
30
+ endTerminalExecution(): Promise<void>;
17
31
  syncWorkspace(language: string, files: readonly ContainerWorkspaceFile[]): Promise<void>;
18
32
  readWorkspace(language: string): Promise<ContainerWorkspaceFile[]>;
19
33
  listWorkspaceFiles(): Promise<ContainerWorkspaceEntry[]>;
@@ -22,5 +36,4 @@ export interface ContainerPlaygroundBinding extends PlaygroundBinding {
22
36
  onWorkspaceChange(listener: (event: ContainerWorkerEvent) => void): () => void;
23
37
  }
24
38
  /** Existing Terminal/Debug controls use this facade; every execution belongs to the owner Container. */
25
- export declare function createContainerPlaygroundBinding(runtimeAssets: SandboxRuntimeAssets, options: BindingOptions): ContainerPlaygroundBinding;
26
- export {};
39
+ export declare function createContainerPlaygroundBinding(runtimeAssets: SandboxRuntimeAssets, options: ContainerPlaygroundBindingOptions): ContainerPlaygroundBinding;
@@ -1,31 +1,31 @@
1
- import { createContainerWorkerClient } from './client';
1
+ import { createContainerWorkerClient } from './client.js';
2
2
  const copyFiles = (files) => files.map((file) => ({
3
3
  path: file.path,
4
4
  content: typeof file.content === 'string' ? file.content : Uint8Array.from(file.content)
5
5
  }));
6
6
  const bytes = (content) => typeof content === 'string' ? new TextEncoder().encode(content) : content;
7
7
  const equal = (left, right) => {
8
+ if (left === right)
9
+ return true;
8
10
  const a = bytes(left), b = bytes(right);
9
11
  return a.length === b.length && a.every((byte, index) => byte === b[index]);
10
12
  };
11
- function sameFiles(left, right) {
12
- return (left.length === right.length &&
13
- left.every((file) => {
14
- const other = right.find((candidate) => candidate.path === file.path);
15
- return other && equal(file.content, other.content);
16
- }));
17
- }
18
13
  /** Existing Terminal/Debug controls use this facade; every execution belongs to the owner Container. */
19
14
  export function createContainerPlaygroundBinding(runtimeAssets, options) {
15
+ if (!options.workerFactory && !options.clientFactory)
16
+ throw new TypeError('A container owner workerFactory is required');
20
17
  let client, disposed = false;
21
18
  const sandboxes = new Map();
22
19
  const published = new Map();
23
20
  const changes = new Set();
24
21
  const queues = new Map();
22
+ const reads = new Map();
23
+ const readQueues = new Map();
25
24
  let shellOutput;
26
25
  let shellError;
27
26
  let shellConnection;
28
27
  let requestedShellLanguage;
28
+ let terminalExecution = false;
29
29
  const decoders = new Map();
30
30
  const decoder = (key) => {
31
31
  let value = decoders.get(key);
@@ -43,7 +43,8 @@ export function createContainerPlaygroundBinding(runtimeAssets, options) {
43
43
  createContainerWorkerClient({
44
44
  runtimeAssets,
45
45
  applicationRootURL: options.applicationRootURL,
46
- workspaceId: options.workspaceId
46
+ workspaceId: options.workspaceId,
47
+ workerFactory: options.workerFactory
47
48
  });
48
49
  client.onEvent((event) => {
49
50
  if (event.name === 'workspace') {
@@ -77,6 +78,18 @@ export function createContainerPlaygroundBinding(runtimeAssets, options) {
77
78
  });
78
79
  return client;
79
80
  };
81
+ const cleanupOwner = async (method, args = []) => {
82
+ if (!client || disposed)
83
+ return;
84
+ try {
85
+ await client.call(method, args);
86
+ }
87
+ catch (error) {
88
+ // Terminal cleanup can race the parent disposing the complete owner.
89
+ if (!disposed)
90
+ throw error;
91
+ }
92
+ };
80
93
  const syncWorkspace = (language, files) => {
81
94
  const snapshot = copyFiles(files);
82
95
  const previous = queues.get(language) ?? Promise.resolve();
@@ -84,14 +97,36 @@ export function createContainerPlaygroundBinding(runtimeAssets, options) {
84
97
  .catch(() => { })
85
98
  .then(async () => {
86
99
  const baseline = published.get(language);
87
- if (baseline && sameFiles(baseline, snapshot))
88
- return;
89
- await connection().call('syncWorkspace', [
90
- language,
91
- snapshot,
92
- baseline && copyFiles(baseline)
93
- ]);
94
- published.set(language, copyFiles(snapshot));
100
+ if (baseline) {
101
+ const before = new Map(baseline.map((file) => [file.path, file]));
102
+ const changed = [];
103
+ const expected = [];
104
+ for (const file of snapshot) {
105
+ const previous = before.get(file.path);
106
+ before.delete(file.path);
107
+ if (previous && equal(previous.content, file.content))
108
+ continue;
109
+ changed.push(file);
110
+ if (previous)
111
+ expected.push(previous);
112
+ }
113
+ expected.push(...before.values());
114
+ if (!changed.length && !expected.length)
115
+ return;
116
+ await connection().call('syncWorkspaceDelta', [
117
+ language,
118
+ changed,
119
+ expected,
120
+ snapshot.map((file) => ({
121
+ path: file.path,
122
+ bytes: bytes(file.content).byteLength
123
+ }))
124
+ ]);
125
+ }
126
+ else
127
+ await connection().call('syncWorkspace', [language, snapshot, undefined]);
128
+ // snapshot already owns its bytes, including while queued behind another write.
129
+ published.set(language, snapshot);
95
130
  });
96
131
  queues.set(language, next);
97
132
  return next;
@@ -104,7 +139,10 @@ export function createContainerPlaygroundBinding(runtimeAssets, options) {
104
139
  const language = requestedShellLanguage ?? options.getLanguage?.() ?? 'CPP';
105
140
  await queues.get(language)?.catch(() => { });
106
141
  await connection().call('shellStart', [
107
- { cwd: `/workspace/${language}`, env: { PS1: '\\w $ ' } }
142
+ {
143
+ cwd: `/workspace/${language}`,
144
+ env: { PS1: '\\[\\e[1;34m\\]\\w\\[\\e[0m\\] $ ' }
145
+ }
108
146
  ]);
109
147
  })());
110
148
  },
@@ -121,11 +159,29 @@ export function createContainerPlaygroundBinding(runtimeAssets, options) {
121
159
  await connection().call('shellInterrupt');
122
160
  },
123
161
  async dispose() {
124
- if (client && !disposed)
125
- await client.call('shellDispose');
162
+ await cleanupOwner('shellDispose');
126
163
  }
127
164
  };
128
165
  const binding = {
166
+ async beginTerminalExecution() {
167
+ if (terminalExecution || !shellConnection || disposed)
168
+ return;
169
+ // A shell unavailable without cross-origin isolation must not block batch Run.
170
+ try {
171
+ await shellConnection;
172
+ }
173
+ catch {
174
+ return;
175
+ }
176
+ await connection().call('shellSuspend');
177
+ terminalExecution = true;
178
+ },
179
+ async endTerminalExecution() {
180
+ if (!terminalExecution)
181
+ return;
182
+ terminalExecution = false;
183
+ await cleanupOwner('shellResume');
184
+ },
129
185
  async setShellDirectory(language) {
130
186
  if (!/^[A-Z][A-Z0-9_]*$/.test(language))
131
187
  throw new TypeError('Invalid shell language');
@@ -165,7 +221,7 @@ export function createContainerPlaygroundBinding(runtimeAssets, options) {
165
221
  }
166
222
  },
167
223
  async clear() {
168
- await invoke('clear');
224
+ await cleanupOwner('clear', [language]);
169
225
  },
170
226
  async restart() {
171
227
  await invoke('restart');
@@ -177,8 +233,7 @@ export function createContainerPlaygroundBinding(runtimeAssets, options) {
177
233
  await invoke('stop');
178
234
  },
179
235
  async dispose() {
180
- if (client && !disposed)
181
- await invoke('clear');
236
+ await cleanupOwner('clear', [language]);
182
237
  },
183
238
  write(text) {
184
239
  void invoke('write', [text]).catch((error) => shellError?.(error));
@@ -191,7 +246,10 @@ export function createContainerPlaygroundBinding(runtimeAssets, options) {
191
246
  'debugCommand',
192
247
  'debugPause',
193
248
  'setBreakpoints',
249
+ 'setSourceBreakpoints',
194
250
  'debugEvaluate',
251
+ 'debugEvaluateValue',
252
+ 'debugSetSteppingOptions',
195
253
  'debugVariables',
196
254
  'debugScopes',
197
255
  'debugFrameScopes',
@@ -215,8 +273,32 @@ export function createContainerPlaygroundBinding(runtimeAssets, options) {
215
273
  async cancelPrewarm() { },
216
274
  syncWorkspace,
217
275
  async readWorkspace(language) {
218
- await queues.get(language)?.catch(() => { });
219
- return await connection().call('readWorkspace', [language]);
276
+ const previous = readQueues.get(language);
277
+ const next = (async () => {
278
+ await previous?.catch(() => { });
279
+ await queues.get(language)?.catch(() => { });
280
+ const baseline = reads.get(language);
281
+ const delta = await connection().call('readWorkspaceDelta', [language, baseline?.revision]);
282
+ if (disposed)
283
+ throw new Error('Container playground has been disposed');
284
+ const files = new Map(delta.reset ? [] : baseline?.files);
285
+ for (const path of delta.deleted)
286
+ files.delete(path);
287
+ for (const file of delta.files)
288
+ files.set(file.path, file);
289
+ reads.set(language, { revision: delta.revision, files });
290
+ // Match the owner's sorted directory traversal after incremental additions.
291
+ return copyFiles([...files.values()].sort((left, right) => {
292
+ const a = left.path.split('/'), b = right.path.split('/');
293
+ for (let index = 0; index < Math.min(a.length, b.length); index++) {
294
+ if (a[index] !== b[index])
295
+ return a[index] < b[index] ? -1 : 1;
296
+ }
297
+ return a.length - b.length;
298
+ }));
299
+ })();
300
+ readQueues.set(language, next);
301
+ return await next;
220
302
  },
221
303
  async listWorkspaceFiles() {
222
304
  return await connection().call('listWorkspaceFiles');
@@ -239,6 +321,8 @@ export function createContainerPlaygroundBinding(runtimeAssets, options) {
239
321
  return;
240
322
  disposed = true;
241
323
  changes.clear();
324
+ reads.clear();
325
+ readQueues.clear();
242
326
  await client?.dispose();
243
327
  }
244
328
  };
@@ -1,14 +1,16 @@
1
- import type { Container } from '@wasm-idle/container';
2
- import { type SandboxExecutionOptions } from '../options';
1
+ import type { Container, HostCommandInvocation } from '@wasm-idle/container';
2
+ import { type SandboxExecutionOptions } from '../playground/options.js';
3
3
  import type { ProgressLike } from '@wasm-idle/core';
4
- import type { ContainerWorkerEvent } from './protocol';
5
- import type { WebsiteRuntimeAdapter } from './runtime-adapter';
4
+ import type { ContainerWorkerEvent } from './protocol.js';
5
+ import type { WebsiteRuntimeAdapter } from './runtime-adapter.js';
6
6
  type Profile = {
7
7
  container: Container;
8
- prepareCommand(invocation: unknown, signal: AbortSignal): Promise<void>;
8
+ sysrootProfile?: 'full' | 'c-base-v1';
9
+ prepareCommand(invocation: HostCommandInvocation, signal: AbortSignal): Promise<void>;
10
+ prepareClang?(profile: 'c' | 'full', signal: AbortSignal): Promise<readonly string[]>;
9
11
  };
10
12
  /** The Run button uses the same real Clang command and artifacts as Bash. Debug uses its qualified backend. */
11
- export declare class WebsiteClangRuntime {
13
+ export declare class ContainerClangRuntime {
12
14
  #private;
13
15
  private readonly profile;
14
16
  private readonly files;
@@ -16,6 +18,8 @@ export declare class WebsiteClangRuntime {
16
18
  constructor(profile: Profile, files: WebsiteRuntimeAdapter, emit: (event: ContainerWorkerEvent) => void);
17
19
  private queue;
18
20
  private key;
21
+ private currentProgram;
22
+ private spawn;
19
23
  private drain;
20
24
  private success;
21
25
  private headerKey;
@@ -35,4 +39,4 @@ export declare class WebsiteClangRuntime {
35
39
  }[];
36
40
  dispose(): Promise<void>;
37
41
  }
38
- export {};
42
+ export { ContainerClangRuntime as WebsiteClangRuntime };