@owlmeans/server-payment 0.1.22-rc.0 → 0.2.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (296) hide show
  1. package/README.md +52 -54
  2. package/agent-meta/manifest.json +2 -2
  3. package/agent-meta/skills/server-payment/SKILL.md +272 -330
  4. package/agent-meta/skills/server-payment/parts/reference.md +3 -3
  5. package/build/access/types.d.ts +7 -16
  6. package/build/access/types.d.ts.map +1 -1
  7. package/build/access.d.ts.map +1 -1
  8. package/build/access.js +6 -8
  9. package/build/access.js.map +1 -1
  10. package/build/actions/resync.d.ts +3 -3
  11. package/build/actions/resync.js +5 -5
  12. package/build/actions/resync.js.map +1 -1
  13. package/build/actions/webhook.d.ts +4 -1
  14. package/build/actions/webhook.d.ts.map +1 -1
  15. package/build/actions/webhook.js +8 -4
  16. package/build/actions/webhook.js.map +1 -1
  17. package/build/bootstrap/types.d.ts +13 -7
  18. package/build/bootstrap/types.d.ts.map +1 -1
  19. package/build/bootstrap.d.ts +4 -4
  20. package/build/bootstrap.d.ts.map +1 -1
  21. package/build/bootstrap.js +19 -10
  22. package/build/bootstrap.js.map +1 -1
  23. package/build/catalogue/types.d.ts +3 -3
  24. package/build/catalogue/types.d.ts.map +1 -1
  25. package/build/catalogue.d.ts.map +1 -1
  26. package/build/catalogue.js +4 -8
  27. package/build/catalogue.js.map +1 -1
  28. package/build/checkout/types.d.ts +21 -0
  29. package/build/checkout/types.d.ts.map +1 -0
  30. package/build/{plugins/stripe → checkout}/types.js.map +1 -1
  31. package/build/checkout.d.ts +6 -0
  32. package/build/checkout.d.ts.map +1 -0
  33. package/build/checkout.js +374 -0
  34. package/build/checkout.js.map +1 -0
  35. package/build/config.d.ts +10 -16
  36. package/build/config.d.ts.map +1 -1
  37. package/build/config.js +18 -59
  38. package/build/config.js.map +1 -1
  39. package/build/consts.d.ts +3 -49
  40. package/build/consts.d.ts.map +1 -1
  41. package/build/consts.js +3 -61
  42. package/build/consts.js.map +1 -1
  43. package/build/consumer/cancellation/types.d.ts +6 -4
  44. package/build/consumer/cancellation/types.d.ts.map +1 -1
  45. package/build/consumer/cancellation.d.ts.map +1 -1
  46. package/build/consumer/cancellation.js +11 -5
  47. package/build/consumer/cancellation.js.map +1 -1
  48. package/build/consumer/capture/types.d.ts +8 -12
  49. package/build/consumer/capture/types.d.ts.map +1 -1
  50. package/build/consumer/capture.d.ts.map +1 -1
  51. package/build/consumer/capture.js +48 -53
  52. package/build/consumer/capture.js.map +1 -1
  53. package/build/consumer/index.d.ts +4 -0
  54. package/build/consumer/index.d.ts.map +1 -1
  55. package/build/consumer/index.js +2 -0
  56. package/build/consumer/index.js.map +1 -1
  57. package/build/consumer/reconcile.d.ts.map +1 -1
  58. package/build/consumer/reconcile.js +82 -72
  59. package/build/consumer/reconcile.js.map +1 -1
  60. package/build/consumer/records/types.d.ts +4 -4
  61. package/build/consumer/records/types.d.ts.map +1 -1
  62. package/build/consumer/records.d.ts.map +1 -1
  63. package/build/consumer/records.js +16 -13
  64. package/build/consumer/records.js.map +1 -1
  65. package/build/consumer/service.d.ts +2 -2
  66. package/build/consumer/service.d.ts.map +1 -1
  67. package/build/consumer/service.js +28 -21
  68. package/build/consumer/service.js.map +1 -1
  69. package/build/consumer/types.d.ts +1 -4
  70. package/build/consumer/types.d.ts.map +1 -1
  71. package/build/consumer/types.local.d.ts +1 -9
  72. package/build/consumer/types.local.d.ts.map +1 -1
  73. package/build/consumer/withdrawal/types.d.ts +14 -12
  74. package/build/consumer/withdrawal/types.d.ts.map +1 -1
  75. package/build/consumer/withdrawal.d.ts.map +1 -1
  76. package/build/consumer/withdrawal.js +55 -71
  77. package/build/consumer/withdrawal.js.map +1 -1
  78. package/build/index.d.ts +12 -6
  79. package/build/index.d.ts.map +1 -1
  80. package/build/index.js +7 -4
  81. package/build/index.js.map +1 -1
  82. package/build/paygate/providers.d.ts +13 -0
  83. package/build/paygate/providers.d.ts.map +1 -0
  84. package/build/paygate/providers.js +38 -0
  85. package/build/paygate/providers.js.map +1 -0
  86. package/build/paygate/registry.d.ts +6 -0
  87. package/build/paygate/registry.d.ts.map +1 -0
  88. package/build/paygate/registry.js +37 -0
  89. package/build/paygate/registry.js.map +1 -0
  90. package/build/paygate/types.d.ts +577 -0
  91. package/build/paygate/types.d.ts.map +1 -0
  92. package/build/{plugins/session → paygate}/types.js.map +1 -1
  93. package/build/plan/types.d.ts +6 -1
  94. package/build/plan/types.d.ts.map +1 -1
  95. package/build/plan.d.ts.map +1 -1
  96. package/build/plan.js +16 -2
  97. package/build/plan.js.map +1 -1
  98. package/build/plugins/checkout-policy/types.d.ts +5 -3
  99. package/build/plugins/checkout-policy/types.d.ts.map +1 -1
  100. package/build/plugins/checkout-policy.d.ts.map +1 -1
  101. package/build/plugins/checkout-policy.js +5 -3
  102. package/build/plugins/checkout-policy.js.map +1 -1
  103. package/build/plugins/consts.local.d.ts +8 -10
  104. package/build/plugins/consts.local.d.ts.map +1 -1
  105. package/build/plugins/consts.local.js +2 -19
  106. package/build/plugins/consts.local.js.map +1 -1
  107. package/build/plugins/customer-lock/types.d.ts +2 -2
  108. package/build/plugins/customer-lock/types.d.ts.map +1 -1
  109. package/build/plugins/customer-lock.js +2 -2
  110. package/build/plugins/customer-lock.js.map +1 -1
  111. package/build/plugins/estimate/cache.js +1 -1
  112. package/build/plugins/estimate/cache.js.map +1 -1
  113. package/build/plugins/estimate/types.d.ts +10 -10
  114. package/build/plugins/estimate/types.d.ts.map +1 -1
  115. package/build/plugins/estimate.d.ts.map +1 -1
  116. package/build/plugins/estimate.js +48 -122
  117. package/build/plugins/estimate.js.map +1 -1
  118. package/build/plugins/events/types.d.ts +17 -10
  119. package/build/plugins/events/types.d.ts.map +1 -1
  120. package/build/plugins/events.d.ts +6 -5
  121. package/build/plugins/events.d.ts.map +1 -1
  122. package/build/plugins/events.js +162 -173
  123. package/build/plugins/events.js.map +1 -1
  124. package/build/plugins/fx/types.d.ts +10 -21
  125. package/build/plugins/fx/types.d.ts.map +1 -1
  126. package/build/plugins/fx.d.ts +1 -1
  127. package/build/plugins/fx.d.ts.map +1 -1
  128. package/build/plugins/fx.js +17 -54
  129. package/build/plugins/fx.js.map +1 -1
  130. package/build/plugins/portal/types.d.ts +8 -37
  131. package/build/plugins/portal/types.d.ts.map +1 -1
  132. package/build/plugins/portal.d.ts.map +1 -1
  133. package/build/plugins/portal.js +38 -208
  134. package/build/plugins/portal.js.map +1 -1
  135. package/build/plugins/refunds/types.d.ts +11 -11
  136. package/build/plugins/refunds/types.d.ts.map +1 -1
  137. package/build/plugins/refunds.d.ts.map +1 -1
  138. package/build/plugins/refunds.js +14 -39
  139. package/build/plugins/refunds.js.map +1 -1
  140. package/build/plugins/snapshot/types.d.ts +11 -0
  141. package/build/plugins/snapshot/types.d.ts.map +1 -0
  142. package/build/plugins/snapshot/types.js +2 -0
  143. package/build/plugins/snapshot/types.js.map +1 -0
  144. package/build/plugins/snapshot.d.ts +4 -0
  145. package/build/plugins/snapshot.d.ts.map +1 -0
  146. package/build/plugins/snapshot.js +19 -0
  147. package/build/plugins/snapshot.js.map +1 -0
  148. package/build/plugins/subscriptions/types.d.ts +17 -17
  149. package/build/plugins/subscriptions/types.d.ts.map +1 -1
  150. package/build/plugins/subscriptions.d.ts +4 -4
  151. package/build/plugins/subscriptions.d.ts.map +1 -1
  152. package/build/plugins/subscriptions.js +69 -77
  153. package/build/plugins/subscriptions.js.map +1 -1
  154. package/build/plugins/types.local.d.ts +9 -43
  155. package/build/plugins/types.local.d.ts.map +1 -1
  156. package/build/plugins/webhook-manager/types.d.ts +15 -43
  157. package/build/plugins/webhook-manager/types.d.ts.map +1 -1
  158. package/build/plugins/webhook-manager.d.ts +3 -3
  159. package/build/plugins/webhook-manager.d.ts.map +1 -1
  160. package/build/plugins/webhook-manager.js +21 -199
  161. package/build/plugins/webhook-manager.js.map +1 -1
  162. package/build/protocol.d.ts +1 -1
  163. package/build/protocol.d.ts.map +1 -1
  164. package/build/protocol.js +1 -1
  165. package/build/protocol.js.map +1 -1
  166. package/build/service.d.ts +11 -11
  167. package/build/service.d.ts.map +1 -1
  168. package/build/service.js +59 -23
  169. package/build/service.js.map +1 -1
  170. package/build/sync/types.d.ts +17 -13
  171. package/build/sync/types.d.ts.map +1 -1
  172. package/build/sync.d.ts.map +1 -1
  173. package/build/sync.js +22 -122
  174. package/build/sync.js.map +1 -1
  175. package/build/types.d.ts +46 -101
  176. package/build/types.d.ts.map +1 -1
  177. package/build/utils/types.d.ts +0 -8
  178. package/build/utils/types.d.ts.map +1 -1
  179. package/build/utils.d.ts +1 -4
  180. package/build/utils.d.ts.map +1 -1
  181. package/build/utils.js +1 -15
  182. package/build/utils.js.map +1 -1
  183. package/package.json +20 -22
  184. package/src/access/types.ts +7 -16
  185. package/src/access.ts +7 -15
  186. package/src/actions/resync.ts +5 -5
  187. package/src/actions/webhook.ts +8 -4
  188. package/src/bootstrap/types.ts +13 -7
  189. package/src/bootstrap.ts +23 -13
  190. package/src/catalogue/types.ts +3 -3
  191. package/src/catalogue.ts +4 -8
  192. package/src/checkout/types.ts +21 -0
  193. package/src/checkout.ts +414 -0
  194. package/src/config.ts +19 -66
  195. package/src/consts.ts +3 -69
  196. package/src/consumer/cancellation/types.ts +6 -4
  197. package/src/consumer/cancellation.ts +13 -7
  198. package/src/consumer/capture/types.ts +8 -12
  199. package/src/consumer/capture.ts +50 -59
  200. package/src/consumer/index.ts +4 -0
  201. package/src/consumer/reconcile.ts +69 -68
  202. package/src/consumer/records/types.ts +4 -4
  203. package/src/consumer/records.ts +19 -14
  204. package/src/consumer/service.ts +35 -22
  205. package/src/consumer/types.local.ts +1 -8
  206. package/src/consumer/types.ts +1 -4
  207. package/src/consumer/withdrawal/types.ts +14 -12
  208. package/src/consumer/withdrawal.ts +61 -77
  209. package/src/index.ts +12 -6
  210. package/src/paygate/providers.ts +48 -0
  211. package/src/paygate/registry.ts +53 -0
  212. package/src/paygate/types.ts +640 -0
  213. package/src/plan/types.ts +6 -1
  214. package/src/plan.ts +21 -3
  215. package/src/plugins/checkout-policy/types.ts +5 -3
  216. package/src/plugins/checkout-policy.ts +6 -5
  217. package/src/plugins/consts.local.ts +2 -26
  218. package/src/plugins/customer-lock/types.ts +2 -2
  219. package/src/plugins/customer-lock.ts +2 -2
  220. package/src/plugins/estimate/cache.ts +1 -1
  221. package/src/plugins/estimate/types.ts +10 -10
  222. package/src/plugins/estimate.ts +52 -128
  223. package/src/plugins/events/types.ts +17 -9
  224. package/src/plugins/events.ts +172 -190
  225. package/src/plugins/fx/types.ts +10 -23
  226. package/src/plugins/fx.ts +28 -64
  227. package/src/plugins/portal/types.ts +8 -38
  228. package/src/plugins/portal.ts +48 -229
  229. package/src/plugins/refunds/types.ts +11 -11
  230. package/src/plugins/refunds.ts +16 -40
  231. package/src/plugins/snapshot/types.ts +11 -0
  232. package/src/plugins/snapshot.ts +22 -0
  233. package/src/plugins/subscriptions/types.ts +17 -17
  234. package/src/plugins/subscriptions.ts +81 -81
  235. package/src/plugins/types.local.ts +9 -33
  236. package/src/plugins/webhook-manager/types.ts +15 -43
  237. package/src/plugins/webhook-manager.ts +24 -220
  238. package/src/protocol.ts +1 -1
  239. package/src/service.ts +66 -30
  240. package/src/sync/types.ts +17 -13
  241. package/src/sync.ts +25 -143
  242. package/src/types.ts +47 -97
  243. package/src/utils/types.ts +0 -9
  244. package/src/utils.ts +2 -20
  245. package/tests/capabilities.spec.ts +219 -0
  246. package/tests/entitlement.spec.ts +4 -4
  247. package/tests/gate-handlers.spec.ts +6 -6
  248. package/tests/gate.spec.ts +2 -2
  249. package/tests/grants.spec.ts +2 -2
  250. package/tests/internal-plan.spec.ts +2 -2
  251. package/tests/limit-gate.spec.ts +2 -2
  252. package/tests/paygates.spec.ts +132 -0
  253. package/tests/protocol.spec.ts +4 -5
  254. package/tests/usage.spec.ts +2 -2
  255. package/tests/webhook.spec.ts +137 -0
  256. package/build/plugins/session/types.d.ts +0 -34
  257. package/build/plugins/session/types.d.ts.map +0 -1
  258. package/build/plugins/session.d.ts +0 -4
  259. package/build/plugins/session.d.ts.map +0 -1
  260. package/build/plugins/session.js +0 -71
  261. package/build/plugins/session.js.map +0 -1
  262. package/build/plugins/status.d.ts +0 -8
  263. package/build/plugins/status.d.ts.map +0 -1
  264. package/build/plugins/status.js +0 -21
  265. package/build/plugins/status.js.map +0 -1
  266. package/build/plugins/stripe/types.d.ts +0 -20
  267. package/build/plugins/stripe/types.d.ts.map +0 -1
  268. package/build/plugins/stripe.d.ts +0 -6
  269. package/build/plugins/stripe.d.ts.map +0 -1
  270. package/build/plugins/stripe.js +0 -518
  271. package/build/plugins/stripe.js.map +0 -1
  272. package/src/plugins/session/types.ts +0 -30
  273. package/src/plugins/session.ts +0 -86
  274. package/src/plugins/status.ts +0 -22
  275. package/src/plugins/stripe/types.ts +0 -20
  276. package/src/plugins/stripe.ts +0 -571
  277. package/tests/checkout-consumer.spec.ts +0 -366
  278. package/tests/checkout-locks.spec.ts +0 -161
  279. package/tests/checkout-plugins.spec.ts +0 -164
  280. package/tests/checkout.spec.ts +0 -313
  281. package/tests/consumer-events.spec.ts +0 -215
  282. package/tests/consumer-fixtures.ts +0 -141
  283. package/tests/consumer-ops.spec.ts +0 -361
  284. package/tests/consumer-rights.integration.spec.ts +0 -147
  285. package/tests/consumer-rights.spec.ts +0 -606
  286. package/tests/context.ts +0 -110
  287. package/tests/estimate.spec.ts +0 -350
  288. package/tests/events.spec.ts +0 -367
  289. package/tests/fake-stripe.ts +0 -1004
  290. package/tests/gateway-options.spec.ts +0 -180
  291. package/tests/portal.spec.ts +0 -202
  292. package/tests/sync.spec.ts +0 -114
  293. package/tests/usage.integration.spec.ts +0 -165
  294. package/tests/webhook-manager.spec.ts +0 -149
  295. /package/build/{plugins/session → checkout}/types.js +0 -0
  296. /package/build/{plugins/stripe → paygate}/types.js +0 -0
@@ -1,1004 +0,0 @@
1
- import Stripe from 'stripe'
2
- import { config as serverConfig, makeServerContext, type ServerConfig } from '@owlmeans/server-context'
3
- import { AppType } from '@owlmeans/context'
4
- import {
5
- CheckoutPricingMode, LimitKind, LimitWindow, PlanDuration, ProductType, type PlanCapability,
6
- } from '@owlmeans/payment'
7
- import { RecordExists, UnknownRecordError, type Criteria, type ListOptions, type ResourceRecord, recordQueryHelper } from '@owlmeans/resource'
8
- import type { MongoResource } from '@owlmeans/mongo-resource'
9
- import { makeConsoleMailerService, MAILER_SERVICE, type MailMessage } from '@owlmeans/mailer'
10
- import type { Context as ApiContext } from '@owlmeans/server-api'
11
- import {
12
- declareConsumerRights, declarePaymentPlan, declarePaymentPricing, declarePaymentProduct, portalBranding,
13
- stripeSecrets,
14
- } from '../src/config.js'
15
- import {
16
- RES_BILLING_PROFILE, RES_CONSUMER_CONSENT, RES_CONSUMER_DECLARATION, RES_CONSUMER_EVENT, RES_PAYGATE_CUSTOMER,
17
- RES_PAYMENT_FINGERPRINT, RES_PAYMENT_FULFILLMENT, RES_PAYMENT_GRANT, RES_PAYMENT_PURCHASE, RES_PAYMENT_SUBSCRIPTION,
18
- RES_PAYMENT_USAGE, RES_PAYMENT_USAGE_COUNTER, RES_PAYMENT_WEBHOOK,
19
- } from '../src/consts.js'
20
- import { appendConsumerRights } from '../src/consumer/service.js'
21
- import {
22
- makeBillingProfileResource, makeConsumerConsentResource, makeConsumerDeclarationResource,
23
- makeConsumerEventResource, makeFingerprintResource, makeFulfillmentResource, makeGrantResource,
24
- makePaygateCustomerResource, makePurchaseResource, makeSubscriptionResource, makeUsageCounterResource, makeUsageResource, makeWebhookResource,
25
- } from '../src/resource.js'
26
- import { appendPaymentGatewayService } from '../src/service.js'
27
- import type {
28
- GatewayServiceOptions, CancellationEvent, Config, ConsentEvent, ConsumerRightsDef, ConsumerRightsOptions,
29
- DisputeEvent, EntitlementGrantEvent, PaymentFailedEvent, PaymentPlanDef, PortalBrandingDef, PricingDef, RefundEvent, SubscriptionEvent,
30
- TopUpCompletion, UsageMeter, WithdrawalEvent,
31
- } from '../src/types.js'
32
- import { paymentAccessOf } from '../src/access.js'
33
-
34
- // -----------------------------------------------------------------------------------------------
35
- // Catalogue — neutral names only
36
- // -----------------------------------------------------------------------------------------------
37
-
38
- export const SERVICE = 'app'
39
- export const HOST = 'api.example.com'
40
- export const PLANS_PRODUCT = 'app-plans'
41
- export const CREDITS_PRODUCT = 'app-credits'
42
- export const FREE = 'free-plan'
43
- export const PRO = 'pro-monthly'
44
- export const TEAM = 'team-monthly'
45
- export const CREDIT_UNIT = 'app-credit-unit'
46
- export const CAP_WHITELABEL = 'feature:whitelabel'
47
- export const CAP_BASIC = 'feature:basic'
48
- export const CAP_PREVIEW = 'feature:preview'
49
-
50
- const DAY = 24 * 60 * 60 * 1000
51
- export const future = (days = 30): Date => new Date(Date.now() + days * DAY)
52
- export const past = (days = 30): Date => new Date(Date.now() - days * DAY)
53
-
54
- export interface CatalogueOptions {
55
- /** Declare the free plan (default true). */
56
- free?: boolean
57
- /** Until when the `feature:preview` promo of the free plan runs (default: in 30 days). */
58
- previewUntil?: Date
59
- /** Until when the `reports` promo of the pro plan runs (default: in 30 days). */
60
- reportsUntil?: Date
61
- /** Extra plans. */
62
- plans?: PaymentPlanDef[]
63
- }
64
-
65
- export const declareTestCatalogue = (cfg: Config, opts: CatalogueOptions = {}): void => {
66
- declarePaymentProduct(cfg, {
67
- sku: CREDITS_PRODUCT, type: ProductType.Consumable, services: [SERVICE], name: 'Credits',
68
- })
69
- declarePaymentPlan(cfg, {
70
- productSku: CREDITS_PRODUCT, sku: CREDIT_UNIT, duration: PlanDuration.Consumable, price: 0.02,
71
- pricingMode: CheckoutPricingMode.Amount,
72
- amountPolicy: {
73
- currency: 'usd', minimumMinor: 500, maximumMinor: 50_000, defaultMinor: 1_000,
74
- presetsMinor: [1_000, 2_000, 5_000, 10_000], fixedMinor: 0, rateBps: 200,
75
- },
76
- })
77
- declarePaymentProduct(cfg, {
78
- sku: PLANS_PRODUCT, type: ProductType.Service, services: [SERVICE], name: 'Plans',
79
- })
80
- if (opts.free !== false) {
81
- declarePaymentPlan(cfg, {
82
- productSku: PLANS_PRODUCT, sku: FREE, duration: PlanDuration.Monthly, rank: 0, free: true, price: 0,
83
- capabilities: [
84
- { scope: 'feature', permissions: { basic: true } },
85
- { scope: 'feature', permissions: { preview: true }, promo: { until: opts.previewUntil ?? future() } },
86
- ] satisfies PlanCapability[],
87
- limits: {
88
- seats: { kind: LimitKind.Occupancy, limit: 0 },
89
- exports: { kind: LimitKind.Window, window: LimitWindow.Month, limit: 1 },
90
- reports: { kind: LimitKind.Lifetime, limit: 1 },
91
- },
92
- })
93
- }
94
- declarePaymentPlan(cfg, {
95
- productSku: PLANS_PRODUCT, sku: PRO, duration: PlanDuration.Monthly, rank: 10, price: 20,
96
- recurring: { interval: 'month' },
97
- capabilities: [{ scope: 'feature', permissions: { basic: true, whitelabel: true, preview: true } }],
98
- limits: {
99
- seats: { kind: LimitKind.Occupancy, limit: 2 },
100
- exports: { kind: LimitKind.Window, window: LimitWindow.Day, limit: 3 },
101
- reports: {
102
- kind: LimitKind.Lifetime, limit: 4, promo: { until: opts.reportsUntil ?? future(), grandfather: true },
103
- },
104
- },
105
- })
106
- declarePaymentPlan(cfg, {
107
- productSku: PLANS_PRODUCT, sku: TEAM, duration: PlanDuration.Monthly, rank: 20, price: 50,
108
- recurring: { interval: 'month' },
109
- capabilities: [{ scope: 'feature', permissions: { basic: true, whitelabel: true, preview: true } }],
110
- limits: {
111
- seats: { kind: LimitKind.Occupancy, limit: 10 },
112
- exports: { kind: LimitKind.Window, window: LimitWindow.Day, limit: 30 },
113
- reports: { kind: LimitKind.Lifetime, limit: 40 },
114
- },
115
- })
116
- for (const plan of opts.plans ?? []) {
117
- declarePaymentPlan(cfg, plan)
118
- }
119
- }
120
-
121
- // -----------------------------------------------------------------------------------------------
122
- // Fake Stripe
123
- // -----------------------------------------------------------------------------------------------
124
-
125
- type Rec = Record<string, any>
126
-
127
- export type FakeFailure = string | Error
128
-
129
- export interface FakeStripeState {
130
- apiVersion: string
131
- /** Every SDK method called, in order: `webhookEndpoints.create`, … */
132
- calls: string[]
133
- webhookEndpoints: Rec[]
134
- portalConfigurations: Rec[]
135
- /** The params every portal session was asked for with. */
136
- portalSessions: Rec[]
137
- checkoutSessions: Rec[]
138
- subscriptions: Record<string, Rec>
139
- invoices: Record<string, Rec>
140
- charges: Record<string, Rec>
141
- refunds: Rec[]
142
- prices: Rec[]
143
- products: Record<string, Rec>
144
- customers: Record<string, Rec>
145
- lineItemQuantity: number
146
- seq: number
147
- /** Every `tax.calculations.create` params, in call order. */
148
- taxCalculations: Rec[]
149
- /** Flat-percentage rates a country charges (uppercase alpha-2). Absent/empty: `not_collecting`. */
150
- taxRates: Record<string, Array<{ type: string, percentage: string }>>
151
- /** Countries whose calculation throws `customer_tax_location_invalid` (simulates a missing ZIP). */
152
- taxInvalidCountries: string[]
153
- /** Countries Stripe Tax does not cover: a `not_supported`, zero-tax breakdown row. */
154
- taxUnsupportedCountries: string[]
155
- taxSettings: Rec
156
- /** Every `rawRequest` call, in order: `{ method, path, params }`. */
157
- rawRequests: Rec[]
158
- /** FX Quotes rates by lowercase source currency. */
159
- fxRates: Record<string, { exchangeRate: number, baseRate?: number, referenceRate?: number, fxFeeRate?: number }>
160
- /** Every `rawRequest` to `/v1/fx_quotes` throws. */
161
- fxUnavailable: boolean
162
- /** Completed or open checkout sessions `checkout.sessions.list` answers. */
163
- listedSessions: Rec[]
164
- creditNotes: Rec[]
165
- /** Every `creditNotes.preview` params. */
166
- creditNotePreviews: Rec[]
167
- /** Every call's request options (`idempotencyKey`), by method. */
168
- requestOptions: Record<string, Rec[]>
169
- /**
170
- * Methods that throw on their next call: name → an error message (a Stripe invalid-request
171
- * error), an error to throw as it is, or a list of those — one per call, in order.
172
- */
173
- failures: Record<string, FakeFailure | FakeFailure[]>
174
- /** Every `subscriptions.update` / `.cancel` params, in order. */
175
- subscriptionChanges: Rec[]
176
- expiredSessions: string[]
177
- }
178
-
179
- /** The API version the installed SDK defaults to, read from a real client. */
180
- export const SDK_API_VERSION = (new Stripe('sk_test_offline') as unknown as { getApiField: (key: string) => string })
181
- .getApiField('version')
182
-
183
- export const missing = (what: string): Error => Object.assign(new Error(`No such ${what}`), {
184
- type: 'StripeInvalidRequestError', code: 'resource_missing', statusCode: 404,
185
- })
186
-
187
- /** A Stripe `invalid_request_error`, duck-typed the same way `missing` fakes `resource_missing`. */
188
- export const invalidRequest = (code: string): Error => Object.assign(new Error(code), {
189
- type: 'StripeInvalidRequestError', code, statusCode: 400,
190
- })
191
-
192
- const page = (items: Rec[], params: Rec = {}) => {
193
- let start = 0
194
- if (params.starting_after != null) {
195
- start = items.findIndex(item => item.id === params.starting_after) + 1
196
- }
197
- const limit = params.limit ?? 10
198
- const data = items.slice(start, start + limit)
199
-
200
- return { object: 'list', data: structuredClone(data), has_more: start + limit < items.length }
201
- }
202
-
203
- export const makeFakeStripe = (initial: Partial<FakeStripeState> = {}): { stripe: Stripe, state: FakeStripeState } => {
204
- const state: FakeStripeState = {
205
- apiVersion: SDK_API_VERSION, calls: [], webhookEndpoints: [], portalConfigurations: [], portalSessions: [],
206
- checkoutSessions: [], subscriptions: {}, invoices: {}, charges: {}, refunds: [], prices: [], products: {},
207
- customers: {}, lineItemQuantity: 7, seq: 0,
208
- taxCalculations: [], taxRates: {}, taxInvalidCountries: [], taxUnsupportedCountries: [],
209
- taxSettings: { defaults: { tax_behavior: null, tax_code: null }, head_office: null, status: 'active', status_details: {} },
210
- rawRequests: [], fxRates: {}, fxUnavailable: false,
211
- listedSessions: [], creditNotes: [], creditNotePreviews: [], requestOptions: {}, failures: {},
212
- subscriptionChanges: [], expiredSessions: [],
213
- ...initial,
214
- }
215
- const next = (prefix: string): string => `${prefix}_${++state.seq}`
216
- const call = (name: string, options?: Rec): void => {
217
- state.calls.push(name)
218
- if (options != null) (state.requestOptions[name] = state.requestOptions[name] ?? []).push(options)
219
- const failure = state.failures[name]
220
- if (failure != null) {
221
- const next = Array.isArray(failure) ? failure.shift() : failure
222
- if (!Array.isArray(failure) || failure.length === 0) delete state.failures[name]
223
- if (next != null) throw typeof next === 'string' ? invalidRequest(next) : next
224
- }
225
- }
226
- const find = (list: Rec[], id: string, what: string): Rec => {
227
- const found = list.find(item => item.id === id)
228
- if (found == null) throw missing(what)
229
- return found
230
- }
231
-
232
- const stripe = {
233
- getApiField: (key: string) => key === 'version' ? state.apiVersion : undefined,
234
- webhookEndpoints: {
235
- create: async (params: Rec) => {
236
- call('webhookEndpoints.create')
237
- const endpoint = {
238
- id: next('we'), object: 'webhook_endpoint', url: params.url, enabled_events: [...params.enabled_events],
239
- api_version: params.api_version, description: params.description, metadata: { ...params.metadata },
240
- status: 'enabled', secret: next('whsec'),
241
- }
242
- state.webhookEndpoints.push(endpoint)
243
- return structuredClone(endpoint)
244
- },
245
- update: async (id: string, params: Rec) => {
246
- call('webhookEndpoints.update')
247
- const endpoint = find(state.webhookEndpoints, id, 'webhook endpoint')
248
- Object.assign(endpoint, params)
249
- const { secret: _secret, ...rest } = endpoint
250
- return structuredClone(rest)
251
- },
252
- retrieve: async (id: string) => {
253
- call('webhookEndpoints.retrieve')
254
- const { secret: _secret, ...rest } = find(state.webhookEndpoints, id, 'webhook endpoint')
255
- return structuredClone(rest)
256
- },
257
- del: async (id: string) => {
258
- call('webhookEndpoints.del')
259
- find(state.webhookEndpoints, id, 'webhook endpoint')
260
- state.webhookEndpoints = state.webhookEndpoints.filter(item => item.id !== id)
261
- return { id, object: 'webhook_endpoint', deleted: true }
262
- },
263
- list: async (params: Rec = {}) => {
264
- call('webhookEndpoints.list')
265
- return page(state.webhookEndpoints.map(({ secret: _secret, ...rest }) => rest), params)
266
- },
267
- },
268
- billingPortal: {
269
- configurations: {
270
- create: async (params: Rec) => {
271
- call('billingPortal.configurations.create')
272
- const configuration = { id: next('bpc'), object: 'billing_portal.configuration', active: true, ...structuredClone(params) }
273
- state.portalConfigurations.push(configuration)
274
- return structuredClone(configuration)
275
- },
276
- retrieve: async (id: string) => {
277
- call('billingPortal.configurations.retrieve')
278
- return structuredClone(find(state.portalConfigurations, id, 'configuration'))
279
- },
280
- update: async (id: string, params: Rec) => {
281
- call('billingPortal.configurations.update')
282
- const configuration = find(state.portalConfigurations, id, 'configuration')
283
- Object.assign(configuration, structuredClone(params))
284
- return structuredClone(configuration)
285
- },
286
- list: async (params: Rec = {}) => {
287
- call('billingPortal.configurations.list')
288
- return page(state.portalConfigurations.filter(item => params.active == null || item.active === params.active), params)
289
- },
290
- },
291
- sessions: {
292
- create: async (params: Rec) => {
293
- call('billingPortal.sessions.create')
294
- state.portalSessions.push(structuredClone(params))
295
- return { id: next('bps'), url: `https://billing.example.test/p/${state.seq}` }
296
- },
297
- },
298
- },
299
- subscriptions: {
300
- retrieve: async (id: string) => {
301
- call('subscriptions.retrieve')
302
- const subscription = state.subscriptions[id]
303
- if (subscription == null) throw missing('subscription')
304
- return structuredClone(subscription)
305
- },
306
- update: async (id: string, params: Rec, options?: Rec) => {
307
- call('subscriptions.update', options)
308
- const subscription = state.subscriptions[id]
309
- if (subscription == null) throw missing('subscription')
310
- state.subscriptionChanges.push({ id, method: 'update', ...structuredClone(params) })
311
- Object.assign(subscription, params)
312
- return structuredClone(subscription)
313
- },
314
- cancel: async (id: string, params: Rec = {}, options?: Rec) => {
315
- call('subscriptions.cancel', options)
316
- const subscription = state.subscriptions[id]
317
- if (subscription == null) throw missing('subscription')
318
- state.subscriptionChanges.push({ id, method: 'cancel', ...structuredClone(params) })
319
- subscription.status = 'canceled'
320
- return structuredClone(subscription)
321
- },
322
- },
323
- creditNotes: {
324
- preview: async (params: Rec) => {
325
- call('creditNotes.preview')
326
- state.creditNotePreviews.push(structuredClone(params))
327
- const invoice = state.invoices[params.invoice]
328
- if (invoice == null) throw missing('invoice')
329
- const discount = (invoice.total_discount_amounts ?? []).reduce((sum: number, item: Rec) => sum + item.amount, 0)
330
- const net = invoice.subtotal - discount
331
- const rate = net > 0 ? (invoice.tax ?? 0) / net : 0
332
- const amount = params.lines.reduce((sum: number, line: Rec) => sum + (line.amount ?? 0), 0)
333
- const discounted = amount - (invoice.subtotal > 0 ? Math.round(amount * discount / invoice.subtotal) : 0)
334
- const tax = Math.round(discounted * rate)
335
- return { id: 'cnpreview', object: 'credit_note', amount: discounted + tax, total: discounted + tax, subtotal: amount, currency: invoice.currency }
336
- },
337
- create: async (params: Rec, options?: Rec) => {
338
- call('creditNotes.create', options)
339
- const invoice = state.invoices[params.invoice]
340
- if (invoice == null) throw missing('invoice')
341
- const discount = (invoice.total_discount_amounts ?? []).reduce((sum: number, item: Rec) => sum + item.amount, 0)
342
- const net = invoice.subtotal - discount
343
- const rate = net > 0 ? (invoice.tax ?? 0) / net : 0
344
- const amount = params.lines.reduce((sum: number, line: Rec) => sum + (line.amount ?? 0), 0)
345
- const discounted = amount - (invoice.subtotal > 0 ? Math.round(amount * discount / invoice.subtotal) : 0)
346
- const note = {
347
- id: next('cn'), object: 'credit_note', invoice: params.invoice, refund: params.refund, status: 'issued',
348
- total: discounted + Math.round(discounted * rate), currency: invoice.currency, memo: params.memo,
349
- metadata: { ...params.metadata }, lines: structuredClone(params.lines),
350
- }
351
- state.creditNotes.push(note)
352
- return structuredClone(note)
353
- },
354
- list: async (params: Rec = {}) => {
355
- call('creditNotes.list')
356
- return page(state.creditNotes.filter(note => params.invoice == null || note.invoice === params.invoice), params)
357
- },
358
- },
359
- invoices: {
360
- retrieve: async (id: string) => {
361
- call('invoices.retrieve')
362
- const invoice = state.invoices[id]
363
- if (invoice == null) throw missing('invoice')
364
- return structuredClone(invoice)
365
- },
366
- },
367
- charges: {
368
- retrieve: async (id: string) => {
369
- call('charges.retrieve')
370
- const charge = state.charges[id]
371
- if (charge == null) throw missing('charge')
372
- return structuredClone(charge)
373
- },
374
- },
375
- refunds: {
376
- list: async (params: Rec = {}) => {
377
- call('refunds.list')
378
- return page(state.refunds.filter(refund => (params.charge == null || refund.charge === params.charge)
379
- && (params.payment_intent == null || refund.payment_intent === params.payment_intent)), params)
380
- },
381
- create: async (params: Rec, options?: Rec) => {
382
- call('refunds.create', options)
383
- const refund = {
384
- id: next('re'), object: 'refund', amount: params.amount, currency: params.currency ?? 'eur', status: 'succeeded',
385
- payment_intent: params.payment_intent, charge: null, reason: params.reason, metadata: { ...params.metadata },
386
- }
387
- state.refunds.push(refund)
388
- return structuredClone(refund)
389
- },
390
- },
391
- prices: {
392
- list: async (params: Rec = {}) => {
393
- call('prices.list')
394
- return page(state.prices.filter(price => (params.product == null || price.product === params.product)
395
- && (params.active == null || price.active === params.active)
396
- && (params.lookup_keys == null || params.lookup_keys.includes(price.lookup_key))), { limit: 100, ...params })
397
- },
398
- create: async (params: Rec) => {
399
- call('prices.create')
400
- // Stripe's own default: a price created with no `tax_behavior` is `unspecified`.
401
- const price = { id: next('price'), active: true, tax_behavior: 'unspecified', ...structuredClone(params) }
402
- state.prices.push(price)
403
- return structuredClone(price)
404
- },
405
- update: async (id: string, params: Rec) => {
406
- call('prices.update')
407
- const price = find(state.prices, id, 'price')
408
- if (
409
- params.tax_behavior != null && price.tax_behavior != null && price.tax_behavior !== 'unspecified'
410
- && price.tax_behavior !== params.tax_behavior
411
- ) {
412
- // Real Stripe: once a price's `tax_behavior` is `exclusive` or `inclusive`, it cannot change.
413
- throw invalidRequest('parameter_invalid_empty')
414
- }
415
- Object.assign(price, params)
416
- return structuredClone(price)
417
- },
418
- },
419
- products: {
420
- retrieve: async (id: string) => {
421
- call('products.retrieve')
422
- if (state.products[id] == null) throw missing('product')
423
- return structuredClone(state.products[id])
424
- },
425
- update: async (id: string, params: Rec) => {
426
- call('products.update')
427
- Object.assign(state.products[id], params)
428
- return structuredClone(state.products[id])
429
- },
430
- create: async (params: Rec) => {
431
- call('products.create')
432
- state.products[params.id] = structuredClone(params)
433
- return structuredClone(params)
434
- },
435
- },
436
- customers: {
437
- retrieve: async (id: string) => {
438
- call('customers.retrieve')
439
- if (state.customers[id] == null) throw missing('customer')
440
- return structuredClone(state.customers[id])
441
- },
442
- create: async (params: Rec) => {
443
- call('customers.create')
444
- const customer = { id: next('cus'), object: 'customer', address: null, ...structuredClone(params) }
445
- state.customers[customer.id] = customer
446
- return structuredClone(customer)
447
- },
448
- update: async (id: string, params: Rec) => {
449
- call('customers.update')
450
- const customer = state.customers[id]
451
- if (customer == null) throw missing('customer')
452
- Object.assign(customer, params)
453
- return structuredClone(customer)
454
- },
455
- },
456
- checkout: {
457
- sessions: {
458
- create: async (params: Rec) => {
459
- call('checkout.sessions.create')
460
- state.checkoutSessions.push(structuredClone(params))
461
- return { id: next('cs'), url: `https://checkout.example.test/${state.seq}` }
462
- },
463
- expire: async (id: string) => {
464
- call('checkout.sessions.expire')
465
- state.expiredSessions.push(id)
466
- return { id, status: 'expired' }
467
- },
468
- list: async (params: Rec = {}) => {
469
- call('checkout.sessions.list')
470
- return page(state.listedSessions.filter(session => (params.status == null || session.status === params.status)
471
- && (params.created?.gte == null || session.created >= params.created.gte)), params)
472
- },
473
- listLineItems: async () => {
474
- call('checkout.sessions.listLineItems')
475
- return { data: [{ quantity: state.lineItemQuantity }] }
476
- },
477
- },
478
- },
479
- tax: {
480
- calculations: {
481
- /**
482
- * A flat-percentage tax model, entirely driven by `state.taxRates` / `taxInvalidCountries`
483
- * / `taxUnsupportedCountries` — real enough to exercise the status mapping and the
484
- * scalability rule, never a stand-in for Stripe's actual jurisdiction logic.
485
- */
486
- create: async (params: Rec) => {
487
- call('tax.calculations.create')
488
- state.taxCalculations.push(structuredClone(params))
489
- const country = params.customer_details?.address?.country as string | undefined
490
- if (country != null && state.taxInvalidCountries.includes(country)) {
491
- throw invalidRequest('customer_tax_location_invalid')
492
- }
493
- const lineItem = params.line_items[0]
494
- const amount: number = lineItem.amount
495
- const inclusive = lineItem.tax_behavior === 'inclusive'
496
- const reverseCharge = (params.customer_details?.tax_ids ?? []).length > 0
497
- const rates = reverseCharge ? [] : (country != null ? state.taxRates[country] ?? [] : [])
498
- const unsupported = !reverseCharge && rates.length === 0
499
- && country != null && state.taxUnsupportedCountries.includes(country)
500
-
501
- const breakdown = reverseCharge
502
- ? [{
503
- amount: 0, inclusive, taxable_amount: amount, taxability_reason: 'reverse_charge',
504
- tax_rate_details: { country, state: null, percentage_decimal: '0', tax_type: 'vat' },
505
- }]
506
- : unsupported
507
- ? [{
508
- amount: 0, inclusive, taxable_amount: amount, taxability_reason: 'not_supported',
509
- tax_rate_details: null,
510
- }]
511
- : rates.length === 0
512
- ? [{
513
- amount: 0, inclusive, taxable_amount: amount, taxability_reason: 'not_collecting',
514
- tax_rate_details: { country, state: null, percentage_decimal: '0', tax_type: 'vat' },
515
- }]
516
- : rates.map(rate => ({
517
- amount: Math.round(amount * Number(rate.percentage) / 100), inclusive, taxable_amount: amount,
518
- taxability_reason: 'standard_rated',
519
- tax_rate_details: { country, state: null, percentage_decimal: rate.percentage, tax_type: rate.type },
520
- }))
521
- const taxTotal = breakdown.reduce((sum, row) => sum + row.amount, 0)
522
-
523
- return {
524
- id: next('taxcalc'), object: 'tax.calculation', currency: params.currency,
525
- amount_total: inclusive ? amount : amount + taxTotal,
526
- tax_amount_exclusive: inclusive ? 0 : taxTotal,
527
- tax_amount_inclusive: inclusive ? taxTotal : 0,
528
- tax_breakdown: breakdown,
529
- }
530
- },
531
- },
532
- settings: {
533
- retrieve: async () => {
534
- call('tax.settings.retrieve')
535
- return structuredClone(state.taxSettings)
536
- },
537
- },
538
- },
539
- rawRequest: async (method: string, path: string, params: Rec = {}) => {
540
- call('rawRequest')
541
- state.rawRequests.push({ method, path, params: structuredClone(params) })
542
- if (path !== '/v1/fx_quotes') {
543
- throw new Error(`fake-stripe: unhandled rawRequest path "${path}"`)
544
- }
545
- if (state.fxUnavailable) {
546
- throw new Error('fx_quotes unavailable')
547
- }
548
- const local = params['from_currencies[]'] as string
549
- const rate = state.fxRates[local]
550
- if (rate == null) {
551
- return { rates: {} }
552
- }
553
- return {
554
- rates: {
555
- [local]: {
556
- exchange_rate: rate.exchangeRate,
557
- rate_details: {
558
- base_rate: rate.baseRate ?? rate.exchangeRate,
559
- reference_rate: rate.referenceRate ?? rate.baseRate ?? rate.exchangeRate,
560
- fx_fee_rate: rate.fxFeeRate ?? 0.02,
561
- },
562
- },
563
- },
564
- }
565
- },
566
- webhooks: {
567
- /** Accepts the signature `sig:<secret>` over any body. */
568
- constructEventAsync: async (raw: string | Buffer, signature: string, secret: string) => {
569
- if (signature !== `sig:${secret}`) throw new Error('bad signature')
570
- return JSON.parse(raw.toString())
571
- },
572
- },
573
- }
574
-
575
- return { stripe: stripe as unknown as Stripe, state }
576
- }
577
-
578
- // -----------------------------------------------------------------------------------------------
579
- // Stripe objects
580
- // -----------------------------------------------------------------------------------------------
581
-
582
- let objectSeq = 0
583
- const epoch = (date: Date): number => Math.floor(date.getTime() / 1000)
584
-
585
- export interface SubscriptionShape {
586
- id?: string
587
- customer?: string
588
- entityId?: string
589
- planSku?: string
590
- status?: Stripe.Subscription.Status
591
- itemId?: string
592
- priceId?: string
593
- periodStart?: Date
594
- periodEnd?: Date
595
- cancelAtPeriodEnd?: boolean
596
- pauseCollection?: Rec | null
597
- trialEnd?: Date
598
- latestInvoice?: string
599
- created?: Date
600
- endedAt?: Date
601
- defaultPaymentMethod?: string
602
- }
603
-
604
- export const subscriptionOf = (shape: SubscriptionShape = {}): Stripe.Subscription => ({
605
- id: shape.id ?? 'sub_1',
606
- object: 'subscription',
607
- customer: shape.customer ?? 'cus_1',
608
- status: shape.status ?? 'active',
609
- metadata: { ...(shape.entityId !== undefined ? { entityId: shape.entityId } : { entityId: 'entity-1' }) },
610
- items: {
611
- object: 'list', has_more: false, url: '',
612
- data: [{ id: shape.itemId ?? 'si_1', price: { id: shape.priceId ?? `price_${shape.planSku ?? PRO}`, lookup_key: shape.planSku ?? PRO } }],
613
- },
614
- current_period_start: epoch(shape.periodStart ?? past(1)),
615
- current_period_end: epoch(shape.periodEnd ?? future(29)),
616
- cancel_at_period_end: shape.cancelAtPeriodEnd ?? false,
617
- canceled_at: null,
618
- ended_at: shape.endedAt != null ? epoch(shape.endedAt) : null,
619
- pause_collection: shape.pauseCollection ?? null,
620
- trial_end: shape.trialEnd != null ? epoch(shape.trialEnd) : null,
621
- latest_invoice: shape.latestInvoice ?? 'in_1',
622
- created: epoch(shape.created ?? past(1)),
623
- default_payment_method: shape.defaultPaymentMethod ?? 'pm_1',
624
- } as unknown as Stripe.Subscription)
625
-
626
- export const eventOf = (type: string, object: unknown, overrides: Rec = {}): Stripe.Event => ({
627
- id: `evt_${++objectSeq}`, object: 'event', type, created: epoch(new Date()), data: { object }, ...overrides,
628
- } as unknown as Stripe.Event)
629
-
630
- // -----------------------------------------------------------------------------------------------
631
- // In-memory resources
632
- // -----------------------------------------------------------------------------------------------
633
-
634
- const duplicate = (): Error => Object.assign(new Error('E11000 duplicate key error'), { code: 11000 })
635
-
636
- const plain = (value: unknown): unknown => value instanceof Date ? value.getTime() : value
637
-
638
- const withoutUndefined = <T extends Rec>(record: T): T =>
639
- Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined)) as T
640
-
641
- const applyUpdate = (doc: Rec, update: Rec, inserting: boolean): void => {
642
- for (const [key, value] of Object.entries(update.$set ?? {})) {
643
- if (value === undefined) continue
644
- doc[key] = value
645
- }
646
- for (const [key, value] of Object.entries(update.$inc ?? {})) {
647
- doc[key] = (doc[key] ?? 0) + (value as number)
648
- }
649
- for (const key of Object.keys(update.$unset ?? {})) {
650
- delete doc[key]
651
- }
652
- if (inserting) {
653
- Object.assign(doc, update.$setOnInsert ?? {})
654
- }
655
- }
656
-
657
- export interface MemoryStore {
658
- rows: Rec[]
659
- /** Make the next calls of a method throw. */
660
- failing: Set<string>
661
- }
662
-
663
- /**
664
- * Turn a real resource (its maker's indexes and helpers kept) into an in-memory one over the shared
665
- * criteria engine, including the raw collection calls the package makes: the conditional counter
666
- * upsert, `$inc` / `$set` / `$unset`, `$match` + `$group` aggregation and `distinct`.
667
- */
668
- export const memoryResource = <T extends ResourceRecord>(resource: MongoResource<T>): MemoryStore => {
669
- const store: MemoryStore = { rows: [], failing: new Set() }
670
- const unique = (resource.indexes ?? []).filter(index => index.options?.unique === true)
671
- .map(index => ({ keys: Object.keys(index.index as Rec), sparse: index.options?.sparse === true }))
672
- let seq = 0
673
- const guard = (method: string): void => {
674
- if (store.failing.has(method)) throw new Error(`${resource.alias}.${method} unavailable`)
675
- }
676
- // A sparse unique index ignores a document that carries none of its keys (as Mongo does).
677
- const violates = (doc: Rec, self?: Rec): boolean => unique.some(({ keys, sparse }) =>
678
- !(sparse && keys.every(key => doc[key] == null)) && store.rows.some(row =>
679
- row !== self && keys.every(key => plain(row[key] ?? null) === plain(doc[key] ?? null))))
680
- const out = (row: Rec): T => structuredClone(row) as T
681
- const byId = (id: string) => store.rows.find(row => row.id === id)
682
-
683
- const target = resource as unknown as Rec
684
- target.init = async () => undefined
685
- target.get = async (idOrWhere: string | Criteria<T>, opts?: { sort?: never[] }) => {
686
- guard('get')
687
- const row = typeof idOrWhere === 'string' ? byId(idOrWhere) : recordQueryHelper.firstMatch(store.rows, idOrWhere as Criteria<any>, opts)
688
- if (row == null) throw new UnknownRecordError(JSON.stringify(idOrWhere))
689
- return out(row)
690
- }
691
- target.load = async (idOrWhere: string | Criteria<T>, opts?: { sort?: never[] }) => {
692
- guard('load')
693
- const row = typeof idOrWhere === 'string' ? byId(idOrWhere) : recordQueryHelper.firstMatch(store.rows, idOrWhere as Criteria<any>, opts)
694
- return row == null ? null : out(row)
695
- }
696
- target.list = async (where?: Criteria<T>, opts?: ListOptions<T>) => {
697
- guard('list')
698
- const result = recordQueryHelper.applyQuery(store.rows, where as Criteria<any>, opts as ListOptions<any>)
699
- return { ...result, items: result.items.map(out) }
700
- }
701
- target.count = async (where?: Criteria<T>) => store.rows.filter(row => recordQueryHelper.matchCriteria(row, where)).length
702
- target.create = async (record: Rec) => {
703
- guard('create')
704
- if (record.id != null) throw new RecordExists('id-present')
705
- const doc = withoutUndefined(structuredClone(record))
706
- delete doc.id
707
- if (violates(doc)) throw duplicate()
708
- doc.id = `${resource.alias}-${++seq}`
709
- store.rows.push(doc)
710
- return out(doc)
711
- }
712
- target.update = async (record: Rec) => {
713
- guard('update')
714
- const existing = byId(record.id)
715
- if (existing == null) throw new UnknownRecordError(String(record.id))
716
- const doc = withoutUndefined(structuredClone(record))
717
- if (violates(doc, existing)) throw duplicate()
718
- store.rows[store.rows.indexOf(existing)] = doc
719
- return out(doc)
720
- }
721
- target.save = async (record: Rec) => record.id != null ? await target.update(record) : await target.create(record)
722
- target.delete = async (id: string) => {
723
- const row = byId(id)
724
- if (row == null) return null
725
- store.rows = store.rows.filter(item => item !== row)
726
- return out(row)
727
- }
728
- target.purge = async (where: Criteria<T>) => {
729
- const before = store.rows.length
730
- store.rows = store.rows.filter(row => !recordQueryHelper.matchCriteria(row, where))
731
- return before - store.rows.length
732
- }
733
-
734
- // A raw filter addresses a record by `_id` (`paymentUtils.idCriteria`); the rows carry it as `id`.
735
- const rawFilter = (filter: Rec): Rec => {
736
- if (!('_id' in filter)) return filter
737
- const { _id: rawId, ...rest } = filter
738
- return { ...rest, id: String(rawId) }
739
- }
740
- const matchRaw = (filter: Rec) => store.rows.find(row => recordQueryHelper.matchCriteria(row, rawFilter(filter)))
741
- const upsert = (filter: Rec, update: Rec, opts: Rec = {}): { doc: Rec | null, inserted: boolean } => {
742
- const found = matchRaw(filter)
743
- if (found != null) {
744
- applyUpdate(found, update, false)
745
- return { doc: found, inserted: false }
746
- }
747
- if (opts.upsert !== true) return { doc: null, inserted: false }
748
- const doc: Rec = Object.fromEntries(Object.entries(rawFilter(filter)).filter(([, value]) =>
749
- value === null || typeof value !== 'object' || value instanceof Date))
750
- applyUpdate(doc, update, true)
751
- if (violates(doc)) throw duplicate()
752
- doc.id = `${resource.alias}-${++seq}`
753
- store.rows.push(doc)
754
- return { doc, inserted: true }
755
- }
756
- target.collection = {
757
- findOneAndUpdate: async (filter: Rec, update: Rec, opts: Rec = {}) => {
758
- guard('findOneAndUpdate')
759
- const before = matchRaw(filter)
760
- const snapshot = before != null ? structuredClone(before) : null
761
- const { doc } = upsert(filter, update, opts)
762
- if (doc == null) return null
763
- const result = opts.returnDocument === 'after' ? doc : snapshot
764
- return result == null ? null : { ...structuredClone(result), _id: result.id }
765
- },
766
- updateOne: async (filter: Rec, update: Rec, opts: Rec = {}) => {
767
- guard('updateOne')
768
- // Like Mongo: an update is checked against the unique indexes before it lands.
769
- const found = matchRaw(filter)
770
- if (found != null) {
771
- const candidate = structuredClone(found)
772
- applyUpdate(candidate, update, false)
773
- if (violates(candidate, found)) throw duplicate()
774
- }
775
- const { doc, inserted } = upsert(filter, update, opts)
776
- return { matchedCount: doc != null && !inserted ? 1 : 0, upsertedCount: inserted ? 1 : 0 }
777
- },
778
- deleteOne: async (filter: Rec) => {
779
- const row = matchRaw(filter)
780
- store.rows = store.rows.filter(item => item !== row)
781
- return { deletedCount: row != null ? 1 : 0 }
782
- },
783
- distinct: async (field: string, filter: Rec = {}) =>
784
- [...new Set(store.rows.filter(row => recordQueryHelper.matchCriteria(row, filter)).map(row => row[field]))],
785
- aggregate: (pipeline: Rec[]) => ({
786
- toArray: async () => {
787
- guard('aggregate')
788
- let docs: Rec[] = store.rows.map(row => structuredClone(row))
789
- for (const stage of pipeline) {
790
- if (stage.$match != null) {
791
- docs = docs.filter(doc => recordQueryHelper.matchCriteria(doc, stage.$match))
792
- } else if (stage.$group != null) {
793
- const groups = new Map<string, Rec>()
794
- const { _id: key, ...accumulators } = stage.$group
795
- for (const doc of docs) {
796
- const id = Object.fromEntries(Object.entries(key as Rec).map(([name, ref]) => [name, doc[(ref as string).slice(1)]]))
797
- const hash = JSON.stringify(id)
798
- const group = groups.get(hash) ?? { _id: id }
799
- for (const [name, spec] of Object.entries(accumulators as Rec)) {
800
- group[name] = (group[name] ?? 0) + (doc[(spec.$sum as string).slice(1)] ?? 0)
801
- }
802
- groups.set(hash, group)
803
- }
804
- docs = [...groups.values()]
805
- } else {
806
- throw new Error(`unsupported stage ${JSON.stringify(stage)}`)
807
- }
808
- }
809
- return docs
810
- },
811
- }),
812
- }
813
-
814
- return store
815
- }
816
-
817
- // -----------------------------------------------------------------------------------------------
818
- // Context
819
- // -----------------------------------------------------------------------------------------------
820
-
821
- export interface FakeContextOptions {
822
- catalogue?: CatalogueOptions
823
- /** Declare the catalogue yourself instead. */
824
- declare?: (cfg: Config) => void
825
- /** This process's `cfg.service` (default `app`). */
826
- service?: string
827
- /** The public host of this process's service (default `api.example.com`). */
828
- host?: string
829
- /** The base path of this process's service (default none). */
830
- base?: string
831
- /** Further backend services by alias, each on its own host (and base). */
832
- services?: Record<string, { host: string, base?: string }>
833
- /** The configured webhook override secret. */
834
- webhookSecret?: string
835
- portal?: PortalBrandingDef
836
- pricing?: PricingDef
837
- stripe?: Partial<FakeStripeState>
838
- /** Rows each store (by resource alias) holds before the context initializes — a shared database. */
839
- seed?: Record<string, Rec[]>
840
- /** Declare a consumer-rights policy (with trader and mail options). */
841
- consumerRights?: ConsumerRightsDef
842
- /** The consumer-rights usage meter. */
843
- meter?: UsageMeter
844
- /** Register a console mailer under `MAILER_SERVICE` (default true). */
845
- mailer?: boolean
846
- /** Register the gateway before the application's consumer-rights call (default: after). */
847
- gatewayFirst?: boolean
848
- /** The application's consumer-rights options (default: managed through the fake, with `meter`). */
849
- rights?: (stripe: Stripe) => ConsumerRightsOptions
850
- /** The gateway's options (default `{ manage: false }`); its Stripe client is always the fake. */
851
- gateway?: GatewayServiceOptions
852
- /** Run on the context after the registrations, before it is configured and initialized. */
853
- wire?: (ctx: ApiContext) => void
854
- }
855
-
856
- export interface Observed {
857
- topUp: TopUpCompletion[]
858
- subscription: SubscriptionEvent[]
859
- refund: RefundEvent[]
860
- dispute: DisputeEvent[]
861
- paymentFailed: PaymentFailedEvent[]
862
- consent: ConsentEvent[]
863
- withdrawal: WithdrawalEvent[]
864
- cancellation: CancellationEvent[]
865
- grant: EntitlementGrantEvent[]
866
- /** Throw from the next `n` subscription callbacks. */
867
- failSubscription: number
868
- failTopUp: number
869
- failWithdrawal: number
870
- /** Throw from the next `n` entitlement grant callbacks. */
871
- failGrant: number
872
- /** Run inside every top-up / subscription callback, before it records the event. */
873
- onTopUp?: (event: TopUpCompletion) => Promise<void>
874
- onSubscription?: (event: SubscriptionEvent) => Promise<void>
875
- }
876
-
877
- export interface FakeContext {
878
- ctx: ApiContext
879
- stripe: Stripe
880
- state: FakeStripeState
881
- stores: Record<string, MemoryStore>
882
- observed: Observed
883
- /** Every mail the console mailer took. */
884
- mails: MailMessage[]
885
- /** The console mailer — replace its `send` to simulate a transport failure. */
886
- mailer: ReturnType<typeof makeConsoleMailerService>
887
- }
888
-
889
- /**
890
- * A real server context — real catalogue, payment service, observer, gateway (unmanaged unless
891
- * `gateway` says otherwise), gates and entitlement service — over in-memory resources, with a fake
892
- * Stripe for the plugin functions and as the gateway's own client.
893
- */
894
- export const makeFakeContext = async (opts: FakeContextOptions = {}): Promise<FakeContext> => {
895
- const own = opts.service ?? SERVICE
896
- const services: Record<string, unknown> = {
897
- [own]: { service: own, type: AppType.Backend, host: opts.host ?? HOST, ...(opts.base != null ? { base: opts.base } : {}) },
898
- }
899
- for (const [alias, { host, base }] of Object.entries(opts.services ?? {})) {
900
- services[alias] = { service: alias, type: AppType.Backend, host, ...(base != null ? { base } : {}) }
901
- }
902
- const cfg = serverConfig<ServerConfig>(own, { services } as Partial<ServerConfig>) as unknown as Config
903
- if (opts.declare != null) {
904
- opts.declare(cfg)
905
- } else {
906
- declareTestCatalogue(cfg, opts.catalogue)
907
- }
908
- stripeSecrets(cfg, { api: 'sk_test_offline', ...(opts.webhookSecret != null ? { webhook: opts.webhookSecret } : {}) })
909
- if (opts.portal != null) {
910
- portalBranding(cfg, opts.portal)
911
- }
912
- if (opts.pricing != null) {
913
- declarePaymentPricing(cfg, opts.pricing)
914
- }
915
- if (opts.consumerRights != null) {
916
- declareConsumerRights(cfg, opts.consumerRights)
917
- }
918
-
919
- const ctx = makeServerContext(cfg as unknown as ServerConfig) as unknown as ApiContext
920
- const stores: Record<string, MemoryStore> = {}
921
- const resources = [
922
- [RES_PAYGATE_CUSTOMER, makePaygateCustomerResource()],
923
- [RES_PAYMENT_SUBSCRIPTION, makeSubscriptionResource()],
924
- [RES_PAYMENT_FULFILLMENT, makeFulfillmentResource()],
925
- [RES_PAYMENT_WEBHOOK, makeWebhookResource()],
926
- [RES_PAYMENT_USAGE, makeUsageResource()],
927
- [RES_PAYMENT_USAGE_COUNTER, makeUsageCounterResource()],
928
- [RES_PAYMENT_FINGERPRINT, makeFingerprintResource()],
929
- [RES_BILLING_PROFILE, makeBillingProfileResource()],
930
- [RES_PAYMENT_PURCHASE, makePurchaseResource()],
931
- [RES_CONSUMER_CONSENT, makeConsumerConsentResource()],
932
- [RES_CONSUMER_DECLARATION, makeConsumerDeclarationResource()],
933
- [RES_CONSUMER_EVENT, makeConsumerEventResource()],
934
- [RES_PAYMENT_GRANT, makeGrantResource()],
935
- ] as const
936
- for (const [alias, resource] of resources) {
937
- stores[alias] = memoryResource(resource as unknown as MongoResource<ResourceRecord>)
938
- stores[alias].rows.push(...structuredClone(opts.seed?.[alias] ?? []))
939
- ctx.registerResource(resource as never)
940
- }
941
- const { stripe, state } = makeFakeStripe(opts.stripe)
942
- const mailer = makeConsoleMailerService(MAILER_SERVICE)
943
- if (opts.mailer !== false) {
944
- ctx.registerService(mailer)
945
- }
946
- // The consumer-rights service manages the paygate through the fake; the gateway stays unmanaged.
947
- const rights = opts.rights?.(stripe)
948
- ?? { manage: true, stripe: async () => stripe, ...(opts.meter != null ? { usage: opts.meter } : {}) }
949
- const gatewayOpts: GatewayServiceOptions = { manage: false, stripe: async () => stripe, ...opts.gateway }
950
- if (opts.gatewayFirst === true) {
951
- appendPaymentGatewayService(ctx as never, gatewayOpts)
952
- appendConsumerRights(ctx as never, rights)
953
- } else {
954
- appendConsumerRights(ctx as never, rights)
955
- appendPaymentGatewayService(ctx as never, gatewayOpts)
956
- }
957
- opts.wire?.(ctx)
958
- ctx.configure()
959
- await ctx.init()
960
-
961
- const observed: Observed = {
962
- topUp: [], subscription: [], refund: [], dispute: [], paymentFailed: [], consent: [], withdrawal: [],
963
- cancellation: [], grant: [], failSubscription: 0, failTopUp: 0, failWithdrawal: 0, failGrant: 0,
964
- }
965
- const completions = paymentAccessOf(ctx).observer()
966
- await completions.ready()
967
- completions.onTopUp(async event => {
968
- if (observed.failTopUp > 0) {
969
- observed.failTopUp--
970
- throw new Error('ledger unavailable')
971
- }
972
- await observed.onTopUp?.(event)
973
- observed.topUp.push(event)
974
- })
975
- completions.onSubscription(async event => {
976
- if (observed.failSubscription > 0) {
977
- observed.failSubscription--
978
- throw new Error('observer unavailable')
979
- }
980
- await observed.onSubscription?.(event)
981
- observed.subscription.push(event)
982
- })
983
- completions.onRefund(async event => { observed.refund.push(event) })
984
- completions.onDispute(async event => { observed.dispute.push(event) })
985
- completions.onPaymentFailed(async event => { observed.paymentFailed.push(event) })
986
- completions.onConsent(async event => { observed.consent.push(event) })
987
- completions.onWithdrawal(async event => {
988
- if (observed.failWithdrawal > 0) {
989
- observed.failWithdrawal--
990
- throw new Error('ledger unavailable')
991
- }
992
- observed.withdrawal.push(event)
993
- })
994
- completions.onCancellation(async event => { observed.cancellation.push(event) })
995
- completions.onEntitlementGrant(async event => {
996
- if (observed.failGrant > 0) {
997
- observed.failGrant--
998
- throw new Error('sweeps unavailable')
999
- }
1000
- observed.grant.push(event)
1001
- })
1002
-
1003
- return { ctx, stripe, state, stores, observed, mails: mailer.captured, mailer }
1004
- }