qarpeo 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. package/dist/chunks/tools.mjs +993 -31
  2. package/dist/cli/index.mjs +1071 -31
  3. package/dist/fate/index.d.ts +9 -1
  4. package/dist/fate/index.mjs +20 -3
  5. package/dist/module.mjs +296 -750
  6. package/dist/runtime/browser.mjs +2 -2
  7. package/dist/runtime/comments-server.d.ts +3 -0
  8. package/dist/runtime/comments-server.mjs +2 -0
  9. package/dist/runtime/comments.d.ts +0 -2
  10. package/dist/runtime/comments.mjs +0 -2
  11. package/dist/runtime/db.d.ts +10 -9
  12. package/dist/runtime/db.mjs +79 -8
  13. package/dist/runtime/drizzle.mjs +21 -6
  14. package/dist/runtime/index.d.ts +4 -0
  15. package/dist/runtime/realtime-server.d.ts +4 -0
  16. package/dist/runtime/realtime-server.mjs +13 -0
  17. package/dist/runtime/realtime.d.ts +1 -4
  18. package/dist/runtime/realtime.mjs +0 -13
  19. package/dist/runtime/replica.d.ts +27 -0
  20. package/dist/runtime/replica.mjs +229 -0
  21. package/dist/runtime/server/durable-objects/agent.mjs +14 -2
  22. package/dist/runtime/server/durable-objects/room.d.ts +10 -0
  23. package/dist/runtime/server/durable-objects/room.mjs +119 -28
  24. package/dist/runtime/server/middleware/devtools.mjs +1 -1
  25. package/dist/runtime/server/middleware/tenancy.mjs +7 -4
  26. package/dist/runtime/server/plugins/store.mjs +1 -1
  27. package/dist/runtime/server/routes/__qarpeo/mail/track/click/[id].get.mjs +57 -17
  28. package/dist/runtime/server/routes/agents/[agent]/chat.post.mjs +19 -12
  29. package/dist/runtime/server/routes/agents/[agent]/clear.post.mjs +8 -9
  30. package/dist/runtime/server/routes/agents/[agent]/history.get.mjs +8 -9
  31. package/dist/runtime/server/routes/analytics/events.get.mjs +12 -2
  32. package/dist/runtime/server/routes/analytics/pageviews.get.mjs +10 -1
  33. package/dist/runtime/server/routes/analytics/summary.get.mjs +10 -1
  34. package/dist/runtime/server/routes/auth/2fa/disable.post.mjs +11 -2
  35. package/dist/runtime/server/routes/auth/2fa/setup.post.mjs +7 -0
  36. package/dist/runtime/server/routes/auth/2fa/verify.post.mjs +11 -2
  37. package/dist/runtime/server/routes/auth/account.delete.mjs +7 -0
  38. package/dist/runtime/server/routes/auth/magic-link/verify.get.mjs +5 -3
  39. package/dist/runtime/server/routes/auth/organization/sso/index.post.mjs +10 -0
  40. package/dist/runtime/server/routes/auth/otp/verify.post.mjs +5 -3
  41. package/dist/runtime/server/routes/auth/sso/saml/acs.post.mjs +18 -0
  42. package/dist/runtime/server/routes/auth/webauthn/login/options.post.d.ts +1 -1
  43. package/dist/runtime/server/routes/auth/webauthn/login/options.post.mjs +11 -2
  44. package/dist/runtime/server/routes/auth/webauthn/login/verify.post.mjs +10 -1
  45. package/dist/runtime/server/routes/auth/webauthn/register/options.post.d.ts +1 -1
  46. package/dist/runtime/server/routes/auth/webauthn/register/options.post.mjs +10 -1
  47. package/dist/runtime/server/routes/auth/webauthn/register/verify.post.mjs +10 -1
  48. package/dist/runtime/server/routes/browser/crawl.post.mjs +13 -0
  49. package/dist/runtime/server/routes/browser/invoice.post.mjs +15 -1
  50. package/dist/runtime/server/routes/browser/og-image.post.mjs +13 -0
  51. package/dist/runtime/server/routes/browser/pdf.post.mjs +15 -1
  52. package/dist/runtime/server/routes/browser/screenshot.post.mjs +13 -0
  53. package/dist/runtime/server/routes/cms/[collection]/[id]/preview-token.post.mjs +23 -8
  54. package/dist/runtime/server/routes/cms/[collection]/[id]/publish.post.mjs +2 -1
  55. package/dist/runtime/server/routes/cms/[collection]/[id]/review.post.mjs +2 -1
  56. package/dist/runtime/server/routes/cms/[collection]/[id]/revisions/[revId]/restore.post.mjs +2 -1
  57. package/dist/runtime/server/routes/cms/[collection]/[id].delete.mjs +2 -1
  58. package/dist/runtime/server/routes/cms/[collection]/[id].put.mjs +2 -1
  59. package/dist/runtime/server/routes/cms/[collection]/index.post.mjs +2 -1
  60. package/dist/runtime/server/routes/cms/categories/[id].delete.mjs +2 -1
  61. package/dist/runtime/server/routes/cms/categories/[id].put.mjs +2 -1
  62. package/dist/runtime/server/routes/cms/categories.post.mjs +2 -1
  63. package/dist/runtime/server/routes/cms/collections/[id].delete.mjs +2 -1
  64. package/dist/runtime/server/routes/cms/collections/[id].put.mjs +2 -1
  65. package/dist/runtime/server/routes/cms/collections/index.post.mjs +2 -1
  66. package/dist/runtime/server/routes/cms/export.post.mjs +1 -1
  67. package/dist/runtime/server/routes/cms/subscribers/[id].delete.mjs +2 -1
  68. package/dist/runtime/server/routes/cms/subscribers/[id].patch.mjs +2 -1
  69. package/dist/runtime/server/routes/cms/tags/[id].delete.mjs +2 -1
  70. package/dist/runtime/server/routes/cms/tags.post.mjs +2 -1
  71. package/dist/runtime/server/routes/comments/[id]/react.post.mjs +7 -3
  72. package/dist/runtime/server/routes/comments/[id]/report.post.mjs +3 -0
  73. package/dist/runtime/server/routes/comments/[id].delete.mjs +1 -1
  74. package/dist/runtime/server/routes/comments/[id].get.mjs +13 -0
  75. package/dist/runtime/server/routes/comments/[id].patch.mjs +1 -1
  76. package/dist/runtime/server/routes/fate.d.ts +6 -0
  77. package/dist/runtime/server/routes/fate.mjs +32 -3
  78. package/dist/runtime/server/routes/mail/bounce.post.mjs +14 -2
  79. package/dist/runtime/server/routes/mail/unsubscribe.mjs +2 -1
  80. package/dist/runtime/server/routes/mail/webhooks.post.mjs +18 -4
  81. package/dist/runtime/server/routes/notifications/[id].get.mjs +3 -4
  82. package/dist/runtime/server/routes/notifications/index.get.mjs +4 -2
  83. package/dist/runtime/server/routes/notifications/push/subscribe.post.mjs +3 -1
  84. package/dist/runtime/server/routes/notifications/push/unsubscribe.post.mjs +5 -3
  85. package/dist/runtime/server/routes/notifications/read-all.post.mjs +6 -2
  86. package/dist/runtime/server/routes/notifications/send.post.mjs +13 -2
  87. package/dist/runtime/server/routes/payments/cancel.post.mjs +1 -1
  88. package/dist/runtime/server/routes/payments/change-plan.post.mjs +1 -1
  89. package/dist/runtime/server/routes/payments/checkout.post.mjs +1 -1
  90. package/dist/runtime/server/routes/payments/pause.post.mjs +1 -1
  91. package/dist/runtime/server/routes/payments/portal.post.mjs +1 -1
  92. package/dist/runtime/server/routes/payments/subscription.get.mjs +1 -1
  93. package/dist/runtime/server/routes/payments/usage.get.mjs +1 -1
  94. package/dist/runtime/server/routes/payments/usage.post.mjs +1 -1
  95. package/dist/runtime/server/routes/payments/webhook.post.mjs +8 -1
  96. package/dist/runtime/server/routes/realtime/broadcast.post.mjs +3 -2
  97. package/dist/runtime/server/routes/realtime/history.delete.mjs +2 -2
  98. package/dist/runtime/server/routes/realtime/history.get.mjs +2 -2
  99. package/dist/runtime/server/routes/realtime/presence.get.mjs +3 -3
  100. package/dist/runtime/server/routes/realtime/state.get.mjs +3 -3
  101. package/dist/runtime/server/routes/realtime/state.post.mjs +13 -4
  102. package/dist/runtime/server/routes/realtime/ws.get.mjs +2 -2
  103. package/dist/runtime/server/routes/storage/file/[...key].delete.mjs +1 -1
  104. package/dist/runtime/server/routes/storage/file/[...key].get.mjs +7 -0
  105. package/dist/runtime/server/routes/storage/files.get.d.ts +1 -1
  106. package/dist/runtime/server/routes/storage/files.get.mjs +24 -4
  107. package/dist/runtime/server/routes/storage/multipart/abort.post.mjs +16 -1
  108. package/dist/runtime/server/routes/storage/multipart/complete.post.d.ts +1 -1
  109. package/dist/runtime/server/routes/storage/multipart/complete.post.mjs +15 -1
  110. package/dist/runtime/server/routes/storage/multipart/create.post.mjs +7 -0
  111. package/dist/runtime/server/routes/storage/multipart/part.put.mjs +15 -1
  112. package/dist/runtime/server/routes/storage/presigned-r2.post.mjs +8 -1
  113. package/dist/runtime/server/routes/storage/presigned.post.d.ts +1 -1
  114. package/dist/runtime/server/routes/storage/presigned.post.mjs +8 -1
  115. package/dist/runtime/server/routes/storage/sign.post.mjs +7 -0
  116. package/dist/runtime/server/routes/storage/upload.post.d.ts +2 -2
  117. package/dist/runtime/server/routes/store/cart/index.delete.mjs +3 -4
  118. package/dist/runtime/server/routes/store/cart/index.get.mjs +3 -10
  119. package/dist/runtime/server/routes/store/cart/items/[id].delete.mjs +6 -4
  120. package/dist/runtime/server/routes/store/cart/items/[id].patch.mjs +12 -4
  121. package/dist/runtime/server/routes/store/cart/items.post.mjs +9 -10
  122. package/dist/runtime/server/routes/store/categories/index.get.mjs +4 -2
  123. package/dist/runtime/server/routes/store/checkout.post.mjs +13 -3
  124. package/dist/runtime/server/routes/store/coupons/apply.post.mjs +6 -5
  125. package/dist/runtime/server/routes/store/orders/[id].get.mjs +2 -2
  126. package/dist/runtime/server/routes/store/orders/download/[token].get.mjs +6 -3
  127. package/dist/runtime/server/routes/store/orders/index.get.mjs +1 -1
  128. package/dist/runtime/server/routes/store/products/[slug].get.mjs +2 -2
  129. package/dist/runtime/server/routes/store/products/index.get.mjs +1 -1
  130. package/dist/runtime/server/routes/store/tax/calculate.post.mjs +10 -0
  131. package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/index.delete.mjs +26 -25
  132. package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/verify.post.mjs +26 -25
  133. package/dist/runtime/server/utils/ai.d.ts +6 -0
  134. package/dist/runtime/server/utils/ai.mjs +12 -2
  135. package/dist/runtime/server/utils/analytics-query.mjs +8 -4
  136. package/dist/runtime/server/utils/browser-utils.d.ts +9 -0
  137. package/dist/runtime/server/utils/browser-utils.mjs +135 -0
  138. package/dist/runtime/server/utils/cms/cache.d.ts +13 -0
  139. package/dist/runtime/server/utils/cms/cache.mjs +95 -0
  140. package/dist/runtime/server/utils/cms/common.mjs +1 -1
  141. package/dist/runtime/server/utils/cms/markdown.mjs +38 -8
  142. package/dist/runtime/server/utils/cms/mutations.d.ts +26 -0
  143. package/dist/runtime/server/utils/cms/mutations.mjs +569 -0
  144. package/dist/runtime/server/utils/cms/path.d.ts +8 -0
  145. package/dist/runtime/server/utils/cms/path.mjs +23 -0
  146. package/dist/runtime/server/utils/cms/queries.d.ts +27 -0
  147. package/dist/runtime/server/utils/cms/queries.mjs +366 -0
  148. package/dist/runtime/server/utils/cms/references.d.ts +48 -0
  149. package/dist/runtime/server/utils/cms/references.mjs +309 -0
  150. package/dist/runtime/server/utils/cms/revisions.d.ts +7 -0
  151. package/dist/runtime/server/utils/cms/revisions.mjs +60 -0
  152. package/dist/runtime/server/utils/cms/sync.mjs +3 -3
  153. package/dist/runtime/server/utils/cms.d.ts +5 -82
  154. package/dist/runtime/server/utils/cms.mjs +28 -1367
  155. package/dist/runtime/server/utils/comments.d.ts +11 -0
  156. package/dist/runtime/server/utils/comments.mjs +65 -17
  157. package/dist/runtime/server/utils/crypto.mjs +1 -1
  158. package/dist/runtime/server/utils/domains.mjs +9 -0
  159. package/dist/runtime/server/utils/drizzle.d.ts +26 -1
  160. package/dist/runtime/server/utils/drizzle.mjs +78 -19
  161. package/dist/runtime/server/utils/email-inbound.mjs +9 -1
  162. package/dist/runtime/server/utils/impersonation.mjs +58 -1
  163. package/dist/runtime/server/utils/lock.d.ts +11 -0
  164. package/dist/runtime/server/utils/lock.mjs +4 -0
  165. package/dist/runtime/server/utils/mail-suppression.mjs +48 -13
  166. package/dist/runtime/server/utils/mail.d.ts +2 -1
  167. package/dist/runtime/server/utils/mail.mjs +17 -11
  168. package/dist/runtime/server/utils/notifications.d.ts +13 -4
  169. package/dist/runtime/server/utils/notifications.mjs +20 -4
  170. package/dist/runtime/server/utils/organization.mjs +36 -1
  171. package/dist/runtime/server/utils/passwordless.mjs +8 -0
  172. package/dist/runtime/server/utils/payments/checkout.d.ts +34 -0
  173. package/dist/runtime/server/utils/payments/checkout.mjs +158 -0
  174. package/dist/runtime/server/utils/payments/common.d.ts +45 -0
  175. package/dist/runtime/server/utils/payments/common.mjs +234 -0
  176. package/dist/runtime/server/utils/payments/index.d.ts +9 -0
  177. package/dist/runtime/server/utils/payments/index.mjs +21 -0
  178. package/dist/runtime/server/utils/payments/lemonsqueezy.d.ts +7 -0
  179. package/dist/runtime/server/utils/payments/lemonsqueezy.mjs +55 -0
  180. package/dist/runtime/server/utils/payments/paddle.d.ts +7 -0
  181. package/dist/runtime/server/utils/payments/paddle.mjs +92 -0
  182. package/dist/runtime/server/utils/payments/polar.d.ts +11 -0
  183. package/dist/runtime/server/utils/payments/polar.mjs +66 -0
  184. package/dist/runtime/server/utils/payments/stripe.d.ts +7 -0
  185. package/dist/runtime/server/utils/payments/stripe.mjs +159 -0
  186. package/dist/runtime/server/utils/payments/subscriptions.d.ts +89 -0
  187. package/dist/runtime/server/utils/payments/subscriptions.mjs +236 -0
  188. package/dist/runtime/server/utils/payments/usage.d.ts +12 -0
  189. package/dist/runtime/server/utils/payments/usage.mjs +143 -0
  190. package/dist/runtime/server/utils/payments/webhooks.d.ts +10 -0
  191. package/dist/runtime/server/utils/payments/webhooks.mjs +200 -0
  192. package/dist/runtime/server/utils/payments.d.ts +1 -158
  193. package/dist/runtime/server/utils/payments.mjs +1 -1289
  194. package/dist/runtime/server/utils/queue.d.ts +2 -0
  195. package/dist/runtime/server/utils/queue.mjs +34 -21
  196. package/dist/runtime/server/utils/rag.mjs +30 -17
  197. package/dist/runtime/server/utils/realtime.d.ts +5 -1
  198. package/dist/runtime/server/utils/realtime.mjs +43 -7
  199. package/dist/runtime/server/utils/session.mjs +16 -3
  200. package/dist/runtime/server/utils/sso.d.ts +3 -0
  201. package/dist/runtime/server/utils/sso.mjs +43 -0
  202. package/dist/runtime/server/utils/storage.mjs +12 -1
  203. package/dist/runtime/server/utils/store/cart.d.ts +63 -0
  204. package/dist/runtime/server/utils/store/cart.mjs +542 -0
  205. package/dist/runtime/server/utils/store/checkout.d.ts +14 -0
  206. package/dist/runtime/server/utils/store/checkout.mjs +118 -0
  207. package/dist/runtime/server/utils/store/common.d.ts +29 -0
  208. package/dist/runtime/server/utils/store/common.mjs +479 -0
  209. package/dist/runtime/server/utils/store/index.d.ts +7 -0
  210. package/dist/runtime/server/utils/store/index.mjs +30 -0
  211. package/dist/runtime/server/utils/store/inventory.d.ts +25 -0
  212. package/dist/runtime/server/utils/store/inventory.mjs +190 -0
  213. package/dist/runtime/server/utils/store/orders.d.ts +60 -0
  214. package/dist/runtime/server/utils/store/orders.mjs +590 -0
  215. package/dist/runtime/server/utils/store/products.d.ts +35 -0
  216. package/dist/runtime/server/utils/store/products.mjs +461 -0
  217. package/dist/runtime/server/utils/store/vendor.d.ts +18 -0
  218. package/dist/runtime/server/utils/store/vendor.mjs +68 -0
  219. package/dist/runtime/server/utils/store.d.ts +1 -207
  220. package/dist/runtime/server/utils/store.mjs +1 -2227
  221. package/dist/runtime/server/utils/string.d.ts +1 -1
  222. package/dist/runtime/server/utils/string.mjs +12 -4
  223. package/dist/runtime/server/utils/tenant.mjs +19 -5
  224. package/dist/runtime/server/utils/tracker.mjs +2 -0
  225. package/dist/runtime/server.d.ts +3 -3
  226. package/dist/runtime/server.mjs +4 -4
  227. package/dist/runtime/storage-server.d.ts +2 -0
  228. package/dist/runtime/storage-server.mjs +1 -0
  229. package/dist/runtime/storage.d.ts +1 -1
  230. package/dist/runtime/storage.mjs +0 -1
  231. package/dist/runtime/store.d.ts +0 -1
  232. package/dist/runtime/store.mjs +0 -1
  233. package/dist/runtime/test-utils.d.ts +4 -0
  234. package/dist/runtime/test-utils.mjs +54 -0
  235. package/dist/runtime/types/d1.d.ts +43 -0
  236. package/dist/runtime/types/drizzle.d.ts +6 -0
  237. package/dist/runtime/types/store.d.ts +1 -1
  238. package/dist/types/analytics.d.ts +80 -0
  239. package/dist/types/auth.d.ts +282 -0
  240. package/dist/types/cache.d.ts +55 -0
  241. package/dist/types/comments.d.ts +130 -0
  242. package/dist/types/db.d.ts +29 -0
  243. package/dist/types/email.d.ts +182 -0
  244. package/dist/types/index.d.ts +22 -0
  245. package/dist/types/jobs.d.ts +58 -0
  246. package/dist/types/notifications.d.ts +77 -0
  247. package/dist/types/options.d.ts +363 -0
  248. package/dist/types/payments.d.ts +145 -0
  249. package/dist/types/ratelimit.d.ts +71 -0
  250. package/dist/types/realtime.d.ts +136 -0
  251. package/dist/types/site.d.ts +121 -0
  252. package/dist/types/storage.d.ts +164 -0
  253. package/dist/types/store-options.d.ts +199 -0
  254. package/dist/types/tenant.d.ts +100 -0
  255. package/dist/types.d.ts +1 -2174
  256. package/dist/utils/migration-lock.d.ts +139 -0
  257. package/dist/utils/pkg.d.ts +14 -1
  258. package/dist/utils/schema-diff.d.ts +39 -0
  259. package/package.json +55 -17
  260. package/dist/chunks/auth-schema.mjs +0 -364
@@ -74,6 +74,17 @@ export interface QueryCommentsOptions {
74
74
  export declare function getCommentsConfig(event?: RequestEvent): CommentsOptions & {
75
75
  prefix?: string;
76
76
  };
77
+ /**
78
+ * Extracts the integer sequence number from a materialized path segment.
79
+ * Handles both hardened segments (e.g. "000005_x9y2" -> 5) and legacy 4-digit segments ("0004" -> 4).
80
+ */
81
+ export declare function extractSegmentIndex(segment: string): number;
82
+ /**
83
+ * Builds a materialized path for a new comment.
84
+ * Formats segments with 6-digit zero padding and a unique 4-character tiebreaker
85
+ * (e.g. /000001_a1b2/) to guarantee collision-free subtree indexing even during concurrent posts.
86
+ */
87
+ export declare function buildPath(parentPath: string, siblingIndex: number): string;
77
88
  /**
78
89
  * Creates all three comments tables if they do not already exist.
79
90
  * Uses a module-level promise cache so the 10+ SQL statements only execute once
@@ -8,6 +8,8 @@ import { nanoid } from "./crypto.mjs";
8
8
  import { validateCommentContent } from "./comments-filter.mjs";
9
9
  import { validateTargetUrn } from "./urn.mjs";
10
10
  import { resolveTableName, resolveIndexName } from "./table-names.mjs";
11
+ import { escapeHtml } from "./string.mjs";
12
+ import { getTenant } from "./tenant.mjs";
11
13
  export { isValidTargetUrn, validateTargetUrn } from "./urn.mjs";
12
14
  function getD1(event) {
13
15
  const env = getCloudflareEnv(event);
@@ -101,7 +103,9 @@ function safeJsonParse(raw, fallback) {
101
103
  }
102
104
  }
103
105
  function generateAvatarSvg(name) {
104
- const initials = name.split(/\s+/).slice(0, 2).map((w) => w[0]?.toUpperCase() ?? "").join("");
106
+ const safeInitials = escapeHtml(
107
+ name.replace(/[^a-zA-Z0-9\s]/g, "").trim().split(/\s+/).slice(0, 2).map((w) => w[0]?.toUpperCase() ?? "").join("") || "A"
108
+ );
105
109
  let hash = 0;
106
110
  for (let i = 0; i < name.length; i++) {
107
111
  hash = (hash << 5) - hash + name.charCodeAt(i) | 0;
@@ -109,12 +113,29 @@ function generateAvatarSvg(name) {
109
113
  const hue = Math.abs(hash) % 360;
110
114
  const bg = `hsl(${hue},60%,45%)`;
111
115
  const fg = "#ffffff";
112
- const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40"><circle cx="20" cy="20" r="20" fill="${bg}"/><text x="20" y="25" text-anchor="middle" font-family="system-ui,sans-serif" font-size="16" font-weight="600" fill="${fg}">${initials}</text></svg>`;
116
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40"><circle cx="20" cy="20" r="20" fill="${bg}"/><text x="20" y="25" text-anchor="middle" font-family="system-ui,sans-serif" font-size="16" font-weight="600" fill="${fg}">${safeInitials}</text></svg>`;
113
117
  return `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`;
114
118
  }
115
- function buildPath(parentPath, siblingIndex) {
116
- const segment = String(siblingIndex + 1).padStart(4, "0");
117
- return `${parentPath}${segment}/`;
119
+ export function extractSegmentIndex(segment) {
120
+ const clean = segment.replace(/\/$/, "");
121
+ const parts = clean.split("_");
122
+ const num = parseInt(parts[0], 10);
123
+ return isNaN(num) ? 0 : num;
124
+ }
125
+ async function resolveNextSiblingIndex(db, table, targetUrn, parentId) {
126
+ const query = parentId ? `SELECT path FROM ${table} WHERE parent_id = ? ORDER BY path DESC LIMIT 1` : `SELECT path FROM ${table} WHERE target_urn = ? AND parent_id IS NULL ORDER BY path DESC LIMIT 1`;
127
+ const params = parentId ? [parentId] : [targetUrn];
128
+ const lastRow = await db.prepare(query).bind(...params).first();
129
+ if (!lastRow?.path) return 0;
130
+ const segments = lastRow.path.split("/").filter(Boolean);
131
+ const lastSegment = segments[segments.length - 1] || "";
132
+ return extractSegmentIndex(lastSegment);
133
+ }
134
+ export function buildPath(parentPath, siblingIndex) {
135
+ const segmentIndex = String(siblingIndex + 1).padStart(6, "0");
136
+ const tieBreaker = nanoid(4);
137
+ const prefix = parentPath.endsWith("/") ? parentPath : `${parentPath}/`;
138
+ return `${prefix}${segmentIndex}_${tieBreaker}/`;
118
139
  }
119
140
  let _ensureCommentsTablesPromise = null;
120
141
  export async function ensureCommentsTables(event) {
@@ -295,10 +316,18 @@ export async function createComment(input, event) {
295
316
  const modResult = validateCommentContent(content, cfg.moderation ?? {});
296
317
  let isQuarantined = !modResult.valid;
297
318
  let moderationViolation = modResult.violation;
298
- const authorName = (input.authorName ?? auth?.user?.name ?? "Anonymous").trim();
319
+ const rawAuthorName = (input.authorName ?? auth?.user?.name ?? "Anonymous").trim();
320
+ const authorName = escapeHtml(rawAuthorName).slice(0, 100);
299
321
  if (!authorName) {
300
322
  throw createError({ statusCode: 400, statusMessage: "Author name is required." });
301
323
  }
324
+ let authorEmail = input.authorEmail ?? auth?.user?.email ?? null;
325
+ if (authorEmail) {
326
+ authorEmail = String(authorEmail).trim().toLowerCase();
327
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(authorEmail) || authorEmail.length > 254) {
328
+ throw createError({ statusCode: 400, statusMessage: "Invalid email address format." });
329
+ }
330
+ }
302
331
  if (cfg.turnstile && event) {
303
332
  await requireTurnstile(event, input.turnstileToken);
304
333
  }
@@ -308,9 +337,7 @@ export async function createComment(input, event) {
308
337
  let path = "/";
309
338
  let depth = 0;
310
339
  if (input.parentId) {
311
- const parent = await db.prepare(
312
- `SELECT id, path, depth, status, (SELECT COUNT(*) FROM ${t} WHERE parent_id = ?) as sibling_cnt FROM ${t} WHERE id = ?`
313
- ).bind(input.parentId, input.parentId).first();
340
+ const parent = await db.prepare(`SELECT id, path, depth, status FROM ${t} WHERE id = ?`).bind(input.parentId).first();
314
341
  if (!parent) {
315
342
  throw createError({ statusCode: 404, statusMessage: "Parent comment not found." });
316
343
  }
@@ -323,13 +350,12 @@ export async function createComment(input, event) {
323
350
  statusMessage: `Maximum thread depth of ${getThreadDepth(event)} reached.`
324
351
  });
325
352
  }
326
- const siblingCount = Number(parent.sibling_cnt) || 0;
327
- path = buildPath(parent.path, siblingCount);
353
+ const siblingIndex = await resolveNextSiblingIndex(db, t, input.targetUrn, input.parentId);
354
+ path = buildPath(parent.path, siblingIndex);
328
355
  depth = parent.depth + 1;
329
356
  } else {
330
- const siblingResult = await db.prepare(`SELECT COUNT(*) as cnt FROM ${t} WHERE target_urn = ? AND parent_id IS NULL`).bind(input.targetUrn).first();
331
- const siblingCount = siblingResult?.cnt ?? 0;
332
- path = buildPath("/", siblingCount);
357
+ const siblingIndex = await resolveNextSiblingIndex(db, t, input.targetUrn, null);
358
+ path = buildPath("/", siblingIndex);
333
359
  }
334
360
  let status = getDefaultStatus(event);
335
361
  if (auth?.user?.id) {
@@ -343,7 +369,6 @@ export async function createComment(input, event) {
343
369
  const avatar = generateAvatarSvg(authorName);
344
370
  const ip = event ? getCallerIp(event) : void 0;
345
371
  const authorId = input.authorId ?? auth?.user?.id ?? null;
346
- const authorEmail = input.authorEmail ?? auth?.user?.email ?? null;
347
372
  const duplicateWindowMs = cfg.moderation?.duplicateWindowMs ?? 3e5;
348
373
  if (duplicateWindowMs > 0 && (ip || authorId)) {
349
374
  const since = now - duplicateWindowMs;
@@ -452,7 +477,19 @@ export async function batchModerateComments(input, event) {
452
477
  return { success: true, count: 0 };
453
478
  }
454
479
  const cappedIds = ids.slice(0, 100);
480
+ const activeTenant = event ? getTenant(event) : null;
481
+ const tenantClause = activeTenant ? ` AND tenant_id = ?` : "";
482
+ const tenantBinds = activeTenant ? [activeTenant.id] : [];
455
483
  if (input.action === "delete") {
484
+ if (activeTenant) {
485
+ const db2 = getD1(event);
486
+ const t2 = getTable(event);
487
+ const placeholders2 = cappedIds.map(() => "?").join(", ");
488
+ const allowedRows = await db2.prepare(`SELECT id FROM ${t2} WHERE id IN (${placeholders2}) AND tenant_id = ?`).bind(...cappedIds, activeTenant.id).all();
489
+ const allowedIds = (allowedRows.results || []).map((r) => r.id);
490
+ await Promise.all(allowedIds.map((id) => deleteComment(id, event)));
491
+ return { success: true, count: allowedIds.length };
492
+ }
456
493
  await Promise.all(cappedIds.map((id) => deleteComment(id, event)));
457
494
  return { success: true, count: cappedIds.length };
458
495
  }
@@ -461,14 +498,25 @@ export async function batchModerateComments(input, event) {
461
498
  const t = getTable(event);
462
499
  const now = Date.now();
463
500
  const placeholders = cappedIds.map(() => "?").join(", ");
464
- await db.prepare(`UPDATE ${t} SET status = ?, updated_at = ? WHERE id IN (${placeholders})`).bind(newStatus, now, ...cappedIds).run();
501
+ await db.prepare(`UPDATE ${t} SET status = ?, updated_at = ? WHERE id IN (${placeholders})${tenantClause}`).bind(newStatus, now, ...cappedIds, ...tenantBinds).run();
465
502
  return { success: true, count: cappedIds.length };
466
503
  }
467
504
  export async function reportComment(commentId, reason, opts, event) {
468
505
  const db = getD1(event);
506
+ const ip = event ? getCallerIp(event) : void 0;
507
+ if (opts?.userId || ip) {
508
+ const existingReport = await db.prepare(
509
+ `SELECT id FROM ${getReportsTable(event)} WHERE comment_id = ? AND ((reporter_user_id IS NOT NULL AND reporter_user_id = ?) OR (reporter_user_id IS NULL AND reporter_ip = ?)) LIMIT 1`
510
+ ).bind(commentId, opts?.userId ?? null, ip ?? null).first();
511
+ if (existingReport) {
512
+ throw createError({
513
+ statusCode: 409,
514
+ statusMessage: "You have already reported this comment."
515
+ });
516
+ }
517
+ }
469
518
  const id = nanoid();
470
519
  const now = Date.now();
471
- const ip = event ? getCallerIp(event) : void 0;
472
520
  await db.prepare(
473
521
  `INSERT INTO ${getReportsTable(event)} (id, comment_id, reporter_ip, reporter_user_id, reason, note, created_at)
474
522
  VALUES (?, ?, ?, ?, ?, ?, ?)`
@@ -17,7 +17,7 @@ export function timingSafeEqualString(a, b) {
17
17
  return diff === 0;
18
18
  }
19
19
  export const constantTimeEqual = timingSafeEqualString;
20
- const NANOID_CHARS = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLFGQZbfghjklqvwyzrict";
20
+ const NANOID_CHARS = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLFGQZbfghjklqvwyzrict_";
21
21
  export function nanoid(size = 21) {
22
22
  const bytes = new Uint8Array(size);
23
23
  crypto.getRandomValues(bytes);
@@ -108,6 +108,15 @@ export async function registerCustomDomain(tenantId, rawDomain, options = {}, ev
108
108
  }
109
109
  const config = getMultitenantConfig(event);
110
110
  const cnameTarget = options.cnameTarget || config.cnameTarget || "cname.qarpeo.com";
111
+ const rawRootDomains = config.rootDomains || [];
112
+ const rootDomains = (Array.isArray(rawRootDomains) ? rawRootDomains : [rawRootDomains]).filter(Boolean).map((d) => d.toLowerCase().trim());
113
+ for (const root of rootDomains) {
114
+ if (domain === root || domain.endsWith(`.${root}`)) {
115
+ throw new Error(
116
+ `[qarpeo/domains] Domain "${domain}" cannot be registered as a custom domain because it is a subdomain of platform root domain "${root}".`
117
+ );
118
+ }
119
+ }
111
120
  const existing = await getCustomDomain(domain, event);
112
121
  if (existing) {
113
122
  throw new Error(`[qarpeo/domains] Domain "${domain}" is already registered.`);
@@ -5,9 +5,26 @@ type SchemaRelations = InferDrizzleRelations<typeof _schema>;
5
5
  export interface UseDrizzleOptions<S extends Record<string, unknown> = typeof _schema> {
6
6
  schema?: S;
7
7
  event?: CFEvent;
8
+ /**
9
+ * Route reads to Cloudflare D1 Read Replicas:
10
+ * - `true`: routes to nearest replica using "first-unconstrained" session
11
+ * - `"first-unconstrained"`: reads from nearest replica immediately
12
+ * - `"first-primary"`: first query routed to primary, subsequent reads routed to replica
13
+ * - `string`: bookmark token string to guarantee sequential consistency
14
+ */
15
+ replica?: boolean | "first-unconstrained" | "first-primary" | string;
16
+ /**
17
+ * Optional Cloudflare D1 session bookmark token.
18
+ */
19
+ bookmark?: string;
20
+ /**
21
+ * Automatically fallback to primary database if replica read fails.
22
+ * Default: `true`.
23
+ */
24
+ fallbackToPrimary?: boolean;
8
25
  }
9
26
  /** Access a typed Drizzle ORM client connected to Cloudflare D1 or PostgreSQL. */
10
- export declare function useDrizzle<S extends Record<string, unknown> = typeof _schema>(bindingName?: string, eventOrOptions?: CFEvent | UseDrizzleOptions<S>): QarpeoDrizzleDB<InferDrizzleRelations<S>>;
27
+ export declare function useDrizzle<S extends Record<string, unknown> = typeof _schema>(bindingNameOrOptions?: string | CFEvent | UseDrizzleOptions<S>, eventOrOptions?: CFEvent | UseDrizzleOptions<S>): QarpeoDrizzleDB<InferDrizzleRelations<S>>;
11
28
  /**
12
29
  * Primary typed database accessor for Cloudflare D1 or PostgreSQL.
13
30
  *
@@ -20,10 +37,18 @@ export declare function useDrizzle<S extends Record<string, unknown> = typeof _s
20
37
  * // Secondary D1 database (e.g. db/d1-analytics/ or ANALYTICS_DB)
21
38
  * const analytics = useDb("analytics")
22
39
  *
40
+ * // Cloudflare D1 Read Replica routing (reads route to replica, writes route to primary)
41
+ * const readDb = useDb({ replica: true })
42
+ * const users = await readDb.query.users.findMany()
43
+ *
44
+ * // Named database with read replica and sequential consistency bookmark
45
+ * const analyticsReplica = useDb("analytics", { replica: true, bookmark: "bm_123" })
46
+ *
23
47
  * // PostgreSQL via Hyperdrive
24
48
  * const warehouse = useDb("postgres")
25
49
  * ```
26
50
  */
51
+ export declare function useDb<S extends Record<string, unknown> = typeof _schema>(options?: UseDrizzleOptions<S>): QarpeoDrizzleDB<InferDrizzleRelations<S>>;
27
52
  export declare function useDb<S extends Record<string, unknown> = typeof _schema>(bindingName?: string, eventOrOptions?: CFEvent | UseDrizzleOptions<S>): QarpeoDrizzleDB<InferDrizzleRelations<S>>;
28
53
  /** Auto-imported `db` client wrapping Cloudflare D1 with Drizzle ORM. */
29
54
  export declare const db: QarpeoDrizzleDB<SchemaRelations>;
@@ -1,32 +1,65 @@
1
1
  import { defineRelations } from "drizzle-orm";
2
2
  import { drizzle as drizzleD1 } from "drizzle-orm/d1";
3
3
  import { drizzle as drizzlePostgres } from "drizzle-orm/postgres-js";
4
- import postgres from "postgres";
5
4
  import * as _schema from "#qarpeo/schema";
6
5
  import { getD1Binding, getDatabaseInfo } from "../../index.mjs";
6
+ import { createReplicaRoutedD1 } from "../../replica.mjs";
7
7
  const drizzleCache = /* @__PURE__ */ new WeakMap();
8
8
  const pgDrizzleCache = /* @__PURE__ */ new Map();
9
- export function useDrizzle(bindingName, eventOrOptions) {
9
+ export function useDrizzle(bindingNameOrOptions, eventOrOptions) {
10
+ let bindingName;
10
11
  let event;
11
12
  let activeSchema = _schema;
12
- if (eventOrOptions) {
13
- if ("node" in eventOrOptions || "context" in eventOrOptions || "req" in eventOrOptions) {
14
- event = eventOrOptions;
15
- } else if ("schema" in eventOrOptions || "event" in eventOrOptions) {
16
- const opts = eventOrOptions;
17
- if (opts.schema) activeSchema = opts.schema;
18
- if (opts.event) event = opts.event;
13
+ let replica;
14
+ let bookmark;
15
+ let fallbackToPrimary = true;
16
+ let rawOpts;
17
+ if (typeof bindingNameOrOptions === "string") {
18
+ bindingName = bindingNameOrOptions;
19
+ rawOpts = eventOrOptions;
20
+ } else if (bindingNameOrOptions && typeof bindingNameOrOptions === "object") {
21
+ if ("node" in bindingNameOrOptions || "context" in bindingNameOrOptions || "req" in bindingNameOrOptions) {
22
+ event = bindingNameOrOptions;
23
+ rawOpts = eventOrOptions;
19
24
  } else {
20
- event = eventOrOptions;
25
+ rawOpts = bindingNameOrOptions;
26
+ }
27
+ } else {
28
+ rawOpts = eventOrOptions;
29
+ }
30
+ if (rawOpts) {
31
+ if ("node" in rawOpts || "context" in rawOpts || "req" in rawOpts) {
32
+ event = rawOpts;
33
+ } else {
34
+ if (rawOpts.schema) activeSchema = rawOpts.schema;
35
+ if (rawOpts.event) event = rawOpts.event;
36
+ if (rawOpts.replica !== void 0) replica = rawOpts.replica;
37
+ if (rawOpts.bookmark !== void 0) bookmark = rawOpts.bookmark;
38
+ if (rawOpts.fallbackToPrimary !== void 0) fallbackToPrimary = rawOpts.fallbackToPrimary;
21
39
  }
22
40
  }
23
41
  const dbInfo = getDatabaseInfo(bindingName, event);
24
42
  if (dbInfo.isPostgres && dbInfo.url) {
43
+ let postgresLib;
44
+ try {
45
+ const req = globalThis.require || (typeof globalThis.process !== "undefined" && typeof require !== "undefined" ? require : void 0);
46
+ if (req) {
47
+ const pgMod = req("postgres");
48
+ postgresLib = pgMod?.default || pgMod;
49
+ }
50
+ } catch {
51
+ }
52
+ if (!postgresLib) {
53
+ throw new Error(
54
+ `[qarpeo] PostgreSQL runtime client requires the \`postgres\` package.
55
+ Install it with: pnpm add postgres`
56
+ );
57
+ }
25
58
  const isDefaultSchema2 = activeSchema === _schema;
26
59
  const cacheKey = `${dbInfo.url}:${isDefaultSchema2 ? "default" : "custom"}`;
27
60
  let pgInstance = pgDrizzleCache.get(cacheKey);
28
61
  if (!pgInstance) {
29
- const client = postgres(dbInfo.url, {
62
+ const client = postgresLib(dbInfo.url, {
30
63
  prepare: false,
31
64
  max: 1
32
65
  });
@@ -72,12 +105,13 @@ Install it with: pnpm add mysql2`
72
105
  const cacheKey = `mysql:${dbInfo.url}:${isDefaultSchema2 ? "default" : "custom"}`;
73
106
  let mysqlInstance = pgDrizzleCache.get(cacheKey);
74
107
  if (!mysqlInstance) {
75
- const pool = mysqlLib.createPool(dbInfo.url);
108
+ const mysqlCreatePool = mysqlLib.default?.createPool ?? mysqlLib.createPool;
109
+ const pool = mysqlCreatePool(dbInfo.url);
76
110
  const relations = defineRelations(activeSchema);
77
- const rawDrizzle = drizzleMysql(pool, {
111
+ const rawDrizzle = drizzleMysql({
112
+ client: pool,
78
113
  relations,
79
- schema: activeSchema,
80
- mode: "default"
114
+ schema: activeSchema
81
115
  });
82
116
  mysqlInstance = Object.assign(rawDrizzle, {
83
117
  raw: () => pool
@@ -89,14 +123,39 @@ Install it with: pnpm add mysql2`
89
123
  return mysqlInstance;
90
124
  }
91
125
  const resolvedBinding = bindingName || globalThis.process?.env?.QARPEO_DEFAULT_DB_BINDING || "DB";
92
- const d1 = getD1Binding(resolvedBinding, event);
126
+ const primaryD1 = getD1Binding(resolvedBinding, event);
127
+ let d1 = primaryD1;
128
+ if (replica) {
129
+ const evtContext = event?.context;
130
+ const sessionKey = `_qarpeo_replica_${resolvedBinding}_${String(replica)}_${bookmark || ""}`;
131
+ if (evtContext && evtContext[sessionKey]) {
132
+ d1 = evtContext[sessionKey];
133
+ } else {
134
+ d1 = createReplicaRoutedD1(
135
+ primaryD1,
136
+ {
137
+ replica,
138
+ bookmark,
139
+ fallbackToPrimary,
140
+ event
141
+ },
142
+ resolvedBinding
143
+ );
144
+ if (evtContext) {
145
+ evtContext[sessionKey] = d1;
146
+ }
147
+ }
148
+ }
93
149
  const isDefaultSchema = activeSchema === _schema;
94
150
  let instance = isDefaultSchema ? drizzleCache.get(d1) : void 0;
95
151
  if (!instance) {
96
152
  const relations = defineRelations(activeSchema);
97
153
  const rawDrizzle = drizzleD1(d1, { relations, schema: activeSchema });
98
154
  instance = Object.assign(rawDrizzle, {
99
- raw: (bName) => getD1Binding(bName || resolvedBinding, event)
155
+ raw: (bName) => getD1Binding(bName || resolvedBinding, event),
156
+ getBookmark: () => d1.getBookmark?.() ?? null,
157
+ primary: () => d1.primary?.() ?? primaryD1,
158
+ replica: () => d1.replica?.() ?? primaryD1
100
159
  });
101
160
  if (isDefaultSchema) {
102
161
  drizzleCache.set(d1, instance);
@@ -104,8 +163,8 @@ Install it with: pnpm add mysql2`
104
163
  }
105
164
  return instance;
106
165
  }
107
- export function useDb(bindingName, eventOrOptions) {
108
- return useDrizzle(bindingName, eventOrOptions);
166
+ export function useDb(bindingNameOrOptions, eventOrOptions) {
167
+ return useDrizzle(bindingNameOrOptions, eventOrOptions);
109
168
  }
110
169
  export const db = new Proxy(
111
170
  {},
@@ -40,7 +40,15 @@ export function createInboundEmailContext(rawMessage, env, ctx) {
40
40
  }
41
41
  },
42
42
  async reply(options) {
43
- const subject = options.subject || (headers.get("subject") ? `Re: ${headers.get("subject")}` : "Re: Your message");
43
+ const origSubject = headers.get("subject");
44
+ let subject = options.subject;
45
+ if (!subject) {
46
+ if (origSubject) {
47
+ subject = /^re:\s*/i.test(origSubject) ? origSubject : `Re: ${origSubject}`;
48
+ } else {
49
+ subject = "Re: Your message";
50
+ }
51
+ }
44
52
  return sendEmail({
45
53
  ...options,
46
54
  to: options.to || from,
@@ -137,6 +137,13 @@ export async function createApiToken(event, input) {
137
137
  if (!user?.id) {
138
138
  throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
139
139
  }
140
+ if (session?.impersonator) {
141
+ throw createError({
142
+ statusCode: 403,
143
+ statusMessage: "Forbidden",
144
+ message: "Cannot create API tokens while impersonating another user"
145
+ });
146
+ }
140
147
  const name = input.name?.trim();
141
148
  if (!name) {
142
149
  throw createError({
@@ -145,6 +152,43 @@ export async function createApiToken(event, input) {
145
152
  message: "Token name is required"
146
153
  });
147
154
  }
155
+ if (input.expiresInDays !== void 0) {
156
+ if (typeof input.expiresInDays !== "number" || !Number.isFinite(input.expiresInDays) || input.expiresInDays <= 0 || input.expiresInDays > 365) {
157
+ throw createError({
158
+ statusCode: 400,
159
+ statusMessage: "Bad Request",
160
+ message: "expiresInDays must be a positive number between 1 and 365"
161
+ });
162
+ }
163
+ }
164
+ let scopes = ["*"];
165
+ if (input.scopes !== void 0) {
166
+ if (!Array.isArray(input.scopes)) {
167
+ throw createError({
168
+ statusCode: 400,
169
+ statusMessage: "Bad Request",
170
+ message: "scopes must be an array of string identifiers"
171
+ });
172
+ }
173
+ if (input.scopes.length > 50) {
174
+ throw createError({
175
+ statusCode: 400,
176
+ statusMessage: "Bad Request",
177
+ message: "Too many scopes requested (maximum 50)"
178
+ });
179
+ }
180
+ const SCOPE_REGEX = /^[a-zA-Z0-9_\-*:]+$/;
181
+ for (const s of input.scopes) {
182
+ if (typeof s !== "string" || !s.trim() || !SCOPE_REGEX.test(s.trim())) {
183
+ throw createError({
184
+ statusCode: 400,
185
+ statusMessage: "Bad Request",
186
+ message: `Invalid scope identifier: "${s}"`
187
+ });
188
+ }
189
+ }
190
+ scopes = input.scopes.map((s) => s.trim());
191
+ }
148
192
  const d1 = getD1(event);
149
193
  await ensureAuthTables(d1);
150
194
  const randomBytes = new Uint8Array(32);
@@ -152,7 +196,6 @@ export async function createApiToken(event, input) {
152
196
  const rawSecret = Array.from(randomBytes).map((b) => b.toString(16).padStart(2, "0")).join("");
153
197
  const rawToken = `${TOKEN_PREFIX}${rawSecret}`;
154
198
  const tokenHash = await hashSessionToken(rawToken);
155
- const scopes = input.scopes && input.scopes.length > 0 ? input.scopes : ["*"];
156
199
  const now = Date.now();
157
200
  const expiresAt = input.expiresInDays ? now + input.expiresInDays * 24 * 60 * 60 * 1e3 : null;
158
201
  const id = crypto.randomUUID();
@@ -168,6 +211,13 @@ export async function listApiTokens(event) {
168
211
  if (!user?.id) {
169
212
  throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
170
213
  }
214
+ if (session?.impersonator) {
215
+ throw createError({
216
+ statusCode: 403,
217
+ statusMessage: "Forbidden",
218
+ message: "Cannot access API tokens while impersonating another user"
219
+ });
220
+ }
171
221
  const d1 = getD1(event);
172
222
  await ensureAuthTables(d1);
173
223
  const results = await d1.prepare(`
@@ -191,6 +241,13 @@ export async function revokeApiToken(event, tokenId) {
191
241
  if (!user?.id) {
192
242
  throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
193
243
  }
244
+ if (session?.impersonator) {
245
+ throw createError({
246
+ statusCode: 403,
247
+ statusMessage: "Forbidden",
248
+ message: "Cannot revoke API tokens while impersonating another user"
249
+ });
250
+ }
194
251
  const d1 = getD1(event);
195
252
  await ensureAuthTables(d1);
196
253
  const existing = await d1.prepare(`SELECT user_id FROM ${apiTokenTbl(event)} WHERE id = ? LIMIT 1`).bind(tokenId).first();
@@ -67,5 +67,16 @@ export declare function releaseLock(key: string, token: string, event?: CFEvent)
67
67
  * ```
68
68
  */
69
69
  export declare function withLock<T>(key: string, optionsOrCallback: LockOptions | (() => Promise<T> | T), maybeCallback?: () => Promise<T> | T): Promise<T | null>;
70
+ /**
71
+ * Convenience helper to run a database migration callback with an exclusive distributed lock.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * await withMigrationLock("analytics", { ttl: "10m" }, async () => {
76
+ * await runDrizzleMigrations()
77
+ * })
78
+ * ```
79
+ */
80
+ export declare function withMigrationLock<T>(dbName: string, optionsOrCallback: LockOptions | (() => Promise<T> | T), maybeCallback?: () => Promise<T> | T): Promise<T | null>;
70
81
  /** Clears all in-memory locks (used during test teardown). */
71
82
  export declare function clearLockStore(): void;
@@ -134,6 +134,10 @@ export async function withLock(key, optionsOrCallback, maybeCallback) {
134
134
  await releaseLock(key, handle.token, options.event);
135
135
  }
136
136
  }
137
+ export async function withMigrationLock(dbName, optionsOrCallback, maybeCallback) {
138
+ const key = `migration:${dbName}`;
139
+ return withLock(key, optionsOrCallback, maybeCallback);
140
+ }
137
141
  export function clearLockStore() {
138
142
  memoryLocks.clear();
139
143
  }
@@ -59,16 +59,21 @@ export async function verifyUnsubscribeToken(token, secret) {
59
59
  while (base64.length % 4) base64 += "=";
60
60
  const decoded = atob(base64);
61
61
  const parts = decoded.split(":");
62
- if (parts.length < 3) return null;
63
- const email = parts[0];
62
+ if (parts.length !== 3) return null;
63
+ const rawEmail = parts[0];
64
64
  const timestamp = Number(parts[1]);
65
65
  const sigHex = parts[2];
66
- if (!email || !timestamp || !sigHex) return null;
66
+ if (!rawEmail || !timestamp || !sigHex || Number.isNaN(timestamp)) return null;
67
+ const cleanEmail = rawEmail.trim().toLowerCase();
68
+ if (!cleanEmail.includes("@") || cleanEmail.length < 3) return null;
69
+ if (sigHex.length !== 64 || !/^[0-9a-f]{64}$/i.test(sigHex)) {
70
+ return null;
71
+ }
67
72
  const maxAgeMs = 90 * 24 * 60 * 60 * 1e3;
68
73
  if (Date.now() - timestamp > maxAgeMs || timestamp > Date.now() + 6e4) {
69
74
  return null;
70
75
  }
71
- const payload = `${email}:${timestamp}`;
76
+ const payload = `${cleanEmail}:${timestamp}`;
72
77
  const keySecret = resolveUnsubscribeSecret(secret);
73
78
  const encoder = new TextEncoder();
74
79
  const cryptoKey = await crypto.subtle.importKey(
@@ -87,7 +92,7 @@ export async function verifyUnsubscribeToken(token, secret) {
87
92
  sigBytes,
88
93
  encoder.encode(payload)
89
94
  );
90
- return isValid ? email : null;
95
+ return isValid ? cleanEmail : null;
91
96
  } catch {
92
97
  return null;
93
98
  }
@@ -317,20 +322,50 @@ export async function listSuppressedEmails(event, options = {}) {
317
322
  }
318
323
  export async function recordSoftBounce(event, email, threshold = 3) {
319
324
  const cleanEmail = email.trim().toLowerCase();
325
+ let currentCount = 0;
326
+ const now = Date.now();
320
327
  const store = getDevSoftBounceStore();
321
- const existing = store.get(cleanEmail) || { count: 0, lastAt: 0 };
322
- existing.count += 1;
323
- existing.lastAt = Date.now();
324
- store.set(cleanEmail, existing);
325
- if (existing.count >= threshold) {
328
+ const devExisting = store.get(cleanEmail) || { count: 0, lastAt: 0 };
329
+ currentCount = devExisting.count;
330
+ try {
331
+ const kv = getKVBinding("KV", event);
332
+ if (kv && typeof kv.get === "function") {
333
+ const kvCached = await kv.get(`mail:soft_bounce:${cleanEmail}`, { type: "json" });
334
+ if (kvCached && typeof kvCached.count === "number") {
335
+ currentCount = Math.max(currentCount, kvCached.count);
336
+ }
337
+ }
338
+ } catch {
339
+ }
340
+ currentCount += 1;
341
+ store.set(cleanEmail, { count: currentCount, lastAt: now });
342
+ try {
343
+ const kv = getKVBinding("KV", event);
344
+ if (kv && typeof kv.put === "function") {
345
+ await kv.put(
346
+ `mail:soft_bounce:${cleanEmail}`,
347
+ JSON.stringify({ count: currentCount, lastAt: now }),
348
+ { expirationTtl: 7 * 86400 }
349
+ );
350
+ }
351
+ } catch {
352
+ }
353
+ if (currentCount >= threshold) {
326
354
  await suppressEmail(event, {
327
355
  email: cleanEmail,
328
356
  reason: "bounce",
329
357
  type: "soft_bounce",
330
358
  source: "soft_bounce_threshold",
331
- metadata: { consecutiveCount: existing.count }
359
+ metadata: { consecutiveCount: currentCount }
332
360
  });
333
- return { suppressed: true, count: existing.count };
361
+ try {
362
+ const kv = getKVBinding("KV", event);
363
+ if (kv && typeof kv.delete === "function") {
364
+ await kv.delete(`mail:soft_bounce:${cleanEmail}`);
365
+ }
366
+ } catch {
367
+ }
368
+ return { suppressed: true, count: currentCount };
334
369
  }
335
- return { suppressed: false, count: existing.count };
370
+ return { suppressed: false, count: currentCount };
336
371
  }
@@ -40,7 +40,8 @@ export declare function injectEmailTracking(html: string, options: {
40
40
  baseUrl: string;
41
41
  opens?: boolean;
42
42
  clicks?: boolean;
43
- }): string;
43
+ secret?: string;
44
+ }): Promise<string>;
44
45
  /**
45
46
  * Direct delivery executor using Cloudflare send_email binding or external providers. Used
46
47
  * internally for immediate sends, waitUntil backgrounds, and queue consumer workers.