@ecopages/browser-router 0.2.1 → 0.3.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 (40) hide show
  1. package/README.md +25 -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/dom-swapper.d.ts +7 -0
  8. package/src/client/dom/dom-swapper.js +15 -0
  9. package/src/client/dom/stylesheet-discovery.d.ts +12 -0
  10. package/src/client/dom/stylesheet-discovery.js +24 -0
  11. package/src/client/eco-router-perform-navigation.d.ts +13 -0
  12. package/src/client/eco-router-perform-navigation.js +24 -0
  13. package/src/client/eco-router.d.ts +2 -35
  14. package/src/client/eco-router.js +329 -479
  15. package/src/client/index.d.ts +3 -0
  16. package/src/client/index.js +3 -0
  17. package/src/client/navigation-commit-reload.d.ts +21 -0
  18. package/src/client/navigation-commit-reload.js +16 -0
  19. package/src/client/navigation-commit.d.ts +19 -0
  20. package/src/client/navigation-commit.js +83 -0
  21. package/src/client/services/prefetch-manager.d.ts +10 -18
  22. package/src/client/services/prefetch-manager.js +353 -360
  23. package/src/client/types.d.ts +16 -13
  24. package/src/client/types.js +21 -20
  25. package/src/index.d.ts +2 -5
  26. package/src/index.js +7 -18
  27. package/CHANGELOG.md +0 -25
  28. package/src/client/services/dom-swapper.d.ts +0 -166
  29. package/src/client/services/dom-swapper.js +0 -497
  30. package/src/client/services/index.d.ts +0 -8
  31. package/src/client/services/index.js +0 -10
  32. package/src/client/services/scroll-manager.d.ts +0 -19
  33. package/src/client/services/scroll-manager.js +0 -36
  34. package/src/client/services/view-transition-manager.d.ts +0 -29
  35. package/src/client/services/view-transition-manager.js +0 -54
  36. package/src/client/view-transition-utils.d.ts +0 -14
  37. package/src/client/view-transition-utils.js +0 -60
  38. package/src/styles.css +0 -218
  39. package/src/types.d.ts +0 -15
  40. package/src/types.js +0 -5
@@ -1,379 +1,372 @@
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, getCachedNavigationHtml, 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
+ /**
89
+ * Retrieves cached HTML for a URL.
90
+ *
91
+ * Returns cached content without consuming it, enabling stale-while-revalidate:
92
+ * - Returns cached HTML immediately for instant navigation
93
+ * - Use cacheVisitedPage() after navigation to update cache in background
94
+ *
95
+ * @param href - The URL to look up
96
+ * @returns The cached HTML string, or null if not cached
97
+ */
98
+ getCachedHtml(href) {
99
+ return getCachedNavigationHtml(href);
100
+ }
101
+ invalidate(href) {
102
+ const url = new URL(href, window.location.origin);
103
+ invalidateNavigationHtml(url);
104
+ this.prefetched.delete(url.href);
105
+ }
106
+ /**
107
+ * Caches HTML content for a visited page and triggers background revalidation.
108
+ *
109
+ * Implements stale-while-revalidate pattern:
110
+ * - Immediately caches the provided HTML for instant revisits
111
+ * - Fetches fresh content in background for next visit (unless it's the current page)
112
+ *
113
+ * @param href - The URL of the visited page
114
+ * @param html - The HTML content to cache initially
115
+ */
116
+ cacheVisitedPage(href, html) {
117
+ const url = new URL(href, window.location.origin);
118
+ if (url.origin !== window.location.origin)
119
+ return;
120
+ cacheNavigationHtml(url, html);
121
+ this.prefetched.add(url.href);
122
+ if (isSamePageHref(url.href))
123
+ return;
124
+ setTimeout(() => {
125
+ void fetchNavigationPage(url, { bypassCache: true, priority: 'low' }).catch(() => { });
126
+ }, 100);
127
+ }
128
+ /**
129
+ * Checks if a URL has already been prefetched.
130
+ * @param href - The URL to check
131
+ */
132
+ isPrefetched(href) {
133
+ const url = new URL(href, window.location.origin);
134
+ return this.prefetched.has(url.href);
135
+ }
136
+ /**
137
+ * Determines if prefetching should be enabled based on network conditions.
138
+ *
139
+ * Respects the user's data saver settings and avoids prefetching on slow
140
+ * connections (2g or slower) when `respectDataSaver` is enabled.
141
+ */
142
+ shouldPrefetch() {
143
+ if (!this.options.respectDataSaver)
144
+ return true;
145
+ const conn = navigator.connection;
146
+ if (!conn)
147
+ return true;
148
+ if (conn.saveData)
149
+ return false;
150
+ if (conn.effectiveType === '2g' || conn.effectiveType === 'slow-2g')
151
+ return false;
152
+ return true;
153
+ }
154
+ /**
155
+ * Creates an IntersectionObserver to prefetch links as they enter the viewport.
156
+ *
157
+ * Uses a 50px root margin to trigger prefetching slightly before elements
158
+ * become visible, improving perceived performance.
159
+ */
160
+ setupIntersectionObserver() {
161
+ this.observer = new IntersectionObserver((entries) => {
162
+ for (const entry of entries) {
163
+ if (entry.isIntersecting) {
164
+ const link = entry.target;
165
+ if (!this.isEligiblePrefetchLink(link))
166
+ continue;
167
+ const strategy = this.getLinkStrategy(link);
168
+ if (strategy === 'viewport' || strategy === 'eager') {
169
+ this.scheduleIdlePrefetch(link.href, strategy === 'eager');
170
+ }
171
+ }
167
172
  }
168
- }
173
+ }, { rootMargin: '50px', threshold: 0 });
174
+ }
175
+ /**
176
+ * Attaches delegated event listeners for hover and focus-based prefetching.
177
+ *
178
+ * Uses event delegation on the document for efficient handling without
179
+ * attaching listeners to individual links.
180
+ */
181
+ setupHoverListeners() {
182
+ document.addEventListener('mouseover', this.handleMouseOver);
183
+ document.addEventListener('mouseout', this.handleMouseOut);
184
+ document.addEventListener('focusin', this.handleFocusIn);
185
+ document.addEventListener('focusout', this.handleFocusOut);
186
+ }
187
+ handleMouseOver = (event) => {
188
+ const link = this.getLinkFromEvent(event);
189
+ if (!link)
190
+ return;
191
+ const strategy = this.getLinkStrategy(link);
192
+ if (strategy === 'hover' || strategy === 'intent' || strategy === 'eager') {
193
+ const delay = strategy === 'eager' ? 0 : this.getLinkDelay(link);
194
+ this.scheduleHoverPrefetch(link.href, delay);
195
+ }
196
+ };
197
+ handleMouseOut = (event) => {
198
+ const link = this.getLinkFromEvent(event);
199
+ if (!link)
200
+ return;
201
+ this.cancelHoverPrefetch(link.href);
202
+ };
203
+ handleFocusIn = (event) => {
204
+ const link = this.getLinkFromEvent(event);
205
+ if (!link)
206
+ return;
207
+ const strategy = this.getLinkStrategy(link);
208
+ if (strategy === 'hover' || strategy === 'intent' || strategy === 'eager') {
209
+ const delay = strategy === 'eager' ? 0 : this.getLinkDelay(link);
210
+ this.scheduleHoverPrefetch(link.href, delay);
169
211
  }
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);
212
+ };
213
+ handleFocusOut = (event) => {
214
+ const link = this.getLinkFromEvent(event);
215
+ if (!link)
216
+ return;
217
+ this.cancelHoverPrefetch(link.href);
218
+ };
219
+ /**
220
+ * Extracts a valid anchor element from a DOM event.
221
+ *
222
+ * Returns null for links that should not be prefetched (opt-outs, downloads,
223
+ * hash links, javascript: URLs).
224
+ */
225
+ getLinkFromEvent(event) {
226
+ const target = event.target;
227
+ const link = target.closest(this.options.linkSelector);
228
+ if (!link)
229
+ return null;
230
+ if (!this.isEligiblePrefetchLink(link)) {
231
+ return null;
232
+ }
233
+ return link;
193
234
  }
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);
235
+ isEligiblePrefetchLink(link) {
236
+ return shouldPrefetchLink(link, {
237
+ reloadAttribute: this.options.reloadAttribute,
238
+ noPrefetchAttribute: this.options.noPrefetchAttribute,
239
+ });
207
240
  }
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;
241
+ /**
242
+ * Resolves the prefetch strategy for a link element.
243
+ *
244
+ * Checks for per-link overrides via `data-eco-prefetch` attribute,
245
+ * falling back to the global strategy.
246
+ */
247
+ getLinkStrategy(link) {
248
+ const override = link.getAttribute('data-eco-prefetch');
249
+ if (override === 'eager' || override === 'viewport' || override === 'hover' || override === 'intent') {
250
+ return override;
251
+ }
252
+ return this.options.strategy;
240
253
  }
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;
254
+ /**
255
+ * Resolves the prefetch delay for a link element.
256
+ *
257
+ * Checks for per-link overrides via `data-eco-prefetch-delay` attribute,
258
+ * falling back to the global delay.
259
+ */
260
+ getLinkDelay(link) {
261
+ const delayAttr = link.getAttribute('data-eco-prefetch-delay');
262
+ if (delayAttr) {
263
+ const delay = parseInt(delayAttr, 10);
264
+ if (!isNaN(delay) && delay >= 0)
265
+ return delay;
266
+ }
267
+ return this.options.delay;
254
268
  }
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;
269
+ /**
270
+ * Schedules a prefetch request during browser idle time.
271
+ *
272
+ * Uses `requestIdleCallback` when available for non-blocking execution.
273
+ * Eager prefetches execute immediately.
274
+ *
275
+ * @param href - The URL to prefetch
276
+ * @param eager - If true, prefetch immediately without waiting for idle
277
+ */
278
+ scheduleIdlePrefetch(href, eager = false) {
279
+ if (this.prefetched.has(href))
280
+ return;
281
+ const prefetch = () => this.prefetch(href);
282
+ if (eager) {
283
+ prefetch();
284
+ return;
285
+ }
286
+ if ('requestIdleCallback' in window) {
287
+ requestIdleCallback(prefetch, { timeout: 2000 });
288
+ }
289
+ else {
290
+ setTimeout(prefetch, 0);
291
+ }
272
292
  }
273
- if ("requestIdleCallback" in window) {
274
- requestIdleCallback(prefetch, { timeout: 2e3 });
275
- } else {
276
- setTimeout(prefetch, 0);
293
+ /**
294
+ * Schedules a prefetch after a hover delay.
295
+ *
296
+ * The delay prevents prefetching when users briefly pass over links
297
+ * without intent to navigate.
298
+ *
299
+ * @param href - The URL to prefetch
300
+ * @param delay - Milliseconds to wait before prefetching
301
+ */
302
+ scheduleHoverPrefetch(href, delay = this.options.delay) {
303
+ if (this.prefetched.has(href))
304
+ return;
305
+ if (this.hoverTimeouts.has(href))
306
+ return;
307
+ const timeout = setTimeout(() => {
308
+ this.hoverTimeouts.delete(href);
309
+ this.prefetch(href);
310
+ }, delay);
311
+ this.hoverTimeouts.set(href, timeout);
277
312
  }
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);
313
+ /**
314
+ * Cancels a pending hover-initiated prefetch.
315
+ * @param href - The URL whose prefetch should be cancelled
316
+ */
317
+ cancelHoverPrefetch(href) {
318
+ const timeout = this.hoverTimeouts.get(href);
319
+ if (timeout) {
320
+ clearTimeout(timeout);
321
+ this.hoverTimeouts.delete(href);
322
+ }
306
323
  }
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
- }
324
+ /**
325
+ * Observes links for prefetching within `root`.
326
+ */
327
+ observeLinks(root = document) {
328
+ const links = root.querySelectorAll(this.options.linkSelector);
329
+ for (const link of links) {
330
+ if (!this.isEligiblePrefetchLink(link))
331
+ continue;
332
+ const strategy = this.getLinkStrategy(link);
333
+ if (strategy === 'eager') {
334
+ this.scheduleIdlePrefetch(link.href, true);
335
+ }
336
+ else if (this.observer && strategy === 'viewport') {
337
+ this.observer.observe(link);
338
+ }
339
+ }
324
340
  }
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
- }
341
+ /**
342
+ * Prefetches stylesheets discovered in HTML content.
343
+ *
344
+ * Parses the HTML to find stylesheet links, then warms the HTTP cache for
345
+ * stylesheets not already present in the current document. This keeps future
346
+ * navigation CSS warm without injecting `preload` hints that browsers expect
347
+ * the current page to consume immediately.
348
+ *
349
+ * @param html - The raw HTML string to parse
350
+ * @param url - The base URL for resolving relative stylesheet paths
351
+ */
352
+ async prefetchStylesheets(doc) {
353
+ const existingHrefs = new Set([...getCurrentStylesheetHrefs(), ...this.prefetchedStylesheets]);
354
+ const newStylesheetHrefs = discoverNewStylesheetLinks(doc, existingHrefs).map((link) => link.href);
355
+ const stylesheetFetches = newStylesheetHrefs.map((href) => {
356
+ this.prefetchedStylesheets.add(href);
357
+ return this.prefetchStylesheet(href);
358
+ });
359
+ await Promise.allSettled(stylesheetFetches);
344
360
  }
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
- }
361
+ async prefetchStylesheet(href) {
362
+ try {
363
+ await fetch(href, {
364
+ credentials: 'same-origin',
365
+ priority: 'low',
366
+ });
367
+ }
368
+ catch {
369
+ this.prefetchedStylesheets.delete(href);
370
+ }
374
371
  }
375
- }
376
372
  }
377
- export {
378
- PrefetchManager
379
- };