@isoloop/runtime 0.0.0-next.5bbb503 → 0.0.0-next.61245db

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/worker.js ADDED
@@ -0,0 +1,2237 @@
1
+ // \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __esmMin = (fn, res, err) => () => {
4
+ if (err) throw err[0];
5
+ try {
6
+ return fn && (res = fn(fn = 0)), res;
7
+ } catch (e) {
8
+ throw err = [e], e;
9
+ }
10
+ };
11
+ var __exportAll = (all, no_symbols) => {
12
+ let target = {};
13
+ for (var name in all) __defProp(target, name, {
14
+ get: all[name],
15
+ enumerable: true
16
+ });
17
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
18
+ return target;
19
+ };
20
+ // ../protocol/dist/index.js
21
+ /**
22
+ * True for a well-formed envelope this build can read: `v` is a supported
23
+ * version, `t` is a string, `id`/`re`/`isolate` are absent or strings, and `p`
24
+ * is present.
25
+ * Says nothing about whether `t` is known; see the per-port guards.
26
+ */
27
+ function isEnvelope(x) {
28
+ return isRecord(x) && x["v"] === PROTOCOL.v && typeof x["t"] === "string" && "p" in x && isOptionalString(x["id"]) && isOptionalString(x["re"]) && isOptionalString(x["isolate"]);
29
+ }
30
+ /**
31
+ * Builds a guard for one port's union from its message types. Each side drops
32
+ * (and counts) envelopes with an unknown `v` or `t` (design §3), so a guard
33
+ * only checks the envelope and the type, not the payload.
34
+ */
35
+ function envelopeGuard(types) {
36
+ return (x) => isEnvelope(x) && Object.hasOwn(types, x.t);
37
+ }
38
+ function isSystemTopic(topic) {
39
+ return topic.startsWith(SYSTEM_TOPIC_PREFIX);
40
+ }
41
+ /** Wraps a hand-written check as a Standard Schema that passes valid values through unchanged. */
42
+ function systemSchema(check) {
43
+ return { "~standard": {
44
+ version: 1,
45
+ vendor: "isoloop",
46
+ validate: (value) => {
47
+ const issues = check(value, []);
48
+ return issues.length === 0 ? { value } : { issues };
49
+ }
50
+ } };
51
+ }
52
+ /** Defines a system topic. The name must start with `isoloop.`. */
53
+ function systemTopic(name, def) {
54
+ if (!isSystemTopic(name)) throw new Error(`system topic names start with isoloop.: ${name}`);
55
+ return Object.freeze({
56
+ ...def,
57
+ name
58
+ });
59
+ }
60
+ /** `"0.4.2"` → `"0.4"`. Anything that isn't `major.minor[.patch…]` gives `undefined`. */
61
+ function majorMinor(version) {
62
+ const m = /^(\d+)\.(\d+)(?:[.+-].*)?$/.exec(version);
63
+ return m ? `${Number(m[1])}.${Number(m[2])}` : void 0;
64
+ }
65
+ var PROTOCOL, isRecord, isOptionalString, ERROR_CODES, SYSTEM_TOPIC_PREFIX, HOST_TO_ISOLATE, isHostToIsolate, BUS_TO_ISOLATE, isBusToIsolate, BusError, isObject, issue, checks, stringOrNull;
66
+ var init_dist = __esmMin((() => {
67
+ PROTOCOL = {
68
+ v: 1,
69
+ min: 1
70
+ };
71
+ isRecord = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
72
+ isOptionalString = (x) => x === void 0 || typeof x === "string";
73
+ ERROR_CODES = [
74
+ "protocol_mismatch",
75
+ "timeout",
76
+ "no_surface",
77
+ "forbidden",
78
+ "not_found",
79
+ "unsupported",
80
+ "cross_origin",
81
+ "routing_disabled",
82
+ "navigate_failed",
83
+ "unknown_topic",
84
+ "too_large",
85
+ "invalid",
86
+ "not_encodable",
87
+ "quota_exceeded",
88
+ "bus_unavailable",
89
+ "not_requestable",
90
+ "already_replied",
91
+ "reply_invalid",
92
+ "contracts_failed",
93
+ "contracts_invalid",
94
+ "contracts_mismatch",
95
+ "reserved_topic",
96
+ "seed_async",
97
+ "seed_pending"
98
+ ];
99
+ new Set(ERROR_CODES);
100
+ SYSTEM_TOPIC_PREFIX = "isoloop.";
101
+ HOST_TO_ISOLATE = {
102
+ init: true,
103
+ event: true,
104
+ result: true,
105
+ shutdown: true,
106
+ reattach: true
107
+ };
108
+ isHostToIsolate = envelopeGuard(HOST_TO_ISOLATE);
109
+ BUS_TO_ISOLATE = {
110
+ deliver: true,
111
+ reset: true,
112
+ result: true
113
+ };
114
+ isBusToIsolate = envelopeGuard(BUS_TO_ISOLATE);
115
+ BusError = class extends Error {
116
+ code;
117
+ issues;
118
+ constructor(error) {
119
+ super(error.message);
120
+ this.name = "BusError";
121
+ this.code = error.code;
122
+ this.issues = error.issues;
123
+ }
124
+ };
125
+ isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
126
+ issue = (path, message) => [{
127
+ message,
128
+ path
129
+ }];
130
+ checks = {
131
+ string: (v, path) => typeof v === "string" ? [] : issue(path, "expected a string"),
132
+ optionalString: (v, path) => v === void 0 || typeof v === "string" ? [] : issue(path, "expected a string or nothing"),
133
+ object: (fields) => (v, path) => {
134
+ if (!isObject(v)) return issue(path, "expected an object");
135
+ return Object.entries(fields).flatMap(([k, check]) => check(v[k], [...path, k]));
136
+ },
137
+ any: () => []
138
+ };
139
+ stringOrNull = (v, path) => v === null || typeof v === "string" ? [] : [{
140
+ message: "expected a string or null",
141
+ path
142
+ }];
143
+ systemTopic("isoloop.route.v1", {
144
+ schema: systemSchema(checks.object({
145
+ href: checks.string,
146
+ pathname: checks.string,
147
+ path: stringOrNull,
148
+ search: checks.string,
149
+ hash: checks.string,
150
+ state: checks.any
151
+ })),
152
+ retention: { kind: "compacted" }
153
+ });
154
+ }));
155
+ // src/freeze.ts
156
+ /**
157
+ * Freezing a prototype makes its data properties read-only, and in strict
158
+ * code assigning a property of the same name on an instance then throws (the
159
+ * "override mistake": `this.name = 'MyError'`, `Foo.prototype.toString = …`).
160
+ * As Hardened JS does, each data property becomes an accessor whose setter
161
+ * defines the property on the instance instead, so overriding still works
162
+ * while the prototype itself can't change.
163
+ */
164
+ function tameOverrides(proto) {
165
+ for (const key of Reflect.ownKeys(proto)) {
166
+ const d = Object.getOwnPropertyDescriptor(proto, key);
167
+ if (!d || !("value" in d) || !d.configurable) continue;
168
+ const value = d.value;
169
+ Object.defineProperty(proto, key, {
170
+ get() {
171
+ return value;
172
+ },
173
+ set(v) {
174
+ if (this === proto) throw new TypeError(`Cannot assign to read only property '${String(key)}' of a frozen built-in`);
175
+ if (typeof this !== "object" && typeof this !== "function") return;
176
+ if (this === null) return;
177
+ Object.defineProperty(this, key, {
178
+ value: v,
179
+ writable: true,
180
+ enumerable: true,
181
+ configurable: true
182
+ });
183
+ },
184
+ enumerable: d.enumerable ?? false,
185
+ configurable: false
186
+ });
187
+ }
188
+ }
189
+ function hardenProto(proto) {
190
+ if (typeof proto !== "object" && typeof proto !== "function" || proto === null) return;
191
+ if (Object.isFrozen(proto)) return;
192
+ tameOverrides(proto);
193
+ Object.freeze(proto);
194
+ }
195
+ function freezeWithPrototype(c) {
196
+ if (typeof c !== "function") return;
197
+ hardenProto(Reflect.get(c, "prototype"));
198
+ if (c !== Error) Object.freeze(c);
199
+ }
200
+ /** Freezes the shared intrinsics. Call once, before any member module loads. */
201
+ function freezeBuiltins() {
202
+ const g = globalThis;
203
+ for (const name of NAMES) freezeWithPrototype(Reflect.get(g, name));
204
+ freezeWithPrototype(Object.getPrototypeOf(Int8Array));
205
+ const protos = [
206
+ Object.getPrototypeOf([][Symbol.iterator]()),
207
+ Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())),
208
+ Object.getPrototypeOf((/* @__PURE__ */ new Map())[Symbol.iterator]()),
209
+ Object.getPrototypeOf((/* @__PURE__ */ new Set())[Symbol.iterator]()),
210
+ Object.getPrototypeOf(""[Symbol.iterator]()),
211
+ Object.getPrototypeOf(function* () {}),
212
+ Object.getPrototypeOf(async function() {}),
213
+ Object.getPrototypeOf(async function* () {})
214
+ ];
215
+ for (const p of protos) {
216
+ if (typeof p !== "object" && typeof p !== "function" || p === null) continue;
217
+ hardenProto(Reflect.get(p, "prototype"));
218
+ hardenProto(p);
219
+ }
220
+ Object.freeze(Math);
221
+ Object.freeze(JSON);
222
+ Object.freeze(Reflect);
223
+ }
224
+ var NAMES;
225
+ var init_freeze = __esmMin((() => {
226
+ NAMES = [
227
+ "Object",
228
+ "Function",
229
+ "Array",
230
+ "String",
231
+ "Number",
232
+ "Boolean",
233
+ "Symbol",
234
+ "BigInt",
235
+ "Date",
236
+ "RegExp",
237
+ "Error",
238
+ "EvalError",
239
+ "RangeError",
240
+ "ReferenceError",
241
+ "SyntaxError",
242
+ "TypeError",
243
+ "URIError",
244
+ "AggregateError",
245
+ "Promise",
246
+ "Map",
247
+ "Set",
248
+ "WeakMap",
249
+ "WeakSet",
250
+ "WeakRef",
251
+ "FinalizationRegistry",
252
+ "ArrayBuffer",
253
+ "DataView",
254
+ "Int8Array",
255
+ "Uint8Array",
256
+ "Uint8ClampedArray",
257
+ "Int16Array",
258
+ "Uint16Array",
259
+ "Int32Array",
260
+ "Uint32Array",
261
+ "Float32Array",
262
+ "Float64Array",
263
+ "BigInt64Array",
264
+ "BigUint64Array"
265
+ ];
266
+ }));
267
+ // src/bus-client.ts
268
+ function createBusClient(first, o = {}) {
269
+ const limit = o.inboxLimit ?? 1e3;
270
+ const now = o.now ?? (() => performance.now());
271
+ let lastDelivery = now();
272
+ let port = first;
273
+ let nextId = 0;
274
+ const epoch = o.epoch ?? randomEpoch();
275
+ /** Publishes and requests sent by this instance: the `seq` of publish ids. */
276
+ let seq = 0;
277
+ const pending = /* @__PURE__ */ new Map();
278
+ const subs = /* @__PURE__ */ new Map();
279
+ /** Which topic a delivered record came from, for `reply` and `commit`. */
280
+ const topicOf = /* @__PURE__ */ new WeakMap();
281
+ const send = (msg) => {
282
+ port.postMessage(msg);
283
+ };
284
+ const call = (msg) => {
285
+ if (pending.size >= limit) return Promise.resolve({
286
+ ok: false,
287
+ error: {
288
+ code: "bus_unavailable",
289
+ message: "Too many bus calls waiting for an answer"
290
+ }
291
+ });
292
+ const id = `b${++nextId}`;
293
+ return new Promise((settle) => {
294
+ const withId = {
295
+ ...msg,
296
+ id
297
+ };
298
+ pending.set(id, {
299
+ msg: withId,
300
+ settle
301
+ });
302
+ send(withId);
303
+ });
304
+ };
305
+ const commit = (topic, offset) => {
306
+ send({
307
+ v: 1,
308
+ t: "commit",
309
+ p: {
310
+ topic,
311
+ offset
312
+ }
313
+ });
314
+ };
315
+ const drain = async (sub) => {
316
+ if (sub.running) return;
317
+ sub.running = true;
318
+ while (sub.queue.length > 0 && subs.get(sub.topic) === sub) {
319
+ const r = sub.queue.shift();
320
+ if (!r) break;
321
+ topicOf.set(r, sub.topic);
322
+ try {
323
+ await sub.fn(r);
324
+ } catch (err) {
325
+ sub.stuck = true;
326
+ o.onError?.(err);
327
+ }
328
+ if (sub.opts.autoCommit !== false && !sub.stuck) commit(sub.topic, r.offset);
329
+ }
330
+ sub.running = false;
331
+ };
332
+ const sendSubscribe = (sub) => {
333
+ const p = {
334
+ topic: sub.topic,
335
+ from: sub.opts.from ?? "latest"
336
+ };
337
+ if (o.wake && p.from === "latest") p.from = "committed";
338
+ if (sub.opts.group !== void 0) p.group = sub.opts.group;
339
+ call({
340
+ v: 1,
341
+ t: "subscribe",
342
+ p
343
+ }).then((r) => {
344
+ if (!r.ok) o.onError?.(new BusError(r.error));
345
+ });
346
+ };
347
+ const receive = (msg) => {
348
+ switch (msg.t) {
349
+ case "result": {
350
+ const p = msg.re === void 0 ? void 0 : pending.get(msg.re);
351
+ if (!p || msg.re === void 0) return;
352
+ pending.delete(msg.re);
353
+ p.settle(msg.p);
354
+ return;
355
+ }
356
+ case "deliver": {
357
+ const sub = subs.get(msg.p.topic);
358
+ if (!sub) return;
359
+ lastDelivery = now();
360
+ const { gap } = msg.p;
361
+ if (gap) try {
362
+ sub.opts.onGap?.(gap);
363
+ } catch (err) {
364
+ o.onError?.(err);
365
+ }
366
+ sub.queue.push(...msg.p.records);
367
+ drain(sub);
368
+ return;
369
+ }
370
+ case "reset": {
371
+ const sub = subs.get(msg.p.topic);
372
+ if (!sub) return;
373
+ sub.queue.length = 0;
374
+ try {
375
+ sub.opts.onReset?.();
376
+ } catch (err) {
377
+ o.onError?.(err);
378
+ }
379
+ return;
380
+ }
381
+ default: return msg;
382
+ }
383
+ };
384
+ const listen = (p) => {
385
+ p.addEventListener("message", (e) => {
386
+ if (port === p && isBusToIsolate(e.data)) receive(e.data);
387
+ });
388
+ p.start();
389
+ };
390
+ listen(first);
391
+ return {
392
+ client: {
393
+ async publish(topic, rec) {
394
+ const p = {
395
+ topic: topic.name,
396
+ value: rec.value,
397
+ epoch,
398
+ seq: ++seq
399
+ };
400
+ if (rec.key !== void 0) p.key = rec.key;
401
+ check(await call({
402
+ v: 1,
403
+ t: "publish",
404
+ p
405
+ }));
406
+ },
407
+ subscribe(topic, fn, opts = {}) {
408
+ subs.get(topic.name)?.queue.splice(0);
409
+ const sub = {
410
+ topic: topic.name,
411
+ fn,
412
+ opts,
413
+ queue: [],
414
+ running: false,
415
+ stuck: false
416
+ };
417
+ subs.set(topic.name, sub);
418
+ sendSubscribe(sub);
419
+ return () => {
420
+ if (subs.get(topic.name) !== sub) return;
421
+ subs.delete(topic.name);
422
+ send({
423
+ v: 1,
424
+ t: "unsubscribe",
425
+ p: { topic: topic.name }
426
+ });
427
+ };
428
+ },
429
+ async request(topic, value, opts = {}) {
430
+ const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
431
+ const p = {
432
+ topic: topic.name,
433
+ value,
434
+ timeoutMs,
435
+ epoch,
436
+ seq: ++seq
437
+ };
438
+ if (opts.key !== void 0) p.key = opts.key;
439
+ let timer;
440
+ const timeout = new Promise((resolve) => {
441
+ timer = setTimeout(() => {
442
+ resolve({
443
+ ok: false,
444
+ error: {
445
+ code: "timeout",
446
+ message: `No reply on ${topic.name} within ${timeoutMs} ms`
447
+ }
448
+ });
449
+ }, timeoutMs);
450
+ });
451
+ const r = await Promise.race([call({
452
+ v: 1,
453
+ t: "request",
454
+ p
455
+ }), timeout]);
456
+ clearTimeout(timer);
457
+ check(r);
458
+ return r.value;
459
+ },
460
+ async reply(record, value) {
461
+ const topic = topicOf.get(record);
462
+ if (topic === void 0) throw new Error("reply: this record was not delivered to this isolate");
463
+ check(await call({
464
+ v: 1,
465
+ t: "reply",
466
+ p: {
467
+ topic,
468
+ offset: record.offset,
469
+ value
470
+ }
471
+ }));
472
+ },
473
+ commit(record) {
474
+ const topic = topicOf.get(record);
475
+ if (topic === void 0) throw new Error("commit: this record was not delivered to this isolate");
476
+ commit(topic, record.offset);
477
+ }
478
+ },
479
+ idle: () => ({
480
+ sinceDeliveryMs: now() - lastDelivery,
481
+ inFlight: pending.size
482
+ }),
483
+ reattach(next) {
484
+ const old = port;
485
+ port = next;
486
+ old.close();
487
+ listen(next);
488
+ const unanswered = [...pending.values()];
489
+ for (const p of unanswered) {
490
+ if (p.msg.t !== "subscribe") continue;
491
+ pending.delete(p.msg.id);
492
+ p.settle({
493
+ ok: true,
494
+ value: null
495
+ });
496
+ }
497
+ for (const sub of subs.values()) {
498
+ sub.queue.length = 0;
499
+ sendSubscribe(sub);
500
+ }
501
+ for (const p of unanswered) if (p.msg.t !== "subscribe") send(p.msg);
502
+ }
503
+ };
504
+ }
505
+ var randomEpoch, check, REQUEST_TIMEOUT_MS;
506
+ var init_bus_client = __esmMin((() => {
507
+ init_dist();
508
+ randomEpoch = () => crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(1))[0] ?? 0;
509
+ check = (r) => {
510
+ if (!r.ok) throw new BusError(r.error);
511
+ };
512
+ REQUEST_TIMEOUT_MS = 3e4;
513
+ }));
514
+ // src/host-calls.ts
515
+ function createHostCalls(opts) {
516
+ const timeoutMs = opts.timeoutMs ?? 5e3;
517
+ const pending = /* @__PURE__ */ new Map();
518
+ let seq = 0;
519
+ const send = (method, args) => {
520
+ const id = `c${++seq}`;
521
+ return new Promise((resolve, reject) => {
522
+ const timer = setTimeout(() => {
523
+ pending.delete(id);
524
+ reject(new HostCallError("timeout", `${method}: no answer within ${timeoutMs} ms`));
525
+ }, timeoutMs);
526
+ pending.set(id, {
527
+ resolve,
528
+ reject,
529
+ timer
530
+ });
531
+ opts.post({
532
+ v: 1,
533
+ t: "call",
534
+ id,
535
+ p: {
536
+ method,
537
+ args
538
+ }
539
+ });
540
+ });
541
+ };
542
+ const call = (method, node, extra = []) => {
543
+ const nodeId = opts.idOf(node);
544
+ if (opts.surface && nodeId === void 0) return Promise.reject(new HostCallError("not_found", `${method}: not a rendered node`));
545
+ opts.beforeCall();
546
+ return send(method, [nodeId ?? null, ...extra]);
547
+ };
548
+ return {
549
+ api: {
550
+ async navigate(href, o = {}) {
551
+ if (!opts.navigate) throw new HostCallError("forbidden", "navigate: this isolate has no navigate grant (ADR 0002)");
552
+ return await send("navigate", [href, {
553
+ replace: o.replace ?? false,
554
+ state: o.state
555
+ }]) === true;
556
+ },
557
+ async measure(node) {
558
+ const value = await call("measure", node);
559
+ if (!isRect(value)) throw new HostCallError("invalid", "measure: the host sent no rect");
560
+ return value;
561
+ },
562
+ async focus(node) {
563
+ await call("focus", node);
564
+ },
565
+ async scrollIntoView(node, o) {
566
+ await call("scrollIntoView", node, o === void 0 ? [] : [o]);
567
+ },
568
+ async requestCanvas(node, size) {
569
+ const value = await call("requestCanvas", node, size === void 0 ? [] : [size]);
570
+ if (!(value instanceof OffscreenCanvas)) throw new HostCallError("invalid", "requestCanvas: the host sent no OffscreenCanvas");
571
+ return value;
572
+ }
573
+ },
574
+ pending: () => pending.size,
575
+ receive(re, result) {
576
+ const p = pending.get(re);
577
+ if (!p) return;
578
+ pending.delete(re);
579
+ clearTimeout(p.timer);
580
+ if (result.ok) p.resolve(result.value);
581
+ else p.reject(new HostCallError(result.error.code, result.error.message));
582
+ }
583
+ };
584
+ }
585
+ var HostCallError, isRect;
586
+ var init_host_calls = __esmMin((() => {
587
+ HostCallError = class extends Error {
588
+ code;
589
+ constructor(code, message) {
590
+ super(message);
591
+ this.name = "HostCallError";
592
+ this.code = code;
593
+ }
594
+ };
595
+ isRect = (x) => typeof x === "object" && x !== null && [
596
+ "x",
597
+ "y",
598
+ "width",
599
+ "height"
600
+ ].every((k) => typeof Reflect.get(x, k) === "number");
601
+ }));
602
+ // src/keep-awake.ts
603
+ function createKeepAwake(now = () => performance.now()) {
604
+ const holds = /* @__PURE__ */ new Map();
605
+ let next = 0;
606
+ return {
607
+ hold() {
608
+ const id = ++next;
609
+ const stack = (/* @__PURE__ */ new Error("keepAwake")).stack?.split("\n").slice(2).join("\n");
610
+ holds.set(id, {
611
+ since: now(),
612
+ stack
613
+ });
614
+ return () => {
615
+ holds.delete(id);
616
+ };
617
+ },
618
+ report(at) {
619
+ return [...holds.values()].map((h) => h.stack === void 0 ? { ageMs: at - h.since } : {
620
+ ageMs: at - h.since,
621
+ stack: h.stack
622
+ });
623
+ }
624
+ };
625
+ }
626
+ var init_keep_awake = __esmMin((() => {}));
627
+ // ../dom/dist/records-wVZrPpqr.js
628
+ var ISOLOOP_DOM_FMT;
629
+ var init_records_wVZrPpqr = __esmMin((() => {
630
+ ISOLOOP_DOM_FMT = "isoloop-dom@1";
631
+ }));
632
+ // ../dom/dist/dom-yLsf0Z4e.js
633
+ function createStyle(el) {
634
+ const decls = /* @__PURE__ */ new Map();
635
+ const write = () => {
636
+ const text = [...decls].map(([k, v]) => `${k}: ${v};`).join(" ");
637
+ if (text) el.setAttribute("style", text);
638
+ else el.removeAttribute("style");
639
+ };
640
+ const set = (name, value) => {
641
+ const v = str(value);
642
+ if (v === "") decls.delete(name);
643
+ else decls.set(name, v);
644
+ };
645
+ return new Proxy({
646
+ setProperty(name, value) {
647
+ set(kebab(name), value);
648
+ write();
649
+ },
650
+ removeProperty(name) {
651
+ const old = decls.get(kebab(name)) ?? "";
652
+ decls.delete(kebab(name));
653
+ write();
654
+ return old;
655
+ },
656
+ getPropertyValue(name) {
657
+ return decls.get(kebab(name)) ?? "";
658
+ },
659
+ get cssText() {
660
+ return [...decls].map(([k, v]) => `${k}: ${v};`).join(" ");
661
+ },
662
+ set cssText(text) {
663
+ decls.clear();
664
+ for (const part of text.split(";")) {
665
+ const i = part.indexOf(":");
666
+ if (i > 0) set(part.slice(0, i).trim(), part.slice(i + 1).trim());
667
+ }
668
+ write();
669
+ }
670
+ }, {
671
+ get(t, key, receiver) {
672
+ if (typeof key !== "string" || key in t) return Reflect.get(t, key, receiver);
673
+ return decls.get(kebab(key === "cssFloat" ? "float" : key)) ?? "";
674
+ },
675
+ set(t, key, value, receiver) {
676
+ if (typeof key !== "string" || key in t) return Reflect.set(t, key, value, receiver);
677
+ set(kebab(key === "cssFloat" ? "float" : key), value);
678
+ write();
679
+ return true;
680
+ }
681
+ });
682
+ }
683
+ /**
684
+ * `element.dataset` (DOM group 1, ADR 0010): camelCase keys over the
685
+ * `data-*` attributes, so every write travels as an `attr` record.
686
+ */
687
+ function createDataset(el) {
688
+ return new Proxy({}, {
689
+ get: (_t, key) => typeof key === "string" ? el.getAttribute(dataAttr(key)) ?? void 0 : void 0,
690
+ set(_t, key, value) {
691
+ if (typeof key !== "string") return false;
692
+ el.setAttribute(dataAttr(key), value);
693
+ return true;
694
+ },
695
+ deleteProperty(_t, key) {
696
+ if (typeof key === "string") el.removeAttribute(dataAttr(key));
697
+ return true;
698
+ },
699
+ has: (_t, key) => typeof key === "string" && el.hasAttribute(dataAttr(key)),
700
+ ownKeys: () => [...el.isoAttrs.keys()].filter((n) => n.startsWith("data-")).map(dataKey),
701
+ getOwnPropertyDescriptor(_t, key) {
702
+ if (typeof key !== "string" || !el.hasAttribute(dataAttr(key))) return void 0;
703
+ return {
704
+ value: el.getAttribute(dataAttr(key)),
705
+ writable: true,
706
+ enumerable: true,
707
+ configurable: true
708
+ };
709
+ }
710
+ });
711
+ }
712
+ function defineHandlers(proto) {
713
+ const handlers = /* @__PURE__ */ new WeakMap();
714
+ for (const type of HANDLER_EVENTS) Object.defineProperty(proto, `on${type}`, {
715
+ configurable: true,
716
+ enumerable: true,
717
+ get() {
718
+ return handlers.get(this)?.get(type) ?? null;
719
+ },
720
+ set(fn) {
721
+ const own = handlers.get(this) ?? /* @__PURE__ */ new Map();
722
+ handlers.set(this, own);
723
+ const old = own.get(type);
724
+ if (old) this.removeEventListener(type, old);
725
+ if (typeof fn === "function") {
726
+ const handler = (e) => {
727
+ Reflect.apply(fn, this, [e]);
728
+ };
729
+ own.set(type, handler);
730
+ this.addEventListener(type, handler);
731
+ } else own.delete(type);
732
+ }
733
+ });
734
+ }
735
+ /** The subtree as `insert` sends it. */
736
+ function serialize(n) {
737
+ if (n instanceof WText) return {
738
+ k: "text",
739
+ id: n.isoId,
740
+ data: n.isoData
741
+ };
742
+ if (n instanceof WComment) return {
743
+ k: "comment",
744
+ id: n.isoId,
745
+ data: n.isoData
746
+ };
747
+ if (!(n instanceof WElement)) throw new TypeError("serialize: unknown node");
748
+ return {
749
+ k: "el",
750
+ id: n.isoId,
751
+ tag: n.localName,
752
+ ns: n.isoNs,
753
+ attrs: [...n.isoAttrs],
754
+ props: [...n.isoProps],
755
+ listen: [...n.isoListeners.keys()],
756
+ children: n.childNodes.map(serialize)
757
+ };
758
+ }
759
+ /** Whether `n` or anything under it was rendered under a root other than `owner`. */
760
+ function ownedElsewhere(n, owner) {
761
+ if (n.isoOwner && n.isoOwner !== owner) return true;
762
+ return !n.isoKnown && n.childNodes.some((c) => ownedElsewhere(c, owner));
763
+ }
764
+ function learn(n, core, owner) {
765
+ n.isoKnown = true;
766
+ n.isoOwner = owner;
767
+ core.known.set(n.isoId, n);
768
+ for (const c of n.childNodes) learn(c, core, owner);
769
+ }
770
+ function forget(n, core) {
771
+ n.isoKnown = false;
772
+ core.known.delete(n.isoId);
773
+ for (const c of n.childNodes) forget(c, core);
774
+ }
775
+ function setValueOf(node, value, o) {
776
+ if (!isControl(node)) throw new TypeError("setValue: not an input, textarea or select");
777
+ if (!o.force) {
778
+ node.value = value;
779
+ return;
780
+ }
781
+ node.isoSetProp("value", value, false);
782
+ if (node.isoKnown) emit(node, [
783
+ "prop",
784
+ node.isoWire,
785
+ "value",
786
+ value,
787
+ true
788
+ ]);
789
+ }
790
+ function deliverTo(node, event) {
791
+ if (!node) return;
792
+ if (isControl(node) && event.value !== void 0) node.isoSetProp("value", event.value, false);
793
+ if (node instanceof WHTMLInputElement && event.checked !== void 0) node.isoSetProp("checked", event.checked, false);
794
+ if (event.type === "scroll" && node instanceof WElement) node.isoScroll = {
795
+ top: event.scrollTop ?? 0,
796
+ left: event.scrollLeft ?? 0
797
+ };
798
+ node.dispatchEvent(toEvent(event));
799
+ }
800
+ /** A root's recorder: records batched per microtask (or `schedule`) into `onBatch`. */
801
+ function recorder(root, onBatch, schedule) {
802
+ let pending = [];
803
+ let scheduled = false;
804
+ let live = true;
805
+ const flush = () => {
806
+ scheduled = false;
807
+ if (pending.length === 0) return;
808
+ const batch = pending;
809
+ pending = [];
810
+ if (live) onBatch(batch);
811
+ };
812
+ return {
813
+ owner: {
814
+ root,
815
+ push(r) {
816
+ if (!live) return;
817
+ pending.push(r);
818
+ if (!scheduled) {
819
+ scheduled = true;
820
+ schedule(flush);
821
+ }
822
+ }
823
+ },
824
+ flush,
825
+ stop: () => {
826
+ live = false;
827
+ pending = [];
828
+ }
829
+ };
830
+ }
831
+ function createDom(opts) {
832
+ const schedule = opts.schedule ?? ((fn) => queueMicrotask(fn));
833
+ const core = {
834
+ roots: /* @__PURE__ */ new Set(),
835
+ nextId: 1,
836
+ known: /* @__PURE__ */ new Map(),
837
+ onHead: opts.onHead ?? (() => {})
838
+ };
839
+ const document = new WDocument(core);
840
+ const makeRoot = (id) => {
841
+ const root = new WHTMLElement(document, id, "iso-root", "html");
842
+ root.isoKnown = true;
843
+ core.known.set(id, root);
844
+ core.roots.add(root);
845
+ return root;
846
+ };
847
+ const root = makeRoot(0);
848
+ const main = recorder(root, (b) => opts.onBatch(b), schedule);
849
+ root.isoOwner = main.owner;
850
+ return {
851
+ document,
852
+ root,
853
+ flush: main.flush,
854
+ idOf: (node) => node.isoId,
855
+ setValue: (node, value, o = {}) => setValueOf(node, value, o),
856
+ deliver: (event) => deliverTo(core.known.get(event.target), event),
857
+ addRoot(o) {
858
+ const member = makeRoot(core.nextId++);
859
+ const rec = recorder(member, (b) => o.onBatch(b), o.schedule ?? schedule);
860
+ member.isoOwner = rec.owner;
861
+ const mine = (node) => node?.isoKnown && node.isoOwner === rec.owner ? node : void 0;
862
+ return {
863
+ root: member,
864
+ flush: rec.flush,
865
+ idOf: (node) => mine(node) ? node.isoWire : void 0,
866
+ setValue(node, value, so = {}) {
867
+ if (node.isoOwner && node.isoOwner !== rec.owner) throw new TypeError("setValue: not a node of this member's root");
868
+ setValueOf(node, value, so);
869
+ },
870
+ deliver: (event) => deliverTo(mine(event.target === 0 ? member : core.known.get(event.target)), event),
871
+ dispose() {
872
+ rec.stop();
873
+ core.roots.delete(member);
874
+ forget(member, core);
875
+ }
876
+ };
877
+ }
878
+ };
879
+ }
880
+ /** A real `Event` with the fields frameworks read from mouse and keyboard events. */
881
+ function toEvent(e) {
882
+ const ev = new Event(e.type, {
883
+ bubbles: e.type !== "scroll",
884
+ cancelable: true
885
+ });
886
+ const mods = {
887
+ Alt: e.mods.alt,
888
+ Control: e.mods.ctrl,
889
+ Meta: e.mods.meta,
890
+ Shift: e.mods.shift
891
+ };
892
+ Object.defineProperties(ev, {
893
+ altKey: { value: e.mods.alt },
894
+ ctrlKey: { value: e.mods.ctrl },
895
+ metaKey: { value: e.mods.meta },
896
+ shiftKey: { value: e.mods.shift },
897
+ getModifierState: { value: (k) => mods[k] ?? false },
898
+ key: { value: e.key },
899
+ code: { value: e.code },
900
+ button: { value: e.button ?? 0 },
901
+ clientX: { value: e.x ?? 0 },
902
+ clientY: { value: e.y ?? 0 },
903
+ width: { value: e.width },
904
+ height: { value: e.height }
905
+ });
906
+ return ev;
907
+ }
908
+ var HTML_NS, SVG_NS, str, domError, emit, WEventTarget, WNode, WCharacterData, WText, WComment, kebab, WDOMTokenList, dataAttr, dataKey, WParentNode, WDocumentFragment, WElement, HANDLER_EVENTS, WHTMLElement, WSVGElement, WHTMLIFrameElement, WHTMLInputElement, WHTMLTextAreaElement, WHTMLSelectElement, WHTMLOptionElement, HTML_CLASSES, WDocument, isControl;
909
+ var init_dom_yLsf0Z4e = __esmMin((() => {
910
+ HTML_NS = "http://www.w3.org/1999/xhtml";
911
+ SVG_NS = "http://www.w3.org/2000/svg";
912
+ str = (v) => typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" || typeof v === "bigint" ? String(v) : "";
913
+ domError = (name, message) => {
914
+ const e = new Error(message);
915
+ e.name = name;
916
+ return e;
917
+ };
918
+ emit = (n, r) => {
919
+ n.isoOwner?.push(r);
920
+ };
921
+ WEventTarget = class {
922
+ /** @internal */ isoListeners = /* @__PURE__ */ new Map();
923
+ /** @internal */ isoParentTarget() {
924
+ return null;
925
+ }
926
+ /** @internal Called when the first listener of `type` is added, or the last removed. */
927
+ isoListenChanged(_type, _on) {}
928
+ addEventListener(type, fn, options) {
929
+ if (!fn) return;
930
+ const capture = typeof options === "boolean" ? options : Boolean(options?.capture);
931
+ const once = typeof options === "object" && Boolean(options.once);
932
+ const list = this.isoListeners.get(type) ?? [];
933
+ if (list.some((l) => l.fn === fn && l.capture === capture)) return;
934
+ list.push({
935
+ fn,
936
+ capture,
937
+ once
938
+ });
939
+ this.isoListeners.set(type, list);
940
+ if (list.length === 1) this.isoListenChanged(type, true);
941
+ }
942
+ removeEventListener(type, fn, options) {
943
+ const capture = typeof options === "boolean" ? options : Boolean(options?.capture);
944
+ const list = this.isoListeners.get(type);
945
+ if (!list) return;
946
+ const i = list.findIndex((l) => l.fn === fn && l.capture === capture);
947
+ if (i < 0) return;
948
+ list.splice(i, 1);
949
+ if (list.length === 0) {
950
+ this.isoListeners.delete(type);
951
+ this.isoListenChanged(type, false);
952
+ }
953
+ }
954
+ /** Capture from the top, then the target, then bubble (if `bubbles`). */
955
+ dispatchEvent(event) {
956
+ const path = [this];
957
+ for (let t = this.isoParentTarget(); t; t = t.isoParentTarget()) path.push(t);
958
+ let stopped = false;
959
+ let stoppedNow = false;
960
+ const stop = event.stopPropagation.bind(event);
961
+ const stopNow = event.stopImmediatePropagation.bind(event);
962
+ Object.defineProperties(event, {
963
+ target: {
964
+ value: this,
965
+ configurable: true
966
+ },
967
+ srcElement: {
968
+ value: this,
969
+ configurable: true
970
+ },
971
+ stopPropagation: {
972
+ value: () => {
973
+ stopped = true;
974
+ stop();
975
+ },
976
+ configurable: true
977
+ },
978
+ stopImmediatePropagation: {
979
+ value: () => {
980
+ stopped = true;
981
+ stoppedNow = true;
982
+ stopNow();
983
+ },
984
+ configurable: true
985
+ },
986
+ composedPath: {
987
+ value: () => path.slice(),
988
+ configurable: true
989
+ }
990
+ });
991
+ const invoke = (t, phase, capture) => {
992
+ Object.defineProperties(event, {
993
+ currentTarget: {
994
+ value: t,
995
+ configurable: true
996
+ },
997
+ eventPhase: {
998
+ value: phase,
999
+ configurable: true
1000
+ }
1001
+ });
1002
+ for (const l of (t.isoListeners.get(event.type) ?? []).slice()) {
1003
+ if (capture !== null && l.capture !== capture) continue;
1004
+ if (l.once) t.removeEventListener(event.type, l.fn, l.capture);
1005
+ if (typeof l.fn === "function") l.fn.call(t, event);
1006
+ else l.fn.handleEvent(event);
1007
+ if (stoppedNow) return;
1008
+ }
1009
+ };
1010
+ const phases = [];
1011
+ for (let i = path.length - 1; i > 0; i--) {
1012
+ const t = path[i];
1013
+ if (t) phases.push([
1014
+ t,
1015
+ 1,
1016
+ true
1017
+ ]);
1018
+ }
1019
+ phases.push([
1020
+ this,
1021
+ 2,
1022
+ null
1023
+ ]);
1024
+ if (event.bubbles) for (const t of path.slice(1)) phases.push([
1025
+ t,
1026
+ 3,
1027
+ false
1028
+ ]);
1029
+ for (const [t, phase, capture] of phases) {
1030
+ if (stopped) break;
1031
+ invoke(t, phase, capture);
1032
+ }
1033
+ Object.defineProperties(event, {
1034
+ currentTarget: {
1035
+ value: null,
1036
+ configurable: true
1037
+ },
1038
+ eventPhase: {
1039
+ value: 0,
1040
+ configurable: true
1041
+ }
1042
+ });
1043
+ return !event.defaultPrevented;
1044
+ }
1045
+ };
1046
+ WNode = class extends WEventTarget {
1047
+ static ELEMENT_NODE = 1;
1048
+ static TEXT_NODE = 3;
1049
+ static COMMENT_NODE = 8;
1050
+ static DOCUMENT_NODE = 9;
1051
+ static DOCUMENT_FRAGMENT_NODE = 11;
1052
+ ELEMENT_NODE = 1;
1053
+ TEXT_NODE = 3;
1054
+ COMMENT_NODE = 8;
1055
+ DOCUMENT_FRAGMENT_NODE = 11;
1056
+ ownerDocument;
1057
+ /** @internal */ isoId;
1058
+ /** @internal */ isoParent = null;
1059
+ /** @internal */ isoPrev = null;
1060
+ /** @internal */ isoNext = null;
1061
+ /** @internal Whether the host knows this node (it's in the tree under the root). */
1062
+ isoKnown = false;
1063
+ /**
1064
+ * @internal The root this node was rendered under, once it has been. Kept
1065
+ * after the node leaves the tree, so it can't move to another member's root
1066
+ * in a pool (ADR 0015, decision 3).
1067
+ */
1068
+ isoOwner = null;
1069
+ constructor(doc, id) {
1070
+ super();
1071
+ this.ownerDocument = doc;
1072
+ this.isoId = id;
1073
+ }
1074
+ /** @internal */ isoParentTarget() {
1075
+ return this.isoParent;
1076
+ }
1077
+ /**
1078
+ * @internal The id the host knows this node by: a render root is always
1079
+ * `ROOT_ID` to its own surface, whatever its id in the document.
1080
+ */
1081
+ get isoWire() {
1082
+ return this.isoOwner?.root === this ? 0 : this.isoId;
1083
+ }
1084
+ /** @internal */ isoListenChanged(type, on) {
1085
+ if (this.isoKnown) emit(this, [
1086
+ "listen",
1087
+ this.isoWire,
1088
+ type,
1089
+ on
1090
+ ]);
1091
+ }
1092
+ get parentNode() {
1093
+ return this.isoParent;
1094
+ }
1095
+ get parentElement() {
1096
+ return this.isoParent instanceof WElement ? this.isoParent : null;
1097
+ }
1098
+ get nextSibling() {
1099
+ return this.isoNext;
1100
+ }
1101
+ get previousSibling() {
1102
+ return this.isoPrev;
1103
+ }
1104
+ get firstChild() {
1105
+ return null;
1106
+ }
1107
+ get lastChild() {
1108
+ return null;
1109
+ }
1110
+ get childNodes() {
1111
+ return [];
1112
+ }
1113
+ get isConnected() {
1114
+ return this.isoKnown;
1115
+ }
1116
+ hasChildNodes() {
1117
+ return this.firstChild !== null;
1118
+ }
1119
+ contains(other) {
1120
+ for (let n = other; n; n = n.isoParent) if (n === this) return true;
1121
+ return false;
1122
+ }
1123
+ remove() {
1124
+ this.isoParent?.removeChild(this);
1125
+ }
1126
+ };
1127
+ WCharacterData = class extends WNode {
1128
+ /** @internal */ isoData;
1129
+ constructor(doc, id, data) {
1130
+ super(doc, id);
1131
+ this.isoData = data;
1132
+ }
1133
+ get data() {
1134
+ return this.isoData;
1135
+ }
1136
+ set data(v) {
1137
+ const data = str(v);
1138
+ if (data === this.isoData) return;
1139
+ this.isoData = data;
1140
+ if (this.isoKnown) emit(this, [
1141
+ "text",
1142
+ this.isoWire,
1143
+ data
1144
+ ]);
1145
+ }
1146
+ get length() {
1147
+ return this.isoData.length;
1148
+ }
1149
+ get textContent() {
1150
+ return this.isoData;
1151
+ }
1152
+ set textContent(v) {
1153
+ this.data = v ?? "";
1154
+ }
1155
+ get nodeValue() {
1156
+ return this.isoData;
1157
+ }
1158
+ set nodeValue(v) {
1159
+ this.data = v ?? "";
1160
+ }
1161
+ };
1162
+ WText = class extends WCharacterData {
1163
+ nodeType = 3;
1164
+ nodeName = "#text";
1165
+ };
1166
+ WComment = class extends WCharacterData {
1167
+ nodeType = 8;
1168
+ nodeName = "#comment";
1169
+ };
1170
+ kebab = (name) => name.startsWith("--") ? name : name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
1171
+ WDOMTokenList = class {
1172
+ /** @internal */ isoEl;
1173
+ constructor(el) {
1174
+ this.isoEl = el;
1175
+ }
1176
+ /** @internal */ isoTokens() {
1177
+ const tokens = [];
1178
+ for (const t of (this.isoEl.getAttribute("class") ?? "").split(/[\t\n\f\r ]+/)) if (t !== "" && !tokens.includes(t)) tokens.push(t);
1179
+ return tokens;
1180
+ }
1181
+ /** @internal */ isoWrite(tokens) {
1182
+ this.isoEl.setAttribute("class", tokens.join(" "));
1183
+ }
1184
+ get length() {
1185
+ return this.isoTokens().length;
1186
+ }
1187
+ get value() {
1188
+ return this.isoEl.getAttribute("class") ?? "";
1189
+ }
1190
+ set value(v) {
1191
+ this.isoEl.setAttribute("class", v);
1192
+ }
1193
+ item(i) {
1194
+ return this.isoTokens()[i] ?? null;
1195
+ }
1196
+ contains(token) {
1197
+ return this.isoTokens().includes(token);
1198
+ }
1199
+ add(...tokens) {
1200
+ const list = this.isoTokens();
1201
+ for (const t of tokens) if (!list.includes(t)) list.push(t);
1202
+ this.isoWrite(list);
1203
+ }
1204
+ remove(...tokens) {
1205
+ this.isoWrite(this.isoTokens().filter((t) => !tokens.includes(t)));
1206
+ }
1207
+ toggle(token, force) {
1208
+ const has = this.contains(token);
1209
+ const on = force ?? !has;
1210
+ if (on && !has) this.add(token);
1211
+ else if (!on && has) this.remove(token);
1212
+ return on;
1213
+ }
1214
+ replace(token, next) {
1215
+ const list = this.isoTokens();
1216
+ const i = list.indexOf(token);
1217
+ if (i < 0) return false;
1218
+ list[i] = next;
1219
+ this.isoWrite(list.filter((t, j) => list.indexOf(t) === j));
1220
+ return true;
1221
+ }
1222
+ toString() {
1223
+ return this.value;
1224
+ }
1225
+ [Symbol.iterator]() {
1226
+ return this.isoTokens()[Symbol.iterator]();
1227
+ }
1228
+ };
1229
+ dataAttr = (key) => `data-${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;
1230
+ dataKey = (attr) => attr.slice(5).replace(/-([a-z])/g, (_m, c) => c.toUpperCase());
1231
+ WParentNode = class extends WNode {
1232
+ /** @internal */ isoFirst = null;
1233
+ /** @internal */ isoLast = null;
1234
+ /** @internal */ isoChildCache = null;
1235
+ get firstChild() {
1236
+ return this.isoFirst;
1237
+ }
1238
+ get lastChild() {
1239
+ return this.isoLast;
1240
+ }
1241
+ get childNodes() {
1242
+ if (!this.isoChildCache) {
1243
+ const list = [];
1244
+ for (let n = this.isoFirst; n; n = n.isoNext) list.push(n);
1245
+ this.isoChildCache = list;
1246
+ }
1247
+ return this.isoChildCache;
1248
+ }
1249
+ get children() {
1250
+ return this.childNodes.filter((n) => n instanceof WElement);
1251
+ }
1252
+ get firstElementChild() {
1253
+ return this.children[0] ?? null;
1254
+ }
1255
+ /** Text of the subtree; comments don't count, as in the DOM. */
1256
+ get textContent() {
1257
+ let out = "";
1258
+ for (let n = this.isoFirst; n; n = n.isoNext) if (!(n instanceof WComment)) out += n.textContent;
1259
+ return out;
1260
+ }
1261
+ set textContent(v) {
1262
+ this.replaceChildren(...v ? [this.ownerDocument.createTextNode(v)] : []);
1263
+ }
1264
+ appendChild(child) {
1265
+ return this.insertBefore(child, null);
1266
+ }
1267
+ insertBefore(child, ref) {
1268
+ if (!(child instanceof WNode)) throw new TypeError("insertBefore: not a node");
1269
+ if (ref && ref.isoParent !== this) throw domError("NotFoundError", "insertBefore: the reference node is not a child");
1270
+ if (child.contains(this)) throw domError("HierarchyRequestError", "insertBefore: would create a cycle");
1271
+ if (ref === child) ref = child.isoNext;
1272
+ if (child instanceof WDocumentFragment) {
1273
+ for (const c of child.childNodes) this.insertBefore(c, ref);
1274
+ return child;
1275
+ }
1276
+ if (this.ownerDocument.head === this && child instanceof WElement) this.ownerDocument.isoCore.onHead(child.localName);
1277
+ if (this.isoKnown && ownedElsewhere(child, this.isoOwner)) throw domError("HierarchyRequestError", "insertBefore: a node can't move to another member's root in a pool");
1278
+ const wasKnown = child.isoKnown;
1279
+ child.isoParent?.isoUnlink(child);
1280
+ this.isoLink(child, ref);
1281
+ const core = this.ownerDocument.isoCore;
1282
+ if (wasKnown && this.isoKnown) emit(this, [
1283
+ "move",
1284
+ this.isoWire,
1285
+ child.isoId,
1286
+ ref?.isoId ?? null
1287
+ ]);
1288
+ else if (wasKnown) {
1289
+ emit(child, ["remove", child.isoId]);
1290
+ forget(child, core);
1291
+ } else if (this.isoKnown) {
1292
+ emit(this, [
1293
+ "insert",
1294
+ this.isoWire,
1295
+ serialize(child),
1296
+ ref?.isoId ?? null
1297
+ ]);
1298
+ learn(child, core, this.isoOwner);
1299
+ }
1300
+ return child;
1301
+ }
1302
+ removeChild(child) {
1303
+ if (child.isoParent !== this) throw domError("NotFoundError", "removeChild: not a child");
1304
+ this.isoUnlink(child);
1305
+ if (child.isoKnown) {
1306
+ emit(child, ["remove", child.isoId]);
1307
+ forget(child, this.ownerDocument.isoCore);
1308
+ }
1309
+ return child;
1310
+ }
1311
+ replaceChildren(...nodes) {
1312
+ while (this.isoLast) this.removeChild(this.isoLast);
1313
+ this.append(...nodes);
1314
+ }
1315
+ append(...nodes) {
1316
+ for (const n of nodes) this.appendChild(typeof n === "string" ? this.ownerDocument.createTextNode(n) : n);
1317
+ }
1318
+ /** @internal */ isoUnlink(child) {
1319
+ if (child.isoPrev) child.isoPrev.isoNext = child.isoNext;
1320
+ else this.isoFirst = child.isoNext;
1321
+ if (child.isoNext) child.isoNext.isoPrev = child.isoPrev;
1322
+ else this.isoLast = child.isoPrev;
1323
+ child.isoParent = null;
1324
+ child.isoPrev = null;
1325
+ child.isoNext = null;
1326
+ this.isoChildCache = null;
1327
+ }
1328
+ /** @internal */ isoLink(child, ref) {
1329
+ child.isoParent = this;
1330
+ child.isoNext = ref;
1331
+ child.isoPrev = ref ? ref.isoPrev : this.isoLast;
1332
+ if (child.isoPrev) child.isoPrev.isoNext = child;
1333
+ else this.isoFirst = child;
1334
+ if (ref) ref.isoPrev = child;
1335
+ else this.isoLast = child;
1336
+ this.isoChildCache = null;
1337
+ }
1338
+ };
1339
+ WDocumentFragment = class extends WParentNode {
1340
+ nodeType = 11;
1341
+ nodeName = "#document-fragment";
1342
+ get nodeValue() {
1343
+ return null;
1344
+ }
1345
+ set nodeValue(_v) {}
1346
+ };
1347
+ WElement = class extends WParentNode {
1348
+ nodeType = 1;
1349
+ localName;
1350
+ namespaceURI;
1351
+ /** @internal */ isoNs;
1352
+ /** @internal */ isoAttrs = /* @__PURE__ */ new Map();
1353
+ /** @internal */ isoProps = /* @__PURE__ */ new Map();
1354
+ /** @internal */ isoStyle = null;
1355
+ /** @internal */ isoClassList = null;
1356
+ /** @internal */ isoDataset = null;
1357
+ /** @internal The offsets the last `scroll` event brought (design §4.6). */
1358
+ isoScroll = {
1359
+ top: 0,
1360
+ left: 0
1361
+ };
1362
+ constructor(doc, id, localName, ns) {
1363
+ super(doc, id);
1364
+ this.localName = localName;
1365
+ this.isoNs = ns;
1366
+ this.namespaceURI = ns === "svg" ? SVG_NS : HTML_NS;
1367
+ }
1368
+ get tagName() {
1369
+ return this.isoNs === "html" ? this.localName.toUpperCase() : this.localName;
1370
+ }
1371
+ get nodeName() {
1372
+ return this.tagName;
1373
+ }
1374
+ get nodeValue() {
1375
+ return null;
1376
+ }
1377
+ set nodeValue(_v) {}
1378
+ get attributes() {
1379
+ return [...this.isoAttrs].map(([name, value]) => ({
1380
+ name,
1381
+ value
1382
+ }));
1383
+ }
1384
+ getAttribute(name) {
1385
+ return this.isoAttrs.get(this.isoAttrName(name)) ?? null;
1386
+ }
1387
+ hasAttribute(name) {
1388
+ return this.isoAttrs.has(this.isoAttrName(name));
1389
+ }
1390
+ setAttribute(name, value) {
1391
+ const n = this.isoAttrName(name);
1392
+ const v = str(value);
1393
+ if (this.isoAttrs.get(n) === v) return;
1394
+ this.isoAttrs.set(n, v);
1395
+ if (this.isoKnown) emit(this, [
1396
+ "attr",
1397
+ this.isoWire,
1398
+ n,
1399
+ v
1400
+ ]);
1401
+ }
1402
+ removeAttribute(name) {
1403
+ const n = this.isoAttrName(name);
1404
+ if (!this.isoAttrs.delete(n)) return;
1405
+ if (this.isoKnown) emit(this, [
1406
+ "attr",
1407
+ this.isoWire,
1408
+ n,
1409
+ null
1410
+ ]);
1411
+ }
1412
+ /** @internal HTML attribute names are case-insensitive; SVG ones aren't. */
1413
+ isoAttrName(name) {
1414
+ return this.isoNs === "html" ? name.toLowerCase() : name;
1415
+ }
1416
+ get style() {
1417
+ this.isoStyle ??= createStyle(this);
1418
+ return this.isoStyle;
1419
+ }
1420
+ get classList() {
1421
+ this.isoClassList ??= new WDOMTokenList(this);
1422
+ return this.isoClassList;
1423
+ }
1424
+ get dataset() {
1425
+ this.isoDataset ??= createDataset(this);
1426
+ return this.isoDataset;
1427
+ }
1428
+ /**
1429
+ * Read only, and as of the last `scroll` event the element got: the host
1430
+ * owns scrolling. 0 until the element is scrolled and listens for `scroll`.
1431
+ */
1432
+ get scrollTop() {
1433
+ return this.isoScroll.top;
1434
+ }
1435
+ get scrollLeft() {
1436
+ return this.isoScroll.left;
1437
+ }
1438
+ get id() {
1439
+ return this.getAttribute("id") ?? "";
1440
+ }
1441
+ set id(v) {
1442
+ this.setAttribute("id", v);
1443
+ }
1444
+ /** @internal */ isoSetProp(name, value, record) {
1445
+ if (this.isoProps.get(name) === value) return;
1446
+ this.isoProps.set(name, value);
1447
+ if (record && this.isoKnown) emit(this, [
1448
+ "prop",
1449
+ this.isoWire,
1450
+ name,
1451
+ value
1452
+ ]);
1453
+ }
1454
+ };
1455
+ HANDLER_EVENTS = [
1456
+ "abort",
1457
+ "animationend",
1458
+ "animationiteration",
1459
+ "animationstart",
1460
+ "auxclick",
1461
+ "beforeinput",
1462
+ "blur",
1463
+ "cancel",
1464
+ "change",
1465
+ "click",
1466
+ "close",
1467
+ "contextmenu",
1468
+ "copy",
1469
+ "cut",
1470
+ "dblclick",
1471
+ "drag",
1472
+ "dragend",
1473
+ "dragenter",
1474
+ "dragleave",
1475
+ "dragover",
1476
+ "dragstart",
1477
+ "drop",
1478
+ "error",
1479
+ "focus",
1480
+ "input",
1481
+ "invalid",
1482
+ "keydown",
1483
+ "keypress",
1484
+ "keyup",
1485
+ "load",
1486
+ "mousedown",
1487
+ "mouseenter",
1488
+ "mouseleave",
1489
+ "mousemove",
1490
+ "mouseout",
1491
+ "mouseover",
1492
+ "mouseup",
1493
+ "paste",
1494
+ "pointercancel",
1495
+ "pointerdown",
1496
+ "pointerenter",
1497
+ "pointerleave",
1498
+ "pointermove",
1499
+ "pointerout",
1500
+ "pointerover",
1501
+ "pointerup",
1502
+ "reset",
1503
+ "resize",
1504
+ "scroll",
1505
+ "select",
1506
+ "submit",
1507
+ "toggle",
1508
+ "touchcancel",
1509
+ "touchend",
1510
+ "touchmove",
1511
+ "touchstart",
1512
+ "transitionend",
1513
+ "wheel"
1514
+ ];
1515
+ defineHandlers(WElement.prototype);
1516
+ WHTMLElement = class extends WElement {};
1517
+ WSVGElement = class extends WElement {};
1518
+ WHTMLIFrameElement = class extends WHTMLElement {};
1519
+ WHTMLInputElement = class extends WHTMLElement {
1520
+ get value() {
1521
+ const v = this.isoProps.get("value");
1522
+ return typeof v === "string" ? v : this.getAttribute("value") ?? "";
1523
+ }
1524
+ set value(v) {
1525
+ this.isoSetProp("value", str(v), true);
1526
+ }
1527
+ get checked() {
1528
+ const v = this.isoProps.get("checked");
1529
+ return typeof v === "boolean" ? v : this.hasAttribute("checked");
1530
+ }
1531
+ set checked(v) {
1532
+ this.isoSetProp("checked", Boolean(v), true);
1533
+ }
1534
+ get defaultValue() {
1535
+ return this.getAttribute("value") ?? "";
1536
+ }
1537
+ set defaultValue(v) {
1538
+ this.setAttribute("value", v);
1539
+ }
1540
+ get defaultChecked() {
1541
+ return this.hasAttribute("checked");
1542
+ }
1543
+ set defaultChecked(v) {
1544
+ if (v) this.setAttribute("checked", "");
1545
+ else this.removeAttribute("checked");
1546
+ }
1547
+ get name() {
1548
+ return this.getAttribute("name") ?? "";
1549
+ }
1550
+ set name(v) {
1551
+ this.setAttribute("name", v);
1552
+ }
1553
+ get type() {
1554
+ return this.getAttribute("type") ?? "text";
1555
+ }
1556
+ set type(v) {
1557
+ this.setAttribute("type", v);
1558
+ }
1559
+ };
1560
+ WHTMLTextAreaElement = class extends WHTMLElement {
1561
+ get value() {
1562
+ const v = this.isoProps.get("value");
1563
+ return typeof v === "string" ? v : this.textContent;
1564
+ }
1565
+ set value(v) {
1566
+ this.isoSetProp("value", str(v), true);
1567
+ }
1568
+ get defaultValue() {
1569
+ return this.textContent;
1570
+ }
1571
+ set defaultValue(v) {
1572
+ this.textContent = v;
1573
+ }
1574
+ get name() {
1575
+ return this.getAttribute("name") ?? "";
1576
+ }
1577
+ set name(v) {
1578
+ this.setAttribute("name", v);
1579
+ }
1580
+ };
1581
+ WHTMLSelectElement = class extends WHTMLElement {
1582
+ /** The `<option>`s under the select, `<optgroup>`s included, in tree order. React walks it. */
1583
+ get options() {
1584
+ const out = [];
1585
+ const walk = (el) => {
1586
+ for (const c of el.children) if (c instanceof WHTMLOptionElement) out.push(c);
1587
+ else if (c.localName === "optgroup") walk(c);
1588
+ };
1589
+ walk(this);
1590
+ return out;
1591
+ }
1592
+ get multiple() {
1593
+ return this.hasAttribute("multiple");
1594
+ }
1595
+ set multiple(v) {
1596
+ if (v) this.setAttribute("multiple", "");
1597
+ else this.removeAttribute("multiple");
1598
+ }
1599
+ get value() {
1600
+ const v = this.isoProps.get("value");
1601
+ return typeof v === "string" ? v : "";
1602
+ }
1603
+ set value(v) {
1604
+ this.isoSetProp("value", str(v), true);
1605
+ }
1606
+ get name() {
1607
+ return this.getAttribute("name") ?? "";
1608
+ }
1609
+ set name(v) {
1610
+ this.setAttribute("name", v);
1611
+ }
1612
+ };
1613
+ WHTMLOptionElement = class extends WHTMLElement {
1614
+ /** The `value` attribute, or the text when there's none, as in the DOM. */
1615
+ get value() {
1616
+ return this.getAttribute("value") ?? this.textContent;
1617
+ }
1618
+ set value(v) {
1619
+ this.setAttribute("value", v);
1620
+ }
1621
+ get selected() {
1622
+ const v = this.isoProps.get("selected");
1623
+ return typeof v === "boolean" ? v : this.hasAttribute("selected");
1624
+ }
1625
+ set selected(v) {
1626
+ this.isoSetProp("selected", Boolean(v), true);
1627
+ }
1628
+ get defaultSelected() {
1629
+ return this.hasAttribute("selected");
1630
+ }
1631
+ set defaultSelected(v) {
1632
+ if (v) this.setAttribute("selected", "");
1633
+ else this.removeAttribute("selected");
1634
+ }
1635
+ get disabled() {
1636
+ return this.hasAttribute("disabled");
1637
+ }
1638
+ set disabled(v) {
1639
+ if (v) this.setAttribute("disabled", "");
1640
+ else this.removeAttribute("disabled");
1641
+ }
1642
+ };
1643
+ HTML_CLASSES = {
1644
+ input: WHTMLInputElement,
1645
+ textarea: WHTMLTextAreaElement,
1646
+ select: WHTMLSelectElement,
1647
+ option: WHTMLOptionElement,
1648
+ iframe: WHTMLIFrameElement
1649
+ };
1650
+ WDocument = class extends WEventTarget {
1651
+ nodeType = 9;
1652
+ nodeName = "#document";
1653
+ /** @internal */ isoCore;
1654
+ /** Set by `install()`: the worker global. */
1655
+ defaultView = null;
1656
+ activeElement = null;
1657
+ /** `null`, as for every document. */
1658
+ ownerDocument = null;
1659
+ /** A detached body, for code that falls back to `document.body`. */
1660
+ body;
1661
+ /**
1662
+ * A detached head: React 19 hoists `<title>`, `<meta>` and `<link>` into
1663
+ * it. The bridge doesn't render it (M3a task 3).
1664
+ */
1665
+ head;
1666
+ constructor(core) {
1667
+ super();
1668
+ this.isoCore = core;
1669
+ this.body = new WHTMLElement(this, -1, "body", "html");
1670
+ this.head = new WHTMLElement(this, -2, "head", "html");
1671
+ }
1672
+ createElement(tag) {
1673
+ const t = tag.toLowerCase();
1674
+ return new ((Object.hasOwn(HTML_CLASSES, t) ? HTML_CLASSES[t] : void 0) ?? WHTMLElement)(this, this.isoCore.nextId++, t, "html");
1675
+ }
1676
+ createElementNS(ns, tag) {
1677
+ if (ns === SVG_NS) return new WSVGElement(this, this.isoCore.nextId++, tag, "svg");
1678
+ if (ns === HTML_NS || ns === null) return this.createElement(tag);
1679
+ throw domError("NotSupportedError", `createElementNS: namespace ${ns} isn't supported`);
1680
+ }
1681
+ /** `data` is converted with `String()`, as in the DOM: Preact passes numbers. */
1682
+ createTextNode(data) {
1683
+ return new WText(this, this.isoCore.nextId++, String(data));
1684
+ }
1685
+ createComment(data) {
1686
+ return new WComment(this, this.isoCore.nextId++, String(data));
1687
+ }
1688
+ /** Fragments never reach the host, so they take no id from the shared counter. */
1689
+ createDocumentFragment() {
1690
+ return new WDocumentFragment(this, -3);
1691
+ }
1692
+ /**
1693
+ * The first element in tree order with this `id` (DOM group 1, ADR 0010):
1694
+ * under the render root, then the detached head. Nodes not yet inserted
1695
+ * aren't in the document, so they aren't found.
1696
+ */
1697
+ getElementById(id) {
1698
+ const walk = (el) => {
1699
+ for (const c of el.children) {
1700
+ if (c.getAttribute("id") === id) return c;
1701
+ const deeper = walk(c);
1702
+ if (deeper) return deeper;
1703
+ }
1704
+ return null;
1705
+ };
1706
+ for (const root of this.isoCore.roots) {
1707
+ const hit = walk(root);
1708
+ if (hit) return hit;
1709
+ }
1710
+ return walk(this.head);
1711
+ }
1712
+ /**
1713
+ * Type selectors only, alone or as a `head > title` child chain: what React
1714
+ * 19 asks when it hoists a `<title>`. Queries in general are DOM group 2
1715
+ * (ADR 0010), built when a library needs them; anything else throws.
1716
+ */
1717
+ querySelector(selector) {
1718
+ const steps = selector.split(">").map((t) => t.trim().toLowerCase());
1719
+ if (!steps.every((t) => /^[a-z][a-z0-9-]*$/.test(t))) throw domError("NotSupportedError", `querySelector: "${selector}" isn't supported yet`);
1720
+ const matches = (el) => {
1721
+ let n = el;
1722
+ for (let i = steps.length - 1; i >= 0; i--) {
1723
+ if (!n || n.localName !== steps[i]) return false;
1724
+ n = i > 0 ? n.parentElement : null;
1725
+ }
1726
+ return true;
1727
+ };
1728
+ const walk = (el) => {
1729
+ for (const c of el.children) {
1730
+ if (matches(c)) return c;
1731
+ const deeper = walk(c);
1732
+ if (deeper) return deeper;
1733
+ }
1734
+ return null;
1735
+ };
1736
+ for (const top of [this.head, this.body]) {
1737
+ if (matches(top)) return top;
1738
+ const hit = walk(top);
1739
+ if (hit) return hit;
1740
+ }
1741
+ return null;
1742
+ }
1743
+ };
1744
+ defineHandlers(WDocument.prototype);
1745
+ isControl = (node) => node instanceof WHTMLInputElement || node instanceof WHTMLTextAreaElement || node instanceof WHTMLSelectElement;
1746
+ }));
1747
+ // ../dom/dist/install-D7m7By8i.js
1748
+ /**
1749
+ * Exposes `dom` as the worker's `document`, `window` and DOM classes, so
1750
+ * frameworks find them where they look. Only for isolates with a surface; a
1751
+ * headless isolate never calls this.
1752
+ */
1753
+ function install(dom, scope) {
1754
+ const define = (name, value) => {
1755
+ Object.defineProperty(scope, name, {
1756
+ value,
1757
+ configurable: true,
1758
+ writable: true
1759
+ });
1760
+ };
1761
+ define("document", dom.document);
1762
+ if (!("window" in scope)) define("window", scope);
1763
+ for (const [name, value] of Object.entries(DOM_GLOBALS)) define(name, value);
1764
+ dom.document.defaultView = scope;
1765
+ }
1766
+ var DOM_GLOBALS;
1767
+ var init_install_D7m7By8i = __esmMin((() => {
1768
+ init_dom_yLsf0Z4e();
1769
+ DOM_GLOBALS = {
1770
+ Node: WNode,
1771
+ Element: WElement,
1772
+ HTMLElement: WHTMLElement,
1773
+ SVGElement: WSVGElement,
1774
+ Text: WText,
1775
+ Comment: WComment,
1776
+ DocumentFragment: WDocumentFragment,
1777
+ HTMLInputElement: WHTMLInputElement,
1778
+ HTMLTextAreaElement: WHTMLTextAreaElement,
1779
+ HTMLSelectElement: WHTMLSelectElement,
1780
+ HTMLOptionElement: WHTMLOptionElement,
1781
+ HTMLIFrameElement: WHTMLIFrameElement,
1782
+ DOMTokenList: WDOMTokenList
1783
+ };
1784
+ }));
1785
+ // ../dom/dist/worker.js
1786
+ var init_worker = __esmMin((() => {
1787
+ init_records_wVZrPpqr();
1788
+ init_dom_yLsf0Z4e();
1789
+ init_install_D7m7By8i();
1790
+ }));
1791
+ // src/render/index.ts
1792
+ function sharedDom(scope) {
1793
+ if (!shared) {
1794
+ shared = createDom({
1795
+ onBatch: () => {},
1796
+ onHead: (tag) => {
1797
+ for (const fn of headListeners) fn(tag);
1798
+ }
1799
+ });
1800
+ if (scope) install(shared, scope);
1801
+ }
1802
+ return shared;
1803
+ }
1804
+ /**
1805
+ * Builds the DOM subset and posts its batches. With `scope`, also installs it
1806
+ * as that global's `document` and DOM classes, which frameworks need. With
1807
+ * `pooled`, the isolate gets its own root in the worker's shared document
1808
+ * instead (ADR 0015).
1809
+ */
1810
+ function createRender(post, scope, pooled = false) {
1811
+ let pendingStyles = [];
1812
+ let pendingHead = [];
1813
+ /** Head tags already reported: each goes to the host once. */
1814
+ const headSeen = /* @__PURE__ */ new Set();
1815
+ let extrasScheduled = false;
1816
+ const postPatch = (batch) => {
1817
+ const styles = pendingStyles;
1818
+ const head = pendingHead;
1819
+ pendingStyles = [];
1820
+ pendingHead = [];
1821
+ post({
1822
+ v: 1,
1823
+ t: "patch",
1824
+ p: {
1825
+ fmt: ISOLOOP_DOM_FMT,
1826
+ batch,
1827
+ ...styles.length > 0 ? { styles } : {},
1828
+ ...head.length > 0 ? { head } : {}
1829
+ }
1830
+ });
1831
+ };
1832
+ /** Styles or head tags with no DOM change still need a patch to travel in. */
1833
+ const scheduleExtras = () => {
1834
+ if (extrasScheduled) return;
1835
+ extrasScheduled = true;
1836
+ queueMicrotask(() => {
1837
+ extrasScheduled = false;
1838
+ target.flush();
1839
+ if (pendingStyles.length > 0 || pendingHead.length > 0) postPatch([]);
1840
+ });
1841
+ };
1842
+ const onHead = (tag) => {
1843
+ if (headSeen.has(tag)) return;
1844
+ headSeen.add(tag);
1845
+ pendingHead.push(tag);
1846
+ scheduleExtras();
1847
+ };
1848
+ let target;
1849
+ if (pooled) {
1850
+ const member = sharedDom(scope).addRoot({ onBatch: postPatch });
1851
+ headListeners.add(onHead);
1852
+ target = {
1853
+ ...member,
1854
+ dispose() {
1855
+ headListeners.delete(onHead);
1856
+ member.dispose();
1857
+ }
1858
+ };
1859
+ } else {
1860
+ const dom = createDom({
1861
+ onBatch: postPatch,
1862
+ schedule: (flush) => queueMicrotask(flush),
1863
+ onHead
1864
+ });
1865
+ if (scope) install(dom, scope);
1866
+ target = {
1867
+ root: dom.root,
1868
+ flush: () => dom.flush(),
1869
+ deliver: (event) => dom.deliver(event),
1870
+ idOf: (node) => node.isConnected ? dom.idOf(node) : void 0,
1871
+ setValue: (node, value, o) => dom.setValue(node, value, o),
1872
+ dispose: () => {}
1873
+ };
1874
+ }
1875
+ return {
1876
+ fmt: ISOLOOP_DOM_FMT,
1877
+ root: target.root,
1878
+ flush: () => target.flush(),
1879
+ setValue: (node, value, o) => target.setValue(node, value, o),
1880
+ dispose: () => target.dispose(),
1881
+ styles(css) {
1882
+ pendingStyles.push(...typeof css === "string" ? [css] : css);
1883
+ scheduleExtras();
1884
+ },
1885
+ idOf(node) {
1886
+ if (!(node instanceof WNode)) return void 0;
1887
+ const id = target.idOf(node);
1888
+ return id === void 0 ? void 0 : String(id);
1889
+ },
1890
+ receive(e) {
1891
+ const t = nodeId(e.target);
1892
+ if (t === void 0) return;
1893
+ const currentTargets = e.currentTargets.map(nodeId).filter((n) => n !== void 0);
1894
+ const { target: _t, currentTargets: _c, ...rest } = e;
1895
+ target.deliver({
1896
+ ...rest,
1897
+ target: t,
1898
+ currentTargets
1899
+ });
1900
+ }
1901
+ };
1902
+ }
1903
+ var nodeId, shared, headListeners;
1904
+ var init_render = __esmMin((() => {
1905
+ init_worker();
1906
+ nodeId = (s) => /^\d+$/.test(s) ? Number(s) : void 0;
1907
+ shared = null;
1908
+ headListeners = /* @__PURE__ */ new Set();
1909
+ }));
1910
+ // package.json
1911
+ var version = "0.0.0";
1912
+ // src/vanilla.ts
1913
+ var vanilla_exports = /* @__PURE__ */ __exportAll({
1914
+ REQUIRES: () => REQUIRES,
1915
+ createVanillaIsolate: () => createVanillaIsolate,
1916
+ defineIsolate: () => defineIsolate
1917
+ });
1918
+ /**
1919
+ * Types an isolate module's default export and stamps it with the version
1920
+ * it was built against. `Root` defaults to the structural `IsolateRoot`.
1921
+ */
1922
+ function defineIsolate(def) {
1923
+ return {
1924
+ requires: REQUIRES,
1925
+ ...def
1926
+ };
1927
+ }
1928
+ /** Builds the context for `start(ctx)`. `scope` is the worker global the DOM subset installs on. */
1929
+ function createVanillaIsolate(init, post, scope, pooled = false) {
1930
+ const render = init.renderFmt === "none" ? null : createRender(post, scope, pooled);
1931
+ const calls = createHostCalls({
1932
+ post,
1933
+ beforeCall: () => render?.flush(),
1934
+ idOf: (node) => render ? render.idOf(node) : void 0,
1935
+ surface: render !== null,
1936
+ navigate: init.grants.navigate === true
1937
+ });
1938
+ const awake = createKeepAwake();
1939
+ const bus = createBusClient(init.busPort, {
1940
+ ...init.wake ? { wake: true } : {},
1941
+ onError: (err) => {
1942
+ post({
1943
+ v: 1,
1944
+ t: "error",
1945
+ p: err instanceof Error && err.stack !== void 0 ? {
1946
+ message: err.message,
1947
+ stack: err.stack,
1948
+ fatal: false
1949
+ } : {
1950
+ message: String(err),
1951
+ fatal: false
1952
+ }
1953
+ });
1954
+ }
1955
+ });
1956
+ const onShutdown = [];
1957
+ let portal;
1958
+ const ctx = {
1959
+ id: init.isolateId,
1960
+ config: init.config,
1961
+ root: render?.root,
1962
+ portalRoot: void 0,
1963
+ reportError(error, o = {}) {
1964
+ const fatal = o.fatal ?? true;
1965
+ post({
1966
+ v: 1,
1967
+ t: "error",
1968
+ p: error instanceof Error ? {
1969
+ message: error.message,
1970
+ ...error.stack === void 0 ? {} : { stack: error.stack },
1971
+ fatal
1972
+ } : {
1973
+ message: String(error),
1974
+ fatal
1975
+ }
1976
+ });
1977
+ },
1978
+ host: calls.api,
1979
+ bus: bus.client,
1980
+ styles: (css) => render?.styles(css),
1981
+ setValue(node, value, o) {
1982
+ if (!render) return;
1983
+ if (!(node instanceof WNode)) throw new TypeError("setValue: not a node of this isolate");
1984
+ render.setValue(node, value, o);
1985
+ },
1986
+ onShutdown: (fn) => {
1987
+ onShutdown.push(fn);
1988
+ },
1989
+ keepAwake: () => awake.hold()
1990
+ };
1991
+ Object.defineProperty(ctx, "portalRoot", {
1992
+ enumerable: false,
1993
+ get() {
1994
+ if (!render) return void 0;
1995
+ if (!portal) {
1996
+ const { root } = render;
1997
+ const div = root.ownerDocument.createElement("div");
1998
+ div.setAttribute("data-isoloop-portal", "");
1999
+ queueMicrotask(() => {
2000
+ if (div.parentNode !== root) root.appendChild(div);
2001
+ });
2002
+ portal = div;
2003
+ }
2004
+ return portal;
2005
+ }
2006
+ });
2007
+ return {
2008
+ ctx,
2009
+ renderFmt: render ? render.fmt : "none",
2010
+ receive(msg) {
2011
+ if (isHostToIsolate(msg)) {
2012
+ if (msg.t === "event") render?.receive(msg.p);
2013
+ else if (msg.t === "reattach") bus.reattach(msg.p.busPort);
2014
+ else if (msg.t === "result" && msg.re !== void 0) calls.receive(msg.re, msg.p);
2015
+ }
2016
+ },
2017
+ idle() {
2018
+ const b = bus.idle();
2019
+ return {
2020
+ sinceDeliveryMs: b.sinceDeliveryMs,
2021
+ inFlight: b.inFlight + calls.pending(),
2022
+ holds: awake.report(performance.now())
2023
+ };
2024
+ },
2025
+ async shutdown(reason) {
2026
+ await Promise.allSettled(onShutdown.map(async (fn) => fn(reason)));
2027
+ render?.flush();
2028
+ render?.dispose();
2029
+ }
2030
+ };
2031
+ }
2032
+ var REQUIRES;
2033
+ var init_vanilla = __esmMin((() => {
2034
+ init_dist();
2035
+ init_bus_client();
2036
+ init_host_calls();
2037
+ init_keep_awake();
2038
+ init_worker();
2039
+ init_render();
2040
+ REQUIRES = majorMinor(version) ?? "0.0";
2041
+ }));
2042
+ // src/bootstrap.ts
2043
+ var bootstrap_exports = /* @__PURE__ */ __exportAll({});
2044
+ /** Once per worker, after the first isolate's protocol check. */
2045
+ function startHeartbeat(everyMs) {
2046
+ if (beating) return;
2047
+ beating = true;
2048
+ let last = performance.now();
2049
+ setInterval(() => {
2050
+ const now = performance.now();
2051
+ const lagMs = Math.max(0, now - last - everyMs);
2052
+ if (mode === "pool") {
2053
+ const reports = {};
2054
+ for (const m of members.values()) if (m.name !== void 0 && m.idleReport) reports[m.name] = m.idleReport();
2055
+ postWorker({
2056
+ v: 1,
2057
+ t: "beat",
2058
+ p: {
2059
+ lagMs,
2060
+ members: reports
2061
+ }
2062
+ });
2063
+ } else {
2064
+ const idle = members.get(void 0)?.idleReport?.();
2065
+ postWorker({
2066
+ v: 1,
2067
+ t: "beat",
2068
+ p: idle ? {
2069
+ lagMs,
2070
+ idle
2071
+ } : { lagMs }
2072
+ });
2073
+ }
2074
+ last = now;
2075
+ }, everyMs);
2076
+ }
2077
+ /** `shutdown` for a member: `bye` once its handlers settle or the grace runs out. */
2078
+ function shutdownMember(m, graceMs, reason) {
2079
+ if (members.get(m.name) === m) members.delete(m.name);
2080
+ m.receive = null;
2081
+ const done = m.shutdownHook?.(reason) ?? Promise.resolve();
2082
+ const grace = new Promise((r) => setTimeout(r, Math.max(0, graceMs - 50)));
2083
+ Promise.race([done, grace]).finally(() => {
2084
+ m.post({
2085
+ v: 1,
2086
+ t: "bye",
2087
+ p: {}
2088
+ });
2089
+ if (members.size === 0) self.close();
2090
+ });
2091
+ }
2092
+ /** Routes one message from the host to the member it is for. */
2093
+ function route(msg) {
2094
+ const m = members.get(mode === "pool" ? msg.isolate : void 0);
2095
+ if (!m) return;
2096
+ if (msg.t === "shutdown") shutdownMember(m, msg.p.graceMs, msg.p.reason);
2097
+ else m.receive?.(msg);
2098
+ }
2099
+ async function boot(m, init) {
2100
+ if (init.protocol.min > PROTOCOL.v || init.protocol.max < PROTOCOL.min) {
2101
+ fatal(m, `Host speaks protocol ${init.protocol.min}–${init.protocol.max}, this runtime ${PROTOCOL.min}–${PROTOCOL.v}`, "protocol_mismatch");
2102
+ return;
2103
+ }
2104
+ startHeartbeat(init.heartbeatMs);
2105
+ const { createVanillaIsolate } = await Promise.resolve().then(() => (init_vanilla(), vanilla_exports));
2106
+ const runtime = createVanillaIsolate(init, m.post, self, mode === "pool");
2107
+ let mod;
2108
+ try {
2109
+ mod = await import(
2110
+ /* @vite-ignore */
2111
+ init.src
2112
+ );
2113
+ } catch (err) {
2114
+ const why = err instanceof Error ? err.message : String(err);
2115
+ const cross = new URL(init.src).origin !== self.location.origin;
2116
+ fatal(m, `Could not import ${init.src}: ${why}${cross ? " (a cross-origin isolate needs CORS headers; see docs/guide/hosting.md)" : ""}`);
2117
+ return;
2118
+ }
2119
+ const main = typeof mod === "object" && mod !== null && "default" in mod ? mod.default : void 0;
2120
+ if (typeof main === "object" && main !== null && "start" in main) {
2121
+ const start = main.start;
2122
+ if (typeof start === "function") {
2123
+ const requires = "requires" in main ? main.requires : void 0;
2124
+ await startIsolate(m, runtime, (ctx) => Reflect.apply(start, main, [ctx]), typeof requires === "string" ? requires : void 0);
2125
+ return;
2126
+ }
2127
+ }
2128
+ fatal(m, `${init.src} has no default export with start(ctx)`);
2129
+ }
2130
+ async function startIsolate(m, runtime, start, requires) {
2131
+ m.receive = (msg) => {
2132
+ runtime.receive(msg);
2133
+ };
2134
+ m.shutdownHook = (reason) => runtime.shutdown(reason);
2135
+ m.idleReport = () => runtime.idle();
2136
+ m.post({
2137
+ v: 1,
2138
+ t: "ready",
2139
+ p: {
2140
+ runtime: "@isoloop/runtime",
2141
+ adapter: "vanilla",
2142
+ renderFmt: runtime.renderFmt,
2143
+ ...requires === void 0 ? {} : { requires }
2144
+ }
2145
+ });
2146
+ try {
2147
+ await start(runtime.ctx);
2148
+ } catch (err) {
2149
+ fatal(m, `start() threw: ${err instanceof Error ? err.message : String(err)}`);
2150
+ }
2151
+ }
2152
+ /** Handles one message from the host: `init` boots a member, the rest is routed. */
2153
+ function onMessage(e) {
2154
+ const msg = e.data;
2155
+ if (!isHostToIsolate(msg)) return;
2156
+ if (msg.t !== "init") {
2157
+ route(msg);
2158
+ return;
2159
+ }
2160
+ const name = msg.isolate;
2161
+ const wants = name === void 0 ? "own" : "pool";
2162
+ if (mode === "own" || mode === "pool" && wants === "own") return;
2163
+ if (mode === null) {
2164
+ mode = wants;
2165
+ if (mode === "pool") freezeBuiltins();
2166
+ }
2167
+ if (members.has(name)) return;
2168
+ const m = {
2169
+ name,
2170
+ post: memberPost(name),
2171
+ shutdownHook: null,
2172
+ idleReport: null,
2173
+ receive: null
2174
+ };
2175
+ members.set(name, m);
2176
+ boot(m, msg.p).catch((err) => {
2177
+ fatal(m, err instanceof Error ? err.message : String(err));
2178
+ });
2179
+ }
2180
+ function startOnce() {
2181
+ self.addEventListener("message", onMessage);
2182
+ }
2183
+ var mode, members, postWorker, memberPost, fatal, beating, STARTED;
2184
+ var init_bootstrap = __esmMin((() => {
2185
+ init_dist();
2186
+ init_freeze();
2187
+ mode = null;
2188
+ members = /* @__PURE__ */ new Map();
2189
+ postWorker = (msg) => {
2190
+ self.postMessage(msg);
2191
+ };
2192
+ memberPost = (name) => (msg) => {
2193
+ self.postMessage(name === void 0 ? msg : {
2194
+ ...msg,
2195
+ isolate: name
2196
+ });
2197
+ };
2198
+ fatal = (m, message, code) => {
2199
+ m.post({
2200
+ v: 1,
2201
+ t: "error",
2202
+ p: code ? {
2203
+ message,
2204
+ fatal: true,
2205
+ code
2206
+ } : {
2207
+ message,
2208
+ fatal: true
2209
+ }
2210
+ });
2211
+ };
2212
+ beating = false;
2213
+ STARTED = Symbol.for("isoloop.bootstrap");
2214
+ if (Reflect.get(self, STARTED) === true) {
2215
+ if (import.meta.env?.DEV === true) console.warn("isoloop: worker entry evaluated twice; ignoring");
2216
+ } else {
2217
+ Reflect.set(self, STARTED, true);
2218
+ startOnce();
2219
+ }
2220
+ }));
2221
+ // src/worker.ts
2222
+ const held = [];
2223
+ const hold = (e) => {
2224
+ held.push(e);
2225
+ };
2226
+ self.addEventListener("message", hold);
2227
+ Promise.resolve().then(() => (init_bootstrap(), bootstrap_exports)).then(() => {
2228
+ self.removeEventListener("message", hold);
2229
+ for (const e of held.splice(0)) self.dispatchEvent(new MessageEvent("message", {
2230
+ data: e.data,
2231
+ ports: [...e.ports]
2232
+ }));
2233
+ }, (err) => {
2234
+ setTimeout(() => {
2235
+ throw err;
2236
+ });
2237
+ });