@manifest-configuration-language/browser 0.4.6 → 0.4.8

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/dist/mcl.wasm CHANGED
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/dist/mcl.wasm
3
- size: 105461896 bytes
4
- sha256: 207a8264f9eb8a2b770622ec9b76ba8fa36c4ad58a62eb930b344ba584fda8b0
3
+ size: 105752732 bytes
4
+ sha256: 2f88848bd9efa0cd06490daa31299281641f5a564645d48dbf2cc60a7a3ef4f9
@@ -0,0 +1,13 @@
1
+ import * as Comlink from "comlink";
2
+ import type { WorkerApi } from "./worker.js";
3
+ import type { ProjectSnapshot, RequestOptions } from "./project.js";
4
+ import type { Error as ProtocolError } from "./protocol.js";
5
+ type ProjectApi = Comlink.Remote<WorkerApi>;
6
+ export declare function createProjectSynchronizer(getApi: () => ProjectApi | undefined, runCall: <T>(signal: AbortSignal | undefined, call: () => Promise<T>) => Promise<T>, makeError: (error: Partial<ProtocolError> & {
7
+ code: string;
8
+ message: string;
9
+ }) => Error): {
10
+ sync: (projectId: string, snapshot: ProjectSnapshot, requestOptions: RequestOptions) => Promise<void>;
11
+ reset: () => void;
12
+ };
13
+ export {};
@@ -0,0 +1,35 @@
1
+ import * as Comlink from "comlink";
2
+ import { computeProjectDelta } from "./project.js";
3
+ export function createProjectSynchronizer(getApi, runCall, makeError) {
4
+ let workerProjectId;
5
+ let workerSnapshot;
6
+ async function sync(projectId, snapshot, requestOptions) {
7
+ if (workerProjectId === projectId && workerSnapshot === snapshot)
8
+ return;
9
+ const api = getApi();
10
+ const previousSnapshot = workerProjectId === projectId ? workerSnapshot : undefined;
11
+ const reset = workerProjectId !== projectId;
12
+ const result = computeProjectDelta(snapshot, previousSnapshot, reset);
13
+ if (result === null) {
14
+ workerSnapshot = snapshot;
15
+ return;
16
+ }
17
+ const { delta, binaryFiles, transferables } = result;
18
+ const updateJSON = JSON.stringify(delta);
19
+ const transferableBinaries = Object.create(null);
20
+ for (const [path, bytes] of Object.entries(binaryFiles)) {
21
+ transferableBinaries[path] = bytes;
22
+ }
23
+ const response = await runCall(requestOptions.signal, () => api.updateProject(projectId, updateJSON, Comlink.transfer(transferableBinaries, transferables)));
24
+ if (!response.ok) {
25
+ throw makeError(response.error ?? { code: "MCL-WASM-PROJECT", message: "Project update failed" });
26
+ }
27
+ workerProjectId = projectId;
28
+ workerSnapshot = snapshot;
29
+ }
30
+ function reset() {
31
+ workerProjectId = undefined;
32
+ workerSnapshot = undefined;
33
+ }
34
+ return { sync, reset };
35
+ }
@@ -0,0 +1,17 @@
1
+ import type { Error as ProtocolError, Request, Response } from "./protocol.js";
2
+ type RequestFields = {
3
+ parameters?: Record<string, unknown>;
4
+ position?: {
5
+ line: number;
6
+ character: number;
7
+ };
8
+ newName?: string;
9
+ oldPath?: string;
10
+ newPath?: string;
11
+ };
12
+ export declare function createWasmRequest(requestId: number, operation: Request["operation"], entrypoint: string, source: string, options: RequestFields): Request;
13
+ export declare function decodeWasmResponse(operation: Request["operation"], response: Response, makeError: (error: Partial<ProtocolError> & {
14
+ code: string;
15
+ message: string;
16
+ }) => Error): object;
17
+ export {};
@@ -0,0 +1,23 @@
1
+ export function createWasmRequest(requestId, operation, entrypoint, source, options) {
2
+ return {
3
+ requestId,
4
+ revision: requestId,
5
+ operation,
6
+ entrypoint,
7
+ source,
8
+ ...(options.parameters !== undefined ? { parameters: { ...options.parameters } } : {}),
9
+ ...(options.position ? { position: options.position } : {}),
10
+ ...(options.newName ? { newName: options.newName } : {}),
11
+ ...(options.oldPath ? { oldPath: options.oldPath } : {}),
12
+ ...(options.newPath ? { newPath: options.newPath } : {}),
13
+ };
14
+ }
15
+ export function decodeWasmResponse(operation, response, makeError) {
16
+ if (!response.ok) {
17
+ throw makeError(response.error ?? { code: "MCL-WASM-RESPONSE", message: "Operation failed" });
18
+ }
19
+ if (operation === "lint") {
20
+ return { operation, diagnostics: (response.result ?? []) };
21
+ }
22
+ return { operation, ...response.result };
23
+ }
@@ -0,0 +1,8 @@
1
+ export type RuntimeQueueTiming = {
2
+ executionStartedAt?: number;
3
+ executionDurationMs?: number;
4
+ };
5
+ export declare function createRuntimeScheduler(): {
6
+ enqueue: <T>(operation: string, run: () => Promise<T>, signal: AbortSignal | undefined, scope: string, requestedPriority: string | undefined, timing?: RuntimeQueueTiming) => Promise<T>;
7
+ abortAll: (reason: Error) => void;
8
+ };
@@ -0,0 +1,92 @@
1
+ import PQueue from "p-queue";
2
+ import { operationPriorities, latestOnlyOperations, requestPriorities, } from "./project.js";
3
+ export function createRuntimeScheduler() {
4
+ const queue = new PQueue({ concurrency: 1 });
5
+ queue.on("error", () => { });
6
+ const signals = new Set();
7
+ const latestPending = new Map();
8
+ function abortError() {
9
+ return new DOMException("The operation was aborted", "AbortError");
10
+ }
11
+ function enqueue(operation, run, signal, scope, requestedPriority, timing = {}) {
12
+ if (signal?.aborted)
13
+ return Promise.reject(signal.reason ?? abortError());
14
+ const priority = requestPriorities[requestedPriority ?? ""] ??
15
+ operationPriorities[operation] ??
16
+ 0;
17
+ const key = (name) => JSON.stringify([scope, name]);
18
+ const pendingKey = key(operation);
19
+ const pendingGroup = () => {
20
+ let group = latestPending.get(pendingKey);
21
+ if (!group) {
22
+ group = new Map();
23
+ latestPending.set(pendingKey, group);
24
+ }
25
+ return group;
26
+ };
27
+ const removePending = (pendingPriority, pending) => {
28
+ const group = latestPending.get(pendingKey);
29
+ if (group?.get(pendingPriority) !== pending)
30
+ return;
31
+ group.delete(pendingPriority);
32
+ if (group.size === 0)
33
+ latestPending.delete(pendingKey);
34
+ };
35
+ const supersedePending = (name, maximumPriority, message) => {
36
+ const groupKey = key(name);
37
+ const group = latestPending.get(groupKey);
38
+ if (!group)
39
+ return;
40
+ for (const [pendingPriority, pending] of group) {
41
+ if (pendingPriority > maximumPriority)
42
+ continue;
43
+ group.delete(pendingPriority);
44
+ pending.controller.abort(new DOMException(message, "AbortError"));
45
+ }
46
+ if (group.size === 0)
47
+ latestPending.delete(groupKey);
48
+ };
49
+ if (["render", "evaluate", "check"].includes(operation)) {
50
+ supersedePending("lint", priority, "An explicit run replaced this pending lint");
51
+ }
52
+ else if (priority > requestPriorities.background && operation !== "lint") {
53
+ supersedePending("lint", requestPriorities.background, "An interactive operation replaced this pending background lint");
54
+ }
55
+ const queueController = new AbortController();
56
+ const pending = { controller: queueController, started: false };
57
+ if (latestOnlyOperations.has(operation)) {
58
+ supersedePending(operation, priority, "A newer operation replaced this request");
59
+ pendingGroup().set(priority, pending);
60
+ }
61
+ signals.add(queueController);
62
+ const abortWhileQueued = () => {
63
+ if (!pending.started)
64
+ queueController.abort(signal?.reason ?? abortError());
65
+ };
66
+ signal?.addEventListener("abort", abortWhileQueued, { once: true });
67
+ return queue
68
+ .add(async () => {
69
+ pending.started = true;
70
+ if (latestOnlyOperations.has(operation))
71
+ removePending(priority, pending);
72
+ timing.executionStartedAt = performance.now();
73
+ try {
74
+ return (await run());
75
+ }
76
+ finally {
77
+ timing.executionDurationMs = Math.max(0, performance.now() - timing.executionStartedAt);
78
+ }
79
+ }, { priority, signal: queueController.signal })
80
+ .finally(() => {
81
+ signal?.removeEventListener("abort", abortWhileQueued);
82
+ signals.delete(queueController);
83
+ if (latestOnlyOperations.has(operation))
84
+ removePending(priority, pending);
85
+ });
86
+ }
87
+ function abortAll(reason) {
88
+ for (const controller of signals)
89
+ controller.abort(reason);
90
+ }
91
+ return { enqueue, abortAll };
92
+ }
@@ -0,0 +1,22 @@
1
+ import * as Comlink from "comlink";
2
+ import type { WorkerApi } from "./worker.js";
3
+ export type WorkerStatus = "fetching" | "compiling" | "initializing" | "ready" | "error";
4
+ export type WorkerStatusDetails = {
5
+ initializationDurationMs?: number;
6
+ };
7
+ export type WorkerSupervisorHooks = {
8
+ emitStatus: (status: WorkerStatus, details?: WorkerStatusDetails) => void;
9
+ onGeneration: (generation: number) => void;
10
+ onReset: () => void;
11
+ };
12
+ export declare function createWorkerSupervisor(workerFactory: () => Worker, initializationTimeoutMs: number, makeInitializationTimeoutError: () => Error, hooks: WorkerSupervisorHooks): {
13
+ readonly api: Comlink.Remote<WorkerApi> | undefined;
14
+ readonly generation: number;
15
+ start: () => Promise<void>;
16
+ waitUntilReady: (signal: AbortSignal | undefined) => Promise<void>;
17
+ runCall: <T>(signal: AbortSignal | undefined, call: () => Promise<T>) => Promise<T>;
18
+ stopCurrent(error: Error): void;
19
+ stopInitialization(error: Error): void;
20
+ terminate: (error: Error) => void;
21
+ dispose: (error: Error) => void;
22
+ };
@@ -0,0 +1,219 @@
1
+ import * as Comlink from "comlink";
2
+ const wasmURL = new URL("../dist/mcl.wasm", import.meta.url).href;
3
+ const wasmExecURL = new URL("../dist/wasm_exec.js", import.meta.url).href;
4
+ export function createWorkerSupervisor(workerFactory, initializationTimeoutMs, makeInitializationTimeoutError, hooks) {
5
+ let rawWorker;
6
+ let workerApi;
7
+ let cleanupWorkerListeners;
8
+ let initializationPromise;
9
+ let workerGeneration = 0;
10
+ let stopCurrent;
11
+ let stopInitialization;
12
+ let disposed = false;
13
+ function start() {
14
+ if (disposed)
15
+ return Promise.reject(new Error("MCL runtime has been disposed"));
16
+ if (initializationPromise)
17
+ return initializationPromise;
18
+ const initializationStartedAt = performance.now();
19
+ const currentRawWorker = workerFactory();
20
+ rawWorker = currentRawWorker;
21
+ const currentApi = Comlink.wrap(currentRawWorker);
22
+ workerApi = currentApi;
23
+ workerGeneration++;
24
+ hooks.onGeneration(workerGeneration);
25
+ hooks.onReset();
26
+ let lastStatus;
27
+ const reportStatus = (status) => {
28
+ if (lastStatus === status)
29
+ return;
30
+ lastStatus = status;
31
+ if (status === "ready" || status === "error") {
32
+ hooks.emitStatus(status, {
33
+ initializationDurationMs: Math.max(0, performance.now() - initializationStartedAt),
34
+ });
35
+ }
36
+ else {
37
+ hooks.emitStatus(status);
38
+ }
39
+ };
40
+ let resolveReady;
41
+ let rejectReady;
42
+ const initialization = new Promise((resolve, reject) => {
43
+ resolveReady = resolve;
44
+ rejectReady = reject;
45
+ });
46
+ initializationPromise = initialization;
47
+ const onStatusMessage = (event) => {
48
+ if (rawWorker !== currentRawWorker)
49
+ return;
50
+ const data = event.data;
51
+ if (data?.type === "status" && typeof data.status === "string") {
52
+ reportStatus(data.status);
53
+ }
54
+ else if (data?.type === "fatal") {
55
+ const error = new Error(typeof data.message === "string" ? data.message : "MCL WebAssembly exited unexpectedly");
56
+ if (initialized)
57
+ terminate(error);
58
+ else
59
+ fail(error);
60
+ }
61
+ };
62
+ currentRawWorker.addEventListener("message", onStatusMessage);
63
+ const onWorkerError = (event) => {
64
+ if (rawWorker !== currentRawWorker)
65
+ return;
66
+ const error = new Error(event.message || "MCL worker failed");
67
+ if (initialized)
68
+ terminate(error);
69
+ else
70
+ fail(error);
71
+ };
72
+ currentRawWorker.addEventListener("error", onWorkerError);
73
+ const onMessageError = (_event) => {
74
+ if (rawWorker !== currentRawWorker)
75
+ return;
76
+ const error = new Error("MCL worker sent a malformed message");
77
+ if (initialized)
78
+ terminate(error);
79
+ else
80
+ fail(error);
81
+ };
82
+ currentRawWorker.addEventListener("messageerror", onMessageError);
83
+ cleanupWorkerListeners = () => {
84
+ currentRawWorker.removeEventListener("message", onStatusMessage);
85
+ currentRawWorker.removeEventListener("error", onWorkerError);
86
+ currentRawWorker.removeEventListener("messageerror", onMessageError);
87
+ };
88
+ let initialized = false;
89
+ const timer = setTimeout(() => fail(makeInitializationTimeoutError()), initializationTimeoutMs);
90
+ function fail(error) {
91
+ if (rawWorker !== currentRawWorker)
92
+ return;
93
+ clearTimeout(timer);
94
+ if (stopInitialization === fail)
95
+ stopInitialization = undefined;
96
+ terminate(error);
97
+ rejectReady(error);
98
+ }
99
+ stopInitialization = fail;
100
+ currentApi
101
+ .initialize({ wasmURL, wasmExecURL })
102
+ .then(() => {
103
+ if (rawWorker !== currentRawWorker)
104
+ return;
105
+ initialized = true;
106
+ reportStatus("ready");
107
+ clearTimeout(timer);
108
+ if (stopInitialization === fail)
109
+ stopInitialization = undefined;
110
+ resolveReady();
111
+ })
112
+ .catch((error) => {
113
+ fail(error instanceof Error ? error : new Error(String(error)));
114
+ });
115
+ return initialization;
116
+ }
117
+ function terminate(error) {
118
+ const currentWorker = rawWorker;
119
+ if (!currentWorker)
120
+ return;
121
+ const currentApi = workerApi;
122
+ const currentStop = stopCurrent;
123
+ const cleanup = cleanupWorkerListeners;
124
+ cleanupWorkerListeners = undefined;
125
+ rawWorker = undefined;
126
+ workerApi = undefined;
127
+ initializationPromise = undefined;
128
+ stopCurrent = undefined;
129
+ hooks.onReset();
130
+ if (!disposed && error.name !== "AbortError")
131
+ hooks.emitStatus("error");
132
+ cleanup?.();
133
+ currentWorker.terminate();
134
+ currentApi?.[Comlink.releaseProxy]();
135
+ currentStop?.(error);
136
+ }
137
+ function runCall(signal, call) {
138
+ return new Promise((resolve, reject) => {
139
+ let settled = false;
140
+ const finish = (error, value) => {
141
+ if (settled)
142
+ return;
143
+ settled = true;
144
+ signal?.removeEventListener("abort", onAbort);
145
+ if (stopCurrent === stop)
146
+ stopCurrent = undefined;
147
+ if (error)
148
+ reject(error);
149
+ else
150
+ resolve(value);
151
+ };
152
+ const stop = (error) => {
153
+ finish(error);
154
+ terminate(error);
155
+ };
156
+ const onAbort = () => stop(new DOMException("The operation was aborted", "AbortError"));
157
+ stopCurrent = stop;
158
+ signal?.addEventListener("abort", onAbort, { once: true });
159
+ if (signal?.aborted) {
160
+ onAbort();
161
+ return;
162
+ }
163
+ try {
164
+ call().then((value) => finish(undefined, value), (error) => stop(error instanceof Error ? error : new Error(String(error))));
165
+ }
166
+ catch (error) {
167
+ stop(error instanceof Error ? error : new Error(String(error)));
168
+ }
169
+ });
170
+ }
171
+ async function waitUntilReady(signal) {
172
+ if (!signal)
173
+ return start();
174
+ if (signal.aborted)
175
+ throw new DOMException("The operation was aborted", "AbortError");
176
+ let onAbort;
177
+ try {
178
+ await Promise.race([
179
+ start(),
180
+ new Promise((_, reject) => {
181
+ onAbort = () => {
182
+ stopInitialization?.(new DOMException("The operation was aborted", "AbortError"));
183
+ reject(new DOMException("The operation was aborted", "AbortError"));
184
+ };
185
+ signal.addEventListener("abort", onAbort, { once: true });
186
+ }),
187
+ ]);
188
+ }
189
+ finally {
190
+ if (onAbort)
191
+ signal.removeEventListener("abort", onAbort);
192
+ }
193
+ }
194
+ function dispose(error) {
195
+ disposed = true;
196
+ stopCurrent?.(error);
197
+ stopInitialization?.(error);
198
+ terminate(error);
199
+ }
200
+ return {
201
+ get api() {
202
+ return workerApi;
203
+ },
204
+ get generation() {
205
+ return workerGeneration;
206
+ },
207
+ start,
208
+ waitUntilReady,
209
+ runCall,
210
+ stopCurrent(error) {
211
+ stopCurrent?.(error);
212
+ },
213
+ stopInitialization(error) {
214
+ stopInitialization?.(error);
215
+ },
216
+ terminate,
217
+ dispose,
218
+ };
219
+ }
package/dist/runtime.js CHANGED
@@ -1,6 +1,8 @@
1
- import PQueue from "p-queue";
2
- import * as Comlink from "comlink";
3
- import { createProjectSnapshot, computeProjectDelta, isValidProjectPath, operationPriorities, latestOnlyOperations, requestPriorities, maxSourceBytes, } from "./project.js";
1
+ import { createRuntimeScheduler } from "./runtime-scheduler.js";
2
+ import { createWorkerSupervisor } from "./runtime-worker.js";
3
+ import { createProjectSynchronizer } from "./runtime-project-sync.js";
4
+ import { createWasmRequest, decodeWasmResponse } from "./runtime-protocol.js";
5
+ import { createProjectSnapshot, isValidProjectPath, maxSourceBytes, } from "./project.js";
4
6
  const maxParameterBytes = 1_048_576;
5
7
  const maxParameterDepth = 64;
6
8
  function isJSONValue(value, ancestors = new Set(), depth = 0) {
@@ -62,8 +64,6 @@ export class MclRuntimeError extends Error {
62
64
  // ---------------------------------------------------------------------------
63
65
  const defaultInitializationTimeoutMs = 30_000;
64
66
  const defaultOperationTimeoutMs = 10_000;
65
- const wasmURL = new URL("../dist/mcl.wasm", import.meta.url).href;
66
- const wasmExecURL = new URL("../dist/wasm_exec.js", import.meta.url).href;
67
67
  // ---------------------------------------------------------------------------
68
68
  // Runtime factory
69
69
  // ---------------------------------------------------------------------------
@@ -71,23 +71,11 @@ export function createMclRuntime(options = {}) {
71
71
  const workerFactory = options.workerFactory ??
72
72
  (() => new Worker(new URL("./worker.js", import.meta.url), { type: "module" }));
73
73
  const initializationTimeoutMs = options.initializationTimeoutMs ?? defaultInitializationTimeoutMs;
74
- let rawWorker;
75
- let workerApi;
76
- let cleanupWorkerListeners;
77
- let initializationPromise;
78
74
  let disposed = false;
79
- const queue = new PQueue({ concurrency: 1 });
80
- queue.on("error", () => { });
81
- const queueSignals = new Set();
82
- const latestPending = new Map();
75
+ const scheduler = createRuntimeScheduler();
83
76
  let sequence = 0;
84
77
  let workerGeneration = 0;
85
- // The snapshot currently synced inside the Worker session.
86
- let workerProjectId;
87
- let workerSnapshot;
88
- // Callbacks for aborting the currently-executing step.
89
- let stopCurrent;
90
- let stopInitialization;
78
+ let resetProjectSync = () => { };
91
79
  // -------------------------------------------------------------------------
92
80
  // Observability
93
81
  // -------------------------------------------------------------------------
@@ -99,6 +87,20 @@ export function createMclRuntime(options = {}) {
99
87
  // Observability callbacks must not affect runtime behavior.
100
88
  }
101
89
  }
90
+ const worker = createWorkerSupervisor(workerFactory, initializationTimeoutMs, () => new MclRuntimeError({
91
+ code: "MCL-WASM-TIMEOUT",
92
+ message: "MCL WebAssembly initialization timed out",
93
+ }), {
94
+ emitStatus,
95
+ onGeneration(generation) {
96
+ workerGeneration = generation;
97
+ },
98
+ onReset() {
99
+ resetProjectSync();
100
+ },
101
+ });
102
+ const projectSynchronizer = createProjectSynchronizer(() => worker.api, (signal, call) => worker.runCall(signal, call), (error) => new MclRuntimeError(error));
103
+ resetProjectSync = projectSynchronizer.reset;
102
104
  function emitOperation(operation, startedAt, outcome, details = {}) {
103
105
  try {
104
106
  const durationMs = Math.max(0, performance.now() - startedAt);
@@ -123,313 +125,6 @@ export function createMclRuntime(options = {}) {
123
125
  }
124
126
  }
125
127
  // -------------------------------------------------------------------------
126
- // Queue management
127
- // -------------------------------------------------------------------------
128
- function abortError() {
129
- return new DOMException("The operation was aborted", "AbortError");
130
- }
131
- function enqueue(operation, run, signal, scope, requestedPriority, timing = {}) {
132
- if (signal?.aborted)
133
- return Promise.reject(signal.reason ?? abortError());
134
- const priority = requestPriorities[requestedPriority ?? ""] ??
135
- operationPriorities[operation] ??
136
- 0;
137
- const key = (name) => JSON.stringify([scope, name]);
138
- const pendingKey = key(operation);
139
- const pendingGroup = () => {
140
- let group = latestPending.get(pendingKey);
141
- if (!group) {
142
- group = new Map();
143
- latestPending.set(pendingKey, group);
144
- }
145
- return group;
146
- };
147
- const removePending = (pendingPriority, pending) => {
148
- const group = latestPending.get(pendingKey);
149
- if (group?.get(pendingPriority) !== pending)
150
- return;
151
- group.delete(pendingPriority);
152
- if (group.size === 0)
153
- latestPending.delete(pendingKey);
154
- };
155
- const supersedePending = (name, maximumPriority, message) => {
156
- const groupKey = key(name);
157
- const group = latestPending.get(groupKey);
158
- if (!group)
159
- return;
160
- for (const [pendingPriority, pending] of group) {
161
- if (pendingPriority > maximumPriority)
162
- continue;
163
- group.delete(pendingPriority);
164
- pending.controller.abort(new DOMException(message, "AbortError"));
165
- }
166
- if (group.size === 0)
167
- latestPending.delete(groupKey);
168
- };
169
- if (["render", "evaluate", "check"].includes(operation)) {
170
- supersedePending("lint", priority, "An explicit run replaced this pending lint");
171
- }
172
- else if (priority > requestPriorities.background && operation !== "lint") {
173
- supersedePending("lint", requestPriorities.background, "An interactive operation replaced this pending background lint");
174
- }
175
- const queueController = new AbortController();
176
- const pending = { controller: queueController, started: false };
177
- if (latestOnlyOperations.has(operation)) {
178
- supersedePending(operation, priority, "A newer operation replaced this request");
179
- pendingGroup().set(priority, pending);
180
- }
181
- queueSignals.add(queueController);
182
- const abortWhileQueued = () => {
183
- if (!pending.started)
184
- queueController.abort(signal?.reason ?? abortError());
185
- };
186
- signal?.addEventListener("abort", abortWhileQueued, { once: true });
187
- return queue
188
- .add(async () => {
189
- pending.started = true;
190
- if (latestOnlyOperations.has(operation))
191
- removePending(priority, pending);
192
- timing.executionStartedAt = performance.now();
193
- try {
194
- return (await run());
195
- }
196
- finally {
197
- timing.executionDurationMs = Math.max(0, performance.now() - timing.executionStartedAt);
198
- }
199
- }, { priority, signal: queueController.signal })
200
- .finally(() => {
201
- signal?.removeEventListener("abort", abortWhileQueued);
202
- queueSignals.delete(queueController);
203
- if (latestOnlyOperations.has(operation))
204
- removePending(priority, pending);
205
- });
206
- }
207
- // -------------------------------------------------------------------------
208
- // Worker lifecycle
209
- // -------------------------------------------------------------------------
210
- function startWorker() {
211
- if (disposed)
212
- return Promise.reject(new Error("MCL runtime has been disposed"));
213
- if (initializationPromise)
214
- return initializationPromise;
215
- const initializationStartedAt = performance.now();
216
- const currentRawWorker = workerFactory();
217
- rawWorker = currentRawWorker;
218
- const currentApi = Comlink.wrap(currentRawWorker);
219
- workerApi = currentApi;
220
- workerGeneration++;
221
- workerProjectId = undefined;
222
- workerSnapshot = undefined;
223
- let lastStatus;
224
- const reportStatus = (status) => {
225
- if (lastStatus === status)
226
- return;
227
- lastStatus = status;
228
- if (status === "ready" || status === "error") {
229
- emitStatus(status, {
230
- initializationDurationMs: Math.max(0, performance.now() - initializationStartedAt),
231
- });
232
- }
233
- else {
234
- emitStatus(status);
235
- }
236
- };
237
- let resolveReady;
238
- let rejectReady;
239
- const initialization = new Promise((resolve, reject) => {
240
- resolveReady = resolve;
241
- rejectReady = reject;
242
- });
243
- initializationPromise = initialization;
244
- // Status messages from the worker arrive via standard message events.
245
- // (Comlink forwards non-Comlink messages transparently.)
246
- const onStatusMessage = (event) => {
247
- if (rawWorker !== currentRawWorker)
248
- return;
249
- const data = event.data;
250
- if (data?.type === "status" && typeof data.status === "string") {
251
- reportStatus(data.status);
252
- }
253
- else if (data?.type === "fatal") {
254
- const error = new Error(typeof data.message === "string" ? data.message : "MCL WebAssembly exited unexpectedly");
255
- if (initialized) {
256
- terminateWorker(error);
257
- }
258
- else
259
- fail(error);
260
- }
261
- };
262
- currentRawWorker.addEventListener("message", onStatusMessage);
263
- // Worker-level error (uncaught exception or load failure).
264
- const onWorkerError = (event) => {
265
- if (rawWorker !== currentRawWorker)
266
- return;
267
- const error = new Error(event.message || "MCL worker failed");
268
- if (initialized) {
269
- terminateWorker(error);
270
- }
271
- else
272
- fail(error);
273
- };
274
- currentRawWorker.addEventListener("error", onWorkerError);
275
- // Malformed message from worker.
276
- const onMessageError = (event) => {
277
- if (rawWorker !== currentRawWorker)
278
- return;
279
- const error = new Error("MCL worker sent a malformed message");
280
- if (initialized) {
281
- terminateWorker(error);
282
- }
283
- else
284
- fail(error);
285
- };
286
- currentRawWorker.addEventListener("messageerror", onMessageError);
287
- cleanupWorkerListeners = () => {
288
- currentRawWorker.removeEventListener("message", onStatusMessage);
289
- currentRawWorker.removeEventListener("error", onWorkerError);
290
- currentRawWorker.removeEventListener("messageerror", onMessageError);
291
- };
292
- let initialized = false;
293
- const timer = setTimeout(() => fail(new MclRuntimeError({
294
- code: "MCL-WASM-TIMEOUT",
295
- message: "MCL WebAssembly initialization timed out",
296
- })), initializationTimeoutMs);
297
- function fail(error) {
298
- if (rawWorker !== currentRawWorker)
299
- return;
300
- clearTimeout(timer);
301
- if (stopInitialization === fail)
302
- stopInitialization = undefined;
303
- terminateWorker(error);
304
- rejectReady(error);
305
- }
306
- stopInitialization = fail;
307
- // Kick off WASM initialization via Comlink.
308
- currentApi
309
- .initialize({ wasmURL, wasmExecURL })
310
- .then(() => {
311
- if (rawWorker !== currentRawWorker)
312
- return;
313
- initialized = true;
314
- reportStatus("ready");
315
- clearTimeout(timer);
316
- if (stopInitialization === fail)
317
- stopInitialization = undefined;
318
- resolveReady();
319
- })
320
- .catch((error) => {
321
- fail(error instanceof Error ? error : new Error(String(error)));
322
- });
323
- return initialization;
324
- }
325
- function terminateWorker(error) {
326
- const currentWorker = rawWorker;
327
- if (!currentWorker)
328
- return;
329
- const currentApi = workerApi;
330
- const currentStop = stopCurrent;
331
- const cleanup = cleanupWorkerListeners;
332
- cleanupWorkerListeners = undefined;
333
- rawWorker = undefined;
334
- workerApi = undefined;
335
- initializationPromise = undefined;
336
- workerProjectId = undefined;
337
- workerSnapshot = undefined;
338
- stopCurrent = undefined;
339
- if (!disposed && error.name !== "AbortError")
340
- emitStatus("error");
341
- cleanup?.();
342
- currentWorker?.terminate();
343
- currentApi?.[Comlink.releaseProxy]();
344
- currentStop?.(error);
345
- }
346
- function runWorkerCall(signal, call) {
347
- return new Promise((resolve, reject) => {
348
- let settled = false;
349
- const finish = (error, value) => {
350
- if (settled)
351
- return;
352
- settled = true;
353
- signal?.removeEventListener("abort", onAbort);
354
- if (stopCurrent === stop)
355
- stopCurrent = undefined;
356
- if (error)
357
- reject(error);
358
- else
359
- resolve(value);
360
- };
361
- const stop = (error) => {
362
- finish(error);
363
- terminateWorker(error);
364
- };
365
- const onAbort = () => stop(new DOMException("The operation was aborted", "AbortError"));
366
- stopCurrent = stop;
367
- signal?.addEventListener("abort", onAbort, { once: true });
368
- if (signal?.aborted) {
369
- onAbort();
370
- return;
371
- }
372
- try {
373
- call().then((value) => finish(undefined, value), (error) => {
374
- stop(error instanceof Error ? error : new Error(String(error)));
375
- });
376
- }
377
- catch (error) {
378
- stop(error instanceof Error ? error : new Error(String(error)));
379
- }
380
- });
381
- }
382
- async function waitUntilReady(signal) {
383
- if (!signal)
384
- return startWorker();
385
- if (signal.aborted)
386
- throw new DOMException("The operation was aborted", "AbortError");
387
- let onAbort;
388
- try {
389
- await Promise.race([
390
- startWorker(),
391
- new Promise((_, reject) => {
392
- onAbort = () => {
393
- stopInitialization?.(new DOMException("The operation was aborted", "AbortError"));
394
- reject(new DOMException("The operation was aborted", "AbortError"));
395
- };
396
- signal.addEventListener("abort", onAbort, { once: true });
397
- }),
398
- ]);
399
- }
400
- finally {
401
- if (onAbort)
402
- signal.removeEventListener("abort", onAbort);
403
- }
404
- }
405
- // -------------------------------------------------------------------------
406
- // Project sync
407
- // -------------------------------------------------------------------------
408
- async function syncProjectToWorker(projectId, snapshot, requestOptions) {
409
- if (workerProjectId === projectId && workerSnapshot === snapshot)
410
- return;
411
- const api = workerApi;
412
- const previousSnapshot = workerProjectId === projectId ? workerSnapshot : undefined;
413
- const reset = workerProjectId !== projectId;
414
- const result = computeProjectDelta(snapshot, previousSnapshot, reset);
415
- if (result === null) {
416
- workerSnapshot = snapshot;
417
- return;
418
- }
419
- const { delta, binaryFiles, transferables } = result;
420
- const updateJSON = JSON.stringify(delta);
421
- // Transfer binary buffers to avoid copying.
422
- const transferableBinaries = Object.create(null);
423
- for (const [path, bytes] of Object.entries(binaryFiles)) {
424
- transferableBinaries[path] = bytes;
425
- }
426
- const response = await runWorkerCall(requestOptions.signal, () => api.updateProject(projectId, updateJSON, Comlink.transfer(transferableBinaries, transferables)));
427
- if (!response.ok)
428
- throw new MclRuntimeError(response.error ?? { code: "MCL-WASM-PROJECT", message: "Project update failed" });
429
- workerProjectId = projectId;
430
- workerSnapshot = snapshot;
431
- }
432
- // -------------------------------------------------------------------------
433
128
  // Core execute function
434
129
  // -------------------------------------------------------------------------
435
130
  async function execute(operation, source, requestOptions, entrypoint, project) {
@@ -481,48 +176,29 @@ export function createMclRuntime(options = {}) {
481
176
  try {
482
177
  if (timeoutMs <= 0)
483
178
  throw timeoutError;
484
- await waitUntilReady(signal);
179
+ await worker.waitUntilReady(signal);
485
180
  if (signal?.aborted)
486
181
  throw new DOMException("The operation was aborted", "AbortError");
487
- timer = setTimeout(() => stopCurrent?.(timeoutError), timeoutMs);
488
- const currentApi = workerApi;
489
- const currentGeneration = workerGeneration;
182
+ timer = setTimeout(() => worker.stopCurrent(timeoutError), timeoutMs);
183
+ const currentApi = worker.api;
184
+ const currentGeneration = worker.generation;
490
185
  operationWorkerGeneration = currentGeneration;
491
186
  if (project) {
492
- await syncProjectToWorker(project.id, project.snapshot, requestOptions);
187
+ await projectSynchronizer.sync(project.id, project.snapshot, requestOptions);
493
188
  }
494
189
  // Build the WASM request.
495
190
  const requestId = ++sequence;
496
- const request = {
497
- requestId,
498
- revision: requestId,
499
- operation,
500
- entrypoint,
501
- source,
502
- ...(requestOptions.parameters !== undefined
503
- ? { parameters: { ...requestOptions.parameters } }
504
- : {}),
505
- ...(requestOptions.position ? { position: requestOptions.position } : {}),
506
- ...(requestOptions.newName ? { newName: requestOptions.newName } : {}),
507
- ...(requestOptions.oldPath ? { oldPath: requestOptions.oldPath } : {}),
508
- ...(requestOptions.newPath ? { newPath: requestOptions.newPath } : {}),
509
- };
191
+ const request = createWasmRequest(requestId, operation, entrypoint, source, requestOptions);
510
192
  timing.wasmStartedAt = performance.now();
511
193
  let response;
512
194
  try {
513
- response = await runWorkerCall(signal, () => currentApi.run(JSON.stringify(request), project.id));
195
+ response = await worker.runCall(signal, () => currentApi.run(JSON.stringify(request), project.id));
514
196
  }
515
197
  finally {
516
198
  timing.wasmDurationMs = Math.max(0, performance.now() - timing.wasmStartedAt);
517
199
  clearTimeout(timer);
518
200
  }
519
- if (!response.ok) {
520
- throw new MclRuntimeError(response.error ?? { code: "MCL-WASM-RESPONSE", message: "Operation failed" });
521
- }
522
- if (operation === "lint") {
523
- return { operation, diagnostics: (response.result ?? []) };
524
- }
525
- return { operation, ...response.result };
201
+ return decodeWasmResponse(operation, response, (error) => new MclRuntimeError(error));
526
202
  }
527
203
  catch (error) {
528
204
  clearTimeout(timer);
@@ -530,7 +206,7 @@ export function createMclRuntime(options = {}) {
530
206
  }
531
207
  };
532
208
  try {
533
- const result = await enqueue(operation, run, signal, project.id, requestOptions.priority, timing);
209
+ const result = await scheduler.enqueue(operation, run, signal, project.id, requestOptions.priority, timing);
534
210
  emitOperation(operation, startedAt, "success", {
535
211
  ...timing,
536
212
  workerGeneration: operationWorkerGeneration,
@@ -602,14 +278,14 @@ export function createMclRuntime(options = {}) {
602
278
  try {
603
279
  if (timeoutMs <= 0)
604
280
  throw timeoutError;
605
- timer = setTimeout(() => stopInitialization?.(timeoutError), timeoutMs);
606
- await waitUntilReady(signal);
281
+ timer = setTimeout(() => worker.stopInitialization(timeoutError), timeoutMs);
282
+ await worker.waitUntilReady(signal);
607
283
  }
608
284
  finally {
609
285
  clearTimeout(timer);
610
286
  }
611
287
  };
612
- return enqueue("warmUp", run, signal, "runtime", requestOptions.priority);
288
+ return scheduler.enqueue("warmUp", run, signal, "runtime", requestOptions.priority);
613
289
  }
614
290
  // -------------------------------------------------------------------------
615
291
  // Public runtime object
@@ -626,11 +302,8 @@ export function createMclRuntime(options = {}) {
626
302
  return;
627
303
  disposed = true;
628
304
  const error = new Error("MCL runtime has been disposed");
629
- for (const controller of queueSignals)
630
- controller.abort(error);
631
- stopCurrent?.(error);
632
- stopInitialization?.(error);
633
- terminateWorker(error);
305
+ scheduler.abortAll(error);
306
+ worker.dispose(error);
634
307
  },
635
308
  };
636
309
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@manifest-configuration-language/browser",
3
- "version": "0.4.6",
3
+ "version": "0.4.8",
4
4
  "description": "Run MCL projects in a browser Web Worker using the Go WebAssembly runtime.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {