@krate/runtime 0.5.0-rc.1 → 0.5.0-rc.10

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 (214) hide show
  1. package/dist/action-context.js +1 -1
  2. package/dist/actions.d.ts +7 -0
  3. package/dist/actions.js +34 -10
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/assets-static.d.ts +10 -1
  7. package/dist/assets-static.js +10 -2
  8. package/dist/base-path.d.ts +7 -0
  9. package/dist/base-path.js +20 -0
  10. package/dist/boundary.js +1 -1
  11. package/dist/builtin-tags.d.ts +12 -0
  12. package/dist/builtin-tags.js +42 -0
  13. package/dist/cache-adapter.js +1 -1
  14. package/dist/cache-scope.d.ts +8 -0
  15. package/dist/cache-scope.js +14 -1
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/context.d.ts +5 -0
  19. package/dist/context.js +28 -17
  20. package/dist/dev-overlay.d.ts +54 -3
  21. package/dist/dev-overlay.js +470 -77
  22. package/dist/dom.js +18 -3
  23. package/dist/effects.js +2 -2
  24. package/dist/flight-props.d.ts +7 -0
  25. package/dist/flight-props.js +105 -0
  26. package/dist/handler-html.js +4 -4
  27. package/dist/handler-routing.d.ts +2 -23
  28. package/dist/handler-routing.js +9 -190
  29. package/dist/handler-segments.d.ts +6 -0
  30. package/dist/handler-segments.js +18 -4
  31. package/dist/head-tags.d.ts +9 -0
  32. package/dist/head-tags.js +93 -6
  33. package/dist/highlight-bind.js +1 -1
  34. package/dist/highlight.d.ts +3 -2
  35. package/dist/highlight.js +17 -12
  36. package/dist/hints.d.ts +25 -2
  37. package/dist/hints.js +147 -74
  38. package/dist/index.d.ts +2 -0
  39. package/dist/index.js +3 -0
  40. package/dist/island-swap.d.ts +47 -0
  41. package/dist/island-swap.js +635 -0
  42. package/dist/jsx-dev-runtime.d.ts +1 -1
  43. package/dist/jsx-types.d.ts +99 -3
  44. package/dist/krate-core.js +1 -1
  45. package/dist/krate-dev.js +385 -66
  46. package/dist/krate-f-actions.js +1 -1
  47. package/dist/krate-f-classes.js +1 -1
  48. package/dist/krate-f-highlight.js +1 -1
  49. package/dist/krate-f-list.js +1 -1
  50. package/dist/krate-f-navigation.js +1 -1
  51. package/dist/krate-f-router-lite.js +1 -1
  52. package/dist/krate-f-router.js +1 -1
  53. package/dist/krate-features.json +454 -0
  54. package/dist/krate-hydrate-lite.js +5 -5
  55. package/dist/krate-hydrate.js +5 -5
  56. package/dist/krate-island-swap.js +1 -0
  57. package/dist/krate-runtime.js +5 -5
  58. package/dist/list.d.ts +14 -4
  59. package/dist/list.js +4 -5
  60. package/dist/metadata.js +5 -2
  61. package/dist/navigation-react.d.ts +13 -0
  62. package/dist/navigation-react.js +86 -0
  63. package/dist/navigation.d.ts +19 -0
  64. package/dist/navigation.js +35 -0
  65. package/dist/node-server.js +3 -3
  66. package/dist/og.js +1 -1
  67. package/dist/platform.d.ts +52 -0
  68. package/dist/platform.js +57 -0
  69. package/dist/react-compat.d.ts +39 -0
  70. package/dist/react-compat.js +359 -0
  71. package/dist/react-server.d.ts +63 -0
  72. package/dist/react-server.js +125 -0
  73. package/dist/region-wire.d.ts +10 -0
  74. package/dist/region-wire.js +154 -0
  75. package/dist/request-context.js +1 -1
  76. package/dist/request-extras.d.ts +4 -0
  77. package/dist/request-extras.js +51 -0
  78. package/dist/resp.js +1 -1
  79. package/dist/route-source.d.ts +39 -0
  80. package/dist/route-source.js +532 -0
  81. package/dist/router-lite.js +3 -9
  82. package/dist/router.d.ts +1 -1
  83. package/dist/router.js +628 -98
  84. package/dist/server-handler.d.ts +69 -1
  85. package/dist/server-handler.js +515 -96
  86. package/dist/server-renderer.js +16 -7
  87. package/dist/server.d.ts +73 -16
  88. package/dist/server.js +619 -102
  89. package/dist/sha256.js +9 -9
  90. package/dist/signal.js +0 -6
  91. package/dist/site-config.d.ts +15 -0
  92. package/dist/site-config.js +28 -0
  93. package/dist/slot.d.ts +12 -0
  94. package/dist/slot.js +23 -0
  95. package/dist/ssr-core.d.ts +2 -0
  96. package/dist/ssr-core.js +12 -4
  97. package/dist/testing.d.ts +62 -0
  98. package/dist/testing.js +90 -0
  99. package/dist/use-id.js +1 -1
  100. package/package.json +28 -3
  101. package/dist/action-context.test.d.ts +0 -1
  102. package/dist/action-context.test.js +0 -72
  103. package/dist/actions.test.d.ts +0 -1
  104. package/dist/actions.test.js +0 -477
  105. package/dist/cache-adapter.test.d.ts +0 -1
  106. package/dist/cache-adapter.test.js +0 -244
  107. package/dist/cache.test.d.ts +0 -1
  108. package/dist/cache.test.js +0 -233
  109. package/dist/class-component.test.d.ts +0 -1
  110. package/dist/class-component.test.js +0 -462
  111. package/dist/class-helpers.test.d.ts +0 -1
  112. package/dist/class-helpers.test.js +0 -169
  113. package/dist/context.test.d.ts +0 -1
  114. package/dist/context.test.js +0 -57
  115. package/dist/derived.test.d.ts +0 -1
  116. package/dist/derived.test.js +0 -140
  117. package/dist/dev-overlay.test.d.ts +0 -1
  118. package/dist/dev-overlay.test.js +0 -165
  119. package/dist/discrete.test.d.ts +0 -1
  120. package/dist/discrete.test.js +0 -100
  121. package/dist/dom.test.d.ts +0 -1
  122. package/dist/dom.test.js +0 -39
  123. package/dist/effect-errors.test.d.ts +0 -1
  124. package/dist/effect-errors.test.js +0 -199
  125. package/dist/effects.test.d.ts +0 -1
  126. package/dist/effects.test.js +0 -485
  127. package/dist/events.test.d.ts +0 -1
  128. package/dist/events.test.js +0 -447
  129. package/dist/handler-html.test.d.ts +0 -1
  130. package/dist/handler-html.test.js +0 -256
  131. package/dist/handler-routing.test.d.ts +0 -1
  132. package/dist/handler-routing.test.js +0 -99
  133. package/dist/handler-segments.test.d.ts +0 -1
  134. package/dist/handler-segments.test.js +0 -217
  135. package/dist/head-tags.test.d.ts +0 -1
  136. package/dist/head-tags.test.js +0 -131
  137. package/dist/highlight-bind.test.d.ts +0 -1
  138. package/dist/highlight-bind.test.js +0 -124
  139. package/dist/highlight.test.d.ts +0 -1
  140. package/dist/highlight.test.js +0 -56
  141. package/dist/lanes.test.d.ts +0 -1
  142. package/dist/lanes.test.js +0 -59
  143. package/dist/list.test.d.ts +0 -1
  144. package/dist/list.test.js +0 -435
  145. package/dist/metadata.test.d.ts +0 -1
  146. package/dist/metadata.test.js +0 -167
  147. package/dist/navigation.test.d.ts +0 -1
  148. package/dist/navigation.test.js +0 -130
  149. package/dist/node-server.test.d.ts +0 -1
  150. package/dist/node-server.test.js +0 -492
  151. package/dist/optimistic-lanes.test.d.ts +0 -1
  152. package/dist/optimistic-lanes.test.js +0 -45
  153. package/dist/patterns.test.d.ts +0 -1
  154. package/dist/patterns.test.js +0 -125
  155. package/dist/portal.test.d.ts +0 -1
  156. package/dist/portal.test.js +0 -99
  157. package/dist/react-effects.test.d.ts +0 -1
  158. package/dist/react-effects.test.js +0 -133
  159. package/dist/react-suspense.test.d.ts +0 -1
  160. package/dist/react-suspense.test.js +0 -194
  161. package/dist/react.test.d.ts +0 -1
  162. package/dist/react.test.js +0 -60
  163. package/dist/react19.test.d.ts +0 -1
  164. package/dist/react19.test.js +0 -176
  165. package/dist/reactivity-core.test.d.ts +0 -1
  166. package/dist/reactivity-core.test.js +0 -152
  167. package/dist/reconcile.test.d.ts +0 -1
  168. package/dist/reconcile.test.js +0 -110
  169. package/dist/refs.test.d.ts +0 -1
  170. package/dist/refs.test.js +0 -257
  171. package/dist/router-layout.test.d.ts +0 -1
  172. package/dist/router-layout.test.js +0 -249
  173. package/dist/router-nav.test.d.ts +0 -1
  174. package/dist/router-nav.test.js +0 -559
  175. package/dist/router-slots.test.d.ts +0 -1
  176. package/dist/router-slots.test.js +0 -144
  177. package/dist/router-speculation.test.d.ts +0 -1
  178. package/dist/router-speculation.test.js +0 -25
  179. package/dist/router-styles.test.d.ts +0 -1
  180. package/dist/router-styles.test.js +0 -98
  181. package/dist/router.test.d.ts +0 -1
  182. package/dist/router.test.js +0 -36
  183. package/dist/server-async.test.d.ts +0 -1
  184. package/dist/server-async.test.js +0 -216
  185. package/dist/server-handler.test.d.ts +0 -1
  186. package/dist/server-handler.test.js +0 -535
  187. package/dist/server-highlight.test.d.ts +0 -1
  188. package/dist/server-highlight.test.js +0 -32
  189. package/dist/server-renderer.test.d.ts +0 -1
  190. package/dist/server-renderer.test.js +0 -266
  191. package/dist/server.test.d.ts +0 -1
  192. package/dist/server.test.js +0 -88
  193. package/dist/sha256.test.d.ts +0 -1
  194. package/dist/sha256.test.js +0 -13
  195. package/dist/signal-lanes.test.d.ts +0 -1
  196. package/dist/signal-lanes.test.js +0 -32
  197. package/dist/signal.test.d.ts +0 -1
  198. package/dist/signal.test.js +0 -68
  199. package/dist/slots.test.d.ts +0 -1
  200. package/dist/slots.test.js +0 -187
  201. package/dist/snapshots.test.d.ts +0 -1
  202. package/dist/snapshots.test.js +0 -208
  203. package/dist/ssr-core-behavior.test.d.ts +0 -1
  204. package/dist/ssr-core-behavior.test.js +0 -620
  205. package/dist/ssr-core.test.d.ts +0 -1
  206. package/dist/ssr-core.test.js +0 -324
  207. package/dist/static-memory.test.d.ts +0 -1
  208. package/dist/static-memory.test.js +0 -26
  209. package/dist/storage.test.d.ts +0 -1
  210. package/dist/storage.test.js +0 -46
  211. package/dist/suspense-actions.test.d.ts +0 -1
  212. package/dist/suspense-actions.test.js +0 -72
  213. package/dist/suspense.test.d.ts +0 -1
  214. package/dist/suspense.test.js +0 -556
@@ -1,559 +0,0 @@
1
- import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
2
- import { initRouter, destroyRouter, krateRouter, navigate, getHistoryState, subscribeNavigation, invalidatePrefetchCache, } from './router';
3
- function page(title, body, head = '') {
4
- return `<!doctype html><html><head><title>${title}</title>${head}</head><body><div id="root">${body}</div></body></html>`;
5
- }
6
- let routes;
7
- let fetchMock;
8
- let hardNavs;
9
- function installFetch() {
10
- fetchMock = vi.fn(async (input, init) => {
11
- const u = new URL(input, location.href);
12
- const r = routes[u.pathname + u.search] ?? routes[u.pathname];
13
- if (!r) {
14
- return mockResponse({ status: 404, body: 'nope', type: 'text/plain' }, u.href);
15
- }
16
- if (r.gate)
17
- await r.gate;
18
- if (init?.signal?.aborted) {
19
- const e = new Error('aborted');
20
- e.name = 'AbortError';
21
- throw e;
22
- }
23
- if (r.fail)
24
- throw r.fail;
25
- return mockResponse(r, r.redirect ? new URL(r.redirect, location.href).href : u.href);
26
- });
27
- vi.stubGlobal('fetch', fetchMock);
28
- }
29
- function mockResponse(r, url) {
30
- const status = r.status ?? 200;
31
- return {
32
- ok: status >= 200 && status < 300,
33
- status,
34
- url,
35
- redirected: !!r.redirect,
36
- headers: new Headers({ 'content-type': r.type ?? 'text/html; charset=utf-8' }),
37
- text: async () => r.body ?? '',
38
- };
39
- }
40
- function link(href, text, attrs = '') {
41
- return `<a data-krate-link href="${href}" ${attrs}>${text}</a>`;
42
- }
43
- function click(el) {
44
- el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 }));
45
- }
46
- async function settle() {
47
- for (let i = 0; i < 10; i++)
48
- await Promise.resolve();
49
- await new Promise((r) => setTimeout(r, 0));
50
- for (let i = 0; i < 10; i++)
51
- await Promise.resolve();
52
- }
53
- function events(name) {
54
- const got = [];
55
- window.addEventListener(name, (e) => got.push(e.detail));
56
- return got;
57
- }
58
- beforeEach(() => {
59
- destroyRouter();
60
- globalThis.__KRATE_CFG__ = { viewTransitions: false };
61
- history.replaceState(null, '', '/');
62
- document.title = 'Home';
63
- document.head.innerHTML = '<title>Home</title>';
64
- document.body.innerHTML = `<div id="root"><h1>Home</h1>${link('/about', 'About')}${link('/docs', 'Docs')}${link('/docs-old', 'Old')}</div>`;
65
- routes = {
66
- '/about': { body: page('About', `<h1>About</h1>${link('/', 'Home')}`) },
67
- '/docs': { body: page('Docs', `<h1>Docs</h1>${link('/docs', 'Docs')}${link('/docs/intro', 'Intro')}`) },
68
- '/docs/intro': { body: page('Intro', `<h1>Intro</h1>${link('/docs', 'Docs')}${link('/docs-old', 'Old')}`) },
69
- };
70
- installFetch();
71
- hardNavs = [];
72
- globalThis.__krateHardNavigate = (url, replace) => hardNavs.push([url, replace]);
73
- initRouter();
74
- });
75
- afterEach(() => {
76
- destroyRouter();
77
- vi.unstubAllGlobals();
78
- delete globalThis.__krateHardNavigate;
79
- delete globalThis.__KRATE_CFG__;
80
- delete document.startViewTransition;
81
- });
82
- describe('SPA navigation', () => {
83
- it('swaps the app root, title, history and announces the route', async () => {
84
- const nav = events('krate:navigate');
85
- click(document.querySelector('a[href="/about"]'));
86
- await settle();
87
- expect(location.pathname).toBe('/about');
88
- expect(document.querySelector('#root h1').textContent).toBe('About');
89
- expect(document.title).toBe('About');
90
- expect(nav.length).toBe(1);
91
- expect(document.getElementById('__krate-route-announcer').textContent).toBe('About');
92
- expect(fetchMock).toHaveBeenCalledTimes(1);
93
- });
94
- it('ignores modified clicks and target=_blank links', async () => {
95
- // Keep happy-dom from performing the default (real) navigation.
96
- const stop = (e) => e.preventDefault();
97
- window.addEventListener('click', stop);
98
- document.getElementById('root').innerHTML = link('/about', 'x', 'target="_blank"');
99
- click(document.querySelector('a'));
100
- const a = document.createElement('a');
101
- a.setAttribute('data-krate-link', '');
102
- a.href = '/about';
103
- document.body.appendChild(a);
104
- a.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, button: 0, metaKey: true }));
105
- await settle();
106
- window.removeEventListener('click', stop);
107
- expect(fetchMock).not.toHaveBeenCalled();
108
- });
109
- it('stores NavigateOptions.state on the history entry', async () => {
110
- await krateRouter.push('/about', { state: { from: 'test' } });
111
- expect(getHistoryState()).toEqual({ from: 'test' });
112
- expect(location.pathname).toBe('/about');
113
- });
114
- it('replace() does not add a history entry', async () => {
115
- const before = history.length;
116
- await krateRouter.replace('/about');
117
- expect(history.length).toBe(before);
118
- expect(location.pathname).toBe('/about');
119
- });
120
- it('navigate() drives the SPA router and returns false', async () => {
121
- expect(navigate('/about')).toBe(false);
122
- await settle();
123
- expect(document.title).toBe('About');
124
- });
125
- it('follows the final URL after a redirect', async () => {
126
- routes['/old'] = { body: page('About', '<h1>About</h1>'), redirect: '/about?moved=1' };
127
- await krateRouter.push('/old');
128
- expect(location.pathname + location.search).toBe('/about?moved=1');
129
- });
130
- it('hard-navigates for non-HTML responses', async () => {
131
- routes['/file.json'] = { body: '{}', type: 'application/json' };
132
- await krateRouter.push('/file.json');
133
- expect(hardNavs).toEqual([['http://localhost:3000/file.json', false]]);
134
- expect(location.pathname).toBe('/');
135
- });
136
- it('hard-navigates when a redirect leaves the origin', async () => {
137
- routes['/out'] = { body: page('x', ''), redirect: 'https://example.com/elsewhere' };
138
- await krateRouter.push('/out');
139
- expect(hardNavs[0][0]).toBe('https://example.com/elsewhere');
140
- });
141
- it('cancels a navigation when krate:navigate-start is prevented', async () => {
142
- const stop = (e) => e.preventDefault();
143
- window.addEventListener('krate:navigate-start', stop);
144
- await krateRouter.push('/about');
145
- window.removeEventListener('krate:navigate-start', stop);
146
- expect(fetchMock).not.toHaveBeenCalled();
147
- expect(location.pathname).toBe('/');
148
- });
149
- it('notifies subscribers with pathname, search and status', async () => {
150
- const seen = [];
151
- const off = subscribeNavigation((s) => seen.push(`${s.status}:${s.pathname}${s.search}`));
152
- await krateRouter.push('/docs?x=1');
153
- off();
154
- expect(seen).toContain('loading:/');
155
- expect(seen[seen.length - 1]).toBe('idle:/docs?x=1');
156
- });
157
- });
158
- describe('view transitions', () => {
159
- it('updates history and focus only after the transition callback ran', async () => {
160
- globalThis.__KRATE_CFG__ = { viewTransitions: 'auto' };
161
- const order = [];
162
- let release;
163
- const gate = new Promise((r) => (release = r));
164
- document.startViewTransition = (cb) => {
165
- // The browser runs the update callback asynchronously.
166
- const updateCallbackDone = gate.then(() => {
167
- order.push('mutate');
168
- cb();
169
- });
170
- return { updateCallbackDone, finished: updateCallbackDone };
171
- };
172
- const origPush = history.pushState.bind(history);
173
- const spy = vi.spyOn(history, 'pushState').mockImplementation((...args) => {
174
- order.push('push:' + document.title);
175
- origPush(...args);
176
- });
177
- const p = krateRouter.push('/about');
178
- await settle();
179
- expect(order).toEqual([]);
180
- release();
181
- await p;
182
- spy.mockRestore();
183
- expect(order).toEqual(['mutate', 'push:About']);
184
- });
185
- });
186
- describe('view transition names', () => {
187
- it('names elements and applies their transition class after a swap', async () => {
188
- routes['/vt'] = {
189
- body: page('VT', '<h1 id="hero" data-view-transition="hero" data-view-transition-class="slow-fade">x</h1>'),
190
- };
191
- await krateRouter.push('/vt');
192
- const hero = document.getElementById('hero');
193
- expect(hero.style.viewTransitionName).toBe('hero');
194
- expect(hero.style.getPropertyValue('view-transition-class')).toBe('slow-fade');
195
- });
196
- });
197
- describe('hash navigation', () => {
198
- it('handles hash-only links in place without fetching', async () => {
199
- document.getElementById('root').innerHTML = `${link('#sec', 'Sec')}<div id="sec">x</div>`;
200
- const scrolled = vi.fn();
201
- document.getElementById('sec').scrollIntoView = scrolled;
202
- click(document.querySelector('a'));
203
- await settle();
204
- expect(fetchMock).not.toHaveBeenCalled();
205
- expect(location.hash).toBe('#sec');
206
- expect(scrolled).toHaveBeenCalled();
207
- });
208
- it('does not refetch on a hash-only popstate', async () => {
209
- history.pushState(history.state, '', '/#a');
210
- window.dispatchEvent(new PopStateEvent('popstate', { state: history.state }));
211
- await settle();
212
- expect(fetchMock).not.toHaveBeenCalled();
213
- });
214
- it('a same-page link with a hash scrolls instead of fetching', async () => {
215
- await krateRouter.push('/docs');
216
- fetchMock.mockClear();
217
- await krateRouter.push('/docs#part');
218
- expect(fetchMock).not.toHaveBeenCalled();
219
- expect(location.href).toBe('http://localhost:3000/docs#part');
220
- });
221
- });
222
- describe('scroll restoration', () => {
223
- it('restores the scroll position of the entry being returned to', async () => {
224
- routes['/'] = { body: page('Home', '<h1>Home</h1>') };
225
- const homeState = history.state;
226
- window.scrollTo(0, 420);
227
- await krateRouter.push('/about');
228
- expect(window.scrollY).toBe(0);
229
- const aboutState = history.state;
230
- window.scrollTo(0, 77);
231
- // Simulate the browser's history step back to "/": the URL and state
232
- // change first, then popstate fires.
233
- history.replaceState(homeState, '', '/');
234
- window.dispatchEvent(new PopStateEvent('popstate', { state: homeState }));
235
- await settle();
236
- expect(document.title).toBe('Home');
237
- expect(window.scrollY).toBe(420);
238
- history.replaceState(aboutState, '', '/about');
239
- window.dispatchEvent(new PopStateEvent('popstate', { state: aboutState }));
240
- await settle();
241
- expect(document.title).toBe('About');
242
- expect(window.scrollY).toBe(77);
243
- });
244
- });
245
- describe('error handling', () => {
246
- it('shows a server-rendered 404 document in place and reports the status', async () => {
247
- const errs = events('krate:navigate-error');
248
- routes['/missing'] = { status: 404, body: page('Not found', '<h1>Not found</h1>') };
249
- await krateRouter.push('/missing');
250
- expect(document.title).toBe('Not found');
251
- expect(location.pathname).toBe('/missing');
252
- expect(errs).toEqual([{ url: 'http://localhost:3000/missing', status: 404 }]);
253
- expect(hardNavs).toEqual([]);
254
- });
255
- it('falls back to <basePath>/404.html when the 404 response is not HTML', async () => {
256
- globalThis.__KRATE_CFG__ = { viewTransitions: false, basePath: '/app' };
257
- routes['/app/gone'] = { status: 404, body: 'nope', type: 'text/plain' };
258
- routes['/app/404.html'] = { body: page('404', '<h1>Lost</h1>') };
259
- await krateRouter.push('/app/gone');
260
- expect(document.querySelector('#root h1').textContent).toBe('Lost');
261
- expect(fetchMock.mock.calls.map((c) => new URL(c[0], location.href).pathname)).toContain('/app/404.html');
262
- });
263
- it('uses /500.html for server errors without an HTML body', async () => {
264
- routes['/boom'] = { status: 503, body: '', type: 'text/plain' };
265
- routes['/500.html'] = { body: page('Error', '<h1>Broken</h1>') };
266
- await krateRouter.push('/boom');
267
- expect(document.querySelector('#root h1').textContent).toBe('Broken');
268
- });
269
- it('does not show the 404 page for 403 responses', async () => {
270
- routes['/secret'] = { status: 403, body: 'forbidden', type: 'text/plain' };
271
- routes['/404.html'] = { body: page('404', '<h1>Lost</h1>') };
272
- await krateRouter.push('/secret');
273
- expect(hardNavs).toEqual([['http://localhost:3000/secret', false]]);
274
- expect(document.querySelector('#root h1').textContent).toBe('Home');
275
- });
276
- it('emits krate:navigate-error on network failure, then hard-navigates', async () => {
277
- const errs = events('krate:navigate-error');
278
- routes['/net'] = { fail: new TypeError('Failed to fetch') };
279
- await krateRouter.push('/net');
280
- expect(errs.length).toBe(1);
281
- expect(errs[0].status).toBe(0);
282
- expect(hardNavs).toEqual([['http://localhost:3000/net', false]]);
283
- });
284
- it('lets the app cancel the hard-reload fallback', async () => {
285
- const stop = (e) => e.preventDefault();
286
- window.addEventListener('krate:navigate-error', stop);
287
- routes['/net'] = { fail: new TypeError('Failed to fetch') };
288
- await krateRouter.push('/net');
289
- window.removeEventListener('krate:navigate-error', stop);
290
- expect(hardNavs).toEqual([]);
291
- expect(location.pathname).toBe('/');
292
- });
293
- it('never uses document.write', async () => {
294
- const spy = vi.spyOn(document, 'write');
295
- routes['/missing'] = { status: 404, body: page('Not found', '<h1>Not found</h1>') };
296
- await krateRouter.push('/missing');
297
- expect(spy).not.toHaveBeenCalled();
298
- });
299
- });
300
- describe('races', () => {
301
- it('a slower superseded navigation never overwrites a newer one', async () => {
302
- let open;
303
- routes['/slow'] = { body: page('Slow', '<h1>Slow</h1>'), gate: new Promise((r) => (open = r)) };
304
- const first = krateRouter.push('/slow');
305
- const second = krateRouter.push('/about');
306
- await second;
307
- open();
308
- await first;
309
- await settle();
310
- expect(document.title).toBe('About');
311
- expect(location.pathname).toBe('/about');
312
- });
313
- });
314
- describe('in-document steps while a page loads', () => {
315
- it('a hash link cancels the navigation still loading', async () => {
316
- let open;
317
- routes['/slow'] = { body: page('Slow', '<h1>Slow</h1>'), gate: new Promise((r) => (open = r)) };
318
- const loading = krateRouter.push('/slow');
319
- await settle();
320
- await krateRouter.push('/#top');
321
- open();
322
- await loading;
323
- await settle();
324
- expect(location.pathname + location.hash).toBe('/#top');
325
- expect(document.querySelector('#root h1').textContent).toBe('Home');
326
- expect(krateRouter.getState().status).toBe('idle');
327
- });
328
- it('going back over a hash entry cancels the navigation still loading', async () => {
329
- await krateRouter.push('/#a');
330
- await krateRouter.push('/#b');
331
- let open;
332
- routes['/slow'] = { body: page('Slow', '<h1>Slow</h1>'), gate: new Promise((r) => (open = r)) };
333
- const loading = krateRouter.push('/slow');
334
- await settle();
335
- history.back();
336
- await settle();
337
- open();
338
- await loading;
339
- await settle();
340
- expect(location.pathname + location.hash).toBe('/#a');
341
- expect(document.querySelector('#root h1').textContent).toBe('Home');
342
- });
343
- });
344
- describe('prefetch cache', () => {
345
- it('serves a prefetched document once, then refetches', async () => {
346
- await krateRouter.prefetch('/about');
347
- expect(fetchMock).toHaveBeenCalledTimes(1);
348
- await krateRouter.push('/about');
349
- expect(fetchMock).toHaveBeenCalledTimes(1);
350
- routes['/'] = { body: page('Home', '<h1>Home</h1>') };
351
- await krateRouter.push('/');
352
- await krateRouter.push('/about');
353
- // The cache hit was consumed: revisiting fetches fresh HTML.
354
- expect(fetchMock.mock.calls.filter((c) => String(c[0]).endsWith('/about')).length).toBe(2);
355
- });
356
- it('keeps the fragment of the link when the document was prefetched', async () => {
357
- routes['/about'] = { body: page('About', '<h1>About</h1><h2 id="team">Team</h2>') };
358
- const original = Element.prototype.scrollIntoView;
359
- const scrolled = vi.fn();
360
- Element.prototype.scrollIntoView = scrolled;
361
- try {
362
- await krateRouter.prefetch('/about#team');
363
- await krateRouter.push('/about#team');
364
- await settle();
365
- expect(location.pathname + location.hash).toBe('/about#team');
366
- expect(scrolled).toHaveBeenCalled();
367
- }
368
- finally {
369
- Element.prototype.scrollIntoView = original;
370
- }
371
- });
372
- it('expires entries after the TTL', async () => {
373
- globalThis.__KRATE_CFG__ = { viewTransitions: false, prefetchTTL: 0 };
374
- await krateRouter.prefetch('/about');
375
- await new Promise((r) => setTimeout(r, 5));
376
- await krateRouter.push('/about');
377
- expect(fetchMock).toHaveBeenCalledTimes(2);
378
- });
379
- it('invalidatePrefetchCache drops entries', async () => {
380
- await krateRouter.prefetch('/about');
381
- invalidatePrefetchCache('/about');
382
- await krateRouter.push('/about');
383
- expect(fetchMock).toHaveBeenCalledTimes(2);
384
- });
385
- it('a prefetch in flight when the cache is invalidated does not repopulate it', async () => {
386
- let release;
387
- routes['/about'].gate = new Promise((r) => (release = r));
388
- const inflight = krateRouter.prefetch('/about');
389
- await settle();
390
- invalidatePrefetchCache();
391
- release();
392
- await inflight;
393
- await krateRouter.push('/about');
394
- // The stale response was dropped, so navigating fetched again.
395
- expect(fetchMock).toHaveBeenCalledTimes(2);
396
- });
397
- it('invalidating one URL also drops its prefetch in flight', async () => {
398
- let release;
399
- routes['/about'].gate = new Promise((r) => (release = r));
400
- const inflight = krateRouter.prefetch('/about');
401
- await settle();
402
- invalidatePrefetchCache('/about');
403
- release();
404
- await inflight;
405
- await krateRouter.push('/about');
406
- expect(fetchMock).toHaveBeenCalledTimes(2);
407
- });
408
- it('does not cache error responses', async () => {
409
- routes['/missing'] = { status: 404, body: page('Not found', '') };
410
- await krateRouter.prefetch('/missing');
411
- await krateRouter.push('/missing');
412
- expect(fetchMock).toHaveBeenCalledTimes(2);
413
- });
414
- });
415
- describe('refresh and revalidation', () => {
416
- it('refresh() refetches the current route bypassing the cache and keeps history', async () => {
417
- await krateRouter.push('/about');
418
- routes['/about'] = { body: page('About v2', '<h1>About v2</h1>') };
419
- await krateRouter.prefetch('/about');
420
- const len = history.length;
421
- window.scrollTo(0, 33);
422
- await krateRouter.refresh();
423
- expect(document.title).toBe('About v2');
424
- expect(history.length).toBe(len);
425
- expect(window.scrollY).toBe(33);
426
- const last = fetchMock.mock.calls[fetchMock.mock.calls.length - 1];
427
- expect(last[1].cache).toBe('no-cache');
428
- });
429
- it('krate:revalidate refreshes the current route', async () => {
430
- await krateRouter.push('/about');
431
- routes['/about'] = { body: page('Fresh', '<h1>Fresh</h1>') };
432
- window.dispatchEvent(new CustomEvent('krate:revalidate', { detail: { paths: ['/about'] } }));
433
- await settle();
434
- expect(document.title).toBe('Fresh');
435
- });
436
- });
437
- describe('active links', () => {
438
- it('marks exact matches with aria-current and segments separately', async () => {
439
- await krateRouter.push('/docs/intro');
440
- const docs = document.querySelector('a[href="/docs"]');
441
- const old = document.querySelector('a[href="/docs-old"]');
442
- expect(docs.getAttribute('aria-current')).toBeNull();
443
- expect(docs.getAttribute('data-krate-active')).toBe('segment');
444
- expect(old.hasAttribute('data-krate-active')).toBe(false);
445
- await krateRouter.push('/docs');
446
- expect(document.querySelector('a[href="/docs"]').getAttribute('aria-current')).toBe('page');
447
- });
448
- });
449
- describe('forms', () => {
450
- it('intercepts GET form submissions', async () => {
451
- routes['/search'] = { body: page('Search', '<h1>Results</h1>') };
452
- document.getElementById('root').innerHTML =
453
- '<form action="/search"><input name="q" value="krate"><button name="go" value="1">Go</button></form>';
454
- const form = document.querySelector('form');
455
- const ev = new Event('submit', { bubbles: true, cancelable: true });
456
- ev.submitter = form.querySelector('button');
457
- form.dispatchEvent(ev);
458
- expect(ev.defaultPrevented).toBe(true);
459
- await settle();
460
- expect(location.pathname + location.search).toBe('/search?q=krate&go=1');
461
- expect(document.title).toBe('Search');
462
- });
463
- it('leaves POST forms alone', async () => {
464
- document.getElementById('root').innerHTML = '<form method="post" action="/search"><input name="q"></form>';
465
- const ev = new Event('submit', { bubbles: true, cancelable: true });
466
- document.querySelector('form').dispatchEvent(ev);
467
- expect(ev.defaultPrevented).toBe(false);
468
- });
469
- });
470
- describe('focus', () => {
471
- it('focuses the root temporarily and removes tabindex on blur', async () => {
472
- await krateRouter.push('/about');
473
- const root = document.getElementById('root');
474
- expect(document.activeElement).toBe(root);
475
- expect(root.getAttribute('tabindex')).toBe('-1');
476
- root.blur();
477
- expect(root.hasAttribute('tabindex')).toBe(false);
478
- });
479
- });
480
- describe('fallback fade and reduced motion', () => {
481
- function stubReducedMotion(reduce) {
482
- vi.stubGlobal('matchMedia', (q) => ({
483
- matches: reduce && q.includes('prefers-reduced-motion'),
484
- media: q,
485
- addEventListener() { },
486
- removeEventListener() { },
487
- addListener() { },
488
- removeListener() { },
489
- }));
490
- window.matchMedia = globalThis.matchMedia;
491
- }
492
- async function rootStyleDuringFetch() {
493
- let release;
494
- routes['/about'].gate = new Promise((r) => (release = r));
495
- const p = krateRouter.push('/about');
496
- await settle();
497
- const el = document.getElementById('root');
498
- const seen = { transition: el.style.transition, opacity: el.style.opacity };
499
- release();
500
- await p;
501
- await settle();
502
- return seen;
503
- }
504
- it('applies the opacity fade without View Transitions', async () => {
505
- stubReducedMotion(false);
506
- const seen = await rootStyleDuringFetch();
507
- expect(seen.opacity).toBe('0');
508
- expect(seen.transition).toContain('opacity');
509
- });
510
- it('applies no fade under prefers-reduced-motion', async () => {
511
- stubReducedMotion(true);
512
- const seen = await rootStyleDuringFetch();
513
- expect(seen.opacity).toBe('');
514
- expect(seen.transition).toBe('');
515
- expect(document.querySelector('#root h1').textContent).toBe('About');
516
- });
517
- });
518
- describe('inline boot scripts', () => {
519
- const bootPage = (title) => page(title, `<h1>${title}</h1>${link('/', 'Home')}<script data-krate-boot>window.__boots=1;</script>`);
520
- // happy-dom does not execute inline scripts: count the ones handed to the document.
521
- let ran;
522
- beforeEach(() => {
523
- ran = [];
524
- const append = document.head.appendChild.bind(document.head);
525
- vi.spyOn(document.head, 'appendChild').mockImplementation(((node) => {
526
- if (node instanceof HTMLScriptElement && !node.src)
527
- ran.push(node.text);
528
- return append(node);
529
- }));
530
- });
531
- afterEach(() => vi.restoreAllMocks());
532
- it('runs a boot script of the new page once, not on every visit', async () => {
533
- routes['/aria'] = { body: bootPage('Aria') };
534
- routes['/aria2'] = { body: bootPage('Aria2') };
535
- await krateRouter.push('/aria');
536
- await settle();
537
- expect(ran).toEqual(['window.__boots=1;']);
538
- await krateRouter.push('/aria2');
539
- await krateRouter.push('/about');
540
- await krateRouter.push('/aria');
541
- await settle();
542
- expect(ran).toEqual(['window.__boots=1;']);
543
- });
544
- it('does not rerun the boot script the first document already ran', async () => {
545
- destroyRouter();
546
- document.body.innerHTML += '<script data-krate-boot>window.__boots=1;</script>';
547
- initRouter();
548
- routes['/aria'] = { body: bootPage('Aria') };
549
- await krateRouter.push('/aria');
550
- await settle();
551
- expect(ran).toEqual([]);
552
- });
553
- it('leaves ordinary inline scripts alone', async () => {
554
- routes['/plain'] = { body: page('Plain', '<h1>Plain</h1><script>window.__boots=99;</script>') };
555
- await krateRouter.push('/plain');
556
- await settle();
557
- expect(ran).toEqual([]);
558
- });
559
- });
@@ -1 +0,0 @@
1
- export {};