@opentf/afw-build 0.4.0 → 0.6.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/compile.js CHANGED
@@ -2,33 +2,53 @@
2
2
  // the build at hand, compile through `afwc`, and turn a failure into either a thrown
3
3
  // diagnostic or a visible stub module.
4
4
 
5
- /** Rendering modes a project chooses from. */
6
- export const MODES = new Set(["spa", "ssg", "ssr"]);
5
+ /**
6
+ * How an app renders overall, from its routes' policies: `client` when every page renders
7
+ * in the browser, `static` when none renders per request but some are built, `server`
8
+ * when any renders per request. It decides the browser build's compiler target.
9
+ */
10
+ export const APP_RENDERS = new Set(["client", "static", "server"]);
7
11
  /** Compiler backends: live DOM, HTML-string renderers, or the hydrating dual module. */
8
12
  export const TARGETS = new Set(["csr", "ssg", "hydrate"]);
9
13
 
10
14
  /** Source modules the compiler owns. */
11
15
  export const SOURCE_FILTER = /\.(mdx|md|[jt]sx)$/;
12
16
 
13
- /** Throw on an unknown mode or target, before any compiler starts. */
14
- export function validateOptions({ mode = "spa", target } = {}) {
15
- if (!MODES.has(mode)) throw new Error(`Unknown AFW rendering mode: ${mode} (expected spa, ssg, or ssr)`);
17
+ /**
18
+ * Throw on an unknown option, before any compiler starts. `mode` was removed: how pages
19
+ * render is set per folder in `_config.js`.
20
+ */
21
+ export function validateOptions({ mode, target } = {}) {
22
+ if (mode !== undefined) {
23
+ throw new Error('The AFW plugin\'s `mode` option was removed: set how pages render in app/_config.js, e.g. `export default defineRoute({ render: "server" })` (or "static", "client").');
24
+ }
16
25
  if (target !== undefined && !TARGETS.has(target)) {
17
26
  throw new Error(`Unknown AFW compiler target: ${target} (expected csr, ssg, or hydrate)`);
18
27
  }
19
28
  }
20
29
 
21
30
  /**
22
- * The compiler target for one module. `server` — the module is bundled for the
23
- * server (string renderers). `dev` — a dev server or test run, which always renders
24
- * on the client. Otherwise a release browser build: CSR for an SPA, the hydrating
25
- * dual module when the server renders first.
31
+ * The compiler target for one module. `app` is how the app renders overall (see
32
+ * `APP_RENDERS`). `server` — the module is bundled for the server (string renderers).
33
+ * `test` — a test run, which renders on the client. `dev` — a dev server's browser build:
34
+ * the hydrating dual module when the dev server renders pages first, as production does
35
+ * (`devRenders`, by default only for a `server` app); CSR otherwise. Otherwise a release
36
+ * browser build: CSR for a client app, the hydrating dual module when pages render first.
26
37
  */
27
- export function chooseTarget({ mode = "spa", target, server = false, dev = false } = {}) {
38
+ export function chooseTarget({ app = "client", target, server = false, dev = false, test = false, devRenders = app === "server" } = {}) {
28
39
  if (target) return target;
29
40
  if (server) return "ssg";
30
- if (dev) return "csr";
31
- return mode === "spa" ? "csr" : "hydrate";
41
+ if (test) return "csr";
42
+ if (dev) return devRenders && app !== "client" ? "hydrate" : "csr";
43
+ return app === "client" ? "csr" : "hydrate";
44
+ }
45
+
46
+ /** The compiler backend token for `target`, with `hot` selecting its refresh build. */
47
+ export function compilerTarget(target, hot = false) {
48
+ if (!hot) return target;
49
+ if (target === "csr") return "csr-hot";
50
+ if (target === "hydrate") return "hydrate-hot";
51
+ return target;
32
52
  }
33
53
 
34
54
  /** Whether framework imports in this build resolve to the DOM-free server entry. */
@@ -57,7 +77,7 @@ export function errorStub(text) {
57
77
 
58
78
  /**
59
79
  * Compile one module. `server` is a compiler client (compiler-client.js). `hot`
60
- * requests the refresh-instrumented CSR build. On failure, `failOnError` throws the
80
+ * requests the refresh-instrumented build of the target (CSR or hydrate). On failure, `failOnError` throws the
61
81
  * diagnostic (after `error(message)` when the toolchain reports through its own
62
82
  * channel); otherwise it logs and returns the stub, so one broken file does not
63
83
  * stop a dev server.
@@ -68,7 +88,7 @@ export async function compileModule(server, code, id, {
68
88
  target, hot = false, failOnError = false, onResult, quiet = () => {}, error,
69
89
  } = {}) {
70
90
  try {
71
- const out = await server.compile(id, code, !isRouteModule(id), hot && target === "csr" ? "csr-hot" : target);
91
+ const out = await server.compile(id, code, !isRouteModule(id), compilerTarget(target, hot));
72
92
  onResult?.(id, null);
73
93
  return typeof out === "string" ? { code: out, map: null } : { code: out.code, map: out.map ?? null };
74
94
  } catch (e) {
package/document.js CHANGED
@@ -242,7 +242,7 @@ export async function renderDocument(render, {
242
242
  ),
243
243
  dataJson,
244
244
  );
245
- return { status, html: document, dataJson, loaded: !!match, metadata };
245
+ return { status, html: document, dataJson, loaded: !!match, metadata, route: result.route ?? null };
246
246
  }
247
247
 
248
248
  /** The 404 page as a document (`noindex`), or `null` when the app has none. */
package/index.js CHANGED
@@ -6,8 +6,8 @@
6
6
  export { assertHost } from "./host.js";
7
7
  export { compileError, closeCompilers, startCompilerServer } from "./compiler-client.js";
8
8
  export {
9
- FRAMEWORK_IMPORT, MODES, SOURCE_FILTER, TARGETS,
10
- chooseTarget, compileModule, errorStub, isRouteModule, usesServerEntry, validateOptions,
9
+ APP_RENDERS, FRAMEWORK_IMPORT, SOURCE_FILTER, TARGETS,
10
+ chooseTarget, compileModule, compilerTarget, errorStub, isRouteModule, usesServerEntry, validateOptions,
11
11
  } from "./compile.js";
12
12
  export { ensureCompiler, findUp, resolveCompiler } from "./resolve-compiler.js";
13
13
  export {
@@ -15,6 +15,10 @@ export {
15
15
  discoverLoaders, discoverPages, findGuard, isUnpublishedPage, isUnpublishedSource, loaderPageRoutes,
16
16
  resolveAppRoot, routeKey, routesModule,
17
17
  } from "./routes.js";
18
+ export {
19
+ CONFIG_FILE, RENDERS,
20
+ clientRouteFiles, discoverRouteConfigs, folderRoute, formatRouteTable, readRouteConfigs, resolveRoutePolicies, routeManifest, routeRenders, staticPathConfigs, appRender,
21
+ } from "./route-policy.js";
18
22
  export { SERVER_ID, discoverServerFiles, hasServerFiles, serverConflicts, serverModule } from "./server.js";
19
23
  export {
20
24
  DATA_FILE, alternateLinks, escapeXml, i18nSettings, injectBeforeBody, injectHead, injectHydrationData,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opentf/afw-build",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "The toolchain-neutral core of AFW's build: compiler client, compile targets and file-based routing.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -17,6 +17,7 @@
17
17
  "compile.js",
18
18
  "resolve-compiler.js",
19
19
  "routes.js",
20
+ "route-policy.js",
20
21
  "server.js",
21
22
  "document.js",
22
23
  "prerender.js",
package/prerender.js CHANGED
@@ -41,6 +41,8 @@ export function robotsTxt(baseUrl, hasSitemap) {
41
41
  * (marked for hydration by the caller when the client hydrates). `loaders` is the
42
42
  * loader registry, run at build time with no request and an empty query. A
43
43
  * `public/sitemap.xml` or `public/robots.txt` in `publicDir` wins over the generated one.
44
+ * `routes` (a Set of route patterns) limits the prerender to those routes and skips the
45
+ * 404 page, sitemap and robots.txt — a server app's static routes.
44
46
  *
45
47
  * @returns {Promise<{ count: number, skipped: string[], failed: string[], siteDescription: string, paths: string[] }>}
46
48
  * `siteDescription` is the site's own description (home route, else the root
@@ -48,12 +50,16 @@ export function robotsTxt(baseUrl, hasSitemap) {
48
50
  */
49
51
  export async function prerender(host, {
50
52
  render, shellHtml, outDir, publicDir, baseUrl = "", lastUpdated = {}, i18n = null, loaders = null,
51
- chunkManifest = null, onRender,
53
+ chunkManifest = null, onRender, routes = null,
52
54
  }) {
53
55
  const settings = i18nSettings(i18n);
54
56
  const locales = settings ? settings.locales : [null];
55
57
  const defaultLocale = settings?.defaultLocale ?? null;
56
- const { paths, skipped } = await render.collectRoutePaths();
58
+ // `routes`: only these route patterns, as a Set (a server app prerenders just its
59
+ // static routes; no 404 page, sitemap or robots.txt then).
60
+ const collected = await render.collectRoutePaths();
61
+ const paths = routes ? collected.paths.filter((p) => routes.has(p.route)) : collected.paths;
62
+ const skipped = routes ? collected.skipped.filter((r) => routes.has(r)) : collected.skipped;
57
63
  const preloadFor = (route) => modulepreloadTags(chunkManifest?.routes?.[route]);
58
64
 
59
65
  const failed = [];
@@ -89,6 +95,10 @@ export async function prerender(host, {
89
95
  }
90
96
  }
91
97
 
98
+ // A partial prerender (a server app's static routes) stops here: its server answers
99
+ // unknown paths and serves no sitemap of its own yet.
100
+ if (routes) return { count: rendered.length, skipped, failed, siteDescription, paths: rendered };
101
+
92
102
  // Any unmatched path is served the 404 page by static hosts.
93
103
  try {
94
104
  const notFound = await renderNotFound(render, { shell: shellHtml, baseUrl, preload: modulepreloadTags(chunkManifest?.notFound) });
@@ -0,0 +1,214 @@
1
+ // Per-route rendering: each folder's `_config.{js,ts}` declares how its pages render
2
+ // (`server`, `static`, `client`), and the nearest one up the folder tree wins. The app
3
+ // default is the root `_config.js`, else `client`. Resolution needs
4
+ // only the files: the compiler reads each config without running it (`route-config`), so
5
+ // the result can decide what each bundle contains before any bundle exists.
6
+
7
+ /** A folder's config file. One per folder; `.js` and `.ts` side by side is an error. */
8
+ export const CONFIG_FILE = /^_config\.(js|ts)$/;
9
+
10
+ /** The render strategies. */
11
+ export const RENDERS = ["server", "static", "client"];
12
+
13
+ const PAGE = /^page\.(mdx|md|[jt]sx)$/;
14
+ const LAYOUT = /^layout\.[jt]sx$/;
15
+
16
+ /** Folder of a `/`-separated relative path ("" for the app root). */
17
+ const folderOf = (rel) => (rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : "");
18
+
19
+ /** The URL pattern a folder serves: route groups `(name)` are not part of it. */
20
+ export function folderRoute(folder) {
21
+ const segments = folder.split("/").filter((s) => s && !/^\(.+\)$/.test(s));
22
+ return `/${segments.join("/")}`;
23
+ }
24
+
25
+ /** The folders from `folder` up to the app root, nearest first. */
26
+ function ancestry(folder) {
27
+ const out = [folder];
28
+ for (let f = folder; f; ) {
29
+ f = folderOf(f);
30
+ out.push(f);
31
+ }
32
+ return out;
33
+ }
34
+
35
+ const relative = (root, abs) => abs.slice(root.replace(/\/+$/, "").length + 1);
36
+
37
+ /**
38
+ * Every `_config.{js,ts}` under `root`, as a map from folder (relative, "" for the
39
+ * root) to absolute path. Excluded subtrees, dot directories and node_modules are skipped.
40
+ */
41
+ export async function discoverRouteConfigs(host, root, { exclude = [] } = {}) {
42
+ const found = new Map();
43
+ const skip = new Set(exclude);
44
+ async function visit(abs, rel) {
45
+ let entries;
46
+ try {
47
+ entries = await host.readDir(abs);
48
+ } catch {
49
+ return;
50
+ }
51
+ for (const entry of entries) {
52
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
53
+ if ([...skip].some((name) => childRel === name || childRel.startsWith(`${name}/`))) continue;
54
+ const childAbs = host.path.join(abs, entry.name);
55
+ let isDir = entry.isDir;
56
+ let isFile = entry.isFile;
57
+ if (entry.isSymlink) {
58
+ const kind = await host.kind(childAbs);
59
+ isDir = kind === "dir";
60
+ isFile = kind === "file";
61
+ }
62
+ if (isDir) {
63
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
64
+ await visit(childAbs, childRel);
65
+ } else if (isFile && CONFIG_FILE.test(entry.name)) {
66
+ if (found.has(rel)) throw new Error(`Two config files for one folder: ${found.get(rel)} and ${childAbs}. Keep one _config.js (or _config.ts).`);
67
+ found.set(rel, childAbs);
68
+ }
69
+ }
70
+ }
71
+ await visit(root, "");
72
+ return found;
73
+ }
74
+
75
+ /**
76
+ * Read each discovered config through the compiler (without running it). Returns a map
77
+ * from folder to `{ file, render, data, paths }`. A config the compiler rejects throws
78
+ * its diagnostic, which names the file and position.
79
+ */
80
+ export async function readRouteConfigs(host, compiler, configs) {
81
+ const out = new Map();
82
+ for (const [folder, file] of configs) {
83
+ const raw = await compiler.compile(file, await host.readText(file), false, "route-config");
84
+ const parsed = JSON.parse(typeof raw === "string" ? raw : raw.code);
85
+ out.set(folder, { file, render: parsed.render ?? null, data: parsed.data ?? null, paths: !!parsed.paths });
86
+ }
87
+ return out;
88
+ }
89
+
90
+ /**
91
+ * Resolve every page's policy. `pages` are absolute page/layout/404/loading/error files
92
+ * (as `discoverPages` returns); only `page.*` files are routes. `configs` is the map
93
+ * `readRouteConfigs` returns.
94
+ *
95
+ * Returns `{ defaultRender, routes, policyOf, warnings }`:
96
+ * - `routes`: one entry per page, sorted by route — `{ route, folder, file, render, data,
97
+ * from }`, where `from` is the config file that decided `render` ("default" without one).
98
+ * - `policyOf(folder)`: the same resolution for any folder (a layout's, say).
99
+ * - `warnings`: config files that govern no page.
100
+ * Throws on a conflict the app must fix: `paths` outside a static folder, `data` outside a
101
+ * client folder, a server or static page inside a client layout.
102
+ */
103
+ export function resolveRoutePolicies({ root, pages, configs }) {
104
+ const rootConfig = configs.get("");
105
+ const defaultRender = rootConfig?.render ?? "client";
106
+ const defaultFrom = rootConfig?.render ? rootConfig.file : "default";
107
+
108
+ function policyOf(folder) {
109
+ let render = null, from = null, data = null;
110
+ for (const f of ancestry(folder)) {
111
+ const c = configs.get(f);
112
+ if (!c) continue;
113
+ if (!render && c.render) { render = c.render; from = c.file; }
114
+ if (!data && c.data) data = c.data;
115
+ }
116
+ return { render: render ?? defaultRender, from: from ?? defaultFrom, data: (render ?? defaultRender) === "client" ? data ?? "server" : null };
117
+ }
118
+
119
+ // A key only means something under the strategy it belongs to.
120
+ for (const [folder, c] of configs) {
121
+ const { render } = policyOf(folder);
122
+ if (c.paths && render !== "static") {
123
+ throw new Error(`${c.file}: \`paths\` lists the pages a static route builds, but this folder renders "${render}". Remove it, or set render: "static".`);
124
+ }
125
+ if (c.data && render !== "client") {
126
+ throw new Error(`${c.file}: \`data\` applies to client routes, but this folder renders "${render}". Remove it, or set render: "client".`);
127
+ }
128
+ }
129
+
130
+ const routes = [];
131
+ const layoutFolders = pages.map((abs) => relative(root, abs)).filter((rel) => LAYOUT.test(rel.split("/").pop())).map(folderOf);
132
+ for (const abs of pages) {
133
+ const rel = relative(root, abs);
134
+ if (!PAGE.test(rel.split("/").pop())) continue;
135
+ const folder = folderOf(rel);
136
+ const policy = policyOf(folder);
137
+ // The server cannot render inside a layout it never loads.
138
+ if (policy.render !== "client") {
139
+ const client = ancestry(folder).find((f) => layoutFolders.includes(f) && policyOf(f).render === "client");
140
+ if (client !== undefined) {
141
+ throw new Error(
142
+ `${abs} renders "${policy.render}", but the layout in app/${client ? `${client}/` : ""} renders "client": ` +
143
+ `the server cannot render a page inside a layout that renders in the browser. Make this folder "client" too, or move the page out of it.`,
144
+ );
145
+ }
146
+ }
147
+ routes.push({ route: folderRoute(folder), folder, file: abs, ...policy });
148
+ }
149
+ routes.sort((a, b) => (a.route < b.route ? -1 : a.route > b.route ? 1 : a.folder < b.folder ? -1 : 1));
150
+
151
+ // `paths` lists the pages of the dynamic route in its own folder; it is not inherited.
152
+ for (const [folder, c] of configs) {
153
+ if (!c.paths) continue;
154
+ const own = routes.find((r) => r.folder === folder);
155
+ if (!own || !own.route.includes("[")) {
156
+ throw new Error(`${c.file}: \`paths\` lists the pages of a dynamic route, but this folder has no dynamic page (like [slug]/page.jsx). Move it to that page's folder.`);
157
+ }
158
+ }
159
+
160
+ const warnings = [];
161
+ for (const [folder, c] of configs) {
162
+ if (!routes.some((r) => r.folder === folder || r.folder.startsWith(folder ? `${folder}/` : ""))) {
163
+ warnings.push(`${c.file} governs no page: there is no page.* in its folder or below it.`);
164
+ }
165
+ }
166
+ return { defaultRender, routes, policyOf, warnings };
167
+ }
168
+
169
+ /**
170
+ * The route files (from `discoverPages`: pages, layouts, 404, loading and error files)
171
+ * that render in the browser: those in a folder whose policy is `client`. The generated
172
+ * route tables mark them with `clientRoute`, and the server bundle leaves them out.
173
+ */
174
+ export function clientRouteFiles({ policyOf }, root, files) {
175
+ return new Set(files.filter((abs) => policyOf(folderOf(relative(root, abs))).render === "client"));
176
+ }
177
+
178
+ /**
179
+ * How the app renders overall: `server` when any route renders per request, else `static`
180
+ * when any is built, else `client` (the default, also for an app without pages).
181
+ */
182
+ export function appRender({ defaultRender, routes }) {
183
+ const strategies = new Set(routes.map((r) => r.render));
184
+ if (strategies.size === 0) strategies.add(defaultRender);
185
+ return strategies.has("server") ? "server" : strategies.has("static") ? "static" : "client";
186
+ }
187
+
188
+ /** The configs that declare `paths`, as `[routePattern, configFile]` for the server module. */
189
+ export function staticPathConfigs({ routes }, configs) {
190
+ return routes.filter((r) => configs.get(r.folder)?.paths).map((r) => [r.folder ? `/${r.folder}` : "/", configs.get(r.folder).file]);
191
+ }
192
+
193
+ /** Each route's strategy keyed by its route-table pattern (`/`, `/(legal)/privacy`), for the server module. */
194
+ export function routeRenders({ routes }) {
195
+ return Object.fromEntries(routes.map((r) => [r.folder ? `/${r.folder}` : "/", r.render]));
196
+ }
197
+
198
+ /** The resolved policies as the build prints them: route, render, and the file that decided it. */
199
+ export function formatRouteTable(routes, root = "") {
200
+ const from = (f) => (root && f.startsWith(`${root}/`) ? `app/${f.slice(root.length + 1)}` : f);
201
+ const rows = [["Route", "Render", "From"], ...routes.map((r) => [r.route, r.render + (r.data === "client" ? " (data: client)" : ""), from(r.from)])];
202
+ const widths = [0, 1].map((i) => Math.max(...rows.map((row) => row[i].length)));
203
+ return rows.map((row) => `${row[0].padEnd(widths[0])} ${row[1].padEnd(widths[1])} ${row[2]}`).join("\n");
204
+ }
205
+
206
+ /** The route manifest written beside the build (`routes.json`): what each route resolved to. */
207
+ export function routeManifest({ defaultRender, routes }, root = "") {
208
+ const rel = (f) => (root && f.startsWith(`${root}/`) ? `app/${f.slice(root.length + 1)}` : f);
209
+ return {
210
+ version: 1,
211
+ default: defaultRender,
212
+ routes: routes.map((r) => ({ route: r.route, render: r.render, ...(r.data ? { data: r.data } : {}), page: rel(r.file), from: rel(r.from) })),
213
+ };
214
+ }
package/routes.js CHANGED
@@ -184,7 +184,7 @@ export async function resolveAppRoot(host, appDir, importer) {
184
184
  *
185
185
  * @returns {Promise<{ code: string, files: string[] }>}
186
186
  */
187
- export async function routesModule(host, root, { exclude = [], drafts = true } = {}) {
187
+ export async function routesModule(host, root, { exclude = [], drafts = true, clientFiles = new Set() } = {}) {
188
188
  const pages = await discoverPages(host, root, { exclude, drafts });
189
189
  const loaders = await discoverLoaders(host, root, { exclude });
190
190
  const layoutLoaders = await discoverLoaders(host, root, { exclude, layout: true });
@@ -202,9 +202,14 @@ export async function routesModule(host, root, { exclude = [], drafts = true } =
202
202
  pageLoaders: loaders.map(([route]) => route),
203
203
  layoutLoaders: layoutLoaders.map(([route]) => route),
204
204
  });
205
- const map = pages
206
- .map((p) => ` [${JSON.stringify(routeKey(p, root))}]: () => import(${JSON.stringify(p)}),`)
207
- .join("\n");
205
+ // Entries that render in the browser (`_config.js` → `client`) are marked, so a page
206
+ // server-rendered around them adopts its layouts and builds the rest. The mark is the
207
+ // flag `clientRoute()` sets, written inline: importing the runtime here would load a
208
+ // second copy of it where a toolchain resolves a virtual module's imports elsewhere.
209
+ const entry = (p) => (clientFiles.has(p)
210
+ ? `Object.assign(() => import(${JSON.stringify(p)}), { __afwClient: true })`
211
+ : `() => import(${JSON.stringify(p)})`);
212
+ const map = pages.map((p) => ` [${JSON.stringify(routeKey(p, root))}]: ${entry(p)},`).join("\n");
208
213
  const code =
209
214
  `export const pages = {\n${map}\n};\n` +
210
215
  `export const loaderRoutes = ${JSON.stringify(loaderRoutes)};\n` +
package/server.js CHANGED
@@ -143,13 +143,13 @@ export function serverConflicts(host, dir, files) {
143
143
  * `createPageRenderer({ shell, baseUrl })`, a `renderPage` step built on
144
144
  * `renderDocument`. `drafts: false` leaves unpublished Markdown pages out.
145
145
  * `hydrate: false` serves rendered pages without the `data-afw-hydrate` marker, for a
146
- * dev loop whose browser build cannot adopt server DOM.
146
+ * browser build that cannot adopt server DOM (one compiled with the `csr` target).
147
147
  *
148
148
  * @param {{ exclude?: string[], i18n?: { locales: string[], defaultLocale?: string } | null,
149
149
  * pages?: boolean, drafts?: boolean, hydrate?: boolean }} [options]
150
150
  * @returns {Promise<{ code: string, files: string[] }>}
151
151
  */
152
- export async function serverModule(host, root, { exclude = [], i18n = null, pages = false, drafts = true, hydrate = true, listExports } = {}) {
152
+ export async function serverModule(host, root, { exclude = [], i18n = null, pages = false, drafts = true, hydrate = true, listExports, clientFiles = new Set(), renders = null, staticPaths = [] } = {}) {
153
153
  const files = await discoverServerFiles(host, root, { exclude });
154
154
  const problems = serverConflicts(host, root, files);
155
155
  if (problems.length) throw new Error(`AFW server routes:\n ${problems.join("\n ")}`);
@@ -180,23 +180,45 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
180
180
  groupScopes[`/${folder}`] = { scopes: [...new Set(scopes)].sort(), paths: paths.sort() };
181
181
  }
182
182
  if (Object.keys(groupScopes).length) options.groupScopes = groupScopes;
183
- const p = group(pageFiles, "p");
183
+ // Route files that render in the browser stay out of the server bundle: they register
184
+ // as `clientRoute()` entries, and the server render leaves their region empty.
185
+ const serverPageFiles = pageFiles.filter((f) => !clientFiles.has(f));
186
+ const p = group(serverPageFiles, "p");
187
+ const registered = pageFiles.map((f) => {
188
+ const key = JSON.stringify(routeKey(f, root));
189
+ return clientFiles.has(f) ? ` [${key}]: clientRoute(),` : ` [${key}]: p${serverPageFiles.indexOf(f)},`;
190
+ });
184
191
  const renderPart = pages
185
- ? `import { collectRoutePaths, configureI18n, registerRoutes, renderHead, renderRoute, resolveMetadata } from "@opentf/afw/server";\n` +
192
+ ? `import { clientRoute, collectRoutePaths, configureI18n, matchRoute, registerRoutes, registerStaticPaths, renderHead, renderRoute, resolveMetadata } from "@opentf/afw/server";\n` +
193
+ staticPaths.map(([, file], i) => `import sp${i} from ${JSON.stringify(file)};\n`).join("") +
186
194
  `import { renderDocument, stampHydrateSentinel } from "@opentf/afw-build/document";\n` +
187
195
  (p.imports ? `${p.imports}\n` : "") +
188
196
  (options.i18n ? `configureI18n(options.i18n);\n` : "") +
189
- `registerRoutes({\n${pageFiles.map((f, i) => ` [${JSON.stringify(routeKey(f, root))}]: p${i},`).join("\n")}\n});\n` +
197
+ `registerRoutes({\n${registered.join("\n")}\n});\n` +
198
+ (staticPaths.length ? `registerStaticPaths({\n${staticPaths.map(([route], i) => ` [${JSON.stringify(route)}]: sp${i}.paths,`).join("\n")}\n});\n` : "") +
190
199
  `export const render = { renderRoute, renderHead, collectRoutePaths, resolveMetadata };\n` +
191
- `/** A \`renderPage\` step: server-render page requests (\`GET\`/\`HEAD\`) into \`shell\`, the client's index.html. */\n` +
192
- `export function createPageRenderer({ shell: html, baseUrl = "" }) {\n` +
193
- // Without `hydrate` (a dev loop whose client is a CSR build) the page is still
200
+ // Each route's resolved render policy (route pattern → strategy), for the response's
201
+ // `x-afw-render` header: what decided how this page was produced.
202
+ `const renders = ${JSON.stringify(renders ?? {})};\n` +
203
+ `/**\n` +
204
+ ` * A \`renderPage\` step: server-render page requests (\`GET\`/\`HEAD\`) into \`shell\`, the client's index.html.\n` +
205
+ ` * \`readStatic(pathname)\` returns the HTML the build prerendered for a static route (or null), which is\n` +
206
+ ` * served instead of rendering; a static route's unlisted page renders per request.\n` +
207
+ ` */\n` +
208
+ `export function createPageRenderer({ shell: html, baseUrl = "", readStatic = null }) {\n` +
209
+ // Without `hydrate` (a browser build compiled for `csr`) the page is still
194
210
  // server-rendered, but not marked for adoption: the client builds it fresh.
195
211
  ` const shell = ${hydrate ? "stampHydrateSentinel(html)" : "html"};\n` +
196
212
  ` return async (request, { locals = {} } = {}) => {\n` +
197
213
  ` const method = request.method.toUpperCase();\n` +
198
214
  ` if (method !== "GET" && method !== "HEAD") return null;\n` +
199
215
  ` const url = new URL(request.url);\n` +
216
+ ` if (readStatic && renders[matchRoute(url.pathname)?.route] === "static") {\n` +
217
+ ` const built = await readStatic(url.pathname);\n` +
218
+ ` if (built != null) return new Response(method === "HEAD" ? null : built, {\n` +
219
+ ` headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache", "x-afw-render": "static" },\n` +
220
+ ` });\n` +
221
+ ` }\n` +
200
222
  ` let doc;\n` +
201
223
  ` try {\n` +
202
224
  ` doc = await renderDocument(render, {\n` +
@@ -209,7 +231,7 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
209
231
  ` }\n` +
210
232
  ` if (!doc) return null;\n` +
211
233
  ` return new Response(method === "HEAD" ? null : doc.html, {\n` +
212
- ` status: doc.status, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache" },\n` +
234
+ ` status: doc.status, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache", ...(renders[doc.route] ? { "x-afw-render": renders[doc.route] } : {}) },\n` +
213
235
  ` });\n` +
214
236
  ` };\n` +
215
237
  `}\n`
@@ -248,7 +270,7 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
248
270
  ` };\n` +
249
271
  ` return createFetchHandler(terminal, { middleware, fallback });\n` +
250
272
  `}\n`;
251
- return { code, files: [...files.routes, ...files.middleware, ...files.loaders, ...files.layoutLoaders, ...pageFiles, ...fns.files] };
273
+ return { code, files: [...files.routes, ...files.middleware, ...files.loaders, ...files.layoutLoaders, ...serverPageFiles, ...fns.files] };
252
274
  }
253
275
 
254
276
  function loaderRoutePatterns(host, root, loaders) {