create-ailk 0.46.5 → 0.47.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 (30) hide show
  1. package/component-catalog.json +90 -7
  2. package/dist/lib/env-catalog.js +4 -0
  3. package/package.json +3 -3
  4. package/templates/apps/api/.env.example +18 -0
  5. package/templates/apps/api/CLAUDE.md +7 -2
  6. package/templates/apps/api/src/__tests__/vercel-handler.test.ts +176 -2
  7. package/templates/apps/api/src/lib/__mocks__/prisma.ts +31 -0
  8. package/templates/apps/api/src/vercel-handler.ts +32 -2
  9. package/templates/apps/mcp/.env.example +8 -0
  10. package/templates/apps/mcp/CLAUDE.md +2 -2
  11. package/templates/apps/web/CLAUDE.md +31 -3
  12. package/templates/apps/web/app/[locale]/layout.tsx +98 -37
  13. package/templates/apps/web/app/llms.txt/__tests__/site-listing.test.ts +13 -3
  14. package/templates/apps/web/lib/__tests__/grid-read.test.ts +212 -0
  15. package/templates/apps/web/lib/__tests__/hub-read.test.ts +90 -0
  16. package/templates/apps/web/lib/__tests__/hub-site-config.test.ts +394 -10
  17. package/templates/apps/web/lib/__tests__/page-chrome-navigation.test.ts +194 -0
  18. package/templates/apps/web/lib/__tests__/pricing-page.test.ts +210 -0
  19. package/templates/apps/web/lib/__tests__/site-identity-feature-list.test.ts +19 -1
  20. package/templates/apps/web/lib/__tests__/site-navigation.test.ts +288 -0
  21. package/templates/apps/web/lib/grid-read.ts +115 -0
  22. package/templates/apps/web/lib/hub-read.ts +35 -0
  23. package/templates/apps/web/lib/hub-site-config.ts +154 -29
  24. package/templates/apps/web/lib/in-page-blocks.ts +11 -67
  25. package/templates/apps/web/lib/in-page-magnet.ts +5 -24
  26. package/templates/apps/web/lib/page-chrome.ts +70 -3
  27. package/templates/apps/web/lib/pricing-page.ts +33 -2
  28. package/templates/apps/web/lib/site-navigation.ts +208 -0
  29. package/templates/apps/web/next.config.mjs +19 -6
  30. package/versions.json +51 -51
@@ -1,38 +1,71 @@
1
1
  /**
2
2
  * The hub read of the site's identity and seo (#11456, spec
3
- * docs/specs/11456-a-hub-connected-site-reads-spec.md D3).
3
+ * docs/specs/11456-a-hub-connected-site-reads-spec.md D3; #12390, spec
4
+ * docs/specs/12390-a-single-tenant-site-shows-what-its-admin-saves-spec.md
5
+ * D2, D3).
4
6
  *
5
- * A HUB-CONNECTED site — one with a spoke key that would go on the wire
6
- * (`sendsSpokeKey()`), whatever its content adapter (#11515) — reads its
7
- * identity and seo from `GET /v1/content/site-config`, which answers its own
8
- * workspace's rows; a site serving file content with a key reads them too. A
9
- * site with no key makes no call and keeps reading `content/_site.mdx`:
10
- * without a key the route can only answer 401.
7
+ * A HUB-CONNECTED site reads its identity and seo from
8
+ * `GET /v1/content/site-config`, whatever its content adapter (#11515). It is
9
+ * one of two kinds:
10
+ * - a spoke: a spoke key that would go on the wire (`sendsSpokeKey()`); the
11
+ * route answers the key's own workspace;
12
+ * - a single-tenant site: no key, but an API address it names
13
+ * (`apiBaseConfigured()`) over `https:` or loopback (`isSafeTransport`,
14
+ * the key's own transport rule); the route answers the deployment's one
15
+ * workspace, and 401 on a hub, or on a deployment with zero or several
16
+ * workspaces or a sole one that is not the seeded default.
17
+ * A site with neither makes no call and keeps reading `content/_site.mdx`;
18
+ * `getApiBase()`'s `localhost:3001` default is not an address it names.
11
19
  *
12
20
  * Cached with Next's `unstable_cache` under `siteConfigTag()` for at most
13
21
  * `HUB_SITE_REVALIDATE_SECONDS`. The `site-config` revalidate event an Admin
14
22
  * save fires purges the tag (`app/api/revalidate/route.ts`); the expiry is the
15
- * safety net for a spoke with no `revalidateUrl`. The key parts carry a
23
+ * safety net for a site with no revalidate target. The key parts carry a
16
24
  * digest of the spoke key — never the key — so two deployments with different
17
- * keys sharing one data cache never share an entry (SEC-11456-2).
25
+ * keys sharing one data cache never share an entry (SEC-11456-2); a keyless
26
+ * read's part is `keyless:` plus a digest of the API address, so it never
27
+ * shares an entry with a keyed read or a site with another API
28
+ * (SEC-12390-3).
18
29
  *
19
30
  * Inside the cached callback a non-2xx, a throw, a read slower than
20
31
  * `HUB_SITE_TIMEOUT_MS` or a body without the two keys THROWS, so nothing is
21
32
  * written and Next keeps serving the last entry (`page-renderer`'s
22
- * `api-source.ts` failure rule). Outside, a failure answers this instance's
23
- * last good value, else `undefined` — so a hub outage never reaches a page.
24
- * The timeout does not abort the request (`http.ts`'s `get` takes no signal).
33
+ * `api-source.ts` failure rule). One exception: a keyless read the API
34
+ * refuses (401) resolves no rows, so the refusal is cached like a workspace
35
+ * with none and the site renders from its file, with one warn per held
36
+ * answer (SEC-12390-4); a keyed 401 still throws, so a spoke whose key was
37
+ * revoked keeps its last good value. Outside, a failure answers this
38
+ * instance's last good value, else `undefined` — so a hub outage never
39
+ * reaches a page — and a failed keyless read makes this instance wait
40
+ * `HUB_SITE_RETRY_SECONDS` before asking again (SEC-12390-5). The timeout
41
+ * does not abort the request (`http.ts`'s `get` takes no signal).
25
42
  *
26
43
  * One read per request: `readHubSite` is wrapped in React's `cache()`, so
27
44
  * the layout's metadata, its render and every page's JSON-LD share it.
28
45
  *
46
+ * The workspace's site navigation rides the same read (#12401, spec
47
+ * docs/specs/12401-a-site-renders-its-header-spec.md D1): `navigation` is
48
+ * `{ version, record }` when the body carries one `siteNavigationSchema`
49
+ * accepts, else `null` — an absent key (a hub older than #12400), `null`, a
50
+ * version that is not a positive integer or a record the schema refuses, the
51
+ * last two with one warning per distinct refused field path, naming the path
52
+ * and never a value. The schema check is the only barrier between a hub value
53
+ * and a link (`localeHref` passes any scheme through), so only its parsed
54
+ * output is kept. `identity` and `seo` are parsed as before in every case.
55
+ *
29
56
  * `site-brand.tsx`, `site-identity.ts`, `site-contact-email.ts` and
30
57
  * `site-contact-lines.ts` import this module; it imports none of them.
31
58
  */
32
59
 
33
60
  import { createHash } from "node:crypto";
34
61
 
35
- import { sendsSpokeKey, siteConfig } from "@working-theory/api-client";
62
+ import {
63
+ apiBaseConfigured,
64
+ getApiBase,
65
+ isSafeTransport,
66
+ sendsSpokeKey,
67
+ siteConfig,
68
+ } from "@working-theory/api-client";
36
69
  import {
37
70
  siteConfigTag,
38
71
  siteWorkspaceSegment,
@@ -43,38 +76,111 @@ import {
43
76
  type SEO,
44
77
  type SiteIdentity,
45
78
  } from "@working-theory/site-config/schema";
79
+ import {
80
+ siteNavigationSchema,
81
+ siteNavigationVersionSchema,
82
+ type SiteNavigation,
83
+ } from "@working-theory/validation";
46
84
  import { cache } from "react";
47
85
  import type { ZodType } from "zod";
48
86
 
49
- /** The workspace's identity and seo rows as the site reads them; each `null` when absent or unreadable. */
87
+ /** The workspace's navigation record and the version it was saved at (#12401 D1). */
88
+ export interface HubNavigation {
89
+ version: number;
90
+ record: SiteNavigation;
91
+ }
92
+
93
+ /** The workspace's identity, seo and navigation rows as the site reads them; each `null` when absent or unreadable. */
50
94
  export interface HubSite {
51
95
  identity: SiteIdentity | null;
52
96
  seo: SEO | null;
97
+ navigation: HubNavigation | null;
53
98
  }
54
99
 
100
+ /**
101
+ * The cache key's shape part, bumped whenever the parsed `HubSite` shape or
102
+ * the schema it is checked with changes, so an entry written by older site
103
+ * code is never served as this shape (#12401 D1).
104
+ */
105
+ const HUB_SITE_SHAPE = "nav1";
106
+
55
107
  /** How long one hub read is served before it is read again. */
56
108
  export const HUB_SITE_REVALIDATE_SECONDS = 300;
57
109
  /** A read slower than this is a failed read. */
58
110
  export const HUB_SITE_TIMEOUT_MS = 3_000;
111
+ /** How long an instance waits after a failed keyless read (the discovery reader's hold). */
112
+ export const HUB_SITE_RETRY_SECONDS = 15;
59
113
 
60
114
  /**
61
- * Whether this site reads its identity and seo from the hub: a spoke key on
62
- * the wire, whatever the content adapter (#11515).
115
+ * Whether this site reads its identity and seo from the hub, whatever the
116
+ * content adapter (#11515): a spoke key on the wire, or an API address it
117
+ * names over `https:` or loopback (#12390 D2).
63
118
  */
64
119
  export function hubConnected(): boolean {
65
- return sendsSpokeKey();
120
+ return (
121
+ sendsSpokeKey() || (apiBaseConfigured() && isSafeTransport(getApiBase()))
122
+ );
66
123
  }
67
124
 
68
125
  /** The last value `readHubSite` resolved on this instance. */
69
126
  let held: HubSite | undefined;
127
+ /** Until when this instance makes no keyless read (epoch ms), after one failed. */
128
+ let keylessRetryAt = 0;
70
129
 
71
130
  function parsedOrNull<T>(schema: ZodType<T>, value: unknown): T | null {
72
131
  const parsed = schema.safeParse(value);
73
132
  return parsed.success ? parsed.data : null;
74
133
  }
75
134
 
76
- /** One hub read. Throws on any failure, so the cache writes nothing. */
77
- async function fetchHubSite(): Promise<HubSite> {
135
+ /** The refused navigation field paths this process has warned about. */
136
+ const warnedNavigationPaths = new Set<string>();
137
+
138
+ /**
139
+ * A refused field's path, with every segment a hub value chose masked — a
140
+ * `byLocale` key, or any segment that is not an index or a plain field name —
141
+ * so it never carries a value.
142
+ */
143
+ function fieldPath(path: readonly PropertyKey[]): string {
144
+ const parts = path.map((part, i) =>
145
+ typeof part === "number" ||
146
+ (typeof part === "string" && /^[A-Za-z]{1,32}$/.test(part) && path[i - 1] !== "byLocale")
147
+ ? String(part)
148
+ : "*",
149
+ );
150
+ return parts.length > 0 ? parts.join(".") : "(record)";
151
+ }
152
+
153
+ function navigationUnreadable(path: string): null {
154
+ if (!warnedNavigationPaths.has(path)) {
155
+ warnedNavigationPaths.add(path);
156
+ console.warn(
157
+ `[hub-site-config] navigation unreadable at ${path}; rendering the site's own navigation`,
158
+ );
159
+ }
160
+ return null;
161
+ }
162
+
163
+ /** The body's `navigation`, parsed, else `null` (#12401 D1). */
164
+ function navigationOrNull(value: unknown): HubNavigation | null {
165
+ if (value === undefined || value === null) return null;
166
+ if (typeof value !== "object" || Array.isArray(value)) {
167
+ return navigationUnreadable("navigation");
168
+ }
169
+ const { version, record } = value as { version?: unknown; record?: unknown };
170
+ const parsedVersion = siteNavigationVersionSchema.safeParse(version);
171
+ if (!parsedVersion.success) return navigationUnreadable("version");
172
+ const parsedRecord = siteNavigationSchema.safeParse(record);
173
+ if (!parsedRecord.success) {
174
+ return navigationUnreadable(fieldPath(parsedRecord.error.issues[0]?.path ?? []));
175
+ }
176
+ return { version: parsedVersion.data, record: parsedRecord.data };
177
+ }
178
+
179
+ /**
180
+ * One hub read. Throws on any failure, so the cache writes nothing — except
181
+ * a keyless read's 401, which resolves no rows (#12390 D3).
182
+ */
183
+ async function fetchHubSite(keyed: boolean): Promise<HubSite> {
78
184
  let timer: ReturnType<typeof setTimeout> | undefined;
79
185
  const timeout = new Promise<never>((_resolve, reject) => {
80
186
  timer = setTimeout(
@@ -85,6 +191,12 @@ async function fetchHubSite(): Promise<HubSite> {
85
191
  });
86
192
  try {
87
193
  const res = await Promise.race([siteConfig.get(), timeout]);
194
+ if (!res.ok && res.status === 401 && !keyed) {
195
+ console.warn(
196
+ "[hub-site-config] the API refused a keyless read (401); rendering from content/_site.mdx",
197
+ );
198
+ return { identity: null, seo: null, navigation: null };
199
+ }
88
200
  if (!res.ok) throw new Error(`hub site-config read answered ${res.status}`);
89
201
  const body: unknown = res.body;
90
202
  if (
@@ -98,22 +210,30 @@ async function fetchHubSite(): Promise<HubSite> {
98
210
  return {
99
211
  identity: parsedOrNull(SiteIdentitySchema, body.identity),
100
212
  seo: parsedOrNull(SEOSchema, body.seo),
213
+ navigation: navigationOrNull("navigation" in body ? body.navigation : undefined),
101
214
  };
102
215
  } finally {
103
216
  clearTimeout(timer);
104
217
  }
105
218
  }
106
219
 
107
- /** The first 16 hex of the spoke key's SHA-256 — a cache-key part, never the key. */
108
- function spokeKeyDigest(): string {
109
- return createHash("sha256")
110
- .update((process.env.AILK_SPOKE_KEY ?? "").trim(), "utf8")
111
- .digest("hex")
112
- .slice(0, 16);
220
+ /** The first 16 hex of a value's SHA-256 — a cache-key part, never the value. */
221
+ function digest16(value: string): string {
222
+ return createHash("sha256").update(value, "utf8").digest("hex").slice(0, 16);
223
+ }
224
+
225
+ /**
226
+ * The cache key's third part: the spoke key's digest for a keyed read, else
227
+ * `keyless:` plus the API address's digest (SEC-12390-3).
228
+ */
229
+ function callerKeyPart(keyed: boolean): string {
230
+ return keyed
231
+ ? digest16((process.env.AILK_SPOKE_KEY ?? "").trim())
232
+ : `keyless:${digest16(getApiBase())}`;
113
233
  }
114
234
 
115
235
  /**
116
- * The hub's identity and seo for this site, or `undefined` when the site is
236
+ * The hub's identity, seo and navigation for this site, or `undefined` when the site is
117
237
  * not hub-connected (no call made) or no read has ever succeeded here.
118
238
  * Never rejects. Shared within one request (React `cache()`).
119
239
  */
@@ -121,17 +241,20 @@ export const readHubSite = cache(async function readHubSite(): Promise<
121
241
  HubSite | undefined
122
242
  > {
123
243
  if (!hubConnected()) return undefined;
244
+ const keyed = sendsSpokeKey();
245
+ if (!keyed && Date.now() < keylessRetryAt) return held;
124
246
  try {
125
247
  // Loaded only on the hub-connected path, so a site that is not one loads
126
248
  // nothing it did not load before.
127
249
  const { unstable_cache } = await import("next/cache");
128
250
  const read = unstable_cache(
129
- fetchHubSite,
130
- ["ailk-hub-site-config", siteWorkspaceSegment(), spokeKeyDigest()],
251
+ () => fetchHubSite(keyed),
252
+ ["ailk-hub-site-config", siteWorkspaceSegment(), callerKeyPart(keyed), HUB_SITE_SHAPE],
131
253
  { tags: [siteConfigTag()], revalidate: HUB_SITE_REVALIDATE_SECONDS },
132
254
  );
133
255
  held = await read();
134
256
  } catch (err) {
257
+ if (!keyed) keylessRetryAt = Date.now() + HUB_SITE_RETRY_SECONDS * 1_000;
135
258
  console.warn(
136
259
  `[hub-site-config] read failed (${err instanceof Error ? err.name : typeof err}); serving the last good value`,
137
260
  );
@@ -148,7 +271,9 @@ export function heldHubSite(): HubSite | undefined {
148
271
  return hubConnected() ? held : undefined;
149
272
  }
150
273
 
151
- /** Test seam: forget the held value. */
274
+ /** Test seam: forget the held value, any keyless wait and the navigation warnings. */
152
275
  export function __resetHubSiteForTests(): void {
153
276
  held = undefined;
277
+ keylessRetryAt = 0;
278
+ warnedNavigationPaths.clear();
154
279
  }
@@ -14,11 +14,10 @@
14
14
  * run through `pricingSections` with `recommended` as the page's `?plan=`,
15
15
  * so the cards are today's Stripe cards. Anything but Stripe cards — an
16
16
  * unconnected site, an expired set, plans not shown — renders nothing.
17
- * - **Grid.** The public read, `GET /v1/content/grids/:kind/:slug`, through
18
- * api-client `content.grid`, shared per instance for 15 s
19
- * (`sharedHubRead`), parsed by `GridAnswerSchema` and worded by
20
- * `gridSection` with the page locale's `grids` messages — no English
21
- * default reaches a page (D18). With `price` or `button`, the table's plan
17
+ * - **Grid.** The public read and its wording are `grid-read.ts`'s
18
+ * (`gridTable`), shared with a `comparison-table` section's `grid` setting
19
+ * (#12370) — no English default reaches a page (D18). With `price` or
20
+ * `button`, the table's plan
22
21
  * columns take their price and button from the shown set through
23
22
  * `pricingSections`' plan-column resolver. Drawn through `SectionRenderer`.
24
23
  *
@@ -27,24 +26,13 @@
27
26
  * adds its own 3,000 ms backstop. The grid's data is never written anywhere:
28
27
  * every render reads the published facts and Stripe's features afresh.
29
28
  */
30
- import { content } from "@working-theory/api-client";
31
29
  import { setBodyBlockRenderer, type BodyBlockRenderer } from "@working-theory/page-renderer";
32
30
  import { SectionRenderer } from "@working-theory/ui";
33
- import {
34
- GridAnswerSchema,
35
- gridSection,
36
- writeBlockLine,
37
- type GridAnswer,
38
- type GridBlock,
39
- type GridLabels,
40
- type OfferBlock,
41
- type PageSection,
42
- } from "@working-theory/validation";
31
+ import type { GridBlock, OfferBlock, PageSection } from "@working-theory/validation";
43
32
  import { unstable_rethrow } from "next/navigation";
44
- import { getTranslations } from "next-intl/server";
45
33
  import { createElement, type ReactElement } from "react";
46
34
 
47
- import { sharedHubRead } from "./in-page-magnet";
35
+ import { gridTable } from "./grid-read";
48
36
  import { pricingSections } from "./pricing-page";
49
37
 
50
38
  type Sections = PageSection[];
@@ -90,60 +78,16 @@ export async function renderOffer(block: OfferBlock, locale: string): Promise<Re
90
78
 
91
79
  // ── Grid ───────────────────────────────────────────────────────────
92
80
 
93
- /** The grid read, or `null` for any failed read or an answer that does not parse. */
94
- export function readGrid(block: GridBlock, locale: string): Promise<GridAnswer | null> {
95
- const key = `grid:${locale}:${writeBlockLine({ tag: "Grid", block })}`;
96
- return sharedHubRead(key, async () => {
97
- try {
98
- const res = await content.grid({
99
- kind: block.kind,
100
- slug: block.kind === "capabilities" ? block.products.join(" ") : block.category,
101
- show: block.show,
102
- ...(block.kind === "capabilities" && block.levels !== undefined ? { levels: block.levels.join(" ") } : {}),
103
- ...(block.kind === "alternatives" && block.ours !== undefined ? { ours: block.ours } : {}),
104
- ...(block.kind === "alternatives" && block.columns !== undefined ? { columns: block.columns.join(" ") } : {}),
105
- locale,
106
- });
107
- if (!res.ok) return null;
108
- const parsed = GridAnswerSchema.safeParse(res.body);
109
- return parsed.success ? parsed.data : null;
110
- } catch {
111
- return null;
112
- }
113
- });
114
- }
115
-
116
- /** The page locale's `grids` words (D18): every fixed word a grid shows. */
117
- export async function gridLabels(locale: string): Promise<GridLabels> {
118
- const t = await getTranslations({ locale, namespace: "grids" });
119
- const dates = new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeZone: "UTC" });
120
- return {
121
- fromLevel: (level) => t("fromLevel", { level }),
122
- addon: t("addon"),
123
- ourAssessment: t("ourAssessment"),
124
- checked: (date) => t("checked", { date }),
125
- factsAsOf: (date) => t("factsAsOf", { date }),
126
- countOf: (yes, of) => t("countOf", { yes, of }),
127
- capabilities: t("capabilities"),
128
- labelHeader: t("labelHeader"),
129
- planPicker: t("planPicker"),
130
- formatDate: (isoDate) => dates.format(new Date(`${isoDate}T00:00:00Z`)),
131
- };
132
- }
133
-
134
81
  export async function renderGrid(block: GridBlock, locale: string): Promise<ReactElement | null> {
135
- const answer = await readGrid(block, locale);
136
- if (answer === null) return null;
137
- const options =
138
- block.kind === "capabilities" ? { price: block.price, button: block.button } : { source: block.source };
139
- const data = gridSection(answer, await gridLabels(locale), options);
140
- if (data === null) return null;
82
+ // The read and its wording are `grid-read.ts`'s, shared with a comparison-table section's `grid` (#12370 D3).
83
+ const read = await gridTable(block, locale);
84
+ if (read === null) return null;
141
85
  const table = {
142
86
  type: "comparison-table",
143
87
  id: `grid-${block.kind}-${block.kind === "capabilities" ? block.products.join("-") : block.category}`,
144
- data,
88
+ data: read.data,
145
89
  } as PageSection;
146
- const plans = answer.columns.flatMap((column) => (column.ours && column.plan !== undefined ? [column.plan] : []));
90
+ const { plans } = read;
147
91
  if (block.kind !== "capabilities" || (block.price !== true && block.button !== true) || plans.length === 0) {
148
92
  return drawn([table], locale);
149
93
  }
@@ -8,7 +8,8 @@
8
8
  * footer signup all read through here.
9
9
  *
10
10
  * - `sharedHubRead` shares a hub read across requests for HUB_READ_TTL_MS
11
- * (#8731, moved here from /contact): a visitor view carries no forwarding
11
+ * (#8731, moved here from /contact; in `hub-read.ts` since #12385 and
12
+ * re-exported here): a visitor view carries no forwarding
12
13
  * headers, so on a spoke every view would otherwise count against the
13
14
  * spoke server's one per-IP limit at the hub. An Admin edit shows within
14
15
  * that window.
@@ -59,6 +60,7 @@ import { unstable_rethrow } from "next/navigation";
59
60
  import { createElement, type ReactElement } from "react";
60
61
 
61
62
  import { consentPoliciesFor } from "./consent-policies";
63
+ import { sharedHubRead } from "./hub-read";
62
64
  import { subscribeNewsletterAction } from "./newsletter.actions";
63
65
  import type { UiSignalCollectorsContract } from "./paid-section-contracts";
64
66
  import { loadUiSignalCollectors } from "./paid-sections.generated";
@@ -69,14 +71,8 @@ export { fillEndingName } from "@working-theory/validation";
69
71
 
70
72
  // ─── Shared hub reads (#8731) ──────────────────────────────────────────────────
71
73
 
72
- /**
73
- * How long a hub read is shared across requests (#8731). Short, so an Admin
74
- * edit to the magnet shows within seconds; long enough that a burst of views
75
- * makes one read of each, not one per view.
76
- */
77
- export const HUB_READ_TTL_MS = 15_000;
78
-
79
- const hubReads = new Map<string, { at: number; read: Promise<unknown> }>();
74
+ // Re-exported under the same names (#12385), so a scaffolded site that imports them from here keeps working.
75
+ export { HUB_READ_TTL_MS, sharedHubRead } from "./hub-read";
80
76
 
81
77
  /**
82
78
  * How long a page waits on one hub read before treating it as failed. The
@@ -94,21 +90,6 @@ function withDeadline<T>(read: Promise<T>, fallback: T): Promise<T> {
94
90
  return Promise.race([read, late]).finally(() => clearTimeout(timer));
95
91
  }
96
92
 
97
- /**
98
- * `read()`'s result, shared per instance for HUB_READ_TTL_MS. Concurrent calls
99
- * share one in-flight read. A read that settles to `null` (any failed read,
100
- * see the readers below) is shared the same way, so a burst against an
101
- * unreachable hub is not a burst of retries.
102
- */
103
- export function sharedHubRead<T>(key: string, read: () => Promise<T>): Promise<T> {
104
- const now = Date.now();
105
- const hit = hubReads.get(key);
106
- if (hit && now - hit.at < HUB_READ_TTL_MS) return hit.read as Promise<T>;
107
- const fresh = read();
108
- hubReads.set(key, { at: now, read: fresh });
109
- return fresh;
110
- }
111
-
112
93
  export type CaptureStatus = Extract<
113
94
  Awaited<ReturnType<typeof leads.captureStatus>>,
114
95
  { ok: true }
@@ -38,6 +38,7 @@ import {
38
38
  type SiteLayout,
39
39
  } from "@working-theory/site-config/schema";
40
40
  import { conventionPath, ROUTES } from "@working-theory/templates/routes";
41
+ import type { SiteNavigation } from "@working-theory/validation";
41
42
  import { readLocales } from "@working-theory/web-i18n";
42
43
  import { cache } from "react";
43
44
  import { parse as parseYaml } from "yaml";
@@ -51,8 +52,10 @@ import {
51
52
  resolveTypeAndSlug,
52
53
  } from "./deck-page";
53
54
  import { toInternalDocsPath } from "./docs-path";
55
+ import { readHubSite } from "./hub-site-config";
54
56
  import { SERVICES_ROUTE, toInternalServicesPath } from "./services-path";
55
57
  import { resolveContentRoot } from "./site-brand";
58
+ import { safeNavigationChrome, type NavigationChrome } from "./site-navigation";
56
59
 
57
60
  /** The chrome settings a site sets in `_site.mdx`. */
58
61
  export interface SiteChromeSettings {
@@ -167,6 +170,60 @@ export const readSiteChromeSettings = cache(
167
170
  },
168
171
  );
169
172
 
173
+ /**
174
+ * The file settings with the hub navigation record's styles laid over them
175
+ * (#12401 D4): the record's header and footer style, and each route family's
176
+ * `header` and `footer`, win where the record sets them; every other value —
177
+ * the layout, a family's `path` — is the file's. Returns new objects and never
178
+ * changes `site`, which `readSiteChromeSettings` shares across the request.
179
+ */
180
+ export function withNavigationStyles(
181
+ site: SiteChromeSettings,
182
+ record: SiteNavigation | null,
183
+ ): SiteChromeSettings {
184
+ if (record === null) return site;
185
+ const families: SiteChromeSettings["families"] = { ...site.families };
186
+ for (const key of ROUTE_FAMILY_KEYS) {
187
+ const styles = record.families?.[key];
188
+ if (styles?.header === undefined && styles?.footer === undefined) continue;
189
+ families[key] = {
190
+ ...site.families[key],
191
+ ...(styles.header !== undefined ? { header: styles.header } : {}),
192
+ ...(styles.footer !== undefined ? { footer: styles.footer } : {}),
193
+ };
194
+ }
195
+ const headerStyle = record.header.style ?? site.headerStyle;
196
+ const footerStyle = record.footer.style ?? site.footerStyle;
197
+ return {
198
+ ...site,
199
+ ...(headerStyle !== undefined ? { headerStyle } : {}),
200
+ ...(footerStyle !== undefined ? { footerStyle } : {}),
201
+ families,
202
+ };
203
+ }
204
+
205
+ /** The hub navigation record a page renders, with its translation (#12401 D3). */
206
+ export interface RecordNavigation {
207
+ version: number;
208
+ record: SiteNavigation;
209
+ chrome: NavigationChrome;
210
+ }
211
+
212
+ /**
213
+ * The hub navigation record this request renders for `locale`, with its
214
+ * translation (#12401 D3, D4) — `null` when the hub read carries none or the
215
+ * translator refuses it. `resolveHomeChrome` answers it, so the record's
216
+ * styles apply exactly when its links render.
217
+ */
218
+ const readRecordNavigation = cache(async function readRecordNavigation(
219
+ locale: string,
220
+ ): Promise<RecordNavigation | null> {
221
+ const navigation = (await readHubSite())?.navigation ?? null;
222
+ if (navigation === null) return null;
223
+ const chrome = safeNavigationChrome(navigation.record, locale);
224
+ return chrome === null ? null : { version: navigation.version, record: navigation.record, chrome };
225
+ });
226
+
170
227
  /** The closing footer's site settings (#10550 D3). */
171
228
  export interface ClosingFooterSettings {
172
229
  locality?: string;
@@ -394,18 +451,28 @@ function templateChrome(
394
451
 
395
452
  /**
396
453
  * The home's layout and chrome — the one resolution both the layout and the
397
- * home page read, so the bar and the landing can never disagree.
454
+ * home page read, so the bar and the landing can never disagree. The site
455
+ * settings are `_site.mdx`'s with the hub navigation record's styles over
456
+ * them (#12401 D4) — only when the record renders, so a refused record's
457
+ * files keep the files' styles. `navigation` is that record, for the layout.
398
458
  */
399
459
  export async function resolveHomeChrome(
400
460
  locale: string,
401
461
  chrome: ChromeKnobs,
402
- ): Promise<{ layout: SiteLayout; chrome: ResolvedChrome; site: SiteChromeSettings }> {
403
- const site = readSiteChromeSettings();
462
+ ): Promise<{
463
+ layout: SiteLayout;
464
+ chrome: ResolvedChrome;
465
+ site: SiteChromeSettings;
466
+ navigation: RecordNavigation | null;
467
+ }> {
468
+ const navigation = await readRecordNavigation(locale);
469
+ const site = withNavigationStyles(readSiteChromeSettings(), navigation?.record ?? null);
404
470
  const page = await resolveChromePage("/", locale);
405
471
  const layout = resolveHomeLayout(site, page, chrome);
406
472
  return {
407
473
  layout,
408
474
  site,
475
+ navigation,
409
476
  chrome: resolvePageChrome({
410
477
  isHome: true,
411
478
  homeIsDeck: layout === "deck",
@@ -59,6 +59,7 @@ import { createElement, type ReactNode } from "react";
59
59
  import { resolveBaseUrl } from "../src/lib/routes";
60
60
 
61
61
  import { browserApiOrigin } from "./api-origin.generated";
62
+ import { gridTable, withinGridDeadline } from "./grid-read";
62
63
  import {
63
64
  OFFERINGS_CHECKOUT_PATH,
64
65
  collectionPlans,
@@ -1040,6 +1041,34 @@ function withPlanColumns(
1040
1041
  });
1041
1042
  }
1042
1043
 
1044
+ /**
1045
+ * The page's grid-bound comparison tables, each read from its Offerings grid
1046
+ * (#12370, spec docs/specs/12370-a-comparison-table-reads-an-offerings-grid-spec.md
1047
+ * D4): a `comparison-table` section whose data carries `grid` takes its
1048
+ * columns and groups from `gridTable` — the Grid block's own read and
1049
+ * wording — and keeps every field it sets itself, so the section's
1050
+ * `headline`, `footnote`, `variant`, `labelHeader`, `yesMark`, `planBar` and
1051
+ * the rest win, and the grid's `labelHeader`, `variant`, `yesMark` and
1052
+ * `footnote` show where the section sets none. A read that fails, takes
1053
+ * longer than 3,000 ms or answers no row removes the table: nothing typed is kept as a fallback.
1054
+ * Run before `withPlanColumns`, so a grid's plan columns resolve from the
1055
+ * shown set as a typed table's do. The input array itself when no table
1056
+ * carries `grid`.
1057
+ */
1058
+ export async function withGrids(sections: PageSection[], locale: string): Promise<PageSection[]> {
1059
+ if (!sections.some((section) => isComparisonTable(section) && section.data.grid !== undefined)) return sections;
1060
+ const resolved = await Promise.all(
1061
+ sections.map(async (section): Promise<PageSection | null> => {
1062
+ if (!isComparisonTable(section) || section.data.grid === undefined) return section;
1063
+ const { grid, columns: _c, groups: _g, ...own } = section.data;
1064
+ // A throw or a read past its deadline is a failed read: the table is left out, the page still renders.
1065
+ const read = await withinGridDeadline(gridTable(grid, locale));
1066
+ return read === null ? null : { ...section, data: { ...read.data, ...own } };
1067
+ }),
1068
+ );
1069
+ return resolved.filter((section): section is PageSection => section !== null);
1070
+ }
1071
+
1043
1072
  /**
1044
1073
  * The hub's `pricingPagesHeading` override (#12213 AC-1): the heading that
1045
1074
  * replaces the `pricingPages.heading` message on the generated `pricing-pages`
@@ -1078,7 +1107,8 @@ export function pricingPagesSectionEnabled(frontmatter: unknown): boolean {
1078
1107
  * - anything else → the contact email in their place.
1079
1108
  * On the written states a `source: written` section never links the
1080
1109
  * Offerings checkout (#12140 D2 rule 7). On every path the authored
1081
- * render-time fields are removed first, each comparison table's plan columns
1110
+ * render-time fields are removed first, each grid-bound comparison table is
1111
+ * read from its Offerings grid (#12370 D4), each comparison table's plan columns
1082
1112
  * are resolved from the shown set the page read (#12246 D3; typed off the
1083
1113
  * shown path), and `?plan=` / `?billing=`'s are set last (#12193 D9, D11).
1084
1114
  */
@@ -1093,7 +1123,8 @@ export async function pricingSections(
1093
1123
  ): Promise<PageSection[]> {
1094
1124
  const { plan, period } = options;
1095
1125
  const { sections, source } = await sectionsFor(withoutRenderTimeFields(authored), options);
1096
- return withSelection(withPlanColumns(sections, { source, period }), plan, period);
1126
+ const tables = await withGrids(sections, options.locale);
1127
+ return withSelection(withPlanColumns(tables, { source, period }), plan, period);
1097
1128
  }
1098
1129
 
1099
1130
  async function sectionsFor(