@opentf/afw 0.38.0 → 0.39.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.
@@ -0,0 +1,33 @@
1
+ /** How a route's pages render. */
2
+ export type RenderStrategy =
3
+ /** Rendered on the server for each request; the browser adopts the HTML. */
4
+ | "server"
5
+ /** Built to HTML at build time; the browser adopts it. */
6
+ | "static"
7
+ /** Rendered in the browser. The page module never enters the server bundle. */
8
+ | "client";
9
+
10
+ /** One page's dynamic params: `{ slug: "hello" }`, or an array for a catch-all segment. */
11
+ export type StaticParams = Record<string, string | number | Array<string | number>>;
12
+
13
+ /** A folder's `_config.js`: applies to its pages and every folder below; the nearest one wins. */
14
+ export interface RouteConfig {
15
+ /**
16
+ * How the pages render. Must be a string literal: the build reads it without running
17
+ * the file, since it decides what each bundle contains. Inherited when omitted.
18
+ */
19
+ render?: RenderStrategy;
20
+ /**
21
+ * `client` routes only: `"server"` (the default) runs the route's loaders on the server
22
+ * and sends their data with the page; `"client"` leaves fetching to the page.
23
+ */
24
+ data?: "server" | "client";
25
+ /**
26
+ * `static` dynamic routes only: the params of each page to build. Runs at build time.
27
+ * A matching URL that is not listed renders when it is requested.
28
+ */
29
+ paths?: () => StaticParams[] | Promise<StaticParams[]>;
30
+ }
31
+
32
+ /** Declare a folder's render policy: `export default defineRoute({ render: "static" })`. */
33
+ export function defineRoute<T extends RouteConfig>(config: T & Record<Exclude<keyof T, keyof RouteConfig>, never>): T;
package/core/route.js ADDED
@@ -0,0 +1,12 @@
1
+ // `defineRoute` — the default export of a folder's `_config.js`, which sets how the
2
+ // pages in that folder and below it render. It returns its argument: the build reads
3
+ // `render` and `data` from the source (they must be string literals) and runs `paths`
4
+ // at build time inside the server bundle. Neutral core: no runtime or Node imports.
5
+
6
+ /**
7
+ * @param {import("./route.d.ts").RouteConfig} config
8
+ * @returns {import("./route.d.ts").RouteConfig}
9
+ */
10
+ export function defineRoute(config) {
11
+ return config;
12
+ }
package/index.d.ts CHANGED
@@ -2,5 +2,6 @@
2
2
  export * from "./core/signals.js";
3
3
  export * from "./core/reactive.js";
4
4
  export * from "./core/errors.js";
5
+ export * from "./core/route.js";
5
6
  export * from "./runtime/index.js";
6
7
  export { default as Link } from "./components/Link.jsx";
package/index.js CHANGED
@@ -3,6 +3,7 @@
3
3
  export * from "./core/signals.js";
4
4
  export * from "./core/reactive.js";
5
5
  export * from "./core/errors.js";
6
+ export * from "./core/route.js";
6
7
  export * from "./runtime/index.js";
7
8
  // `Link` is shipped as JSX source and compiled by the consuming app's pipeline
8
9
  // (the `.jsx` lands in the module graph and afwc transforms it). Its compiled
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opentf/afw",
3
- "version": "0.38.0",
3
+ "version": "0.39.0",
4
4
  "description": "The AFW runtime: signals and zero-VDOM DOM bindings, with routing and server rendering.",
5
5
  "type": "module",
6
6
  "scripts": {
package/runtime/hmr.js CHANGED
@@ -80,6 +80,8 @@ export function registerHotRoute(hot, factory, shape = "", exports = "", data =
80
80
  };
81
81
  return entry;
82
82
  });
83
+ // For `registerHotHydrate`: the adopt factory marks its view with this record's `view`.
84
+ hot.data.afwRoute = record;
83
85
  const updated = record.factory !== factory || record.shape !== shape;
84
86
  record.factory = factory;
85
87
  record.shape = shape;
@@ -93,6 +95,33 @@ export function registerHotRoute(hot, factory, shape = "", exports = "", data =
93
95
  return record.view;
94
96
  }
95
97
 
98
+ /**
99
+ * A development page's `hydrateAt`, registered for the route refresh. The adopt walk runs
100
+ * inside fresh refresh slots (its `$state` reads `hotRouteState`), and the adopted view is
101
+ * marked like a view `registerHotRoute` built, so an edit after hydration refreshes it with
102
+ * its state kept. `shape` is the same state shape `registerHotRoute` was given.
103
+ */
104
+ export function registerHotHydrate(hot, adopt, shape = "") {
105
+ if (!hot) return adopt;
106
+ return (cursor, ...args) => {
107
+ const slots = new Map();
108
+ const outer = routeSlots;
109
+ routeSlots = slots;
110
+ let node;
111
+ try {
112
+ node = adopt(cursor, ...args);
113
+ } finally {
114
+ routeSlots = outer;
115
+ }
116
+ const record = hot.data.afwRoute;
117
+ if (record && node) {
118
+ node.__afwHotFactory = record.view;
119
+ node.__afwHotSlots = { shape, slots };
120
+ }
121
+ return node;
122
+ };
123
+ }
124
+
96
125
  export function hotState(host, key, create) {
97
126
  // A new element built by a refresh picks up the state of the one it replaces.
98
127
  if (!host.__afwHotCarried) {
@@ -164,3 +164,21 @@ export function decodeParams(route, groups, { strict = false } = {}) {
164
164
  }
165
165
  return params;
166
166
  }
167
+
168
+ /**
169
+ * Mark a route-table entry (page, layout, loading or error file) as rendered in the
170
+ * browser — its folder's `_config.js` says `render: "client"`. The generated route tables
171
+ * wrap these entries: the client's keeps the lazy import, the server's has none (the module
172
+ * never enters the server bundle). A server render stops at the first such entry and
173
+ * leaves its region empty; the client builds it there.
174
+ */
175
+ export function clientRoute(load) {
176
+ const entry = load ?? (() => {
177
+ throw new Error("This route renders in the browser: its module is not part of the server bundle.");
178
+ });
179
+ entry.__afwClient = true;
180
+ return entry;
181
+ }
182
+
183
+ /** Whether a route-table entry renders in the browser (see {@link clientRoute}). */
184
+ export const isClientRoute = (entry) => entry?.__afwClient === true;
@@ -183,3 +183,12 @@ export namespace router {
183
183
  function push(path: any): Promise<void>;
184
184
  function replace(path: any): Promise<void>;
185
185
  }
186
+
187
+ /**
188
+ * Mark a route-table entry as rendered in the browser (its folder's `_config.js` says
189
+ * `render: "client"`). Used by the generated route tables; `load` is the client's lazy
190
+ * import, omitted on the server, whose bundle never includes the module.
191
+ */
192
+ export function clientRoute<T extends (() => unknown) | undefined>(load?: T): T extends () => unknown ? T : () => never;
193
+ /** Whether a route-table entry renders in the browser (see `clientRoute`). */
194
+ export function isClientRoute(entry: unknown): boolean;
package/runtime/router.js CHANGED
@@ -14,12 +14,13 @@
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
26
  import { RouteRedirect, fetchRouteData, readInlineRouteData, routeErrorFrom } from "./route-data.js";
@@ -27,7 +28,8 @@ 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;
@@ -1010,6 +1078,10 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
1010
1078
  clearChunkReloadFlag();
1011
1079
  return;
1012
1080
  }
1081
+ // Not a mismatch: the page or a layout has no adopt factory (the compiler could
1082
+ // not emit one), so the server HTML is rebuilt. Say so in development, where the
1083
+ // compiler's warning may have scrolled away.
1084
+ 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
1085
  } catch (e) {
1014
1086
  reportError(e, { phase: "hydrate", path: url.pathname });
1015
1087
  // fall through to a clean CSR build below
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[];
@@ -219,3 +222,8 @@ export function createServerFunctions(
219
222
  /** Limits on decoded input: body size (default 1 MiB) and nesting depth (default 64). */
220
223
  options?: { maxBodyBytes?: number; maxDepth?: number },
221
224
  ): { size: number; handle(request: Request, context?: { locals?: Record<string, unknown>; env?: unknown; ctx?: unknown }): Promise<Response | null> };
225
+
226
+ /** Mark a route-table entry as rendered in the browser (see the client `clientRoute`). */
227
+ export function clientRoute(load?: () => unknown): () => unknown;
228
+ /** Whether a route-table entry renders in the browser. */
229
+ 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.`);