emdash 0.30.0 → 0.31.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/dist/api/route-utils.mjs +13 -13
- package/dist/api/schemas/index.d.mts +1 -1
- package/dist/api/schemas/index.mjs +3 -3
- package/dist/{api-b8WIiGU4.mjs → api-BkqFzIu4.mjs} +23 -23
- package/dist/api-BkqFzIu4.mjs.map +1 -0
- package/dist/{apply-CmIJK9j8.mjs → apply-DuXsqll7.mjs} +26 -25
- package/dist/apply-DuXsqll7.mjs.map +1 -0
- package/dist/astro/index.d.mts +2 -2
- package/dist/astro/index.mjs +1 -1
- package/dist/astro/middleware/auth.d.mts +2 -2
- package/dist/astro/middleware/auth.mjs +2 -2
- package/dist/astro/middleware/redirect.mjs +5 -5
- package/dist/astro/middleware/request-context.mjs +1 -1
- package/dist/astro/middleware.d.mts +2 -2
- package/dist/astro/middleware.mjs +146 -70
- package/dist/astro/middleware.mjs.map +1 -1
- package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs +6 -6
- package/dist/astro/routes/api/admin/allowed-domains/index.mjs +6 -6
- package/dist/astro/routes/api/admin/api-tokens/_id_.mjs +2 -2
- package/dist/astro/routes/api/admin/api-tokens/index.mjs +3 -3
- package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +3 -3
- package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +7 -7
- package/dist/astro/routes/api/admin/byline-fields/index.mjs +7 -7
- package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +7 -7
- package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +14 -14
- package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +14 -14
- package/dist/astro/routes/api/admin/bylines/index.d.mts.map +1 -1
- package/dist/astro/routes/api/admin/bylines/index.mjs +18 -17
- package/dist/astro/routes/api/admin/bylines/index.mjs.map +1 -1
- package/dist/astro/routes/api/admin/comments/_id_/status.mjs +10 -10
- package/dist/astro/routes/api/admin/comments/_id_.mjs +5 -5
- package/dist/astro/routes/api/admin/comments/bulk.mjs +9 -9
- package/dist/astro/routes/api/admin/comments/counts.mjs +5 -5
- package/dist/astro/routes/api/admin/comments/index.mjs +9 -9
- package/dist/astro/routes/api/admin/hooks/exclusive/_hookName_.mjs +4 -4
- package/dist/astro/routes/api/admin/hooks/exclusive/index.mjs +3 -3
- package/dist/astro/routes/api/admin/media-usage/repair.mjs +10 -10
- package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs +3 -3
- package/dist/astro/routes/api/admin/oauth-clients/index.mjs +3 -3
- package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/_id_/mcp.mjs +4 -4
- package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/index.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +3 -3
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +35 -35
- package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +34 -34
- package/dist/astro/routes/api/admin/plugins/registry/install.mjs +35 -35
- package/dist/astro/routes/api/admin/plugins/updates.mjs +34 -34
- package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +34 -34
- package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +3 -3
- package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +34 -34
- package/dist/astro/routes/api/admin/users/_id_/disable.mjs +2 -2
- package/dist/astro/routes/api/admin/users/_id_/enable.mjs +2 -2
- package/dist/astro/routes/api/admin/users/_id_/index.mjs +6 -6
- package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +2 -2
- package/dist/astro/routes/api/admin/users/index.mjs +6 -6
- package/dist/astro/routes/api/auth/dev-bypass.mjs +4 -4
- package/dist/astro/routes/api/auth/invite/accept.mjs +2 -2
- package/dist/astro/routes/api/auth/invite/complete.mjs +6 -6
- package/dist/astro/routes/api/auth/invite/index.mjs +6 -6
- package/dist/astro/routes/api/auth/invite/register-options.mjs +6 -6
- package/dist/astro/routes/api/auth/logout.mjs +2 -2
- package/dist/astro/routes/api/auth/magic-link/send.mjs +7 -7
- package/dist/astro/routes/api/auth/magic-link/verify.mjs +2 -2
- package/dist/astro/routes/api/auth/me.mjs +7 -7
- package/dist/astro/routes/api/auth/mode.mjs +2 -2
- package/dist/astro/routes/api/auth/passkey/_id_.mjs +6 -6
- package/dist/astro/routes/api/auth/passkey/index.mjs +2 -2
- package/dist/astro/routes/api/auth/passkey/options.mjs +7 -7
- package/dist/astro/routes/api/auth/passkey/register/options.mjs +6 -6
- package/dist/astro/routes/api/auth/passkey/register/verify.mjs +6 -6
- package/dist/astro/routes/api/auth/passkey/verify.mjs +6 -6
- package/dist/astro/routes/api/auth/signup/complete.mjs +6 -6
- package/dist/astro/routes/api/auth/signup/request.mjs +7 -7
- package/dist/astro/routes/api/auth/signup/verify.mjs +2 -2
- package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +10 -10
- package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +10 -10
- package/dist/astro/routes/api/content/_collection_/_id_/compare.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_/duplicate.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_/permanent.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs +9 -9
- package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +7 -7
- package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs +14 -14
- package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs +14 -14
- package/dist/astro/routes/api/content/_collection_/_id_/restore.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_/revisions.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs +7 -7
- package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +13 -13
- package/dist/astro/routes/api/content/_collection_/_id_/translations.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/_id_.mjs +7 -7
- package/dist/astro/routes/api/content/_collection_/authors.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/index.mjs +7 -7
- package/dist/astro/routes/api/content/_collection_/trash.mjs +7 -7
- package/dist/astro/routes/api/dashboard.mjs +7 -7
- package/dist/astro/routes/api/dev/emails.mjs +2 -2
- package/dist/astro/routes/api/import/probe.mjs +12 -12
- package/dist/astro/routes/api/import/wordpress/analyze.mjs +3 -3
- package/dist/astro/routes/api/import/wordpress/execute.d.mts +2 -2
- package/dist/astro/routes/api/import/wordpress/execute.mjs +11 -11
- package/dist/astro/routes/api/import/wordpress/media.d.mts +2 -2
- package/dist/astro/routes/api/import/wordpress/media.mjs +7 -7
- package/dist/astro/routes/api/import/wordpress/prepare.mjs +9 -9
- package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts +2 -2
- package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +9 -9
- package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +12 -12
- package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +2 -2
- package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +19 -19
- package/dist/astro/routes/api/manifest.mjs +3 -3
- package/dist/astro/routes/api/mcp.mjs +39 -39
- package/dist/astro/routes/api/media/_id_/confirm.mjs +7 -7
- package/dist/astro/routes/api/media/_id_/usage.mjs +11 -11
- package/dist/astro/routes/api/media/_id_.mjs +10 -10
- package/dist/astro/routes/api/media/file/_...key_.mjs +2 -2
- package/dist/astro/routes/api/media/providers/_providerId_/_itemId_.mjs +3 -3
- package/dist/astro/routes/api/media/providers/_providerId_/index.mjs +3 -3
- package/dist/astro/routes/api/media/providers/index.mjs +3 -3
- package/dist/astro/routes/api/media/upload-url.mjs +7 -7
- package/dist/astro/routes/api/media.mjs +10 -10
- package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +8 -8
- package/dist/astro/routes/api/menus/_name_/items.mjs +8 -8
- package/dist/astro/routes/api/menus/_name_/reorder.mjs +8 -8
- package/dist/astro/routes/api/menus/_name_/translations.mjs +8 -8
- package/dist/astro/routes/api/menus/_name_.mjs +8 -8
- package/dist/astro/routes/api/menus/index.mjs +8 -8
- package/dist/astro/routes/api/oauth/authorize.d.mts.map +1 -1
- package/dist/astro/routes/api/oauth/authorize.mjs +23 -9
- package/dist/astro/routes/api/oauth/authorize.mjs.map +1 -1
- package/dist/astro/routes/api/oauth/device/authorize.mjs +3 -3
- package/dist/astro/routes/api/oauth/device/code.mjs +4 -4
- package/dist/astro/routes/api/oauth/device/token.mjs +4 -4
- package/dist/astro/routes/api/oauth/register.mjs +2 -2
- package/dist/astro/routes/api/oauth/token/refresh.mjs +3 -3
- package/dist/astro/routes/api/oauth/token/revoke.mjs +3 -3
- package/dist/astro/routes/api/oauth/token.mjs +2 -2
- package/dist/astro/routes/api/openapi.json.mjs +4 -4
- package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +4 -4
- package/dist/astro/routes/api/redirects/404s/index.mjs +10 -10
- package/dist/astro/routes/api/redirects/404s/summary.mjs +10 -10
- package/dist/astro/routes/api/redirects/_id_.mjs +11 -11
- package/dist/astro/routes/api/redirects/index.mjs +11 -11
- package/dist/astro/routes/api/relations/_id_/index.mjs +14 -14
- package/dist/astro/routes/api/relations/_id_/translations.mjs +10 -10
- package/dist/astro/routes/api/relations/index.mjs +14 -14
- package/dist/astro/routes/api/revisions/_revisionId_/index.mjs +3 -3
- package/dist/astro/routes/api/revisions/_revisionId_/restore.mjs +3 -3
- package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +34 -34
- package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +34 -34
- package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +34 -34
- package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +34 -34
- package/dist/astro/routes/api/schema/collections/index.mjs +34 -34
- package/dist/astro/routes/api/schema/index.mjs +8 -8
- package/dist/astro/routes/api/schema/orphans/_slug_.mjs +34 -34
- package/dist/astro/routes/api/schema/orphans/index.mjs +34 -34
- package/dist/astro/routes/api/search/enable.mjs +11 -11
- package/dist/astro/routes/api/search/index.mjs +10 -10
- package/dist/astro/routes/api/search/rebuild.mjs +11 -11
- package/dist/astro/routes/api/search/stats.mjs +7 -7
- package/dist/astro/routes/api/search/suggest.mjs +10 -10
- package/dist/astro/routes/api/sections/_slug_.mjs +10 -10
- package/dist/astro/routes/api/sections/index.mjs +10 -10
- package/dist/astro/routes/api/settings/backups/archives/_name_.mjs +4 -4
- package/dist/astro/routes/api/settings/backups/archives/index.mjs +4 -4
- package/dist/astro/routes/api/settings/backups/export.mjs +4 -4
- package/dist/astro/routes/api/settings/backups/index.mjs +5 -5
- package/dist/astro/routes/api/settings/email.mjs +4 -4
- package/dist/astro/routes/api/settings.mjs +12 -12
- package/dist/astro/routes/api/setup/admin-verify.mjs +6 -6
- package/dist/astro/routes/api/setup/admin.mjs +6 -6
- package/dist/astro/routes/api/setup/dev-bypass.mjs +18 -18
- package/dist/astro/routes/api/setup/dev-reset.mjs +2 -2
- package/dist/astro/routes/api/setup/index.mjs +22 -22
- package/dist/astro/routes/api/setup/status.mjs +3 -3
- package/dist/astro/routes/api/snapshot.mjs +4 -4
- package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +13 -13
- package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +13 -13
- package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +13 -13
- package/dist/astro/routes/api/taxonomies/index.mjs +13 -13
- package/dist/astro/routes/api/themes/preview.mjs +4 -4
- package/dist/astro/routes/api/typegen.mjs +5 -5
- package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +7 -7
- package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +10 -10
- package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +10 -10
- package/dist/astro/routes/api/widget-areas/_name_.mjs +6 -6
- package/dist/astro/routes/api/widget-areas/index.mjs +10 -10
- package/dist/astro/routes/api/widget-components.mjs +2 -2
- package/dist/astro/routes/robots.txt.mjs +5 -5
- package/dist/astro/routes/sitemap-_collection_.xml.mjs +7 -7
- package/dist/astro/routes/sitemap.xml.mjs +5 -5
- package/dist/astro/types.d.mts +2 -2
- package/dist/{authorize-WxsiePzy.mjs → authorize-6WPZa1xZ.mjs} +2 -2
- package/dist/{authorize-WxsiePzy.mjs.map → authorize-6WPZa1xZ.mjs.map} +1 -1
- package/dist/{backup-S8kFWtwD.mjs → backup-DoW-H0r4.mjs} +2 -2
- package/dist/{backup-S8kFWtwD.mjs.map → backup-DoW-H0r4.mjs.map} +1 -1
- package/dist/{byline-XEjchwzZ.mjs → byline-BTOxUlFF.mjs} +6 -6
- package/dist/{byline-XEjchwzZ.mjs.map → byline-BTOxUlFF.mjs.map} +1 -1
- package/dist/{bylines-czseViYo.mjs → bylines-Bc-3xtpz.mjs} +6 -6
- package/dist/{bylines-czseViYo.mjs.map → bylines-Bc-3xtpz.mjs.map} +1 -1
- package/dist/{bylines-BJbT4gKS.mjs → bylines-oVN0iPwX.mjs} +12 -8
- package/dist/bylines-oVN0iPwX.mjs.map +1 -0
- package/dist/{cache-CGCd6AVM.mjs → cache-DDwy3JDW.mjs} +2 -2
- package/dist/{cache-CGCd6AVM.mjs.map → cache-DDwy3JDW.mjs.map} +1 -1
- package/dist/{chunks-BxXyunY-.mjs → chunks-Bq-5DPrD.mjs} +2 -2
- package/dist/{chunks-BxXyunY-.mjs.map → chunks-Bq-5DPrD.mjs.map} +1 -1
- package/dist/cli/index.mjs +18 -18
- package/dist/{comment-DPT0WKyd.mjs → comment-B9cUud8H.mjs} +2 -2
- package/dist/{comment-DPT0WKyd.mjs.map → comment-B9cUud8H.mjs.map} +1 -1
- package/dist/{comment-reaction-C65MldIB.mjs → comment-reaction-VUXO981F.mjs} +2 -2
- package/dist/{comment-reaction-C65MldIB.mjs.map → comment-reaction-VUXO981F.mjs.map} +1 -1
- package/dist/{comments-Bz6sCbgD.mjs → comments-PXj1E9Si.mjs} +3 -3
- package/dist/{comments-Bz6sCbgD.mjs.map → comments-PXj1E9Si.mjs.map} +1 -1
- package/dist/{config-CVssduLe.mjs → config-B6b_BobR.mjs} +6 -2
- package/dist/config-B6b_BobR.mjs.map +1 -0
- package/dist/{content-Ci04z2z-.mjs → content-BC43pICM.mjs} +4 -4
- package/dist/{content-Ci04z2z-.mjs.map → content-BC43pICM.mjs.map} +1 -1
- package/dist/{content-refresh-D4khvC0R.mjs → content-refresh-CPMSauD3.mjs} +4 -4
- package/dist/{content-refresh-D4khvC0R.mjs.map → content-refresh-CPMSauD3.mjs.map} +1 -1
- package/dist/{context-B6hc7zJL.mjs → context-DOurRIrb.mjs} +10 -10
- package/dist/{context-B6hc7zJL.mjs.map → context-DOurRIrb.mjs.map} +1 -1
- package/dist/{dashboard-C5NkXFbi.mjs → dashboard-CBm4zhc3.mjs} +4 -4
- package/dist/{dashboard-C5NkXFbi.mjs.map → dashboard-CBm4zhc3.mjs.map} +1 -1
- package/dist/database/pg-migration-lock.d.mts.map +1 -1
- package/dist/database/pg-migration-lock.mjs +1 -4
- package/dist/database/pg-migration-lock.mjs.map +1 -1
- package/dist/db/index.mjs +2 -2
- package/dist/{dialect-helpers-HxEQGl_1.mjs → dialect-helpers-BtOwo2us.mjs} +4 -4
- package/dist/dialect-helpers-BtOwo2us.mjs.map +1 -0
- package/dist/{error-CEGF6UZb.mjs → error-DJ98TRbQ.mjs} +2 -2
- package/dist/{error-CEGF6UZb.mjs.map → error-DJ98TRbQ.mjs.map} +1 -1
- package/dist/{field-defs-cache-DvmlgP-D.mjs → field-defs-cache-KfNJ_qLQ.mjs} +2 -2
- package/dist/{field-defs-cache-DvmlgP-D.mjs.map → field-defs-cache-KfNJ_qLQ.mjs.map} +1 -1
- package/dist/{fts-manager-DzqIBrrW.mjs → fts-manager-hyCU9OOp.mjs} +3 -3
- package/dist/{fts-manager-DzqIBrrW.mjs.map → fts-manager-hyCU9OOp.mjs.map} +1 -1
- package/dist/{hreflang-db2Tpb2o.mjs → hreflang-CbYeCzl9.mjs} +7 -7
- package/dist/{hreflang-db2Tpb2o.mjs.map → hreflang-CbYeCzl9.mjs.map} +1 -1
- package/dist/{import-Dmkm8S1W.mjs → import-oDYCgNYQ.mjs} +2 -2
- package/dist/{import-Dmkm8S1W.mjs.map → import-oDYCgNYQ.mjs.map} +1 -1
- package/dist/{index-wYnC6u4o.d.mts → index-BZJ_5FOX.d.mts} +50 -4
- package/dist/index-BZJ_5FOX.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +48 -48
- package/dist/{load-Cx27ki1l.mjs → load-Dg5gtWma.mjs} +2 -2
- package/dist/{load-Cx27ki1l.mjs.map → load-Dg5gtWma.mjs.map} +1 -1
- package/dist/{loader-Be3ouI5L.mjs → loader-D4rigvjR.mjs} +4 -4
- package/dist/{loader-Be3ouI5L.mjs.map → loader-D4rigvjR.mjs.map} +1 -1
- package/dist/media/local-runtime.d.mts +2 -2
- package/dist/media/local-runtime.mjs +5 -5
- package/dist/{media-kIV1IxFf.mjs → media-BJ6SRY3g.mjs} +8 -4
- package/dist/media-BJ6SRY3g.mjs.map +1 -0
- package/dist/{media-BjhhENaJ.mjs → media-its1WLYv.mjs} +2 -2
- package/dist/{media-BjhhENaJ.mjs.map → media-its1WLYv.mjs.map} +1 -1
- package/dist/{media-upload-D2wk3EIt.mjs → media-upload-DNu3QySc.mjs} +4 -4
- package/dist/{media-upload-D2wk3EIt.mjs.map → media-upload-DNu3QySc.mjs.map} +1 -1
- package/dist/{media-usage-CljdO1mc.mjs → media-usage-DPQ3K4xB.mjs} +6 -6
- package/dist/{media-usage-CljdO1mc.mjs.map → media-usage-DPQ3K4xB.mjs.map} +1 -1
- package/dist/{menus-CZyG6rvx.mjs → menus-BMGzWyWH.mjs} +15 -8
- package/dist/menus-BMGzWyWH.mjs.map +1 -0
- package/dist/{menus-BcyElFtI.mjs → menus-CPf_SW7u.mjs} +86 -8
- package/dist/menus-CPf_SW7u.mjs.map +1 -0
- package/dist/{parse-C_-6klII.mjs → parse-53zyxlpv.mjs} +2 -2
- package/dist/{parse-C_-6klII.mjs.map → parse-53zyxlpv.mjs.map} +1 -1
- package/dist/plugin-utils.d.mts +2 -2
- package/dist/plugins/adapt-sandbox-entry.d.mts +2 -2
- package/dist/{query-DR73ZNfm.mjs → query-Bz9bWZfm.mjs} +14 -14
- package/dist/{query-DR73ZNfm.mjs.map → query-Bz9bWZfm.mjs.map} +1 -1
- package/dist/{query-Di7DOmPV.mjs → query-DdFGHzQF.mjs} +3 -3
- package/dist/{query-Di7DOmPV.mjs.map → query-DdFGHzQF.mjs.map} +1 -1
- package/dist/{rate-limit-CMj83JNW.mjs → rate-limit-D3IEiUi2.mjs} +2 -2
- package/dist/{rate-limit-CMj83JNW.mjs.map → rate-limit-D3IEiUi2.mjs.map} +1 -1
- package/dist/{redirect-CgLPYflR.mjs → redirect-BoUac4NT.mjs} +3 -3
- package/dist/{redirect-CgLPYflR.mjs.map → redirect-BoUac4NT.mjs.map} +1 -1
- package/dist/{redirects-B7t9bKsL.mjs → redirects-ChbpqKiS.mjs} +3 -3
- package/dist/{redirects-B7t9bKsL.mjs.map → redirects-ChbpqKiS.mjs.map} +1 -1
- package/dist/{redirects-BBq3n2Rj.mjs → redirects-D457qwt0.mjs} +8 -8
- package/dist/redirects-D457qwt0.mjs.map +1 -0
- package/dist/{registry-FV15nLge.mjs → registry-y21kjhfG.mjs} +6 -6
- package/dist/{registry-FV15nLge.mjs.map → registry-y21kjhfG.mjs.map} +1 -1
- package/dist/{relation-9M9j_UWo.mjs → relation-Du0r04E0.mjs} +3 -3
- package/dist/{relation-9M9j_UWo.mjs.map → relation-Du0r04E0.mjs.map} +1 -1
- package/dist/{relations-5_avdrN_.mjs → relations-CZMpBqEd.mjs} +3 -3
- package/dist/{relations-5_avdrN_.mjs.map → relations-CZMpBqEd.mjs.map} +1 -1
- package/dist/{relations-BKvO39-9.mjs → relations-DtX1UMBH.mjs} +13 -7
- package/dist/relations-DtX1UMBH.mjs.map +1 -0
- package/dist/{relations-Bh8jlFsU.d.mts → relations-qKmSj9KM.d.mts} +27 -23
- package/dist/relations-qKmSj9KM.d.mts.map +1 -0
- package/dist/{resolve-Cd9dzclN.mjs → resolve-DFr4kq72.mjs} +2 -2
- package/dist/{resolve-Cd9dzclN.mjs.map → resolve-DFr4kq72.mjs.map} +1 -1
- package/dist/{runner-DfnZ5eUr.mjs → runner-BdeLEgad.mjs} +3 -3
- package/dist/{runner-DfnZ5eUr.mjs.map → runner-BdeLEgad.mjs.map} +1 -1
- package/dist/runtime.d.mts +2 -2
- package/dist/runtime.mjs +3 -3
- package/dist/{schema-BXxlHeAf.mjs → schema-BH8P8vaC.mjs} +3 -3
- package/dist/{schema-BXxlHeAf.mjs.map → schema-BH8P8vaC.mjs.map} +1 -1
- package/dist/{scopes-Bl4IwHA-.mjs → scopes-DTIkIaGA.mjs} +2 -2
- package/dist/{scopes-Bl4IwHA-.mjs.map → scopes-DTIkIaGA.mjs.map} +1 -1
- package/dist/{search-Bff-7jFt.mjs → search-D-Yhpmvs.mjs} +8 -7
- package/dist/search-D-Yhpmvs.mjs.map +1 -0
- package/dist/{secrets-CSwQIl4q.mjs → secrets-CQ-69kF9.mjs} +23 -17
- package/dist/secrets-CQ-69kF9.mjs.map +1 -0
- package/dist/{sections-CwW4s1al.mjs → sections-CzVBAKjw.mjs} +3 -3
- package/dist/{sections-CwW4s1al.mjs.map → sections-CzVBAKjw.mjs.map} +1 -1
- package/dist/seed/index.mjs +16 -16
- package/dist/seo/index.mjs +12 -12
- package/dist/{seo-2cmFHZns.mjs → seo-kJzVAmmu.mjs} +2 -2
- package/dist/{seo-2cmFHZns.mjs.map → seo-kJzVAmmu.mjs.map} +1 -1
- package/dist/{service-DkGTWGIi.mjs → service-CQnc276a.mjs} +2 -2
- package/dist/{service-DkGTWGIi.mjs.map → service-CQnc276a.mjs.map} +1 -1
- package/dist/{settings-CpA4lQFt.mjs → settings-C2PaBS49.mjs} +3 -3
- package/dist/{settings-CpA4lQFt.mjs.map → settings-C2PaBS49.mjs.map} +1 -1
- package/dist/{settings-C4s8hFQm.mjs → settings-Dtc0DU31.mjs} +3 -3
- package/dist/{settings-C4s8hFQm.mjs.map → settings-Dtc0DU31.mjs.map} +1 -1
- package/dist/{taxonomies-Ce49uIzY.mjs → taxonomies-BN6M9Nrv.mjs} +26 -17
- package/dist/taxonomies-BN6M9Nrv.mjs.map +1 -0
- package/dist/{taxonomies-DjSKBZpq.mjs → taxonomies-r7pqLBCn.mjs} +53 -24
- package/dist/taxonomies-r7pqLBCn.mjs.map +1 -0
- package/dist/{taxonomy-DfVooU4W.mjs → taxonomy-0mCI25HN.mjs} +3 -3
- package/dist/{taxonomy-DfVooU4W.mjs.map → taxonomy-0mCI25HN.mjs.map} +1 -1
- package/dist/{types-D1iJ3DpO.mjs → types-CrRUFdej.mjs} +2 -2
- package/dist/{types-D1iJ3DpO.mjs.map → types-CrRUFdej.mjs.map} +1 -1
- package/dist/{user-Bh-L1qo6.mjs → user-aTXqmXBz.mjs} +3 -3
- package/dist/{user-Bh-L1qo6.mjs.map → user-aTXqmXBz.mjs.map} +1 -1
- package/dist/{validate-V9nCwq_-.mjs → validate-CDT1jl6_.mjs} +11 -6
- package/dist/validate-CDT1jl6_.mjs.map +1 -0
- package/dist/validate-DULfgpJP.d.mts.map +1 -1
- package/dist/{validation-BsVUJfsP.mjs → validation-DlD0E35W.mjs} +8 -8
- package/dist/{validation-BsVUJfsP.mjs.map → validation-DlD0E35W.mjs.map} +1 -1
- package/dist/version-BRMngh9I.mjs +7 -0
- package/dist/{version-907opKac.mjs.map → version-BRMngh9I.mjs.map} +1 -1
- package/dist/{widgets-DGv1Z04V.mjs → widgets-5fipNkMT.mjs} +2 -2
- package/dist/{widgets-DGv1Z04V.mjs.map → widgets-5fipNkMT.mjs.map} +1 -1
- package/dist/{wxr-taxonomies-Cs1N6O8z.mjs → wxr-taxonomies-DrihupaC.mjs} +4 -4
- package/dist/{wxr-taxonomies-Cs1N6O8z.mjs.map → wxr-taxonomies-DrihupaC.mjs.map} +1 -1
- package/dist/{zod-generator-B5prQ5M4.mjs → zod-generator-CwkHWz4f.mjs} +2 -2
- package/dist/{zod-generator-B5prQ5M4.mjs.map → zod-generator-CwkHWz4f.mjs.map} +1 -1
- package/package.json +7 -7
- package/src/api/handlers/bylines.ts +5 -4
- package/src/api/handlers/content.ts +25 -7
- package/src/api/handlers/menus.ts +11 -6
- package/src/api/handlers/relations.ts +7 -2
- package/src/api/handlers/taxonomies.ts +22 -14
- package/src/api/schemas/bylines.ts +4 -4
- package/src/api/schemas/common.ts +7 -6
- package/src/api/schemas/menus.ts +2 -1
- package/src/api/schemas/relations.ts +3 -1
- package/src/api/schemas/taxonomies.ts +4 -2
- package/src/astro/prefetch.ts +7 -2
- package/src/astro/routes/api/admin/bylines/index.ts +5 -8
- package/src/astro/routes/api/oauth/authorize.ts +42 -10
- package/src/components/Gallery.astro +141 -26
- package/src/components/widgets/Categories.astro +1 -1
- package/src/components/widgets/Tags.astro +1 -1
- package/src/config/secrets.ts +25 -19
- package/src/content/converters/gallery.ts +61 -0
- package/src/content/converters/portable-text-to-prosemirror.ts +19 -0
- package/src/content/converters/prosemirror-to-portable-text.ts +18 -0
- package/src/content/converters/types.ts +36 -0
- package/src/database/dialect-helpers.ts +3 -4
- package/src/database/pg-migration-lock.ts +1 -4
- package/src/emdash-runtime.ts +55 -17
- package/src/i18n/config.ts +8 -0
- package/src/i18n/repair-locale-casing.ts +51 -0
- package/src/search/query.ts +3 -2
- package/src/seed/apply.ts +9 -7
- package/src/seed/validate.ts +15 -4
- package/src/taxonomies/index.ts +64 -23
- package/dist/api-b8WIiGU4.mjs.map +0 -1
- package/dist/apply-CmIJK9j8.mjs.map +0 -1
- package/dist/bylines-BJbT4gKS.mjs.map +0 -1
- package/dist/config-CVssduLe.mjs.map +0 -1
- package/dist/dialect-helpers-HxEQGl_1.mjs.map +0 -1
- package/dist/index-wYnC6u4o.d.mts.map +0 -1
- package/dist/media-kIV1IxFf.mjs.map +0 -1
- package/dist/menus-BcyElFtI.mjs.map +0 -1
- package/dist/menus-CZyG6rvx.mjs.map +0 -1
- package/dist/redirects-BBq3n2Rj.mjs.map +0 -1
- package/dist/relations-BKvO39-9.mjs.map +0 -1
- package/dist/relations-Bh8jlFsU.d.mts.map +0 -1
- package/dist/search-Bff-7jFt.mjs.map +0 -1
- package/dist/secrets-CSwQIl4q.mjs.map +0 -1
- package/dist/taxonomies-Ce49uIzY.mjs.map +0 -1
- package/dist/taxonomies-DjSKBZpq.mjs.map +0 -1
- package/dist/validate-V9nCwq_-.mjs.map +0 -1
- package/dist/version-907opKac.mjs +0 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service-DkGTWGIi.mjs","names":[],"sources":["../src/comments/notifications.ts","../src/comments/service.ts"],"sourcesContent":["/**\n * Comment Notification Emails\n *\n * Sends email notifications to content authors when comments are\n * approved on their content. Used by:\n * - Public comment POST route (comment:afterCreate, if auto-approved)\n * - Admin moderation route (comment:afterModerate, when approving)\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { escapeHtml } from \"../api/escape.js\";\nimport type { Database } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport type { EmailPipeline } from \"../plugins/email.js\";\nimport type { EmailMessage } from \"../plugins/types.js\";\n\nconst NOTIFICATION_SOURCE = \"emdash-comments\";\nconst MAX_EXCERPT_LENGTH = 500;\nconst CRLF_RE = /[\\r\\n]/g;\n\nexport interface CommentNotificationData {\n\tcommentAuthorName: string;\n\tcommentBody: string;\n\tcontentTitle: string;\n\tcollection: string;\n\tadminBaseUrl: string;\n}\n\n/**\n * Build an email notification for a new comment.\n */\nexport function buildCommentNotificationEmail(\n\tto: string,\n\tdata: CommentNotificationData,\n): EmailMessage {\n\tconst title = data.contentTitle || `${data.collection} item`;\n\tconst subject = `New comment on \"${title}\"`.replace(CRLF_RE, \" \");\n\n\tconst excerpt =\n\t\tdata.commentBody.length > MAX_EXCERPT_LENGTH\n\t\t\t? data.commentBody.slice(0, MAX_EXCERPT_LENGTH) + \"...\"\n\t\t\t: data.commentBody;\n\n\tconst adminUrl = `${data.adminBaseUrl}/admin/comments`;\n\n\tconst text = [\n\t\t`${data.commentAuthorName} commented on \"${title}\":`,\n\t\t\"\",\n\t\texcerpt,\n\t\t\"\",\n\t\t`View in admin: ${adminUrl}`,\n\t].join(\"\\n\");\n\n\tconst html = [\n\t\t`<p><strong>${escapeHtml(data.commentAuthorName)}</strong> commented on “${escapeHtml(title)}”:</p>`,\n\t\t`<blockquote style=\"border-left:3px solid #ccc;padding-left:12px;margin:12px 0;color:#555\">${escapeHtml(excerpt)}</blockquote>`,\n\t\t`<p><a href=\"${escapeHtml(adminUrl)}\">View in admin</a></p>`,\n\t].join(\"\\n\");\n\n\treturn { to, subject, text, html };\n}\n\n/**\n * Send a comment notification to the content author if all conditions are met:\n * 1. Comment status is \"approved\"\n * 2. Content author exists and has an email\n * 3. Email provider is configured\n * 4. Commenter is not the content author (no self-notifications)\n *\n * Returns true if the email was sent, false if skipped.\n */\nexport async function sendCommentNotification(params: {\n\temail: EmailPipeline;\n\tcomment: {\n\t\tauthorName: string;\n\t\tauthorEmail: string;\n\t\tbody: string;\n\t\tstatus: string;\n\t\tcollection: string;\n\t};\n\tcontentTitle?: string;\n\tcontentAuthor?: { email: string; name: string | null };\n\tadminBaseUrl: string;\n}): Promise<boolean> {\n\tconst { email, comment, contentAuthor, adminBaseUrl } = params;\n\n\tif (comment.status !== \"approved\") return false;\n\tif (!contentAuthor?.email) return false;\n\tif (!email.isAvailable()) return false;\n\tif (comment.authorEmail.toLowerCase() === contentAuthor.email.toLowerCase()) return false;\n\n\tconst message = buildCommentNotificationEmail(contentAuthor.email, {\n\t\tcommentAuthorName: comment.authorName,\n\t\tcommentBody: comment.body,\n\t\tcontentTitle: params.contentTitle || \"\",\n\t\tcollection: comment.collection,\n\t\tadminBaseUrl,\n\t});\n\n\tawait email.send(message, NOTIFICATION_SOURCE);\n\treturn true;\n}\n\n/**\n * Look up a content item's author from the database.\n *\n * Used by the admin moderation route where content info isn't\n * readily available (only the comment record is at hand).\n */\nexport async function lookupContentAuthor(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tcontentId: string,\n): Promise<{\n\tslug: string;\n\tauthor?: { id: string; email: string; name: string | null };\n} | null> {\n\tvalidateIdentifier(collection, \"collection\");\n\n\tconst contentRow = await db\n\t\t.selectFrom(`ec_${collection}` as never)\n\t\t.select([\"slug\" as never, \"author_id\" as never])\n\t\t.where(\"id\" as never, \"=\", contentId as never)\n\t\t.executeTakeFirst();\n\n\tif (!contentRow) return null;\n\n\tconst typed = contentRow as { slug: string; author_id: string | null };\n\n\tlet author: { id: string; email: string; name: string | null } | undefined;\n\tif (typed.author_id) {\n\t\tconst userRow = await db\n\t\t\t.selectFrom(\"users\")\n\t\t\t.select([\"id\", \"name\", \"email\", \"email_verified\"])\n\t\t\t.where(\"id\", \"=\", typed.author_id)\n\t\t\t.executeTakeFirst();\n\t\tif (userRow && userRow.email_verified) {\n\t\t\tauthor = { id: userRow.id, email: userRow.email, name: userRow.name };\n\t\t}\n\t}\n\n\treturn { slug: typed.slug, author };\n}\n","/**\n * Comment Service\n *\n * Orchestrates comment creation through the hook pipeline:\n * 1. Run comment:beforeCreate pipeline (transform/reject)\n * 2. Query priorApprovedCount for first-time moderation\n * 3. Invoke comment:moderate exclusive hook (or built-in fallback)\n * 4. Save comment with determined status\n * 5. Fire comment:afterCreate (fire-and-forget)\n *\n * Also handles admin moderation (status changes) with afterModerate hooks.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { CommentRepository } from \"../database/repositories/comment.js\";\nimport type { Comment, CommentStatus } from \"../database/repositories/comment.js\";\nimport type { Database } from \"../database/types.js\";\nimport type {\n\tCollectionCommentSettings,\n\tCommentAfterCreateEvent,\n\tCommentAfterModerateEvent,\n\tCommentBeforeCreateEvent,\n\tCommentModerateEvent,\n\tModerationDecision,\n\tStoredComment,\n} from \"../plugins/types.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CommentCreateInput {\n\tcollection: string;\n\tcontentId: string;\n\tparentId?: string | null;\n\tauthorName: string;\n\tauthorEmail: string;\n\tauthorUserId?: string | null;\n\tbody: string;\n\tipHash?: string | null;\n\tuserAgent?: string | null;\n}\n\nexport interface CommentCreateResult {\n\tcomment: Comment;\n\tdecision: ModerationDecision;\n}\n\n/**\n * Hook runner interface — injected from the runtime so the service\n * doesn't need to know about the hook pipeline internals.\n */\nexport interface CommentHookRunner {\n\t/** Run comment:beforeCreate pipeline. Returns modified event or false. */\n\trunBeforeCreate(event: CommentBeforeCreateEvent): Promise<CommentBeforeCreateEvent | false>;\n\n\t/** Run comment:moderate exclusive hook. Returns moderation decision. */\n\trunModerate(event: CommentModerateEvent): Promise<ModerationDecision>;\n\n\t/** Fire comment:afterCreate (fire-and-forget). */\n\tfireAfterCreate(event: CommentAfterCreateEvent): void;\n\n\t/** Fire comment:afterModerate (fire-and-forget). */\n\tfireAfterModerate(event: CommentAfterModerateEvent): void;\n}\n\n// ---------------------------------------------------------------------------\n// Service\n// ---------------------------------------------------------------------------\n\n/**\n * Create a comment through the full hook pipeline.\n *\n * Returns null if the comment was rejected by a beforeCreate handler.\n */\nexport async function createComment(\n\tdb: Kysely<Database>,\n\tinput: CommentCreateInput,\n\tcollectionSettings: CollectionCommentSettings,\n\thooks: CommentHookRunner,\n\tcontentInfo?: {\n\t\tid: string;\n\t\tcollection: string;\n\t\tslug: string;\n\t\ttitle?: string;\n\t\tauthor?: { id: string; name: string | null; email: string };\n\t},\n): Promise<CommentCreateResult | null> {\n\tconst repo = new CommentRepository(db);\n\n\t// 1. Build the beforeCreate event\n\tconst beforeCreateEvent: CommentBeforeCreateEvent = {\n\t\tcomment: {\n\t\t\tcollection: input.collection,\n\t\t\tcontentId: input.contentId,\n\t\t\tparentId: input.parentId ?? null,\n\t\t\tauthorName: input.authorName,\n\t\t\tauthorEmail: input.authorEmail,\n\t\t\tauthorUserId: input.authorUserId ?? null,\n\t\t\tbody: input.body,\n\t\t\tipHash: input.ipHash ?? null,\n\t\t\tuserAgent: input.userAgent ?? null,\n\t\t},\n\t\tmetadata: {},\n\t};\n\n\t// 2. Run comment:beforeCreate pipeline\n\tconst result = await hooks.runBeforeCreate(beforeCreateEvent);\n\tif (result === false) {\n\t\treturn null; // Rejected\n\t}\n\n\tconst event = result;\n\n\t// 3. Query prior approved count for first-time moderation\n\tconst priorApprovedCount = await repo.countApprovedByEmail(event.comment.authorEmail);\n\n\t// 4. Run comment:moderate exclusive hook\n\tconst moderateEvent: CommentModerateEvent = {\n\t\tcomment: event.comment,\n\t\tmetadata: event.metadata,\n\t\tcollectionSettings,\n\t\tpriorApprovedCount,\n\t};\n\n\tconst decision = await hooks.runModerate(moderateEvent);\n\n\t// 5. Save comment with determined status\n\tconst comment = await repo.create({\n\t\tcollection: event.comment.collection,\n\t\tcontentId: event.comment.contentId,\n\t\tparentId: event.comment.parentId,\n\t\tauthorName: event.comment.authorName,\n\t\tauthorEmail: event.comment.authorEmail,\n\t\tauthorUserId: event.comment.authorUserId,\n\t\tbody: event.comment.body,\n\t\tstatus: decision.status,\n\t\tipHash: event.comment.ipHash,\n\t\tuserAgent: event.comment.userAgent,\n\t\tmoderationMetadata: Object.keys(event.metadata).length > 0 ? event.metadata : null,\n\t});\n\n\t// 6. Fire comment:afterCreate (fire-and-forget)\n\tif (contentInfo) {\n\t\tconst afterEvent: CommentAfterCreateEvent = {\n\t\t\tcomment: commentToStored(comment),\n\t\t\tmetadata: event.metadata,\n\t\t\tcontent: {\n\t\t\t\tid: contentInfo.id,\n\t\t\t\tcollection: contentInfo.collection,\n\t\t\t\tslug: contentInfo.slug,\n\t\t\t\ttitle: contentInfo.title,\n\t\t\t},\n\t\t\tcontentAuthor: contentInfo.author,\n\t\t};\n\t\thooks.fireAfterCreate(afterEvent);\n\t}\n\n\treturn { comment, decision };\n}\n\n/**\n * Admin moderation — change a comment's status.\n * Fires comment:afterModerate hook.\n */\nexport async function moderateComment(\n\tdb: Kysely<Database>,\n\tid: string,\n\tnewStatus: CommentStatus,\n\tmoderator: { id: string; name: string | null },\n\thooks: CommentHookRunner,\n): Promise<Comment | null> {\n\tconst repo = new CommentRepository(db);\n\tconst existing = await repo.findById(id);\n\tif (!existing) return null;\n\n\tconst previousStatus = existing.status;\n\tconst updated = await repo.updateStatus(id, newStatus);\n\tif (!updated) return null;\n\n\t// Fire comment:afterModerate (fire-and-forget)\n\tconst afterEvent: CommentAfterModerateEvent = {\n\t\tcomment: commentToStored(updated),\n\t\tpreviousStatus,\n\t\tnewStatus,\n\t\tmoderator,\n\t};\n\thooks.fireAfterModerate(afterEvent);\n\n\treturn updated;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction commentToStored(comment: Comment): StoredComment {\n\treturn {\n\t\tid: comment.id,\n\t\tcollection: comment.collection,\n\t\tcontentId: comment.contentId,\n\t\tparentId: comment.parentId,\n\t\tauthorName: comment.authorName,\n\t\tauthorEmail: comment.authorEmail,\n\t\tauthorUserId: comment.authorUserId,\n\t\tbody: comment.body,\n\t\tstatus: comment.status,\n\t\tmoderationMetadata: comment.moderationMetadata,\n\t\tcreatedAt: comment.createdAt,\n\t\tupdatedAt: comment.updatedAt,\n\t};\n}\n"],"mappings":";;;;;AAiBA,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAC3B,MAAM,UAAU;;;;AAahB,SAAgB,8BACf,IACA,MACe;CACf,MAAM,QAAQ,KAAK,gBAAgB,GAAG,KAAK,WAAW;CACtD,MAAM,UAAU,mBAAmB,MAAM,GAAG,QAAQ,SAAS,IAAI;CAEjE,MAAM,UACL,KAAK,YAAY,SAAS,qBACvB,KAAK,YAAY,MAAM,GAAG,mBAAmB,GAAG,QAChD,KAAK;CAET,MAAM,WAAW,GAAG,KAAK,aAAa;AAgBtC,QAAO;EAAE;EAAI;EAAS,MAdT;GACZ,GAAG,KAAK,kBAAkB,iBAAiB,MAAM;GACjD;GACA;GACA;GACA,kBAAkB;GAClB,CAAC,KAAK,KAAK;EAQgB,MANf;GACZ,cAAc,WAAW,KAAK,kBAAkB,CAAC,gCAAgC,WAAW,MAAM,CAAC;GACnG,6FAA6F,WAAW,QAAQ,CAAC;GACjH,eAAe,WAAW,SAAS,CAAC;GACpC,CAAC,KAAK,KAAK;EAEsB;;;;;;;;;;;AAYnC,eAAsB,wBAAwB,QAYzB;CACpB,MAAM,EAAE,OAAO,SAAS,eAAe,iBAAiB;AAExD,KAAI,QAAQ,WAAW,WAAY,QAAO;AAC1C,KAAI,CAAC,eAAe,MAAO,QAAO;AAClC,KAAI,CAAC,MAAM,aAAa,CAAE,QAAO;AACjC,KAAI,QAAQ,YAAY,aAAa,KAAK,cAAc,MAAM,aAAa,CAAE,QAAO;CAEpF,MAAM,UAAU,8BAA8B,cAAc,OAAO;EAClE,mBAAmB,QAAQ;EAC3B,aAAa,QAAQ;EACrB,cAAc,OAAO,gBAAgB;EACrC,YAAY,QAAQ;EACpB;EACA,C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ACd,QAAQ,QAAQ;EAChB,oBAAoB,QAAQ;EAC5B,WAAW,QAAQ;EACnB,WAAW,QAAQ;EACnB"}
|
|
1
|
+
{"version":3,"file":"service-CQnc276a.mjs","names":[],"sources":["../src/comments/notifications.ts","../src/comments/service.ts"],"sourcesContent":["/**\n * Comment Notification Emails\n *\n * Sends email notifications to content authors when comments are\n * approved on their content. Used by:\n * - Public comment POST route (comment:afterCreate, if auto-approved)\n * - Admin moderation route (comment:afterModerate, when approving)\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { escapeHtml } from \"../api/escape.js\";\nimport type { Database } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport type { EmailPipeline } from \"../plugins/email.js\";\nimport type { EmailMessage } from \"../plugins/types.js\";\n\nconst NOTIFICATION_SOURCE = \"emdash-comments\";\nconst MAX_EXCERPT_LENGTH = 500;\nconst CRLF_RE = /[\\r\\n]/g;\n\nexport interface CommentNotificationData {\n\tcommentAuthorName: string;\n\tcommentBody: string;\n\tcontentTitle: string;\n\tcollection: string;\n\tadminBaseUrl: string;\n}\n\n/**\n * Build an email notification for a new comment.\n */\nexport function buildCommentNotificationEmail(\n\tto: string,\n\tdata: CommentNotificationData,\n): EmailMessage {\n\tconst title = data.contentTitle || `${data.collection} item`;\n\tconst subject = `New comment on \"${title}\"`.replace(CRLF_RE, \" \");\n\n\tconst excerpt =\n\t\tdata.commentBody.length > MAX_EXCERPT_LENGTH\n\t\t\t? data.commentBody.slice(0, MAX_EXCERPT_LENGTH) + \"...\"\n\t\t\t: data.commentBody;\n\n\tconst adminUrl = `${data.adminBaseUrl}/admin/comments`;\n\n\tconst text = [\n\t\t`${data.commentAuthorName} commented on \"${title}\":`,\n\t\t\"\",\n\t\texcerpt,\n\t\t\"\",\n\t\t`View in admin: ${adminUrl}`,\n\t].join(\"\\n\");\n\n\tconst html = [\n\t\t`<p><strong>${escapeHtml(data.commentAuthorName)}</strong> commented on “${escapeHtml(title)}”:</p>`,\n\t\t`<blockquote style=\"border-left:3px solid #ccc;padding-left:12px;margin:12px 0;color:#555\">${escapeHtml(excerpt)}</blockquote>`,\n\t\t`<p><a href=\"${escapeHtml(adminUrl)}\">View in admin</a></p>`,\n\t].join(\"\\n\");\n\n\treturn { to, subject, text, html };\n}\n\n/**\n * Send a comment notification to the content author if all conditions are met:\n * 1. Comment status is \"approved\"\n * 2. Content author exists and has an email\n * 3. Email provider is configured\n * 4. Commenter is not the content author (no self-notifications)\n *\n * Returns true if the email was sent, false if skipped.\n */\nexport async function sendCommentNotification(params: {\n\temail: EmailPipeline;\n\tcomment: {\n\t\tauthorName: string;\n\t\tauthorEmail: string;\n\t\tbody: string;\n\t\tstatus: string;\n\t\tcollection: string;\n\t};\n\tcontentTitle?: string;\n\tcontentAuthor?: { email: string; name: string | null };\n\tadminBaseUrl: string;\n}): Promise<boolean> {\n\tconst { email, comment, contentAuthor, adminBaseUrl } = params;\n\n\tif (comment.status !== \"approved\") return false;\n\tif (!contentAuthor?.email) return false;\n\tif (!email.isAvailable()) return false;\n\tif (comment.authorEmail.toLowerCase() === contentAuthor.email.toLowerCase()) return false;\n\n\tconst message = buildCommentNotificationEmail(contentAuthor.email, {\n\t\tcommentAuthorName: comment.authorName,\n\t\tcommentBody: comment.body,\n\t\tcontentTitle: params.contentTitle || \"\",\n\t\tcollection: comment.collection,\n\t\tadminBaseUrl,\n\t});\n\n\tawait email.send(message, NOTIFICATION_SOURCE);\n\treturn true;\n}\n\n/**\n * Look up a content item's author from the database.\n *\n * Used by the admin moderation route where content info isn't\n * readily available (only the comment record is at hand).\n */\nexport async function lookupContentAuthor(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tcontentId: string,\n): Promise<{\n\tslug: string;\n\tauthor?: { id: string; email: string; name: string | null };\n} | null> {\n\tvalidateIdentifier(collection, \"collection\");\n\n\tconst contentRow = await db\n\t\t.selectFrom(`ec_${collection}` as never)\n\t\t.select([\"slug\" as never, \"author_id\" as never])\n\t\t.where(\"id\" as never, \"=\", contentId as never)\n\t\t.executeTakeFirst();\n\n\tif (!contentRow) return null;\n\n\tconst typed = contentRow as { slug: string; author_id: string | null };\n\n\tlet author: { id: string; email: string; name: string | null } | undefined;\n\tif (typed.author_id) {\n\t\tconst userRow = await db\n\t\t\t.selectFrom(\"users\")\n\t\t\t.select([\"id\", \"name\", \"email\", \"email_verified\"])\n\t\t\t.where(\"id\", \"=\", typed.author_id)\n\t\t\t.executeTakeFirst();\n\t\tif (userRow && userRow.email_verified) {\n\t\t\tauthor = { id: userRow.id, email: userRow.email, name: userRow.name };\n\t\t}\n\t}\n\n\treturn { slug: typed.slug, author };\n}\n","/**\n * Comment Service\n *\n * Orchestrates comment creation through the hook pipeline:\n * 1. Run comment:beforeCreate pipeline (transform/reject)\n * 2. Query priorApprovedCount for first-time moderation\n * 3. Invoke comment:moderate exclusive hook (or built-in fallback)\n * 4. Save comment with determined status\n * 5. Fire comment:afterCreate (fire-and-forget)\n *\n * Also handles admin moderation (status changes) with afterModerate hooks.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { CommentRepository } from \"../database/repositories/comment.js\";\nimport type { Comment, CommentStatus } from \"../database/repositories/comment.js\";\nimport type { Database } from \"../database/types.js\";\nimport type {\n\tCollectionCommentSettings,\n\tCommentAfterCreateEvent,\n\tCommentAfterModerateEvent,\n\tCommentBeforeCreateEvent,\n\tCommentModerateEvent,\n\tModerationDecision,\n\tStoredComment,\n} from \"../plugins/types.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CommentCreateInput {\n\tcollection: string;\n\tcontentId: string;\n\tparentId?: string | null;\n\tauthorName: string;\n\tauthorEmail: string;\n\tauthorUserId?: string | null;\n\tbody: string;\n\tipHash?: string | null;\n\tuserAgent?: string | null;\n}\n\nexport interface CommentCreateResult {\n\tcomment: Comment;\n\tdecision: ModerationDecision;\n}\n\n/**\n * Hook runner interface — injected from the runtime so the service\n * doesn't need to know about the hook pipeline internals.\n */\nexport interface CommentHookRunner {\n\t/** Run comment:beforeCreate pipeline. Returns modified event or false. */\n\trunBeforeCreate(event: CommentBeforeCreateEvent): Promise<CommentBeforeCreateEvent | false>;\n\n\t/** Run comment:moderate exclusive hook. Returns moderation decision. */\n\trunModerate(event: CommentModerateEvent): Promise<ModerationDecision>;\n\n\t/** Fire comment:afterCreate (fire-and-forget). */\n\tfireAfterCreate(event: CommentAfterCreateEvent): void;\n\n\t/** Fire comment:afterModerate (fire-and-forget). */\n\tfireAfterModerate(event: CommentAfterModerateEvent): void;\n}\n\n// ---------------------------------------------------------------------------\n// Service\n// ---------------------------------------------------------------------------\n\n/**\n * Create a comment through the full hook pipeline.\n *\n * Returns null if the comment was rejected by a beforeCreate handler.\n */\nexport async function createComment(\n\tdb: Kysely<Database>,\n\tinput: CommentCreateInput,\n\tcollectionSettings: CollectionCommentSettings,\n\thooks: CommentHookRunner,\n\tcontentInfo?: {\n\t\tid: string;\n\t\tcollection: string;\n\t\tslug: string;\n\t\ttitle?: string;\n\t\tauthor?: { id: string; name: string | null; email: string };\n\t},\n): Promise<CommentCreateResult | null> {\n\tconst repo = new CommentRepository(db);\n\n\t// 1. Build the beforeCreate event\n\tconst beforeCreateEvent: CommentBeforeCreateEvent = {\n\t\tcomment: {\n\t\t\tcollection: input.collection,\n\t\t\tcontentId: input.contentId,\n\t\t\tparentId: input.parentId ?? null,\n\t\t\tauthorName: input.authorName,\n\t\t\tauthorEmail: input.authorEmail,\n\t\t\tauthorUserId: input.authorUserId ?? null,\n\t\t\tbody: input.body,\n\t\t\tipHash: input.ipHash ?? null,\n\t\t\tuserAgent: input.userAgent ?? null,\n\t\t},\n\t\tmetadata: {},\n\t};\n\n\t// 2. Run comment:beforeCreate pipeline\n\tconst result = await hooks.runBeforeCreate(beforeCreateEvent);\n\tif (result === false) {\n\t\treturn null; // Rejected\n\t}\n\n\tconst event = result;\n\n\t// 3. Query prior approved count for first-time moderation\n\tconst priorApprovedCount = await repo.countApprovedByEmail(event.comment.authorEmail);\n\n\t// 4. Run comment:moderate exclusive hook\n\tconst moderateEvent: CommentModerateEvent = {\n\t\tcomment: event.comment,\n\t\tmetadata: event.metadata,\n\t\tcollectionSettings,\n\t\tpriorApprovedCount,\n\t};\n\n\tconst decision = await hooks.runModerate(moderateEvent);\n\n\t// 5. Save comment with determined status\n\tconst comment = await repo.create({\n\t\tcollection: event.comment.collection,\n\t\tcontentId: event.comment.contentId,\n\t\tparentId: event.comment.parentId,\n\t\tauthorName: event.comment.authorName,\n\t\tauthorEmail: event.comment.authorEmail,\n\t\tauthorUserId: event.comment.authorUserId,\n\t\tbody: event.comment.body,\n\t\tstatus: decision.status,\n\t\tipHash: event.comment.ipHash,\n\t\tuserAgent: event.comment.userAgent,\n\t\tmoderationMetadata: Object.keys(event.metadata).length > 0 ? event.metadata : null,\n\t});\n\n\t// 6. Fire comment:afterCreate (fire-and-forget)\n\tif (contentInfo) {\n\t\tconst afterEvent: CommentAfterCreateEvent = {\n\t\t\tcomment: commentToStored(comment),\n\t\t\tmetadata: event.metadata,\n\t\t\tcontent: {\n\t\t\t\tid: contentInfo.id,\n\t\t\t\tcollection: contentInfo.collection,\n\t\t\t\tslug: contentInfo.slug,\n\t\t\t\ttitle: contentInfo.title,\n\t\t\t},\n\t\t\tcontentAuthor: contentInfo.author,\n\t\t};\n\t\thooks.fireAfterCreate(afterEvent);\n\t}\n\n\treturn { comment, decision };\n}\n\n/**\n * Admin moderation — change a comment's status.\n * Fires comment:afterModerate hook.\n */\nexport async function moderateComment(\n\tdb: Kysely<Database>,\n\tid: string,\n\tnewStatus: CommentStatus,\n\tmoderator: { id: string; name: string | null },\n\thooks: CommentHookRunner,\n): Promise<Comment | null> {\n\tconst repo = new CommentRepository(db);\n\tconst existing = await repo.findById(id);\n\tif (!existing) return null;\n\n\tconst previousStatus = existing.status;\n\tconst updated = await repo.updateStatus(id, newStatus);\n\tif (!updated) return null;\n\n\t// Fire comment:afterModerate (fire-and-forget)\n\tconst afterEvent: CommentAfterModerateEvent = {\n\t\tcomment: commentToStored(updated),\n\t\tpreviousStatus,\n\t\tnewStatus,\n\t\tmoderator,\n\t};\n\thooks.fireAfterModerate(afterEvent);\n\n\treturn updated;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction commentToStored(comment: Comment): StoredComment {\n\treturn {\n\t\tid: comment.id,\n\t\tcollection: comment.collection,\n\t\tcontentId: comment.contentId,\n\t\tparentId: comment.parentId,\n\t\tauthorName: comment.authorName,\n\t\tauthorEmail: comment.authorEmail,\n\t\tauthorUserId: comment.authorUserId,\n\t\tbody: comment.body,\n\t\tstatus: comment.status,\n\t\tmoderationMetadata: comment.moderationMetadata,\n\t\tcreatedAt: comment.createdAt,\n\t\tupdatedAt: comment.updatedAt,\n\t};\n}\n"],"mappings":";;;;;AAiBA,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAC3B,MAAM,UAAU;;;;AAahB,SAAgB,8BACf,IACA,MACe;CACf,MAAM,QAAQ,KAAK,gBAAgB,GAAG,KAAK,WAAW;CACtD,MAAM,UAAU,mBAAmB,MAAM,GAAG,QAAQ,SAAS,IAAI;CAEjE,MAAM,UACL,KAAK,YAAY,SAAS,qBACvB,KAAK,YAAY,MAAM,GAAG,mBAAmB,GAAG,QAChD,KAAK;CAET,MAAM,WAAW,GAAG,KAAK,aAAa;AAgBtC,QAAO;EAAE;EAAI;EAAS,MAdT;GACZ,GAAG,KAAK,kBAAkB,iBAAiB,MAAM;GACjD;GACA;GACA;GACA,kBAAkB;GAClB,CAAC,KAAK,KAAK;EAQgB,MANf;GACZ,cAAc,WAAW,KAAK,kBAAkB,CAAC,gCAAgC,WAAW,MAAM,CAAC;GACnG,6FAA6F,WAAW,QAAQ,CAAC;GACjH,eAAe,WAAW,SAAS,CAAC;GACpC,CAAC,KAAK,KAAK;EAEsB;;;;;;;;;;;AAYnC,eAAsB,wBAAwB,QAYzB;CACpB,MAAM,EAAE,OAAO,SAAS,eAAe,iBAAiB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AI,CAAC,QAAS,QAAO;CAGrB,MAAM,aAAwC;EAC7C,SAAS,gBAAgB,QAAQ;EACjC;EACA;EACA;EACA;AACD,OAAM,kBAAkB,WAAW;AAEnC,QAAO;;AAOR,SAAS,gBAAgB,SAAiC;AACzD,QAAO;EACN,IAAI,QAAQ;EACZ,YAAY,QAAQ;EACpB,WAAW,QAAQ;EACnB,UAAU,QAAQ;EAClB,YAAY,QAAQ;EACpB,aAAa,QAAQ;EACrB,cAAc,QAAQ;EACtB,MAAM,QAAQ;EACd,QAAQ,QAAQ;EAChB,oBAAoB,QAAQ;EAC5B,WAAW,QAAQ;EACnB,WAAW,QAAQ;EACnB"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { t as after } from "./after-B1IIdH3Y.mjs";
|
|
2
2
|
import { l as invalidateObjectCache, n as cachedQuery } from "./object-cache-Bok5j2ae.mjs";
|
|
3
|
-
import { t as MediaRepository } from "./media-
|
|
3
|
+
import { t as MediaRepository } from "./media-its1WLYv.mjs";
|
|
4
4
|
import { t as OptionsRepository } from "./options-BlmBHTvX.mjs";
|
|
5
5
|
import { n as peekRequestCache, r as requestCached } from "./request-cache-BSUptuJR.mjs";
|
|
6
|
-
import { a as getDb } from "./loader-
|
|
6
|
+
import { a as getDb } from "./loader-D4rigvjR.mjs";
|
|
7
7
|
import { n as invalidateSingleFlightCache, r as singleFlightCached, t as createSingleFlightCache } from "./single-flight-cache-C2exrGAi.mjs";
|
|
8
8
|
|
|
9
9
|
//#region src/settings/index.ts
|
|
@@ -242,4 +242,4 @@ async function getPluginSettingsWithDb(pluginId, db) {
|
|
|
242
242
|
|
|
243
243
|
//#endregion
|
|
244
244
|
export { getSiteSettingsWithDb as a, getSiteSettings as i, getPluginSettings as n, invalidateSiteSettingsCache as o, getSiteSetting as r, setSiteSettings as s, getPluginSetting as t };
|
|
245
|
-
//# sourceMappingURL=settings-
|
|
245
|
+
//# sourceMappingURL=settings-C2PaBS49.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings-CpA4lQFt.mjs","names":[],"sources":["../src/settings/index.ts"],"sourcesContent":["/**\n * Site Settings API\n *\n * Functions for getting and setting global site configuration.\n * Settings are stored in the options table with 'site:' prefix.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { after } from \"../after.js\";\nimport { MediaRepository } from \"../database/repositories/media.js\";\nimport { OptionsRepository } from \"../database/repositories/options.js\";\nimport type { Database } from \"../database/types.js\";\nimport { getDb } from \"../loader.js\";\nimport { cachedQuery, invalidateObjectCache } from \"../object-cache/index.js\";\nimport { peekRequestCache, requestCached } from \"../request-cache.js\";\n\n/** Object-cache namespace for site settings. */\nconst SETTINGS_CACHE_NAMESPACE = \"settings\";\nimport type { Storage } from \"../storage/types.js\";\nimport {\n\tcreateSingleFlightCache,\n\ttype SingleFlightCache,\n\tinvalidateSingleFlightCache,\n\tsingleFlightCached,\n} from \"../utils/single-flight-cache.js\";\nimport type { SiteSettings, SiteSettingKey, MediaReference, SeoSettings } from \"./types.js\";\n\n/** Prefix for site settings in the options table */\nconst SETTINGS_PREFIX = \"site:\";\n\n/**\n * Worker-isolate cache for the resolved `site:*` settings.\n *\n * Site settings (title, logo, SEO defaults) change rarely but are read on\n * every public request. Caching across the isolate's lifetime drops the\n * `options WHERE name LIKE 'site:%'` prefix scan from once-per-request to\n * once-per-isolate. Cross-isolate staleness is bounded by isolate lifetime\n * (workerd typically recycles within minutes); acceptable for chrome.\n *\n * Backed by single-flight-cache.ts: concurrent cold reads coalesce onto one\n * query via a reclaimable single-flight lock and the resolved *value* is\n * cached — never a shared in-flight promise, so a cancelled request can't\n * poison the isolate (see that file's header). Stored on globalThis with a\n * Symbol.for key so Vite SSR chunk duplication doesn't produce two\n * independent caches (same pattern as request-context.ts).\n */\nconst SITE_SETTINGS_CACHE_KEY = Symbol.for(\"emdash:site-settings\");\nconst g = globalThis as Record<symbol, unknown>;\nconst settingsCache: SingleFlightCache<Partial<SiteSettings>> =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see request-context.ts)\n\t(g[SITE_SETTINGS_CACHE_KEY] as SingleFlightCache<Partial<SiteSettings>> | undefined) ??\n\t(() => {\n\t\tconst c = createSingleFlightCache<Partial<SiteSettings>>();\n\t\tg[SITE_SETTINGS_CACHE_KEY] = c;\n\t\treturn c;\n\t})();\n\n/**\n * Bump the isolate-wide site-settings cache version, forcing the next\n * `getSiteSettings()` to re-query the database.\n *\n * Called from every `site:*` write path. Other isolates still serve their\n * own cached copy until they expire — staleness bounded by isolate lifetime.\n */\nexport function invalidateSiteSettingsCache(): void {\n\tinvalidateSingleFlightCache(settingsCache);\n\t// Cross-isolate invalidation for the optional distributed object cache.\n\tinvalidateObjectCache(SETTINGS_CACHE_NAMESPACE);\n}\n\n/**\n * Type guard for MediaReference values\n */\nfunction isMediaReference(value: unknown): value is MediaReference {\n\treturn typeof value === \"object\" && value !== null && \"mediaId\" in value;\n}\n\n/**\n * Resolve a media reference to include the full URL plus content metadata.\n *\n * Pulls `mimeType` and intrinsic dimensions from the media row so callers\n * can emit correct head tags (e.g. `<link rel=\"icon\" type=\"image/svg+xml\">`,\n * which Chromium requires when the URL has no `.svg` extension) without\n * a second round-trip to the media table.\n */\nasync function resolveMediaReference(\n\tmediaRef: MediaReference | undefined,\n\tdb: Kysely<Database>,\n\t_storage: Storage | null,\n): Promise<MediaReference | undefined> {\n\tif (!mediaRef?.mediaId) {\n\t\treturn mediaRef;\n\t}\n\n\ttry {\n\t\tconst mediaRepo = new MediaRepository(db);\n\t\tconst media = await mediaRepo.findById(mediaRef.mediaId);\n\n\t\tif (media) {\n\t\t\t// Construct URL using the same pattern as API handlers\n\t\t\treturn {\n\t\t\t\t...mediaRef,\n\t\t\t\turl: `/_emdash/api/media/file/${media.storageKey}`,\n\t\t\t\tcontentType: media.mimeType,\n\t\t\t\t...(media.width !== null ? { width: media.width } : {}),\n\t\t\t\t...(media.height !== null ? { height: media.height } : {}),\n\t\t\t};\n\t\t}\n\t} catch {\n\t\t// If media not found or error, return the reference as-is\n\t}\n\n\treturn mediaRef;\n}\n\n/**\n * Get a single site setting by key\n *\n * Returns `undefined` if the setting has not been configured.\n * For media settings (logo, favicon), the URL is resolved automatically.\n *\n * @param key - The setting key (e.g., \"title\", \"logo\", \"social\")\n * @returns The setting value, or undefined if not set\n *\n * @example\n * ```ts\n * import { getSiteSetting } from \"emdash\";\n *\n * const title = await getSiteSetting(\"title\");\n * const logo = await getSiteSetting(\"logo\");\n * console.log(logo?.url); // Resolved URL\n * ```\n */\nexport async function getSiteSetting<K extends SiteSettingKey>(\n\tkey: K,\n): Promise<SiteSettings[K] | undefined> {\n\t// If `getSiteSettings()` has already been called in this request,\n\t// read from that (request-cached) batch rather than firing a second\n\t// options-table query. Common layout: a Base template pulls the\n\t// whole settings object up-front, then `EmDashHead` or a plugin\n\t// asks for one key — no reason the singular call should round-trip\n\t// again.\n\tconst primed = peekRequestCache<Partial<SiteSettings>>(\"siteSettings\");\n\tif (primed) {\n\t\tconst settings = await primed;\n\t\treturn settings[key];\n\t}\n\n\t// Otherwise cache per-key. Templates that pull several settings\n\t// independently still share the in-flight query for each one.\n\treturn requestCached(`siteSetting:${key}`, async () => {\n\t\tconst db = await getDb();\n\t\treturn getSiteSettingWithDb(key, db);\n\t});\n}\n\n/**\n * Get a single site setting by key (with explicit db)\n *\n * @internal Use `getSiteSetting()` in templates. This variant is for admin routes\n * that already have a database handle.\n */\nexport async function getSiteSettingWithDb<K extends SiteSettingKey>(\n\tkey: K,\n\tdb: Kysely<Database>,\n\tstorage: Storage | null = null,\n): Promise<SiteSettings[K] | undefined> {\n\tconst options = new OptionsRepository(db);\n\tconst value = await options.get<SiteSettings[K]>(`${SETTINGS_PREFIX}${key}`);\n\n\tif (!value) {\n\t\treturn undefined;\n\t}\n\n\t// Resolve media references if needed.\n\t// TS cannot narrow generic K from key equality checks — this is a known limitation.\n\t// We use the non-generic getSiteSettingsWithDb for media resolution instead.\n\tif ((key === \"logo\" || key === \"favicon\") && isMediaReference(value)) {\n\t\tconst resolved = await resolveMediaReference(value, db, storage);\n\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- TS can't narrow generic K from key equality; resolved type is correct\n\t\treturn resolved as SiteSettings[K] | undefined;\n\t}\n\n\tif (key === \"seo\" && value && typeof value === \"object\") {\n\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- TS can't narrow generic K from key equality\n\t\tconst seo = value as SeoSettings;\n\t\tif (seo.defaultOgImage) {\n\t\t\tconst resolved = {\n\t\t\t\t...seo,\n\t\t\t\tdefaultOgImage: await resolveMediaReference(seo.defaultOgImage, db, storage),\n\t\t\t};\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- TS can't narrow generic K from key equality\n\t\t\treturn resolved as SiteSettings[K] | undefined;\n\t\t}\n\t}\n\n\treturn value;\n}\n\n/**\n * Get all site settings\n *\n * Returns all configured settings. Unset values are undefined.\n * Media references (logo/favicon) are resolved to include URLs.\n *\n * @example\n * ```ts\n * import { getSiteSettings } from \"emdash\";\n *\n * const settings = await getSiteSettings();\n * console.log(settings.title); // \"My Site\"\n * console.log(settings.logo?.url); // \"/_emdash/api/media/file/abc123\"\n * ```\n */\nexport function getSiteSettings(): Promise<Partial<SiteSettings>> {\n\t// requestCached dedupes within a single request; singleFlightCached\n\t// coalesces across requests and caches the resolved value for the\n\t// global scope's lifetime without ever sharing an awaitable promise. The\n\t// distributed object cache (cachedQuery) sits beneath both, backing cold\n\t// isolates without a database round-trip.\n\treturn requestCached(\"siteSettings\", () =>\n\t\tsingleFlightCached(\n\t\t\tsettingsCache,\n\t\t\t() =>\n\t\t\t\tcachedQuery({\n\t\t\t\t\tnamespace: SETTINGS_CACHE_NAMESPACE,\n\t\t\t\t\tkey: \"all\",\n\t\t\t\t\tload: async () => {\n\t\t\t\t\t\tconst db = await getDb();\n\t\t\t\t\t\treturn getSiteSettingsWithDb(db);\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t{ anchor: (promise) => after(() => promise), ownerTimeoutMs: 30_000 },\n\t\t),\n\t);\n}\n\n/**\n * Get all site settings (with explicit db)\n *\n * @internal Use `getSiteSettings()` in templates. This variant is for admin routes\n * that already have a database handle.\n */\nexport async function getSiteSettingsWithDb(\n\tdb: Kysely<Database>,\n\tstorage: Storage | null = null,\n): Promise<Partial<SiteSettings>> {\n\tconst options = new OptionsRepository(db);\n\tconst allOptions = await options.getByPrefix(SETTINGS_PREFIX);\n\n\tconst settings: Record<string, unknown> = {};\n\n\t// Convert Map to settings object, removing the prefix\n\tfor (const [key, value] of allOptions) {\n\t\tconst settingKey = key.replace(SETTINGS_PREFIX, \"\");\n\t\tsettings[settingKey] = value;\n\t}\n\n\tconst typedSettings = settings as Partial<SiteSettings>;\n\n\t// Resolve media references\n\tif (typedSettings.logo) {\n\t\ttypedSettings.logo = await resolveMediaReference(typedSettings.logo, db, storage);\n\t}\n\tif (typedSettings.favicon) {\n\t\ttypedSettings.favicon = await resolveMediaReference(typedSettings.favicon, db, storage);\n\t}\n\tif (typedSettings.seo?.defaultOgImage) {\n\t\ttypedSettings.seo = {\n\t\t\t...typedSettings.seo,\n\t\t\tdefaultOgImage: await resolveMediaReference(typedSettings.seo.defaultOgImage, db, storage),\n\t\t};\n\t}\n\n\treturn typedSettings;\n}\n\n/**\n * Set site settings (internal function used by admin API)\n *\n * Merges provided settings with existing ones. Only provided fields are updated.\n * Media references should include just the mediaId; URLs are resolved on read.\n *\n * @param settings - Partial settings object with values to update\n * @param db - Kysely database instance\n * @returns Promise that resolves when settings are saved\n *\n * @internal\n *\n * @example\n * ```ts\n * // Update multiple settings at once\n * await setSiteSettings({\n * title: \"My Site\",\n * tagline: \"Welcome\",\n * logo: { mediaId: \"med_123\", alt: \"Logo\" }\n * }, db);\n * ```\n */\nexport async function setSiteSettings(\n\tsettings: Partial<SiteSettings>,\n\tdb: Kysely<Database>,\n): Promise<void> {\n\tconst options = new OptionsRepository(db);\n\n\t// Convert settings to options format\n\tconst updates: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(settings)) {\n\t\tif (value !== undefined) {\n\t\t\tupdates[`${SETTINGS_PREFIX}${key}`] = value;\n\t\t}\n\t}\n\n\ttry {\n\t\tawait options.setMany(updates);\n\t} finally {\n\t\tinvalidateSiteSettingsCache();\n\t}\n}\n\n/**\n * Get a single plugin setting by key.\n *\n * Plugin settings are stored in the options table under\n * `plugin:<pluginId>:settings:<key>`.\n */\nexport async function getPluginSetting<T = unknown>(\n\tpluginId: string,\n\tkey: string,\n): Promise<T | undefined> {\n\tconst db = await getDb();\n\treturn getPluginSettingWithDb<T>(pluginId, key, db);\n}\n\n/**\n * Get a single plugin setting by key (with explicit db).\n *\n * @internal Use `getPluginSetting()` in templates and plugin rendering code.\n */\nexport async function getPluginSettingWithDb<T = unknown>(\n\tpluginId: string,\n\tkey: string,\n\tdb: Kysely<Database>,\n): Promise<T | undefined> {\n\tconst options = new OptionsRepository(db);\n\tconst value = await options.get<T>(`plugin:${pluginId}:settings:${key}`);\n\treturn value ?? undefined;\n}\n\n/**\n * Get all persisted plugin settings for a plugin.\n *\n * Defaults declared in `admin.settingsSchema` are not materialized\n * automatically; callers should apply their own fallback defaults.\n */\nexport async function getPluginSettings(pluginId: string): Promise<Record<string, unknown>> {\n\tconst db = await getDb();\n\treturn getPluginSettingsWithDb(pluginId, db);\n}\n\n/**\n * Get all persisted plugin settings for a plugin (with explicit db).\n *\n * @internal Use `getPluginSettings()` in templates and plugin rendering code.\n */\nexport async function getPluginSettingsWithDb(\n\tpluginId: string,\n\tdb: Kysely<Database>,\n): Promise<Record<string, unknown>> {\n\tconst prefix = `plugin:${pluginId}:settings:`;\n\tconst options = new OptionsRepository(db);\n\tconst allOptions = await options.getByPrefix(prefix);\n\n\tconst settings: Record<string, unknown> = {};\n\tfor (const [key, value] of allOptions) {\n\t\tif (!key.startsWith(prefix)) {\n\t\t\tcontinue;\n\t\t}\n\t\tsettings[key.slice(prefix.length)] = value;\n\t}\n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U,OACb,SAAQ,GAAG,kBAAkB,SAAS;AAIxC,KAAI;AACH,QAAM,QAAQ,QAAQ,QAAQ;WACrB;AACT,+BAA6B;;;;;;;;;AAU/B,eAAsB,iBACrB,UACA,KACyB;AAEzB,QAAO,uBAA0B,UAAU,KADhC,MAAM,OAAO,CAC2B;;;;;;;AAQpD,eAAsB,uBACrB,UACA,KACA,IACyB;AAGzB,QADc,MADE,IAAI,kBAAkB,GAAG,CACb,IAAO,UAAU,SAAS,YAAY,MAAM,IACxD;;;;;;;;AASjB,eAAsB,kBAAkB,UAAoD;AAE3F,QAAO,wBAAwB,UADpB,MAAM,OAAO,CACoB;;;;;;;AAQ7C,eAAsB,wBACrB,UACA,IACmC;CACnC,MAAM,SAAS,UAAU,SAAS;CAElC,MAAM,aAAa,MADH,IAAI,kBAAkB,GAAG,CACR,YAAY,OAAO;CAEpD,MAAM,WAAoC,EAAE;AAC5C,MAAK,MAAM,CAAC,KAAK,UAAU,YAAY;AACtC,MAAI,CAAC,IAAI,WAAW,OAAO,CAC1B;AAED,WAAS,IAAI,MAAM,OAAO,OAAO,IAAI;;AAGtC,QAAO"}
|
|
1
|
+
{"version":3,"file":"settings-C2PaBS49.mjs","names":[],"sources":["../src/settings/index.ts"],"sourcesContent":["/**\n * Site Settings API\n *\n * Functions for getting and setting global site configuration.\n * Settings are stored in the options table with 'site:' prefix.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { after } from \"../after.js\";\nimport { MediaRepository } from \"../database/repositories/media.js\";\nimport { OptionsRepository } from \"../database/repositories/options.js\";\nimport type { Database } from \"../database/types.js\";\nimport { getDb } from \"../loader.js\";\nimport { cachedQuery, invalidateObjectCache } from \"../object-cache/index.js\";\nimport { peekRequestCache, requestCached } from \"../request-cache.js\";\n\n/** Object-cache namespace for site settings. */\nconst SETTINGS_CACHE_NAMESPACE = \"settings\";\nimport type { Storage } from \"../storage/types.js\";\nimport {\n\tcreateSingleFlightCache,\n\ttype SingleFlightCache,\n\tinvalidateSingleFlightCache,\n\tsingleFlightCached,\n} from \"../utils/single-flight-cache.js\";\nimport type { SiteSettings, SiteSettingKey, MediaReference, SeoSettings } from \"./types.js\";\n\n/** Prefix for site settings in the options table */\nconst SETTINGS_PREFIX = \"site:\";\n\n/**\n * Worker-isolate cache for the resolved `site:*` settings.\n *\n * Site settings (title, logo, SEO defaults) change rarely but are read on\n * every public request. Caching across the isolate's lifetime drops the\n * `options WHERE name LIKE 'site:%'` prefix scan from once-per-request to\n * once-per-isolate. Cross-isolate staleness is bounded by isolate lifetime\n * (workerd typically recycles within minutes); acceptable for chrome.\n *\n * Backed by single-flight-cache.ts: concurrent cold reads coalesce onto one\n * query via a reclaimable single-flight lock and the resolved *value* is\n * cached — never a shared in-flight promise, so a cancelled request can't\n * poison the isolate (see that file's header). Stored on globalThis with a\n * Symbol.for key so Vite SSR chunk duplication doesn't produce two\n * independent caches (same pattern as request-context.ts).\n */\nconst SITE_SETTINGS_CACHE_KEY = Symbol.for(\"emdash:site-settings\");\nconst g = globalThis as Record<symbol, unknown>;\nconst settingsCache: SingleFlightCache<Partial<SiteSettings>> =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see request-context.ts)\n\t(g[SITE_SETTINGS_CACHE_KEY] as SingleFlightCache<Partial<SiteSettings>> | undefined) ??\n\t(() => {\n\t\tconst c = createSingleFlightCache<Partial<SiteSettings>>();\n\t\tg[SITE_SETTINGS_CACHE_KEY] = c;\n\t\treturn c;\n\t})();\n\n/**\n * Bump the isolate-wide site-settings cache version, forcing the next\n * `getSiteSettings()` to re-query the database.\n *\n * Called from every `site:*` write path. Other isolates still serve their\n * own cached copy until they expire — staleness bounded by isolate lifetime.\n */\nexport function invalidateSiteSettingsCache(): void {\n\tinvalidateSingleFlightCache(settingsCache);\n\t// Cross-isolate invalidation for the optional distributed object cache.\n\tinvalidateObjectCache(SETTINGS_CACHE_NAMESPACE);\n}\n\n/**\n * Type guard for MediaReference values\n */\nfunction isMediaReference(value: unknown): value is MediaReference {\n\treturn typeof value === \"object\" && value !== null && \"mediaId\" in value;\n}\n\n/**\n * Resolve a media reference to include the full URL plus content metadata.\n *\n * Pulls `mimeType` and intrinsic dimensions from the media row so callers\n * can emit correct head tags (e.g. `<link rel=\"icon\" type=\"image/svg+xml\">`,\n * which Chromium requires when the URL has no `.svg` extension) without\n * a second round-trip to the media table.\n */\nasync function resolveMediaReference(\n\tmediaRef: MediaReference | undefined,\n\tdb: Kysely<Database>,\n\t_storage: Storage | null,\n): Promise<MediaReference | undefined> {\n\tif (!mediaRef?.mediaId) {\n\t\treturn mediaRef;\n\t}\n\n\ttry {\n\t\tconst mediaRepo = new MediaRepository(db);\n\t\tconst media = await mediaRepo.findById(mediaRef.mediaId);\n\n\t\tif (media) {\n\t\t\t// Construct URL using the same pattern as API handlers\n\t\t\treturn {\n\t\t\t\t...mediaRef,\n\t\t\t\turl: `/_emdash/api/media/file/${media.storageKey}`,\n\t\t\t\tcontentType: media.mimeType,\n\t\t\t\t...(media.width !== null ? { width: media.width } : {}),\n\t\t\t\t...(media.height !== null ? { height: media.height } : {}),\n\t\t\t};\n\t\t}\n\t} catch {\n\t\t// If media not found or error, return the reference as-is\n\t}\n\n\treturn mediaRef;\n}\n\n/**\n * Get a single site setting by key\n *\n * Returns `undefined` if the setting has not been configured.\n * For media settings (logo, favicon), the URL is resolved automatically.\n *\n * @param key - The setting key (e.g., \"title\", \"logo\", \"social\")\n * @returns The setting value, or undefined if not set\n *\n * @example\n * ```ts\n * import { getSiteSetting } from \"emdash\";\n *\n * const title = await getSiteSetting(\"title\");\n * const logo = await getSiteSetting(\"logo\");\n * console.log(logo?.url); // Resolved URL\n * ```\n */\nexport async function getSiteSetting<K extends SiteSettingKey>(\n\tkey: K,\n): Promise<SiteSettings[K] | undefined> {\n\t// If `getSiteSettings()` has already been called in this request,\n\t// read from that (request-cached) batch rather than firing a second\n\t// options-table query. Common layout: a Base template pulls the\n\t// whole settings object up-front, then `EmDashHead` or a plugin\n\t// asks for one key — no reason the singular call should round-trip\n\t// again.\n\tconst primed = peekRequestCache<Partial<SiteSettings>>(\"siteSettings\");\n\tif (primed) {\n\t\tconst settings = await primed;\n\t\treturn settings[key];\n\t}\n\n\t// Otherwise cache per-key. Templates that pull several settings\n\t// independently still share the in-flight query for each one.\n\treturn requestCached(`siteSetting:${key}`, async () => {\n\t\tconst db = await getDb();\n\t\treturn getSiteSettingWithDb(key, db);\n\t});\n}\n\n/**\n * Get a single site setting by key (with explicit db)\n *\n * @internal Use `getSiteSetting()` in templates. This variant is for admin routes\n * that already have a database handle.\n */\nexport async function getSiteSettingWithDb<K extends SiteSettingKey>(\n\tkey: K,\n\tdb: Kysely<Database>,\n\tstorage: Storage | null = null,\n): Promise<SiteSettings[K] | undefined> {\n\tconst options = new OptionsRepository(db);\n\tconst value = await options.get<SiteSettings[K]>(`${SETTINGS_PREFIX}${key}`);\n\n\tif (!value) {\n\t\treturn undefined;\n\t}\n\n\t// Resolve media references if needed.\n\t// TS cannot narrow generic K from key equality checks — this is a known limitation.\n\t// We use the non-generic getSiteSettingsWithDb for media resolution instead.\n\tif ((key === \"logo\" || key === \"favicon\") && isMediaReference(value)) {\n\t\tconst resolved = await resolveMediaReference(value, db, storage);\n\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- TS can't narrow generic K from key equality; resolved type is correct\n\t\treturn resolved as SiteSettings[K] | undefined;\n\t}\n\n\tif (key === \"seo\" && value && typeof value === \"object\") {\n\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- TS can't narrow generic K from key equality\n\t\tconst seo = value as SeoSettings;\n\t\tif (seo.defaultOgImage) {\n\t\t\tconst resolved = {\n\t\t\t\t...seo,\n\t\t\t\tdefaultOgImage: await resolveMediaReference(seo.defaultOgImage, db, storage),\n\t\t\t};\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- TS can't narrow generic K from key equality\n\t\t\treturn resolved as SiteSettings[K] | undefined;\n\t\t}\n\t}\n\n\treturn value;\n}\n\n/**\n * Get all site settings\n *\n * Returns all configured settings. Unset values are undefined.\n * Media references (logo/favicon) are resolved to include URLs.\n *\n * @example\n * ```ts\n * import { getSiteSettings } from \"emdash\";\n *\n * const settings = await getSiteSettings();\n * console.log(settings.title); // \"My Site\"\n * console.log(settings.logo?.url); // \"/_emdash/api/media/file/abc123\"\n * ```\n */\nexport function getSiteSettings(): Promise<Partial<SiteSettings>> {\n\t// requestCached dedupes within a single request; singleFlightCached\n\t// coalesces across requests and caches the resolved value for the\n\t// global scope's lifetime without ever sharing an awaitable promise. The\n\t// distributed object cache (cachedQuery) sits beneath both, backing cold\n\t// isolates without a database round-trip.\n\treturn requestCached(\"siteSettings\", () =>\n\t\tsingleFlightCached(\n\t\t\tsettingsCache,\n\t\t\t() =>\n\t\t\t\tcachedQuery({\n\t\t\t\t\tnamespace: SETTINGS_CACHE_NAMESPACE,\n\t\t\t\t\tkey: \"all\",\n\t\t\t\t\tload: async () => {\n\t\t\t\t\t\tconst db = await getDb();\n\t\t\t\t\t\treturn getSiteSettingsWithDb(db);\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t{ anchor: (promise) => after(() => promise), ownerTimeoutMs: 30_000 },\n\t\t),\n\t);\n}\n\n/**\n * Get all site settings (with explicit db)\n *\n * @internal Use `getSiteSettings()` in templates. This variant is for admin routes\n * that already have a database handle.\n */\nexport async function getSiteSettingsWithDb(\n\tdb: Kysely<Database>,\n\tstorage: Storage | null = null,\n): Promise<Partial<SiteSettings>> {\n\tconst options = new OptionsRepository(db);\n\tconst allOptions = await options.getByPrefix(SETTINGS_PREFIX);\n\n\tconst settings: Record<string, unknown> = {};\n\n\t// Convert Map to settings object, removing the prefix\n\tfor (const [key, value] of allOptions) {\n\t\tconst settingKey = key.replace(SETTINGS_PREFIX, \"\");\n\t\tsettings[settingKey] = value;\n\t}\n\n\tconst typedSettings = settings as Partial<SiteSettings>;\n\n\t// Resolve media references\n\tif (typedSettings.logo) {\n\t\ttypedSettings.logo = await resolveMediaReference(typedSettings.logo, db, storage);\n\t}\n\tif (typedSettings.favicon) {\n\t\ttypedSettings.favicon = await resolveMediaReference(typedSettings.favicon, db, storage);\n\t}\n\tif (typedSettings.seo?.defaultOgImage) {\n\t\ttypedSettings.seo = {\n\t\t\t...typedSettings.seo,\n\t\t\tdefaultOgImage: await resolveMediaReference(typedSettings.seo.defaultOgImage, db, storage),\n\t\t};\n\t}\n\n\treturn typedSettings;\n}\n\n/**\n * Set site settings (internal function used by admin API)\n *\n * Merges provided settings with existing ones. Only provided fields are updated.\n * Media references should include just the mediaId; URLs are resolved on read.\n *\n * @param settings - Partial settings object with values to update\n * @param db - Kysely database instance\n * @returns Promise that resolves when settings are saved\n *\n * @internal\n *\n * @example\n * ```ts\n * // Update multiple settings at once\n * await setSiteSettings({\n * title: \"My Site\",\n * tagline: \"Welcome\",\n * logo: { mediaId: \"med_123\", alt: \"Logo\" }\n * }, db);\n * ```\n */\nexport async function setSiteSettings(\n\tsettings: Partial<SiteSettings>,\n\tdb: Kysely<Database>,\n): Promise<void> {\n\tconst options = new OptionsRepository(db);\n\n\t// Convert settings to options format\n\tconst updates: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(settings)) {\n\t\tif (value !== undefined) {\n\t\t\tupdates[`${SETTINGS_PREFIX}${key}`] = value;\n\t\t}\n\t}\n\n\ttry {\n\t\tawait options.setMany(updates);\n\t} finally {\n\t\tinvalidateSiteSettingsCache();\n\t}\n}\n\n/**\n * Get a single plugin setting by key.\n *\n * Plugin settings are stored in the options table under\n * `plugin:<pluginId>:settings:<key>`.\n */\nexport async function getPluginSetting<T = unknown>(\n\tpluginId: string,\n\tkey: string,\n): Promise<T | undefined> {\n\tconst db = await getDb();\n\treturn getPluginSettingWithDb<T>(pluginId, key, db);\n}\n\n/**\n * Get a single plugin setting by key (with explicit db).\n *\n * @internal Use `getPluginSetting()` in templates and plugin rendering code.\n */\nexport async function getPluginSettingWithDb<T = unknown>(\n\tpluginId: string,\n\tkey: string,\n\tdb: Kysely<Database>,\n): Promise<T | undefined> {\n\tconst options = new OptionsRepository(db);\n\tconst value = await options.get<T>(`plugin:${pluginId}:settings:${key}`);\n\treturn value ?? undefined;\n}\n\n/**\n * Get all persisted plugin settings for a plugin.\n *\n * Defaults declared in `admin.settingsSchema` are not materialized\n * automatically; callers should apply their own fallback defaults.\n */\nexport async function getPluginSettings(pluginId: string): Promise<Record<string, unknown>> {\n\tconst db = await getDb();\n\treturn getPluginSettingsWithDb(pluginId, db);\n}\n\n/**\n * Get all persisted plugin settings for a plugin (with explicit db).\n *\n * @internal Use `getPluginSettings()` in templates and plugin rendering code.\n */\nexport async function getPluginSettingsWithDb(\n\tpluginId: string,\n\tdb: Kysely<Database>,\n): Promise<Record<string, unknown>> {\n\tconst prefix = `plugin:${pluginId}:settings:`;\n\tconst options = new OptionsRepository(db);\n\tconst allOptions = await options.getByPrefix(prefix);\n\n\tconst settings: Record<string, unknown> = {};\n\tfor (const [key, value] of allOptions) {\n\t\tif (!key.startsWith(prefix)) {\n\t\t\tcontinue;\n\t\t}\n\t\tsettings[key.slice(prefix.length)] = value;\n\t}\n\n\treturn settings;\n}\n"],"mappings":";;;;;;;;;;AAkBA,MAAM,2BAA2B;;AAWjC,MAAM,kBAAkB;;;;;;;;;;;;;;;;;AAkBxB,MAAM,0BAA0B,OAAO,IAAI,uBAAuB;AAClE,MAAM,IAAI;AACV,MAAM,gBAEJ,EAAE,mCACI;CACN,MAAM,IAAI,yBAAgD;AAC1D,GAAE,2BAA2B;AAC7B,QAAO;IACJ;;;;;;;;AASL,SAAgB,8BAAoC;AACnD,6BAA4B,cAAc;AAE1C,uBAAsB,yBAAyB;;;;;AAMhD,SAAS,iBAAiB,OAAyC;AAClE,QAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa;;;;;;;;;;AAWpE,eAAe,sBACd,UACA,IACA,UACsC;AACtC,KAAI,CAAC,UAAU,QACd,QAAO;AAGR,KAAI;EAEH,MAAM,QAAQ,MADI,I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EpD,MAAM,WAAoC,EAAE;AAC5C,MAAK,MAAM,CAAC,KAAK,UAAU,YAAY;AACtC,MAAI,CAAC,IAAI,WAAW,OAAO,CAC1B;AAED,WAAS,IAAI,MAAM,OAAO,OAAO,IAAI;;AAGtC,QAAO"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { o as __exportAll } from "./runner-
|
|
2
|
-
import { a as getSiteSettingsWithDb, s as setSiteSettings } from "./settings-
|
|
1
|
+
import { o as __exportAll } from "./runner-BdeLEgad.mjs";
|
|
2
|
+
import { a as getSiteSettingsWithDb, s as setSiteSettings } from "./settings-C2PaBS49.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/api/handlers/settings.ts
|
|
5
5
|
var settings_exports = /* @__PURE__ */ __exportAll({
|
|
@@ -48,4 +48,4 @@ async function handleSettingsUpdate(db, storage, input) {
|
|
|
48
48
|
|
|
49
49
|
//#endregion
|
|
50
50
|
export { handleSettingsUpdate as n, settings_exports as r, handleSettingsGet as t };
|
|
51
|
-
//# sourceMappingURL=settings-
|
|
51
|
+
//# sourceMappingURL=settings-Dtc0DU31.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"settings-
|
|
1
|
+
{"version":3,"file":"settings-Dtc0DU31.mjs","names":[],"sources":["../src/api/handlers/settings.ts"],"sourcesContent":["/**\n * Settings handlers\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport type { Database } from \"../../database/types.js\";\nimport { getSiteSettingsWithDb, setSiteSettings } from \"../../settings/index.js\";\nimport type { SiteSettings } from \"../../settings/types.js\";\nimport type { Storage } from \"../../storage/types.js\";\nimport type { ApiResult } from \"../types.js\";\n\n/**\n * Get all site settings\n */\nexport async function handleSettingsGet(\n\tdb: Kysely<Database>,\n\tstorage: Storage | null,\n): Promise<ApiResult<Partial<SiteSettings>>> {\n\ttry {\n\t\tconst settings = await getSiteSettingsWithDb(db, storage);\n\t\treturn { success: true, data: settings };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"SETTINGS_READ_ERROR\", message: \"Failed to get settings\" },\n\t\t};\n\t}\n}\n\n/**\n * Update site settings\n */\nexport async function handleSettingsUpdate(\n\tdb: Kysely<Database>,\n\tstorage: Storage | null,\n\tinput: Partial<SiteSettings>,\n): Promise<ApiResult<Partial<SiteSettings>>> {\n\ttry {\n\t\tawait setSiteSettings(input, db);\n\t\tconst updatedSettings = await getSiteSettingsWithDb(db, storage);\n\t\treturn { success: true, data: updatedSettings };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"SETTINGS_UPDATE_ERROR\", message: \"Failed to update settings\" },\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAeA,eAAsB,kBACrB,IACA,SAC4C;AAC5C,KAAI;AAEH,SAAO;GAAE,SAAS;GAAM,MADP,MAAM,sBAAsB,IAAI,QAAQ;GACjB;SACjC;AACP,SAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAuB,SAAS;IAA0B;GACzE;;;;;;AAOH,eAAsB,qBACrB,IACA,SACA,OAC4C;AAC5C,KAAI;AACH,QAAM,gBAAgB,OAAO,GAAG;AAEhC,SAAO;GAAE,SAAS;GAAM,MADA,MAAM,sBAAsB,IAAI,QAAQ;GACjB;SACxC;AACP,SAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAyB,SAAS;IAA6B;GAC9E"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { o as __exportAll } from "./runner-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { o as __exportAll } from "./runner-BdeLEgad.mjs";
|
|
2
|
+
import { i as resolveConfiguredLocale } from "./config-B6b_BobR.mjs";
|
|
3
|
+
import { t as TaxonomyRepository } from "./taxonomy-0mCI25HN.mjs";
|
|
4
|
+
import { f as fetchVisibleTermCounts, l as invalidateTaxonomyDefsCache, u as invalidateTermCache } from "./taxonomies-r7pqLBCn.mjs";
|
|
4
5
|
import { ulid } from "ulidx";
|
|
5
6
|
|
|
6
7
|
//#region src/api/handlers/taxonomies.ts
|
|
@@ -71,8 +72,9 @@ function rowToDef(row) {
|
|
|
71
72
|
*/
|
|
72
73
|
async function handleTaxonomyList(db, options = {}) {
|
|
73
74
|
try {
|
|
75
|
+
const locale = options.locale ? resolveConfiguredLocale(options.locale) : void 0;
|
|
74
76
|
let query = db.selectFrom("_emdash_taxonomy_defs").selectAll();
|
|
75
|
-
if (
|
|
77
|
+
if (locale !== void 0) query = query.where("locale", "=", locale);
|
|
76
78
|
const [rows, collectionRows] = await Promise.all([query.execute(), db.selectFrom("_emdash_collections").select("slug").execute()]);
|
|
77
79
|
const realCollections = new Set(collectionRows.map((r) => r.slug));
|
|
78
80
|
return {
|
|
@@ -100,6 +102,7 @@ async function handleTaxonomyList(db, options = {}) {
|
|
|
100
102
|
*/
|
|
101
103
|
async function handleTaxonomyCreate(db, input) {
|
|
102
104
|
try {
|
|
105
|
+
const locale = input.locale ? resolveConfiguredLocale(input.locale) : void 0;
|
|
103
106
|
if (!NAME_PATTERN.test(input.name)) return {
|
|
104
107
|
success: false,
|
|
105
108
|
error: {
|
|
@@ -132,12 +135,12 @@ async function handleTaxonomyCreate(db, input) {
|
|
|
132
135
|
};
|
|
133
136
|
translationGroup = source.translation_group ?? source.id;
|
|
134
137
|
}
|
|
135
|
-
if (
|
|
136
|
-
if (await db.selectFrom("_emdash_taxonomy_defs").select("id").where("name", "=", input.name).where("locale", "=",
|
|
138
|
+
if (locale !== void 0) {
|
|
139
|
+
if (await db.selectFrom("_emdash_taxonomy_defs").select("id").where("name", "=", input.name).where("locale", "=", locale).executeTakeFirst()) return {
|
|
137
140
|
success: false,
|
|
138
141
|
error: {
|
|
139
142
|
code: "CONFLICT",
|
|
140
|
-
message: `Taxonomy '${input.name}' already exists in locale '${
|
|
143
|
+
message: `Taxonomy '${input.name}' already exists in locale '${locale}'`
|
|
141
144
|
}
|
|
142
145
|
};
|
|
143
146
|
}
|
|
@@ -149,7 +152,7 @@ async function handleTaxonomyCreate(db, input) {
|
|
|
149
152
|
label_singular: input.labelSingular ?? null,
|
|
150
153
|
hierarchical: input.hierarchical ? 1 : 0,
|
|
151
154
|
collections: JSON.stringify(collections),
|
|
152
|
-
...
|
|
155
|
+
...locale !== void 0 ? { locale } : {},
|
|
153
156
|
translation_group: translationGroup ?? id
|
|
154
157
|
}).execute();
|
|
155
158
|
invalidateTaxonomyDefsCache();
|
|
@@ -181,7 +184,9 @@ async function handleTermList(db, taxonomyName, options = {}) {
|
|
|
181
184
|
try {
|
|
182
185
|
const lookup = await requireTaxonomyDef(db, taxonomyName);
|
|
183
186
|
if (!lookup.success) return lookup;
|
|
184
|
-
const
|
|
187
|
+
const repo = new TaxonomyRepository(db);
|
|
188
|
+
const locale = options.locale ? resolveConfiguredLocale(options.locale) : void 0;
|
|
189
|
+
const terms = await repo.findByName(taxonomyName, { locale });
|
|
185
190
|
const countsByGroup = await fetchVisibleTermCounts(db, taxonomyName, defCollections(lookup.def));
|
|
186
191
|
const termData = terms.map((term) => ({
|
|
187
192
|
id: term.id,
|
|
@@ -269,15 +274,16 @@ async function validateParentTerm(repo, taxonomyName, termId, parentId, selfGrou
|
|
|
269
274
|
*/
|
|
270
275
|
async function handleTermCreate(db, taxonomyName, input) {
|
|
271
276
|
try {
|
|
277
|
+
const locale = input.locale ? resolveConfiguredLocale(input.locale) : void 0;
|
|
272
278
|
const lookup = await requireTaxonomyDef(db, taxonomyName);
|
|
273
279
|
if (!lookup.success) return lookup;
|
|
274
280
|
const repo = new TaxonomyRepository(db);
|
|
275
281
|
const parentId = input.parentId === "" || input.parentId === void 0 ? void 0 : input.parentId;
|
|
276
|
-
if (await repo.findBySlug(taxonomyName, input.slug,
|
|
282
|
+
if (await repo.findBySlug(taxonomyName, input.slug, locale)) return {
|
|
277
283
|
success: false,
|
|
278
284
|
error: {
|
|
279
285
|
code: "CONFLICT",
|
|
280
|
-
message:
|
|
286
|
+
message: locale ? `Term '${input.slug}' already exists in '${taxonomyName}' (${locale})` : `Term with slug '${input.slug}' already exists in taxonomy '${taxonomyName}'`
|
|
281
287
|
}
|
|
282
288
|
};
|
|
283
289
|
let selfGroup = null;
|
|
@@ -296,7 +302,7 @@ async function handleTermCreate(db, taxonomyName, input) {
|
|
|
296
302
|
label: input.label,
|
|
297
303
|
parentId: parentId ?? void 0,
|
|
298
304
|
data: input.description ? { description: input.description } : void 0,
|
|
299
|
-
locale
|
|
305
|
+
locale,
|
|
300
306
|
translationOf: input.translationOf
|
|
301
307
|
});
|
|
302
308
|
invalidateTermCache();
|
|
@@ -329,7 +335,8 @@ async function handleTermCreate(db, taxonomyName, input) {
|
|
|
329
335
|
async function handleTermGet(db, taxonomyName, termSlug, options = {}) {
|
|
330
336
|
try {
|
|
331
337
|
const repo = new TaxonomyRepository(db);
|
|
332
|
-
const
|
|
338
|
+
const locale = options.locale ? resolveConfiguredLocale(options.locale) : void 0;
|
|
339
|
+
const term = await repo.findBySlug(taxonomyName, termSlug, locale);
|
|
333
340
|
if (!term) return {
|
|
334
341
|
success: false,
|
|
335
342
|
error: {
|
|
@@ -409,7 +416,8 @@ async function handleTermTranslations(db, idOrGroup) {
|
|
|
409
416
|
async function handleTermUpdate(db, taxonomyName, termSlug, input, options = {}) {
|
|
410
417
|
try {
|
|
411
418
|
const repo = new TaxonomyRepository(db);
|
|
412
|
-
const
|
|
419
|
+
const locale = options.locale ? resolveConfiguredLocale(options.locale) : void 0;
|
|
420
|
+
const term = await repo.findBySlug(taxonomyName, termSlug, locale);
|
|
413
421
|
if (!term) return {
|
|
414
422
|
success: false,
|
|
415
423
|
error: {
|
|
@@ -420,7 +428,7 @@ async function handleTermUpdate(db, taxonomyName, termSlug, input, options = {})
|
|
|
420
428
|
const newSlug = input.slug === "" || input.slug === void 0 ? void 0 : input.slug;
|
|
421
429
|
const newParentId = input.parentId === "" || input.parentId === void 0 ? void 0 : input.parentId;
|
|
422
430
|
if (newSlug !== void 0 && newSlug !== termSlug) {
|
|
423
|
-
const existing = await repo.findBySlug(taxonomyName, newSlug,
|
|
431
|
+
const existing = await repo.findBySlug(taxonomyName, newSlug, locale);
|
|
424
432
|
if (existing && existing.id !== term.id) return {
|
|
425
433
|
success: false,
|
|
426
434
|
error: {
|
|
@@ -477,7 +485,8 @@ async function handleTermUpdate(db, taxonomyName, termSlug, input, options = {})
|
|
|
477
485
|
async function handleTermDelete(db, taxonomyName, termSlug, options = {}) {
|
|
478
486
|
try {
|
|
479
487
|
const repo = new TaxonomyRepository(db);
|
|
480
|
-
const
|
|
488
|
+
const locale = options.locale ? resolveConfiguredLocale(options.locale) : void 0;
|
|
489
|
+
const term = await repo.findBySlug(taxonomyName, termSlug, locale);
|
|
481
490
|
if (!term) return {
|
|
482
491
|
success: false,
|
|
483
492
|
error: {
|
|
@@ -517,4 +526,4 @@ async function handleTermDelete(db, taxonomyName, termSlug, options = {}) {
|
|
|
517
526
|
|
|
518
527
|
//#endregion
|
|
519
528
|
export { handleTermGet as a, handleTermUpdate as c, handleTermDelete as i, taxonomies_exports as l, handleTaxonomyList as n, handleTermList as o, handleTermCreate as r, handleTermTranslations as s, handleTaxonomyCreate as t };
|
|
520
|
-
//# sourceMappingURL=taxonomies-
|
|
529
|
+
//# sourceMappingURL=taxonomies-BN6M9Nrv.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"taxonomies-BN6M9Nrv.mjs","names":[],"sources":["../src/api/handlers/taxonomies.ts"],"sourcesContent":["/**\n * Taxonomy and term CRUD handlers.\n *\n * i18n: terms and defs are per-locale. `(name, slug, locale)` is unique for\n * terms; `(name, locale)` for defs. Translations of the same term/def share a\n * `translation_group`. The content_taxonomies pivot stores translation_groups\n * so assignments span every locale of a post.\n */\n\nimport type { Kysely, Selectable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { TaxonomyRepository } from \"../../database/repositories/taxonomy.js\";\nimport type { Database, TaxonomyDefTable } from \"../../database/types.js\";\nimport { resolveConfiguredLocale } from \"../../i18n/config.js\";\nimport { invalidateTaxonomyDefsCache, invalidateTermCache } from \"../../taxonomies/index.js\";\nimport { fetchVisibleTermCounts } from \"../../taxonomies/term-counts.js\";\nimport type { ApiResult } from \"../types.js\";\n\nconst NAME_PATTERN = /^[a-z][a-z0-9_]*$/;\n\n// ---------------------------------------------------------------------------\n// Response types\n// ---------------------------------------------------------------------------\n\nexport interface TaxonomyDef {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tlabelSingular?: string;\n\thierarchical: boolean;\n\tcollections: string[];\n\tlocale: string;\n\ttranslationGroup: string | null;\n}\n\nexport interface TaxonomyListResponse {\n\ttaxonomies: TaxonomyDef[];\n}\n\nexport interface TermData {\n\tid: string;\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparentId: string | null;\n\tdescription?: string;\n\tlocale: string;\n\ttranslationGroup: string | null;\n}\n\nexport interface TermWithCount extends TermData {\n\tcount: number;\n\tchildren: TermWithCount[];\n}\n\nexport interface TermListResponse {\n\tterms: TermWithCount[];\n}\n\nexport interface TermResponse {\n\tterm: TermData;\n}\n\nexport interface TermGetResponse {\n\tterm: TermData & {\n\t\tcount: number;\n\t\tchildren: Array<{ id: string; slug: string; label: string }>;\n\t};\n}\n\nexport interface TermTranslationsResponse {\n\ttranslationGroup: string | null;\n\ttranslations: Array<{\n\t\tid: string;\n\t\tslug: string;\n\t\tlabel: string;\n\t\tlocale: string;\n\t}>;\n}\n\nexport interface TaxonomyDefTranslationsResponse {\n\ttranslationGroup: string | null;\n\ttranslations: Array<{\n\t\tid: string;\n\t\tname: string;\n\t\tlabel: string;\n\t\tlocale: string;\n\t}>;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Build tree structure from flat terms\n */\nfunction buildTree(flatTerms: TermWithCount[]): TermWithCount[] {\n\t// `parentId` holds the parent's translation_group, so resolve links by group.\n\t// Key by (locale, group): a child's parent lives in the same locale, and an\n\t// unfiltered list mixes locales whose translated siblings share a group —\n\t// keying by group alone would collide and misattach children across locales.\n\tconst byLocaleGroup = new Map<string, TermWithCount>();\n\tconst roots: TermWithCount[] = [];\n\tfor (const term of flatTerms) {\n\t\tbyLocaleGroup.set(`${term.locale}::${term.translationGroup ?? term.id}`, term);\n\t}\n\tfor (const term of flatTerms) {\n\t\tconst parent = term.parentId\n\t\t\t? byLocaleGroup.get(`${term.locale}::${term.parentId}`)\n\t\t\t: undefined;\n\t\tif (parent) {\n\t\t\tparent.children.push(term);\n\t\t} else {\n\t\t\troots.push(term);\n\t\t}\n\t}\n\treturn roots;\n}\n\n/**\n * Look up a taxonomy definition by name (optionally scoped to a locale).\n * Returns the lowest-locale match when no locale is provided.\n */\nasync function requireTaxonomyDef(\n\tdb: Kysely<Database>,\n\tname: string,\n\tlocale?: string,\n): Promise<\n\t| { success: true; def: Selectable<TaxonomyDefTable> }\n\t| { success: false; error: { code: string; message: string } }\n> {\n\tlet query = db.selectFrom(\"_emdash_taxonomy_defs\").selectAll().where(\"name\", \"=\", name);\n\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\tconst def = await query.orderBy(\"locale\", \"asc\").executeTakeFirst();\n\tif (!def) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"NOT_FOUND\", message: `Taxonomy '${name}' not found` },\n\t\t};\n\t}\n\treturn { success: true, def };\n}\n\n/** Declared collections of a taxonomy def row (deduped, parsed from JSON). */\nfunction defCollections(def: Selectable<TaxonomyDefTable>): string[] {\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- column stores a JSON string[] written by handleTaxonomyCreate\n\tconst parsed = def.collections ? (JSON.parse(def.collections) as string[]) : [];\n\treturn [...new Set(parsed)];\n}\n\nfunction rowToDef(row: Selectable<TaxonomyDefTable>): TaxonomyDef {\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tlabel: row.label,\n\t\tlabelSingular: row.label_singular ?? undefined,\n\t\thierarchical: row.hierarchical === 1,\n\t\tcollections: row.collections ? JSON.parse(row.collections) : [],\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Taxonomy definition handlers\n// ---------------------------------------------------------------------------\n\n/**\n * List all taxonomy definitions\n */\nexport async function handleTaxonomyList(\n\tdb: Kysely<Database>,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<TaxonomyListResponse>> {\n\ttry {\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tlet query = db.selectFrom(\"_emdash_taxonomy_defs\").selectAll();\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst [rows, collectionRows] = await Promise.all([\n\t\t\tquery.execute(),\n\t\t\tdb.selectFrom(\"_emdash_collections\").select(\"slug\").execute(),\n\t\t]);\n\n\t\t// Filter orphan collection references on read so the response stays\n\t\t// consistent with `schema_list_collections`. Storage is untouched —\n\t\t// re-creating the collection re-links automatically.\n\t\tconst realCollections = new Set(collectionRows.map((r) => r.slug));\n\n\t\tconst taxonomies: TaxonomyDef[] = rows.map((row) => {\n\t\t\tconst def = rowToDef(row);\n\t\t\treturn { ...def, collections: def.collections.filter((slug) => realCollections.has(slug)) };\n\t\t});\n\n\t\treturn { success: true, data: { taxonomies } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TAXONOMY_LIST_ERROR\", message: \"Failed to list taxonomies\" },\n\t\t};\n\t}\n}\n\n/**\n * Create a new taxonomy definition\n */\nexport async function handleTaxonomyCreate(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\tname: string;\n\t\tlabel: string;\n\t\tlabelSingular?: string;\n\t\thierarchical?: boolean;\n\t\tcollections?: string[];\n\t\tlocale?: string;\n\t\ttranslationOf?: string;\n\t},\n): Promise<ApiResult<{ taxonomy: TaxonomyDef }>> {\n\ttry {\n\t\tconst locale = input.locale ? resolveConfiguredLocale(input.locale) : undefined;\n\t\tif (!NAME_PATTERN.test(input.name)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"Taxonomy name must start with a letter and contain only lowercase letters, numbers, and underscores\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst collections = [...new Set(input.collections ?? [])];\n\t\tif (collections.length > 0) {\n\t\t\tconst existingCollections = await db\n\t\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t\t.select(\"slug\")\n\t\t\t\t.where(\"slug\", \"in\", collections)\n\t\t\t\t.execute();\n\t\t\tconst existingSlugs = new Set(existingCollections.map((c) => c.slug));\n\t\t\tconst invalid = collections.filter((c) => !existingSlugs.has(c));\n\t\t\tif (invalid.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\tmessage: `Unknown collection(s): ${invalid.join(\", \")}`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tlet translationGroup: string | null = null;\n\t\tif (input.translationOf) {\n\t\t\tconst source = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"id\", \"=\", input.translationOf)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (!source) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Source taxonomy for translation not found\" },\n\t\t\t\t};\n\t\t\t}\n\t\t\ttranslationGroup = source.translation_group ?? source.id;\n\t\t}\n\n\t\t// Duplicate guard scoped to locale (so the same name can exist in ES\n\t\t// and EN).\n\t\tif (locale !== undefined) {\n\t\t\tconst existing = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.select(\"id\")\n\t\t\t\t.where(\"name\", \"=\", input.name)\n\t\t\t\t.where(\"locale\", \"=\", locale)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (existing) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\t\tmessage: `Taxonomy '${input.name}' already exists in locale '${locale}'`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tconst id = ulid();\n\t\tawait db\n\t\t\t.insertInto(\"_emdash_taxonomy_defs\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tname: input.name,\n\t\t\t\tlabel: input.label,\n\t\t\t\tlabel_singular: input.labelSingular ?? null,\n\t\t\t\thierarchical: input.hierarchical ? 1 : 0,\n\t\t\t\tcollections: JSON.stringify(collections),\n\t\t\t\t...(locale !== undefined ? { locale } : {}),\n\t\t\t\ttranslation_group: translationGroup ?? id,\n\t\t\t})\n\t\t\t.execute();\n\n\t\t// A new def changes which taxonomies exist — drop the isolate-wide\n\t\t// defs/names caches so this isolate reflects it immediately.\n\t\tinvalidateTaxonomyDefsCache();\n\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirstOrThrow();\n\t\treturn { success: true, data: { taxonomy: rowToDef(row) } };\n\t} catch (error) {\n\t\tif (error instanceof Error && error.message.includes(\"UNIQUE constraint failed\")) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"CONFLICT\", message: `Taxonomy '${input.name}' already exists` },\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TAXONOMY_CREATE_ERROR\", message: \"Failed to create taxonomy\" },\n\t\t};\n\t}\n}\n\n/**\n * List every locale translation of a taxonomy def (by id or translation_group).\n */\nexport async function handleTaxonomyDefTranslations(\n\tdb: Kysely<Database>,\n\tidOrGroup: string,\n): Promise<ApiResult<TaxonomyDefTranslationsResponse>> {\n\ttry {\n\t\tconst anchor = await db\n\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t.selectAll()\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\tif (!anchor) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Taxonomy not found\" },\n\t\t\t};\n\t\t}\n\t\tconst group = anchor.translation_group ?? anchor.id;\n\t\tconst rows = await db\n\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", group)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\ttranslationGroup: group,\n\t\t\t\ttranslations: rows.map((r) => ({\n\t\t\t\t\tid: r.id,\n\t\t\t\t\tname: r.name,\n\t\t\t\t\tlabel: r.label,\n\t\t\t\t\tlocale: r.locale,\n\t\t\t\t})),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"TAXONOMY_TRANSLATIONS_ERROR\",\n\t\t\t\tmessage: \"Failed to list taxonomy translations\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Term handlers\n// ---------------------------------------------------------------------------\n\n/**\n * List all terms for a taxonomy (returns tree for hierarchical taxonomies)\n */\nexport async function handleTermList(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<TermListResponse>> {\n\ttry {\n\t\t// Definitions are per-locale but terms aren't bound to the def's locale —\n\t\t// just ensure the taxonomy exists somewhere.\n\t\tconst lookup = await requireTaxonomyDef(db, taxonomyName);\n\t\tif (!lookup.success) return lookup;\n\n\t\tconst repo = new TaxonomyRepository(db);\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tconst terms = await repo.findByName(taxonomyName, { locale });\n\n\t\t// Counts match what visitors see on the public site: published (or\n\t\t// scheduled-and-due) entries that aren't soft-deleted, scoped to the\n\t\t// taxonomy's declared collections — one query for the whole list.\n\t\t// content_taxonomies.taxonomy_id stores the translation_group, so we\n\t\t// look up by group and map back to each term's id.\n\t\tconst countsByGroup = await fetchVisibleTermCounts(\n\t\t\tdb,\n\t\t\ttaxonomyName,\n\t\t\tdefCollections(lookup.def),\n\t\t);\n\n\t\tconst termData: TermWithCount[] = terms.map((term) => ({\n\t\t\tid: term.id,\n\t\t\tname: term.name,\n\t\t\tslug: term.slug,\n\t\t\tlabel: term.label,\n\t\t\tparentId: term.parentId,\n\t\t\tdescription: typeof term.data?.description === \"string\" ? term.data.description : undefined,\n\t\t\tchildren: [],\n\t\t\tcount: countsByGroup.get(term.translationGroup ?? term.id) ?? 0,\n\t\t\tlocale: term.locale,\n\t\t\ttranslationGroup: term.translationGroup,\n\t\t}));\n\n\t\tconst isHierarchical = lookup.def.hierarchical === 1;\n\t\tconst result = isHierarchical ? buildTree(termData) : termData;\n\t\treturn { success: true, data: { terms: result } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_LIST_ERROR\", message: \"Failed to list terms\" },\n\t\t};\n\t}\n}\n\n/**\n * Validate a parent term reference for create/update.\n *\n * Returns `null` on success or a structured error message that callers\n * wrap in their own ApiResult.\n *\n * - `parentId === undefined` -> no-op (no parent change requested).\n * - `parentId === null` -> caller intends to detach; no-op here.\n * - parent must exist (FK exists -> term row not soft-deleted).\n * - parent must live in the same taxonomy.\n * - reject a parent in the term's own translation_group (self-parent),\n * including the create path: a translation inherits its source's group, so\n * `selfGroup` carries that prospective group when `termId` is absent.\n * - on update, walk up the parent chain to detect cycles.\n */\nasync function validateParentTerm(\n\trepo: TaxonomyRepository,\n\ttaxonomyName: string,\n\ttermId: string | undefined,\n\tparentId: string | null | undefined,\n\tselfGroup?: string | null,\n): Promise<{ code: \"VALIDATION_ERROR\"; message: string } | null> {\n\tif (parentId === undefined || parentId === null) return null;\n\n\tconst parent = await repo.findById(parentId);\n\tif (!parent) {\n\t\treturn {\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tmessage: `Parent term '${parentId}' not found`,\n\t\t};\n\t}\n\tif (parent.name !== taxonomyName) {\n\t\treturn {\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tmessage: `Parent term '${parentId}' belongs to taxonomy '${parent.name}', not '${taxonomyName}'`,\n\t\t};\n\t}\n\n\t// Parentage keys off translation_group (what `parent_id` persists), so the\n\t// self-parent and cycle checks compare groups, not row ids — picking a\n\t// sibling translation of the term as its parent is still self-parenting.\n\tconst parentGroup = parent.translationGroup ?? parent.id;\n\tlet termGroup: string | null = selfGroup ?? null;\n\tif (termId !== undefined) {\n\t\tconst term = await repo.findById(termId);\n\t\ttermGroup = term ? (term.translationGroup ?? term.id) : termId;\n\t}\n\tif (termGroup !== null && parentGroup === termGroup) {\n\t\treturn {\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tmessage: \"A term cannot be its own parent\",\n\t\t};\n\t}\n\n\t// Walk up the parent chain. Two checks fold into one walk:\n\t// - Cycle detection (only on update — a non-existent term-being-\n\t// created can't be its own ancestor): if the walk revisits termId\n\t// the proposed parent makes the term a descendant of itself.\n\t// - Depth bound: refuse to extend a chain past MAX_DEPTH ancestors.\n\t// Runs on both create and update so a malicious or buggy caller\n\t// can't grow the tree without limit.\n\t//\n\t// The depth-exceeded error fires only when we hit the limit AND there\n\t// was still chain to walk — a legitimate chain of exactly MAX_DEPTH\n\t// ancestors exits with `cursor === null` and is accepted.\n\t// `parent_id` stores a translation_group, which always equals the anchor\n\t// row's id, so findById(cursor) still resolves each ancestor.\n\tconst MAX_DEPTH = 100;\n\tlet cursor: string | null = parent.parentId;\n\tlet steps = 0;\n\twhile (cursor !== null && steps < MAX_DEPTH) {\n\t\tif (termGroup !== null && cursor === termGroup) {\n\t\t\treturn {\n\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\tmessage: \"Cycle detected: cannot make a descendant the parent\",\n\t\t\t};\n\t\t}\n\t\tconst next = await repo.findById(cursor);\n\t\tif (!next) break;\n\t\tcursor = next.parentId;\n\t\tsteps++;\n\t}\n\tif (cursor !== null && steps >= MAX_DEPTH) {\n\t\treturn {\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tmessage: \"Parent chain exceeds maximum depth\",\n\t\t};\n\t}\n\n\treturn null;\n}\n\n/**\n * Create a new term in a taxonomy\n */\nexport async function handleTermCreate(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tinput: {\n\t\tslug: string;\n\t\tlabel: string;\n\t\tparentId?: string | null;\n\t\tdescription?: string;\n\t\tlocale?: string;\n\t\ttranslationOf?: string;\n\t},\n): Promise<ApiResult<TermResponse>> {\n\ttry {\n\t\tconst locale = input.locale ? resolveConfiguredLocale(input.locale) : undefined;\n\t\t// Taxonomy definitions are per-locale, but terms can exist in any locale\n\t\t// regardless of whether the def has been translated there. Look up the\n\t\t// def across all locales — we only care that it *exists*.\n\t\tconst lookup = await requireTaxonomyDef(db, taxonomyName);\n\t\tif (!lookup.success) return lookup;\n\n\t\tconst repo = new TaxonomyRepository(db);\n\n\t\t// Coerce empty-string parentId to undefined (treat as \"no parent\").\n\t\tconst parentId =\n\t\t\tinput.parentId === \"\" || input.parentId === undefined ? undefined : input.parentId;\n\n\t\t// Conflict check is scoped to locale (per-locale slugs are unique).\n\t\tconst existing = await repo.findBySlug(taxonomyName, input.slug, locale);\n\t\tif (existing) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\tmessage: locale\n\t\t\t\t\t\t? `Term '${input.slug}' already exists in '${taxonomyName}' (${locale})`\n\t\t\t\t\t\t: `Term with slug '${input.slug}' already exists in taxonomy '${taxonomyName}'`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// No locale re-pointing needed: `repo.create` persists the parent's\n\t\t// translation_group in `parent_id`, so a child stays nested under the\n\t\t// parent in every locale automatically — including parents translated\n\t\t// after the child was created.\n\n\t\t// A translation inherits its source's translation_group; pass that\n\t\t// prospective group so validateParentTerm can reject a parent in the same\n\t\t// group (cross-locale self-parent) even though the term doesn't exist yet.\n\t\tlet selfGroup: string | null = null;\n\t\tif (input.translationOf) {\n\t\t\tconst source = await repo.findById(input.translationOf);\n\t\t\tselfGroup = source ? (source.translationGroup ?? source.id) : null;\n\t\t}\n\n\t\t// Validate parentId: must exist AND belong to the same taxonomy.\n\t\t// (Cycle check is N/A on create — the term doesn't exist yet.)\n\t\tconst parentError = await validateParentTerm(\n\t\t\trepo,\n\t\t\ttaxonomyName,\n\t\t\tundefined,\n\t\t\tparentId,\n\t\t\tselfGroup,\n\t\t);\n\t\tif (parentError) {\n\t\t\treturn { success: false, error: parentError };\n\t\t}\n\n\t\tconst term = await repo.create({\n\t\t\tname: taxonomyName,\n\t\t\tslug: input.slug,\n\t\t\tlabel: input.label,\n\t\t\tparentId: parentId ?? undefined,\n\t\t\tdata: input.description ? { description: input.description } : undefined,\n\t\t\tlocale,\n\t\t\ttranslationOf: input.translationOf,\n\t\t});\n\n\t\tinvalidateTermCache();\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tterm: {\n\t\t\t\t\tid: term.id,\n\t\t\t\t\tname: term.name,\n\t\t\t\t\tslug: term.slug,\n\t\t\t\t\tlabel: term.label,\n\t\t\t\t\tparentId: term.parentId,\n\t\t\t\t\tdescription:\n\t\t\t\t\t\ttypeof term.data?.description === \"string\" ? term.data.description : undefined,\n\t\t\t\t\tlocale: term.locale,\n\t\t\t\t\ttranslationGroup: term.translationGroup,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_CREATE_ERROR\", message: \"Failed to create term\" },\n\t\t};\n\t}\n}\n\n/**\n * Get a single term by slug\n */\nexport async function handleTermGet(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<TermGetResponse>> {\n\ttry {\n\t\tconst repo = new TaxonomyRepository(db);\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tconst term = await repo.findBySlug(taxonomyName, termSlug, locale);\n\n\t\tif (!term) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\tmessage: `Term '${termSlug}' not found in taxonomy '${taxonomyName}'`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Count matches public visibility (published or scheduled-and-due, not\n\t\t// soft-deleted) scoped to the def's declared collections. The def lookup\n\t\t// is lenient: a term whose def is missing still resolves, with count 0.\n\t\tconst lookup = await requireTaxonomyDef(db, taxonomyName);\n\t\tconst counts = await fetchVisibleTermCounts(\n\t\t\tdb,\n\t\t\ttaxonomyName,\n\t\t\tlookup.success ? defCollections(lookup.def) : [],\n\t\t);\n\t\tconst count = counts.get(term.translationGroup ?? term.id) ?? 0;\n\t\t// Children share this term's translation_group as their parent_id; scope\n\t\t// to the term's own locale so the response stays within one locale's tree.\n\t\tconst children = await repo.findChildren(term.id, term.locale);\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tterm: {\n\t\t\t\t\tid: term.id,\n\t\t\t\t\tname: term.name,\n\t\t\t\t\tslug: term.slug,\n\t\t\t\t\tlabel: term.label,\n\t\t\t\t\tparentId: term.parentId,\n\t\t\t\t\tdescription:\n\t\t\t\t\t\ttypeof term.data?.description === \"string\" ? term.data.description : undefined,\n\t\t\t\t\tcount,\n\t\t\t\t\tchildren: children.map((c) => ({ id: c.id, slug: c.slug, label: c.label })),\n\t\t\t\t\tlocale: term.locale,\n\t\t\t\t\ttranslationGroup: term.translationGroup,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_GET_ERROR\", message: \"Failed to get term\" },\n\t\t};\n\t}\n}\n\n/** List every translation of a term (by id or translation_group). */\nexport async function handleTermTranslations(\n\tdb: Kysely<Database>,\n\tidOrGroup: string,\n): Promise<ApiResult<TermTranslationsResponse>> {\n\ttry {\n\t\tconst anchor = await db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\tif (!anchor) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Term not found\" },\n\t\t\t};\n\t\t}\n\t\tconst group = anchor.translation_group ?? anchor.id;\n\t\tconst rows = await db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", group)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\ttranslationGroup: group,\n\t\t\t\ttranslations: rows.map((r) => ({\n\t\t\t\t\tid: r.id,\n\t\t\t\t\tslug: r.slug,\n\t\t\t\t\tlabel: r.label,\n\t\t\t\t\tlocale: r.locale,\n\t\t\t\t})),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_TRANSLATIONS_ERROR\", message: \"Failed to list term translations\" },\n\t\t};\n\t}\n}\n\n/**\n * Update a term\n */\nexport async function handleTermUpdate(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\tinput: { slug?: string; label?: string; parentId?: string | null; description?: string },\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<TermResponse>> {\n\ttry {\n\t\tconst repo = new TaxonomyRepository(db);\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tconst term = await repo.findBySlug(taxonomyName, termSlug, locale);\n\n\t\tif (!term) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\tmessage: `Term '${termSlug}' not found in taxonomy '${taxonomyName}'`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Coerce empty-string slug/parentId to undefined (treat as \"no change\").\n\t\t// `null` parentId is a valid request meaning \"detach from parent\".\n\t\tconst newSlug = input.slug === \"\" || input.slug === undefined ? undefined : input.slug;\n\t\tconst newParentId =\n\t\t\tinput.parentId === \"\" || input.parentId === undefined ? undefined : input.parentId;\n\n\t\t// Check if new slug conflicts (per-locale uniqueness).\n\t\tif (newSlug !== undefined && newSlug !== termSlug) {\n\t\t\tconst existing = await repo.findBySlug(taxonomyName, newSlug, locale);\n\t\t\tif (existing && existing.id !== term.id) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\t\tmessage: `Term with slug '${newSlug}' already exists in taxonomy '${taxonomyName}'`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Validate parentId: existence, same-taxonomy, no self-parent, no cycle.\n\t\tconst parentError = await validateParentTerm(repo, taxonomyName, term.id, newParentId);\n\t\tif (parentError) {\n\t\t\treturn { success: false, error: parentError };\n\t\t}\n\n\t\tconst updated = await repo.update(term.id, {\n\t\t\tslug: newSlug,\n\t\t\tlabel: input.label,\n\t\t\tparentId: newParentId,\n\t\t\tdata: input.description !== undefined ? { description: input.description } : undefined,\n\t\t});\n\n\t\tinvalidateTermCache();\n\n\t\tif (!updated) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"TERM_UPDATE_ERROR\", message: \"Failed to update term\" },\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tterm: {\n\t\t\t\t\tid: updated.id,\n\t\t\t\t\tname: updated.name,\n\t\t\t\t\tslug: updated.slug,\n\t\t\t\t\tlabel: updated.label,\n\t\t\t\t\tparentId: updated.parentId,\n\t\t\t\t\tdescription:\n\t\t\t\t\t\ttypeof updated.data?.description === \"string\" ? updated.data.description : undefined,\n\t\t\t\t\tlocale: updated.locale,\n\t\t\t\t\ttranslationGroup: updated.translationGroup,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_UPDATE_ERROR\", message: \"Failed to update term\" },\n\t\t};\n\t}\n}\n\n/**\n * Delete a term\n */\nexport async function handleTermDelete(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<{ deleted: true }>> {\n\ttry {\n\t\tconst repo = new TaxonomyRepository(db);\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tconst term = await repo.findBySlug(taxonomyName, termSlug, locale);\n\n\t\tif (!term) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\tmessage: `Term '${termSlug}' not found in taxonomy '${taxonomyName}'`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Block deletion if the term's group still parents any child in any\n\t\t// locale — children store this group in parent_id, so removing the term\n\t\t// would orphan them (or null their parent_id via the self-FK).\n\t\tconst children = await repo.findChildren(term.id);\n\t\tif (children.length > 0) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\tmessage: \"Cannot delete term with children. Delete children first.\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst deleted = await repo.delete(term.id);\n\t\tif (!deleted) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"TERM_DELETE_ERROR\", message: \"Failed to delete term\" },\n\t\t\t};\n\t\t}\n\n\t\tinvalidateTermCache();\n\t\treturn { success: true, data: { deleted: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_DELETE_ERROR\", message: \"Failed to delete term\" },\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmBA,MAAM,eAAe;;;;AA+ErB,SAAS,UAAU,WAA6C;CAK/D,MAAM,gCAAgB,IAAI,KAA4B;CACtD,MAAM,QAAyB,EAAE;AACjC,MAAK,MAAM,QAAQ,UAClB,eAAc,IAAI,GAAG,KAAK,OAAO,IAAI,KAAK,oBAAoB,KAAK,MAAM,KAAK;AAE/E,MAAK,MAAM,QAAQ,WAAW;EAC7B,MAAM,SAAS,KAAK,WACjB,cAAc,IAAI,GAAG,KAAK,OAAO,IAAI,KAAK,WAAW,GACrD;AACH,MAAI,OACH,QAAO,SAAS,KAAK,KAAK;MAE1B,OAAM,KAAK,KAAK;;AAGlB,QAAO;;;;;;AAOR,eAAe,mBACd,IACA,MACA,QAIC;CACD,IAAI,QAAQ,GAAG,WAAW,wBAAwB,CAAC,WAAW,CAAC,MAAM,QAAQ,KAAK,KAAK;AACvF,KAAI,WAAW,OAAW,SAAQ,MAAM,MAAM,UAAU,KAAK,OAAO;CACpE,MAAM,MAAM,MAAM,MAAM,QAAQ,UAAU,MAAM,CAAC,kBAAkB;AACnE,KAAI,CAAC,IACJ,QAAO;EACN,SAAS;EACT,OAAO;GAAE,M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AAM;IAAqB,SAAS;IAAyB;GACtE;AAGF,uBAAqB;AACrB,SAAO;GAAE,SAAS;GAAM,MAAM,EAAE,SAAS,MAAM;GAAE;SAC1C;AACP,SAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAqB,SAAS;IAAyB;GACtE"}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { o as __exportAll } from "./runner-
|
|
1
|
+
import { o as __exportAll } from "./runner-BdeLEgad.mjs";
|
|
2
2
|
import { t as validateIdentifier } from "./validate-VPnKoIzW.mjs";
|
|
3
|
-
import { n as buildStatusCondition } from "./dialect-helpers-
|
|
3
|
+
import { n as buildStatusCondition } from "./dialect-helpers-BtOwo2us.mjs";
|
|
4
4
|
import { getRequestContext } from "./request-context.mjs";
|
|
5
5
|
import { d as invalidateTaxonomyObjectCache, f as isObjectCacheActive, n as cachedQuery, r as contentNamespace, t as CacheNamespace } from "./object-cache-Bok5j2ae.mjs";
|
|
6
|
-
import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-
|
|
6
|
+
import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-Bq-5DPrD.mjs";
|
|
7
7
|
import { n as isMissingTableError } from "./db-errors-CcWLaRiR.mjs";
|
|
8
8
|
import { i as setRequestCacheEntry, n as peekRequestCache, r as requestCached } from "./request-cache-BSUptuJR.mjs";
|
|
9
|
-
import { i as resolveLocaleChain, r as resolveLocale } from "./resolve-
|
|
10
|
-
import { a as getDb, s as resetTaxonomyNamesCache } from "./loader-
|
|
9
|
+
import { i as resolveLocaleChain, r as resolveLocale } from "./resolve-DFr4kq72.mjs";
|
|
10
|
+
import { a as getDb, s as resetTaxonomyNamesCache } from "./loader-D4rigvjR.mjs";
|
|
11
11
|
import { sql } from "kysely";
|
|
12
12
|
|
|
13
13
|
//#region src/taxonomies/term-counts.ts
|
|
@@ -228,24 +228,47 @@ function termCountNamespaces(collections) {
|
|
|
228
228
|
/**
|
|
229
229
|
* All terms of a taxonomy in a specific locale (flat for non-hierarchical,
|
|
230
230
|
* tree for hierarchical).
|
|
231
|
+
*
|
|
232
|
+
* The term list and the visible-entry counts are loaded and cached separately:
|
|
233
|
+
* the list depends only on the taxonomy epoch, while the counts additionally
|
|
234
|
+
* depend on every counted collection's content epoch and cost an aggregate over
|
|
235
|
+
* the whole assignment pivot. Callers that don't render counts pass
|
|
236
|
+
* `includeCounts: false` and skip that aggregate entirely, while still sharing
|
|
237
|
+
* the term list with callers that do.
|
|
231
238
|
*/
|
|
232
239
|
async function getTaxonomyTerms(taxonomyName, options = {}) {
|
|
233
240
|
const locale = resolveLocale(options.locale);
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
241
|
+
const def = await getTaxonomyDef(taxonomyName, options);
|
|
242
|
+
if (!def) return [];
|
|
243
|
+
if (options.includeCounts === false) return getTermList(def, locale);
|
|
244
|
+
const [terms, counts] = await Promise.all([getTermList(def, locale), getVisibleTermCounts(def.name, def.collections)]);
|
|
245
|
+
return withCounts(terms, counts);
|
|
246
|
+
}
|
|
247
|
+
/** Terms without counts, under the cache keys the layout prefetch warms. */
|
|
248
|
+
function getTermList(def, locale) {
|
|
249
|
+
const localeKey = locale ?? "*";
|
|
250
|
+
return requestCached(`taxonomy-terms:${def.name}:${localeKey}`, () => cachedQuery({
|
|
251
|
+
namespace: CacheNamespace.TAXONOMIES,
|
|
252
|
+
key: `termList:${def.name}:${localeKey}`,
|
|
253
|
+
load: () => loadTaxonomyTerms(def, locale)
|
|
254
|
+
}));
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Copy a term list with counts attached. Counts are keyed by translation_group
|
|
258
|
+
* (what the pivot stores) and are locale-independent. Rebuilds every node so
|
|
259
|
+
* the shared, cached count-free list is never mutated.
|
|
260
|
+
*/
|
|
261
|
+
function withCounts(terms, counts) {
|
|
262
|
+
return terms.map((term) => ({
|
|
263
|
+
...term,
|
|
264
|
+
count: counts.get(term.translationGroup ?? term.id) ?? 0,
|
|
265
|
+
children: withCounts(term.children, counts)
|
|
266
|
+
}));
|
|
243
267
|
}
|
|
244
268
|
async function loadTaxonomyTerms(def, locale) {
|
|
245
269
|
let termsQuery = (await getDb()).selectFrom("taxonomies").selectAll().where("name", "=", def.name).orderBy("label", "asc");
|
|
246
270
|
if (locale !== void 0) termsQuery = termsQuery.where("locale", "=", locale);
|
|
247
|
-
const
|
|
248
|
-
const flatTerms = rows.map((row) => ({
|
|
271
|
+
const flatTerms = (await termsQuery.execute()).map((row) => ({
|
|
249
272
|
id: row.id,
|
|
250
273
|
name: row.name,
|
|
251
274
|
slug: row.slug,
|
|
@@ -255,7 +278,7 @@ async function loadTaxonomyTerms(def, locale) {
|
|
|
255
278
|
locale: row.locale,
|
|
256
279
|
translation_group: row.translation_group
|
|
257
280
|
}));
|
|
258
|
-
if (def.hierarchical) return buildTree(flatTerms
|
|
281
|
+
if (def.hierarchical) return buildTree(flatTerms);
|
|
259
282
|
return flatTerms.map((term) => ({
|
|
260
283
|
id: term.id,
|
|
261
284
|
name: term.name,
|
|
@@ -263,7 +286,6 @@ async function loadTaxonomyTerms(def, locale) {
|
|
|
263
286
|
label: term.label,
|
|
264
287
|
description: term.data ? JSON.parse(term.data).description : void 0,
|
|
265
288
|
children: [],
|
|
266
|
-
count: counts.get(term.translation_group ?? term.id) ?? 0,
|
|
267
289
|
locale: term.locale,
|
|
268
290
|
translationGroup: term.translation_group
|
|
269
291
|
}));
|
|
@@ -276,8 +298,16 @@ async function loadTaxonomyTerms(def, locale) {
|
|
|
276
298
|
* single-term page (`getTerm`) never issue separate count queries.
|
|
277
299
|
*/
|
|
278
300
|
function getVisibleTermCounts(taxonomyName, collections) {
|
|
279
|
-
|
|
280
|
-
|
|
301
|
+
const scope = [...new Set(collections)].toSorted().join(",");
|
|
302
|
+
return requestCached(`taxonomy-term-counts:${taxonomyName}:${scope}`, async () => {
|
|
303
|
+
const entries = await cachedQuery({
|
|
304
|
+
namespace: termCountNamespaces(collections),
|
|
305
|
+
key: `termCounts:${taxonomyName}:${scope}`,
|
|
306
|
+
load: async () => {
|
|
307
|
+
return [...await fetchVisibleTermCounts(await getDb(), taxonomyName, collections)];
|
|
308
|
+
}
|
|
309
|
+
});
|
|
310
|
+
return new Map(entries);
|
|
281
311
|
});
|
|
282
312
|
}
|
|
283
313
|
/**
|
|
@@ -553,7 +583,7 @@ function primeFoldedEntryTerms(collection, perEntry, options = {}) {
|
|
|
553
583
|
* the content query respect the active locale.
|
|
554
584
|
*/
|
|
555
585
|
async function getEntriesByTerm(collection, taxonomyName, termSlug, options = {}) {
|
|
556
|
-
const { getEmDashCollection } = await import("./query-
|
|
586
|
+
const { getEmDashCollection } = await import("./query-Bz9bWZfm.mjs").then((n) => n.o);
|
|
557
587
|
const queryOptions = { where: { [taxonomyName]: termSlug } };
|
|
558
588
|
if (options.locale !== void 0) queryOptions.locale = options.locale;
|
|
559
589
|
const { entries } = await getEmDashCollection(collection, queryOptions);
|
|
@@ -574,7 +604,7 @@ function rowToTaxonomyDef(row) {
|
|
|
574
604
|
/**
|
|
575
605
|
* Build tree structure from flat terms
|
|
576
606
|
*/
|
|
577
|
-
function buildTree(flatTerms
|
|
607
|
+
function buildTree(flatTerms) {
|
|
578
608
|
const byLocaleGroup = /* @__PURE__ */ new Map();
|
|
579
609
|
const nodes = [];
|
|
580
610
|
const roots = [];
|
|
@@ -587,7 +617,6 @@ function buildTree(flatTerms, counts) {
|
|
|
587
617
|
parentId: term.parent_id ?? void 0,
|
|
588
618
|
description: term.data ? JSON.parse(term.data).description : void 0,
|
|
589
619
|
children: [],
|
|
590
|
-
count: counts.get(term.translation_group ?? term.id) ?? 0,
|
|
591
620
|
locale: term.locale,
|
|
592
621
|
translationGroup: term.translation_group
|
|
593
622
|
};
|
|
@@ -604,4 +633,4 @@ function buildTree(flatTerms, counts) {
|
|
|
604
633
|
|
|
605
634
|
//#endregion
|
|
606
635
|
export { getTaxonomyDefs as a, getTermsForEntries as c, taxonomies_exports as d, fetchVisibleTermCounts as f, getTaxonomyDef as i, invalidateTaxonomyDefsCache as l, getEntriesByTerm as n, getTaxonomyTerms as o, getEntryTerms as r, getTerm as s, getAllTermsForEntries as t, invalidateTermCache as u };
|
|
607
|
-
//# sourceMappingURL=taxonomies-
|
|
636
|
+
//# sourceMappingURL=taxonomies-r7pqLBCn.mjs.map
|