create-ailk 0.46.5 → 0.46.6

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.
@@ -1706,3 +1706,213 @@ describe("an authored card's images never reach the page (#12241 D8, security)",
1706
1706
  expect(JSON.stringify(placed!.data)).not.toContain("evil.example");
1707
1707
  });
1708
1708
  });
1709
+
1710
+ // ─── #12370 — a comparison table that reads its rows from an Offerings grid ──
1711
+
1712
+ describe("pricingSections — a grid-bound comparison table (#12370 D3, D4)", () => {
1713
+ // Past every other suite's clock, so no earlier shared read is reused.
1714
+ let now = Date.now() + 5 * 10 ** 12;
1715
+ let seq = 0;
1716
+ beforeEach(() => {
1717
+ now += 16_000;
1718
+ seq += 1;
1719
+ jest.spyOn(Date, "now").mockReturnValue(now);
1720
+ });
1721
+ afterEach(() => {
1722
+ jest.useRealTimers();
1723
+ jest.restoreAllMocks();
1724
+ });
1725
+
1726
+ /** `publicGrid`'s answer for a Capabilities grid of two levels, by feature. */
1727
+ const C = {
1728
+ kind: "capabilities",
1729
+ columns: [
1730
+ { key: "pro", ours: true, plan: "pro", name: "Pro" },
1731
+ { key: "pro-plus", ours: true, plan: "pro-plus", name: "Pro Plus" },
1732
+ ],
1733
+ groups: [
1734
+ {
1735
+ id: "site",
1736
+ name: "Site",
1737
+ rows: [
1738
+ // A Capabilities cell is what Stripe grants (`true` / `false`) or a typed value.
1739
+ { id: "pages", name: "Pages", cells: { pro: true, "pro-plus": true } },
1740
+ { id: "drafts", name: "Drafts", cells: { pro: false, "pro-plus": { value: "8" } } },
1741
+ ],
1742
+ summaries: {},
1743
+ },
1744
+ ],
1745
+ factsAsOf: null,
1746
+ };
1747
+ /** `publicGrid`'s answer for an Alternatives grid: ours, then one approved alternative. */
1748
+ const A = {
1749
+ kind: "alternatives",
1750
+ columns: [
1751
+ { key: "ours", ours: true, name: "Growth Hub" },
1752
+ { key: "wix", ours: false, name: "Wix", what: "A website builder", source: { url: "https://wix.com/pricing" }, checkedOn: "2026-11-01" },
1753
+ ],
1754
+ groups: [
1755
+ {
1756
+ id: "build",
1757
+ name: "Build",
1758
+ rows: [{ id: "r1", name: "Pages", cells: { ours: { verdict: "yes" }, wix: { verdict: "partial", words: "Blog only" } } }],
1759
+ summaries: {},
1760
+ },
1761
+ ],
1762
+ factsAsOf: "2026-11-01",
1763
+ };
1764
+
1765
+ const ok = (data: unknown) => ({ ok: true, status: 200, json: async () => ({ ok: true, data }) });
1766
+ /** The site's two reads: the shown set, and the public grid read. */
1767
+ function serve(grid: unknown | (() => Promise<unknown>), shown: unknown = { status: "unconnected" }): void {
1768
+ fetchMock.mockImplementation(async (url: unknown) => {
1769
+ if (!String(url).includes("/v1/content/grids/")) return ok(shown);
1770
+ return typeof grid === "function" ? (grid as () => Promise<unknown>)() : ok(grid);
1771
+ });
1772
+ }
1773
+ const gridCalls = () => fetchMock.mock.calls.map(([url]) => String(url)).filter((url) => url.includes("/v1/content/grids/"));
1774
+
1775
+ type Table = Extract<PageSection, { type: "comparison-table" }>;
1776
+ /** A grid-bound section as a page stores it, parsed as the site parses a page's sections. */
1777
+ const bound = (grid: Record<string, unknown>, own: Record<string, unknown> = {}): PageSection =>
1778
+ PageSectionsSchema.parse([{ id: "t", type: "comparison-table", data: { grid, ...own } }])[0]!;
1779
+ const capabilities = (extra: Record<string, unknown> = {}) => ({
1780
+ kind: "capabilities",
1781
+ products: [`growth-hub-${seq}`],
1782
+ show: "features",
1783
+ ...extra,
1784
+ });
1785
+ const alternatives = (extra: Record<string, unknown> = {}) => ({
1786
+ kind: "alternatives",
1787
+ category: `website-platform-${seq}`,
1788
+ show: "features",
1789
+ ...extra,
1790
+ });
1791
+ const tableOf = (sections: PageSection[]) => {
1792
+ const found = sections.find((s) => s.id === "t");
1793
+ if (!found || found.type !== "comparison-table") throw new Error("no table");
1794
+ return found.data as Table["data"] & { billingPeriod?: string };
1795
+ };
1796
+ const options = { plans: undefined, plan: undefined, locale: "en" };
1797
+
1798
+ it("AC-1: a capabilities grid draws its features under their capability, one column per named level", async () => {
1799
+ serve(C);
1800
+ const sections = await pricingSections([HERO, bound(capabilities({ levels: ["pro", "pro-plus"] }), { headline: "Compare" })], options);
1801
+ const table = tableOf(sections);
1802
+ expect(table.columns.map((c) => [c.key, c.plan, c.name])).toEqual([
1803
+ ["pro", "pro", "Pro"],
1804
+ ["pro-plus", "pro-plus", "Pro Plus"],
1805
+ ]);
1806
+ expect(table.groups.map((g) => [g.groupName, g.rows.map((r) => r.featureName)])).toEqual([["Site", ["Pages", "Drafts"]]]);
1807
+ expect(table.groups[0]!.rows.map((r) => r.values)).toEqual([
1808
+ { pro: true, "pro-plus": true },
1809
+ { pro: false, "pro-plus": "8" },
1810
+ ]);
1811
+ expect(table.headline).toBe("Compare");
1812
+ expect(table).not.toHaveProperty("grid");
1813
+ // One read, of the public grid route, naming the product, the levels and the page's locale.
1814
+ const [url] = gridCalls();
1815
+ expect(gridCalls()).toHaveLength(1);
1816
+ expect(url).toContain(`/v1/content/grids/capabilities/growth-hub-${seq}?`);
1817
+ expect(new URL(url!, "http://x").searchParams.get("levels")).toBe("pro pro-plus");
1818
+ expect(new URL(url!, "http://x").searchParams.get("locale")).toBe("en");
1819
+ });
1820
+
1821
+ it("AC-2: an alternatives grid draws ours first and highlighted, then the answer's alternatives, as answered", async () => {
1822
+ serve(A);
1823
+ const grid = alternatives({ ours: "growth-hub", columns: ["wix"], source: true });
1824
+ const table = tableOf(await pricingSections([HERO, bound(grid)], options));
1825
+ expect(table.columns).toEqual([
1826
+ { key: "ours", name: "Growth Hub", highlighted: true },
1827
+ { key: "wix", name: "Wix" },
1828
+ ]);
1829
+ expect(table.groups[0]!.rows[0]!.values).toEqual({ ours: { text: "", verdict: "yes" }, wix: { text: "Blog only", verdict: "partial" } });
1830
+ // The grid's own look and footnote show, since the section sets none.
1831
+ expect(table).toMatchObject({ variant: "detailed", yesMark: "ink" });
1832
+ expect(table.footnote).toContain("https://wix.com/pricing");
1833
+ const query = new URL(gridCalls()[0]!, "http://x").searchParams;
1834
+ expect([query.get("ours"), query.get("columns")]).toEqual(["growth-hub", "wix"]);
1835
+ });
1836
+
1837
+ it("the section's own fields win over the grid's, and the rest of its settings pass through", async () => {
1838
+ serve(A);
1839
+ const own = { eyebrow: "E", description: "D", footnote: "Mine", variant: "default", labelHeader: "Feature", yesMark: "muted", longCells: "clamp", checkStyle: "inverted" };
1840
+ const table = tableOf(await pricingSections([bound(alternatives(), own)], options));
1841
+ expect(table).toMatchObject(own);
1842
+ expect(table.columns).toHaveLength(2);
1843
+ });
1844
+
1845
+ it("AC-8: the section's planBar gives a grid's plan columns their price and button from the shown set", async () => {
1846
+ const both = (plan: string, monthly: number, yearly: number) => [stripePrice(plan, "monthly", monthly), stripePrice(plan, "yearly", yearly)];
1847
+ const offerings = [
1848
+ stripeProduct("pro", "plan", both("pro", 4900, 49000), { name: "Pro" }),
1849
+ stripeProduct("pro-plus", "plan", both("pro-plus", 9900, 99000), { name: "Pro Plus" }),
1850
+ ];
1851
+ const shownSet = workspaceShownSetSchema.parse({
1852
+ workspaceId: "wksp_01890a5d-ac96-774b-bcce-b302099a8057",
1853
+ organizationId: "org_01890a5d-ac96-774b-bcce-b302099a8058",
1854
+ productIds: offerings.map((o) => o.productId),
1855
+ recommended: { plan: null, addon: null },
1856
+ offerings,
1857
+ state: "current",
1858
+ snapshotAt: "2026-11-20T00:00:00.000Z",
1859
+ });
1860
+ serve(C, { status: "shown", shownSet });
1861
+ const planBar = { pickerLabel: "Plan", price: true, button: true };
1862
+ const cards = pricingSection("p", { source: "offerings", offeringPlans: ["pro", "pro-plus"] });
1863
+ const sections = await pricingSections([cards, bound(capabilities(), { planBar })], options);
1864
+ const table = tableOf(sections);
1865
+ expect(table.planBar).toEqual(planBar);
1866
+ const columns = table.columns as Array<Table["data"]["columns"][number] & { offering?: { cta: { href: string } } }>;
1867
+ expect(columns.map((c) => c.offering?.cta.href)).toEqual([
1868
+ `${OFFERINGS_CHECKOUT_PATH}/pro_monthly`,
1869
+ `${OFFERINGS_CHECKOUT_PATH}/pro-plus_monthly`,
1870
+ ]);
1871
+ // The table opens on the period the page's cards open on, as a typed table's plan columns do.
1872
+ expect(table.billingPeriod).toBe("annual");
1873
+ });
1874
+
1875
+ it.each<[string, unknown]>([
1876
+ ["a refused read", { ok: false, status: 404, json: async () => ({ ok: false, error: { code: "not_found", message: "No grid" } }) }],
1877
+ ["an answer that does not parse", ok({ kind: "capabilities", columns: "x" })],
1878
+ ["a grid with no row", ok({ ...C, groups: [] })],
1879
+ ["a grid with no column", ok({ ...C, columns: [] })],
1880
+ ])("AC-7: %s draws no table, and the page's other sections render", async (_label, response) => {
1881
+ serve(async () => response);
1882
+ const sections = await pricingSections([HERO, bound(capabilities()), EXTRAS], options);
1883
+ expect(sections.map((s) => s.id)).toEqual(["hero", "extras"]);
1884
+ });
1885
+
1886
+ it("AC-7: a read that throws draws no table, and one failed grid leaves another grid's table drawn", async () => {
1887
+ fetchMock.mockImplementation(async (url: unknown) => {
1888
+ if (String(url).includes("/grids/capabilities/")) throw new Error("hub down");
1889
+ return String(url).includes("/grids/alternatives/") ? ok(A) : ok({ status: "unconnected" });
1890
+ });
1891
+ const other = { ...bound(alternatives()), id: "alt" } as PageSection;
1892
+ const sections = await pricingSections([HERO, bound(capabilities()), other], options);
1893
+ expect(sections.map((s) => s.id)).toEqual(["hero", "alt"]);
1894
+ });
1895
+
1896
+ it("AC-7: a read that has not answered in 3,000 ms draws no table", async () => {
1897
+ jest.useFakeTimers({ doNotFake: ["Date"] });
1898
+ serve(() => new Promise(() => undefined));
1899
+ const pending = pricingSections([HERO, bound(capabilities())], options);
1900
+ await jest.advanceTimersByTimeAsync(2_999);
1901
+ let settled = false;
1902
+ void pending.then(() => (settled = true));
1903
+ await jest.advanceTimersByTimeAsync(0);
1904
+ expect(settled).toBe(false);
1905
+ await jest.advanceTimersByTimeAsync(1);
1906
+ expect((await pending).map((s) => s.id)).toEqual(["hero"]);
1907
+ });
1908
+
1909
+ it("AC-9: a typed table, and a page with no grid, makes no grid read and comes back unchanged", async () => {
1910
+ serve(C);
1911
+ const typed = PageSectionsSchema.parse([
1912
+ { id: "t", type: "comparison-table", data: { columns: [{ key: "us", name: "Us" }], groups: [{ groupName: "G", rows: [{ featureName: "F", values: { us: true } }] }] } },
1913
+ ])[0]!;
1914
+ const sections = await pricingSections([HERO, typed], options);
1915
+ expect(gridCalls()).toEqual([]);
1916
+ expect(sections[1]).toBe(typed);
1917
+ });
1918
+ });
@@ -0,0 +1,115 @@
1
+ /**
2
+ * grid-read.ts — the one read of an Offerings grid for a page (#12370, spec
3
+ * docs/specs/12370-a-comparison-table-reads-an-offerings-grid-spec.md D3),
4
+ * shared by its two callers: a `<Grid … />` block line (`in-page-blocks.ts`)
5
+ * and a `comparison-table` section's `grid` setting (`pricing-page.ts`). It
6
+ * imports neither, so the two can both import it.
7
+ *
8
+ * The public read, `GET /v1/content/grids/:kind/:slug`, goes through
9
+ * api-client `content.grid`, shared per instance for 15 s (`sharedHubRead`),
10
+ * is parsed by `GridAnswerSchema` and worded by
11
+ * `gridSection` with the page locale's `grids` messages — no English default
12
+ * reaches a page (#12222 D18). A read that fails, an answer that does not
13
+ * parse and an empty grid all answer `null`: the caller draws no table. The
14
+ * grid's data is never written anywhere: every render reads the published
15
+ * facts and Stripe's features afresh.
16
+ *
17
+ * The read itself carries no deadline. A block line is bounded by
18
+ * page-renderer's own 3,000 ms backstop; a section is bounded here, by
19
+ * `withinGridDeadline`, at the same 3,000 ms.
20
+ */
21
+ import { content } from "@working-theory/api-client";
22
+ import {
23
+ GridAnswerSchema,
24
+ gridSection,
25
+ writeBlockLine,
26
+ type ComparisonGrid,
27
+ type GridAnswer,
28
+ type GridBlock,
29
+ type GridLabels,
30
+ type PageSection,
31
+ } from "@working-theory/validation";
32
+ import { getTranslations } from "next-intl/server";
33
+
34
+ import { sharedHubRead } from "./hub-read";
35
+
36
+ /** A grid as either caller names it: a block's fields, or a section's (the same, less `price` and `button`). */
37
+ export type GridSetting = GridBlock | ComparisonGrid;
38
+
39
+ /** A `comparison-table` section's data. */
40
+ export type GridTableData = Extract<PageSection, { type: "comparison-table" }>["data"];
41
+
42
+ /** How long a section waits on its grid before drawing no table: a block line's backstop (page-renderer). */
43
+ export const GRID_READ_DEADLINE_MS = 3_000;
44
+
45
+ /** `read`'s answer, or `null` once GRID_READ_DEADLINE_MS has passed or `read` rejects. */
46
+ export function withinGridDeadline<T>(read: Promise<T | null>): Promise<T | null> {
47
+ let timer: ReturnType<typeof setTimeout> | undefined;
48
+ const late = new Promise<null>((resolve) => {
49
+ timer = setTimeout(() => resolve(null), GRID_READ_DEADLINE_MS);
50
+ });
51
+ return Promise.race([read.catch(() => null), late]).finally(() => clearTimeout(timer));
52
+ }
53
+
54
+ /** The grid read, or `null` for any failed read or an answer that does not parse. */
55
+ export function readGrid(grid: GridSetting, locale: string): Promise<GridAnswer | null> {
56
+ const key = `grid:${locale}:${writeBlockLine({ tag: "Grid", block: grid as GridBlock })}`;
57
+ return sharedHubRead(key, async () => {
58
+ try {
59
+ const res = await content.grid({
60
+ kind: grid.kind,
61
+ slug: grid.kind === "capabilities" ? grid.products.join(" ") : grid.category,
62
+ show: grid.show,
63
+ ...(grid.kind === "capabilities" && grid.levels !== undefined ? { levels: grid.levels.join(" ") } : {}),
64
+ ...(grid.kind === "alternatives" && grid.ours !== undefined ? { ours: grid.ours } : {}),
65
+ ...(grid.kind === "alternatives" && grid.columns !== undefined ? { columns: grid.columns.join(" ") } : {}),
66
+ locale,
67
+ });
68
+ if (!res.ok) return null;
69
+ const parsed = GridAnswerSchema.safeParse(res.body);
70
+ return parsed.success ? parsed.data : null;
71
+ } catch {
72
+ return null;
73
+ }
74
+ });
75
+ }
76
+
77
+ /** The page locale's `grids` words (#12222 D18): every fixed word a grid shows. */
78
+ export async function gridLabels(locale: string): Promise<GridLabels> {
79
+ const t = await getTranslations({ locale, namespace: "grids" });
80
+ const dates = new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeZone: "UTC" });
81
+ return {
82
+ fromLevel: (level) => t("fromLevel", { level }),
83
+ addon: t("addon"),
84
+ ourAssessment: t("ourAssessment"),
85
+ checked: (date) => t("checked", { date }),
86
+ factsAsOf: (date) => t("factsAsOf", { date }),
87
+ countOf: (yes, of) => t("countOf", { yes, of }),
88
+ capabilities: t("capabilities"),
89
+ labelHeader: t("labelHeader"),
90
+ planPicker: t("planPicker"),
91
+ formatDate: (isoDate) => dates.format(new Date(`${isoDate}T00:00:00Z`)),
92
+ };
93
+ }
94
+
95
+ /**
96
+ * A grid as `comparison-table` data, with the plan slugs of its own columns,
97
+ * or `null` for a failed read or a grid with no row. A block's `price`,
98
+ * `button` and `source` shape the data; a section's grid carries no `price`
99
+ * or `button` (its `planBar` is the one header control).
100
+ */
101
+ export async function gridTable(
102
+ grid: GridSetting,
103
+ locale: string,
104
+ ): Promise<{ data: GridTableData; plans: string[] } | null> {
105
+ const answer = await readGrid(grid, locale);
106
+ if (answer === null) return null;
107
+ const options =
108
+ grid.kind === "capabilities"
109
+ ? { price: "price" in grid ? grid.price : undefined, button: "button" in grid ? grid.button : undefined }
110
+ : { source: grid.source };
111
+ const data = gridSection(answer, await gridLabels(locale), options);
112
+ if (data === null) return null;
113
+ const plans = answer.columns.flatMap((column) => (column.ours && column.plan !== undefined ? [column.plan] : []));
114
+ return { data: data as GridTableData, plans };
115
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * hub-read.ts — a hub read shared across requests (#8731).
3
+ *
4
+ * A visitor view carries no forwarding headers, so on a spoke every view
5
+ * would otherwise count against the spoke server's one per-IP limit at the
6
+ * hub. An Admin edit shows within HUB_READ_TTL_MS.
7
+ *
8
+ * A leaf (#12385): it imports no other apps/web module, so `grid-read.ts` and
9
+ * `in-page-magnet.ts` can both import it without closing a cycle through
10
+ * `site-pages.config.tsx`. `in-page-magnet.ts` re-exports both names.
11
+ */
12
+
13
+ /**
14
+ * How long a hub read is shared across requests (#8731). Short, so an Admin
15
+ * edit to the magnet shows within seconds; long enough that a burst of views
16
+ * makes one read of each, not one per view.
17
+ */
18
+ export const HUB_READ_TTL_MS = 15_000;
19
+
20
+ const hubReads = new Map<string, { at: number; read: Promise<unknown> }>();
21
+
22
+ /**
23
+ * `read()`'s result, shared per instance for HUB_READ_TTL_MS. Concurrent calls
24
+ * share one in-flight read. A read that settles to `null` (any failed read,
25
+ * see the readers in `in-page-magnet.ts`) is shared the same way, so a burst
26
+ * against an unreachable hub is not a burst of retries.
27
+ */
28
+ export function sharedHubRead<T>(key: string, read: () => Promise<T>): Promise<T> {
29
+ const now = Date.now();
30
+ const hit = hubReads.get(key);
31
+ if (hit && now - hit.at < HUB_READ_TTL_MS) return hit.read as Promise<T>;
32
+ const fresh = read();
33
+ hubReads.set(key, { at: now, read: fresh });
34
+ return fresh;
35
+ }
@@ -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 }
@@ -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(