tinyzoo 0.0.0-stage → 0.2.0
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 +99 -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 +392 -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/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 +197 -0
- package/server/utils/cmsWebhooks.ts +101 -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,392 @@
|
|
|
1
|
+
import { eq, inArray, type CmsChange } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Realtime for the admin: who else is looking at (or editing) the same content, and
|
|
5
|
+
* what changed while you were looking. One WebSocket per admin tab
|
|
6
|
+
* (/api/cms/_live, see api/cms/_live.ts) watches a few topics:
|
|
7
|
+
*
|
|
8
|
+
* list:<entity> a collection's list
|
|
9
|
+
* entry:<entity>:<id> one entry (or a global's row)
|
|
10
|
+
*
|
|
11
|
+
* Identity comes from the signed session checked at connect time, never from what a
|
|
12
|
+
* browser says about itself, and is re-checked every heartbeat (a disabled account or
|
|
13
|
+
* a password change drops the socket). Watching a topic needs read access to it.
|
|
14
|
+
*
|
|
15
|
+
* Several replicas: presence is shared over the store's `live` channel. Each
|
|
16
|
+
* instance announces its own people when they change and again every heartbeat;
|
|
17
|
+
* others forget an announcement that was not repeated in time (a crashed replica's
|
|
18
|
+
* people disappear on their own). Content changes arrive through onCmsChange, which
|
|
19
|
+
* already covers changes saved on other replicas.
|
|
20
|
+
*
|
|
21
|
+
* Server → browser messages:
|
|
22
|
+
* { type: 'presence', topic, people: [{ id, name, editing }] } (including you)
|
|
23
|
+
* { type: 'change', topic, change: { type, entity, id, locale, by, byName, at } }
|
|
24
|
+
* { type: 'error', topic?, message }
|
|
25
|
+
* Browser → server:
|
|
26
|
+
* { type: 'watch' | 'unwatch', topic }
|
|
27
|
+
* { type: 'editing', topic, editing: boolean }
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/** The bits of a crossws peer this hub uses (crossws is not a direct dependency). */
|
|
31
|
+
export interface LiveSocket {
|
|
32
|
+
id: string
|
|
33
|
+
send: (data: string) => unknown
|
|
34
|
+
close: (code?: number, reason?: string) => void
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface Person { id: string; name: string; editing: boolean }
|
|
38
|
+
/**
|
|
39
|
+
* `rowFiltered`: the person may read only some rows of this collection — list
|
|
40
|
+
* changes reach them without ids, and an entry watch is re-checked every heartbeat.
|
|
41
|
+
*/
|
|
42
|
+
interface Watch { editing: boolean; rowFiltered: boolean }
|
|
43
|
+
interface LocalPeer {
|
|
44
|
+
socket: LiveSocket
|
|
45
|
+
user: CmsUser
|
|
46
|
+
sv: number
|
|
47
|
+
topics: Map<string, Watch>
|
|
48
|
+
/** Messages are handled one at a time, in order. */
|
|
49
|
+
queue: Promise<void>
|
|
50
|
+
openedAt: number
|
|
51
|
+
/** Last sign of life (any message, including the answer to our ping). */
|
|
52
|
+
seenAt: number
|
|
53
|
+
/** Messages in the current rate window. */
|
|
54
|
+
burst: { at: number; n: number }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const LIVE_CHANNEL = 'live'
|
|
58
|
+
const HEARTBEAT_MS = 20_000
|
|
59
|
+
const REMOTE_TTL_MS = 50_000
|
|
60
|
+
/** A socket that has not answered for this long is gone (sleeping laptop, dead network). */
|
|
61
|
+
const SILENT_MS = 65_000
|
|
62
|
+
/** Sockets are re-opened (and re-authorised) at least this often. */
|
|
63
|
+
const MAX_SOCKET_AGE_MS = 12 * 60 * 60_000
|
|
64
|
+
const MAX_TOPICS = 20
|
|
65
|
+
const MAX_MESSAGE = 1024
|
|
66
|
+
const MAX_SOCKETS_PER_USER = 10
|
|
67
|
+
const RATE_WINDOW_MS = 10_000
|
|
68
|
+
const RATE_MAX = 60
|
|
69
|
+
|
|
70
|
+
const local = new Map<string, LocalPeer>()
|
|
71
|
+
/** topic → `${instance}:${peer}` → what another replica said about one of its peers. */
|
|
72
|
+
const remote = new Map<string, Map<string, { person: Person; at: number }>>()
|
|
73
|
+
|
|
74
|
+
let started: Promise<void> | null = null
|
|
75
|
+
let timer: ReturnType<typeof setInterval> | null = null
|
|
76
|
+
let stopChanges: (() => void) | null = null
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Start listening to other replicas and to content changes (once, on the first
|
|
80
|
+
* connection). Runs in the background: a slow or absent Redis never holds up a
|
|
81
|
+
* socket — presence then stays on this instance until it is back.
|
|
82
|
+
*/
|
|
83
|
+
function start(): void {
|
|
84
|
+
if (started) return
|
|
85
|
+
timer = setInterval(() => { void heartbeat() }, HEARTBEAT_MS)
|
|
86
|
+
;(timer as any).unref?.()
|
|
87
|
+
stopChanges = onCmsChange((change) => { void deliverChange(change).catch((err) => console.error('[cms] realtime delivery failed', scrubError(err))) })
|
|
88
|
+
started = (async () => {
|
|
89
|
+
const store = await useCmsStore()
|
|
90
|
+
await store.subscribe(LIVE_CHANNEL, (raw) => {
|
|
91
|
+
try {
|
|
92
|
+
onRemote(JSON.parse(raw))
|
|
93
|
+
}
|
|
94
|
+
catch { /* not ours */ }
|
|
95
|
+
})
|
|
96
|
+
})().catch((err) => console.error('[cms] realtime cannot hear other instances', scrubError(err)))
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Stop timers and listeners (server shutdown, dev reload). */
|
|
100
|
+
export function stopLive(): void {
|
|
101
|
+
if (timer) clearInterval(timer)
|
|
102
|
+
timer = null
|
|
103
|
+
stopChanges?.()
|
|
104
|
+
stopChanges = null
|
|
105
|
+
started = null
|
|
106
|
+
for (const p of local.values()) p.socket.close(1001, 'Server shutting down')
|
|
107
|
+
local.clear()
|
|
108
|
+
remote.clear()
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ── connections ──
|
|
112
|
+
|
|
113
|
+
export function liveOpen(socket: LiveSocket, user: CmsUser, sv: number): void {
|
|
114
|
+
const mine = [...local.values()].filter((p) => p.user.id === user.id)
|
|
115
|
+
if (mine.length >= MAX_SOCKETS_PER_USER) {
|
|
116
|
+
// Too many tabs: the oldest one gives way.
|
|
117
|
+
const oldest = mine.sort((x, y) => x.openedAt - y.openedAt)[0]!
|
|
118
|
+
oldest.socket.close(4429, 'Too many open tabs')
|
|
119
|
+
liveClose(oldest.socket)
|
|
120
|
+
}
|
|
121
|
+
const now = Date.now()
|
|
122
|
+
local.set(socket.id, { socket, user, sv, topics: new Map(), queue: Promise.resolve(), openedAt: now, seenAt: now, burst: { at: now, n: 0 } })
|
|
123
|
+
start()
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function liveClose(socket: LiveSocket): void {
|
|
127
|
+
const p = local.get(socket.id)
|
|
128
|
+
if (!p) return
|
|
129
|
+
local.delete(socket.id)
|
|
130
|
+
for (const topic of p.topics.keys()) {
|
|
131
|
+
void announce(topic, socket.id, null)
|
|
132
|
+
broadcastPresence(topic)
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function liveMessage(socket: LiveSocket, text: string): Promise<void> {
|
|
137
|
+
const p = local.get(socket.id)
|
|
138
|
+
if (!p) return Promise.resolve()
|
|
139
|
+
const now = Date.now()
|
|
140
|
+
p.seenAt = now
|
|
141
|
+
if (now - p.burst.at > RATE_WINDOW_MS) p.burst = { at: now, n: 0 }
|
|
142
|
+
if (++p.burst.n > RATE_MAX) {
|
|
143
|
+
socket.close(4408, 'Too many messages')
|
|
144
|
+
liveClose(socket)
|
|
145
|
+
return Promise.resolve()
|
|
146
|
+
}
|
|
147
|
+
p.queue = p.queue.then(() => handle(p, text)).catch((err) => console.error('[cms] realtime message failed', scrubError(err)))
|
|
148
|
+
return p.queue
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function handle(p: LocalPeer, text: string): Promise<void> {
|
|
152
|
+
if (!local.has(p.socket.id)) return // closed meanwhile
|
|
153
|
+
if (text.length > MAX_MESSAGE) return send(p, { type: 'error', message: 'Message too large' })
|
|
154
|
+
let msg: any
|
|
155
|
+
try {
|
|
156
|
+
msg = JSON.parse(text)
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
return
|
|
160
|
+
}
|
|
161
|
+
if (msg?.type === 'pong') return
|
|
162
|
+
const topic = typeof msg?.topic === 'string' ? msg.topic : ''
|
|
163
|
+
if (msg?.type === 'watch') {
|
|
164
|
+
if (p.topics.has(topic)) return broadcastPresence(topic)
|
|
165
|
+
if (p.topics.size >= MAX_TOPICS) return send(p, { type: 'error', topic, message: 'Watching too many things at once' })
|
|
166
|
+
const access = await mayWatch(p.user, topic)
|
|
167
|
+
if (!access) return send(p, { type: 'error', topic, message: 'Not found or not permitted' })
|
|
168
|
+
if (!local.has(p.socket.id) || p.topics.size >= MAX_TOPICS) return
|
|
169
|
+
// `editing` may come with the watch (a tab with unsaved changes reconnecting).
|
|
170
|
+
p.topics.set(topic, { editing: msg.editing === true, rowFiltered: access.rowFiltered })
|
|
171
|
+
void announce(topic, p.socket.id, personOf(p, topic))
|
|
172
|
+
broadcastPresence(topic)
|
|
173
|
+
}
|
|
174
|
+
else if (msg?.type === 'unwatch') {
|
|
175
|
+
if (!p.topics.delete(topic)) return
|
|
176
|
+
void announce(topic, p.socket.id, null)
|
|
177
|
+
broadcastPresence(topic)
|
|
178
|
+
}
|
|
179
|
+
else if (msg?.type === 'editing') {
|
|
180
|
+
const w = p.topics.get(topic)
|
|
181
|
+
if (!w || w.editing === !!msg.editing) return
|
|
182
|
+
w.editing = !!msg.editing
|
|
183
|
+
void announce(topic, p.socket.id, personOf(p, topic))
|
|
184
|
+
broadcastPresence(topic)
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// ── topics and access ──
|
|
189
|
+
|
|
190
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
191
|
+
|
|
192
|
+
export function parseTopic(topic: string): { kind: 'list' | 'entry'; entity: string; id?: string } | null {
|
|
193
|
+
const m = /^(list|entry):([a-zA-Z][\w-]{0,63})(?::([0-9a-fA-F-]{36}))?$/.exec(topic)
|
|
194
|
+
if (!m) return null
|
|
195
|
+
if (m[1] === 'list' && m[3]) return null
|
|
196
|
+
if (m[1] === 'entry' && !(m[3] && UUID.test(m[3]))) return null
|
|
197
|
+
return { kind: m[1] as 'list' | 'entry', entity: m[2]!, id: m[3]?.toLowerCase() }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** May this person watch the topic: read access to the collection, and to the row for an entry. */
|
|
201
|
+
async function mayWatch(user: CmsUser, topic: string): Promise<{ rowFiltered: boolean } | null> {
|
|
202
|
+
const t = parseTopic(topic)
|
|
203
|
+
if (!t || topic !== (t.kind === 'list' ? `list:${t.entity}` : `entry:${t.entity}:${t.id}`)) return null
|
|
204
|
+
try {
|
|
205
|
+
const { db, reg } = useCms()
|
|
206
|
+
const e = reg.byName.get(t.entity)
|
|
207
|
+
if (!e) return null
|
|
208
|
+
const rowFilter = authorize(e, 'read', user)
|
|
209
|
+
if (t.kind === 'list') return { rowFiltered: rowFilter !== undefined }
|
|
210
|
+
const [row] = await db.select({ id: e.table.id }).from(e.table).where(both(eq(e.table.id, t.id!), rowFilter))
|
|
211
|
+
return row ? { rowFiltered: rowFilter !== undefined } : null
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
return null
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// ── presence ──
|
|
219
|
+
|
|
220
|
+
/** How colleagues see someone: their name, never their full email address. */
|
|
221
|
+
export function displayName(name?: string | null, email?: string | null): string {
|
|
222
|
+
return name?.trim() || (email ? email.split('@')[0]! : '')
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const personOf = (p: LocalPeer, topic: string): Person => ({ id: p.user.id, name: displayName(p.user.name, p.user.email), editing: !!p.topics.get(topic)?.editing })
|
|
226
|
+
|
|
227
|
+
/** Everyone on a topic, one entry per person (several tabs: editing if any tab is). */
|
|
228
|
+
export function presenceOf(topic: string): Person[] {
|
|
229
|
+
const byId = new Map<string, Person>()
|
|
230
|
+
const add = (person: Person) => {
|
|
231
|
+
const seen = byId.get(person.id)
|
|
232
|
+
if (seen) seen.editing ||= person.editing
|
|
233
|
+
else byId.set(person.id, { ...person })
|
|
234
|
+
}
|
|
235
|
+
for (const p of local.values()) if (p.topics.has(topic)) add(personOf(p, topic))
|
|
236
|
+
const now = Date.now()
|
|
237
|
+
for (const { person, at } of remote.get(topic)?.values() ?? []) if (now - at < REMOTE_TTL_MS) add(person)
|
|
238
|
+
return [...byId.values()].sort((a, b) => a.name.localeCompare(b.name))
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function broadcastPresence(topic: string): void {
|
|
242
|
+
const people = presenceOf(topic)
|
|
243
|
+
for (const p of local.values()) if (p.topics.has(topic)) send(p, { type: 'presence', topic, people })
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
let lastAnnounceError = 0
|
|
247
|
+
|
|
248
|
+
async function announce(topic: string, peerId: string, person: Person | null): Promise<void> {
|
|
249
|
+
try {
|
|
250
|
+
const store = await useCmsStore()
|
|
251
|
+
await store.publish(LIVE_CHANNEL, JSON.stringify({ origin: instanceId(), topic, peer: peerId, person }))
|
|
252
|
+
}
|
|
253
|
+
catch (err) {
|
|
254
|
+
// One line a minute is enough while Redis is down.
|
|
255
|
+
if (Date.now() - lastAnnounceError > 60_000) {
|
|
256
|
+
lastAnnounceError = Date.now()
|
|
257
|
+
console.error('[cms] realtime announce failed', safeErrorMessage(err))
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function onRemote(msg: any): void {
|
|
263
|
+
if (!msg || msg.origin === instanceId() || typeof msg.topic !== 'string' || typeof msg.peer !== 'string') return
|
|
264
|
+
if (!parseTopic(msg.topic)) return
|
|
265
|
+
const key = `${msg.origin}:${msg.peer}`
|
|
266
|
+
let map = remote.get(msg.topic)
|
|
267
|
+
const person = msg.person
|
|
268
|
+
if (person && typeof person.id === 'string' && typeof person.name === 'string') {
|
|
269
|
+
if (!map) remote.set(msg.topic, map = new Map())
|
|
270
|
+
const before = map.get(key)?.person
|
|
271
|
+
map.set(key, { person: { id: person.id, name: person.name, editing: !!person.editing }, at: Date.now() })
|
|
272
|
+
// A repeat of the same announcement (heartbeat) changes nothing anyone sees.
|
|
273
|
+
if (before && before.id === person.id && before.editing === !!person.editing) return
|
|
274
|
+
}
|
|
275
|
+
else {
|
|
276
|
+
if (!map?.delete(key)) return
|
|
277
|
+
if (!map.size) remote.delete(msg.topic)
|
|
278
|
+
}
|
|
279
|
+
broadcastPresence(msg.topic)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Every heartbeat: repeat our people to the other replicas, forget theirs that went
|
|
284
|
+
* quiet, and drop sockets whose account may no longer be used.
|
|
285
|
+
*/
|
|
286
|
+
async function heartbeat(): Promise<void> {
|
|
287
|
+
const now0 = Date.now()
|
|
288
|
+
for (const p of [...local.values()]) {
|
|
289
|
+
// Gone quiet (no answer to the last pings) or open too long: drop it — a live
|
|
290
|
+
// browser reconnects at once, and is authorised afresh.
|
|
291
|
+
if (now0 - p.seenAt > SILENT_MS || now0 - p.openedAt > MAX_SOCKET_AGE_MS) {
|
|
292
|
+
p.socket.close(4000, 'Reconnect')
|
|
293
|
+
liveClose(p.socket)
|
|
294
|
+
continue
|
|
295
|
+
}
|
|
296
|
+
// Keeps proxies from closing an idle socket, and asks for a sign of life.
|
|
297
|
+
send(p, { type: 'ping' })
|
|
298
|
+
}
|
|
299
|
+
for (const [id, p] of local) for (const topic of p.topics.keys()) void announce(topic, id, personOf(p, topic))
|
|
300
|
+
const now = Date.now()
|
|
301
|
+
for (const [topic, map] of remote) {
|
|
302
|
+
let changed = false
|
|
303
|
+
for (const [key, v] of map) if (now - v.at >= REMOTE_TTL_MS) { map.delete(key); changed = true }
|
|
304
|
+
if (!map.size) remote.delete(topic)
|
|
305
|
+
if (changed) broadcastPresence(topic)
|
|
306
|
+
}
|
|
307
|
+
await recheckAccounts().catch((err) => console.error('[cms] realtime account check failed', scrubError(err)))
|
|
308
|
+
await recheckRowWatches().catch((err) => console.error('[cms] realtime access check failed', scrubError(err)))
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Entry watches under a row rule (authors' own entries): still allowed? */
|
|
312
|
+
async function recheckRowWatches(): Promise<void> {
|
|
313
|
+
for (const p of [...local.values()]) {
|
|
314
|
+
for (const [topic, w] of [...p.topics]) {
|
|
315
|
+
if (!w.rowFiltered || !topic.startsWith('entry:')) continue
|
|
316
|
+
if (await mayWatch(p.user, topic)) continue
|
|
317
|
+
if (!p.topics.delete(topic)) continue
|
|
318
|
+
send(p, { type: 'error', topic, message: 'Not found or not permitted' })
|
|
319
|
+
void announce(topic, p.socket.id, null)
|
|
320
|
+
broadcastPresence(topic)
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
async function recheckAccounts(): Promise<void> {
|
|
326
|
+
const ids = [...new Set([...local.values()].map((p) => p.user.id))]
|
|
327
|
+
if (!ids.length) return
|
|
328
|
+
const { db, reg } = useCms()
|
|
329
|
+
const rows: any[] = await db.select({ id: reg.cmsUsers.id, status: reg.cmsUsers.status, sv: reg.cmsUsers.sessionVersion, role: reg.cmsUsers.role })
|
|
330
|
+
.from(reg.cmsUsers).where(inArray(reg.cmsUsers.id, ids))
|
|
331
|
+
const byId = new Map(rows.map((r) => [r.id, r]))
|
|
332
|
+
for (const p of [...local.values()]) {
|
|
333
|
+
const u = byId.get(p.user.id)
|
|
334
|
+
// A changed role reconnects too, so watches are re-authorised under the new one.
|
|
335
|
+
if (!u || u.status !== 'active' || u.sv !== p.sv || u.role !== p.user.role) {
|
|
336
|
+
p.socket.close(4401, 'Session no longer valid')
|
|
337
|
+
liveClose(p.socket)
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// ── content changes ──
|
|
343
|
+
|
|
344
|
+
const names = new Map<string, { name: string; at: number }>()
|
|
345
|
+
|
|
346
|
+
async function nameOf(userId: string | null): Promise<string | null> {
|
|
347
|
+
if (!userId) return null
|
|
348
|
+
const hit = names.get(userId)
|
|
349
|
+
if (hit && Date.now() - hit.at < 60_000) return hit.name
|
|
350
|
+
try {
|
|
351
|
+
const { db, reg } = useCms()
|
|
352
|
+
const [u] = await db.select({ name: reg.cmsUsers.name, email: reg.cmsUsers.email }).from(reg.cmsUsers).where(eq(reg.cmsUsers.id, userId))
|
|
353
|
+
const name = u ? displayName(u.name, u.email) || null : null
|
|
354
|
+
if (name) names.set(userId, { name, at: Date.now() })
|
|
355
|
+
if (names.size > 500) names.clear()
|
|
356
|
+
return name
|
|
357
|
+
}
|
|
358
|
+
catch {
|
|
359
|
+
return null
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
async function deliverChange(change: CmsChange): Promise<void> {
|
|
364
|
+
const topics = [`list:${change.entity}`, `entry:${change.entity}:${change.id}`]
|
|
365
|
+
const recipients = [...local.values()].filter((p) => topics.some((t) => p.topics.has(t)))
|
|
366
|
+
if (!recipients.length) return
|
|
367
|
+
// Only what a watcher needs to react — not the public flag or website addresses.
|
|
368
|
+
const body = { type: change.type, entity: change.entity, id: change.id, locale: change.locale, version: change.version, by: change.by, byName: await nameOf(change.by), at: change.at }
|
|
369
|
+
for (const p of recipients) {
|
|
370
|
+
// Looked up again: the person may have stopped watching while we fetched the name.
|
|
371
|
+
if (p.topics.has(topics[1]!)) {
|
|
372
|
+
send(p, { type: 'change', topic: topics[1], change: body })
|
|
373
|
+
continue
|
|
374
|
+
}
|
|
375
|
+
const list = p.topics.get(topics[0]!)
|
|
376
|
+
if (!list) continue
|
|
377
|
+
// Someone who may read only some rows learns that the list changed, not which row.
|
|
378
|
+
send(p, { type: 'change', topic: topics[0], change: list.rowFiltered ? { ...body, id: null, version: null, by: null, byName: null } : body })
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function send(p: LocalPeer, msg: unknown): void {
|
|
383
|
+
try {
|
|
384
|
+
p.socket.send(JSON.stringify(msg))
|
|
385
|
+
}
|
|
386
|
+
catch { /* closing */ }
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** For tests and diagnostics. */
|
|
390
|
+
export function liveStats() {
|
|
391
|
+
return { sockets: local.size, remoteTopics: remote.size, running: !!timer }
|
|
392
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { and, eq, inArray } from 'tinyzoo'
|
|
2
|
+
import type { CmsEntity, CmsRegistry } from 'tinyzoo'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Content translations. Each entry's own row holds the default language; the
|
|
6
|
+
* `<entity>_locales` table holds one row per (entry, language) with the fields marked
|
|
7
|
+
* `.localized()`. Reading in a language overlays its non-empty values on the entry —
|
|
8
|
+
* anything untranslated falls back to the default language.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** Is `locale` a translation (a configured language other than the default)? */
|
|
12
|
+
export function isTranslationLocale(reg: CmsRegistry, locale: string | null | undefined): locale is string {
|
|
13
|
+
return !!reg.locales && !!locale && locale !== reg.locales.default && reg.locales.locales.includes(locale)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The configured language closest to what a caller wrote: an exact one first, then the
|
|
18
|
+
* same ignoring case ("EN"), then the same language without its region ("en-US" → "en",
|
|
19
|
+
* or "pt-BR" → "pt"); undefined when the site has no such language.
|
|
20
|
+
*/
|
|
21
|
+
export function closestLocale(configured: readonly string[], asked: string): string | undefined {
|
|
22
|
+
const wanted = asked.trim().replace(/_/g, '-').toLowerCase()
|
|
23
|
+
if (!wanted) return undefined
|
|
24
|
+
return configured.find((l) => l === asked)
|
|
25
|
+
?? configured.find((l) => l.toLowerCase() === wanted)
|
|
26
|
+
?? configured.find((l) => l.toLowerCase() === wanted.split('-')[0])
|
|
27
|
+
?? configured.find((l) => l.toLowerCase().split('-')[0] === wanted.split('-')[0])
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The language a request asks for (`?locale=`): null when content is single-language,
|
|
32
|
+
* the default when not given, the closest configured language for "en-US" or "EN" (a
|
|
33
|
+
* browser's language works as it is), 400 for a language the site does not have.
|
|
34
|
+
*/
|
|
35
|
+
export function requestedLocale(event: any, reg: CmsRegistry): string | null {
|
|
36
|
+
if (!reg.locales) return null
|
|
37
|
+
const raw = getQuery(event).locale
|
|
38
|
+
if (raw === undefined || raw === '') return reg.locales.default
|
|
39
|
+
const locale = String(raw)
|
|
40
|
+
const found = closestLocale(reg.locales.locales, locale)
|
|
41
|
+
if (!found) {
|
|
42
|
+
throw createError({ statusCode: 400, statusMessage: `Unknown language "${locale.slice(0, 20)}" (available: ${reg.locales.locales.join(', ')})` })
|
|
43
|
+
}
|
|
44
|
+
return found
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const isEmpty = (v: unknown): boolean => v === null || v === undefined || v === ''
|
|
48
|
+
|| (Array.isArray(v) && v.length === 0)
|
|
49
|
+
|| (typeof v === 'object' && v !== null && (v as any).type === 'doc'
|
|
50
|
+
// An empty editor saves one empty paragraph: still nothing written.
|
|
51
|
+
&& !((v as any).content ?? []).some((n: any) => n?.type !== 'paragraph' || n.content?.length))
|
|
52
|
+
// A group with nothing filled in (an object whose values are all empty): untranslated.
|
|
53
|
+
|| (typeof v === 'object' && v !== null && !Array.isArray(v) && (v as any).type !== 'doc' && Object.values(v).every((x) => typeof x !== 'boolean' && isEmpty(x)))
|
|
54
|
+
|
|
55
|
+
/** The translation rows of `ids` in `locale`, by parent id. */
|
|
56
|
+
export async function translationRows(db: any, e: CmsEntity, ids: string[], locale: string): Promise<Map<string, any>> {
|
|
57
|
+
const out = new Map<string, any>()
|
|
58
|
+
if (!e.localesTable || !ids.length) return out
|
|
59
|
+
const t = e.localesTable
|
|
60
|
+
const rows: any[] = await db.select().from(t).where(and(inArray(t.parentId, ids), eq(t.locale, locale)))
|
|
61
|
+
for (const r of rows) out.set(r.parentId, r)
|
|
62
|
+
return out
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Overlay `locale`'s non-empty translated values on `rows` (in place): per-field fallback. */
|
|
66
|
+
export async function overlayTranslations(db: any, reg: CmsRegistry, e: CmsEntity, rows: any[], locale: string | null): Promise<void> {
|
|
67
|
+
if (!isTranslationLocale(reg, locale) || !e.localized?.length || !rows.length) return
|
|
68
|
+
const byParent = await translationRows(db, e, rows.map((r) => r.id), locale)
|
|
69
|
+
for (const row of rows) {
|
|
70
|
+
const tr = byParent.get(row.id)
|
|
71
|
+
if (tr) mergeTranslation(e, row, tr)
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Put a translation row's non-empty values on `row` (in place): per-field fallback. */
|
|
76
|
+
export function mergeTranslation(e: CmsEntity, row: Record<string, any>, tr: Record<string, any>): Record<string, any> {
|
|
77
|
+
for (const key of e.localized) if (!isEmpty(tr[key])) row[key] = tr[key]
|
|
78
|
+
return row
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** For each id, the languages it is available in: the default plus every translation. */
|
|
82
|
+
export async function availableLocales(db: any, reg: CmsRegistry, e: CmsEntity, ids: string[]): Promise<Map<string, string[]>> {
|
|
83
|
+
const out = new Map<string, string[]>()
|
|
84
|
+
if (!reg.locales) return out
|
|
85
|
+
for (const id of ids) out.set(id, [reg.locales.default])
|
|
86
|
+
if (!e.localesTable || !ids.length) return out
|
|
87
|
+
const t = e.localesTable
|
|
88
|
+
const rows: any[] = await db.select({ parentId: t.parentId, locale: t.locale }).from(t).where(inArray(t.parentId, ids))
|
|
89
|
+
for (const r of rows) {
|
|
90
|
+
if (!reg.locales.locales.includes(r.locale)) continue
|
|
91
|
+
out.get(r.parentId)?.push(r.locale)
|
|
92
|
+
}
|
|
93
|
+
// Keep the configured order.
|
|
94
|
+
for (const [id, list] of out) out.set(id, reg.locales.locales.filter((l) => list.includes(l)))
|
|
95
|
+
return out
|
|
96
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { deliverMail } from '../mail/mailer'
|
|
2
|
+
|
|
3
|
+
export interface CmsMailMessage { to: string; subject: string; text: string; html: string; /** Where replies go (a form's sender). */ replyTo?: string }
|
|
4
|
+
export interface CmsMailConfig {
|
|
5
|
+
transport: 'smtp' | 'file' | 'log'
|
|
6
|
+
from: string
|
|
7
|
+
smtp: { host: string; port: number | string; secure: boolean; user: string; pass: string }
|
|
8
|
+
file: { dir: string }
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function cmsMailConfig(): CmsMailConfig {
|
|
12
|
+
const m = ((useRuntimeConfig().cms as any)?.mail ?? {}) as Partial<CmsMailConfig>
|
|
13
|
+
return {
|
|
14
|
+
transport: (m.transport as CmsMailConfig['transport']) || 'log',
|
|
15
|
+
from: m.from || 'CMS <no-reply@localhost>',
|
|
16
|
+
smtp: { host: '', port: 587, secure: false, user: '', pass: '', ...(m.smtp ?? {}) },
|
|
17
|
+
file: { dir: '.cms-mail', ...(m.file ?? {}) },
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Send an email through the configured transport. Throws on failure (callers decide).
|
|
23
|
+
* Returns whether it was really sent: false with the "log" transport (it is only
|
|
24
|
+
* written to the log), so an invitation can say the link has to be passed on.
|
|
25
|
+
*/
|
|
26
|
+
export async function sendCmsMail(msg: CmsMailMessage): Promise<boolean> {
|
|
27
|
+
return deliverMail(msg, cmsMailConfig())
|
|
28
|
+
}
|