tinyzoo 0.0.0-stage → 0.2.1

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 (392) hide show
  1. package/LICENSE +10 -0
  2. package/README.md +46 -2
  3. package/app/app.config.ts +35 -0
  4. package/app/assets/brand/characters/bright/bird.svg +1 -0
  5. package/app/assets/brand/characters/bright/bunny.svg +1 -0
  6. package/app/assets/brand/characters/bright/elephant.svg +1 -0
  7. package/app/assets/brand/characters/bright/fox.svg +1 -0
  8. package/app/assets/brand/characters/bright/frog.svg +1 -0
  9. package/app/assets/brand/characters/bright/octopus.svg +1 -0
  10. package/app/assets/brand/characters/muted/bee.svg +1 -0
  11. package/app/assets/brand/characters/muted/bird.svg +1 -0
  12. package/app/assets/brand/characters/muted/butterfly.svg +1 -0
  13. package/app/assets/brand/characters/muted/chick.svg +1 -0
  14. package/app/assets/brand/characters/muted/cow.svg +1 -0
  15. package/app/assets/brand/characters/muted/deer.svg +1 -0
  16. package/app/assets/brand/characters/muted/duck.svg +1 -0
  17. package/app/assets/brand/characters/muted/elephant.svg +1 -0
  18. package/app/assets/brand/characters/muted/fox.svg +1 -0
  19. package/app/assets/brand/characters/muted/hedgehog.svg +1 -0
  20. package/app/assets/brand/characters/muted/koala.svg +1 -0
  21. package/app/assets/brand/characters/muted/ladybug.svg +1 -0
  22. package/app/assets/brand/characters/muted/lion.svg +1 -0
  23. package/app/assets/brand/characters/muted/mouse.svg +1 -0
  24. package/app/assets/brand/characters/muted/octopus.svg +1 -0
  25. package/app/assets/brand/characters/muted/owl.svg +1 -0
  26. package/app/assets/brand/characters/muted/panda.svg +1 -0
  27. package/app/assets/brand/characters/muted/penguin.svg +1 -0
  28. package/app/assets/brand/characters/muted/pig.svg +1 -0
  29. package/app/assets/brand/characters/muted/poodle.svg +1 -0
  30. package/app/assets/brand/characters/muted/raccoon.svg +1 -0
  31. package/app/assets/brand/characters/muted/seal.svg +1 -0
  32. package/app/assets/brand/characters/muted/sheep.svg +1 -0
  33. package/app/assets/brand/characters/muted/snail.svg +1 -0
  34. package/app/assets/brand/characters/muted/turtle.svg +1 -0
  35. package/app/assets/brand/characters/muted/whale.svg +1 -0
  36. package/app/assets/brand/logo/favicon.svg +1 -0
  37. package/app/assets/brand/logo/logo-primary-reversed.svg +1 -0
  38. package/app/assets/brand/logo/logo-primary.svg +1 -0
  39. package/app/assets/brand/logo/mascot-reversed.svg +1 -0
  40. package/app/assets/brand/logo/mascot.svg +1 -0
  41. package/app/assets/brand/logo/wordmark-reversed.svg +1 -0
  42. package/app/assets/brand/logo/wordmark.svg +1 -0
  43. package/app/assets/css/cms-admin.css +607 -0
  44. package/app/components/CmsBlocks.vue +30 -0
  45. package/app/components/CmsCell.vue +16 -0
  46. package/app/components/CmsCellBadge.vue +18 -0
  47. package/app/components/CmsCellBlocks.vue +9 -0
  48. package/app/components/CmsCellBoolean.vue +12 -0
  49. package/app/components/CmsCellCode.vue +7 -0
  50. package/app/components/CmsCellColor.vue +13 -0
  51. package/app/components/CmsCellDate.vue +10 -0
  52. package/app/components/CmsCellExcerpt.vue +21 -0
  53. package/app/components/CmsCellGallery.vue +10 -0
  54. package/app/components/CmsCellGroup.vue +23 -0
  55. package/app/components/CmsCellNumber.vue +7 -0
  56. package/app/components/CmsCellRelation.vue +8 -0
  57. package/app/components/CmsCellText.vue +12 -0
  58. package/app/components/CmsCellThumb.vue +18 -0
  59. package/app/components/CmsConfirmDialog.vue +55 -0
  60. package/app/components/CmsContent.vue +103 -0
  61. package/app/components/CmsDayPicker.vue +44 -0
  62. package/app/components/CmsEmptyState.vue +35 -0
  63. package/app/components/CmsField.vue +111 -0
  64. package/app/components/CmsFieldBlocks.vue +353 -0
  65. package/app/components/CmsFieldBoolean.vue +8 -0
  66. package/app/components/CmsFieldColor.vue +42 -0
  67. package/app/components/CmsFieldDate.vue +131 -0
  68. package/app/components/CmsFieldGallery.vue +114 -0
  69. package/app/components/CmsFieldGroup.vue +53 -0
  70. package/app/components/CmsFieldMedia.vue +219 -0
  71. package/app/components/CmsFieldNumber.vue +11 -0
  72. package/app/components/CmsFieldRelationMany.vue +54 -0
  73. package/app/components/CmsFieldRelationOne.vue +47 -0
  74. package/app/components/CmsFieldRichText.vue +45 -0
  75. package/app/components/CmsFieldSelect.vue +41 -0
  76. package/app/components/CmsFieldSlug.vue +46 -0
  77. package/app/components/CmsFieldText.vue +75 -0
  78. package/app/components/CmsFormSections.vue +150 -0
  79. package/app/components/CmsHighlight.vue +22 -0
  80. package/app/components/CmsImage.vue +39 -0
  81. package/app/components/CmsLinkPicker.vue +122 -0
  82. package/app/components/CmsLinkTarget.vue +35 -0
  83. package/app/components/CmsListFilters.vue +107 -0
  84. package/app/components/CmsLiveNotice.vue +64 -0
  85. package/app/components/CmsLoadError.vue +24 -0
  86. package/app/components/CmsMascot.vue +10 -0
  87. package/app/components/CmsMediaLibrary.vue +114 -0
  88. package/app/components/CmsMediaPreview.vue +34 -0
  89. package/app/components/CmsMediaThumb.vue +22 -0
  90. package/app/components/CmsMoment.vue +42 -0
  91. package/app/components/CmsNav.vue +39 -0
  92. package/app/components/CmsPage.vue +86 -0
  93. package/app/components/CmsPasswordInput.vue +22 -0
  94. package/app/components/CmsPresence.vue +29 -0
  95. package/app/components/CmsPreviewPanel.vue +131 -0
  96. package/app/components/CmsPublishReview.vue +102 -0
  97. package/app/components/CmsRevisions.vue +195 -0
  98. package/app/components/CmsRichTextEditor.vue +290 -0
  99. package/app/components/CmsSearch.vue +99 -0
  100. package/app/components/CmsSection.vue +20 -0
  101. package/app/components/CmsSingletonForm.vue +283 -0
  102. package/app/components/CmsStatusBadge.vue +21 -0
  103. package/app/components/CmsTime.vue +16 -0
  104. package/app/components/CmsTranslationRef.vue +27 -0
  105. package/app/components/CmsTreeList.vue +453 -0
  106. package/app/components/CmsUnsavedText.vue +34 -0
  107. package/app/components/CmsWordmark.vue +10 -0
  108. package/app/composables/useCmsAdminHead.ts +18 -0
  109. package/app/composables/useCmsCollab.ts +165 -0
  110. package/app/composables/useCmsConfirm.ts +39 -0
  111. package/app/composables/useCmsEntryActions.ts +75 -0
  112. package/app/composables/useCmsFocus.ts +13 -0
  113. package/app/composables/useCmsForm.ts +273 -0
  114. package/app/composables/useCmsI18n.ts +185 -0
  115. package/app/composables/useCmsLinkTargets.ts +84 -0
  116. package/app/composables/useCmsLive.ts +199 -0
  117. package/app/composables/useCmsSearch.ts +62 -0
  118. package/app/composables/useCmsSeo.ts +99 -0
  119. package/app/composables/useCmsSignedIn.ts +24 -0
  120. package/app/composables/useCmsUiLocale.ts +24 -0
  121. package/app/i18n/cs.ts +781 -0
  122. package/app/i18n/de.ts +781 -0
  123. package/app/i18n/en.ts +782 -0
  124. package/app/i18n/types.ts +22 -0
  125. package/app/layouts/admin.vue +224 -0
  126. package/app/layouts/cms-auth.vue +37 -0
  127. package/app/middleware/cms-api-not-a-page.global.ts +10 -0
  128. package/app/middleware/cms-auth.global.ts +16 -0
  129. package/app/pages/admin/[entity]/[id].vue +1109 -0
  130. package/app/pages/admin/[entity]/index.vue +733 -0
  131. package/app/pages/admin/account.vue +117 -0
  132. package/app/pages/admin/forgot.vue +50 -0
  133. package/app/pages/admin/index.vue +184 -0
  134. package/app/pages/admin/invite/[token].vue +73 -0
  135. package/app/pages/admin/login.vue +84 -0
  136. package/app/pages/admin/media.vue +494 -0
  137. package/app/pages/admin/privacy.vue +193 -0
  138. package/app/pages/admin/reset/[token].vue +52 -0
  139. package/app/pages/admin/setup.vue +87 -0
  140. package/app/pages/admin/styleguide.vue +261 -0
  141. package/app/pages/admin/team.vue +258 -0
  142. package/app/plugins/cmsLivePreview.client.ts +20 -0
  143. package/app/plugins/cmsSignedOut.client.ts +31 -0
  144. package/app/utils/cmsBlockType.ts +11 -0
  145. package/app/utils/cmsBrand.ts +38 -0
  146. package/app/utils/cmsDiff.ts +83 -0
  147. package/app/utils/cmsFetch.ts +7 -0
  148. package/app/utils/cmsFocusInvalid.ts +22 -0
  149. package/app/utils/cmsIssues.ts +128 -0
  150. package/app/utils/cmsJson.ts +28 -0
  151. package/app/utils/cmsMedia.ts +63 -0
  152. package/app/utils/cmsSections.ts +154 -0
  153. package/app/utils/cmsTime.ts +41 -0
  154. package/cli/backup.ts +713 -0
  155. package/cli/breaking.ts +174 -0
  156. package/cli/content-migrate.ts +239 -0
  157. package/cli/db.ts +86 -0
  158. package/cli/export.ts +336 -0
  159. package/cli/generate.ts +146 -0
  160. package/cli/import.ts +643 -0
  161. package/cli/index.ts +140 -0
  162. package/cli/links-convert.ts +291 -0
  163. package/cli/seed-engine.ts +705 -0
  164. package/cli/seed.ts +339 -0
  165. package/cli/status.ts +49 -0
  166. package/cli/tar.ts +304 -0
  167. package/cli/transfer.ts +677 -0
  168. package/cli/up.ts +27 -0
  169. package/cli/upgrade.ts +60 -0
  170. package/cli/versions.ts +60 -0
  171. package/forms/components/CmsForm.vue +186 -0
  172. package/forms/index.ts +203 -0
  173. package/forms/messages.ts +104 -0
  174. package/forms/retention.ts +48 -0
  175. package/forms/server/form.get.ts +12 -0
  176. package/forms/server/form.post.ts +109 -0
  177. package/forms/server/formSettings.ts +12 -0
  178. package/forms/server/forms.ts +127 -0
  179. package/module.ts +373 -0
  180. package/nuxt.config.ts +43 -0
  181. package/package.json +98 -3
  182. package/server/api/cms/[entity]/[id]/revisions/[rev].get.ts +19 -0
  183. package/server/api/cms/[entity]/[id]/revisions/index.get.ts +14 -0
  184. package/server/api/cms/[entity]/[id].delete.ts +52 -0
  185. package/server/api/cms/[entity]/[id].get.ts +21 -0
  186. package/server/api/cms/[entity]/[id].patch.ts +116 -0
  187. package/server/api/cms/[entity]/_export.get.ts +69 -0
  188. package/server/api/cms/[entity]/_move.post.ts +81 -0
  189. package/server/api/cms/[entity]/_order.post.ts +49 -0
  190. package/server/api/cms/[entity]/_tree.get.ts +41 -0
  191. package/server/api/cms/[entity]/index.get.ts +62 -0
  192. package/server/api/cms/[entity]/index.post.ts +38 -0
  193. package/server/api/cms/[entity]/options.get.ts +55 -0
  194. package/server/api/cms/_auth/accept.post.ts +33 -0
  195. package/server/api/cms/_auth/forgot.post.ts +39 -0
  196. package/server/api/cms/_auth/invite/[token].get.ts +18 -0
  197. package/server/api/cms/_auth/login.post.ts +42 -0
  198. package/server/api/cms/_auth/logout.post.ts +7 -0
  199. package/server/api/cms/_auth/me.get.ts +5 -0
  200. package/server/api/cms/_auth/me.patch.ts +32 -0
  201. package/server/api/cms/_auth/password.post.ts +29 -0
  202. package/server/api/cms/_auth/reset.post.ts +34 -0
  203. package/server/api/cms/_auth/setup.post.ts +46 -0
  204. package/server/api/cms/_auth/status.get.ts +18 -0
  205. package/server/api/cms/_collab/session.get.ts +30 -0
  206. package/server/api/cms/_collab/socket.ts +51 -0
  207. package/server/api/cms/_collab/unsaved.delete.ts +16 -0
  208. package/server/api/cms/_graph.get.ts +20 -0
  209. package/server/api/cms/_links/resolve.post.ts +17 -0
  210. package/server/api/cms/_links.get.ts +81 -0
  211. package/server/api/cms/_live.ts +30 -0
  212. package/server/api/cms/_media/[id]/usage.get.ts +14 -0
  213. package/server/api/cms/_media/[id].delete.ts +29 -0
  214. package/server/api/cms/_media/[id].get.ts +13 -0
  215. package/server/api/cms/_media/[id].patch.ts +64 -0
  216. package/server/api/cms/_media/exists.post.ts +15 -0
  217. package/server/api/cms/_media/img/[id]/[file].get.ts +42 -0
  218. package/server/api/cms/_media/index.get.ts +44 -0
  219. package/server/api/cms/_media/index.post.ts +147 -0
  220. package/server/api/cms/_media/raw/[...key].get.ts +85 -0
  221. package/server/api/cms/_media/raw/[...key].head.ts +2 -0
  222. package/server/api/cms/_overview.get.ts +87 -0
  223. package/server/api/cms/_preview.post.ts +17 -0
  224. package/server/api/cms/_privacy/delete.post.ts +14 -0
  225. package/server/api/cms/_privacy/export.post.ts +25 -0
  226. package/server/api/cms/_privacy/lookup.post.ts +27 -0
  227. package/server/api/cms/_search.get.ts +17 -0
  228. package/server/api/cms/_singleton/[name].get.ts +19 -0
  229. package/server/api/cms/_singleton/[name].put.ts +76 -0
  230. package/server/api/cms/_users/[id]/resend.post.ts +25 -0
  231. package/server/api/cms/_users/[id].delete.ts +21 -0
  232. package/server/api/cms/_users/[id].patch.ts +45 -0
  233. package/server/api/cms/_users/index.get.ts +28 -0
  234. package/server/api/cms/_users/index.post.ts +39 -0
  235. package/server/api/content/[entity]/[slug].get.ts +74 -0
  236. package/server/api/content/[entity]/index.get.ts +100 -0
  237. package/server/api/content/_global/[name].get.ts +23 -0
  238. package/server/api/content/_search.get.ts +28 -0
  239. package/server/api/content/_sitemap.get.ts +8 -0
  240. package/server/api/content/_tree/[entity].get.ts +31 -0
  241. package/server/api/content-types.ts.get.ts +17 -0
  242. package/server/api/health/live.get.ts +10 -0
  243. package/server/api/health/ready.get.ts +21 -0
  244. package/server/api/openapi.get.ts +48 -0
  245. package/server/api/openapi.json.get.ts +32 -0
  246. package/server/db/driver.ts +8 -0
  247. package/server/mail/mailer.ts +43 -0
  248. package/server/middleware/cms-0-headers.ts +37 -0
  249. package/server/middleware/cms-0-migrate-gate.ts +14 -0
  250. package/server/middleware/cms-csrf.ts +28 -0
  251. package/server/middleware/cms-limits.ts +20 -0
  252. package/server/middleware/cms-redirects.ts +21 -0
  253. package/server/middleware/cms-session.ts +41 -0
  254. package/server/middleware/cms-z-plugin-access.ts +15 -0
  255. package/server/plugins/cms-0-config-check.ts +35 -0
  256. package/server/plugins/cms-changes.ts +53 -0
  257. package/server/plugins/cms-content-etag.ts +21 -0
  258. package/server/plugins/cms-errors.ts +45 -0
  259. package/server/plugins/cms-migrate.ts +5 -0
  260. package/server/plugins/cms-plugins.ts +17 -0
  261. package/server/plugins/cms-search.ts +12 -0
  262. package/server/plugins/cms-setup-code.ts +15 -0
  263. package/server/routes/sitemap.xml.get.ts +25 -0
  264. package/server/store/redis.ts +95 -0
  265. package/server/store/types.ts +21 -0
  266. package/server/tasks/cms/retention.ts +10 -0
  267. package/server/tasks/cms/scheduled.ts +10 -0
  268. package/server/tasks/cms/search-reindex.ts +12 -0
  269. package/server/utils/cmsAudit.ts +29 -0
  270. package/server/utils/cmsAuth.ts +143 -0
  271. package/server/utils/cmsBlocks.ts +47 -0
  272. package/server/utils/cmsChanges.ts +222 -0
  273. package/server/utils/cmsCollab.ts +286 -0
  274. package/server/utils/cmsCollabServer.ts +451 -0
  275. package/server/utils/cmsCollate.ts +27 -0
  276. package/server/utils/cmsContent.ts +376 -0
  277. package/server/utils/cmsCrud.ts +361 -0
  278. package/server/utils/cmsCsv.ts +24 -0
  279. package/server/utils/cmsDb.ts +23 -0
  280. package/server/utils/cmsDemo.ts +36 -0
  281. package/server/utils/cmsEmails.ts +125 -0
  282. package/server/utils/cmsErrors.ts +40 -0
  283. package/server/utils/cmsFold.ts +17 -0
  284. package/server/utils/cmsImageSizes.ts +51 -0
  285. package/server/utils/cmsJson.ts +6 -0
  286. package/server/utils/cmsLinkAddress.ts +50 -0
  287. package/server/utils/cmsLinks.ts +248 -0
  288. package/server/utils/cmsListQuery.ts +93 -0
  289. package/server/utils/cmsLive.ts +393 -0
  290. package/server/utils/cmsLocales.ts +96 -0
  291. package/server/utils/cmsMail.ts +28 -0
  292. package/server/utils/cmsMediaGc.ts +188 -0
  293. package/server/utils/cmsMediaKeys.ts +62 -0
  294. package/server/utils/cmsMigrate.ts +86 -0
  295. package/server/utils/cmsPreviewDraft.ts +72 -0
  296. package/server/utils/cmsPrivacy.ts +176 -0
  297. package/server/utils/cmsPublished.ts +57 -0
  298. package/server/utils/cmsRange.ts +38 -0
  299. package/server/utils/cmsRateLimit.ts +82 -0
  300. package/server/utils/cmsRedirects.ts +160 -0
  301. package/server/utils/cmsRetention.ts +61 -0
  302. package/server/utils/cmsRevisions.ts +103 -0
  303. package/server/utils/cmsScheduler.ts +45 -0
  304. package/server/utils/cmsScrub.ts +107 -0
  305. package/server/utils/cmsSearch.ts +354 -0
  306. package/server/utils/cmsSession.ts +102 -0
  307. package/server/utils/cmsSetupCode.ts +97 -0
  308. package/server/utils/cmsSitemap.ts +176 -0
  309. package/server/utils/cmsStorage.ts +580 -0
  310. package/server/utils/cmsStore.ts +109 -0
  311. package/server/utils/cmsTiming.ts +14 -0
  312. package/server/utils/cmsTooMany.ts +9 -0
  313. package/server/utils/cmsTranslationWrite.ts +186 -0
  314. package/server/utils/cmsTree.ts +251 -0
  315. package/server/utils/cmsTreeAddress.ts +65 -0
  316. package/server/utils/cmsUpload.ts +228 -0
  317. package/server/utils/cmsWebhooks.ts +104 -0
  318. package/shared/json.ts +11 -0
  319. package/shared/richtext-editor.ts +56 -0
  320. package/shared/richtext-normalize.ts +33 -0
  321. package/shared/richtext-paste.ts +151 -0
  322. package/shared/storage-delivery.ts +53 -0
  323. package/src/blocks.ts +624 -0
  324. package/src/changes.ts +54 -0
  325. package/src/content-shape.ts +340 -0
  326. package/src/deprecate.ts +64 -0
  327. package/src/descriptor.ts +149 -0
  328. package/src/docs.ts +27 -0
  329. package/src/emitter.ts +94 -0
  330. package/src/entity.ts +624 -0
  331. package/src/errorReport.ts +41 -0
  332. package/src/fields.ts +465 -0
  333. package/src/i18n.ts +26 -0
  334. package/src/index.ts +54 -0
  335. package/src/linkref.ts +31 -0
  336. package/src/links.ts +179 -0
  337. package/src/locales.ts +39 -0
  338. package/src/media.ts +48 -0
  339. package/src/migrate.ts +236 -0
  340. package/src/openapi.ts +377 -0
  341. package/src/paths.ts +88 -0
  342. package/src/plugin.ts +505 -0
  343. package/src/presets.ts +230 -0
  344. package/src/richtext.ts +88 -0
  345. package/src/sdk.ts +181 -0
  346. package/src/search.ts +312 -0
  347. package/src/seed.ts +225 -0
  348. package/src/setupCode.ts +30 -0
  349. package/src/system.ts +219 -0
  350. package/src/tree.ts +421 -0
  351. package/src/upgrades.ts +137 -0
  352. package/starter/.env.example +10 -0
  353. package/starter/README.md +65 -0
  354. package/starter/app/app.config.ts +10 -0
  355. package/starter/app/app.vue +12 -0
  356. package/starter/app/assets/css/main.css +15 -0
  357. package/starter/app/components/global/BlockContact.vue +15 -0
  358. package/starter/app/components/global/BlockCta.vue +15 -0
  359. package/starter/app/components/global/BlockHero.vue +23 -0
  360. package/starter/app/components/global/BlockImage.vue +13 -0
  361. package/starter/app/components/global/BlockText.vue +12 -0
  362. package/starter/app/composables/useSite.ts +77 -0
  363. package/starter/app/error.vue +28 -0
  364. package/starter/app/layouts/default.vue +106 -0
  365. package/starter/app/lib/cms-content.ts +152 -0
  366. package/starter/app/pages/[...slug].vue +66 -0
  367. package/starter/app/pages/hledat.vue +59 -0
  368. package/starter/app/pages/index.vue +20 -0
  369. package/starter/cms.config.ts +137 -0
  370. package/starter/compose.yaml +15 -0
  371. package/starter/drizzle.config.ts +8 -0
  372. package/starter/gitignore.txt +8 -0
  373. package/starter/nuxt.config.ts +13 -0
  374. package/starter/package.json +38 -0
  375. package/starter/scripts/typecheck.mjs +38 -0
  376. package/starter/seed/index.ts +297 -0
  377. package/starter/seed/media/about.jpg +0 -0
  378. package/starter/seed/media/hero.jpg +0 -0
  379. package/starter/seed/media/logo.png +0 -0
  380. package/starter/seed/media/news-bread.jpg +0 -0
  381. package/starter/seed/media/news-morning.jpg +0 -0
  382. package/starter/server/db/migrations/0000_init.sql +269 -0
  383. package/starter/server/db/migrations/0001_page_tree.sql +5 -0
  384. package/starter/server/db/migrations/0002_opening_hours_per_language.sql +1 -0
  385. package/starter/server/db/migrations/meta/0000_snapshot.json +1890 -0
  386. package/starter/server/db/migrations/meta/0001_snapshot.json +1887 -0
  387. package/starter/server/db/migrations/meta/0002_snapshot.json +1893 -0
  388. package/starter/server/db/migrations/meta/_journal.json +27 -0
  389. package/starter/server/db/schema.ts +253 -0
  390. package/starter/server/plugins/sitemap.ts +11 -0
  391. package/starter/server/routes/robots.txt.get.ts +12 -0
  392. package/starter/tsconfig.json +9 -0
package/src/system.ts ADDED
@@ -0,0 +1,219 @@
1
+ import { index, integer, jsonb, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from 'drizzle-orm/pg-core'
2
+
3
+ /**
4
+ * The CMS's own tables besides cms_media: people who use the admin, the one-time
5
+ * links they are sent (invites, password resets), and an audit log.
6
+ *
7
+ * Like cms_media, each table exists twice: as a runtime Drizzle table (used by the
8
+ * server) and as source emitted verbatim into the host's db/schema.ts (so
9
+ * drizzle-kit migrations create it). test/unit/system-tables.spec.ts checks the two
10
+ * agree.
11
+ */
12
+
13
+ const ts = (name: string) => timestamp(name, { withTimezone: true, mode: 'date', precision: 3 })
14
+
15
+ /** Built-in roles. `admin` also manages people; `author` edits only what they created and cannot publish. */
16
+ export const CMS_ROLES = ['admin', 'editor', 'author'] as const
17
+ export type CmsRole = (typeof CMS_ROLES)[number]
18
+
19
+ export const cmsUsers = pgTable('cms_users', {
20
+ id: uuid('id').primaryKey().defaultRandom(),
21
+ // Stored lower-cased; unique.
22
+ email: text('email').notNull(),
23
+ name: text('name').notNull().default(''),
24
+ role: text('role').notNull().default('editor'),
25
+ // invited (has not set a password yet) | active | disabled
26
+ status: text('status').notNull().default('invited'),
27
+ passwordHash: text('password_hash'),
28
+ // Admin interface language the person chose (null = browser/default).
29
+ locale: text('locale'),
30
+ // Bumped on password change, disable or "sign out everywhere": sessions carrying
31
+ // an older version stop working on their next request.
32
+ sessionVersion: integer('session_version').notNull().default(0),
33
+ lastLoginAt: ts('last_login_at'),
34
+ createdAt: ts('created_at').notNull().defaultNow(),
35
+ updatedAt: ts('updated_at').notNull().defaultNow(),
36
+ }, (t) => [uniqueIndex('cms_users_email_unique').on(t.email)])
37
+
38
+ export const cmsTokens = pgTable('cms_tokens', {
39
+ id: uuid('id').primaryKey().defaultRandom(),
40
+ userId: uuid('user_id').notNull().references(() => cmsUsers.id, { onDelete: 'cascade' }),
41
+ // invite | reset
42
+ kind: text('kind').notNull(),
43
+ // SHA-256 of the secret sent in the link; the secret itself is never stored.
44
+ tokenHash: text('token_hash').notNull(),
45
+ expiresAt: ts('expires_at').notNull(),
46
+ usedAt: ts('used_at'),
47
+ createdBy: uuid('created_by'),
48
+ createdAt: ts('created_at').notNull().defaultNow(),
49
+ }, (t) => [uniqueIndex('cms_tokens_hash_unique').on(t.tokenHash), index('cms_tokens_user_idx').on(t.userId)])
50
+
51
+ export const cmsAudit = pgTable('cms_audit', {
52
+ id: uuid('id').primaryKey().defaultRandom(),
53
+ // Who did it (null for anonymous events like a failed sign-in).
54
+ userId: uuid('user_id'),
55
+ // e.g. auth.login, user.invite, user.role, entry.create, entry.publish
56
+ action: text('action').notNull(),
57
+ entity: text('entity'),
58
+ recordId: text('record_id'),
59
+ meta: jsonb('meta'),
60
+ createdAt: ts('created_at').notNull().defaultNow(),
61
+ }, (t) => [index('cms_audit_created_idx').on(t.createdAt)])
62
+
63
+ /**
64
+ * Shared editing documents (Yjs state, one per entry and language). The working copy
65
+ * people type into together; saving the entry stores its content as usual. `epoch`
66
+ * changes when the document is started afresh from the saved entry, so a browser
67
+ * holding an older history cannot merge it back in.
68
+ */
69
+ export const cmsCollab = pgTable('cms_collab', {
70
+ // <entity>/<id> or <entity>/<id>/<locale>
71
+ name: text('name').primaryKey(),
72
+ epoch: uuid('epoch').notNull(),
73
+ // Yjs update (state as one update), base64.
74
+ state: text('state').notNull(),
75
+ // The entry (or translation) version the document last matched.
76
+ baseVersion: ts('base_version'),
77
+ updatedAt: ts('updated_at').notNull().defaultNow(),
78
+ // Refreshed while anyone has the document open: it is never restarted under them.
79
+ activeAt: ts('active_at'),
80
+ })
81
+
82
+ /**
83
+ * Revisions: a snapshot of an entry (or one translation) after every save — its
84
+ * field values as the editor sees them — for the history panel, compare and restore.
85
+ */
86
+ export const cmsRevisions = pgTable('cms_revisions', {
87
+ id: uuid('id').primaryKey().defaultRandom(),
88
+ entity: text('entity').notNull(),
89
+ recordId: uuid('record_id').notNull(),
90
+ // null = the entry itself; else the translation's language.
91
+ locale: text('locale'),
92
+ // entry.created, entry.updated, entry.published, translation.updated, …
93
+ action: text('action').notNull(),
94
+ // The entry's (translation's) version after this save.
95
+ version: ts('version'),
96
+ data: jsonb('data').notNull(),
97
+ // Field keys that differ from the previous revision.
98
+ changed: jsonb('changed').notNull(),
99
+ userId: uuid('user_id'),
100
+ createdAt: ts('created_at').notNull().defaultNow(),
101
+ }, (t) => [index('cms_revisions_record_idx').on(t.entity, t.recordId, t.locale, t.createdAt)])
102
+
103
+ /** Small bits of state the CMS keeps for itself (e.g. when the scheduler last ran). */
104
+ export const cmsState = pgTable('cms_state', {
105
+ key: text('key').primaryKey(),
106
+ value: jsonb('value').notNull(),
107
+ updatedAt: ts('updated_at').notNull().defaultNow(),
108
+ })
109
+
110
+ /**
111
+ * The search index: what each entry says, as plain text, one row per entry and
112
+ * language ('' = an entry of a collection without translations, the same in every
113
+ * language). `*_folded` is lowercased without accents, with trigram indexes
114
+ * (pg_trgm) for typo-tolerant matching. `body` is what visitors may read; `extra` is
115
+ * only for the admin's search (hidden fields, the list's searchable fields). Kept up
116
+ * to date on every change and rebuilt when the search configuration changes.
117
+ */
118
+ export const cmsSearch = pgTable('cms_search', {
119
+ entity: text('entity').notNull(),
120
+ recordId: uuid('record_id').notNull(),
121
+ locale: text('locale').notNull().default(''),
122
+ title: text('title').notNull().default(''),
123
+ body: text('body').notNull().default(''),
124
+ extra: text('extra').notNull().default(''),
125
+ titleFolded: text('title_folded').notNull().default(''),
126
+ bodyFolded: text('body_folded').notNull().default(''),
127
+ extraFolded: text('extra_folded').notNull().default(''),
128
+ // The entry's website address in this language (collections with translations).
129
+ path: text('path'),
130
+ updatedAt: ts('updated_at').notNull().defaultNow(),
131
+ }, (t) => [
132
+ primaryKey({ name: 'cms_search_pk', columns: [t.entity, t.recordId, t.locale] }),
133
+ index('cms_search_title_trgm').using('gin', t.titleFolded.op('gin_trgm_ops')),
134
+ index('cms_search_body_trgm').using('gin', t.bodyFolded.op('gin_trgm_ops')),
135
+ index('cms_search_extra_trgm').using('gin', t.extraFolded.op('gin_trgm_ops')),
136
+ ])
137
+
138
+ /** Source emitted verbatim into db/schema.ts (imports provided by the emitter). */
139
+ export const CMS_SYSTEM_SOURCE = `export const cmsUsers = pgTable('cms_users', {
140
+ id: uuid('id').primaryKey().defaultRandom(),
141
+ email: text('email').notNull(),
142
+ name: text('name').notNull().default(''),
143
+ role: text('role').notNull().default('editor'),
144
+ status: text('status').notNull().default('invited'),
145
+ passwordHash: text('password_hash'),
146
+ locale: text('locale'),
147
+ sessionVersion: integer('session_version').notNull().default(0),
148
+ lastLoginAt: timestamp('last_login_at', { withTimezone: true, mode: 'date', precision: 3 }),
149
+ createdAt: timestamp('created_at', { withTimezone: true, mode: 'date', precision: 3 }).notNull().defaultNow(),
150
+ updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'date', precision: 3 }).notNull().defaultNow(),
151
+ }, (t) => [uniqueIndex('cms_users_email_unique').on(t.email)])
152
+
153
+ export const cmsTokens = pgTable('cms_tokens', {
154
+ id: uuid('id').primaryKey().defaultRandom(),
155
+ userId: uuid('user_id').notNull().references(() => cmsUsers.id, { onDelete: 'cascade' }),
156
+ kind: text('kind').notNull(),
157
+ tokenHash: text('token_hash').notNull(),
158
+ expiresAt: timestamp('expires_at', { withTimezone: true, mode: 'date', precision: 3 }).notNull(),
159
+ usedAt: timestamp('used_at', { withTimezone: true, mode: 'date', precision: 3 }),
160
+ createdBy: uuid('created_by'),
161
+ createdAt: timestamp('created_at', { withTimezone: true, mode: 'date', precision: 3 }).notNull().defaultNow(),
162
+ }, (t) => [uniqueIndex('cms_tokens_hash_unique').on(t.tokenHash), index('cms_tokens_user_idx').on(t.userId)])
163
+
164
+ export const cmsAudit = pgTable('cms_audit', {
165
+ id: uuid('id').primaryKey().defaultRandom(),
166
+ userId: uuid('user_id'),
167
+ action: text('action').notNull(),
168
+ entity: text('entity'),
169
+ recordId: text('record_id'),
170
+ meta: jsonb('meta'),
171
+ createdAt: timestamp('created_at', { withTimezone: true, mode: 'date', precision: 3 }).notNull().defaultNow(),
172
+ }, (t) => [index('cms_audit_created_idx').on(t.createdAt)])
173
+
174
+ export const cmsCollab = pgTable('cms_collab', {
175
+ name: text('name').primaryKey(),
176
+ epoch: uuid('epoch').notNull(),
177
+ state: text('state').notNull(),
178
+ baseVersion: timestamp('base_version', { withTimezone: true, mode: 'date', precision: 3 }),
179
+ updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'date', precision: 3 }).notNull().defaultNow(),
180
+ activeAt: timestamp('active_at', { withTimezone: true, mode: 'date', precision: 3 }),
181
+ })
182
+
183
+ export const cmsRevisions = pgTable('cms_revisions', {
184
+ id: uuid('id').primaryKey().defaultRandom(),
185
+ entity: text('entity').notNull(),
186
+ recordId: uuid('record_id').notNull(),
187
+ locale: text('locale'),
188
+ action: text('action').notNull(),
189
+ version: timestamp('version', { withTimezone: true, mode: 'date', precision: 3 }),
190
+ data: jsonb('data').notNull(),
191
+ changed: jsonb('changed').notNull(),
192
+ userId: uuid('user_id'),
193
+ createdAt: timestamp('created_at', { withTimezone: true, mode: 'date', precision: 3 }).notNull().defaultNow(),
194
+ }, (t) => [index('cms_revisions_record_idx').on(t.entity, t.recordId, t.locale, t.createdAt)])
195
+
196
+ export const cmsState = pgTable('cms_state', {
197
+ key: text('key').primaryKey(),
198
+ value: jsonb('value').notNull(),
199
+ updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'date', precision: 3 }).notNull().defaultNow(),
200
+ })
201
+
202
+ export const cmsSearch = pgTable('cms_search', {
203
+ entity: text('entity').notNull(),
204
+ recordId: uuid('record_id').notNull(),
205
+ locale: text('locale').notNull().default(''),
206
+ title: text('title').notNull().default(''),
207
+ body: text('body').notNull().default(''),
208
+ extra: text('extra').notNull().default(''),
209
+ titleFolded: text('title_folded').notNull().default(''),
210
+ bodyFolded: text('body_folded').notNull().default(''),
211
+ extraFolded: text('extra_folded').notNull().default(''),
212
+ path: text('path'),
213
+ updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'date', precision: 3 }).notNull().defaultNow(),
214
+ }, (t) => [
215
+ primaryKey({ name: 'cms_search_pk', columns: [t.entity, t.recordId, t.locale] }),
216
+ index('cms_search_title_trgm').using('gin', t.titleFolded.op('gin_trgm_ops')),
217
+ index('cms_search_body_trgm').using('gin', t.bodyFolded.op('gin_trgm_ops')),
218
+ index('cms_search_extra_trgm').using('gin', t.extraFolded.op('gin_trgm_ops')),
219
+ ])`
package/src/tree.ts ADDED
@@ -0,0 +1,421 @@
1
+ import type { LocalesDef } from './locales'
2
+ import { sitePath, type PathTemplate } from './paths'
3
+
4
+ /**
5
+ * Pure logic of a page tree (`definePages({ tree: true })`): who is whose parent, how
6
+ * deep, what a page's address is in each language, and what a change would break.
7
+ * No database here: the server loads the nodes and asks these functions.
8
+ */
9
+
10
+ /** The deepest a tree may be configured to go (a page at the top is depth 1). */
11
+ export const TREE_MAX_DEPTH_LIMIT = 10
12
+ /** Depth limit when `definePages({ tree: true })` says nothing else. */
13
+ export const TREE_DEFAULT_MAX_DEPTH = 4
14
+
15
+ /** What the tree needs of an entity (from `defineEntity({ tree })`). */
16
+ export interface TreeConfig {
17
+ /** The field pointing at the parent entry (a many-to-one relation to the entity itself). */
18
+ parent: string
19
+ /** The whole-number field holding the position among siblings. */
20
+ order: string
21
+ /** How many levels the tree may have; a page at the top is level 1. */
22
+ maxDepth: number
23
+ }
24
+
25
+ /** One entry as the tree sees it. */
26
+ export interface TreeNode {
27
+ id: string
28
+ parentId: string | null
29
+ /** Its address part in the default language. */
30
+ slug: string
31
+ /** Address parts of its translations (`{ en: 'about' }`); an empty one falls back to the default. */
32
+ slugs?: Record<string, string | null | undefined>
33
+ title?: string
34
+ titles?: Record<string, string | null | undefined>
35
+ /** Languages (besides the default) it has a translation in: it has an address there. */
36
+ locales?: string[]
37
+ position?: number
38
+ }
39
+
40
+ export type TreeIndex = Map<string, TreeNode>
41
+
42
+ /** Does the node have an address in this language? The default language always; others when translated. */
43
+ export function existsIn(node: TreeNode, locale: string | null, defaultLocale: string | null): boolean {
44
+ return !locale || locale === defaultLocale || !!node.locales?.includes(locale)
45
+ }
46
+
47
+ export function indexTree(nodes: TreeNode[]): TreeIndex {
48
+ return new Map(nodes.map((n) => [n.id, n]))
49
+ }
50
+
51
+ /** The address part of a node in a language: its translation, else the default one. */
52
+ export function slugIn(node: TreeNode, locale: string | null, defaultLocale: string | null): string {
53
+ if (locale && locale !== defaultLocale) {
54
+ const t = node.slugs?.[locale]
55
+ if (typeof t === 'string' && t !== '') return t
56
+ }
57
+ return node.slug
58
+ }
59
+
60
+ /** The title of a node in a language, falling back to the default. */
61
+ export function titleIn(node: TreeNode, locale: string | null, defaultLocale: string | null): string {
62
+ if (locale && locale !== defaultLocale) {
63
+ const t = node.titles?.[locale]
64
+ if (typeof t === 'string' && t !== '') return t
65
+ }
66
+ return node.title ?? ''
67
+ }
68
+
69
+ /**
70
+ * The nodes from the top of the tree down to `id` (the node itself last). Stops at an
71
+ * unknown parent or a loop (a stored loop cannot be made through the API).
72
+ */
73
+ export function chainOf(index: TreeIndex, id: string): TreeNode[] {
74
+ const out: TreeNode[] = []
75
+ const seen = new Set<string>()
76
+ let cur = index.get(id)
77
+ while (cur && !seen.has(cur.id)) {
78
+ seen.add(cur.id)
79
+ out.unshift(cur)
80
+ cur = cur.parentId ? index.get(cur.parentId) : undefined
81
+ }
82
+ return out
83
+ }
84
+
85
+ /** Level of a node: 1 for a top-level page. */
86
+ export function depthOf(index: TreeIndex, id: string): number {
87
+ return chainOf(index, id).length
88
+ }
89
+
90
+ export function childrenMap(nodes: Iterable<TreeNode>): Map<string | null, TreeNode[]> {
91
+ const out = new Map<string | null, TreeNode[]>()
92
+ for (const n of nodes) {
93
+ const list = out.get(n.parentId) ?? []
94
+ list.push(n)
95
+ out.set(n.parentId, list)
96
+ }
97
+ return out
98
+ }
99
+
100
+ /** Siblings in their order (position, then title, then id so the order never wobbles). */
101
+ export function sortSiblings(list: TreeNode[]): TreeNode[] {
102
+ return [...list].sort((a, b) => (a.position ?? 0) - (b.position ?? 0) || (a.title ?? '').localeCompare(b.title ?? '') || (a.id < b.id ? -1 : 1))
103
+ }
104
+
105
+ /**
106
+ * Gap between neighbouring positions. Positions are left sparse so that putting a page
107
+ * between two others only writes that page; the siblings are renumbered (`placeAmong`) only
108
+ * when two neighbours have no whole number between them.
109
+ */
110
+ export const TREE_POSITION_STEP = 1024
111
+ /** Positions stay well inside a 32-bit integer column. */
112
+ const TREE_POSITION_LIMIT = 1_000_000_000
113
+
114
+ /**
115
+ * Where a page goes among its (new) siblings. `siblings` are the other pages under the
116
+ * parent in their order (the page itself is not among them); `index` is the place asked
117
+ * for (0 = first, past the end = last); `keep` is the page's position now, kept when it
118
+ * already fits between the neighbours.
119
+ *
120
+ * Returns the page's position and, only when no whole number fits between the
121
+ * neighbours (or the numbers have grown too large), `renumbered`: new positions for every
122
+ * page under the parent (the page included) so the caller can rewrite them in one go.
123
+ * Otherwise `renumbered` is empty and only the page itself is written.
124
+ */
125
+ export function placeAmong(siblings: TreeNode[], id: string, index: number | undefined, keep: number | null): { position: number; renumbered: Map<string, number> } {
126
+ const at = Math.min(Math.max(index ?? siblings.length, 0), siblings.length)
127
+ const prev = siblings[at - 1]
128
+ const next = siblings[at]
129
+ const lo = prev ? prev.position ?? 0 : null
130
+ const hi = next ? next.position ?? 0 : null
131
+ let position: number | null = null
132
+ if (keep !== null && (lo === null || keep > lo) && (hi === null || keep < hi)) position = keep
133
+ else if (lo === null && hi === null) position = 0
134
+ else if (lo === null) position = hi! - TREE_POSITION_STEP
135
+ else if (hi === null) position = lo + TREE_POSITION_STEP
136
+ else {
137
+ const mid = Math.floor((lo + hi) / 2)
138
+ if (mid > lo && mid < hi) position = mid
139
+ }
140
+ if (position !== null && Math.abs(position) <= TREE_POSITION_LIMIT) return { position, renumbered: new Map() }
141
+ const order = [...siblings.slice(0, at).map((n) => n.id), id, ...siblings.slice(at).map((n) => n.id)]
142
+ const renumbered = new Map(order.map((sid, i) => [sid, i * TREE_POSITION_STEP]))
143
+ return { position: renumbered.get(id)!, renumbered }
144
+ }
145
+
146
+ /** Everything below a node (not the node), parents before children, siblings in order. */
147
+ export function descendantsOf(index: TreeIndex, id: string, children = childrenMap(index.values())): TreeNode[] {
148
+ const out: TreeNode[] = []
149
+ const seen = new Set<string>([id])
150
+ const walk = (parent: string) => {
151
+ for (const c of sortSiblings(children.get(parent) ?? [])) {
152
+ if (seen.has(c.id)) continue
153
+ seen.add(c.id)
154
+ out.push(c)
155
+ walk(c.id)
156
+ }
157
+ }
158
+ walk(id)
159
+ return out
160
+ }
161
+
162
+ /** Levels below a node: 0 for a page without children. */
163
+ export function heightOf(index: TreeIndex, id: string, children = childrenMap(index.values())): number {
164
+ const walk = (cur: string, seen: Set<string>): number => {
165
+ let h = 0
166
+ for (const c of children.get(cur) ?? []) {
167
+ if (seen.has(c.id)) continue
168
+ h = Math.max(h, 1 + walk(c.id, new Set([...seen, c.id])))
169
+ }
170
+ return h
171
+ }
172
+ return walk(id, new Set([id]))
173
+ }
174
+
175
+ /** One node's chain of address parts in a language: ['o-nas', 'tym']. */
176
+ export function slugChain(index: TreeIndex, id: string, locale: string | null, defaultLocale: string | null): string[] {
177
+ return chainOf(index, id).map((n) => slugIn(n, locale, defaultLocale))
178
+ }
179
+
180
+ /**
181
+ * The address of a node in a language, prefix included ('/en/about/team'), or null
182
+ * when the collection has no page in that language. The ancestors' address parts are
183
+ * joined with '/', each escaped for a URL.
184
+ */
185
+ export function treeAddress(
186
+ locales: LocalesDef | null, template: PathTemplate | undefined | null, key: string,
187
+ index: TreeIndex, id: string, locale: string | null,
188
+ ): string | null {
189
+ const node = index.get(id)
190
+ if (!node) return null
191
+ const parts = slugChain(index, id, locale, locales?.default ?? null)
192
+ return sitePath(locales, template, locale, { [key]: parts })
193
+ }
194
+
195
+ /** What is wrong with a proposed change of a tree; the server turns it into a 422 or 409. */
196
+ export type TreeProblem =
197
+ | { code: 'tree_cycle'; message: string; loop: string[] }
198
+ | { code: 'tree_depth'; message: string; depth: number; maxDepth: number }
199
+ | { code: 'tree_parent_missing'; message: string }
200
+ | { code: 'tree_address_taken'; message: string; locale: string | null; path: string; otherId: string; otherTitle: string }
201
+
202
+ export interface TreeChange {
203
+ /** The entry being created (its id is already chosen) or changed. */
204
+ id: string
205
+ /** The entry's parent after the change (null: top level). */
206
+ parentId: string | null
207
+ /** The entry's default-language address part after the change. */
208
+ slug: string
209
+ /** A translation's address part after the change (`{ en: 'about' }`, null/'' = falls back). */
210
+ slugs?: Record<string, string | null | undefined>
211
+ title?: string
212
+ /** Languages the entry has a translation in after the change (default: as stored, plus those in `slugs`). */
213
+ locales?: string[]
214
+ }
215
+
216
+ /** The tree as it would be after a change (the node added or replaced). */
217
+ export function applyChange(nodes: TreeNode[], change: TreeChange): TreeNode[] {
218
+ const existing = nodes.find((n) => n.id === change.id)
219
+ const next: TreeNode = {
220
+ ...(existing ?? { id: change.id }),
221
+ id: change.id,
222
+ parentId: change.parentId,
223
+ slug: change.slug,
224
+ slugs: { ...(existing?.slugs ?? {}), ...(change.slugs ?? {}) },
225
+ title: change.title ?? existing?.title,
226
+ locales: change.locales ?? [...new Set([...(existing?.locales ?? []), ...Object.keys(change.slugs ?? {})])],
227
+ }
228
+ return [...nodes.filter((n) => n.id !== change.id), next]
229
+ }
230
+
231
+ export interface TreeCheckOptions {
232
+ maxDepth: number
233
+ locales: LocalesDef | null
234
+ /** The collection's address template, to compare complete addresses. */
235
+ template: PathTemplate | undefined | null
236
+ key: string
237
+ /**
238
+ * Who may see which page: titles of pages this returns false for are left out of the
239
+ * messages (a person who may not read a page is not told its title). Omit to show all.
240
+ */
241
+ visible?: (id: string) => boolean
242
+ }
243
+
244
+ /**
245
+ * Check a change against the tree as it stands: it must not make an entry its own
246
+ * ancestor, must not go deeper than `maxDepth` (counting the subtree it carries), and
247
+ * the addresses of the entry and everything below it must stay unique per language.
248
+ * Addresses that were already shared before (older data) do not block an unrelated edit:
249
+ * only the entry and what is below it are compared, and only against others.
250
+ */
251
+ export function checkTreeChange(nodes: TreeNode[], change: TreeChange, opts: TreeCheckOptions): TreeProblem | null {
252
+ const titleOf = (n: TreeNode | undefined) => (n && opts.visible && !opts.visible(n.id) ? '…' : n?.title || '…')
253
+ const after = indexTree(applyChange(nodes, change))
254
+
255
+ if (change.parentId) {
256
+ if (!after.has(change.parentId)) return { code: 'tree_parent_missing', message: 'The page above does not exist' }
257
+ // A loop: walking up from the new parent meets the entry itself.
258
+ const up: TreeNode[] = []
259
+ const seen = new Set<string>()
260
+ for (let cur = after.get(change.parentId); cur && !seen.has(cur.id); cur = cur.parentId ? after.get(cur.parentId) : undefined) {
261
+ up.push(cur)
262
+ seen.add(cur.id)
263
+ if (cur.id === change.id) {
264
+ // Read downwards: entry → … → new parent → entry.
265
+ const chain = [...up.map((n) => titleOf(n)).reverse(), titleOf(after.get(change.id))]
266
+ return { code: 'tree_cycle', message: `This would make a loop: ${chain.join(' → ')}`, loop: chain }
267
+ }
268
+ }
269
+ }
270
+
271
+ const children = childrenMap(after.values())
272
+ const depth = depthOf(after, change.id) + heightOf(after, change.id, children)
273
+ if (depth > opts.maxDepth) {
274
+ return { code: 'tree_depth', message: `Pages can be nested ${opts.maxDepth} levels deep at most (this would make ${depth})`, depth, maxDepth: opts.maxDepth }
275
+ }
276
+
277
+ // Addresses of the entry and its descendants, against everyone else's, per language
278
+ // (only entries that exist in that language have an address there).
279
+ const affected = new Set([change.id, ...descendantsOf(after, change.id, children).map((n) => n.id)])
280
+ const def = opts.locales?.default ?? null
281
+ for (const locale of opts.locales ? opts.locales.locales : [null]) {
282
+ const taken = new Map<string, string>()
283
+ const address = (id: string) => treeAddress(opts.locales, opts.template, opts.key, after, id, locale)
284
+ for (const n of after.values()) {
285
+ if (affected.has(n.id) || !existsIn(n, locale, def)) continue
286
+ const path = address(n.id)
287
+ if (path !== null && !taken.has(path)) taken.set(path, n.id)
288
+ }
289
+ for (const id of affected) {
290
+ if (!existsIn(after.get(id)!, locale, def)) continue
291
+ const path = address(id)
292
+ if (path === null) continue
293
+ const other = taken.get(path)
294
+ if (other) {
295
+ return {
296
+ code: 'tree_address_taken', locale, path, otherId: other, otherTitle: titleOf(after.get(other)),
297
+ message: `The address ${path} is already used by “${titleOf(after.get(other))}”`,
298
+ }
299
+ }
300
+ taken.set(path, id) // two of the affected entries on one address
301
+ }
302
+ }
303
+ return null
304
+ }
305
+
306
+ /** An address that changed with a write: where it was and where it is now. */
307
+ export interface MovedPath { id: string; locale: string | null; from: string; to: string }
308
+
309
+ /**
310
+ * The entries (`ids`) whose address differs between two states of the tree, in every
311
+ * language: a page that is not translated is still reachable at the address it falls back
312
+ * to (the tree and the item's `path` give it), so that moves too. An entry that is new has
313
+ * nothing to move from; one that lost its translation moves to the address it now falls
314
+ * back to; one that got its first translation does not move (its default-language address
315
+ * still finds it).
316
+ */
317
+ export function movedPaths(
318
+ before: TreeNode[], after: TreeNode[], ids: string[],
319
+ opts: { locales: LocalesDef | null; template: PathTemplate | undefined | null; key: string },
320
+ ): MovedPath[] {
321
+ const a = indexTree(before)
322
+ const b = indexTree(after)
323
+ const def = opts.locales?.default ?? null
324
+ const out: MovedPath[] = []
325
+ for (const id of ids) {
326
+ const was = a.get(id)
327
+ const now = b.get(id)
328
+ if (!was || !now) continue
329
+ for (const locale of opts.locales ? opts.locales.locales : [null]) {
330
+ // A first translation is not a move: the default-language address it replaced still finds the page.
331
+ if (!existsIn(was, locale, def) && existsIn(now, locale, def)) continue
332
+ const from = treeAddress(opts.locales, opts.template, opts.key, a, id, locale)
333
+ const to = treeAddress(opts.locales, opts.template, opts.key, b, id, locale)
334
+ if (from && to && from !== to) out.push({ id, locale, from, to })
335
+ }
336
+ }
337
+ return out
338
+ }
339
+
340
+ /** A problem found in a whole tree (see `checkTree`); `ids` are the pages it involves. */
341
+ export type TreeIssue =
342
+ | { code: 'tree_cycle'; message: string; ids: string[]; loop: string[] }
343
+ | { code: 'tree_depth'; message: string; ids: string[]; depth: number; maxDepth: number }
344
+ | { code: 'tree_parent_missing'; message: string; ids: string[] }
345
+ | { code: 'tree_address_taken'; message: string; ids: string[]; locale: string | null; path: string }
346
+
347
+ /**
348
+ * Check a whole tree, with the same rules `checkTreeChange` applies to one change: no page
349
+ * is its own ancestor, nothing is deeper than `maxDepth`, every page has an address of
350
+ * its own in each language. For data that did not come through the API (an import).
351
+ * Lists up to `limit` problems; each says which pages it involves.
352
+ */
353
+ export function checkTree(nodes: TreeNode[], opts: TreeCheckOptions, limit = 50): TreeIssue[] {
354
+ const issues: TreeIssue[] = []
355
+ const index = indexTree(nodes)
356
+ const title = (n: TreeNode | undefined) => n?.title || n?.slug || '…'
357
+ const full = () => issues.length >= limit
358
+
359
+ // Pages that reach the top: the others hang below a loop or below a page that is not there.
360
+ const rooted = new Set<string>()
361
+ const state = new Map<string, 'open' | 'done'>()
362
+ for (const start of nodes) {
363
+ if (state.has(start.id)) continue
364
+ const path: TreeNode[] = []
365
+ let cur: TreeNode | undefined = start
366
+ let reachesTop = false
367
+ while (cur) {
368
+ const s = state.get(cur.id)
369
+ if (s === 'done') { reachesTop = rooted.has(cur.id); break }
370
+ if (s === 'open') {
371
+ const loopNodes = path.slice(path.findIndex((n) => n.id === cur!.id))
372
+ if (!full()) {
373
+ const loop = [...loopNodes, loopNodes[0]!].map(title)
374
+ issues.push({ code: 'tree_cycle', message: `A loop: ${loop.join(' → ')}`, ids: loopNodes.map((n) => n.id), loop })
375
+ }
376
+ break
377
+ }
378
+ state.set(cur.id, 'open')
379
+ path.push(cur)
380
+ if (!cur.parentId) { reachesTop = true; break }
381
+ const parent = index.get(cur.parentId)
382
+ if (!parent) {
383
+ if (!full()) issues.push({ code: 'tree_parent_missing', message: `“${title(cur)}” sits under a page that does not exist`, ids: [cur.id] })
384
+ break
385
+ }
386
+ cur = parent
387
+ }
388
+ for (const n of path) { state.set(n.id, 'done'); if (reachesTop) rooted.add(n.id) }
389
+ }
390
+
391
+ const sound = nodes.filter((n) => rooted.has(n.id))
392
+ const children = childrenMap(sound)
393
+ for (const n of sound) {
394
+ if (full()) break
395
+ // The first page too deep names the problem; what is below it only repeats it.
396
+ if (depthOf(index, n.id) !== opts.maxDepth + 1) continue
397
+ const depth = depthOf(index, n.id) + heightOf(index, n.id, children)
398
+ issues.push({
399
+ code: 'tree_depth', ids: chainOf(index, n.id).map((x) => x.id), depth, maxDepth: opts.maxDepth,
400
+ message: `“${title(n)}” and what is below it go ${depth} levels deep (at most ${opts.maxDepth})`,
401
+ })
402
+ }
403
+
404
+ const def = opts.locales?.default ?? null
405
+ for (const locale of opts.locales ? opts.locales.locales : [null]) {
406
+ const byPath = new Map<string, string[]>()
407
+ for (const n of sound) {
408
+ if (!existsIn(n, locale, def)) continue
409
+ const path = treeAddress(opts.locales, opts.template, opts.key, index, n.id, locale)
410
+ if (path !== null) byPath.set(path, [...(byPath.get(path) ?? []), n.id])
411
+ }
412
+ for (const [path, ids] of byPath) {
413
+ if (ids.length < 2 || full()) continue
414
+ issues.push({
415
+ code: 'tree_address_taken', locale, path, ids,
416
+ message: `${ids.length} pages share the address ${path}${locale ? ` (${locale})` : ''}: ${ids.slice(0, 4).map((id) => `“${title(index.get(id))}”`).join(', ')}${ids.length > 4 ? ', …' : ''}`,
417
+ })
418
+ }
419
+ }
420
+ return issues
421
+ }