emdash 0.34.0 → 0.35.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 (508) hide show
  1. package/dist/{adapters-34EN2eXO.d.mts → adapters-Bb1vG41D.d.mts} +8 -1
  2. package/dist/adapters-Bb1vG41D.d.mts.map +1 -0
  3. package/dist/api/route-utils.d.mts +3 -3
  4. package/dist/api/route-utils.mjs +9 -9
  5. package/dist/api/schemas/index.d.mts +1 -1
  6. package/dist/api/schemas/index.mjs +1 -1
  7. package/dist/{api-DdAsirBe.mjs → api-BeBglVxU.mjs} +10 -10
  8. package/dist/{api-DdAsirBe.mjs.map → api-BeBglVxU.mjs.map} +1 -1
  9. package/dist/{api-tokens-CFXu8F_2.mjs → api-tokens-KO24G1Fd.mjs} +2 -2
  10. package/dist/{api-tokens-CFXu8F_2.mjs.map → api-tokens-KO24G1Fd.mjs.map} +1 -1
  11. package/dist/{apply-D5zfeD09.mjs → apply-kUDt80-G.mjs} +16 -16
  12. package/dist/{apply-D5zfeD09.mjs.map → apply-kUDt80-G.mjs.map} +1 -1
  13. package/dist/astro/index.d.mts +12 -12
  14. package/dist/astro/index.d.mts.map +1 -1
  15. package/dist/astro/index.mjs +71 -15
  16. package/dist/astro/index.mjs.map +1 -1
  17. package/dist/astro/middleware/auth.d.mts +10 -10
  18. package/dist/astro/middleware/auth.mjs +4 -4
  19. package/dist/astro/middleware/redirect.mjs +2 -2
  20. package/dist/astro/middleware/request-context.mjs +1 -1
  21. package/dist/astro/middleware/setup.mjs +1 -1
  22. package/dist/astro/middleware.d.mts +10 -10
  23. package/dist/astro/middleware.d.mts.map +1 -1
  24. package/dist/astro/middleware.mjs +143 -74
  25. package/dist/astro/middleware.mjs.map +1 -1
  26. package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs +1 -1
  27. package/dist/astro/routes/api/admin/allowed-domains/index.mjs +1 -1
  28. package/dist/astro/routes/api/admin/api-tokens/_id_.mjs +2 -2
  29. package/dist/astro/routes/api/admin/api-tokens/index.mjs +2 -2
  30. package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +2 -2
  31. package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +3 -3
  32. package/dist/astro/routes/api/admin/byline-fields/index.mjs +3 -3
  33. package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +3 -3
  34. package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +7 -7
  35. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +7 -7
  36. package/dist/astro/routes/api/admin/bylines/index.mjs +7 -7
  37. package/dist/astro/routes/api/admin/comments/_id_/status.mjs +5 -5
  38. package/dist/astro/routes/api/admin/comments/_id_.mjs +2 -2
  39. package/dist/astro/routes/api/admin/comments/bulk.mjs +3 -3
  40. package/dist/astro/routes/api/admin/comments/counts.mjs +2 -2
  41. package/dist/astro/routes/api/admin/comments/index.mjs +3 -3
  42. package/dist/astro/routes/api/admin/hooks/exclusive/_hookName_.mjs +1 -1
  43. package/dist/astro/routes/api/admin/hooks/exclusive/index.mjs +1 -1
  44. package/dist/astro/routes/api/admin/media-usage/collection-deletions/index.mjs +7 -7
  45. package/dist/astro/routes/api/admin/media-usage/collection-deletions/retry.mjs +7 -7
  46. package/dist/astro/routes/api/admin/media-usage/repair.mjs +4 -4
  47. package/dist/astro/routes/api/admin/media-usage/work/index.mjs +7 -7
  48. package/dist/astro/routes/api/admin/media-usage/work/retry.mjs +7 -7
  49. package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs +1 -1
  50. package/dist/astro/routes/api/admin/oauth-clients/index.mjs +1 -1
  51. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +28 -28
  52. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +28 -28
  53. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +28 -28
  54. package/dist/astro/routes/api/admin/plugins/_id_/mcp.mjs +1 -1
  55. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs +28 -28
  56. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +28 -28
  57. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +28 -28
  58. package/dist/astro/routes/api/admin/plugins/index.mjs +28 -28
  59. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +1 -1
  60. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +28 -28
  61. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +28 -28
  62. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +28 -28
  63. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +28 -28
  64. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +29 -29
  65. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +28 -28
  66. package/dist/astro/routes/api/admin/plugins/registry/install.mjs +29 -29
  67. package/dist/astro/routes/api/admin/plugins/updates.mjs +28 -28
  68. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +28 -28
  69. package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +1 -1
  70. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +28 -28
  71. package/dist/astro/routes/api/admin/users/_id_/index.mjs +1 -1
  72. package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +1 -1
  73. package/dist/astro/routes/api/admin/users/index.mjs +1 -1
  74. package/dist/astro/routes/api/auth/dev-bypass.d.mts.map +1 -1
  75. package/dist/astro/routes/api/auth/dev-bypass.mjs +2 -6
  76. package/dist/astro/routes/api/auth/dev-bypass.mjs.map +1 -1
  77. package/dist/astro/routes/api/auth/invite/complete.mjs +3 -3
  78. package/dist/astro/routes/api/auth/invite/index.mjs +2 -2
  79. package/dist/astro/routes/api/auth/invite/register-options.mjs +3 -3
  80. package/dist/astro/routes/api/auth/logout.mjs +1 -1
  81. package/dist/astro/routes/api/auth/magic-link/send.mjs +3 -3
  82. package/dist/astro/routes/api/auth/magic-link/verify.mjs +1 -1
  83. package/dist/astro/routes/api/auth/me.mjs +2 -2
  84. package/dist/astro/routes/api/auth/mode.mjs +1 -1
  85. package/dist/astro/routes/api/auth/oauth/_provider_/callback.mjs +2 -2
  86. package/dist/astro/routes/api/auth/oauth/_provider_.mjs +1 -1
  87. package/dist/astro/routes/api/auth/passkey/_id_.mjs +1 -1
  88. package/dist/astro/routes/api/auth/passkey/options.mjs +4 -4
  89. package/dist/astro/routes/api/auth/passkey/register/options.mjs +3 -3
  90. package/dist/astro/routes/api/auth/passkey/register/verify.mjs +3 -3
  91. package/dist/astro/routes/api/auth/passkey/verify.mjs +3 -3
  92. package/dist/astro/routes/api/auth/signup/complete.mjs +3 -3
  93. package/dist/astro/routes/api/auth/signup/request.mjs +3 -3
  94. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +5 -5
  95. package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +4 -4
  96. package/dist/astro/routes/api/content/_collection_/_id_/compare.mjs +1 -1
  97. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs +1 -1
  98. package/dist/astro/routes/api/content/_collection_/_id_/duplicate.mjs +1 -1
  99. package/dist/astro/routes/api/content/_collection_/_id_/permanent.mjs +1 -1
  100. package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs +3 -3
  101. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +2 -2
  102. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs +9 -9
  103. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs +9 -9
  104. package/dist/astro/routes/api/content/_collection_/_id_/restore.mjs +1 -1
  105. package/dist/astro/routes/api/content/_collection_/_id_/revisions.mjs +1 -1
  106. package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs +2 -2
  107. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +6 -6
  108. package/dist/astro/routes/api/content/_collection_/_id_/translations.mjs +1 -1
  109. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs +1 -1
  110. package/dist/astro/routes/api/content/_collection_/_id_.mjs +2 -2
  111. package/dist/astro/routes/api/content/_collection_/authors.mjs +1 -1
  112. package/dist/astro/routes/api/content/_collection_/index.mjs +2 -2
  113. package/dist/astro/routes/api/content/_collection_/trash.mjs +2 -2
  114. package/dist/astro/routes/api/dashboard.mjs +4 -4
  115. package/dist/astro/routes/api/import/probe.d.mts +3 -3
  116. package/dist/astro/routes/api/import/probe.mjs +5 -5
  117. package/dist/astro/routes/api/import/wordpress/analyze.mjs +1 -1
  118. package/dist/astro/routes/api/import/wordpress/execute.d.mts +11 -11
  119. package/dist/astro/routes/api/import/wordpress/execute.mjs +7 -7
  120. package/dist/astro/routes/api/import/wordpress/media.d.mts +10 -10
  121. package/dist/astro/routes/api/import/wordpress/media.mjs +2 -2
  122. package/dist/astro/routes/api/import/wordpress/prepare.mjs +4 -4
  123. package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts +11 -11
  124. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +4 -4
  125. package/dist/astro/routes/api/import/wordpress-plugin/analyze.d.mts +1 -1
  126. package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +5 -5
  127. package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +11 -11
  128. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +11 -11
  129. package/dist/astro/routes/api/manifest.mjs +2 -2
  130. package/dist/astro/routes/api/mcp.mjs +38 -38
  131. package/dist/astro/routes/api/media/_id_/confirm.mjs +2 -2
  132. package/dist/astro/routes/api/media/_id_/upload.mjs +2 -2
  133. package/dist/astro/routes/api/media/_id_/usage.mjs +6 -6
  134. package/dist/astro/routes/api/media/_id_.mjs +5 -5
  135. package/dist/astro/routes/api/media/providers/_providerId_/_itemId_.mjs +1 -1
  136. package/dist/astro/routes/api/media/providers/_providerId_/index.mjs +1 -1
  137. package/dist/astro/routes/api/media/providers/index.mjs +1 -1
  138. package/dist/astro/routes/api/media/upload-url.mjs +3 -3
  139. package/dist/astro/routes/api/media.mjs +5 -5
  140. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +3 -3
  141. package/dist/astro/routes/api/menus/_name_/items.mjs +3 -3
  142. package/dist/astro/routes/api/menus/_name_/reorder.mjs +3 -3
  143. package/dist/astro/routes/api/menus/_name_/translations.mjs +3 -3
  144. package/dist/astro/routes/api/menus/_name_.mjs +3 -3
  145. package/dist/astro/routes/api/menus/index.mjs +3 -3
  146. package/dist/astro/routes/api/oauth/authorize.mjs +5 -5
  147. package/dist/astro/routes/api/oauth/device/authorize.mjs +3 -3
  148. package/dist/astro/routes/api/oauth/device/code.mjs +4 -4
  149. package/dist/astro/routes/api/oauth/device/token.mjs +4 -4
  150. package/dist/astro/routes/api/oauth/register.mjs +1 -1
  151. package/dist/astro/routes/api/oauth/token/refresh.mjs +3 -3
  152. package/dist/astro/routes/api/oauth/token/revoke.mjs +3 -3
  153. package/dist/astro/routes/api/oauth/token.mjs +4 -4
  154. package/dist/astro/routes/api/openapi.json.mjs +1 -1
  155. package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +3 -3
  156. package/dist/astro/routes/api/redirects/404s/index.mjs +3 -3
  157. package/dist/astro/routes/api/redirects/404s/summary.mjs +3 -3
  158. package/dist/astro/routes/api/redirects/_id_.mjs +4 -4
  159. package/dist/astro/routes/api/redirects/index.mjs +4 -4
  160. package/dist/astro/routes/api/relations/_id_/index.mjs +9 -9
  161. package/dist/astro/routes/api/relations/_id_/translations.mjs +8 -8
  162. package/dist/astro/routes/api/relations/index.mjs +9 -9
  163. package/dist/astro/routes/api/revisions/_revisionId_/index.mjs +1 -1
  164. package/dist/astro/routes/api/revisions/_revisionId_/restore.mjs +1 -1
  165. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +28 -28
  166. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +28 -28
  167. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +28 -28
  168. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +28 -28
  169. package/dist/astro/routes/api/schema/collections/index.mjs +28 -28
  170. package/dist/astro/routes/api/schema/collections/reorder.mjs +28 -28
  171. package/dist/astro/routes/api/schema/index.mjs +6 -6
  172. package/dist/astro/routes/api/schema/orphans/_slug_.mjs +28 -28
  173. package/dist/astro/routes/api/schema/orphans/index.mjs +28 -28
  174. package/dist/astro/routes/api/search/enable.mjs +5 -5
  175. package/dist/astro/routes/api/search/index.mjs +4 -4
  176. package/dist/astro/routes/api/search/rebuild.mjs +5 -5
  177. package/dist/astro/routes/api/search/stats.mjs +4 -4
  178. package/dist/astro/routes/api/search/suggest.mjs +4 -4
  179. package/dist/astro/routes/api/sections/_slug_.mjs +4 -4
  180. package/dist/astro/routes/api/sections/index.mjs +4 -4
  181. package/dist/astro/routes/api/settings/backups/archives/_name_.mjs +3 -3
  182. package/dist/astro/routes/api/settings/backups/archives/index.mjs +3 -3
  183. package/dist/astro/routes/api/settings/backups/export.mjs +3 -3
  184. package/dist/astro/routes/api/settings/backups/index.mjs +3 -3
  185. package/dist/astro/routes/api/settings/email.mjs +1 -1
  186. package/dist/astro/routes/api/settings.mjs +5 -5
  187. package/dist/astro/routes/api/setup/admin-verify.mjs +4 -4
  188. package/dist/astro/routes/api/setup/admin.mjs +4 -4
  189. package/dist/astro/routes/api/setup/dev-bypass.d.mts.map +1 -1
  190. package/dist/astro/routes/api/setup/dev-bypass.mjs +18 -21
  191. package/dist/astro/routes/api/setup/dev-bypass.mjs.map +1 -1
  192. package/dist/astro/routes/api/setup/index.d.mts.map +1 -1
  193. package/dist/astro/routes/api/setup/index.mjs +15 -21
  194. package/dist/astro/routes/api/setup/index.mjs.map +1 -1
  195. package/dist/astro/routes/api/setup/status.mjs +2 -2
  196. package/dist/astro/routes/api/snapshot.mjs +4 -4
  197. package/dist/astro/routes/api/taxonomies/_name_/reorder.mjs +6 -6
  198. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +6 -6
  199. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +6 -6
  200. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +6 -6
  201. package/dist/astro/routes/api/taxonomies/_name_/translations.mjs +6 -6
  202. package/dist/astro/routes/api/taxonomies/_name_.mjs +6 -6
  203. package/dist/astro/routes/api/taxonomies/index.mjs +6 -6
  204. package/dist/astro/routes/api/themes/preview.mjs +2 -2
  205. package/dist/astro/routes/api/typegen.mjs +3 -3
  206. package/dist/astro/routes/api/well-known/auth.mjs +1 -1
  207. package/dist/astro/routes/api/well-known/oauth-authorization-server.mjs +1 -1
  208. package/dist/astro/routes/api/well-known/oauth-protected-resource.mjs +1 -1
  209. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +2 -2
  210. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +4 -4
  211. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +4 -4
  212. package/dist/astro/routes/api/widget-areas/_name_.mjs +3 -3
  213. package/dist/astro/routes/api/widget-areas/index.mjs +4 -4
  214. package/dist/astro/routes/robots.txt.mjs +2 -2
  215. package/dist/astro/routes/sitemap-_collection_.xml.mjs +2 -2
  216. package/dist/astro/routes/sitemap.xml.mjs +2 -2
  217. package/dist/astro/types.d.mts +14 -14
  218. package/dist/auth/providers/github.d.mts +1 -1
  219. package/dist/auth/providers/google.d.mts +1 -1
  220. package/dist/{authorize-1iFJzPaZ.mjs → authorize-DUElxgOQ.mjs} +1 -1
  221. package/dist/{authorize-1iFJzPaZ.mjs.map → authorize-DUElxgOQ.mjs.map} +1 -1
  222. package/dist/{backup-LHjIAVNP.mjs → backup-DWYpJlLj.mjs} +3 -3
  223. package/dist/{backup-LHjIAVNP.mjs.map → backup-DWYpJlLj.mjs.map} +1 -1
  224. package/dist/{bundle-CBEXrBnb.mjs → bundle-vn56sLos.mjs} +5 -5
  225. package/dist/{bundle-CBEXrBnb.mjs.map → bundle-vn56sLos.mjs.map} +1 -1
  226. package/dist/{byline-fields-C5S8wygO.mjs → byline-fields-txaLGoME.mjs} +1 -1
  227. package/dist/{byline-fields-C5S8wygO.mjs.map → byline-fields-txaLGoME.mjs.map} +1 -1
  228. package/dist/{byline-pEcoDps8.mjs → byline-yjvWq4ip.mjs} +4 -4
  229. package/dist/{byline-pEcoDps8.mjs.map → byline-yjvWq4ip.mjs.map} +1 -1
  230. package/dist/{bylines-DJfSfXCL.mjs → bylines-Bu7pchQ4.mjs} +3 -3
  231. package/dist/{bylines-DJfSfXCL.mjs.map → bylines-Bu7pchQ4.mjs.map} +1 -1
  232. package/dist/{bylines-BWemdX2k.mjs → bylines-DjXS5p0P.mjs} +5 -5
  233. package/dist/{bylines-BWemdX2k.mjs.map → bylines-DjXS5p0P.mjs.map} +1 -1
  234. package/dist/{cache-CBJaDy_E.mjs → cache-C46-3Irl.mjs} +2 -2
  235. package/dist/{cache-CBJaDy_E.mjs.map → cache-C46-3Irl.mjs.map} +1 -1
  236. package/dist/{challenge-store-CZyFVaad.mjs → challenge-store-SIL5DsF2.mjs} +1 -1
  237. package/dist/{challenge-store-CZyFVaad.mjs.map → challenge-store-SIL5DsF2.mjs.map} +1 -1
  238. package/dist/{chunks-DfPax1I0.mjs → chunks-fiZ8G9RJ.mjs} +2 -2
  239. package/dist/{chunks-DfPax1I0.mjs.map → chunks-fiZ8G9RJ.mjs.map} +1 -1
  240. package/dist/cli/index.mjs +551 -51
  241. package/dist/cli/index.mjs.map +1 -1
  242. package/dist/client/cf-access.d.mts +1 -1
  243. package/dist/client/index.d.mts +2 -2
  244. package/dist/client/index.mjs +2 -2
  245. package/dist/{collection-deletion-C8BugSGz.mjs → collection-deletion-DQPvMD8R.mjs} +2 -2
  246. package/dist/{collection-deletion-C8BugSGz.mjs.map → collection-deletion-DQPvMD8R.mjs.map} +1 -1
  247. package/dist/{comment-reaction-D6qfHKBc.mjs → comment-reaction-D-2J84UE.mjs} +2 -2
  248. package/dist/{comment-reaction-D6qfHKBc.mjs.map → comment-reaction-D-2J84UE.mjs.map} +1 -1
  249. package/dist/{comments-CTOuhTSX.mjs → comments-CTfZtLmM.mjs} +1 -1
  250. package/dist/{comments-CTOuhTSX.mjs.map → comments-CTfZtLmM.mjs.map} +1 -1
  251. package/dist/config-COQzTe5Q.d.mts +34 -0
  252. package/dist/config-COQzTe5Q.d.mts.map +1 -0
  253. package/dist/{content-BNfwh7xX.mjs → content-ZHCc1ngN.mjs} +3 -3
  254. package/dist/{content-BNfwh7xX.mjs.map → content-ZHCc1ngN.mjs.map} +1 -1
  255. package/dist/{content-list-query-DhQ84eVV.d.mts → content-list-query-wJ2WN8Vp.d.mts} +1 -1
  256. package/dist/{content-list-query-DhQ84eVV.d.mts.map → content-list-query-wJ2WN8Vp.d.mts.map} +1 -1
  257. package/dist/{content-refresh-DNERP4-f.mjs → content-refresh-B_8SJzuU.mjs} +2 -2
  258. package/dist/{content-refresh-DNERP4-f.mjs.map → content-refresh-B_8SJzuU.mjs.map} +1 -1
  259. package/dist/{context-DRgOvSnW.mjs → context-ZldbZcle.mjs} +7 -7
  260. package/dist/{context-DRgOvSnW.mjs.map → context-ZldbZcle.mjs.map} +1 -1
  261. package/dist/{dashboard-CB8J89rJ.mjs → dashboard-DvHbk_cv.mjs} +3 -3
  262. package/dist/{dashboard-CB8J89rJ.mjs.map → dashboard-DvHbk_cv.mjs.map} +1 -1
  263. package/dist/db/index.d.mts +4 -4
  264. package/dist/db/index.mjs +30 -7
  265. package/dist/db/index.mjs.map +1 -1
  266. package/dist/db/libsql-migrations.d.mts +11 -0
  267. package/dist/db/libsql-migrations.d.mts.map +1 -0
  268. package/dist/db/libsql-migrations.mjs +57 -0
  269. package/dist/db/libsql-migrations.mjs.map +1 -0
  270. package/dist/db/libsql.d.mts +1 -1
  271. package/dist/db/postgres-migrations.d.mts +10 -0
  272. package/dist/db/postgres-migrations.d.mts.map +1 -0
  273. package/dist/db/postgres-migrations.mjs +47 -0
  274. package/dist/db/postgres-migrations.mjs.map +1 -0
  275. package/dist/db/postgres.d.mts +1 -1
  276. package/dist/db/sqlite-migrations.d.mts +10 -0
  277. package/dist/db/sqlite-migrations.d.mts.map +1 -0
  278. package/dist/db/sqlite-migrations.mjs +28 -0
  279. package/dist/db/sqlite-migrations.mjs.map +1 -0
  280. package/dist/db/sqlite.d.mts +1 -1
  281. package/dist/{deferred-tasks-BMsa9F64.d.mts → deferred-tasks-SDWxrgzJ.d.mts} +1 -1
  282. package/dist/{deferred-tasks-BMsa9F64.d.mts.map → deferred-tasks-SDWxrgzJ.d.mts.map} +1 -1
  283. package/dist/{device-flow-CaioYGK3.mjs → device-flow-C0GdD_z8.mjs} +4 -4
  284. package/dist/{device-flow-CaioYGK3.mjs.map → device-flow-C0GdD_z8.mjs.map} +1 -1
  285. package/dist/direct-executor-CDXeJCSs.mjs +85 -0
  286. package/dist/direct-executor-CDXeJCSs.mjs.map +1 -0
  287. package/dist/{escape-C_aLKP3H.mjs → escape-DUY2r2Zs.mjs} +1 -1
  288. package/dist/{escape-C_aLKP3H.mjs.map → escape-DUY2r2Zs.mjs.map} +1 -1
  289. package/dist/{field-defs-cache-hg6QkjV9.mjs → field-defs-cache-BzwBlJrR.mjs} +2 -2
  290. package/dist/{field-defs-cache-hg6QkjV9.mjs.map → field-defs-cache-BzwBlJrR.mjs.map} +1 -1
  291. package/dist/{fts-manager-CZ-5dVwJ.mjs → fts-manager-DyZEohZC.mjs} +2 -2
  292. package/dist/{fts-manager-CZ-5dVwJ.mjs.map → fts-manager-DyZEohZC.mjs.map} +1 -1
  293. package/dist/{hreflang-DNswoYsi.mjs → hreflang-BBe83kKa.mjs} +5 -5
  294. package/dist/{hreflang-DNswoYsi.mjs.map → hreflang-BBe83kKa.mjs.map} +1 -1
  295. package/dist/{hreflang-D3Uehfv2.d.mts → hreflang-DwT2E0Sa.d.mts} +2 -2
  296. package/dist/{hreflang-D3Uehfv2.d.mts.map → hreflang-DwT2E0Sa.d.mts.map} +1 -1
  297. package/dist/identity-Ys6Dlc9C.mjs +35 -0
  298. package/dist/identity-Ys6Dlc9C.mjs.map +1 -0
  299. package/dist/{import-B41u8Rot.mjs → import-DPkLmeXO.mjs} +2 -2
  300. package/dist/{import-B41u8Rot.mjs.map → import-DPkLmeXO.mjs.map} +1 -1
  301. package/dist/{index-C3Y-rsyN.d.mts → index-BVBZj4-7.d.mts} +28 -49
  302. package/dist/index-BVBZj4-7.d.mts.map +1 -0
  303. package/dist/{index-Cof4-Fab.d.mts → index-C9KuQyO-.d.mts} +3 -3
  304. package/dist/{index-Cof4-Fab.d.mts.map → index-C9KuQyO-.d.mts.map} +1 -1
  305. package/dist/index.d.mts +21 -20
  306. package/dist/index.mjs +42 -42
  307. package/dist/{load-DmvJrtxS.mjs → load-YJ2xl3ra.mjs} +2 -2
  308. package/dist/{load-DmvJrtxS.mjs.map → load-YJ2xl3ra.mjs.map} +1 -1
  309. package/dist/{loader-DLBqRiGP.mjs → loader-CdG_Ci3H.mjs} +2 -2
  310. package/dist/{loader-DLBqRiGP.mjs.map → loader-CdG_Ci3H.mjs.map} +1 -1
  311. package/dist/manifest-builder-B252yQUf.mjs +189 -0
  312. package/dist/manifest-builder-B252yQUf.mjs.map +1 -0
  313. package/dist/media/index.d.mts +1 -1
  314. package/dist/media/local-runtime.d.mts +12 -12
  315. package/dist/media/local-runtime.mjs +2 -2
  316. package/dist/{media-allowlist-BD6HhgXA.mjs → media-allowlist-D6x-Us02.mjs} +1 -1
  317. package/dist/{media-allowlist-BD6HhgXA.mjs.map → media-allowlist-D6x-Us02.mjs.map} +1 -1
  318. package/dist/{media-upload-9yas9zGH.mjs → media-upload-CHBVn6m-.mjs} +2 -2
  319. package/dist/{media-upload-9yas9zGH.mjs.map → media-upload-CHBVn6m-.mjs.map} +1 -1
  320. package/dist/{media-usage-De3qvwjc.mjs → media-usage-BZCydfvu.mjs} +4 -4
  321. package/dist/{media-usage-De3qvwjc.mjs.map → media-usage-BZCydfvu.mjs.map} +1 -1
  322. package/dist/{media-usage-work-B9Bksh_b.mjs → media-usage-work-CLo_6tct.mjs} +2 -2
  323. package/dist/{media-usage-work-B9Bksh_b.mjs.map → media-usage-work-CLo_6tct.mjs.map} +1 -1
  324. package/dist/{menus-CC-yn1F9.mjs → menus-DSo5QeW0.mjs} +6 -6
  325. package/dist/{menus-CC-yn1F9.mjs.map → menus-DSo5QeW0.mjs.map} +1 -1
  326. package/dist/{menus-fxvEDYE6.mjs → menus-TCNSd2vp.mjs} +2 -2
  327. package/dist/{menus-fxvEDYE6.mjs.map → menus-TCNSd2vp.mjs.map} +1 -1
  328. package/dist/migrations/index.d.mts +22 -0
  329. package/dist/migrations/index.d.mts.map +1 -0
  330. package/dist/migrations/index.mjs +7 -0
  331. package/dist/{mode-Bpe-tNNy.mjs → mode-BDoH_WcF.mjs} +1 -1
  332. package/dist/{mode-Bpe-tNNy.mjs.map → mode-BDoH_WcF.mjs.map} +1 -1
  333. package/dist/{oauth-authorization-BXO1MKej.mjs → oauth-authorization-iOikmrJd.mjs} +4 -4
  334. package/dist/{oauth-authorization-BXO1MKej.mjs.map → oauth-authorization-iOikmrJd.mjs.map} +1 -1
  335. package/dist/{oauth-clients-C_DNqtRu.mjs → oauth-clients-CvI0nHMJ.mjs} +1 -1
  336. package/dist/{oauth-clients-C_DNqtRu.mjs.map → oauth-clients-CvI0nHMJ.mjs.map} +1 -1
  337. package/dist/{oauth-state-store-DwAxMtk4.mjs → oauth-state-store-Ba8KZlwW.mjs} +1 -1
  338. package/dist/{oauth-state-store-DwAxMtk4.mjs.map → oauth-state-store-Ba8KZlwW.mjs.map} +1 -1
  339. package/dist/{oauth-user-lookup-BxfZizdk.mjs → oauth-user-lookup-C5SQwGYC.mjs} +1 -1
  340. package/dist/{oauth-user-lookup-BxfZizdk.mjs.map → oauth-user-lookup-C5SQwGYC.mjs.map} +1 -1
  341. package/dist/object-cache/memory.d.mts +1 -1
  342. package/dist/{options-DRe1pIBL.d.mts → options--hhz-jZ1.d.mts} +3 -3
  343. package/dist/{options-DRe1pIBL.d.mts.map → options--hhz-jZ1.d.mts.map} +1 -1
  344. package/dist/page/index.d.mts +2 -2
  345. package/dist/{passkey-config-_2GOwwK8.mjs → passkey-config-DFAmUyuE.mjs} +1 -1
  346. package/dist/{passkey-config-_2GOwwK8.mjs.map → passkey-config-DFAmUyuE.mjs.map} +1 -1
  347. package/dist/{placeholder-CzW7Lshs.d.mts → placeholder-Dp0K3RkD.d.mts} +1 -1
  348. package/dist/{placeholder-CzW7Lshs.d.mts.map → placeholder-Dp0K3RkD.d.mts.map} +1 -1
  349. package/dist/plugin-types.d.mts +1 -1
  350. package/dist/plugin-utils.d.mts +10 -10
  351. package/dist/plugins/adapt-sandbox-entry.d.mts +10 -10
  352. package/dist/policy-TluUIxuu.mjs +45 -0
  353. package/dist/policy-TluUIxuu.mjs.map +1 -0
  354. package/dist/{portable-text-DhKbDAGr.mjs → portable-text-imBW5cHK.mjs} +1 -1
  355. package/dist/{portable-text-DhKbDAGr.mjs.map → portable-text-imBW5cHK.mjs.map} +1 -1
  356. package/dist/protocol-DjsJHTlK.d.mts +52 -0
  357. package/dist/protocol-DjsJHTlK.d.mts.map +1 -0
  358. package/dist/{query-vgZNwIhh.mjs → query-BWs7O5Il.mjs} +3 -3
  359. package/dist/{query-vgZNwIhh.mjs.map → query-BWs7O5Il.mjs.map} +1 -1
  360. package/dist/{query-BgjfiLUQ.mjs → query-zTVAR1Sl.mjs} +12 -12
  361. package/dist/{query-BgjfiLUQ.mjs.map → query-zTVAR1Sl.mjs.map} +1 -1
  362. package/dist/{rate-limit-L5anykgo.mjs → rate-limit-Bx4g9m3p.mjs} +1 -1
  363. package/dist/{rate-limit-L5anykgo.mjs.map → rate-limit-Bx4g9m3p.mjs.map} +1 -1
  364. package/dist/{redirect-KBNE3UEs.mjs → redirect-BgAOGHDq.mjs} +1 -1
  365. package/dist/{redirect-KBNE3UEs.mjs.map → redirect-BgAOGHDq.mjs.map} +1 -1
  366. package/dist/{redirects-cV9g7V-0.mjs → redirects-DTDHWH31.mjs} +2 -2
  367. package/dist/{redirects-cV9g7V-0.mjs.map → redirects-DTDHWH31.mjs.map} +1 -1
  368. package/dist/{redirects-CufRQt0Q.mjs → redirects-DyChwDkG.mjs} +1 -1
  369. package/dist/{redirects-CufRQt0Q.mjs.map → redirects-DyChwDkG.mjs.map} +1 -1
  370. package/dist/{registry-C581V4TP.mjs → registry-Cqa2I749.mjs} +6 -6
  371. package/dist/{registry-C581V4TP.mjs.map → registry-Cqa2I749.mjs.map} +1 -1
  372. package/dist/{relation-DtmAQH7s.mjs → relation-BnHB0T4J.mjs} +2 -2
  373. package/dist/{relation-DtmAQH7s.mjs.map → relation-BnHB0T4J.mjs.map} +1 -1
  374. package/dist/{relations-DItI3MN9.d.mts → relations-BHo5A8Zf.d.mts} +35 -35
  375. package/dist/{relations-DItI3MN9.d.mts.map → relations-BHo5A8Zf.d.mts.map} +1 -1
  376. package/dist/{relations-DICSyfsh.mjs → relations-D5sM5fW0.mjs} +4 -4
  377. package/dist/{relations-DICSyfsh.mjs.map → relations-D5sM5fW0.mjs.map} +1 -1
  378. package/dist/request-context.d.mts +1 -1
  379. package/dist/{runner-CgQbELYC.d.mts → runner-BYHZn3Jy.d.mts} +16 -3
  380. package/dist/runner-BYHZn3Jy.d.mts.map +1 -0
  381. package/dist/{runner-BiDvq5dv.mjs → runner-C1T11CfC.mjs} +34 -4
  382. package/dist/{runner-BiDvq5dv.mjs.map → runner-C1T11CfC.mjs.map} +1 -1
  383. package/dist/runtime.d.mts +11 -11
  384. package/dist/runtime.mjs +1 -1
  385. package/dist/{schema-CeQSNwB3.mjs → schema-2AOsSn2v.mjs} +4 -4
  386. package/dist/{schema-CeQSNwB3.mjs.map → schema-2AOsSn2v.mjs.map} +1 -1
  387. package/dist/{schema-BFyTg38T.mjs → schema-DZ5YVVZj.mjs} +3 -3
  388. package/dist/{schema-BFyTg38T.mjs.map → schema-DZ5YVVZj.mjs.map} +1 -1
  389. package/dist/{scopes-BVeuhGBE.mjs → scopes-8ClPF2bC.mjs} +2 -2
  390. package/dist/{scopes-BVeuhGBE.mjs.map → scopes-8ClPF2bC.mjs.map} +1 -1
  391. package/dist/{search-BpuPKZb0.mjs → search-u1QYdOCG.mjs} +4 -4
  392. package/dist/{search-BpuPKZb0.mjs.map → search-u1QYdOCG.mjs.map} +1 -1
  393. package/dist/{secrets-dtYs2hDo.mjs → secrets-BEgsAQEU.mjs} +1 -1
  394. package/dist/{secrets-dtYs2hDo.mjs.map → secrets-BEgsAQEU.mjs.map} +1 -1
  395. package/dist/{sections-COctk6hf.mjs → sections-DmHviGyM.mjs} +2 -2
  396. package/dist/{sections-COctk6hf.mjs.map → sections-DmHviGyM.mjs.map} +1 -1
  397. package/dist/seed/index.d.mts +2 -2
  398. package/dist/seed/index.mjs +13 -13
  399. package/dist/seo/index.d.mts +3 -3
  400. package/dist/seo/index.mjs +9 -9
  401. package/dist/{seo-CvDxfvFb.mjs → seo-Dq4G-RrO.mjs} +2 -2
  402. package/dist/{seo-CvDxfvFb.mjs.map → seo-Dq4G-RrO.mjs.map} +1 -1
  403. package/dist/{service-xMiMSTsR.mjs → service-BpArayPr.mjs} +2 -2
  404. package/dist/{service-xMiMSTsR.mjs.map → service-BpArayPr.mjs.map} +1 -1
  405. package/dist/{session-user-BzVemLkw.mjs → session-user-BEorKVT-.mjs} +1 -1
  406. package/dist/{session-user-BzVemLkw.mjs.map → session-user-BEorKVT-.mjs.map} +1 -1
  407. package/dist/{settings-BE9aqn_9.mjs → settings-DE9xtzqd.mjs} +3 -3
  408. package/dist/{settings-BE9aqn_9.mjs.map → settings-DE9xtzqd.mjs.map} +1 -1
  409. package/dist/{settings-B372MV0p.mjs → settings-xRdoUZr0.mjs} +2 -2
  410. package/dist/{settings-B372MV0p.mjs.map → settings-xRdoUZr0.mjs.map} +1 -1
  411. package/dist/{setup-complete-DF7TAfD5.mjs → setup-complete-BnT8pq_C.mjs} +1 -1
  412. package/dist/{setup-complete-DF7TAfD5.mjs.map → setup-complete-BnT8pq_C.mjs.map} +1 -1
  413. package/dist/{setup-nonce-Do-U_cg9.mjs → setup-nonce-CBitf_oQ.mjs} +1 -1
  414. package/dist/{setup-nonce-Do-U_cg9.mjs.map → setup-nonce-CBitf_oQ.mjs.map} +1 -1
  415. package/dist/{site-url-Bowsi9T-.mjs → site-url-DjpIXMXJ.mjs} +1 -1
  416. package/dist/{site-url-Bowsi9T-.mjs.map → site-url-DjpIXMXJ.mjs.map} +1 -1
  417. package/dist/{snapshot-B5h6aPMh.mjs → snapshot-BBlGkb2q.mjs} +1 -1
  418. package/dist/{snapshot-B5h6aPMh.mjs.map → snapshot-BBlGkb2q.mjs.map} +1 -1
  419. package/dist/storage/local.d.mts +1 -1
  420. package/dist/storage/local.mjs +2 -2
  421. package/dist/storage/s3.d.mts +1 -1
  422. package/dist/target-DixqqV5i.mjs +27 -0
  423. package/dist/target-DixqqV5i.mjs.map +1 -0
  424. package/dist/{taxonomies-B0o9ExNV.mjs → taxonomies-BlrncHi9.mjs} +5 -5
  425. package/dist/{taxonomies-B0o9ExNV.mjs.map → taxonomies-BlrncHi9.mjs.map} +1 -1
  426. package/dist/{taxonomies-Dk3MAklL.mjs → taxonomies-OHUIiIpI.mjs} +4 -4
  427. package/dist/{taxonomies-Dk3MAklL.mjs.map → taxonomies-OHUIiIpI.mjs.map} +1 -1
  428. package/dist/{taxonomy-CPeM8d2o.mjs → taxonomy-BqCZ1TdU.mjs} +3 -3
  429. package/dist/{taxonomy-CPeM8d2o.mjs.map → taxonomy-BqCZ1TdU.mjs.map} +1 -1
  430. package/dist/{transport--CfOflrp.mjs → transport-DBJwa-Si.mjs} +1 -1
  431. package/dist/{transport--CfOflrp.mjs.map → transport-DBJwa-Si.mjs.map} +1 -1
  432. package/dist/{transport-B_rfeU-a.d.mts → transport-RQE36APG.d.mts} +1 -1
  433. package/dist/{transport-B_rfeU-a.d.mts.map → transport-RQE36APG.d.mts.map} +1 -1
  434. package/dist/{types-CFUfyt1s.d.mts → types-BcqdcT-r.d.mts} +1 -1
  435. package/dist/{types-CFUfyt1s.d.mts.map → types-BcqdcT-r.d.mts.map} +1 -1
  436. package/dist/{types-CPx2lIGo.d.mts → types-BntycPTF.d.mts} +1 -1
  437. package/dist/{types-CPx2lIGo.d.mts.map → types-BntycPTF.d.mts.map} +1 -1
  438. package/dist/{types-C3_AbkDP.d.mts → types-C2pMvO62.d.mts} +1 -1
  439. package/dist/{types-C3_AbkDP.d.mts.map → types-C2pMvO62.d.mts.map} +1 -1
  440. package/dist/{types-DefV3OiO.d.mts → types-CXnOzDe1.d.mts} +1 -1
  441. package/dist/{types-DefV3OiO.d.mts.map → types-CXnOzDe1.d.mts.map} +1 -1
  442. package/dist/{types-D4_1Ga4L.d.mts → types-DN64_zzZ.d.mts} +3 -3
  443. package/dist/{types-D4_1Ga4L.d.mts.map → types-DN64_zzZ.d.mts.map} +1 -1
  444. package/dist/{types-CAGdePf3.d.mts → types-DQIDRKF2.d.mts} +1 -1
  445. package/dist/{types-CAGdePf3.d.mts.map → types-DQIDRKF2.d.mts.map} +1 -1
  446. package/dist/{types-BPuloofb.d.mts → types-DWRhk9xZ.d.mts} +1 -1
  447. package/dist/{types-BPuloofb.d.mts.map → types-DWRhk9xZ.d.mts.map} +1 -1
  448. package/dist/{types-X0MThr7x.d.mts → types-Dfk8KI5R.d.mts} +1 -1
  449. package/dist/{types-X0MThr7x.d.mts.map → types-Dfk8KI5R.d.mts.map} +1 -1
  450. package/dist/{types-Cs-TFLNf.d.mts → types-DrJrVCT1.d.mts} +3 -3
  451. package/dist/{types-Cs-TFLNf.d.mts.map → types-DrJrVCT1.d.mts.map} +1 -1
  452. package/dist/{upload-attempts-hlne3iA1.mjs → upload-attempts-D4FS8LT6.mjs} +1 -1
  453. package/dist/{upload-attempts-hlne3iA1.mjs.map → upload-attempts-D4FS8LT6.mjs.map} +1 -1
  454. package/dist/{user-sHgJ62SP.mjs → user-DJZfUJVE.mjs} +2 -2
  455. package/dist/{user-sHgJ62SP.mjs.map → user-DJZfUJVE.mjs.map} +1 -1
  456. package/dist/{validate-BkqIG_Uj.mjs → validate-BMLBvxOC.mjs} +2 -2
  457. package/dist/{validate-BkqIG_Uj.mjs.map → validate-BMLBvxOC.mjs.map} +1 -1
  458. package/dist/{validate-DeGtBN84.d.mts → validate-CTqt5nuE.d.mts} +5 -5
  459. package/dist/{validate-DeGtBN84.d.mts.map → validate-CTqt5nuE.d.mts.map} +1 -1
  460. package/dist/{validation-CiJb_X5o.mjs → validation-npvENUCB.mjs} +7 -7
  461. package/dist/{validation-CiJb_X5o.mjs.map → validation-npvENUCB.mjs.map} +1 -1
  462. package/dist/version-DB_fqCSI.mjs +7 -0
  463. package/dist/{version-x0NjTScG.mjs.map → version-DB_fqCSI.mjs.map} +1 -1
  464. package/dist/{widgets-Cwzvww0W.mjs → widgets-BD3ho7Rq.mjs} +2 -2
  465. package/dist/{widgets-Cwzvww0W.mjs.map → widgets-BD3ho7Rq.mjs.map} +1 -1
  466. package/dist/{wxr-taxonomies-QZjWxjyk.mjs → wxr-taxonomies-B1R3vBoD.mjs} +3 -3
  467. package/dist/{wxr-taxonomies-QZjWxjyk.mjs.map → wxr-taxonomies-B1R3vBoD.mjs.map} +1 -1
  468. package/dist/{wxr-taxonomies-CmC0ZsDr.d.mts → wxr-taxonomies-Ca68766D.d.mts} +1 -1
  469. package/dist/{wxr-taxonomies-CmC0ZsDr.d.mts.map → wxr-taxonomies-Ca68766D.d.mts.map} +1 -1
  470. package/dist/{zod-generator-D11MhxG4.mjs → zod-generator-LC-on_Vb.mjs} +2 -2
  471. package/dist/{zod-generator-D11MhxG4.mjs.map → zod-generator-LC-on_Vb.mjs.map} +1 -1
  472. package/package.json +21 -5
  473. package/src/astro/integration/index.ts +46 -14
  474. package/src/astro/integration/runtime.ts +3 -0
  475. package/src/astro/middleware/scoped-db.ts +21 -0
  476. package/src/astro/middleware.ts +67 -10
  477. package/src/astro/routes/api/auth/dev-bypass.ts +0 -4
  478. package/src/astro/routes/api/setup/dev-bypass.ts +2 -7
  479. package/src/astro/routes/api/setup/index.ts +5 -13
  480. package/src/cli/commands/migrate.ts +593 -0
  481. package/src/cli/index.ts +2 -23
  482. package/src/database/index.ts +8 -2
  483. package/src/database/migrations/policy.ts +70 -0
  484. package/src/database/migrations/runner.ts +49 -3
  485. package/src/db/adapters.ts +50 -2
  486. package/src/db/index.ts +3 -1
  487. package/src/db/libsql-migrations.ts +72 -0
  488. package/src/db/postgres-migrations.ts +59 -0
  489. package/src/db/sqlite-migrations.ts +37 -0
  490. package/src/emdash-runtime.ts +44 -15
  491. package/src/i18n/normalize.ts +31 -0
  492. package/src/index.ts +7 -1
  493. package/src/migrations/config-loader.ts +205 -0
  494. package/src/migrations/direct-executor.ts +141 -0
  495. package/src/migrations/identity.ts +46 -0
  496. package/src/migrations/index.ts +19 -0
  497. package/src/migrations/integration-metadata.ts +67 -0
  498. package/src/migrations/manifest-builder.ts +55 -0
  499. package/src/migrations/manifest-writer.ts +63 -0
  500. package/src/migrations/manifest.ts +197 -0
  501. package/src/migrations/protocol.ts +59 -0
  502. package/src/migrations/target.ts +35 -0
  503. package/src/virtual-modules.d.ts +8 -0
  504. package/dist/adapters-34EN2eXO.d.mts.map +0 -1
  505. package/dist/index-C3Y-rsyN.d.mts.map +0 -1
  506. package/dist/runner-CgQbELYC.d.mts.map +0 -1
  507. package/dist/version-x0NjTScG.mjs +0 -7
  508. /package/dist/{api-tokens-CyTsLszZ.mjs → api-tokens-rIXC6LdE.mjs} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"snapshot-B5h6aPMh.mjs","names":[],"sources":["../src/api/handlers/snapshot.ts"],"sourcesContent":["/**\n * Snapshot handler — generates a portable database snapshot.\n *\n * Returns all content tables, schema definitions, and supporting data\n * needed to render content in an isolated preview database.\n *\n * Used by:\n * - DO preview database (EmDashPreviewDB.populateFromSnapshot)\n * - Future: CLI export, backup, site migration\n */\n\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport type { Database } from \"../../database/types.js\";\n\n// ─�� Preview signature verification ──────────────────────────────\n\n/**\n * Verify HMAC-SHA256 preview signature using crypto.subtle.\n * Returns true if the signature is valid and not expired.\n */\nexport async function verifyPreviewSignature(\n\tsource: string,\n\texp: number,\n\tsig: string,\n\tsecret: string,\n): Promise<boolean> {\n\tif (exp < Date.now() / 1000) return false;\n\n\tconst encoder = new TextEncoder();\n\tconst key = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tencoder.encode(secret),\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"verify\"],\n\t);\n\n\tconst sigBytes = new Uint8Array(sig.length / 2);\n\tfor (let i = 0; i < sig.length; i += 2) {\n\t\tsigBytes[i / 2] = parseInt(sig.substring(i, i + 2), 16);\n\t}\n\n\treturn crypto.subtle.verify(\"HMAC\", key, sigBytes, encoder.encode(`${source}:${exp}`));\n}\n\n/**\n * Parse an X-Preview-Signature header value into its components.\n *\n * Format: \"source:exp:sig\" where source is a URL (contains colons),\n * exp is a unix timestamp, and sig is 64 hex chars.\n *\n * Parses from the right since source URLs contain colons.\n *\n * @returns Parsed components, or null if the format is invalid\n */\nexport function parsePreviewSignatureHeader(\n\theader: string,\n): { source: string; exp: number; sig: string } | null {\n\tconst lastColon = header.lastIndexOf(\":\");\n\tif (lastColon <= 0) return null;\n\n\tconst sig = header.substring(lastColon + 1);\n\tif (sig.length !== 64) return null;\n\n\tconst rest = header.substring(0, lastColon);\n\tconst secondLastColon = rest.lastIndexOf(\":\");\n\tif (secondLastColon <= 0) return null;\n\n\tconst source = rest.substring(0, secondLastColon);\n\tconst exp = parseInt(rest.substring(secondLastColon + 1), 10);\n\n\tif (isNaN(exp) || source.length === 0) return null;\n\n\treturn { source, exp, sig };\n}\n\n// ── Media URL rewriting ─────────────────────────────────────────\n\nconst MEDIA_FILE_PREFIX = \"/_emdash/api/media/file/\";\n\n/**\n * Parse a JSON string value and inject `src` for local media objects.\n * Returns the original string if it's not a local media value.\n */\nfunction injectMediaSrc(jsonStr: string, origin: string): string {\n\ttry {\n\t\tconst obj = JSON.parse(jsonStr);\n\t\tif (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) return jsonStr;\n\t\tif (injectMediaSrcInto(obj, origin)) {\n\t\t\treturn JSON.stringify(obj);\n\t\t}\n\t\treturn jsonStr;\n\t} catch {\n\t\treturn jsonStr;\n\t}\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Recursively walk an object and inject `src` into local media values.\n * Returns true if any modifications were made.\n */\nfunction injectMediaSrcInto(obj: Record<string, unknown>, origin: string): boolean {\n\tlet modified = false;\n\n\t// Check if this object itself is a local media value\n\tif ((obj.provider === \"local\" || (!obj.provider && obj.id && obj.meta)) && !obj.src) {\n\t\tconst meta = isRecord(obj.meta) ? obj.meta : undefined;\n\t\tconst storageKey = meta?.storageKey ?? obj.id;\n\t\tif (typeof storageKey === \"string\" && storageKey) {\n\t\t\tobj.src = `${origin}${MEDIA_FILE_PREFIX}${storageKey}`;\n\t\t\tmodified = true;\n\t\t}\n\t}\n\n\t// Recurse into nested objects/arrays (e.g. Portable Text with image blocks)\n\tfor (const value of Object.values(obj)) {\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (const item of value) {\n\t\t\t\tif (isRecord(item)) {\n\t\t\t\t\tif (injectMediaSrcInto(item, origin)) {\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (isRecord(value)) {\n\t\t\tif (injectMediaSrcInto(value, origin)) {\n\t\t\t\tmodified = true;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn modified;\n}\n\n// ── Snapshot generation ─────────────────────────────────────────\n\n/**\n * Safe identifier pattern for snapshot table names.\n * More permissive than validateIdentifier() — allows leading underscores\n * (needed for system tables like _emdash_collections).\n */\nconst SAFE_TABLE_NAME = /^[a-z_][a-z0-9_]*$/;\n\n/** Snapshot shape consumed by the DO preview database */\nexport interface Snapshot {\n\ttables: Record<string, Record<string, unknown>[]>;\n\tschema: Record<\n\t\tstring,\n\t\t{\n\t\t\tcolumns: string[];\n\t\t\ttypes?: Record<string, string>;\n\t\t}\n\t>;\n\tgeneratedAt: string;\n}\n\n/**\n * System tables included in snapshots.\n * Content tables (ec_*) are discovered dynamically.\n */\nconst SYSTEM_TABLES = [\n\t\"_emdash_collections\",\n\t\"_emdash_fields\",\n\t\"_emdash_taxonomy_defs\",\n\t\"_emdash_menus\",\n\t\"_emdash_menu_items\",\n\t\"_emdash_sections\",\n\t\"_emdash_widget_areas\",\n\t\"_emdash_widgets\",\n\t\"_emdash_seo\",\n\t\"_emdash_migrations\",\n\t\"taxonomies\",\n\t\"content_taxonomies\",\n\t\"media\",\n\t\"options\",\n\t\"revisions\",\n];\n\n/**\n * Table name prefixes excluded from snapshots (auth/security data).\n */\nconst EXCLUDED_PREFIXES = [\n\t\"_emdash_api_tokens\",\n\t\"_emdash_oauth_tokens\",\n\t\"_emdash_authorization_codes\",\n\t\"_emdash_device_codes\",\n\t\"_emdash_migrations_lock\",\n\t\"_plugin_\",\n\t\"users\",\n\t\"sessions\",\n\t\"credentials\",\n\t\"challenges\",\n];\n\n/**\n * Options key prefixes safe for inclusion in snapshots.\n *\n * The options table contains plugin secrets (plugin:*), passkey challenges\n * (emdash:passkey_pending:*), and setup state that must not leak to\n * preview databases. Only site-level rendering settings are needed.\n */\nconst SAFE_OPTIONS_PREFIXES = [\"site:\"];\n\nfunction isExcluded(tableName: string): boolean {\n\treturn EXCLUDED_PREFIXES.some((prefix) => tableName.startsWith(prefix));\n}\n\n/** Column info from PRAGMA table_info */\ninterface ColumnInfo {\n\tname: string;\n\ttype: string;\n}\n\nexport interface GenerateSnapshotOptions {\n\t/** Include draft and scheduled content (default: false) */\n\tincludeDrafts?: boolean;\n\t/** Include trashed content (deleted_at set). Used by backups (default: false) */\n\tincludeTrashed?: boolean;\n\t/** Origin URL for absolutizing local media URLs (e.g. \"https://mysite.com\") */\n\torigin?: string;\n\t/**\n\t * Allowlist of options-table key prefixes to include (default:\n\t * `SAFE_OPTIONS_PREFIXES`). Callers widening this must never include a\n\t * prefix that matches secrets (`emdash:preview_secret`, `plugin:`,\n\t * `emdash:passkey_pending:`) — the output may be user-downloadable.\n\t */\n\toptionPrefixes?: string[];\n}\n\n/**\n * Generate a portable database snapshot.\n *\n * Discovers ec_* content tables dynamically, exports system tables\n * needed for rendering, and includes schema info for table recreation.\n */\nexport async function generateSnapshot(\n\tdb: Kysely<Database>,\n\toptions?: GenerateSnapshotOptions,\n): Promise<Snapshot> {\n\tconst includeDrafts = options?.includeDrafts ?? false;\n\tconst includeTrashed = options?.includeTrashed ?? false;\n\tconst optionPrefixes = options?.optionPrefixes ?? SAFE_OPTIONS_PREFIXES;\n\n\t// Discover all ec_* content tables\n\tconst tableResult = await sql<{ name: string }>`\n\t\tSELECT name FROM sqlite_master\n\t\tWHERE type = 'table'\n\t\tAND name LIKE 'ec_%'\n\t\tORDER BY name\n\t`.execute(db);\n\n\tconst contentTables = tableResult.rows.map((r) => r.name);\n\n\t// Build list of all tables to export\n\tconst allTables = [...contentTables, ...SYSTEM_TABLES];\n\n\tconst tables: Record<string, Record<string, unknown>[]> = {};\n\tconst schema: Record<string, { columns: string[]; types?: Record<string, string> }> = {};\n\n\tfor (const tableName of allTables) {\n\t\tif (isExcluded(tableName)) continue;\n\n\t\t// Validate identifier before interpolating into sql.raw().\n\t\t// SYSTEM_TABLES are hardcoded and safe, but ec_* names come from\n\t\t// sqlite_master and must be validated.\n\t\tif (!SAFE_TABLE_NAME.test(tableName)) continue;\n\n\t\ttry {\n\t\t\t// Get column info via PRAGMA\n\t\t\tconst pragmaResult = await sql<ColumnInfo>`\n\t\t\t\tPRAGMA table_info(${sql.raw(`\"${tableName}\"`)})\n\t\t\t`.execute(db);\n\n\t\t\tif (pragmaResult.rows.length === 0) continue;\n\n\t\t\tconst columns = pragmaResult.rows.map((r) => r.name);\n\t\t\tconst types: Record<string, string> = {};\n\t\t\tfor (const row of pragmaResult.rows) {\n\t\t\t\ttypes[row.name] = row.type || \"TEXT\";\n\t\t\t}\n\n\t\t\tschema[tableName] = { columns, types };\n\n\t\t\t// Fetch rows\n\t\t\tlet rows: Record<string, unknown>[];\n\n\t\t\tif (tableName.startsWith(\"ec_\")) {\n\t\t\t\tif (includeTrashed) {\n\t\t\t\t\t// Everything, including trash — full-fidelity backup export\n\t\t\t\t\trows = (\n\t\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t\t`.execute(db)\n\t\t\t\t\t).rows;\n\t\t\t\t} else if (includeDrafts) {\n\t\t\t\t\t// Include all non-deleted content (published, draft, scheduled)\n\t\t\t\t\trows = (\n\t\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\t\t`.execute(db)\n\t\t\t\t\t).rows;\n\t\t\t\t} else {\n\t\t\t\t\t// Only export published content\n\t\t\t\t\trows = (\n\t\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\t\t\tAND status = 'published'\n\t\t\t\t\t`.execute(db)\n\t\t\t\t\t).rows;\n\t\t\t\t}\n\t\t\t} else if (tableName === \"options\") {\n\t\t\t\t// Filter options to safe rendering-only prefixes.\n\t\t\t\t// Excludes plugin secrets, passkey challenges, and setup state.\n\t\t\t\trows = (\n\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t`.execute(db)\n\t\t\t\t).rows.filter((row) => {\n\t\t\t\t\tconst name = typeof row.name === \"string\" ? row.name : \"\";\n\t\t\t\t\treturn optionPrefixes.some((prefix) => name.startsWith(prefix));\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\trows = (\n\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t`.execute(db)\n\t\t\t\t).rows;\n\t\t\t}\n\n\t\t\tif (rows.length > 0) {\n\t\t\t\ttables[tableName] = rows;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Table might not exist yet (e.g. pre-migration) — skip silently\n\t\t}\n\t}\n\n\t// Absolutize local media URLs in content tables so snapshots are portable.\n\t// Local image fields are stored as JSON with provider:\"local\" and\n\t// meta.storageKey but no src — the URL is derived at render time.\n\t// For snapshots consumed by external preview services, inject src now.\n\tif (options?.origin) {\n\t\tconst origin = options.origin;\n\t\tfor (const [tableName, rows] of Object.entries(tables)) {\n\t\t\tif (!tableName.startsWith(\"ec_\")) continue;\n\t\t\tfor (const row of rows) {\n\t\t\t\tfor (const [col, value] of Object.entries(row)) {\n\t\t\t\t\tif (typeof value !== \"string\" || !value.startsWith(\"{\")) continue;\n\t\t\t\t\trow[col] = injectMediaSrc(value, origin);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\ttables,\n\t\tschema,\n\t\tgeneratedAt: new Date().toISOString(),\n\t};\n}\n"],"mappings":";;;;;;;AAsBA,eAAsB,uBACrB,QACA,KACA,KACA,QACmB;AACnB,KAAI,MAAM,KAAK,KAAK,GAAG,IAAM,QAAO;CAEpC,MAAM,UAAU,IAAI,aAAa;CACjC,MAAM,MAAM,MAAM,OAAO,OAAO,UAC/B,OACA,QAAQ,OAAO,OAAO,EACtB;EAAE,MAAM;EAAQ,MAAM;EAAW,EACjC,OACA,CAAC,SAAS,CACV;CAED,MAAM,WAAW,IAAI,WAAW,IAAI,SAAS,EAAE;AAC/C,MAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,EACpC,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AC,MAAM,WAAW,IAAI,CAAE;AACzD,QAAI,OAAO,eAAe,OAAO,OAAO;;;;AAM5C,QAAO;EACN;EACA;EACA,8BAAa,IAAI,MAAM,EAAC,aAAa;EACrC"}
1
+ {"version":3,"file":"snapshot-BBlGkb2q.mjs","names":[],"sources":["../src/api/handlers/snapshot.ts"],"sourcesContent":["/**\n * Snapshot handler — generates a portable database snapshot.\n *\n * Returns all content tables, schema definitions, and supporting data\n * needed to render content in an isolated preview database.\n *\n * Used by:\n * - DO preview database (EmDashPreviewDB.populateFromSnapshot)\n * - Future: CLI export, backup, site migration\n */\n\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport type { Database } from \"../../database/types.js\";\n\n// ─�� Preview signature verification ──────────────────────────────\n\n/**\n * Verify HMAC-SHA256 preview signature using crypto.subtle.\n * Returns true if the signature is valid and not expired.\n */\nexport async function verifyPreviewSignature(\n\tsource: string,\n\texp: number,\n\tsig: string,\n\tsecret: string,\n): Promise<boolean> {\n\tif (exp < Date.now() / 1000) return false;\n\n\tconst encoder = new TextEncoder();\n\tconst key = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tencoder.encode(secret),\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"verify\"],\n\t);\n\n\tconst sigBytes = new Uint8Array(sig.length / 2);\n\tfor (let i = 0; i < sig.length; i += 2) {\n\t\tsigBytes[i / 2] = parseInt(sig.substring(i, i + 2), 16);\n\t}\n\n\treturn crypto.subtle.verify(\"HMAC\", key, sigBytes, encoder.encode(`${source}:${exp}`));\n}\n\n/**\n * Parse an X-Preview-Signature header value into its components.\n *\n * Format: \"source:exp:sig\" where source is a URL (contains colons),\n * exp is a unix timestamp, and sig is 64 hex chars.\n *\n * Parses from the right since source URLs contain colons.\n *\n * @returns Parsed components, or null if the format is invalid\n */\nexport function parsePreviewSignatureHeader(\n\theader: string,\n): { source: string; exp: number; sig: string } | null {\n\tconst lastColon = header.lastIndexOf(\":\");\n\tif (lastColon <= 0) return null;\n\n\tconst sig = header.substring(lastColon + 1);\n\tif (sig.length !== 64) return null;\n\n\tconst rest = header.substring(0, lastColon);\n\tconst secondLastColon = rest.lastIndexOf(\":\");\n\tif (secondLastColon <= 0) return null;\n\n\tconst source = rest.substring(0, secondLastColon);\n\tconst exp = parseInt(rest.substring(secondLastColon + 1), 10);\n\n\tif (isNaN(exp) || source.length === 0) return null;\n\n\treturn { source, exp, sig };\n}\n\n// ── Media URL rewriting ─────────────────────────────────────────\n\nconst MEDIA_FILE_PREFIX = \"/_emdash/api/media/file/\";\n\n/**\n * Parse a JSON string value and inject `src` for local media objects.\n * Returns the original string if it's not a local media value.\n */\nfunction injectMediaSrc(jsonStr: string, origin: string): string {\n\ttry {\n\t\tconst obj = JSON.parse(jsonStr);\n\t\tif (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) return jsonStr;\n\t\tif (injectMediaSrcInto(obj, origin)) {\n\t\t\treturn JSON.stringify(obj);\n\t\t}\n\t\treturn jsonStr;\n\t} catch {\n\t\treturn jsonStr;\n\t}\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Recursively walk an object and inject `src` into local media values.\n * Returns true if any modifications were made.\n */\nfunction injectMediaSrcInto(obj: Record<string, unknown>, origin: string): boolean {\n\tlet modified = false;\n\n\t// Check if this object itself is a local media value\n\tif ((obj.provider === \"local\" || (!obj.provider && obj.id && obj.meta)) && !obj.src) {\n\t\tconst meta = isRecord(obj.meta) ? obj.meta : undefined;\n\t\tconst storageKey = meta?.storageKey ?? obj.id;\n\t\tif (typeof storageKey === \"string\" && storageKey) {\n\t\t\tobj.src = `${origin}${MEDIA_FILE_PREFIX}${storageKey}`;\n\t\t\tmodified = true;\n\t\t}\n\t}\n\n\t// Recurse into nested objects/arrays (e.g. Portable Text with image blocks)\n\tfor (const value of Object.values(obj)) {\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (const item of value) {\n\t\t\t\tif (isRecord(item)) {\n\t\t\t\t\tif (injectMediaSrcInto(item, origin)) {\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (isRecord(value)) {\n\t\t\tif (injectMediaSrcInto(value, origin)) {\n\t\t\t\tmodified = true;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn modified;\n}\n\n// ── Snapshot generation ─────────────────────────────────────────\n\n/**\n * Safe identifier pattern for snapshot table names.\n * More permissive than validateIdentifier() — allows leading underscores\n * (needed for system tables like _emdash_collections).\n */\nconst SAFE_TABLE_NAME = /^[a-z_][a-z0-9_]*$/;\n\n/** Snapshot shape consumed by the DO preview database */\nexport interface Snapshot {\n\ttables: Record<string, Record<string, unknown>[]>;\n\tschema: Record<\n\t\tstring,\n\t\t{\n\t\t\tcolumns: string[];\n\t\t\ttypes?: Record<string, string>;\n\t\t}\n\t>;\n\tgeneratedAt: string;\n}\n\n/**\n * System tables included in snapshots.\n * Content tables (ec_*) are discovered dynamically.\n */\nconst SYSTEM_TABLES = [\n\t\"_emdash_collections\",\n\t\"_emdash_fields\",\n\t\"_emdash_taxonomy_defs\",\n\t\"_emdash_menus\",\n\t\"_emdash_menu_items\",\n\t\"_emdash_sections\",\n\t\"_emdash_widget_areas\",\n\t\"_emdash_widgets\",\n\t\"_emdash_seo\",\n\t\"_emdash_migrations\",\n\t\"taxonomies\",\n\t\"content_taxonomies\",\n\t\"media\",\n\t\"options\",\n\t\"revisions\",\n];\n\n/**\n * Table name prefixes excluded from snapshots (auth/security data).\n */\nconst EXCLUDED_PREFIXES = [\n\t\"_emdash_api_tokens\",\n\t\"_emdash_oauth_tokens\",\n\t\"_emdash_authorization_codes\",\n\t\"_emdash_device_codes\",\n\t\"_emdash_migrations_lock\",\n\t\"_plugin_\",\n\t\"users\",\n\t\"sessions\",\n\t\"credentials\",\n\t\"challenges\",\n];\n\n/**\n * Options key prefixes safe for inclusion in snapshots.\n *\n * The options table contains plugin secrets (plugin:*), passkey challenges\n * (emdash:passkey_pending:*), and setup state that must not leak to\n * preview databases. Only site-level rendering settings are needed.\n */\nconst SAFE_OPTIONS_PREFIXES = [\"site:\"];\n\nfunction isExcluded(tableName: string): boolean {\n\treturn EXCLUDED_PREFIXES.some((prefix) => tableName.startsWith(prefix));\n}\n\n/** Column info from PRAGMA table_info */\ninterface ColumnInfo {\n\tname: string;\n\ttype: string;\n}\n\nexport interface GenerateSnapshotOptions {\n\t/** Include draft and scheduled content (default: false) */\n\tincludeDrafts?: boolean;\n\t/** Include trashed content (deleted_at set). Used by backups (default: false) */\n\tincludeTrashed?: boolean;\n\t/** Origin URL for absolutizing local media URLs (e.g. \"https://mysite.com\") */\n\torigin?: string;\n\t/**\n\t * Allowlist of options-table key prefixes to include (default:\n\t * `SAFE_OPTIONS_PREFIXES`). Callers widening this must never include a\n\t * prefix that matches secrets (`emdash:preview_secret`, `plugin:`,\n\t * `emdash:passkey_pending:`) — the output may be user-downloadable.\n\t */\n\toptionPrefixes?: string[];\n}\n\n/**\n * Generate a portable database snapshot.\n *\n * Discovers ec_* content tables dynamically, exports system tables\n * needed for rendering, and includes schema info for table recreation.\n */\nexport async function generateSnapshot(\n\tdb: Kysely<Database>,\n\toptions?: GenerateSnapshotOptions,\n): Promise<Snapshot> {\n\tconst includeDrafts = options?.includeDrafts ?? false;\n\tconst includeTrashed = options?.includeTrashed ?? false;\n\tconst optionPrefixes = options?.optionPrefixes ?? SAFE_OPTIONS_PREFIXES;\n\n\t// Discover all ec_* content tables\n\tconst tableResult = await sql<{ name: string }>`\n\t\tSELECT name FROM sqlite_master\n\t\tWHERE type = 'table'\n\t\tAND name LIKE 'ec_%'\n\t\tORDER BY name\n\t`.execute(db);\n\n\tconst contentTables = tableResult.rows.map((r) => r.name);\n\n\t// Build list of all tables to export\n\tconst allTables = [...contentTables, ...SYSTEM_TABLES];\n\n\tconst tables: Record<string, Record<string, unknown>[]> = {};\n\tconst schema: Record<string, { columns: string[]; types?: Record<string, string> }> = {};\n\n\tfor (const tableName of allTables) {\n\t\tif (isExcluded(tableName)) continue;\n\n\t\t// Validate identifier before interpolating into sql.raw().\n\t\t// SYSTEM_TABLES are hardcoded and safe, but ec_* names come from\n\t\t// sqlite_master and must be validated.\n\t\tif (!SAFE_TABLE_NAME.test(tableName)) continue;\n\n\t\ttry {\n\t\t\t// Get column info via PRAGMA\n\t\t\tconst pragmaResult = await sql<ColumnInfo>`\n\t\t\t\tPRAGMA table_info(${sql.raw(`\"${tableName}\"`)})\n\t\t\t`.execute(db);\n\n\t\t\tif (pragmaResult.rows.length === 0) continue;\n\n\t\t\tconst columns = pragmaResult.rows.map((r) => r.name);\n\t\t\tconst types: Record<string, string> = {};\n\t\t\tfor (const row of pragmaResult.rows) {\n\t\t\t\ttypes[row.name] = row.type || \"TEXT\";\n\t\t\t}\n\n\t\t\tschema[tableName] = { columns, types };\n\n\t\t\t// Fetch rows\n\t\t\tlet rows: Record<string, unknown>[];\n\n\t\t\tif (tableName.startsWith(\"ec_\")) {\n\t\t\t\tif (includeTrashed) {\n\t\t\t\t\t// Everything, including trash — full-fidelity backup export\n\t\t\t\t\trows = (\n\t\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t\t`.execute(db)\n\t\t\t\t\t).rows;\n\t\t\t\t} else if (includeDrafts) {\n\t\t\t\t\t// Include all non-deleted content (published, draft, scheduled)\n\t\t\t\t\trows = (\n\t\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\t\t`.execute(db)\n\t\t\t\t\t).rows;\n\t\t\t\t} else {\n\t\t\t\t\t// Only export published content\n\t\t\t\t\trows = (\n\t\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\t\t\tAND status = 'published'\n\t\t\t\t\t`.execute(db)\n\t\t\t\t\t).rows;\n\t\t\t\t}\n\t\t\t} else if (tableName === \"options\") {\n\t\t\t\t// Filter options to safe rendering-only prefixes.\n\t\t\t\t// Excludes plugin secrets, passkey challenges, and setup state.\n\t\t\t\trows = (\n\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t`.execute(db)\n\t\t\t\t).rows.filter((row) => {\n\t\t\t\t\tconst name = typeof row.name === \"string\" ? row.name : \"\";\n\t\t\t\t\treturn optionPrefixes.some((prefix) => name.startsWith(prefix));\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\trows = (\n\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t`.execute(db)\n\t\t\t\t).rows;\n\t\t\t}\n\n\t\t\tif (rows.length > 0) {\n\t\t\t\ttables[tableName] = rows;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Table might not exist yet (e.g. pre-migration) — skip silently\n\t\t}\n\t}\n\n\t// Absolutize local media URLs in content tables so snapshots are portable.\n\t// Local image fields are stored as JSON with provider:\"local\" and\n\t// meta.storageKey but no src — the URL is derived at render time.\n\t// For snapshots consumed by external preview services, inject src now.\n\tif (options?.origin) {\n\t\tconst origin = options.origin;\n\t\tfor (const [tableName, rows] of Object.entries(tables)) {\n\t\t\tif (!tableName.startsWith(\"ec_\")) continue;\n\t\t\tfor (const row of rows) {\n\t\t\t\tfor (const [col, value] of Object.entries(row)) {\n\t\t\t\t\tif (typeof value !== \"string\" || !value.startsWith(\"{\")) continue;\n\t\t\t\t\trow[col] = injectMediaSrc(value, origin);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\ttables,\n\t\tschema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C;KAC9D;OAEF,SACC,MAAM,GAA4B;qBAClB,IAAI,IAAI,IAAI,UAAU,GAAG,CAAC;MACzC,QAAQ,GAAG,EACX;AAGH,OAAI,KAAK,SAAS,EACjB,QAAO,aAAa;UAEd;;AAST,KAAI,SAAS,QAAQ;EACpB,MAAM,SAAS,QAAQ;AACvB,OAAK,MAAM,CAAC,WAAW,SAAS,OAAO,QAAQ,OAAO,EAAE;AACvD,OAAI,CAAC,UAAU,WAAW,MAAM,CAAE;AAClC,QAAK,MAAM,OAAO,KACjB,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,EAAE;AAC/C,QAAI,OAAO,UAAU,YAAY,CAAC,MAAM,WAAW,IAAI,CAAE;AACzD,QAAI,OAAO,eAAe,OAAO,OAAO;;;;AAM5C,QAAO;EACN;EACA;EACA,8BAAa,IAAI,MAAM,EAAC,aAAa;EACrC"}
@@ -1,4 +1,4 @@
1
- import { a as ListOptions, d as Storage, l as SignedUploadOptions, n as DownloadResult, o as ListResult, p as UploadResult, s as LocalStorageConfig, u as SignedUploadUrl } from "../types-CFUfyt1s.mjs";
1
+ import { a as ListOptions, d as Storage, l as SignedUploadOptions, n as DownloadResult, o as ListResult, p as UploadResult, s as LocalStorageConfig, u as SignedUploadUrl } from "../types-BcqdcT-r.mjs";
2
2
 
3
3
  //#region src/storage/local.d.ts
4
4
  /**
@@ -1,8 +1,8 @@
1
1
  import { t as EmDashStorageError } from "../types-BW1syrlw.mjs";
2
2
  import mime from "mime/lite";
3
- import { createReadStream, existsSync } from "node:fs";
4
- import * as path from "node:path";
5
3
  import * as fs from "node:fs/promises";
4
+ import * as path from "node:path";
5
+ import { createReadStream, existsSync } from "node:fs";
6
6
  import { Readable } from "node:stream";
7
7
 
8
8
  //#region src/storage/local.ts
@@ -1,4 +1,4 @@
1
- import { a as ListOptions, c as S3StorageConfig, d as Storage, l as SignedUploadOptions, n as DownloadResult, o as ListResult, p as UploadResult, u as SignedUploadUrl } from "../types-CFUfyt1s.mjs";
1
+ import { a as ListOptions, c as S3StorageConfig, d as Storage, l as SignedUploadOptions, n as DownloadResult, o as ListResult, p as UploadResult, u as SignedUploadUrl } from "../types-BcqdcT-r.mjs";
2
2
 
3
3
  //#region src/storage/s3.d.ts
4
4
  /**
@@ -0,0 +1,27 @@
1
+ //#region src/migrations/target.ts
2
+ const ENVIRONMENT_VARIABLE_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
3
+ function encodeHex(bytes) {
4
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
5
+ }
6
+ async function createMigrationTarget(kind, label, identity) {
7
+ const encoded = new TextEncoder().encode(JSON.stringify({
8
+ kind,
9
+ identity
10
+ }));
11
+ const digest = await crypto.subtle.digest("SHA-256", encoded);
12
+ return {
13
+ kind,
14
+ label,
15
+ fingerprint: encodeHex(new Uint8Array(digest))
16
+ };
17
+ }
18
+ function requireMigrationEnvironment(name, env) {
19
+ if (typeof name !== "string" || !ENVIRONMENT_VARIABLE_PATTERN.test(name)) throw new Error("Migration credential environment variable name is invalid.");
20
+ const value = env[name];
21
+ if (!value) throw new Error(`Migration credential environment variable ${name} is not set.`);
22
+ return value;
23
+ }
24
+
25
+ //#endregion
26
+ export { requireMigrationEnvironment as n, createMigrationTarget as t };
27
+ //# sourceMappingURL=target-DixqqV5i.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"target-DixqqV5i.mjs","names":[],"sources":["../src/migrations/target.ts"],"sourcesContent":["import type { MigrationTarget } from \"./protocol.js\";\n\nconst ENVIRONMENT_VARIABLE_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nfunction encodeHex(bytes: Uint8Array): string {\n\treturn Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport async function createMigrationTarget(\n\tkind: string,\n\tlabel: string,\n\tidentity: readonly string[],\n): Promise<MigrationTarget> {\n\tconst encoded = new TextEncoder().encode(JSON.stringify({ kind, identity }));\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", encoded);\n\treturn {\n\t\tkind,\n\t\tlabel,\n\t\tfingerprint: encodeHex(new Uint8Array(digest)),\n\t};\n}\n\nexport function requireMigrationEnvironment(\n\tname: unknown,\n\tenv: Readonly<Record<string, string | undefined>>,\n): string {\n\tif (typeof name !== \"string\" || !ENVIRONMENT_VARIABLE_PATTERN.test(name)) {\n\t\tthrow new Error(\"Migration credential environment variable name is invalid.\");\n\t}\n\tconst value = env[name];\n\tif (!value) {\n\t\tthrow new Error(`Migration credential environment variable ${name} is not set.`);\n\t}\n\treturn value;\n}\n"],"mappings":";AAEA,MAAM,+BAA+B;AAErC,SAAS,UAAU,OAA2B;AAC7C,QAAO,MAAM,KAAK,QAAQ,SAAS,KAAK,SAAS,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,KAAK,GAAG;;AAGhF,eAAsB,sBACrB,MACA,OACA,UAC2B;CAC3B,MAAM,UAAU,IAAI,aAAa,CAAC,OAAO,KAAK,UAAU;EAAE;EAAM;EAAU,CAAC,CAAC;CAC5E,MAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,QAAQ;AAC7D,QAAO;EACN;EACA;EACA,aAAa,UAAU,IAAI,WAAW,OAAO,CAAC;EAC9C;;AAGF,SAAgB,4BACf,MACA,KACS;AACT,KAAI,OAAO,SAAS,YAAY,CAAC,6BAA6B,KAAK,KAAK,CACvE,OAAM,IAAI,MAAM,6DAA6D;CAE9E,MAAM,QAAQ,IAAI;AAClB,KAAI,CAAC,MACJ,OAAM,IAAI,MAAM,6CAA6C,KAAK,cAAc;AAEjF,QAAO"}
@@ -1,14 +1,14 @@
1
- import { o as __exportAll } from "./runner-BiDvq5dv.mjs";
1
+ import { c as __exportAll } from "./runner-C1T11CfC.mjs";
2
2
  import { t as validateIdentifier } from "./validate-BpwoDOgt.mjs";
3
3
  import { i as compoundSelectLimit, n as buildStatusCondition } from "./dialect-helpers-BSbfaO3F.mjs";
4
4
  import { r as getI18nConfig } from "./config-C3EBstHi.mjs";
5
5
  import { getRequestContext } from "./request-context.mjs";
6
6
  import { m as isObjectCacheActive, n as cachedQuery, p as invalidateTaxonomyObjectCache, r as contentCacheNamespaces, t as CacheNamespace } from "./object-cache-71tPfV4A.mjs";
7
- import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-DfPax1I0.mjs";
7
+ import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-fiZ8G9RJ.mjs";
8
8
  import { n as isMissingTableError } from "./db-errors-Cl-sKYTm.mjs";
9
9
  import { i as setRequestCacheEntry, n as peekRequestCache, r as requestCached } from "./request-cache-BSUptuJR.mjs";
10
10
  import { i as resolveLocaleChain, r as resolveLocale } from "./resolve-DOhVEvty.mjs";
11
- import { l as resetTaxonomyNamesCache, s as getDb } from "./loader-DLBqRiGP.mjs";
11
+ import { l as resetTaxonomyNamesCache, s as getDb } from "./loader-CdG_Ci3H.mjs";
12
12
  import { sql } from "kysely";
13
13
 
14
14
  //#region src/taxonomies/term-counts.ts
@@ -619,7 +619,7 @@ function primeFoldedEntryTerms(collection, perEntry, options = {}) {
619
619
  * the content query respect the active locale.
620
620
  */
621
621
  async function getEntriesByTerm(collection, taxonomyName, termSlug, options = {}) {
622
- const { getEmDashCollection } = await import("./query-BgjfiLUQ.mjs").then((n) => n.o);
622
+ const { getEmDashCollection } = await import("./query-zTVAR1Sl.mjs").then((n) => n.o);
623
623
  const queryOptions = { where: { [taxonomyName]: termSlug } };
624
624
  if (options.locale !== void 0) queryOptions.locale = options.locale;
625
625
  const { entries } = await getEmDashCollection(collection, queryOptions);
@@ -669,4 +669,4 @@ function buildTree(flatTerms) {
669
669
 
670
670
  //#endregion
671
671
  export { getTaxonomyDefs as a, getTermsForEntries as c, taxonomies_exports as d, fetchVisibleTermCounts as f, getTaxonomyDef as i, invalidateTaxonomyDefsCache as l, getEntriesByTerm as n, getTaxonomyTerms as o, getEntryTerms as r, getTerm as s, getAllTermsForEntries as t, invalidateTermCache as u };
672
- //# sourceMappingURL=taxonomies-B0o9ExNV.mjs.map
672
+ //# sourceMappingURL=taxonomies-BlrncHi9.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"taxonomies-B0o9ExNV.mjs","names":[],"sources":["../src/taxonomies/term-counts.ts","../src/taxonomies/index.ts"],"sourcesContent":["/**\n * Shared visible-usage counts for taxonomy terms (issue #581).\n *\n * `content_taxonomies` rows are written for every entry regardless of status\n * and are never pruned on unpublish/trash, so counting the pivot directly\n * inflates counts with drafts and soft-deleted entries. Every user-facing\n * count (public widget, single-term page, admin term list) must instead count\n * only entries that have completed publication:\n * `status = 'published'` AND `deleted_at IS NULL`.\n *\n * The public render path is latency-sensitive on D1, so per-collection counts\n * are combined with UNION ALL — one query per taxonomy, never one per\n * collection, split only where the backend caps compound-SELECT terms.\n */\n\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport { buildStatusCondition, compoundSelectLimit } from \"../database/dialect-helpers.js\";\nimport type { Database } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport { chunks } from \"../utils/chunks.js\";\nimport { isMissingTableError } from \"../utils/db-errors.js\";\n\ninterface CountRow {\n\ttaxonomy_id: string;\n\tcount: number | string | bigint;\n}\n\n/**\n * Per-collection count branch. `taxonomy_id` stores the term's\n * translation_group, so results are keyed by group (locale-independent) and\n * each assignment is counted once per content translation group. When a\n * locale is provided, only that group's matching content row contributes.\n *\n * Scoping to the taxonomy uses `translation_group IN (...)` rather than a\n * join on `taxonomies.id` — the anchor row (id == group) can be deleted while\n * sibling translations survive, and a plain join on `translation_group` would\n * multiply counts by the number of locales.\n *\n * CROSS JOIN with the join predicate in WHERE keeps stats-blind SQLite/D1 from\n * reordering content_taxonomies out of the outer position; it touches ec_* only\n * through the translation-group index. Postgres treats this as an ordinary\n * inner join and plans freely.\n */\nfunction collectionBranch(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollection: string,\n\tlocale?: string,\n): ReturnType<typeof sql> {\n\treturn sql`\n\t\tSELECT ct.taxonomy_id AS taxonomy_id, COUNT(DISTINCT e.translation_group) AS count\n\t\tFROM content_taxonomies AS ct\n\t\tCROSS JOIN ${sql.ref(`ec_${collection}`)} AS e\n\t\tWHERE e.translation_group = ct.entry_id\n\t\t\tAND ct.collection = ${collection}\n\t\t\tAND ct.taxonomy_id IN (SELECT translation_group FROM taxonomies WHERE name = ${taxonomyName})\n\t\t\t${locale ? sql`AND e.locale = ${locale}` : sql``}\n\t\t\tAND ${buildStatusCondition(db, \"published\", \"e\")}\n\t\t\tAND e.deleted_at IS NULL\n\t\tGROUP BY ct.taxonomy_id`;\n}\n\nasync function runCounts(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollections: string[],\n\tlocale?: string,\n): Promise<Map<string, number>> {\n\tconst branches = collections.map((collection) =>\n\t\tcollectionBranch(db, taxonomyName, collection, locale),\n\t);\n\tconst union = sql.join(branches, sql` UNION ALL `);\n\tconst result = await sql<CountRow>`\n\t\tSELECT taxonomy_id, SUM(count) AS count\n\t\tFROM (${union}) AS per_collection\n\t\tGROUP BY taxonomy_id`.execute(db);\n\n\tconst counts = new Map<string, number>();\n\tfor (const row of result.rows) counts.set(row.taxonomy_id, Number(row.count));\n\treturn counts;\n}\n\nfunction addCounts(into: Map<string, number>, from: Map<string, number>): void {\n\tfor (const [group, count] of from) into.set(group, (into.get(group) ?? 0) + count);\n}\n\n/**\n * Counts for one batch of collections, degrading to a query per collection\n * when a declared collection has no ec_* table so the rest still contribute.\n */\nasync function runBatch(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollections: string[],\n\tlocale?: string,\n): Promise<Map<string, number>> {\n\ttry {\n\t\treturn await runCounts(db, taxonomyName, collections, locale);\n\t} catch (error) {\n\t\tif (!isMissingTableError(error)) throw error;\n\t}\n\n\tconst counts = new Map<string, number>();\n\tfor (const collection of collections) {\n\t\ttry {\n\t\t\taddCounts(counts, await runCounts(db, taxonomyName, [collection], locale));\n\t\t} catch (error) {\n\t\t\tif (!isMissingTableError(error)) throw error;\n\t\t}\n\t}\n\treturn counts;\n}\n\n/**\n * Count publicly-visible term assignments for one taxonomy, keyed by the\n * term's translation_group (what `content_taxonomies.taxonomy_id` stores).\n * When `locale` is provided, only entries in that locale contribute. Omitting\n * it preserves the locale-agnostic API used by legacy callers.\n *\n * Counts are scoped to the taxonomy's declared collections — pass\n * `TaxonomyDef.collections` (`_emdash_taxonomy_defs.collections`). Collections\n * whose `ec_*` table doesn't exist (pre-migration drift, a declared collection\n * that was never created) are skipped, yielding a partial-but-correct count\n * rather than a throw.\n *\n * One database round-trip for the whole taxonomy (UNION ALL across\n * collections). On a backend that caps compound-SELECT terms — D1 allows five\n * — the branches are split into one statement per batch, since a taxonomy\n * declaring more collections than that would otherwise take down every path\n * that shows counts. Per-collection sums are commutative, so batching cannot\n * change the total.\n *\n * Callers on the public render path should go through the request-cached\n * wrapper in `taxonomies/index.ts` so a page rendering both the widget and a\n * term detail shares one computation.\n */\nexport async function fetchVisibleTermCounts(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollections: string[],\n\tlocale?: string,\n): Promise<Map<string, number>> {\n\tconst unique = [...new Set(collections)];\n\tfor (const collection of unique) validateIdentifier(collection, \"collection slug\");\n\tif (unique.length === 0) return new Map();\n\n\tconst limit = compoundSelectLimit(db);\n\tconst batched = limit === null ? [unique] : chunks(unique, limit);\n\tconst batches = await Promise.all(\n\t\tbatched.map((batch) => runBatch(db, taxonomyName, batch, locale)),\n\t);\n\n\tconst counts = new Map<string, number>();\n\tfor (const batch of batches) addCounts(counts, batch);\n\treturn counts;\n}\n","/**\n * Runtime API for taxonomies.\n *\n * All helpers are locale-aware. When a locale is not passed explicitly we fall\n * back to the request context or the configured `defaultLocale` (see\n * `i18n/resolve.ts`).\n *\n * Because `content_taxonomies.taxonomy_id` stores the translation_group (not a\n * specific term id), and `entry_id` stores the content translation_group, one\n * assignment resolves to the requested locale on both sides.\n */\n\nimport { sql, type Kysely } from \"kysely\";\n\nimport type { Database } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport { getI18nConfig } from \"../i18n/config.js\";\nimport { resolveLocale, resolveLocaleChain } from \"../i18n/resolve.js\";\nimport { getDb, resetTaxonomyNamesCache } from \"../loader.js\";\nimport {\n\tcachedQuery,\n\tCacheNamespace,\n\tcontentCacheNamespaces,\n\tinvalidateTaxonomyObjectCache,\n\tisObjectCacheActive,\n} from \"../object-cache/index.js\";\nimport { peekRequestCache, requestCached, setRequestCacheEntry } from \"../request-cache.js\";\nimport { getRequestContext } from \"../request-context.js\";\nimport { chunks, SQL_BATCH_SIZE } from \"../utils/chunks.js\";\nimport { isMissingTableError } from \"../utils/db-errors.js\";\nimport { fetchVisibleTermCounts } from \"./term-counts.js\";\nimport type { TaxonomyDef, TaxonomyTerm, TaxonomyTermRow } from \"./types.js\";\n\nexport interface TaxonomyQueryOptions {\n\tlocale?: string;\n}\n\nexport interface TaxonomyTermsOptions extends TaxonomyQueryOptions {\n\t/**\n\t * Populate each term's `count`. Counts aggregate the whole\n\t * `content_taxonomies` pivot against every declared collection, so callers\n\t * that don't render a count should opt out. Defaults to `true`.\n\t */\n\tincludeCounts?: boolean;\n}\n\ninterface EntryTermRow {\n\tentry_id: string;\n\tid: string;\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparent_id: string | null;\n\tlocale: string;\n\ttranslation_group: string | null;\n}\n\nasync function selectEntryTermRows(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tentryIds: string[],\n\ttaxonomyName?: string,\n\tlocale?: string,\n): Promise<EntryTermRow[]> {\n\tvalidateIdentifier(collection, \"collection slug\");\n\tconst tableName = `ec_${collection}`;\n\tconst preferredLocale = locale ? sql`${locale}` : sql`content.locale`;\n\tconst defaultLocale = getI18nConfig()?.defaultLocale ?? \"en\";\n\tconst result = await sql<EntryTermRow>`\n\t\tSELECT content.id AS entry_id,\n\t\t\tcoalesce(exact_term.id, default_term.id) AS id,\n\t\t\tcoalesce(exact_term.name, default_term.name) AS name,\n\t\t\tcoalesce(exact_term.slug, default_term.slug) AS slug,\n\t\t\tcoalesce(exact_term.label, default_term.label) AS label,\n\t\t\tcoalesce(exact_term.parent_id, default_term.parent_id) AS parent_id,\n\t\t\tcoalesce(exact_term.locale, default_term.locale) AS locale,\n\t\t\tcoalesce(exact_term.translation_group, default_term.translation_group) AS translation_group\n\t\tFROM ${sql.ref(tableName)} AS content\n\t\tINNER JOIN content_taxonomies AS pivot\n\t\t\tON pivot.entry_id = content.translation_group\n\t\t\tAND pivot.collection = ${collection}\n\t\tLEFT JOIN taxonomies AS exact_term\n\t\t\tON exact_term.translation_group = pivot.taxonomy_id\n\t\t\tAND exact_term.locale = ${preferredLocale}\n\t\tLEFT JOIN taxonomies AS default_term\n\t\t\tON default_term.translation_group = pivot.taxonomy_id\n\t\t\tAND default_term.locale = ${defaultLocale}\n\t\tWHERE content.id IN (${sql.join(entryIds.map((id) => sql`${id}`))})\n\t\t\tAND coalesce(exact_term.id, default_term.id) IS NOT NULL\n\t\t\t${taxonomyName ? sql`AND coalesce(exact_term.name, default_term.name) = ${taxonomyName}` : sql``}\n\t\tORDER BY coalesce(exact_term.label, default_term.label) ASC\n\t`.execute(db);\n\treturn result.rows;\n}\n\n/** Invalidate cached taxonomy term data and any content that hydrates terms. */\nexport function invalidateTermCache(): void {\n\tinvalidateTaxonomyObjectCache();\n}\n\n/**\n * Worker-isolate cache for taxonomy definitions, keyed by resolved locale.\n *\n * Taxonomy *definitions* (the \"category\"/\"tag\" taxonomies themselves, not\n * their terms) are read on every public render that hydrates entry terms —\n * `getAllTermsForEntries` → `getCollectionTaxonomyNames` → `getTaxonomyDefs` —\n * but change extremely rarely: they're written only by the admin API and by\n * seed application. Caching them across the isolate lifetime drops the\n * per-render `SELECT * FROM _emdash_taxonomy_defs` to once-per-isolate.\n *\n * Stored on globalThis behind a Symbol key (same pattern as\n * `settings/index.ts`) so the bundler duplicating this module across SSR\n * chunks can't produce two independent caches.\n *\n * When the distributed object cache is configured, it is authoritative and this\n * fallback is bypassed so cross-isolate epoch invalidation cannot be undercut\n * by stale per-isolate data on an object-cache miss.\n *\n * **Isolated databases bypass the cache.** Playground / DO preview requests\n * set `requestContext.dbIsIsolated`; they point at a divergent schema, so we\n * skip both reading and writing the global holder and fall back to the\n * per-request cache (same precedent as `getTaxonomyNames` / byline field defs).\n */\ninterface TaxonomyDefsHolder {\n\tversion: number;\n\t/** locale key (\"*\" for \"all locales\") → { version it was fetched at, promise }. */\n\tcache: Map<string, { version: number; promise: Promise<TaxonomyDef[]> }>;\n}\n\nconst TAXONOMY_DEFS_CACHE_KEY = Symbol.for(\"emdash:taxonomy-defs\");\nconst taxonomyDefsStore = globalThis as Record<symbol, unknown>;\nconst defsHolder: TaxonomyDefsHolder =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see settings/index.ts)\n\t(taxonomyDefsStore[TAXONOMY_DEFS_CACHE_KEY] as TaxonomyDefsHolder | undefined) ??\n\t(() => {\n\t\tconst h: TaxonomyDefsHolder = { version: 0, cache: new Map() };\n\t\ttaxonomyDefsStore[TAXONOMY_DEFS_CACHE_KEY] = h;\n\t\treturn h;\n\t})();\n\n/**\n * Invalidate the isolate-wide taxonomy-definitions cache (and the related\n * loader taxonomy-names cache). Called from every taxonomy-def write path\n * (`handleTaxonomyCreate`/`Update`/`Delete`, seed application). Other isolates\n * refresh on their next recycle — staleness bounded by isolate lifetime.\n */\nexport function invalidateTaxonomyDefsCache(): void {\n\tdefsHolder.version++;\n\tdefsHolder.cache.clear();\n\tresetTaxonomyNamesCache();\n\tinvalidateTaxonomyObjectCache();\n}\n\n/**\n * Test/internal helper: clear the per-isolate taxonomy-defs cache. Useful for\n * unit tests that insert defs directly and need to force a refetch without\n * going through a write path. Production code should rely on\n * `invalidateTaxonomyDefsCache()`.\n */\nexport function resetTaxonomyDefsCacheForTests(): void {\n\tdefsHolder.version++;\n\tdefsHolder.cache.clear();\n}\n\n/**\n * Fetch taxonomy definitions straight from the database (no caching).\n */\nasync function fetchTaxonomyDefs(locale: string | undefined): Promise<TaxonomyDef[]> {\n\tconst db = await getDb();\n\tlet query = db.selectFrom(\"_emdash_taxonomy_defs\").selectAll();\n\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\tconst rows = await query.execute();\n\treturn rows.map(rowToTaxonomyDef);\n}\n\n/**\n * Resolve taxonomy defs through the isolate fallback cache, bypassing it for\n * isolated databases. The returned promise is cached (not the resolved value)\n * so concurrent cold-isolate readers share one in-flight query; a rejection\n * evicts the entry so the next caller retries.\n */\nfunction loadTaxonomyDefs(localeKey: string, locale: string | undefined): Promise<TaxonomyDef[]> {\n\tif (getRequestContext()?.dbIsIsolated === true) {\n\t\treturn fetchTaxonomyDefs(locale);\n\t}\n\tconst existing = defsHolder.cache.get(localeKey);\n\tif (existing && existing.version === defsHolder.version) {\n\t\treturn existing.promise;\n\t}\n\tconst version = defsHolder.version;\n\tconst promise = fetchTaxonomyDefs(locale).catch((error: unknown) => {\n\t\tconst current = defsHolder.cache.get(localeKey);\n\t\tif (current && current.promise === promise) {\n\t\t\tdefsHolder.cache.delete(localeKey);\n\t\t}\n\t\tthrow error;\n\t});\n\tdefsHolder.cache.set(localeKey, { version, promise });\n\treturn promise;\n}\n\n/**\n * Get every taxonomy definition. Definitions are per-locale (one row per\n * locale inside the same translation_group) — by default we resolve to the\n * active locale.\n *\n * Two-tier cache: per-request via `requestCached` (so a single render that\n * hydrates terms for several collections pays at most one call), then\n * per-isolate via the global holder (so warm renders issue zero queries).\n * The `requestCached` key is unchanged so `getTaxonomyDef`'s peek still hits.\n */\nexport async function getTaxonomyDefs(options: TaxonomyQueryOptions = {}): Promise<TaxonomyDef[]> {\n\tconst locale = resolveLocale(options.locale);\n\tconst localeKey = locale ?? \"*\";\n\treturn requestCached(`taxonomy-defs:${localeKey}`, async () => {\n\t\tif (await isObjectCacheActive()) {\n\t\t\treturn cachedQuery({\n\t\t\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\t\t\tkey: `defs:${localeKey}`,\n\t\t\t\tload: () => fetchTaxonomyDefs(locale),\n\t\t\t});\n\t\t}\n\t\treturn loadTaxonomyDefs(localeKey, locale);\n\t});\n}\n\n/**\n * Get a single taxonomy definition by name. Uses the fallback chain so even\n * if there is no translation for the active locale we still return something.\n *\n * If `getTaxonomyDefs()` has already loaded the full list in this request\n * (which happens during entry-term hydration on every page that renders a\n * collection), search the matching def in memory rather than running a\n * second query against `_emdash_taxonomy_defs`.\n */\nexport async function getTaxonomyDef(\n\tname: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyDef | null> {\n\tconst chain = resolveLocaleChain(options.locale);\n\tconst peekKey = `taxonomy-defs:${resolveLocale(options.locale) ?? \"*\"}`;\n\tconst allDefs = peekRequestCache<TaxonomyDef[]>(peekKey);\n\tif (allDefs) {\n\t\tconst defs = await allDefs;\n\t\tif (chain.length === 0) return defs.find((d) => d.name === name) ?? null;\n\t\tfor (const locale of chain) {\n\t\t\tconst found = defs.find((d) => d.name === name && d.locale === locale);\n\t\t\tif (found) return found;\n\t\t}\n\t\treturn null;\n\t}\n\n\treturn requestCached(`taxonomy-def:${name}:${chain.join(\",\")}`, async () => {\n\t\tconst db = await getDb();\n\n\t\tif (chain.length === 0) {\n\t\t\tconst row = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"name\", \"=\", name)\n\t\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t\t.executeTakeFirst();\n\t\t\treturn row ? rowToTaxonomyDef(row) : null;\n\t\t}\n\n\t\tfor (const locale of chain) {\n\t\t\tconst row = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"name\", \"=\", name)\n\t\t\t\t.where(\"locale\", \"=\", locale)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (row) return rowToTaxonomyDef(row);\n\t\t}\n\t\treturn null;\n\t});\n}\n\n/**\n * Object-cache namespaces for values that embed visible term counts: the\n * taxonomy epoch (term/assignment writes) plus each counted collection's\n * content epoch, so publishing, unpublishing, or trashing an entry\n * invalidates the cached count promptly. Both content namespace generations\n * participate so rolling deployments preserve invalidation in either direction.\n */\nfunction termCountNamespaces(collections: string[]): string[] {\n\treturn [\n\t\t...[...new Set(collections)].flatMap((collection) => contentCacheNamespaces(collection)),\n\t\tCacheNamespace.TAXONOMIES,\n\t];\n}\n\n/**\n * All terms of a taxonomy in a specific locale (flat for non-hierarchical,\n * tree for hierarchical).\n *\n * The term list and the visible-entry counts are loaded and cached separately:\n * the list depends only on the taxonomy epoch, while the counts additionally\n * depend on every counted collection's content epoch and cost an aggregate over\n * the whole assignment pivot. Callers that don't render counts pass\n * `includeCounts: false` and skip that aggregate entirely, while still sharing\n * the term list with callers that do.\n */\nexport async function getTaxonomyTerms(\n\ttaxonomyName: string,\n\toptions: TaxonomyTermsOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\tconst def = await getTaxonomyDef(taxonomyName, options);\n\tif (!def) return [];\n\tif (options.includeCounts === false) return getTermList(def, locale);\n\n\t// The two are independent, so run them concurrently to save a round trip.\n\tconst [terms, counts] = await Promise.all([\n\t\tgetTermList(def, locale),\n\t\tgetVisibleTermCounts(def.name, def.collections, locale),\n\t]);\n\treturn withCounts(terms, counts);\n}\n\n/** Terms without counts, under the cache keys the layout prefetch warms. */\nfunction getTermList(def: TaxonomyDef, locale: string | undefined): Promise<TaxonomyTerm[]> {\n\tconst localeKey = locale ?? \"*\";\n\treturn requestCached(`taxonomy-terms:${def.name}:${localeKey}`, () =>\n\t\tcachedQuery({\n\t\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\t\tkey: `termList:${def.name}:${localeKey}`,\n\t\t\tload: () => loadTaxonomyTerms(def, locale),\n\t\t}),\n\t);\n}\n\n/**\n * Copy a term list with counts attached. Counts are keyed by translation_group\n * (what the pivot stores) and are locale-independent. Rebuilds every node so\n * the shared, cached count-free list is never mutated.\n */\nfunction withCounts(terms: TaxonomyTerm[], counts: Map<string, number>): TaxonomyTerm[] {\n\treturn terms.map((term) => ({\n\t\t...term,\n\t\tcount: counts.get(term.translationGroup ?? term.id) ?? 0,\n\t\tchildren: withCounts(term.children, counts),\n\t}));\n}\n\nasync function loadTaxonomyTerms(\n\tdef: TaxonomyDef,\n\tlocale: string | undefined,\n): Promise<TaxonomyTerm[]> {\n\tconst db = await getDb();\n\n\tlet termsQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t.where(\"name\", \"=\", def.name)\n\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t.orderBy(\"label\", \"asc\");\n\tif (locale !== undefined) termsQuery = termsQuery.where(\"locale\", \"=\", locale);\n\n\tconst rows = await termsQuery.execute();\n\n\tconst flatTerms: TaxonomyTermRow[] = rows.map((row) => ({\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tlabel: row.label,\n\t\tparent_id: row.parent_id,\n\t\tdata: row.data,\n\t\tlocale: row.locale,\n\t\ttranslation_group: row.translation_group,\n\t}));\n\n\tif (def.hierarchical) return buildTree(flatTerms);\n\n\treturn flatTerms.map((term) => ({\n\t\tid: term.id,\n\t\tname: term.name,\n\t\tslug: term.slug,\n\t\tlabel: term.label,\n\t\tdescription: term.data ? JSON.parse(term.data).description : undefined,\n\t\tchildren: [],\n\t\tlocale: term.locale,\n\t\ttranslationGroup: term.translation_group,\n\t}));\n}\n\n/**\n * Per-translation-group visible-usage counts for one taxonomy, in a single\n * round-trip (see `fetchVisibleTermCounts`). The pivot identity is the\n * translation group, while entry rows are scoped to the resolved locale.\n * Request and object cache keys include that locale so translated views never\n * reuse each other's visible counts.\n */\nfunction getVisibleTermCounts(\n\ttaxonomyName: string,\n\tcollections: string[],\n\tlocale?: string,\n): Promise<Map<string, number>> {\n\t// The collection scope is part of the key: per-locale rows of the same def\n\t// can drift in their declared collections, and a caller may pass a narrower\n\t// scope. Identical inputs (the widget + term-page hot path) still share one\n\t// entry.\n\tconst scope = [...new Set(collections)].toSorted().join(\",\");\n\tconst localeScope = locale ?? \"*\";\n\treturn requestCached(`taxonomy-term-counts:${taxonomyName}:${scope}:${localeScope}`, async () => {\n\t\t// A Map is not JSON-representable — cache the entries, rebuild on read.\n\t\tconst entries = await cachedQuery({\n\t\t\tnamespace: termCountNamespaces(collections),\n\t\t\tkey: `termCounts:${taxonomyName}:${scope}:${localeScope}`,\n\t\t\tload: async (): Promise<Array<[string, number]>> => {\n\t\t\t\tconst db = await getDb();\n\t\t\t\treturn [...(await fetchVisibleTermCounts(db, taxonomyName, collections, locale))];\n\t\t\t},\n\t\t});\n\t\treturn new Map(entries);\n\t});\n}\n\n/**\n * Get a single term by (taxonomy, slug). Honours the fallback chain — if the\n * slug exists in a fallback locale, we return that row (useful for deep-linking\n * to a term page when the translation is missing).\n */\nexport async function getTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm | null> {\n\tconst chain = resolveLocaleChain(options.locale);\n\t// The def supplies the collections the visible count is scoped to. It is\n\t// resolved before cachedQuery so the entry lives under each collection's\n\t// content namespace — publishing or unpublishing an entry invalidates the\n\t// embedded count (see termCountNamespaces).\n\tconst def = await getTaxonomyDef(taxonomyName, options);\n\tconst collections = def?.collections ?? [];\n\treturn cachedQuery({\n\t\tnamespace: termCountNamespaces(collections),\n\t\tkey: `term:${taxonomyName}:${slug}:${chain.join(\",\")}`,\n\t\tload: () => loadTerm(taxonomyName, slug, chain, collections),\n\t});\n}\n\nasync function loadTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\tchain: string[],\n\tcollections: string[],\n): Promise<TaxonomyTerm | null> {\n\tconst db = await getDb();\n\n\tlet row: Awaited<ReturnType<ReturnType<typeof selectTerm>[\"executeTakeFirst\"]>>;\n\tconst selectTerm = () =>\n\t\tdb\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", taxonomyName)\n\t\t\t.where(\"slug\", \"=\", slug);\n\n\tif (chain.length === 0) {\n\t\trow = await selectTerm().orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t} else {\n\t\trow = undefined;\n\t\tfor (const locale of chain) {\n\t\t\trow = await selectTerm().where(\"locale\", \"=\", locale).executeTakeFirst();\n\t\t\tif (row) break;\n\t\t}\n\t}\n\n\tif (!row) return null;\n\n\tlet childrenQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t// Children store the parent's translation_group in parent_id (not a row\n\t\t// id), so a translated parent still owns its children in its own locale.\n\t\t.where(\"parent_id\", \"=\", row.translation_group ?? row.id)\n\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t.orderBy(\"label\", \"asc\");\n\tconst termLocale = row.locale;\n\tif (termLocale) childrenQuery = childrenQuery.where(\"locale\", \"=\", termLocale);\n\n\t// The visible-usage counts and children queries both depend only on the\n\t// term row, so run them concurrently to save a round trip on remote\n\t// databases. The counts map is request-cached per taxonomy — on a page\n\t// that also renders the taxonomy widget it's a free Map lookup.\n\tconst [counts, childRows] = await Promise.all([\n\t\tgetVisibleTermCounts(taxonomyName, collections, chain[0] ?? row.locale),\n\t\tchildrenQuery.execute(),\n\t]);\n\tconst count = counts.get(row.translation_group ?? row.id) ?? 0;\n\n\tconst children = childRows.map<TaxonomyTerm>((child) => ({\n\t\tid: child.id,\n\t\tname: child.name,\n\t\tslug: child.slug,\n\t\tlabel: child.label,\n\t\tparentId: child.parent_id ?? undefined,\n\t\tchildren: [],\n\t\tlocale: child.locale,\n\t\ttranslationGroup: child.translation_group,\n\t}));\n\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tlabel: row.label,\n\t\tparentId: row.parent_id ?? undefined,\n\t\tdescription: row.data ? JSON.parse(row.data).description : undefined,\n\t\tchildren,\n\t\tcount,\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n/**\n * Terms assigned to a content entry, resolved into the active locale and then\n * the configured default locale.\n */\nexport function getEntryTerms(\n\tcollection: string,\n\tentryId: string,\n\ttaxonomyName?: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\t// requestCached short-circuits to values primed by getAllTermsForEntries\n\t// during entry hydration (same key shape). On a warm content-cache hit\n\t// hydration doesn't run, so the inner cachedQuery serves this from KV\n\t// instead of falling through to D1 on every request.\n\treturn requestCached(\n\t\t`terms:${collection}:${entryId}:${taxonomyName ?? \"*\"}:${locale ?? \"*\"}`,\n\t\t() =>\n\t\t\tcachedQuery({\n\t\t\t\tnamespace: [...contentCacheNamespaces(collection), CacheNamespace.TAXONOMIES],\n\t\t\t\tkey: `entryTerms:${collection}:${entryId}:${taxonomyName ?? \"*\"}:${locale ?? \"*\"}`,\n\t\t\t\tload: async () => {\n\t\t\t\t\tconst db = await getDb();\n\t\t\t\t\tconst rows = await selectEntryTermRows(db, collection, [entryId], taxonomyName, locale);\n\t\t\t\t\treturn rows.map<TaxonomyTerm>((row) => ({\n\t\t\t\t\t\tid: row.id,\n\t\t\t\t\t\tname: row.name,\n\t\t\t\t\t\tslug: row.slug,\n\t\t\t\t\t\tlabel: row.label,\n\t\t\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\t\t\tchildren: [],\n\t\t\t\t\t\tlocale: row.locale,\n\t\t\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t\t\t}));\n\t\t\t\t},\n\t\t\t}),\n\t);\n}\n\n/**\n * Terms for multiple entries of one taxonomy, single query.\n */\nexport async function getTermsForEntries(\n\tcollection: string,\n\tentryIds: string[],\n\ttaxonomyName: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Map<string, TaxonomyTerm[]>> {\n\tconst uniqueIds = [...new Set(entryIds)];\n\tif (uniqueIds.length === 0) return new Map();\n\tconst locale = resolveLocale(options.locale);\n\tconst localeKey = locale ?? \"*\";\n\n\t// The query result is a Map, which JSON can't represent — cache it as an\n\t// array of [entryId, terms] pairs and rebuild the Map on read.\n\tconst load = async (): Promise<Array<[string, TaxonomyTerm[]]>> => {\n\t\tconst result = new Map<string, TaxonomyTerm[]>();\n\t\tfor (const id of uniqueIds) result.set(id, []);\n\n\t\t// Entry-term hydration (getAllTermsForEntries -> primeEntryTermsCache)\n\t\t// seeds the per-entry cache under the same key getEntryTerms uses:\n\t\t// `terms:${collection}:${entryId}:${taxonomyName}:${localeKey}`, storing a\n\t\t// TaxonomyTerm[] (including `[]` for entries with no terms). Satisfy those\n\t\t// from cache and run the batched query only for the ids that missed.\n\t\tconst missedIds: string[] = [];\n\t\ttype CacheRead = { id: string; terms: TaxonomyTerm[] } | { id: string; miss: true };\n\t\tconst cacheReads: Array<Promise<CacheRead>> = [];\n\t\tfor (const id of uniqueIds) {\n\t\t\tconst cached = peekRequestCache<TaxonomyTerm[]>(\n\t\t\t\t`terms:${collection}:${id}:${taxonomyName}:${localeKey}`,\n\t\t\t);\n\t\t\tif (cached) {\n\t\t\t\t// A peeked promise can reject (e.g. a sibling getEntryTerms hit a\n\t\t\t\t// missing table). Treat a rejection as a cache miss so the batched\n\t\t\t\t// query path -- and its isMissingTableError guard below -- still runs,\n\t\t\t\t// rather than propagating an uncaught error.\n\t\t\t\tcacheReads.push(\n\t\t\t\t\tcached.then(\n\t\t\t\t\t\t(terms): CacheRead => ({ id, terms }),\n\t\t\t\t\t\t(): CacheRead => ({ id, miss: true }),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmissedIds.push(id);\n\t\t\t}\n\t\t}\n\t\tfor (const read of await Promise.all(cacheReads)) {\n\t\t\tif (\"miss\" in read) {\n\t\t\t\tmissedIds.push(read.id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Return a private copy. The cached array and its term objects are shared\n\t\t\t// with getEntryTerms/getAllTermsForEntries (primeEntryTermsCache stores\n\t\t\t// the same references), so a caller that mutates the result -- sorting in\n\t\t\t// place, pushing into `children` -- must not poison the cache. The\n\t\t\t// pre-cache implementation always returned freshly built arrays.\n\t\t\tresult.set(\n\t\t\t\tread.id,\n\t\t\t\tread.terms.map((t) => ({ ...t, children: [...t.children] })),\n\t\t\t);\n\t\t}\n\n\t\tif (missedIds.length === 0) return [...result.entries()];\n\n\t\tconst db = await getDb();\n\t\tfor (const chunk of chunks(missedIds, SQL_BATCH_SIZE)) {\n\t\t\tlet rows;\n\t\t\ttry {\n\t\t\t\trows = await selectEntryTermRows(db, collection, chunk, taxonomyName, locale);\n\t\t\t} catch (error) {\n\t\t\t\tif (isMissingTableError(error)) return [...result.entries()];\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst term: TaxonomyTerm = {\n\t\t\t\t\tid: row.id,\n\t\t\t\t\tname: row.name,\n\t\t\t\t\tslug: row.slug,\n\t\t\t\t\tlabel: row.label,\n\t\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\t\tchildren: [],\n\t\t\t\t\tlocale: row.locale,\n\t\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t\t};\n\t\t\t\tconst terms = result.get(row.entry_id);\n\t\t\t\tif (terms) terms.push(term);\n\t\t\t}\n\t\t}\n\n\t\treturn [...result.entries()];\n\t};\n\n\t// Key on the sorted unique ids. Bound the key length: very large batches\n\t// (rare; they come from collection hydration, already served by the content\n\t// cache) bypass the object cache rather than blow past KV's key limit.\n\tconst idKey = uniqueIds.toSorted().join(\",\");\n\tconst pairs =\n\t\tidKey.length <= 256\n\t\t\t? await cachedQuery({\n\t\t\t\t\tnamespace: [...contentCacheNamespaces(collection), CacheNamespace.TAXONOMIES],\n\t\t\t\t\tkey: `termsForEntries:${collection}:${taxonomyName}:${locale ?? \"*\"}:${idKey}`,\n\t\t\t\t\tload,\n\t\t\t\t})\n\t\t\t: await load();\n\n\treturn new Map(pairs);\n}\n\n/**\n * Batch-fetch terms for multiple entries across ALL taxonomies in one query.\n * Primes the request-cache for subsequent per-entry calls to `getEntryTerms`.\n */\nexport async function getAllTermsForEntries(\n\tcollection: string,\n\tentryIds: string[],\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Map<string, Record<string, TaxonomyTerm[]>>> {\n\tconst result = new Map<string, Record<string, TaxonomyTerm[]>>();\n\tconst uniqueIds = [...new Set(entryIds)];\n\tfor (const id of uniqueIds) result.set(id, {});\n\tif (uniqueIds.length === 0) return result;\n\n\tconst db = await getDb();\n\tconst locale = resolveLocale(options.locale);\n\tconst applicableTaxonomyNames = await getCollectionTaxonomyNames(collection, { locale });\n\n\tfor (const chunk of chunks(uniqueIds, SQL_BATCH_SIZE)) {\n\t\tlet rows;\n\t\ttry {\n\t\t\trows = await selectEntryTermRows(db, collection, chunk, undefined, locale);\n\t\t} catch (error) {\n\t\t\tif (isMissingTableError(error)) {\n\t\t\t\tfor (const id of uniqueIds) {\n\t\t\t\t\tprimeEntryTermsCache(collection, id, {}, applicableTaxonomyNames, locale);\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\tfor (const row of rows) {\n\t\t\tconst term: TaxonomyTerm = {\n\t\t\t\tid: row.id,\n\t\t\t\tname: row.name,\n\t\t\t\tslug: row.slug,\n\t\t\t\tlabel: row.label,\n\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\tchildren: [],\n\t\t\t\tlocale: row.locale,\n\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t};\n\t\t\tconst byTaxonomy = result.get(row.entry_id);\n\t\t\tif (!byTaxonomy) continue;\n\t\t\tconst existing = byTaxonomy[row.name];\n\t\t\tif (existing) existing.push(term);\n\t\t\telse byTaxonomy[row.name] = [term];\n\t\t}\n\t}\n\n\tfor (const [entryId, byTaxonomy] of result) {\n\t\tprimeEntryTermsCache(collection, entryId, byTaxonomy, applicableTaxonomyNames, locale);\n\t}\n\n\treturn result;\n}\n\n/**\n * Return the list of taxonomy names applicable to a collection, request-\n * cached so a page render only pays for it once.\n *\n * Returns an empty list when taxonomies haven't been defined yet.\n */\nasync function getCollectionTaxonomyNames(\n\tcollection: string,\n\toptions: TaxonomyQueryOptions,\n): Promise<string[]> {\n\ttry {\n\t\tconst defs = await getTaxonomyDefs(options);\n\t\treturn defs.filter((d) => d.collections.includes(collection)).map((d) => d.name);\n\t} catch (error) {\n\t\tif (isMissingTableError(error)) return [];\n\t\tthrow error;\n\t}\n}\n\n/**\n * Pre-populate the request-cache for every getEntryTerms call-shape that\n * could hit this entry:\n *\n * getEntryTerms(collection, entryId) -> key `terms:C:E:*`\n * getEntryTerms(collection, entryId, \"tag\") -> key `terms:C:E:tag`\n * getEntryTerms(collection, entryId, \"category\") -> key `terms:C:E:category`\n * ...one per taxonomy that applies to this collection\n *\n * Taxonomies with no rows on this entry are seeded with `[]` so legacy\n * callers short-circuit to the cached empty array instead of re-querying.\n */\nfunction primeEntryTermsCache(\n\tcollection: string,\n\tentryId: string,\n\tbyTaxonomy: Record<string, TaxonomyTerm[]>,\n\tapplicableTaxonomyNames: string[],\n\tlocale: string | undefined,\n): void {\n\tconst localeKey = locale ?? \"*\";\n\tfor (const name of applicableTaxonomyNames) {\n\t\tsetRequestCacheEntry(\n\t\t\t`terms:${collection}:${entryId}:${name}:${localeKey}`,\n\t\t\tbyTaxonomy[name] ?? [],\n\t\t);\n\t}\n\tfor (const [name, terms] of Object.entries(byTaxonomy)) {\n\t\tsetRequestCacheEntry(`terms:${collection}:${entryId}:${name}:${localeKey}`, terms);\n\t}\n\tconst allTerms = Object.values(byTaxonomy).flat();\n\tsetRequestCacheEntry(`terms:${collection}:${entryId}:*:${localeKey}`, allTerms);\n}\n\n/**\n * Prime the per-entry request cache from terms that were folded into the\n * content query (query.ts `hydrateEntryTerms` fast path), so subsequent\n * `getEntryTerms` calls in the same render hit the cache instead of issuing an\n * N+1 query. Seeds the wildcard key and one key per taxonomy present on the\n * entry — purely from the folded data, with no DB lookup.\n *\n * Unlike `getAllTermsForEntries`, this deliberately does NOT seed `[]` for\n * taxonomies that apply to the collection but have no rows on the entry: doing\n * so would require a `getTaxonomyDefs` query, adding a round trip to every fold\n * render to serve the rarer `getEntryTerms(id, absentTaxonomy)` case from cache.\n * That call simply falls through to its own cached query. Keeping the key shape\n * here (rather than in query.ts) prevents the two from drifting.\n */\nexport function primeFoldedEntryTerms(\n\tcollection: string,\n\tperEntry: Array<{ entryId: string; byTaxonomy: Record<string, TaxonomyTerm[]> }>,\n\toptions: TaxonomyQueryOptions = {},\n): void {\n\tif (perEntry.length === 0) return;\n\tconst locale = resolveLocale(options.locale);\n\tfor (const { entryId, byTaxonomy } of perEntry) {\n\t\tprimeEntryTermsCache(collection, entryId, byTaxonomy, [], locale);\n\t}\n}\n\n/**\n * Get entries by term. Both the lookup (term slug in the active locale) and\n * the content query respect the active locale.\n */\nexport async function getEntriesByTerm(\n\tcollection: string,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Array<{ id: string; data: Record<string, unknown> }>> {\n\tconst { getEmDashCollection } = await import(\"../query.js\");\n\n\tconst queryOptions: Record<string, unknown> = {\n\t\twhere: { [taxonomyName]: termSlug },\n\t};\n\tif (options.locale !== undefined) queryOptions.locale = options.locale;\n\tconst { entries } = await getEmDashCollection(collection, queryOptions);\n\treturn entries;\n}\n\nfunction rowToTaxonomyDef(row: {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tlabel_singular: string | null;\n\thierarchical: number;\n\tcollections: string | null;\n\tlocale: string;\n\ttranslation_group: string | null;\n}): TaxonomyDef {\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tlabel: row.label,\n\t\tlabelSingular: row.label_singular ?? undefined,\n\t\thierarchical: row.hierarchical === 1,\n\t\tcollections: row.collections ? JSON.parse(row.collections) : [],\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n/**\n * Build tree structure from flat terms\n */\nfunction buildTree(flatTerms: TaxonomyTermRow[]): TaxonomyTerm[] {\n\t// parent_id holds the parent's translation_group, so link children by it.\n\t// Key by (locale, group): a child's parent lives in the same locale, and an\n\t// unfiltered set mixes locales whose translated siblings share a group —\n\t// keying by group alone would collide and misattach children across locales.\n\tconst byLocaleGroup = new Map<string, TaxonomyTerm>();\n\tconst nodes: TaxonomyTerm[] = [];\n\tconst roots: TaxonomyTerm[] = [];\n\n\tfor (const term of flatTerms) {\n\t\tconst node: TaxonomyTerm = {\n\t\t\tid: term.id,\n\t\t\tname: term.name,\n\t\t\tslug: term.slug,\n\t\t\tlabel: term.label,\n\t\t\tparentId: term.parent_id ?? undefined,\n\t\t\tdescription: term.data ? JSON.parse(term.data).description : undefined,\n\t\t\tchildren: [],\n\t\t\tlocale: term.locale,\n\t\t\ttranslationGroup: term.translation_group,\n\t\t};\n\t\tbyLocaleGroup.set(`${term.locale}::${term.translation_group ?? term.id}`, node);\n\t\tnodes.push(node);\n\t}\n\n\tfor (const node of nodes) {\n\t\tconst parent = node.parentId\n\t\t\t? byLocaleGroup.get(`${node.locale}::${node.parentId}`)\n\t\t\t: undefined;\n\t\tif (parent) {\n\t\t\tparent.children.push(node);\n\t\t} else {\n\t\t\troots.push(node);\n\t\t}\n\t}\n\n\treturn roots;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAS,iBACR,IACA,cACA,YACA,QACyB;AACzB,QAAO,GAAG;;;eAGI,IAAI,IAAI,MAAM,aAAa,CAAC;;yBAElB,WAAW;kFAC8C,aAAa;KAC1F,SAAS,GAAG,kBAAkB,WAAW,GAAG,GAAG;SAC3C,qBAAqB,IAAI,aAAa,IAAI,CAAC;;;;AAKpD,eAAe,UACd,IACA,cACA,aACA,QAC+B;CAC/B,MAAM,WAAW,YAAY,KAAK,eACjC,iBAAiB,IA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esContent":["/**\n * Shared visible-usage counts for taxonomy terms (issue #581).\n *\n * `content_taxonomies` rows are written for every entry regardless of status\n * and are never pruned on unpublish/trash, so counting the pivot directly\n * inflates counts with drafts and soft-deleted entries. Every user-facing\n * count (public widget, single-term page, admin term list) must instead count\n * only entries that have completed publication:\n * `status = 'published'` AND `deleted_at IS NULL`.\n *\n * The public render path is latency-sensitive on D1, so per-collection counts\n * are combined with UNION ALL — one query per taxonomy, never one per\n * collection, split only where the backend caps compound-SELECT terms.\n */\n\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport { buildStatusCondition, compoundSelectLimit } from \"../database/dialect-helpers.js\";\nimport type { Database } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport { chunks } from \"../utils/chunks.js\";\nimport { isMissingTableError } from \"../utils/db-errors.js\";\n\ninterface CountRow {\n\ttaxonomy_id: string;\n\tcount: number | string | bigint;\n}\n\n/**\n * Per-collection count branch. `taxonomy_id` stores the term's\n * translation_group, so results are keyed by group (locale-independent) and\n * each assignment is counted once per content translation group. When a\n * locale is provided, only that group's matching content row contributes.\n *\n * Scoping to the taxonomy uses `translation_group IN (...)` rather than a\n * join on `taxonomies.id` — the anchor row (id == group) can be deleted while\n * sibling translations survive, and a plain join on `translation_group` would\n * multiply counts by the number of locales.\n *\n * CROSS JOIN with the join predicate in WHERE keeps stats-blind SQLite/D1 from\n * reordering content_taxonomies out of the outer position; it touches ec_* only\n * through the translation-group index. Postgres treats this as an ordinary\n * inner join and plans freely.\n */\nfunction collectionBranch(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollection: string,\n\tlocale?: string,\n): ReturnType<typeof sql> {\n\treturn sql`\n\t\tSELECT ct.taxonomy_id AS taxonomy_id, COUNT(DISTINCT e.translation_group) AS count\n\t\tFROM content_taxonomies AS ct\n\t\tCROSS JOIN ${sql.ref(`ec_${collection}`)} AS e\n\t\tWHERE e.translation_group = ct.entry_id\n\t\t\tAND ct.collection = ${collection}\n\t\t\tAND ct.taxonomy_id IN (SELECT translation_group FROM taxonomies WHERE name = ${taxonomyName})\n\t\t\t${locale ? sql`AND e.locale = ${locale}` : sql``}\n\t\t\tAND ${buildStatusCondition(db, \"published\", \"e\")}\n\t\t\tAND e.deleted_at IS NULL\n\t\tGROUP BY ct.taxonomy_id`;\n}\n\nasync function runCounts(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollections: string[],\n\tlocale?: string,\n): Promise<Map<string, number>> {\n\tconst branches = collections.map((collection) =>\n\t\tcollectionBranch(db, taxonomyName, collection, locale),\n\t);\n\tconst union = sql.join(branches, sql` UNION ALL `);\n\tconst result = await sql<CountRow>`\n\t\tSELECT taxonomy_id, SUM(count) AS count\n\t\tFROM (${union}) AS per_collection\n\t\tGROUP BY taxonomy_id`.execute(db);\n\n\tconst counts = new Map<string, number>();\n\tfor (const row of result.rows) counts.set(row.taxonomy_id, Number(row.count));\n\treturn counts;\n}\n\nfunction addCounts(into: Map<string, number>, from: Map<string, number>): void {\n\tfor (const [group, count] of from) into.set(group, (into.get(group) ?? 0) + count);\n}\n\n/**\n * Counts for one batch of collections, degrading to a query per collection\n * when a declared collection has no ec_* table so the rest still contribute.\n */\nasync function runBatch(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollections: string[],\n\tlocale?: string,\n): Promise<Map<string, number>> {\n\ttry {\n\t\treturn await runCounts(db, taxonomyName, collections, locale);\n\t} catch (error) {\n\t\tif (!isMissingTableError(error)) throw error;\n\t}\n\n\tconst counts = new Map<string, number>();\n\tfor (const collection of collections) {\n\t\ttry {\n\t\t\taddCounts(counts, await runCounts(db, taxonomyName, [collection], locale));\n\t\t} catch (error) {\n\t\t\tif (!isMissingTableError(error)) throw error;\n\t\t}\n\t}\n\treturn counts;\n}\n\n/**\n * Count publicly-visible term assignments for one taxonomy, keyed by the\n * term's translation_group (what `content_taxonomies.taxonomy_id` stores).\n * When `locale` is provided, only entries in that locale contribute. Omitting\n * it preserves the locale-agnostic API used by legacy callers.\n *\n * Counts are scoped to the taxonomy's declared collections — pass\n * `TaxonomyDef.collections` (`_emdash_taxonomy_defs.collections`). Collections\n * whose `ec_*` table doesn't exist (pre-migration drift, a declared collection\n * that was never created) are skipped, yielding a partial-but-correct count\n * rather than a throw.\n *\n * One database round-trip for the whole taxonomy (UNION ALL across\n * collections). On a backend that caps compound-SELECT terms — D1 allows five\n * — the branches are split into one statement per batch, since a taxonomy\n * declaring more collections than that would otherwise take down every path\n * that shows counts. Per-collection sums are commutative, so batching cannot\n * change the total.\n *\n * Callers on the public render path should go through the request-cached\n * wrapper in `taxonomies/index.ts` so a page rendering both the widget and a\n * term detail shares one computation.\n */\nexport async function fetchVisibleTermCounts(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tcollections: string[],\n\tlocale?: string,\n): Promise<Map<string, number>> {\n\tconst unique = [...new Set(collections)];\n\tfor (const collection of unique) validateIdentifier(collection, \"collection slug\");\n\tif (unique.length === 0) return new Map();\n\n\tconst limit = compoundSelectLimit(db);\n\tconst batched = limit === null ? [unique] : chunks(unique, limit);\n\tconst batches = await Promise.all(\n\t\tbatched.map((batch) => runBatch(db, taxonomyName, batch, locale)),\n\t);\n\n\tconst counts = new Map<string, number>();\n\tfor (const batch of batches) addCounts(counts, batch);\n\treturn counts;\n}\n","/**\n * Runtime API for taxonomies.\n *\n * All helpers are locale-aware. When a locale is not passed explicitly we fall\n * back to the request context or the configured `defaultLocale` (see\n * `i18n/resolve.ts`).\n *\n * Because `content_taxonomies.taxonomy_id` stores the translation_group (not a\n * specific term id), and `entry_id` stores the content translation_group, one\n * assignment resolves to the requested locale on both sides.\n */\n\nimport { sql, type Kysely } from \"kysely\";\n\nimport type { Database } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport { getI18nConfig } from \"../i18n/config.js\";\nimport { resolveLocale, resolveLocaleChain } from \"../i18n/resolve.js\";\nimport { getDb, resetTaxonomyNamesCache } from \"../loader.js\";\nimport {\n\tcachedQuery,\n\tCacheNamespace,\n\tcontentCacheNamespaces,\n\tinvalidateTaxonomyObjectCache,\n\tisObjectCacheActive,\n} from \"../object-cache/index.js\";\nimport { peekRequestCache, requestCached, setRequestCacheEntry } from \"../request-cache.js\";\nimport { getRequestContext } from \"../request-context.js\";\nimport { chunks, SQL_BATCH_SIZE } from \"../utils/chunks.js\";\nimport { isMissingTableError } from \"../utils/db-errors.js\";\nimport { fetchVisibleTermCounts } from \"./term-counts.js\";\nimport type { TaxonomyDef, TaxonomyTerm, TaxonomyTermRow } from \"./types.js\";\n\nexport interface TaxonomyQueryOptions {\n\tlocale?: string;\n}\n\nexport interface TaxonomyTermsOptions extends TaxonomyQueryOptions {\n\t/**\n\t * Populate each term's `count`. Counts aggregate the whole\n\t * `content_taxonomies` pivot against every declared collection, so callers\n\t * that don't render a count should opt out. Defaults to `true`.\n\t */\n\tincludeCounts?: boolean;\n}\n\ninterface EntryTermRow {\n\tentry_id: string;\n\tid: string;\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparent_id: string | null;\n\tlocale: string;\n\ttranslation_group: string | null;\n}\n\nasync function selectEntryTermRows(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tentryIds: string[],\n\ttaxonomyName?: string,\n\tlocale?: string,\n): Promise<EntryTermRow[]> {\n\tvalidateIdentifier(collection, \"collection slug\");\n\tconst tableName = `ec_${collection}`;\n\tconst preferredLocale = locale ? sql`${locale}` : sql`content.locale`;\n\tconst defaultLocale = getI18nConfig()?.defaultLocale ?? \"en\";\n\tconst result = await sql<EntryTermRow>`\n\t\tSELECT content.id AS entry_id,\n\t\t\tcoalesce(exact_term.id, default_term.id) AS id,\n\t\t\tcoalesce(exact_term.name, default_term.name) AS name,\n\t\t\tcoalesce(exact_term.slug, default_term.slug) AS slug,\n\t\t\tcoalesce(exact_term.label, default_term.label) AS label,\n\t\t\tcoalesce(exact_term.parent_id, default_term.parent_id) AS parent_id,\n\t\t\tcoalesce(exact_term.locale, default_term.locale) AS locale,\n\t\t\tcoalesce(exact_term.translation_group, default_term.translation_group) AS translation_group\n\t\tFROM ${sql.ref(tableName)} AS content\n\t\tINNER JOIN content_taxonomies AS pivot\n\t\t\tON pivot.entry_id = content.translation_group\n\t\t\tAND pivot.collection = ${collection}\n\t\tLEFT JOIN taxonomies AS exact_term\n\t\t\tON exact_term.translation_group = pivot.taxonomy_id\n\t\t\tAND exact_term.locale = ${preferredLocale}\n\t\tLEFT JOIN taxonomies AS default_term\n\t\t\tON default_term.translation_group = pivot.taxonomy_id\n\t\t\tAND default_term.locale = ${defaultLocale}\n\t\tWHERE content.id IN (${sql.join(entryIds.map((id) => sql`${id}`))})\n\t\t\tAND coalesce(exact_term.id, default_term.id) IS NOT NULL\n\t\t\t${taxonomyName ? sql`AND coalesce(exact_term.name, default_term.name) = ${taxonomyName}` : sql``}\n\t\tORDER BY coalesce(exact_term.label, default_term.label) ASC\n\t`.execute(db);\n\treturn result.rows;\n}\n\n/** Invalidate cached taxonomy term data and any content that hydrates terms. */\nexport function invalidateTermCache(): void {\n\tinvalidateTaxonomyObjectCache();\n}\n\n/**\n * Worker-isolate cache for taxonomy definitions, keyed by resolved locale.\n *\n * Taxonomy *definitions* (the \"category\"/\"tag\" taxonomies themselves, not\n * their terms) are read on every public render that hydrates entry terms —\n * `getAllTermsForEntries` → `getCollectionTaxonomyNames` → `getTaxonomyDefs` —\n * but change extremely rarely: they're written only by the admin API and by\n * seed application. Caching them across the isolate lifetime drops the\n * per-render `SELECT * FROM _emdash_taxonomy_defs` to once-per-isolate.\n *\n * Stored on globalThis behind a Symbol key (same pattern as\n * `settings/index.ts`) so the bundler duplicating this module across SSR\n * chunks can't produce two independent caches.\n *\n * When the distributed object cache is configured, it is authoritative and this\n * fallback is bypassed so cross-isolate epoch invalidation cannot be undercut\n * by stale per-isolate data on an object-cache miss.\n *\n * **Isolated databases bypass the cache.** Playground / DO preview requests\n * set `requestContext.dbIsIsolated`; they point at a divergent schema, so we\n * skip both reading and writing the global holder and fall back to the\n * per-request cache (same precedent as `getTaxonomyNames` / byline field defs).\n */\ninterface TaxonomyDefsHolder {\n\tversion: number;\n\t/** locale key (\"*\" for \"all locales\") → { version it was fetched at, promise }. */\n\tcache: Map<string, { version: number; promise: Promise<TaxonomyDef[]> }>;\n}\n\nconst TAXONOMY_DEFS_CACHE_KEY = Symbol.for(\"emdash:taxonomy-defs\");\nconst taxonomyDefsStore = globalThis as Record<symbol, unknown>;\nconst defsHolder: TaxonomyDefsHolder =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see settings/index.ts)\n\t(taxonomyDefsStore[TAXONOMY_DEFS_CACHE_KEY] as TaxonomyDefsHolder | undefined) ??\n\t(() => {\n\t\tconst h: TaxonomyDefsHolder = { version: 0, cache: new Map() };\n\t\ttaxonomyDefsStore[TAXONOMY_DEFS_CACHE_KEY] = h;\n\t\treturn h;\n\t})();\n\n/**\n * Invalidate the isolate-wide taxonomy-definitions cache (and the related\n * loader taxonomy-names cache). Called from every taxonomy-def write path\n * (`handleTaxonomyCreate`/`Update`/`Delete`, seed application). Other isolates\n * refresh on their next recycle — staleness bounded by isolate lifetime.\n */\nexport function invalidateTaxonomyDefsCache(): void {\n\tdefsHolder.version++;\n\tdefsHolder.cache.clear();\n\tresetTaxonomyNamesCache();\n\tinvalidateTaxonomyObjectCache();\n}\n\n/**\n * Test/internal helper: clear the per-isolate taxonomy-defs cache. Useful for\n * unit tests that insert defs directly and need to force a refetch without\n * going through a write path. Production code should rely on\n * `invalidateTaxonomyDefsCache()`.\n */\nexport function resetTaxonomyDefsCacheForTests(): void {\n\tdefsHolder.version++;\n\tdefsHolder.cache.clear();\n}\n\n/**\n * Fetch taxonomy definitions straight from the database (no caching).\n */\nasync function fetchTaxonomyDefs(locale: string | undefined): Promise<TaxonomyDef[]> {\n\tconst db = await getDb();\n\tlet query = db.selectFrom(\"_emdash_taxonomy_defs\").selectAll();\n\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\tconst rows = await query.execute();\n\treturn rows.map(rowToTaxonomyDef);\n}\n\n/**\n * Resolve taxonomy defs through the isolate fallback cache, bypassing it for\n * isolated databases. The returned promise is cached (not the resolved value)\n * so concurrent cold-isolate readers share one in-flight query; a rejection\n * evicts the entry so the next caller retries.\n */\nfunction loadTaxonomyDefs(localeKey: string, locale: string | undefined): Promise<TaxonomyDef[]> {\n\tif (getRequestContext()?.dbIsIsolated === true) {\n\t\treturn fetchTaxonomyDefs(locale);\n\t}\n\tconst existing = defsHolder.cache.get(localeKey);\n\tif (existing && existing.version === defsHolder.version) {\n\t\treturn existing.promise;\n\t}\n\tconst version = defsHolder.version;\n\tconst promise = fetchTaxonomyDefs(locale).catch((error: unknown) => {\n\t\tconst current = defsHolder.cache.get(localeKey);\n\t\tif (current && current.promise === promise) {\n\t\t\tdefsHolder.cache.delete(localeKey);\n\t\t}\n\t\tthrow error;\n\t});\n\tdefsHolder.cache.set(localeKey, { version, promise });\n\treturn promise;\n}\n\n/**\n * Get every taxonomy definition. Definitions are per-locale (one row per\n * locale inside the same translation_group) — by default we resolve to the\n * active locale.\n *\n * Two-tier cache: per-request via `requestCached` (so a single render that\n * hydrates terms for several collections pays at most one call), then\n * per-isolate via the global holder (so warm renders issue zero queries).\n * The `requestCached` key is unchanged so `getTaxonomyDef`'s peek still hits.\n */\nexport async function getTaxonomyDefs(options: TaxonomyQueryOptions = {}): Promise<TaxonomyDef[]> {\n\tconst locale = resolveLocale(options.locale);\n\tconst localeKey = locale ?? \"*\";\n\treturn requestCached(`taxonomy-defs:${localeKey}`, async () => {\n\t\tif (await isObjectCacheActive()) {\n\t\t\treturn cachedQuery({\n\t\t\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\t\t\tkey: `defs:${localeKey}`,\n\t\t\t\tload: () => fetchTaxonomyDefs(locale),\n\t\t\t});\n\t\t}\n\t\treturn loadTaxonomyDefs(localeKey, locale);\n\t});\n}\n\n/**\n * Get a single taxonomy definition by name. Uses the fallback chain so even\n * if there is no translation for the active locale we still return something.\n *\n * If `getTaxonomyDefs()` has already loaded the full list in this request\n * (which happens during entry-term hydration on every page that renders a\n * collection), search the matching def in memory rather than running a\n * second query against `_emdash_taxonomy_defs`.\n */\nexport async function getTaxonomyDef(\n\tname: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyDef | null> {\n\tconst chain = resolveLocaleChain(options.locale);\n\tconst peekKey = `taxonomy-defs:${resolveLocale(options.locale) ?? \"*\"}`;\n\tconst allDefs = peekRequestCache<TaxonomyDef[]>(peekKey);\n\tif (allDefs) {\n\t\tconst defs = await allDefs;\n\t\tif (chain.length === 0) return defs.find((d) => d.name === name) ?? null;\n\t\tfor (const locale of chain) {\n\t\t\tconst found = defs.find((d) => d.name === name && d.locale === locale);\n\t\t\tif (found) return found;\n\t\t}\n\t\treturn null;\n\t}\n\n\treturn requestCached(`taxonomy-def:${name}:${chain.join(\",\")}`, async () => {\n\t\tconst db = await getDb();\n\n\t\tif (chain.length === 0) {\n\t\t\tconst row = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"name\", \"=\", name)\n\t\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t\t.executeTakeFirst();\n\t\t\treturn row ? rowToTaxonomyDef(row) : null;\n\t\t}\n\n\t\tfor (const locale of chain) {\n\t\t\tconst row = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"name\", \"=\", name)\n\t\t\t\t.where(\"locale\", \"=\", locale)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (row) return rowToTaxonomyDef(row);\n\t\t}\n\t\treturn null;\n\t});\n}\n\n/**\n * Object-cache namespaces for values that embed visible term counts: the\n * taxonomy epoch (term/assignment writes) plus each counted collection's\n * content epoch, so publishing, unpublishing, or trashing an entry\n * invalidates the cached count promptly. Both content namespace generations\n * participate so rolling deployments preserve invalidation in either direction.\n */\nfunction termCountNamespaces(collections: string[]): string[] {\n\treturn [\n\t\t...[...new Set(collections)].flatMap((collection) => contentCacheNamespaces(collection)),\n\t\tCacheNamespace.TAXONOMIES,\n\t];\n}\n\n/**\n * All terms of a taxonomy in a specific locale (flat for non-hierarchical,\n * tree for hierarchical).\n *\n * The term list and the visible-entry counts are loaded and cached separately:\n * the list depends only on the taxonomy epoch, while the counts additionally\n * depend on every counted collection's content epoch and cost an aggregate over\n * the whole assignment pivot. Callers that don't render counts pass\n * `includeCounts: false` and skip that aggregate entirely, while still sharing\n * the term list with callers that do.\n */\nexport async function getTaxonomyTerms(\n\ttaxonomyName: string,\n\toptions: TaxonomyTermsOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\tconst def = await getTaxonomyDef(taxonomyName, options);\n\tif (!def) return [];\n\tif (options.includeCounts === false) return getTermList(def, locale);\n\n\t// The two are independent, so run them concurrently to save a round trip.\n\tconst [terms, counts] = await Promise.all([\n\t\tgetTermList(def, locale),\n\t\tgetVisibleTermCounts(def.name, def.collections, locale),\n\t]);\n\treturn withCounts(terms, counts);\n}\n\n/** Terms without counts, under the cache keys the layout prefetch warms. */\nfunction getTermList(def: TaxonomyDef, locale: string | undefined): Promise<TaxonomyTerm[]> {\n\tconst localeKey = locale ?? \"*\";\n\treturn requestCached(`taxonomy-terms:${def.name}:${localeKey}`, () =>\n\t\tcachedQuery({\n\t\t\tnamespace: CacheNamespace.TAXONOMIES,\n\t\t\tkey: `termList:${def.name}:${localeKey}`,\n\t\t\tload: () => loadTaxonomyTerms(def, locale),\n\t\t}),\n\t);\n}\n\n/**\n * Copy a term list with counts attached. Counts are keyed by translation_group\n * (what the pivot stores) and are locale-independent. Rebuilds every node so\n * the shared, cached count-free list is never mutated.\n */\nfunction withCounts(terms: TaxonomyTerm[], counts: Map<string, number>): TaxonomyTerm[] {\n\treturn terms.map((term) => ({\n\t\t...term,\n\t\tcount: counts.get(term.translationGroup ?? term.id) ?? 0,\n\t\tchildren: withCounts(term.children, counts),\n\t}));\n}\n\nasync function loadTaxonomyTerms(\n\tdef: TaxonomyDef,\n\tlocale: string | undefined,\n): Promise<TaxonomyTerm[]> {\n\tconst db = await getDb();\n\n\tlet termsQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t.where(\"name\", \"=\", def.name)\n\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t.orderBy(\"label\", \"asc\");\n\tif (locale !== undefined) termsQuery = termsQuery.where(\"locale\", \"=\", locale);\n\n\tconst rows = await termsQuery.execute();\n\n\tconst flatTerms: TaxonomyTermRow[] = rows.map((row) => ({\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tlabel: row.label,\n\t\tparent_id: row.parent_id,\n\t\tdata: row.data,\n\t\tlocale: row.locale,\n\t\ttranslation_group: row.translation_group,\n\t}));\n\n\tif (def.hierarchical) return buildTree(flatTerms);\n\n\treturn flatTerms.map((term) => ({\n\t\tid: term.id,\n\t\tname: term.name,\n\t\tslug: term.slug,\n\t\tlabel: term.label,\n\t\tdescription: term.data ? JSON.parse(term.data).description : undefined,\n\t\tchildren: [],\n\t\tlocale: term.locale,\n\t\ttranslationGroup: term.translation_group,\n\t}));\n}\n\n/**\n * Per-translation-group visible-usage counts for one taxonomy, in a single\n * round-trip (see `fetchVisibleTermCounts`). The pivot identity is the\n * translation group, while entry rows are scoped to the resolved locale.\n * Request and object cache keys include that locale so translated views never\n * reuse each other's visible counts.\n */\nfunction getVisibleTermCounts(\n\ttaxonomyName: string,\n\tcollections: string[],\n\tlocale?: string,\n): Promise<Map<string, number>> {\n\t// The collection scope is part of the key: per-locale rows of the same def\n\t// can drift in their declared collections, and a caller may pass a narrower\n\t// scope. Identical inputs (the widget + term-page hot path) still share one\n\t// entry.\n\tconst scope = [...new Set(collections)].toSorted().join(\",\");\n\tconst localeScope = locale ?? \"*\";\n\treturn requestCached(`taxonomy-term-counts:${taxonomyName}:${scope}:${localeScope}`, async () => {\n\t\t// A Map is not JSON-representable — cache the entries, rebuild on read.\n\t\tconst entries = await cachedQuery({\n\t\t\tnamespace: termCountNamespaces(collections),\n\t\t\tkey: `termCounts:${taxonomyName}:${scope}:${localeScope}`,\n\t\t\tload: async (): Promise<Array<[string, number]>> => {\n\t\t\t\tconst db = await getDb();\n\t\t\t\treturn [...(await fetchVisibleTermCounts(db, taxonomyName, collections, locale))];\n\t\t\t},\n\t\t});\n\t\treturn new Map(entries);\n\t});\n}\n\n/**\n * Get a single term by (taxonomy, slug). Honours the fallback chain — if the\n * slug exists in a fallback locale, we return that row (useful for deep-linking\n * to a term page when the translation is missing).\n */\nexport async function getTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm | null> {\n\tconst chain = resolveLocaleChain(options.locale);\n\t// The def supplies the collections the visible count is scoped to. It is\n\t// resolved before cachedQuery so the entry lives under each collection's\n\t// content namespace — publishing or unpublishing an entry invalidates the\n\t// embedded count (see termCountNamespaces).\n\tconst def = await getTaxonomyDef(taxonomyName, options);\n\tconst collections = def?.collections ?? [];\n\treturn cachedQuery({\n\t\tnamespace: termCountNamespaces(collections),\n\t\tkey: `term:${taxonomyName}:${slug}:${chain.join(\",\")}`,\n\t\tload: () => loadTerm(taxonomyName, slug, chain, collections),\n\t});\n}\n\nasync function loadTerm(\n\ttaxonomyName: string,\n\tslug: string,\n\tchain: string[],\n\tcollections: string[],\n): Promise<TaxonomyTerm | null> {\n\tconst db = await getDb();\n\n\tlet row: Awaited<ReturnType<ReturnType<typeof selectTerm>[\"executeTakeFirst\"]>>;\n\tconst selectTerm = () =>\n\t\tdb\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"name\", \"=\", taxonomyName)\n\t\t\t.where(\"slug\", \"=\", slug);\n\n\tif (chain.length === 0) {\n\t\trow = await selectTerm().orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t} else {\n\t\trow = undefined;\n\t\tfor (const locale of chain) {\n\t\t\trow = await selectTerm().where(\"locale\", \"=\", locale).executeTakeFirst();\n\t\t\tif (row) break;\n\t\t}\n\t}\n\n\tif (!row) return null;\n\n\tlet childrenQuery = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.selectAll()\n\t\t// Children store the parent's translation_group in parent_id (not a row\n\t\t// id), so a translated parent still owns its children in its own locale.\n\t\t.where(\"parent_id\", \"=\", row.translation_group ?? row.id)\n\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t.orderBy(\"label\", \"asc\");\n\tconst termLocale = row.locale;\n\tif (termLocale) childrenQuery = childrenQuery.where(\"locale\", \"=\", termLocale);\n\n\t// The visible-usage counts and children queries both depend only on the\n\t// term row, so run them concurrently to save a round trip on remote\n\t// databases. The counts map is request-cached per taxonomy — on a page\n\t// that also renders the taxonomy widget it's a free Map lookup.\n\tconst [counts, childRows] = await Promise.all([\n\t\tgetVisibleTermCounts(taxonomyName, collections, chain[0] ?? row.locale),\n\t\tchildrenQuery.execute(),\n\t]);\n\tconst count = counts.get(row.translation_group ?? row.id) ?? 0;\n\n\tconst children = childRows.map<TaxonomyTerm>((child) => ({\n\t\tid: child.id,\n\t\tname: child.name,\n\t\tslug: child.slug,\n\t\tlabel: child.label,\n\t\tparentId: child.parent_id ?? undefined,\n\t\tchildren: [],\n\t\tlocale: child.locale,\n\t\ttranslationGroup: child.translation_group,\n\t}));\n\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tslug: row.slug,\n\t\tlabel: row.label,\n\t\tparentId: row.parent_id ?? undefined,\n\t\tdescription: row.data ? JSON.parse(row.data).description : undefined,\n\t\tchildren,\n\t\tcount,\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n/**\n * Terms assigned to a content entry, resolved into the active locale and then\n * the configured default locale.\n */\nexport function getEntryTerms(\n\tcollection: string,\n\tentryId: string,\n\ttaxonomyName?: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<TaxonomyTerm[]> {\n\tconst locale = resolveLocale(options.locale);\n\t// requestCached short-circuits to values primed by getAllTermsForEntries\n\t// during entry hydration (same key shape). On a warm content-cache hit\n\t// hydration doesn't run, so the inner cachedQuery serves this from KV\n\t// instead of falling through to D1 on every request.\n\treturn requestCached(\n\t\t`terms:${collection}:${entryId}:${taxonomyName ?? \"*\"}:${locale ?? \"*\"}`,\n\t\t() =>\n\t\t\tcachedQuery({\n\t\t\t\tnamespace: [...contentCacheNamespaces(collection), CacheNamespace.TAXONOMIES],\n\t\t\t\tkey: `entryTerms:${collection}:${entryId}:${taxonomyName ?? \"*\"}:${locale ?? \"*\"}`,\n\t\t\t\tload: async () => {\n\t\t\t\t\tconst db = await getDb();\n\t\t\t\t\tconst rows = await selectEntryTermRows(db, collection, [entryId], taxonomyName, locale);\n\t\t\t\t\treturn rows.map<TaxonomyTerm>((row) => ({\n\t\t\t\t\t\tid: row.id,\n\t\t\t\t\t\tname: row.name,\n\t\t\t\t\t\tslug: row.slug,\n\t\t\t\t\t\tlabel: row.label,\n\t\t\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\t\t\tchildren: [],\n\t\t\t\t\t\tlocale: row.locale,\n\t\t\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t\t\t}));\n\t\t\t\t},\n\t\t\t}),\n\t);\n}\n\n/**\n * Terms for multiple entries of one taxonomy, single query.\n */\nexport async function getTermsForEntries(\n\tcollection: string,\n\tentryIds: string[],\n\ttaxonomyName: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Map<string, TaxonomyTerm[]>> {\n\tconst uniqueIds = [...new Set(entryIds)];\n\tif (uniqueIds.length === 0) return new Map();\n\tconst locale = resolveLocale(options.locale);\n\tconst localeKey = locale ?? \"*\";\n\n\t// The query result is a Map, which JSON can't represent — cache it as an\n\t// array of [entryId, terms] pairs and rebuild the Map on read.\n\tconst load = async (): Promise<Array<[string, TaxonomyTerm[]]>> => {\n\t\tconst result = new Map<string, TaxonomyTerm[]>();\n\t\tfor (const id of uniqueIds) result.set(id, []);\n\n\t\t// Entry-term hydration (getAllTermsForEntries -> primeEntryTermsCache)\n\t\t// seeds the per-entry cache under the same key getEntryTerms uses:\n\t\t// `terms:${collection}:${entryId}:${taxonomyName}:${localeKey}`, storing a\n\t\t// TaxonomyTerm[] (including `[]` for entries with no terms). Satisfy those\n\t\t// from cache and run the batched query only for the ids that missed.\n\t\tconst missedIds: string[] = [];\n\t\ttype CacheRead = { id: string; terms: TaxonomyTerm[] } | { id: string; miss: true };\n\t\tconst cacheReads: Array<Promise<CacheRead>> = [];\n\t\tfor (const id of uniqueIds) {\n\t\t\tconst cached = peekRequestCache<TaxonomyTerm[]>(\n\t\t\t\t`terms:${collection}:${id}:${taxonomyName}:${localeKey}`,\n\t\t\t);\n\t\t\tif (cached) {\n\t\t\t\t// A peeked promise can reject (e.g. a sibling getEntryTerms hit a\n\t\t\t\t// missing table). Treat a rejection as a cache miss so the batched\n\t\t\t\t// query path -- and its isMissingTableError guard below -- still runs,\n\t\t\t\t// rather than propagating an uncaught error.\n\t\t\t\tcacheReads.push(\n\t\t\t\t\tcached.then(\n\t\t\t\t\t\t(terms): CacheRead => ({ id, terms }),\n\t\t\t\t\t\t(): CacheRead => ({ id, miss: true }),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmissedIds.push(id);\n\t\t\t}\n\t\t}\n\t\tfor (const read of await Promise.all(cacheReads)) {\n\t\t\tif (\"miss\" in read) {\n\t\t\t\tmissedIds.push(read.id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Return a private copy. The cached array and its term objects are shared\n\t\t\t// with getEntryTerms/getAllTermsForEntries (primeEntryTermsCache stores\n\t\t\t// the same references), so a caller that mutates the result -- sorting in\n\t\t\t// place, pushing into `children` -- must not poison the cache. The\n\t\t\t// pre-cache implementation always returned freshly built arrays.\n\t\t\tresult.set(\n\t\t\t\tread.id,\n\t\t\t\tread.terms.map((t) => ({ ...t, children: [...t.children] })),\n\t\t\t);\n\t\t}\n\n\t\tif (missedIds.length === 0) return [...result.entries()];\n\n\t\tconst db = await getDb();\n\t\tfor (const chunk of chunks(missedIds, SQL_BATCH_SIZE)) {\n\t\t\tlet rows;\n\t\t\ttry {\n\t\t\t\trows = await selectEntryTermRows(db, collection, chunk, taxonomyName, locale);\n\t\t\t} catch (error) {\n\t\t\t\tif (isMissingTableError(error)) return [...result.entries()];\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst term: TaxonomyTerm = {\n\t\t\t\t\tid: row.id,\n\t\t\t\t\tname: row.name,\n\t\t\t\t\tslug: row.slug,\n\t\t\t\t\tlabel: row.label,\n\t\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\t\tchildren: [],\n\t\t\t\t\tlocale: row.locale,\n\t\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t\t};\n\t\t\t\tconst terms = result.get(row.entry_id);\n\t\t\t\tif (terms) terms.push(term);\n\t\t\t}\n\t\t}\n\n\t\treturn [...result.entries()];\n\t};\n\n\t// Key on the sorted unique ids. Bound the key length: very large batches\n\t// (rare; they come from collection hydration, already served by the content\n\t// cache) bypass the object cache rather than blow past KV's key limit.\n\tconst idKey = uniqueIds.toSorted().join(\",\");\n\tconst pairs =\n\t\tidKey.length <= 256\n\t\t\t? await cachedQuery({\n\t\t\t\t\tnamespace: [...contentCacheNamespaces(collection), CacheNamespace.TAXONOMIES],\n\t\t\t\t\tkey: `termsForEntries:${collection}:${taxonomyName}:${locale ?? \"*\"}:${idKey}`,\n\t\t\t\t\tload,\n\t\t\t\t})\n\t\t\t: await load();\n\n\treturn new Map(pairs);\n}\n\n/**\n * Batch-fetch terms for multiple entries across ALL taxonomies in one query.\n * Primes the request-cache for subsequent per-entry calls to `getEntryTerms`.\n */\nexport async function getAllTermsForEntries(\n\tcollection: string,\n\tentryIds: string[],\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Map<string, Record<string, TaxonomyTerm[]>>> {\n\tconst result = new Map<string, Record<string, TaxonomyTerm[]>>();\n\tconst uniqueIds = [...new Set(entryIds)];\n\tfor (const id of uniqueIds) result.set(id, {});\n\tif (uniqueIds.length === 0) return result;\n\n\tconst db = await getDb();\n\tconst locale = resolveLocale(options.locale);\n\tconst applicableTaxonomyNames = await getCollectionTaxonomyNames(collection, { locale });\n\n\tfor (const chunk of chunks(uniqueIds, SQL_BATCH_SIZE)) {\n\t\tlet rows;\n\t\ttry {\n\t\t\trows = await selectEntryTermRows(db, collection, chunk, undefined, locale);\n\t\t} catch (error) {\n\t\t\tif (isMissingTableError(error)) {\n\t\t\t\tfor (const id of uniqueIds) {\n\t\t\t\t\tprimeEntryTermsCache(collection, id, {}, applicableTaxonomyNames, locale);\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\n\t\tfor (const row of rows) {\n\t\t\tconst term: TaxonomyTerm = {\n\t\t\t\tid: row.id,\n\t\t\t\tname: row.name,\n\t\t\t\tslug: row.slug,\n\t\t\t\tlabel: row.label,\n\t\t\t\tparentId: row.parent_id ?? undefined,\n\t\t\t\tchildren: [],\n\t\t\t\tlocale: row.locale,\n\t\t\t\ttranslationGroup: row.translation_group,\n\t\t\t};\n\t\t\tconst byTaxonomy = result.get(row.entry_id);\n\t\t\tif (!byTaxonomy) continue;\n\t\t\tconst existing = byTaxonomy[row.name];\n\t\t\tif (existing) existing.push(term);\n\t\t\telse byTaxonomy[row.name] = [term];\n\t\t}\n\t}\n\n\tfor (const [entryId, byTaxonomy] of result) {\n\t\tprimeEntryTermsCache(collection, entryId, byTaxonomy, applicableTaxonomyNames, locale);\n\t}\n\n\treturn result;\n}\n\n/**\n * Return the list of taxonomy names applicable to a collection, request-\n * cached so a page render only pays for it once.\n *\n * Returns an empty list when taxonomies haven't been defined yet.\n */\nasync function getCollectionTaxonomyNames(\n\tcollection: string,\n\toptions: TaxonomyQueryOptions,\n): Promise<string[]> {\n\ttry {\n\t\tconst defs = await getTaxonomyDefs(options);\n\t\treturn defs.filter((d) => d.collections.includes(collection)).map((d) => d.name);\n\t} catch (error) {\n\t\tif (isMissingTableError(error)) return [];\n\t\tthrow error;\n\t}\n}\n\n/**\n * Pre-populate the request-cache for every getEntryTerms call-shape that\n * could hit this entry:\n *\n * getEntryTerms(collection, entryId) -> key `terms:C:E:*`\n * getEntryTerms(collection, entryId, \"tag\") -> key `terms:C:E:tag`\n * getEntryTerms(collection, entryId, \"category\") -> key `terms:C:E:category`\n * ...one per taxonomy that applies to this collection\n *\n * Taxonomies with no rows on this entry are seeded with `[]` so legacy\n * callers short-circuit to the cached empty array instead of re-querying.\n */\nfunction primeEntryTermsCache(\n\tcollection: string,\n\tentryId: string,\n\tbyTaxonomy: Record<string, TaxonomyTerm[]>,\n\tapplicableTaxonomyNames: string[],\n\tlocale: string | undefined,\n): void {\n\tconst localeKey = locale ?? \"*\";\n\tfor (const name of applicableTaxonomyNames) {\n\t\tsetRequestCacheEntry(\n\t\t\t`terms:${collection}:${entryId}:${name}:${localeKey}`,\n\t\t\tbyTaxonomy[name] ?? [],\n\t\t);\n\t}\n\tfor (const [name, terms] of Object.entries(byTaxonomy)) {\n\t\tsetRequestCacheEntry(`terms:${collection}:${entryId}:${name}:${localeKey}`, terms);\n\t}\n\tconst allTerms = Object.values(byTaxonomy).flat();\n\tsetRequestCacheEntry(`terms:${collection}:${entryId}:*:${localeKey}`, allTerms);\n}\n\n/**\n * Prime the per-entry request cache from terms that were folded into the\n * content query (query.ts `hydrateEntryTerms` fast path), so subsequent\n * `getEntryTerms` calls in the same render hit the cache instead of issuing an\n * N+1 query. Seeds the wildcard key and one key per taxonomy present on the\n * entry — purely from the folded data, with no DB lookup.\n *\n * Unlike `getAllTermsForEntries`, this deliberately does NOT seed `[]` for\n * taxonomies that apply to the collection but have no rows on the entry: doing\n * so would require a `getTaxonomyDefs` query, adding a round trip to every fold\n * render to serve the rarer `getEntryTerms(id, absentTaxonomy)` case from cache.\n * That call simply falls through to its own cached query. Keeping the key shape\n * here (rather than in query.ts) prevents the two from drifting.\n */\nexport function primeFoldedEntryTerms(\n\tcollection: string,\n\tperEntry: Array<{ entryId: string; byTaxonomy: Record<string, TaxonomyTerm[]> }>,\n\toptions: TaxonomyQueryOptions = {},\n): void {\n\tif (perEntry.length === 0) return;\n\tconst locale = resolveLocale(options.locale);\n\tfor (const { entryId, byTaxonomy } of perEntry) {\n\t\tprimeEntryTermsCache(collection, entryId, byTaxonomy, [], locale);\n\t}\n}\n\n/**\n * Get entries by term. Both the lookup (term slug in the active locale) and\n * the content query respect the active locale.\n */\nexport async function getEntriesByTerm(\n\tcollection: string,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\toptions: TaxonomyQueryOptions = {},\n): Promise<Array<{ id: string; data: Record<string, unknown> }>> {\n\tconst { getEmDashCollection } = await import(\"../query.js\");\n\n\tconst queryOptions: Record<string, unknown> = {\n\t\twhere: { [taxonomyName]: termSlug },\n\t};\n\tif (options.locale !== undefined) queryOptions.locale = options.locale;\n\tconst { entries } = await getEmDashCollection(collection, queryOptions);\n\treturn entries;\n}\n\nfunction rowToTaxonomyDef(row: {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tlabel_singular: string | null;\n\thierarchical: number;\n\tcollections: string | null;\n\tlocale: string;\n\ttranslation_group: string | null;\n}): TaxonomyDef {\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tlabel: row.label,\n\t\tlabelSingular: row.label_singular ?? undefined,\n\t\thierarchical: row.hierarchical === 1,\n\t\tcollections: row.collections ? JSON.parse(row.collections) : [],\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n/**\n * Build tree structure from flat terms\n */\nfunction buildTree(flatTerms: TaxonomyTermRow[]): TaxonomyTerm[] {\n\t// parent_id holds the parent's translation_group, so link children by it.\n\t// Key by (locale, group): a child's parent lives in the same locale, and an\n\t// unfiltered set mixes locales whose translated siblings share a group —\n\t// keying by group alone would collide and misattach children across locales.\n\tconst byLocaleGroup = new Map<string, TaxonomyTerm>();\n\tconst nodes: TaxonomyTerm[] = [];\n\tconst roots: TaxonomyTerm[] = [];\n\n\tfor (const term of flatTerms) {\n\t\tconst node: TaxonomyTerm = {\n\t\t\tid: term.id,\n\t\t\tname: term.name,\n\t\t\tslug: term.slug,\n\t\t\tlabel: term.label,\n\t\t\tparentId: term.parent_id ?? undefined,\n\t\t\tdescription: term.data ? JSON.parse(term.data).description : undefined,\n\t\t\tchildren: [],\n\t\t\tlocale: term.locale,\n\t\t\ttranslationGroup: term.translation_group,\n\t\t};\n\t\tbyLocaleGroup.set(`${term.locale}::${term.translation_group ?? term.id}`, node);\n\t\tnodes.push(node);\n\t}\n\n\tfor (const node of nodes) {\n\t\tconst parent = node.parentId\n\t\t\t? byLocaleGroup.get(`${node.locale}::${node.parentId}`)\n\t\t\t: undefined;\n\t\tif (parent) {\n\t\t\tparent.children.push(node);\n\t\t} else {\n\t\t\troots.push(node);\n\t\t}\n\t}\n\n\treturn roots;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAS,iBACR,IACA,cACA,YACA,QACyB;AACzB,QAAO,GAAG;;;eAGI,IAAI,IAAI,MAAM,aAAa,CAAC;;yBAElB,WAAW;kFAC8C,aAAa;KAC1F,SAAS,GAAG,kBAAkB,WAAW,GAAG,GAAG;SAC3C,qBAAqB,IAAI,aAAa,IAAI,CAAC;;;;AAKpD,eAAe,UACd,IACA,cACA,aACA,QAC+B;CAC/B,MAAM,WAAW,YAAY,KAAK,eACjC,iBAAiB,IAAI,cAAc,YAAY,OAAO,CACtD;CAED,MAAM,SAAS,MAAM,GAAa;;UADpB,IAAI,KAAK,UAAU,GAAG,cAAc,CAGnC;wBACQ,QAAQ,GAAG;CAElC,MAAM,yBAAS,IAAI,KAAqB;AACxC,MAAK,MAAM,OAAO,OAAO,KAAM,QA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;AACvE,QAAO;;AAGR,SAAS,iBAAiB,KASV;AACf,QAAO;EACN,IAAI,IAAI;EACR,MAAM,IAAI;EACV,OAAO,IAAI;EACX,eAAe,IAAI,kBAAkB;EACrC,cAAc,IAAI,iBAAiB;EACnC,aAAa,IAAI,cAAc,KAAK,MAAM,IAAI,YAAY,GAAG,EAAE;EAC/D,QAAQ,IAAI;EACZ,kBAAkB,IAAI;EACtB;;;;;AAMF,SAAS,UAAU,WAA8C;CAKhE,MAAM,gCAAgB,IAAI,KAA2B;CACrD,MAAM,QAAwB,EAAE;CAChC,MAAM,QAAwB,EAAE;AAEhC,MAAK,MAAM,QAAQ,WAAW;EAC7B,MAAM,OAAqB;GAC1B,IAAI,KAAK;GACT,MAAM,KAAK;GACX,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,aAAa;GAC5B,aAAa,KAAK,OAAO,KAAK,MAAM,KAAK,KAAK,CAAC,cAAc;GAC7D,UAAU,EAAE;GACZ,QAAQ,KAAK;GACb,kBAAkB,KAAK;GACvB;AACD,gBAAc,IAAI,GAAG,KAAK,OAAO,IAAI,KAAK,qBAAqB,KAAK,MAAM,KAAK;AAC/E,QAAM,KAAK,KAAK;;AAGjB,MAAK,MAAM,QAAQ,OAAO;EACzB,MAAM,SAAS,KAAK,WACjB,cAAc,IAAI,GAAG,KAAK,OAAO,IAAI,KAAK,WAAW,GACrD;AACH,MAAI,OACH,QAAO,SAAS,KAAK,KAAK;MAE1B,OAAM,KAAK,KAAK;;AAIlB,QAAO"}
@@ -1,8 +1,8 @@
1
- import { o as __exportAll } from "./runner-BiDvq5dv.mjs";
1
+ import { c as __exportAll } from "./runner-C1T11CfC.mjs";
2
2
  import { a as resolveConfiguredLocale, r as getI18nConfig } from "./config-C3EBstHi.mjs";
3
3
  import { t as withTransaction } from "./transaction-NQj4VJ7Z.mjs";
4
- import { t as TaxonomyRepository } from "./taxonomy-CPeM8d2o.mjs";
5
- import { f as fetchVisibleTermCounts, l as invalidateTaxonomyDefsCache, u as invalidateTermCache } from "./taxonomies-B0o9ExNV.mjs";
4
+ import { t as TaxonomyRepository } from "./taxonomy-BqCZ1TdU.mjs";
5
+ import { f as fetchVisibleTermCounts, l as invalidateTaxonomyDefsCache, u as invalidateTermCache } from "./taxonomies-BlrncHi9.mjs";
6
6
  import { sql } from "kysely";
7
7
  import { ulid } from "ulidx";
8
8
 
@@ -831,4 +831,4 @@ async function handleTermDelete(db, taxonomyName, termSlug, options = {}) {
831
831
 
832
832
  //#endregion
833
833
  export { handleTaxonomyList as a, handleTermDelete as c, handleTermReorder as d, handleTermTranslations as f, handleTaxonomyGet as i, handleTermGet as l, taxonomies_exports as m, handleTaxonomyDefTranslations as n, handleTaxonomyUpdate as o, handleTermUpdate as p, handleTaxonomyDelete as r, handleTermCreate as s, handleTaxonomyCreate as t, handleTermList as u };
834
- //# sourceMappingURL=taxonomies-Dk3MAklL.mjs.map
834
+ //# sourceMappingURL=taxonomies-OHUIiIpI.mjs.map