@ecopages/browser-router 0.2.0-beta.15 → 0.2.0-beta.17

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 +8 -2
  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 +0 -3
  5. package/src/client/dom/body-morpher.d.ts +24 -0
  6. package/src/client/dom/body-morpher.js +103 -0
  7. package/src/client/dom/dom-swapper.d.ts +30 -0
  8. package/src/client/dom/dom-swapper.js +51 -0
  9. package/src/client/dom/head-updater.d.ts +42 -0
  10. package/src/client/dom/head-updater.js +173 -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 +20 -0
  15. package/src/client/dom/stylesheet-preloader.d.ts +10 -0
  16. package/src/client/dom/stylesheet-preloader.js +38 -0
  17. package/src/client/eco-router.d.ts +1 -30
  18. package/src/client/eco-router.js +30 -177
  19. package/src/client/index.d.ts +3 -0
  20. package/src/client/index.js +13 -0
  21. package/src/client/navigation-commit.d.ts +21 -0
  22. package/src/client/navigation-commit.js +114 -0
  23. package/src/client/navigation-fetch.d.ts +8 -0
  24. package/src/client/navigation-fetch.js +28 -0
  25. package/src/client/services/prefetch-manager.d.ts +2 -14
  26. package/src/client/services/prefetch-manager.js +23 -47
  27. package/src/client/services/view-transition-manager.js +1 -1
  28. package/src/client/types.d.ts +6 -0
  29. package/src/index.d.ts +3 -5
  30. package/src/index.js +7 -7
  31. package/src/client/services/dom-swapper.d.ts +0 -168
  32. package/src/client/services/dom-swapper.js +0 -529
  33. package/src/client/services/index.d.ts +0 -8
  34. package/src/client/services/index.js +0 -10
  35. package/src/client/services/scroll-manager.d.ts +0 -19
  36. package/src/client/services/scroll-manager.js +0 -36
  37. package/src/client/view-transition-utils.d.ts +0 -14
  38. package/src/client/view-transition-utils.js +0 -60
  39. package/src/types.d.ts +0 -15
  40. package/src/types.js +0 -5
@@ -1,11 +1,16 @@
1
1
  import { getEcoNavigationRuntime } from "@ecopages/core/router/navigation-coordinator";
2
2
  import {
3
3
  getAnchorFromNavigationEvent,
4
+ isStaticAssetHref,
4
5
  recoverPendingNavigationHref
5
6
  } from "@ecopages/core/router/link-intent";
7
+ import { getNavigableHrefFromClick } from "@ecopages/core/router/link-navigation-policy";
6
8
  import { DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC, DEFAULT_OPTIONS } from "./types.js";
7
- import { syncDocumentElementAttributes } from "./document-element-sync.js";
8
- import { DomSwapper, ScrollManager, ViewTransitionManager, PrefetchManager } from "./services/index.js";
9
+ import { DomSwapper } from "./dom/dom-swapper.js";
10
+ import { PrefetchManager } from "./services/prefetch-manager.js";
11
+ import { ViewTransitionManager } from "./services/view-transition-manager.js";
12
+ import { NavigationCommit } from "./navigation-commit.js";
13
+ import { fetchNavigationPage } from "./navigation-fetch.js";
9
14
  class EcoRouter {
10
15
  options;
11
16
  unregisterNavigationRuntime = null;
@@ -14,9 +19,9 @@ class EcoRouter {
14
19
  pendingPointerNavigation = null;
15
20
  queuedNavigationHref = null;
16
21
  domSwapper;
17
- scrollManager;
18
22
  viewTransitionManager;
19
23
  prefetchManager = null;
24
+ navigationCommit;
20
25
  constructor(options = {}) {
21
26
  this.options = {
22
27
  ...DEFAULT_OPTIONS,
@@ -26,7 +31,6 @@ class EcoRouter {
26
31
  ]
27
32
  };
28
33
  this.domSwapper = new DomSwapper(this.options.persistAttribute);
29
- this.scrollManager = new ScrollManager(this.options.scrollBehavior, this.options.smoothScroll);
30
34
  this.viewTransitionManager = new ViewTransitionManager(this.options.viewTransitions);
31
35
  if (this.options.prefetch !== false) {
32
36
  this.prefetchManager = new PrefetchManager({
@@ -37,27 +41,12 @@ class EcoRouter {
37
41
  this.handleClick = this.handleClick.bind(this);
38
42
  this.handlePointerDown = this.handlePointerDown.bind(this);
39
43
  this.handlePopState = this.handlePopState.bind(this);
40
- }
41
- getLinkFromEvent(event) {
42
- return getAnchorFromNavigationEvent(event, this.options.linkSelector);
43
- }
44
- canInterceptLink(event, link) {
45
- if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return null;
46
- if (event.button !== 0) return null;
47
- const target = link.getAttribute("target");
48
- if (target && target !== "_self") return null;
49
- if (link.hasAttribute(this.options.reloadAttribute)) return null;
50
- if (link.hasAttribute("download")) return null;
51
- const href = link.getAttribute("href");
52
- if (!href) return null;
53
- if (href.startsWith("#")) return null;
54
- if (href.startsWith("javascript:")) return null;
55
- const url = new URL(href, window.location.origin);
56
- if (!this.isSameOrigin(url)) return null;
57
- if (url.hash && url.pathname === window.location.pathname && url.search === window.location.search) {
58
- return null;
59
- }
60
- return href;
44
+ this.navigationCommit = new NavigationCommit(
45
+ this.domSwapper,
46
+ this.viewTransitionManager,
47
+ this.prefetchManager,
48
+ this.options
49
+ );
61
50
  }
62
51
  getRecoveredPointerHref() {
63
52
  const href = recoverPendingNavigationHref(
@@ -74,117 +63,6 @@ class EcoRouter {
74
63
  const ownerState = getEcoNavigationRuntime(window).getOwnerState();
75
64
  return ownerState.owner !== "none" && ownerState.owner !== "browser-router" && ownerState.canHandleSpaNavigation;
76
65
  }
77
- getDocumentOwner(doc) {
78
- return getEcoNavigationRuntime(window).resolveDocumentOwner(doc, "browser-router");
79
- }
80
- adoptDocumentOwner(doc) {
81
- getEcoNavigationRuntime(window).adoptDocumentOwner(doc, "browser-router");
82
- }
83
- syncDocumentElementAttributes(newDocument) {
84
- syncDocumentElementAttributes(document, newDocument, this.options.documentElementAttributesToSync);
85
- }
86
- reloadDocument(url) {
87
- window.location.assign(url.href);
88
- }
89
- /**
90
- * Commits a fully fetched document into the live page.
91
- *
92
- * When browser-router accepts a handoff from another runtime, it delays source
93
- * runtime cleanup until the incoming document has been prepared and is ready to
94
- * commit. That ordering avoids the blank-page window we previously hit when a
95
- * delegated navigation went stale after the source runtime had already torn
96
- * itself down.
97
- */
98
- async commitDocumentNavigation(url, direction, newDocument, options = {}) {
99
- const allowFullDocumentFallback = options.allowFullDocumentFallback ?? true;
100
- const previousUrl = new URL(window.location.href);
101
- const navigationRuntime = getEcoNavigationRuntime(window);
102
- const isStaleNavigation = options.isStaleNavigation ?? (() => false);
103
- const currentDocumentOwner = navigationRuntime.resolveDocumentOwner(document, "browser-router");
104
- const newDocumentOwner = navigationRuntime.resolveDocumentOwner(newDocument, "browser-router");
105
- const activeOwner = navigationRuntime.getOwnerState().owner;
106
- const shouldCleanupCurrentOwner = currentDocumentOwner !== newDocumentOwner && currentDocumentOwner !== "browser-router" && activeOwner === currentDocumentOwner;
107
- let shouldReload = false;
108
- const beforeSwapEvent = {
109
- url,
110
- direction,
111
- newDocument,
112
- reload: () => {
113
- shouldReload = true;
114
- }
115
- };
116
- document.dispatchEvent(new CustomEvent("eco:before-swap", { detail: beforeSwapEvent }));
117
- if (isStaleNavigation()) {
118
- return false;
119
- }
120
- if (shouldReload) {
121
- if (shouldCleanupCurrentOwner) {
122
- await navigationRuntime.cleanupOwner(currentDocumentOwner);
123
- }
124
- if (isStaleNavigation()) {
125
- return false;
126
- }
127
- if (allowFullDocumentFallback) {
128
- this.reloadDocument(url);
129
- }
130
- return false;
131
- }
132
- const useViewTransitions = this.options.viewTransitions;
133
- await this.domSwapper.preloadStylesheets(newDocument);
134
- if (isStaleNavigation()) {
135
- return false;
136
- }
137
- if (shouldCleanupCurrentOwner) {
138
- await navigationRuntime.cleanupOwner(currentDocumentOwner);
139
- }
140
- if (isStaleNavigation()) {
141
- return false;
142
- }
143
- const commitSwap = () => {
144
- if (isStaleNavigation()) return;
145
- if (this.options.updateHistory && direction === "forward") {
146
- window.history.pushState({}, "", url.href);
147
- } else if (direction === "replace") {
148
- window.history.replaceState({}, "", url.href);
149
- }
150
- this.syncDocumentElementAttributes(newDocument);
151
- this.domSwapper.morphHead(newDocument);
152
- if (useViewTransitions && !this.domSwapper.shouldReplaceBodyForRerunScripts()) {
153
- this.domSwapper.morphBody(newDocument);
154
- } else {
155
- this.domSwapper.replaceBody(newDocument);
156
- }
157
- this.domSwapper.flushRerunScripts();
158
- this.scrollManager.handleScroll(url, previousUrl);
159
- };
160
- if (useViewTransitions) {
161
- await this.viewTransitionManager.transition(commitSwap);
162
- } else {
163
- commitSwap();
164
- }
165
- if (isStaleNavigation()) {
166
- return false;
167
- }
168
- navigationRuntime.adoptDocumentOwner(newDocument, "browser-router");
169
- const afterSwapEvent = {
170
- url,
171
- direction
172
- };
173
- document.dispatchEvent(new CustomEvent("eco:after-swap", { detail: afterSwapEvent }));
174
- this.prefetchManager?.observeNewLinks();
175
- if (options.html) {
176
- this.prefetchManager?.cacheVisitedPage(url.href, options.html);
177
- }
178
- requestAnimationFrame(() => {
179
- if (isStaleNavigation()) return;
180
- document.dispatchEvent(
181
- new CustomEvent("eco:page-load", {
182
- detail: { url, direction }
183
- })
184
- );
185
- });
186
- return true;
187
- }
188
66
  /**
189
67
  * Starts the router and begins intercepting navigation.
190
68
  *
@@ -218,7 +96,7 @@ class EcoRouter {
218
96
  const { isStaleNavigation, complete } = this.beginNavigationTransaction();
219
97
  if (isStaleNavigation()) return true;
220
98
  try {
221
- await this.commitDocumentNavigation(
99
+ await this.navigationCommit.commit(
222
100
  new URL(request.finalHref ?? request.href, window.location.origin),
223
101
  request.direction ?? "forward",
224
102
  request.document,
@@ -246,7 +124,7 @@ class EcoRouter {
246
124
  this.cancelNavigationTransaction();
247
125
  }
248
126
  });
249
- this.adoptDocumentOwner(document);
127
+ getEcoNavigationRuntime(window).adoptDocumentOwner(document, "browser-router");
250
128
  const initialHtml = document.documentElement.outerHTML;
251
129
  this.prefetchManager?.cacheVisitedPage(window.location.href, initialHtml);
252
130
  this.started = true;
@@ -283,10 +161,14 @@ class EcoRouter {
283
161
  */
284
162
  async navigate(href, options = {}) {
285
163
  const url = new URL(href, window.location.origin);
286
- if (!this.isSameOrigin(url)) {
164
+ if (url.origin !== window.location.origin) {
287
165
  window.location.href = href;
288
166
  return;
289
167
  }
168
+ if (isStaticAssetHref(href)) {
169
+ window.location.assign(url.href);
170
+ return;
171
+ }
290
172
  await this.performNavigation(url, options.replace ? "replace" : "forward");
291
173
  }
292
174
  /**
@@ -310,12 +192,12 @@ class EcoRouter {
310
192
  * Shadow DOM boundaries (Web Components).
311
193
  */
312
194
  handlePointerDown(event) {
313
- const link = this.getLinkFromEvent(event);
195
+ const link = getAnchorFromNavigationEvent(event, this.options.linkSelector);
314
196
  if (!link) {
315
197
  this.pendingPointerNavigation = null;
316
198
  return;
317
199
  }
318
- const href = this.canInterceptLink(event, link);
200
+ const href = getNavigableHrefFromClick(event, link, { reloadAttribute: this.options.reloadAttribute });
319
201
  this.pendingPointerNavigation = href ? {
320
202
  href,
321
203
  timestamp: performance.now()
@@ -326,8 +208,8 @@ class EcoRouter {
326
208
  }
327
209
  handleClick(event) {
328
210
  const navigationRuntime = getEcoNavigationRuntime(window);
329
- const link = this.getLinkFromEvent(event);
330
- const href = link ? this.canInterceptLink(event, link) : this.getRecoveredPointerHref();
211
+ const link = getAnchorFromNavigationEvent(event, this.options.linkSelector);
212
+ const href = link ? getNavigableHrefFromClick(event, link, { reloadAttribute: this.options.reloadAttribute }) : this.getRecoveredPointerHref();
331
213
  this.pendingPointerNavigation = null;
332
214
  if (!href) return;
333
215
  this.queuedNavigationHref = null;
@@ -359,13 +241,6 @@ class EcoRouter {
359
241
  const url = new URL(window.location.href);
360
242
  this.performNavigation(url, "back");
361
243
  }
362
- /**
363
- * Checks if a URL shares the same origin as the current page.
364
- * Cross-origin navigation always falls back to full page reload.
365
- */
366
- isSameOrigin(url) {
367
- return url.origin === window.location.origin;
368
- }
369
244
  cancelNavigationTransaction() {
370
245
  getEcoNavigationRuntime(window).cancelCurrentNavigationTransaction();
371
246
  }
@@ -402,7 +277,10 @@ class EcoRouter {
402
277
  let queuedNavigationHref = null;
403
278
  let committed = false;
404
279
  try {
405
- const html = await this.fetchPage(url, signal, { bypassCache: options.bypassPrefetchCache });
280
+ const html = await fetchNavigationPage(url, signal, {
281
+ bypassCache: options.bypassPrefetchCache,
282
+ getCachedHtml: this.prefetchManager ? (href) => this.prefetchManager.getCachedHtml(href) : void 0
283
+ });
406
284
  if (isStaleNavigation()) {
407
285
  return false;
408
286
  }
@@ -410,7 +288,7 @@ class EcoRouter {
410
288
  if (isStaleNavigation()) {
411
289
  return false;
412
290
  }
413
- committed = await this.commitDocumentNavigation(url, direction, newDocument, {
291
+ committed = await this.navigationCommit.commit(url, direction, newDocument, {
414
292
  html,
415
293
  isStaleNavigation,
416
294
  allowFullDocumentFallback
@@ -450,31 +328,6 @@ class EcoRouter {
450
328
  }
451
329
  }
452
330
  }
453
- /**
454
- * Fetches the HTML content of a page.
455
- * @param url - The URL to fetch
456
- * @param signal - AbortSignal for cancelling the request
457
- * @throws Error if the response is not ok
458
- */
459
- async fetchPage(url, signal, options = {}) {
460
- if (!options.bypassCache && this.prefetchManager) {
461
- const cachedHtml = this.prefetchManager.getCachedHtml(url.href);
462
- if (cachedHtml) {
463
- return cachedHtml;
464
- }
465
- }
466
- const response = await fetch(url.href, {
467
- signal,
468
- cache: "no-store",
469
- headers: {
470
- Accept: "text/html"
471
- }
472
- });
473
- if (!response.ok) {
474
- throw new Error(`Failed to fetch page: ${response.status}`);
475
- }
476
- return response.text();
477
- }
478
331
  }
479
332
  const ACTIVE_ROUTER_KEY = "__ecopages_browser_router__";
480
333
  function createRouter(options) {
@@ -0,0 +1,3 @@
1
+ export { EcoRouter, createRouter } from './eco-router.js';
2
+ export { syncDocumentElementAttributes } from './document-element-sync.js';
3
+ export { DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC, DEFAULT_OPTIONS, type BrowserRouterNavigateOptions, type EcoAfterSwapEvent, type EcoBeforeSwapEvent, type EcoNavigationEvent, type EcoRouterEventMap, type EcoRouterOptions, } from './types.js';
@@ -0,0 +1,13 @@
1
+ import { EcoRouter, createRouter } from "./eco-router.js";
2
+ import { syncDocumentElementAttributes } from "./document-element-sync.js";
3
+ import {
4
+ DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC,
5
+ DEFAULT_OPTIONS
6
+ } from "./types.js";
7
+ export {
8
+ DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC,
9
+ DEFAULT_OPTIONS,
10
+ EcoRouter,
11
+ createRouter,
12
+ syncDocumentElementAttributes
13
+ };
@@ -0,0 +1,21 @@
1
+ import type { DomSwapper } from './dom/dom-swapper.js';
2
+ import type { PrefetchManager } from './services/prefetch-manager.js';
3
+ import type { ViewTransitionManager } from './services/view-transition-manager.js';
4
+ import type { EcoNavigationEvent, EcoRouterOptions } from './types.js';
5
+ export type NavigationCommitOptions = {
6
+ html?: string;
7
+ isStaleNavigation?: () => boolean;
8
+ allowFullDocumentFallback?: boolean;
9
+ };
10
+ /**
11
+ * Commits a fetched document into the live page and dispatches navigation lifecycle events.
12
+ */
13
+ export declare class NavigationCommit {
14
+ private readonly domSwapper;
15
+ private readonly viewTransitionManager;
16
+ private readonly prefetchManager;
17
+ private readonly options;
18
+ constructor(domSwapper: DomSwapper, viewTransitionManager: ViewTransitionManager, prefetchManager: PrefetchManager | null, options: Required<EcoRouterOptions>);
19
+ commit(url: URL, direction: EcoNavigationEvent['direction'], newDocument: Document, options?: NavigationCommitOptions): Promise<boolean>;
20
+ private reloadDocument;
21
+ }
@@ -0,0 +1,114 @@
1
+ import { getEcoNavigationRuntime } from "@ecopages/core/router/navigation-coordinator";
2
+ import { manageWindowScroll } from "@ecopages/core/client/scroll";
3
+ import { syncDocumentElementAttributes } from "./document-element-sync.js";
4
+ class NavigationCommit {
5
+ domSwapper;
6
+ viewTransitionManager;
7
+ prefetchManager;
8
+ options;
9
+ constructor(domSwapper, viewTransitionManager, prefetchManager, options) {
10
+ this.domSwapper = domSwapper;
11
+ this.viewTransitionManager = viewTransitionManager;
12
+ this.prefetchManager = prefetchManager;
13
+ this.options = options;
14
+ }
15
+ async commit(url, direction, newDocument, options = {}) {
16
+ const allowFullDocumentFallback = options.allowFullDocumentFallback ?? true;
17
+ const previousUrl = new URL(window.location.href);
18
+ const navigationRuntime = getEcoNavigationRuntime(window);
19
+ const isStaleNavigation = options.isStaleNavigation ?? (() => false);
20
+ const currentDocumentOwner = navigationRuntime.resolveDocumentOwner(document, "browser-router");
21
+ const newDocumentOwner = navigationRuntime.resolveDocumentOwner(newDocument, "browser-router");
22
+ const activeOwner = navigationRuntime.getOwnerState().owner;
23
+ const shouldCleanupCurrentOwner = currentDocumentOwner !== newDocumentOwner && currentDocumentOwner !== "browser-router" && activeOwner === currentDocumentOwner;
24
+ let shouldReload = false;
25
+ const beforeSwapEvent = {
26
+ url,
27
+ direction,
28
+ newDocument,
29
+ reload: () => {
30
+ shouldReload = true;
31
+ }
32
+ };
33
+ document.dispatchEvent(new CustomEvent("eco:before-swap", { detail: beforeSwapEvent }));
34
+ if (isStaleNavigation()) {
35
+ return false;
36
+ }
37
+ if (shouldReload) {
38
+ if (shouldCleanupCurrentOwner) {
39
+ await navigationRuntime.cleanupOwner(currentDocumentOwner);
40
+ }
41
+ if (isStaleNavigation()) {
42
+ return false;
43
+ }
44
+ if (allowFullDocumentFallback) {
45
+ this.reloadDocument(url.href);
46
+ }
47
+ return false;
48
+ }
49
+ const useViewTransitions = this.options.viewTransitions;
50
+ await this.domSwapper.preloadStylesheets(newDocument);
51
+ if (isStaleNavigation()) {
52
+ return false;
53
+ }
54
+ if (shouldCleanupCurrentOwner) {
55
+ await navigationRuntime.cleanupOwner(currentDocumentOwner);
56
+ }
57
+ if (isStaleNavigation()) {
58
+ return false;
59
+ }
60
+ const commitSwap = () => {
61
+ if (isStaleNavigation()) return;
62
+ if (this.options.updateHistory && direction === "forward") {
63
+ window.history.pushState({}, "", url.href);
64
+ } else if (direction === "replace") {
65
+ window.history.replaceState({}, "", url.href);
66
+ }
67
+ syncDocumentElementAttributes(document, newDocument, this.options.documentElementAttributesToSync);
68
+ const { bodyStrategy } = this.domSwapper.morphHead(newDocument);
69
+ if (useViewTransitions && bodyStrategy === "morph") {
70
+ this.domSwapper.morphBody(newDocument);
71
+ } else {
72
+ this.domSwapper.replaceBody(newDocument);
73
+ }
74
+ this.domSwapper.flushRerunScripts();
75
+ manageWindowScroll(url, previousUrl, {
76
+ scrollBehavior: this.options.scrollBehavior,
77
+ smoothScroll: this.options.smoothScroll
78
+ });
79
+ };
80
+ if (useViewTransitions) {
81
+ await this.viewTransitionManager.transition(commitSwap);
82
+ } else {
83
+ commitSwap();
84
+ }
85
+ if (isStaleNavigation()) {
86
+ return false;
87
+ }
88
+ navigationRuntime.adoptDocumentOwner(newDocument, "browser-router");
89
+ const afterSwapEvent = {
90
+ url,
91
+ direction
92
+ };
93
+ document.dispatchEvent(new CustomEvent("eco:after-swap", { detail: afterSwapEvent }));
94
+ this.prefetchManager?.observeLinks();
95
+ if (options.html) {
96
+ this.prefetchManager?.cacheVisitedPage(url.href, options.html);
97
+ }
98
+ requestAnimationFrame(() => {
99
+ if (isStaleNavigation()) return;
100
+ document.dispatchEvent(
101
+ new CustomEvent("eco:page-load", {
102
+ detail: { url, direction }
103
+ })
104
+ );
105
+ });
106
+ return true;
107
+ }
108
+ reloadDocument(href) {
109
+ window.location.assign(href);
110
+ }
111
+ }
112
+ export {
113
+ NavigationCommit
114
+ };
@@ -0,0 +1,8 @@
1
+ export type FetchNavigationPageOptions = {
2
+ bypassCache?: boolean;
3
+ getCachedHtml?: (href: string) => string | null | undefined;
4
+ };
5
+ /**
6
+ * Fetches HTML for a client-side navigation request.
7
+ */
8
+ export declare function fetchNavigationPage(url: URL, signal: AbortSignal, options?: FetchNavigationPageOptions): Promise<string>;
@@ -0,0 +1,28 @@
1
+ import { isHtmlPageResponse } from "@ecopages/core/router/link-navigation-policy";
2
+ async function fetchNavigationPage(url, signal, options = {}) {
3
+ if (!options.bypassCache && options.getCachedHtml) {
4
+ const cachedHtml = options.getCachedHtml(url.href);
5
+ if (cachedHtml) {
6
+ return cachedHtml;
7
+ }
8
+ }
9
+ const response = await fetch(url.href, {
10
+ signal,
11
+ cache: "no-store",
12
+ headers: {
13
+ Accept: "text/html"
14
+ }
15
+ });
16
+ if (!response.ok) {
17
+ throw new Error(`Failed to fetch page: ${response.status}`);
18
+ }
19
+ if (!isHtmlPageResponse(response)) {
20
+ throw new Error(
21
+ `Expected HTML page response, received ${response.headers.get("Content-Type") ?? "unknown content type"}`
22
+ );
23
+ }
24
+ return response.text();
25
+ }
26
+ export {
27
+ fetchNavigationPage
28
+ };
@@ -142,21 +142,9 @@ export declare class PrefetchManager {
142
142
  */
143
143
  private cancelHoverPrefetch;
144
144
  /**
145
- * Begins observing all existing links on the page.
146
- *
147
- * Called once during initialization. Eager links are prefetched immediately;
148
- * viewport-strategy links are registered with the IntersectionObserver.
149
- */
150
- private observeExistingLinks;
151
- /**
152
- * Observes newly added links after DOM mutations.
153
- *
154
- * Should be called after client-side navigation or dynamic content updates
155
- * to ensure new links are tracked for prefetching.
156
- *
157
- * @param root - The root element to search for links (defaults to document)
145
+ * Observes links for prefetching within `root`.
158
146
  */
159
- observeNewLinks(root?: Element | Document): void;
147
+ observeLinks(root?: Element | Document): void;
160
148
  /**
161
149
  * Prefetches stylesheets discovered in HTML content.
162
150
  *
@@ -1,3 +1,5 @@
1
+ import { isHtmlPageResponse, shouldPrefetchLink } from "@ecopages/core/router/link-navigation-policy";
2
+ import { discoverNewStylesheetLinks, getCurrentStylesheetHrefs } from "../dom/stylesheet-discovery.js";
1
3
  const DEFAULT_PREFETCH_OPTIONS = {
2
4
  strategy: "intent",
3
5
  delay: 65,
@@ -30,7 +32,7 @@ class PrefetchManager {
30
32
  if (this.options.strategy === "hover" || this.options.strategy === "intent") {
31
33
  this.setupHoverListeners();
32
34
  }
33
- this.observeExistingLinks();
35
+ this.observeLinks();
34
36
  }
35
37
  /**
36
38
  * Cleans up all prefetch-related observers and event listeners.
@@ -68,7 +70,10 @@ class PrefetchManager {
68
70
  headers: { Accept: "text/html" },
69
71
  priority: "low"
70
72
  });
71
- if (!response.ok) return;
73
+ if (!response.ok || !isHtmlPageResponse(response)) {
74
+ this.prefetched.delete(url.href);
75
+ return;
76
+ }
72
77
  const html = await response.text();
73
78
  this.htmlCache.set(url.href, html);
74
79
  await this.prefetchStylesheets(html, url);
@@ -117,9 +122,11 @@ class PrefetchManager {
117
122
  fetch(url.href, {
118
123
  headers: { Accept: "text/html" },
119
124
  priority: "low"
120
- }).then((response) => {
121
- if (response.ok) return response.text();
122
- return null;
125
+ }).then(async (response) => {
126
+ if (!response.ok || !isHtmlPageResponse(response)) {
127
+ return null;
128
+ }
129
+ return response.text();
123
130
  }).then((freshHtml) => {
124
131
  if (freshHtml) {
125
132
  this.htmlCache.set(url.href, freshHtml);
@@ -222,10 +229,9 @@ class PrefetchManager {
222
229
  const target = event.target;
223
230
  const link = target.closest(this.options.linkSelector);
224
231
  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;
232
+ if (!shouldPrefetchLink(link, { noPrefetchAttribute: this.options.noPrefetchAttribute })) {
233
+ return null;
234
+ }
229
235
  return link;
230
236
  }
231
237
  /**
@@ -307,32 +313,9 @@ class PrefetchManager {
307
313
  }
308
314
  }
309
315
  /**
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
- }
325
- }
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)
316
+ * Observes links for prefetching within `root`.
334
317
  */
335
- observeNewLinks(root = document) {
318
+ observeLinks(root = document) {
336
319
  const links = root.querySelectorAll(this.options.linkSelector);
337
320
  for (const link of links) {
338
321
  if (link.hasAttribute(this.options.noPrefetchAttribute)) continue;
@@ -358,19 +341,12 @@ class PrefetchManager {
358
341
  async prefetchStylesheets(html, url) {
359
342
  const parser = new DOMParser();
360
343
  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
- }
373
- }
344
+ const existingHrefs = /* @__PURE__ */ new Set([...getCurrentStylesheetHrefs(), ...this.prefetchedStylesheets]);
345
+ const newStylesheetHrefs = discoverNewStylesheetLinks(doc, existingHrefs).map((link) => link.href);
346
+ const stylesheetFetches = newStylesheetHrefs.map((href) => {
347
+ this.prefetchedStylesheets.add(href);
348
+ return this.prefetchStylesheet(href);
349
+ });
374
350
  await Promise.allSettled(stylesheetFetches);
375
351
  }
376
352
  async prefetchStylesheet(href) {
@@ -1,4 +1,4 @@
1
- import { applyViewTransitionNames, clearViewTransitionNames } from "../view-transition-utils.js";
1
+ import { applyViewTransitionNames, clearViewTransitionNames } from "@ecopages/core/client/view-transitions";
2
2
  class ViewTransitionManager {
3
3
  enabled;
4
4
  constructor(enabled) {
@@ -90,6 +90,12 @@ export interface EcoBeforeSwapEvent extends EcoNavigationEvent {
90
90
  /** Event fired after the DOM swap completes */
91
91
  export interface EcoAfterSwapEvent extends EcoNavigationEvent {
92
92
  }
93
+ /** Custom event map for navigation lifecycle */
94
+ export interface EcoRouterEventMap {
95
+ 'eco:before-swap': CustomEvent<EcoBeforeSwapEvent>;
96
+ 'eco:after-swap': CustomEvent<EcoAfterSwapEvent>;
97
+ 'eco:page-load': CustomEvent<EcoNavigationEvent>;
98
+ }
93
99
  /** Default document-level `<html>` attributes synchronized during navigation swaps. */
94
100
  export declare const DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC: string[];
95
101
  /** Default configuration options */