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

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 (153) hide show
  1. package/dist/actions.d.ts +7 -0
  2. package/dist/actions.js +23 -8
  3. package/dist/actions.test.js +8 -410
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/after.test.js +58 -0
  7. package/dist/assets-static.d.ts +10 -1
  8. package/dist/assets-static.js +10 -2
  9. package/dist/base-path.d.ts +7 -0
  10. package/dist/base-path.js +20 -0
  11. package/dist/builtin-tags.d.ts +12 -0
  12. package/dist/builtin-tags.js +42 -0
  13. package/dist/builtin-tags.test.js +12 -0
  14. package/dist/cache-adapter.test.js +4 -203
  15. package/dist/cache-scope.d.ts +2 -0
  16. package/dist/cache.test.js +1 -197
  17. package/dist/cloudflare-workers.d.ts +2 -0
  18. package/dist/cloudflare-workers.js +27 -0
  19. package/dist/dev-overlay.d.ts +54 -3
  20. package/dist/dev-overlay.js +469 -76
  21. package/dist/dom.js +17 -2
  22. package/dist/events.test.js +2 -407
  23. package/dist/handler-html.test.js +1 -202
  24. package/dist/handler-routing.js +3 -0
  25. package/dist/handler-segments.d.ts +6 -0
  26. package/dist/handler-segments.js +16 -2
  27. package/dist/handler-segments.test.js +8 -200
  28. package/dist/head-tags.d.ts +9 -0
  29. package/dist/head-tags.js +85 -1
  30. package/dist/head-tags.test.js +18 -125
  31. package/dist/index.d.ts +1 -0
  32. package/dist/index.js +3 -0
  33. package/dist/inline-action-token.test.js +31 -0
  34. package/dist/jsx-svg-types.test.js +58 -0
  35. package/dist/jsx-types.d.ts +92 -1
  36. package/dist/krate-core.js +1 -1
  37. package/dist/krate-dev.js +384 -65
  38. package/dist/krate-f-actions.js +1 -1
  39. package/dist/krate-f-navigation.js +1 -1
  40. package/dist/krate-f-router-lite.js +1 -1
  41. package/dist/krate-f-router.js +1 -1
  42. package/dist/krate-features.json +2 -0
  43. package/dist/krate-hydrate-lite.js +5 -5
  44. package/dist/krate-hydrate.js +5 -5
  45. package/dist/krate-runtime.js +5 -5
  46. package/dist/link-base-path.test.js +28 -0
  47. package/dist/metadata.js +3 -0
  48. package/dist/node-server.test.js +1 -355
  49. package/dist/platform.d.ts +52 -0
  50. package/dist/platform.js +57 -0
  51. package/dist/platform.test.js +44 -0
  52. package/dist/router-lite.js +3 -9
  53. package/dist/router-nav.test.js +15 -444
  54. package/dist/router.js +51 -18
  55. package/dist/server-handler.d.ts +49 -0
  56. package/dist/server-handler.js +311 -21
  57. package/dist/server-handler.test.js +56 -344
  58. package/dist/server-renderer.test.js +0 -104
  59. package/dist/server.d.ts +15 -5
  60. package/dist/server.js +150 -22
  61. package/dist/server.test.js +52 -60
  62. package/dist/site-config.d.ts +13 -0
  63. package/dist/site-config.js +28 -0
  64. package/dist/site-config.test.js +30 -0
  65. package/dist/ssr-core-behavior.test.js +3 -515
  66. package/dist/testing.d.ts +59 -0
  67. package/dist/testing.js +88 -0
  68. package/dist/testing.test.js +73 -0
  69. package/package.json +9 -1
  70. package/dist/action-context.test.js +0 -72
  71. package/dist/class-component.test.js +0 -462
  72. package/dist/class-helpers.test.js +0 -169
  73. package/dist/context.test.js +0 -57
  74. package/dist/derived.test.js +0 -140
  75. package/dist/dev-overlay.test.js +0 -165
  76. package/dist/discrete.test.js +0 -100
  77. package/dist/dom.test.js +0 -39
  78. package/dist/effect-errors.test.d.ts +0 -1
  79. package/dist/effect-errors.test.js +0 -199
  80. package/dist/effects.test.d.ts +0 -1
  81. package/dist/effects.test.js +0 -485
  82. package/dist/handler-routing.test.d.ts +0 -1
  83. package/dist/handler-routing.test.js +0 -99
  84. package/dist/highlight-bind.test.d.ts +0 -1
  85. package/dist/highlight-bind.test.js +0 -124
  86. package/dist/highlight.test.d.ts +0 -1
  87. package/dist/highlight.test.js +0 -56
  88. package/dist/lanes.test.d.ts +0 -1
  89. package/dist/lanes.test.js +0 -59
  90. package/dist/list.test.d.ts +0 -1
  91. package/dist/list.test.js +0 -435
  92. package/dist/metadata.test.d.ts +0 -1
  93. package/dist/metadata.test.js +0 -167
  94. package/dist/navigation.test.d.ts +0 -1
  95. package/dist/navigation.test.js +0 -130
  96. package/dist/optimistic-lanes.test.d.ts +0 -1
  97. package/dist/optimistic-lanes.test.js +0 -45
  98. package/dist/patterns.test.d.ts +0 -1
  99. package/dist/patterns.test.js +0 -125
  100. package/dist/portal.test.d.ts +0 -1
  101. package/dist/portal.test.js +0 -99
  102. package/dist/react-effects.test.d.ts +0 -1
  103. package/dist/react-effects.test.js +0 -133
  104. package/dist/react-suspense.test.d.ts +0 -1
  105. package/dist/react-suspense.test.js +0 -194
  106. package/dist/react.test.d.ts +0 -1
  107. package/dist/react.test.js +0 -60
  108. package/dist/react19.test.d.ts +0 -1
  109. package/dist/react19.test.js +0 -176
  110. package/dist/reactivity-core.test.d.ts +0 -1
  111. package/dist/reactivity-core.test.js +0 -152
  112. package/dist/reconcile.test.d.ts +0 -1
  113. package/dist/reconcile.test.js +0 -110
  114. package/dist/refs.test.d.ts +0 -1
  115. package/dist/refs.test.js +0 -257
  116. package/dist/router-layout.test.d.ts +0 -1
  117. package/dist/router-layout.test.js +0 -249
  118. package/dist/router-slots.test.d.ts +0 -1
  119. package/dist/router-slots.test.js +0 -144
  120. package/dist/router-speculation.test.d.ts +0 -1
  121. package/dist/router-speculation.test.js +0 -25
  122. package/dist/router-styles.test.d.ts +0 -1
  123. package/dist/router-styles.test.js +0 -98
  124. package/dist/router.test.d.ts +0 -1
  125. package/dist/router.test.js +0 -36
  126. package/dist/server-async.test.d.ts +0 -1
  127. package/dist/server-async.test.js +0 -216
  128. package/dist/server-highlight.test.d.ts +0 -1
  129. package/dist/server-highlight.test.js +0 -32
  130. package/dist/signal-lanes.test.d.ts +0 -1
  131. package/dist/signal-lanes.test.js +0 -32
  132. package/dist/slots.test.d.ts +0 -1
  133. package/dist/slots.test.js +0 -187
  134. package/dist/snapshots.test.d.ts +0 -1
  135. package/dist/snapshots.test.js +0 -208
  136. package/dist/ssr-core.test.d.ts +0 -1
  137. package/dist/ssr-core.test.js +0 -324
  138. package/dist/static-memory.test.d.ts +0 -1
  139. package/dist/static-memory.test.js +0 -26
  140. package/dist/storage.test.d.ts +0 -1
  141. package/dist/storage.test.js +0 -46
  142. package/dist/suspense-actions.test.d.ts +0 -1
  143. package/dist/suspense-actions.test.js +0 -72
  144. package/dist/suspense.test.d.ts +0 -1
  145. package/dist/suspense.test.js +0 -556
  146. /package/dist/{action-context.test.d.ts → after.test.d.ts} +0 -0
  147. /package/dist/{class-component.test.d.ts → builtin-tags.test.d.ts} +0 -0
  148. /package/dist/{class-helpers.test.d.ts → inline-action-token.test.d.ts} +0 -0
  149. /package/dist/{context.test.d.ts → jsx-svg-types.test.d.ts} +0 -0
  150. /package/dist/{derived.test.d.ts → link-base-path.test.d.ts} +0 -0
  151. /package/dist/{dev-overlay.test.d.ts → platform.test.d.ts} +0 -0
  152. /package/dist/{discrete.test.d.ts → site-config.test.d.ts} +0 -0
  153. /package/dist/{dom.test.d.ts → testing.test.d.ts} +0 -0
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
2
- import { initRouter, destroyRouter, krateRouter, navigate, getHistoryState, subscribeNavigation, invalidatePrefetchCache, } from './router';
2
+ import { initRouter, destroyRouter, krateRouter, } from './router';
3
3
  function page(title, body, head = '') {
4
4
  return `<!doctype html><html><head><title>${title}</title>${head}</head><body><div id="root">${body}</div></body></html>`;
5
5
  }
@@ -91,211 +91,28 @@ describe('SPA navigation', () => {
91
91
  expect(document.getElementById('__krate-route-announcer').textContent).toBe('About');
92
92
  expect(fetchMock).toHaveBeenCalledTimes(1);
93
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 }));
94
+ it('follows html and body attribute changes and keeps runtime-set ones', async () => {
95
+ routes['/themed'] = {
96
+ body: '<!doctype html><html class="dark" lang="fr"><head><title>T</title></head><body data-x="1"><div id="root"><h1>T</h1></div></body></html>',
97
+ };
98
+ document.documentElement.setAttribute('data-runtime', '1');
99
+ await krateRouter.push('/themed');
105
100
  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);
101
+ expect(document.documentElement.getAttribute('class')).toBe('dark');
102
+ expect(document.documentElement.getAttribute('lang')).toBe('fr');
103
+ expect(document.body.getAttribute('data-x')).toBe('1');
104
+ expect(document.documentElement.getAttribute('data-runtime')).toBe('1');
105
+ await krateRouter.push('/about');
122
106
  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('/');
107
+ expect(document.documentElement.hasAttribute('class')).toBe(false);
108
+ expect(document.body.hasAttribute('data-x')).toBe(false);
109
+ expect(document.documentElement.getAttribute('data-runtime')).toBe('1');
135
110
  });
136
111
  it('hard-navigates when a redirect leaves the origin', async () => {
137
112
  routes['/out'] = { body: page('x', ''), redirect: 'https://example.com/elsewhere' };
138
113
  await krateRouter.push('/out');
139
114
  expect(hardNavs[0][0]).toBe('https://example.com/elsewhere');
140
115
  });
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
116
  });
300
117
  describe('races', () => {
301
118
  it('a slower superseded navigation never overwrites a newer one', async () => {
@@ -311,249 +128,3 @@ describe('races', () => {
311
128
  expect(location.pathname).toBe('/about');
312
129
  });
313
130
  });
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
- });
package/dist/router.js CHANGED
@@ -5,6 +5,8 @@
5
5
  // place. All router state lives at module scope so `reinitRouter()` (called
6
6
  // by every page's hydration script) only refreshes per-page bindings and never
7
7
  // loses the prefetch cache, saved scroll positions or the in-flight navigation.
8
+ import { basePath, withBase } from './base-path.js';
9
+ import { siteConfig } from './site-config.js';
8
10
  /**
9
11
  * The shared runtime chunk is loaded once and must persist across SPA
10
12
  * navigations. Page-specific hydration scripts, in contrast, must be
@@ -13,14 +15,7 @@
13
15
  */
14
16
  const RUNTIME_CHUNK_RE = /\/chunks\/runtime\.[^/]+\.js$/;
15
17
  function runtimeConfig() {
16
- return globalThis.__KRATE_CFG__ || {};
17
- }
18
- /** Normalizes the configured base path to "" or "/prefix" (no trailing slash). */
19
- function basePath() {
20
- const bp = runtimeConfig().basePath || '';
21
- if (!bp || bp === '/')
22
- return '';
23
- return '/' + bp.replace(/^\/+|\/+$/g, '');
18
+ return siteConfig();
24
19
  }
25
20
  /** Strips the base path from a pathname so route comparisons are consistent. */
26
21
  function stripBase(pathname) {
@@ -445,14 +440,15 @@ function setupSpeculationRules() {
445
440
  try {
446
441
  const script = document.createElement('script');
447
442
  script.type = 'speculationrules';
443
+ const bp = basePath();
448
444
  script.textContent = JSON.stringify({
449
445
  prefetch: [
450
446
  {
451
447
  where: {
452
448
  and: [
453
- { href_matches: '/*' },
454
- { not: { href_matches: '/__krate/*' } },
455
- { not: { href_matches: '/api/*' } },
449
+ { href_matches: bp + '/*' },
450
+ { not: { href_matches: bp + '/__krate/*' } },
451
+ { not: { href_matches: bp + '/api/*' } },
456
452
  ],
457
453
  },
458
454
  eagerness: 'moderate',
@@ -632,6 +628,36 @@ function reconcileHeadMeta(doc) {
632
628
  document.head.appendChild(document.importNode(el, true));
633
629
  });
634
630
  }
631
+ let docAttrSnap = null;
632
+ function attrsOf(el) {
633
+ const out = {};
634
+ if (el)
635
+ for (const a of Array.from(el.attributes))
636
+ out[a.name] = a.value;
637
+ return out;
638
+ }
639
+ function docAttrsOf(d) {
640
+ return { html: attrsOf(d.documentElement), body: attrsOf(d.body) };
641
+ }
642
+ function reconcileDocAttrs(doc) {
643
+ const prev = docAttrSnap ?? docAttrsOf(document);
644
+ const next = docAttrsOf(doc);
645
+ const apply = (target, before, after) => {
646
+ if (!target)
647
+ return;
648
+ for (const name of new Set([...Object.keys(before), ...Object.keys(after)])) {
649
+ if (before[name] === after[name])
650
+ continue;
651
+ if (after[name] === undefined)
652
+ target.removeAttribute(name);
653
+ else
654
+ target.setAttribute(name, after[name]);
655
+ }
656
+ };
657
+ apply(document.documentElement, prev.html, next.html);
658
+ apply(document.body, prev.body, next.body);
659
+ docAttrSnap = next;
660
+ }
635
661
  function scriptsToLoad(doc, baseUrl) {
636
662
  const keep = new Set();
637
663
  document.querySelectorAll('script[src]:not([data-krate-spa])').forEach((s) => keep.add(s.src));
@@ -977,6 +1003,7 @@ async function commitDocument(loaded, req, seq) {
977
1003
  interceptSnapshots.clear();
978
1004
  sheets.commit();
979
1005
  reconcileHeadMeta(doc);
1006
+ reconcileDocAttrs(doc);
980
1007
  applyViewTransitionNames(document);
981
1008
  };
982
1009
  await runMutation(mutate);
@@ -1055,6 +1082,11 @@ function runMutation(mutate) {
1055
1082
  const vt = document.startViewTransition(once);
1056
1083
  if (vt && vt.finished && typeof vt.finished.catch === 'function')
1057
1084
  vt.finished.catch(() => { });
1085
+ // A newer navigation skips this transition; ready then rejects with
1086
+ // "Transition was skipped", which would otherwise surface as an unhandled
1087
+ // rejection on the page.
1088
+ if (vt && vt.ready && typeof vt.ready.catch === 'function')
1089
+ vt.ready.catch(() => { });
1058
1090
  const done = vt && vt.updateCallbackDone;
1059
1091
  if (done && typeof done.then === 'function') {
1060
1092
  return done.then(() => once(), () => once());
@@ -1712,18 +1744,18 @@ function refresh() {
1712
1744
  function push(url, opts = {}) {
1713
1745
  if (!initialized) {
1714
1746
  if (typeof location !== 'undefined')
1715
- location.assign(url);
1747
+ location.assign(withBase(url));
1716
1748
  return Promise.resolve();
1717
1749
  }
1718
- return start({ url, kind: 'push', scroll: opts.scroll !== false, state: opts.state });
1750
+ return start({ url: withBase(url), kind: 'push', scroll: opts.scroll !== false, state: opts.state });
1719
1751
  }
1720
1752
  function replace(url, opts = {}) {
1721
1753
  if (!initialized) {
1722
1754
  if (typeof location !== 'undefined')
1723
- location.replace(url);
1755
+ location.replace(withBase(url));
1724
1756
  return Promise.resolve();
1725
1757
  }
1726
- return start({ url, kind: 'replace', scroll: opts.scroll !== false, state: opts.state });
1758
+ return start({ url: withBase(url), kind: 'replace', scroll: opts.scroll !== false, state: opts.state });
1727
1759
  }
1728
1760
  /**
1729
1761
  * The router API. Every navigation method resolves once the new route's DOM
@@ -1752,7 +1784,7 @@ export const krateRouter = {
1752
1784
  return Promise.resolve();
1753
1785
  let u;
1754
1786
  try {
1755
- u = new URL(url, location.href);
1787
+ u = new URL(withBase(url), location.href);
1756
1788
  }
1757
1789
  catch {
1758
1790
  return Promise.resolve();
@@ -1777,9 +1809,9 @@ export function navigate(url, opts = {}) {
1777
1809
  }
1778
1810
  if (typeof location !== 'undefined') {
1779
1811
  if (opts.replace)
1780
- location.replace(url);
1812
+ location.replace(withBase(url));
1781
1813
  else
1782
- location.assign(url);
1814
+ location.assign(withBase(url));
1783
1815
  }
1784
1816
  return true;
1785
1817
  }
@@ -1795,6 +1827,7 @@ export function initRouter() {
1795
1827
  document.querySelectorAll('script[data-krate-boot]').forEach((s) => bootRan.add(s.textContent || ''));
1796
1828
  renderedPath = pathOf(location.href);
1797
1829
  currentChain = readRouteChain(document);
1830
+ docAttrSnap = docAttrsOf(document);
1798
1831
  docPath = renderedPath;
1799
1832
  currentKey = entryKey(history.state) || newKey();
1800
1833
  if (entryKey(history.state) === undefined) {