@krate/runtime 0.5.0-rc.13 → 0.5.0-rc.14
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 +2 -0
- package/dist/action-context.js +7 -0
- package/dist/action-seal.d.ts +5 -0
- package/dist/action-seal.js +105 -0
- package/dist/actions.js +7 -1
- package/dist/cache-scope.d.ts +2 -0
- package/dist/flight-props.d.ts +2 -0
- package/dist/flight-props.js +12 -1
- package/dist/handler-routing.js +7 -1
- package/dist/island-swap.js +3 -0
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-navigation.js +1 -1
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-island-swap.js +1 -1
- package/dist/krate-runtime.js +5 -5
- package/dist/navigation-server.d.ts +1 -2
- package/dist/navigation-server.js +1 -2
- package/dist/navigation.d.ts +1 -1
- package/dist/navigation.js +7 -2
- package/dist/process-guard.d.ts +23 -0
- package/dist/process-guard.js +45 -0
- package/dist/react-types.d.ts +29 -0
- package/dist/react-types.js +1 -0
- package/dist/react.d.ts +2 -0
- package/dist/react.js +3 -0
- package/dist/request-context.d.ts +5 -0
- package/dist/request-context.js +17 -0
- package/dist/router.js +17 -0
- package/dist/server-handler.d.ts +2 -0
- package/dist/server-handler.js +42 -7
- package/dist/server-renderer.js +88 -0
- package/dist/server.d.ts +1 -1
- package/dist/server.js +55 -9
- package/dist/ssr-core.d.ts +2 -0
- package/dist/ssr-core.js +6 -3
- package/package.json +5 -1
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
export { redirect as permanentRedirect };
|
|
1
|
+
export { permanentRedirect } from './action-context.js';
|
|
3
2
|
type ParamValue = string | string[];
|
|
4
3
|
/** The current URL path without the query ("/blog/hello"). */
|
|
5
4
|
export declare function usePathname(): string;
|
|
@@ -2,8 +2,7 @@
|
|
|
2
2
|
// the portable handler). They read the request being rendered, so a page
|
|
3
3
|
// rendered per request sees its own URL. See navigation.ts for the browser side.
|
|
4
4
|
import { getRequestContext } from './request-context.js';
|
|
5
|
-
|
|
6
|
-
export { redirect as permanentRedirect };
|
|
5
|
+
export { permanentRedirect } from './action-context.js';
|
|
7
6
|
/** The URL path of the request: the route pattern with its params filled in. */
|
|
8
7
|
function requestPath() {
|
|
9
8
|
const ctx = getRequestContext();
|
package/dist/navigation.d.ts
CHANGED
|
@@ -51,6 +51,6 @@ export declare function useSelectedLayoutSegments(parallelRouteKey?: string, dep
|
|
|
51
51
|
export declare function useSelectedLayoutSegment(parallelRouteKey?: string, depth?: number): string | null;
|
|
52
52
|
/** Throws the signal the host answers with a redirect while rendering; navigates in the browser. */
|
|
53
53
|
export declare function redirect(url: string): never;
|
|
54
|
-
/** redirect()
|
|
54
|
+
/** redirect() that a page or API route answers with 308 instead of 307. */
|
|
55
55
|
export declare function permanentRedirect(url: string): never;
|
|
56
56
|
export { notFound, forbidden, unauthorized } from './request-context.js';
|
package/dist/navigation.js
CHANGED
|
@@ -223,8 +223,13 @@ export function redirect(url) {
|
|
|
223
223
|
err.__krateRedirect = url;
|
|
224
224
|
throw err;
|
|
225
225
|
}
|
|
226
|
-
/** redirect()
|
|
226
|
+
/** redirect() that a page or API route answers with 308 instead of 307. */
|
|
227
227
|
export function permanentRedirect(url) {
|
|
228
|
-
|
|
228
|
+
if (typeof location !== 'undefined')
|
|
229
|
+
void krateRouter.push(url);
|
|
230
|
+
const err = new Error('Server action redirect to ' + url);
|
|
231
|
+
err.__krateRedirect = url;
|
|
232
|
+
err.__krateRedirectStatus = 308;
|
|
233
|
+
throw err;
|
|
229
234
|
}
|
|
230
235
|
export { notFound, forbidden, unauthorized } from './request-context.js';
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process-level error policy of the SSR renderer.
|
|
3
|
+
*
|
|
4
|
+
* A render error is that request's error: it ends as a 500 or the error page.
|
|
5
|
+
* Node's defaults are harsher for the errors a render leaves behind outside its
|
|
6
|
+
* own promise chain, a rejected promise nobody awaited or a throw from a timer
|
|
7
|
+
* or event callback: they end the process, and every other page then answers
|
|
8
|
+
* 503 until the supervisor has restarted the renderer. Those are logged and the
|
|
9
|
+
* renderer keeps serving. What stays fatal is an uncaught exception that does
|
|
10
|
+
* not belong to any request (the renderer's own code, a failed listener), since
|
|
11
|
+
* the process state can no longer be trusted.
|
|
12
|
+
*/
|
|
13
|
+
/** The part of `process` the guards use. */
|
|
14
|
+
export interface GuardedProcess {
|
|
15
|
+
on(event: 'unhandledRejection' | 'uncaughtException', listener: (...args: any[]) => void): unknown;
|
|
16
|
+
exit(code?: number): unknown;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Installs the policy. An unhandled rejection never ends the renderer. An
|
|
20
|
+
* uncaught exception raised inside a request's async scope is logged; one
|
|
21
|
+
* outside any request exits with status 1, as Node does by default.
|
|
22
|
+
*/
|
|
23
|
+
export declare function installProcessGuards(proc?: GuardedProcess, log?: (...args: unknown[]) => void): void;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process-level error policy of the SSR renderer.
|
|
3
|
+
*
|
|
4
|
+
* A render error is that request's error: it ends as a 500 or the error page.
|
|
5
|
+
* Node's defaults are harsher for the errors a render leaves behind outside its
|
|
6
|
+
* own promise chain, a rejected promise nobody awaited or a throw from a timer
|
|
7
|
+
* or event callback: they end the process, and every other page then answers
|
|
8
|
+
* 503 until the supervisor has restarted the renderer. Those are logged and the
|
|
9
|
+
* renderer keeps serving. What stays fatal is an uncaught exception that does
|
|
10
|
+
* not belong to any request (the renderer's own code, a failed listener), since
|
|
11
|
+
* the process state can no longer be trusted.
|
|
12
|
+
*/
|
|
13
|
+
import { getRequestContext } from './request-context.js';
|
|
14
|
+
function describe(err) {
|
|
15
|
+
if (err instanceof Error)
|
|
16
|
+
return err.stack || `${err.name}: ${err.message}`;
|
|
17
|
+
try {
|
|
18
|
+
return typeof err === 'string' ? err : JSON.stringify(err);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return String(err);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function where() {
|
|
25
|
+
const req = getRequestContext();
|
|
26
|
+
return req ? ` while rendering ${req.method} ${req.url}` : '';
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Installs the policy. An unhandled rejection never ends the renderer. An
|
|
30
|
+
* uncaught exception raised inside a request's async scope is logged; one
|
|
31
|
+
* outside any request exits with status 1, as Node does by default.
|
|
32
|
+
*/
|
|
33
|
+
export function installProcessGuards(proc = process, log = console.error) {
|
|
34
|
+
proc.on('unhandledRejection', (reason) => {
|
|
35
|
+
log(`[krate-ssr] unhandled promise rejection${where()} (the renderer keeps running): ${describe(reason)}`);
|
|
36
|
+
});
|
|
37
|
+
proc.on('uncaughtException', (err) => {
|
|
38
|
+
if (getRequestContext()) {
|
|
39
|
+
log(`[krate-ssr] uncaught exception${where()} (the renderer keeps running): ${describe(err)}`);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
log(`[krate-ssr] uncaught exception outside any request, exiting: ${describe(err)}`);
|
|
43
|
+
proc.exit(1);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/// <reference types="react" />
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Opt-in typing bridge for apps that keep React-typed code (@types/react).
|
|
5
|
+
*
|
|
6
|
+
* Krate's global `JSX.Element` extends the DOM `Node`, which React's
|
|
7
|
+
* `ReactNode` rejects. That breaks two setups:
|
|
8
|
+
*
|
|
9
|
+
* - `jsx: "react-jsx"`: the globals `<Link>`, `<Head>`, ... fail with TS2786.
|
|
10
|
+
* - `jsx: "preserve"` + `jsxImportSource: "@krate/runtime"` (what
|
|
11
|
+
* `krate migrate nextjs` writes): every intrinsic element is a Krate
|
|
12
|
+
* `Element`, which React-typed props (`children: ReactNode`) reject.
|
|
13
|
+
*
|
|
14
|
+
* Importing this file makes `JSX.Element` also a `React.ReactElement`, so it is
|
|
15
|
+
* assignable to `ReactNode` in both setups. Include it once, for example:
|
|
16
|
+
*
|
|
17
|
+
* // src/krate-react.d.ts
|
|
18
|
+
* import "@krate/runtime/react-types";
|
|
19
|
+
*
|
|
20
|
+
* It needs @types/react; plain Krate apps should not import it.
|
|
21
|
+
*/
|
|
22
|
+
declare global {
|
|
23
|
+
namespace JSX {
|
|
24
|
+
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
|
|
25
|
+
interface Element extends React.ReactElement<any, any> {}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/react.d.ts
CHANGED
|
@@ -142,6 +142,8 @@ export declare function SuspenseList(props: {
|
|
|
142
142
|
export declare const unstable_SuspenseList: typeof SuspenseList;
|
|
143
143
|
/** React 19.2's useEffectEvent: a function that always runs the latest closure. */
|
|
144
144
|
export declare const useEffectEvent: <T extends (...args: never[]) => unknown>(fn: T) => T;
|
|
145
|
+
/** React's `useId()`; the compiler lowers it, this serves modules that reach it through the compat module. */
|
|
146
|
+
export declare const useId: () => string;
|
|
145
147
|
export declare function useRef<T = unknown>(initial?: T): RefObject<T>;
|
|
146
148
|
type EffectCallback = () => void | (() => void);
|
|
147
149
|
/** Passive effect: runs after paint, re-runs when a live dependency changes. */
|
package/dist/react.js
CHANGED
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
import { h, krateTrackNode } from './dom.js';
|
|
21
21
|
import { getOwner, handleError } from './boundary.js';
|
|
22
22
|
import { createSignal, createReducer, isSignalGetter } from './signal.js';
|
|
23
|
+
import { __krate_useId } from './use-id.js';
|
|
23
24
|
import { createEffectDeps, createEffectEvent } from './effects.js';
|
|
24
25
|
import { krateSetRef } from './refs.js';
|
|
25
26
|
import { krateEventRoot } from './events.js';
|
|
@@ -363,6 +364,8 @@ export function SuspenseList(props) {
|
|
|
363
364
|
export const unstable_SuspenseList = SuspenseList;
|
|
364
365
|
/** React 19.2's useEffectEvent: a function that always runs the latest closure. */
|
|
365
366
|
export const useEffectEvent = createEffectEvent;
|
|
367
|
+
/** React's `useId()`; the compiler lowers it, this serves modules that reach it through the compat module. */
|
|
368
|
+
export const useId = __krate_useId;
|
|
366
369
|
export function useRef(initial) {
|
|
367
370
|
return { current: initial ?? null };
|
|
368
371
|
}
|
|
@@ -81,5 +81,10 @@ export declare function unauthorized(): never;
|
|
|
81
81
|
export declare function accessDeniedStatus(err: unknown): 401 | 403 | 0;
|
|
82
82
|
/** httpFallbackStatus is 404, 403 or 401 for notFound(), forbidden() and unauthorized() signals, else 0. */
|
|
83
83
|
export declare function httpFallbackStatus(err: unknown): 401 | 403 | 404 | 0;
|
|
84
|
+
/**
|
|
85
|
+
* redirectStatus is the HTTP status of a redirect() signal: 307, or 308 for
|
|
86
|
+
* permanentRedirect() (Next.js's NEXT_REDIRECT digest carries it as well).
|
|
87
|
+
*/
|
|
88
|
+
export declare function redirectStatus(err: unknown): 307 | 308;
|
|
84
89
|
/** redirectTarget returns the URL of a redirect() signal, or "" for other errors. */
|
|
85
90
|
export declare function redirectTarget(err: unknown): string;
|
package/dist/request-context.js
CHANGED
|
@@ -134,6 +134,23 @@ export function httpFallbackStatus(err) {
|
|
|
134
134
|
return 404;
|
|
135
135
|
return accessDeniedStatus(err);
|
|
136
136
|
}
|
|
137
|
+
/**
|
|
138
|
+
* redirectStatus is the HTTP status of a redirect() signal: 307, or 308 for
|
|
139
|
+
* permanentRedirect() (Next.js's NEXT_REDIRECT digest carries it as well).
|
|
140
|
+
*/
|
|
141
|
+
export function redirectStatus(err) {
|
|
142
|
+
if (!err || typeof err !== 'object')
|
|
143
|
+
return 307;
|
|
144
|
+
const e = err;
|
|
145
|
+
if (e.__krateRedirectStatus === 308)
|
|
146
|
+
return 308;
|
|
147
|
+
if (typeof e.digest === 'string' && e.digest.startsWith('NEXT_REDIRECT;')) {
|
|
148
|
+
const parts = e.digest.split(';');
|
|
149
|
+
if (parts[3] === '308' || parts[3] === '301')
|
|
150
|
+
return 308;
|
|
151
|
+
}
|
|
152
|
+
return 307;
|
|
153
|
+
}
|
|
137
154
|
/** redirectTarget returns the URL of a redirect() signal, or "" for other errors. */
|
|
138
155
|
export function redirectTarget(err) {
|
|
139
156
|
if (!err || typeof err !== 'object')
|
package/dist/router.js
CHANGED
|
@@ -2102,6 +2102,21 @@ function clickHandler(e) {
|
|
|
2102
2102
|
scroll: a.getAttribute('data-krate-scroll') !== 'false',
|
|
2103
2103
|
});
|
|
2104
2104
|
}
|
|
2105
|
+
/**
|
|
2106
|
+
* True when the form (or its submit button) runs a client action: an island's
|
|
2107
|
+
* `<form action={fn}>` (react-compat sets `__krateForm` / `__krateFormAction`)
|
|
2108
|
+
* or a server-action form (`data-krate-action`). Those listeners bail once the
|
|
2109
|
+
* event is defaultPrevented, so the router must not claim the submit first.
|
|
2110
|
+
*/
|
|
2111
|
+
function carriesClientAction(form, submitter) {
|
|
2112
|
+
const own = (el) => {
|
|
2113
|
+
if (!el)
|
|
2114
|
+
return false;
|
|
2115
|
+
const a = el;
|
|
2116
|
+
return !!(a.__krateForm || a.__krateFormAction) || el.hasAttribute('data-krate-action');
|
|
2117
|
+
};
|
|
2118
|
+
return own(form) || own(submitter);
|
|
2119
|
+
}
|
|
2105
2120
|
function submitHandler(e) {
|
|
2106
2121
|
if (e.defaultPrevented)
|
|
2107
2122
|
return;
|
|
@@ -2111,6 +2126,8 @@ function submitHandler(e) {
|
|
|
2111
2126
|
if (form.hasAttribute('data-krate-reload'))
|
|
2112
2127
|
return;
|
|
2113
2128
|
const submitter = (e.submitter || null);
|
|
2129
|
+
if (carriesClientAction(form, submitter))
|
|
2130
|
+
return;
|
|
2114
2131
|
const method = ((submitter && submitter.getAttribute('formmethod')) || form.getAttribute('method') || 'get').toLowerCase();
|
|
2115
2132
|
if (method !== 'get')
|
|
2116
2133
|
return;
|
package/dist/server-handler.d.ts
CHANGED
|
@@ -229,5 +229,7 @@ export declare function ruleHeaderPairs(h: Record<string, string> | Array<{
|
|
|
229
229
|
* key derived from the action secret (the format the server renderer seals).
|
|
230
230
|
*/
|
|
231
231
|
export declare function openInlineToken(token: unknown, entry: ActionEntry, secret: string): Promise<unknown[]>;
|
|
232
|
+
/** Opens a "k1." token for the action: inline captures, or the arguments a module action was bound to. */
|
|
233
|
+
export declare function openSealedToken(token: unknown, entry: ActionEntry, secret: string): Promise<unknown[]>;
|
|
232
234
|
export declare function createKrateHandler(options: HandlerOptions): KrateHandler;
|
|
233
235
|
export { isDynamicPattern };
|
package/dist/server-handler.js
CHANGED
|
@@ -229,6 +229,13 @@ function decodeInlineValue(v) {
|
|
|
229
229
|
* key derived from the action secret (the format the server renderer seals).
|
|
230
230
|
*/
|
|
231
231
|
export async function openInlineToken(token, entry, secret) {
|
|
232
|
+
const values = await openSealedToken(token, entry, secret);
|
|
233
|
+
if (values.length !== (entry.captures || []).length)
|
|
234
|
+
throw new Error("closure token does not match the action");
|
|
235
|
+
return values;
|
|
236
|
+
}
|
|
237
|
+
/** Opens a "k1." token for the action: inline captures, or the arguments a module action was bound to. */
|
|
238
|
+
export async function openSealedToken(token, entry, secret) {
|
|
232
239
|
if (typeof token !== "string" || !token.startsWith("k1."))
|
|
233
240
|
throw new Error("missing closure token");
|
|
234
241
|
if (!secret)
|
|
@@ -243,7 +250,7 @@ export async function openInlineToken(token, entry, secret) {
|
|
|
243
250
|
const key = await crypto.subtle.importKey("raw", digest, "AES-GCM", false, ["decrypt"]);
|
|
244
251
|
const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: raw.subarray(0, 12), additionalData: enc.encode(entry.id) }, key, raw.subarray(12));
|
|
245
252
|
const values = JSON.parse(new TextDecoder().decode(plain));
|
|
246
|
-
if (!Array.isArray(values)
|
|
253
|
+
if (!Array.isArray(values))
|
|
247
254
|
throw new Error("closure token does not match the action");
|
|
248
255
|
return values.map(decodeInlineValue);
|
|
249
256
|
}
|
|
@@ -365,6 +372,13 @@ export function createKrateHandler(options) {
|
|
|
365
372
|
}
|
|
366
373
|
return null;
|
|
367
374
|
}
|
|
375
|
+
const ssgRoutes = data.allPages.filter((p) => p.mode === "ssg").map((p) => p.route);
|
|
376
|
+
/** A prerendered page that matches urlPath with a more specific route than the request-time page that did. */
|
|
377
|
+
function ssgShadows(urlPath, page) {
|
|
378
|
+
if (!page)
|
|
379
|
+
return false;
|
|
380
|
+
return ssgRoutes.some((r) => compareRouteSpecificity(r, page.route) < 0 && matchRoutePattern(urlPath, r) !== null);
|
|
381
|
+
}
|
|
368
382
|
const templates = [...data.templates].sort((a, b) => compareRouteSpecificity(a.pattern, b.pattern));
|
|
369
383
|
const corsOrigins = cfg.cors.origins.length ? cfg.cors.origins : ["*"];
|
|
370
384
|
// Middleware
|
|
@@ -583,6 +597,8 @@ export function createKrateHandler(options) {
|
|
|
583
597
|
if (k !== "host")
|
|
584
598
|
out[canonicalHeader(k)] = v;
|
|
585
599
|
});
|
|
600
|
+
// The Go server passes Host (Go hoists it out of the header map); so do we.
|
|
601
|
+
out["Host"] = rs.headers.get("host") || new URL(rs.request.url).host;
|
|
586
602
|
return out;
|
|
587
603
|
}
|
|
588
604
|
function canonicalHeader(k) {
|
|
@@ -788,7 +804,7 @@ export function createKrateHandler(options) {
|
|
|
788
804
|
let route = requestRoute(rs.path);
|
|
789
805
|
const found = findPageForRoute(route);
|
|
790
806
|
const page = found ? found.page : null;
|
|
791
|
-
if (await shouldServeStatic(rs.path, page))
|
|
807
|
+
if ((await shouldServeStatic(rs.path, page)) || ssgShadows(rs.path, page))
|
|
792
808
|
return staticHandler(rs);
|
|
793
809
|
if (!found || !page)
|
|
794
810
|
return staticHandler(rs);
|
|
@@ -878,6 +894,7 @@ export function createKrateHandler(options) {
|
|
|
878
894
|
let notFound = false;
|
|
879
895
|
let denied = 0;
|
|
880
896
|
let redirect = "";
|
|
897
|
+
let redirectCode = 307;
|
|
881
898
|
let renderErr = "";
|
|
882
899
|
let fatalErr = "";
|
|
883
900
|
let errStack = "";
|
|
@@ -891,8 +908,10 @@ export function createKrateHandler(options) {
|
|
|
891
908
|
if (id !== "page" && (frame.notFound || frame.denied || frame.redirect)) {
|
|
892
909
|
notFound = notFound || !!frame.notFound;
|
|
893
910
|
denied = denied || frame.denied || 0;
|
|
894
|
-
if (!redirect)
|
|
895
|
-
redirect = frame.redirect
|
|
911
|
+
if (!redirect && frame.redirect) {
|
|
912
|
+
redirect = frame.redirect;
|
|
913
|
+
redirectCode = frame.status === 308 ? 308 : 307;
|
|
914
|
+
}
|
|
896
915
|
continue;
|
|
897
916
|
}
|
|
898
917
|
if (frame.noStore)
|
|
@@ -905,6 +924,8 @@ export function createKrateHandler(options) {
|
|
|
905
924
|
notFound = !!frame.notFound;
|
|
906
925
|
denied = denied || frame.denied || 0;
|
|
907
926
|
redirect = frame.redirect || "";
|
|
927
|
+
if (redirect)
|
|
928
|
+
redirectCode = frame.status === 308 ? 308 : 307;
|
|
908
929
|
if ((frame.status || 0) >= 500 || frame.error) {
|
|
909
930
|
renderErr = frame.error || `page-region render failed with status ${frame.status}`;
|
|
910
931
|
errStack = frame.stack || "";
|
|
@@ -962,7 +983,7 @@ export function createKrateHandler(options) {
|
|
|
962
983
|
}
|
|
963
984
|
if (notFound || denied || redirect) {
|
|
964
985
|
if (redirect)
|
|
965
|
-
return goRedirect(redirect, rs.path, rs.method,
|
|
986
|
+
return goRedirect(redirect, rs.path, rs.method, redirectCode, rs.res);
|
|
966
987
|
if (denied)
|
|
967
988
|
return accessDenied(rs, denied, routeRef);
|
|
968
989
|
const page404 = errorPage(rs.path, 404, routeRef);
|
|
@@ -1667,7 +1688,7 @@ export function createKrateHandler(options) {
|
|
|
1667
1688
|
}
|
|
1668
1689
|
// Runs an API route inside the action store so headers(), cookies() and
|
|
1669
1690
|
// redirect() work in it like in a server action: cookies it sets are added to
|
|
1670
|
-
// the response and a redirect() signal becomes a 307.
|
|
1691
|
+
// the response and a redirect() signal becomes a 307 (308 for permanentRedirect()).
|
|
1671
1692
|
async function runRoute(request, run) {
|
|
1672
1693
|
const ctx = makeActionContext(request.headers, "", new URL(request.url).pathname);
|
|
1673
1694
|
ctx.method = request.method;
|
|
@@ -1678,7 +1699,7 @@ export function createKrateHandler(options) {
|
|
|
1678
1699
|
catch (e) {
|
|
1679
1700
|
if (!e || typeof e.__krateRedirect !== "string")
|
|
1680
1701
|
throw e;
|
|
1681
|
-
out = new Response(null, { status: 307, headers: { location: e.__krateRedirect, "cache-control": "no-store" } });
|
|
1702
|
+
out = new Response(null, { status: e.__krateRedirectStatus === 308 ? 308 : 307, headers: { location: e.__krateRedirect, "cache-control": "no-store" } });
|
|
1682
1703
|
}
|
|
1683
1704
|
if (ctx.setCookies.length > 0) {
|
|
1684
1705
|
const h = new Headers(out.headers);
|
|
@@ -1900,6 +1921,20 @@ export function createKrateHandler(options) {
|
|
|
1900
1921
|
return withHeaders(rs, actionFail(400, "Invalid server action request"));
|
|
1901
1922
|
}
|
|
1902
1923
|
}
|
|
1924
|
+
// Arguments a module action was bound to before it crossed into a client
|
|
1925
|
+
// component: sealed in the URL, so the client cannot choose them.
|
|
1926
|
+
const boundToken = query.get("__krate_bound");
|
|
1927
|
+
if (boundToken !== null) {
|
|
1928
|
+
try {
|
|
1929
|
+
if (entry.inline)
|
|
1930
|
+
throw new Error("an inline action has no bound arguments");
|
|
1931
|
+
args.unshift(...(await openSealedToken(boundToken, entry, actionSecret)));
|
|
1932
|
+
}
|
|
1933
|
+
catch (e) {
|
|
1934
|
+
console.error(`[krate] rejected bound arguments for server action ${entry.source || id}: ${e.message}`);
|
|
1935
|
+
return withHeaders(rs, actionFail(400, "Invalid server action request"));
|
|
1936
|
+
}
|
|
1937
|
+
}
|
|
1903
1938
|
const ctx = makeActionContext(reqHeaders, id, rs.path);
|
|
1904
1939
|
const scope = { kind: "action", paths: [], tags: [] };
|
|
1905
1940
|
let result;
|
package/dist/server-renderer.js
CHANGED
|
@@ -5,6 +5,7 @@ import cluster from "node:cluster";
|
|
|
5
5
|
import fs from "node:fs";
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import vm from "node:vm";
|
|
8
|
+
import nodeModule from "node:module";
|
|
8
9
|
import { pathToFileURL } from "node:url";
|
|
9
10
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
10
11
|
import { createHash, timingSafeEqual } from "node:crypto";
|
|
@@ -14,11 +15,13 @@ import { installRenderStore, patchFetch } from "./cache-scope.js";
|
|
|
14
15
|
import { cacheSpecFromEnv } from "./cache-adapter.js";
|
|
15
16
|
import { isrStoreFor } from "./shared-isr.js";
|
|
16
17
|
import { registerLanguage, setFenceResolver } from "./highlight.js";
|
|
18
|
+
import { installProcessGuards } from "./process-guard.js";
|
|
17
19
|
// Render cache scopes (tags / revalidate windows read during a render) and the
|
|
18
20
|
// Next-style fetch data cache. Installed once per process; page bundles share
|
|
19
21
|
// the state through globalThis.
|
|
20
22
|
installRenderStore(new AsyncLocalStorage());
|
|
21
23
|
patchFetch();
|
|
24
|
+
installProcessGuards();
|
|
22
25
|
// Shared secret for the mutating internal endpoints (/__krate/ssr/revalidate,
|
|
23
26
|
// /refresh, /invalidate, /cache-invalidate). Krate passes it from the Go host;
|
|
24
27
|
// a renderer started by hand without it keeps the endpoints open.
|
|
@@ -126,6 +129,24 @@ if (PARENT_PID > 0) {
|
|
|
126
129
|
parentWatch.unref();
|
|
127
130
|
}
|
|
128
131
|
let manifest = null;
|
|
132
|
+
// manifestFile returns the server manifest on disk: KRATE_MANIFEST, else the
|
|
133
|
+
// one under the output directory.
|
|
134
|
+
function manifestFile() {
|
|
135
|
+
if (manifestPath && fs.existsSync(manifestPath))
|
|
136
|
+
return manifestPath;
|
|
137
|
+
const krateDefault = path.join(OUT_DIR, ".krate", "server-manifest.json");
|
|
138
|
+
return fs.existsSync(krateDefault) ? krateDefault : path.join(OUT_DIR, "server-manifest.json");
|
|
139
|
+
}
|
|
140
|
+
let manifestStamp = "";
|
|
141
|
+
function statStamp(file) {
|
|
142
|
+
try {
|
|
143
|
+
const st = fs.statSync(file);
|
|
144
|
+
return `${st.mtimeMs}:${st.size}`;
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
return "";
|
|
148
|
+
}
|
|
149
|
+
}
|
|
129
150
|
if (manifestPath && fs.existsSync(manifestPath)) {
|
|
130
151
|
const data = fs.readFileSync(manifestPath, "utf-8");
|
|
131
152
|
manifest = JSON.parse(data);
|
|
@@ -197,6 +218,49 @@ async function loadPageModule(page) {
|
|
|
197
218
|
throw err;
|
|
198
219
|
}
|
|
199
220
|
}
|
|
221
|
+
// A page bundle is re-imported with a new query on every dev rebuild, but the
|
|
222
|
+
// modules it imports (the client component render modules under
|
|
223
|
+
// server-bundles/client/ and their chunks) were cached by URL for good: an
|
|
224
|
+
// edited client component kept rendering its old code, and a module first
|
|
225
|
+
// loaded after a rebuild came from a newer build than the layout's, so two
|
|
226
|
+
// copies of a module that creates a context could meet in one render. Once
|
|
227
|
+
// the first dev rebuild arrives, imports inside server-bundles take over the
|
|
228
|
+
// query of the module that imports them, so each reload of a page bundle
|
|
229
|
+
// loads its whole graph afresh and the graph is consistent. Node only; other
|
|
230
|
+
// runtimes keep the cached behaviour.
|
|
231
|
+
let bundleGraphVersioned = false;
|
|
232
|
+
function versionBundleGraph() {
|
|
233
|
+
if (bundleGraphVersioned)
|
|
234
|
+
return;
|
|
235
|
+
bundleGraphVersioned = true;
|
|
236
|
+
const register = nodeModule.register;
|
|
237
|
+
if (typeof register !== "function")
|
|
238
|
+
return;
|
|
239
|
+
const hooks = "let prefixes = [];\n" +
|
|
240
|
+
"export function initialize(data) { prefixes = data.prefixes; }\n" +
|
|
241
|
+
"export async function resolve(specifier, context, nextResolve) {\n" +
|
|
242
|
+
" const out = await nextResolve(specifier, context);\n" +
|
|
243
|
+
" const parent = context.parentURL ? new URL(context.parentURL) : null;\n" +
|
|
244
|
+
" if (parent && parent.search && prefixes.some((p) => out.url.startsWith(p)) && !out.url.includes('?')) return { ...out, url: out.url + parent.search };\n" +
|
|
245
|
+
" return out;\n" +
|
|
246
|
+
"}\n";
|
|
247
|
+
try {
|
|
248
|
+
// Node resolves module URLs to real paths, so a symlinked project root
|
|
249
|
+
// (macOS /var is /private/var) needs the real path as well.
|
|
250
|
+
const dir = path.join(OUT_DIR, ".krate", "server-bundles");
|
|
251
|
+
const prefixes = [pathToFileURL(dir).href + "/"];
|
|
252
|
+
try {
|
|
253
|
+
const real = pathToFileURL(fs.realpathSync(dir)).href + "/";
|
|
254
|
+
if (real !== prefixes[0])
|
|
255
|
+
prefixes.push(real);
|
|
256
|
+
}
|
|
257
|
+
catch { }
|
|
258
|
+
register("data:text/javascript," + encodeURIComponent(hooks), { parentURL: import.meta.url, data: { prefixes } });
|
|
259
|
+
}
|
|
260
|
+
catch (err) {
|
|
261
|
+
console.error("[krate-ssr] Could not version the page module graph; client components may render stale code in dev:", err.message);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
200
264
|
const runtimeBundleCache = new Map();
|
|
201
265
|
// loadRuntimeRenderer loads a compiled runtime component bundle and returns its
|
|
202
266
|
// __krate_render(props) function (props as an object or JSON). Bundles are cached by bundle path.
|
|
@@ -243,6 +307,26 @@ const core = createSSRCore({
|
|
|
243
307
|
});
|
|
244
308
|
const isrCache = isrMemory.cache;
|
|
245
309
|
const { findPage, renderPage, renderRegion, renderPageRegion } = core;
|
|
310
|
+
manifestStamp = statStamp(manifestFile());
|
|
311
|
+
// reloadManifest re-reads the server manifest when a dev rebuild changed it,
|
|
312
|
+
// so pages added while `krate dev` runs resolve without a restart. A manifest
|
|
313
|
+
// that cannot be read keeps the last good one.
|
|
314
|
+
function reloadManifest() {
|
|
315
|
+
const file = manifestFile();
|
|
316
|
+
const stamp = statStamp(file);
|
|
317
|
+
if (!stamp || stamp === manifestStamp)
|
|
318
|
+
return;
|
|
319
|
+
try {
|
|
320
|
+
const next = JSON.parse(fs.readFileSync(file, "utf-8"));
|
|
321
|
+
manifest = next;
|
|
322
|
+
core.setManifest(next);
|
|
323
|
+
manifestStamp = stamp;
|
|
324
|
+
console.log(`[krate-ssr] Reloaded manifest: ${next.pages.length} SSR/ISR/streaming pages`);
|
|
325
|
+
}
|
|
326
|
+
catch (err) {
|
|
327
|
+
console.error("[krate-ssr] Manifest not reloaded, keeping the last good one:", err.message);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
246
330
|
// ISR cache persistence - survives renderer restarts so a bounce doesn't
|
|
247
331
|
// cold-render every ISR variant. Written debounced (coalesced) to the build
|
|
248
332
|
// output dir (.krate/isr-cache.json), overridable via KRATE_ISR_CACHE.
|
|
@@ -304,6 +388,10 @@ async function applyInternalOp(op, payload) {
|
|
|
304
388
|
if (op !== "dev-invalidate")
|
|
305
389
|
return core.applyInternalOp(op, payload);
|
|
306
390
|
const { route: targetRoute, source, bundlePath } = payload;
|
|
391
|
+
reloadManifest();
|
|
392
|
+
versionBundleGraph();
|
|
393
|
+
if (!targetRoute)
|
|
394
|
+
return { ok: true };
|
|
307
395
|
// Invalidate the page and region caches for this route, then the module
|
|
308
396
|
// cache for the source file or bundle.
|
|
309
397
|
const key = bundlePath || source;
|
package/dist/server.d.ts
CHANGED
|
@@ -97,7 +97,7 @@ export declare function lazy<P = Record<string, any>>(loader: () => Promise<{
|
|
|
97
97
|
} | ((props: P) => unknown)>): (props: P & {
|
|
98
98
|
children?: JSXNode;
|
|
99
99
|
}) => Promise<JSXNode>;
|
|
100
|
-
type ClientRender = (component: unknown, props: Record<string, unknown>, childrenHTML: string | null, fwd?: SlotValues, capture?: Record<string, SlotValues
|
|
100
|
+
type ClientRender = (component: unknown, props: Record<string, unknown>, childrenHTML: string | null, fwd?: SlotValues, capture?: Record<string, SlotValues>, ids?: string) => string;
|
|
101
101
|
type SlotValues = {
|
|
102
102
|
k: string;
|
|
103
103
|
v: unknown;
|