create-ailk 0.37.1 → 0.38.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 (230) hide show
  1. package/README.md +129 -0
  2. package/component-catalog.json +44 -6
  3. package/component-catalog.md +6 -5
  4. package/dist/add-module.js +16 -1
  5. package/dist/add-route.d.ts +2 -2
  6. package/dist/add-route.js +18 -11
  7. package/dist/cli.js +52 -0
  8. package/dist/declined-routes.d.ts +13 -0
  9. package/dist/declined-routes.js +74 -0
  10. package/dist/derive-architecture.d.ts +0 -6
  11. package/dist/derive-architecture.js +9 -15
  12. package/dist/index.d.ts +1 -0
  13. package/dist/index.js +3 -0
  14. package/dist/language-import.d.ts +93 -0
  15. package/dist/language-import.js +270 -43
  16. package/dist/lib/import-mdx.js +1 -1
  17. package/dist/lib/scaffold-render-sweep.d.ts +6 -3
  18. package/dist/lib/scaffold-render-sweep.js +8 -4
  19. package/dist/migrate-content.d.ts +6 -2
  20. package/dist/migrate-content.js +62 -5
  21. package/dist/module-architecture.js +139 -103
  22. package/dist/paid-sections.d.ts +13 -0
  23. package/dist/paid-sections.js +35 -5
  24. package/dist/programmatic.js +6 -16
  25. package/dist/remove-module.js +67 -0
  26. package/dist/routes.d.ts +103 -0
  27. package/dist/routes.js +708 -0
  28. package/dist/site-manifest.js +1 -1
  29. package/dist/site-roster.d.ts +2 -1
  30. package/dist/site-roster.js +30 -8
  31. package/dist/spoke-checkout.d.ts +28 -27
  32. package/dist/spoke-checkout.js +71 -102
  33. package/dist/surfaces.d.ts +18 -0
  34. package/dist/surfaces.js +47 -282
  35. package/dist/sync-routes.d.ts +14 -1
  36. package/dist/sync-routes.js +86 -5
  37. package/dist/topology.d.ts +15 -1
  38. package/dist/topology.js +20 -4
  39. package/dist/update.d.ts +17 -2
  40. package/dist/update.js +480 -77
  41. package/package.json +3 -3
  42. package/templates/README.md +1 -1
  43. package/templates/apps/mcp/CLAUDE.md +5 -3
  44. package/templates/apps/web/CLAUDE.md +62 -20
  45. package/templates/apps/web/account.config.tsx +101 -0
  46. package/templates/apps/web/app/[locale]/(authed)/account/appointments/[slug]/page.tsx +3 -161
  47. package/templates/apps/web/app/[locale]/(authed)/account/appointments/page.tsx +3 -139
  48. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/page.tsx +3 -406
  49. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/versions/[version]/file/route.ts +2 -190
  50. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/page.tsx +3 -182
  51. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +8 -420
  52. package/templates/apps/web/app/[locale]/(authed)/account/connect/page.tsx +1 -1
  53. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +8 -214
  54. package/templates/apps/web/app/[locale]/(authed)/account/inbox/[kind]/[id]/page.tsx +8 -115
  55. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/route.ts +2 -80
  56. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/page.tsx +8 -121
  57. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/page.tsx +3 -154
  58. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +7 -149
  59. package/templates/apps/web/app/[locale]/(authed)/account/notifications/page.tsx +3 -143
  60. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/page.tsx +3 -126
  61. package/templates/apps/web/app/[locale]/(authed)/account/page.tsx +8 -302
  62. package/templates/apps/web/app/[locale]/(authed)/account/privacy/export/route.ts +2 -102
  63. package/templates/apps/web/app/[locale]/(authed)/account/privacy/page.tsx +3 -240
  64. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +3 -131
  65. package/templates/apps/web/app/[locale]/(authed)/account/settings/page.tsx +2 -24
  66. package/templates/apps/web/app/[locale]/(authed)/account/support/page.tsx +3 -60
  67. package/templates/apps/web/app/[locale]/layout.tsx +45 -28
  68. package/templates/apps/web/app/apple-icon.tsx +72 -0
  69. package/templates/apps/web/app/llms.txt/__tests__/site-listing.test.ts +22 -12
  70. package/templates/apps/web/app/og/__tests__/__snapshots__/card.test.tsx.snap +3 -0
  71. package/templates/apps/web/app/og/__tests__/card.test.tsx +129 -0
  72. package/templates/apps/web/app/og/__tests__/route.test.ts +3 -4
  73. package/templates/apps/web/app/og/route.tsx +155 -72
  74. package/templates/apps/web/app/sitemap.xml/__tests__/site-listing.test.ts +12 -0
  75. package/templates/apps/web/i18n/request.ts +44 -1
  76. package/templates/apps/web/jest.config.cjs +13 -1
  77. package/templates/apps/web/lib/__tests__/auth-phone.test.ts +11 -0
  78. package/templates/apps/web/lib/__tests__/fixtures/site-topology.ts +70 -0
  79. package/templates/apps/web/lib/__tests__/nav-label-keys.test.ts +14 -0
  80. package/templates/apps/web/lib/__tests__/profile-back-link.test.ts +148 -61
  81. package/templates/apps/web/lib/__tests__/served-pages.test.ts +77 -0
  82. package/templates/apps/web/lib/__tests__/server-api.test.ts +37 -5
  83. package/templates/apps/web/lib/__tests__/structured-data.test.tsx +26 -13
  84. package/templates/apps/web/lib/listings.tsx +2 -2
  85. package/templates/apps/web/lib/nav-label-keys.ts +16 -2
  86. package/templates/apps/web/lib/paid-section-contracts.ts +35 -6
  87. package/templates/apps/web/lib/paid-sections.generated.ts +8 -0
  88. package/templates/apps/web/lib/profile-back-link.ts +105 -32
  89. package/templates/apps/web/lib/served-pages.ts +95 -0
  90. package/templates/apps/web/lib/site-brand.tsx +3 -5
  91. package/templates/apps/web/messages/en.json +8 -684
  92. package/templates/apps/web/middleware.ts +3 -1
  93. package/templates/apps/web/next.config.mjs +27 -0
  94. package/templates/apps/web/package.json +1 -0
  95. package/templates/customizations.yaml +9 -0
  96. package/templates/package.json +3 -1
  97. package/templates/tools/lint-architecture.ts +164 -11
  98. package/versions.json +48 -47
  99. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/account-frame-sign-out.test.tsx +0 -175
  100. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/agreements-prompt.test.tsx +0 -301
  101. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +0 -515
  102. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/general.test.tsx +0 -883
  103. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +0 -758
  104. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/item.test.tsx +0 -264
  105. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +0 -167
  106. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout.test.tsx +0 -730
  107. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-menu.test.tsx +0 -355
  108. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-popups.test.tsx +0 -97
  109. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/notifications.test.tsx +0 -375
  110. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/onboarding.test.tsx +0 -323
  111. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +0 -1208
  112. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/popups.test.tsx +0 -418
  113. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/privacy.test.tsx +0 -462
  114. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/rich-translator.ts +0 -63
  115. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/security.test.tsx +0 -406
  116. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/settings.test.tsx +0 -93
  117. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/support.test.tsx +0 -208
  118. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/thread.test.tsx +0 -340
  119. package/templates/apps/web/app/[locale]/(authed)/account/account-data.ts +0 -182
  120. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +0 -353
  121. package/templates/apps/web/app/[locale]/(authed)/account/actions.ts +0 -57
  122. package/templates/apps/web/app/[locale]/(authed)/account/agreements-actions.ts +0 -58
  123. package/templates/apps/web/app/[locale]/(authed)/account/agreements-gate.ts +0 -61
  124. package/templates/apps/web/app/[locale]/(authed)/account/agreements-prompt.tsx +0 -184
  125. package/templates/apps/web/app/[locale]/(authed)/account/appointments/__tests__/page.test.tsx +0 -426
  126. package/templates/apps/web/app/[locale]/(authed)/account/appointments/appointments-data.ts +0 -76
  127. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/pay-form.tsx +0 -65
  128. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/review-form.tsx +0 -172
  129. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/file-route.test.ts +0 -333
  130. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/page.test.tsx +0 -936
  131. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/pay.test.tsx +0 -193
  132. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/review.test.tsx +0 -476
  133. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/artifact-actions.ts +0 -184
  134. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/artifact-data.ts +0 -197
  135. package/templates/apps/web/app/[locale]/(authed)/account/billing/__tests__/offerings.test.ts +0 -99
  136. package/templates/apps/web/app/[locale]/(authed)/account/billing/offerings.ts +0 -123
  137. package/templates/apps/web/app/[locale]/(authed)/account/billing-source.ts +0 -303
  138. package/templates/apps/web/app/[locale]/(authed)/account/components/request-quote.tsx +0 -274
  139. package/templates/apps/web/app/[locale]/(authed)/account/error-row.tsx +0 -35
  140. package/templates/apps/web/app/[locale]/(authed)/account/for-you-labels.ts +0 -36
  141. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/phone-verification.test.tsx +0 -215
  142. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/seam-imports.test.ts +0 -65
  143. package/templates/apps/web/app/[locale]/(authed)/account/general/account-name.ts +0 -36
  144. package/templates/apps/web/app/[locale]/(authed)/account/general/billing-anchor.tsx +0 -27
  145. package/templates/apps/web/app/[locale]/(authed)/account/general/contact-actions.ts +0 -149
  146. package/templates/apps/web/app/[locale]/(authed)/account/general/contact-details.tsx +0 -42
  147. package/templates/apps/web/app/[locale]/(authed)/account/general/deletion-request.tsx +0 -132
  148. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-actions.ts +0 -122
  149. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-verification.tsx +0 -215
  150. package/templates/apps/web/app/[locale]/(authed)/account/general/photo-actions.ts +0 -73
  151. package/templates/apps/web/app/[locale]/(authed)/account/general/profile-form.tsx +0 -107
  152. package/templates/apps/web/app/[locale]/(authed)/account/general/profile-source.ts +0 -87
  153. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/__tests__/route.test.ts +0 -215
  154. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/member-thread-composer.tsx +0 -43
  155. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/thread-data.ts +0 -88
  156. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/thread-write.ts +0 -31
  157. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/invitation-id.test.ts +0 -35
  158. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/page.test.tsx +0 -266
  159. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/actions.ts +0 -116
  160. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/invitation-id.ts +0 -12
  161. package/templates/apps/web/app/[locale]/(authed)/account/new-actions.ts +0 -219
  162. package/templates/apps/web/app/[locale]/(authed)/account/new-menu.tsx +0 -365
  163. package/templates/apps/web/app/[locale]/(authed)/account/new-popups.tsx +0 -86
  164. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/actions.ts +0 -120
  165. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/onboarding-form.tsx +0 -322
  166. package/templates/apps/web/app/[locale]/(authed)/account/privacy/__tests__/export-route.test.ts +0 -173
  167. package/templates/apps/web/app/[locale]/(authed)/account/privacy/actions.ts +0 -103
  168. package/templates/apps/web/app/[locale]/(authed)/account/profile-actions.ts +0 -116
  169. package/templates/apps/web/app/[locale]/(authed)/account/retry-button.tsx +0 -27
  170. package/templates/apps/web/app/[locale]/(authed)/account/security/__tests__/hub-variant.test.tsx +0 -258
  171. package/templates/apps/web/app/[locale]/(authed)/account/security/security-panel.tsx +0 -130
  172. package/templates/apps/web/app/[locale]/(authed)/account/security/security-source.ts +0 -92
  173. package/templates/apps/web/app/[locale]/(authed)/account/settings-frame.tsx +0 -121
  174. package/templates/apps/web/app/[locale]/(authed)/account/sign-in-method.ts +0 -37
  175. package/templates/apps/web/app/[locale]/(authed)/account/support/support-form.tsx +0 -98
  176. package/templates/apps/web/app/[locale]/(authed)/account/support-actions.ts +0 -100
  177. package/templates/apps/web/app/[locale]/checkout/__tests__/pages.test.tsx +0 -139
  178. package/templates/apps/web/app/[locale]/checkout/__tests__/thank-you-account.test.tsx +0 -146
  179. package/templates/apps/web/app/[locale]/checkout/thank-you/page.tsx +0 -114
  180. package/templates/apps/web/app/[locale]/checkout/unavailable/page.tsx +0 -51
  181. package/templates/apps/web/app/[locale]/flows/[slug]/FlowStepperClient.tsx +0 -614
  182. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.count.test.tsx +0 -43
  183. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.deliverable.test.tsx +0 -214
  184. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.ending.test.tsx +0 -197
  185. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.invite.test.tsx +0 -286
  186. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.permalink.test.tsx +0 -520
  187. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.test.tsx +0 -376
  188. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.thanks-by-tier.test.tsx +0 -306
  189. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/account-invite.actions.test.ts +0 -69
  190. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/flow.actions.test.ts +0 -398
  191. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/magnet-page.test.tsx +0 -704
  192. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/save.actions.test.ts +0 -173
  193. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/two-route-tool.test.tsx +0 -141
  194. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/verify.test.tsx +0 -249
  195. package/templates/apps/web/app/[locale]/flows/[slug]/account-invite.actions.ts +0 -35
  196. package/templates/apps/web/app/[locale]/flows/[slug]/email-moment.ts +0 -92
  197. package/templates/apps/web/app/[locale]/flows/[slug]/flow.actions.ts +0 -177
  198. package/templates/apps/web/app/[locale]/flows/[slug]/magnet-page.tsx +0 -472
  199. package/templates/apps/web/app/[locale]/flows/[slug]/page.tsx +0 -48
  200. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/LevelChart.tsx +0 -100
  201. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsCard.tsx +0 -99
  202. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsClient.tsx +0 -820
  203. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsEmailStep.tsx +0 -203
  204. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/ResultsClient.no-commerce.test.tsx +0 -194
  205. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/ResultsClient.report.test.tsx +0 -284
  206. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/by-result.test.tsx +0 -302
  207. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/cards.test.tsx +0 -402
  208. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/landing.test.tsx +0 -293
  209. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/page.test.tsx +0 -485
  210. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/score.test.tsx +0 -231
  211. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/checkout-seam.ts +0 -74
  212. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/meeting-seam.ts +0 -36
  213. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/page.tsx +0 -420
  214. package/templates/apps/web/app/[locale]/flows/[slug]/save.actions.ts +0 -85
  215. package/templates/apps/web/app/[locale]/flows/[slug]/served-flow.ts +0 -91
  216. package/templates/apps/web/app/[locale]/flows/[slug]/start/page.tsx +0 -32
  217. package/templates/apps/web/app/[locale]/flows/[slug]/verify/page.tsx +0 -153
  218. package/templates/apps/web/app/[locale]/flows/[slug]/verify.actions.ts +0 -151
  219. package/templates/apps/web/app/[locale]/meet/confirmed/BookingHandOff.tsx +0 -128
  220. package/templates/apps/web/app/[locale]/meet/confirmed/__tests__/BookingHandOff.test.tsx +0 -126
  221. package/templates/apps/web/app/[locale]/purchase/__tests__/cancel.test.tsx +0 -162
  222. package/templates/apps/web/app/[locale]/purchase/__tests__/module-scope.test.ts +0 -68
  223. package/templates/apps/web/app/[locale]/purchase/__tests__/success.test.tsx +0 -411
  224. package/templates/apps/web/app/[locale]/purchase/cancel/page.tsx +0 -115
  225. package/templates/apps/web/app/[locale]/purchase/success/page.tsx +0 -348
  226. package/templates/apps/web/lib/__tests__/account-config.test.ts +0 -704
  227. package/templates/apps/web/lib/account-config.ts +0 -678
  228. package/templates/apps/web/lib/checkout-config.ts +0 -16
  229. package/templates/apps/web/src/lib/__tests__/commerce-sections.test.ts +0 -57
  230. package/templates/apps/web/src/lib/commerce-sections.ts +0 -55
package/dist/routes.js ADDED
@@ -0,0 +1,708 @@
1
+ /**
2
+ * `create-ailk routes --write | --check` — the one route-file generator
3
+ * (#11219; ADR 0040 rules 2, 3 and 4).
4
+ *
5
+ * A website page ships in a package. Next mounts a route tree only from the
6
+ * consuming app's `app/` directory, so a site's `apps/web/app/[locale]/`
7
+ * holds one GENERATED file per shipped route and nothing of the page's
8
+ * implementation — the Admin shell's shape
9
+ * (`packages-paid/admin/scripts/write-shell-routes.ts`), owned here once for
10
+ * every page package.
11
+ *
12
+ * Input: every installed `@working-theory/*` dependency of `apps/web` whose
13
+ * `package.json` declares `"ailk": { "routes": "<manifest path>" }`. The
14
+ * manifest (`RouteManifest`) names the package's route prefix under
15
+ * `app/[locale]` (or a list of them, #11252 — a package whose routes sit in
16
+ * more than one top-level directory), the site's config file, and one entry
17
+ * per routing file:
18
+ * its path, kind (`page` · `layout` · `route`), the exports to re-export,
19
+ * the segment-config lines to copy literally, and whether it takes the site
20
+ * config (and, with `metadataConfig` (#11253), whether its `generateMetadata`
21
+ * takes it too).
22
+ *
23
+ * Output: one file per entry — a header naming the package and version, one
24
+ * re-export per listed export, the segment-config lines, and, when the entry
25
+ * takes config, an import of the site's `<config>.tsx` passed to the page.
26
+ * Every statement names one specifier on one line, so the files are
27
+ * prettier-stable, and nothing else is written: a generated file is never
28
+ * hand-edited. A manifest that sets `"oss": false` (#11252) puts the
29
+ * `// oss: false` marker on each file's first line, before the header: a
30
+ * package outside the public tree (`packages-paid/`) generates files the
31
+ * public strip must drop with it (`scripts/check-oss-strip.sh`); in a
32
+ * scaffold the line is inert.
33
+ *
34
+ * Check mode exits 1 naming each file that is MISSING (an entry with no
35
+ * file), STALE (content differs from what would be generated — a version
36
+ * bump included, since the header names it) or STRAY (a routing file under
37
+ * the package's prefix that is neither generated nor recorded — the prefix
38
+ * is the subtree the package has taken over, and a manifest shipping no
39
+ * route owns nothing yet). A route the
40
+ * site has replaced or removed is recorded in `customizations.yaml` — an
41
+ * entry whose `paths` match the route file, in the manifest's own grammar
42
+ * (`build-in: site — …`) — and is REPORTED, never failed: a recorded route
43
+ * with a file is `replaced`, one without is `removed`, and `--write` never
44
+ * overwrites or re-creates either.
45
+ *
46
+ * A routing file the package names in its manifest's `siteOwned` list sits
47
+ * under its prefix but is the site's own page (one the package leaves to a
48
+ * later slice): it is REPORTED as kept by the site, never stray, and
49
+ * `--write` never touches it.
50
+ *
51
+ * A page package's strings ship in its own catalog (ADR 0040 rule 5), named
52
+ * by the manifest's `messages.catalog` (one `<locale>.json` per locale); a
53
+ * site's `messages/<locale>.json` holds overrides only. Check mode also
54
+ * lists each ORPHANED override — a site key under a namespace the package's
55
+ * catalog ships that the package no longer has (a site locale with no
56
+ * package catalog of its own is read against the package's `en`, as the
57
+ * site's request config falls back). Keys under the manifest's
58
+ * `messages.siteOwned` prefixes are the site's own strings, read by its own
59
+ * files, and are never overrides.
60
+ *
61
+ * A route the site's topology does not carry — a spoke without sign-in
62
+ * drops the whole `(authed)` group (`isSpokeExcluded`) — is not a route of
63
+ * that site: neither written, nor missing, nor stray; the check names it as
64
+ * not carried.
65
+ *
66
+ * Pure module: no `import.meta.url`, so jest imports it directly.
67
+ */
68
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
69
+ import { dirname, join, posix, relative, resolve, sep } from "node:path";
70
+ import { parseArgs } from "node:util";
71
+ import { isSpokeExcluded, readSpokeShape } from "./topology.js";
72
+ /** The app a page package's routes mount in, relative to the site root. */
73
+ export const ROUTES_APP_DIR = "apps/web";
74
+ /** The locale segment every shipped route sits under. */
75
+ const LOCALE_DIR = "app/[locale]";
76
+ /** The `package.json` key a page package declares its manifest under. */
77
+ const MANIFEST_KEY = "ailk";
78
+ const PACKAGE_SCOPE = "@working-theory/";
79
+ const ROUTING_FILES = new Set(["page.tsx", "layout.tsx", "route.ts"]);
80
+ const SKIPPED_DIRS = new Set(["__tests__", "node_modules"]);
81
+ const HTTP_METHODS = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]);
82
+ const KIND_OF_FILE = { "page.tsx": "page", "layout.tsx": "layout", "route.ts": "route" };
83
+ const SEGMENT_CONFIG_RE = /^export const (?:dynamic|revalidate|runtime|fetchCache|dynamicParams|preferredRegion|maxDuration) = .+;$/;
84
+ export class RoutesRefusedError extends Error {
85
+ exitCode = 2;
86
+ constructor(message) {
87
+ super(message);
88
+ this.name = "RoutesRefusedError";
89
+ }
90
+ }
91
+ function isRecord(value) {
92
+ return typeof value === "object" && value !== null && !Array.isArray(value);
93
+ }
94
+ /** A POSIX path with no `.`/`..` segment, no leading or trailing slash, as written: an installed package names no write target outside its prefix. */
95
+ function isPlainPath(value) {
96
+ return (typeof value === "string" &&
97
+ value !== "" &&
98
+ posix.normalize(value) === value &&
99
+ !value.startsWith("/") &&
100
+ !value.endsWith("/") &&
101
+ value.split("/").every((seg) => seg !== "." && seg !== ".."));
102
+ }
103
+ function stringList(value, where) {
104
+ if (value === undefined)
105
+ return [];
106
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) {
107
+ throw new RoutesRefusedError(`${where} must be a list of strings`);
108
+ }
109
+ return value;
110
+ }
111
+ /** Parse and validate one manifest; every refusal names the package and the entry. */
112
+ export function parseRouteManifest(pkg, version, raw) {
113
+ const at = `${pkg}'s route manifest`;
114
+ if (!isRecord(raw))
115
+ throw new RoutesRefusedError(`${at} is not an object`);
116
+ if (raw.schema !== 1)
117
+ throw new RoutesRefusedError(`${at}: schema must be 1`);
118
+ const prefixes = Array.isArray(raw.prefix) ? raw.prefix : [raw.prefix];
119
+ if (prefixes.length === 0 ||
120
+ !prefixes.every(isPlainPath) ||
121
+ new Set(prefixes).size !== prefixes.length) {
122
+ throw new RoutesRefusedError(`${at}: prefix must be a plain path under app/[locale]/ (no leading or trailing slash, no . or .. segment), or a non-empty list of distinct ones`);
123
+ }
124
+ if (raw.oss !== undefined && raw.oss !== false) {
125
+ throw new RoutesRefusedError(`${at}: oss must be false when set (the generated files carry the oss: false marker)`);
126
+ }
127
+ if (raw.config !== undefined && (typeof raw.config !== "string" || raw.config.includes("/"))) {
128
+ throw new RoutesRefusedError(`${at}: config must be the site file's basename without extension`);
129
+ }
130
+ if (!Array.isArray(raw.routes))
131
+ throw new RoutesRefusedError(`${at}: routes must be a list`);
132
+ const prefix = prefixes;
133
+ const underPrefix = (path) => prefix.some((p) => path.startsWith(`${p}/`));
134
+ const prefixNamed = prefix.length === 1 ? `prefix ${prefix[0]}/` : `prefixes ${prefix.join(", ")}`;
135
+ const siteOwned = stringList(raw.siteOwned, `${at}: siteOwned`);
136
+ for (const path of siteOwned) {
137
+ if (!isPlainPath(path) || !ROUTING_FILES.has(posix.basename(path)) || !underPrefix(path)) {
138
+ throw new RoutesRefusedError(`${at}: siteOwned ${JSON.stringify(path)} must be a routing file under ${prefix.map((p) => `${p}/`).join(" or ")}`);
139
+ }
140
+ }
141
+ let messages;
142
+ if (raw.messages !== undefined) {
143
+ if (!isRecord(raw.messages) || !isPlainPath(raw.messages.catalog)) {
144
+ throw new RoutesRefusedError(`${at}: messages.catalog must be a plain path inside the package`);
145
+ }
146
+ const owned = stringList(raw.messages.siteOwned, `${at}: messages.siteOwned`);
147
+ for (const key of owned) {
148
+ if (!/^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)+$/.test(key)) {
149
+ throw new RoutesRefusedError(`${at}: messages.siteOwned ${JSON.stringify(key)} must be a dotted key under a namespace`);
150
+ }
151
+ }
152
+ messages = { catalog: raw.messages.catalog, siteOwned: owned };
153
+ }
154
+ const seen = new Set();
155
+ const routes = raw.routes.map((entry, i) => {
156
+ const where = `${at} routes[${i}]`;
157
+ if (!isRecord(entry))
158
+ throw new RoutesRefusedError(`${where} is not an object`);
159
+ const path = entry.path;
160
+ if (!isPlainPath(path) || !ROUTING_FILES.has(posix.basename(path))) {
161
+ throw new RoutesRefusedError(`${where}: path must be a plain path ending in page.tsx, layout.tsx or route.ts`);
162
+ }
163
+ if (!underPrefix(path)) {
164
+ throw new RoutesRefusedError(`${where}: ${path} is outside the manifest's ${prefixNamed}`);
165
+ }
166
+ if (seen.has(path) || siteOwned.includes(path)) {
167
+ throw new RoutesRefusedError(`${where}: ${path} is listed twice`);
168
+ }
169
+ seen.add(path);
170
+ const kind = KIND_OF_FILE[posix.basename(path)];
171
+ if (entry.kind !== kind)
172
+ throw new RoutesRefusedError(`${where}: kind must be ${JSON.stringify(kind)} for ${path}`);
173
+ if (!isPlainPath(entry.module)) {
174
+ throw new RoutesRefusedError(`${where}: module must name the package subpath to re-export from, as a plain path`);
175
+ }
176
+ const exports = stringList(entry.exports, `${where}: exports`);
177
+ if (exports.length === 0)
178
+ throw new RoutesRefusedError(`${where}: exports must list at least one export`);
179
+ const config = entry.config === true;
180
+ if (kind === "route") {
181
+ if (config)
182
+ throw new RoutesRefusedError(`${where}: a route handler (${path}) cannot take the site config`);
183
+ for (const name of exports) {
184
+ if (!HTTP_METHODS.has(name)) {
185
+ throw new RoutesRefusedError(`${where}: a route handler exports HTTP methods only, not ${JSON.stringify(name)}`);
186
+ }
187
+ }
188
+ }
189
+ else {
190
+ if (!exports.includes("default"))
191
+ throw new RoutesRefusedError(`${where}: a ${kind} must export default`);
192
+ for (const name of exports) {
193
+ if (!["default", "metadata", "generateMetadata"].includes(name)) {
194
+ throw new RoutesRefusedError(`${where}: a ${kind} may export default, metadata and generateMetadata only, not ${JSON.stringify(name)}`);
195
+ }
196
+ }
197
+ }
198
+ if (config && raw.config === undefined) {
199
+ throw new RoutesRefusedError(`${where}: takes config, but the manifest names no config file`);
200
+ }
201
+ const metadataConfig = entry.metadataConfig === true;
202
+ if (metadataConfig && !config)
203
+ throw new RoutesRefusedError(`${where}: metadataConfig needs config: true`);
204
+ if (metadataConfig && !exports.includes("generateMetadata")) {
205
+ throw new RoutesRefusedError(`${where}: metadataConfig needs generateMetadata in exports`);
206
+ }
207
+ const segmentConfig = stringList(entry.segmentConfig, `${where}: segmentConfig`);
208
+ for (const line of segmentConfig) {
209
+ if (!SEGMENT_CONFIG_RE.test(line)) {
210
+ throw new RoutesRefusedError(`${where}: ${JSON.stringify(line)} is not a route-segment-config line`);
211
+ }
212
+ }
213
+ return { path, kind, module: entry.module, exports, segmentConfig, config, metadataConfig };
214
+ });
215
+ const oss = raw.oss === false ? false : undefined;
216
+ return { package: pkg, version, prefix, config: raw.config, siteOwned, messages, oss, routes };
217
+ }
218
+ /**
219
+ * The route manifests of the installed page packages, in package-name
220
+ * order: every `@working-theory/*` dependency of `<site>/apps/web` whose
221
+ * installed `package.json` declares one. A dependency not installed yet
222
+ * (before `pnpm install`) declares nothing and is not an error.
223
+ */
224
+ export function readRouteManifests(siteDir) {
225
+ const web = join(resolve(siteDir), ROUTES_APP_DIR);
226
+ const pkgPath = join(web, "package.json");
227
+ if (!existsSync(pkgPath))
228
+ return [];
229
+ let pkg;
230
+ try {
231
+ pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
232
+ }
233
+ catch (err) {
234
+ throw new RoutesRefusedError(`${ROUTES_APP_DIR}/package.json does not parse: ${err.message}`);
235
+ }
236
+ if (!isRecord(pkg))
237
+ return [];
238
+ const names = new Set();
239
+ for (const key of ["dependencies", "devDependencies"]) {
240
+ const deps = pkg[key];
241
+ if (isRecord(deps))
242
+ for (const name of Object.keys(deps))
243
+ if (name.startsWith(PACKAGE_SCOPE))
244
+ names.add(name);
245
+ }
246
+ const manifests = [];
247
+ for (const name of [...names].sort()) {
248
+ const installed = join(web, "node_modules", name, "package.json");
249
+ if (!existsSync(installed))
250
+ continue;
251
+ let meta;
252
+ try {
253
+ meta = JSON.parse(readFileSync(installed, "utf8"));
254
+ }
255
+ catch {
256
+ continue;
257
+ }
258
+ if (!isRecord(meta))
259
+ continue;
260
+ const ailk = meta[MANIFEST_KEY];
261
+ if (!isRecord(ailk) || typeof ailk.routes !== "string")
262
+ continue;
263
+ const manifestPath = join(dirname(installed), ailk.routes);
264
+ if (!existsSync(manifestPath)) {
265
+ throw new RoutesRefusedError(`${name} declares a route manifest at ${ailk.routes}, which its install does not carry`);
266
+ }
267
+ let raw;
268
+ try {
269
+ raw = JSON.parse(readFileSync(manifestPath, "utf8"));
270
+ }
271
+ catch (err) {
272
+ throw new RoutesRefusedError(`${name}'s route manifest does not parse: ${err.message}`);
273
+ }
274
+ const manifest = parseRouteManifest(name, typeof meta.version === "string" ? meta.version : "0.0.0", raw);
275
+ manifests.push({ ...manifest, root: dirname(installed) });
276
+ }
277
+ return manifests;
278
+ }
279
+ /** The header line of every generated route file begins with this; `remove-module` reads it as module code. */
280
+ export const GENERATED_ROUTE_HEADER = "// Generated by create-ailk routes from ";
281
+ /** Line 1 of a generated file whose manifest sets `"oss": false` — the public strip's file marker. */
282
+ export const OSS_FALSE_MARKER = "// oss: false";
283
+ /** The generated file's text for one entry. Every statement is one line; the config wrapper is in prettier's shape. */
284
+ export function renderRouteFile(manifest, entry) {
285
+ const specifier = `${manifest.package}/${entry.module}`;
286
+ const lines = [`${GENERATED_ROUTE_HEADER}${manifest.package} ${manifest.version} — do not edit.`];
287
+ if (manifest.oss === false)
288
+ lines.unshift(OSS_FALSE_MARKER);
289
+ if (entry.config) {
290
+ // The wrapper calls the page as the async function it is and returns its
291
+ // tree — no element boundary of its own — so the route module keeps the
292
+ // page's own contract (`(props) => Promise<ReactElement>`): what Next
293
+ // mounts, and what a test that renders `await Page(props)` renders.
294
+ // `app/[locale]/<path>` → the file's directory depth from the app root.
295
+ const depth = posix.dirname(posix.join(LOCALE_DIR, entry.path)).split("/").length;
296
+ // #11253 — a `metadataConfig` entry's `generateMetadata` reads the config
297
+ // too (the checkout pages answer notFound() off a spoke before any
298
+ // translation), so it is imported beside `Page` and wrapped, never
299
+ // re-exported. Prettier keeps that import on one line only within 80
300
+ // columns, so a longer one is rendered in prettier's broken shape.
301
+ let pageImport = `import Page from "${specifier}";`;
302
+ if (entry.metadataConfig) {
303
+ pageImport = `import Page, { generateMetadata as pageMetadata } from "${specifier}";`;
304
+ if (pageImport.length > 80)
305
+ pageImport = `import Page, {\n generateMetadata as pageMetadata,\n} from "${specifier}";`;
306
+ }
307
+ lines.push(pageImport, "", `import config from "${"../".repeat(depth)}${manifest.config}";`);
308
+ const reexports = entry.exports
309
+ .filter((name) => name !== "default" && !(entry.metadataConfig && name === "generateMetadata"))
310
+ .map((name) => `export { ${name} } from "${specifier}";`);
311
+ if (reexports.length + entry.segmentConfig.length > 0)
312
+ lines.push("", ...reexports, ...entry.segmentConfig);
313
+ if (entry.metadataConfig) {
314
+ lines.push("", "export async function generateMetadata(", ' props: Omit<Parameters<typeof pageMetadata>[0], "config">,', ") {", " return pageMetadata({ ...props, config });", "}");
315
+ }
316
+ lines.push("", "export default async function Route(", ' props: Omit<Parameters<typeof Page>[0], "config">,', ") {", " return Page({ ...props, config });", "}");
317
+ }
318
+ else {
319
+ for (const name of entry.exports)
320
+ lines.push(`export { ${name} } from "${specifier}";`);
321
+ lines.push(...entry.segmentConfig);
322
+ }
323
+ return `${lines.join("\n")}\n`;
324
+ }
325
+ /** The scaffold lint's own glob (`template-overlay/tools/lint-architecture.ts`): `**` is zero or more whole segments, `*` stays inside one. */
326
+ function globToRegExp(glob) {
327
+ const segments = glob.split("/");
328
+ let re = "^";
329
+ segments.forEach((seg, i) => {
330
+ const last = i === segments.length - 1;
331
+ if (seg === "**") {
332
+ re += last ? ".*" : "(?:[^/]+/)*";
333
+ return;
334
+ }
335
+ re += seg.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*");
336
+ if (!last)
337
+ re += "/";
338
+ });
339
+ return new RegExp(`${re}$`);
340
+ }
341
+ /**
342
+ * The entries of `<site>/customizations.yaml`, when the site has one — read
343
+ * by line, in the shape the scaffold's own file documents (create-ailk
344
+ * carries no YAML parser): under `customizations:`, each `- id: <id>` entry's
345
+ * `paths:` list of quoted or bare globs, block or flow form. An entry with no id or no paths
346
+ * records nothing; the overlay lint owns the file's full validation.
347
+ */
348
+ function readRecorded(siteDir) {
349
+ const path = join(siteDir, "customizations.yaml");
350
+ if (!existsSync(path))
351
+ return [];
352
+ const out = [];
353
+ let inList = false;
354
+ let inPaths = false;
355
+ let current;
356
+ const unquote = (raw) => raw.trim().replace(/^["']|["']$/g, "");
357
+ const flush = () => {
358
+ if (current?.id !== undefined && current.paths.length > 0) {
359
+ out.push({ id: current.id, patterns: current.paths.map(globToRegExp) });
360
+ }
361
+ current = undefined;
362
+ };
363
+ for (const raw of readFileSync(path, "utf8").split(/\r?\n/)) {
364
+ const line = raw.replace(/\s+#.*$/, "");
365
+ if (line.trim() === "" || line.trimStart().startsWith("#"))
366
+ continue;
367
+ if (/^\S/.test(line)) {
368
+ flush();
369
+ inList = /^customizations:/.test(line);
370
+ inPaths = false;
371
+ continue;
372
+ }
373
+ if (!inList)
374
+ continue;
375
+ // `- <key>: …` opens an entry, whichever key comes first.
376
+ const entry = /^(\s*)-\s+(\w+):(.*)$/.exec(line);
377
+ const key = entry ? entry[2] : /^\s+(\w+):(.*)$/.exec(line)?.[1];
378
+ const rest = entry ? entry[3] : (/^\s+(\w+):(.*)$/.exec(line)?.[2] ?? "");
379
+ if (entry) {
380
+ flush();
381
+ current = { id: undefined, paths: [] };
382
+ }
383
+ if (current === undefined)
384
+ continue;
385
+ if (key === "id") {
386
+ current.id = unquote(rest);
387
+ inPaths = false;
388
+ }
389
+ else if (key === "paths") {
390
+ // The flow form, `paths: ["a/**", "b/**"]`, or the block form below it.
391
+ const flow = /^\s*\[(.*)\]\s*$/.exec(rest);
392
+ if (flow)
393
+ current.paths.push(...flow[1].split(",").map(unquote).filter((p) => p !== ""));
394
+ inPaths = !flow;
395
+ }
396
+ else if (key !== undefined) {
397
+ inPaths = false;
398
+ }
399
+ else {
400
+ const item = /^\s+-\s+(.+)$/.exec(line);
401
+ if (inPaths && item)
402
+ current.paths.push(unquote(item[1]));
403
+ }
404
+ }
405
+ flush();
406
+ return out;
407
+ }
408
+ function recordFor(recorded, sitePath) {
409
+ return recorded.find((entry) => entry.patterns.some((re) => re.test(sitePath)));
410
+ }
411
+ /** Whether `<siteDir>/customizations.yaml` records `sitePath` — any entry, any path form or glob (the generator's own reading). */
412
+ export function isRecordedRoute(siteDir, sitePath) {
413
+ return recordFor(readRecorded(resolve(siteDir)), sitePath) !== undefined;
414
+ }
415
+ /** Routing files under `<web>/app/[locale]/<prefix>`, as site-relative POSIX paths, sorted. */
416
+ function routingFilesUnder(web, siteDir, prefix) {
417
+ const out = [];
418
+ const walk = (dir) => {
419
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
420
+ const path = join(dir, entry.name);
421
+ if (entry.isDirectory()) {
422
+ if (!SKIPPED_DIRS.has(entry.name))
423
+ walk(path);
424
+ }
425
+ else if (ROUTING_FILES.has(entry.name)) {
426
+ out.push(relative(siteDir, path).split(sep).join("/"));
427
+ }
428
+ }
429
+ };
430
+ const root = join(web, LOCALE_DIR, prefix);
431
+ if (existsSync(root))
432
+ walk(root);
433
+ return out.sort();
434
+ }
435
+ function plan(siteDir) {
436
+ const root = resolve(siteDir);
437
+ const web = join(root, ROUTES_APP_DIR);
438
+ const manifests = readRouteManifests(root);
439
+ const recorded = readRecorded(root);
440
+ // The site's topology (`.ailk-site-manifest.json`): on a spoke, the paths
441
+ // it does not carry are not its routes. A hub, or no manifest, carries all.
442
+ const spoke = readSpokeShape(root);
443
+ const planned = [];
444
+ const notCarried = [];
445
+ for (const manifest of manifests) {
446
+ const carried = manifest.routes.filter((entry) => {
447
+ const sitePath = relative(root, join(web, LOCALE_DIR, entry.path)).split(sep).join("/");
448
+ return spoke === undefined || !isSpokeExcluded(sitePath, spoke);
449
+ });
450
+ if (manifest.config !== undefined && carried.some((entry) => entry.config)) {
451
+ const configPath = join(web, `${manifest.config}.tsx`);
452
+ if (!existsSync(configPath)) {
453
+ throw new RoutesRefusedError(`${manifest.package}'s routes take the site config, but ${ROUTES_APP_DIR}/${manifest.config}.tsx does not exist — create it, typed by the package`);
454
+ }
455
+ }
456
+ for (const entry of manifest.routes) {
457
+ const absPath = join(web, LOCALE_DIR, entry.path);
458
+ const sitePath = relative(root, absPath).split(sep).join("/");
459
+ if (spoke !== undefined && isSpokeExcluded(sitePath, spoke)) {
460
+ notCarried.push(sitePath);
461
+ continue;
462
+ }
463
+ planned.push({ sitePath, absPath, text: renderRouteFile(manifest, entry), record: recordFor(recorded, sitePath) });
464
+ }
465
+ }
466
+ return { root, web, manifests, planned, recorded, notCarried };
467
+ }
468
+ /** The count check mode fails on: missing, stale and stray route files and orphaned overrides. */
469
+ export function routesFailing(drift) {
470
+ return drift.missing.length + drift.stale.length + drift.stray.length + drift.orphanedOverrides.length;
471
+ }
472
+ /** How the site's route files and message overrides differ from the installed page packages. `routesFailing` zero means in sync. */
473
+ export function checkRoutes(siteDir) {
474
+ const { root, web, manifests, planned, recorded, notCarried } = plan(siteDir);
475
+ const drift = {
476
+ missing: [],
477
+ stale: [],
478
+ stray: [],
479
+ recorded: [],
480
+ notCarried,
481
+ siteKept: [],
482
+ orphanedOverrides: orphanedOverrides(web, root, manifests),
483
+ generated: planned.length,
484
+ };
485
+ const known = new Set();
486
+ for (const p of planned) {
487
+ known.add(p.sitePath);
488
+ const exists = existsSync(p.absPath);
489
+ if (p.record) {
490
+ drift.recorded.push({ path: p.sitePath, state: exists ? "replaced" : "removed", id: p.record.id });
491
+ }
492
+ else if (!exists) {
493
+ drift.missing.push(p.sitePath);
494
+ }
495
+ else if (readFileSync(p.absPath, "utf8") !== p.text) {
496
+ drift.stale.push(p.sitePath);
497
+ }
498
+ }
499
+ for (const manifest of manifests) {
500
+ // A manifest that ships no route owns nothing yet (a package landing its
501
+ // contract ahead of its first page): nothing under its prefix is stray.
502
+ if (manifest.routes.length === 0)
503
+ continue;
504
+ const kept = new Set(manifest.siteOwned.map((path) => relative(root, join(web, LOCALE_DIR, path)).split(sep).join("/")));
505
+ for (const sitePath of manifest.prefix.flatMap((prefix) => routingFilesUnder(web, root, prefix))) {
506
+ if (known.has(sitePath))
507
+ continue;
508
+ known.add(sitePath);
509
+ if (kept.has(sitePath)) {
510
+ drift.siteKept.push(sitePath);
511
+ continue;
512
+ }
513
+ const record = recordFor(recorded, sitePath);
514
+ if (record)
515
+ drift.recorded.push({ path: sitePath, state: "replaced", id: record.id });
516
+ else
517
+ drift.stray.push(sitePath);
518
+ }
519
+ }
520
+ return drift;
521
+ }
522
+ function readCatalog(path) {
523
+ if (!existsSync(path))
524
+ return undefined;
525
+ try {
526
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
527
+ return isRecord(parsed) ? parsed : undefined;
528
+ }
529
+ catch {
530
+ return undefined;
531
+ }
532
+ }
533
+ /** Every string leaf of `catalog` under `prefix`, as dotted keys. */
534
+ function leafKeys(catalog, prefix) {
535
+ return Object.entries(catalog).flatMap(([key, value]) => isRecord(value) ? leafKeys(value, `${prefix}${key}.`) : typeof value === "string" ? [`${prefix}${key}`] : []);
536
+ }
537
+ function hasKey(catalog, dotted) {
538
+ let node = catalog;
539
+ for (const segment of dotted.split(".")) {
540
+ if (!isRecord(node) || !Object.prototype.hasOwnProperty.call(node, segment))
541
+ return false;
542
+ node = node[segment];
543
+ }
544
+ return typeof node === "string";
545
+ }
546
+ /**
547
+ * The site keys, across `<web>/messages/<locale>.json`, that sit under a
548
+ * namespace a page package's catalog ships yet name a key that catalog does
549
+ * not have — an override of a string the package no longer carries. A site
550
+ * locale with no package catalog is read against the package's `en`.
551
+ */
552
+ function orphanedOverrides(web, siteDir, manifests) {
553
+ const messagesDir = join(web, "messages");
554
+ if (!existsSync(messagesDir))
555
+ return [];
556
+ const locales = readdirSync(messagesDir)
557
+ .filter((name) => name.endsWith(".json"))
558
+ .map((name) => name.slice(0, -".json".length))
559
+ .sort();
560
+ const out = [];
561
+ for (const manifest of manifests) {
562
+ if (manifest.messages === undefined || manifest.root === undefined)
563
+ continue;
564
+ const catalogDir = join(manifest.root, manifest.messages.catalog);
565
+ const fallback = readCatalog(join(catalogDir, "en.json"));
566
+ // A declared catalog the install cannot answer for checks nothing: refuse,
567
+ // as an unreadable manifest is refused, rather than pass silently.
568
+ if (fallback === undefined) {
569
+ throw new RoutesRefusedError(`${manifest.package} declares its message catalog at ${manifest.messages.catalog}, but its install carries no readable ${manifest.messages.catalog}/en.json`);
570
+ }
571
+ const owned = manifest.messages.siteOwned;
572
+ for (const locale of locales) {
573
+ const sitePath = join(messagesDir, `${locale}.json`);
574
+ const siteCatalog = readCatalog(sitePath);
575
+ const packaged = readCatalog(join(catalogDir, `${locale}.json`)) ?? fallback;
576
+ if (siteCatalog === undefined || packaged === undefined)
577
+ continue;
578
+ const file = relative(siteDir, sitePath).split(sep).join("/");
579
+ for (const namespace of Object.keys(packaged)) {
580
+ const site = siteCatalog[namespace];
581
+ if (!isRecord(site))
582
+ continue;
583
+ for (const key of leafKeys(site, `${namespace}.`)) {
584
+ if (owned.some((prefix) => key === prefix || key.startsWith(`${prefix}.`)))
585
+ continue;
586
+ if (!hasKey(packaged, key))
587
+ out.push(`${file}: ${key} (${manifest.package})`);
588
+ }
589
+ }
590
+ }
591
+ }
592
+ return out;
593
+ }
594
+ /** Write every generated file that is missing or stale; a recorded route is left exactly as it is. */
595
+ export function writeRoutes(siteDir) {
596
+ const { planned } = plan(siteDir);
597
+ const result = { written: [], current: [], recorded: [] };
598
+ for (const p of planned) {
599
+ const exists = existsSync(p.absPath);
600
+ if (p.record) {
601
+ result.recorded.push({ path: p.sitePath, state: exists ? "replaced" : "removed", id: p.record.id });
602
+ continue;
603
+ }
604
+ if (exists && readFileSync(p.absPath, "utf8") === p.text) {
605
+ result.current.push(p.sitePath);
606
+ continue;
607
+ }
608
+ mkdirSync(dirname(p.absPath), { recursive: true });
609
+ writeFileSync(p.absPath, p.text);
610
+ result.written.push(p.sitePath);
611
+ }
612
+ return result;
613
+ }
614
+ export const ROUTES_HELP = `create-ailk routes — generate the route files for the pages a site's packages ship.
615
+
616
+ Usage:
617
+ create-ailk routes --write [<target-dir>]
618
+ create-ailk routes --check [<target-dir>]
619
+
620
+ Arguments:
621
+ <target-dir> The site root (holds apps/web). Defaults to the
622
+ current dir.
623
+
624
+ Options:
625
+ --write Write one generated file per route the installed
626
+ page packages declare, under apps/web/app/[locale]/.
627
+ A file already current is left alone.
628
+ --check Write nothing; exit 1 naming each generated file
629
+ that is missing, stale (differs from what --write
630
+ would write) or stray (a page.tsx, layout.tsx or
631
+ route.ts under a package's route prefix that is
632
+ neither generated, recorded, nor one the package
633
+ leaves to the site). It also names each orphaned
634
+ override: a key in apps/web/messages/<locale>.json
635
+ under a namespace a package's catalog ships that
636
+ the catalog no longer has.
637
+ --help, -h Print this message.
638
+
639
+ A page package is an installed @working-theory/* dependency of apps/web whose
640
+ package.json declares "ailk": { "routes": "<manifest>" }. A generated file
641
+ re-exports the package's page and copies its route-segment config; when the
642
+ page takes the site's config it imports the manifest's config file from the
643
+ app root (apps/web/account.config.tsx, say) and passes it in. Replace or remove a shipped route by recording it in
644
+ customizations.yaml (an entry whose paths match the route file): a recorded
645
+ route is reported as replaced or removed, never failed, and --write never
646
+ touches it. Run --write after \`pnpm install\` (the manifests are read from the
647
+ installed packages); the scaffold's preflight runs --check as \`pnpm routes:check\`.
648
+ `;
649
+ /** Parse the argv AFTER the `routes` word. Strict `node:util` parseArgs, like `parseSyncRoutesArgs`. */
650
+ export function parseRoutesArgs(argv) {
651
+ const parsed = parseArgs({
652
+ args: argv,
653
+ strict: true,
654
+ allowPositionals: true,
655
+ options: {
656
+ write: { type: "boolean", default: false },
657
+ check: { type: "boolean", default: false },
658
+ help: { type: "boolean", default: false, short: "h" },
659
+ },
660
+ });
661
+ if (parsed.positionals.length > 1) {
662
+ throw new RoutesRefusedError(`routes takes one target directory, got ${parsed.positionals.length}`);
663
+ }
664
+ const args = {
665
+ target: parsed.positionals[0],
666
+ write: parsed.values.write,
667
+ check: parsed.values.check,
668
+ help: parsed.values.help,
669
+ };
670
+ if (!args.help && args.write === args.check) {
671
+ throw new RoutesRefusedError("routes needs exactly one of --write or --check");
672
+ }
673
+ return args;
674
+ }
675
+ /** The printed report: one line per file, grouped by state; the recorded routes last, under their decision. */
676
+ export function formatRoutesReport(result, mode) {
677
+ const lines = [];
678
+ if (mode === "check") {
679
+ const drift = result;
680
+ const failing = [
681
+ ...drift.missing.map((p) => ` missing: ${p}`),
682
+ ...drift.stale.map((p) => ` stale: ${p}`),
683
+ ...drift.stray.map((p) => ` stray: ${p}`),
684
+ ...drift.orphanedOverrides.map((p) => ` orphaned override: ${p}`),
685
+ ];
686
+ if (failing.length === 0) {
687
+ lines.push(`[create-ailk] routes: OK — ${drift.generated} generated route file(s) in sync`);
688
+ }
689
+ else {
690
+ lines.push(`[create-ailk] routes: ${failing.length} route file(s) or message override(s) differ from the installed page packages (run \`create-ailk routes --write\` to rewrite a route file; record a replaced or removed route in customizations.yaml; delete an orphaned override, whose key the package no longer has):`, ...failing);
691
+ }
692
+ }
693
+ else {
694
+ const write = result;
695
+ lines.push(`[create-ailk] routes: wrote ${write.written.length} route file(s), ${write.current.length} already current`);
696
+ for (const p of write.written)
697
+ lines.push(` wrote: ${p}`);
698
+ }
699
+ for (const r of result.recorded)
700
+ lines.push(` ${r.state} (recorded): ${r.path} — customizations.yaml "${r.id}"`);
701
+ if ("notCarried" in result)
702
+ for (const p of result.notCarried)
703
+ lines.push(` not carried on this spoke: ${p}`);
704
+ if ("siteKept" in result)
705
+ for (const p of result.siteKept)
706
+ lines.push(` kept by the site (the package ships no page here): ${p}`);
707
+ return `${lines.join("\n")}\n`;
708
+ }