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