emdash 0.25.1 → 0.27.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-DAAjOID4.d.mts → adapters-u037EnTR.d.mts} +1 -1
- package/dist/{adapters-DAAjOID4.d.mts.map → adapters-u037EnTR.d.mts.map} +1 -1
- package/dist/api/route-utils.d.mts +3 -3
- package/dist/api/route-utils.mjs +11 -11
- package/dist/api/schemas/index.d.mts +1 -1
- package/dist/{api-D2_sbavn.mjs → api-80kycR9o.mjs} +86 -30
- package/dist/api-80kycR9o.mjs.map +1 -0
- package/dist/{apply-Bk2mAuLn.mjs → apply-DSypk6Iu.mjs} +20 -18
- package/dist/apply-DSypk6Iu.mjs.map +1 -0
- package/dist/astro/index.d.mts +11 -10
- package/dist/astro/index.d.mts.map +1 -1
- package/dist/astro/index.mjs +12 -3
- package/dist/astro/index.mjs.map +1 -1
- package/dist/astro/middleware/auth.d.mts +10 -9
- package/dist/astro/middleware/auth.d.mts.map +1 -1
- package/dist/astro/middleware/auth.mjs +4 -3
- package/dist/astro/middleware/auth.mjs.map +1 -1
- package/dist/astro/middleware/redirect.mjs +4 -4
- package/dist/astro/middleware.d.mts +2 -9
- package/dist/astro/middleware.d.mts.map +1 -1
- package/dist/astro/middleware.mjs +86 -85
- package/dist/astro/middleware.mjs.map +1 -1
- package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs +3 -3
- package/dist/astro/routes/api/admin/allowed-domains/index.mjs +3 -3
- package/dist/astro/routes/api/admin/api-tokens/_id_.mjs +2 -2
- package/dist/astro/routes/api/admin/api-tokens/index.mjs +3 -3
- package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +3 -3
- package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +4 -4
- package/dist/astro/routes/api/admin/byline-fields/index.mjs +4 -4
- package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +4 -4
- package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +10 -10
- package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +10 -10
- package/dist/astro/routes/api/admin/bylines/index.mjs +10 -10
- package/dist/astro/routes/api/admin/comments/_id_/status.mjs +8 -8
- package/dist/astro/routes/api/admin/comments/_id_.mjs +6 -6
- package/dist/astro/routes/api/admin/comments/bulk.mjs +7 -7
- package/dist/astro/routes/api/admin/comments/counts.mjs +6 -6
- package/dist/astro/routes/api/admin/comments/index.mjs +7 -7
- 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 +3 -3
- package/dist/astro/routes/api/admin/oauth-clients/index.mjs +3 -3
- package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +29 -29
- package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +29 -29
- package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +29 -29
- package/dist/astro/routes/api/admin/plugins/_id_/index.mjs.map +1 -1
- package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +28 -28
- package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +28 -28
- package/dist/astro/routes/api/admin/plugins/index.mjs +29 -29
- 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 +28 -28
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +28 -28
- package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +28 -28
- package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +28 -28
- package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +29 -29
- package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +28 -28
- package/dist/astro/routes/api/admin/plugins/registry/install.mjs +29 -29
- package/dist/astro/routes/api/admin/plugins/updates.mjs +28 -28
- package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +28 -28
- package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +3 -3
- package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +28 -28
- 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 +3 -3
- package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +2 -2
- package/dist/astro/routes/api/admin/users/index.mjs +3 -3
- package/dist/astro/routes/api/auth/dev-bypass.mjs +3 -3
- package/dist/astro/routes/api/auth/invite/accept.mjs +2 -2
- package/dist/astro/routes/api/auth/invite/complete.mjs +3 -3
- package/dist/astro/routes/api/auth/invite/index.mjs +3 -3
- package/dist/astro/routes/api/auth/invite/register-options.mjs +3 -3
- package/dist/astro/routes/api/auth/logout.mjs +2 -2
- package/dist/astro/routes/api/auth/magic-link/send.mjs +4 -4
- package/dist/astro/routes/api/auth/magic-link/verify.mjs +2 -2
- package/dist/astro/routes/api/auth/me.mjs +4 -4
- package/dist/astro/routes/api/auth/passkey/_id_.mjs +3 -3
- package/dist/astro/routes/api/auth/passkey/index.mjs +2 -2
- package/dist/astro/routes/api/auth/passkey/options.mjs +4 -4
- package/dist/astro/routes/api/auth/passkey/register/options.mjs +3 -3
- package/dist/astro/routes/api/auth/passkey/register/verify.mjs +3 -3
- package/dist/astro/routes/api/auth/passkey/verify.mjs +3 -3
- package/dist/astro/routes/api/auth/signup/complete.mjs +3 -3
- package/dist/astro/routes/api/auth/signup/request.mjs +4 -4
- package/dist/astro/routes/api/auth/signup/verify.mjs +2 -2
- package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +7 -7
- package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +7 -7
- 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 +4 -4
- package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +4 -4
- 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 +4 -4
- package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +9 -9
- 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 +4 -4
- package/dist/astro/routes/api/content/_collection_/authors.mjs +3 -3
- package/dist/astro/routes/api/content/_collection_/index.mjs +4 -4
- package/dist/astro/routes/api/content/_collection_/trash.mjs +4 -4
- package/dist/astro/routes/api/dashboard.mjs +8 -8
- package/dist/astro/routes/api/dev/emails.mjs +2 -2
- package/dist/astro/routes/api/import/probe.d.mts +3 -3
- package/dist/astro/routes/api/import/probe.mjs +4 -4
- package/dist/astro/routes/api/import/wordpress/analyze.mjs +3 -3
- package/dist/astro/routes/api/import/wordpress/execute.d.mts +10 -9
- package/dist/astro/routes/api/import/wordpress/execute.d.mts.map +1 -1
- package/dist/astro/routes/api/import/wordpress/execute.mjs +9 -9
- package/dist/astro/routes/api/import/wordpress/media.d.mts +10 -9
- package/dist/astro/routes/api/import/wordpress/media.d.mts.map +1 -1
- package/dist/astro/routes/api/import/wordpress/media.mjs +4 -4
- package/dist/astro/routes/api/import/wordpress/prepare.mjs +6 -6
- package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +5 -5
- package/dist/astro/routes/api/import/wordpress-plugin/analyze.d.mts +1 -1
- package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +4 -4
- package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +1 -1
- package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +7 -7
- package/dist/astro/routes/api/manifest.d.mts.map +1 -1
- package/dist/astro/routes/api/manifest.mjs +13 -4
- package/dist/astro/routes/api/manifest.mjs.map +1 -1
- package/dist/astro/routes/api/mcp.mjs +34 -34
- package/dist/astro/routes/api/media/_id_/confirm.mjs +4 -4
- package/dist/astro/routes/api/media/_id_.mjs +4 -4
- 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 +4 -4
- package/dist/astro/routes/api/media.mjs +5 -5
- package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +6 -6
- package/dist/astro/routes/api/menus/_name_/items.mjs +6 -6
- package/dist/astro/routes/api/menus/_name_/reorder.mjs +6 -6
- package/dist/astro/routes/api/menus/_name_/translations.mjs +6 -6
- package/dist/astro/routes/api/menus/_name_.mjs +6 -6
- package/dist/astro/routes/api/menus/index.mjs +6 -6
- package/dist/astro/routes/api/oauth/device/authorize.mjs +3 -3
- package/dist/astro/routes/api/oauth/device/code.mjs +4 -4
- package/dist/astro/routes/api/oauth/device/token.mjs +4 -4
- package/dist/astro/routes/api/oauth/register.mjs +2 -2
- package/dist/astro/routes/api/oauth/token/refresh.mjs +3 -3
- package/dist/astro/routes/api/oauth/token/revoke.mjs +3 -3
- package/dist/astro/routes/api/oauth/token.mjs +2 -2
- package/dist/astro/routes/api/openapi.json.mjs +2 -2
- package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +3 -3
- package/dist/astro/routes/api/redirects/404s/index.mjs +6 -6
- package/dist/astro/routes/api/redirects/404s/summary.mjs +6 -6
- package/dist/astro/routes/api/redirects/_id_.mjs +7 -7
- package/dist/astro/routes/api/redirects/index.mjs +7 -7
- 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 +28 -28
- package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +28 -28
- package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +28 -28
- package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +28 -28
- package/dist/astro/routes/api/schema/collections/index.mjs +28 -28
- package/dist/astro/routes/api/schema/index.mjs +6 -6
- package/dist/astro/routes/api/schema/orphans/_slug_.mjs +28 -28
- package/dist/astro/routes/api/schema/orphans/index.mjs +28 -28
- package/dist/astro/routes/api/search/enable.mjs +7 -7
- package/dist/astro/routes/api/search/index.mjs +6 -6
- package/dist/astro/routes/api/search/rebuild.mjs +7 -7
- package/dist/astro/routes/api/search/stats.mjs +6 -6
- package/dist/astro/routes/api/search/suggest.mjs +6 -6
- package/dist/astro/routes/api/sections/_slug_.mjs +6 -6
- package/dist/astro/routes/api/sections/index.mjs +6 -6
- package/dist/astro/routes/api/settings/email.mjs +4 -4
- package/dist/astro/routes/api/settings.mjs +9 -9
- package/dist/astro/routes/api/setup/admin-verify.mjs +3 -3
- package/dist/astro/routes/api/setup/admin.mjs +3 -3
- package/dist/astro/routes/api/setup/dev-bypass.d.mts.map +1 -1
- package/dist/astro/routes/api/setup/dev-bypass.mjs +20 -18
- 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 +18 -18
- package/dist/astro/routes/api/setup/status.mjs +3 -3
- package/dist/astro/routes/api/snapshot.mjs +3 -3
- package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +9 -9
- package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +9 -9
- package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +9 -9
- package/dist/astro/routes/api/taxonomies/index.mjs +9 -9
- package/dist/astro/routes/api/themes/preview.mjs +3 -3
- package/dist/astro/routes/api/typegen.mjs +5 -5
- package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +4 -4
- package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +6 -6
- package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +6 -6
- package/dist/astro/routes/api/widget-areas/_name_.mjs +5 -5
- package/dist/astro/routes/api/widget-areas/index.mjs +6 -6
- package/dist/astro/routes/api/widget-components.mjs +2 -2
- package/dist/astro/routes/robots.txt.mjs +5 -5
- package/dist/astro/routes/sitemap-_collection_.xml.mjs +10 -9
- package/dist/astro/routes/sitemap-_collection_.xml.mjs.map +1 -1
- package/dist/astro/routes/sitemap.xml.mjs +5 -5
- package/dist/astro/types.d.mts +12 -10
- package/dist/astro/types.d.mts.map +1 -1
- package/dist/auth/providers/github.d.mts +1 -1
- package/dist/auth/providers/google.d.mts +1 -1
- package/dist/{authorize-CuxZ0i2t.mjs → authorize-C3a_zGsM.mjs} +2 -2
- package/dist/{authorize-CuxZ0i2t.mjs.map → authorize-C3a_zGsM.mjs.map} +1 -1
- package/dist/{byline-C-YajfV7.mjs → byline-DEKSVPTy.mjs} +6 -6
- package/dist/{byline-C-YajfV7.mjs.map → byline-DEKSVPTy.mjs.map} +1 -1
- package/dist/{byline-fields-KD3JFRuH.d.mts → byline-fields-CtQ6blXd.d.mts} +32 -32
- package/dist/{byline-fields-KD3JFRuH.d.mts.map → byline-fields-CtQ6blXd.d.mts.map} +1 -1
- package/dist/{bylines-CPc_q2Vd.mjs → bylines-CiqgTHWF.mjs} +5 -5
- package/dist/{bylines-CPc_q2Vd.mjs.map → bylines-CiqgTHWF.mjs.map} +1 -1
- package/dist/{bylines-D4KADDAi.mjs → bylines-Ds4-otXl.mjs} +4 -4
- package/dist/{bylines-D4KADDAi.mjs.map → bylines-Ds4-otXl.mjs.map} +1 -1
- package/dist/{cache-C35VWD5D.mjs → cache-Ciu3e3AF.mjs} +2 -2
- package/dist/{cache-C35VWD5D.mjs.map → cache-Ciu3e3AF.mjs.map} +1 -1
- package/dist/{chunks-BHgcHh2C.mjs → chunks-CZFiauig.mjs} +2 -2
- package/dist/{chunks-BHgcHh2C.mjs.map → chunks-CZFiauig.mjs.map} +1 -1
- package/dist/cli/index.mjs +17 -17
- 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/{comment-BDx50EX5.mjs → comment-CH1IrFFs.mjs} +3 -3
- package/dist/{comment-BDx50EX5.mjs.map → comment-CH1IrFFs.mjs.map} +1 -1
- package/dist/{comment-reaction-Gv_pgfI3.mjs → comment-reaction-kruNY-kP.mjs} +2 -2
- package/dist/{comment-reaction-Gv_pgfI3.mjs.map → comment-reaction-kruNY-kP.mjs.map} +1 -1
- package/dist/{comments-CXHuQ6jI.mjs → comments-BUJyXbgq.mjs} +3 -3
- package/dist/{comments-CXHuQ6jI.mjs.map → comments-BUJyXbgq.mjs.map} +1 -1
- package/dist/{content-B43-YrIq.mjs → content-RmfHoWqK.mjs} +4 -4
- package/dist/{content-B43-YrIq.mjs.map → content-RmfHoWqK.mjs.map} +1 -1
- package/dist/{context-BW3N7wyt.mjs → context-CzUU_WzL.mjs} +7 -7
- package/dist/{context-BW3N7wyt.mjs.map → context-CzUU_WzL.mjs.map} +1 -1
- package/dist/{dashboard-FIe0S512.mjs → dashboard-CVyGhift.mjs} +4 -4
- package/dist/{dashboard-FIe0S512.mjs.map → dashboard-CVyGhift.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/{error-DXnK2wF4.mjs → error-BHkLZk-w.mjs} +2 -2
- package/dist/{error-DXnK2wF4.mjs.map → error-BHkLZk-w.mjs.map} +1 -1
- package/dist/{field-defs-cache-CYYx8xlG.mjs → field-defs-cache-BA-8ZPiT.mjs} +2 -2
- package/dist/{field-defs-cache-CYYx8xlG.mjs.map → field-defs-cache-BA-8ZPiT.mjs.map} +1 -1
- package/dist/{fts-manager-DW_NR-Fs.mjs → fts-manager-Db9jGavf.mjs} +2 -2
- package/dist/{fts-manager-DW_NR-Fs.mjs.map → fts-manager-Db9jGavf.mjs.map} +1 -1
- package/dist/{index-Cz6_JBL3.d.mts → index-CDZZjrLT.d.mts} +2430 -2363
- package/dist/index-CDZZjrLT.d.mts.map +1 -0
- package/dist/{index-qbL02uhs.d.mts → index-DGIjmUXQ.d.mts} +3 -3
- package/dist/{index-qbL02uhs.d.mts.map → index-DGIjmUXQ.d.mts.map} +1 -1
- package/dist/index.d.mts +16 -15
- package/dist/index.mjs +38 -38
- package/dist/{load-DMFi4n1p.mjs → load-DpHICVPh.mjs} +2 -2
- package/dist/{load-DMFi4n1p.mjs.map → load-DpHICVPh.mjs.map} +1 -1
- package/dist/{loader-DrpofRon.mjs → loader-4K37qA-y.mjs} +81 -18
- package/dist/loader-4K37qA-y.mjs.map +1 -0
- package/dist/{manifest-schema-BOfPXse0.mjs → manifest-schema-kPGX7VS-.mjs} +3 -1
- package/dist/manifest-schema-kPGX7VS-.mjs.map +1 -0
- package/dist/media/local-runtime.d.mts +11 -10
- package/dist/media/local-runtime.d.mts.map +1 -1
- package/dist/media/local-runtime.mjs +5 -5
- package/dist/{media-BjKxjzk8.mjs → media-C0nRRfs1.mjs} +2 -2
- package/dist/{media-BjKxjzk8.mjs.map → media-C0nRRfs1.mjs.map} +1 -1
- package/dist/{menus-CxqJ-z-N.mjs → menus-DzRyC1ID.mjs} +50 -68
- package/dist/menus-DzRyC1ID.mjs.map +1 -0
- package/dist/{menus-8O6xNcYW.mjs → menus-SL2K0xq2.mjs} +3 -3
- package/dist/{menus-8O6xNcYW.mjs.map → menus-SL2K0xq2.mjs.map} +1 -1
- package/dist/object-cache/memory.d.mts +1 -1
- package/dist/{object-cache-SEb2IM4Z.mjs → object-cache-CHbHv83-.mjs} +8 -4
- package/dist/object-cache-CHbHv83-.mjs.map +1 -0
- package/dist/{options-BvClpP5Q.d.mts → options-41nCWqi9.d.mts} +2 -2
- package/dist/{options-BvClpP5Q.d.mts.map → options-41nCWqi9.d.mts.map} +1 -1
- package/dist/page/index.d.mts +6 -3
- package/dist/page/index.d.mts.map +1 -1
- package/dist/page/index.mjs +3 -2
- package/dist/page/index.mjs.map +1 -1
- package/dist/{parse-DqMWHQ8x.mjs → parse-CqyZj3Hp.mjs} +2 -2
- package/dist/{parse-DqMWHQ8x.mjs.map → parse-CqyZj3Hp.mjs.map} +1 -1
- package/dist/plugin-types.d.mts +4 -2
- package/dist/plugin-types.d.mts.map +1 -1
- package/dist/plugin-utils.d.mts +10 -9
- package/dist/plugin-utils.d.mts.map +1 -1
- package/dist/plugins/adapt-sandbox-entry.d.mts +10 -9
- package/dist/plugins/adapt-sandbox-entry.d.mts.map +1 -1
- package/dist/plugins/adapt-sandbox-entry.mjs +1 -1
- package/dist/{query-34pfm02Q.mjs → query-B0M-9LYR.mjs} +14 -14
- package/dist/{query-34pfm02Q.mjs.map → query-B0M-9LYR.mjs.map} +1 -1
- package/dist/{rate-limit-CBQK4ygJ.mjs → rate-limit-BwoUdIpC.mjs} +2 -2
- package/dist/{rate-limit-CBQK4ygJ.mjs.map → rate-limit-BwoUdIpC.mjs.map} +1 -1
- package/dist/{redirect-C1KVGYWe.mjs → redirect-lMOzG04S.mjs} +2 -2
- package/dist/{redirect-C1KVGYWe.mjs.map → redirect-lMOzG04S.mjs.map} +1 -1
- package/dist/{redirects-DgnypVir.mjs → redirects-9218MmYl.mjs} +3 -3
- package/dist/{redirects-DgnypVir.mjs.map → redirects-9218MmYl.mjs.map} +1 -1
- package/dist/{registry-3aOAS4My.mjs → registry-DP-iEtdR.mjs} +4 -4
- package/dist/{registry-3aOAS4My.mjs.map → registry-DP-iEtdR.mjs.map} +1 -1
- package/dist/{runner-CEtq-6Sm.d.mts → runner-BbR3DfrL.d.mts} +2 -2
- package/dist/{runner-CEtq-6Sm.d.mts.map → runner-BbR3DfrL.d.mts.map} +1 -1
- package/dist/{runner-BsquExlK.mjs → runner-CFngB4WZ.mjs} +296 -191
- package/dist/runner-CFngB4WZ.mjs.map +1 -0
- package/dist/runtime.d.mts +10 -9
- package/dist/runtime.d.mts.map +1 -1
- package/dist/runtime.mjs +2 -2
- package/dist/scheduled-publish-BMljtY5G.d.mts +11 -0
- package/dist/scheduled-publish-BMljtY5G.d.mts.map +1 -0
- package/dist/{schema-BGwx8AQY.mjs → schema-BfJ7bIXH.mjs} +5 -5
- package/dist/{schema-BGwx8AQY.mjs.map → schema-BfJ7bIXH.mjs.map} +1 -1
- package/dist/{search-Gl747zMP.mjs → search-C7t3PH1J.mjs} +6 -4
- package/dist/search-C7t3PH1J.mjs.map +1 -0
- package/dist/{sections-C-umuuLj.mjs → sections-Dm0CVX23.mjs} +3 -3
- package/dist/{sections-C-umuuLj.mjs.map → sections-Dm0CVX23.mjs.map} +1 -1
- package/dist/seed/index.d.mts +2 -2
- package/dist/seed/index.mjs +15 -15
- package/dist/{seo-BNzkiK_W.mjs → seo-Dd3tbY_k.mjs} +3 -3
- package/dist/{seo-BNzkiK_W.mjs.map → seo-Dd3tbY_k.mjs.map} +1 -1
- package/dist/{service-CQHK_10l.mjs → service-CTrqp_Jy.mjs} +2 -2
- package/dist/{service-CQHK_10l.mjs.map → service-CTrqp_Jy.mjs.map} +1 -1
- package/dist/{settings-C4tXRYiG.mjs → settings-BX8cWBus.mjs} +4 -4
- package/dist/{settings-C4tXRYiG.mjs.map → settings-BX8cWBus.mjs.map} +1 -1
- package/dist/{settings-fPSR6dJa.mjs → settings-CZ7ZP9cW.mjs} +3 -3
- package/dist/{settings-fPSR6dJa.mjs.map → settings-CZ7ZP9cW.mjs.map} +1 -1
- package/dist/storage/local.d.mts +1 -1
- package/dist/storage/s3.d.mts +1 -1
- package/dist/{taxonomies-DbAtL6m4.mjs → taxonomies-DChKcVxf.mjs} +5 -4
- package/dist/taxonomies-DChKcVxf.mjs.map +1 -0
- package/dist/{taxonomies-n8w72lLQ.mjs → taxonomies-ckPjz-6d.mjs} +75 -20
- package/dist/taxonomies-ckPjz-6d.mjs.map +1 -0
- package/dist/{taxonomy-BBUlGug5.mjs → taxonomy-Cru-he6s.mjs} +4 -4
- package/dist/{taxonomy-BBUlGug5.mjs.map → taxonomy-Cru-he6s.mjs.map} +1 -1
- package/dist/{transport-BZ-03aFT.d.mts → transport-Blrl2k_o.d.mts} +1 -1
- package/dist/{transport-BZ-03aFT.d.mts.map → transport-Blrl2k_o.d.mts.map} +1 -1
- package/dist/{types-h2Cwbzi2.d.mts → types-BYnDBVwe.d.mts} +24 -5
- package/dist/{types-h2Cwbzi2.d.mts.map → types-BYnDBVwe.d.mts.map} +1 -1
- package/dist/{types-BG8_XTLj.d.mts → types-BkZ8DUEI.d.mts} +1 -1
- package/dist/{types-BG8_XTLj.d.mts.map → types-BkZ8DUEI.d.mts.map} +1 -1
- package/dist/{types-DrYMm9s5.d.mts → types-ByChcBgE.d.mts} +1 -1
- package/dist/{types-DrYMm9s5.d.mts.map → types-ByChcBgE.d.mts.map} +1 -1
- package/dist/{types-BWqGVhFn.d.mts → types-CvuKO5Pn.d.mts} +1 -1
- package/dist/{types-BWqGVhFn.d.mts.map → types-CvuKO5Pn.d.mts.map} +1 -1
- package/dist/{types-CmI1OyQg.mjs → types-DU4TSFS5.mjs} +2 -2
- package/dist/{types-CmI1OyQg.mjs.map → types-DU4TSFS5.mjs.map} +1 -1
- package/dist/{types-CUsXGRVj.d.mts → types-Dbqff978.d.mts} +1 -1
- package/dist/{types-CUsXGRVj.d.mts.map → types-Dbqff978.d.mts.map} +1 -1
- package/dist/{types-fS7-VTdR.d.mts → types-Y09-wtyU.d.mts} +1 -1
- package/dist/{types-fS7-VTdR.d.mts.map → types-Y09-wtyU.d.mts.map} +1 -1
- package/dist/{types-B-gIxFCE.d.mts → types-xIfVRNLp.d.mts} +38 -1
- package/dist/types-xIfVRNLp.d.mts.map +1 -0
- package/dist/{user-JAuc8VUf.mjs → user-DgGbKL9s.mjs} +3 -3
- package/dist/{user-JAuc8VUf.mjs.map → user-DgGbKL9s.mjs.map} +1 -1
- package/dist/{validate-Va_An3qb.d.mts → validate-9ECmtEpJ.d.mts} +10 -5
- package/dist/{validate-Va_An3qb.d.mts.map → validate-9ECmtEpJ.d.mts.map} +1 -1
- package/dist/{validate-BzXHWnkV.mjs → validate-CRkcYZAR.mjs} +2 -2
- package/dist/{validate-BzXHWnkV.mjs.map → validate-CRkcYZAR.mjs.map} +1 -1
- package/dist/{validation-B6DKPTtU.mjs → validation-sR26SOwD.mjs} +5 -5
- package/dist/{validation-B6DKPTtU.mjs.map → validation-sR26SOwD.mjs.map} +1 -1
- package/dist/version-CrqhKGWn.mjs +7 -0
- package/dist/{version-DHdCA24u.mjs.map → version-CrqhKGWn.mjs.map} +1 -1
- package/dist/{widgets-C2RbFN0G.mjs → widgets-DRgtn7Cl.mjs} +2 -2
- package/dist/{widgets-C2RbFN0G.mjs.map → widgets-DRgtn7Cl.mjs.map} +1 -1
- package/dist/{zod-generator-xEHODMJf.mjs → zod-generator-C5JaV--i.mjs} +6 -3
- package/dist/zod-generator-C5JaV--i.mjs.map +1 -0
- package/package.json +8 -8
- package/src/api/handlers/content.ts +59 -16
- package/src/api/handlers/plugins.ts +77 -10
- package/src/api/handlers/taxonomies.ts +5 -1
- package/src/astro/integration/virtual-modules.ts +15 -0
- package/src/astro/integration/vite-config.ts +19 -1
- package/src/astro/middleware/auth.ts +1 -0
- package/src/astro/middleware.ts +1 -0
- package/src/astro/routes/api/admin/plugins/[id]/disable.ts +6 -1
- package/src/astro/routes/api/admin/plugins/[id]/enable.ts +6 -1
- package/src/astro/routes/api/admin/plugins/[id]/index.ts +1 -0
- package/src/astro/routes/api/admin/plugins/index.ts +1 -0
- package/src/astro/routes/api/manifest.ts +20 -1
- package/src/astro/routes/api/setup/dev-bypass.ts +7 -2
- package/src/astro/routes/sitemap-[collection].xml.ts +5 -4
- package/src/astro/types.ts +4 -0
- package/src/cli/commands/seed.ts +1 -1
- package/src/components/EmDashHead.astro +23 -3
- package/src/components/JsonLdScript.astro +9 -0
- package/src/components/LiveSearch.astro +40 -4
- package/src/components/live-search-routing.ts +30 -0
- package/src/database/migrations/036_i18n_menus_and_taxonomies.ts +39 -18
- package/src/database/migrations/046_media_usage_index.ts +115 -0
- package/src/database/migrations/047_restore_taxonomy_parent_index.ts +29 -0
- package/src/database/migrations/048_restore_content_taxonomies_term_index.ts +32 -0
- package/src/database/migrations/runner.ts +6 -0
- package/src/database/repositories/media-usage.ts +444 -0
- package/src/database/types.ts +39 -0
- package/src/emdash-runtime.ts +61 -52
- package/src/index.ts +3 -0
- package/src/loader.ts +110 -31
- package/src/media/usage/extractor.ts +302 -0
- package/src/media/usage/types.ts +46 -0
- package/src/object-cache/index.ts +8 -2
- package/src/page/metadata.ts +23 -3
- package/src/plugin-types.ts +10 -0
- package/src/plugins/define-plugin.ts +14 -5
- package/src/plugins/hooks.ts +53 -65
- package/src/plugins/index.ts +5 -0
- package/src/plugins/manager.ts +22 -0
- package/src/plugins/manifest-schema.ts +2 -0
- package/src/plugins/types.ts +35 -3
- package/src/schema/zod-generator.ts +9 -1
- package/src/search/query.ts +3 -0
- package/src/search/types.ts +2 -0
- package/src/seed/apply.ts +8 -2
- package/src/seed/types.ts +6 -1
- package/src/taxonomies/index.ts +121 -18
- package/dist/api-D2_sbavn.mjs.map +0 -1
- package/dist/apply-Bk2mAuLn.mjs.map +0 -1
- package/dist/index-Cz6_JBL3.d.mts.map +0 -1
- package/dist/loader-DrpofRon.mjs.map +0 -1
- package/dist/manifest-schema-BOfPXse0.mjs.map +0 -1
- package/dist/menus-CxqJ-z-N.mjs.map +0 -1
- package/dist/object-cache-SEb2IM4Z.mjs.map +0 -1
- package/dist/runner-BsquExlK.mjs.map +0 -1
- package/dist/search-Gl747zMP.mjs.map +0 -1
- package/dist/taxonomies-DbAtL6m4.mjs.map +0 -1
- package/dist/taxonomies-n8w72lLQ.mjs.map +0 -1
- package/dist/types-B-gIxFCE.d.mts.map +0 -1
- package/dist/version-DHdCA24u.mjs +0 -7
- package/dist/zod-generator-xEHODMJf.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"menus-8O6xNcYW.mjs","names":[],"sources":["../src/database/repositories/menu.ts","../src/api/handlers/menus.ts"],"sourcesContent":["/**\n * Menu repository\n *\n * Owns every SQL touch for `_emdash_menus` and `_emdash_menu_items`, plus the\n * row→entity mapping. Matches the architecture used by every other resource\n * (content, taxonomies, redirects, comments, media): handlers stay thin and\n * orchestrate; the repository is the single place where snake_case DB columns\n * become camelCase entities (and vice versa).\n *\n * i18n: menus are per-locale. `(name, locale)` is unique. Translations of the\n * same menu share a `translation_group` ULID. Menu item `reference_id` stores\n * the referenced content's translation_group (not a specific row id) so a\n * single menu item survives content translations.\n */\n\nimport type { Kysely, Selectable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { invalidateMenuObjectCache } from \"../../object-cache/index.js\";\nimport { withTransaction } from \"../transaction.js\";\nimport type { Database, MenuItemTable, MenuTable } from \"../types.js\";\n\n/**\n * Thrown from inside a repository transaction when the menu the caller\n * resolved earlier has since been deleted. Handlers translate this to a\n * `NOT_FOUND` API response. Necessary because D1 disables FK enforcement\n * (so `ON DELETE CASCADE` won't fire), and an unchecked `setItems` would\n * happily insert items whose `menu_id` no longer exists, leaving orphans.\n */\nexport class MenuGoneError extends Error {\n\tconstructor(public readonly menuId: string) {\n\t\tsuper(`Menu ${menuId} was deleted while being modified`);\n\t\tthis.name = \"MenuGoneError\";\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Entity shapes (camelCase — what the API returns)\n// ---------------------------------------------------------------------------\n\nexport interface Menu {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\tlocale: string;\n\ttranslationGroup: string | null;\n}\n\nexport interface MenuItem {\n\tid: string;\n\tmenuId: string;\n\tparentId: string | null;\n\tsortOrder: number;\n\ttype: string;\n\treferenceCollection: string | null;\n\treferenceId: string | null;\n\tcustomUrl: string | null;\n\tlabel: string;\n\ttitleAttr: string | null;\n\ttarget: string | null;\n\tcssClasses: string | null;\n\tcreatedAt: string;\n\tlocale: string;\n\ttranslationGroup: string | null;\n}\n\nexport interface MenuListItem extends Menu {\n\titemCount: number;\n}\n\nexport interface MenuWithItems extends Menu {\n\titems: MenuItem[];\n}\n\nexport interface MenuTranslation {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tlocale: string;\n\tupdatedAt: string;\n}\n\n// ---------------------------------------------------------------------------\n// Input shapes\n// ---------------------------------------------------------------------------\n\nexport interface CreateMenuInput {\n\tname: string;\n\tlabel: string;\n\tlocale?: string;\n\t/**\n\t * When set, the new menu joins the source menu's translation_group and\n\t * inherits its items (cloned, with new ULIDs but the same translation_group\n\t * per item so nav entries stay logically identified across translations).\n\t */\n\ttranslationOf?: string;\n}\n\nexport interface UpdateMenuInput {\n\tlabel?: string;\n}\n\nexport interface CreateMenuItemInput {\n\ttype: string;\n\tlabel: string;\n\treferenceCollection?: string;\n\treferenceId?: string;\n\tcustomUrl?: string;\n\ttarget?: string;\n\ttitleAttr?: string;\n\tcssClasses?: string;\n\tparentId?: string;\n\tsortOrder?: number;\n}\n\nexport interface UpdateMenuItemInput {\n\tlabel?: string;\n\tcustomUrl?: string;\n\ttarget?: string;\n\ttitleAttr?: string;\n\tcssClasses?: string;\n\tparentId?: string | null;\n\tsortOrder?: number;\n}\n\n/**\n * Item shape used by `setItems()`. Items are placed by array order. Children\n * point at parents via `parentIndex` (must reference an earlier index, so the\n * insert can resolve parents before children). The validation of that ordering\n * lives at the API boundary (`handleMenuSetItems`) so REST/MCP callers receive\n * the same error shape.\n */\nexport interface SetMenuItem {\n\tlabel: string;\n\ttype: \"custom\" | \"page\" | \"post\" | \"taxonomy\" | \"collection\";\n\tcustomUrl?: string;\n\treferenceCollection?: string;\n\treferenceId?: string;\n\ttitleAttr?: string;\n\ttarget?: string;\n\tcssClasses?: string;\n\tparentIndex?: number;\n}\n\nexport interface ReorderItem {\n\tid: string;\n\tparentId: string | null;\n\tsortOrder: number;\n}\n\n// ---------------------------------------------------------------------------\n// Row → entity mappers\n// ---------------------------------------------------------------------------\n\nfunction rowToMenu(row: Selectable<MenuTable>): Menu {\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tlabel: row.label,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\nfunction rowToMenuItem(row: Selectable<MenuItemTable>): MenuItem {\n\treturn {\n\t\tid: row.id,\n\t\tmenuId: row.menu_id,\n\t\tparentId: row.parent_id,\n\t\tsortOrder: row.sort_order,\n\t\ttype: row.type,\n\t\treferenceCollection: row.reference_collection,\n\t\treferenceId: row.reference_id,\n\t\tcustomUrl: row.custom_url,\n\t\tlabel: row.label,\n\t\ttitleAttr: row.title_attr,\n\t\ttarget: row.target,\n\t\tcssClasses: row.css_classes,\n\t\tcreatedAt: row.created_at,\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Repository\n// ---------------------------------------------------------------------------\n\nexport class MenuRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t// --- Menus -------------------------------------------------------------\n\n\t/**\n\t * List menus with their item counts. When `locale` is omitted, returns\n\t * every locale variant as its own row (consistent with the admin listing\n\t * model: each translation is its own menu for editing purposes).\n\t */\n\tasync findMany(options: { locale?: string } = {}): Promise<MenuListItem[]> {\n\t\t// Single LEFT JOIN + GROUP BY for the per-menu count. Avoids N+1.\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_menus as m\")\n\t\t\t.leftJoin(\"_emdash_menu_items as i\", \"i.menu_id\", \"m.id\")\n\t\t\t.select(({ fn }) => [\n\t\t\t\t\"m.id\",\n\t\t\t\t\"m.name\",\n\t\t\t\t\"m.label\",\n\t\t\t\t\"m.created_at\",\n\t\t\t\t\"m.updated_at\",\n\t\t\t\t\"m.locale\",\n\t\t\t\t\"m.translation_group\",\n\t\t\t\tfn.count<number>(\"i.id\").as(\"itemCount\"),\n\t\t\t])\n\t\t\t.groupBy([\n\t\t\t\t\"m.id\",\n\t\t\t\t\"m.name\",\n\t\t\t\t\"m.label\",\n\t\t\t\t\"m.created_at\",\n\t\t\t\t\"m.updated_at\",\n\t\t\t\t\"m.locale\",\n\t\t\t\t\"m.translation_group\",\n\t\t\t])\n\t\t\t.orderBy(\"m.name\", \"asc\");\n\t\tif (options.locale !== undefined) query = query.where(\"m.locale\", \"=\", options.locale);\n\t\tconst rows = await query.execute();\n\n\t\treturn rows.map((row) => ({\n\t\t\t// Postgres returns count() as `string`; SQLite as `number`. Normalize.\n\t\t\titemCount: typeof row.itemCount === \"string\" ? Number(row.itemCount) : row.itemCount,\n\t\t\t...rowToMenu({\n\t\t\t\tid: row.id,\n\t\t\t\tname: row.name,\n\t\t\t\tlabel: row.label,\n\t\t\t\tcreated_at: row.created_at,\n\t\t\t\tupdated_at: row.updated_at,\n\t\t\t\tlocale: row.locale,\n\t\t\t\ttranslation_group: row.translation_group,\n\t\t\t}),\n\t\t}));\n\t}\n\n\t/**\n\t * Find every menu row matching `name` (one per locale on multi-locale\n\t * installs). Callers use this both to look up a single menu (when locale\n\t * is supplied) and to detect AMBIGUOUS_LOCALE situations (`length > 1`).\n\t */\n\tasync findByName(name: string, options: { locale?: string } = {}): Promise<Menu[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.orderBy(\"locale\", \"asc\");\n\t\tif (options.locale !== undefined) query = query.where(\"locale\", \"=\", options.locale);\n\t\tconst rows = await query.execute();\n\t\treturn rows.map(rowToMenu);\n\t}\n\n\tasync findById(id: string): Promise<Menu | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? rowToMenu(row) : null;\n\t}\n\n\t/** Fetch a menu plus its items, ordered by `sort_order`. */\n\tasync findWithItems(menuId: string): Promise<MenuWithItems | null> {\n\t\tconst menu = await this.findById(menuId);\n\t\tif (!menu) return null;\n\t\tconst items = await this.findItems(menuId);\n\t\treturn { ...menu, items };\n\t}\n\n\tasync findItems(menuId: string): Promise<MenuItem[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t.selectAll()\n\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map(rowToMenuItem);\n\t}\n\n\t/**\n\t * Returns true when a menu already exists for the given `(name, locale)`.\n\t * Used by the handler to surface a CONFLICT before attempting the insert.\n\t */\n\tasync existsByNameAndLocale(name: string, locale: string): Promise<boolean> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.where(\"locale\", \"=\", locale)\n\t\t\t.executeTakeFirst();\n\t\treturn row !== undefined;\n\t}\n\n\t/**\n\t * Create a menu. When `translationOf` is supplied the new menu joins the\n\t * source menu's translation_group and clones its items (each clone gets a\n\t * fresh ULID, but inherits the source item's `translation_group` so a\n\t * given nav entry resolves to \"the same item\" across menu translations).\n\t *\n\t * If the source menu is missing this throws — callers should validate\n\t * existence via `findById` first to return a clean NOT_FOUND.\n\t */\n\tasync create(input: CreateMenuInput): Promise<Menu> {\n\t\tconst id = ulid();\n\n\t\tlet translationGroup: string = id;\n\t\tlet sourceMenuId: string | null = null;\n\t\tif (input.translationOf) {\n\t\t\tconst source = await this.findById(input.translationOf);\n\t\t\tif (!source) throw new Error(\"Source menu for translation not found\");\n\t\t\ttranslationGroup = source.translationGroup ?? source.id;\n\t\t\tsourceMenuId = source.id;\n\t\t}\n\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\tawait trx\n\t\t\t\t.insertInto(\"_emdash_menus\")\n\t\t\t\t.values({\n\t\t\t\t\tid,\n\t\t\t\t\tname: input.name,\n\t\t\t\t\tlabel: input.label,\n\t\t\t\t\t...(input.locale !== undefined ? { locale: input.locale } : {}),\n\t\t\t\t\ttranslation_group: translationGroup,\n\t\t\t\t})\n\t\t\t\t.execute();\n\n\t\t\tif (sourceMenuId) {\n\t\t\t\tconst sourceItems = await trx\n\t\t\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t\t\t.selectAll()\n\t\t\t\t\t.where(\"menu_id\", \"=\", sourceMenuId)\n\t\t\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t\t\t.execute();\n\t\t\t\tif (sourceItems.length > 0) {\n\t\t\t\t\t// old-id → new-id map so parent pointers land on the clones.\n\t\t\t\t\tconst idMap = new Map<string, string>();\n\t\t\t\t\tfor (const item of sourceItems) idMap.set(item.id, ulid());\n\n\t\t\t\t\tawait trx\n\t\t\t\t\t\t.insertInto(\"_emdash_menu_items\")\n\t\t\t\t\t\t.values(\n\t\t\t\t\t\t\tsourceItems.map((item) => ({\n\t\t\t\t\t\t\t\tid: idMap.get(item.id)!,\n\t\t\t\t\t\t\t\tmenu_id: id,\n\t\t\t\t\t\t\t\tparent_id: item.parent_id ? (idMap.get(item.parent_id) ?? null) : null,\n\t\t\t\t\t\t\t\tsort_order: item.sort_order,\n\t\t\t\t\t\t\t\ttype: item.type,\n\t\t\t\t\t\t\t\treference_collection: item.reference_collection,\n\t\t\t\t\t\t\t\treference_id: item.reference_id,\n\t\t\t\t\t\t\t\tcustom_url: item.custom_url,\n\t\t\t\t\t\t\t\tlabel: item.label,\n\t\t\t\t\t\t\t\ttitle_attr: item.title_attr,\n\t\t\t\t\t\t\t\ttarget: item.target,\n\t\t\t\t\t\t\t\tcss_classes: item.css_classes,\n\t\t\t\t\t\t\t\t...(input.locale !== undefined ? { locale: input.locale } : {}),\n\t\t\t\t\t\t\t\ttranslation_group: item.translation_group ?? item.id,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.execute();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tinvalidateMenuObjectCache();\n\n\t\tconst created = await this.findById(id);\n\t\tif (!created) throw new Error(\"Failed to create menu\");\n\t\treturn created;\n\t}\n\n\tasync update(id: string, input: UpdateMenuInput): Promise<Menu | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return null;\n\n\t\tconst values: Record<string, unknown> = {};\n\t\tif (input.label !== undefined) values.label = input.label;\n\n\t\tif (Object.keys(values).length > 0) {\n\t\t\tawait this.db.updateTable(\"_emdash_menus\").set(values).where(\"id\", \"=\", id).execute();\n\t\t\tinvalidateMenuObjectCache();\n\t\t}\n\n\t\treturn (await this.findById(id))!;\n\t}\n\n\t/**\n\t * Delete a menu. Items are deleted explicitly to avoid relying on the\n\t * `ON DELETE CASCADE` FK declared in migration 005, which migration 036\n\t * removed: that FK is what made #1021 destructive on D1 (the cascade\n\t * fired when the i18n migration dropped `_emdash_menus`), so dropping\n\t * the FK was the fix. The explicit delete keeps the runtime working\n\t * the same way before and after the migration.\n\t */\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return false;\n\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\tawait trx.deleteFrom(\"_emdash_menu_items\").where(\"menu_id\", \"=\", id).execute();\n\t\t\tawait trx.deleteFrom(\"_emdash_menus\").where(\"id\", \"=\", id).execute();\n\t\t});\n\t\tinvalidateMenuObjectCache();\n\t\treturn true;\n\t}\n\n\t/**\n\t * List every translation of a menu (by id or translation_group).\n\t *\n\t * Returns `null` when neither the id nor the group resolves to a menu,\n\t * mapped to NOT_FOUND by the handler.\n\t */\n\tasync listTranslations(\n\t\tidOrGroup: string,\n\t): Promise<{ translationGroup: string | null; translations: MenuTranslation[] } | null> {\n\t\tconst anchor = await this.db\n\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t.selectAll()\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\tif (!anchor) return null;\n\n\t\tconst group = anchor.translation_group ?? anchor.id;\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", group)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\n\t\treturn {\n\t\t\ttranslationGroup: group,\n\t\t\ttranslations: rows.map((row) => ({\n\t\t\t\tid: row.id,\n\t\t\t\tname: row.name,\n\t\t\t\tlocale: row.locale,\n\t\t\t\tlabel: row.label,\n\t\t\t\tupdatedAt: row.updated_at,\n\t\t\t})),\n\t\t};\n\t}\n\n\t// --- Items -------------------------------------------------------------\n\n\t/**\n\t * Insert a menu item. `locale` is propagated from the parent menu so\n\t * `_emdash_menu_items.locale` mirrors the menu's locale (queries can scope\n\t * by locale without a join).\n\t *\n\t * When `sortOrder` is omitted, the next position within the same parent\n\t * scope is used (max + 1). The fresh `translation_group` defaults to the\n\t * item's own id, matching the migration 036 backfill.\n\t */\n\tasync createItem(menuId: string, locale: string, input: CreateMenuItemInput): Promise<MenuItem> {\n\t\tlet sortOrder = input.sortOrder ?? 0;\n\t\tif (input.sortOrder === undefined) {\n\t\t\tconst maxOrder = await this.db\n\t\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t\t.select(({ fn }) => fn.max(\"sort_order\").as(\"max\"))\n\t\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t\t.where(\"parent_id\", \"is\", input.parentId ?? null)\n\t\t\t\t.executeTakeFirst();\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- Kysely fn.max returns unknown; always a number for sort_order column\n\t\t\tsortOrder = ((maxOrder?.max as number) ?? -1) + 1;\n\t\t}\n\n\t\tconst id = ulid();\n\t\tawait this.db\n\t\t\t.insertInto(\"_emdash_menu_items\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tmenu_id: menuId,\n\t\t\t\tparent_id: input.parentId ?? null,\n\t\t\t\tsort_order: sortOrder,\n\t\t\t\ttype: input.type,\n\t\t\t\treference_collection: input.referenceCollection ?? null,\n\t\t\t\treference_id: input.referenceId ?? null,\n\t\t\t\tcustom_url: input.customUrl ?? null,\n\t\t\t\tlabel: input.label,\n\t\t\t\ttitle_attr: input.titleAttr ?? null,\n\t\t\t\ttarget: input.target ?? null,\n\t\t\t\tcss_classes: input.cssClasses ?? null,\n\t\t\t\tlocale,\n\t\t\t\ttranslation_group: id,\n\t\t\t})\n\t\t\t.execute();\n\n\t\tinvalidateMenuObjectCache();\n\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirstOrThrow();\n\t\treturn rowToMenuItem(row);\n\t}\n\n\t/**\n\t * Update a menu item. Caller must ensure the item belongs to the menu —\n\t * the `where(\"menu_id\", \"=\", menuId)` guard prevents cross-menu writes.\n\t * Returns `null` if the item is not found within the menu.\n\t */\n\tasync updateItem(\n\t\tmenuId: string,\n\t\titemId: string,\n\t\tinput: UpdateMenuItemInput,\n\t): Promise<MenuItem | null> {\n\t\tconst existing = await this.db\n\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"id\", \"=\", itemId)\n\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t.executeTakeFirst();\n\t\tif (!existing) return null;\n\n\t\tconst values: Record<string, unknown> = {};\n\t\tif (input.label !== undefined) values.label = input.label;\n\t\tif (input.customUrl !== undefined) values.custom_url = input.customUrl;\n\t\tif (input.target !== undefined) values.target = input.target;\n\t\tif (input.titleAttr !== undefined) values.title_attr = input.titleAttr;\n\t\tif (input.cssClasses !== undefined) values.css_classes = input.cssClasses;\n\t\tif (input.parentId !== undefined) values.parent_id = input.parentId;\n\t\tif (input.sortOrder !== undefined) values.sort_order = input.sortOrder;\n\n\t\tif (Object.keys(values).length > 0) {\n\t\t\tawait this.db\n\t\t\t\t.updateTable(\"_emdash_menu_items\")\n\t\t\t\t.set(values)\n\t\t\t\t.where(\"id\", \"=\", itemId)\n\t\t\t\t.execute();\n\t\t\tinvalidateMenuObjectCache();\n\t\t}\n\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", itemId)\n\t\t\t.executeTakeFirstOrThrow();\n\t\treturn rowToMenuItem(row);\n\t}\n\n\t/** Delete an item scoped to its menu. Returns false if nothing was deleted. */\n\tasync deleteItem(menuId: string, itemId: string): Promise<boolean> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_emdash_menu_items\")\n\t\t\t.where(\"id\", \"=\", itemId)\n\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t.execute();\n\t\tconst deleted = result[0]?.numDeletedRows !== 0n;\n\t\tif (deleted) invalidateMenuObjectCache();\n\t\treturn deleted;\n\t}\n\n\t/**\n\t * Atomic replace: delete every existing item and re-insert in order.\n\t * `parentIndex` (validated by the caller) is resolved against the live\n\t * insert order so children always reference real parent ids.\n\t *\n\t * Returns the count of inserted items (matches the existing handler API).\n\t */\n\tasync setItems(\n\t\tmenuId: string,\n\t\tlocale: string,\n\t\titems: SetMenuItem[],\n\t): Promise<{ itemCount: number }> {\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\t// Re-check menu existence INSIDE the transaction. The handler\n\t\t\t// resolved by (name, locale) before this call; if a concurrent\n\t\t\t// menu_delete landed in between, inserting new items would\n\t\t\t// silently orphan them. The FK from migration 005 was removed\n\t\t\t// by migration 036 (#1021) and not restored, so nothing at the\n\t\t\t// schema level stops the orphans. Throw a MenuGoneError so the\n\t\t\t// rollback fires and the handler returns NOT_FOUND with the\n\t\t\t// original menu name in the message.\n\t\t\tconst stillThere = await trx\n\t\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t\t.select(\"id\")\n\t\t\t\t.where(\"id\", \"=\", menuId)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (!stillThere) throw new MenuGoneError(menuId);\n\n\t\t\tawait trx.deleteFrom(\"_emdash_menu_items\").where(\"menu_id\", \"=\", menuId).execute();\n\n\t\t\tconst insertedIds: string[] = [];\n\t\t\tfor (let i = 0; i < items.length; i++) {\n\t\t\t\tconst item = items[i];\n\t\t\t\tif (!item) continue;\n\t\t\t\tconst id = ulid();\n\t\t\t\tconst parentId =\n\t\t\t\t\titem.parentIndex !== undefined ? (insertedIds[item.parentIndex] ?? null) : null;\n\t\t\t\tawait trx\n\t\t\t\t\t.insertInto(\"_emdash_menu_items\")\n\t\t\t\t\t.values({\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tmenu_id: menuId,\n\t\t\t\t\t\tparent_id: parentId,\n\t\t\t\t\t\tsort_order: i,\n\t\t\t\t\t\ttype: item.type,\n\t\t\t\t\t\treference_collection: item.referenceCollection ?? null,\n\t\t\t\t\t\treference_id: item.referenceId ?? null,\n\t\t\t\t\t\tcustom_url: item.customUrl ?? null,\n\t\t\t\t\t\tlabel: item.label,\n\t\t\t\t\t\ttitle_attr: item.titleAttr ?? null,\n\t\t\t\t\t\ttarget: item.target ?? null,\n\t\t\t\t\t\tcss_classes: item.cssClasses ?? null,\n\t\t\t\t\t\tlocale,\n\t\t\t\t\t})\n\t\t\t\t\t.execute();\n\t\t\t\tinsertedIds.push(id);\n\t\t\t}\n\n\t\t\tawait trx\n\t\t\t\t.updateTable(\"_emdash_menus\")\n\t\t\t\t.set({ updated_at: new Date().toISOString() })\n\t\t\t\t.where(\"id\", \"=\", menuId)\n\t\t\t\t.execute();\n\t\t});\n\n\t\tinvalidateMenuObjectCache();\n\t\treturn { itemCount: items.length };\n\t}\n\n\t/**\n\t * Batch reorder items. Each entry is applied scoped to the menu so a\n\t * malicious payload cannot move foreign items into this menu's siblings.\n\t */\n\tasync reorderItems(menuId: string, items: ReorderItem[]): Promise<MenuItem[]> {\n\t\tinvalidateMenuObjectCache();\n\t\treturn withTransaction(this.db, async (trx) => {\n\t\t\tfor (const item of items) {\n\t\t\t\tawait trx\n\t\t\t\t\t.updateTable(\"_emdash_menu_items\")\n\t\t\t\t\t.set({ parent_id: item.parentId, sort_order: item.sortOrder })\n\t\t\t\t\t.where(\"id\", \"=\", item.id)\n\t\t\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t\t\t.execute();\n\t\t\t}\n\n\t\t\tconst rows = await trx\n\t\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t\t.execute();\n\t\t\treturn rows.map(rowToMenuItem);\n\t\t});\n\t}\n}\n","/**\n * Menu CRUD handlers.\n *\n * Business logic for menu and menu-item endpoints. Routes are thin wrappers\n * that parse input, check auth, and call these.\n *\n * i18n: Menus are per-locale. `(name, locale)` is unique, so the same `name`\n * (e.g. \"primary\") can exist in several locales within one translation_group.\n * Menu items carry a `locale` + `translation_group` as well, and their\n * `reference_id` points at the referenced content's translation_group (not a\n * specific row id), so a single menu item target survives content translations.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport {\n\tMenuGoneError,\n\tMenuRepository,\n\ttype CreateMenuItemInput as CreateMenuItemRepoInput,\n\ttype Menu,\n\ttype MenuItem,\n\ttype MenuListItem,\n\ttype MenuWithItems,\n\ttype SetMenuItem,\n\ttype UpdateMenuItemInput as UpdateMenuItemRepoInput,\n} from \"../../database/repositories/menu.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { getI18nConfig } from \"../../i18n/config.js\";\nimport type { ApiResult } from \"../types.js\";\n\n// Re-export entity types so route files and tests can import them from the\n// handler module without having to know about the repository layout.\nexport type {\n\tMenu,\n\tMenuItem,\n\tMenuListItem,\n\tMenuTranslation,\n\tMenuWithItems,\n} from \"../../database/repositories/menu.js\";\n\nexport interface MenuTranslationsResponse {\n\ttranslationGroup: string | null;\n\ttranslations: Array<{\n\t\tid: string;\n\t\tname: string;\n\t\tlocale: string;\n\t\tlabel: string;\n\t\tupdatedAt: string;\n\t}>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Error returned when a menu lookup by `name` matches multiple locale\n * variants and the caller did not pass `locale` to disambiguate. Maps to\n * HTTP 400 via `mapErrorStatus`. The available locales are surfaced in the\n * message so MCP/REST callers can recover by re-issuing with `locale`.\n */\nfunction ambiguousMenuLocaleError(\n\tname: string,\n\tlocales: readonly string[],\n): { success: false; error: { code: \"AMBIGUOUS_LOCALE\"; message: string } } {\n\tconst sortedLocales = locales.toSorted();\n\treturn {\n\t\tsuccess: false,\n\t\terror: {\n\t\t\tcode: \"AMBIGUOUS_LOCALE\",\n\t\t\tmessage: `Menu '${name}' exists in multiple locales (${sortedLocales.join(\n\t\t\t\t\", \",\n\t\t\t)}); pass 'locale' to disambiguate.`,\n\t\t},\n\t};\n}\n\ntype ResolveMenuResult =\n\t| { success: true; menu: Menu }\n\t| { success: false; error: { code: \"NOT_FOUND\" | \"AMBIGUOUS_LOCALE\"; message: string } };\n\n/**\n * Resolve a menu by name + optional locale to a single Menu, surfacing the\n * canonical NOT_FOUND / AMBIGUOUS_LOCALE errors. Every item handler relies on\n * this to translate (name, locale) into an unambiguous menu row.\n */\nasync function resolveMenu(\n\trepo: MenuRepository,\n\tname: string,\n\toptions: { locale?: string },\n): Promise<ResolveMenuResult> {\n\tconst matches = await repo.findByName(name, options);\n\tif (matches.length === 0) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\tmessage: `Menu '${name}' not found${options.locale ? ` in locale '${options.locale}'` : \"\"}`,\n\t\t\t},\n\t\t};\n\t}\n\tif (matches.length > 1) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: ambiguousMenuLocaleError(\n\t\t\t\tname,\n\t\t\t\tmatches.map((m) => m.locale),\n\t\t\t).error,\n\t\t};\n\t}\n\treturn { success: true, menu: matches[0] };\n}\n\n// ---------------------------------------------------------------------------\n// Menu handlers\n// ---------------------------------------------------------------------------\n\n/**\n * List menus with item counts. Filter by `locale` when provided.\n */\nexport async function handleMenuList(\n\tdb: Kysely<Database>,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<MenuListItem[]>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst items = await repo.findMany(options);\n\t\treturn { success: true, data: items };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_LIST_ERROR\", message: \"Failed to fetch menus\" },\n\t\t};\n\t}\n}\n\n/**\n * Create a new menu. When `translationOf` is supplied the new menu joins the\n * source menu's translation_group (and gets the source's items cloned by the\n * repository).\n */\nexport async function handleMenuCreate(\n\tdb: Kysely<Database>,\n\tinput: { name: string; label: string; locale?: string; translationOf?: string },\n): Promise<ApiResult<Menu>> {\n\ttry {\n\t\t// Translating from a source menu only makes sense when the caller\n\t\t// names the target locale: otherwise we'd silently clone into the\n\t\t// configured default, which is almost never what's intended (and\n\t\t// will collide if the source is already the default-locale menu).\n\t\t// Enforced here so REST/SDK callers get the same guard as MCP.\n\t\tif (input.translationOf && !input.locale) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\tmessage: \"`locale` is required when `translationOf` is provided\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst repo = new MenuRepository(db);\n\n\t\t// Existence check up front so the repo's \"Source not found\" throw\n\t\t// becomes a clean NOT_FOUND on the API.\n\t\tif (input.translationOf) {\n\t\t\tconst source = await repo.findById(input.translationOf);\n\t\t\tif (!source) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Source menu for translation not found\" },\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Duplicate guard: same (name, locale). Falls back to the configured\n\t\t// defaultLocale to match the column DEFAULT set by migration 036.\n\t\tconst effectiveLocale = input.locale ?? getI18nConfig()?.defaultLocale ?? \"en\";\n\t\tif (await repo.existsByNameAndLocale(input.name, effectiveLocale)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\tmessage: `Menu \"${input.name}\" already exists${\n\t\t\t\t\t\tinput.locale ? ` in locale \"${input.locale}\"` : \"\"\n\t\t\t\t\t}`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst menu = await repo.create(input);\n\t\treturn { success: true, data: menu };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_CREATE_ERROR\", message: \"Failed to create menu\" },\n\t\t};\n\t}\n}\n\n/**\n * Get a single menu by name. Honours an optional `locale` filter; when two\n * menus share a name across locales, the locale distinguishes them.\n *\n * Historical behaviour: when `locale` is omitted, returns the lowest-locale\n * match (deterministic). Mirrors the pre-repo handler.\n */\nexport async function handleMenuGet(\n\tdb: Kysely<Database>,\n\tname: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<MenuWithItems>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst matches = await repo.findByName(name, options);\n\t\tif (matches.length === 0) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: `Menu '${name}' not found` },\n\t\t\t};\n\t\t}\n\t\tconst menu = matches[0];\n\t\tconst items = await repo.findItems(menu.id);\n\t\treturn { success: true, data: { ...menu, items } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_GET_ERROR\", message: \"Failed to fetch menu\" },\n\t\t};\n\t}\n}\n\n/**\n * Get a menu by id. Useful when the caller already has the id (e.g. after\n * creating a translation and navigating to it).\n */\nexport async function handleMenuGetById(\n\tdb: Kysely<Database>,\n\tid: string,\n): Promise<ApiResult<MenuWithItems>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst menu = await repo.findWithItems(id);\n\t\tif (!menu) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: `Menu '${id}' not found` },\n\t\t\t};\n\t\t}\n\t\treturn { success: true, data: menu };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_GET_ERROR\", message: \"Failed to fetch menu\" },\n\t\t};\n\t}\n}\n\n/**\n * Update a menu's label. The name + locale are immutable.\n */\nexport async function handleMenuUpdate(\n\tdb: Kysely<Database>,\n\tname: string,\n\tinput: { label?: string; locale?: string },\n): Promise<ApiResult<Menu>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, name, { locale: input.locale });\n\t\tif (!resolved.success) return resolved;\n\t\tconst updated = await repo.update(resolved.menu.id, { label: input.label });\n\t\tif (!updated) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: `Menu '${name}' not found` },\n\t\t\t};\n\t\t}\n\t\treturn { success: true, data: updated };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_UPDATE_ERROR\", message: \"Failed to update menu\" },\n\t\t};\n\t}\n}\n\n/**\n * Delete a menu (and its items, via the repository's explicit cleanup).\n */\nexport async function handleMenuDelete(\n\tdb: Kysely<Database>,\n\tname: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<{ deleted: true }>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, name, options);\n\t\tif (!resolved.success) return resolved;\n\t\tawait repo.delete(resolved.menu.id);\n\t\treturn { success: true, data: { deleted: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_DELETE_ERROR\", message: \"Failed to delete menu\" },\n\t\t};\n\t}\n}\n\n/**\n * List every translation of a menu (by id or translation_group).\n */\nexport async function handleMenuTranslations(\n\tdb: Kysely<Database>,\n\tidOrGroup: string,\n): Promise<ApiResult<MenuTranslationsResponse>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst result = await repo.listTranslations(idOrGroup);\n\t\tif (!result) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Menu not found\" },\n\t\t\t};\n\t\t}\n\t\treturn { success: true, data: result };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_TRANSLATIONS_ERROR\", message: \"Failed to list menu translations\" },\n\t\t};\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Menu item handlers\n// ---------------------------------------------------------------------------\n\nexport type CreateMenuItemInput = CreateMenuItemRepoInput;\nexport type UpdateMenuItemInput = UpdateMenuItemRepoInput;\nexport type MenuSetItemsInput = SetMenuItem;\n\n/**\n * Add an item to a menu. The item inherits the menu's locale.\n */\nexport async function handleMenuItemCreate(\n\tdb: Kysely<Database>,\n\tmenuName: string,\n\tinput: CreateMenuItemInput,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<MenuItem>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, menuName, options);\n\t\tif (!resolved.success) return resolved;\n\n\t\tconst item = await repo.createItem(resolved.menu.id, resolved.menu.locale, input);\n\t\treturn { success: true, data: item };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_ITEM_CREATE_ERROR\", message: \"Failed to create menu item\" },\n\t\t};\n\t}\n}\n\n/**\n * Update a menu item.\n */\nexport async function handleMenuItemUpdate(\n\tdb: Kysely<Database>,\n\tmenuName: string,\n\titemId: string,\n\tinput: UpdateMenuItemInput,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<MenuItem>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, menuName, options);\n\t\tif (!resolved.success) return resolved;\n\n\t\tconst updated = await repo.updateItem(resolved.menu.id, itemId, input);\n\t\tif (!updated) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Menu item not found\" },\n\t\t\t};\n\t\t}\n\t\treturn { success: true, data: updated };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_ITEM_UPDATE_ERROR\", message: \"Failed to update menu item\" },\n\t\t};\n\t}\n}\n\n/**\n * Delete a menu item.\n */\nexport async function handleMenuItemDelete(\n\tdb: Kysely<Database>,\n\tmenuName: string,\n\titemId: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<{ deleted: true }>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, menuName, options);\n\t\tif (!resolved.success) return resolved;\n\n\t\tconst deleted = await repo.deleteItem(resolved.menu.id, itemId);\n\t\tif (!deleted) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Menu item not found\" },\n\t\t\t};\n\t\t}\n\t\treturn { success: true, data: { deleted: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_ITEM_DELETE_ERROR\", message: \"Failed to delete menu item\" },\n\t\t};\n\t}\n}\n\nexport interface ReorderItem {\n\tid: string;\n\tparentId: string | null;\n\tsortOrder: number;\n}\n\n// ---------------------------------------------------------------------------\n// Atomic-replace menu items (used by the MCP `menu_set_items` tool and admin)\n// ---------------------------------------------------------------------------\n\n/**\n * Replace the entire set of items for a menu in one atomic transaction.\n *\n * Existing items are deleted and the new list is inserted in the order\n * provided. `parentIndex` references resolve to actual parent IDs as the\n * insert proceeds.\n */\nexport async function handleMenuSetItems(\n\tdb: Kysely<Database>,\n\tmenuName: string,\n\titems: MenuSetItemsInput[],\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<{ name: string; itemCount: number }>> {\n\t// Validate parentIndex references — must be strictly earlier so the array\n\t// can be inserted in order with parents resolved first. Negative indices\n\t// are caught by Zod's `.nonnegative()` at the MCP boundary, but we guard\n\t// explicitly so REST routes / direct handler use get the same error.\n\tfor (let i = 0; i < items.length; i++) {\n\t\tconst item = items[i];\n\t\tif (item?.parentIndex !== undefined) {\n\t\t\tif (item.parentIndex < 0 || item.parentIndex >= i) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\tmessage: `item[${i}].parentIndex (${item.parentIndex}) must reference an earlier item`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, menuName, options);\n\t\tif (!resolved.success) return resolved;\n\n\t\tconst { itemCount } = await repo.setItems(resolved.menu.id, resolved.menu.locale, items);\n\t\treturn { success: true, data: { name: menuName, itemCount } };\n\t} catch (error) {\n\t\t// `MenuGoneError` is thrown from inside the repository transaction\n\t\t// when the menu was deleted concurrently between `resolveMenu` and the\n\t\t// setItems write. Returning NOT_FOUND mirrors the original handler's\n\t\t// in-transaction `notFoundSentinel` branch and keeps the response\n\t\t// shape stable for REST/MCP callers.\n\t\tif (error instanceof MenuGoneError) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\tmessage: `Menu '${menuName}' not found${\n\t\t\t\t\t\toptions.locale ? ` in locale '${options.locale}'` : \"\"\n\t\t\t\t\t}`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tconsole.error(\"[emdash] handleMenuSetItems failed:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_SET_ITEMS_ERROR\", message: \"Failed to set menu items\" },\n\t\t};\n\t}\n}\n\n/**\n * Batch reorder menu items.\n */\nexport async function handleMenuItemReorder(\n\tdb: Kysely<Database>,\n\tmenuName: string,\n\titems: ReorderItem[],\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<MenuItem[]>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, menuName, options);\n\t\tif (!resolved.success) return resolved;\n\n\t\tconst updated = await repo.reorderItems(resolved.menu.id, items);\n\t\treturn { success: true, data: updated };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_REORDER_ERROR\", message: \"Failed to reorder menu items\" },\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AA6BA,IAAa,gBAAb,cAAmC,MAAM;CACxC,YAAY,AAAgB,QAAgB;AAC3C,QAAM,QAAQ,OAAO,mCAAmC;EAD7B;AAE3B,OAAK,OAAO;;;AA4Hd,SAAS,UAAU,KAAkC;AACpD,QAAO;EACN,IAAI,IAAI;EACR,MAAM,IAAI;EACV,OAAO,IAAI;EACX,WAAW,IAAI;EACf,WAAW,IAAI;EACf,QAAQ,IAAI;EACZ,kBAAkB,IAAI;EACtB;;AAGF,SAAS,cAA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W,MAAM,YAAY,MAAM,UAAU,QAAQ;AAC3D,MAAI,CAAC,SAAS,QAAS,QAAO;AAG9B,SAAO;GAAE,SAAS;GAAM,MADR,MAAM,KAAK,aAAa,SAAS,KAAK,IAAI,MAAM;GACzB;SAChC;AACP,SAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAsB,SAAS;IAAgC;GAC9E"}
|
|
1
|
+
{"version":3,"file":"menus-SL2K0xq2.mjs","names":[],"sources":["../src/database/repositories/menu.ts","../src/api/handlers/menus.ts"],"sourcesContent":["/**\n * Menu repository\n *\n * Owns every SQL touch for `_emdash_menus` and `_emdash_menu_items`, plus the\n * row→entity mapping. Matches the architecture used by every other resource\n * (content, taxonomies, redirects, comments, media): handlers stay thin and\n * orchestrate; the repository is the single place where snake_case DB columns\n * become camelCase entities (and vice versa).\n *\n * i18n: menus are per-locale. `(name, locale)` is unique. Translations of the\n * same menu share a `translation_group` ULID. Menu item `reference_id` stores\n * the referenced content's translation_group (not a specific row id) so a\n * single menu item survives content translations.\n */\n\nimport type { Kysely, Selectable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { invalidateMenuObjectCache } from \"../../object-cache/index.js\";\nimport { withTransaction } from \"../transaction.js\";\nimport type { Database, MenuItemTable, MenuTable } from \"../types.js\";\n\n/**\n * Thrown from inside a repository transaction when the menu the caller\n * resolved earlier has since been deleted. Handlers translate this to a\n * `NOT_FOUND` API response. Necessary because D1 disables FK enforcement\n * (so `ON DELETE CASCADE` won't fire), and an unchecked `setItems` would\n * happily insert items whose `menu_id` no longer exists, leaving orphans.\n */\nexport class MenuGoneError extends Error {\n\tconstructor(public readonly menuId: string) {\n\t\tsuper(`Menu ${menuId} was deleted while being modified`);\n\t\tthis.name = \"MenuGoneError\";\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Entity shapes (camelCase — what the API returns)\n// ---------------------------------------------------------------------------\n\nexport interface Menu {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\tlocale: string;\n\ttranslationGroup: string | null;\n}\n\nexport interface MenuItem {\n\tid: string;\n\tmenuId: string;\n\tparentId: string | null;\n\tsortOrder: number;\n\ttype: string;\n\treferenceCollection: string | null;\n\treferenceId: string | null;\n\tcustomUrl: string | null;\n\tlabel: string;\n\ttitleAttr: string | null;\n\ttarget: string | null;\n\tcssClasses: string | null;\n\tcreatedAt: string;\n\tlocale: string;\n\ttranslationGroup: string | null;\n}\n\nexport interface MenuListItem extends Menu {\n\titemCount: number;\n}\n\nexport interface MenuWithItems extends Menu {\n\titems: MenuItem[];\n}\n\nexport interface MenuTranslation {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tlocale: string;\n\tupdatedAt: string;\n}\n\n// ---------------------------------------------------------------------------\n// Input shapes\n// ---------------------------------------------------------------------------\n\nexport interface CreateMenuInput {\n\tname: string;\n\tlabel: string;\n\tlocale?: string;\n\t/**\n\t * When set, the new menu joins the source menu's translation_group and\n\t * inherits its items (cloned, with new ULIDs but the same translation_group\n\t * per item so nav entries stay logically identified across translations).\n\t */\n\ttranslationOf?: string;\n}\n\nexport interface UpdateMenuInput {\n\tlabel?: string;\n}\n\nexport interface CreateMenuItemInput {\n\ttype: string;\n\tlabel: string;\n\treferenceCollection?: string;\n\treferenceId?: string;\n\tcustomUrl?: string;\n\ttarget?: string;\n\ttitleAttr?: string;\n\tcssClasses?: string;\n\tparentId?: string;\n\tsortOrder?: number;\n}\n\nexport interface UpdateMenuItemInput {\n\tlabel?: string;\n\tcustomUrl?: string;\n\ttarget?: string;\n\ttitleAttr?: string;\n\tcssClasses?: string;\n\tparentId?: string | null;\n\tsortOrder?: number;\n}\n\n/**\n * Item shape used by `setItems()`. Items are placed by array order. Children\n * point at parents via `parentIndex` (must reference an earlier index, so the\n * insert can resolve parents before children). The validation of that ordering\n * lives at the API boundary (`handleMenuSetItems`) so REST/MCP callers receive\n * the same error shape.\n */\nexport interface SetMenuItem {\n\tlabel: string;\n\ttype: \"custom\" | \"page\" | \"post\" | \"taxonomy\" | \"collection\";\n\tcustomUrl?: string;\n\treferenceCollection?: string;\n\treferenceId?: string;\n\ttitleAttr?: string;\n\ttarget?: string;\n\tcssClasses?: string;\n\tparentIndex?: number;\n}\n\nexport interface ReorderItem {\n\tid: string;\n\tparentId: string | null;\n\tsortOrder: number;\n}\n\n// ---------------------------------------------------------------------------\n// Row → entity mappers\n// ---------------------------------------------------------------------------\n\nfunction rowToMenu(row: Selectable<MenuTable>): Menu {\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tlabel: row.label,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\nfunction rowToMenuItem(row: Selectable<MenuItemTable>): MenuItem {\n\treturn {\n\t\tid: row.id,\n\t\tmenuId: row.menu_id,\n\t\tparentId: row.parent_id,\n\t\tsortOrder: row.sort_order,\n\t\ttype: row.type,\n\t\treferenceCollection: row.reference_collection,\n\t\treferenceId: row.reference_id,\n\t\tcustomUrl: row.custom_url,\n\t\tlabel: row.label,\n\t\ttitleAttr: row.title_attr,\n\t\ttarget: row.target,\n\t\tcssClasses: row.css_classes,\n\t\tcreatedAt: row.created_at,\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Repository\n// ---------------------------------------------------------------------------\n\nexport class MenuRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t// --- Menus -------------------------------------------------------------\n\n\t/**\n\t * List menus with their item counts. When `locale` is omitted, returns\n\t * every locale variant as its own row (consistent with the admin listing\n\t * model: each translation is its own menu for editing purposes).\n\t */\n\tasync findMany(options: { locale?: string } = {}): Promise<MenuListItem[]> {\n\t\t// Single LEFT JOIN + GROUP BY for the per-menu count. Avoids N+1.\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_menus as m\")\n\t\t\t.leftJoin(\"_emdash_menu_items as i\", \"i.menu_id\", \"m.id\")\n\t\t\t.select(({ fn }) => [\n\t\t\t\t\"m.id\",\n\t\t\t\t\"m.name\",\n\t\t\t\t\"m.label\",\n\t\t\t\t\"m.created_at\",\n\t\t\t\t\"m.updated_at\",\n\t\t\t\t\"m.locale\",\n\t\t\t\t\"m.translation_group\",\n\t\t\t\tfn.count<number>(\"i.id\").as(\"itemCount\"),\n\t\t\t])\n\t\t\t.groupBy([\n\t\t\t\t\"m.id\",\n\t\t\t\t\"m.name\",\n\t\t\t\t\"m.label\",\n\t\t\t\t\"m.created_at\",\n\t\t\t\t\"m.updated_at\",\n\t\t\t\t\"m.locale\",\n\t\t\t\t\"m.translation_group\",\n\t\t\t])\n\t\t\t.orderBy(\"m.name\", \"asc\");\n\t\tif (options.locale !== undefined) query = query.where(\"m.locale\", \"=\", options.locale);\n\t\tconst rows = await query.execute();\n\n\t\treturn rows.map((row) => ({\n\t\t\t// Postgres returns count() as `string`; SQLite as `number`. Normalize.\n\t\t\titemCount: typeof row.itemCount === \"string\" ? Number(row.itemCount) : row.itemCount,\n\t\t\t...rowToMenu({\n\t\t\t\tid: row.id,\n\t\t\t\tname: row.name,\n\t\t\t\tlabel: row.label,\n\t\t\t\tcreated_at: row.created_at,\n\t\t\t\tupdated_at: row.updated_at,\n\t\t\t\tlocale: row.locale,\n\t\t\t\ttranslation_group: row.translation_group,\n\t\t\t}),\n\t\t}));\n\t}\n\n\t/**\n\t * Find every menu row matching `name` (one per locale on multi-locale\n\t * installs). Callers use this both to look up a single menu (when locale\n\t * is supplied) and to detect AMBIGUOUS_LOCALE situations (`length > 1`).\n\t */\n\tasync findByName(name: string, options: { locale?: string } = {}): Promise<Menu[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.orderBy(\"locale\", \"asc\");\n\t\tif (options.locale !== undefined) query = query.where(\"locale\", \"=\", options.locale);\n\t\tconst rows = await query.execute();\n\t\treturn rows.map(rowToMenu);\n\t}\n\n\tasync findById(id: string): Promise<Menu | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? rowToMenu(row) : null;\n\t}\n\n\t/** Fetch a menu plus its items, ordered by `sort_order`. */\n\tasync findWithItems(menuId: string): Promise<MenuWithItems | null> {\n\t\tconst menu = await this.findById(menuId);\n\t\tif (!menu) return null;\n\t\tconst items = await this.findItems(menuId);\n\t\treturn { ...menu, items };\n\t}\n\n\tasync findItems(menuId: string): Promise<MenuItem[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t.selectAll()\n\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map(rowToMenuItem);\n\t}\n\n\t/**\n\t * Returns true when a menu already exists for the given `(name, locale)`.\n\t * Used by the handler to surface a CONFLICT before attempting the insert.\n\t */\n\tasync existsByNameAndLocale(name: string, locale: string): Promise<boolean> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.where(\"locale\", \"=\", locale)\n\t\t\t.executeTakeFirst();\n\t\treturn row !== undefined;\n\t}\n\n\t/**\n\t * Create a menu. When `translationOf` is supplied the new menu joins the\n\t * source menu's translation_group and clones its items (each clone gets a\n\t * fresh ULID, but inherits the source item's `translation_group` so a\n\t * given nav entry resolves to \"the same item\" across menu translations).\n\t *\n\t * If the source menu is missing this throws — callers should validate\n\t * existence via `findById` first to return a clean NOT_FOUND.\n\t */\n\tasync create(input: CreateMenuInput): Promise<Menu> {\n\t\tconst id = ulid();\n\n\t\tlet translationGroup: string = id;\n\t\tlet sourceMenuId: string | null = null;\n\t\tif (input.translationOf) {\n\t\t\tconst source = await this.findById(input.translationOf);\n\t\t\tif (!source) throw new Error(\"Source menu for translation not found\");\n\t\t\ttranslationGroup = source.translationGroup ?? source.id;\n\t\t\tsourceMenuId = source.id;\n\t\t}\n\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\tawait trx\n\t\t\t\t.insertInto(\"_emdash_menus\")\n\t\t\t\t.values({\n\t\t\t\t\tid,\n\t\t\t\t\tname: input.name,\n\t\t\t\t\tlabel: input.label,\n\t\t\t\t\t...(input.locale !== undefined ? { locale: input.locale } : {}),\n\t\t\t\t\ttranslation_group: translationGroup,\n\t\t\t\t})\n\t\t\t\t.execute();\n\n\t\t\tif (sourceMenuId) {\n\t\t\t\tconst sourceItems = await trx\n\t\t\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t\t\t.selectAll()\n\t\t\t\t\t.where(\"menu_id\", \"=\", sourceMenuId)\n\t\t\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t\t\t.execute();\n\t\t\t\tif (sourceItems.length > 0) {\n\t\t\t\t\t// old-id → new-id map so parent pointers land on the clones.\n\t\t\t\t\tconst idMap = new Map<string, string>();\n\t\t\t\t\tfor (const item of sourceItems) idMap.set(item.id, ulid());\n\n\t\t\t\t\tawait trx\n\t\t\t\t\t\t.insertInto(\"_emdash_menu_items\")\n\t\t\t\t\t\t.values(\n\t\t\t\t\t\t\tsourceItems.map((item) => ({\n\t\t\t\t\t\t\t\tid: idMap.get(item.id)!,\n\t\t\t\t\t\t\t\tmenu_id: id,\n\t\t\t\t\t\t\t\tparent_id: item.parent_id ? (idMap.get(item.parent_id) ?? null) : null,\n\t\t\t\t\t\t\t\tsort_order: item.sort_order,\n\t\t\t\t\t\t\t\ttype: item.type,\n\t\t\t\t\t\t\t\treference_collection: item.reference_collection,\n\t\t\t\t\t\t\t\treference_id: item.reference_id,\n\t\t\t\t\t\t\t\tcustom_url: item.custom_url,\n\t\t\t\t\t\t\t\tlabel: item.label,\n\t\t\t\t\t\t\t\ttitle_attr: item.title_attr,\n\t\t\t\t\t\t\t\ttarget: item.target,\n\t\t\t\t\t\t\t\tcss_classes: item.css_classes,\n\t\t\t\t\t\t\t\t...(input.locale !== undefined ? { locale: input.locale } : {}),\n\t\t\t\t\t\t\t\ttranslation_group: item.translation_group ?? item.id,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.execute();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tinvalidateMenuObjectCache();\n\n\t\tconst created = await this.findById(id);\n\t\tif (!created) throw new Error(\"Failed to create menu\");\n\t\treturn created;\n\t}\n\n\tasync update(id: string, input: UpdateMenuInput): Promise<Menu | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return null;\n\n\t\tconst values: Record<string, unknown> = {};\n\t\tif (input.label !== undefined) values.label = input.label;\n\n\t\tif (Object.keys(values).length > 0) {\n\t\t\tawait this.db.updateTable(\"_emdash_menus\").set(values).where(\"id\", \"=\", id).execute();\n\t\t\tinvalidateMenuObjectCache();\n\t\t}\n\n\t\treturn (await this.findById(id))!;\n\t}\n\n\t/**\n\t * Delete a menu. Items are deleted explicitly to avoid relying on the\n\t * `ON DELETE CASCADE` FK declared in migration 005, which migration 036\n\t * removed: that FK is what made #1021 destructive on D1 (the cascade\n\t * fired when the i18n migration dropped `_emdash_menus`), so dropping\n\t * the FK was the fix. The explicit delete keeps the runtime working\n\t * the same way before and after the migration.\n\t */\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return false;\n\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\tawait trx.deleteFrom(\"_emdash_menu_items\").where(\"menu_id\", \"=\", id).execute();\n\t\t\tawait trx.deleteFrom(\"_emdash_menus\").where(\"id\", \"=\", id).execute();\n\t\t});\n\t\tinvalidateMenuObjectCache();\n\t\treturn true;\n\t}\n\n\t/**\n\t * List every translation of a menu (by id or translation_group).\n\t *\n\t * Returns `null` when neither the id nor the group resolves to a menu,\n\t * mapped to NOT_FOUND by the handler.\n\t */\n\tasync listTranslations(\n\t\tidOrGroup: string,\n\t): Promise<{ translationGroup: string | null; translations: MenuTranslation[] } | null> {\n\t\tconst anchor = await this.db\n\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t.selectAll()\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\tif (!anchor) return null;\n\n\t\tconst group = anchor.translation_group ?? anchor.id;\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", group)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\n\t\treturn {\n\t\t\ttranslationGroup: group,\n\t\t\ttranslations: rows.map((row) => ({\n\t\t\t\tid: row.id,\n\t\t\t\tname: row.name,\n\t\t\t\tlocale: row.locale,\n\t\t\t\tlabel: row.label,\n\t\t\t\tupdatedAt: row.updated_at,\n\t\t\t})),\n\t\t};\n\t}\n\n\t// --- Items -------------------------------------------------------------\n\n\t/**\n\t * Insert a menu item. `locale` is propagated from the parent menu so\n\t * `_emdash_menu_items.locale` mirrors the menu's locale (queries can scope\n\t * by locale without a join).\n\t *\n\t * When `sortOrder` is omitted, the next position within the same parent\n\t * scope is used (max + 1). The fresh `translation_group` defaults to the\n\t * item's own id, matching the migration 036 backfill.\n\t */\n\tasync createItem(menuId: string, locale: string, input: CreateMenuItemInput): Promise<MenuItem> {\n\t\tlet sortOrder = input.sortOrder ?? 0;\n\t\tif (input.sortOrder === undefined) {\n\t\t\tconst maxOrder = await this.db\n\t\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t\t.select(({ fn }) => fn.max(\"sort_order\").as(\"max\"))\n\t\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t\t.where(\"parent_id\", \"is\", input.parentId ?? null)\n\t\t\t\t.executeTakeFirst();\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- Kysely fn.max returns unknown; always a number for sort_order column\n\t\t\tsortOrder = ((maxOrder?.max as number) ?? -1) + 1;\n\t\t}\n\n\t\tconst id = ulid();\n\t\tawait this.db\n\t\t\t.insertInto(\"_emdash_menu_items\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tmenu_id: menuId,\n\t\t\t\tparent_id: input.parentId ?? null,\n\t\t\t\tsort_order: sortOrder,\n\t\t\t\ttype: input.type,\n\t\t\t\treference_collection: input.referenceCollection ?? null,\n\t\t\t\treference_id: input.referenceId ?? null,\n\t\t\t\tcustom_url: input.customUrl ?? null,\n\t\t\t\tlabel: input.label,\n\t\t\t\ttitle_attr: input.titleAttr ?? null,\n\t\t\t\ttarget: input.target ?? null,\n\t\t\t\tcss_classes: input.cssClasses ?? null,\n\t\t\t\tlocale,\n\t\t\t\ttranslation_group: id,\n\t\t\t})\n\t\t\t.execute();\n\n\t\tinvalidateMenuObjectCache();\n\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirstOrThrow();\n\t\treturn rowToMenuItem(row);\n\t}\n\n\t/**\n\t * Update a menu item. Caller must ensure the item belongs to the menu —\n\t * the `where(\"menu_id\", \"=\", menuId)` guard prevents cross-menu writes.\n\t * Returns `null` if the item is not found within the menu.\n\t */\n\tasync updateItem(\n\t\tmenuId: string,\n\t\titemId: string,\n\t\tinput: UpdateMenuItemInput,\n\t): Promise<MenuItem | null> {\n\t\tconst existing = await this.db\n\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"id\", \"=\", itemId)\n\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t.executeTakeFirst();\n\t\tif (!existing) return null;\n\n\t\tconst values: Record<string, unknown> = {};\n\t\tif (input.label !== undefined) values.label = input.label;\n\t\tif (input.customUrl !== undefined) values.custom_url = input.customUrl;\n\t\tif (input.target !== undefined) values.target = input.target;\n\t\tif (input.titleAttr !== undefined) values.title_attr = input.titleAttr;\n\t\tif (input.cssClasses !== undefined) values.css_classes = input.cssClasses;\n\t\tif (input.parentId !== undefined) values.parent_id = input.parentId;\n\t\tif (input.sortOrder !== undefined) values.sort_order = input.sortOrder;\n\n\t\tif (Object.keys(values).length > 0) {\n\t\t\tawait this.db\n\t\t\t\t.updateTable(\"_emdash_menu_items\")\n\t\t\t\t.set(values)\n\t\t\t\t.where(\"id\", \"=\", itemId)\n\t\t\t\t.execute();\n\t\t\tinvalidateMenuObjectCache();\n\t\t}\n\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", itemId)\n\t\t\t.executeTakeFirstOrThrow();\n\t\treturn rowToMenuItem(row);\n\t}\n\n\t/** Delete an item scoped to its menu. Returns false if nothing was deleted. */\n\tasync deleteItem(menuId: string, itemId: string): Promise<boolean> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_emdash_menu_items\")\n\t\t\t.where(\"id\", \"=\", itemId)\n\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t.execute();\n\t\tconst deleted = result[0]?.numDeletedRows !== 0n;\n\t\tif (deleted) invalidateMenuObjectCache();\n\t\treturn deleted;\n\t}\n\n\t/**\n\t * Atomic replace: delete every existing item and re-insert in order.\n\t * `parentIndex` (validated by the caller) is resolved against the live\n\t * insert order so children always reference real parent ids.\n\t *\n\t * Returns the count of inserted items (matches the existing handler API).\n\t */\n\tasync setItems(\n\t\tmenuId: string,\n\t\tlocale: string,\n\t\titems: SetMenuItem[],\n\t): Promise<{ itemCount: number }> {\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\t// Re-check menu existence INSIDE the transaction. The handler\n\t\t\t// resolved by (name, locale) before this call; if a concurrent\n\t\t\t// menu_delete landed in between, inserting new items would\n\t\t\t// silently orphan them. The FK from migration 005 was removed\n\t\t\t// by migration 036 (#1021) and not restored, so nothing at the\n\t\t\t// schema level stops the orphans. Throw a MenuGoneError so the\n\t\t\t// rollback fires and the handler returns NOT_FOUND with the\n\t\t\t// original menu name in the message.\n\t\t\tconst stillThere = await trx\n\t\t\t\t.selectFrom(\"_emdash_menus\")\n\t\t\t\t.select(\"id\")\n\t\t\t\t.where(\"id\", \"=\", menuId)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (!stillThere) throw new MenuGoneError(menuId);\n\n\t\t\tawait trx.deleteFrom(\"_emdash_menu_items\").where(\"menu_id\", \"=\", menuId).execute();\n\n\t\t\tconst insertedIds: string[] = [];\n\t\t\tfor (let i = 0; i < items.length; i++) {\n\t\t\t\tconst item = items[i];\n\t\t\t\tif (!item) continue;\n\t\t\t\tconst id = ulid();\n\t\t\t\tconst parentId =\n\t\t\t\t\titem.parentIndex !== undefined ? (insertedIds[item.parentIndex] ?? null) : null;\n\t\t\t\tawait trx\n\t\t\t\t\t.insertInto(\"_emdash_menu_items\")\n\t\t\t\t\t.values({\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tmenu_id: menuId,\n\t\t\t\t\t\tparent_id: parentId,\n\t\t\t\t\t\tsort_order: i,\n\t\t\t\t\t\ttype: item.type,\n\t\t\t\t\t\treference_collection: item.referenceCollection ?? null,\n\t\t\t\t\t\treference_id: item.referenceId ?? null,\n\t\t\t\t\t\tcustom_url: item.customUrl ?? null,\n\t\t\t\t\t\tlabel: item.label,\n\t\t\t\t\t\ttitle_attr: item.titleAttr ?? null,\n\t\t\t\t\t\ttarget: item.target ?? null,\n\t\t\t\t\t\tcss_classes: item.cssClasses ?? null,\n\t\t\t\t\t\tlocale,\n\t\t\t\t\t})\n\t\t\t\t\t.execute();\n\t\t\t\tinsertedIds.push(id);\n\t\t\t}\n\n\t\t\tawait trx\n\t\t\t\t.updateTable(\"_emdash_menus\")\n\t\t\t\t.set({ updated_at: new Date().toISOString() })\n\t\t\t\t.where(\"id\", \"=\", menuId)\n\t\t\t\t.execute();\n\t\t});\n\n\t\tinvalidateMenuObjectCache();\n\t\treturn { itemCount: items.length };\n\t}\n\n\t/**\n\t * Batch reorder items. Each entry is applied scoped to the menu so a\n\t * malicious payload cannot move foreign items into this menu's siblings.\n\t */\n\tasync reorderItems(menuId: string, items: ReorderItem[]): Promise<MenuItem[]> {\n\t\tinvalidateMenuObjectCache();\n\t\treturn withTransaction(this.db, async (trx) => {\n\t\t\tfor (const item of items) {\n\t\t\t\tawait trx\n\t\t\t\t\t.updateTable(\"_emdash_menu_items\")\n\t\t\t\t\t.set({ parent_id: item.parentId, sort_order: item.sortOrder })\n\t\t\t\t\t.where(\"id\", \"=\", item.id)\n\t\t\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t\t\t.execute();\n\t\t\t}\n\n\t\t\tconst rows = await trx\n\t\t\t\t.selectFrom(\"_emdash_menu_items\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"menu_id\", \"=\", menuId)\n\t\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t\t.execute();\n\t\t\treturn rows.map(rowToMenuItem);\n\t\t});\n\t}\n}\n","/**\n * Menu CRUD handlers.\n *\n * Business logic for menu and menu-item endpoints. Routes are thin wrappers\n * that parse input, check auth, and call these.\n *\n * i18n: Menus are per-locale. `(name, locale)` is unique, so the same `name`\n * (e.g. \"primary\") can exist in several locales within one translation_group.\n * Menu items carry a `locale` + `translation_group` as well, and their\n * `reference_id` points at the referenced content's translation_group (not a\n * specific row id), so a single menu item target survives content translations.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport {\n\tMenuGoneError,\n\tMenuRepository,\n\ttype CreateMenuItemInput as CreateMenuItemRepoInput,\n\ttype Menu,\n\ttype MenuItem,\n\ttype MenuListItem,\n\ttype MenuWithItems,\n\ttype SetMenuItem,\n\ttype UpdateMenuItemInput as UpdateMenuItemRepoInput,\n} from \"../../database/repositories/menu.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { getI18nConfig } from \"../../i18n/config.js\";\nimport type { ApiResult } from \"../types.js\";\n\n// Re-export entity types so route files and tests can import them from the\n// handler module without having to know about the repository layout.\nexport type {\n\tMenu,\n\tMenuItem,\n\tMenuListItem,\n\tMenuTranslation,\n\tMenuWithItems,\n} from \"../../database/repositories/menu.js\";\n\nexport interface MenuTranslationsResponse {\n\ttranslationGroup: string | null;\n\ttranslations: Array<{\n\t\tid: string;\n\t\tname: string;\n\t\tlocale: string;\n\t\tlabel: string;\n\t\tupdatedAt: string;\n\t}>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Error returned when a menu lookup by `name` matches multiple locale\n * variants and the caller did not pass `locale` to disambiguate. Maps to\n * HTTP 400 via `mapErrorStatus`. The available locales are surfaced in the\n * message so MCP/REST callers can recover by re-issuing with `locale`.\n */\nfunction ambiguousMenuLocaleError(\n\tname: string,\n\tlocales: readonly string[],\n): { success: false; error: { code: \"AMBIGUOUS_LOCALE\"; message: string } } {\n\tconst sortedLocales = locales.toSorted();\n\treturn {\n\t\tsuccess: false,\n\t\terror: {\n\t\t\tcode: \"AMBIGUOUS_LOCALE\",\n\t\t\tmessage: `Menu '${name}' exists in multiple locales (${sortedLocales.join(\n\t\t\t\t\", \",\n\t\t\t)}); pass 'locale' to disambiguate.`,\n\t\t},\n\t};\n}\n\ntype ResolveMenuResult =\n\t| { success: true; menu: Menu }\n\t| { success: false; error: { code: \"NOT_FOUND\" | \"AMBIGUOUS_LOCALE\"; message: string } };\n\n/**\n * Resolve a menu by name + optional locale to a single Menu, surfacing the\n * canonical NOT_FOUND / AMBIGUOUS_LOCALE errors. Every item handler relies on\n * this to translate (name, locale) into an unambiguous menu row.\n */\nasync function resolveMenu(\n\trepo: MenuRepository,\n\tname: string,\n\toptions: { locale?: string },\n): Promise<ResolveMenuResult> {\n\tconst matches = await repo.findByName(name, options);\n\tif (matches.length === 0) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\tmessage: `Menu '${name}' not found${options.locale ? ` in locale '${options.locale}'` : \"\"}`,\n\t\t\t},\n\t\t};\n\t}\n\tif (matches.length > 1) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: ambiguousMenuLocaleError(\n\t\t\t\tname,\n\t\t\t\tmatches.map((m) => m.locale),\n\t\t\t).error,\n\t\t};\n\t}\n\treturn { success: true, menu: matches[0] };\n}\n\n// ---------------------------------------------------------------------------\n// Menu handlers\n// ---------------------------------------------------------------------------\n\n/**\n * List menus with item counts. Filter by `locale` when provided.\n */\nexport async function handleMenuList(\n\tdb: Kysely<Database>,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<MenuListItem[]>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst items = await repo.findMany(options);\n\t\treturn { success: true, data: items };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_LIST_ERROR\", message: \"Failed to fetch menus\" },\n\t\t};\n\t}\n}\n\n/**\n * Create a new menu. When `translationOf` is supplied the new menu joins the\n * source menu's translation_group (and gets the source's items cloned by the\n * repository).\n */\nexport async function handleMenuCreate(\n\tdb: Kysely<Database>,\n\tinput: { name: string; label: string; locale?: string; translationOf?: string },\n): Promise<ApiResult<Menu>> {\n\ttry {\n\t\t// Translating from a source menu only makes sense when the caller\n\t\t// names the target locale: otherwise we'd silently clone into the\n\t\t// configured default, which is almost never what's intended (and\n\t\t// will collide if the source is already the default-locale menu).\n\t\t// Enforced here so REST/SDK callers get the same guard as MCP.\n\t\tif (input.translationOf && !input.locale) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\tmessage: \"`locale` is required when `translationOf` is provided\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst repo = new MenuRepository(db);\n\n\t\t// Existence check up front so the repo's \"Source not found\" throw\n\t\t// becomes a clean NOT_FOUND on the API.\n\t\tif (input.translationOf) {\n\t\t\tconst source = await repo.findById(input.translationOf);\n\t\t\tif (!source) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Source menu for translation not found\" },\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Duplicate guard: same (name, locale). Falls back to the configured\n\t\t// defaultLocale to match the column DEFAULT set by migration 036.\n\t\tconst effectiveLocale = input.locale ?? getI18nConfig()?.defaultLocale ?? \"en\";\n\t\tif (await repo.existsByNameAndLocale(input.name, effectiveLocale)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\tmessage: `Menu \"${input.name}\" already exists${\n\t\t\t\t\t\tinput.locale ? ` in locale \"${input.locale}\"` : \"\"\n\t\t\t\t\t}`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst menu = await repo.create(input);\n\t\treturn { success: true, data: menu };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_CREATE_ERROR\", message: \"Failed to create menu\" },\n\t\t};\n\t}\n}\n\n/**\n * Get a single menu by name. Honours an optional `locale` filter; when two\n * menus share a name across locales, the locale distinguishes them.\n *\n * Historical behaviour: when `locale` is omitted, returns the lowest-locale\n * match (deterministic). Mirrors the pre-repo handler.\n */\nexport async function handleMenuGet(\n\tdb: Kysely<Database>,\n\tname: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<MenuWithItems>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst matches = await repo.findByName(name, options);\n\t\tif (matches.length === 0) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: `Menu '${name}' not found` },\n\t\t\t};\n\t\t}\n\t\tconst menu = matches[0];\n\t\tconst items = await repo.findItems(menu.id);\n\t\treturn { success: true, data: { ...menu, items } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_GET_ERROR\", message: \"Failed to fetch menu\" },\n\t\t};\n\t}\n}\n\n/**\n * Get a menu by id. Useful when the caller already has the id (e.g. after\n * creating a translation and navigating to it).\n */\nexport async function handleMenuGetById(\n\tdb: Kysely<Database>,\n\tid: string,\n): Promise<ApiResult<MenuWithItems>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst menu = await repo.findWithItems(id);\n\t\tif (!menu) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: `Menu '${id}' not found` },\n\t\t\t};\n\t\t}\n\t\treturn { success: true, data: menu };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_GET_ERROR\", message: \"Failed to fetch menu\" },\n\t\t};\n\t}\n}\n\n/**\n * Update a menu's label. The name + locale are immutable.\n */\nexport async function handleMenuUpdate(\n\tdb: Kysely<Database>,\n\tname: string,\n\tinput: { label?: string; locale?: string },\n): Promise<ApiResult<Menu>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, name, { locale: input.locale });\n\t\tif (!resolved.success) return resolved;\n\t\tconst updated = await repo.update(resolved.menu.id, { label: input.label });\n\t\tif (!updated) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: `Menu '${name}' not found` },\n\t\t\t};\n\t\t}\n\t\treturn { success: true, data: updated };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_UPDATE_ERROR\", message: \"Failed to update menu\" },\n\t\t};\n\t}\n}\n\n/**\n * Delete a menu (and its items, via the repository's explicit cleanup).\n */\nexport async function handleMenuDelete(\n\tdb: Kysely<Database>,\n\tname: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<{ deleted: true }>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, name, options);\n\t\tif (!resolved.success) return resolved;\n\t\tawait repo.delete(resolved.menu.id);\n\t\treturn { success: true, data: { deleted: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_DELETE_ERROR\", message: \"Failed to delete menu\" },\n\t\t};\n\t}\n}\n\n/**\n * List every translation of a menu (by id or translation_group).\n */\nexport async function handleMenuTranslations(\n\tdb: Kysely<Database>,\n\tidOrGroup: string,\n): Promise<ApiResult<MenuTranslationsResponse>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst result = await repo.listTranslations(idOrGroup);\n\t\tif (!result) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Menu not found\" },\n\t\t\t};\n\t\t}\n\t\treturn { success: true, data: result };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_TRANSLATIONS_ERROR\", message: \"Failed to list menu translations\" },\n\t\t};\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Menu item handlers\n// ---------------------------------------------------------------------------\n\nexport type CreateMenuItemInput = CreateMenuItemRepoInput;\nexport type UpdateMenuItemInput = UpdateMenuItemRepoInput;\nexport type MenuSetItemsInput = SetMenuItem;\n\n/**\n * Add an item to a menu. The item inherits the menu's locale.\n */\nexport async function handleMenuItemCreate(\n\tdb: Kysely<Database>,\n\tmenuName: string,\n\tinput: CreateMenuItemInput,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<MenuItem>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, menuName, options);\n\t\tif (!resolved.success) return resolved;\n\n\t\tconst item = await repo.createItem(resolved.menu.id, resolved.menu.locale, input);\n\t\treturn { success: true, data: item };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_ITEM_CREATE_ERROR\", message: \"Failed to create menu item\" },\n\t\t};\n\t}\n}\n\n/**\n * Update a menu item.\n */\nexport async function handleMenuItemUpdate(\n\tdb: Kysely<Database>,\n\tmenuName: string,\n\titemId: string,\n\tinput: UpdateMenuItemInput,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<MenuItem>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, menuName, options);\n\t\tif (!resolved.success) return resolved;\n\n\t\tconst updated = await repo.updateItem(resolved.menu.id, itemId, input);\n\t\tif (!updated) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Menu item not found\" },\n\t\t\t};\n\t\t}\n\t\treturn { success: true, data: updated };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_ITEM_UPDATE_ERROR\", message: \"Failed to update menu item\" },\n\t\t};\n\t}\n}\n\n/**\n * Delete a menu item.\n */\nexport async function handleMenuItemDelete(\n\tdb: Kysely<Database>,\n\tmenuName: string,\n\titemId: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<{ deleted: true }>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, menuName, options);\n\t\tif (!resolved.success) return resolved;\n\n\t\tconst deleted = await repo.deleteItem(resolved.menu.id, itemId);\n\t\tif (!deleted) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Menu item not found\" },\n\t\t\t};\n\t\t}\n\t\treturn { success: true, data: { deleted: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_ITEM_DELETE_ERROR\", message: \"Failed to delete menu item\" },\n\t\t};\n\t}\n}\n\nexport interface ReorderItem {\n\tid: string;\n\tparentId: string | null;\n\tsortOrder: number;\n}\n\n// ---------------------------------------------------------------------------\n// Atomic-replace menu items (used by the MCP `menu_set_items` tool and admin)\n// ---------------------------------------------------------------------------\n\n/**\n * Replace the entire set of items for a menu in one atomic transaction.\n *\n * Existing items are deleted and the new list is inserted in the order\n * provided. `parentIndex` references resolve to actual parent IDs as the\n * insert proceeds.\n */\nexport async function handleMenuSetItems(\n\tdb: Kysely<Database>,\n\tmenuName: string,\n\titems: MenuSetItemsInput[],\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<{ name: string; itemCount: number }>> {\n\t// Validate parentIndex references — must be strictly earlier so the array\n\t// can be inserted in order with parents resolved first. Negative indices\n\t// are caught by Zod's `.nonnegative()` at the MCP boundary, but we guard\n\t// explicitly so REST routes / direct handler use get the same error.\n\tfor (let i = 0; i < items.length; i++) {\n\t\tconst item = items[i];\n\t\tif (item?.parentIndex !== undefined) {\n\t\t\tif (item.parentIndex < 0 || item.parentIndex >= i) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\tmessage: `item[${i}].parentIndex (${item.parentIndex}) must reference an earlier item`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, menuName, options);\n\t\tif (!resolved.success) return resolved;\n\n\t\tconst { itemCount } = await repo.setItems(resolved.menu.id, resolved.menu.locale, items);\n\t\treturn { success: true, data: { name: menuName, itemCount } };\n\t} catch (error) {\n\t\t// `MenuGoneError` is thrown from inside the repository transaction\n\t\t// when the menu was deleted concurrently between `resolveMenu` and the\n\t\t// setItems write. Returning NOT_FOUND mirrors the original handler's\n\t\t// in-transaction `notFoundSentinel` branch and keeps the response\n\t\t// shape stable for REST/MCP callers.\n\t\tif (error instanceof MenuGoneError) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\tmessage: `Menu '${menuName}' not found${\n\t\t\t\t\t\toptions.locale ? ` in locale '${options.locale}'` : \"\"\n\t\t\t\t\t}`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tconsole.error(\"[emdash] handleMenuSetItems failed:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_SET_ITEMS_ERROR\", message: \"Failed to set menu items\" },\n\t\t};\n\t}\n}\n\n/**\n * Batch reorder menu items.\n */\nexport async function handleMenuItemReorder(\n\tdb: Kysely<Database>,\n\tmenuName: string,\n\titems: ReorderItem[],\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<MenuItem[]>> {\n\ttry {\n\t\tconst repo = new MenuRepository(db);\n\t\tconst resolved = await resolveMenu(repo, menuName, options);\n\t\tif (!resolved.success) return resolved;\n\n\t\tconst updated = await repo.reorderItems(resolved.menu.id, items);\n\t\treturn { success: true, data: updated };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"MENU_REORDER_ERROR\", message: \"Failed to reorder menu items\" },\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AA6BA,IAAa,gBAAb,cAAmC,MAAM;CACxC,YAAY,AAAgB,QAAgB;AAC3C,QAAM,QAAQ,OAAO,mCAAmC;EAD7B;AAE3B,OAAK,OAAO;;;AA4Hd,SAAS,UAAU,KAAkC;AACpD,QAAO;EACN,IAAI,IAAI;EACR,MAAM,IAAI;EACV,OAAO,IAAI;EACX,WAAW,IAAI;EACf,WAAW,IAAI;EACf,QAAQ,IAAI;EACZ,kBAAkB,IAAI;EACtB;;AAGF,SAAS,cAAc,KAA0C;AAChE,QAAO;EACN,IAAI,IAAI;EACR,QAAQ,IAAI;EACZ,UAAU,IAAI;EACd,WAAW,IAAI;EACf,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GAAM,MADR,MAAM,KAAK,aAAa,SAAS,KAAK,IAAI,MAAM;GACzB;SAChC;AACP,SAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAsB,SAAS;IAAgC;GAC9E"}
|
|
@@ -159,7 +159,7 @@ async function getBackend() {
|
|
|
159
159
|
};
|
|
160
160
|
holder.backend = typeof mod.createObjectCache === "function" ? mod.createObjectCache(config) : null;
|
|
161
161
|
} catch (error) {
|
|
162
|
-
if (import.meta.env
|
|
162
|
+
if (import.meta.env?.DEV) console.warn("[object-cache] backend unavailable:", error);
|
|
163
163
|
holder.backend = null;
|
|
164
164
|
}
|
|
165
165
|
holder.initialized = true;
|
|
@@ -275,12 +275,16 @@ async function cachedQuery(options) {
|
|
|
275
275
|
});
|
|
276
276
|
await backend.set(fullKey, encoded, ttl);
|
|
277
277
|
} catch (error) {
|
|
278
|
-
if (import.meta.env
|
|
278
|
+
if (import.meta.env?.DEV) console.warn("[object-cache] set failed:", error);
|
|
279
279
|
}
|
|
280
280
|
});
|
|
281
281
|
}
|
|
282
282
|
return value;
|
|
283
283
|
}
|
|
284
|
+
/** Whether object-cache reads are active for the current request. */
|
|
285
|
+
async function isObjectCacheActive() {
|
|
286
|
+
return await getBackend() !== null && !shouldBypass();
|
|
287
|
+
}
|
|
284
288
|
/**
|
|
285
289
|
* Invalidate every cached value in `namespace` by bumping its epoch.
|
|
286
290
|
*
|
|
@@ -369,5 +373,5 @@ function invalidateCommentObjectCache() {
|
|
|
369
373
|
}
|
|
370
374
|
|
|
371
375
|
//#endregion
|
|
372
|
-
export { invalidateBylineObjectCache as a, invalidateMenuObjectCache as c, invalidateTaxonomyObjectCache as d, contentNamespaces as i, invalidateObjectCache as l, cachedQuery as n, invalidateCollectionCache as o, contentNamespace as r, invalidateCommentObjectCache as s, CacheNamespace as t, invalidateSchemaObjectCache as u };
|
|
373
|
-
//# sourceMappingURL=object-cache-
|
|
376
|
+
export { invalidateBylineObjectCache as a, invalidateMenuObjectCache as c, invalidateTaxonomyObjectCache as d, isObjectCacheActive as f, contentNamespaces as i, invalidateObjectCache as l, cachedQuery as n, invalidateCollectionCache as o, contentNamespace as r, invalidateCommentObjectCache as s, CacheNamespace as t, invalidateSchemaObjectCache as u };
|
|
377
|
+
//# sourceMappingURL=object-cache-CHbHv83-.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"object-cache-CHbHv83-.mjs","names":[],"sources":["../src/object-cache/codec.ts","../src/object-cache/index.ts"],"sourcesContent":["/**\n * Object-cache serialization codec.\n *\n * Cached values are JSON, with one extension: `Date` instances are preserved\n * across the round-trip. EmDash content entries carry `Date` objects for the\n * system timestamp columns (`createdAt`, `updatedAt`, `publishedAt`,\n * `scheduledAt`) and on `cacheHint.lastModified`; plain `JSON.stringify` would\n * silently flatten those to ISO strings, so a value read from cache would no\n * longer be `=== instanceof Date` and downstream `value instanceof Date`\n * branches (cursor encoding, scheduled-visibility checks) would diverge from a\n * fresh database read.\n *\n * Functions and symbol-keyed properties are NOT preserved — callers that cache\n * values carrying either (e.g. content entries with their `.edit` proxy and\n * the non-enumerable `CURSOR_RAW_VALUES` symbol) must reduce to a serializable\n * snapshot before caching and rebuild the non-serializable parts on read. See\n * `query.ts` content snapshot helpers.\n */\n\n/** Tag used to mark a serialized `Date`. Deliberately unlikely to collide. */\nconst DATE_TAG = \"$$emdashDate\";\n\ninterface TaggedDate {\n\t[DATE_TAG]: string;\n}\n\nfunction isTaggedDate(value: unknown): value is TaggedDate {\n\tif (typeof value !== \"object\" || value === null) return false;\n\t// encode() always emits the tag as the object's *only* key, so requiring\n\t// exactly one key keeps a user object that merely happens to carry a\n\t// `$$emdashDate` string alongside other fields from being collapsed to a\n\t// Date (which would silently drop those other fields).\n\tconst keys = Object.keys(value);\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- narrowing a JSON-parsed value to read the date tag\n\treturn keys.length === 1 && typeof (value as Record<string, unknown>)[DATE_TAG] === \"string\";\n}\n\n/**\n * Serialize a value to a cache string, preserving `Date` instances.\n *\n * Uses the JSON replacer's `this` binding to inspect the *original* property\n * value: `JSON.stringify` invokes `Date.prototype.toJSON` before the replacer\n * sees it, so by the time `value` arrives it is already an ISO string. Reading\n * `this[key]` recovers the live `Date` so we can tag it.\n */\nexport function encode(value: unknown): string {\n\treturn JSON.stringify(value, function (this: Record<string, unknown>, key, val) {\n\t\tconst original = this[key];\n\t\tif (original instanceof Date) {\n\t\t\treturn { [DATE_TAG]: original.toISOString() } satisfies TaggedDate;\n\t\t}\n\t\treturn val;\n\t});\n}\n\n/**\n * Parse a cache string produced by {@link encode}, rehydrating tagged `Date`s.\n *\n * Returns `undefined` if the input is not valid JSON (treated as a cache miss\n * by the read-through layer rather than throwing).\n */\nexport function decode(raw: string): unknown {\n\ttry {\n\t\treturn JSON.parse(raw, (_key, value) => {\n\t\t\tif (isTaggedDate(value)) {\n\t\t\t\treturn new Date(value[DATE_TAG]);\n\t\t\t}\n\t\t\treturn value;\n\t\t});\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n","/**\n * Object cache — distributed read-through query cache.\n *\n * Layering (per query):\n *\n * requestCached → in-request dedupe (per render, WeakMap on ALS context)\n * cachedQuery → THIS layer: distributed L2 (KV / memory), epoch-keyed\n * database → source of truth\n *\n * Optional and off by default: when no `objectCache` descriptor is configured,\n * `virtual:emdash/object-cache` exports `createObjectCache = undefined`,\n * {@link getBackend} resolves to `null`, and {@link cachedQuery} is a\n * transparent passthrough to its `load` function. Configure with\n * `memoryCache()` (Node) or `kvCache()` from `@emdash-cms/cloudflare`.\n *\n * Invalidation is epoch-based: each cache key embeds a per-namespace epoch\n * (\"last changed\" marker) read from the backend. A write calls\n * {@link invalidateObjectCache}, which stamps the namespace epoch to\n * `Date.now()`; every previously-stored key for that namespace is instantly\n * orphaned and reclaimed by its TTL. This is O(1) and needs no key\n * enumeration (KV has no prefix delete).\n *\n * The singleton backend/config and the per-isolate epoch cache live on\n * `globalThis` behind `Symbol.for` keys so Vite SSR chunk duplication can't\n * fork them (same pattern as `request-context.ts`).\n */\n\nimport { after } from \"../after.js\";\nimport { getRequestContext } from \"../request-context.js\";\nimport { decode, encode } from \"./codec.js\";\nimport type {\n\tCreateObjectCacheBackendFn,\n\tObjectCacheBackend,\n\tObjectCacheRuntimeConfig,\n} from \"./types.js\";\n\nconst DEFAULT_KEY_PREFIX = \"em\";\nconst DEFAULT_TTL_SECONDS = 3600;\nconst DEFAULT_REVALIDATE_MS = 1000;\nconst DEFAULT_TIMEOUT_MS = 2000;\n\ninterface BackendHolder {\n\t/** Whether the virtual module has been loaded and the backend resolved. */\n\tinitialized: boolean;\n\t/** Resolved backend, or `null` when no object cache is configured. */\n\tbackend: ObjectCacheBackend | null;\n\t/** In-flight initialization promise (dedupes concurrent first calls). */\n\tinitPromise: Promise<ObjectCacheBackend | null> | null;\n\tconfig: Required<Pick<ObjectCacheRuntimeConfig, \"keyPrefix\">> & {\n\t\tdefaultTtl: number;\n\t\trevalidate: number;\n\t\ttimeout: number;\n\t};\n}\n\n/**\n * Race a backend operation against a timeout so a stalled call (e.g. a KV read\n * that never resolves *and* never rejects — a cold cross-region read, or one\n * queued behind the Workers simultaneous-connection limit) degrades to a\n * rejection instead of hanging the isolate. A rejection is benign: callers\n * already treat a failed read as a cache miss / last-known epoch.\n */\nfunction withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {\n\tif (!(ms > 0)) return promise;\n\tlet timer: ReturnType<typeof setTimeout>;\n\tconst timeout = new Promise<never>((_resolve, reject) => {\n\t\ttimer = setTimeout(() => {\n\t\t\treject(new Error(`object-cache ${label} timed out after ${ms}ms`));\n\t\t}, ms);\n\t});\n\treturn Promise.race([promise, timeout]).finally(() => clearTimeout(timer));\n}\n\ninterface EpochEntry {\n\tvalue: number;\n\t/** `Date.now()` at which this epoch was read from the backend. */\n\tat: number;\n\t/** In-flight read, so concurrent callers share one backend round-trip. */\n\tpromise?: Promise<number>;\n}\n\nconst BACKEND_KEY = Symbol.for(\"emdash:object-cache:backend\");\nconst EPOCH_KEY = Symbol.for(\"emdash:object-cache:epochs\");\nconst PENDING_KEY = Symbol.for(\"emdash:object-cache:pending-bumps\");\nconst g = globalThis as Record<symbol, unknown>;\n\nconst holder: BackendHolder =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see request-context.ts)\n\t(g[BACKEND_KEY] as BackendHolder | undefined) ??\n\t(() => {\n\t\tconst h: BackendHolder = {\n\t\t\tinitialized: false,\n\t\t\tbackend: null,\n\t\t\tinitPromise: null,\n\t\t\tconfig: {\n\t\t\t\tkeyPrefix: DEFAULT_KEY_PREFIX,\n\t\t\t\tdefaultTtl: DEFAULT_TTL_SECONDS,\n\t\t\t\trevalidate: DEFAULT_REVALIDATE_MS,\n\t\t\t\ttimeout: DEFAULT_TIMEOUT_MS,\n\t\t\t},\n\t\t};\n\t\tg[BACKEND_KEY] = h;\n\t\treturn h;\n\t})();\n\nconst epochCache: Map<string, EpochEntry> =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see request-context.ts)\n\t(g[EPOCH_KEY] as Map<string, EpochEntry> | undefined) ??\n\t(() => {\n\t\tconst m = new Map<string, EpochEntry>();\n\t\tg[EPOCH_KEY] = m;\n\t\treturn m;\n\t})();\n\n/** Namespaces with a backend epoch write already scheduled this tick. */\nconst pendingBumps: Set<string> =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see request-context.ts)\n\t(g[PENDING_KEY] as Set<string> | undefined) ??\n\t(() => {\n\t\tconst s = new Set<string>();\n\t\tg[PENDING_KEY] = s;\n\t\treturn s;\n\t})();\n\n/**\n * Resolve (once per isolate) the configured object-cache backend.\n *\n * Loads `virtual:emdash/object-cache`, which exports `createObjectCache`\n * (`undefined` when no cache is configured) and the serialized\n * `objectCacheConfig`. Returns `null` when the cache is disabled.\n */\nasync function getBackend(): Promise<ObjectCacheBackend | null> {\n\tif (holder.initialized) return holder.backend;\n\tif (holder.initPromise) return holder.initPromise;\n\n\tholder.initPromise = (async () => {\n\t\ttry {\n\t\t\tconst mod: {\n\t\t\t\tcreateObjectCache?: CreateObjectCacheBackendFn;\n\t\t\t\tobjectCacheConfig?: ObjectCacheRuntimeConfig;\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n\t\t\t\t// @ts-ignore - virtual module\n\t\t\t} = await import(\"virtual:emdash/object-cache\");\n\n\t\t\tconst config = mod.objectCacheConfig ?? {};\n\t\t\tholder.config = {\n\t\t\t\tkeyPrefix:\n\t\t\t\t\ttypeof config.keyPrefix === \"string\" && config.keyPrefix.length > 0\n\t\t\t\t\t\t? config.keyPrefix\n\t\t\t\t\t\t: DEFAULT_KEY_PREFIX,\n\t\t\t\tdefaultTtl:\n\t\t\t\t\ttypeof config.defaultTtl === \"number\" && config.defaultTtl > 0\n\t\t\t\t\t\t? config.defaultTtl\n\t\t\t\t\t\t: DEFAULT_TTL_SECONDS,\n\t\t\t\trevalidate:\n\t\t\t\t\ttypeof config.revalidate === \"number\" && config.revalidate >= 0\n\t\t\t\t\t\t? config.revalidate\n\t\t\t\t\t\t: DEFAULT_REVALIDATE_MS,\n\t\t\t\ttimeout:\n\t\t\t\t\ttypeof config.timeout === \"number\" && config.timeout >= 0\n\t\t\t\t\t\t? config.timeout\n\t\t\t\t\t\t: DEFAULT_TIMEOUT_MS,\n\t\t\t};\n\n\t\t\tholder.backend =\n\t\t\t\ttypeof mod.createObjectCache === \"function\" ? mod.createObjectCache(config) : null;\n\t\t} catch (error) {\n\t\t\t// Importing the virtual module fails outside an Astro/Vite context\n\t\t\t// (e.g. unit tests, CLI). Treat as \"no cache configured\".\n\t\t\tif (import.meta.env?.DEV) {\n\t\t\t\tconsole.warn(\"[object-cache] backend unavailable:\", error);\n\t\t\t}\n\t\t\tholder.backend = null;\n\t\t}\n\t\tholder.initialized = true;\n\t\tholder.initPromise = null;\n\t\treturn holder.backend;\n\t})();\n\n\treturn holder.initPromise;\n}\n\n/**\n * Test-only override of the backend, bypassing the virtual module.\n *\n * Lets unit tests inject an in-memory backend (and optional config) without a\n * full Astro/Vite build. Pass `null` to simulate \"no cache configured\".\n *\n * @internal\n */\nexport function __setObjectCacheBackendForTests(\n\tbackend: ObjectCacheBackend | null,\n\tconfig?: Partial<BackendHolder[\"config\"]>,\n): void {\n\tholder.initialized = true;\n\tholder.initPromise = null;\n\tholder.backend = backend;\n\tholder.config = { ...holder.config, ...config };\n\tepochCache.clear();\n}\n\n/** Build the backend key for a namespace's epoch anchor. */\nfunction epochKey(namespace: string): string {\n\treturn `${holder.config.keyPrefix}:epoch:${namespace}`;\n}\n\n/**\n * Build the (epoch-independent) backend key for a cached value.\n *\n * The key is stable across invalidations — the namespace epochs are stored\n * *inside* the value envelope and validated on read, not baked into the key.\n * This lets the value and the epochs be fetched in one parallel round-trip\n * (instead of \"read epoch, then read value\"), and means an invalidated value\n * is overwritten in place rather than orphaned under a dead epoch-keyed name.\n */\nfunction valueKey(namespaces: readonly string[], key: string): string {\n\treturn `${holder.config.keyPrefix}:${namespaces.join(\",\")}:${key}`;\n}\n\n/**\n * Stored cache envelope: the namespace epochs captured at write time alongside\n * the cached value. A read is a HIT only when every stored epoch still matches\n * the current epoch for its namespace.\n */\ninterface CacheEnvelope<T> {\n\t/** Epoch per namespace, in the query's namespace order. */\n\te: number[];\n\t/** The cached value. */\n\tv: T;\n}\n\nfunction epochsMatch(stored: readonly number[], current: readonly number[]): boolean {\n\tif (stored.length !== current.length) return false;\n\tfor (let i = 0; i < stored.length; i++) {\n\t\tif (stored[i] !== current[i]) return false;\n\t}\n\treturn true;\n}\n\n/**\n * Requests that must always read live data and never populate the cache:\n * visual edit mode, preview tokens, and isolated databases (playground / DO\n * preview, whose schema and content diverge from the configured site).\n */\nfunction shouldBypass(): boolean {\n\tconst ctx = getRequestContext();\n\tif (!ctx) return false;\n\treturn ctx.editMode === true || ctx.preview !== undefined || ctx.dbIsIsolated === true;\n}\n\n/**\n * Read the current epoch for `namespace`, reusing an isolate-cached value for\n * up to `revalidate` ms. A missing epoch (never bumped) is treated as `0`.\n *\n * Backend errors and stalls are non-fatal: the read is bounded by a timeout,\n * and on failure we fall back to the last known epoch (or `0`), so a flaky or\n * hung cache degrades to \"serve whatever's keyed\" rather than throwing or\n * hanging.\n */\nasync function getEpoch(namespace: string, backend: ObjectCacheBackend): Promise<number> {\n\tconst now = Date.now();\n\tconst cached = epochCache.get(namespace);\n\tif (cached && now - cached.at < holder.config.revalidate) {\n\t\treturn cached.value;\n\t}\n\tif (cached?.promise) return cached.promise;\n\n\tconst promise = (async () => {\n\t\tlet value: number;\n\t\ttry {\n\t\t\tconst raw = await withTimeout(\n\t\t\t\tbackend.get(epochKey(namespace)),\n\t\t\t\tholder.config.timeout,\n\t\t\t\t\"epoch read\",\n\t\t\t);\n\t\t\tconst parsed = raw === null ? 0 : Number(raw);\n\t\t\tvalue = Number.isFinite(parsed) ? parsed : 0;\n\t\t} catch {\n\t\t\tvalue = cached?.value ?? 0;\n\t\t}\n\t\t// A concurrent invalidateObjectCache may have bumped the epoch while this\n\t\t// read was in flight. Epochs are monotonic, so never let a stale backend\n\t\t// read lower a freshly-bumped local epoch — that would resurrect the very\n\t\t// values the bump just invalidated.\n\t\tconst merged = Math.max(value, epochCache.get(namespace)?.value ?? 0);\n\t\tepochCache.set(namespace, { value: merged, at: Date.now() });\n\t\treturn merged;\n\t})();\n\n\t// Concurrent callers share this in-flight read (dedup). The timeout above\n\t// guarantees `promise` settles — its success/catch handler then replaces\n\t// this entry with a fresh, promise-free one — so a stalled backend can no\n\t// longer pin the namespace to a never-settling promise (the bug that\n\t// poisoned an isolate until it was recycled).\n\tepochCache.set(namespace, { value: cached?.value ?? 0, at: cached?.at ?? 0, promise });\n\treturn promise;\n}\n\n/** Options for {@link cachedQuery}. */\nexport interface CachedQueryOptions<T> {\n\t/**\n\t * Invalidation namespace(s). A single string for self-contained data\n\t * (`settings`, `menus`), or several when the cached value depends on data\n\t * owned by other namespaces — e.g. a content entry hydrates bylines and\n\t * taxonomy terms, so it caches under\n\t * `[content:posts, \"bylines\", \"taxonomies\"]` and is invalidated when *any*\n\t * of them is bumped. Every namespace's epoch is folded into the key.\n\t */\n\tnamespace: string | readonly string[];\n\t/** Stable, fully-qualifying cache key *within* the namespace. */\n\tkey: string;\n\t/** Loader run on a miss (or when caching is disabled/bypassed). */\n\tload: () => Promise<T>;\n\t/** TTL override in seconds. Falls back to the configured `defaultTtl`. */\n\tttl?: number;\n\t/**\n\t * Predicate gating whether a freshly-loaded value is stored. Defaults to\n\t * always-cache. Use it to skip caching error/empty sentinels.\n\t */\n\tcacheable?: (value: T) => boolean;\n}\n\n/**\n * Distributed read-through cache around `load`.\n *\n * `T` must be the value as it should be *stored* — i.e. JSON-serializable with\n * the codec's `Date` support, carrying no functions or symbol-keyed props.\n * Callers caching richer objects (content entries) reduce to a serializable\n * snapshot here and rebuild on the way out; see `query.ts`.\n *\n * On a miss or when the cache is disabled/bypassed, this is equivalent to\n * `await load()`. Backend errors never propagate: a failing `get` is a miss, a\n * failing `set` is dropped.\n */\nexport async function cachedQuery<T>(options: CachedQueryOptions<T>): Promise<T> {\n\tconst backend = await getBackend();\n\tif (!backend || shouldBypass()) {\n\t\treturn options.load();\n\t}\n\n\tconst namespaces =\n\t\ttypeof options.namespace === \"string\" ? [options.namespace] : options.namespace;\n\tconst fullKey = valueKey(namespaces, options.key);\n\n\t// Kick off the value read and every namespace epoch read concurrently — one\n\t// round-trip instead of \"read epochs, then read value\". getEpoch never\n\t// rejects, so awaiting the epochs separately from the value read guarantees\n\t// we hold the pre-load epochs even when the value read errors or times out.\n\t// Storing a value under an epoch read *after* load() would mask a write that\n\t// landed during load(): the stale value would match and be served as a HIT.\n\tconst epochsPromise = Promise.all(namespaces.map((ns) => getEpoch(ns, backend)));\n\tconst rawPromise = withTimeout(backend.get(fullKey), holder.config.timeout, \"read\").catch(\n\t\t() => null,\n\t);\n\tconst currentEpochs = await epochsPromise;\n\tconst raw = await rawPromise;\n\tif (raw !== null) {\n\t\tconst decoded = decode(raw);\n\t\tif (decoded !== undefined) {\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- value envelope written by this function\n\t\t\tconst envelope = decoded as CacheEnvelope<T>;\n\t\t\tif (epochsMatch(envelope.e, currentEpochs)) {\n\t\t\t\treturn envelope.v;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst value = await options.load();\n\n\tconst cacheable = options.cacheable ? options.cacheable(value) : true;\n\tif (cacheable) {\n\t\tconst ttl = options.ttl ?? holder.config.defaultTtl;\n\t\t// Defer the write so it never adds to TTFB. The epochs were captured\n\t\t// before load() ran, so a write that invalidated this namespace mid-load\n\t\t// correctly orphans the value stored here.\n\t\tafter(async () => {\n\t\t\ttry {\n\t\t\t\tconst encoded = encode({ e: currentEpochs, v: value } satisfies CacheEnvelope<T>);\n\t\t\t\tawait backend.set(fullKey, encoded, ttl);\n\t\t\t} catch (error) {\n\t\t\t\tif (import.meta.env?.DEV) {\n\t\t\t\t\tconsole.warn(\"[object-cache] set failed:\", error);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\treturn value;\n}\n\n/** Whether object-cache reads are active for the current request. */\nexport async function isObjectCacheActive(): Promise<boolean> {\n\tconst backend = await getBackend();\n\treturn backend !== null && !shouldBypass();\n}\n\n/**\n * Invalidate every cached value in `namespace` by bumping its epoch.\n *\n * Sync and non-blocking: the local epoch is stamped immediately (so the\n * writing isolate is instantly consistent) and the backend write is deferred\n * via `after`. Other isolates pick up the new epoch within their `revalidate`\n * window. No-ops when the cache is disabled.\n */\nexport function invalidateObjectCache(namespace: string): void {\n\t// Monotonic so two writes in the same millisecond still produce distinct\n\t// epochs — otherwise the second write reuses the first's stamp and its\n\t// stale entries survive.\n\tconst prev = epochCache.get(namespace)?.value ?? 0;\n\tconst stamp = Math.max(prev + 1, Date.now());\n\t// Optimistic local bump: keep this isolate consistent without a round-trip.\n\tepochCache.set(namespace, { value: stamp, at: stamp });\n\n\t// Coalesce repeated bumps of the same namespace within a tick (e.g. a bulk\n\t// publish loop) into a single backend write that persists the latest epoch.\n\tif (pendingBumps.has(namespace)) return;\n\tpendingBumps.add(namespace);\n\tafter(async () => {\n\t\tpendingBumps.delete(namespace);\n\t\ttry {\n\t\t\tconst backend = await getBackend();\n\t\t\tif (!backend) return;\n\t\t\tconst latest = epochCache.get(namespace)?.value ?? stamp;\n\t\t\t// Epoch anchors are persistent (no TTL) — they must outlive the\n\t\t\t// value keys they invalidate.\n\t\t\tawait backend.set(epochKey(namespace), String(latest));\n\t\t} catch (error) {\n\t\t\tconsole.error(\"[object-cache] epoch bump failed for\", namespace, error);\n\t\t}\n\t});\n}\n\n/**\n * Fixed namespaces for data shared across collections. Content reads fold the\n * `BYLINES` and `TAXONOMIES` epochs into their keys (via {@link cachedQuery})\n * because entries hydrate byline and taxonomy-term data — so renaming an\n * author or a category correctly invalidates every cached entry that displays\n * it, without tracking which collections reference it.\n */\nexport const CacheNamespace = {\n\tSETTINGS: \"settings\",\n\tMENUS: \"menus\",\n\tTAXONOMIES: \"taxonomies\",\n\tBYLINES: \"bylines\",\n\t/** Collection schema/metadata (label, supports, commentsEnabled, fields). */\n\tSCHEMA: \"schema\",\n\t/** Public (approved) comments. */\n\tCOMMENTS: \"comments\",\n} as const;\n\n/** Namespace for a content collection's cached queries. */\nexport function contentNamespace(collection: string): string {\n\treturn `content:${collection}`;\n}\n\n/**\n * Namespaces a content read depends on: the collection itself plus the shared\n * byline/taxonomy data folded into each entry.\n */\nexport function contentNamespaces(collection: string): readonly string[] {\n\treturn [contentNamespace(collection), CacheNamespace.BYLINES, CacheNamespace.TAXONOMIES];\n}\n\n/**\n * Invalidate all cached reads (list + entry) for a content collection.\n * Call from every write path that mutates rows in `ec_<collection>`.\n */\nexport function invalidateCollectionCache(collection: string): void {\n\tinvalidateObjectCache(contentNamespace(collection));\n}\n\n/** Invalidate cached taxonomy definitions/terms and all content that hydrates them. */\nexport function invalidateTaxonomyObjectCache(): void {\n\tinvalidateObjectCache(CacheNamespace.TAXONOMIES);\n}\n\n/** Invalidate cached bylines and all content that hydrates them. */\nexport function invalidateBylineObjectCache(): void {\n\tinvalidateObjectCache(CacheNamespace.BYLINES);\n}\n\n/** Invalidate cached navigation menus. */\nexport function invalidateMenuObjectCache(): void {\n\tinvalidateObjectCache(CacheNamespace.MENUS);\n}\n\n/** Invalidate cached collection schema/metadata reads (e.g. getCollectionInfo). */\nexport function invalidateSchemaObjectCache(): void {\n\tinvalidateObjectCache(CacheNamespace.SCHEMA);\n}\n\n/** Invalidate cached public comment reads. */\nexport function invalidateCommentObjectCache(): void {\n\tinvalidateObjectCache(CacheNamespace.COMMENTS);\n}\n\nexport type {\n\tObjectCacheBackend,\n\tObjectCacheDescriptor,\n\tObjectCacheRuntimeConfig,\n} from \"./types.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoBA,MAAM,WAAW;AAMjB,SAAS,aAAa,OAAqC;AAC1D,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AAOxD,QAFa,OAAO,KAAK,MAAM,CAEnB,WAAW,KAAK,OAAQ,MAAkC,cAAc;;;;;;;;;;AAWrF,SAAgB,OAAO,OAAwB;AAC9C,QAAO,KAAK,UAAU,OAAO,SAAyC,KAAK,KAAK;EAC/E,MAAM,WAAW,KAAK;AACtB,MAAI,oBAAoB,KACvB,QAAO,GAAG,WAAW,SAAS,aAAa,EAAE;AAE9C,SAAO;GACN;;;;;;;;AASH,SAAgB,OAAO,KAAsB;AAC5C,KAAI;AACH,SAAO,KAAK,MAAM,MAAM,MAAM,UAAU;AACvC,OAAI,aAAa,MAAM,CACtB,QAAO,IAAI,KAAK,MAAM,UAAU;AAEjC,UAAO;IACN;SACK;AACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AClCF,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAC9B,MAAM,qBAAqB;;;;;;;;AAuB3B,SA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,uBAAsB,eAAe,MAAM;;;AAI5C,SAAgB,8BAAoC;AACnD,uBAAsB,eAAe,OAAO;;;AAI7C,SAAgB,+BAAqC;AACpD,uBAAsB,eAAe,SAAS"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as ContentItem } from "./types-ETmO_jQr.mjs";
|
|
2
|
-
import { t as Database } from "./types-
|
|
2
|
+
import { t as Database } from "./types-xIfVRNLp.mjs";
|
|
3
3
|
import { Kysely } from "kysely";
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
|
|
@@ -204,4 +204,4 @@ declare class OptionsRepository {
|
|
|
204
204
|
}
|
|
205
205
|
//#endregion
|
|
206
206
|
export { parseQuery as a, handleError as c, ContentListResponse as d, ContentResponse as f, ManifestResponse as h, parseBody as i, ApiContext as l, ListResponse as m, ParseResult as n, apiError as o, FieldDescriptor as p, isParseError as r, apiSuccess as s, OptionsRepository as t, ApiResult as u };
|
|
207
|
-
//# sourceMappingURL=options-
|
|
207
|
+
//# sourceMappingURL=options-41nCWqi9.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options-
|
|
1
|
+
{"version":3,"file":"options-41nCWqi9.d.mts","names":[],"sources":["../src/api/types.ts","../src/api/error.ts","../src/api/parse.ts","../src/database/repositories/options.ts"],"mappings":";;;;;;;;AASA;UAAiB,YAAA;EAChB,KAAA,EAAO,CAAA;EACP,UAAA;EAF6B;;;;;EAQ7B,KAAA;AAAA;AAMD;;;AAAA,UAAiB,mBAAA,SAA4B,YAAA,CAAa,WAAA;AAAA,UAEzC,eAAA;EAChB,IAAA,EAAM,WAAA;;EAEN,IAAA;AAAA;;;;UAMgB,gBAAA;EAChB,OAAA;EACA,IAAA;EACA,WAAA,EAAa,MAAA;IAGX,KAAA;IACA,aAAA;IACA,QAAA;IACA,MAAA,EAAQ,MAAA,SAAe,eAAA;EAAA;EAGzB,OAAA,EAAS,MAAA;IAGP,UAAA,GAAa,KAAA;MAAQ,IAAA;MA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,IAAA,WAAe,OAAA,CAAQ,CAAA;EHHzC;;AAMN;EGYO,YAAA,GAAA,CAAgB,IAAA,UAAc,YAAA,EAAc,CAAA,GAAI,OAAA,CAAQ,CAAA;;;;EAQxD,GAAA,aAAA,CAAiB,IAAA,UAAc,KAAA,EAAO,CAAA,GAAI,OAAA;EHlBjB;;;;;;;;EGwCzB,WAAA,aAAA,CAAyB,IAAA,UAAc,KAAA,EAAO,CAAA,GAAI,OAAA;EH/BxB;;;EGmD1B,MAAA,CAAO,IAAA,WAAe,OAAA;EHhDf;;;EGyDP,MAAA,CAAO,IAAA,WAAe,OAAA;EHhDb;;;EG6DT,OAAA,aAAA,CAAqB,KAAA,aAAkB,OAAA,CAAQ,GAAA,SAAY,CAAA;EHtEpD;;;EG0FP,OAAA,aAAA,CAAqB,OAAA,EAAS,MAAA,SAAe,CAAA,IAAK,OAAA;EHpFtD;;;EGgGI,MAAA,CAAA,GAAU,OAAA,CAAQ,GAAA;EH7Ff;;;EG0GH,WAAA,aAAA,CAAyB,MAAA,WAAiB,OAAA,CAAQ,GAAA,SAAY,CAAA;EHvG/B;;;EG0H/B,cAAA,CAAe,MAAA,WAAiB,OAAA;AAAA"}
|
package/dist/page/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as SeoSettings } from "../types-
|
|
1
|
+
import { et as PageFragmentContribution, ot as PageMetadataLinkRel, rt as PageMetadataContribution, st as PagePlacement, t as BreadcrumbItem, xt as PublicPageContext } from "../types-BYnDBVwe.mjs";
|
|
2
|
+
import { n as SeoSettings } from "../types-BkZ8DUEI.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/page/context.d.ts
|
|
5
5
|
/** Fields shared by both input forms */
|
|
@@ -78,6 +78,9 @@ interface ResolvedPageMetadata {
|
|
|
78
78
|
json: string;
|
|
79
79
|
}>;
|
|
80
80
|
}
|
|
81
|
+
interface RenderPageMetadataOptions {
|
|
82
|
+
includeJsonLd?: boolean;
|
|
83
|
+
}
|
|
81
84
|
/** Escape a string for safe use in an HTML attribute value */
|
|
82
85
|
declare function escapeHtmlAttr(value: string): string;
|
|
83
86
|
/**
|
|
@@ -95,7 +98,7 @@ declare function safeJsonLdSerialize(value: unknown): string;
|
|
|
95
98
|
*/
|
|
96
99
|
declare function resolvePageMetadata(contributions: PageMetadataContribution[]): ResolvedPageMetadata;
|
|
97
100
|
/** Render resolved metadata to an HTML string for embedding in <head> */
|
|
98
|
-
declare function renderPageMetadata(metadata: ResolvedPageMetadata): string;
|
|
101
|
+
declare function renderPageMetadata(metadata: ResolvedPageMetadata, options?: RenderPageMetadataOptions): string;
|
|
99
102
|
//#endregion
|
|
100
103
|
//#region src/page/fragments.d.ts
|
|
101
104
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/page/context.ts","../../src/page/metadata.ts","../../src/page/fragments.ts","../../src/page/seo-contributions.ts","../../src/page/jsonld.ts","../../src/page/index.ts"],"mappings":";;;;;UAUU,iBAAA;EACT,IAAA;EACA,QAAA;EACA,KAAA;EACA,SAAA;EACA,WAAA;EACA,SAAA;EACA,KAAA;EACA,OAAA;IAAY,UAAA;IAAoB,EAAA;IAAY,IAAA;EAAA;EAI3C;EAFD,GAAA;IACC,OAAA;IACA,aAAA;IACA,OAAA;IACA,MAAA;EAAA;EASD;EANA,WAAA;IACC,aAAA;IACA,YAAA;IACA,MAAA;EAAA;EAeQ;EAZT,QAAA;;;;;;EAMA,WAAA,GAAc,cAAA;EAOK;EALnB,OAAA;AAAA;AAKgC;AAAA,UADvB,UAAA,SAAmB,iBAAA;EAC5B,KAAA;IAAS,GAAA,EAAK,GAAA;IAAK,aAAA;EAAA;AAAA;;UAIV,QAAA,SAAiB,iBAAA;EAC1B,GAAA,EAAK,GAAA;EACL,MAAA;AAAA;AAAA,KAGW,4BAAA,GAA+B,UAAA,GAAa,QAAA;;;AASxD;iBAAgB,uBAAA,CAAwB,KAAA,EAAO,4BAAA,GAA+B,iBAAA;;;UCrD7D,oBAAA;EAChB,IAAA,EAAM,KAAA;IAAQ,IAAA;IAAc,OAAA;EAAA;EAC5B,UAAA,EAAY,KAAA;IAAQ,QAAA;IAAkB,OAAA;EAAA;EACtC,KAAA,EAAO,KAAA;IACN,GAAA,EAAK,mBAAA;IACL,IAAA;IACA,QAAA;EAAA;EAED,MAAA,EAAQ,KAAA;IAAQ,EAAA;IAAa,IAAA;EAAA;AAAA;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/page/context.ts","../../src/page/metadata.ts","../../src/page/fragments.ts","../../src/page/seo-contributions.ts","../../src/page/jsonld.ts","../../src/page/index.ts"],"mappings":";;;;;UAUU,iBAAA;EACT,IAAA;EACA,QAAA;EACA,KAAA;EACA,SAAA;EACA,WAAA;EACA,SAAA;EACA,KAAA;EACA,OAAA;IAAY,UAAA;IAAoB,EAAA;IAAY,IAAA;EAAA;EAI3C;EAFD,GAAA;IACC,OAAA;IACA,aAAA;IACA,OAAA;IACA,MAAA;EAAA;EASD;EANA,WAAA;IACC,aAAA;IACA,YAAA;IACA,MAAA;EAAA;EAeQ;EAZT,QAAA;;;;;;EAMA,WAAA,GAAc,cAAA;EAOK;EALnB,OAAA;AAAA;AAKgC;AAAA,UADvB,UAAA,SAAmB,iBAAA;EAC5B,KAAA;IAAS,GAAA,EAAK,GAAA;IAAK,aAAA;EAAA;AAAA;;UAIV,QAAA,SAAiB,iBAAA;EAC1B,GAAA,EAAK,GAAA;EACL,MAAA;AAAA;AAAA,KAGW,4BAAA,GAA+B,UAAA,GAAa,QAAA;;;AASxD;iBAAgB,uBAAA,CAAwB,KAAA,EAAO,4BAAA,GAA+B,iBAAA;;;UCrD7D,oBAAA;EAChB,IAAA,EAAM,KAAA;IAAQ,IAAA;IAAc,OAAA;EAAA;EAC5B,UAAA,EAAY,KAAA;IAAQ,QAAA;IAAkB,OAAA;EAAA;EACtC,KAAA,EAAO,KAAA;IACN,GAAA,EAAK,mBAAA;IACL,IAAA;IACA,QAAA;EAAA;EAED,MAAA,EAAQ,KAAA;IAAQ,EAAA;IAAa,IAAA;EAAA;AAAA;AAAA,UAGpB,yBAAA;EACT,aAAA;AAAA;;iBAiBe,cAAA,CAAe,KAAA;;;;ADCvB;;;;;iBCuBQ,mBAAA,CAAoB,KAAA;;;;;iBAwBpB,mBAAA,CACf,aAAA,EAAe,wBAAA,KACb,oBAAA;;iBAiFa,kBAAA,CACf,QAAA,EAAU,oBAAA,EACV,OAAA,GAAS,yBAAA;;;;;;;;iBCzJM,gBAAA,CACf,aAAA,EAAe,wBAAA,IACf,SAAA,EAAW,aAAA,GACT,wBAAA;;iBA2Da,eAAA,CACf,aAAA,EAAe,wBAAA,IACf,SAAA,EAAW,aAAA;;;;;;;;;;;;;iBCzDI,4BAAA,CACf,IAAA,EAAM,iBAAA,EACN,cAAA,mBACE,wBAAA;;;;;;;;iBA8Ha,4BAAA,CACf,WAAA,EAAa,WAAA,eACX,wBAAA;;;;;;;iBCjJa,WAAA,CAAY,GAAA,EAAK,MAAA,oBAA0B,MAAA;;;;;;;;;;iBAwB3C,sBAAA,CACf,IAAA,EAAM,iBAAA,EACN,cAAA,mBACE,MAAA;;;;;iBA2Ca,kBAAA,CAAmB,IAAA,EAAM,iBAAA,GAAoB,MAAA;;;;;;;UClD5C,iBAAA;EAChB,mBAAA,GAAsB,IAAA,EAAM,iBAAA,KAAsB,OAAA,CAAQ,wBAAA;EAC1D,oBAAA,GAAuB,IAAA,EAAM,iBAAA,KAAsB,OAAA,CAAQ,wBAAA;AAAA;;;;;iBAO5C,cAAA,CAAe,MAAA,EAAQ,MAAA,oBAA0B,iBAAA"}
|
package/dist/page/index.mjs
CHANGED
|
@@ -148,8 +148,9 @@ function resolvePageMetadata(contributions) {
|
|
|
148
148
|
return result;
|
|
149
149
|
}
|
|
150
150
|
/** Render resolved metadata to an HTML string for embedding in <head> */
|
|
151
|
-
function renderPageMetadata(metadata) {
|
|
151
|
+
function renderPageMetadata(metadata, options = {}) {
|
|
152
152
|
const parts = [];
|
|
153
|
+
const includeJsonLd = options.includeJsonLd ?? true;
|
|
153
154
|
for (const m of metadata.meta) parts.push(`<meta name="${escapeHtmlAttr(m.name)}" content="${escapeHtmlAttr(m.content)}">`);
|
|
154
155
|
for (const p of metadata.properties) parts.push(`<meta property="${escapeHtmlAttr(p.property)}" content="${escapeHtmlAttr(p.content)}">`);
|
|
155
156
|
for (const l of metadata.links) {
|
|
@@ -158,7 +159,7 @@ function renderPageMetadata(metadata) {
|
|
|
158
159
|
tag += ">";
|
|
159
160
|
parts.push(tag);
|
|
160
161
|
}
|
|
161
|
-
for (const j of metadata.jsonld) parts.push(`<script type="application/ld+json">${j.json}<\/script>`);
|
|
162
|
+
if (includeJsonLd) for (const j of metadata.jsonld) parts.push(`<script type="application/ld+json">${j.json}<\/script>`);
|
|
162
163
|
return parts.join("\n");
|
|
163
164
|
}
|
|
164
165
|
|