tinyzoo 0.0.0-stage → 0.2.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 +10 -0
- package/README.md +46 -2
- package/app/app.config.ts +35 -0
- package/app/assets/brand/characters/bright/bird.svg +1 -0
- package/app/assets/brand/characters/bright/bunny.svg +1 -0
- package/app/assets/brand/characters/bright/elephant.svg +1 -0
- package/app/assets/brand/characters/bright/fox.svg +1 -0
- package/app/assets/brand/characters/bright/frog.svg +1 -0
- package/app/assets/brand/characters/bright/octopus.svg +1 -0
- package/app/assets/brand/characters/muted/bee.svg +1 -0
- package/app/assets/brand/characters/muted/bird.svg +1 -0
- package/app/assets/brand/characters/muted/butterfly.svg +1 -0
- package/app/assets/brand/characters/muted/chick.svg +1 -0
- package/app/assets/brand/characters/muted/cow.svg +1 -0
- package/app/assets/brand/characters/muted/deer.svg +1 -0
- package/app/assets/brand/characters/muted/duck.svg +1 -0
- package/app/assets/brand/characters/muted/elephant.svg +1 -0
- package/app/assets/brand/characters/muted/fox.svg +1 -0
- package/app/assets/brand/characters/muted/hedgehog.svg +1 -0
- package/app/assets/brand/characters/muted/koala.svg +1 -0
- package/app/assets/brand/characters/muted/ladybug.svg +1 -0
- package/app/assets/brand/characters/muted/lion.svg +1 -0
- package/app/assets/brand/characters/muted/mouse.svg +1 -0
- package/app/assets/brand/characters/muted/octopus.svg +1 -0
- package/app/assets/brand/characters/muted/owl.svg +1 -0
- package/app/assets/brand/characters/muted/panda.svg +1 -0
- package/app/assets/brand/characters/muted/penguin.svg +1 -0
- package/app/assets/brand/characters/muted/pig.svg +1 -0
- package/app/assets/brand/characters/muted/poodle.svg +1 -0
- package/app/assets/brand/characters/muted/raccoon.svg +1 -0
- package/app/assets/brand/characters/muted/seal.svg +1 -0
- package/app/assets/brand/characters/muted/sheep.svg +1 -0
- package/app/assets/brand/characters/muted/snail.svg +1 -0
- package/app/assets/brand/characters/muted/turtle.svg +1 -0
- package/app/assets/brand/characters/muted/whale.svg +1 -0
- package/app/assets/brand/logo/favicon.svg +1 -0
- package/app/assets/brand/logo/logo-primary-reversed.svg +1 -0
- package/app/assets/brand/logo/logo-primary.svg +1 -0
- package/app/assets/brand/logo/mascot-reversed.svg +1 -0
- package/app/assets/brand/logo/mascot.svg +1 -0
- package/app/assets/brand/logo/wordmark-reversed.svg +1 -0
- package/app/assets/brand/logo/wordmark.svg +1 -0
- package/app/assets/css/cms-admin.css +607 -0
- package/app/components/CmsBlocks.vue +30 -0
- package/app/components/CmsCell.vue +16 -0
- package/app/components/CmsCellBadge.vue +18 -0
- package/app/components/CmsCellBlocks.vue +9 -0
- package/app/components/CmsCellBoolean.vue +12 -0
- package/app/components/CmsCellCode.vue +7 -0
- package/app/components/CmsCellColor.vue +13 -0
- package/app/components/CmsCellDate.vue +10 -0
- package/app/components/CmsCellExcerpt.vue +21 -0
- package/app/components/CmsCellGallery.vue +10 -0
- package/app/components/CmsCellGroup.vue +23 -0
- package/app/components/CmsCellNumber.vue +7 -0
- package/app/components/CmsCellRelation.vue +8 -0
- package/app/components/CmsCellText.vue +12 -0
- package/app/components/CmsCellThumb.vue +18 -0
- package/app/components/CmsConfirmDialog.vue +55 -0
- package/app/components/CmsContent.vue +103 -0
- package/app/components/CmsDayPicker.vue +44 -0
- package/app/components/CmsEmptyState.vue +35 -0
- package/app/components/CmsField.vue +111 -0
- package/app/components/CmsFieldBlocks.vue +353 -0
- package/app/components/CmsFieldBoolean.vue +8 -0
- package/app/components/CmsFieldColor.vue +42 -0
- package/app/components/CmsFieldDate.vue +131 -0
- package/app/components/CmsFieldGallery.vue +114 -0
- package/app/components/CmsFieldGroup.vue +53 -0
- package/app/components/CmsFieldMedia.vue +219 -0
- package/app/components/CmsFieldNumber.vue +11 -0
- package/app/components/CmsFieldRelationMany.vue +54 -0
- package/app/components/CmsFieldRelationOne.vue +47 -0
- package/app/components/CmsFieldRichText.vue +45 -0
- package/app/components/CmsFieldSelect.vue +41 -0
- package/app/components/CmsFieldSlug.vue +46 -0
- package/app/components/CmsFieldText.vue +75 -0
- package/app/components/CmsFormSections.vue +150 -0
- package/app/components/CmsHighlight.vue +22 -0
- package/app/components/CmsImage.vue +39 -0
- package/app/components/CmsLinkPicker.vue +122 -0
- package/app/components/CmsLinkTarget.vue +35 -0
- package/app/components/CmsListFilters.vue +107 -0
- package/app/components/CmsLiveNotice.vue +64 -0
- package/app/components/CmsLoadError.vue +24 -0
- package/app/components/CmsMascot.vue +10 -0
- package/app/components/CmsMediaLibrary.vue +114 -0
- package/app/components/CmsMediaPreview.vue +34 -0
- package/app/components/CmsMediaThumb.vue +22 -0
- package/app/components/CmsMoment.vue +42 -0
- package/app/components/CmsNav.vue +39 -0
- package/app/components/CmsPage.vue +86 -0
- package/app/components/CmsPasswordInput.vue +22 -0
- package/app/components/CmsPresence.vue +29 -0
- package/app/components/CmsPreviewPanel.vue +131 -0
- package/app/components/CmsPublishReview.vue +102 -0
- package/app/components/CmsRevisions.vue +195 -0
- package/app/components/CmsRichTextEditor.vue +290 -0
- package/app/components/CmsSearch.vue +99 -0
- package/app/components/CmsSection.vue +20 -0
- package/app/components/CmsSingletonForm.vue +283 -0
- package/app/components/CmsStatusBadge.vue +21 -0
- package/app/components/CmsTime.vue +16 -0
- package/app/components/CmsTranslationRef.vue +27 -0
- package/app/components/CmsTreeList.vue +453 -0
- package/app/components/CmsUnsavedText.vue +34 -0
- package/app/components/CmsWordmark.vue +10 -0
- package/app/composables/useCmsAdminHead.ts +18 -0
- package/app/composables/useCmsCollab.ts +165 -0
- package/app/composables/useCmsConfirm.ts +39 -0
- package/app/composables/useCmsEntryActions.ts +75 -0
- package/app/composables/useCmsFocus.ts +13 -0
- package/app/composables/useCmsForm.ts +273 -0
- package/app/composables/useCmsI18n.ts +185 -0
- package/app/composables/useCmsLinkTargets.ts +84 -0
- package/app/composables/useCmsLive.ts +199 -0
- package/app/composables/useCmsSearch.ts +62 -0
- package/app/composables/useCmsSeo.ts +99 -0
- package/app/composables/useCmsSignedIn.ts +24 -0
- package/app/composables/useCmsUiLocale.ts +24 -0
- package/app/i18n/cs.ts +781 -0
- package/app/i18n/de.ts +781 -0
- package/app/i18n/en.ts +782 -0
- package/app/i18n/types.ts +22 -0
- package/app/layouts/admin.vue +224 -0
- package/app/layouts/cms-auth.vue +37 -0
- package/app/middleware/cms-api-not-a-page.global.ts +10 -0
- package/app/middleware/cms-auth.global.ts +16 -0
- package/app/pages/admin/[entity]/[id].vue +1109 -0
- package/app/pages/admin/[entity]/index.vue +733 -0
- package/app/pages/admin/account.vue +117 -0
- package/app/pages/admin/forgot.vue +50 -0
- package/app/pages/admin/index.vue +184 -0
- package/app/pages/admin/invite/[token].vue +73 -0
- package/app/pages/admin/login.vue +84 -0
- package/app/pages/admin/media.vue +494 -0
- package/app/pages/admin/privacy.vue +193 -0
- package/app/pages/admin/reset/[token].vue +52 -0
- package/app/pages/admin/setup.vue +87 -0
- package/app/pages/admin/styleguide.vue +261 -0
- package/app/pages/admin/team.vue +258 -0
- package/app/plugins/cmsLivePreview.client.ts +20 -0
- package/app/plugins/cmsSignedOut.client.ts +31 -0
- package/app/utils/cmsBlockType.ts +11 -0
- package/app/utils/cmsBrand.ts +38 -0
- package/app/utils/cmsDiff.ts +83 -0
- package/app/utils/cmsFetch.ts +7 -0
- package/app/utils/cmsFocusInvalid.ts +22 -0
- package/app/utils/cmsIssues.ts +128 -0
- package/app/utils/cmsJson.ts +28 -0
- package/app/utils/cmsMedia.ts +63 -0
- package/app/utils/cmsSections.ts +154 -0
- package/app/utils/cmsTime.ts +41 -0
- package/cli/backup.ts +713 -0
- package/cli/breaking.ts +174 -0
- package/cli/content-migrate.ts +239 -0
- package/cli/db.ts +86 -0
- package/cli/export.ts +336 -0
- package/cli/generate.ts +146 -0
- package/cli/import.ts +643 -0
- package/cli/index.ts +140 -0
- package/cli/links-convert.ts +291 -0
- package/cli/seed-engine.ts +705 -0
- package/cli/seed.ts +339 -0
- package/cli/status.ts +49 -0
- package/cli/tar.ts +304 -0
- package/cli/transfer.ts +677 -0
- package/cli/up.ts +27 -0
- package/cli/upgrade.ts +60 -0
- package/cli/versions.ts +60 -0
- package/forms/components/CmsForm.vue +186 -0
- package/forms/index.ts +203 -0
- package/forms/messages.ts +104 -0
- package/forms/retention.ts +48 -0
- package/forms/server/form.get.ts +12 -0
- package/forms/server/form.post.ts +109 -0
- package/forms/server/formSettings.ts +12 -0
- package/forms/server/forms.ts +127 -0
- package/module.ts +373 -0
- package/nuxt.config.ts +43 -0
- package/package.json +98 -3
- package/server/api/cms/[entity]/[id]/revisions/[rev].get.ts +19 -0
- package/server/api/cms/[entity]/[id]/revisions/index.get.ts +14 -0
- package/server/api/cms/[entity]/[id].delete.ts +52 -0
- package/server/api/cms/[entity]/[id].get.ts +21 -0
- package/server/api/cms/[entity]/[id].patch.ts +116 -0
- package/server/api/cms/[entity]/_export.get.ts +69 -0
- package/server/api/cms/[entity]/_move.post.ts +81 -0
- package/server/api/cms/[entity]/_order.post.ts +49 -0
- package/server/api/cms/[entity]/_tree.get.ts +41 -0
- package/server/api/cms/[entity]/index.get.ts +62 -0
- package/server/api/cms/[entity]/index.post.ts +38 -0
- package/server/api/cms/[entity]/options.get.ts +55 -0
- package/server/api/cms/_auth/accept.post.ts +33 -0
- package/server/api/cms/_auth/forgot.post.ts +39 -0
- package/server/api/cms/_auth/invite/[token].get.ts +18 -0
- package/server/api/cms/_auth/login.post.ts +42 -0
- package/server/api/cms/_auth/logout.post.ts +7 -0
- package/server/api/cms/_auth/me.get.ts +5 -0
- package/server/api/cms/_auth/me.patch.ts +32 -0
- package/server/api/cms/_auth/password.post.ts +29 -0
- package/server/api/cms/_auth/reset.post.ts +34 -0
- package/server/api/cms/_auth/setup.post.ts +46 -0
- package/server/api/cms/_auth/status.get.ts +18 -0
- package/server/api/cms/_collab/session.get.ts +30 -0
- package/server/api/cms/_collab/socket.ts +51 -0
- package/server/api/cms/_collab/unsaved.delete.ts +16 -0
- package/server/api/cms/_graph.get.ts +20 -0
- package/server/api/cms/_links/resolve.post.ts +17 -0
- package/server/api/cms/_links.get.ts +81 -0
- package/server/api/cms/_live.ts +30 -0
- package/server/api/cms/_media/[id]/usage.get.ts +14 -0
- package/server/api/cms/_media/[id].delete.ts +29 -0
- package/server/api/cms/_media/[id].get.ts +13 -0
- package/server/api/cms/_media/[id].patch.ts +64 -0
- package/server/api/cms/_media/exists.post.ts +15 -0
- package/server/api/cms/_media/img/[id]/[file].get.ts +42 -0
- package/server/api/cms/_media/index.get.ts +44 -0
- package/server/api/cms/_media/index.post.ts +147 -0
- package/server/api/cms/_media/raw/[...key].get.ts +85 -0
- package/server/api/cms/_media/raw/[...key].head.ts +2 -0
- package/server/api/cms/_overview.get.ts +87 -0
- package/server/api/cms/_preview.post.ts +17 -0
- package/server/api/cms/_privacy/delete.post.ts +14 -0
- package/server/api/cms/_privacy/export.post.ts +25 -0
- package/server/api/cms/_privacy/lookup.post.ts +27 -0
- package/server/api/cms/_search.get.ts +17 -0
- package/server/api/cms/_singleton/[name].get.ts +19 -0
- package/server/api/cms/_singleton/[name].put.ts +76 -0
- package/server/api/cms/_users/[id]/resend.post.ts +25 -0
- package/server/api/cms/_users/[id].delete.ts +21 -0
- package/server/api/cms/_users/[id].patch.ts +45 -0
- package/server/api/cms/_users/index.get.ts +28 -0
- package/server/api/cms/_users/index.post.ts +39 -0
- package/server/api/content/[entity]/[slug].get.ts +74 -0
- package/server/api/content/[entity]/index.get.ts +100 -0
- package/server/api/content/_global/[name].get.ts +23 -0
- package/server/api/content/_search.get.ts +28 -0
- package/server/api/content/_sitemap.get.ts +8 -0
- package/server/api/content/_tree/[entity].get.ts +31 -0
- package/server/api/content-types.ts.get.ts +17 -0
- package/server/api/health/live.get.ts +10 -0
- package/server/api/health/ready.get.ts +21 -0
- package/server/api/openapi.get.ts +48 -0
- package/server/api/openapi.json.get.ts +32 -0
- package/server/db/driver.ts +8 -0
- package/server/mail/mailer.ts +43 -0
- package/server/middleware/cms-0-headers.ts +37 -0
- package/server/middleware/cms-0-migrate-gate.ts +14 -0
- package/server/middleware/cms-csrf.ts +28 -0
- package/server/middleware/cms-limits.ts +20 -0
- package/server/middleware/cms-redirects.ts +21 -0
- package/server/middleware/cms-session.ts +41 -0
- package/server/middleware/cms-z-plugin-access.ts +15 -0
- package/server/plugins/cms-0-config-check.ts +35 -0
- package/server/plugins/cms-changes.ts +53 -0
- package/server/plugins/cms-content-etag.ts +21 -0
- package/server/plugins/cms-errors.ts +45 -0
- package/server/plugins/cms-migrate.ts +5 -0
- package/server/plugins/cms-plugins.ts +17 -0
- package/server/plugins/cms-search.ts +12 -0
- package/server/plugins/cms-setup-code.ts +15 -0
- package/server/routes/sitemap.xml.get.ts +25 -0
- package/server/store/redis.ts +95 -0
- package/server/store/types.ts +21 -0
- package/server/tasks/cms/retention.ts +10 -0
- package/server/tasks/cms/scheduled.ts +10 -0
- package/server/tasks/cms/search-reindex.ts +12 -0
- package/server/utils/cmsAudit.ts +29 -0
- package/server/utils/cmsAuth.ts +143 -0
- package/server/utils/cmsBlocks.ts +47 -0
- package/server/utils/cmsChanges.ts +222 -0
- package/server/utils/cmsCollab.ts +286 -0
- package/server/utils/cmsCollabServer.ts +451 -0
- package/server/utils/cmsCollate.ts +27 -0
- package/server/utils/cmsContent.ts +376 -0
- package/server/utils/cmsCrud.ts +361 -0
- package/server/utils/cmsCsv.ts +24 -0
- package/server/utils/cmsDb.ts +23 -0
- package/server/utils/cmsDemo.ts +36 -0
- package/server/utils/cmsEmails.ts +125 -0
- package/server/utils/cmsErrors.ts +40 -0
- package/server/utils/cmsFold.ts +17 -0
- package/server/utils/cmsImageSizes.ts +51 -0
- package/server/utils/cmsJson.ts +6 -0
- package/server/utils/cmsLinkAddress.ts +50 -0
- package/server/utils/cmsLinks.ts +248 -0
- package/server/utils/cmsListQuery.ts +93 -0
- package/server/utils/cmsLive.ts +393 -0
- package/server/utils/cmsLocales.ts +96 -0
- package/server/utils/cmsMail.ts +28 -0
- package/server/utils/cmsMediaGc.ts +188 -0
- package/server/utils/cmsMediaKeys.ts +62 -0
- package/server/utils/cmsMigrate.ts +86 -0
- package/server/utils/cmsPreviewDraft.ts +72 -0
- package/server/utils/cmsPrivacy.ts +176 -0
- package/server/utils/cmsPublished.ts +57 -0
- package/server/utils/cmsRange.ts +38 -0
- package/server/utils/cmsRateLimit.ts +82 -0
- package/server/utils/cmsRedirects.ts +160 -0
- package/server/utils/cmsRetention.ts +61 -0
- package/server/utils/cmsRevisions.ts +103 -0
- package/server/utils/cmsScheduler.ts +45 -0
- package/server/utils/cmsScrub.ts +107 -0
- package/server/utils/cmsSearch.ts +354 -0
- package/server/utils/cmsSession.ts +102 -0
- package/server/utils/cmsSetupCode.ts +97 -0
- package/server/utils/cmsSitemap.ts +176 -0
- package/server/utils/cmsStorage.ts +580 -0
- package/server/utils/cmsStore.ts +109 -0
- package/server/utils/cmsTiming.ts +14 -0
- package/server/utils/cmsTooMany.ts +9 -0
- package/server/utils/cmsTranslationWrite.ts +186 -0
- package/server/utils/cmsTree.ts +251 -0
- package/server/utils/cmsTreeAddress.ts +65 -0
- package/server/utils/cmsUpload.ts +228 -0
- package/server/utils/cmsWebhooks.ts +104 -0
- package/shared/json.ts +11 -0
- package/shared/richtext-editor.ts +56 -0
- package/shared/richtext-normalize.ts +33 -0
- package/shared/richtext-paste.ts +151 -0
- package/shared/storage-delivery.ts +53 -0
- package/src/blocks.ts +624 -0
- package/src/changes.ts +54 -0
- package/src/content-shape.ts +340 -0
- package/src/deprecate.ts +64 -0
- package/src/descriptor.ts +149 -0
- package/src/docs.ts +27 -0
- package/src/emitter.ts +94 -0
- package/src/entity.ts +624 -0
- package/src/errorReport.ts +41 -0
- package/src/fields.ts +465 -0
- package/src/i18n.ts +26 -0
- package/src/index.ts +54 -0
- package/src/linkref.ts +31 -0
- package/src/links.ts +179 -0
- package/src/locales.ts +39 -0
- package/src/media.ts +48 -0
- package/src/migrate.ts +236 -0
- package/src/openapi.ts +377 -0
- package/src/paths.ts +88 -0
- package/src/plugin.ts +505 -0
- package/src/presets.ts +230 -0
- package/src/richtext.ts +88 -0
- package/src/sdk.ts +181 -0
- package/src/search.ts +312 -0
- package/src/seed.ts +225 -0
- package/src/setupCode.ts +30 -0
- package/src/system.ts +219 -0
- package/src/tree.ts +421 -0
- package/src/upgrades.ts +137 -0
- package/starter/.env.example +10 -0
- package/starter/README.md +65 -0
- package/starter/app/app.config.ts +10 -0
- package/starter/app/app.vue +12 -0
- package/starter/app/assets/css/main.css +15 -0
- package/starter/app/components/global/BlockContact.vue +15 -0
- package/starter/app/components/global/BlockCta.vue +15 -0
- package/starter/app/components/global/BlockHero.vue +23 -0
- package/starter/app/components/global/BlockImage.vue +13 -0
- package/starter/app/components/global/BlockText.vue +12 -0
- package/starter/app/composables/useSite.ts +77 -0
- package/starter/app/error.vue +28 -0
- package/starter/app/layouts/default.vue +106 -0
- package/starter/app/lib/cms-content.ts +152 -0
- package/starter/app/pages/[...slug].vue +66 -0
- package/starter/app/pages/hledat.vue +59 -0
- package/starter/app/pages/index.vue +20 -0
- package/starter/cms.config.ts +137 -0
- package/starter/compose.yaml +15 -0
- package/starter/drizzle.config.ts +8 -0
- package/starter/gitignore.txt +8 -0
- package/starter/nuxt.config.ts +13 -0
- package/starter/package.json +38 -0
- package/starter/scripts/typecheck.mjs +38 -0
- package/starter/seed/index.ts +297 -0
- package/starter/seed/media/about.jpg +0 -0
- package/starter/seed/media/hero.jpg +0 -0
- package/starter/seed/media/logo.png +0 -0
- package/starter/seed/media/news-bread.jpg +0 -0
- package/starter/seed/media/news-morning.jpg +0 -0
- package/starter/server/db/migrations/0000_init.sql +269 -0
- package/starter/server/db/migrations/0001_page_tree.sql +5 -0
- package/starter/server/db/migrations/0002_opening_hours_per_language.sql +1 -0
- package/starter/server/db/migrations/meta/0000_snapshot.json +1890 -0
- package/starter/server/db/migrations/meta/0001_snapshot.json +1887 -0
- package/starter/server/db/migrations/meta/0002_snapshot.json +1893 -0
- package/starter/server/db/migrations/meta/_journal.json +27 -0
- package/starter/server/db/schema.ts +253 -0
- package/starter/server/plugins/sitemap.ts +11 -0
- package/starter/server/routes/robots.txt.get.ts +12 -0
- package/starter/tsconfig.json +9 -0
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { eq, type TreeNode } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
export default defineEventHandler(async (event) => {
|
|
4
|
+
const { db, reg } = useCms()
|
|
5
|
+
const user = requireCmsUser(event)
|
|
6
|
+
const e = getEntity(reg, getRouterParam(event, 'entity'))
|
|
7
|
+
if (e.singleton) throw createError({ statusCode: 404, statusMessage: 'Use PUT /api/cms/_singleton/:name' })
|
|
8
|
+
const rowFilter = authorize(e, 'update', user)
|
|
9
|
+
const id = getIdParam(event)
|
|
10
|
+
// ?locale=<translation>: write that language's translation only.
|
|
11
|
+
const locale = requestedLocale(event, reg)
|
|
12
|
+
if (isTranslationLocale(reg, locale)) return { row: await writeTranslation(event, e, id, locale, user, rowFilter) }
|
|
13
|
+
const body = await readBody(event)
|
|
14
|
+
|
|
15
|
+
// The row as it is now: for media cleanup, the publish rule, the audit entry and the check of its blocks.
|
|
16
|
+
const [old] = await db.select().from(e.table).where(both(eq(e.table.id, id), rowFilter))
|
|
17
|
+
if (!old) throw createError({ statusCode: 404, statusMessage: 'Not found or not permitted' })
|
|
18
|
+
// Saving over someone else's newer version needs the editor's say-so (409 otherwise): said
|
|
19
|
+
// before the body is judged, so an editor that is behind is told so, not that its blocks are.
|
|
20
|
+
const base = baseVersion(event)
|
|
21
|
+
await assertCurrentVersion(e, old, base)
|
|
22
|
+
// Checked against what is stored: a block that is behind, or of a type that is gone, stays only if it is stored already.
|
|
23
|
+
const data = parseOr422(writeSchema(e, 'update', old), body)
|
|
24
|
+
await assertMediaAccepted(db, reg, e, data)
|
|
25
|
+
const { values, m2m } = splitPayload(e, data)
|
|
26
|
+
|
|
27
|
+
// Capture OLD media references for any media FK or rich-text field being changed,
|
|
28
|
+
// so we can GC the blobs that get replaced/cleared/removed after the write commits.
|
|
29
|
+
const changedMediaCols = Object.entries(e.fields)
|
|
30
|
+
.filter(([k, f]) => (f as any).type === 'media' && `${k}Id` in values)
|
|
31
|
+
.map(([k]) => `${k}Id`)
|
|
32
|
+
const changedRichCols = Object.entries(e.fields)
|
|
33
|
+
.filter(([k, f]) => JSON_MEDIA_TYPES.has((f as any).type) && k in values)
|
|
34
|
+
.map(([k]) => k)
|
|
35
|
+
const oldMedia: Record<string, string | null> = {}
|
|
36
|
+
for (const c of changedMediaCols) oldMedia[c] = old[c] ?? null
|
|
37
|
+
const oldEmbedded: string[] = changedRichCols.flatMap((k) => jsonMediaIds(e.fields[k], old[k]))
|
|
38
|
+
assertPublishAllowed(e, user, values, old)
|
|
39
|
+
await assertNoRedirectLoop(e, values, old)
|
|
40
|
+
stampPublishDate(e, values, old)
|
|
41
|
+
// What visitors could see before this save (for the change report / webhooks).
|
|
42
|
+
const seenBefore = await changeSnapshot(e, id)
|
|
43
|
+
// A page tree: a new parent or address part changes the address of the page and every page below it.
|
|
44
|
+
const treeKeys = e.tree ? treeProps(e) : null
|
|
45
|
+
const treeTouched = !!treeKeys && (treeKeys.parent in values || treeKeys.slug in values)
|
|
46
|
+
|
|
47
|
+
const { row, effect } = await db.transaction(async (tx: any) => {
|
|
48
|
+
let writeTree: Awaited<ReturnType<typeof beginTreeWrite>> | null = null
|
|
49
|
+
let wasLive = new Set<string>()
|
|
50
|
+
if (treeTouched && treeKeys) {
|
|
51
|
+
// What the request does not set (the other of parent and address part) is read under the lock,
|
|
52
|
+
// from the tree as it is now: a rename or move that landed since `old` was read must count.
|
|
53
|
+
let before: TreeNode | undefined
|
|
54
|
+
writeTree = await beginTreeWrite(tx, reg, e, (nodes) => {
|
|
55
|
+
before = nodes.find((n) => n.id === id)
|
|
56
|
+
if (!before) throw createError({ statusCode: 404, statusMessage: 'Not found or not permitted' })
|
|
57
|
+
return {
|
|
58
|
+
id,
|
|
59
|
+
parentId: treeKeys.parent in values ? values[treeKeys.parent] ?? null : before.parentId,
|
|
60
|
+
slug: treeKeys.slug in values ? String(values[treeKeys.slug]) : before.slug,
|
|
61
|
+
title: treeKeys.title in values ? String(values[treeKeys.title] ?? '') : before.title,
|
|
62
|
+
}
|
|
63
|
+
}, user)
|
|
64
|
+
wasLive = await liveAmong(tx, e, subtreeIds(writeTree.nodes, id))
|
|
65
|
+
// Under a new parent a page goes last among its new siblings.
|
|
66
|
+
if (treeKeys.parent in values && (values[treeKeys.parent] ?? null) !== (before!.parentId ?? null) && !(e.tree!.order in values)) {
|
|
67
|
+
values[e.tree!.order] = nextPosition(writeTree.nodes, values[treeKeys.parent] ?? null)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
// Every save is a new version, relation-only ones included.
|
|
71
|
+
values.updatedAt = nextVersion(e.table.updatedAt)
|
|
72
|
+
values.updatedBy = actorId(user)
|
|
73
|
+
// For people who may not publish, the row must still not be live at write time
|
|
74
|
+
// (an editor may have published it since we read it), and it must still be the
|
|
75
|
+
// version the editor saw (someone may have saved since we read it).
|
|
76
|
+
const sameVersion = base ? eq(e.table.updatedAt, base) : undefined
|
|
77
|
+
const [current] = await tx.update(e.table).set(values).where(both(both(both(eq(e.table.id, id), rowFilter), notLiveCond(e, user)), sameVersion)).returning()
|
|
78
|
+
if (!current && base) {
|
|
79
|
+
const [now] = await tx.select().from(e.table).where(both(eq(e.table.id, id), rowFilter))
|
|
80
|
+
await assertCurrentVersion(e, now, base)
|
|
81
|
+
}
|
|
82
|
+
if (!current) throw createError({ statusCode: 404, statusMessage: 'Not found or not permitted' })
|
|
83
|
+
await writeM2M(tx, reg, e, id, m2m, true)
|
|
84
|
+
// The page and everything below it may have new addresses: redirects from the old ones, in the same transaction.
|
|
85
|
+
const effect = writeTree ? await treeEffect(tx, reg, e, writeTree.nodes, writeTree.next, id, wasLive, actorId(user)) : null
|
|
86
|
+
// A redirect away from an address this entry is live at now would loop: gone, in the same transaction.
|
|
87
|
+
await dropRedirectsFromLiveAddresses(tx, reg, e, id)
|
|
88
|
+
return { row: current, effect }
|
|
89
|
+
}).catch((err: unknown) => rethrowDbError(err, e, 'write'))
|
|
90
|
+
|
|
91
|
+
// GC each replaced/cleared media blob after commit (skip if unchanged or reused).
|
|
92
|
+
if (changedMediaCols.length || changedRichCols.length) {
|
|
93
|
+
const storage = useCmsStorage()
|
|
94
|
+
for (const c of changedMediaCols) {
|
|
95
|
+
if (oldMedia[c] && oldMedia[c] !== row[c]) await gcMediaIfOrphan(db, reg, storage, oldMedia[c], gcScope(user))
|
|
96
|
+
}
|
|
97
|
+
// Images dropped from rich text on this edit → GC if now orphaned.
|
|
98
|
+
if (oldEmbedded.length) {
|
|
99
|
+
const stillEmbedded = new Set(changedRichCols.flatMap((k) => jsonMediaIds(e.fields[k], row[k])))
|
|
100
|
+
for (const mid of new Set(oldEmbedded)) {
|
|
101
|
+
if (!stillEmbedded.has(mid)) await gcMediaIfOrphan(db, reg, storage, mid, gcScope(user))
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
await noteCollabSave(event, { entity: e, id, locale: null }, row.updatedAt)
|
|
107
|
+
const action = publishAction(e, old, row)
|
|
108
|
+
await audit(event, action ?? 'entry.update', { entity: e.name, recordId: id, ...(effect?.moved.length ? { meta: { moved: effect.moved.length, redirects: effect.redirects.length } } : {}) })
|
|
109
|
+
await reportChange(event, {
|
|
110
|
+
type: action === 'entry.publish' ? 'entry.published' : action === 'entry.unpublish' ? 'entry.unpublished' : 'entry.updated',
|
|
111
|
+
entity: e, id, before: seenBefore, after: row, moved: effect?.moved,
|
|
112
|
+
})
|
|
113
|
+
if (effect) await reportTreeRedirects(event, reg, effect.redirects)
|
|
114
|
+
// Old addresses that now lead to the new ones (a changed address part or a move): told, so the editor knows.
|
|
115
|
+
return { row, ...(effect?.redirects.length ? { redirects: effect.redirects.length } : {}) }
|
|
116
|
+
})
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { and, desc, inArray, propOf, resolveText } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// GET /api/cms/:entity/_export — the list as a CSV file for Excel or Sheets (form
|
|
4
|
+
// submissions, a price list): the same search, filters and status tab as the list on
|
|
5
|
+
// screen (same query), every plain field, the name of each related item (author),
|
|
6
|
+
// and when it was created; newest first; only what the signed-in user may read. UTF-8 with a BOM, so Excel
|
|
7
|
+
// opens Czech letters correctly.
|
|
8
|
+
const PLAIN = new Set(['text', 'slug', 'number', 'boolean', 'select', 'datetime'])
|
|
9
|
+
const MAX_ROWS = 10_000
|
|
10
|
+
|
|
11
|
+
/** A date as Excel reads it, in the admin's time zone: 2026-11-15 10:59. */
|
|
12
|
+
function localTime(d: Date, timeZone: string): string {
|
|
13
|
+
const p = Object.fromEntries(new Intl.DateTimeFormat('en-GB', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' })
|
|
14
|
+
.formatToParts(d).map((x) => [x.type, x.value]))
|
|
15
|
+
return p.year + '-' + p.month + '-' + p.day + ' ' + p.hour + ':' + p.minute
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export default defineEventHandler(async (event) => {
|
|
19
|
+
const { db, reg } = useCms()
|
|
20
|
+
const user = requireCmsUser(event)
|
|
21
|
+
const e = getEntity(reg, getRouterParam(event, 'entity'))
|
|
22
|
+
if (e.singleton) throw createError({ statusCode: 404, statusMessage: 'Globals have no list to export' })
|
|
23
|
+
const rowFilter = authorize(e, 'read', user)
|
|
24
|
+
|
|
25
|
+
const cols = (Object.entries(e.fields) as [string, any][])
|
|
26
|
+
.filter(([, f]) => (PLAIN.has(f.type) && !f.relation) || f.relation?.kind === 'many-to-one')
|
|
27
|
+
.map(([k, f]) => ({ key: k, prop: f.relation ? `${k}Id` : propOf(k, f), target: f.relation ? (f.relation.to() as any) : null }))
|
|
28
|
+
const conds = listConditions(e, reg, getQuery(event), rowFilter)
|
|
29
|
+
const rows: any[] = await db.select().from(e.table).where(conds.length ? and(...conds) : undefined).orderBy(desc(e.table.createdAt)).limit(MAX_ROWS)
|
|
30
|
+
|
|
31
|
+
// Related items by their title, not their id.
|
|
32
|
+
const names = new Map<string, Map<string, string>>()
|
|
33
|
+
for (const c of cols) {
|
|
34
|
+
if (!c.target) continue
|
|
35
|
+
const ids = [...new Set(rows.map((r) => r[c.prop]).filter(Boolean))] as string[]
|
|
36
|
+
const t = c.target
|
|
37
|
+
const found: any[] = ids.length ? await db.select({ id: t.table.id, title: t.table[t.titleField] }).from(t.table).where(inArray(t.table.id, ids)) : []
|
|
38
|
+
names.set(c.key, new Map(found.map((x) => [x.id, String(x.title ?? '')])))
|
|
39
|
+
}
|
|
40
|
+
const value = (r: any, c: (typeof cols)[number]) => (c.target ? names.get(c.key)?.get(r[c.prop]) ?? r[c.prop] : r[c.prop])
|
|
41
|
+
|
|
42
|
+
// In the admin's language: column names as labelled, choices by their names, yes/no,
|
|
43
|
+
// local dates; Czech and German Excel expect ";" between columns.
|
|
44
|
+
const admin = ((useAppConfig() as any)?.cms?.admin ?? {}) as Record<string, any>
|
|
45
|
+
const locale = String(getCookie(event, 'cms_admin_locale') || admin.defaultLocale || 'en')
|
|
46
|
+
const lang = locale.toLowerCase().split('-')[0]
|
|
47
|
+
const timeZone = String(admin.timeZone || 'Europe/Prague')
|
|
48
|
+
const sep = lang === 'cs' || lang === 'de' ? ';' : ','
|
|
49
|
+
const yes = lang === 'cs' ? 'ano' : lang === 'de' ? 'ja' : 'yes'
|
|
50
|
+
const no = lang === 'cs' ? 'ne' : lang === 'de' ? 'nein' : 'no'
|
|
51
|
+
const show = (v: unknown, c?: (typeof cols)[number]): string => {
|
|
52
|
+
if (v === null || v === undefined) return ''
|
|
53
|
+
if (v instanceof Date) return localTime(v, timeZone)
|
|
54
|
+
if (typeof v === 'boolean') return v ? yes : no
|
|
55
|
+
const f = c ? (e.fields[c.key] as any) : null
|
|
56
|
+
if (f?.type === 'select') return resolveText(f.meta?.labels?.[String(v)], locale) || String(v)
|
|
57
|
+
return String(v)
|
|
58
|
+
}
|
|
59
|
+
const label = (key: string) => resolveText((e.fields[key] as any)?.meta?.label, locale) || key
|
|
60
|
+
const header = [...cols.map((c) => label(c.key)), lang === 'cs' ? 'Vytvořeno' : lang === 'de' ? 'Erstellt' : 'Created'].map(csvCell).join(sep)
|
|
61
|
+
const lines = rows.map((r) => [...cols.map((c) => show(value(r, c), c)), show(r.createdAt)].map(csvCell).join(sep))
|
|
62
|
+
await audit(event, 'entry.export', { entity: e.name, meta: { rows: rows.length } })
|
|
63
|
+
|
|
64
|
+
const day = new Date().toISOString().slice(0, 10)
|
|
65
|
+
setResponseHeader(event, 'content-type', 'text/csv; charset=utf-8')
|
|
66
|
+
setResponseHeader(event, 'content-disposition', 'attachment; filename="' + e.name + '-' + day + '.csv"')
|
|
67
|
+
setResponseHeader(event, 'cache-control', 'no-store')
|
|
68
|
+
return '' + [header, ...lines].join('\r\n') + '\r\n'
|
|
69
|
+
})
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { eq, placeAmong, sortSiblings, type TreeNode } from 'tinyzoo'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
// POST /api/cms/:entity/_move { id, parent, index } — put a page of a tree under another
|
|
5
|
+
// page (or at the top: parent null) at a place among its new siblings (index 0 =
|
|
6
|
+
// first; past the end = last). One call for dragging and for the "Move…" dialog.
|
|
7
|
+
//
|
|
8
|
+
// Refused with a 422 naming the loop when the page would end up under itself, a 422
|
|
9
|
+
// when the tree would get deeper than allowed, a 409 when the address is taken. The
|
|
10
|
+
// page and everything below it get their new addresses at once; redirects from the old
|
|
11
|
+
// ones are written in the same transaction (defineRedirects), and the change report
|
|
12
|
+
// lists every address that moved.
|
|
13
|
+
//
|
|
14
|
+
// Positions are sparse (1024 apart), so a page put between two others gets a number
|
|
15
|
+
// between theirs and only that page is written: a move never touches the siblings, which
|
|
16
|
+
// may be other people's pages. Only when two neighbours have no number between them are
|
|
17
|
+
// all the siblings renumbered, and then as a bookkeeping change of the order alone: their
|
|
18
|
+
// version, author and saved versions stay as they were (an editor with such a page open
|
|
19
|
+
// is not told it changed).
|
|
20
|
+
const body = z.object({ id: z.string().uuid(), parent: z.string().uuid().nullable(), index: z.number().int().min(0).max(100_000).optional() })
|
|
21
|
+
|
|
22
|
+
export default defineEventHandler(async (event) => {
|
|
23
|
+
const { db, reg } = useCms()
|
|
24
|
+
const user = requireCmsUser(event)
|
|
25
|
+
const e = getEntity(reg, getRouterParam(event, 'entity'))
|
|
26
|
+
if (!e.tree || e.singleton) throw createError({ statusCode: 404, statusMessage: 'This collection is not a tree' })
|
|
27
|
+
const rowFilter = authorize(e, 'update', user)
|
|
28
|
+
const { id, parent, index } = parseOr422(body, await readBody(event))
|
|
29
|
+
const p = treeProps(e)
|
|
30
|
+
|
|
31
|
+
const [current] = await db.select().from(e.table).where(both(eq(e.table.id, id), rowFilter))
|
|
32
|
+
if (!current) throw createError({ statusCode: 404, statusMessage: 'Not found or not permitted' })
|
|
33
|
+
assertPublishAllowed(e, user, {}, current)
|
|
34
|
+
const seenBefore = await changeSnapshot(e, id)
|
|
35
|
+
|
|
36
|
+
const result = await db.transaction(async (tx: any) => {
|
|
37
|
+
// Everything the request does not say (the address part) comes from the tree as it is under the lock.
|
|
38
|
+
let before: TreeNode | undefined
|
|
39
|
+
const w = await beginTreeWrite(tx, reg, e, (nodes) => {
|
|
40
|
+
before = nodes.find((n) => n.id === id)
|
|
41
|
+
if (!before) throw createError({ statusCode: 404, statusMessage: 'Not found or not permitted' })
|
|
42
|
+
return { id, parentId: parent, slug: before.slug, title: before.title }
|
|
43
|
+
}, user)
|
|
44
|
+
const was = before!
|
|
45
|
+
const wasLive = await liveAmong(tx, e, subtreeIds(w.nodes, id))
|
|
46
|
+
const parentChanged = (was.parentId ?? null) !== parent
|
|
47
|
+
// The new siblings in order; the page goes in at `index` (its old number stays if it fits there).
|
|
48
|
+
const siblings = sortSiblings(w.nodes.filter((n) => n.parentId === parent && n.id !== id))
|
|
49
|
+
const place = placeAmong(siblings, id, index, was.position ?? 0)
|
|
50
|
+
let touched: any = null
|
|
51
|
+
if (parentChanged || place.position !== (was.position ?? 0)) {
|
|
52
|
+
;[touched] = await tx.update(e.table)
|
|
53
|
+
.set({ [p.parent]: parent, [p.order]: place.position, updatedAt: nextVersion(e.table.updatedAt), updatedBy: actorId(user) })
|
|
54
|
+
.where(both(both(eq(e.table.id, id), rowFilter), notLiveCond(e, user))).returning()
|
|
55
|
+
if (!touched) throw createError({ statusCode: 403, statusMessage: 'You may not move this entry' })
|
|
56
|
+
}
|
|
57
|
+
// No room between two neighbours: the order of the siblings is written down again, nothing else about them.
|
|
58
|
+
const positions = new Map(w.nodes.map((n) => [n.id, n.position ?? 0]))
|
|
59
|
+
let renumbered = 0
|
|
60
|
+
for (const [sid, position] of place.renumbered) {
|
|
61
|
+
if (sid === id || positions.get(sid) === position) continue
|
|
62
|
+
await tx.update(e.table).set({ [p.order]: position }).where(eq(e.table.id, sid))
|
|
63
|
+
renumbered++
|
|
64
|
+
}
|
|
65
|
+
const effect = await treeEffect(tx, reg, e, w.nodes, w.next, id, wasLive, actorId(user))
|
|
66
|
+
return { touched, effect, parentChanged, renumbered }
|
|
67
|
+
}).catch((err: unknown) => rethrowDbError(err, e, 'write'))
|
|
68
|
+
|
|
69
|
+
if (result.touched) {
|
|
70
|
+
await reportChange(event, {
|
|
71
|
+
type: 'entry.updated', entity: e, id, before: seenBefore, after: result.touched, moved: result.effect.moved,
|
|
72
|
+
// A new position is not an edit worth a revision; a new parent is.
|
|
73
|
+
noRevision: !result.parentChanged,
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
await reportTreeRedirects(event, reg, result.effect.redirects)
|
|
77
|
+
if (result.touched) {
|
|
78
|
+
await audit(event, 'entry.move', { entity: e.name, recordId: id, meta: { parent, moved: result.effect.moved.length, redirects: result.effect.redirects.length, renumbered: result.renumbered } })
|
|
79
|
+
}
|
|
80
|
+
return { ok: true, moved: result.effect.moved, redirects: result.effect.redirects.length }
|
|
81
|
+
})
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { eq, inArray, propOf } from 'tinyzoo'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
// POST /api/cms/:entity/_order { ids: [...] } — store a manual order (collections
|
|
5
|
+
// with `admin.list.orderField`): the entries get positions 0, 1, 2… in the order
|
|
6
|
+
// given, all or none, under the same rules as editing each of them. Only entries
|
|
7
|
+
// whose position changed count as changed (version, history, webhooks).
|
|
8
|
+
const body = z.object({ ids: z.array(z.string().uuid()).min(1).max(500) })
|
|
9
|
+
|
|
10
|
+
export default defineEventHandler(async (event) => {
|
|
11
|
+
const { db, reg } = useCms()
|
|
12
|
+
const user = requireCmsUser(event)
|
|
13
|
+
const e = getEntity(reg, getRouterParam(event, 'entity'))
|
|
14
|
+
const key = e.admin?.list?.orderField
|
|
15
|
+
if (!key || e.singleton) throw createError({ statusCode: 404, statusMessage: 'This collection has no manual order' })
|
|
16
|
+
const rowFilter = authorize(e, 'update', user)
|
|
17
|
+
const { ids } = parseOr422(body, await readBody(event))
|
|
18
|
+
if (new Set(ids).size !== ids.length) throw createError({ statusCode: 422, statusMessage: 'Each entry may appear once' })
|
|
19
|
+
const col = e.table[propOf(key, e.fields[key]!)]
|
|
20
|
+
|
|
21
|
+
// Cheap access check first: every entry must be one this person may move.
|
|
22
|
+
const allowed: any[] = await db.select({ id: e.table.id }).from(e.table).where(both(both(inArray(e.table.id, ids), rowFilter), notLiveCond(e, user)))
|
|
23
|
+
if (allowed.length !== ids.length) throw createError({ statusCode: 403, statusMessage: 'You may not move some of these entries' })
|
|
24
|
+
const before = new Map<string, any>()
|
|
25
|
+
for (const id of ids) before.set(id, await changeSnapshot(e, id))
|
|
26
|
+
const moved: any[] = await db.transaction(async (tx: any) => {
|
|
27
|
+
// Locked in id order, so two reorders at once wait for each other instead of deadlocking.
|
|
28
|
+
const current: any[] = await tx.select({ id: e.table.id, pos: col }).from(e.table).where(inArray(e.table.id, ids)).orderBy(e.table.id).for('update')
|
|
29
|
+
if (current.length !== ids.length) throw createError({ statusCode: 404, statusMessage: 'Not found or not permitted' })
|
|
30
|
+
const posOf = new Map(current.map((r) => [r.id, r.pos]))
|
|
31
|
+
const out: any[] = []
|
|
32
|
+
for (const [i, id] of ids.entries()) {
|
|
33
|
+
if (posOf.get(id) === i) continue
|
|
34
|
+
const [row] = await tx.update(e.table)
|
|
35
|
+
.set({ [propOf(key, e.fields[key]!)]: i, updatedAt: nextVersion(e.table.updatedAt), updatedBy: actorId(user) })
|
|
36
|
+
.where(both(both(eq(e.table.id, id), rowFilter), notLiveCond(e, user))).returning()
|
|
37
|
+
if (!row) throw createError({ statusCode: 403, statusMessage: 'You may not move some of these entries' })
|
|
38
|
+
out.push(row)
|
|
39
|
+
}
|
|
40
|
+
return out
|
|
41
|
+
}).catch((err: unknown) => rethrowDbError(err, e, 'write'))
|
|
42
|
+
|
|
43
|
+
for (const row of moved) {
|
|
44
|
+
// A new position is not an edit worth a revision (it would push real edits out).
|
|
45
|
+
await reportChange(event, { type: 'entry.updated', entity: e, id: row.id, before: before.get(row.id), after: row, noRevision: true })
|
|
46
|
+
}
|
|
47
|
+
if (moved.length) await audit(event, 'entry.reorder', { entity: e.name, meta: { moved: moved.length } })
|
|
48
|
+
return { moved: moved.length }
|
|
49
|
+
})
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { chainOf, indexTree, propOf, sql } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// GET /api/cms/:entity/_tree — every entry of a page tree for the admin's tree list and
|
|
4
|
+
// the move dialog: where it sits (parentId, position), its status, whether it is on
|
|
5
|
+
// the website (published, and so is everything above it) and its address in each
|
|
6
|
+
// language. Drafts included; only entries this person may read.
|
|
7
|
+
export default defineEventHandler(async (event) => {
|
|
8
|
+
const { db, reg } = useCms()
|
|
9
|
+
const user = requireCmsUser(event)
|
|
10
|
+
const e = getEntity(reg, getRouterParam(event, 'entity'))
|
|
11
|
+
if (!e.tree || e.singleton) throw createError({ statusCode: 404, statusMessage: 'This collection is not a tree' })
|
|
12
|
+
const rowFilter = authorize(e, 'read', user)
|
|
13
|
+
const p = treeProps(e)
|
|
14
|
+
const pub = e.publish
|
|
15
|
+
const liveCond = publishedCond(e)
|
|
16
|
+
|
|
17
|
+
const cols: Record<string, any> = {
|
|
18
|
+
id: e.table.id, parentId: e.table[p.parent], title: e.table[p.title], slug: e.table[p.slug], position: e.table[p.order],
|
|
19
|
+
updatedAt: e.table.updatedAt, onSite: liveCond ? sql<boolean>`${liveCond}` : sql<boolean>`true`,
|
|
20
|
+
}
|
|
21
|
+
if (pub) {
|
|
22
|
+
cols.status = e.table[propOf(pub.field, e.fields[pub.field]!)]
|
|
23
|
+
if (pub.dateField) cols.publishAt = e.table[propOf(pub.dateField, e.fields[pub.dateField]!)]
|
|
24
|
+
}
|
|
25
|
+
const rows: any[] = await db.select(cols).from(e.table).where(rowFilter)
|
|
26
|
+
const nodes = await loadTreeNodes(db, reg, e)
|
|
27
|
+
const index = indexTree(nodes)
|
|
28
|
+
// An address is made of the address parts of every page above: where one of them is a page this
|
|
29
|
+
// person may not read, its part (and so the address) is not told.
|
|
30
|
+
const readable = rowFilter ? new Set(rows.map((r) => r.id)) : null
|
|
31
|
+
const seesChain = (id: string) => !readable || chainOf(index, id).every((n) => readable.has(n.id))
|
|
32
|
+
const avail = reg.locales && e.localized.length ? await availableLocales(db, reg, e, rows.map((r) => r.id)) : null
|
|
33
|
+
return {
|
|
34
|
+
maxDepth: e.tree.maxDepth,
|
|
35
|
+
rows: rows.map((r) => {
|
|
36
|
+
const paths: Record<string, string> = {}
|
|
37
|
+
if (seesChain(r.id)) for (const v of treeVersions(reg, e, index, r.id)) paths[v.locale ?? ''] = v.loc
|
|
38
|
+
return { ...r, onSite: !!r.onSite, paths, locales: avail?.get(r.id) ?? null }
|
|
39
|
+
}),
|
|
40
|
+
}
|
|
41
|
+
})
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { and, asc, desc, eq, gte, inArray, isNotNull, isNull, lte, ne, not, or, propOf, sql } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
export default defineEventHandler(async (event) => {
|
|
4
|
+
const { db, reg } = useCms()
|
|
5
|
+
const user = requireCmsUser(event)
|
|
6
|
+
const e = getEntity(reg, getRouterParam(event, 'entity'))
|
|
7
|
+
const rowFilter = authorize(e, 'read', user)
|
|
8
|
+
|
|
9
|
+
const query = getQuery(event)
|
|
10
|
+
const page = Math.max(1, Number(query.page) || 1)
|
|
11
|
+
const limit = Math.min(100, Math.max(1, Number(query.limit) || 20))
|
|
12
|
+
const dir = query.dir === 'asc' ? asc : desc
|
|
13
|
+
const sortKey = String(query.sort ?? 'createdAt')
|
|
14
|
+
const sortCol = e.table[sortKey] ?? e.table[`${sortKey}Id`] ?? e.table.createdAt
|
|
15
|
+
|
|
16
|
+
// Search, filters and status tabs: the same conditions the CSV export uses.
|
|
17
|
+
const conds = listConditions(e, reg, query, rowFilter)
|
|
18
|
+
const where = conds.length ? and(...conds) : undefined
|
|
19
|
+
|
|
20
|
+
// Ties (and empty values, last) in a fixed order, so pages never repeat or skip rows.
|
|
21
|
+
// Text in the content's language order ("Č" after "C"); else the admin's language.
|
|
22
|
+
const orderCol = await collated(db, sortCol, reg.locales?.default ?? getCookie(event, 'cms_admin_locale'))
|
|
23
|
+
const rows: any[] = await db.select().from(e.table).where(where)
|
|
24
|
+
.orderBy(sql`${orderCol} ${dir === asc ? sql`asc` : sql`desc`} nulls last`, desc(e.table.createdAt), asc(e.table.id))
|
|
25
|
+
.limit(limit).offset((page - 1) * limit)
|
|
26
|
+
const [counted] = await db.select({ count: sql<number>`count(*)::int` }).from(e.table).where(where)
|
|
27
|
+
const count = counted?.count ?? 0
|
|
28
|
+
// Blocks and lists in the shape the code knows (the list shows counts and excerpts of them).
|
|
29
|
+
for (const r of rows) upgradeStoredJson(e, r, { admin: true })
|
|
30
|
+
|
|
31
|
+
// populate to-one relation labels
|
|
32
|
+
for (const [key, fld] of Object.entries(e.fields)) {
|
|
33
|
+
if (fld.relation?.kind !== 'many-to-one') continue
|
|
34
|
+
const target = reg.byName.get(fld.relation.to().name)!
|
|
35
|
+
const ids = [...new Set(rows.map((r) => r[`${key}Id`]).filter(Boolean))]
|
|
36
|
+
if (!ids.length) continue
|
|
37
|
+
// Only titles this person may read (the related collection's own rules).
|
|
38
|
+
const access = accessWhere(target, 'read', user)
|
|
39
|
+
if (!access.allowed) continue
|
|
40
|
+
const targets: any[] = await db.select().from(target.table).where(both(inArray(target.table.id, ids), access.where))
|
|
41
|
+
const labels = new Map(targets.map((t) => [t.id, t[target.titleField]]))
|
|
42
|
+
for (const r of rows) r[`${key}__label`] = labels.get(r[`${key}Id`]) ?? null
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// populate media thumbnails for any media column shown in the list
|
|
46
|
+
for (const [key, fld] of Object.entries(e.fields)) {
|
|
47
|
+
if (fld.type !== 'media') continue
|
|
48
|
+
const ids = [...new Set(rows.map((r) => r[`${key}Id`]).filter(Boolean))]
|
|
49
|
+
if (!ids.length) continue
|
|
50
|
+
const items: any[] = await db.select().from(reg.cmsMedia).where(inArray(reg.cmsMedia.id, ids))
|
|
51
|
+
const byId = new Map(items.map((m) => [m.id, m]))
|
|
52
|
+
for (const r of rows) r[`${key}__media`] = byId.get(r[`${key}Id`]) ?? null
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Which languages each row is available in (for the list's language column).
|
|
56
|
+
if (reg.locales && e.localized.length) {
|
|
57
|
+
const avail = await availableLocales(db, reg, e, rows.map((r) => r.id))
|
|
58
|
+
for (const r of rows) r.__locales = avail.get(r.id) ?? [reg.locales.default]
|
|
59
|
+
}
|
|
60
|
+
return { rows, total: count, page, limit }
|
|
61
|
+
})
|
|
62
|
+
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export default defineEventHandler(async (event) => {
|
|
2
|
+
const { db, reg } = useCms()
|
|
3
|
+
const user = requireCmsUser(event)
|
|
4
|
+
const e = getEntity(reg, getRouterParam(event, 'entity'))
|
|
5
|
+
if (e.singleton) throw createError({ statusCode: 404, statusMessage: 'Use PUT /api/cms/_singleton/:name' })
|
|
6
|
+
authorize(e, 'create', user)
|
|
7
|
+
|
|
8
|
+
const body = await readBody(event)
|
|
9
|
+
const data = parseOr422(writeSchema(e, 'create'), body)
|
|
10
|
+
await assertMediaAccepted(db, reg, e, data)
|
|
11
|
+
const { values, m2m } = splitPayload(e, data)
|
|
12
|
+
assertPublishAllowed(e, user, values)
|
|
13
|
+
await assertNoRedirectLoop(e, values)
|
|
14
|
+
stampPublishDate(e, values, null)
|
|
15
|
+
values.createdBy = actorId(user)
|
|
16
|
+
values.updatedBy = actorId(user)
|
|
17
|
+
|
|
18
|
+
const row = await db.transaction(async (tx: any) => {
|
|
19
|
+
// A page tree: the address under its parent must be free, the tree no deeper than allowed;
|
|
20
|
+
// a new page goes last among its siblings unless a position was asked for.
|
|
21
|
+
if (e.tree) {
|
|
22
|
+
const p = treeProps(e)
|
|
23
|
+
values.id = crypto.randomUUID()
|
|
24
|
+
const { nodes } = await beginTreeWrite(tx, reg, e, { id: values.id, parentId: values[p.parent] ?? null, slug: String(values[p.slug] ?? ''), title: String(values[p.title] ?? '') }, user)
|
|
25
|
+
if (!body || typeof body !== 'object' || !(e.tree.order in body)) values[p.order] = nextPosition(nodes, values[p.parent] ?? null)
|
|
26
|
+
}
|
|
27
|
+
const [created] = await tx.insert(e.table).values(values).returning()
|
|
28
|
+
await writeM2M(tx, reg, e, created.id, m2m)
|
|
29
|
+
// A redirect away from the address the new entry is live at would loop: gone, in the same transaction.
|
|
30
|
+
await dropRedirectsFromLiveAddresses(tx, reg, e, created.id)
|
|
31
|
+
return created
|
|
32
|
+
}).catch((err: unknown) => rethrowDbError(err, e, 'write'))
|
|
33
|
+
await audit(event, 'entry.create', { entity: e.name, recordId: row.id })
|
|
34
|
+
if (publishAction(e, null, row) === 'entry.publish') await audit(event, 'entry.publish', { entity: e.name, recordId: row.id })
|
|
35
|
+
await reportChange(event, { type: 'entry.created', entity: e, id: row.id, after: row })
|
|
36
|
+
setResponseStatus(event, 201)
|
|
37
|
+
return { row }
|
|
38
|
+
})
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { chainOf, depthOf, heightOf, ilike, indexTree, inArray, notInArray, titleIn } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// Relation-picker typeahead: GET /api/cms/:entity/options?q=&selected=id,id
|
|
4
|
+
export default defineEventHandler(async (event) => {
|
|
5
|
+
const { db, reg } = useCms()
|
|
6
|
+
const user = requireCmsUser(event)
|
|
7
|
+
const e = getEntity(reg, getRouterParam(event, 'entity'))
|
|
8
|
+
// Only entries this person may read (row rules included) — titles must not leak.
|
|
9
|
+
const rowFilter = authorize(e, 'read', user)
|
|
10
|
+
|
|
11
|
+
const query = getQuery(event)
|
|
12
|
+
const q = String(query.q ?? '').trim()
|
|
13
|
+
const selected = String(query.selected ?? '').split(',').filter(Boolean)
|
|
14
|
+
|
|
15
|
+
// A page tree's parent picker: not the page itself nor anything below it (that would be a loop),
|
|
16
|
+
// and not a page with no room left under it (the page and what it carries would be nested too deep).
|
|
17
|
+
// `exclude` is the page being edited; `placing=1` a new one.
|
|
18
|
+
let excluded: string[] = []
|
|
19
|
+
const exclude = String(query.exclude ?? '')
|
|
20
|
+
const placing = /^[0-9a-f-]{36}$/i.test(exclude) || query.placing === '1'
|
|
21
|
+
if (e.tree && placing) {
|
|
22
|
+
const nodes = await loadTreeNodes(db, reg, e)
|
|
23
|
+
const index = indexTree(nodes)
|
|
24
|
+
const own = /^[0-9a-f-]{36}$/i.test(exclude) ? exclude : null
|
|
25
|
+
excluded = own ? subtreeIds(nodes, own) : []
|
|
26
|
+
const carried = own && index.has(own) ? heightOf(index, own) : 0
|
|
27
|
+
for (const n of nodes) if (depthOf(index, n.id) + 1 + carried > e.tree.maxDepth) excluded.push(n.id)
|
|
28
|
+
}
|
|
29
|
+
const notExcluded = excluded.length ? notInArray(e.table.id, excluded) : undefined
|
|
30
|
+
|
|
31
|
+
const esc = q.replace(/[\\%_]/g, (c) => '\\' + c)
|
|
32
|
+
const found: any[] = q
|
|
33
|
+
? await db.select().from(e.table).where(both(both(ilike(e.table[e.titleField], '%' + esc + '%'), rowFilter), notExcluded)).limit(20)
|
|
34
|
+
: await db.select().from(e.table).where(both(rowFilter, notExcluded)).limit(20)
|
|
35
|
+
|
|
36
|
+
// always union in already-selected rows so saved chips show labels, not uuids
|
|
37
|
+
const have = new Set(found.map((r) => r.id))
|
|
38
|
+
const missing = selected.filter((id) => !have.has(id))
|
|
39
|
+
if (missing.length) {
|
|
40
|
+
const extra: any[] = await db.select().from(e.table).where(both(inArray(e.table.id, missing.filter((id) => /^[0-9a-f-]{36}$/i.test(id))), rowFilter))
|
|
41
|
+
found.push(...extra)
|
|
42
|
+
}
|
|
43
|
+
// A page tree: a page is named by its trail ("About us / Team"), so two pages called alike can be told apart.
|
|
44
|
+
// A page above it that this person may not read is "…", not its title.
|
|
45
|
+
if (e.tree) {
|
|
46
|
+
const index = indexTree(await loadTreeNodes(db, reg, e))
|
|
47
|
+
const readable = await readableTreeIds(db, e, user)
|
|
48
|
+
const def = reg.locales?.default ?? null
|
|
49
|
+
return found.map((r) => ({
|
|
50
|
+
id: r.id,
|
|
51
|
+
label: chainOf(index, r.id).map((n) => (n.id === r.id ? titleIn(n, null, def) || r[e.titleField] : readable && !readable.has(n.id) ? '…' : titleIn(n, null, def) || '…')).join(' / ') || r[e.titleField],
|
|
52
|
+
}))
|
|
53
|
+
}
|
|
54
|
+
return found.map((r) => ({ id: r.id, label: r[e.titleField] }))
|
|
55
|
+
})
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { and, eq, isNull } from 'tinyzoo'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
// POST /api/cms/_auth/accept — accept an invitation: choose a name and password, and
|
|
5
|
+
// sign in.
|
|
6
|
+
const body = z.object({ token: z.string().min(1).max(200), name: z.string().trim().min(1).max(120), password: passwordSchema })
|
|
7
|
+
|
|
8
|
+
export default defineEventHandler(async (event) => {
|
|
9
|
+
assertBuiltinAuth()
|
|
10
|
+
if (!(await rateLimit(`accept:ip:${clientIp(event)}`, 20, 15 * 60_000))) throw tooManyRequests(event, 'Too many attempts; try again later', 15 * 60_000)
|
|
11
|
+
const data = parseOr422(body, await readBody(event))
|
|
12
|
+
const { db, reg } = useCms()
|
|
13
|
+
const found = await findToken(db, reg, data.token, 'invite')
|
|
14
|
+
if (!found || found.user.status !== 'invited') {
|
|
15
|
+
throw createError({ statusCode: 410, statusMessage: 'This invitation has expired or was already used' })
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const passwordHash = await hashPassword(data.password)
|
|
19
|
+
const user = await db.transaction(async (tx: any) => {
|
|
20
|
+
// Claim the link atomically: of two simultaneous requests only one gets the row.
|
|
21
|
+
const [claimed] = await tx.update(reg.cmsTokens).set({ usedAt: new Date() })
|
|
22
|
+
.where(and(eq(reg.cmsTokens.id, found.token.id), isNull(reg.cmsTokens.usedAt))).returning({ id: reg.cmsTokens.id })
|
|
23
|
+
if (!claimed) throw createError({ statusCode: 410, statusMessage: 'This link has expired or was already used' })
|
|
24
|
+
const [u] = await tx.update(reg.cmsUsers)
|
|
25
|
+
.set({ name: data.name, passwordHash, status: 'active', updatedAt: new Date(), lastLoginAt: new Date() })
|
|
26
|
+
.where(eq(reg.cmsUsers.id, found.user.id)).returning()
|
|
27
|
+
return u
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
await startCmsSession(event, user)
|
|
31
|
+
await audit(event, 'auth.invite_accept', { userId: user.id })
|
|
32
|
+
return { user: sessionUser(user) }
|
|
33
|
+
})
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { eq } from 'tinyzoo'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
// POST /api/cms/_auth/forgot — email a password-reset link. Always the same answer,
|
|
5
|
+
// at the same speed, whether or not the address has an account: the lookup, token
|
|
6
|
+
// and email happen after the response (event.waitUntil), so neither the reply nor
|
|
7
|
+
// its timing tells who has an account.
|
|
8
|
+
const body = z.object({ email: z.string().trim().toLowerCase().max(320) })
|
|
9
|
+
|
|
10
|
+
export default defineEventHandler(async (event) => {
|
|
11
|
+
assertBuiltinAuth()
|
|
12
|
+
const { email } = parseOr422(body, await readBody(event))
|
|
13
|
+
if (!(await rateLimit(`forgot:ip:${clientIp(event)}`, 10, 60 * 60_000)) || !(await rateLimit(`forgot:email:${email}`, 3, 60 * 60_000))) {
|
|
14
|
+
throw tooManyRequests(event, 'Too many requests; try again later', 60 * 60_000)
|
|
15
|
+
}
|
|
16
|
+
// Resolved now, while the request is alive (it needs the configured public URL, and the
|
|
17
|
+
// language of the person asking, for an account that never saved one).
|
|
18
|
+
const asked = requestLocale(event)
|
|
19
|
+
let linkBase: string | null = null
|
|
20
|
+
try {
|
|
21
|
+
linkBase = adminLink(event, '/admin/reset/')
|
|
22
|
+
}
|
|
23
|
+
catch (err) {
|
|
24
|
+
console.error('[cms] password reset links need cms.publicUrl', redactEmails(safeErrorMessage(err)))
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const work = (async () => {
|
|
28
|
+
if (!linkBase || isDemoAccount(email)) return // the demo account's password is public
|
|
29
|
+
const { db, reg } = useCms()
|
|
30
|
+
const [user] = await db.select().from(reg.cmsUsers).where(eq(reg.cmsUsers.email, email))
|
|
31
|
+
if (!user || user.status !== 'active') return
|
|
32
|
+
const secret = await issueToken(db, reg, { userId: user.id, kind: 'reset', ttlMs: RESET_TTL_MS })
|
|
33
|
+
await sendCmsMail(resetEmail({ to: user.email, url: linkBase + secret, locale: user.locale || asked }))
|
|
34
|
+
await audit(event, 'auth.reset_request', { userId: user.id })
|
|
35
|
+
})().catch((err) => console.error('[cms] could not send the password reset email', redactEmails(safeErrorMessage(err))))
|
|
36
|
+
|
|
37
|
+
event.waitUntil(work)
|
|
38
|
+
return { ok: true }
|
|
39
|
+
})
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { eq } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// GET /api/cms/_auth/invite/:token — what the accept page shows: who is invited and
|
|
4
|
+
// by whom. 410 when the link is no longer valid.
|
|
5
|
+
export default defineEventHandler(async (event) => {
|
|
6
|
+
assertBuiltinAuth()
|
|
7
|
+
const { db, reg } = useCms()
|
|
8
|
+
const found = await findToken(db, reg, getRouterParam(event, 'token') ?? '', 'invite')
|
|
9
|
+
if (!found || found.user.status !== 'invited') {
|
|
10
|
+
throw createError({ statusCode: 410, statusMessage: 'This invitation has expired or was already used' })
|
|
11
|
+
}
|
|
12
|
+
let inviter: string | null = null
|
|
13
|
+
if (found.token.createdBy) {
|
|
14
|
+
const [by] = await db.select({ name: reg.cmsUsers.name, email: reg.cmsUsers.email }).from(reg.cmsUsers).where(eq(reg.cmsUsers.id, found.token.createdBy))
|
|
15
|
+
inviter = by ? (by.name || by.email) : null
|
|
16
|
+
}
|
|
17
|
+
return { email: found.user.email, name: found.user.name, role: found.user.role, inviter }
|
|
18
|
+
})
|