emdash 0.30.0 → 0.31.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.
Files changed (387) hide show
  1. package/dist/api/route-utils.mjs +13 -13
  2. package/dist/api/schemas/index.d.mts +1 -1
  3. package/dist/api/schemas/index.mjs +3 -3
  4. package/dist/{api-b8WIiGU4.mjs → api-EibxGP-V.mjs} +23 -23
  5. package/dist/api-EibxGP-V.mjs.map +1 -0
  6. package/dist/{apply-CmIJK9j8.mjs → apply-fGHCAwWN.mjs} +26 -25
  7. package/dist/apply-fGHCAwWN.mjs.map +1 -0
  8. package/dist/astro/index.d.mts +2 -2
  9. package/dist/astro/index.mjs +1 -1
  10. package/dist/astro/middleware/auth.d.mts +2 -2
  11. package/dist/astro/middleware/auth.mjs +2 -2
  12. package/dist/astro/middleware/redirect.mjs +5 -5
  13. package/dist/astro/middleware/request-context.mjs +1 -1
  14. package/dist/astro/middleware.d.mts +2 -2
  15. package/dist/astro/middleware.mjs +139 -68
  16. package/dist/astro/middleware.mjs.map +1 -1
  17. package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs +6 -6
  18. package/dist/astro/routes/api/admin/allowed-domains/index.mjs +6 -6
  19. package/dist/astro/routes/api/admin/api-tokens/_id_.mjs +2 -2
  20. package/dist/astro/routes/api/admin/api-tokens/index.mjs +3 -3
  21. package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +3 -3
  22. package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +7 -7
  23. package/dist/astro/routes/api/admin/byline-fields/index.mjs +7 -7
  24. package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +7 -7
  25. package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +14 -14
  26. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +14 -14
  27. package/dist/astro/routes/api/admin/bylines/index.d.mts.map +1 -1
  28. package/dist/astro/routes/api/admin/bylines/index.mjs +18 -17
  29. package/dist/astro/routes/api/admin/bylines/index.mjs.map +1 -1
  30. package/dist/astro/routes/api/admin/comments/_id_/status.mjs +10 -10
  31. package/dist/astro/routes/api/admin/comments/_id_.mjs +5 -5
  32. package/dist/astro/routes/api/admin/comments/bulk.mjs +9 -9
  33. package/dist/astro/routes/api/admin/comments/counts.mjs +5 -5
  34. package/dist/astro/routes/api/admin/comments/index.mjs +9 -9
  35. package/dist/astro/routes/api/admin/hooks/exclusive/_hookName_.mjs +4 -4
  36. package/dist/astro/routes/api/admin/hooks/exclusive/index.mjs +3 -3
  37. package/dist/astro/routes/api/admin/media-usage/repair.mjs +10 -10
  38. package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs +3 -3
  39. package/dist/astro/routes/api/admin/oauth-clients/index.mjs +3 -3
  40. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +34 -34
  41. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +34 -34
  42. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +34 -34
  43. package/dist/astro/routes/api/admin/plugins/_id_/mcp.mjs +4 -4
  44. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs +34 -34
  45. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +34 -34
  46. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +34 -34
  47. package/dist/astro/routes/api/admin/plugins/index.mjs +34 -34
  48. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +3 -3
  49. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +34 -34
  50. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +34 -34
  51. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +34 -34
  52. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +34 -34
  53. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +35 -35
  54. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +34 -34
  55. package/dist/astro/routes/api/admin/plugins/registry/install.mjs +35 -35
  56. package/dist/astro/routes/api/admin/plugins/updates.mjs +34 -34
  57. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +34 -34
  58. package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +3 -3
  59. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +34 -34
  60. package/dist/astro/routes/api/admin/users/_id_/disable.mjs +2 -2
  61. package/dist/astro/routes/api/admin/users/_id_/enable.mjs +2 -2
  62. package/dist/astro/routes/api/admin/users/_id_/index.mjs +6 -6
  63. package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +2 -2
  64. package/dist/astro/routes/api/admin/users/index.mjs +6 -6
  65. package/dist/astro/routes/api/auth/dev-bypass.mjs +4 -4
  66. package/dist/astro/routes/api/auth/invite/accept.mjs +2 -2
  67. package/dist/astro/routes/api/auth/invite/complete.mjs +6 -6
  68. package/dist/astro/routes/api/auth/invite/index.mjs +6 -6
  69. package/dist/astro/routes/api/auth/invite/register-options.mjs +6 -6
  70. package/dist/astro/routes/api/auth/logout.mjs +2 -2
  71. package/dist/astro/routes/api/auth/magic-link/send.mjs +7 -7
  72. package/dist/astro/routes/api/auth/magic-link/verify.mjs +2 -2
  73. package/dist/astro/routes/api/auth/me.mjs +7 -7
  74. package/dist/astro/routes/api/auth/mode.mjs +2 -2
  75. package/dist/astro/routes/api/auth/passkey/_id_.mjs +6 -6
  76. package/dist/astro/routes/api/auth/passkey/index.mjs +2 -2
  77. package/dist/astro/routes/api/auth/passkey/options.mjs +7 -7
  78. package/dist/astro/routes/api/auth/passkey/register/options.mjs +6 -6
  79. package/dist/astro/routes/api/auth/passkey/register/verify.mjs +6 -6
  80. package/dist/astro/routes/api/auth/passkey/verify.mjs +6 -6
  81. package/dist/astro/routes/api/auth/signup/complete.mjs +6 -6
  82. package/dist/astro/routes/api/auth/signup/request.mjs +7 -7
  83. package/dist/astro/routes/api/auth/signup/verify.mjs +2 -2
  84. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +10 -10
  85. package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +10 -10
  86. package/dist/astro/routes/api/content/_collection_/_id_/compare.mjs +3 -3
  87. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs +3 -3
  88. package/dist/astro/routes/api/content/_collection_/_id_/duplicate.mjs +3 -3
  89. package/dist/astro/routes/api/content/_collection_/_id_/permanent.mjs +3 -3
  90. package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs +9 -9
  91. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +7 -7
  92. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs +14 -14
  93. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs +14 -14
  94. package/dist/astro/routes/api/content/_collection_/_id_/restore.mjs +3 -3
  95. package/dist/astro/routes/api/content/_collection_/_id_/revisions.mjs +3 -3
  96. package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs +7 -7
  97. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +13 -13
  98. package/dist/astro/routes/api/content/_collection_/_id_/translations.mjs +3 -3
  99. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs +3 -3
  100. package/dist/astro/routes/api/content/_collection_/_id_.mjs +7 -7
  101. package/dist/astro/routes/api/content/_collection_/authors.mjs +3 -3
  102. package/dist/astro/routes/api/content/_collection_/index.mjs +7 -7
  103. package/dist/astro/routes/api/content/_collection_/trash.mjs +7 -7
  104. package/dist/astro/routes/api/dashboard.mjs +7 -7
  105. package/dist/astro/routes/api/dev/emails.mjs +2 -2
  106. package/dist/astro/routes/api/import/probe.mjs +12 -12
  107. package/dist/astro/routes/api/import/wordpress/analyze.mjs +3 -3
  108. package/dist/astro/routes/api/import/wordpress/execute.d.mts +2 -2
  109. package/dist/astro/routes/api/import/wordpress/execute.mjs +11 -11
  110. package/dist/astro/routes/api/import/wordpress/media.d.mts +2 -2
  111. package/dist/astro/routes/api/import/wordpress/media.mjs +7 -7
  112. package/dist/astro/routes/api/import/wordpress/prepare.mjs +9 -9
  113. package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts +2 -2
  114. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +9 -9
  115. package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +12 -12
  116. package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +2 -2
  117. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +19 -19
  118. package/dist/astro/routes/api/manifest.mjs +3 -3
  119. package/dist/astro/routes/api/mcp.mjs +39 -39
  120. package/dist/astro/routes/api/media/_id_/confirm.mjs +7 -7
  121. package/dist/astro/routes/api/media/_id_/usage.mjs +11 -11
  122. package/dist/astro/routes/api/media/_id_.mjs +10 -10
  123. package/dist/astro/routes/api/media/file/_...key_.mjs +2 -2
  124. package/dist/astro/routes/api/media/providers/_providerId_/_itemId_.mjs +3 -3
  125. package/dist/astro/routes/api/media/providers/_providerId_/index.mjs +3 -3
  126. package/dist/astro/routes/api/media/providers/index.mjs +3 -3
  127. package/dist/astro/routes/api/media/upload-url.mjs +7 -7
  128. package/dist/astro/routes/api/media.mjs +10 -10
  129. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +8 -8
  130. package/dist/astro/routes/api/menus/_name_/items.mjs +8 -8
  131. package/dist/astro/routes/api/menus/_name_/reorder.mjs +8 -8
  132. package/dist/astro/routes/api/menus/_name_/translations.mjs +8 -8
  133. package/dist/astro/routes/api/menus/_name_.mjs +8 -8
  134. package/dist/astro/routes/api/menus/index.mjs +8 -8
  135. package/dist/astro/routes/api/oauth/authorize.d.mts.map +1 -1
  136. package/dist/astro/routes/api/oauth/authorize.mjs +23 -9
  137. package/dist/astro/routes/api/oauth/authorize.mjs.map +1 -1
  138. package/dist/astro/routes/api/oauth/device/authorize.mjs +3 -3
  139. package/dist/astro/routes/api/oauth/device/code.mjs +4 -4
  140. package/dist/astro/routes/api/oauth/device/token.mjs +4 -4
  141. package/dist/astro/routes/api/oauth/register.mjs +2 -2
  142. package/dist/astro/routes/api/oauth/token/refresh.mjs +3 -3
  143. package/dist/astro/routes/api/oauth/token/revoke.mjs +3 -3
  144. package/dist/astro/routes/api/oauth/token.mjs +2 -2
  145. package/dist/astro/routes/api/openapi.json.mjs +4 -4
  146. package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +4 -4
  147. package/dist/astro/routes/api/redirects/404s/index.mjs +10 -10
  148. package/dist/astro/routes/api/redirects/404s/summary.mjs +10 -10
  149. package/dist/astro/routes/api/redirects/_id_.mjs +11 -11
  150. package/dist/astro/routes/api/redirects/index.mjs +11 -11
  151. package/dist/astro/routes/api/relations/_id_/index.mjs +14 -14
  152. package/dist/astro/routes/api/relations/_id_/translations.mjs +10 -10
  153. package/dist/astro/routes/api/relations/index.mjs +14 -14
  154. package/dist/astro/routes/api/revisions/_revisionId_/index.mjs +3 -3
  155. package/dist/astro/routes/api/revisions/_revisionId_/restore.mjs +3 -3
  156. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +34 -34
  157. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +34 -34
  158. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +34 -34
  159. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +34 -34
  160. package/dist/astro/routes/api/schema/collections/index.mjs +34 -34
  161. package/dist/astro/routes/api/schema/index.mjs +8 -8
  162. package/dist/astro/routes/api/schema/orphans/_slug_.mjs +34 -34
  163. package/dist/astro/routes/api/schema/orphans/index.mjs +34 -34
  164. package/dist/astro/routes/api/search/enable.mjs +11 -11
  165. package/dist/astro/routes/api/search/index.mjs +10 -10
  166. package/dist/astro/routes/api/search/rebuild.mjs +11 -11
  167. package/dist/astro/routes/api/search/stats.mjs +7 -7
  168. package/dist/astro/routes/api/search/suggest.mjs +10 -10
  169. package/dist/astro/routes/api/sections/_slug_.mjs +10 -10
  170. package/dist/astro/routes/api/sections/index.mjs +10 -10
  171. package/dist/astro/routes/api/settings/backups/archives/_name_.mjs +4 -4
  172. package/dist/astro/routes/api/settings/backups/archives/index.mjs +4 -4
  173. package/dist/astro/routes/api/settings/backups/export.mjs +4 -4
  174. package/dist/astro/routes/api/settings/backups/index.mjs +5 -5
  175. package/dist/astro/routes/api/settings/email.mjs +4 -4
  176. package/dist/astro/routes/api/settings.mjs +12 -12
  177. package/dist/astro/routes/api/setup/admin-verify.mjs +6 -6
  178. package/dist/astro/routes/api/setup/admin.mjs +6 -6
  179. package/dist/astro/routes/api/setup/dev-bypass.mjs +18 -18
  180. package/dist/astro/routes/api/setup/dev-reset.mjs +2 -2
  181. package/dist/astro/routes/api/setup/index.mjs +22 -22
  182. package/dist/astro/routes/api/setup/status.mjs +3 -3
  183. package/dist/astro/routes/api/snapshot.mjs +4 -4
  184. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +13 -13
  185. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +13 -13
  186. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +13 -13
  187. package/dist/astro/routes/api/taxonomies/index.mjs +13 -13
  188. package/dist/astro/routes/api/themes/preview.mjs +4 -4
  189. package/dist/astro/routes/api/typegen.mjs +5 -5
  190. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +7 -7
  191. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +10 -10
  192. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +10 -10
  193. package/dist/astro/routes/api/widget-areas/_name_.mjs +6 -6
  194. package/dist/astro/routes/api/widget-areas/index.mjs +10 -10
  195. package/dist/astro/routes/api/widget-components.mjs +2 -2
  196. package/dist/astro/routes/robots.txt.mjs +5 -5
  197. package/dist/astro/routes/sitemap-_collection_.xml.mjs +7 -7
  198. package/dist/astro/routes/sitemap.xml.mjs +5 -5
  199. package/dist/astro/types.d.mts +2 -2
  200. package/dist/{authorize-WxsiePzy.mjs → authorize-6WPZa1xZ.mjs} +2 -2
  201. package/dist/{authorize-WxsiePzy.mjs.map → authorize-6WPZa1xZ.mjs.map} +1 -1
  202. package/dist/{backup-S8kFWtwD.mjs → backup-Qr9PaGUo.mjs} +2 -2
  203. package/dist/{backup-S8kFWtwD.mjs.map → backup-Qr9PaGUo.mjs.map} +1 -1
  204. package/dist/{byline-XEjchwzZ.mjs → byline-BTOxUlFF.mjs} +6 -6
  205. package/dist/{byline-XEjchwzZ.mjs.map → byline-BTOxUlFF.mjs.map} +1 -1
  206. package/dist/{bylines-czseViYo.mjs → bylines-FyZu6TbJ.mjs} +6 -6
  207. package/dist/{bylines-czseViYo.mjs.map → bylines-FyZu6TbJ.mjs.map} +1 -1
  208. package/dist/{bylines-BJbT4gKS.mjs → bylines-oVN0iPwX.mjs} +12 -8
  209. package/dist/bylines-oVN0iPwX.mjs.map +1 -0
  210. package/dist/{cache-CGCd6AVM.mjs → cache-DDwy3JDW.mjs} +2 -2
  211. package/dist/{cache-CGCd6AVM.mjs.map → cache-DDwy3JDW.mjs.map} +1 -1
  212. package/dist/{chunks-BxXyunY-.mjs → chunks-Bq-5DPrD.mjs} +2 -2
  213. package/dist/{chunks-BxXyunY-.mjs.map → chunks-Bq-5DPrD.mjs.map} +1 -1
  214. package/dist/cli/index.mjs +18 -18
  215. package/dist/{comment-DPT0WKyd.mjs → comment-B9cUud8H.mjs} +2 -2
  216. package/dist/{comment-DPT0WKyd.mjs.map → comment-B9cUud8H.mjs.map} +1 -1
  217. package/dist/{comment-reaction-C65MldIB.mjs → comment-reaction-VUXO981F.mjs} +2 -2
  218. package/dist/{comment-reaction-C65MldIB.mjs.map → comment-reaction-VUXO981F.mjs.map} +1 -1
  219. package/dist/{comments-Bz6sCbgD.mjs → comments-PXj1E9Si.mjs} +3 -3
  220. package/dist/{comments-Bz6sCbgD.mjs.map → comments-PXj1E9Si.mjs.map} +1 -1
  221. package/dist/{config-CVssduLe.mjs → config-B6b_BobR.mjs} +6 -2
  222. package/dist/config-B6b_BobR.mjs.map +1 -0
  223. package/dist/{content-Ci04z2z-.mjs → content-BC43pICM.mjs} +4 -4
  224. package/dist/{content-Ci04z2z-.mjs.map → content-BC43pICM.mjs.map} +1 -1
  225. package/dist/{content-refresh-D4khvC0R.mjs → content-refresh-CPMSauD3.mjs} +4 -4
  226. package/dist/{content-refresh-D4khvC0R.mjs.map → content-refresh-CPMSauD3.mjs.map} +1 -1
  227. package/dist/{context-B6hc7zJL.mjs → context-DOurRIrb.mjs} +10 -10
  228. package/dist/{context-B6hc7zJL.mjs.map → context-DOurRIrb.mjs.map} +1 -1
  229. package/dist/{dashboard-C5NkXFbi.mjs → dashboard-CBm4zhc3.mjs} +4 -4
  230. package/dist/{dashboard-C5NkXFbi.mjs.map → dashboard-CBm4zhc3.mjs.map} +1 -1
  231. package/dist/database/pg-migration-lock.d.mts.map +1 -1
  232. package/dist/database/pg-migration-lock.mjs +1 -4
  233. package/dist/database/pg-migration-lock.mjs.map +1 -1
  234. package/dist/db/index.mjs +2 -2
  235. package/dist/{dialect-helpers-HxEQGl_1.mjs → dialect-helpers-BtOwo2us.mjs} +4 -4
  236. package/dist/dialect-helpers-BtOwo2us.mjs.map +1 -0
  237. package/dist/{error-CEGF6UZb.mjs → error-DJ98TRbQ.mjs} +2 -2
  238. package/dist/{error-CEGF6UZb.mjs.map → error-DJ98TRbQ.mjs.map} +1 -1
  239. package/dist/{field-defs-cache-DvmlgP-D.mjs → field-defs-cache-KfNJ_qLQ.mjs} +2 -2
  240. package/dist/{field-defs-cache-DvmlgP-D.mjs.map → field-defs-cache-KfNJ_qLQ.mjs.map} +1 -1
  241. package/dist/{fts-manager-DzqIBrrW.mjs → fts-manager-hyCU9OOp.mjs} +3 -3
  242. package/dist/{fts-manager-DzqIBrrW.mjs.map → fts-manager-hyCU9OOp.mjs.map} +1 -1
  243. package/dist/{hreflang-db2Tpb2o.mjs → hreflang-CbYeCzl9.mjs} +7 -7
  244. package/dist/{hreflang-db2Tpb2o.mjs.map → hreflang-CbYeCzl9.mjs.map} +1 -1
  245. package/dist/{import-Dmkm8S1W.mjs → import-oDYCgNYQ.mjs} +2 -2
  246. package/dist/{import-Dmkm8S1W.mjs.map → import-oDYCgNYQ.mjs.map} +1 -1
  247. package/dist/{index-wYnC6u4o.d.mts → index-BcEH_FfS.d.mts} +33 -2
  248. package/dist/index-BcEH_FfS.d.mts.map +1 -0
  249. package/dist/index.d.mts +2 -2
  250. package/dist/index.mjs +48 -48
  251. package/dist/{load-Cx27ki1l.mjs → load-Dg5gtWma.mjs} +2 -2
  252. package/dist/{load-Cx27ki1l.mjs.map → load-Dg5gtWma.mjs.map} +1 -1
  253. package/dist/{loader-Be3ouI5L.mjs → loader-D4rigvjR.mjs} +4 -4
  254. package/dist/{loader-Be3ouI5L.mjs.map → loader-D4rigvjR.mjs.map} +1 -1
  255. package/dist/media/local-runtime.d.mts +2 -2
  256. package/dist/media/local-runtime.mjs +5 -5
  257. package/dist/{media-kIV1IxFf.mjs → media-BJ6SRY3g.mjs} +8 -4
  258. package/dist/media-BJ6SRY3g.mjs.map +1 -0
  259. package/dist/{media-BjhhENaJ.mjs → media-its1WLYv.mjs} +2 -2
  260. package/dist/{media-BjhhENaJ.mjs.map → media-its1WLYv.mjs.map} +1 -1
  261. package/dist/{media-upload-D2wk3EIt.mjs → media-upload-DNu3QySc.mjs} +4 -4
  262. package/dist/{media-upload-D2wk3EIt.mjs.map → media-upload-DNu3QySc.mjs.map} +1 -1
  263. package/dist/{media-usage-CljdO1mc.mjs → media-usage-DPQ3K4xB.mjs} +6 -6
  264. package/dist/{media-usage-CljdO1mc.mjs.map → media-usage-DPQ3K4xB.mjs.map} +1 -1
  265. package/dist/{menus-CZyG6rvx.mjs → menus-BMGzWyWH.mjs} +15 -8
  266. package/dist/menus-BMGzWyWH.mjs.map +1 -0
  267. package/dist/{menus-BcyElFtI.mjs → menus-CPf_SW7u.mjs} +86 -8
  268. package/dist/menus-CPf_SW7u.mjs.map +1 -0
  269. package/dist/{parse-C_-6klII.mjs → parse-53zyxlpv.mjs} +2 -2
  270. package/dist/{parse-C_-6klII.mjs.map → parse-53zyxlpv.mjs.map} +1 -1
  271. package/dist/plugin-utils.d.mts +2 -2
  272. package/dist/plugins/adapt-sandbox-entry.d.mts +2 -2
  273. package/dist/{query-DR73ZNfm.mjs → query-BbJQ-dGg.mjs} +14 -14
  274. package/dist/{query-DR73ZNfm.mjs.map → query-BbJQ-dGg.mjs.map} +1 -1
  275. package/dist/{query-Di7DOmPV.mjs → query-DdFGHzQF.mjs} +3 -3
  276. package/dist/{query-Di7DOmPV.mjs.map → query-DdFGHzQF.mjs.map} +1 -1
  277. package/dist/{rate-limit-CMj83JNW.mjs → rate-limit-D3IEiUi2.mjs} +2 -2
  278. package/dist/{rate-limit-CMj83JNW.mjs.map → rate-limit-D3IEiUi2.mjs.map} +1 -1
  279. package/dist/{redirect-CgLPYflR.mjs → redirect-BoUac4NT.mjs} +3 -3
  280. package/dist/{redirect-CgLPYflR.mjs.map → redirect-BoUac4NT.mjs.map} +1 -1
  281. package/dist/{redirects-B7t9bKsL.mjs → redirects-ChbpqKiS.mjs} +3 -3
  282. package/dist/{redirects-B7t9bKsL.mjs.map → redirects-ChbpqKiS.mjs.map} +1 -1
  283. package/dist/{redirects-BBq3n2Rj.mjs → redirects-D457qwt0.mjs} +8 -8
  284. package/dist/redirects-D457qwt0.mjs.map +1 -0
  285. package/dist/{registry-FV15nLge.mjs → registry-y21kjhfG.mjs} +6 -6
  286. package/dist/{registry-FV15nLge.mjs.map → registry-y21kjhfG.mjs.map} +1 -1
  287. package/dist/{relation-9M9j_UWo.mjs → relation-Du0r04E0.mjs} +3 -3
  288. package/dist/{relation-9M9j_UWo.mjs.map → relation-Du0r04E0.mjs.map} +1 -1
  289. package/dist/{relations-Bh8jlFsU.d.mts → relations-BKybBoOX.d.mts} +12 -8
  290. package/dist/relations-BKybBoOX.d.mts.map +1 -0
  291. package/dist/{relations-5_avdrN_.mjs → relations-CZMpBqEd.mjs} +3 -3
  292. package/dist/{relations-5_avdrN_.mjs.map → relations-CZMpBqEd.mjs.map} +1 -1
  293. package/dist/{relations-BKvO39-9.mjs → relations-DtX1UMBH.mjs} +13 -7
  294. package/dist/relations-DtX1UMBH.mjs.map +1 -0
  295. package/dist/{resolve-Cd9dzclN.mjs → resolve-DFr4kq72.mjs} +2 -2
  296. package/dist/{resolve-Cd9dzclN.mjs.map → resolve-DFr4kq72.mjs.map} +1 -1
  297. package/dist/{runner-DfnZ5eUr.mjs → runner-BdeLEgad.mjs} +3 -3
  298. package/dist/{runner-DfnZ5eUr.mjs.map → runner-BdeLEgad.mjs.map} +1 -1
  299. package/dist/runtime.d.mts +2 -2
  300. package/dist/runtime.mjs +3 -3
  301. package/dist/{schema-BXxlHeAf.mjs → schema-BH8P8vaC.mjs} +3 -3
  302. package/dist/{schema-BXxlHeAf.mjs.map → schema-BH8P8vaC.mjs.map} +1 -1
  303. package/dist/{scopes-Bl4IwHA-.mjs → scopes-DTIkIaGA.mjs} +2 -2
  304. package/dist/{scopes-Bl4IwHA-.mjs.map → scopes-DTIkIaGA.mjs.map} +1 -1
  305. package/dist/{search-Bff-7jFt.mjs → search-D-Yhpmvs.mjs} +8 -7
  306. package/dist/search-D-Yhpmvs.mjs.map +1 -0
  307. package/dist/{secrets-CSwQIl4q.mjs → secrets-CQ-69kF9.mjs} +23 -17
  308. package/dist/secrets-CQ-69kF9.mjs.map +1 -0
  309. package/dist/{sections-CwW4s1al.mjs → sections-CzVBAKjw.mjs} +3 -3
  310. package/dist/{sections-CwW4s1al.mjs.map → sections-CzVBAKjw.mjs.map} +1 -1
  311. package/dist/seed/index.mjs +16 -16
  312. package/dist/seo/index.mjs +12 -12
  313. package/dist/{seo-2cmFHZns.mjs → seo-kJzVAmmu.mjs} +2 -2
  314. package/dist/{seo-2cmFHZns.mjs.map → seo-kJzVAmmu.mjs.map} +1 -1
  315. package/dist/{service-DkGTWGIi.mjs → service-CQnc276a.mjs} +2 -2
  316. package/dist/{service-DkGTWGIi.mjs.map → service-CQnc276a.mjs.map} +1 -1
  317. package/dist/{settings-CpA4lQFt.mjs → settings-C2PaBS49.mjs} +3 -3
  318. package/dist/{settings-CpA4lQFt.mjs.map → settings-C2PaBS49.mjs.map} +1 -1
  319. package/dist/{settings-C4s8hFQm.mjs → settings-Dtc0DU31.mjs} +3 -3
  320. package/dist/{settings-C4s8hFQm.mjs.map → settings-Dtc0DU31.mjs.map} +1 -1
  321. package/dist/{taxonomies-DjSKBZpq.mjs → taxonomies-HI9fnTdp.mjs} +7 -7
  322. package/dist/{taxonomies-DjSKBZpq.mjs.map → taxonomies-HI9fnTdp.mjs.map} +1 -1
  323. package/dist/{taxonomies-Ce49uIzY.mjs → taxonomies-rMeBzOjX.mjs} +26 -17
  324. package/dist/taxonomies-rMeBzOjX.mjs.map +1 -0
  325. package/dist/{taxonomy-DfVooU4W.mjs → taxonomy-0mCI25HN.mjs} +3 -3
  326. package/dist/{taxonomy-DfVooU4W.mjs.map → taxonomy-0mCI25HN.mjs.map} +1 -1
  327. package/dist/{types-D1iJ3DpO.mjs → types-CrRUFdej.mjs} +2 -2
  328. package/dist/{types-D1iJ3DpO.mjs.map → types-CrRUFdej.mjs.map} +1 -1
  329. package/dist/{user-Bh-L1qo6.mjs → user-aTXqmXBz.mjs} +3 -3
  330. package/dist/{user-Bh-L1qo6.mjs.map → user-aTXqmXBz.mjs.map} +1 -1
  331. package/dist/{validate-V9nCwq_-.mjs → validate-CDT1jl6_.mjs} +11 -6
  332. package/dist/validate-CDT1jl6_.mjs.map +1 -0
  333. package/dist/validate-DULfgpJP.d.mts.map +1 -1
  334. package/dist/{validation-BsVUJfsP.mjs → validation-DlD0E35W.mjs} +8 -8
  335. package/dist/{validation-BsVUJfsP.mjs.map → validation-DlD0E35W.mjs.map} +1 -1
  336. package/dist/version-Ci6bw6YK.mjs +7 -0
  337. package/dist/{version-907opKac.mjs.map → version-Ci6bw6YK.mjs.map} +1 -1
  338. package/dist/{widgets-DGv1Z04V.mjs → widgets-5fipNkMT.mjs} +2 -2
  339. package/dist/{widgets-DGv1Z04V.mjs.map → widgets-5fipNkMT.mjs.map} +1 -1
  340. package/dist/{wxr-taxonomies-Cs1N6O8z.mjs → wxr-taxonomies-BmUnBNgz.mjs} +4 -4
  341. package/dist/{wxr-taxonomies-Cs1N6O8z.mjs.map → wxr-taxonomies-BmUnBNgz.mjs.map} +1 -1
  342. package/dist/{zod-generator-B5prQ5M4.mjs → zod-generator-CwkHWz4f.mjs} +2 -2
  343. package/dist/{zod-generator-B5prQ5M4.mjs.map → zod-generator-CwkHWz4f.mjs.map} +1 -1
  344. package/package.json +5 -5
  345. package/src/api/handlers/bylines.ts +5 -4
  346. package/src/api/handlers/content.ts +25 -7
  347. package/src/api/handlers/menus.ts +11 -6
  348. package/src/api/handlers/relations.ts +7 -2
  349. package/src/api/handlers/taxonomies.ts +22 -14
  350. package/src/api/schemas/bylines.ts +4 -4
  351. package/src/api/schemas/common.ts +7 -6
  352. package/src/api/schemas/menus.ts +2 -1
  353. package/src/api/schemas/relations.ts +3 -1
  354. package/src/api/schemas/taxonomies.ts +4 -2
  355. package/src/astro/routes/api/admin/bylines/index.ts +5 -8
  356. package/src/astro/routes/api/oauth/authorize.ts +42 -10
  357. package/src/components/Gallery.astro +141 -26
  358. package/src/config/secrets.ts +25 -19
  359. package/src/content/converters/gallery.ts +61 -0
  360. package/src/content/converters/portable-text-to-prosemirror.ts +19 -0
  361. package/src/content/converters/prosemirror-to-portable-text.ts +18 -0
  362. package/src/content/converters/types.ts +36 -0
  363. package/src/database/dialect-helpers.ts +3 -4
  364. package/src/database/pg-migration-lock.ts +1 -4
  365. package/src/emdash-runtime.ts +55 -17
  366. package/src/i18n/config.ts +8 -0
  367. package/src/i18n/repair-locale-casing.ts +51 -0
  368. package/src/search/query.ts +3 -2
  369. package/src/seed/apply.ts +9 -7
  370. package/src/seed/validate.ts +15 -4
  371. package/dist/api-b8WIiGU4.mjs.map +0 -1
  372. package/dist/apply-CmIJK9j8.mjs.map +0 -1
  373. package/dist/bylines-BJbT4gKS.mjs.map +0 -1
  374. package/dist/config-CVssduLe.mjs.map +0 -1
  375. package/dist/dialect-helpers-HxEQGl_1.mjs.map +0 -1
  376. package/dist/index-wYnC6u4o.d.mts.map +0 -1
  377. package/dist/media-kIV1IxFf.mjs.map +0 -1
  378. package/dist/menus-BcyElFtI.mjs.map +0 -1
  379. package/dist/menus-CZyG6rvx.mjs.map +0 -1
  380. package/dist/redirects-BBq3n2Rj.mjs.map +0 -1
  381. package/dist/relations-BKvO39-9.mjs.map +0 -1
  382. package/dist/relations-Bh8jlFsU.d.mts.map +0 -1
  383. package/dist/search-Bff-7jFt.mjs.map +0 -1
  384. package/dist/secrets-CSwQIl4q.mjs.map +0 -1
  385. package/dist/taxonomies-Ce49uIzY.mjs.map +0 -1
  386. package/dist/validate-V9nCwq_-.mjs.map +0 -1
  387. package/dist/version-907opKac.mjs +0 -7
@@ -1 +1 @@
1
- {"version":3,"file":"service-DkGTWGIi.mjs","names":[],"sources":["../src/comments/notifications.ts","../src/comments/service.ts"],"sourcesContent":["/**\n * Comment Notification Emails\n *\n * Sends email notifications to content authors when comments are\n * approved on their content. Used by:\n * - Public comment POST route (comment:afterCreate, if auto-approved)\n * - Admin moderation route (comment:afterModerate, when approving)\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { escapeHtml } from \"../api/escape.js\";\nimport type { Database } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport type { EmailPipeline } from \"../plugins/email.js\";\nimport type { EmailMessage } from \"../plugins/types.js\";\n\nconst NOTIFICATION_SOURCE = \"emdash-comments\";\nconst MAX_EXCERPT_LENGTH = 500;\nconst CRLF_RE = /[\\r\\n]/g;\n\nexport interface CommentNotificationData {\n\tcommentAuthorName: string;\n\tcommentBody: string;\n\tcontentTitle: string;\n\tcollection: string;\n\tadminBaseUrl: string;\n}\n\n/**\n * Build an email notification for a new comment.\n */\nexport function buildCommentNotificationEmail(\n\tto: string,\n\tdata: CommentNotificationData,\n): EmailMessage {\n\tconst title = data.contentTitle || `${data.collection} item`;\n\tconst subject = `New comment on \"${title}\"`.replace(CRLF_RE, \" \");\n\n\tconst excerpt =\n\t\tdata.commentBody.length > MAX_EXCERPT_LENGTH\n\t\t\t? data.commentBody.slice(0, MAX_EXCERPT_LENGTH) + \"...\"\n\t\t\t: data.commentBody;\n\n\tconst adminUrl = `${data.adminBaseUrl}/admin/comments`;\n\n\tconst text = [\n\t\t`${data.commentAuthorName} commented on \"${title}\":`,\n\t\t\"\",\n\t\texcerpt,\n\t\t\"\",\n\t\t`View in admin: ${adminUrl}`,\n\t].join(\"\\n\");\n\n\tconst html = [\n\t\t`<p><strong>${escapeHtml(data.commentAuthorName)}</strong> commented on &ldquo;${escapeHtml(title)}&rdquo;:</p>`,\n\t\t`<blockquote style=\"border-left:3px solid #ccc;padding-left:12px;margin:12px 0;color:#555\">${escapeHtml(excerpt)}</blockquote>`,\n\t\t`<p><a href=\"${escapeHtml(adminUrl)}\">View in admin</a></p>`,\n\t].join(\"\\n\");\n\n\treturn { to, subject, text, html };\n}\n\n/**\n * Send a comment notification to the content author if all conditions are met:\n * 1. Comment status is \"approved\"\n * 2. Content author exists and has an email\n * 3. Email provider is configured\n * 4. Commenter is not the content author (no self-notifications)\n *\n * Returns true if the email was sent, false if skipped.\n */\nexport async function sendCommentNotification(params: {\n\temail: EmailPipeline;\n\tcomment: {\n\t\tauthorName: string;\n\t\tauthorEmail: string;\n\t\tbody: string;\n\t\tstatus: string;\n\t\tcollection: string;\n\t};\n\tcontentTitle?: string;\n\tcontentAuthor?: { email: string; name: string | null };\n\tadminBaseUrl: string;\n}): Promise<boolean> {\n\tconst { email, comment, contentAuthor, adminBaseUrl } = params;\n\n\tif (comment.status !== \"approved\") return false;\n\tif (!contentAuthor?.email) return false;\n\tif (!email.isAvailable()) return false;\n\tif (comment.authorEmail.toLowerCase() === contentAuthor.email.toLowerCase()) return false;\n\n\tconst message = buildCommentNotificationEmail(contentAuthor.email, {\n\t\tcommentAuthorName: comment.authorName,\n\t\tcommentBody: comment.body,\n\t\tcontentTitle: params.contentTitle || \"\",\n\t\tcollection: comment.collection,\n\t\tadminBaseUrl,\n\t});\n\n\tawait email.send(message, NOTIFICATION_SOURCE);\n\treturn true;\n}\n\n/**\n * Look up a content item's author from the database.\n *\n * Used by the admin moderation route where content info isn't\n * readily available (only the comment record is at hand).\n */\nexport async function lookupContentAuthor(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tcontentId: string,\n): Promise<{\n\tslug: string;\n\tauthor?: { id: string; email: string; name: string | null };\n} | null> {\n\tvalidateIdentifier(collection, \"collection\");\n\n\tconst contentRow = await db\n\t\t.selectFrom(`ec_${collection}` as never)\n\t\t.select([\"slug\" as never, \"author_id\" as never])\n\t\t.where(\"id\" as never, \"=\", contentId as never)\n\t\t.executeTakeFirst();\n\n\tif (!contentRow) return null;\n\n\tconst typed = contentRow as { slug: string; author_id: string | null };\n\n\tlet author: { id: string; email: string; name: string | null } | undefined;\n\tif (typed.author_id) {\n\t\tconst userRow = await db\n\t\t\t.selectFrom(\"users\")\n\t\t\t.select([\"id\", \"name\", \"email\", \"email_verified\"])\n\t\t\t.where(\"id\", \"=\", typed.author_id)\n\t\t\t.executeTakeFirst();\n\t\tif (userRow && userRow.email_verified) {\n\t\t\tauthor = { id: userRow.id, email: userRow.email, name: userRow.name };\n\t\t}\n\t}\n\n\treturn { slug: typed.slug, author };\n}\n","/**\n * Comment Service\n *\n * Orchestrates comment creation through the hook pipeline:\n * 1. Run comment:beforeCreate pipeline (transform/reject)\n * 2. Query priorApprovedCount for first-time moderation\n * 3. Invoke comment:moderate exclusive hook (or built-in fallback)\n * 4. Save comment with determined status\n * 5. Fire comment:afterCreate (fire-and-forget)\n *\n * Also handles admin moderation (status changes) with afterModerate hooks.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { CommentRepository } from \"../database/repositories/comment.js\";\nimport type { Comment, CommentStatus } from \"../database/repositories/comment.js\";\nimport type { Database } from \"../database/types.js\";\nimport type {\n\tCollectionCommentSettings,\n\tCommentAfterCreateEvent,\n\tCommentAfterModerateEvent,\n\tCommentBeforeCreateEvent,\n\tCommentModerateEvent,\n\tModerationDecision,\n\tStoredComment,\n} from \"../plugins/types.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CommentCreateInput {\n\tcollection: string;\n\tcontentId: string;\n\tparentId?: string | null;\n\tauthorName: string;\n\tauthorEmail: string;\n\tauthorUserId?: string | null;\n\tbody: string;\n\tipHash?: string | null;\n\tuserAgent?: string | null;\n}\n\nexport interface CommentCreateResult {\n\tcomment: Comment;\n\tdecision: ModerationDecision;\n}\n\n/**\n * Hook runner interface — injected from the runtime so the service\n * doesn't need to know about the hook pipeline internals.\n */\nexport interface CommentHookRunner {\n\t/** Run comment:beforeCreate pipeline. Returns modified event or false. */\n\trunBeforeCreate(event: CommentBeforeCreateEvent): Promise<CommentBeforeCreateEvent | false>;\n\n\t/** Run comment:moderate exclusive hook. Returns moderation decision. */\n\trunModerate(event: CommentModerateEvent): Promise<ModerationDecision>;\n\n\t/** Fire comment:afterCreate (fire-and-forget). */\n\tfireAfterCreate(event: CommentAfterCreateEvent): void;\n\n\t/** Fire comment:afterModerate (fire-and-forget). */\n\tfireAfterModerate(event: CommentAfterModerateEvent): void;\n}\n\n// ---------------------------------------------------------------------------\n// Service\n// ---------------------------------------------------------------------------\n\n/**\n * Create a comment through the full hook pipeline.\n *\n * Returns null if the comment was rejected by a beforeCreate handler.\n */\nexport async function createComment(\n\tdb: Kysely<Database>,\n\tinput: CommentCreateInput,\n\tcollectionSettings: CollectionCommentSettings,\n\thooks: CommentHookRunner,\n\tcontentInfo?: {\n\t\tid: string;\n\t\tcollection: string;\n\t\tslug: string;\n\t\ttitle?: string;\n\t\tauthor?: { id: string; name: string | null; email: string };\n\t},\n): Promise<CommentCreateResult | null> {\n\tconst repo = new CommentRepository(db);\n\n\t// 1. Build the beforeCreate event\n\tconst beforeCreateEvent: CommentBeforeCreateEvent = {\n\t\tcomment: {\n\t\t\tcollection: input.collection,\n\t\t\tcontentId: input.contentId,\n\t\t\tparentId: input.parentId ?? null,\n\t\t\tauthorName: input.authorName,\n\t\t\tauthorEmail: input.authorEmail,\n\t\t\tauthorUserId: input.authorUserId ?? null,\n\t\t\tbody: input.body,\n\t\t\tipHash: input.ipHash ?? null,\n\t\t\tuserAgent: input.userAgent ?? null,\n\t\t},\n\t\tmetadata: {},\n\t};\n\n\t// 2. Run comment:beforeCreate pipeline\n\tconst result = await hooks.runBeforeCreate(beforeCreateEvent);\n\tif (result === false) {\n\t\treturn null; // Rejected\n\t}\n\n\tconst event = result;\n\n\t// 3. Query prior approved count for first-time moderation\n\tconst priorApprovedCount = await repo.countApprovedByEmail(event.comment.authorEmail);\n\n\t// 4. Run comment:moderate exclusive hook\n\tconst moderateEvent: CommentModerateEvent = {\n\t\tcomment: event.comment,\n\t\tmetadata: event.metadata,\n\t\tcollectionSettings,\n\t\tpriorApprovedCount,\n\t};\n\n\tconst decision = await hooks.runModerate(moderateEvent);\n\n\t// 5. Save comment with determined status\n\tconst comment = await repo.create({\n\t\tcollection: event.comment.collection,\n\t\tcontentId: event.comment.contentId,\n\t\tparentId: event.comment.parentId,\n\t\tauthorName: event.comment.authorName,\n\t\tauthorEmail: event.comment.authorEmail,\n\t\tauthorUserId: event.comment.authorUserId,\n\t\tbody: event.comment.body,\n\t\tstatus: decision.status,\n\t\tipHash: event.comment.ipHash,\n\t\tuserAgent: event.comment.userAgent,\n\t\tmoderationMetadata: Object.keys(event.metadata).length > 0 ? event.metadata : null,\n\t});\n\n\t// 6. Fire comment:afterCreate (fire-and-forget)\n\tif (contentInfo) {\n\t\tconst afterEvent: CommentAfterCreateEvent = {\n\t\t\tcomment: commentToStored(comment),\n\t\t\tmetadata: event.metadata,\n\t\t\tcontent: {\n\t\t\t\tid: contentInfo.id,\n\t\t\t\tcollection: contentInfo.collection,\n\t\t\t\tslug: contentInfo.slug,\n\t\t\t\ttitle: contentInfo.title,\n\t\t\t},\n\t\t\tcontentAuthor: contentInfo.author,\n\t\t};\n\t\thooks.fireAfterCreate(afterEvent);\n\t}\n\n\treturn { comment, decision };\n}\n\n/**\n * Admin moderation — change a comment's status.\n * Fires comment:afterModerate hook.\n */\nexport async function moderateComment(\n\tdb: Kysely<Database>,\n\tid: string,\n\tnewStatus: CommentStatus,\n\tmoderator: { id: string; name: string | null },\n\thooks: CommentHookRunner,\n): Promise<Comment | null> {\n\tconst repo = new CommentRepository(db);\n\tconst existing = await repo.findById(id);\n\tif (!existing) return null;\n\n\tconst previousStatus = existing.status;\n\tconst updated = await repo.updateStatus(id, newStatus);\n\tif (!updated) return null;\n\n\t// Fire comment:afterModerate (fire-and-forget)\n\tconst afterEvent: CommentAfterModerateEvent = {\n\t\tcomment: commentToStored(updated),\n\t\tpreviousStatus,\n\t\tnewStatus,\n\t\tmoderator,\n\t};\n\thooks.fireAfterModerate(afterEvent);\n\n\treturn updated;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction commentToStored(comment: Comment): StoredComment {\n\treturn {\n\t\tid: comment.id,\n\t\tcollection: comment.collection,\n\t\tcontentId: comment.contentId,\n\t\tparentId: comment.parentId,\n\t\tauthorName: comment.authorName,\n\t\tauthorEmail: comment.authorEmail,\n\t\tauthorUserId: comment.authorUserId,\n\t\tbody: comment.body,\n\t\tstatus: comment.status,\n\t\tmoderationMetadata: comment.moderationMetadata,\n\t\tcreatedAt: comment.createdAt,\n\t\tupdatedAt: comment.updatedAt,\n\t};\n}\n"],"mappings":";;;;;AAiBA,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAC3B,MAAM,UAAU;;;;AAahB,SAAgB,8BACf,IACA,MACe;CACf,MAAM,QAAQ,KAAK,gBAAgB,GAAG,KAAK,WAAW;CACtD,MAAM,UAAU,mBAAmB,MAAM,GAAG,QAAQ,SAAS,IAAI;CAEjE,MAAM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;AAGF,KAAI,aAAa;EAChB,MAAM,aAAsC;GAC3C,SAAS,gBAAgB,QAAQ;GACjC,UAAU,MAAM;GAChB,SAAS;IACR,IAAI,YAAY;IAChB,YAAY,YAAY;IACxB,MAAM,YAAY;IAClB,OAAO,YAAY;IACnB;GACD,eAAe,YAAY;GAC3B;AACD,QAAM,gBAAgB,WAAW;;AAGlC,QAAO;EAAE;EAAS;EAAU;;;;;;AAO7B,eAAsB,gBACrB,IACA,IACA,WACA,WACA,OAC0B;CAC1B,MAAM,OAAO,IAAI,kBAAkB,GAAG;CACtC,MAAM,WAAW,MAAM,KAAK,SAAS,GAAG;AACxC,KAAI,CAAC,SAAU,QAAO;CAEtB,MAAM,iBAAiB,SAAS;CAChC,MAAM,UAAU,MAAM,KAAK,aAAa,IAAI,UAAU;AACtD,KAAI,CAAC,QAAS,QAAO;CAGrB,MAAM,aAAwC;EAC7C,SAAS,gBAAgB,QAAQ;EACjC;EACA;EACA;EACA;AACD,OAAM,kBAAkB,WAAW;AAEnC,QAAO;;AAOR,SAAS,gBAAgB,SAAiC;AACzD,QAAO;EACN,IAAI,QAAQ;EACZ,YAAY,QAAQ;EACpB,WAAW,QAAQ;EACnB,UAAU,QAAQ;EAClB,YAAY,QAAQ;EACpB,aAAa,QAAQ;EACrB,cAAc,QAAQ;EACtB,MAAM,QAAQ;EACd,QAAQ,QAAQ;EAChB,oBAAoB,QAAQ;EAC5B,WAAW,QAAQ;EACnB,WAAW,QAAQ;EACnB"}
1
+ {"version":3,"file":"service-CQnc276a.mjs","names":[],"sources":["../src/comments/notifications.ts","../src/comments/service.ts"],"sourcesContent":["/**\n * Comment Notification Emails\n *\n * Sends email notifications to content authors when comments are\n * approved on their content. Used by:\n * - Public comment POST route (comment:afterCreate, if auto-approved)\n * - Admin moderation route (comment:afterModerate, when approving)\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { escapeHtml } from \"../api/escape.js\";\nimport type { Database } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport type { EmailPipeline } from \"../plugins/email.js\";\nimport type { EmailMessage } from \"../plugins/types.js\";\n\nconst NOTIFICATION_SOURCE = \"emdash-comments\";\nconst MAX_EXCERPT_LENGTH = 500;\nconst CRLF_RE = /[\\r\\n]/g;\n\nexport interface CommentNotificationData {\n\tcommentAuthorName: string;\n\tcommentBody: string;\n\tcontentTitle: string;\n\tcollection: string;\n\tadminBaseUrl: string;\n}\n\n/**\n * Build an email notification for a new comment.\n */\nexport function buildCommentNotificationEmail(\n\tto: string,\n\tdata: CommentNotificationData,\n): EmailMessage {\n\tconst title = data.contentTitle || `${data.collection} item`;\n\tconst subject = `New comment on \"${title}\"`.replace(CRLF_RE, \" \");\n\n\tconst excerpt =\n\t\tdata.commentBody.length > MAX_EXCERPT_LENGTH\n\t\t\t? data.commentBody.slice(0, MAX_EXCERPT_LENGTH) + \"...\"\n\t\t\t: data.commentBody;\n\n\tconst adminUrl = `${data.adminBaseUrl}/admin/comments`;\n\n\tconst text = [\n\t\t`${data.commentAuthorName} commented on \"${title}\":`,\n\t\t\"\",\n\t\texcerpt,\n\t\t\"\",\n\t\t`View in admin: ${adminUrl}`,\n\t].join(\"\\n\");\n\n\tconst html = [\n\t\t`<p><strong>${escapeHtml(data.commentAuthorName)}</strong> commented on &ldquo;${escapeHtml(title)}&rdquo;:</p>`,\n\t\t`<blockquote style=\"border-left:3px solid #ccc;padding-left:12px;margin:12px 0;color:#555\">${escapeHtml(excerpt)}</blockquote>`,\n\t\t`<p><a href=\"${escapeHtml(adminUrl)}\">View in admin</a></p>`,\n\t].join(\"\\n\");\n\n\treturn { to, subject, text, html };\n}\n\n/**\n * Send a comment notification to the content author if all conditions are met:\n * 1. Comment status is \"approved\"\n * 2. Content author exists and has an email\n * 3. Email provider is configured\n * 4. Commenter is not the content author (no self-notifications)\n *\n * Returns true if the email was sent, false if skipped.\n */\nexport async function sendCommentNotification(params: {\n\temail: EmailPipeline;\n\tcomment: {\n\t\tauthorName: string;\n\t\tauthorEmail: string;\n\t\tbody: string;\n\t\tstatus: string;\n\t\tcollection: string;\n\t};\n\tcontentTitle?: string;\n\tcontentAuthor?: { email: string; name: string | null };\n\tadminBaseUrl: string;\n}): Promise<boolean> {\n\tconst { email, comment, contentAuthor, adminBaseUrl } = params;\n\n\tif (comment.status !== \"approved\") return false;\n\tif (!contentAuthor?.email) return false;\n\tif (!email.isAvailable()) return false;\n\tif (comment.authorEmail.toLowerCase() === contentAuthor.email.toLowerCase()) return false;\n\n\tconst message = buildCommentNotificationEmail(contentAuthor.email, {\n\t\tcommentAuthorName: comment.authorName,\n\t\tcommentBody: comment.body,\n\t\tcontentTitle: params.contentTitle || \"\",\n\t\tcollection: comment.collection,\n\t\tadminBaseUrl,\n\t});\n\n\tawait email.send(message, NOTIFICATION_SOURCE);\n\treturn true;\n}\n\n/**\n * Look up a content item's author from the database.\n *\n * Used by the admin moderation route where content info isn't\n * readily available (only the comment record is at hand).\n */\nexport async function lookupContentAuthor(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tcontentId: string,\n): Promise<{\n\tslug: string;\n\tauthor?: { id: string; email: string; name: string | null };\n} | null> {\n\tvalidateIdentifier(collection, \"collection\");\n\n\tconst contentRow = await db\n\t\t.selectFrom(`ec_${collection}` as never)\n\t\t.select([\"slug\" as never, \"author_id\" as never])\n\t\t.where(\"id\" as never, \"=\", contentId as never)\n\t\t.executeTakeFirst();\n\n\tif (!contentRow) return null;\n\n\tconst typed = contentRow as { slug: string; author_id: string | null };\n\n\tlet author: { id: string; email: string; name: string | null } | undefined;\n\tif (typed.author_id) {\n\t\tconst userRow = await db\n\t\t\t.selectFrom(\"users\")\n\t\t\t.select([\"id\", \"name\", \"email\", \"email_verified\"])\n\t\t\t.where(\"id\", \"=\", typed.author_id)\n\t\t\t.executeTakeFirst();\n\t\tif (userRow && userRow.email_verified) {\n\t\t\tauthor = { id: userRow.id, email: userRow.email, name: userRow.name };\n\t\t}\n\t}\n\n\treturn { slug: typed.slug, author };\n}\n","/**\n * Comment Service\n *\n * Orchestrates comment creation through the hook pipeline:\n * 1. Run comment:beforeCreate pipeline (transform/reject)\n * 2. Query priorApprovedCount for first-time moderation\n * 3. Invoke comment:moderate exclusive hook (or built-in fallback)\n * 4. Save comment with determined status\n * 5. Fire comment:afterCreate (fire-and-forget)\n *\n * Also handles admin moderation (status changes) with afterModerate hooks.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { CommentRepository } from \"../database/repositories/comment.js\";\nimport type { Comment, CommentStatus } from \"../database/repositories/comment.js\";\nimport type { Database } from \"../database/types.js\";\nimport type {\n\tCollectionCommentSettings,\n\tCommentAfterCreateEvent,\n\tCommentAfterModerateEvent,\n\tCommentBeforeCreateEvent,\n\tCommentModerateEvent,\n\tModerationDecision,\n\tStoredComment,\n} from \"../plugins/types.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CommentCreateInput {\n\tcollection: string;\n\tcontentId: string;\n\tparentId?: string | null;\n\tauthorName: string;\n\tauthorEmail: string;\n\tauthorUserId?: string | null;\n\tbody: string;\n\tipHash?: string | null;\n\tuserAgent?: string | null;\n}\n\nexport interface CommentCreateResult {\n\tcomment: Comment;\n\tdecision: ModerationDecision;\n}\n\n/**\n * Hook runner interface — injected from the runtime so the service\n * doesn't need to know about the hook pipeline internals.\n */\nexport interface CommentHookRunner {\n\t/** Run comment:beforeCreate pipeline. Returns modified event or false. */\n\trunBeforeCreate(event: CommentBeforeCreateEvent): Promise<CommentBeforeCreateEvent | false>;\n\n\t/** Run comment:moderate exclusive hook. Returns moderation decision. */\n\trunModerate(event: CommentModerateEvent): Promise<ModerationDecision>;\n\n\t/** Fire comment:afterCreate (fire-and-forget). */\n\tfireAfterCreate(event: CommentAfterCreateEvent): void;\n\n\t/** Fire comment:afterModerate (fire-and-forget). */\n\tfireAfterModerate(event: CommentAfterModerateEvent): void;\n}\n\n// ---------------------------------------------------------------------------\n// Service\n// ---------------------------------------------------------------------------\n\n/**\n * Create a comment through the full hook pipeline.\n *\n * Returns null if the comment was rejected by a beforeCreate handler.\n */\nexport async function createComment(\n\tdb: Kysely<Database>,\n\tinput: CommentCreateInput,\n\tcollectionSettings: CollectionCommentSettings,\n\thooks: CommentHookRunner,\n\tcontentInfo?: {\n\t\tid: string;\n\t\tcollection: string;\n\t\tslug: string;\n\t\ttitle?: string;\n\t\tauthor?: { id: string; name: string | null; email: string };\n\t},\n): Promise<CommentCreateResult | null> {\n\tconst repo = new CommentRepository(db);\n\n\t// 1. Build the beforeCreate event\n\tconst beforeCreateEvent: CommentBeforeCreateEvent = {\n\t\tcomment: {\n\t\t\tcollection: input.collection,\n\t\t\tcontentId: input.contentId,\n\t\t\tparentId: input.parentId ?? null,\n\t\t\tauthorName: input.authorName,\n\t\t\tauthorEmail: input.authorEmail,\n\t\t\tauthorUserId: input.authorUserId ?? null,\n\t\t\tbody: input.body,\n\t\t\tipHash: input.ipHash ?? null,\n\t\t\tuserAgent: input.userAgent ?? null,\n\t\t},\n\t\tmetadata: {},\n\t};\n\n\t// 2. Run comment:beforeCreate pipeline\n\tconst result = await hooks.runBeforeCreate(beforeCreateEvent);\n\tif (result === false) {\n\t\treturn null; // Rejected\n\t}\n\n\tconst event = result;\n\n\t// 3. Query prior approved count for first-time moderation\n\tconst priorApprovedCount = await repo.countApprovedByEmail(event.comment.authorEmail);\n\n\t// 4. Run comment:moderate exclusive hook\n\tconst moderateEvent: CommentModerateEvent = {\n\t\tcomment: event.comment,\n\t\tmetadata: event.metadata,\n\t\tcollectionSettings,\n\t\tpriorApprovedCount,\n\t};\n\n\tconst decision = await hooks.runModerate(moderateEvent);\n\n\t// 5. Save comment with determined status\n\tconst comment = await repo.create({\n\t\tcollection: event.comment.collection,\n\t\tcontentId: event.comment.contentId,\n\t\tparentId: event.comment.parentId,\n\t\tauthorName: event.comment.authorName,\n\t\tauthorEmail: event.comment.authorEmail,\n\t\tauthorUserId: event.comment.authorUserId,\n\t\tbody: event.comment.body,\n\t\tstatus: decision.status,\n\t\tipHash: event.comment.ipHash,\n\t\tuserAgent: event.comment.userAgent,\n\t\tmoderationMetadata: Object.keys(event.metadata).length > 0 ? event.metadata : null,\n\t});\n\n\t// 6. Fire comment:afterCreate (fire-and-forget)\n\tif (contentInfo) {\n\t\tconst afterEvent: CommentAfterCreateEvent = {\n\t\t\tcomment: commentToStored(comment),\n\t\t\tmetadata: event.metadata,\n\t\t\tcontent: {\n\t\t\t\tid: contentInfo.id,\n\t\t\t\tcollection: contentInfo.collection,\n\t\t\t\tslug: contentInfo.slug,\n\t\t\t\ttitle: contentInfo.title,\n\t\t\t},\n\t\t\tcontentAuthor: contentInfo.author,\n\t\t};\n\t\thooks.fireAfterCreate(afterEvent);\n\t}\n\n\treturn { comment, decision };\n}\n\n/**\n * Admin moderation — change a comment's status.\n * Fires comment:afterModerate hook.\n */\nexport async function moderateComment(\n\tdb: Kysely<Database>,\n\tid: string,\n\tnewStatus: CommentStatus,\n\tmoderator: { id: string; name: string | null },\n\thooks: CommentHookRunner,\n): Promise<Comment | null> {\n\tconst repo = new CommentRepository(db);\n\tconst existing = await repo.findById(id);\n\tif (!existing) return null;\n\n\tconst previousStatus = existing.status;\n\tconst updated = await repo.updateStatus(id, newStatus);\n\tif (!updated) return null;\n\n\t// Fire comment:afterModerate (fire-and-forget)\n\tconst afterEvent: CommentAfterModerateEvent = {\n\t\tcomment: commentToStored(updated),\n\t\tpreviousStatus,\n\t\tnewStatus,\n\t\tmoderator,\n\t};\n\thooks.fireAfterModerate(afterEvent);\n\n\treturn updated;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction commentToStored(comment: Comment): StoredComment {\n\treturn {\n\t\tid: comment.id,\n\t\tcollection: comment.collection,\n\t\tcontentId: comment.contentId,\n\t\tparentId: comment.parentId,\n\t\tauthorName: comment.authorName,\n\t\tauthorEmail: comment.authorEmail,\n\t\tauthorUserId: comment.authorUserId,\n\t\tbody: comment.body,\n\t\tstatus: com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,QAAQ;EACnB"}
@@ -1,9 +1,9 @@
1
1
  import { t as after } from "./after-B1IIdH3Y.mjs";
2
2
  import { l as invalidateObjectCache, n as cachedQuery } from "./object-cache-Bok5j2ae.mjs";
3
- import { t as MediaRepository } from "./media-BjhhENaJ.mjs";
3
+ import { t as MediaRepository } from "./media-its1WLYv.mjs";
4
4
  import { t as OptionsRepository } from "./options-BlmBHTvX.mjs";
5
5
  import { n as peekRequestCache, r as requestCached } from "./request-cache-BSUptuJR.mjs";
6
- import { a as getDb } from "./loader-Be3ouI5L.mjs";
6
+ import { a as getDb } from "./loader-D4rigvjR.mjs";
7
7
  import { n as invalidateSingleFlightCache, r as singleFlightCached, t as createSingleFlightCache } from "./single-flight-cache-C2exrGAi.mjs";
8
8
 
9
9
  //#region src/settings/index.ts
@@ -242,4 +242,4 @@ async function getPluginSettingsWithDb(pluginId, db) {
242
242
 
243
243
  //#endregion
244
244
  export { getSiteSettingsWithDb as a, getSiteSettings as i, getPluginSettings as n, invalidateSiteSettingsCache as o, getSiteSetting as r, setSiteSettings as s, getPluginSetting as t };
245
- //# sourceMappingURL=settings-CpA4lQFt.mjs.map
245
+ //# sourceMappingURL=settings-C2PaBS49.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"settings-CpA4lQFt.mjs","names":[],"sources":["../src/settings/index.ts"],"sourcesContent":["/**\n * Site Settings API\n *\n * Functions for getting and setting global site configuration.\n * Settings are stored in the options table with 'site:' prefix.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { after } from \"../after.js\";\nimport { MediaRepository } from \"../database/repositories/media.js\";\nimport { OptionsRepository } from \"../database/repositories/options.js\";\nimport type { Database } from \"../database/types.js\";\nimport { getDb } from \"../loader.js\";\nimport { cachedQuery, invalidateObjectCache } from \"../object-cache/index.js\";\nimport { peekRequestCache, requestCached } from \"../request-cache.js\";\n\n/** Object-cache namespace for site settings. */\nconst SETTINGS_CACHE_NAMESPACE = \"settings\";\nimport type { Storage } from \"../storage/types.js\";\nimport {\n\tcreateSingleFlightCache,\n\ttype SingleFlightCache,\n\tinvalidateSingleFlightCache,\n\tsingleFlightCached,\n} from \"../utils/single-flight-cache.js\";\nimport type { SiteSettings, SiteSettingKey, MediaReference, SeoSettings } from \"./types.js\";\n\n/** Prefix for site settings in the options table */\nconst SETTINGS_PREFIX = \"site:\";\n\n/**\n * Worker-isolate cache for the resolved `site:*` settings.\n *\n * Site settings (title, logo, SEO defaults) change rarely but are read on\n * every public request. Caching across the isolate's lifetime drops the\n * `options WHERE name LIKE 'site:%'` prefix scan from once-per-request to\n * once-per-isolate. Cross-isolate staleness is bounded by isolate lifetime\n * (workerd typically recycles within minutes); acceptable for chrome.\n *\n * Backed by single-flight-cache.ts: concurrent cold reads coalesce onto one\n * query via a reclaimable single-flight lock and the resolved *value* is\n * cached — never a shared in-flight promise, so a cancelled request can't\n * poison the isolate (see that file's header). Stored on globalThis with a\n * Symbol.for key so Vite SSR chunk duplication doesn't produce two\n * independent caches (same pattern as request-context.ts).\n */\nconst SITE_SETTINGS_CACHE_KEY = Symbol.for(\"emdash:site-settings\");\nconst g = globalThis as Record<symbol, unknown>;\nconst settingsCache: SingleFlightCache<Partial<SiteSettings>> =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see request-context.ts)\n\t(g[SITE_SETTINGS_CACHE_KEY] as SingleFlightCache<Partial<SiteSettings>> | undefined) ??\n\t(() => {\n\t\tconst c = createSingleFlightCache<Partial<SiteSettings>>();\n\t\tg[SITE_SETTINGS_CACHE_KEY] = c;\n\t\treturn c;\n\t})();\n\n/**\n * Bump the isolate-wide site-settings cache version, forcing the next\n * `getSiteSettings()` to re-query the database.\n *\n * Called from every `site:*` write path. Other isolates still serve their\n * own cached copy until they expire — staleness bounded by isolate lifetime.\n */\nexport function invalidateSiteSettingsCache(): void {\n\tinvalidateSingleFlightCache(settingsCache);\n\t// Cross-isolate invalidation for the optional distributed object cache.\n\tinvalidateObjectCache(SETTINGS_CACHE_NAMESPACE);\n}\n\n/**\n * Type guard for MediaReference values\n */\nfunction isMediaReference(value: unknown): value is MediaReference {\n\treturn typeof value === \"object\" && value !== null && \"mediaId\" in value;\n}\n\n/**\n * Resolve a media reference to include the full URL plus content metadata.\n *\n * Pulls `mimeType` and intrinsic dimensions from the media row so callers\n * can emit correct head tags (e.g. `<link rel=\"icon\" type=\"image/svg+xml\">`,\n * which Chromium requires when the URL has no `.svg` extension) without\n * a second round-trip to the media table.\n */\nasync function resolveMediaReference(\n\tmediaRef: MediaReference | undefined,\n\tdb: Kysely<Database>,\n\t_storage: Storage | null,\n): Promise<MediaReference | undefined> {\n\tif (!mediaRef?.mediaId) {\n\t\treturn mediaRef;\n\t}\n\n\ttry {\n\t\tconst mediaRepo = new MediaRepository(db);\n\t\tconst media = await mediaRepo.findById(mediaRef.mediaId);\n\n\t\tif (media) {\n\t\t\t// Construct URL using the same pattern as API handlers\n\t\t\treturn {\n\t\t\t\t...mediaRef,\n\t\t\t\turl: `/_emdash/api/media/file/${media.storageKey}`,\n\t\t\t\tcontentType: media.mimeType,\n\t\t\t\t...(media.width !== null ? { width: media.width } : {}),\n\t\t\t\t...(media.height !== null ? { height: media.height } : {}),\n\t\t\t};\n\t\t}\n\t} catch {\n\t\t// If media not found or error, return the reference as-is\n\t}\n\n\treturn mediaRef;\n}\n\n/**\n * Get a single site setting by key\n *\n * Returns `undefined` if the setting has not been configured.\n * For media settings (logo, favicon), the URL is resolved automatically.\n *\n * @param key - The setting key (e.g., \"title\", \"logo\", \"social\")\n * @returns The setting value, or undefined if not set\n *\n * @example\n * ```ts\n * import { getSiteSetting } from \"emdash\";\n *\n * const title = await getSiteSetting(\"title\");\n * const logo = await getSiteSetting(\"logo\");\n * console.log(logo?.url); // Resolved URL\n * ```\n */\nexport async function getSiteSetting<K extends SiteSettingKey>(\n\tkey: K,\n): Promise<SiteSettings[K] | undefined> {\n\t// If `getSiteSettings()` has already been called in this request,\n\t// read from that (request-cached) batch rather than firing a second\n\t// options-table query. Common layout: a Base template pulls the\n\t// whole settings object up-front, then `EmDashHead` or a plugin\n\t// asks for one key — no reason the singular call should round-trip\n\t// again.\n\tconst primed = peekRequestCache<Partial<SiteSettings>>(\"siteSettings\");\n\tif (primed) {\n\t\tconst settings = await primed;\n\t\treturn settings[key];\n\t}\n\n\t// Otherwise cache per-key. Templates that pull several settings\n\t// independently still share the in-flight query for each one.\n\treturn requestCached(`siteSetting:${key}`, async () => {\n\t\tconst db = await getDb();\n\t\treturn getSiteSettingWithDb(key, db);\n\t});\n}\n\n/**\n * Get a single site setting by key (with explicit db)\n *\n * @internal Use `getSiteSetting()` in templates. This variant is for admin routes\n * that already have a database handle.\n */\nexport async function getSiteSettingWithDb<K extends SiteSettingKey>(\n\tkey: K,\n\tdb: Kysely<Database>,\n\tstorage: Storage | null = null,\n): Promise<SiteSettings[K] | undefined> {\n\tconst options = new OptionsRepository(db);\n\tconst value = await options.get<SiteSettings[K]>(`${SETTINGS_PREFIX}${key}`);\n\n\tif (!value) {\n\t\treturn undefined;\n\t}\n\n\t// Resolve media references if needed.\n\t// TS cannot narrow generic K from key equality checks — this is a known limitation.\n\t// We use the non-generic getSiteSettingsWithDb for media resolution instead.\n\tif ((key === \"logo\" || key === \"favicon\") && isMediaReference(value)) {\n\t\tconst resolved = await resolveMediaReference(value, db, storage);\n\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- TS can't narrow generic K from key equality; resolved type is correct\n\t\treturn resolved as SiteSettings[K] | undefined;\n\t}\n\n\tif (key === \"seo\" && value && typeof value === \"object\") {\n\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- TS can't narrow generic K from key equality\n\t\tconst seo = value as SeoSettings;\n\t\tif (seo.defaultOgImage) {\n\t\t\tconst resolved = {\n\t\t\t\t...seo,\n\t\t\t\tdefaultOgImage: await resolveMediaReference(seo.defaultOgImage, db, storage),\n\t\t\t};\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- TS can't narrow generic K from key equality\n\t\t\treturn resolved as SiteSettings[K] | undefined;\n\t\t}\n\t}\n\n\treturn value;\n}\n\n/**\n * Get all site settings\n *\n * Returns all configured settings. Unset values are undefined.\n * Media references (logo/favicon) are resolved to include URLs.\n *\n * @example\n * ```ts\n * import { getSiteSettings } from \"emdash\";\n *\n * const settings = await getSiteSettings();\n * console.log(settings.title); // \"My Site\"\n * console.log(settings.logo?.url); // \"/_emdash/api/media/file/abc123\"\n * ```\n */\nexport function getSiteSettings(): Promise<Partial<SiteSettings>> {\n\t// requestCached dedupes within a single request; singleFlightCached\n\t// coalesces across requests and caches the resolved value for the\n\t// global scope's lifetime without ever sharing an awaitable promise. The\n\t// distributed object cache (cachedQuery) sits beneath both, backing cold\n\t// isolates without a database round-trip.\n\treturn requestCached(\"siteSettings\", () =>\n\t\tsingleFlightCached(\n\t\t\tsettingsCache,\n\t\t\t() =>\n\t\t\t\tcachedQuery({\n\t\t\t\t\tnamespace: SETTINGS_CACHE_NAMESPACE,\n\t\t\t\t\tkey: \"all\",\n\t\t\t\t\tload: async () => {\n\t\t\t\t\t\tconst db = await getDb();\n\t\t\t\t\t\treturn getSiteSettingsWithDb(db);\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t{ anchor: (promise) => after(() => promise), ownerTimeoutMs: 30_000 },\n\t\t),\n\t);\n}\n\n/**\n * Get all site settings (with explicit db)\n *\n * @internal Use `getSiteSettings()` in templates. This variant is for admin routes\n * that already have a database handle.\n */\nexport async function getSiteSettingsWithDb(\n\tdb: Kysely<Database>,\n\tstorage: Storage | null = null,\n): Promise<Partial<SiteSettings>> {\n\tconst options = new OptionsRepository(db);\n\tconst allOptions = await options.getByPrefix(SETTINGS_PREFIX);\n\n\tconst settings: Record<string, unknown> = {};\n\n\t// Convert Map to settings object, removing the prefix\n\tfor (const [key, value] of allOptions) {\n\t\tconst settingKey = key.replace(SETTINGS_PREFIX, \"\");\n\t\tsettings[settingKey] = value;\n\t}\n\n\tconst typedSettings = settings as Partial<SiteSettings>;\n\n\t// Resolve media references\n\tif (typedSettings.logo) {\n\t\ttypedSettings.logo = await resolveMediaReference(typedSettings.logo, db, storage);\n\t}\n\tif (typedSettings.favicon) {\n\t\ttypedSettings.favicon = await resolveMediaReference(typedSettings.favicon, db, storage);\n\t}\n\tif (typedSettings.seo?.defaultOgImage) {\n\t\ttypedSettings.seo = {\n\t\t\t...typedSettings.seo,\n\t\t\tdefaultOgImage: await resolveMediaReference(typedSettings.seo.defaultOgImage, db, storage),\n\t\t};\n\t}\n\n\treturn typedSettings;\n}\n\n/**\n * Set site settings (internal function used by admin API)\n *\n * Merges provided settings with existing ones. Only provided fields are updated.\n * Media references should include just the mediaId; URLs are resolved on read.\n *\n * @param settings - Partial settings object with values to update\n * @param db - Kysely database instance\n * @returns Promise that resolves when settings are saved\n *\n * @internal\n *\n * @example\n * ```ts\n * // Update multiple settings at once\n * await setSiteSettings({\n * title: \"My Site\",\n * tagline: \"Welcome\",\n * logo: { mediaId: \"med_123\", alt: \"Logo\" }\n * }, db);\n * ```\n */\nexport async function setSiteSettings(\n\tsettings: Partial<SiteSettings>,\n\tdb: Kysely<Database>,\n): Promise<void> {\n\tconst options = new OptionsRepository(db);\n\n\t// Convert settings to options format\n\tconst updates: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(settings)) {\n\t\tif (value !== undefined) {\n\t\t\tupdates[`${SETTINGS_PREFIX}${key}`] = value;\n\t\t}\n\t}\n\n\ttry {\n\t\tawait options.setMany(updates);\n\t} finally {\n\t\tinvalidateSiteSettingsCache();\n\t}\n}\n\n/**\n * Get a single plugin setting by key.\n *\n * Plugin settings are stored in the options table under\n * `plugin:<pluginId>:settings:<key>`.\n */\nexport async function getPluginSetting<T = unknown>(\n\tpluginId: string,\n\tkey: string,\n): Promise<T | undefined> {\n\tconst db = await getDb();\n\treturn getPluginSettingWithDb<T>(pluginId, key, db);\n}\n\n/**\n * Get a single plugin setting by key (with explicit db).\n *\n * @internal Use `getPluginSetting()` in templates and plugin rendering code.\n */\nexport async function getPluginSettingWithDb<T = unknown>(\n\tpluginId: string,\n\tkey: string,\n\tdb: Kysely<Database>,\n): Promise<T | undefined> {\n\tconst options = new OptionsRepository(db);\n\tconst value = await options.get<T>(`plugin:${pluginId}:settings:${key}`);\n\treturn value ?? undefined;\n}\n\n/**\n * Get all persisted plugin settings for a plugin.\n *\n * Defaults declared in `admin.settingsSchema` are not materialized\n * automatically; callers should apply their own fallback defaults.\n */\nexport async function getPluginSettings(pluginId: string): Promise<Record<string, unknown>> {\n\tconst db = await getDb();\n\treturn getPluginSettingsWithDb(pluginId, db);\n}\n\n/**\n * Get all persisted plugin settings for a plugin (with explicit db).\n *\n * @internal Use `getPluginSettings()` in templates and plugin rendering code.\n */\nexport async function getPluginSettingsWithDb(\n\tpluginId: string,\n\tdb: Kysely<Database>,\n): Promise<Record<string, unknown>> {\n\tconst prefix = `plugin:${pluginId}:settings:`;\n\tconst options = new OptionsRepository(db);\n\tconst allOptions = await options.getByPrefix(prefix);\n\n\tconst settings: Record<string, unknown> = {};\n\tfor (const [key, value] of allOptions) {\n\t\tif (!key.startsWith(prefix)) {\n\t\t\tcontinue;\n\t\t}\n\t\tsettings[key.slice(prefix.length)] = value;\n\t}\n\n\treturn settings;\n}\n"],"mappings":";;;;;;;;;;AAkBA,MAAM,2BAA2B;;AAWjC,MAAM,kBAAkB;;;;;;;;;;;;;;;;;AAkBxB,MAAM,0BAA0B,OAAO,IAAI,uBAAuB;AAClE,MAAM,IAAI;AACV,MAAM,gBAEJ,EAAE,mCACI;CACN,MAAM,IAAI,yBAAgD;AAC1D,GAAE,2BAA2B;AAC7B,QAAO;IACJ;;;;;;;;AASL,SAAgB,8BAAoC;AACnD,6BAA4B,cAAc;AAE1C,uBAAsB,yBAAyB;;;;;AAMhD,SAAS,iBAAiB,OAAyC;AAClE,QAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa;;;;;;;;;;AAWpE,eAAe,sBACd,UACA,IACA,UACsC;AACtC,KAAI,CAAC,UA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,aAAa,MADH,IAAI,kBAAkB,GAAG,CACR,YAAY,OAAO;CAEpD,MAAM,WAAoC,EAAE;AAC5C,MAAK,MAAM,CAAC,KAAK,UAAU,YAAY;AACtC,MAAI,CAAC,IAAI,WAAW,OAAO,CAC1B;AAED,WAAS,IAAI,MAAM,OAAO,OAAO,IAAI;;AAGtC,QAAO"}
1
+ {"version":3,"file":"settings-C2PaBS49.mjs","names":[],"sources":["../src/settings/index.ts"],"sourcesContent":["/**\n * Site Settings API\n *\n * Functions for getting and setting global site configuration.\n * Settings are stored in the options table with 'site:' prefix.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { after } from \"../after.js\";\nimport { MediaRepository } from \"../database/repositories/media.js\";\nimport { OptionsRepository } from \"../database/repositories/options.js\";\nimport type { Database } from \"../database/types.js\";\nimport { getDb } from \"../loader.js\";\nimport { cachedQuery, invalidateObjectCache } from \"../object-cache/index.js\";\nimport { peekRequestCache, requestCached } from \"../request-cache.js\";\n\n/** Object-cache namespace for site settings. */\nconst SETTINGS_CACHE_NAMESPACE = \"settings\";\nimport type { Storage } from \"../storage/types.js\";\nimport {\n\tcreateSingleFlightCache,\n\ttype SingleFlightCache,\n\tinvalidateSingleFlightCache,\n\tsingleFlightCached,\n} from \"../utils/single-flight-cache.js\";\nimport type { SiteSettings, SiteSettingKey, MediaReference, SeoSettings } from \"./types.js\";\n\n/** Prefix for site settings in the options table */\nconst SETTINGS_PREFIX = \"site:\";\n\n/**\n * Worker-isolate cache for the resolved `site:*` settings.\n *\n * Site settings (title, logo, SEO defaults) change rarely but are read on\n * every public request. Caching across the isolate's lifetime drops the\n * `options WHERE name LIKE 'site:%'` prefix scan from once-per-request to\n * once-per-isolate. Cross-isolate staleness is bounded by isolate lifetime\n * (workerd typically recycles within minutes); acceptable for chrome.\n *\n * Backed by single-flight-cache.ts: concurrent cold reads coalesce onto one\n * query via a reclaimable single-flight lock and the resolved *value* is\n * cached — never a shared in-flight promise, so a cancelled request can't\n * poison the isolate (see that file's header). Stored on globalThis with a\n * Symbol.for key so Vite SSR chunk duplication doesn't produce two\n * independent caches (same pattern as request-context.ts).\n */\nconst SITE_SETTINGS_CACHE_KEY = Symbol.for(\"emdash:site-settings\");\nconst g = globalThis as Record<symbol, unknown>;\nconst settingsCache: SingleFlightCache<Partial<SiteSettings>> =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see request-context.ts)\n\t(g[SITE_SETTINGS_CACHE_KEY] as SingleFlightCache<Partial<SiteSettings>> | undefined) ??\n\t(() => {\n\t\tconst c = createSingleFlightCache<Partial<SiteSettings>>();\n\t\tg[SITE_SETTINGS_CACHE_KEY] = c;\n\t\treturn c;\n\t})();\n\n/**\n * Bump the isolate-wide site-settings cache version, forcing the next\n * `getSiteSettings()` to re-query the database.\n *\n * Called from every `site:*` write path. Other isolates still serve their\n * own cached copy until they expire — staleness bounded by isolate lifetime.\n */\nexport function invalidateSiteSettingsCache(): void {\n\tinvalidateSingleFlightCache(settingsCache);\n\t// Cross-isolate invalidation for the optional distributed object cache.\n\tinvalidateObjectCache(SETTINGS_CACHE_NAMESPACE);\n}\n\n/**\n * Type guard for MediaReference values\n */\nfunction isMediaReference(value: unknown): value is MediaReference {\n\treturn typeof value === \"object\" && value !== null && \"mediaId\" in value;\n}\n\n/**\n * Resolve a media reference to include the full URL plus content metadata.\n *\n * Pulls `mimeType` and intrinsic dimensions from the media row so callers\n * can emit correct head tags (e.g. `<link rel=\"icon\" type=\"image/svg+xml\">`,\n * which Chromium requires when the URL has no `.svg` extension) without\n * a second round-trip to the media table.\n */\nasync function resolveMediaReference(\n\tmediaRef: MediaReference | undefined,\n\tdb: Kysely<Database>,\n\t_storage: Storage | null,\n): Promise<MediaReference | undefined> {\n\tif (!mediaRef?.mediaId) {\n\t\treturn mediaRef;\n\t}\n\n\ttry {\n\t\tconst mediaRepo = new MediaRepository(db);\n\t\tconst media = await mediaRepo.findById(mediaRef.mediaId);\n\n\t\tif (media) {\n\t\t\t// Construct URL using the same pattern as API handlers\n\t\t\treturn {\n\t\t\t\t...mediaRef,\n\t\t\t\turl: `/_emdash/api/media/file/${media.storageKey}`,\n\t\t\t\tcontentType: media.mimeType,\n\t\t\t\t...(media.width !== null ? { width: media.width } : {}),\n\t\t\t\t...(media.height !== null ? { height: media.height } : {}),\n\t\t\t};\n\t\t}\n\t} catch {\n\t\t// If media not found or error, return the reference as-is\n\t}\n\n\treturn mediaRef;\n}\n\n/**\n * Get a single site setting by key\n *\n * Returns `undefined` if the setting has not been configured.\n * For media settings (logo, favicon), the URL is resolved automatically.\n *\n * @param key - The setting key (e.g., \"title\", \"logo\", \"social\")\n * @returns The setting value, or undefined if not set\n *\n * @example\n * ```ts\n * import { getSiteSetting } from \"emdash\";\n *\n * const title = await getSiteSetting(\"title\");\n * const logo = await getSiteSetting(\"logo\");\n * console.log(logo?.url); // Resolved URL\n * ```\n */\nexport async function getSiteSetting<K extends SiteSettingKey>(\n\tkey: K,\n): Promise<SiteSettings[K] | undefined> {\n\t// If `getSiteSettings()` has already been called in this request,\n\t// read from that (request-cached) batch rather than firing a second\n\t// options-table query. Common layout: a Base template pulls the\n\t// whole settings object up-front, then `EmDashHead` or a plugin\n\t// asks for one key — no reason the singular call should round-trip\n\t// again.\n\tconst primed = peekRequestCache<Partial<SiteSettings>>(\"siteSettings\");\n\tif (primed) {\n\t\tconst settings = await primed;\n\t\treturn settings[key];\n\t}\n\n\t// Otherwise cache per-key. Templates that pull several settings\n\t// independently still share the in-flight query for each one.\n\treturn requestCached(`siteSetting:${key}`, async () => {\n\t\tconst db = await getDb();\n\t\treturn getSiteSettingWithDb(key, db);\n\t});\n}\n\n/**\n * Get a single site setting by key (with explicit db)\n *\n * @internal Use `getSiteSetting()` in templates. This variant is for admin routes\n * that already have a database handle.\n */\nexport async function getSiteSettingWithDb<K extends SiteSettingKey>(\n\tkey: K,\n\tdb: Kysely<Database>,\n\tstorage: Storage | null = null,\n): Promise<SiteSettings[K] | undefined> {\n\tconst options = new OptionsRepository(db);\n\tconst value = await options.get<SiteSettings[K]>(`${SETTINGS_PREFIX}${key}`);\n\n\tif (!value) {\n\t\treturn undefined;\n\t}\n\n\t// Resolve media references if needed.\n\t// TS cannot narrow generic K from key equality checks — this is a known limitation.\n\t// We use the non-generic getSiteSettingsWithDb for media resolution instead.\n\tif ((key === \"logo\" || key === \"favicon\") && isMediaReference(value)) {\n\t\tconst resolved = await resolveMediaReference(value, db, storage);\n\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- TS can't narrow generic K from key equality; resolved type is correct\n\t\treturn resolved as SiteSettings[K] | undefined;\n\t}\n\n\tif (key === \"seo\" && value && typeof value === \"object\") {\n\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- TS can't narrow generic K from key equality\n\t\tconst seo = value as SeoSettings;\n\t\tif (seo.defaultOgImage) {\n\t\t\tconst resolved = {\n\t\t\t\t...seo,\n\t\t\t\tdefaultOgImage: await resolveMediaReference(seo.defaultOgImage, db, storage),\n\t\t\t};\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- TS can't narrow generic K from key equality\n\t\t\treturn resolved as SiteSettings[K] | undefined;\n\t\t}\n\t}\n\n\treturn value;\n}\n\n/**\n * Get all site settings\n *\n * Returns all configured settings. Unset values are undefined.\n * Media references (logo/favicon) are resolved to include URLs.\n *\n * @example\n * ```ts\n * import { getSiteSettings } from \"emdash\";\n *\n * const settings = await getSiteSettings();\n * console.log(settings.title); // \"My Site\"\n * console.log(settings.logo?.url); // \"/_emdash/api/media/file/abc123\"\n * ```\n */\nexport function getSiteSettings(): Promise<Partial<SiteSettings>> {\n\t// requestCached dedupes within a single request; singleFlightCached\n\t// coalesces across requests and caches the resolved value for the\n\t// global scope's lifetime without ever sharing an awaitable promise. The\n\t// distributed object cache (cachedQuery) sits beneath both, backing cold\n\t// isolates without a database round-trip.\n\treturn requestCached(\"siteSettings\", () =>\n\t\tsingleFlightCached(\n\t\t\tsettingsCache,\n\t\t\t() =>\n\t\t\t\tcachedQuery({\n\t\t\t\t\tnamespace: SETTINGS_CACHE_NAMESPACE,\n\t\t\t\t\tkey: \"all\",\n\t\t\t\t\tload: async () => {\n\t\t\t\t\t\tconst db = await getDb();\n\t\t\t\t\t\treturn getSiteSettingsWithDb(db);\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t{ anchor: (promise) => after(() => promise), ownerTimeoutMs: 30_000 },\n\t\t),\n\t);\n}\n\n/**\n * Get all site settings (with explicit db)\n *\n * @internal Use `getSiteSettings()` in templates. This variant is for admin routes\n * that already have a database handle.\n */\nexport async function getSiteSettingsWithDb(\n\tdb: Kysely<Database>,\n\tstorage: Storage | null = null,\n): Promise<Partial<SiteSettings>> {\n\tconst options = new OptionsRepository(db);\n\tconst allOptions = await options.getByPrefix(SETTINGS_PREFIX);\n\n\tconst settings: Record<string, unknown> = {};\n\n\t// Convert Map to settings object, removing the prefix\n\tfor (const [key, value] of allOptions) {\n\t\tconst settingKey = key.replace(SETTINGS_PREFIX, \"\");\n\t\tsettings[settingKey] = value;\n\t}\n\n\tconst typedSettings = settings as Partial<SiteSettings>;\n\n\t// Resolve media references\n\tif (typedSettings.logo) {\n\t\ttypedSettings.logo = await resolveMediaReference(typedSettings.logo, db, storage);\n\t}\n\tif (typedSettings.favicon) {\n\t\ttypedSettings.favicon = await resolveMediaReference(typedSettings.favicon, db, storage);\n\t}\n\tif (typedSettings.seo?.defaultOgImage) {\n\t\ttypedSettings.seo = {\n\t\t\t...typedSettings.seo,\n\t\t\tdefaultOgImage: await resolveMediaReference(typedSettings.seo.defaultOgImage, db, storage),\n\t\t};\n\t}\n\n\treturn typedSettings;\n}\n\n/**\n * Set site settings (internal function used by admin API)\n *\n * Merges provided settings with existing ones. Only provided fields are updated.\n * Media references should include just the mediaId; URLs are resolved on read.\n *\n * @param settings - Partial settings object with values to update\n * @param db - Kysely database instance\n * @returns Promise that resolves when settings are saved\n *\n * @internal\n *\n * @example\n * ```ts\n * // Update multiple settings at once\n * await setSiteSettings({\n * title: \"My Site\",\n * tagline: \"Welcome\",\n * logo: { mediaId: \"med_123\", alt: \"Logo\" }\n * }, db);\n * ```\n */\nexport async function setSiteSettings(\n\tsettings: Partial<SiteSettings>,\n\tdb: Kysely<Database>,\n): Promise<void> {\n\tconst options = new OptionsRepository(db);\n\n\t// Convert settings to options format\n\tconst updates: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(settings)) {\n\t\tif (value !== undefined) {\n\t\t\tupdates[`${SETTINGS_PREFIX}${key}`] = value;\n\t\t}\n\t}\n\n\ttry {\n\t\tawait options.setMany(updates);\n\t} finally {\n\t\tinvalidateSiteSettingsCache();\n\t}\n}\n\n/**\n * Get a single plugin setting by key.\n *\n * Plugin settings are stored in the options table under\n * `plugin:<pluginId>:settings:<key>`.\n */\nexport async function getPluginSetting<T = unknown>(\n\tpluginId: string,\n\tkey: string,\n): Promise<T | undefined> {\n\tconst db = await getDb();\n\treturn getPluginSettingWithDb<T>(pluginId, key, db);\n}\n\n/**\n * Get a single plugin setting by key (with explicit db).\n *\n * @internal Use `getPluginSetting()` in templates and plugin rendering code.\n */\nexport async function getPluginSettingWithDb<T = unknown>(\n\tpluginId: string,\n\tkey: string,\n\tdb: Kysely<Database>,\n): Promise<T | undefined> {\n\tconst options = new OptionsRepository(db);\n\tconst value = await options.get<T>(`plugin:${pluginId}:settings:${key}`);\n\treturn value ?? undefined;\n}\n\n/**\n * Get all persisted plugin settings for a plugin.\n *\n * Defaults declared in `admin.settingsSchema` are not materialized\n * automatically; callers should apply their own fallback defaults.\n */\nexport async function getPluginSettings(pluginId: string): Promise<Record<string, unknown>> {\n\tconst db = await getDb();\n\treturn getPluginSettingsWithDb(pluginId, db);\n}\n\n/**\n * Get all persisted plugin settings for a plugin (with explicit db).\n *\n * @internal Use `getPluginSettings()` in templates and plugin rendering code.\n */\nexport async function getPluginSettingsWithDb(\n\tpluginId: string,\n\tdb: Kysely<Database>,\n): Promise<Record<string, unknown>> {\n\tconst prefix = `plugin:${pluginId}:settings:`;\n\tconst options = new OptionsRepository(db);\n\tconst allOptions = await options.getByPrefix(prefix);\n\n\tconst settings: Record<string, unknown> = {};\n\tfor (const [key, value] of allOptions) {\n\t\tif (!key.startsWith(prefix)) {\n\t\t\tcontinue;\n\t\t}\n\t\tsettings[key.slice(prefix.length)] = value;\n\t}\n\n\treturn settings;\n}\n"],"mappings":";;;;;;;;;;AAkBA,MAAM,2BAA2B;;AAWjC,MAAM,kBAAkB;;;;;;;;;;;;;;;;;AAkBxB,MAAM,0BAA0B,OAAO,IAAI,uBAAuB;AAClE,MAAM,IAAI;AACV,MAAM,gBAEJ,EAAE,mCACI;CACN,MAAM,IAAI,yBAAgD;AAC1D,GAAE,2BAA2B;AAC7B,QAAO;IACJ;;;;;;;;AASL,SAAgB,8BAAoC;AACnD,6BAA4B,cAAc;AAE1C,uBAAsB,yBAAyB;;;;;AAMhD,SAAS,iBAAiB,OAAyC;AAClE,QAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,aAAa;;;;;;;;;;AAWpE,eAAe,sBACd,UACA,IACA,UACsC;AACtC,KAAI,CAAC,UAAU,QACd,QAAO;AAGR,KAAI;EAEH,MAAM,QAAQ,MADI,IAAI,gBAAgB,GAAG,CACX,SAAS,SAAS,QAAQ;AAExD,MAAI,MAEH,QAAO;GACN,GAAG;GACH,KAAK,2BAA2B,MAAM;GACtC,aAAa,MAAM;GACnB,GAAI,MAAM,UAAU,OAAO,EAAE,OAAO,MAAM,OAAO,GAAG,EAAE;GACtD,GAAI,MAAM,WAAW,OAAO,EAAE,QAAQ,MAAM,QAAQ,GAAG,EAAE;GACzD;SAEK;AAIR,QAAO;;;;;;;;;;;;;;;;;;;;AAqBR,eAAsB,eACrB,KACuC;CAOvC,MAAM,SAAS,iBAAwC,eAAe;AACtE,KAAI,OAEH,SADiB,MAAM,QACP;AAKjB,QAAO,cAAc,eAAe,OAAO,YAAY;AAEtD,SAAO,qBAAqB,KADjB,MAAM,OAAO,CACY;GACnC;;;;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AGF,QAAO;;;;;;;;;;;;;;;;;;;;;;;;AAyBR,eAAsB,gBACrB,UACA,IACgB;CAChB,MAAM,UAAU,IAAI,kBAAkB,GAAG;CAGzC,MAAM,UAAmC,EAAE;AAC3C,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,SAAS,CAClD,KAAI,UAAU,OACb,SAAQ,GAAG,kBAAkB,SAAS;AAIxC,KAAI;AACH,QAAM,QAAQ,QAAQ,QAAQ;WACrB;AACT,+BAA6B;;;;;;;;;AAU/B,eAAsB,iBACrB,UACA,KACyB;AAEzB,QAAO,uBAA0B,UAAU,KADhC,MAAM,OAAO,CAC2B;;;;;;;AAQpD,eAAsB,uBACrB,UACA,KACA,IACyB;AAGzB,QADc,MADE,IAAI,kBAAkB,GAAG,CACb,IAAO,UAAU,SAAS,YAAY,MAAM,IACxD;;;;;;;;AASjB,eAAsB,kBAAkB,UAAoD;AAE3F,QAAO,wBAAwB,UADpB,MAAM,OAAO,CACoB;;;;;;;AAQ7C,eAAsB,wBACrB,UACA,IACmC;CACnC,MAAM,SAAS,UAAU,SAAS;CAElC,MAAM,aAAa,MADH,IAAI,kBAAkB,GAAG,CACR,YAAY,OAAO;CAEpD,MAAM,WAAoC,EAAE;AAC5C,MAAK,MAAM,CAAC,KAAK,UAAU,YAAY;AACtC,MAAI,CAAC,IAAI,WAAW,OAAO,CAC1B;AAED,WAAS,IAAI,MAAM,OAAO,OAAO,IAAI;;AAGtC,QAAO"}
@@ -1,5 +1,5 @@
1
- import { o as __exportAll } from "./runner-DfnZ5eUr.mjs";
2
- import { a as getSiteSettingsWithDb, s as setSiteSettings } from "./settings-CpA4lQFt.mjs";
1
+ import { o as __exportAll } from "./runner-BdeLEgad.mjs";
2
+ import { a as getSiteSettingsWithDb, s as setSiteSettings } from "./settings-C2PaBS49.mjs";
3
3
 
4
4
  //#region src/api/handlers/settings.ts
5
5
  var settings_exports = /* @__PURE__ */ __exportAll({
@@ -48,4 +48,4 @@ async function handleSettingsUpdate(db, storage, input) {
48
48
 
49
49
  //#endregion
50
50
  export { handleSettingsUpdate as n, settings_exports as r, handleSettingsGet as t };
51
- //# sourceMappingURL=settings-C4s8hFQm.mjs.map
51
+ //# sourceMappingURL=settings-Dtc0DU31.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"settings-C4s8hFQm.mjs","names":[],"sources":["../src/api/handlers/settings.ts"],"sourcesContent":["/**\n * Settings handlers\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport type { Database } from \"../../database/types.js\";\nimport { getSiteSettingsWithDb, setSiteSettings } from \"../../settings/index.js\";\nimport type { SiteSettings } from \"../../settings/types.js\";\nimport type { Storage } from \"../../storage/types.js\";\nimport type { ApiResult } from \"../types.js\";\n\n/**\n * Get all site settings\n */\nexport async function handleSettingsGet(\n\tdb: Kysely<Database>,\n\tstorage: Storage | null,\n): Promise<ApiResult<Partial<SiteSettings>>> {\n\ttry {\n\t\tconst settings = await getSiteSettingsWithDb(db, storage);\n\t\treturn { success: true, data: settings };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"SETTINGS_READ_ERROR\", message: \"Failed to get settings\" },\n\t\t};\n\t}\n}\n\n/**\n * Update site settings\n */\nexport async function handleSettingsUpdate(\n\tdb: Kysely<Database>,\n\tstorage: Storage | null,\n\tinput: Partial<SiteSettings>,\n): Promise<ApiResult<Partial<SiteSettings>>> {\n\ttry {\n\t\tawait setSiteSettings(input, db);\n\t\tconst updatedSettings = await getSiteSettingsWithDb(db, storage);\n\t\treturn { success: true, data: updatedSettings };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"SETTINGS_UPDATE_ERROR\", message: \"Failed to update settings\" },\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAeA,eAAsB,kBACrB,IACA,SAC4C;AAC5C,KAAI;AAEH,SAAO;GAAE,SAAS;GAAM,MADP,MAAM,sBAAsB,IAAI,QAAQ;GACjB;SACjC;AACP,SAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAuB,SAAS;IAA0B;GACzE;;;;;;AAOH,eAAsB,qBACrB,IACA,SACA,OAC4C;AAC5C,KAAI;AACH,QAAM,gBAAgB,OAAO,GAAG;AAEhC,SAAO;GAAE,SAAS;GAAM,MADA,MAAM,sBAAsB,IAAI,QAAQ;GACjB;SACxC;AACP,SAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAyB,SAAS;IAA6B;GAC9E"}
1
+ {"version":3,"file":"settings-Dtc0DU31.mjs","names":[],"sources":["../src/api/handlers/settings.ts"],"sourcesContent":["/**\n * Settings handlers\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport type { Database } from \"../../database/types.js\";\nimport { getSiteSettingsWithDb, setSiteSettings } from \"../../settings/index.js\";\nimport type { SiteSettings } from \"../../settings/types.js\";\nimport type { Storage } from \"../../storage/types.js\";\nimport type { ApiResult } from \"../types.js\";\n\n/**\n * Get all site settings\n */\nexport async function handleSettingsGet(\n\tdb: Kysely<Database>,\n\tstorage: Storage | null,\n): Promise<ApiResult<Partial<SiteSettings>>> {\n\ttry {\n\t\tconst settings = await getSiteSettingsWithDb(db, storage);\n\t\treturn { success: true, data: settings };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"SETTINGS_READ_ERROR\", message: \"Failed to get settings\" },\n\t\t};\n\t}\n}\n\n/**\n * Update site settings\n */\nexport async function handleSettingsUpdate(\n\tdb: Kysely<Database>,\n\tstorage: Storage | null,\n\tinput: Partial<SiteSettings>,\n): Promise<ApiResult<Partial<SiteSettings>>> {\n\ttry {\n\t\tawait setSiteSettings(input, db);\n\t\tconst updatedSettings = await getSiteSettingsWithDb(db, storage);\n\t\treturn { success: true, data: updatedSettings };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"SETTINGS_UPDATE_ERROR\", message: \"Failed to update settings\" },\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAeA,eAAsB,kBACrB,IACA,SAC4C;AAC5C,KAAI;AAEH,SAAO;GAAE,SAAS;GAAM,MADP,MAAM,sBAAsB,IAAI,QAAQ;GACjB;SACjC;AACP,SAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAuB,SAAS;IAA0B;GACzE;;;;;;AAOH,eAAsB,qBACrB,IACA,SACA,OAC4C;AAC5C,KAAI;AACH,QAAM,gBAAgB,OAAO,GAAG;AAEhC,SAAO;GAAE,SAAS;GAAM,MADA,MAAM,sBAAsB,IAAI,QAAQ;GACjB;SACxC;AACP,SAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAyB,SAAS;IAA6B;GAC9E"}
@@ -1,13 +1,13 @@
1
- import { o as __exportAll } from "./runner-DfnZ5eUr.mjs";
1
+ import { o as __exportAll } from "./runner-BdeLEgad.mjs";
2
2
  import { t as validateIdentifier } from "./validate-VPnKoIzW.mjs";
3
- import { n as buildStatusCondition } from "./dialect-helpers-HxEQGl_1.mjs";
3
+ import { n as buildStatusCondition } from "./dialect-helpers-BtOwo2us.mjs";
4
4
  import { getRequestContext } from "./request-context.mjs";
5
5
  import { d as invalidateTaxonomyObjectCache, f as isObjectCacheActive, n as cachedQuery, r as contentNamespace, t as CacheNamespace } from "./object-cache-Bok5j2ae.mjs";
6
- import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-BxXyunY-.mjs";
6
+ import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-Bq-5DPrD.mjs";
7
7
  import { n as isMissingTableError } from "./db-errors-CcWLaRiR.mjs";
8
8
  import { i as setRequestCacheEntry, n as peekRequestCache, r as requestCached } from "./request-cache-BSUptuJR.mjs";
9
- import { i as resolveLocaleChain, r as resolveLocale } from "./resolve-Cd9dzclN.mjs";
10
- import { a as getDb, s as resetTaxonomyNamesCache } from "./loader-Be3ouI5L.mjs";
9
+ import { i as resolveLocaleChain, r as resolveLocale } from "./resolve-DFr4kq72.mjs";
10
+ import { a as getDb, s as resetTaxonomyNamesCache } from "./loader-D4rigvjR.mjs";
11
11
  import { sql } from "kysely";
12
12
 
13
13
  //#region src/taxonomies/term-counts.ts
@@ -553,7 +553,7 @@ function primeFoldedEntryTerms(collection, perEntry, options = {}) {
553
553
  * the content query respect the active locale.
554
554
  */
555
555
  async function getEntriesByTerm(collection, taxonomyName, termSlug, options = {}) {
556
- const { getEmDashCollection } = await import("./query-DR73ZNfm.mjs").then((n) => n.o);
556
+ const { getEmDashCollection } = await import("./query-BbJQ-dGg.mjs").then((n) => n.o);
557
557
  const queryOptions = { where: { [taxonomyName]: termSlug } };
558
558
  if (options.locale !== void 0) queryOptions.locale = options.locale;
559
559
  const { entries } = await getEmDashCollection(collection, queryOptions);
@@ -604,4 +604,4 @@ function buildTree(flatTerms, counts) {
604
604
 
605
605
  //#endregion
606
606
  export { getTaxonomyDefs as a, getTermsForEntries as c, taxonomies_exports as d, fetchVisibleTermCounts as f, getTaxonomyDef as i, invalidateTaxonomyDefsCache as l, getEntriesByTerm as n, getTaxonomyTerms as o, getEntryTerms as r, getTerm as s, getAllTermsForEntries as t, invalidateTermCache as u };
607
- //# sourceMappingURL=taxonomies-DjSKBZpq.mjs.map
607
+ //# sourceMappingURL=taxonomies-HI9fnTdp.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"taxonomies-DjSKBZpq.mjs","names":[],"sources":["../src/taxonomies/term-counts.ts","../src/taxonomies/index.ts"],"sourcesContent":["/**\n * Shared visible-usage counts for taxonomy terms (issue #581).\n *\n * `content_taxonomies` rows are written for every entry regardless of status\n * and are never pruned on unpublish/trash, so counting the pivot directly\n * inflates counts with drafts and soft-deleted entries. Every user-facing\n * count (public widget, single-term page, admin term list) must instead count\n * only entries that are currently visible on the public site:\n * `status = 'published'` OR (`status = 'scheduled'` AND due), AND\n * `deleted_at IS NULL` — via `buildStatusCondition`, which computes scheduled\n * visibility at query time rather than trusting a literal status value.\n *\n * The public render path is latency-sensitive on D1, so per-collection counts\n * are combined into a single round-trip with UNION ALL — one query per\n * taxonomy, never one per collection.\n */\n\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport { buildStatusCondition } from \"../database/dialect-helpers.js\";\nimport type { Database } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport { isMissingTableError } from \"../utils/db-errors.js\";\n\ninterface CountRow {\n\ttaxonomy_id: string;\n\tcount: number | string | bigint;\n}\n\n/**\n * Per-collection count branch. `taxonomy_id` stores the term's\n * translation_group, so results are keyed by group (locale-independent) and\n * each assignment is counted once no matter how many locales the term has.\n *\n * Scoping to the taxonomy uses `translation_group IN (...)` rather than a\n * join on `taxonomies.id` — the anchor row (id == group) can be deleted while\n * sibling translations survive, and a plain join on `translation_group` would\n * multiply counts by the number of locales.\n */\nfunction collectionBranch(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollection: string,\n): ReturnType<typeof sql> {\n\treturn sql`\n\t\tSELECT ct.taxonomy_id AS taxonomy_id, COUNT(*) AS count\n\t\tFROM content_taxonomies AS ct\n\t\tINNER JOIN ${sql.ref(`ec_${collection}`)} AS e ON e.id = ct.entry_id\n\t\tWHERE ct.collection = ${collection}\n\t\t\tAND ct.taxonomy_id IN (SELECT translation_group FROM taxonomies WHERE name = ${taxonomyName})\n\t\t\tAND ${buildStatusCondition(db, \"published\", \"e\")}\n\t\t\tAND e.deleted_at IS NULL\n\t\tGROUP BY ct.taxonomy_id`;\n}\n\nasync function runCounts(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollections: string[],\n): Promise<Map<string, number>> {\n\tconst branches = collections.map((collection) => collectionBranch(db, taxonomyName, collection));\n\tconst union = sql.join(branches, sql` UNION ALL `);\n\tconst result = await sql<CountRow>`\n\t\tSELECT taxonomy_id, SUM(count) AS count\n\t\tFROM (${union}) AS per_collection\n\t\tGROUP BY taxonomy_id`.execute(db);\n\n\tconst counts = new Map<string, number>();\n\tfor (const row of result.rows) counts.set(row.taxonomy_id, Number(row.count));\n\treturn counts;\n}\n\n/**\n * Count publicly-visible term assignments for one taxonomy, keyed by the\n * term's translation_group (what `content_taxonomies.taxonomy_id` stores).\n *\n * Counts are scoped to the taxonomy's declared collections — pass\n * `TaxonomyDef.collections` (`_emdash_taxonomy_defs.collections`). Collections\n * whose `ec_*` table doesn't exist (pre-migration drift, a declared collection\n * that was never created) are skipped, yielding a partial-but-correct count\n * rather than a throw.\n *\n * One database round-trip for the whole taxonomy (UNION ALL across\n * collections). Callers on the public render path should go through the\n * request-cached wrapper in `taxonomies/index.ts` so a page rendering both the\n * widget and a term detail shares one computation.\n */\nexport async function fetchVisibleTermCounts(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollections: string[],\n): Promise<Map<string, number>> {\n\tconst unique = [...new Set(collections)];\n\tfor (const collection of unique) validateIdentifier(collection, \"collection slug\");\n\tif (unique.length === 0) return new Map();\n\n\ttry {\n\t\treturn await runCounts(db, taxonomyName, unique);\n\t} catch (error) {\n\t\tif (!isMissingTableError(error)) throw error;\n\t}\n\n\t// A declared collection has no ec_* table — retry per collection so the\n\t// existing tables still contribute (still scheduled-aware + deleted_at).\n\tconst counts = new Map<string, number>();\n\tfor (const collection of unique) {\n\t\ttry {\n\t\t\tfor (const [group, count] of await runCounts(db, taxonomyName, [collection])) {\n\t\t\t\tcounts.set(group, (counts.get(group) ?? 0) + count);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (!isMissingTableError(error)) throw error;\n\t\t}\n\t}\n\treturn counts;\n}\n","/**\n * Runtime API for taxonomies.\n *\n * All helpers are locale-aware. When a locale is not passed explicitly we fall\n * back to the request context or the configured `defaultLocale` (see\n * `i18n/resolve.ts`).\n *\n * Because `content_taxonomies.taxonomy_id` stores the translation_group (not a\n * specific term id), the joins here are `taxonomies.translation_group =\n * content_taxonomies.taxonomy_id` + filter by `taxonomies.locale`, which picks\n * the right per-locale term.\n */\n\nimport { resolveLocale, resolveLocaleChain } from \"../i18n/resolve.js\";\nimport { getDb, resetTaxonomyNamesCache } from \"../loader.js\";\nimport {\n\tcachedQuery,\n\tCacheNamespace,\n\tcontentNamespace,\n\tinvalidateTaxonomyObjectCache,\n\tisObjectCacheActive,\n} from \"../object-cache/index.js\";\nimport { peekRequestCache, requestCached, setRequestCacheEntry } from \"../request-cache.js\";\nimport { getRequestContext } from \"../request-context.js\";\nimport { chunks, SQL_BATCH_SIZE } from \"../utils/chunks.js\";\nimport { isMissingTableError } from \"../utils/db-errors.js\";\nimport { fetchVisibleTermCounts } from \"./term-counts.js\";\nimport type { TaxonomyDef, TaxonomyTerm, TaxonomyTermRow } from \"./types.js\";\n\nexport interface TaxonomyQueryOptions {\n\tlocale?: string;\n}\n\n/** Invalidate cached taxonomy term data and any content that hydrates terms. */\nexport function invalidateTermCache(): void {\n\tinvalidateTaxonomyObjectCache();\n}\n\n/**\n * Worker-isolate cache for taxonomy definitions, keyed by resolved locale.\n *\n * Taxonomy *definitions* (the \"category\"/\"tag\" taxonomies themselves, not\n * their terms) are read on every public render that hydrates entry terms —\n * `getAllTermsForEntries` → `getCollectionTaxonomyNames` → `getTaxonomyDefs` —\n * but change extremely rarely: they're created via the admin API or applied\n * from a seed, and there is no edit/delete-def path. Caching them across the\n * isolate lifetime drops the per-render `SELECT * FROM _emdash_taxonomy_defs`\n * to once-per-isolate.\n *\n * Stored on globalThis behind a Symbol key (same pattern as\n * `settings/index.ts`) so the bundler duplicating this module across SSR\n * chunks can't produce two independent caches.\n *\n * When the distributed object cache is configured, it is authoritative and this\n * fallback is bypassed so cross-isolate epoch invalidation cannot be undercut\n * by stale per-isolate data on an object-cache miss.\n *\n * **Isolated databases bypass the cache.** Playground / DO preview requests\n * set `requestContext.dbIsIsolated`; they point at a divergent schema, so we\n * skip both reading and writing the global holder and fall back to the\n * per-request cache (same precedent as `getTaxonomyNames` / byline field defs).\n */\ninterface TaxonomyDefsHolder {\n\tversion: number;\n\t/** locale key (\"*\" for \"all locales\") → { version it was fetched at, promise }. */\n\tcache: Map<string, { version: number; promise: Promise<TaxonomyDef[]> }>;\n}\n\nconst TAXONOMY_DEFS_CACHE_KEY = Symbol.for(\"emdash:taxonomy-defs\");\nconst taxonomyDefsStore = globalThis as Record<symbol, unknown>;\nconst defsHolder: TaxonomyDefsHolder =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see settings/index.ts)\n\t(taxonomyDefsStore[TAXONOMY_DEFS_CACHE_KEY] as TaxonomyDefsHolder | undefined) ??\n\t(() => {\n\t\tconst h: TaxonomyDefsHolder = { version: 0, cache: new Map() };\n\t\ttaxonomyDefsStore[TAXONOMY_DEFS_CACHE_KEY] = h;\n\t\treturn h;\n\t})();\n\n/**\n * Invalidate the isolate-wide taxonomy-definitions cache (and the related\n * loader taxonomy-names cache). Called from every taxonomy-def write path\n * (`handleTaxonomyCreate`, seed application). Other isolates refresh on their\n * next recycle — staleness bounded by isolate lifetime.\n */\nexport function invalidateTaxonomyDefsCache(): void {\n\tdefsHolder.version++;\n\tdefsHolder.cache.clear();\n\tresetTaxonomyNamesCache();\n\tinvalidateTaxonomyObjectCache();\n}\n\n/**\n * Test/internal helper: clear the per-isolate taxonomy-defs cache. Useful for\n * unit tests that insert defs directly and need to force a refetch without\n * going through a write path. Production code should rely on\n * `invalidateTaxonomyDefsCache()`.\n */\nexport function resetTaxonomyDefsCacheForTests(): void {\n\tdefsHolder.version++;\n\tdefsHolder.cache.clear();\n}\n\n/**\n * Fetch taxonomy definitions straight from the database (no caching).\n */\nasync function fetchTaxonomyDefs(locale: string | undefined): Promise<TaxonomyDef[]> {\n\tconst db = await getDb();\n\tlet query = db.selectFrom(\"_emdash_taxonomy_defs\").selectAll();\n\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\tconst rows = await query.execute();\n\treturn rows.map(rowToTaxonomyDef);\n}\n\n/**\n * Resolve taxonomy defs through the isolate fallback cache, bypassing it for\n * isolated databases. The returned promise is cached (not the resolved value)\n * so concurrent cold-isolate readers share one in-flight query; a rejection\n * evicts the entry so the next caller retries.\n */\nfunction loadTaxonomyDefs(localeKey: string, locale: string | undefined): Promise<TaxonomyDef[]> {\n\tif (getRequestContext()?.dbIsIsolated === true) {\n\t\treturn fetchTaxonomyDefs(locale);\n\t}\n\tconst existing = defsHolder.cache.get(localeKey);\n\tif (existing && existing.version === defsHolder.version) {\n\t\treturn existing.promise;\n\t}\n\tconst version = defsHolder.version;\n\tconst promise = fetchTaxonomyDefs(locale).catch((error: unknown) => {\n\t\tconst current = defsHolder.cache.get(localeKey);\n\t\tif (current && current.promise === promise) {\n\t\t\tdefsHolder.cache.delete(localeKey);\n\t\t}\n\t\tthrow error;\n\t});\n\tdefsHolder.cache.set(localeKey, { version, promise });\n\treturn promise;\n}\n\n/**\n * Get every taxonomy definition. Definitions are per-locale (one row per\n * locale inside the same translation_group) — by default we resolve to the\n * active locale.\n *\n * Two-tier cache: per-request via `requestCached` (so a single render that\n * hydrates terms for several collections pays at most one call), then\n * per-isolate via the global holder (so warm renders issue zero queries).\n * The `requestCached` key is unchanged so `getTaxonomyDef`'s peek still hits.\n */\nexport async function getTaxonomyDefs(options: TaxonomyQueryOptions = {}): Promise<TaxonomyDef[]> {\n\tconst locale = resolveLocale(options.locale);\n\tconst localeKey = locale ?? \"*\";\n\treturn requestCached(`taxonomy-defs:${localeKey}`, async () => {\n\t\tif (await isObjectCacheActive()) {\n\t\t\treturn cachedQuery({\n\t\t\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\t\t\tkey: `defs:${localeKey}`,\n\t\t\t\tload: () => fetchTaxonomyDefs(locale),\n\t\t\t});\n\t\t}\n\t\treturn loadTaxonomyDefs(localeKey, locale);\n\t});\n}\n\n/**\n * Get a single taxonomy definition by name. Uses the fallback chain so even\n * if there is no translation for the active locale we still return something.\n *\n * If `getTaxonomyDefs()` has already loaded the full list in this request\n * (which happens during entry-term hydration on every page that renders a\n * collection), search the matching def in memory rather than running a\n * second query against `_emdash_taxonomy_defs`.\n */\nexport async function getTaxonomyDef(\n\tname: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyDef | null> {\n\tconst chain = resolveLocaleChain(options.locale);\n\tconst peekKey = `taxonomy-defs:${resolveLocale(options.locale) ?? \"*\"}`;\n\tconst allDefs = peekRequestCache<TaxonomyDef[]>(peekKey);\n\tif (allDefs) {\n\t\tconst defs = await allDefs;\n\t\tif (chain.length === 0) return defs.find((d) => d.name === name) ?? null;\n\t\tfor (const locale of chain) {\n\t\t\tconst found = defs.find((d) => d.name === name && d.locale === locale);\n\t\t\tif (found) return found;\n\t\t}\n\t\treturn null;\n\t}\n\n\treturn requestCached(`taxonomy-def:${name}:${chain.join(\",\")}`, async () => {\n\t\tconst db = await getDb();\n\n\t\tif (chain.length === 0) {\n\t\t\tconst row = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"name\", \"=\", name)\n\t\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t\t.executeTakeFirst();\n\t\t\treturn row ? rowToTaxonomyDef(row) : null;\n\t\t}\n\n\t\tfor (const locale of chain) {\n\t\t\tconst row = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"name\", \"=\", name)\n\t\t\t\t.where(\"locale\", \"=\", locale)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (row) return rowToTaxonomyDef(row);\n\t\t}\n\t\treturn null;\n\t});\n}\n\n/**\n * Object-cache namespaces for values that embed visible term counts: the\n * taxonomy epoch (term/assignment writes) plus each counted collection's\n * content epoch, so publishing, unpublishing, or trashing an entry\n * invalidates the cached count promptly. A scheduled entry becoming due\n * flips visibility without a write, so that staleness stays bounded by the\n * cache entry's TTL.\n */\nfunction termCountNamespaces(collections: string[]): string[] {\n\treturn [...Array.from(new Set(collections), contentNamespace), CacheNamespace.TAXONOMIES];\n}\n\n/**\n * All terms of a taxonomy in a specific locale (flat for non-hierarchical,\n * tree for hierarchical).\n */\nexport async function getTaxonomyTerms(\n\ttaxonomyName: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\treturn requestCached(`taxonomy-terms:${taxonomyName}:${locale ?? \"*\"}`, async () => {\n\t\tconst def = await getTaxonomyDef(taxonomyName, options);\n\t\tif (!def) return [];\n\t\treturn cachedQuery({\n\t\t\tnamespace: termCountNamespaces(def.collections),\n\t\t\tkey: `terms:${taxonomyName}:${locale ?? \"*\"}`,\n\t\t\tload: () => loadTaxonomyTerms(def, locale),\n\t\t});\n\t});\n}\n\nasync function loadTaxonomyTerms(\n\tdef: TaxonomyDef,\n\tlocale: string | undefined,\n): Promise<TaxonomyTerm[]> {\n\tconst db = await getDb();\n\n\tlet termsQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t.where(\"name\", \"=\", def.name)\n\t\t.orderBy(\"label\", \"asc\");\n\tif (locale !== undefined) termsQuery = termsQuery.where(\"locale\", \"=\", locale);\n\n\t// Counts are keyed by translation_group (what the pivot stores) and are\n\t// locale-independent. Only publicly visible entries are counted (#581);\n\t// the map is request-cached so a term detail rendered on the same page\n\t// reuses it. Independent of the terms query, so run both concurrently.\n\tconst [rows, counts] = await Promise.all([\n\t\ttermsQuery.execute(),\n\t\tgetVisibleTermCounts(def.name, def.collections),\n\t]);\n\n\tconst flatTerms: TaxonomyTermRow[] = rows.map((row) => ({\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tlabel: row.label,\n\t\tparent_id: row.parent_id,\n\t\tdata: row.data,\n\t\tlocale: row.locale,\n\t\ttranslation_group: row.translation_group,\n\t}));\n\n\tif (def.hierarchical) return buildTree(flatTerms, counts);\n\n\treturn flatTerms.map((term) => ({\n\t\tid: term.id,\n\t\tname: term.name,\n\t\tslug: term.slug,\n\t\tlabel: term.label,\n\t\tdescription: term.data ? JSON.parse(term.data).description : undefined,\n\t\tchildren: [],\n\t\tcount: counts.get(term.translation_group ?? term.id) ?? 0,\n\t\tlocale: term.locale,\n\t\ttranslationGroup: term.translation_group,\n\t}));\n}\n\n/**\n * Per-translation-group visible-usage counts for one taxonomy, in a single\n * round-trip (see `fetchVisibleTermCounts`). Counts are locale-independent\n * (the pivot stores translation_group), and the request-cached map is shared\n * by every consumer in the render — the widget (`getTaxonomyTerms`) and the\n * single-term page (`getTerm`) never issue separate count queries.\n */\nfunction getVisibleTermCounts(\n\ttaxonomyName: string,\n\tcollections: string[],\n): Promise<Map<string, number>> {\n\t// The collection scope is part of the key: per-locale rows of the same def\n\t// can drift in their declared collections, and a caller may pass a narrower\n\t// scope. Identical inputs (the widget + term-page hot path) still share one\n\t// entry.\n\tconst scope = [...new Set(collections)].toSorted().join(\",\");\n\treturn requestCached(`taxonomy-term-counts:${taxonomyName}:${scope}`, async () => {\n\t\tconst db = await getDb();\n\t\treturn fetchVisibleTermCounts(db, taxonomyName, collections);\n\t});\n}\n\n/**\n * Get a single term by (taxonomy, slug). Honours the fallback chain — if the\n * slug exists in a fallback locale, we return that row (useful for deep-linking\n * to a term page when the translation is missing).\n */\nexport async function getTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm | null> {\n\tconst chain = resolveLocaleChain(options.locale);\n\t// The def supplies the collections the visible count is scoped to. It is\n\t// resolved before cachedQuery so the entry lives under each collection's\n\t// content namespace — publishing or unpublishing an entry invalidates the\n\t// embedded count (see termCountNamespaces).\n\tconst def = await getTaxonomyDef(taxonomyName, options);\n\tconst collections = def?.collections ?? [];\n\treturn cachedQuery({\n\t\tnamespace: termCountNamespaces(collections),\n\t\tkey: `term:${taxonomyName}:${slug}:${chain.join(\",\")}`,\n\t\tload: () => loadTerm(taxonomyName, slug, chain, collections),\n\t});\n}\n\nasync function loadTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\tchain: string[],\n\tcollections: string[],\n): Promise<TaxonomyTerm | null> {\n\tconst db = await getDb();\n\n\tlet row: Awaited<ReturnType<ReturnType<typeof selectTerm>[\"executeTakeFirst\"]>>;\n\tconst selectTerm = () =>\n\t\tdb\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", taxonomyName)\n\t\t\t.where(\"slug\", \"=\", slug);\n\n\tif (chain.length === 0) {\n\t\trow = await selectTerm().orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t} else {\n\t\trow = undefined;\n\t\tfor (const locale of chain) {\n\t\t\trow = await selectTerm().where(\"locale\", \"=\", locale).executeTakeFirst();\n\t\t\tif (row) break;\n\t\t}\n\t}\n\n\tif (!row) return null;\n\n\tlet childrenQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t// Children store the parent's translation_group in parent_id (not a row\n\t\t// id), so a translated parent still owns its children in its own locale.\n\t\t.where(\"parent_id\", \"=\", row.translation_group ?? row.id)\n\t\t.orderBy(\"label\", \"asc\");\n\tconst termLocale = row.locale;\n\tif (termLocale) childrenQuery = childrenQuery.where(\"locale\", \"=\", termLocale);\n\n\t// The visible-usage counts and children queries both depend only on the\n\t// term row, so run them concurrently to save a round trip on remote\n\t// databases. The counts map is request-cached per taxonomy — on a page\n\t// that also renders the taxonomy widget it's a free Map lookup.\n\tconst [counts, childRows] = await Promise.all([\n\t\tgetVisibleTermCounts(taxonomyName, collections),\n\t\tchildrenQuery.execute(),\n\t]);\n\tconst count = counts.get(row.translation_group ?? row.id) ?? 0;\n\n\tconst children = childRows.map<TaxonomyTerm>((child) => ({\n\t\tid: child.id,\n\t\tname: child.name,\n\t\tslug: child.slug,\n\t\tlabel: child.label,\n\t\tparentId: child.parent_id ?? undefined,\n\t\tchildren: [],\n\t\tlocale: child.locale,\n\t\ttranslationGroup: child.translation_group,\n\t}));\n\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tlabel: row.label,\n\t\tparentId: row.parent_id ?? undefined,\n\t\tdescription: row.data ? JSON.parse(row.data).description : undefined,\n\t\tchildren,\n\t\tcount,\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n/**\n * Terms assigned to a content entry, resolved into the active locale. Terms\n * whose translation_group lacks a row in the requested locale are omitted.\n */\nexport function getEntryTerms(\n\tcollection: string,\n\tentryId: string,\n\ttaxonomyName?: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\t// requestCached short-circuits to values primed by getAllTermsForEntries\n\t// during entry hydration (same key shape). On a warm content-cache hit\n\t// hydration doesn't run, so the inner cachedQuery serves this from KV\n\t// instead of falling through to D1 on every request.\n\treturn requestCached(\n\t\t`terms:${collection}:${entryId}:${taxonomyName ?? \"*\"}:${locale ?? \"*\"}`,\n\t\t() =>\n\t\t\tcachedQuery({\n\t\t\t\tnamespace: [contentNamespace(collection), CacheNamespace.TAXONOMIES],\n\t\t\t\tkey: `entryTerms:${collection}:${entryId}:${taxonomyName ?? \"*\"}:${locale ?? \"*\"}`,\n\t\t\t\tload: async () => {\n\t\t\t\t\tconst db = await getDb();\n\n\t\t\t\t\tlet query = db\n\t\t\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t\t\t.innerJoin(\n\t\t\t\t\t\t\t\"taxonomies\",\n\t\t\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t\t\t\t\"content_taxonomies.taxonomy_id\",\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.selectAll(\"taxonomies\")\n\t\t\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryId);\n\n\t\t\t\t\tif (taxonomyName) query = query.where(\"taxonomies.name\", \"=\", taxonomyName);\n\t\t\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\n\t\t\t\t\tconst rows = await query.execute();\n\t\t\t\t\treturn rows.map<TaxonomyTerm>((row) => ({\n\t\t\t\t\t\tid: row.id,\n\t\t\t\t\t\tname: row.name,\n\t\t\t\t\t\tslug: row.slug,\n\t\t\t\t\t\tlabel: row.label,\n\t\t\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\t\t\tchildren: [],\n\t\t\t\t\t\tlocale: row.locale,\n\t\t\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t\t\t}));\n\t\t\t\t},\n\t\t\t}),\n\t);\n}\n\n/**\n * Terms for multiple entries of one taxonomy, single query.\n */\nexport async function getTermsForEntries(\n\tcollection: string,\n\tentryIds: string[],\n\ttaxonomyName: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Map<string, TaxonomyTerm[]>> {\n\tconst uniqueIds = [...new Set(entryIds)];\n\tif (uniqueIds.length === 0) return new Map();\n\tconst locale = resolveLocale(options.locale);\n\tconst localeKey = locale ?? \"*\";\n\n\t// The query result is a Map, which JSON can't represent — cache it as an\n\t// array of [entryId, terms] pairs and rebuild the Map on read.\n\tconst load = async (): Promise<Array<[string, TaxonomyTerm[]]>> => {\n\t\tconst result = new Map<string, TaxonomyTerm[]>();\n\t\tfor (const id of uniqueIds) result.set(id, []);\n\n\t\t// Entry-term hydration (getAllTermsForEntries -> primeEntryTermsCache)\n\t\t// seeds the per-entry cache under the same key getEntryTerms uses:\n\t\t// `terms:${collection}:${entryId}:${taxonomyName}:${localeKey}`, storing a\n\t\t// TaxonomyTerm[] (including `[]` for entries with no terms). Satisfy those\n\t\t// from cache and run the batched query only for the ids that missed.\n\t\tconst missedIds: string[] = [];\n\t\ttype CacheRead = { id: string; terms: TaxonomyTerm[] } | { id: string; miss: true };\n\t\tconst cacheReads: Array<Promise<CacheRead>> = [];\n\t\tfor (const id of uniqueIds) {\n\t\t\tconst cached = peekRequestCache<TaxonomyTerm[]>(\n\t\t\t\t`terms:${collection}:${id}:${taxonomyName}:${localeKey}`,\n\t\t\t);\n\t\t\tif (cached) {\n\t\t\t\t// A peeked promise can reject (e.g. a sibling getEntryTerms hit a\n\t\t\t\t// missing table). Treat a rejection as a cache miss so the batched\n\t\t\t\t// query path -- and its isMissingTableError guard below -- still runs,\n\t\t\t\t// rather than propagating an uncaught error.\n\t\t\t\tcacheReads.push(\n\t\t\t\t\tcached.then(\n\t\t\t\t\t\t(terms): CacheRead => ({ id, terms }),\n\t\t\t\t\t\t(): CacheRead => ({ id, miss: true }),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmissedIds.push(id);\n\t\t\t}\n\t\t}\n\t\tfor (const read of await Promise.all(cacheReads)) {\n\t\t\tif (\"miss\" in read) {\n\t\t\t\tmissedIds.push(read.id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Return a private copy. The cached array and its term objects are shared\n\t\t\t// with getEntryTerms/getAllTermsForEntries (primeEntryTermsCache stores\n\t\t\t// the same references), so a caller that mutates the result -- sorting in\n\t\t\t// place, pushing into `children` -- must not poison the cache. The\n\t\t\t// pre-cache implementation always returned freshly built arrays.\n\t\t\tresult.set(\n\t\t\t\tread.id,\n\t\t\t\tread.terms.map((t) => ({ ...t, children: [...t.children] })),\n\t\t\t);\n\t\t}\n\n\t\tif (missedIds.length === 0) return [...result.entries()];\n\n\t\tconst db = await getDb();\n\t\tfor (const chunk of chunks(missedIds, SQL_BATCH_SIZE)) {\n\t\t\tlet rows;\n\t\t\ttry {\n\t\t\t\tlet query = db\n\t\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t\t\t.select([\n\t\t\t\t\t\t\"content_taxonomies.entry_id\",\n\t\t\t\t\t\t\"taxonomies.id\",\n\t\t\t\t\t\t\"taxonomies.name\",\n\t\t\t\t\t\t\"taxonomies.slug\",\n\t\t\t\t\t\t\"taxonomies.label\",\n\t\t\t\t\t\t\"taxonomies.parent_id\",\n\t\t\t\t\t\t\"taxonomies.locale\",\n\t\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t\t])\n\t\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t\t.where(\"content_taxonomies.entry_id\", \"in\", chunk)\n\t\t\t\t\t.where(\"taxonomies.name\", \"=\", taxonomyName)\n\t\t\t\t\t// Match the order getAllTermsForEntries (the cache primer) uses, so\n\t\t\t\t\t// cache-hit and DB-miss entries in one result are ordered consistently.\n\t\t\t\t\t.orderBy(\"taxonomies.label\", \"asc\");\n\t\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\t\t\t\trows = await query.execute();\n\t\t\t} catch (error) {\n\t\t\t\tif (isMissingTableError(error)) return [...result.entries()];\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst term: TaxonomyTerm = {\n\t\t\t\t\tid: row.id,\n\t\t\t\t\tname: row.name,\n\t\t\t\t\tslug: row.slug,\n\t\t\t\t\tlabel: row.label,\n\t\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\t\tchildren: [],\n\t\t\t\t\tlocale: row.locale,\n\t\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t\t};\n\t\t\t\tconst terms = result.get(row.entry_id);\n\t\t\t\tif (terms) terms.push(term);\n\t\t\t}\n\t\t}\n\n\t\treturn [...result.entries()];\n\t};\n\n\t// Key on the sorted unique ids. Bound the key length: very large batches\n\t// (rare; they come from collection hydration, already served by the content\n\t// cache) bypass the object cache rather than blow past KV's key limit.\n\tconst idKey = uniqueIds.toSorted().join(\",\");\n\tconst pairs =\n\t\tidKey.length <= 256\n\t\t\t? await cachedQuery({\n\t\t\t\t\tnamespace: [contentNamespace(collection), CacheNamespace.TAXONOMIES],\n\t\t\t\t\tkey: `termsForEntries:${collection}:${taxonomyName}:${locale ?? \"*\"}:${idKey}`,\n\t\t\t\t\tload,\n\t\t\t\t})\n\t\t\t: await load();\n\n\treturn new Map(pairs);\n}\n\n/**\n * Batch-fetch terms for multiple entries across ALL taxonomies in one query.\n * Primes the request-cache for subsequent per-entry calls to `getEntryTerms`.\n */\nexport async function getAllTermsForEntries(\n\tcollection: string,\n\tentryIds: string[],\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Map<string, Record<string, TaxonomyTerm[]>>> {\n\tconst result = new Map<string, Record<string, TaxonomyTerm[]>>();\n\tconst uniqueIds = [...new Set(entryIds)];\n\tfor (const id of uniqueIds) result.set(id, {});\n\tif (uniqueIds.length === 0) return result;\n\n\tconst db = await getDb();\n\tconst locale = resolveLocale(options.locale);\n\tconst applicableTaxonomyNames = await getCollectionTaxonomyNames(collection, { locale });\n\n\tfor (const chunk of chunks(uniqueIds, SQL_BATCH_SIZE)) {\n\t\tlet rows;\n\t\ttry {\n\t\t\tlet query = db\n\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t\t.select([\n\t\t\t\t\t\"content_taxonomies.entry_id\",\n\t\t\t\t\t\"taxonomies.id\",\n\t\t\t\t\t\"taxonomies.name\",\n\t\t\t\t\t\"taxonomies.slug\",\n\t\t\t\t\t\"taxonomies.label\",\n\t\t\t\t\t\"taxonomies.parent_id\",\n\t\t\t\t\t\"taxonomies.locale\",\n\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t])\n\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t.where(\"content_taxonomies.entry_id\", \"in\", chunk)\n\t\t\t\t.orderBy(\"taxonomies.label\", \"asc\");\n\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\t\t\trows = await query.execute();\n\t\t} catch (error) {\n\t\t\tif (isMissingTableError(error)) {\n\t\t\t\tfor (const id of uniqueIds) {\n\t\t\t\t\tprimeEntryTermsCache(collection, id, {}, applicableTaxonomyNames, locale);\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\tfor (const row of rows) {\n\t\t\tconst term: TaxonomyTerm = {\n\t\t\t\tid: row.id,\n\t\t\t\tname: row.name,\n\t\t\t\tslug: row.slug,\n\t\t\t\tlabel: row.label,\n\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\tchildren: [],\n\t\t\t\tlocale: row.locale,\n\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t};\n\t\t\tconst byTaxonomy = result.get(row.entry_id);\n\t\t\tif (!byTaxonomy) continue;\n\t\t\tconst existing = byTaxonomy[row.name];\n\t\t\tif (existing) existing.push(term);\n\t\t\telse byTaxonomy[row.name] = [term];\n\t\t}\n\t}\n\n\tfor (const [entryId, byTaxonomy] of result) {\n\t\tprimeEntryTermsCache(collection, entryId, byTaxonomy, applicableTaxonomyNames, locale);\n\t}\n\n\treturn result;\n}\n\n/**\n * Return the list of taxonomy names applicable to a collection, request-\n * cached so a page render only pays for it once.\n *\n * Returns an empty list when taxonomies haven't been defined yet.\n */\nasync function getCollectionTaxonomyNames(\n\tcollection: string,\n\toptions: TaxonomyQueryOptions,\n): Promise<string[]> {\n\ttry {\n\t\tconst defs = await getTaxonomyDefs(options);\n\t\treturn defs.filter((d) => d.collections.includes(collection)).map((d) => d.name);\n\t} catch (error) {\n\t\tif (isMissingTableError(error)) return [];\n\t\tthrow error;\n\t}\n}\n\n/**\n * Pre-populate the request-cache for every getEntryTerms call-shape that\n * could hit this entry:\n *\n * getEntryTerms(collection, entryId) -> key `terms:C:E:*`\n * getEntryTerms(collection, entryId, \"tag\") -> key `terms:C:E:tag`\n * getEntryTerms(collection, entryId, \"category\") -> key `terms:C:E:category`\n * ...one per taxonomy that applies to this collection\n *\n * Taxonomies with no rows on this entry are seeded with `[]` so legacy\n * callers short-circuit to the cached empty array instead of re-querying.\n */\nfunction primeEntryTermsCache(\n\tcollection: string,\n\tentryId: string,\n\tbyTaxonomy: Record<string, TaxonomyTerm[]>,\n\tapplicableTaxonomyNames: string[],\n\tlocale: string | undefined,\n): void {\n\tconst localeKey = locale ?? \"*\";\n\tfor (const name of applicableTaxonomyNames) {\n\t\tsetRequestCacheEntry(\n\t\t\t`terms:${collection}:${entryId}:${name}:${localeKey}`,\n\t\t\tbyTaxonomy[name] ?? [],\n\t\t);\n\t}\n\tfor (const [name, terms] of Object.entries(byTaxonomy)) {\n\t\tsetRequestCacheEntry(`terms:${collection}:${entryId}:${name}:${localeKey}`, terms);\n\t}\n\tconst allTerms = Object.values(byTaxonomy).flat();\n\tsetRequestCacheEntry(`terms:${collection}:${entryId}:*:${localeKey}`, allTerms);\n}\n\n/**\n * Prime the per-entry request cache from terms that were folded into the\n * content query (query.ts `hydrateEntryTerms` fast path), so subsequent\n * `getEntryTerms` calls in the same render hit the cache instead of issuing an\n * N+1 query. Seeds the wildcard key and one key per taxonomy present on the\n * entry — purely from the folded data, with no DB lookup.\n *\n * Unlike `getAllTermsForEntries`, this deliberately does NOT seed `[]` for\n * taxonomies that apply to the collection but have no rows on the entry: doing\n * so would require a `getTaxonomyDefs` query, adding a round trip to every fold\n * render to serve the rarer `getEntryTerms(id, absentTaxonomy)` case from cache.\n * That call simply falls through to its own cached query. Keeping the key shape\n * here (rather than in query.ts) prevents the two from drifting.\n */\nexport function primeFoldedEntryTerms(\n\tcollection: string,\n\tperEntry: Array<{ entryId: string; byTaxonomy: Record<string, TaxonomyTerm[]> }>,\n\toptions: TaxonomyQueryOptions = {},\n): void {\n\tif (perEntry.length === 0) return;\n\tconst locale = resolveLocale(options.locale);\n\tfor (const { entryId, byTaxonomy } of perEntry) {\n\t\tprimeEntryTermsCache(collection, entryId, byTaxonomy, [], locale);\n\t}\n}\n\n/**\n * Get entries by term. Both the lookup (term slug in the active locale) and\n * the content query respect the active locale.\n */\nexport async function getEntriesByTerm(\n\tcollection: string,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Array<{ id: string; data: Record<string, unknown> }>> {\n\tconst { getEmDashCollection } = await import(\"../query.js\");\n\n\tconst queryOptions: Record<string, unknown> = {\n\t\twhere: { [taxonomyName]: termSlug },\n\t};\n\tif (options.locale !== undefined) queryOptions.locale = options.locale;\n\tconst { entries } = await getEmDashCollection(collection, queryOptions);\n\treturn entries;\n}\n\nfunction rowToTaxonomyDef(row: {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tlabel_singular: string | null;\n\thierarchical: number;\n\tcollections: string | null;\n\tlocale: string;\n\ttranslation_group: string | null;\n}): TaxonomyDef {\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tlabel: row.label,\n\t\tlabelSingular: row.label_singular ?? undefined,\n\t\thierarchical: row.hierarchical === 1,\n\t\tcollections: row.collections ? JSON.parse(row.collections) : [],\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n/**\n * Build tree structure from flat terms\n */\nfunction buildTree(flatTerms: TaxonomyTermRow[], counts: Map<string, number>): TaxonomyTerm[] {\n\t// parent_id holds the parent's translation_group, so link children by it.\n\t// Key by (locale, group): a child's parent lives in the same locale, and an\n\t// unfiltered set mixes locales whose translated siblings share a group —\n\t// keying by group alone would collide and misattach children across locales.\n\tconst byLocaleGroup = new Map<string, TaxonomyTerm>();\n\tconst nodes: TaxonomyTerm[] = [];\n\tconst roots: TaxonomyTerm[] = [];\n\n\tfor (const term of flatTerms) {\n\t\tconst node: TaxonomyTerm = {\n\t\t\tid: term.id,\n\t\t\tname: term.name,\n\t\t\tslug: term.slug,\n\t\t\tlabel: term.label,\n\t\t\tparentId: term.parent_id ?? undefined,\n\t\t\tdescription: term.data ? JSON.parse(term.data).description : undefined,\n\t\t\tchildren: [],\n\t\t\tcount: counts.get(term.translation_group ?? term.id) ?? 0,\n\t\t\tlocale: term.locale,\n\t\t\ttranslationGroup: term.translation_group,\n\t\t};\n\t\tbyLocaleGroup.set(`${term.locale}::${term.translation_group ?? term.id}`, node);\n\t\tnodes.push(node);\n\t}\n\n\tfor (const node of nodes) {\n\t\tconst parent = node.parentId\n\t\t\t? byLocaleGroup.get(`${node.locale}::${node.parentId}`)\n\t\t\t: undefined;\n\t\tif (parent) {\n\t\t\tparent.children.push(node);\n\t\t} else {\n\t\t\troots.push(node);\n\t\t}\n\t}\n\n\treturn roots;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAS,iBACR,IACA,cACA,YACyB;AACzB,QAAO,GAAG;;;eAGI,IAAI,IAAI,MAAM,aAAa,CAAC;0BACjB,WAAW;kFAC6C,aAAa;SACtF,qBAAqB,IAAI,aAAa,IAAI,CAAC;;;;AAKpD,eAAe,UACd,IACA,cACA,aAC+B;CAC/B,MAAM,WAAW,YAAY,KAAK,eAAe,iBAAiB,IAAI,cAAc,WAAW,CAAC;CAEhG,MAAM,SAAS,MAAM,GAAa;;UADpB,IAAI,KAAK,UAAU,GAAG,cAAc,CAGnC;wBACQ,QAAQ,GAAG;CAElC,MAAM,yBAAS,IAAI,KAAqB;AACxC,MAAK,MAAM,OAAO,OAAO,KAAM,QAAO,IAAI,IAAI,aAAa,OAAO,IAAI,MAAM,CAAC;AAC7E,QAAO;;;;;;;;;;;;;;;;;AAkBR,eAAsB,uBACrB,IACA,cACA,aAC+B;CAC/B,MAAM,SAAS,CAAC,GAAG,IAAI,IAAI,YAAY,CAAC;AACxC,MAAK,MAAM,cAAc,OAAQ,oBAAmB,YAAY,kBAAkB;AAClF,KAAI,OAAO,WAAW,EAAG,wBAAO,IAAI,KAAK;AAEzC,KAAI;AACH,SAAO,MAAM,UAAU,IAAI,cAAc,OAAO;UACxC,OAAO;AACf,MAAI,CAAC,oBAAoB,MAAM,CAAE,OAAM;;CAKxC,MAAM,yBAAS,IAAI,KAAqB;AACxC,MAAK,MAAM,cAAc,OACxB,KAAI;AACH,OAAK,MAAM,CAAC,OAAO,UAAU,MAAM,UAAU,IAAI,cAAc,CAAC,WAAW,CAAC,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B,KASV;AACf,QAAO;EACN,IAAI,IAAI;EACR,MAAM,IAAI;EACV,OAAO,IAAI;EACX,eAAe,IAAI,kBAAkB;EACrC,cAAc,IAAI,iBAAiB;EACnC,aAAa,IAAI,cAAc,KAAK,MAAM,IAAI,YAAY,GAAG,EAAE;EAC/D,QAAQ,IAAI;EACZ,kBAAkB,IAAI;EACtB;;;;;AAMF,SAAS,UAAU,WAA8B,QAA6C;CAK7F,MAAM,gCAAgB,IAAI,KAA2B;CACrD,MAAM,QAAwB,EAAE;CAChC,MAAM,QAAwB,EAAE;AAEhC,MAAK,MAAM,QAAQ,WAAW;EAC7B,MAAM,OAAqB;GAC1B,IAAI,KAAK;GACT,MAAM,KAAK;GACX,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,aAAa;GAC5B,aAAa,KAAK,OAAO,KAAK,MAAM,KAAK,KAAK,CAAC,cAAc;GAC7D,UAAU,EAAE;GACZ,OAAO,OAAO,IAAI,KAAK,qBAAqB,KAAK,GAAG,IAAI;GACxD,QAAQ,KAAK;GACb,kBAAkB,KAAK;GACvB;AACD,gBAAc,IAAI,GAAG,KAAK,OAAO,IAAI,KAAK,qBAAqB,KAAK,MAAM,KAAK;AAC/E,QAAM,KAAK,KAAK;;AAGjB,MAAK,MAAM,QAAQ,OAAO;EACzB,MAAM,SAAS,KAAK,WACjB,cAAc,IAAI,GAAG,KAAK,OAAO,IAAI,KAAK,WAAW,GACrD;AACH,MAAI,OACH,QAAO,SAAS,KAAK,KAAK;MAE1B,OAAM,KAAK,KAAK;;AAIlB,QAAO"}
1
+ {"version":3,"file":"taxonomies-HI9fnTdp.mjs","names":[],"sources":["../src/taxonomies/term-counts.ts","../src/taxonomies/index.ts"],"sourcesContent":["/**\n * Shared visible-usage counts for taxonomy terms (issue #581).\n *\n * `content_taxonomies` rows are written for every entry regardless of status\n * and are never pruned on unpublish/trash, so counting the pivot directly\n * inflates counts with drafts and soft-deleted entries. Every user-facing\n * count (public widget, single-term page, admin term list) must instead count\n * only entries that are currently visible on the public site:\n * `status = 'published'` OR (`status = 'scheduled'` AND due), AND\n * `deleted_at IS NULL` — via `buildStatusCondition`, which computes scheduled\n * visibility at query time rather than trusting a literal status value.\n *\n * The public render path is latency-sensitive on D1, so per-collection counts\n * are combined into a single round-trip with UNION ALL — one query per\n * taxonomy, never one per collection.\n */\n\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport { buildStatusCondition } from \"../database/dialect-helpers.js\";\nimport type { Database } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport { isMissingTableError } from \"../utils/db-errors.js\";\n\ninterface CountRow {\n\ttaxonomy_id: string;\n\tcount: number | string | bigint;\n}\n\n/**\n * Per-collection count branch. `taxonomy_id` stores the term's\n * translation_group, so results are keyed by group (locale-independent) and\n * each assignment is counted once no matter how many locales the term has.\n *\n * Scoping to the taxonomy uses `translation_group IN (...)` rather than a\n * join on `taxonomies.id` — the anchor row (id == group) can be deleted while\n * sibling translations survive, and a plain join on `translation_group` would\n * multiply counts by the number of locales.\n */\nfunction collectionBranch(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollection: string,\n): ReturnType<typeof sql> {\n\treturn sql`\n\t\tSELECT ct.taxonomy_id AS taxonomy_id, COUNT(*) AS count\n\t\tFROM content_taxonomies AS ct\n\t\tINNER JOIN ${sql.ref(`ec_${collection}`)} AS e ON e.id = ct.entry_id\n\t\tWHERE ct.collection = ${collection}\n\t\t\tAND ct.taxonomy_id IN (SELECT translation_group FROM taxonomies WHERE name = ${taxonomyName})\n\t\t\tAND ${buildStatusCondition(db, \"published\", \"e\")}\n\t\t\tAND e.deleted_at IS NULL\n\t\tGROUP BY ct.taxonomy_id`;\n}\n\nasync function runCounts(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollections: string[],\n): Promise<Map<string, number>> {\n\tconst branches = collections.map((collection) => collectionBranch(db, taxonomyName, collection));\n\tconst union = sql.join(branches, sql` UNION ALL `);\n\tconst result = await sql<CountRow>`\n\t\tSELECT taxonomy_id, SUM(count) AS count\n\t\tFROM (${union}) AS per_collection\n\t\tGROUP BY taxonomy_id`.execute(db);\n\n\tconst counts = new Map<string, number>();\n\tfor (const row of result.rows) counts.set(row.taxonomy_id, Number(row.count));\n\treturn counts;\n}\n\n/**\n * Count publicly-visible term assignments for one taxonomy, keyed by the\n * term's translation_group (what `content_taxonomies.taxonomy_id` stores).\n *\n * Counts are scoped to the taxonomy's declared collections — pass\n * `TaxonomyDef.collections` (`_emdash_taxonomy_defs.collections`). Collections\n * whose `ec_*` table doesn't exist (pre-migration drift, a declared collection\n * that was never created) are skipped, yielding a partial-but-correct count\n * rather than a throw.\n *\n * One database round-trip for the whole taxonomy (UNION ALL across\n * collections). Callers on the public render path should go through the\n * request-cached wrapper in `taxonomies/index.ts` so a page rendering both the\n * widget and a term detail shares one computation.\n */\nexport async function fetchVisibleTermCounts(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollections: string[],\n): Promise<Map<string, number>> {\n\tconst unique = [...new Set(collections)];\n\tfor (const collection of unique) validateIdentifier(collection, \"collection slug\");\n\tif (unique.length === 0) return new Map();\n\n\ttry {\n\t\treturn await runCounts(db, taxonomyName, unique);\n\t} catch (error) {\n\t\tif (!isMissingTableError(error)) throw error;\n\t}\n\n\t// A declared collection has no ec_* table — retry per collection so the\n\t// existing tables still contribute (still scheduled-aware + deleted_at).\n\tconst counts = new Map<string, number>();\n\tfor (const collection of unique) {\n\t\ttry {\n\t\t\tfor (const [group, count] of await runCounts(db, taxonomyName, [collection])) {\n\t\t\t\tcounts.set(group, (counts.get(group) ?? 0) + count);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (!isMissingTableError(error)) throw error;\n\t\t}\n\t}\n\treturn counts;\n}\n","/**\n * Runtime API for taxonomies.\n *\n * All helpers are locale-aware. When a locale is not passed explicitly we fall\n * back to the request context or the configured `defaultLocale` (see\n * `i18n/resolve.ts`).\n *\n * Because `content_taxonomies.taxonomy_id` stores the translation_group (not a\n * specific term id), the joins here are `taxonomies.translation_group =\n * content_taxonomies.taxonomy_id` + filter by `taxonomies.locale`, which picks\n * the right per-locale term.\n */\n\nimport { resolveLocale, resolveLocaleChain } from \"../i18n/resolve.js\";\nimport { getDb, resetTaxonomyNamesCache } from \"../loader.js\";\nimport {\n\tcachedQuery,\n\tCacheNamespace,\n\tcontentNamespace,\n\tinvalidateTaxonomyObjectCache,\n\tisObjectCacheActive,\n} from \"../object-cache/index.js\";\nimport { peekRequestCache, requestCached, setRequestCacheEntry } from \"../request-cache.js\";\nimport { getRequestContext } from \"../request-context.js\";\nimport { chunks, SQL_BATCH_SIZE } from \"../utils/chunks.js\";\nimport { isMissingTableError } from \"../utils/db-errors.js\";\nimport { fetchVisibleTermCounts } from \"./term-counts.js\";\nimport type { TaxonomyDef, TaxonomyTerm, TaxonomyTermRow } from \"./types.js\";\n\nexport interface TaxonomyQueryOptions {\n\tlocale?: string;\n}\n\n/** Invalidate cached taxonomy term data and any content that hydrates terms. */\nexport function invalidateTermCache(): void {\n\tinvalidateTaxonomyObjectCache();\n}\n\n/**\n * Worker-isolate cache for taxonomy definitions, keyed by resolved locale.\n *\n * Taxonomy *definitions* (the \"category\"/\"tag\" taxonomies themselves, not\n * their terms) are read on every public render that hydrates entry terms —\n * `getAllTermsForEntries` → `getCollectionTaxonomyNames` → `getTaxonomyDefs` —\n * but change extremely rarely: they're created via the admin API or applied\n * from a seed, and there is no edit/delete-def path. Caching them across the\n * isolate lifetime drops the per-render `SELECT * FROM _emdash_taxonomy_defs`\n * to once-per-isolate.\n *\n * Stored on globalThis behind a Symbol key (same pattern as\n * `settings/index.ts`) so the bundler duplicating this module across SSR\n * chunks can't produce two independent caches.\n *\n * When the distributed object cache is configured, it is authoritative and this\n * fallback is bypassed so cross-isolate epoch invalidation cannot be undercut\n * by stale per-isolate data on an object-cache miss.\n *\n * **Isolated databases bypass the cache.** Playground / DO preview requests\n * set `requestContext.dbIsIsolated`; they point at a divergent schema, so we\n * skip both reading and writing the global holder and fall back to the\n * per-request cache (same precedent as `getTaxonomyNames` / byline field defs).\n */\ninterface TaxonomyDefsHolder {\n\tversion: number;\n\t/** locale key (\"*\" for \"all locales\") → { version it was fetched at, promise }. */\n\tcache: Map<string, { version: number; promise: Promise<TaxonomyDef[]> }>;\n}\n\nconst TAXONOMY_DEFS_CACHE_KEY = Symbol.for(\"emdash:taxonomy-defs\");\nconst taxonomyDefsStore = globalThis as Record<symbol, unknown>;\nconst defsHolder: TaxonomyDefsHolder =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see settings/index.ts)\n\t(taxonomyDefsStore[TAXONOMY_DEFS_CACHE_KEY] as TaxonomyDefsHolder | undefined) ??\n\t(() => {\n\t\tconst h: TaxonomyDefsHolder = { version: 0, cache: new Map() };\n\t\ttaxonomyDefsStore[TAXONOMY_DEFS_CACHE_KEY] = h;\n\t\treturn h;\n\t})();\n\n/**\n * Invalidate the isolate-wide taxonomy-definitions cache (and the related\n * loader taxonomy-names cache). Called from every taxonomy-def write path\n * (`handleTaxonomyCreate`, seed application). Other isolates refresh on their\n * next recycle — staleness bounded by isolate lifetime.\n */\nexport function invalidateTaxonomyDefsCache(): void {\n\tdefsHolder.version++;\n\tdefsHolder.cache.clear();\n\tresetTaxonomyNamesCache();\n\tinvalidateTaxonomyObjectCache();\n}\n\n/**\n * Test/internal helper: clear the per-isolate taxonomy-defs cache. Useful for\n * unit tests that insert defs directly and need to force a refetch without\n * going through a write path. Production code should rely on\n * `invalidateTaxonomyDefsCache()`.\n */\nexport function resetTaxonomyDefsCacheForTests(): void {\n\tdefsHolder.version++;\n\tdefsHolder.cache.clear();\n}\n\n/**\n * Fetch taxonomy definitions straight from the database (no caching).\n */\nasync function fetchTaxonomyDefs(locale: string | undefined): Promise<TaxonomyDef[]> {\n\tconst db = await getDb();\n\tlet query = db.selectFrom(\"_emdash_taxonomy_defs\").selectAll();\n\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\tconst rows = await query.execute();\n\treturn rows.map(rowToTaxonomyDef);\n}\n\n/**\n * Resolve taxonomy defs through the isolate fallback cache, bypassing it for\n * isolated databases. The returned promise is cached (not the resolved value)\n * so concurrent cold-isolate readers share one in-flight query; a rejection\n * evicts the entry so the next caller retries.\n */\nfunction loadTaxonomyDefs(localeKey: string, locale: string | undefined): Promise<TaxonomyDef[]> {\n\tif (getRequestContext()?.dbIsIsolated === true) {\n\t\treturn fetchTaxonomyDefs(locale);\n\t}\n\tconst existing = defsHolder.cache.get(localeKey);\n\tif (existing && existing.version === defsHolder.version) {\n\t\treturn existing.promise;\n\t}\n\tconst version = defsHolder.version;\n\tconst promise = fetchTaxonomyDefs(locale).catch((error: unknown) => {\n\t\tconst current = defsHolder.cache.get(localeKey);\n\t\tif (current && current.promise === promise) {\n\t\t\tdefsHolder.cache.delete(localeKey);\n\t\t}\n\t\tthrow error;\n\t});\n\tdefsHolder.cache.set(localeKey, { version, promise });\n\treturn promise;\n}\n\n/**\n * Get every taxonomy definition. Definitions are per-locale (one row per\n * locale inside the same translation_group) — by default we resolve to the\n * active locale.\n *\n * Two-tier cache: per-request via `requestCached` (so a single render that\n * hydrates terms for several collections pays at most one call), then\n * per-isolate via the global holder (so warm renders issue zero queries).\n * The `requestCached` key is unchanged so `getTaxonomyDef`'s peek still hits.\n */\nexport async function getTaxonomyDefs(options: TaxonomyQueryOptions = {}): Promise<TaxonomyDef[]> {\n\tconst locale = resolveLocale(options.locale);\n\tconst localeKey = locale ?? \"*\";\n\treturn requestCached(`taxonomy-defs:${localeKey}`, async () => {\n\t\tif (await isObjectCacheActive()) {\n\t\t\treturn cachedQuery({\n\t\t\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\t\t\tkey: `defs:${localeKey}`,\n\t\t\t\tload: () => fetchTaxonomyDefs(locale),\n\t\t\t});\n\t\t}\n\t\treturn loadTaxonomyDefs(localeKey, locale);\n\t});\n}\n\n/**\n * Get a single taxonomy definition by name. Uses the fallback chain so even\n * if there is no translation for the active locale we still return something.\n *\n * If `getTaxonomyDefs()` has already loaded the full list in this request\n * (which happens during entry-term hydration on every page that renders a\n * collection), search the matching def in memory rather than running a\n * second query against `_emdash_taxonomy_defs`.\n */\nexport async function getTaxonomyDef(\n\tname: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyDef | null> {\n\tconst chain = resolveLocaleChain(options.locale);\n\tconst peekKey = `taxonomy-defs:${resolveLocale(options.locale) ?? \"*\"}`;\n\tconst allDefs = peekRequestCache<TaxonomyDef[]>(peekKey);\n\tif (allDefs) {\n\t\tconst defs = await allDefs;\n\t\tif (chain.length === 0) return defs.find((d) => d.name === name) ?? null;\n\t\tfor (const locale of chain) {\n\t\t\tconst found = defs.find((d) => d.name === name && d.locale === locale);\n\t\t\tif (found) return found;\n\t\t}\n\t\treturn null;\n\t}\n\n\treturn requestCached(`taxonomy-def:${name}:${chain.join(\",\")}`, async () => {\n\t\tconst db = await getDb();\n\n\t\tif (chain.length === 0) {\n\t\t\tconst row = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"name\", \"=\", name)\n\t\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t\t.executeTakeFirst();\n\t\t\treturn row ? rowToTaxonomyDef(row) : null;\n\t\t}\n\n\t\tfor (const locale of chain) {\n\t\t\tconst row = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"name\", \"=\", name)\n\t\t\t\t.where(\"locale\", \"=\", locale)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (row) return rowToTaxonomyDef(row);\n\t\t}\n\t\treturn null;\n\t});\n}\n\n/**\n * Object-cache namespaces for values that embed visible term counts: the\n * taxonomy epoch (term/assignment writes) plus each counted collection's\n * content epoch, so publishing, unpublishing, or trashing an entry\n * invalidates the cached count promptly. A scheduled entry becoming due\n * flips visibility without a write, so that staleness stays bounded by the\n * cache entry's TTL.\n */\nfunction termCountNamespaces(collections: string[]): string[] {\n\treturn [...Array.from(new Set(collections), contentNamespace), CacheNamespace.TAXONOMIES];\n}\n\n/**\n * All terms of a taxonomy in a specific locale (flat for non-hierarchical,\n * tree for hierarchical).\n */\nexport async function getTaxonomyTerms(\n\ttaxonomyName: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\treturn requestCached(`taxonomy-terms:${taxonomyName}:${locale ?? \"*\"}`, async () => {\n\t\tconst def = await getTaxonomyDef(taxonomyName, options);\n\t\tif (!def) return [];\n\t\treturn cachedQuery({\n\t\t\tnamespace: termCountNamespaces(def.collections),\n\t\t\tkey: `terms:${taxonomyName}:${locale ?? \"*\"}`,\n\t\t\tload: () => loadTaxonomyTerms(def, locale),\n\t\t});\n\t});\n}\n\nasync function loadTaxonomyTerms(\n\tdef: TaxonomyDef,\n\tlocale: string | undefined,\n): Promise<TaxonomyTerm[]> {\n\tconst db = await getDb();\n\n\tlet termsQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t.where(\"name\", \"=\", def.name)\n\t\t.orderBy(\"label\", \"asc\");\n\tif (locale !== undefined) termsQuery = termsQuery.where(\"locale\", \"=\", locale);\n\n\t// Counts are keyed by translation_group (what the pivot stores) and are\n\t// locale-independent. Only publicly visible entries are counted (#581);\n\t// the map is request-cached so a term detail rendered on the same page\n\t// reuses it. Independent of the terms query, so run both concurrently.\n\tconst [rows, counts] = await Promise.all([\n\t\ttermsQuery.execute(),\n\t\tgetVisibleTermCounts(def.name, def.collections),\n\t]);\n\n\tconst flatTerms: TaxonomyTermRow[] = rows.map((row) => ({\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tlabel: row.label,\n\t\tparent_id: row.parent_id,\n\t\tdata: row.data,\n\t\tlocale: row.locale,\n\t\ttranslation_group: row.translation_group,\n\t}));\n\n\tif (def.hierarchical) return buildTree(flatTerms, counts);\n\n\treturn flatTerms.map((term) => ({\n\t\tid: term.id,\n\t\tname: term.name,\n\t\tslug: term.slug,\n\t\tlabel: term.label,\n\t\tdescription: term.data ? JSON.parse(term.data).description : undefined,\n\t\tchildren: [],\n\t\tcount: counts.get(term.translation_group ?? term.id) ?? 0,\n\t\tlocale: term.locale,\n\t\ttranslationGroup: term.translation_group,\n\t}));\n}\n\n/**\n * Per-translation-group visible-usage counts for one taxonomy, in a single\n * round-trip (see `fetchVisibleTermCounts`). Counts are locale-independent\n * (the pivot stores translation_group), and the request-cached map is shared\n * by every consumer in the render — the widget (`getTaxonomyTerms`) and the\n * single-term page (`getTerm`) never issue separate count queries.\n */\nfunction getVisibleTermCounts(\n\ttaxonomyName: string,\n\tcollections: string[],\n): Promise<Map<string, number>> {\n\t// The collection scope is part of the key: per-locale rows of the same def\n\t// can drift in their declared collections, and a caller may pass a narrower\n\t// scope. Identical inputs (the widget + term-page hot path) still share one\n\t// entry.\n\tconst scope = [...new Set(collections)].toSorted().join(\",\");\n\treturn requestCached(`taxonomy-term-counts:${taxonomyName}:${scope}`, async () => {\n\t\tconst db = await getDb();\n\t\treturn fetchVisibleTermCounts(db, taxonomyName, collections);\n\t});\n}\n\n/**\n * Get a single term by (taxonomy, slug). Honours the fallback chain — if the\n * slug exists in a fallback locale, we return that row (useful for deep-linking\n * to a term page when the translation is missing).\n */\nexport async function getTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm | null> {\n\tconst chain = resolveLocaleChain(options.locale);\n\t// The def supplies the collections the visible count is scoped to. It is\n\t// resolved before cachedQuery so the entry lives under each collection's\n\t// content namespace — publishing or unpublishing an entry invalidates the\n\t// embedded count (see termCountNamespaces).\n\tconst def = await getTaxonomyDef(taxonomyName, options);\n\tconst collections = def?.collections ?? [];\n\treturn cachedQuery({\n\t\tnamespace: termCountNamespaces(collections),\n\t\tkey: `term:${taxonomyName}:${slug}:${chain.join(\",\")}`,\n\t\tload: () => loadTerm(taxonomyName, slug, chain, collections),\n\t});\n}\n\nasync function loadTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\tchain: string[],\n\tcollections: string[],\n): Promise<TaxonomyTerm | null> {\n\tconst db = await getDb();\n\n\tlet row: Awaited<ReturnType<ReturnType<typeof selectTerm>[\"executeTakeFirst\"]>>;\n\tconst selectTerm = () =>\n\t\tdb\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", taxonomyName)\n\t\t\t.where(\"slug\", \"=\", slug);\n\n\tif (chain.length === 0) {\n\t\trow = await selectTerm().orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t} else {\n\t\trow = undefined;\n\t\tfor (const locale of chain) {\n\t\t\trow = await selectTerm().where(\"locale\", \"=\", locale).executeTakeFirst();\n\t\t\tif (row) break;\n\t\t}\n\t}\n\n\tif (!row) return null;\n\n\tlet childrenQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t// Children store the parent's translation_group in parent_id (not a row\n\t\t// id), so a translated parent still owns its children in its own locale.\n\t\t.where(\"parent_id\", \"=\", row.translation_group ?? row.id)\n\t\t.orderBy(\"label\", \"asc\");\n\tconst termLocale = row.locale;\n\tif (termLocale) childrenQuery = childrenQuery.where(\"locale\", \"=\", termLocale);\n\n\t// The visible-usage counts and children queries both depend only on the\n\t// term row, so run them concurrently to save a round trip on remote\n\t// databases. The counts map is request-cached per taxonomy — on a page\n\t// that also renders the taxonomy widget it's a free Map lookup.\n\tconst [counts, childRows] = await Promise.all([\n\t\tgetVisibleTermCounts(taxonomyName, collections),\n\t\tchildrenQuery.execute(),\n\t]);\n\tconst count = counts.get(row.translation_group ?? row.id) ?? 0;\n\n\tconst children = childRows.map<TaxonomyTerm>((child) => ({\n\t\tid: child.id,\n\t\tname: child.name,\n\t\tslug: child.slug,\n\t\tlabel: child.label,\n\t\tparentId: child.parent_id ?? undefined,\n\t\tchildren: [],\n\t\tlocale: child.locale,\n\t\ttranslationGroup: child.translation_group,\n\t}));\n\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tlabel: row.label,\n\t\tparentId: row.parent_id ?? undefined,\n\t\tdescription: row.data ? JSON.parse(row.data).description : undefined,\n\t\tchildren,\n\t\tcount,\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n/**\n * Terms assigned to a content entry, resolved into the active locale. Terms\n * whose translation_group lacks a row in the requested locale are omitted.\n */\nexport function getEntryTerms(\n\tcollection: string,\n\tentryId: string,\n\ttaxonomyName?: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\t// requestCached short-circuits to values primed by getAllTermsForEntries\n\t// during entry hydration (same key shape). On a warm content-cache hit\n\t// hydration doesn't run, so the inner cachedQuery serves this from KV\n\t// instead of falling through to D1 on every request.\n\treturn requestCached(\n\t\t`terms:${collection}:${entryId}:${taxonomyName ?? \"*\"}:${locale ?? \"*\"}`,\n\t\t() =>\n\t\t\tcachedQuery({\n\t\t\t\tnamespace: [contentNamespace(collection), CacheNamespace.TAXONOMIES],\n\t\t\t\tkey: `entryTerms:${collection}:${entryId}:${taxonomyName ?? \"*\"}:${locale ?? \"*\"}`,\n\t\t\t\tload: async () => {\n\t\t\t\t\tconst db = await getDb();\n\n\t\t\t\t\tlet query = db\n\t\t\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t\t\t.innerJoin(\n\t\t\t\t\t\t\t\"taxonomies\",\n\t\t\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t\t\t\t\"content_taxonomies.taxonomy_id\",\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.selectAll(\"taxonomies\")\n\t\t\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryId);\n\n\t\t\t\t\tif (taxonomyName) query = query.where(\"taxonomies.name\", \"=\", taxonomyName);\n\t\t\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\n\t\t\t\t\tconst rows = await query.execute();\n\t\t\t\t\treturn rows.map<TaxonomyTerm>((row) => ({\n\t\t\t\t\t\tid: row.id,\n\t\t\t\t\t\tname: row.name,\n\t\t\t\t\t\tslug: row.slug,\n\t\t\t\t\t\tlabel: row.label,\n\t\t\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\t\t\tchildren: [],\n\t\t\t\t\t\tlocale: row.locale,\n\t\t\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t\t\t}));\n\t\t\t\t},\n\t\t\t}),\n\t);\n}\n\n/**\n * Terms for multiple entries of one taxonomy, single query.\n */\nexport async function getTermsForEntries(\n\tcollection: string,\n\tentryIds: string[],\n\ttaxonomyName: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Map<string, TaxonomyTerm[]>> {\n\tconst uniqueIds = [...new Set(entryIds)];\n\tif (uniqueIds.length === 0) return new Map();\n\tconst locale = resolveLocale(options.locale);\n\tconst localeKey = locale ?? \"*\";\n\n\t// The query result is a Map, which JSON can't represent — cache it as an\n\t// array of [entryId, terms] pairs and rebuild the Map on read.\n\tconst load = async (): Promise<Array<[string, TaxonomyTerm[]]>> => {\n\t\tconst result = new Map<string, TaxonomyTerm[]>();\n\t\tfor (const id of uniqueIds) result.set(id, []);\n\n\t\t// Entry-term hydration (getAllTermsForEntries -> primeEntryTermsCache)\n\t\t// seeds the per-entry cache under the same key getEntryTerms uses:\n\t\t// `terms:${collection}:${entryId}:${taxonomyName}:${localeKey}`, storing a\n\t\t// TaxonomyTerm[] (including `[]` for entries with no terms). Satisfy those\n\t\t// from cache and run the batched query only for the ids that missed.\n\t\tconst missedIds: string[] = [];\n\t\ttype CacheRead = { id: string; terms: TaxonomyTerm[] } | { id: string; miss: true };\n\t\tconst cacheReads: Array<Promise<CacheRead>> = [];\n\t\tfor (const id of uniqueIds) {\n\t\t\tconst cached = peekRequestCache<TaxonomyTerm[]>(\n\t\t\t\t`terms:${collection}:${id}:${taxonomyName}:${localeKey}`,\n\t\t\t);\n\t\t\tif (cached) {\n\t\t\t\t// A peeked promise can reject (e.g. a sibling getEntryTerms hit a\n\t\t\t\t// missing table). Treat a rejection as a cache miss so the batched\n\t\t\t\t// query path -- and its isMissingTableError guard below -- still runs,\n\t\t\t\t// rather than propagating an uncaught error.\n\t\t\t\tcacheReads.push(\n\t\t\t\t\tcached.then(\n\t\t\t\t\t\t(terms): CacheRead => ({ id, terms }),\n\t\t\t\t\t\t(): CacheRead => ({ id, miss: true }),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmissedIds.push(id);\n\t\t\t}\n\t\t}\n\t\tfor (const read of await Promise.all(cacheReads)) {\n\t\t\tif (\"miss\" in read) {\n\t\t\t\tmissedIds.push(read.id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Return a private copy. The cached array and its term objects are shared\n\t\t\t// with getEntryTerms/getAllTermsForEntries (primeEntryTermsCache stores\n\t\t\t// the same references), so a caller that mutates the result -- sorting in\n\t\t\t// place, pushing into `children` -- must not poison the cache. The\n\t\t\t// pre-cache implementation always returned freshly built arrays.\n\t\t\tresult.set(\n\t\t\t\tread.id,\n\t\t\t\tread.terms.map((t) => ({ ...t, children: [...t.children] })),\n\t\t\t);\n\t\t}\n\n\t\tif (missedIds.length === 0) return [...result.entries()];\n\n\t\tconst db = await getDb();\n\t\tfor (const chunk of chunks(missedIds, SQL_BATCH_SIZE)) {\n\t\t\tlet rows;\n\t\t\ttry {\n\t\t\t\tlet query = db\n\t\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t\t\t.select([\n\t\t\t\t\t\t\"content_taxonomies.entry_id\",\n\t\t\t\t\t\t\"taxonomies.id\",\n\t\t\t\t\t\t\"taxonomies.name\",\n\t\t\t\t\t\t\"taxonomies.slug\",\n\t\t\t\t\t\t\"taxonomies.label\",\n\t\t\t\t\t\t\"taxonomies.parent_id\",\n\t\t\t\t\t\t\"taxonomies.locale\",\n\t\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t\t])\n\t\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t\t.where(\"content_taxonomies.entry_id\", \"in\", chunk)\n\t\t\t\t\t.where(\"taxonomies.name\", \"=\", taxonomyName)\n\t\t\t\t\t// Match the order getAllTermsForEntries (the cache primer) uses, so\n\t\t\t\t\t// cache-hit and DB-miss entries in one result are ordered consistently.\n\t\t\t\t\t.orderBy(\"taxonomies.label\", \"asc\");\n\t\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\t\t\t\trows = await query.execute();\n\t\t\t} catch (error) {\n\t\t\t\tif (isMissingTableError(error)) return [...result.entries()];\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst term: TaxonomyTerm = {\n\t\t\t\t\tid: row.id,\n\t\t\t\t\tname: row.name,\n\t\t\t\t\tslug: row.slug,\n\t\t\t\t\tlabel: row.label,\n\t\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\t\tchildren: [],\n\t\t\t\t\tlocale: row.locale,\n\t\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t\t};\n\t\t\t\tconst terms = result.get(row.entry_id);\n\t\t\t\tif (terms) terms.push(term);\n\t\t\t}\n\t\t}\n\n\t\treturn [...result.entries()];\n\t};\n\n\t// Key on the sorted unique ids. Bound the key length: very large batches\n\t// (rare; they come from collection hydration, already served by the content\n\t// cache) bypass the object cache rather than blow past KV's key limit.\n\tconst idKey = uniqueIds.toSorted().join(\",\");\n\tconst pairs =\n\t\tidKey.length <= 256\n\t\t\t? await cachedQuery({\n\t\t\t\t\tnamespace: [contentNamespace(collection), CacheNamespace.TAXONOMIES],\n\t\t\t\t\tkey: `termsForEntries:${collection}:${taxonomyName}:${locale ?? \"*\"}:${idKey}`,\n\t\t\t\t\tload,\n\t\t\t\t})\n\t\t\t: await load();\n\n\treturn new Map(pairs);\n}\n\n/**\n * Batch-fetch terms for multiple entries across ALL taxonomies in one query.\n * Primes the request-cache for subsequent per-entry calls to `getEntryTerms`.\n */\nexport async function getAllTermsForEntries(\n\tcollection: string,\n\tentryIds: string[],\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Map<string, Record<string, TaxonomyTerm[]>>> {\n\tconst result = new Map<string, Record<string, TaxonomyTerm[]>>();\n\tconst uniqueIds = [...new Set(entryIds)];\n\tfor (const id of uniqueIds) result.set(id, {});\n\tif (uniqueIds.length === 0) return result;\n\n\tconst db = await getDb();\n\tconst locale = resolveLocale(options.locale);\n\tconst applicableTaxonomyNames = await getCollectionTaxonomyNames(collection, { locale });\n\n\tfor (const chunk of chunks(uniqueIds, SQL_BATCH_SIZE)) {\n\t\tlet rows;\n\t\ttry {\n\t\t\tlet query = db\n\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t\t.select([\n\t\t\t\t\t\"content_taxonomies.entry_id\",\n\t\t\t\t\t\"taxonomies.id\",\n\t\t\t\t\t\"taxonomies.name\",\n\t\t\t\t\t\"taxonomies.slug\",\n\t\t\t\t\t\"taxonomies.label\",\n\t\t\t\t\t\"taxonomies.parent_id\",\n\t\t\t\t\t\"taxonomies.locale\",\n\t\t\t\t\t\"taxonomies.translation_group\",\n\t\t\t\t])\n\t\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t\t.where(\"content_taxonomies.entry_id\", \"in\", chunk)\n\t\t\t\t.orderBy(\"taxonomies.label\", \"asc\");\n\t\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\t\t\trows = await query.execute();\n\t\t} catch (error) {\n\t\t\tif (isMissingTableError(error)) {\n\t\t\t\tfor (const id of uniqueIds) {\n\t\t\t\t\tprimeEntryTermsCache(collection, id, {}, applicableTaxonomyNames, locale);\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\tfor (const row of rows) {\n\t\t\tconst term: TaxonomyTerm = {\n\t\t\t\tid: row.id,\n\t\t\t\tname: row.name,\n\t\t\t\tslug: row.slug,\n\t\t\t\tlabel: row.label,\n\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\tchildren: [],\n\t\t\t\tlocale: row.locale,\n\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t};\n\t\t\tconst byTaxonomy = result.get(row.entry_id);\n\t\t\tif (!byTaxonomy) continue;\n\t\t\tconst existing = byTaxonomy[row.name];\n\t\t\tif (existing) existing.push(term);\n\t\t\telse byTaxonomy[row.name] = [term];\n\t\t}\n\t}\n\n\tfor (const [entryId, byTaxonomy] of result) {\n\t\tprimeEntryTermsCache(collection, entryId, byTaxonomy, applicableTaxonomyNames, locale);\n\t}\n\n\treturn result;\n}\n\n/**\n * Return the list of taxonomy names applicable to a collection, request-\n * cached so a page render only pays for it once.\n *\n * Returns an empty list when taxonomies haven't been defined yet.\n */\nasync function getCollectionTaxonomyNames(\n\tcollection: string,\n\toptions: TaxonomyQueryOptions,\n): Promise<string[]> {\n\ttry {\n\t\tconst defs = await getTaxonomyDefs(options);\n\t\treturn defs.filter((d) => d.collections.includes(collection)).map((d) => d.name);\n\t} catch (error) {\n\t\tif (isMissingTableError(error)) return [];\n\t\tthrow error;\n\t}\n}\n\n/**\n * Pre-populate the request-cache for every getEntryTerms call-shape that\n * could hit this entry:\n *\n * getEntryTerms(collection, entryId) -> key `terms:C:E:*`\n * getEntryTerms(collection, entryId, \"tag\") -> key `terms:C:E:tag`\n * getEntryTerms(collection, entryId, \"category\") -> key `terms:C:E:category`\n * ...one per taxonomy that applies to this collection\n *\n * Taxonomies with no rows on this entry are seeded with `[]` so legacy\n * callers short-circuit to the cached empty array instead of re-querying.\n */\nfunction primeEntryTermsCache(\n\tcollection: string,\n\tentryId: string,\n\tbyTaxonomy: Record<string, TaxonomyTerm[]>,\n\tapplicableTaxonomyNames: string[],\n\tlocale: string | undefined,\n): void {\n\tconst localeKey = locale ?? \"*\";\n\tfor (const name of applicableTaxonomyNames) {\n\t\tsetRequestCacheEntry(\n\t\t\t`terms:${collection}:${entryId}:${name}:${localeKey}`,\n\t\t\tbyTaxonomy[name] ?? [],\n\t\t);\n\t}\n\tfor (const [name, terms] of Object.entries(byTaxonomy)) {\n\t\tsetRequestCacheEntry(`terms:${collection}:${entryId}:${name}:${localeKey}`, terms);\n\t}\n\tconst allTerms = Object.values(byTaxonomy).flat();\n\tsetRequestCacheEntry(`terms:${collection}:${entryId}:*:${localeKey}`, allTerms);\n}\n\n/**\n * Prime the per-entry request cache from terms that were folded into the\n * content query (query.ts `hydrateEntryTerms` fast path), so subsequent\n * `getEntryTerms` calls in the same render hit the cache instead of issuing an\n * N+1 query. Seeds the wildcard key and one key per taxonomy present on the\n * entry — purely from the folded data, with no DB lookup.\n *\n * Unlike `getAllTermsForEntries`, this deliberately does NOT seed `[]` for\n * taxonomies that apply to the collection but have no rows on the entry: doing\n * so would require a `getTaxonomyDefs` query, adding a round trip to every fold\n * render to serve the rarer `getEntryTerms(id, absentTaxonomy)` case from cache.\n * That call simply falls through to its own cached query. Keeping the key shape\n * here (rather than in query.ts) prevents the two from drifting.\n */\nexport function primeFoldedEntryTerms(\n\tcollection: string,\n\tperEntry: Array<{ entryId: string; byTaxonomy: Record<string, TaxonomyTerm[]> }>,\n\toptions: TaxonomyQueryOptions = {},\n): void {\n\tif (perEntry.length === 0) return;\n\tconst locale = resolveLocale(options.locale);\n\tfor (const { entryId, byTaxonomy } of perEntry) {\n\t\tprimeEntryTermsCache(collection, entryId, byTaxonomy, [], locale);\n\t}\n}\n\n/**\n * Get entries by term. Both the lookup (term slug in the active locale) and\n * the content query respect the active locale.\n */\nexport async function getEntriesByTerm(\n\tcollection: string,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Array<{ id: string; data: Record<string, unknown> }>> {\n\tconst { getEmDashCollection } = await import(\"../query.js\");\n\n\tconst queryOptions: Record<string, unknown> = {\n\t\twhere: { [taxonomyName]: termSlug },\n\t};\n\tif (options.locale !== undefined) queryOptions.locale = options.locale;\n\tconst { entries } = await getEmDashCollection(collection, queryOptions);\n\treturn entries;\n}\n\nfunction rowToTaxonomyDef(row: {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tlabel_singular: string | null;\n\thierarchical: number;\n\tcollections: string | null;\n\tlocale: string;\n\ttranslation_group: string | null;\n}): TaxonomyDef {\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tlabel: row.label,\n\t\tlabelSingular: row.label_singular ?? undefined,\n\t\thierarchical: row.hierarchical === 1,\n\t\tcollections: row.collections ? JSON.parse(row.collections) : [],\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n/**\n * Build tree structure from flat terms\n */\nfunction buildTree(flatTerms: TaxonomyTermRow[], counts: Map<string, number>): TaxonomyTerm[] {\n\t// parent_id holds the parent's translation_group, so link children by it.\n\t// Key by (locale, group): a child's parent lives in the same locale, and an\n\t// unfiltered set mixes locales whose translated siblings share a group —\n\t// keying by group alone would collide and misattach children across locales.\n\tconst byLocaleGroup = new Map<string, TaxonomyTerm>();\n\tconst nodes: TaxonomyTerm[] = [];\n\tconst roots: TaxonomyTerm[] = [];\n\n\tfor (const term of flatTerms) {\n\t\tconst node: TaxonomyTerm = {\n\t\t\tid: term.id,\n\t\t\tname: term.name,\n\t\t\tslug: term.slug,\n\t\t\tlabel: term.label,\n\t\t\tparentId: term.parent_id ?? undefined,\n\t\t\tdescription: term.data ? JSON.parse(term.data).description : undefined,\n\t\t\tchildren: [],\n\t\t\tcount: counts.get(term.translation_group ?? term.id) ?? 0,\n\t\t\tlocale: term.locale,\n\t\t\ttranslationGroup: term.translation_group,\n\t\t};\n\t\tbyLocaleGroup.set(`${term.locale}::${term.translation_group ?? term.id}`, node);\n\t\tnodes.push(node);\n\t}\n\n\tfor (const node of nodes) {\n\t\tconst parent = node.parentId\n\t\t\t? byLocaleGroup.get(`${node.locale}::${node.parentId}`)\n\t\t\t: undefined;\n\t\tif (parent) {\n\t\t\tparent.children.push(node);\n\t\t} else {\n\t\t\troots.push(node);\n\t\t}\n\t}\n\n\treturn roots;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAS,iBACR,IACA,cACA,YACyB;AACzB,QAAO,GAAG;;;eAGI,IAAI,IAAI,MAAM,aAAa,CAAC;0BACjB,WAAW;kFAC6C,aAAa;SACtF,qBAAqB,IAAI,aAAa,IAAI,CAAC;;;;AAKpD,eAAe,UACd,IACA,cACA,aAC+B;CAC/B,MAAM,WAAW,YAAY,KAAK,eAAe,iBAAiB,IAAI,cAAc,WAAW,CAAC;CAEhG,MAAM,SAAS,MAAM,GAAa;;UADpB,IAAI,KAAK,UAAU,GAAG,cAAc,CAGnC;wBACQ,QAAQ,GAAG;CAElC,MAAM,yBAAS,IAAI,KAAqB;AACxC,MAAK,MAAM,OAAO,OAAO,KAAM,QAAO,IAAI,IAAI,aAAa,OAAO,IAAI,MAAM,CAAC;AAC7E,QAAO;;;;;;;;;;;;;;;;;AAkBR,eAAsB,uBACrB,IACA,cACA,aAC+B;CAC/B,MAAM,SAAS,CAAC,GAAG,IAAI,IAAI,YAAY,CAAC;AACxC,MAAK,MAAM,cAAc,OAAQ,oBAAmB,YAAY,kBAAkB;AAClF,KAAI,OAAO,WAAW,EAAG,wBAAO,IAAI,KAAK;AAEzC,KAAI;AACH,SAAO,MAAM,UAAU,IAAI,cAAc,OAAO;UACxC,OAAO;AACf,MAAI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