nuxt-backend 0.2.0 → 0.2.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 (373) hide show
  1. package/dist/chunks/catalog.mjs +1 -1
  2. package/dist/chunks/doctor.mjs +71 -12
  3. package/dist/chunks/email-previews.mjs +1 -1
  4. package/dist/chunks/health.mjs +2 -2
  5. package/dist/chunks/index.mjs +3 -3
  6. package/dist/chunks/install.mjs +4 -4
  7. package/dist/chunks/run.mjs +1 -1
  8. package/dist/chunks/server.mjs +7 -5
  9. package/dist/cli.mjs +122 -23
  10. package/dist/convex/account-data.d.ts +0 -2
  11. package/dist/convex/account-data.d.ts.map +1 -1
  12. package/dist/convex/account-data.js +0 -4
  13. package/dist/convex/account-data.js.map +1 -1
  14. package/dist/convex/catalog.d.ts +22 -0
  15. package/dist/convex/catalog.d.ts.map +1 -1
  16. package/dist/convex/catalog.js.map +1 -1
  17. package/dist/convex/client/better-auth-options.d.ts.map +1 -1
  18. package/dist/convex/client/better-auth-options.js +11 -1
  19. package/dist/convex/client/better-auth-options.js.map +1 -1
  20. package/dist/convex/client/client-address.d.ts +21 -0
  21. package/dist/convex/client/client-address.d.ts.map +1 -0
  22. package/dist/convex/client/client-address.js +37 -0
  23. package/dist/convex/client/client-address.js.map +1 -0
  24. package/dist/convex/client/index.d.ts +34 -2
  25. package/dist/convex/client/index.d.ts.map +1 -1
  26. package/dist/convex/components/backend/_generated/component.d.ts +6 -0
  27. package/dist/convex/components/backend/_generated/component.d.ts.map +1 -1
  28. package/dist/convex/components/backend/account.d.ts +6 -6
  29. package/dist/convex/components/backend/account.d.ts.map +1 -1
  30. package/dist/convex/components/backend/account.js +6 -2
  31. package/dist/convex/components/backend/account.js.map +1 -1
  32. package/dist/convex/components/backend/adapter.d.ts.map +1 -1
  33. package/dist/convex/components/backend/adapter.js +4 -1
  34. package/dist/convex/components/backend/adapter.js.map +1 -1
  35. package/dist/convex/components/backend/ai.d.ts +11 -3
  36. package/dist/convex/components/backend/ai.d.ts.map +1 -1
  37. package/dist/convex/components/backend/ai.js +18 -52
  38. package/dist/convex/components/backend/ai.js.map +1 -1
  39. package/dist/convex/components/backend/billing.d.ts.map +1 -1
  40. package/dist/convex/components/backend/billing.js +12 -32
  41. package/dist/convex/components/backend/billing.js.map +1 -1
  42. package/dist/convex/components/backend/consents.d.ts.map +1 -1
  43. package/dist/convex/components/backend/consents.js +2 -1
  44. package/dist/convex/components/backend/consents.js.map +1 -1
  45. package/dist/convex/components/backend/gifts.d.ts +1 -1
  46. package/dist/convex/components/backend/gifts.d.ts.map +1 -1
  47. package/dist/convex/components/backend/gifts.js +9 -4
  48. package/dist/convex/components/backend/gifts.js.map +1 -1
  49. package/dist/convex/components/backend/lifecycle.d.ts.map +1 -1
  50. package/dist/convex/components/backend/lifecycle.js +18 -14
  51. package/dist/convex/components/backend/lifecycle.js.map +1 -1
  52. package/dist/convex/components/backend/notifications.d.ts +13 -0
  53. package/dist/convex/components/backend/notifications.d.ts.map +1 -1
  54. package/dist/convex/components/backend/notifications.js +21 -0
  55. package/dist/convex/components/backend/notifications.js.map +1 -1
  56. package/dist/convex/components/backend/referrals.d.ts.map +1 -1
  57. package/dist/convex/components/backend/referrals.js +13 -16
  58. package/dist/convex/components/backend/referrals.js.map +1 -1
  59. package/dist/convex/components/backend/reports.js +7 -7
  60. package/dist/convex/components/backend/reports.js.map +1 -1
  61. package/dist/convex/components/backend/schema.d.ts +151 -35
  62. package/dist/convex/components/backend/schema.d.ts.map +1 -1
  63. package/dist/convex/components/backend/schema.js +127 -153
  64. package/dist/convex/components/backend/schema.js.map +1 -1
  65. package/dist/convex/components/backend/storage.d.ts.map +1 -1
  66. package/dist/convex/components/backend/storage.js +10 -10
  67. package/dist/convex/components/backend/storage.js.map +1 -1
  68. package/dist/convex/components/backend/subscriptions.d.ts +3 -3
  69. package/dist/convex/components/backend/subscriptions.d.ts.map +1 -1
  70. package/dist/convex/components/backend/subscriptions.js +6 -35
  71. package/dist/convex/components/backend/subscriptions.js.map +1 -1
  72. package/dist/convex/components/backend/waitlist.d.ts +1 -1
  73. package/dist/convex/components/backend/webhooks.d.ts +0 -1
  74. package/dist/convex/components/backend/webhooks.d.ts.map +1 -1
  75. package/dist/convex/components/backend/webhooks.js +1 -1
  76. package/dist/convex/components/backend/webhooks.js.map +1 -1
  77. package/dist/convex/consent-rules.d.ts +0 -2
  78. package/dist/convex/consent-rules.d.ts.map +1 -1
  79. package/dist/convex/consent-rules.js.map +1 -1
  80. package/dist/convex/constants.d.ts +0 -1
  81. package/dist/convex/constants.d.ts.map +1 -1
  82. package/dist/convex/constants.js +0 -1
  83. package/dist/convex/constants.js.map +1 -1
  84. package/dist/convex/email-templates.d.ts +0 -1
  85. package/dist/convex/email-templates.d.ts.map +1 -1
  86. package/dist/convex/email-templates.js +0 -1
  87. package/dist/convex/email-templates.js.map +1 -1
  88. package/dist/convex/integrations/admin.d.ts +2 -1
  89. package/dist/convex/integrations/admin.d.ts.map +1 -1
  90. package/dist/convex/integrations/admin.js.map +1 -1
  91. package/dist/convex/integrations/ai/job-errors.d.ts +7 -0
  92. package/dist/convex/integrations/ai/job-errors.d.ts.map +1 -1
  93. package/dist/convex/integrations/ai/job-errors.js +22 -0
  94. package/dist/convex/integrations/ai/job-errors.js.map +1 -1
  95. package/dist/convex/integrations/ai/metering.d.ts +12 -0
  96. package/dist/convex/integrations/ai/metering.d.ts.map +1 -1
  97. package/dist/convex/integrations/ai/metering.js +19 -10
  98. package/dist/convex/integrations/ai/metering.js.map +1 -1
  99. package/dist/convex/integrations/ai/models.d.ts.map +1 -1
  100. package/dist/convex/integrations/ai/models.js +3 -1
  101. package/dist/convex/integrations/ai/models.js.map +1 -1
  102. package/dist/convex/integrations/ai/moderation.d.ts +2 -0
  103. package/dist/convex/integrations/ai/moderation.d.ts.map +1 -1
  104. package/dist/convex/integrations/ai/moderation.js +29 -2
  105. package/dist/convex/integrations/ai/moderation.js.map +1 -1
  106. package/dist/convex/integrations/ai/stream.d.ts +1 -1
  107. package/dist/convex/integrations/ai/stream.d.ts.map +1 -1
  108. package/dist/convex/integrations/ai/stream.js +3 -11
  109. package/dist/convex/integrations/ai/stream.js.map +1 -1
  110. package/dist/convex/integrations/billing/context.d.ts +0 -1
  111. package/dist/convex/integrations/billing/context.d.ts.map +1 -1
  112. package/dist/convex/integrations/billing/context.js +1 -4
  113. package/dist/convex/integrations/billing/context.js.map +1 -1
  114. package/dist/convex/integrations/billing/credits.d.ts.map +1 -1
  115. package/dist/convex/integrations/billing/customers.d.ts.map +1 -1
  116. package/dist/convex/integrations/billing/customers.js +25 -5
  117. package/dist/convex/integrations/billing/customers.js.map +1 -1
  118. package/dist/convex/integrations/billing/features.d.ts.map +1 -1
  119. package/dist/convex/integrations/billing/free-plan.d.ts +1 -1
  120. package/dist/convex/integrations/billing/free-plan.d.ts.map +1 -1
  121. package/dist/convex/integrations/billing/free-plan.js +18 -4
  122. package/dist/convex/integrations/billing/free-plan.js.map +1 -1
  123. package/dist/convex/integrations/billing/functions.d.ts +5 -1
  124. package/dist/convex/integrations/billing/functions.d.ts.map +1 -1
  125. package/dist/convex/integrations/billing/functions.js +16 -5
  126. package/dist/convex/integrations/billing/functions.js.map +1 -1
  127. package/dist/convex/integrations/billing/gifts.d.ts.map +1 -1
  128. package/dist/convex/integrations/billing/gifts.js +2 -2
  129. package/dist/convex/integrations/billing/gifts.js.map +1 -1
  130. package/dist/convex/integrations/billing/history.d.ts.map +1 -1
  131. package/dist/convex/integrations/billing/history.js +3 -1
  132. package/dist/convex/integrations/billing/history.js.map +1 -1
  133. package/dist/convex/integrations/billing/lifecycle.d.ts +4 -1
  134. package/dist/convex/integrations/billing/lifecycle.d.ts.map +1 -1
  135. package/dist/convex/integrations/billing/lifecycle.js +33 -2
  136. package/dist/convex/integrations/billing/lifecycle.js.map +1 -1
  137. package/dist/convex/integrations/billing/passes.d.ts +0 -2
  138. package/dist/convex/integrations/billing/passes.d.ts.map +1 -1
  139. package/dist/convex/integrations/billing/passes.js +2 -3
  140. package/dist/convex/integrations/billing/passes.js.map +1 -1
  141. package/dist/convex/integrations/billing/pricing.d.ts +4 -1
  142. package/dist/convex/integrations/billing/pricing.d.ts.map +1 -1
  143. package/dist/convex/integrations/billing/pricing.js +11 -9
  144. package/dist/convex/integrations/billing/pricing.js.map +1 -1
  145. package/dist/convex/integrations/billing/purchase.d.ts.map +1 -1
  146. package/dist/convex/integrations/billing/purchase.js +1 -2
  147. package/dist/convex/integrations/billing/purchase.js.map +1 -1
  148. package/dist/convex/integrations/billing/quotas.d.ts.map +1 -1
  149. package/dist/convex/integrations/billing/subscriptions.d.ts.map +1 -1
  150. package/dist/convex/integrations/billing/types/lifecycle.d.ts +12 -0
  151. package/dist/convex/integrations/billing/types/lifecycle.d.ts.map +1 -1
  152. package/dist/convex/integrations/billing/types/options.d.ts +4 -1
  153. package/dist/convex/integrations/billing/types/options.d.ts.map +1 -1
  154. package/dist/convex/integrations/billing/types/records.d.ts +7 -1
  155. package/dist/convex/integrations/billing/types/records.d.ts.map +1 -1
  156. package/dist/convex/integrations/billing/types/surface.d.ts +5 -1
  157. package/dist/convex/integrations/billing/types/surface.d.ts.map +1 -1
  158. package/dist/convex/integrations/billing.d.ts +2 -2
  159. package/dist/convex/integrations/billing.d.ts.map +1 -1
  160. package/dist/convex/integrations/billing.js +1 -0
  161. package/dist/convex/integrations/billing.js.map +1 -1
  162. package/dist/convex/integrations/email-preferences.d.ts +1 -1
  163. package/dist/convex/integrations/email-preferences.d.ts.map +1 -1
  164. package/dist/convex/integrations/email-sync.d.ts.map +1 -1
  165. package/dist/convex/integrations/email-sync.js +43 -1
  166. package/dist/convex/integrations/email-sync.js.map +1 -1
  167. package/dist/convex/integrations/notifications.d.ts +24 -4
  168. package/dist/convex/integrations/notifications.d.ts.map +1 -1
  169. package/dist/convex/integrations/notifications.js +30 -14
  170. package/dist/convex/integrations/notifications.js.map +1 -1
  171. package/dist/convex/integrations/rate-limit.d.ts +6 -5
  172. package/dist/convex/integrations/rate-limit.d.ts.map +1 -1
  173. package/dist/convex/integrations/rate-limit.js +6 -5
  174. package/dist/convex/integrations/rate-limit.js.map +1 -1
  175. package/dist/convex/integrations/reports.d.ts +1 -1
  176. package/dist/convex/integrations/reports.d.ts.map +1 -1
  177. package/dist/convex/integrations/reports.js +0 -11
  178. package/dist/convex/integrations/reports.js.map +1 -1
  179. package/dist/convex/integrations/webhooks.d.ts +1 -3
  180. package/dist/convex/integrations/webhooks.d.ts.map +1 -1
  181. package/dist/convex/integrations/webhooks.js.map +1 -1
  182. package/dist/convex/label-groups/cancelFlow.d.ts +3 -0
  183. package/dist/convex/label-groups/cancelFlow.d.ts.map +1 -1
  184. package/dist/convex/label-groups/cancelFlow.js +5 -0
  185. package/dist/convex/label-groups/cancelFlow.js.map +1 -1
  186. package/dist/convex/label-groups/credits.d.ts +14 -1
  187. package/dist/convex/label-groups/credits.d.ts.map +1 -1
  188. package/dist/convex/label-groups/credits.js +17 -2
  189. package/dist/convex/label-groups/credits.js.map +1 -1
  190. package/dist/convex/label-groups/notifications.d.ts +19 -2
  191. package/dist/convex/label-groups/notifications.d.ts.map +1 -1
  192. package/dist/convex/label-groups/notifications.js +19 -15
  193. package/dist/convex/label-groups/notifications.js.map +1 -1
  194. package/dist/convex/label-groups/pricing.js +8 -8
  195. package/dist/convex/label-groups/pricing.js.map +1 -1
  196. package/dist/convex/label-groups/settings.d.ts.map +1 -1
  197. package/dist/convex/label-groups/settings.js +4 -3
  198. package/dist/convex/label-groups/settings.js.map +1 -1
  199. package/dist/convex/label-groups/usage.d.ts +1 -1
  200. package/dist/convex/label-groups/usage.d.ts.map +1 -1
  201. package/dist/convex/label-groups/usage.js +2 -2
  202. package/dist/convex/label-groups/usage.js.map +1 -1
  203. package/dist/convex/label-translations.d.ts.map +1 -1
  204. package/dist/convex/label-translations.js +52 -0
  205. package/dist/convex/label-translations.js.map +1 -1
  206. package/dist/convex/labels.d.ts +23 -0
  207. package/dist/convex/labels.d.ts.map +1 -1
  208. package/dist/convex/log.js +2 -0
  209. package/dist/convex/log.js.map +1 -1
  210. package/dist/convex/notifications.d.ts +77 -0
  211. package/dist/convex/notifications.d.ts.map +1 -1
  212. package/dist/convex/notifications.js +64 -13
  213. package/dist/convex/notifications.js.map +1 -1
  214. package/dist/convex/proof.d.ts +25 -0
  215. package/dist/convex/proof.d.ts.map +1 -1
  216. package/dist/convex/proof.js +39 -0
  217. package/dist/convex/proof.js.map +1 -1
  218. package/dist/convex/referral-rules.d.ts +0 -2
  219. package/dist/convex/referral-rules.d.ts.map +1 -1
  220. package/dist/convex/referral-rules.js +0 -2
  221. package/dist/convex/referral-rules.js.map +1 -1
  222. package/dist/convex/waitlist-rules.d.ts +1 -13
  223. package/dist/convex/waitlist-rules.d.ts.map +1 -1
  224. package/dist/convex/waitlist-rules.js +2 -14
  225. package/dist/convex/waitlist-rules.js.map +1 -1
  226. package/dist/devtools-client/index.html +1 -1
  227. package/dist/module.js +2 -2
  228. package/dist/module.json +1 -1
  229. package/dist/runtime/locales/de.json +47 -24
  230. package/dist/runtime/locales/en.json +47 -24
  231. package/dist/runtime/locales/es.json +47 -24
  232. package/dist/runtime/locales/fr.json +47 -24
  233. package/dist/runtime/locales/ru.json +47 -24
  234. package/dist/runtime/server/protection/gate.d.ts +4 -2
  235. package/dist/runtime/server/protection/gate.js +14 -4
  236. package/dist/runtime/vue/admin-client.d.ts +18 -0
  237. package/dist/runtime/vue/admin-client.js +32 -0
  238. package/dist/runtime/vue/auth-client.d.ts +16 -11
  239. package/dist/runtime/vue/auth-client.js +3 -1
  240. package/dist/runtime/vue/components/admin/AdminUsers.d.vue.ts +1 -1
  241. package/dist/runtime/vue/components/admin/AdminUsers.vue.d.ts +1 -1
  242. package/dist/runtime/vue/components/billing/BillingCheckoutLink.d.vue.ts +1 -1
  243. package/dist/runtime/vue/components/billing/BillingCheckoutLink.vue.d.ts +1 -1
  244. package/dist/runtime/vue/components/billing/CancelFlow.css +1 -1
  245. package/dist/runtime/vue/components/billing/CancelFlow.d.vue.ts +3 -0
  246. package/dist/runtime/vue/components/billing/CancelFlow.vue +10 -3
  247. package/dist/runtime/vue/components/billing/CancelFlow.vue.d.ts +3 -0
  248. package/dist/runtime/vue/components/billing/CancelFlowConfirm.d.vue.ts +3 -0
  249. package/dist/runtime/vue/components/billing/CancelFlowConfirm.vue +34 -0
  250. package/dist/runtime/vue/components/billing/CancelFlowConfirm.vue.d.ts +3 -0
  251. package/dist/runtime/vue/components/billing/CancelFlowQuestion.vue +2 -1
  252. package/dist/runtime/vue/components/billing/GiftSent.d.vue.ts +2 -2
  253. package/dist/runtime/vue/components/billing/GiftSent.vue.d.ts +2 -2
  254. package/dist/runtime/vue/components/billing/PricingPackCard.vue +6 -3
  255. package/dist/runtime/vue/components/billing/PricingPlanCard.vue +3 -1
  256. package/dist/runtime/vue/components/billing/PricingTable.d.vue.ts +2 -2
  257. package/dist/runtime/vue/components/billing/PricingTable.vue +3 -1
  258. package/dist/runtime/vue/components/billing/PricingTable.vue.d.ts +2 -2
  259. package/dist/runtime/vue/components/billing/UsageHistoryEvent.vue +3 -1
  260. package/dist/runtime/vue/components/billing/cancel-flow.d.ts +28 -7
  261. package/dist/runtime/vue/components/billing/cancel-flow.js +25 -2
  262. package/dist/runtime/vue/components/shell/NoticeLowCredits.vue +3 -1
  263. package/dist/runtime/vue/components/tokens.css +1 -1
  264. package/dist/runtime/vue/components/workspaces/WorkspaceCredits.vue +6 -3
  265. package/dist/runtime/vue/components/workspaces/WorkspaceSettings.d.vue.ts +2 -2
  266. package/dist/runtime/vue/components/workspaces/WorkspaceSettings.vue.d.ts +2 -2
  267. package/dist/runtime/vue/composables/use-auth.d.ts +13 -1
  268. package/dist/runtime/vue/composables/use-auth.js +4 -1
  269. package/dist/runtime/vue/composables/use-billing.d.ts +10 -2
  270. package/dist/runtime/vue/composables/use-credits.d.ts +3 -0
  271. package/dist/runtime/vue/composables/use-credits.js +1 -0
  272. package/dist/runtime/vue/composables/use-notifications.d.ts +5 -1
  273. package/dist/runtime/vue/composables/use-notifications.js +12 -4
  274. package/dist/runtime/vue/composables/use-webhook-log.d.ts +4 -2
  275. package/dist/runtime/vue/organization-client.d.ts +15 -0
  276. package/dist/runtime/vue/organization-client.js +65 -0
  277. package/dist/runtime/vue/parts.d.ts +2 -1
  278. package/dist/runtime/vue/plugins/checkout-return.d.ts +3 -2
  279. package/dist/runtime/vue/plugins/checkout-return.js +2 -4
  280. package/dist/runtime/vue/plugins/first-touch.js +2 -4
  281. package/dist/runtime/vue/utils/checkout-return.d.ts +9 -2
  282. package/dist/runtime/vue/utils/checkout-return.js +2 -1
  283. package/dist/runtime/vue/utils/every-page.d.ts +10 -0
  284. package/dist/runtime/vue/utils/every-page.js +6 -0
  285. package/dist/runtime/vue/utils/meter-unit.d.ts +14 -0
  286. package/dist/runtime/vue/utils/meter-unit.js +18 -0
  287. package/dist/shared/{nuxt-backend.2YoiKo8j.mjs → nuxt-backend.2m535CLS.mjs} +6 -2
  288. package/dist/shared/{nuxt-backend.CPq101Wi.mjs → nuxt-backend.DXEf0rrv.mjs} +1 -1
  289. package/dist/shared/{nuxt-backend.-uB5CGw-.mjs → nuxt-backend.Dm1NkY7v.mjs} +1 -1
  290. package/dist/shared/{nuxt-backend.OQMX-0U7.mjs → nuxt-backend.KEzfHO2K.mjs} +6 -3
  291. package/dist/shared/{nuxt-backend.S5C2b-4I.mjs → nuxt-backend.ikObmtHs.mjs} +2 -2
  292. package/package.json +2 -2
  293. package/skills/nuxt-backend/references/api.md +13 -3
  294. package/skills/nuxt-backend/references/surface.json +12 -0
  295. package/skills/nuxt-backend-auth/SKILL.md +2 -1
  296. package/skills/nuxt-backend-billing/SKILL.md +7 -0
  297. package/skills/nuxt-backend-billing/references/api.md +12 -2
  298. package/skills/nuxt-backend-data/SKILL.md +4 -1
  299. package/skills/nuxt-backend-email/SKILL.md +4 -0
  300. package/skills/nuxt-backend-email/references/api.md +1 -1
  301. package/skills/nuxt-backend-ui/SKILL.md +6 -5
  302. package/src/convex/account-data.ts +0 -5
  303. package/src/convex/catalog.ts +23 -0
  304. package/src/convex/client/better-auth-options.ts +11 -1
  305. package/src/convex/client/client-address.ts +37 -0
  306. package/src/convex/components/backend/_generated/component.ts +12 -0
  307. package/src/convex/components/backend/account.ts +7 -2
  308. package/src/convex/components/backend/adapter.ts +4 -1
  309. package/src/convex/components/backend/ai.ts +20 -54
  310. package/src/convex/components/backend/billing.ts +14 -33
  311. package/src/convex/components/backend/consents.ts +2 -1
  312. package/src/convex/components/backend/gifts.ts +11 -5
  313. package/src/convex/components/backend/lifecycle.ts +17 -12
  314. package/src/convex/components/backend/notifications.ts +22 -0
  315. package/src/convex/components/backend/referrals.ts +14 -16
  316. package/src/convex/components/backend/reports.ts +7 -7
  317. package/src/convex/components/backend/schema.ts +143 -161
  318. package/src/convex/components/backend/storage.ts +11 -10
  319. package/src/convex/components/backend/subscriptions.ts +7 -35
  320. package/src/convex/components/backend/webhooks.ts +1 -10
  321. package/src/convex/consent-rules.ts +0 -3
  322. package/src/convex/constants.ts +0 -1
  323. package/src/convex/email-templates.ts +0 -1
  324. package/src/convex/integrations/admin.ts +2 -1
  325. package/src/convex/integrations/ai/job-errors.ts +21 -0
  326. package/src/convex/integrations/ai/metering.ts +24 -10
  327. package/src/convex/integrations/ai/models.ts +3 -1
  328. package/src/convex/integrations/ai/moderation.ts +31 -2
  329. package/src/convex/integrations/ai/stream.ts +3 -11
  330. package/src/convex/integrations/billing/context.ts +1 -9
  331. package/src/convex/integrations/billing/customers.ts +28 -5
  332. package/src/convex/integrations/billing/free-plan.ts +20 -5
  333. package/src/convex/integrations/billing/functions.ts +17 -5
  334. package/src/convex/integrations/billing/gifts.ts +2 -2
  335. package/src/convex/integrations/billing/history.ts +2 -1
  336. package/src/convex/integrations/billing/lifecycle.ts +30 -3
  337. package/src/convex/integrations/billing/passes.ts +2 -4
  338. package/src/convex/integrations/billing/pricing.ts +14 -10
  339. package/src/convex/integrations/billing/purchase.ts +1 -2
  340. package/src/convex/integrations/billing/types/lifecycle.ts +13 -0
  341. package/src/convex/integrations/billing/types/options.ts +4 -1
  342. package/src/convex/integrations/billing/types/records.ts +7 -1
  343. package/src/convex/integrations/billing/types/surface.ts +3 -1
  344. package/src/convex/integrations/billing.ts +3 -2
  345. package/src/convex/integrations/email-preferences.ts +1 -1
  346. package/src/convex/integrations/email-sync.ts +44 -1
  347. package/src/convex/integrations/notifications.ts +65 -16
  348. package/src/convex/integrations/rate-limit.ts +6 -5
  349. package/src/convex/integrations/reports.ts +1 -1
  350. package/src/convex/integrations/webhooks.ts +1 -4
  351. package/src/convex/label-groups/cancelFlow.ts +5 -0
  352. package/src/convex/label-groups/credits.ts +17 -2
  353. package/src/convex/label-groups/notifications.ts +19 -15
  354. package/src/convex/label-groups/pricing.ts +8 -8
  355. package/src/convex/label-groups/settings.ts +4 -3
  356. package/src/convex/label-groups/usage.ts +2 -2
  357. package/src/convex/label-translations.ts +52 -0
  358. package/src/convex/log.ts +2 -0
  359. package/src/convex/notifications.ts +99 -13
  360. package/src/convex/proof.ts +43 -0
  361. package/src/convex/referral-rules.ts +0 -2
  362. package/src/convex/waitlist-rules.ts +2 -22
  363. package/src/runtime/vue/components/billing/CancelFlow.css +16 -0
  364. package/src/runtime/vue/components/billing/CancelFlow.vue +16 -6
  365. package/src/runtime/vue/components/billing/CancelFlowConfirm.vue +35 -0
  366. package/src/runtime/vue/components/billing/CancelFlowQuestion.vue +8 -2
  367. package/src/runtime/vue/components/billing/PricingPackCard.vue +6 -3
  368. package/src/runtime/vue/components/billing/PricingPlanCard.vue +3 -1
  369. package/src/runtime/vue/components/billing/PricingTable.vue +3 -1
  370. package/src/runtime/vue/components/billing/UsageHistoryEvent.vue +3 -1
  371. package/src/runtime/vue/components/shell/NoticeLowCredits.vue +3 -1
  372. package/src/runtime/vue/components/tokens.css +19 -15
  373. package/src/runtime/vue/components/workspaces/WorkspaceCredits.vue +6 -3
@@ -3,14 +3,15 @@ import type { Auth, FunctionReference } from 'convex/server'
3
3
  import { resolveBackendPaths } from '../../paths.js'
4
4
  import { backendError } from '../../errors.js'
5
5
  import { logBackend } from '../../log.js'
6
- import { BILLING_ACCESS, type BillingContext, readEnv } from './context.js'
6
+ import { BILLING_ACCESS, type BillingContext } from './context.js'
7
+ import { readEnv } from '../../delivery.js'
7
8
  import type { CatalogDiscounts } from './discounts.js'
8
9
  import type { BillingFreePlan } from './free-plan.js'
9
10
  import { addMonths, type BillingPasses } from './passes.js'
10
11
  import { EMAIL_OPT_OUT_METADATA } from './purchase.js'
11
12
  import { type BillingSubscriptions, CANCELLATION_COMMENT_MAX, epochOf, type SyncedSubscription } from './subscriptions.js'
12
13
  import type { CancellationReason, ProviderCtx, RunQueryCtx, RunWriteCtx } from './types/base.js'
13
- import type { BillingLifecycle, CancelOutcome, BillingConsole, SaveOffer, SaveOfferRule, WithdrawalPeriod } from './types/lifecycle.js'
14
+ import type { BillingLifecycle, CancelFlowState, CancelOutcome, BillingConsole, SaveOffer, SaveOfferRule, WithdrawalPeriod } from './types/lifecycle.js'
14
15
  import type { CancelSubscriptionOptions, SubscriptionTarget } from './types/options.js'
15
16
 
16
17
  // The billing lifecycle (LIFECYCLE): what the package does around a
@@ -194,6 +195,32 @@ export function createLifecycle(
194
195
  return await ctx.runQuery(records.lastOffer, { entityId, since: Date.now() - SAVE_OFFER_WINDOW_MS }) !== null
195
196
  }
196
197
 
198
+ /**
199
+ * What the cancel flow reads before it asks, for a billing manager: the
200
+ * reasons whose offer `cancel` would make now, by the same rules
201
+ * (`offerBarred`, `termsOf`). None without a running paid subscription to
202
+ * cancel. `null` for anyone who may not manage the billing.
203
+ */
204
+ const getCancelFlow = async (ctx: RunQueryCtx & { auth?: Auth }, options: SubscriptionTarget = {}): Promise<CancelFlowState | null> => {
205
+ const entity = await allowedEntity(ctx, BILLING_ACCESS.change)
206
+ if (!entity) return null
207
+ const none: CancelFlowState = { offers: false, reasons: [] }
208
+ const rules = Object.entries(lifecycle.saveOffers ?? {}).filter((entry): entry is [CancellationReason, SaveOfferRule] => Boolean(entry[1]))
209
+ if (rules.length === 0) return none
210
+ let subscription: SyncedSubscription
211
+ try {
212
+ subscription = await subscriptions.resolveSubscription(ctx, entity.userId, options.subscriptionId)
213
+ }
214
+ catch {
215
+ // None running, or several and none named: the cancellation itself refuses.
216
+ return none
217
+ }
218
+ if (await freePlan.isFreeProduct(ctx, subscription.productId) || await offerBarred(ctx, entity.userId, subscription)) return none
219
+ const reasons: CancellationReason[] = []
220
+ for (const [reason, rule] of rules) if (await termsOf(ctx, subscription, rule)) reasons.push(reason)
221
+ return { offers: reasons.length > 0, reasons }
222
+ }
223
+
197
224
  /**
198
225
  * Cancel, or answer with the save offer for the reason first. Cancelling
199
226
  * takes one step: an offer comes only where `saveOffers` names one for the
@@ -503,7 +530,7 @@ export function createLifecycle(
503
530
  await join(ctx, { email: user.email, userId: openedBy, objected: false, checkoutId: order.checkoutId })
504
531
  }
505
532
 
506
- return { cancel, acceptOffer, getWithdrawal, withdraw, recordConsent, confirmConsent, remindRenewal, abandonCheckout, startReverseTrial, consoleOf, softOptIn }
533
+ return { cancel, getCancelFlow, acceptOffer, getWithdrawal, withdraw, recordConsent, confirmConsent, remindRenewal, abandonCheckout, startReverseTrial, consoleOf, softOptIn }
507
534
  }
508
535
 
509
536
  /** The billing lifecycle of one `setupBilling` call. */
@@ -8,7 +8,8 @@ import { resolveBackendPaths } from '../../paths.js'
8
8
  import { backendError } from '../../errors.js'
9
9
  import { logBackend } from '../../log.js'
10
10
  import { hasAnyRole } from '../access.js'
11
- import { type BillingContext, isProviderNotFound, readEnv } from './context.js'
11
+ import { type BillingContext, isProviderNotFound } from './context.js'
12
+ import { readEnv } from '../../delivery.js'
12
13
  import type { BillingCustomers } from './customers.js'
13
14
  import type { BillingFreePlan } from './free-plan.js'
14
15
  import type { GiftRecord } from './types/records.js'
@@ -39,9 +40,6 @@ export function addMonths(from: number, months: number): number {
39
40
  return date.getTime()
40
41
  }
41
42
 
42
- /** The last cycle of a pass is at least this long: from here to the end, the pass is in it. */
43
- export const LAST_CYCLE_MS = 28 * DAY_MS
44
-
45
43
  /** How long a plan pass's claim holds its gift: the provider calls of one claim, with room to spare. */
46
44
  const CLAIM_HOLD_MS = 5 * 60 * 1000
47
45
 
@@ -1,6 +1,6 @@
1
1
  import { queryGeneric } from 'convex/server'
2
2
  import { v } from 'convex/values'
3
- import { type CatalogInterval, featureKeyOf, grantedQuotas, planQuotasKey, quotaLimit } from '../../catalog.js'
3
+ import { type CatalogInterval, featureKeyOf, grantedQuotas, type MeterUnit, planQuotasKey, quotaLimit } from '../../catalog.js'
4
4
  import type { BillingContext } from './context.js'
5
5
  import { type CatalogDiscounts, type KeyedDiscount, offerOf, promotionOf } from './discounts.js'
6
6
  import type { ProviderCtx, RunQueryCtx } from './types/base.js'
@@ -36,6 +36,8 @@ export interface PricingSources {
36
36
  hidden: Set<string>
37
37
  /** Meter id → the catalog's name for it. */
38
38
  meterNames: Map<string, string>
39
+ /** The catalog's meter name → the unit it names for the meter. */
40
+ meterUnits?: ReadonlyMap<string, MeterUnit>
39
41
  /**
40
42
  * Benefit id → its live metadata, where the entitlement cache holds a
41
43
  * snapshot (the `benefit.updated` webhook patches it): what a feature
@@ -85,13 +87,14 @@ function priceOf(row: ProductRow, currencies: readonly string[] = []): { amount:
85
87
  }
86
88
 
87
89
  /** The credits of the product's one meter-credit benefit; none with zero or several. */
88
- function creditsOf(row: ProductRow, meterNames: Map<string, string>): PricedCredits | undefined {
90
+ function creditsOf(row: ProductRow, { meterNames, meterUnits }: Pick<PricingSources, 'meterNames' | 'meterUnits'>): PricedCredits | undefined {
89
91
  const grants = (row.benefits ?? []).filter(benefit => benefit.type === 'meter_credit')
90
92
  if (grants.length !== 1) return undefined
91
93
  const { units, rollover, meterId } = (grants[0]!.properties ?? {}) as { units?: unknown, rollover?: unknown, meterId?: unknown }
92
94
  if (typeof units !== 'number') return undefined
93
95
  const meter = typeof meterId === 'string' ? meterNames.get(meterId) : undefined
94
- return { ...(meter === undefined ? {} : { meter }), units, rollover: rollover === true }
96
+ const unit = meter === undefined ? undefined : meterUnits?.get(meter)
97
+ return { ...(meter === undefined ? {} : { meter }), ...(unit ? { unit } : {}), units, rollover: rollover === true }
95
98
  }
96
99
 
97
100
  function trialOf(row: ProductRow): PricedTrial | undefined {
@@ -140,10 +143,10 @@ function promotionOn(row: ProductRow, price: { amount: number, currency: string
140
143
  }
141
144
 
142
145
  /** One price of a plan, from its product at `interval`; marked `archived` when that product sells to nobody new. */
143
- function planPrice(row: ProductRow, interval: CatalogInterval, { meterNames, currencies, promotion }: Pick<PricingSources, 'meterNames' | 'currencies' | 'promotion'>, archived: boolean): PricedPlanPrice | undefined {
146
+ function planPrice(row: ProductRow, interval: CatalogInterval, { meterNames, meterUnits, currencies, promotion }: Pick<PricingSources, 'meterNames' | 'meterUnits' | 'currencies' | 'promotion'>, archived: boolean): PricedPlanPrice | undefined {
144
147
  const price = priceOf(row, currencies)
145
148
  if (!price) return undefined
146
- const credits = creditsOf(row, meterNames)
149
+ const credits = creditsOf(row, { meterNames, meterUnits })
147
150
  const trial = trialOf(row)
148
151
  return {
149
152
  productId: row.id,
@@ -191,10 +194,10 @@ function comparePacks(packs: PricedPack[]): void {
191
194
  }
192
195
 
193
196
  /** A pack on sale, from its product row: none for an archived one or one without a price to show. */
194
- function packOf(productKey: string, row: ProductRow, { meterNames, currencies, promotion }: Pick<PricingSources, 'meterNames' | 'currencies' | 'promotion'>): PricedPack | undefined {
197
+ function packOf(productKey: string, row: ProductRow, { meterNames, meterUnits, currencies, promotion }: Pick<PricingSources, 'meterNames' | 'meterUnits' | 'currencies' | 'promotion'>): PricedPack | undefined {
195
198
  const price = priceOf(row, currencies)
196
199
  if (row.isArchived || !price) return undefined
197
- const credits = creditsOf(row, meterNames)
200
+ const credits = creditsOf(row, { meterNames, meterUnits })
198
201
  return { key: productKey, productId: row.id, name: row.name, description: row.description ?? null, ...price, ...(credits ? { credits } : {}), isBestValue: false, ...promotionOn(row, price, promotion, false) }
199
202
  }
200
203
 
@@ -215,11 +218,11 @@ type QuotaGrant = { metadata: Readonly<Record<string, unknown>> | undefined }
215
218
  * (in the dashboard, or as a retired plan's) stays listed, marked, for the
216
219
  * people on it; a plan none of whose prices sells is retired.
217
220
  */
218
- function addPlanProduct(plans: Map<string, PlanDraft>, productKey: string, row: ProductRow, { retired, meterNames, benefitMetadata, currencies, free, promotion }: Pick<PricingSources, 'retired' | 'meterNames' | 'benefitMetadata' | 'currencies' | 'free' | 'promotion'>): void {
221
+ function addPlanProduct(plans: Map<string, PlanDraft>, productKey: string, row: ProductRow, { retired, meterNames, meterUnits, benefitMetadata, currencies, free, promotion }: Pick<PricingSources, 'retired' | 'meterNames' | 'meterUnits' | 'benefitMetadata' | 'currencies' | 'free' | 'promotion'>): void {
219
222
  const interval = row.recurringInterval
220
223
  if (interval !== 'month' && interval !== 'year') return
221
224
  const archived = row.isArchived || retired.has(row.id)
222
- const price = planPrice(row, interval, { meterNames, currencies, promotion }, archived)
225
+ const price = planPrice(row, interval, { meterNames, meterUnits, currencies, promotion }, archived)
223
226
  if (!price) return
224
227
  const key = productKey.endsWith(`:${interval}`) ? productKey.slice(0, -interval.length - 1) : productKey
225
228
  const rank = (archived ? 2 : 0) + (interval === 'year' ? 1 : 0)
@@ -333,7 +336,7 @@ function catalogCurrencies(rows: ProductRow[], sources: PricingSources): string[
333
336
  }
334
337
 
335
338
  /** The `getPricing` query of one `setupBilling` call, and the read behind it. */
336
- export function createPricing({ provider, cache, products, retiredProductIds, catalogIds, meterNameById }: BillingContext, { promotionNamed }: Pick<CatalogDiscounts, 'promotionNamed'>) {
339
+ export function createPricing({ provider, cache, products, retiredProductIds, catalogIds, creditMeters, meterNameById }: BillingContext, { promotionNamed }: Pick<CatalogDiscounts, 'promotionNamed'>) {
337
340
  /**
338
341
  * The pricing as the products table holds it now: what `getPricing`
339
342
  * answers, and where a refusal finds the plans to offer. Each catalog
@@ -354,6 +357,7 @@ export function createPricing({ provider, cache, products, retiredProductIds, ca
354
357
  retired: retiredProductIds,
355
358
  hidden: new Set(Object.values(catalogIds?.gifts ?? {})),
356
359
  meterNames: meterNameById,
360
+ meterUnits: new Map(Object.entries(creditMeters).flatMap(([key, meter]) => meter.unit ? [[key, meter.unit]] : [])),
357
361
  benefitMetadata: new Map(snapshots.map(snapshot => [snapshot.benefitId, snapshot.metadata])),
358
362
  ...(catalogIds?.free ? { free: catalogIds.free } : {}),
359
363
  currencies: [currency?.trim().toLowerCase(), catalogIds?.currency].filter((code): code is string => Boolean(code)),
@@ -1,10 +1,9 @@
1
1
  import type { BillingContext } from './context.js'
2
- import { readEnv } from './context.js'
2
+ import { readEnv, backendEnvironment } from '../../delivery.js'
3
3
  import { currencyOf } from './pricing.js'
4
4
  import type { CheckoutCreateInput, ProviderCtx, RunQueryCtx } from './types/base.js'
5
5
  import type { CampaignAttribution, CheckoutTrial } from './types/options.js'
6
6
  import { backendError } from '../../errors.js'
7
- import { backendEnvironment } from '../../delivery.js'
8
7
  import { trustsLocalOrigins } from '../../environment.js'
9
8
  import { isLocalOrigin } from '../../local-origins.js'
10
9
  import { logBackend } from '../../log.js'
@@ -84,6 +84,19 @@ export type SaveOffer
84
84
  /** What `cancelSubscription` answers: the save offer for the reason, or the cancellation and when the plan ends (epoch ms). */
85
85
  export type CancelOutcome = { offer: SaveOffer } | { canceled: true, endsAt: number | null }
86
86
 
87
+ /**
88
+ * What `getCancelFlow` reads before the cancel flow asks its question: the
89
+ * reasons whose save offer could stand for the subscription now, and
90
+ * `offers`, whether any could. None inside the withdrawal period, on a
91
+ * past-due plan or a trial, after an offer in the last 12 months, or with
92
+ * none configured: "Continue" would then cancel at once, so the flow says
93
+ * "Cancel my plan" and asks to confirm instead.
94
+ */
95
+ export interface CancelFlowState {
96
+ offers: boolean
97
+ reasons: CancellationReason[]
98
+ }
99
+
87
100
  /** A purchase and its withdrawal period, as `getWithdrawal` reads it: what `<WithdrawalButton>` shows until `endsAt`. */
88
101
  export interface WithdrawalPeriod {
89
102
  subscriptionId: string
@@ -1,4 +1,5 @@
1
1
  import type { CancellationReason, DiscountInput, ProrationBehavior, ProviderDiscount, RefundReason } from './base.js'
2
+ import type { MeterUnit } from '../../../catalog.js'
2
3
 
3
4
  // What the subscription, order, usage, refund, discount and checkout
4
5
  // operations take and return.
@@ -122,13 +123,15 @@ export interface UsageHistoryOptions {
122
123
  * for a Convex action's return value (dates as ISO strings). `units` is
123
124
  * resolved from the meter's value property — the same property a spend ingests
124
125
  * — and is absent when the meter is unknown or counts events rather than
125
- * summing a property.
126
+ * summing a property. `unit` is what the meter counts, beside `units` when
127
+ * the catalog names it.
126
128
  */
127
129
  export type UsageEvent = {
128
130
  id: string
129
131
  timestamp: string
130
132
  name: string
131
133
  units?: number
134
+ unit?: MeterUnit
132
135
  metadata?: Record<string, string | number | boolean>
133
136
  } & Record<string, unknown>
134
137
 
@@ -1,6 +1,6 @@
1
1
  // The entitlement, credit and gift records the billing modules pass around.
2
2
 
3
- import type { CatalogInterval } from '../../../catalog.js'
3
+ import type { CatalogInterval, MeterUnit } from '../../../catalog.js'
4
4
 
5
5
  /**
6
6
  * What a granted benefit gives, in the package's own words rather than the
@@ -51,6 +51,8 @@ export interface EntitlementBenefit {
51
51
  /** A credit-meter balance in a customer's billing state (prepaid credits). */
52
52
  export interface EntitlementMeter {
53
53
  meterId: string
54
+ /** What the meter counts, when the catalog names its unit (`getCredits` adds it). */
55
+ unit?: MeterUnit
54
56
  consumedUnits: number
55
57
  creditedUnits: number
56
58
  balance: number
@@ -93,6 +95,8 @@ export interface CreditMeterConfig {
93
95
  * count events, so each spend is exactly 1 credit).
94
96
  */
95
97
  property?: string
98
+ /** What the meter counts, as the catalog's `unit` names it: the packaged labels' word for its units. */
99
+ unit?: MeterUnit
96
100
  }
97
101
 
98
102
  /**
@@ -364,6 +368,8 @@ export interface GiftTask {
364
368
  export interface PricedCredits {
365
369
  /** The catalog meter they land on; absent for a meter the catalog does not name. */
366
370
  meter?: string
371
+ /** What that meter counts, when the catalog names its unit. */
372
+ unit?: MeterUnit
367
373
  /** Units per billing cycle (a plan), or once (a pack). */
368
374
  units: number
369
375
  /** Whether unspent units carry over into the next cycle. */
@@ -2,7 +2,7 @@ import type { Polar } from '@convex-dev/polar'
2
2
  import type { actionGeneric, Auth, internalActionGeneric, queryGeneric, RegisteredAction, RegisteredQuery, Scheduler } from 'convex/server'
3
3
  import type { CancellationReason, ProviderSubscription, RunQueryCtx, RunWriteCtx } from './base.js'
4
4
  import type { RecordBillingEvent } from '../activity.js'
5
- import type { CancelOutcome, BillingConsole, WithdrawalPeriod } from './lifecycle.js'
5
+ import type { CancelFlowState, CancelOutcome, BillingConsole, WithdrawalPeriod } from './lifecycle.js'
6
6
  import type { RevenueInterval, RevenueReport } from './revenue.js'
7
7
  import type {
8
8
  ApplyDiscountOptions,
@@ -141,6 +141,8 @@ export interface Billing {
141
141
  * names one (`{ offer }`; `offer: false` cancels past it).
142
142
  */
143
143
  cancelSubscription: RegisteredAction<'public', { subscriptionId?: string, atPeriodEnd?: boolean, reason?: CancellationReason, comment?: string, offer?: false }, Promise<CancelOutcome>>
144
+ /** What the cancel flow reads before it asks: whether a save offer could stand, and for which reasons; `null` for anyone who may not manage the billing (LIFECYCLE). */
145
+ getCancelFlow: RegisteredQuery<'public', { subscriptionId?: string }, Promise<CancelFlowState | null>>
144
146
  /** Apply the save offer the cancel flow made, by its id (LIFECYCLE). */
145
147
  acceptSaveOffer: RegisteredAction<'public', { offerId: string }, Promise<null>>
146
148
  /** The caller's purchase inside its EU withdrawal period, for the withdrawal button (`period`, `null` without one); `null` for anyone who may not manage the billing (LIFECYCLE). */
@@ -78,11 +78,11 @@ export type {
78
78
  export type { BillingWebhookEventHandlers, SaveOfferTerms, BillingComponents, BillingEmail, BillingEntity, BillingAccessRule, BillingEntityCtx, EntityProfile, SetupBillingConfig } from './billing/types/setup.js'
79
79
  export type { AccountBillingErasure, AccountBillingErasureInput, AccountBillingExport, AccountBillingRecord, Billing } from './billing/types/surface.js'
80
80
  export type { BillingAudit } from './billing/activity.js'
81
- export type { BillingLifecycle, CancelOutcome, BillingConsole, SaveOffer, SaveOfferRule, WithdrawalPeriod } from './billing/types/lifecycle.js'
81
+ export type { BillingLifecycle, CancelFlowState, CancelOutcome, BillingConsole, SaveOffer, SaveOfferRule, WithdrawalPeriod } from './billing/types/lifecycle.js'
82
82
  export type { MeterUsage, RevenueCancellations, RevenueInterval, RevenueMetric, RevenueOptions, RevenuePeriod, RevenueReport, RevenueValues } from './billing/types/revenue.js'
83
83
 
84
84
  // Catalog-as-code authoring surface (billing.catalog.ts / `billing sync`).
85
- export { type BillingCatalog, type CatalogCreditGrant, type CatalogCurrencyPrices, type CatalogDiscount, type CatalogDiscountDuration, type CatalogDiscountProducts, type CatalogDiscountTerms, type CatalogFeature, type CatalogInterval, type CatalogMeter, type CatalogPack, type CatalogPackPrices, type CatalogPlan, type CatalogPlanCreditGrant, type CatalogPlanGift, type CatalogPlanPrices, type CatalogQuota, defineBillingCatalog } from '../catalog.js'
85
+ export { type BillingCatalog, type CatalogCreditGrant, type CatalogCurrencyPrices, type CatalogDiscount, type CatalogDiscountDuration, type CatalogDiscountProducts, type CatalogDiscountTerms, type CatalogFeature, type CatalogInterval, type CatalogMeter, type CatalogPack, type CatalogPackPrices, type CatalogPlan, type CatalogPlanCreditGrant, type CatalogPlanGift, type CatalogPlanPrices, type CatalogQuota, defineBillingCatalog, type MeterUnit } from '../catalog.js'
86
86
  export { ALL_BILLING_EVENTS } from './billing/events.js'
87
87
 
88
88
  // The referral program (REF), set up in its own backend file beside billing.
@@ -202,6 +202,7 @@ export function setupBilling(
202
202
  getBillingConsole: functions.getBillingConsole,
203
203
  updateSubscription: functions.updateSubscriptionFn,
204
204
  cancelSubscription: functions.cancelSubscriptionFn,
205
+ getCancelFlow: functions.getCancelFlow,
205
206
  acceptSaveOffer: functions.acceptSaveOfferFn,
206
207
  getWithdrawal: functions.getWithdrawal,
207
208
  withdraw: functions.withdrawFn,
@@ -36,7 +36,7 @@ import { ownCaller } from './access.js'
36
36
  // gate every send under a topic passes, and the RFC 8058 one-click route.
37
37
  // `setupEmail` builds it from its `topics` and `caps` and returns its parts.
38
38
 
39
- export type { ClockTime, EmailCaps, EmailTopic, EmailTopics, TopicSource, TopicState } from '../email-preferences.js'
39
+ export type { EmailCaps, EmailTopics, TopicState } from '../email-preferences.js'
40
40
 
41
41
  type RunMutationCtx = Pick<GenericActionCtx<GenericDataModel>, 'runMutation'>
42
42
  type RunQueryCtx = Pick<GenericActionCtx<GenericDataModel>, 'runQuery'>
@@ -116,6 +116,49 @@ function refused(what: string, error: ProviderError): Error {
116
116
  return new Error(`[nuxt-backend] email sync: the provider refused to ${what}: ${error?.message ?? 'no answer'}`)
117
117
  }
118
118
 
119
+ /** How many times one call is tried while the provider answers it with its rate limit. */
120
+ const RATE_LIMIT_ATTEMPTS = 5
121
+
122
+ /** The longest wait for the provider's rate limit to reset. */
123
+ const RATE_LIMIT_WAIT_MAX_MS = 60_000
124
+
125
+ /** A header of the provider's answer, as a number of seconds; `undefined` when absent. */
126
+ function seconds(headers: Record<string, string> | null, name: string): number | undefined {
127
+ const value = Number(headers?.[name])
128
+ return headers?.[name] !== undefined && Number.isFinite(value) && value >= 0 ? value : undefined
129
+ }
130
+
131
+ /**
132
+ * The provider's client, paced to its rate limit: each answer says how many
133
+ * calls a second the key may make (`ratelimit-limit`) and when the window
134
+ * resets once they are spent, so the next call waits for its turn. A call
135
+ * the provider still answers `429` is tried again after the `retry-after`
136
+ * it names, up to {@link RATE_LIMIT_ATTEMPTS} times. A sync makes dozens of
137
+ * calls one after another (a template, its publication and its automation
138
+ * for every flow); unpaced, it passed the limit on every run.
139
+ */
140
+ function paced(resend: Resend): Resend {
141
+ const unpaced = resend.fetchRequest.bind(resend)
142
+ let spacingMs = 0
143
+ let nextAt = 0
144
+ resend.fetchRequest = async <T>(path: string, options: Parameters<Resend['fetchRequest']>[1] = {}) => {
145
+ for (let attempt = 1; ; attempt++) {
146
+ const ahead = nextAt - Date.now()
147
+ if (ahead > 0) await new Promise(resolve => setTimeout(resolve, ahead))
148
+ const answer = await unpaced<T>(path, options)
149
+ const limit = seconds(answer.headers, 'ratelimit-limit')
150
+ if (limit) spacingMs = Math.ceil(1000 / limit)
151
+ const spent = seconds(answer.headers, 'ratelimit-remaining') === 0
152
+ nextAt = Date.now() + Math.max(spacingMs, spent ? (seconds(answer.headers, 'ratelimit-reset') ?? 0) * 1000 : 0)
153
+ const limited = answer.error?.statusCode === 429 || answer.error?.name === 'rate_limit_exceeded'
154
+ if (!limited || attempt >= RATE_LIMIT_ATTEMPTS) return answer
155
+ const retryAfter = seconds(answer.headers, 'retry-after') ?? seconds(answer.headers, 'ratelimit-reset') ?? 1
156
+ nextAt = Date.now() + Math.min(retryAfter * 1000, RATE_LIMIT_WAIT_MAX_MS)
157
+ }
158
+ }
159
+ return resend
160
+ }
161
+
119
162
  /** The most items one page of a provider listing holds. */
120
163
  const PAGE_LIMIT = 100
121
164
  /** The most pages one listing reads: past them, a sync works from what it read. */
@@ -486,7 +529,7 @@ export async function syncEmail(
486
529
  report.flows.unsynced = flows.unsynced
487
530
  const apiKey = readEnv('EMAIL_API_KEY')
488
531
  if (!apiKey) return report
489
- const resend = new Resend(apiKey)
532
+ const resend = paced(new Resend(apiKey))
490
533
  const listed = await listTopics(resend)
491
534
  if (listed.error) {
492
535
  if (restricted(listed.error)) return { ...report, key: 'restricted' }
@@ -10,8 +10,16 @@ import {
10
10
  NOTIFICATION_KINDS,
11
11
  type NotificationChannel,
12
12
  choosableChannels,
13
+ isTransactional,
14
+ listedKind,
15
+ type NotificationEntity,
16
+ notificationEntity,
17
+ type NotificationFeatures,
18
+ notificationKind,
13
19
  notificationLabelKey,
14
20
  type NotificationPlan,
21
+ type NotificationType,
22
+ notificationWordKeys,
15
23
  type NotifyEvent,
16
24
  type NotifyOptions,
17
25
  notifyProblem,
@@ -34,9 +42,12 @@ export type {
34
42
  Delivery,
35
43
  NotificationAudience,
36
44
  NotificationChannel,
45
+ NotificationEntity,
46
+ NotificationFeature,
37
47
  NotificationKind,
38
48
  NotificationDestination,
39
49
  NotificationPlan,
50
+ NotificationType,
40
51
  NotifyEvent,
41
52
  NotifyKind,
42
53
  NotifyOptions,
@@ -63,6 +74,13 @@ export interface NotificationEntry {
63
74
  actor: NotificationParty
64
75
  /** The workspace it happened in, by its name now. */
65
76
  workspace: { id: string, name: string | null } | null
77
+ /**
78
+ * Whose plan, credits or gift a billing, gift or referral kind is about:
79
+ * `account` the reader's own (`billTo: 'user'`), `workspace` the one
80
+ * `workspace` names. `null` for every other kind. The inbox words an
81
+ * `account` one with the kind's `titleYours` and `bodyYours`.
82
+ */
83
+ entity: NotificationEntity | null
66
84
  /** The thing acted on. */
67
85
  targetId: string | null
68
86
  /** Where it links, for a kind of your own (`notify`'s `link`); `null` for a package kind, which links to a ready-made page by its type. */
@@ -176,6 +194,8 @@ export interface ForgottenNotifications {
176
194
  /** What the notifications need of `setupEmail`'s instance: the layout and words, and the sending rules. */
177
195
  export interface NotificationsEmail {
178
196
  compose: <Message extends EmailMessage | null>(build: (context: EmailRenderContext) => Message | Promise<Message>, options?: { locale?: string | null }) => Promise<Message>
197
+ /** The transactional send, under no sending rule: a transactional kind's email goes through it. */
198
+ send: (ctx: Pick<GenericActionCtx<GenericDataModel>, 'runMutation'>, message: EmailMessage) => Promise<string | null>
179
199
  /**
180
200
  * The sending rules the email instance holds: the weekly cap and the quiet hours.
181
201
  *
@@ -201,12 +221,23 @@ export interface SetupNotificationsOptions {
201
221
  /**
202
222
  * The email instance (`setupEmail`), which email and push notifications
203
223
  * are worded and rendered with: your messages, your brand and layout,
204
- * and the weekly cap and quiet hours. Without it, notifications reach the
224
+ * and the weekly cap and quiet hours, which a transactional kind skips. Without it, notifications reach the
205
225
  * inbox alone. Re-export `deliverNotification` with it.
206
226
  */
207
227
  email?: NotificationsEmail
208
228
  /** The paths the Nuxt module writes to `paths.generated.ts`: a package kind's email links to its ready-made page there. */
209
229
  paths?: Partial<BackendPaths>
230
+ /**
231
+ * The package's kinds your app sends, for the channel list
232
+ * (`getNotificationChannels`, `useEmailPreferences().channels`): only
233
+ * these appear there, with your own kinds of `notify`, and only these
234
+ * take a choice (`setNotificationChannel`). An app that never shares a
235
+ * workspace leaves out the `workspace.` kinds. Left out, every kind
236
+ * appears but those of a billing feature the deployment has never used:
237
+ * gifts, plan passes, reverse trials and referrals. The list shapes the
238
+ * choices only: a kind it leaves out still reaches the inbox if it happens.
239
+ */
240
+ kinds?: readonly NotificationType[]
210
241
  }
211
242
 
212
243
  /** The `backend` component as the inbox reads it. */
@@ -214,14 +245,18 @@ export interface NotificationsComponents {
214
245
  backend: unknown
215
246
  }
216
247
 
248
+ /** A notification as the component reads it: the entry, before the billing entity is told from its workspace. */
249
+ type StoredEntry = Omit<NotificationEntry, 'entity'>
250
+
217
251
  interface NotificationsRefs {
218
252
  notifications: {
219
- list: FunctionReference<'query', 'internal', { userId: string, paginationOpts: PaginationArgs }, NotificationsPage>
253
+ list: FunctionReference<'query', 'internal', { userId: string, paginationOpts: PaginationArgs }, Omit<NotificationsPage, 'page'> & { page: StoredEntry[] }>
220
254
  unread: FunctionReference<'query', 'internal', { userId: string }, UnreadCount>
221
255
  markRead: FunctionReference<'mutation', 'internal', { userId: string, ids: string[] }, number>
222
256
  markAllRead: FunctionReference<'mutation', 'internal', { userId: string }, MarkedRead>
223
257
  forget: FunctionReference<'mutation', 'internal', { type: string, targetId: string }, ForgottenNotifications>
224
258
  listChoices: FunctionReference<'query', 'internal', { userId: string }, Array<{ type: string, channel: NotificationChannel, enabled: boolean }>>
259
+ features: FunctionReference<'query', 'internal', Record<string, never>, NotificationFeatures>
225
260
  choose: FunctionReference<'mutation', 'internal', { userId: string, type: string, channel: NotificationChannel, enabled: boolean }, null>
226
261
  recipient: FunctionReference<'query', 'internal', { userId: string, type: string, channel: NotificationChannel, actorId?: string, impersonated?: boolean, entityId?: string }, Recipient | null>
227
262
  }
@@ -269,17 +304,20 @@ const PUSH_RETRY_MAX_MS = 60 * 60 * 1000
269
304
  /** The words of a party, when the event names none by name. */
270
305
  const ACTOR_WORDS = { you: 'actorSomeone', user: 'actorSomeone', administrator: 'actorAdministrator', app: 'actorApp', erased: 'actorErased' } as const
271
306
 
272
- /** A notification's words in a reader's language: its title and body, the kind's own or the fallback. */
273
- function notificationWords(t: EmailRenderContext['t'], type: string, recipient: Recipient, data: Record<string, string | number | boolean | string[]>): { title: string, body: string | null } {
307
+ /** A notification's words in a reader's language: its title and body, the kind's own (those for the reader's own account, when the billing entity is theirs) or the fallback. */
308
+ function notificationWords(t: EmailRenderContext['t'], type: string, recipient: Recipient, data: Record<string, string | number | boolean | string[]>, entity: NotificationEntity | null): { title: string, body: string | null } {
274
309
  const params: Record<string, string | number> = {}
275
310
  for (const [name, value] of Object.entries(data)) params[name] = Array.isArray(value) ? value.join(', ') : typeof value === 'boolean' ? String(value) : value
276
311
  params.actor = recipient.actor.name ?? t(`notifications.${ACTOR_WORDS[recipient.actor.kind]}`)
277
312
  params.workspace = recipient.workspace ?? t('notifications.workspaceUnnamed')
278
313
  // A package kind's words sit under `backend.notifications` (packaged); an app's own kind's under the same key of its messages.
279
314
  const key = type.startsWith('app.') ? `backend.notifications.${notificationLabelKey(type)}` : `notifications.${notificationLabelKey(type)}`
280
- const read = (part: string) => {
281
- const text = t(`${key}.${part}`, params)
282
- return text === `${key}.${part}` ? null : text
315
+ const read = (part: 'title' | 'body') => {
316
+ for (const name of notificationWordKeys(part, entity)) {
317
+ const text = t(`${key}.${name}`, params)
318
+ if (text !== `${key}.${name}`) return text
319
+ }
320
+ return null
283
321
  }
284
322
  return { title: read('title') ?? t('notifications.fallbackTitle'), body: read('body') }
285
323
  }
@@ -314,11 +352,15 @@ export function setupNotifications(components: NotificationsComponents, options:
314
352
  const notify = options.notify ?? {}
315
353
  const problem = notifyProblem(notify)
316
354
  if (problem) throw new TypeError(`[nuxt-backend] setupNotifications({ notify }): ${problem}`)
355
+ const unknownKind = options.kinds?.find(type => !notificationKind(type))
356
+ if (unknownKind !== undefined) throw new TypeError(`[nuxt-backend] setupNotifications({ kinds }): ${JSON.stringify(unknownKind)} is no kind of the package that notifies. List the package's kinds (\`billing.order_paid\`); your own kinds of \`notify\` are always on the list.`)
357
+ const kinds = options.kinds ? new Set<string>(options.kinds) : null
317
358
 
318
359
  const listNotifications = queryGeneric({
319
360
  args: { paginationOpts: paginationOptsValidator },
320
361
  handler: async (ctx, { paginationOpts }): Promise<NotificationsPage> => {
321
- return ctx.runQuery(refs.notifications.list, { userId: await ownCaller(ctx, 'listNotifications'), paginationOpts })
362
+ const result = await ctx.runQuery(refs.notifications.list, { userId: await ownCaller(ctx, 'listNotifications'), paginationOpts })
363
+ return { ...result, page: result.page.map(entry => ({ ...entry, entity: notificationEntity(entry.type, entry.workspace?.id) })) }
322
364
  },
323
365
  })
324
366
 
@@ -344,9 +386,9 @@ export function setupNotifications(components: NotificationsComponents, options:
344
386
 
345
387
  // ── Channels, kind by kind ───────────────────────────────────────────
346
388
 
347
- /** The channels each kind may use, by the channel matrix, and the email the package sends itself for a new device: the package's kinds that notify, then the app's own. */
389
+ /** The channels each kind may use, by the channel matrix, and the email the package sends itself for a new device: the package's kinds that notify (those `kinds` lists, when it does), then the app's own. */
348
390
  const allowed = new Map<string, NotificationChannel[]>([
349
- ...Object.keys(NOTIFICATION_KINDS).map(type => [type, choosableChannels(type, declaredChannels(type))] as const),
391
+ ...Object.keys(NOTIFICATION_KINDS).filter(type => listedKind(type, kinds, null)).map(type => [type, choosableChannels(type, declaredChannels(type))] as const),
350
392
  ...Object.entries(notify).map(([type, kind]) => [type, choosableChannels(type, kind.channels)] as const),
351
393
  ].filter(([, channels]) => channels.length > 0))
352
394
 
@@ -357,7 +399,9 @@ export function setupNotifications(components: NotificationsComponents, options:
357
399
  if (!identity) return null
358
400
  const userId = await ownCaller(ctx, 'getNotificationChannels')
359
401
  const chosen = new Map((await ctx.runQuery(refs.notifications.listChoices, { userId })).map(row => [`${row.type} ${row.channel}`, row.enabled]))
360
- return [...allowed].map(([type, channels]) => ({ type, channels: channels.map(channel => ({ channel, enabled: chosen.get(`${type} ${channel}`) ?? true })) }))
402
+ // Without `kinds`, a billing feature the deployment has never used (no gift bought, no referral) lists none of its kinds.
403
+ const features = kinds ? null : await ctx.runQuery(refs.notifications.features, {})
404
+ return [...allowed].filter(([type]) => listedKind(type, kinds, features)).map(([type, channels]) => ({ type, channels: channels.map(channel => ({ channel, enabled: chosen.get(`${type} ${channel}`) ?? true })) }))
361
405
  },
362
406
  })
363
407
 
@@ -410,7 +454,7 @@ export function setupNotifications(components: NotificationsComponents, options:
410
454
  const target = (type: string, link: string | null): string => {
411
455
  const site = (readEnv('SITE_URL') ?? '').replace(/\/$/, '')
412
456
  if (link) return `${site}${link}`
413
- const kind = Object.hasOwn(NOTIFICATION_KINDS, type) ? NOTIFICATION_KINDS[type as keyof typeof NOTIFICATION_KINDS] : undefined
457
+ const kind = notificationKind(type)
414
458
  const page = kind?.page === 'security' ? pages.security : kind?.page === 'settings' ? pages.settings : '/profile'
415
459
  return `${site}${page}`
416
460
  }
@@ -420,7 +464,7 @@ export function setupNotifications(components: NotificationsComponents, options:
420
464
  if (!email) return null
421
465
  let words: { title: string, body: string | null, url: string, locale: string } | null = null
422
466
  await email.compose((context) => {
423
- words = { ...notificationWords(context.t, delivery.event.type, recipient, delivery.event.data ?? {}), url: context.link(target(delivery.event.type, delivery.link)), locale: context.locale }
467
+ words = { ...notificationWords(context.t, delivery.event.type, recipient, delivery.event.data ?? {}, notificationEntity(delivery.event.type, delivery.event.entityId)), url: context.link(target(delivery.event.type, delivery.link)), locale: context.locale }
424
468
  return null
425
469
  }, { locale: recipient.locale })
426
470
  return words as { title: string, body: string | null, url: string, locale: string } | null
@@ -429,7 +473,7 @@ export function setupNotifications(components: NotificationsComponents, options:
429
473
  const deliverEmail = async (ctx: DeliveryCtx, delivery: ScheduledDelivery, recipient: Recipient) => {
430
474
  if (!email || !recipient.email) return
431
475
  const message = await email.compose(({ t }) => {
432
- const words = notificationWords(t, delivery.event.type, recipient, delivery.event.data ?? {})
476
+ const words = notificationWords(t, delivery.event.type, recipient, delivery.event.data ?? {}, notificationEntity(delivery.event.type, delivery.event.entityId))
433
477
  return {
434
478
  to: recipient.email!,
435
479
  subject: words.title,
@@ -441,6 +485,11 @@ export function setupNotifications(components: NotificationsComponents, options:
441
485
  ],
442
486
  }
443
487
  }, { locale: recipient.locale })
488
+ // A transactional kind goes at once, as a transactional email does: no cap, no quiet hours.
489
+ if (isTransactional(notify, delivery.event.type)) {
490
+ await email.send(ctx, message)
491
+ return
492
+ }
444
493
  // The weekly cap and the quiet hours, as for every non-transactional email; never the sunset rule.
445
494
  const prepared = await email.preferences.prepare(ctx, message, undefined, async () => ({ unsubscribe: '' }), { sunset: false })
446
495
  if (prepared) await ctx.runMutation(refs.email.send, prepared)
@@ -449,8 +498,8 @@ export function setupNotifications(components: NotificationsComponents, options:
449
498
  const deliverPush = async (ctx: DeliveryCtx, delivery: ScheduledDelivery, recipient: Recipient) => {
450
499
  const keys = pushKeys()
451
500
  if (!keys) return
452
- // The quiet hours hold a push to their end, on the person's own clock.
453
- if (delivery.attempt === undefined) {
501
+ // The quiet hours hold a push to their end, on the person's own clock; a transactional kind's goes at once.
502
+ if (delivery.attempt === undefined && !isTransactional(notify, delivery.event.type)) {
454
503
  const until = await ctx.runQuery(refs.preferences.quietUntil, { userId: delivery.userId, quietHours: email?.preferences.caps.quietHours ?? null })
455
504
  if (until !== null && until > Date.now()) {
456
505
  await ctx.scheduler.runAt(until, self, { ...delivery, attempt: 1 })
@@ -178,11 +178,12 @@ export const DEFAULT_LIMITS = {
178
178
  * tap on "Sign in with passkey", and each sign-in page that offers
179
179
  * passkeys in the browser's autofill, again every four and a half minutes
180
180
  * while it stays open in view, a challenge lasting five. Keyed by an
181
- * HMAC, under the auth secret, of the address Better Auth reads from
182
- * `x-forwarded-for` (its `advanced.ipAddress` options), which only a
183
- * proxy in front of the deployment makes trustworthy: anyone calling the
184
- * deployment directly writes that header themselves. A best effort, then,
185
- * with {@link DEFAULT_LIMITS.passkeySignInGlobal} as the ceiling behind it.
181
+ * HMAC, under the auth secret, of the client's address: the one the app's
182
+ * server signed under `PROTECTION_PROOF_SECRET` for a request through its
183
+ * auth proxy (clientAddressPlugin), else the one Convex wrote into
184
+ * `x-forwarded-for`, the address that connected. Without the secret every
185
+ * visitor through the app's server shares that server's address, so
186
+ * {@link DEFAULT_LIMITS.passkeySignInGlobal} is the ceiling behind it.
186
187
  */
187
188
  passkeySignIn: { kind: 'token bucket', rate: 30, period: MINUTE, capacity: 30 },
188
189
  /**
@@ -39,7 +39,7 @@ import { DEFAULT_LIMITS } from './rate-limit.js'
39
39
  // goes. Every decision is emailed to whoever the law says must hear of it,
40
40
  // and recorded on the activity trail without the reporter.
41
41
 
42
- export { REMOVAL_DEADLINE_MS, REPORT_REASONS, type ReportReason } from '../report-rules.js'
42
+ export type { ReportReason } from '../report-rules.js'
43
43
 
44
44
  /**
45
45
  * A reported thing of the app's: the table it is in and its row id, an id of