@cosmicdrift/kumiko-bundled-features 0.387.0 → 0.389.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (320) hide show
  1. package/dist/agent-tools/index.d.ts +1 -1
  2. package/dist/agent-tools/index.js +1 -1
  3. package/dist/agent-tools/tool-dispatch.d.ts +12 -7
  4. package/dist/agent-tools/tool-dispatch.js +42 -31
  5. package/dist/audit/feature.js +1 -0
  6. package/dist/audit/handlers/audit-events.js +1 -1
  7. package/dist/auth-email-password/handlers/request-account-unlock.write.d.ts +1 -0
  8. package/dist/auth-email-password/handlers/request-account-unlock.write.js +1 -0
  9. package/dist/auth-email-password/handlers/request-email-verification.write.d.ts +1 -0
  10. package/dist/auth-email-password/handlers/request-email-verification.write.js +1 -0
  11. package/dist/auth-email-password/handlers/request-password-reset.write.d.ts +1 -0
  12. package/dist/auth-email-password/handlers/request-password-reset.write.js +1 -0
  13. package/dist/auth-email-password/handlers/signup-request.write.d.ts +1 -0
  14. package/dist/auth-email-password/handlers/signup-request.write.js +4 -0
  15. package/dist/auth-email-password/handlers/token-request-handler.d.ts +2 -0
  16. package/dist/auth-email-password/handlers/token-request-handler.js +5 -0
  17. package/dist/auth-email-password/magic-link-mail.d.ts +2 -0
  18. package/dist/auth-email-password/magic-link-mail.js +7 -3
  19. package/dist/auth-email-password/signup-activation.d.ts +1 -0
  20. package/dist/auth-email-password/signup-activation.js +1 -0
  21. package/dist/auth-email-password/web/auth-client.d.ts +2 -2
  22. package/dist/auth-email-password/web/auth-client.js +8 -4
  23. package/dist/auth-email-password/web/auth-redirect.d.ts +5 -1
  24. package/dist/auth-email-password/web/auth-redirect.js +20 -25
  25. package/dist/auth-email-password/web/default-auth-pages-gate.js +6 -3
  26. package/dist/auth-email-password/web/forgot-password-screen.d.ts +4 -1
  27. package/dist/auth-email-password/web/forgot-password-screen.js +7 -2
  28. package/dist/auth-email-password/web/index.d.ts +1 -0
  29. package/dist/auth-email-password/web/index.js +1 -0
  30. package/dist/auth-email-password/web/login-screen.js +11 -6
  31. package/dist/auth-email-password/web/reset-password-screen.js +7 -1
  32. package/dist/auth-email-password/web/return-path.d.ts +4 -0
  33. package/dist/auth-email-password/web/return-path.js +34 -0
  34. package/dist/auth-email-password/web/session.js +6 -1
  35. package/dist/auth-email-password/web/signup-complete-screen.js +11 -3
  36. package/dist/auth-email-password/web/signup-screen.d.ts +4 -1
  37. package/dist/auth-email-password/web/signup-screen.js +8 -3
  38. package/dist/auth-mfa/config.d.ts +1 -1
  39. package/dist/auth-mfa/config.js +3 -7
  40. package/dist/auth-mfa/feature-exports.d.ts +2 -2
  41. package/dist/auth-mfa/feature.js +8 -0
  42. package/dist/auth-mfa/mfa-status-checker.js +5 -3
  43. package/dist/auth-mfa/web/i18n.js +5 -1
  44. package/dist/auth-mfa/web/mfa-code-or-recovery-field.d.ts +11 -0
  45. package/dist/auth-mfa/web/mfa-code-or-recovery-field.js +12 -0
  46. package/dist/auth-mfa/web/mfa-disable-dialog.js +14 -3
  47. package/dist/auth-mfa/web/mfa-regenerate-recovery-dialog.js +14 -3
  48. package/dist/auth-mfa/web/mfa-setup-preauth-screen.js +10 -5
  49. package/dist/auth-mfa/web/mfa-verify-screen.js +26 -5
  50. package/dist/billing-foundation/checkout-core.d.ts +9 -14
  51. package/dist/billing-foundation/checkout-core.js +24 -39
  52. package/dist/billing-foundation/consumer-protection/confirmation-mail.js +8 -2
  53. package/dist/billing-foundation/consumer-protection/consent-gate.d.ts +1 -0
  54. package/dist/billing-foundation/consumer-protection/consent-gate.js +1 -0
  55. package/dist/billing-foundation/consumer-protection/issue-confirmation.js +9 -3
  56. package/dist/billing-foundation/consumer-protection/mail-notifications.js +3 -1
  57. package/dist/billing-foundation/consumer-protection/termination-receipt-limit.d.ts +4 -2
  58. package/dist/billing-foundation/consumer-protection/termination-receipt-limit.js +6 -5
  59. package/dist/billing-foundation/consumer-protection/termination-record.d.ts +5 -1
  60. package/dist/billing-foundation/consumer-protection/termination-record.js +27 -17
  61. package/dist/billing-foundation/consumer-protection/termination-request.js +12 -7
  62. package/dist/billing-foundation/consumer-protection/termination-revoke.js +12 -7
  63. package/dist/billing-foundation/consumer-protection/termination-texts.d.ts +1 -1
  64. package/dist/billing-foundation/consumer-protection/termination-texts.js +3 -0
  65. package/dist/billing-foundation/consumer-protection/withdrawal-period.d.ts +5 -2
  66. package/dist/billing-foundation/consumer-protection/withdrawal-period.js +8 -9
  67. package/dist/billing-foundation/events.d.ts +1 -0
  68. package/dist/billing-foundation/events.js +1 -0
  69. package/dist/billing-foundation/feature.js +3 -1
  70. package/dist/billing-foundation/handlers/billing-plans.query.js +35 -5
  71. package/dist/billing-foundation/handlers/create-checkout-session.write.js +1 -0
  72. package/dist/billing-foundation/handlers/plan-switch-preview.query.d.ts +13 -0
  73. package/dist/billing-foundation/handlers/plan-switch-preview.query.js +48 -0
  74. package/dist/billing-foundation/handlers/process-event.write.d.ts +6 -0
  75. package/dist/billing-foundation/handlers/process-event.write.js +8 -2
  76. package/dist/billing-foundation/handlers/start-plan-checkout.write.js +32 -5
  77. package/dist/billing-foundation/handlers/switch-plan.write.d.ts +2 -2
  78. package/dist/billing-foundation/handlers/switch-plan.write.js +56 -64
  79. package/dist/billing-foundation/handlers/sync-subscription.write.js +12 -1
  80. package/dist/billing-foundation/i18n.js +22 -0
  81. package/dist/billing-foundation/index.d.ts +1 -1
  82. package/dist/billing-foundation/plan-catalog.d.ts +21 -5
  83. package/dist/billing-foundation/plan-catalog.js +25 -16
  84. package/dist/billing-foundation/plan-switch.d.ts +12 -0
  85. package/dist/billing-foundation/plan-switch.js +60 -0
  86. package/dist/billing-foundation/types.d.ts +57 -1
  87. package/dist/billing-foundation/types.js +9 -0
  88. package/dist/billing-foundation/validate-options.js +17 -0
  89. package/dist/billing-foundation/web/billing-plans-panel.js +78 -32
  90. package/dist/billing-foundation/web/checkout-consent-dialog.d.ts +17 -3
  91. package/dist/billing-foundation/web/checkout-consent-dialog.js +14 -10
  92. package/dist/billing-foundation/web/constants.d.ts +4 -0
  93. package/dist/billing-foundation/web/constants.js +4 -0
  94. package/dist/billing-foundation/web/plan-price.d.ts +15 -0
  95. package/dist/billing-foundation/web/plan-price.js +32 -0
  96. package/dist/billing-foundation/web/plan-switch-confirm-dialog.d.ts +15 -0
  97. package/dist/billing-foundation/web/plan-switch-confirm-dialog.js +66 -0
  98. package/dist/cap-counter/cap-reservation.js +20 -7
  99. package/dist/cap-counter/enforce-cap.js +2 -1
  100. package/dist/cap-counter/feature.js +1 -0
  101. package/dist/cap-counter/stock-cap-guard.js +7 -1
  102. package/dist/cap-overview/feature.js +1 -0
  103. package/dist/channel-email/feature.js +1 -1
  104. package/dist/config/handlers/cascade.query.d.ts +5 -0
  105. package/dist/config/handlers/cascade.query.js +4 -3
  106. package/dist/config/handlers/set.write.js +12 -2
  107. package/dist/config/handlers/values.query.d.ts +5 -0
  108. package/dist/config/handlers/values.query.js +4 -3
  109. package/dist/config/write-helpers.d.ts +1 -0
  110. package/dist/config/write-helpers.js +18 -9
  111. package/dist/crypto-shredding/handlers/forget-subject.write.js +14 -11
  112. package/dist/custom-fields/lib/parse-serialized-field.js +1 -1
  113. package/dist/delivery/channel-context.js +6 -3
  114. package/dist/delivery/db/queries/preferences.js +2 -2
  115. package/dist/delivery/delivery-service.js +22 -7
  116. package/dist/delivery/feature.js +1 -0
  117. package/dist/delivery/handlers/preferences.query.d.ts +1 -1
  118. package/dist/delivery/handlers/preferences.query.js +20 -1
  119. package/dist/delivery/handlers/unsubscribe-page-chrome.query.js +1 -1
  120. package/dist/delivery/index.d.ts +1 -0
  121. package/dist/delivery/index.js +1 -0
  122. package/dist/delivery/system-channel-context.d.ts +15 -0
  123. package/dist/delivery/system-channel-context.js +5 -0
  124. package/dist/delivery/unsubscribe-link.d.ts +3 -1
  125. package/dist/delivery/unsubscribe-page-strings.d.ts +1 -0
  126. package/dist/delivery/unsubscribe-page-strings.js +1 -0
  127. package/dist/delivery/unsubscribe-page.d.ts +2 -0
  128. package/dist/delivery/unsubscribe-page.js +5 -0
  129. package/dist/delivery/unsubscribe.js +25 -7
  130. package/dist/document-ingest-foundation/append-missing-extract-event.d.ts +21 -0
  131. package/dist/document-ingest-foundation/append-missing-extract-event.js +42 -0
  132. package/dist/document-ingest-foundation/events.d.ts +11 -0
  133. package/dist/document-ingest-foundation/events.js +11 -0
  134. package/dist/document-ingest-foundation/index.d.ts +2 -1
  135. package/dist/document-ingest-foundation/index.js +2 -1
  136. package/dist/feature-toggles/feature.js +1 -0
  137. package/dist/file-foundation/index.d.ts +1 -1
  138. package/dist/file-foundation/index.js +1 -1
  139. package/dist/file-foundation/read-file-ref-content.d.ts +3 -0
  140. package/dist/file-foundation/read-file-ref-content.js +6 -1
  141. package/dist/file-provider-s3/env-named-feature.d.ts +0 -2
  142. package/dist/form-draft/db/queries/cleanup.js +2 -2
  143. package/dist/form-draft/decrypt-draft.js +5 -1
  144. package/dist/host-routing/dispatch.js +11 -20
  145. package/dist/host-routing/validate-options.js +3 -0
  146. package/dist/inbound-mail-foundation/feature.js +1 -0
  147. package/dist/inbound-mail-foundation/handlers/update-account.write.d.ts +2 -2
  148. package/dist/inbound-mail-foundation/handlers/update-account.write.js +12 -4
  149. package/dist/inbound-mail-foundation/i18n.js +0 -1
  150. package/dist/inbound-mail-foundation/screens.js +0 -3
  151. package/dist/inbound-mail-foundation/types.d.ts +4 -3
  152. package/dist/inbound-mail-foundation/watch-supervisor.js +28 -11
  153. package/dist/jobs/feature.d.ts +1 -0
  154. package/dist/jobs/feature.js +9 -4
  155. package/dist/jobs/handlers/tenant-failures.query.d.ts +1 -1
  156. package/dist/jobs/handlers/tenant-failures.query.js +45 -41
  157. package/dist/jobs/handlers/tenant-runs.query.d.ts +1 -1
  158. package/dist/jobs/handlers/tenant-runs.query.js +54 -50
  159. package/dist/jobs/job-run-logger.js +5 -4
  160. package/dist/ledger/web/index.js +1 -1
  161. package/dist/legal-pages/seed.d.ts +3 -1
  162. package/dist/legal-pages/seed.js +2 -2
  163. package/dist/mail-foundation/feature.d.ts +3 -3
  164. package/dist/mail-foundation/feature.js +3 -0
  165. package/dist/mail-transport-smtp/config-keys.js +1 -1
  166. package/dist/mail-transport-smtp/feature.js +6 -5
  167. package/dist/managed-pages/constants.d.ts +1 -0
  168. package/dist/managed-pages/constants.js +1 -0
  169. package/dist/managed-pages/feature.js +3 -1
  170. package/dist/managed-pages/index.d.ts +1 -0
  171. package/dist/managed-pages/index.js +1 -0
  172. package/dist/notes-history/handlers/add-note.write.js +1 -1
  173. package/dist/personal-access-tokens/feature.d.ts +1 -1
  174. package/dist/personal-access-tokens/feature.js +5 -0
  175. package/dist/renderer-pdf/render-table-pdf.d.ts +1 -1
  176. package/dist/renderer-pdf/render-table-pdf.js +22 -10
  177. package/dist/secrets/write-gate.js +8 -2
  178. package/dist/sessions/feature.d.ts +2 -2
  179. package/dist/sessions/feature.js +5 -0
  180. package/dist/sessions/index.d.ts +1 -1
  181. package/dist/sessions/index.js +1 -1
  182. package/dist/sessions/session-callbacks.d.ts +0 -2
  183. package/dist/sessions/session-callbacks.js +1 -3
  184. package/dist/shared/decrypt-stored-pii.d.ts +1 -0
  185. package/dist/shared/decrypt-stored-pii.js +6 -1
  186. package/dist/shared/index.d.ts +1 -1
  187. package/dist/shared/index.js +1 -1
  188. package/dist/shared/mail-template-body.d.ts +6 -2
  189. package/dist/shared/mail-template-body.js +7 -4
  190. package/dist/shared/purge-files-reaching-subject.d.ts +1 -0
  191. package/dist/shared/purge-files-reaching-subject.js +19 -2
  192. package/dist/shared/run-in-sub-transaction.js +5 -5
  193. package/dist/step-dispatcher/deliver-dispatch-request.js +16 -3
  194. package/dist/step-dispatcher/feature.js +1 -0
  195. package/dist/step-dispatcher/mail-runner.d.ts +1 -0
  196. package/dist/subscription-dodo/client.d.ts +17 -0
  197. package/dist/subscription-dodo/client.js +31 -0
  198. package/dist/subscription-dodo/constants.d.ts +12 -0
  199. package/dist/subscription-dodo/constants.js +19 -0
  200. package/dist/subscription-dodo/feature.d.ts +37 -0
  201. package/dist/subscription-dodo/feature.js +144 -0
  202. package/dist/subscription-dodo/index.d.ts +2 -0
  203. package/dist/subscription-dodo/index.js +4 -0
  204. package/dist/subscription-dodo/plugin-methods.d.ts +23 -0
  205. package/dist/subscription-dodo/plugin-methods.js +260 -0
  206. package/dist/subscription-dodo/runtime.d.ts +27 -0
  207. package/dist/subscription-dodo/runtime.js +89 -0
  208. package/dist/subscription-dodo/verify-webhook.d.ts +37 -0
  209. package/dist/subscription-dodo/verify-webhook.js +189 -0
  210. package/dist/subscription-stripe/feature.js +1 -0
  211. package/dist/subscription-stripe/runtime.js +7 -6
  212. package/dist/tags/feature.js +1 -0
  213. package/dist/template-resolver/api.d.ts +3 -2
  214. package/dist/template-resolver/api.js +24 -2
  215. package/dist/template-resolver/compile-document-body.js +1 -0
  216. package/dist/template-resolver/document-ops.d.ts +5 -0
  217. package/dist/template-resolver/document-ops.js +18 -2
  218. package/dist/template-resolver/feature.js +4 -4
  219. package/dist/template-resolver/handlers/bundle-import.js +3 -3
  220. package/dist/template-resolver/handlers/copy-locale.write.d.ts +5 -1
  221. package/dist/template-resolver/handlers/copy-locale.write.js +22 -7
  222. package/dist/template-resolver/handlers/diff-to-system.query.js +3 -2
  223. package/dist/template-resolver/handlers/document-base.js +3 -2
  224. package/dist/template-resolver/handlers/find-by-id.query.js +3 -2
  225. package/dist/template-resolver/handlers/layout-source.query.d.ts +4 -0
  226. package/dist/template-resolver/handlers/layout-source.query.js +26 -6
  227. package/dist/template-resolver/handlers/list.query.js +5 -6
  228. package/dist/template-resolver/handlers/overview.query.d.ts +3 -0
  229. package/dist/template-resolver/handlers/overview.query.js +21 -10
  230. package/dist/template-resolver/handlers/patch-draft.write.js +1 -1
  231. package/dist/template-resolver/handlers/send-test-status.query.d.ts +2 -1
  232. package/dist/template-resolver/handlers/send-test-status.query.js +18 -15
  233. package/dist/template-resolver/handlers/tenant-override-counts.query.js +1 -3
  234. package/dist/template-resolver/handlers/tenant-override-selection.d.ts +2 -1
  235. package/dist/template-resolver/handlers/tenant-overrides.query.js +28 -5
  236. package/dist/template-resolver/handlers/usage.query.d.ts +2 -1
  237. package/dist/template-resolver/handlers/usage.query.js +26 -16
  238. package/dist/template-resolver/handlers/validate.query.js +7 -2
  239. package/dist/template-resolver/seeding.d.ts +1 -0
  240. package/dist/template-resolver/seeding.js +31 -12
  241. package/dist/template-resolver/store-template-resource.d.ts +1 -0
  242. package/dist/template-resolver/store-template-resource.js +65 -10
  243. package/dist/template-resolver/template-delivery-policy.d.ts +0 -5
  244. package/dist/template-resolver/template-delivery-policy.js +0 -6
  245. package/dist/template-resolver/template-meta.js +7 -4
  246. package/dist/template-resolver/template-preview.js +4 -3
  247. package/dist/template-resolver/web/constants.d.ts +2 -2
  248. package/dist/template-resolver/web/constants.js +3 -3
  249. package/dist/template-resolver/web/i18n.js +3 -0
  250. package/dist/template-resolver/web/index.d.ts +1 -0
  251. package/dist/template-resolver/web/index.js +1 -0
  252. package/dist/template-resolver/web/mail-layout-constants.d.ts +5 -0
  253. package/dist/template-resolver/web/mail-layout-constants.js +7 -0
  254. package/dist/template-resolver/web/qualified-names.d.ts +1 -0
  255. package/dist/template-resolver/web/qualified-names.js +1 -0
  256. package/dist/tenant/feature.js +1 -0
  257. package/dist/tenant/handlers/member-directory.query.d.ts +1 -0
  258. package/dist/tenant/handlers/member-directory.query.js +10 -3
  259. package/dist/tenant/handlers/team-list.query.js +3 -3
  260. package/dist/tenant/handlers/tenant-directory.query.d.ts +1 -0
  261. package/dist/tenant/handlers/tenant-directory.query.js +8 -4
  262. package/dist/tenant-lifecycle/constants.d.ts +1 -0
  263. package/dist/tenant-lifecycle/constants.js +4 -0
  264. package/dist/tenant-lifecycle/run-tenant-destroy.js +2 -2
  265. package/dist/tenant-lifecycle/stages.js +22 -1
  266. package/dist/tier-engine/handlers/set-tenant-tier.write.d.ts +2 -3
  267. package/dist/tier-engine/handlers/set-tenant-tier.write.js +4 -1
  268. package/dist/tier-engine/web/constants.js +2 -2
  269. package/dist/user/feature.js +1 -0
  270. package/dist/user-data-rights/feature.js +1 -0
  271. package/dist/user-data-rights/index.d.ts +1 -1
  272. package/dist/user-data-rights/index.js +1 -1
  273. package/dist/user-data-rights/run-export-jobs.js +3 -4
  274. package/dist/user-data-rights/run-forget-cleanup.js +2 -1
  275. package/dist/user-data-rights/web/constants.d.ts +6 -0
  276. package/dist/user-data-rights/web/constants.js +6 -0
  277. package/dist/user-data-rights/web/index.d.ts +1 -0
  278. package/dist/user-data-rights/web/index.js +1 -0
  279. package/dist/waitlist/feature.js +1 -0
  280. package/dist/waitlist/handlers/export-purge.write.js +2 -1
  281. package/dist/waitlist/handlers/submit.write.js +14 -10
  282. package/dist/waitlist/import.d.ts +3 -1
  283. package/dist/waitlist/import.js +26 -2
  284. package/dist/waitlist/legacy-migrate.js +18 -7
  285. package/dist/waitlist/link-on-signup.js +18 -6
  286. package/dist/waitlist/options.d.ts +5 -1
  287. package/dist/workflow-runner/handlers/resume-run.write.js +1 -1
  288. package/package.json +19 -9
  289. package/src/agent-tools/changes.json +12 -0
  290. package/src/audit/changes.json +12 -0
  291. package/src/auth-email-password/changes.json +12 -0
  292. package/src/auth-mfa/changes.json +12 -0
  293. package/src/billing-foundation/changes.json +55 -0
  294. package/src/cap-counter/changes.json +30 -0
  295. package/src/channel-email/changes.json +6 -0
  296. package/src/config/changes.json +18 -0
  297. package/src/crypto-shredding/changes.json +18 -0
  298. package/src/delivery/changes.json +42 -0
  299. package/src/document-ingest-foundation/changes.json +6 -0
  300. package/src/form-draft/changes.json +6 -0
  301. package/src/host-routing/changes.json +12 -0
  302. package/src/inbound-mail-foundation/changes.json +18 -0
  303. package/src/jobs/changes.json +13 -0
  304. package/src/mail-foundation/changes.json +6 -0
  305. package/src/mail-transport-smtp/changes.json +6 -0
  306. package/src/managed-pages/changes.json +6 -0
  307. package/src/renderer-pdf/changes.json +6 -0
  308. package/src/secrets/changes.json +6 -0
  309. package/src/sessions/changes.json +7 -0
  310. package/src/step-dispatcher/changes.json +12 -0
  311. package/src/subscription-dodo/changes.json +14 -0
  312. package/src/subscription-stripe/changes.json +12 -0
  313. package/src/template-resolver/changes.json +84 -0
  314. package/src/tenant/changes.json +6 -0
  315. package/src/tenant-lifecycle/changes.json +12 -0
  316. package/src/tier-engine/changes.json +6 -0
  317. package/src/user-data-rights/changes.json +12 -0
  318. package/src/waitlist/changes.json +36 -0
  319. package/dist/billing-foundation/consumer-protection/stored-user-email.d.ts +0 -1
  320. package/dist/billing-foundation/consumer-protection/stored-user-email.js +0 -8
@@ -2,20 +2,20 @@
2
2
  // benefits, the caller's current tier and per-plan action. Only registered
3
3
  // when `createBillingFoundationFeature` gets a `catalog`.
4
4
  import * as z from "zod";
5
- import { findCatalogProvider } from "../checkout-core.js";
5
+ import { filterOfferedProviders, listCatalogProviders, } from "../checkout-core.js";
6
6
  import { CONSENT_TEXTS, consentTextVersion, } from "../consumer-protection/consent-text.js";
7
- import { buildBillingPlans } from "../plan-catalog.js";
7
+ import { buildProviderPlanViews, loadBillingPlansBase, toBillingPlansResult, } from "../plan-catalog.js";
8
8
  import { isLegalLinkSet, } from "../types.js";
9
9
  const billingPlansSchema = z.object({}).strict();
10
10
  export function createBillingPlansQuery(options, catalog) {
11
11
  return {
12
12
  name: "billing-plans",
13
- description: "Lists the purchasable plans with live price, benefits, the caller's current tier and which action (checkout | switch | current | unavailable | paymentPending) each plan offers, plus the optional price-less contact card.",
13
+ description: "Lists the purchasable plans with live price, benefits, the caller's current tier and which action (checkout | switch | current | unavailable | paymentPending) each plan offers, plus the optional price-less contact card. With several live providers it also lists each provider's own plans under `providers`.",
14
14
  schema: billingPlansSchema,
15
15
  access: { roles: catalog.viewRoles },
16
16
  handler: async (_query, ctx) => {
17
- const found = findCatalogProvider(ctx, catalog);
18
- const result = await buildBillingPlans(ctx, found?.plugin ?? null, catalog, options.now);
17
+ const base = await loadBillingPlansBase(ctx, catalog, options.now);
18
+ const result = await resolveProviderPlans(ctx, options, catalog, base);
19
19
  const { consumerProtection } = options;
20
20
  if (!consumerProtection)
21
21
  return result;
@@ -32,6 +32,36 @@ export function createBillingPlansQuery(options, catalog) {
32
32
  },
33
33
  };
34
34
  }
35
+ // A tenant with a blocking subscription sees only the provider holding it
36
+ // (a second provider's prices would be a checkout it cannot start); otherwise
37
+ // every live provider is offered.
38
+ async function resolveProviderPlans(ctx, options, catalog, base) {
39
+ const candidates = listCatalogProviders(ctx, catalog);
40
+ if (base.blockingSubscription && base.subscriptionView) {
41
+ const holder = candidates.find((c) => c.name === base.subscriptionView?.providerName);
42
+ return toBillingPlansResult(catalog, base, await buildProviderPlanViews(ctx, holder?.plugin ?? null, catalog, base));
43
+ }
44
+ const offered = await filterOfferedProviders(ctx, candidates);
45
+ const first = offered[0] ?? candidates[0] ?? null;
46
+ const firstViews = await buildProviderPlanViews(ctx, first?.plugin ?? null, catalog, base);
47
+ const result = toBillingPlansResult(catalog, base, firstViews);
48
+ const providerTexts = options.consumerProtection?.providerTexts;
49
+ const hasNote = first !== null && providerTexts?.[first.name]?.checkoutNote !== undefined;
50
+ if (offered.length <= 1 && !(offered.length === 1 && hasNote))
51
+ return result;
52
+ const providers = await Promise.all(offered.map((provider, index) => providerView(ctx, catalog, base, provider, providerTexts, index === 0 ? firstViews : null)));
53
+ return { ...result, providers };
54
+ }
55
+ async function providerView(ctx, catalog, base, provider, providerTexts, known) {
56
+ const views = known ?? (await buildProviderPlanViews(ctx, provider.plugin, catalog, base));
57
+ const note = providerTexts?.[provider.name]?.checkoutNote;
58
+ return {
59
+ name: provider.name,
60
+ displayName: provider.plugin.displayName ?? provider.name,
61
+ ...(note !== undefined && { note }),
62
+ plans: views.plans,
63
+ };
64
+ }
35
65
  function legalLinksPerLocale(legalLinks) {
36
66
  return isLegalLinkSet(legalLinks) ? { de: legalLinks, en: legalLinks } : legalLinks;
37
67
  }
@@ -90,6 +90,7 @@ export function createCheckoutSessionHandler(options) {
90
90
  tier: mode === "subscription" ? (plugin.priceToTier?.[payload.priceId] ?? null) : null,
91
91
  priceId: payload.priceId,
92
92
  price,
93
+ providerName: payload.providerName,
93
94
  ...(orderItem && { orderItem }),
94
95
  });
95
96
  return {
@@ -0,0 +1,13 @@
1
+ import type { QueryHandlerDef } from "@cosmicdrift/kumiko-framework/engine";
2
+ import type { BillingPlanCatalog, PlanSwitchPreview } from "../types.ts";
3
+ export type PlanSwitchPreviewResult = {
4
+ readonly preview: PlanSwitchPreview;
5
+ readonly target: {
6
+ readonly tier: string;
7
+ readonly unitAmount: number;
8
+ readonly currency: string;
9
+ readonly interval: "day" | "week" | "month" | "year" | null;
10
+ readonly intervalCount: number | null;
11
+ };
12
+ };
13
+ export declare function createPlanSwitchPreviewQuery(catalog: BillingPlanCatalog): QueryHandlerDef;
@@ -0,0 +1,48 @@
1
+ // plan-switch-preview — what switching to a tier would cost right now, for
2
+ // providers that switch plans in-app (previewPlanSwitch + applyPlanSwitch).
3
+ // Only registered when `createBillingFoundationFeature` gets a `catalog`.
4
+ import { UnprocessableError } from "@cosmicdrift/kumiko-framework/errors";
5
+ import * as z from "zod";
6
+ import { isNonEmptyStringArray } from "../checkout-core.js";
7
+ import { purchaseRolesOf } from "../plan-catalog.js";
8
+ import { preparePlanSwitch } from "../plan-switch.js";
9
+ export function createPlanSwitchPreviewQuery(catalog) {
10
+ const plans = catalog.plans;
11
+ if (!isNonEmptyStringArray(plans)) {
12
+ throw new Error("plan-switch-preview: catalog.plans must not be empty");
13
+ }
14
+ const schema = z.object({ tier: z.enum(plans) }).strict();
15
+ return {
16
+ name: "plan-switch-preview",
17
+ description: "Previews what switching the existing subscription to another plan tier costs right now (amount due, tax, credit, effective date) plus the target plan's recurring price. Only for providers that switch plans in-app.",
18
+ schema,
19
+ access: { roles: purchaseRolesOf(catalog) },
20
+ handler: async (query, ctx) => {
21
+ // @cast-boundary engine-payload — dispatcher-zod-validated payload
22
+ const { tier } = query.payload;
23
+ const prepared = await preparePlanSwitch(ctx, catalog, tier, "plan-switch-preview");
24
+ const { plugin } = prepared.provider;
25
+ if (!plugin.previewPlanSwitch || !plugin.applyPlanSwitch) {
26
+ throw new UnprocessableError("plan_switch_not_supported", {
27
+ i18nKey: "billing-foundation.errors.planSwitchNotSupported",
28
+ message: `subscription-foundation: provider "${prepared.provider.name}" switches plans on a hosted page and has no in-app preview`,
29
+ });
30
+ }
31
+ const preview = await plugin.previewPlanSwitch(ctx, {
32
+ providerSubscriptionId: prepared.subscription.providerSubscriptionId,
33
+ targetPriceId: prepared.target.priceId,
34
+ });
35
+ const { price } = prepared.target;
36
+ return {
37
+ preview,
38
+ target: {
39
+ tier,
40
+ unitAmount: price.unitAmount ?? 0,
41
+ currency: price.currency,
42
+ interval: price.interval,
43
+ intervalCount: price.intervalCount,
44
+ },
45
+ };
46
+ },
47
+ };
48
+ }
@@ -27,6 +27,12 @@ export declare const processEventSchema: z.ZodObject<{
27
27
  consentId: z.ZodOptional<z.ZodString>;
28
28
  }, z.core.$strip>;
29
29
  export type ProcessEventPayload = z.infer<typeof processEventSchema>;
30
+ export declare function isLateStateEvent(storedEvents: readonly {
31
+ readonly payload: unknown;
32
+ readonly metadata: {
33
+ readonly headers?: Record<string, unknown>;
34
+ };
35
+ }[], payload: ProcessEventPayload): boolean;
30
36
  export declare function clampProviderEventAt(payload: ProcessEventPayload, now: Temporal.Instant): ProcessEventPayload;
31
37
  export declare function appendSubscriptionEvent(ctx: HandlerContext, tenantId: string, rawPayload: ProcessEventPayload, now?: Temporal.Instant): Promise<{
32
38
  readonly duplicate: boolean;
@@ -65,7 +65,7 @@ const STATE_EVENT_TYPES = new Set([
65
65
  SubscriptionEventTypes.updated,
66
66
  SubscriptionEventTypes.canceled,
67
67
  ]);
68
- function isLateStateEvent(storedEvents, payload) {
68
+ export function isLateStateEvent(storedEvents, payload) {
69
69
  if (payload.providerEventAtIso === undefined || !STATE_EVENT_TYPES.has(payload.type)) {
70
70
  return false;
71
71
  }
@@ -79,7 +79,13 @@ function isLateStateEvent(storedEvents, payload) {
79
79
  // A stored value that does not parse can never prove a newer event; skip it instead of
80
80
  // failing every later delivery of this tenant's stream.
81
81
  try {
82
- return Temporal.Instant.compare(Temporal.Instant.from(storedAt), incoming) > 0;
82
+ const order = Temporal.Instant.compare(Temporal.Instant.from(storedAt), incoming);
83
+ if (order !== 0)
84
+ return order > 0;
85
+ // Provider timestamps have second resolution: on a tie a stored cancellation wins over
86
+ // a non-terminal state, so a reordered same-second `updated` cannot revive a canceled one.
87
+ return (propertyOf(stored.payload, "status") === SubscriptionStatuses.canceled &&
88
+ payload.status !== SubscriptionStatuses.canceled);
83
89
  }
84
90
  catch {
85
91
  return false;
@@ -2,30 +2,56 @@
2
2
  // the catalog while the tenant has no non-terminal subscription. Resolves
3
3
  // the tier's live price server-side and opens a hosted checkout for it.
4
4
  // Only registered when `createBillingFoundationFeature` gets a `catalog`.
5
- import { UnprocessableError } from "@cosmicdrift/kumiko-framework/errors";
5
+ import { FeatureDisabledError, UnprocessableError } from "@cosmicdrift/kumiko-framework/errors";
6
6
  import * as z from "zod";
7
- import { assertBillingEnabled, assertNoActiveSubscription, isNonEmptyStringArray, joinBaseUrl, openCheckout, resolveCatalogProvider, } from "../checkout-core.js";
7
+ import { assertBillingEnabled, assertNoActiveSubscription, isNonEmptyStringArray, joinBaseUrl, listOfferedCatalogProviders, openCheckout, } from "../checkout-core.js";
8
8
  import { consentCheckoutFields, consentPayloadSchema, prepareConsent, recordConsent, } from "../consumer-protection/consent-gate.js";
9
9
  import { purchaseRolesOf, resolvePlanPrices } from "../plan-catalog.js";
10
+ import { BILLING_FOUNDATION_FEATURE } from "../web/constants.js";
11
+ /** The provider this checkout goes to: the named one if it is live, the only
12
+ * live one if the buyer had no choice, otherwise a client error. */
13
+ async function pickCheckoutProvider(ctx, catalog, requestedName) {
14
+ const offered = await listOfferedCatalogProviders(ctx, catalog);
15
+ if (requestedName !== undefined) {
16
+ const chosen = offered.find((provider) => provider.name === requestedName);
17
+ if (!chosen) {
18
+ throw new UnprocessableError("provider_not_offered", {
19
+ i18nKey: "billing-foundation.errors.providerNotOffered",
20
+ message: `subscription-foundation: provider "${requestedName}" is not offered by this catalog right now`,
21
+ });
22
+ }
23
+ return chosen;
24
+ }
25
+ const [only, second] = offered;
26
+ if (!only)
27
+ throw new FeatureDisabledError(BILLING_FOUNDATION_FEATURE, "start-plan-checkout");
28
+ if (second) {
29
+ throw new UnprocessableError("provider_required", {
30
+ i18nKey: "billing-foundation.errors.providerRequired",
31
+ message: "subscription-foundation: several providers are offered, name one as providerName",
32
+ });
33
+ }
34
+ return only;
35
+ }
10
36
  export function createStartPlanCheckoutHandler(options, catalog) {
11
37
  const plans = catalog.plans;
12
38
  if (!isNonEmptyStringArray(plans)) {
13
39
  throw new Error("start-plan-checkout: catalog.plans must not be empty");
14
40
  }
15
41
  const consumerProtection = options.consumerProtection;
16
- const tierSchema = z.object({ tier: z.enum(plans) });
42
+ const tierSchema = z.object({ tier: z.enum(plans), providerName: z.string().min(1).optional() });
17
43
  const schema = (consumerProtection
18
44
  ? tierSchema.extend({ consent: consentPayloadSchema.optional() })
19
45
  : tierSchema).strict();
20
46
  return {
21
47
  name: "start-plan-checkout",
22
- description: "Starts a hosted checkout for a plan tier when the tenant has no active subscription; the server picks price and redirect URLs.",
48
+ description: "Starts a hosted checkout for a plan tier when the tenant has no active subscription; the server picks price and redirect URLs. Name the provider with providerName when the catalog offers several.",
23
49
  schema,
24
50
  access: { roles: purchaseRolesOf(catalog) },
25
51
  handler: async (event, ctx) => {
26
52
  // @cast-boundary engine-payload — dispatcher-zod-validated payload
27
53
  const payload = event.payload;
28
- const { name: providerName, plugin } = resolveCatalogProvider(ctx, catalog, "start-plan-checkout");
54
+ const { name: providerName, plugin } = await pickCheckoutProvider(ctx, catalog, payload.providerName);
29
55
  await assertBillingEnabled(ctx, plugin, "start-plan-checkout");
30
56
  const existing = await assertNoActiveSubscription(ctx, options.now());
31
57
  const prices = await resolvePlanPrices(ctx, plugin, catalog);
@@ -61,6 +87,7 @@ export function createStartPlanCheckoutHandler(options, catalog) {
61
87
  tier: payload.tier,
62
88
  priceId: resolved.priceId,
63
89
  price: resolved.price,
90
+ providerName,
64
91
  });
65
92
  }
66
93
  return { isSuccess: true, data: { url: result.url } };
@@ -1,3 +1,3 @@
1
1
  import type { WriteHandlerDef } from "@cosmicdrift/kumiko-framework/engine";
2
- import type { BillingFoundationOptions, BillingPlanCatalog } from "../types.ts";
3
- export declare function createSwitchPlanHandler(options: BillingFoundationOptions, catalog: BillingPlanCatalog): WriteHandlerDef;
2
+ import type { BillingPlanCatalog, ResolvedBillingFoundationOptions } from "../types.ts";
3
+ export declare function createSwitchPlanHandler(options: ResolvedBillingFoundationOptions, catalog: BillingPlanCatalog): WriteHandlerDef;
@@ -1,83 +1,75 @@
1
1
  // switch-plan — a tenant-admin/purchase-role switches an existing,
2
- // non-terminal subscription to a different plan tier via the provider's
3
- // own confirmation page. Only registered when `createBillingFoundationFeature`
4
- // gets a `catalog`.
5
- import { ConflictError, UnprocessableError } from "@cosmicdrift/kumiko-framework/errors";
2
+ // non-terminal subscription to a different plan tier. A provider with a hosted
3
+ // switch session answers `{ url }`; a provider that switches in-app (preview +
4
+ // apply) applies the switch right here and answers `{ applied: true }`.
5
+ // Only registered when `createBillingFoundationFeature` gets a `catalog`.
6
+ import { InternalError } from "@cosmicdrift/kumiko-framework/errors";
6
7
  import * as z from "zod";
7
- import { assertBillingEnabled, assertRedirectOrigins, isNonEmptyStringArray, joinBaseUrl, resolveCatalogProvider, } from "../checkout-core.js";
8
- import { getSubscriptionForTenant } from "../get-subscription-for-tenant.js";
9
- import { purchaseRolesOf, resolvePlanPrices } from "../plan-catalog.js";
10
- import { isSwitchableSubscriptionStatus } from "../web/constants.js";
8
+ import { assertRedirectOrigins, isNonEmptyStringArray, joinBaseUrl } from "../checkout-core.js";
9
+ import { consentPayloadSchema, prepareConsent, recordConsent, } from "../consumer-protection/consent-gate.js";
10
+ import { purchaseRolesOf } from "../plan-catalog.js";
11
+ import { preparePlanSwitch } from "../plan-switch.js";
11
12
  export function createSwitchPlanHandler(options, catalog) {
12
13
  const plans = catalog.plans;
13
14
  if (!isNonEmptyStringArray(plans)) {
14
15
  throw new Error("switch-plan: catalog.plans must not be empty");
15
16
  }
16
- const schema = z.object({ tier: z.enum(plans) }).strict();
17
+ const consumerProtection = options.consumerProtection;
18
+ const tierSchema = z.object({ tier: z.enum(plans) });
19
+ const schema = (consumerProtection
20
+ ? tierSchema.extend({ consent: consentPayloadSchema.optional() })
21
+ : tierSchema).strict();
17
22
  return {
18
23
  name: "switch-plan",
19
- description: "Opens the provider's confirmation page for switching the existing subscription to another plan tier.",
24
+ description: "Switches the existing subscription to another plan tier: opens the provider's confirmation page (answers { url }), or applies the switch in-app for providers that preview and apply themselves (answers { applied: true }; send consent when consumer protection is configured).",
20
25
  schema,
21
26
  access: { roles: purchaseRolesOf(catalog) },
22
27
  handler: async (event, ctx) => {
23
28
  // @cast-boundary engine-payload — dispatcher-zod-validated payload
24
29
  const payload = event.payload;
25
- const { name: catalogProviderName, plugin } = resolveCatalogProvider(ctx, catalog, "switch-plan");
26
- await assertBillingEnabled(ctx, plugin, "switch-plan");
27
- const sub = await getSubscriptionForTenant(ctx, event.user.tenantId);
28
- if (!sub || !isSwitchableSubscriptionStatus(sub.status)) {
29
- throw new ConflictError({
30
- i18nKey: "billing-foundation.errors.noActiveSubscription",
31
- message: "tenant has no switchable subscription; use billing-foundation:write:start-plan-checkout to start one",
30
+ const prepared = await preparePlanSwitch(ctx, catalog, payload.tier, "switch-plan");
31
+ const { plugin } = prepared.provider;
32
+ if (plugin.createPlanSwitchSession) {
33
+ const baseUrl = options.baseUrl ?? "";
34
+ const returnUrl = joinBaseUrl(baseUrl, catalog.returnPath ?? catalog.successPath);
35
+ assertRedirectOrigins([returnUrl], options.baseUrl);
36
+ const result = await plugin.createPlanSwitchSession(ctx, {
37
+ providerSubscriptionId: prepared.subscription.providerSubscriptionId,
38
+ targetPriceId: prepared.target.priceId,
39
+ allowedPriceIds: prepared.allowedPriceIds,
40
+ returnUrl,
32
41
  });
42
+ return { isSuccess: true, data: { url: result.url } };
33
43
  }
34
- if (sub.cancelAt !== null) {
35
- throw new ConflictError({
36
- i18nKey: "billing-foundation.errors.cancellationScheduled",
37
- message: "subscription has a scheduled cancellation; reactivate it via billing-foundation:write:create-portal-session before switching plans",
38
- });
39
- }
40
- if (payload.tier === sub.tier) {
41
- throw new ConflictError({
42
- i18nKey: "billing-foundation.errors.alreadyOnPlan",
43
- message: `tenant is already on plan "${payload.tier}"`,
44
- });
45
- }
46
- // providerSubscriptionId only exists at the subscription's own provider; after a
47
- // provider migration the catalog provider can differ, which is not a plan switch.
48
- if (sub.providerName !== catalogProviderName) {
49
- throw new ConflictError({
50
- i18nKey: "billing-foundation.errors.providerMismatch",
51
- message: `tenant's active subscription is on provider "${sub.providerName}", the catalog resolves provider "${catalogProviderName}" — switch-plan cannot switch across providers`,
52
- });
53
- }
54
- if (!plugin.createPlanSwitchSession) {
55
- throw new UnprocessableError("plan_switch_not_supported", {
56
- i18nKey: "billing-foundation.errors.planSwitchNotSupported",
57
- message: `subscription-foundation: provider "${sub.providerName}" has no createPlanSwitchSession-method`,
58
- });
59
- }
60
- const prices = await resolvePlanPrices(ctx, plugin, catalog);
61
- const target = prices.get(payload.tier);
62
- if (!target) {
63
- throw new UnprocessableError("price_unavailable", {
64
- i18nKey: "billing-foundation.errors.priceUnavailable",
65
- message: `subscription-foundation: no live price resolved for tier "${payload.tier}"`,
66
- });
67
- }
68
- const allowedPriceIds = [...prices.values()]
69
- .filter((p) => p !== null)
70
- .map((p) => p.priceId);
71
- const baseUrl = options.baseUrl ?? "";
72
- const returnUrl = joinBaseUrl(baseUrl, catalog.returnPath ?? catalog.successPath);
73
- assertRedirectOrigins([returnUrl], options.baseUrl);
74
- const result = await plugin.createPlanSwitchSession(ctx, {
75
- providerSubscriptionId: sub.providerSubscriptionId,
76
- targetPriceId: target.priceId,
77
- allowedPriceIds,
78
- returnUrl,
79
- });
80
- return { isSuccess: true, data: { url: result.url } };
44
+ return applyInApp(prepared, payload, ctx, options);
81
45
  },
82
46
  };
83
47
  }
48
+ // Consent is recorded before the provider call: the apply carries the consentId
49
+ // as provider metadata, and a failing apply rolls the whole handler back.
50
+ async function applyInApp(prepared, payload, ctx, options) {
51
+ const { plugin, name: providerName } = prepared.provider;
52
+ if (!plugin.applyPlanSwitch) {
53
+ throw new InternalError({
54
+ message: `billing-foundation: provider "${providerName}" has neither createPlanSwitchSession nor applyPlanSwitch`,
55
+ });
56
+ }
57
+ const consent = options.consumerProtection
58
+ ? await prepareConsent(ctx, options.consumerProtection, payload.consent, "subscription")
59
+ : undefined;
60
+ if (consent) {
61
+ await recordConsent(ctx, consent, {
62
+ tier: payload.tier,
63
+ priceId: prepared.target.priceId,
64
+ price: prepared.target.price,
65
+ providerName,
66
+ });
67
+ }
68
+ await plugin.applyPlanSwitch(ctx, {
69
+ providerSubscriptionId: prepared.subscription.providerSubscriptionId,
70
+ targetPriceId: prepared.target.priceId,
71
+ tenantId: ctx.user.tenantId,
72
+ ...(consent && { consentId: consent.consentId }),
73
+ });
74
+ return { isSuccess: true, data: { applied: true } };
75
+ }
@@ -48,6 +48,16 @@ function syncProviderEventId(snapshot, lastChangedAt) {
48
48
  ].join("|");
49
49
  return `sync:${createHash("sha256").update(hashInput).digest("hex")}`;
50
50
  }
51
+ // The retrieval time stands in for the provider's event time, so a webhook emitted before
52
+ // this snapshot cannot roll the synced state back later. Provider webhook times are
53
+ // whole-second and come from the provider's clock, so the stamp is floored and shifted back:
54
+ // a genuine webhook right after the sync must not look older than the snapshot.
55
+ const SYNC_SNAPSHOT_EVENT_TIME_MARGIN_SECONDS = 5;
56
+ function snapshotEventTime() {
57
+ return Temporal.Now.instant()
58
+ .round({ smallestUnit: "second", roundingMode: "floor" })
59
+ .subtract({ seconds: SYNC_SNAPSHOT_EVENT_TIME_MARGIN_SECONDS });
60
+ }
51
61
  export const syncSubscriptionHandler = {
52
62
  name: "sync-subscription",
53
63
  agent: { expose: false },
@@ -113,10 +123,11 @@ export const syncSubscriptionHandler = {
113
123
  tier: snapshot.tier,
114
124
  currentPeriodEndIso: snapshot.currentPeriodEnd,
115
125
  cancelAtIso: snapshot.cancelAt,
126
+ providerEventAtIso: snapshotEventTime().toString(),
116
127
  });
117
128
  return {
118
129
  isSuccess: true,
119
- data: (appendResult.duplicate
130
+ data: (appendResult.duplicate || appendResult.stale
120
131
  ? { synced: false, reason: "unchanged" }
121
132
  : { synced: true }),
122
133
  };
@@ -20,6 +20,20 @@ export const BILLING_FOUNDATION_I18N = {
20
20
  "billing-foundation.plans.everyInterval.year": { en: "every {count} years" },
21
21
  "billing-foundation.plans.choose": { en: "Choose {plan}" },
22
22
  "billing-foundation.plans.switch": { en: "Switch to {plan}" },
23
+ "billing-foundation.plans.planSwitchRequested": {
24
+ en: "Plan switch requested. It becomes active once the payment is confirmed.",
25
+ },
26
+ "billing-foundation.planSwitch.title": { en: "Confirm plan switch" },
27
+ "billing-foundation.planSwitch.summary": { en: "{from} to {to}" },
28
+ "billing-foundation.planSwitch.dueNow": { en: "Due now: {amount}" },
29
+ "billing-foundation.planSwitch.includesTax": { en: "including {tax} VAT" },
30
+ "billing-foundation.planSwitch.credit": { en: "Credit for the unused time: {amount}" },
31
+ "billing-foundation.planSwitch.recurring": { en: "New recurring price: {amount}" },
32
+ "billing-foundation.planSwitch.effective": { en: "Effective immediately" },
33
+ "billing-foundation.planSwitch.pendingNote": {
34
+ en: "The switch becomes active after payment confirmation.",
35
+ },
36
+ "billing-foundation.planSwitch.order": { en: "Switch with obligation to pay" },
23
37
  "billing-foundation.plans.manage": { en: "Manage subscription" },
24
38
  "billing-foundation.plans.reactivate": { en: "Reactivate subscription" },
25
39
  "billing-foundation.plans.cancelScheduled": {
@@ -65,6 +79,8 @@ export const BILLING_FOUNDATION_I18N = {
65
79
  "billing-foundation.consent.link.withdrawal": { en: "Withdrawal policy" },
66
80
  "billing-foundation.consent.link.privacy": { en: "Privacy policy" },
67
81
  "billing-foundation.consent.order": { en: "Order with obligation to pay" },
82
+ "billing-foundation.plans.priceFrom": { en: "from" },
83
+ "billing-foundation.consent.chooseProvider": { en: "Payment provider" },
68
84
  "billing-foundation.consent.back": { en: "Back" },
69
85
  "billing-foundation.cancel.open": { en: "Cancel contract here" },
70
86
  "billing-foundation.cancel.title": { en: "Cancel contract" },
@@ -125,6 +141,12 @@ export const BILLING_FOUNDATION_I18N = {
125
141
  "billing-foundation.errors.providerMismatch": {
126
142
  en: "This tenant's subscription is on a different provider than the plan catalog. Contact support to migrate.",
127
143
  },
144
+ "billing-foundation.errors.providerNotOffered": {
145
+ en: "This payment provider is not available right now.",
146
+ },
147
+ "billing-foundation.errors.providerRequired": {
148
+ en: "Choose a payment provider to continue.",
149
+ },
128
150
  "billing-foundation.errors.priceUnavailable": {
129
151
  en: "This plan's price is temporarily unavailable.",
130
152
  },
@@ -10,7 +10,7 @@ export { getSubscriptionForTenant, type SubscriptionView } from "./get-subscript
10
10
  export { paymentsProjectionTable, subscriptionsProjectionTable } from "./projection.ts";
11
11
  export { billingPlansPanel, createBillingPlansScreen } from "./screens.ts";
12
12
  export { createSubscriptionTierSync, effectiveTierFromSubscription, SUBSCRIPTION_WEBHOOK_PATH, type SubscriptionTierSyncDeps, type TierSyncResult, } from "./subscription-tier-sync.ts";
13
- export { type BillingFoundationOptions, type BillingPlanBenefit, type BillingPlanCatalog, type BillingPlanContactCard, type BillingPlanPrice, type BillingPlansResult, type BillingPlanView, type ConsumerProtectionOptions, KNOWN_RECURRING_INTERVALS, type LegalLinkSet, type PaymentEvent, type ProviderPrice, type ProviderSubscriptionSnapshot, type RecurringInterval, type SubscriptionEvent, type SubscriptionProviderPlugin, } from "./types.ts";
13
+ export { type BillingFoundationOptions, type BillingPlanBenefit, type BillingPlanCatalog, type BillingPlanContactCard, type BillingPlanPrice, type BillingPlansResult, type BillingPlanView, type BillingProviderView, type ConsumerProtectionOptions, KNOWN_RECURRING_INTERVALS, type LegalLinkSet, type PaymentEvent, type PlanSwitchPreview, type ProviderPrice, type ProviderSubscriptionSnapshot, type RecurringInterval, type SubscriptionEvent, type SubscriptionProviderPlugin, } from "./types.ts";
14
14
  export { BILLING_FOUNDATION_FEATURE, BILLING_PLANS_PANEL_COMPONENT, BILLING_PLANS_SCREEN_ID, type BillingEventKind, BillingEventKinds, type BillingPlanAction, BillingPlanActions, DEFAULT_PURCHASE_ROLES, isSwitchableSubscriptionStatus, isTerminalSubscriptionStatus, parseProviderConsentId, SUBSCRIPTION_PROVIDER_EXTENSION, type SubscriptionCancelTiming, SubscriptionCancelTimings, type SubscriptionEventType, SubscriptionEventTypes, SubscriptionFoundationHandlers, SubscriptionFoundationQueries, type SubscriptionStatus, SubscriptionStatuses, } from "./web/constants.ts";
15
15
  export { CONSENT_LOCALES, type ConsentLocale, resolveConsentLocale, } from "./web/consumer-protection/consent-locale.ts";
16
16
  export { createSubscriptionWebhookRoute, type SubscriptionWebhookRouteOptions, } from "./webhook-handler.ts";
@@ -1,12 +1,13 @@
1
1
  import type { HandlerContext } from "@cosmicdrift/kumiko-framework/engine";
2
- import type { BillingPlanCatalog, BillingPlansResult, ProviderPrice, SubscriptionProviderPlugin } from "./types.ts";
2
+ import { getSubscriptionForTenant } from "./get-subscription-for-tenant.ts";
3
+ import { type BillingPlanCatalog, type BillingPlansResult, type BillingPlanView, type ProviderPrice, type SubscriptionProviderPlugin } from "./types.ts";
3
4
  /** `catalog?.purchaseRoles ?? DEFAULT_PURCHASE_ROLES` — the one place this
4
5
  * fallback is spelled out; plan-catalog.ts and the start-plan-checkout/
5
6
  * switch-plan/create-portal-session handlers all call this instead of
6
7
  * repeating the literal. Accepts `undefined` so create-portal-session
7
8
  * (mounted with or without a catalog) doesn't need its own fallback. */
8
9
  export declare function purchaseRolesOf(catalog: Pick<BillingPlanCatalog, "purchaseRoles"> | undefined): readonly string[];
9
- type ResolvedPlanPrice = {
10
+ export type ResolvedPlanPrice = {
10
11
  readonly priceId: string;
11
12
  readonly price: ProviderPrice;
12
13
  } | null;
@@ -15,9 +16,24 @@ type ResolvedPlanPrice = {
15
16
  * one the plan means — and resolves to null with a warning instead of an
16
17
  * arbitrary pick. */
17
18
  export declare function resolvePlanPrices(ctx: HandlerContext, plugin: SubscriptionProviderPlugin, catalog: BillingPlanCatalog): Promise<ReadonlyMap<string, ResolvedPlanPrice>>;
19
+ /** Tenant-level state every provider's plan list is measured against; loaded
20
+ * once so a multi-provider result does not repeat the reads per provider. */
21
+ export type BillingPlansBase = {
22
+ readonly currentTierValue: string;
23
+ readonly subscriptionView: Awaited<ReturnType<typeof getSubscriptionForTenant>>;
24
+ readonly subscription: BillingPlansResult["subscription"];
25
+ readonly blockingSubscription: boolean;
26
+ readonly canPurchase: boolean;
27
+ };
28
+ export declare function loadBillingPlansBase(ctx: HandlerContext, catalog: BillingPlanCatalog, now: () => Temporal.Instant): Promise<BillingPlansBase>;
29
+ export type ProviderPlanViews = {
30
+ readonly enabled: boolean;
31
+ readonly inAppSwitch: boolean;
32
+ readonly plans: readonly BillingPlanView[];
33
+ };
18
34
  /** `plugin === null` — no provider is registered/resolvable for this
19
- * catalog (see checkout-core's `findCatalogProvider`) — collapses onto the
35
+ * catalog (see checkout-core's `listCatalogProviders`) — collapses onto the
20
36
  * same "enabled: false" result a disabled provider produces, rather than
21
37
  * a separate error shape the panel would need to special-case. */
22
- export declare function buildBillingPlans(ctx: HandlerContext, plugin: SubscriptionProviderPlugin | null, catalog: BillingPlanCatalog, now: () => Temporal.Instant): Promise<BillingPlansResult>;
23
- export {};
38
+ export declare function buildProviderPlanViews(ctx: HandlerContext, plugin: SubscriptionProviderPlugin | null, catalog: BillingPlanCatalog, base: BillingPlansBase): Promise<ProviderPlanViews>;
39
+ export declare function toBillingPlansResult(catalog: BillingPlanCatalog, base: BillingPlansBase, views: ProviderPlanViews): BillingPlansResult;
@@ -4,6 +4,7 @@
4
4
  // Internal — not re-exported from index.ts.
5
5
  import { isPluginBillingEnabled } from "./checkout-core.js";
6
6
  import { getSubscriptionForTenant } from "./get-subscription-for-tenant.js";
7
+ import { canSwitchPlans, canSwitchPlansInApp, } from "./types.js";
7
8
  import { BillingPlanActions, DEFAULT_PURCHASE_ROLES, isSubscriptionBlockingCheckout, isSwitchableSubscriptionStatus, SubscriptionStatuses, } from "./web/constants.js";
8
9
  function userHasAnyRole(userRoles, allowedRoles) {
9
10
  return allowedRoles.some((role) => userRoles.includes(role));
@@ -80,7 +81,7 @@ function canSwitchToTier(tier, subscription, plugin) {
80
81
  return (isSwitchableSubscriptionStatus(subscription.status) &&
81
82
  tier !== subscription.tier &&
82
83
  subscription.cancelAt === null &&
83
- plugin?.createPlanSwitchSession !== undefined);
84
+ canSwitchPlans(plugin));
84
85
  }
85
86
  /** One plan-row's action — pulled out of `buildBillingPlans`' map callback so
86
87
  * that function's own complexity stays under the guard's budget. paymentPending
@@ -105,29 +106,32 @@ function resolvePlanAction(tier, isCurrent, price, enabled, canPurchase, subscri
105
106
  ? BillingPlanActions.switch
106
107
  : BillingPlanActions.unavailable;
107
108
  }
108
- /** `plugin === null` — no provider is registered/resolvable for this
109
- * catalog (see checkout-core's `findCatalogProvider`) — collapses onto the
110
- * same "enabled: false" result a disabled provider produces, rather than
111
- * a separate error shape the panel would need to special-case. */
112
- export async function buildBillingPlans(ctx, plugin, catalog, now) {
109
+ export async function loadBillingPlansBase(ctx, catalog, now) {
113
110
  const currentTierValue = await catalog.resolveCurrentTier(ctx.db, ctx.user.tenantId);
114
- const enabled = plugin !== null && (await isPluginBillingEnabled(ctx, plugin));
115
- const resolvedPrices = enabled && plugin
116
- ? await resolvePlanPrices(ctx, plugin, catalog)
117
- : new Map(catalog.plans.map((tier) => [tier, null]));
118
111
  const subscriptionView = await getSubscriptionForTenant(ctx, ctx.user.tenantId);
119
- const nowInstant = now();
112
+ const blockingSubscription = subscriptionView !== null && isSubscriptionBlockingCheckout(subscriptionView, now());
120
113
  const subscription = subscriptionView
121
114
  ? {
122
115
  status: subscriptionView.status,
123
116
  tier: subscriptionView.tier,
124
- terminal: !isSubscriptionBlockingCheckout(subscriptionView, nowInstant),
117
+ terminal: !blockingSubscription,
125
118
  currentPeriodEnd: subscriptionView.currentPeriodEnd.toString(),
126
119
  cancelAt: subscriptionView.cancelAt?.toString() ?? null,
127
120
  }
128
121
  : null;
129
- const purchaseRoles = purchaseRolesOf(catalog);
130
- const canPurchase = userHasAnyRole(ctx.user.roles, purchaseRoles);
122
+ const canPurchase = userHasAnyRole(ctx.user.roles, purchaseRolesOf(catalog));
123
+ return { currentTierValue, subscriptionView, subscription, blockingSubscription, canPurchase };
124
+ }
125
+ /** `plugin === null` — no provider is registered/resolvable for this
126
+ * catalog (see checkout-core's `listCatalogProviders`) — collapses onto the
127
+ * same "enabled: false" result a disabled provider produces, rather than
128
+ * a separate error shape the panel would need to special-case. */
129
+ export async function buildProviderPlanViews(ctx, plugin, catalog, base) {
130
+ const { currentTierValue, subscription, canPurchase } = base;
131
+ const enabled = plugin !== null && (await isPluginBillingEnabled(ctx, plugin));
132
+ const resolvedPrices = enabled && plugin
133
+ ? await resolvePlanPrices(ctx, plugin, catalog)
134
+ : new Map(catalog.plans.map((tier) => [tier, null]));
131
135
  const plans = catalog.plans.map((tier) => {
132
136
  const isCurrent = tier === currentTierValue;
133
137
  const resolved = resolvedPrices.get(tier) ?? null;
@@ -149,8 +153,12 @@ export async function buildBillingPlans(ctx, plugin, catalog, now) {
149
153
  action,
150
154
  };
151
155
  });
156
+ return { enabled, inAppSwitch: plugin !== null && canSwitchPlansInApp(plugin), plans };
157
+ }
158
+ export function toBillingPlansResult(catalog, base, views) {
159
+ const { currentTierValue, subscription, canPurchase } = base;
152
160
  return {
153
- enabled,
161
+ enabled: views.enabled,
154
162
  currentTier: {
155
163
  tier: currentTierValue,
156
164
  labelKey: catalog.tierLabelKey(currentTierValue),
@@ -158,7 +166,8 @@ export async function buildBillingPlans(ctx, plugin, catalog, now) {
158
166
  },
159
167
  subscription,
160
168
  canPurchase,
161
- plans,
169
+ plans: views.plans,
170
+ ...(views.inAppSwitch && { inAppPlanSwitch: true }),
162
171
  ...(catalog.contact !== undefined && { contact: catalog.contact }),
163
172
  };
164
173
  }
@@ -0,0 +1,12 @@
1
+ import type { HandlerContext } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { type ResolvedProvider } from "./checkout-core.ts";
3
+ import { type SubscriptionView } from "./get-subscription-for-tenant.ts";
4
+ import { type ResolvedPlanPrice } from "./plan-catalog.ts";
5
+ import { type BillingPlanCatalog } from "./types.ts";
6
+ export type PreparedPlanSwitch = {
7
+ readonly provider: ResolvedProvider;
8
+ readonly subscription: SubscriptionView;
9
+ readonly target: NonNullable<ResolvedPlanPrice>;
10
+ readonly allowedPriceIds: readonly string[];
11
+ };
12
+ export declare function preparePlanSwitch(ctx: HandlerContext, catalog: BillingPlanCatalog, tier: string, handlerName: string): Promise<PreparedPlanSwitch>;