@ecopages/browser-router 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +27 -8
  2. package/package.json +11 -8
  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 +27 -0
  6. package/src/client/dom/body-morpher.js +166 -0
  7. package/src/client/dom/stylesheet-discovery.d.ts +12 -0
  8. package/src/client/dom/stylesheet-discovery.js +24 -0
  9. package/src/client/eco-router-perform-navigation.d.ts +20 -0
  10. package/src/client/eco-router-perform-navigation.js +31 -0
  11. package/src/client/eco-router.d.ts +11 -41
  12. package/src/client/eco-router.js +330 -479
  13. package/src/client/index.d.ts +3 -0
  14. package/src/client/index.js +3 -0
  15. package/src/client/navigation-commit-reload.d.ts +21 -0
  16. package/src/client/navigation-commit-reload.js +16 -0
  17. package/src/client/navigation-commit.d.ts +17 -0
  18. package/src/client/navigation-commit.js +82 -0
  19. package/src/client/services/prefetch-manager.d.ts +15 -39
  20. package/src/client/services/prefetch-manager.js +327 -360
  21. package/src/client/types.d.ts +16 -16
  22. package/src/client/types.js +21 -20
  23. package/src/index.d.ts +1 -5
  24. package/src/index.js +6 -18
  25. package/CHANGELOG.md +0 -25
  26. package/src/client/services/dom-swapper.d.ts +0 -166
  27. package/src/client/services/dom-swapper.js +0 -497
  28. package/src/client/services/index.d.ts +0 -8
  29. package/src/client/services/index.js +0 -10
  30. package/src/client/services/scroll-manager.d.ts +0 -19
  31. package/src/client/services/scroll-manager.js +0 -36
  32. package/src/client/services/view-transition-manager.d.ts +0 -29
  33. package/src/client/services/view-transition-manager.js +0 -54
  34. package/src/client/view-transition-utils.d.ts +0 -14
  35. package/src/client/view-transition-utils.js +0 -60
  36. package/src/styles.css +0 -218
  37. package/src/types.d.ts +0 -15
  38. package/src/types.js +0 -5
@@ -1,379 +1,346 @@
1
+ /**
2
+ * Prefetch manager for client-side navigation.
3
+ * Uses a single IntersectionObserver and hover detection for optimal performance.
4
+ * @module prefetch-manager
5
+ */
6
+ import { cacheNavigationHtml, fetchNavigationPage, invalidateNavigationHtml } from '@ecopages/core/client';
7
+ import { isSamePageHref, shouldPrefetchLink } from '@ecopages/core/client';
8
+ import { discoverNewStylesheetLinks, getCurrentStylesheetHrefs } from '../dom/stylesheet-discovery.js';
1
9
  const DEFAULT_PREFETCH_OPTIONS = {
2
- strategy: "intent",
3
- delay: 65,
4
- noPrefetchAttribute: "data-eco-no-prefetch",
5
- respectDataSaver: true,
6
- linkSelector: "a[href]"
10
+ strategy: 'intent',
11
+ delay: 65,
12
+ reloadAttribute: 'data-eco-reload',
13
+ noPrefetchAttribute: 'data-eco-no-prefetch',
14
+ respectDataSaver: true,
15
+ linkSelector: 'a[href]',
7
16
  };
8
- class PrefetchManager {
9
- options;
10
- prefetched = /* @__PURE__ */ new Set();
11
- htmlCache = /* @__PURE__ */ new Map();
12
- observer = null;
13
- hoverTimeouts = /* @__PURE__ */ new Map();
14
- constructor(options) {
15
- this.options = { ...DEFAULT_PREFETCH_OPTIONS, ...options };
16
- }
17
- /**
18
- * Initializes prefetching based on the configured strategy.
19
- *
20
- * Sets up IntersectionObserver for viewport-based prefetching and/or
21
- * hover/focus listeners for intent-based prefetching. Immediately begins
22
- * observing existing links on the page.
23
- */
24
- start() {
25
- if (!this.shouldPrefetch()) return;
26
- if (this.options.strategy === "viewport" || this.options.strategy === "intent") {
27
- this.setupIntersectionObserver();
17
+ export class PrefetchManager {
18
+ options;
19
+ prefetched = new Set();
20
+ prefetchedStylesheets = new Set();
21
+ observer = null;
22
+ hoverTimeouts = new Map();
23
+ constructor(options) {
24
+ this.options = { ...DEFAULT_PREFETCH_OPTIONS, ...options };
28
25
  }
29
- if (this.options.strategy === "hover" || this.options.strategy === "intent") {
30
- this.setupHoverListeners();
26
+ /**
27
+ * Initializes prefetching based on the configured strategy.
28
+ *
29
+ * Sets up IntersectionObserver for viewport-based prefetching and/or
30
+ * hover/focus listeners for intent-based prefetching. Immediately begins
31
+ * observing existing links on the page.
32
+ */
33
+ start() {
34
+ if (!this.shouldPrefetch())
35
+ return;
36
+ if (this.options.strategy === 'viewport' || this.options.strategy === 'intent') {
37
+ this.setupIntersectionObserver();
38
+ }
39
+ if (this.options.strategy === 'hover' || this.options.strategy === 'intent') {
40
+ this.setupHoverListeners();
41
+ }
42
+ this.observeLinks();
31
43
  }
32
- this.observeExistingLinks();
33
- }
34
- /**
35
- * Cleans up all prefetch-related observers and event listeners.
36
- * Cancels any pending hover timeouts.
37
- */
38
- stop() {
39
- this.observer?.disconnect();
40
- this.observer = null;
41
- document.removeEventListener("mouseover", this.handleMouseOver);
42
- document.removeEventListener("mouseout", this.handleMouseOut);
43
- document.removeEventListener("focusin", this.handleFocusIn);
44
- document.removeEventListener("focusout", this.handleFocusOut);
45
- this.hoverTimeouts.forEach((timeout) => clearTimeout(timeout));
46
- this.hoverTimeouts.clear();
47
- }
48
- /**
49
- * Fetches and caches HTML content for a given URL.
50
- *
51
- * Skips cross-origin URLs or already-prefetched URLs. On success, both the
52
- * HTML content is cached and any new stylesheets are preloaded to prevent
53
- * FOUC during navigation.
54
- *
55
- * @param href - The URL to prefetch
56
- */
57
- async prefetch(href) {
58
- const url = new URL(href, window.location.origin);
59
- if (url.origin !== window.location.origin) return;
60
- if (this.prefetched.has(url.href)) return;
61
- const currentPath = window.location.pathname + window.location.search;
62
- const targetPath = url.pathname + url.search;
63
- if (currentPath === targetPath) return;
64
- this.prefetched.add(url.href);
65
- try {
66
- const response = await fetch(url.href, {
67
- headers: { Accept: "text/html" },
68
- priority: "low"
69
- });
70
- if (!response.ok) return;
71
- const html = await response.text();
72
- this.htmlCache.set(url.href, html);
73
- await this.prefetchStylesheets(html, url);
74
- } catch {
75
- this.prefetched.delete(url.href);
44
+ /**
45
+ * Cleans up all prefetch-related observers and event listeners.
46
+ * Cancels any pending hover timeouts.
47
+ */
48
+ stop() {
49
+ this.observer?.disconnect();
50
+ this.observer = null;
51
+ document.removeEventListener('mouseover', this.handleMouseOver);
52
+ document.removeEventListener('mouseout', this.handleMouseOut);
53
+ document.removeEventListener('focusin', this.handleFocusIn);
54
+ document.removeEventListener('focusout', this.handleFocusOut);
55
+ this.hoverTimeouts.forEach((timeout) => clearTimeout(timeout));
56
+ this.hoverTimeouts.clear();
76
57
  }
77
- }
78
- /**
79
- * Retrieves cached HTML for a URL.
80
- *
81
- * Returns cached content without consuming it, enabling stale-while-revalidate:
82
- * - Returns cached HTML immediately for instant navigation
83
- * - Use cacheVisitedPage() after navigation to update cache in background
84
- *
85
- * @param href - The URL to look up
86
- * @returns The cached HTML string, or null if not cached
87
- */
88
- getCachedHtml(href) {
89
- const url = new URL(href, window.location.origin);
90
- return this.htmlCache.get(url.href) ?? null;
91
- }
92
- invalidate(href) {
93
- const url = new URL(href, window.location.origin);
94
- this.htmlCache.delete(url.href);
95
- this.prefetched.delete(url.href);
96
- }
97
- /**
98
- * Caches HTML content for a visited page and triggers background revalidation.
99
- *
100
- * Implements stale-while-revalidate pattern:
101
- * - Immediately caches the provided HTML for instant revisits
102
- * - Fetches fresh content in background for next visit (unless it's the current page)
103
- *
104
- * @param href - The URL of the visited page
105
- * @param html - The HTML content to cache initially
106
- */
107
- cacheVisitedPage(href, html) {
108
- const url = new URL(href, window.location.origin);
109
- if (url.origin !== window.location.origin) return;
110
- this.htmlCache.set(url.href, html);
111
- this.prefetched.add(url.href);
112
- const currentPath = window.location.pathname + window.location.search;
113
- const targetPath = url.pathname + url.search;
114
- if (currentPath === targetPath) return;
115
- setTimeout(() => {
116
- fetch(url.href, {
117
- headers: { Accept: "text/html" },
118
- priority: "low"
119
- }).then((response) => {
120
- if (response.ok) return response.text();
121
- return null;
122
- }).then((freshHtml) => {
123
- if (freshHtml) {
124
- this.htmlCache.set(url.href, freshHtml);
58
+ /**
59
+ * Fetches and caches HTML content for a given URL.
60
+ *
61
+ * Skips cross-origin URLs or already-prefetched URLs. On success, both the
62
+ * HTML content is cached and any new stylesheets are preloaded to prevent
63
+ * FOUC during navigation.
64
+ *
65
+ * @param href - The URL to prefetch
66
+ */
67
+ async prefetch(href) {
68
+ const url = new URL(href, window.location.origin);
69
+ if (url.origin !== window.location.origin)
70
+ return;
71
+ if (this.prefetched.has(url.href))
72
+ return;
73
+ if (isSamePageHref(url.href))
74
+ return;
75
+ this.prefetched.add(url.href);
76
+ try {
77
+ const page = await fetchNavigationPage(url, { priority: 'low' });
78
+ if (!page) {
79
+ this.prefetched.delete(url.href);
80
+ return;
81
+ }
82
+ await this.prefetchStylesheets(page.document);
125
83
  }
126
- }).catch(() => {
127
- });
128
- }, 100);
129
- }
130
- /**
131
- * Checks if a URL has already been prefetched.
132
- * @param href - The URL to check
133
- */
134
- isPrefetched(href) {
135
- const url = new URL(href, window.location.origin);
136
- return this.prefetched.has(url.href);
137
- }
138
- /**
139
- * Determines if prefetching should be enabled based on network conditions.
140
- *
141
- * Respects the user's data saver settings and avoids prefetching on slow
142
- * connections (2g or slower) when `respectDataSaver` is enabled.
143
- */
144
- shouldPrefetch() {
145
- if (!this.options.respectDataSaver) return true;
146
- const conn = navigator.connection;
147
- if (!conn) return true;
148
- if (conn.saveData) return false;
149
- if (conn.effectiveType === "2g" || conn.effectiveType === "slow-2g") return false;
150
- return true;
151
- }
152
- /**
153
- * Creates an IntersectionObserver to prefetch links as they enter the viewport.
154
- *
155
- * Uses a 50px root margin to trigger prefetching slightly before elements
156
- * become visible, improving perceived performance.
157
- */
158
- setupIntersectionObserver() {
159
- this.observer = new IntersectionObserver(
160
- (entries) => {
161
- for (const entry of entries) {
162
- if (entry.isIntersecting) {
163
- const link = entry.target;
164
- const strategy = this.getLinkStrategy(link);
165
- if (strategy === "viewport" || strategy === "eager") {
166
- this.scheduleIdlePrefetch(link.href, strategy === "eager");
84
+ catch {
85
+ this.prefetched.delete(url.href);
86
+ }
87
+ }
88
+ invalidate(href) {
89
+ const url = new URL(href, window.location.origin);
90
+ invalidateNavigationHtml(url);
91
+ this.prefetched.delete(url.href);
92
+ }
93
+ /**
94
+ * Caches the HTML of a visited page so a revisit renders it immediately.
95
+ *
96
+ * @remarks
97
+ * The cached copy is not refreshed in the background. The page on screen was just fetched or loaded, so
98
+ * fetching it again would add a request to every page load and navigation without a stale copy to fix.
99
+ *
100
+ * @param href - The URL of the visited page
101
+ * @param html - The HTML content to cache
102
+ */
103
+ cacheVisitedPage(href, html) {
104
+ const url = new URL(href, window.location.origin);
105
+ if (url.origin !== window.location.origin)
106
+ return;
107
+ cacheNavigationHtml(url, html);
108
+ this.prefetched.add(url.href);
109
+ }
110
+ /**
111
+ * Determines if prefetching should be enabled based on network conditions.
112
+ *
113
+ * Respects the user's data saver settings and avoids prefetching on slow
114
+ * connections (2g or slower) when `respectDataSaver` is enabled.
115
+ */
116
+ shouldPrefetch() {
117
+ if (!this.options.respectDataSaver)
118
+ return true;
119
+ const conn = navigator.connection;
120
+ if (!conn)
121
+ return true;
122
+ if (conn.saveData)
123
+ return false;
124
+ if (conn.effectiveType === '2g' || conn.effectiveType === 'slow-2g')
125
+ return false;
126
+ return true;
127
+ }
128
+ /**
129
+ * Creates an IntersectionObserver to prefetch links as they enter the viewport.
130
+ *
131
+ * Uses a 50px root margin to trigger prefetching slightly before elements
132
+ * become visible, improving perceived performance.
133
+ */
134
+ setupIntersectionObserver() {
135
+ this.observer = new IntersectionObserver((entries) => {
136
+ for (const entry of entries) {
137
+ if (entry.isIntersecting) {
138
+ const link = entry.target;
139
+ if (!this.isEligiblePrefetchLink(link))
140
+ continue;
141
+ const strategy = this.getLinkStrategy(link);
142
+ if (strategy === 'viewport' || strategy === 'eager') {
143
+ this.scheduleIdlePrefetch(link.href, strategy === 'eager');
144
+ }
145
+ }
167
146
  }
168
- }
147
+ }, { rootMargin: '50px', threshold: 0 });
148
+ }
149
+ /**
150
+ * Attaches delegated event listeners for hover and focus-based prefetching.
151
+ *
152
+ * Uses event delegation on the document for efficient handling without
153
+ * attaching listeners to individual links.
154
+ */
155
+ setupHoverListeners() {
156
+ document.addEventListener('mouseover', this.handleMouseOver);
157
+ document.addEventListener('mouseout', this.handleMouseOut);
158
+ document.addEventListener('focusin', this.handleFocusIn);
159
+ document.addEventListener('focusout', this.handleFocusOut);
160
+ }
161
+ handleMouseOver = (event) => {
162
+ const link = this.getLinkFromEvent(event);
163
+ if (!link)
164
+ return;
165
+ const strategy = this.getLinkStrategy(link);
166
+ if (strategy === 'hover' || strategy === 'intent' || strategy === 'eager') {
167
+ const delay = strategy === 'eager' ? 0 : this.getLinkDelay(link);
168
+ this.scheduleHoverPrefetch(link.href, delay);
169
+ }
170
+ };
171
+ handleMouseOut = (event) => {
172
+ const link = this.getLinkFromEvent(event);
173
+ if (!link)
174
+ return;
175
+ this.cancelHoverPrefetch(link.href);
176
+ };
177
+ handleFocusIn = (event) => {
178
+ const link = this.getLinkFromEvent(event);
179
+ if (!link)
180
+ return;
181
+ const strategy = this.getLinkStrategy(link);
182
+ if (strategy === 'hover' || strategy === 'intent' || strategy === 'eager') {
183
+ const delay = strategy === 'eager' ? 0 : this.getLinkDelay(link);
184
+ this.scheduleHoverPrefetch(link.href, delay);
185
+ }
186
+ };
187
+ handleFocusOut = (event) => {
188
+ const link = this.getLinkFromEvent(event);
189
+ if (!link)
190
+ return;
191
+ this.cancelHoverPrefetch(link.href);
192
+ };
193
+ /**
194
+ * Extracts a valid anchor element from a DOM event.
195
+ *
196
+ * Returns null for links that should not be prefetched (opt-outs, downloads,
197
+ * hash links, javascript: URLs).
198
+ */
199
+ getLinkFromEvent(event) {
200
+ const target = event.target;
201
+ const link = target.closest(this.options.linkSelector);
202
+ if (!link)
203
+ return null;
204
+ if (!this.isEligiblePrefetchLink(link)) {
205
+ return null;
169
206
  }
170
- },
171
- { rootMargin: "50px", threshold: 0 }
172
- );
173
- }
174
- /**
175
- * Attaches delegated event listeners for hover and focus-based prefetching.
176
- *
177
- * Uses event delegation on the document for efficient handling without
178
- * attaching listeners to individual links.
179
- */
180
- setupHoverListeners() {
181
- document.addEventListener("mouseover", this.handleMouseOver);
182
- document.addEventListener("mouseout", this.handleMouseOut);
183
- document.addEventListener("focusin", this.handleFocusIn);
184
- document.addEventListener("focusout", this.handleFocusOut);
185
- }
186
- handleMouseOver = (event) => {
187
- const link = this.getLinkFromEvent(event);
188
- if (!link) return;
189
- const strategy = this.getLinkStrategy(link);
190
- if (strategy === "hover" || strategy === "intent" || strategy === "eager") {
191
- const delay = strategy === "eager" ? 0 : this.getLinkDelay(link);
192
- this.scheduleHoverPrefetch(link.href, delay);
207
+ return link;
193
208
  }
194
- };
195
- handleMouseOut = (event) => {
196
- const link = this.getLinkFromEvent(event);
197
- if (!link) return;
198
- this.cancelHoverPrefetch(link.href);
199
- };
200
- handleFocusIn = (event) => {
201
- const link = this.getLinkFromEvent(event);
202
- if (!link) return;
203
- const strategy = this.getLinkStrategy(link);
204
- if (strategy === "hover" || strategy === "intent" || strategy === "eager") {
205
- const delay = strategy === "eager" ? 0 : this.getLinkDelay(link);
206
- this.scheduleHoverPrefetch(link.href, delay);
209
+ isEligiblePrefetchLink(link) {
210
+ return shouldPrefetchLink(link, {
211
+ reloadAttribute: this.options.reloadAttribute,
212
+ noPrefetchAttribute: this.options.noPrefetchAttribute,
213
+ });
207
214
  }
208
- };
209
- handleFocusOut = (event) => {
210
- const link = this.getLinkFromEvent(event);
211
- if (!link) return;
212
- this.cancelHoverPrefetch(link.href);
213
- };
214
- /**
215
- * Extracts a valid anchor element from a DOM event.
216
- *
217
- * Returns null for links that should not be prefetched (opt-outs, downloads,
218
- * hash links, javascript: URLs).
219
- */
220
- getLinkFromEvent(event) {
221
- const target = event.target;
222
- const link = target.closest(this.options.linkSelector);
223
- if (!link) return null;
224
- if (link.hasAttribute(this.options.noPrefetchAttribute)) return null;
225
- if (link.hasAttribute("download")) return null;
226
- const href = link.getAttribute("href");
227
- if (!href || href.startsWith("#") || href.startsWith("javascript:")) return null;
228
- return link;
229
- }
230
- /**
231
- * Resolves the prefetch strategy for a link element.
232
- *
233
- * Checks for per-link overrides via `data-eco-prefetch` attribute,
234
- * falling back to the global strategy.
235
- */
236
- getLinkStrategy(link) {
237
- const override = link.getAttribute("data-eco-prefetch");
238
- if (override === "eager" || override === "viewport" || override === "hover" || override === "intent") {
239
- return override;
215
+ /**
216
+ * Resolves the prefetch strategy for a link element.
217
+ *
218
+ * Checks for per-link overrides via `data-eco-prefetch` attribute,
219
+ * falling back to the global strategy.
220
+ */
221
+ getLinkStrategy(link) {
222
+ const override = link.getAttribute('data-eco-prefetch');
223
+ if (override === 'eager' || override === 'viewport' || override === 'hover' || override === 'intent') {
224
+ return override;
225
+ }
226
+ return this.options.strategy;
240
227
  }
241
- return this.options.strategy;
242
- }
243
- /**
244
- * Resolves the prefetch delay for a link element.
245
- *
246
- * Checks for per-link overrides via `data-eco-prefetch-delay` attribute,
247
- * falling back to the global delay.
248
- */
249
- getLinkDelay(link) {
250
- const delayAttr = link.getAttribute("data-eco-prefetch-delay");
251
- if (delayAttr) {
252
- const delay = parseInt(delayAttr, 10);
253
- if (!isNaN(delay) && delay >= 0) return delay;
228
+ /**
229
+ * Resolves the prefetch delay for a link element.
230
+ *
231
+ * Checks for per-link overrides via `data-eco-prefetch-delay` attribute,
232
+ * falling back to the global delay.
233
+ */
234
+ getLinkDelay(link) {
235
+ const delayAttr = link.getAttribute('data-eco-prefetch-delay');
236
+ if (delayAttr) {
237
+ const delay = parseInt(delayAttr, 10);
238
+ if (!isNaN(delay) && delay >= 0)
239
+ return delay;
240
+ }
241
+ return this.options.delay;
254
242
  }
255
- return this.options.delay;
256
- }
257
- /**
258
- * Schedules a prefetch request during browser idle time.
259
- *
260
- * Uses `requestIdleCallback` when available for non-blocking execution.
261
- * Eager prefetches execute immediately.
262
- *
263
- * @param href - The URL to prefetch
264
- * @param eager - If true, prefetch immediately without waiting for idle
265
- */
266
- scheduleIdlePrefetch(href, eager = false) {
267
- if (this.prefetched.has(href)) return;
268
- const prefetch = () => this.prefetch(href);
269
- if (eager) {
270
- prefetch();
271
- return;
243
+ /**
244
+ * Schedules a prefetch request during browser idle time.
245
+ *
246
+ * Uses `requestIdleCallback` when available for non-blocking execution.
247
+ * Eager prefetches execute immediately.
248
+ *
249
+ * @param href - The URL to prefetch
250
+ * @param eager - If true, prefetch immediately without waiting for idle
251
+ */
252
+ scheduleIdlePrefetch(href, eager = false) {
253
+ if (this.prefetched.has(href))
254
+ return;
255
+ const prefetch = () => this.prefetch(href);
256
+ if (eager) {
257
+ prefetch();
258
+ return;
259
+ }
260
+ if ('requestIdleCallback' in window) {
261
+ requestIdleCallback(prefetch, { timeout: 2000 });
262
+ }
263
+ else {
264
+ setTimeout(prefetch, 0);
265
+ }
272
266
  }
273
- if ("requestIdleCallback" in window) {
274
- requestIdleCallback(prefetch, { timeout: 2e3 });
275
- } else {
276
- setTimeout(prefetch, 0);
267
+ /**
268
+ * Schedules a prefetch after a hover delay.
269
+ *
270
+ * The delay prevents prefetching when users briefly pass over links
271
+ * without intent to navigate.
272
+ *
273
+ * @param href - The URL to prefetch
274
+ * @param delay - Milliseconds to wait before prefetching
275
+ */
276
+ scheduleHoverPrefetch(href, delay = this.options.delay) {
277
+ if (this.prefetched.has(href))
278
+ return;
279
+ if (this.hoverTimeouts.has(href))
280
+ return;
281
+ const timeout = setTimeout(() => {
282
+ this.hoverTimeouts.delete(href);
283
+ this.prefetch(href);
284
+ }, delay);
285
+ this.hoverTimeouts.set(href, timeout);
277
286
  }
278
- }
279
- /**
280
- * Schedules a prefetch after a hover delay.
281
- *
282
- * The delay prevents prefetching when users briefly pass over links
283
- * without intent to navigate.
284
- *
285
- * @param href - The URL to prefetch
286
- * @param delay - Milliseconds to wait before prefetching
287
- */
288
- scheduleHoverPrefetch(href, delay = this.options.delay) {
289
- if (this.prefetched.has(href)) return;
290
- if (this.hoverTimeouts.has(href)) return;
291
- const timeout = setTimeout(() => {
292
- this.hoverTimeouts.delete(href);
293
- this.prefetch(href);
294
- }, delay);
295
- this.hoverTimeouts.set(href, timeout);
296
- }
297
- /**
298
- * Cancels a pending hover-initiated prefetch.
299
- * @param href - The URL whose prefetch should be cancelled
300
- */
301
- cancelHoverPrefetch(href) {
302
- const timeout = this.hoverTimeouts.get(href);
303
- if (timeout) {
304
- clearTimeout(timeout);
305
- this.hoverTimeouts.delete(href);
287
+ /**
288
+ * Cancels a pending hover-initiated prefetch.
289
+ * @param href - The URL whose prefetch should be cancelled
290
+ */
291
+ cancelHoverPrefetch(href) {
292
+ const timeout = this.hoverTimeouts.get(href);
293
+ if (timeout) {
294
+ clearTimeout(timeout);
295
+ this.hoverTimeouts.delete(href);
296
+ }
306
297
  }
307
- }
308
- /**
309
- * Begins observing all existing links on the page.
310
- *
311
- * Called once during initialization. Eager links are prefetched immediately;
312
- * viewport-strategy links are registered with the IntersectionObserver.
313
- */
314
- observeExistingLinks() {
315
- const links = document.querySelectorAll(this.options.linkSelector);
316
- for (const link of links) {
317
- if (link.hasAttribute(this.options.noPrefetchAttribute)) continue;
318
- const strategy = this.getLinkStrategy(link);
319
- if (strategy === "eager") {
320
- this.scheduleIdlePrefetch(link.href, true);
321
- } else if (this.observer && strategy === "viewport") {
322
- this.observer.observe(link);
323
- }
298
+ /**
299
+ * Observes links for prefetching within `root`.
300
+ */
301
+ observeLinks(root = document) {
302
+ const links = root.querySelectorAll(this.options.linkSelector);
303
+ for (const link of links) {
304
+ if (!this.isEligiblePrefetchLink(link))
305
+ continue;
306
+ const strategy = this.getLinkStrategy(link);
307
+ if (strategy === 'eager') {
308
+ this.scheduleIdlePrefetch(link.href, true);
309
+ }
310
+ else if (this.observer && strategy === 'viewport') {
311
+ this.observer.observe(link);
312
+ }
313
+ }
324
314
  }
325
- }
326
- /**
327
- * Observes newly added links after DOM mutations.
328
- *
329
- * Should be called after client-side navigation or dynamic content updates
330
- * to ensure new links are tracked for prefetching.
331
- *
332
- * @param root - The root element to search for links (defaults to document)
333
- */
334
- observeNewLinks(root = document) {
335
- const links = root.querySelectorAll(this.options.linkSelector);
336
- for (const link of links) {
337
- if (link.hasAttribute(this.options.noPrefetchAttribute)) continue;
338
- const strategy = this.getLinkStrategy(link);
339
- if (strategy === "eager") {
340
- this.scheduleIdlePrefetch(link.href, true);
341
- } else if (this.observer && strategy === "viewport") {
342
- this.observer.observe(link);
343
- }
315
+ /**
316
+ * Prefetches stylesheets discovered in HTML content.
317
+ *
318
+ * Parses the HTML to find stylesheet links, then warms the HTTP cache for
319
+ * stylesheets not already present in the current document. This keeps future
320
+ * navigation CSS warm without injecting `preload` hints that browsers expect
321
+ * the current page to consume immediately.
322
+ *
323
+ * @param html - The raw HTML string to parse
324
+ * @param url - The base URL for resolving relative stylesheet paths
325
+ */
326
+ async prefetchStylesheets(doc) {
327
+ const existingHrefs = new Set([...getCurrentStylesheetHrefs(), ...this.prefetchedStylesheets]);
328
+ const newStylesheetHrefs = discoverNewStylesheetLinks(doc, existingHrefs).map((link) => link.href);
329
+ const stylesheetFetches = newStylesheetHrefs.map((href) => {
330
+ this.prefetchedStylesheets.add(href);
331
+ return this.prefetchStylesheet(href);
332
+ });
333
+ await Promise.allSettled(stylesheetFetches);
344
334
  }
345
- }
346
- /**
347
- * Prefetches stylesheets discovered in HTML content.
348
- *
349
- * Parses the HTML to find stylesheet links, then creates preload hints
350
- * for stylesheets not already present in the current document. This ensures
351
- * styles are cached before navigation to prevent FOUC.
352
- *
353
- * @param html - The raw HTML string to parse
354
- * @param url - The base URL for resolving relative stylesheet paths
355
- */
356
- async prefetchStylesheets(html, url) {
357
- const parser = new DOMParser();
358
- const doc = parser.parseFromString(`<base href="${url.href}">${html}`, "text/html");
359
- const existingHrefs = /* @__PURE__ */ new Set([
360
- ...Array.from(document.querySelectorAll('link[rel="stylesheet"]')).map((l) => l.href),
361
- ...Array.from(document.querySelectorAll('link[rel="preload"][as="style"]')).map(
362
- (l) => l.href
363
- )
364
- ]);
365
- const newStylesheets = doc.querySelectorAll('link[rel="stylesheet"]');
366
- for (const link of newStylesheets) {
367
- if (!existingHrefs.has(link.href)) {
368
- const preloadLink = document.createElement("link");
369
- preloadLink.rel = "preload";
370
- preloadLink.as = "style";
371
- preloadLink.href = link.href;
372
- document.head.appendChild(preloadLink);
373
- }
335
+ async prefetchStylesheet(href) {
336
+ try {
337
+ await fetch(href, {
338
+ credentials: 'same-origin',
339
+ priority: 'low',
340
+ });
341
+ }
342
+ catch {
343
+ this.prefetchedStylesheets.delete(href);
344
+ }
374
345
  }
375
- }
376
346
  }
377
- export {
378
- PrefetchManager
379
- };