@opentf/afw-build 0.3.0 → 0.4.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
@@ -39,10 +39,10 @@ export function usesServerEntry({ target, server = false } = {}) {
39
39
  /** The framework specifiers that resolve to `@opentf/afw/server` in a server build. */
40
40
  export const FRAMEWORK_IMPORT = /^@opentf\/afw(?:\/runtime)?$/;
41
41
 
42
- /** Page, layout and 404 modules compile to route factories; the rest to components. */
42
+ /** Page, layout, 404, loading and error modules compile to route factories; the rest to components. */
43
43
  export function isRouteModule(id) {
44
44
  const base = id.split(/[\\/]/).pop().replace(SOURCE_FILTER, "");
45
- return base === "page" || base === "layout" || base === "404";
45
+ return base === "page" || base === "layout" || base === "404" || base === "loading" || base === "error";
46
46
  }
47
47
 
48
48
  /** A module that shows the compile error in place of the page or component. */
package/document.js CHANGED
@@ -84,7 +84,12 @@ export function stampRenderedPath(shellHtml, path) {
84
84
  export function injectHead(shellHtml, headHtml) {
85
85
  if (!headHtml) return shellHtml;
86
86
  let out = stripRouteHead(shellHtml);
87
- if (/<title[\s>]/i.test(headHtml)) out = out.replace(/<title>[\s\S]*?<\/title>\s*/i, "");
87
+ if (/<title[\s>]/i.test(headHtml)) {
88
+ // The page's title replaces the shell's. Keep the shell's as the client's fallback
89
+ // for a later page without a title (runtime/head.js `prepareRouteHead`).
90
+ out = out.replace(/<title>([\s\S]*?)<\/title>\s*/i, (_, text) =>
91
+ text.trim() ? `<meta name="afw-shell-title" content="${text.trim().replace(/"/g, "&quot;")}">\n` : "");
92
+ }
88
93
  // Function replacer so `$` in `headHtml` (e.g. a price in a meta description) is literal.
89
94
  return out.replace(/<\/head>/i, () => `${headHtml}\n</head>`);
90
95
  }
@@ -187,28 +192,38 @@ export function alternateLinks(path, i18n) {
187
192
  * `modifiedTime` adds `article:modified_time` on article pages. `notFound`: what a
188
193
  * loader's `notFound()` does — `"render"` the 404 page (a request server), or
189
194
  * `"throw"` it to the caller (static generation, which reports the path as failed).
195
+ * `errors`: what any other loader failure does — `"throw"` it (the default: static
196
+ * generation reports the path as failed), or `"render"` the route's nearest
197
+ * `error.jsx` with status 500 (a request server). Thrown `Response`s always throw.
190
198
  *
191
199
  * @returns {Promise<{ status: number, html: string, dataJson: string, loaded: boolean, metadata: object } | null>}
192
200
  * `null` when no page and no 404 page match.
193
201
  */
194
202
  export async function renderDocument(render, {
195
203
  shell, url, params = null, search = "", loaders = null, loaderContext = {}, baseUrl = "", i18n = null,
196
- preload = "", modifiedTime = null, notFound = "render",
204
+ preload = "", modifiedTime = null, notFound = "render", errors = "throw",
197
205
  } = {}) {
198
206
  const { locale, path } = splitLocale(url, i18n);
199
207
  const match = loaders?.match(url);
200
208
  let data;
201
209
  let dataJson = "";
210
+ let failure;
202
211
  if (match) {
203
212
  try {
204
213
  ({ data, json: dataJson } = await loaders.loadSerialized(match, { query: {}, ...loaderContext }));
205
214
  } catch (e) {
206
- if (e?.afwNotFound !== true || notFound === "throw") throw e;
207
- return renderNotFound(render, { shell, baseUrl, preload });
215
+ if (e?.afwNotFound === true && notFound !== "throw") return renderNotFound(render, { shell, baseUrl, preload });
216
+ // A request server renders the route's `error.jsx` (status 500); a redirect or
217
+ // refusal (`throw new Response`), a build, or a route without one keeps the throw.
218
+ if (errors !== "render" || e?.afwNotFound === true || e instanceof Response) throw e;
219
+ failure = e;
208
220
  }
209
221
  }
210
- const result = await render.renderRoute(url, params, search, { data });
222
+ const result = failure === undefined
223
+ ? await render.renderRoute(url, params, search, { data })
224
+ : await render.renderRoute(url, params, search, { error: failure });
211
225
  if (!result) return null;
226
+ if (result.dataJson) dataJson = result.dataJson;
212
227
  const { html, metadata = {}, hydration = "", status = 200 } = result;
213
228
  const alternates = alternateLinks(path, i18n);
214
229
  const meta = alternates.length ? { ...metadata, links: [...(metadata.links || []), ...alternates] } : metadata;
package/index.js CHANGED
@@ -12,7 +12,7 @@ export {
12
12
  export { ensureCompiler, findUp, resolveCompiler } from "./resolve-compiler.js";
13
13
  export {
14
14
  ROUTES_ID,
15
- discoverLoaders, discoverPages, findGuard, isUnpublishedPage, isUnpublishedSource,
15
+ discoverLoaders, discoverPages, findGuard, isUnpublishedPage, isUnpublishedSource, loaderPageRoutes,
16
16
  resolveAppRoot, routeKey, routesModule,
17
17
  } from "./routes.js";
18
18
  export { SERVER_ID, discoverServerFiles, hasServerFiles, serverConflicts, serverModule } from "./server.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opentf/afw-build",
3
- "version": "0.3.0",
3
+ "version": "0.4.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": {
package/routes.js CHANGED
@@ -10,8 +10,9 @@
10
10
  /** The specifier entries import. */
11
11
  export const ROUTES_ID = "@afw/routes";
12
12
 
13
- const PAGE_FILE = /^(page|layout|404)\.(mdx|md|jsx|tsx)$/;
13
+ const PAGE_FILE = /^(page|layout|404|loading|error)\.(mdx|md|jsx|tsx)$/;
14
14
  const LOADER_FILE = /^loader\.(js|ts)$/;
15
+ const LAYOUT_LOADER_FILE = /^layout\.loader\.(js|ts)$/;
15
16
 
16
17
  /**
17
18
  * Whether Markdown source is unpublished: frontmatter `draft: true`, or a `date`
@@ -83,9 +84,9 @@ async function walk(host, dir, pattern, exclude) {
83
84
  }
84
85
 
85
86
  /**
86
- * Page, layout and 404 files under `dir`, as absolute paths. A Markdown 404 is an
87
- * error (the runtime has no Markdown fallback route). Without `drafts`,
88
- * unpublished Markdown pages are left out.
87
+ * Page, layout, 404, loading and error files under `dir`, as absolute paths. A
88
+ * Markdown 404, loading or error file is an error (each is a component the router
89
+ * renders with props). Without `drafts`, unpublished Markdown pages are left out.
89
90
  */
90
91
  export async function discoverPages(host, dir, { exclude = [], drafts = true } = {}) {
91
92
  const out = [];
@@ -94,6 +95,10 @@ export async function discoverPages(host, dir, { exclude = [], drafts = true } =
94
95
  if (/(^|\/)404\.(mdx|md)$/.test(rel)) {
95
96
  throw new Error(`Unsupported Markdown 404 route: ${abs}. Use 404.jsx or 404.tsx instead.`);
96
97
  }
98
+ const special = /(?:^|\/)(loading|error)\.(?:mdx|md)$/.exec(rel);
99
+ if (special) {
100
+ throw new Error(`Unsupported Markdown ${special[1]} file: ${abs}. Use ${special[1]}.jsx or ${special[1]}.tsx instead.`);
101
+ }
97
102
  if (!drafts && (await isUnpublishedPage(host, abs))) continue;
98
103
  out.push(abs);
99
104
  }
@@ -101,19 +106,37 @@ export async function discoverPages(host, dir, { exclude = [], drafts = true } =
101
106
  }
102
107
 
103
108
  /** Loader files under `dir` as `[route, absPath]` pairs, sorted by route. A route
104
- * with both `loader.js` and `loader.ts` is an error. */
105
- export async function discoverLoaders(host, dir, { exclude = [] } = {}) {
109
+ * with both `loader.js` and `loader.ts` is an error. `{ layout: true }` finds
110
+ * `layout.loader.{js,ts}` files instead, keyed by their layout's folder. */
111
+ export async function discoverLoaders(host, dir, { exclude = [], layout = false } = {}) {
106
112
  const routes = new Map();
107
- for (const rel of await walk(host, dir, LOADER_FILE, new Set(exclude))) {
108
- const pattern = rel.replace(/(^|\/)loader\.(js|ts)$/, "") || "/";
113
+ for (const rel of await walk(host, dir, layout ? LAYOUT_LOADER_FILE : LOADER_FILE, new Set(exclude))) {
114
+ const pattern = rel.replace(/(^|\/)(?:layout\.)?loader\.(js|ts)$/, "") || "/";
109
115
  const route = pattern.startsWith("/") ? pattern : `/${pattern}`;
110
116
  const abs = host.path.join(dir, rel);
111
- if (routes.has(route)) throw new Error(`Conflicting loaders for ${route}: ${routes.get(route)} and ${abs}`);
117
+ if (routes.has(route)) throw new Error(`Conflicting ${layout ? "layout " : ""}loaders for ${route}: ${routes.get(route)} and ${abs}`);
112
118
  routes.set(route, abs);
113
119
  }
114
120
  return [...routes].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
115
121
  }
116
122
 
123
+ /** Does the layout at `folder` wrap the page at `route`? (Mirrors `@opentf/afw/server`.) */
124
+ const layoutWraps = (folder, route) => folder === "/" || route === folder || route.startsWith(`${folder}/`);
125
+
126
+ /**
127
+ * The page routes with loader data — their own `loader.*`, or any page beneath a
128
+ * `layout.loader.*` — which the client router fetches `__data.json` for. Mirrors
129
+ * `loaderPageRoutes` in `@opentf/afw/server`, which this package does not import.
130
+ */
131
+ export function loaderPageRoutes({ pages = [], pageLoaders = [], layoutLoaders = [] }) {
132
+ const out = new Set(pageLoaders);
133
+ for (const page of pages) if (layoutLoaders.some((folder) => layoutWraps(folder, page))) out.add(page);
134
+ return [...out].sort();
135
+ }
136
+
137
+ /** The route a `page.*` file serves: its folder (`/` for the app root). */
138
+ const pageRoute = (file, root) => routeKey(file, root).replace(/^\/app/, "").replace(/\/page\.[^/]+$/, "") || "/";
139
+
117
140
  function stripAppPrefix(filePath, appDir) {
118
141
  if (appDir) {
119
142
  const base = appDir.replace(/\/+$/, "");
@@ -164,13 +187,28 @@ export async function resolveAppRoot(host, appDir, importer) {
164
187
  export async function routesModule(host, root, { exclude = [], drafts = true } = {}) {
165
188
  const pages = await discoverPages(host, root, { exclude, drafts });
166
189
  const loaders = await discoverLoaders(host, root, { exclude });
190
+ const layoutLoaders = await discoverLoaders(host, root, { exclude, layout: true });
167
191
  const guard = await findGuard(host, root);
192
+ // Route groups drop out of the URL: two groups holding the same page path collide.
193
+ const byUrl = new Map();
194
+ for (const file of pages.filter((p) => /\/page\.[^/]+$/.test(p))) {
195
+ const route = pageRoute(file, root);
196
+ const url = `/${route.split("/").filter((s) => s && !/^\(.+\)$/.test(s)).join("/")}`;
197
+ if (byUrl.has(url)) throw new Error(`Two pages answer ${url}: ${byUrl.get(url)} and ${file}. Move one to another path.`);
198
+ byUrl.set(url, file);
199
+ }
200
+ const loaderRoutes = loaderPageRoutes({
201
+ pages: pages.filter((p) => /\/page\.[^/]+$/.test(p)).map((p) => pageRoute(p, root)),
202
+ pageLoaders: loaders.map(([route]) => route),
203
+ layoutLoaders: layoutLoaders.map(([route]) => route),
204
+ });
168
205
  const map = pages
169
206
  .map((p) => ` [${JSON.stringify(routeKey(p, root))}]: () => import(${JSON.stringify(p)}),`)
170
207
  .join("\n");
171
208
  const code =
172
209
  `export const pages = {\n${map}\n};\n` +
173
- `export const loaderRoutes = ${JSON.stringify(loaders.map(([route]) => route))};\n` +
210
+ `export const loaderRoutes = ${JSON.stringify(loaderRoutes)};\n` +
174
211
  (guard ? `export { default as guard } from ${JSON.stringify(guard)};\n` : `export const guard = undefined;\n`);
175
- return { code, files: [...pages, ...loaders.map(([, file]) => file), ...(guard ? [guard] : [])] };
212
+ const loaderFiles = [...loaders, ...layoutLoaders].map(([, file]) => file);
213
+ return { code, files: [...pages, ...loaderFiles, ...(guard ? [guard] : [])] };
176
214
  }
@@ -27,8 +27,10 @@ const relativeTo = (root, file) => (file.startsWith(`${root}/`) ? file.slice(roo
27
27
  export function serverFunctionEndpoint(root, file, name) {
28
28
  const rel = relativeTo(root, file);
29
29
  if (rel === null) throw new Error(`${file}: server modules must be inside the app directory (${root})`);
30
- const folder = rel.includes("/") ? `/${rel.slice(0, rel.lastIndexOf("/"))}` : "";
31
- return `${folder}/__fn/${fnv1a64(`${rel}#${name}`)}`;
30
+ // The URL of the folder: route groups (`(app)`) are not part of it. The hash keeps
31
+ // the full path, so two groups' modules never share an endpoint.
32
+ const folder = rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")).split("/").filter((s) => !/^\(.+\)$/.test(s)).join("/") : "";
33
+ return `${folder ? `/${folder}` : ""}/__fn/${fnv1a64(`${rel}#${name}`)}`;
32
34
  }
33
35
 
34
36
  /** Every `*.server` module under `dir`, sorted, skipping dot folders, node_modules and `exclude`. */
@@ -88,20 +90,23 @@ export function serverFunctionStub(root, file, exports) {
88
90
  * The server side: for each server module, its import and the endpoint table entries.
89
91
  * `listExports(file)` returns the module's exports (see `serverExports`).
90
92
  *
91
- * @returns {Promise<{ imports: string, table: string, files: string[] }>}
93
+ * @returns {Promise<{ imports: string, table: string, files: string[], endpoints: Array<[string, string]> }>}
92
94
  */
93
95
  export async function serverFunctionTable(host, root, { exclude = [], listExports }) {
94
96
  const files = await discoverServerModules(host, root, { exclude });
95
97
  const imports = [];
96
98
  const entries = [];
99
+ const endpoints = []; // [file, endpoint]
97
100
  for (const [i, file] of files.entries()) {
98
101
  const exports = await listExports(file);
99
102
  const fns = exports.filter((e) => e.kind);
100
103
  if (!fns.length) continue;
101
104
  imports.push(`import * as sf${i} from ${JSON.stringify(file)};`);
102
105
  for (const { name } of fns) {
103
- entries.push(` [${JSON.stringify(serverFunctionEndpoint(root, file, name))}]: sf${i}[${JSON.stringify(name)}],`);
106
+ const endpoint = serverFunctionEndpoint(root, file, name);
107
+ endpoints.push([file, endpoint]);
108
+ entries.push(` [${JSON.stringify(endpoint)}]: sf${i}[${JSON.stringify(name)}],`);
104
109
  }
105
110
  }
106
- return { imports: imports.join("\n"), table: entries.join("\n"), files };
111
+ return { imports: imports.join("\n"), table: entries.join("\n"), files, endpoints };
107
112
  }
package/server.js CHANGED
@@ -12,7 +12,7 @@
12
12
  // const response = await handle(request);
13
13
  // // middleware → API routes → loader data → files → page render → fallback
14
14
 
15
- import { discoverPages, routeKey } from "./routes.js";
15
+ import { discoverPages, loaderPageRoutes, routeKey } from "./routes.js";
16
16
  import { serverFunctionTable } from "./server-functions.js";
17
17
 
18
18
  /** The specifier a server entry imports. */
@@ -21,7 +21,9 @@ export const SERVER_ID = "@afw/server";
21
21
  const ROUTE_FILE = /^route\.(jsx?|tsx?)$/;
22
22
  const MIDDLEWARE_FILE = /^_middleware\.(jsx?|tsx?)$/;
23
23
  const LOADER_FILE = /^loader\.(js|ts)$/;
24
+ const LAYOUT_LOADER_FILE = /^layout\.loader\.(js|ts)$/;
24
25
  const PAGE_FILE = /^page\.(mdx|md|jsx|tsx)$/;
26
+ const LAYOUT_FILE = /^layout\.(mdx|md|jsx|tsx)$/;
25
27
 
26
28
  async function walk(host, dir, exclude, visitFile) {
27
29
  async function visit(abs, rel) {
@@ -60,22 +62,34 @@ async function walk(host, dir, exclude, visitFile) {
60
62
  * @returns {Promise<{ routes: string[], middleware: string[], loaders: string[], pages: Map<string, string> }>}
61
63
  */
62
64
  export async function discoverServerFiles(host, dir, { exclude = [] } = {}) {
63
- const routes = [], middleware = [], loaders = [];
65
+ const routes = [], middleware = [], loaders = [], layoutLoaders = [];
64
66
  const pages = new Map(); // folder (relative, "" for the root) → page file
67
+ const layouts = new Set(); // folders with a layout.*
65
68
  await walk(host, dir, new Set(exclude), (name, abs, folder) => {
66
69
  if (ROUTE_FILE.test(name)) routes.push(abs);
67
70
  else if (MIDDLEWARE_FILE.test(name)) middleware.push(abs);
68
71
  else if (LOADER_FILE.test(name)) loaders.push(abs);
72
+ else if (LAYOUT_LOADER_FILE.test(name)) layoutLoaders.push(abs);
69
73
  else if (PAGE_FILE.test(name)) pages.set(folder, abs);
74
+ else if (LAYOUT_FILE.test(name)) layouts.add(folder);
70
75
  });
71
- return { routes: routes.sort(), middleware: middleware.sort(), loaders: loaders.sort(), pages };
76
+ return { routes: routes.sort(), middleware: middleware.sort(), loaders: loaders.sort(), layoutLoaders: layoutLoaders.sort(), pages, layouts };
72
77
  }
73
78
 
74
79
  /** Whether the app has anything for a server to run. */
75
- export function hasServerFiles({ routes, middleware, loaders }) {
76
- return routes.length + middleware.length + loaders.length > 0;
80
+ export function hasServerFiles({ routes, middleware, loaders, layoutLoaders = [] }) {
81
+ return routes.length + middleware.length + loaders.length + layoutLoaders.length > 0;
77
82
  }
78
83
 
84
+ /** Is `segment` a route group, `(name)` (a folder that is not part of the URL)? */
85
+ const isGroupSegment = (segment) => /^\(.+\)$/.test(segment);
86
+
87
+ /** The URL a folder answers (`dashboard` → `/dashboard`, `(app)/x` → `/x`, "" → `/`). */
88
+ export const folderUrl = (folder) => `/${folder.split("/").filter((s) => s && !isGroupSegment(s)).join("/")}`;
89
+
90
+ /** Is `folder` the group folder `group`, or inside it? (Relative folders, "" = root.) */
91
+ const within = (group, folder) => group === "" || folder === group || folder.startsWith(`${group}/`);
92
+
79
93
  const folderOf = (host, dir, file) => {
80
94
  const parent = host.path.dirname(file);
81
95
  return parent === dir ? "" : parent.slice(dir.length + 1);
@@ -95,6 +109,15 @@ export function serverConflicts(host, dir, files) {
95
109
  problems.push(`a page and an API route answer /${folder}: ${files.pages.get(folder)} and ${route}. Move one to another folder.`);
96
110
  }
97
111
  }
112
+ // Route groups drop out of the URL, so files in different groups can answer the same one.
113
+ const byUrl = new Map();
114
+ const answers = [...[...files.pages].map(([folder, file]) => [folder, file]), ...files.routes.map((file) => [folderOf(host, dir, file), file])];
115
+ for (const [folder, file] of answers) {
116
+ const url = folderUrl(folder);
117
+ const other = byUrl.get(url);
118
+ if (other && other.folder !== folder) problems.push(`two routes answer ${url}: ${other.file} and ${file}. Move one to another path.`);
119
+ else byUrl.set(url, { folder, file });
120
+ }
98
121
  for (const loader of files.loaders) {
99
122
  const folder = folderOf(host, dir, loader);
100
123
  if (files.pages.has(folder)) continue;
@@ -103,6 +126,9 @@ export function serverConflicts(host, dir, files) {
103
126
  `${loader} ${beside ? "sits next to a route.* API endpoint (endpoints take a Request; loaders feed pages)" : "has no sibling page.* to feed"}.`,
104
127
  );
105
128
  }
129
+ for (const loader of files.layoutLoaders ?? []) {
130
+ if (!files.layouts?.has(folderOf(host, dir, loader))) problems.push(`${loader} has no sibling layout.* to feed.`);
131
+ }
106
132
  return problems;
107
133
  }
108
134
 
@@ -116,12 +142,14 @@ export function serverConflicts(host, dir, files) {
116
142
  * exports `render` (the render API static generation needs) and
117
143
  * `createPageRenderer({ shell, baseUrl })`, a `renderPage` step built on
118
144
  * `renderDocument`. `drafts: false` leaves unpublished Markdown pages out.
145
+ * `hydrate: false` serves rendered pages without the `data-afw-hydrate` marker, for a
146
+ * dev loop whose browser build cannot adopt server DOM.
119
147
  *
120
148
  * @param {{ exclude?: string[], i18n?: { locales: string[], defaultLocale?: string } | null,
121
- * pages?: boolean, drafts?: boolean }} [options]
149
+ * pages?: boolean, drafts?: boolean, hydrate?: boolean }} [options]
122
150
  * @returns {Promise<{ code: string, files: string[] }>}
123
151
  */
124
- export async function serverModule(host, root, { exclude = [], i18n = null, pages = false, drafts = true, listExports } = {}) {
152
+ export async function serverModule(host, root, { exclude = [], i18n = null, pages = false, drafts = true, hydrate = true, listExports } = {}) {
125
153
  const files = await discoverServerFiles(host, root, { exclude });
126
154
  const problems = serverConflicts(host, root, files);
127
155
  if (problems.length) throw new Error(`AFW server routes:\n ${problems.join("\n ")}`);
@@ -129,7 +157,9 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
129
157
  imports: list.map((p, i) => `import * as ${prefix}${i} from ${JSON.stringify(p)};`).join("\n"),
130
158
  map: list.map((p, i) => ` [${JSON.stringify(p)}]: ${prefix}${i},`).join("\n"),
131
159
  });
132
- const r = group(files.routes, "r"), m = group(files.middleware, "m"), l = group(files.loaders, "l");
160
+ const r = group(files.routes, "r"), m = group(files.middleware, "m"), l = group([...files.loaders, ...files.layoutLoaders], "l");
161
+ // Every page route, so a page beneath a layout.loader.* matches without a loader of its own.
162
+ const pageRoutes = [...files.pages.keys()].map((folder) => (folder ? `/${folder}` : "/")).sort();
133
163
  const options = { appDir: root };
134
164
  if (i18n && Array.isArray(i18n.locales) && i18n.locales.length) {
135
165
  options.i18n = { locales: i18n.locales, defaultLocale: i18n.defaultLocale ?? i18n.locales[0] };
@@ -137,7 +167,19 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
137
167
  const pageFiles = pages ? await discoverPages(host, root, { exclude, drafts }) : [];
138
168
  // Server functions (docs/SERVER_FUNCTIONS.md): `listExports(file)` asks the compiler
139
169
  // which exports of a `.server` module are query()/action().
140
- const fns = listExports ? await serverFunctionTable(host, root, { exclude, listExports }) : { imports: "", table: "", files: [] };
170
+ const fns = listExports ? await serverFunctionTable(host, root, { exclude, listExports }) : { imports: "", table: "", files: [], endpoints: [] };
171
+ // A middleware folder inside a route group covers what the group holds — its pages'
172
+ // and API routes' folders, and its server functions' endpoints — not a URL prefix.
173
+ const groupScopes = {};
174
+ for (const file of files.middleware) {
175
+ const folder = folderOf(host, root, file);
176
+ if (!folder.split("/").some(isGroupSegment)) continue;
177
+ const scopes = [...files.pages.keys(), ...files.routes.map((f) => folderOf(host, root, f))]
178
+ .filter((f) => within(folder, f)).map((f) => `/${f}`);
179
+ const paths = fns.endpoints.filter(([f]) => within(folder, folderOf(host, root, f))).map(([, endpoint]) => endpoint);
180
+ groupScopes[`/${folder}`] = { scopes: [...new Set(scopes)].sort(), paths: paths.sort() };
181
+ }
182
+ if (Object.keys(groupScopes).length) options.groupScopes = groupScopes;
141
183
  const p = group(pageFiles, "p");
142
184
  const renderPart = pages
143
185
  ? `import { collectRoutePaths, configureI18n, registerRoutes, renderHead, renderRoute, resolveMetadata } from "@opentf/afw/server";\n` +
@@ -148,7 +190,9 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
148
190
  `export const render = { renderRoute, renderHead, collectRoutePaths, resolveMetadata };\n` +
149
191
  `/** A \`renderPage\` step: server-render page requests (\`GET\`/\`HEAD\`) into \`shell\`, the client's index.html. */\n` +
150
192
  `export function createPageRenderer({ shell: html, baseUrl = "" }) {\n` +
151
- ` const shell = stampHydrateSentinel(html);\n` +
193
+ // Without `hydrate` (a dev loop whose client is a CSR build) the page is still
194
+ // server-rendered, but not marked for adoption: the client builds it fresh.
195
+ ` const shell = ${hydrate ? "stampHydrateSentinel(html)" : "html"};\n` +
152
196
  ` return async (request, { locals = {} } = {}) => {\n` +
153
197
  ` const method = request.method.toUpperCase();\n` +
154
198
  ` if (method !== "GET" && method !== "HEAD") return null;\n` +
@@ -156,7 +200,7 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
156
200
  ` let doc;\n` +
157
201
  ` try {\n` +
158
202
  ` doc = await renderDocument(render, {\n` +
159
- ` shell, url: url.pathname, search: url.search, loaders, baseUrl, i18n: options.i18n ?? null,\n` +
203
+ ` shell, url: url.pathname, search: url.search, loaders, baseUrl, i18n: options.i18n ?? null, errors: "render",\n` +
160
204
  ` loaderContext: { request, query: Object.fromEntries(url.searchParams), locals },\n` +
161
205
  ` });\n` +
162
206
  ` } catch (e) {\n` +
@@ -180,9 +224,13 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
180
224
  `export const apiHandler = createApiHandler(routeModules, middlewareModules, options);\n` +
181
225
  `export const apiRoutes = createApiHandler(routeModules, {}, options);\n` +
182
226
  `export const middleware = createMiddleware(middlewareModules, options);\n` +
183
- `export const loaders = createLoaderRegistry(loaderModules, options);\n` +
227
+ `export const loaders = createLoaderRegistry(loaderModules, { ...options, pageRoutes: ${JSON.stringify(pageRoutes)} });\n` +
184
228
  `export const serverFunctions = createServerFunctions({\n${fns.table}\n});\n` +
185
- `export const loaderRoutes = ${JSON.stringify(loaderRoutePatterns(host, root, files.loaders))};\n` +
229
+ `export const loaderRoutes = ${JSON.stringify(loaderPageRoutes({
230
+ pages: pageRoutes,
231
+ pageLoaders: loaderRoutePatterns(host, root, files.loaders),
232
+ layoutLoaders: loaderRoutePatterns(host, root, files.layoutLoaders),
233
+ }))};\n` +
186
234
  renderPart +
187
235
  `/**\n` +
188
236
  ` * A Fetch handler. Inside the middleware: API routes, loader data (\`<path>/__data.json\`),\n` +
@@ -200,7 +248,7 @@ export async function serverModule(host, root, { exclude = [], i18n = null, page
200
248
  ` };\n` +
201
249
  ` return createFetchHandler(terminal, { middleware, fallback });\n` +
202
250
  `}\n`;
203
- return { code, files: [...files.routes, ...files.middleware, ...files.loaders, ...pageFiles, ...fns.files] };
251
+ return { code, files: [...files.routes, ...files.middleware, ...files.loaders, ...files.layoutLoaders, ...pageFiles, ...fns.files] };
204
252
  }
205
253
 
206
254
  function loaderRoutePatterns(host, root, loaders) {