@cossackframework/cms 0.0.0 → 0.9.2

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 (427) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +145 -2
  3. package/agent-docs.json +259 -0
  4. package/app/README.md +78 -0
  5. package/app/cossack-recipe.json +43 -0
  6. package/app/src/auth-bot-check.ts +32 -0
  7. package/app/src/auth-bot-token.ts +11 -0
  8. package/app/src/auth-input.ts +35 -0
  9. package/app/src/auth-options.ts +21 -0
  10. package/app/src/auth-providers.ts +16 -0
  11. package/app/src/auth.ts +1082 -0
  12. package/app/src/brand.ts +68 -0
  13. package/app/src/cms/ai.ts +54 -0
  14. package/app/src/cms/analytics.ts +33 -0
  15. package/app/src/cms/block-errors.ts +55 -0
  16. package/app/src/cms/block-inserter.ts +111 -0
  17. package/app/src/cms/block-panel.ts +68 -0
  18. package/app/src/cms/block-rows.ts +44 -0
  19. package/app/src/cms/block-tree.ts +585 -0
  20. package/app/src/cms/blocks.css +709 -0
  21. package/app/src/cms/builder.ts +126 -0
  22. package/app/src/cms/cache.ts +44 -0
  23. package/app/src/cms/carousel.client.ts +52 -0
  24. package/app/src/cms/collab/presence.ts +69 -0
  25. package/app/src/cms/collab/rich-text-collab.client.ts +197 -0
  26. package/app/src/cms/collab/rich-text-notes.client.ts +138 -0
  27. package/app/src/cms/collab/room.ts +881 -0
  28. package/app/src/cms/compare.client.ts +47 -0
  29. package/app/src/cms/condition-control.ts +109 -0
  30. package/app/src/cms/content-api.ts +143 -0
  31. package/app/src/cms/content.ts +524 -0
  32. package/app/src/cms/countdown.client.ts +37 -0
  33. package/app/src/cms/editor-layout-editor.ts +260 -0
  34. package/app/src/cms/editor-layout-view.ts +37 -0
  35. package/app/src/cms/editor.ts +381 -0
  36. package/app/src/cms/entry.ts +26 -0
  37. package/app/src/cms/feeds.ts +145 -0
  38. package/app/src/cms/field-controls.ts +222 -0
  39. package/app/src/cms/field-group-editor.ts +105 -0
  40. package/app/src/cms/field-group-view.ts +211 -0
  41. package/app/src/cms/form-view.ts +203 -0
  42. package/app/src/cms/form.client.ts +203 -0
  43. package/app/src/cms/guards.ts +27 -0
  44. package/app/src/cms/handoff.ts +202 -0
  45. package/app/src/cms/headings.ts +51 -0
  46. package/app/src/cms/icons.ts +80 -0
  47. package/app/src/cms/import.client.ts +16 -0
  48. package/app/src/cms/index.ts +191 -0
  49. package/app/src/cms/lightbox.client.ts +114 -0
  50. package/app/src/cms/machine.ts +118 -0
  51. package/app/src/cms/maintenance.ts +97 -0
  52. package/app/src/cms/manage.ts +1236 -0
  53. package/app/src/cms/mcp-tools.ts +388 -0
  54. package/app/src/cms/mcp.ts +242 -0
  55. package/app/src/cms/media-chooser.ts +123 -0
  56. package/app/src/cms/media-usage.ts +57 -0
  57. package/app/src/cms/middleware.ts +199 -0
  58. package/app/src/cms/middlewares.ts +13 -0
  59. package/app/src/cms/network-ui.ts +36 -0
  60. package/app/src/cms/network-view.ts +38 -0
  61. package/app/src/cms/notes-announce.ts +65 -0
  62. package/app/src/cms/notes-rail.ts +207 -0
  63. package/app/src/cms/notification-rules.ts +66 -0
  64. package/app/src/cms/recovery.ts +82 -0
  65. package/app/src/cms/replace.ts +63 -0
  66. package/app/src/cms/reserved-paths.ts +19 -0
  67. package/app/src/cms/rich-text-field.ts +325 -0
  68. package/app/src/cms/rich-text-schema.ts +91 -0
  69. package/app/src/cms/rich-text.client.ts +255 -0
  70. package/app/src/cms/search.client.ts +116 -0
  71. package/app/src/cms/seo-head.ts +78 -0
  72. package/app/src/cms/seo.ts +241 -0
  73. package/app/src/cms/settings-draft.ts +218 -0
  74. package/app/src/cms/settings-file.ts +127 -0
  75. package/app/src/cms/settings-form.ts +180 -0
  76. package/app/src/cms/settings-languages.ts +125 -0
  77. package/app/src/cms/settings-nav.ts +102 -0
  78. package/app/src/cms/settings-network.ts +151 -0
  79. package/app/src/cms/settings-permalinks.ts +114 -0
  80. package/app/src/cms/settings-scroll.ts +10 -0
  81. package/app/src/cms/settings-search.ts +77 -0
  82. package/app/src/cms/settings-section.ts +38 -0
  83. package/app/src/cms/share.client.ts +27 -0
  84. package/app/src/cms/site-editing.ts +219 -0
  85. package/app/src/cms/site-editor.client.ts +1008 -0
  86. package/app/src/cms/site-editor.ts +99 -0
  87. package/app/src/cms/site-export.ts +60 -0
  88. package/app/src/cms/site-forms.ts +143 -0
  89. package/app/src/cms/site-import.ts +28 -0
  90. package/app/src/cms/site-session.ts +36 -0
  91. package/app/src/cms/site-taskbar.ts +77 -0
  92. package/app/src/cms/site-view.ts +1014 -0
  93. package/app/src/cms/site.ts +1322 -0
  94. package/app/src/cms/sitemaps.ts +131 -0
  95. package/app/src/cms/stat.client.ts +56 -0
  96. package/app/src/cms/style-controls.ts +252 -0
  97. package/app/src/cms/tabs.client.ts +36 -0
  98. package/app/src/cms/taskbar.ts +134 -0
  99. package/app/src/cms/term-icons.ts +10 -0
  100. package/app/src/cms/traffic.ts +26 -0
  101. package/app/src/cms/ui.ts +170 -0
  102. package/app/src/cms/updates.ts +124 -0
  103. package/app/src/cms/uploads.ts +26 -0
  104. package/app/src/cms/worker.ts +13 -0
  105. package/app/src/config/auth.ts +30 -0
  106. package/app/src/config/cms.ts +18 -0
  107. package/app/src/dashboard/access.ts +344 -0
  108. package/app/src/dashboard/agent-icons.ts +44 -0
  109. package/app/src/dashboard/app-passwords.ts +62 -0
  110. package/app/src/dashboard/avatar-field.ts +58 -0
  111. package/app/src/dashboard/bulk.ts +22 -0
  112. package/app/src/dashboard/head.ts +29 -0
  113. package/app/src/dashboard/icons.ts +15 -0
  114. package/app/src/dashboard/list-table.ts +28 -0
  115. package/app/src/dashboard/modules/roles.ts +15 -0
  116. package/app/src/dashboard/modules/sessions.ts +15 -0
  117. package/app/src/dashboard/modules/settings.ts +15 -0
  118. package/app/src/dashboard/modules/users.ts +18 -0
  119. package/app/src/dashboard/page.ts +67 -0
  120. package/app/src/dashboard/registry.ts +18 -0
  121. package/app/src/dashboard/session-list.ts +98 -0
  122. package/app/src/dashboard/tabs.ts +2 -0
  123. package/app/src/dashboard/time-ago.ts +16 -0
  124. package/app/src/dashboard/types.ts +43 -0
  125. package/app/src/dashboard/user-sections.ts +172 -0
  126. package/app/src/lib/permissions.ts +84 -0
  127. package/app/src/middlewares/auth.ts +117 -0
  128. package/app/src/pages/(site)/[...path]/index.ts +609 -0
  129. package/app/src/pages/(site)/feed/[...rest]/index.ts +13 -0
  130. package/app/src/pages/(site)/feed/index.ts +12 -0
  131. package/app/src/pages/(site)/index.ts +11 -0
  132. package/app/src/pages/(site)/indexnow/[file]/index.ts +18 -0
  133. package/app/src/pages/(site)/layout.ts +219 -0
  134. package/app/src/pages/(site)/llms.txt/index.ts +23 -0
  135. package/app/src/pages/(site)/manifest.webmanifest/index.ts +29 -0
  136. package/app/src/pages/(site)/media/[id]/[name]/index.ts +59 -0
  137. package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +115 -0
  138. package/app/src/pages/(site)/robots.txt/index.ts +29 -0
  139. package/app/src/pages/(site)/search/index.ts +36 -0
  140. package/app/src/pages/(site)/sitemap.xml/index.ts +26 -0
  141. package/app/src/pages/(site)/sitemaps/[file]/index.ts +33 -0
  142. package/app/src/pages/api/auth/session.ts +48 -0
  143. package/app/src/pages/api/cms/appearance/areas/[name].ts +12 -0
  144. package/app/src/pages/api/cms/appearance/areas/index.ts +6 -0
  145. package/app/src/pages/api/cms/appearance/locations/[location].ts +6 -0
  146. package/app/src/pages/api/cms/appearance/locations/index.ts +6 -0
  147. package/app/src/pages/api/cms/appearance/menus/[id].ts +12 -0
  148. package/app/src/pages/api/cms/appearance/menus/index.ts +13 -0
  149. package/app/src/pages/api/cms/appearance/themes/[name]/activate.ts +6 -0
  150. package/app/src/pages/api/cms/appearance/themes/index.ts +6 -0
  151. package/app/src/pages/api/cms/cache/purge.ts +6 -0
  152. package/app/src/pages/api/cms/collections/index.ts +6 -0
  153. package/app/src/pages/api/cms/commands/[plugin]/[command].ts +26 -0
  154. package/app/src/pages/api/cms/comments/[id].ts +9 -0
  155. package/app/src/pages/api/cms/comments/index.ts +126 -0
  156. package/app/src/pages/api/cms/comments/queue.ts +6 -0
  157. package/app/src/pages/api/cms/content/[collection]/[entry]/autosave.ts +27 -0
  158. package/app/src/pages/api/cms/content/[collection]/[entry]/blocks/[block].ts +16 -0
  159. package/app/src/pages/api/cms/content/[collection]/[entry]/notes.ts +18 -0
  160. package/app/src/pages/api/cms/content/[collection]/[entry]/publish.ts +11 -0
  161. package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/[revision]/index.ts +6 -0
  162. package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/[revision]/restore.ts +6 -0
  163. package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/index.ts +6 -0
  164. package/app/src/pages/api/cms/content/[collection]/[entry]/unpublish.ts +6 -0
  165. package/app/src/pages/api/cms/content/[collection]/[entry].ts +42 -0
  166. package/app/src/pages/api/cms/content/[collection]/index.ts +24 -0
  167. package/app/src/pages/api/cms/export/[collection].ts +37 -0
  168. package/app/src/pages/api/cms/forms/[slug]/index.ts +173 -0
  169. package/app/src/pages/api/cms/forms/[slug]/submissions/[submission]/files/[file].ts +25 -0
  170. package/app/src/pages/api/cms/forms/[slug]/submissions/export.ts +34 -0
  171. package/app/src/pages/api/cms/forms/[slug]/submissions/index.ts +24 -0
  172. package/app/src/pages/api/cms/import/[collection].ts +23 -0
  173. package/app/src/pages/api/cms/mcp.ts +29 -0
  174. package/app/src/pages/api/cms/me/index.ts +6 -0
  175. package/app/src/pages/api/cms/me/recent-blocks.ts +37 -0
  176. package/app/src/pages/api/cms/me/tokens/[id].ts +6 -0
  177. package/app/src/pages/api/cms/me/tokens/index.ts +13 -0
  178. package/app/src/pages/api/cms/media/[id].ts +6 -0
  179. package/app/src/pages/api/cms/media.ts +26 -0
  180. package/app/src/pages/api/cms/menus/[location].ts +14 -0
  181. package/app/src/pages/api/cms/network/sites/[id]/export.ts +15 -0
  182. package/app/src/pages/api/cms/network/sites/[id]/index.ts +9 -0
  183. package/app/src/pages/api/cms/network/sites/index.ts +14 -0
  184. package/app/src/pages/api/cms/notes/[id].ts +13 -0
  185. package/app/src/pages/api/cms/notes/index.ts +6 -0
  186. package/app/src/pages/api/cms/payments/webhook.ts +28 -0
  187. package/app/src/pages/api/cms/plugins/[name]/grant.ts +6 -0
  188. package/app/src/pages/api/cms/plugins/[name]/revoke.ts +6 -0
  189. package/app/src/pages/api/cms/plugins/index.ts +6 -0
  190. package/app/src/pages/api/cms/recovery.ts +29 -0
  191. package/app/src/pages/api/cms/redirects/index.ts +9 -0
  192. package/app/src/pages/api/cms/roles/index.ts +6 -0
  193. package/app/src/pages/api/cms/schema/[collection].ts +13 -0
  194. package/app/src/pages/api/cms/search.ts +16 -0
  195. package/app/src/pages/api/cms/settings/[group].ts +9 -0
  196. package/app/src/pages/api/cms/settings/index.ts +9 -0
  197. package/app/src/pages/api/cms/site-export.ts +34 -0
  198. package/app/src/pages/api/cms/taxonomies/index.ts +6 -0
  199. package/app/src/pages/api/cms/terms/[taxonomy]/[id].ts +12 -0
  200. package/app/src/pages/api/cms/terms/[taxonomy]/index.ts +9 -0
  201. package/app/src/pages/api/cms/uploads/[id]/complete.ts +15 -0
  202. package/app/src/pages/api/cms/uploads/[id]/index.ts +15 -0
  203. package/app/src/pages/api/cms/uploads/index.ts +26 -0
  204. package/app/src/pages/api/cms/users/[id]/index.ts +12 -0
  205. package/app/src/pages/api/cms/users/[id]/meta.ts +40 -0
  206. package/app/src/pages/api/cms/users/index.ts +12 -0
  207. package/app/src/pages/api/cms/webhooks/[id].ts +6 -0
  208. package/app/src/pages/api/cms/webhooks/index.ts +9 -0
  209. package/app/src/pages/auth/[provider]/callback.ts +11 -0
  210. package/app/src/pages/auth/[provider]/redirect.ts +9 -0
  211. package/app/src/pages/auth/forgot-password/index.ts +82 -0
  212. package/app/src/pages/auth/layout.ts +32 -0
  213. package/app/src/pages/auth/login/index.ts +205 -0
  214. package/app/src/pages/auth/magic/index.ts +68 -0
  215. package/app/src/pages/auth/register/index.ts +124 -0
  216. package/app/src/pages/auth/reset-password/index.ts +74 -0
  217. package/app/src/pages/auth/setup/index.ts +194 -0
  218. package/app/src/pages/auth/two-factor/index.ts +69 -0
  219. package/app/src/pages/auth/verify/index.ts +62 -0
  220. package/app/src/pages/dashboard/(cms)/appearance/customize/index.ts +263 -0
  221. package/app/src/pages/dashboard/(cms)/appearance/dashboard-menu/index.ts +241 -0
  222. package/app/src/pages/dashboard/(cms)/appearance/index.ts +89 -0
  223. package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +697 -0
  224. package/app/src/pages/dashboard/(cms)/appearance/menus/index.ts +145 -0
  225. package/app/src/pages/dashboard/(cms)/appearance/widgets/index.ts +279 -0
  226. package/app/src/pages/dashboard/(cms)/blocks/index.ts +84 -0
  227. package/app/src/pages/dashboard/(cms)/calendar/index.ts +92 -0
  228. package/app/src/pages/dashboard/(cms)/collections/[name]/index.ts +525 -0
  229. package/app/src/pages/dashboard/(cms)/collections/index.ts +72 -0
  230. package/app/src/pages/dashboard/(cms)/collections/new/index.ts +66 -0
  231. package/app/src/pages/dashboard/(cms)/comments/index.ts +237 -0
  232. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +2382 -0
  233. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +126 -0
  234. package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +693 -0
  235. package/app/src/pages/dashboard/(cms)/field-groups/[id]/index.ts +193 -0
  236. package/app/src/pages/dashboard/(cms)/field-groups/index.ts +65 -0
  237. package/app/src/pages/dashboard/(cms)/forms/[id]/submissions/[submission]/index.ts +279 -0
  238. package/app/src/pages/dashboard/(cms)/forms/[id]/submissions/index.ts +170 -0
  239. package/app/src/pages/dashboard/(cms)/forms/index.ts +171 -0
  240. package/app/src/pages/dashboard/(cms)/media/[id]/index.ts +317 -0
  241. package/app/src/pages/dashboard/(cms)/media/index.ts +156 -0
  242. package/app/src/pages/dashboard/(cms)/media/new/index.ts +9 -0
  243. package/app/src/pages/dashboard/(cms)/media/summary/index.ts +74 -0
  244. package/app/src/pages/dashboard/(cms)/my-sites/index.ts +63 -0
  245. package/app/src/pages/dashboard/(cms)/network/index.ts +53 -0
  246. package/app/src/pages/dashboard/(cms)/network/plugins/index.ts +110 -0
  247. package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +243 -0
  248. package/app/src/pages/dashboard/(cms)/network/sites/index.ts +186 -0
  249. package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +77 -0
  250. package/app/src/pages/dashboard/(cms)/network/themes/index.ts +82 -0
  251. package/app/src/pages/dashboard/(cms)/network/updates/index.ts +48 -0
  252. package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +176 -0
  253. package/app/src/pages/dashboard/(cms)/network/users/index.ts +174 -0
  254. package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +66 -0
  255. package/app/src/pages/dashboard/(cms)/plugins/index.ts +172 -0
  256. package/app/src/pages/dashboard/(cms)/profile/public/index.ts +105 -0
  257. package/app/src/pages/dashboard/(cms)/registrations/index.ts +70 -0
  258. package/app/src/pages/dashboard/(cms)/settings/index.ts +359 -0
  259. package/app/src/pages/dashboard/(cms)/settings/json/index.ts +202 -0
  260. package/app/src/pages/dashboard/(cms)/settings/layout.ts +67 -0
  261. package/app/src/pages/dashboard/(cms)/taxonomies/[name]/index.ts +85 -0
  262. package/app/src/pages/dashboard/(cms)/taxonomies/index.ts +98 -0
  263. package/app/src/pages/dashboard/(cms)/terms/[taxonomy]/[id]/index.ts +244 -0
  264. package/app/src/pages/dashboard/(cms)/terms/[taxonomy]/index.ts +148 -0
  265. package/app/src/pages/dashboard/(cms)/tools/activity/index.ts +94 -0
  266. package/app/src/pages/dashboard/(cms)/tools/automations/index.ts +131 -0
  267. package/app/src/pages/dashboard/(cms)/tools/cache/index.ts +92 -0
  268. package/app/src/pages/dashboard/(cms)/tools/export/index.ts +99 -0
  269. package/app/src/pages/dashboard/(cms)/tools/health/index.ts +189 -0
  270. package/app/src/pages/dashboard/(cms)/tools/jobs/index.ts +93 -0
  271. package/app/src/pages/dashboard/(cms)/tools/links/index.ts +115 -0
  272. package/app/src/pages/dashboard/(cms)/tools/redirects/index.ts +161 -0
  273. package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +124 -0
  274. package/app/src/pages/dashboard/(cms)/tools/schema/index.ts +54 -0
  275. package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +156 -0
  276. package/app/src/pages/dashboard/(cms)/tools/updates/index.ts +114 -0
  277. package/app/src/pages/dashboard/(cms)/tools/webhooks/index.ts +183 -0
  278. package/app/src/pages/dashboard/index.ts +214 -0
  279. package/app/src/pages/dashboard/layout.ts +227 -0
  280. package/app/src/pages/dashboard/profile/index.ts +211 -0
  281. package/app/src/pages/dashboard/profile/security/index.ts +249 -0
  282. package/app/src/pages/dashboard/roles/[id]/index.ts +116 -0
  283. package/app/src/pages/dashboard/roles/index.ts +134 -0
  284. package/app/src/pages/dashboard/roles/new/index.ts +95 -0
  285. package/app/src/pages/dashboard/sessions/index.ts +105 -0
  286. package/app/src/pages/dashboard/users/[id]/index.ts +472 -0
  287. package/app/src/pages/dashboard/users/index.ts +299 -0
  288. package/app/src/pages/dashboard/users/new/index.ts +123 -0
  289. package/app/src/passkeys.client.ts +18 -0
  290. package/app/src/plugins/default-theme/assets/cover.svg +31 -0
  291. package/app/src/plugins/default-theme/assets/logo.svg +8 -0
  292. package/app/src/plugins/default-theme/parts/comments.ts +66 -0
  293. package/app/src/plugins/default-theme/parts/list.ts +38 -0
  294. package/app/src/plugins/default-theme/parts/media.ts +15 -0
  295. package/app/src/plugins/default-theme/parts/options.ts +45 -0
  296. package/app/src/plugins/default-theme/plugin.json +275 -0
  297. package/app/src/plugins/default-theme/templates/archive.ts +14 -0
  298. package/app/src/plugins/default-theme/templates/entry-blank.ts +13 -0
  299. package/app/src/plugins/default-theme/templates/entry.ts +27 -0
  300. package/app/src/plugins/default-theme/templates/home.ts +8 -0
  301. package/app/src/plugins/default-theme/templates/layout.ts +40 -0
  302. package/app/src/plugins/default-theme/templates/not-found.ts +10 -0
  303. package/app/src/plugins/default-theme/templates/search.ts +32 -0
  304. package/app/src/services/rbac.ts +65 -0
  305. package/app/src/services/roles.ts +89 -0
  306. package/app/src/services/users.ts +173 -0
  307. package/package.json +114 -2
  308. package/src/automations.ts +95 -0
  309. package/src/bindings.ts +138 -0
  310. package/src/block-references.ts +239 -0
  311. package/src/block-shape.ts +155 -0
  312. package/src/blocks.ts +1157 -0
  313. package/src/cache.ts +54 -0
  314. package/src/checks.ts +198 -0
  315. package/src/cloudflare-workers.d.ts +13 -0
  316. package/src/cloudflare.ts +61 -0
  317. package/src/collab.ts +372 -0
  318. package/src/collections.ts +421 -0
  319. package/src/comments.ts +46 -0
  320. package/src/cron.ts +95 -0
  321. package/src/dashboard-menu.ts +105 -0
  322. package/src/diff.ts +113 -0
  323. package/src/editor-layout.ts +316 -0
  324. package/src/errors.ts +50 -0
  325. package/src/field-groups.ts +498 -0
  326. package/src/fields.ts +411 -0
  327. package/src/form-builder.ts +1053 -0
  328. package/src/forms.ts +109 -0
  329. package/src/highlight.ts +134 -0
  330. package/src/hooks.ts +510 -0
  331. package/src/icon-catalog.ts +55 -0
  332. package/src/icons.ts +128 -0
  333. package/src/images.ts +149 -0
  334. package/src/index.ts +100 -0
  335. package/src/isolate-core.ts +245 -0
  336. package/src/isolate.ts +19 -0
  337. package/src/isolation.ts +69 -0
  338. package/src/mail.ts +182 -0
  339. package/src/manifest.ts +476 -0
  340. package/src/media.ts +193 -0
  341. package/src/menus.ts +287 -0
  342. package/src/module.ts +32 -0
  343. package/src/modules/content.ts +64 -0
  344. package/src/modules/forms.ts +35 -0
  345. package/src/node.ts +66 -0
  346. package/src/notes.ts +237 -0
  347. package/src/permissions.ts +139 -0
  348. package/src/plugin-settings.ts +114 -0
  349. package/src/records.ts +56 -0
  350. package/src/redirects.ts +59 -0
  351. package/src/resource.ts +245 -0
  352. package/src/richtext.ts +402 -0
  353. package/src/schema-json.ts +112 -0
  354. package/src/search.ts +89 -0
  355. package/src/seo.ts +477 -0
  356. package/src/server/accounts.ts +418 -0
  357. package/src/server/ai.ts +33 -0
  358. package/src/server/api-tokens.ts +91 -0
  359. package/src/server/areas.ts +116 -0
  360. package/src/server/audit.ts +94 -0
  361. package/src/server/auth.ts +89 -0
  362. package/src/server/automations.ts +190 -0
  363. package/src/server/autosaves.ts +69 -0
  364. package/src/server/brand-icons.ts +50 -0
  365. package/src/server/brands.ts +86 -0
  366. package/src/server/budget.ts +97 -0
  367. package/src/server/cache.ts +104 -0
  368. package/src/server/capabilities.ts +333 -0
  369. package/src/server/cloudflare.ts +92 -0
  370. package/src/server/comments.ts +237 -0
  371. package/src/server/drafts.ts +176 -0
  372. package/src/server/field-groups.ts +88 -0
  373. package/src/server/files.ts +780 -0
  374. package/src/server/forms.ts +726 -0
  375. package/src/server/handoffs.ts +107 -0
  376. package/src/server/host-schema.ts +312 -0
  377. package/src/server/host.ts +2892 -0
  378. package/src/server/images.ts +34 -0
  379. package/src/server/index.ts +59 -0
  380. package/src/server/indexnow.ts +91 -0
  381. package/src/server/isolation.ts +183 -0
  382. package/src/server/locked.ts +45 -0
  383. package/src/server/mail.ts +93 -0
  384. package/src/server/markdown.ts +24 -0
  385. package/src/server/menus.ts +286 -0
  386. package/src/server/network-policy.ts +60 -0
  387. package/src/server/network.ts +665 -0
  388. package/src/server/notes.ts +275 -0
  389. package/src/server/outbox.ts +213 -0
  390. package/src/server/path-moves.ts +33 -0
  391. package/src/server/payments.ts +59 -0
  392. package/src/server/previews.ts +62 -0
  393. package/src/server/purge.ts +140 -0
  394. package/src/server/reconcile.ts +38 -0
  395. package/src/server/redirects.ts +183 -0
  396. package/src/server/repository.ts +1107 -0
  397. package/src/server/schedules.ts +105 -0
  398. package/src/server/schema.ts +562 -0
  399. package/src/server/security.ts +391 -0
  400. package/src/server/seed.ts +52 -0
  401. package/src/server/shared-fields.ts +34 -0
  402. package/src/server/site-export.ts +151 -0
  403. package/src/server/site-import.ts +482 -0
  404. package/src/server/site-search.ts +289 -0
  405. package/src/server/site-settings.ts +286 -0
  406. package/src/server/sites.ts +243 -0
  407. package/src/server/stores.ts +314 -0
  408. package/src/server/stripe.ts +173 -0
  409. package/src/server/taxonomies.ts +415 -0
  410. package/src/server/tokens.ts +25 -0
  411. package/src/server/traffic.ts +118 -0
  412. package/src/server/users.ts +653 -0
  413. package/src/server/webhooks.ts +245 -0
  414. package/src/settings-controls.ts +54 -0
  415. package/src/settings-document.ts +111 -0
  416. package/src/settings.ts +426 -0
  417. package/src/storage/cloudflare.ts +94 -0
  418. package/src/storage/index.ts +30 -0
  419. package/src/storage/node.ts +114 -0
  420. package/src/taxonomy.ts +51 -0
  421. package/src/theme.ts +1135 -0
  422. package/src/to-markdown.ts +179 -0
  423. package/src/updates.ts +126 -0
  424. package/src/version.ts +2 -0
  425. package/src/vite.d.ts +25 -0
  426. package/src/vite.js +199 -0
  427. package/src/webhooks.ts +107 -0
@@ -0,0 +1,289 @@
1
+ /**
2
+ * The site's search index: one `cms_search` document per entry an anonymous visitor may read
3
+ * (published, not protected, not members-only, in a collection with a path on the site), with
4
+ * one full-text index over its title and text. One index ranks every collection together, pages
5
+ * with OFFSET, and holds nothing locked. The collections' own indexes stay for the dashboard.
6
+ *
7
+ * Each entry write keeps its row in step in the same batch, guarded by the write's audit row, and
8
+ * copies the text from the entry document inside the statement, so the request carries no extra
9
+ * text. `search.rebuild` fills the index from scratch in rounds of 200 entries from the outbox.
10
+ */
11
+ import { defineAction } from '@cossackframework/core/hooks';
12
+ import { isLockedRecord } from './locked';
13
+ import { uuidv7 } from '@cossackframework/core';
14
+ import type { Statement, Value } from '@cossackframework/romedb';
15
+ import { CmsError } from '../errors';
16
+ import { ANONYMOUS, hasPermission, ruleScope } from '../permissions';
17
+ import { isSearchSyntaxError, searchQuery, type SnippetPart } from '../search';
18
+ import type { CollectionDefinition } from '../collections';
19
+ import type { RecordShape } from '../records';
20
+ import type { Resource } from '../resource';
21
+ import { searchedAsText, searchTextPath } from './schema';
22
+ import type { CmsHost } from './host';
23
+
24
+ export const SITE_SEARCH = {
25
+ collection: 'cms_search',
26
+ index: 'cms_search__text',
27
+ topic: 'search.rebuild',
28
+ /** Entries one rebuild round reads, and one statement writes. */
29
+ round: 200,
30
+ batch: 100,
31
+ /** RomeDB's largest `search::text` limit, so the deepest page reaches this many hits. */
32
+ hits: 10_000,
33
+ /** Characters of each hit's snippet (`search::snippet` takes 40 to 1000). */
34
+ snippet: 160,
35
+ } as const;
36
+
37
+ /** One round of a rebuild, queued in the outbox; the first clears what it rebuilds. */
38
+ export interface SearchRebuildEvent {
39
+ readonly eventId: string;
40
+ readonly topic: 'search.rebuild';
41
+ readonly at: number;
42
+ readonly run: string;
43
+ /** One collection's rows, or every collection's when null. */
44
+ readonly only: string | null;
45
+ /** Where the round starts: the collection and the last entry ID done in it. Both null for the first round. */
46
+ readonly collection: string | null;
47
+ readonly after: string | null;
48
+ readonly step: number;
49
+ }
50
+
51
+ /** Runs a rebuild round from the outbox. The host handles it; plugins cannot hook it. */
52
+ export const searchRebuild = defineAction<SearchRebuildEvent>('cms.search.rebuild', { version: 1, timeoutMs: 60_000 });
53
+
54
+ /** A collection in the index, with its resource. */
55
+ export interface SearchedCollection {
56
+ readonly collection: CollectionDefinition;
57
+ readonly resource: Resource;
58
+ }
59
+
60
+ /** One hit of a site search, best first. */
61
+ export interface SiteSearchHit {
62
+ readonly collection: string;
63
+ readonly id: string;
64
+ readonly score: number;
65
+ readonly snippet: readonly SnippetPart[];
66
+ }
67
+
68
+ export interface SiteSearchPage {
69
+ readonly hits: readonly SiteSearchHit[];
70
+ readonly page: number;
71
+ /** Another page follows. RomeDB counts only up to its limit, so there is no total. */
72
+ readonly next: boolean;
73
+ /** Nothing had every word, so these have any of them. */
74
+ readonly loose: boolean;
75
+ }
76
+
77
+ export interface SiteSearchOptions {
78
+ /** The page's language, on a site with several. */
79
+ readonly locale?: string;
80
+ /** Only these collections. */
81
+ readonly collections?: readonly string[];
82
+ readonly page?: number;
83
+ readonly perPage?: number;
84
+ readonly signal?: AbortSignal;
85
+ }
86
+
87
+ const WRITE = { kind: 'cms.search', retryConflicts: 5 } as const;
88
+
89
+ export class SiteSearch {
90
+ readonly #host: CmsHost;
91
+
92
+ constructor(host: CmsHost) {
93
+ this.#host = host;
94
+ }
95
+
96
+ /** The collections the index holds: a path on the site, something to search, and visitors may read them. By name. */
97
+ collections(): SearchedCollection[] {
98
+ const found: SearchedCollection[] = [];
99
+ for (const collection of this.#host.collections()) {
100
+ if (collection.path === null || collection.path === undefined) continue;
101
+ const resource = this.#host.resourceById(`cms/${collection.name}`);
102
+ if (!Object.values(resource.fields).some(field => field.search) || ruleScope(resource.access.read, ANONYMOUS) === 'deny') continue;
103
+ found.push({ collection, resource });
104
+ }
105
+ return found.sort((a, b) => a.collection.name < b.collection.name ? -1 : a.collection.name > b.collection.name ? 1 : 0);
106
+ }
107
+
108
+ /** What decides a collection's rows, to tell whether a saved collection needs them rebuilt; null when it has none. */
109
+ signature(name: string): string | null {
110
+ const searched = this.collections().find(entry => entry.collection.name === name);
111
+ if (!searched) return null;
112
+ const fields = Object.entries(searched.resource.fields).filter(([, declaration]) => declaration.search).map(([field, declaration]) => [field, searchedAsText(declaration), declaration.access?.read ?? null]);
113
+ return JSON.stringify({ path: searched.collection.path, publishable: searched.collection.publishable !== false, read: searched.resource.access.read, fields, title: Boolean(searched.resource.fields.title), locale: Boolean(searched.resource.fields.locale) });
114
+ }
115
+
116
+ /**
117
+ * The statements that keep an entry's row in step with a write, for the write's batch: the row
118
+ * when visitors may read the entry (`readable` is the entry as written, or null after a delete
119
+ * or when visitors may not read it), else no row. Guarded by the write's audit row `op`.
120
+ */
121
+ statements(resource: Resource, key: string, op: string, readable: RecordShape | null): Statement[] {
122
+ const searched = this.#searched(resource);
123
+ if (!searched) return [];
124
+ const guard = 'EXISTS (SELECT 1 FROM cms_audit WHERE id = $sOp)';
125
+ if (readable && this.#visible(searched, readable)) {
126
+ return [this.#upsert(searched, `d.id = type::record('${resource.storage}', $sKey) AND ${guard}`, { $sKey: key, $sOp: op })];
127
+ }
128
+ return [{ rql: `DELETE FROM ${SITE_SEARCH.collection} WHERE id = type::record('${SITE_SEARCH.collection}', $sId) AND ${guard}`, params: { $sId: `${searched.collection.name}:${key}`, $sOp: op } }];
129
+ }
130
+
131
+ /** Fill the index again from the entries, in the background: every collection, or one. */
132
+ async rebuild(options: { only?: string; signal?: AbortSignal } = {}): Promise<void> {
133
+ const run = uuidv7();
134
+ const at = this.#host.now();
135
+ const event: SearchRebuildEvent = { eventId: `search:${run}:0`, topic: 'search.rebuild', at, run, only: options.only ?? null, collection: null, after: null, step: 0 };
136
+ await this.#host.outbox.enqueue(SITE_SEARCH.topic, event, options.signal ? { signal: options.signal } : {});
137
+ this.#host.outboxWritten();
138
+ }
139
+
140
+ /** One rebuild round: clear first, then up to 200 entries, then queue the next round. */
141
+ async step(event: SearchRebuildEvent, options: { signal?: AbortSignal } = {}): Promise<void> {
142
+ const call = options.signal ? { signal: options.signal } : {};
143
+ const searched = this.collections().filter(entry => event.only === null || entry.collection.name === event.only);
144
+ if (event.collection === null && event.after === null) {
145
+ await this.#host.db.write([event.only === null
146
+ ? { rql: `DELETE FROM ${SITE_SEARCH.collection}` }
147
+ : { rql: `DELETE FROM ${SITE_SEARCH.collection} WHERE collection = $collection`, params: { $collection: event.only } }], { ...call, ...WRITE });
148
+ }
149
+ let position = event.collection === null ? 0 : searched.findIndex(entry => entry.collection.name >= event.collection!);
150
+ let after = position >= 0 && searched[position]?.collection.name === event.collection ? event.after : null;
151
+ let budget: number = SITE_SEARCH.round;
152
+ while (position >= 0 && position < searched.length && budget > 0) {
153
+ const entry = searched[position]!;
154
+ const storage = entry.resource.storage;
155
+ const size = Math.min(budget, SITE_SEARCH.batch);
156
+ const page = await this.#host.db.read([{
157
+ rql: `SELECT record::id(id) FROM ${storage}${after === null ? '' : ` WHERE id > type::record('${storage}', $after)`} ORDER BY id LIMIT ${size}`,
158
+ params: after === null ? {} : { $after: after },
159
+ }], call);
160
+ const ids = page.results[0]!.rows.map(row => row[0] as string);
161
+ if (ids.length) {
162
+ const visible = this.#visibleRql(entry);
163
+ await this.#host.db.write([this.#upsert(entry, [`d.id >= type::record('${storage}', $from)`, `d.id <= type::record('${storage}', $to)`, ...visible.rql].join(' AND '), { ...visible.params, $from: ids[0]!, $to: ids.at(-1)! })], { ...call, ...WRITE });
164
+ budget -= ids.length;
165
+ after = ids.at(-1)!;
166
+ }
167
+ if (ids.length < size) {
168
+ position++;
169
+ after = null;
170
+ }
171
+ }
172
+ if (position < 0 || position >= searched.length) return;
173
+ const next: SearchRebuildEvent = { ...event, eventId: `search:${event.run}:${event.step + 1}`, at: this.#host.now(), collection: searched[position]!.collection.name, after, step: event.step + 1 };
174
+ await this.#host.outbox.enqueue(SITE_SEARCH.topic, next, { ...call, ignoreDuplicate: true });
175
+ }
176
+
177
+ /** How many entries the index holds, and whether a rebuild is under way. */
178
+ async status(options: { signal?: AbortSignal } = {}): Promise<{ entries: number; rebuilding: boolean }> {
179
+ const result = await this.#host.db.read([
180
+ { rql: `SELECT count(*) FROM ${SITE_SEARCH.collection}` },
181
+ { rql: 'SELECT count(*) FROM cms_outbox WHERE topic = $topic AND delivered_at IS NULL', params: { $topic: SITE_SEARCH.topic } },
182
+ ], options.signal ? { signal: options.signal } : {});
183
+ return { entries: Number(result.results[0]!.rows[0]![0] as bigint), rebuilding: Number(result.results[1]!.rows[0]![0] as bigint) > 0 };
184
+ }
185
+
186
+ /**
187
+ * One page of the site's entries matching what someone typed, best first, with snippets:
188
+ * every word, else (on the first page) any word, with `loose` set. Empty for nothing searchable.
189
+ * The hits name entries; load them as the reader, who may still be refused one.
190
+ */
191
+ async search(text: string, options: SiteSearchOptions = {}): Promise<SiteSearchPage> {
192
+ const page = options.page ?? 1;
193
+ const perPage = options.perPage ?? 10;
194
+ if (!Number.isInteger(perPage) || perPage < 1 || perPage > 50) throw new CmsError('CMS_VALIDATION', 'perPage must be 1..50.');
195
+ if (!Number.isInteger(page) || page < 1) throw new CmsError('CMS_VALIDATION', 'page must be a positive integer.');
196
+ const parsed = searchQuery(text);
197
+ const empty: SiteSearchPage = { hits: [], page, next: false, loose: false };
198
+ const offset = (page - 1) * perPage;
199
+ if (!parsed || offset + perPage > SITE_SEARCH.hits) return empty;
200
+ const shown = this.collections().map(entry => entry.collection.name);
201
+ const wanted = options.collections ? shown.filter(name => options.collections!.includes(name)) : shown;
202
+ if (!wanted.length) return empty;
203
+ const params: { [key: string]: Value } = {};
204
+ const conditions = [`s.collection IN (${wanted.map((name, index) => { params[`$c${index}`] = name; return `$c${index}`; }).join(', ')})`];
205
+ if (options.locale !== undefined) {
206
+ conditions.push('s.locale = $locale');
207
+ params.$locale = options.locale;
208
+ }
209
+ // Hits are checked again in the outer query; fetch more when some may be filtered out.
210
+ const filtered = options.locale !== undefined || wanted.length < shown.length;
211
+ const run = async (query: string) => {
212
+ // The page's hits first, then a snippet cut in the database for each of them only: a
213
+ // projection beside ORDER BY would cut one for every hit fetched, and a hit's text never leaves.
214
+ const onPage = `SELECT h.id, h.score FROM search::text('${SITE_SEARCH.index}', $query, $limit) h JOIN ${SITE_SEARCH.collection} s ON s.id = h.id WHERE ${conditions.join(' AND ')} ORDER BY h.score DESC, h.id LIMIT ${perPage + 1}${offset ? ` OFFSET ${offset}` : ''}`;
215
+ const result = await this.#host.db.read([{
216
+ rql: `SELECT s.collection, s.entry, search::snippet('${SITE_SEARCH.index}', s.text, $query, ${SITE_SEARCH.snippet}), p.score FROM (${onPage}) p JOIN ${SITE_SEARCH.collection} s ON s.id = p.id ORDER BY p.score DESC, p.id`,
217
+ params: { ...params, $query: query, $limit: Math.min((offset + perPage + 1) * (filtered ? 4 : 1), SITE_SEARCH.hits) },
218
+ }], { ...(options.signal ? { signal: options.signal } : {}), workLimits: this.#host.readLimits }).catch(error => {
219
+ if (isSearchSyntaxError(error)) throw new CmsError('CMS_VALIDATION', 'That search could not be read.');
220
+ throw error;
221
+ });
222
+ return result.results[0]!.rows;
223
+ };
224
+ let rows = await run(parsed.all);
225
+ let loose = false;
226
+ if (!rows.length && page === 1 && parsed.any) {
227
+ rows = await run(parsed.any);
228
+ loose = rows.length > 0;
229
+ }
230
+ const hits = rows.slice(0, perPage).map(([collection, id, snippet, score]) => ({
231
+ collection: collection as string, id: id as string, score: Number(score), snippet: snippetOf(snippet),
232
+ }));
233
+ return { hits, page, next: rows.length > perPage, loose };
234
+ }
235
+
236
+ #searched(resource: Resource): SearchedCollection | undefined {
237
+ if (!resource.id.startsWith('cms/')) return undefined;
238
+ return this.collections().find(entry => entry.resource.id === resource.id);
239
+ }
240
+
241
+ /** Whether visitors may read an entry the read rule lets them see: published, not protected, not members-only. */
242
+ #visible(searched: SearchedCollection, record: RecordShape): boolean {
243
+ if (searched.collection.publishable !== false && record.status !== 'published') return false;
244
+ return !isLockedRecord(record);
245
+ }
246
+
247
+ /** `#visible` and the visitor's read rule, as conditions on the entry document `d`. */
248
+ #visibleRql(searched: SearchedCollection): { rql: string[]; params: { [key: string]: Value } } {
249
+ const fields = searched.resource.fields;
250
+ const rql: string[] = [];
251
+ const params: { [key: string]: Value } = {};
252
+ if (searched.collection.publishable !== false) rql.push(`d.status = 'published'`);
253
+ if (fields.password) rql.push(`(d.password IS NULL OR d.password = '')`);
254
+ if (fields.membersOnly) rql.push('NOT coalesce(d."membersOnly", false)');
255
+ const scope = ruleScope(searched.resource.access.read, ANONYMOUS);
256
+ if (scope !== 'allow' && scope !== 'deny') {
257
+ const rules = scope.where.map((rule, ruleIndex) => Object.entries(rule).map(([name, value], index) => {
258
+ params[`$v${ruleIndex}_${index}`] = value as Value;
259
+ return `d."${name}" = $v${ruleIndex}_${index}`;
260
+ }).join(' AND '));
261
+ rql.push(rules.length ? `(${rules.map(rule => `(${rule})`).join(' OR ')})` : 'false');
262
+ }
263
+ return { rql, params };
264
+ }
265
+
266
+ /** Write the rows of the entries `where` picks, copying their text inside the statement. */
267
+ #upsert(searched: SearchedCollection, where: string, params: { [key: string]: Value }): Statement {
268
+ const fields = searched.resource.fields;
269
+ // Searchable fields visitors may read, the title aside; rich text, blocks and rows by their plain text.
270
+ const parts = Object.entries(fields)
271
+ .filter(([name, declaration]) => declaration.search && name !== 'title' && (!declaration.access?.read || hasPermission(ANONYMOUS, declaration.access.read)))
272
+ .map(([name, declaration]) => `d."${searchedAsText(declaration) ? searchTextPath(name) : name}"`);
273
+ const text = parts.length ? `concat_ws(char(10), ${parts.join(', ')})` : `''`;
274
+ const title = fields.title && (!fields.title.access?.read || hasPermission(ANONYMOUS, fields.title.access.read)) ? 'd.title' : 'NULL';
275
+ const locale = fields.locale ? 'd.locale' : 'NULL';
276
+ const at = fields.publishedAt ? 'd."publishedAt"' : 'NULL';
277
+ return {
278
+ rql: `INSERT OR REPLACE INTO ${SITE_SEARCH.collection} (id, collection, entry, locale, title, text, at) SELECT type::record('${SITE_SEARCH.collection}', $sCollection || ':' || record::id(d.id)), $sCollection, record::id(d.id), ${locale}, ${title}, ${text}, ${at} FROM ${searched.resource.storage} d WHERE ${where}`,
279
+ params: { ...params, $sCollection: searched.collection.name },
280
+ };
281
+ }
282
+ }
283
+
284
+ /** `search::snippet`'s parts as plain values: text and a match flag each, empty parts left out. */
285
+ function snippetOf(value: unknown): SnippetPart[] {
286
+ if (!Array.isArray(value)) return [];
287
+ return value.flatMap(part => part !== null && typeof part === 'object' && typeof (part as { text?: unknown }).text === 'string' && (part as { text: string }).text !== ''
288
+ ? [{ text: (part as { text: string }).text, match: (part as { match?: unknown }).match === true }] : []);
289
+ }
@@ -0,0 +1,286 @@
1
+ /** Settings declarations, authorized portable documents, and atomic storage. */
2
+ import { ClientError, LOCAL_REQUEST_BYTES, UncertainWriteError, encodeValue, type RomeDB, type Statement } from '@cossackframework/romedb';
3
+
4
+ /** Room a request needs besides its statement: its identity and work limits. */
5
+ const REQUEST_ROOM = 4096;
6
+ import { CmsError } from '../errors';
7
+ import { FIELD_NAME } from '../fields';
8
+ import { hasPermission, PERMISSIONS, principalId, type Principal } from '../permissions';
9
+ import { OWNER_NAME } from '../resource';
10
+ import type { SettingsGroup, SiteSettings } from '../settings';
11
+ import { settingControlProblems, validateSettingValue } from '../settings-controls';
12
+ import { customCssProblem, presetOverridesProblem } from '../theme';
13
+ import { dashboardMenuProblems } from '../dashboard-menu';
14
+ import { checkSettingsDocument, isPortableSetting, SETTINGS_DOCUMENT_MAX_FIELDS, stringifySettingsDocument, type SettingsDocument, type SettingsValue } from '../settings-document';
15
+
16
+ const WRITE = { kind: 'cms.settings', retryConflicts: 5, workLimits: { rowsRead: 100_000, rowMutations: 5000, vmSteps: 2_000_000 } } as const;
17
+ const UNSAFE = new Set(['__proto__', 'constructor', 'prototype']);
18
+ const EXCLUDED = new Set(['appearance', 'languages', 'permalinks']);
19
+ const encoder = new TextEncoder();
20
+ type Context = { principal: Principal };
21
+
22
+ /**
23
+ * Rules beyond a setting's declaration, run on every write (the dashboard, the settings API,
24
+ * the CLI and MCP alike): the screens that edit these values check them too, for their messages.
25
+ */
26
+ const VALUE_CHECKS: Readonly<Record<string, (value: unknown) => string | undefined>> = {
27
+ 'appearance.customCss': value => typeof value === 'string' ? customCssProblem(value) : undefined,
28
+ 'appearance.presets': value => {
29
+ if (value === null || value === undefined) return undefined;
30
+ if (typeof value !== 'object' || Array.isArray(value)) return 'are an object of preset overrides by theme.';
31
+ for (const overrides of Object.values(value)) { const problem = presetOverridesProblem(overrides); if (problem) return problem; }
32
+ return undefined;
33
+ },
34
+ 'dashboard.menu': value => value === null || value === undefined ? undefined : dashboardMenuProblems(value)[0],
35
+ };
36
+
37
+ function settingProblem(key: string, name: string, declaration: SettingsGroup['fields'][string], value: unknown): string | undefined {
38
+ return validateSettingValue(name, declaration, value) ?? (Object.hasOwn(VALUE_CHECKS, key) ? VALUE_CHECKS[key]!(value) : undefined);
39
+ }
40
+ type Stored = { values: SiteSettings; errors: Record<string, string> };
41
+
42
+ export class CmsSettings {
43
+ readonly #db: RomeDB;
44
+ /** The most a settings save may encode to: the database's request size, less room for the request around it. Learned on the first read or write. */
45
+ #saveBytes = LOCAL_REQUEST_BYTES - REQUEST_ROOM;
46
+ readonly #groups = new Map<string, SettingsGroup>();
47
+ readonly #now: () => number;
48
+ readonly #ttl: number;
49
+ /** Called after a committed change, for the host to purge the site's pages. */
50
+ readonly #changed: (() => void | Promise<void>) | undefined;
51
+ #cache: { at: number; values: Promise<Stored> } | undefined;
52
+
53
+ constructor(db: RomeDB, groups: readonly SettingsGroup[], options: { now?: () => number; ttlMs?: number; changed?: () => void | Promise<void> } = {}) {
54
+ this.#db = db;
55
+ this.#now = options.now ?? Date.now;
56
+ this.#ttl = options.ttlMs ?? 30_000;
57
+ this.#changed = options.changed;
58
+ for (const group of groups) {
59
+ const plugin = group.plugin;
60
+ const valid = plugin !== undefined
61
+ ? OWNER_NAME.test(plugin) && plugin.length <= 64 && group.id === `plugin:${plugin}`
62
+ : /^[a-z][a-z0-9-]{0,40}$/.test(group.id) && !['plugins', 'json'].includes(group.id);
63
+ if (!valid || UNSAFE.has(group.id) || this.#groups.has(group.id)) throw new Error(`Settings group ${group.id} is invalid or declared twice.`);
64
+ for (const name of Object.keys(group.fields)) {
65
+ if (!FIELD_NAME.test(name) || UNSAFE.has(name)) throw new Error(`Settings field ${group.id}.${name} has an invalid name.`);
66
+ const problems = settingControlProblems(name, group.fields[name]!);
67
+ if (problems.length) throw new Error(`Settings group ${group.id}: ${problems.join(' ')}`);
68
+ }
69
+ this.#groups.set(group.id, group);
70
+ }
71
+ }
72
+
73
+ get groups(): readonly SettingsGroup[] { return [...this.#groups.values()]; }
74
+
75
+ group(id: string): SettingsGroup {
76
+ const group = this.#groups.get(id);
77
+ if (!group) throw new CmsError('CMS_NOT_FOUND', `Unknown settings group ${id}.`);
78
+ return group;
79
+ }
80
+
81
+ /** Internal server reads, with defaults. Never expose this method directly through browser RPC. */
82
+ async all(): Promise<SiteSettings> {
83
+ const now = this.#now();
84
+ if (!this.#cache || now - this.#cache.at > this.#ttl) {
85
+ const values = this.#read();
86
+ this.#cache = { at: now, values };
87
+ values.catch(() => { if (this.#cache?.values === values) this.#cache = undefined; });
88
+ }
89
+ return (await this.#cache.values).values;
90
+ }
91
+
92
+ async get<K extends keyof SiteSettings & string>(key: K): Promise<SiteSettings[K]> {
93
+ return (await this.all())[key];
94
+ }
95
+
96
+ /** Only opted-in scalar groups the principal can edit. Declarations are detached before exposure. */
97
+ catalog({ principal }: Context): readonly SettingsGroup[] {
98
+ return this.groups.filter(group => this.#portable(group) && hasPermission(principal, group.permission ?? PERMISSIONS.manageSettings))
99
+ .map(group => structuredClone(group));
100
+ }
101
+
102
+ /** Fresh authorized values. Invalid stored overrides are reported rather than silently exported as defaults. */
103
+ async snapshot(context: Context): Promise<SettingsDocument> {
104
+ return this.#document(await this.#read(), this.catalog(context));
105
+ }
106
+
107
+ async exportDocument(context: Context): Promise<string> {
108
+ return stringifySettingsDocument(await this.snapshot(context));
109
+ }
110
+
111
+ /** Validate the complete patch and its encoded write size before any mutation. */
112
+ validateDocument(input: unknown, context: Context): SettingsDocument {
113
+ const document = checkSettingsDocument(input);
114
+ const errors: Record<string, string> = {};
115
+ for (const [id, fields] of Object.entries(document)) {
116
+ const group = this.#groups.get(id);
117
+ if (!group || !this.#portable(group)) {
118
+ errors[id] = 'is not available in settings JSON.';
119
+ continue;
120
+ }
121
+ this.#authorize(group, context);
122
+ for (const [name, value] of Object.entries(fields)) {
123
+ const declaration = Object.hasOwn(group.fields, name) ? group.fields[name] : undefined;
124
+ const error = declaration ? settingProblem(`${id}.${name}`, name, declaration, value) : 'is not a setting of this group.';
125
+ if (error) errors[`${id}.${name}`] = error;
126
+ }
127
+ }
128
+ if (Object.keys(errors).length) throw new CmsError('CMS_VALIDATION', 'Some settings are invalid.', { fields: errors });
129
+ this.#statement(Object.entries(document).flatMap(([id, fields]) => Object.entries(fields).map(([name, value]) => [`${id}.${name}`, value] as const)), context);
130
+ return document;
131
+ }
132
+
133
+ async applyDocument(input: unknown, context: Context): Promise<SettingsDocument> {
134
+ const document = this.validateDocument(input, context);
135
+ const stored = await this.#read();
136
+ const values = { ...stored.values };
137
+ const errors = { ...stored.errors };
138
+ const entries: (readonly [string, unknown])[] = [];
139
+ for (const [id, fields] of Object.entries(document)) for (const [name, value] of Object.entries(fields)) {
140
+ const key = `${id}.${name}`;
141
+ // Equal values are still explicit overrides: an imported default must remain pinned.
142
+ entries.push([key, value]);
143
+ values[key] = value;
144
+ delete errors[key];
145
+ }
146
+ // Do not commit and then report a validation failure from another invalid stored field.
147
+ const result = this.#document({ values: values as SiteSettings, errors }, this.catalog(context));
148
+ await this.#write(entries, context);
149
+ return result;
150
+ }
151
+
152
+ /** Validate and store part of one group. Dedicated groups retain their existing domain operations. */
153
+ async update(groupId: string, input: { readonly [field: string]: unknown }, context: Context): Promise<SiteSettings> {
154
+ const group = this.group(groupId);
155
+ this.#authorize(group, context);
156
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw new CmsError('CMS_VALIDATION', 'Settings values must be an object.');
157
+ const errors: Record<string, string> = {};
158
+ const entries: (readonly [string, unknown])[] = [];
159
+ for (const [name, value] of Object.entries(input)) {
160
+ const declaration = Object.hasOwn(group.fields, name) ? group.fields[name] : undefined;
161
+ if (!declaration) { errors[name] = 'is not a setting of this group.'; continue; }
162
+ if (value === undefined) continue;
163
+ const error = settingProblem(`${group.id}.${name}`, name, declaration, value);
164
+ if (error) { errors[name] = error; continue; }
165
+ entries.push([`${group.id}.${name}`, value]);
166
+ }
167
+ if (Object.keys(errors).length) throw new CmsError('CMS_VALIDATION', 'Some settings are invalid.', { fields: errors });
168
+ await this.#write(entries, context);
169
+ return this.all();
170
+ }
171
+
172
+ refresh(): void { this.#cache = undefined; }
173
+
174
+ #portable(group: SettingsGroup): boolean {
175
+ return group.json === true && !EXCLUDED.has(group.id) && (group.permission ?? PERMISSIONS.manageSettings) !== PERMISSIONS.manageAppearance
176
+ && Object.values(group.fields).every(isPortableSetting);
177
+ }
178
+
179
+ #authorize(group: SettingsGroup, { principal }: Context): void {
180
+ if (!hasPermission(principal, group.permission ?? PERMISSIONS.manageSettings)) {
181
+ throw new CmsError(principal.kind === 'anonymous' ? 'CMS_UNAUTHENTICATED' : 'CMS_FORBIDDEN', 'Not allowed to change settings.');
182
+ }
183
+ }
184
+
185
+ #document(stored: Stored, groups: readonly SettingsGroup[]): SettingsDocument {
186
+ const document: SettingsDocument = {};
187
+ const errors: Record<string, string> = {};
188
+ for (const group of groups) {
189
+ const fields: Record<string, SettingsValue> = {};
190
+ for (const [name, declaration] of Object.entries(group.fields)) {
191
+ const key = `${group.id}.${name}`;
192
+ if (stored.errors[key]) errors[key] = stored.errors[key]!;
193
+ const value = stored.values[key];
194
+ if (value === null && !declaration.nullable && declaration.default === undefined) continue;
195
+ const problem = validateSettingValue(name, declaration, value);
196
+ if (problem) errors[key] = problem;
197
+ else fields[name] = value as SettingsValue;
198
+ }
199
+ document[group.id] = fields;
200
+ }
201
+ if (Object.keys(errors).length) throw new CmsError('CMS_VALIDATION', 'Some saved settings no longer match their declarations. Correct these values before exporting or applying the document.', { fields: errors });
202
+ // A snapshot can exceed the file limit: keep forms usable and let export fail explicitly.
203
+ return document;
204
+ }
205
+
206
+ #statement(entries: readonly (readonly [string, unknown])[], context: Context): Statement | undefined {
207
+ if (!entries.length) return;
208
+ if (entries.length > SETTINGS_DOCUMENT_MAX_FIELDS) throw new CmsError('CMS_LIMIT', `A settings save contains at most ${SETTINGS_DOCUMENT_MAX_FIELDS} fields.`);
209
+ const statement: Statement = {
210
+ rql: `INSERT INTO cms_settings (key, value, updated_at, updated_by)
211
+ SELECT json_extract(value, '$[0]'), json_extract(value, '$[1]'), $now, $by FROM json_each($rows) WHERE true
212
+ ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at, updated_by = excluded.updated_by`,
213
+ params: { $rows: JSON.stringify(entries.map(([key, value]) => [key, JSON.stringify(value)])), $now: this.#now(), $by: principalId(context.principal) },
214
+ };
215
+ // The service protocol also encodes bound strings. Leave room for its request identity and work limits.
216
+ const bytes = encoder.encode(JSON.stringify({ sql: statement.rql, params: Object.fromEntries(Object.entries(statement.params!).map(([name, value]) => [name, encodeValue(value)])) })).byteLength;
217
+ if (bytes > this.#saveBytes) throw new CmsError('CMS_LIMIT', `This settings save exceeds the ${Math.floor(this.#saveBytes / 1024)} KiB the database takes in one write. Apply fewer changes.`);
218
+ return statement;
219
+ }
220
+
221
+ /** The database's request size; a database stand-in without one counts as a local service. */
222
+ async #requestBytes(): Promise<number> {
223
+ return typeof this.#db.maxRequestBytes === 'function' ? this.#db.maxRequestBytes() : LOCAL_REQUEST_BYTES;
224
+ }
225
+
226
+ async #write(entries: readonly (readonly [string, unknown])[], context: Context): Promise<void> {
227
+ this.#saveBytes = await this.#requestBytes() - REQUEST_ROOM;
228
+ const statement = this.#statement(entries, context);
229
+ if (!statement) return;
230
+ try { await this.#db.write([statement], WRITE); }
231
+ catch (error) {
232
+ if (error instanceof UncertainWriteError) {
233
+ this.refresh();
234
+ throw new CmsError('CMS_UNCERTAIN', 'The settings save was sent but not confirmed. Its exact request is saved for recovery. Reload before making another change.', { requestId: error.requestId, cause: error });
235
+ }
236
+ throw error;
237
+ }
238
+ this.refresh();
239
+ await this.#changed?.();
240
+ }
241
+
242
+ async #read(): Promise<Stored> {
243
+ this.#saveBytes = await this.#requestBytes() - REQUEST_ROOM;
244
+ // Retry if another writer commits between pages, so one export cannot mix snapshots.
245
+ for (let attempt = 0; attempt < 3; attempt++) {
246
+ const values: Record<string, unknown> = {};
247
+ const errors: Record<string, string> = {};
248
+ for (const group of this.#groups.values()) for (const [name, declaration] of Object.entries(group.fields)) values[`${group.id}.${name}`] = declaration.default ?? null;
249
+ let after = '';
250
+ let sequence: number | undefined;
251
+ let count = 0;
252
+ let pageSize = 100;
253
+ for (;;) {
254
+ let result;
255
+ try { result = await this.#db.read([{ rql: 'SELECT key, value FROM cms_settings WHERE key > $after ORDER BY key LIMIT $limit', params: { $after: after, $limit: pageSize } }]); }
256
+ catch (error) {
257
+ if (error instanceof ClientError && /cms_settings/i.test(error.message) && /no such table|not found|does not exist/i.test(error.message)) return { values: Object.freeze(values) as SiteSettings, errors };
258
+ if (error instanceof ClientError && (error.code === 'RDB_LIMIT' || error.code === 'RDB_RESULT_TOO_LARGE') && pageSize > 1) { pageSize = Math.max(1, Math.floor(pageSize / 2)); continue; }
259
+ throw error;
260
+ }
261
+ if (sequence !== undefined && sequence !== result.sequence) break;
262
+ sequence = result.sequence;
263
+ const rows = result.results[0]!.rows;
264
+ count += rows.length;
265
+ if (count > 20_000) throw new CmsError('CMS_LIMIT', 'The settings store exceeds the supported 20000-row read limit.');
266
+ for (const [key, raw] of rows) {
267
+ const full = String(key);
268
+ const dot = full.indexOf('.');
269
+ const group = this.#groups.get(full.slice(0, dot));
270
+ const name = full.slice(dot + 1);
271
+ const declaration = group && Object.hasOwn(group.fields, name) ? group.fields[name] : undefined;
272
+ if (!declaration) continue;
273
+ try {
274
+ const parsed: unknown = JSON.parse(raw as string);
275
+ const error = validateSettingValue(name, declaration, parsed);
276
+ if (error) errors[full] = error;
277
+ else values[full] = parsed;
278
+ } catch { errors[full] = 'contains invalid stored JSON.'; }
279
+ }
280
+ if (rows.length < pageSize) return { values: Object.freeze(values) as SiteSettings, errors };
281
+ after = String(rows[rows.length - 1]![0]);
282
+ }
283
+ }
284
+ throw new CmsError('CMS_CONFLICT', 'Settings changed while they were being read. Reload and try again.');
285
+ }
286
+ }