@manifest-configuration-language/browser 0.3.22 → 0.3.23
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 +5 -5
- package/dist/index.d.ts +6 -0
- package/dist/index.js +4 -0
- package/dist/limits.d.ts +10 -0
- package/dist/mcl.wasm +2 -2
- package/dist/project.d.ts +66 -0
- package/dist/project.js +170 -0
- package/dist/protocol.d.ts +185 -0
- package/dist/protocol.js +2 -0
- package/dist/runtime.d.ts +81 -0
- package/dist/runtime.js +605 -0
- package/dist/worker.d.ts +41 -0
- package/dist/worker.js +115 -0
- package/package.json +11 -7
- package/src/index.d.ts +0 -250
- package/src/index.js +0 -807
- package/src/protocol.d.ts +0 -206
- package/src/worker.js +0 -204
- /package/{src → dist}/limits.js +0 -0
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
import PQueue from "p-queue";
|
|
2
|
+
import * as Comlink from "comlink";
|
|
3
|
+
import { createProjectSnapshot, computeProjectDelta, isValidProjectPath, operationPriorities, latestOnlyOperations, requestPriorities, maxSourceBytes, } from "./project.js";
|
|
4
|
+
// ---------------------------------------------------------------------------
|
|
5
|
+
// Error class
|
|
6
|
+
// ---------------------------------------------------------------------------
|
|
7
|
+
export class MclRuntimeError extends Error {
|
|
8
|
+
code;
|
|
9
|
+
path;
|
|
10
|
+
line;
|
|
11
|
+
column;
|
|
12
|
+
endLine;
|
|
13
|
+
endColumn;
|
|
14
|
+
related;
|
|
15
|
+
constructor(error) {
|
|
16
|
+
super(error.message);
|
|
17
|
+
this.name = "MclRuntimeError";
|
|
18
|
+
this.code = error.code;
|
|
19
|
+
this.path = error.path;
|
|
20
|
+
this.line = error.line;
|
|
21
|
+
this.column = error.column;
|
|
22
|
+
this.endLine = error.endLine;
|
|
23
|
+
this.endColumn = error.endColumn;
|
|
24
|
+
this.related = error.related;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
// ---------------------------------------------------------------------------
|
|
28
|
+
// Timing helpers
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
const defaultInitializationTimeoutMs = 30_000;
|
|
31
|
+
const defaultOperationTimeoutMs = 10_000;
|
|
32
|
+
const wasmURL = new URL("../dist/mcl.wasm", import.meta.url).href;
|
|
33
|
+
const wasmExecURL = new URL("../dist/wasm_exec.js", import.meta.url).href;
|
|
34
|
+
// ---------------------------------------------------------------------------
|
|
35
|
+
// Runtime factory
|
|
36
|
+
// ---------------------------------------------------------------------------
|
|
37
|
+
export function createMclRuntime(options = {}) {
|
|
38
|
+
const workerFactory = options.workerFactory ??
|
|
39
|
+
(() => new Worker(new URL("./worker.js", import.meta.url), { type: "module" }));
|
|
40
|
+
const initializationTimeoutMs = options.initializationTimeoutMs ?? defaultInitializationTimeoutMs;
|
|
41
|
+
let rawWorker;
|
|
42
|
+
let workerApi;
|
|
43
|
+
let cleanupWorkerListeners;
|
|
44
|
+
let initializationPromise;
|
|
45
|
+
let disposed = false;
|
|
46
|
+
const queue = new PQueue({ concurrency: 1 });
|
|
47
|
+
queue.on("error", () => { });
|
|
48
|
+
const queueSignals = new Set();
|
|
49
|
+
const latestPending = new Map();
|
|
50
|
+
let sequence = 0;
|
|
51
|
+
let workerGeneration = 0;
|
|
52
|
+
// The snapshot currently synced inside the Worker session.
|
|
53
|
+
let workerProjectId;
|
|
54
|
+
let workerSnapshot;
|
|
55
|
+
// Callbacks for aborting the currently-executing step.
|
|
56
|
+
let stopCurrent;
|
|
57
|
+
let stopInitialization;
|
|
58
|
+
// -------------------------------------------------------------------------
|
|
59
|
+
// Observability
|
|
60
|
+
// -------------------------------------------------------------------------
|
|
61
|
+
function emitStatus(status, extra = {}) {
|
|
62
|
+
try {
|
|
63
|
+
Promise.resolve(options.onStatus?.({ status, workerGeneration, ...extra })).catch(() => { });
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
// Observability callbacks must not affect runtime behavior.
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function emitOperation(operation, startedAt, outcome, details = {}) {
|
|
70
|
+
try {
|
|
71
|
+
const durationMs = Math.max(0, performance.now() - startedAt);
|
|
72
|
+
Promise.resolve(options.onOperation?.({
|
|
73
|
+
operation,
|
|
74
|
+
durationMs,
|
|
75
|
+
queueWaitMs: details.executionStartedAt !== undefined
|
|
76
|
+
? Math.max(0, details.executionStartedAt - startedAt)
|
|
77
|
+
: durationMs,
|
|
78
|
+
executionDurationMs: details.executionDurationMs ?? 0,
|
|
79
|
+
...(details.wasmDurationMs === undefined
|
|
80
|
+
? {}
|
|
81
|
+
: { wasmDurationMs: details.wasmDurationMs }),
|
|
82
|
+
...(details.workerGeneration === undefined
|
|
83
|
+
? {}
|
|
84
|
+
: { workerGeneration: details.workerGeneration }),
|
|
85
|
+
outcome,
|
|
86
|
+
})).catch(() => { });
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
// Observability callbacks must not affect runtime behavior.
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
// -------------------------------------------------------------------------
|
|
93
|
+
// Queue management
|
|
94
|
+
// -------------------------------------------------------------------------
|
|
95
|
+
function abortError() {
|
|
96
|
+
return new DOMException("The operation was aborted", "AbortError");
|
|
97
|
+
}
|
|
98
|
+
function enqueue(operation, run, signal, scope, requestedPriority, timing = {}) {
|
|
99
|
+
if (signal?.aborted)
|
|
100
|
+
return Promise.reject(signal.reason ?? abortError());
|
|
101
|
+
const priority = requestPriorities[requestedPriority ?? ""] ??
|
|
102
|
+
operationPriorities[operation] ??
|
|
103
|
+
0;
|
|
104
|
+
const key = (name) => JSON.stringify([scope, name]);
|
|
105
|
+
const pendingKey = key(operation);
|
|
106
|
+
const pendingGroup = () => {
|
|
107
|
+
let group = latestPending.get(pendingKey);
|
|
108
|
+
if (!group) {
|
|
109
|
+
group = new Map();
|
|
110
|
+
latestPending.set(pendingKey, group);
|
|
111
|
+
}
|
|
112
|
+
return group;
|
|
113
|
+
};
|
|
114
|
+
const removePending = (pendingPriority, pending) => {
|
|
115
|
+
const group = latestPending.get(pendingKey);
|
|
116
|
+
if (group?.get(pendingPriority) !== pending)
|
|
117
|
+
return;
|
|
118
|
+
group.delete(pendingPriority);
|
|
119
|
+
if (group.size === 0)
|
|
120
|
+
latestPending.delete(pendingKey);
|
|
121
|
+
};
|
|
122
|
+
const supersedePending = (name, maximumPriority, message) => {
|
|
123
|
+
const groupKey = key(name);
|
|
124
|
+
const group = latestPending.get(groupKey);
|
|
125
|
+
if (!group)
|
|
126
|
+
return;
|
|
127
|
+
for (const [pendingPriority, pending] of group) {
|
|
128
|
+
if (pendingPriority > maximumPriority)
|
|
129
|
+
continue;
|
|
130
|
+
group.delete(pendingPriority);
|
|
131
|
+
pending.controller.abort(new DOMException(message, "AbortError"));
|
|
132
|
+
}
|
|
133
|
+
if (group.size === 0)
|
|
134
|
+
latestPending.delete(groupKey);
|
|
135
|
+
};
|
|
136
|
+
if (["render", "evaluate", "check"].includes(operation)) {
|
|
137
|
+
supersedePending("lint", priority, "An explicit run replaced this pending lint");
|
|
138
|
+
}
|
|
139
|
+
else if (priority > requestPriorities.background && operation !== "lint") {
|
|
140
|
+
supersedePending("lint", requestPriorities.background, "An interactive operation replaced this pending background lint");
|
|
141
|
+
}
|
|
142
|
+
const queueController = new AbortController();
|
|
143
|
+
const pending = { controller: queueController, started: false };
|
|
144
|
+
if (latestOnlyOperations.has(operation)) {
|
|
145
|
+
supersedePending(operation, priority, "A newer operation replaced this request");
|
|
146
|
+
pendingGroup().set(priority, pending);
|
|
147
|
+
}
|
|
148
|
+
queueSignals.add(queueController);
|
|
149
|
+
const abortWhileQueued = () => {
|
|
150
|
+
if (!pending.started)
|
|
151
|
+
queueController.abort(signal?.reason ?? abortError());
|
|
152
|
+
};
|
|
153
|
+
signal?.addEventListener("abort", abortWhileQueued, { once: true });
|
|
154
|
+
return queue
|
|
155
|
+
.add(async () => {
|
|
156
|
+
pending.started = true;
|
|
157
|
+
if (latestOnlyOperations.has(operation))
|
|
158
|
+
removePending(priority, pending);
|
|
159
|
+
timing.executionStartedAt = performance.now();
|
|
160
|
+
try {
|
|
161
|
+
return (await run());
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
timing.executionDurationMs = Math.max(0, performance.now() - timing.executionStartedAt);
|
|
165
|
+
}
|
|
166
|
+
}, { priority, signal: queueController.signal })
|
|
167
|
+
.finally(() => {
|
|
168
|
+
signal?.removeEventListener("abort", abortWhileQueued);
|
|
169
|
+
queueSignals.delete(queueController);
|
|
170
|
+
if (latestOnlyOperations.has(operation))
|
|
171
|
+
removePending(priority, pending);
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
// -------------------------------------------------------------------------
|
|
175
|
+
// Worker lifecycle
|
|
176
|
+
// -------------------------------------------------------------------------
|
|
177
|
+
function startWorker() {
|
|
178
|
+
if (disposed)
|
|
179
|
+
return Promise.reject(new Error("MCL runtime has been disposed"));
|
|
180
|
+
if (initializationPromise)
|
|
181
|
+
return initializationPromise;
|
|
182
|
+
const initializationStartedAt = performance.now();
|
|
183
|
+
const currentRawWorker = workerFactory();
|
|
184
|
+
rawWorker = currentRawWorker;
|
|
185
|
+
const currentApi = Comlink.wrap(currentRawWorker);
|
|
186
|
+
workerApi = currentApi;
|
|
187
|
+
workerGeneration++;
|
|
188
|
+
workerProjectId = undefined;
|
|
189
|
+
workerSnapshot = undefined;
|
|
190
|
+
let lastStatus;
|
|
191
|
+
const reportStatus = (status) => {
|
|
192
|
+
if (lastStatus === status)
|
|
193
|
+
return;
|
|
194
|
+
lastStatus = status;
|
|
195
|
+
if (status === "ready" || status === "error") {
|
|
196
|
+
emitStatus(status, {
|
|
197
|
+
initializationDurationMs: Math.max(0, performance.now() - initializationStartedAt),
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
else {
|
|
201
|
+
emitStatus(status);
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
let resolveReady;
|
|
205
|
+
let rejectReady;
|
|
206
|
+
const initialization = new Promise((resolve, reject) => {
|
|
207
|
+
resolveReady = resolve;
|
|
208
|
+
rejectReady = reject;
|
|
209
|
+
});
|
|
210
|
+
initializationPromise = initialization;
|
|
211
|
+
// Status messages from the worker arrive via standard message events.
|
|
212
|
+
// (Comlink forwards non-Comlink messages transparently.)
|
|
213
|
+
const onStatusMessage = (event) => {
|
|
214
|
+
if (rawWorker !== currentRawWorker)
|
|
215
|
+
return;
|
|
216
|
+
const data = event.data;
|
|
217
|
+
if (data?.type === "status" && typeof data.status === "string") {
|
|
218
|
+
reportStatus(data.status);
|
|
219
|
+
}
|
|
220
|
+
else if (data?.type === "fatal") {
|
|
221
|
+
const error = new Error(typeof data.message === "string" ? data.message : "MCL WebAssembly exited unexpectedly");
|
|
222
|
+
if (initialized) {
|
|
223
|
+
emitStatus("error");
|
|
224
|
+
terminateWorker(error);
|
|
225
|
+
}
|
|
226
|
+
else
|
|
227
|
+
fail(error);
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
currentRawWorker.addEventListener("message", onStatusMessage);
|
|
231
|
+
// Worker-level error (uncaught exception or load failure).
|
|
232
|
+
const onWorkerError = (event) => {
|
|
233
|
+
if (rawWorker !== currentRawWorker)
|
|
234
|
+
return;
|
|
235
|
+
const error = new Error(event.message || "MCL worker failed");
|
|
236
|
+
if (initialized) {
|
|
237
|
+
emitStatus("error");
|
|
238
|
+
terminateWorker(error);
|
|
239
|
+
}
|
|
240
|
+
else
|
|
241
|
+
fail(error);
|
|
242
|
+
};
|
|
243
|
+
currentRawWorker.addEventListener("error", onWorkerError);
|
|
244
|
+
// Malformed message from worker.
|
|
245
|
+
const onMessageError = (event) => {
|
|
246
|
+
if (rawWorker !== currentRawWorker)
|
|
247
|
+
return;
|
|
248
|
+
const error = new Error("MCL worker sent a malformed message");
|
|
249
|
+
if (initialized) {
|
|
250
|
+
emitStatus("error");
|
|
251
|
+
terminateWorker(error);
|
|
252
|
+
}
|
|
253
|
+
else
|
|
254
|
+
fail(error);
|
|
255
|
+
};
|
|
256
|
+
currentRawWorker.addEventListener("messageerror", onMessageError);
|
|
257
|
+
cleanupWorkerListeners = () => {
|
|
258
|
+
currentRawWorker.removeEventListener("message", onStatusMessage);
|
|
259
|
+
currentRawWorker.removeEventListener("error", onWorkerError);
|
|
260
|
+
currentRawWorker.removeEventListener("messageerror", onMessageError);
|
|
261
|
+
};
|
|
262
|
+
let initialized = false;
|
|
263
|
+
const timer = setTimeout(() => fail(new MclRuntimeError({
|
|
264
|
+
code: "MCL-WASM-TIMEOUT",
|
|
265
|
+
message: "MCL WebAssembly initialization timed out",
|
|
266
|
+
})), initializationTimeoutMs);
|
|
267
|
+
function fail(error) {
|
|
268
|
+
if (rawWorker !== currentRawWorker)
|
|
269
|
+
return;
|
|
270
|
+
if (!initialized)
|
|
271
|
+
reportStatus("error");
|
|
272
|
+
clearTimeout(timer);
|
|
273
|
+
if (stopInitialization === fail)
|
|
274
|
+
stopInitialization = undefined;
|
|
275
|
+
terminateWorker(error);
|
|
276
|
+
rejectReady(error);
|
|
277
|
+
}
|
|
278
|
+
stopInitialization = fail;
|
|
279
|
+
// Kick off WASM initialization via Comlink.
|
|
280
|
+
currentApi
|
|
281
|
+
.initialize({ wasmURL, wasmExecURL })
|
|
282
|
+
.then(() => {
|
|
283
|
+
if (rawWorker !== currentRawWorker)
|
|
284
|
+
return;
|
|
285
|
+
initialized = true;
|
|
286
|
+
reportStatus("ready");
|
|
287
|
+
clearTimeout(timer);
|
|
288
|
+
if (stopInitialization === fail)
|
|
289
|
+
stopInitialization = undefined;
|
|
290
|
+
resolveReady();
|
|
291
|
+
})
|
|
292
|
+
.catch((error) => {
|
|
293
|
+
fail(error instanceof Error ? error : new Error(String(error)));
|
|
294
|
+
});
|
|
295
|
+
return initialization;
|
|
296
|
+
}
|
|
297
|
+
function terminateWorker(error) {
|
|
298
|
+
const currentWorker = rawWorker;
|
|
299
|
+
const currentApi = workerApi;
|
|
300
|
+
const currentStop = stopCurrent;
|
|
301
|
+
const cleanup = cleanupWorkerListeners;
|
|
302
|
+
cleanupWorkerListeners = undefined;
|
|
303
|
+
rawWorker = undefined;
|
|
304
|
+
workerApi = undefined;
|
|
305
|
+
initializationPromise = undefined;
|
|
306
|
+
workerProjectId = undefined;
|
|
307
|
+
workerSnapshot = undefined;
|
|
308
|
+
stopCurrent = undefined;
|
|
309
|
+
cleanup?.();
|
|
310
|
+
currentWorker?.terminate();
|
|
311
|
+
currentApi?.[Comlink.releaseProxy]();
|
|
312
|
+
currentStop?.(error);
|
|
313
|
+
}
|
|
314
|
+
function runWorkerCall(signal, call) {
|
|
315
|
+
return new Promise((resolve, reject) => {
|
|
316
|
+
let settled = false;
|
|
317
|
+
const finish = (error, value) => {
|
|
318
|
+
if (settled)
|
|
319
|
+
return;
|
|
320
|
+
settled = true;
|
|
321
|
+
signal?.removeEventListener("abort", onAbort);
|
|
322
|
+
if (stopCurrent === stop)
|
|
323
|
+
stopCurrent = undefined;
|
|
324
|
+
if (error)
|
|
325
|
+
reject(error);
|
|
326
|
+
else
|
|
327
|
+
resolve(value);
|
|
328
|
+
};
|
|
329
|
+
const stop = (error) => {
|
|
330
|
+
finish(error);
|
|
331
|
+
terminateWorker(error);
|
|
332
|
+
};
|
|
333
|
+
const onAbort = () => stop(new DOMException("The operation was aborted", "AbortError"));
|
|
334
|
+
stopCurrent = stop;
|
|
335
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
336
|
+
if (signal?.aborted) {
|
|
337
|
+
onAbort();
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
try {
|
|
341
|
+
call().then((value) => finish(undefined, value), (error) => {
|
|
342
|
+
stop(error instanceof Error ? error : new Error(String(error)));
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
catch (error) {
|
|
346
|
+
stop(error instanceof Error ? error : new Error(String(error)));
|
|
347
|
+
}
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
async function waitUntilReady(signal) {
|
|
351
|
+
if (!signal)
|
|
352
|
+
return startWorker();
|
|
353
|
+
if (signal.aborted)
|
|
354
|
+
throw new DOMException("The operation was aborted", "AbortError");
|
|
355
|
+
let onAbort;
|
|
356
|
+
try {
|
|
357
|
+
await Promise.race([
|
|
358
|
+
startWorker(),
|
|
359
|
+
new Promise((_, reject) => {
|
|
360
|
+
onAbort = () => {
|
|
361
|
+
stopInitialization?.(new DOMException("The operation was aborted", "AbortError"));
|
|
362
|
+
reject(new DOMException("The operation was aborted", "AbortError"));
|
|
363
|
+
};
|
|
364
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
365
|
+
}),
|
|
366
|
+
]);
|
|
367
|
+
}
|
|
368
|
+
finally {
|
|
369
|
+
if (onAbort)
|
|
370
|
+
signal.removeEventListener("abort", onAbort);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
// -------------------------------------------------------------------------
|
|
374
|
+
// Project sync
|
|
375
|
+
// -------------------------------------------------------------------------
|
|
376
|
+
async function syncProjectToWorker(projectId, snapshot, requestOptions) {
|
|
377
|
+
if (workerProjectId === projectId && workerSnapshot === snapshot)
|
|
378
|
+
return;
|
|
379
|
+
const api = workerApi;
|
|
380
|
+
const previousSnapshot = workerProjectId === projectId ? workerSnapshot : undefined;
|
|
381
|
+
const reset = workerProjectId !== projectId;
|
|
382
|
+
const result = computeProjectDelta(snapshot, previousSnapshot, reset);
|
|
383
|
+
if (result === null)
|
|
384
|
+
return; // nothing changed
|
|
385
|
+
const { delta, binaryFiles, transferables } = result;
|
|
386
|
+
const updateJSON = JSON.stringify(delta);
|
|
387
|
+
// Transfer binary buffers to avoid copying.
|
|
388
|
+
const transferableBinaries = Object.create(null);
|
|
389
|
+
for (const [path, bytes] of Object.entries(binaryFiles)) {
|
|
390
|
+
transferableBinaries[path] = bytes;
|
|
391
|
+
}
|
|
392
|
+
const response = await runWorkerCall(requestOptions.signal, () => api.updateProject(projectId, updateJSON, Comlink.transfer(transferableBinaries, transferables)));
|
|
393
|
+
if (!response.ok)
|
|
394
|
+
throw new MclRuntimeError(response.error ?? { code: "MCL-WASM-PROJECT", message: "Project update failed" });
|
|
395
|
+
workerProjectId = projectId;
|
|
396
|
+
workerSnapshot = snapshot;
|
|
397
|
+
}
|
|
398
|
+
// -------------------------------------------------------------------------
|
|
399
|
+
// Core execute function
|
|
400
|
+
// -------------------------------------------------------------------------
|
|
401
|
+
async function execute(operation, source, requestOptions, entrypoint, project) {
|
|
402
|
+
if (requestOptions.parameters !== undefined) {
|
|
403
|
+
if (!["check", "evaluate", "render"].includes(operation)) {
|
|
404
|
+
throw new TypeError("parameters are only valid for check, evaluate, and render operations");
|
|
405
|
+
}
|
|
406
|
+
const parameters = requestOptions.parameters;
|
|
407
|
+
if (parameters === null || typeof parameters !== "object" || Array.isArray(parameters)) {
|
|
408
|
+
throw new TypeError("parameters must be an object with string values");
|
|
409
|
+
}
|
|
410
|
+
for (const value of Object.values(parameters)) {
|
|
411
|
+
if (typeof value !== "string") {
|
|
412
|
+
throw new TypeError("parameters must be an object with string values");
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
// Validate renameFileImports paths eagerly so we never spin up a Worker.
|
|
417
|
+
if (operation === "renameFileImports") {
|
|
418
|
+
const { oldPath, newPath } = requestOptions;
|
|
419
|
+
if (!isValidProjectPath(oldPath) ||
|
|
420
|
+
!oldPath.endsWith(".mcl") ||
|
|
421
|
+
!isValidProjectPath(newPath) ||
|
|
422
|
+
!newPath.endsWith(".mcl")) {
|
|
423
|
+
throw new TypeError("oldPath and newPath must be valid project-relative MCL paths");
|
|
424
|
+
}
|
|
425
|
+
if (oldPath === newPath)
|
|
426
|
+
throw new TypeError("oldPath and newPath must be distinct");
|
|
427
|
+
}
|
|
428
|
+
const { signal } = requestOptions;
|
|
429
|
+
if (signal?.aborted)
|
|
430
|
+
throw new DOMException("The operation was aborted", "AbortError");
|
|
431
|
+
const startedAt = performance.now();
|
|
432
|
+
const timing = {};
|
|
433
|
+
let operationWorkerGeneration;
|
|
434
|
+
const run = async () => {
|
|
435
|
+
if (disposed)
|
|
436
|
+
throw new Error("MCL runtime has been disposed");
|
|
437
|
+
if (signal?.aborted)
|
|
438
|
+
throw new DOMException("The operation was aborted", "AbortError");
|
|
439
|
+
const timeoutMs = requestOptions.timeoutMs ?? options.operationTimeoutMs ?? defaultOperationTimeoutMs;
|
|
440
|
+
const timeoutError = new MclRuntimeError({
|
|
441
|
+
code: "MCL-WASM-TIMEOUT",
|
|
442
|
+
message: "MCL operation timed out",
|
|
443
|
+
});
|
|
444
|
+
let timer;
|
|
445
|
+
try {
|
|
446
|
+
if (timeoutMs <= 0)
|
|
447
|
+
throw timeoutError;
|
|
448
|
+
timer = setTimeout(() => {
|
|
449
|
+
if (stopCurrent)
|
|
450
|
+
stopCurrent(timeoutError);
|
|
451
|
+
else
|
|
452
|
+
stopInitialization?.(timeoutError);
|
|
453
|
+
}, timeoutMs);
|
|
454
|
+
await waitUntilReady(signal);
|
|
455
|
+
if (signal?.aborted)
|
|
456
|
+
throw new DOMException("The operation was aborted", "AbortError");
|
|
457
|
+
const currentApi = workerApi;
|
|
458
|
+
const currentGeneration = workerGeneration;
|
|
459
|
+
operationWorkerGeneration = currentGeneration;
|
|
460
|
+
if (project) {
|
|
461
|
+
await syncProjectToWorker(project.id, project.snapshot, requestOptions);
|
|
462
|
+
}
|
|
463
|
+
// Build the WASM request.
|
|
464
|
+
const requestId = ++sequence;
|
|
465
|
+
const request = {
|
|
466
|
+
requestId,
|
|
467
|
+
revision: requestId,
|
|
468
|
+
operation,
|
|
469
|
+
entrypoint,
|
|
470
|
+
source,
|
|
471
|
+
...(requestOptions.parameters !== undefined
|
|
472
|
+
? { parameters: { ...requestOptions.parameters } }
|
|
473
|
+
: {}),
|
|
474
|
+
...(requestOptions.position ? { position: requestOptions.position } : {}),
|
|
475
|
+
...(requestOptions.newName ? { newName: requestOptions.newName } : {}),
|
|
476
|
+
...(requestOptions.oldPath ? { oldPath: requestOptions.oldPath } : {}),
|
|
477
|
+
...(requestOptions.newPath ? { newPath: requestOptions.newPath } : {}),
|
|
478
|
+
};
|
|
479
|
+
timing.wasmStartedAt = performance.now();
|
|
480
|
+
let response;
|
|
481
|
+
try {
|
|
482
|
+
response = await runWorkerCall(signal, () => currentApi.run(JSON.stringify(request), project.id));
|
|
483
|
+
}
|
|
484
|
+
finally {
|
|
485
|
+
timing.wasmDurationMs = Math.max(0, performance.now() - timing.wasmStartedAt);
|
|
486
|
+
clearTimeout(timer);
|
|
487
|
+
}
|
|
488
|
+
if (!response.ok) {
|
|
489
|
+
throw new MclRuntimeError(response.error ?? { code: "MCL-WASM-RESPONSE", message: "Operation failed" });
|
|
490
|
+
}
|
|
491
|
+
if (operation === "lint") {
|
|
492
|
+
return { operation, diagnostics: (response.result ?? []) };
|
|
493
|
+
}
|
|
494
|
+
return { operation, ...response.result };
|
|
495
|
+
}
|
|
496
|
+
catch (error) {
|
|
497
|
+
clearTimeout(timer);
|
|
498
|
+
throw error;
|
|
499
|
+
}
|
|
500
|
+
};
|
|
501
|
+
try {
|
|
502
|
+
const result = await enqueue(operation, run, signal, project.id, requestOptions.priority, timing);
|
|
503
|
+
emitOperation(operation, startedAt, "success", {
|
|
504
|
+
...timing,
|
|
505
|
+
workerGeneration: operationWorkerGeneration,
|
|
506
|
+
});
|
|
507
|
+
return result;
|
|
508
|
+
}
|
|
509
|
+
catch (error) {
|
|
510
|
+
emitOperation(operation, startedAt, error?.name === "AbortError" ? "aborted" : "error", { ...timing, workerGeneration: operationWorkerGeneration });
|
|
511
|
+
throw error;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
// -------------------------------------------------------------------------
|
|
515
|
+
// Project handle factory
|
|
516
|
+
// -------------------------------------------------------------------------
|
|
517
|
+
function makeProject(id, snapshot) {
|
|
518
|
+
const runProjectOperation = async (operation, requestOptions = {}) => {
|
|
519
|
+
const entrypoint = requestOptions.entrypoint ?? snapshot.defaultEntrypoint;
|
|
520
|
+
if (!entrypoint)
|
|
521
|
+
throw new TypeError("Set entrypoint when the project has multiple MCL source files");
|
|
522
|
+
if (!isValidProjectPath(entrypoint) || !Object.hasOwn(snapshot.files, entrypoint))
|
|
523
|
+
throw new TypeError(`Project entrypoint does not exist: ${entrypoint}`);
|
|
524
|
+
const entry = snapshot.files[entrypoint];
|
|
525
|
+
const source = typeof entry === "string"
|
|
526
|
+
? entry
|
|
527
|
+
: new TextDecoder("utf-8", { fatal: true }).decode(entry);
|
|
528
|
+
const sourceBytes = new TextEncoder().encode(source).byteLength;
|
|
529
|
+
if (sourceBytes > maxSourceBytes)
|
|
530
|
+
throw new RangeError(`Source exceeds the ${maxSourceBytes}-byte limit`);
|
|
531
|
+
return execute(operation, source, requestOptions, entrypoint, { id, snapshot });
|
|
532
|
+
};
|
|
533
|
+
const projectApi = Object.freeze({
|
|
534
|
+
patch(changes) {
|
|
535
|
+
// Build new file set from current snapshot + changes.
|
|
536
|
+
const merged = Object.create(null);
|
|
537
|
+
const deleted = new Set(changes.delete);
|
|
538
|
+
for (const [path, content] of Object.entries(snapshot.files)) {
|
|
539
|
+
if (!deleted.has(path))
|
|
540
|
+
merged[path] = content;
|
|
541
|
+
}
|
|
542
|
+
if (changes.set) {
|
|
543
|
+
for (const [path, content] of Object.entries(changes.set)) {
|
|
544
|
+
merged[path] = content;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
return makeProject(id, createProjectSnapshot(merged, snapshot));
|
|
548
|
+
},
|
|
549
|
+
run: ((operation, opts) => runProjectOperation(operation, opts)),
|
|
550
|
+
});
|
|
551
|
+
return projectApi;
|
|
552
|
+
}
|
|
553
|
+
// -------------------------------------------------------------------------
|
|
554
|
+
// warmUp
|
|
555
|
+
// -------------------------------------------------------------------------
|
|
556
|
+
function warmUp(requestOptions = {}) {
|
|
557
|
+
const { signal } = requestOptions;
|
|
558
|
+
if (signal?.aborted)
|
|
559
|
+
return Promise.reject(new DOMException("The operation was aborted", "AbortError"));
|
|
560
|
+
const run = async () => {
|
|
561
|
+
if (disposed)
|
|
562
|
+
throw new Error("MCL runtime has been disposed");
|
|
563
|
+
if (signal?.aborted)
|
|
564
|
+
throw new DOMException("The operation was aborted", "AbortError");
|
|
565
|
+
const timeoutMs = requestOptions.timeoutMs ?? initializationTimeoutMs;
|
|
566
|
+
const timeoutError = new MclRuntimeError({
|
|
567
|
+
code: "MCL-WASM-TIMEOUT",
|
|
568
|
+
message: "MCL WebAssembly initialization timed out",
|
|
569
|
+
});
|
|
570
|
+
let timer;
|
|
571
|
+
try {
|
|
572
|
+
if (timeoutMs <= 0)
|
|
573
|
+
throw timeoutError;
|
|
574
|
+
timer = setTimeout(() => stopInitialization?.(timeoutError), timeoutMs);
|
|
575
|
+
await waitUntilReady(signal);
|
|
576
|
+
}
|
|
577
|
+
finally {
|
|
578
|
+
clearTimeout(timer);
|
|
579
|
+
}
|
|
580
|
+
};
|
|
581
|
+
return enqueue("warmUp", run, signal, "runtime", requestOptions.priority);
|
|
582
|
+
}
|
|
583
|
+
// -------------------------------------------------------------------------
|
|
584
|
+
// Public runtime object
|
|
585
|
+
// -------------------------------------------------------------------------
|
|
586
|
+
return {
|
|
587
|
+
openProject(files) {
|
|
588
|
+
const snapshot = createProjectSnapshot(files);
|
|
589
|
+
const id = `mcl-project-${++sequence}`;
|
|
590
|
+
return makeProject(id, snapshot);
|
|
591
|
+
},
|
|
592
|
+
warmUp,
|
|
593
|
+
dispose() {
|
|
594
|
+
if (disposed)
|
|
595
|
+
return;
|
|
596
|
+
disposed = true;
|
|
597
|
+
const error = new Error("MCL runtime has been disposed");
|
|
598
|
+
for (const controller of queueSignals)
|
|
599
|
+
controller.abort(error);
|
|
600
|
+
stopCurrent?.(error);
|
|
601
|
+
stopInitialization?.(error);
|
|
602
|
+
terminateWorker(error);
|
|
603
|
+
},
|
|
604
|
+
};
|
|
605
|
+
}
|
package/dist/worker.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Response } from "./protocol.js";
|
|
2
|
+
export type RuntimeStatus = "fetching" | "compiling" | "initializing" | "ready" | "error";
|
|
3
|
+
export interface RuntimeAssets {
|
|
4
|
+
wasmURL: string;
|
|
5
|
+
wasmExecURL: string;
|
|
6
|
+
}
|
|
7
|
+
/** Encoded file sent from the main thread. Binary files omit `content`. */
|
|
8
|
+
export interface EncodedFile {
|
|
9
|
+
encoding: "utf8" | "binary";
|
|
10
|
+
content?: string;
|
|
11
|
+
}
|
|
12
|
+
/** A project update delta serialised as JSON. */
|
|
13
|
+
export type ProjectUpdateJSON = string;
|
|
14
|
+
export interface WorkerApi {
|
|
15
|
+
/**
|
|
16
|
+
* Load the WASM binary and initialise the Go runtime.
|
|
17
|
+
* Must be called once before any other method.
|
|
18
|
+
*/
|
|
19
|
+
initialize(assets: RuntimeAssets): Promise<void>;
|
|
20
|
+
/**
|
|
21
|
+
* Apply a project snapshot delta to the in-WASM session.
|
|
22
|
+
* Returns the WASM JSON response directly.
|
|
23
|
+
*/
|
|
24
|
+
updateProject(projectId: string, updateJSON: ProjectUpdateJSON, binaryFiles: Record<string, Uint8Array>): Response;
|
|
25
|
+
/**
|
|
26
|
+
* Execute an MCL operation and return the WASM JSON response.
|
|
27
|
+
* Pass `projectId` to run inside a project session.
|
|
28
|
+
*/
|
|
29
|
+
run(requestJSON: string, projectId?: string): Response;
|
|
30
|
+
}
|
|
31
|
+
declare global {
|
|
32
|
+
var mclWasmReady: boolean | undefined;
|
|
33
|
+
var mclWasm: {
|
|
34
|
+
updateProject(projectId: string, updateJSON: string, binaryFiles: Record<string, Uint8Array>): string;
|
|
35
|
+
run(requestJSON: string, binaryFiles: Record<string, Uint8Array>, projectId?: string): string;
|
|
36
|
+
};
|
|
37
|
+
var Go: new () => {
|
|
38
|
+
importObject: WebAssembly.Imports;
|
|
39
|
+
run(instance: WebAssembly.Instance): Promise<void>;
|
|
40
|
+
};
|
|
41
|
+
}
|