wasm-idle 1.2.0 → 1.4.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 (105) hide show
  1. package/README.md +250 -146
  2. package/dist/container/clang-runtime.js +32 -8
  3. package/dist/container/runtime-adapter.d.ts +2 -0
  4. package/dist/container/runtime-adapter.js +37 -8
  5. package/dist/index.d.ts +1 -0
  6. package/dist/index.js +1 -0
  7. package/dist/playground/assetBridge.js +10 -8
  8. package/dist/playground/assets.d.ts +4 -0
  9. package/dist/playground/assets.js +9 -4
  10. package/dist/playground/c3.js +1 -1
  11. package/dist/playground/compiledLldb.d.ts +2 -0
  12. package/dist/playground/compiledLldb.js +37 -2
  13. package/dist/playground/d.d.ts +1 -0
  14. package/dist/playground/d.js +18 -8
  15. package/dist/playground/index.d.ts +1 -1
  16. package/dist/playground/index.js +7 -0
  17. package/dist/playground/{java-debug-FMHDKUN6.js → java-debug-64JGCLTC.js} +1 -1
  18. package/dist/playground/java-debug-notices.txt +26 -1
  19. package/dist/playground/java.js +3 -2
  20. package/dist/playground/javaDebugBridge.js +42 -7
  21. package/dist/playground/javaDebugSource.js +4 -4
  22. package/dist/playground/javaMain.d.ts +3 -0
  23. package/dist/playground/javaMain.js +2 -0
  24. package/dist/playground/javaRuntimeErrors.d.ts +2 -1
  25. package/dist/playground/javaRuntimeErrors.js +9 -2
  26. package/dist/playground/javaSource.d.ts +1 -1
  27. package/dist/playground/javaSource.js +7 -2
  28. package/dist/playground/lldbSession.d.ts +2 -0
  29. package/dist/playground/lldbSession.js +60 -4
  30. package/dist/playground/objectivec.d.ts +1 -1
  31. package/dist/playground/objectivec.js +2 -1
  32. package/dist/playground/options.d.ts +1 -1
  33. package/dist/playground/python.d.ts +3 -0
  34. package/dist/playground/python.js +122 -2
  35. package/dist/playground/pythonCompileOptions.d.ts +52 -0
  36. package/dist/playground/pythonCompileOptions.js +40 -0
  37. package/dist/playground/scala.d.ts +34 -0
  38. package/dist/playground/scala.js +397 -0
  39. package/dist/playground/scalaAssets.d.ts +16 -0
  40. package/dist/playground/scalaAssets.js +51 -0
  41. package/dist/playground/scalaDiagnostics.d.ts +3 -0
  42. package/dist/playground/scalaDiagnostics.js +29 -0
  43. package/dist/playground/staticRuntimeModuleVersion.d.ts +1 -1
  44. package/dist/playground/staticRuntimeModuleVersion.js +1 -1
  45. package/dist/playground/staticWorkerRuntime.d.ts +2 -0
  46. package/dist/playground/staticWorkerRuntime.js +85 -11
  47. package/dist/playground/tinygo.js +21 -8
  48. package/dist/playground/tinygoExecutableGraph.js +1 -1
  49. package/dist/playground/v.d.ts +1 -0
  50. package/dist/playground/v.js +17 -7
  51. package/dist/playground/wasmC3Version.d.ts +8 -8
  52. package/dist/playground/wasmC3Version.js +8 -8
  53. package/dist/playground/wasmDebugVersion.d.ts +1 -1
  54. package/dist/playground/wasmDebugVersion.js +1 -1
  55. package/dist/playground/wasmDotnetVersion.d.ts +1 -1
  56. package/dist/playground/wasmDotnetVersion.js +1 -1
  57. package/dist/playground/wasmGoVersion.d.ts +1 -1
  58. package/dist/playground/wasmGoVersion.js +1 -1
  59. package/dist/playground/wasmLispVersion.d.ts +5 -0
  60. package/dist/playground/wasmLispVersion.js +5 -0
  61. package/dist/playground/wasmOcamlVersion.d.ts +4 -4
  62. package/dist/playground/wasmOcamlVersion.js +3 -3
  63. package/dist/playground/wasmPrologVersion.d.ts +17 -17
  64. package/dist/playground/wasmPrologVersion.js +16 -16
  65. package/dist/playground/wasmTinyGoVersion.d.ts +57 -57
  66. package/dist/playground/wasmTinyGoVersion.js +57 -57
  67. package/dist/playground/wasmTypeScriptVersion.d.ts +3 -3
  68. package/dist/playground/wasmTypeScriptVersion.js +3 -3
  69. package/dist/playground/wasmZigVersion.d.ts +7 -7
  70. package/dist/playground/wasmZigVersion.js +7 -7
  71. package/dist/playground/worker/java.js +18 -4
  72. package/dist/playground/worker/javaDebugEvaluator.js +2 -2
  73. package/dist/playground/worker/javaDebugRuntime.js +8 -1
  74. package/dist/playground/worker/javaStreaming.js +4 -2
  75. package/dist/playground/worker/ocaml.js +11 -10
  76. package/dist/playground/worker/python.js +45 -165
  77. package/dist/playground/worker/pythonCompile.d.ts +4 -0
  78. package/dist/playground/worker/pythonCompile.js +127 -0
  79. package/dist/playground/worker/pythonDebug.d.ts +20 -0
  80. package/dist/playground/worker/pythonDebug.js +205 -0
  81. package/dist/playground/worker/scala/UPSTREAM-LICENSE.txt +201 -0
  82. package/dist/playground/worker/scala/UPSTREAM-NOTICE.txt +108 -0
  83. package/dist/playground/worker/scala/asset-bootstrap.d.ts +6 -0
  84. package/dist/playground/worker/scala/asset-bootstrap.js +58 -0
  85. package/dist/playground/worker/scala/asset-receipts.d.ts +7 -0
  86. package/dist/playground/worker/scala/asset-receipts.js +58 -0
  87. package/dist/playground/worker/scala/compiler.worker.d.ts +1 -0
  88. package/dist/playground/worker/scala/compiler.worker.js +204 -0
  89. package/dist/playground/worker/scala/execution.worker.d.ts +1 -0
  90. package/dist/playground/worker/scala/execution.worker.js +89 -0
  91. package/dist/playground/worker/scala/memory-fs.d.ts +29 -0
  92. package/dist/playground/worker/scala/memory-fs.js +333 -0
  93. package/dist/playground/worker/scala/runner.d.ts +1 -0
  94. package/dist/playground/worker/scala/runner.js +36 -0
  95. package/dist/playground/worker/zig.d.ts +2 -1
  96. package/dist/playground/worker/zig.js +212 -86
  97. package/dist/playground/worker/zigDebug.d.ts +39 -0
  98. package/dist/playground/worker/zigDebug.js +156 -0
  99. package/dist/playground/zig.d.ts +27 -4
  100. package/dist/playground/zig.js +266 -23
  101. package/dist/playground/zigDebugValues.d.ts +20 -0
  102. package/dist/playground/zigDebugValues.js +248 -0
  103. package/dist/pythonCompiler.d.ts +8 -0
  104. package/dist/pythonCompiler.js +52 -0
  105. package/package.json +37 -26
@@ -0,0 +1,204 @@
1
+ // @ts-nocheck -- upstream Scala.js compiler and virtual FS APIs are untyped; host boundary is typed.
2
+ import { createMemoryFileSystem } from './memory-fs.js';
3
+ import { runnerSource } from './runner.js';
4
+ import { loadScalaCompilerAssets } from './asset-bootstrap.js';
5
+
6
+ const assets = new URL('../../../../../runtimes/wasm-scala/assets/', import.meta.url);
7
+ let runtimePromise;
8
+ let busy = false;
9
+
10
+ async function initialize(payload) {
11
+ const wasm = globalThis.WebAssembly;
12
+ const missing = ['JSTag', 'Suspending', 'promising'].filter((name) =>
13
+ name === 'JSTag' ? typeof wasm?.JSTag === 'undefined' : typeof wasm?.[name] !== 'function'
14
+ );
15
+ if (missing.length)
16
+ throw new Error(`Scala compiler requires WebAssembly ${missing.join(', ')}.`);
17
+ if (payload) return initializeVerifiedRuntime(payload);
18
+ const fs = createMemoryFileSystem();
19
+ globalThis.__scala3CompilerSJSHostFS = fs.hostFS;
20
+ const manifestResponse = await fetch(new URL('manifest.json', assets));
21
+ if (!manifestResponse.ok) throw new Error(`Scala manifest HTTP ${manifestResponse.status}`);
22
+ const manifest = await manifestResponse.json();
23
+ // Upstream manifest URLs are relative to its browser-ide root, not the manifest.
24
+ const base = new URL('../', assets);
25
+ await Promise.all(
26
+ manifest.classpath.map(async (entry) => {
27
+ const response = await fetch(new URL(entry.url, base));
28
+ if (!response.ok) throw new Error(`Scala classpath HTTP ${response.status}`);
29
+ fs.writeBinary(entry.path, new Uint8Array(await response.arrayBuffer()));
30
+ })
31
+ );
32
+ const compiler = await import(/* @vite-ignore */ new URL(manifest.compilerModule, base).href);
33
+ const { default: JSZip } = await import(
34
+ /* @vite-ignore */ new URL('vendor/jszip-wrapper.js', assets).href
35
+ );
36
+ const response = await fetch(new URL(manifest.runtimeIR, base));
37
+ if (!response.ok) throw new Error(`Scala runtime IR HTTP ${response.status}`);
38
+ const zip = await JSZip.loadAsync(await response.arrayBuffer());
39
+ const ir = await Promise.all(
40
+ Object.values(zip.files)
41
+ .filter((entry) => !entry.dir && entry.name.endsWith('.sjsir'))
42
+ .sort((a, b) => a.name.localeCompare(b.name))
43
+ .map(async (entry) => ({
44
+ path: `/runtime/${entry.name}`,
45
+ bytes: await entry.async('uint8array')
46
+ }))
47
+ );
48
+ return { fs, compiler, manifest, ir };
49
+ }
50
+
51
+ async function initializeVerifiedRuntime(payload) {
52
+ const fs = createMemoryFileSystem();
53
+ globalThis.__scala3CompilerSJSHostFS = fs.hostFS;
54
+ const { compiler, JSZip } = await loadScalaCompilerAssets(payload);
55
+ const manifest = JSON.parse(new TextDecoder().decode(payload['manifest.json']));
56
+ for (const entry of manifest.classpath) {
57
+ const name = entry.url.replace(/^\.\/assets\//u, '');
58
+ if (!payload[name]) throw new Error('Scala classpath manifest is inconsistent.');
59
+ fs.writeBinary(entry.path, payload[name]);
60
+ }
61
+ const zip = await JSZip.loadAsync(payload['runtime/runtime-sjsir.zip']);
62
+ const ir = await Promise.all(
63
+ Object.values(zip.files)
64
+ .filter((entry) => !entry.dir && entry.name.endsWith('.sjsir'))
65
+ .sort((a, b) => a.name.localeCompare(b.name))
66
+ .map(async (entry) => ({
67
+ path: `/runtime/${entry.name}`,
68
+ bytes: await entry.async('uint8array')
69
+ }))
70
+ );
71
+ return { fs, compiler, manifest, ir };
72
+ }
73
+
74
+ self.onmessage = async ({ data }) => {
75
+ const { id, files, runtimeAssets, type, limits = {} } = data;
76
+ if (busy) {
77
+ self.postMessage({ id, type: 'error', message: 'Scala compiler is busy', diagnostics: [] });
78
+ return;
79
+ }
80
+ busy = true;
81
+ const diagnostics = [];
82
+ const originals = new Map();
83
+ let diagnosticBytes = 0;
84
+ let diagnosticCount = 0;
85
+ let diagnosticLimitError;
86
+ const maxDiagnostics = Math.min(1000, limits.maxDiagnostics ?? 100);
87
+ const maxDiagnosticBytes = Math.min(1024 * 1024, limits.maxDiagnosticBytes ?? 1024 * 1024);
88
+ try {
89
+ if (
90
+ !Number.isSafeInteger(maxDiagnostics) ||
91
+ maxDiagnostics < 0 ||
92
+ !Number.isSafeInteger(maxDiagnosticBytes) ||
93
+ maxDiagnosticBytes <= 0
94
+ )
95
+ throw new Error('Invalid Scala diagnostic limits.');
96
+ if (type === 'initialize') {
97
+ if (!runtimeAssets)
98
+ throw new Error('Scala initialization requires verified asset bytes.');
99
+ runtimePromise ??= initialize(runtimeAssets).catch((error) => {
100
+ runtimePromise = undefined;
101
+ throw error;
102
+ });
103
+ await runtimePromise;
104
+ self.postMessage({ id, type: 'ready' });
105
+ return;
106
+ }
107
+ if (!Array.isArray(files) || files.length === 0 || files.length > 64)
108
+ throw new Error('Provide 1–64 Scala source files.');
109
+ const seen = new Set();
110
+ let bytes = 0;
111
+ for (const file of files) {
112
+ if (
113
+ typeof file.path !== 'string' ||
114
+ !/^(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+\.scala$/.test(file.path) ||
115
+ file.path === 'WasmIdleScalaRunner.scala' ||
116
+ seen.has(file.path) ||
117
+ typeof file.content !== 'string'
118
+ )
119
+ throw new Error('Invalid or duplicate Scala source path.');
120
+ seen.add(file.path);
121
+ bytes += new TextEncoder().encode(file.content).length;
122
+ }
123
+ if (bytes > 1024 * 1024) throw new Error('Scala source exceeds 1 MiB.');
124
+ const initializeStart = performance.now();
125
+ runtimePromise ??= initialize(runtimeAssets).catch((error) => {
126
+ runtimePromise = undefined;
127
+ throw error;
128
+ });
129
+ const { fs, compiler, manifest, ir } = await runtimePromise;
130
+ const initializeMs = performance.now() - initializeStart;
131
+ fs.removeTree('/workspace');
132
+ fs.mkdir('/workspace/out');
133
+ for (const file of files) fs.writeText(`/workspace/${file.path}`, file.content);
134
+ fs.writeText('/workspace/WasmIdleScalaRunner.scala', runnerSource);
135
+ for (const method of ['log', 'warn', 'error']) {
136
+ originals.set(method, console[method]);
137
+ console[method] = (...args) => {
138
+ if (diagnosticLimitError) throw diagnosticLimitError;
139
+ const text = args.map(String).join(' ');
140
+ diagnosticBytes += new TextEncoder().encode(text).byteLength;
141
+ const plain = text.replace(/\u001b\[[0-9;]*m/gu, '');
142
+ diagnosticCount += plain.split('\n').filter((line) => /^-- /u.test(line)).length;
143
+ if (diagnosticCount > maxDiagnostics || diagnosticBytes > maxDiagnosticBytes) {
144
+ diagnosticLimitError = new Error(
145
+ 'Scala compiler diagnostics exceed configured limits.'
146
+ );
147
+ diagnosticLimitError.limit =
148
+ diagnosticCount > maxDiagnostics ? maxDiagnostics : maxDiagnosticBytes;
149
+ diagnosticLimitError.actual =
150
+ diagnosticCount > maxDiagnostics ? diagnosticCount : diagnosticBytes;
151
+ throw diagnosticLimitError;
152
+ }
153
+ diagnostics.push(text);
154
+ };
155
+ }
156
+ const compileStart = performance.now();
157
+ const exitCode = await compiler.runScala3CompilerSJSAsync([
158
+ '-classpath',
159
+ manifest.classpath.map((entry) => entry.path).join(':'),
160
+ '-d',
161
+ '/workspace/out',
162
+ ...files.map((file) => `/workspace/${file.path}`),
163
+ '/workspace/WasmIdleScalaRunner.scala'
164
+ ]);
165
+ const compileMs = performance.now() - compileStart;
166
+ if (diagnosticLimitError) throw diagnosticLimitError;
167
+ if (exitCode !== 0) throw new Error(`Scala compiler exited with code ${exitCode}.`);
168
+ const generated = fs
169
+ .listFiles('/workspace/out')
170
+ .filter((path) => path.endsWith('.sjsir'))
171
+ .sort()
172
+ .map((path) => ({ path, bytes: fs.readBinary(path) }));
173
+ if (!generated.length) throw new Error('Scala compiler emitted no IR.');
174
+ const linkStart = performance.now();
175
+ const linked = await compiler.linkScalaJSModuleAsync(ir.concat(generated));
176
+ if (diagnosticLimitError) throw diagnosticLimitError;
177
+ if (typeof linked.code !== 'string' || !linked.code.length)
178
+ throw new Error('Scala linker emitted no code.');
179
+ self.postMessage({
180
+ id,
181
+ type: 'compiled',
182
+ code: linked.code,
183
+ diagnostics,
184
+ timings: { initializeMs, compileMs, linkMs: performance.now() - linkStart }
185
+ });
186
+ } catch (error) {
187
+ self.postMessage({
188
+ id,
189
+ type: 'error',
190
+ message: String(error),
191
+ diagnostics,
192
+ ...(diagnosticLimitError
193
+ ? {
194
+ failureKind: 'diagnostic-limit',
195
+ limit: diagnosticLimitError.limit,
196
+ actual: diagnosticLimitError.actual
197
+ }
198
+ : {})
199
+ });
200
+ } finally {
201
+ for (const [method, original] of originals) console[method] = original;
202
+ busy = false;
203
+ }
204
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,89 @@
1
+ // @ts-nocheck
2
+ // One execution per worker: the caller terminates this worker on exit, Stop, or timeout.
3
+ let started = false;
4
+ self.onmessage = async ({ data }) => {
5
+ if (started) return;
6
+ started = true;
7
+ const { id, code, stdin, args } = data;
8
+ const maxOutputBytes = Math.min(data.maxOutputBytes ?? 1024 * 1024, 1024 * 1024);
9
+ let url;
10
+ let outputBytes = 0;
11
+ let outputLimitError;
12
+ let terminalSent = false;
13
+ const reportError = (error) => {
14
+ if (terminalSent) return;
15
+ terminalSent = true;
16
+ self.postMessage({ id, type: 'error', message: String(error) });
17
+ };
18
+ try {
19
+ if (
20
+ typeof code !== 'string' ||
21
+ typeof stdin !== 'string' ||
22
+ !Array.isArray(args) ||
23
+ args.some((arg) => typeof arg !== 'string')
24
+ )
25
+ throw new Error('Invalid Scala execution request.');
26
+ if (
27
+ new TextEncoder().encode(code).length > 32 * 1024 * 1024 ||
28
+ new TextEncoder().encode(stdin).length > 1024 * 1024
29
+ )
30
+ throw new Error('Scala execution request exceeds limits.');
31
+ globalThis.wasmIdleScalaWrite = (stream, text) => {
32
+ if (outputLimitError) throw outputLimitError;
33
+ if (!['stdout', 'stderr'].includes(stream) || typeof text !== 'string')
34
+ throw new Error('Invalid Scala console write.');
35
+ outputBytes += new TextEncoder().encode(text).length;
36
+ if (outputBytes > maxOutputBytes) {
37
+ outputLimitError = new Error(
38
+ maxOutputBytes === 1024 * 1024
39
+ ? 'Scala output exceeds 1 MiB.'
40
+ : `Scala output exceeds ${maxOutputBytes} bytes.`
41
+ );
42
+ // Report before throwing: guest code can catch this exception or loop forever.
43
+ // The host can now terminate this execution even if the guest never returns.
44
+ reportError(outputLimitError);
45
+ throw outputLimitError;
46
+ }
47
+ self.postMessage({ id, type: stream, data: text });
48
+ };
49
+ const decoders = {
50
+ stdout: new TextDecoder('utf-8', { ignoreBOM: true }),
51
+ stderr: new TextDecoder('utf-8', { ignoreBOM: true })
52
+ };
53
+ globalThis.wasmIdleScalaWriteBytes = (stream, values) => {
54
+ if (outputLimitError) throw outputLimitError;
55
+ const decoder = decoders[stream];
56
+ if (!decoder) throw new Error('Invalid Scala stream.');
57
+ globalThis.wasmIdleScalaWrite(
58
+ stream,
59
+ decoder.decode(Uint8Array.from(values), { stream: true })
60
+ );
61
+ };
62
+ url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' }));
63
+ const module = await import(/* @vite-ignore */ url);
64
+ if (typeof module.runWasmIdleScala !== 'function')
65
+ throw new Error('Missing Scala entry export.');
66
+ self.postMessage({
67
+ id,
68
+ type: 'execution-ready',
69
+ progress: {
70
+ kind: 'ready',
71
+ state: 'running',
72
+ reason: 'started',
73
+ label: 'Running Scala.js'
74
+ }
75
+ });
76
+ await module.runWasmIdleScala(stdin, args);
77
+ if (outputLimitError) return;
78
+ for (const [stream, decoder] of Object.entries(decoders)) {
79
+ const tail = decoder.decode();
80
+ if (tail) globalThis.wasmIdleScalaWrite(stream, tail);
81
+ }
82
+ terminalSent = true;
83
+ self.postMessage({ id, type: 'exit', exitCode: 0 });
84
+ } catch (error) {
85
+ reportError(outputLimitError ?? error);
86
+ } finally {
87
+ if (url) URL.revokeObjectURL(url);
88
+ }
89
+ };
@@ -0,0 +1,29 @@
1
+ export function createMemoryFileSystem(): {
2
+ hostFS: {
3
+ cwd(): string;
4
+ existsSync(path: any): boolean;
5
+ statSync(path: any): {
6
+ size: any;
7
+ mtimeMs: any;
8
+ isFile(): boolean;
9
+ isDirectory(): boolean;
10
+ };
11
+ readdirSync(path: any): any[];
12
+ readFileSync(path: any): Uint8Array<any>;
13
+ readBinary(path: any): Uint8Array<any>;
14
+ mkdirSync(path: any, options?: {}): void;
15
+ writeFileSync(path: any, value: any): void;
16
+ appendFileSync(path: any, value: any): void;
17
+ rmSync(path: any, options?: {}): void;
18
+ rmdirSync(path: any, options?: {}): void;
19
+ unlinkSync(path: any): void;
20
+ truncateSync(path: any): void;
21
+ };
22
+ mkdir(path: any): void;
23
+ writeText(path: any, text: any): void;
24
+ writeBinary(path: any, bytes: any): void;
25
+ readText(path: any): string;
26
+ readBinary(path: any): Uint8Array<any>;
27
+ removeTree(path: any): void;
28
+ listFiles: (path: any) => any;
29
+ };
@@ -0,0 +1,333 @@
1
+ // @ts-nocheck -- adapted upstream virtual filesystem; see provenance below.
2
+ // Adapted from pgilliar/scala3-compiler-sjs, revision 357051c857d4ffd5d1e1bfc9a56f0cbf5943a325.
3
+ // Upstream compiler/browser-ide/memory-fs.js; Apache-2.0, see ./UPSTREAM-LICENSE.txt.
4
+ const textEncoder = new TextEncoder();
5
+ const textDecoder = new TextDecoder();
6
+
7
+ function normalizePath(inputPath) {
8
+ const rawPath = String(inputPath ?? '').replace(/\\/g, '/');
9
+ const absolutePath = rawPath.startsWith('/') ? rawPath : `/${rawPath}`;
10
+ const parts = absolutePath.split('/');
11
+ const normalized = [];
12
+
13
+ for (const part of parts) {
14
+ if (!part || part === '.') {
15
+ continue;
16
+ }
17
+ if (part === '..') {
18
+ normalized.pop();
19
+ continue;
20
+ }
21
+ normalized.push(part);
22
+ }
23
+
24
+ return normalized.length === 0 ? '/' : `/${normalized.join('/')}`;
25
+ }
26
+
27
+ function dirname(path) {
28
+ if (path === '/') {
29
+ return null;
30
+ }
31
+ const index = path.lastIndexOf('/');
32
+ return index <= 0 ? '/' : path.slice(0, index);
33
+ }
34
+
35
+ function basename(path) {
36
+ if (path === '/') {
37
+ return '/';
38
+ }
39
+ const index = path.lastIndexOf('/');
40
+ return path.slice(index + 1);
41
+ }
42
+
43
+ function cloneBytes(bytes) {
44
+ return new Uint8Array(bytes);
45
+ }
46
+
47
+ function toUint8Array(value) {
48
+ if (value instanceof Uint8Array) {
49
+ return cloneBytes(value);
50
+ }
51
+ if (value instanceof ArrayBuffer) {
52
+ return new Uint8Array(value.slice(0));
53
+ }
54
+ if (ArrayBuffer.isView(value)) {
55
+ return new Uint8Array(
56
+ value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength)
57
+ );
58
+ }
59
+ if (typeof value === 'string') {
60
+ return textEncoder.encode(value);
61
+ }
62
+ return Uint8Array.from(value ?? []);
63
+ }
64
+
65
+ function makeStat(entry) {
66
+ return {
67
+ size: entry.type === 'file' ? entry.bytes.length : 0,
68
+ mtimeMs: entry.mtimeMs,
69
+ isFile() {
70
+ return entry.type === 'file';
71
+ },
72
+ isDirectory() {
73
+ return entry.type === 'dir';
74
+ }
75
+ };
76
+ }
77
+
78
+ export function createMemoryFileSystem() {
79
+ const entries = new Map();
80
+ entries.set('/', {
81
+ type: 'dir',
82
+ children: new Set(),
83
+ mtimeMs: Date.now()
84
+ });
85
+
86
+ function getEntry(path) {
87
+ return entries.get(normalizePath(path)) ?? null;
88
+ }
89
+
90
+ function requireEntry(path) {
91
+ const entry = getEntry(path);
92
+ if (!entry) {
93
+ throw new Error(`No such file or directory: ${normalizePath(path)}`);
94
+ }
95
+ return entry;
96
+ }
97
+
98
+ function touch(entry) {
99
+ entry.mtimeMs = Date.now();
100
+ }
101
+
102
+ function ensureDirectory(path) {
103
+ const normalized = normalizePath(path);
104
+ if (normalized === '/') {
105
+ return entries.get('/');
106
+ }
107
+
108
+ const existing = entries.get(normalized);
109
+ if (existing) {
110
+ if (existing.type !== 'dir') {
111
+ throw new Error(`Not a directory: ${normalized}`);
112
+ }
113
+ return existing;
114
+ }
115
+
116
+ const parentPath = dirname(normalized) ?? '/';
117
+ const parent = ensureDirectory(parentPath);
118
+ const name = basename(normalized);
119
+ const created = {
120
+ type: 'dir',
121
+ children: new Set(),
122
+ mtimeMs: Date.now()
123
+ };
124
+
125
+ entries.set(normalized, created);
126
+ parent.children.add(name);
127
+ touch(parent);
128
+ return created;
129
+ }
130
+
131
+ function writeFile(path, value) {
132
+ const normalized = normalizePath(path);
133
+ const parentPath = dirname(normalized) ?? '/';
134
+ const parent = ensureDirectory(parentPath);
135
+ const existing = entries.get(normalized);
136
+ const nextBytes = toUint8Array(value);
137
+
138
+ if (existing && existing.type === 'dir') {
139
+ throw new Error(`Is a directory: ${normalized}`);
140
+ }
141
+
142
+ entries.set(normalized, {
143
+ type: 'file',
144
+ bytes: nextBytes,
145
+ mtimeMs: Date.now()
146
+ });
147
+ parent.children.add(basename(normalized));
148
+ touch(parent);
149
+ }
150
+
151
+ function deleteEntry(path, recursive, force) {
152
+ const normalized = normalizePath(path);
153
+ if (normalized === '/') {
154
+ if (force) {
155
+ const root = entries.get('/');
156
+ for (const child of [...root.children]) {
157
+ deleteEntry(`/${child}`, true, true);
158
+ }
159
+ return;
160
+ }
161
+ throw new Error('Cannot delete root directory');
162
+ }
163
+
164
+ const entry = entries.get(normalized);
165
+ if (!entry) {
166
+ if (force) {
167
+ return;
168
+ }
169
+ throw new Error(`No such file or directory: ${normalized}`);
170
+ }
171
+
172
+ if (entry.type === 'dir' && entry.children.size > 0 && !recursive) {
173
+ throw new Error(`Directory not empty: ${normalized}`);
174
+ }
175
+
176
+ if (entry.type === 'dir') {
177
+ for (const child of [...entry.children]) {
178
+ deleteEntry(`${normalized}/${child}`, true, force);
179
+ }
180
+ }
181
+
182
+ entries.delete(normalized);
183
+ const parent = entries.get(dirname(normalized) ?? '/');
184
+ if (parent && parent.type === 'dir') {
185
+ parent.children.delete(basename(normalized));
186
+ touch(parent);
187
+ }
188
+ }
189
+
190
+ function listFiles(path) {
191
+ const normalized = normalizePath(path);
192
+ const entry = getEntry(normalized);
193
+ if (!entry) {
194
+ return [];
195
+ }
196
+ if (entry.type === 'file') {
197
+ return [normalized];
198
+ }
199
+
200
+ const files = [];
201
+ for (const child of [...entry.children].sort()) {
202
+ files.push(...listFiles(`${normalized === '/' ? '' : normalized}/${child}`));
203
+ }
204
+ return files;
205
+ }
206
+
207
+ const hostFS = {
208
+ cwd() {
209
+ return '/';
210
+ },
211
+
212
+ existsSync(path) {
213
+ return entries.has(normalizePath(path));
214
+ },
215
+
216
+ statSync(path) {
217
+ return makeStat(requireEntry(path));
218
+ },
219
+
220
+ readdirSync(path) {
221
+ const entry = requireEntry(path);
222
+ if (entry.type !== 'dir') {
223
+ throw new Error(`Not a directory: ${normalizePath(path)}`);
224
+ }
225
+ return [...entry.children].sort();
226
+ },
227
+
228
+ readFileSync(path) {
229
+ const entry = requireEntry(path);
230
+ if (entry.type !== 'file') {
231
+ throw new Error(`Is a directory: ${normalizePath(path)}`);
232
+ }
233
+ return cloneBytes(entry.bytes);
234
+ },
235
+
236
+ readBinary(path) {
237
+ return this.readFileSync(path);
238
+ },
239
+
240
+ mkdirSync(path, options = {}) {
241
+ if (options.recursive) {
242
+ ensureDirectory(path);
243
+ return;
244
+ }
245
+
246
+ const normalized = normalizePath(path);
247
+ const parentPath = dirname(normalized) ?? '/';
248
+ const parent = requireEntry(parentPath);
249
+ if (parent.type !== 'dir') {
250
+ throw new Error(`Not a directory: ${parentPath}`);
251
+ }
252
+ if (entries.has(normalized)) {
253
+ throw new Error(`File exists: ${normalized}`);
254
+ }
255
+ ensureDirectory(normalized);
256
+ },
257
+
258
+ writeFileSync(path, value) {
259
+ writeFile(path, value);
260
+ },
261
+
262
+ appendFileSync(path, value) {
263
+ const normalized = normalizePath(path);
264
+ const existing = getEntry(normalized);
265
+ if (!existing) {
266
+ writeFile(normalized, value);
267
+ return;
268
+ }
269
+ if (existing.type !== 'file') {
270
+ throw new Error(`Is a directory: ${normalized}`);
271
+ }
272
+
273
+ const appended = new Uint8Array(existing.bytes.length + toUint8Array(value).length);
274
+ appended.set(existing.bytes, 0);
275
+ appended.set(toUint8Array(value), existing.bytes.length);
276
+ writeFile(normalized, appended);
277
+ },
278
+
279
+ rmSync(path, options = {}) {
280
+ deleteEntry(path, Boolean(options.recursive), Boolean(options.force));
281
+ },
282
+
283
+ rmdirSync(path, options = {}) {
284
+ deleteEntry(path, Boolean(options.recursive), false);
285
+ },
286
+
287
+ unlinkSync(path) {
288
+ const entry = requireEntry(path);
289
+ if (entry.type !== 'file') {
290
+ throw new Error(`Not a file: ${normalizePath(path)}`);
291
+ }
292
+ deleteEntry(path, false, false);
293
+ },
294
+
295
+ truncateSync(path) {
296
+ writeFile(path, new Uint8Array(0));
297
+ }
298
+ };
299
+
300
+ return {
301
+ hostFS,
302
+ mkdir(path) {
303
+ ensureDirectory(path);
304
+ },
305
+ writeText(path, text) {
306
+ writeFile(path, textEncoder.encode(text));
307
+ },
308
+ writeBinary(path, bytes) {
309
+ writeFile(path, bytes);
310
+ },
311
+ readText(path) {
312
+ const entry = requireEntry(path);
313
+ if (entry.type !== 'file') {
314
+ throw new Error(`Not a file: ${normalizePath(path)}`);
315
+ }
316
+ return textDecoder.decode(entry.bytes);
317
+ },
318
+ readBinary(path) {
319
+ const entry = requireEntry(path);
320
+ if (entry.type !== 'file') {
321
+ throw new Error(`Not a file: ${normalizePath(path)}`);
322
+ }
323
+ return cloneBytes(entry.bytes);
324
+ },
325
+ removeTree(path) {
326
+ if (!entries.has(normalizePath(path))) {
327
+ return;
328
+ }
329
+ deleteEntry(path, true, true);
330
+ },
331
+ listFiles
332
+ };
333
+ }
@@ -0,0 +1 @@
1
+ export const runnerSource: "import java.io.{StringReader, OutputStream, PrintStream}\nimport scala.scalajs.js\nimport scala.scalajs.js.annotation.JSExportTopLevel\nimport scala.scalajs.js.JSConverters.*\n\nobject WasmIdleScalaRunner:\n private final class TerminalStream(stream: String) extends OutputStream:\n override def write(value: Int): Unit =\n js.Dynamic.global.wasmIdleScalaWriteBytes(stream, js.Array(value & 255))\n override def write(buffer: Array[Byte], offset: Int, length: Int): Unit =\n val bytes = new js.Array[Int]()\n var index = offset\n while index < offset + length do\n bytes.push(buffer(index) & 255)\n index += 1\n js.Dynamic.global.wasmIdleScalaWriteBytes(stream, bytes)\n override def flush(): Unit = ()\n override def close(): Unit = ()\n\n @JSExportTopLevel(\"runWasmIdleScala\")\n def run(input: String, args: js.Array[String]): Unit =\n val out = new PrintStream(new TerminalStream(\"stdout\"), true, \"UTF-8\")\n val err = new PrintStream(new TerminalStream(\"stderr\"), true, \"UTF-8\")\n try\n scala.Console.withIn(new StringReader(input)) {\n scala.Console.withOut(out) {\n scala.Console.withErr(err) {\n Main.main(args.toArray)\n }\n }\n }\n finally\n out.flush()\n err.flush()\n";
@@ -0,0 +1,36 @@
1
+ // This bridge is compiled by the real Scala compiler alongside every user request.
2
+ export const runnerSource = `import java.io.{StringReader, OutputStream, PrintStream}
3
+ import scala.scalajs.js
4
+ import scala.scalajs.js.annotation.JSExportTopLevel
5
+ import scala.scalajs.js.JSConverters.*
6
+
7
+ object WasmIdleScalaRunner:
8
+ private final class TerminalStream(stream: String) extends OutputStream:
9
+ override def write(value: Int): Unit =
10
+ js.Dynamic.global.wasmIdleScalaWriteBytes(stream, js.Array(value & 255))
11
+ override def write(buffer: Array[Byte], offset: Int, length: Int): Unit =
12
+ val bytes = new js.Array[Int]()
13
+ var index = offset
14
+ while index < offset + length do
15
+ bytes.push(buffer(index) & 255)
16
+ index += 1
17
+ js.Dynamic.global.wasmIdleScalaWriteBytes(stream, bytes)
18
+ override def flush(): Unit = ()
19
+ override def close(): Unit = ()
20
+
21
+ @JSExportTopLevel("runWasmIdleScala")
22
+ def run(input: String, args: js.Array[String]): Unit =
23
+ val out = new PrintStream(new TerminalStream("stdout"), true, "UTF-8")
24
+ val err = new PrintStream(new TerminalStream("stderr"), true, "UTF-8")
25
+ try
26
+ scala.Console.withIn(new StringReader(input)) {
27
+ scala.Console.withOut(out) {
28
+ scala.Console.withErr(err) {
29
+ Main.main(args.toArray)
30
+ }
31
+ }
32
+ }
33
+ finally
34
+ out.flush()
35
+ err.flush()
36
+ `;