@zonastery/bursar 2.0.1 → 2.0.3

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 (285) hide show
  1. package/README.md +22 -14
  2. package/dist/billing/auto-recharge-service.d.ts +1 -1
  3. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-service.js +9 -6
  5. package/dist/billing/auto-recharge-service.js.map +1 -1
  6. package/dist/billing/billing-store.d.ts +4 -1
  7. package/dist/billing/billing-store.d.ts.map +1 -1
  8. package/dist/billing/billing-store.js +2 -0
  9. package/dist/billing/billing-store.js.map +1 -1
  10. package/dist/billing/contracts.d.ts +2 -1
  11. package/dist/billing/contracts.d.ts.map +1 -1
  12. package/dist/billing/contracts.js.map +1 -1
  13. package/dist/billing/event-handlers.d.ts +2 -3
  14. package/dist/billing/event-handlers.d.ts.map +1 -1
  15. package/dist/billing/event-handlers.js +38 -49
  16. package/dist/billing/event-handlers.js.map +1 -1
  17. package/dist/billing/event-processor.d.ts.map +1 -1
  18. package/dist/billing/event-processor.js +22 -10
  19. package/dist/billing/event-processor.js.map +1 -1
  20. package/dist/billing/financial-event-handlers.d.ts +2 -2
  21. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  22. package/dist/billing/financial-event-handlers.js +7 -7
  23. package/dist/billing/financial-event-handlers.js.map +1 -1
  24. package/dist/billing/postgres/repositories/auto-recharge.js +1 -1
  25. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  26. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  27. package/dist/billing/postgres/repositories/event.js +33 -1
  28. package/dist/billing/postgres/repositories/event.js.map +1 -1
  29. package/dist/billing/postgres/repositories/offer.d.ts +1 -1
  30. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  31. package/dist/billing/postgres/repositories/offer.js +1 -1
  32. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  33. package/dist/billing/postgres/repositories/topup.d.ts +1 -1
  34. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  35. package/dist/billing/postgres/repositories/topup.js +1 -1
  36. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  37. package/dist/billing/postgres/store.d.ts +6 -2
  38. package/dist/billing/postgres/store.d.ts.map +1 -1
  39. package/dist/billing/postgres/store.js +21 -6
  40. package/dist/billing/postgres/store.js.map +1 -1
  41. package/dist/billing/service-types.d.ts +2 -15
  42. package/dist/billing/service-types.d.ts.map +1 -1
  43. package/dist/billing/service-types.js.map +1 -1
  44. package/dist/billing/types/auto-recharge.d.ts +1 -1
  45. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  46. package/dist/billing/types/auto-recharge.js.map +1 -1
  47. package/dist/billing/types/catalog.d.ts +1 -1
  48. package/dist/billing/types/catalog.d.ts.map +1 -1
  49. package/dist/billing/types/catalog.js.map +1 -1
  50. package/dist/billing/types/documents.d.ts +1 -1
  51. package/dist/billing/types/documents.d.ts.map +1 -1
  52. package/dist/billing/types/documents.js.map +1 -1
  53. package/dist/billing/types/events.d.ts +11 -2
  54. package/dist/billing/types/events.d.ts.map +1 -1
  55. package/dist/billing/types/events.js +2 -2
  56. package/dist/billing/types/events.js.map +1 -1
  57. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  58. package/dist/billing/types/subscriptions.js.map +1 -1
  59. package/dist/breakdown.d.ts +1 -1
  60. package/dist/breakdown.d.ts.map +1 -1
  61. package/dist/breakdown.js +1 -1
  62. package/dist/breakdown.js.map +1 -1
  63. package/dist/bursar.d.ts +21 -11
  64. package/dist/bursar.d.ts.map +1 -1
  65. package/dist/bursar.js +40 -4
  66. package/dist/bursar.js.map +1 -1
  67. package/dist/catalog.d.ts.map +1 -1
  68. package/dist/catalog.js +1 -1
  69. package/dist/catalog.js.map +1 -1
  70. package/dist/commerce/index.d.ts +0 -1
  71. package/dist/commerce/index.d.ts.map +1 -1
  72. package/dist/commerce/index.js +0 -1
  73. package/dist/commerce/index.js.map +1 -1
  74. package/dist/commerce/service.d.ts.map +1 -1
  75. package/dist/commerce/service.js +154 -106
  76. package/dist/commerce/service.js.map +1 -1
  77. package/dist/commerce/types.d.ts +9 -5
  78. package/dist/commerce/types.d.ts.map +1 -1
  79. package/dist/commerce/types.js.map +1 -1
  80. package/dist/config/parse-credits.d.ts.map +1 -1
  81. package/dist/config/parse-credits.js +0 -6
  82. package/dist/config/parse-credits.js.map +1 -1
  83. package/dist/config/parse-utils.d.ts +1 -1
  84. package/dist/config/parse-utils.d.ts.map +1 -1
  85. package/dist/config/parse-utils.js +1 -1
  86. package/dist/config/parse-utils.js.map +1 -1
  87. package/dist/config/types.d.ts +1 -6
  88. package/dist/config/types.d.ts.map +1 -1
  89. package/dist/config/types.js.map +1 -1
  90. package/dist/config.d.ts.map +1 -1
  91. package/dist/config.js +8 -1
  92. package/dist/config.js.map +1 -1
  93. package/dist/credits/amount.d.ts +8 -0
  94. package/dist/credits/amount.d.ts.map +1 -0
  95. package/dist/credits/amount.js +32 -0
  96. package/dist/credits/amount.js.map +1 -0
  97. package/dist/credits/catalog-runtime.d.ts +5 -7
  98. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  99. package/dist/credits/catalog-runtime.js +4 -13
  100. package/dist/credits/catalog-runtime.js.map +1 -1
  101. package/dist/credits/lease-workflow.d.ts +2 -2
  102. package/dist/credits/lease-workflow.d.ts.map +1 -1
  103. package/dist/credits/lease-workflow.js +24 -21
  104. package/dist/credits/lease-workflow.js.map +1 -1
  105. package/dist/credits/low-balance-monitor.d.ts +1 -1
  106. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  107. package/dist/credits/low-balance-monitor.js +3 -4
  108. package/dist/credits/low-balance-monitor.js.map +1 -1
  109. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  110. package/dist/credits/postgres/repositories/balance.js +1 -1
  111. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  112. package/dist/credits/postgres/repositories/bucket.js +1 -1
  113. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  114. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  115. package/dist/credits/postgres/repositories/lease.js +4 -2
  116. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  117. package/dist/credits/postgres/repositories/team.d.ts +2 -1
  118. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  119. package/dist/credits/postgres/repositories/team.js +19 -5
  120. package/dist/credits/postgres/repositories/team.js.map +1 -1
  121. package/dist/credits/postgres/store.d.ts +18 -14
  122. package/dist/credits/postgres/store.d.ts.map +1 -1
  123. package/dist/credits/postgres/store.js +30 -18
  124. package/dist/credits/postgres/store.js.map +1 -1
  125. package/dist/credits/postgres/value-mappers.d.ts +1 -1
  126. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  127. package/dist/credits/postgres/value-mappers.js +1 -1
  128. package/dist/credits/postgres/value-mappers.js.map +1 -1
  129. package/dist/credits/service-errors.d.ts +1 -1
  130. package/dist/credits/service-errors.d.ts.map +1 -1
  131. package/dist/credits/service-errors.js +1 -1
  132. package/dist/credits/service-errors.js.map +1 -1
  133. package/dist/credits/service-types.d.ts +21 -16
  134. package/dist/credits/service-types.d.ts.map +1 -1
  135. package/dist/credits/service-types.js.map +1 -1
  136. package/dist/credits/service.d.ts +21 -17
  137. package/dist/credits/service.d.ts.map +1 -1
  138. package/dist/credits/service.js +81 -38
  139. package/dist/credits/service.js.map +1 -1
  140. package/dist/credits/store.d.ts +26 -23
  141. package/dist/credits/store.d.ts.map +1 -1
  142. package/dist/credits/store.js +4 -2
  143. package/dist/credits/store.js.map +1 -1
  144. package/dist/credits/types/account.d.ts +1 -1
  145. package/dist/credits/types/account.d.ts.map +1 -1
  146. package/dist/credits/types/account.js.map +1 -1
  147. package/dist/credits/types/grants.d.ts.map +1 -1
  148. package/dist/credits/types/grants.js.map +1 -1
  149. package/dist/credits/types/teams.d.ts +1 -0
  150. package/dist/credits/types/teams.d.ts.map +1 -1
  151. package/dist/credits/types/teams.js.map +1 -1
  152. package/dist/engine.js +1 -1
  153. package/dist/engine.js.map +1 -1
  154. package/dist/errors.d.ts +4 -0
  155. package/dist/errors.d.ts.map +1 -1
  156. package/dist/errors.js +34 -0
  157. package/dist/errors.js.map +1 -1
  158. package/dist/expr/ast.d.ts.map +1 -1
  159. package/dist/expr/ast.js.map +1 -1
  160. package/dist/expr/evaluator.d.ts +1 -1
  161. package/dist/expr/evaluator.d.ts.map +1 -1
  162. package/dist/expr/evaluator.js +1 -1
  163. package/dist/expr/evaluator.js.map +1 -1
  164. package/dist/expr/parser.d.ts +1 -0
  165. package/dist/expr/parser.d.ts.map +1 -1
  166. package/dist/expr/parser.js +15 -3
  167. package/dist/expr/parser.js.map +1 -1
  168. package/dist/expr.d.ts +1 -1
  169. package/dist/expr.d.ts.map +1 -1
  170. package/dist/expr.js +1 -1
  171. package/dist/expr.js.map +1 -1
  172. package/dist/generated/pricing-config.schema.json +31 -29
  173. package/dist/generated/pricing-config.types.d.ts +6 -18
  174. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  175. package/dist/generated/pricing-config.types.js.map +1 -1
  176. package/dist/index.d.ts +7 -3
  177. package/dist/index.d.ts.map +1 -1
  178. package/dist/index.js +2 -0
  179. package/dist/index.js.map +1 -1
  180. package/dist/load-config-file.d.ts +2 -3
  181. package/dist/load-config-file.d.ts.map +1 -1
  182. package/dist/load-config-file.js +14 -29
  183. package/dist/load-config-file.js.map +1 -1
  184. package/dist/metrics.d.ts +1 -1
  185. package/dist/metrics.d.ts.map +1 -1
  186. package/dist/metrics.js.map +1 -1
  187. package/dist/node.d.ts +6 -3
  188. package/dist/node.d.ts.map +1 -1
  189. package/dist/node.js +1 -0
  190. package/dist/node.js.map +1 -1
  191. package/dist/providers/_shared.d.ts +3 -3
  192. package/dist/providers/_shared.d.ts.map +1 -1
  193. package/dist/providers/_shared.js +11 -6
  194. package/dist/providers/_shared.js.map +1 -1
  195. package/dist/providers/dodo/client-contract.d.ts +8 -13
  196. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  197. package/dist/providers/dodo/client-contract.js.map +1 -1
  198. package/dist/providers/dodo/event-mapper.d.ts +1 -1
  199. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  200. package/dist/providers/dodo/event-mapper.js +23 -15
  201. package/dist/providers/dodo/event-mapper.js.map +1 -1
  202. package/dist/providers/dodo/provider.d.ts +4 -6
  203. package/dist/providers/dodo/provider.d.ts.map +1 -1
  204. package/dist/providers/dodo/provider.js +44 -82
  205. package/dist/providers/dodo/provider.js.map +1 -1
  206. package/dist/providers/dodo/webhook-bridge.d.ts +1 -2
  207. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
  208. package/dist/providers/dodo/webhook-bridge.js +0 -1
  209. package/dist/providers/dodo/webhook-bridge.js.map +1 -1
  210. package/dist/providers/environment.d.ts +6 -0
  211. package/dist/providers/environment.d.ts.map +1 -0
  212. package/dist/providers/environment.js +10 -0
  213. package/dist/providers/environment.js.map +1 -0
  214. package/dist/providers/index.d.ts +3 -7
  215. package/dist/providers/index.d.ts.map +1 -1
  216. package/dist/providers/index.js +1 -5
  217. package/dist/providers/index.js.map +1 -1
  218. package/dist/providers/mock/provider.d.ts +6 -8
  219. package/dist/providers/mock/provider.d.ts.map +1 -1
  220. package/dist/providers/mock/provider.js +18 -50
  221. package/dist/providers/mock/provider.js.map +1 -1
  222. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  223. package/dist/providers/stripe/event-mapper.js +82 -14
  224. package/dist/providers/stripe/event-mapper.js.map +1 -1
  225. package/dist/providers/stripe/provider.d.ts +3 -3
  226. package/dist/providers/stripe/provider.d.ts.map +1 -1
  227. package/dist/providers/stripe/provider.js +37 -24
  228. package/dist/providers/stripe/provider.js.map +1 -1
  229. package/dist/providers/types.d.ts +9 -20
  230. package/dist/providers/types.d.ts.map +1 -1
  231. package/dist/providers/types.js.map +1 -1
  232. package/dist/shared/diagnostics.d.ts +8 -0
  233. package/dist/shared/diagnostics.d.ts.map +1 -1
  234. package/dist/shared/diagnostics.js +49 -0
  235. package/dist/shared/diagnostics.js.map +1 -1
  236. package/dist/shared/idempotency.d.ts +9 -0
  237. package/dist/shared/idempotency.d.ts.map +1 -0
  238. package/dist/shared/idempotency.js +34 -0
  239. package/dist/shared/idempotency.js.map +1 -0
  240. package/dist/shared/postgres-client.d.ts +7 -0
  241. package/dist/shared/postgres-client.d.ts.map +1 -1
  242. package/dist/shared/postgres-client.js +21 -4
  243. package/dist/shared/postgres-client.js.map +1 -1
  244. package/dist/shared/postgres-errors.d.ts.map +1 -1
  245. package/dist/shared/postgres-errors.js.map +1 -1
  246. package/dist/storage/adapters/clickhouse.d.ts +9 -2
  247. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  248. package/dist/storage/adapters/clickhouse.js +142 -36
  249. package/dist/storage/adapters/clickhouse.js.map +1 -1
  250. package/dist/storage/adapters/s3.d.ts +44 -6
  251. package/dist/storage/adapters/s3.d.ts.map +1 -1
  252. package/dist/storage/adapters/s3.js +59 -21
  253. package/dist/storage/adapters/s3.js.map +1 -1
  254. package/dist/storage/diagnostics.d.ts +105 -0
  255. package/dist/storage/diagnostics.d.ts.map +1 -0
  256. package/dist/storage/diagnostics.js +227 -0
  257. package/dist/storage/diagnostics.js.map +1 -0
  258. package/dist/storage/maintenance.d.ts +88 -0
  259. package/dist/storage/maintenance.d.ts.map +1 -0
  260. package/dist/storage/maintenance.js +266 -0
  261. package/dist/storage/maintenance.js.map +1 -0
  262. package/dist/storage/outbox-worker.d.ts +20 -0
  263. package/dist/storage/outbox-worker.d.ts.map +1 -1
  264. package/dist/storage/outbox-worker.js +172 -42
  265. package/dist/storage/outbox-worker.js.map +1 -1
  266. package/dist/storage/ports.d.ts +43 -1
  267. package/dist/storage/ports.d.ts.map +1 -1
  268. package/dist/storage/ports.js.map +1 -1
  269. package/dist/storage/postgres-repository.d.ts +7 -2
  270. package/dist/storage/postgres-repository.d.ts.map +1 -1
  271. package/dist/storage/postgres-repository.js +155 -54
  272. package/dist/storage/postgres-repository.js.map +1 -1
  273. package/dist/storage/runtime.d.ts +30 -9
  274. package/dist/storage/runtime.d.ts.map +1 -1
  275. package/dist/storage/runtime.js +268 -37
  276. package/dist/storage/runtime.js.map +1 -1
  277. package/dist/telemetry/index.d.ts +37 -0
  278. package/dist/telemetry/index.d.ts.map +1 -0
  279. package/dist/telemetry/index.js +115 -0
  280. package/dist/telemetry/index.js.map +1 -0
  281. package/dist/telemetry/opentelemetry.d.ts +25 -0
  282. package/dist/telemetry/opentelemetry.d.ts.map +1 -0
  283. package/dist/telemetry/opentelemetry.js +74 -0
  284. package/dist/telemetry/opentelemetry.js.map +1 -0
  285. package/package.json +62 -36
package/dist/catalog.js CHANGED
@@ -79,7 +79,7 @@ export function projectPublicCatalog(config) {
79
79
  .sort((a, b) => a.rank - b.rank || a.key.localeCompare(b.key));
80
80
  return {
81
81
  version: 1,
82
- defaultPlan: config.catalog.defaultPlan ?? plans[0]?.key ?? null,
82
+ defaultPlan: config.catalog.defaultPlan ?? null,
83
83
  creditDisplay: config.credits.display
84
84
  ? {
85
85
  currency: config.credits.display.currency,
@@ -1 +1 @@
1
- {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../src/catalog.ts"],"names":[],"mappings":"AA4DA,SAAS,YAAY,CAAC,MAAc;IAClC,IAAI,MAAM,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;QAC/B,OAAO;YACL,IAAI,EAAE,MAAM,CAAC,IAAI;YACjB,IAAI,EAAE,MAAM,CAAC,IAAI;YACjB,KAAK,EAAE,MAAM,CAAC,KAAK;YACnB,QAAQ,EAAE,MAAM,CAAC,QAAQ;SAC1B,CAAC;IACJ,CAAC;IACD,IAAI,MAAM,CAAC,IAAI,KAAK,iBAAiB,EAAE,CAAC;QACtC,OAAO;YACL,IAAI,EAAE,MAAM,CAAC,IAAI;YACjB,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,IAAI;YAC1B,KAAK,EAAE,MAAM,CAAC,QAAQ,CA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AAC,CAAC,GAAG,CAAC,CAAC;KAC3E,CAAC;AACJ,CAAC","sourcesContent":["import type { CommerceOffer, FeatureValue, ParsedBursarConfig, Window } from \"./config/types.js\";\n\nexport interface PublicCatalogWindow {\n type: Window[\"type\"];\n unit: string;\n count: number;\n timezone?: string;\n}\n\nexport interface PublicCatalogOffer {\n key: string;\n type: CommerceOffer[\"type\"];\n displayName: string;\n description?: string;\n sortOrder: number;\n price: {\n amountMinor: number;\n currency: string;\n taxBehavior: \"inclusive\" | \"exclusive\" | \"unspecified\";\n };\n billingInterval?: { unit: string; count: number };\n creditsPerUnit?: string;\n quantity?: { minimum: number; maximum: number; default: number };\n}\n\nexport interface PublicCatalogPlan {\n key: string;\n displayName: string;\n description?: string;\n rank: number;\n features: Record<string, FeatureValue>;\n allowance?: {\n amount: string;\n priority: number;\n window: PublicCatalogWindow;\n };\n quotas: Record<\n string,\n {\n operation: string;\n measure: string;\n limit: string;\n window: PublicCatalogWindow;\n enforcement: \"block\" | \"allow\";\n }\n >;\n offers: PublicCatalogOffer[];\n}\n\nexport interface PublicCatalog {\n version: 1;\n defaultPlan: string | null;\n creditDisplay: {\n currency: string;\n unitsPerMajor: string;\n } | null;\n plans: PublicCatalogPlan[];\n topups: PublicCatalogOffer[];\n}\n\nfunction publicWindow(window: Window): PublicCatalogWindow {\n if (window.type === \"calendar\") {\n return {\n type: window.type,\n unit: window.unit,\n count: window.count,\n timezone: window.timezone,\n };\n }\n if (window.type === \"plan_assignment\") {\n return {\n type: window.type,\n unit: window.interval.unit,\n count: window.interval.count,\n timezone: window.timezone,\n };\n }\n return {\n type: window.type,\n unit: window.duration.unit,\n count: window.duration.count,\n };\n}\n\nfunction publicOffer(key: string, offer: CommerceOffer): PublicCatalogOffer {\n return {\n key,\n type: offer.type,\n displayName: offer.displayName,\n ...(offer.description ? { description: offer.description } : {}),\n sortOrder: offer.sortOrder,\n price: { ...offer.price },\n ...(offer.type === \"subscription\"\n ? {\n billingInterval: {\n unit: offer.billingInterval.unit,\n count: offer.billingInterval.count,\n },\n }\n : {\n creditsPerUnit: offer.creditsPerUnit.toString(),\n quantity: { ...offer.quantity },\n }),\n };\n}\n\n/** Produce a provider-secret-free, JSON-safe catalog for product surfaces. */\nexport function projectPublicCatalog(config: ParsedBursarConfig): PublicCatalog {\n const offers = Object.entries(config.commerce.offers);\n const plans = Object.entries(config.plans)\n .map(\n ([key, plan]): PublicCatalogPlan => ({\n key,\n displayName: plan.displayName,\n ...(plan.description ? { description: plan.description } : {}),\n rank: plan.rank,\n features: { ...plan.features },\n ...(plan.creditAllowance\n ? {\n allowance: {\n amount: plan.creditAllowance.amount.toString(),\n priority: plan.creditAllowance.priority,\n window: publicWindow(plan.creditAllowance.window),\n },\n }\n : {}),\n quotas: Object.fromEntries(\n Object.entries(plan.quotas).map(([quotaKey, quota]) => [\n quotaKey,\n {\n operation: quota.operation,\n measure: quota.measure,\n limit: quota.limit.toString(),\n window: publicWindow(quota.window),\n enforcement: quota.enforcement,\n },\n ]),\n ),\n offers: offers\n .filter(\n (entry): entry is [string, Extract<CommerceOffer, { type: \"subscription\" }>] =>\n entry[1].type === \"subscription\" && entry[1].plan === key,\n )\n .map(([offerKey, offer]) => publicOffer(offerKey, offer))\n .sort((a, b) => a.sortOrder - b.sortOrder || a.key.localeCompare(b.key)),\n }),\n )\n .sort((a, b) => a.rank - b.rank || a.key.localeCompare(b.key));\n\n return {\n version: 1,\n defaultPlan: config.catalog.defaultPlan ?? plans[0]?.key ?? null,\n creditDisplay: config.credits.display\n ? {\n currency: config.credits.display.currency,\n unitsPerMajor: config.credits.display.unitsPerMajor.toString(),\n }\n : null,\n plans,\n topups: offers\n .filter(\n (entry): entry is [string, Extract<CommerceOffer, { type: \"topup\" }>] =>\n entry[1].type === \"topup\",\n )\n .map(([key, offer]) => publicOffer(key, offer))\n .sort((a, b) => a.sortOrder - b.sortOrder || a.key.localeCompare(b.key)),\n };\n}\n"]}
1
+ {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../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Aa,CAAC,QAAQ,EAAE;aAC/D;YACH,CAAC,CAAC,IAAI;QACR,KAAK;QACL,MAAM,EAAE,MAAM;aACX,MAAM,CACL,CAAC,KAAK,EAAgE,EAAE,CACtE,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,OAAO,CAC5B;aACA,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,WAAW,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;aAC9C,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAC3E,CAAC;AACJ,CAAC","sourcesContent":["import type { CommerceOffer, FeatureValue, ParsedBursarConfig, Window } from \"./config/types.js\";\n\nexport interface PublicCatalogWindow {\n type: Window[\"type\"];\n unit: string;\n count: number;\n timezone?: string;\n}\n\nexport interface PublicCatalogOffer {\n key: string;\n type: CommerceOffer[\"type\"];\n displayName: string;\n description?: string;\n sortOrder: number;\n price: {\n amountMinor: number;\n currency: string;\n taxBehavior: \"inclusive\" | \"exclusive\" | \"unspecified\";\n };\n billingInterval?: { unit: string; count: number };\n creditsPerUnit?: string;\n quantity?: { minimum: number; maximum: number; default: number };\n}\n\nexport interface PublicCatalogPlan {\n key: string;\n displayName: string;\n description?: string;\n rank: number;\n features: Record<string, FeatureValue>;\n allowance?: {\n amount: string;\n priority: number;\n window: PublicCatalogWindow;\n };\n quotas: Record<\n string,\n {\n operation: string;\n measure: string;\n limit: string;\n window: PublicCatalogWindow;\n enforcement: \"block\" | \"allow\";\n }\n >;\n offers: PublicCatalogOffer[];\n}\n\nexport interface PublicCatalog {\n version: 1;\n defaultPlan: string | null;\n creditDisplay: {\n currency: string;\n unitsPerMajor: string;\n } | null;\n plans: PublicCatalogPlan[];\n topups: PublicCatalogOffer[];\n}\n\nfunction publicWindow(window: Window): PublicCatalogWindow {\n if (window.type === \"calendar\") {\n return {\n type: window.type,\n unit: window.unit,\n count: window.count,\n timezone: window.timezone,\n };\n }\n if (window.type === \"plan_assignment\") {\n return {\n type: window.type,\n unit: window.interval.unit,\n count: window.interval.count,\n timezone: window.timezone,\n };\n }\n return {\n type: window.type,\n unit: window.duration.unit,\n count: window.duration.count,\n };\n}\n\nfunction publicOffer(key: string, offer: CommerceOffer): PublicCatalogOffer {\n return {\n key,\n type: offer.type,\n displayName: offer.displayName,\n ...(offer.description ? { description: offer.description } : {}),\n sortOrder: offer.sortOrder,\n price: { ...offer.price },\n ...(offer.type === \"subscription\"\n ? {\n billingInterval: {\n unit: offer.billingInterval.unit,\n count: offer.billingInterval.count,\n },\n }\n : {\n creditsPerUnit: offer.creditsPerUnit.toString(),\n quantity: { ...offer.quantity },\n }),\n };\n}\n\n/** Produce a provider-secret-free, JSON-safe catalog for product surfaces. */\nexport function projectPublicCatalog(config: ParsedBursarConfig): PublicCatalog {\n const offers = Object.entries(config.commerce.offers);\n const plans = Object.entries(config.plans)\n .map(([key, plan]): PublicCatalogPlan => ({\n key,\n displayName: plan.displayName,\n ...(plan.description ? { description: plan.description } : {}),\n rank: plan.rank,\n features: { ...plan.features },\n ...(plan.creditAllowance\n ? {\n allowance: {\n amount: plan.creditAllowance.amount.toString(),\n priority: plan.creditAllowance.priority,\n window: publicWindow(plan.creditAllowance.window),\n },\n }\n : {}),\n quotas: Object.fromEntries(\n Object.entries(plan.quotas).map(([quotaKey, quota]) => [\n quotaKey,\n {\n operation: quota.operation,\n measure: quota.measure,\n limit: quota.limit.toString(),\n window: publicWindow(quota.window),\n enforcement: quota.enforcement,\n },\n ]),\n ),\n offers: offers\n .filter(\n (entry): entry is [string, Extract<CommerceOffer, { type: \"subscription\" }>] =>\n entry[1].type === \"subscription\" && entry[1].plan === key,\n )\n .map(([offerKey, offer]) => publicOffer(offerKey, offer))\n .sort((a, b) => a.sortOrder - b.sortOrder || a.key.localeCompare(b.key)),\n }))\n .sort((a, b) => a.rank - b.rank || a.key.localeCompare(b.key));\n\n return {\n version: 1,\n defaultPlan: config.catalog.defaultPlan ?? null,\n creditDisplay: config.credits.display\n ? {\n currency: config.credits.display.currency,\n unitsPerMajor: config.credits.display.unitsPerMajor.toString(),\n }\n : null,\n plans,\n topups: offers\n .filter(\n (entry): entry is [string, Extract<CommerceOffer, { type: \"topup\" }>] =>\n entry[1].type === \"topup\",\n )\n .map(([key, offer]) => publicOffer(key, offer))\n .sort((a, b) => a.sortOrder - b.sortOrder || a.key.localeCompare(b.key)),\n };\n}\n"]}
@@ -1,6 +1,5 @@
1
1
  export * from "./errors.js";
2
2
  export * from "./types.js";
3
- export { CommerceProviderRegistry } from "./provider-registry.js";
4
3
  export * from "./plan-change.js";
5
4
  export { CommerceService } from "./service.js";
6
5
  export type { CommerceCredits } from "./service.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/commerce/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAClE,cAAc,kBAAkB,CAAC;AACjC,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,YAAY,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/commerce/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,kBAAkB,CAAC;AACjC,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,YAAY,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC"}
@@ -1,6 +1,5 @@
1
1
  export * from "./errors.js";
2
2
  export * from "./types.js";
3
- export { CommerceProviderRegistry } from "./provider-registry.js";
4
3
  export * from "./plan-change.js";
5
4
  export { CommerceService } from "./service.js";
6
5
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/commerce/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAClE,cAAc,kBAAkB,CAAC;AACjC,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC","sourcesContent":["export * from \"./errors.js\";\nexport * from \"./types.js\";\nexport { CommerceProviderRegistry } from \"./provider-registry.js\";\nexport * from \"./plan-change.js\";\nexport { CommerceService } from \"./service.js\";\nexport type { CommerceCredits } from \"./service.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/commerce/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,kBAAkB,CAAC;AACjC,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC","sourcesContent":["export * from \"./errors.js\";\nexport * from \"./types.js\";\nexport * from \"./plan-change.js\";\nexport { CommerceService } from \"./service.js\";\nexport type { CommerceCredits } from \"./service.js\";\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/commerce/service.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AACnF,OAAO,KAAK,EAAE,kBAAkB,EAA4B,MAAM,2BAA2B,CAAC;AAG9F,OAAO,KAAK,EACV,aAAa,EAKd,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EACV,eAAe,EACf,eAAe,EACf,aAAa,EACb,oBAAoB,EACpB,iBAAiB,EACjB,WAAW,EACX,UAAU,EACV,wBAAwB,EACxB,uBAAuB,EACvB,eAAe,EAChB,MAAM,2BAA2B,CAAC;AAEnC,OAAO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,OAAO,CAAC,0BAA0B,CAAC;YAe7E,iBAAiB;YAqDjB,kBAAkB;IAgB1B,iBAAiB,CAAC,KAAK,EAAE,sBAAsB,GAAG,OAAO,CAAC,uBAAuB,CAAC;IAuBlF,iBAAiB,CAAC,KAAK,EAAE,sBAAsB,GAAG,OAAO,CAAC,uBAAuB,CAAC;IA8HlF,yBAAyB,CAAC,KAAK,EAAE;QACrC,SAAS,EAAE,MAAM,CAAC;QAClB,YAAY,EAAE,MAAM,CAAC;KACtB,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,IAAI,CAAA;KAAE,CAAC;IAwBxB,mBAAmB,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;IAgD9E,OAAO,CAAC,WAAW;IASb,iBAAiB,CAAC,KAAK,EAAE;QAC7B,SAAS,EAAE,MAAM,CAAC;QAClB,KAAK,EAAE,eAAe,CAAC;KACxB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAO/B,OAAO,CAAC,cAAc;IAwBhB,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,uBAAuB,CAAC;IA8LvE,cAAc,CAAC,KAAK,EAAE,mBAAmB,GAAG,OAAO,CAAC;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;IAqCpE,aAAa,CAAC,KAAK,EAAE,oBAAoB,GAAG,OAAO,CAAC,qBAAqB,CAAC;CAcjF"}
@@ -1,8 +1,12 @@
1
1
  import { createHash } from "node:crypto";
2
- import Decimal from "decimal.js";
2
+ import { z } from "zod";
3
+ import { Decimal } from "decimal.js";
3
4
  import { loadConfigFromDict } from "../config.js";
4
- import { ConfigError } from "../errors.js";
5
+ import { ProviderResponseError } from "../errors.js";
5
6
  import { normalizeLogger } from "../shared/logger.js";
7
+ import { requireStableKey, scopedStableKey } from "../shared/idempotency.js";
8
+ import { normalizeProviderEnvironment } from "../providers/environment.js";
9
+ import { persistedDiagnosticSummary } from "../shared/diagnostics.js";
6
10
  import { ActiveSubscriptionError, CheckoutCompletedError, CheckoutConflictError, CommerceResourceNotFoundError, CoreBillingDataUnavailableError, InvalidOfferQuantityError, ProviderCapabilityNotSupportedError, QuoteChangedError, UnknownOfferError, } from "./errors.js";
7
11
  import { CommerceProviderRegistry } from "./provider-registry.js";
8
12
  import { classifySubscriptionChange } from "./plan-change.js";
@@ -25,11 +29,11 @@ function requireOptionalNonEmptyText(value, field) {
25
29
  }
26
30
  function assertCreateCheckoutInput(input) {
27
31
  requireNonEmptyText(input.subjectId, "subjectId");
32
+ requireNonEmptyText(input.accountId, "accountId");
28
33
  requireNonEmptyText(input.offerKey, "offerKey");
29
34
  requireNonEmptyText(input.returnUrl, "returnUrl");
30
35
  requireNonEmptyText(input.cancelUrl, "cancelUrl");
31
- requireNonEmptyText(input.operationKey, "operationKey");
32
- requireOptionalNonEmptyText(input.accountId, "accountId");
36
+ requireStableKey(input.operationKey, "operationKey");
33
37
  requireOptionalNonEmptyText(input.email, "email");
34
38
  requireOptionalNonEmptyText(input.provider, "provider");
35
39
  if (input.type !== undefined && input.type !== "subscription" && input.type !== "credit_pack") {
@@ -71,27 +75,76 @@ function externalId(reference) {
71
75
  function checkoutRedirectUrl(template, intentId) {
72
76
  return template.replaceAll("{intentId}", encodeURIComponent(intentId));
73
77
  }
78
+ const currencySchema = z
79
+ .string()
80
+ .regex(/^[A-Za-z]{3}$/u, "expected a three-letter ASCII currency")
81
+ .transform((value) => value.toUpperCase());
82
+ const instantSchema = z.string().datetime({ offset: true });
83
+ const changePlanLineItemSchema = z
84
+ .object({
85
+ productId: z.string().trim().min(1),
86
+ name: z.string().trim().min(1),
87
+ unitPrice: z.number().finite(),
88
+ quantity: z.number().finite().int().positive(),
89
+ prorationFactor: z.number().finite(),
90
+ currency: currencySchema,
91
+ tax: z.number().finite(),
92
+ subtotal: z.number().finite(),
93
+ })
94
+ .strict();
95
+ const changePlanPreviewSchema = z
96
+ .object({
97
+ totalAmount: z.number().finite(),
98
+ settlementAmount: z.number().finite(),
99
+ currency: currencySchema,
100
+ lineItems: z.array(changePlanLineItemSchema),
101
+ effectiveAt: instantSchema,
102
+ recurringAmount: z.number().finite().optional(),
103
+ recurringCurrency: currencySchema.optional(),
104
+ nextBillingDate: instantSchema.optional(),
105
+ taxAmount: z.number().finite().optional(),
106
+ customerCredits: z.number().finite().optional(),
107
+ })
108
+ .strict();
109
+ function validatePlanPreview(value, provider, requireNextBillingDate) {
110
+ const parsed = changePlanPreviewSchema.safeParse(value);
111
+ if (!parsed.success) {
112
+ const issue = parsed.error.issues[0];
113
+ throw new ProviderResponseError(provider, "previewChangePlan", {
114
+ details: {
115
+ field: issue?.path.length ? issue.path.join(".") : "response",
116
+ validation: issue?.message,
117
+ },
118
+ cause: parsed.error,
119
+ });
120
+ }
121
+ if (requireNextBillingDate && parsed.data.nextBillingDate === undefined) {
122
+ throw new ProviderResponseError(provider, "previewChangePlan", {
123
+ details: { field: "nextBillingDate" },
124
+ });
125
+ }
126
+ return parsed.data;
127
+ }
74
128
  function quoteFingerprint(preview) {
75
- const amount = (value) => {
76
- const numeric = Number(value);
77
- return Number.isFinite(numeric) ? numeric : null;
78
- };
79
129
  const financialFields = {
80
- totalAmount: amount(preview.totalAmount),
81
- settlementAmount: amount(preview.settlementAmount),
130
+ totalAmount: preview.totalAmount,
131
+ settlementAmount: preview.settlementAmount,
82
132
  currency: preview.currency.toUpperCase(),
83
- recurringAmount: amount(preview.recurringAmount),
133
+ recurringAmount: preview.recurringAmount ?? null,
84
134
  recurringCurrency: preview.recurringCurrency?.toUpperCase() ?? null,
85
- taxAmount: amount(preview.taxAmount),
86
- customerCredits: amount(preview.customerCredits),
135
+ taxAmount: preview.taxAmount ?? null,
136
+ customerCredits: preview.customerCredits ?? null,
137
+ nextBillingDate: preview.nextBillingDate === undefined
138
+ ? null
139
+ : new Date(preview.nextBillingDate).toISOString(),
87
140
  lineItems: preview.lineItems.map((item) => ({
88
141
  productId: item.productId,
89
- unitPrice: amount(item.unitPrice),
90
- quantity: amount(item.quantity),
91
- prorationFactor: amount(item.prorationFactor),
142
+ unitPrice: item.unitPrice,
143
+ quantity: item.quantity,
144
+ prorationFactor: item.prorationFactor,
92
145
  currency: item.currency.toUpperCase(),
93
- tax: amount(item.tax),
94
- subtotal: amount(item.subtotal),
146
+ tax: item.tax,
147
+ subtotal: item.subtotal,
95
148
  })),
96
149
  };
97
150
  return createHash("sha256").update(JSON.stringify(financialFields)).digest("hex");
@@ -182,21 +235,12 @@ export class CommerceService {
182
235
  (!Number.isSafeInteger(options.checkoutIntentTtlMs) || options.checkoutIntentTtlMs <= 0)) {
183
236
  throw new TypeError("checkoutIntentTtlMs must be a positive safe integer");
184
237
  }
238
+ const providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);
185
239
  this.logger = normalizeLogger(options.logger);
186
- const identityResolver = options.identityResolver
187
- ? async (input) => {
188
- const accountId = await options.identityResolver(input);
189
- requireOptionalNonEmptyText(accountId, "identity resolver accountId");
190
- if (accountId && input.customerId) {
191
- await this.billing.upsertCustomer(input.provider, input.customerId, accountId, input.email);
192
- }
193
- return accountId;
194
- }
195
- : undefined;
196
240
  this.providers = new CommerceProviderRegistry(options, {
197
241
  tenantId: options.tenantId,
242
+ providerEnvironment,
198
243
  eventSink,
199
- identityResolver,
200
244
  });
201
245
  this.autoRecharge = new CommerceAutoRechargeService(this, (name) => this.providers.get(name));
202
246
  }
@@ -239,7 +283,7 @@ export class CommerceService {
239
283
  return 1;
240
284
  }
241
285
  const quantity = requested ?? offer.quantity.default;
242
- if (!Number.isInteger(quantity) || quantity < offer.quantity.minimum) {
286
+ if (!Number.isSafeInteger(quantity) || quantity < offer.quantity.minimum) {
243
287
  throw new InvalidOfferQuantityError(`Minimum quantity is ${offer.quantity.minimum}`, offer.quantity.minimum, offer.quantity.maximum);
244
288
  }
245
289
  if (quantity > offer.quantity.maximum) {
@@ -259,12 +303,10 @@ export class CommerceService {
259
303
  assertCreateCheckoutInput(input);
260
304
  const resolved = await this.resolveOffer(input);
261
305
  const quantity = this.quantity(resolved.offer, input.quantity);
262
- const accountState = input.accountId
263
- ? await Promise.all([
264
- this.billing.getBlockingSubscription(input.accountId),
265
- this.billing.getCustomerByUserId(input.accountId),
266
- ])
267
- : [null, null];
306
+ const accountState = await Promise.all([
307
+ this.billing.getBlockingSubscription(input.accountId),
308
+ this.billing.getCustomerByUserId(input.accountId),
309
+ ]);
268
310
  if (resolved.offer.type === "subscription" && accountState[0]) {
269
311
  throw new ActiveSubscriptionError();
270
312
  }
@@ -277,12 +319,10 @@ export class CommerceService {
277
319
  if (!reference)
278
320
  throw new UnknownOfferError("Offer has no reference for the selected provider");
279
321
  const productId = externalId(reference);
280
- const customer = input.accountId
281
- ? await this.billing.getCustomerByUserId(input.accountId, provider.provider)
282
- : null;
322
+ const customer = await this.billing.getCustomerByUserId(input.accountId, provider.provider);
283
323
  const metadata = {
284
324
  ...(input.metadata ?? {}),
285
- ...(input.accountId ? { userId: input.accountId } : {}),
325
+ bursar_account_id: input.accountId,
286
326
  };
287
327
  if (resolved.offer.type === "subscription") {
288
328
  metadata.plan_slug = resolved.offer.plan;
@@ -292,82 +332,88 @@ export class CommerceService {
292
332
  metadata.credits = resolved.offer.creditsPerUnit.mul(quantity).toString();
293
333
  metadata.quantity = String(quantity);
294
334
  }
295
- const requestDigest = createHash("sha256")
296
- .update(JSON.stringify({
335
+ const digestValue = {
336
+ accountId: input.accountId,
297
337
  checkoutKind: resolved.offer.type,
298
338
  offerKey: resolved.offerKey,
299
339
  provider: provider.provider,
300
340
  quantity,
301
- }))
341
+ };
342
+ const requestDigest = createHash("sha256")
343
+ .update(JSON.stringify(digestValue, Object.keys(digestValue).sort()))
302
344
  .digest("hex");
303
345
  const expiresAt = () => new Date(Date.now() + (this.options.checkoutIntentTtlMs ?? DEFAULT_CHECKOUT_INTENT_TTL_MS)).toISOString();
304
346
  const createIntent = () => this.billing.createOrGetCheckoutIntent({
305
347
  subjectId: input.subjectId,
306
348
  provider: provider.provider,
349
+ operationKey: input.operationKey,
307
350
  checkoutKind: resolved.offer.type === "subscription" ? "subscription" : "credit_topup",
308
351
  productKey: resolved.offerKey,
309
352
  requestDigest,
310
353
  expiresAt: expiresAt(),
311
354
  });
312
- let intent = await createIntent();
355
+ const intent = await createIntent();
313
356
  if (intent.requestDigest !== requestDigest) {
314
- throw new CheckoutConflictError("A checkout is already in progress for a different offer");
357
+ throw new CheckoutConflictError("This operation key is already bound to a different checkout request");
358
+ }
359
+ if (intent.status === "completed")
360
+ throw new CheckoutCompletedError();
361
+ if (intent.status !== "open") {
362
+ throw new CheckoutConflictError("This checkout operation is terminal; start a new checkout with a new operation key");
315
363
  }
316
364
  if (intent.checkoutUrl) {
317
365
  const locallyExpired = new Date(intent.expiresAt).getTime() <= Date.now();
318
- if (!locallyExpired && (!intent.providerSessionId || !provider.getCheckoutSessionStatus)) {
319
- throw new CheckoutConflictError("A checkout is already in progress; continue it in the existing checkout window");
366
+ if (locallyExpired) {
367
+ await this.billing.updateCheckoutIntent(intent.id, { status: "expired" });
368
+ throw new CheckoutConflictError("This checkout operation expired; start a new checkout with a new operation key");
320
369
  }
321
- const providerState = locallyExpired
322
- ? null
323
- : await provider.getCheckoutSessionStatus(intent.providerSessionId);
324
- if (providerState?.paymentStatus === "succeeded") {
325
- await this.billing.updateCheckoutIntent(intent.id, { status: "completed" });
326
- throw new CheckoutCompletedError();
327
- }
328
- if (!locallyExpired &&
329
- providerState !== null &&
330
- !TERMINAL_CHECKOUT_STATUSES.has(providerState.paymentStatus ?? "")) {
331
- throw new CheckoutConflictError("A checkout is already in progress; continue it in the existing checkout window");
332
- }
333
- await this.billing.updateCheckoutIntent(intent.id, {
334
- status: providerState === null ? "expired" : "failed",
335
- });
336
- intent = await createIntent();
337
- }
338
- try {
339
- const session = await provider.createCheckoutSession({
340
- ...(input.accountId ? { userId: input.accountId } : {}),
341
- ...(customer?.providerCustomerId ? { customerId: customer.providerCustomerId } : {}),
342
- ...(input.email ? { email: input.email } : {}),
343
- productId,
344
- type: resolved.offer.type === "subscription" ? "subscription" : "credit_pack",
345
- quantity,
346
- returnUrl: checkoutRedirectUrl(input.returnUrl, intent.id),
347
- cancelUrl: checkoutRedirectUrl(input.cancelUrl, intent.id),
348
- metadata: { ...metadata, checkout_intent_id: intent.id },
349
- idempotencyKey: input.operationKey,
350
- });
351
- await this.billing.updateCheckoutIntent(intent.id, {
352
- providerSessionId: session.providerSessionId,
353
- checkoutUrl: session.url,
354
- });
355
- if (input.accountId &&
356
- session.customerId &&
357
- session.customerId !== customer?.providerCustomerId) {
358
- await this.billing.upsertCustomer(provider.provider, session.customerId, input.accountId, input.email ?? null);
370
+ if (intent.providerSessionId && provider.getCheckoutSessionStatus) {
371
+ const providerState = await provider.getCheckoutSessionStatus(intent.providerSessionId);
372
+ if (providerState?.paymentStatus === "succeeded") {
373
+ await this.billing.updateCheckoutIntent(intent.id, { status: "completed" });
374
+ throw new CheckoutCompletedError();
375
+ }
376
+ if (providerState !== null &&
377
+ TERMINAL_CHECKOUT_STATUSES.has(providerState.paymentStatus ?? "")) {
378
+ await this.billing.updateCheckoutIntent(intent.id, { status: "failed" });
379
+ throw new CheckoutConflictError("This checkout operation is no longer active; start a new checkout with a new operation key");
380
+ }
359
381
  }
360
382
  return {
361
383
  intentId: intent.id,
362
- url: session.url,
384
+ url: intent.checkoutUrl,
363
385
  provider: provider.provider,
364
386
  offerKey: resolved.offerKey,
365
387
  };
366
388
  }
367
- catch (error) {
368
- await this.billing.updateCheckoutIntent(intent.id, { status: "failed" });
369
- throw error;
389
+ const session = await provider.createCheckoutSession({
390
+ accountId: input.accountId,
391
+ ...(customer?.providerCustomerId ? { customerId: customer.providerCustomerId } : {}),
392
+ ...(input.email ? { email: input.email } : {}),
393
+ productId,
394
+ type: resolved.offer.type === "subscription" ? "subscription" : "credit_pack",
395
+ quantity,
396
+ returnUrl: checkoutRedirectUrl(input.returnUrl, intent.id),
397
+ cancelUrl: checkoutRedirectUrl(input.cancelUrl, intent.id),
398
+ metadata: { ...metadata, checkout_intent_id: intent.id },
399
+ idempotencyKey: input.operationKey,
400
+ });
401
+ // Complete every fallible local write before publishing the session on the
402
+ // intent. If either write fails, an exact replay reaches the provider with
403
+ // the same idempotency key and can repair the open intent.
404
+ if (session.customerId && session.customerId !== customer?.providerCustomerId) {
405
+ await this.billing.upsertCustomer(provider.provider, session.customerId, input.accountId, input.email ?? null);
370
406
  }
407
+ await this.billing.updateCheckoutIntent(intent.id, {
408
+ providerSessionId: session.providerSessionId,
409
+ checkoutUrl: session.url,
410
+ });
411
+ return {
412
+ intentId: intent.id,
413
+ url: session.url,
414
+ provider: provider.provider,
415
+ offerKey: resolved.offerKey,
416
+ };
371
417
  }
372
418
  async getCheckoutStatus(input) {
373
419
  const intent = await this.billing.getCheckoutIntent(input.intentId, input.subjectId);
@@ -386,6 +432,7 @@ export class CommerceService {
386
432
  };
387
433
  }
388
434
  async cancelSubscription(input) {
435
+ requireStableKey(input.operationKey, "operationKey");
389
436
  const subscription = await this.billing.getUserSubscription(input.accountId);
390
437
  if (!subscription?.providerSubscriptionId) {
391
438
  throw new CommerceResourceNotFoundError("No active subscription found");
@@ -403,7 +450,7 @@ export class CommerceService {
403
450
  eventId: `cancel_${input.accountId}_${input.operationKey}`,
404
451
  eventType: "subscription.cancellation_scheduled",
405
452
  occurredAt: new Date().toISOString(),
406
- userId: input.accountId,
453
+ accountId: input.accountId,
407
454
  customer: { providerCustomerId: subscription.providerCustomerId },
408
455
  subscription: {
409
456
  providerSubscriptionId: subscription.providerSubscriptionId,
@@ -413,6 +460,7 @@ export class CommerceService {
413
460
  return { ok: true, pending: true };
414
461
  }
415
462
  async reactivateSubscription(input) {
463
+ requireStableKey(input.operationKey, "operationKey");
416
464
  const subscription = await this.billing.getUserSubscription(input.accountId);
417
465
  if (!subscription?.providerSubscriptionId) {
418
466
  throw new CommerceResourceNotFoundError("No subscription found");
@@ -431,7 +479,7 @@ export class CommerceService {
431
479
  eventId: `reactivate_${input.accountId}_${input.operationKey}`,
432
480
  eventType: "subscription.cancellation_unscheduled",
433
481
  occurredAt: new Date().toISOString(),
434
- userId: input.accountId,
482
+ accountId: input.accountId,
435
483
  customer: { providerCustomerId: subscription.providerCustomerId },
436
484
  subscription: {
437
485
  providerSubscriptionId: subscription.providerSubscriptionId,
@@ -441,9 +489,7 @@ export class CommerceService {
441
489
  return { ok: true, pending: true };
442
490
  }
443
491
  async cancelAllSubscriptions(input) {
444
- if (!input.operationKey.trim()) {
445
- throw new ConfigError("operationKey must not be empty");
446
- }
492
+ requireStableKey(input.operationKey, "operationKey");
447
493
  const subscriptions = await this.billing.listCancellableSubscriptions(input.accountId);
448
494
  const results = await Promise.all(subscriptions.map(async (subscription) => {
449
495
  try {
@@ -451,14 +497,17 @@ export class CommerceService {
451
497
  if (!provider.cancelSubscription) {
452
498
  throw new ProviderCapabilityNotSupportedError(provider.provider, "cancelSubscription");
453
499
  }
454
- const operationKey = `${input.operationKey}:${subscription.provider}:${subscription.providerSubscriptionId}`;
500
+ const operationKey = scopedStableKey(input.operationKey, "cancel-all", [
501
+ subscription.provider,
502
+ subscription.providerSubscriptionId,
503
+ ]);
455
504
  await provider.cancelSubscription(subscription.providerSubscriptionId, operationKey);
456
505
  await this.billing.ingestBillingEvent({
457
506
  provider: subscription.provider,
458
507
  eventId: `cancel_all_${input.accountId}_${operationKey}`,
459
508
  eventType: "subscription.cancellation_scheduled",
460
509
  occurredAt: new Date().toISOString(),
461
- userId: input.accountId,
510
+ accountId: input.accountId,
462
511
  customer: { providerCustomerId: subscription.providerCustomerId },
463
512
  subscription: {
464
513
  providerSubscriptionId: subscription.providerSubscriptionId,
@@ -598,11 +647,12 @@ export class CommerceService {
598
647
  if (!context.provider.previewChangePlan) {
599
648
  throw new ProviderCapabilityNotSupportedError(context.provider.provider, "previewChangePlan");
600
649
  }
601
- return context.provider.previewChangePlan({
650
+ const preview = await context.provider.previewChangePlan({
602
651
  providerSubscriptionId: context.subscription.providerSubscriptionId,
603
652
  productId: context.targetProductId,
604
653
  ...providerPlanChangeParams(context.policy),
605
654
  });
655
+ return validatePlanPreview(preview, context.provider.provider, context.policy.effective === "renewal");
606
656
  }
607
657
  async previewPlanChange(input) {
608
658
  const context = await this.planChangeContext(input);
@@ -627,6 +677,7 @@ export class CommerceService {
627
677
  };
628
678
  }
629
679
  async confirmPlanChange(input) {
680
+ requireStableKey(input.operationKey, "operationKey");
630
681
  const context = await this.planChangeContext(input);
631
682
  if (context.classification === "unchanged") {
632
683
  return {
@@ -661,11 +712,7 @@ export class CommerceService {
661
712
  throw new CheckoutConflictError("A plan change is already awaiting payment");
662
713
  }
663
714
  const scheduled = context.policy.effective === "renewal";
664
- const effectiveAt = scheduled
665
- ? preview.nextBillingDate
666
- : Number.isFinite(Date.parse(preview.effectiveAt))
667
- ? preview.effectiveAt
668
- : new Date().toISOString();
715
+ const effectiveAt = scheduled ? preview.nextBillingDate : preview.effectiveAt;
669
716
  if (!effectiveAt) {
670
717
  throw new CoreBillingDataUnavailableError("The provider did not return the scheduled change date");
671
718
  }
@@ -687,7 +734,7 @@ export class CommerceService {
687
734
  if (!context.provider.cancelSubscription) {
688
735
  throw new ProviderCapabilityNotSupportedError(context.provider.provider, "cancelSubscription");
689
736
  }
690
- await context.provider.reactivateSubscription(context.subscription.providerSubscriptionId, `${input.operationKey}:keep`);
737
+ await context.provider.reactivateSubscription(context.subscription.providerSubscriptionId, scopedStableKey(input.operationKey, "keep"));
691
738
  cancellationWasReactivated = true;
692
739
  }
693
740
  const result = await context.provider.changePlan({
@@ -696,7 +743,7 @@ export class CommerceService {
696
743
  ...providerPlanChangeParams(context.policy),
697
744
  onPaymentFailure: context.policy.paymentFailure,
698
745
  metadata: {
699
- userId: input.accountId,
746
+ bursar_account_id: input.accountId,
700
747
  plan_slug: context.targetOffer.plan,
701
748
  billing_interval: context.targetInterval,
702
749
  },
@@ -710,7 +757,7 @@ export class CommerceService {
710
757
  let failure = error;
711
758
  if (cancellationWasReactivated) {
712
759
  try {
713
- await context.provider.cancelSubscription(context.subscription.providerSubscriptionId, `${input.operationKey}:restore-cancellation`);
760
+ await context.provider.cancelSubscription(context.subscription.providerSubscriptionId, scopedStableKey(input.operationKey, "restore-cancellation"));
714
761
  }
715
762
  catch (compensationError) {
716
763
  failure = new AggregateError([error, compensationError], "Plan change failed and the original subscription cancellation could not be restored");
@@ -718,7 +765,7 @@ export class CommerceService {
718
765
  }
719
766
  await this.billing.updateBillingSubscriptionChange(change.id, {
720
767
  state: "failed",
721
- errorMessage: failure instanceof Error ? failure.message : String(failure),
768
+ errorMessage: persistedDiagnosticSummary(failure, "subscription_change_failed"),
722
769
  });
723
770
  throw failure;
724
771
  }
@@ -732,6 +779,7 @@ export class CommerceService {
732
779
  };
733
780
  }
734
781
  async cancelScheduledPlanChange(input) {
782
+ requireStableKey(input.operationKey, "operationKey");
735
783
  const subscription = await this.billing.getActiveSubscription(input.accountId);
736
784
  if (!subscription)
737
785
  throw new CommerceResourceNotFoundError("No active subscription found");