create-ailk 0.20.0 → 0.22.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 (222) hide show
  1. package/README.md +21 -1
  2. package/component-catalog.json +220 -8
  3. package/component-catalog.md +21 -9
  4. package/dist/add-module.js +9 -5
  5. package/dist/apply-design.d.ts +9 -0
  6. package/dist/apply-design.js +78 -31
  7. package/dist/derive-architecture.d.ts +8 -1
  8. package/dist/derive-architecture.js +38 -3
  9. package/dist/design-home.d.ts +54 -11
  10. package/dist/design-home.js +160 -22
  11. package/dist/design-package.js +7 -2
  12. package/dist/lib/design-checks.d.ts +6 -1
  13. package/dist/lib/design-checks.js +23 -2
  14. package/dist/lib/env-catalog.js +5 -1
  15. package/dist/module-architecture.js +4 -2
  16. package/dist/programmatic.js +63 -25
  17. package/dist/site-chrome.d.ts +8 -0
  18. package/dist/site-chrome.js +17 -1
  19. package/dist/site-roster.d.ts +4 -2
  20. package/dist/site-roster.js +7 -5
  21. package/dist/spoke-checkout.d.ts +39 -18
  22. package/dist/spoke-checkout.js +177 -236
  23. package/dist/starter-grid.js +16 -0
  24. package/dist/surfaces.js +30 -14
  25. package/dist/sync-routes.d.ts +28 -0
  26. package/dist/sync-routes.js +124 -1
  27. package/dist/template-record.d.ts +4 -3
  28. package/dist/template-record.js +6 -3
  29. package/dist/topology.js +25 -1
  30. package/dist/update.d.ts +6 -1
  31. package/dist/update.js +125 -18
  32. package/package.json +3 -3
  33. package/site-templates/_base/ailk-template.json +2 -2
  34. package/site-templates/_base/content/en/WorkingAgreementPage/working-agreement.mdx +78 -0
  35. package/site-templates/designs/minimalism/DESIGN.md +1 -1
  36. package/site-templates/designs/minimalism/contact/local-business-service.mdx +23 -0
  37. package/site-templates/designs/minimalism/contact/organization-product.mdx +23 -0
  38. package/site-templates/designs/minimalism/contact/organization-service.mdx +23 -0
  39. package/site-templates/designs/minimalism/contact/person-service.mdx +23 -0
  40. package/site-templates/marketing-site/TEMPLATE-MANIFEST.json +18 -1
  41. package/site-templates/marketing-site/TEMPLATE-MANIFEST.md +11 -0
  42. package/site-templates/marketing-site-free/TEMPLATE-MANIFEST.json +18 -1
  43. package/site-templates/marketing-site-free/TEMPLATE-MANIFEST.md +34 -23
  44. package/site-templates/shapes/local-business-service/TEMPLATE-MANIFEST.json +18 -1
  45. package/site-templates/shapes/local-business-service/TEMPLATE-MANIFEST.md +33 -23
  46. package/site-templates/shapes/organization-service/TEMPLATE-MANIFEST.json +18 -1
  47. package/site-templates/shapes/organization-service/TEMPLATE-MANIFEST.md +33 -23
  48. package/site-templates/shapes/person-service/TEMPLATE-MANIFEST.json +18 -1
  49. package/site-templates/shapes/person-service/TEMPLATE-MANIFEST.md +31 -21
  50. package/templates/README.md +26 -25
  51. package/templates/apps/api/CLAUDE.md +20 -7
  52. package/templates/apps/api/jest.config.cjs +1 -0
  53. package/templates/apps/api/src/lib/__tests__/consent-store.test.ts +19 -0
  54. package/templates/apps/api/src/lib/__tests__/flow-completion-store.test.ts +149 -0
  55. package/templates/apps/api/src/lib/consent-store.ts +28 -0
  56. package/templates/apps/api/src/lib/flow-completion-store.ts +136 -0
  57. package/templates/apps/api/src/lib/hub-sign-in-store.ts +38 -2
  58. package/templates/apps/api/src/lib/proposal-paid-store.ts +21 -4
  59. package/templates/apps/api/src/middleware/__tests__/auth.hub-session-path.test.ts +14 -3
  60. package/templates/apps/api/src/middleware/auth.ts +13 -6
  61. package/templates/apps/api/src/openapi/spec.ts +30 -3
  62. package/templates/apps/api/src/routes/auth/__tests__/hub-sign-in.test.ts +49 -0
  63. package/templates/apps/api/src/routes/auth/hub-sign-in.ts +41 -0
  64. package/templates/apps/api/src/routes/consent/__tests__/account.test.ts +386 -0
  65. package/templates/apps/api/src/routes/consent/account.ts +266 -0
  66. package/templates/apps/api/src/routes/consent/index.ts +15 -7
  67. package/templates/apps/api/src/routes/content/__tests__/get-page.test.ts +36 -0
  68. package/templates/apps/api/src/routes/content/get-page.ts +4 -0
  69. package/templates/apps/api/src/routes/leads/__tests__/magnet-completion.test.ts +515 -0
  70. package/templates/apps/api/src/routes/leads/index.ts +161 -7
  71. package/templates/apps/api/src/routes/project-listings/__tests__/drafts.test.ts +26 -0
  72. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-checkout-consent.test.ts +649 -0
  73. package/templates/apps/api/src/routes/webhooks/stripe.ts +154 -19
  74. package/templates/apps/api/src/server.ts +28 -0
  75. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +1038 -118
  76. package/templates/apps/api/src/services/__tests__/magnet-completion.test.ts +389 -0
  77. package/templates/apps/api/src/services/checkout-buyer.ts +100 -4
  78. package/templates/apps/api/src/services/consent.ts +95 -0
  79. package/templates/apps/api/src/services/lead-routing.ts +337 -8
  80. package/templates/apps/api/src/services/magnet-completion.ts +242 -0
  81. package/templates/apps/api/src/services/person.ts +40 -8
  82. package/templates/apps/api/src/services/plan-offerings.ts +59 -0
  83. package/templates/apps/api/src/services/project-listings.ts +6 -1
  84. package/templates/apps/api/src/services/public-site-resolver.ts +8 -1
  85. package/templates/apps/mcp/__tests__/catalog-drift.test.ts +69 -61
  86. package/templates/apps/mcp/jest.config.cjs +1 -0
  87. package/templates/apps/web/.env.example +14 -0
  88. package/templates/apps/web/CLAUDE.md +139 -3
  89. package/templates/apps/web/__tests__/__mocks__/next-intl-server.ts +6 -2
  90. package/templates/apps/web/app/[locale]/(auth)/__tests__/auth-pages.test.tsx +5 -4
  91. package/templates/apps/web/app/[locale]/(auth)/forgot-password/forgot-password-card.tsx +5 -1
  92. package/templates/apps/web/app/[locale]/(auth)/forgot-password/page.tsx +2 -0
  93. package/templates/apps/web/app/[locale]/(auth)/layout.tsx +3 -14
  94. package/templates/apps/web/app/[locale]/(auth)/reset-password/page.tsx +2 -0
  95. package/templates/apps/web/app/[locale]/(auth)/reset-password/reset-password-card.tsx +5 -1
  96. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/page.test.tsx +160 -8
  97. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/sign-in-card.test.tsx +12 -9
  98. package/templates/apps/web/app/[locale]/(auth)/sign-in/page.tsx +105 -2
  99. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +36 -3
  100. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-text.ts +47 -1
  101. package/templates/apps/web/app/[locale]/(auth)/sign-up/__tests__/sign-up-card.test.tsx +60 -22
  102. package/templates/apps/web/app/[locale]/(auth)/sign-up/page.tsx +16 -8
  103. package/templates/apps/web/app/[locale]/(auth)/sign-up/sign-up-card.tsx +85 -31
  104. package/templates/apps/web/app/[locale]/(auth)/use-auth-card-flow.ts +18 -4
  105. package/templates/apps/web/app/[locale]/(auth)/verify-email/page.tsx +3 -1
  106. package/templates/apps/web/app/[locale]/(authed)/__tests__/gate.test.tsx +7 -4
  107. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/agreements-prompt.test.tsx +227 -207
  108. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +17 -1
  109. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout.test.tsx +143 -1
  110. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-menu.test.tsx +4 -0
  111. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +385 -89
  112. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/popups.test.tsx +5 -0
  113. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/privacy.test.tsx +44 -5
  114. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +68 -34
  115. package/templates/apps/web/app/[locale]/(authed)/account/actions.ts +0 -8
  116. package/templates/apps/web/app/[locale]/(authed)/account/agreements-actions.ts +39 -151
  117. package/templates/apps/web/app/[locale]/(authed)/account/agreements-gate.ts +61 -0
  118. package/templates/apps/web/app/[locale]/(authed)/account/agreements-prompt.tsx +143 -140
  119. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +40 -6
  120. package/templates/apps/web/app/[locale]/(authed)/account/page.tsx +68 -54
  121. package/templates/apps/web/app/[locale]/(authed)/account/privacy/page.tsx +5 -1
  122. package/templates/apps/web/app/[locale]/about/[slug]/page.tsx +46 -0
  123. package/templates/apps/web/app/[locale]/about/__tests__/about-routes.test.tsx +350 -0
  124. package/templates/apps/web/app/[locale]/about/page.tsx +83 -1
  125. package/templates/apps/web/app/[locale]/careers/[slug]/apply.actions.ts +293 -0
  126. package/templates/apps/web/app/[locale]/careers/[slug]/job-application-form.ts +115 -0
  127. package/templates/apps/web/app/[locale]/careers/[slug]/page.tsx +146 -1
  128. package/templates/apps/web/app/[locale]/careers/__tests__/apply.actions.test.ts +310 -0
  129. package/templates/apps/web/app/[locale]/careers/__tests__/job-application-form.test.ts +143 -0
  130. package/templates/apps/web/app/[locale]/careers/__tests__/job-apply-page.test.tsx +350 -0
  131. package/templates/apps/web/app/[locale]/careers/__tests__/page-renderer-migration.test.tsx +29 -3
  132. package/templates/apps/web/app/[locale]/case-studies/__tests__/page-renderer-migration.test.tsx +2 -2
  133. package/templates/apps/web/app/[locale]/checkout/__tests__/pages.test.tsx +139 -0
  134. package/templates/apps/web/app/[locale]/checkout/__tests__/thank-you-account.test.tsx +136 -0
  135. package/templates/apps/web/app/[locale]/checkout/thank-you/page.tsx +114 -0
  136. package/templates/apps/web/app/[locale]/checkout/unavailable/page.tsx +51 -0
  137. package/templates/apps/web/app/[locale]/clients/__tests__/page-renderer-migration.test.tsx +1 -1
  138. package/templates/apps/web/app/[locale]/contact/ConversationalIntakeWrapper.tsx +24 -1
  139. package/templates/apps/web/app/[locale]/contact/__tests__/ConversationalIntakeWrapper.test.tsx +79 -4
  140. package/templates/apps/web/app/[locale]/contact/__tests__/contact-form-magnet.test.ts +138 -0
  141. package/templates/apps/web/app/[locale]/contact/__tests__/contact-form-text.test.ts +17 -0
  142. package/templates/apps/web/app/[locale]/contact/__tests__/contact-magnet-page.test.tsx +386 -0
  143. package/templates/apps/web/app/[locale]/contact/__tests__/contact.actions.test.ts +504 -24
  144. package/templates/apps/web/app/[locale]/contact/__tests__/page-renderer-migration.test.tsx +12 -3
  145. package/templates/apps/web/app/[locale]/contact/contact-form-magnet.ts +77 -0
  146. package/templates/apps/web/app/[locale]/contact/contact-form-text.ts +2 -0
  147. package/templates/apps/web/app/[locale]/contact/contact.actions.ts +184 -41
  148. package/templates/apps/web/app/[locale]/contact/intake-script.ts +26 -0
  149. package/templates/apps/web/app/[locale]/contact/page.tsx +120 -16
  150. package/templates/apps/web/app/[locale]/courses/__tests__/page-renderer-migration.test.tsx +2 -2
  151. package/templates/apps/web/app/[locale]/downloads/__tests__/page-renderer-migration.test.tsx +1 -1
  152. package/templates/apps/web/app/[locale]/events/__tests__/page-renderer-migration.test.tsx +2 -2
  153. package/templates/apps/web/app/[locale]/flows/[slug]/FlowStepperClient.tsx +106 -1
  154. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.invite.test.tsx +257 -0
  155. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/account-invite.actions.test.ts +69 -0
  156. package/templates/apps/web/app/[locale]/flows/[slug]/account-invite.actions.ts +35 -0
  157. package/templates/apps/web/app/[locale]/for/__tests__/page-renderer-migration.test.tsx +1 -1
  158. package/templates/apps/web/app/[locale]/how-to/__tests__/page-renderer-migration.test.tsx +1 -1
  159. package/templates/apps/web/app/[locale]/integrations/__tests__/page-renderer-migration.test.tsx +2 -2
  160. package/templates/apps/web/app/[locale]/layout.tsx +23 -2
  161. package/templates/apps/web/app/[locale]/page.tsx +13 -1
  162. package/templates/apps/web/app/[locale]/partners/__tests__/page-renderer-migration.test.tsx +2 -2
  163. package/templates/apps/web/app/[locale]/products/__tests__/page-renderer-migration.test.tsx +2 -2
  164. package/templates/apps/web/app/[locale]/resources/__tests__/page-renderer-migration.test.tsx +2 -2
  165. package/templates/apps/web/app/[locale]/services/__tests__/page-renderer-migration.test.tsx +2 -2
  166. package/templates/apps/web/app/[locale]/software/__tests__/page-renderer-migration.test.tsx +1 -1
  167. package/templates/apps/web/app/[locale]/tech-articles/__tests__/page-renderer-migration.test.tsx +1 -1
  168. package/templates/apps/web/app/[locale]/testimonials/__tests__/page-renderer-migration.test.tsx +1 -1
  169. package/templates/apps/web/app/[locale]/thanks/[slug]/AccountInviteLink.tsx +89 -0
  170. package/templates/apps/web/app/[locale]/thanks/[slug]/__tests__/AccountInviteLink.test.tsx +104 -0
  171. package/templates/apps/web/app/[locale]/thanks/[slug]/__tests__/page.test.tsx +38 -0
  172. package/templates/apps/web/app/[locale]/thanks/[slug]/page.tsx +9 -0
  173. package/templates/apps/web/app/[locale]/whitepapers/__tests__/page-renderer-migration.test.tsx +1 -1
  174. package/templates/apps/web/app/[locale]/working-agreement/__tests__/page.test.tsx +63 -0
  175. package/templates/apps/web/app/[locale]/working-agreement/page.tsx +41 -0
  176. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +114 -0
  177. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +20 -3
  178. package/templates/apps/web/app/api/checkout/[offering]/route.ts +48 -0
  179. package/templates/apps/web/app/api/checkout/__tests__/route.test.ts +120 -0
  180. package/templates/apps/web/app/api/checkout/__tests__/success-path.test.ts +86 -0
  181. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +44 -1
  182. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +22 -3
  183. package/templates/apps/web/app/api/webhooks/stripe/__tests__/route.test.ts +92 -0
  184. package/templates/apps/web/app/api/webhooks/stripe/route.ts +31 -0
  185. package/templates/apps/web/auth.ts +28 -2
  186. package/templates/apps/web/jest.config.cjs +1 -0
  187. package/templates/apps/web/lib/__tests__/account-invite.test.ts +63 -0
  188. package/templates/apps/web/lib/__tests__/checkout.test.ts +243 -0
  189. package/templates/apps/web/lib/__tests__/consent-policies.test.ts +23 -0
  190. package/templates/apps/web/lib/__tests__/deck-page.test.ts +249 -0
  191. package/templates/apps/web/lib/__tests__/structured-data.test.tsx +38 -19
  192. package/templates/apps/web/lib/account-invite.ts +37 -0
  193. package/templates/apps/web/lib/checkout-config.ts +27 -0
  194. package/templates/apps/web/lib/checkout.ts +93 -0
  195. package/templates/apps/web/lib/consent-policies.ts +22 -0
  196. package/templates/apps/web/lib/deck-page.ts +192 -0
  197. package/templates/apps/web/lib/hub-session/__tests__/sign-in-gate.test.tsx +111 -0
  198. package/templates/apps/web/lib/hub-session/sign-in-gate.tsx +88 -32
  199. package/templates/apps/web/lib/prisma-for-auth.ts +8 -0
  200. package/templates/apps/web/lib/sign-up-agreements.ts +447 -0
  201. package/templates/apps/web/lib/site-chrome.ts +2 -0
  202. package/templates/apps/web/lib/telemetry-scrub.ts +5 -1
  203. package/templates/apps/web/messages/en.json +40 -12
  204. package/templates/apps/web/package.json +1 -0
  205. package/templates/apps/web/src/lib/__tests__/lead-write.test.ts +187 -0
  206. package/templates/apps/web/src/lib/__tests__/rate-limit.test.ts +67 -0
  207. package/templates/apps/web/src/lib/lead-write.ts +90 -0
  208. package/templates/apps/web/src/lib/rate-limit.ts +79 -0
  209. package/templates/database/CHANGELOG.md +47 -0
  210. package/templates/database/__tests__/consent-source-checkout-migration.test.ts +79 -0
  211. package/templates/database/__tests__/flow-completion-migration.test.ts +115 -0
  212. package/templates/database/__tests__/flow-completion.db.test.ts +136 -0
  213. package/templates/database/__tests__/seed.test.ts +72 -2
  214. package/templates/database/inbox/schema.prisma +17 -2
  215. package/templates/database/jest.config.cjs +1 -0
  216. package/templates/database/migrations/20261018120000_flow_completion/migration.sql +52 -0
  217. package/templates/database/migrations/20261019120000_consent_source_checkout/migration.sql +27 -0
  218. package/templates/database/package.json +1 -1
  219. package/templates/database/seed.ts +60 -0
  220. package/templates/tools/jest/pin-timezone.cjs +34 -0
  221. package/versions.json +34 -34
  222. package/templates/apps/web/app/[locale]/(auth)/sign-up/sign-up.actions.ts +0 -125
@@ -206,6 +206,42 @@ describe("GET /api/content/:type/:slug", () => {
206
206
  * established for #5831. `get-page.ts` itself is unedited (N3) — it
207
207
  * already accepted both types via `SCHEMA_ORG_TYPES` before this issue.
208
208
  */
209
+ // #8746 D2, AC-1 — the site origin (`_site.mdx` `baseUrl`) reaches the
210
+ // JobPosting builder, so the posting names where to apply.
211
+ describe("a JobPosting carries its ApplyAction when the site is known (#8746 AC-1)", () => {
212
+ const writePosting = () =>
213
+ fixture.writeFixturePage(
214
+ "JobPosting",
215
+ "content-strategist",
216
+ {
217
+ type: "JobPosting",
218
+ slug: "content-strategist",
219
+ title: "Content Strategist",
220
+ description: "Own the content pipeline.",
221
+ },
222
+ "# Content Strategist",
223
+ );
224
+
225
+ it("targets <baseUrl>/<locale>/careers/<slug>#apply", async () => {
226
+ writeSiteMdx(fixture.getContentRoot());
227
+ await writePosting();
228
+ const res = await app.inject({ method: "GET", url: "/v1/content/JobPosting/content-strategist" });
229
+ expect(res.statusCode).toBe(200);
230
+ const entity = JSON.parse(res.body).mainEntity as Record<string, unknown>;
231
+ expect(entity.potentialAction).toEqual({
232
+ "@type": "ApplyAction",
233
+ target: "https://example.com/en/careers/content-strategist#apply",
234
+ });
235
+ });
236
+
237
+ it("emits no ApplyAction when the deployment has no _site.mdx", async () => {
238
+ await writePosting();
239
+ const res = await app.inject({ method: "GET", url: "/v1/content/JobPosting/content-strategist" });
240
+ expect(res.statusCode).toBe(200);
241
+ expect("potentialAction" in (JSON.parse(res.body).mainEntity as Record<string, unknown>)).toBe(false);
242
+ });
243
+ });
244
+
209
245
  describe("parity with the adapter the MCP tool calls (D3)", () => {
210
246
  it.each(["BlogPosting", "DocsDetail"] as const)(
211
247
  "GET /v1/content/%s/:slug?include=body deep-equals adapter.getPageSource",
@@ -230,11 +230,15 @@ export const getPageRoute: FastifyPluginAsync = async (fastify) => {
230
230
  });
231
231
  }
232
232
 
233
+ // #8746 — the site's origin, from `_site.mdx`'s `baseUrl`, for a
234
+ // builder that needs an absolute URL (JobPosting's ApplyAction).
235
+ const origin = readSiteConfig(getContentRoot())?.baseUrl.replace(/\/+$/, "");
233
236
  const input: ContentPageInput = {
234
237
  type: page.type,
235
238
  slug: page.slug,
236
239
  title: page.title,
237
240
  description: page.description,
241
+ ...(origin !== undefined && { origin }),
238
242
  ...(page.publishedAt !== undefined && {
239
243
  publishedAt: page.publishedAt,
240
244
  }),
@@ -0,0 +1,515 @@
1
+ /**
2
+ * @file magnet-completion.test.ts
3
+ *
4
+ * #8757 AC-5 (the API half) and AC-7 (spec
5
+ * docs/specs/8757-a-per-magnet-completion-setting-spec.md D6, NFR3–NFR6):
6
+ * `POST /v1/leads/submit` answers a written `flow:<slug>` lead's completion.
7
+ * On `invite` the 201 gains `next` and the submitter gets one confirmation
8
+ * email whose link starts sign-in with their address prefilled, capped per
9
+ * recipient and per magnet; on `lead` neither; on `checkout` a `next` naming
10
+ * the offering, re-checked at submit time. A `source: "mcp"` submit — the
11
+ * `capture_lead` tool's own argument — answers exactly as before.
12
+ *
13
+ * The world: the route over the in-memory Prisma double, holding one
14
+ * workspace (`WS`, the site alias) and its live `contact` magnet (setting per
15
+ * case). `routeLead` is the route's seam to persistence and is replaced by a
16
+ * double that writes one `Lead` row per first write into the same in-memory
17
+ * table — so the caps count real rows — and answers a replay for a repeated
18
+ * `Idempotency-Key`, as `services/lead-routing.ts` does. `FRONTEND_URL` is
19
+ * `https://site.example` with the `workspace` module on;
20
+ * `@working-theory/email`'s `sendDeliverableEmail` is mocked. The spoke case
21
+ * resolves spoke `S1`, whose sign-in client's callback is
22
+ * `https://spoke.example/api/hub-session/callback`.
23
+ *
24
+ * #8757 AC-11 (D14): a checkout fulfilment's submit carries the caller's
25
+ * account origin into `routeLead` as `accountOrigin` — the spoke's for `S1`,
26
+ * `FRONTEND_URL`'s for a keyless caller, none for a spoke with no client.
27
+ */
28
+ import Fastify from "fastify";
29
+ import type { FastifyInstance } from "fastify";
30
+
31
+ // eslint-disable-next-line no-restricted-syntax -- jest mock factory must be hoisted
32
+ jest.mock("../../../lib/prisma.js", () =>
33
+ jest
34
+ .requireActual<typeof import("../../../__tests__/factories/in-memory-prisma")>(
35
+ "../../../__tests__/factories/in-memory-prisma",
36
+ )
37
+ .createInMemoryPrisma(),
38
+ );
39
+
40
+ const mockSendDeliverableEmail = jest.fn();
41
+ jest.mock("@working-theory/email", () => ({
42
+ sendDeliverableEmail: (...args: unknown[]) => mockSendDeliverableEmail(...args),
43
+ }));
44
+ jest.mock("@working-theory/analytics/server", () => ({ track: jest.fn() }));
45
+
46
+ const mockRouteLead = jest.fn();
47
+ // eslint-disable-next-line no-restricted-syntax -- jest mock factory must be hoisted
48
+ jest.mock("../../../services/lead-routing.js", () => ({
49
+ routeLead: (...args: unknown[]) => mockRouteLead(...args),
50
+ }));
51
+
52
+ const mockResolveCallerSite = jest.fn();
53
+ // eslint-disable-next-line no-restricted-syntax -- jest mock factory must be hoisted
54
+ jest.mock("../../../services/public-site-resolver.js", () => ({
55
+ ...jest.requireActual("../../../services/public-site-resolver.js"),
56
+ resolveCallerSite: (...args: unknown[]) => mockResolveCallerSite(...args),
57
+ }));
58
+
59
+ const mockFindClientByClientId = jest.fn();
60
+ // eslint-disable-next-line no-restricted-syntax -- jest mock factory must be hoisted
61
+ jest.mock("../../../lib/hub-sign-in-store.js", () => ({
62
+ findClientByClientId: (...args: unknown[]) => mockFindClientByClientId(...args),
63
+ }));
64
+
65
+ const mockResolveCommerceClaim = jest.fn();
66
+ // eslint-disable-next-line no-restricted-syntax -- jest mock factory must be hoisted
67
+ jest.mock("../../../lib/require-commerce-claim.js", () => ({
68
+ ...jest.requireActual("../../../lib/require-commerce-claim.js"),
69
+ resolveCommerceClaim: () => mockResolveCommerceClaim(),
70
+ }));
71
+
72
+ const mockListPlanOfferings = jest.fn();
73
+ // eslint-disable-next-line no-restricted-syntax -- jest mock factory must be hoisted
74
+ jest.mock("../../../services/plan-offerings.js", () => ({
75
+ listPlanOfferings: (...args: unknown[]) => mockListPlanOfferings(...args),
76
+ }));
77
+
78
+ import { logger } from "@working-theory/observability";
79
+ import {
80
+ INVITE_EMAILS_PER_SITE_PER_HOUR,
81
+ contactFormFlowConfig,
82
+ } from "@working-theory/validation";
83
+
84
+ import { prisma } from "../../../lib/prisma.js";
85
+ import { __resetSiteWorkspaceCacheForTests } from "../../../lib/site.js";
86
+ import { leadSubmitRoute } from "../index.js";
87
+
88
+ type Row = Record<string, unknown>;
89
+ // eslint-disable-next-line no-restricted-syntax -- the in-memory double exposes its store on keys the real client type does not declare
90
+ const fake = prisma as unknown as {
91
+ __db: Record<string, Row[]>;
92
+ __calls: Array<{ model: string; op: string }>;
93
+ };
94
+
95
+ const WS = "wksp_00000000-0000-7000-8000-0000000000c1";
96
+ const S1 = "spoke_00000000-0000-7000-8000-0000000000d1";
97
+ const MAGNET = "flow_00000000-0000-7000-8000-000000000001";
98
+ const SITE_LINK = "https://site.example/sign-in?next=%2Faccount&email=a%40b.example";
99
+ const SPOKE_LINK =
100
+ "https://spoke.example/api/hub-session/sign-in?next=%2Faccount&email=a%40b.example";
101
+
102
+ let leadSeq = 0;
103
+ const keysSeen = new Map<string, string>();
104
+
105
+ /** `routeLead`'s double: one Lead row per first write, a replay per repeated key. */
106
+ function routeLeadDouble(
107
+ input: { siteId: string; source: string; email: string },
108
+ _meta: unknown,
109
+ options: { idempotencyKey?: string },
110
+ ) {
111
+ const key = options.idempotencyKey;
112
+ if (key !== undefined && keysSeen.has(key)) {
113
+ return Promise.resolve({
114
+ ok: true,
115
+ id: keysSeen.get(key),
116
+ persisted: "db",
117
+ email: { skipped: true },
118
+ replayed: true,
119
+ });
120
+ }
121
+ const id = `lead_00000000-0000-7000-8000-${String(++leadSeq).padStart(12, "0")}`;
122
+ fake.__db.lead!.push({
123
+ id,
124
+ siteId: input.siteId,
125
+ workspaceId: input.siteId,
126
+ source: input.source,
127
+ email: input.email,
128
+ createdAt: new Date(),
129
+ });
130
+ if (key !== undefined) keysSeen.set(key, id);
131
+ return Promise.resolve({ ok: true, id, persisted: "db", email: { skipped: true } });
132
+ }
133
+
134
+ function setMagnet(completion: string, checkoutOffering: string | null = null, extra: Row = {}) {
135
+ fake.__db.flowDefinition = [
136
+ {
137
+ id: MAGNET,
138
+ siteId: WS,
139
+ workspaceId: WS,
140
+ slug: "contact",
141
+ config: contactFormFlowConfig,
142
+ kind: "contact",
143
+ title: "Contact form",
144
+ landingPage: "/contact",
145
+ status: "live",
146
+ listingId: null,
147
+ customersEnabled: false,
148
+ completion,
149
+ checkoutOffering,
150
+ ...extra,
151
+ },
152
+ ];
153
+ }
154
+
155
+ let app: FastifyInstance;
156
+ const originalEnv = process.env;
157
+
158
+ function submit(email = "a@b.example", source = "flow:contact", headers: Record<string, string> = {}) {
159
+ return app.inject({
160
+ method: "POST",
161
+ url: "/v1/leads/submit",
162
+ headers,
163
+ payload: {
164
+ kind: "submit",
165
+ siteId: "default",
166
+ source,
167
+ email,
168
+ consent: true,
169
+ payload: { name: "Ada", message: "Hello there, a question." },
170
+ },
171
+ });
172
+ }
173
+
174
+ const sends = () => mockSendDeliverableEmail.mock.calls.map((call) => call[0] as Row);
175
+ /** The invite email is fired with `void`; let it settle before asserting on it. */
176
+ const settle = () => new Promise((resolve) => setImmediate(resolve));
177
+ const inviteOutcomes = (spy: jest.SpyInstance) =>
178
+ spy.mock.calls
179
+ .map((call) => call[0] as Row)
180
+ .filter((fields) => fields?.event === "magnet-invite")
181
+ .map((fields) => fields.outcome);
182
+
183
+ beforeEach(async () => {
184
+ jest.clearAllMocks();
185
+ process.env = {
186
+ ...originalEnv,
187
+ DATABASE_URL: "postgres://stub",
188
+ AILK_SITE_ID: WS,
189
+ FRONTEND_URL: "https://site.example",
190
+ AILK_ENABLED_MODULES: "workspace",
191
+ AILK_DELIVERABLE_EMAIL_FROM: "hello@site.example",
192
+ };
193
+ for (const key of Object.keys(fake.__db)) delete fake.__db[key];
194
+ fake.__db.workspace = [{ id: WS, organizationId: "org_x", name: "W", slug: "w" }];
195
+ fake.__db.lead = [];
196
+ setMagnet("invite");
197
+ leadSeq = 0;
198
+ keysSeen.clear();
199
+ __resetSiteWorkspaceCacheForTests();
200
+ mockRouteLead.mockImplementation(routeLeadDouble);
201
+ mockResolveCallerSite.mockResolvedValue({ kind: "anonymous" });
202
+ mockSendDeliverableEmail.mockResolvedValue({ ok: true, messageId: "m1" });
203
+ mockResolveCommerceClaim.mockResolvedValue("claimed");
204
+ mockListPlanOfferings.mockResolvedValue([{ key: "retainer", name: "Retainer", type: "service" }]);
205
+ mockFindClientByClientId.mockResolvedValue({
206
+ id: "oauthc_1",
207
+ clientId: S1,
208
+ clientSecret: "x",
209
+ redirectUris: ["https://spoke.example/api/hub-session/callback"],
210
+ enabled: true,
211
+ });
212
+ app = Fastify();
213
+ await app.register(leadSubmitRoute);
214
+ await app.ready();
215
+ });
216
+
217
+ afterEach(async () => {
218
+ await app.close();
219
+ process.env = originalEnv;
220
+ });
221
+
222
+ describe("#8757 AC-5 — invite carries the link on the 201 and in one email", () => {
223
+ it("a flow:contact submit answers next: invite and sends one email with the prefilled sign-in link", async () => {
224
+ const res = await submit();
225
+ expect(res.statusCode).toBe(201);
226
+ expect(res.json().next).toEqual({ completion: "invite" });
227
+ await settle();
228
+ expect(sends()).toHaveLength(1);
229
+ expect(sends()[0]).toMatchObject({
230
+ to: "a@b.example",
231
+ fromAddress: "hello@site.example",
232
+ subject: "We received your Contact form",
233
+ cta: "Track this in your account",
234
+ downloadLink: SITE_LINK,
235
+ });
236
+ });
237
+
238
+ it("on lead: no next and no email", async () => {
239
+ setMagnet("lead");
240
+ const res = await submit();
241
+ expect(res.statusCode).toBe(201);
242
+ expect(res.json()).not.toHaveProperty("next");
243
+ await settle();
244
+ expect(sends()).toHaveLength(0);
245
+ });
246
+
247
+ it("the same Idempotency-Key replayed answers next and sends no second email", async () => {
248
+ const headers = { "idempotency-key": "test-replay-key-not-a-secret" };
249
+ await submit("a@b.example", "flow:contact", headers);
250
+ const replay = await submit("a@b.example", "flow:contact", headers);
251
+ expect(replay.statusCode).toBe(201);
252
+ expect(replay.json().next).toEqual({ completion: "invite" });
253
+ await settle();
254
+ expect(sends()).toHaveLength(1);
255
+ });
256
+
257
+ it("a second unkeyed submit within a day is capped per recipient; another address is still sent", async () => {
258
+ const info = jest.spyOn(logger, "info");
259
+ await submit();
260
+ await settle();
261
+ const second = await submit();
262
+ expect(second.json().next).toEqual({ completion: "invite" });
263
+ await settle();
264
+ expect(sends()).toHaveLength(1);
265
+ expect(inviteOutcomes(info)).toContain("capped_recipient");
266
+
267
+ await submit("c@d.example");
268
+ await settle();
269
+ expect(sends()).toHaveLength(2);
270
+ expect(sends()[1]!.to).toBe("c@d.example");
271
+ info.mockRestore();
272
+ });
273
+
274
+ it("with the per-site hourly cap already reached, a new address gets next and no email", async () => {
275
+ const info = jest.spyOn(logger, "info");
276
+ for (let n = 0; n < INVITE_EMAILS_PER_SITE_PER_HOUR; n += 1) {
277
+ fake.__db.lead!.push({
278
+ id: `lead_prior_${n}`,
279
+ siteId: WS,
280
+ workspaceId: WS,
281
+ source: "flow:contact",
282
+ email: `prior-${n}@example.com`,
283
+ createdAt: new Date(Date.now() - 10 * 60 * 1000),
284
+ });
285
+ }
286
+ const res = await submit("new@example.com");
287
+ expect(res.json().next).toEqual({ completion: "invite" });
288
+ await settle();
289
+ expect(sends()).toHaveLength(0);
290
+ expect(inviteOutcomes(info)).toContain("capped_site");
291
+ info.mockRestore();
292
+ });
293
+
294
+ it("with no sender address: next and no email", async () => {
295
+ delete process.env.AILK_DELIVERABLE_EMAIL_FROM;
296
+ delete process.env.AILK_LEAD_NOTIFICATION_FROM;
297
+ const res = await submit();
298
+ expect(res.json().next).toEqual({ completion: "invite" });
299
+ await settle();
300
+ expect(sends()).toHaveLength(0);
301
+ });
302
+
303
+ it("the email send rejecting still answers 201 with next", async () => {
304
+ mockSendDeliverableEmail.mockRejectedValue(new Error("resend down"));
305
+ const res = await submit();
306
+ expect(res.statusCode).toBe(201);
307
+ expect(res.json().next).toEqual({ completion: "invite" });
308
+ await settle();
309
+ });
310
+
311
+ it("a flow:job-application submit answers next: invite and sends the Job application email (#8771 AC-6)", async () => {
312
+ setMagnet("invite", null, {
313
+ slug: "job-application",
314
+ kind: "diagnostic",
315
+ title: "Job application",
316
+ landingPage: "/careers",
317
+ });
318
+ const res = await submit("ada@example.com", "flow:job-application");
319
+ expect(res.statusCode).toBe(201);
320
+ expect(res.json().next).toEqual({ completion: "invite" });
321
+ await settle();
322
+ expect(sends()).toHaveLength(1);
323
+ expect(sends()[0]).toMatchObject({
324
+ to: "ada@example.com",
325
+ subject: "We received your Job application",
326
+ cta: "Track this in your account",
327
+ downloadLink: expect.stringContaining("https://site.example/sign-in"),
328
+ });
329
+ expect((sends()[0] as { downloadLink: string }).downloadLink).toContain("ada%40example.com");
330
+ });
331
+
332
+ it("a magnet declaring completionEmail sends its own subject and body with the same link", async () => {
333
+ setMagnet("invite", null, {
334
+ config: {
335
+ ...contactFormFlowConfig,
336
+ completionEmail: {
337
+ subject: { en: "Thanks from Acme" },
338
+ body: { en: "We will reply within a day." },
339
+ },
340
+ },
341
+ });
342
+ await submit();
343
+ await settle();
344
+ expect(sends()[0]).toMatchObject({
345
+ subject: "Thanks from Acme",
346
+ body: "We will reply within a day.",
347
+ cta: "Track this in your account",
348
+ downloadLink: SITE_LINK,
349
+ });
350
+ });
351
+ });
352
+
353
+ describe("#8757 AC-5 — no next and no email where the invite does not apply", () => {
354
+ it.each([
355
+ ["a draft magnet", () => setMagnet("invite", null, { status: "draft" }), "flow:contact"],
356
+ ["a contact-form source", () => undefined, "contact-form"],
357
+ ["a build with neither workspace nor multi-tenant", () => {
358
+ process.env.AILK_ENABLED_MODULES = "signal-collectors";
359
+ }, "flow:contact"],
360
+ ])("%s", async (_label, arrange, source) => {
361
+ arrange();
362
+ const res = await submit("a@b.example", source);
363
+ expect(res.statusCode).toBe(201);
364
+ expect(res.json()).not.toHaveProperty("next");
365
+ await settle();
366
+ expect(sends()).toHaveLength(0);
367
+ });
368
+ });
369
+
370
+ describe("#8757 AC-5 — a spoke's link points at the spoke", () => {
371
+ beforeEach(() => {
372
+ mockResolveCallerSite.mockResolvedValue({ kind: "spoke", spokeId: S1, workspaceId: WS });
373
+ });
374
+
375
+ it("links the spoke's own hub sign-in start", async () => {
376
+ const res = await submit();
377
+ expect(res.json().next).toEqual({ completion: "invite" });
378
+ await settle();
379
+ expect(sends()[0]!.downloadLink).toBe(SPOKE_LINK);
380
+ expect(mockFindClientByClientId).toHaveBeenCalledWith(S1);
381
+ });
382
+
383
+ it.each([
384
+ ["no client", () => mockFindClientByClientId.mockResolvedValue(null)],
385
+ ["a disabled client", () =>
386
+ mockFindClientByClientId.mockResolvedValue({
387
+ id: "oauthc_1",
388
+ clientId: S1,
389
+ clientSecret: "x",
390
+ redirectUris: ["https://spoke.example/api/hub-session/callback"],
391
+ enabled: false,
392
+ })],
393
+ ["an http loopback callback in production", () => {
394
+ process.env.NODE_ENV = "production";
395
+ mockFindClientByClientId.mockResolvedValue({
396
+ id: "oauthc_1",
397
+ clientId: S1,
398
+ clientSecret: "x",
399
+ redirectUris: ["http://localhost:3000/api/hub-session/callback"],
400
+ enabled: true,
401
+ });
402
+ }],
403
+ ])("%s: no next and no email", async (_label, arrange) => {
404
+ arrange();
405
+ const res = await submit();
406
+ expect(res.statusCode).toBe(201);
407
+ expect(res.json()).not.toHaveProperty("next");
408
+ await settle();
409
+ expect(sends()).toHaveLength(0);
410
+ });
411
+ });
412
+
413
+ describe("#8757 AC-5 — checkout names the offering only while it is claimed and listed", () => {
414
+ beforeEach(() => setMagnet("checkout", "retainer"));
415
+
416
+ it("retainer listed and the claim claimed → next: checkout, retainer; no email", async () => {
417
+ const res = await submit();
418
+ expect(res.json().next).toEqual({ completion: "checkout", checkoutOffering: "retainer" });
419
+ await settle();
420
+ expect(sends()).toHaveLength(0);
421
+ });
422
+
423
+ it.each([
424
+ ["the offering since unpublished", () => mockListPlanOfferings.mockResolvedValue([])],
425
+ ["the lister failing", () => mockListPlanOfferings.mockResolvedValue({ failed: "Error" })],
426
+ ["an unclaimed licence", () => mockResolveCommerceClaim.mockResolvedValue("unclaimed")],
427
+ ["an undetermined licence", () => mockResolveCommerceClaim.mockResolvedValue("undetermined")],
428
+ ])("%s: no next, still 201", async (_label, arrange) => {
429
+ arrange();
430
+ const res = await submit();
431
+ expect(res.statusCode).toBe(201);
432
+ expect(res.json()).not.toHaveProperty("next");
433
+ });
434
+ });
435
+
436
+ describe("#8757 AC-7 — capture_lead's own arguments get today's answer", () => {
437
+ it("a source: mcp submit answers exactly id, persisted and email, with no store read", async () => {
438
+ fake.__calls.length = 0;
439
+ const res = await submit("a@b.example", "mcp");
440
+ expect(res.statusCode).toBe(201);
441
+ expect(Object.keys(res.json()).sort()).toEqual(["email", "id", "persisted"]);
442
+ expect(fake.__calls.filter((call) => call.model === "flowDefinition")).toEqual([]);
443
+ await settle();
444
+ expect(sends()).toHaveLength(0);
445
+ });
446
+ });
447
+
448
+ describe("#8757 AC-11 — a checkout submit carries the caller's account origin into routeLead", () => {
449
+ const CHECKOUT_KEY = "cs_live_ac11RouteKey"; // gitleaks:allow -- a synthetic Checkout Session id shape (#8757 AC-11), not a credential
450
+
451
+ function checkoutSubmit() {
452
+ return app.inject({
453
+ method: "POST",
454
+ url: "/v1/leads/submit",
455
+ headers: { "idempotency-key": CHECKOUT_KEY },
456
+ payload: {
457
+ kind: "submit",
458
+ siteId: "default",
459
+ source: "web",
460
+ email: "cleo@x.io",
461
+ payload: { site: "wendi", page: "checkout", offering: "wendi_retainer" },
462
+ },
463
+ });
464
+ }
465
+
466
+ const routeLeadOptions = () => {
467
+ expect(mockRouteLead).toHaveBeenCalledTimes(1);
468
+ return mockRouteLead.mock.calls[0]![2] as Record<string, unknown>;
469
+ };
470
+
471
+ it("a spoke S1 submit calls routeLead with the spoke's origin", async () => {
472
+ mockResolveCallerSite.mockResolvedValue({ kind: "spoke", spokeId: S1, workspaceId: WS });
473
+ const res = await checkoutSubmit();
474
+ expect(res.statusCode).toBe(201);
475
+ expect(routeLeadOptions()).toEqual({
476
+ idempotencyKey: CHECKOUT_KEY,
477
+ accountOrigin: "https://spoke.example",
478
+ });
479
+ expect(mockFindClientByClientId).toHaveBeenCalledWith(S1);
480
+ });
481
+
482
+ it("a keyless submit under workspace calls routeLead with the site's origin", async () => {
483
+ const res = await checkoutSubmit();
484
+ expect(res.statusCode).toBe(201);
485
+ expect(routeLeadOptions()).toEqual({
486
+ idempotencyKey: CHECKOUT_KEY,
487
+ accountOrigin: "https://site.example",
488
+ });
489
+ });
490
+
491
+ it.each([
492
+ ["has no client", () => mockFindClientByClientId.mockResolvedValue(null)],
493
+ ["fails its client read", () => mockFindClientByClientId.mockRejectedValue(new Error("down"))],
494
+ ])("a spoke that %s calls routeLead with no accountOrigin, and still answers 201", async (_label, arrange) => {
495
+ mockResolveCallerSite.mockResolvedValue({ kind: "spoke", spokeId: S1, workspaceId: WS });
496
+ arrange();
497
+ const res = await checkoutSubmit();
498
+ expect(res.statusCode).toBe(201);
499
+ expect(routeLeadOptions()).toEqual({ idempotencyKey: CHECKOUT_KEY });
500
+ });
501
+
502
+ it("a submit that is not a checkout makes no origin read and passes no accountOrigin", async () => {
503
+ mockResolveCallerSite.mockResolvedValue({ kind: "spoke", spokeId: S1, workspaceId: WS });
504
+ const res = await submit("a@b.example", "contact-form");
505
+ expect(res.statusCode).toBe(201);
506
+ expect(routeLeadOptions()).toEqual({});
507
+ expect(mockFindClientByClientId).not.toHaveBeenCalled();
508
+ });
509
+
510
+ it("the 201 body is unchanged", async () => {
511
+ mockResolveCallerSite.mockResolvedValue({ kind: "spoke", spokeId: S1, workspaceId: WS });
512
+ const res = await checkoutSubmit();
513
+ expect(Object.keys(res.json()).sort()).toEqual(["email", "id", "persisted"]);
514
+ });
515
+ });