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.
- package/README.md +250 -146
- package/dist/container/clang-runtime.js +32 -8
- package/dist/container/runtime-adapter.d.ts +2 -0
- package/dist/container/runtime-adapter.js +37 -8
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/playground/assetBridge.js +10 -8
- package/dist/playground/assets.d.ts +4 -0
- package/dist/playground/assets.js +9 -4
- package/dist/playground/c3.js +1 -1
- package/dist/playground/compiledLldb.d.ts +2 -0
- package/dist/playground/compiledLldb.js +37 -2
- package/dist/playground/d.d.ts +1 -0
- package/dist/playground/d.js +18 -8
- package/dist/playground/index.d.ts +1 -1
- package/dist/playground/index.js +7 -0
- package/dist/playground/{java-debug-FMHDKUN6.js → java-debug-64JGCLTC.js} +1 -1
- package/dist/playground/java-debug-notices.txt +26 -1
- package/dist/playground/java.js +3 -2
- package/dist/playground/javaDebugBridge.js +42 -7
- package/dist/playground/javaDebugSource.js +4 -4
- package/dist/playground/javaMain.d.ts +3 -0
- package/dist/playground/javaMain.js +2 -0
- package/dist/playground/javaRuntimeErrors.d.ts +2 -1
- package/dist/playground/javaRuntimeErrors.js +9 -2
- package/dist/playground/javaSource.d.ts +1 -1
- package/dist/playground/javaSource.js +7 -2
- package/dist/playground/lldbSession.d.ts +2 -0
- package/dist/playground/lldbSession.js +60 -4
- package/dist/playground/objectivec.d.ts +1 -1
- package/dist/playground/objectivec.js +2 -1
- package/dist/playground/options.d.ts +1 -1
- package/dist/playground/python.d.ts +3 -0
- package/dist/playground/python.js +122 -2
- package/dist/playground/pythonCompileOptions.d.ts +52 -0
- package/dist/playground/pythonCompileOptions.js +40 -0
- package/dist/playground/scala.d.ts +34 -0
- package/dist/playground/scala.js +397 -0
- package/dist/playground/scalaAssets.d.ts +16 -0
- package/dist/playground/scalaAssets.js +51 -0
- package/dist/playground/scalaDiagnostics.d.ts +3 -0
- package/dist/playground/scalaDiagnostics.js +29 -0
- package/dist/playground/staticRuntimeModuleVersion.d.ts +1 -1
- package/dist/playground/staticRuntimeModuleVersion.js +1 -1
- package/dist/playground/staticWorkerRuntime.d.ts +2 -0
- package/dist/playground/staticWorkerRuntime.js +85 -11
- package/dist/playground/tinygo.js +21 -8
- package/dist/playground/tinygoExecutableGraph.js +1 -1
- package/dist/playground/v.d.ts +1 -0
- package/dist/playground/v.js +17 -7
- package/dist/playground/wasmC3Version.d.ts +8 -8
- package/dist/playground/wasmC3Version.js +8 -8
- package/dist/playground/wasmDebugVersion.d.ts +1 -1
- package/dist/playground/wasmDebugVersion.js +1 -1
- package/dist/playground/wasmDotnetVersion.d.ts +1 -1
- package/dist/playground/wasmDotnetVersion.js +1 -1
- package/dist/playground/wasmGoVersion.d.ts +1 -1
- package/dist/playground/wasmGoVersion.js +1 -1
- package/dist/playground/wasmLispVersion.d.ts +5 -0
- package/dist/playground/wasmLispVersion.js +5 -0
- package/dist/playground/wasmOcamlVersion.d.ts +4 -4
- package/dist/playground/wasmOcamlVersion.js +3 -3
- package/dist/playground/wasmPrologVersion.d.ts +17 -17
- package/dist/playground/wasmPrologVersion.js +16 -16
- package/dist/playground/wasmTinyGoVersion.d.ts +57 -57
- package/dist/playground/wasmTinyGoVersion.js +57 -57
- package/dist/playground/wasmTypeScriptVersion.d.ts +3 -3
- package/dist/playground/wasmTypeScriptVersion.js +3 -3
- package/dist/playground/wasmZigVersion.d.ts +7 -7
- package/dist/playground/wasmZigVersion.js +7 -7
- package/dist/playground/worker/java.js +18 -4
- package/dist/playground/worker/javaDebugEvaluator.js +2 -2
- package/dist/playground/worker/javaDebugRuntime.js +8 -1
- package/dist/playground/worker/javaStreaming.js +4 -2
- package/dist/playground/worker/ocaml.js +11 -10
- package/dist/playground/worker/python.js +45 -165
- package/dist/playground/worker/pythonCompile.d.ts +4 -0
- package/dist/playground/worker/pythonCompile.js +127 -0
- package/dist/playground/worker/pythonDebug.d.ts +20 -0
- package/dist/playground/worker/pythonDebug.js +205 -0
- package/dist/playground/worker/scala/UPSTREAM-LICENSE.txt +201 -0
- package/dist/playground/worker/scala/UPSTREAM-NOTICE.txt +108 -0
- package/dist/playground/worker/scala/asset-bootstrap.d.ts +6 -0
- package/dist/playground/worker/scala/asset-bootstrap.js +58 -0
- package/dist/playground/worker/scala/asset-receipts.d.ts +7 -0
- package/dist/playground/worker/scala/asset-receipts.js +58 -0
- package/dist/playground/worker/scala/compiler.worker.d.ts +1 -0
- package/dist/playground/worker/scala/compiler.worker.js +204 -0
- package/dist/playground/worker/scala/execution.worker.d.ts +1 -0
- package/dist/playground/worker/scala/execution.worker.js +89 -0
- package/dist/playground/worker/scala/memory-fs.d.ts +29 -0
- package/dist/playground/worker/scala/memory-fs.js +333 -0
- package/dist/playground/worker/scala/runner.d.ts +1 -0
- package/dist/playground/worker/scala/runner.js +36 -0
- package/dist/playground/worker/zig.d.ts +2 -1
- package/dist/playground/worker/zig.js +212 -86
- package/dist/playground/worker/zigDebug.d.ts +39 -0
- package/dist/playground/worker/zigDebug.js +156 -0
- package/dist/playground/zig.d.ts +27 -4
- package/dist/playground/zig.js +266 -23
- package/dist/playground/zigDebugValues.d.ts +20 -0
- package/dist/playground/zigDebugValues.js +248 -0
- package/dist/pythonCompiler.d.ts +8 -0
- package/dist/pythonCompiler.js +52 -0
- package/package.json +37 -26
|
@@ -5,6 +5,7 @@ import { bufferedSequence, flushBufferedEof, flushQueuedStdin, resetBufferedStdi
|
|
|
5
5
|
import { createWasmIdleSharedBuffer, requireSharedArrayBuffer } from './sharedBuffer';
|
|
6
6
|
import { WorkerSession } from './workerSession';
|
|
7
7
|
import { reportWorkerProgress } from './workerProgress';
|
|
8
|
+
import { resolvePythonCompileRequest } from './pythonCompileOptions';
|
|
8
9
|
import { BusyError, DEFAULT_WORKSPACE_LIMITS, OutputLimitError, RuntimeConfigurationError, TimeoutError, resolveExecutionLimits, validateExecutionWorkspace } from '@wasm-idle/core';
|
|
9
10
|
const debugBreakpointBufferInts = 1028;
|
|
10
11
|
const outputEncoder = new TextEncoder();
|
|
@@ -12,7 +13,7 @@ const abortReason = (signal, phase, label = 'Python') => signal.reason !== undef
|
|
|
12
13
|
? signal.reason
|
|
13
14
|
: new DOMException(phase === 'startup'
|
|
14
15
|
? `${label} runtime startup aborted`
|
|
15
|
-
: `${label} execution aborted`, 'AbortError');
|
|
16
|
+
: `${label} ${phase === 'compile' ? 'compilation' : 'execution'} aborted`, 'AbortError');
|
|
16
17
|
class Python {
|
|
17
18
|
ts = Date.now();
|
|
18
19
|
output = null;
|
|
@@ -188,7 +189,7 @@ class Python {
|
|
|
188
189
|
timeout = setTimeout(() => {
|
|
189
190
|
if (!this.isOperationActive(operation))
|
|
190
191
|
return;
|
|
191
|
-
this.cancelOperation(operation, new TimeoutError(`${this.runtimeLabel} ${operation.phase === 'startup' ? 'startup' : 'execution'} timed out after ${timeoutMs} ms`, {
|
|
192
|
+
this.cancelOperation(operation, new TimeoutError(`${this.runtimeLabel} ${operation.phase === 'startup' ? 'startup' : operation.phase === 'compile' ? 'compilation' : 'execution'} timed out after ${timeoutMs} ms`, {
|
|
192
193
|
phase: operation.phase,
|
|
193
194
|
runtimeId: this.runtimeId,
|
|
194
195
|
timeoutMs
|
|
@@ -347,6 +348,125 @@ class Python {
|
|
|
347
348
|
this.pendingEof = true;
|
|
348
349
|
this.flushPendingInput();
|
|
349
350
|
}
|
|
351
|
+
/** Used by compilePython's dedicated instance; never runs source or resolves its imports. */
|
|
352
|
+
compile(code, options = {}) {
|
|
353
|
+
let operation;
|
|
354
|
+
try {
|
|
355
|
+
operation = this.beginOperation('compile');
|
|
356
|
+
}
|
|
357
|
+
catch (error) {
|
|
358
|
+
return Promise.reject(error);
|
|
359
|
+
}
|
|
360
|
+
let request;
|
|
361
|
+
const worker = this.worker;
|
|
362
|
+
try {
|
|
363
|
+
if (this.workerLanguage !== 'python') {
|
|
364
|
+
throw new RuntimeConfigurationError('Bytecode compilation is only available for Python');
|
|
365
|
+
}
|
|
366
|
+
request = resolvePythonCompileRequest(code, options);
|
|
367
|
+
options.signal?.throwIfAborted();
|
|
368
|
+
if (!worker)
|
|
369
|
+
throw new Error('Python worker not loaded');
|
|
370
|
+
this.assetBridge?.setExecutionPersistentCache(options.persistentCache);
|
|
371
|
+
}
|
|
372
|
+
catch (error) {
|
|
373
|
+
return Promise.reject(this.releaseBeforeSession(operation, error));
|
|
374
|
+
}
|
|
375
|
+
const { fileName, optimize, limits, invalidationMode, timestamp } = request;
|
|
376
|
+
const path = fileName.slice(0, -3) + '.pyc';
|
|
377
|
+
this.exit = false;
|
|
378
|
+
this.begin = Date.now();
|
|
379
|
+
let handler;
|
|
380
|
+
const compiling = new Promise((resolve, reject) => {
|
|
381
|
+
const workerOperation = this.workerSession.beginRun(worker, reject);
|
|
382
|
+
this.bindOperationTimeout(operation, limits.compileTimeoutMs);
|
|
383
|
+
this.bindAbortSignal(operation, options.signal);
|
|
384
|
+
if (!this.isOperationActive(operation))
|
|
385
|
+
return;
|
|
386
|
+
const finish = (result, error) => {
|
|
387
|
+
if (!this.isOperationActive(operation))
|
|
388
|
+
return;
|
|
389
|
+
this.workerSession.complete(workerOperation);
|
|
390
|
+
this.releaseOperation(operation);
|
|
391
|
+
this.cleanupOperation(operation);
|
|
392
|
+
if (result)
|
|
393
|
+
resolve(result);
|
|
394
|
+
else
|
|
395
|
+
reject(error);
|
|
396
|
+
};
|
|
397
|
+
handler = (event) => {
|
|
398
|
+
if (!this.isOperationActive(operation) || this.worker !== worker)
|
|
399
|
+
return;
|
|
400
|
+
try {
|
|
401
|
+
if (this.assetBridge?.handleMessage(event))
|
|
402
|
+
return;
|
|
403
|
+
reportWorkerProgress(options.progress, event.data?.progress);
|
|
404
|
+
if (!this.isOperationActive(operation))
|
|
405
|
+
return;
|
|
406
|
+
if (event.data?.error !== undefined) {
|
|
407
|
+
const outputLimit = event.data.outputLimit;
|
|
408
|
+
finish(undefined, outputLimit
|
|
409
|
+
? new OutputLimitError(String(event.data.error), {
|
|
410
|
+
runtimeId: 'PYTHON3',
|
|
411
|
+
phase: 'compile',
|
|
412
|
+
actual: outputLimit.actual,
|
|
413
|
+
limit: outputLimit.limit
|
|
414
|
+
})
|
|
415
|
+
: event.data.error);
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
if (event.data?.compiled === undefined)
|
|
419
|
+
return;
|
|
420
|
+
const result = event.data.compiled;
|
|
421
|
+
if (!result ||
|
|
422
|
+
result.path !== path ||
|
|
423
|
+
!(result.data instanceof Uint8Array) ||
|
|
424
|
+
result.data.byteLength < 16 ||
|
|
425
|
+
typeof result.pythonVersion !== 'string' ||
|
|
426
|
+
typeof result.cacheTag !== 'string' ||
|
|
427
|
+
typeof result.magicNumber !== 'string' ||
|
|
428
|
+
!/^[0-9a-f]{8}$/.test(result.magicNumber))
|
|
429
|
+
throw new Error('Invalid Python bytecode result');
|
|
430
|
+
if (result.data.byteLength > limits.maxOutputBytes) {
|
|
431
|
+
throw new OutputLimitError('Python bytecode exceeds the configured byte limit', {
|
|
432
|
+
runtimeId: 'PYTHON3',
|
|
433
|
+
phase: 'compile',
|
|
434
|
+
actual: result.data.byteLength,
|
|
435
|
+
limit: limits.maxOutputBytes
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
finish(result);
|
|
439
|
+
}
|
|
440
|
+
catch (error) {
|
|
441
|
+
this.cancelOperation(operation, error);
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
worker.onmessage = handler;
|
|
445
|
+
try {
|
|
446
|
+
worker.postMessage({
|
|
447
|
+
compile: true,
|
|
448
|
+
language: 'python',
|
|
449
|
+
code,
|
|
450
|
+
fileName,
|
|
451
|
+
optimize,
|
|
452
|
+
invalidationMode,
|
|
453
|
+
timestamp,
|
|
454
|
+
maxArtifactBytes: limits.maxOutputBytes
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
catch (error) {
|
|
458
|
+
finish(undefined, error);
|
|
459
|
+
}
|
|
460
|
+
});
|
|
461
|
+
return compiling.finally(() => {
|
|
462
|
+
this.releaseOperation(operation);
|
|
463
|
+
this.cleanupOperation(operation);
|
|
464
|
+
this.exit = true;
|
|
465
|
+
this.elapse = Date.now() - this.begin;
|
|
466
|
+
if (worker?.onmessage === handler)
|
|
467
|
+
worker.onmessage = null;
|
|
468
|
+
});
|
|
469
|
+
}
|
|
350
470
|
flushPendingInput() {
|
|
351
471
|
if (!this.waitingForInput)
|
|
352
472
|
return;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type ExecutionLimits, type RuntimeAssetCacheOptions } from '@wasm-idle/core';
|
|
2
|
+
import type { SandboxProgress, SandboxRuntimeAssets } from './sandbox';
|
|
3
|
+
export interface PythonCompileOptions {
|
|
4
|
+
/** Relative source path used in tracebacks. Defaults to main.py. */
|
|
5
|
+
fileName?: string;
|
|
6
|
+
/** 0 preserves assertions and docstrings; 1 removes assertions; 2 also removes docstrings. */
|
|
7
|
+
optimize?: 0 | 1 | 2;
|
|
8
|
+
/**
|
|
9
|
+
* Defaults to reproducible checked-hash bytecode. `normalized` clears source-dependent
|
|
10
|
+
* header fields for source-free execution and bytecode hashing, preserving the code payload.
|
|
11
|
+
*/
|
|
12
|
+
invalidationMode?: 'checked-hash' | 'unchecked-hash' | 'timestamp' | 'normalized';
|
|
13
|
+
/** Source mtime in integer Unix seconds (0–4294967295). Only valid in timestamp mode; defaults to 0. */
|
|
14
|
+
timestamp?: number;
|
|
15
|
+
runtimeAssets?: SandboxRuntimeAssets;
|
|
16
|
+
persistentCache?: RuntimeAssetCacheOptions;
|
|
17
|
+
signal?: AbortSignal;
|
|
18
|
+
progress?: SandboxProgress;
|
|
19
|
+
/** maxWorkspaceBytes bounds the source; maxOutputBytes bounds the returned .pyc. */
|
|
20
|
+
limits?: Partial<Pick<ExecutionLimits, 'assetTimeoutMs' | 'startupTimeoutMs' | 'compileTimeoutMs' | 'maxWorkspaceBytes' | 'maxOutputBytes' | 'maxAssetBytes'>>;
|
|
21
|
+
}
|
|
22
|
+
export interface PythonCompileResult {
|
|
23
|
+
/** Relative output path, e.g. pkg/main.pyc. */
|
|
24
|
+
path: string;
|
|
25
|
+
data: Uint8Array;
|
|
26
|
+
pythonVersion: string;
|
|
27
|
+
cacheTag: string;
|
|
28
|
+
/** Four-byte CPython magic number encoded as eight hexadecimal digits. */
|
|
29
|
+
magicNumber: string;
|
|
30
|
+
}
|
|
31
|
+
/** Share header-option validation between the host and the actual compiler boundary. */
|
|
32
|
+
export declare function resolvePythonBytecodeOptions(options: Pick<PythonCompileOptions, 'invalidationMode' | 'timestamp'>): {
|
|
33
|
+
invalidationMode: "checked-hash" | "unchecked-hash" | "normalized";
|
|
34
|
+
timestamp: undefined;
|
|
35
|
+
} | {
|
|
36
|
+
invalidationMode: "timestamp";
|
|
37
|
+
timestamp: number;
|
|
38
|
+
};
|
|
39
|
+
/** Validate before starting a runtime, and again at the direct adapter boundary. */
|
|
40
|
+
export declare function resolvePythonCompileRequest(code: string, options: PythonCompileOptions): {
|
|
41
|
+
invalidationMode: "checked-hash" | "unchecked-hash" | "normalized";
|
|
42
|
+
timestamp: undefined;
|
|
43
|
+
fileName: string;
|
|
44
|
+
optimize: 0 | 1 | 2;
|
|
45
|
+
limits: ExecutionLimits;
|
|
46
|
+
} | {
|
|
47
|
+
invalidationMode: "timestamp";
|
|
48
|
+
timestamp: number;
|
|
49
|
+
fileName: string;
|
|
50
|
+
optimize: 0 | 1 | 2;
|
|
51
|
+
limits: ExecutionLimits;
|
|
52
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { RuntimeConfigurationError, resolveExecutionLimits, validateExecutionWorkspace } from '@wasm-idle/core';
|
|
2
|
+
/** Share header-option validation between the host and the actual compiler boundary. */
|
|
3
|
+
export function resolvePythonBytecodeOptions(options) {
|
|
4
|
+
const invalidationMode = options.invalidationMode === undefined ? 'checked-hash' : options.invalidationMode;
|
|
5
|
+
if (!['checked-hash', 'unchecked-hash', 'timestamp', 'normalized'].includes(invalidationMode)) {
|
|
6
|
+
throw new RuntimeConfigurationError('Python invalidationMode must be checked-hash, unchecked-hash, timestamp, or normalized');
|
|
7
|
+
}
|
|
8
|
+
if (invalidationMode !== 'timestamp') {
|
|
9
|
+
if (options.timestamp !== undefined) {
|
|
10
|
+
throw new RuntimeConfigurationError('Python timestamp requires timestamp invalidation mode');
|
|
11
|
+
}
|
|
12
|
+
return { invalidationMode, timestamp: undefined };
|
|
13
|
+
}
|
|
14
|
+
const timestamp = options.timestamp === undefined ? 0 : options.timestamp;
|
|
15
|
+
if (!Number.isInteger(timestamp) || timestamp < 0 || timestamp > 0xffffffff) {
|
|
16
|
+
throw new RuntimeConfigurationError('Python timestamp must be an integer Unix time from 0 to 4294967295 seconds');
|
|
17
|
+
}
|
|
18
|
+
return { invalidationMode, timestamp };
|
|
19
|
+
}
|
|
20
|
+
/** Validate before starting a runtime, and again at the direct adapter boundary. */
|
|
21
|
+
export function resolvePythonCompileRequest(code, options) {
|
|
22
|
+
if (typeof code !== 'string') {
|
|
23
|
+
throw new RuntimeConfigurationError('Python source must be a string');
|
|
24
|
+
}
|
|
25
|
+
const limits = resolveExecutionLimits(options.limits);
|
|
26
|
+
const optimize = options.optimize ?? 0;
|
|
27
|
+
if (![0, 1, 2].includes(optimize)) {
|
|
28
|
+
throw new RuntimeConfigurationError('Python optimize must be 0, 1, or 2');
|
|
29
|
+
}
|
|
30
|
+
const bytecodeOptions = resolvePythonBytecodeOptions(options);
|
|
31
|
+
const workspace = validateExecutionWorkspace(code, [], options.fileName ?? 'main.py', {
|
|
32
|
+
maxFileBytes: limits.maxWorkspaceBytes,
|
|
33
|
+
maxTotalBytes: limits.maxWorkspaceBytes
|
|
34
|
+
});
|
|
35
|
+
const fileName = workspace.activePath;
|
|
36
|
+
if (!/\.py$/i.test(fileName)) {
|
|
37
|
+
throw new RuntimeConfigurationError('Python compilation requires a .py file name');
|
|
38
|
+
}
|
|
39
|
+
return { fileName, optimize, limits, ...bytecodeOptions };
|
|
40
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { PlaygroundRuntimeAssets } from './assets';
|
|
2
|
+
import { type CompilerDiagnostic, type SandboxExecutionOptions } from './options';
|
|
3
|
+
import type { Sandbox, SandboxProgress } from './sandbox';
|
|
4
|
+
/** Scala 3 through the genuine browser compiler and Scala.js linker. */
|
|
5
|
+
export default class Scala implements Sandbox {
|
|
6
|
+
output?: (data: string) => void;
|
|
7
|
+
oncompilerdiagnostic?: (diagnostic: CompilerDiagnostic) => void;
|
|
8
|
+
elapse: number;
|
|
9
|
+
private compiler;
|
|
10
|
+
private execution;
|
|
11
|
+
private active;
|
|
12
|
+
private disposed;
|
|
13
|
+
private sequence;
|
|
14
|
+
private payload;
|
|
15
|
+
private payloadKey;
|
|
16
|
+
private baseUrl?;
|
|
17
|
+
private cache?;
|
|
18
|
+
private pendingInput;
|
|
19
|
+
private begin;
|
|
20
|
+
private check;
|
|
21
|
+
private end;
|
|
22
|
+
private validateOptions;
|
|
23
|
+
private files;
|
|
24
|
+
private retire;
|
|
25
|
+
private request;
|
|
26
|
+
private ensureCompiler;
|
|
27
|
+
load(runtimeAssets?: string | PlaygroundRuntimeAssets, _code?: string, _log?: boolean, _args?: string[], options?: SandboxExecutionOptions, progress?: SandboxProgress): Promise<void>;
|
|
28
|
+
run(code: string, _prepare?: boolean, _log?: boolean, progress?: SandboxProgress, args?: string[], options?: SandboxExecutionOptions): Promise<boolean>;
|
|
29
|
+
write(data: string): void;
|
|
30
|
+
eof(): void;
|
|
31
|
+
terminate(): void;
|
|
32
|
+
clear(): Promise<void>;
|
|
33
|
+
dispose(): Promise<void>;
|
|
34
|
+
}
|
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
import { BusyError, CancelledError, CompileError, DiagnosticLimitError, OutputLimitError, ProtocolError, RuntimeConfigurationError, RuntimeExecutionError, TimeoutError, UnsupportedBrowserFeatureError, resolveExecutionLimits, validateWorkspaceFiles } from '@wasm-idle/core';
|
|
2
|
+
import { resolveSandboxExecutionArgs } from './options';
|
|
3
|
+
import { createScalaCompilerPayload } from './scalaAssets';
|
|
4
|
+
import { parseScalaDiagnostics } from './scalaDiagnostics';
|
|
5
|
+
import { reportWorkerProgress } from './workerProgress';
|
|
6
|
+
const encoder = new TextEncoder();
|
|
7
|
+
const HARD_SOURCE_BYTES = 1024 * 1024;
|
|
8
|
+
/** Scala 3 through the genuine browser compiler and Scala.js linker. */
|
|
9
|
+
export default class Scala {
|
|
10
|
+
output;
|
|
11
|
+
oncompilerdiagnostic;
|
|
12
|
+
elapse = 0;
|
|
13
|
+
compiler = null;
|
|
14
|
+
execution = null;
|
|
15
|
+
active = null;
|
|
16
|
+
disposed = false;
|
|
17
|
+
sequence = 0;
|
|
18
|
+
payload = null;
|
|
19
|
+
payloadKey = '';
|
|
20
|
+
baseUrl;
|
|
21
|
+
cache;
|
|
22
|
+
pendingInput = '';
|
|
23
|
+
begin(signal) {
|
|
24
|
+
if (this.disposed)
|
|
25
|
+
throw new RuntimeConfigurationError('Scala sandbox is disposed', {
|
|
26
|
+
runtimeId: 'SCALA'
|
|
27
|
+
});
|
|
28
|
+
if (this.active)
|
|
29
|
+
throw new BusyError('Scala sandbox is busy', { runtimeId: 'SCALA' });
|
|
30
|
+
if (signal?.aborted)
|
|
31
|
+
throw new CancelledError('Scala request aborted', {
|
|
32
|
+
runtimeId: 'SCALA',
|
|
33
|
+
cause: signal.reason
|
|
34
|
+
});
|
|
35
|
+
const controller = new AbortController();
|
|
36
|
+
const operation = {
|
|
37
|
+
controller,
|
|
38
|
+
signal,
|
|
39
|
+
abort: () => controller.abort(signal?.reason)
|
|
40
|
+
};
|
|
41
|
+
signal?.addEventListener('abort', operation.abort, { once: true });
|
|
42
|
+
this.active = operation;
|
|
43
|
+
return operation;
|
|
44
|
+
}
|
|
45
|
+
check(operation) {
|
|
46
|
+
if (this.disposed || this.active !== operation || operation.controller.signal.aborted)
|
|
47
|
+
throw new CancelledError('Scala request cancelled', {
|
|
48
|
+
runtimeId: 'SCALA',
|
|
49
|
+
cause: operation.controller.signal.reason
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
end(operation) {
|
|
53
|
+
operation.signal?.removeEventListener('abort', operation.abort);
|
|
54
|
+
if (this.active === operation)
|
|
55
|
+
this.active = null;
|
|
56
|
+
}
|
|
57
|
+
validateOptions(options) {
|
|
58
|
+
if ((options.debugMode && options.debugMode !== 'none') ||
|
|
59
|
+
options.debug ||
|
|
60
|
+
options.interactive ||
|
|
61
|
+
options.compileArgs?.length ||
|
|
62
|
+
Object.keys(options.env ?? {}).length)
|
|
63
|
+
throw new RuntimeConfigurationError('Scala.js supports buffered stdin and program arguments; debugging, interactive input, compiler options and environment overrides are unavailable.', { runtimeId: 'SCALA' });
|
|
64
|
+
for (const feature of ['JSTag', 'Suspending', 'promising']) {
|
|
65
|
+
if (typeof globalThis.WebAssembly?.[feature] === 'undefined')
|
|
66
|
+
throw new UnsupportedBrowserFeatureError(`WebAssembly.${feature} (Scala browser compiler)`, { runtimeId: 'SCALA' });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
files(code, options, limits) {
|
|
70
|
+
const activePath = options.activePath ?? 'Main.scala';
|
|
71
|
+
const files = (options.workspaceFiles?.length
|
|
72
|
+
? options.workspaceFiles
|
|
73
|
+
: [{ path: activePath, content: code }]).map((file) => ({
|
|
74
|
+
path: file.path,
|
|
75
|
+
content: file.path === activePath ? code : file.content
|
|
76
|
+
}));
|
|
77
|
+
if (!files.some((file) => file.path === activePath))
|
|
78
|
+
files.push({ path: activePath, content: code });
|
|
79
|
+
const validated = validateWorkspaceFiles(files, {
|
|
80
|
+
...options.workspaceLimits,
|
|
81
|
+
maxFiles: Math.min(options.workspaceLimits?.maxFiles ?? 64, 64),
|
|
82
|
+
maxFileBytes: Math.min(options.workspaceLimits?.maxFileBytes ?? HARD_SOURCE_BYTES, HARD_SOURCE_BYTES),
|
|
83
|
+
maxTotalBytes: Math.min(options.workspaceLimits?.maxTotalBytes ?? HARD_SOURCE_BYTES, HARD_SOURCE_BYTES, limits.maxWorkspaceBytes)
|
|
84
|
+
});
|
|
85
|
+
for (const file of validated) {
|
|
86
|
+
if (!/^(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+\.scala$/.test(file.path) ||
|
|
87
|
+
file.path === 'WasmIdleScalaRunner.scala')
|
|
88
|
+
throw new RuntimeConfigurationError(`Unsupported Scala source path: ${file.path}`, {
|
|
89
|
+
runtimeId: 'SCALA'
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
return validated;
|
|
93
|
+
}
|
|
94
|
+
retire(worker) {
|
|
95
|
+
worker.terminate();
|
|
96
|
+
if (this.compiler === worker)
|
|
97
|
+
this.compiler = null;
|
|
98
|
+
if (this.execution === worker)
|
|
99
|
+
this.execution = null;
|
|
100
|
+
}
|
|
101
|
+
request(worker, payload, operation, phase, timeoutMs, onOutput, progress) {
|
|
102
|
+
this.check(operation);
|
|
103
|
+
return new Promise((resolve, reject) => {
|
|
104
|
+
const id = ++this.sequence;
|
|
105
|
+
let settled = false;
|
|
106
|
+
const finish = (error, reply) => {
|
|
107
|
+
if (settled)
|
|
108
|
+
return;
|
|
109
|
+
settled = true;
|
|
110
|
+
clearTimeout(timer);
|
|
111
|
+
operation.controller.signal.removeEventListener('abort', abort);
|
|
112
|
+
worker.onmessage = null;
|
|
113
|
+
worker.onerror = null;
|
|
114
|
+
worker.onmessageerror = null;
|
|
115
|
+
if (error) {
|
|
116
|
+
this.retire(worker);
|
|
117
|
+
reject(error);
|
|
118
|
+
}
|
|
119
|
+
else
|
|
120
|
+
resolve(reply);
|
|
121
|
+
};
|
|
122
|
+
const abort = () => finish(new CancelledError('Scala request cancelled', { runtimeId: 'SCALA', phase }));
|
|
123
|
+
const timer = setTimeout(() => finish(new TimeoutError(`Scala ${phase} timed out`, {
|
|
124
|
+
runtimeId: 'SCALA',
|
|
125
|
+
phase,
|
|
126
|
+
timeoutMs
|
|
127
|
+
})), timeoutMs);
|
|
128
|
+
operation.controller.signal.addEventListener('abort', abort, { once: true });
|
|
129
|
+
worker.onmessage = ({ data }) => {
|
|
130
|
+
if (data.id !== id)
|
|
131
|
+
return;
|
|
132
|
+
try {
|
|
133
|
+
if (data.type === 'execution-ready') {
|
|
134
|
+
reportWorkerProgress(progress, data.progress);
|
|
135
|
+
}
|
|
136
|
+
else if (data.type === 'stdout' || data.type === 'stderr') {
|
|
137
|
+
if (typeof data.data !== 'string')
|
|
138
|
+
throw new ProtocolError('Invalid Scala output');
|
|
139
|
+
onOutput?.(data.type, data.data);
|
|
140
|
+
}
|
|
141
|
+
else if (['ready', 'compiled', 'exit', 'error'].includes(data.type))
|
|
142
|
+
finish(undefined, data);
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
finish(error);
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
worker.onerror = (event) => finish(new RuntimeExecutionError(event.message || 'Scala worker failed', {
|
|
149
|
+
runtimeId: 'SCALA',
|
|
150
|
+
phase
|
|
151
|
+
}));
|
|
152
|
+
worker.onmessageerror = () => finish(new ProtocolError('Scala worker message cannot be decoded', {
|
|
153
|
+
runtimeId: 'SCALA'
|
|
154
|
+
}));
|
|
155
|
+
try {
|
|
156
|
+
worker.postMessage({ id, ...payload });
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
finish(error);
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
async ensureCompiler(operation, limits, options, progress) {
|
|
164
|
+
this.check(operation);
|
|
165
|
+
const baseUrl = this.baseUrl;
|
|
166
|
+
const cache = options.persistentCache ?? this.cache;
|
|
167
|
+
const key = JSON.stringify([baseUrl, cache]);
|
|
168
|
+
if (this.payload &&
|
|
169
|
+
(this.payloadKey !== key ||
|
|
170
|
+
Object.values(this.payload).some((bytes) => bytes.length > limits.maxAssetBytes))) {
|
|
171
|
+
if (this.compiler)
|
|
172
|
+
this.retire(this.compiler);
|
|
173
|
+
this.payload = null;
|
|
174
|
+
}
|
|
175
|
+
if (this.compiler)
|
|
176
|
+
return;
|
|
177
|
+
if (!this.payload) {
|
|
178
|
+
const controller = new AbortController();
|
|
179
|
+
const abort = () => controller.abort(operation.controller.signal.reason);
|
|
180
|
+
const timer = setTimeout(() => controller.abort(new TimeoutError('Scala asset loading timed out', {
|
|
181
|
+
runtimeId: 'SCALA',
|
|
182
|
+
phase: 'asset',
|
|
183
|
+
timeoutMs: limits.assetTimeoutMs
|
|
184
|
+
})), limits.assetTimeoutMs);
|
|
185
|
+
operation.controller.signal.addEventListener('abort', abort, { once: true });
|
|
186
|
+
try {
|
|
187
|
+
progress?.set?.(0.05, 'Downloading verified Scala compiler assets');
|
|
188
|
+
this.payload = await createScalaCompilerPayload({
|
|
189
|
+
baseUrl,
|
|
190
|
+
persistentCache: cache,
|
|
191
|
+
signal: controller.signal,
|
|
192
|
+
maxAssetBytes: limits.maxAssetBytes
|
|
193
|
+
});
|
|
194
|
+
this.payloadKey = key;
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
if (operation.controller.signal.aborted)
|
|
198
|
+
throw new CancelledError('Scala asset loading cancelled', {
|
|
199
|
+
runtimeId: 'SCALA',
|
|
200
|
+
phase: 'asset'
|
|
201
|
+
});
|
|
202
|
+
if (controller.signal.aborted)
|
|
203
|
+
throw (controller.signal.reason ??
|
|
204
|
+
new CancelledError('Scala asset download cancelled'));
|
|
205
|
+
throw error;
|
|
206
|
+
}
|
|
207
|
+
finally {
|
|
208
|
+
clearTimeout(timer);
|
|
209
|
+
operation.controller.signal.removeEventListener('abort', abort);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
this.check(operation);
|
|
213
|
+
progress?.set?.(0.25, 'Initializing Scala 3 compiler');
|
|
214
|
+
this.check(operation);
|
|
215
|
+
const worker = new Worker(new URL('./worker/scala/compiler.worker.js', import.meta.url), {
|
|
216
|
+
type: 'module'
|
|
217
|
+
});
|
|
218
|
+
this.compiler = worker;
|
|
219
|
+
const reply = await this.request(worker, { type: 'initialize', runtimeAssets: this.payload }, operation, 'startup', limits.startupTimeoutMs);
|
|
220
|
+
this.check(operation);
|
|
221
|
+
if (reply.type !== 'ready') {
|
|
222
|
+
this.retire(worker);
|
|
223
|
+
throw new RuntimeExecutionError(reply.message ?? 'Scala initialization failed', {
|
|
224
|
+
runtimeId: 'SCALA',
|
|
225
|
+
phase: 'startup'
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
async load(runtimeAssets = '', _code = '', _log = true, _args = [], options = {}, progress) {
|
|
230
|
+
const operation = this.begin(options.signal);
|
|
231
|
+
try {
|
|
232
|
+
this.validateOptions(options);
|
|
233
|
+
const config = typeof runtimeAssets === 'object' ? runtimeAssets.scala : undefined;
|
|
234
|
+
const baseUrl = config?.baseUrl ??
|
|
235
|
+
(typeof runtimeAssets === 'string' && runtimeAssets
|
|
236
|
+
? `${runtimeAssets.replace(/\/$/, '')}/wasm-scala/`
|
|
237
|
+
: undefined);
|
|
238
|
+
if (baseUrl !== this.baseUrl) {
|
|
239
|
+
if (this.compiler)
|
|
240
|
+
this.retire(this.compiler);
|
|
241
|
+
this.payload = null;
|
|
242
|
+
}
|
|
243
|
+
this.baseUrl = baseUrl;
|
|
244
|
+
this.cache =
|
|
245
|
+
typeof runtimeAssets === 'object' ? runtimeAssets.persistentCache : undefined;
|
|
246
|
+
await this.ensureCompiler(operation, resolveExecutionLimits(options.limits), options, progress);
|
|
247
|
+
}
|
|
248
|
+
finally {
|
|
249
|
+
this.end(operation);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
async run(code, _prepare = false, _log = true, progress, args = [], options = {}) {
|
|
253
|
+
const operation = this.begin(options.signal);
|
|
254
|
+
let outcome = 'failed';
|
|
255
|
+
const start = performance.now();
|
|
256
|
+
try {
|
|
257
|
+
this.validateOptions(options);
|
|
258
|
+
const requestedLimits = resolveExecutionLimits(options.limits);
|
|
259
|
+
const limits = {
|
|
260
|
+
...requestedLimits,
|
|
261
|
+
maxOutputBytes: Math.min(requestedLimits.maxOutputBytes, 1024 * 1024)
|
|
262
|
+
};
|
|
263
|
+
const files = this.files(code, options, limits);
|
|
264
|
+
const { programArgs } = resolveSandboxExecutionArgs('SCALA', args, options);
|
|
265
|
+
if (encoder.encode(programArgs.join('')).length > HARD_SOURCE_BYTES)
|
|
266
|
+
throw new RuntimeConfigurationError('Scala program arguments exceed 1 MiB', {
|
|
267
|
+
runtimeId: 'SCALA'
|
|
268
|
+
});
|
|
269
|
+
const stdin = options.stdin ?? this.pendingInput;
|
|
270
|
+
this.pendingInput = '';
|
|
271
|
+
if (encoder.encode(stdin).length > HARD_SOURCE_BYTES)
|
|
272
|
+
throw new RuntimeConfigurationError('Scala stdin exceeds 1 MiB', {
|
|
273
|
+
runtimeId: 'SCALA'
|
|
274
|
+
});
|
|
275
|
+
await this.ensureCompiler(operation, limits, options, progress);
|
|
276
|
+
this.check(operation);
|
|
277
|
+
progress?.set?.(0.4, 'Compiling Scala and linking Scala.js');
|
|
278
|
+
const compiled = await this.request(this.compiler, {
|
|
279
|
+
files,
|
|
280
|
+
limits: {
|
|
281
|
+
maxDiagnostics: limits.maxDiagnostics,
|
|
282
|
+
maxDiagnosticBytes: limits.maxOutputBytes
|
|
283
|
+
}
|
|
284
|
+
}, operation, 'compile', limits.compileTimeoutMs);
|
|
285
|
+
this.check(operation);
|
|
286
|
+
if (compiled.failureKind === 'diagnostic-limit') {
|
|
287
|
+
if (this.compiler)
|
|
288
|
+
this.retire(this.compiler);
|
|
289
|
+
throw new DiagnosticLimitError(compiled.message ?? 'Scala diagnostic limit exceeded', {
|
|
290
|
+
runtimeId: 'SCALA',
|
|
291
|
+
limit: compiled.limit ?? limits.maxDiagnostics,
|
|
292
|
+
actual: compiled.actual ?? limits.maxDiagnostics + 1
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
const lines = compiled.diagnostics ?? [];
|
|
296
|
+
if (!Array.isArray(lines) || lines.some((line) => typeof line !== 'string'))
|
|
297
|
+
throw new ProtocolError('Invalid Scala diagnostics');
|
|
298
|
+
if (encoder.encode(lines.join('\n')).length > limits.maxOutputBytes)
|
|
299
|
+
throw new DiagnosticLimitError('Scala diagnostics exceed byte budget', {
|
|
300
|
+
runtimeId: 'SCALA',
|
|
301
|
+
limit: limits.maxOutputBytes,
|
|
302
|
+
actual: encoder.encode(lines.join('\n')).length
|
|
303
|
+
});
|
|
304
|
+
const diagnostics = parseScalaDiagnostics(lines, limits.maxDiagnostics);
|
|
305
|
+
for (const diagnostic of diagnostics)
|
|
306
|
+
this.oncompilerdiagnostic?.(diagnostic);
|
|
307
|
+
if (compiled.type !== 'compiled' || typeof compiled.code !== 'string') {
|
|
308
|
+
if (this.compiler)
|
|
309
|
+
this.retire(this.compiler);
|
|
310
|
+
throw new CompileError(lines.join('\n').replace(/\x1b\[[0-9;]*m/g, '') ||
|
|
311
|
+
compiled.message ||
|
|
312
|
+
'Scala compilation failed', { runtimeId: 'SCALA' });
|
|
313
|
+
}
|
|
314
|
+
if (encoder.encode(compiled.code).length > 32 * 1024 * 1024)
|
|
315
|
+
throw new CompileError('Scala generated program exceeds 32 MiB', {
|
|
316
|
+
runtimeId: 'SCALA'
|
|
317
|
+
});
|
|
318
|
+
if (limits.maxWorkers < 2 && this.compiler)
|
|
319
|
+
this.retire(this.compiler);
|
|
320
|
+
this.check(operation);
|
|
321
|
+
const execution = new Worker(new URL('./worker/scala/execution.worker.js', import.meta.url), { type: 'module' });
|
|
322
|
+
this.execution = execution;
|
|
323
|
+
let outputBytes = 0;
|
|
324
|
+
const result = await this.request(execution, {
|
|
325
|
+
code: compiled.code,
|
|
326
|
+
stdin,
|
|
327
|
+
args: programArgs,
|
|
328
|
+
maxOutputBytes: limits.maxOutputBytes
|
|
329
|
+
}, operation, 'execute', limits.runTimeoutMs, (_stream, text) => {
|
|
330
|
+
outputBytes += encoder.encode(text).length;
|
|
331
|
+
if (outputBytes > limits.maxOutputBytes)
|
|
332
|
+
throw new OutputLimitError('Scala output limit exceeded', {
|
|
333
|
+
runtimeId: 'SCALA',
|
|
334
|
+
limit: limits.maxOutputBytes,
|
|
335
|
+
actual: outputBytes
|
|
336
|
+
});
|
|
337
|
+
this.output?.(text);
|
|
338
|
+
}, progress);
|
|
339
|
+
this.check(operation);
|
|
340
|
+
if (result.type !== 'exit' || result.exitCode !== 0) {
|
|
341
|
+
if (/output exceeds/.test(result.message ?? ''))
|
|
342
|
+
throw new OutputLimitError(result.message, {
|
|
343
|
+
runtimeId: 'SCALA',
|
|
344
|
+
limit: limits.maxOutputBytes,
|
|
345
|
+
actual: limits.maxOutputBytes + 1
|
|
346
|
+
});
|
|
347
|
+
throw new RuntimeExecutionError(result.message ?? 'Scala program failed', {
|
|
348
|
+
runtimeId: 'SCALA'
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
outcome = 'completed';
|
|
352
|
+
return true;
|
|
353
|
+
}
|
|
354
|
+
catch (error) {
|
|
355
|
+
if (operation.controller.signal.aborted || error instanceof CancelledError)
|
|
356
|
+
outcome = 'cancelled';
|
|
357
|
+
else if (error instanceof TimeoutError)
|
|
358
|
+
outcome = 'timed-out';
|
|
359
|
+
throw error;
|
|
360
|
+
}
|
|
361
|
+
finally {
|
|
362
|
+
if (this.execution)
|
|
363
|
+
this.retire(this.execution);
|
|
364
|
+
this.elapse = performance.now() - start;
|
|
365
|
+
this.end(operation);
|
|
366
|
+
progress?.report?.({
|
|
367
|
+
kind: 'settled',
|
|
368
|
+
outcome
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
write(data) {
|
|
373
|
+
// The terminal may submit late keystrokes; they cannot extend buffered execution.
|
|
374
|
+
if (this.active || this.disposed)
|
|
375
|
+
return;
|
|
376
|
+
if (encoder.encode(this.pendingInput + data).length > HARD_SOURCE_BYTES)
|
|
377
|
+
throw new RuntimeConfigurationError('Scala stdin exceeds 1 MiB');
|
|
378
|
+
this.pendingInput += data;
|
|
379
|
+
}
|
|
380
|
+
eof() {
|
|
381
|
+
/* Every supplied input buffer ends in EOF; execution is never replayed. */
|
|
382
|
+
}
|
|
383
|
+
terminate() {
|
|
384
|
+
this.active?.controller.abort(new CancelledError('Scala execution stopped', { runtimeId: 'SCALA' }));
|
|
385
|
+
}
|
|
386
|
+
async clear() {
|
|
387
|
+
this.terminate();
|
|
388
|
+
if (this.compiler)
|
|
389
|
+
this.retire(this.compiler);
|
|
390
|
+
this.pendingInput = '';
|
|
391
|
+
}
|
|
392
|
+
async dispose() {
|
|
393
|
+
this.disposed = true;
|
|
394
|
+
await this.clear();
|
|
395
|
+
this.payload = null;
|
|
396
|
+
}
|
|
397
|
+
}
|