@ecopages/browser-router 0.2.0-beta.8 → 0.2.0-rc.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 (43) hide show
  1. package/README.md +12 -4
  2. package/package.json +7 -7
  3. package/src/client/document-element-sync.d.ts +0 -7
  4. package/src/client/document-element-sync.js +28 -18
  5. package/src/client/dom/body-morpher.d.ts +24 -0
  6. package/src/client/dom/body-morpher.js +143 -0
  7. package/src/client/dom/dom-swapper.d.ts +30 -0
  8. package/src/client/dom/dom-swapper.js +52 -0
  9. package/src/client/dom/head-updater.d.ts +42 -0
  10. package/src/client/dom/head-updater.js +194 -0
  11. package/src/client/dom/html-parser.d.ts +4 -0
  12. package/src/client/dom/html-parser.js +8 -0
  13. package/src/client/dom/stylesheet-discovery.d.ts +12 -0
  14. package/src/client/dom/stylesheet-discovery.js +24 -0
  15. package/src/client/dom/stylesheet-preloader.d.ts +10 -0
  16. package/src/client/dom/stylesheet-preloader.js +44 -0
  17. package/src/client/eco-router.d.ts +2 -31
  18. package/src/client/eco-router.js +337 -443
  19. package/src/client/index.d.ts +3 -0
  20. package/src/client/index.js +3 -0
  21. package/src/client/navigation-commit.d.ts +22 -0
  22. package/src/client/navigation-commit.js +104 -0
  23. package/src/client/navigation-fetch.d.ts +8 -0
  24. package/src/client/navigation-fetch.js +24 -0
  25. package/src/client/services/prefetch-manager.d.ts +2 -14
  26. package/src/client/services/prefetch-manager.js +378 -370
  27. package/src/client/services/view-transition-manager.d.ts +6 -2
  28. package/src/client/services/view-transition-manager.js +76 -52
  29. package/src/client/types.d.ts +6 -13
  30. package/src/client/types.js +19 -20
  31. package/src/index.d.ts +3 -5
  32. package/src/index.js +8 -18
  33. package/src/styles.css +2 -6
  34. package/src/client/services/dom-swapper.d.ts +0 -168
  35. package/src/client/services/dom-swapper.js +0 -529
  36. package/src/client/services/index.d.ts +0 -8
  37. package/src/client/services/index.js +0 -10
  38. package/src/client/services/scroll-manager.d.ts +0 -19
  39. package/src/client/services/scroll-manager.js +0 -36
  40. package/src/client/view-transition-utils.d.ts +0 -14
  41. package/src/client/view-transition-utils.js +0 -60
  42. package/src/types.d.ts +0 -15
  43. package/src/types.js +0 -5
package/README.md CHANGED
@@ -53,6 +53,8 @@ const router = createRouter({
53
53
  });
54
54
  ```
55
55
 
56
+ By default, when view transitions are enabled, the router opts the document out of the UA root group (no lighter flash on dark themes) and only calls `startViewTransition` when a page uses `data-view-transition` shared-element morphs. Set `viewTransitions: false` to disable.
57
+
56
58
  By default, browser-router only syncs root `<html>` metadata it owns. Client-managed attributes and classes such as theme state are preserved unless you explicitly include them in `documentElementAttributesToSync`.
57
59
 
58
60
  For advanced cases, browser-router also exports low-level document sync tooling without changing the router instance API:
@@ -60,7 +62,7 @@ For advanced cases, browser-router also exports low-level document sync tooling
60
62
  ```ts
61
63
  import {
62
64
  createRouter,
63
- defaultDocumentElementAttributesToSync,
65
+ DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC,
64
66
  syncDocumentElementAttributes,
65
67
  } from '@ecopages/browser-router';
66
68
 
@@ -68,7 +70,7 @@ const router = createRouter();
68
70
 
69
71
  document.addEventListener('eco:before-swap', (event) => {
70
72
  syncDocumentElementAttributes(document, event.detail.newDocument, [
71
- ...defaultDocumentElementAttributesToSync,
73
+ ...DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC,
72
74
  'data-theme',
73
75
  ]);
74
76
  });
@@ -76,6 +78,12 @@ document.addEventListener('eco:before-swap', (event) => {
76
78
 
77
79
  Loading the router script is the opt-in point for browser-router-managed navigation on that page shell. Pages without the router script continue to use normal document navigation.
78
80
 
81
+ ## Router singleton
82
+
83
+ `createRouter()` returns a single active router per browser tab. The first call creates, starts, and stores the instance on `window.__ecopages_browser_router__`. Later calls return that same instance and ignore new options.
84
+
85
+ Call `router.stop()` before replacing the router script in long-lived sessions (for example after `data-eco-rerun` layout reloads) if you need a fresh instance with different options.
86
+
79
87
  ## Configuration
80
88
 
81
89
  | Option | Type | Default | Description |
@@ -86,7 +94,7 @@ Loading the router script is the opt-in point for browser-router-managed navigat
86
94
  | `reloadAttribute` | `string` | `'data-eco-reload'` | Attribute to force full page reload |
87
95
  | `updateHistory` | `boolean` | `true` | Whether to update browser history |
88
96
  | `scrollBehavior` | `'top' \| 'preserve' \| 'auto'` | `'top'` | Scroll behavior after navigation |
89
- | `viewTransitions` | `boolean` | `false` | Use View Transition API for animations |
97
+ | `viewTransitions` | `boolean` | `true` | View Transition API; disables UA root crossfade by default. `false` disables. |
90
98
  | `smoothScroll` | `boolean` | `false` | Use smooth scrolling during navigation |
91
99
 
92
100
  ## Persistence
@@ -121,7 +129,7 @@ Use `data-eco-reload` on an anchor tag to bypass the router and force a full pag
121
129
 
122
130
  ## Events
123
131
 
124
- Listen to navigation lifecycle events on the `document`:
132
+ Listen to navigation lifecycle events on the `document`. Event detail types live in `@ecopages/core/router/navigation-lifecycle`.
125
133
 
126
134
  ```ts
127
135
  document.addEventListener('eco:before-swap', (e) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/browser-router",
3
- "version": "0.2.0-beta.8",
3
+ "version": "0.2.0-rc.0",
4
4
  "description": "Client-side router for Ecopages with view transitions support",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -18,24 +18,24 @@
18
18
  "default": "./src/index.js"
19
19
  },
20
20
  "./client": {
21
- "types": "./src/client/eco-router.d.ts",
22
- "default": "./src/client/eco-router.js"
21
+ "types": "./src/client/index.d.ts",
22
+ "default": "./src/client/index.js"
23
23
  },
24
24
  "./client.ts": {
25
- "types": "./src/client/eco-router.d.ts",
26
- "default": "./src/client/eco-router.js"
25
+ "types": "./src/client/index.d.ts",
26
+ "default": "./src/client/index.js"
27
27
  }
28
28
  },
29
29
  "repository": {
30
30
  "type": "git",
31
- "url": "https://github.com/ecopages/ecopages.git",
31
+ "url": "git+https://github.com/ecopages/ecopages.git",
32
32
  "directory": "packages/browser-router"
33
33
  },
34
34
  "dependencies": {
35
35
  "morphdom": "^2.7.8"
36
36
  },
37
37
  "peerDependencies": {
38
- "@ecopages/core": "0.2.0-beta.8"
38
+ "@ecopages/core": "0.2.0-rc.0"
39
39
  },
40
40
  "types": "./src/index.d.ts"
41
41
  }
@@ -2,13 +2,6 @@
2
2
  * Helpers for synchronizing selected root `<html>` attributes during client-side navigation.
3
3
  * @module
4
4
  */
5
- /**
6
- * Default root `<html>` attributes that browser-router treats as document-owned.
7
- *
8
- * These attributes are synchronized from the incoming document during navigation.
9
- * Other root attributes are preserved unless explicitly included.
10
- */
11
- export declare const defaultDocumentElementAttributesToSync: string[];
12
5
  /**
13
6
  * Synchronizes a selected set of root `<html>` attributes from an incoming document
14
7
  * onto the current live document.
@@ -1,20 +1,30 @@
1
- import { DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC } from "./types.js";
2
- const defaultDocumentElementAttributesToSync = DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC;
3
- function syncDocumentElementAttributes(currentDocument, newDocument, attributes) {
4
- const currentHtml = currentDocument.documentElement;
5
- const nextHtml = newDocument.documentElement;
6
- for (const attributeName of attributes) {
7
- const nextValue = nextHtml.getAttribute(attributeName);
8
- if (nextValue === null) {
9
- currentHtml.removeAttribute(attributeName);
10
- continue;
1
+ /**
2
+ * Helpers for synchronizing selected root `<html>` attributes during client-side navigation.
3
+ * @module
4
+ */
5
+ /**
6
+ * Synchronizes a selected set of root `<html>` attributes from an incoming document
7
+ * onto the current live document.
8
+ *
9
+ * Attributes listed here are treated as document-owned metadata. Attributes not
10
+ * listed remain untouched on the live document so client-managed state can survive
11
+ * across navigation swaps.
12
+ *
13
+ * @param currentDocument - The live document being updated
14
+ * @param newDocument - The parsed incoming document for the next page
15
+ * @param attributes - Root `<html>` attributes to synchronize
16
+ */
17
+ export function syncDocumentElementAttributes(currentDocument, newDocument, attributes) {
18
+ const currentHtml = currentDocument.documentElement;
19
+ const nextHtml = newDocument.documentElement;
20
+ for (const attributeName of attributes) {
21
+ const nextValue = nextHtml.getAttribute(attributeName);
22
+ if (nextValue === null) {
23
+ currentHtml.removeAttribute(attributeName);
24
+ continue;
25
+ }
26
+ if (currentHtml.getAttribute(attributeName) !== nextValue) {
27
+ currentHtml.setAttribute(attributeName, nextValue);
28
+ }
11
29
  }
12
- if (currentHtml.getAttribute(attributeName) !== nextValue) {
13
- currentHtml.setAttribute(attributeName, nextValue);
14
- }
15
- }
16
30
  }
17
- export {
18
- defaultDocumentElementAttributesToSync,
19
- syncDocumentElementAttributes
20
- };
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Manually attaches declarative shadow DOM templates.
3
+ *
4
+ * @remarks
5
+ * Browsers only process `<template shadowrootmode>` during initial parse.
6
+ */
7
+ export declare function processDeclarativeShadowDOM(root: Element | Document | ShadowRoot): void;
8
+ /**
9
+ * Morphs document body using morphdom.
10
+ *
11
+ * @remarks
12
+ * Preserves persisted elements and hydrated custom elements.
13
+ * Light-DOM custom elements are fully replaced to trigger proper
14
+ * disconnectedCallback → connectedCallback lifecycle.
15
+ */
16
+ export declare function morphBody(newDocument: Document, persistAttribute: string): void;
17
+ /**
18
+ * Replaces body content in a single operation.
19
+ *
20
+ * @remarks
21
+ * Preserves persisted elements by moving them to the new body.
22
+ * Use when View Transitions are disabled.
23
+ */
24
+ export declare function replaceBody(newDocument: Document, persistAttribute: string): void;
@@ -0,0 +1,143 @@
1
+ import morphdom from 'morphdom';
2
+ const DEFAULT_PERSIST_ATTR = 'data-eco-persist';
3
+ function isPersisted(element, persistAttribute) {
4
+ return element.hasAttribute(persistAttribute) || element.hasAttribute(DEFAULT_PERSIST_ATTR);
5
+ }
6
+ function isHydratedCustomElement(element) {
7
+ return element.localName.includes('-') && element.shadowRoot !== null;
8
+ }
9
+ /**
10
+ * Returns the only body-morph keys that browser-router should trust.
11
+ *
12
+ * @remarks
13
+ * morphdom defaults to treating every `id` attribute as a structural key.
14
+ * That is fragile for content-heavy pages where repeated heading ids or other
15
+ * invalid-but-common markup can appear. Browser-router only needs stable keys
16
+ * for explicitly persisted nodes, so all other elements fall back to normal
17
+ * tree-order diffing.
18
+ */
19
+ function getBodyMorphKey(element, persistAttribute) {
20
+ if (!(element instanceof Element)) {
21
+ return undefined;
22
+ }
23
+ return element.getAttribute(persistAttribute) || element.getAttribute(DEFAULT_PERSIST_ATTR) || undefined;
24
+ }
25
+ function isLightDomCustomElement(element) {
26
+ return element.localName.includes('-') && element.shadowRoot === null;
27
+ }
28
+ /**
29
+ * @returns Always `false` to tell morphdom to skip updating this element.
30
+ *
31
+ * @remarks
32
+ * Replacing elements during morphdom traversal mutates the live DOM tree,
33
+ * which can cause morphdom to skip siblings or process stale nodes.
34
+ * Deferring the replacement until after morphdom finishes avoids this.
35
+ */
36
+ function replaceCustomElement(fromEl, toEl, deferred) {
37
+ deferred.push({ from: fromEl, to: toEl.cloneNode(true) });
38
+ return false;
39
+ }
40
+ function materializeCustomElement(element) {
41
+ const materializedElement = document.createElement(element.localName);
42
+ for (const attr of element.attributes) {
43
+ materializedElement.setAttribute(attr.name, attr.value);
44
+ }
45
+ materializedElement.innerHTML = element.innerHTML;
46
+ return materializedElement;
47
+ }
48
+ /**
49
+ * @remarks
50
+ * Each element is recreated via `document.createElement` so the browser fires
51
+ * the full custom element lifecycle (`disconnectedCallback` on the old instance,
52
+ * `connectedCallback` on the new one). Elements that were already removed during
53
+ * the morph pass are skipped via the `isConnected` guard.
54
+ */
55
+ function flushDeferredCustomElementReplacements(deferred) {
56
+ for (const { from, to } of deferred) {
57
+ if (!from.isConnected)
58
+ continue;
59
+ const newEl = materializeCustomElement(to);
60
+ from.replaceWith(newEl);
61
+ }
62
+ }
63
+ /**
64
+ * Manually attaches declarative shadow DOM templates.
65
+ *
66
+ * @remarks
67
+ * Browsers only process `<template shadowrootmode>` during initial parse.
68
+ */
69
+ export function processDeclarativeShadowDOM(root) {
70
+ const templates = root.querySelectorAll('template[shadowrootmode], template[shadowroot]');
71
+ for (const template of templates) {
72
+ const mode = (template.getAttribute('shadowrootmode') || template.getAttribute('shadowroot'));
73
+ const parent = template.parentElement;
74
+ if (parent && !parent.shadowRoot) {
75
+ const shadowRoot = parent.attachShadow({ mode });
76
+ shadowRoot.appendChild(template.content);
77
+ template.remove();
78
+ processDeclarativeShadowDOM(shadowRoot);
79
+ }
80
+ }
81
+ }
82
+ /**
83
+ * Morphs document body using morphdom.
84
+ *
85
+ * @remarks
86
+ * Preserves persisted elements and hydrated custom elements.
87
+ * Light-DOM custom elements are fully replaced to trigger proper
88
+ * disconnectedCallback → connectedCallback lifecycle.
89
+ */
90
+ export function morphBody(newDocument, persistAttribute) {
91
+ const deferredReplacements = [];
92
+ morphdom(document.body, newDocument.body, {
93
+ getNodeKey: (node) => getBodyMorphKey(node, persistAttribute),
94
+ onBeforeNodeAdded: (node) => {
95
+ if (node instanceof Element && isLightDomCustomElement(node)) {
96
+ return materializeCustomElement(node);
97
+ }
98
+ return node;
99
+ },
100
+ onBeforeElUpdated: (fromEl, toEl) => {
101
+ if (isPersisted(fromEl, persistAttribute)) {
102
+ return false;
103
+ }
104
+ if (isHydratedCustomElement(fromEl)) {
105
+ return replaceCustomElement(fromEl, toEl, deferredReplacements);
106
+ }
107
+ if (isLightDomCustomElement(fromEl)) {
108
+ return replaceCustomElement(fromEl, toEl, deferredReplacements);
109
+ }
110
+ if (fromEl.isEqualNode(toEl)) {
111
+ return false;
112
+ }
113
+ return true;
114
+ },
115
+ });
116
+ flushDeferredCustomElementReplacements(deferredReplacements);
117
+ processDeclarativeShadowDOM(document.body);
118
+ }
119
+ /**
120
+ * Replaces body content in a single operation.
121
+ *
122
+ * @remarks
123
+ * Preserves persisted elements by moving them to the new body.
124
+ * Use when View Transitions are disabled.
125
+ */
126
+ export function replaceBody(newDocument, persistAttribute) {
127
+ const persistedElements = document.body.querySelectorAll(`[${persistAttribute}], [${DEFAULT_PERSIST_ATTR}]`);
128
+ const persistedMap = new Map();
129
+ for (const el of persistedElements) {
130
+ const key = el.getAttribute(persistAttribute) || el.getAttribute(DEFAULT_PERSIST_ATTR);
131
+ if (key) {
132
+ persistedMap.set(key, el);
133
+ }
134
+ }
135
+ for (const [key, oldEl] of persistedMap) {
136
+ const placeholder = newDocument.body.querySelector(`[${persistAttribute}="${key}"], [${DEFAULT_PERSIST_ATTR}="${key}"]`);
137
+ if (placeholder) {
138
+ placeholder.replaceWith(oldEl);
139
+ }
140
+ }
141
+ document.body.replaceChildren(...Array.from(newDocument.body.childNodes));
142
+ processDeclarativeShadowDOM(document.body);
143
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Handles DOM manipulation during client-side page transitions.
3
+ *
4
+ * @remarks
5
+ * Uses a hybrid approach inspired by Turbo:
6
+ * - Surgical head updates (no morphing) to prevent FOUC
7
+ * - Idiomorph for efficient body diffing
8
+ */
9
+ export declare class DomSwapper {
10
+ private persistAttribute;
11
+ private pendingHeadScripts;
12
+ private pendingRerunScripts;
13
+ constructor(persistAttribute: string);
14
+ parseHTML(html: string, url?: URL): Document;
15
+ preloadStylesheets(newDocument: Document): Promise<void>;
16
+ morphHead(newDocument: Document): {
17
+ bodyStrategy: 'morph' | 'replace';
18
+ };
19
+ /**
20
+ * Replays queued scripts after the body swap completes.
21
+ *
22
+ * @remarks
23
+ * Scripts are intentionally flushed after the new body is in place so DOM-
24
+ * dependent bootstraps bind against the incoming page rather than the page
25
+ * being replaced.
26
+ */
27
+ flushRerunScripts(): void;
28
+ morphBody(newDocument: Document): void;
29
+ replaceBody(newDocument: Document): void;
30
+ }
@@ -0,0 +1,52 @@
1
+ import { morphBody, replaceBody } from './body-morpher.js';
2
+ import { flushHeadScripts, flushRerunScripts as flushPendingRerunScripts, morphHead, } from './head-updater.js';
3
+ import { parseHTML } from './html-parser.js';
4
+ import { preloadStylesheets } from './stylesheet-preloader.js';
5
+ /**
6
+ * Handles DOM manipulation during client-side page transitions.
7
+ *
8
+ * @remarks
9
+ * Uses a hybrid approach inspired by Turbo:
10
+ * - Surgical head updates (no morphing) to prevent FOUC
11
+ * - Idiomorph for efficient body diffing
12
+ */
13
+ export class DomSwapper {
14
+ persistAttribute;
15
+ pendingHeadScripts = [];
16
+ pendingRerunScripts = [];
17
+ constructor(persistAttribute) {
18
+ this.persistAttribute = persistAttribute;
19
+ }
20
+ parseHTML(html, url) {
21
+ return parseHTML(html, url);
22
+ }
23
+ async preloadStylesheets(newDocument) {
24
+ return preloadStylesheets(newDocument);
25
+ }
26
+ morphHead(newDocument) {
27
+ const result = morphHead(newDocument, this.persistAttribute);
28
+ this.pendingHeadScripts = result.pendingHeadScripts;
29
+ this.pendingRerunScripts = result.pendingRerunScripts;
30
+ return { bodyStrategy: result.bodyStrategy };
31
+ }
32
+ /**
33
+ * Replays queued scripts after the body swap completes.
34
+ *
35
+ * @remarks
36
+ * Scripts are intentionally flushed after the new body is in place so DOM-
37
+ * dependent bootstraps bind against the incoming page rather than the page
38
+ * being replaced.
39
+ */
40
+ flushRerunScripts() {
41
+ flushHeadScripts(this.pendingHeadScripts);
42
+ this.pendingHeadScripts = [];
43
+ flushPendingRerunScripts(this.pendingRerunScripts);
44
+ this.pendingRerunScripts = [];
45
+ }
46
+ morphBody(newDocument) {
47
+ morphBody(newDocument, this.persistAttribute);
48
+ }
49
+ replaceBody(newDocument) {
50
+ replaceBody(newDocument, this.persistAttribute);
51
+ }
52
+ }
@@ -0,0 +1,42 @@
1
+ import { type PendingRerunScript } from '@ecopages/core/client/navigation-scripts';
2
+ export type PendingHeadScript = {
3
+ attributes: Array<[string, string]>;
4
+ textContent: string;
5
+ src: string | null;
6
+ scriptId: string | null;
7
+ replaceExisting: boolean;
8
+ };
9
+ export type MorphHeadResult = {
10
+ bodyStrategy: 'morph' | 'replace';
11
+ pendingHeadScripts: PendingHeadScript[];
12
+ pendingRerunScripts: PendingRerunScript[];
13
+ };
14
+ /**
15
+ * Derives a stable identity key for a head script.
16
+ *
17
+ * @remarks
18
+ * Priority: `data-eco-script-id` / `id` > `src` > trimmed inline content.
19
+ * Returns `null` for empty anonymous inline scripts that cannot be tracked.
20
+ */
21
+ export declare function getHeadScriptKey(script: HTMLScriptElement | Pick<PendingHeadScript | PendingRerunScript, 'scriptId' | 'src' | 'textContent'>): string | null;
22
+ /**
23
+ * Updates document head using Turbo-style surgical updates.
24
+ *
25
+ * @remarks
26
+ * This approach avoids morphing the head element entirely, which prevents
27
+ * browser repaints that cause FOUC. Instead, it:
28
+ * - Updates the document title
29
+ * - Merges meta tags (adds new, updates changed)
30
+ * - Leaves stylesheets untouched (they're preloaded separately)
31
+ * - Handles script re-execution for marked scripts
32
+ * - Injects new scripts from the incoming page that are absent from the current head
33
+ */
34
+ export declare function morphHead(newDocument: Document, persistAttribute: string): MorphHeadResult;
35
+ /**
36
+ * Replays queued head scripts after the body swap completes.
37
+ */
38
+ export declare function flushHeadScripts(pendingHeadScripts: PendingHeadScript[]): void;
39
+ /**
40
+ * Replays queued `data-eco-rerun` scripts after the body swap completes.
41
+ */
42
+ export declare function flushRerunScripts(pendingRerunScripts: PendingRerunScript[]): void;
@@ -0,0 +1,194 @@
1
+ import { RERUN_SRC_ATTR, collectRerunScripts, flushPendingRerunScripts, isNonExecutableHeadScript, shouldPersistExecutableInlineHeadScript, } from '@ecopages/core/client/navigation-scripts';
2
+ const DEFAULT_PERSIST_ATTR = 'data-eco-persist';
3
+ function isPersisted(element, persistAttribute) {
4
+ return element.hasAttribute(persistAttribute) || element.hasAttribute(DEFAULT_PERSIST_ATTR);
5
+ }
6
+ /**
7
+ * Derives a stable identity key for a head script.
8
+ *
9
+ * @remarks
10
+ * Priority: `data-eco-script-id` / `id` > `src` > trimmed inline content.
11
+ * Returns `null` for empty anonymous inline scripts that cannot be tracked.
12
+ */
13
+ export function getHeadScriptKey(script) {
14
+ const scriptId = script instanceof HTMLScriptElement
15
+ ? script.getAttribute('data-eco-script-id') || script.getAttribute('id')
16
+ : script.scriptId;
17
+ if (scriptId) {
18
+ return `id:${scriptId}`;
19
+ }
20
+ const src = script instanceof HTMLScriptElement
21
+ ? script.getAttribute(RERUN_SRC_ATTR) || script.getAttribute('src')
22
+ : script.src;
23
+ if (src) {
24
+ return `src:${src}`;
25
+ }
26
+ const textContent = (script.textContent ?? '').trim();
27
+ return textContent ? `inline:${textContent}` : null;
28
+ }
29
+ function findExistingHeadScript(script) {
30
+ const scriptKey = getHeadScriptKey(script);
31
+ if (!scriptKey) {
32
+ return null;
33
+ }
34
+ return (Array.from(document.head.querySelectorAll('script')).find((candidate) => getHeadScriptKey(candidate) === scriptKey) ?? null);
35
+ }
36
+ function areHeadScriptsEquivalent(nextScript, currentScript) {
37
+ if (getHeadScriptKey(nextScript) !== getHeadScriptKey(currentScript)) {
38
+ return false;
39
+ }
40
+ if ((nextScript.textContent ?? '') !== (currentScript.textContent ?? '')) {
41
+ return false;
42
+ }
43
+ const nextAttributes = Array.from(nextScript.attributes).map((attribute) => [attribute.name, attribute.value]);
44
+ const currentAttributes = Array.from(currentScript.attributes).map((attribute) => [
45
+ attribute.name,
46
+ attribute.value,
47
+ ]);
48
+ if (nextAttributes.length !== currentAttributes.length) {
49
+ return false;
50
+ }
51
+ return nextAttributes.every(([name, value], index) => currentAttributes[index]?.[0] === name && currentAttributes[index]?.[1] === value);
52
+ }
53
+ /**
54
+ * Removes head scripts that are no longer present in the incoming document.
55
+ *
56
+ * @remarks
57
+ * Persisted scripts and executable inline scripts with stable identifiers
58
+ * are kept to avoid breaking long-lived runtime state.
59
+ */
60
+ function removeStaleHeadScripts(newDocument, persistAttribute) {
61
+ const nextScriptKeys = new Set(Array.from(newDocument.head.querySelectorAll('script'))
62
+ .map((script) => getHeadScriptKey(script))
63
+ .filter((key) => key !== null));
64
+ for (const script of Array.from(document.head.querySelectorAll('script'))) {
65
+ const key = getHeadScriptKey(script);
66
+ if (!key || nextScriptKeys.has(key)) {
67
+ continue;
68
+ }
69
+ if (isPersisted(script, persistAttribute)) {
70
+ continue;
71
+ }
72
+ if (shouldPersistExecutableInlineHeadScript(script)) {
73
+ continue;
74
+ }
75
+ script.remove();
76
+ }
77
+ }
78
+ /**
79
+ * Updates document head using Turbo-style surgical updates.
80
+ *
81
+ * @remarks
82
+ * This approach avoids morphing the head element entirely, which prevents
83
+ * browser repaints that cause FOUC. Instead, it:
84
+ * - Updates the document title
85
+ * - Merges meta tags (adds new, updates changed)
86
+ * - Leaves stylesheets untouched (they're preloaded separately)
87
+ * - Handles script re-execution for marked scripts
88
+ * - Injects new scripts from the incoming page that are absent from the current head
89
+ */
90
+ export function morphHead(newDocument, persistAttribute) {
91
+ const pendingHeadScripts = [];
92
+ const pendingRerunScripts = collectRerunScripts(newDocument);
93
+ removeStaleHeadScripts(newDocument, persistAttribute);
94
+ const newTitle = newDocument.head.querySelector('title');
95
+ if (newTitle && document.title !== newTitle.textContent) {
96
+ document.title = newTitle.textContent || '';
97
+ }
98
+ const newMetas = newDocument.head.querySelectorAll('meta[name], meta[property]');
99
+ for (const newMeta of newMetas) {
100
+ const name = newMeta.getAttribute('name');
101
+ const property = newMeta.getAttribute('property');
102
+ const content = newMeta.getAttribute('content');
103
+ const selector = name ? `meta[name="${name}"]` : `meta[property="${property}"]`;
104
+ const existingMeta = document.head.querySelector(selector);
105
+ if (existingMeta) {
106
+ if (existingMeta.getAttribute('content') !== content) {
107
+ existingMeta.setAttribute('content', content || '');
108
+ }
109
+ }
110
+ else {
111
+ document.head.appendChild(newMeta.cloneNode(true));
112
+ }
113
+ }
114
+ const existingScriptSrcs = new Set(Array.from(document.head.querySelectorAll('script[src]')).map((s) => s.getAttribute('src')));
115
+ const existingInlineContents = new Set(Array.from(document.head.querySelectorAll('script:not([src])')).map((s) => (s.textContent ?? '').trim()));
116
+ const allNewHeadScripts = newDocument.head.querySelectorAll('script');
117
+ for (const script of allNewHeadScripts) {
118
+ if (script.hasAttribute('data-eco-rerun'))
119
+ continue;
120
+ const src = script.getAttribute('src');
121
+ const scriptId = script.getAttribute('data-eco-script-id') || script.getAttribute('id');
122
+ const existingScript = findExistingHeadScript(script);
123
+ if (scriptId && existingScript) {
124
+ if (!isNonExecutableHeadScript(script)) {
125
+ continue;
126
+ }
127
+ if (areHeadScriptsEquivalent(script, existingScript)) {
128
+ continue;
129
+ }
130
+ pendingHeadScripts.push({
131
+ attributes: Array.from(script.attributes).map((attr) => [attr.name, attr.value]),
132
+ textContent: script.textContent ?? '',
133
+ src,
134
+ scriptId,
135
+ replaceExisting: true,
136
+ });
137
+ continue;
138
+ }
139
+ if (src) {
140
+ if (existingScriptSrcs.has(src))
141
+ continue;
142
+ pendingHeadScripts.push({
143
+ attributes: Array.from(script.attributes).map((attr) => [attr.name, attr.value]),
144
+ textContent: script.textContent ?? '',
145
+ src,
146
+ scriptId,
147
+ replaceExisting: false,
148
+ });
149
+ existingScriptSrcs.add(src);
150
+ }
151
+ else {
152
+ const content = (script.textContent ?? '').trim();
153
+ if (!content || existingInlineContents.has(content))
154
+ continue;
155
+ pendingHeadScripts.push({
156
+ attributes: Array.from(script.attributes).map((attr) => [attr.name, attr.value]),
157
+ textContent: script.textContent ?? '',
158
+ src: null,
159
+ scriptId,
160
+ replaceExisting: false,
161
+ });
162
+ existingInlineContents.add(content);
163
+ }
164
+ }
165
+ return {
166
+ bodyStrategy: pendingRerunScripts.length > 0 ? 'replace' : 'morph',
167
+ pendingHeadScripts,
168
+ pendingRerunScripts,
169
+ };
170
+ }
171
+ /**
172
+ * Replays queued head scripts after the body swap completes.
173
+ */
174
+ export function flushHeadScripts(pendingHeadScripts) {
175
+ for (const script of pendingHeadScripts) {
176
+ const replacement = document.createElement('script');
177
+ for (const [name, value] of script.attributes) {
178
+ replacement.setAttribute(name, value);
179
+ }
180
+ replacement.textContent = script.textContent;
181
+ const existingScript = findExistingHeadScript(script);
182
+ if (script.replaceExisting && existingScript) {
183
+ existingScript.replaceWith(replacement);
184
+ continue;
185
+ }
186
+ document.head.appendChild(replacement);
187
+ }
188
+ }
189
+ /**
190
+ * Replays queued `data-eco-rerun` scripts after the body swap completes.
191
+ */
192
+ export function flushRerunScripts(pendingRerunScripts) {
193
+ flushPendingRerunScripts(pendingRerunScripts);
194
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Parses HTML string into a Document, injecting a temporary base tag for URL resolution.
3
+ */
4
+ export declare function parseHTML(html: string, url?: URL): Document;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Parses HTML string into a Document, injecting a temporary base tag for URL resolution.
3
+ */
4
+ export function parseHTML(html, url) {
5
+ const parser = new DOMParser();
6
+ const htmlToParse = url ? `<base href="${url.href}" data-eco-injected>${html}` : html;
7
+ return parser.parseFromString(htmlToParse, 'text/html');
8
+ }