@cossackframework/cms 0.0.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +18 -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 +708 -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 +109 -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 +74 -0
  110. package/app/src/dashboard/avatar-field.ts +58 -0
  111. package/app/src/dashboard/bulk.ts +53 -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 +120 -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 +13 -0
  121. package/app/src/dashboard/session-list.ts +98 -0
  122. package/app/src/dashboard/tabs.ts +26 -0
  123. package/app/src/dashboard/time-ago.ts +16 -0
  124. package/app/src/dashboard/types.ts +40 -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 +75 -0
  212. package/app/src/pages/auth/layout.ts +32 -0
  213. package/app/src/pages/auth/login/index.ts +198 -0
  214. package/app/src/pages/auth/magic/index.ts +68 -0
  215. package/app/src/pages/auth/register/index.ts +117 -0
  216. package/app/src/pages/auth/reset-password/index.ts +65 -0
  217. package/app/src/pages/auth/setup/index.ts +194 -0
  218. package/app/src/pages/auth/two-factor/index.ts +67 -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 +182 -0
  278. package/app/src/pages/dashboard/index.ts +214 -0
  279. package/app/src/pages/dashboard/layout.ts +320 -0
  280. package/app/src/pages/dashboard/profile/index.ts +211 -0
  281. package/app/src/pages/dashboard/profile/security/index.ts +255 -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,402 @@
1
+ import { highlightCode } from './highlight';
2
+ import { blockLayoutProblem, blockStyleProblem, blocksShapeProblem } from './block-shape';
3
+
4
+ /**
5
+ * Rich text: a ProseMirror (TipTap) JSON document, `{ type: 'doc', content }`. The dashboard
6
+ * edits it in the browser, the site renders it to HTML on the server, and the content API
7
+ * returns the JSON for other renderers such as mobile apps. Only the nodes, marks and
8
+ * attributes declared here are accepted; the HTML renderer escapes every text and attribute.
9
+ */
10
+
11
+ export interface RichTextMark {
12
+ readonly type: string;
13
+ readonly attrs?: { readonly [name: string]: unknown };
14
+ }
15
+
16
+ export interface RichTextNode {
17
+ readonly type: string;
18
+ readonly attrs?: { readonly [name: string]: unknown };
19
+ readonly content?: readonly RichTextNode[];
20
+ readonly text?: string;
21
+ readonly marks?: readonly RichTextMark[];
22
+ }
23
+
24
+ export interface RichTextDoc {
25
+ readonly type: 'doc';
26
+ readonly content: readonly RichTextNode[];
27
+ }
28
+
29
+ /** A block embedded in a document: a top-level `cmsBlock` node's attributes. */
30
+ export interface EmbeddedBlock {
31
+ readonly _id: string;
32
+ readonly type: string;
33
+ readonly data: { readonly [field: string]: unknown };
34
+ readonly layout?: { readonly hide?: readonly ('sm' | 'md' | 'lg')[]; readonly anchor?: string; readonly className?: string };
35
+ readonly style?: { readonly background?: string; readonly text?: string; readonly padding?: string; readonly margin?: string; readonly fontSize?: string; readonly align?: 'left' | 'center' | 'right' };
36
+ /** The blocks a container holds. */
37
+ readonly children?: readonly EmbeddedBlock[];
38
+ }
39
+
40
+ export const RICH_TEXT_LIMITS = Object.freeze({ bytes: 512 * 1024, nodes: 20_000, depth: 24, text: 100_000 });
41
+
42
+ /** Node types by where they may appear. `cmsBlock` is allowed only at the top level. */
43
+ export const RICH_TEXT_NODES = Object.freeze({
44
+ block: ['paragraph', 'heading', 'blockquote', 'bulletList', 'orderedList', 'codeBlock', 'horizontalRule', 'image', 'table'] as const,
45
+ inline: ['text', 'hardBreak'] as const,
46
+ top: ['cmsBlock'] as const,
47
+ });
48
+ export const RICH_TEXT_MARKS = Object.freeze(['bold', 'italic', 'underline', 'strike', 'code', 'link'] as const);
49
+
50
+ const BLOCK_ID = /^[A-Za-z0-9_-]{1,40}$/;
51
+ const BLOCK_TYPE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
52
+ const LANGUAGE = /^[a-z0-9+#-]{1,40}$/;
53
+ const ALIGNMENTS = new Set(['left', 'center', 'right', 'justify']);
54
+
55
+ /** A link target: `http(s)`, `mailto:`, `tel:`, a site path or a fragment. */
56
+ export function safeLinkUrl(url: unknown): url is string {
57
+ return typeof url === 'string' && url.length <= 2048 && !/[\s\u0000-\u001f\u007f]/.test(url)
58
+ && !url.includes('\\') && /^(?:https?:\/\/[^/]|mailto:|tel:|\/(?!\/)|#)/i.test(url);
59
+ }
60
+
61
+ /** An image source: a media file of this site or an `https` URL. */
62
+ export function safeImageUrl(url: unknown): url is string {
63
+ return typeof url === 'string' && url.length <= 2048 && !/[\s\u0000-\u001f\u007f]/.test(url) && /^(?:https:\/\/[^/]|\/media\/)/i.test(url);
64
+ }
65
+
66
+ const INVALID = Symbol('invalid');
67
+ type AttributeCheck = (value: unknown) => unknown;
68
+ const span: AttributeCheck = value => Number.isInteger(value) && (value as number) >= 1 && (value as number) <= 100 ? value : INVALID;
69
+ /** A table cell: how many columns and rows it spans, and the column widths the editor dragged. */
70
+ const TABLE_CELL_ATTRIBUTES: { readonly [name: string]: AttributeCheck } = {
71
+ colspan: span, rowspan: span,
72
+ colwidth: value => Array.isArray(value) && value.length <= 100 && value.every(width => Number.isInteger(width) && (width as number) > 0 && (width as number) <= 10_000) ? value : INVALID,
73
+ };
74
+ const text = (max: number): AttributeCheck => value => typeof value === 'string' && [...value].length <= max ? value : INVALID;
75
+ const align: AttributeCheck = value => typeof value === 'string' && ALIGNMENTS.has(value) ? value : INVALID;
76
+
77
+ /** Attributes each node keeps; others, and null values, are dropped. */
78
+ const NODE_ATTRIBUTES: { readonly [type: string]: { readonly [name: string]: AttributeCheck } } = {
79
+ paragraph: { textAlign: align },
80
+ heading: { level: value => Number.isInteger(value) && (value as number) >= 1 && (value as number) <= 6 ? value : INVALID, textAlign: align },
81
+ orderedList: { start: value => Number.isSafeInteger(value) && (value as number) >= 0 && (value as number) <= 1_000_000 ? value : INVALID },
82
+ codeBlock: { language: value => typeof value === 'string' && LANGUAGE.test(value) ? value : INVALID },
83
+ tableCell: TABLE_CELL_ATTRIBUTES, tableHeader: TABLE_CELL_ATTRIBUTES,
84
+ image: { src: value => safeImageUrl(value) ? value : INVALID, alt: text(500), title: text(300), mediaId: value => typeof value === 'string' && /^[A-Za-z0-9_-]{1,80}$/.test(value) ? value : INVALID },
85
+ cmsBlock: {
86
+ _id: value => typeof value === 'string' && BLOCK_ID.test(value) ? value : INVALID,
87
+ type: value => typeof value === 'string' && BLOCK_TYPE.test(value) ? value : INVALID,
88
+ data: value => isPlainObject(value) ? value : INVALID,
89
+ layout: value => blockLayoutProblem(value) ? INVALID : value,
90
+ style: value => blockStyleProblem(value) ? INVALID : value,
91
+ children: value => Array.isArray(value) && !blocksShapeProblem(value) ? value : INVALID,
92
+ },
93
+ };
94
+ const REQUIRED_ATTRIBUTES: { readonly [type: string]: readonly string[] } = { heading: ['level'], image: ['src'], cmsBlock: ['_id', 'type', 'data'] };
95
+ const MARK_ATTRIBUTES: { readonly [type: string]: { readonly [name: string]: AttributeCheck } } = {
96
+ link: { href: value => safeLinkUrl(value) ? value : INVALID, target: value => value === '_blank' ? value : INVALID },
97
+ };
98
+
99
+ /** What each node holds. */
100
+ const CONTENT: { readonly [type: string]: 'block' | 'inline' | 'text' | 'items' | 'rows' | 'cells' | 'none' } = {
101
+ paragraph: 'inline', heading: 'inline', blockquote: 'block', bulletList: 'items', orderedList: 'items', listItem: 'block',
102
+ codeBlock: 'text', horizontalRule: 'none', image: 'none', hardBreak: 'none', cmsBlock: 'none',
103
+ table: 'rows', tableRow: 'cells', tableCell: 'block', tableHeader: 'block',
104
+ };
105
+
106
+ type Checked = { doc: RichTextDoc } | { error: string };
107
+
108
+ /**
109
+ * Validate a document and return a clean copy: known nodes, marks and attributes only, without
110
+ * null attributes. Errors name the path, such as `content[2].marks[0].attrs.href`.
111
+ */
112
+ export function checkRichText(value: unknown): Checked {
113
+ if (!isPlainObject(value) || value.type !== 'doc') return { error: 'must be a rich text document.' };
114
+ const size = JSON.stringify(value).length;
115
+ if (size > RICH_TEXT_LIMITS.bytes) return { error: `must be at most ${RICH_TEXT_LIMITS.bytes / 1024} KB.` };
116
+ const state = { nodes: 0 };
117
+ try {
118
+ const content = checkContent(value.content, 'top', 'content', 1, state);
119
+ return { doc: Object.freeze({ type: 'doc', content }) };
120
+ } catch (error) {
121
+ if (error instanceof RichTextError) return { error: error.message };
122
+ throw error;
123
+ }
124
+ }
125
+
126
+ export function richTextProblem(value: unknown): string | undefined {
127
+ const checked = checkRichText(value);
128
+ return 'error' in checked ? checked.error : undefined;
129
+ }
130
+
131
+ /** The validated, cleaned document. Throws on an invalid one. */
132
+ export function normalizeRichText(value: unknown): RichTextDoc {
133
+ const checked = checkRichText(value);
134
+ if ('error' in checked) throw new RichTextError(checked.error);
135
+ return checked.doc;
136
+ }
137
+
138
+ class RichTextError extends Error {}
139
+
140
+ function checkContent(value: unknown, context: 'top' | 'block' | 'inline' | 'text' | 'items' | 'rows' | 'cells' | 'none', path: string, depth: number, state: { nodes: number }): RichTextNode[] {
141
+ if (value === undefined) return [];
142
+ if (!Array.isArray(value)) throw new RichTextError(`${path} must be a list of nodes.`);
143
+ if (context === 'none' && value.length) throw new RichTextError(`${path} must be empty.`);
144
+ if (depth > RICH_TEXT_LIMITS.depth) throw new RichTextError(`nests deeper than ${RICH_TEXT_LIMITS.depth} levels.`);
145
+ return value.map((node, index) => checkNode(node, context, `${path}[${index}]`, depth, state));
146
+ }
147
+
148
+ function checkNode(value: unknown, context: 'top' | 'block' | 'inline' | 'text' | 'items' | 'rows' | 'cells' | 'none', path: string, depth: number, state: { nodes: number }): RichTextNode {
149
+ if (++state.nodes > RICH_TEXT_LIMITS.nodes) throw new RichTextError(`must have at most ${RICH_TEXT_LIMITS.nodes} nodes.`);
150
+ if (!isPlainObject(value) || typeof value.type !== 'string') throw new RichTextError(`${path} must be a node.`);
151
+ const type = value.type;
152
+ const allowed = context === 'top' ? [...RICH_TEXT_NODES.block, ...RICH_TEXT_NODES.top]
153
+ : context === 'block' ? RICH_TEXT_NODES.block
154
+ : context === 'inline' ? RICH_TEXT_NODES.inline
155
+ : context === 'text' ? ['text']
156
+ : context === 'items' ? ['listItem']
157
+ : context === 'rows' ? ['tableRow']
158
+ : context === 'cells' ? ['tableCell', 'tableHeader'] : [];
159
+ if (!(allowed as readonly string[]).includes(type)) throw new RichTextError(`${path}: ${type} is not allowed here.`);
160
+ if (type === 'text') {
161
+ if (typeof value.text !== 'string' || !value.text || [...value.text].length > RICH_TEXT_LIMITS.text) throw new RichTextError(`${path} must hold 1-${RICH_TEXT_LIMITS.text} characters.`);
162
+ if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(value.text)) throw new RichTextError(`${path} must be well-formed text.`);
163
+ const marks = context === 'text' ? [] : checkMarks(value.marks, `${path}.marks`);
164
+ if (context === 'text' && value.marks !== undefined && (!Array.isArray(value.marks) || value.marks.length)) throw new RichTextError(`${path}: code blocks hold plain text.`);
165
+ return Object.freeze(marks.length ? { type, text: value.text, marks } : { type, text: value.text });
166
+ }
167
+ const attrs = checkAttributes(type, value.attrs, `${path}.attrs`, NODE_ATTRIBUTES[type] ?? {});
168
+ for (const name of REQUIRED_ATTRIBUTES[type] ?? []) if (attrs[name] === undefined) throw new RichTextError(`${path}.attrs.${name} is required.`);
169
+ const content = checkContent(value.content, CONTENT[type] ?? 'none', `${path}.content`, depth + 1, state);
170
+ if ((type === 'bulletList' || type === 'orderedList' || type === 'listItem' || type === 'blockquote' || type === 'table' || type === 'tableRow') && !content.length) throw new RichTextError(`${path} must not be empty.`);
171
+ return Object.freeze({ type, ...(Object.keys(attrs).length ? { attrs: Object.freeze(attrs) } : {}), ...(content.length ? { content: Object.freeze(content) } : {}) });
172
+ }
173
+
174
+ function checkAttributes(owner: string, value: unknown, path: string, spec: { readonly [name: string]: AttributeCheck }): { [name: string]: unknown } {
175
+ if (value === undefined || value === null) return {};
176
+ if (!isPlainObject(value)) throw new RichTextError(`${path} must be an object.`);
177
+ const attrs: { [name: string]: unknown } = {};
178
+ for (const [name, check] of Object.entries(spec)) {
179
+ const entry = value[name];
180
+ if (entry === undefined || entry === null || entry === '') continue;
181
+ const checked = check(entry);
182
+ if (checked === INVALID) throw new RichTextError(`${path}.${name} is not valid for ${owner}.`);
183
+ attrs[name] = checked;
184
+ }
185
+ return attrs;
186
+ }
187
+
188
+ function checkMarks(value: unknown, path: string): RichTextMark[] {
189
+ if (value === undefined) return [];
190
+ if (!Array.isArray(value) || value.length > RICH_TEXT_MARKS.length) throw new RichTextError(`${path} must be a list of marks.`);
191
+ const seen = new Set<string>();
192
+ return value.map((mark, index) => {
193
+ if (!isPlainObject(mark) || !(RICH_TEXT_MARKS as readonly string[]).includes(mark.type as string)) throw new RichTextError(`${path}[${index}] is not an allowed mark.`);
194
+ const type = mark.type as string;
195
+ if (seen.has(type)) throw new RichTextError(`${path} repeats ${type}.`);
196
+ seen.add(type);
197
+ const attrs = checkAttributes(type, mark.attrs, `${path}[${index}].attrs`, MARK_ATTRIBUTES[type] ?? {});
198
+ if (type === 'link' && attrs.href === undefined) throw new RichTextError(`${path}[${index}].attrs.href is required.`);
199
+ return Object.freeze(Object.keys(attrs).length ? { type, attrs: Object.freeze(attrs) } : { type });
200
+ });
201
+ }
202
+
203
+ function isPlainObject(value: unknown): value is { [key: string]: unknown } {
204
+ return value !== null && typeof value === 'object' && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
205
+ }
206
+
207
+ /** An empty document. */
208
+ export function emptyRichText(): RichTextDoc {
209
+ return { type: 'doc', content: [] };
210
+ }
211
+
212
+ /** Plain text as a document: blank lines separate paragraphs, single line breaks stay. */
213
+ export function richTextFromPlain(text: string): RichTextDoc {
214
+ const paragraphs = String(text ?? '').replace(/\r\n?/g, '\n').split(/\n{2,}/).map(part => part.trim()).filter(Boolean);
215
+ return {
216
+ type: 'doc',
217
+ content: paragraphs.map(paragraph => ({
218
+ type: 'paragraph',
219
+ content: paragraph.split('\n').flatMap((line, index): RichTextNode[] => [...(index ? [{ type: 'hardBreak' }] : []), ...(line ? [{ type: 'text', text: line }] : [])]),
220
+ })),
221
+ };
222
+ }
223
+
224
+ /** True when the document has no text, images or blocks. */
225
+ export function richTextEmpty(doc: RichTextDoc | null | undefined): boolean {
226
+ return !doc || !richTextPlain(doc).trim() && !doc.content.some(function visual(node): boolean {
227
+ return node.type === 'image' || node.type === 'cmsBlock' || node.type === 'horizontalRule' || (node.content ?? []).some(visual);
228
+ });
229
+ }
230
+
231
+ /** The document's text, with blank lines between blocks, for search and excerpts. */
232
+ export function richTextPlain(doc: RichTextDoc | null | undefined, max: number = RICH_TEXT_LIMITS.text): string {
233
+ if (!doc || !Array.isArray(doc.content)) return '';
234
+ const parts: string[] = [];
235
+ let length = 0;
236
+ const inline = (nodes: readonly RichTextNode[] = []) => nodes.map(node => node.type === 'text' ? node.text ?? '' : node.type === 'hardBreak' ? '\n' : '').join('');
237
+ const visit = (nodes: readonly RichTextNode[]) => {
238
+ for (const node of nodes) {
239
+ if (length >= max) return;
240
+ if (node.type === 'paragraph' || node.type === 'heading' || node.type === 'codeBlock') {
241
+ const value = inline(node.content).trim();
242
+ if (value) { parts.push(value); length += value.length + 2; }
243
+ } else if (node.type === 'image' && typeof node.attrs?.alt === 'string' && node.attrs.alt) {
244
+ parts.push(node.attrs.alt);
245
+ length += node.attrs.alt.length + 2;
246
+ } else visit(node.content ?? []);
247
+ }
248
+ };
249
+ visit(doc.content);
250
+ const value = parts.join('\n\n');
251
+ return value.length > max ? value.slice(0, max) : value;
252
+ }
253
+
254
+ /** The document's first `words` words, with an ellipsis when cut. */
255
+ export function richTextExcerpt(doc: RichTextDoc | null | undefined, words = 55): string {
256
+ const all = richTextPlain(doc, words * 40).replace(/\s+/g, ' ').trim().split(' ').filter(Boolean);
257
+ return all.length > words ? `${all.slice(0, words).join(' ')}…` : all.join(' ');
258
+ }
259
+
260
+ /** The blocks a document embeds, in order. */
261
+ export function richTextBlocks(doc: RichTextDoc | null | undefined): EmbeddedBlock[] {
262
+ return (doc?.content ?? []).filter(node => node.type === 'cmsBlock' && node.attrs).map(node => ({
263
+ _id: node.attrs!._id as string, type: node.attrs!.type as string, data: (node.attrs!.data ?? {}) as EmbeddedBlock['data'],
264
+ ...(node.attrs!.layout ? { layout: node.attrs!.layout as EmbeddedBlock['layout'] } : {}),
265
+ ...(node.attrs!.style ? { style: node.attrs!.style as EmbeddedBlock['style'] } : {}),
266
+ ...(node.attrs!.children ? { children: node.attrs!.children as EmbeddedBlock['children'] } : {}),
267
+ }));
268
+ }
269
+
270
+ /** Media file IDs of the document's images. Embedded blocks report their own. */
271
+ export function richTextMedia(doc: RichTextDoc | null | undefined): string[] {
272
+ const ids = new Set<string>();
273
+ const visit = (nodes: readonly RichTextNode[]) => {
274
+ for (const node of nodes) {
275
+ if (node.type === 'image' && typeof node.attrs?.mediaId === 'string') ids.add(node.attrs.mediaId);
276
+ visit(node.content ?? []);
277
+ }
278
+ };
279
+ visit(doc?.content ?? []);
280
+ return [...ids];
281
+ }
282
+
283
+ /** Replace the embedded blocks, in order, with checked ones: their data with defaults applied. */
284
+ export function withRichTextBlocks(doc: RichTextDoc, blocks: readonly EmbeddedBlock[]): RichTextDoc {
285
+ const byId = new Map(blocks.map(block => [block._id, block]));
286
+ return Object.freeze({
287
+ type: 'doc',
288
+ content: Object.freeze(doc.content.map(node => {
289
+ const block = node.type === 'cmsBlock' ? byId.get(node.attrs?._id as string) : undefined;
290
+ return block ? Object.freeze({ type: 'cmsBlock', attrs: Object.freeze({ _id: block._id, type: block.type, data: block.data, ...(block.layout ? { layout: block.layout } : {}), ...(block.style ? { style: block.style } : {}), ...(block.children ? { children: block.children } : {}) }) }) : node;
291
+ })),
292
+ });
293
+ }
294
+
295
+ export interface RichTextMediaInfo {
296
+ readonly url: string;
297
+ readonly width?: number | null;
298
+ readonly height?: number | null;
299
+ /** Resized variants, for `srcset`. */
300
+ readonly srcset?: string;
301
+ }
302
+
303
+ export interface RichTextRenderOptions {
304
+ /** Current file details by media ID; null hides an image whose file is gone. Without it, stored sources are used. */
305
+ readonly media?: (id: string) => RichTextMediaInfo | null | undefined;
306
+ /** HTML for an embedded block in `richTextHtml`; omitted when absent. */
307
+ readonly block?: (block: EmbeddedBlock) => string;
308
+ /** Rewrites each text run before it is escaped, such as resolving `{{ $.price }}` bindings. Inline code and code blocks keep their text. */
309
+ readonly text?: (text: string) => string;
310
+ }
311
+
312
+ /** A run of HTML, or an embedded block for the theme to render. */
313
+ export type ContentPart = { readonly kind: 'html'; readonly html: string } | { readonly kind: 'block'; readonly block: EmbeddedBlock };
314
+
315
+ /** The document split at its embedded blocks: HTML runs and blocks, in order. */
316
+ export function richTextParts(doc: RichTextDoc | null | undefined, options: RichTextRenderOptions = {}): ContentPart[] {
317
+ const parts: ContentPart[] = [];
318
+ let run = '';
319
+ for (const node of doc?.content ?? []) {
320
+ if (node.type === 'cmsBlock') {
321
+ if (run) parts.push({ kind: 'html', html: run });
322
+ run = '';
323
+ const [block] = richTextBlocks({ type: 'doc', content: [node] });
324
+ if (block) parts.push({ kind: 'block', block });
325
+ } else run += nodeHtml(node, options);
326
+ }
327
+ if (run) parts.push({ kind: 'html', html: run });
328
+ return parts;
329
+ }
330
+
331
+ /** The document as HTML. Text and attributes are escaped; blocks render through `options.block`. */
332
+ export function richTextHtml(doc: RichTextDoc | null | undefined, options: RichTextRenderOptions = {}): string {
333
+ return (doc?.content ?? []).map(node => node.type === 'cmsBlock' ? options.block?.(richTextBlocks({ type: 'doc', content: [node] })[0]!) ?? '' : nodeHtml(node, options)).join('');
334
+ }
335
+
336
+ const ESCAPES: { readonly [character: string]: string } = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
337
+
338
+ export function escapeHtml(value: string): string {
339
+ return value.replace(/[&<>"']/g, character => ESCAPES[character]!);
340
+ }
341
+
342
+ const MARK_ORDER = ['link', 'bold', 'italic', 'underline', 'strike', 'code'];
343
+ const MARK_TAGS: { readonly [type: string]: string } = { bold: 'strong', italic: 'em', underline: 'u', strike: 's', code: 'code' };
344
+
345
+ function nodeHtml(node: RichTextNode, options: RichTextRenderOptions): string {
346
+ const children = () => (node.content ?? []).map(child => nodeHtml(child, options)).join('');
347
+ const alignment = typeof node.attrs?.textAlign === 'string' && ALIGNMENTS.has(node.attrs.textAlign) && node.attrs.textAlign !== 'left' ? ` style="text-align: ${node.attrs.textAlign}"` : '';
348
+ switch (node.type) {
349
+ case 'text': {
350
+ const code = node.marks?.some(mark => mark.type === 'code');
351
+ let html = escapeHtml(options.text && !code ? options.text(node.text ?? '') : node.text ?? '');
352
+ const marks = [...(node.marks ?? [])].sort((a, b) => MARK_ORDER.indexOf(b.type) - MARK_ORDER.indexOf(a.type));
353
+ for (const mark of marks) {
354
+ if (mark.type === 'link') {
355
+ if (!safeLinkUrl(mark.attrs?.href)) continue;
356
+ const external = mark.attrs?.target === '_blank';
357
+ html = `<a href="${escapeHtml(mark.attrs.href as string)}"${external ? ' target="_blank" rel="noopener noreferrer"' : ''}>${html}</a>`;
358
+ } else if (MARK_TAGS[mark.type]) html = `<${MARK_TAGS[mark.type]}>${html}</${MARK_TAGS[mark.type]}>`;
359
+ }
360
+ return html;
361
+ }
362
+ case 'hardBreak': return '<br>';
363
+ case 'paragraph': return `<p${alignment}>${children()}</p>`;
364
+ case 'heading': {
365
+ const level = Number.isInteger(node.attrs?.level) ? Math.min(Math.max(node.attrs!.level as number, 1), 6) : 2;
366
+ return `<h${level}${alignment}>${children()}</h${level}>`;
367
+ }
368
+ case 'blockquote': return `<blockquote>${children()}</blockquote>`;
369
+ case 'bulletList': return `<ul>${children()}</ul>`;
370
+ case 'orderedList': {
371
+ const start = Number.isSafeInteger(node.attrs?.start) && node.attrs!.start !== 1 ? ` start="${node.attrs!.start as number}"` : '';
372
+ return `<ol${start}>${children()}</ol>`;
373
+ }
374
+ case 'listItem': return `<li>${children()}</li>`;
375
+ case 'codeBlock': {
376
+ const language = typeof node.attrs?.language === 'string' && LANGUAGE.test(node.attrs.language) ? node.attrs.language : '';
377
+ const code = (node.content ?? []).map(child => child.text ?? '').join('');
378
+ return `<pre class="cms-code"><code${language ? ` class="language-${language}"` : ''}>${highlightCode(code, language)}</code></pre>`;
379
+ }
380
+ case 'horizontalRule': return '<hr>';
381
+ case 'table': return `<div class="cms-table"><table>${children()}</table></div>`;
382
+ case 'tableRow': return `<tr>${children()}</tr>`;
383
+ case 'tableCell': case 'tableHeader': {
384
+ const tag = node.type === 'tableHeader' ? 'th' : 'td';
385
+ const colspan = Number.isInteger(node.attrs?.colspan) && node.attrs!.colspan !== 1 ? ` colspan="${node.attrs!.colspan as number}"` : '';
386
+ const rowspan = Number.isInteger(node.attrs?.rowspan) && node.attrs!.rowspan !== 1 ? ` rowspan="${node.attrs!.rowspan as number}"` : '';
387
+ return `<${tag}${colspan}${rowspan}>${children()}</${tag}>`;
388
+ }
389
+ case 'image': {
390
+ const mediaId = typeof node.attrs?.mediaId === 'string' ? node.attrs.mediaId : null;
391
+ const info = mediaId && options.media ? options.media(mediaId) : undefined;
392
+ if (info === null) return '';
393
+ const src = info?.url ?? node.attrs?.src;
394
+ if (!safeImageUrl(src)) return '';
395
+ const size = info?.width && info.height ? ` width="${info.width}" height="${info.height}"` : '';
396
+ const title = typeof node.attrs?.title === 'string' && node.attrs.title ? ` title="${escapeHtml(node.attrs.title)}"` : '';
397
+ const srcset = info?.srcset ? ` srcset="${escapeHtml(info.srcset)}" sizes="(min-width: 768px) 768px, 100vw"` : '';
398
+ return `<img src="${escapeHtml(src)}"${srcset} alt="${escapeHtml(typeof node.attrs?.alt === 'string' ? node.attrs.alt : '')}"${title}${size} loading="lazy" decoding="async">`;
399
+ }
400
+ default: return '';
401
+ }
402
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * JSON Schema (draft 2020-12) for a resource's records as the content API answers and takes
3
+ * them: one property per declared field, typed from its declaration. Editors use it for
4
+ * completion and linting in the JSON tab; imports and API clients validate against it.
5
+ * Client-safe.
6
+ */
7
+ import type { FieldDeclaration } from './fields';
8
+
9
+ export type JsonSchema = { [keyword: string]: unknown };
10
+
11
+ const BLOCK_SCHEMA: JsonSchema = {
12
+ type: 'object',
13
+ properties: {
14
+ _id: { type: 'string', description: 'Distinct among the blocks of the field; 1 to 40 letters, digits, _ or -.' },
15
+ type: { type: 'string', description: 'The block type, such as core/paragraph.' },
16
+ data: { type: 'object', description: 'The block\'s fields, by name.' },
17
+ layout: { type: 'object' },
18
+ style: { type: 'object' },
19
+ when: { type: 'object', description: 'In a form: when the block shows.' },
20
+ children: { type: 'array', items: { $ref: '#/$defs/block' } },
21
+ },
22
+ required: ['_id', 'type', 'data'],
23
+ };
24
+
25
+ const RICH_TEXT_SCHEMA: JsonSchema = {
26
+ type: 'object',
27
+ description: 'A ProseMirror document.',
28
+ properties: { type: { const: 'doc' }, content: { type: 'array', items: { type: 'object' } } },
29
+ required: ['type', 'content'],
30
+ };
31
+
32
+ /** The schema of one value of the declaration's kind, before `multiple` and `nullable` apply. */
33
+ function valueSchema(declaration: FieldDeclaration): JsonSchema {
34
+ switch (declaration.kind) {
35
+ case 'string': return {
36
+ type: 'string',
37
+ ...(declaration.min !== undefined ? { minLength: declaration.min } : {}),
38
+ ...(declaration.max !== undefined ? { maxLength: declaration.max } : {}),
39
+ ...(declaration.pattern ? { pattern: `^(?:${declaration.pattern})$` } : {}),
40
+ ...(declaration.media ? { description: 'The ID of a media file.' } : declaration.taxonomy ? { description: `The ID of a ${declaration.taxonomy} term.` } : {}),
41
+ };
42
+ case 'text': return {
43
+ type: 'string',
44
+ ...(declaration.min !== undefined ? { minLength: declaration.min } : {}),
45
+ ...(declaration.max !== undefined ? { maxLength: declaration.max } : {}),
46
+ ...(declaration.format === 'markdown' ? { description: 'Markdown.' } : {}),
47
+ };
48
+ case 'enum': return { type: 'string', enum: [...(declaration.values ?? [])] };
49
+ case 'integer': return { type: 'integer', ...(declaration.min !== undefined ? { minimum: declaration.min } : {}), ...(declaration.max !== undefined ? { maximum: declaration.max } : {}) };
50
+ case 'datetime': return { type: 'integer', description: 'Milliseconds since 1970-01-01T00:00:00Z.' };
51
+ case 'bigint': return { type: 'string', pattern: '^-?[0-9]+$', description: 'A big integer, as a decimal string.' };
52
+ case 'number': return { type: 'number', ...(declaration.min !== undefined ? { minimum: declaration.min } : {}), ...(declaration.max !== undefined ? { maximum: declaration.max } : {}) };
53
+ case 'boolean': return { type: 'boolean' };
54
+ case 'reference': return { type: 'string', description: `The ID of a ${declaration.target ?? ''} record.` };
55
+ case 'vector': return { type: 'array', items: { type: 'number' }, ...(declaration.dimensions ? { minItems: declaration.dimensions, maxItems: declaration.dimensions } : {}) };
56
+ case 'blocks': return { type: 'array', items: { $ref: '#/$defs/block' }, ...(declaration.blocks ? { description: `Blocks of these types: ${declaration.blocks.join(', ')}.` } : {}) };
57
+ case 'richtext': return { $ref: '#/$defs/richText' };
58
+ case 'rows': return {
59
+ type: 'array',
60
+ items: { type: 'object', properties: { _id: { type: 'string' }, ...propertiesOf(declaration.fields ?? {}) }, required: requiredOf(declaration.fields ?? {}) },
61
+ ...(declaration.min !== undefined ? { minItems: declaration.min } : {}),
62
+ ...(declaration.max !== undefined ? { maxItems: declaration.max } : {}),
63
+ };
64
+ case 'json': return declaration.fields && Object.keys(declaration.fields).length
65
+ ? { type: 'object', properties: propertiesOf(declaration.fields) }
66
+ : { type: ['object', 'array', 'string', 'number', 'boolean', 'null'] };
67
+ }
68
+ }
69
+
70
+ /** A field's schema: the value, a list of them for multiple fields, null allowed when nullable. */
71
+ export function fieldSchema(declaration: FieldDeclaration): JsonSchema {
72
+ const value = valueSchema(declaration);
73
+ const shaped = declaration.multiple
74
+ ? { type: 'array', items: value, ...(declaration.minItems !== undefined ? { minItems: declaration.minItems } : {}), ...(declaration.maxItems !== undefined ? { maxItems: declaration.maxItems } : {}) }
75
+ : value;
76
+ const described = { ...(declaration.label ? { title: declaration.label } : {}), ...(declaration.description ? { description: declaration.description } : {}), ...(declaration.default !== undefined ? { default: declaration.default } : {}) };
77
+ return declaration.nullable && !declaration.multiple ? { ...described, anyOf: [shaped, { type: 'null' }] } : { ...described, ...shaped };
78
+ }
79
+
80
+ function propertiesOf(fields: { readonly [name: string]: FieldDeclaration }): { [name: string]: JsonSchema } {
81
+ return Object.fromEntries(Object.entries(fields).map(([name, declaration]) => [name, fieldSchema(declaration)]));
82
+ }
83
+
84
+ function requiredOf(fields: { readonly [name: string]: FieldDeclaration }): string[] {
85
+ return Object.entries(fields).filter(([, declaration]) => declaration.required).map(([name]) => name);
86
+ }
87
+
88
+ /**
89
+ * The schema of a resource's records: its fields, and the read-only properties every record
90
+ * carries (`id`, `rev`, the dates, `owner`, `url`). Unknown properties are rejected, as a
91
+ * write would reject them.
92
+ */
93
+ export function recordSchema(resource: { readonly id: string; readonly label?: string; readonly fields: { readonly [name: string]: FieldDeclaration } }): JsonSchema {
94
+ return {
95
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
96
+ $id: `urn:cossack:cms:${resource.id}`,
97
+ title: resource.label ?? resource.id,
98
+ type: 'object',
99
+ properties: {
100
+ id: { type: 'string', readOnly: true },
101
+ rev: { type: 'integer', readOnly: true, description: 'The revision number; grows with every write.' },
102
+ createdAt: { type: 'integer', readOnly: true },
103
+ updatedAt: { type: 'integer', readOnly: true },
104
+ owner: { type: ['string', 'null'], readOnly: true },
105
+ url: { type: ['string', 'null'], readOnly: true, description: 'The public URL, when the entry is on the site.' },
106
+ ...propertiesOf(resource.fields),
107
+ },
108
+ required: requiredOf(resource.fields),
109
+ additionalProperties: false,
110
+ $defs: { block: BLOCK_SCHEMA, richText: RICH_TEXT_SCHEMA },
111
+ };
112
+ }
package/src/search.ts ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * What a person types into a search box, turned into RomeDB full-text syntax that never fails.
3
+ *
4
+ * RomeDB's index splits text on anything that is not a letter or a digit, lowercases it and
5
+ * drops tokens of 40 bytes or more (its `default` tokenizer). The parser cuts words the same
6
+ * way, so every word it sends can match, and quotes each one so no word reads as syntax
7
+ * (`AND`, `NOT`, `title:`, `^2`, `*`). The last word typed is a prefix, so a search
8
+ * finds while someone is still typing. Snippets come from RomeDB (`search::snippet`).
9
+ */
10
+
11
+ /** Bounds on a search: characters read from the input, words and phrases kept, and the RomeDB query size. */
12
+ export const SEARCH_LIMITS = { input: 500, terms: 32, excluded: 8, bytes: 4096, tokenBytes: 40 } as const;
13
+
14
+ /** A search ready for `search::text`. */
15
+ export interface SearchQuery {
16
+ /** Every word and phrase required, and `-word` excluded: what a search runs first. */
17
+ readonly all: string;
18
+ /** Any of the words or phrases, for when nothing has them all; null when that is the same search. */
19
+ readonly any: string | null;
20
+ }
21
+
22
+ const WORD = /[\p{Alphabetic}\p{N}]+/gu;
23
+ const encoder = new TextEncoder();
24
+
25
+ /** The words RomeDB indexes in `text`: letters and digits, lowercased, under 40 bytes each. */
26
+ export function searchWords(text: string): string[] {
27
+ return (text.match(WORD) ?? []).map(word => word.toLowerCase()).filter(word => encoder.encode(word).byteLength < SEARCH_LIMITS.tokenBytes);
28
+ }
29
+
30
+ /**
31
+ * Parse what someone typed. Words are all required, as WordPress searches. Balanced
32
+ * `"quoted phrases"` stay phrases, and so does a word that punctuation splits (`e-mail`,
33
+ * `example.com`), the way it was indexed. `-word` and `-"a phrase"` exclude when something
34
+ * else is searched. The word the text ends with is a prefix (`hel` finds `hello`) when it has
35
+ * two characters or more, or ends a split word (`e-m`); a quoted phrase, an excluded word or a
36
+ * trailing space keeps it exact. Anything else is text. Null when nothing searchable is left.
37
+ */
38
+ export function searchQuery(text: string): SearchQuery | null {
39
+ if (typeof text !== 'string') return null;
40
+ const input = text.slice(0, SEARCH_LIMITS.input);
41
+ const include = new Map<string, string[]>();
42
+ const exclude = new Map<string, string[]>();
43
+ // The last word typed, while it is still the last thing in the text: a prefix.
44
+ let tail: string | null = null;
45
+ const add = (into: Map<string, string[]>, words: string[]) => {
46
+ if (!words.length) return null;
47
+ const key = words.join(' ');
48
+ into.set(key, words);
49
+ return key;
50
+ };
51
+ // Odd segments sit between two quotes; a last quote without a partner is plain text.
52
+ const segments = input.split('"');
53
+ for (const [index, segment] of segments.entries()) {
54
+ if (index % 2 === 1 && index < segments.length - 1) {
55
+ add(/(^|\s)-$/.test(segments[index - 1]!) ? exclude : include, searchWords(segment));
56
+ tail = null;
57
+ continue;
58
+ }
59
+ for (const chunk of segment.split(/\s+/)) {
60
+ const negative = chunk.length > 1 && chunk.startsWith('-');
61
+ const key = add(negative ? exclude : include, searchWords(negative ? chunk.slice(1) : chunk));
62
+ tail = negative ? null : key;
63
+ }
64
+ }
65
+ const included = [...include.values()].slice(0, SEARCH_LIMITS.terms);
66
+ if (!included.length) return null;
67
+ const keys = new Set(include.keys());
68
+ const excluded = [...exclude.entries()].filter(([key]) => !keys.has(key)).map(([, words]) => words).slice(0, SEARCH_LIMITS.excluded);
69
+ // RomeDB wants two characters before a one-word prefix's `*`; a split word's phrase prefix needs none.
70
+ const prefix = tail === null ? null : include.get(tail)!;
71
+ const growing = prefix !== null && (prefix.length > 1 || [...prefix[0]!].length > 1) ? prefix : null;
72
+ const term = (words: string[]) => `"${words.join(' ')}"${words === growing ? '*' : ''}`;
73
+ const not = excluded.map(words => `-"${words.join(' ')}"`);
74
+ const all = [...included.map(words => `+${term(words)}`), ...not].join(' ');
75
+ const any = included.length > 1 ? [...included.map(term), ...not].join(' ') : null;
76
+ return { all, any };
77
+ }
78
+
79
+ /** Whether a RomeDB error is about a full-text query, so the CMS can answer 400 rather than 500. */
80
+ export function isSearchSyntaxError(error: unknown): boolean {
81
+ const message = error instanceof Error ? error.message : typeof error === 'object' && error !== null && typeof (error as { message?: unknown }).message === 'string' ? (error as { message: string }).message : '';
82
+ return /\bfulltext:|full-text query|FTS parse error/.test(message);
83
+ }
84
+
85
+ /** One piece of a snippet, as RomeDB's `search::snippet` returns it: plain text, and whether it is a matched word. Never markup. */
86
+ export interface SnippetPart {
87
+ readonly text: string;
88
+ readonly match: boolean;
89
+ }