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,6 +1,7 @@
1
- import { o as __exportAll } from "./runner-DfnZ5eUr.mjs";
2
- import { t as TaxonomyRepository } from "./taxonomy-DfVooU4W.mjs";
3
- import { f as fetchVisibleTermCounts, l as invalidateTaxonomyDefsCache, u as invalidateTermCache } from "./taxonomies-DjSKBZpq.mjs";
1
+ import { o as __exportAll } from "./runner-BdeLEgad.mjs";
2
+ import { i as resolveConfiguredLocale } from "./config-B6b_BobR.mjs";
3
+ import { t as TaxonomyRepository } from "./taxonomy-0mCI25HN.mjs";
4
+ import { f as fetchVisibleTermCounts, l as invalidateTaxonomyDefsCache, u as invalidateTermCache } from "./taxonomies-HI9fnTdp.mjs";
4
5
  import { ulid } from "ulidx";
5
6
 
6
7
  //#region src/api/handlers/taxonomies.ts
@@ -71,8 +72,9 @@ function rowToDef(row) {
71
72
  */
72
73
  async function handleTaxonomyList(db, options = {}) {
73
74
  try {
75
+ const locale = options.locale ? resolveConfiguredLocale(options.locale) : void 0;
74
76
  let query = db.selectFrom("_emdash_taxonomy_defs").selectAll();
75
- if (options.locale !== void 0) query = query.where("locale", "=", options.locale);
77
+ if (locale !== void 0) query = query.where("locale", "=", locale);
76
78
  const [rows, collectionRows] = await Promise.all([query.execute(), db.selectFrom("_emdash_collections").select("slug").execute()]);
77
79
  const realCollections = new Set(collectionRows.map((r) => r.slug));
78
80
  return {
@@ -100,6 +102,7 @@ async function handleTaxonomyList(db, options = {}) {
100
102
  */
101
103
  async function handleTaxonomyCreate(db, input) {
102
104
  try {
105
+ const locale = input.locale ? resolveConfiguredLocale(input.locale) : void 0;
103
106
  if (!NAME_PATTERN.test(input.name)) return {
104
107
  success: false,
105
108
  error: {
@@ -132,12 +135,12 @@ async function handleTaxonomyCreate(db, input) {
132
135
  };
133
136
  translationGroup = source.translation_group ?? source.id;
134
137
  }
135
- if (input.locale !== void 0) {
136
- if (await db.selectFrom("_emdash_taxonomy_defs").select("id").where("name", "=", input.name).where("locale", "=", input.locale).executeTakeFirst()) return {
138
+ if (locale !== void 0) {
139
+ if (await db.selectFrom("_emdash_taxonomy_defs").select("id").where("name", "=", input.name).where("locale", "=", locale).executeTakeFirst()) return {
137
140
  success: false,
138
141
  error: {
139
142
  code: "CONFLICT",
140
- message: `Taxonomy '${input.name}' already exists in locale '${input.locale}'`
143
+ message: `Taxonomy '${input.name}' already exists in locale '${locale}'`
141
144
  }
142
145
  };
143
146
  }
@@ -149,7 +152,7 @@ async function handleTaxonomyCreate(db, input) {
149
152
  label_singular: input.labelSingular ?? null,
150
153
  hierarchical: input.hierarchical ? 1 : 0,
151
154
  collections: JSON.stringify(collections),
152
- ...input.locale !== void 0 ? { locale: input.locale } : {},
155
+ ...locale !== void 0 ? { locale } : {},
153
156
  translation_group: translationGroup ?? id
154
157
  }).execute();
155
158
  invalidateTaxonomyDefsCache();
@@ -181,7 +184,9 @@ async function handleTermList(db, taxonomyName, options = {}) {
181
184
  try {
182
185
  const lookup = await requireTaxonomyDef(db, taxonomyName);
183
186
  if (!lookup.success) return lookup;
184
- const terms = await new TaxonomyRepository(db).findByName(taxonomyName, { locale: options.locale });
187
+ const repo = new TaxonomyRepository(db);
188
+ const locale = options.locale ? resolveConfiguredLocale(options.locale) : void 0;
189
+ const terms = await repo.findByName(taxonomyName, { locale });
185
190
  const countsByGroup = await fetchVisibleTermCounts(db, taxonomyName, defCollections(lookup.def));
186
191
  const termData = terms.map((term) => ({
187
192
  id: term.id,
@@ -269,15 +274,16 @@ async function validateParentTerm(repo, taxonomyName, termId, parentId, selfGrou
269
274
  */
270
275
  async function handleTermCreate(db, taxonomyName, input) {
271
276
  try {
277
+ const locale = input.locale ? resolveConfiguredLocale(input.locale) : void 0;
272
278
  const lookup = await requireTaxonomyDef(db, taxonomyName);
273
279
  if (!lookup.success) return lookup;
274
280
  const repo = new TaxonomyRepository(db);
275
281
  const parentId = input.parentId === "" || input.parentId === void 0 ? void 0 : input.parentId;
276
- if (await repo.findBySlug(taxonomyName, input.slug, input.locale)) return {
282
+ if (await repo.findBySlug(taxonomyName, input.slug, locale)) return {
277
283
  success: false,
278
284
  error: {
279
285
  code: "CONFLICT",
280
- message: input.locale ? `Term '${input.slug}' already exists in '${taxonomyName}' (${input.locale})` : `Term with slug '${input.slug}' already exists in taxonomy '${taxonomyName}'`
286
+ message: locale ? `Term '${input.slug}' already exists in '${taxonomyName}' (${locale})` : `Term with slug '${input.slug}' already exists in taxonomy '${taxonomyName}'`
281
287
  }
282
288
  };
283
289
  let selfGroup = null;
@@ -296,7 +302,7 @@ async function handleTermCreate(db, taxonomyName, input) {
296
302
  label: input.label,
297
303
  parentId: parentId ?? void 0,
298
304
  data: input.description ? { description: input.description } : void 0,
299
- locale: input.locale,
305
+ locale,
300
306
  translationOf: input.translationOf
301
307
  });
302
308
  invalidateTermCache();
@@ -329,7 +335,8 @@ async function handleTermCreate(db, taxonomyName, input) {
329
335
  async function handleTermGet(db, taxonomyName, termSlug, options = {}) {
330
336
  try {
331
337
  const repo = new TaxonomyRepository(db);
332
- const term = await repo.findBySlug(taxonomyName, termSlug, options.locale);
338
+ const locale = options.locale ? resolveConfiguredLocale(options.locale) : void 0;
339
+ const term = await repo.findBySlug(taxonomyName, termSlug, locale);
333
340
  if (!term) return {
334
341
  success: false,
335
342
  error: {
@@ -409,7 +416,8 @@ async function handleTermTranslations(db, idOrGroup) {
409
416
  async function handleTermUpdate(db, taxonomyName, termSlug, input, options = {}) {
410
417
  try {
411
418
  const repo = new TaxonomyRepository(db);
412
- const term = await repo.findBySlug(taxonomyName, termSlug, options.locale);
419
+ const locale = options.locale ? resolveConfiguredLocale(options.locale) : void 0;
420
+ const term = await repo.findBySlug(taxonomyName, termSlug, locale);
413
421
  if (!term) return {
414
422
  success: false,
415
423
  error: {
@@ -420,7 +428,7 @@ async function handleTermUpdate(db, taxonomyName, termSlug, input, options = {})
420
428
  const newSlug = input.slug === "" || input.slug === void 0 ? void 0 : input.slug;
421
429
  const newParentId = input.parentId === "" || input.parentId === void 0 ? void 0 : input.parentId;
422
430
  if (newSlug !== void 0 && newSlug !== termSlug) {
423
- const existing = await repo.findBySlug(taxonomyName, newSlug, options.locale);
431
+ const existing = await repo.findBySlug(taxonomyName, newSlug, locale);
424
432
  if (existing && existing.id !== term.id) return {
425
433
  success: false,
426
434
  error: {
@@ -477,7 +485,8 @@ async function handleTermUpdate(db, taxonomyName, termSlug, input, options = {})
477
485
  async function handleTermDelete(db, taxonomyName, termSlug, options = {}) {
478
486
  try {
479
487
  const repo = new TaxonomyRepository(db);
480
- const term = await repo.findBySlug(taxonomyName, termSlug, options.locale);
488
+ const locale = options.locale ? resolveConfiguredLocale(options.locale) : void 0;
489
+ const term = await repo.findBySlug(taxonomyName, termSlug, locale);
481
490
  if (!term) return {
482
491
  success: false,
483
492
  error: {
@@ -517,4 +526,4 @@ async function handleTermDelete(db, taxonomyName, termSlug, options = {}) {
517
526
 
518
527
  //#endregion
519
528
  export { handleTermGet as a, handleTermUpdate as c, handleTermDelete as i, taxonomies_exports as l, handleTaxonomyList as n, handleTermList as o, handleTermCreate as r, handleTermTranslations as s, handleTaxonomyCreate as t };
520
- //# sourceMappingURL=taxonomies-Ce49uIzY.mjs.map
529
+ //# sourceMappingURL=taxonomies-rMeBzOjX.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"taxonomies-rMeBzOjX.mjs","names":[],"sources":["../src/api/handlers/taxonomies.ts"],"sourcesContent":["/**\n * Taxonomy and term CRUD handlers.\n *\n * i18n: terms and defs are per-locale. `(name, slug, locale)` is unique for\n * terms; `(name, locale)` for defs. Translations of the same term/def share a\n * `translation_group`. The content_taxonomies pivot stores translation_groups\n * so assignments span every locale of a post.\n */\n\nimport type { Kysely, Selectable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { TaxonomyRepository } from \"../../database/repositories/taxonomy.js\";\nimport type { Database, TaxonomyDefTable } from \"../../database/types.js\";\nimport { resolveConfiguredLocale } from \"../../i18n/config.js\";\nimport { invalidateTaxonomyDefsCache, invalidateTermCache } from \"../../taxonomies/index.js\";\nimport { fetchVisibleTermCounts } from \"../../taxonomies/term-counts.js\";\nimport type { ApiResult } from \"../types.js\";\n\nconst NAME_PATTERN = /^[a-z][a-z0-9_]*$/;\n\n// ---------------------------------------------------------------------------\n// Response types\n// ---------------------------------------------------------------------------\n\nexport interface TaxonomyDef {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tlabelSingular?: string;\n\thierarchical: boolean;\n\tcollections: string[];\n\tlocale: string;\n\ttranslationGroup: string | null;\n}\n\nexport interface TaxonomyListResponse {\n\ttaxonomies: TaxonomyDef[];\n}\n\nexport interface TermData {\n\tid: string;\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparentId: string | null;\n\tdescription?: string;\n\tlocale: string;\n\ttranslationGroup: string | null;\n}\n\nexport interface TermWithCount extends TermData {\n\tcount: number;\n\tchildren: TermWithCount[];\n}\n\nexport interface TermListResponse {\n\tterms: TermWithCount[];\n}\n\nexport interface TermResponse {\n\tterm: TermData;\n}\n\nexport interface TermGetResponse {\n\tterm: TermData & {\n\t\tcount: number;\n\t\tchildren: Array<{ id: string; slug: string; label: string }>;\n\t};\n}\n\nexport interface TermTranslationsResponse {\n\ttranslationGroup: string | null;\n\ttranslations: Array<{\n\t\tid: string;\n\t\tslug: string;\n\t\tlabel: string;\n\t\tlocale: string;\n\t}>;\n}\n\nexport interface TaxonomyDefTranslationsResponse {\n\ttranslationGroup: string | null;\n\ttranslations: Array<{\n\t\tid: string;\n\t\tname: string;\n\t\tlabel: string;\n\t\tlocale: string;\n\t}>;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Build tree structure from flat terms\n */\nfunction buildTree(flatTerms: TermWithCount[]): TermWithCount[] {\n\t// `parentId` holds the parent's translation_group, so resolve links by group.\n\t// Key by (locale, group): a child's parent lives in the same locale, and an\n\t// unfiltered list mixes locales whose translated siblings share a group —\n\t// keying by group alone would collide and misattach children across locales.\n\tconst byLocaleGroup = new Map<string, TermWithCount>();\n\tconst roots: TermWithCount[] = [];\n\tfor (const term of flatTerms) {\n\t\tbyLocaleGroup.set(`${term.locale}::${term.translationGroup ?? term.id}`, term);\n\t}\n\tfor (const term of flatTerms) {\n\t\tconst parent = term.parentId\n\t\t\t? byLocaleGroup.get(`${term.locale}::${term.parentId}`)\n\t\t\t: undefined;\n\t\tif (parent) {\n\t\t\tparent.children.push(term);\n\t\t} else {\n\t\t\troots.push(term);\n\t\t}\n\t}\n\treturn roots;\n}\n\n/**\n * Look up a taxonomy definition by name (optionally scoped to a locale).\n * Returns the lowest-locale match when no locale is provided.\n */\nasync function requireTaxonomyDef(\n\tdb: Kysely<Database>,\n\tname: string,\n\tlocale?: string,\n): Promise<\n\t| { success: true; def: Selectable<TaxonomyDefTable> }\n\t| { success: false; error: { code: string; message: string } }\n> {\n\tlet query = db.selectFrom(\"_emdash_taxonomy_defs\").selectAll().where(\"name\", \"=\", name);\n\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\tconst def = await query.orderBy(\"locale\", \"asc\").executeTakeFirst();\n\tif (!def) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"NOT_FOUND\", message: `Taxonomy '${name}' not found` },\n\t\t};\n\t}\n\treturn { success: true, def };\n}\n\n/** Declared collections of a taxonomy def row (deduped, parsed from JSON). */\nfunction defCollections(def: Selectable<TaxonomyDefTable>): string[] {\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- column stores a JSON string[] written by handleTaxonomyCreate\n\tconst parsed = def.collections ? (JSON.parse(def.collections) as string[]) : [];\n\treturn [...new Set(parsed)];\n}\n\nfunction rowToDef(row: Selectable<TaxonomyDefTable>): TaxonomyDef {\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tlabel: row.label,\n\t\tlabelSingular: row.label_singular ?? undefined,\n\t\thierarchical: row.hierarchical === 1,\n\t\tcollections: row.collections ? JSON.parse(row.collections) : [],\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Taxonomy definition handlers\n// ---------------------------------------------------------------------------\n\n/**\n * List all taxonomy definitions\n */\nexport async function handleTaxonomyList(\n\tdb: Kysely<Database>,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<TaxonomyListResponse>> {\n\ttry {\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tlet query = db.selectFrom(\"_emdash_taxonomy_defs\").selectAll();\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst [rows, collectionRows] = await Promise.all([\n\t\t\tquery.execute(),\n\t\t\tdb.selectFrom(\"_emdash_collections\").select(\"slug\").execute(),\n\t\t]);\n\n\t\t// Filter orphan collection references on read so the response stays\n\t\t// consistent with `schema_list_collections`. Storage is untouched —\n\t\t// re-creating the collection re-links automatically.\n\t\tconst realCollections = new Set(collectionRows.map((r) => r.slug));\n\n\t\tconst taxonomies: TaxonomyDef[] = rows.map((row) => {\n\t\t\tconst def = rowToDef(row);\n\t\t\treturn { ...def, collections: def.collections.filter((slug) => realCollections.has(slug)) };\n\t\t});\n\n\t\treturn { success: true, data: { taxonomies } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TAXONOMY_LIST_ERROR\", message: \"Failed to list taxonomies\" },\n\t\t};\n\t}\n}\n\n/**\n * Create a new taxonomy definition\n */\nexport async function handleTaxonomyCreate(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\tname: string;\n\t\tlabel: string;\n\t\tlabelSingular?: string;\n\t\thierarchical?: boolean;\n\t\tcollections?: string[];\n\t\tlocale?: string;\n\t\ttranslationOf?: string;\n\t},\n): Promise<ApiResult<{ taxonomy: TaxonomyDef }>> {\n\ttry {\n\t\tconst locale = input.locale ? resolveConfiguredLocale(input.locale) : undefined;\n\t\tif (!NAME_PATTERN.test(input.name)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"Taxonomy name must start with a letter and contain only lowercase letters, numbers, and underscores\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst collections = [...new Set(input.collections ?? [])];\n\t\tif (collections.length > 0) {\n\t\t\tconst existingCollections = await db\n\t\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t\t.select(\"slug\")\n\t\t\t\t.where(\"slug\", \"in\", collections)\n\t\t\t\t.execute();\n\t\t\tconst existingSlugs = new Set(existingCollections.map((c) => c.slug));\n\t\t\tconst invalid = collections.filter((c) => !existingSlugs.has(c));\n\t\t\tif (invalid.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\tmessage: `Unknown collection(s): ${invalid.join(\", \")}`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tlet translationGroup: string | null = null;\n\t\tif (input.translationOf) {\n\t\t\tconst source = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"id\", \"=\", input.translationOf)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (!source) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Source taxonomy for translation not found\" },\n\t\t\t\t};\n\t\t\t}\n\t\t\ttranslationGroup = source.translation_group ?? source.id;\n\t\t}\n\n\t\t// Duplicate guard scoped to locale (so the same name can exist in ES\n\t\t// and EN).\n\t\tif (locale !== undefined) {\n\t\t\tconst existing = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.select(\"id\")\n\t\t\t\t.where(\"name\", \"=\", input.name)\n\t\t\t\t.where(\"locale\", \"=\", locale)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (existing) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\t\tmessage: `Taxonomy '${input.name}' already exists in locale '${locale}'`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tconst id = ulid();\n\t\tawait db\n\t\t\t.insertInto(\"_emdash_taxonomy_defs\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tname: input.name,\n\t\t\t\tlabel: input.label,\n\t\t\t\tlabel_singular: input.labelSingular ?? null,\n\t\t\t\thierarchical: input.hierarchical ? 1 : 0,\n\t\t\t\tcollections: JSON.stringify(collections),\n\t\t\t\t...(locale !== undefined ? { locale } : {}),\n\t\t\t\ttranslation_group: translationGroup ?? id,\n\t\t\t})\n\t\t\t.execute();\n\n\t\t// A new def changes which taxonomies exist — drop the isolate-wide\n\t\t// defs/names caches so this isolate reflects it immediately.\n\t\tinvalidateTaxonomyDefsCache();\n\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirstOrThrow();\n\t\treturn { success: true, data: { taxonomy: rowToDef(row) } };\n\t} catch (error) {\n\t\tif (error instanceof Error && error.message.includes(\"UNIQUE constraint failed\")) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"CONFLICT\", message: `Taxonomy '${input.name}' already exists` },\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TAXONOMY_CREATE_ERROR\", message: \"Failed to create taxonomy\" },\n\t\t};\n\t}\n}\n\n/**\n * List every locale translation of a taxonomy def (by id or translation_group).\n */\nexport async function handleTaxonomyDefTranslations(\n\tdb: Kysely<Database>,\n\tidOrGroup: string,\n): Promise<ApiResult<TaxonomyDefTranslationsResponse>> {\n\ttry {\n\t\tconst anchor = await db\n\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t.selectAll()\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\tif (!anchor) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Taxonomy not found\" },\n\t\t\t};\n\t\t}\n\t\tconst group = anchor.translation_group ?? anchor.id;\n\t\tconst rows = await db\n\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", group)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\ttranslationGroup: group,\n\t\t\t\ttranslations: rows.map((r) => ({\n\t\t\t\t\tid: r.id,\n\t\t\t\t\tname: r.name,\n\t\t\t\t\tlabel: r.label,\n\t\t\t\t\tlocale: r.locale,\n\t\t\t\t})),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"TAXONOMY_TRANSLATIONS_ERROR\",\n\t\t\t\tmessage: \"Failed to list taxonomy translations\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Term handlers\n// ---------------------------------------------------------------------------\n\n/**\n * List all terms for a taxonomy (returns tree for hierarchical taxonomies)\n */\nexport async function handleTermList(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<TermListResponse>> {\n\ttry {\n\t\t// Definitions are per-locale but terms aren't bound to the def's locale —\n\t\t// just ensure the taxonomy exists somewhere.\n\t\tconst lookup = await requireTaxonomyDef(db, taxonomyName);\n\t\tif (!lookup.success) return lookup;\n\n\t\tconst repo = new TaxonomyRepository(db);\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tconst terms = await repo.findByName(taxonomyName, { locale });\n\n\t\t// Counts match what visitors see on the public site: published (or\n\t\t// scheduled-and-due) entries that aren't soft-deleted, scoped to the\n\t\t// taxonomy's declared collections — one query for the whole list.\n\t\t// content_taxonomies.taxonomy_id stores the translation_group, so we\n\t\t// look up by group and map back to each term's id.\n\t\tconst countsByGroup = await fetchVisibleTermCounts(\n\t\t\tdb,\n\t\t\ttaxonomyName,\n\t\t\tdefCollections(lookup.def),\n\t\t);\n\n\t\tconst termData: TermWithCount[] = terms.map((term) => ({\n\t\t\tid: term.id,\n\t\t\tname: term.name,\n\t\t\tslug: term.slug,\n\t\t\tlabel: term.label,\n\t\t\tparentId: term.parentId,\n\t\t\tdescription: typeof term.data?.description === \"string\" ? term.data.description : undefined,\n\t\t\tchildren: [],\n\t\t\tcount: countsByGroup.get(term.translationGroup ?? term.id) ?? 0,\n\t\t\tlocale: term.locale,\n\t\t\ttranslationGroup: term.translationGroup,\n\t\t}));\n\n\t\tconst isHierarchical = lookup.def.hierarchical === 1;\n\t\tconst result = isHierarchical ? buildTree(termData) : termData;\n\t\treturn { success: true, data: { terms: result } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_LIST_ERROR\", message: \"Failed to list terms\" },\n\t\t};\n\t}\n}\n\n/**\n * Validate a parent term reference for create/update.\n *\n * Returns `null` on success or a structured error message that callers\n * wrap in their own ApiResult.\n *\n * - `parentId === undefined` -> no-op (no parent change requested).\n * - `parentId === null` -> caller intends to detach; no-op here.\n * - parent must exist (FK exists -> term row not soft-deleted).\n * - parent must live in the same taxonomy.\n * - reject a parent in the term's own translation_group (self-parent),\n * including the create path: a translation inherits its source's group, so\n * `selfGroup` carries that prospective group when `termId` is absent.\n * - on update, walk up the parent chain to detect cycles.\n */\nasync function validateParentTerm(\n\trepo: TaxonomyRepository,\n\ttaxonomyName: string,\n\ttermId: string | undefined,\n\tparentId: string | null | undefined,\n\tselfGroup?: string | null,\n): Promise<{ code: \"VALIDATION_ERROR\"; message: string } | null> {\n\tif (parentId === undefined || parentId === null) return null;\n\n\tconst parent = await repo.findById(parentId);\n\tif (!parent) {\n\t\treturn {\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tmessage: `Parent term '${parentId}' not found`,\n\t\t};\n\t}\n\tif (parent.name !== taxonomyName) {\n\t\treturn {\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tmessage: `Parent term '${parentId}' belongs to taxonomy '${parent.name}', not '${taxonomyName}'`,\n\t\t};\n\t}\n\n\t// Parentage keys off translation_group (what `parent_id` persists), so the\n\t// self-parent and cycle checks compare groups, not row ids — picking a\n\t// sibling translation of the term as its parent is still self-parenting.\n\tconst parentGroup = parent.translationGroup ?? parent.id;\n\tlet termGroup: string | null = selfGroup ?? null;\n\tif (termId !== undefined) {\n\t\tconst term = await repo.findById(termId);\n\t\ttermGroup = term ? (term.translationGroup ?? term.id) : termId;\n\t}\n\tif (termGroup !== null && parentGroup === termGroup) {\n\t\treturn {\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tmessage: \"A term cannot be its own parent\",\n\t\t};\n\t}\n\n\t// Walk up the parent chain. Two checks fold into one walk:\n\t// - Cycle detection (only on update — a non-existent term-being-\n\t// created can't be its own ancestor): if the walk revisits termId\n\t// the proposed parent makes the term a descendant of itself.\n\t// - Depth bound: refuse to extend a chain past MAX_DEPTH ancestors.\n\t// Runs on both create and update so a malicious or buggy caller\n\t// can't grow the tree without limit.\n\t//\n\t// The depth-exceeded error fires only when we hit the limit AND there\n\t// was still chain to walk — a legitimate chain of exactly MAX_DEPTH\n\t// ancestors exits with `cursor === null` and is accepted.\n\t// `parent_id` stores a translation_group, which always equals the anchor\n\t// row's id, so findById(cursor) still resolves each ancestor.\n\tconst MAX_DEPTH = 100;\n\tlet cursor: string | null = parent.parentId;\n\tlet steps = 0;\n\twhile (cursor !== null && steps < MAX_DEPTH) {\n\t\tif (termGroup !== null && cursor === termGroup) {\n\t\t\treturn {\n\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\tmessage: \"Cycle detected: cannot make a descendant the parent\",\n\t\t\t};\n\t\t}\n\t\tconst next = await repo.findById(cursor);\n\t\tif (!next) break;\n\t\tcursor = next.parentId;\n\t\tsteps++;\n\t}\n\tif (cursor !== null && steps >= MAX_DEPTH) {\n\t\treturn {\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tmessage: \"Parent chain exceeds maximum depth\",\n\t\t};\n\t}\n\n\treturn null;\n}\n\n/**\n * Create a new term in a taxonomy\n */\nexport async function handleTermCreate(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tinput: {\n\t\tslug: string;\n\t\tlabel: string;\n\t\tparentId?: string | null;\n\t\tdescription?: string;\n\t\tlocale?: string;\n\t\ttranslationOf?: string;\n\t},\n): Promise<ApiResult<TermResponse>> {\n\ttry {\n\t\tconst locale = input.locale ? resolveConfiguredLocale(input.locale) : undefined;\n\t\t// Taxonomy definitions are per-locale, but terms can exist in any locale\n\t\t// regardless of whether the def has been translated there. Look up the\n\t\t// def across all locales — we only care that it *exists*.\n\t\tconst lookup = await requireTaxonomyDef(db, taxonomyName);\n\t\tif (!lookup.success) return lookup;\n\n\t\tconst repo = new TaxonomyRepository(db);\n\n\t\t// Coerce empty-string parentId to undefined (treat as \"no parent\").\n\t\tconst parentId =\n\t\t\tinput.parentId === \"\" || input.parentId === undefined ? undefined : input.parentId;\n\n\t\t// Conflict check is scoped to locale (per-locale slugs are unique).\n\t\tconst existing = await repo.findBySlug(taxonomyName, input.slug, locale);\n\t\tif (existing) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\tmessage: locale\n\t\t\t\t\t\t? `Term '${input.slug}' already exists in '${taxonomyName}' (${locale})`\n\t\t\t\t\t\t: `Term with slug '${input.slug}' already exists in taxonomy '${taxonomyName}'`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// No locale re-pointing needed: `repo.create` persists the parent's\n\t\t// translation_group in `parent_id`, so a child stays nested under the\n\t\t// parent in every locale automatically — including parents translated\n\t\t// after the child was created.\n\n\t\t// A translation inherits its source's translation_group; pass that\n\t\t// prospective group so validateParentTerm can reject a parent in the same\n\t\t// group (cross-locale self-parent) even though the term doesn't exist yet.\n\t\tlet selfGroup: string | null = null;\n\t\tif (input.translationOf) {\n\t\t\tconst source = await repo.findById(input.translationOf);\n\t\t\tselfGroup = source ? (source.translationGroup ?? source.id) : null;\n\t\t}\n\n\t\t// Validate parentId: must exist AND belong to the same taxonomy.\n\t\t// (Cycle check is N/A on create — the term doesn't exist yet.)\n\t\tconst parentError = await validateParentTerm(\n\t\t\trepo,\n\t\t\ttaxonomyName,\n\t\t\tundefined,\n\t\t\tparentId,\n\t\t\tselfGroup,\n\t\t);\n\t\tif (parentError) {\n\t\t\treturn { success: false, error: parentError };\n\t\t}\n\n\t\tconst term = await repo.create({\n\t\t\tname: taxonomyName,\n\t\t\tslug: input.slug,\n\t\t\tlabel: input.label,\n\t\t\tparentId: parentId ?? undefined,\n\t\t\tdata: input.description ? { description: input.description } : undefined,\n\t\t\tlocale,\n\t\t\ttranslationOf: input.translationOf,\n\t\t});\n\n\t\tinvalidateTermCache();\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tterm: {\n\t\t\t\t\tid: term.id,\n\t\t\t\t\tname: term.name,\n\t\t\t\t\tslug: term.slug,\n\t\t\t\t\tlabel: term.label,\n\t\t\t\t\tparentId: term.parentId,\n\t\t\t\t\tdescription:\n\t\t\t\t\t\ttypeof term.data?.description === \"string\" ? term.data.description : undefined,\n\t\t\t\t\tlocale: term.locale,\n\t\t\t\t\ttranslationGroup: term.translationGroup,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_CREATE_ERROR\", message: \"Failed to create term\" },\n\t\t};\n\t}\n}\n\n/**\n * Get a single term by slug\n */\nexport async function handleTermGet(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<TermGetResponse>> {\n\ttry {\n\t\tconst repo = new TaxonomyRepository(db);\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tconst term = await repo.findBySlug(taxonomyName, termSlug, locale);\n\n\t\tif (!term) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\tmessage: `Term '${termSlug}' not found in taxonomy '${taxonomyName}'`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Count matches public visibility (published or scheduled-and-due, not\n\t\t// soft-deleted) scoped to the def's declared collections. The def lookup\n\t\t// is lenient: a term whose def is missing still resolves, with count 0.\n\t\tconst lookup = await requireTaxonomyDef(db, taxonomyName);\n\t\tconst counts = await fetchVisibleTermCounts(\n\t\t\tdb,\n\t\t\ttaxonomyName,\n\t\t\tlookup.success ? defCollections(lookup.def) : [],\n\t\t);\n\t\tconst count = counts.get(term.translationGroup ?? term.id) ?? 0;\n\t\t// Children share this term's translation_group as their parent_id; scope\n\t\t// to the term's own locale so the response stays within one locale's tree.\n\t\tconst children = await repo.findChildren(term.id, term.locale);\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tterm: {\n\t\t\t\t\tid: term.id,\n\t\t\t\t\tname: term.name,\n\t\t\t\t\tslug: term.slug,\n\t\t\t\t\tlabel: term.label,\n\t\t\t\t\tparentId: term.parentId,\n\t\t\t\t\tdescription:\n\t\t\t\t\t\ttypeof term.data?.description === \"string\" ? term.data.description : undefined,\n\t\t\t\t\tcount,\n\t\t\t\t\tchildren: children.map((c) => ({ id: c.id, slug: c.slug, label: c.label })),\n\t\t\t\t\tlocale: term.locale,\n\t\t\t\t\ttranslationGroup: term.translationGroup,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_GET_ERROR\", message: \"Failed to get term\" },\n\t\t};\n\t}\n}\n\n/** List every translation of a term (by id or translation_group). */\nexport async function handleTermTranslations(\n\tdb: Kysely<Database>,\n\tidOrGroup: string,\n): Promise<ApiResult<TermTranslationsResponse>> {\n\ttry {\n\t\tconst anchor = await db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\tif (!anchor) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Term not found\" },\n\t\t\t};\n\t\t}\n\t\tconst group = anchor.translation_group ?? anchor.id;\n\t\tconst rows = await db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", group)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\ttranslationGroup: group,\n\t\t\t\ttranslations: rows.map((r) => ({\n\t\t\t\t\tid: r.id,\n\t\t\t\t\tslug: r.slug,\n\t\t\t\t\tlabel: r.label,\n\t\t\t\t\tlocale: r.locale,\n\t\t\t\t})),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_TRANSLATIONS_ERROR\", message: \"Failed to list term translations\" },\n\t\t};\n\t}\n}\n\n/**\n * Update a term\n */\nexport async function handleTermUpdate(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\tinput: { slug?: string; label?: string; parentId?: string | null; description?: string },\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<TermResponse>> {\n\ttry {\n\t\tconst repo = new TaxonomyRepository(db);\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tconst term = await repo.findBySlug(taxonomyName, termSlug, locale);\n\n\t\tif (!term) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\tmessage: `Term '${termSlug}' not found in taxonomy '${taxonomyName}'`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Coerce empty-string slug/parentId to undefined (treat as \"no change\").\n\t\t// `null` parentId is a valid request meaning \"detach from parent\".\n\t\tconst newSlug = input.slug === \"\" || input.slug === undefined ? undefined : input.slug;\n\t\tconst newParentId =\n\t\t\tinput.parentId === \"\" || input.parentId === undefined ? undefined : input.parentId;\n\n\t\t// Check if new slug conflicts (per-locale uniqueness).\n\t\tif (newSlug !== undefined && newSlug !== termSlug) {\n\t\t\tconst existing = await repo.findBySlug(taxonomyName, newSlug, locale);\n\t\t\tif (existing && existing.id !== term.id) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\t\tmessage: `Term with slug '${newSlug}' already exists in taxonomy '${taxonomyName}'`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Validate parentId: existence, same-taxonomy, no self-parent, no cycle.\n\t\tconst parentError = await validateParentTerm(repo, taxonomyName, term.id, newParentId);\n\t\tif (parentError) {\n\t\t\treturn { success: false, error: parentError };\n\t\t}\n\n\t\tconst updated = await repo.update(term.id, {\n\t\t\tslug: newSlug,\n\t\t\tlabel: input.label,\n\t\t\tparentId: newParentId,\n\t\t\tdata: input.description !== undefined ? { description: input.description } : undefined,\n\t\t});\n\n\t\tinvalidateTermCache();\n\n\t\tif (!updated) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"TERM_UPDATE_ERROR\", message: \"Failed to update term\" },\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tterm: {\n\t\t\t\t\tid: updated.id,\n\t\t\t\t\tname: updated.name,\n\t\t\t\t\tslug: updated.slug,\n\t\t\t\t\tlabel: updated.label,\n\t\t\t\t\tparentId: updated.parentId,\n\t\t\t\t\tdescription:\n\t\t\t\t\t\ttypeof updated.data?.description === \"string\" ? updated.data.description : undefined,\n\t\t\t\t\tlocale: updated.locale,\n\t\t\t\t\ttranslationGroup: updated.translationGroup,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_UPDATE_ERROR\", message: \"Failed to update term\" },\n\t\t};\n\t}\n}\n\n/**\n * Delete a term\n */\nexport async function handleTermDelete(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<{ deleted: true }>> {\n\ttry {\n\t\tconst repo = new TaxonomyRepository(db);\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tconst term = await repo.findBySlug(taxonomyName, termSlug, locale);\n\n\t\tif (!term) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\tmessage: `Term '${termSlug}' not found in taxonomy '${taxonomyName}'`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Block deletion if the term's group still parents any child in any\n\t\t// locale — children store this group in parent_id, so removing the term\n\t\t// would orphan them (or null their parent_id via the self-FK).\n\t\tconst children = await repo.findChildren(term.id);\n\t\tif (children.length > 0) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\tmessage: \"Cannot delete term with children. Delete children first.\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst deleted = await repo.delete(term.id);\n\t\tif (!deleted) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"TERM_DELETE_ERROR\", message: \"Failed to delete term\" },\n\t\t\t};\n\t\t}\n\n\t\tinvalidateTermCache();\n\t\treturn { success: true, data: { deleted: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_DELETE_ERROR\", message: \"Failed to delete term\" },\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmBA,MAAM,eAAe;;;;AA+ErB,SAAS,UAAU,WAA6C;CAK/D,MAAM,gCAAgB,IAAI,KAA4B;CACtD,MAAM,QAAyB,EAAE;AACjC,MAAK,MAAM,QAAQ,UAClB,eAAc,IAAI,GAAG,KAAK,OAAO,IAAI,KAAK,oBAAoB,KAAK,MAAM,KAAK;AAE/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A+B,EAAE,EACO;AACxC,KAAI;EACH,MAAM,OAAO,IAAI,mBAAmB,GAAG;EACvC,MAAM,SAAS,QAAQ,SAAS,wBAAwB,QAAQ,OAAO,GAAG;EAC1E,MAAM,OAAO,MAAM,KAAK,WAAW,cAAc,UAAU,OAAO;AAElE,MAAI,CAAC,KACJ,QAAO;GACN,SAAS;GACT,OAAO;IACN,MAAM;IACN,SAAS,SAAS,SAAS,2BAA2B,aAAa;IACnE;GACD;AAOF,OADiB,MAAM,KAAK,aAAa,KAAK,GAAG,EACpC,SAAS,EACrB,QAAO;GACN,SAAS;GACT,OAAO;IACN,MAAM;IACN,SAAS;IACT;GACD;AAIF,MAAI,CADY,MAAM,KAAK,OAAO,KAAK,GAAG,CAEzC,QAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAqB,SAAS;IAAyB;GACtE;AAGF,uBAAqB;AACrB,SAAO;GAAE,SAAS;GAAM,MAAM,EAAE,SAAS,MAAM;GAAE;SAC1C;AACP,SAAO;GACN,SAAS;GACT,OAAO;IAAE,MAAM;IAAqB,SAAS;IAAyB;GACtE"}
@@ -1,4 +1,4 @@
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
3
  import { d as invalidateTaxonomyObjectCache } from "./object-cache-Bok5j2ae.mjs";
4
4
  import { n as isMissingTableError } from "./db-errors-CcWLaRiR.mjs";
@@ -277,7 +277,7 @@ var TaxonomyRepository = class {
277
277
  */
278
278
  async countEntriesForTerms(translationGroups) {
279
279
  if (translationGroups.length === 0) return /* @__PURE__ */ new Map();
280
- const { chunks, SQL_BATCH_SIZE } = await import("./chunks-BxXyunY-.mjs").then((n) => n.r);
280
+ const { chunks, SQL_BATCH_SIZE } = await import("./chunks-Bq-5DPrD.mjs").then((n) => n.r);
281
281
  const counts = /* @__PURE__ */ new Map();
282
282
  for (const chunk of chunks(translationGroups, SQL_BATCH_SIZE)) {
283
283
  const rows = await this.db.selectFrom("content_taxonomies").select(["taxonomy_id", (eb) => eb.fn.count("entry_id").as("count")]).where("taxonomy_id", "in", chunk).groupBy("taxonomy_id").execute();
@@ -301,4 +301,4 @@ var TaxonomyRepository = class {
301
301
 
302
302
  //#endregion
303
303
  export { taxonomy_exports as n, TaxonomyRepository as t };
304
- //# sourceMappingURL=taxonomy-DfVooU4W.mjs.map
304
+ //# sourceMappingURL=taxonomy-0mCI25HN.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"taxonomy-DfVooU4W.mjs","names":[],"sources":["../src/database/repositories/taxonomy.ts"],"sourcesContent":["import { sql, type Kysely, type Selectable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { invalidateTaxonomyObjectCache } from \"../../object-cache/index.js\";\nimport { isMissingTableError } from \"../../utils/db-errors.js\";\nimport type { Database, TaxonomyTable } from \"../types.js\";\nimport { validateIdentifier } from \"../validate.js\";\n\n/**\n * Filter + sort columns denormalized from an entry's `ec_*` row onto its\n * `content_taxonomies` pivot rows (migration 051). Stamped at insert time so a\n * newly-tagged entry is immediately seekable by a taxonomy-filtered listing.\n */\ninterface PivotDenorm {\n\tstatus: string | null;\n\tscheduled_at: string | null;\n\tdeleted_at: string | null;\n\tlocale: string | null;\n\tpublished_at: string | null;\n\tcreated_at: string | null;\n}\n\nconst EMPTY_DENORM: PivotDenorm = {\n\tstatus: null,\n\tscheduled_at: null,\n\tdeleted_at: null,\n\tlocale: null,\n\tpublished_at: null,\n\tcreated_at: null,\n};\n\nexport interface Taxonomy {\n\tid: string;\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparentId: string | null;\n\tdata: Record<string, unknown> | null;\n\tlocale: string;\n\ttranslationGroup: string | null;\n}\n\nexport interface CreateTaxonomyInput {\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparentId?: string;\n\tdata?: Record<string, unknown>;\n\t/** Omit to let the DB default (current value: 'en') apply. Higher layers\n\t * resolve the locale from the request context / i18n config. */\n\tlocale?: string;\n\t/** When set, links the new term into the source term's translation_group. */\n\ttranslationOf?: string;\n}\n\nexport interface UpdateTaxonomyInput {\n\tslug?: string;\n\tlabel?: string;\n\tparentId?: string | null;\n\tdata?: Record<string, unknown>;\n}\n\nexport interface FindOptions {\n\tparentId?: string | null;\n\tlocale?: string;\n}\n\n/**\n * Taxonomy repository for categories, tags, and other classification.\n *\n * Terms are per-locale. Translations of the same term share a `translation_group`\n * ULID. `content_taxonomies.taxonomy_id` stores the translation_group so a single\n * association spans every locale of a post.\n *\n * The repository does not resolve locale fallbacks on its own — callers supply\n * the locale they want. Runtime helpers and handlers use `getFallbackChain()`\n * from `i18n/config` when they need fallback behaviour.\n */\nexport class TaxonomyRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Create a new taxonomy term. When `translationOf` is set the new row joins\n\t * the source term's translation_group; otherwise a fresh group is minted\n\t * (matching the migration backfill pattern `translation_group = id`).\n\t */\n\tasync create(input: CreateTaxonomyInput): Promise<Taxonomy> {\n\t\tconst id = ulid();\n\n\t\t// Empty-string parentId is coerced to null defensively. Higher layers\n\t\t// also normalize this — see handleTermCreate / handleTermUpdate.\n\t\t// `parent_id` stores the parent's locale-agnostic translation_group (not a\n\t\t// row id), mirroring content_taxonomies.taxonomy_id, so a child stays\n\t\t// nested in every locale's tree. resolveTranslationGroup accepts either a\n\t\t// row id or an already-resolved group, so this is idempotent.\n\t\tconst parentInput =\n\t\t\tinput.parentId === undefined || input.parentId === \"\" ? null : input.parentId;\n\t\tconst parentId = parentInput ? await this.resolveParentRef(parentInput) : null;\n\n\t\tlet translationGroup = id;\n\t\tif (input.translationOf) {\n\t\t\tconst source = await this.findById(input.translationOf);\n\t\t\tif (source?.translationGroup) translationGroup = source.translationGroup;\n\t\t}\n\n\t\tawait this.db\n\t\t\t.insertInto(\"taxonomies\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tname: input.name,\n\t\t\t\tslug: input.slug,\n\t\t\t\tlabel: input.label,\n\t\t\t\tparent_id: parentId,\n\t\t\t\tdata: input.data ? JSON.stringify(input.data) : null,\n\t\t\t\t// When omitted, the DB DEFAULT 'en' is used — keeps behaviour\n\t\t\t\t// consistent with ContentRepository and lets higher layers\n\t\t\t\t// supply an explicit locale from request context.\n\t\t\t\t...(input.locale !== undefined ? { locale: input.locale } : {}),\n\t\t\t\ttranslation_group: translationGroup,\n\t\t\t})\n\t\t\t.execute();\n\n\t\tinvalidateTaxonomyObjectCache();\n\n\t\tconst taxonomy = await this.findById(id);\n\t\tif (!taxonomy) throw new Error(\"Failed to create taxonomy\");\n\t\treturn taxonomy;\n\t}\n\n\tasync findById(id: string): Promise<Taxonomy | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? this.rowToTaxonomy(row) : null;\n\t}\n\n\t/**\n\t * Find a term by (name, slug). When `locale` is provided, filter by it.\n\t * When omitted, returns the lowest-locale-code match (deterministic across\n\t * calls). Mirrors `ContentRepository.findBySlug`.\n\t */\n\tasync findBySlug(name: string, slug: string, locale?: string): Promise<Taxonomy | null> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.where(\"slug\", \"=\", slug);\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst row = await query.orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t\treturn row ? this.rowToTaxonomy(row) : null;\n\t}\n\n\t/**\n\t * Get all terms for a taxonomy (e.g., all categories).\n\t *\n\t * `id asc` is a stable tiebreaker for terms that share a label. Without it\n\t * the SQL ordering is implementation-defined when labels match, which\n\t * breaks keyset pagination over `(label, id)`.\n\t */\n\tasync findByName(name: string, options: FindOptions = {}): Promise<Taxonomy[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.orderBy(\"label\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\n\t\tif (options.locale !== undefined) query = query.where(\"locale\", \"=\", options.locale);\n\n\t\tif (options.parentId !== undefined) {\n\t\t\tif (options.parentId === null) {\n\t\t\t\tquery = query.where(\"parent_id\", \"is\", null);\n\t\t\t} else {\n\t\t\t\tquery = query.where(\"parent_id\", \"=\", options.parentId);\n\t\t\t}\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\t/**\n\t * Children of a term. Accepts a term id OR a translation_group and resolves\n\t * to the group, since `parent_id` stores the parent's translation_group.\n\t * Pass `locale` to scope to one locale's tree (children share the parent's\n\t * group across locales); omit it to find children in every locale (used to\n\t * block deletes that would orphan a sibling translation's subtree).\n\t */\n\tasync findChildren(parentIdOrGroup: string, locale?: string): Promise<Taxonomy[]> {\n\t\tconst group = await this.resolveTranslationGroup(parentIdOrGroup);\n\t\tif (!group) return [];\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"parent_id\", \"=\", group)\n\t\t\t.orderBy(\"label\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\t/**\n\t * Every translation sibling of a term (including itself), identified by\n\t * their shared `translation_group`.\n\t */\n\tasync findTranslations(translationGroup: string): Promise<Taxonomy[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", translationGroup)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\tasync update(id: string, input: UpdateTaxonomyInput): Promise<Taxonomy | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return null;\n\n\t\tconst updates: Record<string, unknown> = {};\n\t\tif (input.slug !== undefined) updates.slug = input.slug;\n\t\tif (input.label !== undefined) updates.label = input.label;\n\t\tif (input.parentId !== undefined) {\n\t\t\t// Defense in depth: empty-string parentId means null (no parent).\n\t\t\t// Otherwise persist the parent's translation_group (locale-agnostic),\n\t\t\t// matching create() — see the note there.\n\t\t\tupdates.parent_id =\n\t\t\t\tinput.parentId === \"\" || input.parentId === null\n\t\t\t\t\t? null\n\t\t\t\t\t: await this.resolveParentRef(input.parentId);\n\t\t}\n\t\tif (input.data !== undefined) updates.data = JSON.stringify(input.data);\n\n\t\tif (Object.keys(updates).length > 0) {\n\t\t\tawait this.db.updateTable(\"taxonomies\").set(updates).where(\"id\", \"=\", id).execute();\n\t\t\tinvalidateTaxonomyObjectCache();\n\t\t}\n\n\t\treturn this.findById(id);\n\t}\n\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst term = await this.findById(id);\n\t\tif (!term) return false;\n\n\t\t// When deleting the last translation of a group the pivot rows that\n\t\t// reference that translation_group become orphaned — purge them.\n\t\tif (term.translationGroup) {\n\t\t\tconst siblings = await this.db\n\t\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t\t.select(\"id\")\n\t\t\t\t.where(\"translation_group\", \"=\", term.translationGroup)\n\t\t\t\t.where(\"id\", \"!=\", id)\n\t\t\t\t.execute();\n\t\t\tif (siblings.length === 0) {\n\t\t\t\tawait this.db\n\t\t\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t\t\t.where(\"taxonomy_id\", \"=\", term.translationGroup)\n\t\t\t\t\t.execute();\n\t\t\t}\n\t\t}\n\n\t\tconst result = await this.db.deleteFrom(\"taxonomies\").where(\"id\", \"=\", id).executeTakeFirst();\n\t\tinvalidateTaxonomyObjectCache();\n\t\treturn (result.numDeletedRows ?? 0n) > 0n;\n\t}\n\n\t// --- Content-Taxonomy Junction (taxonomy_id stores the translation_group) ---\n\n\tasync attachToEntry(collection: string, entryId: string, taxonomyId: string): Promise<void> {\n\t\tconst group = await this.resolveTranslationGroup(taxonomyId);\n\t\tif (!group) return;\n\n\t\tconst denorm = await this.fetchEntryDenorm(collection, entryId);\n\t\tawait this.db\n\t\t\t.insertInto(\"content_taxonomies\")\n\t\t\t.values({ collection, entry_id: entryId, taxonomy_id: group, ...denorm })\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.execute();\n\t\tinvalidateTaxonomyObjectCache();\n\t}\n\n\tasync detachFromEntry(collection: string, entryId: string, taxonomyId: string): Promise<void> {\n\t\tconst group = await this.resolveTranslationGroup(taxonomyId);\n\t\tif (!group) return;\n\n\t\tawait this.db\n\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t.where(\"taxonomy_id\", \"=\", group)\n\t\t\t.execute();\n\t\tinvalidateTaxonomyObjectCache();\n\t}\n\n\t/**\n\t * Taxonomy terms assigned to a content entry, resolved into a specific locale.\n\t * Terms whose translation_group lacks a row in the requested locale are\n\t * omitted — callers wanting fallback behaviour apply it themselves.\n\t */\n\tasync getTermsForEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\ttaxonomyName?: string,\n\t\tlocale?: string,\n\t): Promise<Taxonomy[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t.selectAll(\"taxonomies\")\n\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryId);\n\n\t\tif (taxonomyName) query = query.where(\"taxonomies.name\", \"=\", taxonomyName);\n\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\n\t\tconst rows = await query.orderBy(\"taxonomies.locale\", \"asc\").execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\t/**\n\t * Replace all assignments of a given taxonomy for one content entry.\n\t * Term ids OR translation_groups are accepted and normalised to groups.\n\t */\n\tasync setTermsForEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\ttaxonomyName: string,\n\t\ttermIds: string[],\n\t): Promise<void> {\n\t\tconst groups: string[] = [];\n\t\tfor (const id of termIds) {\n\t\t\tconst group = await this.resolveTranslationGroup(id);\n\t\t\tif (group) groups.push(group);\n\t\t}\n\t\tconst newGroups = new Set(groups);\n\n\t\tconst current = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t.select([\"content_taxonomies.taxonomy_id as group\"])\n\t\t\t.distinct()\n\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryId)\n\t\t\t.where(\"taxonomies.name\", \"=\", taxonomyName)\n\t\t\t.execute();\n\t\tconst currentGroups = new Set(current.map((r) => r.group));\n\n\t\tconst toRemove = [...currentGroups].filter((g) => !newGroups.has(g));\n\t\tif (toRemove.length > 0) {\n\t\t\tawait this.db\n\t\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t\t.where(\"taxonomy_id\", \"in\", toRemove)\n\t\t\t\t.execute();\n\t\t}\n\n\t\tconst toAdd = [...newGroups].filter((g) => !currentGroups.has(g));\n\t\tif (toAdd.length > 0) {\n\t\t\tconst denorm = await this.fetchEntryDenorm(collection, entryId);\n\t\t\tawait this.db\n\t\t\t\t.insertInto(\"content_taxonomies\")\n\t\t\t\t.values(\n\t\t\t\t\ttoAdd.map((taxonomy_id) => ({\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tentry_id: entryId,\n\t\t\t\t\t\ttaxonomy_id,\n\t\t\t\t\t\t...denorm,\n\t\t\t\t\t})),\n\t\t\t\t)\n\t\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t\t.execute();\n\t\t}\n\n\t\tif (toRemove.length > 0 || toAdd.length > 0) invalidateTaxonomyObjectCache();\n\t}\n\n\tasync clearEntryTerms(collection: string, entryId: string): Promise<number> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t.executeTakeFirst();\n\t\tconst removed = Number(result.numDeletedRows ?? 0);\n\t\tif (removed > 0) invalidateTaxonomyObjectCache();\n\t\treturn removed;\n\t}\n\n\t/**\n\t * Copy every term assignment from one content entry to another. Used when\n\t * creating a translation of a post so the new translation inherits the\n\t * source's term assignments. Safe to call when the source has no terms.\n\t */\n\tasync copyEntryTerms(\n\t\tcollection: string,\n\t\tsourceEntryId: string,\n\t\ttargetEntryId: string,\n\t): Promise<void> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select([\"taxonomy_id\"])\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", sourceEntryId)\n\t\t\t.execute();\n\t\tif (rows.length === 0) return;\n\n\t\t// Stamp the TARGET entry's current values — the copy inherits the source's\n\t\t// term memberships but the target's own status/dates/locale.\n\t\tconst denorm = await this.fetchEntryDenorm(collection, targetEntryId);\n\t\tawait this.db\n\t\t\t.insertInto(\"content_taxonomies\")\n\t\t\t.values(\n\t\t\t\trows.map((r) => ({\n\t\t\t\t\tcollection,\n\t\t\t\t\tentry_id: targetEntryId,\n\t\t\t\t\ttaxonomy_id: r.taxonomy_id,\n\t\t\t\t\t...denorm,\n\t\t\t\t})),\n\t\t\t)\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.execute();\n\t\tinvalidateTaxonomyObjectCache();\n\t}\n\n\t/**\n\t * Read the denormalized filter + sort columns from an entry's `ec_*` row so\n\t * they can be stamped onto new pivot rows (migration 051). A missing table or\n\t * missing row yields all-nulls: the pivot columns are advisory, and the\n\t * listing read path re-checks the authoritative `ec_*` row regardless.\n\t */\n\tprivate async fetchEntryDenorm(collection: string, entryId: string): Promise<PivotDenorm> {\n\t\tvalidateIdentifier(collection, \"collection type\");\n\t\tconst tableName = `ec_${collection}`;\n\t\ttry {\n\t\t\tconst result = await sql<PivotDenorm>`\n\t\t\t\tSELECT status, scheduled_at, deleted_at, locale, published_at, created_at\n\t\t\t\tFROM ${sql.ref(tableName)}\n\t\t\t\tWHERE id = ${entryId}\n\t\t\t`.execute(this.db);\n\t\t\treturn result.rows[0] ?? EMPTY_DENORM;\n\t\t} catch (error) {\n\t\t\tif (isMissingTableError(error)) return EMPTY_DENORM;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Count content entries that use any translation of this term. Accepts\n\t * either a term id or a translation_group — we normalise to the group.\n\t *\n\t * Counts raw pivot rows regardless of the entry's status or deletion —\n\t * drafts and trashed entries are included. User-facing counts (admin term\n\t * list/get, public widget and term pages) use `fetchVisibleTermCounts`\n\t * from `taxonomies/term-counts.ts` instead, which counts only publicly\n\t * visible entries.\n\t */\n\tasync countEntriesWithTerm(termIdOrGroup: string): Promise<number> {\n\t\tconst group = await this.resolveTranslationGroup(termIdOrGroup);\n\t\tif (!group) return 0;\n\n\t\tconst result = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select((eb) => eb.fn.count(\"entry_id\").as(\"count\"))\n\t\t\t.where(\"taxonomy_id\", \"=\", group)\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/**\n\t * Resolve a parent reference (a row id or a translation_group) to the value\n\t * persisted in `parent_id`: the parent's translation_group, which is\n\t * locale-agnostic so the child stays nested in every locale. A\n\t * translation_group normally equals its anchor row's id, which satisfies the\n\t * self-FK on `parent_id`. If that anchor row is missing (a translation whose\n\t * anchor was deleted), fall back to the id we were given so we never write a\n\t * dangling FK value.\n\t */\n\tprivate async resolveParentRef(idOrGroup: string): Promise<string> {\n\t\tconst group = await this.resolveTranslationGroup(idOrGroup);\n\t\tif (!group) return idOrGroup;\n\t\tconst anchor = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"id\", \"=\", group)\n\t\t\t.executeTakeFirst();\n\t\treturn anchor ? group : idOrGroup;\n\t}\n\n\tprivate async resolveTranslationGroup(idOrGroup: string): Promise<string | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.select([\"translation_group\"])\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\treturn row?.translation_group ?? null;\n\t}\n\n\t/**\n\t * Batch count entries for multiple taxonomy translation_groups.\n\t * Chunks the query at SQL_BATCH_SIZE to stay below D1's bind-parameter limit.\n\t * Returns a Map from translation_group to count.\n\t *\n\t * Pass translation_groups (not term ids) — `content_taxonomies.taxonomy_id`\n\t * stores the translation_group so a single assignment spans every locale.\n\t *\n\t * Like `countEntriesWithTerm`, this counts raw pivot rows regardless of\n\t * status/deletion; user-facing counts go through `fetchVisibleTermCounts`.\n\t */\n\tasync countEntriesForTerms(translationGroups: string[]): Promise<Map<string, number>> {\n\t\tif (translationGroups.length === 0) return new Map();\n\n\t\tconst { chunks, SQL_BATCH_SIZE } = await import(\"../../utils/chunks.js\");\n\n\t\tconst counts = new Map<string, number>();\n\t\tfor (const chunk of chunks(translationGroups, SQL_BATCH_SIZE)) {\n\t\t\tconst rows = await this.db\n\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t.select([\"taxonomy_id\", (eb) => eb.fn.count(\"entry_id\").as(\"count\")])\n\t\t\t\t.where(\"taxonomy_id\", \"in\", chunk)\n\t\t\t\t.groupBy(\"taxonomy_id\")\n\t\t\t\t.execute();\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tcounts.set(row.taxonomy_id, Number(row.count || 0));\n\t\t\t}\n\t\t}\n\t\treturn counts;\n\t}\n\n\tprivate rowToTaxonomy(row: Selectable<TaxonomyTable>): Taxonomy {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\tname: row.name,\n\t\t\tslug: row.slug,\n\t\t\tlabel: row.label,\n\t\t\tparentId: row.parent_id,\n\t\t\tdata: row.data ? JSON.parse(row.data) : null,\n\t\t\tlocale: row.locale,\n\t\t\ttranslationGroup: row.translation_group,\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;AAsBA,MAAM,eAA4B;CACjC,QAAQ;CACR,cAAc;CACd,YAAY;CACZ,QAAQ;CACR,cAAc;CACd,YAAY;CACZ;;;;;;;;;;;;AAiDD,IAAa,qBAAb,MAAgC;CAC/B,YAAY,AAAQ,IAAsB;EAAtB;;;;;;;CAOpB,MAAM,OAAO,OAA+C;EAC3D,MAAM,KAAK,MAAM;EAQjB,MAAM,cACL,MAAM,aAAa,UAAa,MAAM,aAAa,KAAK,OAAO,MAAM;EACtE,MAAM,WAAW,cAAc,MAAM,KAAK,iBAAiB,YAAY,GAAG;EAE1E,IAAI,mBAAmB;AACvB,MAAI,MAAM,eAAe;GACxB,MAAM,SAAS,MAAM,KAAK,SAAS,MAAM,cAAc;AACvD,OAAI,QAAQ,iBAAkB,oBAAmB,OAAO;;AAGzD,QAAM,KAAK,GACT,WAAW,aAAa,CACxB,OAAO;GACP;GACA,MAAM,MAAM;GACZ,MAAM,MAAM;GACZ,OAAO,MAAM;GACb,WAAW;GACX,MAAM,MAAM,OAAO,KAAK,UAAU,MAAM,KAAK,GAAG;GAIhD,GAAI,MAAM,WAAW,SAAY,EAAE,QAAQ,MAAM,QAAQ,GAAG,EAAE;GAC9D,mBAAmB;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GR,AAAQ,cAAc,KAA0C;AAC/D,SAAO;GACN,IAAI,IAAI;GACR,MAAM,IAAI;GACV,MAAM,IAAI;GACV,OAAO,IAAI;GACX,UAAU,IAAI;GACd,MAAM,IAAI,OAAO,KAAK,MAAM,IAAI,KAAK,GAAG;GACxC,QAAQ,IAAI;GACZ,kBAAkB,IAAI;GACtB"}
1
+ {"version":3,"file":"taxonomy-0mCI25HN.mjs","names":[],"sources":["../src/database/repositories/taxonomy.ts"],"sourcesContent":["import { sql, type Kysely, type Selectable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { invalidateTaxonomyObjectCache } from \"../../object-cache/index.js\";\nimport { isMissingTableError } from \"../../utils/db-errors.js\";\nimport type { Database, TaxonomyTable } from \"../types.js\";\nimport { validateIdentifier } from \"../validate.js\";\n\n/**\n * Filter + sort columns denormalized from an entry's `ec_*` row onto its\n * `content_taxonomies` pivot rows (migration 051). Stamped at insert time so a\n * newly-tagged entry is immediately seekable by a taxonomy-filtered listing.\n */\ninterface PivotDenorm {\n\tstatus: string | null;\n\tscheduled_at: string | null;\n\tdeleted_at: string | null;\n\tlocale: string | null;\n\tpublished_at: string | null;\n\tcreated_at: string | null;\n}\n\nconst EMPTY_DENORM: PivotDenorm = {\n\tstatus: null,\n\tscheduled_at: null,\n\tdeleted_at: null,\n\tlocale: null,\n\tpublished_at: null,\n\tcreated_at: null,\n};\n\nexport interface Taxonomy {\n\tid: string;\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparentId: string | null;\n\tdata: Record<string, unknown> | null;\n\tlocale: string;\n\ttranslationGroup: string | null;\n}\n\nexport interface CreateTaxonomyInput {\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparentId?: string;\n\tdata?: Record<string, unknown>;\n\t/** Omit to let the DB default (current value: 'en') apply. Higher layers\n\t * resolve the locale from the request context / i18n config. */\n\tlocale?: string;\n\t/** When set, links the new term into the source term's translation_group. */\n\ttranslationOf?: string;\n}\n\nexport interface UpdateTaxonomyInput {\n\tslug?: string;\n\tlabel?: string;\n\tparentId?: string | null;\n\tdata?: Record<string, unknown>;\n}\n\nexport interface FindOptions {\n\tparentId?: string | null;\n\tlocale?: string;\n}\n\n/**\n * Taxonomy repository for categories, tags, and other classification.\n *\n * Terms are per-locale. Translations of the same term share a `translation_group`\n * ULID. `content_taxonomies.taxonomy_id` stores the translation_group so a single\n * association spans every locale of a post.\n *\n * The repository does not resolve locale fallbacks on its own — callers supply\n * the locale they want. Runtime helpers and handlers use `getFallbackChain()`\n * from `i18n/config` when they need fallback behaviour.\n */\nexport class TaxonomyRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Create a new taxonomy term. When `translationOf` is set the new row joins\n\t * the source term's translation_group; otherwise a fresh group is minted\n\t * (matching the migration backfill pattern `translation_group = id`).\n\t */\n\tasync create(input: CreateTaxonomyInput): Promise<Taxonomy> {\n\t\tconst id = ulid();\n\n\t\t// Empty-string parentId is coerced to null defensively. Higher layers\n\t\t// also normalize this — see handleTermCreate / handleTermUpdate.\n\t\t// `parent_id` stores the parent's locale-agnostic translation_group (not a\n\t\t// row id), mirroring content_taxonomies.taxonomy_id, so a child stays\n\t\t// nested in every locale's tree. resolveTranslationGroup accepts either a\n\t\t// row id or an already-resolved group, so this is idempotent.\n\t\tconst parentInput =\n\t\t\tinput.parentId === undefined || input.parentId === \"\" ? null : input.parentId;\n\t\tconst parentId = parentInput ? await this.resolveParentRef(parentInput) : null;\n\n\t\tlet translationGroup = id;\n\t\tif (input.translationOf) {\n\t\t\tconst source = await this.findById(input.translationOf);\n\t\t\tif (source?.translationGroup) translationGroup = source.translationGroup;\n\t\t}\n\n\t\tawait this.db\n\t\t\t.insertInto(\"taxonomies\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tname: input.name,\n\t\t\t\tslug: input.slug,\n\t\t\t\tlabel: input.label,\n\t\t\t\tparent_id: parentId,\n\t\t\t\tdata: input.data ? JSON.stringify(input.data) : null,\n\t\t\t\t// When omitted, the DB DEFAULT 'en' is used — keeps behaviour\n\t\t\t\t// consistent with ContentRepository and lets higher layers\n\t\t\t\t// supply an explicit locale from request context.\n\t\t\t\t...(input.locale !== undefined ? { locale: input.locale } : {}),\n\t\t\t\ttranslation_group: translationGroup,\n\t\t\t})\n\t\t\t.execute();\n\n\t\tinvalidateTaxonomyObjectCache();\n\n\t\tconst taxonomy = await this.findById(id);\n\t\tif (!taxonomy) throw new Error(\"Failed to create taxonomy\");\n\t\treturn taxonomy;\n\t}\n\n\tasync findById(id: string): Promise<Taxonomy | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? this.rowToTaxonomy(row) : null;\n\t}\n\n\t/**\n\t * Find a term by (name, slug). When `locale` is provided, filter by it.\n\t * When omitted, returns the lowest-locale-code match (deterministic across\n\t * calls). Mirrors `ContentRepository.findBySlug`.\n\t */\n\tasync findBySlug(name: string, slug: string, locale?: string): Promise<Taxonomy | null> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.where(\"slug\", \"=\", slug);\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst row = await query.orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t\treturn row ? this.rowToTaxonomy(row) : null;\n\t}\n\n\t/**\n\t * Get all terms for a taxonomy (e.g., all categories).\n\t *\n\t * `id asc` is a stable tiebreaker for terms that share a label. Without it\n\t * the SQL ordering is implementation-defined when labels match, which\n\t * breaks keyset pagination over `(label, id)`.\n\t */\n\tasync findByName(name: string, options: FindOptions = {}): Promise<Taxonomy[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", name)\n\t\t\t.orderBy(\"label\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\n\t\tif (options.locale !== undefined) query = query.where(\"locale\", \"=\", options.locale);\n\n\t\tif (options.parentId !== undefined) {\n\t\t\tif (options.parentId === null) {\n\t\t\t\tquery = query.where(\"parent_id\", \"is\", null);\n\t\t\t} else {\n\t\t\t\tquery = query.where(\"parent_id\", \"=\", options.parentId);\n\t\t\t}\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\t/**\n\t * Children of a term. Accepts a term id OR a translation_group and resolves\n\t * to the group, since `parent_id` stores the parent's translation_group.\n\t * Pass `locale` to scope to one locale's tree (children share the parent's\n\t * group across locales); omit it to find children in every locale (used to\n\t * block deletes that would orphan a sibling translation's subtree).\n\t */\n\tasync findChildren(parentIdOrGroup: string, locale?: string): Promise<Taxonomy[]> {\n\t\tconst group = await this.resolveTranslationGroup(parentIdOrGroup);\n\t\tif (!group) return [];\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"parent_id\", \"=\", group)\n\t\t\t.orderBy(\"label\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\t/**\n\t * Every translation sibling of a term (including itself), identified by\n\t * their shared `translation_group`.\n\t */\n\tasync findTranslations(translationGroup: string): Promise<Taxonomy[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", translationGroup)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\tasync update(id: string, input: UpdateTaxonomyInput): Promise<Taxonomy | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return null;\n\n\t\tconst updates: Record<string, unknown> = {};\n\t\tif (input.slug !== undefined) updates.slug = input.slug;\n\t\tif (input.label !== undefined) updates.label = input.label;\n\t\tif (input.parentId !== undefined) {\n\t\t\t// Defense in depth: empty-string parentId means null (no parent).\n\t\t\t// Otherwise persist the parent's translation_group (locale-agnostic),\n\t\t\t// matching create() — see the note there.\n\t\t\tupdates.parent_id =\n\t\t\t\tinput.parentId === \"\" || input.parentId === null\n\t\t\t\t\t? null\n\t\t\t\t\t: await this.resolveParentRef(input.parentId);\n\t\t}\n\t\tif (input.data !== undefined) updates.data = JSON.stringify(input.data);\n\n\t\tif (Object.keys(updates).length > 0) {\n\t\t\tawait this.db.updateTable(\"taxonomies\").set(updates).where(\"id\", \"=\", id).execute();\n\t\t\tinvalidateTaxonomyObjectCache();\n\t\t}\n\n\t\treturn this.findById(id);\n\t}\n\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst term = await this.findById(id);\n\t\tif (!term) return false;\n\n\t\t// When deleting the last translation of a group the pivot rows that\n\t\t// reference that translation_group become orphaned — purge them.\n\t\tif (term.translationGroup) {\n\t\t\tconst siblings = await this.db\n\t\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t\t.select(\"id\")\n\t\t\t\t.where(\"translation_group\", \"=\", term.translationGroup)\n\t\t\t\t.where(\"id\", \"!=\", id)\n\t\t\t\t.execute();\n\t\t\tif (siblings.length === 0) {\n\t\t\t\tawait this.db\n\t\t\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t\t\t.where(\"taxonomy_id\", \"=\", term.translationGroup)\n\t\t\t\t\t.execute();\n\t\t\t}\n\t\t}\n\n\t\tconst result = await this.db.deleteFrom(\"taxonomies\").where(\"id\", \"=\", id).executeTakeFirst();\n\t\tinvalidateTaxonomyObjectCache();\n\t\treturn (result.numDeletedRows ?? 0n) > 0n;\n\t}\n\n\t// --- Content-Taxonomy Junction (taxonomy_id stores the translation_group) ---\n\n\tasync attachToEntry(collection: string, entryId: string, taxonomyId: string): Promise<void> {\n\t\tconst group = await this.resolveTranslationGroup(taxonomyId);\n\t\tif (!group) return;\n\n\t\tconst denorm = await this.fetchEntryDenorm(collection, entryId);\n\t\tawait this.db\n\t\t\t.insertInto(\"content_taxonomies\")\n\t\t\t.values({ collection, entry_id: entryId, taxonomy_id: group, ...denorm })\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.execute();\n\t\tinvalidateTaxonomyObjectCache();\n\t}\n\n\tasync detachFromEntry(collection: string, entryId: string, taxonomyId: string): Promise<void> {\n\t\tconst group = await this.resolveTranslationGroup(taxonomyId);\n\t\tif (!group) return;\n\n\t\tawait this.db\n\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t.where(\"taxonomy_id\", \"=\", group)\n\t\t\t.execute();\n\t\tinvalidateTaxonomyObjectCache();\n\t}\n\n\t/**\n\t * Taxonomy terms assigned to a content entry, resolved into a specific locale.\n\t * Terms whose translation_group lacks a row in the requested locale are\n\t * omitted — callers wanting fallback behaviour apply it themselves.\n\t */\n\tasync getTermsForEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\ttaxonomyName?: string,\n\t\tlocale?: string,\n\t): Promise<Taxonomy[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t.selectAll(\"taxonomies\")\n\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryId);\n\n\t\tif (taxonomyName) query = query.where(\"taxonomies.name\", \"=\", taxonomyName);\n\t\tif (locale !== undefined) query = query.where(\"taxonomies.locale\", \"=\", locale);\n\n\t\tconst rows = await query.orderBy(\"taxonomies.locale\", \"asc\").execute();\n\t\treturn rows.map((row) => this.rowToTaxonomy(row));\n\t}\n\n\t/**\n\t * Replace all assignments of a given taxonomy for one content entry.\n\t * Term ids OR translation_groups are accepted and normalised to groups.\n\t */\n\tasync setTermsForEntry(\n\t\tcollection: string,\n\t\tentryId: string,\n\t\ttaxonomyName: string,\n\t\ttermIds: string[],\n\t): Promise<void> {\n\t\tconst groups: string[] = [];\n\t\tfor (const id of termIds) {\n\t\t\tconst group = await this.resolveTranslationGroup(id);\n\t\t\tif (group) groups.push(group);\n\t\t}\n\t\tconst newGroups = new Set(groups);\n\n\t\tconst current = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.innerJoin(\"taxonomies\", \"taxonomies.translation_group\", \"content_taxonomies.taxonomy_id\")\n\t\t\t.select([\"content_taxonomies.taxonomy_id as group\"])\n\t\t\t.distinct()\n\t\t\t.where(\"content_taxonomies.collection\", \"=\", collection)\n\t\t\t.where(\"content_taxonomies.entry_id\", \"=\", entryId)\n\t\t\t.where(\"taxonomies.name\", \"=\", taxonomyName)\n\t\t\t.execute();\n\t\tconst currentGroups = new Set(current.map((r) => r.group));\n\n\t\tconst toRemove = [...currentGroups].filter((g) => !newGroups.has(g));\n\t\tif (toRemove.length > 0) {\n\t\t\tawait this.db\n\t\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t\t.where(\"taxonomy_id\", \"in\", toRemove)\n\t\t\t\t.execute();\n\t\t}\n\n\t\tconst toAdd = [...newGroups].filter((g) => !currentGroups.has(g));\n\t\tif (toAdd.length > 0) {\n\t\t\tconst denorm = await this.fetchEntryDenorm(collection, entryId);\n\t\t\tawait this.db\n\t\t\t\t.insertInto(\"content_taxonomies\")\n\t\t\t\t.values(\n\t\t\t\t\ttoAdd.map((taxonomy_id) => ({\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\tentry_id: entryId,\n\t\t\t\t\t\ttaxonomy_id,\n\t\t\t\t\t\t...denorm,\n\t\t\t\t\t})),\n\t\t\t\t)\n\t\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t\t.execute();\n\t\t}\n\n\t\tif (toRemove.length > 0 || toAdd.length > 0) invalidateTaxonomyObjectCache();\n\t}\n\n\tasync clearEntryTerms(collection: string, entryId: string): Promise<number> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"content_taxonomies\")\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", entryId)\n\t\t\t.executeTakeFirst();\n\t\tconst removed = Number(result.numDeletedRows ?? 0);\n\t\tif (removed > 0) invalidateTaxonomyObjectCache();\n\t\treturn removed;\n\t}\n\n\t/**\n\t * Copy every term assignment from one content entry to another. Used when\n\t * creating a translation of a post so the new translation inherits the\n\t * source's term assignments. Safe to call when the source has no terms.\n\t */\n\tasync copyEntryTerms(\n\t\tcollection: string,\n\t\tsourceEntryId: string,\n\t\ttargetEntryId: string,\n\t): Promise<void> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select([\"taxonomy_id\"])\n\t\t\t.where(\"collection\", \"=\", collection)\n\t\t\t.where(\"entry_id\", \"=\", sourceEntryId)\n\t\t\t.execute();\n\t\tif (rows.length === 0) return;\n\n\t\t// Stamp the TARGET entry's current values — the copy inherits the source's\n\t\t// term memberships but the target's own status/dates/locale.\n\t\tconst denorm = await this.fetchEntryDenorm(collection, targetEntryId);\n\t\tawait this.db\n\t\t\t.insertInto(\"content_taxonomies\")\n\t\t\t.values(\n\t\t\t\trows.map((r) => ({\n\t\t\t\t\tcollection,\n\t\t\t\t\tentry_id: targetEntryId,\n\t\t\t\t\ttaxonomy_id: r.taxonomy_id,\n\t\t\t\t\t...denorm,\n\t\t\t\t})),\n\t\t\t)\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.execute();\n\t\tinvalidateTaxonomyObjectCache();\n\t}\n\n\t/**\n\t * Read the denormalized filter + sort columns from an entry's `ec_*` row so\n\t * they can be stamped onto new pivot rows (migration 051). A missing table or\n\t * missing row yields all-nulls: the pivot columns are advisory, and the\n\t * listing read path re-checks the authoritative `ec_*` row regardless.\n\t */\n\tprivate async fetchEntryDenorm(collection: string, entryId: string): Promise<PivotDenorm> {\n\t\tvalidateIdentifier(collection, \"collection type\");\n\t\tconst tableName = `ec_${collection}`;\n\t\ttry {\n\t\t\tconst result = await sql<PivotDenorm>`\n\t\t\t\tSELECT status, scheduled_at, deleted_at, locale, published_at, created_at\n\t\t\t\tFROM ${sql.ref(tableName)}\n\t\t\t\tWHERE id = ${entryId}\n\t\t\t`.execute(this.db);\n\t\t\treturn result.rows[0] ?? EMPTY_DENORM;\n\t\t} catch (error) {\n\t\t\tif (isMissingTableError(error)) return EMPTY_DENORM;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Count content entries that use any translation of this term. Accepts\n\t * either a term id or a translation_group — we normalise to the group.\n\t *\n\t * Counts raw pivot rows regardless of the entry's status or deletion —\n\t * drafts and trashed entries are included. User-facing counts (admin term\n\t * list/get, public widget and term pages) use `fetchVisibleTermCounts`\n\t * from `taxonomies/term-counts.ts` instead, which counts only publicly\n\t * visible entries.\n\t */\n\tasync countEntriesWithTerm(termIdOrGroup: string): Promise<number> {\n\t\tconst group = await this.resolveTranslationGroup(termIdOrGroup);\n\t\tif (!group) return 0;\n\n\t\tconst result = await this.db\n\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t.select((eb) => eb.fn.count(\"entry_id\").as(\"count\"))\n\t\t\t.where(\"taxonomy_id\", \"=\", group)\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/**\n\t * Resolve a parent reference (a row id or a translation_group) to the value\n\t * persisted in `parent_id`: the parent's translation_group, which is\n\t * locale-agnostic so the child stays nested in every locale. A\n\t * translation_group normally equals its anchor row's id, which satisfies the\n\t * self-FK on `parent_id`. If that anchor row is missing (a translation whose\n\t * anchor was deleted), fall back to the id we were given so we never write a\n\t * dangling FK value.\n\t */\n\tprivate async resolveParentRef(idOrGroup: string): Promise<string> {\n\t\tconst group = await this.resolveTranslationGroup(idOrGroup);\n\t\tif (!group) return idOrGroup;\n\t\tconst anchor = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"id\", \"=\", group)\n\t\t\t.executeTakeFirst();\n\t\treturn anchor ? group : idOrGroup;\n\t}\n\n\tprivate async resolveTranslationGroup(idOrGroup: string): Promise<string | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.select([\"translation_group\"])\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\treturn row?.translation_group ?? null;\n\t}\n\n\t/**\n\t * Batch count entries for multiple taxonomy translation_groups.\n\t * Chunks the query at SQL_BATCH_SIZE to stay below D1's bind-parameter limit.\n\t * Returns a Map from translation_group to count.\n\t *\n\t * Pass translation_groups (not term ids) — `content_taxonomies.taxonomy_id`\n\t * stores the translation_group so a single assignment spans every locale.\n\t *\n\t * Like `countEntriesWithTerm`, this counts raw pivot rows regardless of\n\t * status/deletion; user-facing counts go through `fetchVisibleTermCounts`.\n\t */\n\tasync countEntriesForTerms(translationGroups: string[]): Promise<Map<string, number>> {\n\t\tif (translationGroups.length === 0) return new Map();\n\n\t\tconst { chunks, SQL_BATCH_SIZE } = await import(\"../../utils/chunks.js\");\n\n\t\tconst counts = new Map<string, number>();\n\t\tfor (const chunk of chunks(translationGroups, SQL_BATCH_SIZE)) {\n\t\t\tconst rows = await this.db\n\t\t\t\t.selectFrom(\"content_taxonomies\")\n\t\t\t\t.select([\"taxonomy_id\", (eb) => eb.fn.count(\"entry_id\").as(\"count\")])\n\t\t\t\t.where(\"taxonomy_id\", \"in\", chunk)\n\t\t\t\t.groupBy(\"taxonomy_id\")\n\t\t\t\t.execute();\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tcounts.set(row.taxonomy_id, Number(row.count || 0));\n\t\t\t}\n\t\t}\n\t\treturn counts;\n\t}\n\n\tprivate rowToTaxonomy(row: Selectable<TaxonomyTable>): Taxonomy {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\tname: row.name,\n\t\t\tslug: row.slug,\n\t\t\tlabel: row.label,\n\t\t\tparentId: row.parent_id,\n\t\t\tdata: row.data ? JSON.parse(row.data) : null,\n\t\t\tlocale: row.locale,\n\t\t\ttranslationGroup: row.translation_group,\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;AAsBA,MAAM,eAA4B;CACjC,QAAQ;CACR,cAAc;CACd,YAAY;CACZ,QAAQ;CACR,cAAc;CACd,YAAY;CACZ;;;;;;;;;;;;AAiDD,IAAa,qBAAb,MAAgC;CAC/B,YAAY,AAAQ,IAAsB;EAAtB;;;;;;;CAOpB,MAAM,OAAO,OAA+C;EAC3D,MAAM,KAAK,MAAM;EAQjB,MAAM,cACL,MAAM,aAAa,UAAa,MAAM,aAAa,KAAK,OAAO,MAAM;EACtE,MAAM,WAAW,cAAc,MAAM,KAAK,iBAAiB,YAAY,GAAG;EAE1E,IAAI,mBAAmB;AACvB,MAAI,MAAM,eAAe;GACxB,MAAM,SAAS,MAAM,KAAK,SAAS,MAAM,cAAc;AACvD,OAAI,QAAQ,iBAAkB,oBAAmB,OAAO;;AAGzD,QAAM,KAAK,GACT,WAAW,aAAa,CACxB,OAAO;GACP;GACA,MAAM,MAAM;GACZ,MAAM,MAAM;GACZ,OAAO,MAAM;GACb,WAAW;GACX,MAAM,MAAM,OAAO,KAAK,UAAU,MAAM,KAAK,GAAG;GAIhD,GAAI,MAAM,WAAW,SAAY,EAAE,QAAQ,MAAM,QAAQ,GAAG,EAAE;GAC9D,mBAAmB;GACnB,CAAC,CACD,SAAS;AAEX,iCAA+B;EAE/B,MAAM,WAAW,MAAM,KAAK,SAAS,GAAG;AACxC,MAAI,CAAC,SAAU,OAAM,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AAU,IAAI;GACd,MAAM,IAAI,OAAO,KAAK,MAAM,IAAI,KAAK,GAAG;GACxC,QAAQ,IAAI;GACZ,kBAAkB,IAAI;GACtB"}
@@ -1,4 +1,4 @@
1
- import { o as __exportAll } from "./runner-DfnZ5eUr.mjs";
1
+ import { o as __exportAll } from "./runner-BdeLEgad.mjs";
2
2
  import { i as encodeBase64, t as decodeBase64 } from "./base64-B-PsqheR.mjs";
3
3
 
4
4
  //#region src/database/repositories/types.ts
@@ -85,4 +85,4 @@ var ScheduledNotDueError = class extends Error {
85
85
 
86
86
  //#endregion
87
87
  export { encodeCursor as a, decodeCursor as i, InvalidCursorError as n, types_exports as o, ScheduledNotDueError as r, EmDashValidationError as t };
88
- //# sourceMappingURL=types-D1iJ3DpO.mjs.map
88
+ //# sourceMappingURL=types-CrRUFdej.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"types-D1iJ3DpO.mjs","names":[],"sources":["../src/database/repositories/types.ts"],"sourcesContent":["import type { CustomFieldValue } from \"../../schema/types.js\";\nimport { encodeBase64, decodeBase64 } from \"../../utils/base64.js\";\n\n/**\n * Hard cap on cursor length. Cursors we issue are short JSON-in-base64\n * blobs; a real cursor is well under 200 chars. This guards against\n * malicious callers passing megabyte-sized strings to force the base64\n * decoder to allocate (decodeBase64 is O(N) in input size). The MCP and\n * REST schemas also clamp at 2048 — this 4096 cap is a defense-in-depth\n * floor inside the repository helpers.\n */\nconst MAX_CURSOR_LENGTH = 4096;\n\nexport interface CreateContentInput {\n\ttype: string;\n\tslug?: string | null;\n\tdata: Record<string, unknown>;\n\tstatus?: string;\n\tauthorId?: string;\n\tprimaryBylineId?: string | null;\n\tlocale?: string;\n\ttranslationOf?: string;\n\tpublishedAt?: string | null;\n\t/** Override created_at (ISO 8601). Used by importers to preserve original dates. */\n\tcreatedAt?: string | null;\n}\n\nexport interface UpdateContentInput {\n\tdata?: Record<string, unknown>;\n\tstatus?: string;\n\tslug?: string | null;\n\tpublishedAt?: string | null;\n\tscheduledAt?: string | null;\n\tauthorId?: string | null;\n\tprimaryBylineId?: string | null;\n}\n\n/** SEO fields for content items */\nexport interface ContentSeo {\n\ttitle: string | null;\n\tdescription: string | null;\n\timage: string | null;\n\tcanonical: string | null;\n\tnoIndex: boolean;\n}\n\n/** Input for updating SEO fields on content */\nexport interface ContentSeoInput {\n\ttitle?: string | null;\n\tdescription?: string | null;\n\timage?: string | null;\n\tcanonical?: string | null;\n\tnoIndex?: boolean;\n}\n\nexport interface BylineSummary {\n\tid: string;\n\tslug: string;\n\tdisplayName: string;\n\tbio: string | null;\n\tavatarMediaId: string | null;\n\t/**\n\t * The avatar media's storage key, folded in by a LEFT JOIN on the\n\t * `media` table during content byline hydration. Non-null only when the\n\t * byline has an avatar AND was loaded through the content-credit hydration\n\t * path (`getContentBylines` / `getContentBylinesMany`, i.e. the\n\t * `entry.data.bylines` populated by `getEmDashCollection` / `getEmDashEntry`).\n\t * The plain byline finders (`findById`, `findBySlug`, …) leave it null.\n\t *\n\t * Lets list pages build a direct storage URL for an author avatar without a\n\t * per-byline `MediaRepository.findById`, avoiding an N+1 when many distinct\n\t * authors appear on one page.\n\t *\n\t * Optional so adding it is a non-breaking change for existing code that\n\t * constructs a `BylineSummary` literal; the repositories always populate it\n\t * (to `null` when there's no avatar or no media join).\n\t */\n\tavatarStorageKey?: string | null;\n\t/** Avatar media alt text, from the same media join. Null when not joined. */\n\tavatarAlt?: string | null;\n\t/**\n\t * Avatar media blurhash (LQIP placeholder, migration 024), folded in by the\n\t * same media join as `avatarStorageKey`. Lets a renderer paint a blurred\n\t * placeholder while the full avatar loads, with no extra media lookup.\n\t * Null when the byline has no avatar, the media row has no blurhash, or the\n\t * byline was loaded through a finder that doesn't join media.\n\t */\n\tavatarBlurhash?: string | null;\n\t/**\n\t * Avatar media dominant colour (LQIP placeholder, migration 024), from the\n\t * same media join. Null under the same conditions as `avatarBlurhash`.\n\t */\n\tavatarDominantColor?: string | null;\n\twebsiteUrl: string | null;\n\tuserId: string | null;\n\tisGuest: boolean;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\t/**\n\t * Locale this byline row is presented in. Added by migration 040.\n\t * `(slug, locale)` is unique; a single slug can repeat across locales.\n\t */\n\tlocale: string;\n\t/**\n\t * Shared across translations of the same byline. Added by migration 040.\n\t * `_emdash_content_bylines.byline_id` and `ec_*.primary_byline_id` store\n\t * this value, so a credit spans every locale variant of a byline.\n\t * Nullable in storage for backwards compatibility; new rows always\n\t * populate it.\n\t */\n\ttranslationGroup: string | null;\n\t/**\n\t * Custom field values registered via the byline-fields schema (migration\n\t * 041, Discussion #1174). Optional in the TypeScript shape so existing\n\t * object-literal consumers (test fixtures, plugin renderers) stay\n\t * source-compatible; the runtime always returns `{}` when no fields are\n\t * registered. Translatable values reflect this row's locale; non-\n\t * translatable values are shared across every locale variant of the\n\t * byline's `translation_group`.\n\t */\n\tcustomFields?: Record<string, CustomFieldValue>;\n}\n\nexport interface ContentBylineCredit {\n\tbyline: BylineSummary;\n\tsortOrder: number;\n\troleLabel: string | null;\n\t/** Whether this credit was explicitly assigned or inferred from authorId */\n\tsource?: \"explicit\" | \"inferred\";\n}\n\n/** A whitelisted timestamp column a content-list date range can filter on. */\nexport type ContentDateField = \"createdAt\" | \"updatedAt\" | \"publishedAt\";\n\n/**\n * Inclusive date-range filter for a single whitelisted timestamp column.\n * Bounds are compared lexicographically against the stored ISO 8601 strings,\n * which is correct because every timestamp is written via `toISOString()`.\n * Callers wanting an inclusive upper bound should pass an end-of-day value\n * (e.g. `2024-12-31T23:59:59.999Z`); the repository does not widen `to`.\n */\nexport interface ContentDateFilter {\n\tfield: ContentDateField;\n\tfrom?: string;\n\tto?: string;\n}\n\nexport interface FindManyOptions {\n\twhere?: {\n\t\tstatus?: string;\n\t\tauthorId?: string;\n\t\tlocale?: string;\n\t\t/** Case-insensitive substring to match against `searchColumns`. */\n\t\tq?: string;\n\t\t/**\n\t\t * Columns the `q` substring filter is applied to (OR'd together).\n\t\t * Resolved by the handler from the collection's display fields so the\n\t\t * repository stays generic. Each name is validated as a SQL identifier.\n\t\t */\n\t\tsearchColumns?: string[];\n\t\t/**\n\t\t * Serve `q` from the collection's FTS5 index (`_emdash_fts_<slug>`)\n\t\t * instead of an unindexable substring LIKE. Set by the handler only\n\t\t * when the collection has search enabled and the index exists\n\t\t * (SQLite only). The repository combines a token-prefix MATCH with\n\t\t * an index-served slug prefix so slug lookups keep working.\n\t\t */\n\t\tuseFts?: boolean;\n\t\t/** Inclusive date range over a whitelisted timestamp column. */\n\t\tdateFilter?: ContentDateFilter;\n\t};\n\torderBy?: {\n\t\tfield: string;\n\t\tdirection: \"asc\" | \"desc\";\n\t};\n\tlimit?: number;\n\tcursor?: string; // Base64-encoded JSON: {orderValue: string, id: string}\n}\n\nexport interface FindManyResult<T> {\n\titems: T[];\n\tnextCursor?: string; // Base64-encoded JSON: {orderValue: string, id: string}\n\t/**\n\t * Total number of rows matching the where clause (ignoring pagination).\n\t * Optional because not every caller needs it; repositories that compute\n\t * it should set it so the UI can render a stable pagination denominator.\n\t */\n\ttotal?: number;\n}\n\n/** Encode a cursor from order value + id */\nexport function encodeCursor(orderValue: string, id: string): string {\n\treturn encodeBase64(JSON.stringify({ orderValue, id }));\n}\n\n/**\n * Thrown when a pagination cursor cannot be decoded.\n *\n * Repository callers should let this propagate; handler catch blocks\n * map it to a structured `INVALID_CURSOR` error so client pagination\n * bugs surface immediately rather than silently re-fetching the first\n * page.\n */\nexport class InvalidCursorError extends Error {\n\tconstructor(cursor: string) {\n\t\tconst display = cursor.length > 50 ? `${cursor.slice(0, 47)}...` : cursor;\n\t\tsuper(`Invalid pagination cursor: ${display}`);\n\t\tthis.name = \"InvalidCursorError\";\n\t}\n}\n\n/**\n * Decode a cursor to order value + id.\n *\n * Throws `InvalidCursorError` if the cursor is empty, not valid base64,\n * not valid JSON, or doesn't contain string `orderValue` and `id` fields.\n */\nexport function decodeCursor(cursor: string): { orderValue: string; id: string } {\n\tif (!cursor) throw new InvalidCursorError(cursor);\n\tif (cursor.length > MAX_CURSOR_LENGTH) throw new InvalidCursorError(cursor);\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(decodeBase64(cursor));\n\t} catch {\n\t\tthrow new InvalidCursorError(cursor);\n\t}\n\tif (parsed === null || typeof parsed !== \"object\") {\n\t\tthrow new InvalidCursorError(cursor);\n\t}\n\tconst candidate = parsed as { orderValue?: unknown; id?: unknown };\n\tif (typeof candidate.orderValue !== \"string\" || typeof candidate.id !== \"string\") {\n\t\tthrow new InvalidCursorError(cursor);\n\t}\n\treturn { orderValue: candidate.orderValue, id: candidate.id };\n}\n\nexport interface ContentItem {\n\tid: string;\n\ttype: string;\n\tslug: string | null;\n\tstatus: string;\n\tdata: Record<string, unknown>;\n\tauthorId: string | null;\n\tprimaryBylineId: string | null;\n\tbyline?: BylineSummary | null;\n\tbylines?: ContentBylineCredit[];\n\tcreatedAt: string;\n\tupdatedAt: string;\n\tpublishedAt: string | null;\n\tscheduledAt: string | null;\n\tliveRevisionId: string | null;\n\tdraftRevisionId: string | null;\n\tversion: number;\n\tlocale: string | null;\n\ttranslationGroup: string | null;\n\t/** SEO metadata — only populated for collections with `has_seo` enabled */\n\tseo?: ContentSeo;\n\t/**\n\t * For collections that support `revisions`: when a draft revision exists,\n\t * `data` reflects the unsaved draft and `liveData` carries the currently-\n\t * published values. When no draft exists, `liveData` is undefined.\n\t *\n\t * Hydrated by `EmDashRuntime.hydrateDraftData()` — repositories themselves\n\t * never set this field; it's purely a runtime-overlay concept that gives\n\t * agents a clear picture of \"draft vs. live\" without re-fetching the\n\t * revision history.\n\t */\n\tliveData?: Record<string, unknown>;\n}\n\nexport class EmDashValidationError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic details?: unknown,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"EmDashValidationError\";\n\t}\n}\n\n/**\n * Thrown by `publish()` when called with `requireDue` for a row that is no\n * longer due (its `scheduled_at` was cleared or pushed into the future between\n * selection and publish — e.g. an editor unscheduled it). Lets the scheduled\n * sweep skip the row silently rather than treating it as a publish failure.\n */\nexport class ScheduledNotDueError extends Error {\n\tconstructor(message = \"Content is no longer scheduled to publish\") {\n\t\tsuper(message);\n\t\tthis.name = \"ScheduledNotDueError\";\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAWA,MAAM,oBAAoB;;AAoL1B,SAAgB,aAAa,YAAoB,IAAoB;AACpE,QAAO,aAAa,KAAK,UAAU;EAAE;EAAY;EAAI,CAAC,CAAC;;;;;;;;;;AAWxD,IAAa,qBAAb,cAAwC,MAAM;CAC7C,YAAY,QAAgB;EAC3B,MAAM,UAAU,OAAO,SAAS,KAAK,GAAG,OAAO,MAAM,GAAG,GAAG,CAAC,OAAO;AACnE,QAAM,8BAA8B,UAAU;AAC9C,OAAK,OAAO;;;;;;;;;AAUd,SAAgB,aAAa,QAAoD;AAChF,KAAI,CAAC,OAAQ,OAAM,IAAI,mBAAmB,OAAO;AACjD,KAAI,OAAO,SAAS,kBAAmB,OAAM,IAAI,mBAAmB,OAAO;CAC3E,IAAI;AACJ,KAAI;AACH,WAAS,KAAK,MAAM,aAAa,OAAO,CAAC;SAClC;AACP,QAAM,IAAI,mBAAmB,OAAO;;AAErC,KAAI,WAAW,QAAQ,OAAO,WAAW,SACxC,OAAM,IAAI,mBAAmB,OAAO;CAErC,MAAM,YAAY;AAClB,KAAI,OAAO,UAAU,eAAe,YAAY,OAAO,UAAU,OAAO,SACvE,OAAM,IAAI,mBAAmB,OAAO;AAErC,QAAO;EAAE,YAAY,UAAU;EAAY,IAAI,UAAU;EAAI;;AAqC9D,IAAa,wBAAb,cAA2C,MAAM;CAChD,YACC,SACA,AAAO,SACN;AACD,QAAM,QAAQ;EAFP;AAGP,OAAK,OAAO;;;;;;;;;AAUd,IAAa,uBAAb,cAA0C,MAAM;CAC/C,YAAY,UAAU,6CAA6C;AAClE,QAAM,QAAQ;AACd,OAAK,OAAO"}
1
+ {"version":3,"file":"types-CrRUFdej.mjs","names":[],"sources":["../src/database/repositories/types.ts"],"sourcesContent":["import type { CustomFieldValue } from \"../../schema/types.js\";\nimport { encodeBase64, decodeBase64 } from \"../../utils/base64.js\";\n\n/**\n * Hard cap on cursor length. Cursors we issue are short JSON-in-base64\n * blobs; a real cursor is well under 200 chars. This guards against\n * malicious callers passing megabyte-sized strings to force the base64\n * decoder to allocate (decodeBase64 is O(N) in input size). The MCP and\n * REST schemas also clamp at 2048 — this 4096 cap is a defense-in-depth\n * floor inside the repository helpers.\n */\nconst MAX_CURSOR_LENGTH = 4096;\n\nexport interface CreateContentInput {\n\ttype: string;\n\tslug?: string | null;\n\tdata: Record<string, unknown>;\n\tstatus?: string;\n\tauthorId?: string;\n\tprimaryBylineId?: string | null;\n\tlocale?: string;\n\ttranslationOf?: string;\n\tpublishedAt?: string | null;\n\t/** Override created_at (ISO 8601). Used by importers to preserve original dates. */\n\tcreatedAt?: string | null;\n}\n\nexport interface UpdateContentInput {\n\tdata?: Record<string, unknown>;\n\tstatus?: string;\n\tslug?: string | null;\n\tpublishedAt?: string | null;\n\tscheduledAt?: string | null;\n\tauthorId?: string | null;\n\tprimaryBylineId?: string | null;\n}\n\n/** SEO fields for content items */\nexport interface ContentSeo {\n\ttitle: string | null;\n\tdescription: string | null;\n\timage: string | null;\n\tcanonical: string | null;\n\tnoIndex: boolean;\n}\n\n/** Input for updating SEO fields on content */\nexport interface ContentSeoInput {\n\ttitle?: string | null;\n\tdescription?: string | null;\n\timage?: string | null;\n\tcanonical?: string | null;\n\tnoIndex?: boolean;\n}\n\nexport interface BylineSummary {\n\tid: string;\n\tslug: string;\n\tdisplayName: string;\n\tbio: string | null;\n\tavatarMediaId: string | null;\n\t/**\n\t * The avatar media's storage key, folded in by a LEFT JOIN on the\n\t * `media` table during content byline hydration. Non-null only when the\n\t * byline has an avatar AND was loaded through the content-credit hydration\n\t * path (`getContentBylines` / `getContentBylinesMany`, i.e. the\n\t * `entry.data.bylines` populated by `getEmDashCollection` / `getEmDashEntry`).\n\t * The plain byline finders (`findById`, `findBySlug`, …) leave it null.\n\t *\n\t * Lets list pages build a direct storage URL for an author avatar without a\n\t * per-byline `MediaRepository.findById`, avoiding an N+1 when many distinct\n\t * authors appear on one page.\n\t *\n\t * Optional so adding it is a non-breaking change for existing code that\n\t * constructs a `BylineSummary` literal; the repositories always populate it\n\t * (to `null` when there's no avatar or no media join).\n\t */\n\tavatarStorageKey?: string | null;\n\t/** Avatar media alt text, from the same media join. Null when not joined. */\n\tavatarAlt?: string | null;\n\t/**\n\t * Avatar media blurhash (LQIP placeholder, migration 024), folded in by the\n\t * same media join as `avatarStorageKey`. Lets a renderer paint a blurred\n\t * placeholder while the full avatar loads, with no extra media lookup.\n\t * Null when the byline has no avatar, the media row has no blurhash, or the\n\t * byline was loaded through a finder that doesn't join media.\n\t */\n\tavatarBlurhash?: string | null;\n\t/**\n\t * Avatar media dominant colour (LQIP placeholder, migration 024), from the\n\t * same media join. Null under the same conditions as `avatarBlurhash`.\n\t */\n\tavatarDominantColor?: string | null;\n\twebsiteUrl: string | null;\n\tuserId: string | null;\n\tisGuest: boolean;\n\tcreatedAt: string;\n\tupdatedAt: string;\n\t/**\n\t * Locale this byline row is presented in. Added by migration 040.\n\t * `(slug, locale)` is unique; a single slug can repeat across locales.\n\t */\n\tlocale: string;\n\t/**\n\t * Shared across translations of the same byline. Added by migration 040.\n\t * `_emdash_content_bylines.byline_id` and `ec_*.primary_byline_id` store\n\t * this value, so a credit spans every locale variant of a byline.\n\t * Nullable in storage for backwards compatibility; new rows always\n\t * populate it.\n\t */\n\ttranslationGroup: string | null;\n\t/**\n\t * Custom field values registered via the byline-fields schema (migration\n\t * 041, Discussion #1174). Optional in the TypeScript shape so existing\n\t * object-literal consumers (test fixtures, plugin renderers) stay\n\t * source-compatible; the runtime always returns `{}` when no fields are\n\t * registered. Translatable values reflect this row's locale; non-\n\t * translatable values are shared across every locale variant of the\n\t * byline's `translation_group`.\n\t */\n\tcustomFields?: Record<string, CustomFieldValue>;\n}\n\nexport interface ContentBylineCredit {\n\tbyline: BylineSummary;\n\tsortOrder: number;\n\troleLabel: string | null;\n\t/** Whether this credit was explicitly assigned or inferred from authorId */\n\tsource?: \"explicit\" | \"inferred\";\n}\n\n/** A whitelisted timestamp column a content-list date range can filter on. */\nexport type ContentDateField = \"createdAt\" | \"updatedAt\" | \"publishedAt\";\n\n/**\n * Inclusive date-range filter for a single whitelisted timestamp column.\n * Bounds are compared lexicographically against the stored ISO 8601 strings,\n * which is correct because every timestamp is written via `toISOString()`.\n * Callers wanting an inclusive upper bound should pass an end-of-day value\n * (e.g. `2024-12-31T23:59:59.999Z`); the repository does not widen `to`.\n */\nexport interface ContentDateFilter {\n\tfield: ContentDateField;\n\tfrom?: string;\n\tto?: string;\n}\n\nexport interface FindManyOptions {\n\twhere?: {\n\t\tstatus?: string;\n\t\tauthorId?: string;\n\t\tlocale?: string;\n\t\t/** Case-insensitive substring to match against `searchColumns`. */\n\t\tq?: string;\n\t\t/**\n\t\t * Columns the `q` substring filter is applied to (OR'd together).\n\t\t * Resolved by the handler from the collection's display fields so the\n\t\t * repository stays generic. Each name is validated as a SQL identifier.\n\t\t */\n\t\tsearchColumns?: string[];\n\t\t/**\n\t\t * Serve `q` from the collection's FTS5 index (`_emdash_fts_<slug>`)\n\t\t * instead of an unindexable substring LIKE. Set by the handler only\n\t\t * when the collection has search enabled and the index exists\n\t\t * (SQLite only). The repository combines a token-prefix MATCH with\n\t\t * an index-served slug prefix so slug lookups keep working.\n\t\t */\n\t\tuseFts?: boolean;\n\t\t/** Inclusive date range over a whitelisted timestamp column. */\n\t\tdateFilter?: ContentDateFilter;\n\t};\n\torderBy?: {\n\t\tfield: string;\n\t\tdirection: \"asc\" | \"desc\";\n\t};\n\tlimit?: number;\n\tcursor?: string; // Base64-encoded JSON: {orderValue: string, id: string}\n}\n\nexport interface FindManyResult<T> {\n\titems: T[];\n\tnextCursor?: string; // Base64-encoded JSON: {orderValue: string, id: string}\n\t/**\n\t * Total number of rows matching the where clause (ignoring pagination).\n\t * Optional because not every caller needs it; repositories that compute\n\t * it should set it so the UI can render a stable pagination denominator.\n\t */\n\ttotal?: number;\n}\n\n/** Encode a cursor from order value + id */\nexport function encodeCursor(orderValue: string, id: string): string {\n\treturn encodeBase64(JSON.stringify({ orderValue, id }));\n}\n\n/**\n * Thrown when a pagination cursor cannot be decoded.\n *\n * Repository callers should let this propagate; handler catch blocks\n * map it to a structured `INVALID_CURSOR` error so client pagination\n * bugs surface immediately rather than silently re-fetching the first\n * page.\n */\nexport class InvalidCursorError extends Error {\n\tconstructor(cursor: string) {\n\t\tconst display = cursor.length > 50 ? `${cursor.slice(0, 47)}...` : cursor;\n\t\tsuper(`Invalid pagination cursor: ${display}`);\n\t\tthis.name = \"InvalidCursorError\";\n\t}\n}\n\n/**\n * Decode a cursor to order value + id.\n *\n * Throws `InvalidCursorError` if the cursor is empty, not valid base64,\n * not valid JSON, or doesn't contain string `orderValue` and `id` fields.\n */\nexport function decodeCursor(cursor: string): { orderValue: string; id: string } {\n\tif (!cursor) throw new InvalidCursorError(cursor);\n\tif (cursor.length > MAX_CURSOR_LENGTH) throw new InvalidCursorError(cursor);\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(decodeBase64(cursor));\n\t} catch {\n\t\tthrow new InvalidCursorError(cursor);\n\t}\n\tif (parsed === null || typeof parsed !== \"object\") {\n\t\tthrow new InvalidCursorError(cursor);\n\t}\n\tconst candidate = parsed as { orderValue?: unknown; id?: unknown };\n\tif (typeof candidate.orderValue !== \"string\" || typeof candidate.id !== \"string\") {\n\t\tthrow new InvalidCursorError(cursor);\n\t}\n\treturn { orderValue: candidate.orderValue, id: candidate.id };\n}\n\nexport interface ContentItem {\n\tid: string;\n\ttype: string;\n\tslug: string | null;\n\tstatus: string;\n\tdata: Record<string, unknown>;\n\tauthorId: string | null;\n\tprimaryBylineId: string | null;\n\tbyline?: BylineSummary | null;\n\tbylines?: ContentBylineCredit[];\n\tcreatedAt: string;\n\tupdatedAt: string;\n\tpublishedAt: string | null;\n\tscheduledAt: string | null;\n\tliveRevisionId: string | null;\n\tdraftRevisionId: string | null;\n\tversion: number;\n\tlocale: string | null;\n\ttranslationGroup: string | null;\n\t/** SEO metadata — only populated for collections with `has_seo` enabled */\n\tseo?: ContentSeo;\n\t/**\n\t * For collections that support `revisions`: when a draft revision exists,\n\t * `data` reflects the unsaved draft and `liveData` carries the currently-\n\t * published values. When no draft exists, `liveData` is undefined.\n\t *\n\t * Hydrated by `EmDashRuntime.hydrateDraftData()` — repositories themselves\n\t * never set this field; it's purely a runtime-overlay concept that gives\n\t * agents a clear picture of \"draft vs. live\" without re-fetching the\n\t * revision history.\n\t */\n\tliveData?: Record<string, unknown>;\n}\n\nexport class EmDashValidationError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic details?: unknown,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"EmDashValidationError\";\n\t}\n}\n\n/**\n * Thrown by `publish()` when called with `requireDue` for a row that is no\n * longer due (its `scheduled_at` was cleared or pushed into the future between\n * selection and publish — e.g. an editor unscheduled it). Lets the scheduled\n * sweep skip the row silently rather than treating it as a publish failure.\n */\nexport class ScheduledNotDueError extends Error {\n\tconstructor(message = \"Content is no longer scheduled to publish\") {\n\t\tsuper(message);\n\t\tthis.name = \"ScheduledNotDueError\";\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAWA,MAAM,oBAAoB;;AAoL1B,SAAgB,aAAa,YAAoB,IAAoB;AACpE,QAAO,aAAa,KAAK,UAAU;EAAE;EAAY;EAAI,CAAC,CAAC;;;;;;;;;;AAWxD,IAAa,qBAAb,cAAwC,MAAM;CAC7C,YAAY,QAAgB;EAC3B,MAAM,UAAU,OAAO,SAAS,KAAK,GAAG,OAAO,MAAM,GAAG,GAAG,CAAC,OAAO;AACnE,QAAM,8BAA8B,UAAU;AAC9C,OAAK,OAAO;;;;;;;;;AAUd,SAAgB,aAAa,QAAoD;AAChF,KAAI,CAAC,OAAQ,OAAM,IAAI,mBAAmB,OAAO;AACjD,KAAI,OAAO,SAAS,kBAAmB,OAAM,IAAI,mBAAmB,OAAO;CAC3E,IAAI;AACJ,KAAI;AACH,WAAS,KAAK,MAAM,aAAa,OAAO,CAAC;SAClC;AACP,QAAM,IAAI,mBAAmB,OAAO;;AAErC,KAAI,WAAW,QAAQ,OAAO,WAAW,SACxC,OAAM,IAAI,mBAAmB,OAAO;CAErC,MAAM,YAAY;AAClB,KAAI,OAAO,UAAU,eAAe,YAAY,OAAO,UAAU,OAAO,SACvE,OAAM,IAAI,mBAAmB,OAAO;AAErC,QAAO;EAAE,YAAY,UAAU;EAAY,IAAI,UAAU;EAAI;;AAqC9D,IAAa,wBAAb,cAA2C,MAAM;CAChD,YACC,SACA,AAAO,SACN;AACD,QAAM,QAAQ;EAFP;AAGP,OAAK,OAAO;;;;;;;;;AAUd,IAAa,uBAAb,cAA0C,MAAM;CAC/C,YAAY,UAAU,6CAA6C;AAClE,QAAM,QAAQ;AACd,OAAK,OAAO"}
@@ -1,5 +1,5 @@
1
- import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-BxXyunY-.mjs";
2
- import { a as encodeCursor, i as decodeCursor } from "./types-D1iJ3DpO.mjs";
1
+ import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-Bq-5DPrD.mjs";
2
+ import { a as encodeCursor, i as decodeCursor } from "./types-CrRUFdej.mjs";
3
3
  import { ulid } from "ulidx";
4
4
 
5
5
  //#region src/database/repositories/user.ts
@@ -168,4 +168,4 @@ var UserRepository = class UserRepository {
168
168
 
169
169
  //#endregion
170
170
  export { UserRepository as t };
171
- //# sourceMappingURL=user-Bh-L1qo6.mjs.map
171
+ //# sourceMappingURL=user-aTXqmXBz.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"user-Bh-L1qo6.mjs","names":[],"sources":["../src/database/repositories/user.ts"],"sourcesContent":["import type { Kysely, Selectable, Updateable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { chunks, SQL_BATCH_SIZE } from \"../../utils/chunks.js\";\nimport type { Database, UserTable } from \"../types.js\";\nimport { encodeCursor, decodeCursor, type FindManyResult } from \"./types.js\";\n\ntype UserRow = Selectable<UserTable>;\n\n/**\n * Valid role levels matching the database schema.\n * 10=subscriber, 20=contributor, 30=author, 40=editor, 50=admin\n */\nexport type UserRole = 10 | 20 | 30 | 40 | 50;\n\n/** String role names for convenience APIs */\nexport type UserRoleName = \"subscriber\" | \"contributor\" | \"author\" | \"editor\" | \"admin\";\n\nexport interface User {\n\tid: string;\n\temail: string;\n\tname: string | null;\n\trole: UserRole;\n\tavatarUrl: string | null;\n\temailVerified: boolean;\n\tdata: Record<string, unknown> | null;\n\tcreatedAt: string;\n}\n\nexport interface CreateUserInput {\n\temail: string;\n\tname?: string;\n\trole?: UserRole | UserRoleName;\n\tavatarUrl?: string;\n\tdata?: Record<string, unknown>;\n}\n\nexport interface UpdateUserInput {\n\tname?: string;\n\trole?: UserRole | UserRoleName;\n\tavatarUrl?: string | null;\n\tdata?: Record<string, unknown>;\n}\n\n/**\n * User repository for CRUD operations\n */\nexport class UserRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Create a new user\n\t */\n\tasync create(input: CreateUserInput): Promise<User> {\n\t\tconst id = ulid();\n\n\t\tconst row: Omit<UserTable, \"created_at\" | \"updated_at\" | \"disabled\"> = {\n\t\t\tid,\n\t\t\temail: input.email.toLowerCase(),\n\t\t\tname: input.name ?? null,\n\t\t\trole: UserRepository.resolveRole(input.role ?? 10),\n\t\t\tavatar_url: input.avatarUrl ?? null,\n\t\t\temail_verified: 0,\n\t\t\tdata: input.data ? JSON.stringify(input.data) : null,\n\t\t};\n\n\t\tawait this.db.insertInto(\"users\").values(row).execute();\n\n\t\tconst user = await this.findById(id);\n\t\tif (!user) {\n\t\t\tthrow new Error(\"Failed to create user\");\n\t\t}\n\t\treturn user;\n\t}\n\n\t/**\n\t * Find user by ID\n\t */\n\tasync findById(id: string): Promise<User | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"users\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.rowToUser(row) : null;\n\t}\n\n\t/**\n\t * Batch-resolve users by ID. Returns only the users that exist; missing\n\t * IDs are silently dropped. Chunked at `SQL_BATCH_SIZE` to stay within\n\t * D1's bind-parameter limit.\n\t */\n\tasync findByIds(ids: string[]): Promise<User[]> {\n\t\tconst unique = [...new Set(ids)].filter((id) => id.length > 0);\n\t\tif (unique.length === 0) return [];\n\n\t\tconst out: User[] = [];\n\t\tfor (const batch of chunks(unique, SQL_BATCH_SIZE)) {\n\t\t\tconst rows = await this.db.selectFrom(\"users\").selectAll().where(\"id\", \"in\", batch).execute();\n\t\t\tfor (const row of rows) out.push(this.rowToUser(row));\n\t\t}\n\t\treturn out;\n\t}\n\n\t/**\n\t * Find user by email (case-insensitive)\n\t */\n\tasync findByEmail(email: string): Promise<User | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"users\")\n\t\t\t.selectAll()\n\t\t\t.where(\"email\", \"=\", email.toLowerCase())\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.rowToUser(row) : null;\n\t}\n\n\t/**\n\t * List all users with cursor-based pagination\n\t */\n\tasync findMany(\n\t\toptions: {\n\t\t\trole?: UserRole | UserRoleName;\n\t\t\tlimit?: number;\n\t\t\tcursor?: string;\n\t\t} = {},\n\t): Promise<FindManyResult<User>> {\n\t\tconst limit = Math.min(Math.max(1, options.limit || 50), 100);\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"users\")\n\t\t\t.selectAll()\n\t\t\t.orderBy(\"created_at\", \"desc\")\n\t\t\t.orderBy(\"id\", \"desc\")\n\t\t\t.limit(limit + 1);\n\n\t\tif (options.role !== undefined) {\n\t\t\tquery = query.where(\"role\", \"=\", UserRepository.resolveRole(options.role));\n\t\t}\n\n\t\tif (options.cursor) {\n\t\t\tconst decoded = decodeCursor(options.cursor);\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.or([\n\t\t\t\t\teb(\"created_at\", \"<\", decoded.orderValue),\n\t\t\t\t\teb.and([eb(\"created_at\", \"=\", decoded.orderValue), eb(\"id\", \"<\", decoded.id)]),\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\tconst items = rows.slice(0, limit).map((row) => this.rowToUser(row));\n\t\tconst result: FindManyResult<User> = { items };\n\n\t\tif (rows.length > limit && items.length > 0) {\n\t\t\tconst last = items.at(-1)!;\n\t\t\tresult.nextCursor = encodeCursor(last.createdAt, last.id);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Update a user\n\t */\n\tasync update(id: string, input: UpdateUserInput): Promise<User | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return null;\n\n\t\tconst updates: Updateable<UserTable> = {};\n\t\tif (input.name !== undefined) updates.name = input.name;\n\t\tif (input.role !== undefined) updates.role = UserRepository.resolveRole(input.role);\n\t\tif (input.avatarUrl !== undefined) updates.avatar_url = input.avatarUrl;\n\t\tif (input.data !== undefined) updates.data = JSON.stringify(input.data);\n\n\t\tif (Object.keys(updates).length > 0) {\n\t\t\tawait this.db.updateTable(\"users\").set(updates).where(\"id\", \"=\", id).execute();\n\t\t}\n\n\t\treturn this.findById(id);\n\t}\n\n\t/**\n\t * Delete a user\n\t */\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst result = await this.db.deleteFrom(\"users\").where(\"id\", \"=\", id).executeTakeFirst();\n\n\t\treturn (result.numDeletedRows ?? 0) > 0;\n\t}\n\n\t/**\n\t * Count users\n\t */\n\tasync count(role?: UserRole | UserRoleName): Promise<number> {\n\t\tlet query = this.db.selectFrom(\"users\").select((eb) => eb.fn.count(\"id\").as(\"count\"));\n\n\t\tif (role !== undefined) {\n\t\t\tquery = query.where(\"role\", \"=\", UserRepository.resolveRole(role));\n\t\t}\n\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result?.count || 0);\n\t}\n\n\t/**\n\t * Check if email exists\n\t */\n\tasync emailExists(email: string): Promise<boolean> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"users\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"email\", \"=\", email.toLowerCase())\n\t\t\t.executeTakeFirst();\n\n\t\treturn !!row;\n\t}\n\n\t/**\n\t * Convert database row to User object\n\t */\n\tprivate rowToUser(row: UserRow): User {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\temail: row.email,\n\t\t\tname: row.name,\n\t\t\trole: UserRepository.toRole(row.role),\n\t\t\tavatarUrl: row.avatar_url,\n\t\t\temailVerified: row.email_verified === 1,\n\t\t\tdata: row.data ? JSON.parse(row.data) : null,\n\t\t\tcreatedAt: row.created_at,\n\t\t};\n\t}\n\n\t/** Map of role name strings to numeric levels */\n\tprivate static readonly ROLE_NAME_TO_LEVEL: Record<UserRoleName, UserRole> = {\n\t\tsubscriber: 10,\n\t\tcontributor: 20,\n\t\tauthor: 30,\n\t\teditor: 40,\n\t\tadmin: 50,\n\t};\n\n\t/** Valid numeric role levels */\n\tprivate static readonly VALID_LEVELS = new Set<number>([10, 20, 30, 40, 50]);\n\n\t/**\n\t * Resolve a role name or number to a valid numeric UserRole.\n\t * Accepts both string names (\"admin\") and numeric levels (50).\n\t */\n\tstatic resolveRole(role: UserRole | UserRoleName): UserRole {\n\t\tif (typeof role === \"string\") {\n\t\t\tconst level = UserRepository.ROLE_NAME_TO_LEVEL[role];\n\t\t\tif (level === undefined) {\n\t\t\t\tthrow new Error(`Invalid role name: ${role}`);\n\t\t\t}\n\t\t\treturn level;\n\t\t}\n\t\tif (!UserRepository.VALID_LEVELS.has(role)) {\n\t\t\tthrow new Error(`Invalid role level: ${role}`);\n\t\t}\n\t\treturn role;\n\t}\n\n\t/**\n\t * Convert a raw DB integer to a typed UserRole.\n\t * Falls back to subscriber (10) for unknown values.\n\t */\n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,KAAK,GAAG;GACxC,WAAW,IAAI;GACf;;;CAIF,OAAwB,qBAAqD;EAC5E,YAAY;EACZ,aAAa;EACb,QAAQ;EACR,QAAQ;EACR,OAAO;EACP;;CAGD,OAAwB,eAAe,IAAI,IAAY;EAAC;EAAI;EAAI;EAAI;EAAI;EAAG,CAAC;;;;;CAM5E,OAAO,YAAY,MAAyC;AAC3D,MAAI,OAAO,SAAS,UAAU;GAC7B,MAAM,QAAQ,eAAe,mBAAmB;AAChD,OAAI,UAAU,OACb,OAAM,IAAI,MAAM,sBAAsB,OAAO;AAE9C,UAAO;;AAER,MAAI,CAAC,eAAe,aAAa,IAAI,KAAK,CACzC,OAAM,IAAI,MAAM,uBAAuB,OAAO;AAE/C,SAAO;;;;;;CAOR,OAAe,OAAO,OAAyB;AAC9C,MAAI,eAAe,aAAa,IAAI,MAAM,CAAE,QAAO;AACnD,SAAO"}
1
+ {"version":3,"file":"user-aTXqmXBz.mjs","names":[],"sources":["../src/database/repositories/user.ts"],"sourcesContent":["import type { Kysely, Selectable, Updateable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { chunks, SQL_BATCH_SIZE } from \"../../utils/chunks.js\";\nimport type { Database, UserTable } from \"../types.js\";\nimport { encodeCursor, decodeCursor, type FindManyResult } from \"./types.js\";\n\ntype UserRow = Selectable<UserTable>;\n\n/**\n * Valid role levels matching the database schema.\n * 10=subscriber, 20=contributor, 30=author, 40=editor, 50=admin\n */\nexport type UserRole = 10 | 20 | 30 | 40 | 50;\n\n/** String role names for convenience APIs */\nexport type UserRoleName = \"subscriber\" | \"contributor\" | \"author\" | \"editor\" | \"admin\";\n\nexport interface User {\n\tid: string;\n\temail: string;\n\tname: string | null;\n\trole: UserRole;\n\tavatarUrl: string | null;\n\temailVerified: boolean;\n\tdata: Record<string, unknown> | null;\n\tcreatedAt: string;\n}\n\nexport interface CreateUserInput {\n\temail: string;\n\tname?: string;\n\trole?: UserRole | UserRoleName;\n\tavatarUrl?: string;\n\tdata?: Record<string, unknown>;\n}\n\nexport interface UpdateUserInput {\n\tname?: string;\n\trole?: UserRole | UserRoleName;\n\tavatarUrl?: string | null;\n\tdata?: Record<string, unknown>;\n}\n\n/**\n * User repository for CRUD operations\n */\nexport class UserRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Create a new user\n\t */\n\tasync create(input: CreateUserInput): Promise<User> {\n\t\tconst id = ulid();\n\n\t\tconst row: Omit<UserTable, \"created_at\" | \"updated_at\" | \"disabled\"> = {\n\t\t\tid,\n\t\t\temail: input.email.toLowerCase(),\n\t\t\tname: input.name ?? null,\n\t\t\trole: UserRepository.resolveRole(input.role ?? 10),\n\t\t\tavatar_url: input.avatarUrl ?? null,\n\t\t\temail_verified: 0,\n\t\t\tdata: input.data ? JSON.stringify(input.data) : null,\n\t\t};\n\n\t\tawait this.db.insertInto(\"users\").values(row).execute();\n\n\t\tconst user = await this.findById(id);\n\t\tif (!user) {\n\t\t\tthrow new Error(\"Failed to create user\");\n\t\t}\n\t\treturn user;\n\t}\n\n\t/**\n\t * Find user by ID\n\t */\n\tasync findById(id: string): Promise<User | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"users\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.rowToUser(row) : null;\n\t}\n\n\t/**\n\t * Batch-resolve users by ID. Returns only the users that exist; missing\n\t * IDs are silently dropped. Chunked at `SQL_BATCH_SIZE` to stay within\n\t * D1's bind-parameter limit.\n\t */\n\tasync findByIds(ids: string[]): Promise<User[]> {\n\t\tconst unique = [...new Set(ids)].filter((id) => id.length > 0);\n\t\tif (unique.length === 0) return [];\n\n\t\tconst out: User[] = [];\n\t\tfor (const batch of chunks(unique, SQL_BATCH_SIZE)) {\n\t\t\tconst rows = await this.db.selectFrom(\"users\").selectAll().where(\"id\", \"in\", batch).execute();\n\t\t\tfor (const row of rows) out.push(this.rowToUser(row));\n\t\t}\n\t\treturn out;\n\t}\n\n\t/**\n\t * Find user by email (case-insensitive)\n\t */\n\tasync findByEmail(email: string): Promise<User | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"users\")\n\t\t\t.selectAll()\n\t\t\t.where(\"email\", \"=\", email.toLowerCase())\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.rowToUser(row) : null;\n\t}\n\n\t/**\n\t * List all users with cursor-based pagination\n\t */\n\tasync findMany(\n\t\toptions: {\n\t\t\trole?: UserRole | UserRoleName;\n\t\t\tlimit?: number;\n\t\t\tcursor?: string;\n\t\t} = {},\n\t): Promise<FindManyResult<User>> {\n\t\tconst limit = Math.min(Math.max(1, options.limit || 50), 100);\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"users\")\n\t\t\t.selectAll()\n\t\t\t.orderBy(\"created_at\", \"desc\")\n\t\t\t.orderBy(\"id\", \"desc\")\n\t\t\t.limit(limit + 1);\n\n\t\tif (options.role !== undefined) {\n\t\t\tquery = query.where(\"role\", \"=\", UserRepository.resolveRole(options.role));\n\t\t}\n\n\t\tif (options.cursor) {\n\t\t\tconst decoded = decodeCursor(options.cursor);\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.or([\n\t\t\t\t\teb(\"created_at\", \"<\", decoded.orderValue),\n\t\t\t\t\teb.and([eb(\"created_at\", \"=\", decoded.orderValue), eb(\"id\", \"<\", decoded.id)]),\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\n\t\tconst rows = await query.execute();\n\t\tconst items = rows.slice(0, limit).map((row) => this.rowToUser(row));\n\t\tconst result: FindManyResult<User> = { items };\n\n\t\tif (rows.length > limit && items.length > 0) {\n\t\t\tconst last = items.at(-1)!;\n\t\t\tresult.nextCursor = encodeCursor(last.createdAt, last.id);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Update a user\n\t */\n\tasync update(id: string, input: UpdateUserInput): Promise<User | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return null;\n\n\t\tconst updates: Updateable<UserTable> = {};\n\t\tif (input.name !== undefined) updates.name = input.name;\n\t\tif (input.role !== undefined) updates.role = UserRepository.resolveRole(input.role);\n\t\tif (input.avatarUrl !== undefined) updates.avatar_url = input.avatarUrl;\n\t\tif (input.data !== undefined) updates.data = JSON.stringify(input.data);\n\n\t\tif (Object.keys(updates).length > 0) {\n\t\t\tawait this.db.updateTable(\"users\").set(updates).where(\"id\", \"=\", id).execute();\n\t\t}\n\n\t\treturn this.findById(id);\n\t}\n\n\t/**\n\t * Delete a user\n\t */\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst result = await this.db.deleteFrom(\"users\").where(\"id\", \"=\", id).executeTakeFirst();\n\n\t\treturn (result.numDeletedRows ?? 0) > 0;\n\t}\n\n\t/**\n\t * Count users\n\t */\n\tasync count(role?: UserRole | UserRoleName): Promise<number> {\n\t\tlet query = this.db.selectFrom(\"users\").select((eb) => eb.fn.count(\"id\").as(\"count\"));\n\n\t\tif (role !== undefined) {\n\t\t\tquery = query.where(\"role\", \"=\", UserRepository.resolveRole(role));\n\t\t}\n\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result?.count || 0);\n\t}\n\n\t/**\n\t * Check if email exists\n\t */\n\tasync emailExists(email: string): Promise<boolean> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"users\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"email\", \"=\", email.toLowerCase())\n\t\t\t.executeTakeFirst();\n\n\t\treturn !!row;\n\t}\n\n\t/**\n\t * Convert database row to User object\n\t */\n\tprivate rowToUser(row: UserRow): User {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\temail: row.email,\n\t\t\tname: row.name,\n\t\t\trole: UserRepository.toRole(row.role),\n\t\t\tavatarUrl: row.avatar_url,\n\t\t\temailVerified: row.email_verified === 1,\n\t\t\tdata: row.data ? JSON.parse(row.data) : null,\n\t\t\tcreatedAt: row.created_at,\n\t\t};\n\t}\n\n\t/** Map of role name strings to numeric levels */\n\tprivate static readonly ROLE_NAME_TO_LEVEL: Record<UserRoleName, UserRole> = {\n\t\tsubscriber: 10,\n\t\tcontributor: 20,\n\t\tauthor: 30,\n\t\teditor: 40,\n\t\tadmin: 50,\n\t};\n\n\t/** Valid numeric role levels */\n\tprivate static readonly VALID_LEVELS = new Set<number>([10, 20, 30, 40, 50]);\n\n\t/**\n\t * Resolve a role name or number to a valid numeric UserRole.\n\t * Accepts both string names (\"admin\") and numeric levels (50).\n\t */\n\tstatic resolveRole(role: UserRole | UserRoleName): UserRole {\n\t\tif (typeof role === \"string\") {\n\t\t\tconst level = UserRepository.ROLE_NAME_TO_LEVEL[role];\n\t\t\tif (level === undefined) {\n\t\t\t\tthrow new Error(`Invalid role name: ${role}`);\n\t\t\t}\n\t\t\treturn level;\n\t\t}\n\t\tif (!UserRepository.VALID_LEVELS.has(role)) {\n\t\t\tthrow new Error(`Invalid role level: ${role}`);\n\t\t}\n\t\treturn role;\n\t}\n\n\t/**\n\t * Convert a raw DB integer to a typed UserRole.\n\t * Falls back to subscriber (10) for unknown values.\n\t */\n\tprivate static toRole(level: number): UserRole {\n\t\tif (UserRepository.VALID_LEVELS.has(level)) return level as UserRole;\n\t\treturn 10;\n\t}\n}\n"],"mappings":";;;;;;;;AA+CA,IAAa,iBAAb,MAAa,eAAe;CAC3B,YAAY,AAAQ,IAAsB;EAAtB;;;;;CAKpB,MAAM,OAAO,OAAuC;EACnD,MAAM,KAAK,MAAM;EAEjB,MAAM,MAAiE;GACtE;GACA,OAAO,MAAM,MAAM,aAAa;GAChC,MAAM,MAAM,QAAQ;GACpB,MAAM,eAAe,YAAY,MAAM,QAAQ,GAAG;GAClD,YAAY,MAAM,aAAa;GAC/B,gBAAgB;GAChB,MAAM,MAAM,OAAO,KAAK,UAAU,MAAM,KAAK,GAAG;GAChD;AAED,QAAM,KAAK,GAAG,WAAW,QAAQ,CAAC,OAAO,IAAI,CAAC,SAAS;EAEvD,MAAM,OAAO,MAAM,KAAK,SAAS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1,4 +1,5 @@
1
- import { o as __exportAll } from "./runner-DfnZ5eUr.mjs";
1
+ import { o as __exportAll } from "./runner-BdeLEgad.mjs";
2
+ import { i as resolveConfiguredLocale, n as getI18nConfig } from "./config-B6b_BobR.mjs";
2
3
  import { n as FIELD_TYPES } from "./types-o7xo7VgH.mjs";
3
4
 
4
5
  //#region src/seed/validate.ts
@@ -44,6 +45,7 @@ function validateSeed(data) {
44
45
  warnings: []
45
46
  };
46
47
  const seed = data;
48
+ const defaultLocale = getI18nConfig()?.defaultLocale ?? (typeof seed.defaultLocale === "string" ? seed.defaultLocale : "en");
47
49
  if (!seed.version) errors.push("Seed must have a version field");
48
50
  else if (seed.version !== "1") errors.push(`Unsupported seed version: ${String(seed.version)}`);
49
51
  if (seed.defaultLocale !== void 0) {
@@ -89,7 +91,8 @@ function validateSeed(data) {
89
91
  const prefix = `taxonomies[${i}]`;
90
92
  if (!taxonomy.name) errors.push(`${prefix}: name is required`);
91
93
  else {
92
- const key = `${taxonomy.name}::${taxonomy.locale ?? ""}`;
94
+ const locale = resolveConfiguredLocale(taxonomy.locale ?? defaultLocale);
95
+ const key = `${taxonomy.name}::${locale}`;
93
96
  if (taxonomyNames.has(key)) errors.push(taxonomy.locale ? `${prefix}.name: duplicate taxonomy "${taxonomy.name}" in locale "${taxonomy.locale}"` : `${prefix}.name: duplicate taxonomy name "${taxonomy.name}"`);
94
97
  taxonomyNames.add(key);
95
98
  }
@@ -105,7 +108,8 @@ function validateSeed(data) {
105
108
  const termPrefix = `${prefix}.terms[${j}]`;
106
109
  if (!term.slug) errors.push(`${termPrefix}: slug is required`);
107
110
  else {
108
- const key = `${term.slug}::${term.locale ?? taxonomy.locale ?? ""}`;
111
+ const locale = resolveConfiguredLocale(term.locale ?? taxonomy.locale ?? defaultLocale);
112
+ const key = `${term.slug}::${locale}`;
109
113
  if (termSlugs.has(key)) errors.push(`${termPrefix}.slug: duplicate term slug "${term.slug}" in taxonomy "${taxonomy.name}"`);
110
114
  termSlugs.add(key);
111
115
  }
@@ -114,7 +118,7 @@ function validateSeed(data) {
114
118
  }
115
119
  if (taxonomy.hierarchical && taxonomy.terms) for (let j = 0; j < taxonomy.terms.length; j++) {
116
120
  const term = taxonomy.terms[j];
117
- const termLocale = term.locale ?? taxonomy.locale ?? "";
121
+ const termLocale = resolveConfiguredLocale(term.locale ?? taxonomy.locale ?? defaultLocale);
118
122
  if (term.parent && !termSlugs.has(`${term.parent}::${termLocale}`)) errors.push(`${prefix}.terms[${j}].parent: parent term "${term.parent}" not found in taxonomy`);
119
123
  if (term.parent === term.slug) errors.push(`${prefix}.terms[${j}].parent: term cannot be its own parent`);
120
124
  }
@@ -129,7 +133,8 @@ function validateSeed(data) {
129
133
  const prefix = `menus[${i}]`;
130
134
  if (!menu.name) errors.push(`${prefix}: name is required`);
131
135
  else {
132
- const key = `${menu.name}::${menu.locale ?? ""}`;
136
+ const locale = resolveConfiguredLocale(menu.locale ?? defaultLocale);
137
+ const key = `${menu.name}::${locale}`;
133
138
  if (menuNames.has(key)) errors.push(menu.locale ? `${prefix}.name: duplicate menu "${menu.name}" in locale "${menu.locale}"` : `${prefix}.name: duplicate menu name "${menu.name}"`);
134
139
  menuNames.add(key);
135
140
  }
@@ -352,4 +357,4 @@ function validateMenuItemRefs(items, contentIds, warnings) {
352
357
 
353
358
  //#endregion
354
359
  export { validate_exports as n, validateSeed as t };
355
- //# sourceMappingURL=validate-V9nCwq_-.mjs.map
360
+ //# sourceMappingURL=validate-CDT1jl6_.mjs.map