@canonical/summon-application 0.33.0 → 0.35.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.
Files changed (88) hide show
  1. package/README.md +9 -9
  2. package/dist/esm/application/react/index.js +403 -277
  3. package/dist/esm/application/react/index.js.map +1 -1
  4. package/dist/esm/application/react/templates/.storybook/decorators/index.ts.ejs +4 -0
  5. package/dist/esm/application/react/templates/.storybook/decorators/withI18n.tsx +35 -0
  6. package/dist/esm/application/react/templates/.storybook/decorators/withRouter.tsx +18 -20
  7. package/dist/esm/application/react/templates/.storybook/preview.ts.ejs +35 -0
  8. package/dist/esm/application/react/templates/index.html.ejs +2 -1
  9. package/dist/esm/application/react/templates/package.json.ejs +34 -3
  10. package/dist/esm/application/react/templates/src/client/entry.tsx.ejs +109 -10
  11. package/dist/esm/application/react/templates/src/domains/account/{AccountPage.tsx → AccountPage.tsx.ejs} +13 -0
  12. package/dist/esm/application/react/templates/src/domains/account/LoginPage.tsx.ejs +51 -0
  13. package/dist/esm/application/react/templates/src/domains/account/routes.ts +21 -8
  14. package/dist/esm/application/react/templates/src/domains/catalog/CatalogPage.tsx.ejs +97 -0
  15. package/dist/esm/application/react/templates/src/domains/catalog/{ErrorBoundary.tests.tsx → ErrorBoundary.tests.tsx.ejs} +24 -0
  16. package/dist/esm/application/react/templates/src/domains/catalog/{ProductCard.tsx → ProductCard.tsx.ejs} +31 -0
  17. package/dist/esm/application/react/templates/src/domains/catalog/{ProductList.stories.tsx → ProductList.stories.tsx.ejs} +63 -4
  18. package/dist/esm/application/react/templates/src/domains/catalog/{ProductList.tests.tsx → ProductList.tests.tsx.ejs} +44 -0
  19. package/dist/esm/application/react/templates/src/domains/catalog/{ProductList.tsx → ProductList.tsx.ejs} +30 -2
  20. package/dist/esm/application/react/templates/src/domains/catalog/routes.ts +25 -0
  21. package/dist/esm/application/react/templates/src/domains/contact/{ContactPage.tsx → ContactPage.tsx.ejs} +40 -0
  22. package/dist/esm/application/react/templates/src/domains/marketing/GuidePage.tsx.ejs +33 -0
  23. package/dist/esm/application/react/templates/src/domains/marketing/{HomePage.tsx → HomePage.tsx.ejs} +30 -0
  24. package/dist/esm/application/react/templates/src/domains/marketing/routes.ts +25 -0
  25. package/dist/esm/application/react/templates/src/i18n/ar.ts +74 -0
  26. package/dist/esm/application/react/templates/src/i18n/catalogs.ts +14 -0
  27. package/dist/esm/application/react/templates/src/i18n/config.ts +19 -0
  28. package/dist/esm/application/react/templates/src/i18n/en.ts +73 -0
  29. package/dist/esm/application/react/templates/src/i18n/fr.ts +70 -0
  30. package/dist/esm/application/react/templates/src/i18n/index.ts +5 -0
  31. package/dist/esm/application/react/templates/src/i18n/negotiation.tests.ts +92 -0
  32. package/dist/esm/application/react/templates/src/lib/LocaleSelector/LocaleSelector.tests.tsx +60 -0
  33. package/dist/esm/application/react/templates/src/lib/LocaleSelector/LocaleSelector.tsx +44 -0
  34. package/dist/esm/application/react/templates/src/lib/LocaleSelector/index.ts +1 -0
  35. package/dist/esm/application/react/templates/src/lib/Navigation/Navigation.tsx.ejs +34 -0
  36. package/dist/esm/application/react/templates/src/lib/ThemeSelector/{ThemeSelector.tsx → ThemeSelector.tsx.ejs} +16 -0
  37. package/dist/esm/application/react/templates/src/lib/index.ts.ejs +3 -0
  38. package/dist/esm/application/react/templates/src/relay/environment.ts +153 -5
  39. package/dist/esm/application/react/templates/src/routes.tsx.ejs +137 -33
  40. package/dist/esm/application/react/templates/src/server/entry.tsx.ejs +293 -11
  41. package/dist/esm/application/react/templates/src/server/preview.bun.ts +30 -7
  42. package/dist/esm/application/react/templates/src/server/preview.express.ts +19 -4
  43. package/dist/esm/application/react/templates/src/server/renderer.tsx.ejs +125 -0
  44. package/dist/esm/application/react/templates/src/server/{server.bun.ts → server.bun.ts.ejs} +56 -4
  45. package/dist/esm/application/react/templates/src/server/{server.express.ts → server.express.ts.ejs} +48 -4
  46. package/dist/esm/application/react/templates/test/e2e/servers.e2e.ts.ejs +197 -0
  47. package/dist/esm/application/react/templates/tsconfig.json.ejs +3 -0
  48. package/dist/esm/application/react/templates/vite.config.ts.ejs +5 -0
  49. package/dist/esm/domain/index.js +8 -1
  50. package/dist/esm/domain/index.js.map +1 -1
  51. package/dist/esm/route/index.js +12 -2
  52. package/dist/esm/route/index.js.map +1 -1
  53. package/dist/esm/route/insertRoute.js +39 -11
  54. package/dist/esm/route/insertRoute.js.map +1 -1
  55. package/dist/esm/shared/packageName.js +7 -0
  56. package/dist/esm/shared/packageName.js.map +1 -0
  57. package/dist/esm/shared/packageVersion.js +50 -0
  58. package/dist/esm/shared/packageVersion.js.map +1 -0
  59. package/dist/esm/shared/validators.js +61 -0
  60. package/dist/esm/shared/validators.js.map +1 -0
  61. package/dist/esm/shared/versions.js +87 -55
  62. package/dist/esm/shared/versions.js.map +1 -1
  63. package/dist/esm/shared/workspace.js +57 -0
  64. package/dist/esm/shared/workspace.js.map +1 -1
  65. package/dist/esm/wrapper/index.js +8 -1
  66. package/dist/esm/wrapper/index.js.map +1 -1
  67. package/dist/types/application/react/index.d.ts +1 -2
  68. package/dist/types/application/react/index.d.ts.map +1 -1
  69. package/dist/types/domain/index.d.ts.map +1 -1
  70. package/dist/types/route/index.d.ts.map +1 -1
  71. package/dist/types/shared/packageName.d.ts +7 -0
  72. package/dist/types/shared/packageName.d.ts.map +1 -0
  73. package/dist/types/shared/packageVersion.d.ts +15 -0
  74. package/dist/types/shared/packageVersion.d.ts.map +1 -0
  75. package/dist/types/shared/validators.d.ts +21 -0
  76. package/dist/types/shared/validators.d.ts.map +1 -0
  77. package/dist/types/shared/versions.d.ts +14 -5
  78. package/dist/types/shared/versions.d.ts.map +1 -1
  79. package/dist/types/shared/workspace.d.ts.map +1 -1
  80. package/dist/types/wrapper/index.d.ts.map +1 -1
  81. package/package.json +8 -8
  82. package/dist/esm/application/react/templates/.storybook/decorators/index.ts +0 -1
  83. package/dist/esm/application/react/templates/.storybook/preview.ts +0 -10
  84. package/dist/esm/application/react/templates/src/domains/account/LoginPage.tsx +0 -27
  85. package/dist/esm/application/react/templates/src/domains/catalog/CatalogPage.tsx +0 -50
  86. package/dist/esm/application/react/templates/src/domains/marketing/GuidePage.tsx +0 -17
  87. package/dist/esm/application/react/templates/src/server/renderer.tsx +0 -50
  88. package/dist/esm/application/react/templates/test/e2e/servers.e2e.ts +0 -99
@@ -1,50 +1,316 @@
1
+ <% if (intl) { -%>
2
+ import { documentAttrs, isSupportedLocale } from "@canonical/i18n-core";
3
+ import { I18nProvider } from "@canonical/i18n-react";
4
+ <% } -%>
1
5
  import { HeadProvider } from "@canonical/react-head";
2
6
  import type { ServerEntrypointProps } from "@canonical/react-ssr/renderer";
3
- import { createStaticRouter } from "@canonical/router-core";
7
+ import {
8
+ createRouter,
9
+ createServerAdapter,
10
+ StatusResponse,
11
+ } from "@canonical/router-core";
4
12
  import { Outlet, RouterProvider } from "@canonical/router-react";
5
13
  <% if (relay) { -%>
6
- import { RelayEnvironmentProvider } from "react-relay";
14
+ import { fetchQuery, RelayEnvironmentProvider } from "react-relay";
15
+ <% } -%>
16
+ <% if (intl) { -%>
17
+ import { catalogs, i18nConfig } from "#i18n/index.js";
18
+ <% } -%>
19
+ <% if (relay) { -%>
7
20
  import { createEnvironment } from "#relay/environment.js";
8
21
  <% } -%>
9
- import { appRoutes, middleware, notFoundRoute } from "../routes.js";
22
+ import {
23
+ appRoutes,
24
+ getAuthRedirectForMatch,
25
+ middleware,
26
+ notFoundRoute,
27
+ <% if (relay) { -%>
28
+ resolveRelayPayloads,
29
+ <% } -%>
30
+ type SerializedRelayPayload,
31
+ <% if (relay) { -%>
32
+ serverQueries,
33
+ <% } -%>
34
+ } from "../routes.js";
10
35
  import "#styles/app.css";
11
36
 
12
37
  interface InitialData extends Record<string, unknown> {
13
38
  readonly url?: string;
14
39
  /** Colour-scheme preference resolved from the request cookie, if any. */
15
40
  readonly theme?: "light" | "dark";
41
+ /**
42
+ * Flat dehydrated router state (from resolveRouteDisposition), read back by
43
+ * router-react's readDehydratedState() on the client. Absent in SPA cells.
44
+ */
45
+ readonly href?: string;
46
+ readonly kind?: "route" | "not-found";
47
+ readonly routeId?: string | null;
48
+ readonly status?: number;
49
+ /**
50
+ * Server-captured GraphQL responses for the matched route (see
51
+ * `prefetchRouteData`), replayed into the Relay store on both the server
52
+ * render and the client. A dedicated nested key — the router state is
53
+ * flat-spread into this same object, so nesting avoids any collision.
54
+ */
55
+ readonly relayPayloads?: readonly SerializedRelayPayload[];
56
+ <% if (intl) { -%>
57
+ /** Locale negotiated from the request cookie / Accept-Language, if any. */
58
+ readonly locale?: string;
59
+ <% } -%>
60
+ }
61
+
62
+ /** How the server should answer a request for this URL. */
63
+ export type RouteDisposition =
64
+ | {
65
+ readonly kind: "render";
66
+ readonly status: number;
67
+ readonly dehydratedState: {
68
+ readonly href: string;
69
+ readonly kind: "route" | "not-found";
70
+ readonly routeId: string | null;
71
+ readonly status: number;
72
+ } | null;
73
+ }
74
+ | {
75
+ readonly kind: "redirect";
76
+ readonly status: number;
77
+ readonly location: string;
78
+ };
79
+
80
+ // A module-scope adapterless router is a pure matcher: without an adapter,
81
+ // construction fires no load and no warm hooks, and match() runs no hooks at
82
+ // all. Never use a server-adapter router here — it warms at construction.
83
+ const dispositionMatcher = createRouter(appRoutes, {
84
+ middleware: [...middleware],
85
+ notFound: notFoundRoute,
86
+ });
87
+
88
+ /**
89
+ * Resolve a request URL to the HTTP answer the router implies: a redirect
90
+ * (auth guard or a static redirect route) or a render with the matched
91
+ * document's real status — a matched not-found page is a 404 response, not a
92
+ * soft 200.
93
+ */
94
+ export function resolveRouteDisposition(url: string): RouteDisposition {
95
+ let matchResult: ReturnType<typeof dispositionMatcher.match>;
96
+
97
+ try {
98
+ matchResult = dispositionMatcher.match(url);
99
+ } catch (error) {
100
+ // A rejected search schema is a client error; render the shell with the
101
+ // error status and let the client router re-derive the same state.
102
+ return {
103
+ kind: "render",
104
+ status: error instanceof StatusResponse ? error.status : 500,
105
+ dehydratedState: null,
106
+ };
107
+ }
108
+
109
+ if (matchResult?.kind === "redirect") {
110
+ return {
111
+ kind: "redirect",
112
+ status: matchResult.status,
113
+ location: matchResult.redirectTo,
114
+ };
115
+ }
116
+
117
+ // Auth is decided from the router's own match (pattern + validated search),
118
+ // never from the raw URL — the two normalize differently.
119
+ const authRedirect =
120
+ matchResult?.kind === "route" ? getAuthRedirectForMatch(matchResult) : null;
121
+
122
+ if (authRedirect) {
123
+ return { kind: "redirect", status: 302, location: authRedirect };
124
+ }
125
+
126
+ const status = matchResult?.status ?? 404;
127
+
128
+ return {
129
+ kind: "render",
130
+ status,
131
+ dehydratedState: {
132
+ href: url,
133
+ kind: matchResult?.kind === "route" ? "route" : "not-found",
134
+ routeId: matchResult?.kind === "route" ? String(matchResult.name) : null,
135
+ status,
136
+ },
137
+ };
138
+ }
139
+
140
+ /**
141
+ * Execute the matched route's declared server query (if any) and return the
142
+ * captured responses in serializable form. Fetch-then-render: the payloads
143
+ * exist before the renderer is constructed, so they ride the fixed
144
+ * `__INITIAL_DATA__` bootstrap script. On any failure the request degrades —
145
+ * render without payloads, the client fetches after hydration — a data
146
+ * hiccup must never take the page down.
147
+ */
148
+ const SSR_PREFETCH_TIMEOUT_MS = 5_000;
149
+
150
+ export async function prefetchRouteData(
151
+ disposition: RouteDisposition,
152
+ ): Promise<readonly SerializedRelayPayload[] | undefined> {
153
+ <% if (relay) { -%>
154
+ if (disposition.kind !== "render") {
155
+ return undefined;
156
+ }
157
+
158
+ const routeId = disposition.dehydratedState?.routeId;
159
+ const serverQuery = routeId
160
+ ? serverQueries[routeId as keyof typeof serverQueries]
161
+ : undefined;
162
+
163
+ if (!serverQuery) {
164
+ return undefined;
165
+ }
166
+
167
+ const captured: SerializedRelayPayload[] = [];
168
+
169
+ try {
170
+ // A fresh, request-scoped environment: nothing leaks across requests,
171
+ // and the capture tee records exactly the responses this route needs.
172
+ const environment = createEnvironment({
173
+ captureResponse: (entry) => {
174
+ captured.push(entry);
175
+ },
176
+ });
177
+
178
+ // Bound the prefetch: an endpoint that never settles must not hold the
179
+ // whole SSR response hostage. On timeout the subscription is cancelled
180
+ // and rendering proceeds without payloads.
181
+ await new Promise<void>((resolve, reject) => {
182
+ const timer = setTimeout(() => {
183
+ subscription.unsubscribe();
184
+ reject(
185
+ new Error(
186
+ `SSR data prefetch exceeded ${SSR_PREFETCH_TIMEOUT_MS}ms`,
187
+ ),
188
+ );
189
+ }, SSR_PREFETCH_TIMEOUT_MS);
190
+ const subscription = fetchQuery(
191
+ environment,
192
+ serverQuery.query,
193
+ serverQuery.variables,
194
+ { fetchPolicy: "network-only" },
195
+ ).subscribe({
196
+ complete: () => {
197
+ clearTimeout(timer);
198
+ resolve();
199
+ },
200
+ error: (error: unknown) => {
201
+ clearTimeout(timer);
202
+ reject(error);
203
+ },
204
+ });
205
+ });
206
+ } catch (error) {
207
+ console.warn(
208
+ "SSR data prefetch failed; rendering without payloads (the client will fetch).",
209
+ error,
210
+ );
211
+
212
+ return undefined;
213
+ }
214
+
215
+ return captured.length > 0 ? captured : undefined;
216
+ <% } else { -%>
217
+ // No data layer scaffolded: nothing to prefetch, every route renders
218
+ // without payloads. The uniform signature keeps the server files (plain
219
+ // copies shared by all flag combinations) unconditional.
220
+ void disposition;
221
+
222
+ return undefined;
223
+ <% } -%>
16
224
  }
17
225
 
18
226
  export default function EntryServer(props: ServerEntrypointProps<InitialData>) {
19
227
  const initialData = props.initialData ?? {};
20
228
  const url = initialData.url ?? "/";
21
- const router = createStaticRouter(appRoutes, url, {
229
+ const router = createRouter(appRoutes, {
22
230
  middleware: [...middleware],
23
231
  notFound: notFoundRoute,
232
+ adapter: createServerAdapter(url),
24
233
  });
234
+ // A rejected search schema throws from match(); resolveRouteDisposition
235
+ // already turned that into the response status (400-class), so render the
236
+ // shell unhydrated instead of letting the throw reach React — a shell
237
+ // error would override the supplied status with 500. The client router
238
+ // re-derives the same error state on load.
239
+ let serverMatch: ReturnType<typeof router.match>;
240
+
241
+ try {
242
+ serverMatch = router.match(url);
243
+ } catch {
244
+ serverMatch = null;
245
+ }
246
+
247
+ // Hydrate the store synchronously so render() works without awaiting
248
+ // load(). Redirects and unmatched URLs are the server's concern before
249
+ // rendering, so only real matches hydrate.
250
+ if (serverMatch?.kind === "route" || serverMatch?.kind === "not-found") {
251
+ router.hydrate({
252
+ href: url,
253
+ kind: serverMatch.kind,
254
+ routeId: serverMatch.kind === "route" ? serverMatch.name : null,
255
+ status: serverMatch.status,
256
+ });
257
+ }
25
258
  <% if (relay) { -%>
26
259
 
27
260
  // A fresh Relay environment per server render, so no store state leaks
28
- // between requests. Nothing fetches through it yet: components that issue
29
- // queries are wrapped in `ClientOnly` (see CatalogPage) until data
30
- // serialization/hydration is supported; the provider is here so any
31
- // component touching Relay context renders without branching on runtime.
32
- const relayEnvironment = createEnvironment();
261
+ // between requests — seeded with the same serialized payloads the client
262
+ // will replay, so server markup and first client render read identical
263
+ // data. Without payloads (no server query, or the prefetch failed) a
264
+ // querying component suspends and fetches through this request's own
265
+ // environment instead.
266
+ const relayEnvironment = createEnvironment({
267
+ payloads: resolveRelayPayloads(initialData.relayPayloads),
268
+ });
33
269
  <% } -%>
34
270
 
271
+ <% if (intl) { -%>
272
+ // The servers negotiate the locale (cookie > Accept-Language > default,
273
+ // via i18n-core's negotiateLocale) and pass it through initialData; the
274
+ // same value reaches the client via `window.__INITIAL_DATA__`, so the
275
+ // server markup and the first client render agree on the language.
276
+ const locale = isSupportedLocale(i18nConfig, initialData.locale)
277
+ ? initialData.locale
278
+ : i18nConfig.defaultLocale;
279
+ // `<html lang dir>` must be right on first paint for assistive technology
280
+ // and RTL locales; after hydration the client's locale source keeps both
281
+ // attributes in sync with every switch.
282
+ const { lang, dir } = documentAttrs(i18nConfig, locale);
283
+
284
+ <% } -%>
35
285
  // Paint the cookie-resolved theme on <html> for a flash-free first render —
36
286
  // the same element `usePreferredTheme` toggles on the client, and one React
37
287
  // does not hydrate (only `#root` is), so there is no mismatch to reconcile.
38
288
  <% if (relay) { -%>
39
289
  return (
290
+ <% if (intl) { -%>
291
+ <html lang={lang} dir={dir} className={initialData.theme}>
292
+ <% } else { -%>
40
293
  <html lang={props.lang} className={initialData.theme}>
294
+ <% } -%>
41
295
  <head>
42
296
  {props.otherHeadElements}
43
297
  {props.scriptElements}
44
298
  {props.linkElements}
45
299
  </head>
46
- <body>
300
+ {/* Surface declaration: context (app) + density (comfortable) — roots the design system's --density-* channel */}
301
+ <body className="app comfortable">
47
302
  <div id="root">
303
+ <% if (intl) { -%>
304
+ <I18nProvider config={i18nConfig} catalogs={catalogs} locale={locale}>
305
+ <HeadProvider>
306
+ <RelayEnvironmentProvider environment={relayEnvironment}>
307
+ <RouterProvider router={router}>
308
+ <Outlet fallback={<p>Loading…</p>} />
309
+ </RouterProvider>
310
+ </RelayEnvironmentProvider>
311
+ </HeadProvider>
312
+ </I18nProvider>
313
+ <% } else { -%>
48
314
  <HeadProvider>
49
315
  <RelayEnvironmentProvider environment={relayEnvironment}>
50
316
  <RouterProvider router={router}>
@@ -52,25 +318,41 @@ export default function EntryServer(props: ServerEntrypointProps<InitialData>) {
52
318
  </RouterProvider>
53
319
  </RelayEnvironmentProvider>
54
320
  </HeadProvider>
321
+ <% } -%>
55
322
  </div>
56
323
  </body>
57
324
  </html>
58
325
  );
59
326
  <% } else { -%>
60
327
  return (
328
+ <% if (intl) { -%>
329
+ <html lang={lang} dir={dir} className={initialData.theme}>
330
+ <% } else { -%>
61
331
  <html lang={props.lang} className={initialData.theme}>
332
+ <% } -%>
62
333
  <head>
63
334
  {props.otherHeadElements}
64
335
  {props.scriptElements}
65
336
  {props.linkElements}
66
337
  </head>
67
- <body>
338
+ {/* Surface declaration: context (app) + density (comfortable) — roots the design system's --density-* channel */}
339
+ <body className="app comfortable">
68
340
  <div id="root">
341
+ <% if (intl) { -%>
342
+ <I18nProvider config={i18nConfig} catalogs={catalogs} locale={locale}>
343
+ <HeadProvider>
344
+ <RouterProvider router={router}>
345
+ <Outlet fallback={<p>Loading…</p>} />
346
+ </RouterProvider>
347
+ </HeadProvider>
348
+ </I18nProvider>
349
+ <% } else { -%>
69
350
  <HeadProvider>
70
351
  <RouterProvider router={router}>
71
352
  <Outlet fallback={<p>Loading…</p>} />
72
353
  </RouterProvider>
73
354
  </HeadProvider>
355
+ <% } -%>
74
356
  </div>
75
357
  </body>
76
358
  </html>
@@ -39,6 +39,14 @@ import createSitemapRenderer from "../../dist/server/sitemap.js";
39
39
  type CreateAppRenderer = typeof import("./renderer.js").default;
40
40
  type CreateSitemapRenderer = typeof import("../sitemap/renderer.js").default;
41
41
 
42
+ // Match Node's semantics for unhandled rejections: warn, don't die. Bun
43
+ // kills the process by default, and a data-layer library's internal floating
44
+ // promise (e.g. a failed GraphQL fetch teed inside its pipeline) must take
45
+ // down a request, never the server.
46
+ process.on("unhandledRejection", (reason) => {
47
+ console.error("Unhandled rejection (server kept alive):", reason);
48
+ });
49
+
42
50
  const PORT = Number(process.env.PORT) || 5174;
43
51
  const staticMount = parseStaticPair(":dist/client");
44
52
 
@@ -63,15 +71,30 @@ Bun.serve({
63
71
  }
64
72
  }
65
73
 
66
- const renderer =
67
- url.pathname === "/sitemap.xml"
68
- ? (createSitemapRenderer as CreateSitemapRenderer)()
69
- : (createAppRenderer as CreateAppRenderer)(req);
70
- const stream = await renderer.renderToReadableStream(req.signal);
74
+ if (url.pathname === "/sitemap.xml") {
75
+ const renderer = (createSitemapRenderer as CreateSitemapRenderer)();
76
+ const stream = await renderer.renderToReadableStream(req.signal);
77
+
78
+ return new Response(stream, {
79
+ status: renderer.statusCode,
80
+ headers: { "Content-Type": renderer.contentType },
81
+ });
82
+ }
83
+
84
+ const appResult = await (createAppRenderer as CreateAppRenderer)(req);
85
+
86
+ if (appResult.kind === "redirect") {
87
+ return new Response(null, {
88
+ status: appResult.status,
89
+ headers: { location: appResult.location },
90
+ });
91
+ }
92
+
93
+ const stream = await appResult.renderer.renderToReadableStream(req.signal);
71
94
 
72
95
  return new Response(stream, {
73
- status: renderer.statusCode,
74
- headers: { "Content-Type": renderer.contentType },
96
+ status: appResult.renderer.statusCode,
97
+ headers: { "Content-Type": appResult.renderer.contentType },
75
98
  });
76
99
  },
77
100
  });
@@ -49,10 +49,25 @@ app.use(express.static("dist/client", { index: false }));
49
49
 
50
50
  app.use(async (req, res, next) => {
51
51
  try {
52
- const renderer =
53
- req.path === "/sitemap.xml"
54
- ? (createSitemapRenderer as CreateSitemapRenderer)()
55
- : (createAppRenderer as CreateAppRenderer)(req);
52
+ if (req.path === "/sitemap.xml") {
53
+ const renderer = (createSitemapRenderer as CreateSitemapRenderer)();
54
+ const result = renderer.renderToPipeableStream();
55
+
56
+ await renderer.statusReady;
57
+ res.status(renderer.statusCode);
58
+ res.setHeader("content-type", renderer.contentType);
59
+ result.pipe(res);
60
+ return;
61
+ }
62
+
63
+ const appResult = await (createAppRenderer as CreateAppRenderer)(req);
64
+
65
+ if (appResult.kind === "redirect") {
66
+ res.redirect(appResult.status, appResult.location);
67
+ return;
68
+ }
69
+
70
+ const renderer = appResult.renderer;
56
71
  const result = renderer.renderToPipeableStream();
57
72
 
58
73
  await renderer.statusReady;
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Compiled JSX app renderer for production / preview.
3
+ *
4
+ * Read once at module load, the built `dist/client/index.html` shell carries
5
+ * the hashed `<script>`/`<link>` tags Vite injected at build time; the renderer
6
+ * extracts them and injects them into the streamed output.
7
+ *
8
+ * This is one Lego brick — a pure renderer. It knows nothing about routing or
9
+ * about the sitemap renderer; it just turns a request into the rendered app.
10
+ * The server (`src/server/index.ts` for preview, `server.bun.ts` /
11
+ * `server.express.ts` for dev) is what looks at the URL and picks a renderer.
12
+ *
13
+ * It reuses the same `EntryServer` (`src/server/entry.tsx`) the dev servers
14
+ * load via `ssrLoadModule` — the renderer is the invariant across dev and
15
+ * production; only the HTML shell source differs.
16
+ */
17
+ import fs from "node:fs";
18
+ import type { IncomingMessage } from "node:http";
19
+ import path from "node:path";
20
+ <% if (intl) { -%>
21
+ import { negotiateLocale } from "@canonical/i18n-core";
22
+ <% } -%>
23
+ import { extractPreferences } from "@canonical/react-hooks";
24
+ import { JSXRenderer } from "@canonical/react-ssr/renderer";
25
+ import { getRequestUrl } from "@canonical/react-ssr/server";
26
+ <% if (intl) { -%>
27
+ import { i18nConfig } from "#i18n/config.js";
28
+ <% } -%>
29
+ import EntryServer, {
30
+ type InitialData,
31
+ prefetchRouteData,
32
+ type RouteDisposition,
33
+ resolveRouteDisposition,
34
+ } from "./entry.js";
35
+
36
+ const htmlString = fs.readFileSync(
37
+ path.join(process.cwd(), "dist", "client", "index.html"),
38
+ "utf-8",
39
+ );
40
+
41
+ /** Read the `Cookie` header from either a Web `Request` or a Node request. */
42
+ function cookieHeader(request: Request | IncomingMessage): string | null {
43
+ return typeof (request as Request).headers?.get === "function"
44
+ ? (request as Request).headers.get("cookie")
45
+ : ((request as IncomingMessage).headers?.cookie ?? null);
46
+ }
47
+
48
+ <% if (intl) { -%>
49
+ /** Read the `Accept-Language` header from a Web `Request` or a Node request. */
50
+ function acceptLanguageHeader(
51
+ request: Request | IncomingMessage,
52
+ ): string | null {
53
+ if (typeof (request as Request).headers?.get === "function") {
54
+ return (request as Request).headers.get("accept-language");
55
+ }
56
+ const header = (request as IncomingMessage).headers?.["accept-language"];
57
+ // Node joins repeated header lines for most headers but can surface arrays;
58
+ // negotiation expects the single comma-separated wire format.
59
+ return Array.isArray(header) ? header.join(",") : (header ?? null);
60
+ }
61
+
62
+ <% } -%>
63
+ /**
64
+ * Per-request factory for the JSX app renderer. Accepts either a Web `Request`
65
+ * (`serve-bun`) or a Node `IncomingMessage` (`serve-express`); it derives the
66
+ * URL for routing and the cookie-backed theme so the first paint matches the
67
+ * user's preference, passing both as the renderer's initial data.
68
+ */
69
+ /** The app renderer's answer: a stream renderer, or an HTTP redirect. */
70
+ export type AppRendererResult =
71
+ | {
72
+ readonly kind: "render";
73
+ readonly renderer: JSXRenderer<typeof EntryServer, InitialData>;
74
+ }
75
+ | Extract<RouteDisposition, { kind: "redirect" }>;
76
+
77
+ export default async function createAppRenderer(
78
+ request: Request | IncomingMessage,
79
+ ): Promise<AppRendererResult> {
80
+ <% if (intl) { -%>
81
+ const cookie = cookieHeader(request);
82
+ const { theme } = extractPreferences(cookie);
83
+ const locale = negotiateLocale(i18nConfig, {
84
+ cookieHeader: cookie,
85
+ acceptLanguage: acceptLanguageHeader(request),
86
+ });
87
+ <% } else { -%>
88
+ const { theme } = extractPreferences(cookieHeader(request));
89
+ <% } -%>
90
+ const url = getRequestUrl(request);
91
+ const disposition = resolveRouteDisposition(url ?? "/");
92
+
93
+ if (disposition.kind === "redirect") {
94
+ return disposition;
95
+ }
96
+
97
+ // Fetch-then-render: the matched route's declared server query runs now so
98
+ // its captured responses can ride the bootstrap script (which is fixed at
99
+ // stream start). Absent or failed, the page renders and the client fetches.
100
+ const relayPayloads = await prefetchRouteData(disposition);
101
+
102
+ const initialData: InitialData = {
103
+ url,
104
+ theme: theme === "light" || theme === "dark" ? theme : undefined,
105
+ <% if (intl) { -%>
106
+ locale,
107
+ <% } -%>
108
+ ...(relayPayloads ? { relayPayloads } : {}),
109
+ };
110
+
111
+ // Flat-spread the dehydrated router state into the page payload; the client
112
+ // reads it back with readDehydratedState() and resumes the server match.
113
+ Object.assign(initialData, disposition.dehydratedState ?? {});
114
+
115
+ return {
116
+ kind: "render",
117
+ renderer: new JSXRenderer(EntryServer, initialData, {
118
+ htmlString,
119
+ <% if (intl) { -%>
120
+ defaultLocale: locale,
121
+ <% } -%>
122
+ statusCode: disposition.status,
123
+ }),
124
+ };
125
+ }
@@ -29,6 +29,14 @@ import * as process from "node:process";
29
29
  import { viteFetchMiddleware } from "@canonical/react-ssr/server";
30
30
  import { createServer as createViteServer } from "vite";
31
31
 
32
+ // Match Node's semantics for unhandled rejections: warn, don't die. Bun
33
+ // kills the process by default, and a data-layer library's internal floating
34
+ // promise (e.g. a failed GraphQL fetch teed inside its pipeline) must take
35
+ // down a request, never the server.
36
+ process.on("unhandledRejection", (reason) => {
37
+ console.error("Unhandled rejection (server kept alive):", reason);
38
+ });
39
+
32
40
  const PORT = Number(process.env.PORT) || 5174;
33
41
 
34
42
  const vite = await createViteServer({
@@ -65,17 +73,48 @@ Bun.serve({
65
73
  const template = fs.readFileSync("index.html", "utf-8");
66
74
  const html = await vite.transformIndexHtml(requestUrl, template);
67
75
 
68
- const { default: EntryServer } = await vite.ssrLoadModule(
69
- "/src/server/entry.tsx",
70
- );
76
+ const {
77
+ default: EntryServer,
78
+ prefetchRouteData,
79
+ resolveRouteDisposition,
80
+ } = await vite.ssrLoadModule("/src/server/entry.tsx");
81
+
82
+ const disposition = resolveRouteDisposition(requestUrl);
83
+
84
+ if (disposition.kind === "redirect") {
85
+ return new Response(null, {
86
+ status: disposition.status,
87
+ headers: { location: disposition.location },
88
+ });
89
+ }
90
+
91
+ // Fetch-then-render: run the matched route's declared server query so
92
+ // its captured responses ride the bootstrap script (fixed at stream
93
+ // start); absent or failed, the client fetches after hydration.
94
+ const relayPayloads = await prefetchRouteData(disposition);
71
95
  const { JSXRenderer } = await vite.ssrLoadModule(
72
96
  "@canonical/react-ssr/renderer",
73
97
  );
74
98
  const { extractPreferences } = await vite.ssrLoadModule(
75
99
  "@canonical/react-hooks",
76
100
  );
101
+ <% if (intl) { -%>
102
+ const { negotiateLocale } = await vite.ssrLoadModule(
103
+ "@canonical/i18n-core",
104
+ );
105
+ const { i18nConfig } = await vite.ssrLoadModule("/src/i18n/config.ts");
106
+ <% } -%>
77
107
 
108
+ <% if (intl) { -%>
109
+ const cookie = req.headers.get("cookie");
110
+ const { theme } = extractPreferences(cookie);
111
+ const locale = negotiateLocale(i18nConfig, {
112
+ cookieHeader: cookie,
113
+ acceptLanguage: req.headers.get("accept-language"),
114
+ });
115
+ <% } else { -%>
78
116
  const { theme } = extractPreferences(req.headers.get("cookie"));
117
+ <% } -%>
79
118
  const renderer = new JSXRenderer(
80
119
  EntryServer,
81
120
  // The cookie is client-controlled, so only the known theme values reach
@@ -84,8 +123,21 @@ Bun.serve({
84
123
  {
85
124
  url: requestUrl,
86
125
  theme: theme === "light" || theme === "dark" ? theme : undefined,
126
+ <% if (intl) { -%>
127
+ locale,
128
+ <% } -%>
129
+ ...(relayPayloads ? { relayPayloads } : {}),
130
+ ...(disposition.dehydratedState ?? {}),
131
+ },
132
+ <% if (intl) { -%>
133
+ {
134
+ htmlString: html,
135
+ defaultLocale: locale,
136
+ statusCode: disposition.status,
87
137
  },
88
- { htmlString: html },
138
+ <% } else { -%>
139
+ { htmlString: html, statusCode: disposition.status },
140
+ <% } -%>
89
141
  );
90
142
  const stream = await renderer.renderToReadableStream(req.signal);
91
143