@ecopages/browser-router 0.2.0-beta.31 → 0.2.0-beta.33

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.
@@ -1,173 +1,194 @@
1
- import {
2
- RERUN_SRC_ATTR,
3
- collectRerunScripts,
4
- flushPendingRerunScripts,
5
- isNonExecutableHeadScript,
6
- shouldPersistExecutableInlineHeadScript
7
- } from "@ecopages/core/client/navigation-scripts";
8
- const DEFAULT_PERSIST_ATTR = "data-eco-persist";
1
+ import { RERUN_SRC_ATTR, collectRerunScripts, flushPendingRerunScripts, isNonExecutableHeadScript, shouldPersistExecutableInlineHeadScript, } from '@ecopages/core/client/navigation-scripts';
2
+ const DEFAULT_PERSIST_ATTR = 'data-eco-persist';
9
3
  function isPersisted(element, persistAttribute) {
10
- return element.hasAttribute(persistAttribute) || element.hasAttribute(DEFAULT_PERSIST_ATTR);
4
+ return element.hasAttribute(persistAttribute) || element.hasAttribute(DEFAULT_PERSIST_ATTR);
11
5
  }
12
- function getHeadScriptKey(script) {
13
- const scriptId = script instanceof HTMLScriptElement ? script.getAttribute("data-eco-script-id") || script.getAttribute("id") : script.scriptId;
14
- if (scriptId) {
15
- return `id:${scriptId}`;
16
- }
17
- const src = script instanceof HTMLScriptElement ? script.getAttribute(RERUN_SRC_ATTR) || script.getAttribute("src") : script.src;
18
- if (src) {
19
- return `src:${src}`;
20
- }
21
- const textContent = (script.textContent ?? "").trim();
22
- return textContent ? `inline:${textContent}` : null;
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;
23
28
  }
24
29
  function findExistingHeadScript(script) {
25
- const scriptKey = getHeadScriptKey(script);
26
- if (!scriptKey) {
27
- return null;
28
- }
29
- return Array.from(document.head.querySelectorAll("script")).find(
30
- (candidate) => getHeadScriptKey(candidate) === scriptKey
31
- ) ?? null;
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);
32
35
  }
33
36
  function areHeadScriptsEquivalent(nextScript, currentScript) {
34
- if (getHeadScriptKey(nextScript) !== getHeadScriptKey(currentScript)) {
35
- return false;
36
- }
37
- if ((nextScript.textContent ?? "") !== (currentScript.textContent ?? "")) {
38
- return false;
39
- }
40
- const nextAttributes = Array.from(nextScript.attributes).map((attribute) => [attribute.name, attribute.value]);
41
- const currentAttributes = Array.from(currentScript.attributes).map((attribute) => [
42
- attribute.name,
43
- attribute.value
44
- ]);
45
- if (nextAttributes.length !== currentAttributes.length) {
46
- return false;
47
- }
48
- return nextAttributes.every(
49
- ([name, value], index) => currentAttributes[index]?.[0] === name && currentAttributes[index]?.[1] === value
50
- );
51
- }
52
- function removeStaleHeadScripts(newDocument, persistAttribute) {
53
- const nextScriptKeys = new Set(
54
- Array.from(newDocument.head.querySelectorAll("script")).map((script) => getHeadScriptKey(script)).filter((key) => key !== null)
55
- );
56
- for (const script of Array.from(document.head.querySelectorAll("script"))) {
57
- const key = getHeadScriptKey(script);
58
- if (!key || nextScriptKeys.has(key)) {
59
- continue;
37
+ if (getHeadScriptKey(nextScript) !== getHeadScriptKey(currentScript)) {
38
+ return false;
60
39
  }
61
- if (isPersisted(script, persistAttribute)) {
62
- continue;
40
+ if ((nextScript.textContent ?? '') !== (currentScript.textContent ?? '')) {
41
+ return false;
63
42
  }
64
- if (shouldPersistExecutableInlineHeadScript(script)) {
65
- continue;
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;
66
50
  }
67
- script.remove();
68
- }
51
+ return nextAttributes.every(([name, value], index) => currentAttributes[index]?.[0] === name && currentAttributes[index]?.[1] === value);
69
52
  }
70
- function morphHead(newDocument, persistAttribute) {
71
- const pendingHeadScripts = [];
72
- const pendingRerunScripts = collectRerunScripts(newDocument);
73
- removeStaleHeadScripts(newDocument, persistAttribute);
74
- const newTitle = newDocument.head.querySelector("title");
75
- if (newTitle && document.title !== newTitle.textContent) {
76
- document.title = newTitle.textContent || "";
77
- }
78
- const newMetas = newDocument.head.querySelectorAll("meta[name], meta[property]");
79
- for (const newMeta of newMetas) {
80
- const name = newMeta.getAttribute("name");
81
- const property = newMeta.getAttribute("property");
82
- const content = newMeta.getAttribute("content");
83
- const selector = name ? `meta[name="${name}"]` : `meta[property="${property}"]`;
84
- const existingMeta = document.head.querySelector(selector);
85
- if (existingMeta) {
86
- if (existingMeta.getAttribute("content") !== content) {
87
- existingMeta.setAttribute("content", content || "");
88
- }
89
- } else {
90
- document.head.appendChild(newMeta.cloneNode(true));
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();
91
76
  }
92
- }
93
- const existingScriptSrcs = new Set(
94
- Array.from(document.head.querySelectorAll("script[src]")).map((s) => s.getAttribute("src"))
95
- );
96
- const existingInlineContents = new Set(
97
- Array.from(document.head.querySelectorAll("script:not([src])")).map((s) => (s.textContent ?? "").trim())
98
- );
99
- const allNewHeadScripts = newDocument.head.querySelectorAll("script");
100
- for (const script of allNewHeadScripts) {
101
- if (script.hasAttribute("data-eco-rerun")) continue;
102
- const src = script.getAttribute("src");
103
- const scriptId = script.getAttribute("data-eco-script-id") || script.getAttribute("id");
104
- const existingScript = findExistingHeadScript(script);
105
- if (scriptId && existingScript) {
106
- if (!isNonExecutableHeadScript(script)) {
107
- continue;
108
- }
109
- if (areHeadScriptsEquivalent(script, existingScript)) {
110
- continue;
111
- }
112
- pendingHeadScripts.push({
113
- attributes: Array.from(script.attributes).map((attr) => [attr.name, attr.value]),
114
- textContent: script.textContent ?? "",
115
- src,
116
- scriptId,
117
- replaceExisting: true
118
- });
119
- continue;
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 || '';
120
97
  }
121
- if (src) {
122
- if (existingScriptSrcs.has(src)) continue;
123
- pendingHeadScripts.push({
124
- attributes: Array.from(script.attributes).map((attr) => [attr.name, attr.value]),
125
- textContent: script.textContent ?? "",
126
- src,
127
- scriptId,
128
- replaceExisting: false
129
- });
130
- existingScriptSrcs.add(src);
131
- } else {
132
- const content = (script.textContent ?? "").trim();
133
- if (!content || existingInlineContents.has(content)) continue;
134
- pendingHeadScripts.push({
135
- attributes: Array.from(script.attributes).map((attr) => [attr.name, attr.value]),
136
- textContent: script.textContent ?? "",
137
- src: null,
138
- scriptId,
139
- replaceExisting: false
140
- });
141
- existingInlineContents.add(content);
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
+ }
142
113
  }
143
- }
144
- return {
145
- bodyStrategy: pendingRerunScripts.length > 0 ? "replace" : "morph",
146
- pendingHeadScripts,
147
- pendingRerunScripts
148
- };
149
- }
150
- function flushHeadScripts(pendingHeadScripts) {
151
- for (const script of pendingHeadScripts) {
152
- const replacement = document.createElement("script");
153
- for (const [name, value] of script.attributes) {
154
- replacement.setAttribute(name, value);
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
+ }
155
164
  }
156
- replacement.textContent = script.textContent;
157
- const existingScript = findExistingHeadScript(script);
158
- if (script.replaceExisting && existingScript) {
159
- existingScript.replaceWith(replacement);
160
- continue;
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);
161
187
  }
162
- document.head.appendChild(replacement);
163
- }
164
188
  }
165
- function flushRerunScripts(pendingRerunScripts) {
166
- flushPendingRerunScripts(pendingRerunScripts);
189
+ /**
190
+ * Replays queued `data-eco-rerun` scripts after the body swap completes.
191
+ */
192
+ export function flushRerunScripts(pendingRerunScripts) {
193
+ flushPendingRerunScripts(pendingRerunScripts);
167
194
  }
168
- export {
169
- flushHeadScripts,
170
- flushRerunScripts,
171
- getHeadScriptKey,
172
- morphHead
173
- };
@@ -1,8 +1,8 @@
1
- function parseHTML(html, url) {
2
- const parser = new DOMParser();
3
- const htmlToParse = url ? `<base href="${url.href}" data-eco-injected>${html}` : html;
4
- return parser.parseFromString(htmlToParse, "text/html");
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');
5
8
  }
6
- export {
7
- parseHTML
8
- };
@@ -1,20 +1,24 @@
1
- function getCurrentStylesheetHrefs() {
2
- return new Set(
3
- Array.from(document.head.querySelectorAll('link[rel="stylesheet"]')).map((link) => link.href)
4
- );
1
+ /**
2
+ * Shared stylesheet href discovery for navigation prefetch and commit.
3
+ * @module
4
+ */
5
+ /**
6
+ * Returns resolved stylesheet hrefs currently in the document head.
7
+ */
8
+ export function getCurrentStylesheetHrefs() {
9
+ return new Set(Array.from(document.head.querySelectorAll('link[rel="stylesheet"]')).map((link) => link.href));
5
10
  }
6
- function discoverNewStylesheetLinks(source, existingHrefs = getCurrentStylesheetHrefs()) {
7
- const discovered = [];
8
- for (const link of source.head.querySelectorAll('link[rel="stylesheet"]')) {
9
- if (existingHrefs.has(link.href)) {
10
- continue;
11
+ /**
12
+ * Returns stylesheet links present in `source` but not in `existingHrefs`.
13
+ */
14
+ export function discoverNewStylesheetLinks(source, existingHrefs = getCurrentStylesheetHrefs()) {
15
+ const discovered = [];
16
+ for (const link of source.head.querySelectorAll('link[rel="stylesheet"]')) {
17
+ if (existingHrefs.has(link.href)) {
18
+ continue;
19
+ }
20
+ existingHrefs.add(link.href);
21
+ discovered.push(link);
11
22
  }
12
- existingHrefs.add(link.href);
13
- discovered.push(link);
14
- }
15
- return discovered;
23
+ return discovered;
16
24
  }
17
- export {
18
- discoverNewStylesheetLinks,
19
- getCurrentStylesheetHrefs
20
- };
@@ -1,38 +1,44 @@
1
- import { discoverNewStylesheetLinks, getCurrentStylesheetHrefs } from "./stylesheet-discovery.js";
2
- async function preloadStylesheets(newDocument) {
3
- const newStylesheetLinks = discoverNewStylesheetLinks(newDocument, getCurrentStylesheetHrefs());
4
- if (newStylesheetLinks.length === 0) {
5
- return;
6
- }
7
- const TIMEOUT = 5e3;
8
- const loadPromises = newStylesheetLinks.map((link) => {
9
- return new Promise((resolve) => {
10
- const newLink = document.createElement("link");
11
- newLink.rel = "stylesheet";
12
- newLink.media = link.media || "all";
13
- const timeoutId = setTimeout(() => {
14
- cleanup();
15
- resolve();
16
- }, TIMEOUT);
17
- const cleanup = () => {
18
- clearTimeout(timeoutId);
19
- newLink.onload = null;
20
- newLink.onerror = null;
21
- };
22
- newLink.onload = () => {
23
- cleanup();
24
- resolve();
25
- };
26
- newLink.onerror = () => {
27
- cleanup();
28
- resolve();
29
- };
30
- newLink.href = link.href;
31
- document.head.appendChild(newLink);
1
+ import { discoverNewStylesheetLinks, getCurrentStylesheetHrefs } from './stylesheet-discovery.js';
2
+ /**
3
+ * Preloads new stylesheets from target document to prevent FOUC.
4
+ *
5
+ * @remarks
6
+ * Discovers stylesheet links in the target document that aren't present in the
7
+ * current document, creates corresponding link elements, and waits for all to
8
+ * load before resolving. This follows Turbo's approach of waiting for stylesheets
9
+ * before any DOM updates.
10
+ */
11
+ export async function preloadStylesheets(newDocument) {
12
+ const newStylesheetLinks = discoverNewStylesheetLinks(newDocument, getCurrentStylesheetHrefs());
13
+ if (newStylesheetLinks.length === 0) {
14
+ return;
15
+ }
16
+ const TIMEOUT = 5000;
17
+ const loadPromises = newStylesheetLinks.map((link) => {
18
+ return new Promise((resolve) => {
19
+ const newLink = document.createElement('link');
20
+ newLink.rel = 'stylesheet';
21
+ newLink.media = link.media || 'all';
22
+ const timeoutId = setTimeout(() => {
23
+ cleanup();
24
+ resolve();
25
+ }, TIMEOUT);
26
+ const cleanup = () => {
27
+ clearTimeout(timeoutId);
28
+ newLink.onload = null;
29
+ newLink.onerror = null;
30
+ };
31
+ newLink.onload = () => {
32
+ cleanup();
33
+ resolve();
34
+ };
35
+ newLink.onerror = () => {
36
+ cleanup();
37
+ resolve();
38
+ };
39
+ newLink.href = link.href;
40
+ document.head.appendChild(newLink);
41
+ });
32
42
  });
33
- });
34
- await Promise.all(loadPromises);
43
+ await Promise.all(loadPromises);
35
44
  }
36
- export {
37
- preloadStylesheets
38
- };
@@ -2,7 +2,7 @@
2
2
  * Client-side router for Ecopages with morphdom-based DOM diffing.
3
3
  * @module eco-router
4
4
  */
5
- import type { EcoRouterOptions } from './types.js';
5
+ import { type EcoRouterOptions } from './types.js';
6
6
  /**
7
7
  * Intercepts same-origin link clicks and performs client-side navigation
8
8
  * using morphdom for efficient DOM diffing. Supports View Transitions API.