@krate/runtime 0.5.0-alpha.4 → 0.5.0-beta.2

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 (165) hide show
  1. package/dist/action-context.d.ts +5 -1
  2. package/dist/action-context.js +33 -3
  3. package/dist/action-context.test.js +26 -1
  4. package/dist/actions.d.ts +12 -1
  5. package/dist/actions.js +84 -4
  6. package/dist/actions.test.js +61 -1
  7. package/dist/assets-static.d.ts +5 -0
  8. package/dist/assets-static.js +31 -0
  9. package/dist/boundary.d.ts +12 -0
  10. package/dist/boundary.js +53 -13
  11. package/dist/cache-adapter.d.ts +113 -0
  12. package/dist/cache-adapter.js +217 -0
  13. package/dist/cache-adapter.test.d.ts +1 -0
  14. package/dist/cache-adapter.test.js +244 -0
  15. package/dist/cache-redis.d.ts +27 -0
  16. package/dist/cache-redis.js +110 -0
  17. package/dist/cache-scope.d.ts +25 -9
  18. package/dist/cache-scope.js +64 -13
  19. package/dist/cache.d.ts +1 -0
  20. package/dist/cache.js +3 -3
  21. package/dist/cache.test.js +16 -0
  22. package/dist/class-component.js +6 -0
  23. package/dist/class-component.test.js +53 -2
  24. package/dist/class-helpers.d.ts +4 -4
  25. package/dist/class-helpers.js +357 -32
  26. package/dist/class-helpers.test.d.ts +1 -0
  27. package/dist/class-helpers.test.js +169 -0
  28. package/dist/context.d.ts +16 -2
  29. package/dist/context.js +44 -3
  30. package/dist/dev-overlay.js +85 -12
  31. package/dist/dev-overlay.test.js +22 -0
  32. package/dist/dom.d.ts +15 -0
  33. package/dist/dom.js +97 -3
  34. package/dist/effect-errors.test.d.ts +1 -0
  35. package/dist/effect-errors.test.js +163 -0
  36. package/dist/effects.d.ts +8 -0
  37. package/dist/effects.js +13 -0
  38. package/dist/error-overlay.js +7 -7
  39. package/dist/handler-html.d.ts +63 -0
  40. package/dist/handler-html.js +285 -0
  41. package/dist/handler-html.test.d.ts +1 -0
  42. package/dist/handler-html.test.js +256 -0
  43. package/dist/handler-routing.d.ts +83 -0
  44. package/dist/handler-routing.js +579 -0
  45. package/dist/handler-routing.test.d.ts +1 -0
  46. package/dist/handler-routing.test.js +99 -0
  47. package/dist/handler-segments.d.ts +43 -0
  48. package/dist/handler-segments.js +115 -0
  49. package/dist/handler-segments.test.d.ts +1 -0
  50. package/dist/handler-segments.test.js +217 -0
  51. package/dist/head-tags.d.ts +51 -0
  52. package/dist/head-tags.js +329 -0
  53. package/dist/head-tags.test.d.ts +1 -0
  54. package/dist/head-tags.test.js +131 -0
  55. package/dist/highlight-bind.d.ts +42 -0
  56. package/dist/highlight-bind.js +176 -0
  57. package/dist/highlight-bind.test.d.ts +1 -0
  58. package/dist/highlight-bind.test.js +124 -0
  59. package/dist/highlight.d.ts +93 -0
  60. package/dist/highlight.js +426 -0
  61. package/dist/highlight.test.d.ts +1 -0
  62. package/dist/highlight.test.js +56 -0
  63. package/dist/hints.d.ts +19 -0
  64. package/dist/hints.js +97 -0
  65. package/dist/hook-args.d.ts +7 -0
  66. package/dist/hook-args.js +10 -0
  67. package/dist/htmlspec-attributes.d.ts +1 -0
  68. package/dist/htmlspec-attributes.js +159 -0
  69. package/dist/index.d.ts +4 -0
  70. package/dist/index.js +3 -0
  71. package/dist/jsx-types.d.ts +11 -0
  72. package/dist/krate-core.js +2 -0
  73. package/dist/krate-dev.js +75 -12
  74. package/dist/krate-f-actions.js +2 -0
  75. package/dist/krate-f-classes.js +8 -0
  76. package/dist/krate-f-helpers.js +2 -0
  77. package/dist/krate-f-highlight.js +2 -0
  78. package/dist/krate-f-list.js +2 -0
  79. package/dist/krate-f-navigation.js +2 -0
  80. package/dist/krate-f-router-lite.js +2 -0
  81. package/dist/krate-f-router.js +2 -0
  82. package/dist/krate-features.json +493 -0
  83. package/dist/krate-hydrate-lite.js +5 -5
  84. package/dist/krate-hydrate.js +5 -5
  85. package/dist/krate-runtime.js +5 -5
  86. package/dist/list.js +4 -2
  87. package/dist/metadata-routes.d.ts +75 -0
  88. package/dist/metadata-routes.js +76 -0
  89. package/dist/metadata.d.ts +222 -0
  90. package/dist/metadata.js +452 -0
  91. package/dist/metadata.test.d.ts +1 -0
  92. package/dist/metadata.test.js +167 -0
  93. package/dist/navigation-server.d.ts +27 -0
  94. package/dist/navigation-server.js +90 -0
  95. package/dist/navigation.d.ts +37 -0
  96. package/dist/navigation.js +195 -0
  97. package/dist/navigation.test.d.ts +1 -0
  98. package/dist/navigation.test.js +130 -0
  99. package/dist/node-server.d.ts +22 -0
  100. package/dist/node-server.js +436 -0
  101. package/dist/node-server.test.d.ts +1 -0
  102. package/dist/node-server.test.js +492 -0
  103. package/dist/og-files.d.ts +2 -0
  104. package/dist/og-files.js +19 -0
  105. package/dist/og.d.ts +56 -0
  106. package/dist/og.js +156 -0
  107. package/dist/patterns.test.d.ts +1 -0
  108. package/dist/patterns.test.js +98 -0
  109. package/dist/react.d.ts +47 -0
  110. package/dist/react.js +59 -1
  111. package/dist/react19.test.d.ts +1 -0
  112. package/dist/react19.test.js +176 -0
  113. package/dist/reactivity-core.test.d.ts +1 -0
  114. package/dist/reactivity-core.test.js +152 -0
  115. package/dist/reconcile.js +4 -2
  116. package/dist/request-context.d.ts +23 -0
  117. package/dist/request-context.js +45 -0
  118. package/dist/resp.d.ts +55 -0
  119. package/dist/resp.js +239 -0
  120. package/dist/router-layout.test.js +70 -0
  121. package/dist/router-nav.test.js +65 -0
  122. package/dist/router-speculation.test.d.ts +1 -0
  123. package/dist/router-speculation.test.js +25 -0
  124. package/dist/router-styles.test.d.ts +1 -0
  125. package/dist/router-styles.test.js +98 -0
  126. package/dist/router.js +175 -36
  127. package/dist/segmented-lru.d.ts +19 -0
  128. package/dist/segmented-lru.js +87 -0
  129. package/dist/server-async.test.js +43 -1
  130. package/dist/server-handler.d.ts +165 -0
  131. package/dist/server-handler.js +1826 -0
  132. package/dist/server-handler.test.d.ts +1 -0
  133. package/dist/server-handler.test.js +522 -0
  134. package/dist/server-highlight.test.d.ts +1 -0
  135. package/dist/server-highlight.test.js +32 -0
  136. package/dist/server-renderer.js +165 -720
  137. package/dist/server-renderer.test.d.ts +1 -0
  138. package/dist/server-renderer.test.js +266 -0
  139. package/dist/server.d.ts +13 -1
  140. package/dist/server.js +131 -16
  141. package/dist/server.test.js +20 -0
  142. package/dist/sha256.d.ts +1 -0
  143. package/dist/sha256.js +66 -0
  144. package/dist/sha256.test.d.ts +1 -0
  145. package/dist/sha256.test.js +13 -0
  146. package/dist/shared-isr.d.ts +31 -0
  147. package/dist/shared-isr.js +142 -0
  148. package/dist/signal.d.ts +3 -2
  149. package/dist/signal.js +163 -23
  150. package/dist/slots.js +12 -1
  151. package/dist/ssr-core-behavior.test.d.ts +1 -0
  152. package/dist/ssr-core-behavior.test.js +620 -0
  153. package/dist/ssr-core.d.ts +175 -0
  154. package/dist/ssr-core.js +940 -0
  155. package/dist/ssr-core.test.d.ts +1 -0
  156. package/dist/ssr-core.test.js +324 -0
  157. package/dist/static-memory.d.ts +3 -0
  158. package/dist/static-memory.js +47 -0
  159. package/dist/static-memory.test.d.ts +1 -0
  160. package/dist/static-memory.test.js +26 -0
  161. package/dist/test-redis.d.ts +12 -0
  162. package/dist/test-redis.js +131 -0
  163. package/dist/use-id.d.ts +8 -0
  164. package/dist/use-id.js +40 -0
  165. package/package.json +30 -2
@@ -17,7 +17,11 @@ export interface ActionCookieOptions {
17
17
  }
18
18
  /** Cookie access for the current action request. */
19
19
  export interface ActionCookies {
20
- get(name: string): string | undefined;
20
+ /** Returns `{ name, value }` like Next.js, or undefined when the cookie is absent. */
21
+ get(name: string): {
22
+ name: string;
23
+ value: string;
24
+ } | undefined;
21
25
  getAll(): Array<{
22
26
  name: string;
23
27
  value: string;
@@ -5,11 +5,37 @@
5
5
  * publishes it on `globalThis[Symbol.for('krate.action.store')]`. These helpers
6
6
  * read that scope, so they only work while a server action is executing.
7
7
  */
8
+ import { markNoStore } from './cache-scope.js';
8
9
  import { getRequestContext, requestCookies, thenable } from './request-context.js';
9
10
  /** The current action context, or undefined outside a server action. */
10
11
  export function getActionContext() {
11
12
  const store = globalThis[Symbol.for('krate.action.store')];
12
- return store && typeof store.getStore === 'function' ? store.getStore() : undefined;
13
+ const ctx = store && typeof store.getStore === 'function' ? store.getStore() : undefined;
14
+ return ctx ? withNextCookies(ctx) : undefined;
15
+ }
16
+ // The sidecar's jar returns the bare value from get(); expose the Next.js
17
+ // shape ({ name, value }) the server-component view already uses.
18
+ const wrapped = new WeakMap();
19
+ function withNextCookies(ctx) {
20
+ let out = wrapped.get(ctx);
21
+ if (!out) {
22
+ const jar = ctx.cookies;
23
+ const cookies = {
24
+ get: (name) => {
25
+ const v = jar.get(name);
26
+ if (v === undefined || v === null)
27
+ return undefined;
28
+ return typeof v === 'object' ? v : { name, value: String(v) };
29
+ },
30
+ getAll: () => jar.getAll(),
31
+ has: (name) => jar.has(name),
32
+ set: (name, value, options) => jar.set(name, value, options),
33
+ delete: (name, options) => jar.delete(name, options),
34
+ };
35
+ out = { ...ctx, cookies };
36
+ wrapped.set(ctx, out);
37
+ }
38
+ return out;
13
39
  }
14
40
  function requireContext(api) {
15
41
  const ctx = getActionContext();
@@ -28,8 +54,10 @@ export function headers() {
28
54
  if (action)
29
55
  return awaitableHeaders(action.headers);
30
56
  const req = getRequestContext();
31
- if (req)
57
+ if (req) {
58
+ markNoStore();
32
59
  return awaitableHeaders(req.headers);
60
+ }
33
61
  return requireContext('headers').headers;
34
62
  }
35
63
  /**
@@ -42,8 +70,10 @@ export function cookies() {
42
70
  if (action)
43
71
  return awaitableActionCookies(action.cookies);
44
72
  const req = getRequestContext();
45
- if (req)
73
+ if (req) {
74
+ markNoStore();
46
75
  return requestCookies(req.cookies);
76
+ }
47
77
  return requireContext('cookies').cookies;
48
78
  }
49
79
  function awaitableActionCookies(c) {
@@ -1,9 +1,13 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
1
2
  import { afterEach, describe, expect, it } from 'vitest';
2
3
  import { cookies, getActionContext, headers, redirect } from './action-context.js';
4
+ import { installRenderStore, withCacheScope } from './cache-scope.js';
3
5
  import { jsx, renderToString } from './server.js';
4
6
  const KEY = Symbol.for('krate.action.store');
7
+ const REQUEST_KEY = Symbol.for('krate.request.store');
5
8
  afterEach(() => {
6
9
  delete globalThis[KEY];
10
+ delete globalThis[REQUEST_KEY];
7
11
  });
8
12
  describe('server action context', () => {
9
13
  it('throws outside an action with an actionable message', () => {
@@ -27,9 +31,30 @@ describe('server action context', () => {
27
31
  };
28
32
  globalThis[KEY] = { getStore: () => ctx };
29
33
  expect(headers().get('x-test')).toBe('yes');
30
- expect(cookies().get('sid')).toBe('abc');
34
+ expect(cookies().get('sid')).toEqual({ name: 'sid', value: 'abc' });
35
+ expect(cookies().get('sid')?.value).toBe('abc');
36
+ expect(cookies().get('missing')).toBeUndefined();
37
+ expect(getActionContext()?.cookies.get('sid')).toEqual({ name: 'sid', value: 'abc' });
31
38
  expect(getActionContext()?.actionId).toBe('a1');
32
39
  });
40
+ it('marks a render uncacheable when headers or cookies are read', async () => {
41
+ const ctx = {
42
+ url: '/p',
43
+ method: 'GET',
44
+ headers: new Headers({ 'x-test': 'yes' }),
45
+ cookies: new Map([['sid', 'abc']]),
46
+ params: {},
47
+ searchParams: {},
48
+ };
49
+ globalThis[REQUEST_KEY] = { getStore: () => ctx };
50
+ installRenderStore(new AsyncLocalStorage());
51
+ const { scope } = await withCacheScope('/p', () => {
52
+ headers();
53
+ cookies();
54
+ return 'ok';
55
+ });
56
+ expect(scope.noStore).toBe(true);
57
+ });
33
58
  it('redirect() throws the marker the sidecar turns into a navigation', () => {
34
59
  let caught;
35
60
  try {
package/dist/actions.d.ts CHANGED
@@ -88,7 +88,7 @@ export declare function getFormStatus(form: HTMLFormElement): FormStatus;
88
88
  export declare function requestFormReset(form: HTMLFormElement): void;
89
89
  type Getter = () => unknown;
90
90
  /** Binds a function action to a form or submit button (`action={fn}` / `formAction={fn}`). */
91
- export declare function __krateBindFormAction(el: Element, get: Getter): void;
91
+ export declare function __krateBindFormAction(el: Element | null, get: Getter): void;
92
92
  interface RunnableAction {
93
93
  (payload: unknown): unknown;
94
94
  __krateRun?: (payload: unknown) => Promise<boolean>;
@@ -101,6 +101,17 @@ interface RunnableAction {
101
101
  export declare function submitFormAction(form: HTMLFormElement, action: unknown, data: FormData, submitter?: HTMLElement | null, url?: string): Promise<boolean>;
102
102
  /** Installs the document submit listener once per window. */
103
103
  export declare function installActionForms(doc?: Document | undefined): void;
104
+ /**
105
+ * Reads and clears the flash state a native form post left for action `id`:
106
+ * the `krate_flash` cookie the action endpoint sets, or, when the server
107
+ * already rendered it into the page (a no-JS style notice carrying the same
108
+ * payload in `data-krate-flash`), that element, which is removed because the
109
+ * form state now shows it.
110
+ */
111
+ export declare function takeFlash(id: string): {
112
+ found: boolean;
113
+ value?: unknown;
114
+ };
104
115
  /**
105
116
  * Backs `const [state, formAction, isPending] = useActionState(fn, initial)`.
106
117
  * The returned dispatch can be a form action, a button formAction, or called
package/dist/actions.js CHANGED
@@ -42,12 +42,26 @@ function basePath() {
42
42
  export function isServerAction(value) {
43
43
  return typeof value === 'function' && typeof value.$$krateAction === 'string';
44
44
  }
45
+ // Counts redirects the client followed, so useActionState can tell that an
46
+ // action navigated away instead of producing a next state.
47
+ let redirectsFollowed = 0;
45
48
  function navigateTo(url) {
49
+ const safe = safeRedirect(url);
50
+ if (!safe)
51
+ return;
46
52
  const nav = globalThis.navigate;
47
53
  if (typeof nav === 'function')
48
- nav(url);
54
+ nav(safe);
49
55
  else if (typeof location !== 'undefined')
50
- location.assign(url);
56
+ location.assign(safe);
57
+ }
58
+ /** Only same-origin absolute paths are followed after an action. */
59
+ function safeRedirect(url) {
60
+ if (!url || !url.startsWith('/') || url.startsWith('//'))
61
+ return '';
62
+ if (url.includes('\\') || /[\u0000-\u001f\u007f]/.test(url))
63
+ return '';
64
+ return url;
51
65
  }
52
66
  /**
53
67
  * Tells the page that the action revalidated server caches. The router
@@ -114,8 +128,10 @@ export async function callServerAction(url, args) {
114
128
  }
115
129
  if (payload.revalidated)
116
130
  dispatchRevalidate(payload.revalidation);
117
- if (typeof payload.redirect === 'string' && payload.redirect)
131
+ if (typeof payload.redirect === 'string' && payload.redirect) {
132
+ redirectsFollowed++;
118
133
  navigateTo(payload.redirect);
134
+ }
119
135
  return payload.result;
120
136
  }
121
137
  function makeProxy(id, bound) {
@@ -315,6 +331,10 @@ export function requestFormReset(form) {
315
331
  }
316
332
  /** Binds a function action to a form or submit button (`action={fn}` / `formAction={fn}`). */
317
333
  export function __krateBindFormAction(el, get) {
334
+ // The ref callback is called with null when the element detaches (a soft
335
+ // navigation replacing the page), which has nothing left to bind.
336
+ if (!el)
337
+ return;
318
338
  el.__krateFormAction = get;
319
339
  // The native POST target only serves the no-JS fallback; once the function
320
340
  // is bound the element matches React's client DOM (no action attribute).
@@ -456,6 +476,56 @@ export function installActionForms(doc = typeof document !== 'undefined' ? docum
456
476
  w.__krateActionBound = true;
457
477
  doc.addEventListener('submit', onSubmit, false);
458
478
  }
479
+ // Flash state from native form posts
480
+ function decodeFlash(value) {
481
+ try {
482
+ // The server signs the cookie as "<payload>.<signature>"; only the payload decodes.
483
+ const raw = value.split('.')[0].replace(/-/g, '+').replace(/_/g, '/');
484
+ const bin = atob(raw + '='.repeat((4 - (raw.length % 4)) % 4));
485
+ return JSON.parse(decodeURIComponent(escape(bin)));
486
+ }
487
+ catch {
488
+ return null;
489
+ }
490
+ }
491
+ /**
492
+ * Reads and clears the flash state a native form post left for action `id`:
493
+ * the `krate_flash` cookie the action endpoint sets, or, when the server
494
+ * already rendered it into the page (a no-JS style notice carrying the same
495
+ * payload in `data-krate-flash`), that element, which is removed because the
496
+ * form state now shows it.
497
+ */
498
+ export function takeFlash(id) {
499
+ if (typeof document === 'undefined')
500
+ return { found: false };
501
+ const m = /(?:^|;\s*)krate_flash=([^;]*)/.exec(document.cookie || '');
502
+ if (m) {
503
+ const payload = decodeFlash(m[1]);
504
+ if (payload && payload.a === id) {
505
+ document.cookie = 'krate_flash=; Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax';
506
+ removeFlashNotices(id);
507
+ return { found: true, value: payload.r };
508
+ }
509
+ return { found: false };
510
+ }
511
+ const notices = document.querySelectorAll('[data-krate-flash]');
512
+ for (let i = 0; i < notices.length; i++) {
513
+ const payload = decodeFlash(notices[i].getAttribute('data-krate-flash') || '');
514
+ if (payload && payload.a === id) {
515
+ removeFlashNotices(id);
516
+ return { found: true, value: payload.r };
517
+ }
518
+ }
519
+ return { found: false };
520
+ }
521
+ function removeFlashNotices(id) {
522
+ const notices = document.querySelectorAll('[data-krate-flash]');
523
+ for (let i = 0; i < notices.length; i++) {
524
+ const payload = decodeFlash(notices[i].getAttribute('data-krate-flash') || '');
525
+ if (payload && payload.a === id)
526
+ notices[i].parentNode?.removeChild(notices[i]);
527
+ }
528
+ }
459
529
  /**
460
530
  * Backs `const [state, formAction, isPending] = useActionState(fn, initial)`.
461
531
  * The returned dispatch can be a form action, a button formAction, or called
@@ -466,14 +536,24 @@ export function installActionForms(doc = typeof document !== 'undefined' ? docum
466
536
  export function __krateActionState(action, getState, setState, setPending) {
467
537
  const queue = [];
468
538
  let running = false;
539
+ // A native (no-JS or not-yet-hydrated) form post redirected back to this page
540
+ // with the action's returned state in a short-lived cookie: start from it.
541
+ if (isServerAction(action)) {
542
+ const flashed = takeFlash(action.$$krateAction);
543
+ if (flashed.found)
544
+ setState(flashed.value);
545
+ }
469
546
  const drain = async () => {
470
547
  running = true;
471
548
  while (queue.length > 0) {
472
549
  const item = queue.shift();
473
550
  let ok = false;
474
551
  try {
552
+ const before = redirectsFollowed;
475
553
  const next = await runActionTransition(() => action(getState(), item.payload));
476
- krateTransitionWrites(() => setState(next));
554
+ // A redirecting action has no next state: the page is being replaced.
555
+ if (redirectsFollowed === before)
556
+ krateTransitionWrites(() => setState(next));
477
557
  ok = true;
478
558
  }
479
559
  catch (err) {
@@ -1,7 +1,7 @@
1
1
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
2
  import { createSignal } from './signal.js';
3
3
  import { krateOn } from './events.js';
4
- import { ACTION_ARGS_FIELD, ServerActionError, __krateAction, __krateActionState, __krateBeginAction, __krateBindFormAction, __krateFormStatusMount, __krateOptimistic, getFormStatus, installActionForms, isServerAction, requestFormReset, setActionTransitionRunner, } from './actions.js';
4
+ import { ACTION_ARGS_FIELD, ServerActionError, __krateAction, __krateActionState, __krateBeginAction, __krateBindFormAction, __krateFormStatusMount, __krateOptimistic, getFormStatus, installActionForms, isServerAction, requestFormReset, setActionTransitionRunner, takeFlash, } from './actions.js';
5
5
  function deferred() {
6
6
  let resolve;
7
7
  let reject;
@@ -290,6 +290,31 @@ describe('useActionState', () => {
290
290
  expect(state()).toBe(5);
291
291
  });
292
292
  });
293
+ describe('useActionState flash from a native form post', () => {
294
+ const flash = (id, result) => btoa(JSON.stringify({ a: id, r: result })).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
295
+ afterEach(() => {
296
+ document.cookie = 'krate_flash=; Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT';
297
+ });
298
+ it('starts from the state the server returned to the redirected native post', () => {
299
+ document.cookie = 'krate_flash=' + flash('save', { errors: { name: 'required' } }) + '; Path=/';
300
+ const [state, setState] = createSignal({ errors: {} });
301
+ const [, setPending] = createSignal(false);
302
+ __krateActionState(__krateAction('save'), state, setState, setPending);
303
+ expect(state()).toEqual({ errors: { name: 'required' } });
304
+ // The flash is single use.
305
+ expect(document.cookie).not.toContain('krate_flash=' + flash('save', { errors: { name: 'required' } }));
306
+ const [again, setAgain] = createSignal('init');
307
+ __krateActionState(__krateAction('save'), again, setAgain, setPending);
308
+ expect(again()).toBe('init');
309
+ });
310
+ it('ignores a flash written for another action', () => {
311
+ document.cookie = 'krate_flash=' + flash('other', 'x') + '; Path=/';
312
+ const [state, setState] = createSignal('init');
313
+ const [, setPending] = createSignal(false);
314
+ __krateActionState(__krateAction('save'), state, setState, setPending);
315
+ expect(state()).toBe('init');
316
+ });
317
+ });
293
318
  describe('useOptimistic', () => {
294
319
  it('applies updates while an action is pending and reverts to the latest base', async () => {
295
320
  const [base, setBase] = createSignal(['a']);
@@ -388,6 +413,20 @@ describe('server action proxies', () => {
388
413
  await __krateAction('a4')();
389
414
  expect(nav).toHaveBeenCalledWith('/next');
390
415
  });
416
+ it('keeps the previous useActionState state when the action redirects', async () => {
417
+ vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ ok: true, result: null, redirect: '/next' })));
418
+ vi.stubGlobal('navigate', vi.fn());
419
+ const proxy = __krateAction('a4b');
420
+ let state = { error: '' };
421
+ const dispatch = __krateActionState((prev, payload) => proxy(prev, payload), () => state, (next) => {
422
+ state = next;
423
+ }, () => { });
424
+ await dispatch.__krateRun(new FormData());
425
+ expect(state).toEqual({ error: '' });
426
+ });
427
+ it('ignores a null element when a form binding is detached', () => {
428
+ expect(() => __krateBindFormAction(null, () => () => { })).not.toThrow();
429
+ });
391
430
  it('dispatches krate:revalidate when the action revalidated server caches', async () => {
392
431
  const revalidation = { paths: [{ path: '/posts', type: 'page' }], tags: ['posts'] };
393
432
  vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ ok: true, result: 1, revalidated: true, revalidation })));
@@ -415,3 +454,24 @@ describe('server action proxies', () => {
415
454
  }
416
455
  });
417
456
  });
457
+ describe('takeFlash', () => {
458
+ const encode = (payload) => btoa(unescape(encodeURIComponent(JSON.stringify(payload)))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
459
+ afterEach(() => {
460
+ document.body.innerHTML = '';
461
+ document.cookie = 'krate_flash=; Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT';
462
+ });
463
+ it('reads the cookie for the matching action only', () => {
464
+ document.cookie = 'krate_flash=' + encode({ a: 'act1', r: { error: 'bad' } }) + '; Path=/';
465
+ expect(takeFlash('other')).toEqual({ found: false });
466
+ expect(takeFlash('act1')).toEqual({ found: true, value: { error: 'bad' } });
467
+ expect(takeFlash('act1')).toEqual({ found: false });
468
+ });
469
+ it('falls back to the notice the server rendered and removes it', () => {
470
+ document.body.innerHTML =
471
+ '<form><div data-krate-flash="' + encode({ a: 'act2', r: { error: 'server rendered' } }) + '" data-krate-action="act2">server rendered</div></form>';
472
+ expect(takeFlash('act1')).toEqual({ found: false });
473
+ expect(document.querySelector('[data-krate-flash]')).not.toBeNull();
474
+ expect(takeFlash('act2')).toEqual({ found: true, value: { error: 'server rendered' } });
475
+ expect(document.querySelector('[data-krate-flash]')).toBeNull();
476
+ });
477
+ });
@@ -0,0 +1,5 @@
1
+ import type { StaticLayer } from "./server-handler.js";
2
+ export interface AssetFetcher {
3
+ fetch(request: Request): Promise<Response>;
4
+ }
5
+ export declare function createAssetsStaticLayer(assets: AssetFetcher): StaticLayer;
@@ -0,0 +1,31 @@
1
+ // A StaticLayer backed by a platform asset fetcher (Cloudflare's env.ASSETS).
2
+ // Used when the Worker runs first and falls through to the uploaded assets.
3
+ import { extName } from "./handler-routing.js";
4
+ export function createAssetsStaticLayer(assets) {
5
+ const probe = async (url, path) => {
6
+ const u = new URL(url);
7
+ u.pathname = path;
8
+ u.search = "";
9
+ const res = await assets.fetch(new Request(u.toString(), { method: "HEAD", redirect: "manual" }));
10
+ return res.status !== 404;
11
+ };
12
+ let origin = "https://assets.invalid";
13
+ return {
14
+ async exists(urlPath) {
15
+ const rel = urlPath.replace(/^\/+|\/+$/g, "");
16
+ return (await probe(origin + "/", rel === "" ? "/index.html" : "/" + rel)) || (rel !== "" && (await probe(origin + "/", "/" + rel + "/index.html")));
17
+ },
18
+ async isAsset(urlPath) {
19
+ const ext = extName(urlPath).toLowerCase();
20
+ if (ext === "" || ext === ".html")
21
+ return false;
22
+ return probe(origin + "/", urlPath);
23
+ },
24
+ async serve(request, urlPath) {
25
+ origin = new URL(request.url).origin;
26
+ void urlPath;
27
+ const res = await assets.fetch(request);
28
+ return res.status === 404 ? null : res;
29
+ },
30
+ };
31
+ }
@@ -38,6 +38,11 @@ export interface Owner {
38
38
  readonly setup: (() => void) | null;
39
39
  /** Free-form per-owner storage (class instances live here). */
40
40
  readonly data: Record<string, unknown>;
41
+ /**
42
+ * Route scope (layout/template id) whose hydration created the owner, null for
43
+ * page code. A soft navigation that keeps a layout keeps its owners.
44
+ */
45
+ readonly scope: string | null;
41
46
  }
42
47
  /** The owner whose code is running, or null. */
43
48
  export declare function getOwner(): Owner | null;
@@ -71,6 +76,13 @@ export declare function handleError(thrown: unknown, source?: Owner | null): voi
71
76
  * be mounted again by running their setup.
72
77
  */
73
78
  export declare function unmountOwner(owner: Owner): void;
79
+ /**
80
+ * Reports whether an error boundary created under route scope `scope` is
81
+ * showing its fallback. The SPA router asks before it keeps such a boundary
82
+ * across a soft navigation: a failed boundary is not kept, so navigating clears
83
+ * the error.
84
+ */
85
+ export declare function krateScopeFailed(scope: string): boolean;
74
86
  /** Mounts a dormant owner (and its mountable descendants). */
75
87
  export declare function mountOwner(owner: Owner): void;
76
88
  /** Unmounts every child of owner (an error boundary dropping its subtree). */
package/dist/boundary.js CHANGED
@@ -14,14 +14,13 @@
14
14
  // unmounted (its cleanups run) when it is swapped out, so componentDidMount /
15
15
  // componentWillUnmount and state resets match React. A dormant owner keeps its
16
16
  // setup function and is remounted by running it again.
17
- import { setOwnerHooks, untrack, onCleanup, krateGetOwner, krateSetOwner } from './signal.js';
17
+ import { setOwnerHooks, untrack, krateGetOwner, krateSetOwner, krateCurrentScope, krateOnDispose, krateScopeOfId } from './signal.js';
18
18
  import { krateForgetOwner, krateOnHookError } from './effects.js';
19
19
  let current = null;
20
20
  let nextOrder = 0;
21
21
  const byId = new Map();
22
22
  const condState = new Map();
23
23
  const condOwners = new Map();
24
- let resetRegistered = false;
25
24
  let mountDepth = 0;
26
25
  const deferredMounts = [];
27
26
  function makeOwner(id, name, parent, creator, cond, branch, setup) {
@@ -40,6 +39,7 @@ function makeOwner(id, name, parent, creator, cond, branch, setup) {
40
39
  branch,
41
40
  setup,
42
41
  data: {},
42
+ scope: krateCurrentScope(),
43
43
  cleanups: [],
44
44
  };
45
45
  if (parent)
@@ -57,8 +57,6 @@ export function getOwner() {
57
57
  export function createOwner(name, parent = current) {
58
58
  const o = makeOwner('', name, parent || null, parent || null, '', '', null);
59
59
  o.state = parent && parent.state !== 'mounted' ? 'dormant' : 'mounted';
60
- if (!parent)
61
- registerReset();
62
60
  return o;
63
61
  }
64
62
  /**
@@ -178,6 +176,19 @@ function reportUncaughtLoose(err) {
178
176
  export function unmountOwner(owner) {
179
177
  disposeTree(owner, 'dormant');
180
178
  }
179
+ /**
180
+ * Reports whether an error boundary created under route scope `scope` is
181
+ * showing its fallback. The SPA router asks before it keeps such a boundary
182
+ * across a soft navigation: a failed boundary is not kept, so navigating clears
183
+ * the error.
184
+ */
185
+ export function krateScopeFailed(scope) {
186
+ for (const o of byId.values()) {
187
+ if (o.scope === scope && o.inError)
188
+ return true;
189
+ }
190
+ return false;
191
+ }
181
192
  /** Mounts a dormant owner (and its mountable descendants). */
182
193
  export function mountOwner(owner) {
183
194
  const o = owner;
@@ -284,13 +295,15 @@ function mount(o) {
284
295
  }
285
296
  }
286
297
  }
287
- function registerReset() {
288
- if (resetRegistered)
289
- return;
290
- resetRegistered = true;
291
- // Top-level registration: runs on disposeAll() (SPA navigation).
292
- onCleanup(resetOwners);
293
- }
298
+ // Page teardown (SPA navigation). A full teardown drops every owner; a partial
299
+ // one, which keeps some layouts mounted, drops only the owners whose route scope
300
+ // is gone and leaves the kept layouts' owners (and their lifecycles) alone.
301
+ krateOnDispose((gone) => {
302
+ if (gone === null)
303
+ resetOwners();
304
+ else
305
+ disposeScopedOwners(gone);
306
+ });
294
307
  function resetOwners() {
295
308
  const roots = [];
296
309
  for (const o of byId.values())
@@ -302,7 +315,35 @@ function resetOwners() {
302
315
  condState.clear();
303
316
  condOwners.clear();
304
317
  deferredMounts.length = 0;
305
- resetRegistered = false;
318
+ }
319
+ function disposeScopedOwners(gone) {
320
+ const dead = [];
321
+ for (const o of byId.values())
322
+ if (gone(o.scope))
323
+ dead.push(o);
324
+ for (const o of dead) {
325
+ if (o.state !== 'disposed')
326
+ disposeTree(o, 'disposed');
327
+ }
328
+ for (const o of dead) {
329
+ byId.delete(o.id);
330
+ const p = o.parent;
331
+ if (p && !gone(p.scope)) {
332
+ const i = p.children.indexOf(o);
333
+ if (i >= 0)
334
+ p.children.splice(i, 1);
335
+ }
336
+ }
337
+ for (const id of Array.from(condState.keys())) {
338
+ if (gone(krateScopeOfId(id))) {
339
+ condState.delete(id);
340
+ condOwners.delete(id);
341
+ }
342
+ }
343
+ for (let i = deferredMounts.length - 1; i >= 0; i--) {
344
+ if (deferredMounts[i].state === 'disposed')
345
+ deferredMounts.splice(i, 1);
346
+ }
306
347
  }
307
348
  /**
308
349
  * Hydration entry point: the compiler wraps each component's hydration scope
@@ -318,7 +359,6 @@ export function __krateOwn(id, meta, setup) {
318
359
  const creator = (m.k && byId.get(m.k)) || null;
319
360
  const o = makeOwner(id, m.n || id, parent, creator, m.c || '', m.b || '', setup);
320
361
  byId.set(id, o);
321
- registerReset();
322
362
  if (o.cond) {
323
363
  let list = condOwners.get(o.cond);
324
364
  if (!list) {
@@ -0,0 +1,113 @@
1
+ import { type SharedDataStore } from './cache-scope.js';
2
+ export interface CacheSetOptions {
3
+ /** Seconds to keep the entry; omitted or Infinity keeps it until it is deleted. */
4
+ ttlSeconds?: number;
5
+ /** Tags the entry can be deleted by (deleteByTags). */
6
+ tags?: string[];
7
+ }
8
+ /** The storage contract of a shared cache. Every method may reject; callers cope. */
9
+ export interface CacheAdapter {
10
+ readonly name: string;
11
+ /** The value stored under key, or null. */
12
+ get(key: string): Promise<string | null>;
13
+ set(key: string, value: string, options?: CacheSetOptions): Promise<void>;
14
+ delete(key: string): Promise<void>;
15
+ /** The keys stored with tag. */
16
+ keysByTag(tag: string): Promise<string[]>;
17
+ /** Deletes every key stored with one of tags; resolves with how many went. */
18
+ deleteByTags(tags: string[]): Promise<number>;
19
+ /** Sends message to every subscriber of channel, including this process. */
20
+ publish(channel: string, message: string): Promise<void>;
21
+ /**
22
+ * Calls handler for each message published on channel. After a lost
23
+ * connection that may have dropped messages, handler is called with "*":
24
+ * treat it as "everything may be stale". Resolves with an unsubscribe function.
25
+ */
26
+ subscribe(channel: string, handler: (message: string) => void): Promise<() => void>;
27
+ /** Releases connections. */
28
+ close(): Promise<void>;
29
+ }
30
+ /** What the config and KRATE_CACHE carry. */
31
+ export interface CacheSpec {
32
+ /** "memory" (default), "redis", or a module specifier / path exporting an adapter factory. */
33
+ adapter?: string;
34
+ url?: string;
35
+ /** Key prefix, so several apps can share one store (default "krate:"). */
36
+ prefix?: string;
37
+ /** Milliseconds one cache call may take before it counts as a failure (default 250). */
38
+ timeoutMs?: number;
39
+ /** Milliseconds to keep ISR entries in the shared store (default 7 days). */
40
+ ttlSeconds?: number;
41
+ /** Adapter-specific options passed to a custom factory. */
42
+ options?: Record<string, unknown>;
43
+ }
44
+ export declare const INVALIDATE_CHANNEL = "invalidate";
45
+ /** The adapter tag a cache tag is stored under (kept apart from route index tags). */
46
+ export declare function tagName(tag: string): string;
47
+ export type GuardResult<T> = {
48
+ ok: true;
49
+ value: T;
50
+ } | {
51
+ ok: false;
52
+ };
53
+ /**
54
+ * Runs adapter calls with a timeout and a circuit breaker. After a few
55
+ * consecutive failures calls are skipped (reported as failed) for a cool-down,
56
+ * so a dead cache costs a microsecond per request, not a timeout.
57
+ */
58
+ export declare class CacheGuard {
59
+ readonly adapter: CacheAdapter;
60
+ private readonly timeoutMs;
61
+ private readonly threshold;
62
+ private readonly coolDownMs;
63
+ private failures;
64
+ private openUntil;
65
+ private lastLog;
66
+ constructor(adapter: CacheAdapter, timeoutMs?: number, threshold?: number, coolDownMs?: number);
67
+ get healthy(): boolean;
68
+ call<T>(fn: (a: CacheAdapter) => Promise<T>): Promise<GuardResult<T>>;
69
+ }
70
+ export declare class SharedDataCache implements SharedDataStore {
71
+ private readonly guard;
72
+ constructor(guard: CacheGuard);
73
+ get(key: string): Promise<GuardResult<string | undefined>>;
74
+ set(key: string, json: string, ttlSeconds: number, tags: string[]): Promise<boolean>;
75
+ deleteTags(tags: string[]): Promise<number>;
76
+ }
77
+ /** A CacheAdapter over a Map. Two processes cannot share it; it exists for tests and as the reference. */
78
+ export declare class MemoryAdapter implements CacheAdapter {
79
+ readonly name = "memory";
80
+ private values;
81
+ private byTag;
82
+ private subs;
83
+ get(key: string): Promise<string | null>;
84
+ set(key: string, value: string, options?: CacheSetOptions): Promise<void>;
85
+ delete(key: string): Promise<void>;
86
+ keysByTag(tag: string): Promise<string[]>;
87
+ deleteByTags(tags: string[]): Promise<number>;
88
+ publish(channel: string, message: string): Promise<void>;
89
+ subscribe(channel: string, handler: (message: string) => void): Promise<() => void>;
90
+ close(): Promise<void>;
91
+ }
92
+ /** Resolves a spec to an adapter, or null for the default in-process caches. */
93
+ export declare function loadCacheAdapter(spec: CacheSpec | undefined): Promise<CacheAdapter | null>;
94
+ /** Reads the cache spec the Go host passes in KRATE_CACHE. */
95
+ export declare function cacheSpecFromEnv(env: Record<string, string | undefined>): CacheSpec | undefined;
96
+ export interface InstalledCache {
97
+ adapter: CacheAdapter;
98
+ guard: CacheGuard;
99
+ data: SharedDataCache;
100
+ }
101
+ /**
102
+ * Wires an adapter into the process: the data cache reads and writes through it
103
+ * (cacheRuntime().shared), and the returned stores replace the in-process ISR
104
+ * cache. Pass the returned `isr` as the renderer's isrStore.
105
+ */
106
+ export declare function installCacheAdapter(adapter: CacheAdapter, spec?: CacheSpec): InstalledCache;
107
+ /**
108
+ * The cache spec a handler bundle carries (data.config.cache): the adapter and
109
+ * its tuning, with the URL left to the environment so no secret is bundled.
110
+ */
111
+ export declare function cacheSpecFromConfig(cfg: (CacheSpec & {
112
+ urlEnv?: string;
113
+ }) | undefined): CacheSpec | undefined;