create-pet-adopt 0.0.0 → 0.3.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 (486) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +120 -0
  3. package/index.js +920 -0
  4. package/package.json +43 -1
  5. package/template/.env.example +136 -0
  6. package/template/.pet-adopt/template.json +581 -0
  7. package/template/LICENSE +21 -0
  8. package/template/README.md +109 -0
  9. package/template/_gitignore +28 -0
  10. package/template/_pnpm-lock.yaml +9251 -0
  11. package/template/assets/sample-pet.png +0 -0
  12. package/template/components.json +25 -0
  13. package/template/docker-compose.yml +110 -0
  14. package/template/drizzle/pg/0000_initial.sql +176 -0
  15. package/template/drizzle/pg/0001_greedy_the_renegades.sql +1 -0
  16. package/template/drizzle/pg/0002_fuzzy_the_renegades.sql +1 -0
  17. package/template/drizzle/pg/0003_thin_multiple_man.sql +1 -0
  18. package/template/drizzle/pg/0004_boring_norman_osborn.sql +15 -0
  19. package/template/drizzle/pg/0005_bitter_proemial_gods.sql +3 -0
  20. package/template/drizzle/pg/0006_friendly_black_knight.sql +2 -0
  21. package/template/drizzle/pg/0007_wise_ozymandias.sql +11 -0
  22. package/template/drizzle/pg/0008_messy_human_fly.sql +2 -0
  23. package/template/drizzle/pg/0009_amused_lady_bullseye.sql +1 -0
  24. package/template/drizzle/pg/0010_cute_mauler.sql +7 -0
  25. package/template/drizzle/pg/0011_clear_purple_man.sql +3 -0
  26. package/template/drizzle/pg/0012_tiresome_gunslinger.sql +2 -0
  27. package/template/drizzle/pg/0013_awesome_wong.sql +18 -0
  28. package/template/drizzle/pg/0014_fantastic_sumo.sql +12 -0
  29. package/template/drizzle/pg/0015_pink_carnage.sql +12 -0
  30. package/template/drizzle/pg/0016_sloppy_king_bedlam.sql +2 -0
  31. package/template/drizzle/pg/0017_steep_warhawk.sql +15 -0
  32. package/template/drizzle/pg/0018_mixed_otto_octavius.sql +4 -0
  33. package/template/drizzle/pg/0019_talented_rocket_raccoon.sql +1 -0
  34. package/template/drizzle/pg/0020_worthless_zodiak.sql +19 -0
  35. package/template/drizzle/pg/0021_adorable_squadron_supreme.sql +1 -0
  36. package/template/drizzle/pg/0022_soft_pixie.sql +5 -0
  37. package/template/drizzle/pg/0023_fluffy_quasar.sql +1 -0
  38. package/template/drizzle/pg/0024_uneven_ken_ellis.sql +2 -0
  39. package/template/drizzle/pg/0025_rich_white_queen.sql +3 -0
  40. package/template/drizzle/pg/0026_spooky_komodo.sql +16 -0
  41. package/template/drizzle/pg/0027_big_thunderbolts.sql +2 -0
  42. package/template/drizzle/pg/meta/0000_snapshot.json +1265 -0
  43. package/template/drizzle/pg/meta/0001_snapshot.json +1272 -0
  44. package/template/drizzle/pg/meta/0002_snapshot.json +1278 -0
  45. package/template/drizzle/pg/meta/0003_snapshot.json +1284 -0
  46. package/template/drizzle/pg/meta/0004_snapshot.json +1401 -0
  47. package/template/drizzle/pg/meta/0005_snapshot.json +1401 -0
  48. package/template/drizzle/pg/meta/0006_snapshot.json +1414 -0
  49. package/template/drizzle/pg/meta/0007_snapshot.json +1485 -0
  50. package/template/drizzle/pg/meta/0008_snapshot.json +1504 -0
  51. package/template/drizzle/pg/meta/0009_snapshot.json +1510 -0
  52. package/template/drizzle/pg/meta/0010_snapshot.json +1556 -0
  53. package/template/drizzle/pg/meta/0011_snapshot.json +1574 -0
  54. package/template/drizzle/pg/meta/0012_snapshot.json +1586 -0
  55. package/template/drizzle/pg/meta/0013_snapshot.json +1730 -0
  56. package/template/drizzle/pg/meta/0014_snapshot.json +1805 -0
  57. package/template/drizzle/pg/meta/0015_snapshot.json +1883 -0
  58. package/template/drizzle/pg/meta/0016_snapshot.json +1897 -0
  59. package/template/drizzle/pg/meta/0017_snapshot.json +2013 -0
  60. package/template/drizzle/pg/meta/0018_snapshot.json +1988 -0
  61. package/template/drizzle/pg/meta/0019_snapshot.json +1994 -0
  62. package/template/drizzle/pg/meta/0020_snapshot.json +2108 -0
  63. package/template/drizzle/pg/meta/0021_snapshot.json +2114 -0
  64. package/template/drizzle/pg/meta/0022_snapshot.json +2126 -0
  65. package/template/drizzle/pg/meta/0023_snapshot.json +2132 -0
  66. package/template/drizzle/pg/meta/0024_snapshot.json +2151 -0
  67. package/template/drizzle/pg/meta/0025_snapshot.json +2169 -0
  68. package/template/drizzle/pg/meta/0026_snapshot.json +2294 -0
  69. package/template/drizzle/pg/meta/0027_snapshot.json +2330 -0
  70. package/template/drizzle/pg/meta/_journal.json +202 -0
  71. package/template/drizzle/sqlite/0000_initial.sql +176 -0
  72. package/template/drizzle/sqlite/0001_easy_sebastian_shaw.sql +1 -0
  73. package/template/drizzle/sqlite/0002_past_king_cobra.sql +1 -0
  74. package/template/drizzle/sqlite/0003_organic_masked_marvel.sql +1 -0
  75. package/template/drizzle/sqlite/0004_panoramic_inhumans.sql +15 -0
  76. package/template/drizzle/sqlite/0005_small_sunset_bain.sql +19 -0
  77. package/template/drizzle/sqlite/0006_narrow_medusa.sql +2 -0
  78. package/template/drizzle/sqlite/0007_gray_grandmaster.sql +10 -0
  79. package/template/drizzle/sqlite/0008_chief_toxin.sql +1 -0
  80. package/template/drizzle/sqlite/0009_vengeful_tag.sql +1 -0
  81. package/template/drizzle/sqlite/0010_kind_klaw.sql +7 -0
  82. package/template/drizzle/sqlite/0011_overrated_meltdown.sql +3 -0
  83. package/template/drizzle/sqlite/0012_robust_next_avengers.sql +2 -0
  84. package/template/drizzle/sqlite/0013_melodic_kitty_pryde.sql +18 -0
  85. package/template/drizzle/sqlite/0014_stormy_cyclops.sql +12 -0
  86. package/template/drizzle/sqlite/0015_parallel_mongu.sql +11 -0
  87. package/template/drizzle/sqlite/0016_grey_quicksilver.sql +2 -0
  88. package/template/drizzle/sqlite/0017_daily_psylocke.sql +15 -0
  89. package/template/drizzle/sqlite/0018_whole_redwing.sql +4 -0
  90. package/template/drizzle/sqlite/0019_spotty_mandroid.sql +1 -0
  91. package/template/drizzle/sqlite/0020_wild_wendell_rand.sql +19 -0
  92. package/template/drizzle/sqlite/0021_calm_lockheed.sql +1 -0
  93. package/template/drizzle/sqlite/0022_lonely_emma_frost.sql +5 -0
  94. package/template/drizzle/sqlite/0023_elite_tony_stark.sql +1 -0
  95. package/template/drizzle/sqlite/0024_little_lily_hollister.sql +1 -0
  96. package/template/drizzle/sqlite/0025_tough_shotgun.sql +3 -0
  97. package/template/drizzle/sqlite/0026_faithful_mephistopheles.sql +16 -0
  98. package/template/drizzle/sqlite/0027_rapid_arclight.sql +2 -0
  99. package/template/drizzle/sqlite/meta/0000_snapshot.json +1237 -0
  100. package/template/drizzle/sqlite/meta/0001_snapshot.json +1245 -0
  101. package/template/drizzle/sqlite/meta/0002_snapshot.json +1252 -0
  102. package/template/drizzle/sqlite/meta/0003_snapshot.json +1259 -0
  103. package/template/drizzle/sqlite/meta/0004_snapshot.json +1369 -0
  104. package/template/drizzle/sqlite/meta/0005_snapshot.json +1369 -0
  105. package/template/drizzle/sqlite/meta/0006_snapshot.json +1384 -0
  106. package/template/drizzle/sqlite/meta/0007_snapshot.json +1459 -0
  107. package/template/drizzle/sqlite/meta/0008_snapshot.json +1479 -0
  108. package/template/drizzle/sqlite/meta/0009_snapshot.json +1486 -0
  109. package/template/drizzle/sqlite/meta/0010_snapshot.json +1533 -0
  110. package/template/drizzle/sqlite/meta/0011_snapshot.json +1554 -0
  111. package/template/drizzle/sqlite/meta/0012_snapshot.json +1568 -0
  112. package/template/drizzle/sqlite/meta/0013_snapshot.json +1687 -0
  113. package/template/drizzle/sqlite/meta/0014_snapshot.json +1769 -0
  114. package/template/drizzle/sqlite/meta/0015_snapshot.json +1852 -0
  115. package/template/drizzle/sqlite/meta/0016_snapshot.json +1867 -0
  116. package/template/drizzle/sqlite/meta/0017_snapshot.json +1973 -0
  117. package/template/drizzle/sqlite/meta/0018_snapshot.json +1944 -0
  118. package/template/drizzle/sqlite/meta/0019_snapshot.json +1951 -0
  119. package/template/drizzle/sqlite/meta/0020_snapshot.json +2077 -0
  120. package/template/drizzle/sqlite/meta/0021_snapshot.json +2084 -0
  121. package/template/drizzle/sqlite/meta/0022_snapshot.json +2098 -0
  122. package/template/drizzle/sqlite/meta/0023_snapshot.json +2105 -0
  123. package/template/drizzle/sqlite/meta/0024_snapshot.json +2125 -0
  124. package/template/drizzle/sqlite/meta/0025_snapshot.json +2146 -0
  125. package/template/drizzle/sqlite/meta/0026_snapshot.json +2265 -0
  126. package/template/drizzle/sqlite/meta/0027_snapshot.json +2280 -0
  127. package/template/drizzle/sqlite/meta/_journal.json +202 -0
  128. package/template/drizzle.pg.config.ts +8 -0
  129. package/template/drizzle.sqlite.config.ts +8 -0
  130. package/template/eslint.config.mjs +22 -0
  131. package/template/next.config.ts +153 -0
  132. package/template/package.json +102 -0
  133. package/template/pet-adopt.blocks.ts +9 -0
  134. package/template/pet-adopt.config.ts +17 -0
  135. package/template/pnpm-workspace.yaml +19 -0
  136. package/template/postcss.config.mjs +5 -0
  137. package/template/scripts/check-routes.ts +405 -0
  138. package/template/scripts/check-schemas.ts +58 -0
  139. package/template/scripts/migrate-all.ts +25 -0
  140. package/template/scripts/migrate-on-build.ts +71 -0
  141. package/template/scripts/migrate.ts +20 -0
  142. package/template/scripts/plugin-generate.ts +92 -0
  143. package/template/scripts/reset-password.ts +45 -0
  144. package/template/scripts/reset-two-factor.ts +53 -0
  145. package/template/scripts/seed.ts +79 -0
  146. package/template/scripts/setup-env.ts +91 -0
  147. package/template/scripts/storage-check.ts +53 -0
  148. package/template/src/app/(admin)/admin/account/AccountForms.tsx +194 -0
  149. package/template/src/app/(admin)/admin/account/page.tsx +59 -0
  150. package/template/src/app/(admin)/admin/activity/page.tsx +76 -0
  151. package/template/src/app/(admin)/admin/authentication/archived/page.tsx +24 -0
  152. package/template/src/app/(admin)/admin/authentication/layout.tsx +20 -0
  153. package/template/src/app/(admin)/admin/authentication/page.tsx +36 -0
  154. package/template/src/app/(admin)/admin/authentication/providers/page.tsx +33 -0
  155. package/template/src/app/(admin)/admin/email/layout.tsx +21 -0
  156. package/template/src/app/(admin)/admin/email/page.tsx +43 -0
  157. package/template/src/app/(admin)/admin/email/templates/page.tsx +38 -0
  158. package/template/src/app/(admin)/admin/error.tsx +36 -0
  159. package/template/src/app/(admin)/admin/layout.tsx +26 -0
  160. package/template/src/app/(admin)/admin/loading.tsx +9 -0
  161. package/template/src/app/(admin)/admin/media/[id]/page.tsx +97 -0
  162. package/template/src/app/(admin)/admin/media/page.tsx +34 -0
  163. package/template/src/app/(admin)/admin/media/search-params.ts +16 -0
  164. package/template/src/app/(admin)/admin/page.tsx +79 -0
  165. package/template/src/app/(admin)/admin/pages/PageForm.tsx +604 -0
  166. package/template/src/app/(admin)/admin/pages/[id]/page.tsx +51 -0
  167. package/template/src/app/(admin)/admin/pages/new/page.tsx +19 -0
  168. package/template/src/app/(admin)/admin/pages/page.tsx +49 -0
  169. package/template/src/app/(admin)/admin/pets/PetForm.tsx +437 -0
  170. package/template/src/app/(admin)/admin/pets/[id]/page.tsx +41 -0
  171. package/template/src/app/(admin)/admin/pets/new/page.tsx +26 -0
  172. package/template/src/app/(admin)/admin/pets/page.tsx +70 -0
  173. package/template/src/app/(admin)/admin/pets/search-params.ts +16 -0
  174. package/template/src/app/(admin)/admin/plugins/[plugin]/[[...path]]/page.tsx +73 -0
  175. package/template/src/app/(admin)/admin/plugins/page.tsx +66 -0
  176. package/template/src/app/(admin)/admin/settings/SettingsForm.tsx +644 -0
  177. package/template/src/app/(admin)/admin/settings/email/page.tsx +9 -0
  178. package/template/src/app/(admin)/admin/settings/page.tsx +40 -0
  179. package/template/src/app/(admin)/admin/settings/templates/page.tsx +9 -0
  180. package/template/src/app/(admin)/admin/theme/[id]/page.tsx +28 -0
  181. package/template/src/app/(admin)/admin/theme/page.tsx +30 -0
  182. package/template/src/app/(admin)/admin/users/page.tsx +33 -0
  183. package/template/src/app/(admin)/layout.tsx +75 -0
  184. package/template/src/app/(admin)/providers.tsx +42 -0
  185. package/template/src/app/(auth)/admin/confirm-email/page.tsx +40 -0
  186. package/template/src/app/(auth)/admin/invite/page.tsx +38 -0
  187. package/template/src/app/(auth)/admin/login/DemoSignIn.tsx +69 -0
  188. package/template/src/app/(auth)/admin/login/page.tsx +83 -0
  189. package/template/src/app/(auth)/admin/reset-password/page.tsx +73 -0
  190. package/template/src/app/(auth)/error.tsx +9 -0
  191. package/template/src/app/(auth)/layout.tsx +71 -0
  192. package/template/src/app/(editor)/EditorToast.tsx +43 -0
  193. package/template/src/app/(editor)/edit/[id]/PageEditor.tsx +586 -0
  194. package/template/src/app/(editor)/edit/[id]/actions.ts +139 -0
  195. package/template/src/app/(editor)/edit/[id]/page.tsx +76 -0
  196. package/template/src/app/(editor)/edit/[id]/preview/page.tsx +81 -0
  197. package/template/src/app/(editor)/edit/email/[id]/EmailEditor.tsx +236 -0
  198. package/template/src/app/(editor)/edit/email/[id]/page.tsx +64 -0
  199. package/template/src/app/(editor)/edit/theme-preview/page.tsx +94 -0
  200. package/template/src/app/(editor)/editor.css +223 -0
  201. package/template/src/app/(editor)/error.tsx +32 -0
  202. package/template/src/app/(editor)/layout.tsx +67 -0
  203. package/template/src/app/(frontend)/[slug]/page.tsx +53 -0
  204. package/template/src/app/(frontend)/fonts.ts +8 -0
  205. package/template/src/app/(frontend)/layout.tsx +107 -0
  206. package/template/src/app/(frontend)/not-found.tsx +16 -0
  207. package/template/src/app/(frontend)/page.tsx +42 -0
  208. package/template/src/app/(frontend)/pets/[slug]/page.tsx +92 -0
  209. package/template/src/app/(frontend)/pets/page.tsx +42 -0
  210. package/template/src/app/(frontend)/styles.css +537 -0
  211. package/template/src/app/(setup)/error.tsx +9 -0
  212. package/template/src/app/(setup)/layout.tsx +41 -0
  213. package/template/src/app/(setup)/setup/page.tsx +105 -0
  214. package/template/src/app/(setup)/setup/storage-check.ts +43 -0
  215. package/template/src/app/api/auth/[...all]/route.ts +144 -0
  216. package/template/src/app/health/route.ts +9 -0
  217. package/template/src/app/media/[...path]/route.ts +45 -0
  218. package/template/src/app/media/email/[name]/route.ts +60 -0
  219. package/template/src/app/robots.ts +19 -0
  220. package/template/src/app/sitemap.ts +24 -0
  221. package/template/src/components/admin/AdminNav.tsx +153 -0
  222. package/template/src/components/admin/AdminShell.tsx +107 -0
  223. package/template/src/components/admin/DemoNotice.tsx +31 -0
  224. package/template/src/components/admin/EmailConfirmBanner.tsx +44 -0
  225. package/template/src/components/admin/EmptyState.tsx +10 -0
  226. package/template/src/components/admin/ErrorSummary.tsx +72 -0
  227. package/template/src/components/admin/MediaDetails.tsx +218 -0
  228. package/template/src/components/admin/MediaGrid.tsx +307 -0
  229. package/template/src/components/admin/MediaLibrary.tsx +103 -0
  230. package/template/src/components/admin/MediaPager.tsx +66 -0
  231. package/template/src/components/admin/PageHeader.tsx +22 -0
  232. package/template/src/components/admin/PhoneInput.tsx +128 -0
  233. package/template/src/components/admin/PluginWidgetBoundary.tsx +38 -0
  234. package/template/src/components/admin/PluginWidgets.tsx +51 -0
  235. package/template/src/components/admin/RemountOnNavigate.tsx +37 -0
  236. package/template/src/components/admin/StatusBadge.tsx +16 -0
  237. package/template/src/components/admin/UploadPhotosDialog.tsx +387 -0
  238. package/template/src/components/admin/UserAvatar.tsx +18 -0
  239. package/template/src/components/admin/UserMenu.tsx +118 -0
  240. package/template/src/components/admin/ViewSiteLink.tsx +24 -0
  241. package/template/src/components/admin/account/ConnectedProviders.tsx +91 -0
  242. package/template/src/components/admin/account/DeleteAccountCard.tsx +136 -0
  243. package/template/src/components/admin/account/EmailCard.tsx +137 -0
  244. package/template/src/components/admin/account/ProfilePicture.tsx +159 -0
  245. package/template/src/components/admin/activity/ActivityFilters.tsx +146 -0
  246. package/template/src/components/admin/activity/ActivityLog.tsx +159 -0
  247. package/template/src/components/admin/activity/RecentActivity.tsx +52 -0
  248. package/template/src/components/admin/demo-mode.tsx +17 -0
  249. package/template/src/components/admin/nav-items.ts +47 -0
  250. package/template/src/components/admin/pages/PageDetails.tsx +198 -0
  251. package/template/src/components/admin/pages/PageVersions.tsx +296 -0
  252. package/template/src/components/admin/pages/PagesTable.tsx +467 -0
  253. package/template/src/components/admin/pets/FilterBar.tsx +154 -0
  254. package/template/src/components/admin/pets/PetCard.tsx +170 -0
  255. package/template/src/components/admin/pets/PetList.tsx +112 -0
  256. package/template/src/components/admin/pets/PetListSkeleton.tsx +84 -0
  257. package/template/src/components/admin/pets/PetPagination.tsx +91 -0
  258. package/template/src/components/admin/pets/form/AgeFields.tsx +132 -0
  259. package/template/src/components/admin/pets/form/LocationFields.tsx +231 -0
  260. package/template/src/components/admin/pets/form/MediaPickerDialog.tsx +359 -0
  261. package/template/src/components/admin/pets/form/PhotosField.tsx +176 -0
  262. package/template/src/components/admin/pets/form/RichTextField.tsx +438 -0
  263. package/template/src/components/admin/pets/form/SeoImageField.tsx +87 -0
  264. package/template/src/components/admin/pets/form/SeoPreview.tsx +142 -0
  265. package/template/src/components/admin/pets/form/fields.tsx +434 -0
  266. package/template/src/components/admin/pets/form/rich-text-extensions.ts +45 -0
  267. package/template/src/components/admin/pets/timeline/PetTimeline.tsx +297 -0
  268. package/template/src/components/admin/pets/timeline/TimelineEntryForm.tsx +289 -0
  269. package/template/src/components/admin/pets/timeline/TimelinePhotosField.tsx +173 -0
  270. package/template/src/components/admin/plugins/PluginNotReady.tsx +28 -0
  271. package/template/src/components/admin/plugins/PluginOverview.tsx +121 -0
  272. package/template/src/components/admin/plugins/SendTestEmail.tsx +70 -0
  273. package/template/src/components/admin/settings/AuthProviders.tsx +373 -0
  274. package/template/src/components/admin/settings/AuthenticationNav.tsx +42 -0
  275. package/template/src/components/admin/settings/EmailNav.tsx +40 -0
  276. package/template/src/components/admin/settings/EmailSettingsForm.tsx +325 -0
  277. package/template/src/components/admin/settings/EmailTemplates.tsx +551 -0
  278. package/template/src/components/admin/settings/RegionFields.tsx +203 -0
  279. package/template/src/components/admin/site-time.tsx +26 -0
  280. package/template/src/components/admin/theme/ThemeEditor.tsx +467 -0
  281. package/template/src/components/admin/theme/ThemeLibrary.tsx +339 -0
  282. package/template/src/components/admin/theme/ThemeSwatches.tsx +30 -0
  283. package/template/src/components/admin/theme/theme-utils.ts +32 -0
  284. package/template/src/components/admin/two-factor/BackupCodeList.tsx +54 -0
  285. package/template/src/components/admin/two-factor/TwoFactorCard.tsx +237 -0
  286. package/template/src/components/admin/two-factor/TwoFactorRequired.tsx +52 -0
  287. package/template/src/components/admin/two-factor/TwoFactorSetup.tsx +180 -0
  288. package/template/src/components/admin/use-unsaved-changes.tsx +101 -0
  289. package/template/src/components/admin/users/ArchivedAccounts.tsx +159 -0
  290. package/template/src/components/admin/users/InviteDialogs.tsx +131 -0
  291. package/template/src/components/admin/users/TwoFactorRoles.tsx +80 -0
  292. package/template/src/components/admin/users/UserDialogs.tsx +681 -0
  293. package/template/src/components/admin/users/UsersTable.tsx +374 -0
  294. package/template/src/components/admin/view-only.tsx +43 -0
  295. package/template/src/components/auth/AcceptInviteForm.tsx +123 -0
  296. package/template/src/components/auth/AuthNav.tsx +80 -0
  297. package/template/src/components/auth/ConfirmEmailForm.tsx +73 -0
  298. package/template/src/components/auth/LoginForm.tsx +250 -0
  299. package/template/src/components/auth/PageError.tsx +37 -0
  300. package/template/src/components/auth/ProviderSignIn.tsx +53 -0
  301. package/template/src/components/auth/ResetPasswordForm.tsx +267 -0
  302. package/template/src/components/demo/DemoBanner.tsx +38 -0
  303. package/template/src/components/demo/SiteDemoBanner.tsx +22 -0
  304. package/template/src/components/demo/wording.ts +21 -0
  305. package/template/src/components/setup/SetupAccountForm.tsx +93 -0
  306. package/template/src/components/setup/SetupDone.tsx +95 -0
  307. package/template/src/components/setup/SetupNav.tsx +49 -0
  308. package/template/src/components/setup/SetupSampleContent.tsx +67 -0
  309. package/template/src/components/setup/SetupSiteForm.tsx +104 -0
  310. package/template/src/components/setup/SetupThemePicker.tsx +73 -0
  311. package/template/src/components/setup/SkipSetup.tsx +35 -0
  312. package/template/src/components/site/BuilderContent.tsx +46 -0
  313. package/template/src/components/site/CopyButton.tsx +28 -0
  314. package/template/src/components/site/ImageCarousel.tsx +52 -0
  315. package/template/src/components/site/PetCard.tsx +32 -0
  316. package/template/src/components/site/PetCatalog.tsx +106 -0
  317. package/template/src/components/site/PetGallery.tsx +75 -0
  318. package/template/src/components/site/PetTimeline.tsx +82 -0
  319. package/template/src/components/site/RemountOnNavigate.tsx +13 -0
  320. package/template/src/components/site/RichText.tsx +56 -0
  321. package/template/src/components/site/SmartLink.tsx +37 -0
  322. package/template/src/components/site/SocialIcons.tsx +26 -0
  323. package/template/src/components/site/ThemePreviewBridge.tsx +29 -0
  324. package/template/src/components/site/ThemeStyle.tsx +22 -0
  325. package/template/src/components/site/ThemeToggle.tsx +36 -0
  326. package/template/src/components/site/WhatsAppButton.tsx +27 -0
  327. package/template/src/components/site/timeline-format.ts +20 -0
  328. package/template/src/db/client.ts +702 -0
  329. package/template/src/db/compare-tables.ts +41 -0
  330. package/template/src/db/migrate.ts +28 -0
  331. package/template/src/db/plugin-migrations.ts +167 -0
  332. package/template/src/db/schema/pg.ts +484 -0
  333. package/template/src/db/schema/sqlite.ts +492 -0
  334. package/template/src/instrumentation.ts +110 -0
  335. package/template/src/lib/activity.ts +29 -0
  336. package/template/src/lib/admin/call-action.ts +19 -0
  337. package/template/src/lib/admin/initials.ts +9 -0
  338. package/template/src/lib/admin/media-cache.ts +16 -0
  339. package/template/src/lib/admin/media-page.ts +3 -0
  340. package/template/src/lib/admin/pet-form.ts +242 -0
  341. package/template/src/lib/admin/pets-cache.ts +22 -0
  342. package/template/src/lib/admin/unwrap-client.ts +11 -0
  343. package/template/src/lib/admin/unwrap.ts +38 -0
  344. package/template/src/lib/admin/use-media-list.ts +41 -0
  345. package/template/src/lib/admin/use-pet-list.ts +58 -0
  346. package/template/src/lib/age.ts +117 -0
  347. package/template/src/lib/auth-provider-errors.ts +38 -0
  348. package/template/src/lib/cache.ts +69 -0
  349. package/template/src/lib/color-mode.ts +48 -0
  350. package/template/src/lib/demo.ts +78 -0
  351. package/template/src/lib/email-address.ts +9 -0
  352. package/template/src/lib/email-template.ts +691 -0
  353. package/template/src/lib/links.ts +78 -0
  354. package/template/src/lib/mail-error.ts +38 -0
  355. package/template/src/lib/media-name.ts +31 -0
  356. package/template/src/lib/options.ts +134 -0
  357. package/template/src/lib/pagination.ts +28 -0
  358. package/template/src/lib/pet-placeholders.ts +34 -0
  359. package/template/src/lib/pet-seo.ts +40 -0
  360. package/template/src/lib/pet-timeline.ts +62 -0
  361. package/template/src/lib/phone.ts +129 -0
  362. package/template/src/lib/places.ts +84 -0
  363. package/template/src/lib/queries.ts +549 -0
  364. package/template/src/lib/revalidate.ts +32 -0
  365. package/template/src/lib/rich-text.ts +215 -0
  366. package/template/src/lib/seo.ts +121 -0
  367. package/template/src/lib/slugify.ts +11 -0
  368. package/template/src/lib/theme.ts +546 -0
  369. package/template/src/lib/utils.ts +2 -0
  370. package/template/src/lib/whatsapp.ts +29 -0
  371. package/template/src/lib/zod-schema/auth.ts +56 -0
  372. package/template/src/lib/zod-schema/page.ts +57 -0
  373. package/template/src/lib/zod-schema/pet-timeline.ts +118 -0
  374. package/template/src/lib/zod-schema/pet.ts +172 -0
  375. package/template/src/lib/zod-schema/settings.ts +162 -0
  376. package/template/src/plugins/host.ts +117 -0
  377. package/template/src/plugins/icon.ts +89 -0
  378. package/template/src/plugins/registry.ts +369 -0
  379. package/template/src/plugins/storage-rules.ts +87 -0
  380. package/template/src/plugins/storage.ts +184 -0
  381. package/template/src/puck/actions.ts +46 -0
  382. package/template/src/puck/config.tsx +1693 -0
  383. package/template/src/puck/data.ts +196 -0
  384. package/template/src/puck/demo-mode.tsx +20 -0
  385. package/template/src/puck/email-config.tsx +267 -0
  386. package/template/src/puck/icons.tsx +76 -0
  387. package/template/src/puck/media-picker.tsx +273 -0
  388. package/template/src/puck/padding.tsx +71 -0
  389. package/template/src/puck/pet-page-config.tsx +511 -0
  390. package/template/src/puck/pet-picker.tsx +40 -0
  391. package/template/src/puck/plugin-block-data.ts +91 -0
  392. package/template/src/puck/plugin-blocks.tsx +235 -0
  393. package/template/src/puck/plugin-choice-field.tsx +87 -0
  394. package/template/src/puck/sanitize.ts +107 -0
  395. package/template/src/puck/server.ts +36 -0
  396. package/template/src/puck/types.ts +41 -0
  397. package/template/src/server/actions/activity.ts +48 -0
  398. package/template/src/server/actions/auth-providers.ts +171 -0
  399. package/template/src/server/actions/auth.ts +217 -0
  400. package/template/src/server/actions/demo.ts +30 -0
  401. package/template/src/server/actions/email-change.ts +80 -0
  402. package/template/src/server/actions/email-templates.ts +144 -0
  403. package/template/src/server/actions/email.ts +70 -0
  404. package/template/src/server/actions/media.ts +127 -0
  405. package/template/src/server/actions/pages.ts +159 -0
  406. package/template/src/server/actions/password-reset.ts +80 -0
  407. package/template/src/server/actions/pet-timeline.ts +75 -0
  408. package/template/src/server/actions/pets.ts +74 -0
  409. package/template/src/server/actions/places.ts +36 -0
  410. package/template/src/server/actions/settings.ts +29 -0
  411. package/template/src/server/actions/setup.ts +72 -0
  412. package/template/src/server/actions/themes.ts +80 -0
  413. package/template/src/server/actions/two-factor.ts +306 -0
  414. package/template/src/server/actions/users.ts +200 -0
  415. package/template/src/server/activity.ts +409 -0
  416. package/template/src/server/auth-errors.ts +17 -0
  417. package/template/src/server/auth-providers.ts +359 -0
  418. package/template/src/server/auth.ts +266 -0
  419. package/template/src/server/avatars.ts +263 -0
  420. package/template/src/server/demo-site.ts +169 -0
  421. package/template/src/server/email-change.ts +278 -0
  422. package/template/src/server/email-templates.ts +350 -0
  423. package/template/src/server/email.ts +442 -0
  424. package/template/src/server/invites.ts +143 -0
  425. package/template/src/server/media-url.ts +20 -0
  426. package/template/src/server/media.ts +236 -0
  427. package/template/src/server/pages.ts +812 -0
  428. package/template/src/server/password-reset.ts +158 -0
  429. package/template/src/server/pending-links.ts +46 -0
  430. package/template/src/server/pet-timeline.ts +181 -0
  431. package/template/src/server/pets.ts +555 -0
  432. package/template/src/server/places.ts +113 -0
  433. package/template/src/server/privacy.ts +21 -0
  434. package/template/src/server/provider-endpoints.ts +94 -0
  435. package/template/src/server/provider-guard.ts +157 -0
  436. package/template/src/server/result.ts +280 -0
  437. package/template/src/server/sample-content.ts +368 -0
  438. package/template/src/server/search-text.ts +43 -0
  439. package/template/src/server/secret-box.ts +38 -0
  440. package/template/src/server/session.ts +154 -0
  441. package/template/src/server/settings.ts +361 -0
  442. package/template/src/server/setup.ts +110 -0
  443. package/template/src/server/sitemap.ts +88 -0
  444. package/template/src/server/storage.ts +267 -0
  445. package/template/src/server/strip-metadata.ts +357 -0
  446. package/template/src/server/themes.ts +195 -0
  447. package/template/src/server/throttle.ts +258 -0
  448. package/template/src/server/two-factor-codes.ts +32 -0
  449. package/template/src/server/two-factor.ts +158 -0
  450. package/template/src/server/types.ts +198 -0
  451. package/template/src/server/uploads.ts +137 -0
  452. package/template/src/server/users.ts +500 -0
  453. package/template/tsconfig.json +44 -0
  454. package/template/ui/components.json +25 -0
  455. package/template/ui/package.json +12 -0
  456. package/template/ui/src/components/alert-dialog.tsx +187 -0
  457. package/template/ui/src/components/avatar.tsx +108 -0
  458. package/template/ui/src/components/badge.tsx +51 -0
  459. package/template/ui/src/components/button.tsx +57 -0
  460. package/template/ui/src/components/card.tsx +102 -0
  461. package/template/ui/src/components/carousel.tsx +245 -0
  462. package/template/ui/src/components/checkbox.tsx +27 -0
  463. package/template/ui/src/components/combobox.tsx +297 -0
  464. package/template/ui/src/components/dialog.tsx +159 -0
  465. package/template/ui/src/components/dropdown-menu.tsx +265 -0
  466. package/template/ui/src/components/field.tsx +238 -0
  467. package/template/ui/src/components/input-group.tsx +158 -0
  468. package/template/ui/src/components/input.tsx +19 -0
  469. package/template/ui/src/components/label.tsx +19 -0
  470. package/template/ui/src/components/pagination.tsx +127 -0
  471. package/template/ui/src/components/popover.tsx +89 -0
  472. package/template/ui/src/components/radio-group.tsx +37 -0
  473. package/template/ui/src/components/select.tsx +200 -0
  474. package/template/ui/src/components/separator.tsx +24 -0
  475. package/template/ui/src/components/sheet.tsx +138 -0
  476. package/template/ui/src/components/sidebar.tsx +723 -0
  477. package/template/ui/src/components/skeleton.tsx +13 -0
  478. package/template/ui/src/components/switch.tsx +31 -0
  479. package/template/ui/src/components/table.tsx +115 -0
  480. package/template/ui/src/components/tabs.tsx +81 -0
  481. package/template/ui/src/components/textarea.tsx +17 -0
  482. package/template/ui/src/components/toggle.tsx +44 -0
  483. package/template/ui/src/components/tooltip.tsx +65 -0
  484. package/template/ui/src/hooks/use-mobile.ts +21 -0
  485. package/template/ui/src/lib/utils.ts +2 -0
  486. package/template/ui/src/styles/globals.css +145 -0
@@ -0,0 +1,812 @@
1
+ // Builder pages. The layout JSON is kept twice: `puckDraft` (what the page builder edits) and
2
+ // `puckPublished` (what visitors see), so saving a draft never changes the live page.
3
+ //
4
+ // Two people (or two tabs) editing the same page would silently overwrite each other, so a save or
5
+ // publish can carry the `version` it was based on (the page's `updatedAt` in milliseconds, which
6
+ // every save returns). If the page has changed since, nothing is written and the person is told to
7
+ // reload. Leave `baseVersion` out to write regardless.
8
+ //
9
+ // History: one version per publish cycle, in `page_versions` (the latest KEEP_VERSIONS kept).
10
+ // The first draft save after a publish opens the next version; later saves update it in place;
11
+ // the next publish closes it. So version N holds the layout published as the Nth release (or, for
12
+ // the newest, the unpublished work since). Any version can be previewed and copied into the draft.
13
+ //
14
+ // Archiving takes a page off the site and makes it read-only, keeping everything (including its
15
+ // address) so it can be restored as it was. Only an archived page can be deleted.
16
+ import type { Config, Data } from '@puckeditor/core'
17
+ import { and, desc, eq, gte, isNotNull, isNull, lt, lte, ne, sql } from 'drizzle-orm'
18
+ import { isEqual } from 'es-toolkit'
19
+
20
+ import { getDatabase, type Db, type Schema } from '@/db/client'
21
+ import type * as S from '@/db/schema/sqlite'
22
+ import { RESERVED_SLUGS } from '@/lib/options'
23
+ import { TAGS } from '@/lib/cache'
24
+ import { safeRevalidate } from '@/lib/revalidate'
25
+ import { sanitizeLayout } from '@/puck/sanitize'
26
+ import { DEFAULT_HOME_DATA, DEFAULT_PET_PAGE_DATA, DEFAULT_PETS_DATA, isPuckData, PET_PAGE_SLUG, isSystemPageSlug, stripControlChars, stripTransient } from '@/puck/data'
27
+
28
+ import { getMediaByIds } from './media'
29
+ import { asRecord, Fields, isUniqueViolation, UserError, ValidationError } from './result'
30
+ import type { MediaItem, Page, PageState, PageStatus, PageVersionSummary } from './types'
31
+
32
+ type PageRow = typeof S.pages.$inferSelect
33
+
34
+ /** The page shown at "/". It always exists (see ensureSystemPages), keeps this slug, and is never archived. */
35
+ export const HOME_SLUG = 'home'
36
+ /** The page shown at "/pets" (the catalogue). Same rules as the homepage. */
37
+ export const PETS_SLUG = 'pets'
38
+
39
+ /** How many snapshots each page keeps. */
40
+ export const KEEP_VERSIONS = 50
41
+
42
+ /**
43
+ * What to refresh when a page changes: its address, or for the Pet page template (no address of its
44
+ * own) every pet's page. The pattern is the route's folder path, route group included: without
45
+ * `(frontend)` it matches no pet page (the `page:pet-page` tag reaches them too).
46
+ */
47
+ const toPath = (slug: string): string | [string, 'page'] =>
48
+ slug === 'home' ? '/' : slug === PET_PAGE_SLUG ? ['/(frontend)/pets/[slug]', 'page'] : `/${slug}`
49
+ /**
50
+ * The cache tags to expire when what visitors see of a page changes (live, offline, renamed): the
51
+ * cached reads of those addresses, and everything that lists live pages (sitemap, privacy policy).
52
+ */
53
+ const pageTags = (...slugs: string[]): string[] => [TAGS.pages, ...new Set(slugs.map(TAGS.page))]
54
+ /** Serialises writes to one page, so version numbers cannot collide. */
55
+ const pageLock = (id: number) => `pages:${id}`
56
+
57
+ const CONFLICT =
58
+ 'This page was changed somewhere else (another tab, or another person) since you opened it. ' +
59
+ 'Reload the page builder to see the latest version, then make your change again.'
60
+ const ARCHIVED = 'This page is archived. Restore it before making changes.'
61
+
62
+ /**
63
+ * A page's settings as one value: what a version keeps and what `details_draft` holds. On a live
64
+ * page, saving the settings form stores them as a draft (visitors keep the old title and address);
65
+ * publishing applies them with the layout. On a page that is not live they are written straight away.
66
+ */
67
+ export type PageDetails = { title: string; slug: string; seoDescription: string | null; seoImageId: number | null }
68
+
69
+ const liveDetails = (row: PageRow): PageDetails => ({
70
+ title: row.title,
71
+ slug: row.slug,
72
+ seoDescription: row.seoDescription ?? null,
73
+ seoImageId: row.seoImageId ?? null,
74
+ })
75
+
76
+ /** Stored details (a version's or the draft's), or null when missing or not the right shape. */
77
+ function asDetails(value: unknown): PageDetails | null {
78
+ if (!value || typeof value !== 'object') return null
79
+ const v = value as Record<string, unknown>
80
+ if (typeof v.title !== 'string' || typeof v.slug !== 'string') return null
81
+ return {
82
+ title: v.title,
83
+ slug: v.slug,
84
+ seoDescription: typeof v.seoDescription === 'string' ? v.seoDescription : null,
85
+ seoImageId: typeof v.seoImageId === 'number' ? v.seoImageId : null,
86
+ }
87
+ }
88
+
89
+ /** The settings the next publish will have: the draft's, or else what is live. */
90
+ const draftOf = (row: PageRow): PageDetails => asDetails(row.detailsDraft) ?? liveDetails(row)
91
+
92
+ /**
93
+ * How to store new settings. A live page keeps showing its published title and address, so they wait
94
+ * in `details_draft` until the next publish (cleared when they match what is live again). A page that
95
+ * is not live has nothing to protect: they are written straight away.
96
+ */
97
+ function draftSettings(current: PageRow, details: PageDetails) {
98
+ if (current.status === 'published') {
99
+ return { detailsDraft: isEqual(details, liveDetails(current)) ? null : details }
100
+ }
101
+ return { title: details.title, slug: details.slug, seoDescription: details.seoDescription, seoImageId: details.seoImageId, detailsDraft: null }
102
+ }
103
+
104
+ /**
105
+ * Another page uses this address already, live or waiting to be published. The unique index only
106
+ * sees live addresses, so pending ones are checked here: two drafts cannot both claim /about.
107
+ */
108
+ async function assertSlugFree(tx: Db, t: Schema, id: number, slug: string, when: 'save' | 'publish' | 'restore') {
109
+ const [live] = await tx.select({ id: t.pages.id }).from(t.pages).where(and(eq(t.pages.slug, slug), ne(t.pages.id, id))).limit(1)
110
+ const pending = live
111
+ ? []
112
+ : await tx.select({ id: t.pages.id, detailsDraft: t.pages.detailsDraft }).from(t.pages).where(and(isNotNull(t.pages.detailsDraft), ne(t.pages.id, id)))
113
+ if (!live && !pending.some((row) => asDetails(row.detailsDraft)?.slug === slug)) return
114
+ if (when === 'save') throw new ValidationError({ slug: 'Another page already uses this address.' })
115
+ throw new UserError(`Another page already uses the address ${toPath(slug)}. Change this page's address before you ${when === 'publish' ? 'publish' : 'restore that version'}.`)
116
+ }
117
+
118
+ /** The image if it still exists, or null (a version or draft may point at one deleted since). */
119
+ async function existingImage(id: number | null): Promise<number | null> {
120
+ return id && (await getMediaByIds([id])).has(id) ? id : null
121
+ }
122
+
123
+ function toPage(row: PageRow, image: MediaItem | null, draftImage: MediaItem | null = null): Page {
124
+ const draft = asDetails(row.detailsDraft)
125
+ return {
126
+ id: row.id,
127
+ title: row.title,
128
+ slug: row.slug,
129
+ status: row.status === 'published' ? 'published' : 'draft',
130
+ puckDraft: row.puckDraft ?? null,
131
+ puckPublished: row.puckPublished ?? null,
132
+ seo: { description: row.seoDescription, image },
133
+ publishedAt: row.publishedAt,
134
+ archivedAt: row.archivedAt ?? null,
135
+ createdAt: row.createdAt,
136
+ updatedAt: row.updatedAt,
137
+ draftDetails: draft ? { title: draft.title, slug: draft.slug, seo: { description: draft.seoDescription, image: draftImage } } : null,
138
+ }
139
+ }
140
+
141
+ async function withImage(row: PageRow | undefined): Promise<Page | null> {
142
+ if (!row) return null
143
+ const draftImageId = asDetails(row.detailsDraft)?.seoImageId ?? null
144
+ const ids = [row.seoImageId, draftImageId].filter((id): id is number => typeof id === 'number')
145
+ const images = ids.length ? await getMediaByIds(ids) : new Map<number, MediaItem>()
146
+ return toPage(row, row.seoImageId ? (images.get(row.seoImageId) ?? null) : null, draftImageId ? (images.get(draftImageId) ?? null) : null)
147
+ }
148
+
149
+ export type PageListItem = Omit<Page, 'puckDraft' | 'puckPublished'> & {
150
+ state: PageState
151
+ hasUnpublishedChanges: boolean
152
+ /** The newest snapshot's number, or 0 when the page has none yet. */
153
+ latestVersion: number
154
+ }
155
+
156
+ export async function listPages(): Promise<PageListItem[]> {
157
+ const { db, t } = await getDatabase()
158
+ const rows = await db.select().from(t.pages).orderBy(desc(t.pages.updatedAt))
159
+ const latest = await db
160
+ .select({ pageId: t.pageVersions.pageId, n: sql<number>`max(${t.pageVersions.number})` })
161
+ .from(t.pageVersions)
162
+ .groupBy(t.pageVersions.pageId)
163
+ const latestOf = new Map(latest.map((r) => [r.pageId, Number(r.n)]))
164
+ return rows.map((row) => {
165
+ // The list leaves the layouts out (they can be large); hasUnpublishedChanges reads them from the row.
166
+ const { puckDraft: _draft, puckPublished: _published, ...page } = toPage(row, null)
167
+ return {
168
+ ...page,
169
+ state: page.archivedAt ? 'archived' : page.status,
170
+ hasUnpublishedChanges: hasUnpublishedChanges(row),
171
+ latestVersion: latestOf.get(row.id) ?? 0,
172
+ }
173
+ })
174
+ }
175
+
176
+ /** The draft differs from what is live: a layout change, or settings waiting to be published. */
177
+ export function hasUnpublishedChanges(row: { puckDraft: unknown; puckPublished: unknown; detailsDraft?: unknown }): boolean {
178
+ return (row.puckDraft != null && !isEqual(row.puckDraft, row.puckPublished ?? null)) || asDetails(row.detailsDraft) !== null
179
+ }
180
+
181
+ /**
182
+ * Refreshes a page's paths and, when the page is the site's privacy policy, every page as well: the
183
+ * footer and the forms link to it by its title and address, and only while it is live.
184
+ */
185
+ async function revalidatePage(id: number, paths: Parameters<typeof safeRevalidate>[0], tags: string[] = []): Promise<void> {
186
+ safeRevalidate(paths, tags)
187
+ const { db, t } = await getDatabase()
188
+ const [settings] = await db.select({ privacyPageId: t.siteSettings.privacyPageId }).from(t.siteSettings).limit(1)
189
+ if (settings?.privacyPageId === id) safeRevalidate([['/', 'layout']])
190
+ }
191
+
192
+ export async function getPageById(id: number): Promise<Page | null> {
193
+ const { db, t } = await getDatabase()
194
+ const [row] = await db.select().from(t.pages).where(eq(t.pages.id, id)).limit(1)
195
+ return withImage(row)
196
+ }
197
+
198
+ /** The published version of a page, or null. Visitors only ever see this, and never an archived page. */
199
+ export async function getPublishedPage(slug: string): Promise<(Page & { puckData: unknown }) | null> {
200
+ const { db, t } = await getDatabase()
201
+ const [row] = await db.select().from(t.pages).where(eq(t.pages.slug, slug)).limit(1)
202
+ if (!row || row.status !== 'published' || row.puckPublished == null || row.archivedAt) return null
203
+ const page = await withImage(row)
204
+ return page && { ...page, puckData: page.puckPublished }
205
+ }
206
+
207
+ /** `ownSlug`: a system page may keep its own address even when that word is reserved ("pets"). */
208
+ function parseDetails(raw: unknown, creating: boolean, ownSlug?: string) {
209
+ const f = new Fields(asRecord(raw), creating)
210
+ const values = {
211
+ title: f.requiredText('title', 120),
212
+ slug: f.slug('slug', { required: true, reserved: RESERVED_SLUGS.filter((word) => word !== ownSlug) }),
213
+ seoDescription: f.text('seoDescription', 200),
214
+ seoImageId: f.id('seoImageId'),
215
+ }
216
+ f.done()
217
+ return values
218
+ }
219
+
220
+ async function assertImage(imageId: number | null | undefined) {
221
+ if (imageId && !(await getMediaByIds([imageId])).has(imageId)) {
222
+ throw new ValidationError({ seoImageId: 'That image no longer exists.' })
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Title, address and share details of a page. The layout is edited with saveDraft/publish. On a live
228
+ * page they are saved as a draft and go live with the next publish (see PageDetails).
229
+ */
230
+ export async function savePageDetails(id: number | null, raw: unknown, opts: { by?: string | null } = {}): Promise<{ id: number; slug: string }> {
231
+ // A system page's own address is allowed for that page only (it is reserved for every other).
232
+ let ownSlug: string | undefined
233
+ if (id !== null) {
234
+ const { db: lookup, t: tables } = await getDatabase()
235
+ const [current] = await lookup.select({ slug: tables.pages.slug }).from(tables.pages).where(eq(tables.pages.id, id)).limit(1)
236
+ if (current && isSystemPageSlug(current.slug)) ownSlug = current.slug
237
+ }
238
+ const values = parseDetails(raw, id === null, ownSlug)
239
+ await assertImage(values.seoImageId)
240
+ const { db, t, withTransaction } = await getDatabase()
241
+ const defined = Object.fromEntries(Object.entries(values).filter(([, v]) => v !== undefined)) as Partial<PageDetails>
242
+ try {
243
+ if (id === null) {
244
+ // The unique index covers live addresses; this also covers ones waiting to be published.
245
+ if (defined.slug) await assertSlugFree(db, t, 0, defined.slug, 'save')
246
+ const [row] = await db
247
+ .insert(t.pages)
248
+ .values(defined as unknown as typeof t.pages.$inferInsert)
249
+ .returning({ id: t.pages.id, slug: t.pages.slug })
250
+ safeRevalidate([toPath(row.slug)], pageTags(row.slug))
251
+ return row
252
+ }
253
+ const result = await withTransaction(
254
+ async (tx) => {
255
+ const [before] = await tx.select().from(t.pages).where(eq(t.pages.id, id)).limit(1)
256
+ if (!before) throw new UserError('Page not found.')
257
+ if (before.archivedAt) throw new UserError(ARCHIVED)
258
+ if (isSystemPageSlug(before.slug) && defined.slug !== undefined && defined.slug !== before.slug) {
259
+ throw new ValidationError({ slug: `This page keeps the address "${before.slug}".` })
260
+ }
261
+ const details: PageDetails = { ...draftOf(before), ...defined }
262
+ if (details.slug !== before.slug) await assertSlugFree(tx, t, id, details.slug, 'save')
263
+ const [row] = await tx
264
+ .update(t.pages)
265
+ .set({ ...draftSettings(before, details), updatedAt: new Date() })
266
+ .where(and(eq(t.pages.id, id), isNull(t.pages.archivedAt)))
267
+ .returning()
268
+ // Deleted or archived by someone else between the lookup and the update.
269
+ if (!row) throw new UserError('Page not found.')
270
+ // The history records settings too: a change opens (or updates) the draft version.
271
+ if (row.puckDraft != null) {
272
+ const draft = draftOf(row)
273
+ await saveOpenVersion(tx, t, { pageId: id, title: draft.title, data: row.puckDraft, details: draft, by: opts.by })
274
+ }
275
+ // A live page keeps its live columns (the settings wait in details_draft); any other page
276
+ // has its title and address written now.
277
+ return { id: row.id, slug: row.slug, previousSlug: before.slug, wroteLive: before.status !== 'published' }
278
+ },
279
+ { lock: pageLock(id) },
280
+ )
281
+ await revalidatePage(id, [toPath(result.slug), toPath(result.previousSlug)], result.wroteLive ? pageTags(result.slug, result.previousSlug) : [])
282
+ return { id: result.id, slug: result.slug }
283
+ } catch (error) {
284
+ if (isUniqueViolation(error)) throw new ValidationError({ slug: 'Another page already uses this address.' })
285
+ throw error
286
+ }
287
+ }
288
+
289
+ /**
290
+ * The `updatedAt` a save writes. A version is that time in milliseconds, so two saves in the same
291
+ * millisecond would share one and a stale save would slip through; making each version strictly
292
+ * greater than the one it was based on rules that out.
293
+ */
294
+ function nextVersion(baseVersion?: number): Date {
295
+ return new Date(Math.max(Date.now(), (baseVersion ?? 0) + 1))
296
+ }
297
+
298
+ /**
299
+ * Matches rows whose `updatedAt` is the given version, to the millisecond. Not an exact equality:
300
+ * PostgreSQL fills a new row's timestamp from its own clock with microseconds (.123456), while a
301
+ * version is milliseconds (.123), so `=` would reject the first save of every new page.
302
+ */
303
+ function atVersion(t: { pages: { updatedAt: Parameters<typeof gte>[0] } }, version: number) {
304
+ return and(gte(t.pages.updatedAt, new Date(version)), lt(t.pages.updatedAt, new Date(version + 1)))
305
+ }
306
+
307
+ /** Every block the builders know: the page blocks and the Pet page template's own. */
308
+ let allBlocks: Promise<Config> | null = null
309
+ function blockConfig(): Promise<Config> {
310
+ // Loaded on first use: the block files import the pickers, which import this module's actions.
311
+ allBlocks ??= Promise.all([import('@/puck/config'), import('@/puck/pet-page-config')]).then(
312
+ ([pages, pet]) => ({ components: { ...pages.config.components, ...pet.petPageConfig.components } }) as unknown as Config,
313
+ )
314
+ return allBlocks
315
+ }
316
+
317
+ async function cleanLayout(data: unknown) {
318
+ // Render-only props (such as PetGrid's `pets`) must never be saved, whatever the save path.
319
+ if (!isPuckData(data)) throw new UserError('The page data looks invalid, so nothing was saved.')
320
+ // A NUL anywhere in the JSON makes PostgreSQL refuse the whole save. Then every block's options
321
+ // are checked against its fields (src/puck/sanitize.ts): a value of the wrong kind would stop the
322
+ // page from drawing, and a made-up choice would end up in a class name.
323
+ return sanitizeLayout(stripTransient(stripControlChars(data)), await blockConfig())
324
+ }
325
+
326
+ /** Why a guarded update matched nothing: gone, archived, or changed by someone else. */
327
+ async function explainMiss(tx: Db, t: Schema, id: number, opts: { needsDraft?: boolean } = {}): Promise<never> {
328
+ const [page] = await tx
329
+ .select({ draft: t.pages.puckDraft, archivedAt: t.pages.archivedAt })
330
+ .from(t.pages)
331
+ .where(eq(t.pages.id, id))
332
+ .limit(1)
333
+ if (!page) throw new UserError('Page not found.')
334
+ if (page.archivedAt) throw new UserError(ARCHIVED)
335
+ if (opts.needsDraft && page.draft == null) throw new UserError('This page has no layout yet. Open the page builder first.')
336
+ throw new UserError(CONFLICT)
337
+ }
338
+
339
+ type VersionInput = { pageId: number; title: string; data: unknown; details: PageDetails; by?: string | null }
340
+
341
+ async function latestVersion(tx: Db, t: Schema, pageId: number) {
342
+ const [latest] = await tx
343
+ .select({ number: t.pageVersions.number, kind: t.pageVersions.kind, data: t.pageVersions.data, details: t.pageVersions.details })
344
+ .from(t.pageVersions)
345
+ .where(eq(t.pageVersions.pageId, pageId))
346
+ .orderBy(desc(t.pageVersions.number))
347
+ .limit(1)
348
+ return latest
349
+ }
350
+
351
+ /**
352
+ * A version already holds this layout and these settings. isEqual ignores key order (PostgreSQL's
353
+ * jsonb hands objects back with their keys re-sorted). A version saved before settings were kept
354
+ * has none, so it never matches: the first save after the upgrade records them once.
355
+ */
356
+ const sameVersion = (latest: { data: unknown; details: unknown }, input: VersionInput) =>
357
+ isEqual(latest.data, input.data) && isEqual(asDetails(latest.details), input.details)
358
+
359
+ async function trimVersions(tx: Db, t: Schema, pageId: number, newest: number) {
360
+ await tx
361
+ .delete(t.pageVersions)
362
+ .where(and(eq(t.pageVersions.pageId, pageId), lte(t.pageVersions.number, newest - KEEP_VERSIONS)))
363
+ }
364
+
365
+ /**
366
+ * A draft save: updates the open (unpublished) version, or opens the next one after a publish.
367
+ * Nothing is opened while the layout is still what was last published. Returns the open version's
368
+ * number, or null when there is none. `restoredFrom` marks a restore from that version;
369
+ * a plain save leaves an earlier mark alone.
370
+ */
371
+ async function saveOpenVersion(
372
+ tx: Db,
373
+ t: Schema,
374
+ input: VersionInput & {
375
+ restoredFrom?: number
376
+ /**
377
+ * Always start a new version, leaving an open draft as it is (a restore: the unpublished work in
378
+ * it stays in the history instead of being overwritten).
379
+ */
380
+ newVersion?: boolean
381
+ },
382
+ ): Promise<number | null> {
383
+ const latest = await latestVersion(tx, t, input.pageId)
384
+ const now = new Date()
385
+ if (latest?.kind === 'draft' && !input.newVersion) {
386
+ await tx
387
+ .update(t.pageVersions)
388
+ .set({
389
+ title: input.title,
390
+ data: input.data as never,
391
+ details: input.details as never,
392
+ createdBy: input.by ?? null,
393
+ updatedAt: now,
394
+ ...(input.restoredFrom !== undefined ? { restoredFrom: input.restoredFrom } : {}),
395
+ })
396
+ .where(and(eq(t.pageVersions.pageId, input.pageId), eq(t.pageVersions.number, latest.number)))
397
+ return latest.number
398
+ }
399
+ // isEqual ignores key order: PostgreSQL's jsonb hands objects back with their keys re-sorted.
400
+ if (latest && sameVersion(latest, input)) return null
401
+ const number = (latest?.number ?? 0) + 1
402
+ await tx.insert(t.pageVersions).values({
403
+ pageId: input.pageId,
404
+ number,
405
+ kind: 'draft',
406
+ title: input.title,
407
+ data: input.data as never,
408
+ details: input.details as never,
409
+ createdBy: input.by ?? null,
410
+ restoredFrom: input.restoredFrom ?? null,
411
+ createdAt: now,
412
+ updatedAt: now,
413
+ })
414
+ await trimVersions(tx, t, input.pageId, number)
415
+ return number
416
+ }
417
+
418
+ /**
419
+ * A publish: closes the open version with what went live. With no open version, a new published
420
+ * version is added, unless the layout is the same as the last one published (a re-publish).
421
+ */
422
+ async function closeVersion(tx: Db, t: Schema, input: VersionInput): Promise<void> {
423
+ const latest = await latestVersion(tx, t, input.pageId)
424
+ const now = new Date()
425
+ if (latest?.kind === 'draft') {
426
+ await tx
427
+ .update(t.pageVersions)
428
+ .set({ kind: 'published', title: input.title, data: input.data as never, details: input.details as never, createdBy: input.by ?? null, updatedAt: now })
429
+ .where(and(eq(t.pageVersions.pageId, input.pageId), eq(t.pageVersions.number, latest.number)))
430
+ return
431
+ }
432
+ if (latest && sameVersion(latest, input)) return
433
+ const number = (latest?.number ?? 0) + 1
434
+ await tx.insert(t.pageVersions).values({
435
+ pageId: input.pageId,
436
+ number,
437
+ kind: 'published',
438
+ title: input.title,
439
+ data: input.data as never,
440
+ details: input.details as never,
441
+ createdBy: input.by ?? null,
442
+ createdAt: now,
443
+ updatedAt: now,
444
+ })
445
+ await trimVersions(tx, t, input.pageId, number)
446
+ }
447
+
448
+ export type SaveOptions = { baseVersion?: number; by?: string | null }
449
+
450
+ export async function saveDraft(id: number, data: unknown, baseVersion?: number, by?: string | null): Promise<{ version: number }> {
451
+ const layout = await cleanLayout(data)
452
+ const { t, withTransaction } = await getDatabase()
453
+ const now = nextVersion(baseVersion)
454
+ return withTransaction(
455
+ async (tx) => {
456
+ // With a base version the update only matches if nobody has changed the page since.
457
+ const where = and(eq(t.pages.id, id), isNull(t.pages.archivedAt), baseVersion === undefined ? undefined : atVersion(t, baseVersion))
458
+ const [row] = await tx.update(t.pages).set({ puckDraft: layout, updatedAt: now }).where(where).returning()
459
+ if (!row) return explainMiss(tx, t, id)
460
+ const details = draftOf(row)
461
+ await saveOpenVersion(tx, t, { pageId: id, title: details.title, data: layout, details, by })
462
+ return { version: now.getTime() }
463
+ },
464
+ { lock: pageLock(id) },
465
+ )
466
+ }
467
+
468
+ /**
469
+ * Makes the draft the live page. With `data`, that layout is saved as the draft first (in the same
470
+ * statement). Without it, the draft already stored is copied across inside the database, so a draft
471
+ * saved at the same moment cannot be overwritten by an older copy read earlier.
472
+ */
473
+ export async function publishPage(
474
+ id: number,
475
+ data?: unknown,
476
+ baseVersion?: number,
477
+ by?: string | null,
478
+ ): Promise<{ slug: string; version: number }> {
479
+ const { t, withTransaction } = await getDatabase()
480
+ const layout = data !== undefined ? await cleanLayout(data) : undefined
481
+ const now = nextVersion(baseVersion)
482
+ const set = layout !== undefined ? { puckDraft: layout, puckPublished: layout } : { puckPublished: sql`${t.pages.puckDraft}` }
483
+ const result = await withTransaction(
484
+ async (tx) => {
485
+ // Settings saved since the last publish go live with the layout (a new address included).
486
+ const [before] = await tx.select({ slug: t.pages.slug, detailsDraft: t.pages.detailsDraft }).from(t.pages).where(eq(t.pages.id, id)).limit(1)
487
+ const pending = asDetails(before?.detailsDraft)
488
+ if (pending && pending.slug !== before!.slug) await assertSlugFree(tx, t, id, pending.slug, 'publish')
489
+ const details = pending
490
+ ? { title: pending.title, slug: pending.slug, seoDescription: pending.seoDescription, seoImageId: await existingImage(pending.seoImageId), detailsDraft: null }
491
+ : {}
492
+ const where = and(
493
+ eq(t.pages.id, id),
494
+ isNull(t.pages.archivedAt),
495
+ baseVersion === undefined ? undefined : atVersion(t, baseVersion),
496
+ layout === undefined ? isNotNull(t.pages.puckDraft) : undefined,
497
+ )
498
+ const [row] = await tx
499
+ .update(t.pages)
500
+ .set({ ...set, ...details, status: 'published' as PageStatus, publishedAt: now, updatedAt: now } as never)
501
+ .where(where)
502
+ .returning()
503
+ if (!row) return explainMiss(tx, t, id, { needsDraft: layout === undefined })
504
+ await closeVersion(tx, t, { pageId: id, title: row.title, data: row.puckPublished, details: liveDetails(row), by })
505
+ return { slug: row.slug, previousSlug: before?.slug ?? row.slug, version: now.getTime() }
506
+ },
507
+ { lock: pageLock(id) },
508
+ )
509
+ // A new address: the old one stops showing the page, so refresh both.
510
+ await revalidatePage(id, [toPath(result.slug), toPath(result.previousSlug)], pageTags(result.slug, result.previousSlug))
511
+ return { slug: result.slug, version: result.version }
512
+ }
513
+
514
+ /** Takes the page offline. The draft is kept. */
515
+ export async function unpublishPage(id: number): Promise<void> {
516
+ const { db, t } = await getDatabase()
517
+ const [row] = await db
518
+ .update(t.pages)
519
+ .set({ puckPublished: null, status: 'draft' as PageStatus, publishedAt: null, updatedAt: new Date() })
520
+ // An archived page is read-only (and already off the site).
521
+ .where(and(eq(t.pages.id, id), isNull(t.pages.archivedAt)))
522
+ .returning({ slug: t.pages.slug })
523
+ if (!row) {
524
+ const [page] = await db.select({ id: t.pages.id }).from(t.pages).where(eq(t.pages.id, id)).limit(1)
525
+ throw new UserError(page ? ARCHIVED : 'Page not found.')
526
+ }
527
+ await revalidatePage(id, [toPath(row.slug)], pageTags(row.slug))
528
+ }
529
+
530
+ /** Takes the page off the site and makes it read-only. Everything is kept for a restore. */
531
+ export async function archivePage(id: number): Promise<void> {
532
+ const { db, t } = await getDatabase()
533
+ await assertNotSystem(id, 'archived')
534
+ const now = new Date()
535
+ const [row] = await db
536
+ .update(t.pages)
537
+ .set({ archivedAt: now, updatedAt: now })
538
+ .where(and(eq(t.pages.id, id), isNull(t.pages.archivedAt)))
539
+ .returning({ slug: t.pages.slug })
540
+ if (!row) {
541
+ const [page] = await db.select({ id: t.pages.id }).from(t.pages).where(eq(t.pages.id, id)).limit(1)
542
+ if (!page) throw new UserError('Page not found.')
543
+ return // Already archived.
544
+ }
545
+ await revalidatePage(id, [toPath(row.slug)], pageTags(row.slug))
546
+ }
547
+
548
+ /**
549
+ * Brings an archived page back exactly as it was (a published page is live again). Refuses a page
550
+ * that is not archived, so a second click changes nothing (an open builder keeps its version).
551
+ */
552
+ export async function restorePage(id: number): Promise<void> {
553
+ const { db, t } = await getDatabase()
554
+ const [row] = await db
555
+ .update(t.pages)
556
+ .set({ archivedAt: null, updatedAt: new Date() })
557
+ .where(and(eq(t.pages.id, id), isNotNull(t.pages.archivedAt)))
558
+ .returning({ slug: t.pages.slug })
559
+ if (!row) {
560
+ const [page] = await db.select({ id: t.pages.id }).from(t.pages).where(eq(t.pages.id, id)).limit(1)
561
+ throw new UserError(page ? 'This page is not archived.' : 'Page not found.')
562
+ }
563
+ await revalidatePage(id, [toPath(row.slug)], pageTags(row.slug))
564
+ }
565
+
566
+ /** Deletes a page and its history for good. Only an archived page can be deleted. */
567
+ export async function deletePage(id: number): Promise<void> {
568
+ const { db, t } = await getDatabase()
569
+ await assertNotSystem(id, 'deleted')
570
+ const [row] = await db
571
+ .delete(t.pages)
572
+ .where(and(eq(t.pages.id, id), isNotNull(t.pages.archivedAt)))
573
+ .returning({ slug: t.pages.slug })
574
+ if (!row) {
575
+ const [page] = await db.select({ id: t.pages.id }).from(t.pages).where(eq(t.pages.id, id)).limit(1)
576
+ throw new UserError(page ? 'Archive the page before deleting it.' : 'Page not found.')
577
+ }
578
+ // settings too: a deleted privacy policy page clears site_settings.privacy_page_id (ON DELETE SET NULL).
579
+ safeRevalidate([toPath(row.slug)], [...pageTags(row.slug), TAGS.settings])
580
+ }
581
+
582
+ /** A page's versions, newest first, without their layouts. */
583
+ export async function listPageVersions(pageId: number): Promise<PageVersionSummary[]> {
584
+ const { db, t } = await getDatabase()
585
+ const rows = await db
586
+ .select({
587
+ number: t.pageVersions.number,
588
+ kind: t.pageVersions.kind,
589
+ title: t.pageVersions.title,
590
+ createdAt: t.pageVersions.createdAt,
591
+ updatedAt: t.pageVersions.updatedAt,
592
+ restoredFrom: t.pageVersions.restoredFrom,
593
+ createdBy: t.users.name,
594
+ })
595
+ .from(t.pageVersions)
596
+ .leftJoin(t.users, eq(t.users.id, t.pageVersions.createdBy))
597
+ .where(eq(t.pageVersions.pageId, pageId))
598
+ .orderBy(desc(t.pageVersions.number))
599
+ return rows.map((r) => ({
600
+ ...r,
601
+ kind: r.kind === 'published' ? ('published' as const) : ('draft' as const),
602
+ restoredFrom: r.restoredFrom ?? null,
603
+ createdBy: r.createdBy ?? null,
604
+ }))
605
+ }
606
+
607
+ /** The layout of one snapshot, for the preview. */
608
+ export async function getPageVersionData(pageId: number, number: number): Promise<unknown | null> {
609
+ const { db, t } = await getDatabase()
610
+ const [row] = await db
611
+ .select({ data: t.pageVersions.data })
612
+ .from(t.pageVersions)
613
+ .where(and(eq(t.pageVersions.pageId, pageId), eq(t.pageVersions.number, number)))
614
+ .limit(1)
615
+ return row?.data ?? null
616
+ }
617
+
618
+ /**
619
+ * Restore: copies a version's layout into the draft as a NEW version that remembers where it came
620
+ * from (the live page is not touched; publish to make it live, or use restoreAndPublishPageVersion).
621
+ * History is never rewritten: an open draft with unpublished work stays as its own version. Returns
622
+ * the new version's number (the latest version's, when the layout is what is already published).
623
+ * Takes the same `baseVersion` as saveDraft.
624
+ */
625
+ export async function restorePageVersion(
626
+ pageId: number,
627
+ number: number,
628
+ opts: SaveOptions = {},
629
+ ): Promise<{ version: number; number: number }> {
630
+ const { t, withTransaction } = await getDatabase()
631
+ const now = nextVersion(opts.baseVersion)
632
+ return withTransaction(
633
+ async (tx) => {
634
+ const [snapshot] = await tx
635
+ .select({ data: t.pageVersions.data, kind: t.pageVersions.kind, details: t.pageVersions.details })
636
+ .from(t.pageVersions)
637
+ .where(and(eq(t.pageVersions.pageId, pageId), eq(t.pageVersions.number, number)))
638
+ .limit(1)
639
+ if (!snapshot) throw new UserError('That version no longer exists.')
640
+ if (snapshot.kind === 'draft') {
641
+ const latest = await latestVersion(tx, t, pageId)
642
+ if (latest?.number === number) throw new UserError('That version is already the draft.')
643
+ }
644
+ const where = and(
645
+ eq(t.pages.id, pageId),
646
+ isNull(t.pages.archivedAt),
647
+ opts.baseVersion === undefined ? undefined : atVersion(t, opts.baseVersion),
648
+ )
649
+ // The version's settings come back with its layout (versions saved before settings were kept
650
+ // have none, and leave the current settings as they are).
651
+ const [current] = await tx.select().from(t.pages).where(where).limit(1)
652
+ if (!current) return explainMiss(tx, t, pageId)
653
+ let settings = {}
654
+ const restored = asDetails(snapshot.details)
655
+ if (restored) {
656
+ // A system page keeps its address whatever an old version says.
657
+ const details: PageDetails = {
658
+ ...restored,
659
+ slug: isSystemPageSlug(current.slug) ? current.slug : restored.slug,
660
+ seoImageId: await existingImage(restored.seoImageId),
661
+ }
662
+ if (details.slug !== current.slug) await assertSlugFree(tx, t, pageId, details.slug, 'restore')
663
+ settings = draftSettings(current, details)
664
+ }
665
+ const [row] = await tx
666
+ .update(t.pages)
667
+ .set({ puckDraft: snapshot.data, ...settings, updatedAt: now })
668
+ .where(where)
669
+ .returning()
670
+ if (!row) return explainMiss(tx, t, pageId)
671
+ const details = draftOf(row)
672
+ const open = await saveOpenVersion(tx, t, { pageId, title: details.title, data: snapshot.data, details, by: opts.by, restoredFrom: number, newVersion: true })
673
+ const latest = open ?? (await latestVersion(tx, t, pageId))?.number ?? number
674
+ return { version: now.getTime(), number: latest }
675
+ },
676
+ { lock: pageLock(pageId) },
677
+ )
678
+ }
679
+
680
+ /**
681
+ * Restore and publish in one step, for rolling a broken live page back quickly. Restoring copies the
682
+ * old version into the draft as a new version (nothing in the history is removed or renumbered), and
683
+ * publishing then makes that draft live. One transaction: if publishing fails, the restore is undone.
684
+ */
685
+ export async function restoreAndPublishPageVersion(
686
+ pageId: number,
687
+ number: number,
688
+ opts: SaveOptions = {},
689
+ ): Promise<{ version: number; number: number }> {
690
+ const { withTransaction } = await getDatabase()
691
+ return withTransaction(
692
+ async () => {
693
+ const restored = await restorePageVersion(pageId, number, opts)
694
+ const published = await publishPage(pageId, undefined, restored.version, opts.by)
695
+ return { version: published.version, number: restored.number }
696
+ },
697
+ { lock: pageLock(pageId) },
698
+ )
699
+ }
700
+
701
+ async function assertNotSystem(id: number, verb: 'archived' | 'deleted') {
702
+ const { db, t } = await getDatabase()
703
+ const [row] = await db.select({ slug: t.pages.slug }).from(t.pages).where(eq(t.pages.id, id)).limit(1)
704
+ const def = row ? SYSTEM_PAGES.find((page) => page.slug === row.slug) : undefined
705
+ if (!def) return
706
+ throw new UserError(
707
+ verb === 'archived'
708
+ ? `${def.label} cannot be archived. Unpublish it to show the built-in ${def.fallback} instead.`
709
+ : `${def.label} cannot be deleted.`,
710
+ )
711
+ }
712
+
713
+ /** The homepage's id. ensureSystemPages keeps it there. */
714
+ export const HOME_ID = 1
715
+ /** The Pets page's id. */
716
+ export const PETS_ID = 2
717
+ /** The Pet page template's id. */
718
+ export const PET_PAGE_ID = 3
719
+
720
+ type SystemPage = { slug: string; id: number; title: string; data: Data; path: string; label: string; fallback: string }
721
+
722
+ /** In order: the homepage is placed first, so it can never be the page that moves out of the way. */
723
+ const SYSTEM_PAGES: SystemPage[] = [
724
+ { slug: HOME_SLUG, id: HOME_ID, title: 'Home', data: DEFAULT_HOME_DATA, path: '/', label: 'The homepage', fallback: 'homepage' },
725
+ { slug: PETS_SLUG, id: PETS_ID, title: 'Adoptable pets', data: DEFAULT_PETS_DATA, path: '/pets', label: 'The Pets page', fallback: 'catalogue' },
726
+ { slug: PET_PAGE_SLUG, id: PET_PAGE_ID, title: 'Pet page', data: DEFAULT_PET_PAGE_DATA, path: '/pets', label: 'The Pet page template', fallback: 'pet page layout' },
727
+ ]
728
+
729
+ /**
730
+ * Makes sure a system page exists at its fixed id, so it is listed, edited, versioned and previewed
731
+ * like any other page, in a fixed place.
732
+ *
733
+ * - Missing: it is created from its built-in layout, published, with that layout as version 1, so
734
+ * its address looks exactly as before.
735
+ * - Under another id (a site set up before this rule): it swaps ids with the page on its id. When
736
+ * it is missing, a page on its id moves to the next free id. Versions follow
737
+ * (page_versions.page_id is ON UPDATE CASCADE), and the id counter is moved past the highest id.
738
+ * - The other system pages are never moved out of the way (they come first in SYSTEM_PAGES).
739
+ *
740
+ * Cheap when everything is in place (one query). Two calls at once are serialised by a lock.
741
+ */
742
+ async function ensureSystemPage(def: SystemPage): Promise<'created' | 'moved' | 'exists'> {
743
+ const { db, t, dialect, withTransaction } = await getDatabase()
744
+ const [current] = await db.select({ id: t.pages.id }).from(t.pages).where(eq(t.pages.slug, def.slug)).limit(1)
745
+ if (current?.id === def.id) return 'exists'
746
+
747
+ const layout = await cleanLayout(def.data)
748
+ const result = await withTransaction(
749
+ async (tx) => {
750
+ const [page] = await tx.select({ id: t.pages.id }).from(t.pages).where(eq(t.pages.slug, def.slug)).limit(1)
751
+ if (page?.id === def.id) return 'exists' as const
752
+
753
+ const [occupant] = await tx.select({ id: t.pages.id, slug: t.pages.slug }).from(t.pages).where(eq(t.pages.id, def.id)).limit(1)
754
+ if (occupant && isSystemPageSlug(occupant.slug)) {
755
+ throw new Error(`Page id ${def.id} belongs to the system page "${occupant.slug}"; not moving it.`)
756
+ }
757
+ const [{ max }] = await tx.select({ max: sql<number>`max(${t.pages.id})` }).from(t.pages)
758
+ const spare = Number(max ?? 0) + 1
759
+
760
+ if (page) {
761
+ // Swap: this page takes its id and the page that had it takes this page's old id
762
+ // (through a spare id, since ids are unique at every step).
763
+ await tx.update(t.pages).set({ id: spare }).where(eq(t.pages.id, page.id))
764
+ if (occupant) await tx.update(t.pages).set({ id: page.id }).where(eq(t.pages.id, def.id))
765
+ await tx.update(t.pages).set({ id: def.id }).where(eq(t.pages.id, spare))
766
+ } else {
767
+ // Free the id: whatever page holds it moves to the end.
768
+ if (occupant) await tx.update(t.pages).set({ id: spare }).where(eq(t.pages.id, def.id))
769
+ const now = new Date()
770
+ await tx.insert(t.pages).values({
771
+ id: def.id,
772
+ title: def.title,
773
+ slug: def.slug,
774
+ status: 'published',
775
+ puckDraft: layout,
776
+ puckPublished: layout,
777
+ publishedAt: now,
778
+ createdAt: now,
779
+ updatedAt: now,
780
+ } as never)
781
+ await closeVersion(tx, t, { pageId: def.id, title: def.title, data: layout, details: { title: def.title, slug: def.slug, seoDescription: null, seoImageId: null } })
782
+ }
783
+
784
+ // Explicit ids do not move the id counter, so the next new page could collide: move it past
785
+ // the highest id. (SQLite's AUTOINCREMENT keeps its counter in sqlite_sequence.)
786
+ if (dialect === 'pg') {
787
+ await (tx as unknown as { execute: (q: unknown) => Promise<unknown> }).execute(
788
+ sql`select setval(pg_get_serial_sequence('pages', 'id'), (select max(id) from pages))`,
789
+ )
790
+ } else {
791
+ await tx.run(sql`update sqlite_sequence set seq = (select max(id) from pages) where name = 'pages' and seq < (select max(id) from pages)`)
792
+ }
793
+ return page ? ('moved' as const) : ('created' as const)
794
+ },
795
+ { lock: 'pages:system' },
796
+ )
797
+ // settings too: a page moved off this id may be the privacy policy (privacy_page_id follows it, ON UPDATE CASCADE).
798
+ if (result !== 'exists') safeRevalidate([def.path], [...pageTags(def.slug), TAGS.settings])
799
+ return result
800
+ }
801
+
802
+ /** The homepage at id 1 (see ensureSystemPage). */
803
+ export const ensureHomePage = () => ensureSystemPage(SYSTEM_PAGES[0])
804
+ /** The Pets page at id 2 (see ensureSystemPage). */
805
+ export const ensurePetsPage = () => ensureSystemPage(SYSTEM_PAGES[1])
806
+ /** The Pet page template at id 3 (see ensureSystemPage). */
807
+ export const ensurePetPageTemplate = () => ensureSystemPage(SYSTEM_PAGES[2])
808
+
809
+ /** Every system page, in order. Runs on start, in the seed, and when the pages list loads. */
810
+ export async function ensureSystemPages(): Promise<void> {
811
+ for (const def of SYSTEM_PAGES) await ensureSystemPage(def)
812
+ }