@sigil-dev/runtime 0.9.2 → 0.9.4

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/index.ts CHANGED
@@ -1,655 +1,760 @@
1
- export { Boundary } from "./boundary";
2
- export {
3
- easeInCubic,
4
- easeInOutCubic,
5
- easeInOutQuad,
6
- easeInOutQuart,
7
- easeInOutQuint,
8
- easeInOutSine,
9
- easeInQuad,
10
- easeInQuart,
11
- easeInQuint,
12
- easeInSine,
13
- easeOutCubic,
14
- easeOutQuad,
15
- easeOutQuart,
16
- easeOutQuint,
17
- easeOutSine,
18
- linear,
19
- } from "./easing.ts";
20
- export { ReactiveMap } from "./reactivity/map.ts";
21
- export { ReactiveSet } from "./reactivity/set.ts";
22
- export {__asyncBoundary} from "./async-boundary.ts"
23
-
24
- export const SIGIL_SAFE = Symbol.for("sigil.safe");
25
- export class SafeHtml {
26
- [SIGIL_SAFE] = true;
27
- constructor(public v: string) {}
28
- toString() {
29
- return this.v;
30
- }
31
- }
32
-
33
- let currentEffect: (() => void) | null = null;
34
- let currentDeps: Set<Set<() => void>> | null = null;
35
-
36
- let batchDepth = 0;
37
- let scheduledFlush = false;
38
- const pendingEffects = new Set<() => void>();
39
- const pendingPreEffects = new Set<() => void>();
40
-
41
- function flush() {
42
- scheduledFlush = false;
43
- // biome-ignore lint/suspicious/useIterableCallbackReturn: effects returning cleanup is intended
44
- pendingPreEffects.forEach((e) => e());
45
- pendingPreEffects.clear();
46
- // biome-ignore lint/suspicious/useIterableCallbackReturn: effects returning cleanup is intended
47
- pendingEffects.forEach((e) => e());
48
- pendingEffects.clear();
49
- }
50
-
51
- function scheduleEffect(fn: () => void) {
52
- const target = (fn as any).__sigil_pre ? pendingPreEffects : pendingEffects;
53
- target.add(fn);
54
- if (batchDepth === 0 && !scheduledFlush) {
55
- scheduledFlush = true;
56
- queueMicrotask(flush);
57
- }
58
- }
59
-
60
- const targetDepsMap = new WeakMap<
61
- object,
62
- Map<string | symbol, Set<() => void>>
63
- >();
64
-
65
- function getDeps(target: object, key: string | symbol): Set<() => void> {
66
- let deps = targetDepsMap.get(target);
67
- if (!deps) {
68
- deps = new Map();
69
- targetDepsMap.set(target, deps);
70
- }
71
- let set = deps.get(key);
72
- if (!set) {
73
- set = new Set();
74
- deps.set(key, set);
75
- }
76
- return set;
77
- }
78
-
79
- function track(target: object, key: string | symbol) {
80
- if (currentEffect && currentDeps) {
81
- const deps = getDeps(target, key);
82
- deps.add(currentEffect);
83
- currentDeps.add(deps); // Set, deduplicates automatically
84
- }
85
- }
86
-
87
- function trigger(target: object, key: string | symbol) {
88
- const deps = targetDepsMap.get(target);
89
- if (!deps) return;
90
- const set = deps.get(key);
91
- if (!set) return;
92
- for (const fn of [...set]) {
93
- scheduleEffect(fn);
94
- }
95
- }
96
-
97
- const proxyCache = new WeakMap<object, object>();
98
- const proxyToTarget = new WeakMap<object, object>();
99
- const reactiveTargets = new WeakSet<object>();
100
- const ARRAY_MUTATORS = new Set([
101
- "push",
102
- "pop",
103
- "shift",
104
- "unshift",
105
- "splice",
106
- "sort",
107
- "reverse",
108
- "fill",
109
- ]);
110
-
111
- function createReactiveProxy<T extends object>(target: T): T {
112
- const existing = proxyCache.get(target);
113
- if (existing) return existing as T;
114
-
115
- const proxy = new Proxy(target, {
116
- get(target, key, receiver) {
117
- if (
118
- Array.isArray(target) &&
119
- typeof key === "string" &&
120
- ARRAY_MUTATORS.has(key)
121
- ) {
122
- return (...args: any[]) => {
123
- const result = (target as any)[key](...args);
124
- trigger(target, "length");
125
- // trigger all numeric keys that changed — for splice/sort
126
- // triggering length is sufficient for most reactive patterns
127
- return result;
128
- };
129
- }
130
- if (key === "set") {
131
- return (newValue: T) => {
132
- const oldKeys = new Set(Object.keys(target));
133
- const newKeys = new Set(Object.keys(newValue));
134
- for (const k of oldKeys) {
135
- if (!newKeys.has(k)) {
136
- delete (target as any)[k];
137
- trigger(target, k);
138
- }
139
- }
140
- for (const k of newKeys) {
141
- (target as any)[k] = (newValue as any)[k];
142
- trigger(target, k);
143
- }
144
- if (Array.isArray(target)) {
145
- trigger(target, "length");
146
- }
147
- };
148
- }
149
-
150
- if (key === "peek") {
151
- return () => target;
152
- }
153
-
154
- if (typeof key === "symbol") {
155
- return Reflect.get(target, key, receiver);
156
- }
157
-
158
- track(target, key);
159
- const value = target[key as keyof T];
160
-
161
- if (typeof value === "object" && value !== null) {
162
- return createReactiveProxy(value);
163
- }
164
-
165
- return value;
166
- },
167
-
168
- set(target, key, newValue, receiver) {
169
- const oldValue = target[key as keyof T];
170
- const result = Reflect.set(target, key, newValue, receiver);
171
- if (oldValue !== newValue) {
172
- trigger(target, key as string | symbol);
173
- if (
174
- Array.isArray(target) &&
175
- typeof key === "string" &&
176
- !Number.isNaN(Number(key))
177
- ) {
178
- trigger(target, "length");
179
- }
180
- }
181
- return result;
182
- },
183
-
184
- deleteProperty(target, key) {
185
- const result = Reflect.deleteProperty(target, key);
186
- trigger(target, key as string | symbol);
187
- return result;
188
- },
189
- });
190
-
191
- proxyCache.set(target, proxy);
192
- proxyToTarget.set(proxy, target);
193
- reactiveTargets.add(target);
194
- return proxy as T;
195
- }
196
-
197
- // ─── createSignal (branches on type) ───
198
-
199
- export type Signal<T> = {
200
- (): T;
201
- set: (next: T) => void;
202
- peek: () => T;
203
- };
204
-
205
- export function batch(fn: () => void) {
206
- batchDepth++;
207
- fn();
208
- batchDepth--;
209
- if (batchDepth === 0) {
210
- scheduledFlush = false;
211
- flush();
212
- }
213
- }
214
-
215
- export function tick(): Promise<void> {
216
- return new Promise((resolve) => queueMicrotask(resolve));
217
- }
218
-
219
- function createPrimitiveSignal<T>(initial: T): Signal<T> {
220
- const subs = new Set<() => void>();
221
- let value = initial;
222
-
223
- const getter = () => {
224
- if (currentEffect && currentDeps) {
225
- subs.add(currentEffect);
226
- currentDeps.add(subs);
227
- }
228
- return value;
229
- };
230
-
231
- getter.set = (next: T) => {
232
- value = next;
233
- for (const fn of [...subs]) {
234
- scheduleEffect(fn);
235
- }
236
- };
237
-
238
- getter.peek = () => value;
239
-
240
- return getter;
241
- }
242
-
243
- export function createSignal<T>(initial: T): Signal<T> {
244
- if (typeof initial === "object" && initial !== null) {
245
- const proxy = createReactiveProxy(initial);
246
- const getter = () => {
247
- // array signals: auto-track length so push/pop/splice re-run effects
248
- if (Array.isArray(initial)) {
249
- track(initial, "length");
250
- }
251
- return proxy;
252
- };
253
- getter.set = (next: T) => (proxy as any).set(next);
254
- getter.peek = () => initial;
255
- return getter;
256
- }
257
-
258
- return createPrimitiveSignal(initial);
259
- }
260
-
261
- // A1: $state.raw — create signal without Proxy wrapping for objects/arrays
262
- export function createRawSignal<T>(initial: T): Signal<T> {
263
- return createPrimitiveSignal(initial);
264
- }
265
-
266
- // A2: $state.snapshot — deep un-proxy a signal value
267
- function deepUnproxy<T>(value: T): T {
268
- if (typeof value !== "object" || value === null) return value;
269
- const raw = proxyToTarget.get(value as object);
270
- if (!raw) return value; // not a proxy, return as-is
271
- if (Array.isArray(raw)) {
272
- return raw.map(deepUnproxy) as T;
273
- }
274
- const result: Record<string, unknown> = {};
275
- for (const key of Object.keys(raw)) {
276
- result[key] = deepUnproxy((raw as Record<string, unknown>)[key]);
277
- }
278
- return result as T;
279
- }
280
-
281
- export function snapshot<T>(value: T): T {
282
- return deepUnproxy(value);
283
- }
284
-
285
- // A3: $effect.tracking() — check if inside reactive context
286
- export function tracking(): boolean {
287
- return currentEffect !== null;
288
- }
289
-
290
- // A4: $inspect — dev-only effect logging
291
- export function createInspectEffect(
292
- getValues: () => unknown[],
293
- cb?: (vals: unknown[]) => void,
294
- ): void {
295
- if (typeof process !== "undefined" && process.env.NODE_ENV === "production")
296
- return;
297
- createEffect(() => {
298
- const vals = getValues();
299
- if (cb) cb(vals);
300
- else console.log(...vals);
301
- });
302
- }
303
-
304
- // A5: $effect.pre — effect that flushes before DOM update
305
- export function createEffectPre(
306
- fn: () => undefined | (() => void),
307
- ): () => void {
308
- let cleanup: (() => void) | undefined;
309
- const ownDeps = new Set<Set<() => void>>();
310
-
311
- const effect = () => {
312
- if (cleanup) cleanup();
313
- for (const depSet of ownDeps) depSet.delete(effect);
314
- ownDeps.clear();
315
-
316
- const prevEffect = currentEffect;
317
- const prevDeps = currentDeps;
318
- currentEffect = effect;
319
- currentDeps = ownDeps;
320
- try {
321
- cleanup = fn();
322
- } finally {
323
- currentEffect = prevEffect;
324
- currentDeps = prevDeps;
325
- }
326
- };
327
-
328
- (effect as any).__sigil_pre = true;
329
- effect();
330
-
331
- const dispose = () => {
332
- for (const depSet of ownDeps) depSet.delete(effect);
333
- ownDeps.clear();
334
- if (cleanup) cleanup();
335
- };
336
-
337
- ((globalThis as any).__sigilEffectScope as (() => void)[] | undefined)?.push(
338
- dispose,
339
- );
340
- return dispose;
341
- }
342
-
343
- // A9: Profiler effect timing (dev)
344
- export function createProfilerEffect(
345
- name: string,
346
- fn: () => undefined | (() => void),
347
- ): () => void {
348
- return createEffect(() => {
349
- if (
350
- typeof process !== "undefined" &&
351
- process.env.NODE_ENV === "production"
352
- ) {
353
- return fn();
354
- }
355
- const start = performance.now();
356
- const cleanup = fn();
357
- const end = performance.now();
358
- // console.log(`[Profiler] ${name}: ${(end - start).toFixed(2)}ms`);
359
- return cleanup;
360
- });
361
- }
362
-
363
- // biome-ignore lint/suspicious/noConfusingVoidType: please shut up its a weird type
364
- export function createEffect(fn: () => void | (() => void)): () => void {
365
- let cleanup: (() => void) | undefined;
366
- const ownDeps = new Set<Set<() => void>>();
367
-
368
- const effect = () => {
369
- if (cleanup) cleanup();
370
- for (const depSet of ownDeps) depSet.delete(effect);
371
- ownDeps.clear();
372
-
373
- const prevEffect = currentEffect;
374
- const prevDeps = currentDeps;
375
- currentEffect = effect;
376
- currentDeps = ownDeps;
377
- try {
378
- //@ts-expect-error kill yourself
379
- cleanup = fn();
380
- } finally {
381
- currentEffect = prevEffect;
382
- currentDeps = prevDeps;
383
- }
384
- };
385
-
386
- effect();
387
-
388
- const dispose = () => {
389
- for (const depSet of ownDeps) depSet.delete(effect);
390
- ownDeps.clear();
391
- if (cleanup) cleanup();
392
- };
393
-
394
- ((globalThis as any).__sigilEffectScope as (() => void)[] | undefined)?.push(
395
- dispose,
396
- );
397
- return dispose;
398
- }
399
-
400
- /**
401
- * Run fn() and return a dispose function that tears down every effect
402
- * created during that call (including effects inside child createMemo calls).
403
- * Supports nesting: inner scopes don't leak to outer ones.
404
- */
405
- export function withEffectScope(fn: () => void): () => void {
406
- const prev = (globalThis as any).__sigilEffectScope;
407
- const disposers: (() => void)[] = [];
408
- (globalThis as any).__sigilEffectScope = disposers;
409
- try {
410
- fn();
411
- } finally {
412
- (globalThis as any).__sigilEffectScope = prev;
413
- }
414
- return () => {
415
- for (const d of disposers) d();
416
- disposers.length = 0;
417
- };
418
- }
419
-
420
- export function createMemo<T>(fn: () => T): Signal<T> {
421
- const inner = createSignal<T>(undefined as T);
422
- createEffect(() => inner.set(fn()));
423
- return inner;
424
- }
425
-
426
- /**
427
- * Claim an existing element from a hydration pool by tag name, or create a new one.
428
- * Removes the claimed node from the pool array.
429
- * When falling back to createElement, appends to parent if provided (SPA mode).
430
- */
431
- export function claim(
432
- nodes: ChildNode[],
433
- tag: string,
434
- parent?: Element,
435
- ): Element {
436
- for (let i = 0; i < nodes.length; i++) {
437
- const node = nodes[i];
438
- if (
439
- node instanceof Element &&
440
- node.tagName.toLowerCase() === tag.toLowerCase()
441
- ) {
442
- nodes.splice(i, 1);
443
- return node;
444
- }
445
- }
446
- const el = document.createElement(tag);
447
- if (parent) parent.appendChild(el);
448
- return el;
449
- }
450
-
451
- /**
452
- * Claim an existing Text node from a hydration pool, or create a new empty one.
453
- * Removes the claimed node from the pool array.
454
- * When falling back to createTextNode, appends to parent if provided (SPA mode).
455
- */
456
- export function claimText(nodes: ChildNode[], parent?: Element): Text {
457
- for (let i = 0; i < nodes.length; i++) {
458
- const node = nodes[i];
459
- if (node instanceof Text) {
460
- nodes.splice(i, 1);
461
- return node;
462
- }
463
- }
464
- const text = document.createTextNode("");
465
- if (parent) parent.appendChild(text);
466
- return text;
467
- }
468
-
469
- /**
470
- * Claim an existing Comment node from a hydration pool, or create a new one.
471
- * Removes the claimed node from the pool array.
472
- * When falling back to createComment, appends to parent if provided (SPA mode).
473
- */
474
- export function claimComment(
475
- nodes: ChildNode[],
476
- text: string = "",
477
- parent?: Element,
478
- ): Comment {
479
- for (let i = 0; i < nodes.length; i++) {
480
- const node = nodes[i];
481
- if (node instanceof Comment && node.data === text) {
482
- nodes.splice(i, 1);
483
- return node;
484
- }
485
- }
486
- const comment = document.createComment(text);
487
- if (parent) parent.appendChild(comment);
488
- return comment;
489
- }
490
-
491
- /**
492
- * Reconcile a list of keyed DOM nodes.
493
- * anchor.before(node) handles both insert and move natively.
494
- * @param claimNode - Optional hydration callback. Called with (element, key) for
495
- * server-rendered elements removed from the DOM. Returns the element to use,
496
- * or null to discard.
497
- */
498
- export function reconcile<T>(
499
- anchor: Partial<Comment>,
500
- keyMap: Map<unknown, Node>,
501
- newItems: T[],
502
- getKey: (item: T) => unknown,
503
- createNode: (item: T) => Node,
504
- // is this meant to be unused? claimNode?: (element: Element, key: unknown) => Element | null,
505
- ): void {
506
- const newKeys = new Set(newItems.map(getKey));
507
-
508
- // Remove nodes no longer in list (or claim them for hydration)
509
- for (const [key, node] of keyMap) {
510
- if (!newKeys.has(key)) {
511
- node.parentNode?.removeChild(node);
512
- keyMap.delete(key);
513
- }
514
- }
515
-
516
- // Insert/move in order — anchor.before() handles both cases
517
- for (const item of newItems) {
518
- const key = getKey(item);
519
- let node = keyMap.get(key);
520
- if (!node) {
521
- node = createNode(item);
522
- keyMap.set(key, node);
523
- }
524
- anchor.before?.(node);
525
- }
526
- }
527
-
528
- /**
529
- * Hydrate a keyed list: claim the comment anchor, walk its sibling elements
530
- * to build a keyMap, then reconcile with signal data.
531
- *
532
- * SSR renders items as flat siblings. Hydration claims them by position,
533
- * builds the keyMap, removes from DOM, then reconcile re-inserts in order.
534
- */
535
- export function hydrateKeyedList<T>(
536
- nodesVar: ChildNode[],
537
- signalItems: T[],
538
- getKey: (item: T) => unknown,
539
- createNode: (item: T) => Node,
540
- parent?: Element,
541
- ): { anchor: Comment; keyMap: Map<unknown, Node> } {
542
- // 1. Claim the <!--g--> opening delimiter as anchor
543
- const anchor = claimComment(nodesVar, "g", parent);
544
-
545
- // 2. Walk siblings after anchor, collect elements up to <!--/g-->, build keyMap
546
- const keyMap = new Map<unknown, Node>();
547
- const anchorParent = anchor.parentNode;
548
- if (anchorParent && signalItems.length > 0) {
549
- const claimed: Element[] = [];
550
- let next = anchor.nextSibling;
551
- while (next) {
552
- const current = next;
553
- next = next.nextSibling;
554
- // Stop at closing <!--/g--> delimiter and consume it
555
- if (current instanceof Comment && current.data === "/g") {
556
- current.remove();
557
- break;
558
- }
559
- if (current instanceof Element) {
560
- current.remove();
561
- claimed.push(current);
562
- }
563
- }
564
- // Map claimed elements to keys by index
565
- for (let i = 0; i < claimed.length && i < signalItems.length; i++) {
566
- //@ts-expect-error i is always in bounds
567
- const key = getKey(signalItems[i]);
568
- //@ts-expect-error i is always in bounds
569
- keyMap.set(key, claimed[i]);
570
- }
571
- }
572
-
573
- // 3. Reconcile — keyMap is pre-populated with claimed nodes
574
- reconcile(anchor, keyMap, signalItems, getKey, createNode);
575
- return { anchor, keyMap };
576
- }
577
-
578
- export function insert(parent: Element, value: unknown): void {
579
- if (value === false || value === null || value === undefined) return;
580
- if (typeof value === "function") {
581
- insert(parent, value());
582
- return;
583
- }
584
- if (Array.isArray(value)) {
585
- for (const item of value) insert(parent, item);
586
- return;
587
- }
588
- if (value instanceof Node) {
589
- parent.appendChild(value);
590
- return;
591
- }
592
- parent.append(String(value));
593
- }
594
-
595
- /**
596
- * Apply a use: directive to an element.
597
- * The directive function receives (element, params) and may return a cleanup function.
598
- * Cleanup runs when the enclosing $effect re-runs or the component is destroyed.
599
- */
600
- export type Directive = (
601
- node: Element,
602
- params: unknown,
603
- ) => undefined | (() => void);
604
-
605
- export function applyDirective(
606
- node: Element,
607
- directive: Directive | [Directive, unknown],
608
- ): void {
609
- const [fn, params] = Array.isArray(directive)
610
- ? directive
611
- : [directive, undefined];
612
- const cleanup = fn(node, params);
613
- if (typeof cleanup === "function") {
614
- createEffect(() => () => cleanup());
615
- }
616
- }
617
-
618
- export type ContextKey<T> = symbol & { __type: T };
619
-
620
- const clientContextStore = new Map<symbol, unknown>();
621
-
622
- let storeProvider: (() => Map<symbol, unknown>) | null = null;
623
- export function __setStoreProvider(fn: () => Map<symbol, unknown>) {
624
- storeProvider = fn;
625
- }
626
-
627
- function getStore(): Map<symbol, unknown> {
628
- return storeProvider?.() ?? clientContextStore;
629
- }
630
-
631
- export function createContext<T>(): ContextKey<T> {
632
- return Symbol() as ContextKey<T>;
633
- }
634
-
635
- export function setContext<T>(key: ContextKey<T>, value: T): void {
636
- getStore().set(key as unknown as symbol, value);
637
- }
638
-
639
- export function getContext<T>(key: ContextKey<T>): T {
640
- return getStore().get(key as unknown as symbol) as T;
641
- }
642
-
643
- const _hydrationStack: ChildNode[][] = [];
644
-
645
- export function pushHydrationNodes(nodes: ChildNode[]): void {
646
- _hydrationStack.push(nodes);
647
- }
648
-
649
- export function popHydrationNodes(): void {
650
- _hydrationStack.pop();
651
- }
652
-
653
- export function getHydrationNodes(): ChildNode[] {
654
- return _hydrationStack[_hydrationStack.length - 1] ?? [];
655
- }
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
+ // biome-ignore lint/suspicious/noConfusingVoidType: please shut up its a weird type
385
+ export function createEffect(fn: () => void | (() => void)): () => void {
386
+ let cleanup: (() => void) | undefined;
387
+ const ownDeps = new Set<Set<() => void>>();
388
+
389
+ const effect = () => {
390
+ if (cleanup) cleanup();
391
+ for (const depSet of ownDeps) depSet.delete(effect);
392
+ ownDeps.clear();
393
+
394
+ const prevEffect = currentEffect;
395
+ const prevDeps = currentDeps;
396
+ currentEffect = effect;
397
+ currentDeps = ownDeps;
398
+ try {
399
+ //@ts-expect-error kill yourself
400
+ cleanup = fn();
401
+ } finally {
402
+ currentEffect = prevEffect;
403
+ currentDeps = prevDeps;
404
+ }
405
+ };
406
+
407
+ effect();
408
+
409
+ const dispose = () => {
410
+ for (const depSet of ownDeps) depSet.delete(effect);
411
+ ownDeps.clear();
412
+ if (cleanup) cleanup();
413
+ };
414
+
415
+ ((globalThis as any).__sigilEffectScope as (() => void)[] | undefined)?.push(
416
+ dispose,
417
+ );
418
+ return dispose;
419
+ }
420
+
421
+ /**
422
+ * Run fn() and return a dispose function that tears down every effect
423
+ * created during that call (including effects inside child createMemo calls).
424
+ * Supports nesting: inner scopes don't leak to outer ones.
425
+ */
426
+ export function withEffectScope(fn: () => void): () => void {
427
+ const prev = (globalThis as any).__sigilEffectScope;
428
+ const disposers: (() => void)[] = [];
429
+ (globalThis as any).__sigilEffectScope = disposers;
430
+ try {
431
+ fn();
432
+ } finally {
433
+ (globalThis as any).__sigilEffectScope = prev;
434
+ }
435
+ return () => {
436
+ for (const d of disposers) d();
437
+ disposers.length = 0;
438
+ };
439
+ }
440
+
441
+ type EffectScopeGlobal = { __sigilEffectScope?: (() => void)[] };
442
+
443
+ /**
444
+ * Run fn() with a detached effect scope. Effects created inside are invisible
445
+ * to enclosing scopes (the scope array is replaced, not merged) and live until
446
+ * dispose() is called — for app bootstrap, routers, and long-lived listeners.
447
+ */
448
+ export function createRoot<T>(fn: (dispose: () => void) => T): T {
449
+ const g = globalThis as EffectScopeGlobal;
450
+ const prev = g.__sigilEffectScope;
451
+ const disposers: (() => void)[] = [];
452
+ g.__sigilEffectScope = disposers;
453
+ const dispose = () => {
454
+ for (const d of disposers.splice(0)) d();
455
+ };
456
+ try {
457
+ return fn(dispose);
458
+ } finally {
459
+ g.__sigilEffectScope = prev;
460
+ }
461
+ }
462
+
463
+ export interface Resource<T> {
464
+ data: () => T | undefined;
465
+ loading: () => boolean;
466
+ error: () => Error | undefined;
467
+ refetch: () => void;
468
+ }
469
+
470
+ /**
471
+ * Async data source with reactive re-fetching. Re-runs when `source()` changes
472
+ * or refetch() is called; stale responses are discarded by request id.
473
+ */
474
+ export function createResource<T>(
475
+ fetcher: (source: unknown, info: { refetch: () => void }) => Promise<T>,
476
+ source?: () => unknown,
477
+ ): Resource<T> {
478
+ const data = createSignal<T | undefined>(undefined);
479
+ const loading = createSignal(true);
480
+ const error = createSignal<Error | undefined>(undefined);
481
+ const version = createSignal(0);
482
+ let requestCount = 0;
483
+ let versionCounter = 0;
484
+
485
+ const refetch = () => {
486
+ versionCounter++;
487
+ version.set(versionCounter);
488
+ };
489
+
490
+ createEffect(() => {
491
+ const src = source?.();
492
+ version(); // track refetch bumps
493
+ const id = ++requestCount;
494
+ loading.set(true);
495
+ error.set(undefined);
496
+ fetcher(src, { refetch }).then(
497
+ (result) => {
498
+ if (id !== requestCount) return; // stale response
499
+ data.set(result);
500
+ loading.set(false);
501
+ },
502
+ (err: unknown) => {
503
+ if (id !== requestCount) return;
504
+ error.set(err instanceof Error ? err : new Error(String(err)));
505
+ loading.set(false);
506
+ },
507
+ );
508
+ });
509
+
510
+ return { data, loading, error, refetch };
511
+ }
512
+
513
+ export function createMemo<T>(fn: () => T): Signal<T> {
514
+ const inner = createSignal<T>(undefined as T);
515
+ createEffect(() => inner.set(fn()));
516
+ return inner;
517
+ }
518
+
519
+ /**
520
+ * Reconcile a list of keyed DOM nodes.
521
+ * anchor.before(node) handles both insert and move natively.
522
+ * @param claimNode - Optional hydration callback. Called with (element, key) for
523
+ * server-rendered elements removed from the DOM. Returns the element to use,
524
+ * or null to discard.
525
+ */
526
+ const lastItemFor = new WeakMap<object, unknown>();
527
+
528
+ export function reconcile<T>(
529
+ anchor: Partial<Comment>,
530
+ keyMap: Map<unknown, Node>,
531
+ newItems: T[],
532
+ getKey: (item: T, index: number) => unknown,
533
+ createNode: (item: T) => Node,
534
+ // is this meant to be unused? claimNode?: (element: Element, key: unknown) => Element | null,
535
+ ): void {
536
+ const newKeys = new Set(newItems.map((item, i) => getKey(item, i)));
537
+
538
+ // Remove nodes no longer in list (or claim them for hydration)
539
+ for (const [key, node] of keyMap) {
540
+ if (!newKeys.has(key)) {
541
+ node.parentNode?.removeChild(node);
542
+ keyMap.delete(key);
543
+ }
544
+ }
545
+
546
+ // Insert/move in order — anchor.before() handles both cases.
547
+ // A surviving node whose item instance changed is rebuilt: compiled row
548
+ // bodies bake item reads at creation time, so immutable-style updates
549
+ // (new object, same key) must swap the node to show fresh content.
550
+ for (let i = 0; i < newItems.length; i++) {
551
+ const item = newItems[i]!;
552
+ const key = getKey(item, i);
553
+ let node = keyMap.get(key);
554
+ if (node && lastItemFor.has(node) && !Object.is(lastItemFor.get(node), item)) {
555
+ node.parentNode?.removeChild(node);
556
+ keyMap.delete(key);
557
+ node = undefined;
558
+ }
559
+ if (!node) {
560
+ node = createNode(item);
561
+ lastItemFor.set(node, item);
562
+ keyMap.set(key, node);
563
+ }
564
+ anchor.before?.(node);
565
+ }
566
+ }
567
+
568
+ /**
569
+ * Claim an existing element from a hydration pool by tag name, or create a new one.
570
+ * Removes the claimed node from the pool array.
571
+ * When falling back to createElement, appends to parent if provided (SPA mode).
572
+ */
573
+ export function claim(
574
+ nodes: ChildNode[],
575
+ tag: string,
576
+ parent?: Element,
577
+ ): Element {
578
+ for (let i = 0; i < nodes.length; i++) {
579
+ const node = nodes[i];
580
+ if (
581
+ node instanceof Element &&
582
+ node.tagName.toLowerCase() === tag.toLowerCase()
583
+ ) {
584
+ nodes.splice(i, 1);
585
+ return node;
586
+ }
587
+ }
588
+ const el = document.createElement(tag);
589
+ if (parent) parent.appendChild(el);
590
+ return el;
591
+ }
592
+
593
+ /**
594
+ * Claim an existing Text node from a hydration pool, or create a new empty one.
595
+ * Removes the claimed node from the pool array.
596
+ * When falling back to createTextNode, appends to parent if provided (SPA mode).
597
+ */
598
+ export function claimText(nodes: ChildNode[], parent?: Element): Text {
599
+ for (let i = 0; i < nodes.length; i++) {
600
+ const node = nodes[i];
601
+ if (node instanceof Text) {
602
+ nodes.splice(i, 1);
603
+ return node;
604
+ }
605
+ }
606
+ const text = document.createTextNode("");
607
+ if (parent) parent.appendChild(text);
608
+ return text;
609
+ }
610
+
611
+ /**
612
+ * Claim an existing Comment node from a hydration pool, or create a new one.
613
+ * Removes the claimed node from the pool array.
614
+ * When falling back to createComment, appends to parent if provided (SPA mode).
615
+ */
616
+ export function claimComment(
617
+ nodes: ChildNode[],
618
+ text: string = "",
619
+ parent?: Element,
620
+ ): Comment {
621
+ for (let i = 0; i < nodes.length; i++) {
622
+ const node = nodes[i];
623
+ if (node instanceof Comment && node.data === text) {
624
+ nodes.splice(i, 1);
625
+ return node;
626
+ }
627
+ }
628
+ const comment = document.createComment(text);
629
+ if (parent) parent.appendChild(comment);
630
+ return comment;
631
+ }
632
+
633
+ /**
634
+ * Hydrate a keyed list: claim the comment anchor, walk its sibling elements
635
+ * to build a keyMap, then reconcile with signal data.
636
+ *
637
+ * SSR renders items as flat siblings. Hydration claims them by position,
638
+ * builds the keyMap, removes from DOM, then reconcile re-inserts in order.
639
+ */
640
+ export function hydrateKeyedList<T>(
641
+ nodesVar: ChildNode[],
642
+ signalItems: T[],
643
+ getKey: (item: T, index: number) => unknown,
644
+ createNode: (item: T) => Node,
645
+ parent?: Element,
646
+ ): { anchor: Comment; keyMap: Map<unknown, Node> } {
647
+ // 1. Claim the <!--g--> opening delimiter as anchor
648
+ const anchor = claimComment(nodesVar, "g", parent);
649
+
650
+ // 2. Walk siblings after anchor, collect elements up to <!--/g-->, build keyMap
651
+ const keyMap = new Map<unknown, Node>();
652
+ const anchorParent = anchor.parentNode;
653
+ if (anchorParent && signalItems.length > 0) {
654
+ const claimed: Element[] = [];
655
+ let next = anchor.nextSibling;
656
+ while (next) {
657
+ const current = next;
658
+ next = next.nextSibling;
659
+ // Stop at closing <!--/g--> delimiter and consume it
660
+ if (current instanceof Comment && current.data === "/g") {
661
+ current.remove();
662
+ break;
663
+ }
664
+ if (current instanceof Element) {
665
+ current.remove();
666
+ claimed.push(current);
667
+ }
668
+ }
669
+ // Map claimed elements to keys by index
670
+ for (let i = 0; i < claimed.length && i < signalItems.length; i++) {
671
+ //@ts-expect-error i is always in bounds
672
+ const key = getKey(signalItems[i], i);
673
+ //@ts-expect-error i is always in bounds
674
+ keyMap.set(key, claimed[i]);
675
+ }
676
+ }
677
+
678
+ // 3. Reconcile — keyMap is pre-populated with claimed nodes
679
+ reconcile(anchor, keyMap, signalItems, getKey, createNode);
680
+ return { anchor, keyMap };
681
+ }
682
+
683
+ export function insert(parent: Element, value: unknown): void {
684
+ if (value === false || value === null || value === undefined) return;
685
+ if (typeof value === "function") {
686
+ insert(parent, value());
687
+ return;
688
+ }
689
+ if (Array.isArray(value)) {
690
+ for (const item of value) insert(parent, item);
691
+ return;
692
+ }
693
+ if (value instanceof Node) {
694
+ parent.appendChild(value);
695
+ return;
696
+ }
697
+ parent.append(String(value));
698
+ }
699
+
700
+ /**
701
+ * Apply a use: directive to an element.
702
+ * The directive function receives (element, params) and may return a cleanup function.
703
+ * Cleanup runs when the enclosing $effect re-runs or the component is destroyed.
704
+ */
705
+ export type Directive = (
706
+ node: Element,
707
+ params: unknown,
708
+ ) => undefined | (() => void);
709
+
710
+ export function applyDirective(
711
+ node: Element,
712
+ directive: Directive | [Directive, unknown],
713
+ ): void {
714
+ const [fn, params] = Array.isArray(directive)
715
+ ? directive
716
+ : [directive, undefined];
717
+ const cleanup = fn(node, params);
718
+ if (typeof cleanup === "function") {
719
+ createEffect(() => () => cleanup());
720
+ }
721
+ }
722
+
723
+ export type ContextKey<T> = symbol & { __type: T };
724
+
725
+ const clientContextStore = new Map<symbol, unknown>();
726
+
727
+ let storeProvider: (() => Map<symbol, unknown>) | null = null;
728
+ export function __setStoreProvider(fn: () => Map<symbol, unknown>) {
729
+ storeProvider = fn;
730
+ }
731
+
732
+ function getStore(): Map<symbol, unknown> {
733
+ return storeProvider?.() ?? clientContextStore;
734
+ }
735
+
736
+ export function createContext<T>(): ContextKey<T> {
737
+ return Symbol() as ContextKey<T>;
738
+ }
739
+
740
+ export function setContext<T>(key: ContextKey<T>, value: T): void {
741
+ getStore().set(key as unknown as symbol, value);
742
+ }
743
+
744
+ export function getContext<T>(key: ContextKey<T>): T {
745
+ return getStore().get(key as unknown as symbol) as T;
746
+ }
747
+
748
+ const _hydrationStack: ChildNode[][] = [];
749
+
750
+ export function pushHydrationNodes(nodes: ChildNode[]): void {
751
+ _hydrationStack.push(nodes);
752
+ }
753
+
754
+ export function popHydrationNodes(): void {
755
+ _hydrationStack.pop();
756
+ }
757
+
758
+ export function getHydrationNodes(): ChildNode[] {
759
+ return _hydrationStack[_hydrationStack.length - 1] ?? [];
760
+ }