@torpor/view 0.4.18 → 1.0.1

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 (72) hide show
  1. package/README.md +41 -16
  2. package/dist/Cleanup-D0wvGW5d.d.cts +9 -0
  3. package/dist/Cleanup-D0wvGW5d.d.cts.map +1 -0
  4. package/dist/Cleanup-D0wvGW5d.d.mts +9 -0
  5. package/dist/Cleanup-D0wvGW5d.d.mts.map +1 -0
  6. package/dist/Component-0MH0zd-m.d.cts +11 -0
  7. package/dist/Component-0MH0zd-m.d.cts.map +1 -0
  8. package/dist/Component-0MH0zd-m.d.mts +11 -0
  9. package/dist/Component-0MH0zd-m.d.mts.map +1 -0
  10. package/dist/Effect-BTKurOpr.d.mts +381 -0
  11. package/dist/Effect-BTKurOpr.d.mts.map +1 -0
  12. package/dist/Effect-COl3aRJV.d.cts +381 -0
  13. package/dist/Effect-COl3aRJV.d.cts.map +1 -0
  14. package/dist/compile.cjs +1734 -739
  15. package/dist/compile.d.cts +85 -50
  16. package/dist/compile.d.cts.map +1 -1
  17. package/dist/compile.d.mts +85 -50
  18. package/dist/compile.d.mts.map +1 -1
  19. package/dist/compile.mjs +1737 -741
  20. package/dist/compile.mjs.map +1 -1
  21. package/dist/dev.cjs +62 -63
  22. package/dist/dev.d.cts +4 -3
  23. package/dist/dev.d.cts.map +1 -1
  24. package/dist/dev.d.mts +4 -3
  25. package/dist/dev.d.mts.map +1 -1
  26. package/dist/dev.mjs +61 -62
  27. package/dist/dev.mjs.map +1 -1
  28. package/dist/{devContext-B3yskfhA.cjs → devContext-BulTn3U5.cjs} +6 -9
  29. package/dist/{devContext-CQ8RhBX-.mjs → devContext-ZNsPyOgB.mjs} +3 -4
  30. package/dist/devContext-ZNsPyOgB.mjs.map +1 -0
  31. package/dist/fromWebSocket-1QOjcrHE.cjs +182 -0
  32. package/dist/fromWebSocket-B52kN3-W.d.mts +91 -0
  33. package/dist/fromWebSocket-B52kN3-W.d.mts.map +1 -0
  34. package/dist/fromWebSocket-DeB35Q4w.d.cts +91 -0
  35. package/dist/fromWebSocket-DeB35Q4w.d.cts.map +1 -0
  36. package/dist/fromWebSocket-Dxc_uwm1.mjs +137 -0
  37. package/dist/fromWebSocket-Dxc_uwm1.mjs.map +1 -0
  38. package/dist/index.cjs +2109 -494
  39. package/dist/index.d.cts +608 -112
  40. package/dist/index.d.cts.map +1 -1
  41. package/dist/index.d.mts +608 -112
  42. package/dist/index.d.mts.map +1 -1
  43. package/dist/index.mjs +2088 -490
  44. package/dist/index.mjs.map +1 -1
  45. package/dist/ssr.cjs +78 -17
  46. package/dist/ssr.d.cts +64 -11
  47. package/dist/ssr.d.cts.map +1 -1
  48. package/dist/ssr.d.mts +64 -11
  49. package/dist/ssr.d.mts.map +1 -1
  50. package/dist/ssr.mjs +67 -14
  51. package/dist/ssr.mjs.map +1 -1
  52. package/package.json +21 -19
  53. package/dist/Cleanup-CYsytTEc.d.cts +0 -9
  54. package/dist/Cleanup-CYsytTEc.d.cts.map +0 -1
  55. package/dist/Cleanup-CgjyN0lW.d.mts +0 -9
  56. package/dist/Cleanup-CgjyN0lW.d.mts.map +0 -1
  57. package/dist/Component-DmWGMgak.d.mts +0 -11
  58. package/dist/Component-DmWGMgak.d.mts.map +0 -1
  59. package/dist/Component-kGLRFYg2.d.cts +0 -11
  60. package/dist/Component-kGLRFYg2.d.cts.map +0 -1
  61. package/dist/Region-Bb6HAb-F.d.cts +0 -201
  62. package/dist/Region-Bb6HAb-F.d.cts.map +0 -1
  63. package/dist/Region-CTchywkr.d.mts +0 -201
  64. package/dist/Region-CTchywkr.d.mts.map +0 -1
  65. package/dist/devContext-CQ8RhBX-.mjs.map +0 -1
  66. package/dist/formatText-BNP3P38F.d.cts +0 -17
  67. package/dist/formatText-BNP3P38F.d.cts.map +0 -1
  68. package/dist/formatText-D6Ov8Ub0.d.mts +0 -17
  69. package/dist/formatText-D6Ov8Ub0.d.mts.map +0 -1
  70. package/dist/formatText-DTIRmc3X.mjs +0 -61
  71. package/dist/formatText-DTIRmc3X.mjs.map +0 -1
  72. package/dist/formatText-Dhl2O0Ee.cjs +0 -96
package/dist/index.mjs CHANGED
@@ -1,6 +1,5 @@
1
- import { t as devContext_default } from "./devContext-CQ8RhBX-.mjs";
2
- import { a as buildStyles, i as proxyHandledSymbol, n as $unwrap, o as buildClasses, r as proxyDataSymbol, t as formatText } from "./formatText-DTIRmc3X.mjs";
3
-
1
+ import { t as devContext } from "./devContext-ZNsPyOgB.mjs";
2
+ import { a as buildStyles, c as proxyDataSymbol, i as formatText, n as fromServer, o as buildClasses, r as fromElement, s as $unwrap, t as fromWebSocket } from "./fromWebSocket-Dxc_uwm1.mjs";
4
3
  //#region src/render/context.ts
5
4
  const CONTEXT_SYMBOL = Symbol.for("torp.Context");
6
5
  const context = globalThis[CONTEXT_SYMBOL] ??= {
@@ -10,55 +9,41 @@ const context = globalThis[CONTEXT_SYMBOL] ??= {
10
9
  batch: 0,
11
10
  batchOperation: 0,
12
11
  registerComputed: null,
13
- firstEffectToRun: null,
12
+ effectsToRun: [],
14
13
  firstSignalToUpdate: null,
14
+ lastSignalToUpdate: null,
15
15
  activeRegion: null,
16
16
  previousRegion: null,
17
17
  rootRegion: null,
18
+ awaitBoundary: null,
19
+ suspendPeek: false,
20
+ suspendPeekHit: false,
21
+ refreshSignals: null,
22
+ refreshInitialized: null,
18
23
  mountEffects: [],
19
24
  stashedEvents: [],
20
25
  stashedAnimations: [],
21
26
  hydrationNode: null
22
27
  };
23
- var context_default = context;
24
-
25
28
  //#endregion
26
29
  //#region src/render/addAnimation.ts
27
30
  function addAnimation(el, entry, exit) {
28
- context_default.stashedAnimations.push({
29
- region: context_default.activeRegion,
31
+ context.stashedAnimations.push({
32
+ region: context.activeRegion,
30
33
  el,
31
34
  in: entry,
32
35
  out: exit
33
36
  });
34
37
  }
35
-
36
38
  //#endregion
37
39
  //#region src/render/addEvent.ts
38
40
  function addEvent(el, type, listener) {
39
- if (listener !== void 0 && listener !== null) context_default.stashedEvents.push({
40
- region: context_default.activeRegion,
41
+ if (listener !== void 0 && listener !== null) context.stashedEvents.push({
41
42
  el,
42
43
  type,
43
44
  listener
44
45
  });
45
46
  }
46
-
47
- //#endregion
48
- //#region src/types/constants.ts
49
- /**
50
- * The type of a Signal object.
51
- */
52
- const SIGNAL_TYPE = 0;
53
- /**
54
- * The type of a Computed object.
55
- */
56
- const COMPUTED_TYPE = 1;
57
- /**
58
- * The type of an Effect object.
59
- */
60
- const EFFECT_TYPE = 2;
61
-
62
47
  //#endregion
63
48
  //#region src/watch/clearSources.ts
64
49
  /**
@@ -77,7 +62,6 @@ function clearSources(target) {
77
62
  previousSub = clearSub;
78
63
  }
79
64
  }
80
-
81
65
  //#endregion
82
66
  //#region src/watch/deactivateSources.ts
83
67
  /**
@@ -86,7 +70,6 @@ function clearSources(target) {
86
70
  function deactivateSources(target) {
87
71
  for (let sourceSub = target.firstSource; sourceSub !== null; sourceSub = sourceSub.nextSource) sourceSub.active = false;
88
72
  }
89
-
90
73
  //#endregion
91
74
  //#region src/watch/trackSignal.ts
92
75
  /**
@@ -94,60 +77,48 @@ function deactivateSources(target) {
94
77
  * run when the signal changes.
95
78
  */
96
79
  function trackSignal(signal) {
97
- const target = context_default.activeTarget;
80
+ const target = context.activeTarget;
98
81
  if (target !== null) {
99
- let sub = null;
100
- let lastSub = null;
101
- for (let nextSub = signal.firstTarget; nextSub !== null; nextSub = nextSub.nextTarget) {
102
- lastSub = nextSub;
103
- if (nextSub.target === target) {
104
- sub = nextSub;
105
- break;
106
- }
82
+ for (let existingSub = target.firstSource; existingSub !== null; existingSub = existingSub.nextSource) if (existingSub.source === signal) {
83
+ existingSub.active = true;
84
+ return;
107
85
  }
108
- if (sub === null) {
109
- sub = {
110
- source: signal,
111
- target,
112
- previousTarget: lastSub,
113
- nextTarget: null,
114
- nextSource: null,
115
- active: true,
116
- recalc: false
117
- };
118
- if (lastSub === null) signal.firstTarget = sub;
119
- else lastSub.nextTarget = sub;
120
- if (target.firstSource === null) target.firstSource = sub;
121
- else {
122
- let lastEffectSub = target.firstSource;
123
- for (let nextSub = lastEffectSub.nextSource; nextSub !== null; nextSub = nextSub.nextSource) lastEffectSub = nextSub;
124
- lastEffectSub.nextSource = sub;
125
- }
126
- } else sub.active = true;
86
+ const oldFirstTarget = signal.firstTarget;
87
+ const sub = {
88
+ source: signal,
89
+ target,
90
+ previousTarget: null,
91
+ nextTarget: oldFirstTarget,
92
+ nextSource: target.firstSource,
93
+ active: true,
94
+ recalc: false
95
+ };
96
+ if (oldFirstTarget !== null) oldFirstTarget.previousTarget = sub;
97
+ signal.firstTarget = sub;
98
+ target.firstSource = sub;
127
99
  }
128
100
  }
129
-
130
101
  //#endregion
131
102
  //#region src/watch/runComputed.ts
132
103
  function runComputed(computed) {
133
- const oldActiveTarget = context_default.activeTarget;
104
+ const oldActiveTarget = context.activeTarget;
134
105
  computed.running = true;
135
106
  computed.didError = false;
107
+ computed.didSuspend = false;
136
108
  try {
137
- context_default.activeTarget = computed;
109
+ context.activeTarget = computed;
138
110
  computed.value = computed.run();
139
111
  } catch (err) {
140
112
  computed.didError = true;
141
113
  computed.value = err;
142
114
  throw err;
143
115
  } finally {
144
- context_default.activeTarget = oldActiveTarget;
116
+ context.activeTarget = oldActiveTarget;
145
117
  computed.running = false;
146
118
  }
147
119
  trackSignal(computed);
148
120
  return computed.value;
149
121
  }
150
-
151
122
  //#endregion
152
123
  //#region src/watch/checkComputed.ts
153
124
  /**
@@ -171,7 +142,6 @@ function checkComputed(computed) {
171
142
  }
172
143
  return changed;
173
144
  }
174
-
175
145
  //#endregion
176
146
  //#region src/watch/checkSources.ts
177
147
  /**
@@ -180,21 +150,20 @@ function checkComputed(computed) {
180
150
  */
181
151
  function checkSources(target) {
182
152
  let haveComputed = false;
183
- for (let sourceSub = target.firstSource; sourceSub !== null; sourceSub = sourceSub.nextSource) if (sourceSub.recalc) if (sourceSub.source.type === SIGNAL_TYPE) return true;
153
+ for (let sourceSub = target.firstSource; sourceSub !== null; sourceSub = sourceSub.nextSource) if (sourceSub.recalc) if (sourceSub.source.type === 0) return true;
184
154
  else if (sourceSub.source.recalc) haveComputed = true;
185
155
  else return true;
186
156
  if (haveComputed) {
187
- for (let sourceSub = target.firstSource; sourceSub !== null; sourceSub = sourceSub.nextSource) if (sourceSub.recalc && sourceSub.source.type === COMPUTED_TYPE && sourceSub.source.recalc) {
188
- const oldActiveTarget = context_default.activeTarget;
189
- context_default.activeTarget = target;
157
+ for (let sourceSub = target.firstSource; sourceSub !== null; sourceSub = sourceSub.nextSource) if (sourceSub.recalc && sourceSub.source.type === 1 && sourceSub.source.recalc) {
158
+ const oldActiveTarget = context.activeTarget;
159
+ context.activeTarget = target;
190
160
  const recalc = checkComputed(sourceSub.source);
191
- context_default.activeTarget = oldActiveTarget;
161
+ context.activeTarget = oldActiveTarget;
192
162
  if (recalc) return true;
193
163
  }
194
164
  }
195
165
  return false;
196
166
  }
197
-
198
167
  //#endregion
199
168
  //#region src/watch/runCleanups.ts
200
169
  /**
@@ -203,9 +172,10 @@ function checkSources(target) {
203
172
  function runCleanups(effect) {
204
173
  let effectToClean = effect;
205
174
  for (let i = 0; i < effect.extent; i++) {
175
+ if (effectToClean === null) break;
206
176
  if (typeof effectToClean.cleanup === "function") {
207
- const oldActiveTarget = context_default.activeTarget;
208
- context_default.activeTarget = null;
177
+ const oldActiveTarget = context.activeTarget;
178
+ context.activeTarget = null;
209
179
  try {
210
180
  effectToClean.cleanup();
211
181
  } catch (err) {
@@ -214,18 +184,12 @@ function runCleanups(effect) {
214
184
  throw err;
215
185
  } finally {
216
186
  effectToClean.cleanup = void 0;
217
- context_default.activeTarget = oldActiveTarget;
187
+ context.activeTarget = oldActiveTarget;
218
188
  }
219
189
  }
220
- const nextEffect = effectToClean.nextEffect;
221
- if (i !== 0 && effect.nextEffectToRun === effectToClean) {
222
- effect.nextEffectToRun = effectToClean.nextEffectToRun;
223
- effectToClean.nextEffect = effectToClean.nextEffectToRun = null;
224
- }
225
- effectToClean = nextEffect;
190
+ effectToClean = effectToClean.nextEffect;
226
191
  }
227
192
  }
228
-
229
193
  //#endregion
230
194
  //#region src/watch/checkEffect.ts
231
195
  /**
@@ -240,130 +204,250 @@ function checkEffect(effect) {
240
204
  clearSources(effect);
241
205
  }
242
206
  }
243
-
244
207
  //#endregion
245
- //#region src/watch/clearTargets.ts
208
+ //#region src/watch/routeEffectError.ts
246
209
  /**
247
- * Clear unused target subscriptions after all Effects have been run.
210
+ * Routes an error thrown by an effect re-run to the nearest enclosing error
211
+ * boundary (`@try`/`@catch` or top-level `@error`), and forces the boundary's
212
+ * control effect to re-run so it renders its catch branch. Returns true if a
213
+ * boundary handled the error.
214
+ *
215
+ * The boundary is found by walking the flattened region chain from the
216
+ * effect's owning region (`Effect.region`, set by `$run`) through its
217
+ * ancestors (regions with strictly decreasing depth on the `previousRegion`
218
+ * chain — the same shape `clearRegion` walks).
219
+ *
220
+ * For recovery, the boundary holds the failing effect's source signals
221
+ * (captured by `runEffect` before it cleared them, `Effect.errorSources`)
222
+ * together with the boundary effect's own sources: reads wrapped in nested
223
+ * `$run` effects (text/attribute interpolation) are tracked by those
224
+ * effects, not the boundary, so without holding them the catch branch would
225
+ * never re-attempt the try branch. `runTry` re-subscribes the boundary
226
+ * effect to the held signals on every run that shows the catch branch.
227
+ *
228
+ * Called from `triggerEffects`' per-effect catch. If forcing the boundary
229
+ * re-run itself throws (e.g. the catch branch content errors), the error
230
+ * propagates to the caller, which reports it as unhandled — matching the
231
+ * compiled form, where a throwing catch branch escapes the boundary.
248
232
  */
249
- function clearTargets(source) {
250
- let previousSub = null;
251
- for (let clearSub = source.firstTarget; clearSub !== null; clearSub = clearSub.nextTarget) if (!clearSub.active) if (previousSub === null) source.firstTarget = clearSub.nextTarget;
252
- else previousSub.nextTarget = clearSub.nextTarget;
253
- else previousSub = clearSub;
233
+ function routeEffectError(effect, error) {
234
+ let region = effect.region ?? null;
235
+ while (region !== null) {
236
+ const boundary = region.errorBoundary;
237
+ if (boundary !== void 0 && boundary.effect !== null) {
238
+ const boundaryEffect = boundary.effect;
239
+ const held = [];
240
+ for (let sub = boundaryEffect.firstSource; sub !== null; sub = sub.nextSource) held.push(sub.source);
241
+ for (const signal of effect.errorSources ?? []) if (!held.includes(signal)) held.push(signal);
242
+ boundary.error = error;
243
+ boundary.hasError = true;
244
+ boundary.heldSignals = held;
245
+ runCleanups(boundaryEffect);
246
+ deactivateSources(boundaryEffect);
247
+ runEffect(boundaryEffect);
248
+ clearSources(boundaryEffect);
249
+ return true;
250
+ }
251
+ const depth = region.depth;
252
+ let previous = region.previousRegion;
253
+ while (previous !== null && previous.depth >= depth) previous = previous.previousRegion;
254
+ region = previous;
255
+ }
256
+ return false;
254
257
  }
255
-
256
258
  //#endregion
257
259
  //#region src/watch/triggerEffects.ts
258
260
  /**
261
+ * Re-subscribes a failed effect to the suspended computeds its run had read,
262
+ * after `runEffect`'s catch detached them via `clearSources`. Called when no
263
+ * error boundary handled the crash: the error still surfaces (see below),
264
+ * but the promise's resolve re-runs the effect, so a crash caused by a
265
+ * pending read's `undefined` heals instead of leaving a dead effect.
266
+ */
267
+ function resubscribeSuspendSources(effect) {
268
+ const sources = effect.suspendSources;
269
+ if (!sources || sources.size === 0) return;
270
+ const oldActive = context.activeTarget;
271
+ context.activeTarget = effect;
272
+ for (const signal of sources) trackSignal(signal);
273
+ context.activeTarget = oldActive;
274
+ }
275
+ /**
259
276
  * Runs the effects that have been collected during the batch.
260
277
  */
261
278
  function triggerEffects() {
262
- let didError = false;
263
- let error;
264
- let effect = context_default.firstEffectToRun;
265
- while (effect !== null) {
266
- context_default.batchOperation++;
279
+ let unhandledError = null;
280
+ const queue = context.effectsToRun;
281
+ for (let i = 0; i < queue.length; i++) {
282
+ const effect = queue[i];
283
+ context.batchOperation++;
284
+ effect.queued = false;
267
285
  try {
268
286
  checkEffect(effect);
269
287
  } catch (err) {
270
- if (!didError) {
271
- didError = true;
272
- error = err;
288
+ let handled = false;
289
+ try {
290
+ handled = routeEffectError(effect, err);
291
+ } catch (routingError) {
292
+ if (unhandledError === null) unhandledError = { error: routingError };
293
+ }
294
+ if (!handled) {
295
+ resubscribeSuspendSources(effect);
296
+ if (unhandledError === null) unhandledError = { error: err };
273
297
  }
274
298
  }
275
- effect = effect.nextEffectToRun;
276
299
  }
277
- effect = context_default.firstEffectToRun;
278
- context_default.firstEffectToRun = null;
279
- while (effect !== null) {
280
- let nextEffect = effect.nextEffectToRun;
281
- effect.nextEffectToRun = null;
282
- effect = nextEffect;
283
- }
284
- let signal = context_default.firstSignalToUpdate;
285
- context_default.firstSignalToUpdate = null;
300
+ for (let effect of queue) effect.queued = false;
301
+ context.effectsToRun = [];
302
+ let signal = context.firstSignalToUpdate;
303
+ context.firstSignalToUpdate = null;
304
+ context.lastSignalToUpdate = null;
286
305
  while (signal !== null) {
287
- clearTargets(signal);
288
306
  const nextSignal = signal.nextSignalToUpdate;
289
307
  signal.nextSignalToUpdate = null;
290
308
  signal = nextSignal;
291
309
  }
292
- if (didError) throw error;
310
+ if (unhandledError !== null) throw unhandledError.error;
293
311
  }
294
-
295
312
  //#endregion
296
313
  //#region src/watch/batchEnd.ts
297
314
  function batchEnd() {
298
- if (context_default.batch > 1) {
299
- context_default.batch--;
315
+ if (context.batch > 1) {
316
+ context.batch--;
300
317
  return;
301
318
  }
302
319
  try {
303
320
  triggerEffects();
304
321
  } finally {
305
- context_default.batch = 0;
306
- context_default.batchOperation = 0;
307
- context_default.previousEffect = null;
322
+ context.batch = 0;
323
+ context.batchOperation = 0;
324
+ context.previousEffect = null;
308
325
  }
309
326
  }
310
-
311
327
  //#endregion
312
328
  //#region src/watch/batchStart.ts
313
329
  function batchStart() {
314
- context_default.batch++;
330
+ context.batch++;
315
331
  }
316
-
317
332
  //#endregion
318
333
  //#region src/watch/runEffect.ts
319
334
  function runEffect(effect) {
320
- devContext_default.effectRun(effect);
321
- const oldActiveTarget = context_default.activeTarget;
322
- const oldExtent = context_default.extent;
335
+ devContext.effectRun(effect);
336
+ const oldActiveTarget = context.activeTarget;
337
+ const oldExtent = context.extent;
323
338
  effect.didError = false;
339
+ effect.errorSources = null;
340
+ effect.didSuspend = false;
341
+ effect.suspendSources = null;
324
342
  batchStart();
325
343
  try {
326
- if (context_default.previousEffect !== null) context_default.previousEffect.nextEffect = effect;
327
- context_default.activeTarget = effect;
328
- context_default.previousEffect = effect;
329
- context_default.extent = 1;
344
+ if (context.previousEffect !== null) context.previousEffect.nextEffect = effect;
345
+ context.activeTarget = effect;
346
+ context.previousEffect = effect;
347
+ context.extent = 1;
330
348
  effect.cleanup = effect.run();
331
- effect.extent = context_default.extent;
349
+ effect.extent = context.extent;
332
350
  } catch (err) {
333
351
  effect.didError = true;
352
+ let sources = null;
353
+ for (let sub = effect.firstSource; sub !== null; sub = sub.nextSource) (sources ??= []).push(sub.source);
354
+ effect.errorSources = sources;
334
355
  clearSources(effect);
335
356
  throw err;
336
357
  } finally {
337
- context_default.activeTarget = oldActiveTarget;
338
- context_default.extent += oldExtent - 1;
358
+ context.activeTarget = oldActiveTarget;
359
+ context.extent += oldExtent - 1;
339
360
  batchEnd();
340
361
  }
341
362
  }
342
-
343
363
  //#endregion
344
364
  //#region src/watch/$run.ts
345
365
  /**
346
366
  * Runs and re-runs a function that depends on a watched object
347
367
  *
348
368
  * @param fn The function to run, which may return a cleanup function.
369
+ * @param options Internal fields to set on the constructed Effect (e.g.
370
+ * `isMountEffect`, `forVarDeps`). Not part of the public API.
349
371
  */
350
- function $run(fn, name) {
372
+ function $run(fn, name, options) {
351
373
  let effect = {
352
- type: EFFECT_TYPE,
374
+ type: 2,
353
375
  run: fn,
354
376
  cleanup: void 0,
355
377
  firstSource: null,
356
378
  nextEffect: null,
357
379
  extent: 0,
358
- nextEffectToRun: null,
380
+ queued: false,
359
381
  didError: false,
360
- name
382
+ didSuspend: false,
383
+ region: null,
384
+ errorSources: null,
385
+ name,
386
+ isMountEffect: options?.isMountEffect,
387
+ forVarMask: options?.forVarMask
361
388
  };
362
- devContext_default.onRun(effect);
389
+ const region = context.activeRegion;
390
+ if (region !== null) {
391
+ region.effects.push(effect);
392
+ effect.region = region;
393
+ }
394
+ devContext.onRun(effect);
363
395
  runEffect(effect);
364
396
  return effect;
365
397
  }
366
-
398
+ //#endregion
399
+ //#region src/watch/$peek.ts
400
+ /**
401
+ * Runs a function without tracking the reactive values it reads: `$watch`'d
402
+ * state accessed inside `fn` does not become a dependency of the currently
403
+ * running effect or computed. Useful for reading state inside an effect
404
+ * without re-running it when that state changes.
405
+ *
406
+ * @param fn The function to run untracked.
407
+ */
408
+ function $peek(fn) {
409
+ const oldActiveTarget = context.activeTarget;
410
+ context.activeTarget = null;
411
+ const result = fn();
412
+ context.activeTarget = oldActiveTarget;
413
+ return result;
414
+ }
415
+ //#endregion
416
+ //#region src/watch/flushMountEffects.ts
417
+ /**
418
+ * Runs the collected `$onmount`/`onmount` callbacks — once, after the
419
+ * component's markup has been added to the DOM (or, when hydrating, after
420
+ * hydration is complete). Multiple callbacks run in the order they were
421
+ * added.
422
+ *
423
+ * Each callback becomes an effect with `isMountEffect` set, so the keyed-list
424
+ * reconciler's force-rerun path (`rerunRegionEffects`) skips it. Its body
425
+ * also runs untracked: mount callbacks are once-only, so reactive reads
426
+ * inside them do not subscribe. In dev builds a tracked pass warns when a
427
+ * callback reads reactive state, since that is almost always a mistake — the
428
+ * reactive part should be wrapped in `$run`.
429
+ */
430
+ function flushMountEffects() {
431
+ if (context.mountEffects.length === 0) return;
432
+ const activeRegion = context.activeRegion;
433
+ for (let effect of context.mountEffects) {
434
+ context.activeRegion = effect.region;
435
+ $run(() => runMountCallback(effect.fn), void 0, { isMountEffect: true });
436
+ }
437
+ context.activeRegion = activeRegion;
438
+ context.mountEffects.length = 0;
439
+ }
440
+ function runMountCallback(fn) {
441
+ if (!devContext.enabled) return $peek(fn);
442
+ const result = fn();
443
+ const effect = context.activeTarget;
444
+ if (effect !== null && effect.type === 2 && effect.firstSource !== null) {
445
+ console.warn("[torpor] A $onmount/onmount callback read reactive state, but mount callbacks run only once and will not re-run. Wrap the reactive part in $run(), e.g. $onmount(() => { $run(() => ...); });");
446
+ deactivateSources(effect);
447
+ clearSources(effect);
448
+ }
449
+ return result;
450
+ }
367
451
  //#endregion
368
452
  //#region src/render/animate.ts
369
453
  /**
@@ -384,76 +468,279 @@ async function animate(el, enter, keyframes, options) {
384
468
  setTimeout(() => {
385
469
  animation.timeline = el.ownerDocument.timeline;
386
470
  }, 1);
387
- const activeRegion = context_default.activeRegion;
471
+ const activeRegion = context.activeRegion;
388
472
  activeRegion.animations ??= /* @__PURE__ */ new Set();
389
473
  activeRegion.animations.add(animation);
390
474
  await animation.finished;
391
475
  }
392
-
476
+ //#endregion
477
+ //#region src/render/delegatedEvents.ts
478
+ /**
479
+ * Event delegation.
480
+ *
481
+ * For event types in `DELEGATED_EVENT_TYPES` (all natively bubbling), we
482
+ * register a single listener on `document` per type and dispatch by walking
483
+ * up from `event.target` to find the closest ancestor with a stashed handler.
484
+ * This replaces per-element `addEventListener` for delegated types.
485
+ *
486
+ * Why: in the js-framework-bench row template, every `<tr>` clones two `<a>`
487
+ * elements each with a `click` handler. With per-element `addEventListener`,
488
+ * `runlots` (10k rows) issues 20000 `addEventListener` calls and the browser
489
+ * allocates 20000 `Listener` objects. With delegation it's 2 calls total
490
+ * (one per delegated type, registered lazily on first use) and zero
491
+ * per-element `Listener` allocations — the handler is stored as a property
492
+ * on the element.
493
+ *
494
+ * Model: last-write-wins per element per type (same as Solid's
495
+ * `delegateEvents`). Repeated `t_event(el, "click", h)` calls with the same
496
+ * element reassign the property; calling with `null`/`undefined` clears it.
497
+ * Torpor's compiler emits `t_event(el, type, h)` exactly once per element
498
+ * lifetime (outside any tracked effect), so this is the natural shape.
499
+ *
500
+ * Non-bubbling events (`focus`, `blur`, `scroll`, `load`, `error`, `abort`,
501
+ * `unload`, `resize`, etc.) bypass delegation and use direct
502
+ * `addEventListener` on the element, preserving native semantics.
503
+ */
504
+ const DELEGATED_EVENT_TYPES = /* @__PURE__ */ new Set([
505
+ "auxclick",
506
+ "beforeinput",
507
+ "change",
508
+ "click",
509
+ "compositionend",
510
+ "compositionstart",
511
+ "compositionupdate",
512
+ "contextmenu",
513
+ "dblclick",
514
+ "drag",
515
+ "dragend",
516
+ "dragenter",
517
+ "dragleave",
518
+ "dragover",
519
+ "dragstart",
520
+ "drop",
521
+ "focusin",
522
+ "focusout",
523
+ "input",
524
+ "keydown",
525
+ "keypress",
526
+ "keyup",
527
+ "mousedown",
528
+ "mousemove",
529
+ "mouseout",
530
+ "mouseover",
531
+ "mouseup",
532
+ "pointerdown",
533
+ "pointermove",
534
+ "pointerout",
535
+ "pointerover",
536
+ "pointerup",
537
+ "reset",
538
+ "submit",
539
+ "touchend",
540
+ "touchmove",
541
+ "touchstart",
542
+ "wheel"
543
+ ]);
544
+ function isDelegatedEventType(type) {
545
+ return DELEGATED_EVENT_TYPES.has(type);
546
+ }
547
+ const DELEGATE_PREFIX = "torp.$$";
548
+ const DELEGATE_REGISTERED = Symbol.for("torp.delegated.registered");
549
+ function delegatedHandler(event) {
550
+ let node = event.target;
551
+ const stopAt = event.currentTarget;
552
+ const key = DELEGATE_PREFIX + event.type;
553
+ while (node != null && node !== stopAt) {
554
+ const handler = node[key];
555
+ if (handler !== void 0) {
556
+ Object.defineProperty(event, "currentTarget", {
557
+ configurable: true,
558
+ value: node,
559
+ writable: false
560
+ });
561
+ try {
562
+ handler.call(node, event);
563
+ } finally {
564
+ delete event.currentTarget;
565
+ }
566
+ return;
567
+ }
568
+ node = node.parentNode;
569
+ }
570
+ }
571
+ function ensureDelegatedListener(type) {
572
+ if (typeof document === "undefined") return;
573
+ let registered = document[DELEGATE_REGISTERED];
574
+ if (!registered) {
575
+ registered = /* @__PURE__ */ new Set();
576
+ document[DELEGATE_REGISTERED] = registered;
577
+ }
578
+ if (registered.has(type)) return;
579
+ registered.add(type);
580
+ document.addEventListener(type, delegatedHandler);
581
+ }
582
+ /**
583
+ * Attach a delegated event handler to an element.
584
+ *
585
+ * Stores the handler as a property on the element and ensures a single
586
+ * document-level listener exists for the type. Idempotent for the
587
+ * document-level listener: the first call for a given type registers it,
588
+ * subsequent calls are a Set-has check.
589
+ *
590
+ * Passing `null` or `undefined` as the listener clears any previously-set
591
+ * handler for that type on the element (mirroring `addEvent`'s existing
592
+ * null-skipping semantics, extended to support explicit removal).
593
+ */
594
+ function attachDelegatedEvent(el, type, listener) {
595
+ const key = DELEGATE_PREFIX + type;
596
+ if (listener === void 0 || listener === null) {
597
+ el[key] = void 0;
598
+ return;
599
+ }
600
+ ensureDelegatedListener(type);
601
+ el[key] = listener;
602
+ }
603
+ const DIRECT_LISTENERS = "torp.$directListeners";
604
+ /**
605
+ * Records a direct (non-delegated) listener on the element at attach time,
606
+ * so `copyEventListeners` can re-attach it after a dynamic-element tag
607
+ * swap. `addEventListener` listeners can't be discovered after the fact.
608
+ */
609
+ function recordDirectListener(el, type, listener) {
610
+ let list = el[DIRECT_LISTENERS];
611
+ if (!list) {
612
+ list = [];
613
+ el[DIRECT_LISTENERS] = list;
614
+ }
615
+ list.push({
616
+ type,
617
+ listener
618
+ });
619
+ }
620
+ /**
621
+ * Copies the event listeners attached to one element onto another — used by
622
+ * `t_dynamic` so a dynamic element keeps its listeners when its tag changes.
623
+ * Delegated handlers are `torp.$$<type>` properties, copied per known
624
+ * delegated type (swaps are rare, so the fixed set of checks is fine);
625
+ * direct listeners are re-registered from the list `recordDirectListener`
626
+ * built at attach time.
627
+ */
628
+ function copyEventListeners(from, to) {
629
+ for (const type of DELEGATED_EVENT_TYPES) {
630
+ const key = DELEGATE_PREFIX + type;
631
+ const handler = from[key];
632
+ if (handler !== void 0) to[key] = handler;
633
+ }
634
+ const direct = from[DIRECT_LISTENERS];
635
+ if (direct) {
636
+ to[DIRECT_LISTENERS] = direct;
637
+ for (const { type, listener } of direct) to.addEventListener(type, listener);
638
+ }
639
+ }
393
640
  //#endregion
394
641
  //#region src/render/isFragmentNode.ts
395
642
  function isFragmentNode(node) {
396
643
  return node.nodeType === 11;
397
644
  }
398
-
645
+ //#endregion
646
+ //#region src/render/runMountSideEffects.ts
647
+ /**
648
+ * Runs the mount-time side effects that both `addFragment` and `addElement`
649
+ * share: `$onmount` effects (only when not hydrating), stashed event
650
+ * listeners, and stashed animations. No-op when `parent` is itself a
651
+ * `DocumentFragment` (we're being inserted into a detached tree, so
652
+ * `$onmount` and event hookup would be premature — they'll run when the
653
+ * outer fragment attaches).
654
+ *
655
+ * Extracted so the `DocumentFragment` path (`addFragment`) and the
656
+ * single-element path (`addElement`) don't duplicate this logic.
657
+ */
658
+ function runMountSideEffects(parent, activeRegion, hydrationNode) {
659
+ if (isFragmentNode(parent)) return;
660
+ if (hydrationNode === null) flushMountEffects();
661
+ if (context.stashedEvents.length > 0) {
662
+ for (let event of context.stashedEvents) if (isDelegatedEventType(event.type)) attachDelegatedEvent(event.el, event.type, event.listener);
663
+ else {
664
+ event.el.addEventListener(event.type, event.listener);
665
+ recordDirectListener(event.el, event.type, event.listener);
666
+ }
667
+ context.stashedEvents.length = 0;
668
+ }
669
+ for (let animation of context.stashedAnimations) {
670
+ context.activeRegion = animation.region;
671
+ $run(function runMountSideEffectsAnimation() {
672
+ if (animation.in !== void 0) animate(animation.el, true, animation.in.keyframes, animation.in.options);
673
+ if (animation.out !== void 0) return () => {
674
+ animate(animation.el, false, animation.out.keyframes, animation.out.options);
675
+ };
676
+ });
677
+ }
678
+ context.stashedAnimations.length = 0;
679
+ context.activeRegion = activeRegion;
680
+ }
681
+ //#endregion
682
+ //#region src/render/addElement.ts
683
+ /**
684
+ * Companion to `addFragment` for the single-root-element codegen path. Wires
685
+ * a cloned root element (produced by `getElementFragment`) into the live DOM
686
+ * tree, sets the active region's start/end nodes, and runs the same
687
+ * mount-time side effects as `addFragment` (`$onmount` effects, stashed event
688
+ * listeners, stashed animations).
689
+ *
690
+ * Differences from `addFragment`:
691
+ * - `node` is both the start and end of the region (no
692
+ * `fragment.firstChild`/`fragment.lastChild` indirection).
693
+ * - When hydrating, the existing DOM node is reused (the cloned `node` is
694
+ * discarded); `endNode` is still `node` because `nodeRootElement` returns
695
+ * the hydration cursor's node in that case, not the cloned one.
696
+ *
697
+ * @param node The root element (cloned by `getElementFragment`, or the
698
+ * hydration cursor's node when hydrating).
699
+ * @param parent The intended parent element.
700
+ * @param before The sibling to insert before (or `null` to append).
701
+ */
702
+ function addElement(node, parent, before) {
703
+ const activeRegion = context.activeRegion;
704
+ const hydrationNode = context.hydrationNode;
705
+ activeRegion.startNode = node;
706
+ activeRegion.endNode = node;
707
+ parent = before?.parentNode ?? parent;
708
+ if (hydrationNode === null) parent.insertBefore(node, before);
709
+ runMountSideEffects(parent, activeRegion, hydrationNode);
710
+ }
399
711
  //#endregion
400
712
  //#region src/render/addFragment.ts
401
- function addFragment(fragment, parent, before, endNode) {
402
- const activeRegion = context_default.activeRegion;
403
- const hydrationNode = context_default.hydrationNode;
404
- if (hydrationNode !== null) activeRegion.endNode = endNode ?? hydrationNode;
405
- else {
713
+ function addFragment(fragment, parent, before, endNode, startNode) {
714
+ const activeRegion = context.activeRegion;
715
+ const hydrationNode = context.hydrationNode;
716
+ if (hydrationNode !== null) {
717
+ if (startNode !== void 0 && startNode.parentNode !== null) activeRegion.startNode = startNode;
718
+ activeRegion.endNode = endNode ?? hydrationNode;
719
+ } else {
406
720
  activeRegion.startNode = fragment.firstChild;
407
721
  activeRegion.endNode = fragment.lastChild;
408
722
  }
409
723
  parent = before?.parentNode ?? parent;
410
724
  if (hydrationNode === null) parent.insertBefore(fragment, before);
411
- if (!isFragmentNode(parent)) {
412
- if (hydrationNode === null) {
413
- for (let effect of context_default.mountEffects) $run(effect);
414
- context_default.mountEffects.length = 0;
415
- }
416
- if (context_default.stashedEvents.length > 0) {
417
- const events = [...context_default.stashedEvents];
418
- $run(function addFragmentEvents() {
419
- for (let event of events) event.el.addEventListener(event.type, event.listener);
420
- return () => {
421
- for (let event of events) event.el.removeEventListener(event.type, event.listener);
422
- };
423
- });
424
- context_default.stashedEvents.length = 0;
425
- }
426
- for (let animation of context_default.stashedAnimations) {
427
- context_default.activeRegion = animation.region;
428
- $run(function addFragmentAnimation() {
429
- if (animation.in !== void 0) animate(animation.el, true, animation.in.keyframes, animation.in.options);
430
- if (animation.out !== void 0) return () => {
431
- animate(animation.el, false, animation.out.keyframes, animation.out.options);
432
- };
433
- });
434
- }
435
- context_default.stashedAnimations.length = 0;
436
- context_default.activeRegion = activeRegion;
437
- }
725
+ runMountSideEffects(parent, activeRegion, hydrationNode);
438
726
  }
439
-
440
727
  //#endregion
441
728
  //#region src/render/applyProps.ts
442
729
  function applyProps(el, props, propNamesUsed) {
443
730
  if (props !== void 0) {
444
731
  for (let [name, value] of Object.entries(props)) if (!propNamesUsed.includes(name)) if (name.startsWith("on")) {
445
732
  const eventName = name.substring(2);
446
- el.addEventListener(eventName, value);
447
- } else $run(function setAttribute$1() {
733
+ if (isDelegatedEventType(eventName)) attachDelegatedEvent(el, eventName, value);
734
+ else el.addEventListener(eventName, value);
735
+ } else $run(function setAttribute() {
448
736
  el.setAttribute(name, value);
449
737
  });
450
738
  }
451
739
  }
452
-
453
740
  //#endregion
454
741
  //#region src/render/clearRegion.ts
455
742
  function clearRegion(region) {
456
- devContext_default.onRegionCleared(region);
743
+ devContext.onRegionCleared(region);
457
744
  let animations = region.animations !== null ? Array.from(region.animations) : void 0;
458
745
  let childRegion = region.nextRegion;
459
746
  while (childRegion !== null && childRegion.depth > region.depth) {
@@ -461,9 +748,10 @@ function clearRegion(region) {
461
748
  animations ??= [];
462
749
  animations.push(...childRegion.animations);
463
750
  }
751
+ const nextChild = childRegion.nextRegion;
464
752
  releaseRegion(childRegion);
465
753
  childRegion.depth = -2;
466
- childRegion = childRegion.nextRegion;
754
+ childRegion = nextChild;
467
755
  }
468
756
  region.nextRegion = childRegion;
469
757
  if (region.previousRegion !== null) region.previousRegion.nextRegion = region.nextRegion;
@@ -478,31 +766,83 @@ function clearRegion(region) {
478
766
  }
479
767
  function clearNodes(region) {
480
768
  if (region.startNode !== null && region.endNode !== null) {
769
+ const after = region.endNode.nextSibling;
770
+ let stop = region.startNode;
771
+ const startDetached = region.startNode.parentNode === null;
772
+ let fallback = false;
773
+ if (startDetached) {
774
+ let prev = region.previousRegion;
775
+ while (prev !== null && prev.depth > region.depth) prev = prev.previousRegion;
776
+ if (prev !== null && prev.endNode !== null && prev.endNode.parentNode !== null) {
777
+ stop = prev.endNode;
778
+ fallback = true;
779
+ }
780
+ }
481
781
  let currentNode = region.endNode;
482
- while (currentNode !== region.startNode) {
782
+ while (currentNode !== null && currentNode !== stop) {
483
783
  let previousNode = currentNode.previousSibling;
484
784
  currentNode.remove();
785
+ if (previousNode === null) break;
485
786
  currentNode = previousNode;
486
787
  }
487
- currentNode.remove();
788
+ if (!fallback && currentNode === region.startNode) currentNode.remove();
789
+ const firstRemaining = fallback ? stop : after;
790
+ if (firstRemaining !== null) {
791
+ let ancestor = region.previousRegion;
792
+ let ancestorDepth = region.depth;
793
+ while (ancestor !== null && ancestor.depth < ancestorDepth) {
794
+ if (ancestor.startNode !== null && ancestor.startNode.parentNode === null) ancestor.startNode = firstRemaining;
795
+ ancestorDepth = ancestor.depth;
796
+ ancestor = ancestor.previousRegion;
797
+ }
798
+ }
488
799
  }
489
800
  releaseRegion(region);
490
801
  }
491
802
  function releaseRegion(region) {
803
+ region.generation = -1;
492
804
  region.startNode = null;
493
805
  region.endNode = null;
494
806
  region.previousRegion = null;
495
807
  region.nextRegion = null;
496
808
  region.animations = null;
809
+ region.errorBoundary = void 0;
810
+ for (const effect of region.effects) {
811
+ if (typeof effect.cleanup === "function") {
812
+ effect.cleanup();
813
+ effect.cleanup = void 0;
814
+ }
815
+ let sub = effect.firstSource;
816
+ effect.firstSource = null;
817
+ while (sub !== null) {
818
+ const nextSource = sub.nextSource;
819
+ const prev = sub.previousTarget;
820
+ const next = sub.nextTarget;
821
+ if (prev === null) {
822
+ if (sub.source.firstTarget === sub) sub.source.firstTarget = next;
823
+ } else prev.nextTarget = next;
824
+ if (next !== null) next.previousTarget = prev;
825
+ sub.previousTarget = null;
826
+ sub.nextTarget = null;
827
+ sub.nextSource = null;
828
+ sub = nextSource;
829
+ }
830
+ }
831
+ region.effects.length = 0;
497
832
  }
498
-
499
833
  //#endregion
500
834
  //#region src/render/clearLayoutSlot.ts
835
+ /**
836
+ * Clears a region that was created by `fillLayoutSlot`: tears down the
837
+ * rendered content and its effects, leaving the surrounding layout intact
838
+ * so the slot can be refilled.
839
+ *
840
+ * @param region The region to clear
841
+ */
501
842
  function clearLayoutSlot(region) {
502
- context_default.previousRegion = region.previousRegion;
843
+ context.previousRegion = region.previousRegion;
503
844
  clearRegion(region);
504
845
  }
505
-
506
846
  //#endregion
507
847
  //#region src/render/newRegion.ts
508
848
  function newRegion(name) {
@@ -513,45 +853,80 @@ function newRegion(name) {
513
853
  nextRegion: null,
514
854
  depth: -1,
515
855
  animations: null,
516
- name
856
+ name,
857
+ effects: []
517
858
  };
518
859
  }
519
-
520
860
  //#endregion
521
861
  //#region src/render/popRegion.ts
522
862
  function popRegion(oldRegion) {
523
- context_default.activeRegion = oldRegion;
524
- devContext_default.onRegionPopped();
863
+ context.activeRegion = oldRegion;
864
+ devContext.onRegionPopped();
525
865
  }
526
-
527
866
  //#endregion
528
867
  //#region src/render/pushRegion.ts
529
868
  function pushRegion(region, toParent = false) {
530
- const activeRegion = context_default.activeRegion;
869
+ const activeRegion = context.activeRegion;
531
870
  if (toParent) {
532
- const previousRegion = context_default.previousRegion;
871
+ const previousRegion = context.previousRegion;
533
872
  region.previousRegion = previousRegion;
534
873
  const nextRegion = previousRegion.nextRegion;
535
874
  previousRegion.nextRegion = region;
536
875
  region.nextRegion = nextRegion;
876
+ if (nextRegion !== null) nextRegion.previousRegion = region;
537
877
  region.depth = activeRegion.depth + 1;
538
878
  }
539
- context_default.activeRegion = region;
540
- context_default.previousRegion = region;
541
- devContext_default.onRegionPushed(region, toParent);
879
+ context.activeRegion = region;
880
+ context.previousRegion = region;
881
+ devContext.onRegionPushed(region, toParent);
542
882
  return activeRegion;
543
883
  }
544
-
545
884
  //#endregion
546
885
  //#region src/render/fillLayoutSlot.ts
886
+ /**
887
+ * Renders a component into a persistent layout slot, and returns the region
888
+ * it was rendered into. Used by the layout engine during navigation: the
889
+ * component is created inside `parent` at `anchor`, with `slot` as its child
890
+ * slot render, and the returned region can later be passed to
891
+ * `clearLayoutSlot` to tear the page down — leaving the layout itself
892
+ * intact — before refilling the slot.
893
+ *
894
+ * @param component The component to render into the slot
895
+ * @param slot The slot render to pass to the component
896
+ * @param parent The parent node to render into
897
+ * @param anchor The node to insert content before, or null to append
898
+ * @param $props Optional props to pass to the component
899
+ * @param $context Optional context to pass to the component
900
+ */
547
901
  function fillLayoutSlot(component, slot, parent, anchor, $props, $context) {
548
- const region = newRegion(devContext_default.enabled ? "Layout slot" : void 0);
902
+ const region = newRegion(devContext.enabled ? "Layout slot" : void 0);
549
903
  const oldRegion = pushRegion(region, true);
550
904
  component(parent, anchor, $props, $context, { _: slot });
551
905
  popRegion(oldRegion);
552
906
  return region;
553
907
  }
554
-
908
+ //#endregion
909
+ //#region src/render/firstInsideNode.ts
910
+ /**
911
+ * During hydration, `nodeAnchor` finds the first node inside a hydration
912
+ * block and removes the start/end marker comments. Generated code for
913
+ * `@html` needs that first node later (to adopt the server-rendered nodes
914
+ * as the region's bounds), but by then the markers are gone — so the only
915
+ * reliable way to recover it is to stash it here, keyed by the anchor node
916
+ * that `nodeAnchor` returns.
917
+ */
918
+ const firstInsideNodes = /* @__PURE__ */ new WeakMap();
919
+ function setFirstInsideNode(anchor, node) {
920
+ firstInsideNodes.set(anchor, node);
921
+ }
922
+ /**
923
+ * Gets the first node that was inside the hydration block for the given
924
+ * anchor node, or `undefined` if the anchor wasn't hydrated through
925
+ * hydration markers.
926
+ */
927
+ function firstInsideNode(anchor) {
928
+ return firstInsideNodes.get(anchor);
929
+ }
555
930
  //#endregion
556
931
  //#region src/render/getFragment.ts
557
932
  function getFragment(document, array, index, html, ns) {
@@ -568,7 +943,44 @@ function getFragment(document, array, index, html, ns) {
568
943
  }
569
944
  return array[index].cloneNode(true);
570
945
  }
571
-
946
+ //#endregion
947
+ //#region src/render/getElementFragment.ts
948
+ /**
949
+ * Returns a clone of the cached template's single root element, bypassing the
950
+ * `DocumentFragment` wrapper that `getFragment` produces.
951
+ *
952
+ * Used by the compiler-emitted `createListItem` for `@for` bodies (and other
953
+ * fragments) whose template has exactly one rendering root child — e.g.
954
+ * `<tr><td>...</td>...</tr>`. Cloning `template.content.firstElementChild`
955
+ * directly saves the per-row `DocumentFragment` allocation that `getFragment`'s
956
+ * `cloneNode(true)` on the cached template's content would otherwise produce,
957
+ * which dominates the cost of bulk-row creates (`run`/`add`/`runlots`).
958
+ *
959
+ * Contract: the compiler only emits `t_fragment_el` for fragment indices whose
960
+ * template has exactly one rendering root, and that root is an `Element`. The
961
+ * cache array (`t_fragment_els`) is separate from `t_fragments` so each helper
962
+ * only ever sees its own cached type at a given index.
963
+ *
964
+ * @param document The owner document (used to build the cached `<template>`).
965
+ * @param array The per-component `t_fragment_els` cache.
966
+ * @param index The fragment's index in the cache.
967
+ * @param html The fragment's HTML source, with `#` placeholders for reactive
968
+ * text and `<!>` for anchor comments.
969
+ * @param ns When true, the template is created in the SVG namespace (its
970
+ * `firstElementChild` is then an SVG element).
971
+ */
972
+ function getElementFragment(document, array, index, html, ns) {
973
+ if (array[index] === void 0) if (ns === true) {
974
+ const template = document.createElementNS("http://www.w3.org/2000/svg", "template");
975
+ template.innerHTML = html;
976
+ array[index] = template.firstElementChild;
977
+ } else {
978
+ const template = document.createElement("template");
979
+ template.innerHTML = html;
980
+ array[index] = template.content.firstElementChild;
981
+ }
982
+ return array[index].cloneNode(true);
983
+ }
572
984
  //#endregion
573
985
  //#region src/render/hydrate.ts
574
986
  /**
@@ -578,16 +990,14 @@ function getFragment(document, array, index, html, ns) {
578
990
  * @param props An object containing component props
579
991
  */
580
992
  function hydrate(parent, component, props, slots) {
581
- context_default.hydrationNode = parent.firstChild;
582
- context_default.rootRegion = newRegion(devContext_default.enabled ? "Root" : void 0);
583
- context_default.previousRegion = context_default.rootRegion;
584
- pushRegion(context_default.rootRegion);
993
+ context.hydrationNode = parent.firstChild;
994
+ context.rootRegion = newRegion(devContext.enabled ? "Root" : void 0);
995
+ context.previousRegion = context.rootRegion;
996
+ pushRegion(context.rootRegion);
585
997
  component(parent, null, props, void 0, slots);
586
- context_default.hydrationNode = null;
587
- for (let effect of context_default.mountEffects) $run(effect);
588
- context_default.mountEffects.length = 0;
998
+ context.hydrationNode = null;
999
+ flushMountEffects();
589
1000
  }
590
-
591
1001
  //#endregion
592
1002
  //#region src/render/mount.ts
593
1003
  /**
@@ -600,14 +1010,36 @@ function hydrate(parent, component, props, slots) {
600
1010
  function mount(parent, component, props, slots) {
601
1011
  if (parent.childElementCount > 0) throw new Error("The parent node must have no child elements");
602
1012
  while (parent.firstChild !== null) parent.firstChild.remove();
603
- if (context_default.rootRegion === null) {
604
- context_default.rootRegion = newRegion(devContext_default.enabled ? "Root" : void 0);
605
- context_default.previousRegion = context_default.rootRegion;
606
- pushRegion(context_default.rootRegion);
1013
+ if (context.rootRegion === null) {
1014
+ context.rootRegion = newRegion(devContext.enabled ? "Root" : void 0);
1015
+ context.previousRegion = context.rootRegion;
1016
+ pushRegion(context.rootRegion);
607
1017
  }
608
1018
  component(parent, null, props, void 0, slots);
609
1019
  }
610
-
1020
+ //#endregion
1021
+ //#region src/render/unmount.ts
1022
+ /**
1023
+ * Tears down the current UI: disposes the root region tree (running effect
1024
+ * cleanups and detaching subscriptions), resets the render context, and
1025
+ * removes any remaining child nodes from `parent`.
1026
+ *
1027
+ * Call this before `mount`ing a fresh component tree into the same container
1028
+ * (e.g. when client-side navigating to a route whose layout chain differs
1029
+ * from the previous one). `mount` refuses to mount into a non-empty parent
1030
+ * and reuses an existing root region, so both must be cleared first.
1031
+ *
1032
+ * @param parent The container that the previous UI was mounted into
1033
+ */
1034
+ function unmount(parent) {
1035
+ if (context.rootRegion !== null) {
1036
+ clearRegion(context.rootRegion);
1037
+ context.rootRegion = null;
1038
+ context.previousRegion = null;
1039
+ context.activeRegion = null;
1040
+ }
1041
+ while (parent.firstChild !== null) parent.firstChild.remove();
1042
+ }
611
1043
  //#endregion
612
1044
  //#region src/render/newListItem.ts
613
1045
  function newListItem(data, key, name) {
@@ -620,28 +1052,20 @@ function newListItem(data, key, name) {
620
1052
  animations: null,
621
1053
  name,
622
1054
  data,
623
- key
1055
+ key,
1056
+ effects: []
624
1057
  };
625
1058
  }
626
-
627
- //#endregion
628
- //#region src/render/hydrationMarkers.ts
629
- const HYDRATION_START = "[";
630
- const HYDRATION_END = "]";
631
- const HYDRATION_BREAK = "^";
632
-
633
1059
  //#endregion
634
1060
  //#region src/render/isCommentNode.ts
635
1061
  function isCommentNode(node) {
636
1062
  return node.nodeType === 8;
637
1063
  }
638
-
639
1064
  //#endregion
640
1065
  //#region src/render/isTextNode.ts
641
1066
  function isTextNode(node) {
642
1067
  return node.nodeType === 3;
643
1068
  }
644
-
645
1069
  //#endregion
646
1070
  //#region src/render/nodeCheckHydrationBreak.ts
647
1071
  /**
@@ -653,17 +1077,14 @@ function isTextNode(node) {
653
1077
  * @returns The next node.
654
1078
  */
655
1079
  function nodeCheckHydrationBreak(node) {
656
- if (context_default.hydrationNode !== null) {
657
- if (node !== null && isCommentNode(node) && node.data === HYDRATION_BREAK) {
658
- let comment = node;
659
- node = node.nextSibling;
660
- comment.remove();
661
- }
662
- context_default.hydrationNode = node;
1080
+ if (node !== null && isCommentNode(node) && node.data === "^") {
1081
+ let comment = node;
1082
+ node = node.nextSibling;
1083
+ comment.remove();
663
1084
  }
1085
+ context.hydrationNode = node;
664
1086
  return node;
665
1087
  }
666
-
667
1088
  //#endregion
668
1089
  //#region src/render/nodeNext.ts
669
1090
  /**
@@ -675,10 +1096,18 @@ function nodeCheckHydrationBreak(node) {
675
1096
  * @param text Whether we require a text node.
676
1097
  */
677
1098
  function nodeNext(node, text = false) {
678
- if (context_default.hydrationNode !== null && text && isTextNode(node)) return node;
679
- return nodeCheckHydrationBreak(node.nextSibling);
1099
+ if (context.hydrationNode !== null) {
1100
+ if (text && isTextNode(node)) return node;
1101
+ let next = nodeCheckHydrationBreak(node.nextSibling);
1102
+ while (!text && next !== null && isTextNode(next) && next.textContent?.trim() === "") next = nodeCheckHydrationBreak(next.nextSibling);
1103
+ if (!text && next !== null && next.nodeName === "TBODY" && next.firstChild && isTextNode(node)) {
1104
+ next = next.firstChild;
1105
+ context.hydrationNode = next;
1106
+ }
1107
+ return next;
1108
+ }
1109
+ return node.nextSibling;
680
1110
  }
681
-
682
1111
  //#endregion
683
1112
  //#region src/render/nodeAnchor.ts
684
1113
  /**
@@ -696,32 +1125,43 @@ function nodeNext(node, text = false) {
696
1125
  * @returns The anchor node.
697
1126
  */
698
1127
  function nodeAnchor(node) {
699
- if (context_default.hydrationNode !== null) {
700
- if (isCommentNode(node) && node.data === HYDRATION_START) {
1128
+ if (context.hydrationNode !== null) {
1129
+ if (isCommentNode(node) && node.data === "[") {
1130
+ const startParent = node.parentNode;
701
1131
  let currentNode = nodeNext(node);
1132
+ const firstInside = currentNode;
702
1133
  node.remove();
703
1134
  let level = 1;
704
1135
  while (currentNode !== null) {
705
1136
  if (isCommentNode(currentNode)) {
706
- if (currentNode.data === HYDRATION_START) level += 1;
707
- else if (currentNode.data === HYDRATION_END) {
1137
+ if (currentNode.data === "[") level += 1;
1138
+ else if (currentNode.data === "]") {
708
1139
  level -= 1;
709
1140
  if (level === 0) {
710
1141
  const endNode = currentNode.nextSibling;
711
1142
  currentNode.remove();
712
- if (context_default.hydrationNode === currentNode) context_default.hydrationNode = endNode;
1143
+ if (context.hydrationNode === currentNode) context.hydrationNode = endNode;
1144
+ const region = context.activeRegion;
1145
+ if (region.startNode === null && firstInside !== null) region.startNode = firstInside;
1146
+ setFirstInsideNode(endNode, firstInside);
713
1147
  return endNode;
714
1148
  }
715
1149
  }
716
1150
  }
717
- currentNode = currentNode.nextSibling;
1151
+ if (currentNode.firstChild) currentNode = currentNode.firstChild;
1152
+ else if (currentNode.nextSibling) currentNode = currentNode.nextSibling;
1153
+ else {
1154
+ let parent = currentNode.parentNode;
1155
+ while (parent !== null && parent.nextSibling === null && parent !== startParent) parent = parent.parentNode;
1156
+ if (parent === null || parent === startParent) currentNode = null;
1157
+ else currentNode = parent.nextSibling;
1158
+ }
718
1159
  }
719
1160
  if (currentNode === null) throw new Error("End hydration comment not found");
720
1161
  }
721
1162
  }
722
1163
  return node;
723
1164
  }
724
-
725
1165
  //#endregion
726
1166
  //#region src/render/nodeChild.ts
727
1167
  /**
@@ -733,40 +1173,104 @@ function nodeAnchor(node) {
733
1173
  */
734
1174
  function nodeChild(parent) {
735
1175
  let childNode = parent.firstChild;
736
- if (context_default.hydrationNode !== null) {
1176
+ if (context.hydrationNode !== null) {
737
1177
  if (childNode === null) childNode = parent.appendChild(parent.ownerDocument.createTextNode(""));
738
- context_default.hydrationNode = childNode;
1178
+ context.hydrationNode = childNode;
739
1179
  }
740
1180
  return childNode;
741
1181
  }
742
-
1182
+ //#endregion
1183
+ //#region src/render/walkHydrationRoot.ts
1184
+ /**
1185
+ * Walks the hydration cursor past skippable leading nodes (whitespace text,
1186
+ * branch-break markers, auto-inserted `<tbody>`) and lands on the first real
1187
+ * content node — the same walk `nodeRoot` performs for the non-text case.
1188
+ *
1189
+ * Sets `region.startNode` to the landed node (unless it's a control-start
1190
+ * marker, which `nodeAnchor` consumes next). Returns the landed node and
1191
+ * advances `context.hydrationNode` to it.
1192
+ *
1193
+ * Extracted so `nodeRoot` and `nodeRootElement` share one implementation of
1194
+ * the cursor walk.
1195
+ */
1196
+ function walkHydrationRoot() {
1197
+ let rootNode = context.hydrationNode;
1198
+ while (rootNode !== null && isSkippable(rootNode)) {
1199
+ const next = rootNode.nextSibling;
1200
+ if (isCommentNode(rootNode) && rootNode.data === "^") rootNode.remove();
1201
+ rootNode = next;
1202
+ context.hydrationNode = rootNode;
1203
+ }
1204
+ while (rootNode !== null && rootNode.nodeName === "TBODY" && rootNode.firstChild !== null) {
1205
+ rootNode = rootNode.firstChild;
1206
+ context.hydrationNode = rootNode;
1207
+ }
1208
+ const region = context.activeRegion;
1209
+ const isControlStart = rootNode !== null && isCommentNode(rootNode) && rootNode.data === "[";
1210
+ if (region.startNode === null && !isControlStart) region.startNode = rootNode;
1211
+ return rootNode;
1212
+ }
1213
+ function isSkippable(node) {
1214
+ if (isTextNode(node) && (node.textContent ?? "").trim() === "") return true;
1215
+ if (isCommentNode(node)) return node.data === "^" || node.data === "";
1216
+ return false;
1217
+ }
1218
+ //#endregion
1219
+ //#region src/render/nodeRootElement.ts
1220
+ /**
1221
+ * Gets the root element of a single-root fragment built via `getElementFragment`.
1222
+ *
1223
+ * Companion to `nodeRoot`, for the codegen path where the compiler has emitted
1224
+ * `t_fragment_el` (cloning the cached template's `firstElementChild` directly)
1225
+ * instead of `t_fragment` (cloning into a `DocumentFragment`). In the
1226
+ * non-hydrating case the cloned element is already the root, so this is a
1227
+ * no-op pass-through. In the hydrating case we perform the same cursor walk as
1228
+ * `nodeRoot`'s non-text branch so the region's `startNode` lands on the
1229
+ * existing DOM node and the hydration cursor advances past any leading
1230
+ * whitespace, branch-break markers, and auto-inserted `<tbody>` wrappers.
1231
+ *
1232
+ * @param node The cloned root element (ignored when hydrating).
1233
+ */
1234
+ function nodeRootElement(node) {
1235
+ if (context.hydrationNode !== null) return walkHydrationRoot();
1236
+ return node;
1237
+ }
743
1238
  //#endregion
744
1239
  //#region src/render/nodeRoot.ts
745
1240
  /**
746
1241
  * Gets the first child in a fragment.
747
1242
  *
748
- * When hydrating, also sets the active range's start node, while we have it.
1243
+ * When hydrating, also sets the active region's start node, while we have it.
1244
+ *
1245
+ * If the hydration cursor is on a control-start marker (`<![>`), the node is
1246
+ * left in place for `nodeAnchor` (called next as `t_anchor(t_root(...))`) to
1247
+ * walk — it consumes the matched `<![>...<!]>` pair, removes the markers and
1248
+ * sets the region's start node to the first node inside the block.
1249
+ *
1250
+ * For non-text fragments, leading branch-break markers (`<!^>`), empty anchor
1251
+ * comments left by preceding siblings, and residual whitespace-only text nodes
1252
+ * are skipped (break markers removed) so the region's start node lands on real
1253
+ * content. This replaces the per-sibling `t_next` calls that the codegen used
1254
+ * to emit when leading whitespace separated siblings; with whitespace trimmed
1255
+ * those calls are gone, so the advancement happens here.
749
1256
  *
750
1257
  * @param parent The parent of the fragment.
751
1258
  * @param text Whether we require a text node.
752
1259
  */
753
1260
  function nodeRoot(parent, text = false) {
754
- if (context_default.hydrationNode !== null) {
755
- let rootNode = context_default.hydrationNode;
1261
+ if (context.hydrationNode !== null) {
1262
+ let rootNode = context.hydrationNode;
756
1263
  if (text && !isTextNode(rootNode) && rootNode.previousSibling !== null && isTextNode(rootNode.previousSibling)) {
757
1264
  rootNode = rootNode.previousSibling;
758
- context_default.hydrationNode = rootNode;
759
- }
760
- if (isCommentNode(rootNode) && rootNode.data === HYDRATION_START) {
761
- rootNode = rootNode.nextSibling;
762
- context_default.hydrationNode = rootNode;
1265
+ context.hydrationNode = rootNode;
763
1266
  }
764
- const region = context_default.activeRegion;
765
- if (region.startNode === null) region.startNode = rootNode;
1267
+ if (!text) return walkHydrationRoot();
1268
+ const region = context.activeRegion;
1269
+ const isControlStart = rootNode !== null && isCommentNode(rootNode) && rootNode.data === "[";
1270
+ if (region.startNode === null && !isControlStart) region.startNode = rootNode;
766
1271
  return rootNode;
767
1272
  } else return parent.firstChild;
768
1273
  }
769
-
770
1274
  //#endregion
771
1275
  //#region src/render/nodeSkip.ts
772
1276
  /**
@@ -779,10 +1283,108 @@ function nodeRoot(parent, text = false) {
779
1283
  */
780
1284
  function nodeSkip(node, count) {
781
1285
  let nextNode = node;
782
- for (let i = 0; i < count; i++) nextNode = nodeCheckHydrationBreak(nextNode.nextSibling);
1286
+ if (context.hydrationNode !== null) for (let i = 0; i < count; i++) nextNode = nodeCheckHydrationBreak(nextNode.nextSibling);
1287
+ else for (let i = 0; i < count; i++) nextNode = nextNode.nextSibling;
783
1288
  return nextNode;
784
1289
  }
785
-
1290
+ //#endregion
1291
+ //#region src/render/rerunRegionEffects.ts
1292
+ /**
1293
+ * Force re-runs every effect owned by `region` and its descendant regions
1294
+ * that depends on at least one of the for-vars set in `changedMask`.
1295
+ *
1296
+ * Used by keyed-list `updateListItem` callbacks emitted by the compiler when
1297
+ * the `@for` body has been classified "no-proxy safe" — i.e. the per-item
1298
+ * data bag is *not* wrapped in a shallow `$watch` Proxy. Without that Proxy,
1299
+ * a write such as `t_old_item.data.row = newRow` doesn't propagate through a
1300
+ * signal, so any effects that read `data.row` must be re-run manually.
1301
+ *
1302
+ * `changedMask` is a bitmask of the for-var positions whose references
1303
+ * actually changed in this update. Each effect carries `forVarMask`
1304
+ * (computed at compile time) listing the for-vars its body reads; effects
1305
+ * whose `forVarMask & changedMask === 0` are skipped. Mount callbacks
1306
+ * (`isMountEffect` — `$onmount`/`onmount`) are always skipped: they run
1307
+ * once per DOM mount and their bodies are untracked.
1308
+ *
1309
+ * Equivalent to what `checkEffect` does when a signal has propagated, but
1310
+ * unconditional for the effects that do match: cleanup → deactivate sources
1311
+ * → run → clear unused sources, for every matching effect on the region and
1312
+ * on every descendant region (`depth > region.depth`, the same chain shape
1313
+ * `clearRegion` walks).
1314
+ */
1315
+ function rerunRegionEffects(region, changedMask) {
1316
+ rerunEffectsOnRegion(region, changedMask);
1317
+ let child = region.nextRegion;
1318
+ while (child !== null && child.depth > region.depth) {
1319
+ rerunEffectsOnRegion(child, changedMask);
1320
+ child = child.nextRegion;
1321
+ }
1322
+ }
1323
+ function rerunEffectsOnRegion(region, changedMask) {
1324
+ for (let effect of region.effects) {
1325
+ if (effect.isMountEffect) continue;
1326
+ if (effect.forVarMask !== void 0 && (effect.forVarMask & changedMask) === 0) continue;
1327
+ runCleanups(effect);
1328
+ deactivateSources(effect);
1329
+ runEffect(effect);
1330
+ clearSources(effect);
1331
+ }
1332
+ }
1333
+ //#endregion
1334
+ //#region src/render/restoreHydration.ts
1335
+ /**
1336
+ * Restores the hydration cursor to a previously-snapshotted node. Used by
1337
+ * `@try`/`@catch`: if the try branch throws partway through its hydration
1338
+ * walk, the catch branch must resume hydrating from where the try group
1339
+ * started, not from wherever the failed branch left the cursor.
1340
+ *
1341
+ * The cursor is set unconditionally: a failed try-branch build can walk the
1342
+ * cursor past the last node (setting it to `null` via `nodeNext`), and the
1343
+ * rewind must still restore it — otherwise the catch branch would think it
1344
+ * isn't hydrating and insert fresh nodes alongside the server's. When not
1345
+ * hydrating at all, the snapshot itself is `null`, so this is a no-op.
1346
+ *
1347
+ * @param node The snapshotted cursor node (from `saveHydration`).
1348
+ */
1349
+ function restoreHydration(node) {
1350
+ context.hydrationNode = node;
1351
+ }
1352
+ //#endregion
1353
+ //#region src/render/widenAncestorsAtAnchor.ts
1354
+ /**
1355
+ * Widens ancestor region node windows after a control re-run rendered
1356
+ * content at its anchor.
1357
+ *
1358
+ * A region that owns only a control's anchor comment captures
1359
+ * `startNode = endNode = anchor` when it mounts (e.g. a `@for` row whose
1360
+ * body is a single `@if`, or an outer `@if` whose body is a single control).
1361
+ * Content rendered by a LATER re-run of that control is inserted into the
1362
+ * live DOM just BEFORE the anchor — outside that window — so clearing the
1363
+ * owning region would remove only the anchor and orphan the branch content.
1364
+ * At mount time this can't happen (content is added to the region's detached
1365
+ * fragment first, so its `startNode` already covers it), which is why only
1366
+ * re-runs need this fix.
1367
+ *
1368
+ * The first node of the newly rendered content is the first DESCENDANT region
1369
+ * of the control that owns nodes (control regions themselves have null
1370
+ * `startNode`). Ancestors are the regions with strictly decreasing depth on
1371
+ * the `previousRegion` chain; only those whose window starts exactly at the
1372
+ * anchor are widened.
1373
+ */
1374
+ function widenAncestorsAtAnchor(region, anchor) {
1375
+ if (anchor === null) return;
1376
+ let child = region.nextRegion;
1377
+ while (child !== null && child.depth > region.depth && child.startNode === null) child = child.nextRegion;
1378
+ if (child === null || child.depth <= region.depth || child.startNode === anchor) return;
1379
+ const firstNode = child.startNode;
1380
+ let ancestor = region.previousRegion;
1381
+ let ancestorDepth = region.depth;
1382
+ while (ancestor !== null && ancestor.depth < ancestorDepth) {
1383
+ if (ancestor.startNode === anchor) ancestor.startNode = firstNode;
1384
+ ancestorDepth = ancestor.depth;
1385
+ ancestor = ancestor.previousRegion;
1386
+ }
1387
+ }
786
1388
  //#endregion
787
1389
  //#region src/render/runControl.ts
788
1390
  /**
@@ -791,92 +1393,136 @@ function nodeSkip(node, count) {
791
1393
  */
792
1394
  function runControl(region, anchor, create, name) {
793
1395
  let first = true;
794
- $run(function runControl$1() {
1396
+ const gen = region.generation = (region.generation ?? 0) + 1;
1397
+ $run(function runControl() {
1398
+ if (region.generation !== gen) return;
1399
+ if (region.depth === -2) region.recreate = true;
795
1400
  const oldRegion = pushRegion(region, first);
796
1401
  first = false;
797
1402
  create(anchor);
798
1403
  popRegion(oldRegion);
1404
+ widenAncestorsAtAnchor(region, anchor);
1405
+ if (context.hydrationNode !== null && anchor !== null) context.hydrationNode = anchor;
799
1406
  }, name);
800
- if (context_default.hydrationNode) anchor = context_default.hydrationNode.nextSibling;
801
1407
  }
802
-
803
1408
  //#endregion
804
1409
  //#region src/render/runControlBranch.ts
805
1410
  function runControlBranch(region, oldIndex, index) {
806
- if (oldIndex === index) return false;
807
- if (region.depth === -2) return false;
808
- if (region.nextRegion !== null && region.nextRegion.depth > region.depth) clearRegion(region.nextRegion);
1411
+ const recreate = region.recreate;
1412
+ if (recreate) region.recreate = false;
1413
+ const firstRender = region.hasRenderedBranch !== true;
1414
+ region.hasRenderedBranch = true;
1415
+ if (oldIndex === index) {
1416
+ if (recreate) {
1417
+ if (region.nextRegion !== null && region.nextRegion.depth > region.depth) clearRegion(region.nextRegion);
1418
+ return true;
1419
+ }
1420
+ return false;
1421
+ }
1422
+ if (!firstRender && region.nextRegion !== null && region.nextRegion.depth > region.depth) clearRegion(region.nextRegion);
809
1423
  return true;
810
1424
  }
811
-
812
1425
  //#endregion
813
- //#region src/watch/propagateSignal.ts
1426
+ //#region src/watch/deepWrap.ts
814
1427
  /**
815
- * When a signal is changed, we need to
816
- * - Set the signal's subscriptions to recalc
817
- * - Set any dependent computed values to recalc
818
- * - Gather dependent effects that will need to be re-run
1428
+ * Wraps a value with `$watch` if it is a plain object (or Date/Map/Set) that
1429
+ * is not already watched and is not a promise. Returns the value unchanged
1430
+ * otherwise.
1431
+ *
1432
+ * Used by the `get` trap (wrap values on read) and the `set` trap (wrap
1433
+ * values on write), so a value stored in watched state is reactive whether
1434
+ * it's been read yet or not.
1435
+ */
1436
+ const proxyCache = /* @__PURE__ */ new WeakMap();
1437
+ function deepWrap(value) {
1438
+ if (value === void 0 || value === null || typeof value !== "object") return value;
1439
+ if (value[proxyDataSymbol] !== void 0) return proxyCache.get(value) ?? value;
1440
+ if (value.then !== void 0) return value;
1441
+ if (value.nodeType !== void 0) return value;
1442
+ const cached = proxyCache.get(value);
1443
+ if (cached !== void 0) return cached;
1444
+ const proxy = $watch(value);
1445
+ proxyCache.set(value, proxy);
1446
+ return proxy;
1447
+ }
1448
+ //#endregion
1449
+ //#region src/watch/propagateSignal.ts
1450
+ /**
1451
+ * Walk the target graph from a signal source (ProxySignal or Computed),
1452
+ * marking each dependent as needing recalculation and queuing effects for
1453
+ * re-run. Shared between `propagateSignal` (for proxy writes) and `$async`'s
1454
+ * promise-resolve handler (for async value resolution).
1455
+ *
1456
+ * Must be called inside `batchStart`/`batchEnd` — callers own the batch.
1457
+ */
1458
+ function propagateFromSignal(signal) {
1459
+ const first = signal.firstTarget;
1460
+ if (first === null) return;
1461
+ let targetSub = first;
1462
+ let computed;
1463
+ outer: while (true) {
1464
+ targetSub.active = false;
1465
+ targetSub.recalc = true;
1466
+ const target = targetSub.target;
1467
+ if (target.type === 2) {
1468
+ if (!target.queued) {
1469
+ target.queued = true;
1470
+ context.effectsToRun.push(target);
1471
+ }
1472
+ } else if (!target.recalc) {
1473
+ target.recalc = true;
1474
+ if (target.firstTarget !== null) {
1475
+ computed = target;
1476
+ computed.rollback = targetSub;
1477
+ targetSub = target.firstTarget;
1478
+ continue;
1479
+ }
1480
+ }
1481
+ while (targetSub.nextTarget === null && computed !== void 0) {
1482
+ const rollback = computed.rollback;
1483
+ if (rollback === null) break;
1484
+ targetSub = rollback;
1485
+ if (targetSub.source.type !== 1) {
1486
+ computed = void 0;
1487
+ continue outer;
1488
+ }
1489
+ computed = targetSub.source;
1490
+ }
1491
+ if (targetSub.nextTarget === null) break;
1492
+ targetSub = targetSub.nextTarget;
1493
+ }
1494
+ }
1495
+ /**
1496
+ * When a signal is changed, we need to
1497
+ * - Set the signal's subscriptions to recalc
1498
+ * - Set any dependent computed values to recalc
1499
+ * - Gather dependent effects that will need to be re-run
819
1500
  */
820
1501
  function propagateSignal(proxy, key) {
821
1502
  let signal = proxy.signals.get(key);
822
1503
  if (signal !== void 0 && signal.firstTarget !== null) {
823
1504
  batchStart();
824
1505
  try {
825
- if (context_default.firstSignalToUpdate === null) context_default.firstSignalToUpdate = signal;
826
- else if (signal.nextSignalToUpdate === null) {
827
- let lastSignal = context_default.firstSignalToUpdate;
828
- while (lastSignal.nextSignalToUpdate !== null) lastSignal = lastSignal.nextSignalToUpdate;
829
- lastSignal.nextSignalToUpdate = signal;
830
- }
831
- let lastEffect = context_default.firstEffectToRun;
832
- if (lastEffect !== null) while (lastEffect.nextEffectToRun !== null) lastEffect = lastEffect.nextEffectToRun;
833
- let targetSub = signal.firstTarget;
834
- let computed;
835
- outer: while (true) {
836
- targetSub.active = false;
837
- targetSub.recalc = true;
838
- const target = targetSub.target;
839
- if (target.type === EFFECT_TYPE) {
840
- if (lastEffect === null) {
841
- context_default.firstEffectToRun = target;
842
- lastEffect = target;
843
- } else if (target.nextEffectToRun === null && lastEffect !== target) {
844
- lastEffect.nextEffectToRun = target;
845
- lastEffect = target;
846
- }
847
- } else if (!target.recalc) {
848
- target.recalc = true;
849
- if (target.firstTarget !== null) {
850
- computed = target;
851
- computed.rollback = targetSub;
852
- targetSub = target.firstTarget;
853
- continue;
854
- }
855
- }
856
- while (targetSub.nextTarget === null && computed !== void 0) {
857
- targetSub = computed.rollback;
858
- if (targetSub.source.type !== COMPUTED_TYPE) {
859
- computed = void 0;
860
- continue outer;
861
- }
862
- computed = targetSub.source;
863
- }
864
- if (targetSub.nextTarget === null) break;
865
- targetSub = targetSub.nextTarget;
1506
+ if (context.lastSignalToUpdate === null) {
1507
+ context.firstSignalToUpdate = signal;
1508
+ context.lastSignalToUpdate = signal;
1509
+ } else if (signal.nextSignalToUpdate === null) {
1510
+ context.lastSignalToUpdate.nextSignalToUpdate = signal;
1511
+ context.lastSignalToUpdate = signal;
866
1512
  }
1513
+ propagateFromSignal(signal);
867
1514
  } finally {
868
1515
  batchEnd();
869
1516
  }
870
1517
  }
871
1518
  }
872
-
873
1519
  //#endregion
874
1520
  //#region src/watch/trackProxySignal.ts
875
1521
  function trackProxySignal(data, key) {
876
1522
  let signal = data.signals.get(key);
877
1523
  if (signal === void 0) {
878
1524
  signal = {
879
- type: SIGNAL_TYPE,
1525
+ type: 0,
880
1526
  firstTarget: null,
881
1527
  nextSignalToUpdate: null
882
1528
  };
@@ -884,12 +1530,53 @@ function trackProxySignal(data, key) {
884
1530
  }
885
1531
  trackSignal(signal);
886
1532
  }
887
-
888
1533
  //#endregion
889
1534
  //#region src/watch/proxyGet.ts
1535
+ /**
1536
+ * Called when a read hits a `didSuspend` computed. Subscribes the reader (so
1537
+ * resolve re-runs it through the normal reactive graph), propagates the
1538
+ * suspend up the cache chain by tainting the active reader, and notifies the
1539
+ * nearest `@await` boundary.
1540
+ *
1541
+ * Return value (stale-while-revalidate, ASYNC.md §6.2): on a refresh suspend
1542
+ * (the computed has resolved before) returns the previously resolved value
1543
+ * held in `staleValue`, so readers keep displaying the old content instead of
1544
+ * a placeholder — an `@await` boundary thus keeps its content mounted
1545
+ * rather than flashing the `with` branch. On a first load (`staleValue` is
1546
+ * undefined) returns `undefined`, which the boundary replaces with its
1547
+ * `with` branch. In peek mode (used by `$pending`) always returns `undefined`
1548
+ * — the value isn't needed, only the subscription.
1549
+ */
1550
+ function suspendRead(signal) {
1551
+ trackSignal(signal);
1552
+ if (context.suspendPeek) {
1553
+ if (!signal.suspendQuiet) context.suspendPeekHit = true;
1554
+ return;
1555
+ }
1556
+ if (context.activeTarget !== null) {
1557
+ context.activeTarget.didSuspend = true;
1558
+ if (context.activeTarget.type === 2) {
1559
+ const effect = context.activeTarget;
1560
+ (effect.suspendSources ??= /* @__PURE__ */ new Set()).add(signal);
1561
+ }
1562
+ }
1563
+ if (context.awaitBoundary !== null) {
1564
+ context.awaitBoundary.suspended = true;
1565
+ context.awaitBoundary.pending.add(signal);
1566
+ const boundaryEffect = context.awaitBoundary.effect;
1567
+ if (boundaryEffect !== null && boundaryEffect !== context.activeTarget) {
1568
+ const oldActive = context.activeTarget;
1569
+ context.activeTarget = boundaryEffect;
1570
+ trackSignal(signal);
1571
+ context.activeTarget = oldActive;
1572
+ }
1573
+ }
1574
+ return signal.staleValue;
1575
+ }
890
1576
  function proxyGet(target, key, receiver) {
891
1577
  let data = target[proxyDataSymbol];
892
1578
  if (key === proxyDataSymbol) return data;
1579
+ if ((data.isDate || data.isMap || data.isSet) && !Object.prototype.hasOwnProperty.call(target, key)) return collectionGet(data, target, key, receiver);
893
1580
  let signal = data.signals.get(key);
894
1581
  if (signal === void 0) {
895
1582
  const propDescriptor = Object.getOwnPropertyDescriptor(target, key);
@@ -897,38 +1584,92 @@ function proxyGet(target, key, receiver) {
897
1584
  if (propDescriptor.writable) {
898
1585
  if (data.shallow !== true) {
899
1586
  const value = target[key];
900
- if (value !== void 0 && value !== null && typeof value === "object" && value[proxyDataSymbol] === void 0 && value.then === void 0) target[key] = $watch(value);
1587
+ const wrapped = deepWrap(value);
1588
+ if (wrapped !== value) target[key] = wrapped;
901
1589
  }
902
1590
  trackProxySignal(data, key);
903
1591
  } else if (propDescriptor.get) {
904
- const oldRegisterComputed = context_default.registerComputed;
1592
+ const oldRegisterComputed = context.registerComputed;
905
1593
  try {
906
- context_default.registerComputed = (computed) => {
1594
+ context.registerComputed = (computed) => {
907
1595
  data.signals.set(key, computed);
908
1596
  };
909
- return Reflect.get(target, key, receiver);
1597
+ const result = Reflect.get(target, key, receiver);
1598
+ const registered = data.signals.get(key);
1599
+ if (context.refreshSignals !== null && registered !== void 0 && registered.type === 1 && registered.isAsync) {
1600
+ context.refreshSignals.push(registered);
1601
+ context.refreshInitialized?.add(registered);
1602
+ }
1603
+ if (registered !== void 0 && registered.type === 1 && registered.didSuspend) return suspendRead(registered);
1604
+ return result;
910
1605
  } finally {
911
- context_default.registerComputed = oldRegisterComputed;
1606
+ context.registerComputed = oldRegisterComputed;
912
1607
  }
913
1608
  }
914
1609
  } else if (data.isArray) {
915
1610
  if (arrayWrapper[key] !== void 0) return arrayWrapper[key](data, target, key);
916
1611
  } else trackProxySignal(data, key);
917
- } else if (signal.type === SIGNAL_TYPE) trackProxySignal(data, key);
918
- else if (signal.type === COMPUTED_TYPE) {
1612
+ } else if (signal.type === 0) {
1613
+ if (data.shallow !== true) {
1614
+ const value = target[key];
1615
+ if (typeof value === "object" && value !== null) {
1616
+ const propDescriptor = Object.getOwnPropertyDescriptor(target, key);
1617
+ if (propDescriptor !== void 0 && propDescriptor.writable) {
1618
+ const wrapped = deepWrap(value);
1619
+ if (wrapped !== value) target[key] = wrapped;
1620
+ }
1621
+ }
1622
+ }
1623
+ trackProxySignal(data, key);
1624
+ } else if (signal.type === 1) {
1625
+ if (context.refreshSignals !== null && signal.isAsync) {
1626
+ context.refreshSignals.push(signal);
1627
+ return signal.value;
1628
+ }
919
1629
  if (signal.running) throw new Error("Cycle detected");
920
1630
  else if (signal.recalc) checkComputed(signal);
921
- else if (signal.didError) throw signal.value;
922
- else trackSignal(signal);
1631
+ if (signal.didError) {
1632
+ trackSignal(signal);
1633
+ throw signal.value;
1634
+ }
1635
+ if (signal.didSuspend) return suspendRead(signal);
1636
+ trackSignal(signal);
923
1637
  return signal.value;
924
1638
  }
925
- return Reflect.get(target, key, receiver);
1639
+ return target[key];
926
1640
  }
927
1641
  const arrayWrapper = {
928
- [Symbol.iterator]: function(data, target, key) {
1642
+ [Symbol.iterator]: function(data, target, _key) {
929
1643
  trackProxySignal(data, "length");
930
- context_default.activeTarget = null;
931
- return target[key];
1644
+ context.activeTarget = null;
1645
+ return function arrayIterator() {
1646
+ let index = 0;
1647
+ return {
1648
+ next() {
1649
+ if (index >= target.length) return {
1650
+ value: void 0,
1651
+ done: true
1652
+ };
1653
+ let value = target[index];
1654
+ if (data.shallow !== true) {
1655
+ const wrapped = deepWrap(value);
1656
+ if (wrapped !== value) {
1657
+ value = wrapped;
1658
+ target[index] = value;
1659
+ }
1660
+ }
1661
+ trackProxySignal(data, String(index));
1662
+ index++;
1663
+ return {
1664
+ value,
1665
+ done: false
1666
+ };
1667
+ },
1668
+ [Symbol.iterator]() {
1669
+ return this;
1670
+ }
1671
+ };
1672
+ };
932
1673
  },
933
1674
  pop: arrayHandle,
934
1675
  push: arrayHandle,
@@ -936,8 +1677,35 @@ const arrayWrapper = {
936
1677
  shift: arrayHandle,
937
1678
  sort: arrayHandle,
938
1679
  splice: arrayHandle,
939
- unshift: arrayHandle
1680
+ unshift: arrayHandle,
1681
+ slice: readHandle,
1682
+ concat: readHandle,
1683
+ filter: readHandle,
1684
+ map: readHandle,
1685
+ toReversed: readHandle,
1686
+ toSorted: readHandle,
1687
+ toSpliced: readHandle,
1688
+ indexOf: readHandle,
1689
+ lastIndexOf: readHandle,
1690
+ includes: readHandle,
1691
+ find: readHandle,
1692
+ findIndex: readHandle,
1693
+ some: readHandle,
1694
+ every: readHandle,
1695
+ join: readHandle,
1696
+ forEach: readHandle,
1697
+ reduce: readHandle,
1698
+ reduceRight: readHandle,
1699
+ flat: readHandle,
1700
+ flatMap: readHandle,
1701
+ at: readHandle
940
1702
  };
1703
+ function readHandle(data, target, key) {
1704
+ return function(...args) {
1705
+ trackProxySignal(data, "length");
1706
+ return target[key].apply(target, args);
1707
+ };
1708
+ }
941
1709
  function arrayHandle(data, target, key) {
942
1710
  return function(...args) {
943
1711
  const result = target[key].apply(target, args);
@@ -945,27 +1713,254 @@ function arrayHandle(data, target, key) {
945
1713
  return result;
946
1714
  };
947
1715
  }
948
-
1716
+ const COLLECTION_KEY = Symbol("torp.collection");
1717
+ const TIME_KEY = "#time";
1718
+ /**
1719
+ * Routes a `get` on a watched Date/Map/Set to the right wrapper handler.
1720
+ *
1721
+ * Note the two levels of indirection for methods: the handler runs at get-trap
1722
+ * time (returning the method to call), and the returned function runs when the
1723
+ * method is invoked. `size` is the exception -- it returns its value at
1724
+ * get-trap time, because it's a readonly property, not a method.
1725
+ */
1726
+ function collectionGet(data, target, key, receiver) {
1727
+ if (data.isDate) return dateGet(data, target, key);
1728
+ const handle = (data.isMap ? mapWrapper : setWrapper)[key];
1729
+ if (handle !== void 0) return handle(data, target, key, receiver);
1730
+ return target[key];
1731
+ }
1732
+ /**
1733
+ * Returns the signal key for a Map/Set operation: primitives get a per-key
1734
+ * signal, so reading one key doesn't re-run effects when an unrelated key
1735
+ * changes. Anything else shares the collection-wide signal.
1736
+ */
1737
+ function collectionKey(key) {
1738
+ const type = typeof key;
1739
+ return type === "string" || type === "number" || type === "symbol" ? key : COLLECTION_KEY;
1740
+ }
1741
+ /**
1742
+ * Propagates a Map/Set mutation: the per-key signal (when the key is a
1743
+ * primitive) plus the collection-wide signal. The collection signal is always
1744
+ * enough for object keys, and propagating the same signal twice would re-run
1745
+ * effects twice (they re-subscribe between flushes).
1746
+ */
1747
+ function propagateCollection(data, key) {
1748
+ if (key !== COLLECTION_KEY) propagateSignal(data, key);
1749
+ propagateSignal(data, COLLECTION_KEY);
1750
+ }
1751
+ function dateGet(data, target, key) {
1752
+ if (typeof key === "symbol") {
1753
+ if (key === Symbol.toPrimitive) return function(hint) {
1754
+ const result = target[Symbol.toPrimitive](hint);
1755
+ trackProxySignal(data, TIME_KEY);
1756
+ return result;
1757
+ };
1758
+ return target[key];
1759
+ }
1760
+ if (typeof key !== "string") return target[key];
1761
+ const value = target[key];
1762
+ if (typeof value !== "function") return value;
1763
+ if (key.startsWith("set")) return function(...args) {
1764
+ const before = target.getTime();
1765
+ const result = value.apply(target, args);
1766
+ if (target.getTime() !== before) propagateSignal(data, TIME_KEY);
1767
+ return result;
1768
+ };
1769
+ if (key.startsWith("get") || key.startsWith("to") || key === "valueOf") return function(...args) {
1770
+ const result = value.apply(target, args);
1771
+ trackProxySignal(data, TIME_KEY);
1772
+ return result;
1773
+ };
1774
+ return value;
1775
+ }
1776
+ const mapWrapper = {
1777
+ size: function(data, target) {
1778
+ trackProxySignal(data, COLLECTION_KEY);
1779
+ return target.size;
1780
+ },
1781
+ get: function(data, target) {
1782
+ return function(key) {
1783
+ key = $unwrap(key);
1784
+ trackProxySignal(data, collectionKey(key));
1785
+ const value = target.get(key);
1786
+ if (data.shallow !== true) {
1787
+ const wrapped = deepWrap(value);
1788
+ if (wrapped !== value) target.set(key, wrapped);
1789
+ return wrapped;
1790
+ }
1791
+ return value;
1792
+ };
1793
+ },
1794
+ has: function(data, target) {
1795
+ return function(key) {
1796
+ key = $unwrap(key);
1797
+ trackProxySignal(data, collectionKey(key));
1798
+ return target.has(key);
1799
+ };
1800
+ },
1801
+ set: function(data, target, _key, receiver) {
1802
+ return function(key, value) {
1803
+ key = $unwrap(key);
1804
+ if (target.has(key) && $unwrap(target.get(key)) === $unwrap(value)) return receiver ?? target;
1805
+ const result = target.set(key, value);
1806
+ propagateCollection(data, collectionKey(key));
1807
+ return receiver ?? result;
1808
+ };
1809
+ },
1810
+ delete: function(data, target) {
1811
+ return function(key) {
1812
+ key = $unwrap(key);
1813
+ const result = target.delete(key);
1814
+ propagateCollection(data, collectionKey(key));
1815
+ return result;
1816
+ };
1817
+ },
1818
+ clear: function(data, target) {
1819
+ return function() {
1820
+ const result = target.clear();
1821
+ batchStart();
1822
+ try {
1823
+ for (const key of data.signals.keys()) propagateSignal(data, key);
1824
+ } finally {
1825
+ batchEnd();
1826
+ }
1827
+ return result;
1828
+ };
1829
+ },
1830
+ keys: function(data, target) {
1831
+ return function() {
1832
+ trackProxySignal(data, COLLECTION_KEY);
1833
+ return [...target.keys()][Symbol.iterator]();
1834
+ };
1835
+ },
1836
+ values: function(data, target) {
1837
+ return function() {
1838
+ trackProxySignal(data, COLLECTION_KEY);
1839
+ let values = [...target.values()];
1840
+ if (data.shallow !== true) values = values.map(deepWrap);
1841
+ return values[Symbol.iterator]();
1842
+ };
1843
+ },
1844
+ entries: mapEntries,
1845
+ [Symbol.iterator]: mapEntries,
1846
+ forEach: function(data, target, _key, receiver) {
1847
+ return function(callback, thisArg) {
1848
+ trackProxySignal(data, COLLECTION_KEY);
1849
+ const wrap = data.shallow !== true;
1850
+ target.forEach((value, key) => {
1851
+ callback.call(thisArg, wrap ? deepWrap(value) : value, key, receiver ?? target);
1852
+ });
1853
+ };
1854
+ }
1855
+ };
1856
+ function mapEntries(data, target) {
1857
+ return function() {
1858
+ trackProxySignal(data, COLLECTION_KEY);
1859
+ const wrap = data.shallow !== true;
1860
+ return [...target.entries()].map((entry) => [entry[0], wrap ? deepWrap(entry[1]) : entry[1]])[Symbol.iterator]();
1861
+ };
1862
+ }
1863
+ const setWrapper = {
1864
+ size: function(data, target) {
1865
+ trackProxySignal(data, COLLECTION_KEY);
1866
+ return target.size;
1867
+ },
1868
+ has: function(data, target) {
1869
+ return function(value) {
1870
+ value = $unwrap(value);
1871
+ trackProxySignal(data, collectionKey(value));
1872
+ return target.has(value);
1873
+ };
1874
+ },
1875
+ add: function(data, target, _key, receiver) {
1876
+ return function(value) {
1877
+ value = $unwrap(value);
1878
+ if (target.has(value)) return receiver ?? target;
1879
+ const result = target.add(value);
1880
+ propagateCollection(data, collectionKey(value));
1881
+ return receiver ?? result;
1882
+ };
1883
+ },
1884
+ delete: function(data, target) {
1885
+ return function(value) {
1886
+ value = $unwrap(value);
1887
+ const result = target.delete(value);
1888
+ propagateCollection(data, collectionKey(value));
1889
+ return result;
1890
+ };
1891
+ },
1892
+ clear: function(data, target) {
1893
+ return function() {
1894
+ const result = target.clear();
1895
+ batchStart();
1896
+ try {
1897
+ for (const key of data.signals.keys()) propagateSignal(data, key);
1898
+ } finally {
1899
+ batchEnd();
1900
+ }
1901
+ return result;
1902
+ };
1903
+ },
1904
+ keys: setValues,
1905
+ values: setValues,
1906
+ [Symbol.iterator]: setValues,
1907
+ entries: setEntries,
1908
+ forEach: function(data, target, _key, receiver) {
1909
+ return function(callback, thisArg) {
1910
+ trackProxySignal(data, COLLECTION_KEY);
1911
+ const wrap = data.shallow !== true;
1912
+ target.forEach((value) => {
1913
+ const wrapped = wrap ? deepWrap(value) : value;
1914
+ callback.call(thisArg, wrapped, wrapped, receiver ?? target);
1915
+ });
1916
+ };
1917
+ }
1918
+ };
1919
+ function setValues(data, target) {
1920
+ return function() {
1921
+ trackProxySignal(data, COLLECTION_KEY);
1922
+ let values = [...target.values()];
1923
+ if (data.shallow !== true) values = values.map(deepWrap);
1924
+ return values[Symbol.iterator]();
1925
+ };
1926
+ }
1927
+ function setEntries(data, target) {
1928
+ return function() {
1929
+ trackProxySignal(data, COLLECTION_KEY);
1930
+ const wrap = data.shallow !== true;
1931
+ return [...target.values()].map((value) => {
1932
+ const wrapped = wrap ? deepWrap(value) : value;
1933
+ return [wrapped, wrapped];
1934
+ })[Symbol.iterator]();
1935
+ };
1936
+ }
949
1937
  //#endregion
950
1938
  //#region src/watch/proxySet.ts
951
1939
  function proxySet(target, key, value, receiver) {
952
1940
  const oldValue = target[key];
953
1941
  if (value !== oldValue) {
954
- if (context_default.batchOperation > 100) throw new Error("Cycle detected");
1942
+ if (context.batchOperation > 100) throw new Error("Cycle detected");
955
1943
  let data = target[proxyDataSymbol];
956
- devContext_default.signalSet(data, key);
957
- if (oldValue && oldValue[proxyDataSymbol] !== void 0) value = $watch(value, { shallow: oldValue[proxyDataSymbol].shallow });
1944
+ devContext.signalSet(data, key);
1945
+ if (data.shallow !== true) value = deepWrap(value);
958
1946
  Reflect.set(target, key, value, receiver);
959
1947
  propagateSignal(data, key);
960
- if (data.isArray && !isNaN(+String(key))) propagateSignal(data, "length");
1948
+ if (data.isArray && typeof key !== "symbol" && !isNaN(+key)) propagateSignal(data, "length");
961
1949
  }
962
1950
  return true;
963
1951
  }
964
-
965
1952
  //#endregion
966
1953
  //#region src/watch/$watch.ts
1954
+ const sharedHandler = {
1955
+ get: proxyGet,
1956
+ set: proxySet
1957
+ };
967
1958
  /**
968
- * Watches an object and runs effects when its properties are changed
1959
+ * Watches an object and runs effects when its properties are changed.
1960
+ *
1961
+ * Dates, Maps and Sets are supported too: their methods are reactive (reads
1962
+ * track, writes notify), so `new Date()`, `new Map()` and `new Set()` can be
1963
+ * used in watched state directly.
969
1964
  *
970
1965
  * @param object The object to watch
971
1966
  */
@@ -974,19 +1969,75 @@ function $watch(object, options) {
974
1969
  const data = {
975
1970
  target: object,
976
1971
  isArray: Array.isArray(object),
1972
+ isDate: object instanceof Date,
1973
+ isMap: object instanceof Map,
1974
+ isSet: object instanceof Set,
977
1975
  shallow: options?.shallow === true,
978
1976
  signals: /* @__PURE__ */ new Map()
979
1977
  };
980
- object[proxyDataSymbol] = data;
981
- const handler = {
982
- get: proxyGet,
983
- set: proxySet
984
- };
985
- const proxy = new Proxy(object, handler);
986
- devContext_default.onWatch(data);
1978
+ Object.defineProperty(object, proxyDataSymbol, {
1979
+ value: data,
1980
+ writable: true,
1981
+ enumerable: false,
1982
+ configurable: true
1983
+ });
1984
+ const proxy = new Proxy(object, sharedHandler);
1985
+ devContext.onWatch(data);
987
1986
  return proxy;
988
1987
  }
989
-
1988
+ //#endregion
1989
+ //#region src/render/getSequence.ts
1990
+ /**
1991
+ * Computes the indices (into `arr`) of a longest strictly-increasing
1992
+ * subsequence, skipping zero entries. Adapted from Vue 3's `getSequence`.
1993
+ *
1994
+ * Used by the keyed-list reconciler (`runListItems`): `arr` is the
1995
+ * `newIndexToOldIndex` map where `arr[i] = oldIndex + 1` (so `0` marks a
1996
+ * new/unmounted slot, which is skipped). The returned indices identify the
1997
+ * items that are already in correct relative order and therefore don't need
1998
+ * to be moved — everything else is moved or mounted.
1999
+ *
2000
+ * Runs in O(n log n).
2001
+ */
2002
+ function getSequence(arr) {
2003
+ const p = arr.slice();
2004
+ const result = [0];
2005
+ let i;
2006
+ let j;
2007
+ let u;
2008
+ let v;
2009
+ let c;
2010
+ const len = arr.length;
2011
+ for (i = 0; i < len; i++) {
2012
+ const arrI = arr[i];
2013
+ if (arrI !== 0) {
2014
+ j = result[result.length - 1];
2015
+ if (arr[j] < arrI) {
2016
+ p[i] = j;
2017
+ result.push(i);
2018
+ continue;
2019
+ }
2020
+ u = 0;
2021
+ v = result.length - 1;
2022
+ while (u < v) {
2023
+ c = u + v >> 1;
2024
+ if (arr[result[c]] < arrI) u = c + 1;
2025
+ else v = c;
2026
+ }
2027
+ if (arrI < arr[result[u]]) {
2028
+ if (u > 0) p[i] = result[u - 1];
2029
+ result[u] = i;
2030
+ }
2031
+ }
2032
+ }
2033
+ u = result.length;
2034
+ v = result[u - 1];
2035
+ while (u-- > 0) {
2036
+ result[u] = v;
2037
+ v = p[v];
2038
+ }
2039
+ return result;
2040
+ }
990
2041
  //#endregion
991
2042
  //#region src/render/moveRegion.ts
992
2043
  function moveRegion(parent, region, before) {
@@ -1000,145 +2051,416 @@ function moveRegion(parent, region, before) {
1000
2051
  currentNode = nextNode;
1001
2052
  }
1002
2053
  }
1003
-
1004
2054
  //#endregion
1005
2055
  //#region src/render/runListItems.ts
2056
+ const SHALLOW_WATCH_OPTIONS = { shallow: true };
1006
2057
  /**
2058
+ * Mounts a new list item from a spec: allocates the ListItem, establishes it
2059
+ * as the active region (so the compiler-emitted `create` callback attaches
2060
+ * effects/events to the right region), sets its depth, optionally wraps its
2061
+ * data in a shallow watch, then runs `create`. Returns the mounted item so the
2062
+ * caller can slot it into the live list. The sibling chain is left for the
2063
+ * end-of-pass relink.
2064
+ */
2065
+ function mountSpec(spec, region, before, create, noWatch) {
2066
+ const item = newListItem(spec.data, spec.key);
2067
+ const savedActiveRegion = context.activeRegion;
2068
+ item.depth = region.depth + 1;
2069
+ context.activeRegion = item;
2070
+ if (noWatch !== true) item.data = $watch(item.data, SHALLOW_WATCH_OPTIONS);
2071
+ create(item, before);
2072
+ context.activeRegion = savedActiveRegion;
2073
+ return item;
2074
+ }
2075
+ /**
2076
+ * Reconciles an old keyed list against a new keyed list, reusing old
2077
+ * ListItems for survivors and producing the minimal set of DOM moves /
2078
+ * mounts / clears.
2079
+ *
2080
+ * @returns The new live list of ListItems (reused old items + freshly
2081
+ * mounted ones), which the caller keeps for the next reconciliation.
2082
+ *
1007
2083
  * @param region The list's region
1008
2084
  * @param parent The parent DOM element
1009
- * @param anchor The DOM element to create new items before
1010
- * @param oldItems The list of current items
1011
- * @param newItems The list of future items
2085
+ * @param anchor The DOM node to create new items before (the list's trailing anchor)
2086
+ * @param oldItems The list of current (live) items from the previous run
2087
+ * @param newSpecs The lightweight {key, data} specs for the new data
1012
2088
  * @param create A function that creates the DOM elements for a new item
2089
+ * @param update A function that syncs a matched item's data from its spec
2090
+ * (re-runs effects if a loop variable's reference actually changed)
2091
+ * @param noWatch When true, skip the per-item shallow `$watch` wrap. The
2092
+ * compiler guarantees the `@for` body never writes to its loop variables,
2093
+ * and emits an `update` callback that re-runs item effects manually when a
2094
+ * loop variable's reference actually changes (via `t_rerun_region_effects`).
1013
2095
  */
1014
- function runListItems(region, parent, anchor, oldItems, newItems, create, update) {
1015
- let oldStartIndex = 0;
1016
- let oldEndIndex = oldItems.length - 1;
1017
- let oldStartItem = oldItems[0];
1018
- let oldEndItem = oldItems[oldEndIndex];
1019
- let newStartIndex = 0;
1020
- let newEndIndex = newItems.length - 1;
1021
- let newStartItem = newItems[0];
1022
- let newEndItem = newItems[newEndIndex];
1023
- let oldKeyToIndex;
1024
- let newKeyToIndex;
1025
- while (oldStartIndex <= oldEndIndex && newStartIndex <= newEndIndex) if (oldStartItem === null) oldStartItem = oldItems[++oldStartIndex];
1026
- else if (oldEndItem === null) oldEndItem = oldItems[--oldEndIndex];
1027
- else if (newStartItem === null) newStartItem = newItems[++newStartIndex];
1028
- else if (newEndItem === null) newEndItem = newItems[--newEndIndex];
1029
- else if (oldStartItem.key === newStartItem.key) {
1030
- transferListItemData(oldStartItem, newStartItem, update);
1031
- oldStartItem = oldItems[++oldStartIndex];
1032
- newStartItem = newItems[++newStartIndex];
1033
- } else if (oldEndItem.key === newEndItem.key) {
1034
- transferListItemData(oldEndItem, newEndItem, update);
1035
- oldEndItem = oldItems[--oldEndIndex];
1036
- newEndItem = newItems[--newEndIndex];
1037
- } else if (oldStartItem.key === newEndItem.key) {
1038
- moveRegion(parent, oldStartItem, oldEndItem.endNode.nextSibling);
1039
- transferListItemData(oldStartItem, newEndItem, update);
1040
- oldStartItem = oldItems[++oldStartIndex];
1041
- newEndItem = newItems[--newEndIndex];
1042
- } else if (oldEndItem.key === newStartItem.key) {
1043
- moveRegion(parent, oldEndItem, oldStartItem.startNode);
1044
- transferListItemData(oldEndItem, newStartItem, update);
1045
- oldEndItem = oldItems[--oldEndIndex];
1046
- newStartItem = newItems[++newStartIndex];
1047
- } else {
1048
- if (oldKeyToIndex === void 0 || newKeyToIndex === void 0) {
1049
- oldKeyToIndex = /* @__PURE__ */ new Map();
1050
- for (let i = oldStartIndex; i < oldEndIndex; i++) oldKeyToIndex.set(oldItems[i].key, i);
1051
- newKeyToIndex = /* @__PURE__ */ new Map();
1052
- for (let i = newStartIndex; i < newEndIndex; i++) newKeyToIndex.set(newItems[i].key, i);
2096
+ function runListItems(region, parent, anchor, oldItems, newSpecs, create, update, noWatch) {
2097
+ const newItems = Array.from({ length: newSpecs.length });
2098
+ let nextSibling;
2099
+ if (oldItems.length > 0) {
2100
+ const lastOld = oldItems[oldItems.length - 1];
2101
+ nextSibling = lastOld.nextRegion;
2102
+ while (nextSibling !== null && nextSibling.depth > lastOld.depth) nextSibling = nextSibling.nextRegion;
2103
+ } else nextSibling = region.nextRegion;
2104
+ let oldStart = 0;
2105
+ let oldEnd = oldItems.length - 1;
2106
+ let newStart = 0;
2107
+ let newEnd = newSpecs.length - 1;
2108
+ let chainNeedsRelink = false;
2109
+ while (oldStart <= oldEnd && newStart <= newEnd) if (oldItems[oldStart].key === newSpecs[newStart].key) {
2110
+ const item = oldItems[oldStart];
2111
+ update(item, newSpecs[newStart]);
2112
+ newItems[newStart] = item;
2113
+ oldStart++;
2114
+ newStart++;
2115
+ } else if (oldItems[oldEnd].key === newSpecs[newEnd].key) {
2116
+ const item = oldItems[oldEnd];
2117
+ update(item, newSpecs[newEnd]);
2118
+ newItems[newEnd] = item;
2119
+ oldEnd--;
2120
+ newEnd--;
2121
+ } else if (oldItems[oldStart].key === newSpecs[newEnd].key) {
2122
+ const item = oldItems[oldStart];
2123
+ moveRegion(parent, item, oldItems[oldEnd].endNode?.nextSibling ?? anchor);
2124
+ chainNeedsRelink = true;
2125
+ update(item, newSpecs[newEnd]);
2126
+ newItems[newEnd] = item;
2127
+ oldStart++;
2128
+ newEnd--;
2129
+ } else if (oldItems[oldEnd].key === newSpecs[newStart].key) {
2130
+ const item = oldItems[oldEnd];
2131
+ moveRegion(parent, item, oldItems[oldStart].startNode);
2132
+ chainNeedsRelink = true;
2133
+ update(item, newSpecs[newStart]);
2134
+ newItems[newStart] = item;
2135
+ oldEnd--;
2136
+ newStart++;
2137
+ } else break;
2138
+ if (oldStart > oldEnd && newStart <= newEnd) {
2139
+ const before = newEnd + 1 < newSpecs.length ? newItems[newEnd + 1].startNode : anchor;
2140
+ for (let i = newStart; i <= newEnd; i++) newItems[i] = mountSpec(newSpecs[i], region, before, create, noWatch);
2141
+ chainNeedsRelink = true;
2142
+ } else if (newStart > newEnd) for (let i = oldStart; i <= oldEnd; i++) clearRegion(oldItems[i]);
2143
+ else {
2144
+ const newKeyToIndex = /* @__PURE__ */ new Map();
2145
+ for (let i = newStart; i <= newEnd; i++) newKeyToIndex.set(newSpecs[i].key, i);
2146
+ let anyOverlap = false;
2147
+ for (let i = oldStart; i <= oldEnd; i++) if (newKeyToIndex.has(oldItems[i].key)) {
2148
+ anyOverlap = true;
2149
+ break;
1053
2150
  }
1054
- let oldIndex = oldKeyToIndex.get(newStartItem.key);
1055
- let newIndex = newKeyToIndex.get(oldStartItem.key);
1056
- if (oldIndex === void 0 && newIndex === void 0) {
1057
- const oldRegion = pushRegion(newStartItem, true);
1058
- newStartItem.data = $watch(newStartItem.data, { shallow: true });
1059
- create(newStartItem, oldStartItem.startNode);
1060
- popRegion(oldRegion);
1061
- newStartItem.previousRegion = oldStartItem.previousRegion;
1062
- newStartItem.nextRegion = oldStartItem;
1063
- oldStartItem.previousRegion = newStartItem;
1064
- clearRegion(oldStartItem);
1065
- oldStartItem = oldItems[++oldStartIndex];
1066
- newStartItem = newItems[++newStartIndex];
1067
- } else if (oldIndex === void 0) {
1068
- const oldRegion = pushRegion(newStartItem, true);
1069
- newStartItem.data = $watch(newStartItem.data, { shallow: true });
1070
- create(newStartItem, oldStartItem.startNode);
1071
- popRegion(oldRegion);
1072
- newStartItem = newItems[++newStartIndex];
1073
- } else if (newIndex === void 0) {
1074
- clearRegion(oldStartItem);
1075
- oldStartItem = oldItems[++oldStartIndex];
2151
+ if (!anyOverlap) {
2152
+ let before = oldItems[oldEnd]?.endNode?.nextSibling ?? anchor;
2153
+ for (let i = oldEnd; i >= oldStart; i--) clearRegion(oldItems[i]);
2154
+ for (let i = newStart; i <= newEnd; i++) {
2155
+ newItems[i] = mountSpec(newSpecs[i], region, before, create, noWatch);
2156
+ before = newItems[i].endNode.nextSibling;
2157
+ }
2158
+ chainNeedsRelink = true;
1076
2159
  } else {
1077
- const oldData = oldItems[oldIndex];
1078
- moveRegion(parent, oldData, oldStartItem.startNode);
1079
- transferListItemData(oldData, newStartItem, update);
1080
- oldItems[oldIndex] = null;
1081
- newStartItem = newItems[++newStartIndex];
2160
+ const newMidLen = newEnd - newStart + 1;
2161
+ const newIndexToOld = Array.from({ length: newMidLen }).fill(0);
2162
+ for (let i = oldStart; i <= oldEnd; i++) {
2163
+ const oldItem = oldItems[i];
2164
+ const newIdx = newKeyToIndex.get(oldItem.key);
2165
+ if (newIdx !== void 0) {
2166
+ newIndexToOld[newIdx - newStart] = i + 1;
2167
+ update(oldItem, newSpecs[newIdx]);
2168
+ newItems[newIdx] = oldItem;
2169
+ } else clearRegion(oldItem);
2170
+ }
2171
+ const seq = getSequence(newIndexToOld);
2172
+ let j = seq.length - 1;
2173
+ for (let i = newMidLen - 1; i >= 0; i--) {
2174
+ const newIdx = newStart + i;
2175
+ const before = newIdx + 1 < newSpecs.length ? newItems[newIdx + 1].startNode : anchor;
2176
+ if (newIndexToOld[i] === 0) {
2177
+ newItems[newIdx] = mountSpec(newSpecs[newIdx], region, before, create, noWatch);
2178
+ chainNeedsRelink = true;
2179
+ } else if (j < 0 || i !== seq[j]) {
2180
+ moveRegion(parent, newItems[newIdx], before);
2181
+ chainNeedsRelink = true;
2182
+ } else j--;
2183
+ }
1082
2184
  }
1083
2185
  }
1084
- if (oldStartIndex <= oldEndIndex || newStartIndex <= newEndIndex) if (oldStartIndex > oldEndIndex) {
1085
- let before = oldStartItem?.startNode ?? oldItems[oldItems.length - 1]?.endNode?.nextSibling ?? anchor;
1086
- for (; newStartIndex <= newEndIndex; newStartItem = newItems[++newStartIndex]) {
1087
- const oldRegion = pushRegion(newStartItem, true);
1088
- newStartItem.data = $watch(newStartItem.data, { shallow: true });
1089
- create(newStartItem, before);
1090
- popRegion(oldRegion);
1091
- before = newStartItem.endNode.nextSibling;
2186
+ if (!chainNeedsRelink && newItems.length > 0) {
2187
+ let lastRegion = newItems[newItems.length - 1];
2188
+ let next = lastRegion.nextRegion;
2189
+ while (next !== null && next.depth > lastRegion.depth) {
2190
+ lastRegion = next;
2191
+ next = next.nextRegion;
1092
2192
  }
1093
- } else for (; oldEndIndex >= oldStartIndex; oldStartItem = oldItems[oldEndIndex--]) clearRegion(oldStartItem);
1094
- if (newItems.length > 0) region.nextRegion = newItems[0];
1095
- else if (oldItems.length > 0) region.nextRegion = oldItems[oldItems.length - 1].nextRegion;
1096
- }
1097
- function transferListItemData(oldItem, newItem, update) {
1098
- newItem.startNode = oldItem.startNode;
1099
- newItem.endNode = oldItem.endNode;
1100
- update(oldItem, newItem);
1101
- newItem.data = oldItem.data;
1102
- newItem.name = oldItem.name;
2193
+ context.previousRegion = lastRegion;
2194
+ return newItems;
2195
+ }
2196
+ if (newItems.length > 0) {
2197
+ let prevTail = region;
2198
+ for (let i = 0; i < newItems.length; i++) {
2199
+ const item = newItems[i];
2200
+ item.previousRegion = prevTail;
2201
+ prevTail.nextRegion = item;
2202
+ let last = item;
2203
+ let next = item.nextRegion;
2204
+ while (next !== null && next.depth > item.depth) {
2205
+ last = next;
2206
+ next = next.nextRegion;
2207
+ }
2208
+ prevTail = last;
2209
+ }
2210
+ prevTail.nextRegion = nextSibling;
2211
+ if (nextSibling !== null) nextSibling.previousRegion = prevTail;
2212
+ region.nextRegion = newItems[0];
2213
+ context.previousRegion = prevTail;
2214
+ } else {
2215
+ region.nextRegion = nextSibling;
2216
+ if (nextSibling !== null) nextSibling.previousRegion = region;
2217
+ context.previousRegion = region;
2218
+ }
2219
+ return newItems;
1103
2220
  }
1104
-
1105
2221
  //#endregion
1106
2222
  //#region src/render/runList.ts
1107
2223
  /**
1108
2224
  * Runs a `for` control statement
2225
+ * @param buildItems A function that returns the current list of lightweight
2226
+ * `{key, data}` specs (one per row of the source data)
1109
2227
  * @param create A function that creates the control statement's branches
2228
+ * @param noWatch When true, the compiler has determined the `@for` body never
2229
+ * writes to its loop variables, so each item's `data` bag can be left
2230
+ * unwrapped (skipping the per-item shallow `$watch` Proxy + ProxyData +
2231
+ * signals Map allocations). The compiler-emitted `update` callback is then
2232
+ * responsible for re-running item effects when a loop variable's reference
2233
+ * actually changes (via `t_rerun_region_effects`).
1110
2234
  */
1111
- function runList(region, parent, anchor, buildItems, create, update) {
2235
+ function runList(region, parent, anchor, buildItems, create, update, noWatch) {
1112
2236
  let first = true;
1113
2237
  let listItems = [];
1114
- $run(function runList$1() {
2238
+ $run(function runList() {
2239
+ if (region.depth === -2) return;
1115
2240
  const oldRegion = pushRegion(region, first);
1116
2241
  first = false;
1117
- const newItems = buildItems();
1118
- context_default.activeTarget = null;
1119
- runListItems(region, parent, anchor, listItems, newItems, create, update);
1120
- listItems = newItems;
2242
+ const newSpecs = buildItems();
2243
+ context.activeTarget = null;
2244
+ listItems = runListItems(region, parent, anchor, listItems, newSpecs, create, update, noWatch);
1121
2245
  popRegion(oldRegion);
1122
2246
  });
1123
- if (context_default.hydrationNode !== null) anchor = context_default.hydrationNode.nextSibling;
1124
2247
  }
1125
-
2248
+ //#endregion
2249
+ //#region src/render/runAwait.ts
2250
+ /**
2251
+ * Renders an `@await` boundary. On the first run, content is rendered
2252
+ * speculatively; if any read inside suspends (`didSuspend`), the boundary
2253
+ * discards the partial render and shows the `with` branch instead.
2254
+ *
2255
+ * Fine-grained updates: on subsequent runs the boundary only decides whether
2256
+ * to SWITCH branches. It does so from its `pending` set — the suspended
2257
+ * computeds recorded by `suspendRead` — dropping entries that resolved and
2258
+ * re-subscribing the still-suspended ones (a re-run deactivates all of the
2259
+ * effect's source subscriptions, so they must be re-tracked to survive
2260
+ * `clearSources`). That check is O(pending reads), not O(all sources), and
2261
+ * non-suspend dependency changes inside content are left to the child
2262
+ * effects that read them — the boundary isn't re-run by them at all.
2263
+ *
2264
+ * Stale-while-revalidate (ASYNC.md §6.2): once content has been produced
2265
+ * (`hasContent`), a subsequent suspend during a refresh does NOT switch to
2266
+ * the `with` branch — the boundary keeps the stale content mounted. `$async`
2267
+ * retains the previous resolved value (`Computed.staleValue`) and
2268
+ * `suspendRead` returns it, so child effects keep displaying the old value
2269
+ * until the new promise resolves and updates them in place. The `with` branch
2270
+ * is shown only on the first load, before content has ever rendered
2271
+ * successfully.
2272
+ *
2273
+ * @param renderContent Builds the content children (may read $async getters).
2274
+ * @param renderWith Builds the `with`-branch children, or null for empty.
2275
+ */
2276
+ function runAwait(region, anchor, renderContent, renderWith, name) {
2277
+ const boundary = {
2278
+ suspended: false,
2279
+ pending: /* @__PURE__ */ new Set(),
2280
+ effect: null
2281
+ };
2282
+ let index = -1;
2283
+ let first = true;
2284
+ let hasContent = false;
2285
+ let theEffect = null;
2286
+ const gen = region.generation = (region.generation ?? 0) + 1;
2287
+ $run(function runAwait() {
2288
+ if (region.generation !== gen) return;
2289
+ theEffect = context.activeTarget;
2290
+ boundary.effect = theEffect;
2291
+ const oldRegion = pushRegion(region, first);
2292
+ first = false;
2293
+ const renderBranch = (targetIndex, fn) => {
2294
+ runControlBranch(region, index, targetIndex);
2295
+ context.previousRegion = region;
2296
+ const oldR = pushRegion(newRegion(targetIndex === 0 ? "await_content" : "await_with"), true);
2297
+ fn(anchor);
2298
+ popRegion(oldR);
2299
+ index = targetIndex;
2300
+ };
2301
+ const attemptContent = () => {
2302
+ const oldBoundary = context.awaitBoundary;
2303
+ context.awaitBoundary = boundary;
2304
+ boundary.suspended = false;
2305
+ const savedHydration = context.hydrationNode;
2306
+ if (savedHydration !== null) context.hydrationNode = null;
2307
+ renderBranch(0, renderContent);
2308
+ if (savedHydration !== null) context.hydrationNode = savedHydration;
2309
+ context.awaitBoundary = oldBoundary;
2310
+ if (boundary.suspended && renderWith !== null) renderBranch(1, renderWith);
2311
+ else if (!boundary.suspended) hasContent = true;
2312
+ };
2313
+ if (theEffect === null) attemptContent();
2314
+ else {
2315
+ let suspended = false;
2316
+ for (const signal of boundary.pending) if (signal.didSuspend) {
2317
+ suspended = true;
2318
+ trackSignal(signal);
2319
+ } else boundary.pending.delete(signal);
2320
+ const targetIndex = suspended ? 1 : 0;
2321
+ if (targetIndex !== index) {
2322
+ if (targetIndex === 0) attemptContent();
2323
+ else if (!hasContent) if (renderWith !== null) renderBranch(1, renderWith);
2324
+ else {
2325
+ runControlBranch(region, index, 1);
2326
+ index = 1;
2327
+ }
2328
+ }
2329
+ }
2330
+ popRegion(oldRegion);
2331
+ widenAncestorsAtAnchor(region, anchor);
2332
+ }, name);
2333
+ }
2334
+ //#endregion
2335
+ //#region src/render/saveHydration.ts
2336
+ /**
2337
+ * Snapshots the hydration cursor so a `@try` branch's partial hydration walk
2338
+ * can be rewound if the branch throws and the `@catch` branch renders instead.
2339
+ *
2340
+ * @returns The current hydration cursor node, or `null` when not hydrating.
2341
+ */
2342
+ function saveHydration() {
2343
+ return context.hydrationNode;
2344
+ }
2345
+ //#endregion
2346
+ //#region src/render/runTry.ts
2347
+ /**
2348
+ * Renders a `@try`/`@catch` group, or a top-level `@error` block (which the
2349
+ * compiler wraps around the whole render).
2350
+ *
2351
+ * Like `runAwait`, the boundary is a control effect that renders one branch
2352
+ * at a time into a fresh child region (`runControlBranch` clears the old
2353
+ * branch on switch). Unlike the old compiled form, the try/catch lives in
2354
+ * this runtime, which gives it three capabilities the compiled form lacked:
2355
+ *
2356
+ * - **Effect-rerun error routing.** The boundary registers itself on its
2357
+ * region (`region.errorBoundary`); when an effect inside the try content
2358
+ * throws on a later re-run, `triggerEffects` → `routeEffectError` stores
2359
+ * the error here and force re-runs the boundary effect, which renders the
2360
+ * catch branch with it.
2361
+ * - **Recovery outside direct reads.** Reactive reads wrapped in nested
2362
+ * `$run` effects (text/attribute interpolation) are tracked by those
2363
+ * effects, not the boundary. When an error is routed, the boundary holds
2364
+ * the erroring effect's source signals (`heldSignals`) and re-subscribes
2365
+ * to them on every run that shows the catch branch, so a later change
2366
+ * re-attempts the try branch.
2367
+ * - **Top-level `@error` recovery.** Because the whole render is a
2368
+ * re-runnable branch, a later re-render error (from a nested control
2369
+ * re-running after a prop change) is caught by the same routing, and a
2370
+ * recovery re-render clears the error content and restores the normal
2371
+ * content.
2372
+ *
2373
+ * Semantics preserved from the compiled form:
2374
+ *
2375
+ * - Synchronous build errors in the try content render the catch branch
2376
+ * (rewinding the hydration cursor and restoring the control region, which
2377
+ * the failed partial build left active).
2378
+ * - While the try branch is showing, a boundary re-run with no routed error
2379
+ * does NOT rebuild it (`runControlBranch` same-index skip) — exactly like
2380
+ * `@if`/`@switch` branches.
2381
+ * - While the catch branch is showing, any boundary re-run re-attempts the
2382
+ * try branch (the recovery path for errors read directly by the boundary
2383
+ * effect, e.g. via `@const`).
2384
+ * - With no catch branch, errors propagate up to the nearest outer boundary
2385
+ * and no boundary is registered on the region.
2386
+ *
2387
+ * @param renderTry Builds the try content. May read reactive state.
2388
+ * @param renderCatch Builds the catch content, or null for `@try` without
2389
+ * `@catch`. Receives the error (the `@catch (err)` variable).
2390
+ */
2391
+ function runTry(region, anchor, renderTry, renderCatch, name) {
2392
+ const boundary = {
2393
+ error: void 0,
2394
+ hasError: false,
2395
+ effect: null,
2396
+ heldSignals: null
2397
+ };
2398
+ if (renderCatch !== null) region.errorBoundary = boundary;
2399
+ let index = -1;
2400
+ let first = true;
2401
+ const gen = region.generation = (region.generation ?? 0) + 1;
2402
+ $run(function runTry() {
2403
+ if (region.generation !== gen) return;
2404
+ const theEffect = context.activeTarget;
2405
+ boundary.effect = theEffect;
2406
+ const oldRegion = pushRegion(region, first);
2407
+ first = false;
2408
+ const renderBranch = (targetIndex, fn) => {
2409
+ runControlBranch(region, index, targetIndex);
2410
+ context.previousRegion = region;
2411
+ const oldR = pushRegion(newRegion(targetIndex === 0 ? "try" : "catch"), true);
2412
+ fn(anchor);
2413
+ popRegion(oldR);
2414
+ index = targetIndex;
2415
+ };
2416
+ const holdSignals = () => {
2417
+ if (boundary.heldSignals === null || theEffect === null) return;
2418
+ for (const signal of boundary.heldSignals) trackSignal(signal);
2419
+ };
2420
+ const hasRoutedError = boundary.hasError;
2421
+ const routedError = boundary.error;
2422
+ boundary.hasError = false;
2423
+ if (hasRoutedError && renderCatch !== null) {
2424
+ index = -1;
2425
+ renderBranch(1, (a) => renderCatch(a, routedError));
2426
+ holdSignals();
2427
+ } else if (index !== 0) {
2428
+ const snapshot = saveHydration();
2429
+ try {
2430
+ renderBranch(0, renderTry);
2431
+ boundary.heldSignals = null;
2432
+ } catch (err) {
2433
+ pushRegion(region);
2434
+ restoreHydration(snapshot);
2435
+ if (renderCatch !== null) {
2436
+ index = -1;
2437
+ renderBranch(1, (a) => renderCatch(a, err));
2438
+ holdSignals();
2439
+ } else throw err;
2440
+ }
2441
+ }
2442
+ popRegion(oldRegion);
2443
+ widenAncestorsAtAnchor(region, anchor);
2444
+ if (context.hydrationNode !== null && anchor !== null) context.hydrationNode = anchor;
2445
+ }, name);
2446
+ }
1126
2447
  //#endregion
1127
2448
  //#region src/render/setAttribute.ts
1128
2449
  function setAttribute(el, name, value) {
1129
2450
  if (value === false || value === void 0 || value === null) el.removeAttribute(name);
1130
2451
  else el.setAttribute(name, value);
1131
2452
  }
1132
-
1133
2453
  //#endregion
1134
2454
  //#region src/render/setDynamicElement.ts
1135
2455
  function setDynamicElement(el, tag) {
1136
- if (context_default.hydrationNode !== null) return el;
2456
+ if (context.hydrationNode !== null) return el;
1137
2457
  let newElement = el.ownerDocument.createElement(tag);
2458
+ for (const attr of el.attributes) newElement.setAttributeNS(null, attr.name, attr.value);
2459
+ copyEventListeners(el, newElement);
2460
+ newElement.replaceChildren(...el.childNodes.values());
1138
2461
  el.replaceWith(newElement);
1139
2462
  return newElement;
1140
2463
  }
1141
-
1142
2464
  //#endregion
1143
2465
  //#region src/watch/$batch.ts
1144
2466
  /**
@@ -1148,7 +2470,7 @@ function setDynamicElement(el, tag) {
1148
2470
  * @param fn The function containing the batched updates to run.
1149
2471
  */
1150
2472
  function $batch(fn) {
1151
- if (context_default.batch > 0) return fn();
2473
+ if (context.batch > 0) return fn();
1152
2474
  batchStart();
1153
2475
  try {
1154
2476
  return fn();
@@ -1156,7 +2478,127 @@ function $batch(fn) {
1156
2478
  batchEnd();
1157
2479
  }
1158
2480
  }
1159
-
2481
+ //#endregion
2482
+ //#region src/watch/$async.ts
2483
+ /**
2484
+ * Caches an async computed value from a thunk that returns a Promise. A peer
2485
+ * of `$cache` for async getters: the returned Computed carries a `didSuspend`
2486
+ * indicator that the proxy get trap reads to suspend callers until the promise
2487
+ * resolves.
2488
+ *
2489
+ * The thenable check and `.then` wiring live inside `computed.run` (a closure
2490
+ * over the computed object), so they fire on both the initial run and every
2491
+ * recalculation — `runComputed` and `checkComputed` are unchanged.
2492
+ *
2493
+ * @param fn A thunk returning the Promise to await. Signal reads inside `fn`
2494
+ * are tracked, so the fetch re-runs when dependencies change.
2495
+ */
2496
+ function $async(fn) {
2497
+ if (context.registerComputed === null) throw new Error("$async must be used in a getter");
2498
+ const computed = {
2499
+ type: 1,
2500
+ isAsync: true,
2501
+ value: null,
2502
+ run: null,
2503
+ firstSource: null,
2504
+ firstTarget: null,
2505
+ recalc: false,
2506
+ running: false,
2507
+ didError: false,
2508
+ didSuspend: false,
2509
+ generation: 0,
2510
+ hasResolved: false,
2511
+ lastErrored: false,
2512
+ suspendQuiet: false,
2513
+ staleValue: void 0,
2514
+ rollback: null
2515
+ };
2516
+ computed.run = () => {
2517
+ const value = fn();
2518
+ if (value !== null && value !== void 0 && typeof value.then === "function") {
2519
+ const gen = ++computed.generation;
2520
+ computed.didSuspend = true;
2521
+ computed.suspendQuiet = computed.hasResolved && !computed.recalc;
2522
+ value.then((v) => {
2523
+ if (computed.generation !== gen) return;
2524
+ computed.value = v;
2525
+ computed.didSuspend = false;
2526
+ computed.hasResolved = true;
2527
+ computed.lastErrored = false;
2528
+ computed.staleValue = v;
2529
+ batchStart();
2530
+ propagateFromSignal(computed);
2531
+ batchEnd();
2532
+ }, (e) => {
2533
+ if (computed.generation !== gen) return;
2534
+ computed.value = e;
2535
+ computed.didError = true;
2536
+ computed.didSuspend = false;
2537
+ computed.hasResolved = true;
2538
+ computed.lastErrored = true;
2539
+ computed.staleValue = void 0;
2540
+ batchStart();
2541
+ propagateFromSignal(computed);
2542
+ batchEnd();
2543
+ });
2544
+ }
2545
+ return value;
2546
+ };
2547
+ context.registerComputed(computed);
2548
+ runComputed(computed);
2549
+ return computed.value;
2550
+ }
2551
+ //#endregion
2552
+ //#region src/watch/$bind.ts
2553
+ /**
2554
+ * Establishes two-way reactive sync between matching keys on a state object
2555
+ * and a props object.
2556
+ *
2557
+ * For each key, `$bind` creates:
2558
+ * - **Forward sync** (`props → state`): when the parent pushes a new value via
2559
+ * `$props[key]`, it flows into `$state[key]`. Skips `undefined` values so
2560
+ * that defaults set in the initial `$watch(...)` are preserved when the
2561
+ * parent doesn't provide a value.
2562
+ * - **Backward sync** (`state → props`): when the component mutates
2563
+ * `$state[key]`, the new value is written back to `$props[key]`, which the
2564
+ * call site's `&key={...}` binding picks up and propagates to the parent.
2565
+ *
2566
+ * Same-value writes are no-ops (handled by the proxy layer), so two-way sync
2567
+ * stabilises without infinite loops.
2568
+ *
2569
+ * `$bind` syncs same-named keys, so the key must exist on the state object.
2570
+ * A state key named differently from the prop (e.g. `values` against a
2571
+ * `value` prop) would silently do nothing -- the binding reads and writes
2572
+ * keys that nothing else touches -- which is almost impossible to debug. The
2573
+ * key is therefore required to exist on the state object, and `$bind` throws
2574
+ * at setup otherwise.
2575
+ *
2576
+ * The prop does *not* need to exist on `props` yet: when the parent doesn't
2577
+ * pass an optional prop, the compiled props object has no key for it, and
2578
+ * the binding is simply inert (uncontrolled mode) until a value is pushed.
2579
+ *
2580
+ * @param state The component's reactive state (created via `$watch`).
2581
+ * @param props The component's `$props` proxy. When `undefined` (component
2582
+ * called with no props), `$bind` does nothing.
2583
+ * @param keys Keys to sync. Each key must exist on `state`.
2584
+ * @throws When a key does not exist on the state object.
2585
+ */
2586
+ function $bind(state, props, ...keys) {
2587
+ if (props === void 0) return;
2588
+ for (let key of keys.flat()) {
2589
+ if (!(key in state)) throw new Error(`$bind: the key "${key}" does not exist on the state object. $bind syncs same-named keys, so the state object must declare it (e.g. in the initial $watch).`);
2590
+ $run(() => {
2591
+ const v = props[key];
2592
+ if (v !== void 0) state[key] = v;
2593
+ }, `bind:forward:${key}`);
2594
+ let firstBackward = true;
2595
+ $run(() => {
2596
+ const value = state[key];
2597
+ if (!firstBackward) props[key] = value;
2598
+ firstBackward = false;
2599
+ }, `bind:backward:${key}`);
2600
+ }
2601
+ }
1160
2602
  //#endregion
1161
2603
  //#region src/watch/$cache.ts
1162
2604
  /**
@@ -1165,9 +2607,13 @@ function $batch(fn) {
1165
2607
  * @param fn The function containing the signals to compute and cache.
1166
2608
  */
1167
2609
  function $cache(fn) {
1168
- if (context_default.registerComputed === null) throw new Error("$cache must be used in a getter");
2610
+ if (context.registerComputed === null) {
2611
+ if (typeof window !== "undefined") throw new Error("$cache must be used in a getter");
2612
+ return fn();
2613
+ }
1169
2614
  let computed = {
1170
- type: COMPUTED_TYPE,
2615
+ type: 1,
2616
+ isAsync: false,
1171
2617
  value: null,
1172
2618
  run: fn,
1173
2619
  firstSource: null,
@@ -1175,74 +2621,226 @@ function $cache(fn) {
1175
2621
  recalc: false,
1176
2622
  running: false,
1177
2623
  didError: false,
2624
+ didSuspend: false,
2625
+ generation: 0,
2626
+ hasResolved: false,
2627
+ lastErrored: false,
2628
+ suspendQuiet: false,
2629
+ staleValue: void 0,
1178
2630
  rollback: null
1179
2631
  };
1180
- context_default.registerComputed(computed);
2632
+ context.registerComputed(computed);
1181
2633
  runComputed(computed);
2634
+ if (computed.value !== null && computed.value !== void 0 && typeof computed.value.then === "function") throw new Error("$cache returned a Promise — use $async for async getters");
1182
2635
  return computed.value;
1183
2636
  }
1184
-
1185
2637
  //#endregion
1186
- //#region src/watch/$mount.ts
2638
+ //#region src/watch/$onmount.ts
1187
2639
  /**
1188
- * Runs and re-runs a function on component mount
2640
+ * Runs `fn` once after the component is mounted to the DOM. May return a
2641
+ * cleanup function that runs on unmount / region clear.
2642
+ *
2643
+ * The callback is **not reactive**: it runs exactly once per mount, and
2644
+ * reactive values it reads are not tracked. To set up something that should
2645
+ * keep updating, wrap the reactive part in `$run`:
2646
+ *
2647
+ * ```ts
2648
+ * $onmount(() => {
2649
+ * $run(() => {
2650
+ * label.textContent = $state.count > 0 ? "+" : "";
2651
+ * });
2652
+ * });
2653
+ * ```
2654
+ *
2655
+ * The element-level equivalent is the `onmount` attribute:
2656
+ * `<input onmount={(el) => el.focus()} />`.
1189
2657
  *
1190
2658
  * @param fn The function to run, which may return a cleanup function
1191
2659
  */
1192
- function $mount(fn) {
1193
- context_default.mountEffects.push(fn);
2660
+ function $onmount(fn) {
2661
+ context.mountEffects.push({
2662
+ region: context.activeRegion,
2663
+ fn
2664
+ });
1194
2665
  }
1195
-
1196
2666
  //#endregion
1197
- //#region src/watch/$peek.ts
1198
- function $peek(fn) {
1199
- const oldActiveTarget = context_default.activeTarget;
1200
- context_default.activeTarget = null;
1201
- const result = fn();
1202
- context_default.activeTarget = oldActiveTarget;
1203
- return result;
2667
+ //#region src/watch/$pending.ts
2668
+ /**
2669
+ * Returns `true` if any value read inside `fn` is currently suspended in a
2670
+ * "loud" way — a `$async` getter whose promise hasn't resolved yet. A reactive
2671
+ * query for inline "loading…" indicators: the calling effect subscribes to the
2672
+ * same computeds, so `$pending` re-evaluates when they resolve.
2673
+ *
2674
+ * Uses a "peek mode" internally: reads during `fn` are tracked for
2675
+ * subscription but don't propagate taint or notify a `@await` boundary.
2676
+ * This lets `$pending` return a plain boolean without itself suspending.
2677
+ *
2678
+ * Quiet-on-refresh semantics (ASYNC.md §7.4): a suspend is *quiet* — and
2679
+ * therefore `$pending` returns `false` for it — when the computed has resolved
2680
+ * before and the re-fetch was a *silent* `$refresh(fn, { silent: true })` (a
2681
+ * bare refresh with no tracked dependency change, used for background
2682
+ * revalidation). This matches Solid's stale-while-revalidate default: quietly
2683
+ * re-asking the same question shouldn't ping the user. First loads and
2684
+ * dependency-change refreshes are loud (`true`), as is the default (loud)
2685
+ * `$refresh(fn)`. Quiet-ness is captured per computed at suspend time via
2686
+ * `suspendQuiet` (computed in `$async`'s run from `hasResolved` and `recalc`).
2687
+ *
2688
+ * @param fn A function that reads the reactive values to check.
2689
+ */
2690
+ function $pending(fn) {
2691
+ const oldPeek = context.suspendPeek;
2692
+ context.suspendPeek = true;
2693
+ context.suspendPeekHit = false;
2694
+ try {
2695
+ fn();
2696
+ return context.suspendPeekHit;
2697
+ } finally {
2698
+ context.suspendPeek = oldPeek;
2699
+ }
1204
2700
  }
1205
-
1206
2701
  //#endregion
1207
- //#region src/wrappers/ReactiveDate.ts
1208
- let initialized = false;
2702
+ //#region src/watch/$refresh.ts
1209
2703
  /**
1210
- * Wraps a Date object for $watching.
2704
+ * Re-fetches the `$async` getters read inside `fn` without changing a
2705
+ * dependency. A companion to `$pending` (ASYNC.md §6.2): pull-to-refresh,
2706
+ * refresh buttons, refetch-on-focus, polling, retry-after-error.
2707
+ *
2708
+ * `fn` is run in a tracking context that collects every `$async` computed it
2709
+ * reads (`$cache` computeds are ignored). Each collected computed is then
2710
+ * re-run with `recalc` left true — a "bare refresh" — so the suspend is
2711
+ * *loud*: `$pending(fn)` returns `true` while the re-fetch is in flight and
2712
+ * subscribers are notified at suspend *start*, so an inline "updating…"
2713
+ * indicator appears immediately. Readers keep displaying the previous
2714
+ * resolved value (`Computed.staleValue`) until the new promise resolves and
2715
+ * propagates through the reactive graph; an `@await` boundary keeps its
2716
+ * content mounted instead of flashing fallback.
2717
+ *
2718
+ * Pass `{ silent: true }` to re-fetch quietly (stale-while-revalidate):
2719
+ * `$pending(fn)` stays `false` and nothing re-runs until the new promise
2720
+ * resolves. For background revalidation where feedback would be noise —
2721
+ * polling, refetch-on-focus:
2722
+ *
2723
+ * ```torp
2724
+ * // poll quietly every 30s
2725
+ * $run(() => {
2726
+ * const id = setInterval(() => $refresh(() => $state.data, { silent: true }), 30_000);
2727
+ * return () => clearInterval(id);
2728
+ * });
2729
+ * ```
2730
+ *
2731
+ * A refresh is loud regardless of `silent` when the computed has never
2732
+ * resolved — e.g. retrying after an error that left `didError` set on a first
2733
+ * load — or when the re-fetch is triggered by a dependency change, which
2734
+ * flows through the normal `recalc` path instead of here.
2735
+ *
2736
+ * If `fn` reads a getter the UI has never read, the collection read
2737
+ * initializes it — and that fetch IS the refresh: the computed is not re-run
2738
+ * (a second fetch would be a duplicate whose resolve the generation guard
2739
+ * drops). Getters already read (pending, resolved, or errored) are re-run as
2740
+ * usual.
2741
+ *
2742
+ * The returned value of `fn` is ignored; use `fn` to reference the getters.
1211
2743
  */
1212
- var ReactiveDate = class ReactiveDate extends Date {
1213
- constructor(...params) {
1214
- super(...params);
1215
- if (!initialized) this.#init();
1216
- this[proxyHandledSymbol] = true;
1217
- this[proxyDataSymbol] = {
1218
- target: this,
1219
- isArray: false,
1220
- shallow: true,
1221
- signals: /* @__PURE__ */ new Map()
1222
- };
2744
+ function $refresh(fn, options) {
2745
+ const silent = options?.silent === true;
2746
+ const oldRefreshSignals = context.refreshSignals;
2747
+ const oldPeek = context.suspendPeek;
2748
+ const oldInitialized = context.refreshInitialized;
2749
+ context.refreshSignals = [];
2750
+ context.suspendPeek = true;
2751
+ context.refreshInitialized = /* @__PURE__ */ new Set();
2752
+ let unique;
2753
+ let initialized;
2754
+ try {
2755
+ fn();
2756
+ unique = new Set(context.refreshSignals ?? []);
2757
+ initialized = context.refreshInitialized;
2758
+ } finally {
2759
+ context.refreshSignals = oldRefreshSignals;
2760
+ context.suspendPeek = oldPeek;
2761
+ context.refreshInitialized = oldInitialized;
1223
2762
  }
1224
- #init() {
1225
- initialized = true;
1226
- let reactivePrototype = ReactiveDate.prototype;
1227
- let datePrototype = Date.prototype;
1228
- const methods = Object.getOwnPropertyNames(datePrototype);
1229
- for (const method of methods) {
1230
- if (method.startsWith("get") || method.startsWith("to") || method === "valueOf") reactivePrototype[method] = function(...args) {
1231
- const data = this[proxyDataSymbol];
1232
- const result = datePrototype[method].apply(this, args);
1233
- trackProxySignal(data, "#time");
1234
- return result;
1235
- };
1236
- if (method.startsWith("set")) reactivePrototype[method] = function(...args) {
1237
- const data = this[proxyDataSymbol];
1238
- const result = datePrototype[method].apply(this, args);
1239
- propagateSignal(data, "#time");
1240
- return result;
1241
- };
2763
+ for (const computed of unique) {
2764
+ if (initialized.has(computed)) continue;
2765
+ computed.recalc = !silent;
2766
+ deactivateSources(computed);
2767
+ const oldActiveTarget = context.activeTarget;
2768
+ context.activeTarget = null;
2769
+ try {
2770
+ runComputed(computed);
2771
+ } finally {
2772
+ context.activeTarget = oldActiveTarget;
2773
+ }
2774
+ computed.recalc = false;
2775
+ clearSources(computed);
2776
+ if (!silent) {
2777
+ batchStart();
2778
+ propagateFromSignal(computed);
2779
+ batchEnd();
1242
2780
  }
1243
2781
  }
1244
- };
1245
-
2782
+ }
2783
+ //#endregion
2784
+ //#region src/watch/$stream.ts
2785
+ /**
2786
+ * Subscribes to an external source of events — server-sent events,
2787
+ * WebSockets, DOM events, or any custom `StreamSource` — and calls
2788
+ * `handler` for each event it pushes. Events are typically written into
2789
+ * reactive state, which keeps templates, computeds and effects updating
2790
+ * through the normal reactivity model:
2791
+ *
2792
+ * ```torp
2793
+ * let $state = $watch({ messages: [] as string[] });
2794
+ *
2795
+ * $stream(fromServer(`/sse/${$props.id}`), (e) => {
2796
+ * $state.messages.push(e.data);
2797
+ * });
2798
+ * ```
2799
+ *
2800
+ * The subscription is managed by the framework:
2801
+ *
2802
+ * - It starts when the component is mounted to the DOM (so `&ref`-bound
2803
+ * elements are available), and is unsubscribed when the component
2804
+ * unmounts or its region is cleared.
2805
+ * - Reactive state read *inside* the source is tracked: when it changes,
2806
+ * the source is unsubscribed and re-subscribed with fresh values (e.g.
2807
+ * re-opening a connection when a user id changes). A pending debounced
2808
+ * call is dropped on re-subscribe.
2809
+ * - The source is never invoked during a server render, so browser-only
2810
+ * APIs are safe to use.
2811
+ *
2812
+ * Errors are values like any other: a source that can fail should push an
2813
+ * error-shaped value and own its own reconnection (e.g. `EventSource`
2814
+ * reconnects automatically).
2815
+ *
2816
+ * @param source The stream source to subscribe to
2817
+ * @param handler Called for each event the source pushes
2818
+ * @param options Timing options. `debounce` delays each handler call until
2819
+ * the source has been quiet for that many milliseconds, resetting on
2820
+ * every event (only the last event in a burst is handled).
2821
+ */
2822
+ function $stream(source, handler, options) {
2823
+ const fn = () => {
2824
+ let timer;
2825
+ $run(() => {
2826
+ const unsub = source((value) => {
2827
+ if (options?.debounce) {
2828
+ clearTimeout(timer);
2829
+ timer = setTimeout(() => handler(value), options.debounce);
2830
+ } else handler(value);
2831
+ });
2832
+ return () => {
2833
+ unsub?.();
2834
+ clearTimeout(timer);
2835
+ };
2836
+ });
2837
+ };
2838
+ context.mountEffects.push({
2839
+ region: context.activeRegion,
2840
+ fn
2841
+ });
2842
+ }
1246
2843
  //#endregion
1247
- export { $batch, $cache, $mount, $peek, $run, $unwrap, $watch, ReactiveDate, clearLayoutSlot, fillLayoutSlot, hydrate, mount, addFragment as t_add_fragment, nodeAnchor as t_anchor, addAnimation as t_animate, applyProps as t_apply_props, setAttribute as t_attribute, nodeChild as t_child, buildClasses as t_class, setDynamicElement as t_dynamic, addEvent as t_event, formatText as t_fmt, getFragment as t_fragment, newListItem as t_list_item, nodeNext as t_next, popRegion as t_pop_region, pushRegion as t_push_region, newRegion as t_region, nodeRoot as t_root, runControlBranch as t_run_branch, runControl as t_run_control, runList as t_run_list, nodeSkip as t_skip, buildStyles as t_style };
2844
+ export { $async, $batch, $bind, $cache, $onmount, $peek, $pending, $refresh, $run, $stream, $unwrap, $watch, clearLayoutSlot, fillLayoutSlot, fromElement, fromServer, fromWebSocket, hydrate, mount, addElement as t_add_element, addFragment as t_add_fragment, nodeAnchor as t_anchor, addAnimation as t_animate, applyProps as t_apply_props, setAttribute as t_attribute, nodeChild as t_child, buildClasses as t_class, setDynamicElement as t_dynamic, addEvent as t_event, firstInsideNode as t_first_inside, formatText as t_fmt, getFragment as t_fragment, getElementFragment as t_fragment_el, newListItem as t_list_item, nodeNext as t_next, popRegion as t_pop_region, pushRegion as t_push_region, newRegion as t_region, rerunRegionEffects as t_rerun_region_effects, restoreHydration as t_restore_hydration, nodeRoot as t_root, nodeRootElement as t_root_el, runAwait as t_run_await, runControlBranch as t_run_branch, runControl as t_run_control, runList as t_run_list, runTry as t_run_try, saveHydration as t_save_hydration, nodeSkip as t_skip, buildStyles as t_style, unmount };
2845
+
1248
2846
  //# sourceMappingURL=index.mjs.map