emdash 0.15.0 → 0.16.1

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 (351) hide show
  1. package/dist/api/route-utils.mjs +10 -10
  2. package/dist/api/schemas/index.d.mts +1 -1
  3. package/dist/{api-CLwG_3dh.mjs → api-BNKqxyFX.mjs} +54 -14
  4. package/dist/{api-CLwG_3dh.mjs.map → api-BNKqxyFX.mjs.map} +1 -1
  5. package/dist/{apply-wJhM_bwU.mjs → apply-BOPaD-s9.mjs} +16 -16
  6. package/dist/{apply-wJhM_bwU.mjs.map → apply-BOPaD-s9.mjs.map} +1 -1
  7. package/dist/astro/index.d.mts +3 -3
  8. package/dist/astro/index.d.mts.map +1 -1
  9. package/dist/astro/index.mjs +33 -1
  10. package/dist/astro/index.mjs.map +1 -1
  11. package/dist/astro/middleware/auth.d.mts +3 -3
  12. package/dist/astro/middleware/auth.mjs +2 -2
  13. package/dist/astro/middleware/redirect.mjs +4 -4
  14. package/dist/astro/middleware/request-context.mjs +1 -1
  15. package/dist/astro/middleware.d.mts.map +1 -1
  16. package/dist/astro/middleware.mjs +66 -46
  17. package/dist/astro/middleware.mjs.map +1 -1
  18. package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs +3 -3
  19. package/dist/astro/routes/api/admin/allowed-domains/index.mjs +3 -3
  20. package/dist/astro/routes/api/admin/api-tokens/_id_.mjs +2 -2
  21. package/dist/astro/routes/api/admin/api-tokens/index.mjs +3 -3
  22. package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +8 -8
  23. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +9 -9
  24. package/dist/astro/routes/api/admin/bylines/index.mjs +9 -9
  25. package/dist/astro/routes/api/admin/comments/_id_/status.mjs +7 -7
  26. package/dist/astro/routes/api/admin/comments/_id_.mjs +5 -5
  27. package/dist/astro/routes/api/admin/comments/bulk.mjs +6 -6
  28. package/dist/astro/routes/api/admin/comments/counts.mjs +5 -5
  29. package/dist/astro/routes/api/admin/comments/index.mjs +6 -6
  30. package/dist/astro/routes/api/admin/hooks/exclusive/_hookName_.mjs +4 -4
  31. package/dist/astro/routes/api/admin/hooks/exclusive/index.mjs +3 -3
  32. package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs +3 -3
  33. package/dist/astro/routes/api/admin/oauth-clients/index.mjs +3 -3
  34. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +27 -27
  35. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +27 -27
  36. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +27 -27
  37. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +27 -27
  38. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +27 -27
  39. package/dist/astro/routes/api/admin/plugins/index.mjs +27 -27
  40. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +3 -3
  41. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +27 -27
  42. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +27 -27
  43. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +27 -27
  44. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +27 -27
  45. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.d.mts.map +1 -1
  46. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +41 -28
  47. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs.map +1 -1
  48. package/dist/astro/routes/api/admin/plugins/registry/artifact.d.mts +8 -0
  49. package/dist/astro/routes/api/admin/plugins/registry/artifact.d.mts.map +1 -0
  50. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +301 -0
  51. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs.map +1 -0
  52. package/dist/astro/routes/api/admin/plugins/registry/install.d.mts.map +1 -1
  53. package/dist/astro/routes/api/admin/plugins/registry/install.mjs +46 -28
  54. package/dist/astro/routes/api/admin/plugins/registry/install.mjs.map +1 -1
  55. package/dist/astro/routes/api/admin/plugins/updates.mjs +27 -27
  56. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +27 -27
  57. package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +3 -3
  58. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +27 -27
  59. package/dist/astro/routes/api/admin/users/_id_/disable.mjs +2 -2
  60. package/dist/astro/routes/api/admin/users/_id_/enable.mjs +2 -2
  61. package/dist/astro/routes/api/admin/users/_id_/index.mjs +3 -3
  62. package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +2 -2
  63. package/dist/astro/routes/api/admin/users/index.mjs +3 -3
  64. package/dist/astro/routes/api/auth/dev-bypass.mjs +3 -3
  65. package/dist/astro/routes/api/auth/invite/accept.mjs +2 -2
  66. package/dist/astro/routes/api/auth/invite/complete.mjs +3 -3
  67. package/dist/astro/routes/api/auth/invite/index.mjs +3 -3
  68. package/dist/astro/routes/api/auth/invite/register-options.mjs +3 -3
  69. package/dist/astro/routes/api/auth/logout.mjs +2 -2
  70. package/dist/astro/routes/api/auth/magic-link/send.mjs +4 -4
  71. package/dist/astro/routes/api/auth/magic-link/verify.mjs +2 -2
  72. package/dist/astro/routes/api/auth/me.mjs +3 -3
  73. package/dist/astro/routes/api/auth/passkey/_id_.mjs +3 -3
  74. package/dist/astro/routes/api/auth/passkey/index.mjs +2 -2
  75. package/dist/astro/routes/api/auth/passkey/options.mjs +4 -4
  76. package/dist/astro/routes/api/auth/passkey/register/options.mjs +3 -3
  77. package/dist/astro/routes/api/auth/passkey/register/verify.mjs +3 -3
  78. package/dist/astro/routes/api/auth/passkey/verify.mjs +3 -3
  79. package/dist/astro/routes/api/auth/signup/complete.mjs +3 -3
  80. package/dist/astro/routes/api/auth/signup/request.mjs +4 -4
  81. package/dist/astro/routes/api/auth/signup/verify.mjs +2 -2
  82. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +6 -6
  83. package/dist/astro/routes/api/content/_collection_/_id_/compare.mjs +3 -3
  84. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs +3 -3
  85. package/dist/astro/routes/api/content/_collection_/_id_/duplicate.mjs +3 -3
  86. package/dist/astro/routes/api/content/_collection_/_id_/permanent.mjs +3 -3
  87. package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs +4 -4
  88. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +4 -4
  89. package/dist/astro/routes/api/content/_collection_/_id_/restore.mjs +3 -3
  90. package/dist/astro/routes/api/content/_collection_/_id_/revisions.mjs +3 -3
  91. package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs +4 -4
  92. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +8 -8
  93. package/dist/astro/routes/api/content/_collection_/_id_/translations.mjs +3 -3
  94. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs +3 -3
  95. package/dist/astro/routes/api/content/_collection_/_id_.mjs +4 -4
  96. package/dist/astro/routes/api/content/_collection_/index.mjs +4 -4
  97. package/dist/astro/routes/api/content/_collection_/trash.mjs +4 -4
  98. package/dist/astro/routes/api/dashboard.mjs +7 -7
  99. package/dist/astro/routes/api/dev/emails.mjs +2 -2
  100. package/dist/astro/routes/api/import/probe.mjs +4 -4
  101. package/dist/astro/routes/api/import/wordpress/analyze.mjs +3 -3
  102. package/dist/astro/routes/api/import/wordpress/execute.d.mts +3 -3
  103. package/dist/astro/routes/api/import/wordpress/execute.mjs +8 -8
  104. package/dist/astro/routes/api/import/wordpress/media.mjs +4 -4
  105. package/dist/astro/routes/api/import/wordpress/prepare.mjs +6 -6
  106. package/dist/astro/routes/api/import/wordpress/rewrite-url-helpers.d.mts +11 -1
  107. package/dist/astro/routes/api/import/wordpress/rewrite-url-helpers.d.mts.map +1 -1
  108. package/dist/astro/routes/api/import/wordpress/rewrite-url-helpers.mjs +17 -1
  109. package/dist/astro/routes/api/import/wordpress/rewrite-url-helpers.mjs.map +1 -1
  110. package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts.map +1 -1
  111. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +7 -7
  112. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs.map +1 -1
  113. package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +4 -4
  114. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +5 -5
  115. package/dist/astro/routes/api/manifest.mjs +3 -3
  116. package/dist/astro/routes/api/mcp.mjs +26 -26
  117. package/dist/astro/routes/api/media/_id_/confirm.mjs +4 -4
  118. package/dist/astro/routes/api/media/_id_.mjs +4 -4
  119. package/dist/astro/routes/api/media/file/_...key_.mjs +2 -2
  120. package/dist/astro/routes/api/media/providers/_providerId_/_itemId_.mjs +3 -3
  121. package/dist/astro/routes/api/media/providers/_providerId_/index.mjs +3 -3
  122. package/dist/astro/routes/api/media/providers/index.mjs +3 -3
  123. package/dist/astro/routes/api/media/upload-url.mjs +4 -4
  124. package/dist/astro/routes/api/media.mjs +5 -5
  125. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +5 -5
  126. package/dist/astro/routes/api/menus/_name_/items.mjs +5 -5
  127. package/dist/astro/routes/api/menus/_name_/reorder.mjs +5 -5
  128. package/dist/astro/routes/api/menus/_name_/translations.mjs +5 -5
  129. package/dist/astro/routes/api/menus/_name_.mjs +5 -5
  130. package/dist/astro/routes/api/menus/index.mjs +5 -5
  131. package/dist/astro/routes/api/oauth/device/authorize.mjs +3 -3
  132. package/dist/astro/routes/api/oauth/device/code.mjs +4 -4
  133. package/dist/astro/routes/api/oauth/device/token.mjs +4 -4
  134. package/dist/astro/routes/api/oauth/register.mjs +2 -2
  135. package/dist/astro/routes/api/oauth/token/refresh.mjs +3 -3
  136. package/dist/astro/routes/api/oauth/token/revoke.mjs +3 -3
  137. package/dist/astro/routes/api/oauth/token.mjs +2 -2
  138. package/dist/astro/routes/api/openapi.json.mjs +2 -2
  139. package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +3 -3
  140. package/dist/astro/routes/api/redirects/404s/index.mjs +6 -6
  141. package/dist/astro/routes/api/redirects/404s/summary.mjs +6 -6
  142. package/dist/astro/routes/api/redirects/_id_.mjs +7 -7
  143. package/dist/astro/routes/api/redirects/index.mjs +7 -7
  144. package/dist/astro/routes/api/revisions/_revisionId_/index.mjs +3 -3
  145. package/dist/astro/routes/api/revisions/_revisionId_/restore.mjs +3 -3
  146. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +27 -27
  147. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +27 -27
  148. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +27 -27
  149. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +27 -27
  150. package/dist/astro/routes/api/schema/collections/index.mjs +27 -27
  151. package/dist/astro/routes/api/schema/index.mjs +6 -6
  152. package/dist/astro/routes/api/schema/orphans/_slug_.mjs +27 -27
  153. package/dist/astro/routes/api/schema/orphans/index.mjs +27 -27
  154. package/dist/astro/routes/api/search/enable.mjs +7 -7
  155. package/dist/astro/routes/api/search/index.mjs +6 -6
  156. package/dist/astro/routes/api/search/rebuild.mjs +7 -7
  157. package/dist/astro/routes/api/search/stats.mjs +6 -6
  158. package/dist/astro/routes/api/search/suggest.mjs +6 -6
  159. package/dist/astro/routes/api/sections/_slug_.mjs +6 -6
  160. package/dist/astro/routes/api/sections/index.mjs +6 -6
  161. package/dist/astro/routes/api/settings/email.mjs +4 -4
  162. package/dist/astro/routes/api/settings.mjs +8 -8
  163. package/dist/astro/routes/api/setup/admin-verify.mjs +3 -3
  164. package/dist/astro/routes/api/setup/admin.mjs +3 -3
  165. package/dist/astro/routes/api/setup/dev-bypass.mjs +15 -15
  166. package/dist/astro/routes/api/setup/dev-reset.mjs +2 -2
  167. package/dist/astro/routes/api/setup/index.mjs +16 -16
  168. package/dist/astro/routes/api/setup/status.mjs +3 -3
  169. package/dist/astro/routes/api/snapshot.mjs +4 -4
  170. package/dist/astro/routes/api/snapshot.mjs.map +1 -1
  171. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +9 -9
  172. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +9 -9
  173. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +9 -9
  174. package/dist/astro/routes/api/taxonomies/index.mjs +9 -9
  175. package/dist/astro/routes/api/themes/preview.mjs +3 -3
  176. package/dist/astro/routes/api/typegen.mjs +5 -5
  177. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +4 -4
  178. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +6 -6
  179. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +6 -6
  180. package/dist/astro/routes/api/widget-areas/_name_.mjs +5 -5
  181. package/dist/astro/routes/api/widget-areas/index.mjs +6 -6
  182. package/dist/astro/routes/api/widget-components.mjs +2 -2
  183. package/dist/astro/routes/robots.txt.mjs +4 -4
  184. package/dist/astro/routes/sitemap-_collection_.xml.d.mts.map +1 -1
  185. package/dist/astro/routes/sitemap-_collection_.xml.mjs +58 -13
  186. package/dist/astro/routes/sitemap-_collection_.xml.mjs.map +1 -1
  187. package/dist/astro/routes/sitemap.xml.mjs +5 -5
  188. package/dist/astro/types.d.mts +10 -3
  189. package/dist/astro/types.d.mts.map +1 -1
  190. package/dist/{authorize-Bkwe8kuL.mjs → authorize-Bn4S4DUT.mjs} +2 -2
  191. package/dist/{authorize-Bkwe8kuL.mjs.map → authorize-Bn4S4DUT.mjs.map} +1 -1
  192. package/dist/{byline-CTaWkMh5.mjs → byline-BDylH_m4.mjs} +3 -3
  193. package/dist/{byline-CTaWkMh5.mjs.map → byline-BDylH_m4.mjs.map} +1 -1
  194. package/dist/{bylines-H0Xh5TMy.mjs → bylines-B7TFEvFf.mjs} +2 -2
  195. package/dist/{bylines-H0Xh5TMy.mjs.map → bylines-B7TFEvFf.mjs.map} +1 -1
  196. package/dist/{bylines-DtDRNF1n.d.mts → bylines-DWLnr6-k.d.mts} +17 -17
  197. package/dist/{bylines-DtDRNF1n.d.mts.map → bylines-DWLnr6-k.d.mts.map} +1 -1
  198. package/dist/{bylines-BYHWU3T7.mjs → bylines-n6nykUyI.mjs} +6 -6
  199. package/dist/{bylines-BYHWU3T7.mjs.map → bylines-n6nykUyI.mjs.map} +1 -1
  200. package/dist/{cache-CNk1jIxp.mjs → cache-BcI1yUjR.mjs} +2 -2
  201. package/dist/{cache-CNk1jIxp.mjs.map → cache-BcI1yUjR.mjs.map} +1 -1
  202. package/dist/{chunks-BkfVdD-3.mjs → chunks-cYG4SnIP.mjs} +2 -2
  203. package/dist/{chunks-BkfVdD-3.mjs.map → chunks-cYG4SnIP.mjs.map} +1 -1
  204. package/dist/cli/index.mjs +61 -15
  205. package/dist/cli/index.mjs.map +1 -1
  206. package/dist/client/cf-access.d.mts +1 -1
  207. package/dist/client/index.d.mts +1 -1
  208. package/dist/{comment-_yzlBYPx.mjs → comment-C76G-9tz.mjs} +2 -2
  209. package/dist/{comment-_yzlBYPx.mjs.map → comment-C76G-9tz.mjs.map} +1 -1
  210. package/dist/{comments-DxID-rsd.mjs → comments-CCxFFGY1.mjs} +3 -3
  211. package/dist/{comments-DxID-rsd.mjs.map → comments-CCxFFGY1.mjs.map} +1 -1
  212. package/dist/{content-C0ooIs-f.mjs → content-8voQNTXX.mjs} +3 -3
  213. package/dist/{content-C0ooIs-f.mjs.map → content-8voQNTXX.mjs.map} +1 -1
  214. package/dist/{context-sAnCaUIR.mjs → context-B7qiYrz2.mjs} +7 -7
  215. package/dist/{context-sAnCaUIR.mjs.map → context-B7qiYrz2.mjs.map} +1 -1
  216. package/dist/{dashboard-Cqw3ay2X.mjs → dashboard-BeaFSPpx.mjs} +4 -4
  217. package/dist/{dashboard-Cqw3ay2X.mjs.map → dashboard-BeaFSPpx.mjs.map} +1 -1
  218. package/dist/db/index.d.mts +1 -1
  219. package/dist/db/index.mjs +1 -1
  220. package/dist/db/sqlite.mjs +1 -1
  221. package/dist/{db-errors-CGN9kJfo.mjs → db-errors-BiYqoX-n.mjs} +14 -2
  222. package/dist/db-errors-BiYqoX-n.mjs.map +1 -0
  223. package/dist/{error-CPh_8eLq.mjs → error-ChfADBuu.mjs} +5 -3
  224. package/dist/error-ChfADBuu.mjs.map +1 -0
  225. package/dist/errors-9P_FDrJ_.mjs +17 -0
  226. package/dist/errors-9P_FDrJ_.mjs.map +1 -0
  227. package/dist/{fts-manager-Mnrtn-r2.mjs → fts-manager-C_b-4x8u.mjs} +2 -2
  228. package/dist/{fts-manager-Mnrtn-r2.mjs.map → fts-manager-C_b-4x8u.mjs.map} +1 -1
  229. package/dist/{index-Bv1Wf1zB.d.mts → index-D_p_jIP1.d.mts} +153 -109
  230. package/dist/index-D_p_jIP1.d.mts.map +1 -0
  231. package/dist/index.d.mts +4 -4
  232. package/dist/index.mjs +38 -38
  233. package/dist/{load-DmXNVhst.mjs → load-CLFRjk9r.mjs} +2 -2
  234. package/dist/{load-DmXNVhst.mjs.map → load-CLFRjk9r.mjs.map} +1 -1
  235. package/dist/{loader-Chm5h7Gr.mjs → loader-D-vIJjfY.mjs} +86 -46
  236. package/dist/loader-D-vIJjfY.mjs.map +1 -0
  237. package/dist/media/local-runtime.d.mts +3 -3
  238. package/dist/media/local-runtime.mjs +4 -4
  239. package/dist/{media-oqRcNiQf.mjs → media-CKQd8AYU.mjs} +2 -2
  240. package/dist/{media-oqRcNiQf.mjs.map → media-CKQd8AYU.mjs.map} +1 -1
  241. package/dist/{menus-C75SSmRy.mjs → menus-C-nWT5Tu.mjs} +17 -11
  242. package/dist/menus-C-nWT5Tu.mjs.map +1 -0
  243. package/dist/{menus-Bjf5R1Qq.mjs → menus-arUNspyU.mjs} +2 -2
  244. package/dist/{menus-Bjf5R1Qq.mjs.map → menus-arUNspyU.mjs.map} +1 -1
  245. package/dist/{parse-3-caTKgt.mjs → parse-DHbXfvxO.mjs} +2 -2
  246. package/dist/{parse-3-caTKgt.mjs.map → parse-DHbXfvxO.mjs.map} +1 -1
  247. package/dist/plugin-utils.d.mts +25 -10
  248. package/dist/plugin-utils.d.mts.map +1 -1
  249. package/dist/plugin-utils.mjs +11 -10
  250. package/dist/plugin-utils.mjs.map +1 -1
  251. package/dist/plugins/adapt-sandbox-entry.d.mts +3 -3
  252. package/dist/{query-BJn8TOPk.mjs → query-7m6-l0f_.mjs} +21 -14
  253. package/dist/query-7m6-l0f_.mjs.map +1 -0
  254. package/dist/{rate-limit-D_-gAeJ0.mjs → rate-limit-D8RAXN8b.mjs} +2 -2
  255. package/dist/{rate-limit-D_-gAeJ0.mjs.map → rate-limit-D8RAXN8b.mjs.map} +1 -1
  256. package/dist/{redirect-CNv4mHX2.mjs → redirect-CjfDGrTd.mjs} +2 -2
  257. package/dist/{redirect-CNv4mHX2.mjs.map → redirect-CjfDGrTd.mjs.map} +1 -1
  258. package/dist/{redirects-B-CUZ1Xh.mjs → redirects-CowoEHdE.mjs} +3 -3
  259. package/dist/{redirects-B-CUZ1Xh.mjs.map → redirects-CowoEHdE.mjs.map} +1 -1
  260. package/dist/{registry-DqrAQDXH.mjs → registry-Cyp-dx6J.mjs} +4 -4
  261. package/dist/{registry-DqrAQDXH.mjs.map → registry-Cyp-dx6J.mjs.map} +1 -1
  262. package/dist/resolve-D6sM-SgF.mjs +143 -0
  263. package/dist/resolve-D6sM-SgF.mjs.map +1 -0
  264. package/dist/{runner-CNHRo1mT.d.mts → runner-DSQBurMS.d.mts} +7 -4
  265. package/dist/runner-DSQBurMS.d.mts.map +1 -0
  266. package/dist/{runner-CGlojznK.mjs → runner-Drnvs96u.mjs} +20 -24
  267. package/dist/{runner-CGlojznK.mjs.map → runner-Drnvs96u.mjs.map} +1 -1
  268. package/dist/runtime.d.mts +3 -3
  269. package/dist/runtime.mjs +2 -2
  270. package/dist/{schema-Djdlfi5G.mjs → schema-CI9mYPX3.mjs} +4 -4
  271. package/dist/{schema-Djdlfi5G.mjs.map → schema-CI9mYPX3.mjs.map} +1 -1
  272. package/dist/{search-By-NN3da.mjs → search-DKz_mGBP.mjs} +4 -4
  273. package/dist/{search-By-NN3da.mjs.map → search-DKz_mGBP.mjs.map} +1 -1
  274. package/dist/{sections-DcBIlOq1.mjs → sections-DBbCDIAT.mjs} +3 -3
  275. package/dist/{sections-DcBIlOq1.mjs.map → sections-DBbCDIAT.mjs.map} +1 -1
  276. package/dist/seed/index.mjs +13 -13
  277. package/dist/{seo-bjDoq9Eg.mjs → seo-BGCyDlkb.mjs} +2 -2
  278. package/dist/{seo-bjDoq9Eg.mjs.map → seo-BGCyDlkb.mjs.map} +1 -1
  279. package/dist/{seo-BoR4wCUh.mjs → seo-Dq707mNQ.mjs} +5 -3
  280. package/dist/seo-Dq707mNQ.mjs.map +1 -0
  281. package/dist/{service-BuuTdGAT.mjs → service-B0H7U1Y9.mjs} +2 -2
  282. package/dist/{service-BuuTdGAT.mjs.map → service-B0H7U1Y9.mjs.map} +1 -1
  283. package/dist/{settings-hcubRfkr.mjs → settings-BSXRtTzk.mjs} +3 -3
  284. package/dist/{settings-hcubRfkr.mjs.map → settings-BSXRtTzk.mjs.map} +1 -1
  285. package/dist/{settings-CJnKiWuR.mjs → settings-DfwNyQkf.mjs} +3 -3
  286. package/dist/{settings-CJnKiWuR.mjs.map → settings-DfwNyQkf.mjs.map} +1 -1
  287. package/dist/{taxonomies-CLs9HPE2.mjs → taxonomies-4vx0nmMr.mjs} +4 -4
  288. package/dist/{taxonomies-CLs9HPE2.mjs.map → taxonomies-4vx0nmMr.mjs.map} +1 -1
  289. package/dist/{taxonomies-WamPVA2x.mjs → taxonomies-CcvrMLbR.mjs} +7 -7
  290. package/dist/{taxonomies-WamPVA2x.mjs.map → taxonomies-CcvrMLbR.mjs.map} +1 -1
  291. package/dist/{taxonomy-D4Uc2LsZ.mjs → taxonomy-zqGQUqgu.mjs} +3 -3
  292. package/dist/{taxonomy-D4Uc2LsZ.mjs.map → taxonomy-zqGQUqgu.mjs.map} +1 -1
  293. package/dist/{transport-DOxLfUir.d.mts → transport-C2MGqtL6.d.mts} +1 -1
  294. package/dist/{transport-DOxLfUir.d.mts.map → transport-C2MGqtL6.d.mts.map} +1 -1
  295. package/dist/{types-ByV5sgsv.mjs → types-B0bmgwMG.mjs} +2 -2
  296. package/dist/{types-ByV5sgsv.mjs.map → types-B0bmgwMG.mjs.map} +1 -1
  297. package/dist/{user-D3BD5zdT.mjs → user-hUSOaIJy.mjs} +2 -2
  298. package/dist/{user-D3BD5zdT.mjs.map → user-hUSOaIJy.mjs.map} +1 -1
  299. package/dist/{validate-mz87i8_1.mjs → validate-IGltez8n.mjs} +2 -2
  300. package/dist/{validate-mz87i8_1.mjs.map → validate-IGltez8n.mjs.map} +1 -1
  301. package/dist/{validation-DKHhXjPr.mjs → validation-Bmymau7y.mjs} +6 -6
  302. package/dist/{validation-DKHhXjPr.mjs.map → validation-Bmymau7y.mjs.map} +1 -1
  303. package/dist/version-ITD3PlQd.mjs +7 -0
  304. package/dist/{version-Ct7C6RSo.mjs.map → version-ITD3PlQd.mjs.map} +1 -1
  305. package/dist/{widgets-lShIQXU5.mjs → widgets-yHQa4c6c.mjs} +2 -2
  306. package/dist/{widgets-lShIQXU5.mjs.map → widgets-yHQa4c6c.mjs.map} +1 -1
  307. package/dist/{zod-generator-dvxgmd1M.mjs → zod-generator-B80aap1J.mjs} +2 -2
  308. package/dist/{zod-generator-dvxgmd1M.mjs.map → zod-generator-B80aap1J.mjs.map} +1 -1
  309. package/package.json +7 -7
  310. package/src/api/errors.ts +2 -0
  311. package/src/api/handlers/index.ts +2 -0
  312. package/src/api/handlers/registry.ts +69 -1
  313. package/src/api/handlers/seo.ts +16 -1
  314. package/src/api/handlers/snapshot.ts +1 -1
  315. package/src/astro/integration/index.ts +26 -0
  316. package/src/astro/integration/routes.ts +5 -0
  317. package/src/astro/integration/runtime.ts +8 -0
  318. package/src/astro/middleware.ts +4 -0
  319. package/src/astro/public-plugin-api-routes.ts +41 -0
  320. package/src/astro/routes/api/admin/plugins/registry/[id]/update.ts +4 -0
  321. package/src/astro/routes/api/admin/plugins/registry/artifact.ts +388 -0
  322. package/src/astro/routes/api/admin/plugins/registry/install.ts +7 -1
  323. package/src/astro/routes/api/import/wordpress/rewrite-url-helpers.ts +22 -0
  324. package/src/astro/routes/api/import/wordpress/rewrite-urls.ts +5 -2
  325. package/src/astro/routes/sitemap-[collection].xml.ts +114 -14
  326. package/src/astro/types.ts +14 -0
  327. package/src/content/converters/portable-text-to-prosemirror.ts +35 -11
  328. package/src/database/connection.ts +3 -10
  329. package/src/database/errors.ts +14 -0
  330. package/src/database/index.ts +3 -1
  331. package/src/database/migrations/runner.ts +29 -21
  332. package/src/emdash-runtime.ts +1 -0
  333. package/src/i18n/resolve.ts +152 -0
  334. package/src/index.ts +2 -0
  335. package/src/loader.ts +133 -59
  336. package/src/plugin-utils.ts +23 -0
  337. package/src/query.ts +24 -5
  338. package/src/utils/db-errors.ts +24 -0
  339. package/dist/connection-2igzM-AT.mjs +0 -57
  340. package/dist/connection-2igzM-AT.mjs.map +0 -1
  341. package/dist/db-errors-CGN9kJfo.mjs.map +0 -1
  342. package/dist/error-CPh_8eLq.mjs.map +0 -1
  343. package/dist/index-Bv1Wf1zB.d.mts.map +0 -1
  344. package/dist/loader-Chm5h7Gr.mjs.map +0 -1
  345. package/dist/menus-C75SSmRy.mjs.map +0 -1
  346. package/dist/query-BJn8TOPk.mjs.map +0 -1
  347. package/dist/resolve-Cj98DuqN.mjs +0 -39
  348. package/dist/resolve-Cj98DuqN.mjs.map +0 -1
  349. package/dist/runner-CNHRo1mT.d.mts.map +0 -1
  350. package/dist/seo-BoR4wCUh.mjs.map +0 -1
  351. package/dist/version-Ct7C6RSo.mjs +0 -7
@@ -1 +1 @@
1
- {"version":3,"file":"context-sAnCaUIR.mjs","names":[],"sources":["../src/plugins/storage-query.ts","../src/database/repositories/plugin-storage.ts","../src/plugins/context.ts"],"sourcesContent":["/**\n * Plugin Storage Query Validation and Building\n *\n * Validates that queries only use indexed fields and builds SQL WHERE clauses.\n *\n * @see PLUGIN-SYSTEM.md § Plugin Storage > Query Validation\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { jsonExtractExpr } from \"../database/dialect-helpers.js\";\nimport { validateJsonFieldName } from \"../database/validate.js\";\nimport type { WhereClause, WhereValue, RangeFilter, InFilter, StartsWithFilter } from \"./types.js\";\n\n/**\n * Error thrown when querying non-indexed fields\n */\nexport class StorageQueryError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic field?: string,\n\t\tpublic suggestion?: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"StorageQueryError\";\n\t}\n}\n\n/**\n * Check if a value is a range filter\n */\nexport function isRangeFilter(value: WhereValue): value is RangeFilter {\n\tif (typeof value !== \"object\" || value === null) return false;\n\treturn \"gt\" in value || \"gte\" in value || \"lt\" in value || \"lte\" in value;\n}\n\n/**\n * Check if a value is an IN filter\n */\nexport function isInFilter(value: WhereValue): value is InFilter {\n\tif (typeof value !== \"object\" || value === null) return false;\n\treturn \"in\" in value && Array.isArray(value.in);\n}\n\n/**\n * Check if a value is a startsWith filter\n */\nexport function isStartsWithFilter(value: WhereValue): value is StartsWithFilter {\n\tif (typeof value !== \"object\" || value === null) return false;\n\treturn \"startsWith\" in value && typeof value.startsWith === \"string\";\n}\n\n/**\n * Get the set of indexed fields from index declarations\n */\nexport function getIndexedFields(indexes: Array<string | string[]>): Set<string> {\n\tconst fields = new Set<string>();\n\tfor (const index of indexes) {\n\t\tif (Array.isArray(index)) {\n\t\t\tfor (const field of index) {\n\t\t\t\tfields.add(field);\n\t\t\t}\n\t\t} else {\n\t\t\tfields.add(index);\n\t\t}\n\t}\n\treturn fields;\n}\n\n/**\n * Validate that all fields in a where clause are indexed\n */\nexport function validateWhereClause(\n\twhere: WhereClause,\n\tindexedFields: Set<string>,\n\tpluginId: string,\n\tcollection: string,\n): void {\n\tfor (const field of Object.keys(where)) {\n\t\tif (!indexedFields.has(field)) {\n\t\t\tthrow new StorageQueryError(\n\t\t\t\t`Cannot query on non-indexed field '${field}'.`,\n\t\t\t\tfield,\n\t\t\t\t`Add '${field}' to storage.${collection}.indexes in plugin '${pluginId}' to enable this query.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Validate orderBy fields are indexed\n */\nexport function validateOrderByClause(\n\torderBy: Record<string, \"asc\" | \"desc\">,\n\tindexedFields: Set<string>,\n\tpluginId: string,\n\tcollection: string,\n): void {\n\tfor (const field of Object.keys(orderBy)) {\n\t\tif (!indexedFields.has(field)) {\n\t\t\tthrow new StorageQueryError(\n\t\t\t\t`Cannot order by non-indexed field '${field}'.`,\n\t\t\t\tfield,\n\t\t\t\t`Add '${field}' to storage.${collection}.indexes in plugin '${pluginId}' to enable ordering by this field.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * SQL expression for extracting JSON field.\n *\n * Validates the field name before interpolation to prevent SQL injection\n * via crafted JSON path expressions.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function jsonExtract(db: Kysely<any>, field: string): string {\n\tvalidateJsonFieldName(field, \"query field name\");\n\treturn jsonExtractExpr(db, \"data\", field);\n}\n\n/**\n * Build a WHERE clause condition for a single field\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function buildCondition(\n\tdb: Kysely<any>,\n\tfield: string,\n\tvalue: WhereValue,\n): { sql: string; params: unknown[] } {\n\tconst extract = jsonExtract(db, field);\n\n\tif (value === null) {\n\t\treturn { sql: `${extract} IS NULL`, params: [] };\n\t}\n\n\tif (typeof value === \"string\" || typeof value === \"number\") {\n\t\treturn { sql: `${extract} = ?`, params: [value] };\n\t}\n\n\tif (typeof value === \"boolean\") {\n\t\t// JSON booleans are stored as true/false strings\n\t\treturn { sql: `${extract} = ?`, params: [value] };\n\t}\n\n\tif (isInFilter(value)) {\n\t\tconst placeholders = value.in.map(() => \"?\").join(\", \");\n\t\treturn {\n\t\t\tsql: `${extract} IN (${placeholders})`,\n\t\t\tparams: value.in,\n\t\t};\n\t}\n\n\tif (isStartsWithFilter(value)) {\n\t\treturn {\n\t\t\tsql: `${extract} LIKE ?`,\n\t\t\tparams: [`${value.startsWith}%`],\n\t\t};\n\t}\n\n\tif (isRangeFilter(value)) {\n\t\tconst conditions: string[] = [];\n\t\tconst params: unknown[] = [];\n\n\t\tif (value.gt !== undefined) {\n\t\t\tconditions.push(`${extract} > ?`);\n\t\t\tparams.push(value.gt);\n\t\t}\n\t\tif (value.gte !== undefined) {\n\t\t\tconditions.push(`${extract} >= ?`);\n\t\t\tparams.push(value.gte);\n\t\t}\n\t\tif (value.lt !== undefined) {\n\t\t\tconditions.push(`${extract} < ?`);\n\t\t\tparams.push(value.lt);\n\t\t}\n\t\tif (value.lte !== undefined) {\n\t\t\tconditions.push(`${extract} <= ?`);\n\t\t\tparams.push(value.lte);\n\t\t}\n\n\t\treturn {\n\t\t\tsql: conditions.join(\" AND \"),\n\t\t\tparams,\n\t\t};\n\t}\n\n\tthrow new StorageQueryError(`Unknown filter type for field '${field}'`);\n}\n\n/**\n * Build a complete WHERE clause from a WhereClause object\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function buildWhereClause(\n\tdb: Kysely<any>,\n\twhere: WhereClause,\n): {\n\tsql: string;\n\tparams: unknown[];\n} {\n\tconst conditions: string[] = [];\n\tconst params: unknown[] = [];\n\n\tfor (const [field, value] of Object.entries(where)) {\n\t\tconst condition = buildCondition(db, field, value);\n\t\tconditions.push(condition.sql);\n\t\tparams.push(...condition.params);\n\t}\n\n\tif (conditions.length === 0) {\n\t\treturn { sql: \"\", params: [] };\n\t}\n\n\treturn {\n\t\tsql: conditions.join(\" AND \"),\n\t\tparams,\n\t};\n}\n\n/**\n * Build ORDER BY clause\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function buildOrderByClause(\n\tdb: Kysely<any>,\n\torderBy: Record<string, \"asc\" | \"desc\">,\n): string {\n\tconst clauses: string[] = [];\n\n\tfor (const [field, direction] of Object.entries(orderBy)) {\n\t\tclauses.push(`${jsonExtract(db, field)} ${direction.toUpperCase()}`);\n\t}\n\n\tif (clauses.length === 0) {\n\t\treturn \"\";\n\t}\n\n\treturn `ORDER BY ${clauses.join(\", \")}`;\n}\n","/**\n * Plugin Storage Repository\n *\n * Provides a document store API for plugin data storage.\n * Uses a single _plugin_storage table with JSON documents and expression indexes.\n *\n * @see PLUGIN-SYSTEM.md § Plugin Storage > Full API Reference\n */\n\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport {\n\tbuildWhereClause,\n\tvalidateWhereClause,\n\tvalidateOrderByClause,\n\tgetIndexedFields,\n\tjsonExtract,\n} from \"../../plugins/storage-query.js\";\nimport type {\n\tStorageCollection,\n\tQueryOptions,\n\tPaginatedResult,\n\tWhereClause,\n} from \"../../plugins/types.js\";\nimport { withTransaction } from \"../transaction.js\";\nimport type { Database } from \"../types.js\";\nimport { encodeCursor, decodeCursor } from \"./types.js\";\n\n/**\n * Plugin Storage Repository\n *\n * Implements the StorageCollection interface for a specific plugin and collection.\n */\nexport class PluginStorageRepository<T = unknown> implements StorageCollection<T> {\n\tprivate indexedFields: Set<string>;\n\n\tconstructor(\n\t\tprivate db: Kysely<Database>,\n\t\tprivate pluginId: string,\n\t\tprivate collection: string,\n\t\tindexes: Array<string | string[]>,\n\t) {\n\t\tthis.indexedFields = getIndexedFields(indexes);\n\t}\n\n\t/**\n\t * Get a document by ID\n\t */\n\tasync get(id: string): Promise<T | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select(\"data\")\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) return null;\n\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- JSON.parse returns any; generic callers provide T\n\t\treturn JSON.parse(row.data) as T;\n\t}\n\n\t/**\n\t * Store a document\n\t */\n\tasync put(id: string, data: T): Promise<void> {\n\t\tconst now = new Date().toISOString();\n\t\tconst jsonData = JSON.stringify(data);\n\n\t\tawait this.db\n\t\t\t.insertInto(\"_plugin_storage\")\n\t\t\t.values({\n\t\t\t\tplugin_id: this.pluginId,\n\t\t\t\tcollection: this.collection,\n\t\t\t\tid,\n\t\t\t\tdata: jsonData,\n\t\t\t\tcreated_at: now,\n\t\t\t\tupdated_at: now,\n\t\t\t})\n\t\t\t.onConflict((oc) =>\n\t\t\t\toc.columns([\"plugin_id\", \"collection\", \"id\"]).doUpdateSet({\n\t\t\t\t\tdata: jsonData,\n\t\t\t\t\tupdated_at: now,\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.execute();\n\t}\n\n\t/**\n\t * Delete a document\n\t */\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_plugin_storage\")\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\treturn (result.numDeletedRows ?? 0) > 0;\n\t}\n\n\t/**\n\t * Check if a document exists\n\t */\n\tasync exists(id: string): Promise<boolean> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\treturn !!row;\n\t}\n\n\t/**\n\t * Get multiple documents by ID\n\t */\n\tasync getMany(ids: string[]): Promise<Map<string, T>> {\n\t\tif (ids.length === 0) return new Map();\n\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select([\"id\", \"data\"])\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"in\", ids)\n\t\t\t.execute();\n\n\t\tconst result = new Map<string, T>();\n\t\tfor (const row of rows) {\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- JSON.parse returns any; generic callers provide T\n\t\t\tresult.set(row.id, JSON.parse(row.data) as T);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Store multiple documents\n\t */\n\tasync putMany(items: Array<{ id: string; data: T }>): Promise<void> {\n\t\tif (items.length === 0) return;\n\n\t\tconst now = new Date().toISOString();\n\n\t\t// SQLite doesn't support batch upserts well, so we do them one at a time\n\t\t// In a transaction for atomicity\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\tfor (const item of items) {\n\t\t\t\tconst jsonData = JSON.stringify(item.data);\n\t\t\t\tawait trx\n\t\t\t\t\t.insertInto(\"_plugin_storage\")\n\t\t\t\t\t.values({\n\t\t\t\t\t\tplugin_id: this.pluginId,\n\t\t\t\t\t\tcollection: this.collection,\n\t\t\t\t\t\tid: item.id,\n\t\t\t\t\t\tdata: jsonData,\n\t\t\t\t\t\tcreated_at: now,\n\t\t\t\t\t\tupdated_at: now,\n\t\t\t\t\t})\n\t\t\t\t\t.onConflict((oc) =>\n\t\t\t\t\t\toc.columns([\"plugin_id\", \"collection\", \"id\"]).doUpdateSet({\n\t\t\t\t\t\t\tdata: jsonData,\n\t\t\t\t\t\t\tupdated_at: now,\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t\t.execute();\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Delete multiple documents\n\t */\n\tasync deleteMany(ids: string[]): Promise<number> {\n\t\tif (ids.length === 0) return 0;\n\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_plugin_storage\")\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"in\", ids)\n\t\t\t.executeTakeFirst();\n\n\t\treturn Number(result.numDeletedRows ?? 0);\n\t}\n\n\t/**\n\t * Query documents with filters\n\t */\n\tasync query(options: QueryOptions = {}): Promise<PaginatedResult<{ id: string; data: T }>> {\n\t\tconst { where = {}, orderBy = {}, cursor } = options;\n\t\tconst limit = Math.min(options.limit ?? 50, 100);\n\n\t\t// Validate that all queried fields are indexed\n\t\tvalidateWhereClause(where, this.indexedFields, this.pluginId, this.collection);\n\t\tif (Object.keys(orderBy).length > 0) {\n\t\t\tvalidateOrderByClause(orderBy, this.indexedFields, this.pluginId, this.collection);\n\t\t}\n\n\t\t// Build base query\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select([\"id\", \"data\", \"created_at\"])\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection);\n\n\t\t// Add JSON extraction WHERE conditions\n\t\tconst whereResult = buildWhereClause(this.db, where);\n\t\tif (whereResult.sql) {\n\t\t\t// Use sql template to add the raw WHERE conditions with params\n\t\t\tconst whereSqlParts: ReturnType<typeof sql>[] = [];\n\t\t\tlet paramIndex = 0;\n\t\t\tconst sqlParts = whereResult.sql.split(\"?\");\n\t\t\tfor (let i = 0; i < sqlParts.length; i++) {\n\t\t\t\tif (i > 0) {\n\t\t\t\t\twhereSqlParts.push(sql`${whereResult.params[paramIndex++]}`);\n\t\t\t\t}\n\t\t\t\tif (sqlParts[i]) {\n\t\t\t\t\twhereSqlParts.push(sql.raw(sqlParts[i]));\n\t\t\t\t}\n\t\t\t}\n\t\t\tquery = query.where(({ eb }) => eb(sql.join(whereSqlParts, sql.raw(\"\")), \"=\", sql.raw(\"1\")));\n\t\t}\n\n\t\t// Handle cursor-based pagination — throws on invalid cursor.\n\t\tif (cursor) {\n\t\t\tconst decoded = decodeCursor(cursor);\n\t\t\tquery = query.where(({ eb }) =>\n\t\t\t\teb(sql`(created_at, id)`, \">\", sql`(${decoded.orderValue}, ${decoded.id})`),\n\t\t\t);\n\t\t}\n\n\t\t// Build ORDER BY using sql template\n\t\tif (Object.keys(orderBy).length > 0) {\n\t\t\tfor (const [field, direction] of Object.entries(orderBy)) {\n\t\t\t\tconst extract = jsonExtract(this.db, field);\n\t\t\t\tconst orderExpr =\n\t\t\t\t\tdirection === \"desc\" ? sql`${sql.raw(extract)} desc` : sql`${sql.raw(extract)} asc`;\n\t\t\t\tquery = query.orderBy(orderExpr);\n\t\t\t}\n\t\t} else {\n\t\t\t// Default ordering for consistent pagination\n\t\t\tquery = query.orderBy(\"created_at\", \"asc\").orderBy(\"id\", \"asc\");\n\t\t}\n\n\t\t// Apply limit (fetch one extra to detect if there's more)\n\t\tquery = query.limit(limit + 1);\n\n\t\tconst rows = await query.execute();\n\n\t\tconst hasMore = rows.length > limit;\n\t\tconst items = rows.slice(0, limit).map((row) => ({\n\t\t\tid: row.id,\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- JSON.parse returns any; generic callers provide T\n\t\t\tdata: JSON.parse(row.data) as T,\n\t\t}));\n\n\t\t// Generate cursor for next page if there are more results\n\t\tlet nextCursor: string | undefined;\n\t\tif (hasMore) {\n\t\t\tconst lastItem = rows[limit - 1];\n\t\t\tif (lastItem) {\n\t\t\t\tnextCursor = encodeCursor(lastItem.created_at, lastItem.id);\n\t\t\t}\n\t\t}\n\n\t\treturn { items, cursor: nextCursor, hasMore };\n\t}\n\n\t/**\n\t * Count documents matching a filter\n\t */\n\tasync count(where?: WhereClause): Promise<number> {\n\t\tif (where && Object.keys(where).length > 0) {\n\t\t\tvalidateWhereClause(where, this.indexedFields, this.pluginId, this.collection);\n\t\t}\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select(sql<number>`COUNT(*)`.as(\"count\"))\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection);\n\n\t\t// Add JSON extraction WHERE conditions\n\t\tif (where && Object.keys(where).length > 0) {\n\t\t\tconst whereResult = buildWhereClause(this.db, where);\n\t\t\tif (whereResult.sql) {\n\t\t\t\t// Use sql template to add the raw WHERE conditions with params\n\t\t\t\tconst whereSqlParts: ReturnType<typeof sql>[] = [];\n\t\t\t\tlet paramIndex = 0;\n\t\t\t\tconst sqlParts = whereResult.sql.split(\"?\");\n\t\t\t\tfor (let i = 0; i < sqlParts.length; i++) {\n\t\t\t\t\tif (i > 0) {\n\t\t\t\t\t\twhereSqlParts.push(sql`${whereResult.params[paramIndex++]}`);\n\t\t\t\t\t}\n\t\t\t\t\tif (sqlParts[i]) {\n\t\t\t\t\t\twhereSqlParts.push(sql.raw(sqlParts[i]));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tquery = query.where(({ eb }) =>\n\t\t\t\t\teb(sql.join(whereSqlParts, sql.raw(\"\")), \"=\", sql.raw(\"1\")),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn result?.count ?? 0;\n\t}\n}\n\n/**\n * Create a scoped storage accessor for a plugin\n */\nexport function createPluginStorageAccessor(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tstorageConfig: Record<\n\t\tstring,\n\t\t{ indexes: Array<string | string[]>; uniqueIndexes?: Array<string | string[]> }\n\t>,\n): Record<string, StorageCollection> {\n\tconst accessor: Record<string, StorageCollection> = {};\n\n\tfor (const [collectionName, config] of Object.entries(storageConfig)) {\n\t\tconst allIndexes = [...config.indexes, ...(config.uniqueIndexes ?? [])];\n\t\taccessor[collectionName] = new PluginStorageRepository(\n\t\t\tdb,\n\t\t\tpluginId,\n\t\t\tcollectionName,\n\t\t\tallIndexes,\n\t\t);\n\t}\n\n\treturn accessor;\n}\n\n/**\n * Delete all storage data for a plugin\n */\nexport async function deleteAllPluginStorage(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n): Promise<number> {\n\tconst result = await db\n\t\t.deleteFrom(\"_plugin_storage\")\n\t\t.where(\"plugin_id\", \"=\", pluginId)\n\t\t.executeTakeFirst();\n\n\treturn Number(result.numDeletedRows ?? 0);\n}\n\n/**\n * Delete all storage data for a plugin collection\n */\nexport async function deletePluginCollection(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tcollection: string,\n): Promise<number> {\n\tconst result = await db\n\t\t.deleteFrom(\"_plugin_storage\")\n\t\t.where(\"plugin_id\", \"=\", pluginId)\n\t\t.where(\"collection\", \"=\", collection)\n\t\t.executeTakeFirst();\n\n\treturn Number(result.numDeletedRows ?? 0);\n}\n","/**\n * Plugin Context v2\n *\n * Creates the unified context object provided to plugins in all hooks and routes.\n *\n */\n\nimport type { Kysely } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { ContentRepository } from \"../database/repositories/content.js\";\nimport { MediaRepository } from \"../database/repositories/media.js\";\nimport { OptionsRepository } from \"../database/repositories/options.js\";\nimport { PluginStorageRepository } from \"../database/repositories/plugin-storage.js\";\nimport { SeoRepository } from \"../database/repositories/seo.js\";\nimport { UserRepository } from \"../database/repositories/user.js\";\nimport { withTransaction } from \"../database/transaction.js\";\nimport type { Database } from \"../database/types.js\";\nimport {\n\tresolveAndValidateExternalUrl,\n\tSsrfError,\n\tstripCredentialHeaders,\n} from \"../import/ssrf.js\";\nimport { invalidateSiteSettingsCache } from \"../settings/index.js\";\nimport type { Storage } from \"../storage/types.js\";\nimport { CronAccessImpl } from \"./cron.js\";\nimport type { EmailPipeline } from \"./email.js\";\nimport type {\n\tResolvedPlugin,\n\tPluginContext,\n\tPluginStorageConfig,\n\tStorageCollection,\n\tKVAccess,\n\tCronAccess,\n\tEmailAccess,\n\tContentAccess,\n\tContentAccessWithWrite,\n\tMediaAccess,\n\tMediaAccessWithWrite,\n\tHttpAccess,\n\tLogAccess,\n\tSiteInfo,\n\tUserAccess,\n\tUserInfo,\n\tContentItem,\n\tContentItemSeoInput,\n\tContentWriteInput,\n\tMediaItem,\n\tPaginatedResult,\n\tQueryOptions,\n\tContentListOptions,\n\tMediaListOptions,\n} from \"./types.js\";\n\n// =============================================================================\n// KV Access\n// =============================================================================\n\n/**\n * Create KV accessor for a plugin\n * All keys are automatically prefixed with the plugin ID\n */\nexport function createKVAccess(optionsRepo: OptionsRepository, pluginId: string): KVAccess {\n\tconst prefix = `plugin:${pluginId}:`;\n\n\treturn {\n\t\tasync get<T>(key: string): Promise<T | null> {\n\t\t\treturn optionsRepo.get<T>(`${prefix}${key}`);\n\t\t},\n\n\t\tasync set(key: string, value: unknown): Promise<void> {\n\t\t\tawait optionsRepo.set(`${prefix}${key}`, value);\n\t\t},\n\n\t\tasync delete(key: string): Promise<boolean> {\n\t\t\treturn optionsRepo.delete(`${prefix}${key}`);\n\t\t},\n\n\t\tasync list(keyPrefix?: string): Promise<Array<{ key: string; value: unknown }>> {\n\t\t\tconst fullPrefix = `${prefix}${keyPrefix ?? \"\"}`;\n\t\t\tconst entriesMap = await optionsRepo.getByPrefix(fullPrefix);\n\t\t\tconst result: Array<{ key: string; value: unknown }> = [];\n\t\t\tfor (const [fullKey, value] of entriesMap) {\n\t\t\t\tresult.push({\n\t\t\t\t\tkey: fullKey.slice(prefix.length),\n\t\t\t\t\tvalue,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Storage Access\n// =============================================================================\n\n/**\n * Create storage collection accessor for a plugin\n * Wraps PluginStorageRepository with the v2 interface (no async iterators)\n */\nfunction createStorageCollection<T>(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tcollectionName: string,\n\tindexes: Array<string | string[]>,\n): StorageCollection<T> {\n\tconst repo = new PluginStorageRepository<T>(db, pluginId, collectionName, indexes);\n\n\treturn {\n\t\tget: (id) => repo.get(id),\n\t\tput: (id, data) => repo.put(id, data),\n\t\tdelete: (id) => repo.delete(id),\n\t\texists: (id) => repo.exists(id),\n\t\tgetMany: (ids) => repo.getMany(ids),\n\t\tputMany: (items) => repo.putMany(items),\n\t\tdeleteMany: (ids) => repo.deleteMany(ids),\n\t\tcount: (where) => repo.count(where),\n\n\t\t// Query returns PaginatedResult instead of the old format\n\t\tasync query(options?: QueryOptions): Promise<PaginatedResult<{ id: string; data: T }>> {\n\t\t\tconst result = await repo.query({\n\t\t\t\twhere: options?.where,\n\t\t\t\torderBy: options?.orderBy,\n\t\t\t\tlimit: options?.limit,\n\t\t\t\tcursor: options?.cursor,\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\titems: result.items,\n\t\t\t\tcursor: result.cursor,\n\t\t\t\thasMore: result.hasMore,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Create storage accessor with all declared collections\n */\nexport function createStorageAccess<T extends PluginStorageConfig>(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tstorageConfig: T,\n): Record<string, StorageCollection> {\n\tconst storage: Record<string, StorageCollection> = {};\n\n\tfor (const [collectionName, config] of Object.entries(storageConfig)) {\n\t\tconst allIndexes = [...config.indexes, ...(config.uniqueIndexes ?? [])];\n\t\tstorage[collectionName] = createStorageCollection(db, pluginId, collectionName, allIndexes);\n\t}\n\n\treturn storage;\n}\n\n// =============================================================================\n// Content Access\n// =============================================================================\n\n/**\n * Extract `seo` from a plugin-supplied content write input and return both\n * parts. Mutates nothing — returns a new field map without the `seo` key.\n */\nfunction splitSeoFromInput(input: ContentWriteInput): {\n\tfields: Record<string, unknown>;\n\tseo: ContentItemSeoInput | undefined;\n} {\n\tconst { seo, ...fields } = input;\n\t// Reject non-object seo values rather than silently dropping them.\n\tif (seo !== undefined && (seo === null || typeof seo !== \"object\" || Array.isArray(seo))) {\n\t\tthrow new Error(\"content.seo must be an object\");\n\t}\n\treturn { fields, seo };\n}\n\n/**\n * Reject writing SEO to a collection that does not have it enabled.\n * Matches the REST API behavior (VALIDATION_ERROR).\n */\nasync function assertSeoEnabled(\n\tseoRepo: SeoRepository,\n\tcollection: string,\n\tseo: ContentItemSeoInput | undefined,\n): Promise<boolean> {\n\tconst hasSeo = await seoRepo.isEnabled(collection);\n\tif (seo !== undefined && !hasSeo) {\n\t\tthrow new Error(\n\t\t\t`Collection \"${collection}\" does not have SEO enabled. ` +\n\t\t\t\t`Remove the seo field or enable SEO on this collection.`,\n\t\t);\n\t}\n\treturn hasSeo;\n}\n\n/**\n * Create read-only content access\n */\nexport function createContentAccess(db: Kysely<Database>): ContentAccess {\n\tconst contentRepo = new ContentRepository(db);\n\tconst seoRepo = new SeoRepository(db);\n\n\treturn {\n\t\tasync get(collection: string, id: string): Promise<ContentItem | null> {\n\t\t\tconst item = await contentRepo.findById(collection, id);\n\t\t\tif (!item) return null;\n\n\t\t\tconst result: ContentItem = {\n\t\t\t\tid: item.id,\n\t\t\t\ttype: item.type,\n\t\t\t\tslug: item.slug,\n\t\t\t\tstatus: item.status,\n\t\t\t\tdata: item.data,\n\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\tlocale: item.locale,\n\t\t\t\tpublishedAt: item.publishedAt,\n\t\t\t};\n\n\t\t\tif (await seoRepo.isEnabled(collection)) {\n\t\t\t\tresult.seo = await seoRepo.get(collection, item.id);\n\t\t\t}\n\n\t\t\treturn result;\n\t\t},\n\n\t\tasync list(\n\t\t\tcollection: string,\n\t\t\toptions?: ContentListOptions,\n\t\t): Promise<PaginatedResult<ContentItem>> {\n\t\t\t// Convert orderBy format if provided\n\t\t\tlet orderBy: { field: string; direction: \"asc\" | \"desc\" } | undefined;\n\t\t\tif (options?.orderBy) {\n\t\t\t\tconst entries = Object.entries(options.orderBy);\n\t\t\t\tconst first = entries[0];\n\t\t\t\tif (first) {\n\t\t\t\t\torderBy = { field: first[0], direction: first[1] };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst result = await contentRepo.findMany(collection, {\n\t\t\t\tlimit: options?.limit ?? 50,\n\t\t\t\tcursor: options?.cursor,\n\t\t\t\torderBy,\n\t\t\t\twhere: options?.where,\n\t\t\t});\n\n\t\t\tconst items: ContentItem[] = result.items.map((item) => ({\n\t\t\t\tid: item.id,\n\t\t\t\ttype: item.type,\n\t\t\t\tslug: item.slug,\n\t\t\t\tstatus: item.status,\n\t\t\t\tdata: item.data,\n\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\tlocale: item.locale,\n\t\t\t\tpublishedAt: item.publishedAt,\n\t\t\t}));\n\n\t\t\tif (items.length > 0 && (await seoRepo.isEnabled(collection))) {\n\t\t\t\tconst seoMap = await seoRepo.getMany(\n\t\t\t\t\tcollection,\n\t\t\t\t\titems.map((i) => i.id),\n\t\t\t\t);\n\t\t\t\tfor (const item of items) {\n\t\t\t\t\tconst seo = seoMap.get(item.id);\n\t\t\t\t\tif (seo) item.seo = seo;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\titems,\n\t\t\t\tcursor: result.nextCursor,\n\t\t\t\thasMore: !!result.nextCursor,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Create full content access with write operations.\n *\n * `create` and `update` accept a reserved `seo` key in their `data`\n * argument. When present, it is routed to the core SEO panel\n * (`_emdash_seo`) via `SeoRepository.upsert`, in the same transaction as\n * the content write. The returned `ContentItem.seo` reflects the resulting\n * SEO state for SEO-enabled collections.\n */\nexport function createContentAccessWithWrite(db: Kysely<Database>): ContentAccessWithWrite {\n\tconst readAccess = createContentAccess(db);\n\n\treturn {\n\t\t...readAccess,\n\n\t\tasync create(collection: string, data: ContentWriteInput): Promise<ContentItem> {\n\t\t\tconst { fields, seo } = splitSeoFromInput(data);\n\n\t\t\treturn withTransaction(db, async (trx) => {\n\t\t\t\tconst trxContentRepo = new ContentRepository(trx);\n\t\t\t\tconst trxSeoRepo = new SeoRepository(trx);\n\n\t\t\t\tconst hasSeo = await assertSeoEnabled(trxSeoRepo, collection, seo);\n\n\t\t\t\tconst item = await trxContentRepo.create({\n\t\t\t\t\ttype: collection,\n\t\t\t\t\tdata: fields,\n\t\t\t\t});\n\n\t\t\t\tconst result: ContentItem = {\n\t\t\t\t\tid: item.id,\n\t\t\t\t\ttype: item.type,\n\t\t\t\t\tslug: item.slug,\n\t\t\t\t\tstatus: item.status,\n\t\t\t\t\tdata: item.data,\n\t\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\t\tlocale: item.locale,\n\t\t\t\t\tpublishedAt: item.publishedAt,\n\t\t\t\t};\n\n\t\t\t\tif (hasSeo) {\n\t\t\t\t\tresult.seo =\n\t\t\t\t\t\tseo !== undefined\n\t\t\t\t\t\t\t? await trxSeoRepo.upsert(collection, item.id, seo)\n\t\t\t\t\t\t\t: await trxSeoRepo.get(collection, item.id);\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t});\n\t\t},\n\n\t\tasync update(collection: string, id: string, data: ContentWriteInput): Promise<ContentItem> {\n\t\t\tconst { fields, seo } = splitSeoFromInput(data);\n\n\t\t\treturn withTransaction(db, async (trx) => {\n\t\t\t\tconst trxContentRepo = new ContentRepository(trx);\n\t\t\t\tconst trxSeoRepo = new SeoRepository(trx);\n\n\t\t\t\tconst hasSeo = await assertSeoEnabled(trxSeoRepo, collection, seo);\n\n\t\t\t\t// Pass the `data` payload to ContentRepository.update only when\n\t\t\t\t// there are field updates — passing an empty object would still\n\t\t\t\t// bump updated_at/version, but we want a seo-only call to touch\n\t\t\t\t// only the SEO table. ContentRepository.update handles the no-op\n\t\t\t\t// path by returning the current row.\n\t\t\t\tconst hasFieldUpdates = Object.keys(fields).length > 0;\n\t\t\t\tconst item = hasFieldUpdates\n\t\t\t\t\t? await trxContentRepo.update(collection, id, { data: fields })\n\t\t\t\t\t: await (async () => {\n\t\t\t\t\t\t\tconst existing = await trxContentRepo.findById(collection, id);\n\t\t\t\t\t\t\tif (!existing) throw new Error(\"Content not found\");\n\t\t\t\t\t\t\treturn existing;\n\t\t\t\t\t\t})();\n\n\t\t\t\tconst result: ContentItem = {\n\t\t\t\t\tid: item.id,\n\t\t\t\t\ttype: item.type,\n\t\t\t\t\tslug: item.slug,\n\t\t\t\t\tstatus: item.status,\n\t\t\t\t\tdata: item.data,\n\t\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\t\tlocale: item.locale,\n\t\t\t\t\tpublishedAt: item.publishedAt,\n\t\t\t\t};\n\n\t\t\t\tif (hasSeo) {\n\t\t\t\t\tresult.seo =\n\t\t\t\t\t\tseo !== undefined\n\t\t\t\t\t\t\t? await trxSeoRepo.upsert(collection, item.id, seo)\n\t\t\t\t\t\t\t: await trxSeoRepo.get(collection, item.id);\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t});\n\t\t},\n\n\t\tasync delete(collection: string, id: string): Promise<boolean> {\n\t\t\tconst contentRepo = new ContentRepository(db);\n\t\t\treturn contentRepo.delete(collection, id);\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Media Access\n// =============================================================================\n\n/**\n * Create read-only media access\n */\nexport function createMediaAccess(db: Kysely<Database>): MediaAccess {\n\tconst mediaRepo = new MediaRepository(db);\n\n\treturn {\n\t\tasync get(id: string): Promise<MediaItem | null> {\n\t\t\tconst item = await mediaRepo.findById(id);\n\t\t\tif (!item) return null;\n\n\t\t\treturn {\n\t\t\t\tid: item.id,\n\t\t\t\tfilename: item.filename,\n\t\t\t\tmimeType: item.mimeType,\n\t\t\t\tsize: item.size,\n\t\t\t\t// Construct URL from storage key (or use a sensible default path)\n\t\t\t\turl: `/media/${item.id}/${item.filename}`,\n\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t};\n\t\t},\n\n\t\tasync list(options?: MediaListOptions): Promise<PaginatedResult<MediaItem>> {\n\t\t\tconst result = await mediaRepo.findMany({\n\t\t\t\tlimit: options?.limit ?? 50,\n\t\t\t\tcursor: options?.cursor,\n\t\t\t\tmimeType: options?.mimeType,\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\titems: result.items.map((item) => ({\n\t\t\t\t\tid: item.id,\n\t\t\t\t\tfilename: item.filename,\n\t\t\t\t\tmimeType: item.mimeType,\n\t\t\t\t\tsize: item.size,\n\t\t\t\t\turl: `/media/${item.id}/${item.filename}`,\n\t\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\t})),\n\t\t\t\tcursor: result.nextCursor,\n\t\t\t\thasMore: !!result.nextCursor,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Create full media access with write operations.\n * If storage is not provided, upload() will throw at call time.\n */\nexport function createMediaAccessWithWrite(\n\tdb: Kysely<Database>,\n\tgetUploadUrlFn: (\n\t\tfilename: string,\n\t\tcontentType: string,\n\t) => Promise<{ uploadUrl: string; mediaId: string }>,\n\tstorage?: Storage,\n): MediaAccessWithWrite {\n\tconst mediaRepo = new MediaRepository(db);\n\tconst readAccess = createMediaAccess(db);\n\n\treturn {\n\t\t...readAccess,\n\n\t\tgetUploadUrl: getUploadUrlFn,\n\n\t\tasync upload(\n\t\t\tfilename: string,\n\t\t\tcontentType: string,\n\t\t\tbytes: ArrayBuffer,\n\t\t): Promise<{ mediaId: string; storageKey: string; url: string }> {\n\t\t\tif (!storage) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Media upload() requires a storage backend. Configure storage in PluginContextFactoryOptions.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Generate a storage key with a unique prefix\n\t\t\tconst keyPrefix = ulid();\n\t\t\t// Extract extension from basename (ignore path separators)\n\t\t\tconst basename = filename.split(\"/\").pop() ?? filename;\n\t\t\tconst dotIdx = basename.lastIndexOf(\".\");\n\t\t\tconst ext = dotIdx > 0 ? basename.slice(dotIdx).toLowerCase() : \"\";\n\t\t\tconst storageKey = `${keyPrefix}${ext}`;\n\n\t\t\t// Upload to storage first\n\t\t\tawait storage.upload({\n\t\t\t\tkey: storageKey,\n\t\t\t\tbody: new Uint8Array(bytes),\n\t\t\t\tcontentType,\n\t\t\t});\n\n\t\t\t// Create DB record — clean up storage on failure\n\t\t\tlet media;\n\t\t\ttry {\n\t\t\t\tmedia = await mediaRepo.create({\n\t\t\t\t\tfilename: basename,\n\t\t\t\t\tmimeType: contentType,\n\t\t\t\t\tsize: bytes.byteLength,\n\t\t\t\t\tstorageKey,\n\t\t\t\t\tstatus: \"ready\",\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tawait storage.delete(storageKey);\n\t\t\t\t} catch {\n\t\t\t\t\t// Best-effort cleanup\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tmediaId: media.id,\n\t\t\t\tstorageKey,\n\t\t\t\turl: `/_emdash/api/media/file/${storageKey}`,\n\t\t\t};\n\t\t},\n\n\t\tasync delete(id: string): Promise<boolean> {\n\t\t\tconst deleted = await mediaRepo.delete(id);\n\t\t\t// Plugins can delete media that's referenced by site settings\n\t\t\t// (`logo`, `favicon`, `seo.defaultOgImage`); the worker-scoped\n\t\t\t// resolved-URL cache must be dropped or it will keep serving\n\t\t\t// 404s. Matches the invalidation in\n\t\t\t// `EmDashRuntime.handleMediaDelete`.\n\t\t\tif (deleted) {\n\t\t\t\tinvalidateSiteSettingsCache();\n\t\t\t}\n\t\t\treturn deleted;\n\t\t},\n\t};\n}\n\n// =============================================================================\n// HTTP Access\n// =============================================================================\n\n/** Maximum number of redirects to follow in plugin HTTP access */\nconst MAX_PLUGIN_REDIRECTS = 5;\n\n/**\n * Check if a hostname matches any pattern in the allowed list.\n * Patterns: \"*\" matches all, \"*.example.com\" matches subdomains AND bare \"example.com\",\n * \"api.example.com\" matches exactly.\n */\nfunction isHostAllowed(host: string, allowedHosts: string[]): boolean {\n\treturn allowedHosts.some((pattern) => {\n\t\tif (pattern === \"*\") return true;\n\t\tif (pattern.startsWith(\"*.\")) {\n\t\t\tconst suffix = pattern.slice(1); // \".example.com\"\n\t\t\t// Match subdomains (foo.example.com) and bare domain (example.com)\n\t\t\treturn host.endsWith(suffix) || host === pattern.slice(2);\n\t\t}\n\t\treturn host === pattern;\n\t});\n}\n\n/**\n * Create HTTP access with host validation.\n *\n * Uses redirect: \"manual\" to re-validate each redirect target against\n * the allowedHosts list, preventing redirects to unauthorized hosts.\n */\nexport function createHttpAccess(pluginId: string, allowedHosts: string[]): HttpAccess {\n\treturn {\n\t\tasync fetch(url: string, init?: RequestInit): Promise<Response> {\n\t\t\t// Deny by default — plugins must declare allowed hosts\n\t\t\tif (allowedHosts.length === 0) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Plugin \"${pluginId}\" has no allowed hosts configured. ` +\n\t\t\t\t\t\t`Add hosts to the plugin's allowedHosts array to enable HTTP requests.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet currentUrl = url;\n\t\t\tlet currentInit = init;\n\n\t\t\tfor (let i = 0; i <= MAX_PLUGIN_REDIRECTS; i++) {\n\t\t\t\tconst hostname = new URL(currentUrl).hostname;\n\t\t\t\tif (!isHostAllowed(hostname, allowedHosts)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Plugin \"${pluginId}\" is not allowed to fetch from host \"${hostname}\". ` +\n\t\t\t\t\t\t\t`Allowed hosts: ${allowedHosts.join(\", \")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst response = await globalThis.fetch(currentUrl, {\n\t\t\t\t\t...currentInit,\n\t\t\t\t\tredirect: \"manual\",\n\t\t\t\t});\n\n\t\t\t\t// Not a redirect -- return directly\n\t\t\t\tif (response.status < 300 || response.status >= 400) {\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Extract redirect target\n\t\t\t\tconst location = response.headers.get(\"Location\");\n\t\t\t\tif (!location) {\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Resolve relative redirects; strip credentials on cross-origin hops\n\t\t\t\tconst previousOrigin = new URL(currentUrl).origin;\n\t\t\t\tcurrentUrl = new URL(location, currentUrl).href;\n\t\t\t\tconst nextOrigin = new URL(currentUrl).origin;\n\n\t\t\t\tif (previousOrigin !== nextOrigin && currentInit) {\n\t\t\t\t\tcurrentInit = stripCredentialHeaders(currentInit);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthrow new Error(`Plugin \"${pluginId}\": too many redirects (max ${MAX_PLUGIN_REDIRECTS})`);\n\t\t},\n\t};\n}\n\n/**\n * Create unrestricted HTTP access (for plugins with network:fetch:any capability).\n * No host validation, but applies SSRF protection on redirect targets to\n * prevent plugins from being tricked into reaching internal services.\n */\nexport function createUnrestrictedHttpAccess(pluginId: string): HttpAccess {\n\treturn {\n\t\tasync fetch(url: string, init?: RequestInit): Promise<Response> {\n\t\t\tlet currentUrl = url;\n\t\t\tlet currentInit = init;\n\n\t\t\tfor (let i = 0; i <= MAX_PLUGIN_REDIRECTS; i++) {\n\t\t\t\t// Validate each URL against SSRF rules (private IPs, metadata\n\t\t\t\t// endpoints, wildcard DNS, resolved-IP private ranges).\n\t\t\t\ttry {\n\t\t\t\t\tawait resolveAndValidateExternalUrl(currentUrl);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tconst msg = e instanceof SsrfError ? e.message : \"SSRF validation failed\";\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Plugin \"${pluginId}\": blocked fetch to \"${new URL(currentUrl).hostname}\": ${msg}`,\n\t\t\t\t\t\t{ cause: e },\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst response = await globalThis.fetch(currentUrl, {\n\t\t\t\t\t...currentInit,\n\t\t\t\t\tredirect: \"manual\",\n\t\t\t\t});\n\n\t\t\t\t// Not a redirect -- return directly\n\t\t\t\tif (response.status < 300 || response.status >= 400) {\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Extract redirect target\n\t\t\t\tconst location = response.headers.get(\"Location\");\n\t\t\t\tif (!location) {\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Resolve relative redirects; strip credentials on cross-origin hops\n\t\t\t\tconst previousOrigin = new URL(currentUrl).origin;\n\t\t\t\tcurrentUrl = new URL(location, currentUrl).href;\n\t\t\t\tconst nextOrigin = new URL(currentUrl).origin;\n\n\t\t\t\tif (previousOrigin !== nextOrigin && currentInit) {\n\t\t\t\t\tcurrentInit = stripCredentialHeaders(currentInit);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthrow new Error(`Plugin \"${pluginId}\": too many redirects (max ${MAX_PLUGIN_REDIRECTS})`);\n\t\t},\n\t};\n}\n\n/**\n * Create blocked HTTP access (for plugins without network:request capability)\n */\nexport function createBlockedHttpAccess(pluginId: string): HttpAccess {\n\treturn {\n\t\tasync fetch(): Promise<never> {\n\t\t\tthrow new Error(\n\t\t\t\t`Plugin \"${pluginId}\" does not have the \"network:request\" capability. ` +\n\t\t\t\t\t`Add \"network:request\" to the plugin's capabilities to enable HTTP requests.`,\n\t\t\t);\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Log Access\n// =============================================================================\n\n/**\n * Create logger for a plugin\n */\nexport function createLogAccess(pluginId: string): LogAccess {\n\tconst prefix = `[plugin:${pluginId}]`;\n\n\treturn {\n\t\tdebug(message: string, data?: unknown): void {\n\t\t\tif (data !== undefined) {\n\t\t\t\tconsole.debug(prefix, message, data);\n\t\t\t} else {\n\t\t\t\tconsole.debug(prefix, message);\n\t\t\t}\n\t\t},\n\n\t\tinfo(message: string, data?: unknown): void {\n\t\t\tif (data !== undefined) {\n\t\t\t\tconsole.info(prefix, message, data);\n\t\t\t} else {\n\t\t\t\tconsole.info(prefix, message);\n\t\t\t}\n\t\t},\n\n\t\twarn(message: string, data?: unknown): void {\n\t\t\tif (data !== undefined) {\n\t\t\t\tconsole.warn(prefix, message, data);\n\t\t\t} else {\n\t\t\t\tconsole.warn(prefix, message);\n\t\t\t}\n\t\t},\n\n\t\terror(message: string, data?: unknown): void {\n\t\t\tif (data !== undefined) {\n\t\t\t\tconsole.error(prefix, message, data);\n\t\t\t} else {\n\t\t\t\tconsole.error(prefix, message);\n\t\t\t}\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Site Info\n// =============================================================================\n\nconst TRAILING_SLASH_RE = /\\/$/;\n\n/**\n * Options for creating site info\n */\nexport interface SiteInfoOptions {\n\t/** Site name from options table */\n\tsiteName?: string;\n\t/** Site URL from options table or Astro config */\n\tsiteUrl?: string;\n\t/** Site locale from options table */\n\tlocale?: string;\n}\n\n/**\n * Create site info from config and settings.\n *\n * Resolution order for URL:\n * 1. options table (emdash:site_url)\n * 2. Astro `site` config\n * 3. fallback to empty string\n */\nexport function createSiteInfo(options: SiteInfoOptions): SiteInfo {\n\treturn {\n\t\tname: options.siteName ?? \"\",\n\t\turl: (options.siteUrl ?? \"\").replace(TRAILING_SLASH_RE, \"\"), // strip trailing slash\n\t\tlocale: options.locale ?? \"en\",\n\t};\n}\n\n/**\n * Create a URL helper that generates absolute URLs from relative paths.\n * Validates that path starts with \"/\" and rejects protocol-relative paths (\"//\").\n */\nexport function createUrlHelper(siteUrl: string): (path: string) => string {\n\tconst base = siteUrl.replace(TRAILING_SLASH_RE, \"\"); // strip trailing slash\n\n\treturn (path: string): string => {\n\t\tif (!path.startsWith(\"/\")) {\n\t\t\tthrow new Error(`URL path must start with \"/\", got: \"${path}\"`);\n\t\t}\n\t\tif (path.startsWith(\"//\")) {\n\t\t\tthrow new Error(`URL path must not be protocol-relative, got: \"${path}\"`);\n\t\t}\n\t\treturn `${base}${path}`;\n\t};\n}\n\n// =============================================================================\n// User Access\n// =============================================================================\n\n/**\n * Convert a UserRepository user to the plugin-facing UserInfo shape.\n * Strips sensitive fields (avatarUrl, emailVerified, data).\n */\nfunction toUserInfo(user: {\n\tid: string;\n\temail: string;\n\tname: string | null;\n\trole: number;\n\tcreatedAt: string;\n}): UserInfo {\n\treturn {\n\t\tid: user.id,\n\t\temail: user.email,\n\t\tname: user.name,\n\t\trole: user.role,\n\t\tcreatedAt: user.createdAt,\n\t};\n}\n\n/**\n * Create read-only user access for plugins.\n * Excludes sensitive fields (password hashes, sessions, passkeys, avatar URL, data).\n */\nexport function createUserAccess(db: Kysely<Database>): UserAccess {\n\tconst userRepo = new UserRepository(db);\n\n\treturn {\n\t\tasync get(id: string): Promise<UserInfo | null> {\n\t\t\tconst user = await userRepo.findById(id);\n\t\t\tif (!user) return null;\n\t\t\treturn toUserInfo(user);\n\t\t},\n\n\t\tasync getByEmail(email: string): Promise<UserInfo | null> {\n\t\t\tconst user = await userRepo.findByEmail(email);\n\t\t\tif (!user) return null;\n\t\t\treturn toUserInfo(user);\n\t\t},\n\n\t\tasync list(opts?: {\n\t\t\trole?: number;\n\t\t\tlimit?: number;\n\t\t\tcursor?: string;\n\t\t}): Promise<{ items: UserInfo[]; nextCursor?: string }> {\n\t\t\tconst result = await userRepo.findMany({\n\t\t\t\trole: opts?.role as 10 | 20 | 30 | 40 | 50 | undefined,\n\t\t\t\tcursor: opts?.cursor,\n\t\t\t\tlimit: opts?.limit,\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\titems: result.items.map(toUserInfo),\n\t\t\t\tnextCursor: result.nextCursor,\n\t\t\t};\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Plugin Context Factory\n// =============================================================================\n\nexport interface PluginContextFactoryOptions {\n\tdb: Kysely<Database>;\n\t/**\n\t * Storage backend for direct media uploads.\n\t * If not provided, upload() will throw.\n\t */\n\tstorage?: Storage;\n\t/**\n\t * Function to generate upload URLs for media.\n\t * If not provided, media write operations will throw.\n\t */\n\tgetUploadUrl?: (\n\t\tfilename: string,\n\t\tcontentType: string,\n\t) => Promise<{ uploadUrl: string; mediaId: string }>;\n\t/**\n\t * Site information for ctx.site and ctx.url().\n\t * If not provided, site info will have empty defaults.\n\t */\n\tsiteInfo?: SiteInfoOptions;\n\t/**\n\t * Callback to notify the cron scheduler that the next due time may have changed.\n\t * If not provided, ctx.cron will not be available.\n\t */\n\tcronReschedule?: () => void;\n\t/**\n\t * Email pipeline instance for ctx.email.\n\t * If not provided (or no provider configured), ctx.email will be undefined.\n\t */\n\temailPipeline?: EmailPipeline;\n\t/**\n\t * Pre-resolved list of trusted proxy header names (from the runtime\n\t * `EmDashConfig.trustedProxyHeaders` or the env var). Plugin route\n\t * handlers pass this to `extractRequestMeta` so plugins see the same\n\t * client IP the core auth path does.\n\t */\n\ttrustedProxyHeaders?: string[];\n}\n\n/**\n * Factory for creating plugin contexts\n */\nexport class PluginContextFactory {\n\tprivate optionsRepo: OptionsRepository;\n\tprivate db: Kysely<Database>;\n\tprivate storage?: Storage;\n\tprivate getUploadUrl?: (\n\t\tfilename: string,\n\t\tcontentType: string,\n\t) => Promise<{ uploadUrl: string; mediaId: string }>;\n\tprivate site: SiteInfo;\n\tprivate urlHelper: (path: string) => string;\n\tprivate cronReschedule?: () => void;\n\tprivate emailPipeline?: EmailPipeline;\n\n\tconstructor(options: PluginContextFactoryOptions) {\n\t\tthis.db = options.db;\n\t\tthis.optionsRepo = new OptionsRepository(options.db);\n\t\tthis.storage = options.storage;\n\t\tthis.getUploadUrl = options.getUploadUrl;\n\t\tthis.site = createSiteInfo(options.siteInfo ?? {});\n\t\tthis.urlHelper = createUrlHelper(this.site.url);\n\t\tthis.cronReschedule = options.cronReschedule;\n\t\tthis.emailPipeline = options.emailPipeline;\n\t}\n\n\t/**\n\t * Create the unified plugin context\n\t */\n\tcreateContext(plugin: ResolvedPlugin): PluginContext {\n\t\tconst capabilities = new Set(plugin.capabilities);\n\n\t\t// Always available\n\t\tconst kv = createKVAccess(this.optionsRepo, plugin.id);\n\t\tconst log = createLogAccess(plugin.id);\n\t\tconst storage = createStorageAccess(this.db, plugin.id, plugin.storage);\n\n\t\t// Capability-gated: content\n\t\t// Note: capabilities reach this point already normalized to the\n\t\t// canonical names by definePlugin / adaptSandboxEntry. Deprecated\n\t\t// names (\"read:content\", \"write:content\") never appear here.\n\t\tlet content: ContentAccess | ContentAccessWithWrite | undefined;\n\t\tif (capabilities.has(\"content:write\")) {\n\t\t\tcontent = createContentAccessWithWrite(this.db);\n\t\t} else if (capabilities.has(\"content:read\")) {\n\t\t\tcontent = createContentAccess(this.db);\n\t\t}\n\n\t\t// Capability-gated: media\n\t\tlet media: MediaAccess | MediaAccessWithWrite | undefined;\n\t\tif (capabilities.has(\"media:write\") && this.getUploadUrl) {\n\t\t\tmedia = createMediaAccessWithWrite(this.db, this.getUploadUrl, this.storage);\n\t\t} else if (capabilities.has(\"media:read\")) {\n\t\t\tmedia = createMediaAccess(this.db);\n\t\t}\n\n\t\t// Capability-gated: http\n\t\tlet http: HttpAccess | undefined;\n\t\tif (capabilities.has(\"network:request:unrestricted\")) {\n\t\t\thttp = createUnrestrictedHttpAccess(plugin.id);\n\t\t} else if (capabilities.has(\"network:request\")) {\n\t\t\thttp = createHttpAccess(plugin.id, plugin.allowedHosts);\n\t\t}\n\n\t\t// Capability-gated: users\n\t\tlet users: UserAccess | undefined;\n\t\tif (capabilities.has(\"users:read\")) {\n\t\t\tusers = createUserAccess(this.db);\n\t\t}\n\n\t\t// Cron access ��� always available (scoped to plugin), but only if\n\t\t// the runtime provided a reschedule callback (i.e. cron is wired up).\n\t\tlet cron: CronAccess | undefined;\n\t\tif (this.cronReschedule) {\n\t\t\tcron = new CronAccessImpl(this.db, plugin.id, this.cronReschedule);\n\t\t}\n\n\t\t// Email access — requires email:send capability AND a configured provider\n\t\tlet email: EmailAccess | undefined;\n\t\tif (capabilities.has(\"email:send\") && this.emailPipeline?.isAvailable()) {\n\t\t\tconst pipeline = this.emailPipeline;\n\t\t\tconst pluginId = plugin.id;\n\t\t\temail = {\n\t\t\t\tsend: (message) => pipeline.send(message, pluginId),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tplugin: {\n\t\t\t\tid: plugin.id,\n\t\t\t\tversion: plugin.version,\n\t\t\t},\n\t\t\tstorage,\n\t\t\tkv,\n\t\t\tcontent,\n\t\t\tmedia,\n\t\t\thttp,\n\t\t\tlog,\n\t\t\tsite: this.site,\n\t\t\turl: this.urlHelper,\n\t\t\tusers,\n\t\t\tcron,\n\t\t\temail,\n\t\t};\n\t}\n}\n\n/**\n * Create a plugin context for a resolved plugin\n */\nexport function createPluginContext(\n\toptions: PluginContextFactoryOptions,\n\tplugin: ResolvedPlugin,\n): PluginContext {\n\tconst factory = new PluginContextFactory(options);\n\treturn factory.createContext(plugin);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiBA,IAAa,oBAAb,cAAuC,MAAM;CAC5C,YACC,SACA,AAAO,OACP,AAAO,YACN;AACD,QAAM,QAAQ;EAHP;EACA;AAGP,OAAK,OAAO;;;;;;AAOd,SAAgB,cAAc,OAAyC;AACtE,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAO,QAAQ,SAAS,SAAS,SAAS,QAAQ,SAAS,SAAS;;;;;AAMrE,SAAgB,WAAW,OAAsC;AAChE,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAO,QAAQ,SAAS,MAAM,QAAQ,MAAM,GAAG;;;;;AAMhD,SAAgB,mBAAmB,OAA8C;AAChF,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAO,gBAAgB,SAAS,OAAO,MAAM,eAAe;;;;;AAM7D,SAAgB,iBAAiB,SAAgD;CAChF,MAAM,yBAAS,IAAI,KAAa;AAChC,MAAK,MAAM,SAAS,QACnB,KAAI,MAAM,QAAQ,MAAM,CACvB,MAAK,MAAM,SAAS,MACnB,QAAO,IAAI,MAAM;KAGlB,QAAO,IAAI,MAAM;AAGnB,QAAO;;;;;AAMR,SAAgB,oBACf,OACA,eACA,UACA,YACO;AACP,MAAK,MAAM,SAAS,OAAO,KAAK,MAAM,CACrC,KAAI,CAAC,cAAc,IAAI,MAAM,CAC5B,OAAM,IAAI,kBACT,sCAAsC,MAAM,KAC5C,OACA,QAAQ,MAAM,eAAe,WAAW,sBAAsB,SAAS,yBACvE;;;;;AAQJ,SAAgB,sBACf,SACA,eACA,UACA,YACO;AACP,MAAK,MAAM,SAAS,OAAO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AAa,IAAI,aAAa,IAAI,KAAK,eAAe,aAAa,EAAE;GACxE,MAAM,WAAW,KAAK;GACtB,MAAM,WAAW,OAAO;AACxB,WAAQ,EACP,OAAO,YAAY,SAAS,KAAK,SAAS,SAAS,EACnD;;AAGF,SAAO;GACN,QAAQ;IACP,IAAI,OAAO;IACX,SAAS,OAAO;IAChB;GACD;GACA;GACA;GACA;GACA;GACA;GACA,MAAM,KAAK;GACX,KAAK,KAAK;GACV;GACA;GACA;GACA"}
1
+ {"version":3,"file":"context-B7qiYrz2.mjs","names":[],"sources":["../src/plugins/storage-query.ts","../src/database/repositories/plugin-storage.ts","../src/plugins/context.ts"],"sourcesContent":["/**\n * Plugin Storage Query Validation and Building\n *\n * Validates that queries only use indexed fields and builds SQL WHERE clauses.\n *\n * @see PLUGIN-SYSTEM.md § Plugin Storage > Query Validation\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { jsonExtractExpr } from \"../database/dialect-helpers.js\";\nimport { validateJsonFieldName } from \"../database/validate.js\";\nimport type { WhereClause, WhereValue, RangeFilter, InFilter, StartsWithFilter } from \"./types.js\";\n\n/**\n * Error thrown when querying non-indexed fields\n */\nexport class StorageQueryError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic field?: string,\n\t\tpublic suggestion?: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"StorageQueryError\";\n\t}\n}\n\n/**\n * Check if a value is a range filter\n */\nexport function isRangeFilter(value: WhereValue): value is RangeFilter {\n\tif (typeof value !== \"object\" || value === null) return false;\n\treturn \"gt\" in value || \"gte\" in value || \"lt\" in value || \"lte\" in value;\n}\n\n/**\n * Check if a value is an IN filter\n */\nexport function isInFilter(value: WhereValue): value is InFilter {\n\tif (typeof value !== \"object\" || value === null) return false;\n\treturn \"in\" in value && Array.isArray(value.in);\n}\n\n/**\n * Check if a value is a startsWith filter\n */\nexport function isStartsWithFilter(value: WhereValue): value is StartsWithFilter {\n\tif (typeof value !== \"object\" || value === null) return false;\n\treturn \"startsWith\" in value && typeof value.startsWith === \"string\";\n}\n\n/**\n * Get the set of indexed fields from index declarations\n */\nexport function getIndexedFields(indexes: Array<string | string[]>): Set<string> {\n\tconst fields = new Set<string>();\n\tfor (const index of indexes) {\n\t\tif (Array.isArray(index)) {\n\t\t\tfor (const field of index) {\n\t\t\t\tfields.add(field);\n\t\t\t}\n\t\t} else {\n\t\t\tfields.add(index);\n\t\t}\n\t}\n\treturn fields;\n}\n\n/**\n * Validate that all fields in a where clause are indexed\n */\nexport function validateWhereClause(\n\twhere: WhereClause,\n\tindexedFields: Set<string>,\n\tpluginId: string,\n\tcollection: string,\n): void {\n\tfor (const field of Object.keys(where)) {\n\t\tif (!indexedFields.has(field)) {\n\t\t\tthrow new StorageQueryError(\n\t\t\t\t`Cannot query on non-indexed field '${field}'.`,\n\t\t\t\tfield,\n\t\t\t\t`Add '${field}' to storage.${collection}.indexes in plugin '${pluginId}' to enable this query.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Validate orderBy fields are indexed\n */\nexport function validateOrderByClause(\n\torderBy: Record<string, \"asc\" | \"desc\">,\n\tindexedFields: Set<string>,\n\tpluginId: string,\n\tcollection: string,\n): void {\n\tfor (const field of Object.keys(orderBy)) {\n\t\tif (!indexedFields.has(field)) {\n\t\t\tthrow new StorageQueryError(\n\t\t\t\t`Cannot order by non-indexed field '${field}'.`,\n\t\t\t\tfield,\n\t\t\t\t`Add '${field}' to storage.${collection}.indexes in plugin '${pluginId}' to enable ordering by this field.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * SQL expression for extracting JSON field.\n *\n * Validates the field name before interpolation to prevent SQL injection\n * via crafted JSON path expressions.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function jsonExtract(db: Kysely<any>, field: string): string {\n\tvalidateJsonFieldName(field, \"query field name\");\n\treturn jsonExtractExpr(db, \"data\", field);\n}\n\n/**\n * Build a WHERE clause condition for a single field\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function buildCondition(\n\tdb: Kysely<any>,\n\tfield: string,\n\tvalue: WhereValue,\n): { sql: string; params: unknown[] } {\n\tconst extract = jsonExtract(db, field);\n\n\tif (value === null) {\n\t\treturn { sql: `${extract} IS NULL`, params: [] };\n\t}\n\n\tif (typeof value === \"string\" || typeof value === \"number\") {\n\t\treturn { sql: `${extract} = ?`, params: [value] };\n\t}\n\n\tif (typeof value === \"boolean\") {\n\t\t// JSON booleans are stored as true/false strings\n\t\treturn { sql: `${extract} = ?`, params: [value] };\n\t}\n\n\tif (isInFilter(value)) {\n\t\tconst placeholders = value.in.map(() => \"?\").join(\", \");\n\t\treturn {\n\t\t\tsql: `${extract} IN (${placeholders})`,\n\t\t\tparams: value.in,\n\t\t};\n\t}\n\n\tif (isStartsWithFilter(value)) {\n\t\treturn {\n\t\t\tsql: `${extract} LIKE ?`,\n\t\t\tparams: [`${value.startsWith}%`],\n\t\t};\n\t}\n\n\tif (isRangeFilter(value)) {\n\t\tconst conditions: string[] = [];\n\t\tconst params: unknown[] = [];\n\n\t\tif (value.gt !== undefined) {\n\t\t\tconditions.push(`${extract} > ?`);\n\t\t\tparams.push(value.gt);\n\t\t}\n\t\tif (value.gte !== undefined) {\n\t\t\tconditions.push(`${extract} >= ?`);\n\t\t\tparams.push(value.gte);\n\t\t}\n\t\tif (value.lt !== undefined) {\n\t\t\tconditions.push(`${extract} < ?`);\n\t\t\tparams.push(value.lt);\n\t\t}\n\t\tif (value.lte !== undefined) {\n\t\t\tconditions.push(`${extract} <= ?`);\n\t\t\tparams.push(value.lte);\n\t\t}\n\n\t\treturn {\n\t\t\tsql: conditions.join(\" AND \"),\n\t\t\tparams,\n\t\t};\n\t}\n\n\tthrow new StorageQueryError(`Unknown filter type for field '${field}'`);\n}\n\n/**\n * Build a complete WHERE clause from a WhereClause object\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function buildWhereClause(\n\tdb: Kysely<any>,\n\twhere: WhereClause,\n): {\n\tsql: string;\n\tparams: unknown[];\n} {\n\tconst conditions: string[] = [];\n\tconst params: unknown[] = [];\n\n\tfor (const [field, value] of Object.entries(where)) {\n\t\tconst condition = buildCondition(db, field, value);\n\t\tconditions.push(condition.sql);\n\t\tparams.push(...condition.params);\n\t}\n\n\tif (conditions.length === 0) {\n\t\treturn { sql: \"\", params: [] };\n\t}\n\n\treturn {\n\t\tsql: conditions.join(\" AND \"),\n\t\tparams,\n\t};\n}\n\n/**\n * Build ORDER BY clause\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function buildOrderByClause(\n\tdb: Kysely<any>,\n\torderBy: Record<string, \"asc\" | \"desc\">,\n): string {\n\tconst clauses: string[] = [];\n\n\tfor (const [field, direction] of Object.entries(orderBy)) {\n\t\tclauses.push(`${jsonExtract(db, field)} ${direction.toUpperCase()}`);\n\t}\n\n\tif (clauses.length === 0) {\n\t\treturn \"\";\n\t}\n\n\treturn `ORDER BY ${clauses.join(\", \")}`;\n}\n","/**\n * Plugin Storage Repository\n *\n * Provides a document store API for plugin data storage.\n * Uses a single _plugin_storage table with JSON documents and expression indexes.\n *\n * @see PLUGIN-SYSTEM.md § Plugin Storage > Full API Reference\n */\n\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport {\n\tbuildWhereClause,\n\tvalidateWhereClause,\n\tvalidateOrderByClause,\n\tgetIndexedFields,\n\tjsonExtract,\n} from \"../../plugins/storage-query.js\";\nimport type {\n\tStorageCollection,\n\tQueryOptions,\n\tPaginatedResult,\n\tWhereClause,\n} from \"../../plugins/types.js\";\nimport { withTransaction } from \"../transaction.js\";\nimport type { Database } from \"../types.js\";\nimport { encodeCursor, decodeCursor } from \"./types.js\";\n\n/**\n * Plugin Storage Repository\n *\n * Implements the StorageCollection interface for a specific plugin and collection.\n */\nexport class PluginStorageRepository<T = unknown> implements StorageCollection<T> {\n\tprivate indexedFields: Set<string>;\n\n\tconstructor(\n\t\tprivate db: Kysely<Database>,\n\t\tprivate pluginId: string,\n\t\tprivate collection: string,\n\t\tindexes: Array<string | string[]>,\n\t) {\n\t\tthis.indexedFields = getIndexedFields(indexes);\n\t}\n\n\t/**\n\t * Get a document by ID\n\t */\n\tasync get(id: string): Promise<T | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select(\"data\")\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) return null;\n\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- JSON.parse returns any; generic callers provide T\n\t\treturn JSON.parse(row.data) as T;\n\t}\n\n\t/**\n\t * Store a document\n\t */\n\tasync put(id: string, data: T): Promise<void> {\n\t\tconst now = new Date().toISOString();\n\t\tconst jsonData = JSON.stringify(data);\n\n\t\tawait this.db\n\t\t\t.insertInto(\"_plugin_storage\")\n\t\t\t.values({\n\t\t\t\tplugin_id: this.pluginId,\n\t\t\t\tcollection: this.collection,\n\t\t\t\tid,\n\t\t\t\tdata: jsonData,\n\t\t\t\tcreated_at: now,\n\t\t\t\tupdated_at: now,\n\t\t\t})\n\t\t\t.onConflict((oc) =>\n\t\t\t\toc.columns([\"plugin_id\", \"collection\", \"id\"]).doUpdateSet({\n\t\t\t\t\tdata: jsonData,\n\t\t\t\t\tupdated_at: now,\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.execute();\n\t}\n\n\t/**\n\t * Delete a document\n\t */\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_plugin_storage\")\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\treturn (result.numDeletedRows ?? 0) > 0;\n\t}\n\n\t/**\n\t * Check if a document exists\n\t */\n\tasync exists(id: string): Promise<boolean> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\treturn !!row;\n\t}\n\n\t/**\n\t * Get multiple documents by ID\n\t */\n\tasync getMany(ids: string[]): Promise<Map<string, T>> {\n\t\tif (ids.length === 0) return new Map();\n\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select([\"id\", \"data\"])\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"in\", ids)\n\t\t\t.execute();\n\n\t\tconst result = new Map<string, T>();\n\t\tfor (const row of rows) {\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- JSON.parse returns any; generic callers provide T\n\t\t\tresult.set(row.id, JSON.parse(row.data) as T);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Store multiple documents\n\t */\n\tasync putMany(items: Array<{ id: string; data: T }>): Promise<void> {\n\t\tif (items.length === 0) return;\n\n\t\tconst now = new Date().toISOString();\n\n\t\t// SQLite doesn't support batch upserts well, so we do them one at a time\n\t\t// In a transaction for atomicity\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\tfor (const item of items) {\n\t\t\t\tconst jsonData = JSON.stringify(item.data);\n\t\t\t\tawait trx\n\t\t\t\t\t.insertInto(\"_plugin_storage\")\n\t\t\t\t\t.values({\n\t\t\t\t\t\tplugin_id: this.pluginId,\n\t\t\t\t\t\tcollection: this.collection,\n\t\t\t\t\t\tid: item.id,\n\t\t\t\t\t\tdata: jsonData,\n\t\t\t\t\t\tcreated_at: now,\n\t\t\t\t\t\tupdated_at: now,\n\t\t\t\t\t})\n\t\t\t\t\t.onConflict((oc) =>\n\t\t\t\t\t\toc.columns([\"plugin_id\", \"collection\", \"id\"]).doUpdateSet({\n\t\t\t\t\t\t\tdata: jsonData,\n\t\t\t\t\t\t\tupdated_at: now,\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t\t.execute();\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Delete multiple documents\n\t */\n\tasync deleteMany(ids: string[]): Promise<number> {\n\t\tif (ids.length === 0) return 0;\n\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_plugin_storage\")\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"in\", ids)\n\t\t\t.executeTakeFirst();\n\n\t\treturn Number(result.numDeletedRows ?? 0);\n\t}\n\n\t/**\n\t * Query documents with filters\n\t */\n\tasync query(options: QueryOptions = {}): Promise<PaginatedResult<{ id: string; data: T }>> {\n\t\tconst { where = {}, orderBy = {}, cursor } = options;\n\t\tconst limit = Math.min(options.limit ?? 50, 100);\n\n\t\t// Validate that all queried fields are indexed\n\t\tvalidateWhereClause(where, this.indexedFields, this.pluginId, this.collection);\n\t\tif (Object.keys(orderBy).length > 0) {\n\t\t\tvalidateOrderByClause(orderBy, this.indexedFields, this.pluginId, this.collection);\n\t\t}\n\n\t\t// Build base query\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select([\"id\", \"data\", \"created_at\"])\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection);\n\n\t\t// Add JSON extraction WHERE conditions\n\t\tconst whereResult = buildWhereClause(this.db, where);\n\t\tif (whereResult.sql) {\n\t\t\t// Use sql template to add the raw WHERE conditions with params\n\t\t\tconst whereSqlParts: ReturnType<typeof sql>[] = [];\n\t\t\tlet paramIndex = 0;\n\t\t\tconst sqlParts = whereResult.sql.split(\"?\");\n\t\t\tfor (let i = 0; i < sqlParts.length; i++) {\n\t\t\t\tif (i > 0) {\n\t\t\t\t\twhereSqlParts.push(sql`${whereResult.params[paramIndex++]}`);\n\t\t\t\t}\n\t\t\t\tif (sqlParts[i]) {\n\t\t\t\t\twhereSqlParts.push(sql.raw(sqlParts[i]));\n\t\t\t\t}\n\t\t\t}\n\t\t\tquery = query.where(({ eb }) => eb(sql.join(whereSqlParts, sql.raw(\"\")), \"=\", sql.raw(\"1\")));\n\t\t}\n\n\t\t// Handle cursor-based pagination — throws on invalid cursor.\n\t\tif (cursor) {\n\t\t\tconst decoded = decodeCursor(cursor);\n\t\t\tquery = query.where(({ eb }) =>\n\t\t\t\teb(sql`(created_at, id)`, \">\", sql`(${decoded.orderValue}, ${decoded.id})`),\n\t\t\t);\n\t\t}\n\n\t\t// Build ORDER BY using sql template\n\t\tif (Object.keys(orderBy).length > 0) {\n\t\t\tfor (const [field, direction] of Object.entries(orderBy)) {\n\t\t\t\tconst extract = jsonExtract(this.db, field);\n\t\t\t\tconst orderExpr =\n\t\t\t\t\tdirection === \"desc\" ? sql`${sql.raw(extract)} desc` : sql`${sql.raw(extract)} asc`;\n\t\t\t\tquery = query.orderBy(orderExpr);\n\t\t\t}\n\t\t} else {\n\t\t\t// Default ordering for consistent pagination\n\t\t\tquery = query.orderBy(\"created_at\", \"asc\").orderBy(\"id\", \"asc\");\n\t\t}\n\n\t\t// Apply limit (fetch one extra to detect if there's more)\n\t\tquery = query.limit(limit + 1);\n\n\t\tconst rows = await query.execute();\n\n\t\tconst hasMore = rows.length > limit;\n\t\tconst items = rows.slice(0, limit).map((row) => ({\n\t\t\tid: row.id,\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- JSON.parse returns any; generic callers provide T\n\t\t\tdata: JSON.parse(row.data) as T,\n\t\t}));\n\n\t\t// Generate cursor for next page if there are more results\n\t\tlet nextCursor: string | undefined;\n\t\tif (hasMore) {\n\t\t\tconst lastItem = rows[limit - 1];\n\t\t\tif (lastItem) {\n\t\t\t\tnextCursor = encodeCursor(lastItem.created_at, lastItem.id);\n\t\t\t}\n\t\t}\n\n\t\treturn { items, cursor: nextCursor, hasMore };\n\t}\n\n\t/**\n\t * Count documents matching a filter\n\t */\n\tasync count(where?: WhereClause): Promise<number> {\n\t\tif (where && Object.keys(where).length > 0) {\n\t\t\tvalidateWhereClause(where, this.indexedFields, this.pluginId, this.collection);\n\t\t}\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select(sql<number>`COUNT(*)`.as(\"count\"))\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection);\n\n\t\t// Add JSON extraction WHERE conditions\n\t\tif (where && Object.keys(where).length > 0) {\n\t\t\tconst whereResult = buildWhereClause(this.db, where);\n\t\t\tif (whereResult.sql) {\n\t\t\t\t// Use sql template to add the raw WHERE conditions with params\n\t\t\t\tconst whereSqlParts: ReturnType<typeof sql>[] = [];\n\t\t\t\tlet paramIndex = 0;\n\t\t\t\tconst sqlParts = whereResult.sql.split(\"?\");\n\t\t\t\tfor (let i = 0; i < sqlParts.length; i++) {\n\t\t\t\t\tif (i > 0) {\n\t\t\t\t\t\twhereSqlParts.push(sql`${whereResult.params[paramIndex++]}`);\n\t\t\t\t\t}\n\t\t\t\t\tif (sqlParts[i]) {\n\t\t\t\t\t\twhereSqlParts.push(sql.raw(sqlParts[i]));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tquery = query.where(({ eb }) =>\n\t\t\t\t\teb(sql.join(whereSqlParts, sql.raw(\"\")), \"=\", sql.raw(\"1\")),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn result?.count ?? 0;\n\t}\n}\n\n/**\n * Create a scoped storage accessor for a plugin\n */\nexport function createPluginStorageAccessor(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tstorageConfig: Record<\n\t\tstring,\n\t\t{ indexes: Array<string | string[]>; uniqueIndexes?: Array<string | string[]> }\n\t>,\n): Record<string, StorageCollection> {\n\tconst accessor: Record<string, StorageCollection> = {};\n\n\tfor (const [collectionName, config] of Object.entries(storageConfig)) {\n\t\tconst allIndexes = [...config.indexes, ...(config.uniqueIndexes ?? [])];\n\t\taccessor[collectionName] = new PluginStorageRepository(\n\t\t\tdb,\n\t\t\tpluginId,\n\t\t\tcollectionName,\n\t\t\tallIndexes,\n\t\t);\n\t}\n\n\treturn accessor;\n}\n\n/**\n * Delete all storage data for a plugin\n */\nexport async function deleteAllPluginStorage(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n): Promise<number> {\n\tconst result = await db\n\t\t.deleteFrom(\"_plugin_storage\")\n\t\t.where(\"plugin_id\", \"=\", pluginId)\n\t\t.executeTakeFirst();\n\n\treturn Number(result.numDeletedRows ?? 0);\n}\n\n/**\n * Delete all storage data for a plugin collection\n */\nexport async function deletePluginCollection(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tcollection: string,\n): Promise<number> {\n\tconst result = await db\n\t\t.deleteFrom(\"_plugin_storage\")\n\t\t.where(\"plugin_id\", \"=\", pluginId)\n\t\t.where(\"collection\", \"=\", collection)\n\t\t.executeTakeFirst();\n\n\treturn Number(result.numDeletedRows ?? 0);\n}\n","/**\n * Plugin Context v2\n *\n * Creates the unified context object provided to plugins in all hooks and routes.\n *\n */\n\nimport type { Kysely } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { ContentRepository } from \"../database/repositories/content.js\";\nimport { MediaRepository } from \"../database/repositories/media.js\";\nimport { OptionsRepository } from \"../database/repositories/options.js\";\nimport { PluginStorageRepository } from \"../database/repositories/plugin-storage.js\";\nimport { SeoRepository } from \"../database/repositories/seo.js\";\nimport { UserRepository } from \"../database/repositories/user.js\";\nimport { withTransaction } from \"../database/transaction.js\";\nimport type { Database } from \"../database/types.js\";\nimport {\n\tresolveAndValidateExternalUrl,\n\tSsrfError,\n\tstripCredentialHeaders,\n} from \"../import/ssrf.js\";\nimport { invalidateSiteSettingsCache } from \"../settings/index.js\";\nimport type { Storage } from \"../storage/types.js\";\nimport { CronAccessImpl } from \"./cron.js\";\nimport type { EmailPipeline } from \"./email.js\";\nimport type {\n\tResolvedPlugin,\n\tPluginContext,\n\tPluginStorageConfig,\n\tStorageCollection,\n\tKVAccess,\n\tCronAccess,\n\tEmailAccess,\n\tContentAccess,\n\tContentAccessWithWrite,\n\tMediaAccess,\n\tMediaAccessWithWrite,\n\tHttpAccess,\n\tLogAccess,\n\tSiteInfo,\n\tUserAccess,\n\tUserInfo,\n\tContentItem,\n\tContentItemSeoInput,\n\tContentWriteInput,\n\tMediaItem,\n\tPaginatedResult,\n\tQueryOptions,\n\tContentListOptions,\n\tMediaListOptions,\n} from \"./types.js\";\n\n// =============================================================================\n// KV Access\n// =============================================================================\n\n/**\n * Create KV accessor for a plugin\n * All keys are automatically prefixed with the plugin ID\n */\nexport function createKVAccess(optionsRepo: OptionsRepository, pluginId: string): KVAccess {\n\tconst prefix = `plugin:${pluginId}:`;\n\n\treturn {\n\t\tasync get<T>(key: string): Promise<T | null> {\n\t\t\treturn optionsRepo.get<T>(`${prefix}${key}`);\n\t\t},\n\n\t\tasync set(key: string, value: unknown): Promise<void> {\n\t\t\tawait optionsRepo.set(`${prefix}${key}`, value);\n\t\t},\n\n\t\tasync delete(key: string): Promise<boolean> {\n\t\t\treturn optionsRepo.delete(`${prefix}${key}`);\n\t\t},\n\n\t\tasync list(keyPrefix?: string): Promise<Array<{ key: string; value: unknown }>> {\n\t\t\tconst fullPrefix = `${prefix}${keyPrefix ?? \"\"}`;\n\t\t\tconst entriesMap = await optionsRepo.getByPrefix(fullPrefix);\n\t\t\tconst result: Array<{ key: string; value: unknown }> = [];\n\t\t\tfor (const [fullKey, value] of entriesMap) {\n\t\t\t\tresult.push({\n\t\t\t\t\tkey: fullKey.slice(prefix.length),\n\t\t\t\t\tvalue,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Storage Access\n// =============================================================================\n\n/**\n * Create storage collection accessor for a plugin\n * Wraps PluginStorageRepository with the v2 interface (no async iterators)\n */\nfunction createStorageCollection<T>(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tcollectionName: string,\n\tindexes: Array<string | string[]>,\n): StorageCollection<T> {\n\tconst repo = new PluginStorageRepository<T>(db, pluginId, collectionName, indexes);\n\n\treturn {\n\t\tget: (id) => repo.get(id),\n\t\tput: (id, data) => repo.put(id, data),\n\t\tdelete: (id) => repo.delete(id),\n\t\texists: (id) => repo.exists(id),\n\t\tgetMany: (ids) => repo.getMany(ids),\n\t\tputMany: (items) => repo.putMany(items),\n\t\tdeleteMany: (ids) => repo.deleteMany(ids),\n\t\tcount: (where) => repo.count(where),\n\n\t\t// Query returns PaginatedResult instead of the old format\n\t\tasync query(options?: QueryOptions): Promise<PaginatedResult<{ id: string; data: T }>> {\n\t\t\tconst result = await repo.query({\n\t\t\t\twhere: options?.where,\n\t\t\t\torderBy: options?.orderBy,\n\t\t\t\tlimit: options?.limit,\n\t\t\t\tcursor: options?.cursor,\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\titems: result.items,\n\t\t\t\tcursor: result.cursor,\n\t\t\t\thasMore: result.hasMore,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Create storage accessor with all declared collections\n */\nexport function createStorageAccess<T extends PluginStorageConfig>(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tstorageConfig: T,\n): Record<string, StorageCollection> {\n\tconst storage: Record<string, StorageCollection> = {};\n\n\tfor (const [collectionName, config] of Object.entries(storageConfig)) {\n\t\tconst allIndexes = [...config.indexes, ...(config.uniqueIndexes ?? [])];\n\t\tstorage[collectionName] = createStorageCollection(db, pluginId, collectionName, allIndexes);\n\t}\n\n\treturn storage;\n}\n\n// =============================================================================\n// Content Access\n// =============================================================================\n\n/**\n * Extract `seo` from a plugin-supplied content write input and return both\n * parts. Mutates nothing — returns a new field map without the `seo` key.\n */\nfunction splitSeoFromInput(input: ContentWriteInput): {\n\tfields: Record<string, unknown>;\n\tseo: ContentItemSeoInput | undefined;\n} {\n\tconst { seo, ...fields } = input;\n\t// Reject non-object seo values rather than silently dropping them.\n\tif (seo !== undefined && (seo === null || typeof seo !== \"object\" || Array.isArray(seo))) {\n\t\tthrow new Error(\"content.seo must be an object\");\n\t}\n\treturn { fields, seo };\n}\n\n/**\n * Reject writing SEO to a collection that does not have it enabled.\n * Matches the REST API behavior (VALIDATION_ERROR).\n */\nasync function assertSeoEnabled(\n\tseoRepo: SeoRepository,\n\tcollection: string,\n\tseo: ContentItemSeoInput | undefined,\n): Promise<boolean> {\n\tconst hasSeo = await seoRepo.isEnabled(collection);\n\tif (seo !== undefined && !hasSeo) {\n\t\tthrow new Error(\n\t\t\t`Collection \"${collection}\" does not have SEO enabled. ` +\n\t\t\t\t`Remove the seo field or enable SEO on this collection.`,\n\t\t);\n\t}\n\treturn hasSeo;\n}\n\n/**\n * Create read-only content access\n */\nexport function createContentAccess(db: Kysely<Database>): ContentAccess {\n\tconst contentRepo = new ContentRepository(db);\n\tconst seoRepo = new SeoRepository(db);\n\n\treturn {\n\t\tasync get(collection: string, id: string): Promise<ContentItem | null> {\n\t\t\tconst item = await contentRepo.findById(collection, id);\n\t\t\tif (!item) return null;\n\n\t\t\tconst result: ContentItem = {\n\t\t\t\tid: item.id,\n\t\t\t\ttype: item.type,\n\t\t\t\tslug: item.slug,\n\t\t\t\tstatus: item.status,\n\t\t\t\tdata: item.data,\n\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\tlocale: item.locale,\n\t\t\t\tpublishedAt: item.publishedAt,\n\t\t\t};\n\n\t\t\tif (await seoRepo.isEnabled(collection)) {\n\t\t\t\tresult.seo = await seoRepo.get(collection, item.id);\n\t\t\t}\n\n\t\t\treturn result;\n\t\t},\n\n\t\tasync list(\n\t\t\tcollection: string,\n\t\t\toptions?: ContentListOptions,\n\t\t): Promise<PaginatedResult<ContentItem>> {\n\t\t\t// Convert orderBy format if provided\n\t\t\tlet orderBy: { field: string; direction: \"asc\" | \"desc\" } | undefined;\n\t\t\tif (options?.orderBy) {\n\t\t\t\tconst entries = Object.entries(options.orderBy);\n\t\t\t\tconst first = entries[0];\n\t\t\t\tif (first) {\n\t\t\t\t\torderBy = { field: first[0], direction: first[1] };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst result = await contentRepo.findMany(collection, {\n\t\t\t\tlimit: options?.limit ?? 50,\n\t\t\t\tcursor: options?.cursor,\n\t\t\t\torderBy,\n\t\t\t\twhere: options?.where,\n\t\t\t});\n\n\t\t\tconst items: ContentItem[] = result.items.map((item) => ({\n\t\t\t\tid: item.id,\n\t\t\t\ttype: item.type,\n\t\t\t\tslug: item.slug,\n\t\t\t\tstatus: item.status,\n\t\t\t\tdata: item.data,\n\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\tlocale: item.locale,\n\t\t\t\tpublishedAt: item.publishedAt,\n\t\t\t}));\n\n\t\t\tif (items.length > 0 && (await seoRepo.isEnabled(collection))) {\n\t\t\t\tconst seoMap = await seoRepo.getMany(\n\t\t\t\t\tcollection,\n\t\t\t\t\titems.map((i) => i.id),\n\t\t\t\t);\n\t\t\t\tfor (const item of items) {\n\t\t\t\t\tconst seo = seoMap.get(item.id);\n\t\t\t\t\tif (seo) item.seo = seo;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\titems,\n\t\t\t\tcursor: result.nextCursor,\n\t\t\t\thasMore: !!result.nextCursor,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Create full content access with write operations.\n *\n * `create` and `update` accept a reserved `seo` key in their `data`\n * argument. When present, it is routed to the core SEO panel\n * (`_emdash_seo`) via `SeoRepository.upsert`, in the same transaction as\n * the content write. The returned `ContentItem.seo` reflects the resulting\n * SEO state for SEO-enabled collections.\n */\nexport function createContentAccessWithWrite(db: Kysely<Database>): ContentAccessWithWrite {\n\tconst readAccess = createContentAccess(db);\n\n\treturn {\n\t\t...readAccess,\n\n\t\tasync create(collection: string, data: ContentWriteInput): Promise<ContentItem> {\n\t\t\tconst { fields, seo } = splitSeoFromInput(data);\n\n\t\t\treturn withTransaction(db, async (trx) => {\n\t\t\t\tconst trxContentRepo = new ContentRepository(trx);\n\t\t\t\tconst trxSeoRepo = new SeoRepository(trx);\n\n\t\t\t\tconst hasSeo = await assertSeoEnabled(trxSeoRepo, collection, seo);\n\n\t\t\t\tconst item = await trxContentRepo.create({\n\t\t\t\t\ttype: collection,\n\t\t\t\t\tdata: fields,\n\t\t\t\t});\n\n\t\t\t\tconst result: ContentItem = {\n\t\t\t\t\tid: item.id,\n\t\t\t\t\ttype: item.type,\n\t\t\t\t\tslug: item.slug,\n\t\t\t\t\tstatus: item.status,\n\t\t\t\t\tdata: item.data,\n\t\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\t\tlocale: item.locale,\n\t\t\t\t\tpublishedAt: item.publishedAt,\n\t\t\t\t};\n\n\t\t\t\tif (hasSeo) {\n\t\t\t\t\tresult.seo =\n\t\t\t\t\t\tseo !== undefined\n\t\t\t\t\t\t\t? await trxSeoRepo.upsert(collection, item.id, seo)\n\t\t\t\t\t\t\t: await trxSeoRepo.get(collection, item.id);\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t});\n\t\t},\n\n\t\tasync update(collection: string, id: string, data: ContentWriteInput): Promise<ContentItem> {\n\t\t\tconst { fields, seo } = splitSeoFromInput(data);\n\n\t\t\treturn withTransaction(db, async (trx) => {\n\t\t\t\tconst trxContentRepo = new ContentRepository(trx);\n\t\t\t\tconst trxSeoRepo = new SeoRepository(trx);\n\n\t\t\t\tconst hasSeo = await assertSeoEnabled(trxSeoRepo, collection, seo);\n\n\t\t\t\t// Pass the `data` payload to ContentRepository.update only when\n\t\t\t\t// there are field updates — passing an empty object would still\n\t\t\t\t// bump updated_at/version, but we want a seo-only call to touch\n\t\t\t\t// only the SEO table. ContentRepository.update handles the no-op\n\t\t\t\t// path by returning the current row.\n\t\t\t\tconst hasFieldUpdates = Object.keys(fields).length > 0;\n\t\t\t\tconst item = hasFieldUpdates\n\t\t\t\t\t? await trxContentRepo.update(collection, id, { data: fields })\n\t\t\t\t\t: await (async () => {\n\t\t\t\t\t\t\tconst existing = await trxContentRepo.findById(collection, id);\n\t\t\t\t\t\t\tif (!existing) throw new Error(\"Content not found\");\n\t\t\t\t\t\t\treturn existing;\n\t\t\t\t\t\t})();\n\n\t\t\t\tconst result: ContentItem = {\n\t\t\t\t\tid: item.id,\n\t\t\t\t\ttype: item.type,\n\t\t\t\t\tslug: item.slug,\n\t\t\t\t\tstatus: item.status,\n\t\t\t\t\tdata: item.data,\n\t\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\t\tlocale: item.locale,\n\t\t\t\t\tpublishedAt: item.publishedAt,\n\t\t\t\t};\n\n\t\t\t\tif (hasSeo) {\n\t\t\t\t\tresult.seo =\n\t\t\t\t\t\tseo !== undefined\n\t\t\t\t\t\t\t? await trxSeoRepo.upsert(collection, item.id, seo)\n\t\t\t\t\t\t\t: await trxSeoRepo.get(collection, item.id);\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t});\n\t\t},\n\n\t\tasync delete(collection: string, id: string): Promise<boolean> {\n\t\t\tconst contentRepo = new ContentRepository(db);\n\t\t\treturn contentRepo.delete(collection, id);\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Media Access\n// =============================================================================\n\n/**\n * Create read-only media access\n */\nexport function createMediaAccess(db: Kysely<Database>): MediaAccess {\n\tconst mediaRepo = new MediaRepository(db);\n\n\treturn {\n\t\tasync get(id: string): Promise<MediaItem | null> {\n\t\t\tconst item = await mediaRepo.findById(id);\n\t\t\tif (!item) return null;\n\n\t\t\treturn {\n\t\t\t\tid: item.id,\n\t\t\t\tfilename: item.filename,\n\t\t\t\tmimeType: item.mimeType,\n\t\t\t\tsize: item.size,\n\t\t\t\t// Construct URL from storage key (or use a sensible default path)\n\t\t\t\turl: `/media/${item.id}/${item.filename}`,\n\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t};\n\t\t},\n\n\t\tasync list(options?: MediaListOptions): Promise<PaginatedResult<MediaItem>> {\n\t\t\tconst result = await mediaRepo.findMany({\n\t\t\t\tlimit: options?.limit ?? 50,\n\t\t\t\tcursor: options?.cursor,\n\t\t\t\tmimeType: options?.mimeType,\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\titems: result.items.map((item) => ({\n\t\t\t\t\tid: item.id,\n\t\t\t\t\tfilename: item.filename,\n\t\t\t\t\tmimeType: item.mimeType,\n\t\t\t\t\tsize: item.size,\n\t\t\t\t\turl: `/media/${item.id}/${item.filename}`,\n\t\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\t})),\n\t\t\t\tcursor: result.nextCursor,\n\t\t\t\thasMore: !!result.nextCursor,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Create full media access with write operations.\n * If storage is not provided, upload() will throw at call time.\n */\nexport function createMediaAccessWithWrite(\n\tdb: Kysely<Database>,\n\tgetUploadUrlFn: (\n\t\tfilename: string,\n\t\tcontentType: string,\n\t) => Promise<{ uploadUrl: string; mediaId: string }>,\n\tstorage?: Storage,\n): MediaAccessWithWrite {\n\tconst mediaRepo = new MediaRepository(db);\n\tconst readAccess = createMediaAccess(db);\n\n\treturn {\n\t\t...readAccess,\n\n\t\tgetUploadUrl: getUploadUrlFn,\n\n\t\tasync upload(\n\t\t\tfilename: string,\n\t\t\tcontentType: string,\n\t\t\tbytes: ArrayBuffer,\n\t\t): Promise<{ mediaId: string; storageKey: string; url: string }> {\n\t\t\tif (!storage) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Media upload() requires a storage backend. Configure storage in PluginContextFactoryOptions.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Generate a storage key with a unique prefix\n\t\t\tconst keyPrefix = ulid();\n\t\t\t// Extract extension from basename (ignore path separators)\n\t\t\tconst basename = filename.split(\"/\").pop() ?? filename;\n\t\t\tconst dotIdx = basename.lastIndexOf(\".\");\n\t\t\tconst ext = dotIdx > 0 ? basename.slice(dotIdx).toLowerCase() : \"\";\n\t\t\tconst storageKey = `${keyPrefix}${ext}`;\n\n\t\t\t// Upload to storage first\n\t\t\tawait storage.upload({\n\t\t\t\tkey: storageKey,\n\t\t\t\tbody: new Uint8Array(bytes),\n\t\t\t\tcontentType,\n\t\t\t});\n\n\t\t\t// Create DB record — clean up storage on failure\n\t\t\tlet media;\n\t\t\ttry {\n\t\t\t\tmedia = await mediaRepo.create({\n\t\t\t\t\tfilename: basename,\n\t\t\t\t\tmimeType: contentType,\n\t\t\t\t\tsize: bytes.byteLength,\n\t\t\t\t\tstorageKey,\n\t\t\t\t\tstatus: \"ready\",\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tawait storage.delete(storageKey);\n\t\t\t\t} catch {\n\t\t\t\t\t// Best-effort cleanup\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tmediaId: media.id,\n\t\t\t\tstorageKey,\n\t\t\t\turl: `/_emdash/api/media/file/${storageKey}`,\n\t\t\t};\n\t\t},\n\n\t\tasync delete(id: string): Promise<boolean> {\n\t\t\tconst deleted = await mediaRepo.delete(id);\n\t\t\t// Plugins can delete media that's referenced by site settings\n\t\t\t// (`logo`, `favicon`, `seo.defaultOgImage`); the worker-scoped\n\t\t\t// resolved-URL cache must be dropped or it will keep serving\n\t\t\t// 404s. Matches the invalidation in\n\t\t\t// `EmDashRuntime.handleMediaDelete`.\n\t\t\tif (deleted) {\n\t\t\t\tinvalidateSiteSettingsCache();\n\t\t\t}\n\t\t\treturn deleted;\n\t\t},\n\t};\n}\n\n// =============================================================================\n// HTTP Access\n// =============================================================================\n\n/** Maximum number of redirects to follow in plugin HTTP access */\nconst MAX_PLUGIN_REDIRECTS = 5;\n\n/**\n * Check if a hostname matches any pattern in the allowed list.\n * Patterns: \"*\" matches all, \"*.example.com\" matches subdomains AND bare \"example.com\",\n * \"api.example.com\" matches exactly.\n */\nfunction isHostAllowed(host: string, allowedHosts: string[]): boolean {\n\treturn allowedHosts.some((pattern) => {\n\t\tif (pattern === \"*\") return true;\n\t\tif (pattern.startsWith(\"*.\")) {\n\t\t\tconst suffix = pattern.slice(1); // \".example.com\"\n\t\t\t// Match subdomains (foo.example.com) and bare domain (example.com)\n\t\t\treturn host.endsWith(suffix) || host === pattern.slice(2);\n\t\t}\n\t\treturn host === pattern;\n\t});\n}\n\n/**\n * Create HTTP access with host validation.\n *\n * Uses redirect: \"manual\" to re-validate each redirect target against\n * the allowedHosts list, preventing redirects to unauthorized hosts.\n */\nexport function createHttpAccess(pluginId: string, allowedHosts: string[]): HttpAccess {\n\treturn {\n\t\tasync fetch(url: string, init?: RequestInit): Promise<Response> {\n\t\t\t// Deny by default — plugins must declare allowed hosts\n\t\t\tif (allowedHosts.length === 0) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Plugin \"${pluginId}\" has no allowed hosts configured. ` +\n\t\t\t\t\t\t`Add hosts to the plugin's allowedHosts array to enable HTTP requests.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet currentUrl = url;\n\t\t\tlet currentInit = init;\n\n\t\t\tfor (let i = 0; i <= MAX_PLUGIN_REDIRECTS; i++) {\n\t\t\t\tconst hostname = new URL(currentUrl).hostname;\n\t\t\t\tif (!isHostAllowed(hostname, allowedHosts)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Plugin \"${pluginId}\" is not allowed to fetch from host \"${hostname}\". ` +\n\t\t\t\t\t\t\t`Allowed hosts: ${allowedHosts.join(\", \")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst response = await globalThis.fetch(currentUrl, {\n\t\t\t\t\t...currentInit,\n\t\t\t\t\tredirect: \"manual\",\n\t\t\t\t});\n\n\t\t\t\t// Not a redirect -- return directly\n\t\t\t\tif (response.status < 300 || response.status >= 400) {\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Extract redirect target\n\t\t\t\tconst location = response.headers.get(\"Location\");\n\t\t\t\tif (!location) {\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Resolve relative redirects; strip credentials on cross-origin hops\n\t\t\t\tconst previousOrigin = new URL(currentUrl).origin;\n\t\t\t\tcurrentUrl = new URL(location, currentUrl).href;\n\t\t\t\tconst nextOrigin = new URL(currentUrl).origin;\n\n\t\t\t\tif (previousOrigin !== nextOrigin && currentInit) {\n\t\t\t\t\tcurrentInit = stripCredentialHeaders(currentInit);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthrow new Error(`Plugin \"${pluginId}\": too many redirects (max ${MAX_PLUGIN_REDIRECTS})`);\n\t\t},\n\t};\n}\n\n/**\n * Create unrestricted HTTP access (for plugins with network:fetch:any capability).\n * No host validation, but applies SSRF protection on redirect targets to\n * prevent plugins from being tricked into reaching internal services.\n */\nexport function createUnrestrictedHttpAccess(pluginId: string): HttpAccess {\n\treturn {\n\t\tasync fetch(url: string, init?: RequestInit): Promise<Response> {\n\t\t\tlet currentUrl = url;\n\t\t\tlet currentInit = init;\n\n\t\t\tfor (let i = 0; i <= MAX_PLUGIN_REDIRECTS; i++) {\n\t\t\t\t// Validate each URL against SSRF rules (private IPs, metadata\n\t\t\t\t// endpoints, wildcard DNS, resolved-IP private ranges).\n\t\t\t\ttry {\n\t\t\t\t\tawait resolveAndValidateExternalUrl(currentUrl);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tconst msg = e instanceof SsrfError ? e.message : \"SSRF validation failed\";\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Plugin \"${pluginId}\": blocked fetch to \"${new URL(currentUrl).hostname}\": ${msg}`,\n\t\t\t\t\t\t{ cause: e },\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst response = await globalThis.fetch(currentUrl, {\n\t\t\t\t\t...currentInit,\n\t\t\t\t\tredirect: \"manual\",\n\t\t\t\t});\n\n\t\t\t\t// Not a redirect -- return directly\n\t\t\t\tif (response.status < 300 || response.status >= 400) {\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Extract redirect target\n\t\t\t\tconst location = response.headers.get(\"Location\");\n\t\t\t\tif (!location) {\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Resolve relative redirects; strip credentials on cross-origin hops\n\t\t\t\tconst previousOrigin = new URL(currentUrl).origin;\n\t\t\t\tcurrentUrl = new URL(location, currentUrl).href;\n\t\t\t\tconst nextOrigin = new URL(currentUrl).origin;\n\n\t\t\t\tif (previousOrigin !== nextOrigin && currentInit) {\n\t\t\t\t\tcurrentInit = stripCredentialHeaders(currentInit);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthrow new Error(`Plugin \"${pluginId}\": too many redirects (max ${MAX_PLUGIN_REDIRECTS})`);\n\t\t},\n\t};\n}\n\n/**\n * Create blocked HTTP access (for plugins without network:request capability)\n */\nexport function createBlockedHttpAccess(pluginId: string): HttpAccess {\n\treturn {\n\t\tasync fetch(): Promise<never> {\n\t\t\tthrow new Error(\n\t\t\t\t`Plugin \"${pluginId}\" does not have the \"network:request\" capability. ` +\n\t\t\t\t\t`Add \"network:request\" to the plugin's capabilities to enable HTTP requests.`,\n\t\t\t);\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Log Access\n// =============================================================================\n\n/**\n * Create logger for a plugin\n */\nexport function createLogAccess(pluginId: string): LogAccess {\n\tconst prefix = `[plugin:${pluginId}]`;\n\n\treturn {\n\t\tdebug(message: string, data?: unknown): void {\n\t\t\tif (data !== undefined) {\n\t\t\t\tconsole.debug(prefix, message, data);\n\t\t\t} else {\n\t\t\t\tconsole.debug(prefix, message);\n\t\t\t}\n\t\t},\n\n\t\tinfo(message: string, data?: unknown): void {\n\t\t\tif (data !== undefined) {\n\t\t\t\tconsole.info(prefix, message, data);\n\t\t\t} else {\n\t\t\t\tconsole.info(prefix, message);\n\t\t\t}\n\t\t},\n\n\t\twarn(message: string, data?: unknown): void {\n\t\t\tif (data !== undefined) {\n\t\t\t\tconsole.warn(prefix, message, data);\n\t\t\t} else {\n\t\t\t\tconsole.warn(prefix, message);\n\t\t\t}\n\t\t},\n\n\t\terror(message: string, data?: unknown): void {\n\t\t\tif (data !== undefined) {\n\t\t\t\tconsole.error(prefix, message, data);\n\t\t\t} else {\n\t\t\t\tconsole.error(prefix, message);\n\t\t\t}\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Site Info\n// =============================================================================\n\nconst TRAILING_SLASH_RE = /\\/$/;\n\n/**\n * Options for creating site info\n */\nexport interface SiteInfoOptions {\n\t/** Site name from options table */\n\tsiteName?: string;\n\t/** Site URL from options table or Astro config */\n\tsiteUrl?: string;\n\t/** Site locale from options table */\n\tlocale?: string;\n}\n\n/**\n * Create site info from config and settings.\n *\n * Resolution order for URL:\n * 1. options table (emdash:site_url)\n * 2. Astro `site` config\n * 3. fallback to empty string\n */\nexport function createSiteInfo(options: SiteInfoOptions): SiteInfo {\n\treturn {\n\t\tname: options.siteName ?? \"\",\n\t\turl: (options.siteUrl ?? \"\").replace(TRAILING_SLASH_RE, \"\"), // strip trailing slash\n\t\tlocale: options.locale ?? \"en\",\n\t};\n}\n\n/**\n * Create a URL helper that generates absolute URLs from relative paths.\n * Validates that path starts with \"/\" and rejects protocol-relative paths (\"//\").\n */\nexport function createUrlHelper(siteUrl: string): (path: string) => string {\n\tconst base = siteUrl.replace(TRAILING_SLASH_RE, \"\"); // strip trailing slash\n\n\treturn (path: string): string => {\n\t\tif (!path.startsWith(\"/\")) {\n\t\t\tthrow new Error(`URL path must start with \"/\", got: \"${path}\"`);\n\t\t}\n\t\tif (path.startsWith(\"//\")) {\n\t\t\tthrow new Error(`URL path must not be protocol-relative, got: \"${path}\"`);\n\t\t}\n\t\treturn `${base}${path}`;\n\t};\n}\n\n// =============================================================================\n// User Access\n// =============================================================================\n\n/**\n * Convert a UserRepository user to the plugin-facing UserInfo shape.\n * Strips sensitive fields (avatarUrl, emailVerified, data).\n */\nfunction toUserInfo(user: {\n\tid: string;\n\temail: string;\n\tname: string | null;\n\trole: number;\n\tcreatedAt: string;\n}): UserInfo {\n\treturn {\n\t\tid: user.id,\n\t\temail: user.email,\n\t\tname: user.name,\n\t\trole: user.role,\n\t\tcreatedAt: user.createdAt,\n\t};\n}\n\n/**\n * Create read-only user access for plugins.\n * Excludes sensitive fields (password hashes, sessions, passkeys, avatar URL, data).\n */\nexport function createUserAccess(db: Kysely<Database>): UserAccess {\n\tconst userRepo = new UserRepository(db);\n\n\treturn {\n\t\tasync get(id: string): Promise<UserInfo | null> {\n\t\t\tconst user = await userRepo.findById(id);\n\t\t\tif (!user) return null;\n\t\t\treturn toUserInfo(user);\n\t\t},\n\n\t\tasync getByEmail(email: string): Promise<UserInfo | null> {\n\t\t\tconst user = await userRepo.findByEmail(email);\n\t\t\tif (!user) return null;\n\t\t\treturn toUserInfo(user);\n\t\t},\n\n\t\tasync list(opts?: {\n\t\t\trole?: number;\n\t\t\tlimit?: number;\n\t\t\tcursor?: string;\n\t\t}): Promise<{ items: UserInfo[]; nextCursor?: string }> {\n\t\t\tconst result = await userRepo.findMany({\n\t\t\t\trole: opts?.role as 10 | 20 | 30 | 40 | 50 | undefined,\n\t\t\t\tcursor: opts?.cursor,\n\t\t\t\tlimit: opts?.limit,\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\titems: result.items.map(toUserInfo),\n\t\t\t\tnextCursor: result.nextCursor,\n\t\t\t};\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Plugin Context Factory\n// =============================================================================\n\nexport interface PluginContextFactoryOptions {\n\tdb: Kysely<Database>;\n\t/**\n\t * Storage backend for direct media uploads.\n\t * If not provided, upload() will throw.\n\t */\n\tstorage?: Storage;\n\t/**\n\t * Function to generate upload URLs for media.\n\t * If not provided, media write operations will throw.\n\t */\n\tgetUploadUrl?: (\n\t\tfilename: string,\n\t\tcontentType: string,\n\t) => Promise<{ uploadUrl: string; mediaId: string }>;\n\t/**\n\t * Site information for ctx.site and ctx.url().\n\t * If not provided, site info will have empty defaults.\n\t */\n\tsiteInfo?: SiteInfoOptions;\n\t/**\n\t * Callback to notify the cron scheduler that the next due time may have changed.\n\t * If not provided, ctx.cron will not be available.\n\t */\n\tcronReschedule?: () => void;\n\t/**\n\t * Email pipeline instance for ctx.email.\n\t * If not provided (or no provider configured), ctx.email will be undefined.\n\t */\n\temailPipeline?: EmailPipeline;\n\t/**\n\t * Pre-resolved list of trusted proxy header names (from the runtime\n\t * `EmDashConfig.trustedProxyHeaders` or the env var). Plugin route\n\t * handlers pass this to `extractRequestMeta` so plugins see the same\n\t * client IP the core auth path does.\n\t */\n\ttrustedProxyHeaders?: string[];\n}\n\n/**\n * Factory for creating plugin contexts\n */\nexport class PluginContextFactory {\n\tprivate optionsRepo: OptionsRepository;\n\tprivate db: Kysely<Database>;\n\tprivate storage?: Storage;\n\tprivate getUploadUrl?: (\n\t\tfilename: string,\n\t\tcontentType: string,\n\t) => Promise<{ uploadUrl: string; mediaId: string }>;\n\tprivate site: SiteInfo;\n\tprivate urlHelper: (path: string) => string;\n\tprivate cronReschedule?: () => void;\n\tprivate emailPipeline?: EmailPipeline;\n\n\tconstructor(options: PluginContextFactoryOptions) {\n\t\tthis.db = options.db;\n\t\tthis.optionsRepo = new OptionsRepository(options.db);\n\t\tthis.storage = options.storage;\n\t\tthis.getUploadUrl = options.getUploadUrl;\n\t\tthis.site = createSiteInfo(options.siteInfo ?? {});\n\t\tthis.urlHelper = createUrlHelper(this.site.url);\n\t\tthis.cronReschedule = options.cronReschedule;\n\t\tthis.emailPipeline = options.emailPipeline;\n\t}\n\n\t/**\n\t * Create the unified plugin context\n\t */\n\tcreateContext(plugin: ResolvedPlugin): PluginContext {\n\t\tconst capabilities = new Set(plugin.capabilities);\n\n\t\t// Always available\n\t\tconst kv = createKVAccess(this.optionsRepo, plugin.id);\n\t\tconst log = createLogAccess(plugin.id);\n\t\tconst storage = createStorageAccess(this.db, plugin.id, plugin.storage);\n\n\t\t// Capability-gated: content\n\t\t// Note: capabilities reach this point already normalized to the\n\t\t// canonical names by definePlugin / adaptSandboxEntry. Deprecated\n\t\t// names (\"read:content\", \"write:content\") never appear here.\n\t\tlet content: ContentAccess | ContentAccessWithWrite | undefined;\n\t\tif (capabilities.has(\"content:write\")) {\n\t\t\tcontent = createContentAccessWithWrite(this.db);\n\t\t} else if (capabilities.has(\"content:read\")) {\n\t\t\tcontent = createContentAccess(this.db);\n\t\t}\n\n\t\t// Capability-gated: media\n\t\tlet media: MediaAccess | MediaAccessWithWrite | undefined;\n\t\tif (capabilities.has(\"media:write\") && this.getUploadUrl) {\n\t\t\tmedia = createMediaAccessWithWrite(this.db, this.getUploadUrl, this.storage);\n\t\t} else if (capabilities.has(\"media:read\")) {\n\t\t\tmedia = createMediaAccess(this.db);\n\t\t}\n\n\t\t// Capability-gated: http\n\t\tlet http: HttpAccess | undefined;\n\t\tif (capabilities.has(\"network:request:unrestricted\")) {\n\t\t\thttp = createUnrestrictedHttpAccess(plugin.id);\n\t\t} else if (capabilities.has(\"network:request\")) {\n\t\t\thttp = createHttpAccess(plugin.id, plugin.allowedHosts);\n\t\t}\n\n\t\t// Capability-gated: users\n\t\tlet users: UserAccess | undefined;\n\t\tif (capabilities.has(\"users:read\")) {\n\t\t\tusers = createUserAccess(this.db);\n\t\t}\n\n\t\t// Cron access ��� always available (scoped to plugin), but only if\n\t\t// the runtime provided a reschedule callback (i.e. cron is wired up).\n\t\tlet cron: CronAccess | undefined;\n\t\tif (this.cronReschedule) {\n\t\t\tcron = new CronAccessImpl(this.db, plugin.id, this.cronReschedule);\n\t\t}\n\n\t\t// Email access — requires email:send capability AND a configured provider\n\t\tlet email: EmailAccess | undefined;\n\t\tif (capabilities.has(\"email:send\") && this.emailPipeline?.isAvailable()) {\n\t\t\tconst pipeline = this.emailPipeline;\n\t\t\tconst pluginId = plugin.id;\n\t\t\temail = {\n\t\t\t\tsend: (message) => pipeline.send(message, pluginId),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tplugin: {\n\t\t\t\tid: plugin.id,\n\t\t\t\tversion: plugin.version,\n\t\t\t},\n\t\t\tstorage,\n\t\t\tkv,\n\t\t\tcontent,\n\t\t\tmedia,\n\t\t\thttp,\n\t\t\tlog,\n\t\t\tsite: this.site,\n\t\t\turl: this.urlHelper,\n\t\t\tusers,\n\t\t\tcron,\n\t\t\temail,\n\t\t};\n\t}\n}\n\n/**\n * Create a plugin context for a resolved plugin\n */\nexport function createPluginContext(\n\toptions: PluginContextFactoryOptions,\n\tplugin: ResolvedPlugin,\n): PluginContext {\n\tconst factory = new PluginContextFactory(options);\n\treturn factory.createContext(plugin);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiBA,IAAa,oBAAb,cAAuC,MAAM;CAC5C,YACC,SACA,AAAO,OACP,AAAO,YACN;AACD,QAAM,QAAQ;EAHP;EACA;AAGP,OAAK,OAAO;;;;;;AAOd,SAAgB,cAAc,OAAyC;AACtE,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAO,QAAQ,SAAS,SAAS,SAAS,QAAQ,SAAS,SAAS;;;;;AAMrE,SAAgB,WAAW,OAAsC;AAChE,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAO,QAAQ,SAAS,MAAM,QAAQ,MAAM,GAAG;;;;;AAMhD,SAAgB,mBAAmB,OAA8C;AAChF,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAO,gBAAgB,SAAS,OAAO,MAAM,eAAe;;;;;AAM7D,SAAgB,iBAAiB,SAAgD;CAChF,MAAM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,SAAQ,2BAA2B,KAAK,IAAI,KAAK,cAAc,KAAK,QAAQ;WAClE,aAAa,IAAI,aAAa,CACxC,SAAQ,kBAAkB,KAAK,GAAG;EAInC,IAAI;AACJ,MAAI,aAAa,IAAI,+BAA+B,CACnD,QAAO,6BAA6B,OAAO,GAAG;WACpC,aAAa,IAAI,kBAAkB,CAC7C,QAAO,iBAAiB,OAAO,IAAI,OAAO,aAAa;EAIxD,IAAI;AACJ,MAAI,aAAa,IAAI,aAAa,CACjC,SAAQ,iBAAiB,KAAK,GAAG;EAKlC,IAAI;AACJ,MAAI,KAAK,eACR,QAAO,IAAI,eAAe,KAAK,IAAI,OAAO,IAAI,KAAK,eAAe;EAInE,IAAI;AACJ,MAAI,aAAa,IAAI,aAAa,IAAI,KAAK,eAAe,aAAa,EAAE;GACxE,MAAM,WAAW,KAAK;GACtB,MAAM,WAAW,OAAO;AACxB,WAAQ,EACP,OAAO,YAAY,SAAS,KAAK,SAAS,SAAS,EACnD;;AAGF,SAAO;GACN,QAAQ;IACP,IAAI,OAAO;IACX,SAAS,OAAO;IAChB;GACD;GACA;GACA;GACA;GACA;GACA;GACA,MAAM,KAAK;GACX,KAAK,KAAK;GACV;GACA;GACA;GACA"}
@@ -1,7 +1,7 @@
1
1
  import { t as validateIdentifier } from "./validate-VPnKoIzW.mjs";
2
- import { t as ContentRepository } from "./content-C0ooIs-f.mjs";
3
- import { t as MediaRepository } from "./media-oqRcNiQf.mjs";
4
- import { t as UserRepository } from "./user-D3BD5zdT.mjs";
2
+ import { t as ContentRepository } from "./content-8voQNTXX.mjs";
3
+ import { t as MediaRepository } from "./media-CKQd8AYU.mjs";
4
+ import { t as UserRepository } from "./user-hUSOaIJy.mjs";
5
5
  import { sql } from "kysely";
6
6
 
7
7
  //#region src/api/handlers/dashboard.ts
@@ -102,4 +102,4 @@ async function fetchRecentItems(db, collections) {
102
102
 
103
103
  //#endregion
104
104
  export { handleDashboardStats as t };
105
- //# sourceMappingURL=dashboard-Cqw3ay2X.mjs.map
105
+ //# sourceMappingURL=dashboard-BeaFSPpx.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"dashboard-Cqw3ay2X.mjs","names":[],"sources":["../src/api/handlers/dashboard.ts"],"sourcesContent":["/**\n * Dashboard stats handler\n *\n * Returns summary data for the admin dashboard in a single request:\n * collection content counts, media count, user count, and recent\n * content across all collections.\n */\n\nimport { sql, type Kysely } from \"kysely\";\n\nimport { ContentRepository } from \"../../database/repositories/content.js\";\nimport { MediaRepository } from \"../../database/repositories/media.js\";\nimport { UserRepository } from \"../../database/repositories/user.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { validateIdentifier } from \"../../database/validate.js\";\nimport type { ApiResult } from \"../types.js\";\n\nexport interface CollectionStats {\n\tslug: string;\n\tlabel: string;\n\ttotal: number;\n\tpublished: number;\n\tdraft: number;\n}\n\nexport interface RecentItem {\n\tid: string;\n\tcollection: string;\n\tcollectionLabel: string;\n\ttitle: string;\n\tslug: string | null;\n\tstatus: string;\n\tupdatedAt: string;\n\tauthorId: string | null;\n}\n\nexport interface DashboardStats {\n\tcollections: CollectionStats[];\n\tmediaCount: number;\n\tuserCount: number;\n\trecentItems: RecentItem[];\n}\n\n/**\n * Fetch dashboard statistics.\n *\n * Queries are intentionally lightweight — counts use indexed columns,\n * and recent items are capped at 10.\n */\nexport async function handleDashboardStats(\n\tdb: Kysely<Database>,\n): Promise<ApiResult<DashboardStats>> {\n\ttry {\n\t\t// Discover collections from the system table\n\t\tconst collections = await db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.select([\"slug\", \"label\"])\n\t\t\t.orderBy(\"slug\", \"asc\")\n\t\t\t.execute();\n\n\t\t// Gather per-collection counts in parallel\n\t\tconst contentRepo = new ContentRepository(db);\n\t\tconst collectionStats: CollectionStats[] = await Promise.all(\n\t\t\tcollections.map(async (col) => {\n\t\t\t\tconst stats = await contentRepo.getStats(col.slug);\n\t\t\t\treturn {\n\t\t\t\t\tslug: col.slug,\n\t\t\t\t\tlabel: col.label,\n\t\t\t\t\ttotal: stats.total,\n\t\t\t\t\tpublished: stats.published,\n\t\t\t\t\tdraft: stats.draft,\n\t\t\t\t};\n\t\t\t}),\n\t\t);\n\n\t\t// Media and user counts\n\t\tconst mediaRepo = new MediaRepository(db);\n\t\tconst userRepo = new UserRepository(db);\n\t\tconst [mediaCount, userCount] = await Promise.all([mediaRepo.count(), userRepo.count()]);\n\n\t\t// Recent items across all collections (last 10 updated, any status)\n\t\tconst recentItems = await fetchRecentItems(db, collections);\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tcollections: collectionStats,\n\t\t\t\tmediaCount,\n\t\t\t\tuserCount,\n\t\t\t\trecentItems,\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\"Dashboard stats error:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"DASHBOARD_STATS_ERROR\",\n\t\t\t\tmessage: \"Failed to load dashboard statistics\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/** Raw row shape from the UNION ALL query — all snake_case. */\ninterface RecentItemRow {\n\tid: string;\n\tcollection: string;\n\tcollection_label: string;\n\ttitle: string;\n\tslug: string | null;\n\tstatus: string;\n\tupdated_at: string;\n\tauthor_id: string | null;\n}\n\n/**\n * Fetch the 10 most recently updated items across all collections.\n *\n * Uses UNION ALL over each ec_* table. The query is safe because\n * collection slugs come from the system table and are validated.\n *\n * `title` is not a standard column — it's a user-defined field. We query\n * `_emdash_fields` to discover which collections have one and fall back\n * to `slug` (which is always present) otherwise.\n */\nasync function fetchRecentItems(\n\tdb: Kysely<Database>,\n\tcollections: Array<{ slug: string; label: string }>,\n): Promise<RecentItem[]> {\n\tif (collections.length === 0) return [];\n\n\t// Discover which collections have a \"title\" column\n\tconst titleFields = await db\n\t\t.selectFrom(\"_emdash_fields as f\")\n\t\t.innerJoin(\"_emdash_collections as c\", \"c.id\", \"f.collection_id\")\n\t\t.select([\"c.slug as collection_slug\"])\n\t\t.where(\"f.slug\", \"=\", \"title\")\n\t\t.execute();\n\n\tconst collectionsWithTitle = new Set(titleFields.map((r) => r.collection_slug));\n\n\t// Issue one query per collection in parallel, then merge in JS.\n\t// A single UNION ALL across N collections trips D1's\n\t// SQLITE_LIMIT_COMPOUND_SELECT cap when N is large enough (#895);\n\t// per-collection queries side-step that. Each query fetches at most\n\t// 10 rows, so the merge handles at most N * 10 rows before slicing.\n\tconst perCollection = await Promise.all(\n\t\tcollections.map(async (col) => {\n\t\t\tvalidateIdentifier(col.slug);\n\t\t\tconst table = `ec_${col.slug}`;\n\t\t\tconst hasTitle = collectionsWithTitle.has(col.slug);\n\n\t\t\t// Use title column if it exists, otherwise fall back to slug, id.\n\t\t\t// All output uses snake_case to avoid SQLite quoting issues on D1.\n\t\t\tconst titleExpr = hasTitle ? sql`COALESCE(title, slug, id)` : sql`COALESCE(slug, id)`;\n\n\t\t\tconst result = await sql<RecentItemRow>`\n\t\t\t\tSELECT\n\t\t\t\t\tid,\n\t\t\t\t\t${sql.lit(col.slug)} AS collection,\n\t\t\t\t\t${sql.lit(col.label)} AS collection_label,\n\t\t\t\t\t${titleExpr} AS title,\n\t\t\t\t\tslug,\n\t\t\t\t\tstatus,\n\t\t\t\t\tupdated_at,\n\t\t\t\t\tauthor_id\n\t\t\t\tFROM ${sql.ref(table)}\n\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\tORDER BY updated_at DESC\n\t\t\t\tLIMIT 10\n\t\t\t`.execute(db);\n\t\t\treturn result.rows;\n\t\t}),\n\t);\n\n\t// Merge across collections, sort by updated_at desc, take top 10.\n\tconst merged = perCollection\n\t\t.flat()\n\t\t.toSorted((a, b) => (a.updated_at < b.updated_at ? 1 : a.updated_at > b.updated_at ? -1 : 0))\n\t\t.slice(0, 10);\n\n\t// Map snake_case DB rows to camelCase API shape\n\treturn merged.map((row) => ({\n\t\tid: row.id,\n\t\tcollection: row.collection,\n\t\tcollectionLabel: row.collection_label,\n\t\ttitle: row.title,\n\t\tslug: row.slug,\n\t\tstatus: row.status,\n\t\tupdatedAt: row.updated_at,\n\t\tauthorId: row.author_id,\n\t}));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiDA,eAAsB,qBACrB,IACqC;AACrC,KAAI;EAEH,MAAM,cAAc,MAAM,GACxB,WAAW,sBAAsB,CACjC,OAAO,CAAC,QAAQ,QAAQ,CAAC,CACzB,QAAQ,QAAQ,MAAM,CACtB,SAAS;EAGX,MAAM,cAAc,IAAI,kBAAkB,GAAG;EAC7C,MAAM,kBAAqC,MAAM,QAAQ,IACxD,YAAY,IAAI,OAAO,QAAQ;GAC9B,MAAM,QAAQ,MAAM,YAAY,SAAS,IAAI,KAAK;AAClD,UAAO;IACN,MAAM,IAAI;IACV,OAAO,IAAI;IACX,OAAO,MAAM;IACb,WAAW,MAAM;IACjB,OAAO,MAAM;IACb;IACA,CACF;EAGD,MAAM,YAAY,IAAI,gBAAgB,GAAG;EACzC,MAAM,WAAW,IAAI,eAAe,GAAG;EACvC,MAAM,CAAC,YAAY,aAAa,MAAM,QAAQ,IAAI,CAAC,UAAU,OAAO,EAAE,SAAS,OAAO,CAAC,CAAC;AAKxF,SAAO;GACN,SAAS;GACT,MAAM;IACL,aAAa;IACb;IACA;IACA,aARkB,MAAM,iBAAiB,IAAI,YAAY;IASzD;GACD;UACO,OAAO;AACf,UAAQ,MAAM,0BAA0B,MAAM;AAC9C,SAAO;GACN,SAAS;GACT,OAAO;IACN,MAAM;IACN,SAAS;IACT;GACD;;;;;;;;;;;;;AA0BH,eAAe,iBACd,IACA,aACwB;AACxB,KAAI,YAAY,WAAW,EAAG,QAAO,EAAE;CAGvC,MAAM,cAAc,MAAM,GACxB,WAAW,sBAAsB,CACjC,UAAU,4BAA4B,QAAQ,kBAAkB,CAChE,OAAO,CAAC,4BAA4B,CAAC,CACrC,MAAM,UAAU,KAAK,QAAQ,CAC7B,SAAS;CAEX,MAAM,uBAAuB,IAAI,IAAI,YAAY,KAAK,MAAM,EAAE,gBAAgB,CAAC;AA2C/E,SApCsB,MAAM,QAAQ,IACnC,YAAY,IAAI,OAAO,QAAQ;AAC9B,qBAAmB,IAAI,KAAK;EAC5B,MAAM,QAAQ,MAAM,IAAI;EAKxB,MAAM,YAJW,qBAAqB,IAAI,IAAI,KAAK,GAItB,GAAG,8BAA8B,GAAG;AAiBjE,UAfe,MAAM,GAAkB;;;OAGnC,IAAI,IAAI,IAAI,KAAK,CAAC;OAClB,IAAI,IAAI,IAAI,MAAM,CAAC;OACnB,UAAU;;;;;WAKN,IAAI,IAAI,MAAM,CAAC;;;;KAIrB,QAAQ,GAAG,EACC;GACb,CACF,EAIC,MAAM,CACN,UAAU,GAAG,MAAO,EAAE,aAAa,EAAE,aAAa,IAAI,EAAE,aAAa,EAAE,aAAa,KAAK,EAAG,CAC5F,MAAM,GAAG,GAAG,CAGA,KAAK,SAAS;EAC3B,IAAI,IAAI;EACR,YAAY,IAAI;EAChB,iBAAiB,IAAI;EACrB,OAAO,IAAI;EACX,MAAM,IAAI;EACV,QAAQ,IAAI;EACZ,WAAW,IAAI;EACf,UAAU,IAAI;EACd,EAAE"}
1
+ {"version":3,"file":"dashboard-BeaFSPpx.mjs","names":[],"sources":["../src/api/handlers/dashboard.ts"],"sourcesContent":["/**\n * Dashboard stats handler\n *\n * Returns summary data for the admin dashboard in a single request:\n * collection content counts, media count, user count, and recent\n * content across all collections.\n */\n\nimport { sql, type Kysely } from \"kysely\";\n\nimport { ContentRepository } from \"../../database/repositories/content.js\";\nimport { MediaRepository } from \"../../database/repositories/media.js\";\nimport { UserRepository } from \"../../database/repositories/user.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { validateIdentifier } from \"../../database/validate.js\";\nimport type { ApiResult } from \"../types.js\";\n\nexport interface CollectionStats {\n\tslug: string;\n\tlabel: string;\n\ttotal: number;\n\tpublished: number;\n\tdraft: number;\n}\n\nexport interface RecentItem {\n\tid: string;\n\tcollection: string;\n\tcollectionLabel: string;\n\ttitle: string;\n\tslug: string | null;\n\tstatus: string;\n\tupdatedAt: string;\n\tauthorId: string | null;\n}\n\nexport interface DashboardStats {\n\tcollections: CollectionStats[];\n\tmediaCount: number;\n\tuserCount: number;\n\trecentItems: RecentItem[];\n}\n\n/**\n * Fetch dashboard statistics.\n *\n * Queries are intentionally lightweight — counts use indexed columns,\n * and recent items are capped at 10.\n */\nexport async function handleDashboardStats(\n\tdb: Kysely<Database>,\n): Promise<ApiResult<DashboardStats>> {\n\ttry {\n\t\t// Discover collections from the system table\n\t\tconst collections = await db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.select([\"slug\", \"label\"])\n\t\t\t.orderBy(\"slug\", \"asc\")\n\t\t\t.execute();\n\n\t\t// Gather per-collection counts in parallel\n\t\tconst contentRepo = new ContentRepository(db);\n\t\tconst collectionStats: CollectionStats[] = await Promise.all(\n\t\t\tcollections.map(async (col) => {\n\t\t\t\tconst stats = await contentRepo.getStats(col.slug);\n\t\t\t\treturn {\n\t\t\t\t\tslug: col.slug,\n\t\t\t\t\tlabel: col.label,\n\t\t\t\t\ttotal: stats.total,\n\t\t\t\t\tpublished: stats.published,\n\t\t\t\t\tdraft: stats.draft,\n\t\t\t\t};\n\t\t\t}),\n\t\t);\n\n\t\t// Media and user counts\n\t\tconst mediaRepo = new MediaRepository(db);\n\t\tconst userRepo = new UserRepository(db);\n\t\tconst [mediaCount, userCount] = await Promise.all([mediaRepo.count(), userRepo.count()]);\n\n\t\t// Recent items across all collections (last 10 updated, any status)\n\t\tconst recentItems = await fetchRecentItems(db, collections);\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tcollections: collectionStats,\n\t\t\t\tmediaCount,\n\t\t\t\tuserCount,\n\t\t\t\trecentItems,\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\"Dashboard stats error:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"DASHBOARD_STATS_ERROR\",\n\t\t\t\tmessage: \"Failed to load dashboard statistics\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/** Raw row shape from the UNION ALL query — all snake_case. */\ninterface RecentItemRow {\n\tid: string;\n\tcollection: string;\n\tcollection_label: string;\n\ttitle: string;\n\tslug: string | null;\n\tstatus: string;\n\tupdated_at: string;\n\tauthor_id: string | null;\n}\n\n/**\n * Fetch the 10 most recently updated items across all collections.\n *\n * Uses UNION ALL over each ec_* table. The query is safe because\n * collection slugs come from the system table and are validated.\n *\n * `title` is not a standard column — it's a user-defined field. We query\n * `_emdash_fields` to discover which collections have one and fall back\n * to `slug` (which is always present) otherwise.\n */\nasync function fetchRecentItems(\n\tdb: Kysely<Database>,\n\tcollections: Array<{ slug: string; label: string }>,\n): Promise<RecentItem[]> {\n\tif (collections.length === 0) return [];\n\n\t// Discover which collections have a \"title\" column\n\tconst titleFields = await db\n\t\t.selectFrom(\"_emdash_fields as f\")\n\t\t.innerJoin(\"_emdash_collections as c\", \"c.id\", \"f.collection_id\")\n\t\t.select([\"c.slug as collection_slug\"])\n\t\t.where(\"f.slug\", \"=\", \"title\")\n\t\t.execute();\n\n\tconst collectionsWithTitle = new Set(titleFields.map((r) => r.collection_slug));\n\n\t// Issue one query per collection in parallel, then merge in JS.\n\t// A single UNION ALL across N collections trips D1's\n\t// SQLITE_LIMIT_COMPOUND_SELECT cap when N is large enough (#895);\n\t// per-collection queries side-step that. Each query fetches at most\n\t// 10 rows, so the merge handles at most N * 10 rows before slicing.\n\tconst perCollection = await Promise.all(\n\t\tcollections.map(async (col) => {\n\t\t\tvalidateIdentifier(col.slug);\n\t\t\tconst table = `ec_${col.slug}`;\n\t\t\tconst hasTitle = collectionsWithTitle.has(col.slug);\n\n\t\t\t// Use title column if it exists, otherwise fall back to slug, id.\n\t\t\t// All output uses snake_case to avoid SQLite quoting issues on D1.\n\t\t\tconst titleExpr = hasTitle ? sql`COALESCE(title, slug, id)` : sql`COALESCE(slug, id)`;\n\n\t\t\tconst result = await sql<RecentItemRow>`\n\t\t\t\tSELECT\n\t\t\t\t\tid,\n\t\t\t\t\t${sql.lit(col.slug)} AS collection,\n\t\t\t\t\t${sql.lit(col.label)} AS collection_label,\n\t\t\t\t\t${titleExpr} AS title,\n\t\t\t\t\tslug,\n\t\t\t\t\tstatus,\n\t\t\t\t\tupdated_at,\n\t\t\t\t\tauthor_id\n\t\t\t\tFROM ${sql.ref(table)}\n\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\tORDER BY updated_at DESC\n\t\t\t\tLIMIT 10\n\t\t\t`.execute(db);\n\t\t\treturn result.rows;\n\t\t}),\n\t);\n\n\t// Merge across collections, sort by updated_at desc, take top 10.\n\tconst merged = perCollection\n\t\t.flat()\n\t\t.toSorted((a, b) => (a.updated_at < b.updated_at ? 1 : a.updated_at > b.updated_at ? -1 : 0))\n\t\t.slice(0, 10);\n\n\t// Map snake_case DB rows to camelCase API shape\n\treturn merged.map((row) => ({\n\t\tid: row.id,\n\t\tcollection: row.collection,\n\t\tcollectionLabel: row.collection_label,\n\t\ttitle: row.title,\n\t\tslug: row.slug,\n\t\tstatus: row.status,\n\t\tupdatedAt: row.updated_at,\n\t\tauthorId: row.author_id,\n\t}));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiDA,eAAsB,qBACrB,IACqC;AACrC,KAAI;EAEH,MAAM,cAAc,MAAM,GACxB,WAAW,sBAAsB,CACjC,OAAO,CAAC,QAAQ,QAAQ,CAAC,CACzB,QAAQ,QAAQ,MAAM,CACtB,SAAS;EAGX,MAAM,cAAc,IAAI,kBAAkB,GAAG;EAC7C,MAAM,kBAAqC,MAAM,QAAQ,IACxD,YAAY,IAAI,OAAO,QAAQ;GAC9B,MAAM,QAAQ,MAAM,YAAY,SAAS,IAAI,KAAK;AAClD,UAAO;IACN,MAAM,IAAI;IACV,OAAO,IAAI;IACX,OAAO,MAAM;IACb,WAAW,MAAM;IACjB,OAAO,MAAM;IACb;I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AS;EAC3B,IAAI,IAAI;EACR,YAAY,IAAI;EAChB,iBAAiB,IAAI;EACrB,OAAO,IAAI;EACX,MAAM,IAAI;EACV,QAAQ,IAAI;EACZ,WAAW,IAAI;EACf,UAAU,IAAI;EACd,EAAE"}
@@ -1,4 +1,4 @@
1
1
  import "../types-DaqNzqVt.mjs";
2
- import { i as runMigrations, n as getMigrationStatus, r as rollbackMigration, t as MigrationStatus } from "../runner-CNHRo1mT.mjs";
2
+ import { i as runMigrations, n as getMigrationStatus, r as rollbackMigration, t as MigrationStatus } from "../runner-DSQBurMS.mjs";
3
3
  import { a as SqliteConfig, c as sqlite, i as PostgresConfig, n as DatabaseDialectType, o as libsql, r as LibsqlConfig, s as postgres, t as DatabaseDescriptor } from "../adapters-C4yd_UJR.mjs";
4
4
  export { type DatabaseDescriptor, type DatabaseDialectType, type LibsqlConfig, type MigrationStatus, type PostgresConfig, type SqliteConfig, getMigrationStatus, libsql, postgres, rollbackMigration, runMigrations, sqlite };
package/dist/db/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { n as rollbackMigration, r as runMigrations, t as getMigrationStatus } from "../runner-CGlojznK.mjs";
1
+ import { n as rollbackMigration, r as runMigrations, t as getMigrationStatus } from "../runner-Drnvs96u.mjs";
2
2
  import "../dialect-helpers-BKCvISIQ.mjs";
3
3
 
4
4
  //#region src/db/adapters.ts
@@ -1,5 +1,5 @@
1
- import BetterSqlite3 from "better-sqlite3";
2
1
  import { SqliteDialect } from "kysely";
2
+ import BetterSqlite3 from "better-sqlite3";
3
3
 
4
4
  //#region src/db/sqlite.ts
5
5
  /**
@@ -22,6 +22,18 @@ function messageOf(error) {
22
22
  return "";
23
23
  }
24
24
  /**
25
+ * Returns true when `error` is a "column does not exist" error.
26
+ * Used to handle where filters that reference non-existent field names
27
+ * gracefully (return empty results) instead of propagating a SQL error.
28
+ */
29
+ function isMissingColumnError(error) {
30
+ const message = messageOf(error);
31
+ if (!message) return false;
32
+ if (message.includes("no such column")) return true;
33
+ if (message.includes("does not exist") && message.includes("column") && !message.includes("relation")) return true;
34
+ return false;
35
+ }
36
+ /**
25
37
  * Returns true when `error` is a "table does not exist" error across the
26
38
  * dialects EmDash supports (D1/SQLite and PostgreSQL). Used by runtime
27
39
  * probes to treat pre-migration databases as empty without logging a scary
@@ -37,5 +49,5 @@ function isMissingTableError(error) {
37
49
  }
38
50
 
39
51
  //#endregion
40
- export { isMissingTableError as t };
41
- //# sourceMappingURL=db-errors-CGN9kJfo.mjs.map
52
+ export { isMissingTableError as n, isMissingColumnError as t };
53
+ //# sourceMappingURL=db-errors-BiYqoX-n.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"db-errors-BiYqoX-n.mjs","names":[],"sources":["../src/utils/db-errors.ts"],"sourcesContent":["/**\n * Shared detection helpers for database-layer error messages.\n *\n * Different SQL dialects phrase \"table or relation does not exist\" differently:\n *\n * - SQLite / D1: \"no such table: foo\"\n * - PostgreSQL: 'relation \"foo\" does not exist'\n * 'table \"foo\" does not exist'\n * - MySQL (future): \"Table 'db.foo' doesn't exist\"\n *\n * Runtime code paths that short-circuit on missing tables (pre-migration\n * probes, optional feature tables, etc.) should use these helpers rather\n * than hand-rolling string matches per call-site.\n */\n\n/**\n * Extract a lowercase error message from any unknown value, safely.\n */\nfunction messageOf(error: unknown): string {\n\tif (error instanceof Error) return error.message.toLowerCase();\n\tif (typeof error === \"string\") return error.toLowerCase();\n\treturn \"\";\n}\n\n/**\n * Returns true when `error` is a \"column does not exist\" error.\n * Used to handle where filters that reference non-existent field names\n * gracefully (return empty results) instead of propagating a SQL error.\n */\nexport function isMissingColumnError(error: unknown): boolean {\n\tconst message = messageOf(error);\n\tif (!message) return false;\n\n\t// SQLite / D1: \"no such column: foo\"\n\tif (message.includes(\"no such column\")) return true;\n\n\t// PostgreSQL SQLSTATE 42703: 'column \"foo\" does not exist'\n\t// Exclude \"relation\" to avoid false positives on table names containing \"column\"\n\tif (\n\t\tmessage.includes(\"does not exist\") &&\n\t\tmessage.includes(\"column\") &&\n\t\t!message.includes(\"relation\")\n\t)\n\t\treturn true;\n\n\treturn false;\n}\n\n/**\n * Returns true when `error` is a \"table does not exist\" error across the\n * dialects EmDash supports (D1/SQLite and PostgreSQL). Used by runtime\n * probes to treat pre-migration databases as empty without logging a scary\n * warning, while still propagating unrelated errors (permissions, connection\n * loss, syntax issues) to callers.\n */\nexport function isMissingTableError(error: unknown): boolean {\n\tconst message = messageOf(error);\n\tif (!message) return false;\n\n\t// SQLite / D1\n\tif (message.includes(\"no such table\")) return true;\n\n\t// PostgreSQL (and some MySQL variants): \"relation ... does not exist\" /\n\t// \"table ... does not exist\" / \"doesn't exist\".\n\tif (message.includes(\"does not exist\") || message.includes(\"doesn't exist\")) {\n\t\treturn message.includes(\"relation\") || message.includes(\"table\");\n\t}\n\n\treturn false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,SAAS,UAAU,OAAwB;AAC1C,KAAI,iBAAiB,MAAO,QAAO,MAAM,QAAQ,aAAa;AAC9D,KAAI,OAAO,UAAU,SAAU,QAAO,MAAM,aAAa;AACzD,QAAO;;;;;;;AAQR,SAAgB,qBAAqB,OAAyB;CAC7D,MAAM,UAAU,UAAU,MAAM;AAChC,KAAI,CAAC,QAAS,QAAO;AAGrB,KAAI,QAAQ,SAAS,iBAAiB,CAAE,QAAO;AAI/C,KACC,QAAQ,SAAS,iBAAiB,IAClC,QAAQ,SAAS,SAAS,IAC1B,CAAC,QAAQ,SAAS,WAAW,CAE7B,QAAO;AAER,QAAO;;;;;;;;;AAUR,SAAgB,oBAAoB,OAAyB;CAC5D,MAAM,UAAU,UAAU,MAAM;AAChC,KAAI,CAAC,QAAS,QAAO;AAGrB,KAAI,QAAQ,SAAS,gBAAgB,CAAE,QAAO;AAI9C,KAAI,QAAQ,SAAS,iBAAiB,IAAI,QAAQ,SAAS,gBAAgB,CAC1E,QAAO,QAAQ,SAAS,WAAW,IAAI,QAAQ,SAAS,QAAQ;AAGjE,QAAO"}
@@ -1,4 +1,4 @@
1
- import { n as InvalidCursorError } from "./types-ByV5sgsv.mjs";
1
+ import { n as InvalidCursorError } from "./types-B0bmgwMG.mjs";
2
2
 
3
3
  //#region src/api/errors.ts
4
4
  /**
@@ -184,6 +184,7 @@ const ErrorCode = {
184
184
  AGGREGATOR_NOT_FOUND: "AGGREGATOR_NOT_FOUND",
185
185
  CAPABILITY_ESCALATION: "CAPABILITY_ESCALATION",
186
186
  ROUTE_VISIBILITY_ESCALATION: "ROUTE_VISIBILITY_ESCALATION",
187
+ ENV_INCOMPATIBLE: "ENV_INCOMPATIBLE",
187
188
  INSTALL_FAILED: "INSTALL_FAILED",
188
189
  UNINSTALL_FAILED: "UNINSTALL_FAILED",
189
190
  SEARCH_FAILED: "SEARCH_FAILED",
@@ -339,7 +340,8 @@ function mapErrorStatus(code) {
339
340
  case ErrorCode.PLUGIN_ID_CONFLICT:
340
341
  case ErrorCode.ALREADY_INSTALLED:
341
342
  case ErrorCode.ALREADY_CONFIGURED:
342
- case ErrorCode.ALREADY_UP_TO_DATE: return 409;
343
+ case ErrorCode.ALREADY_UP_TO_DATE:
344
+ case ErrorCode.ENV_INCOMPATIBLE: return 409;
343
345
  case ErrorCode.TOKEN_EXPIRED: return 410;
344
346
  case ErrorCode.CHECKSUM_MISMATCH:
345
347
  case ErrorCode.INVALID_BUNDLE:
@@ -442,4 +444,4 @@ function unwrapResult(result, successStatus = 200) {
442
444
 
443
445
  //#endregion
444
446
  export { unwrapResult as a, requireDb as i, apiSuccess as n, mapErrorStatus as o, handleError as r, apiError as t };
445
- //# sourceMappingURL=error-CPh_8eLq.mjs.map
447
+ //# sourceMappingURL=error-ChfADBuu.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-ChfADBuu.mjs","names":[],"sources":["../src/api/errors.ts","../src/api/error.ts"],"sourcesContent":["/**\n * Typed error codes and status mapping for the EmDash REST API.\n *\n * All handler-level and route-level error codes are defined here.\n * Routes and handlers should import error codes from this module\n * instead of using ad-hoc strings.\n */\n\nexport const ErrorCode = {\n\t// Shared (used across domains)\n\tNOT_FOUND: \"NOT_FOUND\",\n\tVALIDATION_ERROR: \"VALIDATION_ERROR\",\n\tINVALID_INPUT: \"INVALID_INPUT\",\n\tINVALID_JSON: \"INVALID_JSON\",\n\tINVALID_CURSOR: \"INVALID_CURSOR\",\n\tCONFLICT: \"CONFLICT\",\n\tSLUG_CONFLICT: \"SLUG_CONFLICT\",\n\tNOT_CONFIGURED: \"NOT_CONFIGURED\",\n\tUNAUTHORIZED: \"UNAUTHORIZED\",\n\tFORBIDDEN: \"FORBIDDEN\",\n\tRATE_LIMITED: \"RATE_LIMITED\",\n\tNOT_AUTHENTICATED: \"NOT_AUTHENTICATED\",\n\tNOT_IMPLEMENTED: \"NOT_IMPLEMENTED\",\n\tNOT_SUPPORTED: \"NOT_SUPPORTED\",\n\tMISSING_PARAM: \"MISSING_PARAM\",\n\tCSRF_REJECTED: \"CSRF_REJECTED\",\n\n\t// Content\n\tCONTENT_CREATE_ERROR: \"CONTENT_CREATE_ERROR\",\n\tCONTENT_UPDATE_ERROR: \"CONTENT_UPDATE_ERROR\",\n\tCONTENT_DELETE_ERROR: \"CONTENT_DELETE_ERROR\",\n\tCONTENT_LIST_ERROR: \"CONTENT_LIST_ERROR\",\n\tCONTENT_GET_ERROR: \"CONTENT_GET_ERROR\",\n\tCONTENT_DUPLICATE_ERROR: \"CONTENT_DUPLICATE_ERROR\",\n\tCONTENT_RESTORE_ERROR: \"CONTENT_RESTORE_ERROR\",\n\tCONTENT_PUBLISH_ERROR: \"CONTENT_PUBLISH_ERROR\",\n\tCONTENT_UNPUBLISH_ERROR: \"CONTENT_UNPUBLISH_ERROR\",\n\tCONTENT_SCHEDULE_ERROR: \"CONTENT_SCHEDULE_ERROR\",\n\tCONTENT_UNSCHEDULE_ERROR: \"CONTENT_UNSCHEDULE_ERROR\",\n\tCONTENT_DISCARD_DRAFT_ERROR: \"CONTENT_DISCARD_DRAFT_ERROR\",\n\tCONTENT_COMPARE_ERROR: \"CONTENT_COMPARE_ERROR\",\n\tCONTENT_TRANSLATIONS_ERROR: \"CONTENT_TRANSLATIONS_ERROR\",\n\tCONTENT_COUNT_ERROR: \"CONTENT_COUNT_ERROR\",\n\n\t// Revisions\n\tREVISION_LIST_ERROR: \"REVISION_LIST_ERROR\",\n\tREVISION_GET_ERROR: \"REVISION_GET_ERROR\",\n\tREVISION_RESTORE_ERROR: \"REVISION_RESTORE_ERROR\",\n\tINVALID_REVISION: \"INVALID_REVISION\",\n\n\t// Schema\n\tSCHEMA_LIST_ERROR: \"SCHEMA_LIST_ERROR\",\n\tSCHEMA_GET_ERROR: \"SCHEMA_GET_ERROR\",\n\tSCHEMA_CREATE_ERROR: \"SCHEMA_CREATE_ERROR\",\n\tSCHEMA_UPDATE_ERROR: \"SCHEMA_UPDATE_ERROR\",\n\tSCHEMA_DELETE_ERROR: \"SCHEMA_DELETE_ERROR\",\n\tSCHEMA_EXPORT_ERROR: \"SCHEMA_EXPORT_ERROR\",\n\tSCHEMA_FIELD_LIST_ERROR: \"SCHEMA_FIELD_LIST_ERROR\",\n\tSCHEMA_FIELD_GET_ERROR: \"SCHEMA_FIELD_GET_ERROR\",\n\tSCHEMA_FIELD_CREATE_ERROR: \"SCHEMA_FIELD_CREATE_ERROR\",\n\tSCHEMA_FIELD_UPDATE_ERROR: \"SCHEMA_FIELD_UPDATE_ERROR\",\n\tSCHEMA_FIELD_DELETE_ERROR: \"SCHEMA_FIELD_DELETE_ERROR\",\n\tSCHEMA_FIELD_REORDER_ERROR: \"SCHEMA_FIELD_REORDER_ERROR\",\n\tORPHAN_LIST_ERROR: \"ORPHAN_LIST_ERROR\",\n\tORPHAN_REGISTER_ERROR: \"ORPHAN_REGISTER_ERROR\",\n\tCOLLECTION_EXISTS: \"COLLECTION_EXISTS\",\n\tCOLLECTION_NOT_FOUND: \"COLLECTION_NOT_FOUND\",\n\tTABLE_NOT_FOUND: \"TABLE_NOT_FOUND\",\n\tFIELD_EXISTS: \"FIELD_EXISTS\",\n\tRESERVED_SLUG: \"RESERVED_SLUG\",\n\tINVALID_SLUG: \"INVALID_SLUG\",\n\tCREATE_FAILED: \"CREATE_FAILED\",\n\tUPDATE_FAILED: \"UPDATE_FAILED\",\n\tREGISTER_FAILED: \"REGISTER_FAILED\",\n\n\t// Media\n\tMEDIA_LIST_ERROR: \"MEDIA_LIST_ERROR\",\n\tMEDIA_GET_ERROR: \"MEDIA_GET_ERROR\",\n\tMEDIA_CREATE_ERROR: \"MEDIA_CREATE_ERROR\",\n\tMEDIA_UPDATE_ERROR: \"MEDIA_UPDATE_ERROR\",\n\tMEDIA_DELETE_ERROR: \"MEDIA_DELETE_ERROR\",\n\tNO_STORAGE: \"NO_STORAGE\",\n\tNO_FILE: \"NO_FILE\",\n\tINVALID_TYPE: \"INVALID_TYPE\",\n\tUPLOAD_ERROR: \"UPLOAD_ERROR\",\n\tUPLOAD_URL_ERROR: \"UPLOAD_URL_ERROR\",\n\tCONFIRM_ERROR: \"CONFIRM_ERROR\",\n\tCONFIRM_FAILED: \"CONFIRM_FAILED\",\n\tFILE_NOT_FOUND: \"FILE_NOT_FOUND\",\n\tINVALID_STATE: \"INVALID_STATE\",\n\tFILE_SERVE_ERROR: \"FILE_SERVE_ERROR\",\n\tSTORAGE_NOT_CONFIGURED: \"STORAGE_NOT_CONFIGURED\",\n\tPROVIDER_LIST_ERROR: \"PROVIDER_LIST_ERROR\",\n\tPROVIDER_UPLOAD_ERROR: \"PROVIDER_UPLOAD_ERROR\",\n\tPROVIDER_GET_ERROR: \"PROVIDER_GET_ERROR\",\n\tPROVIDER_DELETE_ERROR: \"PROVIDER_DELETE_ERROR\",\n\n\t// Comments\n\tCOMMENT_LIST_ERROR: \"COMMENT_LIST_ERROR\",\n\tCOMMENT_GET_ERROR: \"COMMENT_GET_ERROR\",\n\tCOMMENT_STATUS_ERROR: \"COMMENT_STATUS_ERROR\",\n\tCOMMENT_DELETE_ERROR: \"COMMENT_DELETE_ERROR\",\n\tCOMMENT_BULK_ERROR: \"COMMENT_BULK_ERROR\",\n\tCOMMENT_INBOX_ERROR: \"COMMENT_INBOX_ERROR\",\n\tCOMMENT_COUNTS_ERROR: \"COMMENT_COUNTS_ERROR\",\n\tCOMMENT_CREATE_ERROR: \"COMMENT_CREATE_ERROR\",\n\tCOMMENTS_DISABLED: \"COMMENTS_DISABLED\",\n\tCOMMENTS_CLOSED: \"COMMENTS_CLOSED\",\n\tCOMMENT_REJECTED: \"COMMENT_REJECTED\",\n\n\t// Auth\n\tACCOUNT_DISABLED: \"ACCOUNT_DISABLED\",\n\tADMIN_EXISTS: \"ADMIN_EXISTS\",\n\tSETUP_COMPLETE: \"SETUP_COMPLETE\",\n\tCREDENTIAL_EXISTS: \"CREDENTIAL_EXISTS\",\n\tCHALLENGE_EXPIRED: \"CHALLENGE_EXPIRED\",\n\tPASSKEY_REGISTER_ERROR: \"PASSKEY_REGISTER_ERROR\",\n\tPASSKEY_REGISTER_OPTIONS_ERROR: \"PASSKEY_REGISTER_OPTIONS_ERROR\",\n\tPASSKEY_OPTIONS_ERROR: \"PASSKEY_OPTIONS_ERROR\",\n\tPASSKEY_VERIFY_ERROR: \"PASSKEY_VERIFY_ERROR\",\n\tPASSKEY_LIST_ERROR: \"PASSKEY_LIST_ERROR\",\n\tPASSKEY_RENAME_ERROR: \"PASSKEY_RENAME_ERROR\",\n\tPASSKEY_DELETE_ERROR: \"PASSKEY_DELETE_ERROR\",\n\tPASSKEY_LIMIT: \"PASSKEY_LIMIT\",\n\tLAST_PASSKEY: \"LAST_PASSKEY\",\n\tLOGOUT_ERROR: \"LOGOUT_ERROR\",\n\tSELF_ROLE_CHANGE: \"SELF_ROLE_CHANGE\",\n\tEMAIL_IN_USE: \"EMAIL_IN_USE\",\n\tEMAIL_NOT_CONFIGURED: \"EMAIL_NOT_CONFIGURED\",\n\tUSER_EXISTS: \"USER_EXISTS\",\n\tINVALID_TOKEN: \"INVALID_TOKEN\",\n\tTOKEN_EXPIRED: \"TOKEN_EXPIRED\",\n\tDOMAIN_NOT_ALLOWED: \"DOMAIN_NOT_ALLOWED\",\n\tINVITE_CREATE_ERROR: \"INVITE_CREATE_ERROR\",\n\tINVITE_VALIDATE_ERROR: \"INVITE_VALIDATE_ERROR\",\n\tINVITE_COMPLETE_ERROR: \"INVITE_COMPLETE_ERROR\",\n\tSIGNUP_VERIFY_ERROR: \"SIGNUP_VERIFY_ERROR\",\n\tSIGNUP_COMPLETE_ERROR: \"SIGNUP_COMPLETE_ERROR\",\n\tRECOVERY_SEND_ERROR: \"RECOVERY_SEND_ERROR\",\n\tUSER_LIST_ERROR: \"USER_LIST_ERROR\",\n\tUSER_DETAIL_ERROR: \"USER_DETAIL_ERROR\",\n\tUSER_UPDATE_ERROR: \"USER_UPDATE_ERROR\",\n\tUSER_DISABLE_ERROR: \"USER_DISABLE_ERROR\",\n\tUSER_ENABLE_ERROR: \"USER_ENABLE_ERROR\",\n\n\t// OAuth (internal codes -- distinct from RFC OAuthErrorCode)\n\tUNSUPPORTED_RESPONSE_TYPE: \"UNSUPPORTED_RESPONSE_TYPE\",\n\tINVALID_REDIRECT_URI: \"INVALID_REDIRECT_URI\",\n\tINVALID_CLIENT: \"INVALID_CLIENT\",\n\tINVALID_SCOPE: \"INVALID_SCOPE\",\n\tAUTHORIZATION_ERROR: \"AUTHORIZATION_ERROR\",\n\tINVALID_GRANT: \"INVALID_GRANT\",\n\tUNSUPPORTED_GRANT_TYPE: \"UNSUPPORTED_GRANT_TYPE\",\n\tINVALID_CODE: \"INVALID_CODE\",\n\tEXPIRED_CODE: \"EXPIRED_CODE\",\n\tINSUFFICIENT_ROLE: \"INSUFFICIENT_ROLE\",\n\tINSUFFICIENT_SCOPE: \"INSUFFICIENT_SCOPE\",\n\tINSUFFICIENT_PERMISSIONS: \"INSUFFICIENT_PERMISSIONS\",\n\tTOKEN_EXCHANGE_ERROR: \"TOKEN_EXCHANGE_ERROR\",\n\tTOKEN_REFRESH_ERROR: \"TOKEN_REFRESH_ERROR\",\n\tTOKEN_REVOKE_ERROR: \"TOKEN_REVOKE_ERROR\",\n\tTOKEN_CREATE_ERROR: \"TOKEN_CREATE_ERROR\",\n\tTOKEN_LIST_ERROR: \"TOKEN_LIST_ERROR\",\n\tTOKEN_ERROR: \"TOKEN_ERROR\",\n\tDEVICE_CODE_ERROR: \"DEVICE_CODE_ERROR\",\n\tAUTHORIZE_ERROR: \"AUTHORIZE_ERROR\",\n\tCLIENT_LIST_ERROR: \"CLIENT_LIST_ERROR\",\n\tCLIENT_GET_ERROR: \"CLIENT_GET_ERROR\",\n\tCLIENT_CREATE_ERROR: \"CLIENT_CREATE_ERROR\",\n\tCLIENT_UPDATE_ERROR: \"CLIENT_UPDATE_ERROR\",\n\tCLIENT_DELETE_ERROR: \"CLIENT_DELETE_ERROR\",\n\n\t// Allowed domains\n\tDOMAIN_LIST_ERROR: \"DOMAIN_LIST_ERROR\",\n\tDOMAIN_CREATE_ERROR: \"DOMAIN_CREATE_ERROR\",\n\tDOMAIN_UPDATE_ERROR: \"DOMAIN_UPDATE_ERROR\",\n\tDOMAIN_DELETE_ERROR: \"DOMAIN_DELETE_ERROR\",\n\n\t// Plugins / Marketplace\n\tPLUGIN_LIST_ERROR: \"PLUGIN_LIST_ERROR\",\n\tPLUGIN_GET_ERROR: \"PLUGIN_GET_ERROR\",\n\tPLUGIN_ENABLE_ERROR: \"PLUGIN_ENABLE_ERROR\",\n\tPLUGIN_DISABLE_ERROR: \"PLUGIN_DISABLE_ERROR\",\n\tPLUGIN_ID_CONFLICT: \"PLUGIN_ID_CONFLICT\",\n\tMARKETPLACE_NOT_CONFIGURED: \"MARKETPLACE_NOT_CONFIGURED\",\n\tMARKETPLACE_UNAVAILABLE: \"MARKETPLACE_UNAVAILABLE\",\n\tMARKETPLACE_ERROR: \"MARKETPLACE_ERROR\",\n\tSANDBOX_NOT_AVAILABLE: \"SANDBOX_NOT_AVAILABLE\",\n\tALREADY_INSTALLED: \"ALREADY_INSTALLED\",\n\tALREADY_UP_TO_DATE: \"ALREADY_UP_TO_DATE\",\n\tNO_VERSION: \"NO_VERSION\",\n\tMANIFEST_MISMATCH: \"MANIFEST_MISMATCH\",\n\tMANIFEST_VERSION_MISMATCH: \"MANIFEST_VERSION_MISMATCH\",\n\tAUDIT_FAILED: \"AUDIT_FAILED\",\n\tCHECKSUM_MISMATCH: \"CHECKSUM_MISMATCH\",\n\tINVALID_BUNDLE: \"INVALID_BUNDLE\",\n\tBUNDLE_EXTRACT_FAILED: \"BUNDLE_EXTRACT_FAILED\",\n\tBUNDLE_DOWNLOAD_FAILED: \"BUNDLE_DOWNLOAD_FAILED\",\n\tAGGREGATOR_RESPONSE_INVALID: \"AGGREGATOR_RESPONSE_INVALID\",\n\tAGGREGATOR_HTTP_ERROR: \"AGGREGATOR_HTTP_ERROR\",\n\tAGGREGATOR_NOT_FOUND: \"AGGREGATOR_NOT_FOUND\",\n\tCAPABILITY_ESCALATION: \"CAPABILITY_ESCALATION\",\n\tROUTE_VISIBILITY_ESCALATION: \"ROUTE_VISIBILITY_ESCALATION\",\n\tENV_INCOMPATIBLE: \"ENV_INCOMPATIBLE\",\n\tINSTALL_FAILED: \"INSTALL_FAILED\",\n\tUNINSTALL_FAILED: \"UNINSTALL_FAILED\",\n\tSEARCH_FAILED: \"SEARCH_FAILED\",\n\tGET_PLUGIN_FAILED: \"GET_PLUGIN_FAILED\",\n\tGET_THEME_FAILED: \"GET_THEME_FAILED\",\n\tTHEME_SEARCH_FAILED: \"THEME_SEARCH_FAILED\",\n\tUPDATE_CHECK_FAILED: \"UPDATE_CHECK_FAILED\",\n\tEXCLUSIVE_HOOKS_LIST_ERROR: \"EXCLUSIVE_HOOKS_LIST_ERROR\",\n\tEXCLUSIVE_HOOK_SET_ERROR: \"EXCLUSIVE_HOOK_SET_ERROR\",\n\n\t// Menus\n\tMENU_LIST_ERROR: \"MENU_LIST_ERROR\",\n\tMENU_CREATE_ERROR: \"MENU_CREATE_ERROR\",\n\tMENU_GET_ERROR: \"MENU_GET_ERROR\",\n\tMENU_UPDATE_ERROR: \"MENU_UPDATE_ERROR\",\n\tMENU_DELETE_ERROR: \"MENU_DELETE_ERROR\",\n\tMENU_ITEM_CREATE_ERROR: \"MENU_ITEM_CREATE_ERROR\",\n\tMENU_ITEM_UPDATE_ERROR: \"MENU_ITEM_UPDATE_ERROR\",\n\tMENU_ITEM_DELETE_ERROR: \"MENU_ITEM_DELETE_ERROR\",\n\tMENU_REORDER_ERROR: \"MENU_REORDER_ERROR\",\n\t// Returned when a menu name resolves to multiple locale variants and\n\t// the caller did not pass `locale` to disambiguate. (name, locale) is\n\t// unique, so this only fires for omitted-locale lookups.\n\tAMBIGUOUS_LOCALE: \"AMBIGUOUS_LOCALE\",\n\n\t// Taxonomies\n\tTAXONOMY_LIST_ERROR: \"TAXONOMY_LIST_ERROR\",\n\tTAXONOMY_CREATE_ERROR: \"TAXONOMY_CREATE_ERROR\",\n\tTERM_LIST_ERROR: \"TERM_LIST_ERROR\",\n\tTERM_CREATE_ERROR: \"TERM_CREATE_ERROR\",\n\tTERM_GET_ERROR: \"TERM_GET_ERROR\",\n\tTERM_UPDATE_ERROR: \"TERM_UPDATE_ERROR\",\n\tTERM_DELETE_ERROR: \"TERM_DELETE_ERROR\",\n\tTERMS_GET_ERROR: \"TERMS_GET_ERROR\",\n\tTERMS_SET_ERROR: \"TERMS_SET_ERROR\",\n\n\t// Sections\n\tSECTION_LIST_ERROR: \"SECTION_LIST_ERROR\",\n\tSECTION_CREATE_ERROR: \"SECTION_CREATE_ERROR\",\n\tSECTION_GET_ERROR: \"SECTION_GET_ERROR\",\n\tSECTION_UPDATE_ERROR: \"SECTION_UPDATE_ERROR\",\n\tSECTION_DELETE_ERROR: \"SECTION_DELETE_ERROR\",\n\n\t// Redirects\n\tREDIRECT_LIST_ERROR: \"REDIRECT_LIST_ERROR\",\n\tREDIRECT_CREATE_ERROR: \"REDIRECT_CREATE_ERROR\",\n\tREDIRECT_GET_ERROR: \"REDIRECT_GET_ERROR\",\n\tREDIRECT_UPDATE_ERROR: \"REDIRECT_UPDATE_ERROR\",\n\tREDIRECT_DELETE_ERROR: \"REDIRECT_DELETE_ERROR\",\n\tNOT_FOUND_LIST_ERROR: \"NOT_FOUND_LIST_ERROR\",\n\tNOT_FOUND_SUMMARY_ERROR: \"NOT_FOUND_SUMMARY_ERROR\",\n\tNOT_FOUND_CLEAR_ERROR: \"NOT_FOUND_CLEAR_ERROR\",\n\tNOT_FOUND_PRUNE_ERROR: \"NOT_FOUND_PRUNE_ERROR\",\n\n\t// Widgets\n\tWIDGET_AREA_LIST_ERROR: \"WIDGET_AREA_LIST_ERROR\",\n\tWIDGET_AREA_CREATE_ERROR: \"WIDGET_AREA_CREATE_ERROR\",\n\tWIDGET_AREA_GET_ERROR: \"WIDGET_AREA_GET_ERROR\",\n\tWIDGET_AREA_DELETE_ERROR: \"WIDGET_AREA_DELETE_ERROR\",\n\tWIDGET_CREATE_ERROR: \"WIDGET_CREATE_ERROR\",\n\tWIDGET_UPDATE_ERROR: \"WIDGET_UPDATE_ERROR\",\n\tWIDGET_DELETE_ERROR: \"WIDGET_DELETE_ERROR\",\n\tWIDGET_REORDER_ERROR: \"WIDGET_REORDER_ERROR\",\n\tWIDGET_COMPONENTS_ERROR: \"WIDGET_COMPONENTS_ERROR\",\n\n\t// Setup\n\tALREADY_CONFIGURED: \"ALREADY_CONFIGURED\",\n\tINVALID_SEED: \"INVALID_SEED\",\n\tINVALID_REDIRECT: \"INVALID_REDIRECT\",\n\tSETUP_ERROR: \"SETUP_ERROR\",\n\tSETUP_STATUS_ERROR: \"SETUP_STATUS_ERROR\",\n\tSETUP_ADMIN_ERROR: \"SETUP_ADMIN_ERROR\",\n\tSETUP_VERIFY_ERROR: \"SETUP_VERIFY_ERROR\",\n\tDEV_BYPASS_ERROR: \"DEV_BYPASS_ERROR\",\n\tDEV_RESET_ERROR: \"DEV_RESET_ERROR\",\n\tMIGRATION_ERROR: \"MIGRATION_ERROR\",\n\tSEED_ERROR: \"SEED_ERROR\",\n\n\t// Settings\n\tSETTINGS_READ_ERROR: \"SETTINGS_READ_ERROR\",\n\tSETTINGS_UPDATE_ERROR: \"SETTINGS_UPDATE_ERROR\",\n\tEMAIL_SETTINGS_READ_ERROR: \"EMAIL_SETTINGS_READ_ERROR\",\n\tEMAIL_TEST_ERROR: \"EMAIL_TEST_ERROR\",\n\n\t// Search\n\tSEARCH_ERROR: \"SEARCH_ERROR\",\n\tSTATS_ERROR: \"STATS_ERROR\",\n\tSUGGESTION_ERROR: \"SUGGESTION_ERROR\",\n\tREBUILD_ERROR: \"REBUILD_ERROR\",\n\n\t// Import\n\tWXR_ANALYZE_ERROR: \"WXR_ANALYZE_ERROR\",\n\tWXR_PREPARE_ERROR: \"WXR_PREPARE_ERROR\",\n\tWXR_IMPORT_ERROR: \"WXR_IMPORT_ERROR\",\n\tIMPORT_ERROR: \"IMPORT_ERROR\",\n\tREWRITE_ERROR: \"REWRITE_ERROR\",\n\tWP_PLUGIN_ANALYZE_ERROR: \"WP_PLUGIN_ANALYZE_ERROR\",\n\tWP_PLUGIN_IMPORT_ERROR: \"WP_PLUGIN_IMPORT_ERROR\",\n\tSSRF_BLOCKED: \"SSRF_BLOCKED\",\n\tPROBE_ERROR: \"PROBE_ERROR\",\n\n\t// Dashboard\n\tDASHBOARD_ERROR: \"DASHBOARD_ERROR\",\n\tDASHBOARD_STATS_ERROR: \"DASHBOARD_STATS_ERROR\",\n\n\t// Misc\n\tSNAPSHOT_ERROR: \"SNAPSHOT_ERROR\",\n\tTYPEGEN_ERROR: \"TYPEGEN_ERROR\",\n\tSITEMAP_ERROR: \"SITEMAP_ERROR\",\n\tNO_DB: \"NO_DB\",\n\tINVALID_REQUEST: \"INVALID_REQUEST\",\n\tUNKNOWN_ACTION: \"UNKNOWN_ACTION\",\n} as const;\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];\n\n/**\n * OAuth RFC 6749 error codes.\n *\n * These MUST be lowercase per the RFC spec. Used only by OAuth token endpoints.\n * Separate from ErrorCode to prevent mixing conventions.\n */\nexport const OAuthErrorCode = {\n\tINVALID_GRANT: \"invalid_grant\",\n\tUNSUPPORTED_GRANT_TYPE: \"unsupported_grant_type\",\n\tEXPIRED_TOKEN: \"expired_token\",\n\tACCESS_DENIED: \"access_denied\",\n\tAUTHORIZATION_PENDING: \"authorization_pending\",\n} as const;\n\nexport type OAuthErrorCode = (typeof OAuthErrorCode)[keyof typeof OAuthErrorCode];\n\n/**\n * Map a handler error code to an HTTP status code.\n *\n * Shared codes have explicit mappings. Domain-specific `*_ERROR` codes\n * (used in catch blocks via handleError) default to 500. Everything else\n * defaults to 400 (client error).\n */\nexport function mapErrorStatus(code: string | undefined): number {\n\tswitch (code) {\n\t\t// 400 Bad Request\n\t\tcase ErrorCode.VALIDATION_ERROR:\n\t\tcase ErrorCode.INVALID_INPUT:\n\t\tcase ErrorCode.INVALID_JSON:\n\t\tcase ErrorCode.INVALID_CURSOR:\n\t\tcase ErrorCode.MISSING_PARAM:\n\t\tcase ErrorCode.INVALID_REQUEST:\n\t\tcase ErrorCode.NOT_SUPPORTED:\n\t\tcase ErrorCode.INVALID_SLUG:\n\t\tcase ErrorCode.RESERVED_SLUG:\n\t\tcase ErrorCode.INVALID_TYPE:\n\t\tcase ErrorCode.NO_FILE:\n\t\tcase ErrorCode.INVALID_STATE:\n\t\tcase ErrorCode.INVALID_SEED:\n\t\tcase ErrorCode.INVALID_REDIRECT:\n\t\tcase ErrorCode.INVALID_TOKEN:\n\t\tcase ErrorCode.INVALID_REVISION:\n\t\tcase ErrorCode.INVALID_CODE:\n\t\tcase ErrorCode.CHALLENGE_EXPIRED:\n\t\tcase ErrorCode.EXPIRED_CODE:\n\t\tcase ErrorCode.LAST_PASSKEY:\n\t\tcase ErrorCode.PASSKEY_LIMIT:\n\t\tcase ErrorCode.ADMIN_EXISTS:\n\t\tcase ErrorCode.SETUP_COMPLETE:\n\t\tcase ErrorCode.SELF_ROLE_CHANGE:\n\t\tcase ErrorCode.SSRF_BLOCKED:\n\t\tcase ErrorCode.UNKNOWN_ACTION:\n\t\tcase ErrorCode.AMBIGUOUS_LOCALE:\n\t\t\treturn 400;\n\n\t\t// 401 Unauthorized\n\t\tcase ErrorCode.UNAUTHORIZED:\n\t\tcase ErrorCode.NOT_AUTHENTICATED:\n\t\t\treturn 401;\n\n\t\t// 403 Forbidden\n\t\tcase ErrorCode.FORBIDDEN:\n\t\tcase ErrorCode.CSRF_REJECTED:\n\t\tcase ErrorCode.ACCOUNT_DISABLED:\n\t\tcase ErrorCode.COMMENTS_DISABLED:\n\t\tcase ErrorCode.COMMENTS_CLOSED:\n\t\tcase ErrorCode.COMMENT_REJECTED:\n\t\tcase ErrorCode.DOMAIN_NOT_ALLOWED:\n\t\tcase ErrorCode.INSUFFICIENT_ROLE:\n\t\tcase ErrorCode.INSUFFICIENT_SCOPE:\n\t\tcase ErrorCode.INSUFFICIENT_PERMISSIONS:\n\t\tcase ErrorCode.CAPABILITY_ESCALATION:\n\t\tcase ErrorCode.ROUTE_VISIBILITY_ESCALATION:\n\t\tcase ErrorCode.AUDIT_FAILED:\n\t\t\treturn 403;\n\n\t\t// 404 Not Found\n\t\tcase ErrorCode.NOT_FOUND:\n\t\tcase ErrorCode.TABLE_NOT_FOUND:\n\t\tcase ErrorCode.COLLECTION_NOT_FOUND:\n\t\tcase ErrorCode.FILE_NOT_FOUND:\n\t\tcase ErrorCode.NO_VERSION:\n\t\tcase ErrorCode.AGGREGATOR_NOT_FOUND:\n\t\t\treturn 404;\n\n\t\t// 409 Conflict\n\t\tcase ErrorCode.CONFLICT:\n\t\tcase ErrorCode.SLUG_CONFLICT:\n\t\tcase ErrorCode.COLLECTION_EXISTS:\n\t\tcase ErrorCode.FIELD_EXISTS:\n\t\tcase ErrorCode.CREDENTIAL_EXISTS:\n\t\tcase ErrorCode.EMAIL_IN_USE:\n\t\tcase ErrorCode.USER_EXISTS:\n\t\tcase ErrorCode.PLUGIN_ID_CONFLICT:\n\t\tcase ErrorCode.ALREADY_INSTALLED:\n\t\tcase ErrorCode.ALREADY_CONFIGURED:\n\t\tcase ErrorCode.ALREADY_UP_TO_DATE:\n\t\tcase ErrorCode.ENV_INCOMPATIBLE:\n\t\t\treturn 409;\n\n\t\t// 410 Gone\n\t\tcase ErrorCode.TOKEN_EXPIRED:\n\t\t\treturn 410;\n\n\t\t// 422 Unprocessable Entity\n\t\tcase ErrorCode.CHECKSUM_MISMATCH:\n\t\tcase ErrorCode.INVALID_BUNDLE:\n\t\tcase ErrorCode.BUNDLE_EXTRACT_FAILED:\n\t\t\treturn 422;\n\n\t\t// 429 Too Many Requests\n\t\tcase ErrorCode.RATE_LIMITED:\n\t\t\treturn 429;\n\n\t\t// 500 Internal Server Error\n\t\tcase ErrorCode.NOT_CONFIGURED:\n\t\tcase ErrorCode.NO_STORAGE:\n\t\tcase ErrorCode.NO_DB:\n\t\tcase ErrorCode.STORAGE_NOT_CONFIGURED:\n\t\tcase ErrorCode.EMAIL_NOT_CONFIGURED:\n\t\t\treturn 500;\n\n\t\t// 501 Not Implemented\n\t\tcase ErrorCode.NOT_IMPLEMENTED:\n\t\t\treturn 501;\n\n\t\t// 502 Bad Gateway\n\t\tcase ErrorCode.BUNDLE_DOWNLOAD_FAILED:\n\t\tcase ErrorCode.AGGREGATOR_RESPONSE_INVALID:\n\t\tcase ErrorCode.AGGREGATOR_HTTP_ERROR:\n\t\t\treturn 502;\n\n\t\t// 503 Service Unavailable\n\t\tcase ErrorCode.MARKETPLACE_UNAVAILABLE:\n\t\tcase ErrorCode.MARKETPLACE_NOT_CONFIGURED:\n\t\tcase ErrorCode.SANDBOX_NOT_AVAILABLE:\n\t\t\treturn 503;\n\n\t\t// Domain-specific *_ERROR codes are catch-block codes -- always 500.\n\t\t// WARNING: If adding a new code that ends in _ERROR but represents a\n\t\t// client error (4xx), add it to an explicit case above or it will\n\t\t// be incorrectly mapped to 500.\n\t\tdefault:\n\t\t\treturn code?.endsWith(\"_ERROR\") ? 500 : 400;\n\t}\n}\n","/**\n * Standardized API error responses.\n *\n * All API routes should use these utilities instead of inline\n * `new Response(JSON.stringify({ error: ... }), ...)` patterns.\n */\n\nimport { InvalidCursorError } from \"../database/repositories/types.js\";\nimport { mapErrorStatus } from \"./errors.js\";\nimport type { ApiResult } from \"./types.js\";\n\n// Re-export everything from errors.ts so existing `import { mapErrorStatus } from \"./error.js\"` still works\nexport * from \"./errors.js\";\n\n/**\n * Standard cache headers for all API responses.\n *\n * Cache-Control: private, no-store -- prevents CDN/proxy caching of authenticated data.\n * no-store already tells caches not to store the response, so Vary is unnecessary.\n */\nconst API_CACHE_HEADERS: HeadersInit = {\n\t\"Cache-Control\": \"private, no-store\",\n};\n\n/**\n * Create a standardized error response.\n *\n * Always returns `{ error: { code, message } }` with correct Content-Type.\n * Use this for all error responses in API routes.\n */\nexport function apiError(\n\tcode: string,\n\tmessage: string,\n\tstatus: number,\n\tdetails?: Record<string, unknown>,\n): Response {\n\tconst error: { code: string; message: string; details?: Record<string, unknown> } = {\n\t\tcode,\n\t\tmessage,\n\t};\n\tif (details !== undefined) error.details = details;\n\treturn Response.json({ error }, { status, headers: API_CACHE_HEADERS });\n}\n\n/**\n * Create a standardized success response.\n *\n * Always returns `{ data: T }` with correct status code.\n * Use this for all success responses in API routes.\n */\nexport function apiSuccess<T>(data: T, status = 200): Response {\n\treturn Response.json({ data }, { status, headers: API_CACHE_HEADERS });\n}\n\n/**\n * Handle an unknown error in a catch block.\n *\n * - Logs the full error server-side\n * - Returns a generic message to the client (never leaks error.message)\n * - Use `fallbackMessage` for the public-facing message\n * - Use `fallbackCode` for the error code\n */\nexport function handleError(\n\terror: unknown,\n\tfallbackMessage: string,\n\tfallbackCode: string,\n): Response {\n\t// Bubble malformed-cursor errors as a structured 400 instead of a\n\t// generic 500.\n\tif (error instanceof InvalidCursorError) {\n\t\treturn apiError(\"INVALID_CURSOR\", error.message, 400);\n\t}\n\tconsole.error(`[${fallbackCode}]`, error);\n\treturn apiError(fallbackCode, fallbackMessage, 500);\n}\n\n/**\n * Standard initialization check.\n *\n * Returns an error response if EmDash is not initialized, or null if OK.\n * Usage: `const err = requireInit(emdash); if (err) return err;`\n */\nexport function requireInit(emdash: unknown): Response | null {\n\tif (!emdash || typeof emdash !== \"object\") {\n\t\treturn apiError(\"NOT_CONFIGURED\", \"EmDash is not initialized\", 500);\n\t}\n\treturn null;\n}\n\n/**\n * Standard database check.\n *\n * Returns an error response if the database is not available, or null if OK.\n * Usage: `const err = requireDb(emdash?.db); if (err) return err;`\n */\nexport function requireDb(db: unknown): Response | null {\n\tif (!db) {\n\t\treturn apiError(\"NOT_CONFIGURED\", \"EmDash is not initialized\", 500);\n\t}\n\treturn null;\n}\n\n/**\n * Convert an ApiResult into an HTTP Response.\n *\n * Collapses the handler-to-response boilerplate:\n * - Success: returns `apiSuccess(result.data, successStatus)`\n * - Error: returns `apiError(code, message, mapErrorStatus(code))`\n */\nexport function unwrapResult<T>(result: ApiResult<T>, successStatus = 200): Response {\n\tif (!result.success) {\n\t\treturn apiError(\n\t\t\tresult.error.code,\n\t\t\tresult.error.message,\n\t\t\tmapErrorStatus(result.error.code),\n\t\t\tresult.error.details,\n\t\t);\n\t}\n\treturn apiSuccess(result.data, successStatus);\n}\n"],"mappings":";;;;;;;;;;AAQA,MAAa,YAAY;CAExB,WAAW;CACX,kBAAkB;CAClB,eAAe;CACf,cAAc;CACd,gBAAgB;CAChB,UAAU;CACV,eAAe;CACf,gBAAgB;CAChB,cAAc;CACd,WAAW;CACX,cAAc;CACd,mBAAmB;CACnB,iBAAiB;CACjB,eAAe;CACf,eAAe;CACf,eAAe;CAGf,sBAAsB;CACtB,sBAAsB;CACtB,sBAAsB;CACtB,oBAAoB;CACpB,mBAAmB;CACnB,yBAAyB;CACzB,uBAAuB;CACvB,uBAAuB;CACvB,yBAAyB;CACzB,wBAAwB;CACxB,0BAA0B;CAC1B,6BAA6B;CAC7B,uBAAuB;CACvB,4BAA4B;CAC5B,q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ACX,MAAM,QAA8E;EACnF;EACA;EACA;AACD,KAAI,YAAY,OAAW,OAAM,UAAU;AAC3C,QAAO,SAAS,KAAK,EAAE,OAAO,EAAE;EAAE;EAAQ,SAAS;EAAmB,CAAC;;;;;;;;AASxE,SAAgB,WAAc,MAAS,SAAS,KAAe;AAC9D,QAAO,SAAS,KAAK,EAAE,MAAM,EAAE;EAAE;EAAQ,SAAS;EAAmB,CAAC;;;;;;;;;;AAWvE,SAAgB,YACf,OACA,iBACA,cACW;AAGX,KAAI,iBAAiB,mBACpB,QAAO,SAAS,kBAAkB,MAAM,SAAS,IAAI;AAEtD,SAAQ,MAAM,IAAI,aAAa,IAAI,MAAM;AACzC,QAAO,SAAS,cAAc,iBAAiB,IAAI;;;;;;;;AAsBpD,SAAgB,UAAU,IAA8B;AACvD,KAAI,CAAC,GACJ,QAAO,SAAS,kBAAkB,6BAA6B,IAAI;AAEpE,QAAO;;;;;;;;;AAUR,SAAgB,aAAgB,QAAsB,gBAAgB,KAAe;AACpF,KAAI,CAAC,OAAO,QACX,QAAO,SACN,OAAO,MAAM,MACb,OAAO,MAAM,SACb,eAAe,OAAO,MAAM,KAAK,EACjC,OAAO,MAAM,QACb;AAEF,QAAO,WAAW,OAAO,MAAM,cAAc"}
@@ -0,0 +1,17 @@
1
+ //#region src/database/errors.ts
2
+ /**
3
+ * Database error types. Kept in their own module (no driver imports) so the
4
+ * public package barrel can re-export them without dragging native database
5
+ * drivers into the module graph of consumers that picked a different dialect.
6
+ */
7
+ var EmDashDatabaseError = class extends Error {
8
+ constructor(message, cause) {
9
+ super(message);
10
+ this.cause = cause;
11
+ this.name = "EmDashDatabaseError";
12
+ }
13
+ };
14
+
15
+ //#endregion
16
+ export { EmDashDatabaseError as t };
17
+ //# sourceMappingURL=errors-9P_FDrJ_.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-9P_FDrJ_.mjs","names":[],"sources":["../src/database/errors.ts"],"sourcesContent":["/**\n * Database error types. Kept in their own module (no driver imports) so the\n * public package barrel can re-export them without dragging native database\n * drivers into the module graph of consumers that picked a different dialect.\n */\nexport class EmDashDatabaseError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic override cause?: unknown,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"EmDashDatabaseError\";\n\t}\n}\n"],"mappings":";;;;;;AAKA,IAAa,sBAAb,cAAyC,MAAM;CAC9C,YACC,SACA,AAAgB,OACf;AACD,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO"}
@@ -1,4 +1,4 @@
1
- import { i as __exportAll } from "./runner-CGlojznK.mjs";
1
+ import { i as __exportAll } from "./runner-Drnvs96u.mjs";
2
2
  import { t as validateIdentifier } from "./validate-VPnKoIzW.mjs";
3
3
  import { l as tableExists, o as isSqlite } from "./dialect-helpers-BKCvISIQ.mjs";
4
4
  import { sql } from "kysely";
@@ -336,4 +336,4 @@ var FTSManager = class {
336
336
 
337
337
  //#endregion
338
338
  export { fts_manager_exports as n, FTSManager as t };
339
- //# sourceMappingURL=fts-manager-Mnrtn-r2.mjs.map
339
+ //# sourceMappingURL=fts-manager-C_b-4x8u.mjs.map