create-pet-adopt 0.0.0-stage → 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 +119 -2
  3. package/index.js +920 -0
  4. package/package.json +40 -3
  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
package/index.js ADDED
@@ -0,0 +1,920 @@
1
+ #!/usr/bin/env node
2
+ // create-pet-adopt: starts a new Pet Adopt site in a new folder, and updates one later.
3
+ //
4
+ // pnpm create pet-adopt my-shelter a new site
5
+ // pnpm pet-adopt:update in a site: move it to this package's release
6
+ // (the script runs `pnpm dlx create-pet-adopt@latest update`)
7
+ //
8
+ // The files of a site travel inside this package (the `template` folder, built from the project
9
+ // by scripts/build-template.mjs when the package is packed), so create-pet-adopt@X.Y.Z always
10
+ // gives the X.Y.Z files.
11
+ //
12
+ // create: copies them, writes .env with a new secret, installs the packages and starts a git
13
+ // repository whose history is one commit. It changes nothing outside the new folder.
14
+ //
15
+ // update: compares the site with the release it was made from (the hashes in
16
+ // .pet-adopt/template.json) and with this package's template, file by file. Files the site never
17
+ // changed are replaced, files only the site changed are kept, and files both changed are merged
18
+ // with `git merge-file`. It never commits, stages or stashes: the changes are left in the working
19
+ // tree for the site's owner to review.
20
+ //
21
+ // No dependencies: plain Node, with its own reader for packed packages (.tgz).
22
+ import { spawnSync } from 'node:child_process'
23
+ import { createHash } from 'node:crypto'
24
+ import { copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
25
+ import os from 'node:os'
26
+ import path from 'node:path'
27
+ import { createInterface } from 'node:readline/promises'
28
+ import { gunzipSync } from 'node:zlib'
29
+
30
+ const PROJECT_URL = 'https://github.com/muhammadarifftaha/pet-adopt'
31
+ const DOCS_URL = 'https://pet-adopt.dev/docs'
32
+ const TEMPLATE = path.join(import.meta.dirname, 'template')
33
+ const MANIFEST = '.pet-adopt/template.json'
34
+ const DATABASES = /** @type {const} */ (['sqlite', 'postgres'])
35
+ const POSTGRES_URL = 'postgres://postgres:postgres@localhost:5432/pet_adopt'
36
+ const SDK = '@pet-adopt/plugin-sdk'
37
+ // Written out in full: the repository's check of add-a-plugin instructions reads this line too.
38
+ const ADD_A_PLUGIN = 'pnpm add @pet-adopt/plugin-form-builder@latest @pet-adopt/plugin-sdk@latest'
39
+ const BIG = 256 * 1024 * 1024
40
+
41
+ const HELP = `Start a new Pet Adopt site, or update one.
42
+
43
+ pnpm create pet-adopt [folder] [options] a new site in a new folder
44
+ pnpm pet-adopt:update [options] in a site: update it (see "update --help")
45
+
46
+ Options
47
+ --db <sqlite|postgres> The database for local development (default: sqlite)
48
+ --no-install Do not run "pnpm install"
49
+ --no-git Do not start a git repository
50
+ -y, --yes Take the default for anything not given
51
+ -h, --help Show this
52
+
53
+ For testing before a release
54
+ --packages <folder> Take the @pet-adopt packages from the .tgz files in this folder
55
+ (made with "pnpm pack") and not from npm
56
+ `
57
+
58
+ const UPDATE_HELP = `Update a Pet Adopt site to the release this create-pet-adopt holds.
59
+
60
+ pnpm pet-adopt:update [options]
61
+ pnpm dlx create-pet-adopt@latest update [options] the same thing
62
+ pnpm dlx create-pet-adopt@X.Y.Z update to one release, not the latest
63
+
64
+ Run it in the site's folder, with nothing uncommitted. Files you never changed are replaced,
65
+ files only you changed are kept, files both changed are merged (conflicts are marked in the
66
+ file). .env, pet-adopt.config.ts and pet-adopt.blocks.ts are never touched. Nothing is
67
+ committed: review with "git status" and "git diff", then commit.
68
+
69
+ Options
70
+ --dry-run Say what would change; write nothing
71
+ --no-install Do not run "pnpm install" afterwards
72
+ --base <folder|.tgz> Where the files of the site's current release are: a create-pet-adopt
73
+ package (a .tgz from "npm pack", or its folder). Without it they are
74
+ downloaded from npm, and only when a file needs merging
75
+ -h, --help Show this
76
+
77
+ Exit code: 0 when done, 2 when a conflict was left for you to resolve (with --dry-run: when
78
+ one would be), 1 when the update was refused and nothing was changed, 3 when it stopped part of the way or
79
+ pnpm install failed (the output says how to go on).
80
+ `
81
+
82
+ /** @param {string} message @param {number} [code] @returns {never} */
83
+ function stop(message, code = 1) {
84
+ console.error(`\n${message}`)
85
+ process.exit(code)
86
+ }
87
+
88
+ /**
89
+ * Runs a program and returns what it printed. Arguments are passed as a list, never through a
90
+ * shell, so a folder name cannot be read as a command. (pnpm and npm on Windows are .cmd files,
91
+ * which only a shell can start; their arguments here are fixed words.)
92
+ * @param {string} command @param {string[]} args @param {{ cwd?: string, show?: boolean, input?: string }} [options]
93
+ */
94
+ function run(command, args, { cwd, show = false, input } = {}) {
95
+ const result = spawnSync(command, args, {
96
+ cwd,
97
+ encoding: 'utf8',
98
+ input,
99
+ maxBuffer: BIG,
100
+ stdio: show ? 'inherit' : [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
101
+ shell: process.platform === 'win32' && (command === 'pnpm' || command === 'npm'),
102
+ })
103
+ const raw = result.stdout ?? ''
104
+ return { ok: result.status === 0, status: result.status, out: raw.trim(), raw, err: (result.stderr ?? '').trim() }
105
+ }
106
+
107
+ /** @param {string} file @returns {any} */
108
+ const readJson = (file) => JSON.parse(readFileSync(file, 'utf8'))
109
+ /** @param {unknown} value */
110
+ const json = (value) => `${JSON.stringify(value, null, 2)}\n`
111
+ /** @param {string} text */
112
+ const lastLine = (text) => text.trim().split('\n').pop() ?? ''
113
+ /** @param {unknown} value @returns {value is Record<string, any>} */
114
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value)
115
+ /** @param {Record<string, any>} group */
116
+ const sorted = (group) => Object.fromEntries(Object.entries(group).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
117
+ /** -1, 0 or 1 for two X.Y.Z versions. @param {string} a @param {string} b */
118
+ function compareVersions(a, b) {
119
+ const [x, y] = [a, b].map((version) => version.split('.').map(Number))
120
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1
121
+ return 0
122
+ }
123
+
124
+ /** npm leaves .gitignore and pnpm-lock.yaml out of a package, so the template holds them under these names. */
125
+ const TEMPLATE_NAMES = /** @type {Record<string, string>} */ ({ '.gitignore': '_gitignore', 'pnpm-lock.yaml': '_pnpm-lock.yaml' })
126
+ /** A site's path as the template names it. @param {string} file */
127
+ const templateName = (file) => TEMPLATE_NAMES[file] ?? file
128
+
129
+ /** @param {Buffer} bytes */
130
+ const isBinary = (bytes) => bytes.subarray(0, 8000).includes(0)
131
+ /**
132
+ * The hash the manifest records for a file. Text is hashed with CRLF turned into LF, so a
133
+ * checkout that converted line ends still counts as unchanged. (The same rule as
134
+ * scripts/build-template.mjs, which writes the manifest.)
135
+ * @param {Buffer} bytes
136
+ */
137
+ const hashOf = (bytes) => createHash('sha256').update(isBinary(bytes) ? bytes : bytes.toString('utf8').replaceAll('\r\n', '\n')).digest('hex')
138
+
139
+ /**
140
+ * The files in a packed npm package (.tgz), by their path inside it. A tar file is a run of
141
+ * 512-byte headers, each followed by its file's bytes padded to 512. Long paths come in one of
142
+ * three ways, all read here: the header's prefix field, a "pax" record before the file, or GNU
143
+ * tar's long-name entry. Throws when the file is not a gzipped tar.
144
+ * @param {string} file
145
+ * @returns {Map<string, Buffer>}
146
+ */
147
+ function readPacked(file) {
148
+ const tar = gunzipSync(readFileSync(file), { maxOutputLength: 2 * 1024 * 1024 * 1024 })
149
+ /** @type {Map<string, Buffer>} */
150
+ const files = new Map()
151
+ /** @type {string | null} */
152
+ let longName = null
153
+ for (let at = 0; at + 512 <= tar.length; ) {
154
+ const header = tar.subarray(at, at + 512)
155
+ // The archive ends with empty blocks.
156
+ if (header.every((byte) => byte === 0)) break
157
+ const field = (/** @type {number} */ from, /** @type {number} */ length) => {
158
+ const end = header.indexOf(0, from)
159
+ return header.toString('utf8', from, end === -1 || end > from + length ? from + length : end)
160
+ }
161
+ const size = parseInt(field(124, 12).trim() || '0', 8)
162
+ if (!Number.isInteger(size) || size < 0 || at + 512 + size > tar.length) throw new Error('not a tar file')
163
+ const type = header[156] === 0 ? '0' : String.fromCharCode(header[156])
164
+ const body = tar.subarray(at + 512, at + 512 + size)
165
+ at += 512 + Math.ceil(size / 512) * 512
166
+ if (type === 'L') {
167
+ longName = body.toString('utf8').replace(/\0+$/, '')
168
+ } else if (type === 'x') {
169
+ // Records of "<length> <key>=<value>\n", the length counting the whole record.
170
+ for (let pos = 0; pos < body.length; ) {
171
+ const space = body.indexOf(0x20, pos)
172
+ const length = space === -1 ? NaN : Number(body.toString('latin1', pos, space))
173
+ if (!Number.isInteger(length) || length <= 0) break
174
+ const record = body.toString('utf8', space + 1, pos + length - 1)
175
+ if (record.startsWith('path=')) longName = record.slice(5)
176
+ pos += length
177
+ }
178
+ } else if (type !== 'g') {
179
+ // The prefix field belongs to the "ustar" format only; older GNU headers keep times there.
180
+ const prefix = header.toString('latin1', 257, 263) === 'ustar\0' ? field(345, 155) : ''
181
+ const name = longName ?? (prefix ? `${prefix}/${field(0, 100)}` : field(0, 100))
182
+ longName = null
183
+ if (type === '0' || type === '7') files.set(name.replace(/^\.\//, ''), body)
184
+ }
185
+ }
186
+ return files
187
+ }
188
+
189
+ // ---------------------------------------------------------------------------------------------
190
+ // create
191
+ // ---------------------------------------------------------------------------------------------
192
+
193
+ /**
194
+ * Reads the command line. Unknown options stop the run: a typo should not create a folder.
195
+ * @param {string[]} args
196
+ */
197
+ function readCreateArgs(args) {
198
+ const options = {
199
+ folder: /** @type {string | undefined} */ (undefined),
200
+ db: /** @type {string | undefined} */ (undefined),
201
+ packages: /** @type {string | undefined} */ (undefined),
202
+ install: true,
203
+ git: true,
204
+ yes: false,
205
+ help: false,
206
+ }
207
+ for (let i = 0; i < args.length; i++) {
208
+ const arg = args[i]
209
+ const value = () => {
210
+ const next = args[++i]
211
+ return next === undefined || next.startsWith('-') ? stop(`${arg} needs a value.`) : next
212
+ }
213
+ if (arg === '--db') options.db = value()
214
+ else if (arg === '--packages') options.packages = value()
215
+ else if (arg === '--no-install') options.install = false
216
+ else if (arg === '--no-git') options.git = false
217
+ else if (arg === '-y' || arg === '--yes') options.yes = true
218
+ else if (arg === '-h' || arg === '--help') options.help = true
219
+ else if (arg.startsWith('-')) stop(`Unknown option ${arg}. Try --help.`)
220
+ else if (options.folder === undefined) options.folder = arg
221
+ else stop(`Only one folder can be given (got "${options.folder}" and "${arg}").`)
222
+ }
223
+ return options
224
+ }
225
+
226
+ /** A valid npm package name made from a folder's name. @param {string} folderName */
227
+ function packageNameFrom(folderName) {
228
+ const name = folderName
229
+ .normalize('NFKD')
230
+ .toLowerCase()
231
+ .replace(/[^a-z0-9._-]+/g, '-')
232
+ .replace(/^[._-]+|[._-]+$/g, '')
233
+ .slice(0, 214)
234
+ return name || 'pet-adopt-site'
235
+ }
236
+
237
+ /** The release this package's template holds, and its manifest. Stops when the template is missing. */
238
+ function bundled() {
239
+ if (!existsSync(path.join(TEMPLATE, 'package.json')) || !existsSync(path.join(TEMPLATE, MANIFEST))) {
240
+ stop(`The site template is missing from this copy of create-pet-adopt (${TEMPLATE}).\nIn the project's own repository, build it first: pnpm --filter create-pet-adopt build:template`)
241
+ }
242
+ const manifest = readJson(path.join(TEMPLATE, MANIFEST))
243
+ if (!isObject(manifest) || typeof manifest.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(manifest.version) || !isObject(manifest.files) || !isObject(manifest.package)) {
244
+ stop(`This copy of create-pet-adopt has a template without a usable ${MANIFEST}.`)
245
+ }
246
+ return /** @type {{ version: string, package: Record<string, any>, files: Record<string, string> }} */ (manifest)
247
+ }
248
+
249
+ /**
250
+ * The name in a packed npm package, from its package/package.json, or null when the file is not one.
251
+ * @param {string} file
252
+ * @returns {string | null}
253
+ */
254
+ function packedName(file) {
255
+ try {
256
+ const manifest = readPacked(file).get('package/package.json')
257
+ const name = manifest ? JSON.parse(manifest.toString('utf8')).name : null
258
+ return typeof name === 'string' ? name : null
259
+ } catch {
260
+ // Not a packed package: the caller says so.
261
+ return null
262
+ }
263
+ }
264
+
265
+ /**
266
+ * Makes the site take packages from packed files: one pnpm override each, under the `overrides:`
267
+ * the site's pnpm-workspace.yaml already has. Returns the lines it could not add.
268
+ * @param {string} workspaceFile @param {{ name: string, file: string }[]} packed
269
+ */
270
+ function addOverrides(workspaceFile, packed) {
271
+ const text = existsSync(workspaceFile) ? readFileSync(workspaceFile, 'utf8') : ''
272
+ const lines = packed.map(({ name, file }) => ` ${JSON.stringify(name)}: ${JSON.stringify(`file:${file.split(path.sep).join('/')}`)}`)
273
+ if (!/^overrides:[ \t]*$/m.test(text)) return lines
274
+ const block = [' # Testing: these packages come from packed files on this machine, not from npm.', ...lines].join('\n')
275
+ writeFileSync(workspaceFile, text.replace(/^overrides:[ \t]*$/m, (heading) => `${heading}\n${block}`))
276
+ return []
277
+ }
278
+
279
+ /** The nearest folder that exists, from a path upward. @param {string} target */
280
+ function nearestExisting(target) {
281
+ let dir = target
282
+ while (!existsSync(dir) && path.dirname(dir) !== dir) dir = path.dirname(dir)
283
+ return dir
284
+ }
285
+
286
+ /** @param {string[]} args */
287
+ async function create(args) {
288
+ // 1. Everything that can be checked before a question is asked or a file is written.
289
+ const options = readCreateArgs(args)
290
+ if (options.help) {
291
+ console.log(HELP)
292
+ return
293
+ }
294
+ const manifest = bundled()
295
+ const release = manifest.version
296
+
297
+ /** @type {{ name: string, file: string }[]} */
298
+ const packed = []
299
+ if (options.packages !== undefined) {
300
+ const dir = path.resolve(process.cwd(), options.packages)
301
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) stop(`--packages: ${dir} is not a folder.`)
302
+ for (const entry of readdirSync(dir).sort()) {
303
+ if (!entry.endsWith('.tgz')) continue
304
+ const file = path.join(dir, entry)
305
+ const name = packedName(file)
306
+ if (name === null) stop(`--packages: ${file} is not a packed npm package (make them with "pnpm pack").`)
307
+ // Only the project's own packages; a later file of the same package wins.
308
+ if (!name.startsWith('@pet-adopt/')) continue
309
+ const earlier = packed.findIndex((one) => one.name === name)
310
+ if (earlier >= 0) packed.splice(earlier, 1)
311
+ packed.push({ name, file })
312
+ }
313
+ if (packed.length === 0) stop(`--packages: ${dir} has no packed @pet-adopt packages (.tgz files made with "pnpm pack").`)
314
+ }
315
+
316
+ // Questions are only asked at a real terminal; otherwise (CI, a pipe) the defaults are used.
317
+ const interactive = !options.yes && Boolean(process.stdin.isTTY && process.stdout.isTTY)
318
+ const prompt = interactive ? createInterface({ input: process.stdin, output: process.stdout }) : null
319
+ /** @param {string} question @param {string} fallback */
320
+ const ask = async (question, fallback) => (prompt ? (await prompt.question(`${question} (${fallback}) `)).trim() || fallback : fallback)
321
+ const folder = options.folder ?? (await ask('Folder for the new site?', 'pet-adopt'))
322
+ const db = options.db ?? (await ask('Database for local development: sqlite or postgres?', 'sqlite'))
323
+ prompt?.close()
324
+
325
+ if (!DATABASES.some((name) => name === db)) stop(`The database must be sqlite or postgres, not "${db}".`)
326
+ const target = path.resolve(process.cwd(), folder)
327
+ if (existsSync(target)) {
328
+ if (!statSync(target).isDirectory()) stop(`${target} already exists and is not a folder. Choose another name.`)
329
+ if (readdirSync(target).length > 0) stop(`${target} already exists and is not empty. Choose another folder.`)
330
+ }
331
+
332
+ /** @type {string[]} */
333
+ const notes = []
334
+
335
+ // 2. Can this folder have a repository of its own?
336
+ /** @type {'yes' | 'off' | 'no-git' | 'inside'} */
337
+ let repository = 'yes'
338
+ if (!options.git) repository = 'off'
339
+ else if (!run('git', ['--version']).ok) repository = 'no-git'
340
+ else if (run('git', ['-C', nearestExisting(target), 'rev-parse', '--is-inside-work-tree']).out === 'true') repository = 'inside'
341
+
342
+ console.log(`\nStarting a Pet Adopt site in ${target}`)
343
+ console.log(`Version: ${release}`)
344
+
345
+ // 3. The files. Two of them travel under other names (npm leaves the real ones out of packages).
346
+ mkdirSync(target, { recursive: true })
347
+ cpSync(TEMPLATE, target, { recursive: true })
348
+ for (const [real, packedAs] of Object.entries(TEMPLATE_NAMES)) {
349
+ if (existsSync(path.join(target, packedAs))) renameSync(path.join(target, packedAs), path.join(target, real))
350
+ }
351
+ const packageFile = path.join(target, 'package.json')
352
+ const sitePackage = readJson(packageFile)
353
+ sitePackage.name = packageNameFrom(path.basename(target))
354
+ writeFileSync(packageFile, json(sitePackage))
355
+
356
+ // 4. .env, by the site's own script (a new secret, the local storage keys). Node runs it as it is.
357
+ const envFile = path.join(target, '.env')
358
+ const wrote = run(process.execPath, [path.join('scripts', 'setup-env.ts')], { cwd: target })
359
+ const envWritten = wrote.ok && existsSync(envFile)
360
+ if (!envWritten) notes.push(`.env was not written (${lastLine(wrote.err) || 'the setup script failed'}). Copy .env.example to .env and follow its comments.`)
361
+ if (db === 'postgres') {
362
+ const text = envWritten ? readFileSync(envFile, 'utf8') : ''
363
+ if (/^DATABASE_URL=.*$/m.test(text)) writeFileSync(envFile, text.replace(/^DATABASE_URL=.*$/m, `DATABASE_URL=${POSTGRES_URL}`))
364
+ else notes.push(`Set DATABASE_URL=${POSTGRES_URL} in .env.`)
365
+ }
366
+
367
+ // 5. Testing: the project's packages from packed files.
368
+ if (packed.length) {
369
+ const missed = addOverrides(path.join(target, 'pnpm-workspace.yaml'), packed)
370
+ if (missed.length) notes.push(`pnpm-workspace.yaml has no "overrides:" to add to. Add under one:\n${missed.map((line) => ` ${line}`).join('\n')}`)
371
+ console.log('\nTesting mode (--packages): this site takes these packages from files on this machine, not from npm:')
372
+ for (const { name, file } of packed) console.log(` ${name} <- ${file}`)
373
+ console.log('Such a site cannot be installed on another machine. Do not use it for a real site.')
374
+ }
375
+
376
+ // 6. The packages. With the template's lockfile a site installs exactly what was tested; packed
377
+ // files are not in that lockfile, so then pnpm may change it (it keeps every other version).
378
+ const lockfile = path.join(target, 'pnpm-lock.yaml')
379
+ const hadLockfile = existsSync(lockfile)
380
+ let installed = false
381
+ if (options.install && run('pnpm', ['--version']).ok) {
382
+ const flag = hadLockfile && packed.length === 0 ? '--frozen-lockfile' : '--no-frozen-lockfile'
383
+ console.log(`\nInstalling packages (pnpm install ${flag})...`)
384
+ installed = run('pnpm', ['install', flag], { cwd: target, show: true }).ok
385
+ if (!installed) notes.push('pnpm install failed. Run it again in the new folder.')
386
+ } else if (options.install) {
387
+ notes.push('pnpm was not found. Install it (https://pnpm.io/installation), then run "pnpm install" in the new folder.')
388
+ }
389
+ if (!existsSync(lockfile)) notes.push('There is no pnpm-lock.yaml yet. After your first "pnpm install", commit it.')
390
+
391
+ // 7. The repository, last, so the lockfile is in the commit. It is the site's own: one commit,
392
+ // no remote, nothing of the project's history.
393
+ const message = `Initialise Pet Adopt ${release}`
394
+ let committed = false
395
+ if (repository === 'off') {
396
+ notes.push('No git repository was started (--no-git). "pnpm pet-adopt:update" needs one: git init && git add --all && git commit -m "Start the site".')
397
+ } else if (repository === 'no-git') {
398
+ notes.push('git was not found, so no repository was started. "pnpm pet-adopt:update" needs one. Later, in the new folder: git init && git add --all && git commit -m "Start the site".')
399
+ } else if (repository === 'inside') {
400
+ notes.push("The new folder is inside another git repository, so no repository was started and nothing was committed. The files are untracked files of that repository; the site's own .gitignore keeps .env, node_modules and data/ out of it.")
401
+ } else {
402
+ // --initial-branch needs git 2.28; older ones get the branch name set afterwards.
403
+ const started = run('git', ['init', '--quiet', '--initial-branch=main'], { cwd: target }).ok || (run('git', ['init', '--quiet'], { cwd: target }).ok && run('git', ['symbolic-ref', 'HEAD', 'refs/heads/main'], { cwd: target }).ok)
404
+ if (!started) {
405
+ repository = 'no-git'
406
+ notes.push('git init failed, so no repository was started. Later, in the new folder: git init && git add --all && git commit -m "Start the site".')
407
+ } else {
408
+ // Exactly the template's files, by name and forced: whatever the machine's own ignore rules
409
+ // say, every one of them is added, and nothing else can be (.env, node_modules, data).
410
+ const names = [...new Set([...Object.keys(manifest.files), MANIFEST, 'pnpm-lock.yaml'])].filter((file) => existsSync(path.join(target, file)))
411
+ let added = run('git', ['--literal-pathspecs', 'add', '-f', '--pathspec-from-file=-', '--pathspec-file-nul'], { cwd: target, input: names.join('\0') })
412
+ if (!added.ok) {
413
+ // git older than 2.26 cannot read the list from its input.
414
+ for (let i = 0; i < names.length; i += 100) {
415
+ added = run('git', ['--literal-pathspecs', 'add', '-f', '--', ...names.slice(i, i + 100)], { cwd: target })
416
+ if (!added.ok) break
417
+ }
418
+ }
419
+ if (!added.ok) {
420
+ notes.push(`git add failed (${lastLine(added.err) || 'no message'}), so the first commit was not made. In the new folder: git add --all && git commit -m "${message}".`)
421
+ } else {
422
+ // Without a name and email git would make an identity up from the machine's account;
423
+ // user.useConfigOnly makes it refuse instead. Hooks and commit signing are the user's own
424
+ // settings and are respected.
425
+ const commit = run('git', ['-c', 'user.useConfigOnly=true', 'commit', '--quiet', '-m', message], { cwd: target })
426
+ committed = commit.ok
427
+ if (!committed && /no (email|name) was given|tell me who you are|empty ident/i.test(commit.err)) {
428
+ notes.push(`The first commit was not made: git has no name and email set. The files are staged. Set them, then commit, in the new folder:\n git config --global user.name "Your Name"\n git config --global user.email "you@example.com"\n git commit -m "${message}"`)
429
+ } else if (!committed) {
430
+ notes.push(`The first commit was not made (${lastLine(commit.err) || lastLine(commit.out) || 'git commit failed'}). The files are staged. In the new folder: git commit -m "${message}"`)
431
+ }
432
+ }
433
+ if (committed) {
434
+ // Checked before saying it worked.
435
+ const count = run('git', ['rev-list', '--count', 'HEAD'], { cwd: target }).out
436
+ if (count !== '1') notes.push(`The repository has ${count || 'an unknown number of'} commits, not one. Look at "git log".`)
437
+ const leaked = run('git', ['ls-files', '--', '.env', 'node_modules', 'data', '.next'], { cwd: target }).out
438
+ if (leaked) notes.push(`These must not be in the repository, and are in the first commit:\n${leaked.split('\n').map((line) => ` ${line}`).join('\n')}`)
439
+ const left = run('git', ['status', '--porcelain'], { cwd: target }).out
440
+ if (left) notes.push(`These files are not part of the first commit (they were not expected, so they were left for you to look at):\n${left.split('\n').map((line) => ` ${line}`).join('\n')}`)
441
+ }
442
+ }
443
+ }
444
+
445
+ const shownFolder = path.relative(process.cwd(), target) || '.'
446
+ const services = db === 'postgres' ? 'garage mailpit postgres' : 'garage mailpit'
447
+ const steps = [
448
+ `cd ${/^[\w./-]+$/.test(shownFolder) ? shownFolder : `'${shownFolder.replaceAll("'", "'\\''")}'`}`,
449
+ ...(installed ? [] : ['pnpm install']),
450
+ `docker compose up -d ${services} # upload storage, a test inbox${db === 'postgres' ? ', the database' : ''}`,
451
+ ...(db === 'postgres' ? ['pnpm migrate'] : []),
452
+ 'pnpm dev',
453
+ ]
454
+ console.log(`\nDone. Next:\n\n${steps.map((step) => ` ${step}`).join('\n')}`)
455
+ console.log('\nThen open http://localhost:3000 and follow the setup link the server prints in its log.')
456
+ if (notes.length) console.log(`\nTo do by hand:\n${notes.map((note) => ` - ${note}`).join('\n')}`)
457
+ const pushing = 'git remote add origin <its address> && git push -u origin main'
458
+ console.log(`
459
+ Your own repository: ${repository === 'yes' ? (committed ? pushing : `commit the files, then ${pushing}`) : repository === 'inside' ? 'the files are part of the repository this folder is in' : `git init, commit the files, then ${pushing}`}
460
+ Add a plugin: ${ADD_A_PLUGIN}
461
+ (always with the SDK, so the two are on the same release), then list it
462
+ in pet-adopt.config.ts. The file's comment shows how.
463
+ Update the site later: pnpm pet-adopt:update
464
+ Going live: ${DOCS_URL}/developers/deployment
465
+ What changes later: ${PROJECT_URL}/blob/main/CHANGELOG.md
466
+ (this site starts on Pet Adopt ${release})
467
+ `)
468
+ }
469
+
470
+ // ---------------------------------------------------------------------------------------------
471
+ // update
472
+ // ---------------------------------------------------------------------------------------------
473
+
474
+ /** Never merged as files: the site's own. */
475
+ const OWN = new Set(['pet-adopt.config.ts', 'pet-adopt.blocks.ts'])
476
+ /** Template files with a rule of their own. */
477
+ const SPECIAL = new Set(['package.json', 'pnpm-lock.yaml', MANIFEST])
478
+ /** The parts of package.json the template owns, merged key by key. */
479
+ const PACKAGE_GROUPS = ['scripts', 'dependencies', 'devDependencies', 'engines']
480
+ const PACKAGE_VALUES = ['packageManager', 'type']
481
+
482
+ /** @param {string[]} args */
483
+ function readUpdateArgs(args) {
484
+ const options = { dryRun: false, install: true, help: false, base: /** @type {string | undefined} */ (undefined) }
485
+ for (let i = 0; i < args.length; i++) {
486
+ const arg = args[i]
487
+ if (arg === '--dry-run') options.dryRun = true
488
+ else if (arg === '--no-install') options.install = false
489
+ else if (arg === '-h' || arg === '--help') options.help = true
490
+ else if (arg === '--base') {
491
+ const next = args[++i]
492
+ if (next === undefined || next.startsWith('-')) stop('--base needs a value: a create-pet-adopt package (.tgz) or its folder.')
493
+ options.base = next
494
+ } else if (arg === '--to') stop('There is no --to. To update to one release: pnpm dlx create-pet-adopt@X.Y.Z update')
495
+ else stop(`Unknown option ${arg}. Try update --help.`)
496
+ }
497
+ return options
498
+ }
499
+
500
+ /**
501
+ * Where the files of the site's current release are read from, when a merge needs them.
502
+ * @param {string | undefined} given The --base option. @param {string} version @param {string} work A temporary folder.
503
+ * @returns {{ read: (file: string) => Buffer | null, from: string }}
504
+ */
505
+ function openBase(given, version, work) {
506
+ const hint = `Nothing was changed. Give the files yourself with --base <a create-pet-adopt-${version}.tgz, or its unpacked folder>.`
507
+ /** @param {string} file A packed create-pet-adopt. @param {string} from */
508
+ const fromPacked = (file, from) => {
509
+ /** @type {Map<string, Buffer>} */
510
+ let files
511
+ try {
512
+ files = readPacked(file)
513
+ } catch {
514
+ return stop(`${file} is not a packed npm package (.tgz). ${hint}`)
515
+ }
516
+ if (!files.has(`package/template/${MANIFEST}`)) stop(`${file} is not a create-pet-adopt package with a site template in it. ${hint}`)
517
+ return { read: (/** @type {string} */ name) => files.get(`package/template/${templateName(name)}`) ?? null, from }
518
+ }
519
+ /** @param {{ read: (file: string) => Buffer | null, from: string }} base */
520
+ const checked = (base) => {
521
+ const manifest = base.read(MANIFEST)
522
+ /** @type {unknown} */
523
+ let found
524
+ try {
525
+ found = manifest ? JSON.parse(manifest.toString('utf8')).version : undefined
526
+ } catch {
527
+ found = undefined
528
+ }
529
+ if (found !== version) stop(`${base.from} holds the files of Pet Adopt ${found ?? '(unknown)'}, and this site is on ${version}. ${hint}`)
530
+ return base
531
+ }
532
+
533
+ if (given !== undefined) {
534
+ const full = path.resolve(process.cwd(), given)
535
+ if (!existsSync(full)) stop(`--base: ${full} does not exist. Nothing was changed.`)
536
+ if (!statSync(full).isDirectory()) return checked(fromPacked(full, full))
537
+ // A folder: the unpacked package (with template/ in it), or a template itself.
538
+ const root = [path.join(full, 'template'), full, path.join(full, 'package', 'template')].find((dir) => existsSync(path.join(dir, MANIFEST)))
539
+ if (!root) stop(`--base: ${full} holds no site template (no ${MANIFEST} in it or in its template folder). Nothing was changed.`)
540
+ return checked({
541
+ read: (file) => {
542
+ const found = [path.join(root, templateName(file)), path.join(root, file)].find((candidate) => existsSync(candidate) && statSync(candidate).isFile())
543
+ return found ? readFileSync(found) : null
544
+ },
545
+ from: full,
546
+ })
547
+ }
548
+
549
+ // npm ships with Node, and (unlike pnpm) can pack a package straight from the registry.
550
+ console.log(`Fetching the files of Pet Adopt ${version} to merge with (npm pack create-pet-adopt@${version})...`)
551
+ const fetched = run('npm', ['pack', `create-pet-adopt@${version}`], { cwd: work })
552
+ const tarball = fetched.ok ? readdirSync(work).find((name) => name.endsWith('.tgz')) : undefined
553
+ if (!tarball) {
554
+ const said = fetched.err.split('\n').filter((line) => line.trim() && !/complete log of this run/i.test(line))
555
+ const why = said.some((line) => /\b404\b/.test(line)) ? `npm has no create-pet-adopt@${version}` : said[0] || 'npm pack failed'
556
+ stop(`Could not download create-pet-adopt@${version} from npm (${why}).\n${hint}`)
557
+ }
558
+ return checked(fromPacked(path.join(work, tarball), `create-pet-adopt@${version}`))
559
+ }
560
+
561
+ /**
562
+ * Why a template path cannot be read or written in a site, or null: a symbolic link at the path or
563
+ * above it, or a file where one of its folders should be.
564
+ * @param {string} site @param {string} file
565
+ */
566
+ function blockedBy(site, file) {
567
+ const parts = file.split('/')
568
+ let at = site
569
+ for (let i = 0; i < parts.length; i++) {
570
+ at = path.join(at, parts[i])
571
+ const stat = lstatSync(at, { throwIfNoEntry: false })
572
+ if (!stat) return null
573
+ const shown = parts.slice(0, i + 1).join('/')
574
+ if (stat.isSymbolicLink()) return `${shown} is a symbolic link in your site`
575
+ if (i < parts.length - 1 && !stat.isDirectory()) return `${shown} is a file in your site and a folder in Pet Adopt`
576
+ }
577
+ return null
578
+ }
579
+
580
+ /** @param {string[]} args */
581
+ async function update(args) {
582
+ const options = readUpdateArgs(args)
583
+ if (options.help) {
584
+ console.log(UPDATE_HELP)
585
+ return
586
+ }
587
+ const to = bundled()
588
+ const site = process.cwd()
589
+ /** @param {string[]} gitArgs */
590
+ const git = (gitArgs) => run('git', gitArgs, { cwd: site })
591
+
592
+ // Refusals, all before anything is written.
593
+ if (!existsSync(path.join(site, 'package.json'))) stop(`${site} has no package.json. Run this in the folder of a Pet Adopt site.`)
594
+ if (!run('git', ['--version']).ok) stop('git was not found. The update merges files with git and leaves the changes for you to review, so it needs it.')
595
+ if (git(['rev-parse', '--is-inside-work-tree']).out !== 'true') {
596
+ stop('This folder is not a git repository. The update changes many files and leaves them for you to review, so it needs one:\n\n git init && git add --all && git commit -m "Before updating Pet Adopt"')
597
+ }
598
+ const dirty = git(['status', '--porcelain', '--', '.'])
599
+ if (!dirty.ok) stop(`git status failed: ${lastLine(dirty.err)}`)
600
+ if (dirty.out) {
601
+ // Not trimmed: a line's first column is part of what git says about the file.
602
+ const lines = dirty.raw.split('\n').filter(Boolean)
603
+ stop(`There are uncommitted changes (files that are not tracked count too). Commit or stash them first, so the update is the only thing in the working tree:\n\n${lines.slice(0, 10).map((line) => ` ${line}`).join('\n')}${lines.length > 10 ? `\n ... and ${lines.length - 10} more` : ''}`)
604
+ }
605
+ /** @type {any} */
606
+ let sitePackage
607
+ try {
608
+ sitePackage = readJson(path.join(site, 'package.json'))
609
+ } catch {
610
+ sitePackage = null
611
+ }
612
+ if (!isObject(sitePackage)) stop('package.json is not JSON. Fix it first.')
613
+ const recorded = isObject(sitePackage.petAdopt) ? sitePackage.petAdopt.version : undefined
614
+ const howToRecord = (/** @type {string} */ version) =>
615
+ `To set it: take ${MANIFEST} from the release this site is on (npm pack create-pet-adopt@${version}, then package/template/${MANIFEST} inside the .tgz), put it at ${MANIFEST}, set "petAdopt": { "version": "${version}" } in package.json, and commit both.`
616
+ if (!existsSync(path.join(site, MANIFEST))) {
617
+ stop(`${MANIFEST} is missing: this site does not record which release of Pet Adopt its files came from, so an update cannot tell your changes from the project's.\n${howToRecord(typeof recorded === 'string' ? recorded : 'X.Y.Z')}`)
618
+ }
619
+ /** @type {any} */
620
+ let from
621
+ try {
622
+ from = readJson(path.join(site, MANIFEST))
623
+ } catch {
624
+ from = null
625
+ }
626
+ if (!isObject(from) || typeof from.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(from.version) || !isObject(from.files) || !isObject(from.package)) {
627
+ stop(`${MANIFEST} is not a release's list of files. Restore it from git (git log -- ${MANIFEST}).`)
628
+ }
629
+ // A path from a manifest is joined to the site's folder: it must stay inside it.
630
+ for (const file of [...Object.keys(from.files), ...Object.keys(to.files)]) {
631
+ if (path.isAbsolute(file) || file.includes('\\') || file.split('/').some((part) => part === '' || part === '.' || part === '..' || part === '.git')) {
632
+ stop(`${MANIFEST} lists "${file}", which is not a path inside a site. Restore it from git (git log -- ${MANIFEST}).`)
633
+ }
634
+ }
635
+ if (recorded !== from.version) {
636
+ stop(`package.json says this site is on Pet Adopt ${recorded ?? '(nothing: it has no petAdopt.version)'}, and ${MANIFEST} is the list of files of ${from.version}. They must agree.\nIf the files are from ${from.version}: set "petAdopt": { "version": "${from.version}" } in package.json and commit. Otherwise restore ${MANIFEST} from git (git log -- ${MANIFEST}).`)
637
+ }
638
+ if (from.version === to.version) {
639
+ console.log(`Already on Pet Adopt ${to.version}.`)
640
+ return
641
+ }
642
+ if (compareVersions(to.version, from.version) < 0) {
643
+ stop(`This site is on Pet Adopt ${from.version}, and this create-pet-adopt holds ${to.version}, which is older. For the newest: pnpm dlx create-pet-adopt@latest update`)
644
+ }
645
+
646
+ const report = {
647
+ replaced: /** @type {string[]} */ ([]),
648
+ merged: /** @type {string[]} */ ([]),
649
+ added: /** @type {string[]} */ ([]),
650
+ deleted: /** @type {string[]} */ ([]),
651
+ packageJson: /** @type {string[]} */ ([]),
652
+ conflicts: /** @type {string[]} */ ([]),
653
+ attention: /** @type {string[]} */ ([]),
654
+ untouched: 0,
655
+ }
656
+
657
+ // The plan: what each file needs, from the three hashes alone.
658
+ /** @typedef {'add' | 'replace' | 'delete' | 'merge' | 'beside'} Action */
659
+ /** @type {{ file: string, action: Action, data?: Buffer }[]} */
660
+ const plan = []
661
+ for (const file of [...new Set([...Object.keys(from.files), ...Object.keys(to.files)])].sort()) {
662
+ if (SPECIAL.has(file)) continue
663
+ const before = from.files[file]
664
+ const next = to.files[file]
665
+ if (OWN.has(file)) {
666
+ if (before !== next) report.attention.push(`${file} is yours and was not touched. The template's own copy changed in this release: see the release notes for what it says now.`)
667
+ else report.untouched++
668
+ continue
669
+ }
670
+ const full = path.join(site, file)
671
+ // Nothing is read or written through a symbolic link (it may lead outside the site), and a
672
+ // file cannot be put under a path where the site has a file instead of a folder.
673
+ const blocked = blockedBy(site, file)
674
+ if (blocked) {
675
+ if (before !== next) report.attention.push(`${file}: ${blocked}. Not touched: bring it in line with the release yourself if you want it.`)
676
+ continue
677
+ }
678
+ const there = existsSync(full)
679
+ if (there && !statSync(full).isFile()) {
680
+ if (before !== next) report.attention.push(`${file} is a folder in your site and a file in Pet Adopt. Not touched: bring it in line with the release yourself if you want it.`)
681
+ continue
682
+ }
683
+ const ours = there ? hashOf(readFileSync(full)) : undefined
684
+ // The template did not change it (a file you deleted stays deleted), or you already have its text.
685
+ if (before === next || ours === next) {
686
+ report.untouched++
687
+ continue
688
+ }
689
+ if (git(['check-ignore', '-q', '--', file]).status === 0) {
690
+ report.attention.push(`${file} is git-ignored in your site and was not touched. Later updates will not offer it again: copy it from the release yourself if you want it.`)
691
+ continue
692
+ }
693
+ if (before === undefined) {
694
+ if (ours === undefined) plan.push({ file, action: 'add' })
695
+ else {
696
+ plan.push({ file, action: 'beside' })
697
+ report.conflicts.push(`${file}: Pet Adopt now ships this file and you have your own. Yours was kept; the new one is ${file}.pet-adopt-new.`)
698
+ }
699
+ } else if (next === undefined) {
700
+ if (ours === undefined) report.untouched++
701
+ else if (ours === before) plan.push({ file, action: 'delete' })
702
+ else report.attention.push(`${file} was removed from Pet Adopt. You changed it, so it was kept.`)
703
+ } else if (ours === undefined) {
704
+ report.attention.push(`${file} changed in Pet Adopt. You deleted it, so it stays deleted.`)
705
+ } else if (ours === before) {
706
+ plan.push({ file, action: 'replace' })
707
+ } else if (isBinary(readFileSync(full)) || isBinary(readFileSync(path.join(TEMPLATE, templateName(file))))) {
708
+ plan.push({ file, action: 'beside' })
709
+ report.conflicts.push(`${file}: changed by you and by Pet Adopt, and it is not text. Yours was kept; the new one is ${file}.pet-adopt-new.`)
710
+ } else {
711
+ plan.push({ file, action: 'merge' })
712
+ }
713
+ }
714
+
715
+ // The merges, worked out before anything is written: they need the files of the site's current
716
+ // release, and when those cannot be had, or are not what the site records, nothing changes.
717
+ const work = mkdtempSync(path.join(os.tmpdir(), 'pet-adopt-update-'))
718
+ // On exit too: a refusal below ends the process, and a `finally` does not run then.
719
+ process.on('exit', () => rmSync(work, { recursive: true, force: true }))
720
+ {
721
+ const merges = plan.filter((entry) => entry.action === 'merge')
722
+ if (merges.length) {
723
+ const base = openBase(options.base, from.version, work)
724
+ const baseFile = path.join(work, 'base')
725
+ for (const entry of merges) {
726
+ const { file } = entry
727
+ const bytes = base.read(file)
728
+ if (!bytes) stop(`${file} is not among the files of Pet Adopt ${from.version} in ${base.from}. Nothing was changed.`)
729
+ if (hashOf(bytes) !== from.files[file]) stop(`${file} in ${base.from} is not the file this site was made from (its hash differs from the one in ${MANIFEST}). Nothing was changed.`)
730
+ if (isBinary(bytes)) {
731
+ entry.action = 'beside'
732
+ report.conflicts.push(`${file}: changed by you and by Pet Adopt, and it is not text. Yours was kept; the new one is ${file}.pet-adopt-new.`)
733
+ continue
734
+ }
735
+ writeFileSync(baseFile, bytes)
736
+ // A checkout that turned line ends into CRLF (Git for Windows does by default) would differ
737
+ // from the release on every line: merge an LF copy, and give the result its CRLF back.
738
+ const oursText = readFileSync(path.join(site, file), 'utf8')
739
+ const crlf = oursText.includes('\r\n') && !bytes.includes('\r\n')
740
+ let oursFile = path.join(site, file)
741
+ if (crlf) {
742
+ oursFile = path.join(work, 'ours')
743
+ writeFileSync(oursFile, oursText.replaceAll('\r\n', '\n'))
744
+ }
745
+ const result = spawnSync('git', ['merge-file', '-p', '-L', 'your site', '-L', `Pet Adopt ${from.version}`, '-L', `Pet Adopt ${to.version}`, oursFile, baseFile, path.join(TEMPLATE, templateName(file))], { cwd: site, maxBuffer: BIG })
746
+ // 0: merged; 1 to 127: that many conflicts, marked in the text; anything else: git failed.
747
+ if (result.status === null || result.status < 0 || result.status > 127) stop(`git merge-file failed on ${file}: ${lastLine(String(result.stderr ?? '')) || 'no message'}. Nothing was changed.`)
748
+ entry.data = crlf ? Buffer.from(String(result.stdout).replaceAll('\n', '\r\n')) : result.stdout
749
+ if (result.status === 0) report.merged.push(file)
750
+ else report.conflicts.push(`${file}: ${result.status} conflict${result.status === 1 ? '' : 's'}, marked with <<<<<<< your site ... >>>>>>> Pet Adopt ${to.version} in the file.`)
751
+ }
752
+ }
753
+ }
754
+
755
+ // package.json, key by key: three-way, with the groups the two manifests record.
756
+ const nextPackage = { ...sitePackage }
757
+ /** Keys both sides changed differently: the site's stays. @type {{ where: string, key: string, line: string }[]} */
758
+ const disagreements = []
759
+ /**
760
+ * @param {Record<string, any>} base @param {Record<string, any>} ours @param {Record<string, any>} theirs @param {string} where
761
+ */
762
+ const mergeKeys = (base, ours, theirs, where) => {
763
+ const out = { ...ours }
764
+ for (const key of new Set([...Object.keys(base), ...Object.keys(theirs)])) {
765
+ const [b, o, t] = [base[key], ours[key], theirs[key]].map((value) => (value === undefined ? undefined : JSON.stringify(value)))
766
+ // The template did not change it, or both sides agree.
767
+ if (t === b || o === t) continue
768
+ const label = where ? `${where}.${key}` : key
769
+ if (o === b) {
770
+ if (t === undefined) delete out[key]
771
+ else out[key] = theirs[key]
772
+ report.packageJson.push(`${label}: ${b ?? '(none)'} -> ${t ?? '(removed)'}`)
773
+ } else {
774
+ disagreements.push({ where, key, line: `package.json ${label}: yours is ${o ?? '(removed)'}, Pet Adopt went from ${b ?? '(none)'} to ${t ?? '(removed)'}. Yours was kept.` })
775
+ }
776
+ }
777
+ return out
778
+ }
779
+ /** @param {unknown} value @returns {Record<string, any>} */
780
+ const group = (value) => (isObject(value) ? value : {})
781
+ for (const key of PACKAGE_GROUPS) {
782
+ const value = mergeKeys(group(from.package[key]), group(sitePackage[key]), group(to.package[key]), key)
783
+ if (Object.keys(value).length || key in sitePackage) nextPackage[key] = key === 'dependencies' || key === 'devDependencies' ? sorted(value) : value
784
+ }
785
+ for (const key of PACKAGE_VALUES) {
786
+ const value = mergeKeys({ [key]: from.package[key] }, { [key]: sitePackage[key] }, { [key]: to.package[key] }, '')
787
+ if (key in value && value[key] !== undefined) nextPackage[key] = value[key]
788
+ else delete nextPackage[key]
789
+ }
790
+ // The project's plugins are released with the SDK, on one version: the SDK and every installed
791
+ // @pet-adopt/plugin-* move to the new release together.
792
+ const sdkRange = group(to.package.dependencies)[SDK]
793
+ const sdkVersion = typeof sdkRange === 'string' ? sdkRange.replace(/^[\^~]/, '') : ''
794
+ if (/^\d+\.\d+\.\d+$/.test(sdkVersion)) {
795
+ for (const name of ['dependencies', 'devDependencies']) {
796
+ for (const [dependency, range] of Object.entries(group(nextPackage[name]))) {
797
+ if (!dependency.startsWith('@pet-adopt/plugin-') || range === sdkRange) continue
798
+ const at = disagreements.findIndex((one) => one.where === name && one.key === dependency)
799
+ if (typeof range !== 'string' || !/^[\^~]?\d+\.\d+\.\d+$/.test(range)) {
800
+ if (at === -1) report.attention.push(`package.json ${name}.${dependency} is "${range}", not a version from npm: left as it is. It should be on the same release as ${SDK} (${sdkRange}).`)
801
+ continue
802
+ }
803
+ if (compareVersions(range.replace(/^[\^~]/, ''), sdkVersion) >= 0) continue
804
+ nextPackage[name][dependency] = sdkRange
805
+ if (at !== -1) disagreements.splice(at, 1)
806
+ report.packageJson.push(`${name}.${dependency}: "${range}" -> "${sdkRange}" (released together with the SDK)`)
807
+ }
808
+ }
809
+ }
810
+ report.attention.push(...disagreements.map((one) => one.line))
811
+ nextPackage.petAdopt = { ...group(sitePackage.petAdopt), version: to.version }
812
+
813
+ // The lockfile is never merged. An untouched one, when the dependencies end up exactly the
814
+ // template's, is replaced by the template's; any other is left for pnpm install to bring up to date.
815
+ const sameGroups = ['dependencies', 'devDependencies'].every((name) => JSON.stringify(sorted(group(nextPackage[name]))) === JSON.stringify(sorted(group(to.package[name]))))
816
+ const lockfile = path.join(site, 'pnpm-lock.yaml')
817
+ const bundledLockfile = path.join(TEMPLATE, templateName('pnpm-lock.yaml'))
818
+ const takeLockfile =
819
+ sameGroups && existsSync(bundledLockfile) && existsSync(lockfile) && from.files['pnpm-lock.yaml'] !== undefined && hashOf(readFileSync(lockfile)) === from.files['pnpm-lock.yaml'] && to.files['pnpm-lock.yaml'] !== from.files['pnpm-lock.yaml']
820
+
821
+ // Now the writing. Nothing above changed a file.
822
+ let migrations = false
823
+ if (!options.dryRun) {
824
+ /** @type {string[]} */
825
+ const done = []
826
+ try {
827
+ for (const { file, action, data } of plan) {
828
+ const full = path.join(site, file)
829
+ const theirs = path.join(TEMPLATE, templateName(file))
830
+ if (action === 'delete') {
831
+ rmSync(full)
832
+ // Folders the deletion emptied go too (git does not track them).
833
+ for (let dir = path.dirname(full); dir !== site && dir.startsWith(site) && readdirSync(dir).length === 0; dir = path.dirname(dir)) rmdirSync(dir)
834
+ } else if (action === 'merge') {
835
+ if (data) writeFileSync(full, data)
836
+ } else {
837
+ // A replaced or added file takes the template's mode with its bytes.
838
+ mkdirSync(path.dirname(full), { recursive: true })
839
+ copyFileSync(theirs, action === 'beside' ? `${full}.pet-adopt-new` : full)
840
+ }
841
+ done.push(file)
842
+ }
843
+ // Last, so a site is only recorded as on the new release when every file made it.
844
+ writeFileSync(path.join(site, 'package.json'), json(nextPackage))
845
+ if (takeLockfile) copyFileSync(bundledLockfile, lockfile)
846
+ mkdirSync(path.dirname(path.join(site, MANIFEST)), { recursive: true })
847
+ copyFileSync(path.join(TEMPLATE, MANIFEST), path.join(site, MANIFEST))
848
+ } catch (error) {
849
+ stop(
850
+ `The update stopped part of the way: ${error instanceof Error ? error.message : String(error)}\n` +
851
+ `${done.length} of ${plan.length} files were changed, and the site is still recorded as on Pet Adopt ${from.version}.\n` +
852
+ 'To go back to where you were: git reset --hard && git clean -fd (the tree was clean before, so this only undoes the update)\n' +
853
+ 'Then fix what stopped it and run the update again.',
854
+ 3,
855
+ )
856
+ }
857
+ }
858
+ for (const { file, action } of plan) {
859
+ if (action === 'add') report.added.push(file)
860
+ else if (action === 'replace') report.replaced.push(file)
861
+ else if (action === 'delete') report.deleted.push(file)
862
+ if ((action === 'add' || action === 'replace') && file.startsWith('drizzle/')) migrations = true
863
+ }
864
+ report.packageJson.push(`petAdopt.version: "${from.version}" -> "${to.version}"`)
865
+ if (takeLockfile) report.packageJson.push("pnpm-lock.yaml: replaced by this release's (yours was unchanged, and the dependencies are the release's own)")
866
+
867
+ // The packages.
868
+ /** @type {string[]} */
869
+ const after = []
870
+ if (options.dryRun) {
871
+ // Nothing to install.
872
+ } else if (!options.install) {
873
+ after.push('Run "pnpm install" (--no-install was given).')
874
+ } else if (!run('pnpm', ['--version']).ok) {
875
+ after.push('pnpm was not found. Run "pnpm install" once it is there.')
876
+ } else {
877
+ console.log('Installing packages (pnpm install --no-frozen-lockfile)...')
878
+ // --no-frozen-lockfile: package.json may have changed, and CI=true makes frozen the default.
879
+ if (!run('pnpm', ['install', '--no-frozen-lockfile'], { cwd: site, show: true }).ok) {
880
+ after.push(`pnpm install failed.${report.conflicts.length ? ' Resolve the conflicts first, then' : ''} Run it again.`)
881
+ process.exitCode = 3
882
+ }
883
+ }
884
+
885
+ const would = options.dryRun
886
+ console.log(`\n${would ? 'Would update' : 'Updated'} this site from Pet Adopt ${from.version} to ${to.version}.${would ? ' Nothing was written (--dry-run).' : ''}`)
887
+ /** @type {[string, string[]][]} */
888
+ const sections = [
889
+ [would ? 'Would replace (you had not changed them)' : 'Replaced (you had not changed them)', report.replaced],
890
+ [would ? 'Would merge with your changes' : 'Merged with your changes', report.merged],
891
+ [would ? 'Would add' : 'Added', report.added],
892
+ [would ? 'Would delete' : 'Deleted', report.deleted],
893
+ ['package.json', report.packageJson],
894
+ [would ? 'CONFLICTS you would have to resolve by hand' : 'CONFLICTS to resolve by hand', report.conflicts],
895
+ ['Needs a look', report.attention],
896
+ ['Still to do', after],
897
+ ]
898
+ for (const [title, lines] of sections) {
899
+ if (lines.length) console.log(`\n${title}:\n${lines.map((line) => ` ${line}`).join('\n')}`)
900
+ }
901
+ console.log(`\n${report.untouched} other file${report.untouched === 1 ? '' : 's'} of Pet Adopt needed nothing.`)
902
+ if (migrations) {
903
+ console.log('\nThis update brings database migrations. A local SQLite file applies them when the server starts. On PostgreSQL or a hosted libSQL database, `pnpm build` applies them, or run `pnpm migrate` before the new code serves requests.')
904
+ }
905
+ console.log(`\nWhat changed in Pet Adopt: ${PROJECT_URL}/blob/main/CHANGELOG.md`)
906
+ if (!would) console.log('Nothing was committed. Review with `git status` and `git diff`, then commit.')
907
+ // 2 for a conflict, written or (in a dry run) only foreseen, so a script can ask before updating.
908
+ // A failed install keeps its 3.
909
+ if (report.conflicts.length && !process.exitCode) process.exitCode = 2
910
+ }
911
+
912
+ // A folder that is really called "update" can be given as ./update.
913
+ const argv = process.argv.slice(2)
914
+ {
915
+ // 22.18 is the first Node that runs the site's TypeScript scripts as they are; 23 is not supported.
916
+ const [major, minor] = process.versions.node.split('.').map(Number)
917
+ if (major < 22 || (major === 22 && minor < 18) || major === 23) stop(`Pet Adopt needs Node.js 22 (22.18 or newer) or 24. This is ${process.versions.node}.`)
918
+ }
919
+ if (argv[0] === 'update') await update(argv.slice(1))
920
+ else await create(argv)