@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
|
@@ -0,0 +1,780 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Files: bytes in Cossack object storage (R2 on Workers, S3 or a local directory on Node),
|
|
3
|
+
* ownership and metadata in RomeDB. Upload and delete are recoverable two-phase operations:
|
|
4
|
+
* the metadata row records intent first, and `sweep()` finishes or cleans up interrupted work.
|
|
5
|
+
*/
|
|
6
|
+
import type { StoragePresignedUpload, StorageProvider } from '@cossackframework/core/storage';
|
|
7
|
+
import type { RomeDB, Statement, Value } from '@cossackframework/romedb';
|
|
8
|
+
import { CmsError } from '../errors';
|
|
9
|
+
import { declaredType, imageHasAlpha, imageSize, matchesSignature, MEDIA_FILTER_EXCLUDES, MEDIA_FILTERS, mediaKind, sanitizeSvg, SVG_TYPE, type MediaKind } from '../media';
|
|
10
|
+
import { hasPermission, PERMISSIONS, principalId, type Principal } from '../permissions';
|
|
11
|
+
import { containsPattern } from './users';
|
|
12
|
+
import { IMAGE_WIDTHS, imageEditsProblems, transformable, variantRect, variantWidth, type ImageEdits } from '../images';
|
|
13
|
+
import { FORMAT_TYPES, negotiateFormat, type ImageFormat, type ImageTransformer } from './images';
|
|
14
|
+
import { uuidv7 } from '@cossackframework/core';
|
|
15
|
+
import { readByIds, readPaged } from './budget';
|
|
16
|
+
|
|
17
|
+
export interface CmsFile {
|
|
18
|
+
readonly id: string;
|
|
19
|
+
readonly name: string;
|
|
20
|
+
readonly contentType: string;
|
|
21
|
+
readonly size: number;
|
|
22
|
+
readonly owner: string | null;
|
|
23
|
+
readonly title: string;
|
|
24
|
+
readonly alt: string;
|
|
25
|
+
readonly caption: string;
|
|
26
|
+
readonly description: string;
|
|
27
|
+
readonly width: number | null;
|
|
28
|
+
readonly height: number | null;
|
|
29
|
+
/** Crop and focal point, for images. */
|
|
30
|
+
readonly edits: ImageEdits | null;
|
|
31
|
+
/** A blurred stand-in of the image as a `data:` URL, a few hundred bytes, shown while it loads; null for other files. */
|
|
32
|
+
readonly placeholder: string | null;
|
|
33
|
+
readonly createdAt: number;
|
|
34
|
+
readonly updatedAt: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface FileServiceOptions {
|
|
38
|
+
/** Makes resized variants of images; without it, images serve as uploaded. */
|
|
39
|
+
images?: ImageTransformer;
|
|
40
|
+
now?: () => number;
|
|
41
|
+
/** Largest accepted file. Default: no limit beyond what the caller passes. */
|
|
42
|
+
maxBytes?: number;
|
|
43
|
+
/** Called after a file's details change or a file is deleted, for the host to purge the pages that show it. */
|
|
44
|
+
changed?: () => void | Promise<void>;
|
|
45
|
+
/** Content types accepted. Default: every type. */
|
|
46
|
+
contentTypes?: readonly string[];
|
|
47
|
+
/** How long an unfinished upload or delete may wait before `sweep()` resolves it. Default 15 minutes. */
|
|
48
|
+
staleMs?: number;
|
|
49
|
+
/** How long a presigned upload URL stays valid. Default one hour. */
|
|
50
|
+
presignSeconds?: number;
|
|
51
|
+
/** The site's image settings (Settings → Files); `IMAGE_WIDTHS`, quality 78 and no downscaling without it. */
|
|
52
|
+
imageSettings?: () => Promise<ImageSettings>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** How images are resized: the variants' widths, their quality, and the widest original kept (0 for any). */
|
|
56
|
+
export interface ImageSettings {
|
|
57
|
+
readonly widths: readonly number[];
|
|
58
|
+
readonly quality: number;
|
|
59
|
+
readonly maxWidth: number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** What the library holds: files and bytes in all and by kind, and the resized copies made of images. */
|
|
63
|
+
export interface FileSummary {
|
|
64
|
+
readonly files: number;
|
|
65
|
+
readonly bytes: number;
|
|
66
|
+
readonly kinds: readonly { readonly kind: MediaKind; readonly files: number; readonly bytes: number }[];
|
|
67
|
+
/** Copies made before their size was recorded count in `files` alone. */
|
|
68
|
+
readonly variants: { readonly files: number; readonly bytes: number };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const DEFAULT_IMAGES: ImageSettings = { widths: IMAGE_WIDTHS, quality: 78, maxWidth: 0 };
|
|
72
|
+
const OWN_FORMAT: { readonly [type: string]: ImageFormat } = { 'image/jpeg': 'jpeg', 'image/png': 'png', 'image/webp': 'webp', 'image/avif': 'avif' };
|
|
73
|
+
|
|
74
|
+
/** An upload the browser sends itself: where to PUT the bytes, then `complete()` makes the file. */
|
|
75
|
+
export interface PendingUpload {
|
|
76
|
+
readonly id: string;
|
|
77
|
+
readonly name: string;
|
|
78
|
+
readonly contentType: string;
|
|
79
|
+
readonly size: number;
|
|
80
|
+
/** The provider's presigned PUT, or null when the bytes go through the application (`receive()`). */
|
|
81
|
+
readonly direct: StoragePresignedUpload | null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface FileMetadata {
|
|
85
|
+
readonly title?: string;
|
|
86
|
+
readonly alt?: string;
|
|
87
|
+
readonly caption?: string;
|
|
88
|
+
readonly description?: string;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const ID = /^[A-Za-z0-9_-]{1,80}$/;
|
|
92
|
+
/**
|
|
93
|
+
* Private files, such as a form's uploads, live in a key space of their own:
|
|
94
|
+
* `cms/private/<scope>/<id>` against the library's `cms/files/<id>`. Every library read
|
|
95
|
+
* (`get`, `getMany`, `list`, `summary`, and through them `open`, `variant`, the public
|
|
96
|
+
* `/media/` route and media references in content) selects library keys alone, so a private
|
|
97
|
+
* file's ID resolves nowhere public; only `openPrivate`, given the file's scope, reads it, and
|
|
98
|
+
* its caller decides who may (forms: `cms:submissions`). The key marks them rather than a
|
|
99
|
+
* status of their own because `cms_files.status` is fixed to pending, ready and deleting, and
|
|
100
|
+
* keeping them in `cms_files` keeps the two-phase upload and `sweep()` for them.
|
|
101
|
+
*/
|
|
102
|
+
export const LIBRARY_KEYS = "key LIKE 'cms/files/%'";
|
|
103
|
+
const PRIVATE_PREFIX = 'cms/private/';
|
|
104
|
+
/** A scope of private files: path segments of letters, digits, `_` and `-`, such as `forms/<form>/<submission>`. */
|
|
105
|
+
const SCOPE = /^[A-Za-z0-9_-]{1,80}(?:\/[A-Za-z0-9_-]{1,80}){0,4}$/;
|
|
106
|
+
const COLUMNS = 'id, name, content_type, size, owner_id, title, alt, caption, description, width, height, created_at, updated_at, edits, placeholder';
|
|
107
|
+
/** The width of the placeholder the transformer makes; the browser blurs it up to the image's size. */
|
|
108
|
+
const PLACEHOLDER_WIDTH = 16;
|
|
109
|
+
const WRITE = { kind: 'cms.files', retryConflicts: 5 } as const;
|
|
110
|
+
/** Enough bytes to check a signature and read image dimensions behind typical metadata. */
|
|
111
|
+
const HEAD_BYTES = 1024 * 1024;
|
|
112
|
+
/** SVG is sanitized as text, so it is held in memory; larger files are refused. */
|
|
113
|
+
const SVG_MAX_BYTES = 8 * 1024 * 1024;
|
|
114
|
+
|
|
115
|
+
export class FileService {
|
|
116
|
+
readonly #db: RomeDB;
|
|
117
|
+
readonly #storage: StorageProvider;
|
|
118
|
+
readonly #now: () => number;
|
|
119
|
+
readonly #maxBytes: number;
|
|
120
|
+
readonly #changed: (() => void | Promise<void>) | undefined;
|
|
121
|
+
readonly #types: readonly string[] | null;
|
|
122
|
+
readonly #staleMs: number;
|
|
123
|
+
readonly #presignSeconds: number;
|
|
124
|
+
readonly #images: ImageTransformer | undefined;
|
|
125
|
+
readonly #imageSettings: () => Promise<ImageSettings>;
|
|
126
|
+
#warned = false;
|
|
127
|
+
/** Variants being made, by key: concurrent first requests for one share its transform. */
|
|
128
|
+
readonly #making = new Map<string, Promise<Uint8Array | null>>();
|
|
129
|
+
|
|
130
|
+
constructor(db: RomeDB, storage: StorageProvider, options: FileServiceOptions = {}) {
|
|
131
|
+
this.#db = db;
|
|
132
|
+
this.#storage = storage;
|
|
133
|
+
this.#now = options.now ?? Date.now;
|
|
134
|
+
this.#changed = options.changed;
|
|
135
|
+
this.#maxBytes = options.maxBytes ?? Number.MAX_SAFE_INTEGER;
|
|
136
|
+
this.#types = options.contentTypes ?? null;
|
|
137
|
+
this.#staleMs = options.staleMs ?? 15 * 60_000;
|
|
138
|
+
this.#presignSeconds = options.presignSeconds ?? 3600;
|
|
139
|
+
this.#images = options.images;
|
|
140
|
+
this.#imageSettings = options.imageSettings ?? (async () => DEFAULT_IMAGES);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The accepted content types, or null for every type. */
|
|
144
|
+
get contentTypes(): readonly string[] | null { return this.#types; }
|
|
145
|
+
|
|
146
|
+
/** Whether the provider presigns uploads, so browsers send bytes to the bucket directly. */
|
|
147
|
+
get direct(): boolean { return typeof this.#storage.presign === 'function'; }
|
|
148
|
+
|
|
149
|
+
/** Whether resized variants, crops and focal points apply. */
|
|
150
|
+
get resizes(): boolean { return this.#images !== undefined; }
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Crop an image or set its focal point; null clears both. Variants made before are removed,
|
|
154
|
+
* and the file's version changes so pages link to new ones.
|
|
155
|
+
*/
|
|
156
|
+
async setEdits(id: string, edits: ImageEdits | null, context: { principal: Principal }): Promise<CmsFile> {
|
|
157
|
+
const file = await this.get(id);
|
|
158
|
+
if (!file) throw new CmsError('CMS_NOT_FOUND', 'File not found.');
|
|
159
|
+
this.#authorizeChange(file, context.principal, 'edit');
|
|
160
|
+
if (!transformable(file.contentType) || !file.width || !file.height) throw new CmsError('CMS_VALIDATION', 'Only JPEG, PNG, WebP and AVIF images can be cropped.');
|
|
161
|
+
const clean: ImageEdits | null = edits && (edits.crop || edits.focus) ? { ...(edits.crop ? { crop: edits.crop } : {}), ...(edits.focus ? { focus: edits.focus } : {}) } : null;
|
|
162
|
+
const problems = clean ? imageEditsProblems(clean, file.width, file.height) : [];
|
|
163
|
+
if (problems.length) throw new CmsError('CMS_VALIDATION', problems.join(' '));
|
|
164
|
+
await this.#db.write([{ rql: "UPDATE cms_files SET edits = $edits, updated_at = $now WHERE id = $id AND status = 'ready'",
|
|
165
|
+
params: { $edits: clean ? JSON.stringify(clean) : null, $now: Math.max(this.#now(), file.updatedAt + 1), $id: id } }], WRITE);
|
|
166
|
+
await this.#dropVariants(id);
|
|
167
|
+
// The placeholder shows the crop.
|
|
168
|
+
return this.#placeholder((await this.get(id))!);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Scale an image wider than the largest width of Settings → Files down to it, in its own
|
|
173
|
+
* format, replacing the original. Other files, and transformers that fail, keep the upload.
|
|
174
|
+
*/
|
|
175
|
+
async #shrink(file: CmsFile): Promise<CmsFile> {
|
|
176
|
+
const { maxWidth, quality } = await this.#imageSettings();
|
|
177
|
+
const format = OWN_FORMAT[file.contentType];
|
|
178
|
+
if (!this.#images || !maxWidth || !format || !file.width || !file.height || file.width <= maxWidth) return file;
|
|
179
|
+
const original = await this.#storage.get(`cms/files/${file.id}`);
|
|
180
|
+
if (!original) return file;
|
|
181
|
+
const height = Math.max(1, Math.round(file.height * maxWidth / file.width));
|
|
182
|
+
let bytes: Uint8Array;
|
|
183
|
+
try {
|
|
184
|
+
bytes = await this.#images.transform(original.body, { rect: { x: 0, y: 0, width: file.width, height: file.height }, source: { width: file.width, height: file.height }, width: maxWidth, height, format, quality });
|
|
185
|
+
} catch (error) {
|
|
186
|
+
if (!this.#warned) console.warn('[cms] could not scale down a large image; keeping it as uploaded.', error);
|
|
187
|
+
this.#warned = true;
|
|
188
|
+
return file;
|
|
189
|
+
}
|
|
190
|
+
await this.#storage.put(`cms/files/${file.id}`, streamOf(bytes), { size: bytes.byteLength, contentType: file.contentType });
|
|
191
|
+
await this.#db.write([{ rql: "UPDATE cms_files SET size = $size, width = $width, height = $height WHERE id = $id AND status = 'ready'",
|
|
192
|
+
params: { $size: bytes.byteLength, $width: maxWidth, $height: height, $id: file.id } }], WRITE);
|
|
193
|
+
return { ...file, size: bytes.byteLength, width: maxWidth, height };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Count the library by kind, and the resized copies; one read. */
|
|
197
|
+
async summary(): Promise<FileSummary> {
|
|
198
|
+
const result = await this.#db.read([
|
|
199
|
+
{ rql: `SELECT content_type, count(*), sum(size) FROM cms_files WHERE status = 'ready' AND ${LIBRARY_KEYS} GROUP BY content_type` },
|
|
200
|
+
{ rql: 'SELECT count(*), sum(size) FROM cms_file_variants' },
|
|
201
|
+
]);
|
|
202
|
+
const kinds = new Map<MediaKind, { files: number; bytes: number }>();
|
|
203
|
+
for (const [type, count, bytes] of result.results[0]!.rows) {
|
|
204
|
+
const kind = mediaKind(String(type));
|
|
205
|
+
const entry = kinds.get(kind) ?? { files: 0, bytes: 0 };
|
|
206
|
+
kinds.set(kind, { files: entry.files + Number(count as bigint), bytes: entry.bytes + Number((bytes as bigint | null) ?? 0) });
|
|
207
|
+
}
|
|
208
|
+
const list = [...kinds].map(([kind, entry]) => ({ kind, ...entry })).sort((a, b) => b.bytes - a.bytes);
|
|
209
|
+
const [variantFiles, variantBytes] = result.results[1]!.rows[0] ?? [0n, null];
|
|
210
|
+
return {
|
|
211
|
+
files: list.reduce((sum, entry) => sum + entry.files, 0), bytes: list.reduce((sum, entry) => sum + entry.bytes, 0), kinds: list,
|
|
212
|
+
variants: { files: Number(variantFiles as bigint), bytes: Number((variantBytes as bigint | null) ?? 0) },
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Make the image's placeholder: the cropped image at 16 pixels wide as WebP, kept on the
|
|
218
|
+
* row as a `data:` URL. Files that are not images, images with transparency (the blur would
|
|
219
|
+
* show through them once loaded) and transformers that fail leave none.
|
|
220
|
+
*/
|
|
221
|
+
async #placeholder(file: CmsFile): Promise<CmsFile> {
|
|
222
|
+
if (!this.#images || !transformable(file.contentType) || !file.width || !file.height) return file;
|
|
223
|
+
const rect = variantRect(file)!;
|
|
224
|
+
const width = Math.min(PLACEHOLDER_WIDTH, rect.width);
|
|
225
|
+
const height = Math.max(1, Math.round(width * rect.height / rect.width));
|
|
226
|
+
const original = await this.#storage.get(`cms/files/${file.id}`);
|
|
227
|
+
if (!original) return file;
|
|
228
|
+
const { head, body } = await peek(original.body, Math.min(HEAD_BYTES, original.size || HEAD_BYTES));
|
|
229
|
+
if (imageHasAlpha(file.contentType, head)) {
|
|
230
|
+
await body.cancel().catch(() => undefined);
|
|
231
|
+
if (file.placeholder) await this.#db.write([{ rql: "UPDATE cms_files SET placeholder = NULL WHERE id = $id AND status = 'ready'", params: { $id: file.id } }], WRITE);
|
|
232
|
+
return { ...file, placeholder: null };
|
|
233
|
+
}
|
|
234
|
+
let placeholder: string;
|
|
235
|
+
try {
|
|
236
|
+
const bytes = await this.#images.transform(body, { rect, source: { width: file.width, height: file.height }, width, height, format: 'webp', quality: 40 });
|
|
237
|
+
placeholder = `data:image/webp;base64,${base64(bytes)}`;
|
|
238
|
+
} catch (error) {
|
|
239
|
+
if (!this.#warned) console.warn('[cms] could not make image placeholders.', error);
|
|
240
|
+
this.#warned = true;
|
|
241
|
+
return file;
|
|
242
|
+
}
|
|
243
|
+
await this.#db.write([{ rql: "UPDATE cms_files SET placeholder = $placeholder WHERE id = $id AND status = 'ready'", params: { $placeholder: placeholder, $id: file.id } }], WRITE);
|
|
244
|
+
return { ...file, placeholder };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* A resized variant of an image, made on first request and kept in storage: `width` snaps to
|
|
249
|
+
* the site's widths and never exceeds the image; `height` crops to the requested shape, snapped
|
|
250
|
+
* to one of `VARIANT_ASPECTS`, around the focal point. The format follows `accept`. Null when
|
|
251
|
+
* the file is missing or cannot be resized.
|
|
252
|
+
*
|
|
253
|
+
* Every request maps to one of a finite set of variants (widths × shapes × formats), so a
|
|
254
|
+
* visitor cannot make a file transform more than `MAX_FILE_VARIANTS` times: each variant is
|
|
255
|
+
* made once and kept. Past the cap (only after the site's widths changed), the original is served.
|
|
256
|
+
*/
|
|
257
|
+
async variant(id: string, request: { width: number; height?: number; accept?: string; signal?: AbortSignal }): Promise<{ file: CmsFile; body: ReadableStream<Uint8Array>; contentType: string; size: number } | null> {
|
|
258
|
+
const file = await this.get(id);
|
|
259
|
+
if (!file || !this.#images || !transformable(file.contentType) || !file.width || !file.height) return null;
|
|
260
|
+
if (!Number.isSafeInteger(request.width) || request.width < 1 || (request.height !== undefined && (!Number.isSafeInteger(request.height) || request.height < 1 || request.height > 10_000))) return null;
|
|
261
|
+
const settings = await this.#imageSettings();
|
|
262
|
+
// The shape asked for (the icons ask for squares) snaps to a short list of common shapes.
|
|
263
|
+
const aspect = request.height ? snapAspect(request.width / request.height) : undefined;
|
|
264
|
+
const rect = variantRect(file, aspect)!;
|
|
265
|
+
const width = Math.min(variantWidth(request.width, settings.widths), rect.width);
|
|
266
|
+
const height = Math.max(1, Math.round(width * rect.height / rect.width));
|
|
267
|
+
const format = negotiateFormat(request.accept, file.contentType);
|
|
268
|
+
// Keyed on the image's content and edits, not its version: a new title or alt text makes no new variants.
|
|
269
|
+
const key = `cms/variants/${id}/${editsKey(file.edits)}/${width}x${height}${request.height ? 'c' : ''}.${format}`;
|
|
270
|
+
const contentType = FORMAT_TYPES[format];
|
|
271
|
+
const stored = await this.#storage.get(key, request.signal ? { signal: request.signal } : {});
|
|
272
|
+
if (stored) return { file, body: stored.body, contentType, size: stored.size };
|
|
273
|
+
let making = this.#making.get(key);
|
|
274
|
+
if (!making) {
|
|
275
|
+
making = this.#makeVariant(file, key, { rect, width, height, format, contentType, quality: format === 'avif' ? Math.max(30, settings.quality - 18) : settings.quality })
|
|
276
|
+
.finally(() => this.#making.delete(key));
|
|
277
|
+
this.#making.set(key, making);
|
|
278
|
+
}
|
|
279
|
+
const bytes = await making;
|
|
280
|
+
return bytes ? { file, body: streamOf(bytes), contentType, size: bytes.byteLength } : null;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Make and keep one variant. The variants a file can have are a finite set, so a file never
|
|
285
|
+
* holds more than `MAX_FILE_VARIANTS`; the count check below only matters once the site's
|
|
286
|
+
* widths changed and left the old widths' variants behind: then the original is served.
|
|
287
|
+
*/
|
|
288
|
+
async #makeVariant(file: CmsFile, key: string, shape: { rect: { x: number; y: number; width: number; height: number }; width: number; height: number; format: ImageFormat; contentType: string; quality: number }): Promise<Uint8Array | null> {
|
|
289
|
+
const kept = await this.#db.read([{ rql: 'SELECT count(*) FROM cms_file_variants WHERE file_id = $id', params: { $id: file.id } }]);
|
|
290
|
+
if (Number(kept.results[0]!.rows[0]![0] ?? 0) >= MAX_FILE_VARIANTS) return null;
|
|
291
|
+
const original = await this.#storage.get(`cms/files/${file.id}`);
|
|
292
|
+
if (!original) return null;
|
|
293
|
+
let bytes: Uint8Array;
|
|
294
|
+
try {
|
|
295
|
+
bytes = await this.#images!.transform(original.body, { rect: shape.rect, source: { width: file.width!, height: file.height! }, width: shape.width, height: shape.height, format: shape.format, quality: shape.quality });
|
|
296
|
+
} catch (error) {
|
|
297
|
+
// A transformer that cannot run, such as sharp missing on Node, leaves the original.
|
|
298
|
+
if (!this.#warned) console.warn('[cms] could not resize images; serving originals.', error);
|
|
299
|
+
this.#warned = true;
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
await this.#db.write([{ rql: 'INSERT INTO cms_file_variants (key, file_id, created_at, size) VALUES ($key, $id, $now, $size) ON CONFLICT (key) DO NOTHING', params: { $key: key, $id: file.id, $now: this.#now(), $size: bytes.byteLength } }], WRITE);
|
|
303
|
+
await this.#storage.put(key, streamOf(bytes), { size: bytes.byteLength, contentType: shape.contentType });
|
|
304
|
+
return bytes;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** Remove the file's variants, a page at a time: each row goes only with its stored object. */
|
|
308
|
+
async #dropVariants(id: string): Promise<void> {
|
|
309
|
+
for (;;) {
|
|
310
|
+
const result = await this.#db.read([{ rql: 'SELECT key FROM cms_file_variants WHERE file_id = $id ORDER BY key LIMIT 500', params: { $id: id } }]);
|
|
311
|
+
const keys = result.results[0]!.rows.map(row => row[0] as string);
|
|
312
|
+
if (!keys.length) return;
|
|
313
|
+
await this.#evictVariants(id, keys);
|
|
314
|
+
if (keys.length < 500) return;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Delete these variant rows of a file, with their stored objects: only keys under the file's own variant prefix are deleted from storage. */
|
|
319
|
+
async #evictVariants(id: string, keys: readonly string[]): Promise<void> {
|
|
320
|
+
if (!keys.length) return;
|
|
321
|
+
for (const key of keys) if (isVariantKey(key, id)) await this.#storage.delete(key).catch(() => undefined);
|
|
322
|
+
const params: { [name: string]: string } = { $id: id };
|
|
323
|
+
keys.forEach((key, index) => { params[`$k${index}`] = key; });
|
|
324
|
+
await this.#db.write([{ rql: `DELETE FROM cms_file_variants WHERE file_id = $id AND key IN (${keys.map((_, index) => `$k${index}`).join(', ')})`, params }], WRITE);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Record intent, store the bytes, then mark the file ready. The declared type must match
|
|
329
|
+
* the file's signature; image dimensions are read from its first bytes; SVG is sanitized.
|
|
330
|
+
*/
|
|
331
|
+
async upload(file: { name: string; contentType: string; size: number; body: ReadableStream<Uint8Array> } & FileMetadata,
|
|
332
|
+
context: { principal: Principal; signal?: AbortSignal; maxBytes?: number; owner?: string }): Promise<CmsFile> {
|
|
333
|
+
const { id, contentType, size, head } = await this.#store(file, context, 'cms/files/');
|
|
334
|
+
return this.#placeholder(await this.#shrink(await this.#ready(id, size, imageSize(contentType, head))));
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** Begin an upload under a key prefix, check its signature and store its bytes; the row stays pending. */
|
|
338
|
+
async #store(file: { name: string; contentType: string; size: number; body: ReadableStream<Uint8Array> } & FileMetadata,
|
|
339
|
+
context: { principal: Principal; signal?: AbortSignal; maxBytes?: number; owner?: string }, prefix: string): Promise<{ id: string; name: string; contentType: string; size: number; head: Uint8Array }> {
|
|
340
|
+
const { id, key, name, contentType } = await this.#begin(file, context, prefix);
|
|
341
|
+
const { head, body } = await peek(file.body, Math.min(HEAD_BYTES, file.size));
|
|
342
|
+
if (!matchesSignature(contentType, head)) {
|
|
343
|
+
await body.cancel().catch(() => undefined);
|
|
344
|
+
await this.#abandon(id);
|
|
345
|
+
throw new CmsError('CMS_VALIDATION', `The file is not a valid ${contentType} file.`);
|
|
346
|
+
}
|
|
347
|
+
let size = file.size;
|
|
348
|
+
try {
|
|
349
|
+
if (contentType === SVG_TYPE) {
|
|
350
|
+
const clean = await this.#cleanSvg(id, body, file.size);
|
|
351
|
+
size = clean.byteLength;
|
|
352
|
+
await this.#storage.put(key, streamOf(clean), { size, contentType, ...(context.signal ? { signal: context.signal } : {}) });
|
|
353
|
+
} else await this.#storage.put(key, body, { size, contentType, ...(context.signal ? { signal: context.signal } : {}) });
|
|
354
|
+
} catch (error) {
|
|
355
|
+
if (!(error instanceof CmsError)) await this.#abandon(id).catch(() => undefined);
|
|
356
|
+
throw error;
|
|
357
|
+
}
|
|
358
|
+
return { id, name, contentType, size, head };
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// --- Private files ----------------------------------------------------------------------
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Store a private file under `cms/private/<scope>/`, checked as an upload is (size, type,
|
|
365
|
+
* signature, SVG sanitized). Its row stays pending: the caller's own write makes it ready
|
|
366
|
+
* with `privateReady`, in the same batch as what the file belongs to, and `sweep()` removes
|
|
367
|
+
* it when that write never happens. The principal is the host's; `owner` names the sender.
|
|
368
|
+
*/
|
|
369
|
+
async stashPrivate(file: { name: string; contentType: string; size: number; body: ReadableStream<Uint8Array> },
|
|
370
|
+
context: { principal: Principal; scope: string; signal?: AbortSignal; maxBytes?: number; owner?: string }): Promise<{ id: string; name: string; contentType: string; size: number }> {
|
|
371
|
+
if (!SCOPE.test(context.scope)) throw new Error(`Invalid private file scope ${context.scope}.`);
|
|
372
|
+
const { head: _head, ...stored } = await this.#store(file, context, `${PRIVATE_PREFIX}${context.scope}/`);
|
|
373
|
+
return stored;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** The statement that makes stashed private files ready, for the caller's batch: it applies only when `guard` (a condition with its params) holds. */
|
|
377
|
+
privateReady(ids: readonly string[], guard: { readonly rql: string; readonly params: { readonly [key: string]: Value } }): Statement {
|
|
378
|
+
const params: { [key: string]: Value } = { ...guard.params, $readyAt: this.#now() };
|
|
379
|
+
const list = ids.map((id, index) => { params[`$ready${index}`] = id; return `$ready${index}`; }).join(', ');
|
|
380
|
+
return { rql: `UPDATE cms_files SET status = 'ready', updated_at = $readyAt WHERE status = 'pending' AND key LIKE '${PRIVATE_PREFIX}%' AND id IN (${list}) AND ${guard.rql}`, params };
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** A ready private file of a scope with its bytes, or null. The caller has checked who may read it. */
|
|
384
|
+
async openPrivate(scope: string, id: string, options: { signal?: AbortSignal } = {}): Promise<{ file: CmsFile; body: ReadableStream<Uint8Array> } | null> {
|
|
385
|
+
if (!SCOPE.test(scope) || !ID.test(id)) return null;
|
|
386
|
+
const key = `${PRIVATE_PREFIX}${scope}/${id}`;
|
|
387
|
+
const result = await this.#db.read([{ rql: `SELECT ${COLUMNS} FROM cms_files WHERE id = $id AND key = $key AND status = 'ready'`, params: { $id: id, $key: key } }]);
|
|
388
|
+
const row = result.results[0]!.rows[0];
|
|
389
|
+
if (!row) return null;
|
|
390
|
+
const object = await this.#storage.get(key, options);
|
|
391
|
+
return object ? { file: fileOf(row), body: object.body } : null;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** Remove stashed private files no write made ready, such as those of a refused submission. */
|
|
395
|
+
async discardPrivate(ids: readonly string[]): Promise<void> {
|
|
396
|
+
for (const id of ids) {
|
|
397
|
+
const marked = await this.#db.write([{ rql: `UPDATE cms_files SET status = 'deleting', updated_at = $now WHERE id = $id AND status = 'pending' AND key LIKE '${PRIVATE_PREFIX}%'`, params: { $id: id, $now: this.#now() } }], WRITE);
|
|
398
|
+
if (marked.results[0]!.affected === 1n) await this.#finishDelete(id);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Delete every private file under a scope, ready or pending, such as a submission's
|
|
404
|
+
* (`forms/<form>/<submission>`) or a whole form's (`forms/<form>`). Returns how many.
|
|
405
|
+
* Keys are matched as a range, so the key index finds them.
|
|
406
|
+
*/
|
|
407
|
+
async deletePrivate(scope: string): Promise<number> {
|
|
408
|
+
if (!SCOPE.test(scope)) throw new Error(`Invalid private file scope ${scope}.`);
|
|
409
|
+
// Every key under `<prefix>/` sorts at or after it and before `<prefix>0`: '0' follows '/'.
|
|
410
|
+
const range = { $from: `${PRIVATE_PREFIX}${scope}/`, $to: `${PRIVATE_PREFIX}${scope}0` };
|
|
411
|
+
let removed = 0;
|
|
412
|
+
for (;;) {
|
|
413
|
+
const found = await this.#db.read([{ rql: "SELECT id FROM cms_files WHERE key >= $from AND key < $to AND status IN ('pending', 'ready') LIMIT 200", params: range }]);
|
|
414
|
+
const ids = found.results[0]!.rows.map(row => row[0] as string);
|
|
415
|
+
for (const id of ids) {
|
|
416
|
+
const marked = await this.#db.write([{ rql: "UPDATE cms_files SET status = 'deleting', updated_at = $now WHERE id = $id AND status IN ('pending', 'ready') AND key >= $from AND key < $to", params: { ...range, $id: id, $now: this.#now() } }], WRITE);
|
|
417
|
+
if (marked.results[0]!.affected !== 1n) continue;
|
|
418
|
+
await this.#finishDelete(id);
|
|
419
|
+
removed++;
|
|
420
|
+
}
|
|
421
|
+
if (ids.length < 200) break;
|
|
422
|
+
}
|
|
423
|
+
return removed;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* Start an upload the browser sends itself. The row records intent; the bytes go to
|
|
428
|
+
* `direct` (the bucket's presigned URL) or through `receive()`; `complete()` checks them
|
|
429
|
+
* and makes the file. Stale uploads that never complete are swept.
|
|
430
|
+
*/
|
|
431
|
+
async begin(file: { name: string; contentType: string; size: number } & FileMetadata, context: { principal: Principal; maxBytes?: number; owner?: string }): Promise<PendingUpload> {
|
|
432
|
+
const { id, name, contentType } = await this.#begin(file, context);
|
|
433
|
+
let direct: StoragePresignedUpload | null = null;
|
|
434
|
+
if (this.#storage.presign) {
|
|
435
|
+
// The browser writes a staging object; the served one is written by complete() alone, from the bytes it checked.
|
|
436
|
+
try { direct = await this.#storage.presign(stagingKey(id), { size: file.size, contentType, expiresIn: this.#presignSeconds }); }
|
|
437
|
+
catch { direct = null; }
|
|
438
|
+
}
|
|
439
|
+
return { id, name, contentType, size: file.size, direct };
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** Store the bytes of an upload the browser sends through the application, as begun. */
|
|
443
|
+
async receive(id: string, body: ReadableStream<Uint8Array>, context: { principal: Principal; signal?: AbortSignal }): Promise<void> {
|
|
444
|
+
const pending = await this.#pending(id, context.principal);
|
|
445
|
+
await this.#storage.put(stagingKey(id), body, { size: pending.size, contentType: pending.contentType, ...(context.signal ? { signal: context.signal } : {}) });
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Finish an upload: the staging object must exist with the declared size and a matching
|
|
450
|
+
* signature. The served key gets only the bytes this read checked (SVG sanitized), so bytes
|
|
451
|
+
* sent to the staging key later, through a presigned URL still valid or a late request,
|
|
452
|
+
* never reach it; the staging object is removed. A failed check removes both.
|
|
453
|
+
*/
|
|
454
|
+
async complete(id: string, context: { principal: Principal; signal?: AbortSignal }): Promise<CmsFile> {
|
|
455
|
+
const pending = await this.#pending(id, context.principal);
|
|
456
|
+
const signal = context.signal ? { signal: context.signal } : {};
|
|
457
|
+
const staging = stagingKey(id);
|
|
458
|
+
const refuse = async (message: string) => { await this.#abandon(id); return new CmsError('CMS_VALIDATION', message); };
|
|
459
|
+
const object = await this.#storage.get(staging, signal);
|
|
460
|
+
if (!object) throw await refuse('The upload did not finish.');
|
|
461
|
+
if (object.size !== pending.size) {
|
|
462
|
+
await object.body.cancel().catch(() => undefined);
|
|
463
|
+
throw await refuse(`The upload has ${object.size} bytes, not the ${pending.size} declared.`);
|
|
464
|
+
}
|
|
465
|
+
const { head, body } = await peek(object.body, Math.min(HEAD_BYTES, pending.size));
|
|
466
|
+
if (!matchesSignature(pending.contentType, head)) {
|
|
467
|
+
await body.cancel().catch(() => undefined);
|
|
468
|
+
throw await refuse(`The file is not a valid ${pending.contentType} file.`);
|
|
469
|
+
}
|
|
470
|
+
let size = pending.size;
|
|
471
|
+
try {
|
|
472
|
+
if (pending.contentType === SVG_TYPE) {
|
|
473
|
+
const clean = await this.#cleanSvg(id, body, pending.size);
|
|
474
|
+
size = clean.byteLength;
|
|
475
|
+
await this.#storage.put(pending.key, streamOf(clean), { size, contentType: pending.contentType, ...signal });
|
|
476
|
+
} else await this.#storage.put(pending.key, body, { size, contentType: pending.contentType, ...signal });
|
|
477
|
+
} catch (error) {
|
|
478
|
+
if (!(error instanceof CmsError)) await this.#abandon(id).catch(() => undefined);
|
|
479
|
+
throw error;
|
|
480
|
+
}
|
|
481
|
+
await this.#storage.delete(staging).catch(() => undefined);
|
|
482
|
+
return this.#placeholder(await this.#shrink(await this.#ready(id, size, imageSize(pending.contentType, head))));
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** Check the upload and record intent; the row is pending until the bytes are in. */
|
|
486
|
+
async #begin(file: { name: string; contentType: string; size: number } & FileMetadata, context: { principal: Principal; maxBytes?: number; owner?: string }, prefix = 'cms/files/'): Promise<{ id: string; key: string; name: string; contentType: string }> {
|
|
487
|
+
if (!hasPermission(context.principal, PERMISSIONS.upload) && !hasPermission(context.principal, PERMISSIONS.manageMedia)) {
|
|
488
|
+
throw new CmsError(context.principal.kind === 'anonymous' ? 'CMS_UNAUTHENTICATED' : 'CMS_FORBIDDEN', 'Not allowed to upload files.');
|
|
489
|
+
}
|
|
490
|
+
const maxBytes = Math.min(context.maxBytes ?? this.#maxBytes, this.#maxBytes);
|
|
491
|
+
if (!Number.isSafeInteger(file.size) || file.size < 1 || file.size > maxBytes) throw new CmsError('CMS_LIMIT', maxBytes === Number.MAX_SAFE_INTEGER ? 'Files must be at least 1 byte.' : `Files must be 1 byte to ${Math.floor(maxBytes / 1024 / 1024)} MB.`);
|
|
492
|
+
const contentType = declaredType(file.contentType);
|
|
493
|
+
if (this.#types && !this.#types.includes(contentType)) throw new CmsError('CMS_VALIDATION', `Files of type ${contentType} are not accepted.`);
|
|
494
|
+
if (contentType === SVG_TYPE && file.size > SVG_MAX_BYTES) throw new CmsError('CMS_LIMIT', `SVG files must be at most ${SVG_MAX_BYTES / 1024 / 1024} MB.`);
|
|
495
|
+
const name = file.name.replace(/[\x00-\x1f\x7f/\\]/g, '_').trim().slice(0, 200) || 'file';
|
|
496
|
+
const id = uuidv7();
|
|
497
|
+
const key = `${prefix}${id}`;
|
|
498
|
+
const now = this.#now();
|
|
499
|
+
// Host work, such as storing an avatar, names the user the file belongs to.
|
|
500
|
+
const owner = context.principal.kind === 'user' ? context.principal.id : context.principal.kind === 'system' ? context.owner ?? null : null;
|
|
501
|
+
const metadata = checkMetadata({ title: file.title ?? name.replace(/\.[^.]+$/, ''), alt: file.alt ?? '', caption: file.caption ?? '', description: file.description ?? '' });
|
|
502
|
+
await this.#db.write([{
|
|
503
|
+
rql: `INSERT INTO cms_files (id, key, owner_id, name, content_type, size, status, title, alt, caption, description, width, height, created_at, updated_at)
|
|
504
|
+
VALUES ($id, $key, $owner, $name, $type, $size, 'pending', $title, $alt, $caption, $description, NULL, NULL, $now, $now)`,
|
|
505
|
+
params: { $id: id, $key: key, $owner: owner, $name: name, $type: contentType, $size: file.size, ...prefixed(metadata), $now: now },
|
|
506
|
+
}], WRITE);
|
|
507
|
+
return { id, key, name, contentType };
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** A pending upload the principal may finish: its owner, a media manager, or host work. */
|
|
511
|
+
async #pending(id: string, principal: Principal): Promise<{ key: string; owner: string | null; contentType: string; size: number }> {
|
|
512
|
+
if (!ID.test(id)) throw new CmsError('CMS_NOT_FOUND', 'Upload not found.');
|
|
513
|
+
const result = await this.#db.read([{ rql: `SELECT key, owner_id, content_type, size FROM cms_files WHERE id = $id AND status = 'pending' AND ${LIBRARY_KEYS}`, params: { $id: id } }]);
|
|
514
|
+
const row = result.results[0]!.rows[0];
|
|
515
|
+
if (!row) throw new CmsError('CMS_NOT_FOUND', 'Upload not found.');
|
|
516
|
+
const pending = { key: row[0] as string, owner: row[1] as string | null, contentType: row[2] as string, size: Number(row[3] as bigint) };
|
|
517
|
+
const own = principal.kind === 'user' && pending.owner === principalId(principal) && hasPermission(principal, PERMISSIONS.upload);
|
|
518
|
+
if (!own && principal.kind !== 'system' && !hasPermission(principal, PERMISSIONS.manageMedia)) throw new CmsError(principal.kind === 'anonymous' ? 'CMS_UNAUTHENTICATED' : 'CMS_FORBIDDEN', 'Not allowed to finish this upload.');
|
|
519
|
+
return pending;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** Sanitized SVG bytes from the stream; refuses what is not an SVG document. */
|
|
523
|
+
async #cleanSvg(id: string, body: ReadableStream<Uint8Array>, size: number): Promise<Uint8Array> {
|
|
524
|
+
const bytes = new Uint8Array(await new Response(body).arrayBuffer());
|
|
525
|
+
const clean = bytes.byteLength <= Math.max(size, SVG_MAX_BYTES) ? sanitizeSvg(new TextDecoder().decode(bytes)) : null;
|
|
526
|
+
if (clean === null) { await this.#abandon(id); throw new CmsError('CMS_VALIDATION', 'The file is not a valid SVG document.'); }
|
|
527
|
+
return new TextEncoder().encode(clean);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
async #ready(id: string, size: number, dimensions: { width: number; height: number } | null): Promise<CmsFile> {
|
|
531
|
+
const ready = await this.#db.write([{ rql: "UPDATE cms_files SET status = 'ready', size = $size, width = $width, height = $height, updated_at = $now WHERE id = $id AND status = 'pending'",
|
|
532
|
+
params: { $id: id, $size: size, $width: dimensions?.width ?? null, $height: dimensions?.height ?? null, $now: this.#now() } }], WRITE);
|
|
533
|
+
if (ready.results[0]!.affected !== 1n) throw new CmsError('CMS_CONFLICT', 'The upload was cancelled.');
|
|
534
|
+
return (await this.get(id))!;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/** Drop a pending upload: its bytes, if any, and its row. */
|
|
538
|
+
async #abandon(id: string): Promise<void> {
|
|
539
|
+
const marked = await this.#db.write([{ rql: "UPDATE cms_files SET status = 'deleting', updated_at = $now WHERE id = $id AND status = 'pending'", params: { $id: id, $now: this.#now() } }], WRITE);
|
|
540
|
+
if (marked.results[0]!.affected === 1n) await this.#finishDelete(id);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
async get(id: string): Promise<CmsFile | null> {
|
|
544
|
+
if (!ID.test(id)) return null;
|
|
545
|
+
const result = await this.#db.read([{ rql: `SELECT ${COLUMNS} FROM cms_files WHERE id = $id AND status = 'ready' AND ${LIBRARY_KEYS}`, params: { $id: id } }]);
|
|
546
|
+
const row = result.results[0]!.rows[0];
|
|
547
|
+
return row ? fileOf(row) : null;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
async getMany(ids: readonly string[]): Promise<Map<string, CmsFile>> {
|
|
551
|
+
const wanted = [...new Set(ids.filter(id => typeof id === 'string' && ID.test(id)))].slice(0, 200);
|
|
552
|
+
if (!wanted.length) return new Map();
|
|
553
|
+
// Files hold captions, descriptions, edits and a placeholder: many may come in smaller reads.
|
|
554
|
+
const rows = await readByIds(this.#db, wanted, slice => ({
|
|
555
|
+
rql: `SELECT ${COLUMNS} FROM cms_files WHERE status = 'ready' AND ${LIBRARY_KEYS} AND id IN (${slice.map((_, index) => `$f${index}`).join(', ')})`,
|
|
556
|
+
params: Object.fromEntries(slice.map((id, index) => [`$f${index}`, id])),
|
|
557
|
+
}));
|
|
558
|
+
return new Map(rows.map(row => { const file = fileOf(row); return [file.id, file]; }));
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** Ready files, newest first, filtered by kind, owner and a search over name and title. */
|
|
562
|
+
async list(options: { kind?: MediaKind; search?: string; owner?: string; limit?: number; offset?: number } = {}): Promise<{ items: CmsFile[]; total: number }> {
|
|
563
|
+
const conditions = ["status = 'ready'", LIBRARY_KEYS];
|
|
564
|
+
const params: { [key: string]: Value } = {};
|
|
565
|
+
if (options.kind) {
|
|
566
|
+
const prefixes = MEDIA_FILTERS[options.kind];
|
|
567
|
+
if (!prefixes) throw new CmsError('CMS_VALIDATION', `Unknown media kind ${options.kind}.`);
|
|
568
|
+
conditions.push(`(${prefixes.map((prefix, index) => { params[`$k${index}`] = `${prefix}%`; return `content_type LIKE $k${index}`; }).join(' OR ')})`);
|
|
569
|
+
const excluded = MEDIA_FILTER_EXCLUDES[options.kind] ?? [];
|
|
570
|
+
if (excluded.length) conditions.push(`content_type NOT IN (${excluded.map((type, index) => { params[`$x${index}`] = type; return `$x${index}`; }).join(', ')})`);
|
|
571
|
+
}
|
|
572
|
+
if (options.search?.trim()) {
|
|
573
|
+
conditions.push("(lower(name) LIKE $q ESCAPE '\\' OR lower(title) LIKE $q ESCAPE '\\')");
|
|
574
|
+
params.$q = containsPattern(options.search.trim().slice(0, 100));
|
|
575
|
+
}
|
|
576
|
+
if (options.owner) { conditions.push('owner_id = $owner'); params.$owner = options.owner; }
|
|
577
|
+
const where = conditions.join(' AND ');
|
|
578
|
+
const counted = await this.#db.read([Object.keys(params).length ? { rql: `SELECT count(*) FROM cms_files WHERE ${where}`, params } : { rql: `SELECT count(*) FROM cms_files WHERE ${where}` }]);
|
|
579
|
+
const rows = await readPaged(this.#db, (size, at) => ({ rql: `SELECT ${COLUMNS} FROM cms_files WHERE ${where} ORDER BY created_at DESC, id DESC LIMIT $limit OFFSET $offset`, params: { ...params, $limit: size, $offset: at } }),
|
|
580
|
+
Math.min(Math.max(options.limit ?? 40, 1), 100), Math.min(Math.max(options.offset ?? 0, 0), 100_000), { afterSequence: counted.sequence });
|
|
581
|
+
return { items: rows.map(fileOf), total: Number(counted.results[0]!.rows[0]![0] as bigint) };
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/** Change title, alt text, caption or description. The owner or a media manager may edit. */
|
|
585
|
+
async update(id: string, patch: FileMetadata, context: { principal: Principal }): Promise<CmsFile> {
|
|
586
|
+
const file = await this.get(id);
|
|
587
|
+
if (!file) throw new CmsError('CMS_NOT_FOUND', 'File not found.');
|
|
588
|
+
this.#authorizeChange(file, context.principal, 'edit');
|
|
589
|
+
const next = checkMetadata({ title: patch.title ?? file.title, alt: patch.alt ?? file.alt, caption: patch.caption ?? file.caption, description: patch.description ?? file.description });
|
|
590
|
+
await this.#db.write([{ rql: "UPDATE cms_files SET title = $title, alt = $alt, caption = $caption, description = $description, updated_at = $now WHERE id = $id AND status = 'ready'",
|
|
591
|
+
params: { ...prefixed(next), $now: this.#now(), $id: id } }], WRITE);
|
|
592
|
+
await this.#changed?.();
|
|
593
|
+
return (await this.get(id))!;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
async open(id: string, options: { signal?: AbortSignal } = {}): Promise<{ file: CmsFile; body: ReadableStream<Uint8Array> } | null> {
|
|
597
|
+
const file = await this.get(id);
|
|
598
|
+
if (!file) return null;
|
|
599
|
+
const object = await this.#storage.get(`cms/files/${id}`, options);
|
|
600
|
+
return object ? { file, body: object.body } : null;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/** Mark for deletion, delete the bytes, then the row. The owner or a media manager may delete. */
|
|
604
|
+
async delete(id: string, context: { principal: Principal }): Promise<void> {
|
|
605
|
+
const file = await this.get(id);
|
|
606
|
+
if (!file) throw new CmsError('CMS_NOT_FOUND', 'File not found.');
|
|
607
|
+
this.#authorizeChange(file, context.principal, 'delete');
|
|
608
|
+
const marked = await this.#db.write([{ rql: "UPDATE cms_files SET status = 'deleting', updated_at = $now WHERE id = $id AND status = 'ready'", params: { $id: id, $now: this.#now() } }], WRITE);
|
|
609
|
+
if (marked.results[0]!.affected !== 1n) throw new CmsError('CMS_CONFLICT', 'The file is already being deleted.');
|
|
610
|
+
await this.#finishDelete(id);
|
|
611
|
+
await this.#changed?.();
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/** Resolve interrupted work: stale pending uploads are removed; stale deletes are completed. */
|
|
615
|
+
/** Delete every stored file and resized copy, for a site that is being deleted. The rows stay. */
|
|
616
|
+
async purgeStorage(): Promise<number> {
|
|
617
|
+
let removed = 0;
|
|
618
|
+
// Only keys the service gives files and variants: a row from an imported export cannot name another object.
|
|
619
|
+
for (const [table, id] of [['cms_files', 'id'], ['cms_file_variants', 'file_id']] as const) {
|
|
620
|
+
let after = '';
|
|
621
|
+
for (;;) {
|
|
622
|
+
const result = await this.#db.read([{ rql: `SELECT key, ${id} FROM ${table} WHERE key > $after ORDER BY key LIMIT 500`, params: { $after: after } }]);
|
|
623
|
+
const rows = result.results[0]!.rows.map(row => [row[0] as string, row[1] as string] as const);
|
|
624
|
+
for (const [key, owner] of rows) {
|
|
625
|
+
if (!(table === 'cms_files' ? isFileKey(key, owner) : isVariantKey(key, owner))) continue;
|
|
626
|
+
await this.#storage.delete(key);
|
|
627
|
+
removed++;
|
|
628
|
+
}
|
|
629
|
+
if (rows.length < 500) break;
|
|
630
|
+
after = rows[rows.length - 1]![0];
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
return removed;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
async sweep(options: { limit?: number } = {}): Promise<{ removed: number }> {
|
|
637
|
+
const before = this.#now() - this.#staleMs;
|
|
638
|
+
const result = await this.#db.read([{
|
|
639
|
+
rql: "SELECT id FROM cms_files WHERE status IN ('pending', 'deleting') AND updated_at <= $before ORDER BY updated_at LIMIT $limit",
|
|
640
|
+
params: { $before: before, $limit: options.limit ?? 50 },
|
|
641
|
+
}]);
|
|
642
|
+
let removed = 0;
|
|
643
|
+
for (const [id] of result.results[0]!.rows) {
|
|
644
|
+
const claimed = await this.#db.write([{ rql: "UPDATE cms_files SET status = 'deleting', updated_at = $now WHERE id = $id AND status IN ('pending', 'deleting') AND updated_at <= $before",
|
|
645
|
+
params: { $id: id!, $now: this.#now(), $before: before } }], WRITE);
|
|
646
|
+
if (claimed.results[0]!.affected !== 1n) continue;
|
|
647
|
+
await this.#finishDelete(id as string);
|
|
648
|
+
removed++;
|
|
649
|
+
}
|
|
650
|
+
return { removed };
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
#authorizeChange(file: CmsFile, principal: Principal, action: 'edit' | 'delete'): void {
|
|
654
|
+
const own = principal.kind === 'user' && file.owner === principalId(principal) && hasPermission(principal, PERMISSIONS.upload);
|
|
655
|
+
if (!own && !hasPermission(principal, PERMISSIONS.manageMedia)) throw new CmsError(principal.kind === 'anonymous' ? 'CMS_UNAUTHENTICATED' : 'CMS_FORBIDDEN', `Not allowed to ${action} this file.`);
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
async #finishDelete(id: string): Promise<void> {
|
|
659
|
+
// The row names its key: a library file's, or a private one's.
|
|
660
|
+
const row = await this.#db.read([{ rql: 'SELECT key FROM cms_files WHERE id = $id', params: { $id: id } }]);
|
|
661
|
+
const key = row.results[0]!.rows[0]?.[0];
|
|
662
|
+
await this.#dropVariants(id);
|
|
663
|
+
// Only a key the service gives a file: a row from an imported export cannot name another object.
|
|
664
|
+
await this.#storage.delete(typeof key === 'string' && isFileKey(key, id) ? key : `cms/files/${id}`);
|
|
665
|
+
// A browser upload that never finished left its bytes in staging.
|
|
666
|
+
await this.#storage.delete(stagingKey(id)).catch(() => undefined);
|
|
667
|
+
await this.#db.write([{ rql: "DELETE FROM cms_files WHERE id = $id AND status = 'deleting'", params: { $id: id } }], WRITE);
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/** A key the service gives file `id`: its library key, or a private one ending in its ID. */
|
|
672
|
+
function isFileKey(key: string, id: string): boolean {
|
|
673
|
+
return key === `cms/files/${id}` || (key.startsWith(PRIVATE_PREFIX) && !key.includes('..') && key.endsWith(`/${id}`));
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/** A key under file `id`'s own variant prefix. */
|
|
677
|
+
function isVariantKey(key: string, id: string): boolean {
|
|
678
|
+
return key.startsWith(`cms/variants/${id}/`) && !key.includes('..');
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/** Where a browser upload's bytes wait for complete(): never a served key, and never written to after it. */
|
|
682
|
+
function stagingKey(id: string): string {
|
|
683
|
+
return `cms/uploads/${id}`;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/** Read up to `bytes` from the start of a stream, and a stream that replays them followed by the rest. */
|
|
687
|
+
async function peek(source: ReadableStream<Uint8Array>, bytes: number): Promise<{ head: Uint8Array; body: ReadableStream<Uint8Array> }> {
|
|
688
|
+
const reader = source.getReader();
|
|
689
|
+
const chunks: Uint8Array[] = [];
|
|
690
|
+
let size = 0;
|
|
691
|
+
let done = false;
|
|
692
|
+
while (size < bytes) {
|
|
693
|
+
const next = await reader.read();
|
|
694
|
+
if (next.done) { done = true; break; }
|
|
695
|
+
chunks.push(next.value);
|
|
696
|
+
size += next.value.byteLength;
|
|
697
|
+
}
|
|
698
|
+
const head = new Uint8Array(size);
|
|
699
|
+
let offset = 0;
|
|
700
|
+
for (const chunk of chunks) { head.set(chunk, offset); offset += chunk.byteLength; }
|
|
701
|
+
const body = new ReadableStream<Uint8Array>({
|
|
702
|
+
start(controller) {
|
|
703
|
+
if (head.byteLength) controller.enqueue(head);
|
|
704
|
+
if (done) controller.close();
|
|
705
|
+
},
|
|
706
|
+
async pull(controller) {
|
|
707
|
+
const next = await reader.read();
|
|
708
|
+
if (next.done) controller.close();
|
|
709
|
+
else controller.enqueue(next.value);
|
|
710
|
+
},
|
|
711
|
+
cancel(reason) { return reader.cancel(reason); },
|
|
712
|
+
});
|
|
713
|
+
return { head, body };
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function checkMetadata(metadata: Required<FileMetadata>): Required<FileMetadata> {
|
|
717
|
+
const limits = { title: 200, alt: 300, caption: 1000, description: 5000 } as const;
|
|
718
|
+
const fields: { [name: string]: string } = {};
|
|
719
|
+
for (const [name, limit] of Object.entries(limits)) {
|
|
720
|
+
const value = metadata[name as keyof FileMetadata];
|
|
721
|
+
if (typeof value !== 'string' || value.length > limit) fields[name] = `must be at most ${limit} characters.`;
|
|
722
|
+
}
|
|
723
|
+
if (Object.keys(fields).length) throw new CmsError('CMS_VALIDATION', 'Some file details are invalid.', { fields });
|
|
724
|
+
return { title: metadata.title.trim(), alt: metadata.alt.trim(), caption: metadata.caption.trim(), description: metadata.description.trim() };
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
function prefixed(metadata: Required<FileMetadata>): { [key: string]: Value } {
|
|
728
|
+
return { $title: metadata.title, $alt: metadata.alt, $caption: metadata.caption, $description: metadata.description };
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
function fileOf(row: readonly Value[]): CmsFile {
|
|
732
|
+
return Object.freeze({
|
|
733
|
+
id: row[0] as string, name: row[1] as string, contentType: row[2] as string, size: Number(row[3] as bigint), owner: row[4] as string | null,
|
|
734
|
+
title: row[5] as string, alt: row[6] as string, caption: row[7] as string, description: row[8] as string,
|
|
735
|
+
width: row[9] === null ? null : Number(row[9] as bigint), height: row[10] === null ? null : Number(row[10] as bigint),
|
|
736
|
+
edits: row[13] ? parseEdits(row[13] as string) : null,
|
|
737
|
+
placeholder: typeof row[14] === 'string' && row[14] ? row[14] : null,
|
|
738
|
+
createdAt: Number(row[11] as bigint), updatedAt: Number(row[12] as bigint),
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
function base64(bytes: Uint8Array): string {
|
|
743
|
+
let binary = '';
|
|
744
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
745
|
+
return btoa(binary);
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
function parseEdits(text: string): ImageEdits | null {
|
|
749
|
+
try { return JSON.parse(text) as ImageEdits; } catch { return null; }
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
function streamOf(bytes: Uint8Array): ReadableStream<Uint8Array> {
|
|
753
|
+
return new ReadableStream({ start(controller) { controller.enqueue(bytes); controller.close(); } });
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/** The shapes variants are cut to: square, and 4:3, 3:2, 16:9 and 21:9 either way up. */
|
|
757
|
+
export const VARIANT_ASPECTS = Object.freeze([1, 4 / 3, 3 / 4, 3 / 2, 2 / 3, 16 / 9, 9 / 16, 21 / 9, 9 / 21] as const);
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* The most variants one file has: up to 12 widths (Settings → Files) × the whole image and each
|
|
761
|
+
* shape × 3 formats. Every request maps to one of these, so this bound holds by construction.
|
|
762
|
+
*/
|
|
763
|
+
export const MAX_FILE_VARIANTS = 12 * (1 + VARIANT_ASPECTS.length) * 3;
|
|
764
|
+
|
|
765
|
+
/** A short, stable name for an image's edits (crop and focus), for its variants' keys. */
|
|
766
|
+
function editsKey(edits: ImageEdits | null | undefined): string {
|
|
767
|
+
if (!edits) return 'o';
|
|
768
|
+
const text = JSON.stringify([edits.crop?.x, edits.crop?.y, edits.crop?.width, edits.crop?.height, edits.focus?.x, edits.focus?.y]);
|
|
769
|
+
let hash = 0x811c9dc5;
|
|
770
|
+
for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193) >>> 0;
|
|
771
|
+
return hash.toString(36);
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/** A requested shape, snapped to the nearest of `VARIANT_ASPECTS` (by ratio, so wide and tall weigh alike). */
|
|
775
|
+
export function snapAspect(aspect: number): number {
|
|
776
|
+
if (!Number.isFinite(aspect) || aspect <= 0) return 1;
|
|
777
|
+
let best: number = VARIANT_ASPECTS[0];
|
|
778
|
+
for (const shape of VARIANT_ASPECTS) if (Math.abs(Math.log(shape / aspect)) < Math.abs(Math.log(best / aspect)) - 1e-12) best = shape;
|
|
779
|
+
return best;
|
|
780
|
+
}
|