@cossackframework/cms 0.0.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +145 -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 +114 -2
- 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
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tan Nguyen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,5 +1,148 @@
|
|
|
1
1
|
# @cossackframework/cms
|
|
2
2
|
|
|
3
|
-
Cossack CMS:
|
|
3
|
+
The Cossack CMS on RomeDB: collections defined as data and stored schemaless, blocks, rich
|
|
4
|
+
text stored as ProseMirror JSON, taxonomies with nested terms, media, settings, themes,
|
|
5
|
+
menus, resources with a schema planner and a migration ledger, authorized repositories,
|
|
6
|
+
users and sign-in with authenticator apps and passkeys, the framework stores, an outbox and
|
|
7
|
+
plugin hosting. Publishing tools: scheduled entries, preview links, autosaves, revisions you
|
|
8
|
+
can compare and restore, automatic and managed redirects, per-entry SEO, resized image
|
|
9
|
+
variants with crops and focal points, application passwords for the content and management API (`cossack cms`, MCP), signed
|
|
10
|
+
webhooks, moderated comments, reusable patterns and translations. Several people edit one
|
|
11
|
+
entry together through its room (live text, presence, a shared draft; `docs/cms/collaboration.md`) and leave
|
|
12
|
+
review notes for each other on passages, blocks and fields (`docs/cms/notes.md`). Forms are built from
|
|
13
|
+
input blocks with conditional logic, and each keeps its submissions in a table of its own,
|
|
14
|
+
with notifications, webhooks and hooks like Gravity Forms'. Add it to an
|
|
15
|
+
application with `cossack add cms`, which renders the shared `auth` and `dashboard` pages
|
|
16
|
+
over CMS storage and a default theme into `src/plugins/default-theme/`. It runs on Cloudflare Workers
|
|
17
|
+
with RomeDB Cloud and on Node.js with a RomeDB file in the server's process, `romedb serve` or Cloud. The package is also an application: `app/`
|
|
18
|
+
holds the pages, components and API routes that `cossack add cms` renders, and `pnpm dev` here (or
|
|
19
|
+
`pnpm dev:cms` at the repository root) runs them from the workspace; see `app/README.md`.
|
|
4
20
|
|
|
5
|
-
|
|
21
|
+
```ts
|
|
22
|
+
import { field, type CollectionDefinition } from '@cossackframework/cms';
|
|
23
|
+
|
|
24
|
+
export const products: CollectionDefinition = {
|
|
25
|
+
name: 'products',
|
|
26
|
+
label: 'Products',
|
|
27
|
+
singular: 'Product',
|
|
28
|
+
path: 'shop',
|
|
29
|
+
taxonomies: ['tags'],
|
|
30
|
+
features: { content: { blocks: ['core/heading', 'core/paragraph', 'core/image'] }, featuredImage: true },
|
|
31
|
+
fields: {
|
|
32
|
+
price: field.number({ required: true, min: 0 }),
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
| Entry | Use |
|
|
38
|
+
| --- | --- |
|
|
39
|
+
| `@cossackframework/cms` | Collections, blocks, fields, rich text, menus, the theme contract, permissions, settings, extension points, manifests, media helpers, the co-editing rules (client-safe) |
|
|
40
|
+
| `@cossackframework/cms/server` | `createCMS`, repositories, planner, users, taxonomies, menus, settings, files, auth, stores, outbox, Markdown (server-only) |
|
|
41
|
+
|
|
42
|
+
Data contract:
|
|
43
|
+
|
|
44
|
+
- Each collection is its own document table, `r__cms__<name>`. Only host fields are typed in
|
|
45
|
+
the database; the host validates content fields, and reads tolerate values that no longer
|
|
46
|
+
fit a changed field. Saving a definition changes only indexes.
|
|
47
|
+
- A collection's standard fields are its features (`content`, `excerpt`, `featuredImage`,
|
|
48
|
+
`revisions`), fixed names themes rely on; its other fields are the field groups attached
|
|
49
|
+
to it, in the order the collection manager sets. Field groups are meta boxes built from
|
|
50
|
+
blocks: field blocks laid out with the core layout blocks, attached to collections,
|
|
51
|
+
taxonomies, users and menu items. They compile to field declarations, so values are
|
|
52
|
+
stored flat by name; a `rows` field is a repeater (rows with an
|
|
53
|
+
`_id`, nested without limit) whose indexed row fields get an array index on their path
|
|
54
|
+
into the rows (`specs.*.name`, RomeDB 0.2.11) for `array::contains` seeks. A field with
|
|
55
|
+
`multiple: true` holds several values of its kind as one array, each checked with the
|
|
56
|
+
kind's rules, bounded by `minItems` and `maxItems`, and indexed as an array when
|
|
57
|
+
filterable; a gallery is a multiple media field and a multiple choice a list of its
|
|
58
|
+
values. Conditions on fields clear what they hide on write.
|
|
59
|
+
- A collection's entry editor is arranged by its `editor` layout: tabs for the main column
|
|
60
|
+
and a sidebar every tab shares, built from `editor/tab`, `editor/section` and `editor/box`
|
|
61
|
+
blocks with the core columns, grids and notes. A box is one of `editorBoxes()`: a field
|
|
62
|
+
(`field:excerpt`), a field group (`group:pricing`), a taxonomy (`taxonomy:categories`) or
|
|
63
|
+
the editor's own (`seo`, `attributes`, `languages`, `template`, `discussion`, `revisions`);
|
|
64
|
+
the title and the Publish box are pinned. Without a stored layout the editor shows
|
|
65
|
+
`defaultEditorLayout()`, the arrangement it always had; `resolveEditorLayout()` appends
|
|
66
|
+
boxes a layout does not name, leaves out boxes that are gone and merges what active
|
|
67
|
+
plugins' manifests add (`editor`). Plugin manifests also ship field groups
|
|
68
|
+
(`fieldGroups`), stored when the plugin is granted. A tab's ID names it in the editor's
|
|
69
|
+
address (`?tab=pricing`, `EDITOR_TAB_ID`). The collection manager's Editor tab edits the
|
|
70
|
+
layout as one tree, the sidebar its last row, so meta boxes (the dashboard's word for
|
|
71
|
+
boxes) drag between a tab and the sidebar.
|
|
72
|
+
- Each mutation is one atomic batch: record, revision, audit and outbox rows, guarded by
|
|
73
|
+
the operation ID, so a stale edit writes nothing.
|
|
74
|
+
- Terms store their ancestors' IDs as a path, so a subtree is a prefix match and a move is
|
|
75
|
+
one statement. Entries hold term IDs in indexed arrays.
|
|
76
|
+
- Code-declared resources use strict collections. Generated schema changes are additive;
|
|
77
|
+
renames, backfills, tighter rules and drops are explicit, versioned steps. Each step is one
|
|
78
|
+
batch sent with `ifSequence`; a conflict re-plans.
|
|
79
|
+
- A resource is active only when the database records its current declaration.
|
|
80
|
+
- Blocks are one tree: `{ id, type, data }`, with `children` under a container (`core/group`,
|
|
81
|
+
`core/columns` holding `core/column`, `core/grid`) and a core-checked `layout` (`hide` by
|
|
82
|
+
container width). A type declares what it holds (`children`) and where it goes (`parent`);
|
|
83
|
+
at most 200 blocks and 4 levels per field. Layouts are blocks, so revisions, patterns and
|
|
84
|
+
the front-end editor cover them; nothing is stored beside the block list.
|
|
85
|
+
- A block's text fields may bind to the entry's fields: `{{ $.price }}` puts the value inside
|
|
86
|
+
the text, with words and formatting around it (`resolveBindings`, `resolveBlockBindings`);
|
|
87
|
+
the default theme lists no fields on its own. The site resolves them when
|
|
88
|
+
it renders an entry; the editor keeps the syntax and offers the fields in a picker.
|
|
89
|
+
- A block's `style` holds slugs of the theme's presets (`background`, `text`, `padding`,
|
|
90
|
+
`margin`, `fontSize`) and an `align`; `layout` adds an `anchor` and `className`. A type's
|
|
91
|
+
`supports` narrows what its Style tab offers over its category's defaults. Themes declare
|
|
92
|
+
`presets` (colors, font sizes, spacing) in their manifest, Customize adjusts the palette
|
|
93
|
+
and adds site-level CSS, and `blockStyleAttributes` renders a styled block's wrapper with
|
|
94
|
+
classes and custom properties, so a palette change recolors stored content.
|
|
95
|
+
- An entry's content is blocks: the `content` feature, on for posts and pages, and the
|
|
96
|
+
`core/richtext` block is the word processor among them. Themes get one `entry.content`
|
|
97
|
+
list: every blocks field, and each rich text or Markdown field as one rich text block. A collection's `template` is the
|
|
98
|
+
blocks every new entry's content starts with (`templateLock` keeps them, or their order too); blocks
|
|
99
|
+
of the `data` category store values and render nothing. Rich text is validated against an
|
|
100
|
+
allow-list of nodes, marks and attributes on every write and rendered to escaped HTML; the
|
|
101
|
+
plain text of searchable rich text and blocks fields feeds the full-text index.
|
|
102
|
+
- Extension points besides the resource and form hooks: `cms.term.before-save`,
|
|
103
|
+
`cms.comment.before-save` and `cms.menu.before-save` adjust or refuse writes;
|
|
104
|
+
`cms.dashboard.entry-actions` (the built-in quick actions, which handlers add to, remove
|
|
105
|
+
or reorder), `entry-columns` and `bulk-actions` add links, plugin commands and
|
|
106
|
+
columns to the dashboard's entry lists.
|
|
107
|
+
- A menu is one JSON tree saved with a revision check. Entries and terms are stored by ID and
|
|
108
|
+
resolved when the site renders.
|
|
109
|
+
- A plugin runs only when its resources are migrated and an administrator grants what its
|
|
110
|
+
manifest requests. Builds run the plugin policy lints (`cossack plugins check`). Its
|
|
111
|
+
`ui.slots` links fill the dashboard navigation (`dashboard.nav`), the dashboard's bottom
|
|
112
|
+
taskbar (`dashboard.taskbar`) and the taskbar signed-in users see on the site (`site.taskbar`).
|
|
113
|
+
- A theme is a plugin whose manifest has a `theme` field and whose `templates/` files (or
|
|
114
|
+
`ui.ts` `theme` export) are the site templates, picked per page from most specific
|
|
115
|
+
(`entry-posts`, `term-category`) to general (`entry`, `archive`). Themes own templates, not
|
|
116
|
+
routes. Activating one is a settings write; its templates need no grant. A theme's
|
|
117
|
+
`server.ts` exports `loaders` that read data under the plugin's grants for its templates;
|
|
118
|
+
`templates/head.ts` adds stylesheets and fonts from `assets/`; `theme.extends` makes a child
|
|
119
|
+
theme; `theme.areas` declares widget areas; a manifest's `collections` ship site
|
|
120
|
+
collections with the plugin. Editors can choose an entry's template and edit its blocks on
|
|
121
|
+
the public page.
|
|
122
|
+
- A form is a `forms` entry whose `body` holds input blocks (`input: { kind }` in the
|
|
123
|
+
declaration), laid out with the containers and shown or hidden by a block's `when`; a
|
|
124
|
+
`form/repeater` holds a row of inputs people fill in once per passenger or item, and a
|
|
125
|
+
text, number or date input with `multiple` on takes several values, added one at a time. A
|
|
126
|
+
`form/file` input takes uploads (allowed extensions or types, up to 10 MB a file, 10 files, 25 MB
|
|
127
|
+
a submission; the content is checked against the type): the files are private files under
|
|
128
|
+
`cms/private/forms/<form>/<submission>/`, which the library and `/media/` never serve, and
|
|
129
|
+
download through `GET /api/cms/forms/<form>/submissions/<id>/files/<file>` with `cms:submissions`;
|
|
130
|
+
the record keeps `{ id, name, size, type }`, and deleting the submission or the form removes them. Its
|
|
131
|
+
submissions are the resource `cms/form_<form id>`, stored in its own table and extended
|
|
132
|
+
when inputs are added. A submission is one batch: the record, a receipt and its
|
|
133
|
+
`form.submitted` outbox event, which sends the form's notifications and webhooks. Hooks:
|
|
134
|
+
`cms.form.validate`, `before-submit`, `prefill`, `confirmation`, `notification` and
|
|
135
|
+
`submitted`.
|
|
136
|
+
- Scheduled entries are published by maintenance as a system write, so their outbox events
|
|
137
|
+
and webhooks fire when they go live. A published entry's URL change records a 301 in the
|
|
138
|
+
same batch.
|
|
139
|
+
- Preview links, application passwords and recovery codes are stored as SHA-256 hashes.
|
|
140
|
+
Webhook deliveries are queued per webhook from the outbox and signed with HMAC-SHA256.
|
|
141
|
+
- After a package upgrade, new host tables and changed built-in collections apply on the
|
|
142
|
+
next request; code-declared resources and plugins still migrate from Tools → Schema.
|
|
143
|
+
|
|
144
|
+
See the guides with `cossack docs --package @cossackframework/cms`, and the developer docs
|
|
145
|
+
in `docs/cms/`: [overview](../../docs/cms/index.md), [plugins](../../docs/cms/plugins.md),
|
|
146
|
+
[manifest](../../docs/cms/manifest.md), [hooks](../../docs/cms/hooks.md),
|
|
147
|
+
[themes](../../docs/cms/themes.md), [menus](../../docs/cms/menus.md),
|
|
148
|
+
[settings](../../docs/cms/settings.md) and [languages](../../docs/cms/languages.md).
|
package/agent-docs.json
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schemaVersion": 1,
|
|
3
|
+
"guides": [
|
|
4
|
+
{
|
|
5
|
+
"id": "cms-resources",
|
|
6
|
+
"title": "Declare CMS resources as data",
|
|
7
|
+
"summary": "defineResource() declares fields, indexes, access rules, ownership and explicit migration steps; the planner turns declarations into additive RomeDB DDL.",
|
|
8
|
+
"imports": [
|
|
9
|
+
"@cossackframework/cms"
|
|
10
|
+
],
|
|
11
|
+
"markdown": "A resource is plain data, so it can live in application code or a plugin manifest. Field builders map to one RomeDB field type and CHECK each: `string`, `text`, `enum`, `integer`, `bigint`, `number`, `boolean`, `datetime` (Unix milliseconds), `reference`, `json`, `vector` and `blocks`; `field.slug(from)`, `field.terms(taxonomy)`, `field.media()` and `field.gallery()` build a unique slug derived from another field, indexed term IDs, a media file ID and several. Options include `required`, `nullable`, `default`, `max`, `min`, `pattern`, `unique`, `index`, `search` (full-text) and `multiple` (several values of the kind as one array, each checked with the kind's rules, bounded by `minItems` and `maxItems`, indexed as an array when `index` is on; `field.list(kind)` is its shorthand). Records are stored in a strict collection `r__<owner>__<name>` with host fields for revision, operation, timestamps and owner. `schemaless: true` types only the host fields in the database and validates the rest in the host, so field changes need no DDL; collections use it.\n\nAccess rules per action are `public`, `authenticated`, `owner` (needs `ownership: true`), `{ permission }`, `{ where: { field: value } }` (records whose fields match, such as published posts), `{ any: [...] }` or `none`. Unlisted actions require `<resource>:<action>`, for example `app/tickets:update`. Field `access` hides or locks single fields.\n\n`cms.plan()` reads the live catalog through INFO and plans additive DDL: new collections, optional fields and indexes. A changed type, a new required field or a tighter rule is blocked until an explicit step covers it: `backfill`, `tighten`, `rename` (keep the old field declared) and, in a later release, `drop`. `cms.migrate()` applies each step as one atomic batch with `ifSequence` from the planning read, records it in the `cms_migrations` ledger with the exact RomeQL and engine release, and re-plans when another write lands first. A failed step rolls back and its resource stays inactive.",
|
|
12
|
+
"examples": [
|
|
13
|
+
{
|
|
14
|
+
"id": "cms-resources",
|
|
15
|
+
"language": "typescript",
|
|
16
|
+
"source": "import { defineResource, field } from '@cossackframework/cms';\n\nexport const tickets = defineResource({\n name: 'tickets',\n label: 'Tickets',\n titleField: 'subject',\n ownership: true,\n fields: {\n subject: field.string({ required: true, max: 120, search: true }),\n status: field.enum(['open', 'closed'], { required: true, default: 'open', index: true }),\n priority: field.integer({ min: 1, max: 5, default: 3 }),\n assignee: field.string({ nullable: true }),\n team: field.string(),\n },\n access: {\n read: { any: ['owner', { permission: 'app/tickets:read' }] },\n create: 'authenticated',\n update: { any: ['owner', { permission: 'app/tickets:update' }] },\n delete: { permission: 'app/tickets:delete' },\n },\n // Generated changes are additive; stricter rules are explicit, ordered steps.\n migrations: [\n { version: 1, kind: 'backfill', field: 'team', value: 'support' },\n ],\n});\n"
|
|
17
|
+
}
|
|
18
|
+
]
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
"id": "cms-repositories",
|
|
22
|
+
"title": "Read and write records through repositories",
|
|
23
|
+
"summary": "Repositories authorize every call, compile bounded parameterized RomeQL, and write the record, revision, audit row and outbox event in one atomic batch.",
|
|
24
|
+
"imports": [
|
|
25
|
+
"@cossackframework/cms/server",
|
|
26
|
+
"@cossackframework/cms"
|
|
27
|
+
],
|
|
28
|
+
"markdown": "`createCMS({ db, modules, resources, plugins, storage })` builds the host; `cms.resource(id)` returns a repository with `get`, `list`, `count`, `countMany`, `search` (full-text over `search: true` fields), `create`, `update`, `delete` and `revisions`. `where` takes a value, `{ ne }`, `{ in }`, ranges (`gt`, `gte`, `lt`, `lte`) and, on indexed lists such as terms, `{ contains }` or `{ containsAny }`; `order` and `offset` give numbered pages, `after` cursor pages. Empty slug fields are derived from their source field, and taken slugs get `-2`, `-3`, …. Every call takes the request principal. Owner rules become query conditions, and owner-scoped search computes allowed IDs first and checks every hit again in the same query. Public shapes are JSON-safe: `{ id, rev, createdAt, updatedAt, owner, ...fields }`, with bigint fields as decimal strings.\n\nA mutation is one atomic batch. An edit carries `expectedRevision`; a stale revision, lost access or a concurrent edit of the same record fails with `CMS_CONFLICT` and writes nothing else, because the revision, audit and outbox rows are guarded by the operation ID the record statement wrote. Before the batch, `cms.resource.before-write` filters can adjust or reject the draft under a deadline. After commit, `cms.outbox.dispatch()` delivers `cms.resource.after-commit` events and retries only the plugins that failed. An unconfirmed write fails with `CMS_UNCERTAIN` and is completed by `db.recoverPending()`.",
|
|
29
|
+
"examples": [
|
|
30
|
+
{
|
|
31
|
+
"id": "cms-repositories",
|
|
32
|
+
"language": "typescript",
|
|
33
|
+
"source": "import { createRomeDB, MemoryPendingWriteStore } from '@cossackframework/romedb';\nimport { contentModule, createCMS, isCmsError, userPrincipal } from '@cossackframework/cms/server';\n\nconst db = createRomeDB({ url: 'http://127.0.0.1:4321', token: 'local-service-token', pending: new MemoryPendingWriteStore() });\nconst cms = createCMS({ db, modules: [contentModule] });\nconst editor = userPrincipal('user-1', ['editor'], ['cms/posts:*']);\n\nexport async function publish(): Promise<string> {\n const report = await cms.migrate();\n if (report.failed) return report.failed.message;\n const posts = cms.resource('cms/posts');\n // The slug is derived from the title: hello-world.\n const draft = await posts.create({ title: 'Hello world' }, { principal: editor });\n try {\n // One atomic batch: the record, its revision, the audit row and the outbox event.\n const live = await posts.update(draft.id, { status: 'published' }, { principal: editor, expectedRevision: draft.rev });\n return `${live.id} is at revision ${live.rev}`;\n } catch (error) {\n if (isCmsError(error, 'CMS_CONFLICT')) return 'Someone else changed the post.';\n throw error;\n } finally {\n await cms.outbox.dispatch();\n }\n}\n"
|
|
34
|
+
}
|
|
35
|
+
]
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
"id": "cms-collections",
|
|
39
|
+
"title": "Define collections, blocks, taxonomies, settings and media",
|
|
40
|
+
"summary": "Collections are content types defined as data and stored schemaless; blocks fields hold typed content blocks; taxonomies group entries by nested terms; settings and media are host services.",
|
|
41
|
+
"imports": [
|
|
42
|
+
"@cossackframework/cms",
|
|
43
|
+
"@cossackframework/cms/server"
|
|
44
|
+
],
|
|
45
|
+
"markdown": "A collection, such as `products`, is the resource `cms/<name>` built from a `CollectionDefinition`: label, title, generated slug, publishing (draft, pending review, scheduled, published, trash), nesting through `parent`, taxonomies, a public URL `path` and fields. A `path` of `''` serves entries at the site root, as WordPress's \"Post name\" permalinks do: root entries share one slug namespace with other root collections, archive bases and the application's `reservedPaths`, and `cms.archiveUrl(collection)` finds where a root collection's archive lives (for posts, the Reading settings' posts page). A collection's standard fields are its `features`, with fixed names themes and code rely on: `content` (blocks, searchable; by hand `{ blocks: [...] }` restricts its types), `excerpt`, `featuredImage` (sidebar media) and `revisions` (default on); their names are reserved (`RESERVED_FIELDS`, the core fields and `FEATURE_FIELDS`), so no field or group declares them. Posts and pages are built-in collections in `contentModule`; administrators add collections with `cms.saveCollection(definition, principal, { groups })`, which needs `cms:collections`: `groups` lists the field groups attached to the collection in order (`[{ id, order? }]`), groups it leaves out are detached, and the schema is planned once. Fields made in the dashboard live in field groups; `fields` is for definitions written by hand. A definition with `managed: true` (forms, or a plugin's collection with screens of its own) is left out of the collection manager, refuses `saveCollection` from the dashboard and takes no field groups; only the module or plugin that ships it declares it. Each collection is its own document table without `STRICT`: saving changes only indexes and records the declaration hash with the stored definition in one step. Built-in collections keep their core fields and features and accept added ones; their `fieldOrder` places the module's fields among the added ones, and new fields go last. Every collection also has `seo` (a `field.group()` of title, description, social image, canonical URL and noindex), `locale` and `translationGroup`; one with `comments: true` has `commentsOpen`. When a package upgrade changes a built-in collection or adds host tables, `ready()` applies them on the next request. Hosts call `await cms.ready()` per request to load definitions; a write that finds a newer definition reloads it first.\n\nA `blocks` field holds a tree of `{ id, type, data }`: a container's `children` hold more blocks, and every block may carry a `layout` (`hide`: the container widths `sm`, `md`, `lg` it is hidden at), which core checks. `CORE_BLOCKS` are paragraph, heading, image, gallery, quote, list, code, button, embed, divider and the layout blocks `core/group` (a stack with a width), `core/columns` (holding only `core/column`, which has a `span` out of 12) and `core/grid` (columns per width); plugins add types in their manifest's `blocks`, and a type declares `children: { allowed?, max? }` to hold blocks and `parent` to go only inside those types. A block type names a Solar `icon` and a `category` from `BLOCK_CATEGORIES` (text, media, design, widgets, embeds; default widgets), which the editor's block picker groups by. The host validates every block's data against its type on write, and the tree against the types' rules: at most 200 blocks and 4 levels per field, IDs distinct across the tree. `validateBlocks`, `blockMedia`, the revision diff and patterns walk the tree; `flattenBlocks`, `placeBlocks`, `findBlock`, `updateBlock`, `insertBlock`, `moveBlock`, `shiftBlock` (up, down, in, out) and `blockTreeProblem` are the tree helpers editors use. A required text field must not be blank.\n\nEvery block may also carry a `style`: slugs of the active theme's presets for `background`, `text`, `padding`, `margin` and `fontSize`, plus `align` (left, center, right); `layout` adds `anchor` (an HTML id) and `className`. A type's `supports` (`color`, `spacing`, `typography`: true, false or a list of properties) narrows or widens its category's defaults (`blockSupports`: text blocks get all three, media blocks spacing alone, the rest color and spacing); `validateBlocks` keeps the supported properties and drops the rest. A theme's manifest declares `presets` (`colors`, `fontSizes`, `spacing` as `{ slug, name, value }`, checked by `presetProblems`; `DEFAULT_PRESETS` fills missing kinds and a child theme's layer over its parent's by slug); the site's changes live in the `appearance.presets` setting keyed by theme (`presetOverridesProblem`) and `resolvePresets` combines them. `blockStyleAttributes(block)` gives a styled block's wrapper (`cms-block cms-bg-<slug> …`, inline `background-color: var(--cms-color-<slug>)`, the anchor as `id`), `presetStyle(presets)` the custom properties for the content root, and `customCssProblem` checks the `appearance.customCss` setting (no `@import`, `url()`, scripts or tags).\n\n`cms.taxonomies` keeps terms with a materialized path of ancestor IDs: `create`, `update` (a move rewrites the subtree in one statement), `delete` (children move up), `tree`, `subtree`, `ancestors`, `counts` and `ensure` (tags typed by name). Records hold term IDs in indexed arrays, so `{ containsAny: await cms.taxonomies.subtree(id) }` lists a category and the categories below it. `cms.saveTaxonomy()` adds vocabularies.\n\n`cms.settings` stores validated groups (General, Media, Writing, Reading and those modules add), cached per isolate. `cms.files` (with `storage`) accepts uploads whose declared type matches the file signature, records image size, alt text and captions, and lists the library by kind.\n\n**Editor layout.** A collection's `editor` arranges its entry editor: `{ tabs, sidebar }`, a block tree of `editor/tab` (label, and an icon from the dashboard's set; its `_id` is the tab's ID, which the editor's address names as `?tab=`: a slug of at most 40 characters, `EDITOR_TAB_ID`, never `json` or `sidebar`, `EDITOR_TAB_RESERVED`; `editorTabId(label, taken)` makes one from a label; the first tab's is `edit`, `EDIT_TAB`), `editor/section` (title, description), `editor/box` (`box`: a box ID; the dashboard calls a box a meta box) and the core columns, grids and notes (`EDITOR_LAYOUT_CORE`; `EDITOR_LAYOUT_INSIDE` is what goes inside a tab, a section, a column or a grid cell: never a tab). A box is one of `editorBoxes({ collection, fields, groups, taxonomies, special })`: `field:<name>` for a feature or a declared field, `group:<id>` for an attached field group, `taxonomy:<name>`, and the editor's own `seo`, `attributes`, `languages`, `template`, `discussion` and `revisions` (`EDITOR_OWN_BOXES`, each with a note saying when it shows); the title and the Publish box are pinned. `defaultEditorLayout(boxes)` is the arrangement the editor always had (one Edit tab with the main boxes, the sidebar's boxes by `fieldPlacement` and the groups' `placement`); `resolveEditorLayout(stored, boxes, additions, { keep? })` is what the editor renders: the stored layout or the default, active plugins' `editor` additions merged (`cms.editorLayoutAdditions(name)`), boxes the layout does not name appended, boxes that are gone left out (`missing`). `editorLayoutProblems(layout, { partial?, types? })` checks a layout (`collectionProblems` runs it); `editorLayoutTypes(boxes?, keep?)` gives the block types with the boxes as the Meta box block's choices; `boxFields(id, groups)` names the fields a box edits, so an editor can badge the tab an error is on. The collection manager has three tabs, General, Search engines and Editor; the Editor tab edits the layout as one tree whose last row is the sidebar, so a meta box drags between a tab and the sidebar. The groups page's placement is the default only.",
|
|
46
|
+
"examples": [
|
|
47
|
+
{
|
|
48
|
+
"id": "cms-collections",
|
|
49
|
+
"language": "typescript",
|
|
50
|
+
"source": "import { createRomeDB, MemoryPendingWriteStore } from '@cossackframework/romedb';\nimport { contentModule, createCMS, field, userPrincipal } from '@cossackframework/cms/server';\n\nconst db = createRomeDB({ url: 'http://127.0.0.1:4321', token: 'local-service-token', pending: new MemoryPendingWriteStore() });\nconst cms = createCMS({ db, modules: [contentModule] });\nconst admin = userPrincipal('admin-1', ['admin'], ['*']);\n\nexport async function launchShop(): Promise<string> {\n await cms.migrate();\n await cms.saveTaxonomy({ name: 'brands', label: 'Brands', singular: 'Brand', hierarchical: false, path: 'brand' }, admin);\n await cms.saveCollection({\n name: 'products', label: 'Products', singular: 'Product', path: 'shop', taxonomies: ['brands'],\n fields: {\n price: field.number({ required: true, min: 0, label: 'Price' }),\n content: field.blocks({ blocks: ['core/heading', 'core/paragraph', 'core/image'], label: 'Content' }),\n },\n }, admin);\n const [acme] = await cms.taxonomies.ensure('brands', ['Acme'], { principal: admin });\n const product = await cms.resource('cms/products').create({\n title: 'Rocket skates', price: 19.5, brands: [acme!], status: 'published',\n content: [{ _id: 'intro', type: 'core/heading', data: { text: 'Fast wheels' } }],\n }, { principal: admin });\n await cms.settings.update('reading', { postsPerPage: 12 }, { principal: admin });\n return `/shop/${String(product.slug)}`;\n}\n"
|
|
51
|
+
}
|
|
52
|
+
]
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
"id": "cms-appearance",
|
|
56
|
+
"title": "Build themes, menus and rich text content",
|
|
57
|
+
"summary": "Themes are plugins with site templates and options; menus are revisioned trees resolved for visitors; rich text fields store validated ProseMirror JSON rendered to escaped HTML.",
|
|
58
|
+
"imports": [
|
|
59
|
+
"@cossackframework/cms",
|
|
60
|
+
"@cossackframework/cms/server"
|
|
61
|
+
],
|
|
62
|
+
"markdown": "Themes are plugins, as extensions are in VS Code. A plugin manifest's `theme` field declares the label, menu `locations` (such as `primary` and `footer`) and `options`, settings fields shown under Appearance → Customize and stored as `<plugin>.<option>`. The plugin ships its templates as files under `templates/`, one default export each: `layout.ts`, `entry.ts` and `archive.ts`, optional `home.ts`, `search.ts` and `not-found.ts`, and narrower ones picked at render time: `entry-<collection>.ts`, `archive-<collection>.ts`, `term.ts` and `term-<taxonomy>.ts`. A `ui.ts` `theme` export (a `SiteTheme`, with `templates` for the narrower ones and `blocks` overrides) is also accepted and wins slot by slot; `assembleSiteTheme(registration)` builds the theme, `entryTemplate` and `archiveTemplate` pick one for a view. Themes own templates, never routes: a route a theme needs is an ordinary plugin page. `templates/head.ts` returns a `HeadValue` (stylesheets and fonts from the plugin's `assets/`, linked with `helpers.asset('assets/theme.css')`), merged under the page's own head. A theme's `server.ts` exports `loaders` (`ThemeLoaders`) keyed like templates; the site runs `layout` and the one loader the template hierarchy picks, with the plugin's grants, the visitor principal and a time limit, and templates read the plain JSON as `helpers.data.layout` and `helpers.data.page` (empty before the grant or on failure). `EntryView.fields` holds every field's typed value (media as `MediaView`, references as `{ id, title, url }`, terms as links). Site collections get a core `template` field: editors choose one of the active theme's `entry-*` templates (`cms.entryTemplates()`). `theme.extends` names a parent theme whose templates, loaders, assets, options, locations and areas the child layers over (one level). `theme.areas` declares widget areas, edited under Appearance → Widgets (`cms.areas`, `cms.areaLocations()`) and rendered on `SiteView.areas`. A manifest's `collections` ship site collections with the plugin, shown only while it is active. `EntryView.content` is the entry's whole content as one `RenderedBlock[]`: its blocks fields and each rich text or Markdown field as one `core/richtext` block (carrying `field`), in field order; `helpers.block(entry.content)` renders it. Editors edit an entry's content on the public page with `?edit`: `helpers.block` marks each block in edit mode, so a theme that renders content through the helper is editable. `helpers.block` renders a container's children through itself and wraps a hidden block in a `data-hide` marker; the scaffold's `cms/blocks.css` lays out groups, columns and grids with CSS grid and `@container` queries against the content root (`.cms-content`, which site pages wrap the theme's page in and a theme puts around a widget area), so the site editor's device toggle only narrows that root. Themes override the classes in their stylesheet or a container's renderer in `blocks`. A styled block (its `style` and `layout.anchor` or `className`) renders inside one `div.cms-block` wrapper with classes per property and the presets' variables inline; the manifest's `theme.presets` (colors, font sizes, spacing) layer over a parent theme's and over the core defaults, Appearance → Customize changes palette values, adds colors and site-level Additional CSS (`appearance.presets`, `appearance.customCss`), and `helpers.presets` holds the result, which `siteContent` puts on the content root as custom properties and a theme's layout can put on its root with `presetStyle`. Templates get plain views (`SiteView`, `EntryView`, `ArchiveView`, resolved `MenuItemView` trees) and `ThemeHelpers` (`options`, `presets`, `block(blocks)`, `content(parts)` for block renderers, `isActive(url)`); they never read the database. `cms.themes()` lists them with their `problems`, `cms.activeTheme()` resolves the `appearance.theme` setting to a usable theme, and `cms.activateTheme(name, principal)` switches it at runtime. Theme templates need no grant; a theme's resources, hooks and network access follow the plugin grant. `cossack add cms` renders `src/plugins/default-theme/` as application source. A manifest's `logo` and `cover` name images in the plugin's `assets/` (default `assets/logo.*` and `assets/cover.*`); the Plugins and Themes screens show them, or initials and a gradient when a plugin ships none. A plugin that only ships a theme has nothing to grant and counts as active.\n\n`cms.menus` stores each menu's items as one JSON tree with a revision: `create`, `update(id, { name, items }, { principal, expectedRevision })` (a stale revision is `CMS_CONFLICT` and writes nothing), `delete`, `place(id, locations)`, `assign(location, id | null)` and `forLocation(location)`, which resolves entries and terms by ID to their current titles and URLs for visitors, hides unpublished or deleted targets and is cached per isolate. Items are `link`, `entry`, `archive` or `term`; `menuProblems` validates them (300 items, 5 levels). The editor works on rows: `flattenMenu`, `buildMenu`, `moveRows`, `dropDepths` and `shiftRows` implement drag-and-drop and the move buttons. All of this needs `cms:appearance`.\n\nA `field.richText()` field stores a ProseMirror (TipTap) document, `{ type: 'doc', content }`. `checkRichText` and the repository accept only the declared nodes, marks and attributes, with safe link and image URLs; top-level `cmsBlock` nodes embed blocks validated like a blocks field. `richTextHtml` renders escaped HTML, `richTextParts` splits a document at its blocks for themes, `richTextPlain` and `richTextExcerpt` give its text. A searchable rich text or blocks field indexes its plain text, kept in `_text_<field>`. Posts and pages have a `content` blocks field; the `core/richtext` block is the word processor among the blocks, and a collection's `template` (with `templateLock`) is the blocks every new entry starts with. Blocks of the `data` category (`core/meta`) store values and render nothing.",
|
|
63
|
+
"examples": [
|
|
64
|
+
{
|
|
65
|
+
"id": "cms-appearance",
|
|
66
|
+
"language": "typescript",
|
|
67
|
+
"source": "import { createRomeDB, MemoryPendingWriteStore } from '@cossackframework/romedb';\nimport { contentModule, createCMS, richTextExcerpt, richTextHtml, userPrincipal, type MenuItem, type RichTextDoc } from '@cossackframework/cms/server';\n\nconst db = createRomeDB({ url: 'http://127.0.0.1:4321', token: 'local-service-token', pending: new MemoryPendingWriteStore() });\nconst cms = createCMS({ db, modules: [contentModule] });\nconst admin = userPrincipal('admin-1', ['admin'], ['*']);\n\nexport async function publishWithMenu(): Promise<{ html: string; excerpt: string; menu: string[] }> {\n const body: RichTextDoc = { type: 'doc', content: [\n { type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: 'Opening hours' }] },\n { type: 'paragraph', content: [{ type: 'text', text: 'Open ' }, { type: 'text', text: 'every day', marks: [{ type: 'bold' }] }] },\n ] };\n const about = await cms.resource('cms/pages').create({ title: 'About', content: [{ _id: 'text', type: 'core/richtext', data: { text: body } }], status: 'published' }, { principal: admin });\n const items: MenuItem[] = [\n { id: 'about', kind: 'entry', label: '', collection: 'pages', entry: about.id, children: [] },\n { id: 'blog', kind: 'archive', label: 'Blog', collection: 'posts', children: [] },\n ];\n const menu = await cms.menus.create({ name: 'Main', items }, { principal: admin });\n const locations = (await cms.menuLocations()).map(location => location.name);\n if (locations.includes('primary')) await cms.menus.place(menu.id, ['primary'], { principal: admin, known: locations });\n const resolved = await cms.menus.forLocation('primary') ?? [];\n const text = (about.content as { data: { text: RichTextDoc } }[])[0]!.data.text;\n return { html: richTextHtml(text), excerpt: richTextExcerpt(text, 20), menu: resolved.flatMap(item => item.url ? [item.url] : []) };\n}\n"
|
|
68
|
+
}
|
|
69
|
+
]
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
"id": "cms-plugins",
|
|
73
|
+
"title": "Write a CMS plugin within its manifest",
|
|
74
|
+
"summary": "A plugin's manifest declares resources, settings, hooks, permissions, network hosts, slots and commands; its server.ts registers handlers through a context limited to those declarations.",
|
|
75
|
+
"imports": [
|
|
76
|
+
"@cossackframework/cms",
|
|
77
|
+
"@cossackframework/cms/server"
|
|
78
|
+
],
|
|
79
|
+
"markdown": "`cossack add plugin` renders a plugin package into `src/plugins/<name>/`. The manifest (`plugin.json`) declares `resources`, `blocks` (block types named `<plugin>/<name>`), `fieldGroups` (field groups with IDs `<plugin>-…`, stored when the plugin is granted), `editor` (tabs and sidebar boxes added to a collection's entry editor while the plugin is active, `[{ collection, tabs?, sidebar? }]`), `hooks` (extension points and versions), `permissions.resources` (access to resources the plugin does not own), `permissions.network` (hosts), `permissions.define` (new permissions), `ui.slots` links and `commands`. `server.ts` exports `register(context)`: `context.hooks` accepts only declared extension points, `context.commands.add` only declared commands, `context.cms` reaches only the plugin's resources and granted ones, and `context.fetch` only granted hosts. Plugin pages under `src/plugins/<name>/pages` route like application pages; pages under `pages/dashboard/` share the dashboard layout. They use `c.get('cms').pluginCms('<name>')`. `ui.slots` links fill `dashboard.nav`, `dashboard.taskbar` (the dashboard's bottom status bar) and `site.taskbar` (the bar signed-in users see on the site), each link with an optional `permission`; `ui.ts` can export `slots` with components for `dashboard.overview`, and `blocks` with a component per block type, which the site renders with `{ block }`. Extension points: `cms.resource.before-write` and `after-commit`, the form hooks (`cms.form.*`), `cms.term.before-save`, `cms.comment.before-save` (return `status: 'spam'` to hold a comment) and `cms.menu.before-save`, and the dashboard list filters `cms.dashboard.entry-actions`, `entry-columns` and `bulk-actions`, whose actions are links or plugin commands run with `{ resource, id }` or `{ resource, ids }`. `cms.mail.before-send` sees every email after its HTML layout (Settings → Email) as `{ to, from, subject, text, html, replyTo? }` with `{ kind, plugin, site }`; return it changed, or null to not send it. `to` and `replyTo` of verification, reset, magic-link, invitation and other mail cannot change, and a failing filter leaves the mail as laid out.\n\nA plugin runs only when its schema is migrated and an administrator grants what the manifest requests (`/dashboard/plugins`); an upgrade that requests more needs a new grant, and disabling removes the grants. Builds of CMS applications run the plugin policy lints (`cossack plugins check`): raw RomeQL, the RomeDB client, undeclared network hosts, permissions, resources or hooks, and host secrets fail the build. `cossack <plugin>:<command>` runs a command in the application as a signed-in dashboard user.\n\nDeclare `settings: { label, description?, sections?: [{ id, label, description? }], fields }` for a generated form under Settings → Plugins. Fields support string, text, boolean, integer, number and enum declarations with scalar validation rules. The host assigns namespace `plugin:<name>` and permission `cms:settings`. Sections organize the form without changing stored keys. Administrators can configure a valid disabled plugin without activating it. Inside active server handlers, `context.settings.get(field)` and `all()` return only that plugin's values with defaults; these reads never expose another plugin's values or provide writes. Theme options stay under Appearance → Customize.",
|
|
80
|
+
"examples": [
|
|
81
|
+
{
|
|
82
|
+
"id": "cms-plugins",
|
|
83
|
+
"language": "typescript",
|
|
84
|
+
"source": "import { afterCommit, beforeWrite } from '@cossackframework/cms';\nimport type { PluginContext } from '@cossackframework/cms/server';\n\n/** src/plugins/support-desk/server.ts: called once by the CMS host at boot. */\nexport function register(context: PluginContext): void {\n context.hooks.addFilter(beforeWrite, (draft, { input }) =>\n input.resource === 'support-desk/tickets' && typeof draft.subject === 'string' ? { ...draft, subject: draft.subject.trim() } : draft);\n context.hooks.addAction(afterCommit, async event => {\n // Deliveries can repeat: event.eventId is the idempotency key.\n await context.fetch(`https://hooks.example.com/tickets/${event.id}`, { method: 'POST', headers: { 'idempotency-key': event.eventId } });\n });\n context.commands.add('close-all', async (_input, { principal }) => {\n const tickets = context.cms.resource('support-desk/tickets');\n const page = await tickets.list({ where: { status: 'open' }, limit: 100 }, { principal });\n for (const ticket of page.records) await tickets.update(ticket.id, { status: 'closed' }, { principal, expectedRevision: ticket.rev });\n return page.records.length;\n });\n}\n"
|
|
85
|
+
}
|
|
86
|
+
]
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
"id": "cms-settings",
|
|
90
|
+
"title": "Declare plugin settings and transfer settings as JSON",
|
|
91
|
+
"summary": "Generated plugin forms, scoped server reads, JSON eligibility, authorized document validation, atomic patches, and import/export limits.",
|
|
92
|
+
"imports": [
|
|
93
|
+
"@cossackframework/cms",
|
|
94
|
+
"@cossackframework/cms/server"
|
|
95
|
+
],
|
|
96
|
+
"markdown": "Settings groups store `<group>.<field>` keys in `cms_settings`. `cms.settings.all()` and `get(key)` are server APIs with declared defaults; do not expose their unrestricted result through a browser action. Ordinary group writes use `update(group, values, { principal })` and validate the group's permission and fields.\n\nA plugin declares `settings: { label, description?, sections?: [{ id, label, description? }], fields }` in its manifest. The supported field kinds are string, text, boolean, integer, number and enum. Scalar bounds, patterns, defaults, nullable/required rules and choice labels follow existing field declarations. String fields accept `control: \"color\"` for a hex color picker (`#RGB`, `#RGBA`, `#RRGGBB`, `#RRGGBBAA`) or `control: \"file\"` for a URL input with media selection and upload. File values are root-relative or HTTP(S) URLs. Optional `fileKinds` lists distinct image, video, audio, document or archive kinds and sets the initial library filter; it does not validate pasted URLs. Uploads create media immediately, while Save attaches the URL to settings; clearing or discarding settings never deletes files. Arrays, nested values, executable validators, dynamic sources and resource-only options are unsupported. The host owns its namespace `plugin:<name>`, ownership and permission `cms:settings`; section changes do not rename fields. `PluginContext.settings.get(field)` and `all()` read only the active plugin's settings and return detached values with defaults. Configuration of a valid disabled plugin is allowed in Settings → Plugins and never activates it. Invalid or absent plugins expose no editable declarations. Theme options remain under Appearance → Customize.\n\nHost and module groups explicitly opt into the JSON catalog with `json: true`. Opt in only when generic scalar validation covers every required check and effect. `catalog({ principal })` returns authorized eligible groups. `snapshot({ principal })` reads their effective values, `validateDocument(input, { principal })` checks a patch without writing, `applyDocument(input, { principal })` commits a validated patch atomically, and `exportDocument({ principal })` serializes saved values. The pure `parseSettingsDocument(text)`, `stringifySettingsDocument(document)` and `settingsJsonSchema(groups)` functions share the two-level format and editor declarations.\n\nJSON is `{ \"general\": { \"siteTitle\": \"Acme\" }, \"plugin:newsletter\": { \"enabled\": true } }`. Field leaves are scalar values or explicitly nullable null. Reject duplicate/unknown/unsafe keys, comments, trailing commas, arrays and deeper objects. Missing keys keep their values; null assigns null and never resets. Forms, JSON editing and imports share validation. Each Apply saves every changed value or none, and rejects oversized documents before writing. Exports contain saved authorized effective values, including defaults; importing them pins those defaults. Site-local media, role, category and page references are not remapped. Appearance, theme options, Languages and Permalinks are excluded because their dedicated operations carry extra behavior. This is a settings export, not a site backup. Keep credentials in server configuration.\n\nSettings uses one scrolling page with lazy sections, a nested plugin menu, and global search that filters fields and menu entries with counts. Sidebar selection follows scrolling. The sticky top bar holds search, the code icon and Save changes; Save includes edits hidden by search. The code icon opens JSON with schema completion, import preview and export. Languages and Permalinks retain their dedicated save operations. Selecting a file or opening a preview makes no write. The user reviews changes before Apply. Form/JSON route switches retain drafts; leaving Settings requires saving or discarding changes. Invalid JSON remains until corrected or discarded, and nullable controls preserve null separately from empty text, false and zero.\n\nLimits: a settings document contains at most 2,048 fields and 48 KiB of UTF-8 text. The encoded database operation must fit in 60 KiB. The service uses one atomic write rather than splitting large saves into transactions. Complete reads paginate and retry on sequence changes, with an explicit 20,000-row ceiling. Any exceeded bound raises an error instead of silently truncating export or partially applying a patch. A plugin declares at most 128 fields and 32 sections.",
|
|
97
|
+
"examples": [
|
|
98
|
+
{
|
|
99
|
+
"id": "cms-settings",
|
|
100
|
+
"language": "typescript",
|
|
101
|
+
"source": "import { field, parseSettingsDocument, settingsJsonSchema, type CmsPluginManifest, type Principal, type SettingsGroup } from '@cossackframework/cms';\nimport type { CmsHost, PluginContext } from '@cossackframework/cms/server';\n\nexport const newsletter: CmsPluginManifest = {\n schemaVersion: 1, name: 'newsletter', version: '1.0.0',\n settings: {\n label: 'Newsletter', sections: [{ id: 'delivery', label: 'Delivery' }],\n fields: {\n enabled: { ...field.boolean({ default: false, label: 'Enable delivery' }), section: 'delivery' },\n senderName: { ...field.string({ max: 120, default: '', label: 'Sender name' }), section: 'delivery' },\n accentColor: { ...field.string({ default: '#336699', label: 'Accent color' }), control: 'color' },\n brandAsset: { ...field.string({ default: '', label: 'Brand asset' }), control: 'file', fileKinds: ['image'] },\n },\n },\n commands: [{ name: 'delivery-status', description: 'Read delivery settings.' }],\n};\n\nexport function register(context: PluginContext): void {\n context.commands.add('delivery-status', async () => ({ enabled: await context.settings.get('enabled') }));\n}\n\nexport const shop: SettingsGroup = {\n id: 'shop', label: 'Shop', json: true,\n fields: { currency: field.enum(['usd', 'eur'], { default: 'usd', label: 'Currency' }) },\n};\n\nexport async function applyReviewedSettings(cms: CmsHost, principal: Principal, text: string): Promise<string> {\n const context = { principal };\n const schema = settingsJsonSchema(cms.settings.catalog(context));\n const document = parseSettingsDocument(text);\n cms.settings.validateDocument(document, context);\n // The dashboard previews the patch and requests Apply before calling this operation.\n await cms.settings.applyDocument(document, context);\n void schema;\n return cms.settings.exportDocument(context);\n}\n"
|
|
102
|
+
}
|
|
103
|
+
]
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
"id": "cms-languages",
|
|
107
|
+
"title": "Publish entries in several languages",
|
|
108
|
+
"summary": "One entry per language in a translation group, language URL modes, per-language slugs, translateEntry and batch translations, fields shared across translations, page and dashboard interface languages, and language packs.",
|
|
109
|
+
"imports": [
|
|
110
|
+
"@cossackframework/cms",
|
|
111
|
+
"@cossackframework/cms/server"
|
|
112
|
+
],
|
|
113
|
+
"markdown": "Each entry has one language (`locale`); its translations are separate entries sharing `translationGroup`, the ID of the group's first entry (`translationGroupOf(record)` from `@cossackframework/cms`). Each translation has its own status, slug, SEO, revisions and comments. Do not store per-language values in one record such as `title.fr`.\n\nSettings → Languages stores `languages.default`, `languages.others` (comma-separated codes, at most 19) and `languages.urls`: `hide-default` serves the default language unprefixed (`/about`, `/fr/a-propos`), `all` prefixes every language (`/en/about`, `/` redirects 302 to `/en`). Write them with `cms.saveLanguages({ default, others, urls? }, principal)`; read `cms.languages()` → `{ default, others, all, multilingual, prefixDefault }`. Build URLs with `cms.entryUrls`, `cms.archiveUrl(collection, locale)` and `cms.localePrefix(locale, languages)`, never by hand.\n\nSlugs are unique per language (`field.slug(..., { uniqueBy: ['locale'] })`); a new entry without a locale takes the default. `cms.translateEntry(collection, id, locale, principal)` starts a draft copy or returns the existing translation (`CMS_CONFLICT` when one exists that the user cannot read). `cms.translations(collection, record, context)` returns a Map by language; `cms.translationsOf(collection, records, context)` batches a list by group, then language.\n\nA field declared `translatable: false` (field groups: Same in every language) has one value for an entry and its translations: an update copies a changed value to every translation in the same write and bumps their revisions; a principal who cannot update every translation gets `CMS_FORBIDDEN`. Not for text, rich text, blocks, rows, vectors, slugs, unique fields or searched lists. `repository.updatable(ids, context)` returns the IDs the principal may update.\n\nSite pages call the core `setRequestLocale(locale)`, so `<html lang>` and theme `__()` text follow the content language. The dashboard follows the `cossack_locale` cookie (Profile → Dashboard language), defaulting to the site's default language when a catalog has it. Language packs are plugins with `translations/<code>.json` (application keys) and `translations/<code>/<plugin>.json` (`<plugin>::` keys), and manifest `translations: [codes]`; `cossack lang add <code>` seeds a catalog from literal `__()` keys when the app has no default catalog. Terms and site settings are not translated.",
|
|
114
|
+
"examples": [
|
|
115
|
+
{
|
|
116
|
+
"id": "cms-languages",
|
|
117
|
+
"language": "typescript",
|
|
118
|
+
"source": "import { field, translationGroupOf, type CollectionDefinition, type Principal } from '@cossackframework/cms';\nimport type { CmsHost } from '@cossackframework/cms/server';\n\n/** Products: the price is the same in every language; the tagline is translated. */\nexport const products: CollectionDefinition = {\n name: 'products', label: 'Products', singular: 'Product', path: 'products', features: {},\n fields: {\n price: field.integer({ nullable: true, translatable: false, label: 'Price' }),\n tagline: field.string({ nullable: true, label: 'Tagline' }),\n },\n};\n\nexport async function translateProduct(cms: CmsHost, id: string, principal: Principal) {\n await cms.saveLanguages({ default: 'en', others: ['fr'], urls: 'hide-default' }, principal);\n const french = await cms.translateEntry('products', id, 'fr', principal);\n const source = await cms.resource('cms/products').get(id, { principal });\n const byLanguage = source ? await cms.translations(cms.collection('products'), source, { principal }) : new Map();\n const urls = await cms.entryUrls(cms.collection('products'), [...byLanguage.values()]);\n return { group: translationGroupOf(french), french: urls.get(french.id) };\n}\n"
|
|
119
|
+
}
|
|
120
|
+
]
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
"id": "cms-auth-and-stores",
|
|
124
|
+
"title": "Use CMS auth, sessions and ledgers",
|
|
125
|
+
"summary": "The scaffolded src/auth.ts runs @cossackframework/auth on CMS users and RomeDB sessions; createCmsAuth() does the same for hand-written apps, and the host provides the session bag and ledgers.",
|
|
126
|
+
"imports": [
|
|
127
|
+
"@cossackframework/cms/server"
|
|
128
|
+
],
|
|
129
|
+
"markdown": "With the `cms` feature, the scaffold renders the shared `auth` and `dashboard` pages over CMS storage: `src/auth.ts` exports the same functions as the database variant (`loginUser`, `registerUser`, `requestPasswordReset`, `resetPassword`, `listUserSessions`, …), backed by `cms.users` and `cms.authSessions`. Starting a session records the user's `lastSignInAt`, which outlives the session; `sessionsOf`, `revokeSessionOf` and `revokeSessionsOf` serve the user screen's Sessions tab, and `createApiToken`, `listApiTokens` and `revokeApiToken` its Application passwords tab; only the user and administrators see them (`canManageAccess`). An application password acts as its user, so give an integration its own user with a narrow role. Registration follows the General settings' \"Anyone can register\" and default role; reset tokens are stored as SHA-256 hashes and one request can use each.\n\n`createCmsAuth(cms)` returns the auth middleware, a session manager on the `cms_auth_sessions` table (keyed by token, so rotation is one conditional update and exactly one concurrent rotation wins), `signIn`, `signOut`, a realtime descriptor provider whose public reference survives rotation while the fingerprint does not, and `principal(c)` for the request. Accounts and members live in relational tables. `cms.accounts` (`cms_accounts`, on the network database, the main site's) is who can sign in: email, password hash (`@cossackframework/auth`'s hasher, `cms.accounts.verifier`), status, reset tokens and the network role; sessions, second factors and application passwords belong to the account. `cms.users` (`cms_users`) are the site's members under the account's ID, with the account's name, email, avatar and status copied in and the site's roles, slug and meta: it creates (an account and its membership), lists, searches, updates (profile changes go to the account first) and removes members, manages roles, and `resolve(id)` returns the member with its principal, or null unless the account is active and a member. An account with `networkRole: 'network_admin'` (`NETWORK_ADMIN`, `isNetworkAdmin(principal)`) also acts with `*`; setup makes the first account one, sites cannot define a role with that ID, and the last active network admin cannot be disabled, demoted or deleted. `createCMS({ db, network })` puts accounts on another database; `network` defaults to `db`. `DEFAULT_ROLES` are Administrator, Editor, Author and Subscriber.\n\n`cms.sessions` is the framework session bag with one row per key, so concurrent writes to different keys never overwrite each other. `cms.oauthStates` consumes OAuth state with one conditional delete. `cms.jobs()` and `cms.notifications()` are the core RomeQL ledgers on RomeDB. `FileService` keeps bytes in Cossack object storage and ownership in RomeDB, with a `sweep()` that finishes or cleans up interrupted uploads and deletes.\n\n`cms:users` manages accounts and `cms:roles` defines roles and chooses users' roles; the dashboard lets a user manager without `cms:roles` add users only with the default role and keeps accounts that can manage roles out of its reach. `cms.uploadAvatar(userId, file, { principal })` stores a still or animated profile picture (PNG, JPEG, GIF, WebP, AVIF; 5 MB) in the media library for the user themself or a user manager, sets it on the user and returns its URL.",
|
|
130
|
+
"examples": [
|
|
131
|
+
{
|
|
132
|
+
"id": "cms-auth-and-stores",
|
|
133
|
+
"language": "typescript",
|
|
134
|
+
"source": "import { Hono } from 'hono';\nimport { createRomeDB, MemoryPendingWriteStore } from '@cossackframework/romedb';\nimport { createCMS, createCmsAuth } from '@cossackframework/cms/server';\n\nconst db = createRomeDB({ url: 'http://127.0.0.1:4321', token: 'local-service-token', pending: new MemoryPendingWriteStore() });\nconst cms = createCMS({ db });\nconst kit = createCmsAuth(cms, { secure: false });\n\nexport const app = new Hono();\napp.use('*', kit.auth.middleware);\napp.post('/sign-in', async c => {\n const form = await c.req.formData();\n const signedIn = await kit.signIn(String(form.get('email')), String(form.get('password')), c);\n if (!signedIn) return c.text('Wrong email or password.', 401);\n signedIn.headers.forEach((value, name) => c.header(name, value, { append: true }));\n return c.redirect('/');\n});\napp.get('/me', c => c.json(kit.principal(c)));\n// The framework session bag, job and notification ledgers on RomeDB:\nexport const stores = { sessions: cms.sessions, jobs: cms.jobs(), notifications: cms.notifications() };\n"
|
|
135
|
+
}
|
|
136
|
+
]
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
"id": "cms-publishing",
|
|
140
|
+
"title": "Schedule, preview, revise, redirect, translate and moderate CMS content",
|
|
141
|
+
"summary": "Scheduled entries and maintenance publishing, preview links, autosaves, revision restore and diffs, automatic and managed redirects, application passwords, signed webhooks, comments, patterns, languages and image variants on the CMS host.",
|
|
142
|
+
"imports": [
|
|
143
|
+
"@cossackframework/cms",
|
|
144
|
+
"@cossackframework/cms/server"
|
|
145
|
+
],
|
|
146
|
+
"markdown": "**Scheduling.** Saving `published` with a future `publishedAt` stores `scheduled`; `cms.runSchedule()` (run by maintenance every minute) publishes due entries as `system:scheduler`, so outbox events and webhooks fire then. `pending` means pending review. Visitors read `published` only.\n\n**Previews and autosave.** `cms.createPreviewLink(resource, id, principal)` returns a 7-day token stored as its SHA-256; `cms.previewByToken(token)` reads the entry whatever its status, and `revokePreviewLinks` ends them. `cms.autosave(resource, id | 'new', principal, values)`, `latestAutosave` and `discardAutosave` keep one autosave per user and entry.\n\n**Revisions.** `repository.revision(id, n)`, `repository.restore(id, n, { expectedRevision })` (keeps status, publication time, slug, nesting and language) and `compareRecords(fields, before, after)` / `diffWords(a, b)` for word-level diffs.\n\n**Redirects.** When a published entry's URL changes, the update's batch records a 301 from the old URL, retargets redirects to it and drops one from the new URL; path changes of collections and taxonomies add prefix redirects (`/old/*` to `/new/*`). `cms.redirects.match(path)` serves paths without content; `save`, `list`, `delete` and `hit` manage them. Statuses: 301, 302, 307, 308 and 410.\n\n**API and webhooks.** `cms.apiTokens.create(userId, { name, scope })` returns `cms_<id>.<secret>` once; `cms.tokenPrincipal(token)` resolves it (read-only tokens may only GET). `cms.webhooks.save({ name, url, events, collections })` subscribes to `entry.created`, `entry.updated`, `entry.published`, `entry.unpublished` and `entry.deleted`; deliveries are queued from the outbox and sent by `cms.webhooks.dispatch()` with `X-Cossack-Signature: sha256=` HMAC of `<timestamp>.<body>` (check with `verifyWebhookSignature`), retried over six attempts.\n\n**Comments.** `cms.postComment(input, { principal, ip })` applies Settings → Discussion (sign-in, name and email, closing after N days, thread depth, moderation of all or first-time commenters, links, disallowed words) and a 15-second throttle per address; `cms.moderateComments(ids, status | 'delete', principal)` needs `cms:comments`.\n\n**Patterns and languages.** The built-in `patterns` collection holds reusable blocks; a `core/pattern` block references a synced one. `cms.saveLanguages({ default, others }, principal)` sets the site's languages; other languages' URLs get a `/<code>` prefix from `entryUrls`, `cms.translations(collection, record)` maps languages to entries and `cms.translateEntry(collection, id, locale, principal)` starts a draft translation.\n\n**Images.** Pass `images: ImageTransformer` (the Images binding on Workers, sharp on Node) to `createCMS`; `cms.files.variant(id, { width, height, accept })` makes and keeps resized AVIF/WebP variants, `setEdits(id, { crop, focus })` crops and sets the focal point, and `imageSrcset(file)` lists variants for `srcset`.\n\n**Sign-in security.** `cms.security` keeps authenticator secrets (`startTotp`, `confirmTotp`, `verifyCode`), recovery codes, passkeys and short-lived challenges for pending sign-ins.",
|
|
147
|
+
"examples": [
|
|
148
|
+
{
|
|
149
|
+
"id": "cms-publishing",
|
|
150
|
+
"language": "typescript",
|
|
151
|
+
"source": "import { createRomeDB, MemoryPendingWriteStore } from '@cossackframework/romedb';\nimport { contentModule, createCMS, userPrincipal } from '@cossackframework/cms/server';\n\nconst db = createRomeDB({ url: 'http://127.0.0.1:4321', token: 'local-service-token', pending: new MemoryPendingWriteStore() });\nconst cms = createCMS({ db, modules: [contentModule] });\nconst editor = userPrincipal('editor-1', ['editor'], ['cms:dashboard', 'cms/*']);\n\nexport async function launchTomorrow(): Promise<string> {\n const tomorrow = Date.now() + 24 * 60 * 60 * 1000;\n const post = await cms.resource('cms/posts').create({ title: 'Launch day', status: 'published', publishedAt: tomorrow }, { principal: editor });\n // post.status is 'scheduled'; maintenance publishes it tomorrow.\n const link = await cms.createPreviewLink('cms/posts', post.id, editor);\n await cms.webhooks.save({ name: 'Rebuild', url: 'https://api.example.com/hooks/build', events: ['entry.published'], collections: ['posts'] });\n return `/preview/posts/${post.id}?token=${link.token}`;\n}\n\nexport async function maintenance(): Promise<void> {\n await cms.runSchedule();\n await cms.outbox.dispatch();\n await cms.webhooks.dispatch();\n}\n"
|
|
152
|
+
}
|
|
153
|
+
]
|
|
154
|
+
},
|
|
155
|
+
{
|
|
156
|
+
"id": "cms-forms",
|
|
157
|
+
"title": "Build forms from blocks and handle their submissions",
|
|
158
|
+
"summary": "The forms collection, input blocks with conditional logic, per-form submission tables, cms.forms.submit with spam checks and validation hooks, notifications with merge tags, webhooks, and handling and exporting submissions.",
|
|
159
|
+
"imports": [
|
|
160
|
+
"@cossackframework/cms",
|
|
161
|
+
"@cossackframework/cms/server"
|
|
162
|
+
],
|
|
163
|
+
"markdown": "**Model.** A form is an entry of the built-in `forms` collection (`formsModule`): `title`, `slug` (names the form on the site and in the API), `enabled`, `body` (a blocks field with `form: true`), `settings` (`FORM_SETTINGS`: submit label, a Markdown message or a redirect, closed message, `limit`, `opensAt`, `closesAt`, `requireSignIn`, `oncePerUser`, `oncePerEmail`, `store`, `recordIp`, `turnstile`) and `notifications` (`{ rules: NotificationRule[] }`, at most 10). Inputs are blocks whose declaration has `input: { kind }` (`string`, `text`, `email`, `url`, `phone`, `number`, `boolean`, `date`, `choice`, `choices`, `rows`, `file`); `FORM_BLOCKS` ships `form/text`, `form/email`, `form/url`, `form/phone`, `form/textarea`, `form/number`, `form/date`, `form/select`, `form/radio`, `form/checkboxes`, `form/checkbox`, `form/consent`, `form/hidden`, `form/file` and `form/repeater` (kind `rows`: a row of inputs filled in once per passenger or item, one level deep, at most `FORM_ROW_LIMIT` rows; `formInputs()` lists the top level with a repeater's `inputs` nested, a row's value is `FormRow` with an `_id`, errors are keyed `repeater.<row id>.<input>`, posts name them `repeater[row id][input]`, and the site adds and removes rows with or without its script). The text, email, URL, phone, paragraph, number and date inputs take `multiple` (`MULTIPLE_INPUT_KINDS`) with `minItems`, `maxItems` (at most `FORM_ITEM_LIMIT`, 50) and `addLabel`: the value is a list of the kind's values, items post under the input's name repeated, item errors are keyed `<input>.<position>`, and the site adds and removes items with or without its script. `form/file` takes uploads: `accept` (extensions or types such as `.pdf, image/*`; a known extension decides the type, `acceptsFile`), `maxSize` (MB, at most `FORM_FILE_MAX_MB`, 10), `multipleFiles` and `maxFiles` (at most `FORM_FILE_LIMIT`, 10), at most `FORM_UPLOAD_LIMIT_MB` (25) a submission, never in a repeater, only on forms that keep submissions; the page posts multipart. Its value is a list of `FormFile` (`{ id?, name, size, type }`, metadata only): hooks see the posted files' metadata, and the host stores the files once the submission is valid, checking each one's content against its type (`FileService.stashPrivate`), as private files under `cms/private/forms/<form>/<submission>/` that the media library, `/media/` and media references never resolve; the submission's batch makes them ready. `cms.forms.file(form, submission, file, principal)` (and `GET /api/cms/forms/<form>/submissions/<id>/files/<file>`) serves one to `cms:submissions`; `delete` and the form's deletion remove them; emails, CSV and webhooks list names and sizes. Plugins build their own with `inputFields(own)`. Input blocks go only in a `form: true` field; an input without `name` takes one from its label in camel case. Containers lay inputs out. Any block in a form can carry `when: { action?, match?, rules: [{ field, op, value? }] }` with `is`, `isNot`, `contains`, `empty`, `notEmpty`, `gt`, `lt` and `in`; `formVisibility` evaluates it, hidden inputs counting as empty. `validateSubmission(blocks, types, raw)` reads posted values by kind, applies conditions and checks the shown inputs; the browser and the host run the same code.\n\n**Storage.** Each form's submissions are a schemaless resource `cms/form_<form id>` (`submissionResource`) in their own table `r__cms__form_<id>`, never a shared one: one field per input, plus `status` (`new`, `read`, `spam`, `trash`), `note` and `meta` (`ip`, `userAgent`, `referrer`, `page`, `locale`); the sender is `owner`. `cms.forms` keeps the table in step with the form's inputs (additive) and drops it when the form is deleted. Handling needs `cms:submissions` (Editors by default).\n\n**Submitting.** `cms.forms.submit(slugOrId, raw, { principal, ip, userAgent, page, origin, trap, startedAt, botCheck })` checks the schedule, the limit (kept submissions), sign-in, the bot check, one post per address and form every five seconds, then `validateSubmission`, `cms.form.validate` (add errors), `cms.form.before-submit` (change values) and the once rules. The trap field or a post within two seconds of rendering is kept as `spam` and answered as usual. One batch writes the record, a receipt and a `form.submitted` outbox event; `store: false` writes the event alone. The answer is `{ form, submission, confirmation }` after `cms.form.confirmation`; merge tags in the message are filled with Markdown-escaped answers.\n\n**After a submission.** The outbox runs `cms.form.submitted` (`FormSubmittedEvent`, key work on `eventId`): the host sends each notification rule through `createCMS({ mail, mailFrom })` once per event, rule and address, after `cms.form.notification` (return null to skip), and queues `form.submitted` webhooks. Merge tags: `{field:name}`, `{all_fields}`, `{form:title}`, `{submission:id}`, `{submission:url}`, `{submission:date}`, `{user:email}`, `{user:name}`, `{site:title}`, `{site:url}`, `{admin_email}` (`MERGE_TAGS`, `renderMergeTags`).\n\n**Handling.** `cms.forms.list(form, { status, search, after, limit }, principal)`, `counts`, `inboxCounts`, `submission`, `setStatus`, `delete`, `setNote` and `csv` (an async iterator of CSV text with formula cells defused); `cms.forms.maintain()` empties old trash. The scaffold places forms with the `core/form` block (`FormView` on `RenderedBlock.form`, `InputView` on each input), posts to `POST /api/cms/forms/<slug>` with or without JavaScript, and adds Forms, the submissions inbox and CSV export to the dashboard.",
|
|
164
|
+
"examples": [
|
|
165
|
+
{
|
|
166
|
+
"id": "cms-forms",
|
|
167
|
+
"language": "typescript",
|
|
168
|
+
"source": "import { createRomeDB, MemoryPendingWriteStore } from '@cossackframework/romedb';\nimport { createHookRegistry } from '@cossackframework/core/hooks';\nimport { ANONYMOUS, contentModule, createCMS, formsModule, formSubmitted, formValidate, userPrincipal, type Block } from '@cossackframework/cms/server';\n\n// A plugin's or the application's own rules, as Gravity Forms' hooks.\nconst hooks = createHookRegistry();\nhooks.addFilter(formValidate, (errors, { input }) => typeof input.values.email === 'string' && input.values.email.endsWith('@example.org')\n ? { ...errors, email: 'Use your work address.' } : errors, { plugin: 'app' });\nhooks.addAction(formSubmitted, async event => {\n // Send the lead to a CRM, keyed by event.eventId: deliveries can repeat.\n console.log(event.form.slug, event.submission.values);\n}, { plugin: 'app' });\n\nconst db = createRomeDB({ url: 'http://127.0.0.1:4321', token: 'local-service-token', pending: new MemoryPendingWriteStore() });\nconst cms = createCMS({\n db, modules: [contentModule, formsModule], hooks, mailFrom: 'site@example.com',\n mail: { async send(message) { console.log('mail to', message.to, message.subject); } },\n});\nconst editor = userPrincipal('editor-1', ['editor'], ['cms:dashboard', 'cms:submissions', 'cms/*']);\n\nconst body: Block[] = [\n { _id: 'n', type: 'form/text', data: { label: 'Your name', required: true } },\n { _id: 'e', type: 'form/email', data: { label: 'Email', name: 'email', required: true } },\n { _id: 'c', type: 'form/checkbox', data: { label: 'Call me', name: 'callMe' } },\n { _id: 'p', type: 'form/phone', data: { label: 'Phone', name: 'phone', required: true }, when: { rules: [{ field: 'callMe', op: 'is', value: 'true' }] } },\n];\n\nexport async function contactForm(): Promise<string> {\n await cms.resource('cms/forms').create({\n title: 'Contact', body,\n notifications: { rules: [{ id: 'admin', label: 'Admin', to: '{admin_email}', subject: 'New message from {field:yourName}', body: '{all_fields}' }] },\n }, { principal: editor });\n const { submission } = await cms.forms.submit('contact', { yourName: 'Ada', email: 'ada@example.com' }, { principal: ANONYMOUS, ip: '203.0.113.7', page: '/contact' });\n await cms.outbox.dispatch();\n const form = await cms.forms.get('contact');\n let csv = '';\n if (form) for await (const chunk of cms.forms.csv(form, {}, editor)) csv += chunk;\n return `${submission.id}\\n${csv}`;\n}\n"
|
|
169
|
+
}
|
|
170
|
+
]
|
|
171
|
+
},
|
|
172
|
+
{
|
|
173
|
+
"id": "cms-field-groups",
|
|
174
|
+
"title": "Build field groups: meta boxes from blocks, with repeaters",
|
|
175
|
+
"summary": "Field groups lay typed fields out with blocks and attach to collections, taxonomies, users and menu items; field blocks compile to declarations, rows fields are repeaters indexed on their array paths, a Multiple field block holds several values of its kind, conditions hide fields on write, and targets without documents carry meta.",
|
|
176
|
+
"imports": [
|
|
177
|
+
"@cossackframework/cms",
|
|
178
|
+
"@cossackframework/cms/server"
|
|
179
|
+
],
|
|
180
|
+
"markdown": "**Field groups are meta boxes built from blocks.** A `FieldGroup` is `{ id, title, description?, placement?, order?, targets, blocks, plugin? }` (`placement` is where the box starts in an entry editor whose collection has no `editor` layout; `plugin` tags a group a plugin's manifest ships, read-only in the dashboard): `targets` lists where its box shows (`{ kind: 'collection', name, order? }`, `{ kind: 'taxonomy', name, order? }`, `{ kind: 'users', order? }`, `{ kind: 'menus', order? }`; a target's `order` places the box among that target's groups, `groupsForTarget(groups, target)` sorts them, and the group's own `order` is the fallback), and `blocks` is a tree of *field blocks* (`field/text`, `field/number`, `field/choice`, `field/media`, `field/reference`, `field/blocks`, `field/repeater`, …; `FIELD_BLOCKS`, one per `FIELD_BLOCK_TYPES` entry; every kind but Yes/no, Blocks and Repeater takes `multiple`, `minItems`, `maxItems` and `addLabel`, so a Single line with Multiple on is a list of strings and an Image a gallery) laid out with the core layout blocks (`FIELD_GROUP_LAYOUT`: group, columns, grid, tabs, heading, paragraph as a note, divider). A field block's data is the builder's field settings: `label`, `name` (from the label when empty, as `inputName`), `description`, `required`, `width`, and per kind `max`, `min`, `unique`, `index` (filterable), `search`, `choices`, `defaultValue`, `target`, `blocks`. `validateBlocks(blocks, types, { fieldGroup: { scope } })` checks a group's tree: only field and layout blocks, names distinct across the group (rows included) and never one of `scope` (the target's own fields), conditions (`Block.when`, the form builder's rules) naming fields in reach.\n\n**Groups compile to declarations.** `fieldGroupDeclarations(blocks, types)` turns the tree into `{ [name]: FieldDeclaration }`: layout contributes what it holds, a repeater becomes a `rows` field whose `fields` are its children. The host merges a target's groups into its resource (`cms.resourceById('cms/products').fields` holds the group's fields), so storage, the API, search and themes see fields and never layout. Values are stored flat by name. A collection's fields are the groups attached to it: the collection manager attaches, orders and detaches them (`saveCollection(definition, principal, { groups })`, `withTarget(group, target, attached, order)`), and `/dashboard/field-groups/new?collection=<name>` makes a group already attached. A group field named as a core field or a feature cannot attach. Collections stored by older versions with a `layout` are converted on load into a group named `<name>-fields`.\n\n**Rows.** `field.rows({ name: field.string({ required: true }), notes: field.rows({ … }) }, { max: 20 })` declares a repeater: a list of at most `max` rows (`ROW_LIMITS`), each an object of its fields with an `_id` the host assigns when missing (`withRowIds`); rows nest without limit. `validateValue` walks rows; `unique` on a row field holds within the record (`rowUniqueProblem`); `search` on a row field adds its text to the record's search text (`rowsPlain`, `rowsSearchable`). A row field with `index` or `unique` gets a RomeDB array index on its path into the rows: `indexedRowPaths(fields)` lists `['specs', 'name']`, `rowIndexPath` turns it into `specs.*.name`, and the index holds the distinct values at that path across every row. `repository.list({ where: { 'specs.name': { contains: 'Weight' } } })` seeks through it (`indexedRowField(fields, ['specs', 'name'])` is the row field it checks values against). Path indexes need RomeDB 0.2.11 or later; on an older engine the schema planner blocks the collection. Ranges and sorting on row fields are not offered.\n\n**Conditions on fields.** `fieldVisibility(blocks, types, values, scope)` returns the `hiddenKey`s of the blocks the conditions hide and the values with hidden fields cleared, rows included: a row's field sees the row's values over the rows above over the top level, and hidden fields count as empty. The repository runs it on every write with the record as it would be, so a hidden required field is not required and a hidden value is stored as null; editors run it on each change.\n\n**Targets without documents.** Terms, users and menu items carry `meta`: `taxonomies.create(taxonomy, { name, meta })`, `users.update(id, { meta })` and `MenuItem.meta` are checked against the target's groups by `metaProblems(fields, meta, next)` through the host (`fieldVisibility` included); `TermShape.meta`, `CmsUser.meta` and `MenuItemView.meta` return them. Host step 10 adds `cms_field_groups` and the `meta` columns.\n\n**Host API.** `cms.fieldGroups.all()`, `.get(id)`, `.forTarget(target)`; `cms.fieldGroupsFor(target)` (the loaded groups); `cms.saveFieldGroup(group, principal)` (checks the tree against the block types and each target's fields, keeps names distinct across a target's groups, stores the group and plans the targets' schemas: new indexes come, dropped fields keep their values); `cms.deleteFieldGroup(id, principal)`. Permission `cms:collections`. The dashboard's `/dashboard/field-groups` screens, the collection manager's Field groups section, the entry editor's boxes with repeater rows, the term editor and the menu item's Fields tab use them; the content API filters with `?filter[specs.name]=Weight`. A plugin's manifest ships groups under `fieldGroups` (IDs `<plugin>-…`): `grantPlugin` stores them tagged with the plugin and plans their targets; `saveFieldGroup` and `deleteFieldGroup` refuse them, the collection manager cannot detach them, and they stay with their values while the plugin is inactive.",
|
|
181
|
+
"examples": [
|
|
182
|
+
{
|
|
183
|
+
"id": "cms-field-groups",
|
|
184
|
+
"language": "typescript",
|
|
185
|
+
"source": "import { createRomeDB, MemoryPendingWriteStore } from '@cossackframework/romedb';\nimport { contentModule, createCMS, fieldGroupDeclarations, indexedRowPaths, rowIndexPath, fieldGroupProblems, fieldVisibility, userPrincipal, type Block, type FieldGroup } from '@cossackframework/cms/server';\n\nconst fieldBlock = (id: string, kind: string, data: { [key: string]: unknown }, extra: Partial<Block> = {}): Block => ({ _id: id, type: `field/${kind}`, data: { label: id, ...data }, ...extra });\n\n// Specifications: a repeater with an indexed name, a kind, and a URL shown for links.\nconst specifications: FieldGroup = {\n id: 'specifications', title: 'Specifications', targets: [{ kind: 'collection', name: 'products' }],\n blocks: [\n { _id: 'h', type: 'core/heading', data: { text: 'Specifications' } },\n fieldBlock('specs', 'repeater', { name: 'specs', label: 'Specifications', max: 20, summary: 'name' }, { children: [\n fieldBlock('name', 'text', { name: 'name', label: 'Name', required: true, index: true, search: true }),\n fieldBlock('kind', 'choice', { name: 'kind', label: 'Kind', choices: ['text', 'link'] }),\n fieldBlock('url', 'text', { name: 'url', label: 'URL' }, { when: { rules: [{ field: 'kind', op: 'is', value: 'link' }] } }),\n ] }),\n ],\n};\n\nconst db = createRomeDB({ url: 'http://127.0.0.1:4321', token: 'token', pending: new MemoryPendingWriteStore() });\nconst cms = createCMS({ db, modules: [contentModule] });\nconst admin = userPrincipal('admin-1', ['admin'], ['*']);\n\nasync function main(): Promise<void> {\n await cms.ready();\n // Pure checks before saving: the tree, the compiled fields, the row index paths.\n const { problems, fields } = fieldGroupProblems(specifications, cms.blockTypes, ['title', 'status']);\n if (problems.length) throw new Error(problems.join(' '));\n console.log(Object.keys(fields), indexedRowPaths(fields).map(rowIndexPath)); // ['specs'], ['specs.*.name']\n console.log(fieldGroupDeclarations(specifications.blocks, cms.blockTypes).specs?.kind); // 'rows'\n const hidden = fieldVisibility(specifications.blocks, cms.blockTypes, { specs: [{ _id: 'r1', kind: 'text', url: 'gone' }] });\n console.log([...hidden.hidden], hidden.values); // ['specs=r1/url'], { specs: [{ _id: 'r1', kind: 'text' }] }\n\n await cms.saveFieldGroup(specifications, admin);\n const products = cms.resource('cms/products');\n const skates = await products.create({ title: 'Rocket skates', specs: [{ name: 'Weight', kind: 'text' }, { name: 'Site', kind: 'link', url: 'https://example.com' }] }, { principal: admin });\n console.log((skates.specs as { _id: string }[]).map(row => row._id));\n const found = await products.list({ where: { 'specs.name': { contains: 'Weight' } } }, { principal: admin });\n console.log(found.records.map(record => record.title)); // ['Rocket skates']\n await cms.taxonomies.create('categories', { name: 'Skates', meta: {} }, { principal: admin });\n}\n\nvoid main();\n"
|
|
186
|
+
}
|
|
187
|
+
]
|
|
188
|
+
},
|
|
189
|
+
{
|
|
190
|
+
"id": "cms-multisite",
|
|
191
|
+
"title": "Run a network of sites",
|
|
192
|
+
"summary": "CmsNetwork resolves a request's host to a site with its own RomeDB database, shares accounts from the main (network) database, hands sign-ins to sites as child sessions, and creates, archives and deletes sites.",
|
|
193
|
+
"imports": [
|
|
194
|
+
"@cossackframework/cms/server"
|
|
195
|
+
],
|
|
196
|
+
"markdown": "Every CMS install is a network of one site. The main database (the network database) holds the accounts (`cms_accounts`, `cms.accounts`) and the site registry (`cms_sites`, `cms_site_domains`); each added site has its own database with the same host schema, its own members (`cms_users`, `cms.users`), roles, content and settings. No query spans two databases.\n\n`new CmsNetwork({ db, host, open, directory, networkHost })` builds one per isolate: `host(site, db)` must call `createCMS({ db, network, site: site.id, sessionsEnded: ended => network.endSessions(ended) })`; `open(site)` opens a site's database by `site.database`; `directory` (`organizationDatabases` for a RomeDB Cloud organization or `romedb serve --directory`, `fileDatabases` on Node) creates and deletes them. `network.resolve(host)` returns `site`, `redirect` (an alias to its primary domain), `archived` or `missing`; while the network has one site every host serves it. `network.hostOf(site)` keeps 32 hosts per isolate. Media of an added site sits under `sites/<id>/` (`prefixedStorage`).\n\nSign-in happens only on the network host. A site sends visitors to the network's `/auth/handoff`; the network issues a one-use code (`network.handoffs`), and the site trades it for a child session in its own database that carries the network role, so site requests read only the site's database. Ending a network session (sign-out, password reset, suspension, new network role, deleting the account) ends its child sessions through `sessionsEnded`. A network admin (`NETWORK_ADMIN`, `isNetworkAdmin`) acts with `*` on every site; setup makes the first account one, and the last cannot be removed.\n\nNetwork admins manage sites: `createSite({ name, host, admin, starter?, language? }, { principal })` records each step (database, schema, roles and settings with the network's defaults, first administrator) and resumes after a failure; `addDomain`, `checkDomain` (the domain's `/.well-known/cossack-site` must answer with the site ID before it becomes primary), `removeDomain`; `setSiteStatus` (archive, delete, restore) and `purgeDeleted` (30 days after deletion); `deleteAccount` removes an account from every site, then the account. `setPluginState(name, 'network' | 'available' | 'hidden', { principal })` runs a plugin on every site with the grants approved then (sites migrate it as they load and cannot disable it), leaves it to each site, or hides it; `setThemeState(name, 'available' | 'hidden')` controls which themes sites may choose (`host.availableThemes()`). `saveSettings({ defaultTheme, defaultPlugins, defaultLanguage })` sets what new sites start with. The CMS app's `/dashboard/network` pages use these. See docs/cms/multisite.md.",
|
|
197
|
+
"examples": [
|
|
198
|
+
{
|
|
199
|
+
"id": "cms-multisite",
|
|
200
|
+
"language": "typescript",
|
|
201
|
+
"source": "import { createRomeDB, MemoryPendingWriteStore, organizationDatabases } from '@cossackframework/romedb';\nimport { CmsNetwork, createCMS, type Principal } from '@cossackframework/cms/server';\n\nconst pending = new MemoryPendingWriteStore();\nconst organization = organizationDatabases({ url: 'https://cloud.romedb.com/v1/organizations/0b6c1a43-5a2e-4f0e-9b37-2f1e8c0d4a11', token: 'organization-key' });\nconst db = createRomeDB({ url: 'http://127.0.0.1:4321', token: 'local-service-token', pending });\n\n// The main database holds the accounts and the site registry; each added site has its own.\nconst network: CmsNetwork = new CmsNetwork({\n db,\n networkHost: () => 'example.com',\n directory: organization,\n open: site => createRomeDB({ url: organization.url(site.database), token: 'organization-key', pending }),\n host: (site, siteDb) => createCMS({ db: siteDb, network: db, site: site.id, sessionsEnded: ended => network.endSessions(ended) }),\n});\n\nexport async function hostFor(hostName: string) {\n const found = await network.resolve(hostName);\n return found.kind === 'site' ? network.hostOf(found.site) : null;\n}\n\nexport function addBlog(principal: Principal, admin: string) {\n return network.createSite({ name: 'Blog', host: 'blog.example.com', admin }, { principal });\n}\n"
|
|
202
|
+
}
|
|
203
|
+
]
|
|
204
|
+
},
|
|
205
|
+
{
|
|
206
|
+
"id": "cms-collab",
|
|
207
|
+
"title": "Edit an entry together",
|
|
208
|
+
"summary": "A saved entry has a room (EntryRoom, a realtime component scoped to the entry) that applies every editor’s change in order and keeps the shared draft in cms_drafts; three client-safe rules converge the editors: last-write-wins scalars with PendingKeys, block tree ops by ID (treeOps, applyTreeOp, treeHash) and prosemirror-collab for rich text (StepLog).",
|
|
209
|
+
"imports": [
|
|
210
|
+
"@cossackframework/cms",
|
|
211
|
+
"@cossackframework/cms/server"
|
|
212
|
+
],
|
|
213
|
+
"markdown": "The room is the authority: its action queue orders every change, so no CRDT is needed. Scalars: an editor applies its own change at once, sends it, and ignores remote values of that field while `PendingKeys` has one of its own in flight (the room applied that one later). Blocks: `treeOps(field, before, after, { skip })` turns two trees into inserts anchored on the sibling before, moves, removes and patches of one key; the room applies each with `applyTreeOp` (dropping what no longer applies) and answers the tree’s `treeHash`, which an editor compares to its own before asking for the room’s tree. Rich text: `StepLog` is the central authority’s version and bounded step log per document (`richTextPath(field, { id, key })` names a block’s document); the browser side is `prosemirror-collab`. `groupPeers`, `livePeers`, `participantColor` and `checkPresence` shape presence. `cms.drafts` (`CmsDrafts`) stores one draft row per entry, capped at what an entry can hold and still be saved in one RomeDB request (`saveBytes`), and names who is editing (`editing`, `editors`). Notes ride the same room: `cms.notes` (`CmsNotes`) keeps review threads in `cms_notes` and `cms_note_mentions`, anchored by `formatNoteTarget` (entry, field:<name>, block:<field>:<id>, text:<richTextPath> with a range and a quote), and `EntryRoom.note` broadcasts each change; see docs/cms/notes.md. See docs/cms/collaboration.md and specs/cms-collaboration.md.",
|
|
214
|
+
"examples": [
|
|
215
|
+
{
|
|
216
|
+
"id": "cms-collab-tree-ops",
|
|
217
|
+
"language": "typescript",
|
|
218
|
+
"source": "import { applyTreeOp, treeHash, treeOps, type Block } from '@cossackframework/cms';\n\n// An editor moved block b first and changed a's text; the room applies the ops in order and answers its hash.\nconst before: Block[] = [{ _id: 'a', type: 'core/paragraph', data: { text: 'A' } }, { _id: 'b', type: 'core/paragraph', data: { text: 'B' } }];\nconst after: Block[] = [{ _id: 'b', type: 'core/paragraph', data: { text: 'B' } }, { _id: 'a', type: 'core/paragraph', data: { text: 'A!' } }];\nlet tree: readonly Block[] = before;\nfor (const op of treeOps('content', before, after)) {\n const next = applyTreeOp(tree, op);\n if (next) tree = next; // null: the op no longer applies (its block went away)\n}\nconsole.log(treeHash(tree) === treeHash(after)); // true\n"
|
|
219
|
+
}
|
|
220
|
+
]
|
|
221
|
+
},
|
|
222
|
+
{
|
|
223
|
+
"id": "cms-project-layout",
|
|
224
|
+
"title": "Configure a CMS project without copying the CMS",
|
|
225
|
+
"summary": "A project mounts the CMS from the package (package.json#cossack.packages) and holds no copy of it, the sign-in pages and the dashboard included. It configures the CMS in src/cms.config.ts (storage as CmsStorage, resources, modules, options as CmsProjectConfig), changes behaviour with plugins or a child theme, replaces one page with cossack eject, and updates with cossack upgrade.",
|
|
226
|
+
"imports": [
|
|
227
|
+
"@cossackframework/cms",
|
|
228
|
+
"@cossackframework/cms/server",
|
|
229
|
+
"@cossackframework/cms/storage",
|
|
230
|
+
"@cossackframework/cms/storage/cloudflare",
|
|
231
|
+
"@cossackframework/cms/storage/node"
|
|
232
|
+
],
|
|
233
|
+
"markdown": "The CMS's pages, the sign-in pages (`/auth/*`), the dashboard (`/dashboard/*`), their modules (`auth.ts`, the services, the dashboard kit) and the default theme are served from `@cossackframework/cms`. The project names the package in `package.json` (`\"cossack\": { \"packages\": [\"@cossackframework/cms\"] }`) and keeps only: `src/cms.config.ts`; `src/bootstrap/middlewares.ts`, which lists `cmsMiddlewares` from `@cossackframework/cms/app/cms/middlewares` and then the project's own middleware; the entry files (`src/index.ts`, `src/App.ts`, `src/root.ts`, `src/client/entry-client.ts`, `src/stores.client.ts`, `src/style.css`); `src/config/app.ts`, `cache.ts` and `cors.ts`; and its own plugins under `src/plugins/`. Do not look for `src/cms/`, `src/dashboard/`, `src/services/`, `src/auth.ts`, `src/pages/auth/`, `src/pages/dashboard/` or `src/plugins/default-theme/` in a project: they are in the package, under `node_modules/@cossackframework/cms/app/src/`. Code there is replaced by an update; every file in the project is the project's own.\n\n`src/cms.config.ts` exports four values. `storage` is a `CmsStorage`: where the CMS keeps its database, unconfirmed writes, media and resized images. Use `cloudflareStorage` from `@cossackframework/cms/storage/cloudflare` on Workers and `nodeStorage` from `@cossackframework/cms/storage/node` on Node, and replace a member to keep something elsewhere (`{ ...nodeStorage, mediaStorage: env => provider }`). `resources` are code-declared resources (`defineResource`). `modules` are the built-in modules (`contentModule`, `formsModule`). `options` is a `CmsProjectConfig`: an object, or a function of the environment bindings and the site. It may set `reservedPaths`, `blocks`, `settings`, `taxonomies`, the `payments`, `ai`, `purgers` and `mail` providers, `mailFrom`, `files` and `updates`. `reservedPaths` and `purgers` are added to the defaults; every other option replaces its default. An option left out keeps the default.\n\nTo change the CMS, in order of preference: a plugin (resources, hooks, blocks, dashboard pages, commands); `src/cms.config.ts`; a child theme (`\"theme\": { \"extends\": \"default-theme\" }`), which keeps receiving the parent's fixes; and last `cossack eject cms <route|path|plugins/name>`, which copies one page, layout (such as `pages/dashboard/layout.ts`), configuration file or served plugin into the project, where it overrides the package's. A shared module such as `cms/site.ts` or `dashboard/list-table.ts` cannot be ejected. An application file at the same path as a served page overrides it, and the build prints each override.\n\nUpdate with `pnpm cossack upgrade`: it moves the dependencies and installs. A CMS project records no scaffold files (no `.cossack/scaffold.json`, no `.cossack/base/` for them; the recipe is `features` and `template` in `package.json#cossack`), so the upgrade never changes the project's own files: `vite.config.ts` is `cossackApp()` from `cossack/vite`, `src/index.ts` calls `cmsAppOptions`, `cmsScheduled` or `startCmsMaintenance` from `@cossackframework/cms/app/cms/entry`, and the `typecheck` script is `cossack typecheck`. The upgrade merges only ejected copies and plugins; a conflicting file is kept and listed, and `--conflicts=markers` writes both versions. Served code imports project modules only as `@/…`. When a build reports `COSSACK_PACKAGE_HOST_MISSING`, run `cossack upgrade`, which writes the missing module. When it reports `COSSACK_PACKAGE_HOST_OUTDATED`, make the changes the message lists in the project's files, then set `cossack.template` in `package.json` to the version it names.",
|
|
234
|
+
"examples": [
|
|
235
|
+
{
|
|
236
|
+
"id": "cms-project-layout",
|
|
237
|
+
"language": "typescript",
|
|
238
|
+
"source": "// src/cms.config.ts: the project's own CMS configuration.\nimport { contentModule, defineResource, field, formsModule, type ResourceDeclaration } from '@cossackframework/cms';\nimport type { CmsProjectConfig } from '@cossackframework/cms/server';\nimport type { CmsStorage } from '@cossackframework/cms/storage';\nimport { nodeStorage, type NodeStorageBindings } from '@cossackframework/cms/storage/node';\n\n/** The runtime's storage, with media kept in another directory. On Workers, start from cloudflareStorage. */\nexport const storage: CmsStorage<NodeStorageBindings> = {\n ...nodeStorage,\n mediaStorage: env => nodeStorage.mediaStorage({ ...env, MEDIA_DIR: '/var/lib/site/media' }),\n};\n\n/** A code-declared resource, stored in a strict RomeDB collection. */\nconst leads = defineResource({\n name: 'leads',\n label: 'Leads',\n titleField: 'email',\n fields: { email: field.string({ required: true, max: 200 }), note: field.string() },\n});\n\nexport const resources: ResourceDeclaration[] = [leads];\n\nexport const modules = [contentModule, formsModule];\n\n/** Computed per site from the environment bindings; an option left out keeps its default. */\nexport const options: CmsProjectConfig = (env, site) => ({\n // An entry at the site root cannot take these addresses.\n reservedPaths: ['pricing', 'status'],\n mailFrom: typeof env.MAIL_FROM === 'string' ? env.MAIL_FROM : `no-reply@${site.host ?? 'example.com'}`,\n updates: { check: true, channel: 'latest' },\n});\n"
|
|
239
|
+
}
|
|
240
|
+
]
|
|
241
|
+
},
|
|
242
|
+
{
|
|
243
|
+
"id": "cms-updates",
|
|
244
|
+
"title": "Show update notices and request an update",
|
|
245
|
+
"summary": "The CMS asks an update server once a day which version is the latest (checkForUpdate, parseUpdateAnswer, compareVersions, CMS_VERSION), sending its version and channel only. Tools → Updates shows the answer to cms:updates holders, and a button posts a repository_dispatch-shaped request to the project's hook (CMS_UPDATE_HOOK_URL, CMS_UPDATE_HOOK_TOKEN), whose pipeline runs cossack upgrade.",
|
|
246
|
+
"imports": [
|
|
247
|
+
"@cossackframework/cms"
|
|
248
|
+
],
|
|
249
|
+
"markdown": "A running site cannot change its own code, so updates have two parts. The notice: with its scheduled upkeep the site calls `GET <url>?version=<installed>&channel=<channel>` at most once a day and keeps the answer in the network's state. The request carries nothing about the site. `checkForUpdate` never throws: when the server is down or answers nonsense it returns the earlier answer with an `error`. `parseUpdateAnswer` accepts only a valid version newer than the installed one, so a wrong answer shows at most a wrong notice. Configure it with `updates: { check, url, channel }` in `src/cms.config.ts`; `check: false` sends no request. The default server is `https://cms.cossack.dev/update` and answers `{ channel, latest, published, notes, security, hostTemplate?, minimumFrom? }`.\n\nThe button: Tools → Updates is for holders of `PERMISSIONS.manageUpdates` (`cms:updates`) on the main site, and in a network for network administrators only. With `CMS_UPDATE_HOOK_URL` and `CMS_UPDATE_HOOK_TOKEN` in the environment (never in the database), the page posts `{ \"event_type\": \"cossack-update\", \"client_payload\": { \"version\": \"<latest>\" } }` with `Authorization: Bearer <token>`. The version is the stored one; the browser cannot name another. For GitHub the URL is `https://api.github.com/repos/<owner>/<repository>/dispatches`, and `cossack add cms` renders `.github/workflows/cossack-update.yml`, which runs `cossack upgrade --tag <version>`, type-checks, builds, and opens a pull request (or pushes when the repository variable `COSSACK_UPDATE_MODE` is `push`, nothing conflicts and the checks pass). Without a hook the page shows `pnpm cossack upgrade`.\n\nA request stays pending until the site runs the requested version, or for a day. The person confirms a backup first: an update may change the database, and an older build cannot open it afterwards. Code always comes from the package registry through the project's lockfile and pipeline; the update server only informs.",
|
|
250
|
+
"examples": [
|
|
251
|
+
{
|
|
252
|
+
"id": "cms-updates",
|
|
253
|
+
"language": "typescript",
|
|
254
|
+
"source": "import { checkForUpdate, CMS_VERSION, compareVersions, DEFAULT_UPDATES_URL, parseUpdateAnswer, type UpdateCheck } from '@cossackframework/cms';\n\n/** Ask the update server; a failed check keeps the earlier answer. */\nexport async function latest(previous: UpdateCheck | null): Promise<UpdateCheck> {\n return checkForUpdate({ installed: CMS_VERSION, url: DEFAULT_UPDATES_URL, channel: 'latest', now: Date.now(), previous });\n}\n\n/** What a notice may say about an answer from any source. */\nexport function notice(body: unknown): string {\n const answer = parseUpdateAnswer(body, CMS_VERSION);\n if (!answer) return `Version ${CMS_VERSION} is the latest.`;\n const steps = answer.minimumFrom && (compareVersions(CMS_VERSION, answer.minimumFrom) ?? 0) < 0 ? ` Update to ${answer.minimumFrom} first.` : '';\n return `Version ${answer.latest} is available${answer.security ? ' and fixes a security problem' : ''}.${steps}`;\n}\n"
|
|
255
|
+
}
|
|
256
|
+
]
|
|
257
|
+
}
|
|
258
|
+
]
|
|
259
|
+
}
|