emdash 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (286) hide show
  1. package/dist/{adapters-BKSf3T9R.d.mts → adapters-DoNJiveC.d.mts} +1 -1
  2. package/dist/{adapters-BKSf3T9R.d.mts.map → adapters-DoNJiveC.d.mts.map} +1 -1
  3. package/dist/{apply-x0eMK1lX.mjs → apply-BzltprvY.mjs} +85 -135
  4. package/dist/apply-BzltprvY.mjs.map +1 -0
  5. package/dist/astro/index.d.mts +6 -6
  6. package/dist/astro/index.d.mts.map +1 -1
  7. package/dist/astro/index.mjs +110 -4
  8. package/dist/astro/index.mjs.map +1 -1
  9. package/dist/astro/middleware/auth.d.mts +6 -7
  10. package/dist/astro/middleware/auth.d.mts.map +1 -1
  11. package/dist/astro/middleware/auth.mjs +16 -59
  12. package/dist/astro/middleware/auth.mjs.map +1 -1
  13. package/dist/astro/middleware/redirect.d.mts.map +1 -1
  14. package/dist/astro/middleware/redirect.mjs +17 -12
  15. package/dist/astro/middleware/redirect.mjs.map +1 -1
  16. package/dist/astro/middleware/request-context.d.mts.map +1 -1
  17. package/dist/astro/middleware/request-context.mjs +9 -6
  18. package/dist/astro/middleware/request-context.mjs.map +1 -1
  19. package/dist/astro/middleware/setup.mjs +1 -1
  20. package/dist/astro/middleware.d.mts.map +1 -1
  21. package/dist/astro/middleware.mjs +72 -124
  22. package/dist/astro/middleware.mjs.map +1 -1
  23. package/dist/astro/types.d.mts +26 -10
  24. package/dist/astro/types.d.mts.map +1 -1
  25. package/dist/{base64-MBPo9ozB.mjs → base64-BRICGH2l.mjs} +1 -1
  26. package/dist/{base64-MBPo9ozB.mjs.map → base64-BRICGH2l.mjs.map} +1 -1
  27. package/dist/{byline-Chbr2GoP.mjs → byline-BSaNL1w7.mjs} +4 -4
  28. package/dist/{byline-Chbr2GoP.mjs.map → byline-BSaNL1w7.mjs.map} +1 -1
  29. package/dist/bylines-CvJ3PYz2.mjs +113 -0
  30. package/dist/bylines-CvJ3PYz2.mjs.map +1 -0
  31. package/dist/cache-C6N_hhN7.mjs +65 -0
  32. package/dist/cache-C6N_hhN7.mjs.map +1 -0
  33. package/dist/{chunks-HGz06Soa.mjs → chunks-NBQVDOci.mjs} +8 -2
  34. package/dist/{chunks-HGz06Soa.mjs.map → chunks-NBQVDOci.mjs.map} +1 -1
  35. package/dist/cli/index.mjs +224 -30
  36. package/dist/cli/index.mjs.map +1 -1
  37. package/dist/client/cf-access.d.mts +1 -1
  38. package/dist/client/index.d.mts +1 -1
  39. package/dist/client/index.mjs +3 -3
  40. package/dist/client/index.mjs.map +1 -1
  41. package/dist/{config-BXwuX8Bx.mjs → config-BI0V3ICQ.mjs} +1 -1
  42. package/dist/{config-BXwuX8Bx.mjs.map → config-BI0V3ICQ.mjs.map} +1 -1
  43. package/dist/{content-BcQPYxdV.mjs → content-8lOYF0pr.mjs} +32 -15
  44. package/dist/{content-BcQPYxdV.mjs.map → content-8lOYF0pr.mjs.map} +1 -1
  45. package/dist/db/index.d.mts +3 -3
  46. package/dist/db/index.mjs +2 -2
  47. package/dist/db/libsql.d.mts +1 -1
  48. package/dist/db/libsql.d.mts.map +1 -1
  49. package/dist/db/libsql.mjs +7 -2
  50. package/dist/db/libsql.mjs.map +1 -1
  51. package/dist/db/postgres.d.mts +1 -1
  52. package/dist/db/sqlite.d.mts +1 -1
  53. package/dist/db/sqlite.d.mts.map +1 -1
  54. package/dist/db/sqlite.mjs +8 -3
  55. package/dist/db/sqlite.mjs.map +1 -1
  56. package/dist/{db-errors-l1Qh2RPR.mjs → db-errors-WRezodiz.mjs} +1 -1
  57. package/dist/{db-errors-l1Qh2RPR.mjs.map → db-errors-WRezodiz.mjs.map} +1 -1
  58. package/dist/{default-DCVqE5ib.mjs → default-D8ksjWhO.mjs} +1 -1
  59. package/dist/{default-DCVqE5ib.mjs.map → default-D8ksjWhO.mjs.map} +1 -1
  60. package/dist/{dialect-helpers-DhTzaUxP.mjs → dialect-helpers-BKCvISIQ.mjs} +19 -2
  61. package/dist/dialect-helpers-BKCvISIQ.mjs.map +1 -0
  62. package/dist/{error-zG5T1UGA.mjs → error-D_-tqP-I.mjs} +1 -1
  63. package/dist/{error-zG5T1UGA.mjs.map → error-D_-tqP-I.mjs.map} +1 -1
  64. package/dist/{index-DIb-CzNx.d.mts → index-BFRaVcD6.d.mts} +94 -34
  65. package/dist/index-BFRaVcD6.d.mts.map +1 -0
  66. package/dist/index.d.mts +11 -11
  67. package/dist/index.mjs +29 -27
  68. package/dist/{load-CyEoextb.mjs → load-DDqMMvZL.mjs} +2 -2
  69. package/dist/{load-CyEoextb.mjs.map → load-DDqMMvZL.mjs.map} +1 -1
  70. package/dist/{loader-CndGj8kM.mjs → loader-CKLbBnhK.mjs} +27 -7
  71. package/dist/loader-CKLbBnhK.mjs.map +1 -0
  72. package/dist/{manifest-schema-DH9xhc6t.mjs → manifest-schema-DqWNC3lM.mjs} +33 -3
  73. package/dist/manifest-schema-DqWNC3lM.mjs.map +1 -0
  74. package/dist/media/index.d.mts +1 -1
  75. package/dist/media/index.mjs +1 -1
  76. package/dist/media/local-runtime.d.mts +7 -7
  77. package/dist/media/local-runtime.mjs +3 -3
  78. package/dist/{media-D8FbNsl0.mjs → media-BW32b4gi.mjs} +2 -2
  79. package/dist/{media-D8FbNsl0.mjs.map → media-BW32b4gi.mjs.map} +1 -1
  80. package/dist/{mode-BnAOqItE.mjs → mode-ier8jbBk.mjs} +1 -1
  81. package/dist/{mode-BnAOqItE.mjs.map → mode-ier8jbBk.mjs.map} +1 -1
  82. package/dist/options-BVp3UsTS.mjs +117 -0
  83. package/dist/options-BVp3UsTS.mjs.map +1 -0
  84. package/dist/page/index.d.mts +2 -2
  85. package/dist/{placeholder-D29tWZ7o.d.mts → placeholder-BE4o_2dc.d.mts} +1 -1
  86. package/dist/{placeholder-D29tWZ7o.d.mts.map → placeholder-BE4o_2dc.d.mts.map} +1 -1
  87. package/dist/{placeholder-C-fk5hYI.mjs → placeholder-CIJejMlK.mjs} +1 -1
  88. package/dist/{placeholder-C-fk5hYI.mjs.map → placeholder-CIJejMlK.mjs.map} +1 -1
  89. package/dist/plugins/adapt-sandbox-entry.d.mts +5 -5
  90. package/dist/plugins/adapt-sandbox-entry.d.mts.map +1 -1
  91. package/dist/plugins/adapt-sandbox-entry.mjs +6 -5
  92. package/dist/plugins/adapt-sandbox-entry.mjs.map +1 -1
  93. package/dist/public-url-DByxYjUw.mjs +51 -0
  94. package/dist/public-url-DByxYjUw.mjs.map +1 -0
  95. package/dist/{query-fqEdLFms.mjs → query-Cg9ZKRQ0.mjs} +114 -16
  96. package/dist/query-Cg9ZKRQ0.mjs.map +1 -0
  97. package/dist/{redirect-D_pshWdf.mjs → redirect-BhUBKRc1.mjs} +11 -6
  98. package/dist/redirect-BhUBKRc1.mjs.map +1 -0
  99. package/dist/{registry-C3Mr0ODu.mjs → registry-Dw70ChxB.mjs} +38 -4
  100. package/dist/registry-Dw70ChxB.mjs.map +1 -0
  101. package/dist/{request-cache-Ci7f5pBb.mjs → request-cache-B-bmkipQ.mjs} +1 -1
  102. package/dist/{request-cache-Ci7f5pBb.mjs.map → request-cache-B-bmkipQ.mjs.map} +1 -1
  103. package/dist/runner-Bnoj7vjK.d.mts +44 -0
  104. package/dist/runner-Bnoj7vjK.d.mts.map +1 -0
  105. package/dist/{runner-tQ7BJ4T7.mjs → runner-C7ADox5q.mjs} +185 -55
  106. package/dist/{runner-tQ7BJ4T7.mjs.map → runner-C7ADox5q.mjs.map} +1 -1
  107. package/dist/runtime.d.mts +6 -6
  108. package/dist/runtime.mjs +4 -4
  109. package/dist/{search-BoZYFuUk.mjs → search-dOGEccMa.mjs} +129 -83
  110. package/dist/search-dOGEccMa.mjs.map +1 -0
  111. package/dist/secrets-CW3reAnU.mjs +314 -0
  112. package/dist/secrets-CW3reAnU.mjs.map +1 -0
  113. package/dist/seed/index.d.mts +2 -2
  114. package/dist/seed/index.mjs +15 -14
  115. package/dist/seo/index.d.mts +1 -1
  116. package/dist/storage/local.d.mts +1 -1
  117. package/dist/storage/local.mjs +1 -1
  118. package/dist/storage/s3.d.mts +1 -1
  119. package/dist/storage/s3.mjs +1 -1
  120. package/dist/{taxonomies-B4IAshV8.mjs → taxonomies-ZlRtD6AG.mjs} +14 -7
  121. package/dist/taxonomies-ZlRtD6AG.mjs.map +1 -0
  122. package/dist/{tokens-D9vnZqYS.mjs → tokens-D7zMmWi2.mjs} +2 -2
  123. package/dist/{tokens-D9vnZqYS.mjs.map → tokens-D7zMmWi2.mjs.map} +1 -1
  124. package/dist/{transport-C9ugt2Nr.mjs → transport-BeMCmin1.mjs} +6 -5
  125. package/dist/{transport-C9ugt2Nr.mjs.map → transport-BeMCmin1.mjs.map} +1 -1
  126. package/dist/{transport-CUnEL3Vs.d.mts → transport-DNEfeMaU.d.mts} +1 -1
  127. package/dist/{transport-CUnEL3Vs.d.mts.map → transport-DNEfeMaU.d.mts.map} +1 -1
  128. package/dist/types-4fVtCIm0.mjs +68 -0
  129. package/dist/types-4fVtCIm0.mjs.map +1 -0
  130. package/dist/{types-BmPPSUEx.d.mts → types-BSyXeCFW.d.mts} +24 -2
  131. package/dist/{types-BmPPSUEx.d.mts.map → types-BSyXeCFW.d.mts.map} +1 -1
  132. package/dist/{types-i36XcA_X.d.mts → types-BuBIptGk.d.mts} +65 -134
  133. package/dist/types-BuBIptGk.d.mts.map +1 -0
  134. package/dist/{types-CgqmmMJB.mjs → types-CDbKp7ND.mjs} +1 -1
  135. package/dist/{types-CgqmmMJB.mjs.map → types-CDbKp7ND.mjs.map} +1 -1
  136. package/dist/{types-Bm1dn-q3.mjs → types-CIOg5AR8.mjs} +1 -1
  137. package/dist/{types-Bm1dn-q3.mjs.map → types-CIOg5AR8.mjs.map} +1 -1
  138. package/dist/{types-BrA0xf5I.d.mts → types-CJsYGpco.d.mts} +1 -1
  139. package/dist/{types-BrA0xf5I.d.mts.map → types-CJsYGpco.d.mts.map} +1 -1
  140. package/dist/{types-BIgulNsW.mjs → types-CRxNbK-Z.mjs} +2 -2
  141. package/dist/{types-BIgulNsW.mjs.map → types-CRxNbK-Z.mjs.map} +1 -1
  142. package/dist/{types-CS8FIX7L.d.mts → types-CrtWgIvl.d.mts} +1 -1
  143. package/dist/{types-CS8FIX7L.d.mts.map → types-CrtWgIvl.d.mts.map} +1 -1
  144. package/dist/{types-DIMwPFub.d.mts → types-M78DQ1lx.d.mts} +1 -1
  145. package/dist/{types-DIMwPFub.d.mts.map → types-M78DQ1lx.d.mts.map} +1 -1
  146. package/dist/{validate-CxVsLehf.mjs → validate-Baqf0slj.mjs} +3 -3
  147. package/dist/{validate-CxVsLehf.mjs.map → validate-Baqf0slj.mjs.map} +1 -1
  148. package/dist/{validate-DHxmpFJt.d.mts → validate-BfQh_C_y.d.mts} +4 -4
  149. package/dist/{validate-DHxmpFJt.d.mts.map → validate-BfQh_C_y.d.mts.map} +1 -1
  150. package/dist/{validation-C-ZpN2GI.mjs → validation-BfEI7tNe.mjs} +6 -6
  151. package/dist/{validation-C-ZpN2GI.mjs.map → validation-BfEI7tNe.mjs.map} +1 -1
  152. package/dist/version-DoxrVdYf.mjs +7 -0
  153. package/dist/{version-Bbq8TCrz.mjs.map → version-DoxrVdYf.mjs.map} +1 -1
  154. package/dist/{zod-generator-CpwccCIv.mjs → zod-generator-CC0xNe_K.mjs} +4 -4
  155. package/dist/zod-generator-CC0xNe_K.mjs.map +1 -0
  156. package/locals.d.ts +1 -6
  157. package/package.json +9 -8
  158. package/src/api/handlers/comments.ts +6 -4
  159. package/src/api/handlers/content.ts +29 -1
  160. package/src/api/handlers/device-flow.ts +5 -0
  161. package/src/api/handlers/marketplace.ts +11 -4
  162. package/src/api/handlers/oauth-authorization.ts +72 -33
  163. package/src/api/handlers/revision.ts +23 -14
  164. package/src/api/handlers/taxonomies.ts +3 -6
  165. package/src/api/public-url.ts +48 -2
  166. package/src/api/schemas/comments.ts +2 -2
  167. package/src/api/schemas/content.ts +17 -0
  168. package/src/api/schemas/sections.ts +3 -3
  169. package/src/api/schemas/users.ts +1 -1
  170. package/src/api/types.ts +5 -1
  171. package/src/astro/integration/index.ts +17 -0
  172. package/src/astro/integration/runtime.ts +30 -0
  173. package/src/astro/integration/virtual-modules.ts +32 -2
  174. package/src/astro/integration/vite-config.ts +6 -1
  175. package/src/astro/middleware/auth.ts +13 -6
  176. package/src/astro/middleware/redirect.ts +29 -16
  177. package/src/astro/middleware/request-context.ts +15 -5
  178. package/src/astro/middleware.ts +23 -9
  179. package/src/astro/routes/api/auth/invite/complete.ts +6 -1
  180. package/src/astro/routes/api/auth/passkey/register/verify.ts +6 -1
  181. package/src/astro/routes/api/auth/passkey/verify.ts +6 -1
  182. package/src/astro/routes/api/auth/signup/complete.ts +6 -1
  183. package/src/astro/routes/api/comments/[collection]/[contentId]/index.ts +2 -2
  184. package/src/astro/routes/api/content/[collection]/[id]/discard-draft.ts +4 -2
  185. package/src/astro/routes/api/content/[collection]/[id]/preview-url.ts +34 -12
  186. package/src/astro/routes/api/content/[collection]/[id]/publish.ts +32 -2
  187. package/src/astro/routes/api/content/[collection]/[id]/restore.ts +4 -2
  188. package/src/astro/routes/api/content/[collection]/[id]/revisions.ts +3 -2
  189. package/src/astro/routes/api/content/[collection]/[id]/terms/[taxonomy].ts +8 -4
  190. package/src/astro/routes/api/content/[collection]/[id].ts +12 -0
  191. package/src/astro/routes/api/import/wordpress/execute.ts +3 -1
  192. package/src/astro/routes/api/import/wordpress/prepare.ts +7 -8
  193. package/src/astro/routes/api/import/wordpress-plugin/execute.ts +3 -1
  194. package/src/astro/routes/api/manifest.ts +62 -45
  195. package/src/astro/routes/api/media/[id]/confirm.ts +10 -1
  196. package/src/astro/routes/api/media/providers/[providerId]/index.ts +12 -3
  197. package/src/astro/routes/api/openapi.json.ts +27 -10
  198. package/src/astro/routes/api/redirects/404s/index.ts +10 -4
  199. package/src/astro/routes/api/redirects/404s/summary.ts +4 -2
  200. package/src/astro/routes/api/redirects/[id].ts +10 -4
  201. package/src/astro/routes/api/redirects/index.ts +7 -3
  202. package/src/astro/routes/api/revisions/[revisionId]/index.ts +1 -1
  203. package/src/astro/routes/api/schema/collections/[slug]/fields/[fieldSlug].ts +0 -2
  204. package/src/astro/routes/api/schema/collections/[slug]/fields/index.ts +0 -1
  205. package/src/astro/routes/api/schema/collections/[slug]/fields/reorder.ts +0 -1
  206. package/src/astro/routes/api/schema/collections/[slug]/index.ts +2 -2
  207. package/src/astro/routes/api/schema/collections/index.ts +1 -1
  208. package/src/astro/routes/api/search/index.ts +10 -2
  209. package/src/astro/routes/api/sections/[slug].ts +10 -4
  210. package/src/astro/routes/api/sections/index.ts +7 -3
  211. package/src/astro/routes/api/setup/admin-verify.ts +6 -1
  212. package/src/astro/routes/api/snapshot.ts +44 -18
  213. package/src/astro/routes/api/taxonomies/index.ts +0 -1
  214. package/src/astro/routes/api/themes/preview.ts +11 -5
  215. package/src/astro/types.ts +23 -3
  216. package/src/auth/allowed-origins.ts +168 -0
  217. package/src/auth/passkey-config.ts +35 -13
  218. package/src/bylines/index.ts +37 -88
  219. package/src/cli/commands/auth.ts +28 -6
  220. package/src/cli/commands/bundle-utils.ts +11 -2
  221. package/src/cli/commands/bundle.ts +28 -8
  222. package/src/cli/commands/content.ts +13 -0
  223. package/src/cli/commands/login.ts +8 -1
  224. package/src/cli/commands/publish.ts +24 -0
  225. package/src/cli/commands/secrets.ts +183 -0
  226. package/src/cli/credentials.ts +1 -1
  227. package/src/cli/index.ts +5 -1
  228. package/src/client/index.ts +4 -4
  229. package/src/client/transport.ts +17 -7
  230. package/src/components/Break.astro +2 -2
  231. package/src/components/EmDashHead.astro +18 -13
  232. package/src/components/Embed.astro +1 -1
  233. package/src/components/Gallery.astro +1 -1
  234. package/src/components/Image.astro +1 -1
  235. package/src/components/InlinePortableTextEditor.tsx +104 -18
  236. package/src/config/secrets.ts +528 -0
  237. package/src/database/dialect-helpers.ts +50 -0
  238. package/src/database/migrations/034_published_at_index.ts +1 -1
  239. package/src/database/migrations/035_bounded_404_log.ts +56 -39
  240. package/src/database/migrations/runner.ts +156 -23
  241. package/src/database/repositories/content.ts +36 -12
  242. package/src/database/repositories/redirect.ts +14 -3
  243. package/src/database/repositories/taxonomy.ts +26 -0
  244. package/src/db/libsql.ts +1 -3
  245. package/src/db/sqlite.ts +2 -5
  246. package/src/emdash-runtime.ts +84 -159
  247. package/src/index.ts +9 -0
  248. package/src/loader.ts +24 -1
  249. package/src/mcp/server.ts +103 -36
  250. package/src/page/site-identity.ts +58 -0
  251. package/src/plugins/adapt-sandbox-entry.ts +22 -10
  252. package/src/plugins/context.ts +13 -10
  253. package/src/plugins/define-plugin.ts +40 -12
  254. package/src/plugins/hooks.ts +23 -19
  255. package/src/plugins/index.ts +9 -0
  256. package/src/plugins/manifest-schema.ts +37 -2
  257. package/src/plugins/types.ts +151 -11
  258. package/src/preview/urls.ts +23 -3
  259. package/src/query.ts +148 -5
  260. package/src/redirects/cache.ts +38 -18
  261. package/src/schema/registry.ts +56 -0
  262. package/src/schema/zod-generator.ts +27 -5
  263. package/src/seed/apply.ts +2 -0
  264. package/src/settings/index.ts +80 -6
  265. package/src/settings/types.ts +23 -1
  266. package/src/taxonomies/index.ts +11 -1
  267. package/dist/apply-x0eMK1lX.mjs.map +0 -1
  268. package/dist/bylines-CRNsVG88.mjs +0 -157
  269. package/dist/bylines-CRNsVG88.mjs.map +0 -1
  270. package/dist/cache-BkKBuIvS.mjs +0 -56
  271. package/dist/cache-BkKBuIvS.mjs.map +0 -1
  272. package/dist/chunk-ClPoSABd.mjs +0 -21
  273. package/dist/dialect-helpers-DhTzaUxP.mjs.map +0 -1
  274. package/dist/index-DIb-CzNx.d.mts.map +0 -1
  275. package/dist/loader-CndGj8kM.mjs.map +0 -1
  276. package/dist/manifest-schema-DH9xhc6t.mjs.map +0 -1
  277. package/dist/query-fqEdLFms.mjs.map +0 -1
  278. package/dist/redirect-D_pshWdf.mjs.map +0 -1
  279. package/dist/registry-C3Mr0ODu.mjs.map +0 -1
  280. package/dist/runner-OURCaApa.d.mts +0 -34
  281. package/dist/runner-OURCaApa.d.mts.map +0 -1
  282. package/dist/search-BoZYFuUk.mjs.map +0 -1
  283. package/dist/taxonomies-B4IAshV8.mjs.map +0 -1
  284. package/dist/types-i36XcA_X.d.mts.map +0 -1
  285. package/dist/version-Bbq8TCrz.mjs +0 -7
  286. package/dist/zod-generator-CpwccCIv.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"placeholder-C-fk5hYI.mjs","names":[],"sources":["../src/media/normalize.ts","../src/media/placeholder.ts"],"sourcesContent":["/**\n * Media Value Normalization\n *\n * Normalizes media field values into a consistent shape regardless of\n * creation path (seed scripts, media picker, WP import, URL input).\n *\n * Called at content create/update time when a media provider is available,\n * filling in missing dimensions, storageKey, mimeType, and filename from\n * the provider's `get()` method.\n */\n\nimport type { MediaProvider, MediaProviderItem, MediaValue } from \"./types.js\";\n\nexport const INTERNAL_MEDIA_PREFIX = \"/_emdash/api/media/file/\";\nconst URL_PATTERN = /^https?:\\/\\//;\n\n/**\n * Normalize a media field value into a consistent MediaValue shape.\n *\n * - `null`/`undefined` → `null`\n * - Bare URL string → `{ provider: \"external\", id: \"\", src: url }`\n * - Bare internal media URL → resolved via local provider's `get()`\n * - Object with `provider` + `id` → enriched with missing fields from provider\n */\nexport async function normalizeMediaValue(\n\tvalue: unknown,\n\tgetProvider: (id: string) => MediaProvider | undefined,\n): Promise<MediaValue | null> {\n\tif (value == null) return null;\n\n\t// Bare string URL\n\tif (typeof value === \"string\") {\n\t\treturn normalizeStringUrl(value, getProvider);\n\t}\n\n\t// Not an object — can't normalize\n\tif (!isRecord(value)) return null;\n\n\t// Must have at least an id to be a valid media value\n\tif (!(\"id\" in value) && !(\"src\" in value)) return null;\n\n\tconst provider = (typeof value.provider === \"string\" ? value.provider : undefined) || \"local\";\n\tconst id = typeof value.id === \"string\" ? value.id : \"\";\n\n\t// External URLs — return as-is, no server-side dimension detection\n\tif (provider === \"external\") {\n\t\treturn recordToMediaValue(value);\n\t}\n\n\t// Build the base value from the input\n\tconst result: MediaValue = { ...recordToMediaValue(value), provider };\n\n\t// For local media, strip `src` — it's derived at display time from storageKey\n\tif (provider === \"local\") {\n\t\tdelete result.src;\n\t}\n\n\t// Determine if we need to call the provider\n\tconst needsDimensions = result.width == null || result.height == null;\n\tconst needsStorageKey = provider === \"local\" && !result.meta?.storageKey;\n\tconst needsFileInfo = !result.mimeType || !result.filename;\n\tconst needsLookup = needsDimensions || needsStorageKey || needsFileInfo;\n\n\tif (!needsLookup || !id) return result;\n\n\t// Try to enrich from provider\n\tconst mediaProvider = getProvider(provider);\n\tif (!mediaProvider?.get) return result;\n\n\tlet providerItem: MediaProviderItem | null;\n\ttry {\n\t\tproviderItem = await mediaProvider.get(id);\n\t} catch {\n\t\treturn result;\n\t}\n\n\tif (!providerItem) return result;\n\n\treturn mergeProviderData(result, providerItem);\n}\n\nfunction normalizeStringUrl(\n\turl: string,\n\tgetProvider: (id: string) => MediaProvider | undefined,\n): Promise<MediaValue | null> {\n\t// Internal media URL — try to resolve via local provider\n\tif (url.startsWith(INTERNAL_MEDIA_PREFIX)) {\n\t\treturn resolveInternalUrl(url, getProvider);\n\t}\n\n\t// External HTTP(S) URL\n\tif (URL_PATTERN.test(url)) {\n\t\treturn Promise.resolve({\n\t\t\tprovider: \"external\",\n\t\t\tid: \"\",\n\t\t\tsrc: url,\n\t\t});\n\t}\n\n\t// Unrecognized string — treat as external\n\treturn Promise.resolve({\n\t\tprovider: \"external\",\n\t\tid: \"\",\n\t\tsrc: url,\n\t});\n}\n\nasync function resolveInternalUrl(\n\turl: string,\n\tgetProvider: (id: string) => MediaProvider | undefined,\n): Promise<MediaValue> {\n\tconst storageKey = url.slice(INTERNAL_MEDIA_PREFIX.length);\n\tconst localProvider = getProvider(\"local\");\n\n\tif (!localProvider?.get) {\n\t\treturn { provider: \"external\", id: \"\", src: url };\n\t}\n\n\tlet item: MediaProviderItem | null;\n\ttry {\n\t\titem = await localProvider.get(storageKey);\n\t} catch {\n\t\treturn { provider: \"external\", id: \"\", src: url };\n\t}\n\n\tif (!item) {\n\t\treturn { provider: \"external\", id: \"\", src: url };\n\t}\n\n\treturn {\n\t\tprovider: \"local\",\n\t\tid: item.id,\n\t\tfilename: item.filename,\n\t\tmimeType: item.mimeType,\n\t\twidth: item.width,\n\t\theight: item.height,\n\t\talt: item.alt,\n\t\tmeta: item.meta,\n\t};\n}\n\n/**\n * Merge provider data into an existing MediaValue, preserving caller-supplied fields.\n * Caller `alt` takes priority over provider `alt` (per-usage, not per-image).\n */\nfunction mergeProviderData(existing: MediaValue, item: MediaProviderItem): MediaValue {\n\tconst result = { ...existing };\n\n\t// Fill missing dimensions\n\tif (result.width == null && item.width != null) result.width = item.width;\n\tif (result.height == null && item.height != null) result.height = item.height;\n\n\t// Fill missing file info\n\tif (!result.filename && item.filename) result.filename = item.filename;\n\tif (!result.mimeType && item.mimeType) result.mimeType = item.mimeType;\n\n\t// Fill missing alt (provider alt is fallback, not override)\n\tif (!result.alt && item.alt) result.alt = item.alt;\n\n\t// Fill missing meta (merge, don't replace)\n\tif (item.meta) {\n\t\tresult.meta = { ...item.meta, ...result.meta };\n\t}\n\n\treturn result;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Extract known MediaValue fields from a runtime-checked record.\n * Avoids unsafe `as MediaValue` cast by reading each property explicitly.\n */\nfunction recordToMediaValue(obj: Record<string, unknown>): MediaValue {\n\tconst result: MediaValue = {\n\t\tid: typeof obj.id === \"string\" ? obj.id : \"\",\n\t};\n\tif (typeof obj.provider === \"string\") result.provider = obj.provider;\n\tif (typeof obj.src === \"string\") result.src = obj.src;\n\tif (typeof obj.previewUrl === \"string\") result.previewUrl = obj.previewUrl;\n\tif (typeof obj.filename === \"string\") result.filename = obj.filename;\n\tif (typeof obj.mimeType === \"string\") result.mimeType = obj.mimeType;\n\tif (typeof obj.width === \"number\") result.width = obj.width;\n\tif (typeof obj.height === \"number\") result.height = obj.height;\n\tif (typeof obj.alt === \"string\") result.alt = obj.alt;\n\tif (isRecord(obj.meta)) result.meta = obj.meta;\n\treturn result;\n}\n","/**\n * Image Placeholder Generation\n *\n * Generates blurhash and dominant color from image buffers for LQIP support.\n * Decodes images via jpeg-js (pure JS) and upng-js (pure JS, uses pako for\n * deflate). No Node-specific dependencies — works in Workers and Node SSR.\n */\n\nimport { encode } from \"blurhash\";\nimport { imageSize } from \"image-size\";\n\nexport interface PlaceholderData {\n\tblurhash: string;\n\tdominantColor: string;\n}\n\nconst SUPPORTED_TYPES: Record<string, \"jpeg\" | \"png\"> = {\n\t\"image/jpeg\": \"jpeg\",\n\t\"image/jpg\": \"jpeg\",\n\t\"image/png\": \"png\",\n};\n\n/** Max width for blurhash input. Encode is O(w*h*components), so downsample first. */\nconst MAX_ENCODE_WIDTH = 32;\n\n/** Max decoded RGBA size (32 MB). Images exceeding this skip placeholder generation. */\nconst MAX_DECODED_BYTES = 32 * 1024 * 1024;\n\ninterface DecodedImage {\n\twidth: number;\n\theight: number;\n\tdata: Uint8Array;\n}\n\n/**\n * Decode a JPEG buffer into raw RGBA pixel data.\n */\nasync function decodeJpeg(buffer: Uint8Array): Promise<DecodedImage> {\n\tconst { decode } = await import(\"jpeg-js\");\n\tconst result = decode(buffer, { useTArray: true });\n\treturn { width: result.width, height: result.height, data: result.data };\n}\n\n/**\n * Decode a PNG buffer into raw RGBA pixel data.\n * Uses upng-js (pure JS with pako deflate) — no Node zlib dependency.\n */\nasync function decodePng(buffer: Uint8Array): Promise<DecodedImage> {\n\t// @ts-expect-error -- upng-js has no type declarations\n\tconst UPNG = (await import(\"upng-js\")).default;\n\tconst img = UPNG.decode(buffer.buffer);\n\t// toRGBA8 returns an array of frames; take the first frame\n\tconst frames: ArrayBuffer[] = UPNG.toRGBA8(img);\n\tconst rgba = new Uint8Array(frames[0]);\n\treturn { width: img.width, height: img.height, data: rgba };\n}\n\n/**\n * Extract the dominant color from RGBA pixel data.\n * Simple average of all non-transparent pixels.\n */\nfunction extractDominantColor(data: Uint8Array, width: number, height: number): string {\n\tlet r = 0;\n\tlet g = 0;\n\tlet b = 0;\n\tlet count = 0;\n\n\tconst len = width * height * 4;\n\tfor (let i = 0; i < len; i += 4) {\n\t\tconst a = data[i + 3];\n\t\tif (a < 128) continue; // skip mostly-transparent pixels\n\t\tr += data[i];\n\t\tg += data[i + 1];\n\t\tb += data[i + 2];\n\t\tcount++;\n\t}\n\n\tif (count === 0) return \"rgb(0,0,0)\";\n\n\tconst avgR = Math.round(r / count);\n\tconst avgG = Math.round(g / count);\n\tconst avgB = Math.round(b / count);\n\treturn `rgb(${avgR},${avgG},${avgB})`;\n}\n\n/**\n * Read image dimensions from headers without decoding pixel data.\n */\nfunction getImageDimensions(buffer: Uint8Array): { width: number; height: number } | null {\n\ttry {\n\t\tconst result = imageSize(buffer);\n\t\tif (result.width != null && result.height != null) {\n\t\t\treturn { width: result.width, height: result.height };\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Generate blurhash and dominant color from an image buffer.\n * Returns null for non-image MIME types or on failure.\n *\n * @param dimensions - Optional pre-known dimensions. Used as a fallback when\n * image-size cannot parse the buffer (e.g. truncated headers). When the\n * decoded size (width * height * 4) exceeds MAX_DECODED_BYTES, placeholder\n * generation is skipped to avoid OOM on memory-constrained runtimes.\n */\nexport async function generatePlaceholder(\n\tbuffer: Uint8Array,\n\tmimeType: string,\n\tdimensions?: { width: number; height: number },\n): Promise<PlaceholderData | null> {\n\tconst format = SUPPORTED_TYPES[mimeType];\n\tif (!format) return null;\n\n\ttry {\n\t\t// Safety net: skip decode if the image would exceed the memory budget\n\t\tconst dims = getImageDimensions(buffer) ?? dimensions;\n\t\tif (dims && dims.width * dims.height * 4 > MAX_DECODED_BYTES) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst imageData = format === \"jpeg\" ? await decodeJpeg(buffer) : await decodePng(buffer);\n\t\tconst { width, height, data } = imageData;\n\n\t\tif (width === 0 || height === 0) return null;\n\n\t\t// Downsample for blurhash encoding if needed\n\t\tlet encodePixels: Uint8ClampedArray;\n\t\tlet encodeWidth: number;\n\t\tlet encodeHeight: number;\n\n\t\tif (width > MAX_ENCODE_WIDTH) {\n\t\t\tconst scale = MAX_ENCODE_WIDTH / width;\n\t\t\tencodeWidth = MAX_ENCODE_WIDTH;\n\t\t\tencodeHeight = Math.max(1, Math.round(height * scale));\n\t\t\tencodePixels = downsample(data, width, height, encodeWidth, encodeHeight);\n\t\t} else {\n\t\t\tencodeWidth = width;\n\t\t\tencodeHeight = height;\n\t\t\tencodePixels = new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength);\n\t\t}\n\n\t\tconst blurhash = encode(encodePixels, encodeWidth, encodeHeight, 4, 3);\n\t\tconst dominantColor = extractDominantColor(data, width, height);\n\n\t\treturn { blurhash, dominantColor };\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Nearest-neighbor downsample of RGBA pixel data.\n */\nfunction downsample(\n\tsrc: Uint8Array,\n\tsrcW: number,\n\tsrcH: number,\n\tdstW: number,\n\tdstH: number,\n): Uint8ClampedArray {\n\tconst dst = new Uint8ClampedArray(dstW * dstH * 4);\n\n\tfor (let y = 0; y < dstH; y++) {\n\t\tconst srcY = Math.floor((y * srcH) / dstH);\n\t\tfor (let x = 0; x < dstW; x++) {\n\t\t\tconst srcX = Math.floor((x * srcW) / dstW);\n\t\t\tconst srcIdx = (srcY * srcW + srcX) * 4;\n\t\t\tconst dstIdx = (y * dstW + x) * 4;\n\t\t\tdst[dstIdx] = src[srcIdx]!;\n\t\t\tdst[dstIdx + 1] = src[srcIdx + 1]!;\n\t\t\tdst[dstIdx + 2] = src[srcIdx + 2]!;\n\t\t\tdst[dstIdx + 3] = src[srcIdx + 3]!;\n\t\t}\n\t}\n\n\treturn dst;\n}\n"],"mappings":";;;;AAaA,MAAa,wBAAwB;AACrC,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GnD,eAFG,qBAAqB,MAAM,OAAO,OAAO;GAE7B;SAC3B;AACP,SAAO;;;;;;AAOT,SAAS,WACR,KACA,MACA,MACA,MACA,MACoB;CACpB,MAAM,MAAM,IAAI,kBAAkB,OAAO,OAAO,EAAE;AAElD,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KAAK;EAC9B,MAAM,OAAO,KAAK,MAAO,IAAI,OAAQ,KAAK;AAC1C,OAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KAAK;GAC9B,MAAM,OAAO,KAAK,MAAO,IAAI,OAAQ,KAAK;GAC1C,MAAM,UAAU,OAAO,OAAO,QAAQ;GACtC,MAAM,UAAU,IAAI,OAAO,KAAK;AAChC,OAAI,UAAU,IAAI;AAClB,OAAI,SAAS,KAAK,IAAI,SAAS;AAC/B,OAAI,SAAS,KAAK,IAAI,SAAS;AAC/B,OAAI,SAAS,KAAK,IAAI,SAAS;;;AAIjC,QAAO"}
1
+ {"version":3,"file":"placeholder-CIJejMlK.mjs","names":[],"sources":["../src/media/normalize.ts","../src/media/placeholder.ts"],"sourcesContent":["/**\n * Media Value Normalization\n *\n * Normalizes media field values into a consistent shape regardless of\n * creation path (seed scripts, media picker, WP import, URL input).\n *\n * Called at content create/update time when a media provider is available,\n * filling in missing dimensions, storageKey, mimeType, and filename from\n * the provider's `get()` method.\n */\n\nimport type { MediaProvider, MediaProviderItem, MediaValue } from \"./types.js\";\n\nexport const INTERNAL_MEDIA_PREFIX = \"/_emdash/api/media/file/\";\nconst URL_PATTERN = /^https?:\\/\\//;\n\n/**\n * Normalize a media field value into a consistent MediaValue shape.\n *\n * - `null`/`undefined` → `null`\n * - Bare URL string → `{ provider: \"external\", id: \"\", src: url }`\n * - Bare internal media URL → resolved via local provider's `get()`\n * - Object with `provider` + `id` → enriched with missing fields from provider\n */\nexport async function normalizeMediaValue(\n\tvalue: unknown,\n\tgetProvider: (id: string) => MediaProvider | undefined,\n): Promise<MediaValue | null> {\n\tif (value == null) return null;\n\n\t// Bare string URL\n\tif (typeof value === \"string\") {\n\t\treturn normalizeStringUrl(value, getProvider);\n\t}\n\n\t// Not an object — can't normalize\n\tif (!isRecord(value)) return null;\n\n\t// Must have at least an id to be a valid media value\n\tif (!(\"id\" in value) && !(\"src\" in value)) return null;\n\n\tconst provider = (typeof value.provider === \"string\" ? value.provider : undefined) || \"local\";\n\tconst id = typeof value.id === \"string\" ? value.id : \"\";\n\n\t// External URLs — return as-is, no server-side dimension detection\n\tif (provider === \"external\") {\n\t\treturn recordToMediaValue(value);\n\t}\n\n\t// Build the base value from the input\n\tconst result: MediaValue = { ...recordToMediaValue(value), provider };\n\n\t// For local media, strip `src` — it's derived at display time from storageKey\n\tif (provider === \"local\") {\n\t\tdelete result.src;\n\t}\n\n\t// Determine if we need to call the provider\n\tconst needsDimensions = result.width == null || result.height == null;\n\tconst needsStorageKey = provider === \"local\" && !result.meta?.storageKey;\n\tconst needsFileInfo = !result.mimeType || !result.filename;\n\tconst needsLookup = needsDimensions || needsStorageKey || needsFileInfo;\n\n\tif (!needsLookup || !id) return result;\n\n\t// Try to enrich from provider\n\tconst mediaProvider = getProvider(provider);\n\tif (!mediaProvider?.get) return result;\n\n\tlet providerItem: MediaProviderItem | null;\n\ttry {\n\t\tproviderItem = await mediaProvider.get(id);\n\t} catch {\n\t\treturn result;\n\t}\n\n\tif (!providerItem) return result;\n\n\treturn mergeProviderData(result, providerItem);\n}\n\nfunction normalizeStringUrl(\n\turl: string,\n\tgetProvider: (id: string) => MediaProvider | undefined,\n): Promise<MediaValue | null> {\n\t// Internal media URL — try to resolve via local provider\n\tif (url.startsWith(INTERNAL_MEDIA_PREFIX)) {\n\t\treturn resolveInternalUrl(url, getProvider);\n\t}\n\n\t// External HTTP(S) URL\n\tif (URL_PATTERN.test(url)) {\n\t\treturn Promise.resolve({\n\t\t\tprovider: \"external\",\n\t\t\tid: \"\",\n\t\t\tsrc: url,\n\t\t});\n\t}\n\n\t// Unrecognized string — treat as external\n\treturn Promise.resolve({\n\t\tprovider: \"external\",\n\t\tid: \"\",\n\t\tsrc: url,\n\t});\n}\n\nasync function resolveInternalUrl(\n\turl: string,\n\tgetProvider: (id: string) => MediaProvider | undefined,\n): Promise<MediaValue> {\n\tconst storageKey = url.slice(INTERNAL_MEDIA_PREFIX.length);\n\tconst localProvider = getProvider(\"local\");\n\n\tif (!localProvider?.get) {\n\t\treturn { provider: \"external\", id: \"\", src: url };\n\t}\n\n\tlet item: MediaProviderItem | null;\n\ttry {\n\t\titem = await localProvider.get(storageKey);\n\t} catch {\n\t\treturn { provider: \"external\", id: \"\", src: url };\n\t}\n\n\tif (!item) {\n\t\treturn { provider: \"external\", id: \"\", src: url };\n\t}\n\n\treturn {\n\t\tprovider: \"local\",\n\t\tid: item.id,\n\t\tfilename: item.filename,\n\t\tmimeType: item.mimeType,\n\t\twidth: item.width,\n\t\theight: item.height,\n\t\talt: item.alt,\n\t\tmeta: item.meta,\n\t};\n}\n\n/**\n * Merge provider data into an existing MediaValue, preserving caller-supplied fields.\n * Caller `alt` takes priority over provider `alt` (per-usage, not per-image).\n */\nfunction mergeProviderData(existing: MediaValue, item: MediaProviderItem): MediaValue {\n\tconst result = { ...existing };\n\n\t// Fill missing dimensions\n\tif (result.width == null && item.width != null) result.width = item.width;\n\tif (result.height == null && item.height != null) result.height = item.height;\n\n\t// Fill missing file info\n\tif (!result.filename && item.filename) result.filename = item.filename;\n\tif (!result.mimeType && item.mimeType) result.mimeType = item.mimeType;\n\n\t// Fill missing alt (provider alt is fallback, not override)\n\tif (!result.alt && item.alt) result.alt = item.alt;\n\n\t// Fill missing meta (merge, don't replace)\n\tif (item.meta) {\n\t\tresult.meta = { ...item.meta, ...result.meta };\n\t}\n\n\treturn result;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Extract known MediaValue fields from a runtime-checked record.\n * Avoids unsafe `as MediaValue` cast by reading each property explicitly.\n */\nfunction recordToMediaValue(obj: Record<string, unknown>): MediaValue {\n\tconst result: MediaValue = {\n\t\tid: typeof obj.id === \"string\" ? obj.id : \"\",\n\t};\n\tif (typeof obj.provider === \"string\") result.provider = obj.provider;\n\tif (typeof obj.src === \"string\") result.src = obj.src;\n\tif (typeof obj.previewUrl === \"string\") result.previewUrl = obj.previewUrl;\n\tif (typeof obj.filename === \"string\") result.filename = obj.filename;\n\tif (typeof obj.mimeType === \"string\") result.mimeType = obj.mimeType;\n\tif (typeof obj.width === \"number\") result.width = obj.width;\n\tif (typeof obj.height === \"number\") result.height = obj.height;\n\tif (typeof obj.alt === \"string\") result.alt = obj.alt;\n\tif (isRecord(obj.meta)) result.meta = obj.meta;\n\treturn result;\n}\n","/**\n * Image Placeholder Generation\n *\n * Generates blurhash and dominant color from image buffers for LQIP support.\n * Decodes images via jpeg-js (pure JS) and upng-js (pure JS, uses pako for\n * deflate). No Node-specific dependencies — works in Workers and Node SSR.\n */\n\nimport { encode } from \"blurhash\";\nimport { imageSize } from \"image-size\";\n\nexport interface PlaceholderData {\n\tblurhash: string;\n\tdominantColor: string;\n}\n\nconst SUPPORTED_TYPES: Record<string, \"jpeg\" | \"png\"> = {\n\t\"image/jpeg\": \"jpeg\",\n\t\"image/jpg\": \"jpeg\",\n\t\"image/png\": \"png\",\n};\n\n/** Max width for blurhash input. Encode is O(w*h*components), so downsample first. */\nconst MAX_ENCODE_WIDTH = 32;\n\n/** Max decoded RGBA size (32 MB). Images exceeding this skip placeholder generation. */\nconst MAX_DECODED_BYTES = 32 * 1024 * 1024;\n\ninterface DecodedImage {\n\twidth: number;\n\theight: number;\n\tdata: Uint8Array;\n}\n\n/**\n * Decode a JPEG buffer into raw RGBA pixel data.\n */\nasync function decodeJpeg(buffer: Uint8Array): Promise<DecodedImage> {\n\tconst { decode } = await import(\"jpeg-js\");\n\tconst result = decode(buffer, { useTArray: true });\n\treturn { width: result.width, height: result.height, data: result.data };\n}\n\n/**\n * Decode a PNG buffer into raw RGBA pixel data.\n * Uses upng-js (pure JS with pako deflate) — no Node zlib dependency.\n */\nasync function decodePng(buffer: Uint8Array): Promise<DecodedImage> {\n\t// @ts-expect-error -- upng-js has no type declarations\n\tconst UPNG = (await import(\"upng-js\")).default;\n\tconst img = UPNG.decode(buffer.buffer);\n\t// toRGBA8 returns an array of frames; take the first frame\n\tconst frames: ArrayBuffer[] = UPNG.toRGBA8(img);\n\tconst rgba = new Uint8Array(frames[0]);\n\treturn { width: img.width, height: img.height, data: rgba };\n}\n\n/**\n * Extract the dominant color from RGBA pixel data.\n * Simple average of all non-transparent pixels.\n */\nfunction extractDominantColor(data: Uint8Array, width: number, height: number): string {\n\tlet r = 0;\n\tlet g = 0;\n\tlet b = 0;\n\tlet count = 0;\n\n\tconst len = width * height * 4;\n\tfor (let i = 0; i < len; i += 4) {\n\t\tconst a = data[i + 3];\n\t\tif (a < 128) continue; // skip mostly-transparent pixels\n\t\tr += data[i];\n\t\tg += data[i + 1];\n\t\tb += data[i + 2];\n\t\tcount++;\n\t}\n\n\tif (count === 0) return \"rgb(0,0,0)\";\n\n\tconst avgR = Math.round(r / count);\n\tconst avgG = Math.round(g / count);\n\tconst avgB = Math.round(b / count);\n\treturn `rgb(${avgR},${avgG},${avgB})`;\n}\n\n/**\n * Read image dimensions from headers without decoding pixel data.\n */\nfunction getImageDimensions(buffer: Uint8Array): { width: number; height: number } | null {\n\ttry {\n\t\tconst result = imageSize(buffer);\n\t\tif (result.width != null && result.height != null) {\n\t\t\treturn { width: result.width, height: result.height };\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Generate blurhash and dominant color from an image buffer.\n * Returns null for non-image MIME types or on failure.\n *\n * @param dimensions - Optional pre-known dimensions. Used as a fallback when\n * image-size cannot parse the buffer (e.g. truncated headers). When the\n * decoded size (width * height * 4) exceeds MAX_DECODED_BYTES, placeholder\n * generation is skipped to avoid OOM on memory-constrained runtimes.\n */\nexport async function generatePlaceholder(\n\tbuffer: Uint8Array,\n\tmimeType: string,\n\tdimensions?: { width: number; height: number },\n): Promise<PlaceholderData | null> {\n\tconst format = SUPPORTED_TYPES[mimeType];\n\tif (!format) return null;\n\n\ttry {\n\t\t// Safety net: skip decode if the image would exceed the memory budget\n\t\tconst dims = getImageDimensions(buffer) ?? dimensions;\n\t\tif (dims && dims.width * dims.height * 4 > MAX_DECODED_BYTES) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst imageData = format === \"jpeg\" ? await decodeJpeg(buffer) : await decodePng(buffer);\n\t\tconst { width, height, data } = imageData;\n\n\t\tif (width === 0 || height === 0) return null;\n\n\t\t// Downsample for blurhash encoding if needed\n\t\tlet encodePixels: Uint8ClampedArray;\n\t\tlet encodeWidth: number;\n\t\tlet encodeHeight: number;\n\n\t\tif (width > MAX_ENCODE_WIDTH) {\n\t\t\tconst scale = MAX_ENCODE_WIDTH / width;\n\t\t\tencodeWidth = MAX_ENCODE_WIDTH;\n\t\t\tencodeHeight = Math.max(1, Math.round(height * scale));\n\t\t\tencodePixels = downsample(data, width, height, encodeWidth, encodeHeight);\n\t\t} else {\n\t\t\tencodeWidth = width;\n\t\t\tencodeHeight = height;\n\t\t\tencodePixels = new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength);\n\t\t}\n\n\t\tconst blurhash = encode(encodePixels, encodeWidth, encodeHeight, 4, 3);\n\t\tconst dominantColor = extractDominantColor(data, width, height);\n\n\t\treturn { blurhash, dominantColor };\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Nearest-neighbor downsample of RGBA pixel data.\n */\nfunction downsample(\n\tsrc: Uint8Array,\n\tsrcW: number,\n\tsrcH: number,\n\tdstW: number,\n\tdstH: number,\n): Uint8ClampedArray {\n\tconst dst = new Uint8ClampedArray(dstW * dstH * 4);\n\n\tfor (let y = 0; y < dstH; y++) {\n\t\tconst srcY = Math.floor((y * srcH) / dstH);\n\t\tfor (let x = 0; x < dstW; x++) {\n\t\t\tconst srcX = Math.floor((x * srcW) /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7B,MAAM,QAAQ,mBAAmB;AACjC,iBAAc;AACd,kBAAe,KAAK,IAAI,GAAG,KAAK,MAAM,SAAS,MAAM,CAAC;AACtD,kBAAe,WAAW,MAAM,OAAO,QAAQ,aAAa,aAAa;SACnE;AACN,iBAAc;AACd,kBAAe;AACf,kBAAe,IAAI,kBAAkB,KAAK,QAAQ,KAAK,YAAY,KAAK,WAAW;;AAMpF,SAAO;GAAE,UAHQ,OAAO,cAAc,aAAa,cAAc,GAAG,EAAE;GAGnD,eAFG,qBAAqB,MAAM,OAAO,OAAO;GAE7B;SAC3B;AACP,SAAO;;;;;;AAOT,SAAS,WACR,KACA,MACA,MACA,MACA,MACoB;CACpB,MAAM,MAAM,IAAI,kBAAkB,OAAO,OAAO,EAAE;AAElD,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KAAK;EAC9B,MAAM,OAAO,KAAK,MAAO,IAAI,OAAQ,KAAK;AAC1C,OAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KAAK;GAC9B,MAAM,OAAO,KAAK,MAAO,IAAI,OAAQ,KAAK;GAC1C,MAAM,UAAU,OAAO,OAAO,QAAQ;GACtC,MAAM,UAAU,IAAI,OAAO,KAAK;AAChC,OAAI,UAAU,IAAI;AAClB,OAAI,SAAS,KAAK,IAAI,SAAS;AAC/B,OAAI,SAAS,KAAK,IAAI,SAAS;AAC/B,OAAI,SAAS,KAAK,IAAI,SAAS;;;AAIjC,QAAO"}
@@ -1,8 +1,8 @@
1
- import "../types-CS8FIX7L.mjs";
2
- import { mn as PluginDescriptor } from "../index-DIb-CzNx.mjs";
3
- import "../runner-OURCaApa.mjs";
4
- import { X as ResolvedPlugin, tt as StandardPluginDefinition } from "../types-i36XcA_X.mjs";
5
- import "../validate-DHxmpFJt.mjs";
1
+ import "../types-CrtWgIvl.mjs";
2
+ import { mn as PluginDescriptor } from "../index-BFRaVcD6.mjs";
3
+ import "../runner-Bnoj7vjK.mjs";
4
+ import { $ as ResolvedPlugin, it as StandardPluginDefinition } from "../types-BuBIptGk.mjs";
5
+ import "../validate-BfQh_C_y.mjs";
6
6
 
7
7
  //#region src/plugins/adapt-sandbox-entry.d.ts
8
8
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"adapt-sandbox-entry.d.mts","names":[],"sources":["../../src/plugins/adapt-sandbox-entry.ts"],"mappings":";;;;;;;;;;;;;;;;;;iBA+FgB,iBAAA,CACf,UAAA,EAAY,wBAAA,EACZ,UAAA,EAAY,gBAAA,GACV,cAAA"}
1
+ {"version":3,"file":"adapt-sandbox-entry.d.mts","names":[],"sources":["../../src/plugins/adapt-sandbox-entry.ts"],"mappings":";;;;;;;;;;;;;;;;;;iBAgGgB,iBAAA,CACf,UAAA,EAAY,wBAAA,EACZ,UAAA,EAAY,gBAAA,GACV,cAAA"}
@@ -1,4 +1,5 @@
1
- import { n as PLUGIN_CAPABILITIES, t as HOOK_NAMES } from "../manifest-schema-DH9xhc6t.mjs";
1
+ import { n as PLUGIN_CAPABILITIES, t as HOOK_NAMES } from "../manifest-schema-DqWNC3lM.mjs";
2
+ import { i as normalizeCapabilities } from "../types-4fVtCIm0.mjs";
2
3
 
3
4
  //#region src/plugins/adapt-sandbox-entry.ts
4
5
  /**
@@ -82,11 +83,11 @@ function adaptSandboxEntry(definition, descriptor) {
82
83
  }
83
84
  const rawCapabilities = descriptor.capabilities ?? [];
84
85
  for (const cap of rawCapabilities) if (!VALID_CAPABILITIES_SET.has(cap)) throw new Error(`Invalid capability "${cap}" in plugin "${pluginId}". Valid capabilities: ${[...VALID_CAPABILITIES_SET].join(", ")}`);
85
- const capabilities = [...rawCapabilities];
86
+ const capabilities = normalizeCapabilities(rawCapabilities);
86
87
  const allowedHosts = descriptor.allowedHosts ?? [];
87
- if (capabilities.includes("write:content") && !capabilities.includes("read:content")) capabilities.push("read:content");
88
- if (capabilities.includes("write:media") && !capabilities.includes("read:media")) capabilities.push("read:media");
89
- if (capabilities.includes("network:fetch:any") && !capabilities.includes("network:fetch")) capabilities.push("network:fetch");
88
+ if (capabilities.includes("content:write") && !capabilities.includes("content:read")) capabilities.push("content:read");
89
+ if (capabilities.includes("media:write") && !capabilities.includes("media:read")) capabilities.push("media:read");
90
+ if (capabilities.includes("network:request:unrestricted") && !capabilities.includes("network:request")) capabilities.push("network:request");
90
91
  const rawStorage = descriptor.storage ?? {};
91
92
  const storage = {};
92
93
  for (const [name, config] of Object.entries(rawStorage)) storage[name] = {
@@ -1 +1 @@
1
- {"version":3,"file":"adapt-sandbox-entry.mjs","names":[],"sources":["../../src/plugins/adapt-sandbox-entry.ts"],"sourcesContent":["/**\n * In-Process Adapter for Standard-Format Plugins\n *\n * Converts a standard plugin definition ({ hooks, routes }) into a\n * ResolvedPlugin compatible with HookPipeline. This allows standard-format\n * plugins to run in-process when placed in the `plugins: []` config array.\n *\n * The adapter wraps each hook and route handler so that the PluginContextFactory\n * provides the same capability-gated context as the native path.\n *\n */\n\nimport type { PluginDescriptor } from \"../astro/integration/runtime.js\";\nimport { PLUGIN_CAPABILITIES, HOOK_NAMES } from \"./manifest-schema.js\";\nimport type {\n\tStandardPluginDefinition,\n\tStandardHookEntry,\n\tStandardHookHandler,\n\tResolvedPlugin,\n\tResolvedPluginHooks,\n\tResolvedHook,\n\tPluginRoute,\n\tPluginCapability,\n\tPluginStorageConfig,\n\tPluginAdminConfig,\n} from \"./types.js\";\n\n/**\n * Default hook configuration values\n */\nconst DEFAULT_PRIORITY = 100;\nconst DEFAULT_TIMEOUT = 5000;\nconst DEFAULT_ERROR_POLICY = \"abort\" as const;\n\n/**\n * Check if a standard hook entry is a config object (has a `handler` property)\n */\nfunction isHookConfig(\n\tentry: StandardHookEntry,\n): entry is Exclude<StandardHookEntry, StandardHookHandler> {\n\treturn typeof entry === \"object\" && entry !== null && \"handler\" in entry;\n}\n\n/**\n * Resolve a single standard hook entry to a ResolvedHook.\n *\n * Standard-format hooks use the sandbox entry convention:\n * handler(event, ctx) -- two args\n *\n * The HookPipeline dispatch methods also call handlers with (event, ctx),\n * so the handler is compatible as-is. We just need to wrap it for type safety.\n */\nfunction resolveStandardHook(\n\tentry: StandardHookEntry,\n\tpluginId: string,\n): ResolvedHook<StandardHookHandler> {\n\tif (isHookConfig(entry)) {\n\t\treturn {\n\t\t\tpriority: entry.priority ?? DEFAULT_PRIORITY,\n\t\t\ttimeout: entry.timeout ?? DEFAULT_TIMEOUT,\n\t\t\tdependencies: entry.dependencies ?? [],\n\t\t\terrorPolicy: entry.errorPolicy ?? DEFAULT_ERROR_POLICY,\n\t\t\texclusive: entry.exclusive ?? false,\n\t\t\thandler: entry.handler,\n\t\t\tpluginId,\n\t\t};\n\t}\n\n\t// Bare function handler\n\treturn {\n\t\tpriority: DEFAULT_PRIORITY,\n\t\ttimeout: DEFAULT_TIMEOUT,\n\t\tdependencies: [],\n\t\terrorPolicy: DEFAULT_ERROR_POLICY,\n\t\texclusive: false,\n\t\thandler: entry,\n\t\tpluginId,\n\t};\n}\n\nconst VALID_CAPABILITIES_SET = new Set<string>(PLUGIN_CAPABILITIES);\n\nconst VALID_HOOK_NAMES_SET = new Set<string>(HOOK_NAMES);\n\n/**\n * Adapt a standard-format plugin definition into a ResolvedPlugin.\n *\n * This is the core of the unified plugin format. It takes the `{ hooks, routes }`\n * export from a standard plugin and produces a ResolvedPlugin that can enter the\n * HookPipeline alongside native plugins.\n *\n * @param definition - The standard plugin definition (from definePlugin() or raw export)\n * @param descriptor - The plugin descriptor with id, version, capabilities, etc.\n * @returns A ResolvedPlugin compatible with HookPipeline\n */\nexport function adaptSandboxEntry(\n\tdefinition: StandardPluginDefinition,\n\tdescriptor: PluginDescriptor,\n): ResolvedPlugin {\n\tconst pluginId = descriptor.id;\n\tconst version = descriptor.version;\n\n\t// Resolve hooks\n\tconst resolvedHooks: ResolvedPluginHooks = {};\n\tif (definition.hooks) {\n\t\tfor (const [hookName, entry] of Object.entries(definition.hooks)) {\n\t\t\tif (!VALID_HOOK_NAMES_SET.has(hookName)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Plugin \"${pluginId}\" declares unknown hook \"${hookName}\". ` +\n\t\t\t\t\t\t`Valid hooks: ${[...VALID_HOOK_NAMES_SET].join(\", \")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// The resolved hook has the correct handler type for the hook name.\n\t\t\t// We store it as the generic type and let HookPipeline's typed dispatch\n\t\t\t// methods handle the type narrowing at call time.\n\t\t\t// eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- bridging untyped map to typed interface\n\t\t\t(resolvedHooks as Record<string, unknown>)[hookName] = resolveStandardHook(entry, pluginId);\n\t\t}\n\t}\n\n\t// Resolve routes: standard format uses (routeCtx, pluginCtx) two-arg pattern.\n\t// Native format uses (ctx: RouteContext) single-arg pattern where RouteContext\n\t// extends PluginContext with { input, request, requestMeta }.\n\t// We wrap standard route handlers to merge the two args into one.\n\tconst resolvedRoutes: Record<string, PluginRoute> = {};\n\tif (definition.routes) {\n\t\tfor (const [routeName, routeEntry] of Object.entries(definition.routes)) {\n\t\t\tconst standardHandler = routeEntry.handler;\n\t\t\tresolvedRoutes[routeName] = {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- StandardRouteEntry.input is intentionally loosely typed; callers validate at runtime\n\t\t\t\tinput: routeEntry.input as PluginRoute[\"input\"],\n\t\t\t\tpublic: routeEntry.public,\n\t\t\t\thandler: async (ctx) => {\n\t\t\t\t\t// Build the routeCtx shape that standard handlers expect\n\t\t\t\t\tconst routeCtx = {\n\t\t\t\t\t\tinput: ctx.input,\n\t\t\t\t\t\trequest: ctx.request,\n\t\t\t\t\t\trequestMeta: ctx.requestMeta,\n\t\t\t\t\t};\n\t\t\t\t\t// Pass only the PluginContext portion (without input/request/requestMeta)\n\t\t\t\t\t// to match what sandboxed handlers receive.\n\t\t\t\t\tconst { input: _, request: __, requestMeta: ___, ...pluginCtx } = ctx;\n\t\t\t\t\treturn standardHandler(routeCtx, pluginCtx);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\t// Build capabilities from descriptor.\n\t// Validate against the known set (same as defineNativePlugin).\n\tconst rawCapabilities = descriptor.capabilities ?? [];\n\tfor (const cap of rawCapabilities) {\n\t\tif (!VALID_CAPABILITIES_SET.has(cap)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid capability \"${cap}\" in plugin \"${pluginId}\". ` +\n\t\t\t\t\t`Valid capabilities: ${[...VALID_CAPABILITIES_SET].join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- validated against VALID_CAPABILITIES_SET above; descriptor uses string[] for flexibility\n\tconst capabilities = [...rawCapabilities] as PluginCapability[];\n\tconst allowedHosts = descriptor.allowedHosts ?? [];\n\n\t// Capability implications: broader capabilities imply narrower ones\n\t// (mirrors the normalization in define-plugin.ts for native format)\n\tif (capabilities.includes(\"write:content\") && !capabilities.includes(\"read:content\")) {\n\t\tcapabilities.push(\"read:content\");\n\t}\n\tif (capabilities.includes(\"write:media\") && !capabilities.includes(\"read:media\")) {\n\t\tcapabilities.push(\"read:media\");\n\t}\n\tif (capabilities.includes(\"network:fetch:any\") && !capabilities.includes(\"network:fetch\")) {\n\t\tcapabilities.push(\"network:fetch\");\n\t}\n\n\t// Build storage config from descriptor.\n\t// StorageCollectionDeclaration uses optional indexes, but PluginStorageConfig\n\t// requires them. Ensure every collection has an indexes array.\n\tconst rawStorage = descriptor.storage ?? {};\n\tconst storage: PluginStorageConfig = {};\n\tfor (const [name, config] of Object.entries(rawStorage)) {\n\t\tstorage[name] = {\n\t\t\tindexes: config.indexes ?? [],\n\t\t\tuniqueIndexes: config.uniqueIndexes,\n\t\t};\n\t}\n\n\t// Build admin config from descriptor\n\tconst admin: PluginAdminConfig = {};\n\tif (descriptor.adminPages) {\n\t\tadmin.pages = descriptor.adminPages;\n\t}\n\tif (descriptor.adminWidgets) {\n\t\tadmin.widgets = descriptor.adminWidgets;\n\t}\n\n\treturn {\n\t\tid: pluginId,\n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sources":["../../src/plugins/adapt-sandbox-entry.ts"],"sourcesContent":["/**\n * In-Process Adapter for Standard-Format Plugins\n *\n * Converts a standard plugin definition ({ hooks, routes }) into a\n * ResolvedPlugin compatible with HookPipeline. This allows standard-format\n * plugins to run in-process when placed in the `plugins: []` config array.\n *\n * The adapter wraps each hook and route handler so that the PluginContextFactory\n * provides the same capability-gated context as the native path.\n *\n */\n\nimport type { PluginDescriptor } from \"../astro/integration/runtime.js\";\nimport { PLUGIN_CAPABILITIES, HOOK_NAMES } from \"./manifest-schema.js\";\nimport { normalizeCapabilities } from \"./types.js\";\nimport type {\n\tStandardPluginDefinition,\n\tStandardHookEntry,\n\tStandardHookHandler,\n\tResolvedPlugin,\n\tResolvedPluginHooks,\n\tResolvedHook,\n\tPluginRoute,\n\tPluginCapability,\n\tPluginStorageConfig,\n\tPluginAdminConfig,\n} from \"./types.js\";\n\n/**\n * Default hook configuration values\n */\nconst DEFAULT_PRIORITY = 100;\nconst DEFAULT_TIMEOUT = 5000;\nconst DEFAULT_ERROR_POLICY = \"abort\" as const;\n\n/**\n * Check if a standard hook entry is a config object (has a `handler` property)\n */\nfunction isHookConfig(\n\tentry: StandardHookEntry,\n): entry is Exclude<StandardHookEntry, StandardHookHandler> {\n\treturn typeof entry === \"object\" && entry !== null && \"handler\" in entry;\n}\n\n/**\n * Resolve a single standard hook entry to a ResolvedHook.\n *\n * Standard-format hooks use the sandbox entry convention:\n * handler(event, ctx) -- two args\n *\n * The HookPipeline dispatch methods also call handlers with (event, ctx),\n * so the handler is compatible as-is. We just need to wrap it for type safety.\n */\nfunction resolveStandardHook(\n\tentry: StandardHookEntry,\n\tpluginId: string,\n): ResolvedHook<StandardHookHandler> {\n\tif (isHookConfig(entry)) {\n\t\treturn {\n\t\t\tpriority: entry.priority ?? DEFAULT_PRIORITY,\n\t\t\ttimeout: entry.timeout ?? DEFAULT_TIMEOUT,\n\t\t\tdependencies: entry.dependencies ?? [],\n\t\t\terrorPolicy: entry.errorPolicy ?? DEFAULT_ERROR_POLICY,\n\t\t\texclusive: entry.exclusive ?? false,\n\t\t\thandler: entry.handler,\n\t\t\tpluginId,\n\t\t};\n\t}\n\n\t// Bare function handler\n\treturn {\n\t\tpriority: DEFAULT_PRIORITY,\n\t\ttimeout: DEFAULT_TIMEOUT,\n\t\tdependencies: [],\n\t\terrorPolicy: DEFAULT_ERROR_POLICY,\n\t\texclusive: false,\n\t\thandler: entry,\n\t\tpluginId,\n\t};\n}\n\nconst VALID_CAPABILITIES_SET = new Set<string>(PLUGIN_CAPABILITIES);\n\nconst VALID_HOOK_NAMES_SET = new Set<string>(HOOK_NAMES);\n\n/**\n * Adapt a standard-format plugin definition into a ResolvedPlugin.\n *\n * This is the core of the unified plugin format. It takes the `{ hooks, routes }`\n * export from a standard plugin and produces a ResolvedPlugin that can enter the\n * HookPipeline alongside native plugins.\n *\n * @param definition - The standard plugin definition (from definePlugin() or raw export)\n * @param descriptor - The plugin descriptor with id, version, capabilities, etc.\n * @returns A ResolvedPlugin compatible with HookPipeline\n */\nexport function adaptSandboxEntry(\n\tdefinition: StandardPluginDefinition,\n\tdescriptor: PluginDescriptor,\n): ResolvedPlugin {\n\tconst pluginId = descriptor.id;\n\tconst version = descriptor.version;\n\n\t// Resolve hooks\n\tconst resolvedHooks: ResolvedPluginHooks = {};\n\tif (definition.hooks) {\n\t\tfor (const [hookName, entry] of Object.entries(definition.hooks)) {\n\t\t\tif (!VALID_HOOK_NAMES_SET.has(hookName)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Plugin \"${pluginId}\" declares unknown hook \"${hookName}\". ` +\n\t\t\t\t\t\t`Valid hooks: ${[...VALID_HOOK_NAMES_SET].join(\", \")}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// The resolved hook has the correct handler type for the hook name.\n\t\t\t// We store it as the generic type and let HookPipeline's typed dispatch\n\t\t\t// methods handle the type narrowing at call time.\n\t\t\t// eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- bridging untyped map to typed interface\n\t\t\t(resolvedHooks as Record<string, unknown>)[hookName] = resolveStandardHook(entry, pluginId);\n\t\t}\n\t}\n\n\t// Resolve routes: standard format uses (routeCtx, pluginCtx) two-arg pattern.\n\t// Native format uses (ctx: RouteContext) single-arg pattern where RouteContext\n\t// extends PluginContext with { input, request, requestMeta }.\n\t// We wrap standard route handlers to merge the two args into one.\n\tconst resolvedRoutes: Record<string, PluginRoute> = {};\n\tif (definition.routes) {\n\t\tfor (const [routeName, routeEntry] of Object.entries(definition.routes)) {\n\t\t\tconst standardHandler = routeEntry.handler;\n\t\t\tresolvedRoutes[routeName] = {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- StandardRouteEntry.input is intentionally loosely typed; callers validate at runtime\n\t\t\t\tinput: routeEntry.input as PluginRoute[\"input\"],\n\t\t\t\tpublic: routeEntry.public,\n\t\t\t\thandler: async (ctx) => {\n\t\t\t\t\t// Build the routeCtx shape that standard handlers expect\n\t\t\t\t\tconst routeCtx = {\n\t\t\t\t\t\tinput: ctx.input,\n\t\t\t\t\t\trequest: ctx.request,\n\t\t\t\t\t\trequestMeta: ctx.requestMeta,\n\t\t\t\t\t};\n\t\t\t\t\t// Pass only the PluginContext portion (without input/request/requestMeta)\n\t\t\t\t\t// to match what sandboxed handlers receive.\n\t\t\t\t\tconst { input: _, request: __, requestMeta: ___, ...pluginCtx } = ctx;\n\t\t\t\t\treturn standardHandler(routeCtx, pluginCtx);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\t// Build capabilities from descriptor.\n\t// Validate against the known set (same as defineNativePlugin). Both\n\t// current and deprecated names are accepted; deprecated names are\n\t// silently normalized to current names below so the runtime only ever\n\t// sees the canonical form.\n\tconst rawCapabilities = descriptor.capabilities ?? [];\n\tfor (const cap of rawCapabilities) {\n\t\tif (!VALID_CAPABILITIES_SET.has(cap)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid capability \"${cap}\" in plugin \"${pluginId}\". ` +\n\t\t\t\t\t`Valid capabilities: ${[...VALID_CAPABILITIES_SET].join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t// Silent normalization: rewrite deprecated names to current names.\n\t// Safe assertion — `normalizeCapabilities` only emits validated input\n\t// plus current names from the rename map, all of which are in the union.\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- validated above; normalizeCapabilities only returns capabilities from the union\n\tconst capabilities = normalizeCapabilities(rawCapabilities) as PluginCapability[];\n\tconst allowedHosts = descriptor.allowedHosts ?? [];\n\n\t// Capability implications: broader capabilities imply narrower ones\n\t// (mirrors the normalization in define-plugin.ts for native format).\n\t// Operates on canonical names only.\n\tif (capabilities.includes(\"content:write\") && !capabilities.includes(\"content:read\")) {\n\t\tcapabilities.push(\"content:read\");\n\t}\n\tif (capabilities.includes(\"media:write\") && !capabilities.includes(\"media:read\")) {\n\t\tcapabilities.push(\"media:read\");\n\t}\n\tif (\n\t\tcapabilities.includes(\"network:request:unrestricted\") &&\n\t\t!capabilities.includes(\"network:request\")\n\t) {\n\t\tcapabilities.push(\"network:request\");\n\t}\n\n\t// Build storage config from descriptor.\n\t// StorageCollectionDeclaration uses optional indexes, but PluginStorageConfig\n\t// requires them. Ensure every collection has an indexes array.\n\tconst rawStorage = descriptor.storage ?? {};\n\tconst storage: PluginStorageConfig = {};\n\tfor (const [name, config] of Object.entries(rawStorage)) {\n\t\tstorage[name] = {\n\t\t\tindexes: config.indexes ?? [],\n\t\t\tuniqueIndexes: config.uniqueIndexes,\n\t\t};\n\t}\n\n\t// Build admin config from descriptor\n\tconst admin: PluginAdminConfig = {};\n\tif (descriptor.adminPages) {\n\t\tadmin.pages = descriptor.adminPages;\n\t}\n\tif (descriptor.adminWidgets) {\n\t\tadmin.widgets = descriptor.adminWidgets;\n\t}\n\n\treturn {\n\t\tid: pluginId,\n\t\tversion,\n\t\tcapabilities,\n\t\tallowedHosts,\n\t\tstorage,\n\t\thooks: resolvedHooks,\n\t\troutes: resolvedR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AW;KAChB,OAAO,IAAI;KACX,SAAS,IAAI;KACb,aAAa,IAAI;KACjB;IAGD,MAAM,EAAE,OAAO,GAAG,SAAS,IAAI,aAAa,KAAK,GAAG,cAAc;AAClE,WAAO,gBAAgB,UAAU,UAAU;;GAE5C;;CASH,MAAM,kBAAkB,WAAW,gBAAgB,EAAE;AACrD,MAAK,MAAM,OAAO,gBACjB,KAAI,CAAC,uBAAuB,IAAI,IAAI,CACnC,OAAM,IAAI,MACT,uBAAuB,IAAI,eAAe,SAAS,yBAC3B,CAAC,GAAG,uBAAuB,CAAC,KAAK,KAAK,GAC9D;CAQH,MAAM,eAAe,sBAAsB,gBAAgB;CAC3D,MAAM,eAAe,WAAW,gBAAgB,EAAE;AAKlD,KAAI,aAAa,SAAS,gBAAgB,IAAI,CAAC,aAAa,SAAS,eAAe,CACnF,cAAa,KAAK,eAAe;AAElC,KAAI,aAAa,SAAS,cAAc,IAAI,CAAC,aAAa,SAAS,aAAa,CAC/E,cAAa,KAAK,aAAa;AAEhC,KACC,aAAa,SAAS,+BAA+B,IACrD,CAAC,aAAa,SAAS,kBAAkB,CAEzC,cAAa,KAAK,kBAAkB;CAMrC,MAAM,aAAa,WAAW,WAAW,EAAE;CAC3C,MAAM,UAA+B,EAAE;AACvC,MAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,WAAW,CACtD,SAAQ,QAAQ;EACf,SAAS,OAAO,WAAW,EAAE;EAC7B,eAAe,OAAO;EACtB;CAIF,MAAM,QAA2B,EAAE;AACnC,KAAI,WAAW,WACd,OAAM,QAAQ,WAAW;AAE1B,KAAI,WAAW,aACd,OAAM,UAAU,WAAW;AAG5B,QAAO;EACN,IAAI;EACJ;EACA;EACA;EACA;EACA,OAAO;EACP,QAAQ;EACR;EACA"}
@@ -0,0 +1,51 @@
1
+ //#region src/api/public-url.ts
2
+ /**
3
+ * Resolve siteUrl from runtime environment variables.
4
+ *
5
+ * Uses process.env (not import.meta.env) because Vite statically replaces
6
+ * import.meta.env at build time, baking out any env vars not present during
7
+ * the build. Container deployments set env vars at runtime, so we must read
8
+ * process.env which Vite leaves untouched.
9
+ *
10
+ * On Cloudflare Workers process.env is unavailable (returns undefined),
11
+ * so the fallback chain continues to url.origin.
12
+ *
13
+ * Caches after first call.
14
+ */
15
+ let _envSiteUrl = null;
16
+ function getEnvSiteUrl() {
17
+ if (_envSiteUrl !== null) return _envSiteUrl || void 0;
18
+ try {
19
+ const value = typeof process !== "undefined" && process.env?.EMDASH_SITE_URL || typeof process !== "undefined" && process.env?.SITE_URL || "";
20
+ if (value) {
21
+ const parsed = new URL(value);
22
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
23
+ _envSiteUrl = "";
24
+ return;
25
+ }
26
+ _envSiteUrl = parsed.origin;
27
+ } else _envSiteUrl = "";
28
+ } catch {
29
+ _envSiteUrl = "";
30
+ }
31
+ return _envSiteUrl || void 0;
32
+ }
33
+ /**
34
+ * Return the public-facing origin for the site.
35
+ *
36
+ * Resolution order:
37
+ * 1. `config.siteUrl` (set in astro.config.mjs, origin-normalized at startup)
38
+ * 2. `EMDASH_SITE_URL` or `SITE_URL` env var (resolved at runtime for containers)
39
+ * 3. `url.origin` (internal request URL — correct when no proxy)
40
+ *
41
+ * @param url The request URL (`new URL(request.url)` or `Astro.url`)
42
+ * @param config The EmDash config (from `locals.emdash?.config`)
43
+ * @returns Origin string, e.g. `"https://mysite.example.com"`
44
+ */
45
+ function getPublicOrigin(url, config) {
46
+ return config?.siteUrl || getEnvSiteUrl() || url.origin;
47
+ }
48
+
49
+ //#endregion
50
+ export { getPublicOrigin as t };
51
+ //# sourceMappingURL=public-url-DByxYjUw.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"public-url-DByxYjUw.mjs","names":[],"sources":["../src/api/public-url.ts"],"sourcesContent":["/**\n * Public URL helpers for reverse-proxy deployments.\n *\n * Behind a TLS-terminating proxy the internal request URL\n * (`http://localhost:4321`) differs from the browser-facing origin\n * (`https://mysite.example.com`). These pure helpers resolve the\n * correct public origin from config, falling back to the request URL.\n *\n * Workers-safe: no Node.js imports.\n */\n\n/** Minimal config shape — avoids importing the full EmDashConfig type tree. */\ninterface SiteUrlConfig {\n\tsiteUrl?: string;\n}\n\n/**\n * Resolve siteUrl from runtime environment variables.\n *\n * Uses process.env (not import.meta.env) because Vite statically replaces\n * import.meta.env at build time, baking out any env vars not present during\n * the build. Container deployments set env vars at runtime, so we must read\n * process.env which Vite leaves untouched.\n *\n * On Cloudflare Workers process.env is unavailable (returns undefined),\n * so the fallback chain continues to url.origin.\n *\n * Caches after first call.\n */\nlet _envSiteUrl: string | undefined | null = null;\n\n/** @internal Reset cached env values — test-only. */\nexport function _resetEnvCache(): void {\n\t_envSiteUrl = null;\n\t_envAllowedOrigins = null;\n}\n\nfunction getEnvSiteUrl(): string | undefined {\n\tif (_envSiteUrl !== null) return _envSiteUrl || undefined;\n\ttry {\n\t\t// process.env is available on Node.js; undefined on Workers\n\t\tconst value =\n\t\t\t(typeof process !== \"undefined\" && process.env?.EMDASH_SITE_URL) ||\n\t\t\t(typeof process !== \"undefined\" && process.env?.SITE_URL) ||\n\t\t\t\"\";\n\t\tif (value) {\n\t\t\tconst parsed = new URL(value);\n\t\t\tif (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n\t\t\t\t_envSiteUrl = \"\";\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\t_envSiteUrl = parsed.origin;\n\t\t} else {\n\t\t\t_envSiteUrl = \"\";\n\t\t}\n\t} catch {\n\t\t_envSiteUrl = \"\";\n\t}\n\treturn _envSiteUrl || undefined;\n}\n\n/**\n * Return the public-facing origin for the site.\n *\n * Resolution order:\n * 1. `config.siteUrl` (set in astro.config.mjs, origin-normalized at startup)\n * 2. `EMDASH_SITE_URL` or `SITE_URL` env var (resolved at runtime for containers)\n * 3. `url.origin` (internal request URL — correct when no proxy)\n *\n * @param url The request URL (`new URL(request.url)` or `Astro.url`)\n * @param config The EmDash config (from `locals.emdash?.config`)\n * @returns Origin string, e.g. `\"https://mysite.example.com\"`\n */\nexport function getPublicOrigin(url: URL, config?: SiteUrlConfig): string {\n\treturn config?.siteUrl || getEnvSiteUrl() || url.origin;\n}\n\n/**\n * Resolve additional accepted passkey origins from runtime environment.\n *\n * Reads `EMDASH_ALLOWED_ORIGINS` (comma-separated list of origins) for\n * multi-origin deployments where the same RP is reachable under several\n * hostnames sharing the registrable parent domain (e.g. apex + preview).\n *\n * Each entry is parsed via `new URL()` and reduced to its `origin`. Unlike\n * `getEnvSiteUrl` (which silently falls back to `url.origin` on bad input),\n * this throws on any unparseable or non-http(s) entry — `EMDASH_ALLOWED_ORIGINS`\n * is an allowlist for passkey verification, so silently dropping a typo would\n * surface as \"I can't authenticate on this origin\" with no diagnostic. Fail\n * loud at first read.\n *\n * Uses `process.env` (Vite leaves it untouched at runtime). Result is cached\n * on success.\n */\nlet _envAllowedOrigins: string[] | null = null;\n\nexport function getEnvAllowedOrigins(): string[] {\n\tif (_envAllowedOrigins !== null) return _envAllowedOrigins;\n\tconst raw = typeof process !== \"undefined\" ? process.env?.EMDASH_ALLOWED_ORIGINS || \"\" : \"\";\n\tconst parsed: string[] = [];\n\tfor (const entry of raw.split(\",\")) {\n\t\tconst trimmed = entry.trim();\n\t\tif (!trimmed) continue;\n\t\tlet u: URL;\n\t\ttry {\n\t\t\tu = new URL(trimmed);\n\t\t} catch (e) {\n\t\t\tthrow new Error(`EmDash config error in EMDASH_ALLOWED_ORIGINS: invalid URL: \"${trimmed}\"`, {\n\t\t\t\tcause: e,\n\t\t\t});\n\t\t}\n\t\tif (u.protocol !== \"http:\" && u.protocol !== \"https:\") {\n\t\t\tthrow new Error(\n\t\t\t\t`EmDash config error in EMDASH_ALLOWED_ORIGINS: origin must be http or https: \"${trimmed}\" (got ${u.protocol})`,\n\t\t\t);\n\t\t}\n\t\tparsed.push(u.origin);\n\t}\n\t_envAllowedOrigins = parsed;\n\treturn parsed;\n}\n\n/**\n * Build a full public URL by appending a path to the public origin.\n *\n * @param url The request URL\n * @param config The EmDash config\n * @param path Path to append (must start with `/`)\n * @returns Full URL string, e.g. `\"https://mysite.example.com/_emdash/admin/login\"`\n */\nexport function getPublicUrl(url: URL, config: SiteUrlConfig | undefined, path: string): string {\n\treturn `${getPublicOrigin(url, config)}${path}`;\n}\n"],"mappings":";;;;;;;;;;;;;;AA6BA,IAAI,cAAyC;AAQ7C,SAAS,gBAAoC;AAC5C,KAAI,gBAAgB,KAAM,QAAO,eAAe;AAChD,KAAI;EAEH,MAAM,QACJ,OAAO,YAAY,eAAe,QAAQ,KAAK,mBAC/C,OAAO,YAAY,eAAe,QAAQ,KAAK,YAChD;AACD,MAAI,OAAO;GACV,MAAM,SAAS,IAAI,IAAI,MAAM;AAC7B,OAAI,OAAO,aAAa,WAAW,OAAO,aAAa,UAAU;AAChE,kBAAc;AACd;;AAED,iBAAc,OAAO;QAErB,eAAc;SAER;AACP,gBAAc;;AAEf,QAAO,eAAe;;;;;;;;;;;;;;AAevB,SAAgB,gBAAgB,KAAU,QAAgC;AACzE,QAAO,QAAQ,WAAW,eAAe,IAAI,IAAI"}
@@ -1,8 +1,10 @@
1
- import { t as __exportAll } from "./chunk-ClPoSABd.mjs";
1
+ import { i as __exportAll } from "./runner-C7ADox5q.mjs";
2
2
  import { getRequestContext } from "./request-context.mjs";
3
- import { n as getI18nConfig, r as isI18nEnabled, t as getFallbackChain } from "./config-BXwuX8Bx.mjs";
4
- import { t as isMissingTableError } from "./db-errors-l1Qh2RPR.mjs";
5
- import { n as requestCached } from "./request-cache-Ci7f5pBb.mjs";
3
+ import { i as encodeCursor } from "./types-CRxNbK-Z.mjs";
4
+ import { n as getI18nConfig, r as isI18nEnabled, t as getFallbackChain } from "./config-BI0V3ICQ.mjs";
5
+ import { t as isMissingTableError } from "./db-errors-WRezodiz.mjs";
6
+ import { t as CURSOR_RAW_VALUES } from "./loader-CKLbBnhK.mjs";
7
+ import { n as requestCached } from "./request-cache-B-bmkipQ.mjs";
6
8
 
7
9
  //#region src/visual-editing/editable.ts
8
10
  /**
@@ -74,12 +76,14 @@ function createNoop() {
74
76
  * and sets the context; query functions read it automatically.
75
77
  */
76
78
  var query_exports = /* @__PURE__ */ __exportAll({
79
+ bucketFilter: () => bucketFilter,
77
80
  getEditMeta: () => getEditMeta,
78
81
  getEmDashCollection: () => getEmDashCollection,
79
82
  getEmDashEntry: () => getEmDashEntry,
80
83
  getTranslations: () => getTranslations,
81
84
  invalidateUrlPatternCache: () => invalidateUrlPatternCache,
82
- resolveEmDashPath: () => resolveEmDashPath
85
+ resolveEmDashPath: () => resolveEmDashPath,
86
+ sliceCollectionResult: () => sliceCollectionResult
83
87
  });
84
88
  const COLLECTION_NAME = "_emdash";
85
89
  /** Symbol key for edit metadata on PT arrays — avoids collision with user data */
@@ -169,7 +173,94 @@ function entryEditOptions(entry) {
169
173
  * ```
170
174
  */
171
175
  async function getEmDashCollection(type, filter) {
172
- return requestCached(collectionCacheKey(type, filter), () => getEmDashCollectionUncached(type, filter));
176
+ const bucketed = bucketFilter(filter);
177
+ const cached = await requestCached(collectionCacheKey(type, bucketed.fetchFilter), () => getEmDashCollectionUncached(type, bucketed.fetchFilter));
178
+ return bucketed.requestedLimit === void 0 ? cached : sliceCollectionResult(cached, bucketed.requestedLimit, filter?.orderBy);
179
+ }
180
+ /**
181
+ * Threshold for limit bucketing. Page templates routinely render small
182
+ * "recent posts" widgets at limits 3-8; rounding those up to a single
183
+ * shared bucket lets one fetch satisfy several widgets within a request.
184
+ * Above this, the requested limit is honoured exactly — bucketing limit:50
185
+ * to limit:64 would waste hydration work for callers fetching real pages.
186
+ */
187
+ const BUCKET_LIMIT_THRESHOLD = 10;
188
+ /** @internal exported for unit tests; not part of the public API. */
189
+ function bucketFilter(filter) {
190
+ const limit = filter?.limit;
191
+ if (limit === void 0 || limit >= BUCKET_LIMIT_THRESHOLD || limit <= 0 || filter?.cursor !== void 0) return {
192
+ fetchFilter: filter,
193
+ requestedLimit: void 0
194
+ };
195
+ return {
196
+ fetchFilter: {
197
+ ...filter,
198
+ limit: BUCKET_LIMIT_THRESHOLD
199
+ },
200
+ requestedLimit: limit
201
+ };
202
+ }
203
+ /**
204
+ * Slice a cached bucketed result down to the originally-requested limit
205
+ * and recompute `nextCursor` from the row that would have been the
206
+ * over-fetch detector for that limit. When truncation is needed, returns
207
+ * a shallow-copied result with a new `entries` array; otherwise returns
208
+ * the cached result unchanged (including error results and results
209
+ * already within the requested limit).
210
+ */
211
+ /** @internal exported for unit tests; not part of the public API. */
212
+ function sliceCollectionResult(cached, limit, orderBy) {
213
+ if (cached.error) return cached;
214
+ if (cached.entries.length <= limit) return cached;
215
+ const sliced = cached.entries.slice(0, limit);
216
+ const lastEntry = sliced.at(-1);
217
+ const nextCursor = lastEntry ? encodeEntryCursor(lastEntry, orderBy) : void 0;
218
+ return {
219
+ ...cached,
220
+ entries: sliced,
221
+ nextCursor
222
+ };
223
+ }
224
+ /** Map of database column names to camelCase keys present on entry.data. */
225
+ const ENTRY_DATA_KEY_MAP = {
226
+ created_at: "createdAt",
227
+ updated_at: "updatedAt",
228
+ published_at: "publishedAt",
229
+ scheduled_at: "scheduledAt",
230
+ author_id: "authorId",
231
+ primary_byline_id: "primaryBylineId"
232
+ };
233
+ const FIELD_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
234
+ /**
235
+ * Encode a `nextCursor` from a content entry, mirroring the loader's
236
+ * encoding scheme: `(orderValue, id)` where `orderValue` is the primary
237
+ * sort field's stringified value. For date columns, reads the raw DB
238
+ * string the loader stashed via CURSOR_RAW_VALUES — round-tripping the
239
+ * parsed Date through `toISOString()` would lose precision for stored
240
+ * values that aren't already ISO-with-milliseconds.
241
+ */
242
+ function encodeEntryCursor(entry, orderBy) {
243
+ const data = entryData(entry);
244
+ const id = dataStr(data, "id");
245
+ if (!id) return void 0;
246
+ let dbField = "created_at";
247
+ if (orderBy) {
248
+ for (const field of Object.keys(orderBy)) if (FIELD_NAME_PATTERN.test(field)) {
249
+ dbField = field;
250
+ break;
251
+ }
252
+ }
253
+ const rawDateValuesRaw = Reflect.get(data, CURSOR_RAW_VALUES);
254
+ if (rawDateValuesRaw !== null && typeof rawDateValuesRaw === "object") {
255
+ const raw = Reflect.get(rawDateValuesRaw, dbField);
256
+ if (typeof raw === "string") return encodeCursor(raw, id);
257
+ }
258
+ const value = data[ENTRY_DATA_KEY_MAP[dbField] ?? dbField];
259
+ let orderValue;
260
+ if (value instanceof Date) orderValue = value.toISOString();
261
+ else if (typeof value === "string" || typeof value === "number") orderValue = String(value);
262
+ else orderValue = "";
263
+ return encodeCursor(orderValue, id);
173
264
  }
174
265
  /**
175
266
  * Build a canonical cache key for `getEmDashCollection`.
@@ -381,10 +472,17 @@ async function getEmDashEntry(type, id, options) {
381
472
  async function hydrateEntryBylines(type, entries) {
382
473
  if (entries.length === 0) return;
383
474
  try {
384
- const { getBylinesForEntries } = await import("./bylines-CRNsVG88.mjs").then((n) => n.t);
385
- const ids = entries.map((e) => dataStr(entryData(e), "id")).filter(Boolean);
386
- if (ids.length === 0) return;
387
- const bylinesMap = await getBylinesForEntries(type, ids);
475
+ const { getBylinesForEntries } = await import("./bylines-CvJ3PYz2.mjs").then((n) => n.t);
476
+ const refs = entries.map((e) => {
477
+ const data = entryData(e);
478
+ const id = dataStr(data, "id");
479
+ return id ? {
480
+ id,
481
+ authorId: dataStr(data, "authorId") || null
482
+ } : null;
483
+ }).filter((r) => r !== null);
484
+ if (refs.length === 0) return;
485
+ const bylinesMap = await getBylinesForEntries(type, refs);
388
486
  for (const entry of entries) {
389
487
  const data = entryData(entry);
390
488
  const dbId = dataStr(data, "id");
@@ -417,7 +515,7 @@ async function hydrateEntryBylines(type, entries) {
417
515
  async function hydrateEntryTerms(type, entries) {
418
516
  if (entries.length === 0) return;
419
517
  try {
420
- const { getAllTermsForEntries } = await import("./taxonomies-B4IAshV8.mjs").then((n) => n.u);
518
+ const { getAllTermsForEntries } = await import("./taxonomies-ZlRtD6AG.mjs").then((n) => n.u);
421
519
  const ids = entries.map((e) => dataStr(entryData(e), "id")).filter(Boolean);
422
520
  if (ids.length === 0) return;
423
521
  const termsMap = await getAllTermsForEntries(type, ids);
@@ -451,9 +549,9 @@ async function hydrateEntryTerms(type, entries) {
451
549
  */
452
550
  async function getTranslations(type, id) {
453
551
  try {
454
- const db = (await import("./loader-CndGj8kM.mjs").then((n) => n.r)).getDb;
552
+ const db = (await import("./loader-CKLbBnhK.mjs").then((n) => n.i)).getDb;
455
553
  const dbInstance = await db();
456
- const { ContentRepository } = await import("./content-BcQPYxdV.mjs").then((n) => n.n);
554
+ const { ContentRepository } = await import("./content-8lOYF0pr.mjs").then((n) => n.n);
457
555
  const repo = new ContentRepository(dbInstance);
458
556
  const item = await repo.findByIdOrSlug(type, id);
459
557
  if (!item) return {
@@ -522,8 +620,8 @@ function invalidateUrlPatternCache() {
522
620
  */
523
621
  async function resolveEmDashPath(path) {
524
622
  if (!cachedUrlPatterns) {
525
- const { getDb } = await import("./loader-CndGj8kM.mjs").then((n) => n.r);
526
- const { SchemaRegistry } = await import("./registry-C3Mr0ODu.mjs").then((n) => n.r);
623
+ const { getDb } = await import("./loader-CKLbBnhK.mjs").then((n) => n.i);
624
+ const { SchemaRegistry } = await import("./registry-Dw70ChxB.mjs").then((n) => n.r);
527
625
  const collections = await new SchemaRegistry(await getDb()).listCollections();
528
626
  cachedUrlPatterns = [];
529
627
  for (const collection of collections) {
@@ -555,4 +653,4 @@ async function resolveEmDashPath(path) {
555
653
 
556
654
  //#endregion
557
655
  export { invalidateUrlPatternCache as a, createEditable as c, getTranslations as i, createNoop as l, getEmDashCollection as n, query_exports as o, getEmDashEntry as r, resolveEmDashPath as s, getEditMeta as t };
558
- //# sourceMappingURL=query-fqEdLFms.mjs.map
656
+ //# sourceMappingURL=query-Cg9ZKRQ0.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-Cg9ZKRQ0.mjs","names":[],"sources":["../src/visual-editing/editable.ts","../src/query.ts"],"sourcesContent":["/**\n * Visual editing annotation system\n *\n * Creates Proxy objects that emit data-emdash-ref attributes when spread onto elements.\n */\n\nexport interface CMSAnnotation {\n\tcollection: string;\n\tid: string;\n\tfield?: string;\n\t/** Entry status — only present on entry-level annotations (not field-level) */\n\tstatus?: string;\n\t/** Whether the entry has unpublished draft changes */\n\thasDraft?: boolean;\n}\n\n/** The shape returned when spreading an edit annotation onto an element */\nexport interface FieldAnnotation {\n\t\"data-emdash-ref\": string;\n}\n\nexport interface EditableOptions {\n\t/** Entry status: \"draft\", \"published\", \"scheduled\" */\n\tstatus?: string;\n\t/** true when draftRevisionId exists and differs from liveRevisionId */\n\thasDraft?: boolean;\n}\n\n/**\n * Create an editable proxy for an entry.\n *\n * Usage:\n * - `{...entry.edit}` - entry-level annotation (includes status/hasDraft)\n * - `{...entry.edit.title}` - field-level annotation\n * - `{...entry.edit['nested.field']}` - nested field (bracket notation)\n */\nexport function createEditable(\n\tcollection: string,\n\tid: string,\n\toptions?: EditableOptions,\n): EditProxy {\n\tconst base: CMSAnnotation = {\n\t\tcollection,\n\t\tid,\n\t\t...(options?.status && { status: options.status }),\n\t\t...(options?.hasDraft && { hasDraft: true }),\n\t};\n\n\treturn new Proxy({} as EditProxy, {\n\t\tget(_, prop) {\n\t\t\tif (prop === \"toJSON\") return () => ({ \"data-emdash-ref\": JSON.stringify(base) });\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\n\t\t\t// data-emdash-ref access returns the entry-level string\n\t\t\tif (prop === \"data-emdash-ref\") return JSON.stringify(base);\n\n\t\t\t// Field-level: return a FieldAnnotation for the specific field\n\t\t\treturn {\n\t\t\t\t\"data-emdash-ref\": JSON.stringify({ ...base, field: String(prop) }),\n\t\t\t} satisfies FieldAnnotation;\n\t\t},\n\t\townKeys() {\n\t\t\treturn [\"data-emdash-ref\"];\n\t\t},\n\t\tgetOwnPropertyDescriptor(_, prop) {\n\t\t\tif (prop === \"data-emdash-ref\") {\n\t\t\t\treturn {\n\t\t\t\t\tconfigurable: true,\n\t\t\t\t\tenumerable: true,\n\t\t\t\t\tvalue: JSON.stringify(base),\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t});\n}\n\n/**\n * Create a noop proxy for production mode.\n * Spreading this produces no attributes.\n */\nexport function createNoop(): EditProxy {\n\treturn new Proxy({} as EditProxy, {\n\t\tget(_, prop) {\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\t\t\t// All property access returns undefined in noop mode\n\t\t\treturn undefined;\n\t\t},\n\t\townKeys() {\n\t\t\treturn [];\n\t\t},\n\t\tgetOwnPropertyDescriptor() {\n\t\t\treturn undefined;\n\t\t},\n\t});\n}\n\n/**\n * Visual editing proxy type.\n *\n * Spread directly onto elements for entry-level annotations: `{...entry.edit}`\n * Access a field for field-level annotations: `{...entry.edit.title}`\n *\n * In production, spreading produces no attributes (noop).\n */\nexport type EditProxy = {\n\treadonly [field: string]: Partial<FieldAnnotation>;\n};\n","/**\n * Query functions for EmDash content\n *\n * These wrap Astro's getLiveCollection/getLiveEntry with type filtering.\n * Use these instead of calling Astro's functions directly.\n *\n * Error handling follows Astro's pattern - returns { entries/entry, error }\n * so callers can gracefully handle errors (including 404s).\n *\n * Preview mode is handled implicitly via ALS request context —\n * no parameters needed. The middleware verifies the preview token\n * and sets the context; query functions read it automatically.\n */\n\nimport { encodeCursor } from \"./database/repositories/types.js\";\nimport { getFallbackChain, getI18nConfig, isI18nEnabled } from \"./i18n/config.js\";\nimport { CURSOR_RAW_VALUES } from \"./loader.js\";\nimport { requestCached } from \"./request-cache.js\";\nimport { getRequestContext } from \"./request-context.js\";\nimport { isMissingTableError } from \"./utils/db-errors.js\";\nimport {\n\tcreateEditable,\n\tcreateNoop,\n\ttype EditProxy,\n\ttype EditableOptions,\n} from \"./visual-editing/editable.js\";\n\n/**\n * Collection type registry for type-safe queries.\n *\n * This interface is extended by the generated emdash-env.d.ts file\n * to provide type inference for collection names and their data shapes.\n *\n * @example\n * ```ts\n * // In emdash-env.d.ts (generated):\n * declare module \"emdash\" {\n * interface EmDashCollections {\n * posts: { title: string; content: PortableTextBlock[]; };\n * pages: { title: string; body: PortableTextBlock[]; };\n * }\n * }\n *\n * // Then in your code:\n * const { entries } = await getEmDashCollection(\"posts\");\n * // entries[0].data.title is typed as string\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface EmDashCollections {}\n\n/**\n * Helper type to infer the data type for a collection.\n * Returns the registered type if known, otherwise falls back to Record<string, unknown>.\n */\nexport type InferCollectionData<T extends string> = T extends keyof EmDashCollections\n\t? EmDashCollections[T]\n\t: Record<string, unknown>;\n\n/**\n * Sort direction\n */\nexport type SortDirection = \"asc\" | \"desc\";\n\n/**\n * Order by specification - field name to direction\n * @example { created_at: \"desc\" } - Sort by created_at descending\n * @example { title: \"asc\" } - Sort by title ascending\n * @example { published_at: \"desc\", title: \"asc\" } - Multi-field sort\n */\nexport type OrderBySpec = Record<string, SortDirection>;\n\nexport interface CollectionFilter {\n\tstatus?: \"draft\" | \"published\" | \"archived\";\n\tlimit?: number;\n\t/**\n\t * Opaque cursor for keyset pagination.\n\t * Pass the `nextCursor` value from a previous result to fetch the next page.\n\t * @example\n\t * ```ts\n\t * const cursor = Astro.url.searchParams.get(\"cursor\") ?? undefined;\n\t * const { entries, nextCursor } = await getEmDashCollection(\"posts\", {\n\t * limit: 10,\n\t * cursor,\n\t * });\n\t * ```\n\t */\n\tcursor?: string;\n\t/**\n\t * Filter by field values or taxonomy terms\n\t * @example { category: 'news' } - Filter by taxonomy term\n\t * @example { category: ['news', 'featured'] } - Filter by multiple terms (OR)\n\t */\n\twhere?: Record<string, string | string[]>;\n\t/**\n\t * Order results by field(s)\n\t * @default { created_at: \"desc\" }\n\t * @example { created_at: \"desc\" } - Sort by created_at descending (default)\n\t * @example { title: \"asc\" } - Sort by title ascending\n\t * @example { published_at: \"desc\", title: \"asc\" } - Multi-field sort\n\t */\n\torderBy?: OrderBySpec;\n\t/**\n\t * Filter by locale. When set, only returns entries in this locale.\n\t * Only relevant when i18n is configured.\n\t * @example \"en\" — English entries only\n\t * @example \"fr\" — French entries only\n\t */\n\tlocale?: string;\n}\n\nexport interface ContentEntry<T = Record<string, unknown>> {\n\tid: string;\n\tdata: T;\n\t/** Visual editing annotations. Spread onto elements: {...entry.edit.title} */\n\tedit: EditProxy;\n}\n\n/** Cache hint returned by the content loader for route caching */\nexport interface CacheHint {\n\ttags?: string[];\n\tlastModified?: Date;\n}\n\n/**\n * Result from getEmDashCollection\n */\nexport interface CollectionResult<T> {\n\t/** The entries (empty array if error or none found) */\n\tentries: ContentEntry<T>[];\n\t/** Error if the query failed */\n\terror?: Error;\n\t/** Cache hint for route caching (pass to Astro.cache.set()) */\n\tcacheHint: CacheHint;\n\t/**\n\t * Opaque cursor for the next page.\n\t * Undefined when there are no more results.\n\t * Pass this as `cursor` in the next query to get the next page.\n\t */\n\tnextCursor?: string;\n}\n\n/**\n * Result from getEmDashEntry\n */\nexport interface EntryResult<T> {\n\t/** The entry, or null if not found */\n\tentry: ContentEntry<T> | null;\n\t/** Error if the query failed (not set for \"not found\", only for actual errors) */\n\terror?: Error;\n\t/** Whether we're in preview mode (valid token was provided) */\n\tisPreview: boolean;\n\t/** Set when a fallback locale was used instead of the requested locale */\n\tfallbackLocale?: string;\n\t/** Cache hint for route caching (pass to Astro.cache.set()) */\n\tcacheHint: CacheHint;\n}\n\nconst COLLECTION_NAME = \"_emdash\";\n\n/** Symbol key for edit metadata on PT arrays — avoids collision with user data */\nconst EMDASH_EDIT = Symbol.for(\"__emdash\");\n\n/** Edit metadata attached to PT arrays in edit mode */\nexport interface EditFieldMeta {\n\tcollection: string;\n\tid: string;\n\tfield: string;\n}\n\n/** Type guard for EditFieldMeta */\nfunction isEditFieldMeta(value: unknown): value is EditFieldMeta {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (!(\"collection\" in value) || !(\"id\" in value) || !(\"field\" in value)) return false;\n\t// After `in` checks, TS narrows to Record<\"collection\" | \"id\" | \"field\", unknown>\n\tconst { collection, id, field } = value;\n\treturn typeof collection === \"string\" && typeof id === \"string\" && typeof field === \"string\";\n}\n\n/**\n * Read edit metadata from a value (returns undefined if not tagged).\n * Uses Object.getOwnPropertyDescriptor to access Symbol-keyed property\n * without an unsafe type assertion.\n */\nexport function getEditMeta(value: unknown): EditFieldMeta | undefined {\n\tif (value && typeof value === \"object\") {\n\t\tconst desc = Object.getOwnPropertyDescriptor(value, EMDASH_EDIT);\n\t\tconst meta: unknown = desc?.value;\n\t\tif (isEditFieldMeta(meta)) {\n\t\t\treturn meta;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Tag PT-like arrays in entry data with edit metadata (non-enumerable).\n * A PT array is identified by: is an array, first element has _type property.\n */\nfunction tagEditableFields(data: Record<string, unknown>, collection: string, id: string): void {\n\tfor (const [field, value] of Object.entries(data)) {\n\t\tif (\n\t\t\tArray.isArray(value) &&\n\t\t\tvalue.length > 0 &&\n\t\t\tvalue[0] &&\n\t\t\ttypeof value[0] === \"object\" &&\n\t\t\t\"_type\" in value[0]\n\t\t) {\n\t\t\tObject.defineProperty(value, EMDASH_EDIT, {\n\t\t\t\tvalue: { collection, id, field } satisfies EditFieldMeta,\n\t\t\t\tenumerable: false,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\t}\n\t}\n}\n\n/** Safely read a string field from a Record, with optional fallback */\nfunction dataStr(data: Record<string, unknown>, key: string, fallback = \"\"): string {\n\tconst val = data[key];\n\treturn typeof val === \"string\" ? val : fallback;\n}\n\n/** Type guard for Record<string, unknown> */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Extract data as Record from an Astro entry (which is any-typed) */\nfunction entryData(entry: { data?: unknown }): Record<string, unknown> {\n\treturn isRecord(entry.data) ? entry.data : {};\n}\n\n/** Extract the database ID from entry data (data.id is the ULID, entry.id is the slug) */\nfunction entryDatabaseId(entry: { id: string; data?: unknown }): string {\n\tconst d = entryData(entry);\n\treturn dataStr(d, \"id\") || entry.id;\n}\n\n/** Extract edit options from entry data for the proxy */\nfunction entryEditOptions(entry: { data?: unknown }): EditableOptions {\n\tconst data = entryData(entry);\n\tconst status = dataStr(data, \"status\", \"draft\");\n\tconst draftRevisionId = dataStr(data, \"draftRevisionId\") || undefined;\n\tconst liveRevisionId = dataStr(data, \"liveRevisionId\") || undefined;\n\tconst hasDraft = !!draftRevisionId && draftRevisionId !== liveRevisionId;\n\treturn { status, hasDraft };\n}\n\n/**\n * Get all entries of a content type\n *\n * Returns { entries, error } for graceful error handling.\n *\n * When emdash-env.d.ts is generated, the collection name will be\n * type-checked and the return type will be inferred automatically.\n *\n * @example\n * ```ts\n * import { getEmDashCollection } from \"emdash\";\n *\n * const { entries: posts, error } = await getEmDashCollection(\"posts\");\n * if (error) {\n * console.error(\"Failed to load posts:\", error);\n * return;\n * }\n * // posts[0].data.title is typed (if emdash-env.d.ts exists)\n *\n * // With filters\n * const { entries: drafts } = await getEmDashCollection(\"posts\", { status: \"draft\" });\n * ```\n */\nexport async function getEmDashCollection<T extends string, D = InferCollectionData<T>>(\n\ttype: T,\n\tfilter?: CollectionFilter,\n): Promise<CollectionResult<D>> {\n\t// Cache per (type, filter) within a single request. Edit mode and\n\t// preview are request-scoped and stable, so they don't need to be\n\t// part of the key. Widgets and layouts frequently request the same\n\t// collection shape as the page itself (e.g. a \"recent posts\" list\n\t// appears on the home page AND in the sidebar) — caching collapses\n\t// those duplicate queries, along with the bylines and taxonomy-term\n\t// hydration each call would otherwise re-do.\n\t//\n\t// Bucket small limits to a shared minimum so a page with several\n\t// \"recent N posts\" widgets at slightly different limits (e.g. a\n\t// post-detail page asking for 4 in the body and 5 in the sidebar)\n\t// shares one fetch + hydration round-trip rather than running two.\n\t// Cursor-paginated calls are exempt: their limit is part of the\n\t// pagination contract.\n\tconst bucketed = bucketFilter(filter);\n\tconst cached = await requestCached(collectionCacheKey(type, bucketed.fetchFilter), () =>\n\t\tgetEmDashCollectionUncached<T, D>(type, bucketed.fetchFilter),\n\t);\n\treturn bucketed.requestedLimit === undefined\n\t\t? cached\n\t\t: sliceCollectionResult(cached, bucketed.requestedLimit, filter?.orderBy);\n}\n\n/**\n * Threshold for limit bucketing. Page templates routinely render small\n * \"recent posts\" widgets at limits 3-8; rounding those up to a single\n * shared bucket lets one fetch satisfy several widgets within a request.\n * Above this, the requested limit is honoured exactly — bucketing limit:50\n * to limit:64 would waste hydration work for callers fetching real pages.\n */\nconst BUCKET_LIMIT_THRESHOLD = 10;\n\ninterface BucketedFilter {\n\t/** Filter to pass to the loader (with limit possibly raised). */\n\tfetchFilter: CollectionFilter | undefined;\n\t/** Original limit; defined only when bucketing was applied. */\n\trequestedLimit: number | undefined;\n}\n\n/** @internal exported for unit tests; not part of the public API. */\nexport function bucketFilter(filter: CollectionFilter | undefined): BucketedFilter {\n\tconst limit = filter?.limit;\n\tif (\n\t\tlimit === undefined ||\n\t\tlimit >= BUCKET_LIMIT_THRESHOLD ||\n\t\tlimit <= 0 ||\n\t\tfilter?.cursor !== undefined\n\t) {\n\t\treturn { fetchFilter: filter, requestedLimit: undefined };\n\t}\n\treturn {\n\t\tfetchFilter: { ...filter, limit: BUCKET_LIMIT_THRESHOLD },\n\t\trequestedLimit: limit,\n\t};\n}\n\n/**\n * Slice a cached bucketed result down to the originally-requested limit\n * and recompute `nextCursor` from the row that would have been the\n * over-fetch detector for that limit. When truncation is needed, returns\n * a shallow-copied result with a new `entries` array; otherwise returns\n * the cached result unchanged (including error results and results\n * already within the requested limit).\n */\n/** @internal exported for unit tests; not part of the public API. */\nexport function sliceCollectionResult<D>(\n\tcached: CollectionResult<D>,\n\tlimit: number,\n\torderBy: OrderBySpec | undefined,\n): CollectionResult<D> {\n\tif (cached.error) return cached;\n\tif (cached.entries.length <= limit) return cached;\n\tconst sliced = cached.entries.slice(0, limit);\n\t// Mirror the loader's encoding: cursor points at the last returned row,\n\t// so \"next page\" picks up at the row immediately after it. See\n\t// buildCursorCondition in loader.ts — it filters strictly past this row.\n\tconst lastEntry = sliced.at(-1);\n\tconst nextCursor = lastEntry ? encodeEntryCursor(lastEntry, orderBy) : undefined;\n\treturn { ...cached, entries: sliced, nextCursor };\n}\n\n/** Map of database column names to camelCase keys present on entry.data. */\nconst ENTRY_DATA_KEY_MAP: Record<string, string> = {\n\tcreated_at: \"createdAt\",\n\tupdated_at: \"updatedAt\",\n\tpublished_at: \"publishedAt\",\n\tscheduled_at: \"scheduledAt\",\n\tauthor_id: \"authorId\",\n\tprimary_byline_id: \"primaryBylineId\",\n};\n\n// Mirror loader.ts FIELD_NAME_PATTERN. Kept in sync intentionally — diverging\n// would let the encoder accept a field name the loader's getPrimarySort then\n// rejected, producing a cursor that paginates against a different column.\nconst FIELD_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n/**\n * Encode a `nextCursor` from a content entry, mirroring the loader's\n * encoding scheme: `(orderValue, id)` where `orderValue` is the primary\n * sort field's stringified value. For date columns, reads the raw DB\n * string the loader stashed via CURSOR_RAW_VALUES — round-tripping the\n * parsed Date through `toISOString()` would lose precision for stored\n * values that aren't already ISO-with-milliseconds.\n */\nfunction encodeEntryCursor<D>(\n\tentry: ContentEntry<D>,\n\torderBy: OrderBySpec | undefined,\n): string | undefined {\n\tconst data = entryData(entry);\n\tconst id = dataStr(data, \"id\");\n\tif (!id) return undefined;\n\n\t// Match loader.ts getPrimarySort: take the first valid field, default to created_at.\n\tlet dbField = \"created_at\";\n\tif (orderBy) {\n\t\tfor (const field of Object.keys(orderBy)) {\n\t\t\tif (FIELD_NAME_PATTERN.test(field)) {\n\t\t\t\tdbField = field;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Date columns: prefer the raw stored string captured by the loader so\n\t// the cursor matches what a direct loader fetch would emit, regardless\n\t// of how the DB stored the timestamp.\n\tconst rawDateValuesRaw = Reflect.get(data, CURSOR_RAW_VALUES);\n\tif (rawDateValuesRaw !== null && typeof rawDateValuesRaw === \"object\") {\n\t\tconst raw = Reflect.get(rawDateValuesRaw, dbField);\n\t\tif (typeof raw === \"string\") return encodeCursor(raw, id);\n\t}\n\n\tconst dataKey = ENTRY_DATA_KEY_MAP[dbField] ?? dbField;\n\tconst value = data[dataKey];\n\tlet orderValue: string;\n\tif (value instanceof Date) {\n\t\torderValue = value.toISOString();\n\t} else if (typeof value === \"string\" || typeof value === \"number\") {\n\t\torderValue = String(value);\n\t} else {\n\t\t// Match the loader's empty-string fallback for null/undefined order\n\t\t// values so cursor decoding stays valid even at the boundary.\n\t\torderValue = \"\";\n\t}\n\treturn encodeCursor(orderValue, id);\n}\n\n/**\n * Build a canonical cache key for `getEmDashCollection`.\n *\n * `JSON.stringify` is insertion-order-sensitive, so two callers passing\n * semantically identical filters with different key orders would miss\n * the cache. We fix the top-level field order and sort `where` keys\n * (order there is irrelevant), while preserving `orderBy` key order\n * because that's the sort priority.\n */\nfunction collectionCacheKey(type: string, filter?: CollectionFilter): string {\n\tif (!filter) return `collection:${type}:`;\n\tconst parts = [\n\t\tfilter.status ?? \"\",\n\t\tfilter.limit ?? \"\",\n\t\tfilter.cursor ?? \"\",\n\t\tfilter.where ? stableStringify(filter.where) : \"\",\n\t\tfilter.orderBy ? JSON.stringify(filter.orderBy) : \"\",\n\t\tfilter.locale ?? \"\",\n\t];\n\treturn `collection:${type}:${parts.join(\"|\")}`;\n}\n\nfunction stableStringify(value: Record<string, unknown>): string {\n\tconst keys = Object.keys(value).toSorted();\n\tconst ordered: Record<string, unknown> = {};\n\tfor (const k of keys) ordered[k] = value[k];\n\treturn JSON.stringify(ordered);\n}\n\nasync function getEmDashCollectionUncached<T extends string, D = InferCollectionData<T>>(\n\ttype: T,\n\tfilter?: CollectionFilter,\n): Promise<CollectionResult<D>> {\n\t// Dynamic import to avoid build-time issues\n\tconst { getLiveCollection } = await import(\"astro:content\");\n\n\t// Resolve locale: explicit filter > ALS context > defaultLocale (when i18n enabled)\n\t// Without this, queries return all locale rows, producing broken IDs\n\tconst ctx = getRequestContext();\n\tconst i18nConfig = getI18nConfig();\n\tconst resolvedLocale =\n\t\tfilter?.locale ?? ctx?.locale ?? (isI18nEnabled() ? i18nConfig!.defaultLocale : undefined);\n\n\tconst result = await getLiveCollection(COLLECTION_NAME, {\n\t\ttype,\n\t\tstatus: filter?.status,\n\t\tlimit: filter?.limit,\n\t\tcursor: filter?.cursor,\n\t\twhere: filter?.where,\n\t\torderBy: filter?.orderBy,\n\t\tlocale: resolvedLocale,\n\t});\n\n\tconst { entries, error, cacheHint } = result;\n\t// nextCursor is returned by the emdash loader but not part of Astro's base\n\t// LiveLoader return type. Extract it safely via property descriptor to avoid\n\t// an unsafe type assertion on the `any`-typed result object.\n\tconst rawCursor = Object.getOwnPropertyDescriptor(result, \"nextCursor\")?.value;\n\tconst nextCursor: string | undefined = typeof rawCursor === \"string\" ? rawCursor : undefined;\n\n\tif (error) {\n\t\treturn { entries: [], error, cacheHint: {} };\n\t}\n\n\tconst isEditMode = ctx?.editMode ?? false;\n\tconst entriesWithEdit = entries.map((entry: ContentEntry<D>) => {\n\t\tconst dbId = entryDatabaseId(entry);\n\t\tif (isEditMode) {\n\t\t\ttagEditableFields(entryData(entry), type, dbId);\n\t\t}\n\t\treturn {\n\t\t\t...entry,\n\t\t\tedit: isEditMode ? createEditable(type, dbId, entryEditOptions(entry)) : createNoop(),\n\t\t};\n\t});\n\n\t// Eagerly hydrate bylines and taxonomy terms for all entries in parallel.\n\t// Both are independent queries, so running them concurrently halves the\n\t// round-trip cost on remote databases (D1 replicas, etc.).\n\tawait Promise.all([\n\t\thydrateEntryBylines(type, entriesWithEdit),\n\t\thydrateEntryTerms(type, entriesWithEdit),\n\t]);\n\n\treturn { entries: entriesWithEdit, nextCursor, cacheHint: cacheHint ?? {} };\n}\n\n/**\n * Get a single entry by type and ID/slug\n *\n * Returns { entry, error, isPreview } for graceful error handling.\n * - entry is null if not found (not an error)\n * - error is set only for actual errors (db issues, etc.)\n *\n * Preview mode is detected automatically from request context (ALS).\n * When the URL has a valid `_preview` token, the middleware sets preview\n * context and this function serves draft revision data if available.\n *\n * @example\n * ```ts\n * import { getEmDashEntry } from \"emdash\";\n *\n * // Simple usage — preview just works via middleware\n * const { entry: post, isPreview, error } = await getEmDashEntry(\"posts\", \"my-slug\");\n * if (!post) return Astro.redirect(\"/404\");\n * ```\n */\nexport async function getEmDashEntry<T extends string, D = InferCollectionData<T>>(\n\ttype: T,\n\tid: string,\n\toptions?: { locale?: string },\n): Promise<EntryResult<D>> {\n\t// Dynamic import to avoid build-time issues\n\tconst { getLiveEntry } = await import(\"astro:content\");\n\n\t// Check ALS for preview and edit mode context\n\tconst ctx = getRequestContext();\n\tconst preview = ctx?.preview;\n\tconst isEditMode = ctx?.editMode ?? false;\n\tconst isPreviewMode = !!preview && preview.collection === type;\n\t// Edit mode implies preview — editors should see draft content\n\tconst serveDrafts = isPreviewMode || isEditMode;\n\n\t// Resolve locale: explicit option > ALS context > undefined (no filter)\n\tconst requestedLocale = options?.locale ?? ctx?.locale;\n\n\t/** Wrap a raw Astro entry with edit proxy, tagging editable fields if needed */\n\tfunction wrapEntry(raw: ContentEntry<D>): ContentEntry<D> {\n\t\tconst dbId = entryDatabaseId(raw);\n\t\tif (isEditMode) {\n\t\t\ttagEditableFields(entryData(raw), type, dbId);\n\t\t}\n\t\treturn {\n\t\t\t...raw,\n\t\t\tedit: isEditMode ? createEditable(type, dbId, entryEditOptions(raw)) : createNoop(),\n\t\t};\n\t}\n\n\t/** Check if an entry is publicly visible (published or scheduled past its time) */\n\tfunction isVisible(entry: ContentEntry<D>): boolean {\n\t\tconst data = entryData(entry);\n\t\tconst status = dataStr(data, \"status\");\n\t\tconst scheduledAt = dataStr(data, \"scheduledAt\") || undefined;\n\t\tconst isPublished = status === \"published\";\n\t\tconst isScheduledAndReady =\n\t\t\tstatus === \"scheduled\" && scheduledAt && new Date(scheduledAt) <= new Date();\n\t\treturn isPublished || !!isScheduledAndReady;\n\t}\n\n\t// Build the fallback chain: [requestedLocale, fallback1, ..., defaultLocale]\n\t// When i18n is disabled or no locale requested, just use a single-element chain\n\tconst localeChain =\n\t\trequestedLocale && isI18nEnabled() ? getFallbackChain(requestedLocale) : [requestedLocale];\n\n\t/** Return a successful EntryResult with bylines and taxonomy terms hydrated */\n\tasync function successResult(\n\t\twrapped: ContentEntry<D>,\n\t\topts: { isPreview: boolean; fallbackLocale?: string; cacheHint: CacheHint },\n\t): Promise<EntryResult<D>> {\n\t\tawait Promise.all([hydrateEntryBylines(type, [wrapped]), hydrateEntryTerms(type, [wrapped])]);\n\t\treturn {\n\t\t\tentry: wrapped,\n\t\t\tisPreview: opts.isPreview,\n\t\t\tfallbackLocale: opts.fallbackLocale,\n\t\t\tcacheHint: opts.cacheHint,\n\t\t};\n\t}\n\n\tif (serveDrafts) {\n\t\t// Draft mode: try each locale in the fallback chain\n\t\tfor (let i = 0; i < localeChain.length; i++) {\n\t\t\tconst locale = localeChain[i];\n\t\t\tconst fallbackLocale = i > 0 ? locale : undefined;\n\n\t\t\tconst {\n\t\t\t\tentry: baseEntry,\n\t\t\t\terror: baseError,\n\t\t\t\tcacheHint,\n\t\t\t} = await getLiveEntry(COLLECTION_NAME, {\n\t\t\t\ttype,\n\t\t\t\tid,\n\t\t\t\tlocale,\n\t\t\t});\n\n\t\t\tif (baseError) {\n\t\t\t\treturn { entry: null, error: baseError, isPreview: serveDrafts, cacheHint: {} };\n\t\t\t}\n\n\t\t\tif (!baseEntry) continue; // Try next locale in chain\n\n\t\t\t// Preview tokens are item-scoped: verify the resolved entry matches.\n\t\t\t// Edit mode (authenticated editors) has collection-wide draft access.\n\t\t\tif (isPreviewMode && !isEditMode) {\n\t\t\t\tconst dbId = entryDatabaseId(baseEntry);\n\t\t\t\tif (preview.id !== dbId && preview.id !== id) {\n\t\t\t\t\t// Token doesn't match — serve only if publicly visible, without draft access\n\t\t\t\t\tif (isVisible(baseEntry)) {\n\t\t\t\t\t\treturn successResult(wrapEntry(baseEntry), {\n\t\t\t\t\t\t\tisPreview: false,\n\t\t\t\t\t\t\tfallbackLocale,\n\t\t\t\t\t\t\tcacheHint: cacheHint ?? {},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\t// Not visible — try next locale in fallback chain\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check if entry has a draft revision — if so, re-fetch with revision data\n\t\t\tconst baseData = entryData(baseEntry);\n\t\t\tconst draftRevisionId = dataStr(baseData, \"draftRevisionId\") || undefined;\n\n\t\t\tif (draftRevisionId) {\n\t\t\t\tconst { entry: draftEntry, error: draftError } = await getLiveEntry(COLLECTION_NAME, {\n\t\t\t\t\ttype,\n\t\t\t\t\tid,\n\t\t\t\t\trevisionId: draftRevisionId,\n\t\t\t\t\tlocale,\n\t\t\t\t});\n\n\t\t\t\tif (!draftError && draftEntry) {\n\t\t\t\t\treturn successResult(wrapEntry(draftEntry), {\n\t\t\t\t\t\tisPreview: serveDrafts,\n\t\t\t\t\t\tfallbackLocale,\n\t\t\t\t\t\tcacheHint: cacheHint ?? {},\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn successResult(wrapEntry(baseEntry), {\n\t\t\t\tisPreview: serveDrafts,\n\t\t\t\tfallbackLocale,\n\t\t\t\tcacheHint: cacheHint ?? {},\n\t\t\t});\n\t\t}\n\n\t\t// No entry found in any locale\n\t\treturn { entry: null, isPreview: serveDrafts, cacheHint: {} };\n\t}\n\n\t// Normal mode: try each locale in the fallback chain, only return published content\n\tfor (let i = 0; i < localeChain.length; i++) {\n\t\tconst locale = localeChain[i];\n\t\tconst fallbackLocale = i > 0 ? locale : undefined;\n\n\t\tconst { entry, error, cacheHint } = await getLiveEntry(COLLECTION_NAME, { type, id, locale });\n\t\tif (error) {\n\t\t\treturn { entry: null, error, isPreview: false, cacheHint: {} };\n\t\t}\n\n\t\tif (entry && isVisible(entry)) {\n\t\t\treturn successResult(wrapEntry(entry), {\n\t\t\t\tisPreview: false,\n\t\t\t\tfallbackLocale,\n\t\t\t\tcacheHint: cacheHint ?? {},\n\t\t\t});\n\t\t}\n\t\t// Entry not found or not visible in this locale — try next\n\t}\n\n\treturn { entry: null, isPreview: false, cacheHint: {} };\n}\n\n/**\n * Eagerly hydrate byline data onto entry.data for one or more entries.\n *\n * Attaches `bylines` (array of ContentBylineCredit) and `byline`\n * (primary BylineSummary or null) to each entry's data object.\n * Uses batch queries to avoid N+1.\n *\n * Fails silently if the byline tables don't exist yet (pre-migration).\n */\nasync function hydrateEntryBylines<D>(type: string, entries: ContentEntry<D>[]): Promise<void> {\n\tif (entries.length === 0) return;\n\n\ttry {\n\t\tconst { getBylinesForEntries } = await import(\"./bylines/index.js\");\n\n\t\tconst refs = entries\n\t\t\t.map((e) => {\n\t\t\t\tconst data = entryData(e);\n\t\t\t\tconst id = dataStr(data, \"id\");\n\t\t\t\treturn id ? { id, authorId: dataStr(data, \"authorId\") || null } : null;\n\t\t\t})\n\t\t\t.filter((r): r is { id: string; authorId: string | null } => r !== null);\n\t\tif (refs.length === 0) return;\n\n\t\tconst bylinesMap = await getBylinesForEntries(type, refs);\n\n\t\tfor (const entry of entries) {\n\t\t\tconst data = entryData(entry);\n\t\t\tconst dbId = dataStr(data, \"id\");\n\t\t\tif (!dbId) continue;\n\n\t\t\tconst credits = bylinesMap.get(dbId) ?? [];\n\t\t\tdata.bylines = credits;\n\t\t\tdata.byline = credits[0]?.byline ?? null;\n\t\t}\n\t} catch (err) {\n\t\t// Only swallow \"table not found\" errors from pre-migration databases.\n\t\t// Matches SQLite/D1 (\"no such table\") and PostgreSQL (\"relation/table\n\t\t// ... does not exist\") via the shared helper.\n\t\tif (!isMissingTableError(err)) {\n\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\tconsole.warn(\"[emdash] Failed to hydrate bylines:\", msg);\n\t\t}\n\t}\n}\n\n/**\n * Eagerly hydrate taxonomy term data onto entry.data for one or more entries.\n *\n * Attaches `terms` (Record keyed by taxonomy name with an array of TaxonomyTerm\n * values) to each entry's data object. Uses a single batched JOIN query across\n * all taxonomies so the cost is O(1) regardless of the number of entries or\n * taxonomies on the site.\n *\n * This eliminates the common N+1 pattern where templates loop over list\n * results and call getEntryTerms() per entry. With hydration, the list page\n * stays at a single round-trip for term data.\n *\n * Fails silently if the taxonomy tables don't exist yet (pre-migration).\n */\nasync function hydrateEntryTerms<D>(type: string, entries: ContentEntry<D>[]): Promise<void> {\n\tif (entries.length === 0) return;\n\n\ttry {\n\t\tconst { getAllTermsForEntries } = await import(\"./taxonomies/index.js\");\n\n\t\tconst ids = entries.map((e) => dataStr(entryData(e), \"id\")).filter(Boolean);\n\t\tif (ids.length === 0) return;\n\n\t\tconst termsMap = await getAllTermsForEntries(type, ids);\n\n\t\tfor (const entry of entries) {\n\t\t\tconst data = entryData(entry);\n\t\t\tconst dbId = dataStr(data, \"id\");\n\t\t\tif (!dbId) continue;\n\n\t\t\tdata.terms = termsMap.get(dbId) ?? {};\n\t\t}\n\t} catch (err) {\n\t\t// Only swallow \"table not found\" errors from pre-migration databases.\n\t\t// Matches SQLite/D1 (\"no such table\") and PostgreSQL (\"relation/table\n\t\t// ... does not exist\") via the shared helper.\n\t\tif (!isMissingTableError(err)) {\n\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\tconsole.warn(\"[emdash] Failed to hydrate terms:\", msg);\n\t\t}\n\t}\n}\n\n/**\n * Translation summary for a single locale variant\n */\nexport interface TranslationSummary {\n\t/** Content item ID */\n\tid: string;\n\t/** Locale code (e.g. \"en\", \"fr\") */\n\tlocale: string;\n\t/** URL slug */\n\tslug: string | null;\n\t/** Current status */\n\tstatus: string;\n}\n\n/**\n * Result from getTranslations\n */\nexport interface TranslationsResult {\n\t/** The translation group ID (shared across locales) */\n\ttranslationGroup: string;\n\t/** All locale variants in this group */\n\ttranslations: TranslationSummary[];\n\t/** Error if the query failed */\n\terror?: Error;\n}\n\n/**\n * Get all translations of a content item.\n *\n * Given a content entry, returns all locale variants that share the same\n * translation group. This is useful for building language switcher UI.\n *\n * @example\n * ```ts\n * import { getEmDashEntry, getTranslations } from \"emdash\";\n *\n * const { entry: post } = await getEmDashEntry(\"posts\", \"hello-world\", { locale: \"en\" });\n * const { translations } = await getTranslations(\"posts\", post.data.id);\n * // translations = [{ id: \"...\", locale: \"en\", slug: \"hello-world\", status: \"published\" }, ...]\n * ```\n */\nexport async function getTranslations(type: string, id: string): Promise<TranslationsResult> {\n\ttry {\n\t\tconst db = (await import(\"./loader.js\")).getDb;\n\t\tconst dbInstance = await db();\n\t\tconst { ContentRepository } = await import(\"./database/repositories/content.js\");\n\t\tconst repo = new ContentRepository(dbInstance);\n\n\t\t// Find the item to get its translation group\n\t\tconst item = await repo.findByIdOrSlug(type, id);\n\t\tif (!item) {\n\t\t\treturn {\n\t\t\t\ttranslationGroup: \"\",\n\t\t\t\ttranslations: [],\n\t\t\t\terror: new Error(`Content item not found: ${id}`),\n\t\t\t};\n\t\t}\n\n\t\tconst group = item.translationGroup || item.id;\n\t\tconst translations = await repo.findTranslations(type, group);\n\n\t\treturn {\n\t\t\ttranslationGroup: group,\n\t\t\ttranslations: translations.map((t) => ({\n\t\t\t\tid: t.id,\n\t\t\t\tlocale: t.locale || \"en\",\n\t\t\t\tslug: t.slug,\n\t\t\t\tstatus: t.status,\n\t\t\t})),\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\ttranslationGroup: \"\",\n\t\t\ttranslations: [],\n\t\t\terror: error instanceof Error ? error : new Error(String(error)),\n\t\t};\n\t}\n}\n\n/**\n * Result from resolveEmDashPath\n */\nexport interface ResolvePathResult<T = Record<string, unknown>> {\n\t/** The matched entry */\n\tentry: ContentEntry<T>;\n\t/** The collection slug that matched */\n\tcollection: string;\n\t/** Extracted parameters from the URL pattern (e.g. { slug: \"my-post\" }) */\n\tparams: Record<string, string>;\n}\n\n/** Matches `{paramName}` placeholders in URL patterns */\nconst URL_PARAM_PATTERN = /\\{(\\w+)\\}/g;\n\n/** Convert a URL pattern like \"/blog/{slug}\" to a regex and param name list */\nfunction patternToRegex(pattern: string): { regex: RegExp; paramNames: string[] } {\n\tconst paramNames: string[] = [];\n\tconst regexStr = pattern.replace(URL_PARAM_PATTERN, (_match, name: string) => {\n\t\tparamNames.push(name);\n\t\treturn \"([^/]+)\";\n\t});\n\treturn { regex: new RegExp(`^${regexStr}$`), paramNames };\n}\n\n/** Cached compiled URL patterns for resolveEmDashPath */\ninterface CachedPattern {\n\tslug: string;\n\tregex: RegExp;\n\tparamNames: string[];\n}\nlet cachedUrlPatterns: CachedPattern[] | null = null;\n\n/**\n * Invalidate the cached URL patterns used by resolveEmDashPath.\n * Call when collection URL patterns change (schema updates).\n */\nexport function invalidateUrlPatternCache(): void {\n\tcachedUrlPatterns = null;\n}\n\n/**\n * Resolve a URL path to a content entry by matching against collection URL patterns.\n *\n * Loads all collections with a `urlPattern` set, converts each pattern to a regex,\n * and tests the given path. On match, extracts the slug and fetches the entry.\n *\n * @example\n * ```ts\n * import { resolveEmDashPath } from \"emdash\";\n *\n * // Given pages with urlPattern \"/{slug}\" and posts with \"/blog/{slug}\":\n * const result = await resolveEmDashPath(\"/blog/hello-world\");\n * if (result) {\n * console.log(result.collection); // \"posts\"\n * console.log(result.params.slug); // \"hello-world\"\n * console.log(result.entry.data); // post data\n * }\n * ```\n */\nexport async function resolveEmDashPath<T = Record<string, unknown>>(\n\tpath: string,\n): Promise<ResolvePathResult<T> | null> {\n\t// Build and cache compiled patterns on first call\n\tif (!cachedUrlPatterns) {\n\t\tconst { getDb } = await import(\"./loader.js\");\n\t\tconst { SchemaRegistry } = await import(\"./schema/registry.js\");\n\t\tconst db = await getDb();\n\t\tconst registry = new SchemaRegistry(db);\n\t\tconst collections = await registry.listCollections();\n\n\t\tcachedUrlPatterns = [];\n\t\tfor (const collection of collections) {\n\t\t\tif (!collection.urlPattern) continue;\n\t\t\tconst { regex, paramNames } = patternToRegex(collection.urlPattern);\n\t\t\tcachedUrlPatterns.push({ slug: collection.slug, regex, paramNames });\n\t\t}\n\t}\n\n\tfor (const pattern of cachedUrlPatterns) {\n\t\tconst match = path.match(pattern.regex);\n\t\tif (!match) continue;\n\n\t\t// Extract params\n\t\tconst params: Record<string, string> = {};\n\t\tfor (let i = 0; i < pattern.paramNames.length; i++) {\n\t\t\tparams[pattern.paramNames[i]] = match[i + 1];\n\t\t}\n\n\t\t// Look up entry by slug (most common pattern)\n\t\tconst slug = params.slug;\n\t\tif (!slug) continue;\n\n\t\tconst { entry } = await getEmDashEntry<string, T>(pattern.slug, slug);\n\t\tif (entry) {\n\t\t\treturn { entry, collection: pattern.slug, params };\n\t\t}\n\t}\n\n\treturn null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoCA,SAAgB,eACf,YACA,IACA,SACY;CACZ,MAAM,OAAsB;EAC3B;EACA;EACA,GAAI,SAAS,UAAU,EAAE,QAAQ,QAAQ,QAAQ;EACjD,GAAI,SAAS,YAAY,EAAE,UAAU,MAAM;EAC3C;AAED,QAAO,IAAI,MAAM,EAAE,EAAe;EACjC,IAAI,GAAG,MAAM;AACZ,OAAI,SAAS,SAAU,eAAc,EAAE,mBAAmB,KAAK,UAAU,KAAK,EAAE;AAChF,OAAI,OAAO,SAAS,SAAU,QAAO;AAGrC,OAAI,SAAS,kBAAmB,QAAO,KAAK,UAAU,KAAK;AAG3D,UAAO,EACN,mBAAmB,KAAK,UAAU;IAAE,GAAG;IAAM,OAAO,OAAO,KAAK;IAAE,CAAC,EACnE;;EAEF,UAAU;AACT,UAAO,CAAC,kBAAkB;;EAE3B,yBAAyB,GAAG,MAAM;AACjC,OAAI,SAAS,kBACZ,QAAO;IACN,cAAc;IACd,YAAY;IACZ,OAAO,KAAK,UAAU,KAAK;IAC3B;;EAIH,CAAC;;;;;;AAOH,SAAgB,aAAwB;AACvC,QAAO,IAAI,MAAM,EAAE,EAAe;EACjC,IAAI,GAAG,MAAM;AACZ,OAAI,OAAO,SAAS,SAA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,IAAI,eADV,MAAM,OAAO,CACe,CACJ,iBAAiB;AAEpD,sBAAoB,EAAE;AACtB,OAAK,MAAM,cAAc,aAAa;AACrC,OAAI,CAAC,WAAW,WAAY;GAC5B,MAAM,EAAE,OAAO,eAAe,eAAe,WAAW,WAAW;AACnE,qBAAkB,KAAK;IAAE,MAAM,WAAW;IAAM;IAAO;IAAY,CAAC;;;AAItE,MAAK,MAAM,WAAW,mBAAmB;EACxC,MAAM,QAAQ,KAAK,MAAM,QAAQ,MAAM;AACvC,MAAI,CAAC,MAAO;EAGZ,MAAM,SAAiC,EAAE;AACzC,OAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,WAAW,QAAQ,IAC9C,QAAO,QAAQ,WAAW,MAAM,MAAM,IAAI;EAI3C,MAAM,OAAO,OAAO;AACpB,MAAI,CAAC,KAAM;EAEX,MAAM,EAAE,UAAU,MAAM,eAA0B,QAAQ,MAAM,KAAK;AACrE,MAAI,MACH,QAAO;GAAE;GAAO,YAAY,QAAQ;GAAM;GAAQ;;AAIpD,QAAO"}
@@ -1,5 +1,5 @@
1
- import { r as currentTimestampValue } from "./dialect-helpers-DhTzaUxP.mjs";
2
- import { i as encodeCursor, r as decodeCursor } from "./types-BIgulNsW.mjs";
1
+ import { i as currentTimestampValue } from "./dialect-helpers-BKCvISIQ.mjs";
2
+ import { i as encodeCursor, r as decodeCursor } from "./types-CRxNbK-Z.mjs";
3
3
  import { i as matchPattern, n as interpolateDestination, r as isPattern, t as compilePattern } from "./patterns-CrCYkMBb.mjs";
4
4
  import { sql } from "kysely";
5
5
  import { ulid } from "ulidx";
@@ -15,6 +15,8 @@ const MAX_404_LOG_ROWS = 1e4;
15
15
  const REFERRER_MAX_LENGTH = 512;
16
16
  /** Max stored length for the `User-Agent` header — truncated on insert. */
17
17
  const USER_AGENT_MAX_LENGTH = 256;
18
+ /** Pattern to escape LIKE wildcards: %, _, and backslash */
19
+ const LIKE_ESCAPE_RE = /[\\%_]/g;
18
20
  /**
19
21
  * Truncate a header-derived string to `max` chars, preserving `null`/`undefined`
20
22
  * as `null`. Empty strings stay empty (the caller decides whether to coerce).
@@ -55,8 +57,8 @@ var RedirectRepository = class {
55
57
  const limit = Math.min(Math.max(opts.limit ?? 50, 1), 100);
56
58
  let query = this.db.selectFrom("_emdash_redirects").selectAll().orderBy("created_at", "desc").orderBy("id", "desc").limit(limit + 1);
57
59
  if (opts.search) {
58
- const term = `%${opts.search}%`;
59
- query = query.where((eb) => eb.or([eb("source", "like", term), eb("destination", "like", term)]));
60
+ const term = `%${opts.search.replace(LIKE_ESCAPE_RE, (c) => `\\${c}`)}%`;
61
+ query = query.where((eb) => eb.or([sql`source LIKE ${term} ESCAPE '\\'`, sql`destination LIKE ${term} ESCAPE '\\'`]));
60
62
  }
61
63
  if (opts.group !== void 0) query = query.where("group_name", "=", opts.group);
62
64
  if (opts.enabled !== void 0) query = query.where("enabled", "=", opts.enabled ? 1 : 0);
@@ -239,7 +241,10 @@ var RedirectRepository = class {
239
241
  async find404s(opts) {
240
242
  const limit = Math.min(Math.max(opts.limit ?? 50, 1), 100);
241
243
  let query = this.db.selectFrom("_emdash_404_log").selectAll().orderBy("created_at", "desc").orderBy("id", "desc").limit(limit + 1);
242
- if (opts.search) query = query.where("path", "like", `%${opts.search}%`);
244
+ if (opts.search) {
245
+ const term = `%${opts.search.replace(LIKE_ESCAPE_RE, (c) => `\\${c}`)}%`;
246
+ query = query.where(sql`path LIKE ${term} ESCAPE '\\'`);
247
+ }
243
248
  if (opts.cursor) {
244
249
  const decoded = decodeCursor(opts.cursor);
245
250
  query = query.where((eb) => eb.or([eb("created_at", "<", decoded.orderValue), eb.and([eb("created_at", "=", decoded.orderValue), eb("id", "<", decoded.id)])]));
@@ -299,4 +304,4 @@ var RedirectRepository = class {
299
304
 
300
305
  //#endregion
301
306
  export { RedirectRepository as t };
302
- //# sourceMappingURL=redirect-D_pshWdf.mjs.map
307
+ //# sourceMappingURL=redirect-BhUBKRc1.mjs.map