emdash 0.37.0 → 0.39.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 (1445) hide show
  1. package/dist/action-token-On1sot_c.mjs +26 -0
  2. package/dist/action-token-On1sot_c.mjs.map +1 -0
  3. package/dist/activation-CaMfdBt1.mjs +382 -0
  4. package/dist/activation-CaMfdBt1.mjs.map +1 -0
  5. package/dist/adapters-Cq10K4_c.d.mts +171 -0
  6. package/dist/adapters-Cq10K4_c.d.mts.map +1 -0
  7. package/dist/after-PcEvMY_6.mjs +96 -0
  8. package/dist/after-PcEvMY_6.mjs.map +1 -0
  9. package/dist/allowed-origins-1Sa-2wZK.mjs +116 -0
  10. package/dist/allowed-origins-1Sa-2wZK.mjs.map +1 -0
  11. package/dist/api/route-utils.d.mts +4 -3
  12. package/dist/api/route-utils.d.mts.map +1 -1
  13. package/dist/api/route-utils.mjs +45 -29
  14. package/dist/api/route-utils.mjs.map +1 -1
  15. package/dist/api/schemas/index.d.mts +2 -2
  16. package/dist/api/schemas/index.mjs +7 -6
  17. package/dist/api-DmjKxPCY.mjs +4831 -0
  18. package/dist/api-DmjKxPCY.mjs.map +1 -0
  19. package/dist/api-tokens-BIXItFKV.mjs +163 -0
  20. package/dist/api-tokens-BIXItFKV.mjs.map +1 -0
  21. package/dist/apply-drpfmqrR.mjs +1005 -0
  22. package/dist/apply-drpfmqrR.mjs.map +1 -0
  23. package/dist/artifact-fetch-COiMhVgk.mjs +813 -0
  24. package/dist/artifact-fetch-COiMhVgk.mjs.map +1 -0
  25. package/dist/astro/index.d.mts +14 -12
  26. package/dist/astro/index.d.mts.map +1 -1
  27. package/dist/astro/index.mjs +123 -13
  28. package/dist/astro/index.mjs.map +1 -1
  29. package/dist/astro/middleware/auth.d.mts +12 -10
  30. package/dist/astro/middleware/auth.d.mts.map +1 -1
  31. package/dist/astro/middleware/auth.mjs +20 -11
  32. package/dist/astro/middleware/auth.mjs.map +1 -1
  33. package/dist/astro/middleware/media-usage-write-fence.mjs +5 -5
  34. package/dist/astro/middleware/redirect.mjs +11 -9
  35. package/dist/astro/middleware/redirect.mjs.map +1 -1
  36. package/dist/astro/middleware/request-context.d.mts +1 -1
  37. package/dist/astro/middleware/request-context.d.mts.map +1 -1
  38. package/dist/astro/middleware/request-context.mjs +154 -28
  39. package/dist/astro/middleware/request-context.mjs.map +1 -1
  40. package/dist/astro/middleware/setup.mjs +1 -1
  41. package/dist/astro/middleware.d.mts +13 -10
  42. package/dist/astro/middleware.d.mts.map +1 -1
  43. package/dist/astro/middleware.mjs +122 -3041
  44. package/dist/astro/middleware.mjs.map +1 -1
  45. package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs +10 -9
  46. package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs.map +1 -1
  47. package/dist/astro/routes/api/admin/allowed-domains/index.mjs +10 -9
  48. package/dist/astro/routes/api/admin/allowed-domains/index.mjs.map +1 -1
  49. package/dist/astro/routes/api/admin/api-tokens/_id_.mjs +5 -5
  50. package/dist/astro/routes/api/admin/api-tokens/index.mjs +6 -6
  51. package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +6 -6
  52. package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +13 -12
  53. package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs.map +1 -1
  54. package/dist/astro/routes/api/admin/byline-fields/index.mjs +13 -12
  55. package/dist/astro/routes/api/admin/byline-fields/index.mjs.map +1 -1
  56. package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +13 -12
  57. package/dist/astro/routes/api/admin/byline-fields/reorder.mjs.map +1 -1
  58. package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +22 -21
  59. package/dist/astro/routes/api/admin/bylines/_id_/index.mjs.map +1 -1
  60. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +22 -21
  61. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs.map +1 -1
  62. package/dist/astro/routes/api/admin/bylines/index.mjs +22 -21
  63. package/dist/astro/routes/api/admin/bylines/index.mjs.map +1 -1
  64. package/dist/astro/routes/api/admin/comments/_id_/status.d.mts.map +1 -1
  65. package/dist/astro/routes/api/admin/comments/_id_/status.mjs +21 -54
  66. package/dist/astro/routes/api/admin/comments/_id_/status.mjs.map +1 -1
  67. package/dist/astro/routes/api/admin/comments/_id_.mjs +8 -8
  68. package/dist/astro/routes/api/admin/comments/bulk.mjs +15 -14
  69. package/dist/astro/routes/api/admin/comments/bulk.mjs.map +1 -1
  70. package/dist/astro/routes/api/admin/comments/counts.mjs +8 -8
  71. package/dist/astro/routes/api/admin/comments/index.mjs +15 -14
  72. package/dist/astro/routes/api/admin/comments/index.mjs.map +1 -1
  73. package/dist/astro/routes/api/admin/hooks/exclusive/_hookName_.mjs +6 -6
  74. package/dist/astro/routes/api/admin/hooks/exclusive/index.mjs +5 -5
  75. package/dist/astro/routes/api/admin/media-usage/activation.mjs +17 -16
  76. package/dist/astro/routes/api/admin/media-usage/activation.mjs.map +1 -1
  77. package/dist/astro/routes/api/admin/media-usage/collection-deletions/index.mjs +19 -18
  78. package/dist/astro/routes/api/admin/media-usage/collection-deletions/index.mjs.map +1 -1
  79. package/dist/astro/routes/api/admin/media-usage/collection-deletions/retry.mjs +19 -18
  80. package/dist/astro/routes/api/admin/media-usage/collection-deletions/retry.mjs.map +1 -1
  81. package/dist/astro/routes/api/admin/media-usage/progress.mjs +17 -17
  82. package/dist/astro/routes/api/admin/media-usage/repair.mjs +21 -20
  83. package/dist/astro/routes/api/admin/media-usage/repair.mjs.map +1 -1
  84. package/dist/astro/routes/api/admin/media-usage/work/index.mjs +19 -18
  85. package/dist/astro/routes/api/admin/media-usage/work/index.mjs.map +1 -1
  86. package/dist/astro/routes/api/admin/media-usage/work/retry.mjs +19 -18
  87. package/dist/astro/routes/api/admin/media-usage/work/retry.mjs.map +1 -1
  88. package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs +5 -5
  89. package/dist/astro/routes/api/admin/oauth-clients/index.mjs +5 -5
  90. package/dist/astro/routes/api/admin/plugins/_id_/disable.d.mts.map +1 -1
  91. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +9 -66
  92. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs.map +1 -1
  93. package/dist/astro/routes/api/admin/plugins/_id_/enable.d.mts.map +1 -1
  94. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +9 -69
  95. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs.map +1 -1
  96. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +66 -59
  97. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs.map +1 -1
  98. package/dist/astro/routes/api/admin/plugins/_id_/mcp.mjs +6 -6
  99. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs +65 -59
  100. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs.map +1 -1
  101. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +70 -61
  102. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs.map +1 -1
  103. package/dist/astro/routes/api/admin/plugins/_id_/update.d.mts.map +1 -1
  104. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +87 -63
  105. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs.map +1 -1
  106. package/dist/astro/routes/api/admin/plugins/index.mjs +66 -59
  107. package/dist/astro/routes/api/admin/plugins/index.mjs.map +1 -1
  108. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +4 -4
  109. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +65 -59
  110. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs.map +1 -1
  111. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.d.mts.map +1 -1
  112. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +85 -63
  113. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs.map +1 -1
  114. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +65 -59
  115. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs.map +1 -1
  116. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +70 -61
  117. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs.map +1 -1
  118. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.d.mts.map +1 -1
  119. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +90 -66
  120. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs.map +1 -1
  121. package/dist/astro/routes/api/admin/plugins/registry/artifact.d.mts.map +1 -1
  122. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +9 -7
  123. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs.map +1 -1
  124. package/dist/astro/routes/api/admin/plugins/registry/install.d.mts.map +1 -1
  125. package/dist/astro/routes/api/admin/plugins/registry/install.mjs +77 -63
  126. package/dist/astro/routes/api/admin/plugins/registry/install.mjs.map +1 -1
  127. package/dist/astro/routes/api/admin/plugins/registry/verify.d.mts.map +1 -1
  128. package/dist/astro/routes/api/admin/plugins/registry/verify.mjs +67 -61
  129. package/dist/astro/routes/api/admin/plugins/registry/verify.mjs.map +1 -1
  130. package/dist/astro/routes/api/admin/plugins/updates.d.mts.map +1 -1
  131. package/dist/astro/routes/api/admin/plugins/updates.mjs +66 -60
  132. package/dist/astro/routes/api/admin/plugins/updates.mjs.map +1 -1
  133. package/dist/astro/routes/api/admin/scheduled-policy-rejections/_collection_/_id_.d.mts +8 -0
  134. package/dist/astro/routes/api/admin/scheduled-policy-rejections/_collection_/_id_.d.mts.map +1 -0
  135. package/dist/astro/routes/api/admin/scheduled-policy-rejections/_collection_/_id_.mjs +27 -0
  136. package/dist/astro/routes/api/admin/scheduled-policy-rejections/_collection_/_id_.mjs.map +1 -0
  137. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +65 -59
  138. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs.map +1 -1
  139. package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +4 -4
  140. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +65 -59
  141. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs.map +1 -1
  142. package/dist/astro/routes/api/admin/users/_id_/disable.mjs +4 -4
  143. package/dist/astro/routes/api/admin/users/_id_/enable.mjs +3 -3
  144. package/dist/astro/routes/api/admin/users/_id_/index.mjs +11 -10
  145. package/dist/astro/routes/api/admin/users/_id_/index.mjs.map +1 -1
  146. package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +5 -5
  147. package/dist/astro/routes/api/admin/users/index.mjs +10 -9
  148. package/dist/astro/routes/api/admin/users/index.mjs.map +1 -1
  149. package/dist/astro/routes/api/auth/dev-bypass.mjs +5 -5
  150. package/dist/astro/routes/api/auth/invite/accept.mjs +3 -3
  151. package/dist/astro/routes/api/auth/invite/complete.mjs +15 -14
  152. package/dist/astro/routes/api/auth/invite/complete.mjs.map +1 -1
  153. package/dist/astro/routes/api/auth/invite/index.mjs +12 -11
  154. package/dist/astro/routes/api/auth/invite/index.mjs.map +1 -1
  155. package/dist/astro/routes/api/auth/invite/register-options.mjs +14 -13
  156. package/dist/astro/routes/api/auth/invite/register-options.mjs.map +1 -1
  157. package/dist/astro/routes/api/auth/logout.mjs +4 -4
  158. package/dist/astro/routes/api/auth/magic-link/send.mjs +14 -13
  159. package/dist/astro/routes/api/auth/magic-link/send.mjs.map +1 -1
  160. package/dist/astro/routes/api/auth/magic-link/verify.mjs +4 -4
  161. package/dist/astro/routes/api/auth/me.mjs +11 -10
  162. package/dist/astro/routes/api/auth/me.mjs.map +1 -1
  163. package/dist/astro/routes/api/auth/mode.mjs +4 -4
  164. package/dist/astro/routes/api/auth/oauth/_provider_/callback.mjs +4 -4
  165. package/dist/astro/routes/api/auth/oauth/_provider_.mjs +2 -2
  166. package/dist/astro/routes/api/auth/passkey/_id_.mjs +10 -9
  167. package/dist/astro/routes/api/auth/passkey/_id_.mjs.map +1 -1
  168. package/dist/astro/routes/api/auth/passkey/index.mjs +3 -3
  169. package/dist/astro/routes/api/auth/passkey/options.mjs +16 -15
  170. package/dist/astro/routes/api/auth/passkey/options.mjs.map +1 -1
  171. package/dist/astro/routes/api/auth/passkey/register/options.mjs +14 -13
  172. package/dist/astro/routes/api/auth/passkey/register/options.mjs.map +1 -1
  173. package/dist/astro/routes/api/auth/passkey/register/verify.mjs +15 -14
  174. package/dist/astro/routes/api/auth/passkey/register/verify.mjs.map +1 -1
  175. package/dist/astro/routes/api/auth/passkey/verify.mjs +15 -14
  176. package/dist/astro/routes/api/auth/passkey/verify.mjs.map +1 -1
  177. package/dist/astro/routes/api/auth/signup/complete.mjs +15 -14
  178. package/dist/astro/routes/api/auth/signup/complete.mjs.map +1 -1
  179. package/dist/astro/routes/api/auth/signup/request.mjs +14 -13
  180. package/dist/astro/routes/api/auth/signup/request.mjs.map +1 -1
  181. package/dist/astro/routes/api/auth/signup/verify.mjs +3 -3
  182. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.d.mts.map +1 -1
  183. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +15 -211
  184. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs.map +1 -1
  185. package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +18 -17
  186. package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs.map +1 -1
  187. package/dist/astro/routes/api/content/_collection_/_id_/compare.mjs +4 -4
  188. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.d.mts.map +1 -1
  189. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs +17 -11
  190. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs.map +1 -1
  191. package/dist/astro/routes/api/content/_collection_/_id_/duplicate.mjs +5 -5
  192. package/dist/astro/routes/api/content/_collection_/_id_/lock.d.mts +10 -0
  193. package/dist/astro/routes/api/content/_collection_/_id_/lock.d.mts.map +1 -0
  194. package/dist/astro/routes/api/content/_collection_/_id_/lock.mjs +67 -0
  195. package/dist/astro/routes/api/content/_collection_/_id_/lock.mjs.map +1 -0
  196. package/dist/astro/routes/api/content/_collection_/_id_/permanent.mjs +4 -4
  197. package/dist/astro/routes/api/content/_collection_/_id_/plugin-extensions/_pluginId_/_kind_/_extensionId_.d.mts +8 -0
  198. package/dist/astro/routes/api/content/_collection_/_id_/plugin-extensions/_pluginId_/_kind_/_extensionId_.d.mts.map +1 -0
  199. package/dist/astro/routes/api/content/_collection_/_id_/plugin-extensions/_pluginId_/_kind_/_extensionId_.mjs +35 -0
  200. package/dist/astro/routes/api/content/_collection_/_id_/plugin-extensions/_pluginId_/_kind_/_extensionId_.mjs.map +1 -0
  201. package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs +16 -15
  202. package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs.map +1 -1
  203. package/dist/astro/routes/api/content/_collection_/_id_/publish.d.mts +9 -2
  204. package/dist/astro/routes/api/content/_collection_/_id_/publish.d.mts.map +1 -1
  205. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +28 -16
  206. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs.map +1 -1
  207. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs +27 -23
  208. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs.map +1 -1
  209. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs +27 -23
  210. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs.map +1 -1
  211. package/dist/astro/routes/api/content/_collection_/_id_/restore.mjs +5 -5
  212. package/dist/astro/routes/api/content/_collection_/_id_/revisions.mjs +4 -4
  213. package/dist/astro/routes/api/content/_collection_/_id_/schedule.d.mts.map +1 -1
  214. package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs +27 -12
  215. package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs.map +1 -1
  216. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +23 -20
  217. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs.map +1 -1
  218. package/dist/astro/routes/api/content/_collection_/_id_/translations.mjs +4 -4
  219. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.d.mts.map +1 -1
  220. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs +25 -12
  221. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs.map +1 -1
  222. package/dist/astro/routes/api/content/_collection_/_id_.d.mts.map +1 -1
  223. package/dist/astro/routes/api/content/_collection_/_id_.mjs +27 -14
  224. package/dist/astro/routes/api/content/_collection_/_id_.mjs.map +1 -1
  225. package/dist/astro/routes/api/content/_collection_/authors.mjs +4 -4
  226. package/dist/astro/routes/api/content/_collection_/index.mjs +18 -12
  227. package/dist/astro/routes/api/content/_collection_/index.mjs.map +1 -1
  228. package/dist/astro/routes/api/content/_collection_/trash.mjs +11 -10
  229. package/dist/astro/routes/api/content/_collection_/trash.mjs.map +1 -1
  230. package/dist/astro/routes/api/dashboard.mjs +14 -12
  231. package/dist/astro/routes/api/dashboard.mjs.map +1 -1
  232. package/dist/astro/routes/api/dev/emails.mjs +4 -4
  233. package/dist/astro/routes/api/health.d.mts +8 -0
  234. package/dist/astro/routes/api/health.d.mts.map +1 -0
  235. package/dist/astro/routes/api/health.mjs +21 -0
  236. package/dist/astro/routes/api/health.mjs.map +1 -0
  237. package/dist/astro/routes/api/import/probe.d.mts +3 -3
  238. package/dist/astro/routes/api/import/probe.mjs +25 -23
  239. package/dist/astro/routes/api/import/probe.mjs.map +1 -1
  240. package/dist/astro/routes/api/import/wordpress/analyze.mjs +5 -5
  241. package/dist/astro/routes/api/import/wordpress/execute.d.mts +13 -11
  242. package/dist/astro/routes/api/import/wordpress/execute.d.mts.map +1 -1
  243. package/dist/astro/routes/api/import/wordpress/execute.mjs +20 -19
  244. package/dist/astro/routes/api/import/wordpress/execute.mjs.map +1 -1
  245. package/dist/astro/routes/api/import/wordpress/media.d.mts +12 -10
  246. package/dist/astro/routes/api/import/wordpress/media.d.mts.map +1 -1
  247. package/dist/astro/routes/api/import/wordpress/media.mjs +15 -14
  248. package/dist/astro/routes/api/import/wordpress/media.mjs.map +1 -1
  249. package/dist/astro/routes/api/import/wordpress/prepare.mjs +14 -13
  250. package/dist/astro/routes/api/import/wordpress/prepare.mjs.map +1 -1
  251. package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts +13 -11
  252. package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts.map +1 -1
  253. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +18 -17
  254. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs.map +1 -1
  255. package/dist/astro/routes/api/import/wordpress-plugin/analyze.d.mts +1 -1
  256. package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +25 -23
  257. package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs.map +1 -1
  258. package/dist/astro/routes/api/import/wordpress-plugin/callback.mjs +1 -1
  259. package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +13 -11
  260. package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts.map +1 -1
  261. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +36 -33
  262. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs.map +1 -1
  263. package/dist/astro/routes/api/manifest.mjs +17 -9
  264. package/dist/astro/routes/api/manifest.mjs.map +1 -1
  265. package/dist/astro/routes/api/mcp.d.mts.map +1 -1
  266. package/dist/astro/routes/api/mcp.mjs +192 -110
  267. package/dist/astro/routes/api/mcp.mjs.map +1 -1
  268. package/dist/astro/routes/api/media/_id_/confirm.mjs +15 -14
  269. package/dist/astro/routes/api/media/_id_/confirm.mjs.map +1 -1
  270. package/dist/astro/routes/api/media/_id_/replace.mjs +12 -11
  271. package/dist/astro/routes/api/media/_id_/replace.mjs.map +1 -1
  272. package/dist/astro/routes/api/media/_id_/upload.mjs +8 -8
  273. package/dist/astro/routes/api/media/_id_/usage.mjs +23 -22
  274. package/dist/astro/routes/api/media/_id_/usage.mjs.map +1 -1
  275. package/dist/astro/routes/api/media/_id_.mjs +22 -21
  276. package/dist/astro/routes/api/media/_id_.mjs.map +1 -1
  277. package/dist/astro/routes/api/media/asset/_id_/_filename_.d.mts +8 -0
  278. package/dist/astro/routes/api/media/asset/_id_/_filename_.d.mts.map +1 -0
  279. package/dist/astro/routes/api/media/asset/_id_/_filename_.mjs +52 -0
  280. package/dist/astro/routes/api/media/asset/_id_/_filename_.mjs.map +1 -0
  281. package/dist/astro/routes/api/media/file/_...key_.mjs +3 -3
  282. package/dist/astro/routes/api/media/folders/_id_.mjs +12 -11
  283. package/dist/astro/routes/api/media/folders/_id_.mjs.map +1 -1
  284. package/dist/astro/routes/api/media/folders/index.mjs +12 -11
  285. package/dist/astro/routes/api/media/folders/index.mjs.map +1 -1
  286. package/dist/astro/routes/api/media/providers/_providerId_/_itemId_.mjs +4 -4
  287. package/dist/astro/routes/api/media/providers/_providerId_/index.mjs +4 -4
  288. package/dist/astro/routes/api/media/providers/index.mjs +4 -4
  289. package/dist/astro/routes/api/media/upload-url.mjs +14 -13
  290. package/dist/astro/routes/api/media/upload-url.mjs.map +1 -1
  291. package/dist/astro/routes/api/media.mjs +26 -25
  292. package/dist/astro/routes/api/media.mjs.map +1 -1
  293. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +15 -14
  294. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs.map +1 -1
  295. package/dist/astro/routes/api/menus/_name_/items.mjs +15 -14
  296. package/dist/astro/routes/api/menus/_name_/items.mjs.map +1 -1
  297. package/dist/astro/routes/api/menus/_name_/reorder.mjs +15 -14
  298. package/dist/astro/routes/api/menus/_name_/reorder.mjs.map +1 -1
  299. package/dist/astro/routes/api/menus/_name_/translations.mjs +15 -14
  300. package/dist/astro/routes/api/menus/_name_/translations.mjs.map +1 -1
  301. package/dist/astro/routes/api/menus/_name_.mjs +15 -14
  302. package/dist/astro/routes/api/menus/_name_.mjs.map +1 -1
  303. package/dist/astro/routes/api/menus/index.mjs +15 -14
  304. package/dist/astro/routes/api/menus/index.mjs.map +1 -1
  305. package/dist/astro/routes/api/oauth/authorize.mjs +6 -6
  306. package/dist/astro/routes/api/oauth/device/authorize.mjs +7 -7
  307. package/dist/astro/routes/api/oauth/device/code.mjs +10 -10
  308. package/dist/astro/routes/api/oauth/device/token.mjs +9 -9
  309. package/dist/astro/routes/api/oauth/register.mjs +4 -4
  310. package/dist/astro/routes/api/oauth/token/refresh.mjs +7 -7
  311. package/dist/astro/routes/api/oauth/token/revoke.mjs +7 -7
  312. package/dist/astro/routes/api/oauth/token.mjs +7 -7
  313. package/dist/astro/routes/api/openapi.json.mjs +95 -24
  314. package/dist/astro/routes/api/openapi.json.mjs.map +1 -1
  315. package/dist/astro/routes/api/plugins/_pluginId_/_...path_.d.mts +2 -1
  316. package/dist/astro/routes/api/plugins/_pluginId_/_...path_.d.mts.map +1 -1
  317. package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +22 -40
  318. package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs.map +1 -1
  319. package/dist/astro/routes/api/redirects/404s/index.mjs +18 -14
  320. package/dist/astro/routes/api/redirects/404s/index.mjs.map +1 -1
  321. package/dist/astro/routes/api/redirects/404s/summary.mjs +18 -14
  322. package/dist/astro/routes/api/redirects/404s/summary.mjs.map +1 -1
  323. package/dist/astro/routes/api/redirects/_id_.d.mts.map +1 -1
  324. package/dist/astro/routes/api/redirects/_id_.mjs +20 -22
  325. package/dist/astro/routes/api/redirects/_id_.mjs.map +1 -1
  326. package/dist/astro/routes/api/redirects/index.d.mts.map +1 -1
  327. package/dist/astro/routes/api/redirects/index.mjs +19 -19
  328. package/dist/astro/routes/api/redirects/index.mjs.map +1 -1
  329. package/dist/astro/routes/api/relations/_id_/index.mjs +27 -23
  330. package/dist/astro/routes/api/relations/_id_/index.mjs.map +1 -1
  331. package/dist/astro/routes/api/relations/_id_/translations.mjs +21 -18
  332. package/dist/astro/routes/api/relations/_id_/translations.mjs.map +1 -1
  333. package/dist/astro/routes/api/relations/index.mjs +27 -23
  334. package/dist/astro/routes/api/relations/index.mjs.map +1 -1
  335. package/dist/astro/routes/api/revisions/_revisionId_/index.mjs +4 -4
  336. package/dist/astro/routes/api/revisions/_revisionId_/restore.mjs +5 -5
  337. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +65 -59
  338. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs.map +1 -1
  339. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +65 -59
  340. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs.map +1 -1
  341. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +65 -59
  342. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs.map +1 -1
  343. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +65 -59
  344. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs.map +1 -1
  345. package/dist/astro/routes/api/schema/collections/index.mjs +65 -59
  346. package/dist/astro/routes/api/schema/collections/index.mjs.map +1 -1
  347. package/dist/astro/routes/api/schema/collections/reorder.mjs +65 -59
  348. package/dist/astro/routes/api/schema/collections/reorder.mjs.map +1 -1
  349. package/dist/astro/routes/api/schema/index.mjs +16 -14
  350. package/dist/astro/routes/api/schema/index.mjs.map +1 -1
  351. package/dist/astro/routes/api/schema/orphans/_slug_.mjs +65 -59
  352. package/dist/astro/routes/api/schema/orphans/_slug_.mjs.map +1 -1
  353. package/dist/astro/routes/api/schema/orphans/index.mjs +65 -59
  354. package/dist/astro/routes/api/schema/orphans/index.mjs.map +1 -1
  355. package/dist/astro/routes/api/search/enable.mjs +16 -14
  356. package/dist/astro/routes/api/search/enable.mjs.map +1 -1
  357. package/dist/astro/routes/api/search/index.mjs +17 -14
  358. package/dist/astro/routes/api/search/index.mjs.map +1 -1
  359. package/dist/astro/routes/api/search/rebuild.mjs +16 -14
  360. package/dist/astro/routes/api/search/rebuild.mjs.map +1 -1
  361. package/dist/astro/routes/api/search/stats.mjs +10 -9
  362. package/dist/astro/routes/api/search/stats.mjs.map +1 -1
  363. package/dist/astro/routes/api/search/suggest.mjs +15 -13
  364. package/dist/astro/routes/api/search/suggest.mjs.map +1 -1
  365. package/dist/astro/routes/api/sections/_slug_.mjs +15 -13
  366. package/dist/astro/routes/api/sections/_slug_.mjs.map +1 -1
  367. package/dist/astro/routes/api/sections/index.mjs +15 -13
  368. package/dist/astro/routes/api/sections/index.mjs.map +1 -1
  369. package/dist/astro/routes/api/settings/backups/archives/_name_.mjs +9 -8
  370. package/dist/astro/routes/api/settings/backups/archives/_name_.mjs.map +1 -1
  371. package/dist/astro/routes/api/settings/backups/archives/index.mjs +8 -7
  372. package/dist/astro/routes/api/settings/backups/archives/index.mjs.map +1 -1
  373. package/dist/astro/routes/api/settings/backups/export.mjs +9 -8
  374. package/dist/astro/routes/api/settings/backups/export.mjs.map +1 -1
  375. package/dist/astro/routes/api/settings/backups/index.mjs +10 -9
  376. package/dist/astro/routes/api/settings/backups/index.mjs.map +1 -1
  377. package/dist/astro/routes/api/settings/email.mjs +6 -6
  378. package/dist/astro/routes/api/settings.mjs +22 -20
  379. package/dist/astro/routes/api/settings.mjs.map +1 -1
  380. package/dist/astro/routes/api/setup/admin-verify.mjs +16 -15
  381. package/dist/astro/routes/api/setup/admin-verify.mjs.map +1 -1
  382. package/dist/astro/routes/api/setup/admin.mjs +15 -14
  383. package/dist/astro/routes/api/setup/admin.mjs.map +1 -1
  384. package/dist/astro/routes/api/setup/dev-bypass.mjs +42 -38
  385. package/dist/astro/routes/api/setup/dev-bypass.mjs.map +1 -1
  386. package/dist/astro/routes/api/setup/dev-reset.mjs +4 -4
  387. package/dist/astro/routes/api/setup/index.mjs +43 -38
  388. package/dist/astro/routes/api/setup/index.mjs.map +1 -1
  389. package/dist/astro/routes/api/setup/status.mjs +5 -5
  390. package/dist/astro/routes/api/snapshot.mjs +11 -10
  391. package/dist/astro/routes/api/snapshot.mjs.map +1 -1
  392. package/dist/astro/routes/api/taxonomies/_name_/reorder.mjs +23 -21
  393. package/dist/astro/routes/api/taxonomies/_name_/reorder.mjs.map +1 -1
  394. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +23 -21
  395. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs.map +1 -1
  396. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +23 -21
  397. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs.map +1 -1
  398. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +23 -21
  399. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs.map +1 -1
  400. package/dist/astro/routes/api/taxonomies/_name_/translations.mjs +22 -20
  401. package/dist/astro/routes/api/taxonomies/_name_/translations.mjs.map +1 -1
  402. package/dist/astro/routes/api/taxonomies/_name_.mjs +23 -21
  403. package/dist/astro/routes/api/taxonomies/_name_.mjs.map +1 -1
  404. package/dist/astro/routes/api/taxonomies/index.mjs +23 -21
  405. package/dist/astro/routes/api/taxonomies/index.mjs.map +1 -1
  406. package/dist/astro/routes/api/themes/preview.mjs +8 -8
  407. package/dist/astro/routes/api/typegen.mjs +6 -6
  408. package/dist/astro/routes/api/visual-editing/action-token.d.mts +8 -0
  409. package/dist/astro/routes/api/visual-editing/action-token.d.mts.map +1 -0
  410. package/dist/astro/routes/api/visual-editing/action-token.mjs +25 -0
  411. package/dist/astro/routes/api/visual-editing/action-token.mjs.map +1 -0
  412. package/dist/astro/routes/api/visual-editing/content/_collection_/_id_/publish.d.mts +8 -0
  413. package/dist/astro/routes/api/visual-editing/content/_collection_/_id_/publish.d.mts.map +1 -0
  414. package/dist/astro/routes/api/visual-editing/content/_collection_/_id_/publish.mjs +37 -0
  415. package/dist/astro/routes/api/visual-editing/content/_collection_/_id_/publish.mjs.map +1 -0
  416. package/dist/astro/routes/api/visual-editing/toolbar-labels.d.mts +8 -0
  417. package/dist/astro/routes/api/visual-editing/toolbar-labels.d.mts.map +1 -0
  418. package/dist/astro/routes/api/visual-editing/toolbar-labels.mjs +20 -0
  419. package/dist/astro/routes/api/visual-editing/toolbar-labels.mjs.map +1 -0
  420. package/dist/astro/routes/api/well-known/auth.mjs +2 -2
  421. package/dist/astro/routes/api/well-known/oauth-authorization-server.mjs +2 -2
  422. package/dist/astro/routes/api/well-known/oauth-protected-resource.mjs +2 -2
  423. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +12 -11
  424. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs.map +1 -1
  425. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +16 -15
  426. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs.map +1 -1
  427. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +16 -15
  428. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs.map +1 -1
  429. package/dist/astro/routes/api/widget-areas/_name_.mjs +10 -10
  430. package/dist/astro/routes/api/widget-areas/index.mjs +16 -15
  431. package/dist/astro/routes/api/widget-areas/index.mjs.map +1 -1
  432. package/dist/astro/routes/api/widget-components.mjs +4 -4
  433. package/dist/astro/routes/robots.txt.mjs +13 -12
  434. package/dist/astro/routes/robots.txt.mjs.map +1 -1
  435. package/dist/astro/routes/sitemap-_collection_.xml.d.mts.map +1 -1
  436. package/dist/astro/routes/sitemap-_collection_.xml.mjs +24 -19
  437. package/dist/astro/routes/sitemap-_collection_.xml.mjs.map +1 -1
  438. package/dist/astro/routes/sitemap.xml.mjs +14 -13
  439. package/dist/astro/routes/sitemap.xml.mjs.map +1 -1
  440. package/dist/astro/types.d.mts +79 -26
  441. package/dist/astro/types.d.mts.map +1 -1
  442. package/dist/auth/providers/github.d.mts +1 -1
  443. package/dist/auth/providers/google.d.mts +1 -1
  444. package/dist/authoritative-records-DbqshfKD.mjs +5172 -0
  445. package/dist/authoritative-records-DbqshfKD.mjs.map +1 -0
  446. package/dist/authorize-BXpfMpp0.mjs +40 -0
  447. package/dist/authorize-BXpfMpp0.mjs.map +1 -0
  448. package/dist/backup-BsPQdwnS.mjs +246 -0
  449. package/dist/backup-BsPQdwnS.mjs.map +1 -0
  450. package/dist/base64-DvnNgP7e.mjs +63 -0
  451. package/dist/base64-DvnNgP7e.mjs.map +1 -0
  452. package/dist/byline-Doh-wt99.mjs +906 -0
  453. package/dist/byline-Doh-wt99.mjs.map +1 -0
  454. package/dist/byline-fields-CsrdvaLV.mjs +123 -0
  455. package/dist/byline-fields-CsrdvaLV.mjs.map +1 -0
  456. package/dist/byline-registry-D6lWzXk6.mjs +406 -0
  457. package/dist/byline-registry-D6lWzXk6.mjs.map +1 -0
  458. package/dist/bylines-Cop0hkoy.mjs +214 -0
  459. package/dist/bylines-Cop0hkoy.mjs.map +1 -0
  460. package/dist/bylines-kpBzHPr8.mjs +232 -0
  461. package/dist/bylines-kpBzHPr8.mjs.map +1 -0
  462. package/dist/cache-B0pOlXdM.mjs +108 -0
  463. package/dist/cache-B0pOlXdM.mjs.map +1 -0
  464. package/dist/capture-triggers-gxQxnxrJ.mjs +362 -0
  465. package/dist/capture-triggers-gxQxnxrJ.mjs.map +1 -0
  466. package/dist/challenge-store-CkRdSdd8.mjs +51 -0
  467. package/dist/challenge-store-CkRdSdd8.mjs.map +1 -0
  468. package/dist/checksum-Bsi2D9M1.mjs +162 -0
  469. package/dist/checksum-Bsi2D9M1.mjs.map +1 -0
  470. package/dist/chrome-tags-D7LGB91U.mjs +24 -0
  471. package/dist/chrome-tags-D7LGB91U.mjs.map +1 -0
  472. package/dist/chunks-BmWyou79.mjs +25 -0
  473. package/dist/chunks-BmWyou79.mjs.map +1 -0
  474. package/dist/cli/index.mjs +921 -106
  475. package/dist/cli/index.mjs.map +1 -1
  476. package/dist/client/cf-access.d.mts +1 -1
  477. package/dist/client/index.d.mts +17 -7
  478. package/dist/client/index.d.mts.map +1 -1
  479. package/dist/client/index.mjs +17 -12
  480. package/dist/client/index.mjs.map +1 -1
  481. package/dist/collection-deletion-C3Xixmkx.mjs +436 -0
  482. package/dist/collection-deletion-C3Xixmkx.mjs.map +1 -0
  483. package/dist/collection-slugs-cache-D9auiKmI.mjs +85 -0
  484. package/dist/collection-slugs-cache-D9auiKmI.mjs.map +1 -0
  485. package/dist/comment-DcT8qdPK.mjs +313 -0
  486. package/dist/comment-DcT8qdPK.mjs.map +1 -0
  487. package/dist/comment-reaction-DY5-y8Y5.mjs +85 -0
  488. package/dist/comment-reaction-DY5-y8Y5.mjs.map +1 -0
  489. package/dist/comments-B67VRNGw.mjs +204 -0
  490. package/dist/comments-B67VRNGw.mjs.map +1 -0
  491. package/dist/comments-BVzzt6x5.mjs +99 -0
  492. package/dist/comments-BVzzt6x5.mjs.map +1 -0
  493. package/dist/components-DIl9Qzh6.mjs +108 -0
  494. package/dist/components-DIl9Qzh6.mjs.map +1 -0
  495. package/dist/config-B2acLeC5.mjs +242 -0
  496. package/dist/config-B2acLeC5.mjs.map +1 -0
  497. package/dist/config-CGVeT8Hc.mjs +73 -0
  498. package/dist/config-CGVeT8Hc.mjs.map +1 -0
  499. package/dist/config-D3HhLON3.d.mts +39 -0
  500. package/dist/config-D3HhLON3.d.mts.map +1 -0
  501. package/dist/config-DS7e4EZ9.d.mts +6387 -0
  502. package/dist/config-DS7e4EZ9.d.mts.map +1 -0
  503. package/dist/content-DZ3B5qtA.mjs +2216 -0
  504. package/dist/content-DZ3B5qtA.mjs.map +1 -0
  505. package/dist/content-list-query-CbPdzsna.d.mts +26 -0
  506. package/dist/content-list-query-CbPdzsna.d.mts.map +1 -0
  507. package/dist/content-policy-CM4skrNi.mjs +46 -0
  508. package/dist/content-policy-CM4skrNi.mjs.map +1 -0
  509. package/dist/content-refresh-BHLHJgyt.mjs +3599 -0
  510. package/dist/content-refresh-BHLHJgyt.mjs.map +1 -0
  511. package/dist/content-repair-BVll5WNl.mjs +440 -0
  512. package/dist/content-repair-BVll5WNl.mjs.map +1 -0
  513. package/dist/context-B195kjqZ.mjs +1835 -0
  514. package/dist/context-B195kjqZ.mjs.map +1 -0
  515. package/dist/cron-BcR3RN4K.mjs +282 -0
  516. package/dist/cron-BcR3RN4K.mjs.map +1 -0
  517. package/dist/dashboard-CZD4G7k_.mjs +151 -0
  518. package/dist/dashboard-CZD4G7k_.mjs.map +1 -0
  519. package/dist/database/migration-lock.d.mts +37 -0
  520. package/dist/database/migration-lock.d.mts.map +1 -0
  521. package/dist/database/migration-lock.mjs +76 -0
  522. package/dist/database/migration-lock.mjs.map +1 -0
  523. package/dist/database/pg-migration-lock.d.mts +1 -1
  524. package/dist/database/pg-migration-lock.mjs +1 -1
  525. package/dist/database/pg-migration-lock.mjs.map +1 -1
  526. package/dist/datetime-normalization-PeiEdcRY.mjs +187 -0
  527. package/dist/datetime-normalization-PeiEdcRY.mjs.map +1 -0
  528. package/dist/db/index.d.mts +3 -3
  529. package/dist/db/index.mjs +4 -3
  530. package/dist/db/index.mjs.map +1 -1
  531. package/dist/db/libsql-migrations.d.mts +1 -1
  532. package/dist/db/libsql-migrations.mjs +7 -6
  533. package/dist/db/libsql-migrations.mjs.map +1 -1
  534. package/dist/db/libsql.d.mts +1 -1
  535. package/dist/db/postgres-migrations.d.mts +1 -1
  536. package/dist/db/postgres-migrations.mjs +7 -6
  537. package/dist/db/postgres-migrations.mjs.map +1 -1
  538. package/dist/db/postgres.d.mts +1 -1
  539. package/dist/db/sqlite-migrations.d.mts +1 -1
  540. package/dist/db/sqlite-migrations.mjs +7 -6
  541. package/dist/db/sqlite-migrations.mjs.map +1 -1
  542. package/dist/db/sqlite.d.mts +1 -1
  543. package/dist/db/sqlite.mjs +1 -1
  544. package/dist/db-errors-CBD5yMro.mjs +55 -0
  545. package/dist/db-errors-CBD5yMro.mjs.map +1 -0
  546. package/dist/default-BtlxWgh9.mjs +81 -0
  547. package/dist/default-BtlxWgh9.mjs.map +1 -0
  548. package/dist/deferred-tasks-Ba9fphlE.d.mts +9 -0
  549. package/dist/deferred-tasks-Ba9fphlE.d.mts.map +1 -0
  550. package/dist/dev-typegen-CZaPLl3V.mjs +29 -0
  551. package/dist/dev-typegen-CZaPLl3V.mjs.map +1 -0
  552. package/dist/device-flow-3E5l0fpH.mjs +466 -0
  553. package/dist/device-flow-3E5l0fpH.mjs.map +1 -0
  554. package/dist/dialect-helpers-CtYdsX4W.mjs +307 -0
  555. package/dist/dialect-helpers-CtYdsX4W.mjs.map +1 -0
  556. package/dist/direct-executor-ZI8E01Yt.mjs +104 -0
  557. package/dist/direct-executor-ZI8E01Yt.mjs.map +1 -0
  558. package/dist/dist-2hDLsLeq.mjs +810 -0
  559. package/dist/dist-2hDLsLeq.mjs.map +1 -0
  560. package/dist/email-console-gc-E3Eqj.mjs +50 -0
  561. package/dist/email-console-gc-E3Eqj.mjs.map +1 -0
  562. package/dist/emdash-runtime-DZGinqTL.mjs +4041 -0
  563. package/dist/emdash-runtime-DZGinqTL.mjs.map +1 -0
  564. package/dist/enrich-C2Mk0lwE.mjs +194 -0
  565. package/dist/enrich-C2Mk0lwE.mjs.map +1 -0
  566. package/dist/entry-lock-D3C99MXS.mjs +1520 -0
  567. package/dist/entry-lock-D3C99MXS.mjs.map +1 -0
  568. package/dist/entry-lock-D9rnj2Lu.mjs +163 -0
  569. package/dist/entry-lock-D9rnj2Lu.mjs.map +1 -0
  570. package/dist/entry-lock-DX7QkqEg.d.mts +3503 -0
  571. package/dist/entry-lock-DX7QkqEg.d.mts.map +1 -0
  572. package/dist/entry-locks-CO_KaoU5.mjs +167 -0
  573. package/dist/entry-locks-CO_KaoU5.mjs.map +1 -0
  574. package/dist/error-CCTCskie.mjs +90 -0
  575. package/dist/error-CCTCskie.mjs.map +1 -0
  576. package/dist/errors-W3PA8HqB.mjs +447 -0
  577. package/dist/errors-W3PA8HqB.mjs.map +1 -0
  578. package/dist/escape-DN4Qmjsl.mjs +9 -0
  579. package/dist/escape-DN4Qmjsl.mjs.map +1 -0
  580. package/dist/field-defs-cache-B337z8UJ.mjs +77 -0
  581. package/dist/field-defs-cache-B337z8UJ.mjs.map +1 -0
  582. package/dist/focal-point-Gr34o-4o.mjs +23 -0
  583. package/dist/focal-point-Gr34o-4o.mjs.map +1 -0
  584. package/dist/fts-manager-DMb0sbIQ.mjs +413 -0
  585. package/dist/fts-manager-DMb0sbIQ.mjs.map +1 -0
  586. package/dist/hash-CLVFzWvx.mjs +37 -0
  587. package/dist/hash-CLVFzWvx.mjs.map +1 -0
  588. package/dist/hook-result-KY1jq21o.d.mts +31 -0
  589. package/dist/hook-result-KY1jq21o.d.mts.map +1 -0
  590. package/dist/hreflang-BgS2FqhH.d.mts +50 -0
  591. package/dist/hreflang-BgS2FqhH.d.mts.map +1 -0
  592. package/dist/hreflang-CrJwqoeb.mjs +105 -0
  593. package/dist/hreflang-CrJwqoeb.mjs.map +1 -0
  594. package/dist/http-route-dispatch-DAKlanXb.mjs +339 -0
  595. package/dist/http-route-dispatch-DAKlanXb.mjs.map +1 -0
  596. package/dist/identity-DRGSHEEr.mjs +35 -0
  597. package/dist/identity-DRGSHEEr.mjs.map +1 -0
  598. package/dist/import-DFr5B_hC.mjs +2020 -0
  599. package/dist/import-DFr5B_hC.mjs.map +1 -0
  600. package/dist/index-CDwKDkTq.d.mts +623 -0
  601. package/dist/index-CDwKDkTq.d.mts.map +1 -0
  602. package/dist/index.d.mts +27 -22
  603. package/dist/index.mjs +101 -86
  604. package/dist/init-lock-4eRRB4Le.mjs +56 -0
  605. package/dist/init-lock-4eRRB4Le.mjs.map +1 -0
  606. package/dist/install-finalization-5Os-QZ-2.mjs +58 -0
  607. package/dist/install-finalization-5Os-QZ-2.mjs.map +1 -0
  608. package/dist/lifecycle-7e-Lt_kX.mjs +25 -0
  609. package/dist/lifecycle-7e-Lt_kX.mjs.map +1 -0
  610. package/dist/load-Cu5bvCZh.mjs +28 -0
  611. package/dist/load-Cu5bvCZh.mjs.map +1 -0
  612. package/dist/loader-t4TxaFiQ.mjs +1004 -0
  613. package/dist/loader-t4TxaFiQ.mjs.map +1 -0
  614. package/dist/manifest-builder-D31UoJCu.mjs +189 -0
  615. package/dist/manifest-builder-D31UoJCu.mjs.map +1 -0
  616. package/dist/manifest-schema-Bkh8SeHd.mjs +491 -0
  617. package/dist/manifest-schema-Bkh8SeHd.mjs.map +1 -0
  618. package/dist/media/image-endpoint.mjs +1 -1
  619. package/dist/media/index.d.mts +1 -1
  620. package/dist/media/index.mjs +4 -4
  621. package/dist/media/local-runtime.d.mts +14 -12
  622. package/dist/media/local-runtime.d.mts.map +1 -1
  623. package/dist/media/local-runtime.mjs +12 -11
  624. package/dist/media/local-runtime.mjs.map +1 -1
  625. package/dist/media-TBlKCwo7.mjs +334 -0
  626. package/dist/media-TBlKCwo7.mjs.map +1 -0
  627. package/dist/media-allowlist-s60eAIf6.mjs +44 -0
  628. package/dist/media-allowlist-s60eAIf6.mjs.map +1 -0
  629. package/dist/media-folders-ClIRLUQv.mjs +210 -0
  630. package/dist/media-folders-ClIRLUQv.mjs.map +1 -0
  631. package/dist/media-url-DY_ijO3B.mjs +43 -0
  632. package/dist/media-url-DY_ijO3B.mjs.map +1 -0
  633. package/dist/media-usage-C4NolTpQ.mjs +1833 -0
  634. package/dist/media-usage-C4NolTpQ.mjs.map +1 -0
  635. package/dist/media-usage-activation-CAhmb14O.mjs +78 -0
  636. package/dist/media-usage-activation-CAhmb14O.mjs.map +1 -0
  637. package/dist/media-usage-work-Cu5DqewW.mjs +586 -0
  638. package/dist/media-usage-work-Cu5DqewW.mjs.map +1 -0
  639. package/dist/media-usage-work-DJr3rOEN.mjs +152 -0
  640. package/dist/media-usage-work-DJr3rOEN.mjs.map +1 -0
  641. package/dist/media-usage-write-fence-DW5oHT7q.mjs +42 -0
  642. package/dist/media-usage-write-fence-DW5oHT7q.mjs.map +1 -0
  643. package/dist/menus-DbgU9z5Q.mjs +3732 -0
  644. package/dist/menus-DbgU9z5Q.mjs.map +1 -0
  645. package/dist/menus-Wy8m5NcH.mjs +753 -0
  646. package/dist/menus-Wy8m5NcH.mjs.map +1 -0
  647. package/dist/migrations/index.d.mts +2 -2
  648. package/dist/migrations/index.d.mts.map +1 -1
  649. package/dist/migrations/index.mjs +6 -5
  650. package/dist/mime-CCYRC4r1.mjs +36 -0
  651. package/dist/mime-CCYRC4r1.mjs.map +1 -0
  652. package/dist/mode-CkmOhFqj.mjs +23 -0
  653. package/dist/mode-CkmOhFqj.mjs.map +1 -0
  654. package/dist/node-sqlite-compat-vpVaILnb.mjs +46 -0
  655. package/dist/node-sqlite-compat-vpVaILnb.mjs.map +1 -0
  656. package/dist/normalize-dChXQjwS.mjs +191 -0
  657. package/dist/normalize-dChXQjwS.mjs.map +1 -0
  658. package/dist/oauth-authorization-DZ-R-hmx.mjs +274 -0
  659. package/dist/oauth-authorization-DZ-R-hmx.mjs.map +1 -0
  660. package/dist/oauth-clients-BMPA8vjl.mjs +266 -0
  661. package/dist/oauth-clients-BMPA8vjl.mjs.map +1 -0
  662. package/dist/oauth-state-store-0gIdb48-.mjs +50 -0
  663. package/dist/oauth-state-store-0gIdb48-.mjs.map +1 -0
  664. package/dist/oauth-user-lookup-ChVW4UWu.mjs +26 -0
  665. package/dist/oauth-user-lookup-ChVW4UWu.mjs.map +1 -0
  666. package/dist/object-cache/memory.d.mts +1 -1
  667. package/dist/object-cache-DlSVbn5Y.mjs +534 -0
  668. package/dist/object-cache-DlSVbn5Y.mjs.map +1 -0
  669. package/dist/options-D5WcorD5.mjs +200 -0
  670. package/dist/options-D5WcorD5.mjs.map +1 -0
  671. package/dist/options-DAknChnw.d.mts +77 -0
  672. package/dist/options-DAknChnw.d.mts.map +1 -0
  673. package/dist/page/index.d.mts +2 -2
  674. package/dist/page/index.d.mts.map +1 -1
  675. package/dist/page/index.mjs +13 -0
  676. package/dist/page/index.mjs.map +1 -1
  677. package/dist/parse-Cr379Av9.mjs +81 -0
  678. package/dist/parse-Cr379Av9.mjs.map +1 -0
  679. package/dist/parse-tj9XLNO_.d.mts +165 -0
  680. package/dist/parse-tj9XLNO_.d.mts.map +1 -0
  681. package/dist/passkey-config-BD-wMaCf.mjs +46 -0
  682. package/dist/passkey-config-BD-wMaCf.mjs.map +1 -0
  683. package/dist/patterns-Do3iqi7N.mjs +145 -0
  684. package/dist/patterns-Do3iqi7N.mjs.map +1 -0
  685. package/dist/placeholder-CubPFn_L.d.mts +306 -0
  686. package/dist/placeholder-CubPFn_L.d.mts.map +1 -0
  687. package/dist/plugin-test-runtime.d.mts +97 -0
  688. package/dist/plugin-test-runtime.d.mts.map +1 -0
  689. package/dist/plugin-test-runtime.mjs +105 -0
  690. package/dist/plugin-types.d.mts +53 -15
  691. package/dist/plugin-types.d.mts.map +1 -1
  692. package/dist/plugin-types.mjs +18 -1
  693. package/dist/plugin-types.mjs.map +1 -0
  694. package/dist/plugin-utils.d.mts +12 -10
  695. package/dist/plugin-utils.d.mts.map +1 -1
  696. package/dist/plugins/adapt-sandbox-entry.d.mts +12 -10
  697. package/dist/plugins/adapt-sandbox-entry.d.mts.map +1 -1
  698. package/dist/plugins/adapt-sandbox-entry.mjs +18 -13
  699. package/dist/plugins/adapt-sandbox-entry.mjs.map +1 -1
  700. package/dist/plugins/host.d.mts +7 -0
  701. package/dist/plugins/host.mjs +45 -0
  702. package/dist/plugins/http-wire.d.mts +25 -0
  703. package/dist/plugins/http-wire.d.mts.map +1 -0
  704. package/dist/plugins/http-wire.mjs +148 -0
  705. package/dist/plugins/http-wire.mjs.map +1 -0
  706. package/dist/plugins/secret-redactor.d.mts +9 -0
  707. package/dist/plugins/secret-redactor.d.mts.map +1 -0
  708. package/dist/plugins/secret-redactor.mjs +51 -0
  709. package/dist/plugins/secret-redactor.mjs.map +1 -0
  710. package/dist/plugins-DHurtdXQ.mjs +277 -0
  711. package/dist/plugins-DHurtdXQ.mjs.map +1 -0
  712. package/dist/policy-lyZnjpwz.mjs +45 -0
  713. package/dist/policy-lyZnjpwz.mjs.map +1 -0
  714. package/dist/portable-text-oAwodbPS.mjs +286 -0
  715. package/dist/portable-text-oAwodbPS.mjs.map +1 -0
  716. package/dist/preview-Cup2bj8c.mjs +107 -0
  717. package/dist/preview-Cup2bj8c.mjs.map +1 -0
  718. package/dist/protocol-C1CNiKX4.d.mts +61 -0
  719. package/dist/protocol-C1CNiKX4.d.mts.map +1 -0
  720. package/dist/public-submission-Cs-pFMQK.mjs +245 -0
  721. package/dist/public-submission-Cs-pFMQK.mjs.map +1 -0
  722. package/dist/public-url-BWVHsfQv.mjs +101 -0
  723. package/dist/public-url-BWVHsfQv.mjs.map +1 -0
  724. package/dist/query-D-lxiOgn.mjs +890 -0
  725. package/dist/query-D-lxiOgn.mjs.map +1 -0
  726. package/dist/query-D7kHKOws.mjs +41 -0
  727. package/dist/query-D7kHKOws.mjs.map +1 -0
  728. package/dist/rate-limit-CqJn-w4h.mjs +120 -0
  729. package/dist/rate-limit-CqJn-w4h.mjs.map +1 -0
  730. package/dist/redirect-BrChFPIu.mjs +17 -0
  731. package/dist/redirect-BrChFPIu.mjs.map +1 -0
  732. package/dist/redirect-D2Yo-b6S.mjs +415 -0
  733. package/dist/redirect-D2Yo-b6S.mjs.map +1 -0
  734. package/dist/redirects-BCiTaIQ-.mjs +146 -0
  735. package/dist/redirects-BCiTaIQ-.mjs.map +1 -0
  736. package/dist/redirects-ByItliuu.mjs +644 -0
  737. package/dist/redirects-ByItliuu.mjs.map +1 -0
  738. package/dist/registry/testing.d.mts +14 -0
  739. package/dist/registry/testing.d.mts.map +1 -0
  740. package/dist/registry/testing.mjs +255 -0
  741. package/dist/registry/testing.mjs.map +1 -0
  742. package/dist/registry-CkuPoZs7.mjs +1222 -0
  743. package/dist/registry-CkuPoZs7.mjs.map +1 -0
  744. package/dist/relation-XTAtOpJO.mjs +334 -0
  745. package/dist/relation-XTAtOpJO.mjs.map +1 -0
  746. package/dist/relations-B4w-G5U9.mjs +309 -0
  747. package/dist/relations-B4w-G5U9.mjs.map +1 -0
  748. package/dist/relations-O63JWBRj.mjs +403 -0
  749. package/dist/relations-O63JWBRj.mjs.map +1 -0
  750. package/dist/request-cache-DaMhSQdx.mjs +104 -0
  751. package/dist/request-cache-DaMhSQdx.mjs.map +1 -0
  752. package/dist/request-context.d.mts +1 -1
  753. package/dist/request-meta-C8yl_sIs.mjs +141 -0
  754. package/dist/request-meta-C8yl_sIs.mjs.map +1 -0
  755. package/dist/resolve-BJIS8wKr.mjs +199 -0
  756. package/dist/resolve-BJIS8wKr.mjs.map +1 -0
  757. package/dist/route-wire-D66L2oaZ.mjs +197 -0
  758. package/dist/route-wire-D66L2oaZ.mjs.map +1 -0
  759. package/dist/routes-DYsTe-oR.mjs +321 -0
  760. package/dist/routes-DYsTe-oR.mjs.map +1 -0
  761. package/dist/runner-3gfxRsJG.d.mts +68 -0
  762. package/dist/runner-3gfxRsJG.d.mts.map +1 -0
  763. package/dist/runner-ClrleR8A.mjs +5502 -0
  764. package/dist/runner-ClrleR8A.mjs.map +1 -0
  765. package/dist/runtime.d.mts +13 -11
  766. package/dist/runtime.d.mts.map +1 -1
  767. package/dist/runtime.mjs +6 -5
  768. package/dist/runtime.mjs.map +1 -1
  769. package/dist/schema-CPhPM9Do.mjs +420 -0
  770. package/dist/schema-CPhPM9Do.mjs.map +1 -0
  771. package/dist/schema-DEERRrKS.mjs +9 -0
  772. package/dist/schema-DEERRrKS.mjs.map +1 -0
  773. package/dist/scopes-Bn8_rCSt.mjs +27 -0
  774. package/dist/scopes-Bn8_rCSt.mjs.map +1 -0
  775. package/dist/search-lami_Ota.mjs +448 -0
  776. package/dist/search-lami_Ota.mjs.map +1 -0
  777. package/dist/secrets-DNgVgz_e.mjs +341 -0
  778. package/dist/secrets-DNgVgz_e.mjs.map +1 -0
  779. package/dist/sections-BIpd4Cxf.mjs +346 -0
  780. package/dist/sections-BIpd4Cxf.mjs.map +1 -0
  781. package/dist/seed/index.d.mts +2 -2
  782. package/dist/seed/index.mjs +35 -31
  783. package/dist/seo/index.d.mts +3 -3
  784. package/dist/seo/index.d.mts.map +1 -1
  785. package/dist/seo/index.mjs +27 -26
  786. package/dist/seo/index.mjs.map +1 -1
  787. package/dist/seo-BtU70b7l.mjs +114 -0
  788. package/dist/seo-BtU70b7l.mjs.map +1 -0
  789. package/dist/seo-_4qmazxz.mjs +133 -0
  790. package/dist/seo-_4qmazxz.mjs.map +1 -0
  791. package/dist/service-Bpy5iTX0.mjs +150 -0
  792. package/dist/service-Bpy5iTX0.mjs.map +1 -0
  793. package/dist/session-user-BQeS2Mrb.mjs +51 -0
  794. package/dist/session-user-BQeS2Mrb.mjs.map +1 -0
  795. package/dist/settings-DmroR53o.mjs +420 -0
  796. package/dist/settings-DmroR53o.mjs.map +1 -0
  797. package/dist/settings-g2F2a3Ub.mjs +51 -0
  798. package/dist/settings-g2F2a3Ub.mjs.map +1 -0
  799. package/dist/setup-complete-BrZaXpVV.mjs +26 -0
  800. package/dist/setup-complete-BrZaXpVV.mjs.map +1 -0
  801. package/dist/setup-nonce-Cb9-884O.mjs +25 -0
  802. package/dist/setup-nonce-Cb9-884O.mjs.map +1 -0
  803. package/dist/single-flight-cache-B5O2qhO1.mjs +104 -0
  804. package/dist/single-flight-cache-B5O2qhO1.mjs.map +1 -0
  805. package/dist/site-url-DjhYCaep.mjs +16 -0
  806. package/dist/site-url-DjhYCaep.mjs.map +1 -0
  807. package/dist/slugify-T5GHH42D.mjs +17 -0
  808. package/dist/slugify-T5GHH42D.mjs.map +1 -0
  809. package/dist/snapshot-C32Xuv3o.mjs +233 -0
  810. package/dist/snapshot-C32Xuv3o.mjs.map +1 -0
  811. package/dist/ssrf-Co1GGFZz.mjs +406 -0
  812. package/dist/ssrf-Co1GGFZz.mjs.map +1 -0
  813. package/dist/state-C7gCoiHr.mjs +153 -0
  814. package/dist/state-C7gCoiHr.mjs.map +1 -0
  815. package/dist/status-DLoBmcDz.mjs +30 -0
  816. package/dist/status-DLoBmcDz.mjs.map +1 -0
  817. package/dist/storage/local.d.mts +1 -1
  818. package/dist/storage/local.mjs +1 -1
  819. package/dist/storage/s3.d.mts +1 -1
  820. package/dist/storage/s3.mjs +1 -1
  821. package/dist/storage-query-CPctdMKX.d.mts +1519 -0
  822. package/dist/storage-query-CPctdMKX.d.mts.map +1 -0
  823. package/dist/target-CUKlGrXb.mjs +27 -0
  824. package/dist/target-CUKlGrXb.mjs.map +1 -0
  825. package/dist/taxonomies-BpqpXJUE.mjs +707 -0
  826. package/dist/taxonomies-BpqpXJUE.mjs.map +1 -0
  827. package/dist/taxonomies-ClCo4IGO.mjs +899 -0
  828. package/dist/taxonomies-ClCo4IGO.mjs.map +1 -0
  829. package/dist/taxonomy-Dj1vpw5E.mjs +508 -0
  830. package/dist/taxonomy-Dj1vpw5E.mjs.map +1 -0
  831. package/dist/tokens-Ns02GAma.mjs +171 -0
  832. package/dist/tokens-Ns02GAma.mjs.map +1 -0
  833. package/dist/transaction-BcJO4Tmc.mjs +29 -0
  834. package/dist/transaction-BcJO4Tmc.mjs.map +1 -0
  835. package/dist/transport-B8P1xsqk.mjs +136 -0
  836. package/dist/transport-B8P1xsqk.mjs.map +1 -0
  837. package/dist/transport-BLHZZcD_.d.mts +42 -0
  838. package/dist/transport-BLHZZcD_.d.mts.map +1 -0
  839. package/dist/trusted-proxy-Cg7SuD15.mjs +51 -0
  840. package/dist/trusted-proxy-Cg7SuD15.mjs.map +1 -0
  841. package/dist/turnstile-DWCSh_Qc.mjs +53 -0
  842. package/dist/turnstile-DWCSh_Qc.mjs.map +1 -0
  843. package/dist/types-B3RkqvDW.mjs +156 -0
  844. package/dist/types-B3RkqvDW.mjs.map +1 -0
  845. package/dist/types-BkUg2yHx.mjs +92 -0
  846. package/dist/types-BkUg2yHx.mjs.map +1 -0
  847. package/dist/types-BtuppOTV.mjs +16 -0
  848. package/dist/types-BtuppOTV.mjs.map +1 -0
  849. package/dist/types-CCR3ivXE.d.mts +363 -0
  850. package/dist/types-CCR3ivXE.d.mts.map +1 -0
  851. package/dist/types-CSHgU_-_.mjs +18 -0
  852. package/dist/types-CSHgU_-_.mjs.map +1 -0
  853. package/dist/types-CbwqGOXm.d.mts +766 -0
  854. package/dist/types-CbwqGOXm.d.mts.map +1 -0
  855. package/dist/types-D4RGIc2I.d.mts +198 -0
  856. package/dist/types-D4RGIc2I.d.mts.map +1 -0
  857. package/dist/types-DEHidMEk.d.mts +1637 -0
  858. package/dist/types-DEHidMEk.d.mts.map +1 -0
  859. package/dist/types-DQeU2SR7.d.mts +279 -0
  860. package/dist/types-DQeU2SR7.d.mts.map +1 -0
  861. package/dist/types-DxQWoQLA.d.mts +264 -0
  862. package/dist/types-DxQWoQLA.d.mts.map +1 -0
  863. package/dist/types-FBBnGZ2Y.d.mts +198 -0
  864. package/dist/types-FBBnGZ2Y.d.mts.map +1 -0
  865. package/dist/types-ZCnlropY.mjs +69 -0
  866. package/dist/types-ZCnlropY.mjs.map +1 -0
  867. package/dist/types-_Qtyawiy.d.mts +124 -0
  868. package/dist/types-_Qtyawiy.d.mts.map +1 -0
  869. package/dist/types-gC6FAoa_.d.mts +75 -0
  870. package/dist/types-gC6FAoa_.d.mts.map +1 -0
  871. package/dist/types-k--LneIF.mjs +22 -0
  872. package/dist/types-k--LneIF.mjs.map +1 -0
  873. package/dist/upload-attempts-2xdnoKGe.mjs +27 -0
  874. package/dist/upload-attempts-2xdnoKGe.mjs.map +1 -0
  875. package/dist/url-pattern-3m3reMzr.mjs +33 -0
  876. package/dist/url-pattern-3m3reMzr.mjs.map +1 -0
  877. package/dist/user-DroRntkx.mjs +171 -0
  878. package/dist/user-DroRntkx.mjs.map +1 -0
  879. package/dist/utils-CC2oNGV8.mjs +435 -0
  880. package/dist/utils-CC2oNGV8.mjs.map +1 -0
  881. package/dist/validate-BCP9HNDn.mjs +384 -0
  882. package/dist/validate-BCP9HNDn.mjs.map +1 -0
  883. package/dist/validate-CyQ7I3xF.d.mts +410 -0
  884. package/dist/validate-CyQ7I3xF.d.mts.map +1 -0
  885. package/dist/validate-DANX1-Qi.mjs +120 -0
  886. package/dist/validate-DANX1-Qi.mjs.map +1 -0
  887. package/dist/validation-DBy6WF94.mjs +216 -0
  888. package/dist/validation-DBy6WF94.mjs.map +1 -0
  889. package/dist/version-B57E4Uo7.mjs +7 -0
  890. package/dist/version-B57E4Uo7.mjs.map +1 -0
  891. package/dist/widgets-wQ7Xcgq8.mjs +126 -0
  892. package/dist/widgets-wQ7Xcgq8.mjs.map +1 -0
  893. package/dist/wxr-taxonomies-DIHfvEDt.mjs +406 -0
  894. package/dist/wxr-taxonomies-DIHfvEDt.mjs.map +1 -0
  895. package/dist/wxr-taxonomies-DU2ZSiGc.d.mts +34 -0
  896. package/dist/wxr-taxonomies-DU2ZSiGc.d.mts.map +1 -0
  897. package/dist/zod-generator-D_yHIWfs.mjs +329 -0
  898. package/dist/zod-generator-D_yHIWfs.mjs.map +1 -0
  899. package/package.json +39 -12
  900. package/src/api/errors.ts +23 -0
  901. package/src/api/handlers/backup.ts +11 -5
  902. package/src/api/handlers/content.ts +226 -85
  903. package/src/api/handlers/dashboard.ts +31 -1
  904. package/src/api/handlers/entry-lock.ts +206 -0
  905. package/src/api/handlers/index.ts +3 -0
  906. package/src/api/handlers/manifest.ts +5 -6
  907. package/src/api/handlers/marketplace.ts +126 -34
  908. package/src/api/handlers/media-upload.ts +31 -4
  909. package/src/api/handlers/menus.ts +9 -0
  910. package/src/api/handlers/plugin-settings.ts +35 -3
  911. package/src/api/handlers/redirects.ts +221 -138
  912. package/src/api/handlers/registry.ts +75 -29
  913. package/src/api/handlers/revision.ts +16 -27
  914. package/src/api/handlers/seo.ts +10 -1
  915. package/src/api/handlers/snapshot.ts +87 -72
  916. package/src/api/handlers/taxonomies.ts +79 -5
  917. package/src/api/handlers/validation.ts +120 -19
  918. package/src/api/openapi/document.ts +133 -11
  919. package/src/api/schemas/content.ts +32 -12
  920. package/src/api/schemas/entry-lock.ts +57 -0
  921. package/src/api/schemas/index.ts +1 -0
  922. package/src/api/schemas/schema.ts +10 -1
  923. package/src/api/schemas/search.ts +4 -0
  924. package/src/api/types.ts +4 -0
  925. package/src/astro/integration/index.ts +22 -6
  926. package/src/astro/integration/routes.ts +89 -0
  927. package/src/astro/integration/runtime.ts +40 -24
  928. package/src/astro/integration/virtual-modules.ts +4 -0
  929. package/src/astro/integration/vite-config.ts +31 -0
  930. package/src/astro/middleware/auth.ts +25 -4
  931. package/src/astro/middleware/request-context.ts +28 -10
  932. package/src/astro/middleware.ts +33 -1
  933. package/src/astro/prefetch.ts +2 -2
  934. package/src/astro/routes/api/admin/comments/[id]/status.ts +22 -58
  935. package/src/astro/routes/api/admin/plugins/[id]/disable.ts +2 -15
  936. package/src/astro/routes/api/admin/plugins/[id]/enable.ts +2 -25
  937. package/src/astro/routes/api/admin/plugins/[id]/uninstall.ts +1 -0
  938. package/src/astro/routes/api/admin/plugins/[id]/update.ts +23 -4
  939. package/src/astro/routes/api/admin/plugins/marketplace/[id]/install.ts +12 -2
  940. package/src/astro/routes/api/admin/plugins/registry/[id]/uninstall.ts +1 -0
  941. package/src/astro/routes/api/admin/plugins/registry/[id]/update.ts +29 -10
  942. package/src/astro/routes/api/admin/plugins/registry/artifact.ts +8 -2
  943. package/src/astro/routes/api/admin/plugins/registry/install.ts +15 -4
  944. package/src/astro/routes/api/admin/plugins/registry/verify.ts +2 -1
  945. package/src/astro/routes/api/admin/plugins/updates.ts +6 -1
  946. package/src/astro/routes/api/admin/scheduled-policy-rejections/[collection]/[id].ts +34 -0
  947. package/src/astro/routes/api/comments/[collection]/[contentId]/index.ts +4 -259
  948. package/src/astro/routes/api/content/[collection]/[id]/discard-draft.ts +10 -0
  949. package/src/astro/routes/api/content/[collection]/[id]/lock.ts +133 -0
  950. package/src/astro/routes/api/content/[collection]/[id]/plugin-extensions/[pluginId]/[kind]/[extensionId].ts +29 -0
  951. package/src/astro/routes/api/content/[collection]/[id]/publish.ts +21 -4
  952. package/src/astro/routes/api/content/[collection]/[id]/schedule.ts +30 -1
  953. package/src/astro/routes/api/content/[collection]/[id]/unpublish.ts +15 -1
  954. package/src/astro/routes/api/content/[collection]/[id].ts +27 -2
  955. package/src/astro/routes/api/content/[collection]/index.ts +3 -0
  956. package/src/astro/routes/api/health.ts +23 -0
  957. package/src/astro/routes/api/manifest.ts +14 -4
  958. package/src/astro/routes/api/mcp.ts +2 -1
  959. package/src/astro/routes/api/media/asset/[id]/[filename].ts +50 -0
  960. package/src/astro/routes/api/plugins/[pluginId]/[...path].ts +13 -81
  961. package/src/astro/routes/api/redirects/[id].ts +0 -3
  962. package/src/astro/routes/api/redirects/index.ts +0 -2
  963. package/src/astro/routes/api/search/index.ts +1 -0
  964. package/src/astro/routes/api/visual-editing/action-token.ts +36 -0
  965. package/src/astro/routes/api/visual-editing/content/[collection]/[id]/publish.ts +32 -0
  966. package/src/astro/routes/api/visual-editing/toolbar-labels.ts +16 -0
  967. package/src/astro/routes/sitemap-[collection].xml.ts +11 -4
  968. package/src/astro/types.ts +83 -12
  969. package/src/cli/commands/bundle-utils.ts +19 -19
  970. package/src/cli/commands/bundle.ts +9 -6
  971. package/src/cli/commands/content.ts +32 -6
  972. package/src/cli/commands/doctor.ts +25 -0
  973. package/src/cli/commands/export-seed.ts +195 -56
  974. package/src/cli/commands/migrate.ts +71 -23
  975. package/src/cli/commands/publish.ts +2 -2
  976. package/src/client/index.ts +34 -7
  977. package/src/comments/public-submission.ts +246 -0
  978. package/src/comments/service.ts +59 -12
  979. package/src/components/EmDashBodyEnd.astro +4 -1
  980. package/src/components/EmDashBodyStart.astro +4 -1
  981. package/src/components/EmDashHead.astro +36 -16
  982. package/src/components/Gallery.astro +18 -4
  983. package/src/components/InlineEditor.astro +3 -1
  984. package/src/components/InlinePortableTextEditor.tsx +106 -11
  985. package/src/components/PortableText.astro +4 -0
  986. package/src/components/Table.astro +147 -62
  987. package/src/components/widgets/Archives.astro +6 -5
  988. package/src/config/errors.ts +13 -0
  989. package/src/config/secrets.ts +25 -11
  990. package/src/content/converters/portable-text-to-prosemirror.ts +26 -2
  991. package/src/content/converters/prosemirror-to-portable-text.ts +35 -6
  992. package/src/content/converters/types.ts +10 -0
  993. package/src/content/known-fields.ts +44 -0
  994. package/src/database/connection.ts +5 -1
  995. package/src/database/content-datetime.ts +123 -0
  996. package/src/database/datetime-storage.ts +452 -0
  997. package/src/database/dialect-helpers.ts +161 -1
  998. package/src/database/migration-lock.ts +140 -0
  999. package/src/database/migrations/075_entry_edit_locks.ts +44 -0
  1000. package/src/database/migrations/076_collection_nav_group.ts +22 -0
  1001. package/src/database/migrations/077_plugin_storage_revisions.ts +89 -0
  1002. package/src/database/migrations/078_menu_item_translation_groups.ts +15 -0
  1003. package/src/database/migrations/079_datetime_normalization.ts +13 -0
  1004. package/src/database/migrations/080_content_translation_locale_unique.ts +88 -0
  1005. package/src/database/migrations/081_redirect_write_guards.ts +257 -0
  1006. package/src/database/migrations/082_taxonomy_translation_locale_unique.ts +49 -0
  1007. package/src/database/migrations/runner.ts +63 -15
  1008. package/src/database/pg-migration-lock.ts +2 -2
  1009. package/src/database/repositories/byline.ts +9 -0
  1010. package/src/database/repositories/comment.ts +86 -0
  1011. package/src/database/repositories/content.ts +560 -69
  1012. package/src/database/repositories/entry-locks.ts +257 -0
  1013. package/src/database/repositories/media.ts +35 -4
  1014. package/src/database/repositories/menu.ts +1 -0
  1015. package/src/database/repositories/options.ts +113 -7
  1016. package/src/database/repositories/plugin-storage.ts +159 -0
  1017. package/src/database/repositories/redirect.ts +262 -56
  1018. package/src/database/repositories/revision.ts +116 -17
  1019. package/src/database/repositories/taxonomy.ts +42 -0
  1020. package/src/database/repositories/types.ts +5 -0
  1021. package/src/database/types.ts +26 -1
  1022. package/src/datetime-normalization.ts +311 -0
  1023. package/src/db/node-sqlite-compat.ts +3 -2
  1024. package/src/emdash-runtime.ts +1994 -424
  1025. package/src/fields/image.ts +2 -0
  1026. package/src/i18n/config.ts +6 -6
  1027. package/src/i18n/resolve.ts +98 -15
  1028. package/src/index.ts +101 -0
  1029. package/src/loader.ts +49 -4
  1030. package/src/mcp/server.ts +216 -68
  1031. package/src/media/responsive.ts +23 -0
  1032. package/src/media/usage/content-refresh.ts +2 -1
  1033. package/src/media/usage/extractor.ts +50 -15
  1034. package/src/media/usage/types.ts +1 -1
  1035. package/src/menus/index.ts +64 -35
  1036. package/src/migrations/direct-executor.ts +40 -2
  1037. package/src/migrations/index.ts +1 -0
  1038. package/src/migrations/protocol.ts +11 -1
  1039. package/src/page/seo-contributions.ts +78 -1
  1040. package/src/page/seo-panel.ts +47 -0
  1041. package/src/plugin-test-runtime.ts +17 -0
  1042. package/src/plugin-types.ts +128 -21
  1043. package/src/plugins/adapt-sandbox-entry.ts +34 -27
  1044. package/src/plugins/conditional-storage.ts +30 -0
  1045. package/src/plugins/content-access.ts +170 -0
  1046. package/src/plugins/content-policy.ts +74 -0
  1047. package/src/plugins/context.ts +790 -166
  1048. package/src/plugins/cron.ts +18 -10
  1049. package/src/plugins/define-plugin.ts +55 -54
  1050. package/src/plugins/editor-draft.ts +257 -0
  1051. package/src/plugins/hooks.ts +136 -3
  1052. package/src/plugins/host.ts +29 -0
  1053. package/src/plugins/http-route-dispatch.ts +389 -0
  1054. package/src/plugins/http-wire.ts +180 -0
  1055. package/src/plugins/index.ts +97 -3
  1056. package/src/plugins/install-finalization.ts +77 -0
  1057. package/src/plugins/lifecycle.ts +47 -0
  1058. package/src/plugins/manager.ts +5 -2
  1059. package/src/plugins/manifest-schema.ts +314 -58
  1060. package/src/plugins/media.ts +166 -0
  1061. package/src/plugins/request-meta.ts +12 -2
  1062. package/src/plugins/route-wire.ts +304 -0
  1063. package/src/plugins/routes.ts +38 -5
  1064. package/src/plugins/sandbox/index.ts +4 -0
  1065. package/src/plugins/sandbox/proxy.ts +129 -0
  1066. package/src/plugins/sandbox/types.ts +83 -7
  1067. package/src/plugins/secret-redactor.ts +65 -0
  1068. package/src/plugins/settings.ts +303 -0
  1069. package/src/plugins/state.ts +26 -0
  1070. package/src/plugins/storage-query.ts +45 -0
  1071. package/src/plugins/storage-update.ts +96 -0
  1072. package/src/plugins/types.ts +602 -15
  1073. package/src/query.ts +84 -4
  1074. package/src/registry/authoritative-records.ts +26 -0
  1075. package/src/registry/config.ts +182 -31
  1076. package/src/registry/testing.ts +100 -0
  1077. package/src/registry/types.ts +12 -70
  1078. package/src/scheduled-publish.ts +70 -3
  1079. package/src/schema/collection-slugs-cache.ts +157 -0
  1080. package/src/schema/index.ts +1 -0
  1081. package/src/schema/registry.ts +64 -1
  1082. package/src/schema/types.ts +32 -6
  1083. package/src/schema/zod-generator.ts +5 -13
  1084. package/src/search/fts-manager.ts +3 -3
  1085. package/src/search/query.ts +32 -5
  1086. package/src/search/types.ts +8 -0
  1087. package/src/security/ssrf.ts +167 -141
  1088. package/src/seed/apply.ts +41 -3
  1089. package/src/seed/types.ts +13 -3
  1090. package/src/seed/validate.ts +18 -1
  1091. package/src/seo/hreflang.ts +10 -6
  1092. package/src/seo/index.ts +5 -10
  1093. package/src/seo/media-url.ts +26 -0
  1094. package/src/settings/index.ts +53 -11
  1095. package/src/taxonomies/term-counts.ts +22 -5
  1096. package/src/visual-editing/action-token.ts +31 -0
  1097. package/src/visual-editing/toolbar-bootstrap.ts +31 -6
  1098. package/src/visual-editing/toolbar.ts +103 -12
  1099. package/src/widgets/archives.ts +10 -9
  1100. package/src/widgets/index.ts +11 -1
  1101. package/dist/activation-K0kGBWuJ.mjs +0 -382
  1102. package/dist/activation-K0kGBWuJ.mjs.map +0 -1
  1103. package/dist/adapters-BDQwg236.d.mts +0 -171
  1104. package/dist/adapters-BDQwg236.d.mts.map +0 -1
  1105. package/dist/after-CBU2vkoO.mjs +0 -96
  1106. package/dist/after-CBU2vkoO.mjs.map +0 -1
  1107. package/dist/allowed-origins-BGglilcs.mjs +0 -116
  1108. package/dist/allowed-origins-BGglilcs.mjs.map +0 -1
  1109. package/dist/api-Dz6rgoa3.mjs +0 -10040
  1110. package/dist/api-Dz6rgoa3.mjs.map +0 -1
  1111. package/dist/api-tokens-BSsQACNe.mjs +0 -163
  1112. package/dist/api-tokens-BSsQACNe.mjs.map +0 -1
  1113. package/dist/apply-B4SIOxR1.mjs +0 -980
  1114. package/dist/apply-B4SIOxR1.mjs.map +0 -1
  1115. package/dist/authorize-Bkf_UHhD.mjs +0 -40
  1116. package/dist/authorize-Bkf_UHhD.mjs.map +0 -1
  1117. package/dist/backup-rwVAl9NI.mjs +0 -241
  1118. package/dist/backup-rwVAl9NI.mjs.map +0 -1
  1119. package/dist/base64-CvLhUKQv.mjs +0 -63
  1120. package/dist/base64-CvLhUKQv.mjs.map +0 -1
  1121. package/dist/bundle-C8S2Zl6U.mjs +0 -663
  1122. package/dist/bundle-C8S2Zl6U.mjs.map +0 -1
  1123. package/dist/byline-DuhF7NWl.mjs +0 -902
  1124. package/dist/byline-DuhF7NWl.mjs.map +0 -1
  1125. package/dist/byline-fields-BovY4KYM.mjs +0 -123
  1126. package/dist/byline-fields-BovY4KYM.mjs.map +0 -1
  1127. package/dist/byline-registry-Bpu9-MVs.mjs +0 -406
  1128. package/dist/byline-registry-Bpu9-MVs.mjs.map +0 -1
  1129. package/dist/bylines-CJ5nd6Lw.mjs +0 -232
  1130. package/dist/bylines-CJ5nd6Lw.mjs.map +0 -1
  1131. package/dist/bylines-RwBAeOF1.mjs +0 -214
  1132. package/dist/bylines-RwBAeOF1.mjs.map +0 -1
  1133. package/dist/cache-BF5Kvn59.mjs +0 -108
  1134. package/dist/cache-BF5Kvn59.mjs.map +0 -1
  1135. package/dist/capture-triggers-CNW1q3HK.mjs +0 -362
  1136. package/dist/capture-triggers-CNW1q3HK.mjs.map +0 -1
  1137. package/dist/challenge-store-DQN_Yrck.mjs +0 -51
  1138. package/dist/challenge-store-DQN_Yrck.mjs.map +0 -1
  1139. package/dist/chrome-tags-D8fiZG94.mjs +0 -24
  1140. package/dist/chrome-tags-D8fiZG94.mjs.map +0 -1
  1141. package/dist/chunks-C4szrD8o.mjs +0 -25
  1142. package/dist/chunks-C4szrD8o.mjs.map +0 -1
  1143. package/dist/collection-deletion-Bj07NHbj.mjs +0 -436
  1144. package/dist/collection-deletion-Bj07NHbj.mjs.map +0 -1
  1145. package/dist/comment-reaction-BhrvSHml.mjs +0 -85
  1146. package/dist/comment-reaction-BhrvSHml.mjs.map +0 -1
  1147. package/dist/comment-vxOzWbZN.mjs +0 -255
  1148. package/dist/comment-vxOzWbZN.mjs.map +0 -1
  1149. package/dist/comments-Ct4ensnf.mjs +0 -204
  1150. package/dist/comments-Ct4ensnf.mjs.map +0 -1
  1151. package/dist/components-DJbo1z0S.mjs +0 -108
  1152. package/dist/components-DJbo1z0S.mjs.map +0 -1
  1153. package/dist/config-B9eZ340f.d.mts +0 -34
  1154. package/dist/config-B9eZ340f.d.mts.map +0 -1
  1155. package/dist/config-C3EBstHi.mjs +0 -72
  1156. package/dist/config-C3EBstHi.mjs.map +0 -1
  1157. package/dist/config-it29yDLA.mjs +0 -1163
  1158. package/dist/config-it29yDLA.mjs.map +0 -1
  1159. package/dist/content-DjvM0T92.mjs +0 -1725
  1160. package/dist/content-DjvM0T92.mjs.map +0 -1
  1161. package/dist/content-list-query-Btqd4uV2.d.mts +0 -26
  1162. package/dist/content-list-query-Btqd4uV2.d.mts.map +0 -1
  1163. package/dist/content-refresh-Bwp-8yGy.mjs +0 -3588
  1164. package/dist/content-refresh-Bwp-8yGy.mjs.map +0 -1
  1165. package/dist/content-repair-Czdp7jz5.mjs +0 -440
  1166. package/dist/content-repair-Czdp7jz5.mjs.map +0 -1
  1167. package/dist/context-CX6gxOLW.mjs +0 -1068
  1168. package/dist/context-CX6gxOLW.mjs.map +0 -1
  1169. package/dist/cron-C6o7VppJ.mjs +0 -277
  1170. package/dist/cron-C6o7VppJ.mjs.map +0 -1
  1171. package/dist/dashboard-C2kTeeRI.mjs +0 -140
  1172. package/dist/dashboard-C2kTeeRI.mjs.map +0 -1
  1173. package/dist/db-errors-Cl-sKYTm.mjs +0 -55
  1174. package/dist/db-errors-Cl-sKYTm.mjs.map +0 -1
  1175. package/dist/default-Clra32mw.mjs +0 -81
  1176. package/dist/default-Clra32mw.mjs.map +0 -1
  1177. package/dist/deferred-tasks-CvDETTJO.d.mts +0 -9
  1178. package/dist/deferred-tasks-CvDETTJO.d.mts.map +0 -1
  1179. package/dist/dev-typegen-DzOPfsNj.mjs +0 -29
  1180. package/dist/dev-typegen-DzOPfsNj.mjs.map +0 -1
  1181. package/dist/device-flow-D2oCWvLJ.mjs +0 -466
  1182. package/dist/device-flow-D2oCWvLJ.mjs.map +0 -1
  1183. package/dist/dialect-helpers-BSbfaO3F.mjs +0 -202
  1184. package/dist/dialect-helpers-BSbfaO3F.mjs.map +0 -1
  1185. package/dist/direct-executor-Bfa5_ToE.mjs +0 -85
  1186. package/dist/direct-executor-Bfa5_ToE.mjs.map +0 -1
  1187. package/dist/dist-89xCrGqi.mjs +0 -810
  1188. package/dist/dist-89xCrGqi.mjs.map +0 -1
  1189. package/dist/email-console-Dzb6uGYa.mjs +0 -50
  1190. package/dist/email-console-Dzb6uGYa.mjs.map +0 -1
  1191. package/dist/enrich-BX0IDp4z.mjs +0 -194
  1192. package/dist/enrich-BX0IDp4z.mjs.map +0 -1
  1193. package/dist/error-DFrQjppn.mjs +0 -90
  1194. package/dist/error-DFrQjppn.mjs.map +0 -1
  1195. package/dist/errors-DsVoDUjJ.mjs +0 -427
  1196. package/dist/errors-DsVoDUjJ.mjs.map +0 -1
  1197. package/dist/escape-HmHTC1Is.mjs +0 -9
  1198. package/dist/escape-HmHTC1Is.mjs.map +0 -1
  1199. package/dist/field-defs-cache-BM4SIRqH.mjs +0 -77
  1200. package/dist/field-defs-cache-BM4SIRqH.mjs.map +0 -1
  1201. package/dist/focal-point-BeWFo6Xx.mjs +0 -23
  1202. package/dist/focal-point-BeWFo6Xx.mjs.map +0 -1
  1203. package/dist/fts-manager-Do1BlW2r.mjs +0 -413
  1204. package/dist/fts-manager-Do1BlW2r.mjs.map +0 -1
  1205. package/dist/hash-3JJPlHF2.mjs +0 -37
  1206. package/dist/hash-3JJPlHF2.mjs.map +0 -1
  1207. package/dist/hook-result-DCh2WUpe.d.mts +0 -31
  1208. package/dist/hook-result-DCh2WUpe.d.mts.map +0 -1
  1209. package/dist/hreflang-B6hbAuuO.d.mts +0 -48
  1210. package/dist/hreflang-B6hbAuuO.d.mts.map +0 -1
  1211. package/dist/hreflang-DQbPZliA.mjs +0 -102
  1212. package/dist/hreflang-DQbPZliA.mjs.map +0 -1
  1213. package/dist/identity-DksvEazf.mjs +0 -35
  1214. package/dist/identity-DksvEazf.mjs.map +0 -1
  1215. package/dist/import-CJpaBBBT.mjs +0 -2020
  1216. package/dist/import-CJpaBBBT.mjs.map +0 -1
  1217. package/dist/index-BJNMCWmu.d.mts +0 -6562
  1218. package/dist/index-BJNMCWmu.d.mts.map +0 -1
  1219. package/dist/index-Du8K7bWa.d.mts +0 -278
  1220. package/dist/index-Du8K7bWa.d.mts.map +0 -1
  1221. package/dist/init-lock-DJkX6Hto.mjs +0 -56
  1222. package/dist/init-lock-DJkX6Hto.mjs.map +0 -1
  1223. package/dist/load-CawHjTOH.mjs +0 -28
  1224. package/dist/load-CawHjTOH.mjs.map +0 -1
  1225. package/dist/loader-Z8vl7zTq.mjs +0 -966
  1226. package/dist/loader-Z8vl7zTq.mjs.map +0 -1
  1227. package/dist/manifest-builder-COtzuca2.mjs +0 -189
  1228. package/dist/manifest-builder-COtzuca2.mjs.map +0 -1
  1229. package/dist/manifest-schema-BNWwR8Vd.mjs +0 -301
  1230. package/dist/manifest-schema-BNWwR8Vd.mjs.map +0 -1
  1231. package/dist/media-BBm8Wg3f.mjs +0 -318
  1232. package/dist/media-BBm8Wg3f.mjs.map +0 -1
  1233. package/dist/media-BHjus86Y.mjs +0 -464
  1234. package/dist/media-BHjus86Y.mjs.map +0 -1
  1235. package/dist/media-allowlist-CoTBWoDp.mjs +0 -44
  1236. package/dist/media-allowlist-CoTBWoDp.mjs.map +0 -1
  1237. package/dist/media-folders-BGkATs8n.mjs +0 -210
  1238. package/dist/media-folders-BGkATs8n.mjs.map +0 -1
  1239. package/dist/media-upload-BCidR-EY.mjs +0 -147
  1240. package/dist/media-upload-BCidR-EY.mjs.map +0 -1
  1241. package/dist/media-url-DHoPr0hq.mjs +0 -26
  1242. package/dist/media-url-DHoPr0hq.mjs.map +0 -1
  1243. package/dist/media-usage-CdY5jhSR.mjs +0 -1833
  1244. package/dist/media-usage-CdY5jhSR.mjs.map +0 -1
  1245. package/dist/media-usage-activation-BgeMtK5C.mjs +0 -78
  1246. package/dist/media-usage-activation-BgeMtK5C.mjs.map +0 -1
  1247. package/dist/media-usage-work-CnGCdHxx.mjs +0 -152
  1248. package/dist/media-usage-work-CnGCdHxx.mjs.map +0 -1
  1249. package/dist/media-usage-work-D6D9sMCA.mjs +0 -586
  1250. package/dist/media-usage-work-D6D9sMCA.mjs.map +0 -1
  1251. package/dist/media-usage-write-fence-hjeD4u7s.mjs +0 -42
  1252. package/dist/media-usage-write-fence-hjeD4u7s.mjs.map +0 -1
  1253. package/dist/menus-6qSwTNxG.mjs +0 -4010
  1254. package/dist/menus-6qSwTNxG.mjs.map +0 -1
  1255. package/dist/menus-uvPLXMZf.mjs +0 -744
  1256. package/dist/menus-uvPLXMZf.mjs.map +0 -1
  1257. package/dist/mime-CUIG6x84.mjs +0 -36
  1258. package/dist/mime-CUIG6x84.mjs.map +0 -1
  1259. package/dist/mode-DN_WneRx.mjs +0 -23
  1260. package/dist/mode-DN_WneRx.mjs.map +0 -1
  1261. package/dist/node-sqlite-compat-BuJXIeMz.mjs +0 -46
  1262. package/dist/node-sqlite-compat-BuJXIeMz.mjs.map +0 -1
  1263. package/dist/normalize-C2xNjTSG.mjs +0 -191
  1264. package/dist/normalize-C2xNjTSG.mjs.map +0 -1
  1265. package/dist/oauth-authorization-Dj6Kwc21.mjs +0 -274
  1266. package/dist/oauth-authorization-Dj6Kwc21.mjs.map +0 -1
  1267. package/dist/oauth-clients-FD7I0J8m.mjs +0 -266
  1268. package/dist/oauth-clients-FD7I0J8m.mjs.map +0 -1
  1269. package/dist/oauth-state-store-DkmDOmHs.mjs +0 -50
  1270. package/dist/oauth-state-store-DkmDOmHs.mjs.map +0 -1
  1271. package/dist/oauth-user-lookup-CvIwGpYd.mjs +0 -26
  1272. package/dist/oauth-user-lookup-CvIwGpYd.mjs.map +0 -1
  1273. package/dist/object-cache-DVKnyOfy.mjs +0 -534
  1274. package/dist/object-cache-DVKnyOfy.mjs.map +0 -1
  1275. package/dist/options-BHPeIbBd.mjs +0 -117
  1276. package/dist/options-BHPeIbBd.mjs.map +0 -1
  1277. package/dist/options-CYb4y7hM.d.mts +0 -221
  1278. package/dist/options-CYb4y7hM.d.mts.map +0 -1
  1279. package/dist/parse-Ckpg-Qfp.mjs +0 -81
  1280. package/dist/parse-Ckpg-Qfp.mjs.map +0 -1
  1281. package/dist/passkey-config-O_lj3y0k.mjs +0 -46
  1282. package/dist/passkey-config-O_lj3y0k.mjs.map +0 -1
  1283. package/dist/patterns-D9iDO3j8.mjs +0 -145
  1284. package/dist/patterns-D9iDO3j8.mjs.map +0 -1
  1285. package/dist/placeholder-4X9BrRrp.d.mts +0 -306
  1286. package/dist/placeholder-4X9BrRrp.d.mts.map +0 -1
  1287. package/dist/policy-Dhtwntrt.mjs +0 -45
  1288. package/dist/policy-Dhtwntrt.mjs.map +0 -1
  1289. package/dist/portable-text-U85hOafW.mjs +0 -286
  1290. package/dist/portable-text-U85hOafW.mjs.map +0 -1
  1291. package/dist/preview-B_vJLvf8.mjs +0 -107
  1292. package/dist/preview-B_vJLvf8.mjs.map +0 -1
  1293. package/dist/protocol-JdD2YhY9.d.mts +0 -52
  1294. package/dist/protocol-JdD2YhY9.d.mts.map +0 -1
  1295. package/dist/public-url-CarhZJgf.mjs +0 -101
  1296. package/dist/public-url-CarhZJgf.mjs.map +0 -1
  1297. package/dist/query-BZKZcG5b.mjs +0 -881
  1298. package/dist/query-BZKZcG5b.mjs.map +0 -1
  1299. package/dist/query-BndaFxxp.mjs +0 -41
  1300. package/dist/query-BndaFxxp.mjs.map +0 -1
  1301. package/dist/rate-limit-BZmATC6W.mjs +0 -120
  1302. package/dist/rate-limit-BZmATC6W.mjs.map +0 -1
  1303. package/dist/redirect-CZkbozu9.mjs +0 -313
  1304. package/dist/redirect-CZkbozu9.mjs.map +0 -1
  1305. package/dist/redirect-CzqnLxK-.mjs +0 -17
  1306. package/dist/redirect-CzqnLxK-.mjs.map +0 -1
  1307. package/dist/redirects-BLNOWQTn.mjs +0 -1238
  1308. package/dist/redirects-BLNOWQTn.mjs.map +0 -1
  1309. package/dist/redirects-CqzNM0KM.mjs +0 -579
  1310. package/dist/redirects-CqzNM0KM.mjs.map +0 -1
  1311. package/dist/registry-AZAsRsor.mjs +0 -1179
  1312. package/dist/registry-AZAsRsor.mjs.map +0 -1
  1313. package/dist/relation-04DfKRTO.mjs +0 -334
  1314. package/dist/relation-04DfKRTO.mjs.map +0 -1
  1315. package/dist/relations-C4htk5sb.mjs +0 -309
  1316. package/dist/relations-C4htk5sb.mjs.map +0 -1
  1317. package/dist/relations-CcFwDJdJ.mjs +0 -403
  1318. package/dist/relations-CcFwDJdJ.mjs.map +0 -1
  1319. package/dist/relations-DnRK4YIT.d.mts +0 -3354
  1320. package/dist/relations-DnRK4YIT.d.mts.map +0 -1
  1321. package/dist/request-cache-DH9zdCOD.mjs +0 -104
  1322. package/dist/request-cache-DH9zdCOD.mjs.map +0 -1
  1323. package/dist/request-meta-DYxLlnmz.mjs +0 -140
  1324. package/dist/request-meta-DYxLlnmz.mjs.map +0 -1
  1325. package/dist/resolve-prZ3mP7l.mjs +0 -143
  1326. package/dist/resolve-prZ3mP7l.mjs.map +0 -1
  1327. package/dist/runner-BLIDKpmA.mjs +0 -4676
  1328. package/dist/runner-BLIDKpmA.mjs.map +0 -1
  1329. package/dist/runner-YKfIMnaF.d.mts +0 -67
  1330. package/dist/runner-YKfIMnaF.d.mts.map +0 -1
  1331. package/dist/schema-CGnBeLiW.mjs +0 -9
  1332. package/dist/schema-CGnBeLiW.mjs.map +0 -1
  1333. package/dist/schema-DYr-Vd-L.mjs +0 -420
  1334. package/dist/schema-DYr-Vd-L.mjs.map +0 -1
  1335. package/dist/scopes-BhWvBavj.mjs +0 -27
  1336. package/dist/scopes-BhWvBavj.mjs.map +0 -1
  1337. package/dist/search-C-qDk4kx.mjs +0 -439
  1338. package/dist/search-C-qDk4kx.mjs.map +0 -1
  1339. package/dist/secrets-rEtHt-6z.mjs +0 -330
  1340. package/dist/secrets-rEtHt-6z.mjs.map +0 -1
  1341. package/dist/sections-B_nYvlwn.mjs +0 -346
  1342. package/dist/sections-B_nYvlwn.mjs.map +0 -1
  1343. package/dist/seo-926NRIgt.mjs +0 -133
  1344. package/dist/seo-926NRIgt.mjs.map +0 -1
  1345. package/dist/seo-CVWkdv6x.mjs +0 -113
  1346. package/dist/seo-CVWkdv6x.mjs.map +0 -1
  1347. package/dist/service-CJl3ZAYs.mjs +0 -195
  1348. package/dist/service-CJl3ZAYs.mjs.map +0 -1
  1349. package/dist/session-user-BlMgqCHS.mjs +0 -51
  1350. package/dist/session-user-BlMgqCHS.mjs.map +0 -1
  1351. package/dist/settings--wobrkkC.mjs +0 -258
  1352. package/dist/settings--wobrkkC.mjs.map +0 -1
  1353. package/dist/settings-Cwm6o2jY.mjs +0 -51
  1354. package/dist/settings-Cwm6o2jY.mjs.map +0 -1
  1355. package/dist/setup-complete-DQbClIN2.mjs +0 -26
  1356. package/dist/setup-complete-DQbClIN2.mjs.map +0 -1
  1357. package/dist/setup-nonce-DZCFS2sn.mjs +0 -25
  1358. package/dist/setup-nonce-DZCFS2sn.mjs.map +0 -1
  1359. package/dist/single-flight-cache-BPuGPdcN.mjs +0 -104
  1360. package/dist/single-flight-cache-BPuGPdcN.mjs.map +0 -1
  1361. package/dist/site-url-BrxA_E9H.mjs +0 -16
  1362. package/dist/site-url-BrxA_E9H.mjs.map +0 -1
  1363. package/dist/slugify-B994zkXC.mjs +0 -17
  1364. package/dist/slugify-B994zkXC.mjs.map +0 -1
  1365. package/dist/snapshot--OCDTqdb.mjs +0 -216
  1366. package/dist/snapshot--OCDTqdb.mjs.map +0 -1
  1367. package/dist/ssrf-5sIM5jzl.mjs +0 -349
  1368. package/dist/ssrf-5sIM5jzl.mjs.map +0 -1
  1369. package/dist/state-BpFVsJZB.mjs +0 -136
  1370. package/dist/state-BpFVsJZB.mjs.map +0 -1
  1371. package/dist/status-B777-dXz.mjs +0 -30
  1372. package/dist/status-B777-dXz.mjs.map +0 -1
  1373. package/dist/target-BmR0iTwz.mjs +0 -27
  1374. package/dist/target-BmR0iTwz.mjs.map +0 -1
  1375. package/dist/taxonomies-DkAkMupr.mjs +0 -837
  1376. package/dist/taxonomies-DkAkMupr.mjs.map +0 -1
  1377. package/dist/taxonomies-Wfy_Lg12.mjs +0 -698
  1378. package/dist/taxonomies-Wfy_Lg12.mjs.map +0 -1
  1379. package/dist/taxonomy-tJepplLL.mjs +0 -484
  1380. package/dist/taxonomy-tJepplLL.mjs.map +0 -1
  1381. package/dist/tokens-BCO1oruF.mjs +0 -171
  1382. package/dist/tokens-BCO1oruF.mjs.map +0 -1
  1383. package/dist/transaction-0KOpOyMu.mjs +0 -29
  1384. package/dist/transaction-0KOpOyMu.mjs.map +0 -1
  1385. package/dist/transport-Dr3qtwXC.mjs +0 -136
  1386. package/dist/transport-Dr3qtwXC.mjs.map +0 -1
  1387. package/dist/transport-xh6YKW2G.d.mts +0 -42
  1388. package/dist/transport-xh6YKW2G.d.mts.map +0 -1
  1389. package/dist/trusted-proxy-BR5F1Otp.mjs +0 -51
  1390. package/dist/trusted-proxy-BR5F1Otp.mjs.map +0 -1
  1391. package/dist/types-3qNFPlci.mjs +0 -16
  1392. package/dist/types-3qNFPlci.mjs.map +0 -1
  1393. package/dist/types-75KIqzL9.mjs +0 -142
  1394. package/dist/types-75KIqzL9.mjs.map +0 -1
  1395. package/dist/types-B6GrPic4.d.mts +0 -1335
  1396. package/dist/types-B6GrPic4.d.mts.map +0 -1
  1397. package/dist/types-BuHW4xDE.d.mts +0 -259
  1398. package/dist/types-BuHW4xDE.d.mts.map +0 -1
  1399. package/dist/types-C00oyCZp.d.mts +0 -198
  1400. package/dist/types-C00oyCZp.d.mts.map +0 -1
  1401. package/dist/types-CDtkNSFQ.d.mts +0 -75
  1402. package/dist/types-CDtkNSFQ.d.mts.map +0 -1
  1403. package/dist/types-CPeXo1wF.d.mts +0 -124
  1404. package/dist/types-CPeXo1wF.d.mts.map +0 -1
  1405. package/dist/types-CQPWhPxE.mjs +0 -92
  1406. package/dist/types-CQPWhPxE.mjs.map +0 -1
  1407. package/dist/types-CXFkwEGC.d.mts +0 -198
  1408. package/dist/types-CXFkwEGC.d.mts.map +0 -1
  1409. package/dist/types-DM3vioBY.mjs +0 -18
  1410. package/dist/types-DM3vioBY.mjs.map +0 -1
  1411. package/dist/types-DczELMop.d.mts +0 -363
  1412. package/dist/types-DczELMop.d.mts.map +0 -1
  1413. package/dist/types-DfuTR6dL.mjs +0 -3
  1414. package/dist/types-FV23hEoW.d.mts +0 -743
  1415. package/dist/types-FV23hEoW.d.mts.map +0 -1
  1416. package/dist/types-xDMtUFnO.d.mts +0 -257
  1417. package/dist/types-xDMtUFnO.d.mts.map +0 -1
  1418. package/dist/upload-attempts-BsqoQ1fn.mjs +0 -27
  1419. package/dist/upload-attempts-BsqoQ1fn.mjs.map +0 -1
  1420. package/dist/url-pattern-D4c2czpJ.mjs +0 -33
  1421. package/dist/url-pattern-D4c2czpJ.mjs.map +0 -1
  1422. package/dist/user-BTZ40aq6.mjs +0 -171
  1423. package/dist/user-BTZ40aq6.mjs.map +0 -1
  1424. package/dist/utils-BKvNjjhY.mjs +0 -435
  1425. package/dist/utils-BKvNjjhY.mjs.map +0 -1
  1426. package/dist/validate-BpwoDOgt.mjs +0 -120
  1427. package/dist/validate-BpwoDOgt.mjs.map +0 -1
  1428. package/dist/validate-DE_LRwo9.mjs +0 -379
  1429. package/dist/validate-DE_LRwo9.mjs.map +0 -1
  1430. package/dist/validate-DUP27OYD.d.mts +0 -400
  1431. package/dist/validate-DUP27OYD.d.mts.map +0 -1
  1432. package/dist/validation-BMImFJ11.mjs +0 -153
  1433. package/dist/validation-BMImFJ11.mjs.map +0 -1
  1434. package/dist/version-Bii3suaO.mjs +0 -7
  1435. package/dist/version-Bii3suaO.mjs.map +0 -1
  1436. package/dist/widgets-D3gJ10xU.mjs +0 -122
  1437. package/dist/widgets-D3gJ10xU.mjs.map +0 -1
  1438. package/dist/wxr-taxonomies-B2Og_6rU.d.mts +0 -34
  1439. package/dist/wxr-taxonomies-B2Og_6rU.d.mts.map +0 -1
  1440. package/dist/wxr-taxonomies-Cxngsjwo.mjs +0 -406
  1441. package/dist/wxr-taxonomies-Cxngsjwo.mjs.map +0 -1
  1442. package/dist/zod-generator-BuYSQJB7.mjs +0 -331
  1443. package/dist/zod-generator-BuYSQJB7.mjs.map +0 -1
  1444. /package/dist/{api-tokens-BfYts-sq.mjs → api-tokens-DS1VzN7_.mjs} +0 -0
  1445. /package/dist/{ssrf-Dg3cIT-b.mjs → ssrf-BRpTDMV6.mjs} +0 -0
@@ -0,0 +1,4831 @@
1
+ import { n as isMissingTableError, t as isMissingColumnError } from "./db-errors-CBD5yMro.mjs";
2
+ import { i as validateStorageCollectionName, n as validateJsonFieldName, r as validatePluginIdentifier, t as validateIdentifier } from "./validate-DANX1-Qi.mjs";
3
+ import { d as jsonExtractExpr, l as isPostgres, u as isSqlite } from "./dialect-helpers-CtYdsX4W.mjs";
4
+ import { a as resolveConfiguredLocale, i as isI18nEnabled, r as getI18nConfig } from "./config-CGVeT8Hc.mjs";
5
+ import { t as after } from "./after-PcEvMY_6.mjs";
6
+ import { t as OptionsRepository } from "./options-D5WcorD5.mjs";
7
+ import { i as encodeBase64, t as decodeBase64 } from "./base64-DvnNgP7e.mjs";
8
+ import { t as EmDashSecretsError } from "./secrets-DNgVgz_e.mjs";
9
+ import { i as RevisionRepository, r as isSystemOrderField, t as ContentRepository } from "./content-DZ3B5qtA.mjs";
10
+ import { a as MAX_COLLECTION_LIST_COLUMNS } from "./types-B3RkqvDW.mjs";
11
+ import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-BmWyou79.mjs";
12
+ import { a as ScheduledNotDueError, i as InvalidCursorError, n as ContentMutationConflictError, r as EmDashValidationError, t as ContentCollectionNotFoundError } from "./types-BkUg2yHx.mjs";
13
+ import { t as withTransaction } from "./transaction-BcJO4Tmc.mjs";
14
+ import { t as isValidFocalPointUpdate } from "./focal-point-Gr34o-4o.mjs";
15
+ import { t as MediaRepository } from "./media-TBlKCwo7.mjs";
16
+ import { t as UserRepository } from "./user-DroRntkx.mjs";
17
+ import { t as TaxonomyRepository } from "./taxonomy-Dj1vpw5E.mjs";
18
+ import { t as CommentRepository } from "./comment-DcT8qdPK.mjs";
19
+ import { t as RedirectRepository } from "./redirect-D2Yo-b6S.mjs";
20
+ import { r as requestCached } from "./request-cache-DaMhSQdx.mjs";
21
+ import { t as BylineRepository } from "./byline-Doh-wt99.mjs";
22
+ import { r as parseAllowedMimeTypes, t as matchesMimeAllowlist } from "./mime-CCYRC4r1.mjs";
23
+ import { t as EntryLockRepository } from "./entry-locks-CO_KaoU5.mjs";
24
+ import { t as SeoRepository } from "./seo-_4qmazxz.mjs";
25
+ import { i as scheduledPolicyRejectionKey } from "./content-policy-CM4skrNi.mjs";
26
+ import { n as invalidateRedirectCache } from "./cache-B0pOlXdM.mjs";
27
+ import { t as FTSManager } from "./fts-manager-DMb0sbIQ.mjs";
28
+ import { d as invalidateTermCache } from "./taxonomies-BpqpXJUE.mjs";
29
+ import { n as SchemaRegistry } from "./registry-CkuPoZs7.mjs";
30
+ import { r as hashString } from "./hash-CLVFzWvx.mjs";
31
+ import { t as ErrorCode } from "./errors-W3PA8HqB.mjs";
32
+ import { t as PluginStateRepository } from "./state-C7gCoiHr.mjs";
33
+ import { f as encodePluginSettingValue, l as PluginSettingEncryptionError } from "./settings-DmroR53o.mjs";
34
+ import { i as normalizeManifestRoute$1, o as pluginManifestSchema$1, s as reconcileManifestAccess$1 } from "./manifest-schema-Bkh8SeHd.mjs";
35
+ import { o as withUnavailableReason } from "./types-ZCnlropY.mjs";
36
+ import { a as normalizeCapabilities } from "./types-k--LneIF.mjs";
37
+ import { t as EmDashStorageError } from "./types-BtuppOTV.mjs";
38
+ import { i as verificationError, r as verifyMultihash, t as computeArtifactDigestCandidates } from "./checksum-Bsi2D9M1.mjs";
39
+ import { n as fetchReleaseArtifact, t as fetchRegistryArtifactUrl } from "./artifact-fetch-COiMhVgk.mjs";
40
+ import { i as resolveAndValidateExternalUrlTarget } from "./ssrf-Co1GGFZz.mjs";
41
+ import { r as verifyAuthoritativePackageRelease, t as readAuthoritativePackageRelease } from "./authoritative-records-DbqshfKD.mjs";
42
+ import { a as parseDurationSeconds, l as validateAggregatorUrl, n as coerceRegistryConfig, o as releaseExemptFromMinimumAge, t as canonicalCapabilitiesForDriftCheck } from "./config-B2acLeC5.mjs";
43
+ import { sql } from "kysely";
44
+ import { canonicalizeDeclaredAccess, pluginManifestSchema, reconcileManifestAccess } from "@emdash-cms/plugin-types";
45
+ import { createGzipDecoder, unpackTar } from "modern-tar";
46
+ import { ClientResponseError, ClientValidationError } from "@atcute/client";
47
+ import { checkEnvCompatibility, findSkippedEnvConstraints } from "@emdash-cms/registry-client/env";
48
+ import { isProvenFirstRelease } from "@emdash-cms/registry-client/listing-policy";
49
+ import { evaluateRegistryReleaseWithdrawal } from "@emdash-cms/registry-client/withdrawal";
50
+ import { NSID } from "@emdash-cms/registry-lexicons";
51
+
52
+ //#region src/api/rev.ts
53
+ /**
54
+ * Generate a _rev token from a content item's version and updatedAt.
55
+ */
56
+ function encodeRev(item) {
57
+ return encodeBase64(`${item.version}:${item.updatedAt}`);
58
+ }
59
+ /**
60
+ * Decode a _rev token into its components.
61
+ * Returns null if the token is malformed.
62
+ */
63
+ function decodeRev(rev) {
64
+ try {
65
+ const decoded = decodeBase64(rev);
66
+ const colonIdx = decoded.indexOf(":");
67
+ if (colonIdx === -1) return null;
68
+ const version = parseInt(decoded.slice(0, colonIdx), 10);
69
+ const updatedAt = decoded.slice(colonIdx + 1);
70
+ if (isNaN(version) || !updatedAt) return null;
71
+ return {
72
+ version,
73
+ updatedAt
74
+ };
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
79
+ /**
80
+ * Validate a _rev token against a content item.
81
+ * Returns null if valid (or if no _rev provided), or an error message if invalid.
82
+ */
83
+ function validateRev(rev, item) {
84
+ if (!rev) return { valid: true };
85
+ const decoded = decodeRev(rev);
86
+ if (!decoded) return {
87
+ valid: false,
88
+ message: "Malformed _rev token"
89
+ };
90
+ if (decoded.version !== item.version || decoded.updatedAt !== item.updatedAt) return {
91
+ valid: false,
92
+ message: "Content has been modified since last read (version conflict)"
93
+ };
94
+ return { valid: true };
95
+ }
96
+
97
+ //#endregion
98
+ //#region src/api/handlers/validate-media-fields.ts
99
+ function asMediaRef(value) {
100
+ if (value === null || value === void 0) return null;
101
+ if (typeof value !== "object" || Array.isArray(value)) return null;
102
+ return value;
103
+ }
104
+ function fail(message) {
105
+ return {
106
+ success: false,
107
+ error: {
108
+ code: "INVALID_MIME_FOR_FIELD",
109
+ message
110
+ }
111
+ };
112
+ }
113
+ async function loadMediaFieldsForCollection(db, collectionSlug) {
114
+ const rows = await db.selectFrom("_emdash_fields").innerJoin("_emdash_collections", "_emdash_collections.id", "_emdash_fields.collection_id").select([
115
+ "_emdash_fields.slug",
116
+ "_emdash_fields.type",
117
+ "_emdash_fields.validation"
118
+ ]).where("_emdash_collections.slug", "=", collectionSlug).where("_emdash_fields.type", "in", ["file", "image"]).execute();
119
+ const out = [];
120
+ for (const row of rows) {
121
+ const list = parseAllowedMimeTypes(row.validation);
122
+ if (!list) continue;
123
+ out.push({
124
+ slug: row.slug,
125
+ type: row.type,
126
+ allowedMimeTypes: list
127
+ });
128
+ }
129
+ return out;
130
+ }
131
+ async function validateMediaFields(db, collectionSlug, data) {
132
+ const fields = await requestCached(`mediaFields:${collectionSlug}`, () => loadMediaFieldsForCollection(db, collectionSlug));
133
+ if (fields.length === 0) return {
134
+ success: true,
135
+ data: true
136
+ };
137
+ const localIds = /* @__PURE__ */ new Set();
138
+ for (const field of fields) {
139
+ const ref = asMediaRef(data[field.slug]);
140
+ if (!ref) continue;
141
+ if ((typeof ref.provider === "string" ? ref.provider : "local") === "local" && typeof ref.id === "string") localIds.add(ref.id);
142
+ }
143
+ const idList = [...localIds];
144
+ const mimeById = /* @__PURE__ */ new Map();
145
+ if (idList.length > 0) for (const batch of chunks(idList, SQL_BATCH_SIZE)) {
146
+ const rows = await db.selectFrom("media").select(["id", "mime_type"]).where("id", "in", batch).execute();
147
+ for (const r of rows) mimeById.set(r.id, r.mime_type);
148
+ }
149
+ for (const field of fields) {
150
+ const value = data[field.slug];
151
+ if (value === null || value === void 0) continue;
152
+ const ref = asMediaRef(value);
153
+ if (!ref) continue;
154
+ const provider = typeof ref.provider === "string" ? ref.provider : "local";
155
+ let mime;
156
+ if (provider === "local") {
157
+ if (typeof ref.id !== "string") return fail(`Field '${field.slug}' references media with an invalid id`);
158
+ mime = mimeById.get(ref.id);
159
+ if (!mime) return fail(`Field '${field.slug}' references media with unknown MIME type`);
160
+ } else {
161
+ if (typeof ref.mimeType !== "string") return fail(`Field '${field.slug}' requires a mimeType declaration for non-local media`);
162
+ mime = ref.mimeType;
163
+ }
164
+ if (!matchesMimeAllowlist(mime, field.allowedMimeTypes)) return fail(`Field '${field.slug}' does not accept ${mime}`);
165
+ }
166
+ return {
167
+ success: true,
168
+ data: true
169
+ };
170
+ }
171
+
172
+ //#endregion
173
+ //#region src/api/handlers/content.ts
174
+ /**
175
+ * Narrow a caught error to one carrying a structured `apiError` discriminant.
176
+ * Used by transaction callbacks that want to surface a specific error code
177
+ * through the standard Error throwing path.
178
+ */
179
+ function hasApiError(error) {
180
+ if (!(error instanceof Error) || !("apiError" in error)) return false;
181
+ const { apiError } = error;
182
+ return typeof apiError === "object" && apiError !== null && "code" in apiError && typeof apiError.code === "string";
183
+ }
184
+ function isTranslationLocaleConflict(error, collection) {
185
+ if (!(error instanceof Error)) return false;
186
+ const message = error.message.toLowerCase();
187
+ const storedIndexName = `uidx_ec_${collection}_active_tg_locale`.slice(0, 63).toLowerCase();
188
+ return message.includes(storedIndexName) || message.includes("unique constraint failed") && message.includes("translation_group") && message.includes("locale");
189
+ }
190
+ function decodeRevisionPrecondition(rev) {
191
+ if (rev === void 0) return void 0;
192
+ const decoded = decodeRev(rev);
193
+ if (!decoded) throw new ContentMutationConflictError("Revision precondition did not match");
194
+ return decoded;
195
+ }
196
+ /**
197
+ * Extract a slug source (title or name) from content data.
198
+ * Returns null if no suitable string field is found.
199
+ */
200
+ function getSlugSource(data) {
201
+ if (typeof data.title === "string" && data.title.length > 0) return data.title;
202
+ if (typeof data.name === "string" && data.name.length > 0) return data.name;
203
+ return null;
204
+ }
205
+ /** Default SEO values for content without an explicit SEO row */
206
+ const SEO_DEFAULTS = {
207
+ title: null,
208
+ description: null,
209
+ image: null,
210
+ canonical: null,
211
+ noIndex: false
212
+ };
213
+ /**
214
+ * Check if a collection has SEO enabled.
215
+ */
216
+ async function collectionHasSeo(db, collection) {
217
+ return (await db.selectFrom("_emdash_collections").select("has_seo").where("slug", "=", collection).executeTakeFirst())?.has_seo === 1;
218
+ }
219
+ async function getCollectionPublishConfig(db, collection) {
220
+ const row = await db.selectFrom("_emdash_collections").select(["supports", "routable"]).where("slug", "=", collection).executeTakeFirst();
221
+ const supports = row?.supports ? JSON.parse(row.supports) : [];
222
+ return {
223
+ supportsRevisions: Array.isArray(supports) && supports.includes("revisions"),
224
+ routable: row?.routable !== 0
225
+ };
226
+ }
227
+ function requireRoutablePublishSlug(routable, slug) {
228
+ if (routable && !slug?.trim()) throw new EmDashValidationError("Cannot publish routable content without a slug");
229
+ }
230
+ /**
231
+ * Hydrate SEO data on a single content item if the collection has SEO enabled.
232
+ */
233
+ async function hydrateSeo(db, collection, item, hasSeo) {
234
+ if (!hasSeo) return;
235
+ item.seo = await new SeoRepository(db).get(collection, item.id);
236
+ }
237
+ /**
238
+ * Hydrate SEO data on multiple content items using a single batch query.
239
+ */
240
+ async function hydrateSeoMany(db, collection, items, hasSeo) {
241
+ if (!hasSeo || items.length === 0) return;
242
+ const seoMap = await new SeoRepository(db).getMany(collection, items.map((i) => i.id));
243
+ for (const item of items) item.seo = seoMap.get(item.id) ?? { ...SEO_DEFAULTS };
244
+ }
245
+ async function hydrateBylines(db, collection, item) {
246
+ const bylineRepo = new BylineRepository(db);
247
+ const localeOpt = item.locale ? { locale: item.locale } : void 0;
248
+ const bylines = await bylineRepo.getContentBylines(collection, item.id, localeOpt);
249
+ if (bylines.length > 0) {
250
+ item.bylines = bylines.map((c) => ({
251
+ ...c,
252
+ source: "explicit"
253
+ }));
254
+ item.byline = bylines[0]?.byline ?? null;
255
+ return;
256
+ }
257
+ if (item.primaryBylineId) {
258
+ item.bylines = [];
259
+ item.byline = null;
260
+ return;
261
+ }
262
+ if (item.authorId) {
263
+ const fallback = await bylineRepo.findByUserId(item.authorId, localeOpt);
264
+ if (fallback) {
265
+ item.bylines = [{
266
+ byline: fallback,
267
+ sortOrder: 0,
268
+ roleLabel: null,
269
+ source: "inferred"
270
+ }];
271
+ item.byline = fallback;
272
+ return;
273
+ }
274
+ }
275
+ item.bylines = [];
276
+ item.byline = null;
277
+ }
278
+ /**
279
+ * Batch-hydrate bylines for multiple items using two bulk queries instead of N+1.
280
+ *
281
+ * Items may live at different locales (e.g. a list endpoint returning the
282
+ * translations of an entry). Group by `item.locale` and call the strict
283
+ * per-locale repo method once per group so each item resolves against its
284
+ * own locale's byline rows.
285
+ */
286
+ async function hydrateBylinesMany(db, collection, items) {
287
+ if (items.length === 0) return;
288
+ const bylineRepo = new BylineRepository(db);
289
+ const localeBuckets = /* @__PURE__ */ new Map();
290
+ for (const item of items) {
291
+ const key = item.locale ?? null;
292
+ const bucket = localeBuckets.get(key);
293
+ if (bucket) bucket.push(item);
294
+ else localeBuckets.set(key, [item]);
295
+ }
296
+ const bylinesByItem = /* @__PURE__ */ new Map();
297
+ const itemsNeedingAuthorCheck = [];
298
+ for (const [locale, bucket] of localeBuckets) {
299
+ const localeOpt = locale ? { locale } : void 0;
300
+ const ids = bucket.map((i) => i.id);
301
+ const credits = await bylineRepo.getContentBylinesMany(collection, ids, localeOpt);
302
+ for (const [id, list] of credits) bylinesByItem.set(id, list);
303
+ for (const item of bucket) {
304
+ if (credits.has(item.id) && credits.get(item.id).length > 0) continue;
305
+ if (item.authorId) itemsNeedingAuthorCheck.push(item);
306
+ }
307
+ }
308
+ const fallbackByItem = /* @__PURE__ */ new Map();
309
+ if (itemsNeedingAuthorCheck.length > 0) {
310
+ const authorBuckets = /* @__PURE__ */ new Map();
311
+ for (const item of itemsNeedingAuthorCheck) {
312
+ if (item.primaryBylineId) continue;
313
+ const key = item.locale ?? null;
314
+ const bucket = authorBuckets.get(key);
315
+ if (bucket) bucket.push(item);
316
+ else authorBuckets.set(key, [item]);
317
+ }
318
+ for (const [locale, bucket] of authorBuckets) {
319
+ const localeOpt = locale ? { locale } : void 0;
320
+ const authorIds = bucket.map((i) => i.authorId).filter((id) => id !== null);
321
+ const uniqueAuthorIds = [...new Set(authorIds)];
322
+ if (uniqueAuthorIds.length === 0) continue;
323
+ const authorMap = await bylineRepo.findByUserIds(uniqueAuthorIds, localeOpt);
324
+ for (const item of bucket) {
325
+ if (!item.authorId) continue;
326
+ const f = authorMap.get(item.authorId);
327
+ if (f) fallbackByItem.set(item.id, f);
328
+ }
329
+ }
330
+ }
331
+ for (const item of items) {
332
+ const explicit = bylinesByItem.get(item.id);
333
+ if (explicit && explicit.length > 0) {
334
+ item.bylines = explicit.map((c) => ({
335
+ ...c,
336
+ source: "explicit"
337
+ }));
338
+ item.byline = explicit[0]?.byline ?? null;
339
+ continue;
340
+ }
341
+ const fallback = fallbackByItem.get(item.id);
342
+ if (fallback) {
343
+ item.bylines = [{
344
+ byline: fallback,
345
+ sortOrder: 0,
346
+ roleLabel: null,
347
+ source: "inferred"
348
+ }];
349
+ item.byline = fallback;
350
+ continue;
351
+ }
352
+ item.bylines = [];
353
+ item.byline = null;
354
+ }
355
+ }
356
+ /**
357
+ * Resolve an identifier (ID or slug) to a real content ID.
358
+ * Returns the ID if found, null if not found.
359
+ * When locale is provided, slug lookups are scoped to that locale.
360
+ */
361
+ async function resolveId(repo, collection, identifier, locale) {
362
+ return (await repo.findByIdOrSlug(collection, identifier, locale ? resolveConfiguredLocale(locale) : void 0))?.id ?? null;
363
+ }
364
+ /**
365
+ * Resolve an identifier (ID or slug) to a real content ID,
366
+ * including trashed (soft-deleted) items.
367
+ */
368
+ async function resolveIdIncludingTrashed(repo, collection, identifier, locale) {
369
+ return (await repo.findByIdOrSlugIncludingTrashed(collection, identifier, locale ? resolveConfiguredLocale(locale) : void 0))?.id ?? null;
370
+ }
371
+ /**
372
+ * Resolve the columns a content-list search should match against. Always
373
+ * includes `slug` (a standard column), adds the configured `titleField` plus
374
+ * the `title`/`name` display fields when the collection actually defines them,
375
+ * mirroring the admin's item-title resolution (titleField -> title -> name ->
376
+ * slug), and includes every field explicitly marked searchable. Returning only
377
+ * schema-backed columns avoids "no such column" errors.
378
+ */
379
+ async function resolveSearchColumns(db, collection) {
380
+ const row = await db.selectFrom("_emdash_collections").select(["id", "title_field"]).where("slug", "=", collection).executeTakeFirst();
381
+ if (!row) return ["slug"];
382
+ const fields = await db.selectFrom("_emdash_fields").select(["slug", "searchable"]).where("collection_id", "=", row.id).orderBy("sort_order", "asc").execute();
383
+ const columns = new Set(["slug"]);
384
+ const fieldSlugs = new Set(fields.map((f) => f.slug));
385
+ if (row.title_field && fieldSlugs.has(row.title_field)) columns.add(row.title_field);
386
+ for (const candidate of ["title", "name"]) if (fieldSlugs.has(candidate)) columns.add(candidate);
387
+ for (const field of fields) if (field.searchable === 1) columns.add(field.slug);
388
+ return [...columns];
389
+ }
390
+ /**
391
+ * Decide whether the content-list `q` filter can be served from the
392
+ * collection's FTS5 index instead of a full-scan substring LIKE (#1517).
393
+ *
394
+ * Requires SQLite (FTS5 is SQLite-only), search enabled on the collection,
395
+ * every non-slug display column present in the searchable-field set (or the
396
+ * index would miss matches the LIKE finds), and the index table actually
397
+ * existing.
398
+ */
399
+ async function canUseFtsForListFilter(db, collection, searchColumns) {
400
+ if (!isSqlite(db)) return false;
401
+ const ftsManager = new FTSManager(db);
402
+ if (!(await ftsManager.getSearchConfig(collection))?.enabled) return false;
403
+ const searchable = new Set(await ftsManager.getSearchableFields(collection));
404
+ if (!searchColumns.every((col) => col === "slug" || searchable.has(col))) return false;
405
+ return ftsManager.ftsTableExists(collection);
406
+ }
407
+ /**
408
+ * Create a 301 auto-redirect from an entry's old URL to its new one after a
409
+ * slug change, using the collection's URL pattern. Shared by
410
+ * handleContentUpdate (direct slug edits) and handleContentPublish (slug edits
411
+ * staged as `_slug` in a draft revision, which only land on publish).
412
+ */
413
+ async function createSlugChangeRedirect(db, collection, oldSlug, newSlug, contentId, oldPublishedAt, newPublishedAt) {
414
+ if (await slugStillTaken(db, collection, oldSlug, contentId)) return;
415
+ const collectionRow = await db.selectFrom("_emdash_collections").select("url_pattern").where("slug", "=", collection).executeTakeFirst();
416
+ await new RedirectRepository(db).createAutoRedirect(collection, oldSlug, newSlug, contentId, collectionRow?.url_pattern ?? null, oldPublishedAt, newPublishedAt);
417
+ invalidateRedirectCache();
418
+ }
419
+ /** Whether a row other than `contentId` still holds `slug` in this collection. */
420
+ async function slugStillTaken(db, collection, slug, contentId) {
421
+ validateIdentifier(collection, "collection slug");
422
+ return (await sql`
423
+ SELECT id FROM ${sql.ref(`ec_${collection}`)}
424
+ WHERE slug = ${slug}
425
+ AND id != ${contentId}
426
+ AND deleted_at IS NULL
427
+ LIMIT 1
428
+ `.execute(db)).rows.length > 0;
429
+ }
430
+ /** Matches a date-only `YYYY-MM-DD` bound (no time component). */
431
+ const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
432
+ /**
433
+ * Normalize a date-range bound to an ISO datetime for lexicographic comparison
434
+ * against stored ISO 8601 timestamps. A bare `YYYY-MM-DD` is widened to the
435
+ * appropriate UTC day boundary so the range stays inclusive: a `start` bound
436
+ * becomes the start of the day and an `end` bound the end of the day.
437
+ * Otherwise a date-only upper bound would exclude every same-day row (since
438
+ * `2024-06-01T12:00:00Z` sorts after `2024-06-01`). Full datetimes pass
439
+ * through unchanged.
440
+ */
441
+ function normalizeDateBound(value, edge) {
442
+ if (!value) return void 0;
443
+ if (!DATE_ONLY_RE.test(value)) return new Date(value).toISOString();
444
+ return edge === "start" ? `${value}T00:00:00.000Z` : `${value}T23:59:59.999Z`;
445
+ }
446
+ /**
447
+ * Build the repository's byline filter from the wire params.
448
+ *
449
+ * `locale` is the locale the list is scoped to, which is the locale an
450
+ * inferred credit has to resolve at — the admin list is always scoped to the
451
+ * locale picked in its switcher.
452
+ */
453
+ function resolveBylineFilter(params, locale) {
454
+ const includeInferred = params.includeInferredBylines === true;
455
+ if (params.bylinesNone) return {
456
+ mode: "none",
457
+ includeInferred,
458
+ locale
459
+ };
460
+ const bylineIds = params.bylines ?? [];
461
+ if (bylineIds.length === 0) return void 0;
462
+ return {
463
+ mode: "any",
464
+ bylineIds,
465
+ includeInferred,
466
+ locale
467
+ };
468
+ }
469
+ /**
470
+ * Create content list handler
471
+ */
472
+ async function handleContentList(db, collection, params) {
473
+ try {
474
+ const repo = new ContentRepository(db);
475
+ const where = {};
476
+ if (params.status) where.status = params.status;
477
+ const locale = params.locale ? resolveConfiguredLocale(params.locale) : void 0;
478
+ if (locale) where.locale = locale;
479
+ if (params.authorId) where.authorId = params.authorId;
480
+ if (params.fieldFilters && Object.keys(params.fieldFilters).length > 0) where.fieldFilters = params.fieldFilters;
481
+ const bylineFilter = resolveBylineFilter(params, locale);
482
+ if (bylineFilter) where.bylineFilter = bylineFilter;
483
+ if (params.dateField && (params.dateFrom || params.dateTo)) where.dateFilter = {
484
+ field: params.dateField,
485
+ from: normalizeDateBound(params.dateFrom, "start"),
486
+ to: normalizeDateBound(params.dateTo, "end")
487
+ };
488
+ const q = params.q?.trim();
489
+ if (q) {
490
+ where.q = q;
491
+ where.searchColumns = await resolveSearchColumns(db, collection);
492
+ where.useFts = await canUseFtsForListFilter(db, collection, where.searchColumns);
493
+ }
494
+ let sortableExtras;
495
+ if (params.orderBy && !isSystemOrderField(params.orderBy)) {
496
+ const coll = await db.selectFrom("_emdash_collections").select(["title_field", "date_field"]).where("slug", "=", collection).executeTakeFirst();
497
+ sortableExtras = [coll?.title_field, coll?.date_field].filter((slug) => !!slug);
498
+ }
499
+ const result = await repo.findMany(collection, {
500
+ cursor: params.cursor,
501
+ limit: params.limit || 50,
502
+ where: Object.keys(where).length > 0 ? where : void 0,
503
+ orderBy: params.orderBy ? {
504
+ field: params.orderBy,
505
+ direction: params.order || "desc"
506
+ } : void 0,
507
+ sortableExtras
508
+ });
509
+ const hasSeo = await collectionHasSeo(db, collection);
510
+ await hydrateSeoMany(db, collection, result.items, hasSeo);
511
+ await hydrateBylinesMany(db, collection, result.items);
512
+ return {
513
+ success: true,
514
+ data: {
515
+ items: result.items,
516
+ nextCursor: result.nextCursor,
517
+ total: result.total
518
+ }
519
+ };
520
+ } catch (error) {
521
+ if (error instanceof InvalidCursorError) return {
522
+ success: false,
523
+ error: {
524
+ code: "INVALID_CURSOR",
525
+ message: error.message
526
+ }
527
+ };
528
+ if (error instanceof ContentCollectionNotFoundError || isMissingTableError(error)) return {
529
+ success: false,
530
+ error: {
531
+ code: "COLLECTION_NOT_FOUND",
532
+ message: `Collection '${collection}' not found`
533
+ }
534
+ };
535
+ if (isMissingColumnError(error, "deleted_at")) return {
536
+ success: false,
537
+ error: {
538
+ code: "COLLECTION_SCHEMA_MISMATCH",
539
+ message: `Collection '${collection}' backing table is missing the 'deleted_at' column`
540
+ }
541
+ };
542
+ if (error instanceof EmDashValidationError) return {
543
+ success: false,
544
+ error: {
545
+ code: "VALIDATION_ERROR",
546
+ message: error.message
547
+ }
548
+ };
549
+ console.error("Content list error:", error);
550
+ return {
551
+ success: false,
552
+ error: {
553
+ code: "CONTENT_LIST_ERROR",
554
+ message: "Failed to list content"
555
+ }
556
+ };
557
+ }
558
+ }
559
+ /**
560
+ * List the distinct authors of a collection's live content.
561
+ *
562
+ * Backs the admin content-list author filter. Unlike `/admin/users` (ADMIN
563
+ * only), this is gated on `content:read`, so any editor can filter by author.
564
+ * Returns only users who have authored at least one non-trashed entry, sorted
565
+ * by display name then email for a stable dropdown order.
566
+ */
567
+ async function handleContentAuthors(db, collection) {
568
+ try {
569
+ const authorIds = await new ContentRepository(db).findDistinctAuthorIds(collection);
570
+ if (authorIds.length === 0) return {
571
+ success: true,
572
+ data: { items: [] }
573
+ };
574
+ return {
575
+ success: true,
576
+ data: { items: (await new UserRepository(db).findByIds(authorIds)).map((u) => ({
577
+ id: u.id,
578
+ name: u.name,
579
+ email: u.email,
580
+ avatarUrl: u.avatarUrl
581
+ })).toSorted((a, b) => (a.name ?? a.email).localeCompare(b.name ?? b.email)) }
582
+ };
583
+ } catch (error) {
584
+ if (isMissingTableError(error)) return {
585
+ success: false,
586
+ error: {
587
+ code: "COLLECTION_NOT_FOUND",
588
+ message: `Collection '${collection}' not found`
589
+ }
590
+ };
591
+ console.error("Content authors error:", error);
592
+ return {
593
+ success: false,
594
+ error: {
595
+ code: "CONTENT_AUTHORS_ERROR",
596
+ message: "Failed to list content authors"
597
+ }
598
+ };
599
+ }
600
+ }
601
+ /**
602
+ * Get single content item
603
+ */
604
+ async function handleContentGet(db, collection, id, locale) {
605
+ try {
606
+ const item = await new ContentRepository(db).findByIdOrSlug(collection, id, locale ? resolveConfiguredLocale(locale) : void 0);
607
+ if (!item) return {
608
+ success: false,
609
+ error: {
610
+ code: "NOT_FOUND",
611
+ message: `Content item not found: ${id}`
612
+ }
613
+ };
614
+ await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
615
+ await hydrateBylines(db, collection, item);
616
+ return {
617
+ success: true,
618
+ data: {
619
+ item,
620
+ _rev: encodeRev(item)
621
+ }
622
+ };
623
+ } catch (error) {
624
+ console.error("Content get error:", error);
625
+ return {
626
+ success: false,
627
+ error: {
628
+ code: "CONTENT_GET_ERROR",
629
+ message: "Failed to get content"
630
+ }
631
+ };
632
+ }
633
+ }
634
+ /**
635
+ * Get a content item by id, including trashed items.
636
+ * Used by restore endpoint for ownership checks on soft-deleted items.
637
+ */
638
+ async function handleContentGetIncludingTrashed(db, collection, id, locale) {
639
+ try {
640
+ const item = await new ContentRepository(db).findByIdOrSlugIncludingTrashed(collection, id, locale ? resolveConfiguredLocale(locale) : void 0);
641
+ if (!item) return {
642
+ success: false,
643
+ error: {
644
+ code: "NOT_FOUND",
645
+ message: `Content item not found: ${id}`
646
+ }
647
+ };
648
+ await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
649
+ await hydrateBylines(db, collection, item);
650
+ return {
651
+ success: true,
652
+ data: {
653
+ item,
654
+ _rev: encodeRev(item)
655
+ }
656
+ };
657
+ } catch (error) {
658
+ console.error("Content get error:", error);
659
+ return {
660
+ success: false,
661
+ error: {
662
+ code: "CONTENT_GET_ERROR",
663
+ message: "Failed to get content"
664
+ }
665
+ };
666
+ }
667
+ }
668
+ /**
669
+ * Create content item.
670
+ *
671
+ * Content + SEO writes are wrapped in a transaction so either both succeed
672
+ * or neither does. If `body.seo` is provided for a non-SEO collection, the
673
+ * API returns a validation error rather than silently dropping it.
674
+ */
675
+ async function handleContentCreate(db, collection, body) {
676
+ try {
677
+ const hasSeo = await collectionHasSeo(db, collection);
678
+ if (body.seo && !hasSeo) return {
679
+ success: false,
680
+ error: {
681
+ code: "VALIDATION_ERROR",
682
+ message: `Collection "${collection}" does not have SEO enabled. Remove the seo field or enable SEO on this collection.`
683
+ }
684
+ };
685
+ const mimeCheck = await validateMediaFields(db, collection, body.data);
686
+ if (!mimeCheck.success) return mimeCheck;
687
+ const item = await withTransaction(db, async (trx) => {
688
+ const repo = new ContentRepository(trx);
689
+ const bylineRepo = new BylineRepository(trx);
690
+ const inheritedFields = body.translationOf ? (await trx.selectFrom("_emdash_fields as field").innerJoin("_emdash_collections as collection", "collection.id", "field.collection_id").select("field.slug").where("collection.slug", "=", collection).where("field.translatable", "=", 0).execute()).map((field) => field.slug) : [];
691
+ const effectiveLocale = body.locale ? resolveConfiguredLocale(body.locale) : getI18nConfig()?.defaultLocale;
692
+ let slug = body.slug;
693
+ if (!slug) {
694
+ const slugSource = getSlugSource(body.data);
695
+ if (slugSource) slug = await repo.generateUniqueSlug(collection, slugSource, effectiveLocale);
696
+ }
697
+ if (body.status === "published") requireRoutablePublishSlug((await getCollectionPublishConfig(trx, collection)).routable, slug);
698
+ const created = await repo.create({
699
+ type: collection,
700
+ slug,
701
+ data: body.data,
702
+ status: body.status || "draft",
703
+ authorId: body.authorId,
704
+ locale: effectiveLocale,
705
+ translationOf: body.translationOf,
706
+ inheritFields: inheritedFields,
707
+ createdAt: body.createdAt,
708
+ publishedAt: body.publishedAt
709
+ });
710
+ if (body.bylines !== void 0) created.primaryBylineId = (await bylineRepo.setContentBylines(collection, created.id, body.bylines))[0]?.byline.translationGroup ?? null;
711
+ if (body.translationOf) {
712
+ if (body.bylines === void 0) {
713
+ await bylineRepo.copyContentBylines(collection, body.translationOf, created.id);
714
+ const source = await repo.findById(collection, body.translationOf);
715
+ if (source) created.primaryBylineId = source.primaryBylineId;
716
+ }
717
+ }
718
+ await hydrateBylines(trx, collection, created);
719
+ if (body.seo && hasSeo) created.seo = await new SeoRepository(trx).upsert(collection, created.id, body.seo);
720
+ else if (hasSeo) created.seo = { ...SEO_DEFAULTS };
721
+ if (body.taxonomies) await assignTaxonomies(trx, collection, created.id, effectiveLocale, body.taxonomies);
722
+ return created;
723
+ });
724
+ return {
725
+ success: true,
726
+ data: {
727
+ item,
728
+ _rev: encodeRev(item)
729
+ }
730
+ };
731
+ } catch (error) {
732
+ if (isMissingTableError(error)) return {
733
+ success: false,
734
+ error: {
735
+ code: "COLLECTION_NOT_FOUND",
736
+ message: `Collection '${collection}' not found`
737
+ }
738
+ };
739
+ if (error instanceof EmDashValidationError) {
740
+ if (error.message === "Translation source content not found") return {
741
+ success: false,
742
+ error: {
743
+ code: "NOT_FOUND",
744
+ message: error.message
745
+ }
746
+ };
747
+ return {
748
+ success: false,
749
+ error: {
750
+ code: "VALIDATION_ERROR",
751
+ message: error.message
752
+ }
753
+ };
754
+ }
755
+ const message = error instanceof Error ? error.message.toLowerCase() : "";
756
+ if (message.includes("unique constraint failed") || message.includes("duplicate key")) {
757
+ if (message.includes("active_tg_locale") || message.includes("translation_group") && message.includes("locale")) return {
758
+ success: false,
759
+ error: {
760
+ code: "CONFLICT",
761
+ message: `Translation already exists in locale "${body.locale ?? getI18nConfig()?.defaultLocale ?? "en"}" for this content item`
762
+ }
763
+ };
764
+ if (message.includes("slug")) return {
765
+ success: false,
766
+ error: {
767
+ code: "SLUG_CONFLICT",
768
+ message: `Slug '${body.slug ?? "(auto-generated)"}' already exists in collection '${collection}'`
769
+ }
770
+ };
771
+ return {
772
+ success: false,
773
+ error: {
774
+ code: "CONFLICT",
775
+ message: "Unique constraint violation"
776
+ }
777
+ };
778
+ }
779
+ console.error("Content create error:", error);
780
+ return {
781
+ success: false,
782
+ error: {
783
+ code: "CONTENT_CREATE_ERROR",
784
+ message: "Failed to create content"
785
+ }
786
+ };
787
+ }
788
+ }
789
+ /**
790
+ * Update content item.
791
+ * If `_rev` is provided, validates it against the current version before writing.
792
+ * No `_rev` = blind write (backwards-compatible for admin UI).
793
+ *
794
+ * Content + SEO writes are wrapped in a transaction for atomicity.
795
+ */
796
+ async function handleContentUpdate(db, collection, id, body) {
797
+ try {
798
+ const hasSeo = await collectionHasSeo(db, collection);
799
+ if (body.seo && !hasSeo) return {
800
+ success: false,
801
+ error: {
802
+ code: "VALIDATION_ERROR",
803
+ message: `Collection "${collection}" does not have SEO enabled. Remove the seo field or enable SEO on this collection.`
804
+ }
805
+ };
806
+ if (body.data) {
807
+ const mimeCheck = await validateMediaFields(db, collection, body.data);
808
+ if (!mimeCheck.success) return mimeCheck;
809
+ }
810
+ const resolvedId = await resolveId(new ContentRepository(db), collection, id, body.locale) ?? id;
811
+ const item = await withTransaction(db, async (trx) => {
812
+ const trxRepo = new ContentRepository(trx);
813
+ const bylineRepo = new BylineRepository(trx);
814
+ const existing = body._rev || body.slug !== void 0 || body.status === "published" ? await trxRepo.findById(collection, resolvedId) : null;
815
+ if (body._rev) {
816
+ if (!existing) throw Object.assign(/* @__PURE__ */ new Error(`Content item not found: ${id}`), { apiError: { code: "NOT_FOUND" } });
817
+ const revCheck = validateRev(body._rev, existing);
818
+ if (!revCheck.valid) throw Object.assign(new Error(revCheck.message), { apiError: { code: "CONFLICT" } });
819
+ }
820
+ let oldSlug;
821
+ if (body.slug && existing?.slug && existing.slug !== body.slug) oldSlug = existing.slug;
822
+ if ((body.status ?? existing?.status) === "published") {
823
+ if (!existing) throw Object.assign(/* @__PURE__ */ new Error(`Content item not found: ${id}`), { apiError: { code: "NOT_FOUND" } });
824
+ const publishConfig = await getCollectionPublishConfig(trx, collection);
825
+ const intendedSlug = body.slug !== void 0 ? body.slug : existing.slug;
826
+ requireRoutablePublishSlug(publishConfig.routable, intendedSlug);
827
+ }
828
+ const updated = await trxRepo.update(collection, resolvedId, {
829
+ data: body.data,
830
+ slug: body.slug,
831
+ status: body.status,
832
+ authorId: body.authorId,
833
+ publishedAt: body.publishedAt
834
+ });
835
+ if (body.bylines !== void 0) updated.primaryBylineId = (await bylineRepo.setContentBylines(collection, resolvedId, body.bylines))[0]?.byline.translationGroup ?? null;
836
+ if (oldSlug && body.slug) await createSlugChangeRedirect(trx, collection, oldSlug, body.slug, resolvedId, existing?.publishedAt ?? null, updated.publishedAt ?? null);
837
+ if (isI18nEnabled() && body.data && updated.translationGroup) await trxRepo.syncNonTranslatableFields(collection, updated.id, updated.translationGroup, body.data);
838
+ if (body.seo && hasSeo) updated.seo = await new SeoRepository(trx).upsert(collection, resolvedId, body.seo);
839
+ else if (hasSeo) updated.seo = await new SeoRepository(trx).get(collection, resolvedId);
840
+ await hydrateBylines(trx, collection, updated);
841
+ if (body.taxonomies) await assignTaxonomies(trx, collection, resolvedId, updated.locale ?? body.locale, body.taxonomies);
842
+ return updated;
843
+ });
844
+ return {
845
+ success: true,
846
+ data: {
847
+ item,
848
+ _rev: encodeRev(item)
849
+ }
850
+ };
851
+ } catch (error) {
852
+ if (hasApiError(error)) return {
853
+ success: false,
854
+ error: {
855
+ code: error.apiError.code,
856
+ message: error.message
857
+ }
858
+ };
859
+ if (isMissingTableError(error)) return {
860
+ success: false,
861
+ error: {
862
+ code: "COLLECTION_NOT_FOUND",
863
+ message: `Collection '${collection}' not found`
864
+ }
865
+ };
866
+ if (error instanceof EmDashValidationError) return {
867
+ success: false,
868
+ error: {
869
+ code: "VALIDATION_ERROR",
870
+ message: error.message
871
+ }
872
+ };
873
+ const message = error instanceof Error ? error.message.toLowerCase() : "";
874
+ if (message.includes("unique constraint failed") || message.includes("duplicate key")) {
875
+ if (message.includes("slug")) return {
876
+ success: false,
877
+ error: {
878
+ code: "SLUG_CONFLICT",
879
+ message: `Slug '${body.slug ?? id}' already exists in collection '${collection}'`
880
+ }
881
+ };
882
+ return {
883
+ success: false,
884
+ error: {
885
+ code: "CONFLICT",
886
+ message: "Unique constraint violation"
887
+ }
888
+ };
889
+ }
890
+ console.error("Content update error:", error);
891
+ return {
892
+ success: false,
893
+ error: {
894
+ code: "CONTENT_UPDATE_ERROR",
895
+ message: "Failed to update content"
896
+ }
897
+ };
898
+ }
899
+ }
900
+ /**
901
+ * Duplicate content item.
902
+ *
903
+ * Only copies SEO data if the collection has SEO enabled.
904
+ * Always returns consistent `seo` shape for SEO-enabled collections.
905
+ */
906
+ async function handleContentDuplicate(db, collection, id, authorId) {
907
+ try {
908
+ const hasSeo = await collectionHasSeo(db, collection);
909
+ return {
910
+ success: true,
911
+ data: { item: await withTransaction(db, async (trx) => {
912
+ const repo = new ContentRepository(trx);
913
+ const bylineRepo = new BylineRepository(trx);
914
+ const resolvedId = await resolveId(repo, collection, id) ?? id;
915
+ const dup = await repo.duplicate(collection, resolvedId, authorId);
916
+ const existingBylines = await bylineRepo.getContentBylines(collection, resolvedId);
917
+ if (existingBylines.length > 0) await bylineRepo.setContentBylines(collection, dup.id, existingBylines.map((entry) => ({
918
+ bylineId: entry.byline.id,
919
+ roleLabel: entry.roleLabel
920
+ })));
921
+ if (hasSeo) {
922
+ const seoRepo = new SeoRepository(trx);
923
+ await seoRepo.copyForDuplicate(collection, resolvedId, dup.id);
924
+ dup.seo = await seoRepo.get(collection, dup.id);
925
+ }
926
+ await hydrateBylines(trx, collection, dup);
927
+ return dup;
928
+ }) }
929
+ };
930
+ } catch (err) {
931
+ if (err instanceof EmDashValidationError) return {
932
+ success: false,
933
+ error: {
934
+ code: "NOT_FOUND",
935
+ message: err.message
936
+ }
937
+ };
938
+ console.error("Content duplicate error:", err);
939
+ return {
940
+ success: false,
941
+ error: {
942
+ code: "CONTENT_DUPLICATE_ERROR",
943
+ message: "Failed to duplicate content"
944
+ }
945
+ };
946
+ }
947
+ }
948
+ /**
949
+ * Delete content item (soft delete - moves to trash)
950
+ */
951
+ async function handleContentDelete(db, collection, id) {
952
+ try {
953
+ const result = await withTransaction(db, async (trx) => {
954
+ const repo = new ContentRepository(trx);
955
+ const resolvedId = await resolveId(repo, collection, id) ?? id;
956
+ const deleted = await repo.delete(collection, resolvedId);
957
+ if (deleted) await new EntryLockRepository(trx).releaseEntry(collection, resolvedId);
958
+ return {
959
+ id: resolvedId,
960
+ deleted
961
+ };
962
+ });
963
+ if (!result.deleted) return {
964
+ success: false,
965
+ error: {
966
+ code: "NOT_FOUND",
967
+ message: `Content item not found: ${id}`
968
+ }
969
+ };
970
+ return {
971
+ success: true,
972
+ data: {
973
+ deleted: true,
974
+ id: result.id
975
+ }
976
+ };
977
+ } catch (error) {
978
+ console.error("Content delete error:", error);
979
+ return {
980
+ success: false,
981
+ error: {
982
+ code: "CONTENT_DELETE_ERROR",
983
+ message: "Failed to delete content"
984
+ }
985
+ };
986
+ }
987
+ }
988
+ /**
989
+ * Restore content item from trash
990
+ */
991
+ async function handleContentRestore(db, collection, id, options = {}) {
992
+ try {
993
+ const expectedRevision = decodeRevisionPrecondition(options._rev);
994
+ const item = await withTransaction(db, async (trx) => {
995
+ const repo = new ContentRepository(trx);
996
+ const resolvedId = await resolveIdIncludingTrashed(repo, collection, id) ?? id;
997
+ return repo.restore(collection, resolvedId, expectedRevision);
998
+ });
999
+ if (!item) return {
1000
+ success: false,
1001
+ error: {
1002
+ code: "NOT_FOUND",
1003
+ message: `Trashed content item not found: ${id}`
1004
+ }
1005
+ };
1006
+ return {
1007
+ success: true,
1008
+ data: {
1009
+ restored: true,
1010
+ item,
1011
+ _rev: encodeRev(item)
1012
+ }
1013
+ };
1014
+ } catch (error) {
1015
+ if (error instanceof ContentMutationConflictError) return {
1016
+ success: false,
1017
+ error: {
1018
+ code: "CONFLICT",
1019
+ message: error.message
1020
+ }
1021
+ };
1022
+ if (isTranslationLocaleConflict(error, collection)) return {
1023
+ success: false,
1024
+ error: {
1025
+ code: "CONFLICT",
1026
+ message: "An active translation already exists in this locale"
1027
+ }
1028
+ };
1029
+ console.error("Content restore error:", error);
1030
+ return {
1031
+ success: false,
1032
+ error: {
1033
+ code: "CONTENT_RESTORE_ERROR",
1034
+ message: "Failed to restore content"
1035
+ }
1036
+ };
1037
+ }
1038
+ }
1039
+ /**
1040
+ * Permanently delete content item (cannot be undone).
1041
+ * Also cleans up associated SEO data.
1042
+ */
1043
+ async function handleContentPermanentDelete(db, collection, id) {
1044
+ try {
1045
+ const resolvedId = await resolveIdIncludingTrashed(new ContentRepository(db), collection, id) ?? id;
1046
+ if (!await withTransaction(db, async (trx) => {
1047
+ const trxRepo = new ContentRepository(trx);
1048
+ const item = await trxRepo.findByIdIncludingTrashed(collection, resolvedId);
1049
+ const wasDeleted = await trxRepo.permanentDelete(collection, resolvedId);
1050
+ if (wasDeleted) {
1051
+ await new SeoRepository(trx).delete(collection, resolvedId);
1052
+ await new CommentRepository(trx).deleteByContent(collection, resolvedId);
1053
+ await new RevisionRepository(trx).deleteByEntry(collection, resolvedId);
1054
+ await new EntryLockRepository(trx).releaseEntry(collection, resolvedId);
1055
+ await new BylineRepository(trx).deleteContentBylines(collection, resolvedId);
1056
+ if (item?.translationGroup) {
1057
+ if (!await trxRepo.hasTranslationsIncludingTrashed(collection, item.translationGroup)) await new TaxonomyRepository(trx).clearEntryGroupTerms(collection, item.translationGroup);
1058
+ }
1059
+ }
1060
+ return wasDeleted;
1061
+ })) return {
1062
+ success: false,
1063
+ error: {
1064
+ code: "NOT_FOUND",
1065
+ message: `Content item not found: ${id}`
1066
+ }
1067
+ };
1068
+ return {
1069
+ success: true,
1070
+ data: {
1071
+ deleted: true,
1072
+ id: resolvedId
1073
+ }
1074
+ };
1075
+ } catch (error) {
1076
+ console.error("Content permanent delete error:", error);
1077
+ return {
1078
+ success: false,
1079
+ error: {
1080
+ code: "CONTENT_DELETE_ERROR",
1081
+ message: "Failed to permanently delete content"
1082
+ }
1083
+ };
1084
+ }
1085
+ }
1086
+ /**
1087
+ * List trashed content items
1088
+ */
1089
+ async function handleContentListTrashed(db, collection, options = {}) {
1090
+ try {
1091
+ const result = await new ContentRepository(db).findTrashed(collection, {
1092
+ limit: options.limit,
1093
+ cursor: options.cursor,
1094
+ where: { locale: options.locale }
1095
+ });
1096
+ return {
1097
+ success: true,
1098
+ data: {
1099
+ items: result.items.map((item) => ({
1100
+ id: item.id,
1101
+ type: item.type,
1102
+ slug: item.slug,
1103
+ status: item.status,
1104
+ locale: item.locale,
1105
+ translationGroup: item.translationGroup,
1106
+ data: item.data,
1107
+ authorId: item.authorId,
1108
+ createdAt: item.createdAt,
1109
+ updatedAt: item.updatedAt,
1110
+ publishedAt: item.publishedAt,
1111
+ deletedAt: item.deletedAt
1112
+ })),
1113
+ nextCursor: result.nextCursor
1114
+ }
1115
+ };
1116
+ } catch (error) {
1117
+ if (error instanceof InvalidCursorError) return {
1118
+ success: false,
1119
+ error: {
1120
+ code: "INVALID_CURSOR",
1121
+ message: error.message
1122
+ }
1123
+ };
1124
+ console.error("Content list trashed error:", error);
1125
+ return {
1126
+ success: false,
1127
+ error: {
1128
+ code: "CONTENT_LIST_ERROR",
1129
+ message: "Failed to list trashed content"
1130
+ }
1131
+ };
1132
+ }
1133
+ }
1134
+ /**
1135
+ * Count trashed content items
1136
+ */
1137
+ async function handleContentCountTrashed(db, collection, options = {}) {
1138
+ try {
1139
+ return {
1140
+ success: true,
1141
+ data: { count: await new ContentRepository(db).countTrashed(collection, { locale: options.locale }) }
1142
+ };
1143
+ } catch (error) {
1144
+ console.error("Content count trashed error:", error);
1145
+ return {
1146
+ success: false,
1147
+ error: {
1148
+ code: "CONTENT_COUNT_ERROR",
1149
+ message: "Failed to count trashed content"
1150
+ }
1151
+ };
1152
+ }
1153
+ }
1154
+ /**
1155
+ * Schedule content for future publishing
1156
+ */
1157
+ async function handleContentSchedule(db, collection, id, scheduledAt, currentTime = /* @__PURE__ */ new Date(), _rev) {
1158
+ try {
1159
+ const expectedRevision = decodeRevisionPrecondition(_rev);
1160
+ const item = await withTransaction(db, async (trx) => {
1161
+ const repo = new ContentRepository(trx);
1162
+ const existing = await repo.findByIdOrSlug(collection, id);
1163
+ const resolvedId = existing?.id ?? id;
1164
+ if (existing) requireRoutablePublishSlug((await getCollectionPublishConfig(trx, collection)).routable, existing.slug);
1165
+ return repo.schedule(collection, resolvedId, scheduledAt, currentTime, expectedRevision);
1166
+ });
1167
+ await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1168
+ return {
1169
+ success: true,
1170
+ data: {
1171
+ item,
1172
+ _rev: encodeRev(item)
1173
+ }
1174
+ };
1175
+ } catch (error) {
1176
+ if (error instanceof ContentMutationConflictError) return {
1177
+ success: false,
1178
+ error: {
1179
+ code: "CONFLICT",
1180
+ message: error.message
1181
+ }
1182
+ };
1183
+ if (error instanceof EmDashValidationError) return {
1184
+ success: false,
1185
+ error: {
1186
+ code: "VALIDATION_ERROR",
1187
+ message: error.message
1188
+ }
1189
+ };
1190
+ console.error("Content schedule error:", error);
1191
+ return {
1192
+ success: false,
1193
+ error: {
1194
+ code: "CONTENT_SCHEDULE_ERROR",
1195
+ message: "Failed to schedule content"
1196
+ }
1197
+ };
1198
+ }
1199
+ }
1200
+ /**
1201
+ * Unschedule content (revert to draft)
1202
+ */
1203
+ async function handleContentUnschedule(db, collection, id, options = {}) {
1204
+ try {
1205
+ const expectedRevision = decodeRevisionPrecondition(options._rev);
1206
+ const item = await withTransaction(db, async (trx) => {
1207
+ const repo = new ContentRepository(trx);
1208
+ const resolvedId = await resolveId(repo, collection, id) ?? id;
1209
+ return repo.unschedule(collection, resolvedId, expectedRevision);
1210
+ });
1211
+ await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1212
+ return {
1213
+ success: true,
1214
+ data: {
1215
+ item,
1216
+ _rev: encodeRev(item)
1217
+ }
1218
+ };
1219
+ } catch (error) {
1220
+ if (error instanceof ContentMutationConflictError) return {
1221
+ success: false,
1222
+ error: {
1223
+ code: "CONFLICT",
1224
+ message: error.message
1225
+ }
1226
+ };
1227
+ if (error instanceof EmDashValidationError) return {
1228
+ success: false,
1229
+ error: {
1230
+ code: "VALIDATION_ERROR",
1231
+ message: error.message
1232
+ }
1233
+ };
1234
+ console.error("Content unschedule error:", error);
1235
+ return {
1236
+ success: false,
1237
+ error: {
1238
+ code: "CONTENT_UNSCHEDULE_ERROR",
1239
+ message: "Failed to unschedule content"
1240
+ }
1241
+ };
1242
+ }
1243
+ }
1244
+ /**
1245
+ * Persist a permanent policy rejection and unschedule the publication.
1246
+ * Databases with transactions commit both writes together. D1 persists the
1247
+ * reason first so a failed option write cannot silently remove the entry from
1248
+ * future sweeps; if unscheduling then fails, the due entry and its dashboard
1249
+ * notice remain available for retry and operator action.
1250
+ */
1251
+ async function handleScheduledPolicyRejection(db, collection, id, options) {
1252
+ try {
1253
+ const expectedRevision = decodeRevisionPrecondition(options._rev);
1254
+ const item = await withTransaction(db, async (trx) => {
1255
+ const repo = new ContentRepository(trx);
1256
+ const resolvedId = await resolveId(repo, collection, id) ?? id;
1257
+ const optionsRepo = new OptionsRepository(trx);
1258
+ const rejectionKey = scheduledPolicyRejectionKey(collection, resolvedId);
1259
+ const rejectionRevision = await optionsRepo.setVersioned(rejectionKey, {
1260
+ ...options.rejection,
1261
+ id: resolvedId
1262
+ });
1263
+ try {
1264
+ return await repo.unschedule(collection, resolvedId, expectedRevision);
1265
+ } catch (error) {
1266
+ if (error instanceof ContentMutationConflictError) try {
1267
+ await optionsRepo.compareAndDelete(rejectionKey, rejectionRevision);
1268
+ } catch (cleanupError) {
1269
+ console.error("Failed to clear stale scheduled policy rejection:", cleanupError);
1270
+ }
1271
+ throw error;
1272
+ }
1273
+ });
1274
+ await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1275
+ return {
1276
+ success: true,
1277
+ data: {
1278
+ item,
1279
+ _rev: encodeRev(item)
1280
+ }
1281
+ };
1282
+ } catch (error) {
1283
+ if (error instanceof ContentMutationConflictError) return {
1284
+ success: false,
1285
+ error: {
1286
+ code: "CONFLICT",
1287
+ message: error.message
1288
+ }
1289
+ };
1290
+ if (error instanceof EmDashValidationError) return {
1291
+ success: false,
1292
+ error: {
1293
+ code: "VALIDATION_ERROR",
1294
+ message: error.message
1295
+ }
1296
+ };
1297
+ console.error("Scheduled policy rejection error:", error);
1298
+ return {
1299
+ success: false,
1300
+ error: {
1301
+ code: "CONTENT_UNSCHEDULE_ERROR",
1302
+ message: "Failed to record scheduled publication rejection"
1303
+ }
1304
+ };
1305
+ }
1306
+ }
1307
+ /**
1308
+ * Publish content immediately.
1309
+ *
1310
+ * Publication is one atomic content-row statement. On databases that support
1311
+ * transactions, the slug redirect and the locale sync stay grouped with it.
1312
+ */
1313
+ async function handleContentPublish(db, collection, id, options = {}) {
1314
+ try {
1315
+ const expectedRevision = decodeRevisionPrecondition(options._rev);
1316
+ const item = await withTransaction(db, async (trx) => {
1317
+ const repo = new ContentRepository(trx);
1318
+ const resolvedId = await resolveId(repo, collection, id) ?? id;
1319
+ const publishConfig = await getCollectionPublishConfig(trx, collection);
1320
+ const existing = await repo.findById(collection, resolvedId);
1321
+ const published = await repo.publish(collection, resolvedId, options.publishedAt, options.requireScheduledDue, options.expectedScheduledAt, publishConfig.supportsRevisions, publishConfig.routable, expectedRevision, options.currentTime);
1322
+ if (existing && isI18nEnabled() && publishConfig.supportsRevisions && published.translationGroup) await repo.syncNonTranslatableFields(collection, published.id, published.translationGroup, published.data, { previous: existing.data });
1323
+ if (existing?.status === "published" && existing.slug && published.slug && existing.slug !== published.slug) await createSlugChangeRedirect(trx, collection, existing.slug, published.slug, resolvedId, existing.publishedAt ?? null, published.publishedAt ?? null);
1324
+ return published;
1325
+ });
1326
+ await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1327
+ return {
1328
+ success: true,
1329
+ data: {
1330
+ item,
1331
+ _rev: encodeRev(item)
1332
+ }
1333
+ };
1334
+ } catch (error) {
1335
+ if (error instanceof ContentMutationConflictError) return {
1336
+ success: false,
1337
+ error: {
1338
+ code: "CONFLICT",
1339
+ message: error.message
1340
+ }
1341
+ };
1342
+ if (error instanceof ScheduledNotDueError) return {
1343
+ success: false,
1344
+ error: {
1345
+ code: "NOT_DUE",
1346
+ message: error.message
1347
+ }
1348
+ };
1349
+ if (error instanceof EmDashValidationError) {
1350
+ const details = error.details;
1351
+ return {
1352
+ success: false,
1353
+ error: {
1354
+ code: typeof details === "object" && details !== null && "code" in details && details.code === "SLUG_CONFLICT" ? "SLUG_CONFLICT" : "VALIDATION_ERROR",
1355
+ message: error.message
1356
+ }
1357
+ };
1358
+ }
1359
+ const message = error instanceof Error ? error.message.toLowerCase() : "";
1360
+ if ((message.includes("unique constraint failed") || message.includes("duplicate key")) && message.includes("slug")) return {
1361
+ success: false,
1362
+ error: {
1363
+ code: "SLUG_CONFLICT",
1364
+ message: `The staged slug is already used by another entry in collection '${collection}'`
1365
+ }
1366
+ };
1367
+ console.error("Content publish error:", error);
1368
+ return {
1369
+ success: false,
1370
+ error: {
1371
+ code: "CONTENT_PUBLISH_ERROR",
1372
+ message: "Failed to publish content"
1373
+ }
1374
+ };
1375
+ }
1376
+ }
1377
+ /**
1378
+ * Unpublish content (revert to draft).
1379
+ *
1380
+ * Wrapped in a transaction — unpublish may create a draft revision
1381
+ * from the live version then update the status, which is multi-step.
1382
+ */
1383
+ async function handleContentUnpublish(db, collection, id, options = {}) {
1384
+ try {
1385
+ const expectedRevision = decodeRevisionPrecondition(options._rev);
1386
+ const item = await withTransaction(db, async (trx) => {
1387
+ const repo = new ContentRepository(trx);
1388
+ const resolvedId = await resolveId(repo, collection, id) ?? id;
1389
+ return repo.unpublish(collection, resolvedId, expectedRevision);
1390
+ });
1391
+ await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1392
+ return {
1393
+ success: true,
1394
+ data: {
1395
+ item,
1396
+ _rev: encodeRev(item)
1397
+ }
1398
+ };
1399
+ } catch (error) {
1400
+ if (error instanceof ContentMutationConflictError) return {
1401
+ success: false,
1402
+ error: {
1403
+ code: "CONFLICT",
1404
+ message: error.message
1405
+ }
1406
+ };
1407
+ if (error instanceof EmDashValidationError) return {
1408
+ success: false,
1409
+ error: {
1410
+ code: "VALIDATION_ERROR",
1411
+ message: error.message
1412
+ }
1413
+ };
1414
+ console.error("Content unpublish error:", error);
1415
+ return {
1416
+ success: false,
1417
+ error: {
1418
+ code: "CONTENT_UNPUBLISH_ERROR",
1419
+ message: "Failed to unpublish content"
1420
+ }
1421
+ };
1422
+ }
1423
+ }
1424
+ /**
1425
+ * Count scheduled content items
1426
+ */
1427
+ async function handleContentCountScheduled(db, collection) {
1428
+ try {
1429
+ return {
1430
+ success: true,
1431
+ data: { count: await new ContentRepository(db).countScheduled(collection) }
1432
+ };
1433
+ } catch (error) {
1434
+ console.error("Content count scheduled error:", error);
1435
+ return {
1436
+ success: false,
1437
+ error: {
1438
+ code: "CONTENT_COUNT_ERROR",
1439
+ message: "Failed to count scheduled content"
1440
+ }
1441
+ };
1442
+ }
1443
+ }
1444
+ /**
1445
+ * Discard draft changes (revert to live version)
1446
+ */
1447
+ async function handleContentDiscardDraft(db, collection, id, options = {}) {
1448
+ try {
1449
+ const expectedRevision = decodeRevisionPrecondition(options._rev);
1450
+ const item = await withTransaction(db, async (trx) => {
1451
+ const repo = new ContentRepository(trx);
1452
+ const resolvedId = await resolveId(repo, collection, id) ?? id;
1453
+ return repo.discardDraft(collection, resolvedId, expectedRevision);
1454
+ });
1455
+ await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1456
+ return {
1457
+ success: true,
1458
+ data: {
1459
+ item,
1460
+ _rev: encodeRev(item)
1461
+ }
1462
+ };
1463
+ } catch (error) {
1464
+ if (error instanceof ContentMutationConflictError) return {
1465
+ success: false,
1466
+ error: {
1467
+ code: "CONFLICT",
1468
+ message: error.message
1469
+ }
1470
+ };
1471
+ if (error instanceof EmDashValidationError) return {
1472
+ success: false,
1473
+ error: {
1474
+ code: "NOT_FOUND",
1475
+ message: error.message
1476
+ }
1477
+ };
1478
+ console.error("Content discard draft error:", error);
1479
+ return {
1480
+ success: false,
1481
+ error: {
1482
+ code: "CONTENT_DISCARD_DRAFT_ERROR",
1483
+ message: "Failed to discard draft"
1484
+ }
1485
+ };
1486
+ }
1487
+ }
1488
+ /**
1489
+ * Compare live and draft revisions
1490
+ */
1491
+ async function handleContentCompare(db, collection, id) {
1492
+ try {
1493
+ const entry = await new ContentRepository(db).findByIdOrSlug(collection, id);
1494
+ if (!entry) return {
1495
+ success: false,
1496
+ error: {
1497
+ code: "NOT_FOUND",
1498
+ message: `Content item not found: ${id}`
1499
+ }
1500
+ };
1501
+ const revisionRepo = new RevisionRepository(db);
1502
+ const live = entry.liveRevisionId ? await revisionRepo.findById(entry.liveRevisionId) : null;
1503
+ const draft = entry.draftRevisionId ? await revisionRepo.findById(entry.draftRevisionId) : null;
1504
+ return {
1505
+ success: true,
1506
+ data: {
1507
+ hasChanges: entry.draftRevisionId !== null && entry.draftRevisionId !== entry.liveRevisionId,
1508
+ live: live?.data ?? null,
1509
+ draft: draft?.data ?? null
1510
+ }
1511
+ };
1512
+ } catch (error) {
1513
+ console.error("Content compare error:", error);
1514
+ return {
1515
+ success: false,
1516
+ error: {
1517
+ code: "CONTENT_COMPARE_ERROR",
1518
+ message: "Failed to compare revisions"
1519
+ }
1520
+ };
1521
+ }
1522
+ }
1523
+ /**
1524
+ * Get all translations for a content item.
1525
+ * Returns the item's translation group members with locale and status info.
1526
+ */
1527
+ async function handleContentTranslations(db, collection, id) {
1528
+ try {
1529
+ const repo = new ContentRepository(db);
1530
+ const item = await repo.findByIdOrSlug(collection, id);
1531
+ if (!item) return {
1532
+ success: false,
1533
+ error: {
1534
+ code: "NOT_FOUND",
1535
+ message: `Content item not found: ${id}`
1536
+ }
1537
+ };
1538
+ if (!item.translationGroup) return {
1539
+ success: true,
1540
+ data: {
1541
+ translationGroup: item.id,
1542
+ translations: [{
1543
+ id: item.id,
1544
+ locale: item.locale,
1545
+ slug: item.slug,
1546
+ status: item.status,
1547
+ updatedAt: item.updatedAt
1548
+ }]
1549
+ }
1550
+ };
1551
+ const translations = await repo.findTranslations(collection, item.translationGroup);
1552
+ return {
1553
+ success: true,
1554
+ data: {
1555
+ translationGroup: item.translationGroup,
1556
+ translations: translations.map((t) => ({
1557
+ id: t.id,
1558
+ locale: t.locale,
1559
+ slug: t.slug,
1560
+ status: t.status,
1561
+ updatedAt: t.updatedAt
1562
+ }))
1563
+ }
1564
+ };
1565
+ } catch (error) {
1566
+ if (error instanceof Error) console.error("Content translations error:", error);
1567
+ return {
1568
+ success: false,
1569
+ error: {
1570
+ code: "CONTENT_TRANSLATIONS_ERROR",
1571
+ message: "Failed to get translations"
1572
+ }
1573
+ };
1574
+ }
1575
+ }
1576
+ /**
1577
+ * Resolve a `{ taxonomyName: [slug, ...] }` map to term IDs and replace the
1578
+ * entry's assignments for each named taxonomy.
1579
+ *
1580
+ * Shared by handleContentCreate and handleContentUpdate so both MCP entry
1581
+ * points behave identically. Slug resolution is scoped to `locale`; passing
1582
+ * `undefined` lets `findBySlug` fall back to its default (lowest locale code)
1583
+ * so callers on single-locale sites don't need to know the site's default.
1584
+ *
1585
+ * Throws EmDashValidationError on unknown slug or wrong shape; the calling
1586
+ * handler translates that into a VALIDATION_ERROR response.
1587
+ */
1588
+ async function assignTaxonomies(trx, collection, entryId, locale, taxonomies) {
1589
+ const taxRepo = new TaxonomyRepository(trx);
1590
+ let anyChange = false;
1591
+ for (const [taxonomyName, slugs] of Object.entries(taxonomies)) {
1592
+ if (!Array.isArray(slugs)) throw new EmDashValidationError(`taxonomies.${taxonomyName} must be an array of term slugs`);
1593
+ const termIds = [];
1594
+ for (const slug of slugs) {
1595
+ if (typeof slug !== "string" || slug.length === 0) throw new EmDashValidationError(`taxonomies.${taxonomyName} contains a non-string or empty slug`);
1596
+ const term = await taxRepo.findBySlug(taxonomyName, slug, locale);
1597
+ if (!term) throw new EmDashValidationError(`Unknown taxonomy term: ${taxonomyName}='${slug}'${locale ? ` (locale '${locale}')` : ""}`);
1598
+ termIds.push(term.id);
1599
+ }
1600
+ await taxRepo.setTermsForEntry(collection, entryId, taxonomyName, termIds);
1601
+ anyChange = true;
1602
+ }
1603
+ if (anyChange) invalidateTermCache();
1604
+ }
1605
+
1606
+ //#endregion
1607
+ //#region src/api/handlers/manifest.ts
1608
+ /** Pattern to add spaces before capital letters */
1609
+ const CAMEL_CASE_PATTERN = /([A-Z])/g;
1610
+ const FIRST_CHAR_PATTERN = /^./;
1611
+ /**
1612
+ * Map schema field types to editor field kinds.
1613
+ */
1614
+ /** Field types that can be surfaced as list columns in the admin. */
1615
+ const LIST_COLUMN_FIELD_TYPES = new Set([
1616
+ "string",
1617
+ "number",
1618
+ "integer",
1619
+ "boolean",
1620
+ "datetime",
1621
+ "select",
1622
+ "multiSelect"
1623
+ ]);
1624
+ const FIELD_TYPE_TO_KIND = {
1625
+ string: "string",
1626
+ slug: "string",
1627
+ url: "url",
1628
+ text: "richText",
1629
+ number: "number",
1630
+ integer: "number",
1631
+ boolean: "boolean",
1632
+ datetime: "datetime",
1633
+ select: "select",
1634
+ multiSelect: "multiSelect",
1635
+ portableText: "portableText",
1636
+ image: "image",
1637
+ file: "file",
1638
+ reference: "reference",
1639
+ json: "json",
1640
+ repeater: "repeater"
1641
+ };
1642
+ /**
1643
+ * Generate admin manifest from collections
1644
+ */
1645
+ async function generateManifest(collections, plugins = {}, options = {}) {
1646
+ const manifestCollections = await buildManifestCollections(collections, options.db);
1647
+ return {
1648
+ version: "0.1.0",
1649
+ hash: await hashString(JSON.stringify(manifestCollections)),
1650
+ collections: manifestCollections,
1651
+ plugins
1652
+ };
1653
+ }
1654
+ /**
1655
+ * Build collection descriptors from build-time config plus live database rows.
1656
+ *
1657
+ * Config collections are added first and win on slug conflicts. Runtime/manual
1658
+ * collections have no Zod schema to inspect, so their field descriptors are
1659
+ * synthesized from `_emdash_fields`.
1660
+ */
1661
+ async function buildManifestCollections(collections, db) {
1662
+ const manifestCollections = {};
1663
+ for (const [name, definition] of Object.entries(collections)) {
1664
+ const fields = extractFieldDescriptors(definition.schema);
1665
+ manifestCollections[name] = {
1666
+ label: definition.admin.label,
1667
+ labelSingular: definition.admin.labelSingular || definition.admin.label,
1668
+ supports: definition.admin.supports || [],
1669
+ hasSeo: (definition.admin.supports || []).includes("seo"),
1670
+ routable: definition.admin.routable ?? true,
1671
+ fields
1672
+ };
1673
+ }
1674
+ if (!db) return manifestCollections;
1675
+ try {
1676
+ const dbCollections = await new SchemaRegistry(db).listCollectionsWithFields();
1677
+ for (const collection of dbCollections) {
1678
+ if (manifestCollections[collection.slug]) continue;
1679
+ const fields = {};
1680
+ for (const field of collection.fields) fields[field.slug] = dbFieldDescriptor(field);
1681
+ const configuredListColumns = collection.admin?.listColumns ?? [];
1682
+ const fieldTypes = new Map(collection.fields.map((field) => [field.slug, field.type]));
1683
+ const listColumns = [];
1684
+ for (const slug of configuredListColumns) {
1685
+ if (listColumns.includes(slug)) continue;
1686
+ const fieldType = fieldTypes.get(slug);
1687
+ if (!fieldType || !LIST_COLUMN_FIELD_TYPES.has(fieldType)) {
1688
+ console.warn(`EmDash: Ignoring unsupported or unknown list column "${slug}" in collection "${collection.slug}".`);
1689
+ continue;
1690
+ }
1691
+ if (listColumns.length >= MAX_COLLECTION_LIST_COLUMNS) {
1692
+ console.warn(`EmDash: Collection "${collection.slug}" declares more than ${MAX_COLLECTION_LIST_COLUMNS} list columns; extra columns are ignored.`);
1693
+ break;
1694
+ }
1695
+ listColumns.push(slug);
1696
+ }
1697
+ manifestCollections[collection.slug] = {
1698
+ label: collection.label,
1699
+ labelSingular: collection.labelSingular || collection.label,
1700
+ supports: collection.supports || [],
1701
+ hasSeo: collection.hasSeo,
1702
+ urlPattern: collection.urlPattern,
1703
+ routable: collection.routable !== false,
1704
+ titleField: collection.titleField,
1705
+ dateField: collection.dateField,
1706
+ ...collection.hidden ? { hidden: true } : {},
1707
+ ...collection.group ? { group: collection.group } : {},
1708
+ listColumns: listColumns.length > 0 ? listColumns : void 0,
1709
+ fields
1710
+ };
1711
+ }
1712
+ } catch (error) {
1713
+ console.debug("EmDash: Could not load database collections for manifest:", error);
1714
+ }
1715
+ return manifestCollections;
1716
+ }
1717
+ /**
1718
+ * Extract field descriptors from Zod schema
1719
+ * Note: This is a simplified implementation that handles common types
1720
+ */
1721
+ function extractFieldDescriptors(schema) {
1722
+ const fields = {};
1723
+ const shape = typeof schema._def?.shape === "function" ? schema._def.shape() : schema.shape || {};
1724
+ for (const [name, fieldSchema] of Object.entries(shape)) fields[name] = extractFieldType(name, fieldSchema);
1725
+ return fields;
1726
+ }
1727
+ /**
1728
+ * Extract field type from Zod schema
1729
+ */
1730
+ /** Type guard: check if a value is a non-null object */
1731
+ function isObject(value) {
1732
+ return typeof value === "object" && value !== null;
1733
+ }
1734
+ function extractFieldType(name, schema) {
1735
+ if (!isObject(schema)) return {
1736
+ kind: "string",
1737
+ label: formatLabel(name)
1738
+ };
1739
+ if (schema.isPortableText) return {
1740
+ kind: "portableText",
1741
+ label: formatLabel(name)
1742
+ };
1743
+ if (schema.isImage) return {
1744
+ kind: "image",
1745
+ label: formatLabel(name)
1746
+ };
1747
+ if (schema.isReference) return {
1748
+ kind: "reference",
1749
+ label: formatLabel(name)
1750
+ };
1751
+ const def = isObject(schema._def) ? schema._def : void 0;
1752
+ switch (typeof def?.typeName === "string" ? def.typeName : void 0) {
1753
+ case "ZodString": return {
1754
+ kind: "string",
1755
+ label: formatLabel(name)
1756
+ };
1757
+ case "ZodNumber": return {
1758
+ kind: "number",
1759
+ label: formatLabel(name)
1760
+ };
1761
+ case "ZodBoolean": return {
1762
+ kind: "boolean",
1763
+ label: formatLabel(name)
1764
+ };
1765
+ case "ZodDate": return {
1766
+ kind: "datetime",
1767
+ label: formatLabel(name)
1768
+ };
1769
+ case "ZodEnum": {
1770
+ const values = Array.isArray(def?.values) ? def.values : [];
1771
+ return {
1772
+ kind: "select",
1773
+ label: formatLabel(name),
1774
+ options: values.filter((v) => typeof v === "string").map((v) => ({
1775
+ value: v,
1776
+ label: v.charAt(0).toUpperCase() + v.slice(1)
1777
+ }))
1778
+ };
1779
+ }
1780
+ case "ZodArray": return {
1781
+ kind: "array",
1782
+ label: formatLabel(name)
1783
+ };
1784
+ case "ZodObject": return {
1785
+ kind: "object",
1786
+ label: formatLabel(name)
1787
+ };
1788
+ case "ZodOptional":
1789
+ case "ZodDefault":
1790
+ if (def?.innerType) return extractFieldType(name, def.innerType);
1791
+ return {
1792
+ kind: "string",
1793
+ label: formatLabel(name)
1794
+ };
1795
+ default: return {
1796
+ kind: "string",
1797
+ label: formatLabel(name)
1798
+ };
1799
+ }
1800
+ }
1801
+ function dbFieldDescriptor(field) {
1802
+ const entry = {
1803
+ kind: field.unsupportedType ? "unsupported" : FIELD_TYPE_TO_KIND[field.type],
1804
+ label: field.label,
1805
+ required: field.required,
1806
+ translatable: field.translatable,
1807
+ id: field.id
1808
+ };
1809
+ if (field.unsupportedType) entry.unsupportedType = field.unsupportedType;
1810
+ if (field.widget) entry.widget = field.widget;
1811
+ if (field.options) entry.options = field.options;
1812
+ if (field.validation?.options) entry.options = field.validation.options.map((value) => ({
1813
+ value,
1814
+ label: value.charAt(0).toUpperCase() + value.slice(1)
1815
+ }));
1816
+ if (field.validation) entry.validation = { ...field.validation };
1817
+ return entry;
1818
+ }
1819
+ /**
1820
+ * Format field name as label
1821
+ */
1822
+ function formatLabel(name) {
1823
+ return name.replace(CAMEL_CASE_PATTERN, " $1").replace(FIRST_CHAR_PATTERN, (str) => str.toUpperCase()).trim();
1824
+ }
1825
+
1826
+ //#endregion
1827
+ //#region src/api/handlers/revision.ts
1828
+ /**
1829
+ * List revisions for a content entry
1830
+ */
1831
+ async function handleRevisionList(db, collection, entryId, params = {}) {
1832
+ try {
1833
+ const repo = new RevisionRepository(db);
1834
+ const [items, total] = await Promise.all([repo.findByEntry(collection, entryId, { limit: Math.min(params.limit || 50, 100) }), repo.countByEntry(collection, entryId)]);
1835
+ return {
1836
+ success: true,
1837
+ data: {
1838
+ items,
1839
+ total
1840
+ }
1841
+ };
1842
+ } catch {
1843
+ return {
1844
+ success: false,
1845
+ error: {
1846
+ code: "REVISION_LIST_ERROR",
1847
+ message: "Failed to list revisions"
1848
+ }
1849
+ };
1850
+ }
1851
+ }
1852
+ /**
1853
+ * Get a specific revision
1854
+ */
1855
+ async function handleRevisionGet(db, revisionId) {
1856
+ try {
1857
+ const item = await new RevisionRepository(db).findById(revisionId);
1858
+ if (!item) return {
1859
+ success: false,
1860
+ error: {
1861
+ code: "NOT_FOUND",
1862
+ message: `Revision not found: ${revisionId}`
1863
+ }
1864
+ };
1865
+ return {
1866
+ success: true,
1867
+ data: { item }
1868
+ };
1869
+ } catch {
1870
+ return {
1871
+ success: false,
1872
+ error: {
1873
+ code: "REVISION_GET_ERROR",
1874
+ message: "Failed to get revision"
1875
+ }
1876
+ };
1877
+ }
1878
+ }
1879
+ /**
1880
+ * Restore a revision (updates content to this revision's data and creates new revision)
1881
+ */
1882
+ async function handleRevisionRestore(db, revisionId, callerUserId) {
1883
+ try {
1884
+ const revision = await new RevisionRepository(db).findById(revisionId);
1885
+ if (!revision) return {
1886
+ success: false,
1887
+ error: {
1888
+ code: "NOT_FOUND",
1889
+ message: `Revision not found: ${revisionId}`
1890
+ }
1891
+ };
1892
+ const { item, revisionId: queuedRevisionId } = await new ContentRepository(db).restoreRevision(revision.collection, revision.entryId, revision.data, callerUserId);
1893
+ const pruneRepo = new RevisionRepository(db);
1894
+ after(async () => {
1895
+ try {
1896
+ await pruneRepo.pruneQueuedEntry(revision.collection, revision.entryId, queuedRevisionId, 50);
1897
+ } catch (error) {
1898
+ console.error(`[revisions] Failed to prune revisions for ${revision.collection}/${revision.entryId}:`, error);
1899
+ }
1900
+ });
1901
+ return {
1902
+ success: true,
1903
+ data: {
1904
+ item,
1905
+ _rev: encodeRev(item)
1906
+ }
1907
+ };
1908
+ } catch (error) {
1909
+ if (error instanceof ContentMutationConflictError) return {
1910
+ success: false,
1911
+ error: {
1912
+ code: "CONFLICT",
1913
+ message: error.message
1914
+ }
1915
+ };
1916
+ return {
1917
+ success: false,
1918
+ error: {
1919
+ code: "REVISION_RESTORE_ERROR",
1920
+ message: "Failed to restore revision"
1921
+ }
1922
+ };
1923
+ }
1924
+ }
1925
+
1926
+ //#endregion
1927
+ //#region src/api/handlers/media.ts
1928
+ const FOREIGN_KEY_VIOLATION_RE = /foreign key constraint failed/i;
1929
+ /**
1930
+ * List media items
1931
+ */
1932
+ async function handleMediaList(db, params) {
1933
+ try {
1934
+ if (params.page !== void 0) {
1935
+ const limit = Math.min(params.limit || 50, 100);
1936
+ const offset = (params.page - 1) * limit;
1937
+ if (params.cursor !== void 0 || !Number.isSafeInteger(params.page) || params.page < 1 || !Number.isSafeInteger(offset)) return {
1938
+ success: false,
1939
+ error: {
1940
+ code: "VALIDATION_ERROR",
1941
+ message: "Invalid media page"
1942
+ }
1943
+ };
1944
+ return {
1945
+ success: true,
1946
+ data: await new MediaRepository(db).findPage({
1947
+ page: params.page,
1948
+ limit,
1949
+ mimeType: params.mimeType,
1950
+ q: params.q,
1951
+ folderId: params.folderId
1952
+ })
1953
+ };
1954
+ }
1955
+ const result = await new MediaRepository(db).findMany({
1956
+ cursor: params.cursor,
1957
+ limit: Math.min(params.limit || 50, 100),
1958
+ mimeType: params.mimeType,
1959
+ q: params.q,
1960
+ folderId: params.folderId
1961
+ });
1962
+ return {
1963
+ success: true,
1964
+ data: {
1965
+ items: result.items,
1966
+ nextCursor: result.nextCursor
1967
+ }
1968
+ };
1969
+ } catch (error) {
1970
+ if (error instanceof InvalidCursorError) return {
1971
+ success: false,
1972
+ error: {
1973
+ code: "INVALID_CURSOR",
1974
+ message: error.message
1975
+ }
1976
+ };
1977
+ return {
1978
+ success: false,
1979
+ error: {
1980
+ code: "MEDIA_LIST_ERROR",
1981
+ message: "Failed to list media"
1982
+ }
1983
+ };
1984
+ }
1985
+ }
1986
+ /**
1987
+ * Get single media item
1988
+ */
1989
+ async function handleMediaGet(db, id) {
1990
+ try {
1991
+ const item = await new MediaRepository(db).findById(id);
1992
+ if (!item) return {
1993
+ success: false,
1994
+ error: {
1995
+ code: "NOT_FOUND",
1996
+ message: `Media item not found: ${id}`
1997
+ }
1998
+ };
1999
+ return {
2000
+ success: true,
2001
+ data: { item }
2002
+ };
2003
+ } catch {
2004
+ return {
2005
+ success: false,
2006
+ error: {
2007
+ code: "MEDIA_GET_ERROR",
2008
+ message: "Failed to get media"
2009
+ }
2010
+ };
2011
+ }
2012
+ }
2013
+ /**
2014
+ * Create media item (after file upload)
2015
+ */
2016
+ async function handleMediaCreate(db, input) {
2017
+ try {
2018
+ return {
2019
+ success: true,
2020
+ data: { item: await new MediaRepository(db).create(input) }
2021
+ };
2022
+ } catch {
2023
+ return {
2024
+ success: false,
2025
+ error: {
2026
+ code: "MEDIA_CREATE_ERROR",
2027
+ message: "Failed to create media"
2028
+ }
2029
+ };
2030
+ }
2031
+ }
2032
+ /**
2033
+ * Update media metadata
2034
+ */
2035
+ async function handleMediaUpdate(db, id, input) {
2036
+ if (!isValidFocalPointUpdate(input)) return {
2037
+ success: false,
2038
+ error: {
2039
+ code: "VALIDATION_ERROR",
2040
+ message: "focalX and focalY must both be valid numbers or both be null"
2041
+ }
2042
+ };
2043
+ try {
2044
+ const item = await new MediaRepository(db).update(id, input);
2045
+ if (!item) return {
2046
+ success: false,
2047
+ error: {
2048
+ code: "NOT_FOUND",
2049
+ message: `Media item not found: ${id}`
2050
+ }
2051
+ };
2052
+ return {
2053
+ success: true,
2054
+ data: { item }
2055
+ };
2056
+ } catch (error) {
2057
+ if (isForeignKeyViolation(error)) return {
2058
+ success: false,
2059
+ error: {
2060
+ code: "NOT_FOUND",
2061
+ message: "Media folder not found"
2062
+ }
2063
+ };
2064
+ return {
2065
+ success: false,
2066
+ error: {
2067
+ code: "MEDIA_UPDATE_ERROR",
2068
+ message: "Failed to update media"
2069
+ }
2070
+ };
2071
+ }
2072
+ }
2073
+ async function handleMediaReplaceMetadata(db, id, expectedStorageKey, input) {
2074
+ try {
2075
+ const item = await new MediaRepository(db).replaceReadyFile(id, expectedStorageKey, input);
2076
+ if (!item) return {
2077
+ success: false,
2078
+ error: {
2079
+ code: "MEDIA_REPLACE_METADATA_ERROR",
2080
+ message: "Failed to update replaced media metadata"
2081
+ }
2082
+ };
2083
+ return {
2084
+ success: true,
2085
+ data: { item }
2086
+ };
2087
+ } catch {
2088
+ return {
2089
+ success: false,
2090
+ error: {
2091
+ code: "MEDIA_REPLACE_METADATA_ERROR",
2092
+ message: "Failed to update replaced media metadata"
2093
+ }
2094
+ };
2095
+ }
2096
+ }
2097
+ function isForeignKeyViolation(error) {
2098
+ if (error && typeof error === "object") {
2099
+ if ("code" in error && error.code === "23503") return true;
2100
+ }
2101
+ const message = error instanceof Error ? error.message : "";
2102
+ if (FOREIGN_KEY_VIOLATION_RE.test(message)) return true;
2103
+ return Boolean(error && typeof error === "object" && "cause" in error && isForeignKeyViolation(error.cause));
2104
+ }
2105
+ /**
2106
+ * Delete media item
2107
+ */
2108
+ async function handleMediaDelete(db, id) {
2109
+ try {
2110
+ const storageKey = await new MediaRepository(db).deleteWithStorageKey(id);
2111
+ if (!storageKey) return {
2112
+ success: false,
2113
+ error: {
2114
+ code: "NOT_FOUND",
2115
+ message: `Media item not found: ${id}`
2116
+ }
2117
+ };
2118
+ return {
2119
+ success: true,
2120
+ data: {
2121
+ deleted: true,
2122
+ storageKey
2123
+ }
2124
+ };
2125
+ } catch {
2126
+ return {
2127
+ success: false,
2128
+ error: {
2129
+ code: "MEDIA_DELETE_ERROR",
2130
+ message: "Failed to delete media"
2131
+ }
2132
+ };
2133
+ }
2134
+ }
2135
+
2136
+ //#endregion
2137
+ //#region src/api/handlers/plugin-settings.ts
2138
+ function settingsKey(pluginId, key) {
2139
+ return `plugin:${pluginId}:settings:${key}`;
2140
+ }
2141
+ /**
2142
+ * Resolve a plugin's settings schema from either the configured
2143
+ * (in-process) plugin list or the statically-sandboxed entries.
2144
+ * Returns null when the plugin doesn't exist, undefined-equivalent
2145
+ * empty object when it declares no schema.
2146
+ */
2147
+ function getPluginSettingsSchema(configuredPlugins, sandboxedPluginEntries, pluginId) {
2148
+ const plugin = configuredPlugins.find((p) => p.id === pluginId);
2149
+ if (plugin) return plugin.admin.settingsSchema ?? {};
2150
+ const sandboxed = sandboxedPluginEntries.find((e) => e.id === pluginId);
2151
+ if (sandboxed) return sandboxed.settingsSchema ?? {};
2152
+ return null;
2153
+ }
2154
+ /**
2155
+ * Validate a single value against its schema field.
2156
+ * Returns an error message, or null when valid.
2157
+ */
2158
+ function validateValue(key, field, value) {
2159
+ switch (field.type) {
2160
+ case "string":
2161
+ case "secret":
2162
+ case "url":
2163
+ case "email":
2164
+ if (typeof value !== "string") return `Setting "${key}" must be a string`;
2165
+ if (field.type === "url" && value !== "" && !URL.canParse(value)) return `Setting "${key}" must be a valid URL`;
2166
+ if (field.type === "email" && value !== "" && !value.includes("@")) return `Setting "${key}" must be a valid email address`;
2167
+ return null;
2168
+ case "number":
2169
+ if (typeof value !== "number" || Number.isNaN(value)) return `Setting "${key}" must be a number`;
2170
+ if (field.min !== void 0 && value < field.min) return `Setting "${key}" must be at least ${field.min}`;
2171
+ if (field.max !== void 0 && value > field.max) return `Setting "${key}" must be at most ${field.max}`;
2172
+ return null;
2173
+ case "boolean": return typeof value === "boolean" ? null : `Setting "${key}" must be a boolean`;
2174
+ case "select":
2175
+ if (typeof value !== "string" || !field.options.some((o) => o.value === value)) return `Setting "${key}" must be one of the defined options`;
2176
+ return null;
2177
+ default: return `Setting "${key}" has an unknown field type`;
2178
+ }
2179
+ }
2180
+ async function buildSettingsResponse(optionsRepo, pluginId, schema) {
2181
+ const keys = Object.keys(schema);
2182
+ const stored = await optionsRepo.getMany(keys.map((key) => settingsKey(pluginId, key)));
2183
+ const values = {};
2184
+ const secretsSet = {};
2185
+ for (const key of keys) {
2186
+ const field = schema[key];
2187
+ if (!field) continue;
2188
+ const storedValue = stored.get(settingsKey(pluginId, key));
2189
+ if (field.type === "secret") {
2190
+ secretsSet[key] = storedValue !== void 0 && storedValue !== null && storedValue !== "";
2191
+ continue;
2192
+ }
2193
+ if (storedValue !== void 0 && storedValue !== null) values[key] = storedValue;
2194
+ else if ("default" in field && field.default !== void 0) values[key] = field.default;
2195
+ else values[key] = null;
2196
+ }
2197
+ return {
2198
+ schema,
2199
+ values,
2200
+ secretsSet
2201
+ };
2202
+ }
2203
+ /**
2204
+ * Get a plugin's settings (schema + current values, secrets masked)
2205
+ */
2206
+ async function handlePluginSettingsGet(db, pluginId, schema) {
2207
+ try {
2208
+ return {
2209
+ success: true,
2210
+ data: await buildSettingsResponse(new OptionsRepository(db), pluginId, schema)
2211
+ };
2212
+ } catch {
2213
+ return {
2214
+ success: false,
2215
+ error: {
2216
+ code: ErrorCode.PLUGIN_SETTINGS_READ_ERROR,
2217
+ message: "Failed to read plugin settings"
2218
+ }
2219
+ };
2220
+ }
2221
+ }
2222
+ /**
2223
+ * Update a plugin's settings.
2224
+ *
2225
+ * Only keys present in `updates` are written. A `null` value deletes the
2226
+ * stored value (reverting to the schema default). Secret fields are
2227
+ * write-only: they accept a new string value or `null` to clear, and the
2228
+ * response never echoes them back.
2229
+ */
2230
+ async function handlePluginSettingsUpdate(db, pluginId, schema, updates) {
2231
+ try {
2232
+ for (const [key, value] of Object.entries(updates)) {
2233
+ const field = schema[key];
2234
+ if (!field) return {
2235
+ success: false,
2236
+ error: {
2237
+ code: ErrorCode.VALIDATION_ERROR,
2238
+ message: `Unknown setting "${key}" for plugin "${pluginId}"`
2239
+ }
2240
+ };
2241
+ if (value === null) continue;
2242
+ const error = validateValue(key, field, value);
2243
+ if (error) return {
2244
+ success: false,
2245
+ error: {
2246
+ code: ErrorCode.VALIDATION_ERROR,
2247
+ message: error
2248
+ }
2249
+ };
2250
+ }
2251
+ const encodedUpdates = /* @__PURE__ */ new Map();
2252
+ for (const [key, value] of Object.entries(updates)) encodedUpdates.set(key, value === null ? null : await encodePluginSettingValue(pluginId, key, value, schema));
2253
+ return {
2254
+ success: true,
2255
+ data: await withTransaction(db, async (trx) => {
2256
+ const txRepo = new OptionsRepository(trx);
2257
+ for (const [key, value] of encodedUpdates) {
2258
+ if (value === null) await txRepo.delete(settingsKey(pluginId, key));
2259
+ else await txRepo.set(settingsKey(pluginId, key), value);
2260
+ await trx.deleteFrom("_plugin_storage").where("plugin_id", "=", pluginId).where("collection", "=", "__kv").where("id", "=", `settings:${key}`).execute();
2261
+ }
2262
+ return buildSettingsResponse(txRepo, pluginId, schema);
2263
+ })
2264
+ };
2265
+ } catch (error) {
2266
+ if (error instanceof PluginSettingEncryptionError) return {
2267
+ success: false,
2268
+ error: {
2269
+ code: error.code,
2270
+ message: error.message
2271
+ }
2272
+ };
2273
+ if (error instanceof EmDashSecretsError) return {
2274
+ success: false,
2275
+ error: {
2276
+ code: ErrorCode.PLUGIN_SETTING_ENCRYPTION_KEY_INVALID,
2277
+ message: "EMDASH_ENCRYPTION_KEY is malformed. Restore or correct the configured key from its secret backup. Generate a new key only if no stored plugin setting depends on the lost key."
2278
+ }
2279
+ };
2280
+ return {
2281
+ success: false,
2282
+ error: {
2283
+ code: ErrorCode.PLUGIN_SETTINGS_UPDATE_ERROR,
2284
+ message: "Failed to update plugin settings"
2285
+ }
2286
+ };
2287
+ }
2288
+ }
2289
+
2290
+ //#endregion
2291
+ //#region src/plugins/marketplace.ts
2292
+ /**
2293
+ * MarketplaceClient — HTTP client for the EmDash Plugin Marketplace
2294
+ *
2295
+ * Used by the install/update/proxy endpoints in EmDash core to communicate
2296
+ * with the marketplace Worker. The marketplace is a distribution channel,
2297
+ * not a runtime dependency — bundles are copied to site-local R2 at install time.
2298
+ */
2299
+ const TRAILING_SLASHES = /\/+$/;
2300
+ const LEADING_DOT_SLASH = /^\.\//;
2301
+ var MarketplaceError = class extends Error {
2302
+ constructor(message, status, code) {
2303
+ super(message);
2304
+ this.status = status;
2305
+ this.code = code;
2306
+ this.name = "MarketplaceError";
2307
+ }
2308
+ };
2309
+ var MarketplaceUnavailableError = class extends MarketplaceError {
2310
+ constructor(cause) {
2311
+ super("Plugin marketplace is unavailable", void 0, "MARKETPLACE_UNAVAILABLE");
2312
+ if (cause) this.cause = cause;
2313
+ }
2314
+ };
2315
+ var MarketplaceClientImpl = class {
2316
+ baseUrl;
2317
+ siteOrigin;
2318
+ constructor(baseUrl, siteOrigin) {
2319
+ this.baseUrl = baseUrl.replace(TRAILING_SLASHES, "");
2320
+ this.siteOrigin = siteOrigin;
2321
+ }
2322
+ async search(query, opts) {
2323
+ const params = new URLSearchParams();
2324
+ if (query) params.set("q", query);
2325
+ if (opts?.category) params.set("category", opts.category);
2326
+ if (opts?.capability) params.set("capability", opts.capability);
2327
+ if (opts?.sort) params.set("sort", opts.sort);
2328
+ if (opts?.cursor) params.set("cursor", opts.cursor);
2329
+ if (opts?.limit) params.set("limit", String(opts.limit));
2330
+ const qs = params.toString();
2331
+ const url = `${this.baseUrl}/api/v1/plugins${qs ? `?${qs}` : ""}`;
2332
+ return await this.fetchJson(url);
2333
+ }
2334
+ async getPlugin(id) {
2335
+ const url = `${this.baseUrl}/api/v1/plugins/${encodeURIComponent(id)}`;
2336
+ return this.fetchJson(url);
2337
+ }
2338
+ async getVersions(id) {
2339
+ const url = `${this.baseUrl}/api/v1/plugins/${encodeURIComponent(id)}/versions`;
2340
+ return (await this.fetchJson(url)).items;
2341
+ }
2342
+ async downloadBundle(id, version) {
2343
+ const bundleUrl = `${this.baseUrl}/api/v1/plugins/${encodeURIComponent(id)}/versions/${encodeURIComponent(version)}/bundle`;
2344
+ const marketplaceOrigin = new URL(this.baseUrl).origin;
2345
+ const MAX_REDIRECTS = 5;
2346
+ let response;
2347
+ try {
2348
+ let currentUrl = bundleUrl;
2349
+ response = await fetch(currentUrl, { redirect: "manual" });
2350
+ for (let i = 0; i < MAX_REDIRECTS; i++) {
2351
+ if (response.status < 300 || response.status >= 400) break;
2352
+ const location = response.headers.get("location");
2353
+ if (!location) break;
2354
+ const target = new URL(location, currentUrl);
2355
+ if (target.origin !== marketplaceOrigin) throw new MarketplaceError(`Bundle download redirected to untrusted host: ${target.origin}`, response.status, "BUNDLE_REDIRECT_UNTRUSTED");
2356
+ currentUrl = target.href;
2357
+ response = await fetch(currentUrl, { redirect: "manual" });
2358
+ }
2359
+ if (response.status >= 300 && response.status < 400) throw new MarketplaceError(`Bundle download exceeded maximum redirects (${MAX_REDIRECTS})`, response.status, "BUNDLE_TOO_MANY_REDIRECTS");
2360
+ } catch (err) {
2361
+ if (err instanceof MarketplaceError) throw err;
2362
+ throw new MarketplaceUnavailableError(err);
2363
+ }
2364
+ if (!response.ok) throw new MarketplaceError(`Failed to download bundle: ${response.status} ${response.statusText}`, response.status, "BUNDLE_DOWNLOAD_FAILED");
2365
+ const tarballBytes = new Uint8Array(await response.arrayBuffer());
2366
+ try {
2367
+ return await extractBundle(tarballBytes);
2368
+ } catch (err) {
2369
+ if (err instanceof MarketplaceError) throw err;
2370
+ throw new MarketplaceError("Failed to extract plugin bundle", void 0, "BUNDLE_EXTRACT_FAILED");
2371
+ }
2372
+ }
2373
+ async reportInstall(id, version) {
2374
+ const siteHash = await generateSiteHash(this.siteOrigin);
2375
+ const url = `${this.baseUrl}/api/v1/plugins/${encodeURIComponent(id)}/installs`;
2376
+ try {
2377
+ await fetch(url, {
2378
+ method: "POST",
2379
+ headers: { "Content-Type": "application/json" },
2380
+ body: JSON.stringify({
2381
+ siteHash,
2382
+ version
2383
+ })
2384
+ });
2385
+ } catch {}
2386
+ }
2387
+ async searchThemes(query, opts) {
2388
+ const params = new URLSearchParams();
2389
+ if (query) params.set("q", query);
2390
+ if (opts?.keyword) params.set("keyword", opts.keyword);
2391
+ if (opts?.sort) params.set("sort", opts.sort);
2392
+ if (opts?.cursor) params.set("cursor", opts.cursor);
2393
+ if (opts?.limit) params.set("limit", String(opts.limit));
2394
+ const qs = params.toString();
2395
+ const url = `${this.baseUrl}/api/v1/themes${qs ? `?${qs}` : ""}`;
2396
+ return this.fetchJson(url);
2397
+ }
2398
+ async getTheme(id) {
2399
+ const url = `${this.baseUrl}/api/v1/themes/${encodeURIComponent(id)}`;
2400
+ return this.fetchJson(url);
2401
+ }
2402
+ async fetchJson(url) {
2403
+ let response;
2404
+ try {
2405
+ response = await fetch(url, { headers: { Accept: "application/json" } });
2406
+ } catch (err) {
2407
+ throw new MarketplaceUnavailableError(err);
2408
+ }
2409
+ if (!response.ok) {
2410
+ let errorMessage = `Marketplace request failed: ${response.status}`;
2411
+ try {
2412
+ const body = await response.json();
2413
+ if (body.error) errorMessage = body.error;
2414
+ } catch {}
2415
+ throw new MarketplaceError(errorMessage, response.status);
2416
+ }
2417
+ return await response.json();
2418
+ }
2419
+ };
2420
+ /**
2421
+ * Extract manifest + code files from a tarball.
2422
+ *
2423
+ * The tarball is a gzipped tar archive containing:
2424
+ * - manifest.json
2425
+ * - backend.js
2426
+ * - admin.js (optional)
2427
+ *
2428
+ * We use a minimal tar parser since we only need to read a few small files.
2429
+ */
2430
+ /**
2431
+ * Exported so the experimental registry install handler can reuse the
2432
+ * same parse / validate / hash primitive. Despite the file name, this
2433
+ * function predates the marketplace-vs-registry split and is generic
2434
+ * over plugin bundle tarballs regardless of distribution channel.
2435
+ */
2436
+ const MAX_DECOMPRESSED_BUNDLE_BYTES = 256 * 1024;
2437
+ const MAX_BUNDLE_TAR_ENTRIES = 32;
2438
+ async function extractBundle(tarballBytes) {
2439
+ const reader = new ReadableStream({ start(controller) {
2440
+ controller.enqueue(tarballBytes);
2441
+ controller.close();
2442
+ } }).pipeThrough(createGzipDecoder()).getReader();
2443
+ const chunks = [];
2444
+ let total = 0;
2445
+ while (true) {
2446
+ const { done, value } = await reader.read();
2447
+ if (done) break;
2448
+ if (!value) continue;
2449
+ total += value.byteLength;
2450
+ if (total > MAX_DECOMPRESSED_BUNDLE_BYTES) {
2451
+ try {
2452
+ await reader.cancel();
2453
+ } catch {}
2454
+ throw new MarketplaceError(`Bundle decompressed size exceeds limit (${MAX_DECOMPRESSED_BUNDLE_BYTES} bytes)`, void 0, "INVALID_BUNDLE");
2455
+ }
2456
+ chunks.push(value);
2457
+ }
2458
+ const decompressedBytes = new Uint8Array(total);
2459
+ {
2460
+ let offset = 0;
2461
+ for (const chunk of chunks) {
2462
+ decompressedBytes.set(chunk, offset);
2463
+ offset += chunk.byteLength;
2464
+ }
2465
+ }
2466
+ const entries = await unpackTar(new ReadableStream({ start(controller) {
2467
+ controller.enqueue(decompressedBytes);
2468
+ controller.close();
2469
+ } }));
2470
+ if (entries.length > MAX_BUNDLE_TAR_ENTRIES) throw new MarketplaceError(`Bundle has too many tar entries (${entries.length} > ${MAX_BUNDLE_TAR_ENTRIES})`, void 0, "INVALID_BUNDLE");
2471
+ const decoder = new TextDecoder();
2472
+ const files = /* @__PURE__ */ new Map();
2473
+ for (const entry of entries) if (entry.data && entry.header.type === "file") {
2474
+ const name = entry.header.name.replace(LEADING_DOT_SLASH, "");
2475
+ files.set(name, decoder.decode(entry.data));
2476
+ }
2477
+ const manifestJson = files.get("manifest.json");
2478
+ const backendCode = files.get("backend.js");
2479
+ if (!manifestJson) throw new MarketplaceError("Invalid bundle: missing manifest.json", void 0, "INVALID_BUNDLE");
2480
+ if (!backendCode) throw new MarketplaceError("Invalid bundle: missing backend.js", void 0, "INVALID_BUNDLE");
2481
+ let manifest;
2482
+ try {
2483
+ const parsed = JSON.parse(manifestJson);
2484
+ const result = pluginManifestSchema$1.safeParse(parsed);
2485
+ if (!result.success) throw new MarketplaceError("Invalid bundle: manifest.json failed validation", void 0, "INVALID_BUNDLE");
2486
+ manifest = reconcileManifestAccess$1(result.data);
2487
+ } catch (err) {
2488
+ if (err instanceof MarketplaceError) throw err;
2489
+ throw new MarketplaceError("Invalid bundle: malformed manifest.json", void 0, "INVALID_BUNDLE");
2490
+ }
2491
+ const hashBuffer = await crypto.subtle.digest("SHA-256", tarballBytes);
2492
+ const hashArray = new Uint8Array(hashBuffer);
2493
+ const checksum = Array.from(hashArray, (b) => b.toString(16).padStart(2, "0")).join("");
2494
+ return {
2495
+ manifest,
2496
+ backendCode,
2497
+ adminCode: files.get("admin.js"),
2498
+ checksum
2499
+ };
2500
+ }
2501
+ /**
2502
+ * Generate a stable non-identifying site hash from the site origin.
2503
+ * The same origin always produces the same hash, so the marketplace
2504
+ * installs table deduplicates correctly per (plugin_id, site_hash).
2505
+ */
2506
+ async function generateSiteHash(siteOrigin) {
2507
+ const seed = siteOrigin ? `emdash-site:${siteOrigin}` : `emdash-anonymous`;
2508
+ try {
2509
+ const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(seed));
2510
+ const arr = new Uint8Array(hash);
2511
+ return Array.from(arr.slice(0, 8), (b) => b.toString(16).padStart(2, "0")).join("");
2512
+ } catch {
2513
+ let h = 2166136261;
2514
+ for (let i = 0; i < seed.length; i++) {
2515
+ h ^= seed.charCodeAt(i);
2516
+ h = Math.imul(h, 16777619);
2517
+ }
2518
+ const h2 = h ^ h >>> 16;
2519
+ return (h >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
2520
+ }
2521
+ }
2522
+ /**
2523
+ * Create a MarketplaceClient for the given marketplace URL.
2524
+ *
2525
+ * @param baseUrl - The marketplace API base URL (e.g. "https://marketplace.emdashcms.com")
2526
+ * @param siteOrigin - The origin of the EmDash site (e.g. "https://myblog.example.com").
2527
+ * Used to generate a stable, non-identifying site hash for install deduplication.
2528
+ */
2529
+ function createMarketplaceClient(baseUrl, siteOrigin) {
2530
+ return new MarketplaceClientImpl(baseUrl, siteOrigin);
2531
+ }
2532
+
2533
+ //#endregion
2534
+ //#region src/plugins/storage-indexes.ts
2535
+ /**
2536
+ * Generate a deterministic index name.
2537
+ * Unique indexes use a `uidx_` prefix to avoid collisions with regular indexes on the same fields.
2538
+ */
2539
+ function generateIndexName(pluginId, collection, fields, options) {
2540
+ return `${options?.unique ? "uidx" : "idx"}_plugin_${pluginId}_${collection}_${fields.join("_")}`.substring(0, 128);
2541
+ }
2542
+ /**
2543
+ * Generate a Kysely sql expression for creating an expression index.
2544
+ *
2545
+ * Validates all inputs before interpolation. The collection uses the
2546
+ * permissive manifest-key rules rather than SQL-identifier rules — it is
2547
+ * stored as opaque text and only reaches SQL inside the generated index
2548
+ * name — so kebab-case collections index like any other.
2549
+ */
2550
+ function generateCreateIndexSql(db, pluginId, collection, fields, options) {
2551
+ validatePluginIdentifier(pluginId, "plugin ID");
2552
+ validateStorageCollectionName(collection, "collection name");
2553
+ for (const field of fields) validateJsonFieldName(field, "index field name");
2554
+ const indexName = generateIndexName(pluginId, collection, fields, options);
2555
+ const expressions = fields.map((field) => {
2556
+ if (isPostgres(db)) return `(${jsonExtractExpr(db, "data", field)})`;
2557
+ return jsonExtractExpr(db, "data", field);
2558
+ }).join(", ");
2559
+ const createKeyword = options?.unique ? "CREATE UNIQUE INDEX" : "CREATE INDEX";
2560
+ return sql`${sql.raw(createKeyword)} IF NOT EXISTS ${sql.ref(indexName)}
2561
+ ON _plugin_storage(plugin_id, collection, ${sql.raw(expressions)})
2562
+ `;
2563
+ }
2564
+ /**
2565
+ * Generate a Kysely sql expression for dropping an index.
2566
+ *
2567
+ * Uses sql.ref() for safe identifier quoting.
2568
+ */
2569
+ function generateDropIndexSql(indexName) {
2570
+ return sql`DROP INDEX IF EXISTS ${sql.ref(indexName)}`;
2571
+ }
2572
+ /**
2573
+ * Normalize index declarations to arrays of field arrays
2574
+ */
2575
+ function normalizeIndexes(indexes) {
2576
+ return indexes.map((index) => Array.isArray(index) ? index : [index]);
2577
+ }
2578
+ /**
2579
+ * Create all declared indexes for a plugin collection
2580
+ */
2581
+ async function createStorageIndexes(db, pluginId, collection, indexes, options) {
2582
+ const normalized = normalizeIndexes(indexes);
2583
+ const uniqueNormalized = options?.uniqueIndexes ? normalizeIndexes(options.uniqueIndexes) : [];
2584
+ const uniqueSet = new Set(uniqueNormalized.map((f) => f.join(",")));
2585
+ const allEntries = [...normalized.filter((f) => !uniqueSet.has(f.join(","))).map((fields) => ({
2586
+ fields,
2587
+ unique: false
2588
+ })), ...uniqueNormalized.map((fields) => ({
2589
+ fields,
2590
+ unique: true
2591
+ }))];
2592
+ const created = [];
2593
+ const errors = [];
2594
+ for (const entry of allEntries) {
2595
+ const { fields } = entry;
2596
+ const indexName = generateIndexName(pluginId, collection, fields, { unique: entry.unique });
2597
+ try {
2598
+ await generateCreateIndexSql(db, pluginId, collection, fields, { unique: entry.unique }).execute(db);
2599
+ await db.insertInto("_plugin_indexes").values({
2600
+ plugin_id: pluginId,
2601
+ collection,
2602
+ index_name: indexName,
2603
+ fields: JSON.stringify(fields)
2604
+ }).onConflict((oc) => oc.columns([
2605
+ "plugin_id",
2606
+ "collection",
2607
+ "index_name"
2608
+ ]).doUpdateSet({ fields: JSON.stringify(fields) })).execute();
2609
+ created.push(indexName);
2610
+ } catch (error) {
2611
+ errors.push({
2612
+ index: indexName,
2613
+ error: error instanceof Error ? error.message : String(error)
2614
+ });
2615
+ }
2616
+ }
2617
+ return {
2618
+ created,
2619
+ errors
2620
+ };
2621
+ }
2622
+ /**
2623
+ * Remove indexes that are no longer declared
2624
+ */
2625
+ async function removeOrphanedIndexes(db, pluginId, collection, currentIndexes, options) {
2626
+ const normalized = normalizeIndexes(currentIndexes);
2627
+ const uniqueNormalized = options?.uniqueIndexes ? normalizeIndexes(options.uniqueIndexes) : [];
2628
+ const uniqueSet = new Set(uniqueNormalized.map((f) => f.join(",")));
2629
+ const currentIndexNames = /* @__PURE__ */ new Set();
2630
+ for (const fields of normalized) if (!uniqueSet.has(fields.join(","))) currentIndexNames.add(generateIndexName(pluginId, collection, fields));
2631
+ for (const fields of uniqueNormalized) currentIndexNames.add(generateIndexName(pluginId, collection, fields, { unique: true }));
2632
+ const existingIndexes = await db.selectFrom("_plugin_indexes").select(["index_name"]).where("plugin_id", "=", pluginId).where("collection", "=", collection).execute();
2633
+ const removed = [];
2634
+ const errors = [];
2635
+ for (const { index_name } of existingIndexes) if (!currentIndexNames.has(index_name)) try {
2636
+ await generateDropIndexSql(index_name).execute(db);
2637
+ await db.deleteFrom("_plugin_indexes").where("plugin_id", "=", pluginId).where("collection", "=", collection).where("index_name", "=", index_name).execute();
2638
+ removed.push(index_name);
2639
+ } catch (error) {
2640
+ errors.push({
2641
+ index: index_name,
2642
+ error: error instanceof Error ? error.message : String(error)
2643
+ });
2644
+ }
2645
+ return {
2646
+ removed,
2647
+ errors
2648
+ };
2649
+ }
2650
+ /**
2651
+ * Sync indexes for a plugin collection (create new, remove old)
2652
+ */
2653
+ async function syncStorageIndexes(db, pluginId, collection, indexes, options) {
2654
+ const [createResult, removeResult] = await Promise.all([createStorageIndexes(db, pluginId, collection, indexes, options), removeOrphanedIndexes(db, pluginId, collection, indexes, options)]);
2655
+ return {
2656
+ created: createResult.created,
2657
+ removed: removeResult.removed,
2658
+ errors: [...createResult.errors, ...removeResult.errors]
2659
+ };
2660
+ }
2661
+ /**
2662
+ * Materialize the storage indexes a set of plugins declare in their
2663
+ * manifests. Failures are logged per collection and never thrown — a missing
2664
+ * index affects query performance, not correctness, so it must not fail an
2665
+ * install or a scheduler tick.
2666
+ */
2667
+ async function syncDeclaredStorageIndexes(db, plugins) {
2668
+ for (const plugin of plugins) for (const [collection, config] of Object.entries(plugin.storage ?? {})) try {
2669
+ const result = await syncStorageIndexes(db, plugin.id, collection, config.indexes, { uniqueIndexes: config.uniqueIndexes });
2670
+ for (const failure of result.errors) console.error(`[plugins] Failed to sync storage index ${failure.index} for ${plugin.id}/${collection}: ${failure.error}`);
2671
+ } catch (error) {
2672
+ console.error(`[plugins] Failed to sync storage indexes for ${plugin.id}/${collection}:`, error);
2673
+ }
2674
+ }
2675
+ /**
2676
+ * Remove all indexes for a plugin
2677
+ */
2678
+ async function removeAllPluginIndexes(db, pluginId) {
2679
+ const existingIndexes = await db.selectFrom("_plugin_indexes").select(["index_name", "collection"]).where("plugin_id", "=", pluginId).execute();
2680
+ const removed = [];
2681
+ const errors = [];
2682
+ for (const { index_name } of existingIndexes) try {
2683
+ await generateDropIndexSql(index_name).execute(db);
2684
+ removed.push(index_name);
2685
+ } catch (error) {
2686
+ errors.push({
2687
+ index: index_name,
2688
+ error: error instanceof Error ? error.message : String(error)
2689
+ });
2690
+ }
2691
+ await db.deleteFrom("_plugin_indexes").where("plugin_id", "=", pluginId).execute();
2692
+ return {
2693
+ removed,
2694
+ errors
2695
+ };
2696
+ }
2697
+
2698
+ //#endregion
2699
+ //#region src/api/handlers/marketplace.ts
2700
+ /** Semver-like pattern: digits, dots, hyphens, plus signs (e.g. 1.0.0, 1.0.0-beta.1) */
2701
+ const VERSION_PATTERN = /^[a-z0-9][a-z0-9._+-]*$/i;
2702
+ function validateVersion(version) {
2703
+ if (version.includes("..")) throw new Error("Invalid version format");
2704
+ if (!VERSION_PATTERN.test(version)) throw new Error("Invalid version format");
2705
+ }
2706
+ function getClient(marketplaceUrl, siteOrigin) {
2707
+ if (!marketplaceUrl) return null;
2708
+ return createMarketplaceClient(marketplaceUrl, siteOrigin);
2709
+ }
2710
+ function diffCapabilities(oldCaps, newCaps) {
2711
+ const oldNorm = normalizeCapabilities(oldCaps);
2712
+ const newNorm = normalizeCapabilities(newCaps);
2713
+ const oldSet = new Set(oldNorm);
2714
+ const newSet = new Set(newNorm);
2715
+ return {
2716
+ added: newNorm.filter((c) => !oldSet.has(c)),
2717
+ removed: oldNorm.filter((c) => !newSet.has(c))
2718
+ };
2719
+ }
2720
+ /**
2721
+ * Diff route visibility between two manifests.
2722
+ * Returns routes that changed from private to public (newly exposed).
2723
+ */
2724
+ function diffRouteVisibility(oldManifest, newManifest) {
2725
+ const oldPublicRoutes = /* @__PURE__ */ new Set();
2726
+ if (oldManifest) for (const entry of oldManifest.routes) {
2727
+ const normalized = normalizeManifestRoute$1(entry);
2728
+ if (normalized.public === true) oldPublicRoutes.add(normalized.name);
2729
+ }
2730
+ const newlyPublic = [];
2731
+ for (const entry of newManifest.routes) {
2732
+ const normalized = normalizeManifestRoute$1(entry);
2733
+ if (normalized.public === true && !oldPublicRoutes.has(normalized.name)) newlyPublic.push(normalized.name);
2734
+ }
2735
+ return { newlyPublic };
2736
+ }
2737
+ async function resolveVersionMetadata(client, pluginId, pluginDetail, version) {
2738
+ if (pluginDetail.latestVersion?.version === version) return {
2739
+ version: pluginDetail.latestVersion.version,
2740
+ minEmDashVersion: pluginDetail.latestVersion.minEmDashVersion,
2741
+ bundleSize: pluginDetail.latestVersion.bundleSize,
2742
+ checksum: pluginDetail.latestVersion.checksum,
2743
+ changelog: pluginDetail.latestVersion.changelog,
2744
+ capabilities: pluginDetail.latestVersion.capabilities,
2745
+ status: pluginDetail.latestVersion.status,
2746
+ auditVerdict: pluginDetail.latestVersion.audit?.verdict ?? null,
2747
+ imageAuditVerdict: pluginDetail.latestVersion.imageAudit?.verdict ?? null,
2748
+ publishedAt: pluginDetail.latestVersion.publishedAt
2749
+ };
2750
+ return (await client.getVersions(pluginId)).find((v) => v.version === version) ?? null;
2751
+ }
2752
+ function validateBundleIdentity(bundle, pluginId, version) {
2753
+ if (bundle.manifest.id !== pluginId) return {
2754
+ success: false,
2755
+ error: {
2756
+ code: "MANIFEST_MISMATCH",
2757
+ message: `Bundle manifest ID (${bundle.manifest.id}) does not match requested plugin (${pluginId})`
2758
+ }
2759
+ };
2760
+ if (bundle.manifest.version !== version) return {
2761
+ success: false,
2762
+ error: {
2763
+ code: "MANIFEST_VERSION_MISMATCH",
2764
+ message: `Bundle manifest version (${bundle.manifest.version}) does not match requested version (${version})`
2765
+ }
2766
+ };
2767
+ return null;
2768
+ }
2769
+ function bundlePrefix(source, pluginId, version) {
2770
+ return `${source}/${pluginId}/${version}`;
2771
+ }
2772
+ async function storeBundleInR2(storage, pluginId, version, bundle, source = "marketplace") {
2773
+ validatePluginIdentifier(pluginId, "plugin ID");
2774
+ validateVersion(version);
2775
+ const prefix = bundlePrefix(source, pluginId, version);
2776
+ await storage.upload({
2777
+ key: `${prefix}/manifest.json`,
2778
+ body: new TextEncoder().encode(JSON.stringify(bundle.manifest)),
2779
+ contentType: "application/json"
2780
+ });
2781
+ await storage.upload({
2782
+ key: `${prefix}/backend.js`,
2783
+ body: new TextEncoder().encode(bundle.backendCode),
2784
+ contentType: "application/javascript"
2785
+ });
2786
+ if (bundle.adminCode) await storage.upload({
2787
+ key: `${prefix}/admin.js`,
2788
+ body: new TextEncoder().encode(bundle.adminCode),
2789
+ contentType: "application/javascript"
2790
+ });
2791
+ }
2792
+ /** Read a ReadableStream to string */
2793
+ async function streamToText(stream) {
2794
+ return new Response(stream).text();
2795
+ }
2796
+ /**
2797
+ * Load a plugin bundle from site-local R2 storage.
2798
+ *
2799
+ * `source` selects the R2 key prefix: marketplace plugins are stored
2800
+ * under `marketplace/<id>/<version>/`, registry plugins under
2801
+ * `registry/<id>/<version>/`. Defaults to `"marketplace"` for
2802
+ * backwards compatibility with pre-registry call sites.
2803
+ */
2804
+ async function loadBundleFromR2(storage, pluginId, version, source = "marketplace") {
2805
+ validatePluginIdentifier(pluginId, "plugin ID");
2806
+ validateVersion(version);
2807
+ const prefix = bundlePrefix(source, pluginId, version);
2808
+ try {
2809
+ const manifestResult = await storage.download(`${prefix}/manifest.json`);
2810
+ const backendResult = await storage.download(`${prefix}/backend.js`);
2811
+ const manifestText = await streamToText(manifestResult.body);
2812
+ const backendCode = await streamToText(backendResult.body);
2813
+ const parsed = JSON.parse(manifestText);
2814
+ const result = pluginManifestSchema$1.safeParse(parsed);
2815
+ if (!result.success) return null;
2816
+ const manifest = reconcileManifestAccess$1(result.data);
2817
+ let adminCode;
2818
+ try {
2819
+ adminCode = await streamToText((await storage.download(`${prefix}/admin.js`)).body);
2820
+ } catch {}
2821
+ return {
2822
+ manifest,
2823
+ backendCode,
2824
+ adminCode
2825
+ };
2826
+ } catch {
2827
+ return null;
2828
+ }
2829
+ }
2830
+ /** Delete a plugin bundle from site-local R2 storage */
2831
+ async function deleteBundleFromR2(storage, pluginId, version, source = "marketplace") {
2832
+ validatePluginIdentifier(pluginId, "plugin ID");
2833
+ validateVersion(version);
2834
+ const prefix = bundlePrefix(source, pluginId, version);
2835
+ for (const file of [
2836
+ "manifest.json",
2837
+ "backend.js",
2838
+ "admin.js"
2839
+ ]) try {
2840
+ await storage.delete(`${prefix}/${file}`);
2841
+ } catch {}
2842
+ }
2843
+ async function rollbackPluginUpdate(db, storage, previousState, failedVersion, source) {
2844
+ if (!storage) return {
2845
+ success: false,
2846
+ error: {
2847
+ code: "STORAGE_NOT_CONFIGURED",
2848
+ message: "Storage is required"
2849
+ }
2850
+ };
2851
+ if (previousState.source !== source) return {
2852
+ success: false,
2853
+ error: {
2854
+ code: "UPDATE_ROLLBACK_CONFLICT",
2855
+ message: "Plugin source changed during update"
2856
+ }
2857
+ };
2858
+ try {
2859
+ if (!await new PluginStateRepository(db).restoreIfVersion(failedVersion, previousState)) return {
2860
+ success: false,
2861
+ error: {
2862
+ code: "UPDATE_ROLLBACK_CONFLICT",
2863
+ message: "Plugin state changed before the failed update could be rolled back"
2864
+ }
2865
+ };
2866
+ await deleteBundleFromR2(storage, previousState.pluginId, failedVersion, source);
2867
+ return {
2868
+ success: true,
2869
+ data: {
2870
+ pluginId: previousState.pluginId,
2871
+ version: previousState.version
2872
+ }
2873
+ };
2874
+ } catch (error) {
2875
+ console.error("Failed to roll back plugin update:", error);
2876
+ return {
2877
+ success: false,
2878
+ error: {
2879
+ code: "UPDATE_ROLLBACK_FAILED",
2880
+ message: "Failed to roll back plugin update"
2881
+ }
2882
+ };
2883
+ }
2884
+ }
2885
+ async function handleMarketplaceInstall(db, storage, sandboxRunner, marketplaceUrl, pluginId, opts) {
2886
+ const client = getClient(marketplaceUrl, opts?.siteOrigin);
2887
+ if (!client) return {
2888
+ success: false,
2889
+ error: {
2890
+ code: "MARKETPLACE_NOT_CONFIGURED",
2891
+ message: "Marketplace is not configured"
2892
+ }
2893
+ };
2894
+ if (!storage) return {
2895
+ success: false,
2896
+ error: {
2897
+ code: "STORAGE_NOT_CONFIGURED",
2898
+ message: "Storage is required for marketplace plugin installation"
2899
+ }
2900
+ };
2901
+ if (!opts?.sandboxBypassed && (!sandboxRunner || !sandboxRunner.isAvailable())) return {
2902
+ success: false,
2903
+ error: {
2904
+ code: "SANDBOX_NOT_AVAILABLE",
2905
+ message: withUnavailableReason("Sandbox runner is required for marketplace plugins", sandboxRunner)
2906
+ }
2907
+ };
2908
+ try {
2909
+ const stateRepo = new PluginStateRepository(db);
2910
+ const existing = await stateRepo.get(pluginId);
2911
+ if (existing && existing.source === "marketplace") return {
2912
+ success: false,
2913
+ error: {
2914
+ code: "ALREADY_INSTALLED",
2915
+ message: `Plugin ${pluginId} is already installed`
2916
+ }
2917
+ };
2918
+ if (opts?.configuredPluginIds?.has(pluginId)) return {
2919
+ success: false,
2920
+ error: {
2921
+ code: "PLUGIN_ID_CONFLICT",
2922
+ message: `Cannot install marketplace plugin "${pluginId}" — a configured plugin with the same ID already exists`
2923
+ }
2924
+ };
2925
+ const pluginDetail = await client.getPlugin(pluginId);
2926
+ const version = opts?.version ?? pluginDetail.latestVersion?.version;
2927
+ if (!version) return {
2928
+ success: false,
2929
+ error: {
2930
+ code: "NO_VERSION",
2931
+ message: `No published versions found for plugin ${pluginId}`
2932
+ }
2933
+ };
2934
+ const versionMetadata = await resolveVersionMetadata(client, pluginId, pluginDetail, version);
2935
+ if (!versionMetadata) return {
2936
+ success: false,
2937
+ error: {
2938
+ code: "NO_VERSION",
2939
+ message: `Version ${version} was not found for plugin ${pluginId}`
2940
+ }
2941
+ };
2942
+ if (versionMetadata.auditVerdict === "fail" || versionMetadata.auditVerdict === "warn") return {
2943
+ success: false,
2944
+ error: {
2945
+ code: "AUDIT_FAILED",
2946
+ message: versionMetadata.auditVerdict === "fail" ? "Plugin failed security audit and cannot be installed" : "Plugin audit was inconclusive and cannot be installed until reviewed"
2947
+ }
2948
+ };
2949
+ const bundle = await client.downloadBundle(pluginId, version);
2950
+ if (versionMetadata.checksum && bundle.checksum !== versionMetadata.checksum) return {
2951
+ success: false,
2952
+ error: {
2953
+ code: "CHECKSUM_MISMATCH",
2954
+ message: "Bundle checksum does not match marketplace record. Download may be corrupted."
2955
+ }
2956
+ };
2957
+ const bundleIdentityError = validateBundleIdentity(bundle, pluginId, version);
2958
+ if (bundleIdentityError) return bundleIdentityError;
2959
+ const routeVisibilityChanges = diffRouteVisibility(void 0, bundle.manifest);
2960
+ const hasPublicRoutes = routeVisibilityChanges.newlyPublic.length > 0;
2961
+ const publicRoutes = routeVisibilityChanges.newlyPublic.toSorted();
2962
+ const acknowledgedPublicRoutes = (opts?.acknowledgedPublicRoutes ?? []).toSorted();
2963
+ const mcpTools = bundle.manifest.mcp?.tools.map(({ inputSchema: _, outputSchema: __, ...tool }) => tool);
2964
+ const consentDetails = {
2965
+ routeVisibilityChanges: hasPublicRoutes ? { newlyPublic: publicRoutes } : void 0,
2966
+ mcpTools
2967
+ };
2968
+ if (hasPublicRoutes && JSON.stringify(acknowledgedPublicRoutes) !== JSON.stringify(publicRoutes)) return {
2969
+ success: false,
2970
+ error: {
2971
+ code: "ROUTE_VISIBILITY_ESCALATION",
2972
+ message: "Plugin install exposes public (unauthenticated) routes",
2973
+ details: consentDetails
2974
+ }
2975
+ };
2976
+ if ((mcpTools?.length ?? 0) > 0 && !opts?.confirmMcpTools) return {
2977
+ success: false,
2978
+ error: {
2979
+ code: "MCP_TOOL_CONSENT_REQUIRED",
2980
+ message: "Plugin MCP tools require explicit consent",
2981
+ details: consentDetails
2982
+ }
2983
+ };
2984
+ await storeBundleInR2(storage, pluginId, version, bundle);
2985
+ await stateRepo.upsert(pluginId, version, "active", {
2986
+ source: "marketplace",
2987
+ marketplaceVersion: version,
2988
+ displayName: pluginDetail.name,
2989
+ description: pluginDetail.description ?? void 0
2990
+ });
2991
+ await syncDeclaredStorageIndexes(db, [bundle.manifest]);
2992
+ client.reportInstall(pluginId, version).catch(() => {});
2993
+ return {
2994
+ success: true,
2995
+ data: {
2996
+ pluginId,
2997
+ version,
2998
+ capabilities: bundle.manifest.capabilities
2999
+ }
3000
+ };
3001
+ } catch (err) {
3002
+ if (err instanceof MarketplaceUnavailableError) return {
3003
+ success: false,
3004
+ error: {
3005
+ code: "MARKETPLACE_UNAVAILABLE",
3006
+ message: "Plugin marketplace is currently unavailable"
3007
+ }
3008
+ };
3009
+ if (err instanceof MarketplaceError) return {
3010
+ success: false,
3011
+ error: {
3012
+ code: err.code ?? "MARKETPLACE_ERROR",
3013
+ message: err.message
3014
+ }
3015
+ };
3016
+ if (err instanceof EmDashStorageError) return {
3017
+ success: false,
3018
+ error: {
3019
+ code: err.code ?? "STORAGE_ERROR",
3020
+ message: "Storage error while installing plugin"
3021
+ }
3022
+ };
3023
+ if (err && typeof err === "object" && "code" in err) {
3024
+ const code = err.code;
3025
+ if (typeof code === "string" && code.trim()) return {
3026
+ success: false,
3027
+ error: {
3028
+ code,
3029
+ message: "Failed to install plugin from marketplace"
3030
+ }
3031
+ };
3032
+ }
3033
+ console.error("Failed to install marketplace plugin:", err);
3034
+ return {
3035
+ success: false,
3036
+ error: {
3037
+ code: "INSTALL_FAILED",
3038
+ message: "Failed to install plugin from marketplace"
3039
+ }
3040
+ };
3041
+ }
3042
+ }
3043
+ async function handleMarketplaceUpdate(db, storage, sandboxRunner, marketplaceUrl, pluginId, opts) {
3044
+ const client = getClient(marketplaceUrl);
3045
+ if (!client) return {
3046
+ success: false,
3047
+ error: {
3048
+ code: "MARKETPLACE_NOT_CONFIGURED",
3049
+ message: "Marketplace is not configured"
3050
+ }
3051
+ };
3052
+ if (!storage) return {
3053
+ success: false,
3054
+ error: {
3055
+ code: "STORAGE_NOT_CONFIGURED",
3056
+ message: "Storage is required"
3057
+ }
3058
+ };
3059
+ if (!opts?.sandboxBypassed && (!sandboxRunner || !sandboxRunner.isAvailable())) return {
3060
+ success: false,
3061
+ error: {
3062
+ code: "SANDBOX_NOT_AVAILABLE",
3063
+ message: withUnavailableReason("Sandbox runner is required", sandboxRunner)
3064
+ }
3065
+ };
3066
+ try {
3067
+ const stateRepo = new PluginStateRepository(db);
3068
+ const existing = await stateRepo.get(pluginId);
3069
+ if (!existing || existing.source !== "marketplace") return {
3070
+ success: false,
3071
+ error: {
3072
+ code: "NOT_FOUND",
3073
+ message: `No marketplace plugin found: ${pluginId}`
3074
+ }
3075
+ };
3076
+ const oldVersion = existing.marketplaceVersion ?? existing.version;
3077
+ const pluginDetail = await client.getPlugin(pluginId);
3078
+ const newVersion = opts?.version ?? pluginDetail.latestVersion?.version;
3079
+ if (!newVersion) return {
3080
+ success: false,
3081
+ error: {
3082
+ code: "NO_VERSION",
3083
+ message: "No newer version available"
3084
+ }
3085
+ };
3086
+ if (newVersion === oldVersion) return {
3087
+ success: false,
3088
+ error: {
3089
+ code: "ALREADY_UP_TO_DATE",
3090
+ message: "Plugin is already up to date"
3091
+ }
3092
+ };
3093
+ const versionMetadata = await resolveVersionMetadata(client, pluginId, pluginDetail, newVersion);
3094
+ if (!versionMetadata) return {
3095
+ success: false,
3096
+ error: {
3097
+ code: "NO_VERSION",
3098
+ message: `Version ${newVersion} was not found for plugin ${pluginId}`
3099
+ }
3100
+ };
3101
+ const bundle = await client.downloadBundle(pluginId, newVersion);
3102
+ if (versionMetadata.checksum && bundle.checksum !== versionMetadata.checksum) return {
3103
+ success: false,
3104
+ error: {
3105
+ code: "CHECKSUM_MISMATCH",
3106
+ message: "Bundle checksum does not match marketplace record. Download may be corrupted."
3107
+ }
3108
+ };
3109
+ const bundleIdentityError = validateBundleIdentity(bundle, pluginId, newVersion);
3110
+ if (bundleIdentityError) return bundleIdentityError;
3111
+ const oldBundle = await loadBundleFromR2(storage, pluginId, oldVersion);
3112
+ const capabilityChanges = diffCapabilities(oldBundle?.manifest.capabilities ?? [], bundle.manifest.capabilities);
3113
+ const hasEscalation = capabilityChanges.added.length > 0;
3114
+ const routeVisibilityChanges = diffRouteVisibility(oldBundle?.manifest, bundle.manifest);
3115
+ const hasNewPublicRoutes = routeVisibilityChanges.newlyPublic.length > 0;
3116
+ const newlyPublicRoutes = routeVisibilityChanges.newlyPublic.toSorted();
3117
+ const acknowledgedPublicRoutes = (opts?.acknowledgedPublicRoutes ?? []).toSorted();
3118
+ const oldMcpTools = [...oldBundle?.manifest.mcp?.tools ?? []].toSorted((a, b) => a.name.localeCompare(b.name));
3119
+ const newMcpTools = [...bundle.manifest.mcp?.tools ?? []].toSorted((a, b) => a.name.localeCompare(b.name));
3120
+ const hasMcpChanges = JSON.stringify(oldMcpTools) !== JSON.stringify(newMcpTools);
3121
+ const mcpTools = newMcpTools.map(({ inputSchema: _, outputSchema: __, ...tool }) => tool);
3122
+ const consentDetails = {
3123
+ capabilityChanges,
3124
+ routeVisibilityChanges: hasNewPublicRoutes ? { newlyPublic: newlyPublicRoutes } : void 0,
3125
+ mcpTools: hasMcpChanges ? mcpTools : void 0
3126
+ };
3127
+ if (hasEscalation && !opts?.confirmCapabilityChanges) return {
3128
+ success: false,
3129
+ error: {
3130
+ code: "CAPABILITY_ESCALATION",
3131
+ message: "Plugin update requires new capabilities",
3132
+ details: consentDetails
3133
+ }
3134
+ };
3135
+ if (hasNewPublicRoutes && JSON.stringify(acknowledgedPublicRoutes) !== JSON.stringify(newlyPublicRoutes)) return {
3136
+ success: false,
3137
+ error: {
3138
+ code: "ROUTE_VISIBILITY_ESCALATION",
3139
+ message: "Plugin update exposes new public (unauthenticated) routes",
3140
+ details: consentDetails
3141
+ }
3142
+ };
3143
+ if (hasMcpChanges && !opts?.confirmMcpTools) return {
3144
+ success: false,
3145
+ error: {
3146
+ code: "MCP_TOOL_CONSENT_REQUIRED",
3147
+ message: "Plugin update changes its MCP tools",
3148
+ details: consentDetails
3149
+ }
3150
+ };
3151
+ await storeBundleInR2(storage, pluginId, newVersion, bundle);
3152
+ await stateRepo.upsert(pluginId, newVersion, "active", {
3153
+ source: "marketplace",
3154
+ marketplaceVersion: newVersion,
3155
+ displayName: pluginDetail.name,
3156
+ description: pluginDetail.description ?? void 0,
3157
+ mcpToolsEnabled: false,
3158
+ mcpToolsConsent: null
3159
+ });
3160
+ await syncDeclaredStorageIndexes(db, [bundle.manifest]);
3161
+ return {
3162
+ success: true,
3163
+ data: {
3164
+ pluginId,
3165
+ oldVersion,
3166
+ newVersion,
3167
+ capabilityChanges,
3168
+ routeVisibilityChanges: hasNewPublicRoutes ? routeVisibilityChanges : void 0
3169
+ }
3170
+ };
3171
+ } catch (err) {
3172
+ if (err instanceof MarketplaceUnavailableError) return {
3173
+ success: false,
3174
+ error: {
3175
+ code: "MARKETPLACE_UNAVAILABLE",
3176
+ message: "Marketplace is unavailable"
3177
+ }
3178
+ };
3179
+ if (err instanceof MarketplaceError) return {
3180
+ success: false,
3181
+ error: {
3182
+ code: err.code ?? "MARKETPLACE_ERROR",
3183
+ message: err.message
3184
+ }
3185
+ };
3186
+ console.error("Failed to update marketplace plugin:", err);
3187
+ return {
3188
+ success: false,
3189
+ error: {
3190
+ code: "UPDATE_FAILED",
3191
+ message: "Failed to update plugin"
3192
+ }
3193
+ };
3194
+ }
3195
+ }
3196
+ async function handleMarketplaceUninstall(db, storage, pluginId, opts) {
3197
+ try {
3198
+ const stateRepo = new PluginStateRepository(db);
3199
+ const existing = await stateRepo.get(pluginId);
3200
+ if (!existing || existing.source !== "marketplace") return {
3201
+ success: false,
3202
+ error: {
3203
+ code: "NOT_FOUND",
3204
+ message: `No marketplace plugin found: ${pluginId}`
3205
+ }
3206
+ };
3207
+ const version = existing.marketplaceVersion ?? existing.version;
3208
+ await opts?.beforeDelete?.();
3209
+ let dataDeleted = false;
3210
+ if (opts?.deleteData) try {
3211
+ await db.deleteFrom("_plugin_storage").where("plugin_id", "=", pluginId).execute();
3212
+ dataDeleted = true;
3213
+ } catch {}
3214
+ try {
3215
+ await removeAllPluginIndexes(db, pluginId);
3216
+ } catch {}
3217
+ await stateRepo.delete(pluginId);
3218
+ if (storage) await deleteBundleFromR2(storage, pluginId, version);
3219
+ return {
3220
+ success: true,
3221
+ data: {
3222
+ pluginId,
3223
+ dataDeleted
3224
+ }
3225
+ };
3226
+ } catch (err) {
3227
+ console.error("Failed to uninstall marketplace plugin:", err);
3228
+ return {
3229
+ success: false,
3230
+ error: {
3231
+ code: "UNINSTALL_FAILED",
3232
+ message: "Failed to uninstall plugin"
3233
+ }
3234
+ };
3235
+ }
3236
+ }
3237
+ async function handleMarketplaceUpdateCheck(db, marketplaceUrl) {
3238
+ const client = getClient(marketplaceUrl);
3239
+ if (!client) return {
3240
+ success: false,
3241
+ error: {
3242
+ code: "MARKETPLACE_NOT_CONFIGURED",
3243
+ message: "Marketplace is not configured"
3244
+ }
3245
+ };
3246
+ try {
3247
+ const marketplacePlugins = await new PluginStateRepository(db).getMarketplacePlugins();
3248
+ const items = [];
3249
+ for (const plugin of marketplacePlugins) try {
3250
+ const detail = await client.getPlugin(plugin.pluginId);
3251
+ const latest = detail.latestVersion?.version;
3252
+ const installed = plugin.marketplaceVersion ?? plugin.version;
3253
+ if (!latest) continue;
3254
+ const hasUpdate = latest !== installed;
3255
+ let capabilityChanges;
3256
+ let hasCapabilityChanges = false;
3257
+ if (hasUpdate && detail.latestVersion) {
3258
+ capabilityChanges = diffCapabilities(detail.capabilities ?? [], detail.latestVersion.capabilities ?? []);
3259
+ hasCapabilityChanges = capabilityChanges.added.length > 0 || capabilityChanges.removed.length > 0;
3260
+ }
3261
+ items.push({
3262
+ pluginId: plugin.pluginId,
3263
+ installed,
3264
+ latest: latest ?? installed,
3265
+ hasUpdate,
3266
+ hasCapabilityChanges,
3267
+ capabilityChanges: hasCapabilityChanges ? capabilityChanges : void 0,
3268
+ hasRouteVisibilityChanges: false
3269
+ });
3270
+ } catch (err) {
3271
+ console.warn(`Failed to check updates for ${plugin.pluginId}:`, err);
3272
+ }
3273
+ return {
3274
+ success: true,
3275
+ data: { items }
3276
+ };
3277
+ } catch (err) {
3278
+ if (err instanceof MarketplaceUnavailableError) return {
3279
+ success: false,
3280
+ error: {
3281
+ code: "MARKETPLACE_UNAVAILABLE",
3282
+ message: "Marketplace is unavailable"
3283
+ }
3284
+ };
3285
+ console.error("Failed to check marketplace updates:", err);
3286
+ return {
3287
+ success: false,
3288
+ error: {
3289
+ code: "UPDATE_CHECK_FAILED",
3290
+ message: "Failed to check for updates"
3291
+ }
3292
+ };
3293
+ }
3294
+ }
3295
+ async function handleMarketplaceSearch(marketplaceUrl, query, opts) {
3296
+ const client = getClient(marketplaceUrl);
3297
+ if (!client) return {
3298
+ success: false,
3299
+ error: {
3300
+ code: "MARKETPLACE_NOT_CONFIGURED",
3301
+ message: "Marketplace is not configured"
3302
+ }
3303
+ };
3304
+ try {
3305
+ return {
3306
+ success: true,
3307
+ data: await client.search(query, opts)
3308
+ };
3309
+ } catch (err) {
3310
+ if (err instanceof MarketplaceUnavailableError) return {
3311
+ success: false,
3312
+ error: {
3313
+ code: "MARKETPLACE_UNAVAILABLE",
3314
+ message: "Marketplace is unavailable"
3315
+ }
3316
+ };
3317
+ console.error("Failed to search marketplace:", err);
3318
+ return {
3319
+ success: false,
3320
+ error: {
3321
+ code: "SEARCH_FAILED",
3322
+ message: "Failed to search marketplace"
3323
+ }
3324
+ };
3325
+ }
3326
+ }
3327
+ async function handleMarketplaceGetPlugin(marketplaceUrl, pluginId) {
3328
+ const client = getClient(marketplaceUrl);
3329
+ if (!client) return {
3330
+ success: false,
3331
+ error: {
3332
+ code: "MARKETPLACE_NOT_CONFIGURED",
3333
+ message: "Marketplace is not configured"
3334
+ }
3335
+ };
3336
+ try {
3337
+ return {
3338
+ success: true,
3339
+ data: await client.getPlugin(pluginId)
3340
+ };
3341
+ } catch (err) {
3342
+ if (err instanceof MarketplaceError && err.status === 404) return {
3343
+ success: false,
3344
+ error: {
3345
+ code: "NOT_FOUND",
3346
+ message: `Plugin not found: ${pluginId}`
3347
+ }
3348
+ };
3349
+ if (err instanceof MarketplaceUnavailableError) return {
3350
+ success: false,
3351
+ error: {
3352
+ code: "MARKETPLACE_UNAVAILABLE",
3353
+ message: "Marketplace is unavailable"
3354
+ }
3355
+ };
3356
+ console.error("Failed to get marketplace plugin:", err);
3357
+ return {
3358
+ success: false,
3359
+ error: {
3360
+ code: "GET_PLUGIN_FAILED",
3361
+ message: "Failed to get plugin details"
3362
+ }
3363
+ };
3364
+ }
3365
+ }
3366
+ async function handleThemeSearch(marketplaceUrl, query, opts) {
3367
+ const client = getClient(marketplaceUrl);
3368
+ if (!client) return {
3369
+ success: false,
3370
+ error: {
3371
+ code: "MARKETPLACE_NOT_CONFIGURED",
3372
+ message: "Marketplace is not configured"
3373
+ }
3374
+ };
3375
+ try {
3376
+ return {
3377
+ success: true,
3378
+ data: await client.searchThemes(query, opts)
3379
+ };
3380
+ } catch (err) {
3381
+ if (err instanceof MarketplaceUnavailableError) return {
3382
+ success: false,
3383
+ error: {
3384
+ code: "MARKETPLACE_UNAVAILABLE",
3385
+ message: "Marketplace is unavailable"
3386
+ }
3387
+ };
3388
+ console.error("Failed to search themes:", err);
3389
+ return {
3390
+ success: false,
3391
+ error: {
3392
+ code: "THEME_SEARCH_FAILED",
3393
+ message: "Failed to search themes"
3394
+ }
3395
+ };
3396
+ }
3397
+ }
3398
+ async function handleThemeGetDetail(marketplaceUrl, themeId) {
3399
+ const client = getClient(marketplaceUrl);
3400
+ if (!client) return {
3401
+ success: false,
3402
+ error: {
3403
+ code: "MARKETPLACE_NOT_CONFIGURED",
3404
+ message: "Marketplace is not configured"
3405
+ }
3406
+ };
3407
+ try {
3408
+ return {
3409
+ success: true,
3410
+ data: await client.getTheme(themeId)
3411
+ };
3412
+ } catch (err) {
3413
+ if (err instanceof MarketplaceError && err.status === 404) return {
3414
+ success: false,
3415
+ error: {
3416
+ code: "NOT_FOUND",
3417
+ message: `Theme not found: ${themeId}`
3418
+ }
3419
+ };
3420
+ if (err instanceof MarketplaceUnavailableError) return {
3421
+ success: false,
3422
+ error: {
3423
+ code: "MARKETPLACE_UNAVAILABLE",
3424
+ message: "Marketplace is unavailable"
3425
+ }
3426
+ };
3427
+ console.error("Failed to get marketplace theme:", err);
3428
+ return {
3429
+ success: false,
3430
+ error: {
3431
+ code: "GET_THEME_FAILED",
3432
+ message: "Failed to get theme details"
3433
+ }
3434
+ };
3435
+ }
3436
+ }
3437
+
3438
+ //#endregion
3439
+ //#region ../registry-verification/dist/bundle.js
3440
+ /** Maximum accepted gzip payload size. */
3441
+ const MAX_BUNDLE_COMPRESSED_BYTES = 384 * 1024;
3442
+ /** Maximum aggregate size of regular-file contents. */
3443
+ const MAX_BUNDLE_SIZE = 256 * 1024;
3444
+ /** Maximum size of one regular file. */
3445
+ const MAX_BUNDLE_FILE_BYTES = 128 * 1024;
3446
+ /** Maximum number of regular files. */
3447
+ const MAX_BUNDLE_FILE_COUNT = 20;
3448
+ /** Maximum total tar entries, including harmless directory entries. */
3449
+ const MAX_BUNDLE_TAR_ENTRY_COUNT = 32;
3450
+ /**
3451
+ * Maximum tar stream size after decompression. This includes USTAR headers,
3452
+ * file padding, and the end marker in addition to the regular-file contents.
3453
+ */
3454
+ const MAX_BUNDLE_DECOMPRESSED_BYTES = MAX_BUNDLE_SIZE + MAX_BUNDLE_TAR_ENTRY_COUNT * 512 + MAX_BUNDLE_FILE_COUNT * 511 + 2 * 512;
3455
+ const TAR_BLOCK_BYTES = 512;
3456
+ const TAR_END_BYTES = TAR_BLOCK_BYTES * 2;
3457
+ const OCTAL_PATTERN = /^[0-7]+$/;
3458
+ const WINDOWS_DRIVE_PATTERN = /^[a-zA-Z]:/;
3459
+ const decoder = new TextDecoder("utf-8", {
3460
+ fatal: true,
3461
+ ignoreBOM: false
3462
+ });
3463
+ async function validatePluginBundle(compressed, options = {}) {
3464
+ if (compressed.byteLength > MAX_BUNDLE_COMPRESSED_BYTES) return verificationError("BUNDLE_COMPRESSED_SIZE_EXCEEDED", "The compressed plugin bundle exceeds the size limit.");
3465
+ const decompressed = await decompressBundle(compressed);
3466
+ if (!decompressed.success) return decompressed;
3467
+ const files = parseTar(decompressed.value);
3468
+ if (!files.success) return files;
3469
+ const manifestFile = files.value.get("manifest.json");
3470
+ if (!manifestFile) return verificationError("BUNDLE_MISSING_MANIFEST", "The plugin bundle is missing manifest.json.");
3471
+ const backend = files.value.get("backend.js");
3472
+ if (!backend) return verificationError("BUNDLE_MISSING_BACKEND", "The plugin bundle is missing backend.js.");
3473
+ let parsed;
3474
+ try {
3475
+ parsed = JSON.parse(decoder.decode(manifestFile.data));
3476
+ } catch {
3477
+ return verificationError("BUNDLE_INVALID_MANIFEST", "The plugin bundle manifest is not valid JSON.");
3478
+ }
3479
+ const validated = pluginManifestSchema.safeParse(parsed);
3480
+ if (!validated.success) return verificationError("BUNDLE_INVALID_MANIFEST", "The plugin bundle manifest failed schema validation.");
3481
+ const manifest = reconcileManifestAccess(validated.data);
3482
+ if (options.expectedSlug !== void 0 && manifest.id !== options.expectedSlug) return verificationError("BUNDLE_ID_MISMATCH", "The plugin bundle manifest id does not match the expected plugin.");
3483
+ if (options.expectedVersion !== void 0 && manifest.version !== options.expectedVersion) return verificationError("BUNDLE_VERSION_MISMATCH", "The plugin bundle manifest version does not match the expected version.");
3484
+ const result = {
3485
+ manifest,
3486
+ declaredAccess: manifest.declaredAccess ?? {},
3487
+ backend: backend.data
3488
+ };
3489
+ const admin = files.value.get("admin.js");
3490
+ if (admin) result.admin = admin.data;
3491
+ return {
3492
+ success: true,
3493
+ value: result
3494
+ };
3495
+ }
3496
+ async function decompressBundle(bytes) {
3497
+ const source = new ReadableStream({ start(controller) {
3498
+ controller.enqueue(bytes);
3499
+ controller.close();
3500
+ } });
3501
+ let reader;
3502
+ try {
3503
+ reader = source.pipeThrough(createGzipDecoder()).getReader();
3504
+ } catch {
3505
+ return verificationError("BUNDLE_INVALID_ARCHIVE", "The plugin bundle is not valid gzip data.");
3506
+ }
3507
+ const chunks = [];
3508
+ let total = 0;
3509
+ try {
3510
+ while (true) {
3511
+ const { done, value } = await reader.read();
3512
+ if (done) break;
3513
+ if (!value) continue;
3514
+ total += value.byteLength;
3515
+ if (total > MAX_BUNDLE_DECOMPRESSED_BYTES) {
3516
+ await reader.cancel().catch(() => void 0);
3517
+ return verificationError("BUNDLE_DECOMPRESSED_SIZE_EXCEEDED", "The decompressed plugin bundle exceeds the size limit.");
3518
+ }
3519
+ chunks.push(value);
3520
+ }
3521
+ } catch {
3522
+ return verificationError("BUNDLE_INVALID_ARCHIVE", "The plugin bundle is not valid gzip data.");
3523
+ }
3524
+ const output = new Uint8Array(total);
3525
+ let offset = 0;
3526
+ for (const chunk of chunks) {
3527
+ output.set(chunk, offset);
3528
+ offset += chunk.byteLength;
3529
+ }
3530
+ return {
3531
+ success: true,
3532
+ value: output
3533
+ };
3534
+ }
3535
+ function parseTar(bytes) {
3536
+ if (bytes.byteLength < TAR_END_BYTES || bytes.byteLength % TAR_BLOCK_BYTES !== 0) return invalidArchive();
3537
+ const files = /* @__PURE__ */ new Map();
3538
+ const rawPaths = /* @__PURE__ */ new Set();
3539
+ const normalizedPaths = /* @__PURE__ */ new Set();
3540
+ let offset = 0;
3541
+ let fileCount = 0;
3542
+ let entryCount = 0;
3543
+ let totalFileBytes = 0;
3544
+ let ended = false;
3545
+ while (offset + TAR_BLOCK_BYTES <= bytes.byteLength) {
3546
+ const header = bytes.subarray(offset, offset + TAR_BLOCK_BYTES);
3547
+ if (isZeroBlock(header)) {
3548
+ if (!isZeroBlock(bytes.subarray(offset + TAR_BLOCK_BYTES, offset + TAR_END_BYTES))) return invalidArchive();
3549
+ if (bytes.subarray(offset + TAR_END_BYTES).some((byte) => byte !== 0)) return invalidArchive();
3550
+ ended = true;
3551
+ break;
3552
+ }
3553
+ if (!validChecksum(header)) return invalidArchive();
3554
+ entryCount += 1;
3555
+ if (entryCount > MAX_BUNDLE_TAR_ENTRY_COUNT) return verificationError("BUNDLE_FILE_COUNT_EXCEEDED", "The plugin bundle contains too many archive entries.");
3556
+ const rawName = readTarPath(header);
3557
+ if (!rawName.success) return rawName;
3558
+ const typeFlag = header[156];
3559
+ const type = typeFlag === 0 ? "file" : String.fromCharCode(typeFlag ?? 0);
3560
+ const isDirectory = type === "5";
3561
+ const normalized = normalizePath(rawName.value, isDirectory);
3562
+ if (!normalized.success) return normalized;
3563
+ if (rawPaths.has(rawName.value) || normalizedPaths.has(normalized.value)) return verificationError("BUNDLE_PATH_COLLISION", "The plugin bundle contains duplicate or ambiguous paths.");
3564
+ rawPaths.add(rawName.value);
3565
+ normalizedPaths.add(normalized.value);
3566
+ const size = readOctal(header.subarray(124, 136));
3567
+ if (size === null || !Number.isSafeInteger(size)) return invalidArchive();
3568
+ const bodyStart = offset + TAR_BLOCK_BYTES;
3569
+ const nextOffset = bodyStart + Math.ceil(size / TAR_BLOCK_BYTES) * TAR_BLOCK_BYTES;
3570
+ if (nextOffset > bytes.byteLength) return invalidArchive();
3571
+ if (isDirectory) {
3572
+ if (size !== 0) return invalidArchive();
3573
+ } else if (type === "file" || type === "0") {
3574
+ fileCount += 1;
3575
+ if (fileCount > MAX_BUNDLE_FILE_COUNT) return verificationError("BUNDLE_FILE_COUNT_EXCEEDED", "The plugin bundle contains too many files.");
3576
+ if (size > MAX_BUNDLE_FILE_BYTES) return verificationError("BUNDLE_FILE_SIZE_EXCEEDED", "A file in the plugin bundle exceeds the per-file size limit.");
3577
+ totalFileBytes += size;
3578
+ if (totalFileBytes > MAX_BUNDLE_SIZE) return verificationError("BUNDLE_DECOMPRESSED_SIZE_EXCEEDED", "The plugin bundle file contents exceed the size limit.");
3579
+ files.set(normalized.value, {
3580
+ name: normalized.value,
3581
+ data: bytes.slice(bodyStart, bodyStart + size)
3582
+ });
3583
+ } else return verificationError("BUNDLE_UNSUPPORTED_ENTRY", "The plugin bundle contains an unsupported archive entry type.");
3584
+ offset = nextOffset;
3585
+ }
3586
+ if (!ended) return invalidArchive();
3587
+ return {
3588
+ success: true,
3589
+ value: files
3590
+ };
3591
+ }
3592
+ function readTarPath(header) {
3593
+ const name = readTarString(header.subarray(0, 100));
3594
+ const prefix = readTarString(header.subarray(345, 500));
3595
+ if (name === null || prefix === null || name.length === 0) return verificationError("BUNDLE_INVALID_PATH", "The plugin bundle contains a malformed path.");
3596
+ return {
3597
+ success: true,
3598
+ value: prefix ? `${prefix}/${name}` : name
3599
+ };
3600
+ }
3601
+ function readTarString(field) {
3602
+ const terminator = field.indexOf(0);
3603
+ const end = terminator === -1 ? field.length : terminator;
3604
+ if (terminator !== -1 && field.subarray(terminator + 1).some((byte) => byte !== 0)) return null;
3605
+ try {
3606
+ return decoder.decode(field.subarray(0, end));
3607
+ } catch {
3608
+ return null;
3609
+ }
3610
+ }
3611
+ function normalizePath(raw, isDirectory) {
3612
+ if (raw.includes("\\") || raw.startsWith("/") || WINDOWS_DRIVE_PATTERN.test(raw) || hasControlCharacter(raw) || raw.endsWith("/") !== isDirectory) return verificationError("BUNDLE_INVALID_PATH", "The plugin bundle contains an unsafe path.");
3613
+ const parts = raw.split("/");
3614
+ if (isDirectory) parts.pop();
3615
+ const normalized = [];
3616
+ for (const part of parts) {
3617
+ if (part === ".") continue;
3618
+ if (part === "" || part === "..") return verificationError("BUNDLE_INVALID_PATH", "The plugin bundle contains an unsafe path.");
3619
+ normalized.push(part.normalize("NFC"));
3620
+ }
3621
+ if (normalized.length === 0) return verificationError("BUNDLE_INVALID_PATH", "The plugin bundle contains a malformed path.");
3622
+ return {
3623
+ success: true,
3624
+ value: normalized.join("/")
3625
+ };
3626
+ }
3627
+ function hasControlCharacter(value) {
3628
+ for (const character of value) {
3629
+ const codePoint = character.codePointAt(0);
3630
+ if (codePoint !== void 0 && (codePoint <= 31 || codePoint === 127)) return true;
3631
+ }
3632
+ return false;
3633
+ }
3634
+ function readOctal(field) {
3635
+ const text = new TextDecoder().decode(field).replaceAll("\0", "").trim();
3636
+ if (!OCTAL_PATTERN.test(text)) return null;
3637
+ const value = Number.parseInt(text, 8);
3638
+ return Number.isSafeInteger(value) ? value : null;
3639
+ }
3640
+ function validChecksum(header) {
3641
+ const expected = readOctal(header.subarray(148, 156));
3642
+ if (expected === null) return false;
3643
+ let actual = 0;
3644
+ for (let index = 0; index < header.length; index += 1) actual += index >= 148 && index < 156 ? 32 : header[index] ?? 0;
3645
+ return actual === expected;
3646
+ }
3647
+ function isZeroBlock(block) {
3648
+ return block.byteLength === TAR_BLOCK_BYTES && block.every((byte) => byte === 0);
3649
+ }
3650
+ function invalidArchive() {
3651
+ return verificationError("BUNDLE_INVALID_ARCHIVE", "The plugin bundle is not a valid tar archive.");
3652
+ }
3653
+
3654
+ //#endregion
3655
+ //#region src/registry/artifact-verification.ts
3656
+ const bundleDecoder = new TextDecoder("utf-8", { fatal: true });
3657
+ async function validateRegistryArtifact(bytes, checksum, slug, version) {
3658
+ const checksumReport = await verifyMultihash(bytes, checksum);
3659
+ if (!checksumReport.success) return checksumReport;
3660
+ const [artifactDigest, ...artifactDigests] = await computeArtifactDigestCandidates(bytes);
3661
+ const bundleReport = await validatePluginBundle(bytes, {
3662
+ expectedSlug: slug,
3663
+ expectedVersion: version
3664
+ });
3665
+ if (!bundleReport.success) return bundleReport;
3666
+ const manifest = pluginManifestSchema$1.safeParse(bundleReport.value.manifest);
3667
+ if (!manifest.success) return {
3668
+ success: false,
3669
+ error: {
3670
+ code: "BUNDLE_RUNTIME_UNSUPPORTED",
3671
+ message: "The plugin bundle uses manifest features unsupported by this EmDash version."
3672
+ }
3673
+ };
3674
+ try {
3675
+ return {
3676
+ success: true,
3677
+ value: {
3678
+ bundle: {
3679
+ manifest: reconcileManifestAccess$1(manifest.data),
3680
+ backendCode: bundleDecoder.decode(bundleReport.value.backend),
3681
+ adminCode: bundleReport.value.admin === void 0 ? void 0 : bundleDecoder.decode(bundleReport.value.admin),
3682
+ checksum
3683
+ },
3684
+ artifactDigest,
3685
+ artifactDigests
3686
+ }
3687
+ };
3688
+ } catch {
3689
+ return {
3690
+ success: false,
3691
+ error: {
3692
+ code: "BUNDLE_INVALID_CODE_ENCODING",
3693
+ message: "Plugin bundle code must be valid UTF-8."
3694
+ }
3695
+ };
3696
+ }
3697
+ }
3698
+
3699
+ //#endregion
3700
+ //#region src/registry/plugin-id.ts
3701
+ /**
3702
+ * Plugin identifier helpers for the experimental decentralized plugin
3703
+ * registry.
3704
+ *
3705
+ * Registry plugins are addressed by `(publisher_did, slug)`, but the
3706
+ * EmDash runtime threads a single `pluginId: string` through every
3707
+ * install primitive (R2 storage keys, `PluginStateRepository`,
3708
+ * `syncMarketplacePlugins`, sandbox cache keys). Rather than refactor
3709
+ * everything to carry a composite identifier, we normalize the registry
3710
+ * tuple to an opaque content-addressed id that satisfies the existing
3711
+ * `validatePluginIdentifier` shape (`/^[a-z][a-z0-9_-]*$/`).
3712
+ *
3713
+ * The normalized id is:
3714
+ *
3715
+ * `r_` + base32-encoded SHA-256(publisher_did + "\n" + slug), truncated.
3716
+ *
3717
+ * Properties:
3718
+ *
3719
+ * - Deterministic. The same `(publisher, slug)` always produces the
3720
+ * same id, so re-resolving an installed plugin's metadata against
3721
+ * the aggregator is a straightforward lookup keyed by the columns
3722
+ * stored alongside `plugin_id` in `plugin_states`.
3723
+ * - Collision-resistant. 80 bits of truncated hash; a 50% birthday
3724
+ * collision happens around 2^40 distinct plugins, well beyond what
3725
+ * this registry will ever index.
3726
+ * - R2-safe. Lowercase alphanumerics + underscore (no hyphens), no
3727
+ * `:` or `/`. Existing sandbox cache keys (`${pluginId}:${version}`)
3728
+ * keep working because the id contains no `:`.
3729
+ * - Syntactically distinct from typical marketplace plugin ids: the
3730
+ * `r_` prefix plus exactly 16 base32 characters is unlikely to be
3731
+ * chosen as a marketplace id. Not formally guaranteed by the
3732
+ * validator -- marketplace ids may begin with `r_` and contain
3733
+ * hyphens -- so the install handler also performs an explicit
3734
+ * pre-existing-row check at the derived id and rejects any cross-
3735
+ * source collision (`PLUGIN_ID_COLLISION`).
3736
+ *
3737
+ * Reverse lookup (id → publisher + slug) requires the `plugin_states`
3738
+ * row -- the hash is one-way. That's intentional: any code path that
3739
+ * needs the human-meaningful pair already has the state row in hand.
3740
+ */
3741
+ /** Length (in base32 characters) of the truncated hash portion of the id. */
3742
+ const HASH_LENGTH = 16;
3743
+ /** Total expected length of a registry plugin id. */
3744
+ const REGISTRY_PLUGIN_ID_LENGTH = 2 + HASH_LENGTH;
3745
+ const BASE32_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
3746
+ /**
3747
+ * RFC 4648 base32 encoding without padding, lowercase. Implemented inline
3748
+ * rather than depending on a multibase library because (a) we only need
3749
+ * lowercase base32 here, (b) we need it to run identically in workerd,
3750
+ * Node, and the browser, and (c) the implementation is fewer lines than
3751
+ * the import statement would be.
3752
+ */
3753
+ function base32Encode(bytes) {
3754
+ let bits = 0;
3755
+ let value = 0;
3756
+ let out = "";
3757
+ for (const byte of bytes) {
3758
+ value = value << 8 | byte;
3759
+ bits += 8;
3760
+ while (bits >= 5) {
3761
+ bits -= 5;
3762
+ out += BASE32_ALPHABET[value >>> bits & 31];
3763
+ }
3764
+ }
3765
+ if (bits > 0) out += BASE32_ALPHABET[value << 5 - bits & 31];
3766
+ return out;
3767
+ }
3768
+ /**
3769
+ * Derive the normalized plugin id for a registry-published plugin.
3770
+ *
3771
+ * Throws if either input is empty or whitespace-only -- a missing DID
3772
+ * or slug is always a programming error in the install path, not a
3773
+ * recoverable runtime condition.
3774
+ */
3775
+ async function makeRegistryPluginId(publisherDid, slug) {
3776
+ const did = publisherDid.trim();
3777
+ const s = slug.trim();
3778
+ if (!did) throw new Error("makeRegistryPluginId: publisherDid is required");
3779
+ if (!s) throw new Error("makeRegistryPluginId: slug is required");
3780
+ const input = `${did}\n${s}`;
3781
+ const hashBuffer = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input));
3782
+ return `r_${base32Encode(new Uint8Array(hashBuffer)).slice(0, HASH_LENGTH)}`;
3783
+ }
3784
+
3785
+ //#endregion
3786
+ //#region src/registry/record-labels.ts
3787
+ function hasCurrentRecordLabel(labels, value, record, now = Date.now()) {
3788
+ return labels.some((label) => {
3789
+ if (label.val !== value || label.uri !== record.uri || label.cid !== record.cid || label.neg === true) return false;
3790
+ if (label.exp === void 0) return true;
3791
+ const expiresAt = Date.parse(label.exp);
3792
+ return Number.isFinite(expiresAt) && expiresAt > now;
3793
+ });
3794
+ }
3795
+
3796
+ //#endregion
3797
+ //#region src/api/handlers/registry.ts
3798
+ /**
3799
+ * Registry installs use aggregator results only for discovery and moderation
3800
+ * metadata. The handler reads profile and release records from the publisher's
3801
+ * PDS, verifies their repository proofs, then validates the bundle checksum,
3802
+ * manifest, policy, and consent before storing or activating executable code.
3803
+ * Applicable labels can block installation but cannot supply any verified
3804
+ * record, checksum, permission, or executable byte.
3805
+ */
3806
+ function verifiedAccessEqual(a, b) {
3807
+ return JSON.stringify(a) === JSON.stringify(canonicalizeDeclaredAccess(b));
3808
+ }
3809
+ function registryArtifactError(code, message, operation) {
3810
+ let apiCode;
3811
+ switch (code) {
3812
+ case "BUNDLE_ID_MISMATCH":
3813
+ apiCode = operation === "install" ? "MANIFEST_ID_MISMATCH" : "BUNDLE_IDENTITY_MISMATCH";
3814
+ break;
3815
+ case "BUNDLE_VERSION_MISMATCH":
3816
+ apiCode = operation === "install" ? "MANIFEST_VERSION_MISMATCH" : code;
3817
+ break;
3818
+ case "CHECKSUM_MISMATCH":
3819
+ case "INVALID_MULTIHASH":
3820
+ case "UNSUPPORTED_MULTIHASH":
3821
+ apiCode = "CHECKSUM_MISMATCH";
3822
+ break;
3823
+ case "FETCH_FAILED":
3824
+ case "HOST_REJECTED":
3825
+ case "REDIRECT_LIMIT_EXCEEDED":
3826
+ case "REDIRECT_LOCATION_MISSING":
3827
+ case "RESOURCE_STATUS_ERROR":
3828
+ case "RESOURCE_TIMEOUT":
3829
+ apiCode = operation === "install" ? "INSTALL_FAILED" : "UPDATE_FAILED";
3830
+ break;
3831
+ default: apiCode = "INVALID_BUNDLE";
3832
+ }
3833
+ return {
3834
+ success: false,
3835
+ error: {
3836
+ code: apiCode,
3837
+ message,
3838
+ details: { verificationCode: code }
3839
+ }
3840
+ };
3841
+ }
3842
+ function registryRecordError(code, message) {
3843
+ return {
3844
+ success: false,
3845
+ error: {
3846
+ code: "RECORD_VERIFICATION_FAILED",
3847
+ message,
3848
+ details: { verificationCode: code }
3849
+ }
3850
+ };
3851
+ }
3852
+ function recordConsentError(input, records) {
3853
+ if (!input.profileCid || !input.releaseCid) return {
3854
+ success: false,
3855
+ error: {
3856
+ code: "RECORD_CONSENT_REQUIRED",
3857
+ message: "Verify the signed package records before confirming this action."
3858
+ }
3859
+ };
3860
+ if (input.profileCid !== records.profile.cid || input.releaseCid !== records.release.cid) return {
3861
+ success: false,
3862
+ error: {
3863
+ code: "RECORD_VERIFICATION_DRIFT",
3864
+ message: "The signed package records changed after review. Verify them again."
3865
+ }
3866
+ };
3867
+ return null;
3868
+ }
3869
+ function recordVerificationSummary(records, report) {
3870
+ return {
3871
+ profileCid: records.profile.cid,
3872
+ releaseCid: records.release.cid,
3873
+ provenance: report.provenance.status,
3874
+ policy: report.value.policy
3875
+ };
3876
+ }
3877
+ /**
3878
+ * Bytes-per-artifact cap on the gzipped tarball we'll download before
3879
+ * decompression. RFC 0001 caps a sandboxed plugin bundle at 256 KiB
3880
+ * decompressed (see `MAX_BUNDLE_SIZE` in cli/commands/bundle-utils.ts);
3881
+ * gzip on a mix of JSON manifest + JS code typically gives 0.3-0.6
3882
+ * ratio, so compressed bundles are well under 200 KiB in practice.
3883
+ * 512 KiB leaves margin for unusual file mixes that compress poorly
3884
+ * while still rejecting anything that's obviously not a legitimate
3885
+ * plugin bundle.
3886
+ */
3887
+ const MAX_ARTIFACT_BYTES = 512 * 1024;
3888
+ /**
3889
+ * Maximum number of HTTP redirects followed during artifact download.
3890
+ * Each hop is independently URL-validated, so a malicious server cannot
3891
+ * redirect through a series of allowed-looking origins to reach a
3892
+ * forbidden one.
3893
+ */
3894
+ const MAX_REDIRECTS = 5;
3895
+ /**
3896
+ * Wall-clock cap on any single artifact fetch attempt (per URL).
3897
+ * Defends against slow-loris artifact sources that accept the connection but
3898
+ * never finish sending headers or body.
3899
+ */
3900
+ const ARTIFACT_FETCH_TIMEOUT_MS = 15e3;
3901
+ /**
3902
+ * Total wall-clock budget for the artifact-download phase across all
3903
+ * advertised caches, the publisher PDS, and the declared URL. Even with the
3904
+ * per-URL timeout, unavailable sources could otherwise tie up the install request for
3905
+ * minutes; this caps total time at a budget interactive admins can
3906
+ * tolerate. Tuned so a fast happy path takes <1s of budget per
3907
+ * attempt and a worst case still completes in under a minute.
3908
+ */
3909
+ const ARTIFACT_TOTAL_BUDGET_MS = 45e3;
3910
+ /**
3911
+ * Per-request timeout applied to every aggregator XRPC call
3912
+ * (`resolvePackage`, `getLatestRelease`, `listReleases`). Matches the
3913
+ * per-URL artifact-fetch cap. Without this, a slow-loris aggregator
3914
+ * can stall the install before the artifact phase even starts.
3915
+ */
3916
+ const AGGREGATOR_REQUEST_TIMEOUT_MS = 15e3;
3917
+ /**
3918
+ * Total wall-clock budget for the aggregator-discovery phase
3919
+ * (resolve + selected-release lookup). Mirrors the artifact-download
3920
+ * budget. Worst case with the pinned-version path's 20-page cap is
3921
+ * 20 + 1 calls; capping the total ensures any one stalled call
3922
+ * still bounds the whole phase.
3923
+ */
3924
+ const AGGREGATOR_TOTAL_BUDGET_MS = 3e4;
3925
+ var RegistryArtifactFetchError = class extends Error {
3926
+ constructor(code, message) {
3927
+ super(message);
3928
+ this.code = code;
3929
+ this.name = "RegistryArtifactFetchError";
3930
+ }
3931
+ };
3932
+ /** Build a fetch function that enforces a per-request and per-budget timeout. */
3933
+ function timedFetch(totalDeadline) {
3934
+ return (input, init) => {
3935
+ const now = Date.now();
3936
+ const remaining = Math.max(0, totalDeadline - now);
3937
+ if (remaining === 0) return Promise.reject(/* @__PURE__ */ new Error("Aggregator request budget exhausted"));
3938
+ const timeout = Math.min(AGGREGATOR_REQUEST_TIMEOUT_MS, remaining);
3939
+ const controller = new AbortController();
3940
+ const timer = setTimeout(() => controller.abort(), timeout);
3941
+ const callerSignal = init?.signal;
3942
+ if (callerSignal) if (callerSignal.aborted) controller.abort(callerSignal.reason);
3943
+ else callerSignal.addEventListener("abort", () => controller.abort(callerSignal.reason));
3944
+ return fetch(input, {
3945
+ ...init,
3946
+ signal: controller.signal
3947
+ }).finally(() => {
3948
+ clearTimeout(timer);
3949
+ });
3950
+ };
3951
+ }
3952
+ async function fetchArtifact(artifactCaches, artifact, record, auth) {
3953
+ const result = await fetchReleaseArtifact({
3954
+ artifact,
3955
+ record,
3956
+ artifactCaches,
3957
+ ...auth === void 0 ? {} : { auth }
3958
+ }, {
3959
+ fetch: async (url, init) => {
3960
+ if (!init.signal) throw new Error("Registry artifact fetch requires an abort signal");
3961
+ return fetchRegistryArtifactUrl(url.href, {
3962
+ signal: init.signal,
3963
+ maxResponseBytes: MAX_ARTIFACT_BYTES
3964
+ });
3965
+ },
3966
+ resolveHostname: async (hostname) => (await resolveAndValidateExternalUrlTarget(`https://${hostname}`)).addresses,
3967
+ allowHttpLocalhost: import.meta.env.DEV,
3968
+ headerTimeoutMs: ARTIFACT_FETCH_TIMEOUT_MS,
3969
+ totalTimeoutMs: ARTIFACT_TOTAL_BUDGET_MS,
3970
+ maxBytes: MAX_ARTIFACT_BYTES,
3971
+ maxRedirects: MAX_REDIRECTS
3972
+ });
3973
+ if (!result.success) throw new RegistryArtifactFetchError(result.error.code, result.error.message);
3974
+ return result.value.bytes;
3975
+ }
3976
+ /**
3977
+ * Gate a release's `requires` constraints against the running host
3978
+ * environment. `requires` is the lexicon-`unknown` value off the signed
3979
+ * release record — never trust its shape; `checkEnvCompatibility` guards it.
3980
+ *
3981
+ * Returns `null` when every advertised constraint is satisfied (or there are
3982
+ * none), or a structured `ENV_INCOMPATIBLE` error naming the unsatisfied
3983
+ * constraints and the host versions. The error carries the guarded `requires`
3984
+ * and `host` maps so the admin can render the same mismatch the UI gate shows.
3985
+ */
3986
+ function assertEnvCompatible(requires, hostEnv) {
3987
+ for (const skipped of findSkippedEnvConstraints(requires, hostEnv)) console.warn(`[registry] env compatibility constraint skipped: ${skipped.key} requires ${skipped.required} but host version is ${skipped.reason}`);
3988
+ const mismatches = checkEnvCompatibility(requires, hostEnv);
3989
+ if (mismatches.length === 0) return null;
3990
+ const guarded = {};
3991
+ for (const m of mismatches) guarded[m.key] = m.required;
3992
+ return {
3993
+ code: "ENV_INCOMPATIBLE",
3994
+ message: `This release is not compatible with the current environment: ${mismatches.map((m) => `${m.key} requires ${m.required} but host is ${m.host}`).join("; ")}.`,
3995
+ details: {
3996
+ requires: guarded,
3997
+ host: hostEnv
3998
+ }
3999
+ };
4000
+ }
4001
+ async function handleRegistryInstall(db, storage, sandboxRunner, registryConfigInput, input, opts) {
4002
+ const registryConfig = coerceRegistryConfig(registryConfigInput);
4003
+ if (!registryConfig) return {
4004
+ success: false,
4005
+ error: {
4006
+ code: "REGISTRY_NOT_CONFIGURED",
4007
+ message: "Registry is not configured"
4008
+ }
4009
+ };
4010
+ if (!storage) return {
4011
+ success: false,
4012
+ error: {
4013
+ code: "STORAGE_NOT_CONFIGURED",
4014
+ message: "Storage is required for registry plugin installation"
4015
+ }
4016
+ };
4017
+ if (!sandboxRunner || !sandboxRunner.isAvailable()) return {
4018
+ success: false,
4019
+ error: {
4020
+ code: "SANDBOX_NOT_AVAILABLE",
4021
+ message: withUnavailableReason("Sandbox runner is required for registry plugins", sandboxRunner)
4022
+ }
4023
+ };
4024
+ try {
4025
+ validateAggregatorUrl(registryConfig.aggregatorUrl);
4026
+ } catch (err) {
4027
+ return {
4028
+ success: false,
4029
+ error: {
4030
+ code: "REGISTRY_NOT_CONFIGURED",
4031
+ message: err instanceof Error ? err.message : "Invalid aggregator URL"
4032
+ }
4033
+ };
4034
+ }
4035
+ const { did, slug, version: requestedVersion } = input;
4036
+ const { DiscoveryClient, registryLabelerPolicy } = await import("@emdash-cms/registry-client/discovery");
4037
+ const aggregatorDeadline = Date.now() + AGGREGATOR_TOTAL_BUDGET_MS;
4038
+ const discovery = new DiscoveryClient({
4039
+ aggregatorUrl: registryConfig.aggregatorUrl,
4040
+ acceptLabelers: registryConfig.acceptLabelers,
4041
+ labelerPolicy: registryLabelerPolicy(registryConfig.acceptLabelers),
4042
+ fetch: timedFetch(aggregatorDeadline)
4043
+ });
4044
+ if (!did.startsWith("did:") || did.split(":").length < 3) return {
4045
+ success: false,
4046
+ error: {
4047
+ code: "INVALID_DID",
4048
+ message: "DID must be a valid atproto DID (e.g. did:plc:abc123)"
4049
+ }
4050
+ };
4051
+ try {
4052
+ const publisherDid = did;
4053
+ const packageView = await discovery.getPackage({
4054
+ did: publisherDid,
4055
+ slug
4056
+ });
4057
+ const MAX_LIST_PAGES = 20;
4058
+ const releaseView = await (async () => {
4059
+ if (!requestedVersion) return discovery.getLatestRelease({
4060
+ did: publisherDid,
4061
+ package: slug
4062
+ });
4063
+ let cursor;
4064
+ const seenCursors = /* @__PURE__ */ new Set();
4065
+ for (let page = 0; page < MAX_LIST_PAGES; page++) {
4066
+ if (cursor !== void 0) {
4067
+ if (seenCursors.has(cursor)) break;
4068
+ seenCursors.add(cursor);
4069
+ }
4070
+ const result = await discovery.listReleases({
4071
+ did: publisherDid,
4072
+ package: slug,
4073
+ cursor,
4074
+ limit: 50
4075
+ });
4076
+ for (const r of result.releases) if (r.version === requestedVersion) return r;
4077
+ if (!result.cursor) break;
4078
+ cursor = result.cursor;
4079
+ }
4080
+ })();
4081
+ if (!releaseView) return {
4082
+ success: false,
4083
+ error: {
4084
+ code: "NO_RELEASE",
4085
+ message: requestedVersion ? `Version ${requestedVersion} not found for ${publisherDid}/${slug}` : `No installable release found for ${publisherDid}/${slug}`
4086
+ }
4087
+ };
4088
+ if (packageView.did !== publisherDid || packageView.slug !== slug) return {
4089
+ success: false,
4090
+ error: {
4091
+ code: "AGGREGATOR_IDENTITY_MISMATCH",
4092
+ message: "Aggregator returned a package view for a different publisher or slug."
4093
+ }
4094
+ };
4095
+ if (releaseView.did !== publisherDid || releaseView.package !== slug || requestedVersion !== void 0 && releaseView.version !== requestedVersion) return {
4096
+ success: false,
4097
+ error: {
4098
+ code: "AGGREGATOR_IDENTITY_MISMATCH",
4099
+ message: "Aggregator returned a release view that does not match the requested package or version."
4100
+ }
4101
+ };
4102
+ const version = releaseView.version;
4103
+ if (evaluateRegistryReleaseWithdrawal(releaseView, discovery.labelerPolicy).withdrawn) return {
4104
+ success: false,
4105
+ error: {
4106
+ code: "RELEASE_YANKED",
4107
+ message: "This release has been withdrawn"
4108
+ }
4109
+ };
4110
+ const authoritative = await (opts?.readAuthoritativeRecords ?? readAuthoritativePackageRelease)(publisherDid, slug, version, opts?.authoritativeRecords);
4111
+ if (!authoritative.success) return registryRecordError(authoritative.error.code, authoritative.error.message);
4112
+ const records = authoritative.value;
4113
+ const { profile, release } = records.inspection.value;
4114
+ if (packageView.uri !== records.profile.uri || packageView.cid !== records.profile.cid || releaseView.uri !== records.release.uri || releaseView.cid !== records.release.cid) return {
4115
+ success: false,
4116
+ error: {
4117
+ code: "AGGREGATOR_RECORD_MISMATCH",
4118
+ message: "Aggregator metadata does not match the publisher's signed records."
4119
+ }
4120
+ };
4121
+ if (!opts?.verifyOnly) {
4122
+ const consentError = recordConsentError({
4123
+ profileCid: input.acknowledgedProfileCid,
4124
+ releaseCid: input.acknowledgedReleaseCid
4125
+ }, records);
4126
+ if (consentError) return consentError;
4127
+ }
4128
+ if (hasCurrentRecordLabel(packageView.labels ?? [], "security:yanked", records.profile) || hasCurrentRecordLabel(packageView.labels ?? [], "security-yanked", records.profile)) return {
4129
+ success: false,
4130
+ error: {
4131
+ code: "RELEASE_YANKED",
4132
+ message: "This release has been withdrawn"
4133
+ }
4134
+ };
4135
+ if (opts?.hostEnv) {
4136
+ const envError = assertEnvCompatible(release.requires, opts.hostEnv);
4137
+ if (envError) return {
4138
+ success: false,
4139
+ error: envError
4140
+ };
4141
+ }
4142
+ const minimumReleaseAge = registryConfig.policy?.minimumReleaseAge;
4143
+ let minimumReleaseAgeSeconds = 0;
4144
+ if (minimumReleaseAge !== void 0) try {
4145
+ minimumReleaseAgeSeconds = parseDurationSeconds(minimumReleaseAge);
4146
+ } catch (err) {
4147
+ return {
4148
+ success: false,
4149
+ error: {
4150
+ code: "REGISTRY_POLICY_INVALID",
4151
+ message: err instanceof Error ? err.message : "Invalid minimumReleaseAge value in registry config"
4152
+ }
4153
+ };
4154
+ }
4155
+ if (minimumReleaseAgeSeconds > 0) {
4156
+ const exclude = registryConfig.policy?.minimumReleaseAgeExclude?.map((e) => e.trim().toLowerCase());
4157
+ if (!(releaseExemptFromMinimumAge(exclude, publisherDid, slug) || isProvenFirstRelease(packageView))) {
4158
+ const indexedAt = Date.parse(releaseView.indexedAt);
4159
+ if (!Number.isFinite(indexedAt)) return {
4160
+ success: false,
4161
+ error: {
4162
+ code: "RELEASE_TIMESTAMP_INVALID",
4163
+ message: "Release record is missing a valid indexed-at timestamp; cannot evaluate minimum release age policy."
4164
+ }
4165
+ };
4166
+ const ageSeconds = (Date.now() - indexedAt) / 1e3;
4167
+ if (ageSeconds < minimumReleaseAgeSeconds) {
4168
+ const remaining = Math.ceil(minimumReleaseAgeSeconds - ageSeconds);
4169
+ return {
4170
+ success: false,
4171
+ error: {
4172
+ code: "RELEASE_TOO_NEW",
4173
+ message: `This release does not meet the configured minimum release age of ${minimumReleaseAgeSeconds}s. It will be installable in ~${remaining}s.`
4174
+ }
4175
+ };
4176
+ }
4177
+ }
4178
+ }
4179
+ const pluginId = await makeRegistryPluginId(publisherDid, slug);
4180
+ if (opts?.configuredPluginIds?.has(pluginId)) return {
4181
+ success: false,
4182
+ error: {
4183
+ code: "PLUGIN_ID_CONFLICT",
4184
+ message: "A configured plugin with the same derived id already exists"
4185
+ }
4186
+ };
4187
+ const stateRepo = new PluginStateRepository(db);
4188
+ const existing = await stateRepo.get(pluginId);
4189
+ if (existing) {
4190
+ if (existing.source === "registry") return {
4191
+ success: false,
4192
+ error: {
4193
+ code: "ALREADY_INSTALLED",
4194
+ message: `Plugin ${publisherDid}/${slug} is already installed`
4195
+ }
4196
+ };
4197
+ return {
4198
+ success: false,
4199
+ error: {
4200
+ code: "PLUGIN_ID_COLLISION",
4201
+ message: `A non-registry plugin already exists at the derived id ${pluginId}. Uninstall it before installing this registry plugin.`
4202
+ }
4203
+ };
4204
+ }
4205
+ const packageArtifact = release.artifacts.package;
4206
+ const declaredChecksum = release.artifacts.package.checksum;
4207
+ if (!packageArtifact || !declaredChecksum) return {
4208
+ success: false,
4209
+ error: {
4210
+ code: "INVALID_RELEASE",
4211
+ message: "Release record is missing its package artifact or checksum"
4212
+ }
4213
+ };
4214
+ let artifactBytes;
4215
+ try {
4216
+ artifactBytes = await fetchArtifact(releaseView.artifactCaches ?? [], packageArtifact, {
4217
+ did: publisherDid,
4218
+ collection: NSID.packageRelease,
4219
+ rkey: `${slug}:${version}`,
4220
+ cid: releaseView.cid
4221
+ }, release.auth);
4222
+ } catch (error) {
4223
+ if (error instanceof RegistryArtifactFetchError) return registryArtifactError(error.code, error.message, "install");
4224
+ throw error;
4225
+ }
4226
+ const artifactReport = await validateRegistryArtifact(artifactBytes, declaredChecksum, slug, version);
4227
+ if (!artifactReport.success) return registryArtifactError(artifactReport.error.code, artifactReport.error.message, "install");
4228
+ const { bundle, artifactDigest, artifactDigests } = artifactReport.value;
4229
+ const recordReport = await verifyAuthoritativePackageRelease(records, artifactDigest, {
4230
+ ...opts?.authoritativeRecords,
4231
+ artifactDigests
4232
+ });
4233
+ if (!recordReport.success) return registryRecordError(recordReport.code, recordReport.reasons[0]?.message ?? "The release provenance is invalid.");
4234
+ const verification = recordVerificationSummary(records, recordReport);
4235
+ bundle.manifest = {
4236
+ ...bundle.manifest,
4237
+ id: pluginId
4238
+ };
4239
+ if (!verifiedAccessEqual(recordReport.value.declaredAccess, bundle.manifest.declaredAccess ?? {})) return {
4240
+ success: false,
4241
+ error: {
4242
+ code: "DECLARED_ACCESS_DRIFT",
4243
+ message: "The plugin bundle declares different permissions than its published record. Installation refused."
4244
+ }
4245
+ };
4246
+ const actualCapabilities = canonicalCapabilitiesForDriftCheck(bundle.manifest.capabilities);
4247
+ if (!opts?.verifyOnly && actualCapabilities.length > 0) {
4248
+ if (input.acknowledgedDeclaredAccess === void 0) return {
4249
+ success: false,
4250
+ error: {
4251
+ code: "DECLARED_ACCESS_REQUIRED",
4252
+ message: "This plugin declares capabilities that require consent. Re-open the install dialog to review and acknowledge them."
4253
+ }
4254
+ };
4255
+ const acknowledged = canonicalCapabilitiesForDriftCheck(input.acknowledgedDeclaredAccess);
4256
+ if (acknowledged.length !== actualCapabilities.length || acknowledged.some((cap, i) => cap !== actualCapabilities[i])) return {
4257
+ success: false,
4258
+ error: {
4259
+ code: "DECLARED_ACCESS_DRIFT",
4260
+ message: "Plugin manifest has changed since you consented. Re-open the install dialog to review the new permissions."
4261
+ }
4262
+ };
4263
+ }
4264
+ const actualMcpTools = (bundle.manifest.mcp?.tools ?? []).map(({ inputSchema: _, outputSchema: __, ...tool }) => tool);
4265
+ const publicRoutes = diffRouteVisibility(void 0, bundle.manifest).newlyPublic.toSorted();
4266
+ if (!opts?.verifyOnly && publicRoutes.length > 0) {
4267
+ const acknowledgedPublicRoutes = Array.isArray(input.acknowledgedPublicRoutes) ? input.acknowledgedPublicRoutes.filter((route) => typeof route === "string").toSorted() : [];
4268
+ if (JSON.stringify(acknowledgedPublicRoutes) !== JSON.stringify(publicRoutes)) return {
4269
+ success: false,
4270
+ error: {
4271
+ code: "ROUTE_VISIBILITY_ESCALATION",
4272
+ message: "Plugin install exposes public (unauthenticated) routes",
4273
+ details: {
4274
+ routeVisibilityChanges: { newlyPublic: publicRoutes },
4275
+ mcpTools: actualMcpTools,
4276
+ verification
4277
+ }
4278
+ }
4279
+ };
4280
+ }
4281
+ if (!opts?.verifyOnly && actualMcpTools.length > 0) {
4282
+ if (JSON.stringify(input.acknowledgedMcpTools) !== JSON.stringify(actualMcpTools)) return {
4283
+ success: false,
4284
+ error: {
4285
+ code: "MCP_TOOL_CONSENT_REQUIRED",
4286
+ message: "Plugin MCP tools require explicit consent",
4287
+ details: {
4288
+ mcpTools: actualMcpTools,
4289
+ routeVisibilityChanges: publicRoutes.length > 0 ? { newlyPublic: publicRoutes } : void 0,
4290
+ verification
4291
+ }
4292
+ }
4293
+ };
4294
+ }
4295
+ const result = {
4296
+ pluginId,
4297
+ publisherDid,
4298
+ slug,
4299
+ version,
4300
+ capabilities: bundle.manifest.capabilities,
4301
+ declaredAccess: recordReport.value.releaseExtension.declaredAccess,
4302
+ mcpTools: actualMcpTools,
4303
+ publicRoutes,
4304
+ verification
4305
+ };
4306
+ if (opts?.verifyOnly) return {
4307
+ success: true,
4308
+ data: result
4309
+ };
4310
+ await storeBundleInR2(storage, pluginId, version, bundle, "registry");
4311
+ try {
4312
+ await stateRepo.upsert(pluginId, version, "active", {
4313
+ source: "registry",
4314
+ displayName: profile.name ?? slug,
4315
+ description: profile.description ?? void 0,
4316
+ registryPublisherDid: publisherDid,
4317
+ registrySlug: slug
4318
+ });
4319
+ } catch (stateErr) {
4320
+ let lostRace = false;
4321
+ try {
4322
+ const winner = await stateRepo.get(pluginId);
4323
+ lostRace = winner !== void 0 && winner !== null;
4324
+ } catch (probeErr) {
4325
+ console.warn(`[registry-install] Failed to probe state row for ${pluginId} after state-write failure; treating as orphan:`, probeErr);
4326
+ }
4327
+ if (!lostRace) try {
4328
+ await deleteBundleFromR2(storage, pluginId, version, "registry");
4329
+ } catch (cleanupErr) {
4330
+ console.warn(`[registry-install] Failed to clean up R2 bundle for ${pluginId}@${version} after state-row write failure:`, cleanupErr);
4331
+ }
4332
+ throw stateErr;
4333
+ }
4334
+ await syncDeclaredStorageIndexes(db, [bundle.manifest]);
4335
+ return {
4336
+ success: true,
4337
+ data: result
4338
+ };
4339
+ } catch (err) {
4340
+ if (err instanceof ClientValidationError) return {
4341
+ success: false,
4342
+ error: {
4343
+ code: "AGGREGATOR_RESPONSE_INVALID",
4344
+ message: `Aggregator returned a response that does not conform to its lexicon (${err.target})`
4345
+ }
4346
+ };
4347
+ if (err instanceof ClientResponseError) {
4348
+ if (err.error === "ListingUnavailable") return {
4349
+ success: false,
4350
+ error: {
4351
+ code: "LISTING_UNAVAILABLE",
4352
+ message: "This plugin is unavailable under the active registry policy"
4353
+ }
4354
+ };
4355
+ return {
4356
+ success: false,
4357
+ error: {
4358
+ code: err.status === 404 ? "AGGREGATOR_NOT_FOUND" : "AGGREGATOR_HTTP_ERROR",
4359
+ message: `Aggregator returned ${err.status}: ${err.error}`
4360
+ }
4361
+ };
4362
+ }
4363
+ if (err instanceof EmDashStorageError) return {
4364
+ success: false,
4365
+ error: {
4366
+ code: err.code ?? "STORAGE_ERROR",
4367
+ message: "Storage error while installing plugin"
4368
+ }
4369
+ };
4370
+ console.error("[registry-install] Failed:", err);
4371
+ return {
4372
+ success: false,
4373
+ error: {
4374
+ code: "INSTALL_FAILED",
4375
+ message: err instanceof Error ? err.message : "Failed to install plugin from registry"
4376
+ }
4377
+ };
4378
+ }
4379
+ }
4380
+ /**
4381
+ * Uninstall a registry-source plugin. Deletes the R2 bundle under
4382
+ * `registry/<pluginId>/<version>/`, optionally drops the plugin's
4383
+ * `_plugin_storage` rows, and removes the `_plugin_state` row. The
4384
+ * sandbox runtime is reconciled by the route's `syncRegistryPlugins`
4385
+ * call after this returns.
4386
+ *
4387
+ * Refuses to uninstall plugins whose `source` is not `"registry"` to
4388
+ * avoid trashing a marketplace/config plugin that happens to share the
4389
+ * pluginId namespace.
4390
+ */
4391
+ async function handleRegistryUninstall(db, storage, pluginId, opts) {
4392
+ try {
4393
+ const stateRepo = new PluginStateRepository(db);
4394
+ const existing = await stateRepo.get(pluginId);
4395
+ if (!existing || existing.source !== "registry") return {
4396
+ success: false,
4397
+ error: {
4398
+ code: "NOT_FOUND",
4399
+ message: `No registry plugin found: ${pluginId}`
4400
+ }
4401
+ };
4402
+ const version = existing.version;
4403
+ await opts?.beforeDelete?.();
4404
+ let dataDeleted = false;
4405
+ if (opts?.deleteData) {
4406
+ await db.deleteFrom("_plugin_storage").where("plugin_id", "=", pluginId).execute();
4407
+ dataDeleted = true;
4408
+ }
4409
+ try {
4410
+ await removeAllPluginIndexes(db, pluginId);
4411
+ } catch {}
4412
+ await stateRepo.delete(pluginId);
4413
+ if (storage) await deleteBundleFromR2(storage, pluginId, version, "registry");
4414
+ return {
4415
+ success: true,
4416
+ data: {
4417
+ pluginId,
4418
+ dataDeleted
4419
+ }
4420
+ };
4421
+ } catch (err) {
4422
+ console.error("[registry-uninstall] Failed:", err);
4423
+ return {
4424
+ success: false,
4425
+ error: {
4426
+ code: "UNINSTALL_FAILED",
4427
+ message: "Failed to uninstall plugin"
4428
+ }
4429
+ };
4430
+ }
4431
+ }
4432
+ /**
4433
+ * Update a registry-source plugin to a newer release. Mirrors
4434
+ * `handleMarketplaceUpdate`: resolves the target version via the aggregator,
4435
+ * re-runs the artifact fetch / checksum / extract pipeline, diffs capabilities
4436
+ * and route visibility against the currently installed bundle, and gates
4437
+ * escalations behind `confirmCapabilityChanges` and an exact
4438
+ * `acknowledgedPublicRoutes` match so the admin re-consents to widened permissions.
4439
+ *
4440
+ * Refuses non-registry sources. Refuses when the stored state row is missing
4441
+ * the `(publisherDid, slug)` it needs to resolve against the aggregator.
4442
+ */
4443
+ async function handleRegistryUpdate(db, storage, sandboxRunner, registryConfigInput, pluginId, opts) {
4444
+ const registryConfig = coerceRegistryConfig(registryConfigInput);
4445
+ if (!registryConfig) return {
4446
+ success: false,
4447
+ error: {
4448
+ code: "REGISTRY_NOT_CONFIGURED",
4449
+ message: "Registry is not configured"
4450
+ }
4451
+ };
4452
+ if (!storage) return {
4453
+ success: false,
4454
+ error: {
4455
+ code: "STORAGE_NOT_CONFIGURED",
4456
+ message: "Storage is required for registry plugin updates"
4457
+ }
4458
+ };
4459
+ if (!sandboxRunner || !sandboxRunner.isAvailable()) return {
4460
+ success: false,
4461
+ error: {
4462
+ code: "SANDBOX_NOT_AVAILABLE",
4463
+ message: withUnavailableReason("Sandbox runner is required", sandboxRunner)
4464
+ }
4465
+ };
4466
+ try {
4467
+ validateAggregatorUrl(registryConfig.aggregatorUrl);
4468
+ } catch (err) {
4469
+ return {
4470
+ success: false,
4471
+ error: {
4472
+ code: "REGISTRY_NOT_CONFIGURED",
4473
+ message: err instanceof Error ? err.message : "Invalid aggregator URL"
4474
+ }
4475
+ };
4476
+ }
4477
+ try {
4478
+ const stateRepo = new PluginStateRepository(db);
4479
+ const existing = await stateRepo.get(pluginId);
4480
+ if (!existing || existing.source !== "registry") return {
4481
+ success: false,
4482
+ error: {
4483
+ code: "NOT_FOUND",
4484
+ message: `No registry plugin found: ${pluginId}`
4485
+ }
4486
+ };
4487
+ if (!existing.registryPublisherDid || !existing.registrySlug) return {
4488
+ success: false,
4489
+ error: {
4490
+ code: "INVALID_STATE",
4491
+ message: `Registry plugin ${pluginId} is missing publisher DID or slug in state`
4492
+ }
4493
+ };
4494
+ const oldVersion = existing.version;
4495
+ const publisherDid = existing.registryPublisherDid;
4496
+ const slug = existing.registrySlug;
4497
+ const { DiscoveryClient, registryLabelerPolicy } = await import("@emdash-cms/registry-client/discovery");
4498
+ const aggregatorDeadline = Date.now() + AGGREGATOR_TOTAL_BUDGET_MS;
4499
+ const discovery = new DiscoveryClient({
4500
+ aggregatorUrl: registryConfig.aggregatorUrl,
4501
+ acceptLabelers: registryConfig.acceptLabelers,
4502
+ labelerPolicy: registryLabelerPolicy(registryConfig.acceptLabelers),
4503
+ fetch: timedFetch(aggregatorDeadline)
4504
+ });
4505
+ const MAX_LIST_PAGES = 20;
4506
+ const releaseView = await (async () => {
4507
+ if (!opts?.version) return discovery.getLatestRelease({
4508
+ did: publisherDid,
4509
+ package: slug
4510
+ });
4511
+ let cursor;
4512
+ const seenCursors = /* @__PURE__ */ new Set();
4513
+ for (let page = 0; page < MAX_LIST_PAGES; page++) {
4514
+ if (cursor !== void 0) {
4515
+ if (seenCursors.has(cursor)) break;
4516
+ seenCursors.add(cursor);
4517
+ }
4518
+ const result = await discovery.listReleases({
4519
+ did: publisherDid,
4520
+ package: slug,
4521
+ cursor,
4522
+ limit: 50
4523
+ });
4524
+ for (const r of result.releases) if (r.version === opts.version) return r;
4525
+ if (!result.cursor) break;
4526
+ cursor = result.cursor;
4527
+ }
4528
+ })();
4529
+ if (!releaseView) return {
4530
+ success: false,
4531
+ error: {
4532
+ code: "NO_VERSION",
4533
+ message: opts?.version ? `Version ${opts.version} not found for ${publisherDid}/${slug}` : `No installable release found for ${publisherDid}/${slug}`
4534
+ }
4535
+ };
4536
+ if (releaseView.did !== publisherDid || releaseView.package !== slug || opts?.version !== void 0 && releaseView.version !== opts.version) return {
4537
+ success: false,
4538
+ error: {
4539
+ code: "AGGREGATOR_IDENTITY_MISMATCH",
4540
+ message: "Aggregator returned a release view that does not match the requested package or version."
4541
+ }
4542
+ };
4543
+ const packageView = await discovery.getPackage({
4544
+ did: publisherDid,
4545
+ slug
4546
+ });
4547
+ if (!packageView || packageView.did !== publisherDid || packageView.slug !== slug) return {
4548
+ success: false,
4549
+ error: {
4550
+ code: "AGGREGATOR_IDENTITY_MISMATCH",
4551
+ message: "Aggregator returned a package view that does not match the installed plugin."
4552
+ }
4553
+ };
4554
+ const newVersion = releaseView.version;
4555
+ if (evaluateRegistryReleaseWithdrawal(releaseView, discovery.labelerPolicy).withdrawn) return {
4556
+ success: false,
4557
+ error: {
4558
+ code: "YANKED",
4559
+ message: "Release has been withdrawn"
4560
+ }
4561
+ };
4562
+ if (newVersion === oldVersion) return {
4563
+ success: false,
4564
+ error: {
4565
+ code: "ALREADY_UP_TO_DATE",
4566
+ message: "Plugin is already at the requested version"
4567
+ }
4568
+ };
4569
+ const authoritative = await (opts?.readAuthoritativeRecords ?? readAuthoritativePackageRelease)(publisherDid, slug, newVersion, opts?.authoritativeRecords);
4570
+ if (!authoritative.success) return registryRecordError(authoritative.error.code, authoritative.error.message);
4571
+ const records = authoritative.value;
4572
+ const { profile, release } = records.inspection.value;
4573
+ if (packageView.uri !== records.profile.uri || packageView.cid !== records.profile.cid || releaseView.uri !== records.release.uri || releaseView.cid !== records.release.cid) return {
4574
+ success: false,
4575
+ error: {
4576
+ code: "AGGREGATOR_RECORD_MISMATCH",
4577
+ message: "Aggregator metadata does not match the publisher's signed records."
4578
+ }
4579
+ };
4580
+ if (hasCurrentRecordLabel(packageView.labels ?? [], "security:yanked", records.profile) || hasCurrentRecordLabel(packageView.labels ?? [], "security-yanked", records.profile)) return {
4581
+ success: false,
4582
+ error: {
4583
+ code: "YANKED",
4584
+ message: "Package has been withdrawn"
4585
+ }
4586
+ };
4587
+ if (opts?.confirmCapabilityChanges || (opts?.acknowledgedPublicRoutes?.length ?? 0) > 0 || opts?.confirmMcpTools) {
4588
+ const consentError = recordConsentError({
4589
+ profileCid: opts?.acknowledgedProfileCid,
4590
+ releaseCid: opts?.acknowledgedReleaseCid
4591
+ }, records);
4592
+ if (consentError) return consentError;
4593
+ }
4594
+ if (opts?.hostEnv) {
4595
+ const envError = assertEnvCompatible(release.requires, opts.hostEnv);
4596
+ if (envError) return {
4597
+ success: false,
4598
+ error: envError
4599
+ };
4600
+ }
4601
+ const packageArtifact = release.artifacts.package;
4602
+ const declaredChecksum = packageArtifact?.checksum;
4603
+ if (!packageArtifact || !declaredChecksum) return {
4604
+ success: false,
4605
+ error: {
4606
+ code: "INVALID_RELEASE",
4607
+ message: "Release record is missing its package artifact or checksum"
4608
+ }
4609
+ };
4610
+ let artifactBytes;
4611
+ try {
4612
+ artifactBytes = await fetchArtifact(releaseView.artifactCaches ?? [], packageArtifact, {
4613
+ did: publisherDid,
4614
+ collection: NSID.packageRelease,
4615
+ rkey: `${slug}:${newVersion}`,
4616
+ cid: releaseView.cid
4617
+ }, release.auth);
4618
+ } catch (error) {
4619
+ if (error instanceof RegistryArtifactFetchError) return registryArtifactError(error.code, error.message, "update");
4620
+ throw error;
4621
+ }
4622
+ const artifactReport = await validateRegistryArtifact(artifactBytes, declaredChecksum, slug, newVersion);
4623
+ if (!artifactReport.success) return registryArtifactError(artifactReport.error.code, artifactReport.error.message, "update");
4624
+ const { bundle, artifactDigest, artifactDigests } = artifactReport.value;
4625
+ const recordReport = await verifyAuthoritativePackageRelease(records, artifactDigest, {
4626
+ ...opts?.authoritativeRecords,
4627
+ artifactDigests
4628
+ });
4629
+ if (!recordReport.success) return registryRecordError(recordReport.code, recordReport.reasons[0]?.message ?? "The release provenance is invalid.");
4630
+ const verification = recordVerificationSummary(records, recordReport);
4631
+ bundle.manifest = {
4632
+ ...bundle.manifest,
4633
+ id: pluginId
4634
+ };
4635
+ if (!verifiedAccessEqual(recordReport.value.declaredAccess, bundle.manifest.declaredAccess ?? {})) return {
4636
+ success: false,
4637
+ error: {
4638
+ code: "DECLARED_ACCESS_DRIFT",
4639
+ message: "The plugin bundle declares different permissions than its published record. Update refused."
4640
+ }
4641
+ };
4642
+ const oldBundle = await loadBundleFromR2(storage, pluginId, oldVersion, "registry");
4643
+ const capabilityChanges = diffCapabilities(oldBundle?.manifest.capabilities ?? [], bundle.manifest.capabilities);
4644
+ if (capabilityChanges.added.length > 0 && !opts?.confirmCapabilityChanges) return {
4645
+ success: false,
4646
+ error: {
4647
+ code: "CAPABILITY_ESCALATION",
4648
+ message: "Plugin update requires new capabilities",
4649
+ details: {
4650
+ capabilityChanges,
4651
+ verification
4652
+ }
4653
+ }
4654
+ };
4655
+ const newlyPublicRoutes = diffRouteVisibility(oldBundle?.manifest, bundle.manifest).newlyPublic.toSorted();
4656
+ const acknowledgedPublicRoutes = (opts?.acknowledgedPublicRoutes ?? []).filter((route) => typeof route === "string").toSorted();
4657
+ if (newlyPublicRoutes.length > 0 && JSON.stringify(acknowledgedPublicRoutes) !== JSON.stringify(newlyPublicRoutes)) return {
4658
+ success: false,
4659
+ error: {
4660
+ code: "ROUTE_VISIBILITY_ESCALATION",
4661
+ message: "Plugin update exposes new public (unauthenticated) routes",
4662
+ details: {
4663
+ routeVisibilityChanges: { newlyPublic: newlyPublicRoutes },
4664
+ capabilityChanges,
4665
+ verification
4666
+ }
4667
+ }
4668
+ };
4669
+ const oldMcpTools = [...oldBundle?.manifest.mcp?.tools ?? []].toSorted((a, b) => a.name.localeCompare(b.name));
4670
+ const newMcpTools = [...bundle.manifest.mcp?.tools ?? []].toSorted((a, b) => a.name.localeCompare(b.name));
4671
+ if (JSON.stringify(oldMcpTools) !== JSON.stringify(newMcpTools) && !opts?.confirmMcpTools) return {
4672
+ success: false,
4673
+ error: {
4674
+ code: "MCP_TOOL_CONSENT_REQUIRED",
4675
+ message: "Plugin update changes its MCP tools",
4676
+ details: {
4677
+ mcpTools: newMcpTools.map(({ inputSchema: _, outputSchema: __, ...tool }) => tool),
4678
+ verification
4679
+ }
4680
+ }
4681
+ };
4682
+ await storeBundleInR2(storage, pluginId, newVersion, bundle, "registry");
4683
+ await stateRepo.upsert(pluginId, newVersion, "active", {
4684
+ source: "registry",
4685
+ registryPublisherDid: publisherDid,
4686
+ registrySlug: slug,
4687
+ displayName: profile.name ?? slug,
4688
+ description: profile.description ?? void 0,
4689
+ mcpToolsEnabled: false,
4690
+ mcpToolsConsent: null
4691
+ });
4692
+ await syncDeclaredStorageIndexes(db, [bundle.manifest]);
4693
+ return {
4694
+ success: true,
4695
+ data: {
4696
+ pluginId,
4697
+ oldVersion,
4698
+ newVersion,
4699
+ capabilityChanges,
4700
+ routeVisibilityChanges: newlyPublicRoutes.length > 0 ? { newlyPublic: newlyPublicRoutes } : void 0,
4701
+ verification
4702
+ }
4703
+ };
4704
+ } catch (err) {
4705
+ if (err instanceof ClientValidationError) return {
4706
+ success: false,
4707
+ error: {
4708
+ code: "AGGREGATOR_RESPONSE_INVALID",
4709
+ message: `Aggregator returned a response that does not conform to its lexicon (${err.target})`
4710
+ }
4711
+ };
4712
+ if (err instanceof ClientResponseError) {
4713
+ if (err.error === "ListingUnavailable") return {
4714
+ success: false,
4715
+ error: {
4716
+ code: "LISTING_UNAVAILABLE",
4717
+ message: "This plugin is unavailable under the active registry policy"
4718
+ }
4719
+ };
4720
+ return {
4721
+ success: false,
4722
+ error: {
4723
+ code: err.status === 404 ? "AGGREGATOR_NOT_FOUND" : "AGGREGATOR_HTTP_ERROR",
4724
+ message: `Aggregator returned ${err.status}: ${err.error}`
4725
+ }
4726
+ };
4727
+ }
4728
+ if (err instanceof EmDashStorageError) return {
4729
+ success: false,
4730
+ error: {
4731
+ code: err.code ?? "STORAGE_ERROR",
4732
+ message: "Storage error while updating plugin"
4733
+ }
4734
+ };
4735
+ console.error("[registry-update] Failed:", err);
4736
+ return {
4737
+ success: false,
4738
+ error: {
4739
+ code: "UPDATE_FAILED",
4740
+ message: err instanceof Error ? err.message : "Failed to update plugin"
4741
+ }
4742
+ };
4743
+ }
4744
+ }
4745
+ /**
4746
+ * Bulk update check across every installed registry plugin. Queries the
4747
+ * aggregator for each plugin's latest release and reports `hasUpdate`
4748
+ * based on the version comparison. Plugins whose aggregator lookup fails
4749
+ * (unreachable, delisted, malformed) are skipped silently — one bad
4750
+ * publisher must not blank the whole admin Updates list.
4751
+ */
4752
+ async function handleRegistryUpdateCheck(db, registryConfigInput) {
4753
+ const registryConfig = coerceRegistryConfig(registryConfigInput);
4754
+ if (!registryConfig) return {
4755
+ success: false,
4756
+ error: {
4757
+ code: "REGISTRY_NOT_CONFIGURED",
4758
+ message: "Registry is not configured"
4759
+ }
4760
+ };
4761
+ try {
4762
+ const registryPlugins = await new PluginStateRepository(db).getRegistryPlugins();
4763
+ if (registryPlugins.length === 0) return {
4764
+ success: true,
4765
+ data: { items: [] }
4766
+ };
4767
+ const { DiscoveryClient, registryLabelerPolicy } = await import("@emdash-cms/registry-client/discovery");
4768
+ const aggregatorDeadline = Date.now() + AGGREGATOR_TOTAL_BUDGET_MS;
4769
+ const discovery = new DiscoveryClient({
4770
+ aggregatorUrl: registryConfig.aggregatorUrl,
4771
+ acceptLabelers: registryConfig.acceptLabelers,
4772
+ labelerPolicy: registryLabelerPolicy(registryConfig.acceptLabelers),
4773
+ fetch: timedFetch(aggregatorDeadline)
4774
+ });
4775
+ const items = [];
4776
+ for (const plugin of registryPlugins) {
4777
+ if (!plugin.registryPublisherDid || !plugin.registrySlug) continue;
4778
+ try {
4779
+ const releaseView = await discovery.getLatestRelease({
4780
+ did: plugin.registryPublisherDid,
4781
+ package: plugin.registrySlug
4782
+ });
4783
+ if (evaluateRegistryReleaseWithdrawal(releaseView, discovery.labelerPolicy).withdrawn) continue;
4784
+ const latest = releaseView.version;
4785
+ if (!latest) continue;
4786
+ const installed = plugin.version;
4787
+ items.push({
4788
+ pluginId: plugin.pluginId,
4789
+ installed,
4790
+ latest,
4791
+ hasUpdate: latest !== installed,
4792
+ hasCapabilityChanges: false,
4793
+ hasRouteVisibilityChanges: false
4794
+ });
4795
+ } catch (err) {
4796
+ console.warn(`[registry-update-check] Skipped ${plugin.pluginId}:`, err);
4797
+ }
4798
+ }
4799
+ return {
4800
+ success: true,
4801
+ data: { items }
4802
+ };
4803
+ } catch (err) {
4804
+ if (err instanceof ClientValidationError) return {
4805
+ success: false,
4806
+ error: {
4807
+ code: "AGGREGATOR_RESPONSE_INVALID",
4808
+ message: `Aggregator returned a response that does not conform to its lexicon (${err.target})`
4809
+ }
4810
+ };
4811
+ if (err instanceof ClientResponseError) return {
4812
+ success: false,
4813
+ error: {
4814
+ code: err.status === 404 ? "AGGREGATOR_NOT_FOUND" : "AGGREGATOR_HTTP_ERROR",
4815
+ message: `Aggregator returned ${err.status}: ${err.error}`
4816
+ }
4817
+ };
4818
+ console.error("[registry-update-check] Failed:", err);
4819
+ return {
4820
+ success: false,
4821
+ error: {
4822
+ code: "UPDATE_CHECK_FAILED",
4823
+ message: "Failed to check for registry updates"
4824
+ }
4825
+ };
4826
+ }
4827
+ }
4828
+
4829
+ //#endregion
4830
+ export { handleContentAuthors as A, handleContentList as B, handleMediaReplaceMetadata as C, handleRevisionRestore as D, handleRevisionList as E, handleContentDelete as F, handleContentSchedule as G, handleContentPermanentDelete as H, handleContentDiscardDraft as I, handleContentUnschedule as J, handleContentTranslations as K, handleContentDuplicate as L, handleContentCountScheduled as M, handleContentCountTrashed as N, buildManifestCollections as O, handleContentCreate as P, handleContentGet as R, handleMediaList as S, handleRevisionGet as T, handleContentPublish as U, handleContentListTrashed as V, handleContentRestore as W, handleScheduledPolicyRejection as X, handleContentUpdate as Y, validateRev as Z, handlePluginSettingsGet as _, handleMarketplaceGetPlugin as a, handleMediaDelete as b, handleMarketplaceUninstall as c, handleThemeGetDetail as d, handleThemeSearch as f, getPluginSettingsSchema as g, syncDeclaredStorageIndexes as h, handleRegistryUpdateCheck as i, handleContentCompare as j, generateManifest as k, handleMarketplaceUpdate as l, rollbackPluginUpdate as m, handleRegistryUninstall as n, handleMarketplaceInstall as o, loadBundleFromR2 as p, handleContentUnpublish as q, handleRegistryUpdate as r, handleMarketplaceSearch as s, handleRegistryInstall as t, handleMarketplaceUpdateCheck as u, handlePluginSettingsUpdate as v, handleMediaUpdate as w, handleMediaGet as x, handleMediaCreate as y, handleContentGetIncludingTrashed as z };
4831
+ //# sourceMappingURL=api-DmjKxPCY.mjs.map