tinyzoo 0.0.0-stage → 0.2.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 (391) 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 +99 -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 +392 -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/cmsTooMany.ts +9 -0
  312. package/server/utils/cmsTranslationWrite.ts +186 -0
  313. package/server/utils/cmsTree.ts +251 -0
  314. package/server/utils/cmsTreeAddress.ts +65 -0
  315. package/server/utils/cmsUpload.ts +197 -0
  316. package/server/utils/cmsWebhooks.ts +101 -0
  317. package/shared/json.ts +11 -0
  318. package/shared/richtext-editor.ts +56 -0
  319. package/shared/richtext-normalize.ts +33 -0
  320. package/shared/richtext-paste.ts +151 -0
  321. package/shared/storage-delivery.ts +53 -0
  322. package/src/blocks.ts +624 -0
  323. package/src/changes.ts +54 -0
  324. package/src/content-shape.ts +340 -0
  325. package/src/deprecate.ts +64 -0
  326. package/src/descriptor.ts +149 -0
  327. package/src/docs.ts +27 -0
  328. package/src/emitter.ts +94 -0
  329. package/src/entity.ts +624 -0
  330. package/src/errorReport.ts +41 -0
  331. package/src/fields.ts +465 -0
  332. package/src/i18n.ts +26 -0
  333. package/src/index.ts +54 -0
  334. package/src/linkref.ts +31 -0
  335. package/src/links.ts +179 -0
  336. package/src/locales.ts +39 -0
  337. package/src/media.ts +48 -0
  338. package/src/migrate.ts +236 -0
  339. package/src/openapi.ts +377 -0
  340. package/src/paths.ts +88 -0
  341. package/src/plugin.ts +505 -0
  342. package/src/presets.ts +230 -0
  343. package/src/richtext.ts +88 -0
  344. package/src/sdk.ts +181 -0
  345. package/src/search.ts +312 -0
  346. package/src/seed.ts +225 -0
  347. package/src/setupCode.ts +30 -0
  348. package/src/system.ts +219 -0
  349. package/src/tree.ts +421 -0
  350. package/src/upgrades.ts +137 -0
  351. package/starter/.env.example +10 -0
  352. package/starter/README.md +65 -0
  353. package/starter/app/app.config.ts +10 -0
  354. package/starter/app/app.vue +12 -0
  355. package/starter/app/assets/css/main.css +15 -0
  356. package/starter/app/components/global/BlockContact.vue +15 -0
  357. package/starter/app/components/global/BlockCta.vue +15 -0
  358. package/starter/app/components/global/BlockHero.vue +23 -0
  359. package/starter/app/components/global/BlockImage.vue +13 -0
  360. package/starter/app/components/global/BlockText.vue +12 -0
  361. package/starter/app/composables/useSite.ts +77 -0
  362. package/starter/app/error.vue +28 -0
  363. package/starter/app/layouts/default.vue +106 -0
  364. package/starter/app/lib/cms-content.ts +152 -0
  365. package/starter/app/pages/[...slug].vue +66 -0
  366. package/starter/app/pages/hledat.vue +59 -0
  367. package/starter/app/pages/index.vue +20 -0
  368. package/starter/cms.config.ts +137 -0
  369. package/starter/compose.yaml +15 -0
  370. package/starter/drizzle.config.ts +8 -0
  371. package/starter/gitignore.txt +8 -0
  372. package/starter/nuxt.config.ts +13 -0
  373. package/starter/package.json +38 -0
  374. package/starter/scripts/typecheck.mjs +38 -0
  375. package/starter/seed/index.ts +297 -0
  376. package/starter/seed/media/about.jpg +0 -0
  377. package/starter/seed/media/hero.jpg +0 -0
  378. package/starter/seed/media/logo.png +0 -0
  379. package/starter/seed/media/news-bread.jpg +0 -0
  380. package/starter/seed/media/news-morning.jpg +0 -0
  381. package/starter/server/db/migrations/0000_init.sql +269 -0
  382. package/starter/server/db/migrations/0001_page_tree.sql +5 -0
  383. package/starter/server/db/migrations/0002_opening_hours_per_language.sql +1 -0
  384. package/starter/server/db/migrations/meta/0000_snapshot.json +1890 -0
  385. package/starter/server/db/migrations/meta/0001_snapshot.json +1887 -0
  386. package/starter/server/db/migrations/meta/0002_snapshot.json +1893 -0
  387. package/starter/server/db/migrations/meta/_journal.json +27 -0
  388. package/starter/server/db/schema.ts +253 -0
  389. package/starter/server/plugins/sitemap.ts +11 -0
  390. package/starter/server/routes/robots.txt.get.ts +12 -0
  391. package/starter/tsconfig.json +9 -0
@@ -0,0 +1,9 @@
1
+ /**
2
+ * A 429 that says when to come back: `Retry-After` in seconds. The window is what is
3
+ * known here (the oldest hit leaves it sooner, so this is the most a person waits), and
4
+ * it lets a client, a script or the admin say "in 15 minutes" instead of guessing.
5
+ */
6
+ export function tooManyRequests(event: any, message: string, windowMs: number) {
7
+ setResponseHeader(event, 'Retry-After', Math.max(1, Math.ceil(windowMs / 1000)))
8
+ return createError({ statusCode: 429, statusMessage: message })
9
+ }
@@ -0,0 +1,186 @@
1
+ import { and, eq, sql } from 'tinyzoo'
2
+ import type { CmsEntity, CmsRegistry } from 'tinyzoo'
3
+ import { z } from 'zod'
4
+ import type { CmsUser } from './cmsSession'
5
+
6
+ /** The admin's view of one entry in a translation language (GET/PATCH response shape). */
7
+ export async function translationFormRow(db: any, reg: CmsRegistry, e: CmsEntity, row: any, locale: string) {
8
+ const found = (await translationRows(db, e, [row.id], locale)).get(row.id)
9
+ const tr = found ? upgradedCopy(e, found, { admin: true, recordId: row.id }) : found
10
+ row.__defaults = Object.fromEntries(e.localized.map((k) => [k, row[k]]))
11
+ for (const k of e.localized) row[k] = tr?.[k] ?? null
12
+ row.__translated = !!tr
13
+ // The translation's own version: what a translation save is checked against.
14
+ row.__version = tr?.updatedAt ? new Date(tr.updatedAt).toISOString() : null
15
+ return row
16
+ }
17
+
18
+ /** Nothing written: no text, no list items, no blocks (an emptied field means "use the default language"). */
19
+ function emptyTranslationValue(v: unknown): boolean {
20
+ if (v === null || v === undefined || v === '') return true
21
+ if (Array.isArray(v)) return v.length === 0
22
+ if (typeof v === 'object') {
23
+ const o = v as any
24
+ if (o.type === 'doc') return !(o.content ?? []).some((n: any) => n?.type !== 'paragraph' || n.content?.length)
25
+ return Object.keys(o).length === 0
26
+ }
27
+ return false
28
+ }
29
+
30
+ /**
31
+ * Write the translation of one entry: only `.localized()` fields, empty = fall back to
32
+ * the default language. Same access as editing the entry (row rules, and people who
33
+ * cannot publish cannot change a live entry). The entry's own version (updatedAt) stays:
34
+ * the translation has its own, so translating never conflicts with editing the entry
35
+ * — but two people saving the same language do (X-CMS-Version, 409).
36
+ */
37
+ export async function writeTranslation(event: any, e: CmsEntity, id: string, locale: string, user: CmsUser, rowFilter: any) {
38
+ const { db, reg } = useCms()
39
+ const t = e.localesTable
40
+ if (!t) throw createError({ statusCode: 404, statusMessage: 'This content has nothing to translate' })
41
+
42
+ const raw = (await readBody(event)) ?? {}
43
+ // An emptied field means "use the default language".
44
+ const cleaned = Object.fromEntries(Object.entries(raw as Record<string, unknown>).map(([k, v]) => [k, v === '' ? null : v]))
45
+
46
+ const [base] = await db.select().from(e.table).where(both(eq(e.table.id, id), rowFilter))
47
+ if (!base) throw createError({ statusCode: 404, statusMessage: 'Not found or not permitted' })
48
+ assertPublishAllowed(e, user, {}, base)
49
+ const seenBefore = await changeSnapshot(e, id)
50
+
51
+ // The translation as it is now: blocks that are behind or of a type that is gone are only kept when stored already.
52
+ const before = (await translationRows(db, e, [id], locale)).get(id)
53
+ const schema = z.object(Object.fromEntries(e.localized.map((k) => [k, (e.fields[k]!.zod('update', { stored: before?.[k] }) as any).nullable().optional()]))).strict()
54
+ const data: Record<string, unknown> = parseOr422(schema, cleaned)
55
+ const jsonKeys = e.localized.filter((k) => JSON_MEDIA_TYPES.has(e.fields[k]!.type) && k in data)
56
+ const oldMedia = jsonKeys.flatMap((k) => jsonMediaIds(e.fields[k], before?.[k]))
57
+
58
+ const baseTr = baseVersion(event)
59
+ // Saving with nothing written is not translating: no empty row that would make the
60
+ // language count as translated ("Missing: EN" and the publish warning must stay). An
61
+ // existing translation emptied entirely is gone, as if removed.
62
+ const merged: Record<string, unknown> = { ...(before ?? {}), ...data }
63
+ if (e.localized.every((k) => emptyTranslationValue(merged[k]))) {
64
+ if (before) {
65
+ await assertCurrentVersion(e, { updatedAt: before.updatedAt, updatedBy: null }, baseTr)
66
+ await deleteTranslation(event, e, id, locale, user, rowFilter)
67
+ }
68
+ const [bare] = await db.select().from(e.table).where(eq(e.table.id, id))
69
+ await hydrateRowForForm(db, reg, e, bare)
70
+ return translationFormRow(db, reg, e, bare, locale)
71
+ }
72
+ const { row, effect } = await db.transaction(async (tx: any) => {
73
+ // A page tree: the tree lock before any row lock, in the order every tree write takes
74
+ // them (moves and page saves lock the tree, then rows), or two writes can deadlock.
75
+ if (e.tree) await lockTree(tx, e)
76
+ // Touch the entry first, under the same rules as editing it — including "not
77
+ // live" for people who cannot publish, re-checked here at write time (an editor
78
+ // may have published it since we read it).
79
+ // A no-op update: it locks the entry and re-checks access at write time.
80
+ const [touched] = await tx.update(e.table).set({ updatedAt: sql`${e.table.updatedAt}` })
81
+ .where(both(both(eq(e.table.id, id), rowFilter), notLiveCond(e, user))).returning({ id: e.table.id })
82
+ if (!touched) throw createError({ statusCode: 404, statusMessage: 'Not found or not permitted' })
83
+ // The entry is locked now, so this is the translation as it stands.
84
+ const [current] = await tx.select({ updatedAt: t.updatedAt }).from(t).where(and(eq(t.parentId, id), eq(t.locale, locale)))
85
+ if (current) await assertCurrentVersion(e, { updatedAt: current.updatedAt, updatedBy: null }, baseTr)
86
+ // A page tree: a translated address part (or a first translation) changes the address of the
87
+ // page in this language and of every page below it.
88
+ let writeTree: Awaited<ReturnType<typeof beginTreeWrite>> | null = null
89
+ let wasLive = new Set<string>()
90
+ const tp = e.tree ? treeProps(e) : null
91
+ if (tp && (!current || (e.localized.includes(tp.slug) && tp.slug in data))) {
92
+ // The parent and address part come from the tree under the lock, not from `base` (read before it).
93
+ writeTree = await beginTreeWrite(tx, reg, e, (nodes) => {
94
+ const node = nodes.find((n) => n.id === id)
95
+ if (!node) throw createError({ statusCode: 404, statusMessage: 'Not found or not permitted' })
96
+ return {
97
+ id, parentId: node.parentId, slug: node.slug, title: node.title ?? '',
98
+ slugs: { [locale]: e.localized.includes(tp.slug) ? (data[tp.slug] as string | null | undefined) ?? null : null },
99
+ locales: [...new Set([...(node.locales ?? []), locale])],
100
+ }
101
+ }, user)
102
+ wasLive = await liveAmong(tx, e, subtreeIds(writeTree.nodes, id))
103
+ }
104
+ // A new version, never equal to the last one (clocks may differ between replicas).
105
+ const now = new Date(Math.max(Date.now(), current ? new Date(current.updatedAt).getTime() + 1 : 0))
106
+ const [saved] = await tx.insert(t).values({ parentId: id, locale, ...data, updatedAt: now })
107
+ .onConflictDoUpdate({ target: [t.parentId, t.locale], set: { ...data, updatedAt: now } })
108
+ .returning()
109
+ const effect = writeTree ? await treeEffect(tx, reg, e, writeTree.nodes, writeTree.next, id, wasLive, actorId(user)) : null
110
+ // A translated address part (or a first translation) may put the entry where a redirect leaves from: that one goes, in this transaction.
111
+ if (e.content?.path && (!current || pathKeys(e.content.path).some((k) => k in data))) await dropRedirectsFromLiveAddresses(tx, reg, e, id)
112
+ return { row: saved, effect }
113
+ }).catch((err: unknown) => rethrowDbError(err, e, 'write'))
114
+
115
+ if (oldMedia.length) {
116
+ const still = new Set(jsonKeys.flatMap((k) => jsonMediaIds(e.fields[k], row[k])))
117
+ const storage = useCmsStorage()
118
+ for (const mid of new Set(oldMedia)) if (!still.has(mid)) await gcMediaIfOrphan(db, reg, storage, mid, gcScope(user))
119
+ }
120
+ await audit(event, 'entry.translate', { entity: e.name, recordId: id, meta: { locale } })
121
+ await noteCollabSave(event, { entity: e, id, locale }, row.updatedAt)
122
+
123
+ const [fresh] = await db.select().from(e.table).where(eq(e.table.id, id))
124
+ await reportChange(event, { type: 'translation.updated', entity: e, id, locale, before: seenBefore, after: { updatedAt: row.updatedAt }, moved: effect?.moved })
125
+ if (effect) await reportTreeRedirects(event, reg, effect.redirects)
126
+ await hydrateRowForForm(db, reg, e, fresh)
127
+ const result = await translationFormRow(db, reg, e, fresh, locale)
128
+ // Old addresses that now lead to the new one (a translated address part changed): told, so the editor knows.
129
+ if (effect?.redirects.length) result.__redirects = effect.redirects.length
130
+ return result
131
+ }
132
+
133
+ /** Remove one entry's translation (falls back to the default language again). */
134
+ export async function deleteTranslation(event: any, e: CmsEntity, id: string, locale: string, user: CmsUser, rowFilter: any) {
135
+ const { db, reg } = useCms()
136
+ const t = e.localesTable
137
+ if (!t) throw createError({ statusCode: 404, statusMessage: 'This content has nothing to translate' })
138
+ const [base] = await db.select().from(e.table).where(both(eq(e.table.id, id), rowFilter))
139
+ if (!base) throw createError({ statusCode: 404, statusMessage: 'Not found or not permitted' })
140
+ assertPublishAllowed(e, user, {}, base)
141
+ const seenBefore = await changeSnapshot(e, id)
142
+ const { gone, effect } = await db.transaction(async (tx: any) => {
143
+ if (e.tree) await lockTree(tx, e) // the tree lock before the row lock, as every tree write takes them
144
+ const [touched] = await tx.update(e.table).set({ updatedAt: sql`${e.table.updatedAt}` })
145
+ .where(both(both(eq(e.table.id, id), rowFilter), notLiveCond(e, user))).returning({ id: e.table.id })
146
+ if (!touched) throw createError({ statusCode: 404, statusMessage: 'Not found or not permitted' })
147
+ // A page tree: without its translation the page falls back to the default language's address
148
+ // part, and so does every page below it.
149
+ const tp = e.tree ? treeProps(e) : null
150
+ let writeTree: Awaited<ReturnType<typeof beginTreeWrite>> | null = null
151
+ let wasLive = new Set<string>()
152
+ if (tp) {
153
+ writeTree = await beginTreeWrite(tx, reg, e, (nodes) => {
154
+ const node = nodes.find((n) => n.id === id)
155
+ if (!node) throw createError({ statusCode: 404, statusMessage: 'Not found or not permitted' })
156
+ return {
157
+ id, parentId: node.parentId, slug: node.slug, title: node.title ?? '',
158
+ slugs: { [locale]: null },
159
+ locales: (node.locales ?? []).filter((l) => l !== locale),
160
+ }
161
+ }, user)
162
+ wasLive = await liveAmong(tx, e, subtreeIds(writeTree.nodes, id))
163
+ }
164
+ const [deleted]: any[] = await tx.delete(t).where(and(eq(t.parentId, id), eq(t.locale, locale))).returning()
165
+ if (!deleted) throw createError({ statusCode: 404, statusMessage: 'No translation in this language' })
166
+ const effect = writeTree ? await treeEffect(tx, reg, e, writeTree.nodes, writeTree.next, id, wasLive, actorId(user)) : null
167
+ return { gone: deleted, effect }
168
+ })
169
+ const storage = useCmsStorage()
170
+ for (const k of e.localized) {
171
+ for (const mid of new Set(jsonMediaIds(e.fields[k], gone[k]))) await gcMediaIfOrphan(db, reg, storage, mid, gcScope(user))
172
+ }
173
+ await audit(event, 'entry.translation_delete', { entity: e.name, recordId: id, meta: { locale } })
174
+ await dropCollabDocuments(e.name, id, locale)
175
+ await dropTranslationRevisions(e, id, locale)
176
+ await reportChange(event, { type: 'translation.deleted', entity: e, id, locale, before: seenBefore, after: null, moved: effect?.moved })
177
+ if (effect) await reportTreeRedirects(event, reg, effect.redirects)
178
+ return { ok: true }
179
+ }
180
+
181
+ /** Media referenced by all translations of an entry (for cleanup when it is deleted). */
182
+ export async function translationMediaIds(db: any, e: CmsEntity, id: string): Promise<string[]> {
183
+ if (!e.localesTable) return []
184
+ const rows: any[] = await db.select().from(e.localesTable).where(eq(e.localesTable.parentId, id))
185
+ return rows.flatMap((r) => e.localized.flatMap((k) => jsonMediaIds(e.fields[k], r[k])))
186
+ }
@@ -0,0 +1,251 @@
1
+ import { eq, inArray, sql } from 'tinyzoo'
2
+ // Address helpers live apart, without Nitro auto-imports: the CLI (links:convert) uses them too.
3
+ import { loadTreeNodes, treeOptions, treePathIn, treeProps, treeVersions } from './cmsTreeAddress'
4
+ import {
5
+ TREE_POSITION_STEP, applyChange, checkTreeChange, childrenMap, chainOf, descendantsOf, existsIn, indexTree, movedPaths, slugChain, titleIn, treeAddress,
6
+ type CmsEntity, type CmsRegistry, type MovedPath, type TreeChange, type TreeIndex, type TreeNode, type TreeProblem,
7
+ } from 'tinyzoo'
8
+ import type { CmsUser } from './cmsSession'
9
+
10
+ /**
11
+ * The page tree on the server (`definePages({ tree: true })`; the rules themselves are
12
+ * pure and live in src/tree.ts). A tree is small (pages, not posts), so it is read whole,
13
+ * in two queries, whenever an address or a check needs it: nothing is cached, so a move
14
+ * is seen by the very next request on every replica.
15
+ *
16
+ * Addresses go through ONE function, `localePaths` (cmsSitemap.ts), which the sitemap, the
17
+ * change reports, the website's search and the link picker all use; it asks `treeVersions`
18
+ * here for entities that are trees.
19
+ */
20
+
21
+ const LOCK_NAMESPACE = 72_011_050
22
+
23
+ /**
24
+ * The entry's trail from the top of the tree down to itself, in a language: title and
25
+ * address of each. Without `includeDrafts` only live ancestors are listed (`live` holds
26
+ * the ids that are live, ancestors included).
27
+ */
28
+ export function treeBreadcrumbs(reg: CmsRegistry, e: CmsEntity, index: TreeIndex, id: string, locale: string | null, live?: Set<string>): { title: string; path: string }[] {
29
+ const def = reg.locales?.default ?? null
30
+ const out: { title: string; path: string }[] = []
31
+ for (const n of chainOf(index, id)) {
32
+ if (live && !live.has(n.id)) continue
33
+ const path = treePathIn(reg, e, index, n.id, locale)
34
+ if (path) out.push({ title: titleIn(n, locale, def), path })
35
+ }
36
+ return out
37
+ }
38
+
39
+ /**
40
+ * The entry whose chain of address parts ('o-nas/tym') matches `chain` in `locale`, in this
41
+ * order: pages translated into that language, by their translated parts; any page, by the
42
+ * parts it has in that language (the default ones where it is not translated: the address
43
+ * the tree and `paths` give for it); any page by its default-language parts (served in the
44
+ * language asked for, its untranslated texts falling back as for any other collection).
45
+ *
46
+ * With `live` (visitors) only pages in that set can match: a draft's translated part must
47
+ * not hide the live page that falls back to the same address.
48
+ */
49
+ export function findByChain(reg: CmsRegistry, index: TreeIndex, chain: string, locale: string | null, live?: Set<string>): TreeNode | null {
50
+ const def = reg.locales?.default ?? null
51
+ const want = chain.split('/').filter(Boolean).join('/')
52
+ if (!want) return null
53
+ const l = locale && locale !== def && reg.locales?.locales.includes(locale) ? locale : null
54
+ const tries: { lang: string | null; onlyTranslated: boolean }[] = [...(l ? [{ lang: l, onlyTranslated: true }, { lang: l, onlyTranslated: false }] : []), { lang: def, onlyTranslated: false }]
55
+ for (const { lang, onlyTranslated } of tries) {
56
+ for (const n of index.values()) {
57
+ if (live && !live.has(n.id)) continue
58
+ if (onlyTranslated && !existsIn(n, lang, def)) continue
59
+ if (slugChain(index, n.id, lang, def).join('/') === want) return n
60
+ }
61
+ }
62
+ return null
63
+ }
64
+
65
+ /**
66
+ * Which entries this person may read, as ids (null: all of them, no row rule). Titles of
67
+ * the others stay out of every answer that names pages next to the ones asked for: a
68
+ * trail, a conflict, a loop, a list of subpages.
69
+ */
70
+ export async function readableTreeIds(db: any, e: CmsEntity, user: CmsUser): Promise<Set<string> | null> {
71
+ const { allowed, where } = accessWhere(e, 'read', user)
72
+ if (!allowed) return new Set()
73
+ if (!where) return null
74
+ const rows: any[] = await db.select({ id: e.table.id }).from(e.table).where(where)
75
+ return new Set(rows.map((r) => r.id))
76
+ }
77
+
78
+ /** Ids of the live entries (published, every ancestor too, scheduling included). */
79
+ export async function liveTreeIds(db: any, e: CmsEntity): Promise<Set<string>> {
80
+ const rows: any[] = await db.select({ id: e.table.id }).from(e.table).where(publishedCond(e))
81
+ return new Set(rows.map((r) => r.id))
82
+ }
83
+
84
+ /**
85
+ * Lock the tree for the rest of the transaction, so two writes that look at the tree
86
+ * and then change it (a move, a new page under the same parent) cannot both pass.
87
+ */
88
+ export async function lockTree(tx: any, e: CmsEntity): Promise<void> {
89
+ await tx.execute(sql`select pg_advisory_xact_lock(${LOCK_NAMESPACE}, hashtext(${e.name}))`)
90
+ }
91
+
92
+ /** The refusal for a problem found by `checkTreeChange`: 422 on the parent, 409 for a taken address. */
93
+ export function treeError(p: TreeProblem) {
94
+ const taken = p.code === 'tree_address_taken'
95
+ return createError({
96
+ statusCode: taken ? 409 : 422,
97
+ statusMessage: taken ? 'Value already in use' : 'Validation failed',
98
+ data: [{
99
+ path: [taken ? 'slug' : 'parent'],
100
+ // 'unique' is what the admin's duplicate action waits for to try the next "-copy".
101
+ code: taken ? 'unique' : p.code,
102
+ message: p.message,
103
+ ...(p.code === 'tree_cycle' ? { loop: p.loop } : {}),
104
+ ...(p.code === 'tree_depth' ? { depth: p.depth, maxDepth: p.maxDepth } : {}),
105
+ ...(taken ? { address: p.path, locale: p.locale, otherId: p.otherId, otherTitle: p.otherTitle } : {}),
106
+ }],
107
+ })
108
+ }
109
+
110
+ /** The tree as it stands, checked against a change (throws the matching 409/422). */
111
+ export function assertTreeChange(nodes: TreeNode[], reg: CmsRegistry, e: CmsEntity, change: TreeChange, readable?: Set<string> | null): void {
112
+ const problem = checkTreeChange(nodes, change, { ...treeOptions(reg, e), visible: readable ? (id) => readable.has(id) : undefined })
113
+ if (problem) throw treeError(problem)
114
+ }
115
+
116
+ /** Position after the last sibling under a parent (for a new page). Positions are sparse (see `placeAmong`). */
117
+ export function nextPosition(nodes: TreeNode[], parentId: string | null): number {
118
+ const sib = nodes.filter((n) => n.parentId === parentId)
119
+ return sib.length ? Math.max(...sib.map((n) => n.position ?? 0)) + TREE_POSITION_STEP : 0
120
+ }
121
+
122
+ /** What a tree write did to addresses and to what visitors can see: for redirects and the change report. */
123
+ export interface TreeEffect {
124
+ /** Addresses that changed: the entry and everything below it, in every language. */
125
+ moved: MovedPath[]
126
+ /** Redirects written (created or pointed at a new address). */
127
+ redirects: { id: string; from: string; to: string }[]
128
+ }
129
+
130
+ /**
131
+ * Leave redirects for addresses that moved while they were live (the entry and every
132
+ * descendant, in every language): old → new, 301, through `defineRedirects`. A site
133
+ * without redirects gets none (the change report still lists what moved).
134
+ *
135
+ * Redirects that already pointed at an old address are pointed at the new one (no
136
+ * chains), and a redirect from an address something now lives at is removed.
137
+ * Runs in the transaction of the write, so a move and its redirects land together.
138
+ */
139
+ export async function writeTreeRedirects(tx: any, reg: CmsRegistry, moved: MovedPath[], wasLive: Set<string>, isLive: Set<string>, actor: string | null): Promise<TreeEffect['redirects']> {
140
+ const re = redirectEntity(reg)
141
+ const due = moved.filter((m) => wasLive.has(m.id) && isLive.has(m.id))
142
+ if (!re || !due.length) return []
143
+ const table = re.table
144
+ // Something lives at the new addresses now: a redirect away from one would hide it.
145
+ await tx.delete(table).where(inArray(table.from, due.map((m) => m.to)))
146
+ const out: TreeEffect['redirects'] = []
147
+ for (const m of due) {
148
+ // Redirects that led to the old address lead to the new one (a chain would cost visitors a hop each).
149
+ await tx.update(table).set({ to: m.to, updatedAt: sql`now()`, updatedBy: actor }).where(eq(table.to, m.from))
150
+ const [row] = await tx.insert(table).values({ from: m.from, to: m.to, permanent: true, createdBy: actor, updatedBy: actor })
151
+ .onConflictDoUpdate({ target: table.from, set: { to: m.to, permanent: true, updatedAt: sql`now()`, updatedBy: actor } })
152
+ .returning({ id: table.id })
153
+ out.push({ id: row.id, from: m.from, to: m.to })
154
+ }
155
+ invalidateRedirects()
156
+ return out
157
+ }
158
+
159
+ /** Tell the website and the other replicas about redirects written by `writeTreeRedirects`. */
160
+ export async function reportTreeRedirects(event: any, reg: CmsRegistry, redirects: TreeEffect['redirects']): Promise<void> {
161
+ const re = redirectEntity(reg)
162
+ if (!re) return
163
+ for (const r of redirects) await reportChange(event, { type: 'entry.created', entity: re, id: r.id, noRevision: true })
164
+ }
165
+
166
+ /**
167
+ * Everything a write to an entry of a tree needs, in one place: lock the tree, load
168
+ * it, refuse what is wrong (a loop, too deep, an address taken), and — after the caller
169
+ * wrote the change — list what moved. Pass the proposed change; call `after()` once the
170
+ * row is saved, in the same transaction.
171
+ *
172
+ * Anything the request does not set (the address part, the parent) has to come from the
173
+ * nodes loaded under the lock, not from a row read earlier: pass a function of the nodes.
174
+ *
175
+ * With `user`, pages they may not read are not named in a refusal, and a page cannot be
176
+ * put under a parent they may not read (as far as they can tell it does not exist).
177
+ */
178
+ export async function beginTreeWrite(tx: any, reg: CmsRegistry, e: CmsEntity, change: TreeChange | ((nodes: TreeNode[]) => TreeChange), user?: CmsUser) {
179
+ await lockTree(tx, e)
180
+ const nodes = await loadTreeNodes(tx, reg, e)
181
+ const c = typeof change === 'function' ? change(nodes) : change
182
+ const readable = user ? await readableTreeIds(tx, e, user) : null
183
+ // Only a NEW parent has to be readable: a page may stay where it is.
184
+ if (c.parentId && readable && !readable.has(c.parentId) && nodes.find((n) => n.id === c.id)?.parentId !== c.parentId) {
185
+ throw treeError({ code: 'tree_parent_missing', message: 'The page above does not exist' })
186
+ }
187
+ assertTreeChange(nodes, reg, e, c, readable)
188
+ const next = applyChange(nodes, c)
189
+ return { nodes, next, change: c }
190
+ }
191
+
192
+ /** Ids of an entry and everything below it, in a given state of the tree. */
193
+ export function subtreeIds(nodes: TreeNode[], id: string): string[] {
194
+ const index = indexTree(nodes)
195
+ return [id, ...descendantsOf(index, id, childrenMap(nodes)).map((n) => n.id)]
196
+ }
197
+
198
+ /** Which of these entries are live (published, every ancestor too, scheduling included). */
199
+ export async function liveAmong(db: any, e: CmsEntity, ids: string[]): Promise<Set<string>> {
200
+ if (!ids.length) return new Set()
201
+ const rows: any[] = await db.select({ id: e.table.id }).from(e.table).where(both(inArray(e.table.id, ids), publishedCond(e)))
202
+ return new Set(rows.map((r) => r.id))
203
+ }
204
+
205
+ /** What the effect of a write on the tree is: addresses moved and who was live before and after. */
206
+ export async function treeEffect(tx: any, reg: CmsRegistry, e: CmsEntity, before: TreeNode[], after: TreeNode[], id: string, wasLive: Set<string>, actor: string | null): Promise<TreeEffect> {
207
+ const ids = subtreeIds(after, id)
208
+ const moved = movedPaths(before, after, ids, treeOptions(reg, e))
209
+ if (!moved.length) return { moved, redirects: [] }
210
+ const isLive = await liveAmong(tx, e, ids)
211
+ const redirects = await writeTreeRedirects(tx, reg, moved, wasLive, isLive, actor)
212
+ // The report only lists addresses a visitor could have reached or can reach now.
213
+ return { moved: moved.filter((m) => wasLive.has(m.id) || isLive.has(m.id)), redirects }
214
+ }
215
+
216
+ /**
217
+ * Items of a page tree carry `path` (their address in the language served, ancestors'
218
+ * address parts included) and `breadcrumbs` (title and address from the top of the
219
+ * tree down to the page itself). Mirrored by content-shape.
220
+ * Visitors only get live pages and so only live ancestors; with `drafts` (an editor's
221
+ * preview) the trail is the real one, drafts included.
222
+ */
223
+ export async function attachTreeInfo(db: any, reg: CmsRegistry, e: CmsEntity, rows: any[], items: any[], locale: string | null, opts: { drafts?: boolean } = {}): Promise<void> {
224
+ if (!e.tree || !rows.length) return
225
+ const index = indexTree(await loadTreeNodes(db, reg, e))
226
+ // A visitor's trail names live pages only, whatever the stored data looks like.
227
+ const live = opts.drafts ? undefined : await liveTreeIds(db, e)
228
+ rows.forEach((row, i) => {
229
+ items[i].path = treePathIn(reg, e, index, row.id, locale)
230
+ items[i].breadcrumbs = treeBreadcrumbs(reg, e, index, row.id, locale, live)
231
+ })
232
+ }
233
+
234
+ /**
235
+ * Refuse to delete an entry that has pages under it (409, listing a few of them). No cascade:
236
+ * nothing below disappears by accident. `readable` (from `readableTreeIds`): the titles of
237
+ * subpages the person may not read are left out; the count stays.
238
+ */
239
+ export async function assertNoChildren(db: any, e: CmsEntity, id: string, readable?: Set<string> | null): Promise<void> {
240
+ const p = treeProps(e)
241
+ const kids: any[] = await db.select({ id: e.table.id, title: e.table[p.title] }).from(e.table).where(eq(e.table[p.parent], id)).limit(6)
242
+ if (!kids.length) return
243
+ const [{ count }] = await db.select({ count: sql<number>`count(*)::int` }).from(e.table).where(eq(e.table[p.parent], id))
244
+ throw createError({
245
+ statusCode: 409, statusMessage: 'This page has pages under it; move or delete them first',
246
+ data: {
247
+ code: 'has_children', count,
248
+ children: kids.slice(0, 5).map((k) => (readable && !readable.has(k.id) ? { id: k.id, title: '' } : { id: k.id, title: k.title == null ? '' : String(k.title) })),
249
+ },
250
+ })
251
+ }
@@ -0,0 +1,65 @@
1
+ import { existsIn, inArray, treeAddress } from 'tinyzoo'
2
+ import type { CmsEntity, CmsRegistry, TreeIndex, TreeNode } from 'tinyzoo'
3
+
4
+ // The page tree's addresses, with explicit imports only (no Nitro auto-imports), so the
5
+ // CLI (`tinyzoo links:convert`) can resolve links to pages in a tree too. The rest of
6
+ // the tree's server logic is in cmsTree.ts.
7
+
8
+ /** Property keys of a tree entity's columns. */
9
+ export function treeProps(e: CmsEntity) {
10
+ const tree = e.tree!
11
+ return { parent: `${tree.parent}Id`, order: tree.order, slug: e.content!.slug!, title: e.titleField }
12
+ }
13
+
14
+ /** Every entry of the tree as a node: parent, address parts and titles in every language, position. */
15
+ export async function loadTreeNodes(db: any, reg: CmsRegistry, e: CmsEntity): Promise<TreeNode[]> {
16
+ const p = treeProps(e)
17
+ const rows: any[] = await db.select({
18
+ id: e.table.id, parentId: e.table[p.parent], slug: e.table[p.slug], title: e.table[p.title], position: e.table[p.order],
19
+ }).from(e.table)
20
+ const nodes = new Map<string, TreeNode>(rows.map((r) => [r.id, {
21
+ id: r.id, parentId: r.parentId ?? null, slug: String(r.slug ?? ''), title: r.title == null ? '' : String(r.title),
22
+ position: Number(r.position ?? 0), slugs: {}, titles: {}, locales: [],
23
+ }]))
24
+ const t = e.localesTable
25
+ const others = reg.locales?.locales.filter((l) => l !== reg.locales!.default) ?? []
26
+ if (t && others.length && nodes.size) {
27
+ const cols: Record<string, any> = { parentId: t.parentId, locale: t.locale }
28
+ if (e.localized.includes(p.slug)) cols.slug = t[p.slug]
29
+ if (e.localized.includes(p.title)) cols.title = t[p.title]
30
+ const trs: any[] = await db.select(cols).from(t).where(inArray(t.locale, others))
31
+ for (const tr of trs) {
32
+ const n = nodes.get(tr.parentId)
33
+ if (!n) continue
34
+ n.locales!.push(tr.locale)
35
+ if ('slug' in tr) n.slugs![tr.locale] = tr.slug
36
+ if ('title' in tr) n.titles![tr.locale] = tr.title
37
+ }
38
+ }
39
+ return [...nodes.values()]
40
+ }
41
+
42
+ /** Settings the pure checks need, from the entity. */
43
+ export function treeOptions(reg: CmsRegistry, e: CmsEntity) {
44
+ return { maxDepth: e.tree!.maxDepth, locales: reg.locales, template: e.content!.path, key: e.content!.slug! }
45
+ }
46
+
47
+ /** One entry's addresses: the default language and every language it is translated into. */
48
+ export function treeVersions(reg: CmsRegistry, e: CmsEntity, index: TreeIndex, id: string): { locale: string | null; loc: string }[] {
49
+ const node = index.get(id)
50
+ if (!node) return []
51
+ const { locales, template, key } = treeOptions(reg, e)
52
+ const out: { locale: string | null; loc: string }[] = []
53
+ for (const locale of locales ? locales.locales : [null]) {
54
+ if (!existsIn(node, locale, locales?.default ?? null)) continue
55
+ const loc = treeAddress(locales, template, key, index, id, locale)
56
+ if (loc) out.push({ locale, loc })
57
+ }
58
+ return out
59
+ }
60
+
61
+ /** The address of an entry in one language (its fallback parts included), or null. */
62
+ export function treePathIn(reg: CmsRegistry, e: CmsEntity, index: TreeIndex, id: string, locale: string | null): string | null {
63
+ const { locales, template, key } = treeOptions(reg, e)
64
+ return treeAddress(locales, template, key, index, id, locale && locales?.locales.includes(locale) ? locale : locales?.default ?? null)
65
+ }