create-ailk 0.32.0 → 0.34.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 (53) hide show
  1. package/README.md +21 -3
  2. package/component-catalog.json +12 -1
  3. package/component-catalog.md +6 -5
  4. package/dist/export-content.d.ts +6 -3
  5. package/dist/export-content.js +82 -11
  6. package/dist/lib/env-catalog.js +4 -0
  7. package/dist/lib/import-mdx.d.ts +111 -0
  8. package/dist/lib/import-mdx.js +648 -46
  9. package/dist/migrate-content.d.ts +3 -1
  10. package/dist/migrate-content.js +52 -1
  11. package/dist/seed-flows.d.ts +1 -1
  12. package/dist/seed-flows.js +9 -4
  13. package/dist/surfaces.js +1 -0
  14. package/package.json +3 -3
  15. package/templates/apps/api/.env.example +11 -0
  16. package/templates/apps/api/CLAUDE.md +7 -5
  17. package/templates/apps/api/src/lib/__mocks__/prisma.ts +13 -0
  18. package/templates/apps/mcp/CLAUDE.md +4 -2
  19. package/templates/apps/web/CLAUDE.md +4 -1
  20. package/templates/apps/web/app/[locale]/(auth)/__tests__/password-reset.test.tsx +28 -0
  21. package/templates/apps/web/app/[locale]/(auth)/verify-email/__tests__/actions.test.ts +94 -0
  22. package/templates/apps/web/app/[locale]/(auth)/verify-email/actions.ts +77 -0
  23. package/templates/apps/web/app/[locale]/(auth)/verify-email/page.tsx +79 -14
  24. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +7 -0
  25. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-menu.test.tsx +7 -0
  26. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +7 -0
  27. package/templates/apps/web/app/[locale]/contact/__tests__/contact.actions.test.ts +21 -0
  28. package/templates/apps/web/app/[locale]/contact/contact.actions.ts +15 -9
  29. package/templates/apps/web/app/[locale]/flows/[slug]/FlowStepperClient.tsx +38 -105
  30. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.invite.test.tsx +72 -58
  31. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/verify.test.tsx +249 -0
  32. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsClient.tsx +164 -20
  33. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/by-result.test.tsx +269 -0
  34. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/score.test.tsx +179 -0
  35. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/page.tsx +108 -40
  36. package/templates/apps/web/app/[locale]/flows/[slug]/verify/page.tsx +153 -0
  37. package/templates/apps/web/app/[locale]/flows/[slug]/verify.actions.ts +151 -0
  38. package/templates/apps/web/app/[locale]/meet/confirmed/BookingHandOff.tsx +1 -1
  39. package/templates/apps/web/app/[locale]/thanks/[slug]/__tests__/page.test.tsx +3 -20
  40. package/templates/apps/web/app/[locale]/thanks/[slug]/page.tsx +2 -9
  41. package/templates/apps/web/auth.ts +22 -6
  42. package/templates/apps/web/lib/__tests__/account-config.test.ts +69 -0
  43. package/templates/apps/web/lib/__tests__/auth-email.test.ts +99 -1
  44. package/templates/apps/web/lib/__tests__/telemetry-scrub.test.ts +20 -0
  45. package/templates/apps/web/lib/account-config.ts +52 -14
  46. package/templates/apps/web/lib/auth-email.ts +87 -5
  47. package/templates/apps/web/lib/mcp-oauth.ts +49 -6
  48. package/templates/apps/web/lib/telemetry-scrub.ts +6 -0
  49. package/templates/apps/web/messages/en.json +26 -1
  50. package/templates/database/seed.ts +7 -7
  51. package/versions.json +48 -48
  52. package/templates/apps/web/app/[locale]/thanks/[slug]/AccountInviteLink.tsx +0 -89
  53. package/templates/apps/web/app/[locale]/thanks/[slug]/__tests__/AccountInviteLink.test.tsx +0 -104
@@ -0,0 +1,269 @@
1
+ // oss: false
2
+ /**
3
+ * Tests for the by-result rows on the results permalink (#10827).
4
+ *
5
+ * `recommend()` returns the first matching row's `routeTo`; the page then
6
+ * sends a checkout row with a shown `_monthly` key straight to the Offerings
7
+ * buy route (a top-level navigation from the browser), and renders an offering row as one card named from the
8
+ * offering — priced, with its `/pricing?plan=` link, only while the offering
9
+ * is shown. A draft (an offering not in the shown set) renders its card with
10
+ * no price and no link, for either kind.
11
+ *
12
+ * Mocks mirror `landing.test.tsx`; the clock moves 16 s between cases so the
13
+ * page's 15 s shown-set read never carries over.
14
+ */
15
+ import { render, screen } from "@testing-library/react";
16
+ import type { FlowConfig, FlowResultRow } from "@working-theory/validation";
17
+ import {
18
+ encodePermalink,
19
+ PERMALINK_VERSION,
20
+ workspaceShownSetWireSchema,
21
+ } from "@working-theory/validation";
22
+ import type { ReactElement } from "react";
23
+
24
+ const mockGet = jest.fn();
25
+ const mockShown = jest.fn();
26
+ jest.mock("@working-theory/api-client", () => ({
27
+ __esModule: true,
28
+ flows: { get: (...args: unknown[]) => mockGet(...args) },
29
+ offerings: { shown: (...args: unknown[]) => mockShown(...args) },
30
+ }));
31
+
32
+ const mockRedirect = jest.fn((url: string) => {
33
+ throw new Error(`NEXT_REDIRECT:${url}`);
34
+ });
35
+ jest.mock("next/navigation", () => ({
36
+ __esModule: true,
37
+ redirect: (url: string) => mockRedirect(url),
38
+ }));
39
+
40
+ jest.mock("next-intl", () => ({
41
+ __esModule: true,
42
+ useTranslations: () => (key: string) => key,
43
+ useMessages: () => ({}),
44
+ }));
45
+
46
+ import Page from "../page";
47
+
48
+ const SLUG = "readiness";
49
+ const en = (s: string) => ({ en: s });
50
+
51
+ /** A scored diagnostic — never 0, monthly 2, weekly 4 points — with rows only. */
52
+ function config(byResult: FlowResultRow[]): FlowConfig {
53
+ return {
54
+ slug: SLUG,
55
+ defaultLocale: "en",
56
+ mode: "recommending",
57
+ steps: [
58
+ {
59
+ key: "q0",
60
+ type: "segmentation",
61
+ copy: { title: en("How often do you ship?") },
62
+ questions: [
63
+ {
64
+ name: "cadence",
65
+ options: [
66
+ { value: "never", label: en("Never") },
67
+ { value: "monthly", label: en("Monthly") },
68
+ { value: "weekly", label: en("Weekly") },
69
+ ],
70
+ },
71
+ ],
72
+ },
73
+ ],
74
+ scoring: {
75
+ version: 1,
76
+ points: [
77
+ {
78
+ name: "p_cadence",
79
+ question: "cadence",
80
+ kind: "optionWeights",
81
+ weights: { never: 0, monthly: 2, weekly: 4 },
82
+ },
83
+ ],
84
+ scores: { total: { sum: ["p_cadence"] } },
85
+ tiers: [{ key: "all", when: { score: "total", gte: 0 } }],
86
+ default: "all",
87
+ },
88
+ recommendation: { key: "result", copy: { title: en("Your result") }, byResult },
89
+ } as FlowConfig;
90
+ }
91
+
92
+ const SHOWN_SET = workspaceShownSetWireSchema.parse({
93
+ productIds: ["prod_growth"],
94
+ recommended: { plan: null, addon: null },
95
+ offerings: [
96
+ {
97
+ productId: "prod_growth",
98
+ plan: "growth-ops-growth",
99
+ name: "Growth Ops - Growth",
100
+ description: null,
101
+ marketingFeatures: [],
102
+ unitLabel: null,
103
+ note: null,
104
+ termsNote: null,
105
+ ailkGroup: "plan",
106
+ ailkOrder: null,
107
+ recommended: false,
108
+ prices: [
109
+ {
110
+ priceId: "price_growth_monthly",
111
+ lookupKey: "growth-ops-growth_monthly",
112
+ plan: "growth-ops-growth",
113
+ period: "monthly",
114
+ interval: "month",
115
+ amount: 120000,
116
+ currency: "usd",
117
+ },
118
+ ],
119
+ },
120
+ ],
121
+ state: "current",
122
+ snapshotAt: "2026-11-04T12:00:00.000Z",
123
+ });
124
+
125
+ function page(answers: Record<string, string>): Promise<ReactElement> {
126
+ return Page({
127
+ params: Promise.resolve({
128
+ locale: "en",
129
+ slug: SLUG,
130
+ payload: encodePermalink({ version: PERMALINK_VERSION, flowSlug: SLUG, answers }),
131
+ }),
132
+ });
133
+ }
134
+
135
+ async function redirectOf(answers: Record<string, string>): Promise<string | null> {
136
+ const err = await page(answers).then(
137
+ () => null,
138
+ (e: unknown) => e,
139
+ );
140
+ const message = err instanceof Error ? err.message : "";
141
+ return message.startsWith("NEXT_REDIRECT:") ? message.slice("NEXT_REDIRECT:".length) : null;
142
+ }
143
+
144
+ const checkoutRow = (offeringKey: string): FlowResultRow => ({
145
+ when: { kind: "tier", op: "is", level: 4 },
146
+ routeTo: { kind: "checkout", offeringKey },
147
+ });
148
+ const offeringRow = (offeringKey: string): FlowResultRow => ({
149
+ when: { kind: "answer", op: "atLeast", question: "cadence", value: "monthly" },
150
+ routeTo: { kind: "offering", offeringKey },
151
+ });
152
+
153
+ /** The navigations jsdom was asked for and reports as not implemented. */
154
+ let consoleError: jest.SpyInstance<void, unknown[]>;
155
+ function navigations(): unknown[] {
156
+ return consoleError.mock.calls.filter((args) =>
157
+ args.some((arg: unknown) => String(arg instanceof Error ? arg.message : arg).includes("navigation")),
158
+ );
159
+ }
160
+
161
+ beforeAll(() => {
162
+ jest.useFakeTimers({ now: new Date("2026-11-04T12:00:00.000Z") });
163
+ });
164
+
165
+ afterAll(() => {
166
+ jest.useRealTimers();
167
+ });
168
+
169
+ beforeEach(() => {
170
+ jest.setSystemTime(Date.now() + 16_000);
171
+ mockGet.mockReset();
172
+ mockShown.mockReset();
173
+ mockRedirect.mockClear();
174
+ consoleError = jest.spyOn(console, "error").mockImplementation(() => undefined);
175
+ window.sessionStorage.clear();
176
+ mockShown.mockResolvedValue({ ok: true, status: 200, body: { status: "shown", shownSet: SHOWN_SET } });
177
+ });
178
+
179
+ afterEach(() => {
180
+ consoleError.mockRestore();
181
+ // Every landing is a root-relative path of grammar characters only.
182
+ for (const [url] of mockRedirect.mock.calls) {
183
+ expect(url).toMatch(/^\/[a-z0-9/?=_-]+$/);
184
+ expect(url).not.toContain("//");
185
+ }
186
+ });
187
+
188
+ describe("#10827 — a checkout row sends the respondent to checkout", () => {
189
+ it("a shown _monthly key → a top-level navigation to the Offerings buy route for that key", async () => {
190
+ // The walk arrives by a client-side navigation, which the buy route
191
+ // refuses — so the browser, not a server redirect, goes to checkout.
192
+ mockGet.mockResolvedValue({ ok: true, status: 200, body: config([checkoutRow("growth-ops-growth_monthly")]) });
193
+ // This tab just walked the flow: `FlowStepperClient`'s session entry.
194
+ window.sessionStorage.setItem(`ailk:flow-session:${SLUG}`, "sess_1");
195
+ render(await page({ cadence: "weekly" }));
196
+ expect(mockRedirect).not.toHaveBeenCalled();
197
+ // jsdom performs no navigation; it reports each one it was asked for.
198
+ expect(navigations()).toHaveLength(1);
199
+ expect(screen.getByTestId("recommendation-card-growth-ops-growth_monthly-terminal-getStarted")).toBeInTheDocument();
200
+ // The card stays as the fallback, priced from the offering.
201
+ expect(screen.getByTestId("recommendation-card-growth-ops-growth_monthly-price")).toBeInTheDocument();
202
+ });
203
+
204
+ it.each<[string, Record<string, string> | undefined, boolean]>([
205
+ ["a cold load of a shared permalink (no walk in this tab)", undefined, false],
206
+ ["a ?checkout=cancelled return", { checkout: "cancelled" }, true],
207
+ ])("%s shows the priced card and waits for the click", async (_label, search, walked) => {
208
+ mockGet.mockResolvedValue({ ok: true, status: 200, body: config([checkoutRow("growth-ops-growth_monthly")]) });
209
+ if (walked) window.sessionStorage.setItem(`ailk:flow-session:${SLUG}`, "sess_1");
210
+ render(
211
+ await Page({
212
+ params: Promise.resolve({
213
+ locale: "en",
214
+ slug: SLUG,
215
+ payload: encodePermalink({ version: PERMALINK_VERSION, flowSlug: SLUG, answers: { cadence: "weekly" } }),
216
+ }),
217
+ ...(search !== undefined ? { searchParams: Promise.resolve(search) } : {}),
218
+ }),
219
+ );
220
+ expect(navigations()).toEqual([]);
221
+ expect(screen.getByTestId("recommendation-card-growth-ops-growth_monthly-terminal-getStarted")).toBeInTheDocument();
222
+ });
223
+
224
+ it("a {plan} key → the /pricing?plan= landing", async () => {
225
+ mockGet.mockResolvedValue({ ok: true, status: 200, body: config([checkoutRow("growth-ops-growth")]) });
226
+ await expect(redirectOf({ cadence: "weekly" })).resolves.toBe("/en/pricing?plan=growth-ops-growth");
227
+ });
228
+
229
+ it("a key not shown (a draft) renders its card with no price and no checkout", async () => {
230
+ mockGet.mockResolvedValue({ ok: true, status: 200, body: config([checkoutRow("ai-readiness-workshop_monthly")]) });
231
+ render(await page({ cadence: "weekly" }));
232
+ expect(mockRedirect).not.toHaveBeenCalled();
233
+ const card = screen.getByTestId("recommendation-card-ai-readiness-workshop_monthly");
234
+ expect(card).toHaveTextContent("Ai readiness workshop");
235
+ expect(screen.queryByTestId("recommendation-card-ai-readiness-workshop_monthly-price")).toBeNull();
236
+ expect(screen.queryByTestId("recommendation-card-ai-readiness-workshop_monthly-terminal-getStarted")).toBeNull();
237
+ expect(navigations()).toEqual([]);
238
+ });
239
+ });
240
+
241
+ describe("#10827 — an offering row renders a card named from the offering", () => {
242
+ it("a shown offering: its product name, its price and its /pricing link", async () => {
243
+ mockGet.mockResolvedValue({ ok: true, status: 200, body: config([offeringRow("growth-ops-growth")]) });
244
+ render(await page({ cadence: "monthly" }));
245
+ expect(mockRedirect).not.toHaveBeenCalled();
246
+ expect(screen.getByTestId("recommendation-card-growth-ops-growth")).toHaveTextContent("Growth Ops - Growth");
247
+ expect(screen.getByTestId("recommendation-card-growth-ops-growth-price")).toBeInTheDocument();
248
+ expect(screen.getByTestId("recommendation-card-growth-ops-growth-terminal-getStarted")).toBeInTheDocument();
249
+ expect(navigations()).toEqual([]);
250
+ });
251
+
252
+ it("a draft offering (not shown): the card with no price and no link", async () => {
253
+ mockGet.mockResolvedValue({ ok: true, status: 200, body: config([offeringRow("ai-readiness-workshop")]) });
254
+ render(await page({ cadence: "weekly" }));
255
+ expect(screen.getByTestId("recommendation-card-ai-readiness-workshop")).toHaveTextContent(
256
+ "Ai readiness workshop",
257
+ );
258
+ expect(screen.queryByTestId("recommendation-card-ai-readiness-workshop-price")).toBeNull();
259
+ expect(screen.queryByTestId("recommendation-card-ai-readiness-workshop-terminal-getStarted")).toBeNull();
260
+ });
261
+
262
+ it("no row matches: the results page with no card and no redirect", async () => {
263
+ mockGet.mockResolvedValue({ ok: true, status: 200, body: config([offeringRow("growth-ops-growth")]) });
264
+ render(await page({ cadence: "never" }));
265
+ expect(screen.getByTestId("flow-results")).toBeInTheDocument();
266
+ expect(screen.queryByTestId("recommendation-card-growth-ops-growth")).toBeNull();
267
+ expect(mockRedirect).not.toHaveBeenCalled();
268
+ });
269
+ });
@@ -0,0 +1,179 @@
1
+ // oss: false
2
+ /**
3
+ * The respondent's own score on the results page (#10828).
4
+ *
5
+ * A scored submission renders the overall score — points out of the max and
6
+ * its Level name — then one labelled bar with its Level per dimension, in
7
+ * register order, then the cards. An unscored magnet renders the cards only.
8
+ * The score is the browser's own `evaluateWaitlistScoring` run over the
9
+ * decoded answers (#10825), as `recommend()` already is.
10
+ *
11
+ * Mocks mirror `ResultsClient.no-commerce.test.tsx`; the translator echoes
12
+ * its `n` value so the "Level {n}" fallback is observable.
13
+ */
14
+ import { render, screen, within } from "@testing-library/react";
15
+ import type { FlowConfig } from "@working-theory/validation";
16
+
17
+ jest.mock("@working-theory/api-client", () => ({
18
+ __esModule: true,
19
+ flows: { get: jest.fn() },
20
+ }));
21
+
22
+ // The boundary under test is ResultsClient's render, not the save action
23
+ // (save.actions.test.ts) — the narrow-scope mock ResultsClient's suites carry.
24
+ // eslint-disable-next-line no-restricted-syntax -- see comment above
25
+ jest.mock("../../../save.actions", () => ({
26
+ saveRecommendationAction: jest.fn(),
27
+ }));
28
+
29
+ jest.mock("next-intl", () => ({
30
+ __esModule: true,
31
+ useTranslations:
32
+ () =>
33
+ (key: string, values?: { n?: number }): string =>
34
+ values?.n !== undefined ? `${key} ${values.n}` : key,
35
+ useMessages: () => ({}),
36
+ }));
37
+
38
+ import { ResultsClient } from "../ResultsClient";
39
+
40
+ const SLUG = "ai-readiness";
41
+ const en = (s: string) => ({ en: s });
42
+
43
+ /** A three-option question, scored 0 / 2 / 4. */
44
+ function question(name: string) {
45
+ return {
46
+ key: `s_${name}`,
47
+ type: "segmentation" as const,
48
+ copy: { title: en(name) },
49
+ questions: [
50
+ {
51
+ name,
52
+ options: [
53
+ { value: "low", label: en("Low") },
54
+ { value: "mid", label: en("Mid") },
55
+ { value: "high", label: en("High") },
56
+ ],
57
+ },
58
+ ],
59
+ };
60
+ }
61
+
62
+ const QUESTIONS = ["vision", "data", "skills"] as const;
63
+
64
+ type Scoring = NonNullable<FlowConfig["scoring"]>;
65
+
66
+ const SCORING = {
67
+ version: 1,
68
+ points: QUESTIONS.map((q) => ({
69
+ name: `p_${q}`,
70
+ question: q,
71
+ kind: "optionWeights" as const,
72
+ weights: { low: 0, mid: 2, high: 4 },
73
+ })),
74
+ scores: { total: { sum: QUESTIONS.map((q) => `p_${q}`) } },
75
+ tiers: [{ key: "all", when: { score: "total", gte: 0 } }],
76
+ default: "all",
77
+ // Register order is not alphabetical: the page keeps it.
78
+ dimensions: [
79
+ { key: "strategy", name: "Strategy", questions: ["vision"] },
80
+ { key: "data", name: "Data", questions: ["data"] },
81
+ { key: "people", name: "People", questions: ["skills"] },
82
+ ],
83
+ levels: { names: ["Exploring", "Practising", "Scaling", "Leading"] },
84
+ } satisfies Scoring;
85
+
86
+ function config(scoring: Scoring | undefined): FlowConfig {
87
+ return {
88
+ slug: SLUG,
89
+ defaultLocale: "en",
90
+ mode: "recommending",
91
+ steps: QUESTIONS.map(question),
92
+ ...(scoring !== undefined ? { scoring } : {}),
93
+ offers: [
94
+ {
95
+ key: "workshop",
96
+ copy: { name: en("Workshop") },
97
+ price: { kind: "label", label: en("On request") },
98
+ rules: [{ when: { answer: "vision", in: ["low", "mid", "high"] }, reason: en("Start here.") }],
99
+ },
100
+ ],
101
+ recommendation: { key: "result", copy: { title: en("Your AI readiness") } },
102
+ } as FlowConfig;
103
+ }
104
+
105
+ // vision low (0/4) · data mid (2/4) · skills high (4/4) → 6 of 12 = 50%.
106
+ const ANSWERS = { vision: "low", data: "mid", skills: "high" };
107
+
108
+ function renderResults(cfg: FlowConfig): void {
109
+ render(<ResultsClient config={cfg} locale="en" answers={ANSWERS} slug={SLUG} payload="v1-abc" />);
110
+ }
111
+
112
+ describe("#10828 — a scored submission's results page", () => {
113
+ it("renders the overall score as points and its Level name", () => {
114
+ renderResults(config(SCORING));
115
+ const total = screen.getByTestId("flow-results-score-total");
116
+ expect(within(total).getByTestId("flow-results-score-total-points")).toHaveTextContent("6 / 12");
117
+ // 50% of all points is Level 3.
118
+ expect(within(total).getByTestId("flow-results-score-total-level")).toHaveTextContent("Scaling");
119
+ });
120
+
121
+ it("renders one labelled bar with its Level per dimension, in register order", () => {
122
+ renderResults(config(SCORING));
123
+ const region = screen.getByTestId("flow-results-score");
124
+ const meters = within(region).getAllByRole("meter");
125
+ // The overall meter, then Strategy · Data · People as the register lists them.
126
+ expect(meters.map((m) => m.getAttribute("aria-label"))).toEqual(["score", "Strategy", "Data", "People"]);
127
+ expect(meters.map((m) => m.getAttribute("aria-valuetext"))).toEqual([
128
+ "6 / 12, Scaling",
129
+ "0 / 4, Exploring",
130
+ "2 / 4, Scaling",
131
+ "4 / 4, Leading",
132
+ ]);
133
+ expect(screen.getByTestId("flow-results-score-dimension-data-level")).toHaveTextContent("Scaling");
134
+ });
135
+
136
+ it("renders the score after the heading and before the cards", () => {
137
+ renderResults(config(SCORING));
138
+ const heading = screen.getByRole("heading", { name: "Your AI readiness" });
139
+ const score = screen.getByTestId("flow-results-score");
140
+ const card = screen.getByTestId("recommendation-card-workshop");
141
+ expect(heading.compareDocumentPosition(score) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
142
+ expect(score.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
143
+ });
144
+
145
+ it("names a Level 'Level {n}' when the register names none", () => {
146
+ const { levels: _levels, ...unnamed } = SCORING;
147
+ renderResults(config(unnamed));
148
+ expect(screen.getByTestId("flow-results-score-total-level")).toHaveTextContent("label 3");
149
+ });
150
+
151
+ it("renders the overall score alone for a register with no dimensions", () => {
152
+ const { dimensions: _dimensions, ...flat } = SCORING;
153
+ renderResults(config(flat));
154
+ expect(within(screen.getByTestId("flow-results-score")).getAllByRole("meter")).toHaveLength(1);
155
+ });
156
+ });
157
+
158
+ describe("#10828 — an unscored magnet's results page", () => {
159
+ it("renders the cards only — no score, no bar", () => {
160
+ renderResults(config(undefined));
161
+ expect(screen.queryByTestId("flow-results-score")).toBeNull();
162
+ expect(screen.queryAllByRole("meter")).toHaveLength(0);
163
+ expect(screen.getByTestId("recommendation-card-workshop")).toBeInTheDocument();
164
+ });
165
+
166
+ it("renders the cards only for a register that scores no points", () => {
167
+ renderResults(
168
+ config({
169
+ ...SCORING,
170
+ points: [],
171
+ scores: {},
172
+ tiers: [{ key: "all", when: { answer: "vision", in: ["low", "mid", "high"] } }],
173
+ dimensions: [],
174
+ }),
175
+ );
176
+ expect(screen.queryByTestId("flow-results-score")).toBeNull();
177
+ expect(screen.getByTestId("recommendation-card-workshop")).toBeInTheDocument();
178
+ });
179
+ });
@@ -11,7 +11,8 @@
11
11
  * — step 1, never an error page — on ANY of: an invalid payload (FR6), a
12
12
  * stale-version payload (FR6), a payload whose own `flowSlug` does not match
13
13
  * this route's `[slug]` (D2/FR6), or a served flow that is not a
14
- * recommending register (D8 — `mode !== "recommending" || !offers`, checked
14
+ * recommending register (D8 — `mode !== "recommending"`, or neither `offers`
15
+ * nor `recommendation.byResult` (#10827), checked
15
16
  * against the field `recommend()` is about to be handed rather than
16
17
  * inferring the compiler's five-keys-travel-together guarantee).
17
18
  *
@@ -34,11 +35,22 @@
34
35
  * key no longer shown, any failed read). The URL is built only from an
35
36
  * allowlisted locale and a `parseLookupKey` plan. A flow with no such offer,
36
37
  * or whose first fit carries none, renders as before with no read.
38
+ *
39
+ * #10827 — the by-result rows. `recommend()` returns the first matching
40
+ * row's `routeTo` (a legacy offer rule read as a row when the flow carries
41
+ * no `recommendation.byResult`; the landing above is that row's checkout
42
+ * kind for a `{plan}` key). A checkout row with a full lookup key goes
43
+ * straight to the Offerings buy route while the key is shown; an offering
44
+ * row — or a checkout row whose offering is not shown, a draft — renders
45
+ * the results page with one card named from the offering, priced only
46
+ * while the offering is shown.
37
47
  */
38
48
  import { flows, offerings } from "@working-theory/api-client";
39
49
  import {
40
50
  decodePermalink,
41
51
  type FlowConfig,
52
+ type FlowResultRouteTo,
53
+ flowRecommendRegister,
42
54
  parseLookupKey,
43
55
  recommend,
44
56
  resolveLocalizedString,
@@ -51,8 +63,9 @@ import { redirect } from "next/navigation";
51
63
  import type { ReactElement } from "react";
52
64
 
53
65
  import { browserApiOrigin } from "../../../../../../lib/api-origin.generated";
66
+ import { offeringsCheckoutHref } from "../../../../../../lib/offerings-pricing";
54
67
 
55
- import type { ResultsReturnState } from "./ResultsClient";
68
+ import type { ResultsOfferingCard, ResultsReturnState } from "./ResultsClient";
56
69
  import { ResultsClient } from "./ResultsClient";
57
70
 
58
71
  export const dynamic = "force-dynamic";
@@ -142,58 +155,109 @@ function isOfferingsOffer(offer: unknown): boolean {
142
155
  );
143
156
  }
144
157
 
158
+ /** #10827 — a shown set's prices of `offeringKey`: its own key, else its plan's. */
159
+ function shownPricesOf(shown: WorkspaceShownSetWire | null, offeringKey: string) {
160
+ const exact = parseLookupKey(offeringKey);
161
+ const plan = exact?.plan ?? offeringKey;
162
+ const product = shown?.offerings.find((o) => o.prices.some((p) => p.plan === plan));
163
+ const prices = product?.prices ?? [];
164
+ return {
165
+ plan,
166
+ product,
167
+ price:
168
+ exact !== null
169
+ ? prices.find((p) => p.lookupKey === offeringKey)
170
+ : (prices.find((p) => p.period === "monthly") ?? prices[0]),
171
+ };
172
+ }
173
+
174
+ type ResultLanding =
175
+ | { kind: "redirect"; url: string }
176
+ | { kind: "render"; card?: ResultsOfferingCard };
177
+
145
178
  /**
146
- * #9071 D3 — where a completed Offerings recommender lands, or `null` to
147
- * render the results page as before. The served config is not re-parsed
148
- * here, so every read of it is shape-checked and any throw is `null`.
179
+ * #9071 D3 / #10827 — where a completed walk lands: a redirect (the
180
+ * `/pricing?plan=` landing, or checkout), or the results page with the
181
+ * matched row's offering card. The served config is not re-parsed here, so
182
+ * every read of it is shape-checked and any throw renders as before.
149
183
  */
150
- async function recommenderLanding(
184
+ async function resultLanding(
151
185
  config: FlowConfig,
152
186
  answers: WaitlistAnswers,
153
187
  locale: string,
154
- ): Promise<string | null> {
188
+ ): Promise<ResultLanding> {
155
189
  try {
190
+ const byResult: unknown = config.recommendation?.byResult;
191
+ const authored = Array.isArray(byResult);
156
192
  const offers: unknown = config.offers;
157
- if (!Array.isArray(offers) || !offers.some(isOfferingsOffer)) return null;
193
+ if (!authored && !(Array.isArray(offers) && offers.some(isOfferingsOffer))) {
194
+ return { kind: "render" };
195
+ }
158
196
 
159
- let fitKey: string | undefined;
197
+ let routeTo: FlowResultRouteTo | undefined;
160
198
  try {
161
- fitKey = recommend(
162
- {
163
- key: config.experiment?.key ?? config.slug,
164
- offers: config.offers,
165
- pairings: config.pairings,
166
- rateTable: config.rateTable,
167
- scoring: config.scoring,
168
- },
169
- answers,
170
- ).fits[0]?.offerKey;
199
+ routeTo = recommend(flowRecommendRegister(config), answers).routeTo;
171
200
  } catch {
172
- fitKey = undefined;
201
+ routeTo = undefined;
173
202
  }
174
- const fit: unknown =
175
- fitKey === undefined
176
- ? undefined
177
- : offers.find(
178
- (o: unknown) =>
179
- typeof o === "object" && o !== null && (o as { key?: unknown }).key === fitKey,
180
- );
181
- if (fit !== undefined && !isOfferingsOffer(fit)) return null;
182
203
 
183
204
  const safeLocale = ENABLED_LOCALES.includes(locale) ? locale : DEFAULT_LOCALE;
184
205
  const base = `/${safeLocale}/pricing`;
185
- if (fit === undefined) return base;
186
- const lookupKey = (fit as { lookupKey: string }).lookupKey;
187
- const parsed = parseLookupKey(lookupKey);
188
- if (parsed === null) return base;
206
+ if (routeTo === undefined || routeTo.kind === "none") {
207
+ // An Offerings recommender with no fit lands on /pricing with no badge.
208
+ return authored ? { kind: "render" } : { kind: "redirect", url: base };
209
+ }
210
+ if (!authored && routeTo.kind === "offering") return { kind: "render" };
189
211
 
212
+ const { offeringKey } = routeTo;
190
213
  const shown = await readCurrentShownSet();
191
- const isShown =
192
- shown?.offerings.some((o) => o.prices.some((p) => p.lookupKey === lookupKey)) ??
193
- false;
194
- return isShown ? `${base}?plan=${parsed.plan}` : base;
214
+ const { plan, product, price } = shownPricesOf(shown, offeringKey);
215
+ // Built from the shown set's own grammar-checked Price, never the config key.
216
+ let checkoutHref: string | null = null;
217
+ if (routeTo.kind === "checkout") {
218
+ // A `{plan}` key lands on /pricing?plan=. A full key goes straight to
219
+ // the buy route — from the browser (`ResultsClient`), because the walk
220
+ // arrives by a client-side navigation and the buy route refuses
221
+ // anything but a top-level document load.
222
+ if (price !== undefined && parseLookupKey(offeringKey) === null) {
223
+ return { kind: "redirect", url: `${base}?plan=${price.plan}` };
224
+ }
225
+ if (price !== undefined) checkoutHref = offeringsCheckoutHref(price.lookupKey);
226
+ if (checkoutHref === null && !authored) return { kind: "redirect", url: base };
227
+ }
228
+
229
+ // An offering's card — or a checkout row's offering not shown (a draft).
230
+ const legacy = Array.isArray(offers)
231
+ ? (offers as unknown[]).find(
232
+ (o): o is { copy: { name: Parameters<typeof resolveLocalizedString>[0] } } =>
233
+ typeof o === "object" &&
234
+ o !== null &&
235
+ (o as { key?: unknown }).key === offeringKey &&
236
+ (o as { copy?: { name?: unknown } }).copy?.name !== undefined,
237
+ )
238
+ : undefined;
239
+ // `/pricing`'s last guard before markup: no format or control characters.
240
+ const title =
241
+ product?.name.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}]/gu, "") ??
242
+ (legacy
243
+ ? resolveLocalizedString(legacy.copy.name, locale, config.defaultLocale)
244
+ : plan.charAt(0).toUpperCase() + plan.slice(1).replace(/-/g, " "));
245
+ return {
246
+ kind: "render",
247
+ card: {
248
+ offeringKey,
249
+ title,
250
+ ...(price !== undefined
251
+ ? {
252
+ price: { amount: price.amount, currency: price.currency, period: price.period },
253
+ href: checkoutHref ?? `${base}?plan=${price.plan}`,
254
+ }
255
+ : {}),
256
+ ...(checkoutHref !== null ? { checkoutOnLoad: true } : {}),
257
+ },
258
+ };
195
259
  } catch {
196
- return null;
260
+ return { kind: "render" };
197
261
  }
198
262
  }
199
263
 
@@ -236,16 +300,19 @@ export default async function Page({
236
300
  if (!res.ok) {
237
301
  redirect(`/${locale}/flows/${slug}`);
238
302
  }
239
- if (res.body.mode !== "recommending" || res.body.offers === undefined) {
303
+ if (
304
+ res.body.mode !== "recommending" ||
305
+ (res.body.offers === undefined && res.body.recommendation?.byResult === undefined)
306
+ ) {
240
307
  redirect(`/${locale}/flows/${slug}`);
241
308
  }
242
309
 
243
- const landing = await recommenderLanding(
310
+ const landing = await resultLanding(
244
311
  res.body,
245
312
  decoded.value.answers,
246
313
  locale,
247
314
  );
248
- if (landing !== null) redirect(landing);
315
+ if (landing.kind === "redirect") redirect(landing.url);
249
316
 
250
317
  // FR7 — read AFTER every redirect guard above, so a return param never
251
318
  // changes which guard fires or where it sends the visitor.
@@ -258,6 +325,7 @@ export default async function Page({
258
325
  answers={decoded.value.answers}
259
326
  slug={slug}
260
327
  payload={payload}
328
+ {...(landing.card !== undefined ? { offeringCard: landing.card } : {})}
261
329
  {...(returnState !== undefined ? { returnState } : {})}
262
330
  />
263
331
  );