@zonastery/bursar 2.0.1 → 2.0.2

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 (173) hide show
  1. package/README.md +21 -14
  2. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  3. package/dist/billing/auto-recharge-service.js +6 -4
  4. package/dist/billing/auto-recharge-service.js.map +1 -1
  5. package/dist/billing/billing-store.d.ts +3 -0
  6. package/dist/billing/billing-store.d.ts.map +1 -1
  7. package/dist/billing/billing-store.js +2 -0
  8. package/dist/billing/billing-store.js.map +1 -1
  9. package/dist/billing/event-handlers.d.ts +2 -3
  10. package/dist/billing/event-handlers.d.ts.map +1 -1
  11. package/dist/billing/event-handlers.js +38 -49
  12. package/dist/billing/event-handlers.js.map +1 -1
  13. package/dist/billing/event-processor.js +4 -4
  14. package/dist/billing/event-processor.js.map +1 -1
  15. package/dist/billing/financial-event-handlers.d.ts +2 -2
  16. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  17. package/dist/billing/financial-event-handlers.js +7 -7
  18. package/dist/billing/financial-event-handlers.js.map +1 -1
  19. package/dist/billing/postgres/store.d.ts +5 -1
  20. package/dist/billing/postgres/store.d.ts.map +1 -1
  21. package/dist/billing/postgres/store.js +5 -0
  22. package/dist/billing/postgres/store.js.map +1 -1
  23. package/dist/billing/service-types.d.ts +2 -15
  24. package/dist/billing/service-types.d.ts.map +1 -1
  25. package/dist/billing/service-types.js.map +1 -1
  26. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  27. package/dist/billing/types/auto-recharge.js.map +1 -1
  28. package/dist/billing/types/events.d.ts +3 -2
  29. package/dist/billing/types/events.d.ts.map +1 -1
  30. package/dist/billing/types/events.js +2 -2
  31. package/dist/billing/types/events.js.map +1 -1
  32. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  33. package/dist/billing/types/subscriptions.js.map +1 -1
  34. package/dist/bursar.d.ts +21 -11
  35. package/dist/bursar.d.ts.map +1 -1
  36. package/dist/bursar.js +40 -4
  37. package/dist/bursar.js.map +1 -1
  38. package/dist/catalog.d.ts.map +1 -1
  39. package/dist/catalog.js +1 -1
  40. package/dist/catalog.js.map +1 -1
  41. package/dist/commerce/index.d.ts +0 -1
  42. package/dist/commerce/index.d.ts.map +1 -1
  43. package/dist/commerce/index.js +0 -1
  44. package/dist/commerce/index.js.map +1 -1
  45. package/dist/commerce/service.d.ts.map +1 -1
  46. package/dist/commerce/service.js +99 -59
  47. package/dist/commerce/service.js.map +1 -1
  48. package/dist/commerce/types.d.ts +8 -4
  49. package/dist/commerce/types.d.ts.map +1 -1
  50. package/dist/commerce/types.js.map +1 -1
  51. package/dist/config/parse-credits.d.ts.map +1 -1
  52. package/dist/config/parse-credits.js +0 -6
  53. package/dist/config/parse-credits.js.map +1 -1
  54. package/dist/config/types.d.ts +0 -5
  55. package/dist/config/types.d.ts.map +1 -1
  56. package/dist/config/types.js.map +1 -1
  57. package/dist/config.d.ts.map +1 -1
  58. package/dist/config.js +7 -0
  59. package/dist/config.js.map +1 -1
  60. package/dist/credits/amount.d.ts +8 -0
  61. package/dist/credits/amount.d.ts.map +1 -0
  62. package/dist/credits/amount.js +32 -0
  63. package/dist/credits/amount.js.map +1 -0
  64. package/dist/credits/catalog-runtime.d.ts +4 -6
  65. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  66. package/dist/credits/catalog-runtime.js +3 -12
  67. package/dist/credits/catalog-runtime.js.map +1 -1
  68. package/dist/credits/lease-workflow.d.ts +1 -1
  69. package/dist/credits/lease-workflow.d.ts.map +1 -1
  70. package/dist/credits/lease-workflow.js +23 -20
  71. package/dist/credits/lease-workflow.js.map +1 -1
  72. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  73. package/dist/credits/low-balance-monitor.js +2 -3
  74. package/dist/credits/low-balance-monitor.js.map +1 -1
  75. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  76. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  77. package/dist/credits/postgres/store.d.ts +15 -11
  78. package/dist/credits/postgres/store.d.ts.map +1 -1
  79. package/dist/credits/postgres/store.js +24 -15
  80. package/dist/credits/postgres/store.js.map +1 -1
  81. package/dist/credits/service-types.d.ts +17 -15
  82. package/dist/credits/service-types.d.ts.map +1 -1
  83. package/dist/credits/service-types.js.map +1 -1
  84. package/dist/credits/service.d.ts +16 -17
  85. package/dist/credits/service.d.ts.map +1 -1
  86. package/dist/credits/service.js +61 -33
  87. package/dist/credits/service.js.map +1 -1
  88. package/dist/credits/store.d.ts +16 -22
  89. package/dist/credits/store.d.ts.map +1 -1
  90. package/dist/credits/store.js +3 -1
  91. package/dist/credits/store.js.map +1 -1
  92. package/dist/credits/types/account.d.ts +1 -1
  93. package/dist/credits/types/account.d.ts.map +1 -1
  94. package/dist/credits/types/account.js.map +1 -1
  95. package/dist/credits/types/grants.d.ts.map +1 -1
  96. package/dist/credits/types/grants.js.map +1 -1
  97. package/dist/expr/ast.d.ts.map +1 -1
  98. package/dist/expr/ast.js.map +1 -1
  99. package/dist/expr/parser.d.ts +1 -0
  100. package/dist/expr/parser.d.ts.map +1 -1
  101. package/dist/expr/parser.js +15 -3
  102. package/dist/expr/parser.js.map +1 -1
  103. package/dist/generated/pricing-config.schema.json +31 -29
  104. package/dist/generated/pricing-config.types.d.ts +6 -18
  105. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  106. package/dist/generated/pricing-config.types.js.map +1 -1
  107. package/dist/index.d.ts +4 -2
  108. package/dist/index.d.ts.map +1 -1
  109. package/dist/index.js +1 -0
  110. package/dist/index.js.map +1 -1
  111. package/dist/load-config-file.d.ts +2 -3
  112. package/dist/load-config-file.d.ts.map +1 -1
  113. package/dist/load-config-file.js +14 -29
  114. package/dist/load-config-file.js.map +1 -1
  115. package/dist/providers/_shared.js +1 -1
  116. package/dist/providers/_shared.js.map +1 -1
  117. package/dist/providers/dodo/client-contract.d.ts +3 -1
  118. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  119. package/dist/providers/dodo/client-contract.js.map +1 -1
  120. package/dist/providers/dodo/event-mapper.d.ts +1 -1
  121. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  122. package/dist/providers/dodo/event-mapper.js +5 -13
  123. package/dist/providers/dodo/event-mapper.js.map +1 -1
  124. package/dist/providers/dodo/provider.d.ts +4 -6
  125. package/dist/providers/dodo/provider.d.ts.map +1 -1
  126. package/dist/providers/dodo/provider.js +22 -71
  127. package/dist/providers/dodo/provider.js.map +1 -1
  128. package/dist/providers/dodo/webhook-bridge.d.ts +1 -2
  129. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
  130. package/dist/providers/dodo/webhook-bridge.js +0 -1
  131. package/dist/providers/dodo/webhook-bridge.js.map +1 -1
  132. package/dist/providers/environment.d.ts +6 -0
  133. package/dist/providers/environment.d.ts.map +1 -0
  134. package/dist/providers/environment.js +10 -0
  135. package/dist/providers/environment.js.map +1 -0
  136. package/dist/providers/index.d.ts +3 -7
  137. package/dist/providers/index.d.ts.map +1 -1
  138. package/dist/providers/index.js +1 -5
  139. package/dist/providers/index.js.map +1 -1
  140. package/dist/providers/mock/provider.d.ts +6 -8
  141. package/dist/providers/mock/provider.d.ts.map +1 -1
  142. package/dist/providers/mock/provider.js +18 -50
  143. package/dist/providers/mock/provider.js.map +1 -1
  144. package/dist/providers/stripe/event-mapper.js +11 -11
  145. package/dist/providers/stripe/event-mapper.js.map +1 -1
  146. package/dist/providers/stripe/provider.d.ts +3 -3
  147. package/dist/providers/stripe/provider.d.ts.map +1 -1
  148. package/dist/providers/stripe/provider.js +37 -24
  149. package/dist/providers/stripe/provider.js.map +1 -1
  150. package/dist/providers/types.d.ts +9 -19
  151. package/dist/providers/types.d.ts.map +1 -1
  152. package/dist/providers/types.js.map +1 -1
  153. package/dist/shared/idempotency.d.ts +9 -0
  154. package/dist/shared/idempotency.d.ts.map +1 -0
  155. package/dist/shared/idempotency.js +34 -0
  156. package/dist/shared/idempotency.js.map +1 -0
  157. package/dist/shared/postgres-client.d.ts +4 -0
  158. package/dist/shared/postgres-client.d.ts.map +1 -1
  159. package/dist/shared/postgres-client.js +6 -2
  160. package/dist/shared/postgres-client.js.map +1 -1
  161. package/dist/shared/postgres-errors.d.ts.map +1 -1
  162. package/dist/shared/postgres-errors.js.map +1 -1
  163. package/dist/storage/outbox-worker.d.ts.map +1 -1
  164. package/dist/storage/outbox-worker.js +22 -21
  165. package/dist/storage/outbox-worker.js.map +1 -1
  166. package/dist/storage/postgres-repository.d.ts.map +1 -1
  167. package/dist/storage/postgres-repository.js +67 -46
  168. package/dist/storage/postgres-repository.js.map +1 -1
  169. package/dist/storage/runtime.d.ts +11 -7
  170. package/dist/storage/runtime.d.ts.map +1 -1
  171. package/dist/storage/runtime.js +52 -8
  172. package/dist/storage/runtime.js.map +1 -1
  173. package/package.json +52 -36
@@ -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,CAAC,KAAK;YAC5B,QAAQ,EAAE,MAAM,CAAC,QAAQ;SAC1B,CAAC;IACJ,CAAC;IACD,OAAO;QACL,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,IAAI;Q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,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAC3E,CAAC,CACH;SACA,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IAEjE,OAAO;QACL,OAAO,EAAE,CAAC;QACV,WAAW,EAAE,MAAM,CAAC,OAAO,CAAC,WAAW,IAAI,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,IAAI,IAAI;QAChE,aAAa,EAAE,MAAM,CAAC,OAAO,CAAC,OAAO;YACnC,CAAC,CAAC;gBACE,QAAQ,EAAE,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,QAAQ;gBACzC,aAAa,EAAE,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,aAAa,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(\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":["../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,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AAK,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,KAAK,EAGV,eAAe,EAEhB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AActD,OAAO,KAAK,EACV,uBAAuB,EACvB,0BAA0B,EAG1B,oBAAoB,EAEpB,eAAe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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,11 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { z } from "zod";
2
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";
6
9
  import { ActiveSubscriptionError, CheckoutCompletedError, CheckoutConflictError, CommerceResourceNotFoundError, CoreBillingDataUnavailableError, InvalidOfferQuantityError, ProviderCapabilityNotSupportedError, QuoteChangedError, UnknownOfferError, } from "./errors.js";
7
10
  import { CommerceProviderRegistry } from "./provider-registry.js";
8
11
  import { classifySubscriptionChange } from "./plan-change.js";
@@ -25,11 +28,11 @@ function requireOptionalNonEmptyText(value, field) {
25
28
  }
26
29
  function assertCreateCheckoutInput(input) {
27
30
  requireNonEmptyText(input.subjectId, "subjectId");
31
+ requireNonEmptyText(input.accountId, "accountId");
28
32
  requireNonEmptyText(input.offerKey, "offerKey");
29
33
  requireNonEmptyText(input.returnUrl, "returnUrl");
30
34
  requireNonEmptyText(input.cancelUrl, "cancelUrl");
31
- requireNonEmptyText(input.operationKey, "operationKey");
32
- requireOptionalNonEmptyText(input.accountId, "accountId");
35
+ requireStableKey(input.operationKey, "operationKey");
33
36
  requireOptionalNonEmptyText(input.email, "email");
34
37
  requireOptionalNonEmptyText(input.provider, "provider");
35
38
  if (input.type !== undefined && input.type !== "subscription" && input.type !== "credit_pack") {
@@ -71,27 +74,76 @@ function externalId(reference) {
71
74
  function checkoutRedirectUrl(template, intentId) {
72
75
  return template.replaceAll("{intentId}", encodeURIComponent(intentId));
73
76
  }
77
+ const currencySchema = z
78
+ .string()
79
+ .regex(/^[A-Za-z]{3}$/u, "expected a three-letter ASCII currency")
80
+ .transform((value) => value.toUpperCase());
81
+ const instantSchema = z.string().datetime({ offset: true });
82
+ const changePlanLineItemSchema = z
83
+ .object({
84
+ productId: z.string().trim().min(1),
85
+ name: z.string().trim().min(1),
86
+ unitPrice: z.number().finite(),
87
+ quantity: z.number().finite().int().positive(),
88
+ prorationFactor: z.number().finite(),
89
+ currency: currencySchema,
90
+ tax: z.number().finite(),
91
+ subtotal: z.number().finite(),
92
+ })
93
+ .strict();
94
+ const changePlanPreviewSchema = z
95
+ .object({
96
+ totalAmount: z.number().finite(),
97
+ settlementAmount: z.number().finite(),
98
+ currency: currencySchema,
99
+ lineItems: z.array(changePlanLineItemSchema),
100
+ effectiveAt: instantSchema,
101
+ recurringAmount: z.number().finite().optional(),
102
+ recurringCurrency: currencySchema.optional(),
103
+ nextBillingDate: instantSchema.optional(),
104
+ taxAmount: z.number().finite().optional(),
105
+ customerCredits: z.number().finite().optional(),
106
+ })
107
+ .strict();
108
+ function validatePlanPreview(value, provider, requireNextBillingDate) {
109
+ const parsed = changePlanPreviewSchema.safeParse(value);
110
+ if (!parsed.success) {
111
+ const issue = parsed.error.issues[0];
112
+ throw new ProviderResponseError(provider, "previewChangePlan", {
113
+ details: {
114
+ field: issue?.path.length ? issue.path.join(".") : "response",
115
+ validation: issue?.message,
116
+ },
117
+ cause: parsed.error,
118
+ });
119
+ }
120
+ if (requireNextBillingDate && parsed.data.nextBillingDate === undefined) {
121
+ throw new ProviderResponseError(provider, "previewChangePlan", {
122
+ details: { field: "nextBillingDate" },
123
+ });
124
+ }
125
+ return parsed.data;
126
+ }
74
127
  function quoteFingerprint(preview) {
75
- const amount = (value) => {
76
- const numeric = Number(value);
77
- return Number.isFinite(numeric) ? numeric : null;
78
- };
79
128
  const financialFields = {
80
- totalAmount: amount(preview.totalAmount),
81
- settlementAmount: amount(preview.settlementAmount),
129
+ totalAmount: preview.totalAmount,
130
+ settlementAmount: preview.settlementAmount,
82
131
  currency: preview.currency.toUpperCase(),
83
- recurringAmount: amount(preview.recurringAmount),
132
+ recurringAmount: preview.recurringAmount ?? null,
84
133
  recurringCurrency: preview.recurringCurrency?.toUpperCase() ?? null,
85
- taxAmount: amount(preview.taxAmount),
86
- customerCredits: amount(preview.customerCredits),
134
+ taxAmount: preview.taxAmount ?? null,
135
+ customerCredits: preview.customerCredits ?? null,
136
+ nextBillingDate: preview.nextBillingDate === undefined
137
+ ? null
138
+ : new Date(preview.nextBillingDate).toISOString(),
87
139
  lineItems: preview.lineItems.map((item) => ({
88
140
  productId: item.productId,
89
- unitPrice: amount(item.unitPrice),
90
- quantity: amount(item.quantity),
91
- prorationFactor: amount(item.prorationFactor),
141
+ unitPrice: item.unitPrice,
142
+ quantity: item.quantity,
143
+ prorationFactor: item.prorationFactor,
92
144
  currency: item.currency.toUpperCase(),
93
- tax: amount(item.tax),
94
- subtotal: amount(item.subtotal),
145
+ tax: item.tax,
146
+ subtotal: item.subtotal,
95
147
  })),
96
148
  };
97
149
  return createHash("sha256").update(JSON.stringify(financialFields)).digest("hex");
@@ -182,21 +234,12 @@ export class CommerceService {
182
234
  (!Number.isSafeInteger(options.checkoutIntentTtlMs) || options.checkoutIntentTtlMs <= 0)) {
183
235
  throw new TypeError("checkoutIntentTtlMs must be a positive safe integer");
184
236
  }
237
+ const providerEnvironment = normalizeProviderEnvironment(options.providerEnvironment);
185
238
  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
239
  this.providers = new CommerceProviderRegistry(options, {
197
240
  tenantId: options.tenantId,
241
+ providerEnvironment,
198
242
  eventSink,
199
- identityResolver,
200
243
  });
201
244
  this.autoRecharge = new CommerceAutoRechargeService(this, (name) => this.providers.get(name));
202
245
  }
@@ -239,7 +282,7 @@ export class CommerceService {
239
282
  return 1;
240
283
  }
241
284
  const quantity = requested ?? offer.quantity.default;
242
- if (!Number.isInteger(quantity) || quantity < offer.quantity.minimum) {
285
+ if (!Number.isSafeInteger(quantity) || quantity < offer.quantity.minimum) {
243
286
  throw new InvalidOfferQuantityError(`Minimum quantity is ${offer.quantity.minimum}`, offer.quantity.minimum, offer.quantity.maximum);
244
287
  }
245
288
  if (quantity > offer.quantity.maximum) {
@@ -259,12 +302,10 @@ export class CommerceService {
259
302
  assertCreateCheckoutInput(input);
260
303
  const resolved = await this.resolveOffer(input);
261
304
  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];
305
+ const accountState = await Promise.all([
306
+ this.billing.getBlockingSubscription(input.accountId),
307
+ this.billing.getCustomerByUserId(input.accountId),
308
+ ]);
268
309
  if (resolved.offer.type === "subscription" && accountState[0]) {
269
310
  throw new ActiveSubscriptionError();
270
311
  }
@@ -277,12 +318,10 @@ export class CommerceService {
277
318
  if (!reference)
278
319
  throw new UnknownOfferError("Offer has no reference for the selected provider");
279
320
  const productId = externalId(reference);
280
- const customer = input.accountId
281
- ? await this.billing.getCustomerByUserId(input.accountId, provider.provider)
282
- : null;
321
+ const customer = await this.billing.getCustomerByUserId(input.accountId, provider.provider);
283
322
  const metadata = {
284
323
  ...(input.metadata ?? {}),
285
- ...(input.accountId ? { userId: input.accountId } : {}),
324
+ bursar_account_id: input.accountId,
286
325
  };
287
326
  if (resolved.offer.type === "subscription") {
288
327
  metadata.plan_slug = resolved.offer.plan;
@@ -298,6 +337,7 @@ export class CommerceService {
298
337
  offerKey: resolved.offerKey,
299
338
  provider: provider.provider,
300
339
  quantity,
340
+ accountId: input.accountId,
301
341
  }))
302
342
  .digest("hex");
303
343
  const expiresAt = () => new Date(Date.now() + (this.options.checkoutIntentTtlMs ?? DEFAULT_CHECKOUT_INTENT_TTL_MS)).toISOString();
@@ -337,7 +377,7 @@ export class CommerceService {
337
377
  }
338
378
  try {
339
379
  const session = await provider.createCheckoutSession({
340
- ...(input.accountId ? { userId: input.accountId } : {}),
380
+ accountId: input.accountId,
341
381
  ...(customer?.providerCustomerId ? { customerId: customer.providerCustomerId } : {}),
342
382
  ...(input.email ? { email: input.email } : {}),
343
383
  productId,
@@ -352,9 +392,7 @@ export class CommerceService {
352
392
  providerSessionId: session.providerSessionId,
353
393
  checkoutUrl: session.url,
354
394
  });
355
- if (input.accountId &&
356
- session.customerId &&
357
- session.customerId !== customer?.providerCustomerId) {
395
+ if (session.customerId && session.customerId !== customer?.providerCustomerId) {
358
396
  await this.billing.upsertCustomer(provider.provider, session.customerId, input.accountId, input.email ?? null);
359
397
  }
360
398
  return {
@@ -386,6 +424,7 @@ export class CommerceService {
386
424
  };
387
425
  }
388
426
  async cancelSubscription(input) {
427
+ requireStableKey(input.operationKey, "operationKey");
389
428
  const subscription = await this.billing.getUserSubscription(input.accountId);
390
429
  if (!subscription?.providerSubscriptionId) {
391
430
  throw new CommerceResourceNotFoundError("No active subscription found");
@@ -403,7 +442,7 @@ export class CommerceService {
403
442
  eventId: `cancel_${input.accountId}_${input.operationKey}`,
404
443
  eventType: "subscription.cancellation_scheduled",
405
444
  occurredAt: new Date().toISOString(),
406
- userId: input.accountId,
445
+ accountId: input.accountId,
407
446
  customer: { providerCustomerId: subscription.providerCustomerId },
408
447
  subscription: {
409
448
  providerSubscriptionId: subscription.providerSubscriptionId,
@@ -413,6 +452,7 @@ export class CommerceService {
413
452
  return { ok: true, pending: true };
414
453
  }
415
454
  async reactivateSubscription(input) {
455
+ requireStableKey(input.operationKey, "operationKey");
416
456
  const subscription = await this.billing.getUserSubscription(input.accountId);
417
457
  if (!subscription?.providerSubscriptionId) {
418
458
  throw new CommerceResourceNotFoundError("No subscription found");
@@ -431,7 +471,7 @@ export class CommerceService {
431
471
  eventId: `reactivate_${input.accountId}_${input.operationKey}`,
432
472
  eventType: "subscription.cancellation_unscheduled",
433
473
  occurredAt: new Date().toISOString(),
434
- userId: input.accountId,
474
+ accountId: input.accountId,
435
475
  customer: { providerCustomerId: subscription.providerCustomerId },
436
476
  subscription: {
437
477
  providerSubscriptionId: subscription.providerSubscriptionId,
@@ -441,9 +481,7 @@ export class CommerceService {
441
481
  return { ok: true, pending: true };
442
482
  }
443
483
  async cancelAllSubscriptions(input) {
444
- if (!input.operationKey.trim()) {
445
- throw new ConfigError("operationKey must not be empty");
446
- }
484
+ requireStableKey(input.operationKey, "operationKey");
447
485
  const subscriptions = await this.billing.listCancellableSubscriptions(input.accountId);
448
486
  const results = await Promise.all(subscriptions.map(async (subscription) => {
449
487
  try {
@@ -451,14 +489,17 @@ export class CommerceService {
451
489
  if (!provider.cancelSubscription) {
452
490
  throw new ProviderCapabilityNotSupportedError(provider.provider, "cancelSubscription");
453
491
  }
454
- const operationKey = `${input.operationKey}:${subscription.provider}:${subscription.providerSubscriptionId}`;
492
+ const operationKey = scopedStableKey(input.operationKey, "cancel-all", [
493
+ subscription.provider,
494
+ subscription.providerSubscriptionId,
495
+ ]);
455
496
  await provider.cancelSubscription(subscription.providerSubscriptionId, operationKey);
456
497
  await this.billing.ingestBillingEvent({
457
498
  provider: subscription.provider,
458
499
  eventId: `cancel_all_${input.accountId}_${operationKey}`,
459
500
  eventType: "subscription.cancellation_scheduled",
460
501
  occurredAt: new Date().toISOString(),
461
- userId: input.accountId,
502
+ accountId: input.accountId,
462
503
  customer: { providerCustomerId: subscription.providerCustomerId },
463
504
  subscription: {
464
505
  providerSubscriptionId: subscription.providerSubscriptionId,
@@ -598,11 +639,12 @@ export class CommerceService {
598
639
  if (!context.provider.previewChangePlan) {
599
640
  throw new ProviderCapabilityNotSupportedError(context.provider.provider, "previewChangePlan");
600
641
  }
601
- return context.provider.previewChangePlan({
642
+ const preview = await context.provider.previewChangePlan({
602
643
  providerSubscriptionId: context.subscription.providerSubscriptionId,
603
644
  productId: context.targetProductId,
604
645
  ...providerPlanChangeParams(context.policy),
605
646
  });
647
+ return validatePlanPreview(preview, context.provider.provider, context.policy.effective === "renewal");
606
648
  }
607
649
  async previewPlanChange(input) {
608
650
  const context = await this.planChangeContext(input);
@@ -627,6 +669,7 @@ export class CommerceService {
627
669
  };
628
670
  }
629
671
  async confirmPlanChange(input) {
672
+ requireStableKey(input.operationKey, "operationKey");
630
673
  const context = await this.planChangeContext(input);
631
674
  if (context.classification === "unchanged") {
632
675
  return {
@@ -661,11 +704,7 @@ export class CommerceService {
661
704
  throw new CheckoutConflictError("A plan change is already awaiting payment");
662
705
  }
663
706
  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();
707
+ const effectiveAt = scheduled ? preview.nextBillingDate : preview.effectiveAt;
669
708
  if (!effectiveAt) {
670
709
  throw new CoreBillingDataUnavailableError("The provider did not return the scheduled change date");
671
710
  }
@@ -687,7 +726,7 @@ export class CommerceService {
687
726
  if (!context.provider.cancelSubscription) {
688
727
  throw new ProviderCapabilityNotSupportedError(context.provider.provider, "cancelSubscription");
689
728
  }
690
- await context.provider.reactivateSubscription(context.subscription.providerSubscriptionId, `${input.operationKey}:keep`);
729
+ await context.provider.reactivateSubscription(context.subscription.providerSubscriptionId, scopedStableKey(input.operationKey, "keep"));
691
730
  cancellationWasReactivated = true;
692
731
  }
693
732
  const result = await context.provider.changePlan({
@@ -696,7 +735,7 @@ export class CommerceService {
696
735
  ...providerPlanChangeParams(context.policy),
697
736
  onPaymentFailure: context.policy.paymentFailure,
698
737
  metadata: {
699
- userId: input.accountId,
738
+ bursar_account_id: input.accountId,
700
739
  plan_slug: context.targetOffer.plan,
701
740
  billing_interval: context.targetInterval,
702
741
  },
@@ -710,7 +749,7 @@ export class CommerceService {
710
749
  let failure = error;
711
750
  if (cancellationWasReactivated) {
712
751
  try {
713
- await context.provider.cancelSubscription(context.subscription.providerSubscriptionId, `${input.operationKey}:restore-cancellation`);
752
+ await context.provider.cancelSubscription(context.subscription.providerSubscriptionId, scopedStableKey(input.operationKey, "restore-cancellation"));
714
753
  }
715
754
  catch (compensationError) {
716
755
  failure = new AggregateError([error, compensationError], "Plan change failed and the original subscription cancellation could not be restored");
@@ -732,6 +771,7 @@ export class CommerceService {
732
771
  };
733
772
  }
734
773
  async cancelScheduledPlanChange(input) {
774
+ requireStableKey(input.operationKey, "operationKey");
735
775
  const subscription = await this.billing.getActiveSubscription(input.accountId);
736
776
  if (!subscription)
737
777
  throw new CommerceResourceNotFoundError("No active subscription found");