@sigil-dev/runtime 0.7.4 → 0.7.6

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