@opentf/afw 0.38.0 → 0.40.0

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/runtime/router.js CHANGED
@@ -14,20 +14,22 @@
14
14
  // emit yet — for now pages read params via the reactive `router.params`, and a
15
15
  // route loader's data via the reactive `router.data` (docs/DATA.md).
16
16
 
17
+ import { DEV } from "../core/dev.js";
17
18
  import { clearError, reportError } from "../core/errors.js";
18
19
  import { signal } from "../core/signals.js";
19
20
  import { getRenderContext } from "../core/render-context.js";
20
21
  import { resolveMetadataModules } from "../core/metadata.js";
21
22
  import { prepareRouteHead, updateRouteHead } from "./head.js";
22
- import { beginHydration, cursor, endHydration, renderedForPath } from "./hydrate.js";
23
+ import { beginHydration, cursor, endHydration, renderedForPath, runBuild } from "./hydrate.js";
23
24
  import { collectHotState, withHotCarry } from "./hot-carry.js";
24
25
  import { buildScopedView, runCleanup, runMount } from "./mount.js";
25
- import { RouteRedirect, fetchRouteData, readInlineRouteData, routeErrorFrom } from "./route-data.js";
26
+ import { RouteNotFound, RouteRedirect, fetchRouteData, isNotFoundPayload, readInlineRouteData, routeErrorFrom } from "./route-data.js";
26
27
  import { enterPending, exitPending } from "./pending-scope.js";
27
28
  import { setRouteErrorHandler } from "./route-errors.js";
28
29
  import { enterEntry, manageScroll, rememberScroll, restoreScroll } from "./scroll.js";
29
30
  import { setRouteDataRefresher } from "./invalidate.js";
30
- import { compareRoutes, compileRoute, decodeParams, urlCollisions } from "./route-match.js";
31
+ import { compareRoutes, compileRoute, decodeParams, isClientRoute, urlCollisions } from "./route-match.js";
32
+ export { clientRoute, isClientRoute } from "./route-match.js";
31
33
 
32
34
  const isBrowser = typeof window !== "undefined";
33
35
 
@@ -385,9 +387,11 @@ async function resolveAll(entries, resolve) {
385
387
  * the ordered `nodes` list (page → … → root) so callers can run lifecycle on each.
386
388
  * Each factory owns a reactive scope, disposed with its node on navigation.
387
389
  */
388
- export async function buildRouteNode(match, query = {}, { error = null, loadingShown = false } = {}) {
390
+ export async function buildRouteNode(match, query = {}, { error = null, loadingShown = false, outer = 0 } = {}) {
389
391
  const props = { params: match.params, query };
390
- const folders = layoutFolders(match.route);
392
+ // `outer` leaves out that many outermost layouts: the server rendered them and the
393
+ // client adopts them, building only what is inside (a client route's part).
394
+ const folders = layoutFolders(match.route).slice(outer);
391
395
  // A failed loader replaces the page (its own loader) or a layout and everything in it
392
396
  // (a layout loader: `afwLayoutRoute`) with the error view at that site.
393
397
  const broken = error?.afwLayoutRoute ?? null;
@@ -609,6 +613,10 @@ export async function hydrateRouteNode(match, query, rootEl, { error = null } =
609
613
  // Page + layout chunks download concurrently (see `resolveAll`). Adoptability is
610
614
  // checked after they all land rather than short-circuiting on the page: bailing
611
615
  // early would only skip imports the CSR fallback below is about to need anyway.
616
+ // A client route: the server rendered the layouts above its first client entry and left
617
+ // that region empty. Adopt those layouts and build the rest into the region.
618
+ const split = error ? -1 : clientSplit(match.entry, chain);
619
+ if (split >= 0) return hydrateClientRoute(match, query, rootEl, props, folders.slice(0, split), chain.slice(0, split));
612
620
  const [pageMod, ...layoutMods] = await resolveAll([errorEntry ?? match.entry, ...chain], resolveModule);
613
621
  if (!error) setRouteToc(pageMod);
614
622
  if (!pageMod || typeof pageMod.hydrateAt !== "function") return null;
@@ -644,6 +652,66 @@ export async function hydrateRouteNode(match, query, rootEl, { error = null } =
644
652
  return { nodes };
645
653
  }
646
654
 
655
+ /**
656
+ * Where a route's client part starts: the index of its first client layout (outermost
657
+ * first), the chain's length when only the page renders in the browser, or -1 when the
658
+ * whole route renders on the server.
659
+ */
660
+ export function clientSplit(pageEntry, chain) {
661
+ const layout = chain.findIndex(isClientRoute);
662
+ if (layout >= 0) return layout;
663
+ return isClientRoute(pageEntry) ? chain.length : -1;
664
+ }
665
+
666
+ /**
667
+ * First paint of a client route: adopt the server-rendered layouts (`outerFolders`,
668
+ * outermost first) and build the client part — the first client layout or the page, and
669
+ * everything inside it — into the innermost adopted layout's empty `{children}` region.
670
+ * The build is inserted inside `runBuild`, so its components build rather than adopt.
671
+ */
672
+ async function hydrateClientRoute(match, query, rootEl, props, outerFolders, outerEntries) {
673
+ const [layoutMods, inner] = await Promise.all([
674
+ resolveAll(outerEntries, resolveModule),
675
+ buildRouteNode(match, query, { outer: outerEntries.length }),
676
+ ]);
677
+ if (layoutMods.some((m) => !m || typeof m.hydrateAt !== "function")) {
678
+ for (const n of inner.nodes) runCleanup(n);
679
+ return null;
680
+ }
681
+ const place = (parent, before) => runBuild(() => parent.insertBefore(inner.node, before));
682
+ const nodes = [...inner.nodes];
683
+ if (outerEntries.length === 0) {
684
+ // The page or the root layout is the client part: the server left `#app` empty.
685
+ place(rootEl, null);
686
+ return { nodes, region: inner.region };
687
+ }
688
+ // The innermost adopted layout's children thunk: the cursor stands on its region's end
689
+ // marker, so the built part goes right before it.
690
+ let thunk = (c) => {
691
+ if (!c.node?.parentNode) throw new Error("hydrate: no region for the client part of this route");
692
+ place(c.node.parentNode, c.node);
693
+ return inner.node;
694
+ };
695
+ for (let i = outerEntries.length - 1; i >= 0; i--) {
696
+ const layout = layoutMods[i];
697
+ const innerThunk = thunk;
698
+ const folder = outerFolders[i];
699
+ thunk = (c) => {
700
+ const n = buildScopedView(() => layout.hydrateAt(c, { ...props, children: innerThunk }));
701
+ n.__afwLayoutRoute = folder;
702
+ nodes.push(n);
703
+ return n;
704
+ };
705
+ }
706
+ try {
707
+ thunk(cursor(rootEl));
708
+ } catch (error) {
709
+ for (const node of nodes) runCleanup(node);
710
+ throw error;
711
+ }
712
+ return { nodes, region: inner.region };
713
+ }
714
+
647
715
  /** Resolve a route entry (lazy loader or module namespace) to its module. */
648
716
  export async function resolveModule(entry) {
649
717
  return typeof entry === "function" ? await entry() : entry;
@@ -796,6 +864,8 @@ export async function refreshRouteData() {
796
864
  const data = await fetchRouteData(pathname, window.location.search);
797
865
  if (seq !== navSeq) return; // a navigation since owns the data
798
866
  if (data instanceof RouteRedirect) return followRedirect(data);
867
+ // The data is gone (`notFound()` now): navigate again, which shows the 404 page.
868
+ if (data instanceof RouteNotFound) return navigate(pathname + window.location.search, true);
799
869
  state.data.value = data;
800
870
  } catch (e) {
801
871
  reportError(e, { phase: "data", path: pathname });
@@ -927,9 +997,8 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
927
997
  if (redirected) return;
928
998
  }
929
999
 
930
- const match =
931
- matchRoute(url.pathname) ||
932
- (routes.notFound ? { entry: routes.notFound, params: {}, route: null } : null);
1000
+ const notFoundMatch = () => (routes.notFound ? { entry: routes.notFound, params: {}, route: null } : null);
1001
+ let match = matchRoute(url.pathname) || notFoundMatch();
933
1002
 
934
1003
  // Loader data (docs/DATA.md): resolved before any state write / history push /
935
1004
  // DOM swap, mirroring the guard's "settle before commit" flow. First paint over
@@ -953,6 +1022,12 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
953
1022
  // The server rendered this page's `error.jsx` (its loader failed).
954
1023
  dataError = routeErrorFrom(data);
955
1024
  if (dataError) data = undefined;
1025
+ // The server answered with the 404 page (the loader called `notFound()`): adopt
1026
+ // that markup, inside the root layout, not this route's layout chain.
1027
+ if (isNotFoundPayload(data)) {
1028
+ data = undefined;
1029
+ match = notFoundMatch();
1030
+ }
956
1031
  } else {
957
1032
  try {
958
1033
  const warmed = takePrefetched(url.pathname + url.search);
@@ -963,6 +1038,12 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
963
1038
  }
964
1039
  if (seq !== navSeq) return; // a newer navigation superseded this one
965
1040
  if (data instanceof RouteRedirect) return followRedirect(data);
1041
+ // The loader called `notFound()`: show the 404 page, as the server does for a
1042
+ // full page load of this URL, instead of the page with no data.
1043
+ if (data instanceof RouteNotFound) {
1044
+ data = undefined;
1045
+ match = notFoundMatch();
1046
+ }
966
1047
  }
967
1048
  }
968
1049
 
@@ -1010,6 +1091,10 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
1010
1091
  clearChunkReloadFlag();
1011
1092
  return;
1012
1093
  }
1094
+ // Not a mismatch: the page or a layout has no adopt factory (the compiler could
1095
+ // not emit one), so the server HTML is rebuilt. Say so in development, where the
1096
+ // compiler's warning may have scrolled away.
1097
+ if (DEV && !dataError) console.warn(`[afw:hydrate] ${url.pathname}: the page or one of its layouts cannot adopt the server-rendered HTML, so it is rebuilt on the client. See the compiler's warning for that file.`);
1013
1098
  } catch (e) {
1014
1099
  reportError(e, { phase: "hydrate", path: url.pathname });
1015
1100
  // fall through to a clean CSR build below
@@ -2,12 +2,53 @@
2
2
  // `*.server` module with stubs made here: `serverFunction("/todos/__fn/<id>", "query")`
3
3
  // is an async function with the server function's signature that calls its endpoint.
4
4
 
5
- import { CONTENT_TYPE, decode, encode } from "../core/fn-codec.js";
6
- import { trackServerCall } from "./invalidate.js";
5
+ import { CONTENT_TYPE, LIVE_HEADER, MAX_REFRESH, REFRESH_HEADER, decode, encode } from "../core/fn-codec.js";
6
+ import { liveCalls, trackServerCall } from "./invalidate.js";
7
+ import { applyRefresh } from "./mutate.js";
8
+ import { callKey, fetchShared } from "./query-cache.js";
7
9
 
8
10
  // Queries go by GET while the encoded arguments fit comfortably in a URL.
9
11
  const MAX_GET_ARGS = 2000;
10
12
 
13
+ // A query whose request never reached the server (`fetch` itself rejected: offline, a
14
+ // dropped connection) is retried after these delays. An HTTP error answer is the
15
+ // server's, and actions are never retried: their request may have been applied.
16
+ let retryDelays = [300, 1000];
17
+
18
+ /** Replace the query retry delays (tests only). */
19
+ export function __setRetryDelays(delays) {
20
+ retryDelays = delays;
21
+ }
22
+
23
+ /** Wait `ms`, or reject as soon as `signal` aborts. */
24
+ function wait(ms, signal) {
25
+ return new Promise((resolve, reject) => {
26
+ if (signal?.aborted) return reject(signal.reason);
27
+ const timer = setTimeout(() => {
28
+ signal?.removeEventListener("abort", stop);
29
+ resolve();
30
+ }, ms);
31
+ function stop() {
32
+ clearTimeout(timer);
33
+ reject(signal.reason);
34
+ }
35
+ signal?.addEventListener("abort", stop, { once: true });
36
+ });
37
+ }
38
+
39
+ /** `fetch`, retried on network failure for queries. */
40
+ async function request(url, init, retry) {
41
+ for (let attempt = 0; ; attempt++) {
42
+ try {
43
+ return await fetch(url, init);
44
+ } catch (error) {
45
+ const aborted = init.signal?.aborted || error?.name === "AbortError";
46
+ if (!retry || aborted || attempt >= retryDelays.length) throw error;
47
+ await wait(retryDelays[attempt], init.signal);
48
+ }
49
+ }
50
+ }
51
+
11
52
  /** A failed server function call: `status`, and `issues` when the input was invalid. */
12
53
  export class ServerFunctionError extends Error {
13
54
  constructor(message, { status, issues, redirected = false } = {}) {
@@ -23,20 +64,49 @@ export class ServerFunctionError extends Error {
23
64
  * A stub for the server function at `endpoint`. `kind` is `"query"` (GET, or POST for
24
65
  * large arguments) or `"action"` (POST). The stub takes the input and an optional
25
66
  * `{ signal }` to abort the call.
67
+ *
68
+ * Query calls go through the query cache: identical calls in flight share one request,
69
+ * and a call made by a starting resource may answer from a fresh entry (`staleTime`).
70
+ * Actions always make their own request.
26
71
  */
27
72
  export function serverFunction(endpoint, kind) {
28
- async function call(input, { signal } = {}) {
29
- trackServerCall(endpoint); // a resource starting this call depends on it (invalidate)
73
+ function call(input, { signal } = {}) {
74
+ if (kind !== "query") {
75
+ trackServerCall(endpoint); // a resource starting this call depends on it (invalidate)
76
+ return act(input, signal);
77
+ }
78
+ let key;
79
+ try {
80
+ key = callKey(endpoint, input);
81
+ } catch (error) {
82
+ return Promise.reject(error); // an input the codec refuses (a function, a symbol)
83
+ }
84
+ const staleTime = trackServerCall(endpoint, key) ?? 0;
85
+ return fetchShared(key, (shared) => send(input, shared).then((r) => r.value), { signal, staleTime, call: [endpoint, input] });
86
+ }
87
+ // An action sends the calls the page shows, so its `refresh()` can answer them in the
88
+ // response; the fresh data is in the cache before the call resolves.
89
+ async function act(input, signal) {
90
+ const live = liveCalls(MAX_REFRESH);
91
+ const { value, refreshed } = live.length
92
+ ? await send({ input, live }, signal, { [LIVE_HEADER]: "1" })
93
+ : await send(input, signal);
94
+ if (!refreshed) return value;
95
+ await applyRefresh(value.refresh);
96
+ return value.result;
97
+ }
98
+ async function send(input, signal, extra) {
30
99
  const args = encode(input);
31
- const init = { signal, credentials: "same-origin", redirect: "manual", headers: { accept: CONTENT_TYPE } };
100
+ const init = { signal, credentials: "same-origin", redirect: "manual", headers: { accept: CONTENT_TYPE, ...extra } };
101
+ const retry = kind === "query";
32
102
  const response = kind === "query" && args.length <= MAX_GET_ARGS
33
- ? await fetch(`${endpoint}?a=${encodeURIComponent(args)}`, init)
34
- : await fetch(endpoint, { ...init, method: "POST", headers: { ...init.headers, "content-type": CONTENT_TYPE }, body: args });
103
+ ? await request(`${endpoint}?a=${encodeURIComponent(args)}`, init, retry)
104
+ : await request(endpoint, { ...init, method: "POST", headers: { ...init.headers, "content-type": CONTENT_TYPE }, body: args }, retry);
35
105
  // A redirect (an auth guard sending to a login page, say) is not data: the caller decides.
36
106
  if (response.type === "opaqueredirect" || (response.status >= 300 && response.status < 400)) {
37
107
  throw new ServerFunctionError("The server redirected the call", { status: response.status || 302, redirected: true });
38
108
  }
39
- if (response.ok) return decode(await response.text());
109
+ if (response.ok) return { value: decode(await response.text()), refreshed: response.headers.get(REFRESH_HEADER) === "1" };
40
110
  let body = null;
41
111
  try {
42
112
  body = await response.json();
package/server/index.d.ts CHANGED
@@ -7,6 +7,7 @@ export * from "./cookies.js";
7
7
  export * from "../core/signals.js";
8
8
  export * from "../core/reactive.js";
9
9
  export * from "../core/errors.js";
10
+ export * from "../core/route.js";
10
11
  export * from "../core/context.js";
11
12
  export * from "../runtime/lifecycle.js";
12
13
  export { resource } from "../runtime/resource.js";
@@ -85,6 +86,8 @@ export function renderRoute(
85
86
  options?: { data?: unknown },
86
87
  ): Promise<RenderResult | null>;
87
88
  export function renderToString(pathname: string, search?: string): Promise<string>;
89
+ /** Register `_config.js` `paths` functions by route pattern (used by the generated server module). */
90
+ export function registerStaticPaths(map: Record<string, () => unknown>): void;
88
91
  export function collectRoutePaths(): Promise<{
89
92
  paths: Array<{ path: string; params: Record<string, unknown>; route: string }>;
90
93
  skipped: string[];
@@ -171,6 +174,10 @@ export function attr(name: string, value: unknown): string;
171
174
  export function ssgText(v: unknown): string;
172
175
  export function ssgList<T>(arr: T[], fn: (item: T, index: number) => string): string;
173
176
  export function ssgComponent(tag: string, props?: Record<string, unknown>, children?: unknown): string;
177
+ /** Render `children()` with `context` provided as `value` (a server-rendered `<ContextProvider>`). */
178
+ export function ssgProvide(context: unknown, value: unknown, children: () => string): string;
179
+ /** `$context(context)` on the server: the nearest provided value, else the context's default. */
180
+ export function ssgContext<T>(context: { fallback: { value: T } }): { value: T };
174
181
 
175
182
  // ── Server functions (server-functions.js, docs/SERVER_FUNCTIONS.md) ───────────
176
183
  /** A Standard Schema (https://standardschema.dev): zod, valibot, arktype… */
@@ -196,10 +203,21 @@ export interface ServerFunctionContext {
196
203
  locals: Record<string, unknown>;
197
204
  env?: unknown;
198
205
  ctx?: unknown;
206
+ /**
207
+ * In an action called from the browser: re-run these queries after the action and send
208
+ * their fresh data with its response (single-flight updates). A query alone refreshes
209
+ * every input the page shows; a value after it, that one input:
210
+ * `refresh(listTodos, getTodo, { id })`. Queries outside the action's folder (or its
211
+ * parents) are refetched by the browser instead. A no-op elsewhere.
212
+ */
213
+ refresh: (...targets: unknown[]) => void;
199
214
  }
200
215
 
201
- /** A server function: called with its input (and, from server code, a context). */
202
- export type ServerFunction<Input, Output> = (input: Input, context?: Partial<ServerFunctionContext>) => Promise<Awaited<Output>>;
216
+ /**
217
+ * A server function: called with its input, and a context from server code. In the
218
+ * browser the stub takes `{ signal }` to abort the call (and `resource()` passes one).
219
+ */
220
+ export type ServerFunction<Input, Output> = (input: Input, context?: Partial<ServerFunctionContext> & { signal?: AbortSignal }) => Promise<Awaited<Output>>;
203
221
 
204
222
  /** A read: idempotent, callable with GET or POST. */
205
223
  export function query<Output, Input = void>(fn: (input: Input, context: ServerFunctionContext) => Output): ServerFunction<Input, Output>;
@@ -219,3 +237,8 @@ export function createServerFunctions(
219
237
  /** Limits on decoded input: body size (default 1 MiB) and nesting depth (default 64). */
220
238
  options?: { maxBodyBytes?: number; maxDepth?: number },
221
239
  ): { size: number; handle(request: Request, context?: { locals?: Record<string, unknown>; env?: unknown; ctx?: unknown }): Promise<Response | null> };
240
+
241
+ /** Mark a route-table entry as rendered in the browser (see the client `clientRoute`). */
242
+ export function clientRoute(load?: () => unknown): () => unknown;
243
+ /** Whether a route-table entry renders in the browser. */
244
+ export function isClientRoute(entry: unknown): boolean;
package/server/index.js CHANGED
@@ -6,6 +6,7 @@ export * from "./ssg-runtime.js";
6
6
  export * from "../core/signals.js";
7
7
  export * from "../core/reactive.js";
8
8
  export * from "../core/errors.js";
9
+ export * from "../core/route.js";
9
10
  export * from "../core/context.js";
10
11
  export * from "../runtime/lifecycle.js";
11
12
  export { resource } from "../runtime/resource.js";
@@ -22,7 +23,7 @@ export * from "./render.js";
22
23
  export {
23
24
  registerRoutes, router, matchRoute, configureI18n, i18nLocales,
24
25
  resolveLocale, localizePath, shouldInterceptNav,
25
- setLocale, setRouteState, setRouteToc, navigate, prefetch,
26
+ setLocale, setRouteState, setRouteToc, navigate, prefetch, clientRoute, isClientRoute,
26
27
  } from "../runtime/router.js";
27
28
  export { isHydrating } from "../runtime/hydrate.js";
28
29
  export { emit } from "../runtime/events.js";
package/server/render.js CHANGED
@@ -10,7 +10,9 @@
10
10
  import { DEV } from "../core/dev.js";
11
11
  import { urlOf } from "../runtime/route-match.js";
12
12
  import { routeErrorPayload } from "../runtime/route-data.js";
13
+ import { isClientRoute } from "../runtime/route-match.js";
13
14
  import {
15
+ clientSplit,
14
16
  layoutChain,
15
17
  layoutFolders,
16
18
  layoutWraps,
@@ -86,8 +88,13 @@ async function renderInContext(pathname, params, search, data, failure) {
86
88
  const chain = broken
87
89
  ? layoutFolders(match.route).filter((f) => f !== broken && layoutWraps(f, broken)).map((f) => routes.layouts[f])
88
90
  : layoutChain(match.route);
91
+ // A client route renders the layouts above its first client entry; that region stays
92
+ // empty for the browser to build (`hydrateClientRoute`). Client entries have no module.
93
+ const split = error ? -1 : clientSplit(match.entry, chain);
94
+ const serverChain = split >= 0 ? chain.slice(0, split) : chain;
89
95
  const [pageModule, ...layoutModules] = await Promise.all(
90
- [match.entry, ...chain].map(async entry => {
96
+ [split >= 0 ? null : match.entry, ...serverChain].map(async entry => {
97
+ if (!entry) return null;
91
98
  const module = await resolveModule(entry);
92
99
  // A loader can return a bare factory. Keep it distinguishable from a
93
100
  // loader when these resolved entries are passed to metadata resolution.
@@ -103,7 +110,7 @@ async function renderInContext(pathname, params, search, data, failure) {
103
110
  let html, hydration;
104
111
  beginHydrationCollect();
105
112
  try {
106
- html = page(props);
113
+ html = split >= 0 ? "" : page(props);
107
114
  // Wrap with layouts, most-specific inward to root outermost.
108
115
  for (let i = layouts.length - 1; i >= 0; i--) {
109
116
  html = layouts[i]({ ...props, children: html });
@@ -114,7 +121,7 @@ async function renderInContext(pathname, params, search, data, failure) {
114
121
 
115
122
  const metadata = await resolveMetadata({
116
123
  route: match.route,
117
- entry: pageModule,
124
+ entry: pageModule ?? {},
118
125
  layouts: layoutModules,
119
126
  params: match.params,
120
127
  query,
@@ -126,7 +133,7 @@ async function renderInContext(pathname, params, search, data, failure) {
126
133
  const dataJson = routeErrorPayload(error);
127
134
  return { html, metadata, status: error.status, hydration, route: match.route, dataJson, error };
128
135
  }
129
- return { html, metadata, status: real ? 200 : 404, hydration, route: match.route };
136
+ return { html, metadata, status: real ? 200 : 404, hydration, route: match.route, ...(split >= 0 ? { client: true } : {}) };
130
137
  }
131
138
 
132
139
  /** Back-compat / convenience: render just the `#app` markup for `pathname`. */
@@ -180,6 +187,19 @@ function fillRoute(route, params) {
180
187
  * (the chunk manifest behind `<link rel="modulepreload">`). Dynamic routes without
181
188
  * `getStaticPaths` are collected as `skipped`.
182
189
  */
190
+ /** Each static route's `paths` from its folder's `_config.js`, keyed by route pattern. */
191
+ const staticPaths = new Map();
192
+
193
+ /**
194
+ * Register the `paths` functions of `_config.js` files (route pattern → function); the
195
+ * generated server module calls this. They list a dynamic static route's pages, like a
196
+ * page's `getStaticPaths`, which they take precedence over.
197
+ */
198
+ export function registerStaticPaths(map) {
199
+ staticPaths.clear();
200
+ for (const [route, fn] of Object.entries(map ?? {})) if (typeof fn === "function") staticPaths.set(route, fn);
201
+ }
202
+
183
203
  export async function collectRoutePaths() {
184
204
  const paths = [];
185
205
  const skipped = [];
@@ -195,9 +215,14 @@ export async function collectRoutePaths() {
195
215
  add(urlOf(route), {}, route);
196
216
  continue;
197
217
  }
198
- const ns = await resolveModule(routes.pages[route]);
199
- const getStaticPaths =
200
- ns && (ns.getStaticPaths || (ns.default && ns.default.getStaticPaths));
218
+ // A dynamic page that renders in the browser has no module here to list its pages.
219
+ if (isClientRoute(routes.pages[route]) && !staticPaths.has(route)) {
220
+ skipped.push(route);
221
+ continue;
222
+ }
223
+ const ns = staticPaths.has(route) ? null : await resolveModule(routes.pages[route]);
224
+ const getStaticPaths = staticPaths.get(route) ??
225
+ (ns && (ns.getStaticPaths || (ns.default && ns.default.getStaticPaths)));
201
226
  if (typeof getStaticPaths === "function") {
202
227
  const entries = await getStaticPaths();
203
228
  if (!Array.isArray(entries)) throw new Error(`getStaticPaths for ${route} must return an array.`);
@@ -8,12 +8,29 @@
8
8
  // The build gives each function an endpoint under its folder (`/todos/__fn/<id>`), so
9
9
  // that folder's `_middleware` guards it like a page. `createServerFunctions` turns the
10
10
  // build's `{ endpoint: fn }` map into a handler for those requests.
11
+ //
12
+ // Single-flight updates: an action names the queries it changed with `refresh()` from
13
+ // its context, and their fresh results go back with its own response:
14
+ //
15
+ // export const addTodo = action(schema, async (input, { refresh }) => {
16
+ // await db.insert(input);
17
+ // refresh(listTodos); // every input of listTodos the page shows
18
+ // refresh(getTodo, { id: 1 }); // or one input
19
+ // });
20
+ //
21
+ // The browser sends the inputs of the queries it shows (`x-afw-live`, at most
22
+ // MAX_REFRESH); the server re-runs the named ones after the action and returns them.
23
+ // Only queries in the action's folder or a parent folder run there, since their
24
+ // middleware already ran for this request; others go back as stale and the browser
25
+ // refetches them through their own middleware.
11
26
 
12
- import { CONTENT_TYPE, MAX_DEPTH, SerializeError, decode, encode } from "../core/fn-codec.js";
27
+ import { CONTENT_TYPE, LIVE_HEADER, MAX_DEPTH, MAX_REFRESH, REFRESH_HEADER, SerializeError, decode, encode } from "../core/fn-codec.js";
13
28
  import { isNotFound } from "./loader.js";
14
29
 
15
30
  const MARK = Symbol.for("afw.serverFunction");
16
31
 
32
+ const noRefresh = () => {};
33
+
17
34
  /** Thrown to the caller when the input does not match the function's schema. */
18
35
  export class ValidationError extends Error {
19
36
  constructor(issues) {
@@ -41,7 +58,9 @@ function define(kind, args) {
41
58
  if (typeof handler !== "function") throw new TypeError(`${kind}(): the last argument must be a function`);
42
59
  // Called directly from server code (a loader, an API route, another function): run it
43
60
  // with the given context, input validated the same way as over HTTP.
44
- const fn = async (input, context = {}) => handler(await validate(schema, input), context);
61
+ // `refresh` is a no-op outside an HTTP action call, so a handler can always call it.
62
+ const fn = async (input, context = {}) =>
63
+ handler(await validate(schema, input), typeof context.refresh === "function" ? context : { ...context, refresh: noRefresh });
45
64
  Object.defineProperty(fn, MARK, { value: { kind, schema, handler } });
46
65
  return fn;
47
66
  }
@@ -88,10 +107,58 @@ function crossSite(request, url) {
88
107
  export function createServerFunctions(endpoints = {}, { maxBodyBytes = 1024 * 1024, maxDepth = MAX_DEPTH } = {}) {
89
108
  const limits = { maxLength: maxBodyBytes, maxDepth };
90
109
  const table = new Map();
110
+ const paths = new Map(); // fn → endpoint, for `refresh(listTodos)`
91
111
  for (const [path, fn] of Object.entries(endpoints)) {
92
112
  const kind = serverFunctionKind(fn);
93
113
  if (!kind) throw new TypeError(`${path}: not a query() or action()`);
94
114
  table.set(path, { kind, fn });
115
+ paths.set(fn, path);
116
+ }
117
+
118
+ /** `refresh()`'s arguments as targets: a query, optionally followed by one input. */
119
+ function targetsOf(args, into) {
120
+ for (let i = 0; i < args.length; i++) {
121
+ const path = paths.get(args[i]);
122
+ if (!path || table.get(path).kind !== "query") {
123
+ throw new TypeError("refresh() takes queries exported from a .server module, each optionally followed by its input");
124
+ }
125
+ if (i + 1 < args.length && typeof args[i + 1] !== "function") into.push({ path, inputs: [args[++i]] });
126
+ else into.push({ path, inputs: null });
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Re-run the queries an action refreshed: `{ fresh: [[endpoint, input, data]],
132
+ * stale: [[endpoint, input?]], endpoints }`. `live` holds the inputs the page shows;
133
+ * `endpoints` are the queries refreshed without an input (all their calls changed).
134
+ */
135
+ async function runRefresh(action, targets, live, ctx) {
136
+ const folder = folderOf(action);
137
+ const fresh = [];
138
+ const stale = [];
139
+ const endpoints = new Set();
140
+ const runs = [];
141
+ for (const { path, inputs } of targets) {
142
+ // A query refreshed without an input covers all of its calls; with one, only that.
143
+ if (!inputs) endpoints.add(path);
144
+ if (!inScope(folder, folderOf(path))) {
145
+ // Its own middleware must run: the browser refetches it.
146
+ if (inputs) for (const input of inputs) stale.push([path, input]);
147
+ else stale.push([path]);
148
+ continue;
149
+ }
150
+ for (const input of inputs ?? live.filter(([p]) => p === path).map(([, i]) => i)) {
151
+ if (runs.length >= MAX_REFRESH) stale.push([path, input]);
152
+ else runs.push({ path, input });
153
+ }
154
+ }
155
+ const settled = await Promise.allSettled(runs.map(({ path, input }) => table.get(path).fn(input, { ...ctx, refresh: noRefresh })));
156
+ settled.forEach((outcome, i) => {
157
+ const { path, input } = runs[i];
158
+ if (outcome.status === "fulfilled") fresh.push([path, input, outcome.value]);
159
+ else stale.push([path, input]); // the browser's own call reports the error
160
+ });
161
+ return { fresh, stale, endpoints: [...endpoints] };
95
162
  }
96
163
 
97
164
  async function handle(request, context = {}) {
@@ -104,6 +171,7 @@ export function createServerFunctions(endpoints = {}, { maxBodyBytes = 1024 * 10
104
171
  if (crossSite(request, url)) return json(403, { error: { message: "Cross-site request refused" } });
105
172
 
106
173
  let input;
174
+ let live = [];
107
175
  try {
108
176
  if (method === "GET") {
109
177
  input = decode(url.searchParams.get("a") ?? "", limits);
@@ -112,6 +180,10 @@ export function createServerFunctions(endpoints = {}, { maxBodyBytes = 1024 * 10
112
180
  // Forms and plain-text posts can be sent cross-site without a preflight; JSON cannot.
113
181
  if (!type.startsWith(CONTENT_TYPE)) return json(415, { error: { message: `Expected ${CONTENT_TYPE}` } });
114
182
  input = decode(await request.text(), limits);
183
+ if (entry.kind === "action" && request.headers.get(LIVE_HEADER) === "1") {
184
+ if (!isEnvelope(input)) return json(400, { error: { message: "Malformed request body" } });
185
+ ({ input, live } = input);
186
+ }
115
187
  }
116
188
  } catch (error) {
117
189
  if (error instanceof SerializeError && error.code === "INPUT_TOO_LARGE") {
@@ -121,10 +193,17 @@ export function createServerFunctions(endpoints = {}, { maxBodyBytes = 1024 * 10
121
193
  }
122
194
 
123
195
  const ctx = { request, url, locals: context.locals ?? {}, env: context.env, ctx: context.ctx };
196
+ const targets = [];
197
+ if (entry.kind === "action") ctx.refresh = (...args) => targetsOf(args, targets);
124
198
  try {
125
199
  const result = await entry.fn(input, ctx);
126
- // A result the codec refuses (a class instance, a function) is a server bug: 500.
127
- return new Response(encode(result), { status: 200, headers: { "content-type": CONTENT_TYPE, "cache-control": "no-store" } });
200
+ const headers = { "content-type": CONTENT_TYPE, "cache-control": "no-store" };
201
+ if (targets.length === 0) {
202
+ // A result the codec refuses (a class instance, a function) is a server bug: 500.
203
+ return new Response(encode(result), { status: 200, headers });
204
+ }
205
+ const refresh = await runRefresh(url.pathname, targets, live, ctx);
206
+ return new Response(encode({ result, refresh }), { status: 200, headers: { ...headers, [REFRESH_HEADER]: "1" } });
128
207
  } catch (error) {
129
208
  if (error instanceof Response) return error; // a redirect or custom status from the function
130
209
  if (error instanceof ValidationError) return json(400, { error: { message: error.message, issues: error.issues } });
@@ -136,3 +215,21 @@ export function createServerFunctions(endpoints = {}, { maxBodyBytes = 1024 * 10
136
215
 
137
216
  return { size: table.size, handle };
138
217
  }
218
+
219
+ /** The folder of an endpoint: `/todos/__fn/x` → `/todos`, `/__fn/x` → `""`. */
220
+ function folderOf(endpoint) {
221
+ const i = endpoint.lastIndexOf("/__fn/");
222
+ return i <= 0 ? "" : endpoint.slice(0, i);
223
+ }
224
+
225
+ /** Is `query` in `action`'s folder or above it (so its middleware ran for the action)? */
226
+ function inScope(action, query) {
227
+ return query === "" || action === query || action.startsWith(`${query}/`);
228
+ }
229
+
230
+ /** An action body with the page's shown queries: `{ input, live: [[endpoint, input]] }`. */
231
+ function isEnvelope(body) {
232
+ if (!body || typeof body !== "object" || !("input" in body) || !Array.isArray(body.live)) return false;
233
+ if (body.live.length > MAX_REFRESH) return false;
234
+ return body.live.every((call) => Array.isArray(call) && call.length === 2 && typeof call[0] === "string");
235
+ }
@@ -94,6 +94,10 @@ function jsonSafeProps(props) {
94
94
  } catch {
95
95
  return null; // cyclic / non-serializable → client falls back to attributes/defaults
96
96
  }
97
+ // Function props (callbacks, render props) are named instead: the client component
98
+ // waits for its parent to set them before it adopts (`awaitHydrationProps`).
99
+ const fns = Object.keys(props).filter((key) => typeof props[key] === "function");
100
+ if (fns.length) safe = { ...(safe && typeof safe === "object" ? safe : {}), __afwFn: fns };
97
101
  if (!safe || typeof safe !== "object" || Object.keys(safe).length === 0) return null;
98
102
  return safe;
99
103
  }
@@ -267,6 +271,8 @@ export function ssgList(arr, fn) {
267
271
  */
268
272
  export function ssgComponent(tag, props, children) {
269
273
  const render = registry[tag];
274
+ // A `<ContextProvider>`'s children arrive as a thunk: render them with its value in scope.
275
+ if (typeof children === "function") children = ssgProvide(props?.context, props?.value, children);
270
276
  let inner;
271
277
  try {
272
278
  inner = render ? render(props || {}, children ?? "") : (children ?? "");
@@ -294,4 +300,30 @@ export function ssgComponent(tag, props, children) {
294
300
  return `<${tag}${attrs}>${inner}</${tag}>`;
295
301
  }
296
302
 
303
+ /*
304
+ * Context on the server. A page renders synchronously to a string, so the providers
305
+ * enclosing the component being rendered are a stack: `<ContextProvider>` pushes while
306
+ * its children render, and `$context` reads the nearest entry for its context.
307
+ */
308
+ const providers = [];
309
+
310
+ /** Render `children()` with `context` provided as `value`. */
311
+ export function ssgProvide(context, value, children) {
312
+ if (!context) return children();
313
+ providers.push([context, value]);
314
+ try {
315
+ return children();
316
+ } finally {
317
+ providers.pop();
318
+ }
319
+ }
320
+
321
+ /** `$context(context)` on the server: the nearest provided value, else the default. */
322
+ export function ssgContext(context) {
323
+ for (let i = providers.length - 1; i >= 0; i--) {
324
+ if (providers[i][0] === context) return { value: providers[i][1] };
325
+ }
326
+ return context.fallback;
327
+ }
328
+
297
329
  export { VOID };