@opentf/afw 0.37.0 → 0.38.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/server/render.js CHANGED
@@ -7,9 +7,15 @@
7
7
  // client router; here we resolve a route's page + layout chain to string
8
8
  // renderers and concatenate them, passing `children` as an HTML string.
9
9
 
10
+ import { DEV } from "../core/dev.js";
11
+ import { urlOf } from "../runtime/route-match.js";
12
+ import { routeErrorPayload } from "../runtime/route-data.js";
10
13
  import {
11
14
  layoutChain,
15
+ layoutFolders,
16
+ layoutWraps,
12
17
  matchRoute,
18
+ routeErrorSite,
13
19
  resolveModule,
14
20
  routes,
15
21
  setRouteState,
@@ -30,27 +36,56 @@ import { withRenderContext } from "./render-context.js";
30
36
  * prerender own the loader bundle) and is exposed to the page as `router.data`.
31
37
  * Returns `null` if there's no match and no 404 page.
32
38
  */
33
- export async function renderRoute(pathname, params = null, search = "", { data } = {}) {
39
+ export async function renderRoute(pathname, params = null, search = "", { data, error } = {}) {
34
40
  return withRenderContext({ route: {}, hydration: null }, () =>
35
- renderInContext(pathname, params, search, data));
41
+ renderInContext(pathname, params, search, data, error));
36
42
  }
37
43
 
38
- async function renderInContext(pathname, params, search, data) {
44
+ /**
45
+ * The error a page's `error.jsx` receives after a server-side failure. Production
46
+ * shows a generic message, so a loader's internals (a query, a hostname) never reach
47
+ * the page; development shows the real one.
48
+ */
49
+ function publicError(error) {
50
+ const status = Number.isInteger(error?.status) && error.status >= 400 ? error.status : 500;
51
+ const message = DEV && error?.message ? String(error.message) : "Something went wrong";
52
+ const out = Object.assign(new Error(message), { status });
53
+ if (error?.afwLayoutRoute) out.afwLayoutRoute = error.afwLayoutRoute;
54
+ return out;
55
+ }
56
+
57
+ async function renderInContext(pathname, params, search, data, failure) {
39
58
  const real = matchRoute(pathname);
40
- const match =
59
+ let match =
41
60
  real || (routes.notFound ? { entry: routes.notFound, params: {}, route: null } : null);
42
61
  if (!match) return null;
43
62
  if (params) match.params = params;
63
+ // A failed loader renders an `error.jsx` with status 500: the page's nearest one, or —
64
+ // when a layout's loader failed — the one above that layout, inside the layouts above
65
+ // it. No error file: the caller's error stands.
66
+ let error = null;
67
+ let broken = null;
68
+ if (failure !== undefined) {
69
+ broken = failure?.afwLayoutRoute ?? null;
70
+ const entry = routeErrorSite(match.route, broken).entry;
71
+ if (!entry) throw failure;
72
+ error = publicError(failure);
73
+ match = { ...match, entry };
74
+ }
44
75
 
45
76
  // Let a page reading `router.params`/`pathname`/`query`/`data` resolve to this route.
46
77
  setRouteState({ pathname, search, params: match.params, data });
47
78
 
48
79
  const query = Object.fromEntries(new URLSearchParams(search));
49
- const props = { params: match.params, query };
80
+ const props = error
81
+ ? { params: match.params, query, error, retry: () => {} }
82
+ : { params: match.params, query };
50
83
 
51
84
  // Import modules before collecting: module-level JSX must keep its inline
52
85
  // props rather than capture hydration ids belonging to just the first request.
53
- const chain = layoutChain(match.route);
86
+ const chain = broken
87
+ ? layoutFolders(match.route).filter((f) => f !== broken && layoutWraps(f, broken)).map((f) => routes.layouts[f])
88
+ : layoutChain(match.route);
54
89
  const [pageModule, ...layoutModules] = await Promise.all(
55
90
  [match.entry, ...chain].map(async entry => {
56
91
  const module = await resolveModule(entry);
@@ -86,6 +121,11 @@ async function renderInContext(pathname, params, search, data) {
86
121
  });
87
122
  // `route` is the matched *pattern* ("/docs/[slug]", null for the 404 fallback) — the
88
123
  // toolchain keys its per-route chunk manifest by it to emit `<link rel="modulepreload">`.
124
+ if (error) {
125
+ // The client reads this marker from the inline data and shows the same error view.
126
+ const dataJson = routeErrorPayload(error);
127
+ return { html, metadata, status: error.status, hydration, route: match.route, dataJson, error };
128
+ }
89
129
  return { html, metadata, status: real ? 200 : 404, hydration, route: match.route };
90
130
  }
91
131
 
@@ -113,7 +153,11 @@ function fillRoute(route, params) {
113
153
  if (!params || typeof params !== "object" || Array.isArray(params)) {
114
154
  throw new Error(`getStaticPaths for ${route}: params must be an object.`);
115
155
  }
116
- return route.replace(/\[(\.\.\.)?([^\]]+)\]/g, (_, rest, key) => {
156
+ // The URL, not the folder: route groups drop out. An optional segment
157
+ // (`[[lang]]`, `[[...rest]]`) left out of `params` (or undefined) drops out too.
158
+ const url = urlOf(route).replace(/\/\[\[(\.\.\.)?([^\]]+)\]\]/g, (whole, rest, key) =>
159
+ params[key] === undefined || (rest && Array.isArray(params[key]) && params[key].length === 0) ? "" : `/[${rest ?? ""}${key}]`);
160
+ return (url.replace(/\[(\.\.\.)?([^\]]+)\]/g, (_, rest, key) => {
117
161
  if (!Object.prototype.hasOwnProperty.call(params, key)) {
118
162
  throw new Error(`getStaticPaths for ${route}: missing parameter "${key}".`);
119
163
  }
@@ -124,7 +168,7 @@ function fillRoute(route, params) {
124
168
  return segments.map(segment => encodedSegment(segment, route, key)).join("/");
125
169
  }
126
170
  return encodedSegment(value, route, key);
127
- });
171
+ })) || "/";
128
172
  }
129
173
 
130
174
  /**
@@ -148,7 +192,7 @@ export async function collectRoutePaths() {
148
192
  }
149
193
  for (const route in routes.pages) {
150
194
  if (!route.includes("[")) {
151
- add(route, {}, route);
195
+ add(urlOf(route), {}, route);
152
196
  continue;
153
197
  }
154
198
  const ns = await resolveModule(routes.pages[route]);