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