@torpor/view 1.3.2 → 1.4.0

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 (60) hide show
  1. package/dist/{Effect-99HYQdzZ.d.mts → Effect-Bi_nt6cx.d.cts} +31 -3
  2. package/dist/Effect-Bi_nt6cx.d.cts.map +1 -0
  3. package/dist/{Effect-Bf8fz_zC.d.cts → Effect-Bi_nt6cx.d.mts} +31 -3
  4. package/dist/Effect-Bi_nt6cx.d.mts.map +1 -0
  5. package/dist/ListItemSpec-DFkYr2TE.d.cts +28 -0
  6. package/dist/ListItemSpec-DFkYr2TE.d.cts.map +1 -0
  7. package/dist/ListItemSpec-DFkYr2TE.d.mts +28 -0
  8. package/dist/ListItemSpec-DFkYr2TE.d.mts.map +1 -0
  9. package/dist/{AsyncOptions-BDtArmeL.d.mts → WatchOptions--xq-Gn4e.d.cts} +77 -4
  10. package/dist/WatchOptions--xq-Gn4e.d.cts.map +1 -0
  11. package/dist/{AsyncOptions-C_7mWR6F.d.cts → WatchOptions-DWF4EqB6.d.mts} +77 -4
  12. package/dist/WatchOptions-DWF4EqB6.d.mts.map +1 -0
  13. package/dist/compile.cjs +1316 -400
  14. package/dist/compile.d.cts +16 -12
  15. package/dist/compile.d.cts.map +1 -1
  16. package/dist/compile.d.mts +16 -12
  17. package/dist/compile.d.mts.map +1 -1
  18. package/dist/compile.mjs +1316 -400
  19. package/dist/compile.mjs.map +1 -1
  20. package/dist/dev.cjs +101 -51
  21. package/dist/dev.d.cts +33 -2
  22. package/dist/dev.d.cts.map +1 -1
  23. package/dist/dev.d.mts +33 -2
  24. package/dist/dev.d.mts.map +1 -1
  25. package/dist/dev.mjs +51 -2
  26. package/dist/dev.mjs.map +1 -1
  27. package/dist/{fromWebSocket-ERhd9KZR.mjs → fromWebSocket-B22DIys7.mjs} +11 -2
  28. package/dist/fromWebSocket-B22DIys7.mjs.map +1 -0
  29. package/dist/{fromWebSocket-Cdoghvmh.cjs → fromWebSocket-C56rkQpZ.cjs} +15 -0
  30. package/dist/index.cjs +621 -269
  31. package/dist/index.d.cts +36 -129
  32. package/dist/index.d.cts.map +1 -1
  33. package/dist/index.d.mts +36 -129
  34. package/dist/index.d.mts.map +1 -1
  35. package/dist/index.mjs +609 -258
  36. package/dist/index.mjs.map +1 -1
  37. package/dist/runtime.iife.js +1 -1
  38. package/dist/ssr.cjs +122 -22
  39. package/dist/ssr.d.cts +46 -12
  40. package/dist/ssr.d.cts.map +1 -1
  41. package/dist/ssr.d.mts +46 -12
  42. package/dist/ssr.d.mts.map +1 -1
  43. package/dist/ssr.mjs +121 -23
  44. package/dist/ssr.mjs.map +1 -1
  45. package/dist/titleWarning-BMjLAXpn.mjs +72 -0
  46. package/dist/titleWarning-BMjLAXpn.mjs.map +1 -0
  47. package/dist/titleWarning-DXp4fK7q.cjs +87 -0
  48. package/package.json +2 -1
  49. package/dist/AsyncOptions-BDtArmeL.d.mts.map +0 -1
  50. package/dist/AsyncOptions-C_7mWR6F.d.cts.map +0 -1
  51. package/dist/Cleanup-D0wvGW5d.d.cts +0 -9
  52. package/dist/Cleanup-D0wvGW5d.d.cts.map +0 -1
  53. package/dist/Cleanup-D0wvGW5d.d.mts +0 -9
  54. package/dist/Cleanup-D0wvGW5d.d.mts.map +0 -1
  55. package/dist/Effect-99HYQdzZ.d.mts.map +0 -1
  56. package/dist/Effect-Bf8fz_zC.d.cts.map +0 -1
  57. package/dist/devContext-BulTn3U5.cjs +0 -27
  58. package/dist/devContext-ZNsPyOgB.mjs +0 -24
  59. package/dist/devContext-ZNsPyOgB.mjs.map +0 -1
  60. package/dist/fromWebSocket-ERhd9KZR.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { t as devContext } from "./devContext-ZNsPyOgB.mjs";
2
- import { a as buildStyles, c as proxyDataSymbol, i as formatText, l as proxyKeysSymbol, n as fromServer, o as buildClasses, r as fromElement, s as $unwrap, t as fromWebSocket } from "./fromWebSocket-ERhd9KZR.mjs";
1
+ import { n as setDevSlotDepth, r as devContext } from "./titleWarning-BMjLAXpn.mjs";
2
+ import { a as buildStyles, c as proxyArrayContentSymbol, i as formatText, l as proxyDataSymbol, n as fromServer, o as buildClasses, r as fromElement, s as $unwrap, t as fromWebSocket, u as proxyKeysSymbol } from "./fromWebSocket-B22DIys7.mjs";
3
3
  //#region src/render/context.ts
4
4
  const CONTEXT_SYMBOL = Symbol.for("torp.Context");
5
5
  const context = globalThis[CONTEXT_SYMBOL] ??= {
@@ -7,7 +7,6 @@ const context = globalThis[CONTEXT_SYMBOL] ??= {
7
7
  previousEffect: null,
8
8
  extent: 0,
9
9
  batch: 0,
10
- batchOperation: 0,
11
10
  registerComputed: null,
12
11
  effectsToRun: [],
13
12
  firstSignalToUpdate: null,
@@ -23,98 +22,11 @@ const context = globalThis[CONTEXT_SYMBOL] ??= {
23
22
  mountEffects: [],
24
23
  stashedEvents: [],
25
24
  stashedAnimations: [],
25
+ runAnimations: null,
26
26
  hydrationNode: null,
27
27
  serverValues: null
28
28
  };
29
29
  //#endregion
30
- //#region src/render/addAnimation.ts
31
- function addAnimation(el, entry, exit) {
32
- context.stashedAnimations.push({
33
- region: context.activeRegion,
34
- el,
35
- in: entry,
36
- out: exit
37
- });
38
- }
39
- //#endregion
40
- //#region src/render/addEvent.ts
41
- function addEvent(el, type, listener) {
42
- if (listener !== void 0 && listener !== null) context.stashedEvents.push({
43
- el,
44
- type,
45
- listener
46
- });
47
- }
48
- //#endregion
49
- //#region src/render/isTextNode.ts
50
- function isTextNode(node) {
51
- return node.nodeType === 3;
52
- }
53
- const HYDRATION_BREAK_REGEX = /^\^(?:\d+)?$/;
54
- /**
55
- * Whether a comment node's data is a branch-break marker (`^`, or `^<index>`
56
- * when the server recorded the branch it rendered).
57
- */
58
- function isHydrationBreak(data) {
59
- return HYDRATION_BREAK_REGEX.test(data);
60
- }
61
- /**
62
- * The branch index encoded in a `^<index>` branch-break marker, or `undefined`
63
- * for a plain `^` marker (e.g. from `@for`, which has no branch index).
64
- */
65
- function hydrationBreakIndex(data) {
66
- if (!data.startsWith("^") || data.length === 1) return;
67
- const index = Number(data.slice(1));
68
- return Number.isNaN(index) ? void 0 : index;
69
- }
70
- //#endregion
71
- //#region src/render/isCommentNode.ts
72
- function isCommentNode(node) {
73
- return node.nodeType === 8;
74
- }
75
- //#endregion
76
- //#region src/render/nodeCheckHydrationBreak.ts
77
- /**
78
- * When hydrating, removes and skips hydration comments that are inserted at the
79
- * start of branches and used to split up text nodes that would otherwise be
80
- * joined in HTML.
81
- *
82
- * @param node The node to check and maybe skip.
83
- * @returns The next node.
84
- */
85
- function nodeCheckHydrationBreak(node) {
86
- if (node !== null && isCommentNode(node) && isHydrationBreak(node.data)) {
87
- let comment = node;
88
- node = node.nextSibling;
89
- comment.remove();
90
- }
91
- context.hydrationNode = node;
92
- return node;
93
- }
94
- //#endregion
95
- //#region src/render/nodeNext.ts
96
- /**
97
- * Gets the next sibling of a node.
98
- *
99
- * When hydrating, sets the hydration node.
100
- *
101
- * @param node The node.
102
- * @param text Whether we require a text node.
103
- */
104
- function nodeNext(node, text = false) {
105
- if (context.hydrationNode !== null) {
106
- if (text && isTextNode(node)) return node;
107
- let next = nodeCheckHydrationBreak(node.nextSibling);
108
- while (!text && next !== null && isTextNode(next) && next.textContent?.trim() === "") next = nodeCheckHydrationBreak(next.nextSibling);
109
- if (!text && next !== null && next.nodeName === "TBODY" && next.firstChild && isTextNode(node)) {
110
- next = next.firstChild;
111
- context.hydrationNode = next;
112
- }
113
- return next;
114
- }
115
- return node.nextSibling;
116
- }
117
- //#endregion
118
30
  //#region src/dev/devAssert.ts
119
31
  /**
120
32
  * Throws when `condition` is false — but only when dev mode is enabled (the
@@ -362,15 +274,30 @@ function resubscribeSuspendSources(effect) {
362
274
  context.activeTarget = oldActive;
363
275
  }
364
276
  /**
277
+ * How many times a single effect may run in one flush before it's treated as
278
+ * a cycle. Deliberately generous: the limit is per effect, so a large flush
279
+ * (hundreds of effects reacting to one change) is fine — only an effect that
280
+ * keeps re-queuing itself hits it.
281
+ */
282
+ const MAX_EFFECT_RUNS_PER_FLUSH = 100;
283
+ /**
365
284
  * Runs the effects that have been collected during the batch.
366
285
  */
367
286
  function triggerEffects() {
368
287
  let unhandledError = null;
288
+ let cycle = false;
369
289
  const queue = context.effectsToRun;
290
+ queue.sort((a, b) => a.seq - b.seq);
370
291
  for (let i = 0; i < queue.length; i++) {
371
292
  const effect = queue[i];
372
- context.batchOperation++;
373
293
  effect.queued = false;
294
+ if (effect.destroyed) continue;
295
+ const runs = (effect.flushRuns ?? 0) + 1;
296
+ effect.flushRuns = runs;
297
+ if (runs > MAX_EFFECT_RUNS_PER_FLUSH) {
298
+ cycle = true;
299
+ break;
300
+ }
374
301
  try {
375
302
  checkEffect(effect);
376
303
  } catch (err) {
@@ -386,7 +313,10 @@ function triggerEffects() {
386
313
  }
387
314
  }
388
315
  }
389
- for (let effect of queue) effect.queued = false;
316
+ for (let effect of queue) {
317
+ effect.queued = false;
318
+ effect.flushRuns = 0;
319
+ }
390
320
  context.effectsToRun = [];
391
321
  let signal = context.firstSignalToUpdate;
392
322
  context.firstSignalToUpdate = null;
@@ -396,6 +326,7 @@ function triggerEffects() {
396
326
  signal.nextSignalToUpdate = null;
397
327
  signal = nextSignal;
398
328
  }
329
+ if (cycle) throw new Error("Cycle detected");
399
330
  if (unhandledError !== null) throw unhandledError.error;
400
331
  }
401
332
  //#endregion
@@ -410,7 +341,6 @@ function batchEnd() {
410
341
  triggerEffects();
411
342
  } finally {
412
343
  context.batch = 0;
413
- context.batchOperation = 0;
414
344
  context.previousEffect = null;
415
345
  }
416
346
  }
@@ -452,6 +382,7 @@ function runEffect(effect) {
452
382
  }
453
383
  //#endregion
454
384
  //#region src/watch/$run.ts
385
+ let effectSeq = 0;
455
386
  /**
456
387
  * Runs and re-runs a function that depends on a watched object
457
388
  *
@@ -467,6 +398,7 @@ function $run(fn, name, options) {
467
398
  firstSource: null,
468
399
  nextEffect: null,
469
400
  extent: 0,
401
+ seq: ++effectSeq,
470
402
  queued: false,
471
403
  didError: false,
472
404
  didSuspend: false,
@@ -486,59 +418,6 @@ function $run(fn, name, options) {
486
418
  return effect;
487
419
  }
488
420
  //#endregion
489
- //#region src/watch/$peek.ts
490
- /**
491
- * Runs a function without tracking the reactive values it reads: `$watch`'d
492
- * state accessed inside `fn` does not become a dependency of the currently
493
- * running effect or computed. Useful for reading state inside an effect
494
- * without re-running it when that state changes.
495
- *
496
- * @param fn The function to run untracked.
497
- */
498
- function $peek(fn) {
499
- const oldActiveTarget = context.activeTarget;
500
- context.activeTarget = null;
501
- const result = fn();
502
- context.activeTarget = oldActiveTarget;
503
- return result;
504
- }
505
- //#endregion
506
- //#region src/watch/flushMountEffects.ts
507
- /**
508
- * Runs the collected `$onmount`/`onmount` callbacks — once, after the
509
- * component's markup has been added to the DOM (or, when hydrating, after
510
- * hydration is complete). Multiple callbacks run in the order they were
511
- * added.
512
- *
513
- * Each callback becomes an effect with `isMountEffect` set, so the keyed-list
514
- * reconciler's force-rerun path (`rerunRegionEffects`) skips it. Its body
515
- * also runs untracked: mount callbacks are once-only, so reactive reads
516
- * inside them do not subscribe. In dev builds a tracked pass warns when a
517
- * callback reads reactive state, since that is almost always a mistake — the
518
- * reactive part should be wrapped in `$run`.
519
- */
520
- function flushMountEffects() {
521
- if (context.mountEffects.length === 0) return;
522
- const activeRegion = context.activeRegion;
523
- for (let effect of context.mountEffects) {
524
- context.activeRegion = effect.region;
525
- $run(() => runMountCallback(effect.fn), void 0, { isMountEffect: true });
526
- }
527
- context.activeRegion = activeRegion;
528
- context.mountEffects.length = 0;
529
- }
530
- function runMountCallback(fn) {
531
- if (!devContext.enabled) return $peek(fn);
532
- const result = fn();
533
- const effect = context.activeTarget;
534
- if (effect !== null && effect.type === 2 && effect.firstSource !== null) {
535
- 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(() => ...); });");
536
- deactivateSources(effect);
537
- clearSources(effect);
538
- }
539
- return result;
540
- }
541
- //#endregion
542
421
  //#region src/render/animate.ts
543
422
  /**
544
423
  * Parses a transform function argument as a number, returning null for
@@ -693,13 +572,183 @@ async function animate(el, enter, keyframes, options) {
693
572
  await animation.finished;
694
573
  }
695
574
  //#endregion
575
+ //#region src/render/runAnimations.ts
576
+ /**
577
+ * Runs the animations stashed by `addAnimation` (`context.stashedAnimations`)
578
+ * when their element has been added to the DOM.
579
+ *
580
+ * Kept in its own module (imported only by `addAnimation`) rather than in
581
+ * `runMountSideEffects`: this way a component that never uses a
582
+ * `transition`/`transition-in`/`transition-out` attribute never imports
583
+ * `t_animate`, so this module — and `animate.ts` with it — is tree-shaken
584
+ * out of the bundle. `runMountSideEffects` reaches the runner through
585
+ * `context.runAnimations`, which stays null until `addAnimation` installs it.
586
+ */
587
+ function runAnimations() {
588
+ for (let animation of context.stashedAnimations) {
589
+ context.activeRegion = animation.region;
590
+ $run(function runMountSideEffectsAnimation() {
591
+ if (animation.in !== void 0) animate(animation.el, true, animation.in.keyframes, animation.in.options);
592
+ if (animation.out !== void 0) return () => {
593
+ animate(animation.el, false, animation.out.keyframes, animation.out.options);
594
+ };
595
+ });
596
+ }
597
+ context.stashedAnimations.length = 0;
598
+ }
599
+ //#endregion
600
+ //#region src/render/addAnimation.ts
601
+ function addAnimation(el, entry, exit) {
602
+ context.runAnimations ??= runAnimations;
603
+ context.stashedAnimations.push({
604
+ region: context.activeRegion,
605
+ el,
606
+ in: entry,
607
+ out: exit
608
+ });
609
+ }
610
+ //#endregion
611
+ //#region src/render/addEvent.ts
612
+ function addEvent(el, type, listener) {
613
+ if (listener !== void 0 && listener !== null) context.stashedEvents.push({
614
+ el,
615
+ type,
616
+ listener
617
+ });
618
+ }
619
+ //#endregion
620
+ //#region src/render/isTextNode.ts
621
+ function isTextNode(node) {
622
+ return node.nodeType === 3;
623
+ }
624
+ const HYDRATION_BREAK_REGEX = /^\^(?:\d+)?$/;
625
+ /**
626
+ * Whether a comment node's data is a branch-break marker (`^`, or `^<index>`
627
+ * when the server recorded the branch it rendered).
628
+ */
629
+ function isHydrationBreak(data) {
630
+ return HYDRATION_BREAK_REGEX.test(data);
631
+ }
632
+ /**
633
+ * The branch index encoded in a `^<index>` branch-break marker, or `undefined`
634
+ * for a plain `^` marker (e.g. from `@for`, which has no branch index).
635
+ */
636
+ function hydrationBreakIndex(data) {
637
+ if (!data.startsWith("^") || data.length === 1) return;
638
+ const index = Number(data.slice(1));
639
+ return Number.isNaN(index) ? void 0 : index;
640
+ }
641
+ //#endregion
642
+ //#region src/render/isCommentNode.ts
643
+ function isCommentNode(node) {
644
+ return node.nodeType === 8;
645
+ }
646
+ //#endregion
647
+ //#region src/render/nodeCheckHydrationBreak.ts
648
+ /**
649
+ * When hydrating, removes and skips hydration comments that are inserted at the
650
+ * start of branches and used to split up text nodes that would otherwise be
651
+ * joined in HTML.
652
+ *
653
+ * @param node The node to check and maybe skip.
654
+ * @returns The next node.
655
+ */
656
+ function nodeCheckHydrationBreak(node) {
657
+ if (node !== null && isCommentNode(node) && isHydrationBreak(node.data)) {
658
+ let comment = node;
659
+ node = node.nextSibling;
660
+ comment.remove();
661
+ }
662
+ context.hydrationNode = node;
663
+ return node;
664
+ }
665
+ //#endregion
666
+ //#region src/render/nodeNext.ts
667
+ /**
668
+ * Gets the next sibling of a node.
669
+ *
670
+ * When hydrating, sets the hydration node.
671
+ *
672
+ * @param node The node.
673
+ * @param text Whether we require a text node.
674
+ */
675
+ function nodeNext(node, text = false) {
676
+ if (context.hydrationNode !== null) {
677
+ if (text && isTextNode(node)) return node;
678
+ let next = nodeCheckHydrationBreak(node.nextSibling);
679
+ while (!text && next !== null && isTextNode(next) && next.textContent?.trim() === "") next = nodeCheckHydrationBreak(next.nextSibling);
680
+ if (!text && next !== null && next.nodeName === "TBODY" && next.firstChild && isTextNode(node)) {
681
+ next = next.firstChild;
682
+ context.hydrationNode = next;
683
+ }
684
+ return next;
685
+ }
686
+ return node.nextSibling;
687
+ }
688
+ //#endregion
689
+ //#region src/watch/$peek.ts
690
+ /**
691
+ * Runs a function without tracking the reactive values it reads: `$watch`'d
692
+ * state accessed inside `fn` does not become a dependency of the currently
693
+ * running effect or computed. Useful for reading state inside an effect
694
+ * without re-running it when that state changes.
695
+ *
696
+ * @param fn The function to run untracked.
697
+ */
698
+ function $peek(fn) {
699
+ const oldActiveTarget = context.activeTarget;
700
+ context.activeTarget = null;
701
+ try {
702
+ return fn();
703
+ } finally {
704
+ context.activeTarget = oldActiveTarget;
705
+ }
706
+ }
707
+ //#endregion
708
+ //#region src/watch/flushMountEffects.ts
709
+ /**
710
+ * Runs the collected `$onmount`/`onmount` callbacks — once, after the
711
+ * component's markup has been added to the DOM (or, when hydrating, after
712
+ * hydration is complete). Multiple callbacks run in the order they were
713
+ * added.
714
+ *
715
+ * Each callback becomes an effect with `isMountEffect` set, so the keyed-list
716
+ * reconciler's force-rerun path (`rerunRegionEffects`) skips it. Its body
717
+ * also runs untracked: mount callbacks are once-only, so reactive reads
718
+ * inside them do not subscribe. In dev builds a tracked pass warns when a
719
+ * callback reads reactive state, since that is almost always a mistake — the
720
+ * reactive part should be wrapped in `$run`.
721
+ */
722
+ function flushMountEffects() {
723
+ if (context.mountEffects.length === 0) return;
724
+ const activeRegion = context.activeRegion;
725
+ for (let effect of context.mountEffects) {
726
+ context.activeRegion = effect.region;
727
+ $run(() => runMountCallback(effect.fn), void 0, { isMountEffect: true });
728
+ }
729
+ context.activeRegion = activeRegion;
730
+ context.mountEffects.length = 0;
731
+ }
732
+ function runMountCallback(fn) {
733
+ if (!devContext.enabled) return $peek(fn);
734
+ const result = fn();
735
+ const effect = context.activeTarget;
736
+ if (effect !== null && effect.type === 2 && effect.firstSource !== null) {
737
+ 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(() => ...); });");
738
+ deactivateSources(effect);
739
+ clearSources(effect);
740
+ }
741
+ return result;
742
+ }
743
+ //#endregion
696
744
  //#region src/render/delegatedEvents.ts
697
745
  /**
698
746
  * Event delegation.
699
747
  *
700
748
  * For event types in `DELEGATED_EVENT_TYPES` (all natively bubbling), we
701
- * register a single listener on `document` per type and dispatch by walking
702
- * up from `event.target` to find the closest ancestor with a stashed handler.
749
+ * register a single listener on each element's `ownerDocument` per type and
750
+ * dispatch by walking up from the event target, running each ancestor's
751
+ * stashed handler in turn until one calls `stopPropagation()`.
703
752
  * This replaces per-element `addEventListener` for delegated types.
704
753
  *
705
754
  * Why: in the js-framework-bench row template, every `<tr>` clones two `<a>`
@@ -719,6 +768,22 @@ async function animate(el, enter, keyframes, options) {
719
768
  * Non-bubbling events (`focus`, `blur`, `scroll`, `load`, `error`, `abort`,
720
769
  * `unload`, `resize`, etc.) bypass delegation and use direct
721
770
  * `addEventListener` on the element, preserving native semantics.
771
+ *
772
+ * Limitations (inherent to delegating to the document, same trade-off as
773
+ * React and Solid):
774
+ *
775
+ * - A native `stopPropagation()` — third-party code, or a listener added in
776
+ * `$onmount` — stops the event before it reaches the document, so the
777
+ * delegated handlers won't run. Torpor handlers can still call
778
+ * `stopPropagation()` among themselves (that's what ends the walk below).
779
+ * - `stopPropagation()` in a delegated handler runs after the native event
780
+ * has finished bubbling, so it only affects other delegated handlers, not
781
+ * native listeners.
782
+ *
783
+ * Shadow DOM and multiple documents are supported: the listener lives on the
784
+ * element's `ownerDocument` (so components mounted into an iframe or popup
785
+ * document work), and the path comes from `composedPath()` (so the listener
786
+ * sees the real target inside a shadow root, not the retargeted host).
722
787
  */
723
788
  const DELEGATED_EVENT_TYPES = /* @__PURE__ */ new Set([
724
789
  "auxclick",
@@ -766,10 +831,12 @@ function isDelegatedEventType(type) {
766
831
  const DELEGATE_PREFIX = "torp.$$";
767
832
  const DELEGATE_REGISTERED = Symbol.for("torp.delegated.registered");
768
833
  function delegatedHandler(event) {
769
- let node = event.target;
770
834
  const stopAt = event.currentTarget;
771
835
  const key = DELEGATE_PREFIX + event.type;
772
- while (node != null && node !== stopAt) {
836
+ const path = event.composedPath();
837
+ for (let i = 0; i < path.length; i++) {
838
+ const node = path[i];
839
+ if (node === stopAt) break;
773
840
  const handler = node[key];
774
841
  if (handler !== void 0) {
775
842
  Object.defineProperty(event, "currentTarget", {
@@ -782,29 +849,28 @@ function delegatedHandler(event) {
782
849
  } finally {
783
850
  delete event.currentTarget;
784
851
  }
785
- return;
852
+ if (event.cancelBubble) return;
786
853
  }
787
- node = node.parentNode;
788
854
  }
789
855
  }
790
- function ensureDelegatedListener(type) {
791
- if (typeof document === "undefined") return;
792
- let registered = document[DELEGATE_REGISTERED];
856
+ function ensureDelegatedListener(doc, type) {
857
+ let registered = doc[DELEGATE_REGISTERED];
793
858
  if (!registered) {
794
859
  registered = /* @__PURE__ */ new Set();
795
- document[DELEGATE_REGISTERED] = registered;
860
+ doc[DELEGATE_REGISTERED] = registered;
796
861
  }
797
862
  if (registered.has(type)) return;
798
863
  registered.add(type);
799
- document.addEventListener(type, delegatedHandler);
864
+ doc.addEventListener(type, delegatedHandler);
800
865
  }
801
866
  /**
802
867
  * Attach a delegated event handler to an element.
803
868
  *
804
869
  * Stores the handler as a property on the element and ensures a single
805
- * document-level listener exists for the type. Idempotent for the
806
- * document-level listener: the first call for a given type registers it,
807
- * subsequent calls are a Set-has check.
870
+ * listener exists for the type on the element's own document (so components
871
+ * mounted into another document — an iframe or popup — get delegated events
872
+ * too). Idempotent for the document-level listener: the first call for a
873
+ * given type registers it, subsequent calls are a Set-has check.
808
874
  *
809
875
  * Passing `null` or `undefined` as the listener clears any previously-set
810
876
  * handler for that type on the element (mirroring `addEvent`'s existing
@@ -816,7 +882,9 @@ function attachDelegatedEvent(el, type, listener) {
816
882
  el[key] = void 0;
817
883
  return;
818
884
  }
819
- ensureDelegatedListener(type);
885
+ const doc = el.ownerDocument;
886
+ if (doc === null || typeof doc.addEventListener !== "function") return;
887
+ ensureDelegatedListener(doc, type);
820
888
  el[key] = listener;
821
889
  }
822
890
  const DIRECT_LISTENERS = "torp.$directListeners";
@@ -858,8 +926,19 @@ function copyEventListeners(from, to) {
858
926
  }
859
927
  //#endregion
860
928
  //#region src/render/isFragmentNode.ts
929
+ /**
930
+ * Whether the node is a detached template/document fragment — i.e. a tree
931
+ * we're still building, where mount-time side effects (`$onmount`, event
932
+ * hookup, animations) must wait until the outer tree is inserted.
933
+ *
934
+ * A `ShadowRoot` is also `nodeType 11`, but it's a live tree root (its host
935
+ * may already be connected), so side effects must run when content is added
936
+ * to it. `host` distinguishes a shadow root without relying on
937
+ * `instanceof ShadowRoot`, which fails across realms (e.g. an iframe's
938
+ * shadow root).
939
+ */
861
940
  function isFragmentNode(node) {
862
- return node.nodeType === 11;
941
+ return node.nodeType === 11 && node.host === void 0;
863
942
  }
864
943
  //#endregion
865
944
  //#region src/render/runMountSideEffects.ts
@@ -885,16 +964,7 @@ function runMountSideEffects(parent, activeRegion, hydrationNode) {
885
964
  }
886
965
  context.stashedEvents.length = 0;
887
966
  }
888
- for (let animation of context.stashedAnimations) {
889
- context.activeRegion = animation.region;
890
- $run(function runMountSideEffectsAnimation() {
891
- if (animation.in !== void 0) animate(animation.el, true, animation.in.keyframes, animation.in.options);
892
- if (animation.out !== void 0) return () => {
893
- animate(animation.el, false, animation.out.keyframes, animation.out.options);
894
- };
895
- });
896
- }
897
- context.stashedAnimations.length = 0;
967
+ if (context.stashedAnimations.length > 0) context.runAnimations?.();
898
968
  context.activeRegion = activeRegion;
899
969
  }
900
970
  //#endregion
@@ -946,6 +1016,47 @@ function addFragment(fragment, parent, before, endNode, startNode) {
946
1016
  if (hydrationNode !== null && endNode !== void 0) nodeNext(endNode);
947
1017
  }
948
1018
  //#endregion
1019
+ //#region src/render/urlAttributes.ts
1020
+ /**
1021
+ * A function that rewrites the URLs in `href`, `src` and `action` attributes
1022
+ * as the client sets them, registered by a host framework with
1023
+ * `setUrlRewriter` (e.g. `@torpor/build` adds a site's base path, so markup
1024
+ * can be written base-free). Undefined when no rewriting is needed.
1025
+ */
1026
+ let rewriteUrl;
1027
+ /**
1028
+ * Registers a function that rewrites the URLs in `href`, `src` and `action`
1029
+ * attributes the client sets -- from dynamic attributes, spread props and
1030
+ * client-rendered markup -- or clears it with `undefined`. Fragments already
1031
+ * cached are not rewritten again, so register it before the first render.
1032
+ */
1033
+ function setUrlRewriter(rewriter) {
1034
+ rewriteUrl = rewriter;
1035
+ }
1036
+ const URL_ATTRIBUTES = /* @__PURE__ */ new Set([
1037
+ "href",
1038
+ "src",
1039
+ "action"
1040
+ ]);
1041
+ /** An attribute value, with its URL rewritten if it's a URL attribute. */
1042
+ function urlAttributeValue(name, value) {
1043
+ if (rewriteUrl === void 0 || typeof value !== "string") return value;
1044
+ return URL_ATTRIBUTES.has(name.toLowerCase()) ? rewriteUrl(value) : value;
1045
+ }
1046
+ /** Rewrites the URL attributes of the elements in a freshly parsed template. */
1047
+ function rewriteUrlsIn(root) {
1048
+ if (rewriteUrl === void 0) return;
1049
+ const elements = [...root.querySelectorAll("[href], [src], [action]")];
1050
+ if (root instanceof Element && root.matches("[href], [src], [action]")) elements.push(root);
1051
+ for (const el of elements) for (const name of URL_ATTRIBUTES) {
1052
+ const value = el.getAttribute(name);
1053
+ if (value !== null) {
1054
+ const rewritten = rewriteUrl(value);
1055
+ if (rewritten !== value) el.setAttribute(name, rewritten);
1056
+ }
1057
+ }
1058
+ }
1059
+ //#endregion
949
1060
  //#region src/render/applyProps.ts
950
1061
  function applyProps(el, props, propNamesUsed) {
951
1062
  if (props !== void 0) {
@@ -955,7 +1066,7 @@ function applyProps(el, props, propNamesUsed) {
955
1066
  if (isDelegatedEventType(eventName)) attachDelegatedEvent(el, eventName, value);
956
1067
  else el.addEventListener(eventName, value);
957
1068
  } else $run(function setAttribute() {
958
- el.setAttribute(name, value);
1069
+ el.setAttribute(name, urlAttributeValue(name, value));
959
1070
  });
960
1071
  }
961
1072
  }
@@ -1031,6 +1142,7 @@ function releaseRegion(region) {
1031
1142
  region.animations = null;
1032
1143
  region.errorBoundary = void 0;
1033
1144
  for (const effect of region.effects) {
1145
+ effect.destroyed = true;
1034
1146
  if (typeof effect.cleanup === "function") {
1035
1147
  effect.cleanup();
1036
1148
  effect.cleanup = void 0;
@@ -1127,7 +1239,9 @@ function fillLayoutSlot(component, slot, parent, anchor, $props, $context) {
1127
1239
  region.depth = refillDepth;
1128
1240
  refillDepths.delete(parent);
1129
1241
  }
1242
+ const previousSlotDepth = devContext.enabled ? setDevSlotDepth(region.depth) : -1;
1130
1243
  component(parent, anchor, $props, $context, { _: slot });
1244
+ if (devContext.enabled) setDevSlotDepth(previousSlotDepth);
1131
1245
  popRegion(oldRegion);
1132
1246
  return region;
1133
1247
  }
@@ -1183,8 +1297,9 @@ function getFragment(document, array, index, html, ns) {
1183
1297
  template.innerHTML = html;
1184
1298
  array[index] = template.content;
1185
1299
  }
1300
+ rewriteUrlsIn(array[index]);
1186
1301
  }
1187
- return array[index].cloneNode(true);
1302
+ return document.importNode(array[index], true);
1188
1303
  }
1189
1304
  //#endregion
1190
1305
  //#region src/render/getElementFragment.ts
@@ -1223,8 +1338,9 @@ function getElementFragment(document, array, index, html, ns) {
1223
1338
  template.innerHTML = html;
1224
1339
  array[index] = template.content.firstElementChild;
1225
1340
  }
1341
+ rewriteUrlsIn(array[index]);
1226
1342
  }
1227
- return array[index].cloneNode(true);
1343
+ return document.importNode(array[index], true);
1228
1344
  }
1229
1345
  //#endregion
1230
1346
  //#region src/render/isServerComponent.ts
@@ -1287,8 +1403,12 @@ function containedTrees(parent) {
1287
1403
  * @param parent The parent node
1288
1404
  * @param component The component to mount
1289
1405
  * @param props An object containing component props
1406
+ * @param slots Slot render functions for the component
1407
+ * @param rootContext The root `$context`, which the component and all of its
1408
+ * descendants inherit (e.g. app-wide state that a framework provides to
1409
+ * every page)
1290
1410
  */
1291
- function hydrate(parent, component, props, slots) {
1411
+ function hydrate(parent, component, props, slots, rootContext) {
1292
1412
  if (isServerComponent(component)) throw new Error("The component was compiled for SSR (it renders to an HTML string) and cannot be hydrated in the browser. Import the client build instead, e.g. with the '?client' import query");
1293
1413
  const saved = context.rootRegion !== null ? {
1294
1414
  activeRegion: context.activeRegion,
@@ -1301,7 +1421,7 @@ function hydrate(parent, component, props, slots) {
1301
1421
  context.rootRegion = root;
1302
1422
  context.previousRegion = root;
1303
1423
  pushRegion(root);
1304
- component(parent, null, props, void 0, slots);
1424
+ component(parent, null, props, rootContext, slots);
1305
1425
  context.hydrationNode = null;
1306
1426
  flushMountEffects();
1307
1427
  if (saved === null) {
@@ -1334,8 +1454,12 @@ function hydrate(parent, component, props, slots) {
1334
1454
  * child elements
1335
1455
  * @param component The component to mount
1336
1456
  * @param props An object containing component props
1457
+ * @param slots Slot render functions for the component
1458
+ * @param rootContext The root `$context`, which the component and all of its
1459
+ * descendants inherit (e.g. app-wide state that a framework provides to
1460
+ * every page)
1337
1461
  */
1338
- function mount(parent, component, props, slots) {
1462
+ function mount(parent, component, props, slots, rootContext) {
1339
1463
  if (isServerComponent(component)) throw new Error("The component was compiled for SSR (it renders to an HTML string) and cannot be mounted in the browser. Import the client build instead, e.g. with the '?client' import query");
1340
1464
  if (parent.childElementCount > 0) throw new Error("The parent node must have no child elements");
1341
1465
  while (parent.firstChild !== null) parent.firstChild.remove();
@@ -1348,13 +1472,28 @@ function mount(parent, component, props, slots) {
1348
1472
  context.rootRegion = root;
1349
1473
  context.previousRegion = root;
1350
1474
  pushRegion(root);
1351
- component(parent, null, props, void 0, slots);
1352
- if (saved !== null) {
1353
- context.rootRegion = saved.rootRegion;
1354
- context.previousRegion = saved.previousRegion;
1355
- context.activeRegion = saved.activeRegion;
1475
+ let mounted = false;
1476
+ try {
1477
+ component(parent, null, props, rootContext, slots);
1478
+ mounted = true;
1479
+ } finally {
1480
+ if (mounted) {
1481
+ if (saved !== null) {
1482
+ context.rootRegion = saved.rootRegion;
1483
+ context.previousRegion = saved.previousRegion;
1484
+ context.activeRegion = saved.activeRegion;
1485
+ }
1486
+ } else {
1487
+ unregisterRegionTree(parent);
1488
+ try {
1489
+ clearRegion(root);
1490
+ } catch {}
1491
+ context.rootRegion = saved !== null ? saved.rootRegion : null;
1492
+ context.previousRegion = saved !== null ? saved.previousRegion : null;
1493
+ context.activeRegion = saved !== null ? saved.activeRegion : null;
1494
+ }
1356
1495
  }
1357
- registerRegionTree(parent, root);
1496
+ if (mounted) registerRegionTree(parent, root);
1358
1497
  }
1359
1498
  //#endregion
1360
1499
  //#region src/render/unmount.ts
@@ -1368,6 +1507,10 @@ function mount(parent, component, props, slots) {
1368
1507
  * embed is disposed and the host's render context is left untouched. Any
1369
1508
  * embeds living inside a root container are disposed along with it.
1370
1509
  *
1510
+ * When no tree was mounted into `parent`, this is a no-op apart from
1511
+ * disposing any embeds living inside it and removing `parent`'s own child
1512
+ * nodes — it never touches the running app's root context.
1513
+ *
1371
1514
  * Call this before `mount`ing a fresh component tree into the same container
1372
1515
  * (e.g. when client-side navigating to a route whose layout chain differs
1373
1516
  * from the previous one). `mount` refuses to mount into a non-empty parent
@@ -1381,17 +1524,17 @@ function unmount(parent) {
1381
1524
  clearRegion(nestedTree);
1382
1525
  unregisterRegionTree(nestedParent);
1383
1526
  }
1384
- if (owned !== void 0 && owned !== context.rootRegion) {
1385
- clearRegion(owned);
1386
- unregisterRegionTree(parent);
1387
- } else {
1388
- if (context.rootRegion !== null) {
1389
- clearRegion(context.rootRegion);
1527
+ if (owned !== void 0) {
1528
+ if (owned !== context.rootRegion) {
1529
+ clearRegion(owned);
1530
+ unregisterRegionTree(parent);
1531
+ } else {
1532
+ clearRegion(owned);
1390
1533
  context.rootRegion = null;
1391
1534
  context.previousRegion = null;
1392
1535
  context.activeRegion = null;
1536
+ unregisterRegionTree(parent);
1393
1537
  }
1394
- if (owned !== void 0) unregisterRegionTree(parent);
1395
1538
  }
1396
1539
  while (parent.firstChild !== null) parent.firstChild.remove();
1397
1540
  }
@@ -1855,50 +1998,23 @@ function clearServerBranch(region, removedFirst, anchor) {
1855
1998
  }
1856
1999
  }
1857
2000
  //#endregion
1858
- //#region src/render/checkListKeys.ts
1859
- const warnedByRegion = /* @__PURE__ */ new WeakMap();
2001
+ //#region src/watch/isWrappable.ts
1860
2002
  /**
1861
- * DEV-ONLY: warns when a keyed `@for` list contains duplicate `@key` values.
2003
+ * Whether `$watch`/`deepWrap` can proxy this value.
1862
2004
  *
1863
- * `runListItems` matches old and new rows by key (first match wins), so
1864
- * duplicate keys make updates and removals hit the wrong rows, desyncing the
1865
- * DOM from the data. Called from `runList` only when `devContext.enabled`, so
1866
- * it never runs in a production build.
1867
- *
1868
- * `undefined`/`null` keys are the "unkeyed" case (rows are matched
1869
- * positionally) and are ignored.
1870
- *
1871
- * @param region The `@for` list's region, used to dedupe warnings per list.
1872
- * @param specs The new row specs, in order.
2005
+ * Only plain objects, plain arrays, and exact Date/Map/Set/URL/
2006
+ * URLSearchParams instances are deep-watched. Everything else -- class
2007
+ * instances, array/collection subclasses, RegExp, typed arrays, promises, DOM
2008
+ * nodes, weak collections, and any frozen/non-extensible object -- is treated
2009
+ * as an opaque value: it is returned unchanged, and only replacing the
2010
+ * property that holds it is reactive.
1873
2011
  */
1874
- function checkListKeys(region, specs) {
1875
- let seen;
1876
- for (let i = 0; i < specs.length; i++) {
1877
- const key = specs[i].key;
1878
- if (key === void 0 || key === null) continue;
1879
- if (seen === void 0) seen = /* @__PURE__ */ new Set();
1880
- if (!seen.has(key)) {
1881
- seen.add(key);
1882
- continue;
1883
- }
1884
- let warned = warnedByRegion.get(region);
1885
- if (warned === void 0) {
1886
- warned = /* @__PURE__ */ new Set();
1887
- warnedByRegion.set(region, warned);
1888
- }
1889
- if (!warned.has(key)) {
1890
- warned.add(key);
1891
- console.warn(`[torpor] Duplicate @key value ${formatKey(key)} in a keyed @for list. Keys must be unique, or updates and removals will affect the wrong rows.`);
1892
- }
1893
- }
1894
- }
1895
- function formatKey(key) {
1896
- try {
1897
- const json = JSON.stringify(key);
1898
- return json === void 0 ? String(key) : json;
1899
- } catch {
1900
- return String(key);
1901
- }
2012
+ function isWrappable(value) {
2013
+ if (value === null || typeof value !== "object") return false;
2014
+ if (!Object.isExtensible(value)) return false;
2015
+ const proto = Object.getPrototypeOf(value);
2016
+ if (proto === Date.prototype || proto === Map.prototype || proto === Set.prototype || typeof URL !== "undefined" && proto === URL.prototype || typeof URLSearchParams !== "undefined" && proto === URLSearchParams.prototype) return true;
2017
+ return proto === Object.prototype || proto === null || proto === Array.prototype;
1902
2018
  }
1903
2019
  //#endregion
1904
2020
  //#region src/watch/propagateSignal.ts
@@ -1994,29 +2110,49 @@ var AwaitSuspend = class extends Error {
1994
2110
  //#endregion
1995
2111
  //#region src/watch/deepWrap.ts
1996
2112
  /**
1997
- * Wraps a value with `$watch` if it is a plain object (or Date/Map/Set) that
1998
- * is not already watched and is not a promise. Returns the value unchanged
1999
- * otherwise.
2113
+ * Wraps a value with `$watch` if it is a plain object, plain array, or exact
2114
+ * Date/Map/Set instance that is not already watched. Returns the value
2115
+ * unchanged otherwise (class instances, subclasses, RegExp, typed arrays,
2116
+ * frozen objects, promises, DOM nodes, ... stay opaque).
2000
2117
  *
2001
2118
  * Used by the `get` trap (wrap values on read) and the `set` trap (wrap
2002
2119
  * values on write), so a value stored in watched state is reactive whether
2003
2120
  * it's been read yet or not.
2004
2121
  */
2005
2122
  const proxyCache = /* @__PURE__ */ new WeakMap();
2123
+ const wrappedProxies = /* @__PURE__ */ new WeakSet();
2124
+ /**
2125
+ * Whether `value` is a proxy created by `deepWrap` — checked without going
2126
+ * through the proxy's `get` trap.
2127
+ */
2128
+ function isWrappedProxy(value) {
2129
+ return value !== null && typeof value === "object" && wrappedProxies.has(value);
2130
+ }
2006
2131
  function deepWrap(value) {
2007
2132
  if (value === void 0 || value === null || typeof value !== "object") return value;
2133
+ if (wrappedProxies.has(value)) return value;
2008
2134
  if (value[proxyDataSymbol] !== void 0) return proxyCache.get(value) ?? value;
2135
+ if (!isWrappable(value)) return value;
2009
2136
  if (value.then !== void 0) return value;
2010
- if (value.nodeType !== void 0) return value;
2011
2137
  const cached = proxyCache.get(value);
2012
2138
  if (cached !== void 0) return cached;
2013
2139
  const proxy = $watch(value);
2014
2140
  proxyCache.set(value, proxy);
2141
+ wrappedProxies.add(proxy);
2015
2142
  return proxy;
2016
2143
  }
2017
2144
  //#endregion
2018
2145
  //#region src/watch/trackProxySignal.ts
2019
2146
  function trackProxySignal(data, key) {
2147
+ trackSignal(ensureProxySignal(data, key));
2148
+ }
2149
+ /**
2150
+ * Creates or gets the signal for a proxy key, without subscribing the active
2151
+ * effect to it. Used where a signal must exist for later reads (e.g. the
2152
+ * array iterator creating per-index signals) but the current reader
2153
+ * shouldn't re-run when that key changes.
2154
+ */
2155
+ function ensureProxySignal(data, key) {
2020
2156
  let signal = data.signals.get(key);
2021
2157
  if (signal === void 0) {
2022
2158
  signal = {
@@ -2026,7 +2162,115 @@ function trackProxySignal(data, key) {
2026
2162
  };
2027
2163
  data.signals.set(key, signal);
2028
2164
  }
2029
- trackSignal(signal);
2165
+ return signal;
2166
+ }
2167
+ //#endregion
2168
+ //#region src/watch/urlHandlers.ts
2169
+ const URL_KEY = Symbol("torp.url");
2170
+ const URL_PARAMS_KEY = Symbol("torp.urlParams");
2171
+ const URL_PROPERTIES = /* @__PURE__ */ new Set([
2172
+ "href",
2173
+ "origin",
2174
+ "protocol",
2175
+ "username",
2176
+ "password",
2177
+ "host",
2178
+ "hostname",
2179
+ "port",
2180
+ "pathname",
2181
+ "search",
2182
+ "searchParams",
2183
+ "hash"
2184
+ ]);
2185
+ const URL_METHODS = /* @__PURE__ */ new Set(["toString", "toJSON"]);
2186
+ const URL_MEMBERS = /* @__PURE__ */ new Set([...URL_PROPERTIES, ...URL_METHODS]);
2187
+ const URL_PARAMS_METHODS = /* @__PURE__ */ new Set([
2188
+ "append",
2189
+ "delete",
2190
+ "get",
2191
+ "getAll",
2192
+ "has",
2193
+ "set",
2194
+ "sort",
2195
+ "entries",
2196
+ "forEach",
2197
+ "keys",
2198
+ "values",
2199
+ "toString"
2200
+ ]);
2201
+ const URL_PARAMS_MUTATORS = /* @__PURE__ */ new Set([
2202
+ "append",
2203
+ "delete",
2204
+ "set",
2205
+ "sort"
2206
+ ]);
2207
+ function urlGet(data, target, key, wrap) {
2208
+ trackProxySignal(data, URL_KEY);
2209
+ if (key === "searchParams") {
2210
+ const params = target.searchParams;
2211
+ if (data.shallow === true) return params;
2212
+ const proxy = wrap(params);
2213
+ const paramsData = params[proxyDataSymbol];
2214
+ if (paramsData !== void 0) {
2215
+ paramsData.linkedUrlData = data;
2216
+ data.urlParamsData = paramsData;
2217
+ }
2218
+ return proxy;
2219
+ }
2220
+ if (URL_METHODS.has(key)) return function(...args) {
2221
+ return target[key](...args);
2222
+ };
2223
+ return target[key];
2224
+ }
2225
+ function urlSet(data, target, key, value) {
2226
+ const before = target.href;
2227
+ const descriptor = typeof key === "string" ? Object.getOwnPropertyDescriptor(URL.prototype, key) : void 0;
2228
+ if (descriptor?.set !== void 0) descriptor.set.call(target, value);
2229
+ else if (!Reflect.set(target, key, value, target)) return false;
2230
+ if (target.href !== before) {
2231
+ batchStart();
2232
+ try {
2233
+ propagateSignal(data, URL_KEY);
2234
+ if (data.urlParamsData !== void 0) propagateSignal(data.urlParamsData, URL_PARAMS_KEY);
2235
+ } finally {
2236
+ batchEnd();
2237
+ }
2238
+ }
2239
+ return true;
2240
+ }
2241
+ function trackUrlParams(data) {
2242
+ trackProxySignal(data, URL_PARAMS_KEY);
2243
+ if (data.linkedUrlData !== void 0) trackProxySignal(data.linkedUrlData, URL_KEY);
2244
+ }
2245
+ function propagateUrlParams(data) {
2246
+ batchStart();
2247
+ try {
2248
+ propagateSignal(data, URL_PARAMS_KEY);
2249
+ if (data.linkedUrlData !== void 0) propagateSignal(data.linkedUrlData, URL_KEY);
2250
+ } finally {
2251
+ batchEnd();
2252
+ }
2253
+ }
2254
+ function urlParamsGet(data, target, key) {
2255
+ if (key === "size") {
2256
+ trackUrlParams(data);
2257
+ return target.size;
2258
+ }
2259
+ if (key === Symbol.iterator) {
2260
+ trackUrlParams(data);
2261
+ return target[Symbol.iterator].bind(target);
2262
+ }
2263
+ return function(...args) {
2264
+ const method = key;
2265
+ if (URL_PARAMS_MUTATORS.has(method)) {
2266
+ const before = target.toString();
2267
+ const result = target[method](...args);
2268
+ if (target.toString() !== before) propagateUrlParams(data);
2269
+ return result;
2270
+ }
2271
+ trackUrlParams(data);
2272
+ return target[method](...args);
2273
+ };
2030
2274
  }
2031
2275
  //#endregion
2032
2276
  //#region src/watch/proxyGet.ts
@@ -2079,6 +2323,8 @@ function proxyGet(target, key, receiver) {
2079
2323
  let data = target[proxyDataSymbol];
2080
2324
  if (key === proxyDataSymbol) return data;
2081
2325
  if ((data.isDate || data.isMap || data.isSet) && !Object.prototype.hasOwnProperty.call(target, key)) return collectionGet(data, target, key, receiver);
2326
+ if (data.isUrl && typeof key === "string" && URL_MEMBERS.has(key) && !Object.prototype.hasOwnProperty.call(target, key)) return urlGet(data, target, key, deepWrap);
2327
+ if (data.isUrlParams && (key === "size" || key === Symbol.iterator || typeof key === "string" && URL_PARAMS_METHODS.has(key)) && !Object.prototype.hasOwnProperty.call(target, key)) return urlParamsGet(data, target, key);
2082
2328
  let signal = data.signals.get(key);
2083
2329
  if (signal === void 0) {
2084
2330
  const propDescriptor = Object.getOwnPropertyDescriptor(target, key);
@@ -2142,8 +2388,7 @@ function proxyGet(target, key, receiver) {
2142
2388
  }
2143
2389
  const arrayWrapper = {
2144
2390
  [Symbol.iterator]: function(data, target, _key) {
2145
- trackProxySignal(data, "length");
2146
- context.activeTarget = null;
2391
+ trackArrayReads(data);
2147
2392
  return function arrayIterator() {
2148
2393
  let index = 0;
2149
2394
  return {
@@ -2160,7 +2405,7 @@ const arrayWrapper = {
2160
2405
  target[index] = value;
2161
2406
  }
2162
2407
  }
2163
- trackProxySignal(data, String(index));
2408
+ ensureProxySignal(data, String(index));
2164
2409
  index++;
2165
2410
  return {
2166
2411
  value,
@@ -2187,29 +2432,112 @@ const arrayWrapper = {
2187
2432
  toReversed: readHandle,
2188
2433
  toSorted: readHandle,
2189
2434
  toSpliced: readHandle,
2190
- indexOf: readHandle,
2191
- lastIndexOf: readHandle,
2192
- includes: readHandle,
2435
+ indexOf: searchHandle,
2436
+ lastIndexOf: searchHandle,
2437
+ includes: searchHandle,
2193
2438
  find: readHandle,
2194
2439
  findIndex: readHandle,
2195
2440
  some: readHandle,
2196
2441
  every: readHandle,
2197
- join: readHandle,
2442
+ join: joinHandle,
2198
2443
  forEach: readHandle,
2199
2444
  reduce: readHandle,
2200
2445
  reduceRight: readHandle,
2201
2446
  flat: readHandle,
2202
2447
  flatMap: readHandle,
2203
- at: readHandle
2448
+ at: atHandle
2204
2449
  };
2450
+ /**
2451
+ * Wraps (and writes back) every object element of a raw array, so callback
2452
+ * parameters and returned values are reactive proxies — the same lazy wrapping
2453
+ * the iterator does. Skipped entirely once every element is wrapped (the
2454
+ * `elementsWrapped` flag, reset by mutations that can insert raw elements);
2455
+ * `isWrappedProxy` skips elements that are already proxies without reading
2456
+ * through their `get` trap. Shallow arrays are left unwrapped to match the
2457
+ * `get` trap's deep-only behaviour.
2458
+ */
2459
+ function wrapArrayElements(data, target) {
2460
+ if (data.shallow === true || data.elementsWrapped === true) return;
2461
+ const length = target.length;
2462
+ for (let i = 0; i < length; i++) {
2463
+ const value = target[i];
2464
+ if (value !== null && typeof value === "object" && !isWrappedProxy(value)) {
2465
+ const wrapped = deepWrap(value);
2466
+ if (wrapped !== value) target[i] = wrapped;
2467
+ }
2468
+ }
2469
+ data.elementsWrapped = true;
2470
+ }
2471
+ /**
2472
+ * Subscribes the active effect to everything a read of the array's contents
2473
+ * depends on: `length` (rows added/removed) and the content signal (an
2474
+ * element replaced at an existing index, which keeps the length). When no
2475
+ * effect is active both are cheap no-ops.
2476
+ */
2477
+ function trackArrayReads(data) {
2478
+ trackProxySignal(data, "length");
2479
+ trackProxySignal(data, proxyArrayContentSymbol);
2480
+ }
2205
2481
  function readHandle(data, target, key) {
2206
2482
  return function(...args) {
2207
- trackProxySignal(data, "length");
2483
+ trackArrayReads(data);
2484
+ wrapArrayElements(data, target);
2485
+ return target[key].apply(target, args);
2486
+ };
2487
+ }
2488
+ function joinHandle(data, target, key) {
2489
+ return function(...args) {
2490
+ trackArrayReads(data);
2208
2491
  return target[key].apply(target, args);
2209
2492
  };
2210
2493
  }
2494
+ /**
2495
+ * `indexOf` / `lastIndexOf` / `includes`.
2496
+ *
2497
+ * Elements are wrapped lazily, so the array can hold raw objects or their
2498
+ * proxies — and a raw search value can miss the proxy that replaced it (or a
2499
+ * proxy can miss the raw object it wraps). On a miss with an object argument,
2500
+ * retry with the unwrapped and wrapped forms.
2501
+ */
2502
+ function searchHandle(data, target, key) {
2503
+ return function(...args) {
2504
+ trackArrayReads(data);
2505
+ const search = args[0];
2506
+ const func = target[key];
2507
+ const found = func.apply(target, args);
2508
+ if ((found === -1 || found === false) && search !== null && typeof search === "object") for (const candidate of [$unwrap(search), deepWrap(search)]) {
2509
+ if (candidate === search) continue;
2510
+ const result = func.apply(target, [candidate, ...args.slice(1)]);
2511
+ if (result !== -1 && result !== false) return result;
2512
+ }
2513
+ return found;
2514
+ };
2515
+ }
2516
+ /**
2517
+ * `at`: like a direct `arr[i]` read, but it wraps just the element it returns
2518
+ * (a whole-array wrap would turn the O(1) lookup into O(n)).
2519
+ */
2520
+ function atHandle(data, target, _key) {
2521
+ return function(index) {
2522
+ trackArrayReads(data);
2523
+ const length = target.length;
2524
+ let i = Math.trunc(Number(index ?? 0)) || 0;
2525
+ if (i < 0) i += length;
2526
+ if (i < 0 || i >= length) return void 0;
2527
+ let value = target[i];
2528
+ if (data.shallow !== true) {
2529
+ const wrapped = deepWrap(value);
2530
+ if (wrapped !== value) {
2531
+ value = wrapped;
2532
+ target[i] = value;
2533
+ }
2534
+ }
2535
+ return value;
2536
+ };
2537
+ }
2211
2538
  function arrayHandle(data, target, key) {
2212
2539
  return function(...args) {
2540
+ if (key === "push" || key === "unshift" || key === "splice") data.elementsWrapped = false;
2213
2541
  const result = target[key].apply(target, args);
2214
2542
  propagateSignal(data, "length");
2215
2543
  if (key !== "sort" && key !== "reverse") propagateSignal(data, proxyKeysSymbol);
@@ -2314,7 +2642,7 @@ const mapWrapper = {
2314
2642
  return function(key) {
2315
2643
  key = $unwrap(key);
2316
2644
  const result = target.delete(key);
2317
- propagateCollection(data, collectionKey(key));
2645
+ if (result) propagateCollection(data, collectionKey(key));
2318
2646
  return result;
2319
2647
  };
2320
2648
  },
@@ -2388,7 +2716,7 @@ const setWrapper = {
2388
2716
  return function(value) {
2389
2717
  value = $unwrap(value);
2390
2718
  const result = target.delete(value);
2391
- propagateCollection(data, collectionKey(value));
2719
+ if (result) propagateCollection(data, collectionKey(value));
2392
2720
  return result;
2393
2721
  };
2394
2722
  },
@@ -2441,16 +2769,21 @@ function setEntries(data, target) {
2441
2769
  //#region src/watch/proxySet.ts
2442
2770
  function proxySet(target, key, value, receiver) {
2443
2771
  const oldValue = target[key];
2444
- if (value !== oldValue) {
2445
- if (context.batchOperation > 100) throw new Error("Cycle detected");
2772
+ if (!Object.is(value, oldValue)) {
2446
2773
  let data = target[proxyDataSymbol];
2447
2774
  devContext.signalSet(data, key);
2775
+ if (data.isUrl && !Object.prototype.hasOwnProperty.call(target, key)) return urlSet(data, target, key, value);
2448
2776
  if (data.shallow !== true) value = deepWrap(value);
2449
2777
  const isNewKey = !Object.prototype.hasOwnProperty.call(target, key);
2778
+ const isArrayIndex = data.isArray && typeof key !== "symbol" && !isNaN(+key);
2779
+ const oldLength = isArrayIndex ? target.length : 0;
2450
2780
  Reflect.set(target, key, value, receiver);
2451
2781
  propagateSignal(data, key);
2452
2782
  if (isNewKey) propagateSignal(data, proxyKeysSymbol);
2453
- if (data.isArray && typeof key !== "symbol" && !isNaN(+key)) propagateSignal(data, "length");
2783
+ if (isArrayIndex) {
2784
+ propagateSignal(data, proxyArrayContentSymbol);
2785
+ if (target.length !== oldLength) propagateSignal(data, "length");
2786
+ }
2454
2787
  }
2455
2788
  return true;
2456
2789
  }
@@ -2464,6 +2797,11 @@ const sharedHandler = {
2464
2797
  if (data !== void 0) trackProxySignal(data, proxyKeysSymbol);
2465
2798
  return Reflect.ownKeys(target);
2466
2799
  },
2800
+ has: (target, key) => {
2801
+ const data = target[proxyDataSymbol];
2802
+ if (data !== void 0) trackProxySignal(data, proxyKeysSymbol);
2803
+ return Reflect.has(target, key);
2804
+ },
2467
2805
  deleteProperty: (target, key) => {
2468
2806
  const deleted = Reflect.deleteProperty(target, key);
2469
2807
  const data = target[proxyDataSymbol];
@@ -2477,20 +2815,33 @@ const sharedHandler = {
2477
2815
  /**
2478
2816
  * Watches an object and runs effects when its properties are changed.
2479
2817
  *
2480
- * Dates, Maps and Sets are supported too: their methods are reactive (reads
2481
- * track, writes notify), so `new Date()`, `new Map()` and `new Set()` can be
2482
- * used in watched state directly.
2818
+ * Only plain objects, plain arrays, and exact Date/Map/Set/URL/
2819
+ * URLSearchParams instances are deep-watched. Other values -- class instances,
2820
+ * subclasses, RegExp, typed arrays, frozen/non-extensible objects, promises,
2821
+ * DOM nodes, ... -- are returned unchanged. Effects still track the property
2822
+ * that holds them, so replacing the value is reactive even though mutating it
2823
+ * in place isn't.
2824
+ *
2825
+ * Dates, Maps, Sets, URLs and URLSearchParams are supported: their methods are
2826
+ * reactive (reads track, writes notify), so they can be used in watched state
2827
+ * directly.
2483
2828
  *
2484
2829
  * @param object The object to watch
2485
2830
  */
2486
2831
  function $watch(object, options) {
2487
2832
  if (object === void 0 || object === null || object[proxyDataSymbol] !== void 0) return object;
2833
+ if (!isWrappable(object)) {
2834
+ if (devContext.enabled) console.warn("$watch() only deep-watches plain objects, arrays and exact Date/Map/Set/URL/URLSearchParams instances; returning this value unchanged.");
2835
+ return object;
2836
+ }
2488
2837
  const data = {
2489
2838
  target: object,
2490
2839
  isArray: Array.isArray(object),
2491
2840
  isDate: object instanceof Date,
2492
2841
  isMap: object instanceof Map,
2493
2842
  isSet: object instanceof Set,
2843
+ isUrl: typeof URL !== "undefined" && object instanceof URL,
2844
+ isUrlParams: typeof URLSearchParams !== "undefined" && object instanceof URLSearchParams,
2494
2845
  shallow: options?.shallow === true,
2495
2846
  signals: /* @__PURE__ */ new Map()
2496
2847
  };
@@ -2763,7 +3114,7 @@ function runList(region, parent, anchor, buildItems, create, update, noWatch) {
2763
3114
  const oldRegion = pushRegion(region, first);
2764
3115
  first = false;
2765
3116
  const newSpecs = buildItems();
2766
- if (devContext.enabled) checkListKeys(region, newSpecs);
3117
+ if (devContext.enabled) devContext.checkListKeys(region, newSpecs);
2767
3118
  context.activeTarget = null;
2768
3119
  listItems = runListItems(region, parent, anchor, listItems, newSpecs, create, update, noWatch);
2769
3120
  popRegion(oldRegion);
@@ -3047,7 +3398,7 @@ function setAttribute(el, name, value) {
3047
3398
  if (name === "value") {
3048
3399
  if (setValueProperty(el, String(value))) return;
3049
3400
  }
3050
- el.setAttribute(name, value);
3401
+ el.setAttribute(name, urlAttributeValue(name, value));
3051
3402
  }
3052
3403
  /** Sets the `value` property on a form control; returns false for other elements. */
3053
3404
  function setValueProperty(el, value) {
@@ -3480,6 +3831,6 @@ function $stream(source, handler, options) {
3480
3831
  });
3481
3832
  }
3482
3833
  //#endregion
3483
- 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, headElement as t_head_element, 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 };
3834
+ export { $async, $batch, $bind, $cache, $onmount, $peek, $pending, $refresh, $run, $stream, $unwrap, $watch, clearLayoutSlot, fillLayoutSlot, fromElement, fromServer, fromWebSocket, hydrate, mount, setUrlRewriter, 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, headElement as t_head_element, 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 };
3484
3835
 
3485
3836
  //# sourceMappingURL=index.mjs.map