@cossackframework/cms 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +147 -2
- package/agent-docs.json +259 -0
- package/app/README.md +78 -0
- package/app/cossack-recipe.json +43 -0
- package/app/src/auth-bot-check.ts +32 -0
- package/app/src/auth-bot-token.ts +11 -0
- package/app/src/auth-input.ts +35 -0
- package/app/src/auth-options.ts +18 -0
- package/app/src/auth-providers.ts +16 -0
- package/app/src/auth.ts +1082 -0
- package/app/src/brand.ts +68 -0
- package/app/src/cms/ai.ts +54 -0
- package/app/src/cms/analytics.ts +33 -0
- package/app/src/cms/block-errors.ts +55 -0
- package/app/src/cms/block-inserter.ts +111 -0
- package/app/src/cms/block-panel.ts +68 -0
- package/app/src/cms/block-rows.ts +44 -0
- package/app/src/cms/block-tree.ts +585 -0
- package/app/src/cms/blocks.css +708 -0
- package/app/src/cms/builder.ts +126 -0
- package/app/src/cms/cache.ts +44 -0
- package/app/src/cms/carousel.client.ts +52 -0
- package/app/src/cms/collab/presence.ts +69 -0
- package/app/src/cms/collab/rich-text-collab.client.ts +197 -0
- package/app/src/cms/collab/rich-text-notes.client.ts +138 -0
- package/app/src/cms/collab/room.ts +881 -0
- package/app/src/cms/compare.client.ts +47 -0
- package/app/src/cms/condition-control.ts +109 -0
- package/app/src/cms/content-api.ts +143 -0
- package/app/src/cms/content.ts +524 -0
- package/app/src/cms/countdown.client.ts +37 -0
- package/app/src/cms/editor-layout-editor.ts +260 -0
- package/app/src/cms/editor-layout-view.ts +37 -0
- package/app/src/cms/editor.ts +381 -0
- package/app/src/cms/entry.ts +26 -0
- package/app/src/cms/feeds.ts +145 -0
- package/app/src/cms/field-controls.ts +222 -0
- package/app/src/cms/field-group-editor.ts +105 -0
- package/app/src/cms/field-group-view.ts +211 -0
- package/app/src/cms/form-view.ts +203 -0
- package/app/src/cms/form.client.ts +203 -0
- package/app/src/cms/guards.ts +27 -0
- package/app/src/cms/handoff.ts +202 -0
- package/app/src/cms/headings.ts +51 -0
- package/app/src/cms/icons.ts +80 -0
- package/app/src/cms/import.client.ts +16 -0
- package/app/src/cms/index.ts +191 -0
- package/app/src/cms/lightbox.client.ts +109 -0
- package/app/src/cms/machine.ts +118 -0
- package/app/src/cms/maintenance.ts +97 -0
- package/app/src/cms/manage.ts +1236 -0
- package/app/src/cms/mcp-tools.ts +388 -0
- package/app/src/cms/mcp.ts +242 -0
- package/app/src/cms/media-chooser.ts +123 -0
- package/app/src/cms/media-usage.ts +57 -0
- package/app/src/cms/middleware.ts +199 -0
- package/app/src/cms/middlewares.ts +13 -0
- package/app/src/cms/network-ui.ts +36 -0
- package/app/src/cms/network-view.ts +38 -0
- package/app/src/cms/notes-announce.ts +65 -0
- package/app/src/cms/notes-rail.ts +207 -0
- package/app/src/cms/notification-rules.ts +66 -0
- package/app/src/cms/recovery.ts +82 -0
- package/app/src/cms/replace.ts +63 -0
- package/app/src/cms/reserved-paths.ts +19 -0
- package/app/src/cms/rich-text-field.ts +325 -0
- package/app/src/cms/rich-text-schema.ts +91 -0
- package/app/src/cms/rich-text.client.ts +255 -0
- package/app/src/cms/search.client.ts +116 -0
- package/app/src/cms/seo-head.ts +78 -0
- package/app/src/cms/seo.ts +241 -0
- package/app/src/cms/settings-draft.ts +218 -0
- package/app/src/cms/settings-file.ts +127 -0
- package/app/src/cms/settings-form.ts +180 -0
- package/app/src/cms/settings-languages.ts +125 -0
- package/app/src/cms/settings-nav.ts +102 -0
- package/app/src/cms/settings-network.ts +151 -0
- package/app/src/cms/settings-permalinks.ts +114 -0
- package/app/src/cms/settings-scroll.ts +10 -0
- package/app/src/cms/settings-search.ts +77 -0
- package/app/src/cms/settings-section.ts +38 -0
- package/app/src/cms/share.client.ts +27 -0
- package/app/src/cms/site-editing.ts +219 -0
- package/app/src/cms/site-editor.client.ts +1008 -0
- package/app/src/cms/site-editor.ts +99 -0
- package/app/src/cms/site-export.ts +60 -0
- package/app/src/cms/site-forms.ts +143 -0
- package/app/src/cms/site-import.ts +28 -0
- package/app/src/cms/site-session.ts +36 -0
- package/app/src/cms/site-taskbar.ts +77 -0
- package/app/src/cms/site-view.ts +1014 -0
- package/app/src/cms/site.ts +1322 -0
- package/app/src/cms/sitemaps.ts +131 -0
- package/app/src/cms/stat.client.ts +56 -0
- package/app/src/cms/style-controls.ts +252 -0
- package/app/src/cms/tabs.client.ts +36 -0
- package/app/src/cms/taskbar.ts +134 -0
- package/app/src/cms/term-icons.ts +10 -0
- package/app/src/cms/traffic.ts +26 -0
- package/app/src/cms/ui.ts +170 -0
- package/app/src/cms/updates.ts +124 -0
- package/app/src/cms/uploads.ts +26 -0
- package/app/src/cms/worker.ts +13 -0
- package/app/src/config/auth.ts +30 -0
- package/app/src/config/cms.ts +18 -0
- package/app/src/dashboard/access.ts +344 -0
- package/app/src/dashboard/agent-icons.ts +44 -0
- package/app/src/dashboard/app-passwords.ts +74 -0
- package/app/src/dashboard/avatar-field.ts +58 -0
- package/app/src/dashboard/bulk.ts +53 -0
- package/app/src/dashboard/head.ts +29 -0
- package/app/src/dashboard/icons.ts +15 -0
- package/app/src/dashboard/list-table.ts +120 -0
- package/app/src/dashboard/modules/roles.ts +15 -0
- package/app/src/dashboard/modules/sessions.ts +15 -0
- package/app/src/dashboard/modules/settings.ts +15 -0
- package/app/src/dashboard/modules/users.ts +18 -0
- package/app/src/dashboard/page.ts +67 -0
- package/app/src/dashboard/registry.ts +13 -0
- package/app/src/dashboard/session-list.ts +98 -0
- package/app/src/dashboard/tabs.ts +26 -0
- package/app/src/dashboard/time-ago.ts +16 -0
- package/app/src/dashboard/types.ts +40 -0
- package/app/src/dashboard/user-sections.ts +172 -0
- package/app/src/lib/permissions.ts +84 -0
- package/app/src/middlewares/auth.ts +117 -0
- package/app/src/pages/(site)/[...path]/index.ts +609 -0
- package/app/src/pages/(site)/feed/[...rest]/index.ts +13 -0
- package/app/src/pages/(site)/feed/index.ts +12 -0
- package/app/src/pages/(site)/index.ts +11 -0
- package/app/src/pages/(site)/indexnow/[file]/index.ts +18 -0
- package/app/src/pages/(site)/layout.ts +219 -0
- package/app/src/pages/(site)/llms.txt/index.ts +23 -0
- package/app/src/pages/(site)/manifest.webmanifest/index.ts +29 -0
- package/app/src/pages/(site)/media/[id]/[name]/index.ts +59 -0
- package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +115 -0
- package/app/src/pages/(site)/robots.txt/index.ts +29 -0
- package/app/src/pages/(site)/search/index.ts +36 -0
- package/app/src/pages/(site)/sitemap.xml/index.ts +26 -0
- package/app/src/pages/(site)/sitemaps/[file]/index.ts +33 -0
- package/app/src/pages/api/auth/session.ts +48 -0
- package/app/src/pages/api/cms/appearance/areas/[name].ts +12 -0
- package/app/src/pages/api/cms/appearance/areas/index.ts +6 -0
- package/app/src/pages/api/cms/appearance/locations/[location].ts +6 -0
- package/app/src/pages/api/cms/appearance/locations/index.ts +6 -0
- package/app/src/pages/api/cms/appearance/menus/[id].ts +12 -0
- package/app/src/pages/api/cms/appearance/menus/index.ts +13 -0
- package/app/src/pages/api/cms/appearance/themes/[name]/activate.ts +6 -0
- package/app/src/pages/api/cms/appearance/themes/index.ts +6 -0
- package/app/src/pages/api/cms/cache/purge.ts +6 -0
- package/app/src/pages/api/cms/collections/index.ts +6 -0
- package/app/src/pages/api/cms/commands/[plugin]/[command].ts +26 -0
- package/app/src/pages/api/cms/comments/[id].ts +9 -0
- package/app/src/pages/api/cms/comments/index.ts +126 -0
- package/app/src/pages/api/cms/comments/queue.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/autosave.ts +27 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/blocks/[block].ts +16 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/notes.ts +18 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/publish.ts +11 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/[revision]/index.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/[revision]/restore.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/index.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/unpublish.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry].ts +42 -0
- package/app/src/pages/api/cms/content/[collection]/index.ts +24 -0
- package/app/src/pages/api/cms/export/[collection].ts +37 -0
- package/app/src/pages/api/cms/forms/[slug]/index.ts +173 -0
- package/app/src/pages/api/cms/forms/[slug]/submissions/[submission]/files/[file].ts +25 -0
- package/app/src/pages/api/cms/forms/[slug]/submissions/export.ts +34 -0
- package/app/src/pages/api/cms/forms/[slug]/submissions/index.ts +24 -0
- package/app/src/pages/api/cms/import/[collection].ts +23 -0
- package/app/src/pages/api/cms/mcp.ts +29 -0
- package/app/src/pages/api/cms/me/index.ts +6 -0
- package/app/src/pages/api/cms/me/recent-blocks.ts +37 -0
- package/app/src/pages/api/cms/me/tokens/[id].ts +6 -0
- package/app/src/pages/api/cms/me/tokens/index.ts +13 -0
- package/app/src/pages/api/cms/media/[id].ts +6 -0
- package/app/src/pages/api/cms/media.ts +26 -0
- package/app/src/pages/api/cms/menus/[location].ts +14 -0
- package/app/src/pages/api/cms/network/sites/[id]/export.ts +15 -0
- package/app/src/pages/api/cms/network/sites/[id]/index.ts +9 -0
- package/app/src/pages/api/cms/network/sites/index.ts +14 -0
- package/app/src/pages/api/cms/notes/[id].ts +13 -0
- package/app/src/pages/api/cms/notes/index.ts +6 -0
- package/app/src/pages/api/cms/payments/webhook.ts +28 -0
- package/app/src/pages/api/cms/plugins/[name]/grant.ts +6 -0
- package/app/src/pages/api/cms/plugins/[name]/revoke.ts +6 -0
- package/app/src/pages/api/cms/plugins/index.ts +6 -0
- package/app/src/pages/api/cms/recovery.ts +29 -0
- package/app/src/pages/api/cms/redirects/index.ts +9 -0
- package/app/src/pages/api/cms/roles/index.ts +6 -0
- package/app/src/pages/api/cms/schema/[collection].ts +13 -0
- package/app/src/pages/api/cms/search.ts +16 -0
- package/app/src/pages/api/cms/settings/[group].ts +9 -0
- package/app/src/pages/api/cms/settings/index.ts +9 -0
- package/app/src/pages/api/cms/site-export.ts +34 -0
- package/app/src/pages/api/cms/taxonomies/index.ts +6 -0
- package/app/src/pages/api/cms/terms/[taxonomy]/[id].ts +12 -0
- package/app/src/pages/api/cms/terms/[taxonomy]/index.ts +9 -0
- package/app/src/pages/api/cms/uploads/[id]/complete.ts +15 -0
- package/app/src/pages/api/cms/uploads/[id]/index.ts +15 -0
- package/app/src/pages/api/cms/uploads/index.ts +26 -0
- package/app/src/pages/api/cms/users/[id]/index.ts +12 -0
- package/app/src/pages/api/cms/users/[id]/meta.ts +40 -0
- package/app/src/pages/api/cms/users/index.ts +12 -0
- package/app/src/pages/api/cms/webhooks/[id].ts +6 -0
- package/app/src/pages/api/cms/webhooks/index.ts +9 -0
- package/app/src/pages/auth/[provider]/callback.ts +11 -0
- package/app/src/pages/auth/[provider]/redirect.ts +9 -0
- package/app/src/pages/auth/forgot-password/index.ts +75 -0
- package/app/src/pages/auth/layout.ts +32 -0
- package/app/src/pages/auth/login/index.ts +198 -0
- package/app/src/pages/auth/magic/index.ts +68 -0
- package/app/src/pages/auth/register/index.ts +117 -0
- package/app/src/pages/auth/reset-password/index.ts +65 -0
- package/app/src/pages/auth/setup/index.ts +194 -0
- package/app/src/pages/auth/two-factor/index.ts +67 -0
- package/app/src/pages/auth/verify/index.ts +62 -0
- package/app/src/pages/dashboard/(cms)/appearance/customize/index.ts +263 -0
- package/app/src/pages/dashboard/(cms)/appearance/dashboard-menu/index.ts +241 -0
- package/app/src/pages/dashboard/(cms)/appearance/index.ts +89 -0
- package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +697 -0
- package/app/src/pages/dashboard/(cms)/appearance/menus/index.ts +145 -0
- package/app/src/pages/dashboard/(cms)/appearance/widgets/index.ts +279 -0
- package/app/src/pages/dashboard/(cms)/blocks/index.ts +84 -0
- package/app/src/pages/dashboard/(cms)/calendar/index.ts +92 -0
- package/app/src/pages/dashboard/(cms)/collections/[name]/index.ts +525 -0
- package/app/src/pages/dashboard/(cms)/collections/index.ts +72 -0
- package/app/src/pages/dashboard/(cms)/collections/new/index.ts +66 -0
- package/app/src/pages/dashboard/(cms)/comments/index.ts +237 -0
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +2382 -0
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +126 -0
- package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +693 -0
- package/app/src/pages/dashboard/(cms)/field-groups/[id]/index.ts +193 -0
- package/app/src/pages/dashboard/(cms)/field-groups/index.ts +65 -0
- package/app/src/pages/dashboard/(cms)/forms/[id]/submissions/[submission]/index.ts +279 -0
- package/app/src/pages/dashboard/(cms)/forms/[id]/submissions/index.ts +170 -0
- package/app/src/pages/dashboard/(cms)/forms/index.ts +171 -0
- package/app/src/pages/dashboard/(cms)/media/[id]/index.ts +317 -0
- package/app/src/pages/dashboard/(cms)/media/index.ts +156 -0
- package/app/src/pages/dashboard/(cms)/media/new/index.ts +9 -0
- package/app/src/pages/dashboard/(cms)/media/summary/index.ts +74 -0
- package/app/src/pages/dashboard/(cms)/my-sites/index.ts +63 -0
- package/app/src/pages/dashboard/(cms)/network/index.ts +53 -0
- package/app/src/pages/dashboard/(cms)/network/plugins/index.ts +110 -0
- package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +243 -0
- package/app/src/pages/dashboard/(cms)/network/sites/index.ts +186 -0
- package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +77 -0
- package/app/src/pages/dashboard/(cms)/network/themes/index.ts +82 -0
- package/app/src/pages/dashboard/(cms)/network/updates/index.ts +48 -0
- package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +176 -0
- package/app/src/pages/dashboard/(cms)/network/users/index.ts +174 -0
- package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +66 -0
- package/app/src/pages/dashboard/(cms)/plugins/index.ts +172 -0
- package/app/src/pages/dashboard/(cms)/profile/public/index.ts +105 -0
- package/app/src/pages/dashboard/(cms)/registrations/index.ts +70 -0
- package/app/src/pages/dashboard/(cms)/settings/index.ts +359 -0
- package/app/src/pages/dashboard/(cms)/settings/json/index.ts +202 -0
- package/app/src/pages/dashboard/(cms)/settings/layout.ts +67 -0
- package/app/src/pages/dashboard/(cms)/taxonomies/[name]/index.ts +85 -0
- package/app/src/pages/dashboard/(cms)/taxonomies/index.ts +98 -0
- package/app/src/pages/dashboard/(cms)/terms/[taxonomy]/[id]/index.ts +244 -0
- package/app/src/pages/dashboard/(cms)/terms/[taxonomy]/index.ts +148 -0
- package/app/src/pages/dashboard/(cms)/tools/activity/index.ts +94 -0
- package/app/src/pages/dashboard/(cms)/tools/automations/index.ts +131 -0
- package/app/src/pages/dashboard/(cms)/tools/cache/index.ts +92 -0
- package/app/src/pages/dashboard/(cms)/tools/export/index.ts +99 -0
- package/app/src/pages/dashboard/(cms)/tools/health/index.ts +189 -0
- package/app/src/pages/dashboard/(cms)/tools/jobs/index.ts +93 -0
- package/app/src/pages/dashboard/(cms)/tools/links/index.ts +115 -0
- package/app/src/pages/dashboard/(cms)/tools/redirects/index.ts +161 -0
- package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +124 -0
- package/app/src/pages/dashboard/(cms)/tools/schema/index.ts +54 -0
- package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +156 -0
- package/app/src/pages/dashboard/(cms)/tools/updates/index.ts +114 -0
- package/app/src/pages/dashboard/(cms)/tools/webhooks/index.ts +182 -0
- package/app/src/pages/dashboard/index.ts +214 -0
- package/app/src/pages/dashboard/layout.ts +320 -0
- package/app/src/pages/dashboard/profile/index.ts +211 -0
- package/app/src/pages/dashboard/profile/security/index.ts +255 -0
- package/app/src/pages/dashboard/roles/[id]/index.ts +116 -0
- package/app/src/pages/dashboard/roles/index.ts +134 -0
- package/app/src/pages/dashboard/roles/new/index.ts +95 -0
- package/app/src/pages/dashboard/sessions/index.ts +105 -0
- package/app/src/pages/dashboard/users/[id]/index.ts +472 -0
- package/app/src/pages/dashboard/users/index.ts +299 -0
- package/app/src/pages/dashboard/users/new/index.ts +123 -0
- package/app/src/passkeys.client.ts +18 -0
- package/app/src/plugins/default-theme/assets/cover.svg +31 -0
- package/app/src/plugins/default-theme/assets/logo.svg +8 -0
- package/app/src/plugins/default-theme/parts/comments.ts +66 -0
- package/app/src/plugins/default-theme/parts/list.ts +38 -0
- package/app/src/plugins/default-theme/parts/media.ts +15 -0
- package/app/src/plugins/default-theme/parts/options.ts +45 -0
- package/app/src/plugins/default-theme/plugin.json +275 -0
- package/app/src/plugins/default-theme/templates/archive.ts +14 -0
- package/app/src/plugins/default-theme/templates/entry-blank.ts +13 -0
- package/app/src/plugins/default-theme/templates/entry.ts +27 -0
- package/app/src/plugins/default-theme/templates/home.ts +8 -0
- package/app/src/plugins/default-theme/templates/layout.ts +40 -0
- package/app/src/plugins/default-theme/templates/not-found.ts +10 -0
- package/app/src/plugins/default-theme/templates/search.ts +32 -0
- package/app/src/services/rbac.ts +65 -0
- package/app/src/services/roles.ts +89 -0
- package/app/src/services/users.ts +173 -0
- package/package.json +123 -3
- package/src/automations.ts +95 -0
- package/src/bindings.ts +138 -0
- package/src/block-references.ts +239 -0
- package/src/block-shape.ts +155 -0
- package/src/blocks.ts +1157 -0
- package/src/cache.ts +54 -0
- package/src/checks.ts +198 -0
- package/src/cloudflare-workers.d.ts +13 -0
- package/src/cloudflare.ts +61 -0
- package/src/collab.ts +372 -0
- package/src/collections.ts +421 -0
- package/src/comments.ts +46 -0
- package/src/cron.ts +95 -0
- package/src/dashboard-menu.ts +105 -0
- package/src/diff.ts +113 -0
- package/src/editor-layout.ts +316 -0
- package/src/errors.ts +50 -0
- package/src/field-groups.ts +498 -0
- package/src/fields.ts +411 -0
- package/src/form-builder.ts +1053 -0
- package/src/forms.ts +109 -0
- package/src/highlight.ts +134 -0
- package/src/hooks.ts +510 -0
- package/src/icon-catalog.ts +55 -0
- package/src/icons.ts +128 -0
- package/src/images.ts +149 -0
- package/src/index.ts +100 -0
- package/src/isolate-core.ts +245 -0
- package/src/isolate.ts +19 -0
- package/src/isolation.ts +69 -0
- package/src/mail.ts +182 -0
- package/src/manifest.ts +476 -0
- package/src/media.ts +193 -0
- package/src/menus.ts +287 -0
- package/src/module.ts +32 -0
- package/src/modules/content.ts +64 -0
- package/src/modules/forms.ts +35 -0
- package/src/node.ts +66 -0
- package/src/notes.ts +237 -0
- package/src/permissions.ts +139 -0
- package/src/plugin-settings.ts +114 -0
- package/src/records.ts +56 -0
- package/src/redirects.ts +59 -0
- package/src/resource.ts +245 -0
- package/src/richtext.ts +402 -0
- package/src/schema-json.ts +112 -0
- package/src/search.ts +89 -0
- package/src/seo.ts +477 -0
- package/src/server/accounts.ts +418 -0
- package/src/server/ai.ts +33 -0
- package/src/server/api-tokens.ts +91 -0
- package/src/server/areas.ts +116 -0
- package/src/server/audit.ts +94 -0
- package/src/server/auth.ts +89 -0
- package/src/server/automations.ts +190 -0
- package/src/server/autosaves.ts +69 -0
- package/src/server/brand-icons.ts +50 -0
- package/src/server/brands.ts +86 -0
- package/src/server/budget.ts +97 -0
- package/src/server/cache.ts +104 -0
- package/src/server/capabilities.ts +333 -0
- package/src/server/cloudflare.ts +92 -0
- package/src/server/comments.ts +237 -0
- package/src/server/drafts.ts +176 -0
- package/src/server/field-groups.ts +88 -0
- package/src/server/files.ts +780 -0
- package/src/server/forms.ts +726 -0
- package/src/server/handoffs.ts +107 -0
- package/src/server/host-schema.ts +312 -0
- package/src/server/host.ts +2892 -0
- package/src/server/images.ts +34 -0
- package/src/server/index.ts +59 -0
- package/src/server/indexnow.ts +91 -0
- package/src/server/isolation.ts +183 -0
- package/src/server/locked.ts +45 -0
- package/src/server/mail.ts +93 -0
- package/src/server/markdown.ts +24 -0
- package/src/server/menus.ts +286 -0
- package/src/server/network-policy.ts +60 -0
- package/src/server/network.ts +665 -0
- package/src/server/notes.ts +275 -0
- package/src/server/outbox.ts +213 -0
- package/src/server/path-moves.ts +33 -0
- package/src/server/payments.ts +59 -0
- package/src/server/previews.ts +62 -0
- package/src/server/purge.ts +140 -0
- package/src/server/reconcile.ts +38 -0
- package/src/server/redirects.ts +183 -0
- package/src/server/repository.ts +1107 -0
- package/src/server/schedules.ts +105 -0
- package/src/server/schema.ts +562 -0
- package/src/server/security.ts +391 -0
- package/src/server/seed.ts +52 -0
- package/src/server/shared-fields.ts +34 -0
- package/src/server/site-export.ts +151 -0
- package/src/server/site-import.ts +482 -0
- package/src/server/site-search.ts +289 -0
- package/src/server/site-settings.ts +286 -0
- package/src/server/sites.ts +243 -0
- package/src/server/stores.ts +314 -0
- package/src/server/stripe.ts +173 -0
- package/src/server/taxonomies.ts +415 -0
- package/src/server/tokens.ts +25 -0
- package/src/server/traffic.ts +118 -0
- package/src/server/users.ts +653 -0
- package/src/server/webhooks.ts +245 -0
- package/src/settings-controls.ts +54 -0
- package/src/settings-document.ts +111 -0
- package/src/settings.ts +426 -0
- package/src/storage/cloudflare.ts +94 -0
- package/src/storage/index.ts +30 -0
- package/src/storage/node.ts +114 -0
- package/src/taxonomy.ts +51 -0
- package/src/theme.ts +1135 -0
- package/src/to-markdown.ts +179 -0
- package/src/updates.ts +126 -0
- package/src/version.ts +2 -0
- package/src/vite.d.ts +25 -0
- package/src/vite.js +199 -0
- package/src/webhooks.ts +107 -0
|
@@ -0,0 +1,1107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resource repositories. Reads compile to bounded parameterized RomeQL with access
|
|
3
|
+
* conditions. Each mutation is one atomic batch: the record statement, then revision,
|
|
4
|
+
* audit and outbox rows guarded by the operation ID the record statement wrote, so a
|
|
5
|
+
* zero-row edit writes nothing else. IDs are allocated before dispatch and the exact
|
|
6
|
+
* request is saved for recovery.
|
|
7
|
+
*/
|
|
8
|
+
import { ClientError, Float64, MAX_STATEMENTS, RecordId, RequestTooLargeError, statementBytes, UncertainWriteError, Vector, type Statement, type Value } from '@cossackframework/romedb';
|
|
9
|
+
import { LIBRARY_KEYS } from './files';
|
|
10
|
+
import type { HookRegistry } from '@cossackframework/core/hooks';
|
|
11
|
+
import { CmsError, isCmsError } from '../errors';
|
|
12
|
+
import { translationGroupOf } from '../collections';
|
|
13
|
+
import { FIELD_NAME, slugify, validateValue, type FieldDeclaration } from '../fields';
|
|
14
|
+
import { blockId, blockMedia, blocksPlain, flattenBlocks, htmlBlocksChanged, textFieldProblem, validateBlocks, type Block } from '../blocks';
|
|
15
|
+
import { fieldVisibility, indexedRowField, rowIndexPath, rowsPlain, rowsSearchable, rowUniqueProblem, withRowIds } from '../field-groups';
|
|
16
|
+
import { normalizeRichText, richTextBlocks, richTextMedia, richTextPlain, withRichTextBlocks, type RichTextDoc } from '../richtext';
|
|
17
|
+
import { searchedAsText, searchTextPath } from './schema';
|
|
18
|
+
import { isSearchSyntaxError, searchQuery } from '../search';
|
|
19
|
+
import { afterCommit, beforeWrite, type Draft, type ResourceEvent, type WriteActor } from '../hooks';
|
|
20
|
+
import { sharedOp, type SharedFieldsEvent } from './shared-fields';
|
|
21
|
+
import { readByIds, readPaged } from './budget';
|
|
22
|
+
import { isLockedRecord, lockedView } from './locked';
|
|
23
|
+
import { ANONYMOUS, evaluateRule, hasPermission, PERMISSIONS, principalId, ruleScope, type Principal, type RecordScope } from '../permissions';
|
|
24
|
+
import type { FieldFilter, ListFilter, ListOptions, RecordPage, RecordShape, RevisionShape } from '../records';
|
|
25
|
+
|
|
26
|
+
export type { FieldFilter, ListFilter, ListOptions };
|
|
27
|
+
import type { AccessRule, Resource, ResourceAction } from '../resource';
|
|
28
|
+
import type { CmsHost } from './host';
|
|
29
|
+
import { uuidv7 } from '@cossackframework/core';
|
|
30
|
+
|
|
31
|
+
export interface OperationContext {
|
|
32
|
+
readonly principal: Principal;
|
|
33
|
+
readonly signal?: AbortSignal;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The translation group a create may join: set only by `translateEntry`, which owns joining a
|
|
38
|
+
* group (rule 3 of specs/cms-invariants.md). A client-set group is refused.
|
|
39
|
+
*/
|
|
40
|
+
export const JOIN_GROUP: unique symbol = Symbol('cms.joinGroup');
|
|
41
|
+
|
|
42
|
+
const KEY = /^[A-Za-z0-9_-]{1,80}$/;
|
|
43
|
+
/** Fields a restored revision does not change: where and whether the entry is published, and its translations. */
|
|
44
|
+
const KEPT_ON_RESTORE = new Set(['status', 'publishedAt', 'parent', 'menuOrder', 'locale', 'translationGroup', 'commentsOpen']);
|
|
45
|
+
|
|
46
|
+
/** RomeDB rejects unused bindings: keep only the parameters a statement references. */
|
|
47
|
+
export function bound(rql: string, params: { readonly [key: string]: Value }): Statement {
|
|
48
|
+
const used = Object.entries(params).filter(([name]) => new RegExp(`\\${name}(?![A-Za-z0-9_])`).test(rql));
|
|
49
|
+
return used.length ? { rql, params: Object.fromEntries(used) } : { rql };
|
|
50
|
+
}
|
|
51
|
+
const SCALAR = new Set(['string', 'enum', 'integer', 'number', 'boolean', 'datetime', 'reference', 'bigint']);
|
|
52
|
+
const RANGED = new Set(['integer', 'number', 'datetime']);
|
|
53
|
+
const ORDERED = new Set(['string', 'enum', 'integer', 'number', 'boolean', 'datetime', 'bigint']);
|
|
54
|
+
type Access = 'allow' | RecordScope;
|
|
55
|
+
const quote = (name: string) => `"${name}"`;
|
|
56
|
+
|
|
57
|
+
export class ResourceRepository {
|
|
58
|
+
readonly #host: CmsHost;
|
|
59
|
+
readonly #id: string;
|
|
60
|
+
|
|
61
|
+
constructor(host: CmsHost, id: string) {
|
|
62
|
+
this.#host = host;
|
|
63
|
+
this.#id = id;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The current declaration. Collections change when an administrator edits them. */
|
|
67
|
+
get resource(): Resource { return this.#host.resourceById(this.#id); }
|
|
68
|
+
|
|
69
|
+
async get(id: string, context: OperationContext): Promise<RecordShape | null> {
|
|
70
|
+
const access = await this.#authorize('read', context.principal);
|
|
71
|
+
if (typeof id !== 'string' || !KEY.test(id)) return null;
|
|
72
|
+
const result = await this.#host.db.read([this.#one(id, access, context.principal)], this.#readOptions(context));
|
|
73
|
+
const document = result.results[0]!.rows[0]?.[0] as Document | undefined;
|
|
74
|
+
return document ? this.#public(document, context.principal) : null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Records by ID, for those the principal may read. Invalid IDs are skipped; at most 200. Whole
|
|
79
|
+
* documents: a set of long entries can pass the result budget, so it may come in smaller reads.
|
|
80
|
+
*/
|
|
81
|
+
async getMany(ids: readonly string[], context: OperationContext): Promise<Map<string, RecordShape>> {
|
|
82
|
+
const access = await this.#authorize('read', context.principal);
|
|
83
|
+
const wanted = [...new Set(ids.filter(id => typeof id === 'string' && KEY.test(id)))].slice(0, 200);
|
|
84
|
+
if (!wanted.length) return new Map();
|
|
85
|
+
const rows = await readByIds(this.#host.db, wanted, slice => {
|
|
86
|
+
const params: { [key: string]: Value } = {};
|
|
87
|
+
const list = slice.map((id, index) => { params[`$k${index}`] = id; return `type::record('${this.resource.storage}', $k${index})`; }).join(', ');
|
|
88
|
+
const { rql, params: bound } = this.#conditions(access, context.principal, [`id IN (${list})`], params);
|
|
89
|
+
return { rql: `SELECT * FROM ${this.resource.storage} WHERE ${rql} LIMIT ${slice.length}`, params: bound };
|
|
90
|
+
}, this.#readOptions(context));
|
|
91
|
+
return new Map(rows.map(row => { const record = this.#public(row[0] as Document, context.principal); return [record.id, record]; }));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async list(options: ListOptions, context: OperationContext): Promise<RecordPage> {
|
|
95
|
+
const access = await this.#authorize('read', context.principal);
|
|
96
|
+
const limit = options.limit ?? 20;
|
|
97
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new CmsError('CMS_VALIDATION', 'limit must be 1..100.');
|
|
98
|
+
const offset = options.offset ?? 0;
|
|
99
|
+
if (!Number.isInteger(offset) || offset < 0 || offset > 10_000) throw new CmsError('CMS_VALIDATION', 'offset must be 0..10000.');
|
|
100
|
+
const params: { [key: string]: Value } = { $limit: limit + 1 };
|
|
101
|
+
const conditions = this.#filters(options, context.principal, params);
|
|
102
|
+
const order = this.#order(options.order);
|
|
103
|
+
// Cursors page through the default order and through the creation or update time.
|
|
104
|
+
const timed = !options.order ? '_updatedAt' : options.order.field === 'createdAt' ? '_createdAt' : options.order.field === 'updatedAt' ? '_updatedAt' : undefined;
|
|
105
|
+
const ascending = options.order?.direction === 'asc';
|
|
106
|
+
if (options.after !== undefined) {
|
|
107
|
+
if (!timed || offset) throw new CmsError('CMS_VALIDATION', 'Cursors apply to the default order, or the creation or update time, without an offset.');
|
|
108
|
+
const cursor = decodeCursor(options.after);
|
|
109
|
+
params.$afterAt = cursor.at;
|
|
110
|
+
params.$afterKey = cursor.key;
|
|
111
|
+
const past = ascending ? '>' : '<';
|
|
112
|
+
conditions.push(`("${timed}" ${past} $afterAt OR ("${timed}" = $afterAt AND record::id(id) ${past} $afterKey))`);
|
|
113
|
+
}
|
|
114
|
+
const where = this.#conditions(access, context.principal, conditions, params);
|
|
115
|
+
// Whole documents: a page of long entries can pass the result budget, so it may come in smaller reads.
|
|
116
|
+
const rows = await readPaged(this.#host.db, (size, at) => bound(
|
|
117
|
+
`SELECT * FROM ${this.resource.storage}${where.rql ? ` WHERE ${where.rql}` : ''} ORDER BY ${order} LIMIT $limit OFFSET $offset`,
|
|
118
|
+
{ ...where.params, $limit: size, $offset: at },
|
|
119
|
+
), limit + 1, offset, this.#readOptions(context));
|
|
120
|
+
const documents = rows.map(row => row[0] as Document);
|
|
121
|
+
const page = documents.slice(0, limit).map(document => this.#public(document, context.principal));
|
|
122
|
+
const last = documents.length > limit && timed && !offset ? documents[limit - 1]! : undefined;
|
|
123
|
+
if (!last) return { records: page, ...(documents.length > limit ? { more: true } : {}) };
|
|
124
|
+
const next = encodeCursor(Number(last[timed!]), (last.id as RecordId).key as string);
|
|
125
|
+
return options.order ? { records: page, next, more: true } : { records: page, next };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Records matching a filter that the principal may read. */
|
|
129
|
+
async count(filter: ListFilter, context: OperationContext): Promise<number> {
|
|
130
|
+
return (await this.countMany([filter], context))[0]!;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Counts for several filters in one read, such as the status tabs of a list. */
|
|
134
|
+
async countMany(filters: readonly ListFilter[], context: OperationContext): Promise<number[]> {
|
|
135
|
+
const access = await this.#authorize('read', context.principal);
|
|
136
|
+
if (filters.length < 1 || filters.length > 30) throw new CmsError('CMS_VALIDATION', 'Count 1-30 filters at a time.');
|
|
137
|
+
const statements = filters.map(filter => {
|
|
138
|
+
const params: { [key: string]: Value } = {};
|
|
139
|
+
const where = this.#conditions(access, context.principal, this.#filters(filter, context.principal, params), params);
|
|
140
|
+
return bound(`SELECT count(*) FROM ${this.resource.storage}${where.rql ? ` WHERE ${where.rql}` : ''}`, where.params);
|
|
141
|
+
});
|
|
142
|
+
const result = await this.#host.db.read(statements, this.#readOptions(context));
|
|
143
|
+
return result.results.map(entry => Number(entry.rows[0]![0] as bigint));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Full-text search over `search: true` fields, for what a person typed (`searchQuery`): every
|
|
148
|
+
* word by default, any word with `match: 'any'`. Empty when nothing searchable was typed.
|
|
149
|
+
* Owner-scoped readers search only their records: allowed IDs are computed first and every
|
|
150
|
+
* hit is checked again in the same query. `offset + limit` stays within RomeDB's 10000 hits.
|
|
151
|
+
*/
|
|
152
|
+
async search(query: string, options: ListFilter & { limit?: number; offset?: number; match?: 'all' | 'any' }, context: OperationContext): Promise<RecordShape[]> {
|
|
153
|
+
const access = await this.#authorize('read', context.principal);
|
|
154
|
+
if (!Object.values(this.resource.fields).some(field => field.search)) throw new CmsError('CMS_VALIDATION', `${this.resource.id} has no searchable fields.`);
|
|
155
|
+
if (typeof query !== 'string') throw new CmsError('CMS_VALIDATION', 'Search needs text.');
|
|
156
|
+
const limit = options.limit ?? 20;
|
|
157
|
+
const offset = options.offset ?? 0;
|
|
158
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 200) throw new CmsError('CMS_VALIDATION', 'limit must be 1..200.');
|
|
159
|
+
if (!Number.isInteger(offset) || offset < 0 || offset + limit > 10_000) throw new CmsError('CMS_VALIDATION', 'Search reaches the first 10000 results.');
|
|
160
|
+
const parsed = searchQuery(query);
|
|
161
|
+
if (!parsed) return [];
|
|
162
|
+
const text = options.match === 'any' ? parsed.any ?? parsed.all : parsed.all;
|
|
163
|
+
const filtered = access !== 'allow' || options.where !== undefined || options.owner !== undefined;
|
|
164
|
+
// Hits are checked again in the outer query; fetch more when some may be filtered out.
|
|
165
|
+
const params: { [key: string]: Value } = { $query: text, $hits: Math.min(filtered ? (offset + limit) * 4 : offset + limit, 10_000) };
|
|
166
|
+
let source = `search::text('${this.resource.storage}__text', $query, $hits)`;
|
|
167
|
+
if (access !== 'allow' && access.owner && !access.where.length) {
|
|
168
|
+
const owned = await this.#host.db.read([{ rql: `SELECT id FROM ${this.resource.storage} WHERE "_owner" = $owner LIMIT 4097`, params: { $owner: principalId(context.principal) } }], this.#readOptions(context));
|
|
169
|
+
if (owned.results[0]!.rows.length > 4096) throw new CmsError('CMS_LIMIT', 'Search over more than 4096 owned records needs a separate collection per owner.');
|
|
170
|
+
params.$allowed = owned.results[0]!.rows.map(row => row[0]!);
|
|
171
|
+
source = `search::text('${this.resource.storage}__text', $query, $hits, $allowed)`;
|
|
172
|
+
}
|
|
173
|
+
const where = this.#conditions(access, context.principal, this.#filters(options, context.principal, params, 'd.'), params, 'd.');
|
|
174
|
+
// Whole documents: a page of long entries can pass the result budget, so it may come in smaller reads.
|
|
175
|
+
const rows = await readPaged(this.#host.db, (size, at) => bound(
|
|
176
|
+
`SELECT d FROM ${source} h JOIN ${this.resource.storage} d ON d.id = h.id${where.rql ? ` WHERE ${where.rql}` : ''} ORDER BY h.score DESC, h.id LIMIT $limit OFFSET $offset`,
|
|
177
|
+
{ ...where.params, $limit: size, $offset: at },
|
|
178
|
+
), limit, offset, this.#readOptions(context)).catch(error => {
|
|
179
|
+
if (isSearchSyntaxError(error)) throw new CmsError('CMS_VALIDATION', 'That search could not be read.');
|
|
180
|
+
throw error;
|
|
181
|
+
});
|
|
182
|
+
return rows.map(row => this.#public(row[0] as Document, context.principal));
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async revisions(id: string, context: OperationContext, options: { limit?: number } = {}): Promise<RevisionShape[]> {
|
|
186
|
+
const { editor, since } = await this.#historyOf(id, context);
|
|
187
|
+
// Each row is a whole snapshot: read in pages that fit the result budget.
|
|
188
|
+
const rows = await readPaged(this.#host.db, (size, at) => ({
|
|
189
|
+
rql: 'SELECT revision, at, actor, data FROM cms_revisions WHERE resource = $resource AND record_id = $key AND at >= $since ORDER BY revision DESC LIMIT $limit OFFSET $offset',
|
|
190
|
+
params: { $resource: this.resource.id, $key: id, $since: since, $limit: size, $offset: at },
|
|
191
|
+
}), options.limit ?? 50, 0, this.#readOptions(context));
|
|
192
|
+
return rows.map(([revision, at, actor, data]) => this.#historyRow(revision, at, actor, data, editor, context.principal))
|
|
193
|
+
.filter((row): row is RevisionShape => row !== null);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* A record's history is editorial: earlier revisions hold drafts and passwords the
|
|
198
|
+
* published record does not show. Those who may change the record read all of it. Holders
|
|
199
|
+
* of the resource's read permission, who read its drafts anyway, read the history of an
|
|
200
|
+
* open record, without passwords or snapshots that were protected or members-only, as
|
|
201
|
+
* export and the API treat them. Answers whether the principal may change the record, and
|
|
202
|
+
* when the record was created: an ID created again after a delete starts a new history, so
|
|
203
|
+
* rows of the deleted record its cleanup job has not removed yet are not its own.
|
|
204
|
+
*/
|
|
205
|
+
async #historyOf(id: string, context: OperationContext): Promise<{ editor: boolean; since: number }> {
|
|
206
|
+
const record = await this.get(id, context);
|
|
207
|
+
if (!record) throw new CmsError('CMS_NOT_FOUND', 'Record not found.');
|
|
208
|
+
const since = record.createdAt;
|
|
209
|
+
if (this.canUpdate(record, context.principal)) return { editor: true, since };
|
|
210
|
+
if (!hasPermission(context.principal, `${this.resource.id}:read`) || isLockedRecord(record)) {
|
|
211
|
+
throw new CmsError('CMS_FORBIDDEN', 'Only editors read this record\'s revisions.');
|
|
212
|
+
}
|
|
213
|
+
return { editor: false, since };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
#historyRow(revision: unknown, at: unknown, actor: unknown, data: unknown, editor: boolean, principal: Principal): RevisionShape | null {
|
|
217
|
+
const snapshot = JSON.parse(data as string) as RecordShape;
|
|
218
|
+
if (!editor && isLockedRecord(snapshot)) return null;
|
|
219
|
+
const shaped = this.#redact(snapshot, principal);
|
|
220
|
+
return { revision: Number(revision), at: Number(at), actor: actor as string | null, data: editor || !('password' in shaped) ? shaped : Object.freeze({ ...shaped, password: null }) as RecordShape };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** One revision's snapshot of a record the principal may change, or null. */
|
|
224
|
+
async revision(id: string, revision: number, context: OperationContext): Promise<RevisionShape | null> {
|
|
225
|
+
const { editor, since } = await this.#historyOf(id, context);
|
|
226
|
+
if (!Number.isSafeInteger(revision) || revision < 1) return null;
|
|
227
|
+
const result = await this.#host.db.read([{
|
|
228
|
+
rql: 'SELECT revision, at, actor, data FROM cms_revisions WHERE resource = $resource AND record_id = $key AND revision = $revision AND at >= $since',
|
|
229
|
+
params: { $resource: this.resource.id, $key: id, $revision: revision, $since: since },
|
|
230
|
+
}], this.#readOptions(context));
|
|
231
|
+
const row = result.results[0]!.rows[0];
|
|
232
|
+
return row ? this.#historyRow(row[0], row[1], row[2], row[3], editor, context.principal) : null;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Copy a revision's content into a new revision. Status, publication time, slug, nesting,
|
|
237
|
+
* language, comment setting and terms stay as they are; values that no longer fit a changed
|
|
238
|
+
* field are left out.
|
|
239
|
+
*/
|
|
240
|
+
async restore(id: string, revision: number, context: OperationContext & { readonly expectedRevision: number }): Promise<RecordShape> {
|
|
241
|
+
const snapshot = await this.revision(id, revision, context);
|
|
242
|
+
if (!snapshot) throw new CmsError('CMS_NOT_FOUND', 'Revision not found.');
|
|
243
|
+
const patch: { [field: string]: unknown } = {};
|
|
244
|
+
for (const [name, declaration] of Object.entries(this.resource.fields)) {
|
|
245
|
+
if (KEPT_ON_RESTORE.has(name) || declaration.taxonomy || declaration.slugFrom) continue;
|
|
246
|
+
if (declaration.access?.write && !hasPermission(context.principal, declaration.access.write)) continue;
|
|
247
|
+
const value = snapshot.data[name];
|
|
248
|
+
if (value === undefined || validateValue(name, declaration, value) !== undefined) continue;
|
|
249
|
+
patch[name] = value;
|
|
250
|
+
}
|
|
251
|
+
return this.update(id, patch, context);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Whether the principal may update the record: its rule allows, or the record is in the rule's scope. */
|
|
255
|
+
/** The record as this principal may read it outside the site's gate: whole for those who may update it, else the reader's view (`lockedView`). */
|
|
256
|
+
readerView(record: RecordShape, principal: Principal): RecordShape {
|
|
257
|
+
return this.canUpdate(record, principal) ? record : lockedView(record, this.resource.fields);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
canUpdate(record: RecordShape, principal: Principal): boolean {
|
|
261
|
+
return this.#inScope(this.resource.access.update, record, principal);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Whether the principal may read this record: the read rule, evaluated on the record itself. */
|
|
265
|
+
canRead(record: RecordShape, principal: Principal): boolean {
|
|
266
|
+
return this.#inScope(this.resource.access.read, record, principal);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Co-owners (an entry's authors): a new record starts with its creator. Only people the update
|
|
271
|
+
* rule allows on every record (who edit others' entries) choose others; an empty list reads as
|
|
272
|
+
* the creator alone.
|
|
273
|
+
*/
|
|
274
|
+
#checkCoOwners(action: 'create' | 'update', draft: { [field: string]: unknown }, previous: RecordShape | null, principal: Principal, errors: { [field: string]: string }): void {
|
|
275
|
+
const co = this.resource.coOwners;
|
|
276
|
+
if (!co || principal.kind !== 'user' || errors[co]) return;
|
|
277
|
+
const given = draft[co] as readonly string[] | null | undefined;
|
|
278
|
+
if (action === 'create' && !given?.length) { draft[co] = [principal.id]; return; }
|
|
279
|
+
if (given === undefined || evaluateRule(this.resource.access.update, principal) === 'allow') return;
|
|
280
|
+
const fallback = previous ? (previous.owner ? [previous.owner] : []) : [principal.id];
|
|
281
|
+
const list = (value: unknown) => JSON.stringify(Array.isArray(value) && value.length ? value : fallback);
|
|
282
|
+
if (list(given) !== list(previous?.[co])) errors[co] = 'can be changed by people who edit others\' entries.';
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Whether the user owns the record: its creator, or one of its co-owners (an entry's authors). */
|
|
286
|
+
#owns(record: RecordShape, user: string): boolean {
|
|
287
|
+
if (record.owner === user) return true;
|
|
288
|
+
const co = this.resource.coOwners;
|
|
289
|
+
return co !== undefined && Array.isArray(record[co]) && (record[co] as unknown[]).includes(user);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
#inScope(rule: AccessRule, record: RecordShape, principal: Principal): boolean {
|
|
293
|
+
const scope = ruleScope(rule, principal);
|
|
294
|
+
if (scope === 'allow' || scope === 'deny') return scope === 'allow';
|
|
295
|
+
if (scope.owner && principal.kind === 'user' && this.#owns(record, principal.id)) return true;
|
|
296
|
+
return scope.where.some(rule => Object.entries(rule).every(([name, value]) => record[name] === value));
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* The records a record-link field leads to, level by level, in one request: RomeQL's
|
|
301
|
+
* record projections (`parent.*`, `parent.*.parent.*`, …) fetch each record's chain up to
|
|
302
|
+
* `depth` links deep. Each chain is nearest first and stops at the first link that is
|
|
303
|
+
* missing or that the principal may not read.
|
|
304
|
+
*/
|
|
305
|
+
async ancestors(ids: readonly string[], field: string, context: OperationContext, depth = 8): Promise<Map<string, RecordShape[]>> {
|
|
306
|
+
await this.#authorize('read', context.principal);
|
|
307
|
+
const declaration = this.resource.fields[field];
|
|
308
|
+
if (!declaration || declaration.kind !== 'reference' || !FIELD_NAME.test(field)) throw new CmsError('CMS_VALIDATION', `${field} is not a reference field.`);
|
|
309
|
+
const wanted = [...new Set(ids.filter(id => typeof id === 'string' && KEY.test(id)))].slice(0, 200);
|
|
310
|
+
const chains = new Map<string, RecordShape[]>();
|
|
311
|
+
if (!wanted.length) return chains;
|
|
312
|
+
const params: { [key: string]: Value } = {};
|
|
313
|
+
const list = wanted.map((id, index) => { params[`$k${index}`] = id; return `type::record('${this.resource.storage}', $k${index})`; }).join(', ');
|
|
314
|
+
const levels = Array.from({ length: Math.min(Math.max(depth, 1), 8) }, (_, index) => Array.from({ length: index + 1 }, () => `${field}.*`).join('.'));
|
|
315
|
+
const result = await this.#host.db.read([{
|
|
316
|
+
rql: `SELECT id, ${levels.map((path, index) => `${path} AS l${index}`).join(', ')} FROM ${this.resource.storage} WHERE id IN (${list}) LIMIT ${wanted.length}`, params,
|
|
317
|
+
}], this.#readOptions(context));
|
|
318
|
+
for (const row of result.results[0]!.rows) {
|
|
319
|
+
const chain: RecordShape[] = [];
|
|
320
|
+
for (let index = 1; index < row.length; index++) {
|
|
321
|
+
const document = row[index];
|
|
322
|
+
if (!document || typeof document !== 'object' || document instanceof RecordId || !(document as Document).id) break;
|
|
323
|
+
const record = this.#public(document as Document, context.principal);
|
|
324
|
+
if (!this.canRead(record, context.principal)) break;
|
|
325
|
+
chain.push(record);
|
|
326
|
+
}
|
|
327
|
+
chains.set(String((row[0] as RecordId).key), chain);
|
|
328
|
+
}
|
|
329
|
+
return chains;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
async create(input: { readonly [field: string]: unknown }, context: OperationContext & { readonly id?: string }): Promise<RecordShape> {
|
|
333
|
+
const access = await this.#authorize('create', context.principal);
|
|
334
|
+
// Only an owner rule lets a user create; a record condition cannot be checked before the record exists.
|
|
335
|
+
if (access !== 'allow' && !(access.owner && context.principal.kind === 'user')) {
|
|
336
|
+
throw new CmsError(context.principal.kind === 'user' ? 'CMS_FORBIDDEN' : 'CMS_UNAUTHENTICATED', `Not allowed to create ${this.resource.id}.`);
|
|
337
|
+
}
|
|
338
|
+
const key = context.id ?? uuidv7();
|
|
339
|
+
checkKey(key);
|
|
340
|
+
const draft = await this.#prepareDraft('create', null, input, null, context);
|
|
341
|
+
const now = this.#host.now();
|
|
342
|
+
const op = uuidv7();
|
|
343
|
+
const owner = this.resource.ownership && context.principal.kind === 'user' ? context.principal.id : null;
|
|
344
|
+
const record = this.#shape(key, 1, now, now, owner, draft);
|
|
345
|
+
const document: { [field: string]: Value } = { id: new RecordId(this.resource.storage, key), _rev: 1, _op: op, _createdAt: now, _updatedAt: now, _owner: owner };
|
|
346
|
+
for (const [name, value] of Object.entries(draft)) if (value !== undefined) document[name] = this.#store(name, this.resource.fields[name]!, value);
|
|
347
|
+
for (const [path, text] of this.#searchText(draft)) document[path] = text;
|
|
348
|
+
const statements: Statement[] = [{ rql: `INSERT INTO ${this.resource.storage} DOCUMENT $document`, params: { $document: document } }];
|
|
349
|
+
const guard = `EXISTS (SELECT 1 FROM ${this.resource.storage} WHERE id = type::record('${this.resource.storage}', $key) AND "_op" = $op)`;
|
|
350
|
+
statements.push(...this.#sideEffects(guard, op, key, 1, 'create', record, actor(context.principal), now));
|
|
351
|
+
await this.#write(statements, op, context, error => {
|
|
352
|
+
if (error.code === 'RDB_CONSTRAINT') throw new CmsError('CMS_CONFLICT', 'A record with the same unique value already exists.', { cause: error });
|
|
353
|
+
});
|
|
354
|
+
return this.#redact(record, context.principal);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Insert a record the host writes for itself, such as a form submission. The declared
|
|
359
|
+
* fields are checked, but no write hooks, revisions, audit rows or resource events run.
|
|
360
|
+
* `attach` adds statements to the batch; its guard holds once the record is written.
|
|
361
|
+
* The caller chooses the ID, the operation ID (the request ID) and the reconciler kind.
|
|
362
|
+
*/
|
|
363
|
+
async insert(input: { readonly [field: string]: unknown }, context: OperationContext & {
|
|
364
|
+
readonly id: string; readonly op: string; readonly owner: string | null; readonly kind: string;
|
|
365
|
+
readonly attach?: (guard: { readonly rql: string; readonly params: { readonly [key: string]: Value } }) => readonly Statement[];
|
|
366
|
+
}): Promise<RecordShape> {
|
|
367
|
+
const access = await this.#authorize('create', context.principal);
|
|
368
|
+
if (access !== 'allow') throw new CmsError(context.principal.kind === 'user' ? 'CMS_FORBIDDEN' : 'CMS_UNAUTHENTICATED', `Not allowed to create ${this.resource.id}.`);
|
|
369
|
+
checkKey(context.id);
|
|
370
|
+
const draft = this.#validate('create', input, null, context.principal);
|
|
371
|
+
const now = this.#host.now();
|
|
372
|
+
const owner = this.resource.ownership ? context.owner : null;
|
|
373
|
+
const record = this.#shape(context.id, 1, now, now, owner, draft);
|
|
374
|
+
const document: { [field: string]: Value } = { id: new RecordId(this.resource.storage, context.id), _rev: 1, _op: context.op, _createdAt: now, _updatedAt: now, _owner: owner };
|
|
375
|
+
for (const [name, value] of Object.entries(draft)) if (value !== undefined) document[name] = this.#store(name, this.resource.fields[name]!, value);
|
|
376
|
+
for (const [path, text] of this.#searchText(draft)) document[path] = text;
|
|
377
|
+
const guard = { rql: `EXISTS (SELECT 1 FROM ${this.resource.storage} WHERE id = type::record('${this.resource.storage}', $key) AND "_op" = $op)`, params: { $key: context.id, $op: context.op } };
|
|
378
|
+
const statements: Statement[] = [{ rql: `INSERT INTO ${this.resource.storage} DOCUMENT $document`, params: { $document: document } }, ...(context.attach?.(guard) ?? [])];
|
|
379
|
+
await this.#write(statements, context.op, context, error => {
|
|
380
|
+
if (error.code === 'RDB_CONSTRAINT') throw new CmsError('CMS_CONFLICT', 'A record with the same unique value already exists.', { cause: error });
|
|
381
|
+
}, 0, context.kind);
|
|
382
|
+
return record;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** Edit with an expected revision. A stale revision or lost access is a conflict, and nothing is written. */
|
|
386
|
+
async update(id: string, patch: { readonly [field: string]: unknown }, context: OperationContext & { readonly expectedRevision: number }): Promise<RecordShape> {
|
|
387
|
+
const access = await this.#authorize('update', context.principal);
|
|
388
|
+
checkKey(id);
|
|
389
|
+
if (!Number.isSafeInteger(context.expectedRevision) || context.expectedRevision < 1) throw new CmsError('CMS_VALIDATION', 'expectedRevision must be a positive integer.');
|
|
390
|
+
const previous = await this.#current(id, access, context);
|
|
391
|
+
if (!previous) throw new CmsError('CMS_NOT_FOUND', 'Record not found.');
|
|
392
|
+
if (previous.rev !== context.expectedRevision) throw new CmsError('CMS_CONFLICT', 'The record changed since it was read. Reload and try again.');
|
|
393
|
+
const draft = await this.#prepareDraft('update', id, patch, previous, context);
|
|
394
|
+
const changed = Object.keys(draft).filter(name => draft[name] !== undefined);
|
|
395
|
+
const now = this.#host.now();
|
|
396
|
+
const op = uuidv7();
|
|
397
|
+
const revision = previous.rev + 1;
|
|
398
|
+
const record = this.#shape(id, revision, previous.createdAt, now, previous.owner, { ...this.#fieldsOf(previous), ...draft });
|
|
399
|
+
const params: { [key: string]: Value } = { $key: id, $expected: context.expectedRevision, $op: op, $now: now };
|
|
400
|
+
const assignments = changed.map((name, index) => {
|
|
401
|
+
params[`$f${index}`] = this.#store(name, this.resource.fields[name]!, draft[name]);
|
|
402
|
+
return `${quote(name)} = $f${index}`;
|
|
403
|
+
});
|
|
404
|
+
for (const [index, [path, text]] of this.#searchText(draft).entries()) {
|
|
405
|
+
params[`$t${index}`] = text;
|
|
406
|
+
assignments.push(`${quote(path)} = $t${index}`);
|
|
407
|
+
}
|
|
408
|
+
const condition = this.#conditions(access, context.principal, [`id = type::record('${this.resource.storage}', $key)`, '"_rev" = $expected'], params);
|
|
409
|
+
const statements: Statement[] = [bound(
|
|
410
|
+
`UPDATE ${this.resource.storage} SET ${[...assignments, '"_rev" = "_rev" + 1', '"_op" = $op', '"_updatedAt" = $now'].join(', ')} WHERE ${condition.rql}`,
|
|
411
|
+
condition.params,
|
|
412
|
+
)];
|
|
413
|
+
const guard = `EXISTS (SELECT 1 FROM ${this.resource.storage} WHERE id = type::record('${this.resource.storage}', $key) AND "_op" = $op)`;
|
|
414
|
+
const shared = await this.#sharedStatement(id, previous, draft, guard, { $key: id, $op: op, $now: now }, context);
|
|
415
|
+
if (shared) {
|
|
416
|
+
statements.push(shared);
|
|
417
|
+
// The other translations' own rows follow from the outbox, queued only when this commits.
|
|
418
|
+
const event: SharedFieldsEvent = { eventId: `shared:${op}`, topic: 'resource.shared', at: now, resource: this.resource.id, id, group: translationGroupOf(previous), op, actor: actor(context.principal) };
|
|
419
|
+
statements.push(bound(
|
|
420
|
+
`INSERT INTO cms_outbox (id, topic, payload, created_at, available_at, attempts, lease_until) SELECT $sharedId, $sharedTopic, $sharedPayload, $now, $now, 0, 0 WHERE ${guard}`,
|
|
421
|
+
{ $key: id, $op: op, $now: now, $sharedId: event.eventId, $sharedTopic: event.topic, $sharedPayload: JSON.stringify(event) },
|
|
422
|
+
));
|
|
423
|
+
}
|
|
424
|
+
statements.push(...this.#sideEffects(guard, op, id, revision, 'update', record, actor(context.principal), now, {}, previous));
|
|
425
|
+
// A published entry whose URL changes keeps answering at the old one. The audit row,
|
|
426
|
+
// written only when the change commits, guards these relational statements.
|
|
427
|
+
statements.push(...await this.#host.redirectStatements(this.resource, previous, record, { rql: 'EXISTS (SELECT 1 FROM cms_audit WHERE id = $rOp)', params: { $rOp: op } }, principalId(context.principal)));
|
|
428
|
+
const result = await this.#write(statements, op, context);
|
|
429
|
+
if (result.affected !== 1) throw new CmsError('CMS_CONFLICT', 'The record changed since it was read. Reload and try again.');
|
|
430
|
+
return this.#redact(record, context.principal);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Fields that are the same in every language (`translatable: false`) and changed: one
|
|
435
|
+
* statement gives them to every other translation of the entry, once the entry's own update
|
|
436
|
+
* committed, with each translation's revision moved on (so an editor holding an older one
|
|
437
|
+
* reloads) and the entry's operation ID. The principal must be able to update every
|
|
438
|
+
* translation. The translations' revision, audit, search and outbox rows follow from an outbox
|
|
439
|
+
* job (`sharedSideEffects`), so a site with many languages still fits one request.
|
|
440
|
+
*/
|
|
441
|
+
async #sharedStatement(id: string, previous: RecordShape, draft: Draft, guard: string, params: { [key: string]: Value }, context: OperationContext): Promise<Statement | null> {
|
|
442
|
+
if (!this.resource.fields.translationGroup) return null;
|
|
443
|
+
const changed = Object.entries(this.resource.fields).filter(([name, declaration]) => declaration.translatable === false && draft[name] !== undefined
|
|
444
|
+
&& JSON.stringify(draft[name] ?? null) !== JSON.stringify(previous[name] ?? null)).map(([name]) => name);
|
|
445
|
+
if (!changed.length) return null;
|
|
446
|
+
const group = translationGroupOf(previous);
|
|
447
|
+
const members = await this.#host.db.read([{
|
|
448
|
+
rql: `SELECT record::id(id) FROM ${this.resource.storage} WHERE ${this.#membersOf()} ORDER BY record::id(id) LIMIT ${SHARED_MEMBERS + 1}`,
|
|
449
|
+
params: { $group: group, $key: id },
|
|
450
|
+
}], this.#readOptions(context));
|
|
451
|
+
const others = members.results[0]!.rows.map(row => row[0] as string);
|
|
452
|
+
if (!others.length) return null;
|
|
453
|
+
// The check, the update and its side effects all cover the same members: every one of them.
|
|
454
|
+
if (others.length > SHARED_MEMBERS) throw new CmsError('CMS_LIMIT', `An entry with more than ${SHARED_MEMBERS} translations cannot change a field that is the same in every language.`);
|
|
455
|
+
if ((await this.updatable(others, context)).size < others.length) {
|
|
456
|
+
const labels = changed.map(name => this.resource.fields[name]!.label ?? name).join(', ');
|
|
457
|
+
throw new CmsError('CMS_FORBIDDEN', `${labels} is the same in every language, and you cannot edit every translation.`, { fields: Object.fromEntries(changed.map(name => [name, 'is the same in every language.'])) });
|
|
458
|
+
}
|
|
459
|
+
const shared: Draft = Object.fromEntries(changed.map(name => [name, draft[name]]));
|
|
460
|
+
const values: { [key: string]: Value } = { ...params, $group: group };
|
|
461
|
+
const assignments = changed.map((name, index) => {
|
|
462
|
+
values[`$s${index}`] = this.#store(name, this.resource.fields[name]!, draft[name]);
|
|
463
|
+
return `${quote(name)} = $s${index}`;
|
|
464
|
+
});
|
|
465
|
+
for (const [index, [path, text]] of this.#searchText(shared).entries()) {
|
|
466
|
+
values[`$st${index}`] = text;
|
|
467
|
+
assignments.push(`${quote(path)} = $st${index}`);
|
|
468
|
+
}
|
|
469
|
+
// Only the members checked above: a translation started since then keeps the value it copied.
|
|
470
|
+
const checked = others.map((other, index) => { values[`$m${index}`] = other; return `type::record('${this.resource.storage}', $m${index})`; }).join(', ');
|
|
471
|
+
return {
|
|
472
|
+
rql: `UPDATE ${this.resource.storage} SET ${[...assignments, '"_rev" = "_rev" + 1', '"_op" = $op', '"_updatedAt" = $now'].join(', ')} WHERE id IN (${checked}) AND ${this.#membersOf()} AND ${guard}`,
|
|
473
|
+
params: values,
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/** The entry's other translations, by `$group` and the entry's own `$key`. */
|
|
478
|
+
#membersOf(): string {
|
|
479
|
+
return `("translationGroup" = $group OR id = type::record('${this.resource.storage}', $group)) AND record::id(id) != $key`;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* The revision, audit, search and outbox rows of the translations a shared-field update
|
|
484
|
+
* changed (the `resource.shared` outbox job). Each translation still holding that update is
|
|
485
|
+
* read on its own, so a read stays inside RomeDB's result budget, and its rows are written
|
|
486
|
+
* under an operation ID derived from the update's, guarded on the translation still holding
|
|
487
|
+
* the update (its `_op` and revision): a translation saved again since wrote its own rows,
|
|
488
|
+
* and rows a retry finds written are skipped. Writes are batched to fit a request; a failure
|
|
489
|
+
* throws, and the outbox retries.
|
|
490
|
+
*/
|
|
491
|
+
async sharedSideEffects(event: SharedFieldsEvent, options: { signal?: AbortSignal } = {}): Promise<void> {
|
|
492
|
+
const call = { ...(options.signal ? { signal: options.signal } : {}), workLimits: this.#host.readLimits };
|
|
493
|
+
const listed = await this.#host.db.read([{
|
|
494
|
+
rql: `SELECT record::id(id) FROM ${this.resource.storage} WHERE ${this.#membersOf()} AND "_op" = $op LIMIT ${SHARED_MEMBERS}`,
|
|
495
|
+
params: { $group: event.group, $key: event.id, $op: event.op },
|
|
496
|
+
}], call);
|
|
497
|
+
const ids = listed.results[0]!.rows.map(row => row[0] as string);
|
|
498
|
+
if (!ids.length) return;
|
|
499
|
+
const ops = new Map(await Promise.all(ids.map(async id => [id, await sharedOp(event.op, id)] as const)));
|
|
500
|
+
const params: { [key: string]: Value } = {};
|
|
501
|
+
const list = ids.map((id, index) => { params[`$a${index}`] = ops.get(id)!; return `$a${index}`; }).join(', ');
|
|
502
|
+
const written = await this.#host.db.read([{ rql: `SELECT id FROM cms_audit WHERE id IN (${list})`, params }], call);
|
|
503
|
+
const done = new Set(written.results[0]!.rows.map(row => row[0] as string));
|
|
504
|
+
const limit = await this.#host.db.maxRequestBytes() - REQUEST_MARGIN;
|
|
505
|
+
const guard = `EXISTS (SELECT 1 FROM ${this.resource.storage} WHERE id = type::record('${this.resource.storage}', $key) AND "_op" = $sharedOp AND "_rev" = $sharedRev)`;
|
|
506
|
+
let batch: Statement[] = [];
|
|
507
|
+
let bytes = 0;
|
|
508
|
+
const flush = async () => {
|
|
509
|
+
if (!batch.length) return;
|
|
510
|
+
await this.#host.db.write(batch, { kind: 'cms.resource.shared', ...(options.signal ? { signal: options.signal } : {}), workLimits: this.#host.writeLimits });
|
|
511
|
+
batch = []; bytes = 0;
|
|
512
|
+
this.#host.outboxWritten();
|
|
513
|
+
};
|
|
514
|
+
for (const id of ids) {
|
|
515
|
+
const op = ops.get(id)!;
|
|
516
|
+
if (done.has(op)) continue;
|
|
517
|
+
const row = await this.#host.db.read([{
|
|
518
|
+
rql: `SELECT * FROM ${this.resource.storage} WHERE id = type::record('${this.resource.storage}', $key) AND "_op" = $op`,
|
|
519
|
+
params: { $key: id, $op: event.op },
|
|
520
|
+
}], call);
|
|
521
|
+
const document = row.results[0]!.rows[0]?.[0] as Document | undefined;
|
|
522
|
+
if (!document) continue;
|
|
523
|
+
const member = this.#shapeOf(document);
|
|
524
|
+
const group = this.#sideEffects(guard, op, member.id, member.rev, 'update', member, event.actor, event.at, { $sharedOp: event.op, $sharedRev: member.rev }, member);
|
|
525
|
+
const size = statementBytes(group);
|
|
526
|
+
if (batch.length && (batch.length + group.length > MAX_STATEMENTS || bytes + size > limit)) await flush();
|
|
527
|
+
batch.push(...group); bytes += size;
|
|
528
|
+
}
|
|
529
|
+
await flush();
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/** The IDs among these the principal may update. */
|
|
533
|
+
async updatable(ids: readonly string[], context: OperationContext): Promise<Set<string>> {
|
|
534
|
+
let access: Access;
|
|
535
|
+
try { access = await this.#authorize('update', context.principal); } catch (error) { if (error instanceof CmsError) return new Set(); throw error; }
|
|
536
|
+
const wanted = [...new Set(ids.filter(id => typeof id === 'string' && KEY.test(id)))].slice(0, 200);
|
|
537
|
+
if (!wanted.length) return new Set();
|
|
538
|
+
const params: { [key: string]: Value } = {};
|
|
539
|
+
const list = wanted.map((key, index) => { params[`$k${index}`] = key; return `type::record('${this.resource.storage}', $k${index})`; }).join(', ');
|
|
540
|
+
const { rql, params: bound } = this.#conditions(access, context.principal, [`id IN (${list})`], params);
|
|
541
|
+
const result = await this.#host.db.read([{ rql: `SELECT record::id(id) FROM ${this.resource.storage} WHERE ${rql} LIMIT ${wanted.length}`, params: bound }], this.#readOptions(context));
|
|
542
|
+
return new Set(result.results[0]!.rows.map(row => row[0] as string));
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
async delete(id: string, context: OperationContext & { readonly expectedRevision: number }): Promise<void> {
|
|
546
|
+
const access = await this.#authorize('delete', context.principal);
|
|
547
|
+
checkKey(id);
|
|
548
|
+
if (!Number.isSafeInteger(context.expectedRevision) || context.expectedRevision < 1) throw new CmsError('CMS_VALIDATION', 'expectedRevision must be a positive integer.');
|
|
549
|
+
const now = this.#host.now();
|
|
550
|
+
const op = uuidv7();
|
|
551
|
+
const condition = this.#conditions(access, context.principal, [`id = type::record('${this.resource.storage}', $key)`, '"_rev" = $expected'], { $key: id, $expected: context.expectedRevision });
|
|
552
|
+
// Guards run before the delete, against the same snapshot.
|
|
553
|
+
const guard = `EXISTS (SELECT 1 FROM ${this.resource.storage} WHERE ${condition.rql})`;
|
|
554
|
+
const previous = this.resource.fields.status ? await this.#current(id, access, context) : null;
|
|
555
|
+
const statements = this.#sideEffects(guard, op, id, context.expectedRevision, 'delete', null, actor(context.principal), now, condition.params, previous);
|
|
556
|
+
statements.push(bound(`DELETE FROM ${this.resource.storage} WHERE ${condition.rql}`, condition.params));
|
|
557
|
+
const deleted = await this.#write(statements, op, context, undefined, statements.length - 1);
|
|
558
|
+
if (deleted.affected !== 1) throw new CmsError('CMS_CONFLICT', 'The record changed or was deleted since it was read.');
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
async #authorize(action: ResourceAction, principal: Principal): Promise<Access> {
|
|
562
|
+
await this.#host.assertActive(this.resource, { fresh: action !== 'read' });
|
|
563
|
+
const outcome = ruleScope(this.resource.access[action], principal);
|
|
564
|
+
if (outcome === 'deny') throw new CmsError(principal.kind === 'anonymous' ? 'CMS_UNAUTHENTICATED' : 'CMS_FORBIDDEN', `Not allowed to ${action} ${this.resource.id}.`);
|
|
565
|
+
return outcome;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** Join conditions with the access scope: the principal's own records or those matching a rule's fields. */
|
|
569
|
+
/** One record by key, as a RomeQL record source (`FROM type::record(...)`: an ID lookup), under the principal's read conditions. */
|
|
570
|
+
#one(id: string, access: Access, principal: Principal): Statement {
|
|
571
|
+
const { rql, params } = this.#conditions(access, principal, [], { $key: id });
|
|
572
|
+
return { rql: `SELECT * FROM type::record('${this.resource.storage}', $key)${rql ? ` WHERE ${rql}` : ''} LIMIT 1`, params };
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
#conditions(access: Access, principal: Principal, conditions: string[], params: { [key: string]: Value }, prefix = ''): { rql: string; params: { [key: string]: Value } } {
|
|
576
|
+
if (access !== 'allow') {
|
|
577
|
+
const scope: string[] = [];
|
|
578
|
+
params = { ...params };
|
|
579
|
+
if (access.owner && principal.kind === 'user') {
|
|
580
|
+
const co = this.resource.coOwners;
|
|
581
|
+
scope.push(co ? `(${prefix}"_owner" = $owner OR array::contains(${prefix}${quote(co)}, $owner))` : `${prefix}"_owner" = $owner`);
|
|
582
|
+
params.$owner = principalId(principal);
|
|
583
|
+
}
|
|
584
|
+
access.where.forEach((rule, ruleIndex) => {
|
|
585
|
+
const parts = Object.entries(rule).map(([name, value], index) => {
|
|
586
|
+
params[`$a${ruleIndex}_${index}`] = value;
|
|
587
|
+
return `${prefix}${quote(name)} = $a${ruleIndex}_${index}`;
|
|
588
|
+
});
|
|
589
|
+
scope.push(parts.length > 1 ? `(${parts.join(' AND ')})` : parts[0]!);
|
|
590
|
+
});
|
|
591
|
+
conditions = [...conditions, scope.length ? scope.join(' OR ') : '1 = 0'];
|
|
592
|
+
}
|
|
593
|
+
return { rql: conditions.map(condition => conditions.length > 1 ? `(${condition})` : condition).join(' AND '), params };
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** RomeQL conditions for a filter. Parameters are added to `params`. */
|
|
597
|
+
#filters(filter: ListFilter, principal: Principal, params: { [key: string]: Value }, prefix = ''): string[] {
|
|
598
|
+
const conditions: string[] = [];
|
|
599
|
+
let index = Object.keys(params).filter(name => name.startsWith('$w')).length;
|
|
600
|
+
const parameter = (value: Value) => { const name = `$w${index++}`; params[name] = value; return name; };
|
|
601
|
+
for (const [given, condition] of Object.entries(filter.where ?? {})) {
|
|
602
|
+
// A row field, as `specs.name`, filters through the array index on its path into the rows.
|
|
603
|
+
if (given.includes('.')) {
|
|
604
|
+
const path = given.split('.');
|
|
605
|
+
const row = indexedRowField(this.resource.fields, path);
|
|
606
|
+
if (!row || !this.#canRead(path[0]!, principal)) throw new CmsError('CMS_VALIDATION', `Cannot filter on ${given}.`);
|
|
607
|
+
const values = condition !== null && typeof condition === 'object' && 'contains' in condition ? [condition.contains]
|
|
608
|
+
: condition !== null && typeof condition === 'object' && 'containsAny' in condition ? [...condition.containsAny] : undefined;
|
|
609
|
+
if (!values || !values.length || values.length > 50) throw new CmsError('CMS_VALIDATION', `Filter ${given} with contains or containsAny (1-50 values).`);
|
|
610
|
+
const column = prefix + rowIndexPath(path).split('.').map(part => part === '*' ? part : quote(part)).join('.');
|
|
611
|
+
conditions.push(values.map(value => {
|
|
612
|
+
const error = validateValue(given, row, value);
|
|
613
|
+
if (error) throw new CmsError('CMS_VALIDATION', `Filter ${given} ${error}`, { fields: { [given]: error } });
|
|
614
|
+
return `array::contains(${column}, ${parameter(storedJson(value))})`;
|
|
615
|
+
}).join(' OR '));
|
|
616
|
+
continue;
|
|
617
|
+
}
|
|
618
|
+
const name = given;
|
|
619
|
+
const declaration = this.resource.fields[name];
|
|
620
|
+
if (!declaration || !this.#canRead(name, principal)) throw new CmsError('CMS_VALIDATION', `Cannot filter on ${given}.`);
|
|
621
|
+
const column = `${prefix}${quote(name)}`;
|
|
622
|
+
const check = (value: unknown, kind: FieldDeclaration = declaration) => {
|
|
623
|
+
const error = validateValue(name, kind, value);
|
|
624
|
+
if (error) throw new CmsError('CMS_VALIDATION', `Filter ${name} ${error}`, { fields: { [name]: error } });
|
|
625
|
+
};
|
|
626
|
+
if (declaration.multiple) {
|
|
627
|
+
const values = condition !== null && typeof condition === 'object' && 'contains' in condition ? [condition.contains]
|
|
628
|
+
: condition !== null && typeof condition === 'object' && 'containsAny' in condition ? [...condition.containsAny] : undefined;
|
|
629
|
+
if (!values || !values.length || values.length > 50 || !declaration.index) throw new CmsError('CMS_VALIDATION', `Filter ${name} with contains or containsAny (1-50 values) on an indexed multiple field.`);
|
|
630
|
+
const item: FieldDeclaration = { ...declaration, multiple: false, required: false, nullable: false };
|
|
631
|
+
conditions.push(values.map(value => {
|
|
632
|
+
check(value, item);
|
|
633
|
+
return `array::contains(${column}, ${parameter(this.#store(name, item, value))})`;
|
|
634
|
+
}).join(' OR '));
|
|
635
|
+
continue;
|
|
636
|
+
}
|
|
637
|
+
if (!SCALAR.has(declaration.kind)) throw new CmsError('CMS_VALIDATION', `Cannot filter on ${name}.`);
|
|
638
|
+
if (condition === null) { conditions.push(`${column} IS NULL`); continue; }
|
|
639
|
+
if (typeof condition !== 'object') {
|
|
640
|
+
check(condition);
|
|
641
|
+
conditions.push(`${column} = ${parameter(this.#store(name, declaration, condition))}`);
|
|
642
|
+
continue;
|
|
643
|
+
}
|
|
644
|
+
if ('ne' in condition) {
|
|
645
|
+
if (condition.ne === null) { conditions.push(`${column} IS NOT NULL`); continue; }
|
|
646
|
+
check(condition.ne);
|
|
647
|
+
conditions.push(`(${column} IS NULL OR ${column} != ${parameter(this.#store(name, declaration, condition.ne))})`);
|
|
648
|
+
} else if ('in' in condition) {
|
|
649
|
+
if (!Array.isArray(condition.in) || !condition.in.length || condition.in.length > 100) throw new CmsError('CMS_VALIDATION', `Filter ${name} with 1-100 values.`);
|
|
650
|
+
const values = condition.in.filter(value => value !== null);
|
|
651
|
+
const listed = values.length ? `${column} IN (${values.map(value => { check(value); return parameter(this.#store(name, declaration, value)); }).join(', ')})` : '';
|
|
652
|
+
const unset = values.length < condition.in.length ? `${column} IS NULL` : '';
|
|
653
|
+
conditions.push(listed && unset ? `(${unset} OR ${listed})` : listed || unset);
|
|
654
|
+
} else {
|
|
655
|
+
const bounds = Object.entries(condition) as [string, unknown][];
|
|
656
|
+
if (!RANGED.has(declaration.kind) || !bounds.length || bounds.some(([operator]) => !['gt', 'gte', 'lt', 'lte'].includes(operator))) throw new CmsError('CMS_VALIDATION', `Cannot filter ${name} that way.`);
|
|
657
|
+
for (const [operator, value] of bounds) {
|
|
658
|
+
check(value);
|
|
659
|
+
conditions.push(`${column} ${{ gt: '>', gte: '>=', lt: '<', lte: '<=' }[operator]} ${parameter(this.#store(name, declaration, value))}`);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
if (filter.owner !== undefined) {
|
|
664
|
+
if (!this.resource.ownership || typeof filter.owner !== 'string' || !KEY.test(filter.owner)) throw new CmsError('CMS_VALIDATION', 'Cannot filter on the owner.');
|
|
665
|
+
// An entry's authors own it too, so an author's archive lists what they co-wrote.
|
|
666
|
+
const owner = parameter(filter.owner);
|
|
667
|
+
const co = this.resource.coOwners;
|
|
668
|
+
conditions.push(co ? `(${prefix}"_owner" = ${owner} OR array::contains(${prefix}${quote(co)}, ${owner}))` : `${prefix}"_owner" = ${owner}`);
|
|
669
|
+
}
|
|
670
|
+
return conditions;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
#order(order: ListOptions['order']): string {
|
|
674
|
+
if (!order) return '"_updatedAt" DESC, record::id(id) DESC';
|
|
675
|
+
const direction = order.direction === 'asc' ? 'ASC' : order.direction === undefined || order.direction === 'desc' ? 'DESC' : undefined;
|
|
676
|
+
const system = order.field === 'createdAt' ? '"_createdAt"' : order.field === 'updatedAt' ? '"_updatedAt"' : undefined;
|
|
677
|
+
const declared = this.resource.fields[order.field];
|
|
678
|
+
if (!direction || (!system && (!declared || !ORDERED.has(declared.kind)))) throw new CmsError('CMS_VALIDATION', `Cannot sort by ${order.field}.`);
|
|
679
|
+
return `${system ?? quote(order.field)} ${direction}, record::id(id) ${direction}`;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
async #current(id: string, access: Access, context: OperationContext): Promise<RecordShape | null> {
|
|
683
|
+
const result = await this.#host.db.read([this.#one(id, access, context.principal)], this.#readOptions(context));
|
|
684
|
+
const document = result.results[0]!.rows[0]?.[0] as Document | undefined;
|
|
685
|
+
return document ? this.#shapeOf(document) : null;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
async #prepareDraft(action: 'create' | 'update', id: string | null, input: { readonly [field: string]: unknown }, previous: RecordShape | null, context: OperationContext): Promise<Draft> {
|
|
689
|
+
const draft = this.#validate(action, input, previous, context.principal);
|
|
690
|
+
let filtered: Draft;
|
|
691
|
+
try {
|
|
692
|
+
filtered = await this.#host.hooks.applyFilters(beforeWrite, draft, { resource: this.resource.id, action, id, previous, actor: actor(context.principal) }, context.signal ? { signal: context.signal } : {});
|
|
693
|
+
} catch (error) {
|
|
694
|
+
const cause = (error as { cause?: unknown }).cause;
|
|
695
|
+
// A filter's own field errors (a CmsError it threw) stay with the fields they name.
|
|
696
|
+
const fields = isCmsError(cause) ? cause.fields : undefined;
|
|
697
|
+
throw new CmsError('CMS_VALIDATION', cause instanceof Error ? cause.message : 'A plugin rejected the change.', { cause: error, ...(fields ? { fields } : {}) });
|
|
698
|
+
}
|
|
699
|
+
// Filters can change values; validate the result again.
|
|
700
|
+
const final = filtered === draft ? draft : this.#validate(action, filtered, previous, context.principal);
|
|
701
|
+
this.#checkGroup(final, previous, context);
|
|
702
|
+
await this.#checkReferences(final, id);
|
|
703
|
+
await this.#checkTemplate(final, previous);
|
|
704
|
+
await this.#checkNotes(final, previous);
|
|
705
|
+
return this.#uniqueSlugs(await this.#withLocale(action, final), id, previous, context);
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* Joining a translation group goes through `translateEntry` alone: a save may keep the
|
|
710
|
+
* entry's group or leave it (null), never name another one, which would make the entry a
|
|
711
|
+
* translation of somebody else's.
|
|
712
|
+
*/
|
|
713
|
+
#checkGroup(draft: Draft, previous: RecordShape | null, context: OperationContext): void {
|
|
714
|
+
const group = draft.translationGroup;
|
|
715
|
+
if (group === undefined || group === null) return;
|
|
716
|
+
const current = previous && typeof previous.translationGroup === 'string' ? previous.translationGroup : null;
|
|
717
|
+
if (group === current) return;
|
|
718
|
+
if ((context as { readonly [JOIN_GROUP]?: string })[JOIN_GROUP] === group) return;
|
|
719
|
+
throw new CmsError('CMS_VALIDATION', 'Start a translation from the entry it translates.', { fields: { translationGroup: 'is set when a translation starts.' } });
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** A new content entry belongs to a language: the site's default unless it names one. */
|
|
723
|
+
async #withLocale(action: 'create' | 'update', draft: Draft): Promise<Draft> {
|
|
724
|
+
if (action !== 'create' || !this.resource.id.startsWith('cms/') || !this.resource.fields.locale || !this.resource.fields.translationGroup || typeof draft.locale === 'string') return draft;
|
|
725
|
+
return Object.freeze({ ...draft, locale: (await this.#host.languages()).default });
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/** Terms, media and parent records named by the draft must exist; a record cannot be its own ancestor. */
|
|
729
|
+
async #checkReferences(draft: Draft, id: string | null): Promise<void> {
|
|
730
|
+
for (const [name, value] of Object.entries(draft)) {
|
|
731
|
+
const declaration = this.resource.fields[name]!;
|
|
732
|
+
if (value === null || value === undefined) continue;
|
|
733
|
+
if (declaration.taxonomy) await this.#host.taxonomies.assertTerms(declaration.taxonomy, value as string[], name);
|
|
734
|
+
const files = declaration.media ? (Array.isArray(value) ? value as string[] : [value as string])
|
|
735
|
+
: declaration.kind === 'blocks' ? blockMedia(value as Block[], this.#host.blockTypes)
|
|
736
|
+
: declaration.kind === 'richtext' ? [...richTextMedia(value as RichTextDoc), ...blockMedia(richTextBlocks(value as RichTextDoc), this.#host.blockTypes)]
|
|
737
|
+
: declaration.fields ? groupMedia(declaration, value as { [key: string]: unknown }) : [];
|
|
738
|
+
if (files.length) {
|
|
739
|
+
const unique = [...new Set(files)];
|
|
740
|
+
if (unique.length > 100) throw new CmsError('CMS_VALIDATION', `${declaration.label ?? name} names too many files.`, { fields: { [name]: 'names too many files.' } });
|
|
741
|
+
const list = unique.map((_, index) => `$m${index}`).join(', ');
|
|
742
|
+
const found = await this.#host.db.read([{ rql: `SELECT count(*) FROM cms_files WHERE status = 'ready' AND ${LIBRARY_KEYS} AND id IN (${list})`, params: Object.fromEntries(unique.map((file, index) => [`$m${index}`, file])) }]);
|
|
743
|
+
if (Number(found.results[0]!.rows[0]![0] as bigint) !== unique.length) throw new CmsError('CMS_VALIDATION', `${declaration.label ?? name} names a missing file.`, { fields: { [name]: 'names a missing file.' } });
|
|
744
|
+
}
|
|
745
|
+
if (declaration.kind === 'reference' && declaration.target === this.resource.id) {
|
|
746
|
+
// Walk up from the new parent; reaching this record would make a cycle.
|
|
747
|
+
let current: string | null = value as string;
|
|
748
|
+
for (let depth = 0; current; depth++) {
|
|
749
|
+
if (current === id) throw new CmsError('CMS_VALIDATION', `${declaration.label ?? name} cannot be this record or one below it.`, { fields: { [name]: 'would make a cycle.' } });
|
|
750
|
+
if (depth >= 32) throw new CmsError('CMS_LIMIT', 'Records nest at most 32 levels deep.');
|
|
751
|
+
const row: Value | undefined = (await this.#host.db.read([{ rql: `SELECT ${quote(name)} FROM type::record('${this.resource.storage}', $key)`, params: { $key: current } }])).results[0]!.rows[0]?.[0];
|
|
752
|
+
if (row === undefined) throw new CmsError('CMS_VALIDATION', `${declaration.label ?? name} names a missing record.`, { fields: { [name]: 'names a missing record.' } });
|
|
753
|
+
current = row instanceof RecordId ? String(row.key) : null;
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* With "Open notes hold publishing" on (Settings → Writing), an entry that is not live yet is
|
|
761
|
+
* not published or scheduled while it has open notes, whoever writes it: the editor, the API,
|
|
762
|
+
* a plugin or an automation. An entry already live keeps being updated, and a scheduled one
|
|
763
|
+
* is published when due.
|
|
764
|
+
*/
|
|
765
|
+
async #checkNotes(draft: Draft, previous: RecordShape | null): Promise<void> {
|
|
766
|
+
const status = draft.status;
|
|
767
|
+
if (this.resource.owner !== 'cms' || !previous || (status !== 'published' && status !== 'scheduled')) return;
|
|
768
|
+
if (previous.status === 'published' || previous.status === 'scheduled') return;
|
|
769
|
+
if (!(await this.#host.settings.get('writing.requireResolvedNotes'))) return;
|
|
770
|
+
const open = (await this.#host.notes.counts(this.resource.id, [previous.id])).get(previous.id) ?? 0;
|
|
771
|
+
if (open) throw new CmsError('CMS_VALIDATION', open === 1 ? 'Resolve the open note before publishing.' : `Resolve the ${open} open notes before publishing.`, { fields: { status: 'Open notes hold publishing.' } });
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/**
|
|
775
|
+
* An entry's chosen template must be one of the active theme's when it changes. A value
|
|
776
|
+
* the theme no longer has, as after a theme switch, stays: the site falls back silently.
|
|
777
|
+
*/
|
|
778
|
+
async #checkTemplate(draft: Draft, previous: RecordShape | null): Promise<void> {
|
|
779
|
+
const value = draft.template;
|
|
780
|
+
if (this.resource.owner !== 'cms' || !this.resource.fields.template || typeof value !== 'string' || !value || value === previous?.template) return;
|
|
781
|
+
if (!(await this.#host.entryTemplates()).includes(value)) {
|
|
782
|
+
throw new CmsError('CMS_VALIDATION', `${value} is not a template of the active theme.`, { fields: { template: 'is not a template of the active theme.' } });
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/**
|
|
787
|
+
* Unique slug fields get the first free `-2`, `-3`, … suffix, so a duplicate title does not fail the write.
|
|
788
|
+
* A slug unique by other fields (its language) is free when those differ; changing them checks the slug again.
|
|
789
|
+
*/
|
|
790
|
+
async #uniqueSlugs(draft: Draft, id: string | null, previous: RecordShape | null, context: OperationContext): Promise<Draft> {
|
|
791
|
+
let adjusted: { [field: string]: unknown } | undefined;
|
|
792
|
+
for (const [name, declaration] of Object.entries(this.resource.fields)) {
|
|
793
|
+
const scope = declaration.uniqueBy ?? [];
|
|
794
|
+
const value = draft[name] ?? (scope.some(other => draft[other] !== undefined) ? previous?.[name] : undefined);
|
|
795
|
+
if (!declaration.slugFrom || !declaration.unique || typeof value !== 'string' || !value) continue;
|
|
796
|
+
const params: { [key: string]: Value } = { $slug: value, $prefix: `${value}-%`, ...(id ? { $key: id } : {}) };
|
|
797
|
+
const within = scope.map((other, index) => {
|
|
798
|
+
const current = draft[other] !== undefined ? draft[other] : previous?.[other];
|
|
799
|
+
if (current === null || current === undefined) return ` AND ${quote(other)} IS NULL`;
|
|
800
|
+
params[`$u${index}`] = current as Value;
|
|
801
|
+
return ` AND ${quote(other)} = $u${index}`;
|
|
802
|
+
}).join('');
|
|
803
|
+
const result = await this.#host.db.read([{
|
|
804
|
+
rql: `SELECT ${quote(name)} FROM ${this.resource.storage} WHERE (${quote(name)} = $slug OR ${quote(name)} LIKE $prefix)${within}${id ? ' AND record::id(id) != $key' : ''} LIMIT 1000`, params,
|
|
805
|
+
}], this.#readOptions(context));
|
|
806
|
+
const taken = new Set(result.results[0]!.rows.map(row => row[0] as string));
|
|
807
|
+
// Entries at the site root share one namespace, per language, with routes and other root collections.
|
|
808
|
+
const locale = draft.locale !== undefined ? draft.locale : previous?.locale;
|
|
809
|
+
for (const slug of await this.#host.rootSlugConflicts(this.resource.id, value, typeof locale === 'string' ? locale : null)) taken.add(slug);
|
|
810
|
+
if (!taken.has(value)) continue;
|
|
811
|
+
let suffix = 2;
|
|
812
|
+
while (taken.has(`${value}-${suffix}`)) suffix++;
|
|
813
|
+
const max = declaration.max ?? 200;
|
|
814
|
+
const base = value.length + String(suffix).length + 1 > max ? value.slice(0, max - String(suffix).length - 1).replace(/-+$/, '') : value;
|
|
815
|
+
adjusted = { ...(adjusted ?? draft), [name]: `${base}-${suffix}` };
|
|
816
|
+
}
|
|
817
|
+
return adjusted ? Object.freeze(adjusted) : draft;
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
#validate(action: 'create' | 'update', input: { readonly [field: string]: unknown }, previous: RecordShape | null, principal: Principal): Draft {
|
|
821
|
+
if (input === null || typeof input !== 'object' || Array.isArray(input)) throw new CmsError('CMS_VALIDATION', 'Record input must be an object.');
|
|
822
|
+
const errors: { [field: string]: string } = {};
|
|
823
|
+
const draft: { [field: string]: unknown } = {};
|
|
824
|
+
const generate = new Set<string>();
|
|
825
|
+
// A field the layout's conditions hide may come back null, as a write filter sees it.
|
|
826
|
+
const hiddenBefore = this.#hiddenFields(previous, { ...input });
|
|
827
|
+
for (const [name, value] of Object.entries(input)) {
|
|
828
|
+
const declaration = this.resource.fields[name];
|
|
829
|
+
if (!declaration) { errors[name] = 'is not a field of this resource.'; continue; }
|
|
830
|
+
if (value === undefined) continue;
|
|
831
|
+
if (value === null && hiddenBefore.has(name)) { draft[name] = null; continue; }
|
|
832
|
+
// An empty slug is derived from its source field below.
|
|
833
|
+
if (declaration.slugFrom && (value === '' || value === null)) { generate.add(name); continue; }
|
|
834
|
+
if (declaration.access?.write && !hasPermission(principal, declaration.access.write)) { errors[name] = 'cannot be changed by you.'; continue; }
|
|
835
|
+
const error = validateValue(name, declaration, value) ?? textFieldProblem(declaration, value, this.#host.blockTypes);
|
|
836
|
+
if (error) { errors[name] = error; continue; }
|
|
837
|
+
if ((declaration.kind === 'blocks' || declaration.kind === 'richtext') && !hasPermission(principal, PERMISSIONS.unfilteredHtml) && htmlBlocksChanged(value, previous?.[name])) {
|
|
838
|
+
errors[name] = 'has a Custom HTML block, which only people allowed to post HTML can add or change.';
|
|
839
|
+
continue;
|
|
840
|
+
}
|
|
841
|
+
if (declaration.kind === 'blocks') {
|
|
842
|
+
// Each block's data is checked against its type's fields; defaults fill gaps.
|
|
843
|
+
const checked = validateBlocks(value as Block[], this.#host.blockTypes, { ...(declaration.blocks ? { allowed: declaration.blocks } : {}), form: declaration.form === true });
|
|
844
|
+
const [path, message] = Object.entries(checked.errors)[0] ?? [];
|
|
845
|
+
if (path) { errors[name] = `block ${path} ${message}`; continue; }
|
|
846
|
+
draft[name] = checked.blocks;
|
|
847
|
+
continue;
|
|
848
|
+
}
|
|
849
|
+
if (declaration.kind === 'rows') {
|
|
850
|
+
// Rows get IDs the editor did not give; unique row fields are unique within the record.
|
|
851
|
+
const rows = withRowIds(declaration, value, () => blockId());
|
|
852
|
+
const unique = rowUniqueProblem(name, declaration, rows);
|
|
853
|
+
if (unique) { errors[name] = unique.slice(name.length + 2); continue; }
|
|
854
|
+
draft[name] = rows;
|
|
855
|
+
continue;
|
|
856
|
+
}
|
|
857
|
+
if (declaration.kind === 'richtext') {
|
|
858
|
+
// A clean copy of the document; embedded blocks are checked like a blocks field.
|
|
859
|
+
const doc = normalizeRichText(value);
|
|
860
|
+
const checked = validateBlocks(richTextBlocks(doc), this.#host.blockTypes, declaration.blocks ? { allowed: declaration.blocks } : {});
|
|
861
|
+
const [path, message] = Object.entries(checked.errors)[0] ?? [];
|
|
862
|
+
if (path) { errors[name] = `block ${path} ${message}`; continue; }
|
|
863
|
+
draft[name] = withRichTextBlocks(doc, checked.blocks);
|
|
864
|
+
continue;
|
|
865
|
+
}
|
|
866
|
+
draft[name] = value;
|
|
867
|
+
}
|
|
868
|
+
for (const [name, declaration] of Object.entries(this.resource.fields)) {
|
|
869
|
+
if (!declaration.slugFrom || errors[name] || !(generate.has(name) || (action === 'create' && draft[name] === undefined))) continue;
|
|
870
|
+
const source = draft[declaration.slugFrom] ?? previous?.[declaration.slugFrom];
|
|
871
|
+
draft[name] = slugify(typeof source === 'string' ? source : '', declaration.max ?? 200) || 'untitled';
|
|
872
|
+
}
|
|
873
|
+
// Fields the layout's conditions hide are not required and are cleared, rows included.
|
|
874
|
+
const hidden = this.#hiddenFields(previous, draft);
|
|
875
|
+
if (action === 'create') {
|
|
876
|
+
for (const [name, declaration] of Object.entries(this.resource.fields)) {
|
|
877
|
+
if (draft[name] === undefined && declaration.default !== undefined) draft[name] = declaration.default;
|
|
878
|
+
if (declaration.required && draft[name] === undefined && !errors[name] && !hidden.has(name)) errors[name] = 'is required.';
|
|
879
|
+
}
|
|
880
|
+
} else if (previous) {
|
|
881
|
+
for (const [name, declaration] of Object.entries(this.resource.fields)) {
|
|
882
|
+
if (declaration.required && Object.hasOwn(input, name) && input[name] === null && !hidden.has(name)) errors[name] = 'is required.';
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
this.#checkCoOwners(action, draft, previous, principal, errors);
|
|
886
|
+
if (Object.keys(errors).length) throw new CmsError('CMS_VALIDATION', 'Some fields are invalid.', { fields: errors });
|
|
887
|
+
for (const name of hidden) draft[name] = action === 'create' ? undefined : null;
|
|
888
|
+
return Object.freeze(draft);
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
/**
|
|
892
|
+
* Top-level fields the layout's conditions hide for the record as it would be after the
|
|
893
|
+
* draft; rows in the draft lose the values hidden inside them in place.
|
|
894
|
+
*/
|
|
895
|
+
#hiddenFields(previous: RecordShape | null, draft: { [field: string]: unknown }): Set<string> {
|
|
896
|
+
const layout = this.resource.layout;
|
|
897
|
+
if (!layout?.length) return new Set();
|
|
898
|
+
const values: { [field: string]: unknown } = { ...(previous ? this.#fieldsOf(previous) : {}), ...draft };
|
|
899
|
+
const { hidden, values: cleared } = fieldVisibility(layout, this.#host.blockTypes, values);
|
|
900
|
+
const names = new Map(flattenBlocks(layout).map(block => [block._id, typeof block.data.name === 'string' ? block.data.name : '']));
|
|
901
|
+
const top = new Set<string>();
|
|
902
|
+
for (const key of hidden) {
|
|
903
|
+
if (key.includes('/')) continue;
|
|
904
|
+
const name = names.get(key);
|
|
905
|
+
if (name && Object.hasOwn(this.resource.fields, name)) top.add(name);
|
|
906
|
+
}
|
|
907
|
+
for (const [name, declaration] of Object.entries(this.resource.fields)) if (declaration.kind === 'rows' && draft[name] !== undefined && !top.has(name)) draft[name] = cleared[name] ?? draft[name];
|
|
908
|
+
return top;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
#sideEffects(guard: string, op: string, key: string, revision: number, action: 'create' | 'update' | 'delete', record: RecordShape | null, who: WriteActor, now: number, extra: { [key: string]: Value } = {}, previous: RecordShape | null = null): Statement[] {
|
|
912
|
+
const params = { ...extra, $key: key, $op: op, $resource: this.resource.id, $revision: revision, $actor: who.id, $at: now };
|
|
913
|
+
const statements: Statement[] = [];
|
|
914
|
+
if (this.resource.revisions && record) {
|
|
915
|
+
statements.push(bound(
|
|
916
|
+
// A row left by a deleted entry of the same ID (its cleanup job not run yet) gives way.
|
|
917
|
+
`INSERT INTO cms_revisions (id, resource, record_id, revision, data, actor, at) SELECT $revisionId, $resource, $key, $revision, $data, $actor, $at WHERE ${guard}
|
|
918
|
+
ON CONFLICT (id) DO UPDATE SET data = excluded.data, actor = excluded.actor, at = excluded.at`,
|
|
919
|
+
{ ...params, $revisionId: `${this.resource.id}:${key}:${revision}`, $data: JSON.stringify(record) },
|
|
920
|
+
));
|
|
921
|
+
}
|
|
922
|
+
statements.push(bound(
|
|
923
|
+
`INSERT INTO cms_audit (id, actor, action, resource, record_id, revision, at) SELECT $op, $actor, $action, $resource, $key, $revision, $at WHERE ${guard}`,
|
|
924
|
+
{ ...params, $action: action },
|
|
925
|
+
));
|
|
926
|
+
// A deleted record's revisions, drafts, notes and preview links go in an outbox job
|
|
927
|
+
// (`entryDeleted` in the host), a page at a time: an entry saved a thousand times still deletes.
|
|
928
|
+
// The site's search index, guarded by the audit row above.
|
|
929
|
+
statements.push(...this.#host.siteSearch.statements(this.resource, key, op, record && this.canRead(record, ANONYMOUS) ? record : null));
|
|
930
|
+
const event: ResourceEvent = {
|
|
931
|
+
eventId: op, topic: action === 'create' ? 'resource.created' : action === 'update' ? 'resource.updated' : 'resource.deleted',
|
|
932
|
+
// Webhooks, plugins and automations get the reader's view: a locked entry's password and content stay here.
|
|
933
|
+
resource: this.resource.id, id: key, revision, actor: who, at: now, record: record ? lockedView(record, this.resource.fields) : null,
|
|
934
|
+
...(this.resource.fields.status ? { previousStatus: typeof previous?.status === 'string' ? previous.status : null } : {}),
|
|
935
|
+
};
|
|
936
|
+
statements.push(bound(
|
|
937
|
+
`INSERT INTO cms_outbox (id, topic, payload, created_at, available_at, attempts, lease_until) SELECT $op, $topic, $payload, $at, $at, 0, 0 WHERE ${guard}`,
|
|
938
|
+
{ ...params, $topic: event.topic, $payload: JSON.stringify(event) },
|
|
939
|
+
));
|
|
940
|
+
return statements;
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
async #write(statements: Statement[], op: string, context: OperationContext, onRolledBack?: (error: ClientError) => void, statement = 0, kind = 'cms.resource.write'): Promise<{ affected: number; sequence: number }> {
|
|
944
|
+
try {
|
|
945
|
+
const result = await this.#host.db.write(statements, { requestId: op, kind, ...(context.signal ? { signal: context.signal } : {}), workLimits: this.#host.writeLimits });
|
|
946
|
+
this.#host.outboxWritten();
|
|
947
|
+
return { affected: Number(result.results[statement]!.affected), sequence: result.sequence };
|
|
948
|
+
} catch (error) {
|
|
949
|
+
if (error instanceof RequestTooLargeError) throw new CmsError('CMS_LIMIT', 'This entry is too large to save. Shorten it, or split it into several entries.', { cause: error });
|
|
950
|
+
if (error instanceof UncertainWriteError) throw new CmsError('CMS_UNCERTAIN', 'The change was sent but not confirmed. It will be completed or reported shortly.', { requestId: error.requestId, cause: error });
|
|
951
|
+
if (error instanceof ClientError && error.outcome === 'rolled-back') {
|
|
952
|
+
if (error.code === 'RDB_WRITE_CONFLICT') throw new CmsError('CMS_CONFLICT', 'The record changed since it was read. Reload and try again.', { cause: error });
|
|
953
|
+
// Over the write's work limits (rows changed, rows read, steps): a plain limit, not a 500.
|
|
954
|
+
if (error.code === 'RDB_LIMIT') throw new CmsError('CMS_LIMIT', 'This change is too large for one write. Make it in smaller steps.', { cause: error });
|
|
955
|
+
onRolledBack?.(error);
|
|
956
|
+
if (error.code === 'RDB_VALIDATION' || error.code === 'RDB_CONSTRAINT') throw new CmsError('CMS_VALIDATION', 'The database rejected the values.', { cause: error });
|
|
957
|
+
}
|
|
958
|
+
throw error;
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
#readOptions(context: OperationContext) {
|
|
963
|
+
return { ...(context.signal ? { signal: context.signal } : {}), workLimits: this.#host.readLimits };
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
#store(name: string, declaration: FieldDeclaration, value: unknown): Value {
|
|
967
|
+
if (value === null) return null;
|
|
968
|
+
// A multiple field stores its items as the kind stores one.
|
|
969
|
+
if (declaration.multiple) return (value as unknown[]).map(item => this.#store(name, { ...declaration, multiple: false }, item));
|
|
970
|
+
switch (declaration.kind) {
|
|
971
|
+
case 'bigint': return BigInt(value as string | bigint);
|
|
972
|
+
case 'number': return new Float64(value as number);
|
|
973
|
+
case 'reference': return new RecordId(this.#host.resourceById(declaration.target!).storage, value as string);
|
|
974
|
+
case 'vector': return Vector.float32(value as number[]);
|
|
975
|
+
case 'json': case 'blocks': case 'richtext': case 'rows': return storedJson(value);
|
|
976
|
+
default: return value as Value;
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
/** Plain text of the draft's searchable rich text, blocks, rows and multiple fields, at their search paths. */
|
|
981
|
+
#searchText(draft: Draft): [string, string | null][] {
|
|
982
|
+
const plain = (declaration: FieldDeclaration, value: unknown): string => declaration.multiple && Array.isArray(value) ? value.map(item => plain({ ...declaration, multiple: false }, item)).filter(Boolean).join('\n')
|
|
983
|
+
: declaration.kind === 'blocks' ? blocksPlain(value as Block[], this.#host.blockTypes, doc => richTextPlain(doc))
|
|
984
|
+
: declaration.kind === 'rows' ? rowsPlain(declaration, value)
|
|
985
|
+
: declaration.kind === 'richtext' ? richTextPlain(value as RichTextDoc) : typeof value === 'string' ? value : '';
|
|
986
|
+
return Object.entries(this.resource.fields)
|
|
987
|
+
.filter(([name, declaration]) => searchedAsText(declaration) && draft[name] !== undefined)
|
|
988
|
+
.map(([name, declaration]) => [searchTextPath(name), draft[name] === null ? null : plain(declaration, draft[name])]);
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
#shapeOf(document: Document): RecordShape {
|
|
992
|
+
const fields: { [field: string]: unknown } = {};
|
|
993
|
+
const schemaless = this.resource.schemaless;
|
|
994
|
+
for (const [name, declaration] of Object.entries(this.resource.fields)) {
|
|
995
|
+
const value = document[name];
|
|
996
|
+
if (value === undefined) { fields[name] = declaration.default ?? null; continue; }
|
|
997
|
+
if (!schemaless) { fields[name] = publicValue(declaration, value); continue; }
|
|
998
|
+
// A schemaless record can hold a value from before its field changed; it reads as the default.
|
|
999
|
+
let shaped: unknown;
|
|
1000
|
+
try { shaped = publicValue(declaration, value); } catch { shaped = undefined; }
|
|
1001
|
+
fields[name] = shaped === undefined || (shaped !== null && validateValue(name, declaration, shaped) !== undefined) ? declaration.default ?? null : shaped;
|
|
1002
|
+
}
|
|
1003
|
+
const id = document.id as RecordId;
|
|
1004
|
+
return this.#shape(String(id.key), Number(document._rev), Number(document._createdAt), Number(document._updatedAt), (document._owner as string | null | undefined) ?? null, fields);
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
#public(document: Document, principal: Principal): RecordShape {
|
|
1008
|
+
return this.#redact(this.#shapeOf(document), principal);
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
#shape(id: string, rev: number, createdAt: number, updatedAt: number, owner: string | null, fields: { readonly [field: string]: unknown }): RecordShape {
|
|
1012
|
+
const shape: { [field: string]: unknown } = { id, rev, createdAt, updatedAt, owner };
|
|
1013
|
+
for (const name of Object.keys(this.resource.fields)) shape[name] = fields[name] === undefined ? this.resource.fields[name]!.default ?? null : fields[name];
|
|
1014
|
+
return Object.freeze(shape) as RecordShape;
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
#fieldsOf(record: RecordShape): { [field: string]: unknown } {
|
|
1018
|
+
return Object.fromEntries(Object.keys(this.resource.fields).map(name => [name, record[name]]));
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
#canRead(name: string, principal: Principal): boolean {
|
|
1022
|
+
const permission = this.resource.fields[name]?.access?.read;
|
|
1023
|
+
return !permission || hasPermission(principal, permission);
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
/** Remove fields the principal may not read. */
|
|
1027
|
+
#redact(record: RecordShape, principal: Principal): RecordShape {
|
|
1028
|
+
const hidden = Object.keys(this.resource.fields).filter(name => !this.#canRead(name, principal));
|
|
1029
|
+
if (!hidden.length) return record;
|
|
1030
|
+
const copy: { [field: string]: unknown } = { ...record };
|
|
1031
|
+
for (const name of hidden) delete copy[name];
|
|
1032
|
+
return Object.freeze(copy) as RecordShape;
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
type Document = { [field: string]: Value };
|
|
1037
|
+
|
|
1038
|
+
function publicValue(declaration: FieldDeclaration, value: Value): unknown {
|
|
1039
|
+
if (value === null) return null;
|
|
1040
|
+
if (declaration.multiple) return Array.isArray(value) ? value.map(item => publicValue({ ...declaration, multiple: false }, item)) : [];
|
|
1041
|
+
switch (declaration.kind) {
|
|
1042
|
+
case 'integer': case 'datetime': return Number(value as bigint);
|
|
1043
|
+
case 'bigint': return String(value);
|
|
1044
|
+
case 'number': return value instanceof Float64 ? value.value : Number(value as bigint);
|
|
1045
|
+
case 'reference': return value instanceof RecordId ? String(value.key) : null;
|
|
1046
|
+
case 'json': case 'blocks': case 'richtext': case 'rows': return toJson(value);
|
|
1047
|
+
case 'vector': {
|
|
1048
|
+
const bytes = (value as Vector).bytes;
|
|
1049
|
+
return [...new Float32Array(bytes.buffer, bytes.byteOffset, Math.floor(bytes.byteLength / 4))];
|
|
1050
|
+
}
|
|
1051
|
+
default: return value;
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
/** Plain JSON for storage: fractional numbers become explicit floats, integers stay int64. */
|
|
1056
|
+
function storedJson(value: unknown): Value {
|
|
1057
|
+
if (typeof value === 'number') return Number.isInteger(value) ? value : new Float64(value);
|
|
1058
|
+
if (Array.isArray(value)) return value.map(storedJson);
|
|
1059
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, storedJson(entry)]));
|
|
1060
|
+
return value as Value;
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
function toJson(value: Value): unknown {
|
|
1064
|
+
if (typeof value === 'bigint') return Number(value);
|
|
1065
|
+
if (value instanceof Float64) return value.value;
|
|
1066
|
+
if (value instanceof RecordId) return `${value.table}:${String(value.key)}`;
|
|
1067
|
+
if (Array.isArray(value)) return value.map(toJson);
|
|
1068
|
+
if (value && typeof value === 'object' && !(value instanceof Uint8Array) && !(value instanceof Vector)) {
|
|
1069
|
+
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, toJson(entry)]));
|
|
1070
|
+
}
|
|
1071
|
+
return value;
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
/** Media IDs in a group field's media subfields. */
|
|
1075
|
+
function groupMedia(declaration: FieldDeclaration, value: { readonly [key: string]: unknown }): string[] {
|
|
1076
|
+
return Object.entries(declaration.fields ?? {}).filter(([, nested]) => nested.media).flatMap(([key]) => {
|
|
1077
|
+
const entry = value[key];
|
|
1078
|
+
return typeof entry === 'string' && entry ? [entry] : Array.isArray(entry) ? entry.filter((item): item is string => typeof item === 'string') : [];
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
function actor(principal: Principal): WriteActor {
|
|
1083
|
+
return { kind: principal.kind, id: principalId(principal) };
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
function checkKey(id: string): void {
|
|
1087
|
+
if (typeof id !== 'string' || !KEY.test(id)) throw new CmsError('CMS_VALIDATION', 'Record IDs are 1-80 letters, digits, underscores or hyphens.');
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
function encodeCursor(at: number, key: string): string {
|
|
1091
|
+
return btoa(JSON.stringify([at, key])).replaceAll('=', '');
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
function decodeCursor(cursor: string): { at: number; key: string } {
|
|
1095
|
+
try {
|
|
1096
|
+
const [at, key] = JSON.parse(atob(cursor)) as [unknown, unknown];
|
|
1097
|
+
if (Number.isSafeInteger(at) && typeof key === 'string' && KEY.test(key)) return { at: at as number, key };
|
|
1098
|
+
} catch { /* invalid below */ }
|
|
1099
|
+
throw new CmsError('CMS_VALIDATION', 'Invalid page cursor.');
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
export { afterCommit };
|
|
1103
|
+
|
|
1104
|
+
/** Translations one shared-field update reaches. */
|
|
1105
|
+
const SHARED_MEMBERS = 100;
|
|
1106
|
+
/** Room left in a request for its envelope (request ID, sequences, work limits). */
|
|
1107
|
+
const REQUEST_MARGIN = 2048;
|