@sigil-dev/runtime 0.9.6 → 0.9.10

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.
Files changed (4) hide show
  1. package/README.md +140 -140
  2. package/index.test.ts +66 -0
  3. package/index.ts +934 -850
  4. package/package.json +1 -1
package/index.ts CHANGED
@@ -1,850 +1,934 @@
1
- export { __asyncBoundary } from "./async-boundary.ts";
2
- export { Boundary } from "./boundary";
3
- export {
4
- easeInCubic,
5
- easeInOutCubic,
6
- easeInOutQuad,
7
- easeInOutQuart,
8
- easeInOutQuint,
9
- easeInOutSine,
10
- easeInQuad,
11
- easeInQuart,
12
- easeInQuint,
13
- easeInSine,
14
- easeOutCubic,
15
- easeOutQuad,
16
- easeOutQuart,
17
- easeOutQuint,
18
- easeOutSine,
19
- linear,
20
- } from "./easing.ts";
21
- export { ReactiveMap } from "./reactivity/map.ts";
22
- export { ReactiveSet } from "./reactivity/set.ts";
23
- export { mountTransition, removeAnimated } from "./transition.ts";
24
-
25
- export const SIGIL_SAFE = Symbol.for("sigil.safe");
26
- export class SafeHtml {
27
- [SIGIL_SAFE] = true;
28
- constructor(public v: string) {}
29
- toString() {
30
- return this.v;
31
- }
32
- }
33
-
34
- let currentEffect: (() => void) | null = null;
35
- let currentDeps: Set<Set<() => void>> | null = null;
36
-
37
- let batchDepth = 0;
38
- let scheduledFlush = false;
39
- const pendingEffects = new Set<() => void>();
40
- const pendingPreEffects = new Set<() => void>();
41
-
42
- function flush() {
43
- scheduledFlush = false;
44
- // biome-ignore lint/suspicious/useIterableCallbackReturn: effects returning cleanup is intended
45
- pendingPreEffects.forEach((e) => e());
46
- pendingPreEffects.clear();
47
- // biome-ignore lint/suspicious/useIterableCallbackReturn: effects returning cleanup is intended
48
- pendingEffects.forEach((e) => e());
49
- pendingEffects.clear();
50
- }
51
-
52
- function scheduleEffect(fn: () => void) {
53
- const target = (fn as any).__sigil_pre ? pendingPreEffects : pendingEffects;
54
- target.add(fn);
55
- if (batchDepth === 0 && !scheduledFlush) {
56
- scheduledFlush = true;
57
- queueMicrotask(flush);
58
- }
59
- }
60
-
61
- const targetDepsMap = new WeakMap<
62
- object,
63
- Map<string | symbol, Set<() => void>>
64
- >();
65
-
66
- function getDeps(target: object, key: string | symbol): Set<() => void> {
67
- let deps = targetDepsMap.get(target);
68
- if (!deps) {
69
- deps = new Map();
70
- targetDepsMap.set(target, deps);
71
- }
72
- let set = deps.get(key);
73
- if (!set) {
74
- set = new Set();
75
- deps.set(key, set);
76
- }
77
- return set;
78
- }
79
-
80
- function track(target: object, key: string | symbol) {
81
- if (currentEffect && currentDeps) {
82
- const deps = getDeps(target, key);
83
- deps.add(currentEffect);
84
- currentDeps.add(deps); // Set, deduplicates automatically
85
- }
86
- }
87
-
88
- function trigger(target: object, key: string | symbol) {
89
- const deps = targetDepsMap.get(target);
90
- if (!deps) return;
91
- const set = deps.get(key);
92
- if (!set) return;
93
- for (const fn of [...set]) {
94
- scheduleEffect(fn);
95
- }
96
- }
97
-
98
- const proxyCache = new WeakMap<object, object>();
99
- const proxyToTarget = new WeakMap<object, object>();
100
- const reactiveTargets = new WeakSet<object>();
101
- const ARRAY_MUTATORS = new Set([
102
- "push",
103
- "pop",
104
- "shift",
105
- "unshift",
106
- "splice",
107
- "sort",
108
- "reverse",
109
- "fill",
110
- ]);
111
-
112
- function createReactiveProxy<T extends object>(target: T): T {
113
- const existing = proxyCache.get(target);
114
- if (existing) return existing as T;
115
-
116
- const proxy = new Proxy(target, {
117
- get(target, key, receiver) {
118
- if (
119
- Array.isArray(target) &&
120
- typeof key === "string" &&
121
- ARRAY_MUTATORS.has(key)
122
- ) {
123
- return (...args: any[]) => {
124
- const result = (target as any)[key](...args);
125
- trigger(target, "length");
126
- // trigger all numeric keys that changed — for splice/sort
127
- // triggering length is sufficient for most reactive patterns
128
- return result;
129
- };
130
- }
131
- if (key === "set") {
132
- return (newValue: T) => {
133
- const oldKeys = new Set(Object.keys(target));
134
- const newKeys = new Set(Object.keys(newValue));
135
- for (const k of oldKeys) {
136
- if (!newKeys.has(k)) {
137
- delete (target as any)[k];
138
- trigger(target, k);
139
- }
140
- }
141
- for (const k of newKeys) {
142
- (target as any)[k] = (newValue as any)[k];
143
- trigger(target, k);
144
- }
145
- if (Array.isArray(target)) {
146
- // delete leaves holes — length must shrink to the new value's,
147
- // or iteration (spread, reconcile) sees phantom trailing slots
148
- target.length = (newValue as unknown[]).length;
149
- trigger(target, "length");
150
- }
151
- };
152
- }
153
-
154
- if (key === "peek") {
155
- return () => target;
156
- }
157
-
158
- if (typeof key === "symbol") {
159
- return Reflect.get(target, key, receiver);
160
- }
161
-
162
- track(target, key);
163
- const value = target[key as keyof T];
164
-
165
- if (typeof value === "object" && value !== null) {
166
- return createReactiveProxy(value);
167
- }
168
-
169
- return value;
170
- },
171
-
172
- set(target, key, newValue, receiver) {
173
- const oldValue = target[key as keyof T];
174
- const result = Reflect.set(target, key, newValue, receiver);
175
- if (oldValue !== newValue) {
176
- trigger(target, key as string | symbol);
177
- if (
178
- Array.isArray(target) &&
179
- typeof key === "string" &&
180
- !Number.isNaN(Number(key))
181
- ) {
182
- trigger(target, "length");
183
- }
184
- }
185
- return result;
186
- },
187
-
188
- deleteProperty(target, key) {
189
- const result = Reflect.deleteProperty(target, key);
190
- trigger(target, key as string | symbol);
191
- return result;
192
- },
193
- });
194
-
195
- proxyCache.set(target, proxy);
196
- proxyToTarget.set(proxy, target);
197
- reactiveTargets.add(target);
198
- return proxy as T;
199
- }
200
-
201
- // ─── createSignal (branches on type) ───
202
-
203
- export type Signal<T> = {
204
- (): T;
205
- set: (next: T) => void;
206
- peek: () => T;
207
- };
208
-
209
- export function batch(fn: () => void) {
210
- batchDepth++;
211
- fn();
212
- batchDepth--;
213
- if (batchDepth === 0) {
214
- scheduledFlush = false;
215
- flush();
216
- }
217
- }
218
-
219
- export function tick(): Promise<void> {
220
- return new Promise((resolve) => queueMicrotask(resolve));
221
- }
222
-
223
- function createPrimitiveSignal<T>(initial: T): Signal<T> {
224
- const subs = new Set<() => void>();
225
- let value = initial;
226
-
227
- const getter = () => {
228
- if (currentEffect && currentDeps) {
229
- subs.add(currentEffect);
230
- currentDeps.add(subs);
231
- }
232
- return value;
233
- };
234
-
235
- getter.set = (next: T) => {
236
- value = next;
237
- for (const fn of [...subs]) {
238
- scheduleEffect(fn);
239
- }
240
- };
241
-
242
- getter.peek = () => value;
243
-
244
- return getter;
245
- }
246
-
247
- export function createSignal<T>(initial: T): Signal<T> {
248
- if (typeof initial === "object" && initial !== null) {
249
- const proxy = createReactiveProxy(initial);
250
- const getter = () => {
251
- // array signals: auto-track length so push/pop/splice re-run effects
252
- if (Array.isArray(initial)) {
253
- track(initial, "length");
254
- }
255
- return proxy;
256
- };
257
- getter.set = (next: T) => (proxy as any).set(next);
258
- getter.peek = () => initial;
259
- return getter;
260
- }
261
-
262
- return createPrimitiveSignal(initial);
263
- }
264
-
265
- // A1: $state.raw — create signal without Proxy wrapping for objects/arrays
266
- export function createRawSignal<T>(initial: T): Signal<T> {
267
- return createPrimitiveSignal(initial);
268
- }
269
-
270
- // A2: $state.snapshot — deep un-proxy a signal value
271
- function deepUnproxy<T>(value: T): T {
272
- if (typeof value !== "object" || value === null) return value;
273
- const raw = proxyToTarget.get(value as object);
274
- if (!raw) return value; // not a proxy, return as-is
275
- if (Array.isArray(raw)) {
276
- return raw.map(deepUnproxy) as T;
277
- }
278
- const result: Record<string, unknown> = {};
279
- for (const key of Object.keys(raw)) {
280
- result[key] = deepUnproxy((raw as Record<string, unknown>)[key]);
281
- }
282
- return result as T;
283
- }
284
-
285
- export function snapshot<T>(value: T): T {
286
- return deepUnproxy(value);
287
- }
288
-
289
- // A3: $effect.tracking() — check if inside reactive context
290
- export function tracking(): boolean {
291
- return currentEffect !== null;
292
- }
293
-
294
- /**
295
- * Run fn() outside of any reactive context: signal reads inside fn() do not
296
- * register dependencies on the enclosing effect.
297
- */
298
- export function untrack<T>(fn: () => T): T {
299
- const prevEffect = currentEffect;
300
- const prevDeps = currentDeps;
301
- currentEffect = null;
302
- currentDeps = null;
303
- try {
304
- return fn();
305
- } finally {
306
- currentEffect = prevEffect;
307
- currentDeps = prevDeps;
308
- }
309
- }
310
-
311
- // A4: $inspect — dev-only effect logging
312
- export function createInspectEffect(
313
- getValues: () => unknown[],
314
- cb?: (vals: unknown[]) => void,
315
- ): void {
316
- if (typeof process !== "undefined" && process.env.NODE_ENV === "production")
317
- return;
318
- createEffect(() => {
319
- const vals = getValues();
320
- if (cb) cb(vals);
321
- else console.log(...vals);
322
- });
323
- }
324
-
325
- // A5: $effect.pre — effect that flushes before DOM update
326
- export function createEffectPre(
327
- fn: () => undefined | (() => void),
328
- ): () => void {
329
- let cleanup: (() => void) | undefined;
330
- const ownDeps = new Set<Set<() => void>>();
331
-
332
- const effect = () => {
333
- if (cleanup) cleanup();
334
- for (const depSet of ownDeps) depSet.delete(effect);
335
- ownDeps.clear();
336
-
337
- const prevEffect = currentEffect;
338
- const prevDeps = currentDeps;
339
- currentEffect = effect;
340
- currentDeps = ownDeps;
341
- try {
342
- cleanup = fn();
343
- } finally {
344
- currentEffect = prevEffect;
345
- currentDeps = prevDeps;
346
- }
347
- };
348
-
349
- (effect as any).__sigil_pre = true;
350
- effect();
351
-
352
- const dispose = () => {
353
- for (const depSet of ownDeps) depSet.delete(effect);
354
- ownDeps.clear();
355
- if (cleanup) cleanup();
356
- };
357
-
358
- ((globalThis as any).__sigilEffectScope as (() => void)[] | undefined)?.push(
359
- dispose,
360
- );
361
- return dispose;
362
- }
363
-
364
- // A9: Profiler effect timing (dev)
365
- export function createProfilerEffect(
366
- _name: string,
367
- fn: () => undefined | (() => void),
368
- ): () => void {
369
- return createEffect(() => {
370
- if (
371
- typeof process !== "undefined" &&
372
- process.env.NODE_ENV === "production"
373
- ) {
374
- return fn();
375
- }
376
- const _start = performance.now();
377
- const cleanup = fn();
378
- const _end = performance.now();
379
- // console.log(`[Profiler] ${name}: ${(end - start).toFixed(2)}ms`);
380
- return cleanup;
381
- });
382
- }
383
-
384
- // Deferred effect mode for hydration: effects created while the flag is set
385
- // are queued instead of run immediately, then flushed after DOM insertion.
386
- const deferredEffectQueue: (() => void)[] = [];
387
-
388
- export function flushDeferredEffects(): void {
389
- const pending = deferredEffectQueue.splice(0);
390
- for (const run of pending) run();
391
- }
392
-
393
- // biome-ignore lint/suspicious/noConfusingVoidType: please shut up its a weird type
394
- export function createEffect(fn: () => void | (() => void)): () => void {
395
- let cleanup: (() => void) | undefined;
396
- const ownDeps = new Set<Set<() => void>>();
397
-
398
- const effect = () => {
399
- if (cleanup) cleanup();
400
- for (const depSet of ownDeps) depSet.delete(effect);
401
- ownDeps.clear();
402
-
403
- const prevEffect = currentEffect;
404
- const prevDeps = currentDeps;
405
- currentEffect = effect;
406
- currentDeps = ownDeps;
407
- try {
408
- //@ts-expect-error kill yourself
409
- cleanup = fn();
410
- } finally {
411
- currentEffect = prevEffect;
412
- currentDeps = prevDeps;
413
- }
414
- };
415
-
416
- // In deferred mode (hydration), queue the effect instead of running immediately.
417
- // This ensures the DOM is inserted before effect callbacks query it.
418
- if ((globalThis as any).__sigilDeferEffects) {
419
- deferredEffectQueue.push(() => effect());
420
- } else {
421
- effect();
422
- }
423
-
424
- const dispose = () => {
425
- for (const depSet of ownDeps) depSet.delete(effect);
426
- ownDeps.clear();
427
- if (cleanup) cleanup();
428
- };
429
-
430
- ((globalThis as any).__sigilEffectScope as (() => void)[] | undefined)?.push(
431
- dispose,
432
- );
433
- return dispose;
434
- }
435
-
436
- /**
437
- * Run fn() and return a dispose function that tears down every effect
438
- * created during that call (including effects inside child createMemo calls).
439
- * Supports nesting: inner scopes don't leak to outer ones.
440
- */
441
- export function withEffectScope(fn: () => void): () => void {
442
- const prev = (globalThis as any).__sigilEffectScope;
443
- const disposers: (() => void)[] = [];
444
- (globalThis as any).__sigilEffectScope = disposers;
445
- try {
446
- fn();
447
- } finally {
448
- (globalThis as any).__sigilEffectScope = prev;
449
- }
450
- return () => {
451
- for (const d of disposers) d();
452
- disposers.length = 0;
453
- };
454
- }
455
-
456
- type EffectScopeGlobal = { __sigilEffectScope?: (() => void)[] };
457
-
458
- /**
459
- * Run fn() with a detached effect scope. Effects created inside are invisible
460
- * to enclosing scopes (the scope array is replaced, not merged) and live until
461
- * dispose() is called — for app bootstrap, routers, and long-lived listeners.
462
- */
463
- export function createRoot<T>(fn: (dispose: () => void) => T): T {
464
- const g = globalThis as EffectScopeGlobal;
465
- const prev = g.__sigilEffectScope;
466
- const disposers: (() => void)[] = [];
467
- g.__sigilEffectScope = disposers;
468
- const dispose = () => {
469
- for (const d of disposers.splice(0)) d();
470
- };
471
- try {
472
- return fn(dispose);
473
- } finally {
474
- g.__sigilEffectScope = prev;
475
- }
476
- }
477
-
478
- export interface Resource<T> {
479
- data: () => T | undefined;
480
- loading: () => boolean;
481
- error: () => Error | undefined;
482
- refetch: () => void;
483
- }
484
-
485
- /**
486
- * Async data source with reactive re-fetching. Re-runs when `source()` changes
487
- * or refetch() is called; stale responses are discarded by request id.
488
- */
489
- export function createResource<T>(
490
- fetcher: (source: unknown, info: { refetch: () => void }) => Promise<T>,
491
- source?: () => unknown,
492
- ): Resource<T> {
493
- const data = createSignal<T | undefined>(undefined);
494
- const loading = createSignal(true);
495
- const error = createSignal<Error | undefined>(undefined);
496
- const version = createSignal(0);
497
- let requestCount = 0;
498
- let versionCounter = 0;
499
-
500
- const refetch = () => {
501
- versionCounter++;
502
- version.set(versionCounter);
503
- };
504
-
505
- createEffect(() => {
506
- const src = source?.();
507
- version(); // track refetch bumps
508
- const id = ++requestCount;
509
- loading.set(true);
510
- error.set(undefined);
511
- fetcher(src, { refetch }).then(
512
- (result) => {
513
- if (id !== requestCount) return; // stale response
514
- data.set(result);
515
- loading.set(false);
516
- },
517
- (err: unknown) => {
518
- if (id !== requestCount) return;
519
- error.set(err instanceof Error ? err : new Error(String(err)));
520
- loading.set(false);
521
- },
522
- );
523
- });
524
-
525
- return { data, loading, error, refetch };
526
- }
527
-
528
- export function createMemo<T>(fn: () => T): Signal<T> {
529
- const inner = createSignal<T>(undefined as T);
530
- createEffect(() => inner.set(fn()));
531
- return inner;
532
- }
533
-
534
- /**
535
- * Reconcile a list of keyed DOM nodes.
536
- * anchor.before(node) handles both insert and move natively.
537
- * @param claimNode - Optional hydration callback. Called with (element, key) for
538
- * server-rendered elements removed from the DOM. Returns the element to use,
539
- * or null to discard.
540
- */
541
- const lastItemFor = new WeakMap<object, unknown>();
542
-
543
- export function reconcile<T>(
544
- anchor: Partial<Comment>,
545
- keyMap: Map<unknown, Node>,
546
- newItems: T[],
547
- getKey: (item: T, index: number) => unknown,
548
- createNode: (item: T) => Node,
549
- // is this meant to be unused? claimNode?: (element: Element, key: unknown) => Element | null,
550
- ): void {
551
- const newKeys = new Set(newItems.map((item, i) => getKey(item, i)));
552
-
553
- // Remove nodes no longer in list (or claim them for hydration)
554
- for (const [key, node] of keyMap) {
555
- if (!newKeys.has(key)) {
556
- node.parentNode?.removeChild(node);
557
- keyMap.delete(key);
558
- }
559
- }
560
-
561
- // Insert/move in order — anchor.before() handles both cases.
562
- // A surviving node whose item instance changed is rebuilt: compiled row
563
- // bodies bake item reads at creation time, so immutable-style updates
564
- // (new object, same key) must swap the node to show fresh content.
565
- for (let i = 0; i < newItems.length; i++) {
566
- const item = newItems[i]!;
567
- const key = getKey(item, i);
568
- let node = keyMap.get(key);
569
- if (
570
- node &&
571
- lastItemFor.has(node) &&
572
- !Object.is(lastItemFor.get(node), item)
573
- ) {
574
- node.parentNode?.removeChild(node);
575
- keyMap.delete(key);
576
- node = undefined;
577
- }
578
- if (!node) {
579
- node = createNode(item);
580
- lastItemFor.set(node, item);
581
- keyMap.set(key, node);
582
- }
583
- anchor.before?.(node);
584
- }
585
- }
586
-
587
- /**
588
- * Claim an existing element from a hydration pool by tag name, or create a new one.
589
- * Removes the claimed node from the pool array.
590
- * When falling back to createElement, appends to parent if provided (SPA mode).
591
- */
592
- export function claim(
593
- nodes: ChildNode[],
594
- tag: string,
595
- parent?: Element,
596
- ): Element {
597
- for (let i = 0; i < nodes.length; i++) {
598
- const node = nodes[i];
599
- if (
600
- node instanceof Element &&
601
- node.tagName.toLowerCase() === tag.toLowerCase()
602
- ) {
603
- nodes.splice(i, 1);
604
- return node;
605
- }
606
- }
607
- const el = document.createElement(tag);
608
- if (parent) parent.appendChild(el);
609
- return el;
610
- }
611
-
612
- /**
613
- * Claim an existing Text node from a hydration pool, or create a new empty one.
614
- * Removes the claimed node from the pool array.
615
- * When falling back to createTextNode, appends to parent if provided (SPA mode).
616
- */
617
- export function claimText(nodes: ChildNode[], parent?: Element): Text {
618
- for (let i = 0; i < nodes.length; i++) {
619
- const node = nodes[i];
620
- if (node instanceof Text) {
621
- nodes.splice(i, 1);
622
- return node;
623
- }
624
- }
625
- const text = document.createTextNode("");
626
- if (parent) parent.appendChild(text);
627
- return text;
628
- }
629
-
630
- /**
631
- * Claim an existing Comment node from a hydration pool, or create a new one.
632
- * Removes the claimed node from the pool array.
633
- * When falling back to createComment, appends to parent if provided (SPA mode).
634
- */
635
- export function claimComment(
636
- nodes: ChildNode[],
637
- text: string = "",
638
- parent?: Element,
639
- ): Comment {
640
- for (let i = 0; i < nodes.length; i++) {
641
- const node = nodes[i];
642
- if (node instanceof Comment && node.data === text) {
643
- nodes.splice(i, 1);
644
- return node;
645
- }
646
- }
647
- const comment = document.createComment(text);
648
- if (parent) parent.appendChild(comment);
649
- return comment;
650
- }
651
-
652
- /**
653
- * Hydrate a keyed list: claim the comment anchor, walk its sibling elements
654
- * to build a keyMap, then reconcile with signal data.
655
- *
656
- * SSR renders items as flat siblings. Hydration claims them by position,
657
- * builds the keyMap, removes from DOM, then reconcile re-inserts in order.
658
- */
659
- export function hydrateKeyedList<T>(
660
- nodesVar: ChildNode[],
661
- signalItems: T[],
662
- getKey: (item: T, index: number) => unknown,
663
- createNode: (item: T) => Node,
664
- parent?: Element,
665
- ): { anchor: Comment; keyMap: Map<unknown, Node> } {
666
- // 1. Claim the <!--g--> opening delimiter as anchor
667
- const anchor = claimComment(nodesVar, "g", parent);
668
-
669
- // 2. Walk siblings after anchor, collect elements up to <!--/g-->, build keyMap
670
- const keyMap = new Map<unknown, Node>();
671
- const anchorParent = anchor.parentNode;
672
- if (anchorParent && signalItems.length > 0) {
673
- const claimed: Element[] = [];
674
- let next = anchor.nextSibling;
675
- while (next) {
676
- const current = next;
677
- next = next.nextSibling;
678
- // Stop at closing <!--/g--> delimiter and consume it
679
- if (current instanceof Comment && current.data === "/g") {
680
- current.remove();
681
- break;
682
- }
683
- if (current instanceof Element) {
684
- current.remove();
685
- claimed.push(current);
686
- }
687
- }
688
- // Map claimed elements to keys by index
689
- for (let i = 0; i < claimed.length && i < signalItems.length; i++) {
690
- //@ts-expect-error i is always in bounds
691
- const key = getKey(signalItems[i], i);
692
- //@ts-expect-error i is always in bounds
693
- keyMap.set(key, claimed[i]);
694
- }
695
- }
696
-
697
- // 3. Reconcile — keyMap is pre-populated with claimed nodes
698
- reconcile(anchor, keyMap, signalItems, getKey, createNode);
699
- return { anchor, keyMap };
700
- }
701
-
702
- export function insert(
703
- parent: Element | DocumentFragment,
704
- value: unknown,
705
- ): void {
706
- if (value === false || value === null || value === undefined) return;
707
- if (typeof value === "function") {
708
- insert(parent, value());
709
- return;
710
- }
711
- if (Array.isArray(value)) {
712
- for (const item of value) insert(parent, item);
713
- return;
714
- }
715
- if (value instanceof Node) {
716
- parent.appendChild(value);
717
- return;
718
- }
719
- parent.append(String(value));
720
- }
721
-
722
- /**
723
- * Hydrate a `<!--g-->…<!--/g-->` slot.
724
- *
725
- * Consumes the delimiter pair and the SSR content between them from `nodes`,
726
- * then runs `value` against that content as its hydration pool. Component
727
- * children are compiled to thunks precisely so this call — not the caller's
728
- * pool — decides what they claim: `<Wrap><Item/></Wrap>` puts `Item`'s SSR
729
- * markup inside `Wrap`'s root, which the caller cannot see.
730
- *
731
- * SSR left no slot (SPA navigation renders into empty elements): fall back to
732
- * a fresh `insert`.
733
- */
734
- export function hydrateSlot(
735
- nodes: ChildNode[],
736
- parent: Element | DocumentFragment,
737
- value: unknown,
738
- ): void {
739
- let open = -1;
740
- for (let i = 0; i < nodes.length; i++) {
741
- const node = nodes[i];
742
- if (node instanceof Comment && node.data === "g") {
743
- open = i;
744
- break;
745
- }
746
- }
747
- if (open === -1) {
748
- insert(parent, value);
749
- return;
750
- }
751
- let close = open + 1;
752
- while (close < nodes.length) {
753
- const node = nodes[close];
754
- if (node instanceof Comment && node.data === "/g") break;
755
- close++;
756
- }
757
- const inner = nodes.slice(open + 1, close);
758
- // Drop the whole run so later siblings can't claim slot content.
759
- nodes.splice(open, close - open + 1);
760
- pushHydrationNodes(inner);
761
- try {
762
- attachHydrated(parent, value);
763
- } finally {
764
- popHydrationNodes();
765
- }
766
- }
767
-
768
- /**
769
- * Realize a slot value that already has SSR markup in the DOM: run thunks,
770
- * skip primitives (their text is already rendered), and append only nodes
771
- * that hydration created fresh instead of claiming.
772
- */
773
- function attachHydrated(
774
- parent: Element | DocumentFragment,
775
- value: unknown,
776
- ): void {
777
- if (typeof value === "function") {
778
- attachHydrated(parent, (value as () => unknown)());
779
- return;
780
- }
781
- if (Array.isArray(value)) {
782
- for (const item of value) attachHydrated(parent, item);
783
- return;
784
- }
785
- if (value instanceof Node && value.parentNode !== parent) {
786
- parent.appendChild(value);
787
- }
788
- }
789
-
790
- /**
791
- * Apply a use: directive to an element.
792
- * The directive function receives (element, params) and may return a cleanup function.
793
- * Cleanup runs when the enclosing $effect re-runs or the component is destroyed.
794
- */
795
- export type Directive = (
796
- node: Element,
797
- params: unknown,
798
- ) => undefined | (() => void);
799
-
800
- export function applyDirective(
801
- node: Element,
802
- directive: Directive | [Directive, unknown],
803
- ): void {
804
- const [fn, params] = Array.isArray(directive)
805
- ? directive
806
- : [directive, undefined];
807
- const cleanup = fn(node, params);
808
- if (typeof cleanup === "function") {
809
- createEffect(() => () => cleanup());
810
- }
811
- }
812
-
813
- export type ContextKey<T> = symbol & { __type: T };
814
-
815
- const clientContextStore = new Map<symbol, unknown>();
816
-
817
- let storeProvider: (() => Map<symbol, unknown>) | null = null;
818
- export function __setStoreProvider(fn: () => Map<symbol, unknown>) {
819
- storeProvider = fn;
820
- }
821
-
822
- function getStore(): Map<symbol, unknown> {
823
- return storeProvider?.() ?? clientContextStore;
824
- }
825
-
826
- export function createContext<T>(): ContextKey<T> {
827
- return Symbol() as ContextKey<T>;
828
- }
829
-
830
- export function setContext<T>(key: ContextKey<T>, value: T): void {
831
- getStore().set(key as unknown as symbol, value);
832
- }
833
-
834
- export function getContext<T>(key: ContextKey<T>): T {
835
- return getStore().get(key as unknown as symbol) as T;
836
- }
837
-
838
- const _hydrationStack: ChildNode[][] = [];
839
-
840
- export function pushHydrationNodes(nodes: ChildNode[]): void {
841
- _hydrationStack.push(nodes);
842
- }
843
-
844
- export function popHydrationNodes(): void {
845
- _hydrationStack.pop();
846
- }
847
-
848
- export function getHydrationNodes(): ChildNode[] {
849
- return _hydrationStack[_hydrationStack.length - 1] ?? [];
850
- }
1
+ export { __asyncBoundary } from "./async-boundary.ts";
2
+ export { Boundary } from "./boundary";
3
+ export {
4
+ easeInCubic,
5
+ easeInOutCubic,
6
+ easeInOutQuad,
7
+ easeInOutQuart,
8
+ easeInOutQuint,
9
+ easeInOutSine,
10
+ easeInQuad,
11
+ easeInQuart,
12
+ easeInQuint,
13
+ easeInSine,
14
+ easeOutCubic,
15
+ easeOutQuad,
16
+ easeOutQuart,
17
+ easeOutQuint,
18
+ easeOutSine,
19
+ linear,
20
+ } from "./easing.ts";
21
+ export { ReactiveMap } from "./reactivity/map.ts";
22
+ export { ReactiveSet } from "./reactivity/set.ts";
23
+ export { mountTransition, removeAnimated } from "./transition.ts";
24
+
25
+ export const SIGIL_SAFE = Symbol.for("sigil.safe");
26
+ export class SafeHtml {
27
+ [SIGIL_SAFE] = true;
28
+ constructor(public v: string) {}
29
+ toString() {
30
+ return this.v;
31
+ }
32
+ }
33
+
34
+ let currentEffect: (() => void) | null = null;
35
+ let currentDeps: Set<Set<() => void>> | null = null;
36
+
37
+ let batchDepth = 0;
38
+ let scheduledFlush = false;
39
+ const pendingEffects = new Set<() => void>();
40
+ const pendingPreEffects = new Set<() => void>();
41
+
42
+ function flush() {
43
+ scheduledFlush = false;
44
+ // biome-ignore lint/suspicious/useIterableCallbackReturn: effects returning cleanup is intended
45
+ pendingPreEffects.forEach((e) => e());
46
+ pendingPreEffects.clear();
47
+ // biome-ignore lint/suspicious/useIterableCallbackReturn: effects returning cleanup is intended
48
+ pendingEffects.forEach((e) => e());
49
+ pendingEffects.clear();
50
+ }
51
+
52
+ function scheduleEffect(fn: () => void) {
53
+ const target = (fn as any).__sigil_pre ? pendingPreEffects : pendingEffects;
54
+ target.add(fn);
55
+ if (batchDepth === 0 && !scheduledFlush) {
56
+ scheduledFlush = true;
57
+ queueMicrotask(flush);
58
+ }
59
+ }
60
+
61
+ const targetDepsMap = new WeakMap<
62
+ object,
63
+ Map<string | symbol, Set<() => void>>
64
+ >();
65
+
66
+ function getDeps(target: object, key: string | symbol): Set<() => void> {
67
+ let deps = targetDepsMap.get(target);
68
+ if (!deps) {
69
+ deps = new Map();
70
+ targetDepsMap.set(target, deps);
71
+ }
72
+ let set = deps.get(key);
73
+ if (!set) {
74
+ set = new Set();
75
+ deps.set(key, set);
76
+ }
77
+ return set;
78
+ }
79
+
80
+ function track(target: object, key: string | symbol) {
81
+ if (currentEffect && currentDeps) {
82
+ const deps = getDeps(target, key);
83
+ deps.add(currentEffect);
84
+ currentDeps.add(deps); // Set, deduplicates automatically
85
+ }
86
+ }
87
+
88
+ function trigger(target: object, key: string | symbol) {
89
+ const deps = targetDepsMap.get(target);
90
+ if (!deps) return;
91
+ const set = deps.get(key);
92
+ if (!set) return;
93
+ for (const fn of [...set]) {
94
+ scheduleEffect(fn);
95
+ }
96
+ }
97
+
98
+ const proxyCache = new WeakMap<object, object>();
99
+ const proxyToTarget = new WeakMap<object, object>();
100
+ const reactiveTargets = new WeakSet<object>();
101
+ const ARRAY_MUTATORS = new Set([
102
+ "push",
103
+ "pop",
104
+ "shift",
105
+ "unshift",
106
+ "splice",
107
+ "sort",
108
+ "reverse",
109
+ "fill",
110
+ ]);
111
+
112
+ function createReactiveProxy<T extends object>(target: T): T {
113
+ const existing = proxyCache.get(target);
114
+ if (existing) return existing as T;
115
+
116
+ const proxy = new Proxy(target, {
117
+ get(target, key, receiver) {
118
+ if (
119
+ Array.isArray(target) &&
120
+ typeof key === "string" &&
121
+ ARRAY_MUTATORS.has(key)
122
+ ) {
123
+ return (...args: any[]) => {
124
+ const result = (target as any)[key](...args);
125
+ trigger(target, "length");
126
+ // trigger all numeric keys that changed — for splice/sort
127
+ // triggering length is sufficient for most reactive patterns
128
+ return result;
129
+ };
130
+ }
131
+ if (key === "set") {
132
+ return (newValue: T) => {
133
+ const oldKeys = new Set(Object.keys(target));
134
+ const newKeys = new Set(Object.keys(newValue));
135
+ for (const k of oldKeys) {
136
+ if (!newKeys.has(k)) {
137
+ delete (target as any)[k];
138
+ trigger(target, k);
139
+ }
140
+ }
141
+ for (const k of newKeys) {
142
+ (target as any)[k] = (newValue as any)[k];
143
+ trigger(target, k);
144
+ }
145
+ if (Array.isArray(target)) {
146
+ // delete leaves holes — length must shrink to the new value's,
147
+ // or iteration (spread, reconcile) sees phantom trailing slots
148
+ target.length = (newValue as unknown[]).length;
149
+ trigger(target, "length");
150
+ }
151
+ };
152
+ }
153
+
154
+ if (key === "peek") {
155
+ return () => target;
156
+ }
157
+
158
+ if (typeof key === "symbol") {
159
+ return Reflect.get(target, key, receiver);
160
+ }
161
+
162
+ track(target, key);
163
+ const value = target[key as keyof T];
164
+
165
+ if (typeof value === "object" && value !== null) {
166
+ return createReactiveProxy(value);
167
+ }
168
+
169
+ return value;
170
+ },
171
+
172
+ set(target, key, newValue, receiver) {
173
+ const oldValue = target[key as keyof T];
174
+ const result = Reflect.set(target, key, newValue, receiver);
175
+ if (oldValue !== newValue) {
176
+ trigger(target, key as string | symbol);
177
+ if (
178
+ Array.isArray(target) &&
179
+ typeof key === "string" &&
180
+ !Number.isNaN(Number(key))
181
+ ) {
182
+ trigger(target, "length");
183
+ }
184
+ }
185
+ return result;
186
+ },
187
+
188
+ deleteProperty(target, key) {
189
+ const result = Reflect.deleteProperty(target, key);
190
+ trigger(target, key as string | symbol);
191
+ return result;
192
+ },
193
+ });
194
+
195
+ proxyCache.set(target, proxy);
196
+ proxyToTarget.set(proxy, target);
197
+ reactiveTargets.add(target);
198
+ return proxy as T;
199
+ }
200
+
201
+ // ─── createSignal (branches on type) ───
202
+
203
+ export type Signal<T> = {
204
+ (): T;
205
+ set: (next: T) => void;
206
+ peek: () => T;
207
+ };
208
+
209
+ export function batch(fn: () => void) {
210
+ batchDepth++;
211
+ fn();
212
+ batchDepth--;
213
+ if (batchDepth === 0) {
214
+ scheduledFlush = false;
215
+ flush();
216
+ }
217
+ }
218
+
219
+ export function tick(): Promise<void> {
220
+ return new Promise((resolve) => queueMicrotask(resolve));
221
+ }
222
+
223
+ function createPrimitiveSignal<T>(initial: T): Signal<T> {
224
+ const subs = new Set<() => void>();
225
+ let value = initial;
226
+
227
+ const getter = () => {
228
+ if (currentEffect && currentDeps) {
229
+ subs.add(currentEffect);
230
+ currentDeps.add(subs);
231
+ }
232
+ return value;
233
+ };
234
+
235
+ getter.set = (next: T) => {
236
+ value = next;
237
+ for (const fn of [...subs]) {
238
+ scheduleEffect(fn);
239
+ }
240
+ };
241
+
242
+ getter.peek = () => value;
243
+
244
+ return getter;
245
+ }
246
+
247
+ export function createSignal<T>(initial: T): Signal<T> {
248
+ if (typeof initial === "object" && initial !== null) {
249
+ const proxy = createReactiveProxy(initial);
250
+ const getter = () => {
251
+ // array signals: auto-track length so push/pop/splice re-run effects
252
+ if (Array.isArray(initial)) {
253
+ track(initial, "length");
254
+ }
255
+ return proxy;
256
+ };
257
+ getter.set = (next: T) => (proxy as any).set(next);
258
+ getter.peek = () => initial;
259
+ return getter;
260
+ }
261
+
262
+ return createPrimitiveSignal(initial);
263
+ }
264
+
265
+ // A1: $state.raw — create signal without Proxy wrapping for objects/arrays
266
+ export function createRawSignal<T>(initial: T): Signal<T> {
267
+ return createPrimitiveSignal(initial);
268
+ }
269
+
270
+ // A2: $state.snapshot — deep un-proxy a signal value
271
+ function deepUnproxy<T>(value: T): T {
272
+ if (typeof value !== "object" || value === null) return value;
273
+ const raw = proxyToTarget.get(value as object);
274
+ if (!raw) return value; // not a proxy, return as-is
275
+ if (Array.isArray(raw)) {
276
+ return raw.map(deepUnproxy) as T;
277
+ }
278
+ const result: Record<string, unknown> = {};
279
+ for (const key of Object.keys(raw)) {
280
+ result[key] = deepUnproxy((raw as Record<string, unknown>)[key]);
281
+ }
282
+ return result as T;
283
+ }
284
+
285
+ export function snapshot<T>(value: T): T {
286
+ return deepUnproxy(value);
287
+ }
288
+
289
+ // A3: $effect.tracking() — check if inside reactive context
290
+ export function tracking(): boolean {
291
+ return currentEffect !== null;
292
+ }
293
+
294
+ /**
295
+ * Run fn() outside of any reactive context: signal reads inside fn() do not
296
+ * register dependencies on the enclosing effect.
297
+ */
298
+ export function untrack<T>(fn: () => T): T {
299
+ const prevEffect = currentEffect;
300
+ const prevDeps = currentDeps;
301
+ currentEffect = null;
302
+ currentDeps = null;
303
+ try {
304
+ return fn();
305
+ } finally {
306
+ currentEffect = prevEffect;
307
+ currentDeps = prevDeps;
308
+ }
309
+ }
310
+
311
+ // A4: $inspect — dev-only effect logging
312
+ export function createInspectEffect(
313
+ getValues: () => unknown[],
314
+ cb?: (vals: unknown[]) => void,
315
+ ): void {
316
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "production")
317
+ return;
318
+ createEffect(() => {
319
+ const vals = getValues();
320
+ if (cb) cb(vals);
321
+ else console.log(...vals);
322
+ });
323
+ }
324
+
325
+ // A5: $effect.pre — effect that flushes before DOM update
326
+ export function createEffectPre(
327
+ fn: () => undefined | (() => void),
328
+ ): () => void {
329
+ let cleanup: (() => void) | undefined;
330
+ const ownDeps = new Set<Set<() => void>>();
331
+
332
+ const effect = () => {
333
+ if (cleanup) cleanup();
334
+ for (const depSet of ownDeps) depSet.delete(effect);
335
+ ownDeps.clear();
336
+
337
+ const prevEffect = currentEffect;
338
+ const prevDeps = currentDeps;
339
+ currentEffect = effect;
340
+ currentDeps = ownDeps;
341
+ try {
342
+ cleanup = fn();
343
+ } finally {
344
+ currentEffect = prevEffect;
345
+ currentDeps = prevDeps;
346
+ }
347
+ };
348
+
349
+ (effect as any).__sigil_pre = true;
350
+ effect();
351
+
352
+ const dispose = () => {
353
+ for (const depSet of ownDeps) depSet.delete(effect);
354
+ ownDeps.clear();
355
+ if (cleanup) cleanup();
356
+ };
357
+
358
+ ((globalThis as any).__sigilEffectScope as (() => void)[] | undefined)?.push(
359
+ dispose,
360
+ );
361
+ return dispose;
362
+ }
363
+
364
+ // A9: Profiler effect timing (dev)
365
+ export function createProfilerEffect(
366
+ _name: string,
367
+ fn: () => undefined | (() => void),
368
+ ): () => void {
369
+ return createEffect(() => {
370
+ if (
371
+ typeof process !== "undefined" &&
372
+ process.env.NODE_ENV === "production"
373
+ ) {
374
+ return fn();
375
+ }
376
+ const _start = performance.now();
377
+ const cleanup = fn();
378
+ const _end = performance.now();
379
+ // console.log(`[Profiler] ${name}: ${(end - start).toFixed(2)}ms`);
380
+ return cleanup;
381
+ });
382
+ }
383
+
384
+ // Deferred effect mode for hydration: effects created while the flag is set
385
+ // are queued instead of run immediately, then flushed after DOM insertion.
386
+ const deferredEffectQueue: (() => void)[] = [];
387
+
388
+ export function flushDeferredEffects(): void {
389
+ const pending = deferredEffectQueue.splice(0);
390
+ for (const run of pending) run();
391
+ }
392
+
393
+ // biome-ignore lint/suspicious/noConfusingVoidType: please shut up its a weird type
394
+ export function createEffect(fn: () => void | (() => void)): () => void {
395
+ let cleanup: (() => void) | undefined;
396
+ const ownDeps = new Set<Set<() => void>>();
397
+
398
+ const effect = () => {
399
+ if (cleanup) cleanup();
400
+ for (const depSet of ownDeps) depSet.delete(effect);
401
+ ownDeps.clear();
402
+
403
+ const prevEffect = currentEffect;
404
+ const prevDeps = currentDeps;
405
+ currentEffect = effect;
406
+ currentDeps = ownDeps;
407
+ try {
408
+ //@ts-expect-error kill yourself
409
+ cleanup = fn();
410
+ } finally {
411
+ currentEffect = prevEffect;
412
+ currentDeps = prevDeps;
413
+ }
414
+ };
415
+
416
+ // In deferred mode (hydration), queue the effect instead of running immediately.
417
+ // This ensures the DOM is inserted before effect callbacks query it.
418
+ if ((globalThis as any).__sigilDeferEffects) {
419
+ deferredEffectQueue.push(() => effect());
420
+ } else {
421
+ effect();
422
+ }
423
+
424
+ const dispose = () => {
425
+ for (const depSet of ownDeps) depSet.delete(effect);
426
+ ownDeps.clear();
427
+ if (cleanup) cleanup();
428
+ };
429
+
430
+ ((globalThis as any).__sigilEffectScope as (() => void)[] | undefined)?.push(
431
+ dispose,
432
+ );
433
+ return dispose;
434
+ }
435
+
436
+ /**
437
+ * Run fn() and return a dispose function that tears down every effect
438
+ * created during that call (including effects inside child createMemo calls).
439
+ * Supports nesting: inner scopes don't leak to outer ones.
440
+ */
441
+ export function withEffectScope(fn: () => void): () => void {
442
+ const prev = (globalThis as any).__sigilEffectScope;
443
+ const disposers: (() => void)[] = [];
444
+ (globalThis as any).__sigilEffectScope = disposers;
445
+ try {
446
+ fn();
447
+ } finally {
448
+ (globalThis as any).__sigilEffectScope = prev;
449
+ }
450
+ return () => {
451
+ for (const d of disposers) d();
452
+ disposers.length = 0;
453
+ };
454
+ }
455
+
456
+ type EffectScopeGlobal = { __sigilEffectScope?: (() => void)[] };
457
+
458
+ /**
459
+ * Run fn() with a detached effect scope. Effects created inside are invisible
460
+ * to enclosing scopes (the scope array is replaced, not merged) and live until
461
+ * dispose() is called — for app bootstrap, routers, and long-lived listeners.
462
+ */
463
+ export function createRoot<T>(fn: (dispose: () => void) => T): T {
464
+ const g = globalThis as EffectScopeGlobal;
465
+ const prev = g.__sigilEffectScope;
466
+ const disposers: (() => void)[] = [];
467
+ g.__sigilEffectScope = disposers;
468
+ const dispose = () => {
469
+ for (const d of disposers.splice(0)) d();
470
+ };
471
+ try {
472
+ return fn(dispose);
473
+ } finally {
474
+ g.__sigilEffectScope = prev;
475
+ }
476
+ }
477
+
478
+ export interface Resource<T> {
479
+ data: () => T | undefined;
480
+ loading: () => boolean;
481
+ error: () => Error | undefined;
482
+ refetch: () => void;
483
+ }
484
+
485
+ /**
486
+ * Async data source with reactive re-fetching. Re-runs when `source()` changes
487
+ * or refetch() is called; stale responses are discarded by request id.
488
+ */
489
+ export function createResource<T>(
490
+ fetcher: (source: unknown, info: { refetch: () => void }) => Promise<T>,
491
+ source?: () => unknown,
492
+ ): Resource<T> {
493
+ const data = createSignal<T | undefined>(undefined);
494
+ const loading = createSignal(true);
495
+ const error = createSignal<Error | undefined>(undefined);
496
+ const version = createSignal(0);
497
+ let requestCount = 0;
498
+ let versionCounter = 0;
499
+
500
+ const refetch = () => {
501
+ versionCounter++;
502
+ version.set(versionCounter);
503
+ };
504
+
505
+ createEffect(() => {
506
+ const src = source?.();
507
+ version(); // track refetch bumps
508
+ const id = ++requestCount;
509
+ loading.set(true);
510
+ error.set(undefined);
511
+ fetcher(src, { refetch }).then(
512
+ (result) => {
513
+ if (id !== requestCount) return; // stale response
514
+ data.set(result);
515
+ loading.set(false);
516
+ },
517
+ (err: unknown) => {
518
+ if (id !== requestCount) return;
519
+ error.set(err instanceof Error ? err : new Error(String(err)));
520
+ loading.set(false);
521
+ },
522
+ );
523
+ });
524
+
525
+ return { data, loading, error, refetch };
526
+ }
527
+
528
+ export function createMemo<T>(fn: () => T): Signal<T> {
529
+ const inner = createSignal<T>(undefined as T);
530
+ createEffect(() => inner.set(fn()));
531
+ return inner;
532
+ }
533
+
534
+ /**
535
+ * Reconcile a list of keyed DOM nodes.
536
+ * anchor.before(node) handles both insert and move natively.
537
+ * @param claimNode - Optional hydration callback. Called with (element, key) for
538
+ * server-rendered elements removed from the DOM. Returns the element to use,
539
+ * or null to discard.
540
+ */
541
+ const lastItemFor = new WeakMap<object, unknown>();
542
+
543
+ export function reconcile<T>(
544
+ anchor: Partial<Comment>,
545
+ keyMap: Map<unknown, Node>,
546
+ newItems: T[],
547
+ getKey: (item: T, index: number) => unknown,
548
+ createNode: (item: T) => Node,
549
+ // is this meant to be unused? claimNode?: (element: Element, key: unknown) => Element | null,
550
+ ): void {
551
+ const newKeys = new Set(newItems.map((item, i) => getKey(item, i)));
552
+
553
+ // Remove nodes no longer in list (or claim them for hydration)
554
+ for (const [key, node] of keyMap) {
555
+ if (!newKeys.has(key)) {
556
+ node.parentNode?.removeChild(node);
557
+ keyMap.delete(key);
558
+ }
559
+ }
560
+
561
+ // Insert/move in order — anchor.before() handles both cases.
562
+ // A surviving node whose item instance changed is rebuilt: compiled row
563
+ // bodies bake item reads at creation time, so immutable-style updates
564
+ // (new object, same key) must swap the node to show fresh content.
565
+ for (let i = 0; i < newItems.length; i++) {
566
+ const item = newItems[i]!;
567
+ const key = getKey(item, i);
568
+ let node = keyMap.get(key);
569
+ if (
570
+ node &&
571
+ lastItemFor.has(node) &&
572
+ !Object.is(lastItemFor.get(node), item)
573
+ ) {
574
+ node.parentNode?.removeChild(node);
575
+ keyMap.delete(key);
576
+ node = undefined;
577
+ }
578
+ if (!node) {
579
+ node = createNode(item);
580
+ lastItemFor.set(node, item);
581
+ keyMap.set(key, node);
582
+ }
583
+ anchor.before?.(node);
584
+ }
585
+ }
586
+
587
+ /**
588
+ * Claim an existing element from a hydration pool by tag name, or create a new one.
589
+ * Removes the claimed node from the pool array.
590
+ * When falling back to createElement, appends to parent if provided (SPA mode).
591
+ * SVG elements (and children of SVG parents) are created with createElementNS —
592
+ * plain createElement puts them in the HTML namespace where they render as
593
+ * invisible unknown elements (killed CSR-rendered inline SVG, e.g. topbar icons).
594
+ */
595
+ const SVG_NS = "http://www.w3.org/2000/svg";
596
+
597
+ export function claim(
598
+ nodes: ChildNode[],
599
+ tag: string,
600
+ parent?: Element,
601
+ ): Element {
602
+ for (let i = 0; i < nodes.length; i++) {
603
+ const node = nodes[i];
604
+ if (
605
+ node instanceof Element &&
606
+ node.tagName.toLowerCase() === tag.toLowerCase()
607
+ ) {
608
+ // SSR injects a _csrf hidden input as the first child of every <form>
609
+ // (rendering/index.ts). The compiled hydration code doesn't know about
610
+ // it, so it must never be claimed — claiming it shifts the whole chain
611
+ // by one and duplicates the last form child (e.g. two display_name
612
+ // inputs). Skip it; it stays in place as a live DOM node.
613
+ if (
614
+ tag.toLowerCase() === "input" &&
615
+ node.hasAttribute("data-grimoire-csrf")
616
+ ) {
617
+ continue;
618
+ }
619
+ nodes.splice(i, 1);
620
+ return node;
621
+ }
622
+ }
623
+ const el =
624
+ tag.toLowerCase() === "svg" || parent?.namespaceURI === SVG_NS
625
+ ? document.createElementNS(SVG_NS, tag)
626
+ : document.createElement(tag);
627
+ if (parent) parent.appendChild(el);
628
+ return el;
629
+ }
630
+
631
+ /**
632
+ * Write a JSX prop to an element. On HTML elements this is `el[name] = value`
633
+ * (preserves IDL semantics for value/checked/etc) whenever the element has a
634
+ * writable property of that name. Names with no writable property go through
635
+ * setAttribute instead, like SSR does: some IDL attributes are getter-only
636
+ * (`input.list`, `input.form`, `button.form`), and assigning them throws and
637
+ * aborts the whole render; unknown names would otherwise land as a bare JS
638
+ * expando the DOM never sees. On SVG-namespace elements everything is
639
+ * attribute-routed — IDL property assignment throws there too (`svg.width`).
640
+ */
641
+ const SVG_ATTR_FIX: Record<string, string> = {
642
+ className: "class",
643
+ htmlFor: "for",
644
+ };
645
+
646
+ // Never attribute-routed, even inside SVG.
647
+ const SVG_PROP_ONLY = new Set(["textContent", "innerHTML", "outerHTML"]);
648
+
649
+ // Per-prototype cache of "can `el[name] = v` be assigned?".
650
+ const writableCache = new WeakMap<object, Map<string, boolean>>();
651
+
652
+ function isWritableProp(el: Element, name: string): boolean {
653
+ const proto = Object.getPrototypeOf(el) as object;
654
+ let cache = writableCache.get(proto);
655
+ if (!cache) writableCache.set(proto, (cache = new Map()));
656
+ let writable = cache.get(name);
657
+ if (writable === undefined) {
658
+ writable = false;
659
+ for (let o: object | null = proto; o; o = Object.getPrototypeOf(o)) {
660
+ const d = Object.getOwnPropertyDescriptor(o, name);
661
+ if (d) {
662
+ writable = !!(d.set || d.writable);
663
+ break;
664
+ }
665
+ }
666
+ cache.set(name, writable);
667
+ }
668
+ // Own properties (expandos set earlier) are always assignable.
669
+ return writable || Object.hasOwn(el, name);
670
+ }
671
+
672
+ function setAttr(el: Element, attr: string, value: unknown): void {
673
+ if (value == null || value === false) el.removeAttribute(attr);
674
+ else el.setAttribute(attr, value === true ? "" : String(value));
675
+ }
676
+
677
+ export function setProp(el: Element, name: string, value: unknown): void {
678
+ if (el.namespaceURI === SVG_NS) {
679
+ if (SVG_PROP_ONLY.has(name))
680
+ (el as unknown as Record<string, unknown>)[name] = value;
681
+ else setAttr(el, SVG_ATTR_FIX[name] ?? name, value);
682
+ } else if (isWritableProp(el, name)) {
683
+ (el as unknown as Record<string, unknown>)[name] = value;
684
+ } else {
685
+ setAttr(el, name, value);
686
+ }
687
+ }
688
+
689
+ /**
690
+ * Claim an existing Text node from a hydration pool, or create a new empty one.
691
+ * Removes the claimed node from the pool array.
692
+ * When falling back to createTextNode, appends to parent if provided (SPA mode).
693
+ */
694
+ export function claimText(nodes: ChildNode[], parent?: Element): Text {
695
+ for (let i = 0; i < nodes.length; i++) {
696
+ const node = nodes[i];
697
+ if (node instanceof Text) {
698
+ nodes.splice(i, 1);
699
+ return node;
700
+ }
701
+ }
702
+ const text = document.createTextNode("");
703
+ if (parent) parent.appendChild(text);
704
+ return text;
705
+ }
706
+
707
+ /**
708
+ * Claim an existing Comment node from a hydration pool, or create a new one.
709
+ * Removes the claimed node from the pool array.
710
+ * When falling back to createComment, appends to parent if provided (SPA mode).
711
+ */
712
+ export function claimComment(
713
+ nodes: ChildNode[],
714
+ text: string = "",
715
+ parent?: Element,
716
+ ): Comment {
717
+ for (let i = 0; i < nodes.length; i++) {
718
+ const node = nodes[i];
719
+ if (node instanceof Comment && node.data === text) {
720
+ nodes.splice(i, 1);
721
+ return node;
722
+ }
723
+ }
724
+ const comment = document.createComment(text);
725
+ if (parent) parent.appendChild(comment);
726
+ return comment;
727
+ }
728
+
729
+ /**
730
+ * Hydrate a keyed list: claim the comment anchor, walk its sibling elements
731
+ * to build a keyMap, then reconcile with signal data.
732
+ *
733
+ * SSR renders items as flat siblings. Hydration claims them by position,
734
+ * builds the keyMap, removes from DOM, then reconcile re-inserts in order.
735
+ */
736
+ export function hydrateKeyedList<T>(
737
+ nodesVar: ChildNode[],
738
+ signalItems: T[],
739
+ getKey: (item: T, index: number) => unknown,
740
+ createNode: (item: T) => Node,
741
+ parent?: Element,
742
+ ): { anchor: Comment; keyMap: Map<unknown, Node> } {
743
+ // 1. Claim the <!--g--> opening delimiter as anchor
744
+ const anchor = claimComment(nodesVar, "g", parent);
745
+
746
+ // 2. Walk siblings after anchor, collect elements up to <!--/g-->, build keyMap
747
+ const keyMap = new Map<unknown, Node>();
748
+ const anchorParent = anchor.parentNode;
749
+ if (anchorParent && signalItems.length > 0) {
750
+ const claimed: Element[] = [];
751
+ let next = anchor.nextSibling;
752
+ while (next) {
753
+ const current = next;
754
+ next = next.nextSibling;
755
+ // Stop at closing <!--/g--> delimiter and consume it
756
+ if (current instanceof Comment && current.data === "/g") {
757
+ current.remove();
758
+ break;
759
+ }
760
+ if (current instanceof Element) {
761
+ current.remove();
762
+ claimed.push(current);
763
+ }
764
+ }
765
+ // Map claimed elements to keys by index
766
+ for (let i = 0; i < claimed.length && i < signalItems.length; i++) {
767
+ //@ts-expect-error i is always in bounds
768
+ const key = getKey(signalItems[i], i);
769
+ //@ts-expect-error i is always in bounds
770
+ keyMap.set(key, claimed[i]);
771
+ }
772
+ }
773
+
774
+ // 3. Reconcile — keyMap is pre-populated with claimed nodes
775
+ reconcile(anchor, keyMap, signalItems, getKey, createNode);
776
+ return { anchor, keyMap };
777
+ }
778
+
779
+ export function insert(
780
+ parent: Element | DocumentFragment,
781
+ value: unknown,
782
+ ): void {
783
+ if (value === false || value === null || value === undefined) return;
784
+ if (typeof value === "function") {
785
+ insert(parent, value());
786
+ return;
787
+ }
788
+ if (Array.isArray(value)) {
789
+ for (const item of value) insert(parent, item);
790
+ return;
791
+ }
792
+ if (value instanceof Node) {
793
+ parent.appendChild(value);
794
+ return;
795
+ }
796
+ parent.append(String(value));
797
+ }
798
+
799
+ /**
800
+ * Hydrate a `<!--g-->…<!--/g-->` slot.
801
+ *
802
+ * Consumes the delimiter pair and the SSR content between them from `nodes`,
803
+ * then runs `value` against that content as its hydration pool. Component
804
+ * children are compiled to thunks precisely so this call — not the caller's
805
+ * pool — decides what they claim: `<Wrap><Item/></Wrap>` puts `Item`'s SSR
806
+ * markup inside `Wrap`'s root, which the caller cannot see.
807
+ *
808
+ * SSR left no slot (SPA navigation renders into empty elements): fall back to
809
+ * a fresh `insert`.
810
+ */
811
+ export function hydrateSlot(
812
+ nodes: ChildNode[],
813
+ parent: Element | DocumentFragment,
814
+ value: unknown,
815
+ ): void {
816
+ let open = -1;
817
+ for (let i = 0; i < nodes.length; i++) {
818
+ const node = nodes[i];
819
+ if (node instanceof Comment && node.data === "g") {
820
+ open = i;
821
+ break;
822
+ }
823
+ }
824
+ if (open === -1) {
825
+ insert(parent, value);
826
+ return;
827
+ }
828
+ let close = open + 1;
829
+ while (close < nodes.length) {
830
+ const node = nodes[close];
831
+ if (node instanceof Comment && node.data === "/g") break;
832
+ close++;
833
+ }
834
+ const inner = nodes.slice(open + 1, close);
835
+ // Drop the whole run so later siblings can't claim slot content.
836
+ nodes.splice(open, close - open + 1);
837
+ pushHydrationNodes(inner);
838
+ try {
839
+ attachHydrated(parent, value);
840
+ } finally {
841
+ popHydrationNodes();
842
+ }
843
+ }
844
+
845
+ /**
846
+ * Realize a slot value that already has SSR markup in the DOM: run thunks,
847
+ * skip primitives (their text is already rendered), and append only nodes
848
+ * that hydration created fresh instead of claiming.
849
+ */
850
+ function attachHydrated(
851
+ parent: Element | DocumentFragment,
852
+ value: unknown,
853
+ ): void {
854
+ if (typeof value === "function") {
855
+ attachHydrated(parent, (value as () => unknown)());
856
+ return;
857
+ }
858
+ if (Array.isArray(value)) {
859
+ for (const item of value) attachHydrated(parent, item);
860
+ return;
861
+ }
862
+ if (value instanceof Node) {
863
+ // During hydration the parent's SSR-rendered children are already in
864
+ // the DOM. A freshly-created JSX Node for the same slot is a duplicate
865
+ // — appending it doubles the content (e.g. a `<span>` rendered both
866
+ // server-side and as a JSX value prop). Keep the SSR node, drop the clone.
867
+ // A node that already sits in the DOM was claimed from SSR markup:
868
+ // leave it where it is.
869
+ if (parent.childNodes.length > 0 || value.parentNode) return;
870
+ parent.appendChild(value);
871
+ }
872
+ }
873
+
874
+ /**
875
+ * Apply a use: directive to an element.
876
+ * The directive function receives (element, params) and may return a cleanup function.
877
+ * Cleanup runs when the enclosing $effect re-runs or the component is destroyed.
878
+ */
879
+ export type Directive = (
880
+ node: Element,
881
+ params: unknown,
882
+ ) => undefined | (() => void);
883
+
884
+ export function applyDirective(
885
+ node: Element,
886
+ directive: Directive | [Directive, unknown],
887
+ ): void {
888
+ const [fn, params] = Array.isArray(directive)
889
+ ? directive
890
+ : [directive, undefined];
891
+ const cleanup = fn(node, params);
892
+ if (typeof cleanup === "function") {
893
+ createEffect(() => () => cleanup());
894
+ }
895
+ }
896
+
897
+ export type ContextKey<T> = symbol & { __type: T };
898
+
899
+ const clientContextStore = new Map<symbol, unknown>();
900
+
901
+ let storeProvider: (() => Map<symbol, unknown>) | null = null;
902
+ export function __setStoreProvider(fn: () => Map<symbol, unknown>) {
903
+ storeProvider = fn;
904
+ }
905
+
906
+ function getStore(): Map<symbol, unknown> {
907
+ return storeProvider?.() ?? clientContextStore;
908
+ }
909
+
910
+ export function createContext<T>(): ContextKey<T> {
911
+ return Symbol() as ContextKey<T>;
912
+ }
913
+
914
+ export function setContext<T>(key: ContextKey<T>, value: T): void {
915
+ getStore().set(key as unknown as symbol, value);
916
+ }
917
+
918
+ export function getContext<T>(key: ContextKey<T>): T {
919
+ return getStore().get(key as unknown as symbol) as T;
920
+ }
921
+
922
+ const _hydrationStack: ChildNode[][] = [];
923
+
924
+ export function pushHydrationNodes(nodes: ChildNode[]): void {
925
+ _hydrationStack.push(nodes);
926
+ }
927
+
928
+ export function popHydrationNodes(): void {
929
+ _hydrationStack.pop();
930
+ }
931
+
932
+ export function getHydrationNodes(): ChildNode[] {
933
+ return _hydrationStack[_hydrationStack.length - 1] ?? [];
934
+ }