@kirana-style/compiler-browser 0.0.0 → 0.3.5

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/compiler.js ADDED
@@ -0,0 +1,1093 @@
1
+ import { c as WASI, d as createContext, f as __exportAll, i as instantiateNapiModule, l as asyncWork, n as memfs, s as createOnMessage, u as threadsafeFunction } from "./fs.js";
2
+ // ../../dist-packages/stage/compiler-browser/engine/kirana.wasi-browser.js
3
+ var kirana_wasi_browser_exports = /* @__PURE__ */ __exportAll({
4
+ Compiler: () => Compiler,
5
+ __fs: () => __fs,
6
+ __napiBindingTarget: () => __napiBindingTarget,
7
+ __volume: () => __volume,
8
+ default: () => kirana_wasi_browser_default,
9
+ runCli: () => runCli,
10
+ runLsp: () => runLsp,
11
+ scanComponent: () => scanComponent
12
+ });
13
+ const __napiBindingTarget = "wasm32-wasi";
14
+ function __napiStampBindingTarget(exportsObject, target) {
15
+ if (Object.prototype.hasOwnProperty.call(exportsObject, "__napiBindingTarget")) {
16
+ if (exportsObject.__napiBindingTarget === target) return target;
17
+ const error = /* @__PURE__ */ new Error("`__napiBindingTarget` is reserved by the generated binding loader, but the loaded binding already exports it. Rename the export, e.g. #[napi(js_name = \"...\")].");
18
+ error.code = "ERR_NAPI_BINDING_TARGET_CONFLICT";
19
+ throw error;
20
+ }
21
+ if (!Object.isExtensible(exportsObject)) return target;
22
+ try {
23
+ Object.defineProperty(exportsObject, "__napiBindingTarget", {
24
+ configurable: true,
25
+ enumerable: true,
26
+ value: target,
27
+ writable: true
28
+ });
29
+ } catch {}
30
+ return target;
31
+ }
32
+ const { fs: __fs, vol: __volume } = memfs();
33
+ const __wasi = new WASI({
34
+ version: "preview1",
35
+ fs: __fs,
36
+ preopens: { "/": "/" }
37
+ });
38
+ const __wasmUrl = new URL("./kirana.wasm32-wasi.wasm", import.meta.url).href;
39
+ const __wasmResponse = await globalThis.fetch(__wasmUrl);
40
+ if (!__wasmResponse.ok) throw new Error("Failed to fetch WASI module " + __wasmUrl + ": " + __wasmResponse.status + " " + (__wasmResponse.statusText || "Unknown Status"));
41
+ const __wasmFile = await __wasmResponse.arrayBuffer();
42
+ const __sharedMemory = new WebAssembly.Memory({
43
+ initial: 4e3,
44
+ maximum: 65536,
45
+ shared: true
46
+ });
47
+ const __asyncWorkPoolSize = 4;
48
+ const __workerPoolSize = Math.max(2, globalThis.navigator?.hardwareConcurrency ?? 4);
49
+ let __emnapiContext;
50
+ const __wasiDisposeSymbol = Symbol.for("napi.rs.wasi.dispose");
51
+ const __wasiWorkers = /* @__PURE__ */ new Set();
52
+ let __wasiThreadManager;
53
+ function __captureWasiThreadManager(context) {
54
+ if (context && context.PThread) __wasiThreadManager = context.PThread;
55
+ return {};
56
+ }
57
+ function __getWasiThreadManager() {
58
+ const manager = __wasiThreadManager !== void 0 ? __wasiThreadManager : __napiModule ? __napiModule.PThread : void 0;
59
+ if (manager && typeof manager.terminateWorker === "function") return manager;
60
+ }
61
+ let __napiInstance;
62
+ let __emnapiContextDestroyed = false;
63
+ let __emnapiContextDestroyPromise;
64
+ let __emnapiWasmEnvCleanupPrepared = false;
65
+ let __emnapiWasmEnvCleanupPreparing = false;
66
+ let __finishParkedWasmEnvCleanup;
67
+ let __emnapiWasmEnvCleanupYielding = false;
68
+ let __emnapiWasmEnvSettlementLossReported = false;
69
+ let __emnapiWasmEnvCleanupRan = false;
70
+ let __emnapiWasmEnvCleanupDrained = false;
71
+ let __emnapiWasmEnvCleanupDrainPromise;
72
+ let __wasiDisposed = false;
73
+ let __wasiAsyncWorkDrainPromise;
74
+ let __wasiDisposePromise;
75
+ let __completeWasiDisposal = function() {};
76
+ function __isThenable(value) {
77
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
78
+ }
79
+ function __createCleanupError(errors, message) {
80
+ if (errors.length === 1) return errors[0];
81
+ const __AggregateError = globalThis.AggregateError;
82
+ if (typeof __AggregateError === "function") return new __AggregateError(errors, message);
83
+ const error = new Error(message);
84
+ error.errors = errors;
85
+ return error;
86
+ }
87
+ function __attachCleanupErrors(error, cleanupErrors) {
88
+ if (cleanupErrors.length === 0) return error;
89
+ const cleanupError = __createCleanupError(cleanupErrors, "WASI binding cleanup failed");
90
+ try {
91
+ if (error && (typeof error === "object" || typeof error === "function")) {
92
+ if (error.cause === void 0) {
93
+ error.cause = cleanupError;
94
+ if (error.cause === cleanupError) return error;
95
+ }
96
+ if (Array.isArray(error.cleanupErrors)) {
97
+ error.cleanupErrors.push(cleanupError);
98
+ return error;
99
+ } else {
100
+ const attachedCleanupErrors = [cleanupError];
101
+ error.cleanupErrors = attachedCleanupErrors;
102
+ if (error.cleanupErrors === attachedCleanupErrors) return error;
103
+ }
104
+ }
105
+ } catch {}
106
+ const aggregate = __createCleanupError([error, cleanupError], "WASI binding initialization and cleanup failed");
107
+ try {
108
+ aggregate.cause = error;
109
+ } catch {}
110
+ return aggregate;
111
+ }
112
+ function __wrapEmnapiContextDestroyForSettlement(context, prepareEnvCleanup, isPreparingEnvCleanup) {
113
+ let destroy;
114
+ try {
115
+ destroy = context.destroy;
116
+ } catch {
117
+ return context;
118
+ }
119
+ if (typeof destroy !== "function") return context;
120
+ try {
121
+ Object.defineProperty(context, "destroy", {
122
+ configurable: true,
123
+ enumerable: false,
124
+ writable: true,
125
+ value: function() {
126
+ if (isPreparingEnvCleanup?.()) return;
127
+ prepareEnvCleanup?.();
128
+ return Reflect.apply(destroy, this, arguments);
129
+ }
130
+ });
131
+ } catch {}
132
+ return context;
133
+ }
134
+ function __isPreparingWasmEnvCleanup() {
135
+ return __emnapiWasmEnvCleanupPreparing;
136
+ }
137
+ function __prepareWasmEnvCleanup() {
138
+ if (__emnapiWasmEnvCleanupPrepared) return;
139
+ const finishParked = __finishParkedWasmEnvCleanup;
140
+ if (finishParked !== void 0) {
141
+ finishParked();
142
+ __reportUnreachedWasmEnvSettlements();
143
+ return;
144
+ }
145
+ if (__emnapiWasmEnvCleanupPreparing) return;
146
+ const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup;
147
+ if (typeof prepare === "function") {
148
+ __emnapiWasmEnvCleanupPreparing = true;
149
+ try {
150
+ prepare();
151
+ } finally {
152
+ __emnapiWasmEnvCleanupPreparing = false;
153
+ }
154
+ __emnapiWasmEnvCleanupRan = true;
155
+ __reportUnreachedWasmEnvSettlements();
156
+ }
157
+ __emnapiWasmEnvCleanupPrepared = true;
158
+ }
159
+ /**
160
+ * Say so when the barrier leaves settlements queued and nothing is left that
161
+ * could deliver them.
162
+ *
163
+ * Only the disposal chain yields the event-loop turns @emnapi/core needs to
164
+ * dispatch its queue. Every other caller of the barrier destroys in the same
165
+ * turn — a raw `Context.destroy()`, the 'exit' teardown — and
166
+ * `Context.destroy()` runs the threadsafe function's cleanup hook, which drains
167
+ * that queue with a null env and discards it. The promises those settlements
168
+ * were for then hang forever, silently.
169
+ *
170
+ * Loud, once, and never throwing: this runs from inside `Context.destroy()`,
171
+ * emnapi's own beforeExit destroy included, where throwing would take the whole
172
+ * teardown down with it. Destroying anyway is still the right trade — the queue
173
+ * is already unreachable by then.
174
+ */
175
+ function __reportUnreachedWasmEnvSettlements() {
176
+ if (__emnapiWasmEnvCleanupYielding || __emnapiWasmEnvSettlementLossReported) return;
177
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending;
178
+ if (typeof pending !== "function") return;
179
+ let queued;
180
+ try {
181
+ queued = pending();
182
+ } catch {
183
+ return;
184
+ }
185
+ if (!queued) return;
186
+ __emnapiWasmEnvSettlementLossReported = true;
187
+ try {
188
+ const consoleHost = globalThis.console;
189
+ if (consoleHost && typeof consoleHost.error === "function") consoleHost.error("napi-rs: the wasm environment is being destroyed with " + queued + " queued promise settlement(s). Context.destroy() discards them, so those promises never settle. Dispose with binding[Symbol.for('napi.rs.wasi.dispose')]() instead: only it yields the event-loop turns the settlements need.");
190
+ } catch {}
191
+ }
192
+ const __scheduleMacrotask = (function() {
193
+ if (typeof setImmediate === "function") return function(callback) {
194
+ setImmediate(callback);
195
+ };
196
+ const __MessageChannel = globalThis.MessageChannel;
197
+ if (typeof __MessageChannel === "function") return function(callback) {
198
+ const channel = new __MessageChannel();
199
+ channel.port1.onmessage = function() {
200
+ channel.port1.onmessage = null;
201
+ try {
202
+ channel.port1.close();
203
+ } catch {}
204
+ try {
205
+ channel.port2.close();
206
+ } catch {}
207
+ callback();
208
+ };
209
+ channel.port2.postMessage(null);
210
+ };
211
+ return function(callback) {
212
+ setTimeout(callback, 0);
213
+ };
214
+ })();
215
+ function __scheduleTimer(callback, delay) {
216
+ const setTimer = globalThis.setTimeout;
217
+ if (typeof setTimer !== "function") {
218
+ __scheduleMacrotask(callback);
219
+ return;
220
+ }
221
+ try {
222
+ setTimer(callback, delay);
223
+ } catch {
224
+ __scheduleMacrotask(callback);
225
+ }
226
+ }
227
+ const __WASM_RUNTIME_WORK_POLL_INTERVAL_MS = 1;
228
+ const __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS = 2;
229
+ const __WASM_RUNTIME_WORK_POLL_STALL_MS = 50;
230
+ const __WASM_RUNTIME_WORK_POLL_BACKUP_MS = 200;
231
+ /**
232
+ * Pacing state for one runtime-work poll.
233
+ *
234
+ * Per poll, never per module: whether the host's timers arrive is not a
235
+ * property of the module. A host can lose its timers between two disposals,
236
+ * and in the deferred shape every instance shares this module — one healthy
237
+ * instance must not disarm the fallback for the next one.
238
+ */
239
+ function __createWasmRuntimePollPace() {
240
+ return {
241
+ arrivals: 0,
242
+ settleTurn: void 0,
243
+ turnTimerDueAt: 0
244
+ };
245
+ }
246
+ /**
247
+ * The backup that ends a turn whose timer is never going to arrive.
248
+ *
249
+ * Once the poll paces on the timer alone it has nothing left to fall back on
250
+ * if the host's timers stop mid-poll: the turn that armed the dead timer is
251
+ * the turn that parks, and a parked poll schedules nothing that could notice.
252
+ * So every turn arms one of these before it yields, and each one compares due
253
+ * times instead of measuring how long the parked turn has been waiting.
254
+ *
255
+ * Invariant: a parked turn is ended by the newest backup that was armed while
256
+ * the host's timers still worked, and a backup ends a turn only when that
257
+ * turn's own timer was already due a whole window before the backup itself.
258
+ * Neither half turns on how far apart the arms happen to fall — what bounds
259
+ * the rescue is how far back that newest live backup is:
260
+ *
261
+ * - *Ends it.* Hosts run timers in due order, so a backup that runs while a
262
+ * turn due a whole window earlier is still parked proves that turn's timer
263
+ * was dropped rather than merely late. That same comparison is what leaves a
264
+ * healthy host alone: there the turn's timer has already run and cleared
265
+ * `settleTurn` before any backup due after it can look.
266
+ * - *Two turns back, not one.* A turn that ended does not prove its own timer
267
+ * arrived: until `…_TRUSTED_ARRIVALS` is reached every turn arms both
268
+ * primitives and the macrotask wins, so such a turn can end with its own
269
+ * timer — and the backup armed one line before it — already dead. The
270
+ * arrival that then flips the poll onto the timer alone can itself be a
271
+ * timer armed before the host's timers died. So the turn that parks can sit
272
+ * two turns past the last live arm, and the newest live backup is due
273
+ * `…_BACKUP_MS` less *two* turn lengths after that turn's own timer.
274
+ * Arming on every turn is what holds it to two, rather than however far back
275
+ * a throttle last let one through.
276
+ * - *Ceiling.* Coverage therefore holds while two consecutive poll turns fit
277
+ * inside `…_BACKUP_MS` less the slack and one interval: 149 ms, so 74 ms
278
+ * per turn (measured: a 74 ms turn is still rescued, a 75 ms one parks).
279
+ * Past that the turn stays parked and the disposal promise never settles.
280
+ * The bound is deliberate: reaching it takes a host that drops timers
281
+ * mid-poll *and* keeps every poll turn busy for more than 74 ms, and neither
282
+ * Node nor WebContainer — the hosts that run the threaded artifact — does
283
+ * the second.
284
+ *
285
+ * The poll then goes back to arming both primitives until two fresh arrivals
286
+ * prove the timers again. A host that stops running the timers it has
287
+ * *already* accepted leaves nothing to fire, and the disposal promise stays
288
+ * pending rather than wedging the thread — the same outcome as a blocking
289
+ * closure that never returns. Unreferenced wherever the host allows it: the
290
+ * poll's own turn timers are what keep the loop alive, never these.
291
+ */
292
+ function __armWasmRuntimePollStallBackup(pace) {
293
+ const setTimer = globalThis.setTimeout;
294
+ if (typeof setTimer !== "function") return;
295
+ const dueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_BACKUP_MS;
296
+ let handle;
297
+ try {
298
+ handle = setTimer(() => {
299
+ const settleTurn = pace.settleTurn;
300
+ if (!settleTurn || pace.turnTimerDueAt > dueAt - __WASM_RUNTIME_WORK_POLL_STALL_MS) return;
301
+ pace.arrivals = 0;
302
+ pace.settleTurn = void 0;
303
+ settleTurn();
304
+ }, __WASM_RUNTIME_WORK_POLL_BACKUP_MS);
305
+ } catch {
306
+ return;
307
+ }
308
+ if (handle && typeof handle.unref === "function") try {
309
+ handle.unref();
310
+ } catch {}
311
+ }
312
+ /**
313
+ * One turn of the runtime-work poll.
314
+ *
315
+ * `__scheduleTimer` falls back to the macrotask scheduler when `setTimeout` is
316
+ * missing or throws, but not when it is present, returns a handle and never
317
+ * fires — fake timers in a test suite that disposes from an `afterEach`, or a
318
+ * host whose timers belong to an IO context that is already gone. That host
319
+ * would park this poll forever, and the poll is unbounded, so nothing would
320
+ * ever call `…_finish`.
321
+ *
322
+ * Arm both primitives until timers armed by this poll have arrived twice, and
323
+ * let whichever lands first end the turn; the loser resolves nothing. A host
324
+ * with working timers therefore pays the double arming for the first turn or
325
+ * two — the macrotask wins the race, but the timers behind it still arrive and
326
+ * are counted — and paces on the timer alone from then on, instead of spinning
327
+ * the loop on a zero-delay queue. A host whose timers never arrive keeps both,
328
+ * and the macrotask is what keeps the poll moving. A host whose timers stop
329
+ * after proving themselves is caught by `__armWasmRuntimePollStallBackup`,
330
+ * which ends the parked turn and puts this poll back on both.
331
+ */
332
+ function __yieldWasmRuntimePollTurn(pace) {
333
+ __armWasmRuntimePollStallBackup(pace);
334
+ return new Promise((resolve) => {
335
+ let settled = false;
336
+ const settle = () => {
337
+ if (settled) return;
338
+ settled = true;
339
+ if (pace.settleTurn === settle) pace.settleTurn = void 0;
340
+ resolve();
341
+ };
342
+ __scheduleTimer(() => {
343
+ pace.arrivals++;
344
+ settle();
345
+ }, __WASM_RUNTIME_WORK_POLL_INTERVAL_MS);
346
+ const turnTimerDueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_INTERVAL_MS;
347
+ if (pace.arrivals < __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS) {
348
+ __scheduleMacrotask(settle);
349
+ return;
350
+ }
351
+ pace.settleTurn = settle;
352
+ pace.turnTimerDueAt = turnTimerDueAt;
353
+ });
354
+ }
355
+ /**
356
+ * The barrier for callers that can yield: `__prepareWasmEnvCleanup` with real
357
+ * event-loop turns in the middle.
358
+ *
359
+ * `napi_prepare_wasm_env_cleanup` waits — it returns only once the addon's
360
+ * async runtime has quiesced, and on `wasm32-wasip1-threads` the thread it
361
+ * waits on is this one, the only thread that can give a running blocking
362
+ * closure the JavaScript turn *it* is waiting for. A single call there can wait
363
+ * for work that can never finish. The addon's two-phase form splits that:
364
+ * `…_begin` stops the runtime without joining and reports whether anything is
365
+ * still live, `napi_wasm_runtime_work_pending` answers that question again
366
+ * without blocking, and `…_finish` joins. The turns yielded in between are the
367
+ * entire point.
368
+ *
369
+ * The poll has no deadline, for the same reason the async-work drain below has
370
+ * none: giving up means calling `…_finish`, which joins on this thread, and the
371
+ * work it would join is the work that is waiting for a turn from this thread —
372
+ * so a bound does not end the wait, it only moves it somewhere the JavaScript
373
+ * thread can no longer be reached. A blocking closure that never returns keeps
374
+ * the disposal promise pending instead, exactly as a task whose `execute` never
375
+ * returns already keeps an *undisposed* process alive. The host contract is in
376
+ * `crates/async-runtime/README.md`: a blocking closure must never wait on a
377
+ * JavaScript turn. The process-exit path still blocks in `…_finish`, because it
378
+ * has no turns left to give (see `__prepareWasmEnvCleanup`).
379
+ *
380
+ * Feature-detected like every other export in this teardown, so an addon built
381
+ * against a napi crate that predates the split keeps the single blocking call.
382
+ * Returns nothing whenever the handshake finished without yielding, which keeps
383
+ * an idle disposal synchronous.
384
+ */
385
+ function __prepareWasmEnvCleanupWithTurns() {
386
+ if (__emnapiWasmEnvCleanupPrepared || __emnapiWasmEnvCleanupPreparing) return;
387
+ const exports = __napiInstance?.exports;
388
+ const begin = exports?.napi_prepare_wasm_env_cleanup_begin;
389
+ const finish = exports?.napi_prepare_wasm_env_cleanup_finish;
390
+ if (typeof begin !== "function" || typeof finish !== "function") {
391
+ __emnapiWasmEnvCleanupYielding = true;
392
+ try {
393
+ __prepareWasmEnvCleanup();
394
+ } finally {
395
+ __emnapiWasmEnvCleanupYielding = false;
396
+ }
397
+ return;
398
+ }
399
+ const workPending = exports?.napi_wasm_runtime_work_pending;
400
+ __emnapiWasmEnvCleanupPreparing = true;
401
+ let live;
402
+ try {
403
+ live = begin();
404
+ } catch (error) {
405
+ __emnapiWasmEnvCleanupPreparing = false;
406
+ throw error;
407
+ }
408
+ __emnapiWasmEnvCleanupRan = true;
409
+ const finishCleanup = () => {
410
+ if (__emnapiWasmEnvCleanupPrepared) return;
411
+ __finishParkedWasmEnvCleanup = void 0;
412
+ try {
413
+ finish();
414
+ } finally {
415
+ __emnapiWasmEnvCleanupPreparing = false;
416
+ }
417
+ __emnapiWasmEnvCleanupPrepared = true;
418
+ };
419
+ if (!live || typeof workPending !== "function") {
420
+ finishCleanup();
421
+ return;
422
+ }
423
+ __finishParkedWasmEnvCleanup = finishCleanup;
424
+ return (async () => {
425
+ const pace = __createWasmRuntimePollPace();
426
+ for (;;) {
427
+ await __yieldWasmRuntimePollTurn(pace);
428
+ try {
429
+ if (!workPending()) return;
430
+ } catch {
431
+ return;
432
+ }
433
+ }
434
+ })().then(finishCleanup, finishCleanup);
435
+ }
436
+ const __WASM_ENV_CLEANUP_DRAIN_TURNS = 128;
437
+ const __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS = 4;
438
+ /**
439
+ * `napi_prepare_wasm_env_cleanup` only *queues* the promise settlements of the
440
+ * tasks it cancelled: `napi_call_threadsafe_function` appends to the
441
+ * threadsafe-function queue, and @emnapi/core dispatches that queue from a
442
+ * macrotask — two coalescing turns later, even for a call made on this very
443
+ * thread. `Context.destroy()` then runs the threadsafe function's cleanup hook,
444
+ * which drains the queue with a null env and *discards* whatever is still in it.
445
+ *
446
+ * So destroying without yielding first strands exactly the promises the barrier
447
+ * exists to settle. Yield real event-loop turns until the addon reports the
448
+ * queue empty; microtask checkpoints cannot help, no number of them lets a
449
+ * macrotask run.
450
+ *
451
+ * Returns nothing when there is nothing to wait for, which keeps disposal
452
+ * synchronous in the common case.
453
+ *
454
+ * The "already drained" flag is set only once a wait has actually finished.
455
+ * Scheduling a macrotask can fail — a host-provided or patched `setImmediate`
456
+ * that throws is enough — and a disposal that rejects stays retryable, so
457
+ * marking the drain complete up front would make the retry skip it and destroy
458
+ * the context with the barrier's settlements still queued.
459
+ *
460
+ * A wait that runs out of turns with the counter still nonzero rejects with
461
+ * `ERR_NAPI_WASI_CLEANUP_PENDING` for the same reason: at that point
462
+ * "finished" is indistinguishable from the stranding above, and destroying
463
+ * would discard the very settlement the wait was for. The rejection leaves the
464
+ * flag unset and disposal retryable.
465
+ */
466
+ function __drainWasmEnvCleanup() {
467
+ if (__emnapiWasmEnvCleanupDrained || !__emnapiWasmEnvCleanupRan) return;
468
+ if (__emnapiWasmEnvCleanupDrainPromise) return __emnapiWasmEnvCleanupDrainPromise;
469
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending;
470
+ const observable = typeof pending === "function";
471
+ if (observable) {
472
+ let queued;
473
+ try {
474
+ queued = pending();
475
+ } catch {
476
+ __emnapiWasmEnvCleanupDrained = true;
477
+ return;
478
+ }
479
+ if (!queued) {
480
+ __emnapiWasmEnvCleanupDrained = true;
481
+ return;
482
+ }
483
+ }
484
+ const limit = observable ? __WASM_ENV_CLEANUP_DRAIN_TURNS : __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS;
485
+ const drainPromise = (async () => {
486
+ let queued = 0;
487
+ for (let turn = 0; turn < limit; turn++) {
488
+ await new Promise((resolve) => {
489
+ __scheduleMacrotask(resolve);
490
+ });
491
+ if (!observable) continue;
492
+ try {
493
+ queued = pending();
494
+ } catch {
495
+ return;
496
+ }
497
+ if (!queued) return;
498
+ }
499
+ if (!observable) return;
500
+ const drainError = /* @__PURE__ */ new Error("the wasm environment still reports " + queued + " queued settlement(s) after " + limit + " event-loop turns; the context was not destroyed - retry dispose() to wait for the queue again");
501
+ drainError.code = "ERR_NAPI_WASI_CLEANUP_PENDING";
502
+ throw drainError;
503
+ })().then((value) => {
504
+ __emnapiWasmEnvCleanupDrained = true;
505
+ __emnapiWasmEnvCleanupDrainPromise = void 0;
506
+ return value;
507
+ }, (error) => {
508
+ __emnapiWasmEnvCleanupDrainPromise = void 0;
509
+ throw error;
510
+ });
511
+ __emnapiWasmEnvCleanupDrainPromise = drainPromise;
512
+ return drainPromise;
513
+ }
514
+ function __destroyEmnapiContext() {
515
+ if (__emnapiContextDestroyed || __emnapiContext === void 0) {
516
+ __emnapiContextDestroyed = true;
517
+ return;
518
+ }
519
+ if (__emnapiContextDestroyPromise) return __emnapiContextDestroyPromise;
520
+ __prepareWasmEnvCleanup();
521
+ if (__isPreparingWasmEnvCleanup()) return;
522
+ const result = __emnapiContext.destroy();
523
+ if (!__isThenable(result)) {
524
+ __emnapiContextDestroyed = true;
525
+ return;
526
+ }
527
+ const destroyPromise = Promise.resolve(result).then((value) => {
528
+ __emnapiContextDestroyed = true;
529
+ return value;
530
+ }, (error) => {
531
+ __emnapiContextDestroyPromise = void 0;
532
+ throw error;
533
+ });
534
+ __emnapiContextDestroyPromise = destroyPromise;
535
+ return destroyPromise;
536
+ }
537
+ /**
538
+ * Holds the event loop open until `work` settles.
539
+ *
540
+ * Nothing else can: the pool workers are deliberately unreferenced so an idle
541
+ * binding cannot keep a process alive, and referencing them again for the
542
+ * termination does not hold either — emnapi unreferences a worker the moment it
543
+ * reports `async-thread-ready`, which for a worker that was still starting
544
+ * lands *after* the termination began. Without a handle of its own, an
545
+ * `await dispose()` with nothing else pending exits the process with its
546
+ * promise unsettled, and everything after the `await` is skipped.
547
+ *
548
+ * The timer is cleared as soon as the work settles, so this never outlives the
549
+ * disposal that asked for it.
550
+ */
551
+ function __keepEventLoopAliveUntil(work) {
552
+ const setTimer = globalThis.setInterval;
553
+ const clearTimer = globalThis.clearInterval;
554
+ if (typeof setTimer !== "function" || typeof clearTimer !== "function") return work;
555
+ let timer;
556
+ try {
557
+ timer = setTimer(function() {}, 50);
558
+ } catch {
559
+ return work;
560
+ }
561
+ const release = function() {
562
+ try {
563
+ clearTimer(timer);
564
+ } catch {}
565
+ };
566
+ return work.then((value) => {
567
+ release();
568
+ return value;
569
+ }, (error) => {
570
+ release();
571
+ throw error;
572
+ });
573
+ }
574
+ const __WASI_ASYNC_WORK_POLL_INTERVAL_MS = 1;
575
+ /**
576
+ * Settles this addon's outstanding `napi_async_work` before the teardown that
577
+ * would strand it.
578
+ *
579
+ * `napi_prepare_wasm_env_cleanup` does not cover async work, and nothing about
580
+ * it is observable from JavaScript: the threadless archive resolves
581
+ * `napi_*_async_work` through the `@emnapi/core` plugins, but the threaded one
582
+ * links the C `async_work.c` on the uv threadpool, so there the wasm neither
583
+ * imports nor exports those symbols and the only brackets a loader could watch
584
+ * (`_emnapi_ctx_*_waiting_request_counter`) are shared with threadsafe
585
+ * functions. The addon is the one place both flavors go through, so it answers
586
+ * for both, through the same kind of handshake the settlement drain uses:
587
+ *
588
+ * - `napi_wasm_cancel_pending_async_work()` cancels what no thread has
589
+ * started. Those completion callbacks run with `napi_cancelled`, which
590
+ * napi-rs turns into a promise rejected with an `AbortError`.
591
+ * - `napi_wasm_async_work_pending()` counts what is still owed a completion
592
+ * callback. Work already executing refuses cancellation and stays counted
593
+ * until it finishes normally — which it can, because this runs before the
594
+ * barrier, before `Context.destroy()` and before anything is terminated.
595
+ *
596
+ * Both exports are optional: an addon built against a napi crate that predates
597
+ * them drains nothing and keeps the previous behavior, exactly as the
598
+ * `napi_wasm_env_cleanup_pending` handshake degrades.
599
+ *
600
+ * Returns nothing when there is nothing outstanding, which keeps disposal
601
+ * synchronous in the common case. The promise it returns otherwise never
602
+ * rejects.
603
+ *
604
+ * The wait has no deadline, and that is the point: giving up would destroy the
605
+ * environment with a completion callback still owed, which is the stranding
606
+ * this exists to prevent. A task whose `execute` never returns already keeps an
607
+ * *undisposed* process alive in exactly the same way, so disposal inherits that
608
+ * rather than inventing a bound it cannot honor.
609
+ *
610
+ * Safe to call from inside a completion callback, which is reachable: settling
611
+ * a task runs addon code that can re-enter JavaScript — a setter on the value
612
+ * being handed back, a threadsafe-function callback — and that JavaScript can
613
+ * call `dispose()`. Two things make it terminate rather than wait on itself:
614
+ *
615
+ * - The addon keeps a work registered until its completion callback
616
+ * *finishes*, so the count read here is at least one and this takes the
617
+ * polling path instead of declaring the environment drained and tearing it
618
+ * down from inside the frame that is still settling a promise.
619
+ * - The poll is a timer, so it cannot run until the callback has returned to
620
+ * the host — by which time that work has left the registry. The count the
621
+ * next poll reads is the one taken after the callback finished.
622
+ *
623
+ * `__disposeWasiBinding` hands every caller the same in-flight promise, so the
624
+ * nested call joins this disposal rather than starting a second one.
625
+ */
626
+ function __drainWasiAsyncWork() {
627
+ if (__wasiAsyncWorkDrainPromise !== void 0) return __wasiAsyncWorkDrainPromise;
628
+ const exports = __napiInstance?.exports;
629
+ const pending = exports?.napi_wasm_async_work_pending;
630
+ const cancelPending = exports?.napi_wasm_cancel_pending_async_work;
631
+ if (typeof pending !== "function" || typeof cancelPending !== "function") return;
632
+ const readPending = () => {
633
+ try {
634
+ return pending();
635
+ } catch (error) {
636
+ if (error instanceof globalThis.WebAssembly.RuntimeError) return 0;
637
+ throw error;
638
+ }
639
+ };
640
+ if (!readPending()) return;
641
+ try {
642
+ cancelPending();
643
+ } catch {}
644
+ if (!readPending()) return;
645
+ const drainPromise = __keepEventLoopAliveUntil((async () => {
646
+ while (readPending()) await new Promise((resolve) => {
647
+ __scheduleTimer(resolve, __WASI_ASYNC_WORK_POLL_INTERVAL_MS);
648
+ });
649
+ })()).then(() => {
650
+ __wasiAsyncWorkDrainPromise = void 0;
651
+ }, (error) => {
652
+ __wasiAsyncWorkDrainPromise = void 0;
653
+ throw error;
654
+ });
655
+ __wasiAsyncWorkDrainPromise = drainPromise;
656
+ return drainPromise;
657
+ }
658
+ /**
659
+ * `@emnapi/wasi-threads` counts a worker exit as expected only when its own
660
+ * thread manager performed the termination. A bare `worker.terminate()` reaches
661
+ * the manager's `exit` listener instead, which reports
662
+ * `worker (tid = N) sent an error! ... stopped with exit code 1` and rethrows
663
+ * inside the emit — aborting the `once('exit')` that backs the terminate
664
+ * promise, so disposal never settles and the process dies with an uncaught
665
+ * exception. Mark the termination through the manager first.
666
+ *
667
+ * The manager comes from `__getWasiThreadManager`, not from `__napiModule`:
668
+ * the initialization rollback runs on the one path where instantiation never
669
+ * returned, so `__napiModule` is still undefined there while the workers it
670
+ * spawned are already registered and loaded.
671
+ *
672
+ * Not `terminateAllThreads()`: that one recreates the pool it just shut down.
673
+ */
674
+ function __terminateWasiWorkers() {
675
+ const cleanupErrors = [];
676
+ const pending = [];
677
+ const threadManager = __getWasiThreadManager();
678
+ for (const worker of __wasiWorkers) {
679
+ let result;
680
+ try {
681
+ if (threadManager) {
682
+ threadManager.terminateWorker(worker);
683
+ worker.onmessage = void 0;
684
+ }
685
+ result = worker.terminate();
686
+ } catch (error) {
687
+ cleanupErrors.push(error);
688
+ continue;
689
+ }
690
+ if (__isThenable(result)) pending.push(Promise.resolve(result).then(() => {
691
+ __wasiWorkers.delete(worker);
692
+ }, (error) => {
693
+ cleanupErrors.push(error);
694
+ }));
695
+ else __wasiWorkers.delete(worker);
696
+ }
697
+ const finish = () => {
698
+ if (cleanupErrors.length > 0) throw __createCleanupError(cleanupErrors, "Failed to terminate WASI workers");
699
+ };
700
+ return pending.length > 0 ? __keepEventLoopAliveUntil(Promise.all(pending)).then(finish) : finish();
701
+ }
702
+ function __finishWasiDisposal() {
703
+ const workerResult = __terminateWasiWorkers();
704
+ if (__isThenable(workerResult)) return Promise.resolve(workerResult).then(__completeWasiDisposal);
705
+ }
706
+ function __continueWasiDisposal() {
707
+ const destroyResult = __destroyEmnapiContext();
708
+ if (__isThenable(destroyResult)) return Promise.resolve(destroyResult).then(__finishWasiDisposal);
709
+ return __finishWasiDisposal();
710
+ }
711
+ function __drainWasmEnvForWasiDisposal() {
712
+ const drainResult = __drainWasmEnvCleanup();
713
+ if (__isThenable(drainResult)) return Promise.resolve(drainResult).then(__continueWasiDisposal);
714
+ return __continueWasiDisposal();
715
+ }
716
+ function __cleanUpWasmEnvForWasiDisposal() {
717
+ const prepareResult = __prepareWasmEnvCleanupWithTurns();
718
+ if (__isThenable(prepareResult)) return Promise.resolve(prepareResult).then(__drainWasmEnvForWasiDisposal);
719
+ return __drainWasmEnvForWasiDisposal();
720
+ }
721
+ function __startWasiDisposal() {
722
+ const asyncWorkResult = __drainWasiAsyncWork();
723
+ if (__isThenable(asyncWorkResult)) return Promise.resolve(asyncWorkResult).then(__cleanUpWasmEnvForWasiDisposal);
724
+ return __cleanUpWasmEnvForWasiDisposal();
725
+ }
726
+ /**
727
+ * Disposes this generated WASI binding.
728
+ *
729
+ * Access this function with:
730
+ * binding[Symbol.for('napi.rs.wasi.dispose')]()
731
+ */
732
+ function __disposeWasiBinding() {
733
+ if (__wasiDisposePromise) return __wasiDisposePromise;
734
+ if (__wasiDisposed) return Promise.resolve();
735
+ let resolveDispose;
736
+ let rejectDispose;
737
+ const disposePromise = new Promise((resolve, reject) => {
738
+ resolveDispose = resolve;
739
+ rejectDispose = reject;
740
+ });
741
+ __wasiDisposePromise = disposePromise;
742
+ let result;
743
+ try {
744
+ result = __startWasiDisposal();
745
+ } catch (error) {
746
+ __wasiDisposePromise = void 0;
747
+ rejectDispose(error);
748
+ return disposePromise;
749
+ }
750
+ Promise.resolve(result).then((value) => {
751
+ __wasiDisposed = true;
752
+ resolveDispose(value);
753
+ }, (error) => {
754
+ __wasiDisposePromise = void 0;
755
+ rejectDispose(error);
756
+ });
757
+ return disposePromise;
758
+ }
759
+ function __publishWasiDispose(exports) {
760
+ Object.defineProperty(exports, __wasiDisposeSymbol, {
761
+ configurable: false,
762
+ enumerable: false,
763
+ value: __disposeWasiBinding,
764
+ writable: false
765
+ });
766
+ }
767
+ function __finishWasiInitializationRollback(cleanupErrors) {
768
+ let workerResult;
769
+ try {
770
+ workerResult = __terminateWasiWorkers();
771
+ } catch (cleanupError) {
772
+ cleanupErrors.push(cleanupError);
773
+ return cleanupErrors;
774
+ }
775
+ if (__isThenable(workerResult)) return Promise.resolve(workerResult).catch((cleanupError) => {
776
+ cleanupErrors.push(cleanupError);
777
+ }).then(() => cleanupErrors);
778
+ return cleanupErrors;
779
+ }
780
+ function __destroyContextForWasiRollback(cleanupErrors) {
781
+ let destroyResult;
782
+ try {
783
+ destroyResult = __destroyEmnapiContext();
784
+ } catch (cleanupError) {
785
+ cleanupErrors.push(cleanupError);
786
+ return __finishWasiInitializationRollback(cleanupErrors);
787
+ }
788
+ if (__isThenable(destroyResult)) return Promise.resolve(destroyResult).catch((cleanupError) => {
789
+ cleanupErrors.push(cleanupError);
790
+ }).then(() => __finishWasiInitializationRollback(cleanupErrors));
791
+ return __finishWasiInitializationRollback(cleanupErrors);
792
+ }
793
+ /**
794
+ * Leaves a rollback that could not reach the queued settlements undestroyed, and
795
+ * hands it to whatever this flavor has that can still reclaim it.
796
+ */
797
+ function __retainFailedWasiRollback(cleanupErrors) {
798
+ return cleanupErrors;
799
+ }
800
+ /**
801
+ * Initialization can fail *after* registration has already run, and registration
802
+ * runs with a live environment: a module-init hook can start async work and then
803
+ * return an error, and the promise it created may already have escaped into
804
+ * JavaScript. The barrier cancels that work and *queues* the settlement, so this
805
+ * path needs the same drain the ordinary disposal does — destroying without
806
+ * yielding discards the queue with a null env and strands the promise.
807
+ *
808
+ * Stays synchronous when nothing is queued, which covers every failure before
809
+ * `beforeInit`: there is no instance to run the barrier on, so nothing to drain.
810
+ *
811
+ * A barrier or drain that did *not* finish stops the rollback short of
812
+ * destroying, which is what `dispose()` already does — a rejected drain there
813
+ * never reaches `__continueWasiDisposal`. Destroying anyway is the worse of the
814
+ * two trades, and not because of what it saves:
815
+ *
816
+ * - It cannot deliver the settlements. `Context.destroy()` runs the
817
+ * threadsafe function's cleanup hook, which drains the queue with a null env
818
+ * and discards it, so a promise that already escaped into JavaScript hangs
819
+ * forever with nothing left that could ever settle it.
820
+ * - It saves less than it looks. `Context.destroy()` stops JavaScript calls
821
+ * and runs cleanup hooks; it does not free the wasm instance or its Memory,
822
+ * which this module's scope holds either way. What stopping short retains is
823
+ * the emnapi context's bookkeeping and its un-run cleanup hooks.
824
+ * - Retry is not theoretical. A rollback that records a cleanup error is
825
+ * already kept in the process-wide registry above, so re-`require()`ing this
826
+ * file replays it instead of re-instantiating — and the `6e15de6f` flag fix
827
+ * means the replay drains again rather than skipping it. Destroying first is
828
+ * what makes that retained record useless.
829
+ *
830
+ * The residual cost is honest: the CJS flavor hands the context to its
831
+ * `process.on('exit')` teardown, so a process that never retries still reclaims
832
+ * it on the way out. The ESM browser flavor has no equivalent — a module that
833
+ * throws while evaluating is permanently errored, so re-importing rethrows
834
+ * without re-running this file — and there the context stays until the realm
835
+ * goes away. That is the deliberate choice: a hung promise is a silent liveness
836
+ * bug with no upper bound, while the retained bookkeeping is bounded by the page.
837
+ */
838
+ function __rollbackWasiInitialization() {
839
+ function __rollbackWasmEnvForWasiInitialization() {
840
+ const cleanupErrors = [];
841
+ let prepareResult;
842
+ try {
843
+ prepareResult = __prepareWasmEnvCleanupWithTurns();
844
+ } catch (cleanupError) {
845
+ cleanupErrors.push(cleanupError);
846
+ return __retainFailedWasiRollback(cleanupErrors);
847
+ }
848
+ if (__isThenable(prepareResult)) return Promise.resolve(prepareResult).then(() => __drainWasmEnvForWasiRollback(cleanupErrors), (cleanupError) => {
849
+ cleanupErrors.push(cleanupError);
850
+ return __retainFailedWasiRollback(cleanupErrors);
851
+ });
852
+ return __drainWasmEnvForWasiRollback(cleanupErrors);
853
+ }
854
+ function __drainWasmEnvForWasiRollback(cleanupErrors) {
855
+ let drainResult;
856
+ try {
857
+ drainResult = __drainWasmEnvCleanup();
858
+ } catch (cleanupError) {
859
+ cleanupErrors.push(cleanupError);
860
+ return __retainFailedWasiRollback(cleanupErrors);
861
+ }
862
+ if (__isThenable(drainResult)) return Promise.resolve(drainResult).then(() => __destroyContextForWasiRollback(cleanupErrors), (cleanupError) => {
863
+ cleanupErrors.push(cleanupError);
864
+ return __retainFailedWasiRollback(cleanupErrors);
865
+ });
866
+ return __destroyContextForWasiRollback(cleanupErrors);
867
+ }
868
+ const __retainAfterAsyncWorkDrainFailure = (cleanupError) => __retainFailedWasiRollback([cleanupError]);
869
+ let asyncWorkResult;
870
+ try {
871
+ asyncWorkResult = __drainWasiAsyncWork();
872
+ } catch (cleanupError) {
873
+ return __retainAfterAsyncWorkDrainFailure(cleanupError);
874
+ }
875
+ if (__isThenable(asyncWorkResult)) return Promise.resolve(asyncWorkResult).then(__rollbackWasmEnvForWasiInitialization, __retainAfterAsyncWorkDrainFailure);
876
+ return __rollbackWasmEnvForWasiInitialization();
877
+ }
878
+ let __wasiAddonCrashFlag;
879
+ function __captureWasiAddonCrashFlag(instance) {
880
+ try {
881
+ const getAddress = instance.exports.napi_wasm_thread_crash_flag_address;
882
+ if (typeof getAddress !== "function") return;
883
+ const address = getAddress() >>> 0;
884
+ const buffer = __sharedMemory.buffer;
885
+ if (address === 0 || address % 4 !== 0 || address + 4 > buffer.byteLength) return;
886
+ __wasiAddonCrashFlag = new Int32Array(buffer, address, 1);
887
+ } catch {}
888
+ }
889
+ function __shareWasiAddonCrashFlag(worker) {
890
+ if (__wasiAddonCrashFlag === void 0) return;
891
+ try {
892
+ worker.postMessage({ __napiRsAddonCrashFlag: __wasiAddonCrashFlag });
893
+ } catch {}
894
+ }
895
+ let __wasiModule;
896
+ let __napiModule;
897
+ try {
898
+ __emnapiContext = __wrapEmnapiContextDestroyForSettlement(createContext({ autoDestroy: false }), __prepareWasmEnvCleanup, __isPreparingWasmEnvCleanup);
899
+ __emnapiContext.suppressDestroy();
900
+ ({instance: __napiInstance, module: __wasiModule, napiModule: __napiModule} = await instantiateNapiModule(__wasmFile, {
901
+ context: __emnapiContext,
902
+ asyncWorkPoolSize: __asyncWorkPoolSize,
903
+ reuseWorker: { size: __asyncWorkPoolSize + __workerPoolSize },
904
+ plugins: [
905
+ __captureWasiThreadManager,
906
+ asyncWork,
907
+ threadsafeFunction
908
+ ],
909
+ wasi: __wasi,
910
+ onCreateWorker() {
911
+ const worker = new Worker(new URL("./wasi-worker-browser.mjs", import.meta.url), { type: "module" });
912
+ __wasiWorkers.add(worker);
913
+ __shareWasiAddonCrashFlag(worker);
914
+ worker.addEventListener("message", createOnMessage(__fs));
915
+ return worker;
916
+ },
917
+ overwriteImports(importObject) {
918
+ importObject.env = {
919
+ ...importObject.env,
920
+ ...importObject.napi,
921
+ ...importObject.emnapi,
922
+ memory: __sharedMemory
923
+ };
924
+ return importObject;
925
+ },
926
+ beforeInit({ instance }) {
927
+ __napiInstance = instance;
928
+ __captureWasiAddonCrashFlag(instance);
929
+ for (const worker of __wasiWorkers) __shareWasiAddonCrashFlag(worker);
930
+ for (const name of Object.keys(instance.exports)) if (name.startsWith("__napi_register__")) instance.exports[name]();
931
+ }
932
+ }));
933
+ __publishWasiDispose(__napiModule.exports);
934
+ __napiStampBindingTarget(__napiModule.exports, __napiBindingTarget);
935
+ } catch (error) {
936
+ throw __attachCleanupErrors(error, await __rollbackWasiInitialization());
937
+ }
938
+ var kirana_wasi_browser_default = __napiModule.exports;
939
+ const Compiler = __napiModule.exports.Compiler;
940
+ const runCli = __napiModule.exports.runCli;
941
+ const runLsp = __napiModule.exports.runLsp;
942
+ const scanComponent = __napiModule.exports.scanComponent;
943
+ // ../compiler/src/engine-json.ts
944
+ /**
945
+ * `root` joined with a relative module, for POSIX paths: `.` and `..` segments are resolved and
946
+ * the result is absolute when `root` is. The browser's in-memory projects have no other kind.
947
+ */
948
+ function posixResolve(root, module) {
949
+ const segments = [];
950
+ for (const segment of `${root}/${module}`.split("/")) {
951
+ if (segment === "" || segment === ".") continue;
952
+ if (segment === "..") segments.pop();
953
+ else segments.push(segment);
954
+ }
955
+ return `${root.startsWith("/") ? "/" : ""}${segments.join("/")}`;
956
+ }
957
+ /**
958
+ * The engine's JSON: file configuration, overridden key by key by inline options. `jsx` is the
959
+ * mode detected from the project when the configuration names none.
960
+ */
961
+ function engineJson(root, config, inline, options = {}) {
962
+ const { presets = [], utilities, ui: _registry, ...merged } = {
963
+ ...config,
964
+ ...inline
965
+ };
966
+ const jsx = merged.jsx ?? options.jsx;
967
+ const grammar = mergeGrammars([...presets.map((preset) => preset.utilities), utilities], root, options.resolveModule);
968
+ return JSON.stringify({
969
+ ...merged,
970
+ ...jsx ? { jsx } : {},
971
+ ...grammar ? { utilities: grammar } : {},
972
+ root
973
+ });
974
+ }
975
+ /**
976
+ * The presets' utility grammars and the project's, merged in order: a later scale, root or variant
977
+ * replaces an earlier one of the same name (KRN-TOK-008). A relative scale module is resolved from
978
+ * the project root, since the engine reads it from whichever module uses the utility.
979
+ */
980
+ function mergeGrammars(grammars, root, resolveModule = posixResolve) {
981
+ const present = grammars.filter((grammar) => grammar !== void 0);
982
+ if (present.length === 0) return void 0;
983
+ const scales = {};
984
+ const utilities = {};
985
+ const variants = {};
986
+ for (const grammar of present) {
987
+ for (const [name, sources] of Object.entries(grammar.scales ?? {})) scales[name] = sources.map((source) => ({
988
+ module: /^\.\.?\//.test(source.module) ? resolveModule(root, source.module) : source.module,
989
+ export: source.export
990
+ }));
991
+ Object.assign(utilities, grammar.utilities);
992
+ Object.assign(variants, grammar.variants);
993
+ }
994
+ return {
995
+ scales,
996
+ utilities,
997
+ variants
998
+ };
999
+ }
1000
+ // src/project.ts
1001
+ /**
1002
+ * A Kirana project held in memory, for the engine in a browser (KRN-CMP-012, D-113): the files are
1003
+ * written to the WebAssembly engine's file system, so a module's imports, the tokens it reads and
1004
+ * the configuration's scale modules resolve as they would on disk, and the `Compiler` session
1005
+ * compiles them.
1006
+ *
1007
+ * Nothing here loads the engine: `openProject` takes it, so the same code runs on the native engine
1008
+ * and a directory in the tests, and on the WebAssembly engine and its in-memory volume in a page.
1009
+ */
1010
+ const encoder = new TextEncoder();
1011
+ const decoder = new TextDecoder();
1012
+ /** The position of a UTF-8 byte offset in `source`. */
1013
+ function positionOf(source, offset) {
1014
+ const lines = decoder.decode(encoder.encode(source).subarray(0, offset)).split("\n");
1015
+ return {
1016
+ line: lines.length,
1017
+ column: lines.at(-1).length + 1
1018
+ };
1019
+ }
1020
+ /** A path relative to `root`, absolute as the engine needs it. */
1021
+ function absolute(root, file) {
1022
+ return `${root}/${file.replace(/^\.?\//, "")}`;
1023
+ }
1024
+ /** An engine path back to one relative to `root`; a path outside it is kept as it is. */
1025
+ function relative(root, file) {
1026
+ return file.startsWith(`${root}/`) ? file.slice(root.length + 1) : file;
1027
+ }
1028
+ /** Opens a project on `engine`: the configuration becomes the engine's JSON, the files are written. */
1029
+ function openProject(engine, { config = {}, root = "/app", files = {} } = {}) {
1030
+ const configJson = engineJson(root, config, {});
1031
+ const volume = engine.__volume;
1032
+ volume.mkdirSync(root, { recursive: true });
1033
+ const session = new engine.Compiler(configJson);
1034
+ const sources = /* @__PURE__ */ new Map();
1035
+ const diagnosticsOf = (json) => JSON.parse(json).map((diagnostic) => {
1036
+ const source = sources.get(diagnostic.file);
1037
+ return source === void 0 ? diagnostic : {
1038
+ ...diagnostic,
1039
+ start: positionOf(source, diagnostic.span.start),
1040
+ end: positionOf(source, diagnostic.span.end)
1041
+ };
1042
+ });
1043
+ const project = {
1044
+ root,
1045
+ configJson,
1046
+ write(file, code) {
1047
+ const path = absolute(root, file);
1048
+ volume.mkdirSync(path.slice(0, path.lastIndexOf("/")), { recursive: true });
1049
+ volume.writeFileSync(path, code);
1050
+ sources.set(relative(root, path), code);
1051
+ return session.invalidate(path).map((id) => relative(root, id));
1052
+ },
1053
+ remove(file) {
1054
+ const path = absolute(root, file);
1055
+ volume.rmSync(path, { force: true });
1056
+ sources.delete(relative(root, path));
1057
+ session.remove(path);
1058
+ },
1059
+ transform(file) {
1060
+ const path = absolute(root, file);
1061
+ const code = sources.get(relative(root, path));
1062
+ if (code === void 0) throw new Error(`${file} is not a file of this project`);
1063
+ const result = session.transform(path, code);
1064
+ return {
1065
+ code: result.code,
1066
+ map: result.map,
1067
+ diagnostics: diagnosticsOf(result.diagnostics),
1068
+ cssChanged: result.cssChanged,
1069
+ dependencies: result.dependencies.map((id) => relative(root, id))
1070
+ };
1071
+ },
1072
+ stylesheet: (minify = false) => session.stylesheet(minify),
1073
+ diagnostics: () => diagnosticsOf(session.diagnostics()),
1074
+ files: () => [...sources.keys()]
1075
+ };
1076
+ for (const [file, code] of Object.entries(files)) project.write(file, code);
1077
+ return project;
1078
+ }
1079
+ // src/index.js
1080
+ /**
1081
+ * The Kirana engine in a browser (D-113). Importing this module fetches the WebAssembly engine
1082
+ * beside it and starts its threads, so the page must be cross-origin isolated (COOP `same-origin`,
1083
+ * COEP `require-corp`): the engine's memory is a `SharedArrayBuffer`.
1084
+ *
1085
+ * Hand-written JavaScript: the engine it imports is the loader napi-rs writes for browsers, with an
1086
+ * in-memory file system (`napi.wasm.browser.fs`), and exists only once the WebAssembly build has
1087
+ * run. `scripts/pack.ts` bundles it, its worker and its runtime into this package.
1088
+ */
1089
+ /** Opens a project in the engine's in-memory file system. */
1090
+ function createProject(options) {
1091
+ return openProject(kirana_wasi_browser_exports, options);
1092
+ }
1093
+ export { engineJson as configJson, createProject, positionOf };