emdash 0.27.0 → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapters-u037EnTR.d.mts → adapters-hUy8vOB-.d.mts} +1 -1
- package/dist/{adapters-u037EnTR.d.mts.map → adapters-hUy8vOB-.d.mts.map} +1 -1
- package/dist/{allowed-origins-D5FxMUo8.mjs → allowed-origins-CRsJ6BPM.mjs} +2 -2
- package/dist/{allowed-origins-D5FxMUo8.mjs.map → allowed-origins-CRsJ6BPM.mjs.map} +1 -1
- package/dist/api/route-utils.d.mts +3 -3
- package/dist/api/route-utils.mjs +17 -16
- package/dist/api/route-utils.mjs.map +1 -1
- package/dist/api/schemas/index.d.mts +1 -1
- package/dist/api/schemas/index.mjs +3 -3
- package/dist/{api-80kycR9o.mjs → api-BFURZn1i.mjs} +33 -23
- package/dist/api-BFURZn1i.mjs.map +1 -0
- package/dist/{api-tokens-D6ppjIVi.mjs → api-tokens-DvqeZmVq.mjs} +2 -2
- package/dist/{api-tokens-D6ppjIVi.mjs.map → api-tokens-DvqeZmVq.mjs.map} +1 -1
- package/dist/{apply-DSypk6Iu.mjs → apply-Bu-8nYHL.mjs} +111 -74
- package/dist/apply-Bu-8nYHL.mjs.map +1 -0
- package/dist/astro/index.d.mts +12 -12
- package/dist/astro/index.mjs +3 -3
- package/dist/astro/index.mjs.map +1 -1
- package/dist/astro/middleware/auth.d.mts +10 -10
- package/dist/astro/middleware/auth.d.mts.map +1 -1
- package/dist/astro/middleware/auth.mjs +50 -11
- package/dist/astro/middleware/auth.mjs.map +1 -1
- package/dist/astro/middleware/redirect.mjs +5 -5
- package/dist/astro/middleware/request-context.mjs +2 -2
- package/dist/astro/middleware/setup.mjs +1 -1
- package/dist/astro/middleware.d.mts +2 -2
- package/dist/astro/middleware.mjs +124 -71
- 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 +4 -4
- package/dist/astro/routes/api/admin/api-tokens/index.mjs +5 -5
- package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +4 -4
- package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +8 -8
- package/dist/astro/routes/api/admin/byline-fields/index.mjs +8 -8
- package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +8 -8
- 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.mjs +14 -14
- package/dist/astro/routes/api/admin/comments/_id_/status.mjs +12 -12
- package/dist/astro/routes/api/admin/comments/_id_.mjs +6 -6
- package/dist/astro/routes/api/admin/comments/bulk.mjs +10 -10
- package/dist/astro/routes/api/admin/comments/counts.mjs +6 -6
- package/dist/astro/routes/api/admin/comments/index.mjs +10 -10
- 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/oauth-clients/_id_.mjs +4 -4
- package/dist/astro/routes/api/admin/oauth-clients/index.mjs +4 -4
- package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +37 -36
- package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +37 -36
- package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +36 -35
- package/dist/astro/routes/api/admin/plugins/_id_/index.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +36 -35
- package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +36 -35
- package/dist/astro/routes/api/admin/plugins/_id_/update.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/index.mjs +36 -35
- package/dist/astro/routes/api/admin/plugins/index.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +3 -3
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +36 -35
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +36 -35
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +36 -35
- package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +36 -35
- package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +37 -36
- package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +36 -35
- package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/registry/install.mjs +37 -36
- package/dist/astro/routes/api/admin/plugins/registry/install.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/updates.mjs +36 -35
- package/dist/astro/routes/api/admin/plugins/updates.mjs.map +1 -1
- package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +36 -35
- package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs.map +1 -1
- package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +3 -3
- package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +36 -35
- package/dist/astro/routes/api/admin/themes/marketplace/index.mjs.map +1 -1
- 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 +3 -3
- package/dist/astro/routes/api/admin/users/index.mjs +6 -6
- package/dist/astro/routes/api/auth/dev-bypass.mjs +5 -5
- package/dist/astro/routes/api/auth/invite/accept.mjs +2 -2
- package/dist/astro/routes/api/auth/invite/complete.mjs +10 -10
- package/dist/astro/routes/api/auth/invite/index.mjs +7 -7
- package/dist/astro/routes/api/auth/invite/register-options.mjs +9 -9
- package/dist/astro/routes/api/auth/logout.mjs +3 -3
- package/dist/astro/routes/api/auth/magic-link/send.mjs +9 -9
- package/dist/astro/routes/api/auth/magic-link/verify.mjs +3 -3
- package/dist/astro/routes/api/auth/me.mjs +7 -7
- package/dist/astro/routes/api/auth/mode.mjs +1 -1
- package/dist/astro/routes/api/auth/oauth/_provider_/callback.mjs +3 -3
- package/dist/astro/routes/api/auth/oauth/_provider_.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 +11 -11
- package/dist/astro/routes/api/auth/passkey/register/options.mjs +9 -9
- package/dist/astro/routes/api/auth/passkey/register/verify.mjs +10 -10
- package/dist/astro/routes/api/auth/passkey/verify.mjs +10 -10
- package/dist/astro/routes/api/auth/signup/complete.mjs +10 -10
- package/dist/astro/routes/api/auth/signup/request.mjs +9 -9
- package/dist/astro/routes/api/auth/signup/verify.mjs +2 -2
- package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +13 -13
- package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +12 -12
- 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 +10 -10
- package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +7 -7
- 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 +8 -8
- package/dist/astro/routes/api/dev/emails.mjs +3 -3
- package/dist/astro/routes/api/import/probe.d.mts +3 -3
- package/dist/astro/routes/api/import/probe.mjs +19 -11
- package/dist/astro/routes/api/import/probe.mjs.map +1 -1
- package/dist/astro/routes/api/import/wordpress/analyze.mjs +3 -3
- package/dist/astro/routes/api/import/wordpress/execute.d.mts +11 -41
- package/dist/astro/routes/api/import/wordpress/execute.d.mts.map +1 -1
- package/dist/astro/routes/api/import/wordpress/execute.mjs +12 -407
- package/dist/astro/routes/api/import/wordpress/execute.mjs.map +1 -1
- package/dist/astro/routes/api/import/wordpress/media.d.mts +10 -10
- package/dist/astro/routes/api/import/wordpress/media.mjs +9 -9
- package/dist/astro/routes/api/import/wordpress/prepare.mjs +9 -9
- package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts +19 -1
- package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts.map +1 -1
- package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +97 -79
- package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs.map +1 -1
- package/dist/astro/routes/api/import/wordpress-plugin/analyze.d.mts +1 -1
- package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +19 -11
- package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs.map +1 -1
- package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +40 -2
- package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts.map +1 -1
- package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +519 -39
- package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs.map +1 -1
- package/dist/astro/routes/api/manifest.mjs +4 -4
- 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_.mjs +7 -7
- 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 +8 -8
- package/dist/astro/routes/api/media.mjs +9 -9
- package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +9 -9
- package/dist/astro/routes/api/menus/_name_/items.mjs +9 -9
- package/dist/astro/routes/api/menus/_name_/reorder.mjs +9 -9
- package/dist/astro/routes/api/menus/_name_/translations.mjs +9 -9
- package/dist/astro/routes/api/menus/_name_.mjs +9 -9
- package/dist/astro/routes/api/menus/index.mjs +9 -9
- package/dist/astro/routes/api/oauth/authorize.mjs +6 -6
- package/dist/astro/routes/api/oauth/device/authorize.mjs +6 -6
- package/dist/astro/routes/api/oauth/device/code.mjs +9 -9
- package/dist/astro/routes/api/oauth/device/token.mjs +8 -8
- package/dist/astro/routes/api/oauth/register.mjs +3 -3
- package/dist/astro/routes/api/oauth/token/refresh.mjs +6 -6
- package/dist/astro/routes/api/oauth/token/revoke.mjs +6 -6
- package/dist/astro/routes/api/oauth/token.mjs +6 -6
- 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 +9 -9
- package/dist/astro/routes/api/redirects/404s/summary.mjs +9 -9
- package/dist/astro/routes/api/redirects/_id_.mjs +10 -10
- package/dist/astro/routes/api/redirects/index.mjs +10 -10
- 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 +36 -35
- package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs.map +1 -1
- package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +36 -35
- package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs.map +1 -1
- package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +36 -35
- package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs.map +1 -1
- package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +36 -35
- package/dist/astro/routes/api/schema/collections/_slug_/index.mjs.map +1 -1
- package/dist/astro/routes/api/schema/collections/index.mjs +36 -35
- package/dist/astro/routes/api/schema/collections/index.mjs.map +1 -1
- package/dist/astro/routes/api/schema/index.mjs +7 -6
- package/dist/astro/routes/api/schema/index.mjs.map +1 -1
- package/dist/astro/routes/api/schema/orphans/_slug_.mjs +36 -35
- package/dist/astro/routes/api/schema/orphans/_slug_.mjs.map +1 -1
- package/dist/astro/routes/api/schema/orphans/index.mjs +36 -35
- package/dist/astro/routes/api/schema/orphans/index.mjs.map +1 -1
- package/dist/astro/routes/api/search/enable.mjs +10 -10
- package/dist/astro/routes/api/search/index.mjs +9 -9
- package/dist/astro/routes/api/search/rebuild.mjs +10 -10
- package/dist/astro/routes/api/search/stats.mjs +6 -6
- package/dist/astro/routes/api/search/suggest.mjs +9 -9
- package/dist/astro/routes/api/sections/_slug_.mjs +9 -9
- package/dist/astro/routes/api/sections/index.mjs +9 -9
- 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 +11 -11
- package/dist/astro/routes/api/setup/admin.mjs +10 -10
- package/dist/astro/routes/api/setup/dev-bypass.mjs +25 -24
- package/dist/astro/routes/api/setup/dev-bypass.mjs.map +1 -1
- package/dist/astro/routes/api/setup/dev-reset.mjs +2 -2
- package/dist/astro/routes/api/setup/index.mjs +26 -25
- package/dist/astro/routes/api/setup/index.mjs.map +1 -1
- package/dist/astro/routes/api/setup/status.mjs +4 -4
- package/dist/astro/routes/api/snapshot.mjs +6 -6
- 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 +5 -5
- package/dist/astro/routes/api/typegen.mjs +5 -5
- package/dist/astro/routes/api/well-known/auth.mjs +1 -1
- package/dist/astro/routes/api/well-known/oauth-authorization-server.mjs +2 -2
- package/dist/astro/routes/api/well-known/oauth-protected-resource.mjs +2 -2
- package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +7 -7
- package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +9 -9
- package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +9 -9
- package/dist/astro/routes/api/widget-areas/_name_.mjs +5 -5
- package/dist/astro/routes/api/widget-areas/index.mjs +9 -9
- package/dist/astro/routes/api/widget-components.mjs +3 -3
- package/dist/astro/routes/robots.txt.mjs +6 -6
- package/dist/astro/routes/sitemap-_collection_.xml.mjs +9 -9
- package/dist/astro/routes/sitemap.xml.mjs +7 -7
- package/dist/astro/types.d.mts +13 -13
- package/dist/auth/providers/github.d.mts +1 -1
- package/dist/auth/providers/google.d.mts +1 -1
- package/dist/{authorize-C3a_zGsM.mjs → authorize-Dz88F_Fw.mjs} +2 -2
- package/dist/{authorize-C3a_zGsM.mjs.map → authorize-Dz88F_Fw.mjs.map} +1 -1
- package/dist/{byline-DEKSVPTy.mjs → byline-Bm8ZgUP9.mjs} +6 -6
- package/dist/{byline-DEKSVPTy.mjs.map → byline-Bm8ZgUP9.mjs.map} +1 -1
- package/dist/{byline-fields-eyJMblSr.mjs → byline-fields-2Lp5Hbgf.mjs} +18 -3
- package/dist/byline-fields-2Lp5Hbgf.mjs.map +1 -0
- package/dist/{byline-fields-DaMKzkhO.mjs → byline-fields-CIx_GuN4.mjs} +1 -1
- package/dist/{byline-fields-DaMKzkhO.mjs.map → byline-fields-CIx_GuN4.mjs.map} +1 -1
- package/dist/{byline-fields-CtQ6blXd.d.mts → byline-fields-Cgrt9-aL.d.mts} +49 -34
- package/dist/{byline-fields-CtQ6blXd.d.mts.map → byline-fields-Cgrt9-aL.d.mts.map} +1 -1
- package/dist/{bylines-Ds4-otXl.mjs → bylines-6tm9mgQb.mjs} +4 -4
- package/dist/{bylines-Ds4-otXl.mjs.map → bylines-6tm9mgQb.mjs.map} +1 -1
- package/dist/{bylines-CiqgTHWF.mjs → bylines-Woq87129.mjs} +6 -6
- package/dist/{bylines-CiqgTHWF.mjs.map → bylines-Woq87129.mjs.map} +1 -1
- package/dist/{cache-Ciu3e3AF.mjs → cache-CEBAZjir.mjs} +2 -2
- package/dist/{cache-Ciu3e3AF.mjs.map → cache-CEBAZjir.mjs.map} +1 -1
- package/dist/{challenge-store-LhiqMccz.mjs → challenge-store-anhwVER0.mjs} +1 -1
- package/dist/{challenge-store-LhiqMccz.mjs.map → challenge-store-anhwVER0.mjs.map} +1 -1
- package/dist/{chunks-CZFiauig.mjs → chunks-B2isWQhr.mjs} +2 -2
- package/dist/{chunks-CZFiauig.mjs.map → chunks-B2isWQhr.mjs.map} +1 -1
- package/dist/cli/index.mjs +22 -21
- package/dist/cli/index.mjs.map +1 -1
- package/dist/client/cf-access.d.mts +1 -1
- package/dist/client/index.d.mts +1 -1
- package/dist/client/index.mjs +2 -2
- package/dist/{comment-CH1IrFFs.mjs → comment-CzeatwBV.mjs} +3 -3
- package/dist/{comment-CH1IrFFs.mjs.map → comment-CzeatwBV.mjs.map} +1 -1
- package/dist/{comment-reaction-kruNY-kP.mjs → comment-reaction-Cj9QJY7I.mjs} +2 -2
- package/dist/{comment-reaction-kruNY-kP.mjs.map → comment-reaction-Cj9QJY7I.mjs.map} +1 -1
- package/dist/{comments-BUJyXbgq.mjs → comments-BLE-jv5k.mjs} +3 -3
- package/dist/{comments-BUJyXbgq.mjs.map → comments-BLE-jv5k.mjs.map} +1 -1
- package/dist/{components-CYt4uVK9.mjs → components-B_sATNUc.mjs} +1 -1
- package/dist/{components-CYt4uVK9.mjs.map → components-B_sATNUc.mjs.map} +1 -1
- package/dist/{content-RmfHoWqK.mjs → content-DhgEth4k.mjs} +4 -4
- package/dist/{content-RmfHoWqK.mjs.map → content-DhgEth4k.mjs.map} +1 -1
- package/dist/content-refresh-CA4uKwzH.mjs +1531 -0
- package/dist/content-refresh-CA4uKwzH.mjs.map +1 -0
- package/dist/{context-CzUU_WzL.mjs → context-CUsR9dXL.mjs} +76 -54
- package/dist/context-CUsR9dXL.mjs.map +1 -0
- package/dist/{cron-C5LVoNmP.mjs → cron-v4FTEFR_.mjs} +1 -1
- package/dist/{cron-C5LVoNmP.mjs.map → cron-v4FTEFR_.mjs.map} +1 -1
- package/dist/{dashboard-CVyGhift.mjs → dashboard-EvEKF5en.mjs} +4 -4
- package/dist/{dashboard-CVyGhift.mjs.map → dashboard-EvEKF5en.mjs.map} +1 -1
- package/dist/db/index.d.mts +3 -3
- package/dist/db/index.mjs +1 -1
- package/dist/db/libsql.d.mts +1 -1
- package/dist/db/postgres.d.mts +1 -1
- package/dist/db/sqlite.d.mts +1 -1
- package/dist/{default-CeRG-Ot4.mjs → default-CM_D83Mg.mjs} +1 -1
- package/dist/{default-CeRG-Ot4.mjs.map → default-CM_D83Mg.mjs.map} +1 -1
- package/dist/{device-flow-DENDCQ9F.mjs → device-flow-CfGP18Uw.mjs} +4 -4
- package/dist/{device-flow-DENDCQ9F.mjs.map → device-flow-CfGP18Uw.mjs.map} +1 -1
- package/dist/{email-console-DJP32ucW.mjs → email-console-CIf4Lfvv.mjs} +1 -1
- package/dist/{email-console-DJP32ucW.mjs.map → email-console-CIf4Lfvv.mjs.map} +1 -1
- package/dist/{error-BHkLZk-w.mjs → error-CkAseSqZ.mjs} +2 -2
- package/dist/{error-BHkLZk-w.mjs.map → error-CkAseSqZ.mjs.map} +1 -1
- package/dist/{escape-Bjio4ZsM.mjs → escape-DqD0aCKu.mjs} +1 -1
- package/dist/{escape-Bjio4ZsM.mjs.map → escape-DqD0aCKu.mjs.map} +1 -1
- package/dist/{field-defs-cache-BA-8ZPiT.mjs → field-defs-cache-WUI88LX5.mjs} +2 -2
- package/dist/{field-defs-cache-BA-8ZPiT.mjs.map → field-defs-cache-WUI88LX5.mjs.map} +1 -1
- package/dist/{fts-manager-Db9jGavf.mjs → fts-manager-BbFaF_V8.mjs} +2 -2
- package/dist/{fts-manager-Db9jGavf.mjs.map → fts-manager-BbFaF_V8.mjs.map} +1 -1
- package/dist/{import-Bb1T9WJS.mjs → import-fYLf14Co.mjs} +514 -25
- package/dist/import-fYLf14Co.mjs.map +1 -0
- package/dist/{index-CDZZjrLT.d.mts → index-B9sIxwe4.d.mts} +21 -22
- package/dist/{index-CDZZjrLT.d.mts.map → index-B9sIxwe4.d.mts.map} +1 -1
- package/dist/{index-DGIjmUXQ.d.mts → index-Bm-Gy8Mh.d.mts} +25 -4
- package/dist/index-Bm-Gy8Mh.d.mts.map +1 -0
- package/dist/index.d.mts +18 -18
- package/dist/index.mjs +54 -53
- package/dist/{load-DpHICVPh.mjs → load-Djn3HWQS.mjs} +2 -2
- package/dist/{load-DpHICVPh.mjs.map → load-Djn3HWQS.mjs.map} +1 -1
- package/dist/{loader-4K37qA-y.mjs → loader-CB6YHeul.mjs} +6 -5
- package/dist/loader-CB6YHeul.mjs.map +1 -0
- package/dist/{manifest-schema-kPGX7VS-.mjs → manifest-schema-BHlgZM1W.mjs} +1 -1
- package/dist/{manifest-schema-kPGX7VS-.mjs.map → manifest-schema-BHlgZM1W.mjs.map} +1 -1
- package/dist/media/index.d.mts +1 -1
- package/dist/media/local-runtime.d.mts +12 -12
- package/dist/media/local-runtime.mjs +5 -5
- package/dist/{media-C0nRRfs1.mjs → media-BrXIaMFN.mjs} +2 -2
- package/dist/{media-C0nRRfs1.mjs.map → media-BrXIaMFN.mjs.map} +1 -1
- package/dist/{media-allowlist-Du8t1u6a.mjs → media-allowlist-CRHEeJ_i.mjs} +1 -1
- package/dist/{media-allowlist-Du8t1u6a.mjs.map → media-allowlist-CRHEeJ_i.mjs.map} +1 -1
- package/dist/{media-url-O4rm9-SQ.mjs → media-url-CKi5XSw4.mjs} +1 -1
- package/dist/{media-url-O4rm9-SQ.mjs.map → media-url-CKi5XSw4.mjs.map} +1 -1
- package/dist/{menus-SL2K0xq2.mjs → menus-Cfivc2Ad.mjs} +3 -3
- package/dist/{menus-SL2K0xq2.mjs.map → menus-Cfivc2Ad.mjs.map} +1 -1
- package/dist/{menus-DzRyC1ID.mjs → menus-CsZ2ZEK2.mjs} +16 -12
- package/dist/{menus-DzRyC1ID.mjs.map → menus-CsZ2ZEK2.mjs.map} +1 -1
- package/dist/{mode-BB0F8xTC.mjs → mode-BM9QgEmt.mjs} +1 -1
- package/dist/{mode-BB0F8xTC.mjs.map → mode-BM9QgEmt.mjs.map} +1 -1
- package/dist/{oauth-authorization-CsvzIp_F.mjs → oauth-authorization-CXWkIGT4.mjs} +4 -4
- package/dist/{oauth-authorization-CsvzIp_F.mjs.map → oauth-authorization-CXWkIGT4.mjs.map} +1 -1
- package/dist/{oauth-clients-C9SYwEbZ.mjs → oauth-clients-BmTI5rsl.mjs} +1 -1
- package/dist/{oauth-clients-C9SYwEbZ.mjs.map → oauth-clients-BmTI5rsl.mjs.map} +1 -1
- package/dist/{oauth-state-store---zrApfB.mjs → oauth-state-store-YLFLcH5F.mjs} +1 -1
- package/dist/{oauth-state-store---zrApfB.mjs.map → oauth-state-store-YLFLcH5F.mjs.map} +1 -1
- package/dist/{oauth-user-lookup-SHsWRlG9.mjs → oauth-user-lookup-Bsc_GsX-.mjs} +1 -1
- package/dist/{oauth-user-lookup-SHsWRlG9.mjs.map → oauth-user-lookup-Bsc_GsX-.mjs.map} +1 -1
- package/dist/object-cache/memory.d.mts +1 -1
- package/dist/{object-cache-CHbHv83-.mjs → object-cache-Bok5j2ae.mjs} +43 -3
- package/dist/object-cache-Bok5j2ae.mjs.map +1 -0
- package/dist/{options-41nCWqi9.d.mts → options-iMpRRxIe.d.mts} +3 -3
- package/dist/{options-41nCWqi9.d.mts.map → options-iMpRRxIe.d.mts.map} +1 -1
- package/dist/page/index.d.mts +2 -2
- package/dist/{parse-CqyZj3Hp.mjs → parse-GmjecGct.mjs} +2 -2
- package/dist/{parse-CqyZj3Hp.mjs.map → parse-GmjecGct.mjs.map} +1 -1
- package/dist/{passkey-config-C0YfSBko.mjs → passkey-config-De0ahnRg.mjs} +1 -1
- package/dist/{passkey-config-C0YfSBko.mjs.map → passkey-config-De0ahnRg.mjs.map} +1 -1
- package/dist/{placeholder-Cuce9U-m.d.mts → placeholder-BSKwzRe4.d.mts} +1 -1
- package/dist/{placeholder-Cuce9U-m.d.mts.map → placeholder-BSKwzRe4.d.mts.map} +1 -1
- package/dist/plugin-types.d.mts +1 -1
- package/dist/plugin-utils.d.mts +10 -10
- package/dist/plugins/adapt-sandbox-entry.d.mts +10 -10
- package/dist/plugins/adapt-sandbox-entry.mjs +2 -2
- package/dist/{portable-text-BICg8bTk.mjs → portable-text-cCa0cGV6.mjs} +1 -1
- package/dist/{portable-text-BICg8bTk.mjs.map → portable-text-cCa0cGV6.mjs.map} +1 -1
- package/dist/{preview-DKGCt2_p.mjs → preview-SSXNVPAC.mjs} +2 -2
- package/dist/{preview-DKGCt2_p.mjs.map → preview-SSXNVPAC.mjs.map} +1 -1
- package/dist/{public-url-CTVqgMmg.mjs → public-url-Danv47cS.mjs} +1 -1
- package/dist/{public-url-CTVqgMmg.mjs.map → public-url-Danv47cS.mjs.map} +1 -1
- package/dist/{query-B0M-9LYR.mjs → query-ByGq6ver.mjs} +14 -14
- package/dist/{query-B0M-9LYR.mjs.map → query-ByGq6ver.mjs.map} +1 -1
- package/dist/{rate-limit-BwoUdIpC.mjs → rate-limit-C_Lf63Dd.mjs} +2 -2
- package/dist/{rate-limit-BwoUdIpC.mjs.map → rate-limit-C_Lf63Dd.mjs.map} +1 -1
- package/dist/{redirect-CS-PHtNh.mjs → redirect-CoW3G-0U.mjs} +1 -1
- package/dist/{redirect-CS-PHtNh.mjs.map → redirect-CoW3G-0U.mjs.map} +1 -1
- package/dist/{redirect-lMOzG04S.mjs → redirect-IyfNirgS.mjs} +2 -2
- package/dist/{redirect-lMOzG04S.mjs.map → redirect-IyfNirgS.mjs.map} +1 -1
- package/dist/{redirects-9218MmYl.mjs → redirects-Bs1g42Ri.mjs} +4 -4
- package/dist/{redirects-9218MmYl.mjs.map → redirects-Bs1g42Ri.mjs.map} +1 -1
- package/dist/{redirects-Dcbuisoj.mjs → redirects-DXEXBAII.mjs} +2 -2
- package/dist/{redirects-Dcbuisoj.mjs.map → redirects-DXEXBAII.mjs.map} +1 -1
- package/dist/{registry-DP-iEtdR.mjs → registry-B65mUtPa.mjs} +122 -79
- package/dist/registry-B65mUtPa.mjs.map +1 -0
- package/dist/{request-meta-CmS1tDFf.mjs → request-meta-DbvXaAvU.mjs} +2 -2
- package/dist/{request-meta-CmS1tDFf.mjs.map → request-meta-DbvXaAvU.mjs.map} +1 -1
- package/dist/{resolve-C7I0qiR0.mjs → resolve-DR3wqMTy.mjs} +1 -1
- package/dist/{resolve-C7I0qiR0.mjs.map → resolve-DR3wqMTy.mjs.map} +1 -1
- package/dist/{runner-BbR3DfrL.d.mts → runner-DvFWoz8-.d.mts} +2 -2
- package/dist/{runner-BbR3DfrL.d.mts.map → runner-DvFWoz8-.d.mts.map} +1 -1
- package/dist/{runner-CFngB4WZ.mjs → runner-K8XK101B.mjs} +309 -190
- package/dist/runner-K8XK101B.mjs.map +1 -0
- package/dist/runtime.d.mts +11 -11
- package/dist/runtime.mjs +2 -2
- package/dist/{scheduled-publish-BMljtY5G.d.mts → scheduled-publish-Drffrf2a.d.mts} +1 -1
- package/dist/scheduled-publish-Drffrf2a.d.mts.map +1 -0
- package/dist/{schema-BfJ7bIXH.mjs → schema-Blhoxp3P.mjs} +5 -5
- package/dist/{schema-BfJ7bIXH.mjs.map → schema-Blhoxp3P.mjs.map} +1 -1
- package/dist/{search-C7t3PH1J.mjs → search-DZN2HZ-V.mjs} +4 -4
- package/dist/{search-C7t3PH1J.mjs.map → search-DZN2HZ-V.mjs.map} +1 -1
- package/dist/{secrets-BSf9pRRY.mjs → secrets-kp760LlD.mjs} +2 -2
- package/dist/{secrets-BSf9pRRY.mjs.map → secrets-kp760LlD.mjs.map} +1 -1
- package/dist/{sections-Dm0CVX23.mjs → sections-CpF5SaGr.mjs} +3 -3
- package/dist/{sections-Dm0CVX23.mjs.map → sections-CpF5SaGr.mjs.map} +1 -1
- package/dist/seed/index.d.mts +2 -2
- package/dist/seed/index.mjs +19 -18
- package/dist/seo/index.d.mts +1 -1
- package/dist/seo/index.mjs +1 -1
- package/dist/{seo-BkhuuaaE.mjs → seo-89-53DDs.mjs} +1 -1
- package/dist/{seo-BkhuuaaE.mjs.map → seo-89-53DDs.mjs.map} +1 -1
- package/dist/{seo-Dd3tbY_k.mjs → seo-DXu2UQnC.mjs} +3 -3
- package/dist/{seo-Dd3tbY_k.mjs.map → seo-DXu2UQnC.mjs.map} +1 -1
- package/dist/{service-CTrqp_Jy.mjs → service-DQmiBMzt.mjs} +3 -3
- package/dist/{service-CTrqp_Jy.mjs.map → service-DQmiBMzt.mjs.map} +1 -1
- package/dist/{session-user-B8aLtKAH.mjs → session-user-Cascbax7.mjs} +1 -1
- package/dist/{session-user-B8aLtKAH.mjs.map → session-user-Cascbax7.mjs.map} +1 -1
- package/dist/{settings-CZ7ZP9cW.mjs → settings-rZyHEcNT.mjs} +3 -3
- package/dist/{settings-CZ7ZP9cW.mjs.map → settings-rZyHEcNT.mjs.map} +1 -1
- package/dist/{settings-BX8cWBus.mjs → settings-zhmdKyJQ.mjs} +5 -5
- package/dist/{settings-BX8cWBus.mjs.map → settings-zhmdKyJQ.mjs.map} +1 -1
- package/dist/{setup-complete-gEiySUc-.mjs → setup-complete-Cb3LRyzy.mjs} +1 -1
- package/dist/{setup-complete-gEiySUc-.mjs.map → setup-complete-Cb3LRyzy.mjs.map} +1 -1
- package/dist/{setup-nonce-DzS50zme.mjs → setup-nonce-Z8x0tHf8.mjs} +1 -1
- package/dist/{setup-nonce-DzS50zme.mjs.map → setup-nonce-Z8x0tHf8.mjs.map} +1 -1
- package/dist/{single-flight-cache-Cdfkic3t.mjs → single-flight-cache-BG3B_GhN.mjs} +1 -1
- package/dist/{single-flight-cache-Cdfkic3t.mjs.map → single-flight-cache-BG3B_GhN.mjs.map} +1 -1
- package/dist/{site-url-BLebyON8.mjs → site-url-BBfDTgZB.mjs} +1 -1
- package/dist/{site-url-BLebyON8.mjs.map → site-url-BBfDTgZB.mjs.map} +1 -1
- package/dist/{ssrf-BRKb343l.mjs → ssrf-1g7usGBg.mjs} +1 -1
- package/dist/{ssrf-BRKb343l.mjs.map → ssrf-1g7usGBg.mjs.map} +1 -1
- package/dist/{status-vUK0SA17.mjs → status-CqJQX1QN.mjs} +1 -1
- package/dist/{status-vUK0SA17.mjs.map → status-CqJQX1QN.mjs.map} +1 -1
- package/dist/storage/local.d.mts +1 -1
- package/dist/storage/local.mjs +1 -1
- package/dist/storage/s3.d.mts +1 -1
- package/dist/storage/s3.mjs +1 -1
- package/dist/{taxonomies-DChKcVxf.mjs → taxonomies-BGBd16Eu.mjs} +4 -4
- package/dist/{taxonomies-DChKcVxf.mjs.map → taxonomies-BGBd16Eu.mjs.map} +1 -1
- package/dist/{taxonomies-ckPjz-6d.mjs → taxonomies-Cnb4F-Pb.mjs} +7 -7
- package/dist/{taxonomies-ckPjz-6d.mjs.map → taxonomies-Cnb4F-Pb.mjs.map} +1 -1
- package/dist/{taxonomy-Cru-he6s.mjs → taxonomy-BxGxZZdu.mjs} +4 -4
- package/dist/{taxonomy-Cru-he6s.mjs.map → taxonomy-BxGxZZdu.mjs.map} +1 -1
- package/dist/{tokens-LeuXF9gG.mjs → tokens-BGT0TUUo.mjs} +1 -1
- package/dist/{tokens-LeuXF9gG.mjs.map → tokens-BGT0TUUo.mjs.map} +1 -1
- package/dist/{transport-Blrl2k_o.d.mts → transport-BMDWHSgZ.d.mts} +1 -1
- package/dist/{transport-Blrl2k_o.d.mts.map → transport-BMDWHSgZ.d.mts.map} +1 -1
- package/dist/{transport-_2nBz7e9.mjs → transport-DPefPMcz.mjs} +1 -1
- package/dist/{transport-_2nBz7e9.mjs.map → transport-DPefPMcz.mjs.map} +1 -1
- package/dist/{trusted-proxy-DZY5WCn2.mjs → trusted-proxy-VTPRiX2s.mjs} +1 -1
- package/dist/{trusted-proxy-DZY5WCn2.mjs.map → trusted-proxy-VTPRiX2s.mjs.map} +1 -1
- package/dist/{types-ETmO_jQr.d.mts → types-BcLUUbbR.d.mts} +2 -2
- package/dist/{types-ETmO_jQr.d.mts.map → types-BcLUUbbR.d.mts.map} +1 -1
- package/dist/{types-BYnDBVwe.d.mts → types-CGbYowGQ.d.mts} +2 -2
- package/dist/{types-BYnDBVwe.d.mts.map → types-CGbYowGQ.d.mts.map} +1 -1
- package/dist/{types-CvuKO5Pn.d.mts → types-CgvhU-hF.d.mts} +1 -1
- package/dist/{types-CvuKO5Pn.d.mts.map → types-CgvhU-hF.d.mts.map} +1 -1
- package/dist/{types-Y09-wtyU.d.mts → types-ClUkdbWb.d.mts} +1 -1
- package/dist/{types-Y09-wtyU.d.mts.map → types-ClUkdbWb.d.mts.map} +1 -1
- package/dist/{types-DU4TSFS5.mjs → types-CuW0zWDA.mjs} +2 -2
- package/dist/{types-DU4TSFS5.mjs.map → types-CuW0zWDA.mjs.map} +1 -1
- package/dist/{types-BkZ8DUEI.d.mts → types-DmHk7vAt.d.mts} +1 -1
- package/dist/{types-BkZ8DUEI.d.mts.map → types-DmHk7vAt.d.mts.map} +1 -1
- package/dist/{types-CQAugunJ.mjs → types-Jo3UYd6b.mjs} +1 -1
- package/dist/{types-CQAugunJ.mjs.map → types-Jo3UYd6b.mjs.map} +1 -1
- package/dist/{types-xIfVRNLp.d.mts → types-_HFLRzTn.d.mts} +22 -1
- package/dist/types-_HFLRzTn.d.mts.map +1 -0
- package/dist/{types-ByChcBgE.d.mts → types-ea9sAPck.d.mts} +1 -1
- package/dist/{types-ByChcBgE.d.mts.map → types-ea9sAPck.d.mts.map} +1 -1
- package/dist/{types-CNlaBFzx.d.mts → types-g_aFIdW0.d.mts} +1 -1
- package/dist/{types-CNlaBFzx.d.mts.map → types-g_aFIdW0.d.mts.map} +1 -1
- package/dist/{types-Dbqff978.d.mts → types-vgEWF18A.d.mts} +19 -1
- package/dist/{types-Dbqff978.d.mts.map → types-vgEWF18A.d.mts.map} +1 -1
- package/dist/{user-DgGbKL9s.mjs → user-BjAOvU3Z.mjs} +3 -3
- package/dist/{user-DgGbKL9s.mjs.map → user-BjAOvU3Z.mjs.map} +1 -1
- package/dist/{utils-B7A57fm9.mjs → utils-BJXElxdw.mjs} +156 -7
- package/dist/utils-BJXElxdw.mjs.map +1 -0
- package/dist/{validate-CRkcYZAR.mjs → validate-CWSnKVIJ.mjs} +2 -2
- package/dist/{validate-CRkcYZAR.mjs.map → validate-CWSnKVIJ.mjs.map} +1 -1
- package/dist/{validate-9ECmtEpJ.d.mts → validate-Z1b86_3B.d.mts} +5 -5
- package/dist/{validate-9ECmtEpJ.d.mts.map → validate-Z1b86_3B.d.mts.map} +1 -1
- package/dist/{validation-sR26SOwD.mjs → validation-c8WjhH8z.mjs} +8 -5
- package/dist/{validation-sR26SOwD.mjs.map → validation-c8WjhH8z.mjs.map} +1 -1
- package/dist/version-CaccU7DM.mjs +7 -0
- package/dist/{version-CrqhKGWn.mjs.map → version-CaccU7DM.mjs.map} +1 -1
- package/dist/{widgets-DRgtn7Cl.mjs → widgets-hWcIicX8.mjs} +3 -3
- package/dist/{widgets-DRgtn7Cl.mjs.map → widgets-hWcIicX8.mjs.map} +1 -1
- package/dist/wxr-taxonomies-0_uxSrmf.d.mts +34 -0
- package/dist/wxr-taxonomies-0_uxSrmf.d.mts.map +1 -0
- package/dist/wxr-taxonomies-BC3OYpvx.mjs +425 -0
- package/dist/wxr-taxonomies-BC3OYpvx.mjs.map +1 -0
- package/dist/{zod-generator-C5JaV--i.mjs → zod-generator-CacrR-i8.mjs} +2 -2
- package/dist/{zod-generator-C5JaV--i.mjs.map → zod-generator-CacrR-i8.mjs.map} +1 -1
- package/package.json +7 -7
- package/src/api/handlers/content.ts +10 -7
- package/src/api/schemas/import.ts +19 -0
- package/src/astro/integration/runtime.ts +3 -6
- package/src/astro/middleware/auth.ts +9 -3
- package/src/astro/middleware/csp.ts +54 -3
- package/src/astro/routes/admin.astro +9 -0
- package/src/astro/routes/api/import/wordpress/rewrite-urls.ts +122 -98
- package/src/astro/routes/api/import/wordpress-plugin/execute.ts +794 -44
- package/src/components/EmDashImage.astro +59 -23
- package/src/components/Image.astro +36 -35
- package/src/database/migrations/049_taxonomies_name_locale_index.ts +42 -0
- package/src/database/migrations/050_media_usage_index_status.ts +142 -0
- package/src/database/migrations/runner.ts +4 -0
- package/src/database/repositories/media-usage.ts +932 -58
- package/src/database/types.ts +22 -0
- package/src/emdash-runtime.ts +123 -3
- package/src/import/comments.ts +159 -0
- package/src/import/index.ts +8 -1
- package/src/import/settings.ts +65 -189
- package/src/import/sources/wordpress-plugin.ts +338 -42
- package/src/import/sources/wxr.ts +4 -1
- package/src/import/types.ts +12 -0
- package/src/import/utils.ts +207 -0
- package/src/import/wxr-taxonomies.ts +39 -0
- package/src/loader.ts +13 -2
- package/src/media/usage/content-fields.ts +119 -0
- package/src/media/usage/content-refresh.ts +524 -0
- package/src/media/usage/content-repair.ts +491 -0
- package/src/media/usage/content-snapshots.ts +435 -0
- package/src/media/usage/extractor.ts +4 -4
- package/src/media/usage/source-key.ts +22 -0
- package/src/menus/index.ts +17 -1
- package/src/object-cache/index.ts +82 -7
- package/src/plugins/context.ts +100 -71
- package/src/schema/registry.ts +240 -154
- package/src/seed/apply.ts +156 -99
- package/dist/api-80kycR9o.mjs.map +0 -1
- package/dist/apply-DSypk6Iu.mjs.map +0 -1
- package/dist/byline-fields-eyJMblSr.mjs.map +0 -1
- package/dist/context-CzUU_WzL.mjs.map +0 -1
- package/dist/import-Bb1T9WJS.mjs.map +0 -1
- package/dist/index-DGIjmUXQ.d.mts.map +0 -1
- package/dist/loader-4K37qA-y.mjs.map +0 -1
- package/dist/object-cache-CHbHv83-.mjs.map +0 -1
- package/dist/registry-DP-iEtdR.mjs.map +0 -1
- package/dist/runner-CFngB4WZ.mjs.map +0 -1
- package/dist/scheduled-publish-BMljtY5G.d.mts.map +0 -1
- package/dist/types-xIfVRNLp.d.mts.map +0 -1
- package/dist/utils-B7A57fm9.mjs.map +0 -1
- package/dist/version-CrqhKGWn.mjs +0 -7
- /package/dist/{api-tokens-B4BQybOp.mjs → api-tokens-DsvvCtdh.mjs} +0 -0
- /package/dist/{ssrf-CcX9zvMK.mjs → ssrf-CmuGgCq3.mjs} +0 -0
- /package/dist/{types-BvbeGEtr.mjs → types-DROWRxYV.mjs} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"taxonomies-ckPjz-6d.mjs","names":[],"sources":["../src/taxonomies/index.ts"],"sourcesContent":["/**\n * Runtime API for taxonomies.\n *\n * All helpers are locale-aware. When a locale is not passed explicitly we fall\n * back to the request context or the configured `defaultLocale` (see\n * `i18n/resolve.ts`).\n *\n * Because `content_taxonomies.taxonomy_id` stores the translation_group (not a\n * specific term id), the joins here are `taxonomies.translation_group =\n * content_taxonomies.taxonomy_id` + filter by `taxonomies.locale`, which picks\n * the right per-locale term.\n */\n\nimport { resolveLocale, resolveLocaleChain } from \"../i18n/resolve.js\";\nimport { getDb, resetTaxonomyNamesCache } from \"../loader.js\";\nimport {\n\tcachedQuery,\n\tCacheNamespace,\n\tcontentNamespace,\n\tinvalidateTaxonomyObjectCache,\n\tisObjectCacheActive,\n} from \"../object-cache/index.js\";\nimport { peekRequestCache, requestCached, setRequestCacheEntry } from \"../request-cache.js\";\nimport { getRequestContext } from \"../request-context.js\";\nimport { chunks, SQL_BATCH_SIZE } from \"../utils/chunks.js\";\nimport { isMissingTableError } from \"../utils/db-errors.js\";\nimport type { TaxonomyDef, TaxonomyTerm, TaxonomyTermRow } from \"./types.js\";\n\nexport interface TaxonomyQueryOptions {\n\tlocale?: string;\n}\n\n/** Invalidate cached taxonomy term data and any content that hydrates terms. */\nexport function invalidateTermCache(): void {\n\tinvalidateTaxonomyObjectCache();\n}\n\n/**\n * Worker-isolate cache for taxonomy definitions, keyed by resolved locale.\n *\n * Taxonomy *definitions* (the \"category\"/\"tag\" taxonomies themselves, not\n * their terms) are read on every public render that hydrates entry terms —\n * `getAllTermsForEntries` → `getCollectionTaxonomyNames` → `getTaxonomyDefs` —\n * but change extremely rarely: they're created via the admin API or applied\n * from a seed, and there is no edit/delete-def path. Caching them across the\n * isolate lifetime drops the per-render `SELECT * FROM _emdash_taxonomy_defs`\n * to once-per-isolate.\n *\n * Stored on globalThis behind a Symbol key (same pattern as\n * `settings/index.ts`) so the bundler duplicating this module across SSR\n * chunks can't produce two independent caches.\n *\n * When the distributed object cache is configured, it is authoritative and this\n * fallback is bypassed so cross-isolate epoch invalidation cannot be undercut\n * by stale per-isolate data on an object-cache miss.\n *\n * **Isolated databases bypass the cache.** Playground / DO preview requests\n * set `requestContext.dbIsIsolated`; they point at a divergent schema, so we\n * skip both reading and writing the global holder and fall back to the\n * per-request cache (same precedent as `getTaxonomyNames` / byline field defs).\n */\ninterface TaxonomyDefsHolder {\n\tversion: number;\n\t/** locale key (\"*\" for \"all locales\") → { version it was fetched at, promise }. */\n\tcache: Map<string, { version: number; promise: Promise<TaxonomyDef[]> }>;\n}\n\nconst TAXONOMY_DEFS_CACHE_KEY = Symbol.for(\"emdash:taxonomy-defs\");\nconst taxonomyDefsStore = globalThis as Record<symbol, unknown>;\nconst defsHolder: TaxonomyDefsHolder =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see settings/index.ts)\n\t(taxonomyDefsStore[TAXONOMY_DEFS_CACHE_KEY] as TaxonomyDefsHolder | undefined) ??\n\t(() => {\n\t\tconst h: TaxonomyDefsHolder = { version: 0, cache: new Map() };\n\t\ttaxonomyDefsStore[TAXONOMY_DEFS_CACHE_KEY] = h;\n\t\treturn h;\n\t})();\n\n/**\n * Invalidate the isolate-wide taxonomy-definitions cache (and the related\n * loader taxonomy-names cache). Called from every taxonomy-def write path\n * (`handleTaxonomyCreate`, seed application). Other isolates refresh on their\n * next recycle — staleness bounded by isolate lifetime.\n */\nexport function invalidateTaxonomyDefsCache(): void {\n\tdefsHolder.version++;\n\tdefsHolder.cache.clear();\n\tresetTaxonomyNamesCache();\n\tinvalidateTaxonomyObjectCache();\n}\n\n/**\n * Test/internal helper: clear the per-isolate taxonomy-defs cache. Useful for\n * unit tests that insert defs directly and need to force a refetch without\n * going through a write path. Production code should rely on\n * `invalidateTaxonomyDefsCache()`.\n */\nexport function resetTaxonomyDefsCacheForTests(): void {\n\tdefsHolder.version++;\n\tdefsHolder.cache.clear();\n}\n\n/**\n * Fetch taxonomy definitions straight from the database (no caching).\n */\nasync function fetchTaxonomyDefs(locale: string | undefined): Promise<TaxonomyDef[]> {\n\tconst db = await getDb();\n\tlet query = db.selectFrom(\"_emdash_taxonomy_defs\").selectAll();\n\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\tconst rows = await query.execute();\n\treturn rows.map(rowToTaxonomyDef);\n}\n\n/**\n * Resolve taxonomy defs through the isolate fallback cache, bypassing it for\n * isolated databases. The returned promise is cached (not the resolved value)\n * so concurrent cold-isolate readers share one in-flight query; a rejection\n * evicts the entry so the next caller retries.\n */\nfunction loadTaxonomyDefs(localeKey: string, locale: string | undefined): Promise<TaxonomyDef[]> {\n\tif (getRequestContext()?.dbIsIsolated === true) {\n\t\treturn fetchTaxonomyDefs(locale);\n\t}\n\tconst existing = defsHolder.cache.get(localeKey);\n\tif (existing && existing.version === defsHolder.version) {\n\t\treturn existing.promise;\n\t}\n\tconst version = defsHolder.version;\n\tconst promise = fetchTaxonomyDefs(locale).catch((error: unknown) => {\n\t\tconst current = defsHolder.cache.get(localeKey);\n\t\tif (current && current.promise === promise) {\n\t\t\tdefsHolder.cache.delete(localeKey);\n\t\t}\n\t\tthrow error;\n\t});\n\tdefsHolder.cache.set(localeKey, { version, promise });\n\treturn promise;\n}\n\n/**\n * Get every taxonomy definition. Definitions are per-locale (one row per\n * locale inside the same translation_group) — by default we resolve to the\n * active locale.\n *\n * Two-tier cache: per-request via `requestCached` (so a single render that\n * hydrates terms for several collections pays at most one call), then\n * per-isolate via the global holder (so warm renders issue zero queries).\n * The `requestCached` key is unchanged so `getTaxonomyDef`'s peek still hits.\n */\nexport async function getTaxonomyDefs(options: TaxonomyQueryOptions = {}): Promise<TaxonomyDef[]> {\n\tconst locale = resolveLocale(options.locale);\n\tconst localeKey = locale ?? \"*\";\n\treturn requestCached(`taxonomy-defs:${localeKey}`, async () => {\n\t\tif (await isObjectCacheActive()) {\n\t\t\treturn cachedQuery({\n\t\t\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\t\t\tkey: `defs:${localeKey}`,\n\t\t\t\tload: () => fetchTaxonomyDefs(locale),\n\t\t\t});\n\t\t}\n\t\treturn loadTaxonomyDefs(localeKey, locale);\n\t});\n}\n\n/**\n * Get a single taxonomy definition by name. Uses the fallback chain so even\n * if there is no translation for the active locale we still return something.\n *\n * If `getTaxonomyDefs()` has already loaded the full list in this request\n * (which happens during entry-term hydration on every page that renders a\n * collection), search the matching def in memory rather than running a\n * second query against `_emdash_taxonomy_defs`.\n */\nexport async function getTaxonomyDef(\n\tname: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyDef | null> {\n\tconst chain = resolveLocaleChain(options.locale);\n\tconst peekKey = `taxonomy-defs:${resolveLocale(options.locale) ?? \"*\"}`;\n\tconst allDefs = peekRequestCache<TaxonomyDef[]>(peekKey);\n\tif (allDefs) {\n\t\tconst defs = await allDefs;\n\t\tif (chain.length === 0) return defs.find((d) => d.name === name) ?? null;\n\t\tfor (const locale of chain) {\n\t\t\tconst found = defs.find((d) => d.name === name && d.locale === locale);\n\t\t\tif (found) return found;\n\t\t}\n\t\treturn null;\n\t}\n\n\treturn requestCached(`taxonomy-def:${name}:${chain.join(\",\")}`, async () => {\n\t\tconst db = await getDb();\n\n\t\tif (chain.length === 0) {\n\t\t\tconst row = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"name\", \"=\", name)\n\t\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t\t.executeTakeFirst();\n\t\t\treturn row ? rowToTaxonomyDef(row) : null;\n\t\t}\n\n\t\tfor (const locale of chain) {\n\t\t\tconst row = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"name\", \"=\", name)\n\t\t\t\t.where(\"locale\", \"=\", locale)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (row) return rowToTaxonomyDef(row);\n\t\t}\n\t\treturn null;\n\t});\n}\n\n/**\n * All terms of a taxonomy in a specific locale (flat for non-hierarchical,\n * tree for hierarchical).\n */\nexport async function getTaxonomyTerms(\n\ttaxonomyName: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\treturn requestCached(`taxonomy-terms:${taxonomyName}:${locale ?? \"*\"}`, () =>\n\t\tcachedQuery({\n\t\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\t\tkey: `terms:${taxonomyName}:${locale ?? \"*\"}`,\n\t\t\tload: () => loadTaxonomyTerms(taxonomyName, locale, options),\n\t\t}),\n\t);\n}\n\nasync function loadTaxonomyTerms(\n\ttaxonomyName: string,\n\tlocale: string | undefined,\n\toptions: TaxonomyQueryOptions,\n): Promise<TaxonomyTerm[]> {\n\tconst db = await getDb();\n\n\tconst def = await getTaxonomyDef(taxonomyName, options);\n\tif (!def) return [];\n\n\tlet termsQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t.where(\"name\", \"=\", taxonomyName)\n\t\t.orderBy(\"label\", \"asc\");\n\tif (locale !== undefined) termsQuery = termsQuery.where(\"locale\", \"=\", locale);\n\tconst rows = await termsQuery.execute();\n\n\t// Counts are keyed by translation_group (what the pivot stores) and are\n\t// locale-independent, so the aggregate is shared across every taxonomy\n\t// rendered in this request (Categories + Tags widgets, etc.).\n\tconst counts = await getTaxonomyTermCounts();\n\n\tconst flatTerms: TaxonomyTermRow[] = rows.map((row) => ({\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tlabel: row.label,\n\t\tparent_id: row.parent_id,\n\t\tdata: row.data,\n\t\tlocale: row.locale,\n\t\ttranslation_group: row.translation_group,\n\t}));\n\n\tif (def.hierarchical) return buildTree(flatTerms, counts);\n\n\treturn flatTerms.map((term) => ({\n\t\tid: term.id,\n\t\tname: term.name,\n\t\tslug: term.slug,\n\t\tlabel: term.label,\n\t\tdescription: term.data ? JSON.parse(term.data).description : undefined,\n\t\tchildren: [],\n\t\tcount: counts.get(term.translation_group ?? term.id) ?? 0,\n\t\tlocale: term.locale,\n\t\ttranslationGroup: term.translation_group,\n\t}));\n}\n\n/**\n * Per-translation-group usage counts across all taxonomies, in one aggregate\n * scan of `content_taxonomies`. Counts are locale-independent (the pivot stores\n * translation_group), so a single request-cached entry serves every taxonomy\n * that renders during the request.\n */\nfunction getTaxonomyTermCounts(): Promise<Map<string, number>> {\n\treturn requestCached(\"taxonomy-term-counts\", async () => {\n\t\tconst db = await getDb();\n\t\tconst countsResult = await db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select([\"taxonomy_id\"])\n\t\t\t.select((eb) => eb.fn.count<number>(\"entry_id\").as(\"count\"))\n\t\t\t.groupBy(\"taxonomy_id\")\n\t\t\t.execute();\n\t\tconst counts = new Map<string, number>();\n\t\tfor (const row of countsResult) counts.set(row.taxonomy_id, row.count);\n\t\treturn counts;\n\t});\n}\n\n/**\n * Get a single term by (taxonomy, slug). Honours the fallback chain — if the\n * slug exists in a fallback locale, we return that row (useful for deep-linking\n * to a term page when the translation is missing).\n */\nexport async function getTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm | null> {\n\tconst chain = resolveLocaleChain(options.locale);\n\t// Cached under the shared taxonomies epoch (bumped on any taxonomy / term\n\t// assignment write). The `count` reflects content_taxonomies rows; a stale\n\t// count after a bare content delete is bounded by the entry's TTL.\n\treturn cachedQuery({\n\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\tkey: `term:${taxonomyName}:${slug}:${chain.join(\",\")}`,\n\t\tload: () => loadTerm(taxonomyName, slug, chain),\n\t});\n}\n\nasync function loadTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\tchain: string[],\n): Promise<TaxonomyTerm | null> {\n\tconst db = await getDb();\n\n\tlet row: Awaited<ReturnType<ReturnType<typeof selectTerm>[\"executeTakeFirst\"]>>;\n\tconst selectTerm = () =>\n\t\tdb\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", taxonomyName)\n\t\t\t.where(\"slug\", \"=\", slug);\n\n\tif (chain.length === 0) {\n\t\trow = await selectTerm().orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t} else {\n\t\trow = undefined;\n\t\tfor (const locale of chain) {\n\t\t\trow = await selectTerm().where(\"locale\", \"=\", locale).executeTakeFirst();\n\t\t\tif (row) break;\n\t\t}\n\t}\n\n\tif (!row) return null;\n\n\tlet childrenQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t// Children store the parent's translation_group in parent_id (not a row\n\t\t// id), so a translated parent still owns its children in its own locale.\n\t\t.where(\"parent_id\", \"=\", row.translation_group ?? row.id)\n\t\t.orderBy(\"label\", \"asc\");\n\tconst termLocale = row.locale;\n\tif (termLocale) childrenQuery = childrenQuery.where(\"locale\", \"=\", termLocale);\n\n\t// The usage-count and children queries both depend only on the term row,\n\t// so run them concurrently to save a round trip on remote databases.\n\tconst [countResult, childRows] = await Promise.all([\n\t\tdb\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select((eb) => eb.fn.count<number>(\"entry_id\").as(\"count\"))\n\t\t\t.where(\"taxonomy_id\", \"=\", row.translation_group ?? row.id)\n\t\t\t.executeTakeFirst(),\n\t\tchildrenQuery.execute(),\n\t]);\n\tconst count = countResult?.count ?? 0;\n\n\tconst children = childRows.map<TaxonomyTerm>((child) => ({\n\t\tid: child.id,\n\t\tname: child.name,\n\t\tslug: child.slug,\n\t\tlabel: child.label,\n\t\tparentId: child.parent_id ?? undefined,\n\t\tchildren: [],\n\t\tlocale: child.locale,\n\t\ttranslationGroup: child.translation_group,\n\t}));\n\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tlabel: row.label,\n\t\tparentId: row.parent_id ?? undefined,\n\t\tdescription: row.data ? JSON.parse(row.data).description : undefined,\n\t\tchildren,\n\t\tcount,\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n/**\n * Terms assigned to a content entry, resolved into the active locale. Terms\n * whose translation_group lacks a row in the requested locale are omitted.\n */\nexport function getEntryTerms(\n\tcollection: string,\n\tentryId: string,\n\ttaxonomyName?: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\t// requestCached short-circuits to values primed by getAllTermsForEntries\n\t// during entry hydration (same key shape). On a warm content-cache hit\n\t// hydration doesn't run, so the inner cachedQuery serves this from KV\n\t// instead of falling through to D1 on every request.\n\treturn requestCached(\n\t\t`terms:${collection}:${entryId}:${taxonomyName ?? \"*\"}:${locale ?? \"*\"}`,\n\t\t() =>\n\t\t\tcachedQuery({\n\t\t\t\tnamespace: [contentNamespace(collection), CacheNamespace.TAXONOMIES],\n\t\t\t\tkey: `entryTerms:${collection}:${entryId}:${taxonomyName ?? \"*\"}:${locale ?? \"*\"}`,\n\t\t\t\tload: async () => {\n\t\t\t\t\tconst db = await getDb();\n\n\t\t\t\t\tlet query = db\n\t\t\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t\t\t.innerJoin(\n\t\t\t\t\t\t\t\"taxonomies\",\n\t\t\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t\t\t\t\"content_taxonomies.taxonomy_id\",\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.selectAll(\"taxonomies\")\n\t\t\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryId);\n\n\t\t\t\t\tif (taxonomyName) query = query.where(\"taxonomies.name\", \"=\", taxonomyName);\n\t\t\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\n\t\t\t\t\tconst rows = await query.execute();\n\t\t\t\t\treturn rows.map<TaxonomyTerm>((row) => ({\n\t\t\t\t\t\tid: row.id,\n\t\t\t\t\t\tname: row.name,\n\t\t\t\t\t\tslug: row.slug,\n\t\t\t\t\t\tlabel: row.label,\n\t\t\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\t\t\tchildren: [],\n\t\t\t\t\t\tlocale: row.locale,\n\t\t\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t\t\t}));\n\t\t\t\t},\n\t\t\t}),\n\t);\n}\n\n/**\n * Terms for multiple entries of one taxonomy, single query.\n */\nexport async function getTermsForEntries(\n\tcollection: string,\n\tentryIds: string[],\n\ttaxonomyName: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Map<string, TaxonomyTerm[]>> {\n\tconst uniqueIds = [...new Set(entryIds)];\n\tif (uniqueIds.length === 0) return new Map();\n\tconst locale = resolveLocale(options.locale);\n\tconst localeKey = locale ?? \"*\";\n\n\t// The query result is a Map, which JSON can't represent — cache it as an\n\t// array of [entryId, terms] pairs and rebuild the Map on read.\n\tconst load = async (): Promise<Array<[string, TaxonomyTerm[]]>> => {\n\t\tconst result = new Map<string, TaxonomyTerm[]>();\n\t\tfor (const id of uniqueIds) result.set(id, []);\n\n\t\t// Entry-term hydration (getAllTermsForEntries -> primeEntryTermsCache)\n\t\t// seeds the per-entry cache under the same key getEntryTerms uses:\n\t\t// `terms:${collection}:${entryId}:${taxonomyName}:${localeKey}`, storing a\n\t\t// TaxonomyTerm[] (including `[]` for entries with no terms). Satisfy those\n\t\t// from cache and run the batched query only for the ids that missed.\n\t\tconst missedIds: string[] = [];\n\t\ttype CacheRead = { id: string; terms: TaxonomyTerm[] } | { id: string; miss: true };\n\t\tconst cacheReads: Array<Promise<CacheRead>> = [];\n\t\tfor (const id of uniqueIds) {\n\t\t\tconst cached = peekRequestCache<TaxonomyTerm[]>(\n\t\t\t\t`terms:${collection}:${id}:${taxonomyName}:${localeKey}`,\n\t\t\t);\n\t\t\tif (cached) {\n\t\t\t\t// A peeked promise can reject (e.g. a sibling getEntryTerms hit a\n\t\t\t\t// missing table). Treat a rejection as a cache miss so the batched\n\t\t\t\t// query path -- and its isMissingTableError guard below -- still runs,\n\t\t\t\t// rather than propagating an uncaught error.\n\t\t\t\tcacheReads.push(\n\t\t\t\t\tcached.then(\n\t\t\t\t\t\t(terms): CacheRead => ({ id, terms }),\n\t\t\t\t\t\t(): CacheRead => ({ id, miss: true }),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmissedIds.push(id);\n\t\t\t}\n\t\t}\n\t\tfor (const read of await Promise.all(cacheReads)) {\n\t\t\tif (\"miss\" in read) {\n\t\t\t\tmissedIds.push(read.id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Return a private copy. The cached array and its term objects are shared\n\t\t\t// with getEntryTerms/getAllTermsForEntries (primeEntryTermsCache stores\n\t\t\t// the same references), so a caller that mutates the result -- sorting in\n\t\t\t// place, pushing into `children` -- must not poison the cache. The\n\t\t\t// pre-cache implementation always returned freshly built arrays.\n\t\t\tresult.set(\n\t\t\t\tread.id,\n\t\t\t\tread.terms.map((t) => ({ ...t, children: [...t.children] })),\n\t\t\t);\n\t\t}\n\n\t\tif (missedIds.length === 0) return [...result.entries()];\n\n\t\tconst db = await getDb();\n\t\tfor (const chunk of chunks(missedIds, SQL_BATCH_SIZE)) {\n\t\t\tlet rows;\n\t\t\ttry {\n\t\t\t\tlet query = db\n\t\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t\t\t.select([\n\t\t\t\t\t\t\"content_taxonomies.entry_id\",\n\t\t\t\t\t\t\"taxonomies.id\",\n\t\t\t\t\t\t\"taxonomies.name\",\n\t\t\t\t\t\t\"taxonomies.slug\",\n\t\t\t\t\t\t\"taxonomies.label\",\n\t\t\t\t\t\t\"taxonomies.parent_id\",\n\t\t\t\t\t\t\"taxonomies.locale\",\n\t\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t\t])\n\t\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t\t.where(\"content_taxonomies.entry_id\", \"in\", chunk)\n\t\t\t\t\t.where(\"taxonomies.name\", \"=\", taxonomyName)\n\t\t\t\t\t// Match the order getAllTermsForEntries (the cache primer) uses, so\n\t\t\t\t\t// cache-hit and DB-miss entries in one result are ordered consistently.\n\t\t\t\t\t.orderBy(\"taxonomies.label\", \"asc\");\n\t\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\t\t\t\trows = await query.execute();\n\t\t\t} catch (error) {\n\t\t\t\tif (isMissingTableError(error)) return [...result.entries()];\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst term: TaxonomyTerm = {\n\t\t\t\t\tid: row.id,\n\t\t\t\t\tname: row.name,\n\t\t\t\t\tslug: row.slug,\n\t\t\t\t\tlabel: row.label,\n\t\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\t\tchildren: [],\n\t\t\t\t\tlocale: row.locale,\n\t\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t\t};\n\t\t\t\tconst terms = result.get(row.entry_id);\n\t\t\t\tif (terms) terms.push(term);\n\t\t\t}\n\t\t}\n\n\t\treturn [...result.entries()];\n\t};\n\n\t// Key on the sorted unique ids. Bound the key length: very large batches\n\t// (rare; they come from collection hydration, already served by the content\n\t// cache) bypass the object cache rather than blow past KV's key limit.\n\tconst idKey = uniqueIds.toSorted().join(\",\");\n\tconst pairs =\n\t\tidKey.length <= 256\n\t\t\t? await cachedQuery({\n\t\t\t\t\tnamespace: [contentNamespace(collection), CacheNamespace.TAXONOMIES],\n\t\t\t\t\tkey: `termsForEntries:${collection}:${taxonomyName}:${locale ?? \"*\"}:${idKey}`,\n\t\t\t\t\tload,\n\t\t\t\t})\n\t\t\t: await load();\n\n\treturn new Map(pairs);\n}\n\n/**\n * Batch-fetch terms for multiple entries across ALL taxonomies in one query.\n * Primes the request-cache for subsequent per-entry calls to `getEntryTerms`.\n */\nexport async function getAllTermsForEntries(\n\tcollection: string,\n\tentryIds: string[],\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Map<string, Record<string, TaxonomyTerm[]>>> {\n\tconst result = new Map<string, Record<string, TaxonomyTerm[]>>();\n\tconst uniqueIds = [...new Set(entryIds)];\n\tfor (const id of uniqueIds) result.set(id, {});\n\tif (uniqueIds.length === 0) return result;\n\n\tconst db = await getDb();\n\tconst locale = resolveLocale(options.locale);\n\tconst applicableTaxonomyNames = await getCollectionTaxonomyNames(collection, { locale });\n\n\tfor (const chunk of chunks(uniqueIds, SQL_BATCH_SIZE)) {\n\t\tlet rows;\n\t\ttry {\n\t\t\tlet query = db\n\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t\t.select([\n\t\t\t\t\t\"content_taxonomies.entry_id\",\n\t\t\t\t\t\"taxonomies.id\",\n\t\t\t\t\t\"taxonomies.name\",\n\t\t\t\t\t\"taxonomies.slug\",\n\t\t\t\t\t\"taxonomies.label\",\n\t\t\t\t\t\"taxonomies.parent_id\",\n\t\t\t\t\t\"taxonomies.locale\",\n\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t])\n\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t.where(\"content_taxonomies.entry_id\", \"in\", chunk)\n\t\t\t\t.orderBy(\"taxonomies.label\", \"asc\");\n\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\t\t\trows = await query.execute();\n\t\t} catch (error) {\n\t\t\tif (isMissingTableError(error)) {\n\t\t\t\tfor (const id of uniqueIds) {\n\t\t\t\t\tprimeEntryTermsCache(collection, id, {}, applicableTaxonomyNames, locale);\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\tfor (const row of rows) {\n\t\t\tconst term: TaxonomyTerm = {\n\t\t\t\tid: row.id,\n\t\t\t\tname: row.name,\n\t\t\t\tslug: row.slug,\n\t\t\t\tlabel: row.label,\n\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\tchildren: [],\n\t\t\t\tlocale: row.locale,\n\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t};\n\t\t\tconst byTaxonomy = result.get(row.entry_id);\n\t\t\tif (!byTaxonomy) continue;\n\t\t\tconst existing = byTaxonomy[row.name];\n\t\t\tif (existing) existing.push(term);\n\t\t\telse byTaxonomy[row.name] = [term];\n\t\t}\n\t}\n\n\tfor (const [entryId, byTaxonomy] of result) {\n\t\tprimeEntryTermsCache(collection, entryId, byTaxonomy, applicableTaxonomyNames, locale);\n\t}\n\n\treturn result;\n}\n\n/**\n * Return the list of taxonomy names applicable to a collection, request-\n * cached so a page render only pays for it once.\n *\n * Returns an empty list when taxonomies haven't been defined yet.\n */\nasync function getCollectionTaxonomyNames(\n\tcollection: string,\n\toptions: TaxonomyQueryOptions,\n): Promise<string[]> {\n\ttry {\n\t\tconst defs = await getTaxonomyDefs(options);\n\t\treturn defs.filter((d) => d.collections.includes(collection)).map((d) => d.name);\n\t} catch (error) {\n\t\tif (isMissingTableError(error)) return [];\n\t\tthrow error;\n\t}\n}\n\n/**\n * Pre-populate the request-cache for every getEntryTerms call-shape that\n * could hit this entry:\n *\n * getEntryTerms(collection, entryId) -> key `terms:C:E:*`\n * getEntryTerms(collection, entryId, \"tag\") -> key `terms:C:E:tag`\n * getEntryTerms(collection, entryId, \"category\") -> key `terms:C:E:category`\n * ...one per taxonomy that applies to this collection\n *\n * Taxonomies with no rows on this entry are seeded with `[]` so legacy\n * callers short-circuit to the cached empty array instead of re-querying.\n */\nfunction primeEntryTermsCache(\n\tcollection: string,\n\tentryId: string,\n\tbyTaxonomy: Record<string, TaxonomyTerm[]>,\n\tapplicableTaxonomyNames: string[],\n\tlocale: string | undefined,\n): void {\n\tconst localeKey = locale ?? \"*\";\n\tfor (const name of applicableTaxonomyNames) {\n\t\tsetRequestCacheEntry(\n\t\t\t`terms:${collection}:${entryId}:${name}:${localeKey}`,\n\t\t\tbyTaxonomy[name] ?? [],\n\t\t);\n\t}\n\tfor (const [name, terms] of Object.entries(byTaxonomy)) {\n\t\tsetRequestCacheEntry(`terms:${collection}:${entryId}:${name}:${localeKey}`, terms);\n\t}\n\tconst allTerms = Object.values(byTaxonomy).flat();\n\tsetRequestCacheEntry(`terms:${collection}:${entryId}:*:${localeKey}`, allTerms);\n}\n\n/**\n * Prime the per-entry request cache from terms that were folded into the\n * content query (query.ts `hydrateEntryTerms` fast path), so subsequent\n * `getEntryTerms` calls in the same render hit the cache instead of issuing an\n * N+1 query. Seeds the wildcard key and one key per taxonomy present on the\n * entry — purely from the folded data, with no DB lookup.\n *\n * Unlike `getAllTermsForEntries`, this deliberately does NOT seed `[]` for\n * taxonomies that apply to the collection but have no rows on the entry: doing\n * so would require a `getTaxonomyDefs` query, adding a round trip to every fold\n * render to serve the rarer `getEntryTerms(id, absentTaxonomy)` case from cache.\n * That call simply falls through to its own cached query. Keeping the key shape\n * here (rather than in query.ts) prevents the two from drifting.\n */\nexport function primeFoldedEntryTerms(\n\tcollection: string,\n\tperEntry: Array<{ entryId: string; byTaxonomy: Record<string, TaxonomyTerm[]> }>,\n\toptions: TaxonomyQueryOptions = {},\n): void {\n\tif (perEntry.length === 0) return;\n\tconst locale = resolveLocale(options.locale);\n\tfor (const { entryId, byTaxonomy } of perEntry) {\n\t\tprimeEntryTermsCache(collection, entryId, byTaxonomy, [], locale);\n\t}\n}\n\n/**\n * Get entries by term. Both the lookup (term slug in the active locale) and\n * the content query respect the active locale.\n */\nexport async function getEntriesByTerm(\n\tcollection: string,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Array<{ id: string; data: Record<string, unknown> }>> {\n\tconst { getEmDashCollection } = await import(\"../query.js\");\n\n\tconst queryOptions: Record<string, unknown> = {\n\t\twhere: { [taxonomyName]: termSlug },\n\t};\n\tif (options.locale !== undefined) queryOptions.locale = options.locale;\n\tconst { entries } = await getEmDashCollection(collection, queryOptions);\n\treturn entries;\n}\n\nfunction rowToTaxonomyDef(row: {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tlabel_singular: string | null;\n\thierarchical: number;\n\tcollections: string | null;\n\tlocale: string;\n\ttranslation_group: string | null;\n}): 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 * Build tree structure from flat terms\n */\nfunction buildTree(flatTerms: TaxonomyTermRow[], counts: Map<string, number>): TaxonomyTerm[] {\n\t// parent_id holds the parent's translation_group, so link children by it.\n\t// Key by (locale, group): a child's parent lives in the same locale, and an\n\t// unfiltered set 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, TaxonomyTerm>();\n\tconst nodes: TaxonomyTerm[] = [];\n\tconst roots: TaxonomyTerm[] = [];\n\n\tfor (const term of flatTerms) {\n\t\tconst node: TaxonomyTerm = {\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.parent_id ?? undefined,\n\t\t\tdescription: term.data ? JSON.parse(term.data).description : undefined,\n\t\t\tchildren: [],\n\t\t\tcount: counts.get(term.translation_group ?? term.id) ?? 0,\n\t\t\tlocale: term.locale,\n\t\t\ttranslationGroup: term.translation_group,\n\t\t};\n\t\tbyLocaleGroup.set(`${term.locale}::${term.translation_group ?? term.id}`, node);\n\t\tnodes.push(node);\n\t}\n\n\tfor (const node of nodes) {\n\t\tconst parent = node.parentId\n\t\t\t? byLocaleGroup.get(`${node.locale}::${node.parentId}`)\n\t\t\t: undefined;\n\t\tif (parent) {\n\t\t\tparent.children.push(node);\n\t\t} else {\n\t\t\troots.push(node);\n\t\t}\n\t}\n\n\treturn roots;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;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Y,GAAG,EAAE;EAC/D,QAAQ,IAAI;EACZ,kBAAkB,IAAI;EACtB;;;;;AAMF,SAAS,UAAU,WAA8B,QAA6C;CAK7F,MAAM,gCAAgB,IAAI,KAA2B;CACrD,MAAM,QAAwB,EAAE;CAChC,MAAM,QAAwB,EAAE;AAEhC,MAAK,MAAM,QAAQ,WAAW;EAC7B,MAAM,OAAqB;GAC1B,IAAI,KAAK;GACT,MAAM,KAAK;GACX,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,aAAa;GAC5B,aAAa,KAAK,OAAO,KAAK,MAAM,KAAK,KAAK,CAAC,cAAc;GAC7D,UAAU,EAAE;GACZ,OAAO,OAAO,IAAI,KAAK,qBAAqB,KAAK,GAAG,IAAI;GACxD,QAAQ,KAAK;GACb,kBAAkB,KAAK;GACvB;AACD,gBAAc,IAAI,GAAG,KAAK,OAAO,IAAI,KAAK,qBAAqB,KAAK,MAAM,KAAK;AAC/E,QAAM,KAAK,KAAK;;AAGjB,MAAK,MAAM,QAAQ,OAAO;EACzB,MAAM,SAAS,KAAK,WACjB,cAAc,IAAI,GAAG,KAAK,OAAO,IAAI,KAAK,WAAW,GACrD;AACH,MAAI,OACH,QAAO,SAAS,KAAK,KAAK;MAE1B,OAAM,KAAK,KAAK;;AAIlB,QAAO"}
|
|
1
|
+
{"version":3,"file":"taxonomies-Cnb4F-Pb.mjs","names":[],"sources":["../src/taxonomies/index.ts"],"sourcesContent":["/**\n * Runtime API for taxonomies.\n *\n * All helpers are locale-aware. When a locale is not passed explicitly we fall\n * back to the request context or the configured `defaultLocale` (see\n * `i18n/resolve.ts`).\n *\n * Because `content_taxonomies.taxonomy_id` stores the translation_group (not a\n * specific term id), the joins here are `taxonomies.translation_group =\n * content_taxonomies.taxonomy_id` + filter by `taxonomies.locale`, which picks\n * the right per-locale term.\n */\n\nimport { resolveLocale, resolveLocaleChain } from \"../i18n/resolve.js\";\nimport { getDb, resetTaxonomyNamesCache } from \"../loader.js\";\nimport {\n\tcachedQuery,\n\tCacheNamespace,\n\tcontentNamespace,\n\tinvalidateTaxonomyObjectCache,\n\tisObjectCacheActive,\n} from \"../object-cache/index.js\";\nimport { peekRequestCache, requestCached, setRequestCacheEntry } from \"../request-cache.js\";\nimport { getRequestContext } from \"../request-context.js\";\nimport { chunks, SQL_BATCH_SIZE } from \"../utils/chunks.js\";\nimport { isMissingTableError } from \"../utils/db-errors.js\";\nimport type { TaxonomyDef, TaxonomyTerm, TaxonomyTermRow } from \"./types.js\";\n\nexport interface TaxonomyQueryOptions {\n\tlocale?: string;\n}\n\n/** Invalidate cached taxonomy term data and any content that hydrates terms. */\nexport function invalidateTermCache(): void {\n\tinvalidateTaxonomyObjectCache();\n}\n\n/**\n * Worker-isolate cache for taxonomy definitions, keyed by resolved locale.\n *\n * Taxonomy *definitions* (the \"category\"/\"tag\" taxonomies themselves, not\n * their terms) are read on every public render that hydrates entry terms —\n * `getAllTermsForEntries` → `getCollectionTaxonomyNames` → `getTaxonomyDefs` —\n * but change extremely rarely: they're created via the admin API or applied\n * from a seed, and there is no edit/delete-def path. Caching them across the\n * isolate lifetime drops the per-render `SELECT * FROM _emdash_taxonomy_defs`\n * to once-per-isolate.\n *\n * Stored on globalThis behind a Symbol key (same pattern as\n * `settings/index.ts`) so the bundler duplicating this module across SSR\n * chunks can't produce two independent caches.\n *\n * When the distributed object cache is configured, it is authoritative and this\n * fallback is bypassed so cross-isolate epoch invalidation cannot be undercut\n * by stale per-isolate data on an object-cache miss.\n *\n * **Isolated databases bypass the cache.** Playground / DO preview requests\n * set `requestContext.dbIsIsolated`; they point at a divergent schema, so we\n * skip both reading and writing the global holder and fall back to the\n * per-request cache (same precedent as `getTaxonomyNames` / byline field defs).\n */\ninterface TaxonomyDefsHolder {\n\tversion: number;\n\t/** locale key (\"*\" for \"all locales\") → { version it was fetched at, promise }. */\n\tcache: Map<string, { version: number; promise: Promise<TaxonomyDef[]> }>;\n}\n\nconst TAXONOMY_DEFS_CACHE_KEY = Symbol.for(\"emdash:taxonomy-defs\");\nconst taxonomyDefsStore = globalThis as Record<symbol, unknown>;\nconst defsHolder: TaxonomyDefsHolder =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see settings/index.ts)\n\t(taxonomyDefsStore[TAXONOMY_DEFS_CACHE_KEY] as TaxonomyDefsHolder | undefined) ??\n\t(() => {\n\t\tconst h: TaxonomyDefsHolder = { version: 0, cache: new Map() };\n\t\ttaxonomyDefsStore[TAXONOMY_DEFS_CACHE_KEY] = h;\n\t\treturn h;\n\t})();\n\n/**\n * Invalidate the isolate-wide taxonomy-definitions cache (and the related\n * loader taxonomy-names cache). Called from every taxonomy-def write path\n * (`handleTaxonomyCreate`, seed application). Other isolates refresh on their\n * next recycle — staleness bounded by isolate lifetime.\n */\nexport function invalidateTaxonomyDefsCache(): void {\n\tdefsHolder.version++;\n\tdefsHolder.cache.clear();\n\tresetTaxonomyNamesCache();\n\tinvalidateTaxonomyObjectCache();\n}\n\n/**\n * Test/internal helper: clear the per-isolate taxonomy-defs cache. Useful for\n * unit tests that insert defs directly and need to force a refetch without\n * going through a write path. Production code should rely on\n * `invalidateTaxonomyDefsCache()`.\n */\nexport function resetTaxonomyDefsCacheForTests(): void {\n\tdefsHolder.version++;\n\tdefsHolder.cache.clear();\n}\n\n/**\n * Fetch taxonomy definitions straight from the database (no caching).\n */\nasync function fetchTaxonomyDefs(locale: string | undefined): Promise<TaxonomyDef[]> {\n\tconst db = await getDb();\n\tlet query = db.selectFrom(\"_emdash_taxonomy_defs\").selectAll();\n\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\tconst rows = await query.execute();\n\treturn rows.map(rowToTaxonomyDef);\n}\n\n/**\n * Resolve taxonomy defs through the isolate fallback cache, bypassing it for\n * isolated databases. The returned promise is cached (not the resolved value)\n * so concurrent cold-isolate readers share one in-flight query; a rejection\n * evicts the entry so the next caller retries.\n */\nfunction loadTaxonomyDefs(localeKey: string, locale: string | undefined): Promise<TaxonomyDef[]> {\n\tif (getRequestContext()?.dbIsIsolated === true) {\n\t\treturn fetchTaxonomyDefs(locale);\n\t}\n\tconst existing = defsHolder.cache.get(localeKey);\n\tif (existing && existing.version === defsHolder.version) {\n\t\treturn existing.promise;\n\t}\n\tconst version = defsHolder.version;\n\tconst promise = fetchTaxonomyDefs(locale).catch((error: unknown) => {\n\t\tconst current = defsHolder.cache.get(localeKey);\n\t\tif (current && current.promise === promise) {\n\t\t\tdefsHolder.cache.delete(localeKey);\n\t\t}\n\t\tthrow error;\n\t});\n\tdefsHolder.cache.set(localeKey, { version, promise });\n\treturn promise;\n}\n\n/**\n * Get every taxonomy definition. Definitions are per-locale (one row per\n * locale inside the same translation_group) — by default we resolve to the\n * active locale.\n *\n * Two-tier cache: per-request via `requestCached` (so a single render that\n * hydrates terms for several collections pays at most one call), then\n * per-isolate via the global holder (so warm renders issue zero queries).\n * The `requestCached` key is unchanged so `getTaxonomyDef`'s peek still hits.\n */\nexport async function getTaxonomyDefs(options: TaxonomyQueryOptions = {}): Promise<TaxonomyDef[]> {\n\tconst locale = resolveLocale(options.locale);\n\tconst localeKey = locale ?? \"*\";\n\treturn requestCached(`taxonomy-defs:${localeKey}`, async () => {\n\t\tif (await isObjectCacheActive()) {\n\t\t\treturn cachedQuery({\n\t\t\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\t\t\tkey: `defs:${localeKey}`,\n\t\t\t\tload: () => fetchTaxonomyDefs(locale),\n\t\t\t});\n\t\t}\n\t\treturn loadTaxonomyDefs(localeKey, locale);\n\t});\n}\n\n/**\n * Get a single taxonomy definition by name. Uses the fallback chain so even\n * if there is no translation for the active locale we still return something.\n *\n * If `getTaxonomyDefs()` has already loaded the full list in this request\n * (which happens during entry-term hydration on every page that renders a\n * collection), search the matching def in memory rather than running a\n * second query against `_emdash_taxonomy_defs`.\n */\nexport async function getTaxonomyDef(\n\tname: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyDef | null> {\n\tconst chain = resolveLocaleChain(options.locale);\n\tconst peekKey = `taxonomy-defs:${resolveLocale(options.locale) ?? \"*\"}`;\n\tconst allDefs = peekRequestCache<TaxonomyDef[]>(peekKey);\n\tif (allDefs) {\n\t\tconst defs = await allDefs;\n\t\tif (chain.length === 0) return defs.find((d) => d.name === name) ?? null;\n\t\tfor (const locale of chain) {\n\t\t\tconst found = defs.find((d) => d.name === name && d.locale === locale);\n\t\t\tif (found) return found;\n\t\t}\n\t\treturn null;\n\t}\n\n\treturn requestCached(`taxonomy-def:${name}:${chain.join(\",\")}`, async () => {\n\t\tconst db = await getDb();\n\n\t\tif (chain.length === 0) {\n\t\t\tconst row = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"name\", \"=\", name)\n\t\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t\t.executeTakeFirst();\n\t\t\treturn row ? rowToTaxonomyDef(row) : null;\n\t\t}\n\n\t\tfor (const locale of chain) {\n\t\t\tconst row = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"name\", \"=\", name)\n\t\t\t\t.where(\"locale\", \"=\", locale)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (row) return rowToTaxonomyDef(row);\n\t\t}\n\t\treturn null;\n\t});\n}\n\n/**\n * All terms of a taxonomy in a specific locale (flat for non-hierarchical,\n * tree for hierarchical).\n */\nexport async function getTaxonomyTerms(\n\ttaxonomyName: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\treturn requestCached(`taxonomy-terms:${taxonomyName}:${locale ?? \"*\"}`, () =>\n\t\tcachedQuery({\n\t\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\t\tkey: `terms:${taxonomyName}:${locale ?? \"*\"}`,\n\t\t\tload: () => loadTaxonomyTerms(taxonomyName, locale, options),\n\t\t}),\n\t);\n}\n\nasync function loadTaxonomyTerms(\n\ttaxonomyName: string,\n\tlocale: string | undefined,\n\toptions: TaxonomyQueryOptions,\n): Promise<TaxonomyTerm[]> {\n\tconst db = await getDb();\n\n\tconst def = await getTaxonomyDef(taxonomyName, options);\n\tif (!def) return [];\n\n\tlet termsQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t.where(\"name\", \"=\", taxonomyName)\n\t\t.orderBy(\"label\", \"asc\");\n\tif (locale !== undefined) termsQuery = termsQuery.where(\"locale\", \"=\", locale);\n\tconst rows = await termsQuery.execute();\n\n\t// Counts are keyed by translation_group (what the pivot stores) and are\n\t// locale-independent, so the aggregate is shared across every taxonomy\n\t// rendered in this request (Categories + Tags widgets, etc.).\n\tconst counts = await getTaxonomyTermCounts();\n\n\tconst flatTerms: TaxonomyTermRow[] = rows.map((row) => ({\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tlabel: row.label,\n\t\tparent_id: row.parent_id,\n\t\tdata: row.data,\n\t\tlocale: row.locale,\n\t\ttranslation_group: row.translation_group,\n\t}));\n\n\tif (def.hierarchical) return buildTree(flatTerms, counts);\n\n\treturn flatTerms.map((term) => ({\n\t\tid: term.id,\n\t\tname: term.name,\n\t\tslug: term.slug,\n\t\tlabel: term.label,\n\t\tdescription: term.data ? JSON.parse(term.data).description : undefined,\n\t\tchildren: [],\n\t\tcount: counts.get(term.translation_group ?? term.id) ?? 0,\n\t\tlocale: term.locale,\n\t\ttranslationGroup: term.translation_group,\n\t}));\n}\n\n/**\n * Per-translation-group usage counts across all taxonomies, in one aggregate\n * scan of `content_taxonomies`. Counts are locale-independent (the pivot stores\n * translation_group), so a single request-cached entry serves every taxonomy\n * that renders during the request.\n */\nfunction getTaxonomyTermCounts(): Promise<Map<string, number>> {\n\treturn requestCached(\"taxonomy-term-counts\", async () => {\n\t\tconst db = await getDb();\n\t\tconst countsResult = await db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select([\"taxonomy_id\"])\n\t\t\t.select((eb) => eb.fn.count<number>(\"entry_id\").as(\"count\"))\n\t\t\t.groupBy(\"taxonomy_id\")\n\t\t\t.execute();\n\t\tconst counts = new Map<string, number>();\n\t\tfor (const row of countsResult) counts.set(row.taxonomy_id, row.count);\n\t\treturn counts;\n\t});\n}\n\n/**\n * Get a single term by (taxonomy, slug). Honours the fallback chain — if the\n * slug exists in a fallback locale, we return that row (useful for deep-linking\n * to a term page when the translation is missing).\n */\nexport async function getTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm | null> {\n\tconst chain = resolveLocaleChain(options.locale);\n\t// Cached under the shared taxonomies epoch (bumped on any taxonomy / term\n\t// assignment write). The `count` reflects content_taxonomies rows; a stale\n\t// count after a bare content delete is bounded by the entry's TTL.\n\treturn cachedQuery({\n\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\tkey: `term:${taxonomyName}:${slug}:${chain.join(\",\")}`,\n\t\tload: () => loadTerm(taxonomyName, slug, chain),\n\t});\n}\n\nasync function loadTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\tchain: string[],\n): Promise<TaxonomyTerm | null> {\n\tconst db = await getDb();\n\n\tlet row: Awaited<ReturnType<ReturnType<typeof selectTerm>[\"executeTakeFirst\"]>>;\n\tconst selectTerm = () =>\n\t\tdb\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", taxonomyName)\n\t\t\t.where(\"slug\", \"=\", slug);\n\n\tif (chain.length === 0) {\n\t\trow = await selectTerm().orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t} else {\n\t\trow = undefined;\n\t\tfor (const locale of chain) {\n\t\t\trow = await selectTerm().where(\"locale\", \"=\", locale).executeTakeFirst();\n\t\t\tif (row) break;\n\t\t}\n\t}\n\n\tif (!row) return null;\n\n\tlet childrenQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t// Children store the parent's translation_group in parent_id (not a row\n\t\t// id), so a translated parent still owns its children in its own locale.\n\t\t.where(\"parent_id\", \"=\", row.translation_group ?? row.id)\n\t\t.orderBy(\"label\", \"asc\");\n\tconst termLocale = row.locale;\n\tif (termLocale) childrenQuery = childrenQuery.where(\"locale\", \"=\", termLocale);\n\n\t// The usage-count and children queries both depend only on the term row,\n\t// so run them concurrently to save a round trip on remote databases.\n\tconst [countResult, childRows] = await Promise.all([\n\t\tdb\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select((eb) => eb.fn.count<number>(\"entry_id\").as(\"count\"))\n\t\t\t.where(\"taxonomy_id\", \"=\", row.translation_group ?? row.id)\n\t\t\t.executeTakeFirst(),\n\t\tchildrenQuery.execute(),\n\t]);\n\tconst count = countResult?.count ?? 0;\n\n\tconst children = childRows.map<TaxonomyTerm>((child) => ({\n\t\tid: child.id,\n\t\tname: child.name,\n\t\tslug: child.slug,\n\t\tlabel: child.label,\n\t\tparentId: child.parent_id ?? undefined,\n\t\tchildren: [],\n\t\tlocale: child.locale,\n\t\ttranslationGroup: child.translation_group,\n\t}));\n\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tlabel: row.label,\n\t\tparentId: row.parent_id ?? undefined,\n\t\tdescription: row.data ? JSON.parse(row.data).description : undefined,\n\t\tchildren,\n\t\tcount,\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n/**\n * Terms assigned to a content entry, resolved into the active locale. Terms\n * whose translation_group lacks a row in the requested locale are omitted.\n */\nexport function getEntryTerms(\n\tcollection: string,\n\tentryId: string,\n\ttaxonomyName?: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\t// requestCached short-circuits to values primed by getAllTermsForEntries\n\t// during entry hydration (same key shape). On a warm content-cache hit\n\t// hydration doesn't run, so the inner cachedQuery serves this from KV\n\t// instead of falling through to D1 on every request.\n\treturn requestCached(\n\t\t`terms:${collection}:${entryId}:${taxonomyName ?? \"*\"}:${locale ?? \"*\"}`,\n\t\t() =>\n\t\t\tcachedQuery({\n\t\t\t\tnamespace: [contentNamespace(collection), CacheNamespace.TAXONOMIES],\n\t\t\t\tkey: `entryTerms:${collection}:${entryId}:${taxonomyName ?? \"*\"}:${locale ?? \"*\"}`,\n\t\t\t\tload: async () => {\n\t\t\t\t\tconst db = await getDb();\n\n\t\t\t\t\tlet query = db\n\t\t\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t\t\t.innerJoin(\n\t\t\t\t\t\t\t\"taxonomies\",\n\t\t\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t\t\t\t\"content_taxonomies.taxonomy_id\",\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.selectAll(\"taxonomies\")\n\t\t\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryId);\n\n\t\t\t\t\tif (taxonomyName) query = query.where(\"taxonomies.name\", \"=\", taxonomyName);\n\t\t\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\n\t\t\t\t\tconst rows = await query.execute();\n\t\t\t\t\treturn rows.map<TaxonomyTerm>((row) => ({\n\t\t\t\t\t\tid: row.id,\n\t\t\t\t\t\tname: row.name,\n\t\t\t\t\t\tslug: row.slug,\n\t\t\t\t\t\tlabel: row.label,\n\t\t\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\t\t\tchildren: [],\n\t\t\t\t\t\tlocale: row.locale,\n\t\t\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t\t\t}));\n\t\t\t\t},\n\t\t\t}),\n\t);\n}\n\n/**\n * Terms for multiple entries of one taxonomy, single query.\n */\nexport async function getTermsForEntries(\n\tcollection: string,\n\tentryIds: string[],\n\ttaxonomyName: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Map<string, TaxonomyTerm[]>> {\n\tconst uniqueIds = [...new Set(entryIds)];\n\tif (uniqueIds.length === 0) return new Map();\n\tconst locale = resolveLocale(options.locale);\n\tconst localeKey = locale ?? \"*\";\n\n\t// The query result is a Map, which JSON can't represent — cache it as an\n\t// array of [entryId, terms] pairs and rebuild the Map on read.\n\tconst load = async (): Promise<Array<[string, TaxonomyTerm[]]>> => {\n\t\tconst result = new Map<string, TaxonomyTerm[]>();\n\t\tfor (const id of uniqueIds) result.set(id, []);\n\n\t\t// Entry-term hydration (getAllTermsForEntries -> primeEntryTermsCache)\n\t\t// seeds the per-entry cache under the same key getEntryTerms uses:\n\t\t// `terms:${collection}:${entryId}:${taxonomyName}:${localeKey}`, storing a\n\t\t// TaxonomyTerm[] (including `[]` for entries with no terms). Satisfy those\n\t\t// from cache and run the batched query only for the ids that missed.\n\t\tconst missedIds: string[] = [];\n\t\ttype CacheRead = { id: string; terms: TaxonomyTerm[] } | { id: string; miss: true };\n\t\tconst cacheReads: Array<Promise<CacheRead>> = [];\n\t\tfor (const id of uniqueIds) {\n\t\t\tconst cached = peekRequestCache<TaxonomyTerm[]>(\n\t\t\t\t`terms:${collection}:${id}:${taxonomyName}:${localeKey}`,\n\t\t\t);\n\t\t\tif (cached) {\n\t\t\t\t// A peeked promise can reject (e.g. a sibling getEntryTerms hit a\n\t\t\t\t// missing table). Treat a rejection as a cache miss so the batched\n\t\t\t\t// query path -- and its isMissingTableError guard below -- still runs,\n\t\t\t\t// rather than propagating an uncaught error.\n\t\t\t\tcacheReads.push(\n\t\t\t\t\tcached.then(\n\t\t\t\t\t\t(terms): CacheRead => ({ id, terms }),\n\t\t\t\t\t\t(): CacheRead => ({ id, miss: true }),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmissedIds.push(id);\n\t\t\t}\n\t\t}\n\t\tfor (const read of await Promise.all(cacheReads)) {\n\t\t\tif (\"miss\" in read) {\n\t\t\t\tmissedIds.push(read.id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Return a private copy. The cached array and its term objects are shared\n\t\t\t// with getEntryTerms/getAllTermsForEntries (primeEntryTermsCache stores\n\t\t\t// the same references), so a caller that mutates the result -- sorting in\n\t\t\t// place, pushing into `children` -- must not poison the cache. The\n\t\t\t// pre-cache implementation always returned freshly built arrays.\n\t\t\tresult.set(\n\t\t\t\tread.id,\n\t\t\t\tread.terms.map((t) => ({ ...t, children: [...t.children] })),\n\t\t\t);\n\t\t}\n\n\t\tif (missedIds.length === 0) return [...result.entries()];\n\n\t\tconst db = await getDb();\n\t\tfor (const chunk of chunks(missedIds, SQL_BATCH_SIZE)) {\n\t\t\tlet rows;\n\t\t\ttry {\n\t\t\t\tlet query = db\n\t\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t\t\t.select([\n\t\t\t\t\t\t\"content_taxonomies.entry_id\",\n\t\t\t\t\t\t\"taxonomies.id\",\n\t\t\t\t\t\t\"taxonomies.name\",\n\t\t\t\t\t\t\"taxonomies.slug\",\n\t\t\t\t\t\t\"taxonomies.label\",\n\t\t\t\t\t\t\"taxonomies.parent_id\",\n\t\t\t\t\t\t\"taxonomies.locale\",\n\t\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t\t])\n\t\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t\t.where(\"content_taxonomies.entry_id\", \"in\", chunk)\n\t\t\t\t\t.where(\"taxonomies.name\", \"=\", taxonomyName)\n\t\t\t\t\t// Match the order getAllTermsForEntries (the cache primer) uses, so\n\t\t\t\t\t// cache-hit and DB-miss entries in one result are ordered consistently.\n\t\t\t\t\t.orderBy(\"taxonomies.label\", \"asc\");\n\t\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\t\t\t\trows = await query.execute();\n\t\t\t} catch (error) {\n\t\t\t\tif (isMissingTableError(error)) return [...result.entries()];\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst term: TaxonomyTerm = {\n\t\t\t\t\tid: row.id,\n\t\t\t\t\tname: row.name,\n\t\t\t\t\tslug: row.slug,\n\t\t\t\t\tlabel: row.label,\n\t\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\t\tchildren: [],\n\t\t\t\t\tlocale: row.locale,\n\t\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t\t};\n\t\t\t\tconst terms = result.get(row.entry_id);\n\t\t\t\tif (terms) terms.push(term);\n\t\t\t}\n\t\t}\n\n\t\treturn [...result.entries()];\n\t};\n\n\t// Key on the sorted unique ids. Bound the key length: very large batches\n\t// (rare; they come from collection hydration, already served by the content\n\t// cache) bypass the object cache rather than blow past KV's key limit.\n\tconst idKey = uniqueIds.toSorted().join(\",\");\n\tconst pairs =\n\t\tidKey.length <= 256\n\t\t\t? await cachedQuery({\n\t\t\t\t\tnamespace: [contentNamespace(collection), CacheNamespace.TAXONOMIES],\n\t\t\t\t\tkey: `termsForEntries:${collection}:${taxonomyName}:${locale ?? \"*\"}:${idKey}`,\n\t\t\t\t\tload,\n\t\t\t\t})\n\t\t\t: await load();\n\n\treturn new Map(pairs);\n}\n\n/**\n * Batch-fetch terms for multiple entries across ALL taxonomies in one query.\n * Primes the request-cache for subsequent per-entry calls to `getEntryTerms`.\n */\nexport async function getAllTermsForEntries(\n\tcollection: string,\n\tentryIds: string[],\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Map<string, Record<string, TaxonomyTerm[]>>> {\n\tconst result = new Map<string, Record<string, TaxonomyTerm[]>>();\n\tconst uniqueIds = [...new Set(entryIds)];\n\tfor (const id of uniqueIds) result.set(id, {});\n\tif (uniqueIds.length === 0) return result;\n\n\tconst db = await getDb();\n\tconst locale = resolveLocale(options.locale);\n\tconst applicableTaxonomyNames = await getCollectionTaxonomyNames(collection, { locale });\n\n\tfor (const chunk of chunks(uniqueIds, SQL_BATCH_SIZE)) {\n\t\tlet rows;\n\t\ttry {\n\t\t\tlet query = db\n\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t\t.select([\n\t\t\t\t\t\"content_taxonomies.entry_id\",\n\t\t\t\t\t\"taxonomies.id\",\n\t\t\t\t\t\"taxonomies.name\",\n\t\t\t\t\t\"taxonomies.slug\",\n\t\t\t\t\t\"taxonomies.label\",\n\t\t\t\t\t\"taxonomies.parent_id\",\n\t\t\t\t\t\"taxonomies.locale\",\n\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t])\n\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t.where(\"content_taxonomies.entry_id\", \"in\", chunk)\n\t\t\t\t.orderBy(\"taxonomies.label\", \"asc\");\n\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\t\t\trows = await query.execute();\n\t\t} catch (error) {\n\t\t\tif (isMissingTableError(error)) {\n\t\t\t\tfor (const id of uniqueIds) {\n\t\t\t\t\tprimeEntryTermsCache(collection, id, {}, applicableTaxonomyNames, locale);\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\tfor (const row of rows) {\n\t\t\tconst term: TaxonomyTerm = {\n\t\t\t\tid: row.id,\n\t\t\t\tname: row.name,\n\t\t\t\tslug: row.slug,\n\t\t\t\tlabel: row.label,\n\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\tchildren: [],\n\t\t\t\tlocale: row.locale,\n\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t};\n\t\t\tconst byTaxonomy = result.get(row.entry_id);\n\t\t\tif (!byTaxonomy) continue;\n\t\t\tconst existing = byTaxonomy[row.name];\n\t\t\tif (existing) existing.push(term);\n\t\t\telse byTaxonomy[row.name] = [term];\n\t\t}\n\t}\n\n\tfor (const [entryId, byTaxonomy] of result) {\n\t\tprimeEntryTermsCache(collection, entryId, byTaxonomy, applicableTaxonomyNames, locale);\n\t}\n\n\treturn result;\n}\n\n/**\n * Return the list of taxonomy names applicable to a collection, request-\n * cached so a page render only pays for it once.\n *\n * Returns an empty list when taxonomies haven't been defined yet.\n */\nasync function getCollectionTaxonomyNames(\n\tcollection: string,\n\toptions: TaxonomyQueryOptions,\n): Promise<string[]> {\n\ttry {\n\t\tconst defs = await getTaxonomyDefs(options);\n\t\treturn defs.filter((d) => d.collections.includes(collection)).map((d) => d.name);\n\t} catch (error) {\n\t\tif (isMissingTableError(error)) return [];\n\t\tthrow error;\n\t}\n}\n\n/**\n * Pre-populate the request-cache for every getEntryTerms call-shape that\n * could hit this entry:\n *\n * getEntryTerms(collection, entryId) -> key `terms:C:E:*`\n * getEntryTerms(collection, entryId, \"tag\") -> key `terms:C:E:tag`\n * getEntryTerms(collection, entryId, \"category\") -> key `terms:C:E:category`\n * ...one per taxonomy that applies to this collection\n *\n * Taxonomies with no rows on this entry are seeded with `[]` so legacy\n * callers short-circuit to the cached empty array instead of re-querying.\n */\nfunction primeEntryTermsCache(\n\tcollection: string,\n\tentryId: string,\n\tbyTaxonomy: Record<string, TaxonomyTerm[]>,\n\tapplicableTaxonomyNames: string[],\n\tlocale: string | undefined,\n): void {\n\tconst localeKey = locale ?? \"*\";\n\tfor (const name of applicableTaxonomyNames) {\n\t\tsetRequestCacheEntry(\n\t\t\t`terms:${collection}:${entryId}:${name}:${localeKey}`,\n\t\t\tbyTaxonomy[name] ?? [],\n\t\t);\n\t}\n\tfor (const [name, terms] of Object.entries(byTaxonomy)) {\n\t\tsetRequestCacheEntry(`terms:${collection}:${entryId}:${name}:${localeKey}`, terms);\n\t}\n\tconst allTerms = Object.values(byTaxonomy).flat();\n\tsetRequestCacheEntry(`terms:${collection}:${entryId}:*:${localeKey}`, allTerms);\n}\n\n/**\n * Prime the per-entry request cache from terms that were folded into the\n * content query (query.ts `hydrateEntryTerms` fast path), so subsequent\n * `getEntryTerms` calls in the same render hit the cache instead of issuing an\n * N+1 query. Seeds the wildcard key and one key per taxonomy present on the\n * entry — purely from the folded data, with no DB lookup.\n *\n * Unlike `getAllTermsForEntries`, this deliberately does NOT seed `[]` for\n * taxonomies that apply to the collection but have no rows on the entry: doing\n * so would require a `getTaxonomyDefs` query, adding a round trip to every fold\n * render to serve the rarer `getEntryTerms(id, absentTaxonomy)` case from cache.\n * That call simply falls through to its own cached query. Keeping the key shape\n * here (rather than in query.ts) prevents the two from drifting.\n */\nexport function primeFoldedEntryTerms(\n\tcollection: string,\n\tperEntry: Array<{ entryId: string; byTaxonomy: Record<string, TaxonomyTerm[]> }>,\n\toptions: TaxonomyQueryOptions = {},\n): void {\n\tif (perEntry.length === 0) return;\n\tconst locale = resolveLocale(options.locale);\n\tfor (const { entryId, byTaxonomy } of perEntry) {\n\t\tprimeEntryTermsCache(collection, entryId, byTaxonomy, [], locale);\n\t}\n}\n\n/**\n * Get entries by term. Both the lookup (term slug in the active locale) and\n * the content query respect the active locale.\n */\nexport async function getEntriesByTerm(\n\tcollection: string,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Array<{ id: string; data: Record<string, unknown> }>> {\n\tconst { getEmDashCollection } = await import(\"../query.js\");\n\n\tconst queryOptions: Record<string, unknown> = {\n\t\twhere: { [taxonomyName]: termSlug },\n\t};\n\tif (options.locale !== undefined) queryOptions.locale = options.locale;\n\tconst { entries } = await getEmDashCollection(collection, queryOptions);\n\treturn entries;\n}\n\nfunction rowToTaxonomyDef(row: {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tlabel_singular: string | null;\n\thierarchical: number;\n\tcollections: string | null;\n\tlocale: string;\n\ttranslation_group: string | null;\n}): 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 * Build tree structure from flat terms\n */\nfunction buildTree(flatTerms: TaxonomyTermRow[], counts: Map<string, number>): TaxonomyTerm[] {\n\t// parent_id holds the parent's translation_group, so link children by it.\n\t// Key by (locale, group): a child's parent lives in the same locale, and an\n\t// unfiltered set 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, TaxonomyTerm>();\n\tconst nodes: TaxonomyTerm[] = [];\n\tconst roots: TaxonomyTerm[] = [];\n\n\tfor (const term of flatTerms) {\n\t\tconst node: TaxonomyTerm = {\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.parent_id ?? undefined,\n\t\t\tdescription: term.data ? JSON.parse(term.data).description : undefined,\n\t\t\tchildren: [],\n\t\t\tcount: counts.get(term.translation_group ?? term.id) ?? 0,\n\t\t\tlocale: term.locale,\n\t\t\ttranslationGroup: term.translation_group,\n\t\t};\n\t\tbyLocaleGroup.set(`${term.locale}::${term.translation_group ?? term.id}`, node);\n\t\tnodes.push(node);\n\t}\n\n\tfor (const node of nodes) {\n\t\tconst parent = node.parentId\n\t\t\t? byLocaleGroup.get(`${node.locale}::${node.parentId}`)\n\t\t\t: undefined;\n\t\tif (parent) {\n\t\t\tparent.children.push(node);\n\t\t} else {\n\t\t\troots.push(node);\n\t\t}\n\t}\n\n\treturn roots;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,sBAA4B;AAC3C,gCAA+B;;AAiChC,MAAM,0BAA0B,OAAO,IAAI,uBAAuB;AAClE,MAAM,oBAAoB;AAC1B,MAAM,aAEJ,kBAAkB,mCACZ;CACN,MAAM,I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AwB,EAAE;AAEhC,MAAK,MAAM,QAAQ,WAAW;EAC7B,MAAM,OAAqB;GAC1B,IAAI,KAAK;GACT,MAAM,KAAK;GACX,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,aAAa;GAC5B,aAAa,KAAK,OAAO,KAAK,MAAM,KAAK,KAAK,CAAC,cAAc;GAC7D,UAAU,EAAE;GACZ,OAAO,OAAO,IAAI,KAAK,qBAAqB,KAAK,GAAG,IAAI;GACxD,QAAQ,KAAK;GACb,kBAAkB,KAAK;GACvB;AACD,gBAAc,IAAI,GAAG,KAAK,OAAO,IAAI,KAAK,qBAAqB,KAAK,MAAM,KAAK;AAC/E,QAAM,KAAK,KAAK;;AAGjB,MAAK,MAAM,QAAQ,OAAO;EACzB,MAAM,SAAS,KAAK,WACjB,cAAc,IAAI,GAAG,KAAK,OAAO,IAAI,KAAK,WAAW,GACrD;AACH,MAAI,OACH,QAAO,SAAS,KAAK,KAAK;MAE1B,OAAM,KAAK,KAAK;;AAIlB,QAAO"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as __exportAll } from "./runner-
|
|
2
|
-
import { d as invalidateTaxonomyObjectCache } from "./object-cache-
|
|
1
|
+
import { a as __exportAll } from "./runner-K8XK101B.mjs";
|
|
2
|
+
import { d as invalidateTaxonomyObjectCache } from "./object-cache-Bok5j2ae.mjs";
|
|
3
3
|
import { ulid } from "ulidx";
|
|
4
4
|
|
|
5
5
|
//#region src/database/repositories/taxonomy.ts
|
|
@@ -230,7 +230,7 @@ var TaxonomyRepository = class {
|
|
|
230
230
|
*/
|
|
231
231
|
async countEntriesForTerms(translationGroups) {
|
|
232
232
|
if (translationGroups.length === 0) return /* @__PURE__ */ new Map();
|
|
233
|
-
const { chunks, SQL_BATCH_SIZE } = await import("./chunks-
|
|
233
|
+
const { chunks, SQL_BATCH_SIZE } = await import("./chunks-B2isWQhr.mjs").then((n) => n.r);
|
|
234
234
|
const counts = /* @__PURE__ */ new Map();
|
|
235
235
|
for (const chunk of chunks(translationGroups, SQL_BATCH_SIZE)) {
|
|
236
236
|
const rows = await this.db.selectFrom("content_taxonomies").select(["taxonomy_id", (eb) => eb.fn.count("entry_id").as("count")]).where("taxonomy_id", "in", chunk).groupBy("taxonomy_id").execute();
|
|
@@ -254,4 +254,4 @@ var TaxonomyRepository = class {
|
|
|
254
254
|
|
|
255
255
|
//#endregion
|
|
256
256
|
export { taxonomy_exports as n, TaxonomyRepository as t };
|
|
257
|
-
//# sourceMappingURL=taxonomy-
|
|
257
|
+
//# sourceMappingURL=taxonomy-BxGxZZdu.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"taxonomy-Cru-he6s.mjs","names":[],"sources":["../src/database/repositories/taxonomy.ts"],"sourcesContent":["import type { Kysely, Selectable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { invalidateTaxonomyObjectCache } from \"../../object-cache/index.js\";\nimport type { Database, TaxonomyTable, ContentTaxonomyTable } from \"../types.js\";\n\nexport interface Taxonomy {\n\tid: string;\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparentId: string | null;\n\tdata: Record<string, unknown> | null;\n\tlocale: string;\n\ttranslationGroup: string | null;\n}\n\nexport interface CreateTaxonomyInput {\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparentId?: string;\n\tdata?: Record<string, unknown>;\n\t/** Omit to let the DB default (current value: 'en') apply. Higher layers\n\t * resolve the locale from the request context / i18n config. */\n\tlocale?: string;\n\t/** When set, links the new term into the source term's translation_group. */\n\ttranslationOf?: string;\n}\n\nexport interface UpdateTaxonomyInput {\n\tslug?: string;\n\tlabel?: string;\n\tparentId?: string | null;\n\tdata?: Record<string, unknown>;\n}\n\nexport interface FindOptions {\n\tparentId?: string | null;\n\tlocale?: string;\n}\n\n/**\n * Taxonomy repository for categories, tags, and other classification.\n *\n * Terms are per-locale. Translations of the same term share a `translation_group`\n * ULID. `content_taxonomies.taxonomy_id` stores the translation_group so a single\n * association spans every locale of a post.\n *\n * The repository does not resolve locale fallbacks on its own — callers supply\n * the locale they want. Runtime helpers and handlers use `getFallbackChain()`\n * from `i18n/config` when they need fallback behaviour.\n */\nexport class TaxonomyRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Create a new taxonomy term. When `translationOf` is set the new row joins\n\t * the source term's translation_group; otherwise a fresh group is minted\n\t * (matching the migration backfill pattern `translation_group = id`).\n\t */\n\tasync create(input: CreateTaxonomyInput): Promise<Taxonomy> {\n\t\tconst id = ulid();\n\n\t\t// Empty-string parentId is coerced to null defensively. Higher layers\n\t\t// also normalize this — see handleTermCreate / handleTermUpdate.\n\t\t// `parent_id` stores the parent's locale-agnostic translation_group (not a\n\t\t// row id), mirroring content_taxonomies.taxonomy_id, so a child stays\n\t\t// nested in every locale's tree. resolveTranslationGroup accepts either a\n\t\t// row id or an already-resolved group, so this is idempotent.\n\t\tconst parentInput =\n\t\t\tinput.parentId === undefined || input.parentId === \"\" ? null : input.parentId;\n\t\tconst parentId = parentInput ? await this.resolveParentRef(parentInput) : null;\n\n\t\tlet translationGroup = id;\n\t\tif (input.translationOf) {\n\t\t\tconst source = await this.findById(input.translationOf);\n\t\t\tif (source?.translationGroup) translationGroup = source.translationGroup;\n\t\t}\n\n\t\tawait this.db\n\t\t\t.insertInto(\"taxonomies\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tname: input.name,\n\t\t\t\tslug: input.slug,\n\t\t\t\tlabel: input.label,\n\t\t\t\tparent_id: parentId,\n\t\t\t\tdata: input.data ? JSON.stringify(input.data) : null,\n\t\t\t\t// When omitted, the DB DEFAULT 'en' is used — keeps behaviour\n\t\t\t\t// consistent with ContentRepository and lets higher layers\n\t\t\t\t// supply an explicit locale from request context.\n\t\t\t\t...(input.locale !== undefined ? { locale: input.locale } : {}),\n\t\t\t\ttranslation_group: translationGroup,\n\t\t\t})\n\t\t\t.execute();\n\n\t\tinvalidateTaxonomyObjectCache();\n\n\t\tconst taxonomy = await this.findById(id);\n\t\tif (!taxonomy) throw new Error(\"Failed to create taxonomy\");\n\t\treturn taxonomy;\n\t}\n\n\tasync findById(id: string): Promise<Taxonomy | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? this.rowToTaxonomy(row) : null;\n\t}\n\n\t/**\n\t * Find a term by (name, slug). When `locale` is provided, filter by it.\n\t * When omitted, returns the lowest-locale-code match (deterministic across\n\t * calls). Mirrors `ContentRepository.findBySlug`.\n\t */\n\tasync findBySlug(name: string, slug: string, locale?: string): Promise<Taxonomy | null> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.where(\"slug\", \"=\", slug);\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst row = await query.orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t\treturn row ? this.rowToTaxonomy(row) : null;\n\t}\n\n\t/**\n\t * Get all terms for a taxonomy (e.g., all categories).\n\t *\n\t * `id asc` is a stable tiebreaker for terms that share a label. Without it\n\t * the SQL ordering is implementation-defined when labels match, which\n\t * breaks keyset pagination over `(label, id)`.\n\t */\n\tasync findByName(name: string, options: FindOptions = {}): Promise<Taxonomy[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.orderBy(\"label\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\n\t\tif (options.locale !== undefined) query = query.where(\"locale\", \"=\", options.locale);\n\n\t\tif (options.parentId !== undefined) {\n\t\t\tif (options.parentId === null) {\n\t\t\t\tquery = query.where(\"parent_id\", \"is\", null);\n\t\t\t} else {\n\t\t\t\tquery = query.where(\"parent_id\", \"=\", options.parentId);\n\t\t\t}\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\t/**\n\t * Children of a term. Accepts a term id OR a translation_group and resolves\n\t * to the group, since `parent_id` stores the parent's translation_group.\n\t * Pass `locale` to scope to one locale's tree (children share the parent's\n\t * group across locales); omit it to find children in every locale (used to\n\t * block deletes that would orphan a sibling translation's subtree).\n\t */\n\tasync findChildren(parentIdOrGroup: string, locale?: string): Promise<Taxonomy[]> {\n\t\tconst group = await this.resolveTranslationGroup(parentIdOrGroup);\n\t\tif (!group) return [];\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"parent_id\", \"=\", group)\n\t\t\t.orderBy(\"label\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\t/**\n\t * Every translation sibling of a term (including itself), identified by\n\t * their shared `translation_group`.\n\t */\n\tasync findTranslations(translationGroup: string): Promise<Taxonomy[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", translationGroup)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\tasync update(id: string, input: UpdateTaxonomyInput): Promise<Taxonomy | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return null;\n\n\t\tconst updates: Record<string, unknown> = {};\n\t\tif (input.slug !== undefined) updates.slug = input.slug;\n\t\tif (input.label !== undefined) updates.label = input.label;\n\t\tif (input.parentId !== undefined) {\n\t\t\t// Defense in depth: empty-string parentId means null (no parent).\n\t\t\t// Otherwise persist the parent's translation_group (locale-agnostic),\n\t\t\t// matching create() — see the note there.\n\t\t\tupdates.parent_id =\n\t\t\t\tinput.parentId === \"\" || input.parentId === null\n\t\t\t\t\t? null\n\t\t\t\t\t: await this.resolveParentRef(input.parentId);\n\t\t}\n\t\tif (input.data !== undefined) updates.data = JSON.stringify(input.data);\n\n\t\tif (Object.keys(updates).length > 0) {\n\t\t\tawait this.db.updateTable(\"taxonomies\").set(updates).where(\"id\", \"=\", id).execute();\n\t\t\tinvalidateTaxonomyObjectCache();\n\t\t}\n\n\t\treturn this.findById(id);\n\t}\n\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst term = await this.findById(id);\n\t\tif (!term) return false;\n\n\t\t// When deleting the last translation of a group the pivot rows that\n\t\t// reference that translation_group become orphaned — purge them.\n\t\tif (term.translationGroup) {\n\t\t\tconst siblings = await this.db\n\t\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t\t.select(\"id\")\n\t\t\t\t.where(\"translation_group\", \"=\", term.translationGroup)\n\t\t\t\t.where(\"id\", \"!=\", id)\n\t\t\t\t.execute();\n\t\t\tif (siblings.length === 0) {\n\t\t\t\tawait this.db\n\t\t\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t\t\t.where(\"taxonomy_id\", \"=\", term.translationGroup)\n\t\t\t\t\t.execute();\n\t\t\t}\n\t\t}\n\n\t\tconst result = await this.db.deleteFrom(\"taxonomies\").where(\"id\", \"=\", id).executeTakeFirst();\n\t\tinvalidateTaxonomyObjectCache();\n\t\treturn (result.numDeletedRows ?? 0n) > 0n;\n\t}\n\n\t// --- Content-Taxonomy Junction (taxonomy_id stores the translation_group) ---\n\n\tasync attachToEntry(collection: string, entryId: string, taxonomyId: string): Promise<void> {\n\t\tconst group = await this.resolveTranslationGroup(taxonomyId);\n\t\tif (!group) return;\n\n\t\tconst row: ContentTaxonomyTable = {\n\t\t\tcollection,\n\t\t\tentry_id: entryId,\n\t\t\ttaxonomy_id: group,\n\t\t};\n\t\tawait this.db\n\t\t\t.insertInto(\"content_taxonomies\")\n\t\t\t.values(row)\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.execute();\n\t\tinvalidateTaxonomyObjectCache();\n\t}\n\n\tasync detachFromEntry(collection: string, entryId: string, taxonomyId: string): Promise<void> {\n\t\tconst group = await this.resolveTranslationGroup(taxonomyId);\n\t\tif (!group) return;\n\n\t\tawait this.db\n\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t.where(\"taxonomy_id\", \"=\", group)\n\t\t\t.execute();\n\t\tinvalidateTaxonomyObjectCache();\n\t}\n\n\t/**\n\t * Taxonomy terms assigned to a content entry, resolved into a specific locale.\n\t * Terms whose translation_group lacks a row in the requested locale are\n\t * omitted — callers wanting fallback behaviour apply it themselves.\n\t */\n\tasync getTermsForEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\ttaxonomyName?: string,\n\t\tlocale?: string,\n\t): Promise<Taxonomy[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t.selectAll(\"taxonomies\")\n\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryId);\n\n\t\tif (taxonomyName) query = query.where(\"taxonomies.name\", \"=\", taxonomyName);\n\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\n\t\tconst rows = await query.orderBy(\"taxonomies.locale\", \"asc\").execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\t/**\n\t * Replace all assignments of a given taxonomy for one content entry.\n\t * Term ids OR translation_groups are accepted and normalised to groups.\n\t */\n\tasync setTermsForEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\ttaxonomyName: string,\n\t\ttermIds: string[],\n\t): Promise<void> {\n\t\tconst groups: string[] = [];\n\t\tfor (const id of termIds) {\n\t\t\tconst group = await this.resolveTranslationGroup(id);\n\t\t\tif (group) groups.push(group);\n\t\t}\n\t\tconst newGroups = new Set(groups);\n\n\t\tconst current = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t.select([\"content_taxonomies.taxonomy_id as group\"])\n\t\t\t.distinct()\n\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryId)\n\t\t\t.where(\"taxonomies.name\", \"=\", taxonomyName)\n\t\t\t.execute();\n\t\tconst currentGroups = new Set(current.map((r) => r.group));\n\n\t\tconst toRemove = [...currentGroups].filter((g) => !newGroups.has(g));\n\t\tif (toRemove.length > 0) {\n\t\t\tawait this.db\n\t\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t\t.where(\"taxonomy_id\", \"in\", toRemove)\n\t\t\t\t.execute();\n\t\t}\n\n\t\tconst toAdd = [...newGroups].filter((g) => !currentGroups.has(g));\n\t\tif (toAdd.length > 0) {\n\t\t\tawait this.db\n\t\t\t\t.insertInto(\"content_taxonomies\")\n\t\t\t\t.values(\n\t\t\t\t\ttoAdd.map((taxonomy_id) => ({\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tentry_id: entryId,\n\t\t\t\t\t\ttaxonomy_id,\n\t\t\t\t\t})),\n\t\t\t\t)\n\t\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t\t.execute();\n\t\t}\n\n\t\tif (toRemove.length > 0 || toAdd.length > 0) invalidateTaxonomyObjectCache();\n\t}\n\n\tasync clearEntryTerms(collection: string, entryId: string): Promise<number> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t.executeTakeFirst();\n\t\tconst removed = Number(result.numDeletedRows ?? 0);\n\t\tif (removed > 0) invalidateTaxonomyObjectCache();\n\t\treturn removed;\n\t}\n\n\t/**\n\t * Copy every term assignment from one content entry to another. Used when\n\t * creating a translation of a post so the new translation inherits the\n\t * source's term assignments. Safe to call when the source has no terms.\n\t */\n\tasync copyEntryTerms(\n\t\tcollection: string,\n\t\tsourceEntryId: string,\n\t\ttargetEntryId: string,\n\t): Promise<void> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select([\"taxonomy_id\"])\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", sourceEntryId)\n\t\t\t.execute();\n\t\tif (rows.length === 0) return;\n\n\t\tawait this.db\n\t\t\t.insertInto(\"content_taxonomies\")\n\t\t\t.values(\n\t\t\t\trows.map((r) => ({\n\t\t\t\t\tcollection,\n\t\t\t\t\tentry_id: targetEntryId,\n\t\t\t\t\ttaxonomy_id: r.taxonomy_id,\n\t\t\t\t})),\n\t\t\t)\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.execute();\n\t\tinvalidateTaxonomyObjectCache();\n\t}\n\n\t/**\n\t * Count content entries that use any translation of this term. Accepts\n\t * either a term id or a translation_group — we normalise to the group.\n\t */\n\tasync countEntriesWithTerm(termIdOrGroup: string): Promise<number> {\n\t\tconst group = await this.resolveTranslationGroup(termIdOrGroup);\n\t\tif (!group) return 0;\n\n\t\tconst result = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select((eb) => eb.fn.count(\"entry_id\").as(\"count\"))\n\t\t\t.where(\"taxonomy_id\", \"=\", group)\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/**\n\t * Resolve a parent reference (a row id or a translation_group) to the value\n\t * persisted in `parent_id`: the parent's translation_group, which is\n\t * locale-agnostic so the child stays nested in every locale. A\n\t * translation_group normally equals its anchor row's id, which satisfies the\n\t * self-FK on `parent_id`. If that anchor row is missing (a translation whose\n\t * anchor was deleted), fall back to the id we were given so we never write a\n\t * dangling FK value.\n\t */\n\tprivate async resolveParentRef(idOrGroup: string): Promise<string> {\n\t\tconst group = await this.resolveTranslationGroup(idOrGroup);\n\t\tif (!group) return idOrGroup;\n\t\tconst anchor = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"id\", \"=\", group)\n\t\t\t.executeTakeFirst();\n\t\treturn anchor ? group : idOrGroup;\n\t}\n\n\tprivate async resolveTranslationGroup(idOrGroup: string): Promise<string | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.select([\"translation_group\"])\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\treturn row?.translation_group ?? null;\n\t}\n\n\t/**\n\t * Batch count entries for multiple taxonomy translation_groups.\n\t * Chunks the query at SQL_BATCH_SIZE to stay below D1's bind-parameter limit.\n\t * Returns a Map from translation_group to count.\n\t *\n\t * Pass translation_groups (not term ids) — `content_taxonomies.taxonomy_id`\n\t * stores the translation_group so a single assignment spans every locale.\n\t */\n\tasync countEntriesForTerms(translationGroups: string[]): Promise<Map<string, number>> {\n\t\tif (translationGroups.length === 0) return new Map();\n\n\t\tconst { chunks, SQL_BATCH_SIZE } = await import(\"../../utils/chunks.js\");\n\n\t\tconst counts = new Map<string, number>();\n\t\tfor (const chunk of chunks(translationGroups, SQL_BATCH_SIZE)) {\n\t\t\tconst rows = await this.db\n\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t.select([\"taxonomy_id\", (eb) => eb.fn.count(\"entry_id\").as(\"count\")])\n\t\t\t\t.where(\"taxonomy_id\", \"in\", chunk)\n\t\t\t\t.groupBy(\"taxonomy_id\")\n\t\t\t\t.execute();\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tcounts.set(row.taxonomy_id, Number(row.count || 0));\n\t\t\t}\n\t\t}\n\t\treturn counts;\n\t}\n\n\tprivate rowToTaxonomy(row: Selectable<TaxonomyTable>): Taxonomy {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\tname: row.name,\n\t\t\tslug: row.slug,\n\t\t\tlabel: row.label,\n\t\t\tparentId: row.parent_id,\n\t\t\tdata: row.data ? JSON.parse(row.data) : null,\n\t\t\tlocale: row.locale,\n\t\t\ttranslationGroup: row.translation_group,\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqDA,IAAa,qBAAb,MAAgC;CAC/B,YAAY,AAAQ,IAAsB;EAAtB;;;;;;;CAOpB,MAAM,OAAO,OAA+C;EAC3D,MAAM,KAAK,MAAM;EAQjB,MAAM,cACL,MAAM,aAAa,UAAa,MAAM,aAAa,KAAK,OAAO,MAAM;EACtE,MAAM,WAAW,cAAc,MAAM,KAAK,iBAAiB,YAAY,GAAG;EAE1E,IAAI,mBAAmB;AACvB,MAAI,MAAM,eAAe;GACxB,MAAM,SAAS,MAAM,KAAK,SAAS,MAAM,cAAc;AACvD,OAAI,QAAQ,iBAAkB,oBAAmB,OAAO;;AAGzD,QAAM,KAAK,GACT,WAAW,aAAa,CACxB,OAAO;GACP;GACA,MAAM,MAAM;GACZ,MAAM,MAAM;GACZ,OAAO,MAAM;GACb,WAAW;GACX,MAAM,MAAM,OAAO,KAAK,UAAU,MAAM,KAAK,GAAG;GAIhD,GAAI,MAAM,WAAW,SAAY,EAAE,QAAQ,MAAM,QAAQ,GAAG,EAAE;GAC9D,mBAAmB;GACnB,CAAC,CACD,SAAS;AAEX,iCAA+B;EAE/B,MAAM,WAAW,MAAM,KAAK,SAAS,GAAG;AACxC,MAAI,CAAC,SAAU,OAAM,IAAI,MAAM,4BAA4B;AAC3D,SAAO;;CAGR,MAAM,SAAS,IAAsC;EACpD,MAAM,MAAM,MAA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,CAAC,CACzF,kBAAkB,GACR,qBAAqB;;;;;;;;;;CAWlC,MAAM,qBAAqB,mBAA2D;AACrF,MAAI,kBAAkB,WAAW,EAAG,wBAAO,IAAI,KAAK;EAEpD,MAAM,EAAE,QAAQ,mBAAmB,MAAM,OAAO;EAEhD,MAAM,yBAAS,IAAI,KAAqB;AACxC,OAAK,MAAM,SAAS,OAAO,mBAAmB,eAAe,EAAE;GAC9D,MAAM,OAAO,MAAM,KAAK,GACtB,WAAW,qBAAqB,CAChC,OAAO,CAAC,gBAAgB,OAAO,GAAG,GAAG,MAAM,WAAW,CAAC,GAAG,QAAQ,CAAC,CAAC,CACpE,MAAM,eAAe,MAAM,MAAM,CACjC,QAAQ,cAAc,CACtB,SAAS;AAEX,QAAK,MAAM,OAAO,KACjB,QAAO,IAAI,IAAI,aAAa,OAAO,IAAI,SAAS,EAAE,CAAC;;AAGrD,SAAO;;CAGR,AAAQ,cAAc,KAA0C;AAC/D,SAAO;GACN,IAAI,IAAI;GACR,MAAM,IAAI;GACV,MAAM,IAAI;GACV,OAAO,IAAI;GACX,UAAU,IAAI;GACd,MAAM,IAAI,OAAO,KAAK,MAAM,IAAI,KAAK,GAAG;GACxC,QAAQ,IAAI;GACZ,kBAAkB,IAAI;GACtB"}
|
|
1
|
+
{"version":3,"file":"taxonomy-BxGxZZdu.mjs","names":[],"sources":["../src/database/repositories/taxonomy.ts"],"sourcesContent":["import type { Kysely, Selectable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { invalidateTaxonomyObjectCache } from \"../../object-cache/index.js\";\nimport type { Database, TaxonomyTable, ContentTaxonomyTable } from \"../types.js\";\n\nexport interface Taxonomy {\n\tid: string;\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparentId: string | null;\n\tdata: Record<string, unknown> | null;\n\tlocale: string;\n\ttranslationGroup: string | null;\n}\n\nexport interface CreateTaxonomyInput {\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparentId?: string;\n\tdata?: Record<string, unknown>;\n\t/** Omit to let the DB default (current value: 'en') apply. Higher layers\n\t * resolve the locale from the request context / i18n config. */\n\tlocale?: string;\n\t/** When set, links the new term into the source term's translation_group. */\n\ttranslationOf?: string;\n}\n\nexport interface UpdateTaxonomyInput {\n\tslug?: string;\n\tlabel?: string;\n\tparentId?: string | null;\n\tdata?: Record<string, unknown>;\n}\n\nexport interface FindOptions {\n\tparentId?: string | null;\n\tlocale?: string;\n}\n\n/**\n * Taxonomy repository for categories, tags, and other classification.\n *\n * Terms are per-locale. Translations of the same term share a `translation_group`\n * ULID. `content_taxonomies.taxonomy_id` stores the translation_group so a single\n * association spans every locale of a post.\n *\n * The repository does not resolve locale fallbacks on its own — callers supply\n * the locale they want. Runtime helpers and handlers use `getFallbackChain()`\n * from `i18n/config` when they need fallback behaviour.\n */\nexport class TaxonomyRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Create a new taxonomy term. When `translationOf` is set the new row joins\n\t * the source term's translation_group; otherwise a fresh group is minted\n\t * (matching the migration backfill pattern `translation_group = id`).\n\t */\n\tasync create(input: CreateTaxonomyInput): Promise<Taxonomy> {\n\t\tconst id = ulid();\n\n\t\t// Empty-string parentId is coerced to null defensively. Higher layers\n\t\t// also normalize this — see handleTermCreate / handleTermUpdate.\n\t\t// `parent_id` stores the parent's locale-agnostic translation_group (not a\n\t\t// row id), mirroring content_taxonomies.taxonomy_id, so a child stays\n\t\t// nested in every locale's tree. resolveTranslationGroup accepts either a\n\t\t// row id or an already-resolved group, so this is idempotent.\n\t\tconst parentInput =\n\t\t\tinput.parentId === undefined || input.parentId === \"\" ? null : input.parentId;\n\t\tconst parentId = parentInput ? await this.resolveParentRef(parentInput) : null;\n\n\t\tlet translationGroup = id;\n\t\tif (input.translationOf) {\n\t\t\tconst source = await this.findById(input.translationOf);\n\t\t\tif (source?.translationGroup) translationGroup = source.translationGroup;\n\t\t}\n\n\t\tawait this.db\n\t\t\t.insertInto(\"taxonomies\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tname: input.name,\n\t\t\t\tslug: input.slug,\n\t\t\t\tlabel: input.label,\n\t\t\t\tparent_id: parentId,\n\t\t\t\tdata: input.data ? JSON.stringify(input.data) : null,\n\t\t\t\t// When omitted, the DB DEFAULT 'en' is used — keeps behaviour\n\t\t\t\t// consistent with ContentRepository and lets higher layers\n\t\t\t\t// supply an explicit locale from request context.\n\t\t\t\t...(input.locale !== undefined ? { locale: input.locale } : {}),\n\t\t\t\ttranslation_group: translationGroup,\n\t\t\t})\n\t\t\t.execute();\n\n\t\tinvalidateTaxonomyObjectCache();\n\n\t\tconst taxonomy = await this.findById(id);\n\t\tif (!taxonomy) throw new Error(\"Failed to create taxonomy\");\n\t\treturn taxonomy;\n\t}\n\n\tasync findById(id: string): Promise<Taxonomy | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? this.rowToTaxonomy(row) : null;\n\t}\n\n\t/**\n\t * Find a term by (name, slug). When `locale` is provided, filter by it.\n\t * When omitted, returns the lowest-locale-code match (deterministic across\n\t * calls). Mirrors `ContentRepository.findBySlug`.\n\t */\n\tasync findBySlug(name: string, slug: string, locale?: string): Promise<Taxonomy | null> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.where(\"slug\", \"=\", slug);\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst row = await query.orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t\treturn row ? this.rowToTaxonomy(row) : null;\n\t}\n\n\t/**\n\t * Get all terms for a taxonomy (e.g., all categories).\n\t *\n\t * `id asc` is a stable tiebreaker for terms that share a label. Without it\n\t * the SQL ordering is implementation-defined when labels match, which\n\t * breaks keyset pagination over `(label, id)`.\n\t */\n\tasync findByName(name: string, options: FindOptions = {}): Promise<Taxonomy[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.orderBy(\"label\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\n\t\tif (options.locale !== undefined) query = query.where(\"locale\", \"=\", options.locale);\n\n\t\tif (options.parentId !== undefined) {\n\t\t\tif (options.parentId === null) {\n\t\t\t\tquery = query.where(\"parent_id\", \"is\", null);\n\t\t\t} else {\n\t\t\t\tquery = query.where(\"parent_id\", \"=\", options.parentId);\n\t\t\t}\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\t/**\n\t * Children of a term. Accepts a term id OR a translation_group and resolves\n\t * to the group, since `parent_id` stores the parent's translation_group.\n\t * Pass `locale` to scope to one locale's tree (children share the parent's\n\t * group across locales); omit it to find children in every locale (used to\n\t * block deletes that would orphan a sibling translation's subtree).\n\t */\n\tasync findChildren(parentIdOrGroup: string, locale?: string): Promise<Taxonomy[]> {\n\t\tconst group = await this.resolveTranslationGroup(parentIdOrGroup);\n\t\tif (!group) return [];\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"parent_id\", \"=\", group)\n\t\t\t.orderBy(\"label\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\t/**\n\t * Every translation sibling of a term (including itself), identified by\n\t * their shared `translation_group`.\n\t */\n\tasync findTranslations(translationGroup: string): Promise<Taxonomy[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", translationGroup)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\tasync update(id: string, input: UpdateTaxonomyInput): Promise<Taxonomy | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return null;\n\n\t\tconst updates: Record<string, unknown> = {};\n\t\tif (input.slug !== undefined) updates.slug = input.slug;\n\t\tif (input.label !== undefined) updates.label = input.label;\n\t\tif (input.parentId !== undefined) {\n\t\t\t// Defense in depth: empty-string parentId means null (no parent).\n\t\t\t// Otherwise persist the parent's translation_group (locale-agnostic),\n\t\t\t// matching create() — see the note there.\n\t\t\tupdates.parent_id =\n\t\t\t\tinput.parentId === \"\" || input.parentId === null\n\t\t\t\t\t? null\n\t\t\t\t\t: await this.resolveParentRef(input.parentId);\n\t\t}\n\t\tif (input.data !== undefined) updates.data = JSON.stringify(input.data);\n\n\t\tif (Object.keys(updates).length > 0) {\n\t\t\tawait this.db.updateTable(\"taxonomies\").set(updates).where(\"id\", \"=\", id).execute();\n\t\t\tinvalidateTaxonomyObjectCache();\n\t\t}\n\n\t\treturn this.findById(id);\n\t}\n\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst term = await this.findById(id);\n\t\tif (!term) return false;\n\n\t\t// When deleting the last translation of a group the pivot rows that\n\t\t// reference that translation_group become orphaned — purge them.\n\t\tif (term.translationGroup) {\n\t\t\tconst siblings = await this.db\n\t\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t\t.select(\"id\")\n\t\t\t\t.where(\"translation_group\", \"=\", term.translationGroup)\n\t\t\t\t.where(\"id\", \"!=\", id)\n\t\t\t\t.execute();\n\t\t\tif (siblings.length === 0) {\n\t\t\t\tawait this.db\n\t\t\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t\t\t.where(\"taxonomy_id\", \"=\", term.translationGroup)\n\t\t\t\t\t.execute();\n\t\t\t}\n\t\t}\n\n\t\tconst result = await this.db.deleteFrom(\"taxonomies\").where(\"id\", \"=\", id).executeTakeFirst();\n\t\tinvalidateTaxonomyObjectCache();\n\t\treturn (result.numDeletedRows ?? 0n) > 0n;\n\t}\n\n\t// --- Content-Taxonomy Junction (taxonomy_id stores the translation_group) ---\n\n\tasync attachToEntry(collection: string, entryId: string, taxonomyId: string): Promise<void> {\n\t\tconst group = await this.resolveTranslationGroup(taxonomyId);\n\t\tif (!group) return;\n\n\t\tconst row: ContentTaxonomyTable = {\n\t\t\tcollection,\n\t\t\tentry_id: entryId,\n\t\t\ttaxonomy_id: group,\n\t\t};\n\t\tawait this.db\n\t\t\t.insertInto(\"content_taxonomies\")\n\t\t\t.values(row)\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.execute();\n\t\tinvalidateTaxonomyObjectCache();\n\t}\n\n\tasync detachFromEntry(collection: string, entryId: string, taxonomyId: string): Promise<void> {\n\t\tconst group = await this.resolveTranslationGroup(taxonomyId);\n\t\tif (!group) return;\n\n\t\tawait this.db\n\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t.where(\"taxonomy_id\", \"=\", group)\n\t\t\t.execute();\n\t\tinvalidateTaxonomyObjectCache();\n\t}\n\n\t/**\n\t * Taxonomy terms assigned to a content entry, resolved into a specific locale.\n\t * Terms whose translation_group lacks a row in the requested locale are\n\t * omitted — callers wanting fallback behaviour apply it themselves.\n\t */\n\tasync getTermsForEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\ttaxonomyName?: string,\n\t\tlocale?: string,\n\t): Promise<Taxonomy[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t.selectAll(\"taxonomies\")\n\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryId);\n\n\t\tif (taxonomyName) query = query.where(\"taxonomies.name\", \"=\", taxonomyName);\n\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\n\t\tconst rows = await query.orderBy(\"taxonomies.locale\", \"asc\").execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\t/**\n\t * Replace all assignments of a given taxonomy for one content entry.\n\t * Term ids OR translation_groups are accepted and normalised to groups.\n\t */\n\tasync setTermsForEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\ttaxonomyName: string,\n\t\ttermIds: string[],\n\t): Promise<void> {\n\t\tconst groups: string[] = [];\n\t\tfor (const id of termIds) {\n\t\t\tconst group = await this.resolveTranslationGroup(id);\n\t\t\tif (group) groups.push(group);\n\t\t}\n\t\tconst newGroups = new Set(groups);\n\n\t\tconst current = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t.select([\"content_taxonomies.taxonomy_id as group\"])\n\t\t\t.distinct()\n\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryId)\n\t\t\t.where(\"taxonomies.name\", \"=\", taxonomyName)\n\t\t\t.execute();\n\t\tconst currentGroups = new Set(current.map((r) => r.group));\n\n\t\tconst toRemove = [...currentGroups].filter((g) => !newGroups.has(g));\n\t\tif (toRemove.length > 0) {\n\t\t\tawait this.db\n\t\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t\t.where(\"taxonomy_id\", \"in\", toRemove)\n\t\t\t\t.execute();\n\t\t}\n\n\t\tconst toAdd = [...newGroups].filter((g) => !currentGroups.has(g));\n\t\tif (toAdd.length > 0) {\n\t\t\tawait this.db\n\t\t\t\t.insertInto(\"content_taxonomies\")\n\t\t\t\t.values(\n\t\t\t\t\ttoAdd.map((taxonomy_id) => ({\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tentry_id: entryId,\n\t\t\t\t\t\ttaxonomy_id,\n\t\t\t\t\t})),\n\t\t\t\t)\n\t\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t\t.execute();\n\t\t}\n\n\t\tif (toRemove.length > 0 || toAdd.length > 0) invalidateTaxonomyObjectCache();\n\t}\n\n\tasync clearEntryTerms(collection: string, entryId: string): Promise<number> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t.executeTakeFirst();\n\t\tconst removed = Number(result.numDeletedRows ?? 0);\n\t\tif (removed > 0) invalidateTaxonomyObjectCache();\n\t\treturn removed;\n\t}\n\n\t/**\n\t * Copy every term assignment from one content entry to another. Used when\n\t * creating a translation of a post so the new translation inherits the\n\t * source's term assignments. Safe to call when the source has no terms.\n\t */\n\tasync copyEntryTerms(\n\t\tcollection: string,\n\t\tsourceEntryId: string,\n\t\ttargetEntryId: string,\n\t): Promise<void> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select([\"taxonomy_id\"])\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", sourceEntryId)\n\t\t\t.execute();\n\t\tif (rows.length === 0) return;\n\n\t\tawait this.db\n\t\t\t.insertInto(\"content_taxonomies\")\n\t\t\t.values(\n\t\t\t\trows.map((r) => ({\n\t\t\t\t\tcollection,\n\t\t\t\t\tentry_id: targetEntryId,\n\t\t\t\t\ttaxonomy_id: r.taxonomy_id,\n\t\t\t\t})),\n\t\t\t)\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.execute();\n\t\tinvalidateTaxonomyObjectCache();\n\t}\n\n\t/**\n\t * Count content entries that use any translation of this term. Accepts\n\t * either a term id or a translation_group — we normalise to the group.\n\t */\n\tasync countEntriesWithTerm(termIdOrGroup: string): Promise<number> {\n\t\tconst group = await this.resolveTranslationGroup(termIdOrGroup);\n\t\tif (!group) return 0;\n\n\t\tconst result = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select((eb) => eb.fn.count(\"entry_id\").as(\"count\"))\n\t\t\t.where(\"taxonomy_id\", \"=\", group)\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/**\n\t * Resolve a parent reference (a row id or a translation_group) to the value\n\t * persisted in `parent_id`: the parent's translation_group, which is\n\t * locale-agnostic so the child stays nested in every locale. A\n\t * translation_group normally equals its anchor row's id, which satisfies the\n\t * self-FK on `parent_id`. If that anchor row is missing (a translation whose\n\t * anchor was deleted), fall back to the id we were given so we never write a\n\t * dangling FK value.\n\t */\n\tprivate async resolveParentRef(idOrGroup: string): Promise<string> {\n\t\tconst group = await this.resolveTranslationGroup(idOrGroup);\n\t\tif (!group) return idOrGroup;\n\t\tconst anchor = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"id\", \"=\", group)\n\t\t\t.executeTakeFirst();\n\t\treturn anchor ? group : idOrGroup;\n\t}\n\n\tprivate async resolveTranslationGroup(idOrGroup: string): Promise<string | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.select([\"translation_group\"])\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\treturn row?.translation_group ?? null;\n\t}\n\n\t/**\n\t * Batch count entries for multiple taxonomy translation_groups.\n\t * Chunks the query at SQL_BATCH_SIZE to stay below D1's bind-parameter limit.\n\t * Returns a Map from translation_group to count.\n\t *\n\t * Pass translation_groups (not term ids) — `content_taxonomies.taxonomy_id`\n\t * stores the translation_group so a single assignment spans every locale.\n\t */\n\tasync countEntriesForTerms(translationGroups: string[]): Promise<Map<string, number>> {\n\t\tif (translationGroups.length === 0) return new Map();\n\n\t\tconst { chunks, SQL_BATCH_SIZE } = await import(\"../../utils/chunks.js\");\n\n\t\tconst counts = new Map<string, number>();\n\t\tfor (const chunk of chunks(translationGroups, SQL_BATCH_SIZE)) {\n\t\t\tconst rows = await this.db\n\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t.select([\"taxonomy_id\", (eb) => eb.fn.count(\"entry_id\").as(\"count\")])\n\t\t\t\t.where(\"taxonomy_id\", \"in\", chunk)\n\t\t\t\t.groupBy(\"taxonomy_id\")\n\t\t\t\t.execute();\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tcounts.set(row.taxonomy_id, Number(row.count || 0));\n\t\t\t}\n\t\t}\n\t\treturn counts;\n\t}\n\n\tprivate rowToTaxonomy(row: Selectable<TaxonomyTable>): Taxonomy {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\tname: row.name,\n\t\t\tslug: row.slug,\n\t\t\tlabel: row.label,\n\t\t\tparentId: row.parent_id,\n\t\t\tdata: row.data ? JSON.parse(row.data) : null,\n\t\t\tlocale: row.locale,\n\t\t\ttranslationGroup: row.translation_group,\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqDA,IAAa,qBAAb,MAAgC;CAC/B,YAAY,AAAQ,IAAsB;EAAtB;;;;;;;CAOpB,MAAM,OAAO,OAA+C;EAC3D,MAAM,KAAK,MAAM;EAQjB,MAAM,cACL,MAAM,aAAa,UAAa,MAAM,aAAa,KAAK,OAAO,MAAM;EACtE,MAAM,WAAW,cAAc,MAAM,KAAK,iBAAiB,YAAY,GAAG;EAE1E,IAAI,mBAAmB;AACvB,MAAI,MAAM,eAAe;GACxB,MAAM,SAAS,MAAM,KAAK,SAAS,MAAM,cAAc;AACvD,OAAI,QAAQ,iBAAkB,oBAAmB,OAAO;;AAGzD,QAAM,KAAK,GACT,WAAW,aAAa,CACxB,OAAO;GACP;GACA,M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G.mjs","names":[],"sources":["../src/preview/tokens.ts"],"sourcesContent":["/**\n * Preview token generation and verification\n *\n * Tokens are compact, URL-safe, and HMAC-signed.\n * Format: base64url(JSON payload).base64url(HMAC signature)\n *\n * Payload: { cid: contentId, exp: expiryTimestamp, iat: issuedAt }\n */\n\nimport { encodeBase64url, decodeBase64url } from \"../utils/base64.js\";\n\n// Regex pattern for duration parsing\nconst DURATION_PATTERN = /^(\\d+)([smhdw])$/;\n\n/**\n * Preview token payload\n */\nexport interface PreviewTokenPayload {\n\t/** Content ID in format \"collection:id\" (e.g., \"posts:abc123\") */\n\tcid: string;\n\t/** Expiry timestamp (seconds since epoch) */\n\texp: number;\n\t/** Issued at timestamp (seconds since epoch) */\n\tiat: number;\n}\n\n/**\n * Options for generating a preview token\n */\nexport interface GeneratePreviewTokenOptions {\n\t/** Content ID in format \"collection:id\" */\n\tcontentId: string;\n\t/** How long the token is valid. Accepts \"1h\", \"30m\", \"1d\", or seconds as number. Default: \"1h\" */\n\texpiresIn?: string | number;\n\t/** Secret key for signing. Should be from environment variable. */\n\tsecret: string;\n}\n\n/**\n * Parse duration string to seconds\n * Supports: \"1h\", \"30m\", \"1d\", \"2w\", or raw seconds\n */\nfunction parseDuration(duration: string | number): number {\n\tif (typeof duration === \"number\") {\n\t\treturn duration;\n\t}\n\n\tconst match = duration.match(DURATION_PATTERN);\n\tif (!match) {\n\t\tthrow new Error(\n\t\t\t`Invalid duration format: \"${duration}\". Use \"1h\", \"30m\", \"1d\", \"2w\", or seconds.`,\n\t\t);\n\t}\n\n\tconst value = parseInt(match[1], 10);\n\tconst unit = match[2];\n\n\tswitch (unit) {\n\t\tcase \"s\":\n\t\t\treturn value;\n\t\tcase \"m\":\n\t\t\treturn value * 60;\n\t\tcase \"h\":\n\t\t\treturn value * 60 * 60;\n\t\tcase \"d\":\n\t\t\treturn value * 60 * 60 * 24;\n\t\tcase \"w\":\n\t\t\treturn value * 60 * 60 * 24 * 7;\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown duration unit: ${unit}`);\n\t}\n}\n\n/**\n * Create HMAC-SHA256 signature using Web Crypto API\n */\nasync function createSignature(data: string, secret: string): Promise<Uint8Array> {\n\tconst encoder = new TextEncoder();\n\tconst key = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tencoder.encode(secret),\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"sign\"],\n\t);\n\tconst signature = await crypto.subtle.sign(\"HMAC\", key, encoder.encode(data));\n\treturn new Uint8Array(signature);\n}\n\n/**\n * Verify HMAC-SHA256 signature\n */\nasync function verifySignature(\n\tdata: string,\n\tsignature: Uint8Array,\n\tsecret: string,\n): Promise<boolean> {\n\tconst encoder = new TextEncoder();\n\tconst key = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tencoder.encode(secret),\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"verify\"],\n\t);\n\t// Create a new ArrayBuffer from the signature to satisfy BufferSource typing\n\t// (Uint8Array.buffer is ArrayBufferLike which includes SharedArrayBuffer)\n\tconst sigBuffer: ArrayBuffer = new ArrayBuffer(signature.byteLength);\n\tnew Uint8Array(sigBuffer).set(signature);\n\treturn crypto.subtle.verify(\"HMAC\", key, sigBuffer, encoder.encode(data));\n}\n\n/**\n * Generate a preview token for content\n *\n * @example\n * ```ts\n * const token = await generatePreviewToken({\n * contentId: \"posts:abc123\",\n * expiresIn: \"1h\",\n * secret: process.env.PREVIEW_SECRET!,\n * });\n * ```\n */\nexport async function generatePreviewToken(options: GeneratePreviewTokenOptions): Promise<string> {\n\tconst { contentId, expiresIn = \"1h\", secret } = options;\n\n\tif (!secret) {\n\t\tthrow new Error(\"Preview secret is required\");\n\t}\n\n\tif (!contentId || !contentId.includes(\":\")) {\n\t\tthrow new Error('Content ID must be in format \"collection:id\"');\n\t}\n\n\tconst now = Math.floor(Date.now() / 1000);\n\tconst duration = parseDuration(expiresIn);\n\n\tconst payload: PreviewTokenPayload = {\n\t\tcid: contentId,\n\t\texp: now + duration,\n\t\tiat: now,\n\t};\n\n\t// Encode payload\n\tconst payloadJson = JSON.stringify(payload);\n\tconst encodedPayload = encodeBase64url(new TextEncoder().encode(payloadJson));\n\n\t// Sign it\n\tconst signature = await createSignature(encodedPayload, secret);\n\tconst encodedSignature = encodeBase64url(signature);\n\n\treturn `${encodedPayload}.${encodedSignature}`;\n}\n\n/**\n * Result of verifying a preview token\n */\nexport type VerifyPreviewTokenResult =\n\t| { valid: true; payload: PreviewTokenPayload }\n\t| { valid: false; error: \"invalid\" | \"expired\" | \"malformed\" | \"none\" };\n\n/**\n * Options for verifyPreviewToken\n */\nexport type VerifyPreviewTokenOptions = {\n\t/** Secret key for verifying tokens */\n\tsecret: string;\n} & (\n\t| { /** URL to extract _preview token from */ url: URL }\n\t| {\n\t\t\t/** Preview token string (can be null) */ token: string | null | undefined;\n\t }\n);\n\n/**\n * Verify a preview token and return the payload\n *\n * @example\n * ```ts\n * // With URL (extracts _preview query param)\n * const result = await verifyPreviewToken({\n * url: Astro.url,\n * secret: import.meta.env.PREVIEW_SECRET,\n * });\n *\n * // With token directly\n * const result = await verifyPreviewToken({\n * token: someToken,\n * secret: import.meta.env.PREVIEW_SECRET,\n * });\n *\n * if (result.valid) {\n * console.log(result.payload.cid); // \"posts:abc123\"\n * }\n * ```\n */\nexport async function verifyPreviewToken(\n\toptions: VerifyPreviewTokenOptions,\n): Promise<VerifyPreviewTokenResult> {\n\tconst { secret } = options;\n\n\tif (!secret) {\n\t\tthrow new Error(\"Preview secret is required\");\n\t}\n\n\t// Extract token from URL or use provided token\n\tconst token = \"url\" in options ? options.url.searchParams.get(\"_preview\") : options.token;\n\n\t// Handle null/undefined token\n\tif (!token) {\n\t\treturn { valid: false, error: \"none\" };\n\t}\n\n\t// Split token into payload and signature\n\tconst parts = token.split(\".\");\n\tif (parts.length !== 2) {\n\t\treturn { valid: false, error: \"malformed\" };\n\t}\n\n\tconst [encodedPayload, encodedSignature] = parts;\n\n\t// Verify signature\n\tlet signature: Uint8Array;\n\ttry {\n\t\tsignature = decodeBase64url(encodedSignature);\n\t} catch {\n\t\treturn { valid: false, error: \"malformed\" };\n\t}\n\n\tconst isValid = await verifySignature(encodedPayload, signature, secret);\n\tif (!isValid) {\n\t\treturn { valid: false, error: \"invalid\" };\n\t}\n\n\t// Decode and parse payload\n\tlet payload: PreviewTokenPayload;\n\ttry {\n\t\tconst payloadBytes = decodeBase64url(encodedPayload);\n\t\tconst payloadJson = new TextDecoder().decode(payloadBytes);\n\t\tpayload = JSON.parse(payloadJson);\n\t} catch {\n\t\treturn { valid: false, error: \"malformed\" };\n\t}\n\n\t// Check required fields\n\tif (\n\t\ttypeof payload.cid !== \"string\" ||\n\t\ttypeof payload.exp !== \"number\" ||\n\t\ttypeof payload.iat !== \"number\"\n\t) {\n\t\treturn { valid: false, error: \"malformed\" };\n\t}\n\n\t// Check expiry\n\tconst now = Math.floor(Date.now() / 1000);\n\tif (payload.exp < now) {\n\t\treturn { valid: false, error: \"expired\" };\n\t}\n\n\treturn { valid: true, payload };\n}\n\n/**\n * Parse a content ID into collection and id\n */\nexport function parseContentId(contentId: string): {\n\tcollection: string;\n\tid: string;\n} {\n\tconst colonIndex = contentId.indexOf(\":\");\n\tif (colonIndex === -1) {\n\t\tthrow new Error('Content ID must be in format \"collection:id\"');\n\t}\n\treturn {\n\t\tcollection: contentId.slice(0, colonIndex),\n\t\tid: contentId.slice(colonIndex + 1),\n\t};\n}\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,mBAAmB;;;;;AA8BzB,SAAS,cAAc,UAAmC;AACzD,KAAI,OAAO,aAAa,SACvB,QAAO;CAGR,MAAM,QAAQ,SAAS,MAAM,iBAAiB;AAC9C,KAAI,CAAC,MACJ,OAAM,IAAI,MACT,6BAA6B,SAAS,6CACtC;CAGF,MAAM,QAAQ,SAAS,MAAM,IAAI,GAAG;CACpC,MAAM,OAAO,MAAM;AAEnB,SAAQ,MAAR;E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;EAAO,OAAO;EAAW;AAG1C,QAAO;EAAE,OAAO;EAAM;EAAS;;;;;AAMhC,SAAgB,eAAe,WAG7B;CACD,MAAM,aAAa,UAAU,QAAQ,IAAI;AACzC,KAAI,eAAe,GAClB,OAAM,IAAI,MAAM,iDAA+C;AAEhE,QAAO;EACN,YAAY,UAAU,MAAM,GAAG,WAAW;EAC1C,IAAI,UAAU,MAAM,aAAa,EAAE;EACnC"}
|
|
1
|
+
{"version":3,"file":"tokens-BGT0TUUo.mjs","names":[],"sources":["../src/preview/tokens.ts"],"sourcesContent":["/**\n * Preview token generation and verification\n *\n * Tokens are compact, URL-safe, and HMAC-signed.\n * Format: base64url(JSON payload).base64url(HMAC signature)\n *\n * Payload: { cid: contentId, exp: expiryTimestamp, iat: issuedAt }\n */\n\nimport { encodeBase64url, decodeBase64url } from \"../utils/base64.js\";\n\n// Regex pattern for duration parsing\nconst DURATION_PATTERN = /^(\\d+)([smhdw])$/;\n\n/**\n * Preview token payload\n */\nexport interface PreviewTokenPayload {\n\t/** Content ID in format \"collection:id\" (e.g., \"posts:abc123\") */\n\tcid: string;\n\t/** Expiry timestamp (seconds since epoch) */\n\texp: number;\n\t/** Issued at timestamp (seconds since epoch) */\n\tiat: number;\n}\n\n/**\n * Options for generating a preview token\n */\nexport interface GeneratePreviewTokenOptions {\n\t/** Content ID in format \"collection:id\" */\n\tcontentId: string;\n\t/** How long the token is valid. Accepts \"1h\", \"30m\", \"1d\", or seconds as number. Default: \"1h\" */\n\texpiresIn?: string | number;\n\t/** Secret key for signing. Should be from environment variable. */\n\tsecret: string;\n}\n\n/**\n * Parse duration string to seconds\n * Supports: \"1h\", \"30m\", \"1d\", \"2w\", or raw seconds\n */\nfunction parseDuration(duration: string | number): number {\n\tif (typeof duration === \"number\") {\n\t\treturn duration;\n\t}\n\n\tconst match = duration.match(DURATION_PATTERN);\n\tif (!match) {\n\t\tthrow new Error(\n\t\t\t`Invalid duration format: \"${duration}\". Use \"1h\", \"30m\", \"1d\", \"2w\", or seconds.`,\n\t\t);\n\t}\n\n\tconst value = parseInt(match[1], 10);\n\tconst unit = match[2];\n\n\tswitch (unit) {\n\t\tcase \"s\":\n\t\t\treturn value;\n\t\tcase \"m\":\n\t\t\treturn value * 60;\n\t\tcase \"h\":\n\t\t\treturn value * 60 * 60;\n\t\tcase \"d\":\n\t\t\treturn value * 60 * 60 * 24;\n\t\tcase \"w\":\n\t\t\treturn value * 60 * 60 * 24 * 7;\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown duration unit: ${unit}`);\n\t}\n}\n\n/**\n * Create HMAC-SHA256 signature using Web Crypto API\n */\nasync function createSignature(data: string, secret: string): Promise<Uint8Array> {\n\tconst encoder = new TextEncoder();\n\tconst key = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tencoder.encode(secret),\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"sign\"],\n\t);\n\tconst signature = await crypto.subtle.sign(\"HMAC\", key, encoder.encode(data));\n\treturn new Uint8Array(signature);\n}\n\n/**\n * Verify HMAC-SHA256 signature\n */\nasync function verifySignature(\n\tdata: string,\n\tsignature: Uint8Array,\n\tsecret: string,\n): Promise<boolean> {\n\tconst encoder = new TextEncoder();\n\tconst key = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tencoder.encode(secret),\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"verify\"],\n\t);\n\t// Create a new ArrayBuffer from the signature to satisfy BufferSource typing\n\t// (Uint8Array.buffer is ArrayBufferLike which includes SharedArrayBuffer)\n\tconst sigBuffer: ArrayBuffer = new ArrayBuffer(signature.byteLength);\n\tnew Uint8Array(sigBuffer).set(signature);\n\treturn crypto.subtle.verify(\"HMAC\", key, sigBuffer, encoder.encode(data));\n}\n\n/**\n * Generate a preview token for content\n *\n * @example\n * ```ts\n * const token = await generatePreviewToken({\n * contentId: \"posts:abc123\",\n * expiresIn: \"1h\",\n * secret: process.env.PREVIEW_SECRET!,\n * });\n * ```\n */\nexport async function generatePreviewToken(options: GeneratePreviewTokenOptions): Promise<string> {\n\tconst { contentId, expiresIn = \"1h\", secret } = options;\n\n\tif (!secret) {\n\t\tthrow new Error(\"Preview secret is required\");\n\t}\n\n\tif (!contentId || !contentId.includes(\":\")) {\n\t\tthrow new Error('Content ID must be in format \"collection:id\"');\n\t}\n\n\tconst now = Math.floor(Date.now() / 1000);\n\tconst duration = parseDuration(expiresIn);\n\n\tconst payload: PreviewTokenPayload = {\n\t\tcid: contentId,\n\t\texp: now + duration,\n\t\tiat: now,\n\t};\n\n\t// Encode payload\n\tconst payloadJson = JSON.stringify(payload);\n\tconst encodedPayload = encodeBase64url(new TextEncoder().encode(payloadJson));\n\n\t// Sign it\n\tconst signature = await createSignature(encodedPayload, secret);\n\tconst encodedSignature = encodeBase64url(signature);\n\n\treturn `${encodedPayload}.${encodedSignature}`;\n}\n\n/**\n * Result of verifying a preview token\n */\nexport type VerifyPreviewTokenResult =\n\t| { valid: true; payload: PreviewTokenPayload }\n\t| { valid: false; error: \"invalid\" | \"expired\" | \"malformed\" | \"none\" };\n\n/**\n * Options for verifyPreviewToken\n */\nexport type VerifyPreviewTokenOptions = {\n\t/** Secret key for verifying tokens */\n\tsecret: string;\n} & (\n\t| { /** URL to extract _preview token from */ url: URL }\n\t| {\n\t\t\t/** Preview token string (can be null) */ token: string | null | undefined;\n\t }\n);\n\n/**\n * Verify a preview token and return the payload\n *\n * @example\n * ```ts\n * // With URL (extracts _preview query param)\n * const result = await verifyPreviewToken({\n * url: Astro.url,\n * secret: import.meta.env.PREVIEW_SECRET,\n * });\n *\n * // With token directly\n * const result = await verifyPreviewToken({\n * token: someToken,\n * secret: import.meta.env.PREVIEW_SECRET,\n * });\n *\n * if (result.valid) {\n * console.log(result.payload.cid); // \"posts:abc123\"\n * }\n * ```\n */\nexport async function verifyPreviewToken(\n\toptions: VerifyPreviewTokenOptions,\n): Promise<VerifyPreviewTokenResult> {\n\tconst { secret } = options;\n\n\tif (!secret) {\n\t\tthrow new Error(\"Preview secret is required\");\n\t}\n\n\t// Extract token from URL or use provided token\n\tconst token = \"url\" in options ? options.url.searchParams.get(\"_preview\") : options.token;\n\n\t// Handle null/undefined token\n\tif (!token) {\n\t\treturn { valid: false, error: \"none\" };\n\t}\n\n\t// Split token into payload and signature\n\tconst parts = token.split(\".\");\n\tif (parts.length !== 2) {\n\t\treturn { valid: false, error: \"malformed\" };\n\t}\n\n\tconst [encodedPayload, encodedSignature] = parts;\n\n\t// Verify signature\n\tlet signature: Uint8Array;\n\ttry {\n\t\tsignature = decodeBase64url(encodedSignature);\n\t} catch {\n\t\treturn { valid: false, error: \"malformed\" };\n\t}\n\n\tconst isValid = await verifySignature(encodedPayload, signature, secret);\n\tif (!isValid) {\n\t\treturn { valid: false, error: \"invalid\" };\n\t}\n\n\t// Decode and parse payload\n\tlet payload: PreviewTokenPayload;\n\ttry {\n\t\tconst payloadBytes = decodeBase64url(encodedPayload);\n\t\tconst payloadJson = new TextDecoder().decode(payloadBytes);\n\t\tpayload = JSON.parse(payloadJson);\n\t} catch {\n\t\treturn { valid: false, error: \"malformed\" };\n\t}\n\n\t// Check required fields\n\tif (\n\t\ttypeof payload.cid !== \"string\" ||\n\t\ttypeof payload.exp !== \"number\" ||\n\t\ttypeof payload.iat !== \"number\"\n\t) {\n\t\treturn { valid: false, error: \"malformed\" };\n\t}\n\n\t// Check expiry\n\tconst now = Math.floor(Date.now() / 1000);\n\tif (payload.exp < now) {\n\t\treturn { valid: false, error: \"expired\" };\n\t}\n\n\treturn { valid: true, payload };\n}\n\n/**\n * Parse a content ID into collection and id\n */\nexport function parseContentId(contentId: string): {\n\tcollection: string;\n\tid: string;\n} {\n\tconst colonIndex = contentId.indexOf(\":\");\n\tif (colonIndex === -1) {\n\t\tthrow new Error('Content ID must be in format \"collection:id\"');\n\t}\n\treturn {\n\t\tcollection: contentId.slice(0, colonIndex),\n\t\tid: contentId.slice(colonIndex + 1),\n\t};\n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,YAAU,KAAK,MAAM,YAAY;SAC1B;AACP,SAAO;GAAE,OAAO;GAAO,OAAO;GAAa;;AAI5C,KACC,OAAO,QAAQ,QAAQ,YACvB,OAAO,QAAQ,QAAQ,YACvB,OAAO,QAAQ,QAAQ,SAEvB,QAAO;EAAE,OAAO;EAAO,OAAO;EAAa;CAI5C,MAAM,MAAM,KAAK,MAAM,KAAK,KAAK,GAAG,IAAK;AACzC,KAAI,QAAQ,MAAM,IACjB,QAAO;EAAE,OAAO;EAAO,OAAO;EAAW;AAG1C,QAAO;EAAE,OAAO;EAAM;EAAS;;;;;AAMhC,SAAgB,eAAe,WAG7B;CACD,MAAM,aAAa,UAAU,QAAQ,IAAI;AACzC,KAAI,eAAe,GAClB,OAAM,IAAI,MAAM,iDAA+C;AAEhE,QAAO;EACN,YAAY,UAAU,MAAM,GAAG,WAAW;EAC1C,IAAI,UAAU,MAAM,aAAa,EAAE;EACnC"}
|
|
@@ -39,4 +39,4 @@ declare function tokenInterceptor(token: string): Interceptor;
|
|
|
39
39
|
declare function devBypassInterceptor(baseUrl: string): Interceptor;
|
|
40
40
|
//#endregion
|
|
41
41
|
export { tokenInterceptor as a, devBypassInterceptor as i, createTransport as n, csrfInterceptor as r, Interceptor as t };
|
|
42
|
-
//# sourceMappingURL=transport-
|
|
42
|
+
//# sourceMappingURL=transport-BMDWHSgZ.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport-
|
|
1
|
+
{"version":3,"file":"transport-BMDWHSgZ.d.mts","names":[],"sources":["../src/client/transport.ts"],"mappings":";;AAeA;;;;;;;;;;KAAY,WAAA,IACX,OAAA,EAAS,OAAA,EACT,IAAA,GAAO,OAAA,EAAS,OAAA,KAAY,OAAA,CAAQ,QAAA,MAChC,OAAA,CAAQ,QAAA;AAAA,UAEI,gBAAA;EAChB,YAAA,GAAe,WAAA;AAAA;;;;iBAUA,eAAA,CAAgB,OAAA,GAAS,gBAAA;EACxC,KAAA,GAAQ,OAAA,EAAS,OAAA,KAAY,OAAA,CAAQ,QAAA;AAAA;;;AAZtC;;;;iBAqCgB,eAAA,CAAA,GAAmB,WAAA;AA1BnC;;;AAAA,iBA8CgB,gBAAA,CAAiB,KAAA,WAAgB,WAAA;;;;;;iBAajC,oBAAA,CAAqB,OAAA,WAAkB,WAAA"}
|
|
@@ -132,4 +132,4 @@ function refreshInterceptor(options) {
|
|
|
132
132
|
|
|
133
133
|
//#endregion
|
|
134
134
|
export { tokenInterceptor as a, refreshInterceptor as i, csrfInterceptor as n, devBypassInterceptor as r, createTransport as t };
|
|
135
|
-
//# sourceMappingURL=transport-
|
|
135
|
+
//# sourceMappingURL=transport-DPefPMcz.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport-
|
|
1
|
+
{"version":3,"file":"transport-DPefPMcz.mjs","names":[],"sources":["../src/client/transport.ts"],"sourcesContent":["/**\n * Transport layer for the EmDash client.\n *\n * Implements a composable interceptor pipeline that modifies requests\n * and responses. The client calls `transport.fetch(request)` — everything\n * else (auth, CSRF, retry) is handled by interceptors.\n */\n\n// Regex patterns for transport utilities\nconst COOKIE_NAME_VALUE_PATTERN = /^([^;]+)/;\n\n/**\n * An interceptor can modify the request, call next(), inspect\n * the response, and optionally retry.\n */\nexport type Interceptor = (\n\trequest: Request,\n\tnext: (request: Request) => Promise<Response>,\n) => Promise<Response>;\n\nexport interface TransportOptions {\n\tinterceptors?: Interceptor[];\n}\n\nfunction baseFetch(request: Request): Promise<Response> {\n\treturn globalThis.fetch(request);\n}\n\n/**\n * Creates a fetch function that runs requests through an interceptor pipeline.\n */\nexport function createTransport(options: TransportOptions = {}): {\n\tfetch: (request: Request) => Promise<Response>;\n} {\n\tconst interceptors = options.interceptors ?? [];\n\n\t// Build the chain once — interceptors don't change after construction\n\tlet chain: (request: Request) => Promise<Response> = baseFetch;\n\tfor (let i = interceptors.length - 1; i >= 0; i--) {\n\t\tconst interceptor = interceptors[i];\n\t\tconst next = chain;\n\t\tchain = (req) => interceptor(req, next);\n\t}\n\n\treturn { fetch: chain };\n}\n\n// ---------------------------------------------------------------------------\n// Built-in interceptors\n// ---------------------------------------------------------------------------\n\n/**\n * Adds X-EmDash-Request: 1 and Origin headers to mutation requests\n * (POST, PUT, DELETE). The custom header satisfies EmDash's CSRF check;\n * the Origin header satisfies Astro's built-in origin verification which\n * rejects server-side POST requests that lack a matching Origin.\n */\nexport function csrfInterceptor(): Interceptor {\n\tconst MUTATION_METHODS = new Set([\"POST\", \"PUT\", \"DELETE\", \"PATCH\"]);\n\n\treturn (request, next) => {\n\t\tif (MUTATION_METHODS.has(request.method)) {\n\t\t\tconst headers = new Headers(request.headers);\n\t\t\theaders.set(\"X-EmDash-Request\", \"1\");\n\t\t\tif (!headers.has(\"Origin\")) {\n\t\t\t\tconst url = new URL(request.url);\n\t\t\t\theaders.set(\"Origin\", url.origin);\n\t\t\t}\n\t\t\treturn next(new Request(request, { headers }));\n\t\t}\n\t\treturn next(request);\n\t};\n}\n\n/**\n * Adds Authorization: Bearer header from a static token.\n */\nexport function tokenInterceptor(token: string): Interceptor {\n\treturn (request, next) => {\n\t\tconst headers = new Headers(request.headers);\n\t\theaders.set(\"Authorization\", `Bearer ${token}`);\n\t\treturn next(new Request(request, { headers }));\n\t};\n}\n\n/**\n * Dev bypass interceptor. Calls the dev-bypass endpoint on first request\n * to establish a session, then forwards the session cookie on subsequent\n * requests.\n */\nexport function devBypassInterceptor(baseUrl: string): Interceptor {\n\tlet sessionCookie: string | null = null;\n\tlet initializing: Promise<void> | null = null;\n\n\tasync function init(): Promise<void> {\n\t\tconst bypassUrl = new URL(\"/_emdash/api/auth/dev-bypass\", baseUrl);\n\t\tconst res = await globalThis.fetch(bypassUrl, { redirect: \"manual\" });\n\n\t\t// Extract session cookie from Set-Cookie header\n\t\tconst setCookie = res.headers.get(\"set-cookie\");\n\t\tif (setCookie) {\n\t\t\t// Extract just the cookie name=value part\n\t\t\tconst match = setCookie.match(COOKIE_NAME_VALUE_PATTERN);\n\t\t\tif (match) {\n\t\t\t\tsessionCookie = match[1]!;\n\t\t\t}\n\t\t}\n\n\t\t// Consume the response body\n\t\tif (res.body) {\n\t\t\tawait res.text().catch(() => {});\n\t\t}\n\t}\n\n\treturn async (request, next) => {\n\t\t// Ensure we've initialized (only once, even with concurrent requests)\n\t\tif (!sessionCookie) {\n\t\t\tif (!initializing) {\n\t\t\t\tinitializing = init();\n\t\t\t}\n\t\t\tawait initializing;\n\t\t}\n\n\t\tif (sessionCookie) {\n\t\t\tconst headers = new Headers(request.headers);\n\t\t\tconst existing = headers.get(\"cookie\");\n\t\t\theaders.set(\"cookie\", existing ? `${existing}; ${sessionCookie}` : sessionCookie);\n\t\t\treturn next(new Request(request, { headers }));\n\t\t}\n\n\t\treturn next(request);\n\t};\n}\n\n/**\n * Auto-refreshes expired OAuth tokens on 401 responses.\n * Requires a refresh token and the token endpoint URL.\n */\nexport function refreshInterceptor(options: {\n\trefreshToken: string;\n\ttokenEndpoint: string;\n\tonTokenRefreshed?: (accessToken: string, refreshToken: string, expiresAt: string) => void;\n}): Interceptor {\n\tlet refreshing: Promise<string | null> | null = null;\n\n\tasync function refresh(): Promise<string | null> {\n\t\tconst res = await globalThis.fetch(options.tokenEndpoint, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({\n\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\trefresh_token: options.refreshToken,\n\t\t\t}),\n\t\t});\n\n\t\tif (!res.ok) return null;\n\n\t\tinterface TokenFields {\n\t\t\taccess_token: string;\n\t\t\trefresh_token?: string;\n\t\t\texpires_in?: number;\n\t\t}\n\n\t\tconst json = (await res.json()) as Record<string, unknown>;\n\n\t\t// The token endpoint wraps the response in { data: ... } via apiSuccess.\n\t\t// Handle both wrapped and bare shapes for robustness.\n\t\tconst tokenData: TokenFields =\n\t\t\tjson.data && typeof json.data === \"object\" && \"access_token\" in json.data\n\t\t\t\t? (json.data as TokenFields)\n\t\t\t\t: (json as unknown as TokenFields);\n\n\t\tconst expiresAt = tokenData.expires_in\n\t\t\t? new Date(Date.now() + tokenData.expires_in * 1000).toISOString()\n\t\t\t: new Date(Date.now() + 3600_000).toISOString();\n\n\t\tif (options.onTokenRefreshed) {\n\t\t\toptions.onTokenRefreshed(\n\t\t\t\ttokenData.access_token,\n\t\t\t\ttokenData.refresh_token ?? options.refreshToken,\n\t\t\t\texpiresAt,\n\t\t\t);\n\t\t}\n\n\t\treturn tokenData.access_token;\n\t}\n\n\treturn async (request, next) => {\n\t\tconst response = await next(request);\n\n\t\tif (response.status === 401) {\n\t\t\t// Try to refresh\n\t\t\tif (!refreshing) {\n\t\t\t\trefreshing = refresh().finally(() => {\n\t\t\t\t\trefreshing = null;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst newToken = await refreshing;\n\t\t\tif (newToken) {\n\t\t\t\t// Retry with new token\n\t\t\t\tconst headers = new Headers(request.headers);\n\t\t\t\theaders.set(\"Authorization\", `Bearer ${newToken}`);\n\t\t\t\treturn next(new Request(request, { headers }));\n\t\t\t}\n\t\t}\n\n\t\treturn response;\n\t};\n}\n"],"mappings":";;;;;;;;AASA,MAAM,4BAA4B;AAelC,SAAS,UAAU,SAAqC;AACvD,QAAO,WAAW,MAAM,QAAQ;;;;;AAMjC,SAAgB,gBAAgB,UAA4B,EAAE,EAE5D;CACD,MAAM,eAAe,QAAQ,gBAAgB,EAAE;CAG/C,IAAI,QAAiD;AACrD,MAAK,IAAI,IAAI,aAAa,SAAS,GAAG,KAAK,GAAG,KAAK;EAClD,MAAM,cAAc,aAAa;EACjC,MAAM,OAAO;AACb,WAAS,QAAQ,YAAY,KAAK,KAAK;;AAGxC,QAAO,EAAE,OAAO,OAAO;;;;;;;;AAaxB,SAAgB,kBAA+B;CAC9C,MAAM,mBAAmB,IAAI,IAAI;EAAC;EAAQ;EAAO;EAAU;EAAQ,CAAC;AAEpE,SAAQ,SAAS,SAAS;AACzB,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],"sources":["../src/auth/trusted-proxy.ts"],"sourcesContent":["/**\n * Resolve the list of client-IP headers the operator trusts.\n *\n * Resolution order:\n * 1. `config.trustedProxyHeaders` — explicit opt-in via astro.config.mjs.\n * An empty array is respected (means \"trust nothing, ignore env\").\n * 2. `EMDASH_TRUSTED_PROXY_HEADERS` env var — comma-separated header names.\n * 3. `[]` — default, no trusted headers.\n *\n * Operators must only set this when they control the reverse proxy.\n * Untrusted clients can set any header they like; trusting headers from\n * an open network defeats rate limiting.\n *\n * Header names are returned lowercased because HTTP header lookups are\n * case-insensitive.\n */\n\nimport type { EmDashConfig } from \"../astro/integration/runtime.js\";\n\n/**\n * RFC 7230 token — valid characters for an HTTP header name. Invalid names\n * passed to `Headers.get()` throw a TypeError at runtime, which would\n * otherwise surface as a 500 from every auth route.\n */\nconst HEADER_NAME_PATTERN = /^[!#$%&'*+\\-.^_`|~0-9a-z]+$/;\n\n/**\n * Normalise a list of header names the way both the config path and any\n * caller passing a pre-resolved list should do: trim, lowercase, drop\n * empty, drop anything that isn't a valid RFC 7230 token. Invalid names\n * would crash `Headers.get()` at runtime.\n */\nexport function normalizeTrustedHeaders(names: readonly string[]): string[] {\n\treturn names\n\t\t.map((h) => h.trim().toLowerCase())\n\t\t.filter((h) => h.length > 0 && HEADER_NAME_PATTERN.test(h));\n}\n\nfunction isValidHeaderName(name: string): boolean {\n\treturn HEADER_NAME_PATTERN.test(name);\n}\n\n/** Cache for the env-derived value. `null` means \"not yet parsed\". */\nlet _envCache: string[] | null = null;\n\n/** Test-only: clear the env cache so a fresh value is read on next call. */\nexport function _resetTrustedProxyHeadersCache(): void {\n\t_envCache = null;\n}\n\nfunction getEnvTrustedHeaders(): string[] {\n\tif (_envCache !== null) return _envCache;\n\tlet raw: string | undefined;\n\ttry {\n\t\t// Prefer process.env so SSR/container deployments can override this\n\t\t// value at runtime (Vite/Astro inline import.meta.env at build time,\n\t\t// which locks the value into the bundle). Fall back to import.meta.env\n\t\t// for bundler-managed environments where process.env isn't populated.\n\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- import.meta.env shape varies by bundler\n\t\tconst importMetaEnv = (import.meta as unknown as { env?: Record<string, string | undefined> })\n\t\t\t.env;\n\t\traw =\n\t\t\t(typeof process !== \"undefined\" ? process.env?.EMDASH_TRUSTED_PROXY_HEADERS : undefined) ||\n\t\t\timportMetaEnv?.EMDASH_TRUSTED_PROXY_HEADERS;\n\t} catch {\n\t\traw = undefined;\n\t}\n\tif (!raw) {\n\t\t_envCache = [];\n\t\treturn _envCache;\n\t}\n\t_envCache = raw\n\t\t.split(\",\")\n\t\t.map((s) => s.trim().toLowerCase())\n\t\t.filter((s) => s.length > 0 && isValidHeaderName(s));\n\treturn _envCache;\n}\n\n/**\n * Return the lowercased list of headers to trust for client-IP resolution.\n *\n * When `config?.trustedProxyHeaders` is explicitly set (even to `[]`), it\n * wins. Otherwise fall through to the env var, then to `[]`.\n */\nexport function getTrustedProxyHeaders(config: EmDashConfig | null | undefined): string[] {\n\tif (config && config.trustedProxyHeaders !== undefined) {\n\t\treturn config.trustedProxyHeaders\n\t\t\t.map((h) => h.trim().toLowerCase())\n\t\t\t.filter((h) => h.length > 0 && isValidHeaderName(h));\n\t}\n\treturn getEnvTrustedHeaders();\n}\n"],"mappings":";;;;;;AAwBA,MAAM,sBAAsB;;;;;;;AAQ5B,SAAgB,wBAAwB,OAAoC;AAC3E,QAAO,MACL,KAAK,MAAM,EAAE,MAAM,CAAC,aAAa,CAAC,CAClC,QAAQ,MAAM,EAAE,SAAS,KAAK,oBAAoB,KAAK,EAAE,CAAC;;AAG7D,SAAS,kBAAkB,MAAuB;AACjD,QAAO,oBAAoB,KAAK,KAAK;;;AAItC,IAAI,YAA6B;AAOjC,SAAS,uBAAiC;AACzC,KAAI,cAAc,KAAM,QAAO;CAC/B,IAAI;AACJ,KAAI;EAMH,MAAM,gBAAiB,OAAO,KAC5B;AACF,SACE,OAAO,YAAY,cAAc,QAAQ,KAAK,+BAA+B,WAC9E,eAAe;SACT;AACP,QAAM;;AAEP,KAAI,CAAC,KAAK;AACT,cAAY,EAAE;AACd,SAAO;;AAER,aAAY,IACV,MAAM,IAAI,CACV,KAAK,MAAM,EAAE,MAAM,CAAC,aAAa,CAAC,CAClC,QAAQ,MAAM,EAAE,SAAS,KAAK,kBAAkB,EAAE,CAAC;AACrD,QAAO;;;;;;;;AASR,SAAgB,uBAAuB,QAAmD;AACzF,KAAI,UAAU,OAAO,wBAAwB,OAC5C,QAAO,OAAO,oBACZ,KAAK,MAAM,EAAE,MAAM,CAAC,aAAa,CAAC,CAClC,QAAQ,MAAM,EAAE,SAAS,KAAK,kBAAkB,EAAE,CAAC;AAEtD,QAAO,sBAAsB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as CustomFieldValue } from "./types-
|
|
1
|
+
import { c as CustomFieldValue } from "./types-g_aFIdW0.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/database/repositories/types.d.ts
|
|
4
4
|
interface CreateContentInput {
|
|
@@ -208,4 +208,4 @@ declare class EmDashValidationError extends Error {
|
|
|
208
208
|
}
|
|
209
209
|
//#endregion
|
|
210
210
|
export { ContentSeo as a, EmDashValidationError as c, InvalidCursorError as d, UpdateContentInput as f, ContentItem as i, FindManyOptions as l, ContentBylineCredit as n, ContentSeoInput as o, ContentDateField as r, CreateContentInput as s, BylineSummary as t, FindManyResult as u };
|
|
211
|
-
//# sourceMappingURL=types-
|
|
211
|
+
//# sourceMappingURL=types-BcLUUbbR.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types-
|
|
1
|
+
{"version":3,"file":"types-BcLUUbbR.d.mts","names":[],"sources":["../src/database/repositories/types.ts"],"mappings":";;;UAaiB,kBAAA;EAChB,IAAA;EACA,IAAA;EACA,IAAA,EAAM,MAAA;EACN,MAAA;EACA,QAAA;EACA,eAAA;EACA,MAAA;EACA,aAAA;EACA,WAAA;EALA;EAOA,SAAA;AAAA;AAAA,UAGgB,kB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A;EACA,IAAA,EAAM,MAAA;EACN,QAAA;EACA,eAAA;EACA,MAAA,GAAS,aAAA;EACT,OAAA,GAAU,mBAAA;EACV,SAAA;EACA,SAAA;EACA,WAAA;EACA,WAAA;EACA,cAAA;EACA,eAAA;EACA,OAAA;EACA,MAAA;EACA,gBAAA;;EAEA,GAAA,GAAM,UAAA;;;;;;;;;;;EAWN,QAAA,GAAW,MAAA;AAAA;AAAA,cAGC,qBAAA,SAA8B,KAAA;EAGlC,OAAA;cADP,OAAA,UACO,OAAA;AAAA"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { d as FieldType } from "./types-
|
|
1
|
+
import { d as FieldType } from "./types-g_aFIdW0.mjs";
|
|
2
2
|
import { z } from "astro/zod";
|
|
3
3
|
import { CAPABILITY_RENAMES, CurrentPluginCapability, DeclaredAccess, DeprecatedPluginCapability, ManifestHookEntry, ManifestRouteEntry, PluginCapability, PluginStorageConfig, StorageCollectionConfig, isDeprecatedCapability, normalizeCapabilities, normalizeCapability } from "@emdash-cms/plugin-types";
|
|
4
4
|
import "react/jsx-runtime";
|
|
@@ -1220,4 +1220,4 @@ interface PluginManifest {
|
|
|
1220
1220
|
}
|
|
1221
1221
|
//#endregion
|
|
1222
1222
|
export { ModerationDecision as $, CurrentPluginCapability as A, StoredComment as At, HookConfig as B, ContentHookEvent as C, RequestMeta as Ct, ContentStateChangeEvent as D, RouteContext as Dt, ContentScheduleStateChangeEvent as E, ResolvedPluginHooks as Et, EmailBeforeSendHandler as F, normalizeCapabilities as Ft, LifecycleHandler as G, HttpAccess as H, EmailDeliverEvent as I, normalizeCapability as It, MediaAfterUploadEvent as J, LogAccess as K, EmailDeliverHandler as L, Element as Lt, EmailAfterSendEvent as M, UninstallHandler as Mt, EmailAfterSendHandler as N, WhereClause as Nt, CronEvent as O, StorageCollection as Ot, EmailBeforeSendEvent as P, isDeprecatedCapability as Pt, MediaUploadEvent as Q, EmailMessage as R, ContentDeleteEvent as S, QueryOptions as St, ContentRestoreStateChangeEvent as T, ResolvedPlugin as Tt, KVAccess as U, HookName as V, LifecycleEvent as W, MediaBeforeUploadHandler as X, MediaAfterUploadHandler as Y, MediaItem as Z, ContentAfterScheduleHandler as _, PluginRoute as _t, CommentAfterCreateHandler as a, PageMetadataHandler as at, ContentBeforeDeleteHandler as b, PortableTextBlockField as bt, CommentBeforeCreateEvent as c, PaginatedResult as ct, CommentModerateHandler as d, PluginAdminPage as dt, PageFragmentContribution as et, ContentAccess as f, PluginCapability as ft, ContentAfterSaveHandler as g, PluginManifest as gt, ContentAfterRestoreHandler as h, PluginHooks as ht, CommentAfterCreateEvent as i, PageMetadataEvent as it, DeprecatedPluginCapability as j, UninstallEvent as jt, CronHandler as k, StorageCollectionConfig as kt, CommentBeforeCreateHandler as l, PluginAdminConfig as lt, ContentAfterPublishHandler as m, PluginDefinition as mt, CAPABILITY_RENAMES as n, PageFragmentHandler as nt, CommentAfterModerateEvent as o, PageMetadataLinkRel as ot, ContentAfterDeleteHandler as p, PluginContext as pt, MediaAccess as q, CollectionCommentSettings as r, PageMetadataContribution as rt, CommentAfterModerateHandler as s, PagePlacement as st, BreadcrumbItem as t, PageFragmentEvent as tt, CommentModerateEvent as u, PluginAdminExports as ut, ContentAfterUnpublishHandler as v, PluginStorageConfig as vt, ContentPublishStateChangeEvent as w, ResolvedHook as wt, ContentBeforeSaveHandler as x, PublicPageContext as xt, ContentAfterUnscheduleHandler as y, PortableTextBlockConfig as yt, FieldWidgetConfig as z };
|
|
1223
|
-
//# sourceMappingURL=types-
|
|
1223
|
+
//# sourceMappingURL=types-CGbYowGQ.d.mts.map
|