@webjsdev/core 0.7.38 → 0.7.40

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.
@@ -18,7 +18,7 @@ import { scanSeeds } from './action-seed-client.js';
18
18
  // reused hydrated light-DOM component across a soft nav (#908).
19
19
  import {
20
20
  SLOT_STATE, LIGHT_SLOT_ATTR, PROJECTION_ATTR, PROJECTION_ACTUAL,
21
- applyActualAssignment, applyFallback, fireSlotChange,
21
+ setSlotContent,
22
22
  } from './slot.js';
23
23
 
24
24
  /** The content type a content-negotiated stream-action response carries (#248). */
@@ -39,26 +39,32 @@ const STREAM_MIME = 'text/vnd.webjs-stream.html';
39
39
  * `disableClientRouter()` to opt out, or `enableClientRouter()` for
40
40
  * programmatic control.
41
41
  *
42
- * Mechanism: auto-derived from folder structure:
43
- * 1. SSR injects `<!--wj:children:<segment-path>-->...<!--/wj:children-->`
44
- * comment markers around each layout's `${children}` interpolation
45
- * (one pair per layout in the chain).
46
- * 2. On link click, walk both the live DOM and the incoming HTML for
47
- * these markers and build path → range maps.
48
- * 3. Find the longest shared marker path. That's the deepest layout
49
- * both pages have in common.
50
- * 4. Replace nodes between that marker pair in the live DOM with the
51
- * equivalent range from the incoming HTML, using a keyed reconciler
52
- * that preserves input values, scroll, popover state, and the
53
- * identity of any matched DOM nodes.
42
+ * Mechanism: auto-derived from folder structure (#1015):
43
+ * 1. SSR injects KEYED boundary comment pairs around each layout's
44
+ * `${children}` interpolation and around the page itself:
45
+ * `<!--wj:children:<segment>:<route-key>-->` ... `<!--/wj:children:<segment>-->`.
46
+ * The close carries the segment (deterministic id-matched pairing, no
47
+ * LIFO), the open carries the resolved route-key (param values
48
+ * percent-encoded).
49
+ * 2. On link click, STRICTLY scan both the live DOM and the incoming HTML
50
+ * into segment → {routeKey, range} maps. Any pairing violation poisons
51
+ * the scan.
52
+ * 3. Two-tier decision (Next.js remount parity): a CHANGED route-key
53
+ * REPLACES (fresh remount) at the PARENT of the shallowest changed
54
+ * boundary (whose range contains the changed layout's own markup),
55
+ * else MORPH (keyed reconcile preserving input values, scroll, popover
56
+ * state, and node identity) at the deepest shared boundary.
57
+ * 4. A poisoned scan or no shared boundary degrades to a FULL PAGE LOAD:
58
+ * bounded and correct, never a guessed recovery.
54
59
  * 5. Merge head, re-run scripts, upgrade custom elements, pushState.
55
60
  *
56
61
  * Optimizations bundled into the same response cycle:
57
- * - `X-Webjs-Have` request header lists the marker paths the client
58
- * already has. Server walks the target's layout chain, skips
59
- * layouts at-or-above the deepest match, returns only the
60
- * divergent fragment (wrapped in the deepest shared marker). Real
61
- * wire-byte savings: the layout chain is never re-serialized for
62
+ * - `X-Webjs-Have` request header lists `segment:route-key` entries for
63
+ * the boundaries the client already has. The server walks the target's
64
+ * layout chain and short-circuits at the deepest FULL match (segment AND
65
+ * key, so a dynamic layout held for other params is re-rendered), then
66
+ * returns only the divergent fragment (wrapped in the matched boundary).
67
+ * Real wire-byte savings: the layout chain is never re-serialized for
62
68
  * same-shell navigations.
63
69
  * - URL-keyed snapshot cache (Turbo SnapshotCache pattern). Back/
64
70
  * forward via popstate restores from cache instantly, then
@@ -79,18 +85,26 @@ const STREAM_MIME = 'text/vnd.webjs-stream.html';
79
85
  */
80
86
 
81
87
  /**
82
- * Parse HTML into a Document. Prefers Document.parseHTMLUnsafe (processes
83
- * Declarative Shadow DOM) over DOMParser (does NOT process DSD).
88
+ * Parse a navigation response into a Document, PRESERVING COMMENTS.
89
+ *
90
+ * Comments are load-bearing here, not incidental: the partial swap pairs on
91
+ * `<!--wj:children:<path>-->` markers and hydration keys off `<!--webjs-hydrate-->`.
92
+ * `Document.parseHTMLUnsafe` would be the natural choice (it is the only
93
+ * single-pass API that also processes Declarative Shadow DOM) but it STRIPS
94
+ * EVERY COMMENT in Chromium 150 (#1007), which deletes both. So it is used only
95
+ * when a one-time probe proves it lossless on this engine, and otherwise we parse
96
+ * with DOMParser (comments preserved; DSD is left unprocessed, see
97
+ * `parseDocumentPreservingComments` for why that gap beats both ways of closing it).
84
98
  *
85
99
  * A partial-nav response (#936) is an INNER fragment that BEGINS with the
86
- * `<!--wj:children:<path>-->` layout marker and carries no `<!doctype>`/`<html>`.
87
- * Parsing such a fragment as a DOCUMENT hoists that leading comment OUT of
88
- * `<body>` (the HTML parser's "before html" insertion mode makes a leading
89
- * comment a child of the document, before `<html>`), so
90
- * `collectChildrenSlots(doc.body)` never sees the opening marker, finds no
91
- * shared slot, and `applySwap` falls to the destructive full-body swap that
92
- * strips the head stylesheets and the outer layout. So a fragment is parsed in
93
- * BODY (fragment) context instead, keeping the marker with its content.
100
+ * `<!--wj:children:<segment>:<route-key>-->` boundary open and carries no
101
+ * `<!doctype>`/`<html>`. Parsing such a fragment as a DOCUMENT hoists that
102
+ * leading comment OUT of `<body>` (the HTML parser's "before html" insertion
103
+ * mode makes a leading comment a child of the document, before `<html>`), so
104
+ * `collectBoundaries(doc.body)` never sees the opening boundary, finds no
105
+ * shared segment, and `applySwap` degrades to a full load. So a fragment is
106
+ * parsed in BODY (fragment) context instead, keeping the boundary with its
107
+ * content.
94
108
  * `body.setHTMLUnsafe` also processes Declarative Shadow DOM, so a shadow
95
109
  * component inside the swapped content still re-attaches its root; the
96
110
  * `<template>` path is the fallback for browsers without it (markers preserved,
@@ -116,13 +130,99 @@ function parseHTML(html) {
116
130
  // Fall through to a document parse (still functional, just the #936 path).
117
131
  }
118
132
  }
119
- if (typeof Document !== 'undefined' && typeof Document.parseHTMLUnsafe === 'function') {
133
+ if (
134
+ typeof Document !== 'undefined' &&
135
+ typeof Document.parseHTMLUnsafe === 'function' &&
136
+ parseHTMLUnsafePreservesComments()
137
+ ) {
120
138
  return Document.parseHTMLUnsafe(html);
121
139
  }
122
- if (typeof DOMParser !== 'undefined') {
123
- return new DOMParser().parseFromString(html, 'text/html');
140
+ return parseDocumentPreservingComments(html);
141
+ }
142
+
143
+ /**
144
+ * Is `Document.parseHTMLUnsafe` lossless for comments?
145
+ *
146
+ * Chromium 150 strips EVERY comment from `Document.parseHTMLUnsafe` output
147
+ * (#1007). No other parse API does: `DOMParser`, `setHTMLUnsafe`,
148
+ * `template.innerHTML`, and plain `innerHTML` all preserve them, and the
149
+ * document's own navigation parser preserves them (which is why a hard refresh
150
+ * always looked fine and only soft nav broke). MDN documents parseHTMLUnsafe as
151
+ * the parse-WITHOUT-sanitization entry point, so this reads as a browser defect
152
+ * rather than intent, but the whole router rides on comments (`wj:children`
153
+ * layout markers) and so does hydration (`webjs-hydrate`), so we cannot take
154
+ * the risk either way.
155
+ *
156
+ * Probed once, lazily, rather than version-sniffed: when the browser is fixed
157
+ * we silently return to the fast single-pass native path, and a future browser
158
+ * that regresses the same way is caught with no code change.
159
+ *
160
+ * @returns {boolean}
161
+ */
162
+ let _parseUnsafeLossless = null;
163
+ function parseHTMLUnsafePreservesComments() {
164
+ if (_parseUnsafeLossless !== null) return _parseUnsafeLossless;
165
+ try {
166
+ const probe = Document.parseHTMLUnsafe('<!doctype html><body><!--c--><i></i>');
167
+ _parseUnsafeLossless = probe?.body?.firstChild?.nodeType === 8;
168
+ } catch {
169
+ _parseUnsafeLossless = false;
124
170
  }
125
- return null;
171
+ return _parseUnsafeLossless;
172
+ }
173
+
174
+ /**
175
+ * Clear the memoized losslessness probe. Test-only: a browser cannot change
176
+ * mid-session, so nothing in the runtime needs this. Tests SIMULATE a stripping
177
+ * parser (rather than depending on the runner's browser actually being an
178
+ * affected version, which the Chromium web-test-runner currently resolves is not) and reset the
179
+ * memo around that stub.
180
+ */
181
+ function resetParseProbe() {
182
+ _parseUnsafeLossless = null;
183
+ }
184
+
185
+ /**
186
+ * Parse a FULL document while preserving comments.
187
+ *
188
+ * `DOMParser` keeps comments but does NOT process Declarative Shadow DOM, so a
189
+ * `<template shadowrootmode>` stays an inert template here. That is a DELIBERATE
190
+ * limitation on this path, and both obvious ways to "fix" it are worse than the
191
+ * gap (measured on Chromium 150, not reasoned about):
192
+ *
193
+ * - `body.setHTMLUnsafe(body.innerHTML)` re-serializes, and that round-trip is
194
+ * not idempotent: Chromium omits the spec's LF-compensation rule (append
195
+ * U+000A when a `pre` / `textarea` / `listing` element's first Text child
196
+ * starts with one), so `<textarea>\n\nfoo</textarea>` parses to `"\nfoo"`
197
+ * natively but `"foo"` after a round-trip. In a `<textarea>` that is silent
198
+ * form-data corruption: a soft nav would submit different bytes than a hard
199
+ * refresh.
200
+ * - Attaching each root by hand (`host.attachShadow()` + move the template's
201
+ * nodes) is USELESS on the common path and HARMFUL on the other. Useless
202
+ * because the marker swap imports with `document.importNode(n, true)`, which
203
+ * drops a shadow root unless it is `clonable`, and SSR emits a bare
204
+ * `<template shadowrootmode="open">`, so the root never survives the import
205
+ * and `component.js` re-attaches from scratch exactly as it always did.
206
+ * Harmful because the full-body-swap path ADOPTS instead, so a script-created
207
+ * root does survive, and a script-created root is not `declarative`: the spec
208
+ * only permits a second `attachShadow()` over an existing root when that root
209
+ * is declarative, so any element whose constructor unconditionally calls
210
+ * `attachShadow()` then throws `NotSupportedError` on upgrade, where the
211
+ * native parse it replaced worked fine.
212
+ *
213
+ * The gap this leaves is narrow and strictly better than the bug it replaces: on
214
+ * a comment-stripping browser only, an element that depends on DSD content and
215
+ * ships NO JavaScript loses that content on a full-body-swap navigation. Every
216
+ * WebJs `static shadow = true` component is unaffected, because it attaches and
217
+ * renders its own root on upgrade (`component.js`, guarded by `if
218
+ * (!this.shadowRoot)`), and a soft nav runs JS by definition. Tracked separately.
219
+ *
220
+ * @param {string} html
221
+ * @returns {Document | null}
222
+ */
223
+ function parseDocumentPreservingComments(html) {
224
+ if (typeof DOMParser === 'undefined') return null;
225
+ return new DOMParser().parseFromString(html, 'text/html');
126
226
  }
127
227
 
128
228
  let enabled = false;
@@ -642,6 +742,44 @@ function warnOnce(key, message) {
642
742
  if (typeof console !== 'undefined' && console.warn) console.warn(message);
643
743
  }
644
744
 
745
+ /**
746
+ * True when a nav must degrade to a full page load because the document is
747
+ * still parsing. A forward, main-document nav fired at `readyState: 'loading'`
748
+ * races the DOM: the leaving page's closing layout markers may not be attached
749
+ * yet, so a soft swap would snapshot an incomplete tree and corrupt the DOM
750
+ * (#1008 / #936). Scoped to frameless forward navs (popstate is browser-driven,
751
+ * a frame nav carries its own boundary element).
752
+ *
753
+ * @param {boolean} isPopState
754
+ * @param {string | null | undefined} frameId
755
+ * @returns {boolean}
756
+ */
757
+ function shouldFullLoadDuringParse(isPopState, frameId) {
758
+ return (
759
+ !isPopState &&
760
+ !frameId &&
761
+ typeof document !== 'undefined' &&
762
+ document.readyState === 'loading'
763
+ );
764
+ }
765
+
766
+ /**
767
+ * Dev-only diagnostic: the client router degraded a soft navigation to a full
768
+ * page load. Records WHY (the `cause`) so the "why did my SPA nav do a full
769
+ * reload?" question is answerable from the console instead of guessed at. Silent
770
+ * in production and deduped per cause so a repeated trigger does not spam.
771
+ *
772
+ * @param {string} cause a short stable slug for the degradation reason
773
+ * @param {string} href the destination the router fell back to loading
774
+ */
775
+ function devWarnFallback(cause, href) {
776
+ if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'production') return;
777
+ warnOnce(
778
+ `fallback:${cause}`,
779
+ `[webjs] client router fell back to a full page load (${cause}) navigating to ${href}. This is correct (no DOM corruption), just not a soft nav.`
780
+ );
781
+ }
782
+
645
783
  /**
646
784
  * Dev-only, fire-once hint: the router forces an INSTANT scroll-to-top on a
647
785
  * forward navigation (matching a native page load), so an app-level
@@ -701,81 +839,192 @@ function setNavigating(on) {
701
839
  }
702
840
 
703
841
  /* ====================================================================
704
- * Marker discovery (the heart of the partial-swap mechanism)
842
+ * Boundary discovery (the heart of the partial-swap mechanism, #1015)
705
843
  * ==================================================================== */
706
844
 
707
845
  /**
708
- * Walk a node tree collecting wj:children marker pairs into a Map
846
+ * Walk a node tree collecting KEYED children-boundary pairs into a Map
709
847
  * keyed by segment path.
710
848
  *
711
- * Markers are HTML comments emitted by SSR around each layout's
712
- * children interpolation:
713
- * <!--wj:children:/docs-->
849
+ * Boundaries are HTML comments emitted by SSR around each layout's
850
+ * children interpolation AND around the page itself:
851
+ * <!--wj:children:/docs:/docs--> (open: segment + route-key)
714
852
  * <page content>
715
- * <!--/wj:children-->
716
- *
717
- * The walk uses a stack to track nested marker pairs: a path can
718
- * appear multiple times in a document only if a layout transitively
719
- * includes itself (pathological; we take the outermost).
853
+ * <!--/wj:children:/docs--> (close: segment)
854
+ *
855
+ * The close carries the SEGMENT, so pairing is deterministic id-matching:
856
+ * a close must match the segment of the INNERMOST open boundary (proper
857
+ * nesting), never a positional LIFO guess. The open additionally carries
858
+ * the resolved ROUTE-KEY (param values percent-encoded at emit), which
859
+ * `planBoundarySwap` compares between the live and incoming DOM to pick
860
+ * the swap tier.
861
+ *
862
+ * STRICT INTEGRITY, by design (#1015): this scanner never guesses. ANY
863
+ * violation poisons the whole scan and returns null:
864
+ * - an open with no route-key (the legacy anonymous format, or truncation)
865
+ * - a close whose segment does not match the innermost open boundary
866
+ * - a close with no open boundary at all
867
+ * - a duplicate segment (two boundaries claiming one id)
868
+ * - an open boundary never closed (truncated response)
869
+ * The caller degrades a poisoned side to a FULL PAGE LOAD: bounded, correct,
870
+ * and honest, where the deleted heuristic recovery (#994's orphan recovery +
871
+ * trailing-count bounding) could guess wrong and corrupt silently. The main
872
+ * PRODUCER of mispairing (our own comment-stripping parse, #1007, and
873
+ * mid-parse soft navs, #1008) is already fixed upstream, so poisoning is a
874
+ * rare backstop, not a common path.
720
875
  *
721
876
  * @param {ParentNode} root
722
- * @returns {Map<string, { start: Comment, end: Comment }>}
877
+ * @returns {Map<string, { routeKey: string, start: Comment, end: Comment }> | null}
878
+ * The boundary map, or null when the tree's boundaries are malformed.
723
879
  */
724
- export function collectChildrenSlots(root) {
725
- /** @type {Map<string, { start: Comment, end: Comment }>} */
726
- const slots = new Map();
727
- /** @type {{ path: string, start: Comment }[]} */
880
+ export function collectBoundaries(root) {
881
+ /** @type {Map<string, { routeKey: string, start: Comment, end: Comment }>} */
882
+ const out = new Map();
883
+ /** @type {{ segment: string, routeKey: string, start: Comment }[]} */
728
884
  const stack = [];
885
+ let poisoned = false;
729
886
 
730
887
  // Plain recursive comment walk: TreeWalker/NodeFilter aren't available
731
888
  // in every DOM polyfill (notably linkedom in tests). Iterative depth-
732
889
  // first traversal keeps us portable across linkedom + native + jsdom.
733
890
  /** @param {Node} node */
734
891
  function visit(node) {
892
+ if (poisoned) return;
735
893
  if (node.nodeType === 8 /* COMMENT_NODE */) {
736
- const c = /** @type {Comment} */ (node);
737
- const data = c.data;
738
- const open = /^wj:children:(.+)$/.exec(data);
739
- if (open) {
740
- stack.push({ path: open[1], start: c });
894
+ const data = /** @type {Comment} */ (node).data.trim();
895
+ if (data.startsWith('wj:children:')) {
896
+ const rest = data.slice('wj:children:'.length);
897
+ // The route-key is everything after the LAST ':'. Substituted param
898
+ // values are percent-encoded at emit and static pieces have their
899
+ // delimiter characters encoded too, so the last colon is unambiguous
900
+ // for framework-emitted boundaries. A hand-authored folder name that
901
+ // still smuggles a delimiter through can only MIS-SPLIT here, which
902
+ // mismatches the close and poisons the scan: degrade-only, never a
903
+ // wrong pairing.
904
+ const cut = rest.lastIndexOf(':');
905
+ if (cut <= 0 || cut === rest.length - 1) { poisoned = true; return; }
906
+ const segment = rest.slice(0, cut);
907
+ const routeKey = rest.slice(cut + 1);
908
+ if (out.has(segment) || stack.some((f) => f.segment === segment)) {
909
+ poisoned = true;
910
+ return;
911
+ }
912
+ stack.push({ segment, routeKey, start: /** @type {Comment} */ (node) });
741
913
  return;
742
914
  }
743
- if (data.trim() === '/wj:children') {
915
+ if (data.startsWith('/wj:children')) {
916
+ const seg = data.slice('/wj:children'.length).replace(/^:/, '');
744
917
  const frame = stack.pop();
745
- if (frame && !slots.has(frame.path)) {
746
- slots.set(frame.path, { start: frame.start, end: c });
918
+ if (!frame || frame.segment !== seg) { poisoned = true; return; }
919
+ // Same-parent integrity: HTML parser reparenting (a <p> auto-closed
920
+ // by block content) can split a pair across parents. The range
921
+ // operations walk nextSibling from start and insert before end, so a
922
+ // cross-parent pair would empty the region and then throw mid-swap.
923
+ // Poison instead: degrade up front.
924
+ if (frame.start.parentNode !== /** @type {Comment} */ (node).parentNode) {
925
+ poisoned = true;
926
+ return;
927
+ }
928
+ // Table-context integrity: foster-parenting moves CONTENT out of the
929
+ // table while comment tokens stay put, so a boundary emitted in table
930
+ // context shares a parent (passing the check above) while its actual
931
+ // children were fostered OUTSIDE the range. Swapping that empty range
932
+ // would silently leave stale visible content. A `${children}` slot
933
+ // directly in table context cannot work as a swap boundary at all,
934
+ // so poison it.
935
+ {
936
+ const pt = /** @type {Element} */ (frame.start.parentNode).tagName;
937
+ if (pt === 'TABLE' || pt === 'TBODY' || pt === 'THEAD' || pt === 'TFOOT' || pt === 'TR') {
938
+ poisoned = true;
939
+ return;
940
+ }
747
941
  }
942
+ out.set(frame.segment, {
943
+ routeKey: frame.routeKey,
944
+ start: frame.start,
945
+ end: /** @type {Comment} */ (node),
946
+ });
748
947
  return;
749
948
  }
750
949
  return;
751
950
  }
752
951
  if (node.hasChildNodes && node.hasChildNodes()) {
753
- for (let child = node.firstChild; child; child = child.nextSibling) {
952
+ for (let child = node.firstChild; child && !poisoned; child = child.nextSibling) {
754
953
  visit(child);
755
954
  }
756
955
  }
757
956
  }
758
957
  visit(/** @type {Node} */ (root));
759
- return slots;
760
- }
761
958
 
762
- /**
763
- * Pick the longest path that exists in both maps.
764
- *
765
- * Path comparison is plain string equality (matches Next.js's
766
- * `matchSegment`). Longest wins so the swap is as scoped as possible.
767
- *
768
- * @param {Map<string, unknown>} here
769
- * @param {Map<string, unknown>} there
770
- * @returns {string | null}
771
- */
772
- export function longestSharedPath(here, there) {
773
- let best = null;
774
- for (const p of here.keys()) {
775
- if (!there.has(p)) continue;
776
- if (best === null || p.length > best.length) best = p;
959
+ if (poisoned || stack.length > 0) return null;
960
+ return out;
961
+ }
962
+
963
+ /**
964
+ * Plan the two-tier boundary swap from the live + incoming boundary maps
965
+ * (#1015). Boundary segments are nested path prefixes, so the shared segments
966
+ * form a chain from `/` down to the deepest shared boundary D.
967
+ *
968
+ * Rules (Next.js remount-vs-preserve parity):
969
+ * - A changed route-key REPLACES at the PARENT of the shallowest changed
970
+ * boundary. The parent, not the changed boundary itself: a LAYOUT's
971
+ * boundary wraps its CHILDREN slot, so the layout's OWN markup (an
972
+ * `[org]`-name header it renders around `${children}`) lives inside the
973
+ * PARENT's range. Anchoring at the parent remounts the changed layout's
974
+ * chrome AND its subtree, exactly like Next re-rendering the layout with
975
+ * new params. The page boundary composes the same way: its parent is the
976
+ * nearest layout's children slot, so `/blog/a` -> `/blog/b` under a
977
+ * `/blog` layout remounts just the page while the `/blog` layout chrome
978
+ * is preserved; with no intermediate layout the anchor is `/` and the
979
+ * root layout's chrome (outside its own children boundary) is still
980
+ * preserved. A changed boundary with NO shared parent degrades (null).
981
+ * - No route-key changed but the subtree below D diverges (D is a LAYOUT,
982
+ * not the deepest boundary, on either side, e.g. `/about` -> `/contact`
983
+ * under a shared static root layout): REPLACE D's contents wholesale.
984
+ * - No route-key changed and D is the deepest boundary on BOTH sides: MORPH
985
+ * D. The searchParams-only / refresh / revalidate nav, which must preserve
986
+ * hydrated component state while updating searchParam-driven DOM.
987
+ * - No shared segment at all: null (the caller degrades to a full load). In
988
+ * practice the page boundary exists on both sides of any same-app nav, so
989
+ * this is reached only for a divergent or malformed shell.
990
+ *
991
+ * @param {Map<string, { routeKey: string, start: Comment, end: Comment }>} here
992
+ * @param {Map<string, { routeKey: string, start: Comment, end: Comment }>} there
993
+ * @returns {{ mode: 'replace' | 'morph', segment: string,
994
+ * live: { routeKey: string, start: Comment, end: Comment },
995
+ * incoming: { routeKey: string, start: Comment, end: Comment } } | null}
996
+ */
997
+ export function planBoundarySwap(here, there) {
998
+ // Shared segments, shallowest first (a nested path prefix is shorter).
999
+ const shared = [...here.keys()].filter((s) => there.has(s)).sort((a, b) => a.length - b.length);
1000
+ if (shared.length === 0) return null;
1001
+ // A changed route-key remounts at the PARENT of the shallowest change.
1002
+ for (const seg of shared) {
1003
+ if (here.get(seg).routeKey !== there.get(seg).routeKey) {
1004
+ let parent = null;
1005
+ for (const p of shared) {
1006
+ if (p === seg) break;
1007
+ if (seg.startsWith(p === '/' ? p : p + '/')) parent = p;
1008
+ }
1009
+ if (!parent) return null; // no anchored parent: degrade
1010
+ return { mode: 'replace', segment: parent, live: here.get(parent), incoming: there.get(parent) };
1011
+ }
777
1012
  }
778
- return best;
1013
+ // No route-key changed. D = deepest shared boundary.
1014
+ const D = shared[shared.length - 1];
1015
+ /** @param {Map<string, unknown>} m */
1016
+ const deepestOf = (m) => {
1017
+ let best = null;
1018
+ for (const s of m.keys()) if (best === null || s.length > best.length) best = s;
1019
+ return best;
1020
+ };
1021
+ const leafOnBoth = deepestOf(here) === D && deepestOf(there) === D;
1022
+ return {
1023
+ mode: leafOnBoth ? 'morph' : 'replace',
1024
+ segment: D,
1025
+ live: here.get(D),
1026
+ incoming: there.get(D),
1027
+ };
779
1028
  }
780
1029
 
781
1030
  /* ====================================================================
@@ -859,6 +1108,22 @@ function cacheKey(url) {
859
1108
  * @param {string | null} frameId Active <webjs-frame> id, or null.
860
1109
  */
861
1110
  async function performNavigation(href, isPopState, frameId) {
1111
+ // #1008 / #936: a forward, main-document nav fired while the document is
1112
+ // still parsing (`readyState === 'loading'`) races the DOM. The leaving
1113
+ // page's closing layout markers at the bottom of the body may not exist yet,
1114
+ // so `snapshotCurrent` plus region discovery would capture an incomplete tree
1115
+ // and drive a corrupt or over-wide swap (the suspected root cause of the
1116
+ // dropped-marker reports). The PREFETCH path already skips this window (see
1117
+ // the `buildHaveHeader` call site); the click / `navigate()` path did not.
1118
+ // Degrade to a correct full-page load, which is what an MPA would do anyway.
1119
+ // Scoped to frameless forward navs: popstate is browser-driven, and a frame
1120
+ // nav carries its own boundary element.
1121
+ if (shouldFullLoadDuringParse(isPopState, frameId) && typeof location !== 'undefined') {
1122
+ devWarnFallback('readyState-loading', href);
1123
+ location.href = href;
1124
+ return;
1125
+ }
1126
+
862
1127
  // Cancel any in-flight fetch: Turbo Drive's navigator.stop().
863
1128
  if (activeAbortController) activeAbortController.abort();
864
1129
  activeAbortController = new AbortController();
@@ -906,7 +1171,7 @@ async function performNavigation(href, isPopState, frameId) {
906
1171
  // Fire-and-forget revalidation. Uses a fresh AbortController
907
1172
  // since this background fetch is allowed to overlap with the
908
1173
  // next foreground nav (it'll get aborted if a new nav lands).
909
- fetchAndApply(href, frameId, /* recordHistory */ false, optimisticState, 'GET', null, signal, myToken)
1174
+ fetchAndApply(href, frameId, /* recordHistory */ false, optimisticState, 'GET', null, signal, myToken, /* revalidating */ true)
910
1175
  .catch(() => {});
911
1176
  return;
912
1177
  }
@@ -1040,15 +1305,27 @@ async function performSubmission(href, method, body, frameId, form) {
1040
1305
  }
1041
1306
 
1042
1307
  /**
1043
- * Build the X-Webjs-Have header value from the live DOM's marker paths.
1044
- * Comma-separated, in document order (no canonicalization needed; the
1045
- * server intersects with the target's layout chain).
1308
+ * Build the X-Webjs-Have header value from the live DOM's boundaries.
1309
+ * Comma-separated `<segment>:<route-key>` entries in document order. The
1310
+ * ROUTE-KEY rides along so the server's short-circuit can distinguish "the
1311
+ * client has this layout" from "the client has this layout rendered for
1312
+ * DIFFERENT params": a dynamic `[org]` layout the client holds for org-a
1313
+ * must be re-rendered (and re-shipped) on an org-b navigation, or the
1314
+ * parent-anchored REPLACE would have no fresh layout markup to swap in.
1315
+ * The server ignores the page-boundary entry (never a layout segment).
1316
+ *
1317
+ * A poisoned live DOM (malformed boundaries) reports an EMPTY have, so the
1318
+ * server returns the full page. The subsequent applySwap re-scans, sees the
1319
+ * same poisoned live tree, and degrades to a full load: consistent with the
1320
+ * integrity-gate model, never a reduced fragment spliced against a tree we
1321
+ * cannot trust (#1015).
1046
1322
  *
1047
1323
  * @returns {string}
1048
1324
  */
1049
1325
  function buildHaveHeader() {
1050
- const slots = collectChildrenSlots(document.body);
1051
- return [...slots.keys()].join(',');
1326
+ const boundaries = collectBoundaries(document.body);
1327
+ if (!boundaries) return '';
1328
+ return [...boundaries.entries()].map(([seg, b]) => `${seg}:${b.routeKey}`).join(',');
1052
1329
  }
1053
1330
 
1054
1331
  /* ====================================================================
@@ -1580,8 +1857,9 @@ function refreshPrefetchObservers() {
1580
1857
  */
1581
1858
  function renderInPlaceNavError(status) {
1582
1859
  if (typeof document === 'undefined' || !document.body) return false;
1583
- const here = collectChildrenSlots(document.body);
1584
- // The deepest slot is the same swap target a normal partial swap writes
1860
+ const here = collectBoundaries(document.body);
1861
+ if (!here) return false; // poisoned live tree: let the caller hard-load
1862
+ // The deepest boundary is the same swap target a normal partial swap writes
1585
1863
  // to (longest path wins), so the outer chrome / nav are preserved.
1586
1864
  /** @type {{ start: Comment, end: Comment } | undefined} */
1587
1865
  let deepest;
@@ -1662,6 +1940,9 @@ function handleNavigationError(href, status, error) {
1662
1940
  * @param {BodyInit | null} [body] Request body for non-GET methods.
1663
1941
  * @param {AbortSignal | null} [signal] Abort signal. A newer nav cancels this fetch.
1664
1942
  * @param {number} [token] Nav-token captured at the caller's entry; stale → skip apply.
1943
+ * @param {boolean} [revalidating] True for the BACKGROUND refresh after a
1944
+ * snapshot restore: the user is already viewing a page, so a boundary
1945
+ * mismatch must degrade in place (never a jarring `location.href` load).
1665
1946
  * @returns {Promise<{ ok: boolean, status: number | null, aborted: boolean }>}
1666
1947
  * The fetch outcome, so a caller (the form-submission busy/event lifecycle)
1667
1948
  * can report whether the submission settled as a success, an error, or an
@@ -1670,7 +1951,7 @@ function handleNavigationError(href, status, error) {
1670
1951
  * for an abort (which also sets `aborted:true`). `status` is the HTTP status
1671
1952
  * or `null` when the request never produced one.
1672
1953
  */
1673
- async function fetchAndApply(href, frameId, recordHistory, optimisticState, method, body, signal, token) {
1954
+ async function fetchAndApply(href, frameId, recordHistory, optimisticState, method, body, signal, token, revalidating) {
1674
1955
  method = method || 'GET';
1675
1956
  const myToken = typeof token === 'number' ? token : currentNavigationToken;
1676
1957
  let html;
@@ -1837,7 +2118,15 @@ async function fetchAndApply(href, frameId, recordHistory, optimisticState, meth
1837
2118
  // recover in place rather than a destructive full reload.
1838
2119
  if (!doc) { restoreOptimistic(optimisticState); handleNavigationError(href, null, new Error('navigation response did not parse as HTML')); return { ok: false, status: respStatus, aborted: false }; }
1839
2120
 
1840
- applySwap(doc, frameId, false, finalUrl, incomingBuild, incomingSrc);
2121
+ const disposition = applySwap(doc, frameId, !!revalidating, finalUrl, incomingBuild, incomingSrc);
2122
+ // A discarded revalidation must be discarded OUTRIGHT: a streamed response's
2123
+ // boundary templates must not splice into the restored snapshot afterward
2124
+ // (boundary ids are per-render sequential, so a reduced render's numbering
2125
+ // need not line up with the snapshot's). Cancel the reader and stop here.
2126
+ if (disposition === 'discard') {
2127
+ if (streamCtx && streamCtx.reader) { try { streamCtx.reader.cancel(); } catch { /* ignore */ } }
2128
+ return { ok: respOk, status: respStatus, aborted: false };
2129
+ }
1841
2130
 
1842
2131
  if (recordHistory) history.pushState(null, '', finalUrl);
1843
2132
 
@@ -2299,7 +2588,7 @@ function findInSlice(slice, id) {
2299
2588
  * swap settles. The View Transitions API snapshots and replaces DOM, so
2300
2589
  * elements can need a re-upgrade once the animation finishes.
2301
2590
  *
2302
- * @param {{ start: Comment, end: Comment } | undefined} range
2591
+ * @param {{ start: Comment, end: Comment | null } | undefined} range
2303
2592
  */
2304
2593
  function upgradeCustomElementsInRange(range) {
2305
2594
  if (!range || !range.start) return;
@@ -2493,31 +2782,68 @@ function applySwap(doc, frameId, revalidating, href, incomingBuild, incomingSrc)
2493
2782
  return;
2494
2783
  }
2495
2784
 
2496
- // 2. Auto-derived layout-marker swap.
2497
- const here = collectChildrenSlots(document.body);
2498
- const there = collectChildrenSlots(doc.body);
2499
- const sharedPath = longestSharedPath(here, there);
2500
-
2501
- if (sharedPath) {
2502
- // ADD-ONLY head merge for the same reason: outer layout stays
2503
- // mounted, its head-bound runtime state must not be invalidated.
2785
+ // 2. Two-tier keyed boundary swap (#1015). Scan both trees STRICTLY: a
2786
+ // poisoned side (malformed, truncated, or mispaired boundaries) yields null
2787
+ // and falls through to the integrity degradation below. A valid pair of
2788
+ // scans picks the swap tier by route-key comparison: a CHANGED key REPLACES
2789
+ // (remount, Next param-change parity) at the PARENT of the shallowest
2790
+ // change, else MORPH (state-preserving keyed reconcile) at the deepest
2791
+ // shared boundary.
2792
+ const here = collectBoundaries(document.body);
2793
+ const there = collectBoundaries(doc.body);
2794
+ const plan = here && there ? planBoundarySwap(here, there) : null;
2795
+
2796
+ if (plan) {
2797
+ const { mode, live, incoming } = plan;
2798
+ // ADD-ONLY head merge: the outer layout stays mounted, so its head-bound
2799
+ // runtime state (Tailwind injection, etc.) must not be invalidated.
2504
2800
  addNewHeadElements(doc.head);
2505
2801
  runWithTransition(() => {
2506
- swapMarkerRange(here.get(sharedPath), there.get(sharedPath), doc);
2802
+ if (mode === 'replace') replaceBoundaryRange(live, incoming);
2803
+ else swapMarkerRange(live, incoming, doc);
2804
+ // No key sync is needed on the anchor's own comments: the plan's anchor
2805
+ // carries EQUAL live/incoming route-keys in every tier (a changed-key
2806
+ // REPLACE anchors at a parent already compared equal; the other tiers
2807
+ // require no change at all), and the fresh deeper keys arrive via the
2808
+ // physically replaced boundary comments inside the range.
2507
2809
  blurOutgoingFocus();
2508
- }, () => upgradeCustomElementsInRange(here.get(sharedPath)));
2810
+ }, () => upgradeCustomElementsInRange(live));
2509
2811
  forwardSuspenseResolvers(doc.body);
2510
2812
  return;
2511
2813
  }
2512
2814
 
2513
- // 3. Full body swap fallback: no shared layout marker (a genuine root-layout
2514
- // change, or a same-layout nav whose markers could not be paired). Full head
2515
- // merge, so a real root-layout change removes stale head elements. `mergeHead`
2516
- // now PRESERVES stylesheets and `<style>` unconditionally (#936): even if the
2517
- // client reaches this path with an incoming head that lacks the app's
2518
- // `<link rel=stylesheet>` (a partial or mangled response, e.g. from a
2519
- // mid-parse empty-`have` prefetch), the live CSS is never stripped, so the
2520
- // swap can no longer leave the page unstyled.
2815
+ // 3. Integrity degradation (#1015). No trustworthy shared boundary exists:
2816
+ // one side is poisoned, or the trees share no segment (a divergent shell).
2817
+ // For a FOREGROUND nav, degrade to a FULL PAGE LOAD: bounded, correct, and
2818
+ // exactly what an MPA would do, where the deleted heuristic recovery could
2819
+ // guess wrong and corrupt silently. Dev logs the cause so a systematic
2820
+ // producer of malformed boundaries is visible immediately. A REVALIDATION
2821
+ // (the background refresh after a snapshot restore) is excluded: the user
2822
+ // is already viewing a page, so a background op must never yank them
2823
+ // through a hard load; it takes the in-place path below.
2824
+ if (href && !revalidating && typeof location !== 'undefined') {
2825
+ devWarnFallback(!here ? 'live-boundaries-malformed'
2826
+ : !there ? 'incoming-boundaries-malformed'
2827
+ : 'no-shared-boundary', href);
2828
+ location.href = href;
2829
+ return;
2830
+ }
2831
+
2832
+ // A BACKGROUND revalidation (revalidating + href) with no trustworthy plan
2833
+ // DISCARDS the response outright: the user is viewing a valid restored
2834
+ // snapshot, and the response may be a reduced (chrome-less) X-Webjs-Have
2835
+ // fragment, so the full-body swap below would wipe the shell from a
2836
+ // background op. Doing nothing is the only safe degradation here.
2837
+ if (href && revalidating) {
2838
+ devWarnFallback('revalidation-discarded', href);
2839
+ return 'discard';
2840
+ }
2841
+
2842
+ // 4. In-place full-body swap: the background paths only (a snapshot
2843
+ // restore or its revalidation, where a full load is not an option
2844
+ // because the user is already viewing the page). Full head merge;
2845
+ // `mergeHead` PRESERVES stylesheets and `<style>` unconditionally
2846
+ // (#936) so the swap can never leave the page unstyled.
2521
2847
  mergeHead(doc.head);
2522
2848
  // Persist permanent elements by node identity across the full-body
2523
2849
  // swap: move each live [data-webjs-permanent][id] node into the matching
@@ -2563,11 +2889,58 @@ function blurOutgoingFocus() {
2563
2889
  }
2564
2890
 
2565
2891
  /**
2566
- * Replace nodes between `target.start` and `target.end` (exclusive) in the
2567
- * live document with the nodes between `source.start` and `source.end` in
2568
- * the parsed Document. Uses a keyed reconciler that preserves DOM
2569
- * identity for matched elements + their live attributes (scroll, value,
2570
- * etc.).
2892
+ * Wholesale-REPLACE the contents of a boundary range (#1015): remove every
2893
+ * live node between `target.start` and `target.end` (exclusive) and insert a
2894
+ * fresh import of the incoming range. This is the REMOUNT tier: the boundary's
2895
+ * route-key changed (a param change, or a different page under a shared static
2896
+ * layout), so Next.js parity demands fresh component instances, not a keyed
2897
+ * reuse of old-page DOM. The only nodes that survive by identity are
2898
+ * `data-webjs-permanent` elements, regrafted into the imported slice before
2899
+ * insertion so a playing `<audio>`/widget keeps running.
2900
+ *
2901
+ * @param {{ start: Comment, end: Comment }} target The live boundary.
2902
+ * @param {{ start: Comment, end: Comment }} source The incoming boundary.
2903
+ */
2904
+ function replaceBoundaryRange(target, source) {
2905
+ const liveParent = target.start.parentNode;
2906
+ if (!liveParent) return;
2907
+ /** @type {Node[]} */
2908
+ const liveSlice = [];
2909
+ for (let n = target.start.nextSibling; n && n !== target.end; n = n.nextSibling) {
2910
+ liveSlice.push(n);
2911
+ }
2912
+ /** @type {Node[]} */
2913
+ const incomingSlice = [];
2914
+ for (let n = source.start.nextSibling; n && n !== source.end; n = n.nextSibling) {
2915
+ incomingSlice.push(document.importNode(n, true));
2916
+ }
2917
+ regraftPermanentInSlice(liveSlice, incomingSlice);
2918
+ for (const n of liveSlice) {
2919
+ if (n.parentNode === liveParent) liveParent.removeChild(n);
2920
+ }
2921
+ for (const n of incomingSlice) {
2922
+ liveParent.insertBefore(n, target.end);
2923
+ }
2924
+ for (let n = target.start.nextSibling; n && n !== target.end; n = n.nextSibling) {
2925
+ if (n.nodeType === 1) {
2926
+ reactivateScripts(/** @type {Element} */ (n));
2927
+ upgradeCustomElements(/** @type {Element} */ (n));
2928
+ }
2929
+ }
2930
+ }
2931
+
2932
+ /**
2933
+ * MORPH the contents of a boundary range (#1015): reconcile the nodes between
2934
+ * `target.start` and `target.end` (exclusive) in the live document against the
2935
+ * nodes between `source.start` and `source.end` in the parsed Document, using
2936
+ * a keyed reconciler that preserves DOM identity for matched elements + their
2937
+ * live attributes (scroll, value, etc.). This is the state-preserving tier for
2938
+ * a searchParams-only / refresh nav, where the route-key is unchanged and
2939
+ * hydrated component state must survive.
2940
+ *
2941
+ * Boundaries are strictly paired by the scanner (#1015), so `end` is always a
2942
+ * real close comment here (the null-orphan tolerance of the deleted #994
2943
+ * recovery is gone with it).
2571
2944
  *
2572
2945
  * @param {{ start: Comment, end: Comment } | undefined} target
2573
2946
  * @param {{ start: Comment, end: Comment } | undefined} source
@@ -2634,7 +3007,7 @@ function swapMarkerRange(target, source, _doc) {
2634
3007
  *
2635
3008
  * @param {Node} parent
2636
3009
  * @param {Comment} startMarker
2637
- * @param {Comment} endMarker
3010
+ * @param {Comment | null} endMarker Null (recovered orphan, #994) appends at the parent end.
2638
3011
  * @param {Node[]} live
2639
3012
  * @param {Node[]} incoming
2640
3013
  */
@@ -2800,39 +3173,7 @@ function ownActualLightSlots(host) {
2800
3173
  return byName;
2801
3174
  }
2802
3175
 
2803
- /**
2804
- * The component's own light slot for `name`, whatever its projection state
2805
- * (first-wins by document order). Used to resolve the slot to fill on a
2806
- * fallback->actual transition, where the target slot is currently `fallback`
2807
- * so it is absent from `ownActualLightSlots`. Nested-child slots are excluded.
2808
- *
2809
- * @param {Element} host
2810
- * @param {string|null} name
2811
- * @returns {HTMLSlotElement | null}
2812
- */
2813
- function ownLightSlotForName(host, name) {
2814
- for (const slot of host.querySelectorAll(`slot[${LIGHT_SLOT_ATTR}]`)) {
2815
- const s = /** @type {HTMLSlotElement} */ (slot);
2816
- if (!isOwnLightSlot(s, host)) continue;
2817
- if ((s.getAttribute('name') || null) === name) return s;
2818
- }
2819
- return null;
2820
- }
2821
3176
 
2822
- /**
2823
- * Per-index node-identity equality of two node lists. Used to decide whether a
2824
- * slot's assigned-node SET actually changed (so `slotchange` should fire); an
2825
- * in-place text edit that reuses the same node is NOT a set change.
2826
- *
2827
- * @param {ArrayLike<Node>} a
2828
- * @param {ArrayLike<Node>} b
2829
- * @returns {boolean}
2830
- */
2831
- function sameNodeList(a, b) {
2832
- if (a.length !== b.length) return false;
2833
- for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
2834
- return true;
2835
- }
2836
3177
 
2837
3178
  /**
2838
3179
  * Re-project the page-authored slotted content of a REUSED hydrated light-DOM
@@ -2856,8 +3197,8 @@ function sameNodeList(a, b) {
2856
3197
  * slot runtime's own primitives (`applyFallback` / `applyActualAssignment`)
2857
3198
  * on the ONE resolved own slot, which restore or swap the render-owned
2858
3199
  * fallback without reconciling any lit-html part (#912). This is applied
2859
- * surgically to the target slot, NOT via a whole-host `projectChildren`
2860
- * pass: `projectChildren` selects EVERY `data-webjs-light` slot in the
3200
+ * surgically to the target slot, NOT via a whole-host application
3201
+ * pass: a whole-host pass selects EVERY `data-webjs-light` slot in the
2861
3202
  * subtree (including a nested child component's), so running it here would
2862
3203
  * let this component's assignment reach into a nested child's same-named
2863
3204
  * slot and clobber its render-owned nodes (the #906 hazard, one level down).
@@ -2866,54 +3207,39 @@ function sameNodeList(a, b) {
2866
3207
  * @param {Element} src Incoming SSR copy of the same component.
2867
3208
  */
2868
3209
  function reprojectSlottedContent(dst, src) {
2869
- // Only a light-DOM component that tracks slot assignments has projected
3210
+ // Only a light-DOM component that tracks slot assignments has placed
2870
3211
  // page-authored content to update. No slot state (no <slot>, or a shadow-DOM
2871
3212
  // component whose slotted nodes are ordinary light children) means nothing
2872
- // to re-project here.
2873
- const state = /** @type {any} */ (dst)[SLOT_STATE];
2874
- if (!state) return;
3213
+ // to update here.
3214
+ if (!(/** @type {any} */ (dst)[SLOT_STATE])) return;
2875
3215
 
2876
3216
  const liveSlots = ownActualLightSlots(dst);
2877
3217
  const incSlots = ownActualLightSlots(src);
2878
3218
  if (liveSlots.size === 0 && incSlots.size === 0) return;
2879
3219
 
2880
- // A slot name is `actual` on the live side, the incoming side, or both. Walk
2881
- // the union so a boundary transition (present on only one side) is handled.
3220
+ // #1015: slotted children are VALUES pushed through the ONE public seam,
3221
+ // setSlotContent (no cross-module state surgery; the slot runtime owns the
3222
+ // record, fires slotchange on a genuine set change, and re-applies). The
3223
+ // union walk covers boundary transitions (a name present on only one side).
2882
3224
  const names = new Set([...liveSlots.keys(), ...incSlots.keys()]);
2883
3225
  for (const name of names) {
2884
3226
  const liveSlot = liveSlots.get(name);
2885
3227
  const incSlot = incSlots.get(name);
2886
3228
  if (liveSlot && incSlot) {
2887
- // actual->actual: the slot's children are page-authored, so
2888
- // reconcileChildren is safe: it preserves node identity where it can and
2889
- // never touches lit-html parts. Keep the slot runtime's assignment
2890
- // bookkeeping in sync so a later re-render materialises THESE nodes.
2891
- const prevAssigned = state.lastSnapshot.get(liveSlot) || [];
3229
+ // actual->actual: reconcile IN PLACE first so page-authored slotted
3230
+ // nodes keep DOM identity where they match (#908: a nested live
3231
+ // component survives; an in-place text edit reuses the same node),
3232
+ // then push the resulting set through the public API. The runtime's
3233
+ // set-equality check makes slotchange fire exactly on an
3234
+ // add/remove/replace and stay silent on a pure text edit (#912).
2892
3235
  reconcileChildren(liveSlot, incSlot);
2893
- const children = [...liveSlot.childNodes];
2894
- state.assignedByName.set(name, children);
2895
- state.lastSnapshot.set(liveSlot, children.slice());
2896
- // Fire slotchange on an assigned-node-SET change (add / remove / reorder),
2897
- // not an in-place text edit that reuses the same node: that matches the
2898
- // spec and keeps this branch uniform with the boundary branches below.
2899
- if (!sameNodeList(prevAssigned, children)) fireSlotChange(liveSlot);
2900
- } else if (liveSlot && !incSlot) {
2901
- // actual->fallback: incoming REMOVED this slot's content. Clear the
2902
- // assignment and flip THIS slot to fallback; applyFallback restores the
2903
- // render-owned fallback from the slot-part holding fragment.
2904
- state.assignedByName.delete(name);
2905
- if (applyFallback(state, liveSlot)) fireSlotChange(liveSlot);
3236
+ setSlotContent(dst, name, [...liveSlot.childNodes]);
3237
+ } else if (incSlot) {
3238
+ // fallback->actual: incoming ADDED content. Import and push.
3239
+ setSlotContent(dst, name, [...incSlot.childNodes].map((n) => document.importNode(n, true)));
2906
3240
  } else {
2907
- // fallback->actual: incoming ADDED content where the live slot shows
2908
- // fallback. The target slot is currently fallback, so resolve it directly
2909
- // (it is absent from the actual-only map) and fill it with the imported
2910
- // page-authored nodes; applyActualAssignment tucks the render-owned
2911
- // fallback into the holding fragment first.
2912
- const targetSlot = ownLightSlotForName(dst, name);
2913
- if (!targetSlot) continue;
2914
- const nodes = [...incSlot.childNodes].map((n) => document.importNode(n, true));
2915
- state.assignedByName.set(name, nodes);
2916
- if (applyActualAssignment(state, targetSlot, nodes)) fireSlotChange(targetSlot);
3241
+ // actual->fallback: incoming DROPPED the content. Reset to fallback.
3242
+ setSlotContent(dst, name, null);
2917
3243
  }
2918
3244
  }
2919
3245
  }
@@ -3047,16 +3373,21 @@ const LIVE_ATTRS = new Set([
3047
3373
  * @returns {{ slot: { start: Comment, end: Comment }, oldChildren: Node[], token: number } | null}
3048
3374
  */
3049
3375
  function applyOptimisticLoading() {
3050
- const slots = collectChildrenSlots(document.body);
3051
- if (slots.size === 0) return null;
3052
- // Pick the deepest current slot (longest path).
3376
+ const slots = collectBoundaries(document.body);
3377
+ if (!slots || slots.size === 0) return null;
3378
+ // Walk boundaries deepest-first and use the first whose segment has a
3379
+ // loading template. Loading templates are keyed by LAYOUT segment
3380
+ // (loading.ts files live next to layouts), while the deepest boundary is
3381
+ // usually the PAGE's own (#1015), which has no template: skipping over it
3382
+ // finds the innermost layout skeleton, matching the pre-#1015 behaviour.
3383
+ const bySegment = [...slots.keys()].sort((a, b) => b.length - a.length);
3053
3384
  let deepest = null;
3054
- for (const p of slots.keys()) {
3055
- if (deepest === null || p.length > deepest.length) deepest = p;
3385
+ let tpl = null;
3386
+ for (const p of bySegment) {
3387
+ const t = document.getElementById(`wj-loading:${p}`);
3388
+ if (t instanceof HTMLTemplateElement) { deepest = p; tpl = t; break; }
3056
3389
  }
3057
- if (deepest === null) return null;
3058
- const tpl = document.getElementById(`wj-loading:${deepest}`);
3059
- if (!(tpl instanceof HTMLTemplateElement)) return null;
3390
+ if (deepest === null || tpl === null) return null;
3060
3391
 
3061
3392
  const slot = slots.get(deepest);
3062
3393
  /** @type {Node[]} */
@@ -3550,9 +3881,10 @@ export {
3550
3881
  clearFrameBusy as _clearFrameBusy,
3551
3882
  markFormBusy as _markFormBusy,
3552
3883
  clearFormBusy as _clearFormBusy,
3553
- collectChildrenSlots as _collectChildrenSlots,
3554
- longestSharedPath as _longestSharedPath,
3884
+ collectBoundaries as _collectBoundaries,
3885
+ planBoundarySwap as _planBoundarySwap,
3555
3886
  parseHTML as _parseHTML,
3887
+ resetParseProbe as _resetParseProbe,
3556
3888
  keyOf as _keyOf,
3557
3889
  diffElementInPlace as _diffElementInPlace,
3558
3890
  reconcileChildren as _reconcileChildren,
@@ -3610,6 +3942,11 @@ export function _setCurrentPageUrl(u) { currentPageUrl = u; }
3610
3942
  /** Test-only: clear the fire-once warning guards so a case can be re-exercised. */
3611
3943
  export function _resetWarnOnce() { warnedKeys.clear(); smoothScrollChecked = false; }
3612
3944
 
3945
+ /** Test-only: the readyState-loading full-load degradation predicate (#1008). */
3946
+ export function _shouldFullLoadDuringParse(isPopState, frameId) {
3947
+ return shouldFullLoadDuringParse(isPopState, frameId);
3948
+ }
3949
+
3613
3950
  /**
3614
3951
  * Predicate used by the onClick handler to decide whether a same-origin
3615
3952
  * href should bypass the router. Exposed for unit testing.