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":"loader-DLBqRiGP.mjs","names":[],"sources":["../src/loader.ts"],"sourcesContent":["/**\n * Astro Live Collections loader for EmDash\n *\n * This loader implements the Astro LiveLoader interface to fetch content\n * at runtime from the database, enabling live editing without rebuilds.\n *\n * Architecture:\n * - Single `_emdash` Astro collection handles all content types\n * - Dialect comes from virtual module (configured in astro.config.mjs)\n * - Each content type maps to its own database table: ec_posts, ec_products, etc.\n * - `getEmDashCollection()` / `getEmDashEntry()` wrap Astro's live collection API\n */\n\nimport type { LiveLoader } from \"astro/loaders\";\nimport { Kysely, type RawBuilder, sql, type Dialect } from \"kysely\";\n\nimport { buildStatusCondition, isPostgres } from \"./database/dialect-helpers.js\";\nimport { kyselyLogOption } from \"./database/instrumentation.js\";\nimport { decodeCursor, encodeCursor } from \"./database/repositories/types.js\";\nimport { validateIdentifier } from \"./database/validate.js\";\nimport { getI18nConfig } from \"./i18n/config.js\";\nimport type { Database } from \"./index.js\";\nimport { getRequestContext } from \"./request-context.js\";\nimport { isMissingColumnError, isMissingTableError } from \"./utils/db-errors.js\";\n\nconst FIELD_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n/**\n * SEO columns folded into the single-entry query as a single JSON column\n * (`_emdash_seo` in the result set), then expanded onto the row under these\n * aliases for `extractSeo()`. Surfacing SEO as one aggregated column keeps the\n * result-set width bounded regardless of how many fields the collection has,\n * which matters for D1: a flat `LEFT JOIN _emdash_seo` adds 5 alias columns to\n * every row and pushes wide collections (common after WordPress / ACF imports)\n * past D1's per-result-set column limit, surfacing as a silent null entry.\n * One JSON column is one column, so the join stays safe at any schema width.\n *\n * The aliases mirror the strategy used by `foldedHydrationSelects` for byline\n * and taxonomy hydration: aggregate in SQL, expand in JS. SEO is 1:1 with\n * content, so the subquery uses `json_object` (not the array aggregator).\n *\n * The `_emdash_` prefix on the aliases guarantees they can never collide with\n * a content field. Field slugs must match `/^[a-z][a-z0-9_]*$/`, so a user can\n * legitimately define a `seo_title` field; surfacing the SEO column under its\n * bare name would shadow that field in the result set and drop the user's\n * value. The prefix (illegal as a leading slug char) sidesteps this entirely.\n */\nconst SEO_COLUMN_ALIASES: Record<string, string> = {\n\tseo_title: \"_emdash_seo_title\",\n\tseo_description: \"_emdash_seo_description\",\n\tseo_image: \"_emdash_seo_image\",\n\tseo_canonical: \"_emdash_seo_canonical\",\n\tseo_no_index: \"_emdash_seo_no_index\",\n};\n\n/** Aliased SEO result keys — excluded from generic field mapping. */\nconst SEO_ALIAS_COLUMNS = Object.values(SEO_COLUMN_ALIASES);\n\n/** Folded SEO JSON column name in the result set (expanded onto aliases in JS). */\nconst SEO_FOLDED_COLUMN = \"_emdash_seo\";\n\n/**\n * System columns excluded from entry.data\n * Note: slug is intentionally NOT excluded - it's useful as data.slug in templates\n */\nconst SYSTEM_COLUMNS = new Set([\n\t\"id\",\n\t// \"slug\" - kept in data for template access\n\t\"status\",\n\t\"author_id\",\n\t\"primary_byline_id\",\n\t\"created_at\",\n\t\"updated_at\",\n\t\"published_at\",\n\t\"scheduled_at\",\n\t\"deleted_at\",\n\t\"version\",\n\t\"live_revision_id\",\n\t\"draft_revision_id\",\n\t\"locale\",\n\t\"translation_group\",\n\t// Aliased SEO columns expanded from the folded _emdash_seo JSON column on\n\t// the single-entry path. Surfaced as a nested data.seo object (see\n\t// extractSeo), never as flat fields. The aliases are _emdash_-prefixed so\n\t// they can't shadow a user field named e.g. `seo_title`.\n\t...SEO_ALIAS_COLUMNS,\n\t// Folded hydration JSON columns (see foldedHydrationSelects and\n\t// foldedSeoSelect) — surfaced via the FOLDED_* markers or expanded onto\n\t// SEO_ALIAS_COLUMNS, never as flat fields.\n\t\"_emdash_terms\",\n\t\"_emdash_bylines\",\n\t\"_emdash_bylines_exist\",\n\tSEO_FOLDED_COLUMN,\n]);\n\n/** Markers for byline/taxonomy hydration folded into the content query. */\nexport const FOLDED_TERMS = Symbol.for(\"emdash:foldedTerms\");\nexport const FOLDED_BYLINES = Symbol.for(\"emdash:foldedBylines\");\n/**\n * Marker for whether `_emdash_bylines` has any rows at all (`false` = table\n * empty). Lets byline hydration trust an empty fold instead of re-checking\n * via the byline query path on sites that never use bylines.\n */\nexport const FOLDED_BYLINES_EXIST = Symbol.for(\"emdash:foldedBylinesExist\");\n\n/**\n * Correlated JSON-array subqueries that fold taxonomy-term and byline hydration\n * into the content query, removing the two separate hydration round trips per\n * fetch. `outer` is the content table's alias/name; each subquery correlates on\n * `<outer>.id`, so the base query stays one row per entry (no join fan-out, no\n * duplicated content payload). Order is NOT applied in the aggregate (it differs\n * across dialects) — the consumer sorts terms by label and credits by sortOrder.\n *\n * Dialect-specific aggregation: SQLite `json_group_array`/`json_object` returns\n * a JSON *string*; Postgres `json_agg`/`json_build_object` (coalesced to `[]`)\n * returns parsed JSON. {@link stashFolded} handles both.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any Kysely instance\nfunction foldedHydrationSelects(db: Kysely<any>, type: string, outer: string) {\n\tconst o = sql.ref(outer);\n\tconst pg = isPostgres(db);\n\tconst obj = (pairs: string) =>\n\t\tpg ? sql.raw(`json_build_object(${pairs})`) : sql.raw(`json_object(${pairs})`);\n\tconst agg = (inner: RawBuilder<unknown>) =>\n\t\tpg ? sql`coalesce(json_agg(${inner}), '[]'::json)` : sql`json_group_array(${inner})`;\n\n\t// Pin the byline join order on SQLite (#1722). Taxonomy hydration uses\n\t// LEFT JOINs below, whose order is already fixed by SQL semantics. SQLite\n\t// honours `CROSS JOIN` ordering, forcing the byline subquery to drive from\n\t// its pivot by content reference and probe by translation_group. Postgres\n\t// keeps statistics and rejects `CROSS JOIN … ON`, so it stays a plain JOIN.\n\tconst foldJoin = pg ? sql`JOIN` : sql`CROSS JOIN`;\n\n\tconst termObj = obj(\n\t\t\"'id', coalesce(exact_term.id, default_term.id), 'name', coalesce(exact_term.name, default_term.name), 'slug', coalesce(exact_term.slug, default_term.slug), 'label', coalesce(exact_term.label, default_term.label), 'parent_id', coalesce(exact_term.parent_id, default_term.parent_id), 'locale', coalesce(exact_term.locale, default_term.locale), 'translation_group', coalesce(exact_term.translation_group, default_term.translation_group)\",\n\t);\n\tconst defaultLocale = getI18nConfig()?.defaultLocale ?? \"en\";\n\tconst selectedTermId = sql`coalesce(exact_term.id, default_term.id)`;\n\tconst termAgg = pg\n\t\t? sql`coalesce(json_agg(${termObj}) FILTER (WHERE ${selectedTermId} IS NOT NULL), '[]'::json)`\n\t\t: sql`json_group_array(${termObj}) FILTER (WHERE ${selectedTermId} IS NOT NULL)`;\n\tconst terms = sql`(SELECT ${termAgg} FROM ${sql.ref(\"content_taxonomies\")} AS ct LEFT JOIN ${sql.ref(\"taxonomies\")} AS exact_term ON exact_term.translation_group = ct.taxonomy_id AND exact_term.locale = ${o}.locale LEFT JOIN ${sql.ref(\"taxonomies\")} AS default_term ON default_term.translation_group = ct.taxonomy_id AND default_term.locale = ${defaultLocale} WHERE ct.collection = ${type} AND ct.entry_id = ${o}.translation_group) AS ${sql.ref(\"_emdash_terms\")}`;\n\n\tconst bylineInner = obj(\n\t\t\"'id', b.id, 'slug', b.slug, 'displayName', b.display_name, 'bio', b.bio, 'avatarMediaId', b.avatar_media_id, 'avatarStorageKey', m.storage_key, 'avatarAlt', m.alt, 'avatarBlurhash', m.blurhash, 'avatarDominantColor', m.dominant_color, 'websiteUrl', b.website_url, 'userId', b.user_id, 'isGuest', b.is_guest, 'createdAt', b.created_at, 'updatedAt', b.updated_at, 'locale', b.locale, 'translationGroup', b.translation_group\",\n\t);\n\tconst creditObj = pg\n\t\t? sql.raw(\n\t\t\t\t\"json_build_object('roleLabel', cb.role_label, 'sortOrder', cb.sort_order, 'byline', \",\n\t\t\t)\n\t\t: sql.raw(\"json_object('roleLabel', cb.role_label, 'sortOrder', cb.sort_order, 'byline', \");\n\tconst credit = sql`${creditObj}${bylineInner})`;\n\tconst bylines = sql`(SELECT ${agg(credit)} FROM ${sql.ref(\"_emdash_content_bylines\")} AS cb ${foldJoin} ${sql.ref(\"_emdash_bylines\")} AS b ON b.translation_group = cb.byline_id LEFT JOIN ${sql.ref(\"media\")} AS m ON m.id = b.avatar_media_id WHERE cb.collection_slug = ${type} AND cb.content_id = ${o}.id AND b.locale = ${o}.locale) AS ${sql.ref(\"_emdash_bylines\")}`;\n\t// Uncorrelated existence probe (evaluated once per statement, not per row):\n\t// 1 when `_emdash_bylines` has any row, NULL when empty. An empty table\n\t// means an empty fold is authoritative — no credit in any locale, no\n\t// author-fallback byline — so hydration can skip the byline query path.\n\tconst bylinesExist = sql`(SELECT 1 FROM ${sql.ref(\"_emdash_bylines\")} LIMIT 1) AS ${sql.ref(\"_emdash_bylines_exist\")}`;\n\treturn { terms, bylines, bylinesExist };\n}\n\n/**\n * Correlated JSON-object subquery that folds per-entry SEO into the content\n * query without widening the result set: 1 row of `_emdash_seo` becomes 1 JSON\n * column rather than 5 flat columns. The JSON column is expanded onto the row\n * via {@link expandFoldedSeo} after the query runs, preserving the alias keys\n * that {@link extractSeo} reads. Missing SEO row (no entry in `_emdash_seo`)\n * yields NULL, which {@link expandFoldedSeo} treats as \"no SEO\" - identical to\n * the prior LEFT JOIN miss behavior.\n *\n * Dialect-specific aggregation mirrors {@link foldedHydrationSelects}: SQLite\n * `json_object` returns a JSON *string*, Postgres `json_build_object` returns\n * parsed JSON; both branches are handled in expansion.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any Kysely instance\nfunction foldedSeoSelect(db: Kysely<any>, type: string, outer: string) {\n\tconst o = sql.ref(outer);\n\tconst pg = isPostgres(db);\n\t// Use raw column names (not aliases) as JSON keys: the JSON is expanded back\n\t// onto SEO_COLUMN_ALIASES in JS, and keeping the keys matched to the\n\t// underlying columns makes the SQL readable and the expansion 1-to-1.\n\tconst pairs =\n\t\t\"'seo_title', s.seo_title, 'seo_description', s.seo_description, 'seo_image', s.seo_image, 'seo_canonical', s.seo_canonical, 'seo_no_index', s.seo_no_index\";\n\tconst obj = pg ? sql.raw(`json_build_object(${pairs})`) : sql.raw(`json_object(${pairs})`);\n\treturn sql`(SELECT ${obj} FROM ${sql.ref(\"_emdash_seo\")} AS s WHERE s.collection = ${type} AND s.content_id = ${o}.id LIMIT 1) AS ${sql.ref(SEO_FOLDED_COLUMN)}`;\n}\n\n/**\n * Expand the folded `_emdash_seo` JSON column onto the row using SEO_COLUMN_ALIASES,\n * so {@link extractSeo} reads it transparently. SQLite returns a JSON string\n * (parse it); Postgres returns already-parsed JSON. Missing/malformed/null is\n * a no-op: {@link extractSeo} returns null when the aliases are absent.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction expandFoldedSeo(row: Record<string, unknown>): void {\n\tconst raw = row[SEO_FOLDED_COLUMN];\n\tdelete row[SEO_FOLDED_COLUMN];\n\tlet parsed: Record<string, unknown> | null = null;\n\tif (typeof raw === \"string\") {\n\t\ttry {\n\t\t\tconst candidate: unknown = JSON.parse(raw);\n\t\t\tif (isPlainObject(candidate)) parsed = candidate;\n\t\t} catch {\n\t\t\treturn; // malformed JSON: leave the row without SEO aliases (extractSeo returns null)\n\t\t}\n\t} else if (isPlainObject(raw)) {\n\t\tparsed = raw;\n\t}\n\tif (!parsed) return;\n\tfor (const [col, alias] of Object.entries(SEO_COLUMN_ALIASES)) {\n\t\trow[alias] = parsed[col] ?? null;\n\t}\n}\n\nexport function creditsFromFoldedBylines(folded: unknown[]) {\n\treturn folded\n\t\t.map((raw) => {\n\t\t\tconst credit = isPlainObject(raw) ? raw : {};\n\t\t\tconst byline = isPlainObject(credit.byline) ? credit.byline : {};\n\t\t\treturn {\n\t\t\t\troleLabel: typeof credit.roleLabel === \"string\" ? credit.roleLabel : null,\n\t\t\t\tsortOrder: Number(credit.sortOrder ?? 0),\n\t\t\t\tsource: \"explicit\" as const,\n\t\t\t\tbyline: {\n\t\t\t\t\t...byline,\n\t\t\t\t\tisGuest: Boolean(byline.isGuest),\n\t\t\t\t\t// Folded rows omit custom-field values.\n\t\t\t\t\tcustomFields: {},\n\t\t\t\t},\n\t\t\t};\n\t\t})\n\t\t.toSorted((a, b) => a.sortOrder - b.sortOrder);\n}\n\n/**\n * Stash folded hydration JSON (non-enumerable) for the query.ts fast paths.\n * SQLite returns a JSON string (parse it); Postgres returns already-parsed JSON.\n */\nfunction stashFolded(data: Record<string, unknown>, row: Record<string, unknown>): void {\n\tfor (const [col, sym] of [\n\t\t[\"_emdash_terms\", FOLDED_TERMS],\n\t\t[\"_emdash_bylines\", FOLDED_BYLINES],\n\t] as const) {\n\t\tconst raw = row[col];\n\t\tlet value: unknown;\n\t\tif (typeof raw === \"string\") {\n\t\t\ttry {\n\t\t\t\tvalue = JSON.parse(raw);\n\t\t\t} catch {\n\t\t\t\tcontinue; // malformed: fall back to the query path\n\t\t\t}\n\t\t} else if (Array.isArray(raw)) {\n\t\t\tvalue = raw; // Postgres json/jsonb already parsed by the driver\n\t\t} else {\n\t\t\tcontinue;\n\t\t}\n\t\tObject.defineProperty(data, sym, { value, enumerable: false, configurable: true });\n\t}\n\t// Existence probe: 1 = table has rows, NULL = empty (both dialects). A row\n\t// without the column (e.g. a cached snapshot) leaves the marker unset,\n\t// which hydration treats as \"unknown\" and falls back conservatively.\n\tif (\"_emdash_bylines_exist\" in row) {\n\t\tObject.defineProperty(data, FOLDED_BYLINES_EXIST, {\n\t\t\tvalue: row[\"_emdash_bylines_exist\"] != null,\n\t\t\tenumerable: false,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\n\tconst foldedBylines = Reflect.get(data, FOLDED_BYLINES);\n\tif (!Array.isArray(foldedBylines)) return;\n\tconst credits = creditsFromFoldedBylines(foldedBylines);\n\tdata.bylines = credits;\n\tdata.byline = credits[0]?.byline ?? null;\n}\n\n/** Resolved SEO shape attached to `entry.data.seo`. Mirrors `ContentSeo`. */\ninterface EntrySeo {\n\ttitle: string | null;\n\tdescription: string | null;\n\timage: string | null;\n\tcanonical: string | null;\n\tnoIndex: boolean;\n}\n\n/**\n * Build a `data.seo` object from the joined `_emdash_seo` columns on a row.\n *\n * Returns `null` when no SEO row exists (LEFT JOIN miss → `seo_no_index` is\n * NULL, since the column is `NOT NULL DEFAULT 0` whenever a row is present).\n * Returning null keeps the `seo` key off entries that have none, so\n * `getSeoMeta()` falls back to its defaults exactly as before.\n */\nfunction extractSeo(row: Record<string, unknown>): EntrySeo | null {\n\tconst noIndex = row[SEO_COLUMN_ALIASES.seo_no_index];\n\tif (noIndex === null || noIndex === undefined) return null;\n\tconst title = row[SEO_COLUMN_ALIASES.seo_title];\n\tconst description = row[SEO_COLUMN_ALIASES.seo_description];\n\tconst image = row[SEO_COLUMN_ALIASES.seo_image];\n\tconst canonical = row[SEO_COLUMN_ALIASES.seo_canonical];\n\treturn {\n\t\ttitle: typeof title === \"string\" ? title : null,\n\t\tdescription: typeof description === \"string\" ? description : null,\n\t\timage: typeof image === \"string\" ? image : null,\n\t\tcanonical: typeof canonical === \"string\" ? canonical : null,\n\t\tnoIndex: noIndex === 1,\n\t};\n}\n\n/**\n * Get the table name for a collection type\n */\nfunction getTableName(type: string): string {\n\tvalidateIdentifier(type, \"collection type\");\n\treturn `ec_${type}`;\n}\n\n/**\n * Cache for taxonomy names by collection (only used for the primary database).\n * Stored on globalThis so Vite SSR chunk duplication cannot create independent\n * caches. Skipped when a per-request DB override is active (e.g. preview mode)\n * because the override DB may have different taxonomies.\n */\ninterface TaxonomyNamesHolder {\n\tcache: Map<string, Set<string>> | null;\n}\n\nconst TAXONOMY_NAMES_CACHE_KEY = Symbol.for(\"emdash:taxonomy-names\");\nconst taxonomyNamesStore = globalThis as Record<symbol, unknown>;\nconst taxonomyNamesHolder: TaxonomyNamesHolder =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see taxonomies/index.ts)\n\t(taxonomyNamesStore[TAXONOMY_NAMES_CACHE_KEY] as TaxonomyNamesHolder | undefined) ??\n\t(() => {\n\t\tconst holder: TaxonomyNamesHolder = { cache: null };\n\t\ttaxonomyNamesStore[TAXONOMY_NAMES_CACHE_KEY] = holder;\n\t\treturn holder;\n\t})();\n\nfunction setTaxonomyNamesCache(cache: Map<string, Set<string>> | null): void {\n\ttaxonomyNamesHolder.cache = cache;\n}\n\n/**\n * Get taxonomy names attached to a collection (cached for the primary DB,\n * bypassed only when the per-request DB is an isolated instance — playground /\n * DO preview). Plain D1 Sessions routing shares schema with the singleton, so\n * the isolate-wide cache stays valid.\n */\nasync function getTaxonomyNames(db: Kysely<Database>, collection: string): Promise<Set<string>> {\n\tconst hasIsolatedDb = getRequestContext()?.dbIsIsolated === true;\n\n\tif (!hasIsolatedDb && taxonomyNamesHolder.cache) {\n\t\treturn taxonomyNamesHolder.cache.get(collection) ?? new Set();\n\t}\n\n\ttry {\n\t\tconst defs = await db\n\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t.select([\"name\", \"collections\"])\n\t\t\t.execute();\n\t\tconst namesByCollection = new Map<string, Set<string>>();\n\t\tfor (const def of defs) {\n\t\t\tlet collections: unknown;\n\t\t\ttry {\n\t\t\t\tcollections = JSON.parse(def.collections ?? \"[]\");\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!Array.isArray(collections)) continue;\n\t\t\tfor (const attachedCollection of collections) {\n\t\t\t\tif (typeof attachedCollection !== \"string\") continue;\n\t\t\t\tconst names = namesByCollection.get(attachedCollection) ?? new Set<string>();\n\t\t\t\tnames.add(def.name);\n\t\t\t\tnamesByCollection.set(attachedCollection, names);\n\t\t\t}\n\t\t}\n\t\tif (!hasIsolatedDb) {\n\t\t\tsetTaxonomyNamesCache(namesByCollection);\n\t\t}\n\t\treturn namesByCollection.get(collection) ?? new Set();\n\t} catch (error) {\n\t\tif (!isMissingTableError(error) && !isMissingColumnError(error)) throw error;\n\n\t\tconst empty = new Set<string>();\n\t\tif (!hasIsolatedDb) {\n\t\t\tsetTaxonomyNamesCache(new Map());\n\t\t}\n\t\treturn empty;\n\t}\n}\n\n/**\n * Reset the isolate-wide taxonomy-names cache.\n *\n * Called from `invalidateTaxonomyDefsCache()` so that creating or seeding a\n * taxonomy definition is reflected within the current isolate instead of\n * waiting for the isolate to recycle. Keeps this cache consistent with the\n * isolate-wide taxonomy-defs cache in `taxonomies/index.ts`.\n */\nexport function resetTaxonomyNamesCache(): void {\n\tsetTaxonomyNamesCache(null);\n}\n\n/**\n * System columns to include in data (mapped to camelCase where needed)\n */\nconst INCLUDE_IN_DATA: Record<string, string> = {\n\tid: \"id\",\n\tstatus: \"status\",\n\tauthor_id: \"authorId\",\n\tprimary_byline_id: \"primaryBylineId\",\n\tcreated_at: \"createdAt\",\n\tupdated_at: \"updatedAt\",\n\tpublished_at: \"publishedAt\",\n\tscheduled_at: \"scheduledAt\",\n\tdraft_revision_id: \"draftRevisionId\",\n\tlive_revision_id: \"liveRevisionId\",\n\tlocale: \"locale\",\n\ttranslation_group: \"translationGroup\",\n};\n\n/** System date columns that should be converted to Date objects */\nconst DATE_COLUMNS = new Set([\"created_at\", \"updated_at\", \"published_at\", \"scheduled_at\"]);\n\n/**\n * Hidden, symbol-keyed property on each mapped data record carrying the raw\n * DB string for every date column. Lets cursor encoders downstream reproduce\n * the loader's exact `nextCursor` format without round-tripping through\n * `new Date()`, which loses precision for stored values that aren't already\n * ISO-with-milliseconds (e.g. `2026-01-01T00:00:00Z` becomes\n * `2026-01-01T00:00:00.000Z`).\n */\nexport const CURSOR_RAW_VALUES: unique symbol = Symbol(\"emdash:cursorRawValues\");\n\nconst LOCAL_MEDIA_FILE_PREFIX = \"/_emdash/api/media/file/\";\nconst URL_SCHEME_PATTERN = /^[a-zA-Z][a-zA-Z\\d+\\-.]*:/;\n\n/** Safely extract a string value from a record, returning fallback if not a string */\nfunction rowStr(row: Record<string, unknown>, key: string, fallback = \"\"): string {\n\tconst val = row[key];\n\treturn typeof val === \"string\" ? val : fallback;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isBareMediaKey(src: string): boolean {\n\treturn !src.startsWith(\"/\") && !URL_SCHEME_PATTERN.test(src);\n}\n\nfunction normalizeLocalMediaValue(value: unknown): unknown {\n\tif (Array.isArray(value)) {\n\t\treturn value.map(normalizeLocalMediaValue);\n\t}\n\n\tif (!isRecord(value)) {\n\t\treturn value;\n\t}\n\n\tconst normalized: Record<string, unknown> = {};\n\tfor (const [key, child] of Object.entries(value)) {\n\t\tnormalized[key] = normalizeLocalMediaValue(child);\n\t}\n\n\tif (\n\t\tnormalized.provider === \"local\" &&\n\t\ttypeof normalized.src === \"string\" &&\n\t\tnormalized.src.length > 0\n\t) {\n\t\tconst src = normalized.src;\n\t\tif (src.startsWith(LOCAL_MEDIA_FILE_PREFIX)) {\n\t\t\tconst id = src.slice(LOCAL_MEDIA_FILE_PREFIX.length);\n\t\t\tif (!normalized.id && id) {\n\t\t\t\tnormalized.id = id;\n\t\t\t}\n\t\t} else if (isBareMediaKey(src)) {\n\t\t\tif (!normalized.id) {\n\t\t\t\tnormalized.id = src;\n\t\t\t}\n\t\t\tnormalized.src = `${LOCAL_MEDIA_FILE_PREFIX}${src}`;\n\t\t}\n\t}\n\n\treturn normalized;\n}\n\n/**\n * Map a database row to entry data\n * Extracts content fields (non-system columns) and parses JSON where needed.\n * System columns needed for templates (id, status, dates) are included with camelCase names.\n */\nfunction mapRowToData(row: Record<string, unknown>): Record<string, unknown> {\n\tconst data: Record<string, unknown> = {};\n\tconst rawDateValues: Record<string, string> = {};\n\n\tfor (const [key, value] of Object.entries(row)) {\n\t\t// Include certain system columns (mapped to camelCase where needed)\n\t\tif (key in INCLUDE_IN_DATA) {\n\t\t\t// Convert date columns from ISO strings to Date objects\n\t\t\tif (DATE_COLUMNS.has(key)) {\n\t\t\t\tif (typeof value === \"string\") {\n\t\t\t\t\trawDateValues[key] = value;\n\t\t\t\t\tdata[INCLUDE_IN_DATA[key]] = new Date(value);\n\t\t\t\t} else {\n\t\t\t\t\tdata[INCLUDE_IN_DATA[key]] = null;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdata[INCLUDE_IN_DATA[key]] = value;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (SYSTEM_COLUMNS.has(key)) continue;\n\n\t\t// Try to parse JSON strings (for portableText, json fields, etc.)\n\t\tif (typeof value === \"string\") {\n\t\t\ttry {\n\t\t\t\t// Only parse if it looks like JSON (starts with { or [)\n\t\t\t\tif (value.startsWith(\"{\") || value.startsWith(\"[\")) {\n\t\t\t\t\tdata[key] = normalizeLocalMediaValue(JSON.parse(value));\n\t\t\t\t} else {\n\t\t\t\t\tdata[key] = value;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tdata[key] = value;\n\t\t\t}\n\t\t} else {\n\t\t\tdata[key] = value;\n\t\t}\n\t}\n\n\tObject.defineProperty(data, CURSOR_RAW_VALUES, {\n\t\tvalue: rawDateValues,\n\t\tenumerable: false,\n\t\tconfigurable: false,\n\t\twritable: false,\n\t});\n\n\treturn data;\n}\n\n/**\n * Map revision data (already-parsed JSON object) to entry data.\n * Strips _-prefixed metadata keys (e.g. _slug) used internally by revisions.\n */\nfunction mapRevisionData(data: Record<string, unknown>): Record<string, unknown> {\n\tconst result: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(data)) {\n\t\tif (key.startsWith(\"_\")) continue; // revision metadata\n\t\tresult[key] = normalizeLocalMediaValue(value);\n\t}\n\treturn result;\n}\n\n// Virtual module imports are lazy-loaded to avoid errors when importing\n// emdash outside of Astro/Vite context (e.g., in astro.config.mjs)\nlet virtualConfig:\n\t| {\n\t\t\tdatabase?: { config: unknown };\n\t\t\ti18n?: { defaultLocale: string; locales: string[]; prefixDefaultLocale?: boolean } | null;\n\t }\n\t| undefined;\nlet virtualCreateDialect: ((config: unknown) => Dialect) | undefined;\n\nasync function loadVirtualModules() {\n\tif (virtualConfig === undefined) {\n\t\t// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n\t\t// @ts-ignore - virtual module\n\t\tconst configModule = await import(\"virtual:emdash/config\");\n\t\tvirtualConfig = configModule.default;\n\t}\n\tif (virtualCreateDialect === undefined) {\n\t\t// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n\t\t// @ts-ignore - virtual module\n\t\tconst dialectModule = await import(\"virtual:emdash/dialect\");\n\t\tvirtualCreateDialect = dialectModule.createDialect;\n\t\t// dialectType is no longer needed here — dialect detection is\n\t\t// done via the db adapter instance in dialect-helpers.ts\n\t}\n}\n\n/**\n * Entry data type - generic object\n */\nexport type EntryData = Record<string, unknown>;\n\n/**\n * Sort direction\n */\nexport type SortDirection = \"asc\" | \"desc\";\n\n/**\n * Order by specification - field name to direction\n * @example { created_at: \"desc\" } - Sort by created_at descending\n * @example { title: \"asc\" } - Sort by title ascending\n */\nexport type OrderBySpec = Record<string, SortDirection>;\n\n/**\n * Resolved primary sort field and direction (used for cursor pagination).\n */\ninterface PrimarySort {\n\tfield: string;\n\tdirection: SortDirection;\n}\n\n/**\n * Get the primary sort field from an orderBy spec (first valid field, or default).\n */\nfunction getPrimarySort(orderBy: OrderBySpec | undefined, tablePrefix?: string): PrimarySort {\n\tif (orderBy) {\n\t\tfor (const [field, direction] of Object.entries(orderBy)) {\n\t\t\tif (FIELD_NAME_PATTERN.test(field)) {\n\t\t\t\tconst fullField = tablePrefix ? `${tablePrefix}.${field}` : field;\n\t\t\t\treturn { field: fullField, direction };\n\t\t\t}\n\t\t}\n\t}\n\tconst defaultField = tablePrefix ? `${tablePrefix}.created_at` : \"created_at\";\n\treturn { field: defaultField, direction: \"desc\" };\n}\n\n/**\n * Build ORDER BY clause from orderBy spec\n * Validates field names to prevent SQL injection (alphanumeric + underscore only)\n * Supports multiple sort fields in object key order\n */\nfunction buildOrderByClause(\n\torderBy: OrderBySpec | undefined,\n\ttablePrefix?: string,\n): ReturnType<typeof sql> {\n\t// Default to created_at DESC\n\tif (!orderBy || Object.keys(orderBy).length === 0) {\n\t\tconst field = tablePrefix ? `${tablePrefix}.created_at` : \"created_at\";\n\t\treturn sql`ORDER BY ${sql.ref(field)} DESC, ${sql.ref(tablePrefix ? `${tablePrefix}.id` : \"id\")} DESC`;\n\t}\n\n\tconst sortParts: ReturnType<typeof sql>[] = [];\n\n\tfor (const [field, direction] of Object.entries(orderBy)) {\n\t\t// Validate field name (alphanumeric + underscore only)\n\t\tif (!FIELD_NAME_PATTERN.test(field)) {\n\t\t\tcontinue; // Skip invalid field names\n\t\t}\n\n\t\tconst fullField = tablePrefix ? `${tablePrefix}.${field}` : field;\n\t\tconst dir = direction === \"asc\" ? sql`ASC` : sql`DESC`;\n\t\tsortParts.push(sql`${sql.ref(fullField)} ${dir}`);\n\t}\n\n\t// If no valid sort fields, fall back to default\n\tif (sortParts.length === 0) {\n\t\tconst defaultField = tablePrefix ? `${tablePrefix}.created_at` : \"created_at\";\n\t\treturn sql`ORDER BY ${sql.ref(defaultField)} DESC, ${sql.ref(tablePrefix ? `${tablePrefix}.id` : \"id\")} DESC`;\n\t}\n\n\t// Add id as tiebreaker to ensure stable cursor ordering\n\tconst primary = getPrimarySort(orderBy, tablePrefix);\n\tconst idField = tablePrefix ? `${tablePrefix}.id` : \"id\";\n\tconst idDir = primary.direction === \"asc\" ? sql`ASC` : sql`DESC`;\n\tsortParts.push(sql`${sql.ref(idField)} ${idDir}`);\n\n\treturn sql`ORDER BY ${sql.join(sortParts, sql`, `)}`;\n}\n\n/**\n * Build a cursor WHERE condition for keyset pagination.\n * Uses the primary sort field + id as tiebreaker for stable ordering.\n *\n * Throws `InvalidCursorError` if the cursor is malformed; callers should\n * let this propagate so users see a real error rather than silently\n * falling back to the first page.\n */\nfunction buildCursorCondition(\n\tcursor: string,\n\torderBy: OrderBySpec | undefined,\n\ttablePrefix?: string,\n): ReturnType<typeof sql> {\n\tconst { orderValue, id: cursorId } = decodeCursor(cursor);\n\tconst primary = getPrimarySort(orderBy, tablePrefix);\n\tconst idField = tablePrefix ? `${tablePrefix}.id` : \"id\";\n\n\tif (primary.direction === \"desc\") {\n\t\treturn sql`(${sql.ref(primary.field)} < ${orderValue} OR (${sql.ref(primary.field)} = ${orderValue} AND ${sql.ref(idField)} < ${cursorId}))`;\n\t}\n\treturn sql`(${sql.ref(primary.field)} > ${orderValue} OR (${sql.ref(primary.field)} = ${orderValue} AND ${sql.ref(idField)} > ${cursorId}))`;\n}\n\n/** Type guard: is the where value a range object (not a string or array)? */\nfunction isWhereRange(value: WhereValue): value is WhereRange {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Build AND conditions for non-taxonomy field filters.\n * Returns an array of sql fragments; empty if no field filters apply.\n * Field names are validated against FIELD_NAME_PATTERN to prevent injection.\n */\nfunction buildFieldConditions(\n\tfields: Record<string, WhereValue>,\n\ttablePrefix?: string,\n): ReturnType<typeof sql>[] {\n\tconst conditions: ReturnType<typeof sql>[] = [];\n\n\tfor (const [key, value] of Object.entries(fields)) {\n\t\tif (!FIELD_NAME_PATTERN.test(key)) {\n\t\t\tconsole.warn(`[emdash] where filter: invalid field name \"${key}\" ignored`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (value == null) continue;\n\t\tconst ref = tablePrefix ? sql.ref(`${tablePrefix}.${key}`) : sql.ref(key);\n\n\t\tif (isWhereRange(value)) {\n\t\t\tif (value.gt !== undefined) conditions.push(sql`${ref} > ${value.gt}`);\n\t\t\tif (value.gte !== undefined) conditions.push(sql`${ref} >= ${value.gte}`);\n\t\t\tif (value.lt !== undefined) conditions.push(sql`${ref} < ${value.lt}`);\n\t\t\tif (value.lte !== undefined) conditions.push(sql`${ref} <= ${value.lte}`);\n\t\t} else if (Array.isArray(value)) {\n\t\t\tif (value.length > 0) {\n\t\t\t\tconditions.push(sql`${ref} IN (${sql.join(value.map((v) => sql`${v}`))})`);\n\t\t\t}\n\t\t} else {\n\t\t\tconditions.push(sql`${ref} = ${value}`);\n\t\t}\n\t}\n\n\treturn conditions;\n}\n\n/**\n * Resolve a taxonomy filter (`name` + one or more `slug`s, optionally scoped to\n * `locale`) to the set of `translation_group`s the pivot stores in\n * `content_taxonomies.taxonomy_id`. Exact terms only — no subtree expansion.\n *\n * Mirrors the meaning of the old EXISTS join (`t.name = ? AND t.slug IN (?)\n * [AND t.locale = ?]`): a pivot row matches when its group has a term with that\n * name/slug in the active locale. Resolving to explicit values (rather than an\n * `IN (subquery)`) keeps the single-term case a plain equality on the pivot\n * index, which is what gives the clean early-`LIMIT` seek.\n */\nasync function resolveTermGroups(\n\tdb: Kysely<Database>,\n\tname: string,\n\tslugs: string[],\n\tlocale: string | undefined,\n): Promise<string[]> {\n\tlet query = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.select(\"translation_group\")\n\t\t.distinct()\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"slug\", \"in\", slugs);\n\tif (locale) query = query.where(\"locale\", \"=\", locale);\n\tconst rows = await query.execute();\n\tconst groups = new Set<string>();\n\tfor (const row of rows) {\n\t\tif (row.translation_group) groups.add(row.translation_group);\n\t}\n\treturn [...groups];\n}\n\n/** Equality (single) or `IN` (multiple) condition on a pivot group column. */\nfunction pivotGroupCondition(ref: string, groups: string[]): ReturnType<typeof sql> {\n\tif (groups.length === 1) return sql`${sql.ref(ref)} = ${groups[0]}`;\n\treturn sql`${sql.ref(ref)} IN (${sql.join(groups.map((g) => sql`${g}`))})`;\n}\n\n/** LIMIT/OFFSET fragment matching the loader's single-table variant. */\nfunction buildPivotLimitOffset(\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any Kysely instance\n\tdb: Kysely<any>,\n\tfetchLimit: number | undefined,\n\toffset: number | undefined,\n): ReturnType<typeof sql> {\n\tif (fetchLimit != null && offset != null) return sql`LIMIT ${fetchLimit} OFFSET ${offset}`;\n\tif (fetchLimit != null) return sql`LIMIT ${fetchLimit}`;\n\tif (offset != null) {\n\t\treturn isPostgres(db) ? sql`OFFSET ${offset}` : sql`LIMIT -1 OFFSET ${offset}`;\n\t}\n\treturn sql``;\n}\n\n/**\n * Options for {@link buildTaxonomyPivotQuery}.\n *\n * Parameterized on the `deletedIsNull` predicate and `status` condition so the\n * same builder serves the public live path (`deleted_at IS NULL` + published)\n * and, without any schema change, an admin trash (`deleted_at IS NOT\n * NULL`) or all-statuses shape. Admin wiring is out of scope today; the\n * parameters exist so `ContentRepository` can adopt this if it gains taxonomy\n * filtering.\n */\nexport interface TaxonomyPivotQueryOptions {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any Kysely instance\n\tdb: Kysely<any>;\n\t/** Collection slug (pivot `collection` value). */\n\tcollection: string;\n\t/** Content table name (`ec_<collection>`). */\n\ttableName: string;\n\t/**\n\t * Resolved translation_group sets, one per taxonomy filter. The first drives\n\t * the pivot seek; each additional set becomes a residual `EXISTS` (AND across\n\t * taxonomies). Multiple groups within a set are OR'd (dedup via GROUP BY).\n\t */\n\tgroupSets: string[][];\n\torderBy: OrderBySpec | undefined;\n\tcursor: string | undefined;\n\tlocale: string | undefined;\n\t/**\n\t * Status shape. A concrete value (`published`/`draft`/…) applies the same\n\t * condition `buildStatusCondition` produces (public: published only).\n\t * `undefined` drops the status filter entirely — the admin all-statuses shape.\n\t */\n\tstatus: string | undefined;\n\t/** `true` → `deleted_at IS NULL` (live); `false` → `IS NOT NULL` (trash). */\n\tdeletedIsNull: boolean;\n\t/** Byline translation_groups for an AND'd byline filter, or `null`. */\n\tbylineGroups: string[] | null;\n\tfetchLimit: number | undefined;\n\toffset: number | undefined;\n}\n\n/**\n * Build the pivot-driven taxonomy listing query (#1834).\n *\n * Drives from the term pivot and joins content translations through their\n * shared translation_group. Content columns remain authoritative for locale,\n * visibility, sorting, and cursor predicates.\n *\n * Two shapes:\n * - **Indexed sort** (`published_at`/`created_at`, single sort field): the\n * `LIMIT` lives in `picked`.\n * - **Temp-sort** (`updated_at` or any other field, or multi-field sort): no\n * pivot sort index applies, so `picked` collects the tagged candidate set and\n * the outer query sorts the joined rows. Bounded to tagged rows — no\n * `ec_*` full scan — but no early-`LIMIT`.\n */\nexport function buildTaxonomyPivotQuery(\n\topts: TaxonomyPivotQueryOptions,\n): ReturnType<typeof sql<Record<string, unknown>>> {\n\tconst {\n\t\tdb,\n\t\tcollection,\n\t\ttableName,\n\t\tgroupSets,\n\t\torderBy,\n\t\tcursor,\n\t\tlocale,\n\t\tstatus,\n\t\tdeletedIsNull,\n\t\tbylineGroups,\n\t\tfetchLimit,\n\t\toffset,\n\t} = opts;\n\n\tconst primary = getPrimarySort(orderBy);\n\tconst validSortKeys = orderBy\n\t\t? Object.keys(orderBy).filter((k) => FIELD_NAME_PATTERN.test(k))\n\t\t: [];\n\tconst singleSort = validSortKeys.length <= 1;\n\tconst isIndexedSort =\n\t\tsingleSort && (primary.field === \"published_at\" || primary.field === \"created_at\");\n\tconst dir = primary.direction === \"asc\" ? sql`ASC` : sql`DESC`;\n\tconst cmp = primary.direction === \"asc\" ? sql.raw(\">\") : sql.raw(\"<\");\n\n\tconst firstGroups = groupSets[0] ?? [];\n\tconst restGroups = groupSets.slice(1);\n\tconst multiGroup = firstGroups.length > 1;\n\n\t// Multi-term AND: one residual pivot-PK EXISTS per additional taxonomy.\n\tconst residual =\n\t\trestGroups.length > 0\n\t\t\t? sql`${sql.join(\n\t\t\t\t\trestGroups.map(\n\t\t\t\t\t\t(g) => sql`AND EXISTS (\n\t\t\t\t\t\tSELECT 1 FROM content_taxonomies ct2\n\t\t\t\t\t\tWHERE ct2.collection = ${collection}\n\t\t\t\t\t\t\tAND ct2.entry_id = ct.entry_id\n\t\t\t\t\t\t\tAND ${pivotGroupCondition(\"ct2.taxonomy_id\", g)}\n\t\t\t\t\t)`,\n\t\t\t\t\t),\n\t\t\t\t\tsql` `,\n\t\t\t\t)}`\n\t\t\t: sql``;\n\n\t// Byline assignments remain keyed to a locale-specific content row.\n\tconst bylineCt = bylineGroups\n\t\t? sql`AND EXISTS (\n\t\t\t\tSELECT 1 FROM _emdash_content_bylines cb\n\t\t\t\tWHERE cb.collection_slug = ${collection}\n\t\t\t\t\tAND cb.content_id = r.id\n\t\t\t\t\tAND cb.byline_id IN (${sql.join(bylineGroups.map((g) => sql`${g}`))})\n\t\t\t)`\n\t\t: sql``;\n\n\tconst firstGroupCond = pivotGroupCondition(\"ct.taxonomy_id\", firstGroups);\n\tconst pivotContentJoin = isPostgres(db) ? sql`JOIN` : sql`CROSS JOIN`;\n\tconst {\n\t\tterms: termsSelect,\n\t\tbylines: bylinesSelect,\n\t\tbylinesExist: bylinesExistSelect,\n\t} = foldedHydrationSelects(db, collection, \"r\");\n\n\t// Authoritative re-check on the joined `ec_*` row.\n\tconst deletedR = deletedIsNull ? sql`r.deleted_at IS NULL` : sql`r.deleted_at IS NOT NULL`;\n\tconst statusR = status !== undefined ? sql`AND ${buildStatusCondition(db, status, \"r\")}` : sql``;\n\tconst localeR = locale ? sql`AND r.locale = ${locale}` : sql``;\n\n\tif (isIndexedSort) {\n\t\tconst sortRef = sql.ref(`r.${primary.field}`);\n\t\tconst sortval = multiGroup ? sql`MAX(${sortRef})` : sortRef;\n\t\tconst groupByClause = multiGroup ? sql`GROUP BY r.id` : sql``;\n\n\t\tlet cursorClause = sql``;\n\t\tlet havingClause = sql``;\n\t\tif (cursor) {\n\t\t\tconst { orderValue, id } = decodeCursor(cursor);\n\t\t\tconst cond = sql`(${sortval} ${cmp} ${orderValue} OR (${sortval} = ${orderValue} AND r.id ${cmp} ${id}))`;\n\t\t\t// A GROUP BY makes `sortval` an aggregate → cursor goes in HAVING.\n\t\t\tif (multiGroup) havingClause = sql`HAVING ${cond}`;\n\t\t\telse cursorClause = sql`AND ${cond}`;\n\t\t}\n\n\t\tconst limitClause = buildPivotLimitOffset(db, fetchLimit, offset);\n\n\t\treturn sql<Record<string, unknown>>`\n\t\t\tWITH picked AS (\n\t\t\t\tSELECT r.id AS entry_id, ${sortval} AS sortval\n\t\t\t\tFROM content_taxonomies ct\n\t\t\t\t${pivotContentJoin} ${sql.ref(tableName)} AS r ON r.translation_group = ct.entry_id\n\t\t\t\tWHERE ct.collection = ${collection}\n\t\t\t\t\tAND ${firstGroupCond}\n\t\t\t\t\tAND ${deletedR}\n\t\t\t\t\t${statusR}\n\t\t\t\t\t${localeR}\n\t\t\t\t\t${residual}\n\t\t\t\t\t${bylineCt}\n\t\t\t\t\t${cursorClause}\n\t\t\t\t${groupByClause}\n\t\t\t\t${havingClause}\n\t\t\t\tORDER BY sortval ${dir}, r.id ${dir}\n\t\t\t\t${limitClause}\n\t\t\t)\n\t\t\tSELECT r.*, ${termsSelect}, ${bylinesSelect}, ${bylinesExistSelect}\n\t\t\tFROM picked JOIN ${sql.ref(tableName)} AS r ON r.id = picked.entry_id\n\t\t\tWHERE ${deletedR} ${statusR} ${localeR}\n\t\t\tORDER BY picked.sortval ${dir}, picked.entry_id ${dir}\n\t\t`;\n\t}\n\n\t// Temp-sort path: seek the term via the pivot, sort the joined candidate set.\n\tconst orderByClause = buildOrderByClause(orderBy, \"r\");\n\tconst cursorCond = cursor ? sql`AND ${buildCursorCondition(cursor, orderBy, \"r\")}` : sql``;\n\tconst limitClause = buildPivotLimitOffset(db, fetchLimit, offset);\n\treturn sql<Record<string, unknown>>`\n\t\tWITH picked AS (\n\t\t\tSELECT DISTINCT r.id AS entry_id\n\t\t\tFROM content_taxonomies ct\n\t\t\t${pivotContentJoin} ${sql.ref(tableName)} AS r ON r.translation_group = ct.entry_id\n\t\t\tWHERE ct.collection = ${collection}\n\t\t\t\tAND ${firstGroupCond}\n\t\t\t\tAND ${deletedR}\n\t\t\t\t${statusR}\n\t\t\t\t${localeR}\n\t\t\t\t${residual}\n\t\t\t\t${bylineCt}\n\t\t)\n\t\tSELECT r.*, ${termsSelect}, ${bylinesSelect}, ${bylinesExistSelect}\n\t\tFROM picked JOIN ${sql.ref(tableName)} AS r ON r.id = picked.entry_id\n\t\tWHERE ${deletedR} ${statusR} ${localeR}\n\t\t\t${cursorCond}\n\t\t${orderByClause}\n\t\t${limitClause}\n\t`;\n}\n\n/**\n * Range filter for comparison operators on field values.\n * Values are compared as strings in the database. This works correctly for\n * ISO 8601 dates (e.g. \"2024-01-01T00:00:00Z\") because lexicographic ordering\n * matches chronological ordering. Ensure date values use a consistent format.\n */\nexport interface WhereRange {\n\tgt?: string;\n\tgte?: string;\n\tlt?: string;\n\tlte?: string;\n}\n\n/**\n * A where clause value: exact match, multi-value match, or range comparison.\n */\nexport type WhereValue = string | string[] | WhereRange;\n\n/**\n * Fields shared by every collection filter, independent of pagination mode.\n *\n * Cursor and offset pagination are mutually exclusive, so they live on the\n * `CursorCollectionFilter` / `OffsetCollectionFilter` variants rather than\n * here. Use the {@link CollectionFilter} union for any value that may be\n * either.\n */\nexport interface CollectionFilterBase {\n\ttype: string;\n\tstatus?: \"draft\" | \"published\" | \"archived\";\n\tlimit?: number;\n\t/**\n\t * Filter by field values, taxonomy terms, byline credits, or ranges.\n\t *\n\t * Taxonomy names are detected automatically and filtered via JOIN.\n\t * The reserved `byline` key filters by byline credit (any credit, not\n\t * just the primary one) via the `_emdash_content_bylines` junction\n\t * table; its value is one or more byline translation groups.\n\t * Other keys are treated as column filters on the content table.\n\t *\n\t * @example { category: 'news' } - taxonomy term\n\t * @example { byline: '01HXYZ...' } - entries credited to a byline (any position)\n\t * @example { series: 'main' } - exact match on a content field\n\t * @example { published_at: { gte: '2024-01-01', lt: '2025-01-01' } } - date range\n\t */\n\twhere?: Record<string, WhereValue>;\n\t/**\n\t * Order results by field(s)\n\t * @default { created_at: \"desc\" }\n\t */\n\torderBy?: OrderBySpec;\n\t/**\n\t * Filter by locale (e.g. 'en', 'fr').\n\t * When set, only returns content in this locale.\n\t */\n\tlocale?: string;\n}\n\n/** Keyset-paginated collection filter. Cannot also carry an `offset`. */\nexport interface CursorCollectionFilter extends CollectionFilterBase {\n\t/**\n\t * Opaque cursor for keyset pagination.\n\t * Pass the `nextCursor` value from a previous result to fetch the next page.\n\t */\n\tcursor?: string;\n\toffset?: never;\n}\n\n/** Offset-paginated collection filter. Cannot also carry a `cursor`. */\nexport interface OffsetCollectionFilter extends CollectionFilterBase {\n\t/**\n\t * Skip this many rows before returning results (offset pagination).\n\t * Use with `limit` for numbered archive routes (`/page/2`):\n\t * `offset = (page - 1) * perPage`. Ignored unless it is a positive\n\t * integer.\n\t */\n\toffset?: number;\n\tcursor?: never;\n}\n\n/**\n * Filter for loadCollection - type is required.\n *\n * A union of the cursor and offset pagination variants: supplying both\n * `cursor` and `offset` is a compile-time error, since they are mutually\n * exclusive ways to express \"the next page\" (cursor wins at runtime).\n */\nexport type CollectionFilter = CursorCollectionFilter | OffsetCollectionFilter;\n\n/**\n * Filter for loadEntry - type and id are required\n */\nexport interface EntryFilter {\n\ttype: string;\n\tid: string;\n\t/**\n\t * When set, fetch content data from this revision instead of the content table.\n\t * Used by preview mode to serve draft revision data.\n\t */\n\trevisionId?: string;\n\t/**\n\t * Locale to scope slug lookup. Only affects slug resolution;\n\t * IDs are globally unique and always resolve regardless of locale.\n\t */\n\tlocale?: string;\n}\n\n// Cached database instance (shared across calls)\nlet dbInstance: Kysely<Database> | null = null;\n\n/**\n * Get the database instance. Used by query wrapper functions and middleware.\n *\n * Checks the ALS request context first — if a per-request DB override is set\n * (e.g. by DO preview middleware), it takes precedence over the module-level\n * cached instance. This allows preview mode to route queries to an isolated\n * Durable Object database without modifying any calling code.\n *\n * Initializes the default database on first call using config from virtual module.\n */\nexport async function getDb(): Promise<Kysely<Database>> {\n\t// Per-request DB override via ALS (normal mode)\n\tconst ctx = getRequestContext();\n\tif (ctx?.db) {\n\t\treturn ctx.db as Kysely<Database>; // eslint-disable-line typescript/no-unsafe-type-assertion -- db is typed as unknown in RequestContext to avoid circular deps\n\t}\n\n\tif (!dbInstance) {\n\t\tawait loadVirtualModules();\n\t\tif (!virtualConfig?.database || typeof virtualCreateDialect !== \"function\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"EmDash database not configured. Add database config to emdash() in astro.config.mjs\",\n\t\t\t);\n\t\t}\n\t\tconst dialect = virtualCreateDialect(virtualConfig.database.config);\n\t\tdbInstance = new Kysely<Database>({ dialect, log: kyselyLogOption() });\n\t}\n\treturn dbInstance;\n}\n\n/**\n * Create an EmDash Live Collections loader\n *\n * This loader handles ALL content types in a single Astro collection.\n * Use `getEmDashCollection()` and `getEmDashEntry()` to query\n * specific content types.\n *\n * Database is configured in astro.config.mjs via the emdash() integration.\n *\n * @example\n * ```ts\n * // src/live.config.ts\n * import { defineLiveCollection } from \"astro:content\";\n * import { emdashLoader } from \"emdash\";\n *\n * export const collections = {\n * emdash: defineLiveCollection({\n * loader: emdashLoader(),\n * }),\n * };\n * ```\n */\nexport function emdashLoader(): LiveLoader<EntryData, EntryFilter, CollectionFilter> {\n\treturn {\n\t\tname: \"emdash\",\n\n\t\t/**\n\t\t * Load all entries for a content type\n\t\t */\n\t\tasync loadCollection({ filter }) {\n\t\t\ttry {\n\t\t\t\t// Get DB instance (initializes on first use)\n\t\t\t\tconst db = await getDb();\n\n\t\t\t\t// Type filter is required\n\t\t\t\tconst type = filter?.type;\n\t\t\t\tif (!type) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\terror: new Error(\n\t\t\t\t\t\t\t\"type filter is required. Use getEmDashCollection() instead of getLiveCollection() directly.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Query the per-collection table (ec_posts, ec_products, etc.)\n\t\t\t\tconst tableName = getTableName(type);\n\n\t\t\t\t// Build query with dynamic table name\n\t\t\t\tconst status = filter?.status || \"published\";\n\t\t\t\tconst limit = filter?.limit;\n\t\t\t\tconst cursor = filter?.cursor;\n\t\t\t\tconst where = filter?.where;\n\t\t\t\tconst orderBy = filter?.orderBy;\n\t\t\t\tconst locale = filter?.locale;\n\n\t\t\t\t// Cursor pagination: over-fetch by 1 to detect next page\n\t\t\t\tconst fetchLimit = limit ? limit + 1 : undefined;\n\n\t\t\t\t// Offset pagination (numbered archive routes). Keyset (cursor)\n\t\t\t\t// and offset are mutually exclusive ways to express \"the next\n\t\t\t\t// page\" — when both are supplied, cursor wins and offset is\n\t\t\t\t// dropped so the two don't stack into a double skip. Only a\n\t\t\t\t// positive integer applies; 0 / negative / fractional are no-ops.\n\t\t\t\tconst rawOffset = cursor ? undefined : filter?.offset;\n\t\t\t\tconst offset =\n\t\t\t\t\ttypeof rawOffset === \"number\" && Number.isInteger(rawOffset) && rawOffset > 0\n\t\t\t\t\t\t? rawOffset\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\t// Build cursor condition if cursor is provided\n\t\t\t\tconst cursorCondition = cursor ? buildCursorCondition(cursor, orderBy) : null;\n\n\t\t\t\t// Separate taxonomy / byline filters from field filters\n\t\t\t\tlet result: { rows: Record<string, unknown>[] };\n\t\t\t\t// Taxonomy filters AND together: each entry constrains the base\n\t\t\t\t// row to match at least one of its slugs *within that taxonomy*.\n\t\t\t\t// Term slugs are unique only within a taxonomy, so every filter\n\t\t\t\t// keeps its own `name` and emits its own `EXISTS` clause rather\n\t\t\t\t// than pooling slugs into one `IN`.\n\t\t\t\tconst taxonomyFilters: { name: string; slugs: string[] }[] = [];\n\t\t\t\t// A byline filter matches entries credited to any of the given\n\t\t\t\t// byline translation groups via the `_emdash_content_bylines`\n\t\t\t\t// junction table. `null` means no byline filter; an empty\n\t\t\t\t// `groups` array means the filter was requested but matches\n\t\t\t\t// nothing (short-circuited to an empty result below).\n\t\t\t\tlet bylineFilter: { groups: string[] } | null = null;\n\t\t\t\tconst fieldFilters: Record<string, WhereValue> = {};\n\n\t\t\t\tif (where && Object.keys(where).length > 0) {\n\t\t\t\t\tconst taxNames = await getTaxonomyNames(db, type);\n\n\t\t\t\t\tfor (const [key, value] of Object.entries(where)) {\n\t\t\t\t\t\tif (value == null) continue;\n\t\t\t\t\t\tif (key === \"byline\") {\n\t\t\t\t\t\t\tif (isWhereRange(value)) {\n\t\t\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t\t\t`[emdash] where filter: range operators are not supported on \"byline\", ignored`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst groups = Array.isArray(value) ? value : [value];\n\t\t\t\t\t\t\tbylineFilter = { groups };\n\t\t\t\t\t\t} else if (taxNames.has(key)) {\n\t\t\t\t\t\t\tif (isWhereRange(value)) {\n\t\t\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t\t\t`[emdash] where filter: range operators are not supported on taxonomy \"${key}\", ignored`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst slugs = Array.isArray(value) ? value : [value];\n\t\t\t\t\t\t\ttaxonomyFilters.push({ name: key, slugs });\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfieldFilters[key] = value;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// A byline or taxonomy filter with no values matches nothing —\n\t\t\t\t// short-circuit before building SQL (an empty `IN ()` is invalid\n\t\t\t\t// SQL on both dialects).\n\t\t\t\tif (\n\t\t\t\t\t(bylineFilter && bylineFilter.groups.length === 0) ||\n\t\t\t\t\ttaxonomyFilters.some((f) => f.slugs.length === 0)\n\t\t\t\t) {\n\t\t\t\t\treturn { entries: [], cacheHint: { tags: [type] } };\n\t\t\t\t}\n\n\t\t\t\tif (taxonomyFilters.length > 0 && Object.keys(fieldFilters).length === 0) {\n\t\t\t\t\t// Pivot-drive fast path (#1834): seek the matching entries on the\n\t\t\t\t\t// denormalized `content_taxonomies` pivot instead of scanning the\n\t\t\t\t\t// whole collection and probing a taxonomy EXISTS per row. Only the\n\t\t\t\t\t// taxonomy path is restructured — a taxonomy filter combined with a\n\t\t\t\t\t// content-field filter falls through to the single-table shape\n\t\t\t\t\t// below (field predicates live on `ec_*`, not the pivot). A byline\n\t\t\t\t\t// filter rides along inside the pivot CTE (see the builder).\n\t\t\t\t\tconst groupSets: string[][] = [];\n\t\t\t\t\tfor (const taxFilter of taxonomyFilters) {\n\t\t\t\t\t\tconst groups = await resolveTermGroups(db, taxFilter.name, taxFilter.slugs, locale);\n\t\t\t\t\t\t// A slug that resolves to no term matches nothing; since taxonomy\n\t\t\t\t\t\t// filters AND together, one empty set empties the whole result.\n\t\t\t\t\t\tif (groups.length === 0) {\n\t\t\t\t\t\t\treturn { entries: [], cacheHint: { tags: [type] } };\n\t\t\t\t\t\t}\n\t\t\t\t\t\tgroupSets.push(groups);\n\t\t\t\t\t}\n\n\t\t\t\t\tresult = await buildTaxonomyPivotQuery({\n\t\t\t\t\t\tdb,\n\t\t\t\t\t\tcollection: type,\n\t\t\t\t\t\ttableName,\n\t\t\t\t\t\tgroupSets,\n\t\t\t\t\t\torderBy,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t\tlocale,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\t// Public listings only ever want live content.\n\t\t\t\t\t\tdeletedIsNull: true,\n\t\t\t\t\t\tbylineGroups: bylineFilter ? bylineFilter.groups : null,\n\t\t\t\t\t\tfetchLimit,\n\t\t\t\t\t\toffset,\n\t\t\t\t\t}).execute(db);\n\t\t\t\t} else {\n\t\t\t\t\t// Taxonomy and byline filters are applied as correlated\n\t\t\t\t\t// `EXISTS` semi-joins rather than `INNER JOIN ... DISTINCT`.\n\t\t\t\t\t// A join fan-out would force `SELECT DISTINCT table.*`, and\n\t\t\t\t\t// Postgres cannot apply DISTINCT to a row containing a `json`\n\t\t\t\t\t// column (no equality operator), so the join approach throws\n\t\t\t\t\t// there. EXISTS matches \"credited/tagged at least once\"\n\t\t\t\t\t// without duplicating rows, needs no DISTINCT, and works on\n\t\t\t\t\t// both SQLite and Postgres. The base query stays a single-\n\t\t\t\t\t// table `SELECT *`, so all field/status/locale/cursor/order\n\t\t\t\t\t// conditions reference unprefixed columns as before.\n\t\t\t\t\tconst orderByClause = buildOrderByClause(orderBy);\n\t\t\t\t\tconst statusCondition = buildStatusCondition(db, status);\n\t\t\t\t\tconst localeFilter = locale ? sql`AND locale = ${locale}` : sql``;\n\t\t\t\t\tconst cursorCond = cursorCondition ? sql`AND ${cursorCondition}` : sql``;\n\t\t\t\t\tconst fieldConds = buildFieldConditions(fieldFilters);\n\t\t\t\t\tconst fieldCondsSQL =\n\t\t\t\t\t\tfieldConds.length > 0 ? sql`${sql.join(fieldConds, sql` AND `)}` : null;\n\n\t\t\t\t\t// One `EXISTS` per taxonomy, AND'd together: an entry must be\n\t\t\t\t\t// tagged with a matching term in *every* requested taxonomy.\n\t\t\t\t\t// Each clause pins its own `t.name`, so slugs never pool\n\t\t\t\t\t// across taxonomies (they're only unique within one).\n\t\t\t\t\tconst taxonomyCond =\n\t\t\t\t\t\ttaxonomyFilters.length > 0\n\t\t\t\t\t\t\t? sql`${sql.join(\n\t\t\t\t\t\t\t\t\ttaxonomyFilters.map(\n\t\t\t\t\t\t\t\t\t\t(f) => sql`AND EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM content_taxonomies ct\n\t\t\t\t\t\t\tINNER JOIN taxonomies t ON t.translation_group = ct.taxonomy_id\n\t\t\t\t\t\t\tWHERE ct.collection = ${type}\n\t\t\t\t\t\t\t\tAND ct.entry_id = ${sql.ref(tableName)}.translation_group\n\t\t\t\t\t\t\t\tAND t.name = ${f.name}\n\t\t\t\t\t\t\t\tAND t.slug IN (${sql.join(f.slugs.map((s) => sql`${s}`))})\n\t\t\t\t\t\t\t${locale ? sql`AND t.locale = ${locale}` : sql``}\n\t\t\t\t\t\t)`,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\tsql` `,\n\t\t\t\t\t\t\t\t)}`\n\t\t\t\t\t\t\t: sql``;\n\n\t\t\t\t\t// `_emdash_content_bylines.byline_id` stores the byline's\n\t\t\t\t\t// translation_group (migration 040), so a credit spans every\n\t\t\t\t\t// locale variant of the byline and we match the group directly.\n\t\t\t\t\tconst bylineCond = bylineFilter\n\t\t\t\t\t\t? sql`AND EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM _emdash_content_bylines cb\n\t\t\t\t\t\t\tWHERE cb.collection_slug = ${type}\n\t\t\t\t\t\t\t\tAND cb.content_id = ${sql.ref(tableName)}.id\n\t\t\t\t\t\t\t\tAND cb.byline_id IN (${sql.join(bylineFilter.groups.map((g) => sql`${g}`))})\n\t\t\t\t\t\t)`\n\t\t\t\t\t\t: sql``;\n\n\t\t\t\t\t// Fold byline + taxonomy hydration into the list query.\n\t\t\t\t\tconst {\n\t\t\t\t\t\tterms: termsSelect,\n\t\t\t\t\t\tbylines: bylinesSelect,\n\t\t\t\t\t\tbylinesExist: bylinesExistSelect,\n\t\t\t\t\t} = foldedHydrationSelects(db, type, tableName);\n\n\t\t\t\t\t// LIMIT/OFFSET clause. SQLite only accepts OFFSET when a\n\t\t\t\t\t// LIMIT is present, so a bare offset uses `LIMIT -1`\n\t\t\t\t\t// (unbounded); Postgres takes a standalone OFFSET.\n\t\t\t\t\tlet limitOffsetClause = sql``;\n\t\t\t\t\tif (fetchLimit != null && offset != null) {\n\t\t\t\t\t\tlimitOffsetClause = sql`LIMIT ${fetchLimit} OFFSET ${offset}`;\n\t\t\t\t\t} else if (fetchLimit != null) {\n\t\t\t\t\t\tlimitOffsetClause = sql`LIMIT ${fetchLimit}`;\n\t\t\t\t\t} else if (offset != null) {\n\t\t\t\t\t\tlimitOffsetClause = isPostgres(db)\n\t\t\t\t\t\t\t? sql`OFFSET ${offset}`\n\t\t\t\t\t\t\t: sql`LIMIT -1 OFFSET ${offset}`;\n\t\t\t\t\t}\n\t\t\t\t\tresult = await sql<Record<string, unknown>>`\n\t\t\t\t\t\tSELECT *, ${termsSelect}, ${bylinesSelect}, ${bylinesExistSelect} FROM ${sql.ref(tableName)}\n\t\t\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\t\t\tAND ${statusCondition}\n\t\t\t\t\t\t${localeFilter}\n\t\t\t\t\t\t${cursorCond}\n\t\t\t\t\t\t${taxonomyCond}\n\t\t\t\t\t\t${bylineCond}\n\t\t\t\t\t\t${fieldCondsSQL ? sql`AND ${fieldCondsSQL}` : sql``}\n\t\t\t\t\t\t${orderByClause}\n\t\t\t\t\t\t${limitOffsetClause}\n\t\t\t\t\t`.execute(db);\n\t\t\t\t}\n\n\t\t\t\t// Detect whether there are more results (over-fetched by 1)\n\t\t\t\tconst hasMore = limit ? result.rows.length > limit : false;\n\t\t\t\tconst rows = hasMore ? result.rows.slice(0, limit) : result.rows;\n\n\t\t\t\t// Map rows to entries\n\t\t\t\tconst i18nConfig = virtualConfig?.i18n;\n\t\t\t\tconst i18nEnabled = i18nConfig && i18nConfig.locales.length > 1;\n\t\t\t\tconst entries = rows.map((row) => {\n\t\t\t\t\tconst slug = rowStr(row, \"slug\") || rowStr(row, \"id\");\n\t\t\t\t\tconst rowLocale = rowStr(row, \"locale\");\n\t\t\t\t\tconst shouldPrefix =\n\t\t\t\t\t\ti18nEnabled &&\n\t\t\t\t\t\trowLocale !== \"\" &&\n\t\t\t\t\t\t(rowLocale !== i18nConfig.defaultLocale || i18nConfig.prefixDefaultLocale);\n\t\t\t\t\tconst id = shouldPrefix ? `${rowLocale}/${slug}` : slug;\n\t\t\t\t\tconst data = mapRowToData(row);\n\t\t\t\t\tstashFolded(data, row);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tslug: rowStr(row, \"slug\"),\n\t\t\t\t\t\tstatus: rowStr(row, \"status\", \"draft\"),\n\t\t\t\t\t\tdata,\n\t\t\t\t\t\tcacheHint: {\n\t\t\t\t\t\t\ttags: [rowStr(row, \"id\")],\n\t\t\t\t\t\t\tlastModified: row.updated_at ? new Date(rowStr(row, \"updated_at\")) : undefined,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t});\n\n\t\t\t\t// Encode nextCursor from the last row if there are more results\n\t\t\t\tlet nextCursor: string | undefined;\n\t\t\t\tif (hasMore && rows.length > 0) {\n\t\t\t\t\tconst lastRow = rows.at(-1)!;\n\t\t\t\t\tconst primary = getPrimarySort(orderBy);\n\t\t\t\t\t// Strip table prefix from field name for row lookup\n\t\t\t\t\tconst fieldName = primary.field.includes(\".\")\n\t\t\t\t\t\t? primary.field.split(\".\").pop()!\n\t\t\t\t\t\t: primary.field;\n\t\t\t\t\tconst lastOrderValue = lastRow[fieldName];\n\t\t\t\t\tconst orderStr =\n\t\t\t\t\t\ttypeof lastOrderValue === \"string\" || typeof lastOrderValue === \"number\"\n\t\t\t\t\t\t\t? String(lastOrderValue)\n\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\tnextCursor = encodeCursor(orderStr, String(lastRow.id));\n\t\t\t\t}\n\n\t\t\t\t// Collection-level cache hint uses the most recent updated_at\n\t\t\t\tlet collectionLastModified: Date | undefined;\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tif (row.updated_at) {\n\t\t\t\t\t\tconst d = new Date(rowStr(row, \"updated_at\"));\n\t\t\t\t\t\tif (!collectionLastModified || d > collectionLastModified) {\n\t\t\t\t\t\t\tcollectionLastModified = d;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tentries,\n\t\t\t\t\tnextCursor,\n\t\t\t\t\tcacheHint: {\n\t\t\t\t\t\ttags: [type],\n\t\t\t\t\t\tlastModified: collectionLastModified,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\t// Handle missing table/column gracefully - return empty collection.\n\t\t\t\t// Missing table happens before migrations have run.\n\t\t\t\t// Missing column happens when a where filter references a non-existent field.\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tif (isMissingTableError(error) || isMissingColumnError(error)) {\n\t\t\t\t\tif (isMissingColumnError(error)) {\n\t\t\t\t\t\tconsole.warn(`[emdash] where filter: ${message}`);\n\t\t\t\t\t}\n\t\t\t\t\treturn { entries: [] };\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\terror: new Error(`Failed to load collection: ${message}`),\n\t\t\t\t};\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * Load a single entry by type and ID/slug\n\t\t *\n\t\t * When filter.revisionId is set (preview mode), the entry's data\n\t\t * comes from the revisions table instead of the content table columns.\n\t\t */\n\t\tasync loadEntry({ filter }) {\n\t\t\ttry {\n\t\t\t\t// Get DB instance\n\t\t\t\tconst db = await getDb();\n\n\t\t\t\t// Both type and id are required\n\t\t\t\tconst type = filter?.type;\n\t\t\t\tconst id = filter?.id;\n\n\t\t\t\tif (!type || !id) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\terror: new Error(\n\t\t\t\t\t\t\t\"type and id filters are required. Use getEmDashEntry() instead of getLiveEntry() directly.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Query the per-collection table\n\t\t\t\tconst tableName = getTableName(type);\n\t\t\t\tconst locale = filter?.locale;\n\n\t\t\t\t// Use raw SQL for dynamic table name, match by slug or id\n\t\t\t\t// When locale is specified, prefer locale-scoped slug match,\n\t\t\t\t// but IDs are globally unique so always check id without locale scope.\n\t\t\t\t//\n\t\t\t\t// Byline + taxonomy hydration (foldedHydrationSelects) and per-entry\n\t\t\t\t// SEO (foldedSeoSelect) are each surfaced as a single aggregated JSON\n\t\t\t\t// column rather than flat columns. This keeps the result-set width\n\t\t\t\t// bounded at any collection schema width: a flat `LEFT JOIN _emdash_seo`\n\t\t\t\t// adds 5 alias columns to every row and pushes wide flat-schema\n\t\t\t\t// collections (common after WordPress / ACF imports) past D1's\n\t\t\t\t// per-result-set column limit, surfacing as a silent null entry. One\n\t\t\t\t// JSON column is one column, so the join stays safe at any width and\n\t\t\t\t// we keep the single round trip.\n\t\t\t\tconst {\n\t\t\t\t\tterms: termsSelect,\n\t\t\t\t\tbylines: bylinesSelect,\n\t\t\t\t\tbylinesExist: bylinesExistSelect,\n\t\t\t\t} = foldedHydrationSelects(db, type, \"c\");\n\t\t\t\tconst seoSelect = foldedSeoSelect(db, type, \"c\");\n\t\t\t\tconst result = locale\n\t\t\t\t\t? await sql<Record<string, unknown>>`\n\t\t\t\t\t\t\tSELECT c.*, ${seoSelect}, ${termsSelect}, ${bylinesSelect}, ${bylinesExistSelect}\n\t\t\t\t\t\t\tFROM ${sql.ref(tableName)} AS c\n\t\t\t\t\t\t\tWHERE c.deleted_at IS NULL\n\t\t\t\t\t\t\tAND ((c.slug = ${id} AND c.locale = ${locale}) OR c.id = ${id})\n\t\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t\t`.execute(db)\n\t\t\t\t\t: await sql<Record<string, unknown>>`\n\t\t\t\t\t\t\tSELECT c.*, ${seoSelect}, ${termsSelect}, ${bylinesSelect}, ${bylinesExistSelect}\n\t\t\t\t\t\t\tFROM ${sql.ref(tableName)} AS c\n\t\t\t\t\t\t\tWHERE c.deleted_at IS NULL\n\t\t\t\t\t\t\tAND (c.slug = ${id} OR c.id = ${id})\n\t\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t\t`.execute(db);\n\n\t\t\t\tconst row = result.rows[0];\n\t\t\t\tif (!row) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\t// Expand the folded SEO JSON column onto SEO_COLUMN_ALIASES so\n\t\t\t\t// extractSeo() reads it transparently. Missing/null SEO is a\n\t\t\t\t// no-op: extractSeo() returns null when the aliases are absent.\n\t\t\t\texpandFoldedSeo(row);\n\n\t\t\t\tconst i18nConfig = virtualConfig?.i18n;\n\t\t\t\tconst i18nEnabled = i18nConfig && i18nConfig.locales.length > 1;\n\t\t\t\tconst entrySlug = rowStr(row, \"slug\") || rowStr(row, \"id\");\n\t\t\t\tconst entryLocale = rowStr(row, \"locale\");\n\t\t\t\tconst shouldPrefixEntry =\n\t\t\t\t\ti18nEnabled &&\n\t\t\t\t\tentryLocale !== \"\" &&\n\t\t\t\t\t(entryLocale !== i18nConfig.defaultLocale || i18nConfig.prefixDefaultLocale);\n\t\t\t\tconst entryId = shouldPrefixEntry ? `${entryLocale}/${entrySlug}` : entrySlug;\n\n\t\t\t\t// Preview mode: override content fields with revision data,\n\t\t\t\t// keeping system metadata from the content table row.\n\t\t\t\tconst revisionId = filter?.revisionId;\n\t\t\t\tif (revisionId) {\n\t\t\t\t\tconst revRow = await sql<{ data: string }>`\n\t\t\t\t\t\tSELECT data FROM revisions\n\t\t\t\t\t\tWHERE id = ${revisionId}\n\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t`.execute(db);\n\n\t\t\t\t\tconst revData = revRow.rows[0];\n\t\t\t\t\tif (revData) {\n\t\t\t\t\t\tconst parsed: Record<string, unknown> = JSON.parse(revData.data);\n\t\t\t\t\t\t// System metadata from content table + content fields from revision\n\t\t\t\t\t\tconst systemData: Record<string, unknown> = {};\n\t\t\t\t\t\tfor (const [key, mappedKey] of Object.entries(INCLUDE_IN_DATA)) {\n\t\t\t\t\t\t\tif (key in row) {\n\t\t\t\t\t\t\t\tif (DATE_COLUMNS.has(key)) {\n\t\t\t\t\t\t\t\t\tsystemData[mappedKey] = typeof row[key] === \"string\" ? new Date(row[key]) : null;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tsystemData[mappedKey] = row[key];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Use slug from revision metadata if present, else from content table\n\t\t\t\t\t\tconst slug = typeof parsed._slug === \"string\" ? parsed._slug : rowStr(row, \"slug\");\n\t\t\t\t\t\tconst revSlug = slug || rowStr(row, \"id\");\n\t\t\t\t\t\tconst revLocale = rowStr(row, \"locale\");\n\t\t\t\t\t\tconst shouldPrefixRev =\n\t\t\t\t\t\t\ti18nEnabled &&\n\t\t\t\t\t\t\trevLocale !== \"\" &&\n\t\t\t\t\t\t\t(revLocale !== i18nConfig.defaultLocale || i18nConfig.prefixDefaultLocale);\n\t\t\t\t\t\tconst revId = shouldPrefixRev ? `${revLocale}/${revSlug}` : revSlug;\n\t\t\t\t\t\t// SEO is not revisioned — it comes from the content row's\n\t\t\t\t\t\t// joined _emdash_seo columns, not the revision snapshot.\n\t\t\t\t\t\tconst revEntryData: Record<string, unknown> = {\n\t\t\t\t\t\t\t...systemData,\n\t\t\t\t\t\t\tslug,\n\t\t\t\t\t\t\t...mapRevisionData(parsed),\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst revSeo = extractSeo(row);\n\t\t\t\t\t\tif (revSeo) revEntryData.seo = revSeo;\n\t\t\t\t\t\tstashFolded(revEntryData, row);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tid: revId,\n\t\t\t\t\t\t\tslug,\n\t\t\t\t\t\t\tstatus: rowStr(row, \"status\", \"draft\"),\n\t\t\t\t\t\t\tdata: revEntryData,\n\t\t\t\t\t\t\tcacheHint: {\n\t\t\t\t\t\t\t\ttags: [rowStr(row, \"id\")],\n\t\t\t\t\t\t\t\tlastModified: row.updated_at ? new Date(rowStr(row, \"updated_at\")) : undefined,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst entryData = mapRowToData(row);\n\t\t\t\tconst entrySeo = extractSeo(row);\n\t\t\t\tif (entrySeo) entryData.seo = entrySeo;\n\t\t\t\tstashFolded(entryData, row);\n\t\t\t\treturn {\n\t\t\t\t\tid: entryId,\n\t\t\t\t\tslug: rowStr(row, \"slug\"),\n\t\t\t\t\tstatus: rowStr(row, \"status\", \"draft\"),\n\t\t\t\t\tdata: entryData,\n\t\t\t\t\tcacheHint: {\n\t\t\t\t\t\ttags: [rowStr(row, \"id\")],\n\t\t\t\t\t\tlastModified: row.updated_at ? new Date(rowStr(row, \"updated_at\")) : undefined,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\t// Handle missing table gracefully - return undefined (not found).\n\t\t\t\t// This happens before migrations have run.\n\t\t\t\tif (isMissingTableError(error)) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\treturn {\n\t\t\t\t\terror: new Error(`Failed to load entry: ${message}`),\n\t\t\t\t};\n\t\t\t}\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;AAsB3B,MAAM,qBAA6C;CAClD,WAAW;CACX,iBAAiB;CACjB,WAAW;CACX,eAAe;CACf,cAAc;CACd;;AAGD,MAAM,oBA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IH,MAAM,YAAY,aAAa,IAAI;IACnC,MAAM,WAAW,WAAW,IAAI;AAChC,QAAI,SAAU,WAAU,MAAM;AAC9B,gBAAY,WAAW,IAAI;AAC3B,WAAO;KACN,IAAI;KACJ,MAAM,OAAO,KAAK,OAAO;KACzB,QAAQ,OAAO,KAAK,UAAU,QAAQ;KACtC,MAAM;KACN,WAAW;MACV,MAAM,CAAC,OAAO,KAAK,KAAK,CAAC;MACzB,cAAc,IAAI,aAAa,IAAI,KAAK,OAAO,KAAK,aAAa,CAAC,GAAG;MACrE;KACD;YACO,OAAO;AAGf,QAAI,oBAAoB,MAAM,CAC7B;IAGD,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AACtE,WAAO,EACN,uBAAO,IAAI,MAAM,yBAAyB,UAAU,EACpD;;;EAGH"}
1
+ {"version":3,"file":"loader-CdG_Ci3H.mjs","names":[],"sources":["../src/loader.ts"],"sourcesContent":["/**\n * Astro Live Collections loader for EmDash\n *\n * This loader implements the Astro LiveLoader interface to fetch content\n * at runtime from the database, enabling live editing without rebuilds.\n *\n * Architecture:\n * - Single `_emdash` Astro collection handles all content types\n * - Dialect comes from virtual module (configured in astro.config.mjs)\n * - Each content type maps to its own database table: ec_posts, ec_products, etc.\n * - `getEmDashCollection()` / `getEmDashEntry()` wrap Astro's live collection API\n */\n\nimport type { LiveLoader } from \"astro/loaders\";\nimport { Kysely, type RawBuilder, sql, type Dialect } from \"kysely\";\n\nimport { buildStatusCondition, isPostgres } from \"./database/dialect-helpers.js\";\nimport { kyselyLogOption } from \"./database/instrumentation.js\";\nimport { decodeCursor, encodeCursor } from \"./database/repositories/types.js\";\nimport { validateIdentifier } from \"./database/validate.js\";\nimport { getI18nConfig } from \"./i18n/config.js\";\nimport type { Database } from \"./index.js\";\nimport { getRequestContext } from \"./request-context.js\";\nimport { isMissingColumnError, isMissingTableError } from \"./utils/db-errors.js\";\n\nconst FIELD_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n/**\n * SEO columns folded into the single-entry query as a single JSON column\n * (`_emdash_seo` in the result set), then expanded onto the row under these\n * aliases for `extractSeo()`. Surfacing SEO as one aggregated column keeps the\n * result-set width bounded regardless of how many fields the collection has,\n * which matters for D1: a flat `LEFT JOIN _emdash_seo` adds 5 alias columns to\n * every row and pushes wide collections (common after WordPress / ACF imports)\n * past D1's per-result-set column limit, surfacing as a silent null entry.\n * One JSON column is one column, so the join stays safe at any schema width.\n *\n * The aliases mirror the strategy used by `foldedHydrationSelects` for byline\n * and taxonomy hydration: aggregate in SQL, expand in JS. SEO is 1:1 with\n * content, so the subquery uses `json_object` (not the array aggregator).\n *\n * The `_emdash_` prefix on the aliases guarantees they can never collide with\n * a content field. Field slugs must match `/^[a-z][a-z0-9_]*$/`, so a user can\n * legitimately define a `seo_title` field; surfacing the SEO column under its\n * bare name would shadow that field in the result set and drop the user's\n * value. The prefix (illegal as a leading slug char) sidesteps this entirely.\n */\nconst SEO_COLUMN_ALIASES: Record<string, string> = {\n\tseo_title: \"_emdash_seo_title\",\n\tseo_description: \"_emdash_seo_description\",\n\tseo_image: \"_emdash_seo_image\",\n\tseo_canonical: \"_emdash_seo_canonical\",\n\tseo_no_index: \"_emdash_seo_no_index\",\n};\n\n/** Aliased SEO result keys — excluded from generic field mapping. */\nconst SEO_ALIAS_COLUMNS = Object.values(SEO_COLUMN_ALIASES);\n\n/** Folded SEO JSON column name in the result set (expanded onto aliases in JS). */\nconst SEO_FOLDED_COLUMN = \"_emdash_seo\";\n\n/**\n * System columns excluded from entry.data\n * Note: slug is intentionally NOT excluded - it's useful as data.slug in templates\n */\nconst SYSTEM_COLUMNS = new Set([\n\t\"id\",\n\t// \"slug\" - kept in data for template access\n\t\"status\",\n\t\"author_id\",\n\t\"primary_byline_id\",\n\t\"created_at\",\n\t\"updated_at\",\n\t\"published_at\",\n\t\"scheduled_at\",\n\t\"deleted_at\",\n\t\"version\",\n\t\"live_revision_id\",\n\t\"draft_revision_id\",\n\t\"locale\",\n\t\"translation_group\",\n\t// Aliased SEO columns expanded from the folded _emdash_seo JSON column on\n\t// the single-entry path. Surfaced as a nested data.seo object (see\n\t// extractSeo), never as flat fields. The aliases are _emdash_-prefixed so\n\t// they can't shadow a user field named e.g. `seo_title`.\n\t...SEO_ALIAS_COLUMNS,\n\t// Folded hydration JSON columns (see foldedHydrationSelects and\n\t// foldedSeoSelect) — surfaced via the FOLDED_* markers or expanded onto\n\t// SEO_ALIAS_COLUMNS, never as flat fields.\n\t\"_emdash_terms\",\n\t\"_emdash_bylines\",\n\t\"_emdash_bylines_exist\",\n\tSEO_FOLDED_COLUMN,\n]);\n\n/** Markers for byline/taxonomy hydration folded into the content query. */\nexport const FOLDED_TERMS = Symbol.for(\"emdash:foldedTerms\");\nexport const FOLDED_BYLINES = Symbol.for(\"emdash:foldedBylines\");\n/**\n * Marker for whether `_emdash_bylines` has any rows at all (`false` = table\n * empty). Lets byline hydration trust an empty fold instead of re-checking\n * via the byline query path on sites that never use bylines.\n */\nexport const FOLDED_BYLINES_EXIST = Symbol.for(\"emdash:foldedBylinesExist\");\n\n/**\n * Correlated JSON-array subqueries that fold taxonomy-term and byline hydration\n * into the content query, removing the two separate hydration round trips per\n * fetch. `outer` is the content table's alias/name; each subquery correlates on\n * `<outer>.id`, so the base query stays one row per entry (no join fan-out, no\n * duplicated content payload). Order is NOT applied in the aggregate (it differs\n * across dialects) — the consumer sorts terms by label and credits by sortOrder.\n *\n * Dialect-specific aggregation: SQLite `json_group_array`/`json_object` returns\n * a JSON *string*; Postgres `json_agg`/`json_build_object` (coalesced to `[]`)\n * returns parsed JSON. {@link stashFolded} handles both.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any Kysely instance\nfunction foldedHydrationSelects(db: Kysely<any>, type: string, outer: string) {\n\tconst o = sql.ref(outer);\n\tconst pg = isPostgres(db);\n\tconst obj = (pairs: string) =>\n\t\tpg ? sql.raw(`json_build_object(${pairs})`) : sql.raw(`json_object(${pairs})`);\n\tconst agg = (inner: RawBuilder<unknown>) =>\n\t\tpg ? sql`coalesce(json_agg(${inner}), '[]'::json)` : sql`json_group_array(${inner})`;\n\n\t// Pin the byline join order on SQLite (#1722). Taxonomy hydration uses\n\t// LEFT JOINs below, whose order is already fixed by SQL semantics. SQLite\n\t// honours `CROSS JOIN` ordering, forcing the byline subquery to drive from\n\t// its pivot by content reference and probe by translation_group. Postgres\n\t// keeps statistics and rejects `CROSS JOIN … ON`, so it stays a plain JOIN.\n\tconst foldJoin = pg ? sql`JOIN` : sql`CROSS JOIN`;\n\n\tconst termObj = obj(\n\t\t\"'id', coalesce(exact_term.id, default_term.id), 'name', coalesce(exact_term.name, default_term.name), 'slug', coalesce(exact_term.slug, default_term.slug), 'label', coalesce(exact_term.label, default_term.label), 'parent_id', coalesce(exact_term.parent_id, default_term.parent_id), 'locale', coalesce(exact_term.locale, default_term.locale), 'translation_group', coalesce(exact_term.translation_group, default_term.translation_group)\",\n\t);\n\tconst defaultLocale = getI18nConfig()?.defaultLocale ?? \"en\";\n\tconst selectedTermId = sql`coalesce(exact_term.id, default_term.id)`;\n\tconst termAgg = pg\n\t\t? sql`coalesce(json_agg(${termObj}) FILTER (WHERE ${selectedTermId} IS NOT NULL), '[]'::json)`\n\t\t: sql`json_group_array(${termObj}) FILTER (WHERE ${selectedTermId} IS NOT NULL)`;\n\tconst terms = sql`(SELECT ${termAgg} FROM ${sql.ref(\"content_taxonomies\")} AS ct LEFT JOIN ${sql.ref(\"taxonomies\")} AS exact_term ON exact_term.translation_group = ct.taxonomy_id AND exact_term.locale = ${o}.locale LEFT JOIN ${sql.ref(\"taxonomies\")} AS default_term ON default_term.translation_group = ct.taxonomy_id AND default_term.locale = ${defaultLocale} WHERE ct.collection = ${type} AND ct.entry_id = ${o}.translation_group) AS ${sql.ref(\"_emdash_terms\")}`;\n\n\tconst bylineInner = obj(\n\t\t\"'id', b.id, 'slug', b.slug, 'displayName', b.display_name, 'bio', b.bio, 'avatarMediaId', b.avatar_media_id, 'avatarStorageKey', m.storage_key, 'avatarAlt', m.alt, 'avatarBlurhash', m.blurhash, 'avatarDominantColor', m.dominant_color, 'websiteUrl', b.website_url, 'userId', b.user_id, 'isGuest', b.is_guest, 'createdAt', b.created_at, 'updatedAt', b.updated_at, 'locale', b.locale, 'translationGroup', b.translation_group\",\n\t);\n\tconst creditObj = pg\n\t\t? sql.raw(\n\t\t\t\t\"json_build_object('roleLabel', cb.role_label, 'sortOrder', cb.sort_order, 'byline', \",\n\t\t\t)\n\t\t: sql.raw(\"json_object('roleLabel', cb.role_label, 'sortOrder', cb.sort_order, 'byline', \");\n\tconst credit = sql`${creditObj}${bylineInner})`;\n\tconst bylines = sql`(SELECT ${agg(credit)} FROM ${sql.ref(\"_emdash_content_bylines\")} AS cb ${foldJoin} ${sql.ref(\"_emdash_bylines\")} AS b ON b.translation_group = cb.byline_id LEFT JOIN ${sql.ref(\"media\")} AS m ON m.id = b.avatar_media_id WHERE cb.collection_slug = ${type} AND cb.content_id = ${o}.id AND b.locale = ${o}.locale) AS ${sql.ref(\"_emdash_bylines\")}`;\n\t// Uncorrelated existence probe (evaluated once per statement, not per row):\n\t// 1 when `_emdash_bylines` has any row, NULL when empty. An empty table\n\t// means an empty fold is authoritative — no credit in any locale, no\n\t// author-fallback byline — so hydration can skip the byline query path.\n\tconst bylinesExist = sql`(SELECT 1 FROM ${sql.ref(\"_emdash_bylines\")} LIMIT 1) AS ${sql.ref(\"_emdash_bylines_exist\")}`;\n\treturn { terms, bylines, bylinesExist };\n}\n\n/**\n * Correlated JSON-object subquery that folds per-entry SEO into the content\n * query without widening the result set: 1 row of `_emdash_seo` becomes 1 JSON\n * column rather than 5 flat columns. The JSON column is expanded onto the row\n * via {@link expandFoldedSeo} after the query runs, preserving the alias keys\n * that {@link extractSeo} reads. Missing SEO row (no entry in `_emdash_seo`)\n * yields NULL, which {@link expandFoldedSeo} treats as \"no SEO\" - identical to\n * the prior LEFT JOIN miss behavior.\n *\n * Dialect-specific aggregation mirrors {@link foldedHydrationSelects}: SQLite\n * `json_object` returns a JSON *string*, Postgres `json_build_object` returns\n * parsed JSON; both branches are handled in expansion.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any Kysely instance\nfunction foldedSeoSelect(db: Kysely<any>, type: string, outer: string) {\n\tconst o = sql.ref(outer);\n\tconst pg = isPostgres(db);\n\t// Use raw column names (not aliases) as JSON keys: the JSON is expanded back\n\t// onto SEO_COLUMN_ALIASES in JS, and keeping the keys matched to the\n\t// underlying columns makes the SQL readable and the expansion 1-to-1.\n\tconst pairs =\n\t\t\"'seo_title', s.seo_title, 'seo_description', s.seo_description, 'seo_image', s.seo_image, 'seo_canonical', s.seo_canonical, 'seo_no_index', s.seo_no_index\";\n\tconst obj = pg ? sql.raw(`json_build_object(${pairs})`) : sql.raw(`json_object(${pairs})`);\n\treturn sql`(SELECT ${obj} FROM ${sql.ref(\"_emdash_seo\")} AS s WHERE s.collection = ${type} AND s.content_id = ${o}.id LIMIT 1) AS ${sql.ref(SEO_FOLDED_COLUMN)}`;\n}\n\n/**\n * Expand the folded `_emdash_seo` JSON column onto the row using SEO_COLUMN_ALIASES,\n * so {@link extractSeo} reads it transparently. SQLite returns a JSON string\n * (parse it); Postgres returns already-parsed JSON. Missing/malformed/null is\n * a no-op: {@link extractSeo} returns null when the aliases are absent.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction expandFoldedSeo(row: Record<string, unknown>): void {\n\tconst raw = row[SEO_FOLDED_COLUMN];\n\tdelete row[SEO_FOLDED_COLUMN];\n\tlet parsed: Record<string, unknown> | null = null;\n\tif (typeof raw === \"string\") {\n\t\ttry {\n\t\t\tconst candidate: unknown = JSON.parse(raw);\n\t\t\tif (isPlainObject(candidate)) parsed = candidate;\n\t\t} catch {\n\t\t\treturn; // malformed JSON: leave the row without SEO aliases (extractSeo returns null)\n\t\t}\n\t} else if (isPlainObject(raw)) {\n\t\tparsed = raw;\n\t}\n\tif (!parsed) return;\n\tfor (const [col, alias] of Object.entries(SEO_COLUMN_ALIASES)) {\n\t\trow[alias] = parsed[col] ?? null;\n\t}\n}\n\nexport function creditsFromFoldedBylines(folded: unknown[]) {\n\treturn folded\n\t\t.map((raw) => {\n\t\t\tconst credit = isPlainObject(raw) ? raw : {};\n\t\t\tconst byline = isPlainObject(credit.byline) ? credit.byline : {};\n\t\t\treturn {\n\t\t\t\troleLabel: typeof credit.roleLabel === \"string\" ? credit.roleLabel : null,\n\t\t\t\tsortOrder: Number(credit.sortOrder ?? 0),\n\t\t\t\tsource: \"explicit\" as const,\n\t\t\t\tbyline: {\n\t\t\t\t\t...byline,\n\t\t\t\t\tisGuest: Boolean(byline.isGuest),\n\t\t\t\t\t// Folded rows omit custom-field values.\n\t\t\t\t\tcustomFields: {},\n\t\t\t\t},\n\t\t\t};\n\t\t})\n\t\t.toSorted((a, b) => a.sortOrder - b.sortOrder);\n}\n\n/**\n * Stash folded hydration JSON (non-enumerable) for the query.ts fast paths.\n * SQLite returns a JSON string (parse it); Postgres returns already-parsed JSON.\n */\nfunction stashFolded(data: Record<string, unknown>, row: Record<string, unknown>): void {\n\tfor (const [col, sym] of [\n\t\t[\"_emdash_terms\", FOLDED_TERMS],\n\t\t[\"_emdash_bylines\", FOLDED_BYLINES],\n\t] as const) {\n\t\tconst raw = row[col];\n\t\tlet value: unknown;\n\t\tif (typeof raw === \"string\") {\n\t\t\ttry {\n\t\t\t\tvalue = JSON.parse(raw);\n\t\t\t} catch {\n\t\t\t\tcontinue; // malformed: fall back to the query path\n\t\t\t}\n\t\t} else if (Array.isArray(raw)) {\n\t\t\tvalue = raw; // Postgres json/jsonb already parsed by the driver\n\t\t} else {\n\t\t\tcontinue;\n\t\t}\n\t\tObject.defineProperty(data, sym, { value, enumerable: false, configurable: true });\n\t}\n\t// Existence probe: 1 = table has rows, NULL = empty (both dialects). A row\n\t// without the column (e.g. a cached snapshot) leaves the marker unset,\n\t// which hydration treats as \"unknown\" and falls back conservatively.\n\tif (\"_emdash_bylines_exist\" in row) {\n\t\tObject.defineProperty(data, FOLDED_BYLINES_EXIST, {\n\t\t\tvalue: row[\"_emdash_bylines_exist\"] != null,\n\t\t\tenumerable: false,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\n\tconst foldedBylines = Reflect.get(data, FOLDED_BYLINES);\n\tif (!Array.isArray(foldedBylines)) return;\n\tconst credits = creditsFromFoldedBylines(foldedBylines);\n\tdata.bylines = credits;\n\tdata.byline = credits[0]?.byline ?? null;\n}\n\n/** Resolved SEO shape attached to `entry.data.seo`. Mirrors `ContentSeo`. */\ninterface EntrySeo {\n\ttitle: string | null;\n\tdescription: string | null;\n\timage: string | null;\n\tcanonical: string | null;\n\tnoIndex: boolean;\n}\n\n/**\n * Build a `data.seo` object from the joined `_emdash_seo` columns on a row.\n *\n * Returns `null` when no SEO row exists (LEFT JOIN miss → `seo_no_index` is\n * NULL, since the column is `NOT NULL DEFAULT 0` whenever a row is present).\n * Returning null keeps the `seo` key off entries that have none, so\n * `getSeoMeta()` falls back to its defaults exactly as before.\n */\nfunction extractSeo(row: Record<string, unknown>): EntrySeo | null {\n\tconst noIndex = row[SEO_COLUMN_ALIASES.seo_no_index];\n\tif (noIndex === null || noIndex === undefined) return null;\n\tconst title = row[SEO_COLUMN_ALIASES.seo_title];\n\tconst description = row[SEO_COLUMN_ALIASES.seo_description];\n\tconst image = row[SEO_COLUMN_ALIASES.seo_image];\n\tconst canonical = row[SEO_COLUMN_ALIASES.seo_canonical];\n\treturn {\n\t\ttitle: typeof title === \"string\" ? title : null,\n\t\tdescription: typeof description === \"string\" ? description : null,\n\t\timage: typeof image === \"string\" ? image : null,\n\t\tcanonical: typeof canonical === \"string\" ? canonical : null,\n\t\tnoIndex: noIndex === 1,\n\t};\n}\n\n/**\n * Get the table name for a collection type\n */\nfunction getTableName(type: string): string {\n\tvalidateIdentifier(type, \"collection type\");\n\treturn `ec_${type}`;\n}\n\n/**\n * Cache for taxonomy names by collection (only used for the primary database).\n * Stored on globalThis so Vite SSR chunk duplication cannot create independent\n * caches. Skipped when a per-request DB override is active (e.g. preview mode)\n * because the override DB may have different taxonomies.\n */\ninterface TaxonomyNamesHolder {\n\tcache: Map<string, Set<string>> | null;\n}\n\nconst TAXONOMY_NAMES_CACHE_KEY = Symbol.for(\"emdash:taxonomy-names\");\nconst taxonomyNamesStore = globalThis as Record<symbol, unknown>;\nconst taxonomyNamesHolder: TaxonomyNamesHolder =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see taxonomies/index.ts)\n\t(taxonomyNamesStore[TAXONOMY_NAMES_CACHE_KEY] as TaxonomyNamesHolder | undefined) ??\n\t(() => {\n\t\tconst holder: TaxonomyNamesHolder = { cache: null };\n\t\ttaxonomyNamesStore[TAXONOMY_NAMES_CACHE_KEY] = holder;\n\t\treturn holder;\n\t})();\n\nfunction setTaxonomyNamesCache(cache: Map<string, Set<string>> | null): void {\n\ttaxonomyNamesHolder.cache = cache;\n}\n\n/**\n * Get taxonomy names attached to a collection (cached for the primary DB,\n * bypassed only when the per-request DB is an isolated instance — playground /\n * DO preview). Plain D1 Sessions routing shares schema with the singleton, so\n * the isolate-wide cache stays valid.\n */\nasync function getTaxonomyNames(db: Kysely<Database>, collection: string): Promise<Set<string>> {\n\tconst hasIsolatedDb = getRequestContext()?.dbIsIsolated === true;\n\n\tif (!hasIsolatedDb && taxonomyNamesHolder.cache) {\n\t\treturn taxonomyNamesHolder.cache.get(collection) ?? new Set();\n\t}\n\n\ttry {\n\t\tconst defs = await db\n\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t.select([\"name\", \"collections\"])\n\t\t\t.execute();\n\t\tconst namesByCollection = new Map<string, Set<string>>();\n\t\tfor (const def of defs) {\n\t\t\tlet collections: unknown;\n\t\t\ttry {\n\t\t\t\tcollections = JSON.parse(def.collections ?? \"[]\");\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!Array.isArray(collections)) continue;\n\t\t\tfor (const attachedCollection of collections) {\n\t\t\t\tif (typeof attachedCollection !== \"string\") continue;\n\t\t\t\tconst names = namesByCollection.get(attachedCollection) ?? new Set<string>();\n\t\t\t\tnames.add(def.name);\n\t\t\t\tnamesByCollection.set(attachedCollection, names);\n\t\t\t}\n\t\t}\n\t\tif (!hasIsolatedDb) {\n\t\t\tsetTaxonomyNamesCache(namesByCollection);\n\t\t}\n\t\treturn namesByCollection.get(collection) ?? new Set();\n\t} catch (error) {\n\t\tif (!isMissingTableError(error) && !isMissingColumnError(error)) throw error;\n\n\t\tconst empty = new Set<string>();\n\t\tif (!hasIsolatedDb) {\n\t\t\tsetTaxonomyNamesCache(new Map());\n\t\t}\n\t\treturn empty;\n\t}\n}\n\n/**\n * Reset the isolate-wide taxonomy-names cache.\n *\n * Called from `invalidateTaxonomyDefsCache()` so that creating or seeding a\n * taxonomy definition is reflected within the current isolate instead of\n * waiting for the isolate to recycle. Keeps this cache consistent with the\n * isolate-wide taxonomy-defs cache in `taxonomies/index.ts`.\n */\nexport function resetTaxonomyNamesCache(): void {\n\tsetTaxonomyNamesCache(null);\n}\n\n/**\n * System columns to include in data (mapped to camelCase where needed)\n */\nconst INCLUDE_IN_DATA: Record<string, string> = {\n\tid: \"id\",\n\tstatus: \"status\",\n\tauthor_id: \"authorId\",\n\tprimary_byline_id: \"primaryBylineId\",\n\tcreated_at: \"createdAt\",\n\tupdated_at: \"updatedAt\",\n\tpublished_at: \"publishedAt\",\n\tscheduled_at: \"scheduledAt\",\n\tdraft_revision_id: \"draftRevisionId\",\n\tlive_revision_id: \"liveRevisionId\",\n\tlocale: \"locale\",\n\ttranslation_group: \"translationGroup\",\n};\n\n/** System date columns that should be converted to Date objects */\nconst DATE_COLUMNS = new Set([\"created_at\", \"updated_at\", \"published_at\", \"scheduled_at\"]);\n\n/**\n * Hidden, symbol-keyed property on each mapped data record carrying the raw\n * DB string for every date column. Lets cursor encoders downstream reproduce\n * the loader's exact `nextCursor` format without round-tripping through\n * `new Date()`, which loses precision for stored values that aren't already\n * ISO-with-milliseconds (e.g. `2026-01-01T00:00:00Z` becomes\n * `2026-01-01T00:00:00.000Z`).\n */\nexport const CURSOR_RAW_VALUES: unique symbol = Symbol(\"emdash:cursorRawValues\");\n\nconst LOCAL_MEDIA_FILE_PREFIX = \"/_emdash/api/media/file/\";\nconst URL_SCHEME_PATTERN = /^[a-zA-Z][a-zA-Z\\d+\\-.]*:/;\n\n/** Safely extract a string value from a record, returning fallback if not a string */\nfunction rowStr(row: Record<string, unknown>, key: string, fallback = \"\"): string {\n\tconst val = row[key];\n\treturn typeof val === \"string\" ? val : fallback;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isBareMediaKey(src: string): boolean {\n\treturn !src.startsWith(\"/\") && !URL_SCHEME_PATTERN.test(src);\n}\n\nfunction normalizeLocalMediaValue(value: unknown): unknown {\n\tif (Array.isArray(value)) {\n\t\treturn value.map(normalizeLocalMediaValue);\n\t}\n\n\tif (!isRecord(value)) {\n\t\treturn value;\n\t}\n\n\tconst normalized: Record<string, unknown> = {};\n\tfor (const [key, child] of Object.entries(value)) {\n\t\tnormalized[key] = normalizeLocalMediaValue(child);\n\t}\n\n\tif (\n\t\tnormalized.provider === \"local\" &&\n\t\ttypeof normalized.src === \"string\" &&\n\t\tnormalized.src.length > 0\n\t) {\n\t\tconst src = normalized.src;\n\t\tif (src.startsWith(LOCAL_MEDIA_FILE_PREFIX)) {\n\t\t\tconst id = src.slice(LOCAL_MEDIA_FILE_PREFIX.length);\n\t\t\tif (!normalized.id && id) {\n\t\t\t\tnormalized.id = id;\n\t\t\t}\n\t\t} else if (isBareMediaKey(src)) {\n\t\t\tif (!normalized.id) {\n\t\t\t\tnormalized.id = src;\n\t\t\t}\n\t\t\tnormalized.src = `${LOCAL_MEDIA_FILE_PREFIX}${src}`;\n\t\t}\n\t}\n\n\treturn normalized;\n}\n\n/**\n * Map a database row to entry data\n * Extracts content fields (non-system columns) and parses JSON where needed.\n * System columns needed for templates (id, status, dates) are included with camelCase names.\n */\nfunction mapRowToData(row: Record<string, unknown>): Record<string, unknown> {\n\tconst data: Record<string, unknown> = {};\n\tconst rawDateValues: Record<string, string> = {};\n\n\tfor (const [key, value] of Object.entries(row)) {\n\t\t// Include certain system columns (mapped to camelCase where needed)\n\t\tif (key in INCLUDE_IN_DATA) {\n\t\t\t// Convert date columns from ISO strings to Date objects\n\t\t\tif (DATE_COLUMNS.has(key)) {\n\t\t\t\tif (typeof value === \"string\") {\n\t\t\t\t\trawDateValues[key] = value;\n\t\t\t\t\tdata[INCLUDE_IN_DATA[key]] = new Date(value);\n\t\t\t\t} else {\n\t\t\t\t\tdata[INCLUDE_IN_DATA[key]] = null;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdata[INCLUDE_IN_DATA[key]] = value;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (SYSTEM_COLUMNS.has(key)) continue;\n\n\t\t// Try to parse JSON strings (for portableText, json fields, etc.)\n\t\tif (typeof value === \"string\") {\n\t\t\ttry {\n\t\t\t\t// Only parse if it looks like JSON (starts with { or [)\n\t\t\t\tif (value.startsWith(\"{\") || value.startsWith(\"[\")) {\n\t\t\t\t\tdata[key] = normalizeLocalMediaValue(JSON.parse(value));\n\t\t\t\t} else {\n\t\t\t\t\tdata[key] = value;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\tdata[key] = value;\n\t\t\t}\n\t\t} else {\n\t\t\tdata[key] = value;\n\t\t}\n\t}\n\n\tObject.defineProperty(data, CURSOR_RAW_VALUES, {\n\t\tvalue: rawDateValues,\n\t\tenumerable: false,\n\t\tconfigurable: false,\n\t\twritable: false,\n\t});\n\n\treturn data;\n}\n\n/**\n * Map revision data (already-parsed JSON object) to entry data.\n * Strips _-prefixed metadata keys (e.g. _slug) used internally by revisions.\n */\nfunction mapRevisionData(data: Record<string, unknown>): Record<string, unknown> {\n\tconst result: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(data)) {\n\t\tif (key.startsWith(\"_\")) continue; // revision metadata\n\t\tresult[key] = normalizeLocalMediaValue(value);\n\t}\n\treturn result;\n}\n\n// Virtual module imports are lazy-loaded to avoid errors when importing\n// emdash outside of Astro/Vite context (e.g., in astro.config.mjs)\nlet virtualConfig:\n\t| {\n\t\t\tdatabase?: { config: unknown };\n\t\t\ti18n?: { defaultLocale: string; locales: string[]; prefixDefaultLocale?: boolean } | null;\n\t }\n\t| undefined;\nlet virtualCreateDialect: ((config: unknown) => Dialect) | undefined;\n\nasync function loadVirtualModules() {\n\tif (virtualConfig === undefined) {\n\t\t// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n\t\t// @ts-ignore - virtual module\n\t\tconst configModule = await import(\"virtual:emdash/config\");\n\t\tvirtualConfig = configModule.default;\n\t}\n\tif (virtualCreateDialect === undefined) {\n\t\t// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n\t\t// @ts-ignore - virtual module\n\t\tconst dialectModule = await import(\"virtual:emdash/dialect\");\n\t\tvirtualCreateDialect = dialectModule.createDialect;\n\t\t// dialectType is no longer needed here — dialect detection is\n\t\t// done via the db adapter instance in dialect-helpers.ts\n\t}\n}\n\n/**\n * Entry data type - generic object\n */\nexport type EntryData = Record<string, unknown>;\n\n/**\n * Sort direction\n */\nexport type SortDirection = \"asc\" | \"desc\";\n\n/**\n * Order by specification - field name to direction\n * @example { created_at: \"desc\" } - Sort by created_at descending\n * @example { title: \"asc\" } - Sort by title ascending\n */\nexport type OrderBySpec = Record<string, SortDirection>;\n\n/**\n * Resolved primary sort field and direction (used for cursor pagination).\n */\ninterface PrimarySort {\n\tfield: string;\n\tdirection: SortDirection;\n}\n\n/**\n * Get the primary sort field from an orderBy spec (first valid field, or default).\n */\nfunction getPrimarySort(orderBy: OrderBySpec | undefined, tablePrefix?: string): PrimarySort {\n\tif (orderBy) {\n\t\tfor (const [field, direction] of Object.entries(orderBy)) {\n\t\t\tif (FIELD_NAME_PATTERN.test(field)) {\n\t\t\t\tconst fullField = tablePrefix ? `${tablePrefix}.${field}` : field;\n\t\t\t\treturn { field: fullField, direction };\n\t\t\t}\n\t\t}\n\t}\n\tconst defaultField = tablePrefix ? `${tablePrefix}.created_at` : \"created_at\";\n\treturn { field: defaultField, direction: \"desc\" };\n}\n\n/**\n * Build ORDER BY clause from orderBy spec\n * Validates field names to prevent SQL injection (alphanumeric + underscore only)\n * Supports multiple sort fields in object key order\n */\nfunction buildOrderByClause(\n\torderBy: OrderBySpec | undefined,\n\ttablePrefix?: string,\n): ReturnType<typeof sql> {\n\t// Default to created_at DESC\n\tif (!orderBy || Object.keys(orderBy).length === 0) {\n\t\tconst field = tablePrefix ? `${tablePrefix}.created_at` : \"created_at\";\n\t\treturn sql`ORDER BY ${sql.ref(field)} DESC, ${sql.ref(tablePrefix ? `${tablePrefix}.id` : \"id\")} DESC`;\n\t}\n\n\tconst sortParts: ReturnType<typeof sql>[] = [];\n\n\tfor (const [field, direction] of Object.entries(orderBy)) {\n\t\t// Validate field name (alphanumeric + underscore only)\n\t\tif (!FIELD_NAME_PATTERN.test(field)) {\n\t\t\tcontinue; // Skip invalid field names\n\t\t}\n\n\t\tconst fullField = tablePrefix ? `${tablePrefix}.${field}` : field;\n\t\tconst dir = direction === \"asc\" ? sql`ASC` : sql`DESC`;\n\t\tsortParts.push(sql`${sql.ref(fullField)} ${dir}`);\n\t}\n\n\t// If no valid sort fields, fall back to default\n\tif (sortParts.length === 0) {\n\t\tconst defaultField = tablePrefix ? `${tablePrefix}.created_at` : \"created_at\";\n\t\treturn sql`ORDER BY ${sql.ref(defaultField)} DESC, ${sql.ref(tablePrefix ? `${tablePrefix}.id` : \"id\")} DESC`;\n\t}\n\n\t// Add id as tiebreaker to ensure stable cursor ordering\n\tconst primary = getPrimarySort(orderBy, tablePrefix);\n\tconst idField = tablePrefix ? `${tablePrefix}.id` : \"id\";\n\tconst idDir = primary.direction === \"asc\" ? sql`ASC` : sql`DESC`;\n\tsortParts.push(sql`${sql.ref(idField)} ${idDir}`);\n\n\treturn sql`ORDER BY ${sql.join(sortParts, sql`, `)}`;\n}\n\n/**\n * Build a cursor WHERE condition for keyset pagination.\n * Uses the primary sort field + id as tiebreaker for stable ordering.\n *\n * Throws `InvalidCursorError` if the cursor is malformed; callers should\n * let this propagate so users see a real error rather than silently\n * falling back to the first page.\n */\nfunction buildCursorCondition(\n\tcursor: string,\n\torderBy: OrderBySpec | undefined,\n\ttablePrefix?: string,\n): ReturnType<typeof sql> {\n\tconst { orderValue, id: cursorId } = decodeCursor(cursor);\n\tconst primary = getPrimarySort(orderBy, tablePrefix);\n\tconst idField = tablePrefix ? `${tablePrefix}.id` : \"id\";\n\n\tif (primary.direction === \"desc\") {\n\t\treturn sql`(${sql.ref(primary.field)} < ${orderValue} OR (${sql.ref(primary.field)} = ${orderValue} AND ${sql.ref(idField)} < ${cursorId}))`;\n\t}\n\treturn sql`(${sql.ref(primary.field)} > ${orderValue} OR (${sql.ref(primary.field)} = ${orderValue} AND ${sql.ref(idField)} > ${cursorId}))`;\n}\n\n/** Type guard: is the where value a range object (not a string or array)? */\nfunction isWhereRange(value: WhereValue): value is WhereRange {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Build AND conditions for non-taxonomy field filters.\n * Returns an array of sql fragments; empty if no field filters apply.\n * Field names are validated against FIELD_NAME_PATTERN to prevent injection.\n */\nfunction buildFieldConditions(\n\tfields: Record<string, WhereValue>,\n\ttablePrefix?: string,\n): ReturnType<typeof sql>[] {\n\tconst conditions: ReturnType<typeof sql>[] = [];\n\n\tfor (const [key, value] of Object.entries(fields)) {\n\t\tif (!FIELD_NAME_PATTERN.test(key)) {\n\t\t\tconsole.warn(`[emdash] where filter: invalid field name \"${key}\" ignored`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (value == null) continue;\n\t\tconst ref = tablePrefix ? sql.ref(`${tablePrefix}.${key}`) : sql.ref(key);\n\n\t\tif (isWhereRange(value)) {\n\t\t\tif (value.gt !== undefined) conditions.push(sql`${ref} > ${value.gt}`);\n\t\t\tif (value.gte !== undefined) conditions.push(sql`${ref} >= ${value.gte}`);\n\t\t\tif (value.lt !== undefined) conditions.push(sql`${ref} < ${value.lt}`);\n\t\t\tif (value.lte !== undefined) conditions.push(sql`${ref} <= ${value.lte}`);\n\t\t} else if (Array.isArray(value)) {\n\t\t\tif (value.length > 0) {\n\t\t\t\tconditions.push(sql`${ref} IN (${sql.join(value.map((v) => sql`${v}`))})`);\n\t\t\t}\n\t\t} else {\n\t\t\tconditions.push(sql`${ref} = ${value}`);\n\t\t}\n\t}\n\n\treturn conditions;\n}\n\n/**\n * Resolve a taxonomy filter (`name` + one or more `slug`s, optionally scoped to\n * `locale`) to the set of `translation_group`s the pivot stores in\n * `content_taxonomies.taxonomy_id`. Exact terms only — no subtree expansion.\n *\n * Mirrors the meaning of the old EXISTS join (`t.name = ? AND t.slug IN (?)\n * [AND t.locale = ?]`): a pivot row matches when its group has a term with that\n * name/slug in the active locale. Resolving to explicit values (rather than an\n * `IN (subquery)`) keeps the single-term case a plain equality on the pivot\n * index, which is what gives the clean early-`LIMIT` seek.\n */\nasync function resolveTermGroups(\n\tdb: Kysely<Database>,\n\tname: string,\n\tslugs: string[],\n\tlocale: string | undefined,\n): Promise<string[]> {\n\tlet query = db\n\t\t.selectFrom(\"taxonomies\")\n\t\t.select(\"translation_group\")\n\t\t.distinct()\n\t\t.where(\"name\", \"=\", name)\n\t\t.where(\"slug\", \"in\", slugs);\n\tif (locale) query = query.where(\"locale\", \"=\", locale);\n\tconst rows = await query.execute();\n\tconst groups = new Set<string>();\n\tfor (const row of rows) {\n\t\tif (row.translation_group) groups.add(row.translation_group);\n\t}\n\treturn [...groups];\n}\n\n/** Equality (single) or `IN` (multiple) condition on a pivot group column. */\nfunction pivotGroupCondition(ref: string, groups: string[]): ReturnType<typeof sql> {\n\tif (groups.length === 1) return sql`${sql.ref(ref)} = ${groups[0]}`;\n\treturn sql`${sql.ref(ref)} IN (${sql.join(groups.map((g) => sql`${g}`))})`;\n}\n\n/** LIMIT/OFFSET fragment matching the loader's single-table variant. */\nfunction buildPivotLimitOffset(\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any Kysely instance\n\tdb: Kysely<any>,\n\tfetchLimit: number | undefined,\n\toffset: number | undefined,\n): ReturnType<typeof sql> {\n\tif (fetchLimit != null && offset != null) return sql`LIMIT ${fetchLimit} OFFSET ${offset}`;\n\tif (fetchLimit != null) return sql`LIMIT ${fetchLimit}`;\n\tif (offset != null) {\n\t\treturn isPostgres(db) ? sql`OFFSET ${offset}` : sql`LIMIT -1 OFFSET ${offset}`;\n\t}\n\treturn sql``;\n}\n\n/**\n * Options for {@link buildTaxonomyPivotQuery}.\n *\n * Parameterized on the `deletedIsNull` predicate and `status` condition so the\n * same builder serves the public live path (`deleted_at IS NULL` + published)\n * and, without any schema change, an admin trash (`deleted_at IS NOT\n * NULL`) or all-statuses shape. Admin wiring is out of scope today; the\n * parameters exist so `ContentRepository` can adopt this if it gains taxonomy\n * filtering.\n */\nexport interface TaxonomyPivotQueryOptions {\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any Kysely instance\n\tdb: Kysely<any>;\n\t/** Collection slug (pivot `collection` value). */\n\tcollection: string;\n\t/** Content table name (`ec_<collection>`). */\n\ttableName: string;\n\t/**\n\t * Resolved translation_group sets, one per taxonomy filter. The first drives\n\t * the pivot seek; each additional set becomes a residual `EXISTS` (AND across\n\t * taxonomies). Multiple groups within a set are OR'd (dedup via GROUP BY).\n\t */\n\tgroupSets: string[][];\n\torderBy: OrderBySpec | undefined;\n\tcursor: string | undefined;\n\tlocale: string | undefined;\n\t/**\n\t * Status shape. A concrete value (`published`/`draft`/…) applies the same\n\t * condition `buildStatusCondition` produces (public: published only).\n\t * `undefined` drops the status filter entirely — the admin all-statuses shape.\n\t */\n\tstatus: string | undefined;\n\t/** `true` → `deleted_at IS NULL` (live); `false` → `IS NOT NULL` (trash). */\n\tdeletedIsNull: boolean;\n\t/** Byline translation_groups for an AND'd byline filter, or `null`. */\n\tbylineGroups: string[] | null;\n\tfetchLimit: number | undefined;\n\toffset: number | undefined;\n}\n\n/**\n * Build the pivot-driven taxonomy listing query (#1834).\n *\n * Drives from the term pivot and joins content translations through their\n * shared translation_group. Content columns remain authoritative for locale,\n * visibility, sorting, and cursor predicates.\n *\n * Two shapes:\n * - **Indexed sort** (`published_at`/`created_at`, single sort field): the\n * `LIMIT` lives in `picked`.\n * - **Temp-sort** (`updated_at` or any other field, or multi-field sort): no\n * pivot sort index applies, so `picked` collects the tagged candidate set and\n * the outer query sorts the joined rows. Bounded to tagged rows — no\n * `ec_*` full scan — but no early-`LIMIT`.\n */\nexport function buildTaxonomyPivotQuery(\n\topts: TaxonomyPivotQueryOptions,\n): ReturnType<typeof sql<Record<string, unknown>>> {\n\tconst {\n\t\tdb,\n\t\tcollection,\n\t\ttableName,\n\t\tgroupSets,\n\t\torderBy,\n\t\tcursor,\n\t\tlocale,\n\t\tstatus,\n\t\tdeletedIsNull,\n\t\tbylineGroups,\n\t\tfetchLimit,\n\t\toffset,\n\t} = opts;\n\n\tconst primary = getPrimarySort(orderBy);\n\tconst validSortKeys = orderBy\n\t\t? Object.keys(orderBy).filter((k) => FIELD_NAME_PATTERN.test(k))\n\t\t: [];\n\tconst singleSort = validSortKeys.length <= 1;\n\tconst isIndexedSort =\n\t\tsingleSort && (primary.field === \"published_at\" || primary.field === \"created_at\");\n\tconst dir = primary.direction === \"asc\" ? sql`ASC` : sql`DESC`;\n\tconst cmp = primary.direction === \"asc\" ? sql.raw(\">\") : sql.raw(\"<\");\n\n\tconst firstGroups = groupSets[0] ?? [];\n\tconst restGroups = groupSets.slice(1);\n\tconst multiGroup = firstGroups.length > 1;\n\n\t// Multi-term AND: one residual pivot-PK EXISTS per additional taxonomy.\n\tconst residual =\n\t\trestGroups.length > 0\n\t\t\t? sql`${sql.join(\n\t\t\t\t\trestGroups.map(\n\t\t\t\t\t\t(g) => sql`AND EXISTS (\n\t\t\t\t\t\tSELECT 1 FROM content_taxonomies ct2\n\t\t\t\t\t\tWHERE ct2.collection = ${collection}\n\t\t\t\t\t\t\tAND ct2.entry_id = ct.entry_id\n\t\t\t\t\t\t\tAND ${pivotGroupCondition(\"ct2.taxonomy_id\", g)}\n\t\t\t\t\t)`,\n\t\t\t\t\t),\n\t\t\t\t\tsql` `,\n\t\t\t\t)}`\n\t\t\t: sql``;\n\n\t// Byline assignments remain keyed to a locale-specific content row.\n\tconst bylineCt = bylineGroups\n\t\t? sql`AND EXISTS (\n\t\t\t\tSELECT 1 FROM _emdash_content_bylines cb\n\t\t\t\tWHERE cb.collection_slug = ${collection}\n\t\t\t\t\tAND cb.content_id = r.id\n\t\t\t\t\tAND cb.byline_id IN (${sql.join(bylineGroups.map((g) => sql`${g}`))})\n\t\t\t)`\n\t\t: sql``;\n\n\tconst firstGroupCond = pivotGroupCondition(\"ct.taxonomy_id\", firstGroups);\n\tconst pivotContentJoin = isPostgres(db) ? sql`JOIN` : sql`CROSS JOIN`;\n\tconst {\n\t\tterms: termsSelect,\n\t\tbylines: bylinesSelect,\n\t\tbylinesExist: bylinesExistSelect,\n\t} = foldedHydrationSelects(db, collection, \"r\");\n\n\t// Authoritative re-check on the joined `ec_*` row.\n\tconst deletedR = deletedIsNull ? sql`r.deleted_at IS NULL` : sql`r.deleted_at IS NOT NULL`;\n\tconst statusR = status !== undefined ? sql`AND ${buildStatusCondition(db, status, \"r\")}` : sql``;\n\tconst localeR = locale ? sql`AND r.locale = ${locale}` : sql``;\n\n\tif (isIndexedSort) {\n\t\tconst sortRef = sql.ref(`r.${primary.field}`);\n\t\tconst sortval = multiGroup ? sql`MAX(${sortRef})` : sortRef;\n\t\tconst groupByClause = multiGroup ? sql`GROUP BY r.id` : sql``;\n\n\t\tlet cursorClause = sql``;\n\t\tlet havingClause = sql``;\n\t\tif (cursor) {\n\t\t\tconst { orderValue, id } = decodeCursor(cursor);\n\t\t\tconst cond = sql`(${sortval} ${cmp} ${orderValue} OR (${sortval} = ${orderValue} AND r.id ${cmp} ${id}))`;\n\t\t\t// A GROUP BY makes `sortval` an aggregate → cursor goes in HAVING.\n\t\t\tif (multiGroup) havingClause = sql`HAVING ${cond}`;\n\t\t\telse cursorClause = sql`AND ${cond}`;\n\t\t}\n\n\t\tconst limitClause = buildPivotLimitOffset(db, fetchLimit, offset);\n\n\t\treturn sql<Record<string, unknown>>`\n\t\t\tWITH picked AS (\n\t\t\t\tSELECT r.id AS entry_id, ${sortval} AS sortval\n\t\t\t\tFROM content_taxonomies ct\n\t\t\t\t${pivotContentJoin} ${sql.ref(tableName)} AS r ON r.translation_group = ct.entry_id\n\t\t\t\tWHERE ct.collection = ${collection}\n\t\t\t\t\tAND ${firstGroupCond}\n\t\t\t\t\tAND ${deletedR}\n\t\t\t\t\t${statusR}\n\t\t\t\t\t${localeR}\n\t\t\t\t\t${residual}\n\t\t\t\t\t${bylineCt}\n\t\t\t\t\t${cursorClause}\n\t\t\t\t${groupByClause}\n\t\t\t\t${havingClause}\n\t\t\t\tORDER BY sortval ${dir}, r.id ${dir}\n\t\t\t\t${limitClause}\n\t\t\t)\n\t\t\tSELECT r.*, ${termsSelect}, ${bylinesSelect}, ${bylinesExistSelect}\n\t\t\tFROM picked JOIN ${sql.ref(tableName)} AS r ON r.id = picked.entry_id\n\t\t\tWHERE ${deletedR} ${statusR} ${localeR}\n\t\t\tORDER BY picked.sortval ${dir}, picked.entry_id ${dir}\n\t\t`;\n\t}\n\n\t// Temp-sort path: seek the term via the pivot, sort the joined candidate set.\n\tconst orderByClause = buildOrderByClause(orderBy, \"r\");\n\tconst cursorCond = cursor ? sql`AND ${buildCursorCondition(cursor, orderBy, \"r\")}` : sql``;\n\tconst limitClause = buildPivotLimitOffset(db, fetchLimit, offset);\n\treturn sql<Record<string, unknown>>`\n\t\tWITH picked AS (\n\t\t\tSELECT DISTINCT r.id AS entry_id\n\t\t\tFROM content_taxonomies ct\n\t\t\t${pivotContentJoin} ${sql.ref(tableName)} AS r ON r.translation_group = ct.entry_id\n\t\t\tWHERE ct.collection = ${collection}\n\t\t\t\tAND ${firstGroupCond}\n\t\t\t\tAND ${deletedR}\n\t\t\t\t${statusR}\n\t\t\t\t${localeR}\n\t\t\t\t${residual}\n\t\t\t\t${bylineCt}\n\t\t)\n\t\tSELECT r.*, ${termsSelect}, ${bylinesSelect}, ${bylinesExistSelect}\n\t\tFROM picked JOIN ${sql.ref(tableName)} AS r ON r.id = picked.entry_id\n\t\tWHERE ${deletedR} ${statusR} ${localeR}\n\t\t\t${cursorCond}\n\t\t${orderByClause}\n\t\t${limitClause}\n\t`;\n}\n\n/**\n * Range filter for comparison operators on field values.\n * Values are compared as strings in the database. This works correctly for\n * ISO 8601 dates (e.g. \"2024-01-01T00:00:00Z\") because lexicographic ordering\n * matches chronological ordering. Ensure date values use a consistent format.\n */\nexport interface WhereRange {\n\tgt?: string;\n\tgte?: string;\n\tlt?: string;\n\tlte?: string;\n}\n\n/**\n * A where clause value: exact match, multi-value match, or range comparison.\n */\nexport type WhereValue = string | string[] | WhereRange;\n\n/**\n * Fields shared by every collection filter, independent of pagination mode.\n *\n * Cursor and offset pagination are mutually exclusive, so they live on the\n * `CursorCollectionFilter` / `OffsetCollectionFilter` variants rather than\n * here. Use the {@link CollectionFilter} union for any value that may be\n * either.\n */\nexport interface CollectionFilterBase {\n\ttype: string;\n\tstatus?: \"draft\" | \"published\" | \"archived\";\n\tlimit?: number;\n\t/**\n\t * Filter by field values, taxonomy terms, byline credits, or ranges.\n\t *\n\t * Taxonomy names are detected automatically and filtered via JOIN.\n\t * The reserved `byline` key filters by byline credit (any credit, not\n\t * just the primary one) via the `_emdash_content_bylines` junction\n\t * table; its value is one or more byline translation groups.\n\t * Other keys are treated as column filters on the content table.\n\t *\n\t * @example { category: 'news' } - taxonomy term\n\t * @example { byline: '01HXYZ...' } - entries credited to a byline (any position)\n\t * @example { series: 'main' } - exact match on a content field\n\t * @example { published_at: { gte: '2024-01-01', lt: '2025-01-01' } } - date range\n\t */\n\twhere?: Record<string, WhereValue>;\n\t/**\n\t * Order results by field(s)\n\t * @default { created_at: \"desc\" }\n\t */\n\torderBy?: OrderBySpec;\n\t/**\n\t * Filter by locale (e.g. 'en', 'fr').\n\t * When set, only returns content in this locale.\n\t */\n\tlocale?: string;\n}\n\n/** Keyset-paginated collection filter. Cannot also carry an `offset`. */\nexport interface CursorCollectionFilter extends CollectionFilterBase {\n\t/**\n\t * Opaque cursor for keyset pagination.\n\t * Pass the `nextCursor` value from a previous result to fetch the next page.\n\t */\n\tcursor?: string;\n\toffset?: never;\n}\n\n/** Offset-paginated collection filter. Cannot also carry a `cursor`. */\nexport interface OffsetCollectionFilter extends CollectionFilterBase {\n\t/**\n\t * Skip this many rows before returning results (offset pagination).\n\t * Use with `limit` for numbered archive routes (`/page/2`):\n\t * `offset = (page - 1) * perPage`. Ignored unless it is a positive\n\t * integer.\n\t */\n\toffset?: number;\n\tcursor?: never;\n}\n\n/**\n * Filter for loadCollection - type is required.\n *\n * A union of the cursor and offset pagination variants: supplying both\n * `cursor` and `offset` is a compile-time error, since they are mutually\n * exclusive ways to express \"the next page\" (cursor wins at runtime).\n */\nexport type CollectionFilter = CursorCollectionFilter | OffsetCollectionFilter;\n\n/**\n * Filter for loadEntry - type and id are required\n */\nexport interface EntryFilter {\n\ttype: string;\n\tid: string;\n\t/**\n\t * When set, fetch content data from this revision instead of the content table.\n\t * Used by preview mode to serve draft revision data.\n\t */\n\trevisionId?: string;\n\t/**\n\t * Locale to scope slug lookup. Only affects slug resolution;\n\t * IDs are globally unique and always resolve regardless of locale.\n\t */\n\tlocale?: string;\n}\n\n// Cached database instance (shared across calls)\nlet dbInstance: Kysely<Database> | null = null;\n\n/**\n * Get the database instance. Used by query wrapper functions and middleware.\n *\n * Checks the ALS request context first — if a per-request DB override is set\n * (e.g. by DO preview middleware), it takes precedence over the module-level\n * cached instance. This allows preview mode to route queries to an isolated\n * Durable Object database without modifying any calling code.\n *\n * Initializes the default database on first call using config from virtual module.\n */\nexport async function getDb(): Promise<Kysely<Database>> {\n\t// Per-request DB override via ALS (normal mode)\n\tconst ctx = getRequestContext();\n\tif (ctx?.db) {\n\t\treturn ctx.db as Kysely<Database>; // eslint-disable-line typescript/no-unsafe-type-assertion -- db is typed as unknown in RequestContext to avoid circular deps\n\t}\n\n\tif (!dbInstance) {\n\t\tawait loadVirtualModules();\n\t\tif (!virtualConfig?.database || typeof virtualCreateDialect !== \"function\") {\n\t\t\tthrow new Error(\n\t\t\t\t\"EmDash database not configured. Add database config to emdash() in astro.config.mjs\",\n\t\t\t);\n\t\t}\n\t\tconst dialect = virtualCreateDialect(virtualConfig.database.config);\n\t\tdbInstance = new Kysely<Database>({ dialect, log: kyselyLogOption() });\n\t}\n\treturn dbInstance;\n}\n\n/**\n * Create an EmDash Live Collections loader\n *\n * This loader handles ALL content types in a single Astro collection.\n * Use `getEmDashCollection()` and `getEmDashEntry()` to query\n * specific content types.\n *\n * Database is configured in astro.config.mjs via the emdash() integration.\n *\n * @example\n * ```ts\n * // src/live.config.ts\n * import { defineLiveCollection } from \"astro:content\";\n * import { emdashLoader } from \"emdash\";\n *\n * export const collections = {\n * emdash: defineLiveCollection({\n * loader: emdashLoader(),\n * }),\n * };\n * ```\n */\nexport function emdashLoader(): LiveLoader<EntryData, EntryFilter, CollectionFilter> {\n\treturn {\n\t\tname: \"emdash\",\n\n\t\t/**\n\t\t * Load all entries for a content type\n\t\t */\n\t\tasync loadCollection({ filter }) {\n\t\t\ttry {\n\t\t\t\t// Get DB instance (initializes on first use)\n\t\t\t\tconst db = await getDb();\n\n\t\t\t\t// Type filter is required\n\t\t\t\tconst type = filter?.type;\n\t\t\t\tif (!type) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\terror: new Error(\n\t\t\t\t\t\t\t\"type filter is required. Use getEmDashCollection() instead of getLiveCollection() directly.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Query the per-collection table (ec_posts, ec_products, etc.)\n\t\t\t\tconst tableName = getTableName(type);\n\n\t\t\t\t// Build query with dynamic table name\n\t\t\t\tconst status = filter?.status || \"published\";\n\t\t\t\tconst limit = filter?.limit;\n\t\t\t\tconst cursor = filter?.cursor;\n\t\t\t\tconst where = filter?.where;\n\t\t\t\tconst orderBy = filter?.orderBy;\n\t\t\t\tconst locale = filter?.locale;\n\n\t\t\t\t// Cursor pagination: over-fetch by 1 to detect next page\n\t\t\t\tconst fetchLimit = limit ? limit + 1 : undefined;\n\n\t\t\t\t// Offset pagination (numbered archive routes). Keyset (cursor)\n\t\t\t\t// and offset are mutually exclusive ways to express \"the next\n\t\t\t\t// page\" — when both are supplied, cursor wins and offset is\n\t\t\t\t// dropped so the two don't stack into a double skip. Only a\n\t\t\t\t// positive integer applies; 0 / negative / fractional are no-ops.\n\t\t\t\tconst rawOffset = cursor ? undefined : filter?.offset;\n\t\t\t\tconst offset =\n\t\t\t\t\ttypeof rawOffset === \"number\" && Number.isInteger(rawOffset) && rawOffset > 0\n\t\t\t\t\t\t? rawOffset\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\t// Build cursor condition if cursor is provided\n\t\t\t\tconst cursorCondition = cursor ? buildCursorCondition(cursor, orderBy) : null;\n\n\t\t\t\t// Separate taxonomy / byline filters from field filters\n\t\t\t\tlet result: { rows: Record<string, unknown>[] };\n\t\t\t\t// Taxonomy filters AND together: each entry constrains the base\n\t\t\t\t// row to match at least one of its slugs *within that taxonomy*.\n\t\t\t\t// Term slugs are unique only within a taxonomy, so every filter\n\t\t\t\t// keeps its own `name` and emits its own `EXISTS` clause rather\n\t\t\t\t// than pooling slugs into one `IN`.\n\t\t\t\tconst taxonomyFilters: { name: string; slugs: string[] }[] = [];\n\t\t\t\t// A byline filter matches entries credited to any of the given\n\t\t\t\t// byline translation groups via the `_emdash_content_bylines`\n\t\t\t\t// junction table. `null` means no byline filter; an empty\n\t\t\t\t// `groups` array means the filter was requested but matches\n\t\t\t\t// nothing (short-circuited to an empty result below).\n\t\t\t\tlet bylineFilter: { groups: string[] } | null = null;\n\t\t\t\tconst fieldFilters: Record<string, WhereValue> = {};\n\n\t\t\t\tif (where && Object.keys(where).length > 0) {\n\t\t\t\t\tconst taxNames = await getTaxonomyNames(db, type);\n\n\t\t\t\t\tfor (const [key, value] of Object.entries(where)) {\n\t\t\t\t\t\tif (value == null) continue;\n\t\t\t\t\t\tif (key === \"byline\") {\n\t\t\t\t\t\t\tif (isWhereRange(value)) {\n\t\t\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t\t\t`[emdash] where filter: range operators are not supported on \"byline\", ignored`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst groups = Array.isArray(value) ? value : [value];\n\t\t\t\t\t\t\tbylineFilter = { groups };\n\t\t\t\t\t\t} else if (taxNames.has(key)) {\n\t\t\t\t\t\t\tif (isWhereRange(value)) {\n\t\t\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t\t\t`[emdash] where filter: range operators are not supported on taxonomy \"${key}\", ignored`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst slugs = Array.isArray(value) ? value : [value];\n\t\t\t\t\t\t\ttaxonomyFilters.push({ name: key, slugs });\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfieldFilters[key] = value;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// A byline or taxonomy filter with no values matches nothing —\n\t\t\t\t// short-circuit before building SQL (an empty `IN ()` is invalid\n\t\t\t\t// SQL on both dialects).\n\t\t\t\tif (\n\t\t\t\t\t(bylineFilter && bylineFilter.groups.length === 0) ||\n\t\t\t\t\ttaxonomyFilters.some((f) => f.slugs.length === 0)\n\t\t\t\t) {\n\t\t\t\t\treturn { entries: [], cacheHint: { tags: [type] } };\n\t\t\t\t}\n\n\t\t\t\tif (taxonomyFilters.length > 0 && Object.keys(fieldFilters).length === 0) {\n\t\t\t\t\t// Pivot-drive fast path (#1834): seek the matching entries on the\n\t\t\t\t\t// denormalized `content_taxonomies` pivot instead of scanning the\n\t\t\t\t\t// whole collection and probing a taxonomy EXISTS per row. Only the\n\t\t\t\t\t// taxonomy path is restructured — a taxonomy filter combined with a\n\t\t\t\t\t// content-field filter falls through to the single-table shape\n\t\t\t\t\t// below (field predicates live on `ec_*`, not the pivot). A byline\n\t\t\t\t\t// filter rides along inside the pivot CTE (see the builder).\n\t\t\t\t\tconst groupSets: string[][] = [];\n\t\t\t\t\tfor (const taxFilter of taxonomyFilters) {\n\t\t\t\t\t\tconst groups = await resolveTermGroups(db, taxFilter.name, taxFilter.slugs, locale);\n\t\t\t\t\t\t// A slug that resolves to no term matches nothing; since taxonomy\n\t\t\t\t\t\t// filters AND together, one empty set empties the whole result.\n\t\t\t\t\t\tif (groups.length === 0) {\n\t\t\t\t\t\t\treturn { entries: [], cacheHint: { tags: [type] } };\n\t\t\t\t\t\t}\n\t\t\t\t\t\tgroupSets.push(groups);\n\t\t\t\t\t}\n\n\t\t\t\t\tresult = await buildTaxonomyPivotQuery({\n\t\t\t\t\t\tdb,\n\t\t\t\t\t\tcollection: type,\n\t\t\t\t\t\ttableName,\n\t\t\t\t\t\tgroupSets,\n\t\t\t\t\t\torderBy,\n\t\t\t\t\t\tcursor,\n\t\t\t\t\t\tlocale,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\t// Public listings only ever want live content.\n\t\t\t\t\t\tdeletedIsNull: true,\n\t\t\t\t\t\tbylineGroups: bylineFilter ? bylineFilter.groups : null,\n\t\t\t\t\t\tfetchLimit,\n\t\t\t\t\t\toffset,\n\t\t\t\t\t}).execute(db);\n\t\t\t\t} else {\n\t\t\t\t\t// Taxonomy and byline filters are applied as correlated\n\t\t\t\t\t// `EXISTS` semi-joins rather than `INNER JOIN ... DISTINCT`.\n\t\t\t\t\t// A join fan-out would force `SELECT DISTINCT table.*`, and\n\t\t\t\t\t// Postgres cannot apply DISTINCT to a row containing a `json`\n\t\t\t\t\t// column (no equality operator), so the join approach throws\n\t\t\t\t\t// there. EXISTS matches \"credited/tagged at least once\"\n\t\t\t\t\t// without duplicating rows, needs no DISTINCT, and works on\n\t\t\t\t\t// both SQLite and Postgres. The base query stays a single-\n\t\t\t\t\t// table `SELECT *`, so all field/status/locale/cursor/order\n\t\t\t\t\t// conditions reference unprefixed columns as before.\n\t\t\t\t\tconst orderByClause = buildOrderByClause(orderBy);\n\t\t\t\t\tconst statusCondition = buildStatusCondition(db, status);\n\t\t\t\t\tconst localeFilter = locale ? sql`AND locale = ${locale}` : sql``;\n\t\t\t\t\tconst cursorCond = cursorCondition ? sql`AND ${cursorCondition}` : sql``;\n\t\t\t\t\tconst fieldConds = buildFieldConditions(fieldFilters);\n\t\t\t\t\tconst fieldCondsSQL =\n\t\t\t\t\t\tfieldConds.length > 0 ? sql`${sql.join(fieldConds, sql` AND `)}` : null;\n\n\t\t\t\t\t// One `EXISTS` per taxonomy, AND'd together: an entry must be\n\t\t\t\t\t// tagged with a matching term in *every* requested taxonomy.\n\t\t\t\t\t// Each clause pins its own `t.name`, so slugs never pool\n\t\t\t\t\t// across taxonomies (they're only unique within one).\n\t\t\t\t\tconst taxonomyCond =\n\t\t\t\t\t\ttaxonomyFilters.length > 0\n\t\t\t\t\t\t\t? sql`${sql.join(\n\t\t\t\t\t\t\t\t\ttaxonomyFilters.map(\n\t\t\t\t\t\t\t\t\t\t(f) => sql`AND EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM content_taxonomies ct\n\t\t\t\t\t\t\tINNER JOIN taxonomies t ON t.translation_group = ct.taxonomy_id\n\t\t\t\t\t\t\tWHERE ct.collection = ${type}\n\t\t\t\t\t\t\t\tAND ct.entry_id = ${sql.ref(tableName)}.translation_group\n\t\t\t\t\t\t\t\tAND t.name = ${f.name}\n\t\t\t\t\t\t\t\tAND t.slug IN (${sql.join(f.slugs.map((s) => sql`${s}`))})\n\t\t\t\t\t\t\t${locale ? sql`AND t.locale = ${locale}` : sql``}\n\t\t\t\t\t\t)`,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\tsql` `,\n\t\t\t\t\t\t\t\t)}`\n\t\t\t\t\t\t\t: sql``;\n\n\t\t\t\t\t// `_emdash_content_bylines.byline_id` stores the byline's\n\t\t\t\t\t// translation_group (migration 040), so a credit spans every\n\t\t\t\t\t// locale variant of the byline and we match the group directly.\n\t\t\t\t\tconst bylineCond = bylineFilter\n\t\t\t\t\t\t? sql`AND EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM _emdash_content_bylines cb\n\t\t\t\t\t\t\tWHERE cb.collection_slug = ${type}\n\t\t\t\t\t\t\t\tAND cb.content_id = ${sql.ref(tableName)}.id\n\t\t\t\t\t\t\t\tAND cb.byline_id IN (${sql.join(bylineFilter.groups.map((g) => sql`${g}`))})\n\t\t\t\t\t\t)`\n\t\t\t\t\t\t: sql``;\n\n\t\t\t\t\t// Fold byline + taxonomy hydration into the list query.\n\t\t\t\t\tconst {\n\t\t\t\t\t\tterms: termsSelect,\n\t\t\t\t\t\tbylines: bylinesSelect,\n\t\t\t\t\t\tbylinesExist: bylinesExistSelect,\n\t\t\t\t\t} = foldedHydrationSelects(db, type, tableName);\n\n\t\t\t\t\t// LIMIT/OFFSET clause. SQLite only accepts OFFSET when a\n\t\t\t\t\t// LIMIT is present, so a bare offset uses `LIMIT -1`\n\t\t\t\t\t// (unbounded); Postgres takes a standalone OFFSET.\n\t\t\t\t\tlet limitOffsetClause = sql``;\n\t\t\t\t\tif (fetchLimit != null && offset != null) {\n\t\t\t\t\t\tlimitOffsetClause = sql`LIMIT ${fetchLimit} OFFSET ${offset}`;\n\t\t\t\t\t} else if (fetchLimit != null) {\n\t\t\t\t\t\tlimitOffsetClause = sql`LIMIT ${fetchLimit}`;\n\t\t\t\t\t} else if (offset != null) {\n\t\t\t\t\t\tlimitOffsetClause = isPostgres(db)\n\t\t\t\t\t\t\t? sql`OFFSET ${offset}`\n\t\t\t\t\t\t\t: sql`LIMIT -1 OFFSET ${offset}`;\n\t\t\t\t\t}\n\t\t\t\t\tresult = await sql<Record<string, unknown>>`\n\t\t\t\t\t\tSELECT *, ${termsSelect}, ${bylinesSelect}, ${bylinesExistSelect} FROM ${sql.ref(tableName)}\n\t\t\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\t\t\tAND ${statusCondition}\n\t\t\t\t\t\t${localeFilter}\n\t\t\t\t\t\t${cursorCond}\n\t\t\t\t\t\t${taxonomyCond}\n\t\t\t\t\t\t${bylineCond}\n\t\t\t\t\t\t${fieldCondsSQL ? sql`AND ${fieldCondsSQL}` : sql``}\n\t\t\t\t\t\t${orderByClause}\n\t\t\t\t\t\t${limitOffsetClause}\n\t\t\t\t\t`.execute(db);\n\t\t\t\t}\n\n\t\t\t\t// Detect whether there are more results (over-fetched by 1)\n\t\t\t\tconst hasMore = limit ? result.rows.length > limit : false;\n\t\t\t\tconst rows = hasMore ? result.rows.slice(0, limit) : result.rows;\n\n\t\t\t\t// Map rows to entries\n\t\t\t\tconst i18nConfig = virtualConfig?.i18n;\n\t\t\t\tconst i18nEnabled = i18nConfig && i18nConfig.locales.length > 1;\n\t\t\t\tconst entries = rows.map((row) => {\n\t\t\t\t\tconst slug = rowStr(row, \"slug\") || rowStr(row, \"id\");\n\t\t\t\t\tconst rowLocale = rowStr(row, \"locale\");\n\t\t\t\t\tconst shouldPrefix =\n\t\t\t\t\t\ti18nEnabled &&\n\t\t\t\t\t\trowLocale !== \"\" &&\n\t\t\t\t\t\t(rowLocale !== i18nConfig.defaultLocale || i18nConfig.prefixDefaultLocale);\n\t\t\t\t\tconst id = shouldPrefix ? `${rowLocale}/${slug}` : slug;\n\t\t\t\t\tconst data = mapRowToData(row);\n\t\t\t\t\tstashFolded(data, row);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tslug: rowStr(row, \"slug\"),\n\t\t\t\t\t\tstatus: rowStr(row, \"status\", \"draft\"),\n\t\t\t\t\t\tdata,\n\t\t\t\t\t\tcacheHint: {\n\t\t\t\t\t\t\ttags: [rowStr(row, \"id\")],\n\t\t\t\t\t\t\tlastModified: row.updated_at ? new Date(rowStr(row, \"updated_at\")) : undefined,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t});\n\n\t\t\t\t// Encode nextCursor from the last row if there are more results\n\t\t\t\tlet nextCursor: string | undefined;\n\t\t\t\tif (hasMore && rows.length > 0) {\n\t\t\t\t\tconst lastRow = rows.at(-1)!;\n\t\t\t\t\tconst primary = getPrimarySort(orderBy);\n\t\t\t\t\t// Strip table prefix from field name for row lookup\n\t\t\t\t\tconst fieldName = primary.field.includes(\".\")\n\t\t\t\t\t\t? primary.field.split(\".\").pop()!\n\t\t\t\t\t\t: primary.field;\n\t\t\t\t\tconst lastOrderValue = lastRow[fieldName];\n\t\t\t\t\tconst orderStr =\n\t\t\t\t\t\ttypeof lastOrderValue === \"string\" || typeof lastOrderValue === \"number\"\n\t\t\t\t\t\t\t? String(lastOrderValue)\n\t\t\t\t\t\t\t: \"\";\n\t\t\t\t\tnextCursor = encodeCursor(orderStr, String(lastRow.id));\n\t\t\t\t}\n\n\t\t\t\t// Collection-level cache hint uses the most recent updated_at\n\t\t\t\tlet collectionLastModified: Date | undefined;\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tif (row.updated_at) {\n\t\t\t\t\t\tconst d = new Date(rowStr(row, \"updated_at\"));\n\t\t\t\t\t\tif (!collectionLastModified || d > collectionLastModified) {\n\t\t\t\t\t\t\tcollectionLastModified = d;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tentries,\n\t\t\t\t\tnextCursor,\n\t\t\t\t\tcacheHint: {\n\t\t\t\t\t\ttags: [type],\n\t\t\t\t\t\tlastModified: collectionLastModified,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\t// Handle missing table/column gracefully - return empty collection.\n\t\t\t\t// Missing table happens before migrations have run.\n\t\t\t\t// Missing column happens when a where filter references a non-existent field.\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\tif (isMissingTableError(error) || isMissingColumnError(error)) {\n\t\t\t\t\tif (isMissingColumnError(error)) {\n\t\t\t\t\t\tconsole.warn(`[emdash] where filter: ${message}`);\n\t\t\t\t\t}\n\t\t\t\t\treturn { entries: [] };\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\terror: new Error(`Failed to load collection: ${message}`),\n\t\t\t\t};\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * Load a single entry by type and ID/slug\n\t\t *\n\t\t * When filter.revisionId is set (preview mode), the entry's data\n\t\t * comes from the revisions table instead of the content table columns.\n\t\t */\n\t\tasync loadEntry({ filter }) {\n\t\t\ttry {\n\t\t\t\t// Get DB instance\n\t\t\t\tconst db = await getDb();\n\n\t\t\t\t// Both type and id are required\n\t\t\t\tconst type = filter?.type;\n\t\t\t\tconst id = filter?.id;\n\n\t\t\t\tif (!type || !id) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\terror: new Error(\n\t\t\t\t\t\t\t\"type and id filters are required. Use getEmDashEntry() instead of getLiveEntry() directly.\",\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Query the per-collection table\n\t\t\t\tconst tableName = getTableName(type);\n\t\t\t\tconst locale = filter?.locale;\n\n\t\t\t\t// Use raw SQL for dynamic table name, match by slug or id\n\t\t\t\t// When locale is specified, prefer locale-scoped slug match,\n\t\t\t\t// but IDs are globally unique so always check id without locale scope.\n\t\t\t\t//\n\t\t\t\t// Byline + taxonomy hydration (foldedHydrationSelects) and per-entry\n\t\t\t\t// SEO (foldedSeoSelect) are each surfaced as a single aggregated JSON\n\t\t\t\t// column rather than flat columns. This keeps the result-set width\n\t\t\t\t// bounded at any collection schema width: a flat `LEFT JOIN _emdash_seo`\n\t\t\t\t// adds 5 alias columns to every row and pushes wide flat-schema\n\t\t\t\t// collections (common after WordPress / ACF imports) past D1's\n\t\t\t\t// per-result-set column limit, surfacing as a silent null entry. One\n\t\t\t\t// JSON column is one column, so the join stays safe at any width and\n\t\t\t\t// we keep the single round trip.\n\t\t\t\tconst {\n\t\t\t\t\tterms: termsSelect,\n\t\t\t\t\tbylines: bylinesSelect,\n\t\t\t\t\tbylinesExist: bylinesExistSelect,\n\t\t\t\t} = foldedHydrationSelects(db, type, \"c\");\n\t\t\t\tconst seoSelect = foldedSeoSelect(db, type, \"c\");\n\t\t\t\tconst result = locale\n\t\t\t\t\t? await sql<Record<string, unknown>>`\n\t\t\t\t\t\t\tSELECT c.*, ${seoSelect}, ${termsSelect}, ${bylinesSelect}, ${bylinesExistSelect}\n\t\t\t\t\t\t\tFROM ${sql.ref(tableName)} AS c\n\t\t\t\t\t\t\tWHERE c.deleted_at IS NULL\n\t\t\t\t\t\t\tAND ((c.slug = ${id} AND c.locale = ${locale}) OR c.id = ${id})\n\t\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t\t`.execute(db)\n\t\t\t\t\t: await sql<Record<string, unknown>>`\n\t\t\t\t\t\t\tSELECT c.*, ${seoSelect}, ${termsSelect}, ${bylinesSelect}, ${bylinesExistSelect}\n\t\t\t\t\t\t\tFROM ${sql.ref(tableName)} AS c\n\t\t\t\t\t\t\tWHERE c.deleted_at IS NULL\n\t\t\t\t\t\t\tAND (c.slug = ${id} OR c.id = ${id})\n\t\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t\t`.execute(db);\n\n\t\t\t\tconst row = result.rows[0];\n\t\t\t\tif (!row) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\t// Expand the folded SEO JSON column onto SEO_COLUMN_ALIASES so\n\t\t\t\t// extractSeo() reads it transparently. Missing/null SEO is a\n\t\t\t\t// no-op: extractSeo() returns null when the aliases are absent.\n\t\t\t\texpandFoldedSeo(row);\n\n\t\t\t\tconst i18nConfig = virtualConfig?.i18n;\n\t\t\t\tconst i18nEnabled = i18nConfig && i18nConfig.locales.length > 1;\n\t\t\t\tconst entrySlug = rowStr(row, \"slug\") || rowStr(row, \"id\");\n\t\t\t\tconst entryLocale = rowStr(row, \"locale\");\n\t\t\t\tconst shouldPrefixEntry =\n\t\t\t\t\ti18nEnabled &&\n\t\t\t\t\tentryLocale !== \"\" &&\n\t\t\t\t\t(entryLocale !== i18nConfig.defaultLocale || i18nConfig.prefixDefaultLocale);\n\t\t\t\tconst entryId = shouldPrefixEntry ? `${entryLocale}/${entrySlug}` : entrySlug;\n\n\t\t\t\t// Preview mode: override content fields with revision data,\n\t\t\t\t// keeping system metadata from the content table row.\n\t\t\t\tconst revisionId = filter?.revisionId;\n\t\t\t\tif (revisionId) {\n\t\t\t\t\tconst revRow = await sql<{ data: string }>`\n\t\t\t\t\t\tSELECT data FROM revisions\n\t\t\t\t\t\tWHERE id = ${revisionId}\n\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t`.execute(db);\n\n\t\t\t\t\tconst revData = revRow.rows[0];\n\t\t\t\t\tif (revData) {\n\t\t\t\t\t\tconst parsed: Record<string, unknown> = JSON.parse(revData.data);\n\t\t\t\t\t\t// System metadata from content table + content fields from revision\n\t\t\t\t\t\tconst systemData: Record<string, unknown> = {};\n\t\t\t\t\t\tfor (const [key, mappedKey] of Object.entries(INCLUDE_IN_DATA)) {\n\t\t\t\t\t\t\tif (key in row) {\n\t\t\t\t\t\t\t\tif (DATE_COLUMNS.has(key)) {\n\t\t\t\t\t\t\t\t\tsystemData[mappedKey] = typeof row[key] === \"string\" ? new Date(row[key]) : null;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tsystemData[mappedKey] = row[key];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Use slug from revision metadata if present, else from content table\n\t\t\t\t\t\tconst slug = typeof parsed._slug === \"string\" ? parsed._slug : rowStr(row, \"slug\");\n\t\t\t\t\t\tconst revSlug = slug || rowStr(row, \"id\");\n\t\t\t\t\t\tconst revLocale = rowStr(row, \"locale\");\n\t\t\t\t\t\tconst shouldPrefixRev =\n\t\t\t\t\t\t\ti18nEnabled &&\n\t\t\t\t\t\t\trevLocale !== \"\" &&\n\t\t\t\t\t\t\t(revLocale !== i18nConfig.defaultLocale || i18nConfig.prefixDefaultLocale);\n\t\t\t\t\t\tconst revId = shouldPrefixRev ? `${revLocale}/${revSlug}` : revSlug;\n\t\t\t\t\t\t// SEO is not revisioned — it comes from the content row's\n\t\t\t\t\t\t// joined _emdash_seo columns, not the revision snapshot.\n\t\t\t\t\t\tconst revEntryData: Record<string, unknown> = {\n\t\t\t\t\t\t\t...systemData,\n\t\t\t\t\t\t\tslug,\n\t\t\t\t\t\t\t...mapRevisionData(parsed),\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst revSeo = extractSeo(row);\n\t\t\t\t\t\tif (revSeo) revEntryData.seo = revSeo;\n\t\t\t\t\t\tstashFolded(revEntryData, row);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tid: revId,\n\t\t\t\t\t\t\tslug,\n\t\t\t\t\t\t\tstatus: rowStr(row, \"status\", \"draft\"),\n\t\t\t\t\t\t\tdata: revEntryData,\n\t\t\t\t\t\t\tcacheHint: {\n\t\t\t\t\t\t\t\ttags: [rowStr(row, \"id\")],\n\t\t\t\t\t\t\t\tlastModified: row.updated_at ? new Date(rowStr(row, \"updated_at\")) : undefined,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst entryData = mapRowToData(row);\n\t\t\t\tconst entrySeo = extractSeo(row);\n\t\t\t\tif (entrySeo) entryData.seo = entrySeo;\n\t\t\t\tstashFolded(entryData, row);\n\t\t\t\treturn {\n\t\t\t\t\tid: entryId,\n\t\t\t\t\tslug: rowStr(row, \"slug\"),\n\t\t\t\t\tstatus: rowStr(row, \"status\", \"draft\"),\n\t\t\t\t\tdata: entryData,\n\t\t\t\t\tcacheHint: {\n\t\t\t\t\t\ttags: [rowStr(row, \"id\")],\n\t\t\t\t\t\tlastModified: row.updated_at ? new Date(rowStr(row, \"updated_at\")) : undefined,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\t// Handle missing table gracefully - return undefined (not found).\n\t\t\t\t// This happens before migrations have run.\n\t\t\t\tif (isMissingTableError(error)) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\treturn {\n\t\t\t\t\terror: new Error(`Failed to load entry: ${message}`),\n\t\t\t\t};\n\t\t\t}\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;AAsB3B,MAAM,qBAA6C;CAClD,WAAW;CACX,iBAAiB;CACjB,WAAW;CACX,eAAe;CACf,cAAc;CACd;;AAGD,MAAM,oBAAoB,OAAO,OAAO,mBAAmB;;AAG3D,MAAM,oBAAoB;;;;;AAM1B,MAAM,iBAAiB,IAAI,IAAI;CAC9B;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAKA,GAAG;CAIH;CACA;CACA;CACA;CACA,CAAC;;AAGF,MAAa,eAAe,OAAO,IAAI,qBAAqB;AAC5D,MAAa,iBAAiB,OAAO,IAAI,uBAAuB;;;;;;AAMhE,MAAa,uBAAuB,OAAO,IAAI,4BAA4B;;;;;;;;;;;;;AAe3E,SAAS,uBAAuB,IAAiB,MAAc,OAAe;CAC7E,MAAM,IAAI,IAAI,IAAI,MAAM;CAC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MAAM,UAAU,OAAO,MAAM;AACtE,WAAO,EACN,uBAAO,IAAI,MAAM,yBAAyB,UAAU,EACpD;;;EAGH"}
@@ -0,0 +1,189 @@
1
+ import { n as fingerprintMigrationSet } from "./identity-Ys6Dlc9C.mjs";
2
+ import { z } from "zod";
3
+
4
+ //#region src/i18n/normalize.ts
5
+ function normalizeAstroI18n(config) {
6
+ if (!config) return null;
7
+ return {
8
+ defaultLocale: config.defaultLocale,
9
+ locales: config.locales.map((locale) => typeof locale === "string" ? locale : locale.path),
10
+ fallback: config.fallback ? Object.fromEntries(Object.entries(config.fallback).filter((entry) => entry[1] !== void 0)) : void 0,
11
+ prefixDefaultLocale: typeof config.routing === "object" ? config.routing.prefixDefaultLocale ?? false : false
12
+ };
13
+ }
14
+
15
+ //#endregion
16
+ //#region src/migrations/manifest.ts
17
+ const FINGERPRINT_PATTERN = /^[0-9a-f]{64}$/;
18
+ const MIGRATION_NAME_PATTERN = /^\d{3}_[a-z0-9_]+$/;
19
+ const EXECUTOR_ENTRYPOINT_PATTERN = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;
20
+ const ENVIRONMENT_VARIABLE_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
21
+ const ENVIRONMENT_REFERENCE_KEY_PATTERN = /(?:env|envName|envVar)$/i;
22
+ const URL_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*:/;
23
+ const SECRET_QUERY_KEY_PATTERN = /(?:auth|credential|key|password|secret|signature|token)/i;
24
+ const SECRET_CONFIG_KEY_PATTERN = /(?:accessToken|apiKey|authToken|certificate|connectionString|password|privateKey|secret)/i;
25
+ const SECRET_CONFIG_EXACT_KEY_PATTERN = /^(?:ca|cert|key)$/i;
26
+ const CONNECTION_URL_PROTOCOLS = new Set([
27
+ "mysql:",
28
+ "postgres:",
29
+ "postgresql:"
30
+ ]);
31
+ const i18nConfigSchema = z.object({
32
+ defaultLocale: z.string().min(1),
33
+ locales: z.array(z.string().min(1)).min(1),
34
+ fallback: z.record(z.string(), z.string()).optional(),
35
+ prefixDefaultLocale: z.boolean().optional()
36
+ }).strict();
37
+ const migrationManifestV1Schema = z.object({
38
+ schemaVersion: z.literal(1),
39
+ emdashVersion: z.string().min(1),
40
+ migrationSet: z.object({
41
+ names: z.array(z.string().regex(MIGRATION_NAME_PATTERN)).min(1).refine((names) => new Set(names).size === names.length),
42
+ fingerprint: z.string().regex(FINGERPRINT_PATTERN)
43
+ }).strict(),
44
+ i18n: i18nConfigSchema.nullable(),
45
+ database: z.object({
46
+ type: z.enum(["sqlite", "postgres"]),
47
+ executorEntrypoint: z.string().regex(EXECUTOR_ENTRYPOINT_PATTERN),
48
+ executorConfig: z.unknown()
49
+ }).strict()
50
+ }).strict();
51
+ var MigrationManifestValidationError = class extends Error {
52
+ constructor(message) {
53
+ super(`Invalid migration manifest: ${message}`);
54
+ this.name = "MigrationManifestValidationError";
55
+ }
56
+ };
57
+ function isEnvironmentReferenceKey(key) {
58
+ return ENVIRONMENT_REFERENCE_KEY_PATTERN.test(key);
59
+ }
60
+ function assertSafeUrl(value, path) {
61
+ if (!URL_SCHEME_PATTERN.test(value)) return;
62
+ let url;
63
+ try {
64
+ url = new URL(value);
65
+ } catch {
66
+ throw new MigrationManifestValidationError(`${path} contains an invalid URL`);
67
+ }
68
+ if (CONNECTION_URL_PROTOCOLS.has(url.protocol)) throw new MigrationManifestValidationError(`${path} contains a database connection URL`);
69
+ if (url.username || url.password) throw new MigrationManifestValidationError(`${path} contains URL credentials`);
70
+ for (const key of url.searchParams.keys()) if (SECRET_QUERY_KEY_PATTERN.test(key)) throw new MigrationManifestValidationError(`${path} contains a credential query parameter`);
71
+ }
72
+ function cloneSecretFreeJson(value, path, ancestors) {
73
+ if (value === null || typeof value === "boolean") return value;
74
+ if (typeof value === "string") {
75
+ assertSafeUrl(value, path);
76
+ return value;
77
+ }
78
+ if (typeof value === "number") {
79
+ if (Number.isFinite(value)) return value;
80
+ throw new MigrationManifestValidationError(`${path} contains a non-finite number`);
81
+ }
82
+ if (typeof value !== "object") throw new MigrationManifestValidationError(`${path} is not JSON-serializable`);
83
+ if (ancestors.has(value)) throw new MigrationManifestValidationError(`${path} contains a cycle`);
84
+ ancestors.add(value);
85
+ try {
86
+ if (Array.isArray(value)) return value.map((item, index) => cloneSecretFreeJson(item, `${path}[${index}]`, ancestors));
87
+ const prototype = Object.getPrototypeOf(value);
88
+ if (prototype !== Object.prototype && prototype !== null) throw new MigrationManifestValidationError(`${path} contains a non-plain object`);
89
+ const cloned = {};
90
+ for (const [key, item] of Object.entries(value)) {
91
+ const itemPath = `${path}.${key}`;
92
+ const environmentReference = isEnvironmentReferenceKey(key);
93
+ if (!environmentReference && (SECRET_CONFIG_KEY_PATTERN.test(key) || SECRET_CONFIG_EXACT_KEY_PATTERN.test(key))) throw new MigrationManifestValidationError(`${itemPath} is a credential-bearing field`);
94
+ if (environmentReference) {
95
+ if (typeof item !== "string" || !ENVIRONMENT_VARIABLE_PATTERN.test(item)) throw new MigrationManifestValidationError(`${itemPath} must contain an environment-variable name`);
96
+ }
97
+ cloned[key] = cloneSecretFreeJson(item, itemPath, ancestors);
98
+ }
99
+ return cloned;
100
+ } finally {
101
+ ancestors.delete(value);
102
+ }
103
+ }
104
+ function validateSecretFreeExecutorConfig(value, path = "database.executorConfig") {
105
+ return cloneSecretFreeJson(value, path, /* @__PURE__ */ new Set());
106
+ }
107
+ function identitiesMatch(manifest, expectedIdentity) {
108
+ return manifest.emdashVersion === expectedIdentity.emdashVersion && manifest.migrationSet.fingerprint === expectedIdentity.fingerprint && manifest.migrationSet.names.length === expectedIdentity.names.length && manifest.migrationSet.names.every((name, index) => name === expectedIdentity.names[index]);
109
+ }
110
+ async function validateMigrationManifest(value, expectedIdentity) {
111
+ const parsed = migrationManifestV1Schema.safeParse(value);
112
+ if (!parsed.success) throw new MigrationManifestValidationError("schema validation failed");
113
+ const executorConfig = validateSecretFreeExecutorConfig(parsed.data.database.executorConfig);
114
+ const manifest = {
115
+ ...parsed.data,
116
+ database: {
117
+ ...parsed.data.database,
118
+ executorConfig
119
+ }
120
+ };
121
+ if (await fingerprintMigrationSet(manifest.emdashVersion, manifest.migrationSet.names) !== manifest.migrationSet.fingerprint) throw new MigrationManifestValidationError("migrationSet fingerprint does not match its version and ordered names");
122
+ if (expectedIdentity && !identitiesMatch(manifest, expectedIdentity)) throw new MigrationManifestValidationError("manifest does not match the loaded EmDash migration identity");
123
+ return manifest;
124
+ }
125
+ function serializeMigrationManifest(manifest) {
126
+ return `${JSON.stringify(manifest, null, " ")}\n`;
127
+ }
128
+
129
+ //#endregion
130
+ //#region src/migrations/integration-metadata.ts
131
+ const MIGRATION_CONFIG_SYMBOL = Symbol.for("emdash:migration-config");
132
+ function isRecord(value) {
133
+ return typeof value === "object" && value !== null;
134
+ }
135
+ function isMigrationIntegrationMetadata(value) {
136
+ if (!isRecord(value)) return false;
137
+ const database = value.database;
138
+ if (database === void 0) return true;
139
+ if (!isRecord(database) || database.type !== "sqlite" && database.type !== "postgres") return false;
140
+ const migrations = database.migrations;
141
+ return migrations === void 0 || isRecord(migrations) && typeof migrations.entrypoint === "string" && Object.hasOwn(migrations, "manifestConfig");
142
+ }
143
+ function createMigrationIntegrationMetadata(database) {
144
+ if (!database) return {};
145
+ return { database: {
146
+ type: database.type,
147
+ migrations: database.migrations ? {
148
+ entrypoint: database.migrations.entrypoint,
149
+ manifestConfig: validateSecretFreeExecutorConfig(database.migrations.manifestConfig, "database.migrations.manifestConfig")
150
+ } : void 0
151
+ } };
152
+ }
153
+ function getMigrationIntegrationMetadata(integration) {
154
+ if ((typeof integration !== "object" || integration === null) && typeof integration !== "function") return;
155
+ if (!Object.hasOwn(integration, MIGRATION_CONFIG_SYMBOL)) return;
156
+ const metadata = Reflect.get(integration, MIGRATION_CONFIG_SYMBOL);
157
+ return isMigrationIntegrationMetadata(metadata) ? metadata : void 0;
158
+ }
159
+
160
+ //#endregion
161
+ //#region src/migrations/manifest-builder.ts
162
+ var UnsupportedMigrationAdapterError = class extends Error {
163
+ constructor() {
164
+ super("The configured database adapter does not provide a deployment migration executor");
165
+ this.name = "UnsupportedMigrationAdapterError";
166
+ }
167
+ };
168
+ async function buildMigrationManifest({ identity, i18n, database }) {
169
+ if (await fingerprintMigrationSet(identity.emdashVersion, identity.names) !== identity.fingerprint) throw new MigrationManifestValidationError("loaded identity fingerprint does not match its version and ordered names");
170
+ if (!database.migrations) throw new UnsupportedMigrationAdapterError();
171
+ return validateMigrationManifest({
172
+ schemaVersion: 1,
173
+ emdashVersion: identity.emdashVersion,
174
+ migrationSet: {
175
+ names: [...identity.names],
176
+ fingerprint: identity.fingerprint
177
+ },
178
+ i18n,
179
+ database: {
180
+ type: database.type,
181
+ executorEntrypoint: database.migrations.entrypoint,
182
+ executorConfig: database.migrations.manifestConfig
183
+ }
184
+ }, identity);
185
+ }
186
+
187
+ //#endregion
188
+ export { MigrationManifestValidationError as a, normalizeAstroI18n as c, getMigrationIntegrationMetadata as i, MIGRATION_CONFIG_SYMBOL as n, serializeMigrationManifest as o, createMigrationIntegrationMetadata as r, validateMigrationManifest as s, buildMigrationManifest as t };
189
+ //# sourceMappingURL=manifest-builder-B252yQUf.mjs.map