@krate/runtime 0.5.0-alpha.3 → 0.5.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/action-context.d.ts +14 -3
- package/dist/action-context.js +70 -4
- package/dist/action-context.test.js +26 -1
- package/dist/actions.d.ts +12 -1
- package/dist/actions.js +101 -5
- package/dist/actions.test.js +87 -1
- package/dist/cache-scope.d.ts +118 -0
- package/dist/cache-scope.js +314 -0
- package/dist/cache.d.ts +55 -0
- package/dist/cache.js +155 -0
- package/dist/cache.test.d.ts +1 -0
- package/dist/cache.test.js +233 -0
- package/dist/class-helpers.d.ts +4 -4
- package/dist/class-helpers.js +357 -32
- package/dist/class-helpers.test.d.ts +1 -0
- package/dist/class-helpers.test.js +169 -0
- package/dist/context.d.ts +16 -2
- package/dist/context.js +44 -3
- package/dist/dev-overlay.js +75 -2
- package/dist/dev-overlay.test.js +22 -0
- package/dist/dom.d.ts +7 -0
- package/dist/dom.js +69 -3
- package/dist/effects.js +74 -3
- package/dist/error-overlay.js +4 -4
- package/dist/hook-args.d.ts +7 -0
- package/dist/hook-args.js +10 -0
- package/dist/htmlspec-attributes.d.ts +1 -0
- package/dist/htmlspec-attributes.js +159 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -1
- package/dist/krate-core.js +2 -0
- package/dist/krate-dev.js +65 -2
- package/dist/krate-f-actions.js +2 -0
- package/dist/krate-f-classes.js +8 -0
- package/dist/krate-f-helpers.js +2 -0
- package/dist/krate-f-list.js +2 -0
- package/dist/krate-f-router-lite.js +2 -0
- package/dist/krate-f-router.js +2 -0
- package/dist/krate-features.json +239 -0
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-runtime.js +5 -5
- package/dist/patterns.test.d.ts +1 -0
- package/dist/patterns.test.js +98 -0
- package/dist/portal.d.ts +5 -1
- package/dist/portal.js +15 -4
- package/dist/reactivity-core.test.d.ts +1 -0
- package/dist/reactivity-core.test.js +152 -0
- package/dist/reconcile.js +4 -2
- package/dist/request-context.d.ts +62 -0
- package/dist/request-context.js +107 -0
- package/dist/router-layout.test.d.ts +1 -0
- package/dist/router-layout.test.js +179 -0
- package/dist/router-lite.d.ts +25 -0
- package/dist/router-lite.js +73 -0
- package/dist/router-nav.test.d.ts +1 -0
- package/dist/router-nav.test.js +437 -0
- package/dist/router-slots.test.d.ts +1 -0
- package/dist/router-slots.test.js +144 -0
- package/dist/router-speculation.test.d.ts +1 -0
- package/dist/router-speculation.test.js +25 -0
- package/dist/router-styles.test.d.ts +1 -0
- package/dist/router-styles.test.js +98 -0
- package/dist/router.d.ts +66 -2
- package/dist/router.js +1617 -648
- package/dist/server-async.test.d.ts +1 -0
- package/dist/server-async.test.js +194 -0
- package/dist/server-renderer.js +556 -132
- package/dist/server.d.ts +24 -0
- package/dist/server.js +247 -11
- package/dist/server.test.js +20 -0
- package/dist/signal.d.ts +41 -4
- package/dist/signal.js +254 -24
- package/dist/slots.d.ts +5 -1
- package/dist/slots.js +40 -3
- package/package.json +6 -2
package/dist/action-context.d.ts
CHANGED
|
@@ -17,7 +17,11 @@ export interface ActionCookieOptions {
|
|
|
17
17
|
}
|
|
18
18
|
/** Cookie access for the current action request. */
|
|
19
19
|
export interface ActionCookies {
|
|
20
|
-
|
|
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;
|
|
@@ -37,9 +41,16 @@ export interface ActionContext {
|
|
|
37
41
|
}
|
|
38
42
|
/** The current action context, or undefined outside a server action. */
|
|
39
43
|
export declare function getActionContext(): ActionContext | undefined;
|
|
40
|
-
/**
|
|
44
|
+
/**
|
|
45
|
+
* Request headers of the current server action call or server component
|
|
46
|
+
* render. The result can also be awaited (`await headers()`), as in Next.js 15.
|
|
47
|
+
*/
|
|
41
48
|
export declare function headers(): Headers;
|
|
42
|
-
/**
|
|
49
|
+
/**
|
|
50
|
+
* Cookies of the current server action call, or a read-only view of the
|
|
51
|
+
* request cookies while a server component renders (`get(name)` returns
|
|
52
|
+
* `{ name, value }` there, like Next.js). Can also be awaited.
|
|
53
|
+
*/
|
|
43
54
|
export declare function cookies(): ActionCookies;
|
|
44
55
|
/**
|
|
45
56
|
* Ends the server action and navigates the client to `url` (a JSON
|
package/dist/action-context.js
CHANGED
|
@@ -5,26 +5,92 @@
|
|
|
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';
|
|
9
|
+
import { getRequestContext, requestCookies, thenable } from './request-context.js';
|
|
8
10
|
/** The current action context, or undefined outside a server action. */
|
|
9
11
|
export function getActionContext() {
|
|
10
12
|
const store = globalThis[Symbol.for('krate.action.store')];
|
|
11
|
-
|
|
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;
|
|
12
39
|
}
|
|
13
40
|
function requireContext(api) {
|
|
14
41
|
const ctx = getActionContext();
|
|
15
42
|
if (!ctx) {
|
|
16
|
-
throw new Error(`${api}() can only be called while a server action runs (inside a "use server" export)`
|
|
43
|
+
throw new Error(`${api}() can only be called while a server action runs (inside a "use server" export) ` +
|
|
44
|
+
`or while a server component (an async component) renders in the SSR sidecar`);
|
|
17
45
|
}
|
|
18
46
|
return ctx;
|
|
19
47
|
}
|
|
20
|
-
/**
|
|
48
|
+
/**
|
|
49
|
+
* Request headers of the current server action call or server component
|
|
50
|
+
* render. The result can also be awaited (`await headers()`), as in Next.js 15.
|
|
51
|
+
*/
|
|
21
52
|
export function headers() {
|
|
53
|
+
const action = getActionContext();
|
|
54
|
+
if (action)
|
|
55
|
+
return awaitableHeaders(action.headers);
|
|
56
|
+
const req = getRequestContext();
|
|
57
|
+
if (req) {
|
|
58
|
+
markNoStore();
|
|
59
|
+
return awaitableHeaders(req.headers);
|
|
60
|
+
}
|
|
22
61
|
return requireContext('headers').headers;
|
|
23
62
|
}
|
|
24
|
-
/**
|
|
63
|
+
/**
|
|
64
|
+
* Cookies of the current server action call, or a read-only view of the
|
|
65
|
+
* request cookies while a server component renders (`get(name)` returns
|
|
66
|
+
* `{ name, value }` there, like Next.js). Can also be awaited.
|
|
67
|
+
*/
|
|
25
68
|
export function cookies() {
|
|
69
|
+
const action = getActionContext();
|
|
70
|
+
if (action)
|
|
71
|
+
return awaitableActionCookies(action.cookies);
|
|
72
|
+
const req = getRequestContext();
|
|
73
|
+
if (req) {
|
|
74
|
+
markNoStore();
|
|
75
|
+
return requestCookies(req.cookies);
|
|
76
|
+
}
|
|
26
77
|
return requireContext('cookies').cookies;
|
|
27
78
|
}
|
|
79
|
+
function awaitableActionCookies(c) {
|
|
80
|
+
const view = () => ({
|
|
81
|
+
get: (name) => c.get(name),
|
|
82
|
+
getAll: () => c.getAll(),
|
|
83
|
+
has: (name) => c.has(name),
|
|
84
|
+
set: (name, value, options) => c.set(name, value, options),
|
|
85
|
+
delete: (name, options) => c.delete(name, options),
|
|
86
|
+
});
|
|
87
|
+
return thenable(view(), view);
|
|
88
|
+
}
|
|
89
|
+
function awaitableHeaders(h) {
|
|
90
|
+
const plain = new Headers(h);
|
|
91
|
+
const view = new Headers(h);
|
|
92
|
+
return thenable(view, () => plain);
|
|
93
|
+
}
|
|
28
94
|
/**
|
|
29
95
|
* Ends the server action and navigates the client to `url` (a JSON
|
|
30
96
|
* `redirect` for enhanced forms, a 303 for native form posts). Returning
|
|
@@ -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')).
|
|
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
|
@@ -17,7 +17,8 @@
|
|
|
17
17
|
* request JSON {"args":[...]} every argument JSON
|
|
18
18
|
* multipart form fields + "__krate_args" last argument a FormData;
|
|
19
19
|
* (JSON array of leading args)
|
|
20
|
-
* response {"ok":true,"result":R,"redirect":"/path"
|
|
20
|
+
* response {"ok":true,"result":R,"redirect":"/path"?,
|
|
21
|
+
* "revalidated":true?,"revalidation":{"paths":[...],"tags":[...]}?}
|
|
21
22
|
* {"ok":false,"error":{"message":M,"digest":D}}
|
|
22
23
|
*/
|
|
23
24
|
import { createEffect, onCleanup, krateRunEvent, krateTransitionWrites } from './signal.js';
|
|
@@ -41,12 +42,40 @@ function basePath() {
|
|
|
41
42
|
export function isServerAction(value) {
|
|
42
43
|
return typeof value === 'function' && typeof value.$$krateAction === 'string';
|
|
43
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;
|
|
44
48
|
function navigateTo(url) {
|
|
49
|
+
const safe = safeRedirect(url);
|
|
50
|
+
if (!safe)
|
|
51
|
+
return;
|
|
45
52
|
const nav = globalThis.navigate;
|
|
46
53
|
if (typeof nav === 'function')
|
|
47
|
-
nav(
|
|
54
|
+
nav(safe);
|
|
48
55
|
else if (typeof location !== 'undefined')
|
|
49
|
-
location.assign(
|
|
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;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Tells the page that the action revalidated server caches. The router
|
|
68
|
+
* listens for `krate:revalidate` and refreshes the current route; detail is
|
|
69
|
+
* `{ paths: [{ path, type }], tags: [...] }`.
|
|
70
|
+
*/
|
|
71
|
+
function dispatchRevalidate(info) {
|
|
72
|
+
if (typeof window === 'undefined' || typeof CustomEvent === 'undefined')
|
|
73
|
+
return;
|
|
74
|
+
const detail = {
|
|
75
|
+
paths: info && Array.isArray(info.paths) ? info.paths : [],
|
|
76
|
+
tags: info && Array.isArray(info.tags) ? info.tags : [],
|
|
77
|
+
};
|
|
78
|
+
window.dispatchEvent(new CustomEvent('krate:revalidate', { detail }));
|
|
50
79
|
}
|
|
51
80
|
function errorFrom(p, status, statusText) {
|
|
52
81
|
const e = p ? p.error : undefined;
|
|
@@ -97,8 +126,12 @@ export async function callServerAction(url, args) {
|
|
|
97
126
|
if (!res.ok || !payload || payload.ok === false) {
|
|
98
127
|
throw errorFrom(payload, res.status, res.statusText);
|
|
99
128
|
}
|
|
100
|
-
if (
|
|
129
|
+
if (payload.revalidated)
|
|
130
|
+
dispatchRevalidate(payload.revalidation);
|
|
131
|
+
if (typeof payload.redirect === 'string' && payload.redirect) {
|
|
132
|
+
redirectsFollowed++;
|
|
101
133
|
navigateTo(payload.redirect);
|
|
134
|
+
}
|
|
102
135
|
return payload.result;
|
|
103
136
|
}
|
|
104
137
|
function makeProxy(id, bound) {
|
|
@@ -298,6 +331,10 @@ export function requestFormReset(form) {
|
|
|
298
331
|
}
|
|
299
332
|
/** Binds a function action to a form or submit button (`action={fn}` / `formAction={fn}`). */
|
|
300
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;
|
|
301
338
|
el.__krateFormAction = get;
|
|
302
339
|
// The native POST target only serves the no-JS fallback; once the function
|
|
303
340
|
// is bound the element matches React's client DOM (no action attribute).
|
|
@@ -439,6 +476,55 @@ export function installActionForms(doc = typeof document !== 'undefined' ? docum
|
|
|
439
476
|
w.__krateActionBound = true;
|
|
440
477
|
doc.addEventListener('submit', onSubmit, false);
|
|
441
478
|
}
|
|
479
|
+
// Flash state from native form posts
|
|
480
|
+
function decodeFlash(value) {
|
|
481
|
+
try {
|
|
482
|
+
const raw = value.replace(/-/g, '+').replace(/_/g, '/');
|
|
483
|
+
const bin = atob(raw + '='.repeat((4 - (raw.length % 4)) % 4));
|
|
484
|
+
return JSON.parse(decodeURIComponent(escape(bin)));
|
|
485
|
+
}
|
|
486
|
+
catch {
|
|
487
|
+
return null;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Reads and clears the flash state a native form post left for action `id`:
|
|
492
|
+
* the `krate_flash` cookie the action endpoint sets, or, when the server
|
|
493
|
+
* already rendered it into the page (a no-JS style notice carrying the same
|
|
494
|
+
* payload in `data-krate-flash`), that element, which is removed because the
|
|
495
|
+
* form state now shows it.
|
|
496
|
+
*/
|
|
497
|
+
export function takeFlash(id) {
|
|
498
|
+
if (typeof document === 'undefined')
|
|
499
|
+
return { found: false };
|
|
500
|
+
const m = /(?:^|;\s*)krate_flash=([^;]*)/.exec(document.cookie || '');
|
|
501
|
+
if (m) {
|
|
502
|
+
const payload = decodeFlash(m[1]);
|
|
503
|
+
if (payload && payload.a === id) {
|
|
504
|
+
document.cookie = 'krate_flash=; Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax';
|
|
505
|
+
removeFlashNotices(id);
|
|
506
|
+
return { found: true, value: payload.r };
|
|
507
|
+
}
|
|
508
|
+
return { found: false };
|
|
509
|
+
}
|
|
510
|
+
const notices = document.querySelectorAll('[data-krate-flash]');
|
|
511
|
+
for (let i = 0; i < notices.length; i++) {
|
|
512
|
+
const payload = decodeFlash(notices[i].getAttribute('data-krate-flash') || '');
|
|
513
|
+
if (payload && payload.a === id) {
|
|
514
|
+
removeFlashNotices(id);
|
|
515
|
+
return { found: true, value: payload.r };
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
return { found: false };
|
|
519
|
+
}
|
|
520
|
+
function removeFlashNotices(id) {
|
|
521
|
+
const notices = document.querySelectorAll('[data-krate-flash]');
|
|
522
|
+
for (let i = 0; i < notices.length; i++) {
|
|
523
|
+
const payload = decodeFlash(notices[i].getAttribute('data-krate-flash') || '');
|
|
524
|
+
if (payload && payload.a === id)
|
|
525
|
+
notices[i].parentNode?.removeChild(notices[i]);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
442
528
|
/**
|
|
443
529
|
* Backs `const [state, formAction, isPending] = useActionState(fn, initial)`.
|
|
444
530
|
* The returned dispatch can be a form action, a button formAction, or called
|
|
@@ -449,14 +535,24 @@ export function installActionForms(doc = typeof document !== 'undefined' ? docum
|
|
|
449
535
|
export function __krateActionState(action, getState, setState, setPending) {
|
|
450
536
|
const queue = [];
|
|
451
537
|
let running = false;
|
|
538
|
+
// A native (no-JS or not-yet-hydrated) form post redirected back to this page
|
|
539
|
+
// with the action's returned state in a short-lived cookie: start from it.
|
|
540
|
+
if (isServerAction(action)) {
|
|
541
|
+
const flashed = takeFlash(action.$$krateAction);
|
|
542
|
+
if (flashed.found)
|
|
543
|
+
setState(flashed.value);
|
|
544
|
+
}
|
|
452
545
|
const drain = async () => {
|
|
453
546
|
running = true;
|
|
454
547
|
while (queue.length > 0) {
|
|
455
548
|
const item = queue.shift();
|
|
456
549
|
let ok = false;
|
|
457
550
|
try {
|
|
551
|
+
const before = redirectsFollowed;
|
|
458
552
|
const next = await runActionTransition(() => action(getState(), item.payload));
|
|
459
|
-
|
|
553
|
+
// A redirecting action has no next state: the page is being replaced.
|
|
554
|
+
if (redirectsFollowed === before)
|
|
555
|
+
krateTransitionWrites(() => setState(next));
|
|
460
556
|
ok = true;
|
|
461
557
|
}
|
|
462
558
|
catch (err) {
|
package/dist/actions.test.js
CHANGED
|
@@ -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,4 +413,65 @@ 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
|
+
});
|
|
430
|
+
it('dispatches krate:revalidate when the action revalidated server caches', async () => {
|
|
431
|
+
const revalidation = { paths: [{ path: '/posts', type: 'page' }], tags: ['posts'] };
|
|
432
|
+
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ ok: true, result: 1, revalidated: true, revalidation })));
|
|
433
|
+
const seen = [];
|
|
434
|
+
const onRevalidate = (e) => seen.push(e.detail);
|
|
435
|
+
window.addEventListener('krate:revalidate', onRevalidate);
|
|
436
|
+
try {
|
|
437
|
+
await expect(__krateAction('a5')()).resolves.toBe(1);
|
|
438
|
+
expect(seen).toEqual([revalidation]);
|
|
439
|
+
}
|
|
440
|
+
finally {
|
|
441
|
+
window.removeEventListener('krate:revalidate', onRevalidate);
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
it('does not dispatch krate:revalidate for actions that revalidated nothing', async () => {
|
|
445
|
+
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ ok: true, result: null })));
|
|
446
|
+
const handler = vi.fn();
|
|
447
|
+
window.addEventListener('krate:revalidate', handler);
|
|
448
|
+
try {
|
|
449
|
+
await __krateAction('a6')();
|
|
450
|
+
expect(handler).not.toHaveBeenCalled();
|
|
451
|
+
}
|
|
452
|
+
finally {
|
|
453
|
+
window.removeEventListener('krate:revalidate', handler);
|
|
454
|
+
}
|
|
455
|
+
});
|
|
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
|
+
});
|
|
391
477
|
});
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server data cache and render cache scopes.
|
|
3
|
+
*
|
|
4
|
+
* This module holds the process-wide state behind `@krate/runtime/cache`:
|
|
5
|
+
*
|
|
6
|
+
* - The render scope: the SSR renderer runs every page and region render
|
|
7
|
+
* inside `withCacheScope`, which records the cache tags, the smallest
|
|
8
|
+
* revalidate window and any no-store read the render made. The renderer
|
|
9
|
+
* stores the tags on its ISR/region cache entry so `revalidateTag` can find
|
|
10
|
+
* the entries a tag fed.
|
|
11
|
+
* - The data cache: `unstable_cache` results and `fetch` responses cached via
|
|
12
|
+
* `{ next: { revalidate, tags } }` or `cache: "force-cache"`, keyed by the
|
|
13
|
+
* call, expired by revalidate seconds and indexed by tag.
|
|
14
|
+
* - The `fetch` wrapper that applies those options.
|
|
15
|
+
*
|
|
16
|
+
* State lives on `globalThis` under `Symbol.for` keys, so the copy bundled
|
|
17
|
+
* into the renderer and the copy a page bundle imports share it. The module
|
|
18
|
+
* has no Node imports: the embedded QuickJS API runtime bundles it too, and
|
|
19
|
+
* there the data cache is backed by the Go host (`_go_cache_get/_go_cache_set`).
|
|
20
|
+
*/
|
|
21
|
+
/** What one render read through the cache. */
|
|
22
|
+
export interface CacheScope {
|
|
23
|
+
/** Route being rendered (diagnostics only). */
|
|
24
|
+
route: string;
|
|
25
|
+
/** Cache tags the render read. */
|
|
26
|
+
tags: Set<string>;
|
|
27
|
+
/** Smallest positive revalidate window (seconds) a read declared; 0 = none. */
|
|
28
|
+
revalidate: number;
|
|
29
|
+
/** True when a read opted out of caching (no-store, revalidate 0, unstable_noStore). */
|
|
30
|
+
noStore: boolean;
|
|
31
|
+
}
|
|
32
|
+
/** Minimal AsyncLocalStorage shape (the Node class satisfies it). */
|
|
33
|
+
export interface AsyncStore<T> {
|
|
34
|
+
getStore(): T | undefined;
|
|
35
|
+
run<R>(store: T, fn: () => R): R;
|
|
36
|
+
}
|
|
37
|
+
/** Pending revalidations of one server action or API request. */
|
|
38
|
+
export interface RevalidateScope {
|
|
39
|
+
kind: string;
|
|
40
|
+
paths: Array<{
|
|
41
|
+
path: string;
|
|
42
|
+
type: 'page' | 'layout';
|
|
43
|
+
}>;
|
|
44
|
+
tags: string[];
|
|
45
|
+
}
|
|
46
|
+
/** In-process data cache with tag index and FIFO bound. */
|
|
47
|
+
export declare class DataCache {
|
|
48
|
+
private max;
|
|
49
|
+
private map;
|
|
50
|
+
private byTag;
|
|
51
|
+
constructor(max?: number);
|
|
52
|
+
get size(): number;
|
|
53
|
+
get(key: string): unknown | undefined;
|
|
54
|
+
set(key: string, value: unknown, ttlSeconds: number, tags: string[]): void;
|
|
55
|
+
delete(key: string): void;
|
|
56
|
+
/** Removes every entry carrying one of tags; returns how many. */
|
|
57
|
+
invalidateTags(tags: string[]): number;
|
|
58
|
+
clear(): void;
|
|
59
|
+
}
|
|
60
|
+
/** Process-wide cache runtime shared by every bundled copy of this module. */
|
|
61
|
+
export interface CacheRuntime {
|
|
62
|
+
dataCache: DataCache;
|
|
63
|
+
/** Render scope storage; installed by the SSR renderer. */
|
|
64
|
+
renderStore?: AsyncStore<CacheScope>;
|
|
65
|
+
/** Bumped on every invalidation so in-flight renders/reads do not store stale results. */
|
|
66
|
+
epoch: number;
|
|
67
|
+
/** Applies a tag invalidation to the local data cache. */
|
|
68
|
+
invalidate(payload: {
|
|
69
|
+
tags?: string[];
|
|
70
|
+
}): {
|
|
71
|
+
dataEntries: number;
|
|
72
|
+
};
|
|
73
|
+
fetchPatched?: boolean;
|
|
74
|
+
}
|
|
75
|
+
/** The shared cache runtime, created on first use. */
|
|
76
|
+
export declare function cacheRuntime(): CacheRuntime;
|
|
77
|
+
/** Installs the render scope storage (an AsyncLocalStorage). Renderer only. */
|
|
78
|
+
export declare function installRenderStore(store: AsyncStore<CacheScope>): void;
|
|
79
|
+
/** The scope of the render currently running, if any. */
|
|
80
|
+
export declare function currentRenderScope(): CacheScope | undefined;
|
|
81
|
+
/** The pending-revalidation scope of the current server action / API request. */
|
|
82
|
+
export declare function currentRevalidateScope(): RevalidateScope | undefined;
|
|
83
|
+
/**
|
|
84
|
+
* Runs fn inside a fresh render scope and returns its result together with
|
|
85
|
+
* the scope (tags, revalidate window, noStore) and whether an invalidation
|
|
86
|
+
* happened while it ran (then the result must not be cached).
|
|
87
|
+
*/
|
|
88
|
+
export declare function withCacheScope<T>(route: string, fn: () => T | Promise<T>): Promise<{
|
|
89
|
+
result: T;
|
|
90
|
+
scope: CacheScope;
|
|
91
|
+
invalidated: boolean;
|
|
92
|
+
}>;
|
|
93
|
+
/**
|
|
94
|
+
* Implicit tag carried by data-cache entries first stored while rendering
|
|
95
|
+
* route, so revalidatePath(route) also drops the data that render cached.
|
|
96
|
+
*/
|
|
97
|
+
export declare function routeDataTag(route: string): string;
|
|
98
|
+
/** Records tags and a revalidate window on the current render scope. */
|
|
99
|
+
export declare function recordCacheRead(tags: readonly string[] | undefined, revalidate: number | false | undefined): void;
|
|
100
|
+
/** Marks the current render as uncacheable. Outside a render it has no effect. */
|
|
101
|
+
export declare function markNoStore(): void;
|
|
102
|
+
/** Reads a JSON value from the data cache; undefined on a miss. */
|
|
103
|
+
export declare function dataCacheGetJSON(key: string): string | undefined;
|
|
104
|
+
/**
|
|
105
|
+
* Stores a JSON value unless an invalidation happened since epoch. Inside a
|
|
106
|
+
* render the entry also gets the route's implicit tag (see routeDataTag).
|
|
107
|
+
*/
|
|
108
|
+
export declare function dataCacheSetJSON(key: string, json: string, ttlSeconds: number, tags: string[], epoch: number): void;
|
|
109
|
+
/**
|
|
110
|
+
* Wraps globalThis.fetch once so Next-style cache options work in server
|
|
111
|
+
* code: `next.tags` are recorded on the current render, `next.revalidate: N`
|
|
112
|
+
* or `cache: "force-cache"` cache successful GET/HEAD responses (by method,
|
|
113
|
+
* URL and headers) for N seconds (indefinitely for force-cache or
|
|
114
|
+
* `revalidate: false`) under the given tags, and `cache: "no-store"` /
|
|
115
|
+
* `next.revalidate: 0` bypass the cache and make the render uncacheable.
|
|
116
|
+
* Requests without these options are passed through untouched.
|
|
117
|
+
*/
|
|
118
|
+
export declare function patchFetch(): void;
|