@manifest-configuration-language/browser 0.0.0-stage → 0.1.2

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 CHANGED
@@ -1,3 +1,33 @@
1
- # Temporary Holding Version
1
+ # @manifest-configuration-language/browser
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@manifest-configuration-language/browser` runs MCL parse, lint, format, check, evaluate, and render operations in a dedicated Web Worker. Its `prepack` step uses the shared WASM build script, which builds with the active Go toolchain, applies the mise-pinned Binaryen `wasm-opt -Oz`, selects the smaller binary, and copies the matching Go `wasm_exec.js` so both runtime assets ship together. GitHub Release assets use this same output. Update the Go and Binaryen pins in the repository's `mise.toml` when upgrading either tool.
4
+
5
+ ```js
6
+ import { createMclRuntime } from "@manifest-configuration-language/browser";
7
+
8
+ const runtime = createMclRuntime();
9
+ try {
10
+ const project = runtime.openProject({
11
+ "main.mcl": source,
12
+ "values.json": JSON.stringify(values),
13
+ });
14
+ const result = await project.render({ entrypoint: "main.mcl" });
15
+ console.log(result.yaml);
16
+ } finally {
17
+ runtime.dispose();
18
+ }
19
+ ```
20
+
21
+ Pass an `AbortSignal` through the final options argument to cancel an operation. The operation timeout covers both worker initialization and execution; `initializationTimeoutMs` is an additional upper bound for worker startup. Cancellation or a timeout terminates the current worker, and the runtime creates a fresh worker for the next operation. Operations are serialized because the current Go runtime uses one in-memory project root.
22
+
23
+ Project files can be UTF-8 strings or `Uint8Array` values. UTF-8 files remain inline in the JSON request. The Browser SDK copies each `Uint8Array` and transfers its buffer to the Worker; the Worker sends only `{ "encoding": "binary" }` metadata in the request JSON and passes a path-to-`Uint8Array` map as the second argument to `mclWasm.run(requestJSON, binaryFiles)`. The Go runtime copies those bytes into its project filesystem. The SDK-owned and caller-owned arrays remain reusable after each operation.
24
+
25
+ The package exports `maxSourceBytes`, `maxProjectFiles`, `maxProjectFileBytes`, and `maxProjectBytes` so browser interfaces can display the same limits enforced by the runtime.
26
+
27
+ MCL decodes the request into a root-relative `io/fs` filesystem for project files, module imports, schemas, resource catalogs, and dependency locks. The runtime limits are defined in the [protocol schema](https://github.com/manifest-configuration-language/mcl/blob/main/cmd/mcl-wasm/protocol.schema.json). The worker blocks `fetch` after loading the WASM runtime assets, so MCL project evaluation cannot make external network requests.
28
+
29
+ The wire format is described in [`protocol.schema.json`](https://github.com/manifest-configuration-language/mcl/blob/main/cmd/mcl-wasm/protocol.schema.json). Go protocol models are generated with `go generate ./cmd/mcl-wasm`, and the browser package declarations are generated with `npm run generate:protocol`. The browser API declarations reuse the generated operation, diagnostic, and result types. MCL decodes each request into a root-relative `io/fs` project filesystem. Kustomize project overlays and locked Git archives use kyaml's in-memory filesystem, and Helm source loading accepts an `io/fs` filesystem. The Go `wasm_exec.js` runtime supplies its standard browser fallbacks for process, path, and stdout APIs; the Browser SDK does not provide a Node-style project filesystem or require Node polyfills in Vite.
30
+
31
+ `MclRuntimeError` and lint diagnostics report project-relative paths with UTF-16 start and end positions. Evaluation errors also include related source locations when the Go engine provides them, such as the schema declaration associated with a resource validation error.
32
+
33
+ The [WebAssembly code size profile](https://github.com/manifest-configuration-language/mcl/blob/main/packages/browser/performance-profile.md) records package-level function body sizes and explains which WebAssembly sections it excludes.
package/dist/mcl.wasm ADDED
@@ -0,0 +1,4 @@
1
+ [diffend] Oversized file quarantined before diffing.
2
+ name: package/dist/mcl.wasm
3
+ size: 95920350 bytes
4
+ sha256: 3723f11f7acbd32086281639d28c5d0c25e7f1b9f0593b251876f2c60d1d5f2f
@@ -0,0 +1,575 @@
1
+ // Copyright 2018 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ "use strict";
6
+
7
+ (() => {
8
+ const enosys = () => {
9
+ const err = new Error("not implemented");
10
+ err.code = "ENOSYS";
11
+ return err;
12
+ };
13
+
14
+ if (!globalThis.fs) {
15
+ let outputBuf = "";
16
+ globalThis.fs = {
17
+ constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 }, // unused
18
+ writeSync(fd, buf) {
19
+ outputBuf += decoder.decode(buf);
20
+ const nl = outputBuf.lastIndexOf("\n");
21
+ if (nl != -1) {
22
+ console.log(outputBuf.substring(0, nl));
23
+ outputBuf = outputBuf.substring(nl + 1);
24
+ }
25
+ return buf.length;
26
+ },
27
+ write(fd, buf, offset, length, position, callback) {
28
+ if (offset !== 0 || length !== buf.length || position !== null) {
29
+ callback(enosys());
30
+ return;
31
+ }
32
+ const n = this.writeSync(fd, buf);
33
+ callback(null, n);
34
+ },
35
+ chmod(path, mode, callback) { callback(enosys()); },
36
+ chown(path, uid, gid, callback) { callback(enosys()); },
37
+ close(fd, callback) { callback(enosys()); },
38
+ fchmod(fd, mode, callback) { callback(enosys()); },
39
+ fchown(fd, uid, gid, callback) { callback(enosys()); },
40
+ fstat(fd, callback) { callback(enosys()); },
41
+ fsync(fd, callback) { callback(null); },
42
+ ftruncate(fd, length, callback) { callback(enosys()); },
43
+ lchown(path, uid, gid, callback) { callback(enosys()); },
44
+ link(path, link, callback) { callback(enosys()); },
45
+ lstat(path, callback) { callback(enosys()); },
46
+ mkdir(path, perm, callback) { callback(enosys()); },
47
+ open(path, flags, mode, callback) { callback(enosys()); },
48
+ read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
49
+ readdir(path, callback) { callback(enosys()); },
50
+ readlink(path, callback) { callback(enosys()); },
51
+ rename(from, to, callback) { callback(enosys()); },
52
+ rmdir(path, callback) { callback(enosys()); },
53
+ stat(path, callback) { callback(enosys()); },
54
+ symlink(path, link, callback) { callback(enosys()); },
55
+ truncate(path, length, callback) { callback(enosys()); },
56
+ unlink(path, callback) { callback(enosys()); },
57
+ utimes(path, atime, mtime, callback) { callback(enosys()); },
58
+ };
59
+ }
60
+
61
+ if (!globalThis.process) {
62
+ globalThis.process = {
63
+ getuid() { return -1; },
64
+ getgid() { return -1; },
65
+ geteuid() { return -1; },
66
+ getegid() { return -1; },
67
+ getgroups() { throw enosys(); },
68
+ pid: -1,
69
+ ppid: -1,
70
+ umask() { throw enosys(); },
71
+ cwd() { throw enosys(); },
72
+ chdir() { throw enosys(); },
73
+ }
74
+ }
75
+
76
+ if (!globalThis.path) {
77
+ globalThis.path = {
78
+ resolve(...pathSegments) {
79
+ return pathSegments.join("/");
80
+ }
81
+ }
82
+ }
83
+
84
+ if (!globalThis.crypto) {
85
+ throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
86
+ }
87
+
88
+ if (!globalThis.performance) {
89
+ throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
90
+ }
91
+
92
+ if (!globalThis.TextEncoder) {
93
+ throw new Error("globalThis.TextEncoder is not available, polyfill required");
94
+ }
95
+
96
+ if (!globalThis.TextDecoder) {
97
+ throw new Error("globalThis.TextDecoder is not available, polyfill required");
98
+ }
99
+
100
+ const encoder = new TextEncoder("utf-8");
101
+ const decoder = new TextDecoder("utf-8");
102
+
103
+ globalThis.Go = class {
104
+ constructor() {
105
+ this.argv = ["js"];
106
+ this.env = {};
107
+ this.exit = (code) => {
108
+ if (code !== 0) {
109
+ console.warn("exit code:", code);
110
+ }
111
+ };
112
+ this._exitPromise = new Promise((resolve) => {
113
+ this._resolveExitPromise = resolve;
114
+ });
115
+ this._pendingEvent = null;
116
+ this._scheduledTimeouts = new Map();
117
+ this._nextCallbackTimeoutID = 1;
118
+
119
+ const setInt64 = (addr, v) => {
120
+ this.mem.setUint32(addr + 0, v, true);
121
+ this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
122
+ }
123
+
124
+ const setInt32 = (addr, v) => {
125
+ this.mem.setUint32(addr + 0, v, true);
126
+ }
127
+
128
+ const getInt64 = (addr) => {
129
+ const low = this.mem.getUint32(addr + 0, true);
130
+ const high = this.mem.getInt32(addr + 4, true);
131
+ return low + high * 4294967296;
132
+ }
133
+
134
+ const loadValue = (addr) => {
135
+ const f = this.mem.getFloat64(addr, true);
136
+ if (f === 0) {
137
+ return undefined;
138
+ }
139
+ if (!isNaN(f)) {
140
+ return f;
141
+ }
142
+
143
+ const id = this.mem.getUint32(addr, true);
144
+ return this._values[id];
145
+ }
146
+
147
+ const storeValue = (addr, v) => {
148
+ const nanHead = 0x7FF80000;
149
+
150
+ if (typeof v === "number" && v !== 0) {
151
+ if (isNaN(v)) {
152
+ this.mem.setUint32(addr + 4, nanHead, true);
153
+ this.mem.setUint32(addr, 0, true);
154
+ return;
155
+ }
156
+ this.mem.setFloat64(addr, v, true);
157
+ return;
158
+ }
159
+
160
+ if (v === undefined) {
161
+ this.mem.setFloat64(addr, 0, true);
162
+ return;
163
+ }
164
+
165
+ let id = this._ids.get(v);
166
+ if (id === undefined) {
167
+ id = this._idPool.pop();
168
+ if (id === undefined) {
169
+ id = this._values.length;
170
+ }
171
+ this._values[id] = v;
172
+ this._goRefCounts[id] = 0;
173
+ this._ids.set(v, id);
174
+ }
175
+ this._goRefCounts[id]++;
176
+ let typeFlag = 0;
177
+ switch (typeof v) {
178
+ case "object":
179
+ if (v !== null) {
180
+ typeFlag = 1;
181
+ }
182
+ break;
183
+ case "string":
184
+ typeFlag = 2;
185
+ break;
186
+ case "symbol":
187
+ typeFlag = 3;
188
+ break;
189
+ case "function":
190
+ typeFlag = 4;
191
+ break;
192
+ }
193
+ this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
194
+ this.mem.setUint32(addr, id, true);
195
+ }
196
+
197
+ const loadSlice = (addr) => {
198
+ const array = getInt64(addr + 0);
199
+ const len = getInt64(addr + 8);
200
+ return new Uint8Array(this._inst.exports.mem.buffer, array, len);
201
+ }
202
+
203
+ const loadSliceOfValues = (addr) => {
204
+ const array = getInt64(addr + 0);
205
+ const len = getInt64(addr + 8);
206
+ const a = new Array(len);
207
+ for (let i = 0; i < len; i++) {
208
+ a[i] = loadValue(array + i * 8);
209
+ }
210
+ return a;
211
+ }
212
+
213
+ const loadString = (addr) => {
214
+ const saddr = getInt64(addr + 0);
215
+ const len = getInt64(addr + 8);
216
+ return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
217
+ }
218
+
219
+ const testCallExport = (a, b) => {
220
+ this._inst.exports.testExport0();
221
+ return this._inst.exports.testExport(a, b);
222
+ }
223
+
224
+ const timeOrigin = Date.now() - performance.now();
225
+ this.importObject = {
226
+ _gotest: {
227
+ add: (a, b) => a + b,
228
+ callExport: testCallExport,
229
+ },
230
+ gojs: {
231
+ // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
232
+ // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
233
+ // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
234
+ // This changes the SP, thus we have to update the SP used by the imported function.
235
+
236
+ // func wasmExit(code int32)
237
+ "runtime.wasmExit": (sp) => {
238
+ sp >>>= 0;
239
+ const code = this.mem.getInt32(sp + 8, true);
240
+ this.exited = true;
241
+ delete this._inst;
242
+ delete this._values;
243
+ delete this._goRefCounts;
244
+ delete this._ids;
245
+ delete this._idPool;
246
+ this.exit(code);
247
+ },
248
+
249
+ // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
250
+ "runtime.wasmWrite": (sp) => {
251
+ sp >>>= 0;
252
+ const fd = getInt64(sp + 8);
253
+ const p = getInt64(sp + 16);
254
+ const n = this.mem.getInt32(sp + 24, true);
255
+ fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
256
+ },
257
+
258
+ // func resetMemoryDataView()
259
+ "runtime.resetMemoryDataView": (sp) => {
260
+ sp >>>= 0;
261
+ this.mem = new DataView(this._inst.exports.mem.buffer);
262
+ },
263
+
264
+ // func nanotime1() int64
265
+ "runtime.nanotime1": (sp) => {
266
+ sp >>>= 0;
267
+ setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
268
+ },
269
+
270
+ // func walltime() (sec int64, nsec int32)
271
+ "runtime.walltime": (sp) => {
272
+ sp >>>= 0;
273
+ const msec = (new Date).getTime();
274
+ setInt64(sp + 8, msec / 1000);
275
+ this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
276
+ },
277
+
278
+ // func scheduleTimeoutEvent(delay int64) int32
279
+ "runtime.scheduleTimeoutEvent": (sp) => {
280
+ sp >>>= 0;
281
+ const id = this._nextCallbackTimeoutID;
282
+ this._nextCallbackTimeoutID++;
283
+ this._scheduledTimeouts.set(id, setTimeout(
284
+ () => {
285
+ this._resume();
286
+ while (this._scheduledTimeouts.has(id)) {
287
+ // for some reason Go failed to register the timeout event, log and try again
288
+ // (temporary workaround for https://github.com/golang/go/issues/28975)
289
+ console.warn("scheduleTimeoutEvent: missed timeout event");
290
+ this._resume();
291
+ }
292
+ },
293
+ getInt64(sp + 8),
294
+ ));
295
+ this.mem.setInt32(sp + 16, id, true);
296
+ },
297
+
298
+ // func clearTimeoutEvent(id int32)
299
+ "runtime.clearTimeoutEvent": (sp) => {
300
+ sp >>>= 0;
301
+ const id = this.mem.getInt32(sp + 8, true);
302
+ clearTimeout(this._scheduledTimeouts.get(id));
303
+ this._scheduledTimeouts.delete(id);
304
+ },
305
+
306
+ // func getRandomData(r []byte)
307
+ "runtime.getRandomData": (sp) => {
308
+ sp >>>= 0;
309
+ crypto.getRandomValues(loadSlice(sp + 8));
310
+ },
311
+
312
+ // func finalizeRef(v ref)
313
+ "syscall/js.finalizeRef": (sp) => {
314
+ sp >>>= 0;
315
+ const id = this.mem.getUint32(sp + 8, true);
316
+ this._goRefCounts[id]--;
317
+ if (this._goRefCounts[id] === 0) {
318
+ const v = this._values[id];
319
+ this._values[id] = null;
320
+ this._ids.delete(v);
321
+ this._idPool.push(id);
322
+ }
323
+ },
324
+
325
+ // func stringVal(value string) ref
326
+ "syscall/js.stringVal": (sp) => {
327
+ sp >>>= 0;
328
+ storeValue(sp + 24, loadString(sp + 8));
329
+ },
330
+
331
+ // func valueGet(v ref, p string) ref
332
+ "syscall/js.valueGet": (sp) => {
333
+ sp >>>= 0;
334
+ const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
335
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
336
+ storeValue(sp + 32, result);
337
+ },
338
+
339
+ // func valueSet(v ref, p string, x ref)
340
+ "syscall/js.valueSet": (sp) => {
341
+ sp >>>= 0;
342
+ Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
343
+ },
344
+
345
+ // func valueDelete(v ref, p string)
346
+ "syscall/js.valueDelete": (sp) => {
347
+ sp >>>= 0;
348
+ Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
349
+ },
350
+
351
+ // func valueIndex(v ref, i int) ref
352
+ "syscall/js.valueIndex": (sp) => {
353
+ sp >>>= 0;
354
+ storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
355
+ },
356
+
357
+ // valueSetIndex(v ref, i int, x ref)
358
+ "syscall/js.valueSetIndex": (sp) => {
359
+ sp >>>= 0;
360
+ Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
361
+ },
362
+
363
+ // func valueCall(v ref, m string, args []ref) (ref, bool)
364
+ "syscall/js.valueCall": (sp) => {
365
+ sp >>>= 0;
366
+ try {
367
+ const v = loadValue(sp + 8);
368
+ const m = Reflect.get(v, loadString(sp + 16));
369
+ const args = loadSliceOfValues(sp + 32);
370
+ const result = Reflect.apply(m, v, args);
371
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
372
+ storeValue(sp + 56, result);
373
+ this.mem.setUint8(sp + 64, 1);
374
+ } catch (err) {
375
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
376
+ storeValue(sp + 56, err);
377
+ this.mem.setUint8(sp + 64, 0);
378
+ }
379
+ },
380
+
381
+ // func valueInvoke(v ref, args []ref) (ref, bool)
382
+ "syscall/js.valueInvoke": (sp) => {
383
+ sp >>>= 0;
384
+ try {
385
+ const v = loadValue(sp + 8);
386
+ const args = loadSliceOfValues(sp + 16);
387
+ const result = Reflect.apply(v, undefined, args);
388
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
389
+ storeValue(sp + 40, result);
390
+ this.mem.setUint8(sp + 48, 1);
391
+ } catch (err) {
392
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
393
+ storeValue(sp + 40, err);
394
+ this.mem.setUint8(sp + 48, 0);
395
+ }
396
+ },
397
+
398
+ // func valueNew(v ref, args []ref) (ref, bool)
399
+ "syscall/js.valueNew": (sp) => {
400
+ sp >>>= 0;
401
+ try {
402
+ const v = loadValue(sp + 8);
403
+ const args = loadSliceOfValues(sp + 16);
404
+ const result = Reflect.construct(v, args);
405
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
406
+ storeValue(sp + 40, result);
407
+ this.mem.setUint8(sp + 48, 1);
408
+ } catch (err) {
409
+ sp = this._inst.exports.getsp() >>> 0; // see comment above
410
+ storeValue(sp + 40, err);
411
+ this.mem.setUint8(sp + 48, 0);
412
+ }
413
+ },
414
+
415
+ // func valueLength(v ref) int
416
+ "syscall/js.valueLength": (sp) => {
417
+ sp >>>= 0;
418
+ setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
419
+ },
420
+
421
+ // valuePrepareString(v ref) (ref, int)
422
+ "syscall/js.valuePrepareString": (sp) => {
423
+ sp >>>= 0;
424
+ const str = encoder.encode(String(loadValue(sp + 8)));
425
+ storeValue(sp + 16, str);
426
+ setInt64(sp + 24, str.length);
427
+ },
428
+
429
+ // valueLoadString(v ref, b []byte)
430
+ "syscall/js.valueLoadString": (sp) => {
431
+ sp >>>= 0;
432
+ const str = loadValue(sp + 8);
433
+ loadSlice(sp + 16).set(str);
434
+ },
435
+
436
+ // func valueInstanceOf(v ref, t ref) bool
437
+ "syscall/js.valueInstanceOf": (sp) => {
438
+ sp >>>= 0;
439
+ this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
440
+ },
441
+
442
+ // func copyBytesToGo(dst []byte, src ref) (int, bool)
443
+ "syscall/js.copyBytesToGo": (sp) => {
444
+ sp >>>= 0;
445
+ const dst = loadSlice(sp + 8);
446
+ const src = loadValue(sp + 32);
447
+ if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
448
+ this.mem.setUint8(sp + 48, 0);
449
+ return;
450
+ }
451
+ const toCopy = src.subarray(0, dst.length);
452
+ dst.set(toCopy);
453
+ setInt64(sp + 40, toCopy.length);
454
+ this.mem.setUint8(sp + 48, 1);
455
+ },
456
+
457
+ // func copyBytesToJS(dst ref, src []byte) (int, bool)
458
+ "syscall/js.copyBytesToJS": (sp) => {
459
+ sp >>>= 0;
460
+ const dst = loadValue(sp + 8);
461
+ const src = loadSlice(sp + 16);
462
+ if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
463
+ this.mem.setUint8(sp + 48, 0);
464
+ return;
465
+ }
466
+ const toCopy = src.subarray(0, dst.length);
467
+ dst.set(toCopy);
468
+ setInt64(sp + 40, toCopy.length);
469
+ this.mem.setUint8(sp + 48, 1);
470
+ },
471
+
472
+ "debug": (value) => {
473
+ console.log(value);
474
+ },
475
+ }
476
+ };
477
+ }
478
+
479
+ async run(instance) {
480
+ if (!(instance instanceof WebAssembly.Instance)) {
481
+ throw new Error("Go.run: WebAssembly.Instance expected");
482
+ }
483
+ this._inst = instance;
484
+ this.mem = new DataView(this._inst.exports.mem.buffer);
485
+ this._values = [ // JS values that Go currently has references to, indexed by reference id
486
+ NaN,
487
+ 0,
488
+ null,
489
+ true,
490
+ false,
491
+ globalThis,
492
+ this,
493
+ ];
494
+ this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
495
+ this._ids = new Map([ // mapping from JS values to reference ids
496
+ [0, 1],
497
+ [null, 2],
498
+ [true, 3],
499
+ [false, 4],
500
+ [globalThis, 5],
501
+ [this, 6],
502
+ ]);
503
+ this._idPool = []; // unused ids that have been garbage collected
504
+ this.exited = false; // whether the Go program has exited
505
+
506
+ // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
507
+ let offset = 4096;
508
+
509
+ const strPtr = (str) => {
510
+ const ptr = offset;
511
+ const bytes = encoder.encode(str + "\0");
512
+ new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
513
+ offset += bytes.length;
514
+ if (offset % 8 !== 0) {
515
+ offset += 8 - (offset % 8);
516
+ }
517
+ return ptr;
518
+ };
519
+
520
+ const argc = this.argv.length;
521
+
522
+ const argvPtrs = [];
523
+ this.argv.forEach((arg) => {
524
+ argvPtrs.push(strPtr(arg));
525
+ });
526
+ argvPtrs.push(0);
527
+
528
+ const keys = Object.keys(this.env).sort();
529
+ keys.forEach((key) => {
530
+ argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
531
+ });
532
+ argvPtrs.push(0);
533
+
534
+ const argv = offset;
535
+ argvPtrs.forEach((ptr) => {
536
+ this.mem.setUint32(offset, ptr, true);
537
+ this.mem.setUint32(offset + 4, 0, true);
538
+ offset += 8;
539
+ });
540
+
541
+ // The linker guarantees global data starts from at least wasmMinDataAddr.
542
+ // Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr.
543
+ const wasmMinDataAddr = 4096 + 8192;
544
+ if (offset >= wasmMinDataAddr) {
545
+ throw new Error("total length of command line and environment variables exceeds limit");
546
+ }
547
+
548
+ this._inst.exports.run(argc, argv);
549
+ if (this.exited) {
550
+ this._resolveExitPromise();
551
+ }
552
+ await this._exitPromise;
553
+ }
554
+
555
+ _resume() {
556
+ if (this.exited) {
557
+ throw new Error("Go program has already exited");
558
+ }
559
+ this._inst.exports.resume();
560
+ if (this.exited) {
561
+ this._resolveExitPromise();
562
+ }
563
+ }
564
+
565
+ _makeFuncWrapper(id) {
566
+ const go = this;
567
+ return function () {
568
+ const event = { id: id, this: this, args: arguments };
569
+ go._pendingEvent = event;
570
+ go._resume();
571
+ return event.result;
572
+ };
573
+ }
574
+ }
575
+ })();
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@manifest-configuration-language/browser",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "description": "Run MCL projects in a browser Web Worker using the Go WebAssembly runtime.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/manifest-configuration-language/mcl.git",
8
+ "directory": "packages/browser"
9
+ },
10
+ "type": "module",
11
+ "license": "Apache-2.0",
12
+ "files": [
13
+ "dist",
14
+ "src",
15
+ "README.md"
16
+ ],
17
+ "exports": {
18
+ ".": {
19
+ "types": "./src/index.d.ts",
20
+ "import": "./src/index.js"
21
+ }
22
+ },
23
+ "scripts": {
24
+ "build:wasm": "node ./scripts/build-wasm.mjs",
25
+ "generate:protocol": "node ./scripts/generate-protocol.mjs",
26
+ "test:unit": "node --test ./test/runtime-lifecycle.test.mjs",
27
+ "prepack": "npm run build:wasm"
28
+ },
29
+ "engines": {
30
+ "node": ">=20.19"
31
+ },
32
+ "devDependencies": {
33
+ "json-schema-to-typescript": "16.0.0"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ }
38
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,81 @@
1
+ import type {
2
+ CheckResult,
3
+ Error as ProtocolError,
4
+ EvaluateResult,
5
+ FormatResult,
6
+ LintDiagnostic as ProtocolLintDiagnostic,
7
+ ParseResult,
8
+ RelatedLocation as ProtocolRelatedLocation,
9
+ RenderResult,
10
+ Request as WasmRequest,
11
+ } from "./protocol.js";
12
+
13
+ export type MclOperation = WasmRequest["operation"];
14
+
15
+ export declare const maxSourceBytes: number;
16
+ export declare const maxProjectFiles: number;
17
+ export declare const maxProjectFileBytes: number;
18
+ export declare const maxProjectBytes: number;
19
+
20
+ /** Root-relative project files passed to MCL's per-request filesystem. Uint8Array values are copied before transfer so callers can reuse them. */
21
+ export type ProjectFile = string | Uint8Array;
22
+ export type ProjectFiles = Readonly<Record<string, ProjectFile>>;
23
+
24
+ export type MclError = ProtocolError;
25
+
26
+ export type LintDiagnostic = ProtocolLintDiagnostic;
27
+
28
+ export type MclResult =
29
+ | ({ operation: "parse" } & ParseResult)
30
+ | { operation: "lint"; diagnostics: ProtocolLintDiagnostic[] }
31
+ | ({ operation: "format" } & FormatResult)
32
+ | ({ operation: "check" } & CheckResult)
33
+ | ({ operation: "evaluate" } & EvaluateResult)
34
+ | ({ operation: "render" } & RenderResult);
35
+
36
+ export interface RuntimeOptions {
37
+ initializationTimeoutMs?: number;
38
+ operationTimeoutMs?: number;
39
+ workerFactory?: () => Worker;
40
+ }
41
+
42
+ export interface MclRuntime {
43
+ openProject(files: ProjectFiles): MclProject;
44
+ parse(source: string, options?: RequestOptions): Promise<MclResult & { operation: "parse" }>;
45
+ lint(source: string, options?: RequestOptions): Promise<MclResult & { operation: "lint" }>;
46
+ format(source: string, options?: RequestOptions): Promise<MclResult & { operation: "format" }>;
47
+ check(source: string, files?: ProjectFiles, options?: RequestOptions): Promise<MclResult & { operation: "check" }>;
48
+ evaluate(source: string, files?: ProjectFiles, options?: RequestOptions): Promise<MclResult & { operation: "evaluate" }>;
49
+ render(source: string, files?: ProjectFiles, options?: RequestOptions): Promise<MclResult & { operation: "render" }>;
50
+ dispose(): void;
51
+ }
52
+
53
+ export interface MclProject {
54
+ parse(options?: ProjectOperationOptions): Promise<MclResult & { operation: "parse" }>;
55
+ lint(options?: ProjectOperationOptions): Promise<MclResult & { operation: "lint" }>;
56
+ format(options?: ProjectOperationOptions): Promise<MclResult & { operation: "format" }>;
57
+ check(options?: ProjectOperationOptions): Promise<MclResult & { operation: "check" }>;
58
+ evaluate(options?: ProjectOperationOptions): Promise<MclResult & { operation: "evaluate" }>;
59
+ render(options?: ProjectOperationOptions): Promise<MclResult & { operation: "render" }>;
60
+ }
61
+
62
+ export interface RequestOptions {
63
+ signal?: AbortSignal;
64
+ timeoutMs?: number;
65
+ }
66
+
67
+ export interface ProjectOperationOptions extends RequestOptions {
68
+ entrypoint?: string;
69
+ }
70
+
71
+ export declare class MclRuntimeError extends Error {
72
+ readonly code: string;
73
+ readonly path?: string;
74
+ readonly line?: number;
75
+ readonly column?: number;
76
+ readonly endLine?: number;
77
+ readonly endColumn?: number;
78
+ readonly related?: ProtocolRelatedLocation[];
79
+ }
80
+
81
+ export declare function createMclRuntime(options?: RuntimeOptions): MclRuntime;
package/src/index.js ADDED
@@ -0,0 +1,281 @@
1
+ import { maxProjectBytes, maxProjectFileBytes, maxProjectFiles, maxSourceBytes } from "./limits.js";
2
+
3
+ export { maxProjectBytes, maxProjectFileBytes, maxProjectFiles, maxSourceBytes };
4
+
5
+ const defaultInitializationTimeoutMs = 30_000;
6
+ const defaultOperationTimeoutMs = 10_000;
7
+ const wasmURL = new URL("../dist/mcl.wasm", import.meta.url).href;
8
+ const wasmExecURL = new URL("../dist/wasm_exec.js", import.meta.url).href;
9
+
10
+ export class MclRuntimeError extends Error {
11
+ constructor(error) {
12
+ super(error.message);
13
+ this.name = "MclRuntimeError";
14
+ this.code = error.code;
15
+ this.path = error.path;
16
+ this.line = error.line;
17
+ this.column = error.column;
18
+ this.endLine = error.endLine;
19
+ this.endColumn = error.endColumn;
20
+ this.related = error.related;
21
+ }
22
+ }
23
+
24
+ export function createMclRuntime(options = {}) {
25
+ const workerFactory = options.workerFactory ?? (() => new Worker(new URL("./worker.js", import.meta.url), { type: "module" }));
26
+ const initializationTimeoutMs = options.initializationTimeoutMs ?? defaultInitializationTimeoutMs;
27
+ let worker;
28
+ let ready;
29
+ let disposed = false;
30
+ let queue = Promise.resolve();
31
+ let sequence = 0;
32
+ let workerGeneration = 0;
33
+ let stopCurrent;
34
+ let stopInitialization;
35
+
36
+ function startWorker() {
37
+ if (disposed) return Promise.reject(new Error("MCL runtime has been disposed"));
38
+ if (ready) return ready;
39
+ const currentWorker = workerFactory();
40
+ worker = currentWorker;
41
+ workerGeneration++;
42
+ let resolveReady;
43
+ let rejectReady;
44
+ const initialization = new Promise((resolve, reject) => {
45
+ resolveReady = resolve;
46
+ rejectReady = reject;
47
+ });
48
+ ready = initialization;
49
+ const timer = setTimeout(() => fail(new Error("MCL WebAssembly initialization timed out")), initializationTimeoutMs);
50
+ const onMessage = (event) => {
51
+ if (event.data?.type === "ready") {
52
+ clearTimeout(timer);
53
+ currentWorker.removeEventListener("message", onMessage);
54
+ currentWorker.removeEventListener("error", onError);
55
+ if (stopInitialization === fail) stopInitialization = undefined;
56
+ resolveReady();
57
+ } else if (event.data?.type === "fatal") {
58
+ fail(new Error(event.data.message || "MCL WebAssembly initialization failed"));
59
+ }
60
+ };
61
+ const onError = (event) => fail(new Error(event.message || "MCL worker failed"));
62
+ function fail(error) {
63
+ clearTimeout(timer);
64
+ currentWorker.removeEventListener("message", onMessage);
65
+ currentWorker.removeEventListener("error", onError);
66
+ currentWorker.terminate();
67
+ if (worker === currentWorker) {
68
+ worker = undefined;
69
+ ready = undefined;
70
+ }
71
+ if (stopInitialization === fail) stopInitialization = undefined;
72
+ rejectReady(error);
73
+ }
74
+ stopInitialization = fail;
75
+ try {
76
+ currentWorker.addEventListener("message", onMessage);
77
+ currentWorker.addEventListener("error", onError);
78
+ currentWorker.postMessage({ type: "configure", wasmURL, wasmExecURL });
79
+ } catch (error) {
80
+ fail(error);
81
+ }
82
+ return initialization;
83
+ }
84
+
85
+ async function waitUntilReady(signal) {
86
+ if (!signal) return startWorker();
87
+ if (signal.aborted) throw new DOMException("The operation was aborted", "AbortError");
88
+ let onAbort;
89
+ try {
90
+ await Promise.race([
91
+ startWorker(),
92
+ new Promise((_, reject) => {
93
+ onAbort = () => {
94
+ stopInitialization?.(new DOMException("The operation was aborted", "AbortError"));
95
+ };
96
+ signal.addEventListener("abort", onAbort, { once: true });
97
+ }),
98
+ ]);
99
+ } finally {
100
+ signal.removeEventListener("abort", onAbort);
101
+ }
102
+ }
103
+
104
+ async function execute(operation, source, files, requestOptions = {}, entrypoint = "main.mcl") {
105
+ const signal = requestOptions.signal;
106
+ if (signal?.aborted) throw new DOMException("The operation was aborted", "AbortError");
107
+ const run = async () => {
108
+ if (disposed) throw new Error("MCL runtime has been disposed");
109
+ if (requestOptions.signal?.aborted) throw new DOMException("The operation was aborted", "AbortError");
110
+ const timeoutMs = requestOptions.timeoutMs ?? options.operationTimeoutMs ?? defaultOperationTimeoutMs;
111
+ const timeoutError = new MclRuntimeError({ code: "MCL-WASM-TIMEOUT", message: "MCL operation timed out" });
112
+ let timer;
113
+ try {
114
+ if (timeoutMs <= 0) throw timeoutError;
115
+ timer = setTimeout(() => {
116
+ if (stopCurrent) stopCurrent(timeoutError);
117
+ else stopInitialization?.(timeoutError);
118
+ }, timeoutMs);
119
+ await waitUntilReady(requestOptions.signal);
120
+ if (requestOptions.signal?.aborted) throw new DOMException("The operation was aborted", "AbortError");
121
+ const preparedFiles = prepareFilesForTransfer(source, files, entrypoint);
122
+ const requestId = ++sequence;
123
+ const currentWorker = worker;
124
+ const currentGeneration = workerGeneration;
125
+ return await new Promise((resolve, reject) => {
126
+ let settled = false;
127
+ const cleanup = () => {
128
+ clearTimeout(timer);
129
+ currentWorker.removeEventListener("message", onMessage);
130
+ currentWorker.removeEventListener("error", onError);
131
+ requestOptions.signal?.removeEventListener("abort", onAbort);
132
+ };
133
+ const finish = (callback, value) => {
134
+ if (settled) return;
135
+ settled = true;
136
+ cleanup();
137
+ if (stopCurrent === stop) stopCurrent = undefined;
138
+ callback(value);
139
+ };
140
+ const onMessage = (event) => {
141
+ if (worker !== currentWorker || workerGeneration !== currentGeneration) return;
142
+ const response = event.data;
143
+ if (response?.type !== "response" || response.requestId !== requestId) return;
144
+ if (!response.value.ok) finish(reject, new MclRuntimeError(response.value.error));
145
+ else if (operation === "lint") finish(resolve, { operation, diagnostics: response.value.result });
146
+ else finish(resolve, { operation, ...response.value.result });
147
+ };
148
+ const onError = (event) => stop(new Error(event.message || "MCL worker failed"));
149
+ const onAbort = () => stop(new DOMException("The operation was aborted", "AbortError"));
150
+ const stop = (error) => {
151
+ finish(reject, error);
152
+ currentWorker.terminate();
153
+ if (worker === currentWorker) {
154
+ worker = undefined;
155
+ ready = undefined;
156
+ }
157
+ };
158
+ currentWorker.addEventListener("message", onMessage);
159
+ currentWorker.addEventListener("error", onError);
160
+ requestOptions.signal?.addEventListener("abort", onAbort, { once: true });
161
+ stopCurrent = stop;
162
+ try {
163
+ currentWorker.postMessage({ type: "run", requestId, operation, source, files: preparedFiles.files, entrypoint }, preparedFiles.transferables);
164
+ } catch (error) {
165
+ stop(error);
166
+ }
167
+ });
168
+ } catch (error) {
169
+ clearTimeout(timer);
170
+ throw error;
171
+ }
172
+ };
173
+ const result = queue.then(run, run);
174
+ queue = result.catch(() => {});
175
+ if (!signal) return result;
176
+
177
+ let onAbort;
178
+ const aborted = new Promise((_, reject) => {
179
+ onAbort = () => reject(new DOMException("The operation was aborted", "AbortError"));
180
+ signal.addEventListener("abort", onAbort, { once: true });
181
+ if (signal.aborted) onAbort();
182
+ });
183
+ return Promise.race([result, aborted]).finally(() => signal.removeEventListener("abort", onAbort));
184
+ }
185
+
186
+ function openProject(files) {
187
+ const entries = Object.entries(files ?? {});
188
+ if (entries.length === 0) throw new TypeError("Project must contain at least one MCL source file");
189
+ if (entries.length > maxProjectFiles) throw new RangeError(`Project has more than ${maxProjectFiles} files`);
190
+ let totalBytes = 0;
191
+ // Project paths are user controlled; a null prototype keeps names such as
192
+ // `__proto__` as ordinary file paths instead of mutating the file map.
193
+ const projectFiles = Object.create(null);
194
+ for (const [filePath, content] of entries) {
195
+ if (!isSafeRelativePath(filePath)) throw new TypeError(`Invalid project file path: ${filePath}`);
196
+ if (typeof content !== "string" && !(content instanceof Uint8Array)) throw new TypeError(`Project file ${filePath} must be a string or Uint8Array`);
197
+ const fileBytes = typeof content === "string" ? new TextEncoder().encode(content).byteLength : content.byteLength;
198
+ if (fileBytes > maxProjectFileBytes) throw new RangeError(`Project file ${filePath} exceeds the ${maxProjectFileBytes}-byte limit`);
199
+ totalBytes += fileBytes;
200
+ if (totalBytes > maxProjectBytes) throw new RangeError(`Project files exceed the ${maxProjectBytes}-byte limit`);
201
+ projectFiles[filePath] = typeof content === "string" ? content : new Uint8Array(content);
202
+ }
203
+
204
+ const sourcePaths = Object.keys(projectFiles).filter((filePath) => filePath.endsWith(".mcl")).sort();
205
+ const defaultEntrypoint = Object.hasOwn(projectFiles, "main.mcl") ? "main.mcl" : sourcePaths.length === 1 ? sourcePaths[0] : undefined;
206
+ const runProjectOperation = async (operation, requestOptions = {}) => {
207
+ const entrypoint = requestOptions.entrypoint ?? defaultEntrypoint;
208
+ if (!entrypoint) throw new TypeError("Set entrypoint when the project has multiple MCL source files");
209
+ if (!isSafeRelativePath(entrypoint) || !Object.hasOwn(projectFiles, entrypoint)) throw new TypeError(`Project entrypoint does not exist: ${entrypoint}`);
210
+ const entry = projectFiles[entrypoint];
211
+ const source = typeof entry === "string" ? entry : new TextDecoder("utf-8", { fatal: true }).decode(entry);
212
+ const sourceBytes = new TextEncoder().encode(source).byteLength;
213
+ if (sourceBytes > maxSourceBytes) throw new RangeError(`Source exceeds the ${maxSourceBytes}-byte limit`);
214
+ const projectBytes = Object.values(projectFiles).reduce((total, file) => total + (typeof file === "string" ? new TextEncoder().encode(file).byteLength : file.byteLength), 0);
215
+ if (projectBytes > maxProjectBytes) throw new RangeError(`Project files exceed the ${maxProjectBytes}-byte limit`);
216
+ const otherFiles = Object.fromEntries(Object.entries(projectFiles).filter(([filePath]) => filePath !== entrypoint));
217
+ return execute(operation, source, otherFiles, requestOptions, entrypoint);
218
+ };
219
+ return Object.freeze({
220
+ parse: (requestOptions) => runProjectOperation("parse", requestOptions),
221
+ lint: (requestOptions) => runProjectOperation("lint", requestOptions),
222
+ format: (requestOptions) => runProjectOperation("format", requestOptions),
223
+ check: (requestOptions) => runProjectOperation("check", requestOptions),
224
+ evaluate: (requestOptions) => runProjectOperation("evaluate", requestOptions),
225
+ render: (requestOptions) => runProjectOperation("render", requestOptions),
226
+ });
227
+ }
228
+
229
+ function isSafeRelativePath(filePath) {
230
+ return typeof filePath === "string" && filePath.length > 0 && !/^[a-z]:/i.test(filePath) && !filePath.startsWith("/") && !filePath.includes("\\") && filePath.split("/").every((part) => part && part !== "." && part !== "..");
231
+ }
232
+
233
+ function prepareFilesForTransfer(source, files, entrypoint) {
234
+ if (!isSafeRelativePath(entrypoint)) throw new TypeError(`Invalid project entrypoint: ${entrypoint}`);
235
+ const sourceBytes = new TextEncoder().encode(source).byteLength;
236
+ if (sourceBytes > maxSourceBytes) throw new RangeError(`Source exceeds the ${maxSourceBytes}-byte limit`);
237
+ const entries = Object.entries(files ?? {});
238
+ if (entries.length + 1 > maxProjectFiles) throw new RangeError(`Project has more than ${maxProjectFiles} files`);
239
+ let totalBytes = sourceBytes;
240
+ const transferredFiles = Object.create(null);
241
+ const transferables = [];
242
+ for (const [filePath, content] of entries) {
243
+ if (!isSafeRelativePath(filePath) || filePath === entrypoint) throw new TypeError(`Invalid project file path: ${filePath}`);
244
+ if (typeof content === "string") {
245
+ const fileBytes = new TextEncoder().encode(content).byteLength;
246
+ if (fileBytes > maxProjectFileBytes) throw new RangeError(`Project file ${filePath} exceeds the ${maxProjectFileBytes}-byte limit`);
247
+ totalBytes += fileBytes;
248
+ transferredFiles[filePath] = content;
249
+ } else if (content instanceof Uint8Array) {
250
+ if (content.byteLength > maxProjectFileBytes) throw new RangeError(`Project file ${filePath} exceeds the ${maxProjectFileBytes}-byte limit`);
251
+ totalBytes += content.byteLength;
252
+ const copy = new Uint8Array(content);
253
+ transferredFiles[filePath] = copy;
254
+ transferables.push(copy.buffer);
255
+ } else {
256
+ throw new TypeError(`Project file ${filePath} must be a string or Uint8Array`);
257
+ }
258
+ if (totalBytes > maxProjectBytes) throw new RangeError(`Project files exceed the ${maxProjectBytes}-byte limit`);
259
+ }
260
+ return { files: transferredFiles, transferables };
261
+ }
262
+
263
+ return {
264
+ openProject,
265
+ parse: (source, requestOptions) => execute("parse", source, undefined, requestOptions),
266
+ lint: (source, requestOptions) => execute("lint", source, undefined, requestOptions),
267
+ format: (source, requestOptions) => execute("format", source, undefined, requestOptions),
268
+ check: (source, files, requestOptions) => execute("check", source, files, requestOptions),
269
+ evaluate: (source, files, requestOptions) => execute("evaluate", source, files, requestOptions),
270
+ render: (source, files, requestOptions) => execute("render", source, files, requestOptions),
271
+ dispose() {
272
+ if (disposed) return;
273
+ disposed = true;
274
+ stopCurrent?.(new Error("MCL runtime has been disposed"));
275
+ stopInitialization?.(new Error("MCL runtime has been disposed"));
276
+ worker?.terminate();
277
+ worker = undefined;
278
+ ready = undefined;
279
+ },
280
+ };
281
+ }
package/src/limits.js ADDED
@@ -0,0 +1,7 @@
1
+ // Generated from cmd/mcl-wasm/protocol.schema.json. Do not edit.
2
+ export const maxSourceBytes = 65536;
3
+ export const maxProjectFiles = 4096;
4
+ export const maxProjectFileBytes = 16777216;
5
+ export const maxProjectBytes = 67108864;
6
+ export const maxOutputBytes = 1048576;
7
+ export const evaluationTimeoutMillis = 4000;
@@ -0,0 +1,84 @@
1
+ /* Generated from cmd/mcl-wasm/protocol.schema.json. Do not edit. */
2
+
3
+ export type MCLWebAssemblyRequestAndResponseProtocol = Request | Response;
4
+ /**
5
+ * Binary files omit content and are supplied in the optional second run argument under the same path.
6
+ */
7
+ export type FileInput = {
8
+ encoding: "utf8" | "binary";
9
+ content?: string;
10
+ };
11
+ export type LintResult = LintDiagnostic[];
12
+
13
+ export interface Request {
14
+ requestId?: number;
15
+ revision?: number;
16
+ operation: "parse" | "lint" | "format" | "check" | "evaluate" | "render";
17
+ /**
18
+ * Project-relative MCL source path. Defaults to main.mcl.
19
+ */
20
+ entrypoint?: string;
21
+ /**
22
+ * UTF-8 entrypoint source, limited by the runtime.
23
+ */
24
+ source: string;
25
+ /**
26
+ * Project files are limited by the runtime; this count excludes the entrypoint.
27
+ */
28
+ files?: {
29
+ [k: string]: FileInput;
30
+ };
31
+ }
32
+ export interface Response {
33
+ requestId: number;
34
+ revision?: number;
35
+ ok: boolean;
36
+ result?: ParseResult | LintResult | FormatResult | CheckResult | EvaluateResult | RenderResult;
37
+ error?: Error;
38
+ }
39
+ export interface ParseResult {
40
+ declarations: number;
41
+ }
42
+ export interface LintDiagnostic {
43
+ code: string;
44
+ message: string;
45
+ severity: string;
46
+ path: string;
47
+ line: number;
48
+ column: number;
49
+ endLine: number;
50
+ endColumn: number;
51
+ }
52
+ export interface FormatResult {
53
+ source: string;
54
+ }
55
+ export interface CheckResult {
56
+ valid: true;
57
+ artifacts: number;
58
+ }
59
+ export interface EvaluateResult {
60
+ artifacts: number;
61
+ renderedBytes: number;
62
+ }
63
+ export interface RenderResult {
64
+ yaml: string;
65
+ artifacts: number;
66
+ }
67
+ export interface Error {
68
+ code: string;
69
+ message: string;
70
+ path?: string;
71
+ line?: number;
72
+ column?: number;
73
+ endLine?: number;
74
+ endColumn?: number;
75
+ related?: RelatedLocation[];
76
+ }
77
+ export interface RelatedLocation {
78
+ path: string;
79
+ message: string;
80
+ line: number;
81
+ column: number;
82
+ endLine: number;
83
+ endColumn: number;
84
+ }
package/src/worker.js ADDED
@@ -0,0 +1,145 @@
1
+ let initialized;
2
+ let runtimeAssets;
3
+ let wasmMemory;
4
+ let networkAccessDenied = false;
5
+ const runtimeFetch = globalThis.fetch.bind(globalThis);
6
+ const networkAPINames = [
7
+ "Worker",
8
+ "SharedWorker",
9
+ "XMLHttpRequest",
10
+ "WebSocket",
11
+ "EventSource",
12
+ "WebTransport",
13
+ "WebSocketStream",
14
+ "RTCPeerConnection",
15
+ "importScripts",
16
+ ];
17
+ const originalFetch = globalThis.fetch;
18
+ const originalNetworkAPIs = new Map(
19
+ networkAPINames
20
+ .filter((name) => typeof globalThis[name] === "function")
21
+ .map((name) => [name, globalThis[name]]),
22
+ );
23
+
24
+ function denyNetworkAccess() {
25
+ globalThis.fetch = () => Promise.reject(new TypeError("Network access is disabled in the MCL runtime"));
26
+ for (const [name] of originalNetworkAPIs) {
27
+ Object.defineProperty(globalThis, name, {
28
+ configurable: true,
29
+ writable: true,
30
+ value: function MclNetworkAccessDenied() {
31
+ throw new TypeError("Network access is disabled in the MCL runtime");
32
+ },
33
+ });
34
+ }
35
+ networkAccessDenied = true;
36
+ }
37
+
38
+ async function probeNetworkAccess(url) {
39
+ let fetchBlocked = false;
40
+ try {
41
+ await globalThis.fetch(url);
42
+ } catch {
43
+ fetchBlocked = true;
44
+ }
45
+
46
+ const availableAPIs = ["fetch", ...originalNetworkAPIs.keys()];
47
+ const blockedAPIs = availableAPIs.filter(
48
+ (name) => name === "fetch" ? globalThis.fetch !== originalFetch : globalThis[name] !== originalNetworkAPIs.get(name),
49
+ );
50
+ return { fetchBlocked, availableAPIs, blockedAPIs };
51
+ }
52
+
53
+ async function initialize() {
54
+ if (initialized) return initialized;
55
+ initialized = (async () => {
56
+ if (!runtimeAssets?.wasmURL || !runtimeAssets?.wasmExecURL) throw new Error("MCL runtime assets were not configured");
57
+ await import(runtimeAssets.wasmExecURL);
58
+ const go = new Go();
59
+ const response = await runtimeFetch(runtimeAssets.wasmURL);
60
+ if (!response.ok) throw new Error(`Unable to load MCL WebAssembly: ${response.status}`);
61
+ const instantiateStartedAt = performance.now();
62
+ // Load the runtime before denying network APIs, then lock them before Go starts.
63
+ denyNetworkAccess();
64
+ let instance;
65
+ try {
66
+ ({ instance } = await WebAssembly.instantiateStreaming(response.clone(), go.importObject));
67
+ } catch {
68
+ ({ instance } = await WebAssembly.instantiate(await response.arrayBuffer(), go.importObject));
69
+ }
70
+ const wasmInstantiateMs = performance.now() - instantiateStartedAt;
71
+ wasmMemory = instance.exports.mem;
72
+ void go.run(instance);
73
+ while (!globalThis.mclWasmReady) await new Promise((resolve) => setTimeout(resolve, 0));
74
+ postMessage({
75
+ type: "ready",
76
+ wasmInstantiateMs,
77
+ wasmMemoryBytes: wasmMemory.buffer.byteLength,
78
+ });
79
+ })().catch((error) => {
80
+ postMessage({ type: "fatal", message: error instanceof Error ? error.message : String(error) });
81
+ throw error;
82
+ });
83
+ return initialized;
84
+ }
85
+
86
+ function encodeFiles(files) {
87
+ // Paths come from project input and may legally contain object property
88
+ // names such as `__proto__`; keep them as data when serializing the request.
89
+ const encoded = Object.create(null);
90
+ const binaryFiles = Object.create(null);
91
+ for (const [filePath, content] of Object.entries(files ?? {})) {
92
+ if (typeof content === "string") {
93
+ encoded[filePath] = { encoding: "utf8", content };
94
+ } else if (content instanceof Uint8Array) {
95
+ encoded[filePath] = { encoding: "binary" };
96
+ binaryFiles[filePath] = content;
97
+ } else {
98
+ throw new TypeError(`Project file ${filePath} must be a string or Uint8Array`);
99
+ }
100
+ }
101
+ return { files: encoded, binaryFiles };
102
+ }
103
+
104
+ self.addEventListener("message", async (event) => {
105
+ const message = event.data;
106
+ if (message?.type === "network-probe" && networkAccessDenied) {
107
+ const result = await probeNetworkAccess(message.url);
108
+ postMessage({ type: "network-probe-result", requestId: message.requestId, ...result });
109
+ return;
110
+ }
111
+ if (message?.type === "configure") {
112
+ runtimeAssets = message;
113
+ initialize().catch(() => {});
114
+ return;
115
+ }
116
+ if (message?.type !== "run") return;
117
+ try {
118
+ await initialize();
119
+ const encodedFiles = encodeFiles(message.files);
120
+ const request = {
121
+ requestId: message.requestId,
122
+ revision: message.requestId,
123
+ operation: message.operation,
124
+ entrypoint: message.entrypoint,
125
+ source: message.source,
126
+ files: encodedFiles.files,
127
+ };
128
+ const value = JSON.parse(globalThis.mclWasm.run(JSON.stringify(request), encodedFiles.binaryFiles));
129
+ postMessage({
130
+ type: "response",
131
+ requestId: message.requestId,
132
+ value,
133
+ wasmMemoryBytes: wasmMemory.buffer.byteLength,
134
+ });
135
+ } catch (error) {
136
+ postMessage({
137
+ type: "response",
138
+ requestId: message.requestId,
139
+ value: {
140
+ ok: false,
141
+ error: { code: "MCL-WASM-INPUT", message: error instanceof Error ? error.message : String(error) },
142
+ },
143
+ });
144
+ }
145
+ });