emdash 0.36.0 → 0.38.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 (991) hide show
  1. package/dist/{activation-K0kGBWuJ.mjs → activation-DyNTe_Tl.mjs} +3 -3
  2. package/dist/{activation-K0kGBWuJ.mjs.map → activation-DyNTe_Tl.mjs.map} +1 -1
  3. package/dist/{adapters-CzL3H752.d.mts → adapters-DCEgOBXi.d.mts} +4 -2
  4. package/dist/{adapters-CzL3H752.d.mts.map → adapters-DCEgOBXi.d.mts.map} +1 -1
  5. package/dist/{allowed-origins-maylGaHv.mjs → allowed-origins-GFUVavRj.mjs} +2 -2
  6. package/dist/{allowed-origins-maylGaHv.mjs.map → allowed-origins-GFUVavRj.mjs.map} +1 -1
  7. package/dist/api/route-utils.d.mts +3 -3
  8. package/dist/api/route-utils.mjs +25 -24
  9. package/dist/api/route-utils.mjs.map +1 -1
  10. package/dist/api/schemas/index.d.mts +2 -2
  11. package/dist/api/schemas/index.mjs +5 -5
  12. package/dist/api-BvxJmnFY.mjs +10094 -0
  13. package/dist/api-BvxJmnFY.mjs.map +1 -0
  14. package/dist/{api-tokens-9YrrCoE6.mjs → api-tokens-xpGqMHrC.mjs} +2 -2
  15. package/dist/{api-tokens-9YrrCoE6.mjs.map → api-tokens-xpGqMHrC.mjs.map} +1 -1
  16. package/dist/{apply-B_VMpJ2P.mjs → apply-DLmM3R7f.mjs} +26 -22
  17. package/dist/apply-DLmM3R7f.mjs.map +1 -0
  18. package/dist/artifact-fetch-P2JXVwOq.mjs +972 -0
  19. package/dist/artifact-fetch-P2JXVwOq.mjs.map +1 -0
  20. package/dist/astro/image-endpoint.mjs +2 -2
  21. package/dist/astro/image-endpoint.mjs.map +1 -1
  22. package/dist/astro/index.d.mts +12 -12
  23. package/dist/astro/index.d.mts.map +1 -1
  24. package/dist/astro/index.mjs +138 -39
  25. package/dist/astro/index.mjs.map +1 -1
  26. package/dist/astro/middleware/auth.d.mts +10 -10
  27. package/dist/astro/middleware/auth.mjs +6 -6
  28. package/dist/astro/middleware/media-usage-write-fence.mjs +3 -3
  29. package/dist/astro/middleware/redirect.mjs +7 -5
  30. package/dist/astro/middleware/redirect.mjs.map +1 -1
  31. package/dist/astro/middleware/request-context.mjs +3 -3
  32. package/dist/astro/middleware/setup.mjs +1 -1
  33. package/dist/astro/middleware.d.mts +10 -10
  34. package/dist/astro/middleware.d.mts.map +1 -1
  35. package/dist/astro/middleware.mjs +223 -232
  36. package/dist/astro/middleware.mjs.map +1 -1
  37. package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs +6 -6
  38. package/dist/astro/routes/api/admin/allowed-domains/index.mjs +6 -6
  39. package/dist/astro/routes/api/admin/api-tokens/_id_.mjs +3 -3
  40. package/dist/astro/routes/api/admin/api-tokens/index.d.mts.map +1 -1
  41. package/dist/astro/routes/api/admin/api-tokens/index.mjs +5 -5
  42. package/dist/astro/routes/api/admin/api-tokens/index.mjs.map +1 -1
  43. package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +4 -4
  44. package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +9 -9
  45. package/dist/astro/routes/api/admin/byline-fields/index.mjs +9 -9
  46. package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +9 -9
  47. package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +17 -17
  48. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +17 -17
  49. package/dist/astro/routes/api/admin/bylines/index.mjs +17 -17
  50. package/dist/astro/routes/api/admin/comments/_id_/status.mjs +13 -13
  51. package/dist/astro/routes/api/admin/comments/_id_.mjs +5 -5
  52. package/dist/astro/routes/api/admin/comments/bulk.mjs +10 -10
  53. package/dist/astro/routes/api/admin/comments/counts.mjs +5 -5
  54. package/dist/astro/routes/api/admin/comments/index.mjs +10 -10
  55. package/dist/astro/routes/api/admin/hooks/exclusive/_hookName_.mjs +4 -4
  56. package/dist/astro/routes/api/admin/hooks/exclusive/index.mjs +3 -3
  57. package/dist/astro/routes/api/admin/media-usage/activation.mjs +13 -13
  58. package/dist/astro/routes/api/admin/media-usage/collection-deletions/index.mjs +15 -15
  59. package/dist/astro/routes/api/admin/media-usage/collection-deletions/retry.mjs +15 -15
  60. package/dist/astro/routes/api/admin/media-usage/progress.mjs +14 -14
  61. package/dist/astro/routes/api/admin/media-usage/repair.mjs +17 -17
  62. package/dist/astro/routes/api/admin/media-usage/work/index.mjs +15 -15
  63. package/dist/astro/routes/api/admin/media-usage/work/retry.mjs +15 -15
  64. package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs +4 -4
  65. package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs.map +1 -1
  66. package/dist/astro/routes/api/admin/oauth-clients/index.mjs +4 -4
  67. package/dist/astro/routes/api/admin/oauth-clients/index.mjs.map +1 -1
  68. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +59 -56
  69. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs.map +1 -1
  70. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +59 -56
  71. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs.map +1 -1
  72. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +57 -54
  73. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs.map +1 -1
  74. package/dist/astro/routes/api/admin/plugins/_id_/mcp.mjs +4 -4
  75. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs +57 -54
  76. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs.map +1 -1
  77. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +58 -55
  78. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs.map +1 -1
  79. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +58 -55
  80. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs.map +1 -1
  81. package/dist/astro/routes/api/admin/plugins/index.mjs +57 -54
  82. package/dist/astro/routes/api/admin/plugins/index.mjs.map +1 -1
  83. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +2 -2
  84. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +57 -54
  85. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs.map +1 -1
  86. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +58 -55
  87. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs.map +1 -1
  88. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +57 -54
  89. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs.map +1 -1
  90. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +58 -55
  91. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs.map +1 -1
  92. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.d.mts.map +1 -1
  93. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +64 -57
  94. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs.map +1 -1
  95. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +18 -16
  96. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs.map +1 -1
  97. package/dist/astro/routes/api/admin/plugins/registry/install.d.mts.map +1 -1
  98. package/dist/astro/routes/api/admin/plugins/registry/install.mjs +65 -58
  99. package/dist/astro/routes/api/admin/plugins/registry/install.mjs.map +1 -1
  100. package/dist/astro/routes/api/admin/plugins/registry/verify.d.mts +8 -0
  101. package/dist/astro/routes/api/admin/plugins/registry/verify.d.mts.map +1 -0
  102. package/dist/astro/routes/api/admin/plugins/registry/verify.mjs +96 -0
  103. package/dist/astro/routes/api/admin/plugins/registry/verify.mjs.map +1 -0
  104. package/dist/astro/routes/api/admin/plugins/updates.mjs +57 -54
  105. package/dist/astro/routes/api/admin/plugins/updates.mjs.map +1 -1
  106. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +57 -54
  107. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs.map +1 -1
  108. package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +2 -2
  109. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +57 -54
  110. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs.map +1 -1
  111. package/dist/astro/routes/api/admin/users/_id_/disable.mjs +1 -1
  112. package/dist/astro/routes/api/admin/users/_id_/enable.mjs +1 -1
  113. package/dist/astro/routes/api/admin/users/_id_/index.mjs +6 -6
  114. package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +3 -3
  115. package/dist/astro/routes/api/admin/users/index.mjs +6 -6
  116. package/dist/astro/routes/api/auth/dev-bypass.mjs +3 -3
  117. package/dist/astro/routes/api/auth/invite/accept.mjs +1 -1
  118. package/dist/astro/routes/api/auth/invite/complete.mjs +11 -11
  119. package/dist/astro/routes/api/auth/invite/index.mjs +8 -8
  120. package/dist/astro/routes/api/auth/invite/register-options.mjs +10 -10
  121. package/dist/astro/routes/api/auth/logout.mjs +2 -2
  122. package/dist/astro/routes/api/auth/magic-link/send.mjs +10 -10
  123. package/dist/astro/routes/api/auth/magic-link/verify.mjs +2 -2
  124. package/dist/astro/routes/api/auth/me.mjs +7 -7
  125. package/dist/astro/routes/api/auth/mode.mjs +2 -2
  126. package/dist/astro/routes/api/auth/oauth/_provider_/callback.mjs +4 -4
  127. package/dist/astro/routes/api/auth/oauth/_provider_.mjs +2 -2
  128. package/dist/astro/routes/api/auth/passkey/_id_.mjs +6 -6
  129. package/dist/astro/routes/api/auth/passkey/index.mjs +1 -1
  130. package/dist/astro/routes/api/auth/passkey/options.mjs +12 -12
  131. package/dist/astro/routes/api/auth/passkey/register/options.mjs +10 -10
  132. package/dist/astro/routes/api/auth/passkey/register/verify.mjs +11 -11
  133. package/dist/astro/routes/api/auth/passkey/verify.mjs +11 -11
  134. package/dist/astro/routes/api/auth/signup/complete.mjs +11 -11
  135. package/dist/astro/routes/api/auth/signup/request.mjs +10 -10
  136. package/dist/astro/routes/api/auth/signup/verify.mjs +1 -1
  137. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +14 -14
  138. package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +13 -13
  139. package/dist/astro/routes/api/content/_collection_/_id_/compare.mjs +2 -2
  140. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.d.mts.map +1 -1
  141. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs +19 -5
  142. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs.map +1 -1
  143. package/dist/astro/routes/api/content/_collection_/_id_/duplicate.mjs +3 -3
  144. package/dist/astro/routes/api/content/_collection_/_id_/lock.d.mts +10 -0
  145. package/dist/astro/routes/api/content/_collection_/_id_/lock.d.mts.map +1 -0
  146. package/dist/astro/routes/api/content/_collection_/_id_/lock.mjs +66 -0
  147. package/dist/astro/routes/api/content/_collection_/_id_/lock.mjs.map +1 -0
  148. package/dist/astro/routes/api/content/_collection_/_id_/permanent.mjs +2 -2
  149. package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs +11 -11
  150. package/dist/astro/routes/api/content/_collection_/_id_/publish.d.mts.map +1 -1
  151. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +18 -10
  152. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs.map +1 -1
  153. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs +20 -18
  154. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs.map +1 -1
  155. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs +20 -18
  156. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs.map +1 -1
  157. package/dist/astro/routes/api/content/_collection_/_id_/restore.mjs +3 -3
  158. package/dist/astro/routes/api/content/_collection_/_id_/revisions.mjs +2 -2
  159. package/dist/astro/routes/api/content/_collection_/_id_/schedule.d.mts.map +1 -1
  160. package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs +15 -8
  161. package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs.map +1 -1
  162. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +16 -15
  163. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs.map +1 -1
  164. package/dist/astro/routes/api/content/_collection_/_id_/translations.mjs +2 -2
  165. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.d.mts.map +1 -1
  166. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs +19 -5
  167. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs.map +1 -1
  168. package/dist/astro/routes/api/content/_collection_/_id_.d.mts.map +1 -1
  169. package/dist/astro/routes/api/content/_collection_/_id_.mjs +23 -11
  170. package/dist/astro/routes/api/content/_collection_/_id_.mjs.map +1 -1
  171. package/dist/astro/routes/api/content/_collection_/authors.mjs +2 -2
  172. package/dist/astro/routes/api/content/_collection_/index.mjs +14 -9
  173. package/dist/astro/routes/api/content/_collection_/index.mjs.map +1 -1
  174. package/dist/astro/routes/api/content/_collection_/trash.mjs +7 -7
  175. package/dist/astro/routes/api/dashboard.mjs +8 -8
  176. package/dist/astro/routes/api/dev/emails.mjs +2 -2
  177. package/dist/astro/routes/api/import/probe.d.mts +3 -3
  178. package/dist/astro/routes/api/import/probe.mjs +18 -18
  179. package/dist/astro/routes/api/import/wordpress/analyze.mjs +3 -3
  180. package/dist/astro/routes/api/import/wordpress/execute.d.mts +11 -11
  181. package/dist/astro/routes/api/import/wordpress/execute.mjs +15 -14
  182. package/dist/astro/routes/api/import/wordpress/execute.mjs.map +1 -1
  183. package/dist/astro/routes/api/import/wordpress/media.d.mts +10 -10
  184. package/dist/astro/routes/api/import/wordpress/media.mjs +11 -11
  185. package/dist/astro/routes/api/import/wordpress/prepare.mjs +10 -10
  186. package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts +11 -11
  187. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +13 -13
  188. package/dist/astro/routes/api/import/wordpress-plugin/analyze.d.mts +1 -1
  189. package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +18 -18
  190. package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +11 -11
  191. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +29 -28
  192. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs.map +1 -1
  193. package/dist/astro/routes/api/manifest.mjs +4 -4
  194. package/dist/astro/routes/api/manifest.mjs.map +1 -1
  195. package/dist/astro/routes/api/mcp.mjs +213 -74
  196. package/dist/astro/routes/api/mcp.mjs.map +1 -1
  197. package/dist/astro/routes/api/media/_id_/confirm.mjs +11 -11
  198. package/dist/astro/routes/api/media/_id_/replace.d.mts +8 -0
  199. package/dist/astro/routes/api/media/_id_/replace.d.mts.map +1 -0
  200. package/dist/astro/routes/api/media/_id_/replace.mjs +91 -0
  201. package/dist/astro/routes/api/media/_id_/replace.mjs.map +1 -0
  202. package/dist/astro/routes/api/media/_id_/upload.mjs +6 -6
  203. package/dist/astro/routes/api/media/_id_/usage.mjs +19 -19
  204. package/dist/astro/routes/api/media/_id_.mjs +18 -18
  205. package/dist/astro/routes/api/media/file/_...key_.d.mts.map +1 -1
  206. package/dist/astro/routes/api/media/file/_...key_.mjs +3 -2
  207. package/dist/astro/routes/api/media/file/_...key_.mjs.map +1 -1
  208. package/dist/astro/routes/api/media/folders/_id_.mjs +8 -8
  209. package/dist/astro/routes/api/media/folders/index.mjs +8 -8
  210. package/dist/astro/routes/api/media/providers/_providerId_/_itemId_.mjs +2 -2
  211. package/dist/astro/routes/api/media/providers/_providerId_/index.mjs +2 -2
  212. package/dist/astro/routes/api/media/providers/index.mjs +2 -2
  213. package/dist/astro/routes/api/media/upload-url.mjs +16 -14
  214. package/dist/astro/routes/api/media/upload-url.mjs.map +1 -1
  215. package/dist/astro/routes/api/media.d.mts.map +1 -1
  216. package/dist/astro/routes/api/media.mjs +53 -30
  217. package/dist/astro/routes/api/media.mjs.map +1 -1
  218. package/dist/astro/routes/api/menus/_name_/items/_id_.d.mts.map +1 -1
  219. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +20 -13
  220. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs.map +1 -1
  221. package/dist/astro/routes/api/menus/_name_/items.d.mts.map +1 -1
  222. package/dist/astro/routes/api/menus/_name_/items.mjs +15 -11
  223. package/dist/astro/routes/api/menus/_name_/items.mjs.map +1 -1
  224. package/dist/astro/routes/api/menus/_name_/reorder.d.mts.map +1 -1
  225. package/dist/astro/routes/api/menus/_name_/reorder.mjs +15 -11
  226. package/dist/astro/routes/api/menus/_name_/reorder.mjs.map +1 -1
  227. package/dist/astro/routes/api/menus/_name_/translations.d.mts.map +1 -1
  228. package/dist/astro/routes/api/menus/_name_/translations.mjs +16 -12
  229. package/dist/astro/routes/api/menus/_name_/translations.mjs.map +1 -1
  230. package/dist/astro/routes/api/menus/_name_.d.mts.map +1 -1
  231. package/dist/astro/routes/api/menus/_name_.mjs +21 -14
  232. package/dist/astro/routes/api/menus/_name_.mjs.map +1 -1
  233. package/dist/astro/routes/api/menus/index.d.mts.map +1 -1
  234. package/dist/astro/routes/api/menus/index.mjs +15 -11
  235. package/dist/astro/routes/api/menus/index.mjs.map +1 -1
  236. package/dist/astro/routes/api/oauth/authorize.mjs +6 -6
  237. package/dist/astro/routes/api/oauth/device/authorize.mjs +5 -5
  238. package/dist/astro/routes/api/oauth/device/code.mjs +8 -8
  239. package/dist/astro/routes/api/oauth/device/token.mjs +7 -7
  240. package/dist/astro/routes/api/oauth/register.mjs +2 -2
  241. package/dist/astro/routes/api/oauth/token/refresh.mjs +5 -5
  242. package/dist/astro/routes/api/oauth/token/revoke.mjs +5 -5
  243. package/dist/astro/routes/api/oauth/token.mjs +5 -5
  244. package/dist/astro/routes/api/openapi.json.mjs +184 -52
  245. package/dist/astro/routes/api/openapi.json.mjs.map +1 -1
  246. package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +4 -4
  247. package/dist/astro/routes/api/redirects/404s/index.mjs +12 -11
  248. package/dist/astro/routes/api/redirects/404s/index.mjs.map +1 -1
  249. package/dist/astro/routes/api/redirects/404s/summary.mjs +12 -11
  250. package/dist/astro/routes/api/redirects/404s/summary.mjs.map +1 -1
  251. package/dist/astro/routes/api/redirects/_id_.mjs +13 -12
  252. package/dist/astro/routes/api/redirects/_id_.mjs.map +1 -1
  253. package/dist/astro/routes/api/redirects/index.mjs +13 -12
  254. package/dist/astro/routes/api/redirects/index.mjs.map +1 -1
  255. package/dist/astro/routes/api/relations/_id_/index.mjs +20 -18
  256. package/dist/astro/routes/api/relations/_id_/index.mjs.map +1 -1
  257. package/dist/astro/routes/api/relations/_id_/translations.mjs +15 -13
  258. package/dist/astro/routes/api/relations/_id_/translations.mjs.map +1 -1
  259. package/dist/astro/routes/api/relations/index.mjs +20 -18
  260. package/dist/astro/routes/api/relations/index.mjs.map +1 -1
  261. package/dist/astro/routes/api/revisions/_revisionId_/index.mjs +2 -2
  262. package/dist/astro/routes/api/revisions/_revisionId_/restore.mjs +3 -3
  263. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +57 -54
  264. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs.map +1 -1
  265. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +57 -54
  266. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs.map +1 -1
  267. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +57 -54
  268. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs.map +1 -1
  269. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +57 -54
  270. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs.map +1 -1
  271. package/dist/astro/routes/api/schema/collections/index.mjs +57 -54
  272. package/dist/astro/routes/api/schema/collections/index.mjs.map +1 -1
  273. package/dist/astro/routes/api/schema/collections/reorder.mjs +57 -54
  274. package/dist/astro/routes/api/schema/collections/reorder.mjs.map +1 -1
  275. package/dist/astro/routes/api/schema/index.mjs +13 -11
  276. package/dist/astro/routes/api/schema/index.mjs.map +1 -1
  277. package/dist/astro/routes/api/schema/orphans/_slug_.mjs +57 -54
  278. package/dist/astro/routes/api/schema/orphans/_slug_.mjs.map +1 -1
  279. package/dist/astro/routes/api/schema/orphans/index.mjs +57 -54
  280. package/dist/astro/routes/api/schema/orphans/index.mjs.map +1 -1
  281. package/dist/astro/routes/api/search/enable.mjs +12 -11
  282. package/dist/astro/routes/api/search/enable.mjs.map +1 -1
  283. package/dist/astro/routes/api/search/index.mjs +11 -10
  284. package/dist/astro/routes/api/search/index.mjs.map +1 -1
  285. package/dist/astro/routes/api/search/rebuild.mjs +12 -11
  286. package/dist/astro/routes/api/search/rebuild.mjs.map +1 -1
  287. package/dist/astro/routes/api/search/stats.mjs +7 -6
  288. package/dist/astro/routes/api/search/stats.mjs.map +1 -1
  289. package/dist/astro/routes/api/search/suggest.mjs +11 -10
  290. package/dist/astro/routes/api/search/suggest.mjs.map +1 -1
  291. package/dist/astro/routes/api/sections/_slug_.mjs +11 -10
  292. package/dist/astro/routes/api/sections/_slug_.mjs.map +1 -1
  293. package/dist/astro/routes/api/sections/index.mjs +11 -10
  294. package/dist/astro/routes/api/sections/index.mjs.map +1 -1
  295. package/dist/astro/routes/api/settings/backups/archives/_name_.mjs +7 -6
  296. package/dist/astro/routes/api/settings/backups/archives/_name_.mjs.map +1 -1
  297. package/dist/astro/routes/api/settings/backups/archives/index.mjs +6 -5
  298. package/dist/astro/routes/api/settings/backups/archives/index.mjs.map +1 -1
  299. package/dist/astro/routes/api/settings/backups/export.mjs +7 -6
  300. package/dist/astro/routes/api/settings/backups/export.mjs.map +1 -1
  301. package/dist/astro/routes/api/settings/backups/index.mjs +8 -7
  302. package/dist/astro/routes/api/settings/backups/index.mjs.map +1 -1
  303. package/dist/astro/routes/api/settings/email.mjs +5 -5
  304. package/dist/astro/routes/api/settings/email.mjs.map +1 -1
  305. package/dist/astro/routes/api/settings.d.mts.map +1 -1
  306. package/dist/astro/routes/api/settings.mjs +21 -17
  307. package/dist/astro/routes/api/settings.mjs.map +1 -1
  308. package/dist/astro/routes/api/setup/admin-verify.mjs +12 -12
  309. package/dist/astro/routes/api/setup/admin.mjs +11 -11
  310. package/dist/astro/routes/api/setup/dev-bypass.mjs +35 -33
  311. package/dist/astro/routes/api/setup/dev-bypass.mjs.map +1 -1
  312. package/dist/astro/routes/api/setup/dev-reset.mjs +2 -2
  313. package/dist/astro/routes/api/setup/index.mjs +35 -33
  314. package/dist/astro/routes/api/setup/index.mjs.map +1 -1
  315. package/dist/astro/routes/api/setup/status.mjs +3 -3
  316. package/dist/astro/routes/api/snapshot.mjs +8 -7
  317. package/dist/astro/routes/api/snapshot.mjs.map +1 -1
  318. package/dist/astro/routes/api/taxonomies/_name_/reorder.d.mts.map +1 -1
  319. package/dist/astro/routes/api/taxonomies/_name_/reorder.mjs +22 -17
  320. package/dist/astro/routes/api/taxonomies/_name_/reorder.mjs.map +1 -1
  321. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.d.mts.map +1 -1
  322. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +23 -18
  323. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs.map +1 -1
  324. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.d.mts.map +1 -1
  325. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +27 -19
  326. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs.map +1 -1
  327. package/dist/astro/routes/api/taxonomies/_name_/terms/index.d.mts.map +1 -1
  328. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +22 -17
  329. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs.map +1 -1
  330. package/dist/astro/routes/api/taxonomies/_name_/translations.mjs +16 -15
  331. package/dist/astro/routes/api/taxonomies/_name_/translations.mjs.map +1 -1
  332. package/dist/astro/routes/api/taxonomies/_name_.d.mts.map +1 -1
  333. package/dist/astro/routes/api/taxonomies/_name_.mjs +28 -20
  334. package/dist/astro/routes/api/taxonomies/_name_.mjs.map +1 -1
  335. package/dist/astro/routes/api/taxonomies/index.d.mts.map +1 -1
  336. package/dist/astro/routes/api/taxonomies/index.mjs +22 -17
  337. package/dist/astro/routes/api/taxonomies/index.mjs.map +1 -1
  338. package/dist/astro/routes/api/themes/preview.mjs +5 -5
  339. package/dist/astro/routes/api/typegen.mjs +4 -4
  340. package/dist/astro/routes/api/well-known/auth.mjs +2 -2
  341. package/dist/astro/routes/api/well-known/oauth-authorization-server.mjs +2 -2
  342. package/dist/astro/routes/api/well-known/oauth-protected-resource.mjs +2 -2
  343. package/dist/astro/routes/api/widget-areas/_name_/reorder.d.mts.map +1 -1
  344. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +10 -8
  345. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs.map +1 -1
  346. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.d.mts.map +1 -1
  347. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +18 -14
  348. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs.map +1 -1
  349. package/dist/astro/routes/api/widget-areas/_name_/widgets.d.mts.map +1 -1
  350. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +16 -13
  351. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs.map +1 -1
  352. package/dist/astro/routes/api/widget-areas/_name_.d.mts.map +1 -1
  353. package/dist/astro/routes/api/widget-areas/_name_.mjs +9 -7
  354. package/dist/astro/routes/api/widget-areas/_name_.mjs.map +1 -1
  355. package/dist/astro/routes/api/widget-areas/index.d.mts.map +1 -1
  356. package/dist/astro/routes/api/widget-areas/index.mjs +16 -13
  357. package/dist/astro/routes/api/widget-areas/index.mjs.map +1 -1
  358. package/dist/astro/routes/api/widget-components.mjs +2 -2
  359. package/dist/astro/routes/robots.txt.mjs +8 -8
  360. package/dist/astro/routes/sitemap-_collection_.xml.mjs +13 -12
  361. package/dist/astro/routes/sitemap-_collection_.xml.mjs.map +1 -1
  362. package/dist/astro/routes/sitemap.xml.mjs +9 -9
  363. package/dist/astro/types.d.mts +50 -20
  364. package/dist/astro/types.d.mts.map +1 -1
  365. package/dist/auth/providers/github.d.mts +1 -1
  366. package/dist/auth/providers/google.d.mts +1 -1
  367. package/dist/{authorize-ByYs-Uxs.mjs → authorize-C2QHlWSS.mjs} +2 -2
  368. package/dist/{authorize-ByYs-Uxs.mjs.map → authorize-C2QHlWSS.mjs.map} +1 -1
  369. package/dist/{backup-ChyHfIoX.mjs → backup-oS8ft5Cm.mjs} +5 -5
  370. package/dist/{backup-ChyHfIoX.mjs.map → backup-oS8ft5Cm.mjs.map} +1 -1
  371. package/dist/{bundle-DZFhFurR.mjs → bundle-CL0JjIPx.mjs} +4 -4
  372. package/dist/{bundle-DZFhFurR.mjs.map → bundle-CL0JjIPx.mjs.map} +1 -1
  373. package/dist/{byline-Cpnwrje1.mjs → byline-Vdi85CsZ.mjs} +27 -14
  374. package/dist/byline-Vdi85CsZ.mjs.map +1 -0
  375. package/dist/{byline-fields-CAyA_Umd.mjs → byline-fields-DPVRFMz2.mjs} +2 -2
  376. package/dist/{byline-fields-CAyA_Umd.mjs.map → byline-fields-DPVRFMz2.mjs.map} +1 -1
  377. package/dist/{byline-registry-Bpu9-MVs.mjs → byline-registry-BxDGIO0I.mjs} +2 -2
  378. package/dist/{byline-registry-Bpu9-MVs.mjs.map → byline-registry-BxDGIO0I.mjs.map} +1 -1
  379. package/dist/{bylines-BSo9B9RX.mjs → bylines-BX8QhcTk.mjs} +7 -7
  380. package/dist/{bylines-BSo9B9RX.mjs.map → bylines-BX8QhcTk.mjs.map} +1 -1
  381. package/dist/{bylines-CHjvehVX.mjs → bylines-w-E1IEQd.mjs} +3 -3
  382. package/dist/{bylines-CHjvehVX.mjs.map → bylines-w-E1IEQd.mjs.map} +1 -1
  383. package/dist/{cache-5VirJ2Cn.mjs → cache--7HKu5Xm.mjs} +4 -4
  384. package/dist/{cache-5VirJ2Cn.mjs.map → cache--7HKu5Xm.mjs.map} +1 -1
  385. package/dist/{capture-triggers-CNW1q3HK.mjs → capture-triggers-CeAsC76Z.mjs} +2 -2
  386. package/dist/{capture-triggers-CNW1q3HK.mjs.map → capture-triggers-CeAsC76Z.mjs.map} +1 -1
  387. package/dist/{challenge-store-D5pSY2S1.mjs → challenge-store-BIOak-tp.mjs} +5 -3
  388. package/dist/challenge-store-BIOak-tp.mjs.map +1 -0
  389. package/dist/chrome-tags-DzDQBCjX.mjs +24 -0
  390. package/dist/chrome-tags-DzDQBCjX.mjs.map +1 -0
  391. package/dist/{chunks-bNiX6_DR.mjs → chunks-VG_tyqnP.mjs} +2 -2
  392. package/dist/{chunks-bNiX6_DR.mjs.map → chunks-VG_tyqnP.mjs.map} +1 -1
  393. package/dist/cli/index.mjs +68 -40
  394. package/dist/cli/index.mjs.map +1 -1
  395. package/dist/client/cf-access.d.mts +1 -1
  396. package/dist/client/index.d.mts +17 -7
  397. package/dist/client/index.d.mts.map +1 -1
  398. package/dist/client/index.mjs +17 -12
  399. package/dist/client/index.mjs.map +1 -1
  400. package/dist/{collection-deletion-m_oi2c0N.mjs → collection-deletion-BCwaWTDw.mjs} +4 -4
  401. package/dist/{collection-deletion-m_oi2c0N.mjs.map → collection-deletion-BCwaWTDw.mjs.map} +1 -1
  402. package/dist/collection-slugs-cache-7lTmNzeA.mjs +85 -0
  403. package/dist/collection-slugs-cache-7lTmNzeA.mjs.map +1 -0
  404. package/dist/{comment-reaction-CRuItEjt.mjs → comment-reaction-CDyvPQRj.mjs} +2 -2
  405. package/dist/{comment-reaction-CRuItEjt.mjs.map → comment-reaction-CDyvPQRj.mjs.map} +1 -1
  406. package/dist/{comment-DhvLEdhQ.mjs → comment-vxOzWbZN.mjs} +2 -2
  407. package/dist/{comment-DhvLEdhQ.mjs.map → comment-vxOzWbZN.mjs.map} +1 -1
  408. package/dist/{comments-CLj4bi8I.mjs → comments-VzmVLyaC.mjs} +2 -2
  409. package/dist/{comments-CLj4bi8I.mjs.map → comments-VzmVLyaC.mjs.map} +1 -1
  410. package/dist/{components-v4U4DT2y.mjs → components-CL6Wkdk-.mjs} +1 -1
  411. package/dist/{components-v4U4DT2y.mjs.map → components-CL6Wkdk-.mjs.map} +1 -1
  412. package/dist/config--eWjQJE5.mjs +217 -0
  413. package/dist/config--eWjQJE5.mjs.map +1 -0
  414. package/dist/{index-DWbJrsAg.d.mts → config-CGAhyOjP.d.mts} +276 -76
  415. package/dist/config-CGAhyOjP.d.mts.map +1 -0
  416. package/dist/{config-DrfghTPe.d.mts → config-ChFzshGd.d.mts} +1 -1
  417. package/dist/{config-DrfghTPe.d.mts.map → config-ChFzshGd.d.mts.map} +1 -1
  418. package/dist/{content-CP-SeXNa.mjs → content-CNfMWuhY.mjs} +202 -46
  419. package/dist/content-CNfMWuhY.mjs.map +1 -0
  420. package/dist/{content-list-query-BhejKVqb.d.mts → content-list-query-B8d4UQp9.d.mts} +1 -1
  421. package/dist/{content-list-query-BhejKVqb.d.mts.map → content-list-query-B8d4UQp9.d.mts.map} +1 -1
  422. package/dist/{content-refresh-DLOfIhYc.mjs → content-refresh-GTMyi2Xy.mjs} +53 -26
  423. package/dist/content-refresh-GTMyi2Xy.mjs.map +1 -0
  424. package/dist/{content-repair-BCxzy0r4.mjs → content-repair-CIMt5C0U.mjs} +4 -4
  425. package/dist/{content-repair-BCxzy0r4.mjs.map → content-repair-CIMt5C0U.mjs.map} +1 -1
  426. package/dist/{context-BR5hRWiK.mjs → context-C9PB8vGd.mjs} +308 -33
  427. package/dist/context-C9PB8vGd.mjs.map +1 -0
  428. package/dist/{cron-CWfWrWKG.mjs → cron-DHAy9oyq.mjs} +1 -1
  429. package/dist/{cron-CWfWrWKG.mjs.map → cron-DHAy9oyq.mjs.map} +1 -1
  430. package/dist/{dashboard-CkIV2rnQ.mjs → dashboard-BNSvAN8A.mjs} +5 -5
  431. package/dist/{dashboard-CkIV2rnQ.mjs.map → dashboard-BNSvAN8A.mjs.map} +1 -1
  432. package/dist/db/index.d.mts +3 -3
  433. package/dist/db/index.mjs +2 -2
  434. package/dist/db/index.mjs.map +1 -1
  435. package/dist/db/libsql-migrations.d.mts +1 -1
  436. package/dist/db/libsql-migrations.mjs +5 -5
  437. package/dist/db/libsql.d.mts +1 -1
  438. package/dist/db/postgres-migrations.d.mts +1 -1
  439. package/dist/db/postgres-migrations.mjs +5 -5
  440. package/dist/db/postgres.d.mts +1 -1
  441. package/dist/db/postgres.d.mts.map +1 -1
  442. package/dist/db/postgres.mjs +19 -3
  443. package/dist/db/postgres.mjs.map +1 -1
  444. package/dist/db/sqlite-migrations.d.mts +1 -1
  445. package/dist/db/sqlite-migrations.mjs +5 -5
  446. package/dist/db/sqlite.d.mts +1 -1
  447. package/dist/db/sqlite.mjs +1 -1
  448. package/dist/{default-YMEfcQUx.mjs → default-ByZ0JqZo.mjs} +1 -1
  449. package/dist/{default-YMEfcQUx.mjs.map → default-ByZ0JqZo.mjs.map} +1 -1
  450. package/dist/{deferred-tasks-DfqxH5Xf.d.mts → deferred-tasks-Cu4NSJpa.d.mts} +1 -1
  451. package/dist/{deferred-tasks-DfqxH5Xf.d.mts.map → deferred-tasks-Cu4NSJpa.d.mts.map} +1 -1
  452. package/dist/dev-typegen-DHT7lcMU.mjs +29 -0
  453. package/dist/dev-typegen-DHT7lcMU.mjs.map +1 -0
  454. package/dist/{device-flow-CojjSBwb.mjs → device-flow-Cf6bhCCT.mjs} +4 -4
  455. package/dist/{device-flow-CojjSBwb.mjs.map → device-flow-Cf6bhCCT.mjs.map} +1 -1
  456. package/dist/{dialect-helpers-BSbfaO3F.mjs → dialect-helpers-BcQvkHgn.mjs} +83 -2
  457. package/dist/dialect-helpers-BcQvkHgn.mjs.map +1 -0
  458. package/dist/{direct-executor-BWeWiRYB.mjs → direct-executor-yAyUGSqB.mjs} +3 -3
  459. package/dist/{direct-executor-BWeWiRYB.mjs.map → direct-executor-yAyUGSqB.mjs.map} +1 -1
  460. package/dist/{dist-89xCrGqi.mjs → dist-BAsh8dbf.mjs} +1 -1
  461. package/dist/{dist-89xCrGqi.mjs.map → dist-BAsh8dbf.mjs.map} +1 -1
  462. package/dist/{email-console-CEJgR_LB.mjs → email-console-DNup1Fku.mjs} +1 -1
  463. package/dist/{email-console-CEJgR_LB.mjs.map → email-console-DNup1Fku.mjs.map} +1 -1
  464. package/dist/{enrich-BX0IDp4z.mjs → enrich-t2Xvjdqa.mjs} +3 -3
  465. package/dist/{enrich-BX0IDp4z.mjs.map → enrich-t2Xvjdqa.mjs.map} +1 -1
  466. package/dist/entry-lock-BEr8gDkG.mjs +163 -0
  467. package/dist/entry-lock-BEr8gDkG.mjs.map +1 -0
  468. package/dist/{relations-C7B46bcU.d.mts → entry-lock-CGAtrwAR.d.mts} +265 -76
  469. package/dist/entry-lock-CGAtrwAR.d.mts.map +1 -0
  470. package/dist/{redirects-CRIM55KH.mjs → entry-lock-DIYHAaSw.mjs} +112 -34
  471. package/dist/entry-lock-DIYHAaSw.mjs.map +1 -0
  472. package/dist/entry-locks-BEcX7ET0.mjs +167 -0
  473. package/dist/entry-locks-BEcX7ET0.mjs.map +1 -0
  474. package/dist/{error-D9w94fjV.mjs → error-BDcFyoRt.mjs} +2 -2
  475. package/dist/{error-D9w94fjV.mjs.map → error-BDcFyoRt.mjs.map} +1 -1
  476. package/dist/{errors-n2j49uNf.mjs → errors-DvMdNrgf.mjs} +10 -1
  477. package/dist/errors-DvMdNrgf.mjs.map +1 -0
  478. package/dist/{escape-DN4Qmjsl.mjs → escape-B3asJC6W.mjs} +1 -1
  479. package/dist/{escape-DN4Qmjsl.mjs.map → escape-B3asJC6W.mjs.map} +1 -1
  480. package/dist/{field-defs-cache-Bh4q6oar.mjs → field-defs-cache-Cf5FHK0M.mjs} +5 -5
  481. package/dist/{field-defs-cache-Bh4q6oar.mjs.map → field-defs-cache-Cf5FHK0M.mjs.map} +1 -1
  482. package/dist/{fts-manager-BhOdW0bi.mjs → fts-manager-iddym8cd.mjs} +4 -4
  483. package/dist/{fts-manager-BhOdW0bi.mjs.map → fts-manager-iddym8cd.mjs.map} +1 -1
  484. package/dist/{hash-CTcngWvj.mjs → hash-BRweX6jz.mjs} +1 -1
  485. package/dist/{hash-CTcngWvj.mjs.map → hash-BRweX6jz.mjs.map} +1 -1
  486. package/dist/hook-result-BrshYHLx.d.mts +31 -0
  487. package/dist/hook-result-BrshYHLx.d.mts.map +1 -0
  488. package/dist/{hreflang-7pTHsLZJ.d.mts → hreflang-CQpu5bMy.d.mts} +2 -2
  489. package/dist/{hreflang-7pTHsLZJ.d.mts.map → hreflang-CQpu5bMy.d.mts.map} +1 -1
  490. package/dist/{hreflang-Huc6O5wa.mjs → hreflang-DshnweTC.mjs} +9 -8
  491. package/dist/{hreflang-Huc6O5wa.mjs.map → hreflang-DshnweTC.mjs.map} +1 -1
  492. package/dist/{identity-DXmb4aVp.mjs → identity-CjGKDq8J.mjs} +3 -3
  493. package/dist/{identity-DXmb4aVp.mjs.map → identity-CjGKDq8J.mjs.map} +1 -1
  494. package/dist/{import-C4_O3KXU.mjs → import-D96g2otw.mjs} +6 -6
  495. package/dist/{import-C4_O3KXU.mjs.map → import-D96g2otw.mjs.map} +1 -1
  496. package/dist/{index-6bRee8zb.d.mts → index-1ECYpfiF.d.mts} +3 -3
  497. package/dist/{index-6bRee8zb.d.mts.map → index-1ECYpfiF.d.mts.map} +1 -1
  498. package/dist/index.d.mts +22 -21
  499. package/dist/index.mjs +84 -81
  500. package/dist/{init-lock-DJkX6Hto.mjs → init-lock-CFNBe_iH.mjs} +1 -1
  501. package/dist/{init-lock-DJkX6Hto.mjs.map → init-lock-CFNBe_iH.mjs.map} +1 -1
  502. package/dist/{load-Bo7fZAbg.mjs → load-DPtY9cZo.mjs} +2 -2
  503. package/dist/{load-Bo7fZAbg.mjs.map → load-DPtY9cZo.mjs.map} +1 -1
  504. package/dist/{loader-ZsjE4paL.mjs → loader-WJi6GFRn.mjs} +90 -17
  505. package/dist/loader-WJi6GFRn.mjs.map +1 -0
  506. package/dist/{manifest-builder-QXuqvVMP.mjs → manifest-builder-BfNlGQIA.mjs} +2 -2
  507. package/dist/{manifest-builder-QXuqvVMP.mjs.map → manifest-builder-BfNlGQIA.mjs.map} +1 -1
  508. package/dist/{manifest-schema-CUYPfCEH.mjs → manifest-schema-CILooI5J.mjs} +5 -5
  509. package/dist/manifest-schema-CILooI5J.mjs.map +1 -0
  510. package/dist/media/image-endpoint.d.mts +4 -2
  511. package/dist/media/image-endpoint.d.mts.map +1 -1
  512. package/dist/media/image-endpoint.mjs +6 -4
  513. package/dist/media/image-endpoint.mjs.map +1 -1
  514. package/dist/media/index.d.mts +1 -1
  515. package/dist/media/index.mjs +3 -3
  516. package/dist/media/local-runtime.d.mts +12 -12
  517. package/dist/media/local-runtime.mjs +7 -7
  518. package/dist/{media-D6SeAfBl.mjs → media-BBm8Wg3f.mjs} +30 -2
  519. package/dist/media-BBm8Wg3f.mjs.map +1 -0
  520. package/dist/{media-BjwNuLEu.mjs → media-C1EIZKh1.mjs} +35 -5
  521. package/dist/media-C1EIZKh1.mjs.map +1 -0
  522. package/dist/{media-allowlist-D35v7bmL.mjs → media-allowlist-elXJgb_K.mjs} +2 -2
  523. package/dist/{media-allowlist-D35v7bmL.mjs.map → media-allowlist-elXJgb_K.mjs.map} +1 -1
  524. package/dist/{media-folders-D-0CmRZj.mjs → media-folders-DASfX_DH.mjs} +1 -1
  525. package/dist/{media-folders-D-0CmRZj.mjs.map → media-folders-DASfX_DH.mjs.map} +1 -1
  526. package/dist/{media-upload-C7bLXGcI.mjs → media-upload-C7_AQJ5v.mjs} +9 -9
  527. package/dist/{media-upload-C7bLXGcI.mjs.map → media-upload-C7_AQJ5v.mjs.map} +1 -1
  528. package/dist/{media-url-DH7giMx_.mjs → media-url-8dVl1loq.mjs} +19 -2
  529. package/dist/media-url-8dVl1loq.mjs.map +1 -0
  530. package/dist/{media-usage-BTRJvS6V.mjs → media-usage-C1EswMTq.mjs} +10 -10
  531. package/dist/{media-usage-BTRJvS6V.mjs.map → media-usage-C1EswMTq.mjs.map} +1 -1
  532. package/dist/{media-usage-activation-Dx0kPV6b.mjs → media-usage-activation-CrHNltlL.mjs} +3 -3
  533. package/dist/{media-usage-activation-Dx0kPV6b.mjs.map → media-usage-activation-CrHNltlL.mjs.map} +1 -1
  534. package/dist/{media-usage-work-C-fhM30c.mjs → media-usage-work-C5B1zT1c.mjs} +2 -2
  535. package/dist/{media-usage-work-C-fhM30c.mjs.map → media-usage-work-C5B1zT1c.mjs.map} +1 -1
  536. package/dist/{media-usage-work-DWb2XPMI.mjs → media-usage-work-IkQx_Yz6.mjs} +4 -4
  537. package/dist/{media-usage-work-DWb2XPMI.mjs.map → media-usage-work-IkQx_Yz6.mjs.map} +1 -1
  538. package/dist/{media-usage-write-fence-BwoJVRDC.mjs → media-usage-write-fence-B9anjOSg.mjs} +3 -3
  539. package/dist/{media-usage-write-fence-BwoJVRDC.mjs.map → media-usage-write-fence-B9anjOSg.mjs.map} +1 -1
  540. package/dist/{menus-CNg0QlDt.mjs → menus-D8mC4eaN.mjs} +406 -175
  541. package/dist/menus-D8mC4eaN.mjs.map +1 -0
  542. package/dist/{menus-CD7EFLwz.mjs → menus-UdwjHZJC.mjs} +12 -4
  543. package/dist/{menus-CD7EFLwz.mjs.map → menus-UdwjHZJC.mjs.map} +1 -1
  544. package/dist/migrations/index.d.mts +1 -1
  545. package/dist/migrations/index.mjs +4 -4
  546. package/dist/{mime-CUIG6x84.mjs → mime-DYpsOAny.mjs} +1 -1
  547. package/dist/{mime-CUIG6x84.mjs.map → mime-DYpsOAny.mjs.map} +1 -1
  548. package/dist/{mode-DaUM_MB2.mjs → mode-Dm4BHhRH.mjs} +1 -1
  549. package/dist/{mode-DaUM_MB2.mjs.map → mode-Dm4BHhRH.mjs.map} +1 -1
  550. package/dist/{node-sqlite-compat-Udb4Y-rs.mjs → node-sqlite-compat-2sezm-Zd.mjs} +1 -1
  551. package/dist/{node-sqlite-compat-Udb4Y-rs.mjs.map → node-sqlite-compat-2sezm-Zd.mjs.map} +1 -1
  552. package/dist/{normalize-CSxdKBVa.mjs → normalize-4nkKGsuW.mjs} +15 -5
  553. package/dist/normalize-4nkKGsuW.mjs.map +1 -0
  554. package/dist/{oauth-authorization-Dpsb-fMJ.mjs → oauth-authorization-BxE_lURD.mjs} +4 -4
  555. package/dist/{oauth-authorization-Dpsb-fMJ.mjs.map → oauth-authorization-BxE_lURD.mjs.map} +1 -1
  556. package/dist/{oauth-clients-Bxnoe_67.mjs → oauth-clients-DJIdOdq0.mjs} +1 -1
  557. package/dist/{oauth-clients-Bxnoe_67.mjs.map → oauth-clients-DJIdOdq0.mjs.map} +1 -1
  558. package/dist/{oauth-state-store-0C4s0K6w.mjs → oauth-state-store-CsdxP57n.mjs} +1 -1
  559. package/dist/{oauth-state-store-0C4s0K6w.mjs.map → oauth-state-store-CsdxP57n.mjs.map} +1 -1
  560. package/dist/{oauth-user-lookup-wlGYSeqX.mjs → oauth-user-lookup-HzzW-dkF.mjs} +1 -1
  561. package/dist/{oauth-user-lookup-wlGYSeqX.mjs.map → oauth-user-lookup-HzzW-dkF.mjs.map} +1 -1
  562. package/dist/object-cache/memory.d.mts +1 -1
  563. package/dist/{object-cache-71tPfV4A.mjs → object-cache-DVKnyOfy.mjs} +19 -3
  564. package/dist/object-cache-DVKnyOfy.mjs.map +1 -0
  565. package/dist/{options-BHPeIbBd.mjs → options-D1FBiAv1.mjs} +60 -5
  566. package/dist/options-D1FBiAv1.mjs.map +1 -0
  567. package/dist/{options-BhZIeFY1.d.mts → options-D8Y0VHc7.d.mts} +30 -11
  568. package/dist/options-D8Y0VHc7.d.mts.map +1 -0
  569. package/dist/page/index.d.mts +2 -2
  570. package/dist/page/index.d.mts.map +1 -1
  571. package/dist/page/index.mjs +12 -0
  572. package/dist/page/index.mjs.map +1 -1
  573. package/dist/{parse-BRJg1kz8.mjs → parse-WRg5C3NX.mjs} +2 -2
  574. package/dist/{parse-BRJg1kz8.mjs.map → parse-WRg5C3NX.mjs.map} +1 -1
  575. package/dist/{passkey-config-B3P0nHRR.mjs → passkey-config-qIdO-wF6.mjs} +1 -1
  576. package/dist/{passkey-config-B3P0nHRR.mjs.map → passkey-config-qIdO-wF6.mjs.map} +1 -1
  577. package/dist/{patterns-D9iDO3j8.mjs → patterns-DC8CLptu.mjs} +1 -1
  578. package/dist/{patterns-D9iDO3j8.mjs.map → patterns-DC8CLptu.mjs.map} +1 -1
  579. package/dist/{placeholder-BR4ZhVJl.d.mts → placeholder-COrvARyD.d.mts} +1 -1
  580. package/dist/{placeholder-BR4ZhVJl.d.mts.map → placeholder-COrvARyD.d.mts.map} +1 -1
  581. package/dist/plugin-types.d.mts +8 -3
  582. package/dist/plugin-types.d.mts.map +1 -1
  583. package/dist/plugin-utils.d.mts +10 -10
  584. package/dist/plugins/adapt-sandbox-entry.d.mts +10 -10
  585. package/dist/plugins/adapt-sandbox-entry.mjs +2 -2
  586. package/dist/{policy-BVRganJQ.mjs → policy-XCfb-IE9.mjs} +2 -2
  587. package/dist/{policy-BVRganJQ.mjs.map → policy-XCfb-IE9.mjs.map} +1 -1
  588. package/dist/{portable-text-C8Tvp4_g.mjs → portable-text-BS3d5n-0.mjs} +1 -1
  589. package/dist/{portable-text-C8Tvp4_g.mjs.map → portable-text-BS3d5n-0.mjs.map} +1 -1
  590. package/dist/{preview-dn2dUyM0.mjs → preview-BxwsGgGp.mjs} +2 -2
  591. package/dist/{preview-dn2dUyM0.mjs.map → preview-BxwsGgGp.mjs.map} +1 -1
  592. package/dist/{protocol-CuBEsqgE.d.mts → protocol-CLn58-nw.d.mts} +2 -2
  593. package/dist/{protocol-CuBEsqgE.d.mts.map → protocol-CLn58-nw.d.mts.map} +1 -1
  594. package/dist/{public-url-DRz_AinV.mjs → public-url-FWWAvnre.mjs} +1 -1
  595. package/dist/{public-url-DRz_AinV.mjs.map → public-url-FWWAvnre.mjs.map} +1 -1
  596. package/dist/{query-D18vTdha.mjs → query-DygOte9M.mjs} +26 -17
  597. package/dist/query-DygOte9M.mjs.map +1 -0
  598. package/dist/{query-tZDEdtCN.mjs → query-gtXT03Wc.mjs} +5 -5
  599. package/dist/{query-tZDEdtCN.mjs.map → query-gtXT03Wc.mjs.map} +1 -1
  600. package/dist/{rate-limit-on7KPo-v.mjs → rate-limit-CQUPm0dh.mjs} +2 -2
  601. package/dist/{rate-limit-on7KPo-v.mjs.map → rate-limit-CQUPm0dh.mjs.map} +1 -1
  602. package/dist/{redirect-DrbEmU9a.mjs → redirect-D1cWafi6.mjs} +1 -1
  603. package/dist/{redirect-DrbEmU9a.mjs.map → redirect-D1cWafi6.mjs.map} +1 -1
  604. package/dist/{redirect-CZkbozu9.mjs → redirect-DId44BS1.mjs} +19 -6
  605. package/dist/redirect-DId44BS1.mjs.map +1 -0
  606. package/dist/{redirects-BahWiu8Z.mjs → redirects-DN-ZE33W.mjs} +5 -5
  607. package/dist/{redirects-BahWiu8Z.mjs.map → redirects-DN-ZE33W.mjs.map} +1 -1
  608. package/dist/{registry-Cx-jEJOS.mjs → registry-DTqaqxed.mjs} +46 -12
  609. package/dist/registry-DTqaqxed.mjs.map +1 -0
  610. package/dist/{relation-A6wLF_DS.mjs → relation-DxgCHOBw.mjs} +2 -2
  611. package/dist/{relation-A6wLF_DS.mjs.map → relation-DxgCHOBw.mjs.map} +1 -1
  612. package/dist/{relations-Cj5hZ6Zg.mjs → relations-KKDSLUwS.mjs} +4 -4
  613. package/dist/{relations-Cj5hZ6Zg.mjs.map → relations-KKDSLUwS.mjs.map} +1 -1
  614. package/dist/{relations-BTPM2saV.mjs → relations-rOmbndUJ.mjs} +8 -8
  615. package/dist/relations-rOmbndUJ.mjs.map +1 -0
  616. package/dist/{request-cache-DH9zdCOD.mjs → request-cache-DAZZmesc.mjs} +1 -1
  617. package/dist/{request-cache-DH9zdCOD.mjs.map → request-cache-DAZZmesc.mjs.map} +1 -1
  618. package/dist/request-context.d.mts +1 -1
  619. package/dist/{request-meta-DRp5ENd_.mjs → request-meta-BgjUQLQ-.mjs} +2 -2
  620. package/dist/{request-meta-DRp5ENd_.mjs.map → request-meta-BgjUQLQ-.mjs.map} +1 -1
  621. package/dist/{resolve-DxUpTMmE.mjs → resolve-Cy0aWSRj.mjs} +37 -4
  622. package/dist/resolve-Cy0aWSRj.mjs.map +1 -0
  623. package/dist/{runner-zgqA_CqP.d.mts → runner-CfwysRM0.d.mts} +3 -2
  624. package/dist/runner-CfwysRM0.d.mts.map +1 -0
  625. package/dist/{runner-77GOZCnH.mjs → runner-nEzvnogG.mjs} +476 -295
  626. package/dist/runner-nEzvnogG.mjs.map +1 -0
  627. package/dist/runtime.d.mts +11 -11
  628. package/dist/runtime.mjs +3 -2
  629. package/dist/runtime.mjs.map +1 -1
  630. package/dist/{schema-BY-oVntF.mjs → schema-CRu38Pr5.mjs} +3 -3
  631. package/dist/{schema-BY-oVntF.mjs.map → schema-CRu38Pr5.mjs.map} +1 -1
  632. package/dist/{schema-Cw9kVK0I.mjs → schema-DifxndJx.mjs} +5 -5
  633. package/dist/{schema-Cw9kVK0I.mjs.map → schema-DifxndJx.mjs.map} +1 -1
  634. package/dist/{scopes-vMR1uIbt.mjs → scopes-D5A1OZbq.mjs} +3 -3
  635. package/dist/{scopes-vMR1uIbt.mjs.map → scopes-D5A1OZbq.mjs.map} +1 -1
  636. package/dist/{search-CfT3KxO5.mjs → search-DEPFSBFq.mjs} +4 -4
  637. package/dist/{search-CfT3KxO5.mjs.map → search-DEPFSBFq.mjs.map} +1 -1
  638. package/dist/{secrets-BH2Qow1-.mjs → secrets-CdfzLdoO.mjs} +3 -3
  639. package/dist/{secrets-BH2Qow1-.mjs.map → secrets-CdfzLdoO.mjs.map} +1 -1
  640. package/dist/{sections-DTfjyf1z.mjs → sections-3X52kmIR.mjs} +2 -2
  641. package/dist/{sections-DTfjyf1z.mjs.map → sections-3X52kmIR.mjs.map} +1 -1
  642. package/dist/seed/index.d.mts +2 -2
  643. package/dist/seed/index.mjs +28 -26
  644. package/dist/seo/index.d.mts +3 -3
  645. package/dist/seo/index.d.mts.map +1 -1
  646. package/dist/seo/index.mjs +20 -21
  647. package/dist/seo/index.mjs.map +1 -1
  648. package/dist/{seo-Cm-dtvgk.mjs → seo-Bw68KxRc.mjs} +3 -3
  649. package/dist/{seo-Cm-dtvgk.mjs.map → seo-Bw68KxRc.mjs.map} +1 -1
  650. package/dist/{seo-BSiTIXzd.mjs → seo-C4AmbsMU.mjs} +3 -2
  651. package/dist/seo-C4AmbsMU.mjs.map +1 -0
  652. package/dist/{service-DYsDHEKe.mjs → service-J_-Vgo7R.mjs} +3 -3
  653. package/dist/{service-DYsDHEKe.mjs.map → service-J_-Vgo7R.mjs.map} +1 -1
  654. package/dist/{session-user-CNAfvsdw.mjs → session-user-CbnMMwk6.mjs} +1 -1
  655. package/dist/{session-user-CNAfvsdw.mjs.map → session-user-CbnMMwk6.mjs.map} +1 -1
  656. package/dist/{settings-DjtkUo__.mjs → settings-AnEFYICn.mjs} +3 -3
  657. package/dist/{settings-DjtkUo__.mjs.map → settings-AnEFYICn.mjs.map} +1 -1
  658. package/dist/{settings-BgN-0DT-.mjs → settings-DcMjREe5.mjs} +21 -8
  659. package/dist/settings-DcMjREe5.mjs.map +1 -0
  660. package/dist/{setup-complete-CcpXaPU7.mjs → setup-complete-BClXXTvr.mjs} +2 -2
  661. package/dist/{setup-complete-CcpXaPU7.mjs.map → setup-complete-BClXXTvr.mjs.map} +1 -1
  662. package/dist/{setup-nonce-Reyw30jg.mjs → setup-nonce-BheRa4RG.mjs} +1 -1
  663. package/dist/{setup-nonce-Reyw30jg.mjs.map → setup-nonce-BheRa4RG.mjs.map} +1 -1
  664. package/dist/{single-flight-cache-BPuGPdcN.mjs → single-flight-cache-jaswDzmQ.mjs} +2 -2
  665. package/dist/{single-flight-cache-BPuGPdcN.mjs.map → single-flight-cache-jaswDzmQ.mjs.map} +1 -1
  666. package/dist/{site-url-Cs_V9n3V.mjs → site-url-Bqf-ea3N.mjs} +3 -3
  667. package/dist/{site-url-Cs_V9n3V.mjs.map → site-url-Bqf-ea3N.mjs.map} +1 -1
  668. package/dist/{snapshot-DSB8P7Lm.mjs → snapshot-C4CtXntb.mjs} +51 -35
  669. package/dist/snapshot-C4CtXntb.mjs.map +1 -0
  670. package/dist/{ssrf-DqebVE34.mjs → ssrf-gl4gFNhw.mjs} +151 -93
  671. package/dist/ssrf-gl4gFNhw.mjs.map +1 -0
  672. package/dist/{state-BJfU9Uzw.mjs → state-1F6IOhdQ.mjs} +1 -1
  673. package/dist/{state-BJfU9Uzw.mjs.map → state-1F6IOhdQ.mjs.map} +1 -1
  674. package/dist/{status-DDu8HIQl.mjs → status-Cenfk_r5.mjs} +1 -1
  675. package/dist/{status-DDu8HIQl.mjs.map → status-Cenfk_r5.mjs.map} +1 -1
  676. package/dist/storage/local.d.mts +2 -1
  677. package/dist/storage/local.d.mts.map +1 -1
  678. package/dist/storage/local.mjs +1 -1
  679. package/dist/storage/local.mjs.map +1 -1
  680. package/dist/storage/s3.d.mts +2 -1
  681. package/dist/storage/s3.d.mts.map +1 -1
  682. package/dist/storage/s3.mjs +3 -2
  683. package/dist/storage/s3.mjs.map +1 -1
  684. package/dist/{target-D0o26Azo.mjs → target-CRzeTs8G.mjs} +1 -1
  685. package/dist/{target-D0o26Azo.mjs.map → target-CRzeTs8G.mjs.map} +1 -1
  686. package/dist/{taxonomies-CPGxo-bn.mjs → taxonomies-BOdxuZpV.mjs} +23 -13
  687. package/dist/taxonomies-BOdxuZpV.mjs.map +1 -0
  688. package/dist/{taxonomies-kmyudNGP.mjs → taxonomies-NcFDq5Gg.mjs} +58 -23
  689. package/dist/taxonomies-NcFDq5Gg.mjs.map +1 -0
  690. package/dist/{taxonomy-8X09dLN5.mjs → taxonomy-DP1vny4K.mjs} +12 -4
  691. package/dist/{taxonomy-8X09dLN5.mjs.map → taxonomy-DP1vny4K.mjs.map} +1 -1
  692. package/dist/{tokens-gTS-IVUp.mjs → tokens-CDk8ox9p.mjs} +1 -1
  693. package/dist/{tokens-gTS-IVUp.mjs.map → tokens-CDk8ox9p.mjs.map} +1 -1
  694. package/dist/{transport-_6R1ub7t.d.mts → transport-BVn4tVb9.d.mts} +1 -1
  695. package/dist/{transport-_6R1ub7t.d.mts.map → transport-BVn4tVb9.d.mts.map} +1 -1
  696. package/dist/{transport-fX59xaJz.mjs → transport-DP0JI-8i.mjs} +1 -1
  697. package/dist/{transport-fX59xaJz.mjs.map → transport-DP0JI-8i.mjs.map} +1 -1
  698. package/dist/{trusted-proxy-fe6nEgR4.mjs → trusted-proxy-BTM6UxqD.mjs} +1 -1
  699. package/dist/{trusted-proxy-fe6nEgR4.mjs.map → trusted-proxy-BTM6UxqD.mjs.map} +1 -1
  700. package/dist/{types-D_DWe7k9.d.mts → types-2n848aVW.d.mts} +3 -2
  701. package/dist/types-2n848aVW.d.mts.map +1 -0
  702. package/dist/types-A2cN6a4a.mjs +3 -0
  703. package/dist/{types-75KIqzL9.mjs → types-BMXnRIrX.mjs} +4 -2
  704. package/dist/types-BMXnRIrX.mjs.map +1 -0
  705. package/dist/{types-Vg6f5i3s.d.mts → types-BouXpOsa.d.mts} +121 -4
  706. package/dist/types-BouXpOsa.d.mts.map +1 -0
  707. package/dist/{types-BXUmsINL.mjs → types-ByG2coLw.mjs} +1 -1
  708. package/dist/{types-BXUmsINL.mjs.map → types-ByG2coLw.mjs.map} +1 -1
  709. package/dist/types-CQPWhPxE.mjs.map +1 -1
  710. package/dist/{types-Blb-MRC3.d.mts → types-DEfNJ__A.d.mts} +1 -1
  711. package/dist/{types-Blb-MRC3.d.mts.map → types-DEfNJ__A.d.mts.map} +1 -1
  712. package/dist/{types-Br-ERaxh.d.mts → types-DKcKSbtB.d.mts} +23 -7
  713. package/dist/types-DKcKSbtB.d.mts.map +1 -0
  714. package/dist/{types-BzBd3PeX.d.mts → types-DRYs7uTL.d.mts} +1 -1
  715. package/dist/{types-BzBd3PeX.d.mts.map → types-DRYs7uTL.d.mts.map} +1 -1
  716. package/dist/{types-CLqvnd05.d.mts → types-DaEg7KX2.d.mts} +1 -1
  717. package/dist/{types-CLqvnd05.d.mts.map → types-DaEg7KX2.d.mts.map} +1 -1
  718. package/dist/{types-DJQxln7q.d.mts → types-LU8utpP_.d.mts} +14 -10
  719. package/dist/types-LU8utpP_.d.mts.map +1 -0
  720. package/dist/{types-D5VVLr7J.d.mts → types-VpYfPUxN.d.mts} +1 -1
  721. package/dist/{types-D5VVLr7J.d.mts.map → types-VpYfPUxN.d.mts.map} +1 -1
  722. package/dist/{types-DM3vioBY.mjs → types-c9GP7Dj5.mjs} +1 -1
  723. package/dist/{types-DM3vioBY.mjs.map → types-c9GP7Dj5.mjs.map} +1 -1
  724. package/dist/{types-DHxzBjbD.d.mts → types-tJWDK__M.d.mts} +14 -1
  725. package/dist/types-tJWDK__M.d.mts.map +1 -0
  726. package/dist/{upload-attempts-CNyGSepg.mjs → upload-attempts-C6S2y-lp.mjs} +1 -1
  727. package/dist/{upload-attempts-CNyGSepg.mjs.map → upload-attempts-C6S2y-lp.mjs.map} +1 -1
  728. package/dist/{url-pattern-K-KdXcSe.mjs → url-pattern-UYtxVTuj.mjs} +1 -1
  729. package/dist/{url-pattern-K-KdXcSe.mjs.map → url-pattern-UYtxVTuj.mjs.map} +1 -1
  730. package/dist/{user-CtYY0tp2.mjs → user-DIsIXogT.mjs} +2 -2
  731. package/dist/{user-CtYY0tp2.mjs.map → user-DIsIXogT.mjs.map} +1 -1
  732. package/dist/{utils-HztC73hq.mjs → utils-BicP5Qbg.mjs} +2 -2
  733. package/dist/{utils-HztC73hq.mjs.map → utils-BicP5Qbg.mjs.map} +1 -1
  734. package/dist/{validate-Dd-IUjnZ.mjs → validate-D8VPn4Hv.mjs} +8 -3
  735. package/dist/validate-D8VPn4Hv.mjs.map +1 -0
  736. package/dist/{validate-DlqdOZXB.d.mts → validate-Df6Dvwbw.d.mts} +12 -7
  737. package/dist/validate-Df6Dvwbw.d.mts.map +1 -0
  738. package/dist/{validation-D83n7Npi.mjs → validation-CzMJn9Ku.mjs} +13 -11
  739. package/dist/{validation-D83n7Npi.mjs.map → validation-CzMJn9Ku.mjs.map} +1 -1
  740. package/dist/version-CK67_SXX.mjs +7 -0
  741. package/dist/{version-ri-sCyAp.mjs.map → version-CK67_SXX.mjs.map} +1 -1
  742. package/dist/{widgets-CpmZd9Q-.mjs → widgets-RFVAxQl3.mjs} +18 -5
  743. package/dist/widgets-RFVAxQl3.mjs.map +1 -0
  744. package/dist/{wxr-taxonomies-BFd0y72_.d.mts → wxr-taxonomies-BX4yQL9s.d.mts} +1 -1
  745. package/dist/{wxr-taxonomies-BFd0y72_.d.mts.map → wxr-taxonomies-BX4yQL9s.d.mts.map} +1 -1
  746. package/dist/{wxr-taxonomies-Df4vxWcU.mjs → wxr-taxonomies-Csdp7yde.mjs} +4 -4
  747. package/dist/{wxr-taxonomies-Df4vxWcU.mjs.map → wxr-taxonomies-Csdp7yde.mjs.map} +1 -1
  748. package/dist/{zod-generator-DylzusHh.mjs → zod-generator-CNRGdnBY.mjs} +11 -7
  749. package/dist/zod-generator-CNRGdnBY.mjs.map +1 -0
  750. package/package.json +16 -11
  751. package/src/api/errors.ts +9 -0
  752. package/src/api/handlers/content.ts +115 -90
  753. package/src/api/handlers/entry-lock.ts +206 -0
  754. package/src/api/handlers/index.ts +1 -0
  755. package/src/api/handlers/manifest.ts +162 -12
  756. package/src/api/handlers/marketplace.ts +28 -20
  757. package/src/api/handlers/media.ts +30 -0
  758. package/src/api/handlers/menus.ts +9 -0
  759. package/src/api/handlers/registry.ts +406 -297
  760. package/src/api/handlers/revision.ts +2 -1
  761. package/src/api/handlers/seo.ts +10 -1
  762. package/src/api/handlers/snapshot.ts +84 -72
  763. package/src/api/handlers/taxonomies.ts +25 -9
  764. package/src/api/openapi/document.ts +196 -11
  765. package/src/api/parse.ts +1 -1
  766. package/src/api/schemas/auth.ts +4 -4
  767. package/src/api/schemas/bylines.ts +3 -3
  768. package/src/api/schemas/comments.ts +1 -1
  769. package/src/api/schemas/common.ts +3 -2
  770. package/src/api/schemas/content.ts +86 -22
  771. package/src/api/schemas/entry-lock.ts +48 -0
  772. package/src/api/schemas/index.ts +1 -0
  773. package/src/api/schemas/media.ts +52 -0
  774. package/src/api/schemas/redirects.ts +6 -1
  775. package/src/api/schemas/schema.ts +14 -1
  776. package/src/api/schemas/setup.ts +1 -1
  777. package/src/api/schemas/taxonomies.ts +2 -2
  778. package/src/api/schemas/users.ts +1 -1
  779. package/src/api/types.ts +25 -10
  780. package/src/astro/dev-typegen.ts +35 -0
  781. package/src/astro/image-endpoint.ts +2 -2
  782. package/src/astro/integration/dev-typegen.ts +91 -0
  783. package/src/astro/integration/index.ts +18 -50
  784. package/src/astro/integration/routes.ts +10 -0
  785. package/src/astro/integration/runtime.ts +13 -5
  786. package/src/astro/integration/vite-config.ts +51 -2
  787. package/src/astro/middleware.ts +21 -0
  788. package/src/astro/routes/api/admin/api-tokens/index.ts +4 -1
  789. package/src/astro/routes/api/admin/oauth-clients/[id].ts +1 -1
  790. package/src/astro/routes/api/admin/oauth-clients/index.ts +1 -1
  791. package/src/astro/routes/api/admin/plugins/registry/[id]/update.ts +4 -0
  792. package/src/astro/routes/api/admin/plugins/registry/artifact.ts +3 -7
  793. package/src/astro/routes/api/admin/plugins/registry/install.ts +4 -0
  794. package/src/astro/routes/api/admin/plugins/registry/verify.ts +60 -0
  795. package/src/astro/routes/api/content/[collection]/[id]/discard-draft.ts +18 -2
  796. package/src/astro/routes/api/content/[collection]/[id]/lock.ts +133 -0
  797. package/src/astro/routes/api/content/[collection]/[id]/publish.ts +12 -1
  798. package/src/astro/routes/api/content/[collection]/[id]/schedule.ts +20 -0
  799. package/src/astro/routes/api/content/[collection]/[id]/unpublish.ts +16 -2
  800. package/src/astro/routes/api/content/[collection]/[id].ts +27 -2
  801. package/src/astro/routes/api/content/[collection]/index.ts +3 -0
  802. package/src/astro/routes/api/manifest.ts +1 -1
  803. package/src/astro/routes/api/media/[id]/replace.ts +114 -0
  804. package/src/astro/routes/api/media/file/[...key].ts +4 -1
  805. package/src/astro/routes/api/media/upload-url.ts +8 -4
  806. package/src/astro/routes/api/media.ts +54 -8
  807. package/src/astro/routes/api/menus/[name]/items/[id].ts +7 -2
  808. package/src/astro/routes/api/menus/[name]/items.ts +4 -1
  809. package/src/astro/routes/api/menus/[name]/reorder.ts +4 -1
  810. package/src/astro/routes/api/menus/[name]/translations.ts +4 -1
  811. package/src/astro/routes/api/menus/[name].ts +7 -2
  812. package/src/astro/routes/api/menus/index.ts +4 -1
  813. package/src/astro/routes/api/settings/email.ts +1 -1
  814. package/src/astro/routes/api/settings.ts +4 -1
  815. package/src/astro/routes/api/taxonomies/[name]/reorder.ts +4 -1
  816. package/src/astro/routes/api/taxonomies/[name]/terms/[slug]/translations.ts +4 -1
  817. package/src/astro/routes/api/taxonomies/[name]/terms/[slug].ts +7 -2
  818. package/src/astro/routes/api/taxonomies/[name]/terms/index.ts +4 -1
  819. package/src/astro/routes/api/taxonomies/[name].ts +7 -2
  820. package/src/astro/routes/api/taxonomies/index.ts +4 -1
  821. package/src/astro/routes/api/widget-areas/[name]/reorder.ts +3 -1
  822. package/src/astro/routes/api/widget-areas/[name]/widgets/[id].ts +5 -2
  823. package/src/astro/routes/api/widget-areas/[name]/widgets.ts +3 -1
  824. package/src/astro/routes/api/widget-areas/[name].ts +3 -1
  825. package/src/astro/routes/api/widget-areas/index.ts +3 -1
  826. package/src/astro/routes/sitemap-[collection].xml.ts +4 -0
  827. package/src/astro/types.ts +36 -8
  828. package/src/auth/challenge-store.ts +3 -1
  829. package/src/aws-sdk.d.ts +1 -0
  830. package/src/cache/chrome-tags.ts +24 -0
  831. package/src/cli/commands/content.ts +31 -5
  832. package/src/cli/commands/export-seed.ts +2 -0
  833. package/src/client/index.ts +34 -7
  834. package/src/components/EmDashBodyEnd.astro +4 -1
  835. package/src/components/EmDashBodyStart.astro +4 -1
  836. package/src/components/EmDashHead.astro +35 -16
  837. package/src/components/EmDashImage.astro +2 -1
  838. package/src/components/EmDashMedia.astro +2 -1
  839. package/src/components/Gallery.astro +18 -4
  840. package/src/components/InlineEditor.astro +3 -1
  841. package/src/components/InlinePortableTextEditor.tsx +112 -12
  842. package/src/components/PortableText.astro +4 -0
  843. package/src/components/Table.astro +147 -62
  844. package/src/components/widgets/Archives.astro +2 -37
  845. package/src/config/errors.ts +13 -0
  846. package/src/content/converters/index.ts +2 -0
  847. package/src/content/converters/mark-safety.ts +1 -0
  848. package/src/content/converters/portable-text-identity.ts +139 -0
  849. package/src/content/converters/portable-text-to-prosemirror.ts +226 -69
  850. package/src/content/converters/prosemirror-to-portable-text.ts +128 -28
  851. package/src/content/converters/types.ts +11 -0
  852. package/src/database/dialect-helpers.ts +125 -0
  853. package/src/database/migrations/017_authorization_codes.ts +14 -4
  854. package/src/database/migrations/074_content_deleted_scheduled_index.ts +55 -0
  855. package/src/database/migrations/075_entry_edit_locks.ts +44 -0
  856. package/src/database/migrations/076_collection_nav_group.ts +22 -0
  857. package/src/database/migrations/077_plugin_storage_revisions.ts +89 -0
  858. package/src/database/migrations/runner.ts +9 -1
  859. package/src/database/repositories/byline.ts +32 -16
  860. package/src/database/repositories/content.ts +284 -48
  861. package/src/database/repositories/entry-locks.ts +257 -0
  862. package/src/database/repositories/media-usage.ts +66 -37
  863. package/src/database/repositories/media.ts +60 -1
  864. package/src/database/repositories/options.ts +69 -5
  865. package/src/database/repositories/plugin-storage.ts +233 -9
  866. package/src/database/repositories/redirect.ts +17 -6
  867. package/src/database/repositories/taxonomy.ts +8 -0
  868. package/src/database/repositories/types.ts +11 -7
  869. package/src/database/types.ts +15 -1
  870. package/src/db/adapters.ts +8 -1
  871. package/src/db/postgres.ts +23 -0
  872. package/src/emdash-runtime.ts +196 -199
  873. package/src/fields/boolean.ts +1 -1
  874. package/src/fields/datetime.ts +1 -1
  875. package/src/fields/file.ts +1 -1
  876. package/src/fields/integer.ts +1 -1
  877. package/src/fields/json.ts +1 -1
  878. package/src/fields/multiselect.ts +1 -1
  879. package/src/fields/number.ts +1 -1
  880. package/src/fields/portable-text.ts +1 -1
  881. package/src/fields/richtext.ts +1 -1
  882. package/src/fields/select.ts +1 -1
  883. package/src/fields/slug.ts +1 -1
  884. package/src/fields/text.ts +1 -1
  885. package/src/fields/textarea.ts +1 -1
  886. package/src/fields/types.ts +2 -2
  887. package/src/i18n/resolve.ts +44 -4
  888. package/src/index.ts +39 -3
  889. package/src/loader.ts +96 -12
  890. package/src/mcp/server.ts +251 -29
  891. package/src/media/image-endpoint.ts +5 -2
  892. package/src/media/normalize.ts +15 -4
  893. package/src/media/responsive.ts +23 -0
  894. package/src/media/usage/cleanup.ts +9 -8
  895. package/src/media/usage/content-refresh.ts +2 -1
  896. package/src/menus/index.ts +33 -21
  897. package/src/object-cache/index.ts +44 -2
  898. package/src/page/seo-contributions.ts +78 -1
  899. package/src/page/seo-panel.ts +47 -0
  900. package/src/plugin-types.ts +27 -1
  901. package/src/plugins/conditional-storage.ts +30 -0
  902. package/src/plugins/context.ts +49 -17
  903. package/src/plugins/hooks.ts +10 -1
  904. package/src/plugins/index.ts +15 -0
  905. package/src/plugins/manager.ts +6 -2
  906. package/src/plugins/manifest-schema.ts +1 -1
  907. package/src/plugins/routes.ts +3 -1
  908. package/src/plugins/sandbox/hook-result.ts +52 -0
  909. package/src/plugins/sandbox/index.ts +10 -0
  910. package/src/plugins/sandbox/types.ts +16 -2
  911. package/src/plugins/storage-query.ts +45 -0
  912. package/src/plugins/storage-update.ts +96 -0
  913. package/src/plugins/types.ts +120 -0
  914. package/src/query.ts +29 -3
  915. package/src/registry/artifact-checksum.ts +15 -0
  916. package/src/registry/artifact-verification.ts +85 -0
  917. package/src/registry/authoritative-records.ts +180 -0
  918. package/src/registry/config.ts +130 -27
  919. package/src/registry/record-labels.ts +28 -0
  920. package/src/registry/types.ts +5 -6
  921. package/src/schema/collection-slugs-cache.ts +157 -0
  922. package/src/schema/registry.ts +45 -3
  923. package/src/schema/types.ts +25 -6
  924. package/src/schema/zod-generator.ts +16 -13
  925. package/src/security/ssrf.ts +172 -143
  926. package/src/seed/apply.ts +4 -0
  927. package/src/seed/types.ts +7 -2
  928. package/src/seed/validate.ts +18 -1
  929. package/src/seo/hreflang.ts +1 -0
  930. package/src/seo/index.ts +5 -10
  931. package/src/seo/media-url.ts +26 -0
  932. package/src/settings/index.ts +16 -0
  933. package/src/storage/local.ts +1 -0
  934. package/src/storage/s3.ts +2 -0
  935. package/src/storage/types.ts +2 -0
  936. package/src/taxonomies/index.ts +40 -20
  937. package/src/taxonomies/term-counts.ts +22 -5
  938. package/src/widgets/archives.ts +67 -0
  939. package/src/widgets/index.ts +16 -0
  940. package/dist/api-B0w3uBiG.mjs +0 -2269
  941. package/dist/api-B0w3uBiG.mjs.map +0 -1
  942. package/dist/apply-B_VMpJ2P.mjs.map +0 -1
  943. package/dist/byline-Cpnwrje1.mjs.map +0 -1
  944. package/dist/challenge-store-D5pSY2S1.mjs.map +0 -1
  945. package/dist/content-CP-SeXNa.mjs.map +0 -1
  946. package/dist/content-refresh-DLOfIhYc.mjs.map +0 -1
  947. package/dist/context-BR5hRWiK.mjs.map +0 -1
  948. package/dist/dialect-helpers-BSbfaO3F.mjs.map +0 -1
  949. package/dist/errors-n2j49uNf.mjs.map +0 -1
  950. package/dist/index-DWbJrsAg.d.mts.map +0 -1
  951. package/dist/loader-ZsjE4paL.mjs.map +0 -1
  952. package/dist/manifest-schema-CUYPfCEH.mjs.map +0 -1
  953. package/dist/media-BjwNuLEu.mjs.map +0 -1
  954. package/dist/media-D6SeAfBl.mjs.map +0 -1
  955. package/dist/media-url-DH7giMx_.mjs.map +0 -1
  956. package/dist/menus-CNg0QlDt.mjs.map +0 -1
  957. package/dist/normalize-CSxdKBVa.mjs.map +0 -1
  958. package/dist/object-cache-71tPfV4A.mjs.map +0 -1
  959. package/dist/options-BHPeIbBd.mjs.map +0 -1
  960. package/dist/options-BhZIeFY1.d.mts.map +0 -1
  961. package/dist/query-D18vTdha.mjs.map +0 -1
  962. package/dist/redirect-CZkbozu9.mjs.map +0 -1
  963. package/dist/redirects-CRIM55KH.mjs.map +0 -1
  964. package/dist/registry-BiO5WwPq.mjs +0 -2716
  965. package/dist/registry-BiO5WwPq.mjs.map +0 -1
  966. package/dist/registry-Cx-jEJOS.mjs.map +0 -1
  967. package/dist/relations-BTPM2saV.mjs.map +0 -1
  968. package/dist/relations-C7B46bcU.d.mts.map +0 -1
  969. package/dist/resolve-DxUpTMmE.mjs.map +0 -1
  970. package/dist/runner-77GOZCnH.mjs.map +0 -1
  971. package/dist/runner-zgqA_CqP.d.mts.map +0 -1
  972. package/dist/seo-BSiTIXzd.mjs.map +0 -1
  973. package/dist/settings-BgN-0DT-.mjs.map +0 -1
  974. package/dist/snapshot-DSB8P7Lm.mjs.map +0 -1
  975. package/dist/ssrf-DqebVE34.mjs.map +0 -1
  976. package/dist/taxonomies-CPGxo-bn.mjs.map +0 -1
  977. package/dist/taxonomies-kmyudNGP.mjs.map +0 -1
  978. package/dist/types-75KIqzL9.mjs.map +0 -1
  979. package/dist/types-Br-ERaxh.d.mts.map +0 -1
  980. package/dist/types-D6OcIp2P.mjs +0 -3
  981. package/dist/types-DHxzBjbD.d.mts.map +0 -1
  982. package/dist/types-DJQxln7q.d.mts.map +0 -1
  983. package/dist/types-D_DWe7k9.d.mts.map +0 -1
  984. package/dist/types-Vg6f5i3s.d.mts.map +0 -1
  985. package/dist/validate-Dd-IUjnZ.mjs.map +0 -1
  986. package/dist/validate-DlqdOZXB.d.mts.map +0 -1
  987. package/dist/version-ri-sCyAp.mjs +0 -7
  988. package/dist/widgets-CpmZd9Q-.mjs.map +0 -1
  989. package/dist/zod-generator-DylzusHh.mjs.map +0 -1
  990. /package/dist/{api-tokens-B5NHLNUN.mjs → api-tokens-B_lfpmH3.mjs} +0 -0
  991. /package/dist/{ssrf-BPKzkm6O.mjs → ssrf-TQhaljuI.mjs} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry-DTqaqxed.mjs","names":[],"sources":["../src/schema/registry.ts"],"sourcesContent":["import type {\n\tColumnDataType,\n\tCreateTableBuilder,\n\tInsertable,\n\tKysely,\n\tSelectable,\n\tUpdateable,\n} from \"kysely\";\nimport { sql } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { refreshDevTypes } from \"../astro/dev-typegen.js\";\nimport { currentTimestamp, listTablesLike, tableExists } from \"../database/dialect-helpers.js\";\nimport { withTransaction } from \"../database/transaction.js\";\nimport type { CollectionTable, Database, FieldTable } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport {\n\tcanResumeMediaUsageCollectionCapture,\n\tfinalizeMediaUsageCollectionCapture,\n\tinstallPreparedMediaUsageCollectionCapture,\n\tmarkMediaUsageCollectionCaptureReady,\n\tprepareMediaUsageCollectionCapture,\n} from \"../media/usage/activation.js\";\nimport {\n\tdeleteActivatedMediaUsageCollection,\n\tisMediaUsageCollectionSlugDeleting,\n} from \"../media/usage/collection-deletion.js\";\nimport {\n\tdeleteContentMediaUsageCollection,\n\tinvalidateContentMediaUsageSchemaChange,\n\tmarkContentMediaUsageCollectionStaleSafely,\n} from \"../media/usage/content-refresh.js\";\nimport { FTSManager } from \"../search/fts-manager.js\";\nimport { chunks, SQL_BATCH_SIZE } from \"../utils/chunks.js\";\nimport { resetRegisteredCollectionsCache } from \"./collection-slugs-cache.js\";\nimport {\n\ttype Collection,\n\ttype CollectionAdminConfig,\n\ttype CollectionSource,\n\ttype CollectionSupport,\n\ttype ColumnType,\n\ttype Field,\n\ttype CreateCollectionInput,\n\ttype UpdateCollectionInput,\n\ttype CreateFieldInput,\n\ttype UpdateFieldInput,\n\ttype CollectionWithFields,\n\ttype FieldType,\n\tFIELD_TYPE_TO_COLUMN,\n\tisIndexableFieldType,\n\tRESERVED_FIELD_SLUGS,\n\tRESERVED_COLLECTION_SLUGS,\n} from \"./types.js\";\n\n// Regex patterns for schema registry\nconst SLUG_VALIDATION_PATTERN = /^[a-z][a-z0-9_]*$/;\nconst EC_PREFIX_PATTERN = /^ec_/;\nconst SINGLE_QUOTE_PATTERN = /'/g;\nconst UNDERSCORE_PATTERN = /_/g;\nconst WORD_BOUNDARY_PATTERN = /\\b\\w/g;\nconst FIELD_ID_PATTERN = /^[0-9A-Z]{26}$/;\n\n/** Valid column types for runtime validation */\nconst COLUMN_TYPES: ReadonlySet<string> = new Set([\"TEXT\", \"REAL\", \"INTEGER\", \"JSON\"]);\nconst COLUMN_TYPE_TO_DATA_TYPE = {\n\tTEXT: \"text\",\n\tREAL: \"real\",\n\tINTEGER: \"integer\",\n\tJSON: \"json\",\n} satisfies Record<ColumnType, ColumnDataType>;\nconst TEXT_ALIAS_FIELD_TYPES: ReadonlySet<FieldType> = new Set([\"string\", \"text\", \"slug\"]);\n\n/** Field types usable as a `titleField` — plain text that reads well as a title. */\nconst TITLE_FIELD_TYPES: ReadonlySet<string> = new Set([\"string\", \"text\", \"slug\"]);\n\n/** Valid collection source prefixes/values */\nconst VALID_SOURCES: ReadonlySet<string> = new Set([\"manual\", \"discovered\", \"seed\"]);\n\nfunction isCollectionSource(value: string): value is CollectionSource {\n\treturn VALID_SOURCES.has(value) || value.startsWith(\"template:\") || value.startsWith(\"import:\");\n}\n\nfunction isFieldType(value: string): value is FieldType {\n\treturn value in FIELD_TYPE_TO_COLUMN;\n}\n\nfunction isColumnType(value: string): value is ColumnType {\n\treturn COLUMN_TYPES.has(value);\n}\n\nconst VALID_COLLECTION_SUPPORTS: ReadonlySet<string> = new Set<CollectionSupport>([\n\t\"drafts\",\n\t\"revisions\",\n\t\"preview\",\n\t\"scheduling\",\n\t\"search\",\n\t\"seo\",\n]);\n\n// Each _emdash_fields row uses 16 bound parameters. Six rows keep every\n// multi-row INSERT below D1's 100-parameter statement limit.\nconst SEED_FIELD_INSERT_BATCH_SIZE = 6;\n\n/**\n * Rank given to collections without an explicit `sort_order`. SQLite sorts\n * NULL first on ASC while Postgres sorts it last, so the fallback is\n * materialised with COALESCE rather than left to the dialect.\n */\nconst UNORDERED_COLLECTION_RANK = 2147483647;\n\n/**\n * Collection ordering shared by every list read: explicit `sort_order`\n * first (ascending), then alphabetically by slug.\n */\nconst collectionOrder = sql<number>`coalesce(sort_order, ${sql.lit(UNORDERED_COLLECTION_RANK)})`;\n\nfunction assertIndexableField(type: FieldType, indexed: boolean | undefined, slug: string): void {\n\tif (indexed && !isIndexableFieldType(type)) {\n\t\tthrow new SchemaError(\n\t\t\t`Field \"${slug}\" cannot be indexed because type \"${type}\" is not a scalar query type`,\n\t\t\t\"FIELD_NOT_INDEXABLE\",\n\t\t);\n\t}\n}\n\nfunction isCollectionSupport(value: unknown): value is CollectionSupport {\n\treturn typeof value === \"string\" && VALID_COLLECTION_SUPPORTS.has(value);\n}\n\n/**\n * Parse a collection's `supports` column (stored as a JSON array of\n * CollectionSupport keys). Unknown/invalid entries are filtered out so the\n * runtime value matches the declared `CollectionSupport[]` type.\n *\n * Throws on malformed JSON so corruption surfaces loudly; returns an empty\n * array only for explicitly null/empty values or non-array JSON.\n */\nfunction parseSupports(raw: string | null | undefined): CollectionSupport[] {\n\tif (!raw) return [];\n\tconst parsed: unknown = JSON.parse(raw);\n\tif (!Array.isArray(parsed)) return [];\n\treturn parsed.filter(isCollectionSupport);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseCollectionAdmin(raw: string | null | undefined): CollectionAdminConfig | undefined {\n\tif (!raw) return undefined;\n\tconst parsed: unknown = JSON.parse(raw);\n\tif (!isRecord(parsed)) return undefined;\n\tconst listColumns = parsed.listColumns;\n\treturn {\n\t\tlistColumns: Array.isArray(listColumns)\n\t\t\t? listColumns.filter((value): value is string => typeof value === \"string\")\n\t\t\t: undefined,\n\t};\n}\n\nexport async function buildSeedCollectionCaptureFingerprint(\n\tinput: Omit<CreateCollectionInput, \"source\">,\n\tfields: readonly CreateFieldInput[],\n): Promise<string> {\n\tconst supports = input.supports ?? [\"drafts\", \"revisions\"];\n\tconst hasSeo = input.hasSeo ?? supports.includes(\"seo\") ?? false;\n\tlet maxSortOrder = -1;\n\tconst definitions = fields.map((field) => {\n\t\tconst sortOrder = field.sortOrder ?? maxSortOrder + 1;\n\t\tmaxSortOrder = Math.max(maxSortOrder, sortOrder);\n\t\treturn {\n\t\t\tslug: field.slug,\n\t\t\tlabel: field.label,\n\t\t\ttype: field.type,\n\t\t\trequired: field.required ?? false,\n\t\t\tunique: field.unique ?? false,\n\t\t\tdefaultValue: field.defaultValue === undefined ? null : JSON.stringify(field.defaultValue),\n\t\t\tvalidation: field.validation ? JSON.stringify(field.validation) : null,\n\t\t\twidget: field.widget ?? null,\n\t\t\toptions: field.options ? JSON.stringify(field.options) : null,\n\t\t\tsortOrder,\n\t\t\tsearchable: field.searchable ?? false,\n\t\t\ttranslatable: field.translatable ?? true,\n\t\t};\n\t});\n\tconst payload = JSON.stringify(\n\t\tcanonicalizeFingerprintValue({\n\t\t\tversion: 1,\n\t\t\tcollection: {\n\t\t\t\tslug: input.slug,\n\t\t\t\tlabel: input.label,\n\t\t\t\tlabelSingular: input.labelSingular ?? null,\n\t\t\t\tdescription: input.description ?? null,\n\t\t\t\ticon: input.icon ?? null,\n\t\t\t\tadmin: input.admin ?? null,\n\t\t\t\tsupports,\n\t\t\t\thasSeo,\n\t\t\t\thidden: input.hidden ?? false,\n\t\t\t\tsortOrder: input.sortOrder ?? null,\n\t\t\t\t...(input.group ? { group: input.group } : {}),\n\t\t\t\tcommentsEnabled: input.commentsEnabled ?? false,\n\t\t\t\t...(input.editLocking === false ? { editLocking: false } : {}),\n\t\t\t\turlPattern: input.urlPattern ?? null,\n\t\t\t\troutable: input.routable ?? true,\n\t\t\t},\n\t\t\tfields: definitions,\n\t\t}),\n\t);\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(payload));\n\tconst hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\n\t\t\"\",\n\t);\n\treturn `media-usage-seed:v1:sha256:${hex}`;\n}\n\nfunction canonicalizeFingerprintValue(value: unknown): unknown {\n\tif (value === undefined) return { __emdashUndefined: true };\n\tif (Array.isArray(value)) return value.map(canonicalizeFingerprintValue);\n\tif (typeof value !== \"object\" || value === null) return value;\n\n\tconst canonical: Record<string, unknown> = {};\n\tfor (const [key, entry] of Object.entries(value).toSorted(([a], [b]) => a.localeCompare(b))) {\n\t\tcanonical[key] = canonicalizeFingerprintValue(entry);\n\t}\n\treturn canonical;\n}\n\n/**\n * Error thrown when a schema operation fails\n */\nexport class SchemaError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic code: string,\n\t\tpublic details?: Record<string, unknown>,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"SchemaError\";\n\t}\n}\n\n/**\n * Schema Registry\n *\n * Manages collection and field definitions stored in D1.\n * Handles runtime DDL operations (CREATE TABLE, ALTER TABLE).\n */\nexport class SchemaRegistry {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Notify the dev typegen hook that the schema has changed.\n\t */\n\tprivate notifyTypegen(): void {\n\t\trefreshDevTypes(this.db);\n\t}\n\n\t// ============================================\n\t// Collection Operations\n\t// ============================================\n\n\t/**\n\t * List all collections\n\t */\n\tasync listCollections(): Promise<Collection[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.selectAll()\n\t\t\t.orderBy(collectionOrder, \"asc\")\n\t\t\t.orderBy(\"slug\", \"asc\")\n\t\t\t.execute();\n\n\t\treturn rows.map(this.mapCollectionRow);\n\t}\n\n\t/**\n\t * Get a collection by slug\n\t */\n\tasync getCollection(slug: string): Promise<Collection | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.where(\"slug\", \"=\", slug)\n\t\t\t.selectAll()\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.mapCollectionRow(row) : null;\n\t}\n\n\t/**\n\t * Get a collection with all its fields\n\t */\n\tasync getCollectionWithFields(slug: string): Promise<CollectionWithFields | null> {\n\t\tconst collection = await this.getCollection(slug);\n\t\tif (!collection) return null;\n\n\t\tconst fields = await this.listFields(collection.id);\n\n\t\treturn { ...collection, fields };\n\t}\n\n\t/**\n\t * List every collection together with its fields in O(1) query shapes\n\t * — one for collections, then one batched query for the fields of every\n\t * returned collection — instead of the N+1 pattern of `listCollections`\n\t * + per-collection `listFields`. The fields query is chunked at\n\t * `SQL_BATCH_SIZE` to stay under D1's bound-parameter limit, so on\n\t * sites with more than `SQL_BATCH_SIZE` collections the field fetch\n\t * becomes `ceil(collectionCount / SQL_BATCH_SIZE)` queries — still\n\t * a constant factor, not N+1. Typical sites have well under\n\t * `SQL_BATCH_SIZE` collections, so this is two queries in practice.\n\t *\n\t * Used by the manifest build, which previously paid N+1 round-trips on\n\t * every admin request. Each round-trip costs ~80–150ms against the D1\n\t * primary on a busy link, so a 10-collection site spent ~1 s rebuilding\n\t * a manifest that is now built fresh per admin request (no cache).\n\t */\n\tasync listCollectionsWithFields(): Promise<CollectionWithFields[]> {\n\t\tconst collectionRows = await this.db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.selectAll()\n\t\t\t.orderBy(collectionOrder, \"asc\")\n\t\t\t.orderBy(\"slug\", \"asc\")\n\t\t\t.execute();\n\n\t\tif (collectionRows.length === 0) return [];\n\n\t\tconst fieldsByCollection = new Map<string, Field[]>();\n\t\t// Chunk to stay under D1's bound-parameter limit. Typical sites have\n\t\t// well under SQL_BATCH_SIZE collections, so this is a single query\n\t\t// in practice; on larger sites it becomes a small constant number\n\t\t// of queries, never N+1.\n\t\tfor (const idChunk of chunks(\n\t\t\tcollectionRows.map((c) => c.id),\n\t\t\tSQL_BATCH_SIZE,\n\t\t)) {\n\t\t\tconst fieldRows = await this.db\n\t\t\t\t.selectFrom(\"_emdash_fields\")\n\t\t\t\t.where(\"collection_id\", \"in\", idChunk)\n\t\t\t\t.selectAll()\n\t\t\t\t.orderBy(\"collection_id\", \"asc\")\n\t\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t\t.orderBy(\"created_at\", \"asc\")\n\t\t\t\t.execute();\n\t\t\tfor (const row of fieldRows) {\n\t\t\t\tconst list = fieldsByCollection.get(row.collection_id) ?? [];\n\t\t\t\tlist.push(this.mapFieldRow(row));\n\t\t\t\tfieldsByCollection.set(row.collection_id, list);\n\t\t\t}\n\t\t}\n\n\t\treturn collectionRows.map((c) => ({\n\t\t\t...this.mapCollectionRow(c),\n\t\t\tfields: fieldsByCollection.get(c.id) ?? [],\n\t\t}));\n\t}\n\n\t/**\n\t * Validate `titleField`/`dateField` against the collection's fields:\n\t * `titleField` must be a text-like field; `dateField` must be a `datetime` field.\n\t * Only truthy values are checked (undefined = unchanged, null/\"\" = cleared).\n\t */\n\tprivate async validateTitleDateFields(\n\t\tcollectionId: string,\n\t\tcollectionSlug: string,\n\t\tinput: { titleField?: string | null; dateField?: string | null },\n\t\tdb: Kysely<Database> = this.db,\n\t): Promise<void> {\n\t\tconst slugs = [input.titleField, input.dateField].filter((slug): slug is string => !!slug);\n\t\tif (slugs.length === 0) return;\n\n\t\tconst rows = await db\n\t\t\t.selectFrom(\"_emdash_fields\")\n\t\t\t.where(\"collection_id\", \"=\", collectionId)\n\t\t\t.where(\"slug\", \"in\", slugs)\n\t\t\t.select([\"slug\", \"type\"])\n\t\t\t.execute();\n\t\tconst typeBySlug = new Map(rows.map((row) => [row.slug, row.type]));\n\n\t\tif (input.titleField) {\n\t\t\tconst type = typeBySlug.get(input.titleField);\n\t\t\tif (type === undefined) {\n\t\t\t\tthrow new SchemaError(\n\t\t\t\t\t`titleField \"${input.titleField}\" is not a field on \"${collectionSlug}\"`,\n\t\t\t\t\t\"INVALID_TITLE_FIELD\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!TITLE_FIELD_TYPES.has(type)) {\n\t\t\t\tthrow new SchemaError(\n\t\t\t\t\t`titleField \"${input.titleField}\" must be a text field (got \"${type}\")`,\n\t\t\t\t\t\"INVALID_TITLE_FIELD\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tif (input.dateField) {\n\t\t\tconst type = typeBySlug.get(input.dateField);\n\t\t\tif (type === undefined) {\n\t\t\t\tthrow new SchemaError(\n\t\t\t\t\t`dateField \"${input.dateField}\" is not a field on \"${collectionSlug}\"`,\n\t\t\t\t\t\"INVALID_DATE_FIELD\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (type !== \"datetime\") {\n\t\t\t\tthrow new SchemaError(\n\t\t\t\t\t`dateField \"${input.dateField}\" must be a datetime field (got \"${type}\")`,\n\t\t\t\t\t\"INVALID_DATE_FIELD\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Create a new collection\n\t */\n\tasync createCollection(input: CreateCollectionInput): Promise<Collection> {\n\t\t// Validate slug\n\t\tthis.validateSlug(input.slug, \"collection\");\n\t\tif (RESERVED_COLLECTION_SLUGS.includes(input.slug)) {\n\t\t\tthrow new SchemaError(`Collection slug \"${input.slug}\" is reserved`, \"RESERVED_SLUG\");\n\t\t}\n\t\tif (await isMediaUsageCollectionSlugDeleting(this.db, input.slug)) {\n\t\t\tthrow new SchemaError(`Collection \"${input.slug}\" already exists`, \"COLLECTION_EXISTS\");\n\t\t}\n\n\t\t// Check if collection already exists\n\t\tconst existing = await this.getCollection(input.slug);\n\t\tif (await isMediaUsageCollectionSlugDeleting(this.db, input.slug)) {\n\t\t\tthrow new SchemaError(`Collection \"${input.slug}\" already exists`, \"COLLECTION_EXISTS\");\n\t\t}\n\t\tif (\n\t\t\texisting &&\n\t\t\t!(await canResumeMediaUsageCollectionCapture(this.db, {\n\t\t\t\tcollectionId: existing.id,\n\t\t\t\tcollectionSlug: existing.slug,\n\t\t\t}))\n\t\t) {\n\t\t\tthrow new SchemaError(`Collection \"${input.slug}\" already exists`, \"COLLECTION_EXISTS\");\n\t\t}\n\n\t\tconst proposedId = existing?.id ?? ulid();\n\n\t\t// Default `supports` to drafts + revisions when the caller didn't\n\t\t// specify it. Explicit empty array (`[]`) is preserved as an opt-out\n\t\t// — only `undefined` triggers the default. This is the canonical\n\t\t// default for new collections; the MCP and admin UI layers used to\n\t\t// duplicate this default but now defer to the registry.\n\t\tconst supports = input.supports ?? [\"drafts\", \"revisions\"];\n\n\t\t// Insert collection record and create content table in a transaction\n\t\t// so a failure in table creation doesn't leave an orphaned row.\n\t\t// Uses withTransaction for D1 compatibility (no transaction support).\n\t\t// Derive hasSeo from supports array if not explicitly set\n\t\tconst hasSeo = input.hasSeo ?? supports.includes(\"seo\") ?? false;\n\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\tconst capture = await prepareMediaUsageCollectionCapture(trx, {\n\t\t\t\tcollectionId: proposedId,\n\t\t\t\tcollectionSlug: input.slug,\n\t\t\t\tregisteredCollectionId: existing?.id,\n\t\t\t});\n\t\t\tconst values: Insertable<CollectionTable> = {\n\t\t\t\tid: capture.collectionId,\n\t\t\t\tslug: input.slug,\n\t\t\t\tlabel: input.label,\n\t\t\t\tlabel_singular: input.labelSingular ?? null,\n\t\t\t\tdescription: input.description ?? null,\n\t\t\t\ticon: input.icon ?? null,\n\t\t\t\tadmin_config: input.admin ? JSON.stringify(input.admin) : null,\n\t\t\t\tsupports: JSON.stringify(supports),\n\t\t\t\tsource: input.source ?? \"manual\",\n\t\t\t\thas_seo: hasSeo ? 1 : 0,\n\t\t\t\troutable: input.routable === false ? 0 : 1,\n\t\t\t\thidden: input.hidden ? 1 : 0,\n\t\t\t\tsort_order: input.sortOrder ?? null,\n\t\t\t\tnav_group: input.group?.trim() || null,\n\t\t\t\tcomments_enabled: input.commentsEnabled ? 1 : 0,\n\t\t\t\tedit_locking: input.editLocking === false ? 0 : 1,\n\t\t\t\turl_pattern: input.urlPattern ?? null,\n\t\t\t};\n\n\t\t\tif (capture.captureRequired) {\n\t\t\t\tawait this.createContentTable(input.slug, trx, [], {\n\t\t\t\t\tifNotExists: capture.resuming,\n\t\t\t\t});\n\t\t\t\tawait installPreparedMediaUsageCollectionCapture(trx, {\n\t\t\t\t\tcollectionId: capture.collectionId,\n\t\t\t\t\tcollectionSlug: input.slug,\n\t\t\t\t});\n\t\t\t\tawait markMediaUsageCollectionCaptureReady(trx, {\n\t\t\t\t\tcollectionId: capture.collectionId,\n\t\t\t\t\tcollectionSlug: input.slug,\n\t\t\t\t});\n\t\t\t\tif (!capture.registrationExists) {\n\t\t\t\t\tawait trx.insertInto(\"_emdash_collections\").values(values).execute();\n\t\t\t\t}\n\t\t\t\tawait finalizeMediaUsageCollectionCapture(trx, {\n\t\t\t\t\tcollectionId: capture.collectionId,\n\t\t\t\t\tcollectionSlug: input.slug,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tawait trx.insertInto(\"_emdash_collections\").values(values).execute();\n\t\t\tawait this.createContentTable(input.slug, trx);\n\t\t});\n\n\t\tconst collection = await this.getCollection(input.slug);\n\t\tif (!collection) {\n\t\t\tthrow new SchemaError(\"Failed to create collection\", \"CREATE_FAILED\");\n\t\t}\n\n\t\tresetRegisteredCollectionsCache();\n\t\tthis.notifyTypegen();\n\t\treturn collection;\n\t}\n\n\t/**\n\t * Create a seed-owned collection and all of its fields in bulk.\n\t *\n\t * Fresh seeds can define dozens of fields. Creating them through\n\t * `createField` performs multiple reads, one ALTER TABLE, and one media\n\t * usage invalidation per field, which can exhaust D1's per-request query\n\t * budget. This path validates the full schema before mutating it, creates\n\t * the complete content table in one statement, and inserts field metadata\n\t * in parameter-safe batches.\n\t */\n\tasync createSeedCollection(\n\t\tinput: Omit<CreateCollectionInput, \"source\">,\n\t\tfields: readonly CreateFieldInput[],\n\t): Promise<void> {\n\t\tthis.validateSlug(input.slug, \"collection\");\n\t\tif (RESERVED_COLLECTION_SLUGS.includes(input.slug)) {\n\t\t\tthrow new SchemaError(`Collection slug \"${input.slug}\" is reserved`, \"RESERVED_SLUG\");\n\t\t}\n\t\tif (await isMediaUsageCollectionSlugDeleting(this.db, input.slug)) {\n\t\t\tthrow new SchemaError(`Collection \"${input.slug}\" already exists`, \"COLLECTION_EXISTS\");\n\t\t}\n\n\t\tconst fieldSlugs = new Set<string>();\n\t\tfor (const field of fields) {\n\t\t\tthis.validateSlug(field.slug, \"field\");\n\t\t\tassertIndexableField(field.type, field.indexed, field.slug);\n\t\t\tif (RESERVED_FIELD_SLUGS.includes(field.slug)) {\n\t\t\t\tthrow new SchemaError(`Field slug \"${field.slug}\" is reserved`, \"RESERVED_SLUG\");\n\t\t\t}\n\t\t\tif (fieldSlugs.has(field.slug)) {\n\t\t\t\tthrow new SchemaError(\n\t\t\t\t\t`Field \"${field.slug}\" already exists in collection \"${input.slug}\"`,\n\t\t\t\t\t\"FIELD_EXISTS\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tfieldSlugs.add(field.slug);\n\t\t}\n\n\t\tconst supports = input.supports ?? [\"drafts\", \"revisions\"];\n\t\tconst hasSeo = input.hasSeo ?? supports.includes(\"seo\") ?? false;\n\t\tconst creationFingerprint = await buildSeedCollectionCaptureFingerprint(input, fields);\n\t\tconst existing = await this.getCollection(input.slug);\n\t\tif (await isMediaUsageCollectionSlugDeleting(this.db, input.slug)) {\n\t\t\tthrow new SchemaError(`Collection \"${input.slug}\" already exists`, \"COLLECTION_EXISTS\");\n\t\t}\n\t\tif (\n\t\t\texisting &&\n\t\t\t!(await canResumeMediaUsageCollectionCapture(this.db, {\n\t\t\t\tcollectionId: existing.id,\n\t\t\t\tcollectionSlug: existing.slug,\n\t\t\t\tcreationFingerprint,\n\t\t\t}))\n\t\t) {\n\t\t\tthrow new SchemaError(`Collection \"${input.slug}\" already exists`, \"COLLECTION_EXISTS\");\n\t\t}\n\n\t\tconst proposedCollectionId = existing?.id ?? ulid();\n\t\tlet maxSortOrder = -1;\n\t\tconst fieldRows: Insertable<FieldTable>[] = fields.map((field) => {\n\t\t\tconst sortOrder = field.sortOrder ?? maxSortOrder + 1;\n\t\t\tmaxSortOrder = Math.max(maxSortOrder, sortOrder);\n\n\t\t\treturn {\n\t\t\t\tid: ulid(),\n\t\t\t\tcollection_id: proposedCollectionId,\n\t\t\t\tslug: field.slug,\n\t\t\t\tlabel: field.label,\n\t\t\t\ttype: field.type,\n\t\t\t\tcolumn_type: FIELD_TYPE_TO_COLUMN[field.type],\n\t\t\t\trequired: field.required ? 1 : 0,\n\t\t\t\tunique: field.unique ? 1 : 0,\n\t\t\t\tdefault_value: field.defaultValue !== undefined ? JSON.stringify(field.defaultValue) : null,\n\t\t\t\tvalidation: field.validation ? JSON.stringify(field.validation) : null,\n\t\t\t\twidget: field.widget ?? null,\n\t\t\t\toptions: field.options ? JSON.stringify(field.options) : null,\n\t\t\t\tsort_order: sortOrder,\n\t\t\t\tsearchable: field.searchable ? 1 : 0,\n\t\t\t\tindexed: field.indexed ? 1 : 0,\n\t\t\t\ttranslatable: field.translatable === false ? 0 : 1,\n\t\t\t};\n\t\t});\n\n\t\tlet schemaMutated = false;\n\t\ttry {\n\t\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\t\tconst capture = await prepareMediaUsageCollectionCapture(trx, {\n\t\t\t\t\tcollectionId: proposedCollectionId,\n\t\t\t\t\tcollectionSlug: input.slug,\n\t\t\t\t\tcreationFingerprint,\n\t\t\t\t\tregisteredCollectionId: existing?.id,\n\t\t\t\t});\n\t\t\t\tconst collectionValues: Insertable<CollectionTable> = {\n\t\t\t\t\tid: capture.collectionId,\n\t\t\t\t\tslug: input.slug,\n\t\t\t\t\tlabel: input.label,\n\t\t\t\t\tlabel_singular: input.labelSingular ?? null,\n\t\t\t\t\tdescription: input.description ?? null,\n\t\t\t\t\ticon: input.icon ?? null,\n\t\t\t\t\tadmin_config: input.admin ? JSON.stringify(input.admin) : null,\n\t\t\t\t\tsupports: JSON.stringify(supports),\n\t\t\t\t\tsource: \"seed\",\n\t\t\t\t\thas_seo: hasSeo ? 1 : 0,\n\t\t\t\t\troutable: input.routable === false ? 0 : 1,\n\t\t\t\t\thidden: input.hidden ? 1 : 0,\n\t\t\t\t\tsort_order: input.sortOrder ?? null,\n\t\t\t\t\tnav_group: input.group?.trim() || null,\n\t\t\t\t\tcomments_enabled: input.commentsEnabled ? 1 : 0,\n\t\t\t\t\tedit_locking: input.editLocking === false ? 0 : 1,\n\t\t\t\t\turl_pattern: input.urlPattern ?? null,\n\t\t\t\t};\n\t\t\t\tconst rows = fieldRows.map((row) => ({\n\t\t\t\t\t...row,\n\t\t\t\t\tcollection_id: capture.collectionId,\n\t\t\t\t}));\n\n\t\t\t\tif (capture.captureRequired) {\n\t\t\t\t\tawait this.createContentTable(input.slug, trx, fields, {\n\t\t\t\t\t\tifNotExists: capture.resuming,\n\t\t\t\t\t});\n\t\t\t\t\tawait installPreparedMediaUsageCollectionCapture(trx, {\n\t\t\t\t\t\tcollectionId: capture.collectionId,\n\t\t\t\t\t\tcollectionSlug: input.slug,\n\t\t\t\t\t});\n\t\t\t\t\tawait markMediaUsageCollectionCaptureReady(trx, {\n\t\t\t\t\t\tcollectionId: capture.collectionId,\n\t\t\t\t\t\tcollectionSlug: input.slug,\n\t\t\t\t\t});\n\t\t\t\t\tif (!capture.registrationExists) {\n\t\t\t\t\t\tawait trx.insertInto(\"_emdash_collections\").values(collectionValues).execute();\n\t\t\t\t\t\tschemaMutated = true;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tawait trx.insertInto(\"_emdash_collections\").values(collectionValues).execute();\n\t\t\t\t\tschemaMutated = true;\n\t\t\t\t\tawait this.createContentTable(input.slug, trx, fields);\n\t\t\t\t}\n\n\t\t\t\tfor (const fieldBatch of chunks(rows, SEED_FIELD_INSERT_BATCH_SIZE)) {\n\t\t\t\t\tlet insert = trx.insertInto(\"_emdash_fields\").values(fieldBatch);\n\t\t\t\t\tif (capture.resuming) {\n\t\t\t\t\t\tinsert = insert.onConflict((conflict) =>\n\t\t\t\t\t\t\tconflict.columns([\"collection_id\", \"slug\"]).doNothing(),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tawait insert.execute();\n\t\t\t\t}\n\t\t\t\tlet indexedRows: readonly { id: string; slug: string; indexed?: number }[] = rows;\n\t\t\t\tif (capture.resuming) {\n\t\t\t\t\tindexedRows = await this.assertSeedFieldDefinitions(capture.collectionId, fields, trx);\n\t\t\t\t}\n\t\t\t\tfor (const field of indexedRows) {\n\t\t\t\t\tif (field.indexed === 1) {\n\t\t\t\t\t\tawait this.createFieldIndex(input.slug, field.id, field.slug, trx);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (capture.captureRequired) {\n\t\t\t\t\tawait finalizeMediaUsageCollectionCapture(trx, {\n\t\t\t\t\t\tcollectionId: capture.collectionId,\n\t\t\t\t\t\tcollectionSlug: input.slug,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tawait markContentMediaUsageCollectionStaleSafely(this.db, input.slug, \"CONTENT_USAGE_STALE\");\n\t\t} catch (error) {\n\t\t\tif (schemaMutated) {\n\t\t\t\tawait markContentMediaUsageCollectionStaleSafely(\n\t\t\t\t\tthis.db,\n\t\t\t\t\tinput.slug,\n\t\t\t\t\t\"CONTENT_USAGE_STALE\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tif (schemaMutated) resetRegisteredCollectionsCache();\n\t\t}\n\t\tthis.notifyTypegen();\n\t}\n\n\tprivate async assertSeedFieldDefinitions(\n\t\tcollectionId: string,\n\t\tfields: readonly CreateFieldInput[],\n\t\tdb: Kysely<Database>,\n\t): Promise<Selectable<FieldTable>[]> {\n\t\tconst stored = await db\n\t\t\t.selectFrom(\"_emdash_fields\")\n\t\t\t.selectAll()\n\t\t\t.where(\"collection_id\", \"=\", collectionId)\n\t\t\t.execute();\n\t\tif (stored.length !== fields.length) {\n\t\t\tthrow new SchemaError(\"Interrupted seed collection fields do not match\", \"CREATE_FAILED\");\n\t\t}\n\n\t\tlet maxSortOrder = -1;\n\t\tfor (const field of fields) {\n\t\t\tconst sortOrder = field.sortOrder ?? maxSortOrder + 1;\n\t\t\tmaxSortOrder = Math.max(maxSortOrder, sortOrder);\n\t\t\tconst row = stored.find((candidate) => candidate.slug === field.slug);\n\t\t\tif (\n\t\t\t\t!row ||\n\t\t\t\trow.label !== field.label ||\n\t\t\t\trow.type !== field.type ||\n\t\t\t\trow.column_type !== FIELD_TYPE_TO_COLUMN[field.type] ||\n\t\t\t\trow.required !== (field.required ? 1 : 0) ||\n\t\t\t\trow.unique !== (field.unique ? 1 : 0) ||\n\t\t\t\trow.default_value !==\n\t\t\t\t\t(field.defaultValue !== undefined ? JSON.stringify(field.defaultValue) : null) ||\n\t\t\t\trow.validation !== (field.validation ? JSON.stringify(field.validation) : null) ||\n\t\t\t\trow.widget !== (field.widget ?? null) ||\n\t\t\t\trow.options !== (field.options ? JSON.stringify(field.options) : null) ||\n\t\t\t\trow.sort_order !== sortOrder ||\n\t\t\t\trow.searchable !== (field.searchable ? 1 : 0) ||\n\t\t\t\trow.indexed !== (field.indexed ? 1 : 0) ||\n\t\t\t\trow.translatable !== (field.translatable === false ? 0 : 1)\n\t\t\t) {\n\t\t\t\tthrow new SchemaError(\"Interrupted seed collection fields do not match\", \"CREATE_FAILED\");\n\t\t\t}\n\t\t}\n\t\treturn stored;\n\t}\n\n\t/**\n\t * Update a collection\n\t */\n\tasync updateCollection(slug: string, input: UpdateCollectionInput): Promise<Collection> {\n\t\tconst updated = await withTransaction(this.db, async (trx) => {\n\t\t\tconst existingRow = await trx\n\t\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t\t.where(\"slug\", \"=\", slug)\n\t\t\t\t.selectAll()\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (!existingRow) {\n\t\t\t\tthrow new SchemaError(`Collection \"${slug}\" not found`, \"COLLECTION_NOT_FOUND\");\n\t\t\t}\n\t\t\tconst existing = this.mapCollectionRow(existingRow);\n\t\t\tawait this.validateTitleDateFields(\n\t\t\t\texisting.id,\n\t\t\t\tslug,\n\t\t\t\t{\n\t\t\t\t\ttitleField: input.titleField,\n\t\t\t\t\tdateField: input.dateField,\n\t\t\t\t},\n\t\t\t\ttrx,\n\t\t\t);\n\t\t\tconst updates: Updateable<CollectionTable> = {};\n\n\t\t\tif (input.label !== undefined) updates.label = input.label;\n\t\t\tif (input.labelSingular !== undefined) updates.label_singular = input.labelSingular;\n\t\t\tif (input.description !== undefined) updates.description = input.description;\n\t\t\tif (input.icon !== undefined) updates.icon = input.icon;\n\t\t\tif (input.admin !== undefined) updates.admin_config = JSON.stringify(input.admin);\n\t\t\tif (input.supports !== undefined) updates.supports = JSON.stringify(input.supports);\n\t\t\tif (input.urlPattern !== undefined) updates.url_pattern = input.urlPattern;\n\t\t\tif (input.routable !== undefined) updates.routable = input.routable ? 1 : 0;\n\t\t\tif (input.hasSeo !== undefined) {\n\t\t\t\tupdates.has_seo = input.hasSeo ? 1 : 0;\n\t\t\t} else if (input.supports !== undefined) {\n\t\t\t\tupdates.has_seo = input.supports.includes(\"seo\") ? 1 : 0;\n\t\t\t}\n\t\t\tif (input.hidden !== undefined) updates.hidden = input.hidden ? 1 : 0;\n\t\t\tif (input.sortOrder !== undefined) updates.sort_order = input.sortOrder;\n\t\t\tif (input.group !== undefined) updates.nav_group = input.group?.trim() || null;\n\t\t\tif (input.titleField !== undefined) updates.title_field = input.titleField || null;\n\t\t\tif (input.dateField !== undefined) updates.date_field = input.dateField || null;\n\t\t\tif (input.commentsEnabled !== undefined) {\n\t\t\t\tupdates.comments_enabled = input.commentsEnabled ? 1 : 0;\n\t\t\t}\n\t\t\tif (input.commentsModeration !== undefined) {\n\t\t\t\tupdates.comments_moderation = input.commentsModeration;\n\t\t\t}\n\t\t\tif (input.commentsClosedAfterDays !== undefined) {\n\t\t\t\tupdates.comments_closed_after_days = input.commentsClosedAfterDays;\n\t\t\t}\n\t\t\tif (input.commentsAutoApproveUsers !== undefined) {\n\t\t\t\tupdates.comments_auto_approve_users = input.commentsAutoApproveUsers ? 1 : 0;\n\t\t\t}\n\t\t\tif (input.editLocking !== undefined) updates.edit_locking = input.editLocking ? 1 : 0;\n\n\t\t\tupdates.updated_at = new Date().toISOString();\n\t\t\tawait trx\n\t\t\t\t.updateTable(\"_emdash_collections\")\n\t\t\t\t.set(updates)\n\t\t\t\t.where(\"id\", \"=\", existing.id)\n\t\t\t\t.execute();\n\n\t\t\tconst row = await trx\n\t\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t\t.where(\"slug\", \"=\", slug)\n\t\t\t\t.selectAll()\n\t\t\t\t.executeTakeFirst();\n\n\t\t\tif (!row) {\n\t\t\t\tthrow new SchemaError(\"Failed to update collection\", \"UPDATE_FAILED\");\n\t\t\t}\n\n\t\t\t// Sync FTS state when the supports array changes (e.g. search toggled on/off)\n\t\t\tif (input.supports !== undefined) {\n\t\t\t\tconst hadSearch = existing.supports.includes(\"search\");\n\t\t\t\tconst hasSearch = parseSupports(row.supports).includes(\"search\");\n\t\t\t\tif (hadSearch !== hasSearch) {\n\t\t\t\t\tawait this.syncSearchState(slug, trx);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn this.mapCollectionRow(row);\n\t\t});\n\t\tthis.notifyTypegen();\n\t\treturn updated;\n\t}\n\n\t/**\n\t * Delete a collection\n\t */\n\tasync deleteCollection(slug: string, options?: { force?: boolean }): Promise<void> {\n\t\tconst existing = await this.getCollection(slug);\n\t\tif (existing && !options?.force && (await this.collectionHasContent(slug))) {\n\t\t\tthrow new SchemaError(\n\t\t\t\t`Collection \"${slug}\" has content. Use force: true to delete.`,\n\t\t\t\t\"COLLECTION_HAS_CONTENT\",\n\t\t\t);\n\t\t}\n\t\tconst activated = await deleteActivatedMediaUsageCollection(this.db, {\n\t\t\tcollectionId: existing?.id,\n\t\t\tcollectionSlug: slug,\n\t\t\tforceDelete: options?.force === true,\n\t\t});\n\t\tif (activated === \"has_content\") {\n\t\t\tthrow new SchemaError(\n\t\t\t\t`Collection \"${slug}\" has content. Use force: true to delete.`,\n\t\t\t\t\"COLLECTION_HAS_CONTENT\",\n\t\t\t);\n\t\t}\n\t\tif (activated === \"in_progress\") {\n\t\t\tthrow new SchemaError(`Collection \"${slug}\" deletion is already in progress`, \"CONFLICT\");\n\t\t}\n\t\tif (activated === \"deleted\") return;\n\t\tif (!existing) {\n\t\t\tthrow new SchemaError(`Collection \"${slug}\" not found`, \"COLLECTION_NOT_FOUND\");\n\t\t}\n\n\t\tlet contentTableDropped = false;\n\t\ttry {\n\t\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\t\t// Drop FTS table and triggers before dropping the content table\n\t\t\t\tconst ftsManager = new FTSManager(trx);\n\t\t\t\tawait ftsManager.dropFtsTable(slug);\n\n\t\t\t\t// Drop the content table\n\t\t\t\tconst tableName = this.getTableName(slug);\n\t\t\t\tawait sql`DROP TABLE IF EXISTS ${sql.ref(tableName)}`.execute(trx);\n\t\t\t\tcontentTableDropped = true;\n\n\t\t\t\t// Delete the collection record (fields will cascade)\n\t\t\t\tawait trx.deleteFrom(\"_emdash_collections\").where(\"id\", \"=\", existing.id).execute();\n\t\t\t});\n\t\t\tawait deleteContentMediaUsageCollection(this.db, slug);\n\t\t} catch (error) {\n\t\t\tif (contentTableDropped && !(await tableExists(this.db, this.getTableName(slug)))) {\n\t\t\t\tawait deleteContentMediaUsageCollection(this.db, slug);\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\t// Even a failed delete may have dropped the ec_* table (D1 has no\n\t\t\t// real transactions) — over-invalidation is harmless, a stale set\n\t\t\t// is not.\n\t\t\tif (contentTableDropped) resetRegisteredCollectionsCache();\n\t\t}\n\t\tthis.notifyTypegen();\n\t}\n\n\t// ============================================\n\t// Field Operations\n\t// ============================================\n\n\t/**\n\t * List fields for a collection\n\t */\n\tasync listFields(collectionId: string): Promise<Field[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_fields\")\n\t\t\t.where(\"collection_id\", \"=\", collectionId)\n\t\t\t.selectAll()\n\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t.orderBy(\"created_at\", \"asc\")\n\t\t\t.execute();\n\n\t\treturn rows.map(this.mapFieldRow);\n\t}\n\n\t/**\n\t * Get a field by slug within a collection\n\t */\n\tasync getField(collectionSlug: string, fieldSlug: string): Promise<Field | null> {\n\t\tconst collection = await this.getCollection(collectionSlug);\n\t\tif (!collection) return null;\n\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_fields\")\n\t\t\t.where(\"collection_id\", \"=\", collection.id)\n\t\t\t.where(\"slug\", \"=\", fieldSlug)\n\t\t\t.selectAll()\n\t\t\t.executeTakeFirst();\n\n\t\treturn row ? this.mapFieldRow(row) : null;\n\t}\n\n\t/**\n\t * Create a new field\n\t */\n\tasync createField(collectionSlug: string, input: CreateFieldInput): Promise<Field> {\n\t\tconst collection = await this.getCollection(collectionSlug);\n\t\tif (!collection) {\n\t\t\tthrow new SchemaError(`Collection \"${collectionSlug}\" not found`, \"COLLECTION_NOT_FOUND\");\n\t\t}\n\n\t\t// Validate slug\n\t\tthis.validateSlug(input.slug, \"field\");\n\t\tif (RESERVED_FIELD_SLUGS.includes(input.slug)) {\n\t\t\tthrow new SchemaError(`Field slug \"${input.slug}\" is reserved`, \"RESERVED_SLUG\");\n\t\t}\n\n\t\t// Check if field already exists\n\t\tconst existing = await this.getField(collectionSlug, input.slug);\n\t\tif (existing) {\n\t\t\tthrow new SchemaError(\n\t\t\t\t`Field \"${input.slug}\" already exists in collection \"${collectionSlug}\"`,\n\t\t\t\t\"FIELD_EXISTS\",\n\t\t\t);\n\t\t}\n\n\t\tconst id = ulid();\n\t\tconst columnType = FIELD_TYPE_TO_COLUMN[input.type];\n\t\tassertIndexableField(input.type, input.indexed, input.slug);\n\n\t\t// Get max sort order\n\t\tconst maxSort = await this.db\n\t\t\t.selectFrom(\"_emdash_fields\")\n\t\t\t.where(\"collection_id\", \"=\", collection.id)\n\t\t\t.select((eb) => eb.fn.max<number>(\"sort_order\").as(\"max\"))\n\t\t\t.executeTakeFirst();\n\n\t\tconst sortOrder = input.sortOrder ?? (maxSort?.max ?? -1) + 1;\n\t\tconst activeCoverageInvalidated = await invalidateContentMediaUsageSchemaChange(\n\t\t\tthis.db,\n\t\t\tcollectionSlug,\n\t\t);\n\n\t\tlet schemaMutated = false;\n\t\ttry {\n\t\t\tconst created = await withTransaction(this.db, async (trx) => {\n\t\t\t\t// Insert field record\n\t\t\t\tawait trx\n\t\t\t\t\t.insertInto(\"_emdash_fields\")\n\t\t\t\t\t.values({\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tcollection_id: collection.id,\n\t\t\t\t\t\tslug: input.slug,\n\t\t\t\t\t\tlabel: input.label,\n\t\t\t\t\t\ttype: input.type,\n\t\t\t\t\t\tcolumn_type: columnType,\n\t\t\t\t\t\trequired: input.required ? 1 : 0,\n\t\t\t\t\t\tunique: input.unique ? 1 : 0,\n\t\t\t\t\t\tdefault_value:\n\t\t\t\t\t\t\tinput.defaultValue !== undefined ? JSON.stringify(input.defaultValue) : null,\n\t\t\t\t\t\tvalidation: input.validation ? JSON.stringify(input.validation) : null,\n\t\t\t\t\t\twidget: input.widget ?? null,\n\t\t\t\t\t\toptions: input.options ? JSON.stringify(input.options) : null,\n\t\t\t\t\t\tsort_order: sortOrder,\n\t\t\t\t\t\tsearchable: input.searchable ? 1 : 0,\n\t\t\t\t\t\tindexed: input.indexed ? 1 : 0,\n\t\t\t\t\t\ttranslatable: input.translatable === false ? 0 : 1,\n\t\t\t\t\t})\n\t\t\t\t\t.execute();\n\t\t\t\tschemaMutated = true;\n\n\t\t\t\t// Add column to content table — pass trx to stay on the same connection\n\t\t\t\tawait this.addColumn(\n\t\t\t\t\tcollectionSlug,\n\t\t\t\t\tinput.slug,\n\t\t\t\t\tinput.type,\n\t\t\t\t\t{\n\t\t\t\t\t\trequired: input.required,\n\t\t\t\t\t\tdefaultValue: input.defaultValue,\n\t\t\t\t\t},\n\t\t\t\t\ttrx,\n\t\t\t\t);\n\n\t\t\t\tif (input.indexed) {\n\t\t\t\t\tawait this.createFieldIndex(collectionSlug, id, input.slug, trx);\n\t\t\t\t}\n\n\t\t\t\t// Read the created field via trx (not this.db) to avoid connection mutex deadlock\n\t\t\t\tconst fieldRow = await trx\n\t\t\t\t\t.selectFrom(\"_emdash_fields\")\n\t\t\t\t\t.where(\"collection_id\", \"=\", collection.id)\n\t\t\t\t\t.where(\"slug\", \"=\", input.slug)\n\t\t\t\t\t.selectAll()\n\t\t\t\t\t.executeTakeFirst();\n\n\t\t\t\tif (!fieldRow) {\n\t\t\t\t\tthrow new SchemaError(\"Failed to create field\", \"CREATE_FAILED\");\n\t\t\t\t}\n\n\t\t\t\tconst field = this.mapFieldRow(fieldRow);\n\n\t\t\t\t// Sync search state if this field is searchable; support checks are handled by syncSearchState()\n\t\t\t\tif (input.searchable) {\n\t\t\t\t\tawait this.syncSearchState(collectionSlug, trx);\n\t\t\t\t}\n\n\t\t\t\treturn field;\n\t\t\t});\n\t\t\tif (activeCoverageInvalidated) {\n\t\t\t\tawait invalidateContentMediaUsageSchemaChange(this.db, collectionSlug);\n\t\t\t} else {\n\t\t\t\tawait markContentMediaUsageCollectionStaleSafely(\n\t\t\t\t\tthis.db,\n\t\t\t\t\tcollectionSlug,\n\t\t\t\t\t\"CONTENT_USAGE_STALE\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.notifyTypegen();\n\t\t\treturn created;\n\t\t} catch (error) {\n\t\t\tif (schemaMutated) {\n\t\t\t\tif (activeCoverageInvalidated) {\n\t\t\t\t\tawait invalidateContentMediaUsageSchemaChange(this.db, collectionSlug);\n\t\t\t\t} else {\n\t\t\t\t\tawait markContentMediaUsageCollectionStaleSafely(\n\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\tcollectionSlug,\n\t\t\t\t\t\t\"CONTENT_USAGE_STALE\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Update a field\n\t */\n\tasync updateField(\n\t\tcollectionSlug: string,\n\t\tfieldSlug: string,\n\t\tinput: UpdateFieldInput,\n\t): Promise<Field> {\n\t\tlet activeCoverageInvalidated = false;\n\t\tlet schemaMutated = false;\n\t\ttry {\n\t\t\tconst updatedField = await withTransaction(this.db, async (trx) => {\n\t\t\t\tconst collectionRow = await trx\n\t\t\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t\t\t.where(\"slug\", \"=\", collectionSlug)\n\t\t\t\t\t.select([\"id\", \"title_field\", \"date_field\"])\n\t\t\t\t\t.executeTakeFirst();\n\t\t\t\tconst fieldRow = collectionRow\n\t\t\t\t\t? await trx\n\t\t\t\t\t\t\t.selectFrom(\"_emdash_fields\")\n\t\t\t\t\t\t\t.where(\"collection_id\", \"=\", collectionRow.id)\n\t\t\t\t\t\t\t.where(\"slug\", \"=\", fieldSlug)\n\t\t\t\t\t\t\t.selectAll()\n\t\t\t\t\t\t\t.executeTakeFirst()\n\t\t\t\t\t: undefined;\n\t\t\t\tif (!fieldRow) {\n\t\t\t\t\tthrow new SchemaError(\n\t\t\t\t\t\t`Field \"${fieldSlug}\" not found in collection \"${collectionSlug}\"`,\n\t\t\t\t\t\t\"FIELD_NOT_FOUND\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst field = this.mapFieldRow(fieldRow);\n\t\t\t\tconst updates: Updateable<FieldTable> = {};\n\t\t\t\tlet nextType = field.type;\n\n\t\t\t\tif (input.type !== undefined && input.type !== field.type) {\n\t\t\t\t\tconst newColumnType = FIELD_TYPE_TO_COLUMN[input.type];\n\t\t\t\t\tif (newColumnType !== field.columnType) {\n\t\t\t\t\t\tthrow new SchemaError(\n\t\t\t\t\t\t\t`Cannot change field \"${fieldSlug}\" in collection \"${collectionSlug}\" from type ` +\n\t\t\t\t\t\t\t\t`\"${field.type}\" to \"${input.type}\": the underlying column type would change from ` +\n\t\t\t\t\t\t\t\t`${field.columnType} to ${newColumnType}, which requires a manual content migration.`,\n\t\t\t\t\t\t\t\"FIELD_TYPE_COLUMN_CHANGE\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (!TEXT_ALIAS_FIELD_TYPES.has(field.type) || !TEXT_ALIAS_FIELD_TYPES.has(input.type)) {\n\t\t\t\t\t\tthrow new SchemaError(\n\t\t\t\t\t\t\t`Cannot change field \"${fieldSlug}\" in collection \"${collectionSlug}\" from type ` +\n\t\t\t\t\t\t\t\t`\"${field.type}\" to \"${input.type}\" without a manual content migration.`,\n\t\t\t\t\t\t\t\"FIELD_TYPE_CHANGE_REQUIRES_MIGRATION\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (collectionRow?.title_field === fieldSlug && !TITLE_FIELD_TYPES.has(input.type)) {\n\t\t\t\t\t\tthrow new SchemaError(\n\t\t\t\t\t\t\t`titleField \"${fieldSlug}\" must stay a text field, not \"${input.type}\"`,\n\t\t\t\t\t\t\t\"INVALID_TITLE_FIELD\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (collectionRow?.date_field === fieldSlug && input.type !== \"datetime\") {\n\t\t\t\t\t\tthrow new SchemaError(\n\t\t\t\t\t\t\t`dateField \"${fieldSlug}\" must stay a datetime field, not \"${input.type}\"`,\n\t\t\t\t\t\t\t\"INVALID_DATE_FIELD\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tnextType = input.type;\n\t\t\t\t\tupdates.type = input.type;\n\t\t\t\t\tupdates.column_type = newColumnType;\n\t\t\t\t}\n\n\t\t\t\tif (input.required !== undefined && input.required !== field.required) {\n\t\t\t\t\tthrow new SchemaError(\n\t\t\t\t\t\t`Changing required for field \"${fieldSlug}\" requires a manual content migration.`,\n\t\t\t\t\t\t\"FIELD_UPDATE_REQUIRES_MIGRATION\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (input.unique !== undefined && input.unique !== field.unique) {\n\t\t\t\t\tthrow new SchemaError(\n\t\t\t\t\t\t`Changing unique for field \"${fieldSlug}\" requires a manual content migration.`,\n\t\t\t\t\t\t\"FIELD_UPDATE_REQUIRES_MIGRATION\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (input.translatable === false && field.translatable) {\n\t\t\t\t\tthrow new SchemaError(\n\t\t\t\t\t\t`Changing field \"${fieldSlug}\" to non-translatable requires a manual content migration.`,\n\t\t\t\t\t\t\"FIELD_UPDATE_REQUIRES_MIGRATION\",\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (input.label !== undefined) updates.label = input.label;\n\t\t\t\tif (input.required !== undefined) updates.required = input.required ? 1 : 0;\n\t\t\t\tif (input.unique !== undefined) updates.unique = input.unique ? 1 : 0;\n\t\t\t\tif (input.searchable !== undefined) updates.searchable = input.searchable ? 1 : 0;\n\t\t\t\tconst indexedChanged = input.indexed !== undefined && input.indexed !== field.indexed;\n\t\t\t\tif (indexedChanged) updates.indexed = input.indexed ? 1 : 0;\n\t\t\t\tif (input.translatable !== undefined) {\n\t\t\t\t\tupdates.translatable = input.translatable ? 1 : 0;\n\t\t\t\t}\n\t\t\t\tif (input.defaultValue !== undefined) {\n\t\t\t\t\tupdates.default_value = JSON.stringify(input.defaultValue);\n\t\t\t\t}\n\t\t\t\tif (input.validation !== undefined) {\n\t\t\t\t\tupdates.validation = input.validation ? JSON.stringify(input.validation) : null;\n\t\t\t\t}\n\t\t\t\tif (input.widget !== undefined) updates.widget = input.widget;\n\t\t\t\tif (input.options !== undefined) updates.options = JSON.stringify(input.options);\n\t\t\t\tif (input.sortOrder !== undefined) updates.sort_order = input.sortOrder;\n\n\t\t\t\tassertIndexableField(nextType, input.indexed ?? field.indexed, fieldSlug);\n\t\t\t\tif (Object.keys(updates).length === 0) return field;\n\n\t\t\t\tactiveCoverageInvalidated = await invalidateContentMediaUsageSchemaChange(\n\t\t\t\t\ttrx,\n\t\t\t\t\tcollectionSlug,\n\t\t\t\t);\n\n\t\t\t\tif (Object.keys(updates).length > 0) {\n\t\t\t\t\tawait trx.updateTable(\"_emdash_fields\").set(updates).where(\"id\", \"=\", field.id).execute();\n\t\t\t\t\tschemaMutated = true;\n\t\t\t\t}\n\n\t\t\t\tif (indexedChanged) {\n\t\t\t\t\tif (input.indexed) {\n\t\t\t\t\t\tawait this.createFieldIndex(collectionSlug, field.id, fieldSlug, trx);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.dropFieldIndex(field.id, trx);\n\t\t\t\t\t}\n\t\t\t\t\tschemaMutated = true;\n\t\t\t\t}\n\n\t\t\t\t// Read the updated field via trx (not this.db) to avoid connection mutex deadlock\n\t\t\t\tconst updatedRow = await trx\n\t\t\t\t\t.selectFrom(\"_emdash_fields\")\n\t\t\t\t\t.where(\"collection_id\", \"=\", field.collectionId)\n\t\t\t\t\t.where(\"slug\", \"=\", fieldSlug)\n\t\t\t\t\t.selectAll()\n\t\t\t\t\t.executeTakeFirst();\n\n\t\t\t\tif (!updatedRow) {\n\t\t\t\t\tthrow new SchemaError(\"Failed to update field\", \"UPDATE_FAILED\");\n\t\t\t\t}\n\n\t\t\t\tconst updated = this.mapFieldRow(updatedRow);\n\n\t\t\t\t// If searchable changed, sync FTS state for this collection\n\t\t\t\tconst searchableChanged =\n\t\t\t\t\tschemaMutated && input.searchable !== undefined && input.searchable !== field.searchable;\n\t\t\t\tif (searchableChanged) {\n\t\t\t\t\tawait this.syncSearchState(collectionSlug, trx);\n\t\t\t\t}\n\n\t\t\t\treturn updated;\n\t\t\t});\n\t\t\tif (schemaMutated) {\n\t\t\t\tif (activeCoverageInvalidated) {\n\t\t\t\t\tawait invalidateContentMediaUsageSchemaChange(this.db, collectionSlug);\n\t\t\t\t} else {\n\t\t\t\t\tawait markContentMediaUsageCollectionStaleSafely(\n\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\tcollectionSlug,\n\t\t\t\t\t\t\"CONTENT_USAGE_STALE\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.notifyTypegen();\n\t\t\treturn updatedField;\n\t\t} catch (error) {\n\t\t\tif (schemaMutated) {\n\t\t\t\tif (activeCoverageInvalidated) {\n\t\t\t\t\tawait invalidateContentMediaUsageSchemaChange(this.db, collectionSlug);\n\t\t\t\t} else {\n\t\t\t\t\tawait markContentMediaUsageCollectionStaleSafely(\n\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\tcollectionSlug,\n\t\t\t\t\t\t\"CONTENT_USAGE_STALE\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Synchronize an existing FTS index with the collection's current state.\n\t *\n\t * Only rebuilds or disables — never first-time enables. First-time FTS\n\t * enablement is handled by the seed's explicit enableSearch call (which\n\t * is try-caught) or the admin UI toggle.\n\t *\n\t * - FTS active + still has search support and searchable fields → rebuild\n\t * - FTS active + lost search support or no searchable fields → disable\n\t * - FTS not active → no-op\n\t *\n\t * Pass `db` when calling from within a transaction so FTS operations\n\t * participate in the same transaction and are rolled back on failure.\n\t */\n\tprivate async syncSearchState(collectionSlug: string, db?: Kysely<Database>): Promise<void> {\n\t\tconst conn = db ?? this.db;\n\t\tconst ftsManager = new FTSManager(conn);\n\n\t\t// Query via conn (not this.db) to avoid connection mutex deadlock when called inside a transaction\n\t\tconst row = await conn\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.where(\"slug\", \"=\", collectionSlug)\n\t\t\t.select(\"supports\")\n\t\t\t.executeTakeFirst();\n\t\tif (!row) return;\n\n\t\tconst wantsSearch = parseSupports(row.supports).includes(\"search\");\n\t\tconst searchableFields = await ftsManager.getSearchableFields(collectionSlug);\n\t\tconst config = await ftsManager.getSearchConfig(collectionSlug);\n\t\tconst ftsActive = config?.enabled === true;\n\n\t\tif (wantsSearch && searchableFields.length > 0 && ftsActive) {\n\t\t\tawait ftsManager.rebuildIndex(\n\t\t\t\tcollectionSlug,\n\t\t\t\tsearchableFields,\n\t\t\t\tconfig?.weights,\n\t\t\t\tconfig?.tokenize,\n\t\t\t);\n\t\t} else if (ftsActive && (!wantsSearch || searchableFields.length === 0)) {\n\t\t\tawait ftsManager.disableSearch(collectionSlug);\n\t\t}\n\t}\n\n\t/**\n\t * Delete a field\n\t */\n\tasync deleteField(collectionSlug: string, fieldSlug: string): Promise<void> {\n\t\tconst field = await this.getField(collectionSlug, fieldSlug);\n\t\tif (!field) {\n\t\t\tthrow new SchemaError(\n\t\t\t\t`Field \"${fieldSlug}\" not found in collection \"${collectionSlug}\"`,\n\t\t\t\t\"FIELD_NOT_FOUND\",\n\t\t\t);\n\t\t}\n\t\tconst activeCoverageInvalidated = await invalidateContentMediaUsageSchemaChange(\n\t\t\tthis.db,\n\t\t\tcollectionSlug,\n\t\t);\n\n\t\t// If this field powers the collection's titleField/dateField,\n\t\t// clear that reference in the same transaction — otherwise the metadata\n\t\t// would point at a dropped column and later crash the content list sort.\n\t\tconst collection = await this.getCollection(collectionSlug);\n\t\tconst clearTitle = collection?.titleField === fieldSlug;\n\t\tconst clearDate = collection?.dateField === fieldSlug;\n\n\t\tlet schemaMutated = false;\n\t\ttry {\n\t\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\t\t// Delete the field record first so syncSearchState sees the updated field list.\n\t\t\t\t// This ordering matters for searchable fields: SQLite prevents dropping a column\n\t\t\t\t// that is still referenced by a trigger. syncSearchState drops and recreates the\n\t\t\t\t// FTS triggers based on the remaining searchable fields, clearing the dependency\n\t\t\t\t// before we attempt the ALTER TABLE DROP COLUMN below.\n\t\t\t\tawait trx.deleteFrom(\"_emdash_fields\").where(\"id\", \"=\", field.id).execute();\n\t\t\t\tschemaMutated = true;\n\n\t\t\t\tif (clearTitle || clearDate) {\n\t\t\t\t\tawait trx\n\t\t\t\t\t\t.updateTable(\"_emdash_collections\")\n\t\t\t\t\t\t.set({\n\t\t\t\t\t\t\t...(clearTitle ? { title_field: null } : {}),\n\t\t\t\t\t\t\t...(clearDate ? { date_field: null } : {}),\n\t\t\t\t\t\t\tupdated_at: new Date().toISOString(),\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.where(\"slug\", \"=\", collectionSlug)\n\t\t\t\t\t\t.execute();\n\t\t\t\t}\n\n\t\t\t\t// If the deleted field was searchable, sync FTS state (removes old triggers)\n\t\t\t\tif (field.searchable) {\n\t\t\t\t\tawait this.syncSearchState(collectionSlug, trx);\n\t\t\t\t}\n\n\t\t\t\tif (field.indexed) {\n\t\t\t\t\tawait this.dropFieldIndex(field.id, trx);\n\t\t\t\t}\n\n\t\t\t\t// Drop column from content table — safe now because FTS triggers are gone\n\t\t\t\tawait this.dropColumn(collectionSlug, fieldSlug, trx);\n\t\t\t});\n\t\t\tif (activeCoverageInvalidated) {\n\t\t\t\tawait invalidateContentMediaUsageSchemaChange(this.db, collectionSlug);\n\t\t\t} else {\n\t\t\t\tawait markContentMediaUsageCollectionStaleSafely(\n\t\t\t\t\tthis.db,\n\t\t\t\t\tcollectionSlug,\n\t\t\t\t\t\"CONTENT_USAGE_STALE\",\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (schemaMutated) {\n\t\t\t\tif (activeCoverageInvalidated) {\n\t\t\t\t\tawait invalidateContentMediaUsageSchemaChange(this.db, collectionSlug);\n\t\t\t\t} else {\n\t\t\t\t\tawait markContentMediaUsageCollectionStaleSafely(\n\t\t\t\t\t\tthis.db,\n\t\t\t\t\t\tcollectionSlug,\n\t\t\t\t\t\t\"CONTENT_USAGE_STALE\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tthis.notifyTypegen();\n\t}\n\n\t/**\n\t * Reorder collections in the admin sidebar.\n\t *\n\t * `slugs` is the full desired order: every listed collection gets its\n\t * index as `sort_order`, and any collection left out has its explicit\n\t * position cleared, dropping it back to the alphabetical tail. Unknown or\n\t * duplicate slugs throw before anything is written.\n\t */\n\tasync reorderCollections(slugs: string[]): Promise<void> {\n\t\tconst known = new Set((await this.listCollections()).map((collection) => collection.slug));\n\n\t\tconst unknown = slugs.filter((slug) => !known.has(slug));\n\t\tif (unknown.length > 0) {\n\t\t\tthrow new SchemaError(\n\t\t\t\t`Unknown collection${unknown.length > 1 ? \"s\" : \"\"}: ${unknown.join(\", \")}`,\n\t\t\t\t\"COLLECTION_NOT_FOUND\",\n\t\t\t\t{ slugs: unknown },\n\t\t\t);\n\t\t}\n\n\t\tconst duplicates = slugs.filter((slug, index) => slugs.indexOf(slug) !== index);\n\t\tif (duplicates.length > 0) {\n\t\t\tthrow new SchemaError(\n\t\t\t\t`Duplicate collection${duplicates.length > 1 ? \"s\" : \"\"}: ${[...new Set(duplicates)].join(\", \")}`,\n\t\t\t\t\"DUPLICATE_SLUG\",\n\t\t\t\t{ slugs: [...new Set(duplicates)] },\n\t\t\t);\n\t\t}\n\n\t\tconst now = new Date().toISOString();\n\t\tconst ordered = new Set(slugs);\n\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\tfor (const [index, slug] of slugs.entries()) {\n\t\t\t\tawait trx\n\t\t\t\t\t.updateTable(\"_emdash_collections\")\n\t\t\t\t\t.set({ sort_order: index, updated_at: now })\n\t\t\t\t\t.where(\"slug\", \"=\", slug)\n\t\t\t\t\t.execute();\n\t\t\t}\n\n\t\t\tconst cleared = [...known].filter((slug) => !ordered.has(slug));\n\t\t\t// Chunked to stay under D1's bound-parameter limit; typical sites\n\t\t\t// clear far fewer than one chunk.\n\t\t\tfor (const slugChunk of chunks(cleared, SQL_BATCH_SIZE)) {\n\t\t\t\tawait trx\n\t\t\t\t\t.updateTable(\"_emdash_collections\")\n\t\t\t\t\t.set({ sort_order: null, updated_at: now })\n\t\t\t\t\t.where(\"slug\", \"in\", slugChunk)\n\t\t\t\t\t.execute();\n\t\t\t}\n\t\t});\n\t\tthis.notifyTypegen();\n\t}\n\n\t/**\n\t * Reorder fields\n\t */\n\tasync reorderFields(collectionSlug: string, fieldSlugs: string[]): Promise<void> {\n\t\tconst collection = await this.getCollection(collectionSlug);\n\t\tif (!collection) {\n\t\t\tthrow new SchemaError(`Collection \"${collectionSlug}\" not found`, \"COLLECTION_NOT_FOUND\");\n\t\t}\n\n\t\t// Update sort_order for each field\n\t\tfor (let i = 0; i < fieldSlugs.length; i++) {\n\t\t\tawait this.db\n\t\t\t\t.updateTable(\"_emdash_fields\")\n\t\t\t\t.set({ sort_order: i })\n\t\t\t\t.where(\"collection_id\", \"=\", collection.id)\n\t\t\t\t.where(\"slug\", \"=\", fieldSlugs[i])\n\t\t\t\t.execute();\n\t\t}\n\t\tthis.notifyTypegen();\n\t}\n\n\t// ============================================\n\t// DDL Operations\n\t// ============================================\n\n\t/**\n\t * Create a content table for a collection\n\t */\n\tprivate async createContentTable(\n\t\tslug: string,\n\t\tdb?: Kysely<Database>,\n\t\tfields: readonly CreateFieldInput[] = [],\n\t\toptions: { ifNotExists?: boolean } = {},\n\t): Promise<void> {\n\t\tconst conn = db ?? this.db;\n\t\tconst tableName = this.getTableName(slug);\n\n\t\tlet table: CreateTableBuilder<string, string> = conn.schema\n\t\t\t.createTable(tableName)\n\t\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t\t.addColumn(\"slug\", \"text\")\n\t\t\t.addColumn(\"status\", \"text\", (col) => col.defaultTo(\"draft\"))\n\t\t\t.addColumn(\"author_id\", \"text\")\n\t\t\t.addColumn(\"primary_byline_id\", \"text\")\n\t\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(conn)))\n\t\t\t.addColumn(\"updated_at\", \"text\", (col) => col.defaultTo(currentTimestamp(conn)))\n\t\t\t.addColumn(\"published_at\", \"text\")\n\t\t\t.addColumn(\"scheduled_at\", \"text\")\n\t\t\t.addColumn(\"deleted_at\", \"text\")\n\t\t\t.addColumn(\"version\", \"integer\", (col) => col.defaultTo(1))\n\t\t\t.addColumn(\"live_revision_id\", \"text\", (col) => col.references(\"revisions.id\"))\n\t\t\t.addColumn(\"draft_revision_id\", \"text\", (col) => col.references(\"revisions.id\"))\n\t\t\t.addColumn(\"locale\", \"text\", (col) => col.notNull().defaultTo(\"en\"))\n\t\t\t.addColumn(\"translation_group\", \"text\");\n\t\tif (options.ifNotExists) table = table.ifNotExists();\n\n\t\tfor (const field of fields) {\n\t\t\tconst columnName = this.getColumnName(field.slug);\n\t\t\tconst columnType = COLUMN_TYPE_TO_DATA_TYPE[FIELD_TYPE_TO_COLUMN[field.type]];\n\t\t\ttable = table.addColumn(columnName, columnType, (column) => {\n\t\t\t\tif (!field.required) return column;\n\n\t\t\t\tconst defaultValue =\n\t\t\t\t\tfield.defaultValue !== undefined\n\t\t\t\t\t\t? this.formatDefaultValue(field.defaultValue, field.type)\n\t\t\t\t\t\t: this.getEmptyDefault(field.type);\n\t\t\t\treturn column.notNull().defaultTo(sql.raw(defaultValue));\n\t\t\t});\n\t\t}\n\n\t\tawait table\n\t\t\t.addUniqueConstraint(`${tableName}_slug_locale_unique`, [\"slug\", \"locale\"])\n\t\t\t.execute();\n\n\t\tconst createIndex = options.ifNotExists ? sql`CREATE INDEX IF NOT EXISTS` : sql`CREATE INDEX`;\n\n\t\t// Create standard indexes\n\t\tawait sql`\n\t\t\t${createIndex} ${sql.ref(`idx_${tableName}_slug`)}\n\t\t\tON ${sql.ref(tableName)} (slug)\n\t\t`.execute(conn);\n\n\t\t// Name must stay identical to migration 074. `deleted_at` leads so the\n\t\t// scheduled-publishing sweep can seek it and walk `scheduled_at` for both\n\t\t// its range and its ORDER BY; a `scheduled_at`-only index leaves a\n\t\t// stats-blind planner reading every live row.\n\t\tawait sql`\n\t\t\t${createIndex} ${sql.ref(`idx_${tableName}_del_sched`)}\n\t\t\tON ${sql.ref(tableName)} (deleted_at, scheduled_at)\n\t\t\tWHERE scheduled_at IS NOT NULL\n\t\t`.execute(conn);\n\n\t\tawait sql`\n\t\t\t${createIndex} ${sql.ref(`idx_${tableName}_live_revision`)}\n\t\t\tON ${sql.ref(tableName)} (live_revision_id)\n\t\t`.execute(conn);\n\n\t\tawait sql`\n\t\t\t${createIndex} ${sql.ref(`idx_${tableName}_draft_revision`)}\n\t\t\tON ${sql.ref(tableName)} (draft_revision_id)\n\t\t`.execute(conn);\n\n\t\tawait sql`\n\t\t\t${createIndex} ${sql.ref(`idx_${tableName}_author`)}\n\t\t\tON ${sql.ref(tableName)} (author_id)\n\t\t`.execute(conn);\n\n\t\tawait sql`\n\t\t\t${createIndex} ${sql.ref(`idx_${tableName}_primary_byline`)}\n\t\t\tON ${sql.ref(tableName)} (primary_byline_id)\n\t\t`.execute(conn);\n\n\t\tawait sql`\n\t\t\t${createIndex} ${sql.ref(`idx_${tableName}_locale`)}\n\t\t\tON ${sql.ref(tableName)} (locale)\n\t\t`.execute(conn);\n\n\t\t// Names must stay identical to migration 055, which creates these indexes\n\t\t// on tables that already exist. Lookups that don't constrain `deleted_at`\n\t\t// (menu and reference resolution) need the first; reads that do need the\n\t\t// second.\n\t\tawait sql`\n\t\t\t${createIndex} ${sql.ref(`idx_${tableName}_tg_locale`)}\n\t\t\tON ${sql.ref(tableName)} (translation_group, locale)\n\t\t`.execute(conn);\n\n\t\tawait sql`\n\t\t\t${createIndex} ${sql.ref(`idx_${tableName}_del_tg_locale`)}\n\t\t\tON ${sql.ref(tableName)} (deleted_at, translation_group, locale)\n\t\t`.execute(conn);\n\n\t\t// Composite indexes for optimized query performance (see migration 033)\n\t\tawait sql`\n\t\t\t${createIndex} ${sql.ref(`idx_${tableName}_deleted_updated_id`)}\n\t\t\tON ${sql.ref(tableName)} (deleted_at, updated_at DESC, id DESC)\n\t\t`.execute(conn);\n\n\t\tawait sql`\n\t\t\t${createIndex} ${sql.ref(`idx_${tableName}_deleted_status`)}\n\t\t\tON ${sql.ref(tableName)} (deleted_at, status)\n\t\t`.execute(conn);\n\n\t\tawait sql`\n\t\t\t${createIndex} ${sql.ref(`idx_${tableName}_deleted_created_id`)}\n\t\t\tON ${sql.ref(tableName)} (deleted_at, created_at DESC, id DESC)\n\t\t`.execute(conn);\n\n\t\tawait sql`\n\t\t\t${createIndex} ${sql.ref(`idx_${tableName}_deleted_published_id`)}\n\t\t\tON ${sql.ref(tableName)} (deleted_at, published_at DESC, id DESC)\n\t\t`.execute(conn);\n\n\t\t// Locale-aware composite indexes for i18n content lists (see migration 041).\n\t\t// Short `loc_upd`/`loc_crt` suffix keeps the updated/created discriminator\n\t\t// inside Postgres's 63-byte identifier limit for long slugs; keep these\n\t\t// names identical to migration 041.\n\t\tawait sql`\n\t\t\t${createIndex} ${sql.ref(`idx_${tableName}_loc_upd`)}\n\t\t\tON ${sql.ref(tableName)} (deleted_at, locale, updated_at DESC, id DESC)\n\t\t`.execute(conn);\n\n\t\tawait sql`\n\t\t\t${createIndex} ${sql.ref(`idx_${tableName}_loc_crt`)}\n\t\t\tON ${sql.ref(tableName)} (deleted_at, locale, created_at DESC, id DESC)\n\t\t`.execute(conn);\n\t}\n\n\tprivate getFieldIndexName(fieldId: string): string {\n\t\tif (!FIELD_ID_PATTERN.test(fieldId)) {\n\t\t\tthrow new SchemaError(`Invalid field id \"${fieldId}\"`, \"INVALID_FIELD_ID\");\n\t\t}\n\t\treturn `idx_cf_${fieldId.toLowerCase()}`;\n\t}\n\n\tprivate getLocaleFieldIndexName(fieldId: string): string {\n\t\treturn `${this.getFieldIndexName(fieldId)}_loc`;\n\t}\n\n\tprivate async createFieldIndex(\n\t\tcollectionSlug: string,\n\t\tfieldId: string,\n\t\tfieldSlug: string,\n\t\tdb?: Kysely<Database>,\n\t): Promise<void> {\n\t\tconst conn = db ?? this.db;\n\t\tconst tableName = this.getTableName(collectionSlug);\n\t\tconst columnName = this.getColumnName(fieldSlug);\n\t\tconst indexName = this.getFieldIndexName(fieldId);\n\t\tconst localeIndexName = this.getLocaleFieldIndexName(fieldId);\n\n\t\tawait sql`\n\t\t\tCREATE INDEX IF NOT EXISTS ${sql.ref(indexName)}\n\t\t\tON ${sql.ref(tableName)} (\n\t\t\t\t(${sql.ref(columnName)} IS NOT NULL),\n\t\t\t\t${sql.ref(columnName)},\n\t\t\t\tid\n\t\t\t)\n\t\t\tWHERE deleted_at IS NULL\n\t\t`.execute(conn);\n\n\t\tawait sql`\n\t\t\tCREATE INDEX IF NOT EXISTS ${sql.ref(localeIndexName)}\n\t\t\tON ${sql.ref(tableName)} (\n\t\t\t\tlocale,\n\t\t\t\t(${sql.ref(columnName)} IS NOT NULL),\n\t\t\t\t${sql.ref(columnName)},\n\t\t\t\tid\n\t\t\t)\n\t\t\tWHERE deleted_at IS NULL\n\t\t`.execute(conn);\n\t}\n\n\tprivate async dropFieldIndex(fieldId: string, db?: Kysely<Database>): Promise<void> {\n\t\tconst conn = db ?? this.db;\n\t\tawait sql`DROP INDEX IF EXISTS ${sql.ref(this.getFieldIndexName(fieldId))}`.execute(conn);\n\t\tawait sql`DROP INDEX IF EXISTS ${sql.ref(this.getLocaleFieldIndexName(fieldId))}`.execute(conn);\n\t}\n\n\t/**\n\t * Add a column to a content table\n\t */\n\tprivate async addColumn(\n\t\tcollectionSlug: string,\n\t\tfieldSlug: string,\n\t\tfieldType: FieldType,\n\t\toptions?: { required?: boolean; defaultValue?: unknown },\n\t\tdb?: Kysely<Database>,\n\t): Promise<void> {\n\t\tconst conn = db ?? this.db;\n\t\tconst tableName = this.getTableName(collectionSlug);\n\t\tconst columnType = FIELD_TYPE_TO_COLUMN[fieldType];\n\t\tconst columnName = this.getColumnName(fieldSlug);\n\n\t\t// Build ALTER TABLE statement\n\t\t// Note: SQLite requires DEFAULT for NOT NULL columns in ALTER TABLE\n\t\tif (options?.required && options?.defaultValue !== undefined) {\n\t\t\tconst defaultVal = this.formatDefaultValue(options.defaultValue, fieldType);\n\t\t\tawait sql`\n\t\t\t\tALTER TABLE ${sql.ref(tableName)}\n\t\t\t\tADD COLUMN ${sql.ref(columnName)} ${sql.raw(columnType)} NOT NULL DEFAULT ${sql.raw(defaultVal)}\n\t\t\t`.execute(conn);\n\t\t} else if (options?.required) {\n\t\t\t// For required fields without default, use empty string/0 as default\n\t\t\tconst defaultVal = this.getEmptyDefault(fieldType);\n\t\t\tawait sql`\n\t\t\t\tALTER TABLE ${sql.ref(tableName)}\n\t\t\t\tADD COLUMN ${sql.ref(columnName)} ${sql.raw(columnType)} NOT NULL DEFAULT ${sql.raw(defaultVal)}\n\t\t\t`.execute(conn);\n\t\t} else {\n\t\t\tawait sql`\n\t\t\t\tALTER TABLE ${sql.ref(tableName)}\n\t\t\t\tADD COLUMN ${sql.ref(columnName)} ${sql.raw(columnType)}\n\t\t\t`.execute(conn);\n\t\t}\n\t}\n\n\t/**\n\t * Drop a column from a content table\n\t */\n\tprivate async dropColumn(\n\t\tcollectionSlug: string,\n\t\tfieldSlug: string,\n\t\tdb?: Kysely<Database>,\n\t): Promise<void> {\n\t\tconst tableName = this.getTableName(collectionSlug);\n\t\tconst columnName = this.getColumnName(fieldSlug);\n\n\t\tawait sql`\n\t\t\tALTER TABLE ${sql.ref(tableName)}\n\t\t\tDROP COLUMN ${sql.ref(columnName)}\n\t\t`.execute(db ?? this.db);\n\t}\n\n\t// ============================================\n\t// Helpers\n\t// ============================================\n\n\t/**\n\t * Check if a collection has any content\n\t */\n\tprivate async collectionHasContent(slug: string): Promise<boolean> {\n\t\tconst tableName = this.getTableName(slug);\n\t\ttry {\n\t\t\tconst result = await sql<{ count: number }>`\n\t\t\t\tSELECT COUNT(*) as count FROM ${sql.ref(tableName)}\n\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t`.execute(this.db);\n\t\t\treturn (result.rows[0]?.count ?? 0) > 0;\n\t\t} catch {\n\t\t\t// Table might not exist\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Get table name for a collection\n\t */\n\tprivate getTableName(slug: string): string {\n\t\tvalidateIdentifier(slug, \"collection slug\");\n\t\treturn `ec_${slug}`;\n\t}\n\n\t/**\n\t * Get column name for a field\n\t */\n\tprivate getColumnName(slug: string): string {\n\t\tvalidateIdentifier(slug, \"field slug\");\n\t\treturn slug;\n\t}\n\n\t/**\n\t * Validate a slug\n\t */\n\tprivate validateSlug(slug: string, type: \"collection\" | \"field\"): void {\n\t\tif (!slug || typeof slug !== \"string\") {\n\t\t\tthrow new SchemaError(`${type} slug is required`, \"INVALID_SLUG\");\n\t\t}\n\n\t\tif (!SLUG_VALIDATION_PATTERN.test(slug)) {\n\t\t\tthrow new SchemaError(\n\t\t\t\t`${type} slug must start with a letter and contain only lowercase letters, numbers, and underscores`,\n\t\t\t\t\"INVALID_SLUG\",\n\t\t\t);\n\t\t}\n\n\t\tif (slug.length > 63) {\n\t\t\tthrow new SchemaError(`${type} slug must be 63 characters or less`, \"INVALID_SLUG\");\n\t\t}\n\t}\n\n\t/**\n\t * Format a default value for SQL.\n\t *\n\t * SQLite `ALTER TABLE ADD COLUMN ... DEFAULT` requires a literal constant\n\t * expression — parameterized values cannot be used here. We manually escape\n\t * single quotes and coerce types to ensure the output is safe.\n\t *\n\t * INTEGER/REAL values are coerced through `Number()` which can only produce\n\t * digits, `.`, `-`, `e`, `Infinity`, or `NaN` — all safe in SQL.\n\t * TEXT/JSON values have single quotes escaped via SQL standard doubling (`''`).\n\t */\n\tprivate formatDefaultValue(value: unknown, fieldType: FieldType): string {\n\t\tif (value === null || value === undefined) {\n\t\t\treturn \"NULL\";\n\t\t}\n\n\t\tconst columnType = FIELD_TYPE_TO_COLUMN[fieldType];\n\n\t\tif (columnType === \"JSON\") {\n\t\t\t// JSON.stringify produces valid JSON; escape single quotes for SQL literal\n\t\t\tconst json = JSON.stringify(value);\n\t\t\treturn `'${json.replace(SINGLE_QUOTE_PATTERN, \"''\")}'`;\n\t\t}\n\n\t\tif (columnType === \"INTEGER\") {\n\t\t\tif (typeof value === \"boolean\") {\n\t\t\t\treturn value ? \"1\" : \"0\";\n\t\t\t}\n\t\t\tconst num = Number(value);\n\t\t\tif (!Number.isFinite(num)) {\n\t\t\t\treturn \"0\";\n\t\t\t}\n\t\t\treturn String(Math.trunc(num));\n\t\t}\n\n\t\tif (columnType === \"REAL\") {\n\t\t\tconst num = Number(value);\n\t\t\tif (!Number.isFinite(num)) {\n\t\t\t\treturn \"0\";\n\t\t\t}\n\t\t\treturn String(num);\n\t\t}\n\n\t\t// TEXT — escape single quotes via SQL standard doubling\n\t\tlet text: string;\n\t\tif (typeof value === \"string\") {\n\t\t\ttext = value;\n\t\t} else if (typeof value === \"number\" || typeof value === \"boolean\") {\n\t\t\ttext = String(value);\n\t\t} else if (typeof value === \"object\" && value !== null) {\n\t\t\ttext = JSON.stringify(value);\n\t\t} else {\n\t\t\ttext = \"\";\n\t\t}\n\t\treturn `'${text.replace(SINGLE_QUOTE_PATTERN, \"''\")}'`;\n\t}\n\n\t/**\n\t * Get empty default for a field type\n\t */\n\tprivate getEmptyDefault(fieldType: FieldType): string {\n\t\tconst columnType = FIELD_TYPE_TO_COLUMN[fieldType];\n\n\t\tswitch (columnType) {\n\t\t\tcase \"INTEGER\":\n\t\t\t\treturn \"0\";\n\t\t\tcase \"REAL\":\n\t\t\t\treturn \"0.0\";\n\t\t\tcase \"JSON\":\n\t\t\t\treturn \"'null'\";\n\t\t\tdefault:\n\t\t\t\treturn \"''\";\n\t\t}\n\t}\n\n\t/**\n\t * Map a collection row to a Collection object\n\t */\n\tprivate mapCollectionRow = (row: Selectable<CollectionTable>): Collection => {\n\t\tconst moderation = row.comments_moderation;\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\tslug: row.slug,\n\t\t\tlabel: row.label,\n\t\t\tlabelSingular: row.label_singular ?? undefined,\n\t\t\tdescription: row.description ?? undefined,\n\t\t\ticon: row.icon ?? undefined,\n\t\t\tadmin: parseCollectionAdmin(row.admin_config),\n\t\t\tsupports: parseSupports(row.supports),\n\t\t\tsource: row.source && isCollectionSource(row.source) ? row.source : undefined,\n\t\t\thasSeo: row.has_seo === 1,\n\t\t\t// Raw value; undefined when unset. The admin list resolves the\n\t\t\t// default (title fallback chain / updatedAt) at the point of use.\n\t\t\ttitleField: row.title_field ?? undefined,\n\t\t\tdateField: row.date_field ?? undefined,\n\t\t\turlPattern: row.url_pattern ?? undefined,\n\t\t\troutable: row.routable !== 0,\n\t\t\thidden: row.hidden === 1,\n\t\t\tsortOrder: row.sort_order ?? undefined,\n\t\t\tgroup: row.nav_group ?? undefined,\n\t\t\tcommentsEnabled: row.comments_enabled === 1,\n\t\t\tcommentsModeration:\n\t\t\t\tmoderation === \"all\" || moderation === \"first_time\" || moderation === \"none\"\n\t\t\t\t\t? moderation\n\t\t\t\t\t: \"first_time\",\n\t\t\tcommentsClosedAfterDays: row.comments_closed_after_days ?? 90,\n\t\t\tcommentsAutoApproveUsers: row.comments_auto_approve_users === 1,\n\t\t\teditLocking: row.edit_locking !== 0,\n\t\t\tcreatedAt: row.created_at,\n\t\t\tupdatedAt: row.updated_at,\n\t\t};\n\t};\n\n\t/**\n\t * Map a field row to a Field object\n\t */\n\tprivate mapFieldRow = (row: Selectable<FieldTable>): Field => {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\tcollectionId: row.collection_id,\n\t\t\tslug: row.slug,\n\t\t\tlabel: row.label,\n\t\t\ttype: isFieldType(row.type) ? row.type : \"string\",\n\t\t\tcolumnType: isColumnType(row.column_type) ? row.column_type : \"TEXT\",\n\t\t\trequired: row.required === 1,\n\t\t\tunique: row.unique === 1,\n\t\t\tdefaultValue: row.default_value ? JSON.parse(row.default_value) : undefined,\n\t\t\tvalidation: row.validation ? JSON.parse(row.validation) : undefined,\n\t\t\twidget: row.widget ?? undefined,\n\t\t\toptions: row.options ? JSON.parse(row.options) : undefined,\n\t\t\tsortOrder: row.sort_order,\n\t\t\tsearchable: row.searchable === 1,\n\t\t\tindexed: row.indexed === 1,\n\t\t\ttranslatable: row.translatable !== 0,\n\t\t\tcreatedAt: row.created_at,\n\t\t};\n\t};\n\n\t// ============================================\n\t// Discovery\n\t// ============================================\n\n\t/**\n\t * Discover orphaned content tables\n\t *\n\t * Finds ec_* tables that exist in the database but don't have a\n\t * corresponding entry in _emdash_collections.\n\t */\n\tasync discoverOrphanedTables(): Promise<\n\t\tArray<{ slug: string; tableName: string; rowCount: number }>\n\t> {\n\t\t// Get all ec_* tables\n\t\t// Content tables are ec_* (e.g., ec_posts, ec_pages)\n\t\t// Internal tables are _emdash_* (e.g., _emdash_collections, _emdash_fts_posts)\n\t\tconst allTables = await listTablesLike(this.db, \"ec_%\");\n\n\t\t// Get registered collections\n\t\tconst registered = await this.listCollections();\n\t\tconst registeredSlugs = new Set(registered.map((c) => c.slug));\n\n\t\t// Find orphans\n\t\tconst orphans: Array<{\n\t\t\tslug: string;\n\t\t\ttableName: string;\n\t\t\trowCount: number;\n\t\t}> = [];\n\n\t\tfor (const tableName of allTables) {\n\t\t\tconst slug = tableName.replace(EC_PREFIX_PATTERN, \"\");\n\n\t\t\tif (!registeredSlugs.has(slug)) {\n\t\t\t\t// Count rows in the orphaned table\n\t\t\t\ttry {\n\t\t\t\t\tconst countResult = await sql<{ count: number }>`\n\t\t\t\t\t\tSELECT COUNT(*) as count FROM ${sql.ref(tableName)}\n\t\t\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\t\t`.execute(this.db);\n\n\t\t\t\t\torphans.push({\n\t\t\t\t\t\tslug,\n\t\t\t\t\t\ttableName,\n\t\t\t\t\t\trowCount: countResult.rows[0]?.count ?? 0,\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\t// Table might have unexpected schema, still report it\n\t\t\t\t\torphans.push({\n\t\t\t\t\t\tslug,\n\t\t\t\t\t\ttableName,\n\t\t\t\t\t\trowCount: 0,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn orphans;\n\t}\n\n\t/**\n\t * Register an orphaned table as a collection\n\t *\n\t * Creates a _emdash_collections entry for an existing ec_* table.\n\t */\n\tasync registerOrphanedTable(\n\t\tslug: string,\n\t\toptions?: {\n\t\t\tlabel?: string;\n\t\t\tlabelSingular?: string;\n\t\t\tdescription?: string;\n\t\t},\n\t): Promise<Collection> {\n\t\t// Verify table exists\n\t\tconst tableName = this.getTableName(slug);\n\t\tif (await isMediaUsageCollectionSlugDeleting(this.db, slug)) {\n\t\t\tthrow new SchemaError(`Collection \"${slug}\" is already registered`, \"COLLECTION_EXISTS\");\n\t\t}\n\t\tconst exists = await tableExists(this.db, tableName);\n\n\t\tif (!exists) {\n\t\t\tthrow new SchemaError(`Table \"${tableName}\" does not exist`, \"TABLE_NOT_FOUND\");\n\t\t}\n\n\t\t// Check if already registered\n\t\tconst existing = await this.getCollection(slug);\n\t\tif (await isMediaUsageCollectionSlugDeleting(this.db, slug)) {\n\t\t\tthrow new SchemaError(`Collection \"${slug}\" is already registered`, \"COLLECTION_EXISTS\");\n\t\t}\n\t\tif (\n\t\t\texisting &&\n\t\t\t!(await canResumeMediaUsageCollectionCapture(this.db, {\n\t\t\t\tcollectionId: existing.id,\n\t\t\t\tcollectionSlug: existing.slug,\n\t\t\t}))\n\t\t) {\n\t\t\tthrow new SchemaError(`Collection \"${slug}\" is already registered`, \"COLLECTION_EXISTS\");\n\t\t}\n\n\t\t// Create collection entry\n\t\tconst proposedId = existing?.id ?? ulid();\n\t\tconst label = options?.label || this.slugToLabel(slug);\n\n\t\tlet collectionRegistered = false;\n\t\ttry {\n\t\t\tconst capture = await prepareMediaUsageCollectionCapture(this.db, {\n\t\t\t\tcollectionId: proposedId,\n\t\t\t\tcollectionSlug: slug,\n\t\t\t\tregisteredCollectionId: existing?.id,\n\t\t\t});\n\t\t\tif (capture.captureRequired) {\n\t\t\t\tawait installPreparedMediaUsageCollectionCapture(this.db, {\n\t\t\t\t\tcollectionId: capture.collectionId,\n\t\t\t\t\tcollectionSlug: slug,\n\t\t\t\t});\n\t\t\t\tawait markMediaUsageCollectionCaptureReady(this.db, {\n\t\t\t\t\tcollectionId: capture.collectionId,\n\t\t\t\t\tcollectionSlug: slug,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (!capture.registrationExists) {\n\t\t\t\tawait this.db\n\t\t\t\t\t.insertInto(\"_emdash_collections\")\n\t\t\t\t\t.values({\n\t\t\t\t\t\tid: capture.collectionId,\n\t\t\t\t\t\tslug,\n\t\t\t\t\t\tlabel,\n\t\t\t\t\t\tlabel_singular: options?.labelSingular ?? null,\n\t\t\t\t\t\tdescription: options?.description ?? null,\n\t\t\t\t\t\ticon: null,\n\t\t\t\t\t\tsupports: JSON.stringify([]),\n\t\t\t\t\t\tsource: \"discovered\",\n\t\t\t\t\t\thas_seo: 0,\n\t\t\t\t\t\turl_pattern: null,\n\t\t\t\t\t})\n\t\t\t\t\t.execute();\n\t\t\t\tcollectionRegistered = true;\n\t\t\t}\n\t\t\tif (capture.captureRequired) {\n\t\t\t\tawait finalizeMediaUsageCollectionCapture(this.db, {\n\t\t\t\t\tcollectionId: capture.collectionId,\n\t\t\t\t\tcollectionSlug: slug,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst collection = await this.getCollection(slug);\n\t\t\tif (!collection) {\n\t\t\t\tthrow new SchemaError(\"Failed to register orphaned table\", \"REGISTER_FAILED\");\n\t\t\t}\n\t\t\tawait markContentMediaUsageCollectionStaleSafely(this.db, slug, \"CONTENT_USAGE_STALE\");\n\t\t\tthis.notifyTypegen();\n\n\t\t\treturn collection;\n\t\t} catch (error) {\n\t\t\tif (collectionRegistered) {\n\t\t\t\tawait markContentMediaUsageCollectionStaleSafely(this.db, slug, \"CONTENT_USAGE_STALE\");\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Convert slug to human-readable label\n\t */\n\tprivate slugToLabel(slug: string): string {\n\t\treturn slug\n\t\t\t.replace(UNDERSCORE_PATTERN, \" \")\n\t\t\t.replace(WORD_BOUNDARY_PATTERN, (c) => c.toUpperCase());\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuDA,MAAM,0BAA0B;AAChC,MAAM,oBAAoB;AAC1B,MAAM,uBAAuB;AAC7B,MAAM,qBAAqB;AAC3B,MAAM,wBAAwB;AAC9B,MAAM,mBAAmB;;AAGzB,MAAM,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A2C,KAAK,IAAI,MAAM,sBAAsB;AACtF,QAAK,eAAe;AAEpB,UAAO;WACC,OAAO;AACf,OAAI,qBACH,OAAM,2CAA2C,KAAK,IAAI,MAAM,sBAAsB;AAEvF,SAAM;;;;;;CAOR,AAAQ,YAAY,MAAsB;AACzC,SAAO,KACL,QAAQ,oBAAoB,IAAI,CAChC,QAAQ,wBAAwB,MAAM,EAAE,aAAa,CAAC"}
@@ -1,4 +1,4 @@
1
- import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-bNiX6_DR.mjs";
1
+ import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-VG_tyqnP.mjs";
2
2
  import { i as InvalidCursorError, o as decodeCursor, s as encodeCursor } from "./types-CQPWhPxE.mjs";
3
3
  import { ulid } from "ulidx";
4
4
 
@@ -331,4 +331,4 @@ var RelationRepository = class {
331
331
 
332
332
  //#endregion
333
333
  export { RelationRepository as t };
334
- //# sourceMappingURL=relation-A6wLF_DS.mjs.map
334
+ //# sourceMappingURL=relation-DxgCHOBw.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"relation-A6wLF_DS.mjs","names":[],"sources":["../src/database/repositories/relation.ts"],"sourcesContent":["import type { Kysely, Selectable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { chunks, SQL_BATCH_SIZE } from \"../../utils/chunks.js\";\nimport type { Database, RelationTable, ContentReferenceTable } from \"../types.js\";\nimport { decodeCursor, encodeCursor, InvalidCursorError, type FindManyResult } from \"./types.js\";\n\nexport interface Relation {\n\tid: string;\n\tname: string;\n\tparentCollection: string;\n\tchildCollection: string;\n\tparentLabel: string;\n\tchildLabel: string;\n\tlocale: string;\n\ttranslationGroup: string;\n}\n\nexport interface CreateRelationInput {\n\tname: string;\n\t/** Required for a base relation; ignored (inherited from the source) when\n\t * `translationOf` is set. */\n\tparentCollection?: string;\n\t/** Required for a base relation; ignored (inherited from the source) when\n\t * `translationOf` is set. */\n\tchildCollection?: string;\n\tparentLabel: string;\n\tchildLabel: string;\n\t/** Omit to let the DB default (current value: 'en') apply. Higher layers\n\t * resolve locale from request context / i18n config. */\n\tlocale?: string;\n\t/** When set, joins the source relation's translation_group AND inherits its\n\t * structural fields (name, parentCollection, childCollection). Only locale +\n\t * labels may differ on a translation. */\n\ttranslationOf?: string;\n}\n\nexport interface UpdateRelationInput {\n\t/** Only localized fields are mutable per row. Changing structural fields\n\t * (name/collections) is a cross-group operation deferred to a later slice. */\n\tparentLabel?: string;\n\tchildLabel?: string;\n}\n\nexport interface ContentReference {\n\tid: string;\n\trelationGroup: string;\n\tparentGroup: string;\n\tchildGroup: string;\n\tsortOrder: number;\n}\n\n/**\n * Content-references repository.\n *\n * Owns relation *definitions* (`_emdash_relations`, row-per-locale, mirroring\n * `_emdash_taxonomy_defs`) and the *edge* junction (`_emdash_content_references`,\n * keyed by `translation_group` so edges are locale-agnostic, mirroring\n * `content_taxonomies`).\n *\n * Like `TaxonomyRepository`, this is not the validation boundary: it trusts its\n * typed inputs. The API slice supplies Zod schemas at the route and enforces\n * collection-agreement / relation-existence invariants in the handler. The repo\n * does not resolve locale fallbacks — callers pass the locale they want.\n */\nexport class RelationRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Create a relation. Without `translationOf`, mints a fresh group\n\t * (`translation_group = id`, matching the migration backfill pattern). With\n\t * `translationOf`, the structural fields (name, parentCollection,\n\t * childCollection) and the translation_group are inherited from the source;\n\t * locale and the two labels are taken from `input`.\n\t */\n\tasync create(input: CreateRelationInput): Promise<Relation> {\n\t\tconst id = ulid();\n\t\tconst now = new Date().toISOString();\n\n\t\tlet translationGroup = id;\n\t\tlet name: string;\n\t\tlet parentCollection: string;\n\t\tlet childCollection: string;\n\n\t\tif (input.translationOf) {\n\t\t\tconst source = await this.findById(input.translationOf);\n\t\t\t// translation_group is NOT NULL here, so we cannot fall back to a\n\t\t\t// fresh group like TaxonomyRepository does — a bad translationOf must\n\t\t\t// fail loudly rather than silently mint an unlinked relation.\n\t\t\tif (!source) throw new Error(\"Source relation for translation not found\");\n\t\t\ttranslationGroup = source.translationGroup;\n\t\t\tname = source.name;\n\t\t\tparentCollection = source.parentCollection;\n\t\t\tchildCollection = source.childCollection;\n\t\t} else {\n\t\t\t// A base relation carries its own structural fields. The API layer's Zod\n\t\t\t// schema enforces this; guard here too since the repo trusts its inputs\n\t\t\t// and the columns are NOT NULL.\n\t\t\tif (input.parentCollection === undefined || input.childCollection === undefined) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"parentCollection and childCollection are required unless translationOf is set\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tname = input.name;\n\t\t\tparentCollection = input.parentCollection;\n\t\t\tchildCollection = input.childCollection;\n\t\t}\n\n\t\tawait this.db\n\t\t\t.insertInto(\"_emdash_relations\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tname,\n\t\t\t\tparent_collection: parentCollection,\n\t\t\t\tchild_collection: childCollection,\n\t\t\t\tparent_label: input.parentLabel,\n\t\t\t\tchild_label: input.childLabel,\n\t\t\t\tcreated_at: now,\n\t\t\t\tupdated_at: now,\n\t\t\t\t// Omit `locale` so the DB DEFAULT (configured defaultLocale)\n\t\t\t\t// applies — matches TaxonomyRepository.create.\n\t\t\t\t...(input.locale !== undefined ? { locale: input.locale } : {}),\n\t\t\t\ttranslation_group: translationGroup,\n\t\t\t})\n\t\t\t.execute();\n\n\t\tconst relation = await this.findById(id);\n\t\tif (!relation) throw new Error(\"Failed to create relation\");\n\t\treturn relation;\n\t}\n\n\tasync findById(id: string): Promise<Relation | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? this.rowToRelation(row) : null;\n\t}\n\n\t/**\n\t * Find a relation by name. With `locale`, filter by it; without, return the\n\t * lowest-locale-code match deterministically. Mirrors\n\t * `TaxonomyRepository.findBySlug` — note this returns a single row, unlike\n\t * `TaxonomyRepository.findByName` which returns every term in a taxonomy.\n\t */\n\tasync findByName(name: string, locale?: string): Promise<Relation | null> {\n\t\tlet query = this.db.selectFrom(\"_emdash_relations\").selectAll().where(\"name\", \"=\", name);\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst row = await query.orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t\treturn row ? this.rowToRelation(row) : null;\n\t}\n\n\t/** Every translation sibling (including itself) sharing a translation_group. */\n\tasync findTranslations(translationGroup: string): Promise<Relation[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", translationGroup)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map((row) => this.rowToRelation(row));\n\t}\n\n\t/**\n\t * All relations, ordered by name then id (id is a stable tiebreak for\n\t * relations sharing a name across locales). Optionally filtered by locale.\n\t */\n\tasync list(locale?: string): Promise<Relation[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.selectAll()\n\t\t\t.orderBy(\"name\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToRelation(row));\n\t}\n\n\t/** Relations where `collection` is the parent OR the child side. */\n\tasync findForCollection(collection: string, locale?: string): Promise<Relation[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.selectAll()\n\t\t\t.where((eb) =>\n\t\t\t\teb.or([eb(\"parent_collection\", \"=\", collection), eb(\"child_collection\", \"=\", collection)]),\n\t\t\t)\n\t\t\t.orderBy(\"name\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToRelation(row));\n\t}\n\n\t/**\n\t * Update the localized labels of one relation row. Structural fields are\n\t * immutable here (a cross-group concern). No-ops when nothing is supplied.\n\t */\n\tasync update(id: string, input: UpdateRelationInput): Promise<Relation | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return null;\n\n\t\tconst updates: Record<string, unknown> = {};\n\t\tif (input.parentLabel !== undefined) updates.parent_label = input.parentLabel;\n\t\tif (input.childLabel !== undefined) updates.child_label = input.childLabel;\n\n\t\tif (Object.keys(updates).length > 0) {\n\t\t\tupdates.updated_at = new Date().toISOString();\n\t\t\tawait this.db.updateTable(\"_emdash_relations\").set(updates).where(\"id\", \"=\", id).execute();\n\t\t}\n\n\t\treturn this.findById(id);\n\t}\n\n\t/**\n\t * Delete one relation row. When it is the *last* translation of its group,\n\t * purge edges referencing that group (application-layer cascade — group\n\t * linking precludes a SQL FK). Mirrors `TaxonomyRepository.delete`.\n\t */\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst relation = await this.findById(id);\n\t\tif (!relation) return false;\n\n\t\tconst siblings = await this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"translation_group\", \"=\", relation.translationGroup)\n\t\t\t.where(\"id\", \"!=\", id)\n\t\t\t.execute();\n\t\tif (siblings.length === 0) {\n\t\t\tawait this.db\n\t\t\t\t.deleteFrom(\"_emdash_content_references\")\n\t\t\t\t.where(\"relation_group\", \"=\", relation.translationGroup)\n\t\t\t\t.execute();\n\t\t}\n\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_emdash_relations\")\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn (result.numDeletedRows ?? 0n) > 0n;\n\t}\n\n\t/** Normalize a relation id OR group to its translation_group. Returns null\n\t * for an unknown relation (edge methods then no-op, matching\n\t * `TaxonomyRepository.attachToEntry`). */\n\tprivate async resolveRelationGroup(idOrGroup: string): Promise<string | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.select([\"translation_group\"])\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\treturn row?.translation_group ?? null;\n\t}\n\n\tprivate rowToReference(row: Selectable<ContentReferenceTable>): ContentReference {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\trelationGroup: row.relation_group,\n\t\t\tparentGroup: row.parent_group,\n\t\t\tchildGroup: row.child_group,\n\t\t\tsortOrder: row.sort_order,\n\t\t};\n\t}\n\n\t/**\n\t * Link `parentGroup → childGroup` under a relation. `relation` is a relation\n\t * id or group. Idempotent (onConflict doNothing against the unique edge).\n\t * `sortOrder` defaults to append: max(sort_order)+1 within (relation, parent).\n\t *\n\t * The default-append MAX→INSERT is not atomic: concurrent appends without an\n\t * explicit `sortOrder` may both read the same max and collide on sort_order,\n\t * and onConflict silently drops the loser. Callers needing strict ordering\n\t * under concurrency should pass `sortOrder` explicitly (or serialize).\n\t */\n\tasync addReference(\n\t\trelation: string,\n\t\tparentGroup: string,\n\t\tchildGroup: string,\n\t\tsortOrder?: number,\n\t): Promise<void> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return;\n\n\t\tlet order = sortOrder;\n\t\tif (order === undefined) {\n\t\t\tconst max = await this.db\n\t\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t\t.select((eb) => eb.fn.max(\"sort_order\").as(\"max\"))\n\t\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t\t.where(\"parent_group\", \"=\", parentGroup)\n\t\t\t\t.executeTakeFirst();\n\t\t\torder = max?.max === null || max?.max === undefined ? 0 : Number(max.max) + 1;\n\t\t}\n\n\t\tawait this.db\n\t\t\t.insertInto(\"_emdash_content_references\")\n\t\t\t.values({\n\t\t\t\tid: ulid(),\n\t\t\t\trelation_group: relationGroup,\n\t\t\t\tparent_group: parentGroup,\n\t\t\t\tchild_group: childGroup,\n\t\t\t\tsort_order: order,\n\t\t\t\tcreated_at: new Date().toISOString(),\n\t\t\t})\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.execute();\n\t}\n\n\t/** Remove one `parentGroup → childGroup` edge under a relation. */\n\tasync removeReference(relation: string, parentGroup: string, childGroup: string): Promise<void> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return;\n\n\t\tawait this.db\n\t\t\t.deleteFrom(\"_emdash_content_references\")\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"parent_group\", \"=\", parentGroup)\n\t\t\t.where(\"child_group\", \"=\", childGroup)\n\t\t\t.execute();\n\t}\n\n\t/** Forward traversal: a parent's children for a relation, ordered. */\n\tasync getChildren(relation: string, parentGroup: string): Promise<ContentReference[]> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return [];\n\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.selectAll()\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"parent_group\", \"=\", parentGroup)\n\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map((row) => this.rowToReference(row));\n\t}\n\n\t/**\n\t * Forward traversal, paginated: one page of a parent's children for a\n\t * relation, ordered by `(sort_order, id)`. Use this on request paths — a\n\t * parent's children are capped but still up to 1000, and an unbounded read\n\t * scales poorly. Returns `{ items, nextCursor? }`; the cursor's order value is\n\t * the row's `sort_order`. Default limit 50, max 100.\n\t */\n\tasync getChildrenPage(\n\t\trelation: string,\n\t\tparentGroup: string,\n\t\toptions: { limit?: number; cursor?: string } = {},\n\t): Promise<FindManyResult<ContentReference>> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return { items: [] };\n\n\t\tconst limit = Math.min(options.limit || 50, 100);\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.selectAll()\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"parent_group\", \"=\", parentGroup);\n\n\t\tif (options.cursor) {\n\t\t\tconst decoded = decodeCursor(options.cursor);\n\t\t\tconst sortOrder = Number(decoded.orderValue);\n\t\t\t// `decodeCursor` only guarantees `orderValue` is a string; a hand-crafted\n\t\t\t// cursor with a non-numeric order value would coerce to NaN and blow up at\n\t\t\t// the driver bind as a 500. A bad cursor is a client error — surface it as\n\t\t\t// INVALID_CURSOR (400). Server-issued cursors are always numeric here.\n\t\t\tif (!Number.isFinite(sortOrder)) throw new InvalidCursorError(options.cursor);\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.or([\n\t\t\t\t\teb(\"sort_order\", \">\", sortOrder),\n\t\t\t\t\teb.and([eb(\"sort_order\", \"=\", sortOrder), eb(\"id\", \">\", decoded.id)]),\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\n\t\tconst rows = await query\n\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\")\n\t\t\t.limit(limit + 1)\n\t\t\t.execute();\n\n\t\tconst hasMore = rows.length > limit;\n\t\tconst items = rows.slice(0, limit).map((row) => this.rowToReference(row));\n\t\tconst result: FindManyResult<ContentReference> = { items };\n\t\tconst last = items.at(-1);\n\t\tif (hasMore && last) {\n\t\t\tresult.nextCursor = encodeCursor(String(last.sortOrder), last.id);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Backlink traversal: the parents that reference a child for a relation. */\n\tasync getParents(relation: string, childGroup: string): Promise<ContentReference[]> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return [];\n\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.selectAll()\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"child_group\", \"=\", childGroup)\n\t\t\t.orderBy(\"id\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map((row) => this.rowToReference(row));\n\t}\n\n\t/**\n\t * Replace all children of `parentGroup` under a relation with `childGroups`,\n\t * assigning positional sort_order (index in the deduped array). Deletes the\n\t * old set for this (relation, parent) and re-inserts — simple and correct;\n\t * the set is small (one parent's children). Mirrors the intent of\n\t * `TaxonomyRepository.setTermsForEntry`.\n\t *\n\t * A parent references a given child at most once (the unique edge), so\n\t * duplicate `childGroups` are collapsed first-occurrence-wins rather than\n\t * relying on the insert's onConflict to silently drop them. Not wrapped in a\n\t * transaction: a crash between the delete and insert leaves the parent with\n\t * no children — acceptable for a replace-all, since a retry restores state.\n\t *\n\t * Concurrency: two simultaneous replace-all calls for the same (relation,\n\t * parent) can interleave their deletes and inserts and merge into the union of\n\t * both sets (a lost update — neither \"replace\" wins). This is non-corrupting —\n\t * keyset pagination stays totally ordered via the `(sort_order, id)` tiebreak\n\t * even with duplicate sort_orders — and a single client editing one parent's\n\t * children serially never hits it. A D1-portable fix isn't available (no\n\t * multi-statement transactions), so concurrent replace-all on one parent is\n\t * unsupported by design rather than guarded here.\n\t */\n\tasync setChildren(relation: string, parentGroup: string, childGroups: string[]): Promise<void> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return;\n\n\t\tawait this.db\n\t\t\t.deleteFrom(\"_emdash_content_references\")\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"parent_group\", \"=\", parentGroup)\n\t\t\t.execute();\n\n\t\t// Collapse duplicates so positional sort_order has no gaps.\n\t\tconst uniqueChildGroups = [...new Set(childGroups)];\n\t\tif (uniqueChildGroups.length === 0) return;\n\n\t\tconst now = new Date().toISOString();\n\t\tawait this.db\n\t\t\t.insertInto(\"_emdash_content_references\")\n\t\t\t.values(\n\t\t\t\tuniqueChildGroups.map((childGroup, index) => ({\n\t\t\t\t\tid: ulid(),\n\t\t\t\t\trelation_group: relationGroup,\n\t\t\t\t\tparent_group: parentGroup,\n\t\t\t\t\tchild_group: childGroup,\n\t\t\t\t\tsort_order: index,\n\t\t\t\t\tcreated_at: now,\n\t\t\t\t})),\n\t\t\t)\n\t\t\t// Belt-and-suspenders: the DELETE above already cleared this\n\t\t\t// (relation, parent), so no conflict is possible within one call.\n\t\t\t// This is NOT a concurrency guarantee — delete-then-insert is not atomic.\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.execute();\n\t}\n\n\t/**\n\t * Backlink traversal, paginated: one page of the parents that reference a\n\t * child for a relation, ordered by `id`. Unlike a parent's children, a\n\t * child's backlinks are *unbounded* — one popular entry can be referenced by\n\t * arbitrarily many parents — so this read must paginate. Returns\n\t * `{ items, nextCursor? }`; the cursor's order value is the row `id`. Default\n\t * limit 50, max 100.\n\t */\n\tasync getParentsPage(\n\t\trelation: string,\n\t\tchildGroup: string,\n\t\toptions: { limit?: number; cursor?: string } = {},\n\t): Promise<FindManyResult<ContentReference>> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return { items: [] };\n\n\t\tconst limit = Math.min(options.limit || 50, 100);\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.selectAll()\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"child_group\", \"=\", childGroup);\n\n\t\tif (options.cursor) {\n\t\t\tconst decoded = decodeCursor(options.cursor);\n\t\t\tquery = query.where(\"id\", \">\", decoded.id);\n\t\t}\n\n\t\tconst rows = await query\n\t\t\t.orderBy(\"id\", \"asc\")\n\t\t\t.limit(limit + 1)\n\t\t\t.execute();\n\n\t\tconst hasMore = rows.length > limit;\n\t\tconst items = rows.slice(0, limit).map((row) => this.rowToReference(row));\n\t\tconst result: FindManyResult<ContentReference> = { items };\n\t\tconst last = items.at(-1);\n\t\tif (hasMore && last) {\n\t\t\tresult.nextCursor = encodeCursor(last.id, last.id);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Remove every edge where `group` is the parent OR the child — i.e. ensure no\n\t * orphaned reference edges survive when a content entry is deleted. The\n\t * application-layer cascade that group-linking precludes at the SQL level.\n\t * Wiring this into the content-delete path is a later (handler) slice.\n\t * Returns the number of edges removed.\n\t */\n\tasync clearReferencesForGroup(group: string): Promise<number> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_emdash_content_references\")\n\t\t\t.where((eb) => eb.or([eb(\"parent_group\", \"=\", group), eb(\"child_group\", \"=\", group)]))\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result.numDeletedRows ?? 0);\n\t}\n\n\t/** Count a parent's children under a relation. */\n\tasync countChildren(relation: string, parentGroup: string): Promise<number> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return 0;\n\t\tconst result = await this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.select((eb) => eb.fn.count(\"id\").as(\"count\"))\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"parent_group\", \"=\", parentGroup)\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/** Count a child's parents (backlinks) under a relation. */\n\tasync countParents(relation: string, childGroup: string): Promise<number> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return 0;\n\t\tconst result = await this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.select((eb) => eb.fn.count(\"id\").as(\"count\"))\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"child_group\", \"=\", childGroup)\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/**\n\t * Batch child-counts for many parents under a relation. Chunks at\n\t * SQL_BATCH_SIZE for D1's bind-parameter limit. Returns parent_group → count\n\t * (parents with no children are absent from the map). Mirrors\n\t * `TaxonomyRepository.countEntriesForTerms`.\n\t */\n\tasync countChildrenForParents(\n\t\trelation: string,\n\t\tparentGroups: string[],\n\t): Promise<Map<string, number>> {\n\t\tconst counts = new Map<string, number>();\n\t\tif (parentGroups.length === 0) return counts;\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return counts;\n\n\t\tfor (const chunk of chunks(parentGroups, SQL_BATCH_SIZE)) {\n\t\t\tconst rows = await this.db\n\t\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t\t.select([\"parent_group\", (eb) => eb.fn.count(\"id\").as(\"count\")])\n\t\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t\t.where(\"parent_group\", \"in\", chunk)\n\t\t\t\t.groupBy(\"parent_group\")\n\t\t\t\t.execute();\n\t\t\tfor (const row of rows) {\n\t\t\t\tcounts.set(row.parent_group, Number(row.count ?? 0));\n\t\t\t}\n\t\t}\n\t\treturn counts;\n\t}\n\n\tprivate rowToRelation(row: Selectable<RelationTable>): Relation {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\tname: row.name,\n\t\t\tparentCollection: row.parent_collection,\n\t\t\tchildCollection: row.child_collection,\n\t\t\tparentLabel: row.parent_label,\n\t\t\tchildLabel: row.child_label,\n\t\t\tlocale: row.locale,\n\t\t\ttranslationGroup: row.translation_group,\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiEA,IAAa,qBAAb,MAAgC;CAC/B,YAAY,AAAQ,IAAsB;EAAtB;;;;;;;;;CASpB,MAAM,OAAO,OAA+C;EAC3D,MAAM,KAAK,MAAM;EACjB,MAAM,uBAAM,IAAI,MAAM,EAAC,aAAa;EAEpC,IAAI,mBAAmB;EACvB,IAAI;EACJ,IAAI;EACJ,IAAI;AAEJ,MAAI,MAAM,eAAe;GACxB,MAAM,SAAS,MAAM,KAAK,SAAS,MAAM,cAAc;AAIvD,OAAI,CAAC,OAAQ,OAAM,IAAI,MAAM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AAO,GAAG,GAAG,MAAM,KAAK,CAAC,GAAG,QAAQ,CAAC,CAAC,CAC/D,MAAM,kBAAkB,KAAK,cAAc,CAC3C,MAAM,gBAAgB,MAAM,MAAM,CAClC,QAAQ,eAAe,CACvB,SAAS;AACX,QAAK,MAAM,OAAO,KACjB,QAAO,IAAI,IAAI,cAAc,OAAO,IAAI,SAAS,EAAE,CAAC;;AAGtD,SAAO;;CAGR,AAAQ,cAAc,KAA0C;AAC/D,SAAO;GACN,IAAI,IAAI;GACR,MAAM,IAAI;GACV,kBAAkB,IAAI;GACtB,iBAAiB,IAAI;GACrB,aAAa,IAAI;GACjB,YAAY,IAAI;GAChB,QAAQ,IAAI;GACZ,kBAAkB,IAAI;GACtB"}
1
+ {"version":3,"file":"relation-DxgCHOBw.mjs","names":[],"sources":["../src/database/repositories/relation.ts"],"sourcesContent":["import type { Kysely, Selectable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { chunks, SQL_BATCH_SIZE } from \"../../utils/chunks.js\";\nimport type { Database, RelationTable, ContentReferenceTable } from \"../types.js\";\nimport { decodeCursor, encodeCursor, InvalidCursorError, type FindManyResult } from \"./types.js\";\n\nexport interface Relation {\n\tid: string;\n\tname: string;\n\tparentCollection: string;\n\tchildCollection: string;\n\tparentLabel: string;\n\tchildLabel: string;\n\tlocale: string;\n\ttranslationGroup: string;\n}\n\nexport interface CreateRelationInput {\n\tname: string;\n\t/** Required for a base relation; ignored (inherited from the source) when\n\t * `translationOf` is set. */\n\tparentCollection?: string;\n\t/** Required for a base relation; ignored (inherited from the source) when\n\t * `translationOf` is set. */\n\tchildCollection?: string;\n\tparentLabel: string;\n\tchildLabel: string;\n\t/** Omit to let the DB default (current value: 'en') apply. Higher layers\n\t * resolve locale from request context / i18n config. */\n\tlocale?: string;\n\t/** When set, joins the source relation's translation_group AND inherits its\n\t * structural fields (name, parentCollection, childCollection). Only locale +\n\t * labels may differ on a translation. */\n\ttranslationOf?: string;\n}\n\nexport interface UpdateRelationInput {\n\t/** Only localized fields are mutable per row. Changing structural fields\n\t * (name/collections) is a cross-group operation deferred to a later slice. */\n\tparentLabel?: string;\n\tchildLabel?: string;\n}\n\nexport interface ContentReference {\n\tid: string;\n\trelationGroup: string;\n\tparentGroup: string;\n\tchildGroup: string;\n\tsortOrder: number;\n}\n\n/**\n * Content-references repository.\n *\n * Owns relation *definitions* (`_emdash_relations`, row-per-locale, mirroring\n * `_emdash_taxonomy_defs`) and the *edge* junction (`_emdash_content_references`,\n * keyed by `translation_group` so edges are locale-agnostic, mirroring\n * `content_taxonomies`).\n *\n * Like `TaxonomyRepository`, this is not the validation boundary: it trusts its\n * typed inputs. The API slice supplies Zod schemas at the route and enforces\n * collection-agreement / relation-existence invariants in the handler. The repo\n * does not resolve locale fallbacks — callers pass the locale they want.\n */\nexport class RelationRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Create a relation. Without `translationOf`, mints a fresh group\n\t * (`translation_group = id`, matching the migration backfill pattern). With\n\t * `translationOf`, the structural fields (name, parentCollection,\n\t * childCollection) and the translation_group are inherited from the source;\n\t * locale and the two labels are taken from `input`.\n\t */\n\tasync create(input: CreateRelationInput): Promise<Relation> {\n\t\tconst id = ulid();\n\t\tconst now = new Date().toISOString();\n\n\t\tlet translationGroup = id;\n\t\tlet name: string;\n\t\tlet parentCollection: string;\n\t\tlet childCollection: string;\n\n\t\tif (input.translationOf) {\n\t\t\tconst source = await this.findById(input.translationOf);\n\t\t\t// translation_group is NOT NULL here, so we cannot fall back to a\n\t\t\t// fresh group like TaxonomyRepository does — a bad translationOf must\n\t\t\t// fail loudly rather than silently mint an unlinked relation.\n\t\t\tif (!source) throw new Error(\"Source relation for translation not found\");\n\t\t\ttranslationGroup = source.translationGroup;\n\t\t\tname = source.name;\n\t\t\tparentCollection = source.parentCollection;\n\t\t\tchildCollection = source.childCollection;\n\t\t} else {\n\t\t\t// A base relation carries its own structural fields. The API layer's Zod\n\t\t\t// schema enforces this; guard here too since the repo trusts its inputs\n\t\t\t// and the columns are NOT NULL.\n\t\t\tif (input.parentCollection === undefined || input.childCollection === undefined) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"parentCollection and childCollection are required unless translationOf is set\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tname = input.name;\n\t\t\tparentCollection = input.parentCollection;\n\t\t\tchildCollection = input.childCollection;\n\t\t}\n\n\t\tawait this.db\n\t\t\t.insertInto(\"_emdash_relations\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tname,\n\t\t\t\tparent_collection: parentCollection,\n\t\t\t\tchild_collection: childCollection,\n\t\t\t\tparent_label: input.parentLabel,\n\t\t\t\tchild_label: input.childLabel,\n\t\t\t\tcreated_at: now,\n\t\t\t\tupdated_at: now,\n\t\t\t\t// Omit `locale` so the DB DEFAULT (configured defaultLocale)\n\t\t\t\t// applies — matches TaxonomyRepository.create.\n\t\t\t\t...(input.locale !== undefined ? { locale: input.locale } : {}),\n\t\t\t\ttranslation_group: translationGroup,\n\t\t\t})\n\t\t\t.execute();\n\n\t\tconst relation = await this.findById(id);\n\t\tif (!relation) throw new Error(\"Failed to create relation\");\n\t\treturn relation;\n\t}\n\n\tasync findById(id: string): Promise<Relation | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn row ? this.rowToRelation(row) : null;\n\t}\n\n\t/**\n\t * Find a relation by name. With `locale`, filter by it; without, return the\n\t * lowest-locale-code match deterministically. Mirrors\n\t * `TaxonomyRepository.findBySlug` — note this returns a single row, unlike\n\t * `TaxonomyRepository.findByName` which returns every term in a taxonomy.\n\t */\n\tasync findByName(name: string, locale?: string): Promise<Relation | null> {\n\t\tlet query = this.db.selectFrom(\"_emdash_relations\").selectAll().where(\"name\", \"=\", name);\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst row = await query.orderBy(\"locale\", \"asc\").executeTakeFirst();\n\t\treturn row ? this.rowToRelation(row) : null;\n\t}\n\n\t/** Every translation sibling (including itself) sharing a translation_group. */\n\tasync findTranslations(translationGroup: string): Promise<Relation[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", translationGroup)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map((row) => this.rowToRelation(row));\n\t}\n\n\t/**\n\t * All relations, ordered by name then id (id is a stable tiebreak for\n\t * relations sharing a name across locales). Optionally filtered by locale.\n\t */\n\tasync list(locale?: string): Promise<Relation[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.selectAll()\n\t\t\t.orderBy(\"name\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToRelation(row));\n\t}\n\n\t/** Relations where `collection` is the parent OR the child side. */\n\tasync findForCollection(collection: string, locale?: string): Promise<Relation[]> {\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.selectAll()\n\t\t\t.where((eb) =>\n\t\t\t\teb.or([eb(\"parent_collection\", \"=\", collection), eb(\"child_collection\", \"=\", collection)]),\n\t\t\t)\n\t\t\t.orderBy(\"name\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\");\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst rows = await query.execute();\n\t\treturn rows.map((row) => this.rowToRelation(row));\n\t}\n\n\t/**\n\t * Update the localized labels of one relation row. Structural fields are\n\t * immutable here (a cross-group concern). No-ops when nothing is supplied.\n\t */\n\tasync update(id: string, input: UpdateRelationInput): Promise<Relation | null> {\n\t\tconst existing = await this.findById(id);\n\t\tif (!existing) return null;\n\n\t\tconst updates: Record<string, unknown> = {};\n\t\tif (input.parentLabel !== undefined) updates.parent_label = input.parentLabel;\n\t\tif (input.childLabel !== undefined) updates.child_label = input.childLabel;\n\n\t\tif (Object.keys(updates).length > 0) {\n\t\t\tupdates.updated_at = new Date().toISOString();\n\t\t\tawait this.db.updateTable(\"_emdash_relations\").set(updates).where(\"id\", \"=\", id).execute();\n\t\t}\n\n\t\treturn this.findById(id);\n\t}\n\n\t/**\n\t * Delete one relation row. When it is the *last* translation of its group,\n\t * purge edges referencing that group (application-layer cascade — group\n\t * linking precludes a SQL FK). Mirrors `TaxonomyRepository.delete`.\n\t */\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst relation = await this.findById(id);\n\t\tif (!relation) return false;\n\n\t\tconst siblings = await this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"translation_group\", \"=\", relation.translationGroup)\n\t\t\t.where(\"id\", \"!=\", id)\n\t\t\t.execute();\n\t\tif (siblings.length === 0) {\n\t\t\tawait this.db\n\t\t\t\t.deleteFrom(\"_emdash_content_references\")\n\t\t\t\t.where(\"relation_group\", \"=\", relation.translationGroup)\n\t\t\t\t.execute();\n\t\t}\n\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_emdash_relations\")\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\t\treturn (result.numDeletedRows ?? 0n) > 0n;\n\t}\n\n\t/** Normalize a relation id OR group to its translation_group. Returns null\n\t * for an unknown relation (edge methods then no-op, matching\n\t * `TaxonomyRepository.attachToEntry`). */\n\tprivate async resolveRelationGroup(idOrGroup: string): Promise<string | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_emdash_relations\")\n\t\t\t.select([\"translation_group\"])\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\treturn row?.translation_group ?? null;\n\t}\n\n\tprivate rowToReference(row: Selectable<ContentReferenceTable>): ContentReference {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\trelationGroup: row.relation_group,\n\t\t\tparentGroup: row.parent_group,\n\t\t\tchildGroup: row.child_group,\n\t\t\tsortOrder: row.sort_order,\n\t\t};\n\t}\n\n\t/**\n\t * Link `parentGroup → childGroup` under a relation. `relation` is a relation\n\t * id or group. Idempotent (onConflict doNothing against the unique edge).\n\t * `sortOrder` defaults to append: max(sort_order)+1 within (relation, parent).\n\t *\n\t * The default-append MAX→INSERT is not atomic: concurrent appends without an\n\t * explicit `sortOrder` may both read the same max and collide on sort_order,\n\t * and onConflict silently drops the loser. Callers needing strict ordering\n\t * under concurrency should pass `sortOrder` explicitly (or serialize).\n\t */\n\tasync addReference(\n\t\trelation: string,\n\t\tparentGroup: string,\n\t\tchildGroup: string,\n\t\tsortOrder?: number,\n\t): Promise<void> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return;\n\n\t\tlet order = sortOrder;\n\t\tif (order === undefined) {\n\t\t\tconst max = await this.db\n\t\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t\t.select((eb) => eb.fn.max(\"sort_order\").as(\"max\"))\n\t\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t\t.where(\"parent_group\", \"=\", parentGroup)\n\t\t\t\t.executeTakeFirst();\n\t\t\torder = max?.max === null || max?.max === undefined ? 0 : Number(max.max) + 1;\n\t\t}\n\n\t\tawait this.db\n\t\t\t.insertInto(\"_emdash_content_references\")\n\t\t\t.values({\n\t\t\t\tid: ulid(),\n\t\t\t\trelation_group: relationGroup,\n\t\t\t\tparent_group: parentGroup,\n\t\t\t\tchild_group: childGroup,\n\t\t\t\tsort_order: order,\n\t\t\t\tcreated_at: new Date().toISOString(),\n\t\t\t})\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.execute();\n\t}\n\n\t/** Remove one `parentGroup → childGroup` edge under a relation. */\n\tasync removeReference(relation: string, parentGroup: string, childGroup: string): Promise<void> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return;\n\n\t\tawait this.db\n\t\t\t.deleteFrom(\"_emdash_content_references\")\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"parent_group\", \"=\", parentGroup)\n\t\t\t.where(\"child_group\", \"=\", childGroup)\n\t\t\t.execute();\n\t}\n\n\t/** Forward traversal: a parent's children for a relation, ordered. */\n\tasync getChildren(relation: string, parentGroup: string): Promise<ContentReference[]> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return [];\n\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.selectAll()\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"parent_group\", \"=\", parentGroup)\n\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map((row) => this.rowToReference(row));\n\t}\n\n\t/**\n\t * Forward traversal, paginated: one page of a parent's children for a\n\t * relation, ordered by `(sort_order, id)`. Use this on request paths — a\n\t * parent's children are capped but still up to 1000, and an unbounded read\n\t * scales poorly. Returns `{ items, nextCursor? }`; the cursor's order value is\n\t * the row's `sort_order`. Default limit 50, max 100.\n\t */\n\tasync getChildrenPage(\n\t\trelation: string,\n\t\tparentGroup: string,\n\t\toptions: { limit?: number; cursor?: string } = {},\n\t): Promise<FindManyResult<ContentReference>> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return { items: [] };\n\n\t\tconst limit = Math.min(options.limit || 50, 100);\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.selectAll()\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"parent_group\", \"=\", parentGroup);\n\n\t\tif (options.cursor) {\n\t\t\tconst decoded = decodeCursor(options.cursor);\n\t\t\tconst sortOrder = Number(decoded.orderValue);\n\t\t\t// `decodeCursor` only guarantees `orderValue` is a string; a hand-crafted\n\t\t\t// cursor with a non-numeric order value would coerce to NaN and blow up at\n\t\t\t// the driver bind as a 500. A bad cursor is a client error — surface it as\n\t\t\t// INVALID_CURSOR (400). Server-issued cursors are always numeric here.\n\t\t\tif (!Number.isFinite(sortOrder)) throw new InvalidCursorError(options.cursor);\n\t\t\tquery = query.where((eb) =>\n\t\t\t\teb.or([\n\t\t\t\t\teb(\"sort_order\", \">\", sortOrder),\n\t\t\t\t\teb.and([eb(\"sort_order\", \"=\", sortOrder), eb(\"id\", \">\", decoded.id)]),\n\t\t\t\t]),\n\t\t\t);\n\t\t}\n\n\t\tconst rows = await query\n\t\t\t.orderBy(\"sort_order\", \"asc\")\n\t\t\t.orderBy(\"id\", \"asc\")\n\t\t\t.limit(limit + 1)\n\t\t\t.execute();\n\n\t\tconst hasMore = rows.length > limit;\n\t\tconst items = rows.slice(0, limit).map((row) => this.rowToReference(row));\n\t\tconst result: FindManyResult<ContentReference> = { items };\n\t\tconst last = items.at(-1);\n\t\tif (hasMore && last) {\n\t\t\tresult.nextCursor = encodeCursor(String(last.sortOrder), last.id);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Backlink traversal: the parents that reference a child for a relation. */\n\tasync getParents(relation: string, childGroup: string): Promise<ContentReference[]> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return [];\n\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.selectAll()\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"child_group\", \"=\", childGroup)\n\t\t\t.orderBy(\"id\", \"asc\")\n\t\t\t.execute();\n\t\treturn rows.map((row) => this.rowToReference(row));\n\t}\n\n\t/**\n\t * Replace all children of `parentGroup` under a relation with `childGroups`,\n\t * assigning positional sort_order (index in the deduped array). Deletes the\n\t * old set for this (relation, parent) and re-inserts — simple and correct;\n\t * the set is small (one parent's children). Mirrors the intent of\n\t * `TaxonomyRepository.setTermsForEntry`.\n\t *\n\t * A parent references a given child at most once (the unique edge), so\n\t * duplicate `childGroups` are collapsed first-occurrence-wins rather than\n\t * relying on the insert's onConflict to silently drop them. Not wrapped in a\n\t * transaction: a crash between the delete and insert leaves the parent with\n\t * no children — acceptable for a replace-all, since a retry restores state.\n\t *\n\t * Concurrency: two simultaneous replace-all calls for the same (relation,\n\t * parent) can interleave their deletes and inserts and merge into the union of\n\t * both sets (a lost update — neither \"replace\" wins). This is non-corrupting —\n\t * keyset pagination stays totally ordered via the `(sort_order, id)` tiebreak\n\t * even with duplicate sort_orders — and a single client editing one parent's\n\t * children serially never hits it. A D1-portable fix isn't available (no\n\t * multi-statement transactions), so concurrent replace-all on one parent is\n\t * unsupported by design rather than guarded here.\n\t */\n\tasync setChildren(relation: string, parentGroup: string, childGroups: string[]): Promise<void> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return;\n\n\t\tawait this.db\n\t\t\t.deleteFrom(\"_emdash_content_references\")\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"parent_group\", \"=\", parentGroup)\n\t\t\t.execute();\n\n\t\t// Collapse duplicates so positional sort_order has no gaps.\n\t\tconst uniqueChildGroups = [...new Set(childGroups)];\n\t\tif (uniqueChildGroups.length === 0) return;\n\n\t\tconst now = new Date().toISOString();\n\t\tawait this.db\n\t\t\t.insertInto(\"_emdash_content_references\")\n\t\t\t.values(\n\t\t\t\tuniqueChildGroups.map((childGroup, index) => ({\n\t\t\t\t\tid: ulid(),\n\t\t\t\t\trelation_group: relationGroup,\n\t\t\t\t\tparent_group: parentGroup,\n\t\t\t\t\tchild_group: childGroup,\n\t\t\t\t\tsort_order: index,\n\t\t\t\t\tcreated_at: now,\n\t\t\t\t})),\n\t\t\t)\n\t\t\t// Belt-and-suspenders: the DELETE above already cleared this\n\t\t\t// (relation, parent), so no conflict is possible within one call.\n\t\t\t// This is NOT a concurrency guarantee — delete-then-insert is not atomic.\n\t\t\t.onConflict((oc) => oc.doNothing())\n\t\t\t.execute();\n\t}\n\n\t/**\n\t * Backlink traversal, paginated: one page of the parents that reference a\n\t * child for a relation, ordered by `id`. Unlike a parent's children, a\n\t * child's backlinks are *unbounded* — one popular entry can be referenced by\n\t * arbitrarily many parents — so this read must paginate. Returns\n\t * `{ items, nextCursor? }`; the cursor's order value is the row `id`. Default\n\t * limit 50, max 100.\n\t */\n\tasync getParentsPage(\n\t\trelation: string,\n\t\tchildGroup: string,\n\t\toptions: { limit?: number; cursor?: string } = {},\n\t): Promise<FindManyResult<ContentReference>> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return { items: [] };\n\n\t\tconst limit = Math.min(options.limit || 50, 100);\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.selectAll()\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"child_group\", \"=\", childGroup);\n\n\t\tif (options.cursor) {\n\t\t\tconst decoded = decodeCursor(options.cursor);\n\t\t\tquery = query.where(\"id\", \">\", decoded.id);\n\t\t}\n\n\t\tconst rows = await query\n\t\t\t.orderBy(\"id\", \"asc\")\n\t\t\t.limit(limit + 1)\n\t\t\t.execute();\n\n\t\tconst hasMore = rows.length > limit;\n\t\tconst items = rows.slice(0, limit).map((row) => this.rowToReference(row));\n\t\tconst result: FindManyResult<ContentReference> = { items };\n\t\tconst last = items.at(-1);\n\t\tif (hasMore && last) {\n\t\t\tresult.nextCursor = encodeCursor(last.id, last.id);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Remove every edge where `group` is the parent OR the child — i.e. ensure no\n\t * orphaned reference edges survive when a content entry is deleted. The\n\t * application-layer cascade that group-linking precludes at the SQL level.\n\t * Wiring this into the content-delete path is a later (handler) slice.\n\t * Returns the number of edges removed.\n\t */\n\tasync clearReferencesForGroup(group: string): Promise<number> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_emdash_content_references\")\n\t\t\t.where((eb) => eb.or([eb(\"parent_group\", \"=\", group), eb(\"child_group\", \"=\", group)]))\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result.numDeletedRows ?? 0);\n\t}\n\n\t/** Count a parent's children under a relation. */\n\tasync countChildren(relation: string, parentGroup: string): Promise<number> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return 0;\n\t\tconst result = await this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.select((eb) => eb.fn.count(\"id\").as(\"count\"))\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"parent_group\", \"=\", parentGroup)\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/** Count a child's parents (backlinks) under a relation. */\n\tasync countParents(relation: string, childGroup: string): Promise<number> {\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return 0;\n\t\tconst result = await this.db\n\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t.select((eb) => eb.fn.count(\"id\").as(\"count\"))\n\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t.where(\"child_group\", \"=\", childGroup)\n\t\t\t.executeTakeFirst();\n\t\treturn Number(result?.count ?? 0);\n\t}\n\n\t/**\n\t * Batch child-counts for many parents under a relation. Chunks at\n\t * SQL_BATCH_SIZE for D1's bind-parameter limit. Returns parent_group → count\n\t * (parents with no children are absent from the map). Mirrors\n\t * `TaxonomyRepository.countEntriesForTerms`.\n\t */\n\tasync countChildrenForParents(\n\t\trelation: string,\n\t\tparentGroups: string[],\n\t): Promise<Map<string, number>> {\n\t\tconst counts = new Map<string, number>();\n\t\tif (parentGroups.length === 0) return counts;\n\t\tconst relationGroup = await this.resolveRelationGroup(relation);\n\t\tif (!relationGroup) return counts;\n\n\t\tfor (const chunk of chunks(parentGroups, SQL_BATCH_SIZE)) {\n\t\t\tconst rows = await this.db\n\t\t\t\t.selectFrom(\"_emdash_content_references\")\n\t\t\t\t.select([\"parent_group\", (eb) => eb.fn.count(\"id\").as(\"count\")])\n\t\t\t\t.where(\"relation_group\", \"=\", relationGroup)\n\t\t\t\t.where(\"parent_group\", \"in\", chunk)\n\t\t\t\t.groupBy(\"parent_group\")\n\t\t\t\t.execute();\n\t\t\tfor (const row of rows) {\n\t\t\t\tcounts.set(row.parent_group, Number(row.count ?? 0));\n\t\t\t}\n\t\t}\n\t\treturn counts;\n\t}\n\n\tprivate rowToRelation(row: Selectable<RelationTable>): Relation {\n\t\treturn {\n\t\t\tid: row.id,\n\t\t\tname: row.name,\n\t\t\tparentCollection: row.parent_collection,\n\t\t\tchildCollection: row.child_collection,\n\t\t\tparentLabel: row.parent_label,\n\t\t\tchildLabel: row.child_label,\n\t\t\tlocale: row.locale,\n\t\t\ttranslationGroup: row.translation_group,\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiEA,IAAa,qBAAb,MAAgC;CAC/B,YAAY,AAAQ,IAAsB;EAAtB;;;;;;;;;CASpB,MAAM,OAAO,OAA+C;EAC3D,MAAM,KAAK,MAAM;EACjB,MAAM,uBAAM,IAAI,MAAM,EAAC,aAAa;EAEpC,IAAI,mBAAmB;EACvB,IAAI;EACJ,IAAI;EACJ,IAAI;AAEJ,MAAI,MAAM,eAAe;GACxB,MAAM,SAAS,MAAM,KAAK,SAAS,MAAM,cAAc;AAIvD,OAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,4CAA4C;AACzE,sBAAmB,OAAO;AAC1B,UAAO,OAAO;AACd,sBAAmB,OAAO;AAC1B,qBAAkB,OAAO;SACnB;AAIN,OAAI,MAAM,qBAAqB,UAAa,MAAM,oBAAoB,OACrE,OAAM,IAAI,MACT,gFACA;AAEF,UAAO,MAAM;AACb,sBAAmB,MA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cAAc,OAAO,IAAI,SAAS,EAAE,CAAC;;AAGtD,SAAO;;CAGR,AAAQ,cAAc,KAA0C;AAC/D,SAAO;GACN,IAAI,IAAI;GACR,MAAM,IAAI;GACV,kBAAkB,IAAI;GACtB,iBAAiB,IAAI;GACrB,aAAa,IAAI;GACjB,YAAY,IAAI;GAChB,QAAQ,IAAI;GACZ,kBAAkB,IAAI;GACtB"}
@@ -1,8 +1,8 @@
1
1
  import { a as resolveConfiguredLocale } from "./config-C3EBstHi.mjs";
2
- import { t as ContentRepository } from "./content-CP-SeXNa.mjs";
2
+ import { t as ContentRepository } from "./content-CNfMWuhY.mjs";
3
3
  import { i as InvalidCursorError } from "./types-CQPWhPxE.mjs";
4
- import { t as RelationRepository } from "./relation-A6wLF_DS.mjs";
5
- import { n as SchemaRegistry } from "./registry-Cx-jEJOS.mjs";
4
+ import { t as RelationRepository } from "./relation-DxgCHOBw.mjs";
5
+ import { n as SchemaRegistry } from "./registry-DTqaqxed.mjs";
6
6
 
7
7
  //#region src/api/handlers/relations.ts
8
8
  /** Map an edge-read failure: a bad pagination cursor is a 400 client error,
@@ -400,4 +400,4 @@ async function handleReferenceParentsGet(db, collection, entryId, relation, page
400
400
 
401
401
  //#endregion
402
402
  export { handleRelationDelete as a, handleRelationTranslations as c, handleRelationCreate as i, handleRelationUpdate as l, handleReferenceChildrenSet as n, handleRelationGet as o, handleReferenceParentsGet as r, handleRelationList as s, handleReferenceChildrenGet as t };
403
- //# sourceMappingURL=relations-Cj5hZ6Zg.mjs.map
403
+ //# sourceMappingURL=relations-KKDSLUwS.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"relations-Cj5hZ6Zg.mjs","names":[],"sources":["../src/api/handlers/relations.ts"],"sourcesContent":["import type { Kysely } from \"kysely\";\n\nimport { ContentRepository } from \"../../database/repositories/content.js\";\nimport {\n\tRelationRepository,\n\ttype ContentReference,\n\ttype CreateRelationInput,\n\ttype Relation,\n} from \"../../database/repositories/relation.js\";\nimport { InvalidCursorError } from \"../../database/repositories/types.js\";\nimport type { ContentItem } from \"../../database/repositories/types.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { resolveConfiguredLocale } from \"../../i18n/config.js\";\nimport { SchemaRegistry } from \"../../schema/registry.js\";\nimport type { ApiResult } from \"../types.js\";\n\n/** Map an edge-read failure: a bad pagination cursor is a 400 client error,\n * everything else is the generic 500-shaped reference-read error. */\nfunction referencesGetError(error: unknown): ApiResult<never> {\n\tif (error instanceof InvalidCursorError) {\n\t\treturn { success: false, error: { code: \"INVALID_CURSOR\", message: error.message } };\n\t}\n\treturn {\n\t\tsuccess: false,\n\t\terror: { code: \"REFERENCES_GET_ERROR\", message: \"Failed to get references\" },\n\t};\n}\n\n/** True for SQLite UNIQUE / Postgres unique_violation messages (matches the\n * fingerprint used in the content handlers). Narrow enough not to catch NOT\n * NULL / CHECK violations whose messages also say \"constraint\". */\nfunction isUniqueViolation(error: unknown): boolean {\n\tconst message = error instanceof Error ? error.message.toLowerCase() : \"\";\n\treturn message.includes(\"unique constraint failed\") || message.includes(\"duplicate key\");\n}\n\nexport async function handleRelationCreate(\n\tdb: Kysely<Database>,\n\tinput: CreateRelationInput,\n): Promise<ApiResult<{ relation: Relation }>> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\n\t\t// Invariant: a relation must point at collections that exist. There is no\n\t\t// SQL FK (group-linking precludes it), so a ghost collection would yield a\n\t\t// structurally-valid-but-permanently-useless relation. Skip when\n\t\t// `translationOf` is set — structural fields are then inherited from an\n\t\t// already-validated source, and the input collections are ignored.\n\t\tif (!input.translationOf) {\n\t\t\tif (!input.parentCollection || !input.childCollection) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"parentCollection and childCollection are required unless translationOf is set\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst registry = new SchemaRegistry(db);\n\t\t\tfor (const collection of [input.parentCollection, input.childCollection]) {\n\t\t\t\tif (!(await registry.getCollection(collection))) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\tcode: \"COLLECTION_NOT_FOUND\",\n\t\t\t\t\t\t\tmessage: `Collection '${collection}' not found`,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst relation = await repo.create({\n\t\t\t...input,\n\t\t\tlocale: input.locale ? resolveConfiguredLocale(input.locale) : undefined,\n\t\t});\n\t\treturn { success: true, data: { relation } };\n\t} catch (error) {\n\t\t// A bad `translationOf` makes the repo throw loudly rather than mint an\n\t\t// unlinked relation — surface it as 404, not a generic 500.\n\t\tif (\n\t\t\terror instanceof Error &&\n\t\t\terror.message.includes(\"Source relation for translation not found\")\n\t\t) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Source relation for translation not found\" },\n\t\t\t};\n\t\t}\n\t\t// UNIQUE(name, locale) collision, or a second translation for an\n\t\t// already-present (translation_group, locale) — both are client conflicts.\n\t\tif (isUniqueViolation(error)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\tmessage: \"A relation with this name or locale already exists\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"RELATION_CREATE_ERROR\", message: \"Failed to create relation\" },\n\t\t};\n\t}\n}\n\nexport async function handleRelationGet(\n\tdb: Kysely<Database>,\n\tid: string,\n): Promise<ApiResult<{ relation: Relation }>> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\t\tconst relation = await repo.findById(id);\n\t\tif (!relation) {\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Relation not found\" } };\n\t\t}\n\t\treturn { success: true, data: { relation } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"RELATION_GET_ERROR\", message: \"Failed to get relation\" },\n\t\t};\n\t}\n}\n\nexport async function handleRelationList(\n\tdb: Kysely<Database>,\n\topts: { locale?: string },\n): Promise<ApiResult<{ relations: Relation[] }>> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\t\tconst locale = opts.locale ? resolveConfiguredLocale(opts.locale) : undefined;\n\t\tconst relations = await repo.list(locale);\n\t\treturn { success: true, data: { relations } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"RELATION_LIST_ERROR\", message: \"Failed to list relations\" },\n\t\t};\n\t}\n}\n\nexport async function handleRelationUpdate(\n\tdb: Kysely<Database>,\n\tid: string,\n\tinput: { parentLabel?: string; childLabel?: string },\n): Promise<ApiResult<{ relation: Relation }>> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\t\tconst relation = await repo.update(id, input);\n\t\tif (!relation) {\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Relation not found\" } };\n\t\t}\n\t\treturn { success: true, data: { relation } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"RELATION_UPDATE_ERROR\", message: \"Failed to update relation\" },\n\t\t};\n\t}\n}\n\nexport async function handleRelationDelete(\n\tdb: Kysely<Database>,\n\tid: string,\n): Promise<ApiResult<{ deleted: true }>> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\t\tconst deleted = await repo.delete(id);\n\t\tif (!deleted) {\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Relation not found\" } };\n\t\t}\n\t\treturn { success: true, data: { deleted: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"RELATION_DELETE_ERROR\", message: \"Failed to delete relation\" },\n\t\t};\n\t}\n}\n\nexport async function handleRelationTranslations(\n\tdb: Kysely<Database>,\n\tid: string,\n): Promise<\n\tApiResult<{\n\t\ttranslationGroup: string;\n\t\ttranslations: {\n\t\t\tid: string;\n\t\t\tname: string;\n\t\t\tlocale: string;\n\t\t\tparentLabel: string;\n\t\t\tchildLabel: string;\n\t\t}[];\n\t}>\n> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\t\tconst relation = await repo.findById(id);\n\t\tif (!relation) {\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Relation not found\" } };\n\t\t}\n\t\tconst siblings = await repo.findTranslations(relation.translationGroup);\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\ttranslationGroup: relation.translationGroup,\n\t\t\t\ttranslations: siblings.map((r) => ({\n\t\t\t\t\tid: r.id,\n\t\t\t\t\tname: r.name,\n\t\t\t\t\tlocale: r.locale,\n\t\t\t\t\tparentLabel: r.parentLabel,\n\t\t\t\t\tchildLabel: r.childLabel,\n\t\t\t\t})),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"RELATION_TRANSLATIONS_ERROR\", message: \"Failed to get translations\" },\n\t\t};\n\t}\n}\n\nexport type EntryRef = {\n\tid: string;\n\tslug: string | null;\n\tcollection: string;\n\t/** The actual locale of the resolved variant — see `pickVariant`. */\n\tlocale: string | null;\n\tsortOrder?: number;\n};\n\n/** Resolve a relation from an id OR its translation_group. */\nasync function resolveRelation(\n\trepo: RelationRepository,\n\tidOrGroup: string,\n): Promise<Relation | null> {\n\tconst byId = await repo.findById(idOrGroup);\n\tif (byId) return byId;\n\tconst group = await repo.findTranslations(idOrGroup);\n\treturn group[0] ?? null;\n}\n\n/**\n * Pick the locale variant matching `locale`, falling back to the first entry\n * (lowest locale code). The fallback is intentional — an edge is keyed by\n * `translation_group`, so a referenced entry that exists only in another locale\n * is still a real reference — but the returned ref carries the variant's actual\n * `locale` so callers never mistake a fallback for the requested locale.\n */\nfunction pickVariant(items: ContentItem[], locale: string | null): ContentItem | undefined {\n\treturn items.find((i) => i.locale === locale) ?? items[0];\n}\n\n/**\n * Resolve edge groups to loadable entries in `collection` at `locale`.\n * Dangling groups (no surviving entry) are skipped — cleanup is a later slice.\n *\n * All groups are loaded in one batched query (chunked at `SQL_BATCH_SIZE`)\n * rather than a `findTranslations` per edge, so a parent with N children costs\n * a constant number of queries, not N+1. Edge order (the caller's `sort_order`)\n * is preserved by iterating `edges`.\n *\n * `includeDrafts` is false for callers without `content:read_drafts`: the load\n * is restricted to published entries so a draft/scheduled entry referenced by an\n * edge is skipped exactly like a dangling one, never leaking its id/slug/locale.\n */\nasync function resolveEntries(\n\tcontent: ContentRepository,\n\tcollection: string,\n\tedges: ContentReference[],\n\tpick: (e: ContentReference) => string,\n\tlocale: string | null,\n\tincludeDrafts: boolean,\n): Promise<EntryRef[]> {\n\tconst groups = edges.map(pick);\n\tconst all = await content.findTranslationsForGroups(collection, groups, {\n\t\tpublishedOnly: !includeDrafts,\n\t});\n\n\t// Group the flat variant list by translation_group so each edge can pick its\n\t// own locale variant.\n\tconst variantsByGroup = new Map<string, ContentItem[]>();\n\tfor (const item of all) {\n\t\tif (item.translationGroup == null) continue;\n\t\tconst list = variantsByGroup.get(item.translationGroup);\n\t\tif (list) list.push(item);\n\t\telse variantsByGroup.set(item.translationGroup, [item]);\n\t}\n\n\tconst refs: EntryRef[] = [];\n\tfor (const edge of edges) {\n\t\tconst variants = variantsByGroup.get(pick(edge));\n\t\tif (!variants) continue;\n\t\tconst entry = pickVariant(variants, locale);\n\t\tif (!entry) continue;\n\t\trefs.push({\n\t\t\tid: entry.id,\n\t\t\tslug: entry.slug,\n\t\t\tcollection,\n\t\t\tlocale: entry.locale,\n\t\t\tsortOrder: edge.sortOrder,\n\t\t});\n\t}\n\treturn refs;\n}\n\n/** Pagination inputs for the edge read endpoints. */\nexport type PageOptions = { limit?: number; cursor?: string };\n\nexport async function handleReferenceChildrenGet(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tentryId: string,\n\trelation: string,\n\tpage: PageOptions = {},\n\tincludeDrafts = false,\n): Promise<ApiResult<{ children: EntryRef[]; nextCursor?: string }>> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\t\tconst content = new ContentRepository(db);\n\n\t\tconst rel = await resolveRelation(repo, relation);\n\t\tif (!rel)\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Relation not found\" } };\n\t\tif (collection !== rel.parentCollection) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\tmessage: \"Entry is not the parent side of this relation\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst entry = await content.findByIdOrSlug(collection, entryId);\n\t\t// A caller without draft access must not anchor on a non-published entry —\n\t\t// return NOT_FOUND (not 403) so they can't probe draft ids by status code,\n\t\t// mirroring the single-item content read.\n\t\tif (!entry?.translationGroup || (!includeDrafts && entry.status !== \"published\")) {\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Content entry not found\" } };\n\t\t}\n\n\t\tconst edges = await repo.getChildrenPage(rel.translationGroup, entry.translationGroup, page);\n\t\tconst children = await resolveEntries(\n\t\t\tcontent,\n\t\t\trel.childCollection,\n\t\t\tedges.items,\n\t\t\t(e) => e.childGroup,\n\t\t\tentry.locale,\n\t\t\tincludeDrafts,\n\t\t);\n\t\treturn { success: true, data: { children, nextCursor: edges.nextCursor } };\n\t} catch (error) {\n\t\treturn referencesGetError(error);\n\t}\n}\n\nexport async function handleReferenceChildrenSet(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tentryId: string,\n\trelation: string,\n\tchildIds: string[],\n): Promise<ApiResult<{ children: EntryRef[]; nextCursor?: string }>> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\t\tconst content = new ContentRepository(db);\n\n\t\tconst rel = await resolveRelation(repo, relation);\n\t\tif (!rel)\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Relation not found\" } };\n\t\tif (collection !== rel.parentCollection) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\tmessage: \"Entry is not the parent side of this relation\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst entry = await content.findByIdOrSlug(collection, entryId);\n\t\tif (!entry?.translationGroup) {\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Content entry not found\" } };\n\t\t}\n\n\t\t// Resolve every child within the relation's child_collection in one batch\n\t\t// (constant queries, not an N+1 of point lookups for a set up to 1000). A\n\t\t// child id that does not resolve there fails collection-agreement\n\t\t// (invariant 3); order is preserved by iterating the caller's `childIds`.\n\t\tconst resolvedChildren = await content.findManyByIdOrSlug(rel.childCollection, childIds);\n\t\tconst childGroups: string[] = [];\n\t\tfor (const childId of childIds) {\n\t\t\tconst child = resolvedChildren.get(childId);\n\t\t\tif (!child?.translationGroup) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\t\tmessage: `Child entry '${childId}' not found in ${rel.childCollection}`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\tchildGroups.push(child.translationGroup);\n\t\t}\n\n\t\tawait repo.setChildren(rel.translationGroup, entry.translationGroup, childGroups);\n\n\t\t// Return the first page of the new set, mirroring the GET shape. The actor\n\t\t// holds an edit permission (gated by the route), so draft children are\n\t\t// included in the echo.\n\t\tconst edges = await repo.getChildrenPage(rel.translationGroup, entry.translationGroup);\n\t\tconst children = await resolveEntries(\n\t\t\tcontent,\n\t\t\trel.childCollection,\n\t\t\tedges.items,\n\t\t\t(e) => e.childGroup,\n\t\t\tentry.locale,\n\t\t\ttrue,\n\t\t);\n\t\treturn { success: true, data: { children, nextCursor: edges.nextCursor } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"REFERENCES_SET_ERROR\", message: \"Failed to set references\" },\n\t\t};\n\t}\n}\n\nexport async function handleReferenceParentsGet(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tentryId: string,\n\trelation: string,\n\tpage: PageOptions = {},\n\tincludeDrafts = false,\n): Promise<ApiResult<{ parents: EntryRef[]; nextCursor?: string }>> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\t\tconst content = new ContentRepository(db);\n\n\t\tconst rel = await resolveRelation(repo, relation);\n\t\tif (!rel)\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Relation not found\" } };\n\t\tif (collection !== rel.childCollection) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\tmessage: \"Entry is not the child side of this relation\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst entry = await content.findByIdOrSlug(collection, entryId);\n\t\t// Same draft-anchor guard as the children read: a non-draft-reader anchoring\n\t\t// on an unpublished entry gets NOT_FOUND, not its backlinks.\n\t\tif (!entry?.translationGroup || (!includeDrafts && entry.status !== \"published\")) {\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Content entry not found\" } };\n\t\t}\n\n\t\tconst edges = await repo.getParentsPage(rel.translationGroup, entry.translationGroup, page);\n\t\tconst parents = await resolveEntries(\n\t\t\tcontent,\n\t\t\trel.parentCollection,\n\t\t\tedges.items,\n\t\t\t(e) => e.parentGroup,\n\t\t\tentry.locale,\n\t\t\tincludeDrafts,\n\t\t);\n\t\treturn { success: true, data: { parents, nextCursor: edges.nextCursor } };\n\t} catch (error) {\n\t\treturn referencesGetError(error);\n\t}\n}\n"],"mappings":";;;;;;;;;AAkBA,SAAS,mBAAmB,OAAkC;AAC7D,KAAI,iBAAiB,mBACpB,QAAO;EAAE,SAAS;EAAO,OAAO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C,MAAM,UAAU,IAAI,kBAAkB,GAAG;EAEzC,MAAM,MAAM,MAAM,gBAAgB,MAAM,SAAS;AACjD,MAAI,CAAC,IACJ,QAAO;GAAE,SAAS;GAAO,OAAO;IAAE,MAAM;IAAa,SAAS;IAAsB;GAAE;AACvF,MAAI,eAAe,IAAI,gBACtB,QAAO;GACN,SAAS;GACT,OAAO;IACN,MAAM;IACN,SAAS;IACT;GACD;EAGF,MAAM,QAAQ,MAAM,QAAQ,eAAe,YAAY,QAAQ;AAG/D,MAAI,CAAC,OAAO,oBAAqB,CAAC,iBAAiB,MAAM,WAAW,YACnE,QAAO;GAAE,SAAS;GAAO,OAAO;IAAE,MAAM;IAAa,SAAS;IAA2B;GAAE;EAG5F,MAAM,QAAQ,MAAM,KAAK,eAAe,IAAI,kBAAkB,MAAM,kBAAkB,KAAK;AAS3F,SAAO;GAAE,SAAS;GAAM,MAAM;IAAE,SARhB,MAAM,eACrB,SACA,IAAI,kBACJ,MAAM,QACL,MAAM,EAAE,aACT,MAAM,QACN,cACA;IACwC,YAAY,MAAM;IAAY;GAAE;UACjE,OAAO;AACf,SAAO,mBAAmB,MAAM"}
1
+ {"version":3,"file":"relations-KKDSLUwS.mjs","names":[],"sources":["../src/api/handlers/relations.ts"],"sourcesContent":["import type { Kysely } from \"kysely\";\n\nimport { ContentRepository } from \"../../database/repositories/content.js\";\nimport {\n\tRelationRepository,\n\ttype ContentReference,\n\ttype CreateRelationInput,\n\ttype Relation,\n} from \"../../database/repositories/relation.js\";\nimport { InvalidCursorError } from \"../../database/repositories/types.js\";\nimport type { ContentItem } from \"../../database/repositories/types.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { resolveConfiguredLocale } from \"../../i18n/config.js\";\nimport { SchemaRegistry } from \"../../schema/registry.js\";\nimport type { ApiResult } from \"../types.js\";\n\n/** Map an edge-read failure: a bad pagination cursor is a 400 client error,\n * everything else is the generic 500-shaped reference-read error. */\nfunction referencesGetError(error: unknown): ApiResult<never> {\n\tif (error instanceof InvalidCursorError) {\n\t\treturn { success: false, error: { code: \"INVALID_CURSOR\", message: error.message } };\n\t}\n\treturn {\n\t\tsuccess: false,\n\t\terror: { code: \"REFERENCES_GET_ERROR\", message: \"Failed to get references\" },\n\t};\n}\n\n/** True for SQLite UNIQUE / Postgres unique_violation messages (matches the\n * fingerprint used in the content handlers). Narrow enough not to catch NOT\n * NULL / CHECK violations whose messages also say \"constraint\". */\nfunction isUniqueViolation(error: unknown): boolean {\n\tconst message = error instanceof Error ? error.message.toLowerCase() : \"\";\n\treturn message.includes(\"unique constraint failed\") || message.includes(\"duplicate key\");\n}\n\nexport async function handleRelationCreate(\n\tdb: Kysely<Database>,\n\tinput: CreateRelationInput,\n): Promise<ApiResult<{ relation: Relation }>> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\n\t\t// Invariant: a relation must point at collections that exist. There is no\n\t\t// SQL FK (group-linking precludes it), so a ghost collection would yield a\n\t\t// structurally-valid-but-permanently-useless relation. Skip when\n\t\t// `translationOf` is set — structural fields are then inherited from an\n\t\t// already-validated source, and the input collections are ignored.\n\t\tif (!input.translationOf) {\n\t\t\tif (!input.parentCollection || !input.childCollection) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"parentCollection and childCollection are required unless translationOf is set\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst registry = new SchemaRegistry(db);\n\t\t\tfor (const collection of [input.parentCollection, input.childCollection]) {\n\t\t\t\tif (!(await registry.getCollection(collection))) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\tcode: \"COLLECTION_NOT_FOUND\",\n\t\t\t\t\t\t\tmessage: `Collection '${collection}' not found`,\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst relation = await repo.create({\n\t\t\t...input,\n\t\t\tlocale: input.locale ? resolveConfiguredLocale(input.locale) : undefined,\n\t\t});\n\t\treturn { success: true, data: { relation } };\n\t} catch (error) {\n\t\t// A bad `translationOf` makes the repo throw loudly rather than mint an\n\t\t// unlinked relation — surface it as 404, not a generic 500.\n\t\tif (\n\t\t\terror instanceof Error &&\n\t\t\terror.message.includes(\"Source relation for translation not found\")\n\t\t) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Source relation for translation not found\" },\n\t\t\t};\n\t\t}\n\t\t// UNIQUE(name, locale) collision, or a second translation for an\n\t\t// already-present (translation_group, locale) — both are client conflicts.\n\t\tif (isUniqueViolation(error)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\tmessage: \"A relation with this name or locale already exists\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"RELATION_CREATE_ERROR\", message: \"Failed to create relation\" },\n\t\t};\n\t}\n}\n\nexport async function handleRelationGet(\n\tdb: Kysely<Database>,\n\tid: string,\n): Promise<ApiResult<{ relation: Relation }>> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\t\tconst relation = await repo.findById(id);\n\t\tif (!relation) {\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Relation not found\" } };\n\t\t}\n\t\treturn { success: true, data: { relation } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"RELATION_GET_ERROR\", message: \"Failed to get relation\" },\n\t\t};\n\t}\n}\n\nexport async function handleRelationList(\n\tdb: Kysely<Database>,\n\topts: { locale?: string },\n): Promise<ApiResult<{ relations: Relation[] }>> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\t\tconst locale = opts.locale ? resolveConfiguredLocale(opts.locale) : undefined;\n\t\tconst relations = await repo.list(locale);\n\t\treturn { success: true, data: { relations } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"RELATION_LIST_ERROR\", message: \"Failed to list relations\" },\n\t\t};\n\t}\n}\n\nexport async function handleRelationUpdate(\n\tdb: Kysely<Database>,\n\tid: string,\n\tinput: { parentLabel?: string; childLabel?: string },\n): Promise<ApiResult<{ relation: Relation }>> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\t\tconst relation = await repo.update(id, input);\n\t\tif (!relation) {\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Relation not found\" } };\n\t\t}\n\t\treturn { success: true, data: { relation } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"RELATION_UPDATE_ERROR\", message: \"Failed to update relation\" },\n\t\t};\n\t}\n}\n\nexport async function handleRelationDelete(\n\tdb: Kysely<Database>,\n\tid: string,\n): Promise<ApiResult<{ deleted: true }>> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\t\tconst deleted = await repo.delete(id);\n\t\tif (!deleted) {\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Relation not found\" } };\n\t\t}\n\t\treturn { success: true, data: { deleted: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"RELATION_DELETE_ERROR\", message: \"Failed to delete relation\" },\n\t\t};\n\t}\n}\n\nexport async function handleRelationTranslations(\n\tdb: Kysely<Database>,\n\tid: string,\n): Promise<\n\tApiResult<{\n\t\ttranslationGroup: string;\n\t\ttranslations: {\n\t\t\tid: string;\n\t\t\tname: string;\n\t\t\tlocale: string;\n\t\t\tparentLabel: string;\n\t\t\tchildLabel: string;\n\t\t}[];\n\t}>\n> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\t\tconst relation = await repo.findById(id);\n\t\tif (!relation) {\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Relation not found\" } };\n\t\t}\n\t\tconst siblings = await repo.findTranslations(relation.translationGroup);\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\ttranslationGroup: relation.translationGroup,\n\t\t\t\ttranslations: siblings.map((r) => ({\n\t\t\t\t\tid: r.id,\n\t\t\t\t\tname: r.name,\n\t\t\t\t\tlocale: r.locale,\n\t\t\t\t\tparentLabel: r.parentLabel,\n\t\t\t\t\tchildLabel: r.childLabel,\n\t\t\t\t})),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"RELATION_TRANSLATIONS_ERROR\", message: \"Failed to get translations\" },\n\t\t};\n\t}\n}\n\nexport type EntryRef = {\n\tid: string;\n\tslug: string | null;\n\tcollection: string;\n\t/** The actual locale of the resolved variant — see `pickVariant`. */\n\tlocale: string | null;\n\tsortOrder?: number;\n};\n\n/** Resolve a relation from an id OR its translation_group. */\nasync function resolveRelation(\n\trepo: RelationRepository,\n\tidOrGroup: string,\n): Promise<Relation | null> {\n\tconst byId = await repo.findById(idOrGroup);\n\tif (byId) return byId;\n\tconst group = await repo.findTranslations(idOrGroup);\n\treturn group[0] ?? null;\n}\n\n/**\n * Pick the locale variant matching `locale`, falling back to the first entry\n * (lowest locale code). The fallback is intentional — an edge is keyed by\n * `translation_group`, so a referenced entry that exists only in another locale\n * is still a real reference — but the returned ref carries the variant's actual\n * `locale` so callers never mistake a fallback for the requested locale.\n */\nfunction pickVariant(items: ContentItem[], locale: string | null): ContentItem | undefined {\n\treturn items.find((i) => i.locale === locale) ?? items[0];\n}\n\n/**\n * Resolve edge groups to loadable entries in `collection` at `locale`.\n * Dangling groups (no surviving entry) are skipped — cleanup is a later slice.\n *\n * All groups are loaded in one batched query (chunked at `SQL_BATCH_SIZE`)\n * rather than a `findTranslations` per edge, so a parent with N children costs\n * a constant number of queries, not N+1. Edge order (the caller's `sort_order`)\n * is preserved by iterating `edges`.\n *\n * `includeDrafts` is false for callers without `content:read_drafts`: the load\n * is restricted to published entries so a draft/scheduled entry referenced by an\n * edge is skipped exactly like a dangling one, never leaking its id/slug/locale.\n */\nasync function resolveEntries(\n\tcontent: ContentRepository,\n\tcollection: string,\n\tedges: ContentReference[],\n\tpick: (e: ContentReference) => string,\n\tlocale: string | null,\n\tincludeDrafts: boolean,\n): Promise<EntryRef[]> {\n\tconst groups = edges.map(pick);\n\tconst all = await content.findTranslationsForGroups(collection, groups, {\n\t\tpublishedOnly: !includeDrafts,\n\t});\n\n\t// Group the flat variant list by translation_group so each edge can pick its\n\t// own locale variant.\n\tconst variantsByGroup = new Map<string, ContentItem[]>();\n\tfor (const item of all) {\n\t\tif (item.translationGroup == null) continue;\n\t\tconst list = variantsByGroup.get(item.translationGroup);\n\t\tif (list) list.push(item);\n\t\telse variantsByGroup.set(item.translationGroup, [item]);\n\t}\n\n\tconst refs: EntryRef[] = [];\n\tfor (const edge of edges) {\n\t\tconst variants = variantsByGroup.get(pick(edge));\n\t\tif (!variants) continue;\n\t\tconst entry = pickVariant(variants, locale);\n\t\tif (!entry) continue;\n\t\trefs.push({\n\t\t\tid: entry.id,\n\t\t\tslug: entry.slug,\n\t\t\tcollection,\n\t\t\tlocale: entry.locale,\n\t\t\tsortOrder: edge.sortOrder,\n\t\t});\n\t}\n\treturn refs;\n}\n\n/** Pagination inputs for the edge read endpoints. */\nexport type PageOptions = { limit?: number; cursor?: string };\n\nexport async function handleReferenceChildrenGet(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tentryId: string,\n\trelation: string,\n\tpage: PageOptions = {},\n\tincludeDrafts = false,\n): Promise<ApiResult<{ children: EntryRef[]; nextCursor?: string }>> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\t\tconst content = new ContentRepository(db);\n\n\t\tconst rel = await resolveRelation(repo, relation);\n\t\tif (!rel)\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Relation not found\" } };\n\t\tif (collection !== rel.parentCollection) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\tmessage: \"Entry is not the parent side of this relation\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst entry = await content.findByIdOrSlug(collection, entryId);\n\t\t// A caller without draft access must not anchor on a non-published entry —\n\t\t// return NOT_FOUND (not 403) so they can't probe draft ids by status code,\n\t\t// mirroring the single-item content read.\n\t\tif (!entry?.translationGroup || (!includeDrafts && entry.status !== \"published\")) {\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Content entry not found\" } };\n\t\t}\n\n\t\tconst edges = await repo.getChildrenPage(rel.translationGroup, entry.translationGroup, page);\n\t\tconst children = await resolveEntries(\n\t\t\tcontent,\n\t\t\trel.childCollection,\n\t\t\tedges.items,\n\t\t\t(e) => e.childGroup,\n\t\t\tentry.locale,\n\t\t\tincludeDrafts,\n\t\t);\n\t\treturn { success: true, data: { children, nextCursor: edges.nextCursor } };\n\t} catch (error) {\n\t\treturn referencesGetError(error);\n\t}\n}\n\nexport async function handleReferenceChildrenSet(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tentryId: string,\n\trelation: string,\n\tchildIds: string[],\n): Promise<ApiResult<{ children: EntryRef[]; nextCursor?: string }>> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\t\tconst content = new ContentRepository(db);\n\n\t\tconst rel = await resolveRelation(repo, relation);\n\t\tif (!rel)\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Relation not found\" } };\n\t\tif (collection !== rel.parentCollection) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\tmessage: \"Entry is not the parent side of this relation\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst entry = await content.findByIdOrSlug(collection, entryId);\n\t\tif (!entry?.translationGroup) {\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Content entry not found\" } };\n\t\t}\n\n\t\t// Resolve every child within the relation's child_collection in one batch\n\t\t// (constant queries, not an N+1 of point lookups for a set up to 1000). A\n\t\t// child id that does not resolve there fails collection-agreement\n\t\t// (invariant 3); order is preserved by iterating the caller's `childIds`.\n\t\tconst resolvedChildren = await content.findManyByIdOrSlug(rel.childCollection, childIds);\n\t\tconst childGroups: string[] = [];\n\t\tfor (const childId of childIds) {\n\t\t\tconst child = resolvedChildren.get(childId);\n\t\t\tif (!child?.translationGroup) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\t\tmessage: `Child entry '${childId}' not found in ${rel.childCollection}`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\tchildGroups.push(child.translationGroup);\n\t\t}\n\n\t\tawait repo.setChildren(rel.translationGroup, entry.translationGroup, childGroups);\n\n\t\t// Return the first page of the new set, mirroring the GET shape. The actor\n\t\t// holds an edit permission (gated by the route), so draft children are\n\t\t// included in the echo.\n\t\tconst edges = await repo.getChildrenPage(rel.translationGroup, entry.translationGroup);\n\t\tconst children = await resolveEntries(\n\t\t\tcontent,\n\t\t\trel.childCollection,\n\t\t\tedges.items,\n\t\t\t(e) => e.childGroup,\n\t\t\tentry.locale,\n\t\t\ttrue,\n\t\t);\n\t\treturn { success: true, data: { children, nextCursor: edges.nextCursor } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"REFERENCES_SET_ERROR\", message: \"Failed to set references\" },\n\t\t};\n\t}\n}\n\nexport async function handleReferenceParentsGet(\n\tdb: Kysely<Database>,\n\tcollection: string,\n\tentryId: string,\n\trelation: string,\n\tpage: PageOptions = {},\n\tincludeDrafts = false,\n): Promise<ApiResult<{ parents: EntryRef[]; nextCursor?: string }>> {\n\ttry {\n\t\tconst repo = new RelationRepository(db);\n\t\tconst content = new ContentRepository(db);\n\n\t\tconst rel = await resolveRelation(repo, relation);\n\t\tif (!rel)\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Relation not found\" } };\n\t\tif (collection !== rel.childCollection) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\tmessage: \"Entry is not the child side of this relation\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst entry = await content.findByIdOrSlug(collection, entryId);\n\t\t// Same draft-anchor guard as the children read: a non-draft-reader anchoring\n\t\t// on an unpublished entry gets NOT_FOUND, not its backlinks.\n\t\tif (!entry?.translationGroup || (!includeDrafts && entry.status !== \"published\")) {\n\t\t\treturn { success: false, error: { code: \"NOT_FOUND\", message: \"Content entry not found\" } };\n\t\t}\n\n\t\tconst edges = await repo.getParentsPage(rel.translationGroup, entry.translationGroup, page);\n\t\tconst parents = await resolveEntries(\n\t\t\tcontent,\n\t\t\trel.parentCollection,\n\t\t\tedges.items,\n\t\t\t(e) => e.parentGroup,\n\t\t\tentry.locale,\n\t\t\tincludeDrafts,\n\t\t);\n\t\treturn { success: true, data: { parents, nextCursor: edges.nextCursor } };\n\t} catch (error) {\n\t\treturn referencesGetError(error);\n\t}\n}\n"],"mappings":";;;;;;;;;AAkBA,SAAS,mBAAmB,OAAkC;AAC7D,KAAI,iBAAiB,mBACpB,QAAO;EAAE,SAAS;EAAO,OAAO;GAAE,MAAM;GAAkB,SAAS,MAAM;GAAS;EAAE;AAErF,QAAO;EACN,SAAS;EACT,OAAO;GAAE,MAAM;GAAwB,SAAS;GAA4B;EAC5E;;;;;AAMF,SAAS,kBAAkB,OAAyB;CACnD,MAAM,UAAU,iBAAiB,QAAQ,MAAM,QAAQ,aAAa,GAAG;AACvE,QAAO,QAAQ,SAAS,2BAA2B,IAAI,QAAQ,SAAS,gBAAgB;;AAGzF,eAAsB,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