@owlmeans/server-payment 0.1.18-rc.9 → 0.1.19-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (537) hide show
  1. package/README.md +157 -26
  2. package/agent-meta/manifest.json +30 -4
  3. package/agent-meta/skills/server-payment/SKILL.md +639 -54
  4. package/agent-meta/skills/server-payment/parts/reference.md +174 -0
  5. package/build/access/types.d.ts +46 -0
  6. package/build/access/types.d.ts.map +1 -0
  7. package/build/access/types.js +2 -0
  8. package/build/access/types.js.map +1 -0
  9. package/build/access.d.ts +6 -0
  10. package/build/access.d.ts.map +1 -0
  11. package/build/access.js +45 -0
  12. package/build/access.js.map +1 -0
  13. package/build/actions/index.d.ts +1 -0
  14. package/build/actions/index.d.ts.map +1 -1
  15. package/build/actions/index.js +1 -0
  16. package/build/actions/index.js.map +1 -1
  17. package/build/actions/resync-subscriptions.d.ts +3 -0
  18. package/build/actions/resync-subscriptions.d.ts.map +1 -0
  19. package/build/actions/resync-subscriptions.js +7 -0
  20. package/build/actions/resync-subscriptions.js.map +1 -0
  21. package/build/actions/resync.d.ts +6 -1
  22. package/build/actions/resync.d.ts.map +1 -1
  23. package/build/actions/resync.js +15 -5
  24. package/build/actions/resync.js.map +1 -1
  25. package/build/actions/webhook.d.ts +2 -1
  26. package/build/actions/webhook.d.ts.map +1 -1
  27. package/build/actions/webhook.js +10 -4
  28. package/build/actions/webhook.js.map +1 -1
  29. package/build/bootstrap/types.d.ts +16 -0
  30. package/build/bootstrap/types.d.ts.map +1 -0
  31. package/build/bootstrap/types.js +2 -0
  32. package/build/bootstrap/types.js.map +1 -0
  33. package/build/bootstrap.d.ts +6 -0
  34. package/build/bootstrap.d.ts.map +1 -0
  35. package/build/bootstrap.js +26 -0
  36. package/build/bootstrap.js.map +1 -0
  37. package/build/catalogue/types.d.ts +38 -0
  38. package/build/catalogue/types.d.ts.map +1 -0
  39. package/build/catalogue/types.js +2 -0
  40. package/build/catalogue/types.js.map +1 -0
  41. package/build/catalogue.d.ts +6 -0
  42. package/build/catalogue.d.ts.map +1 -0
  43. package/build/catalogue.js +110 -0
  44. package/build/catalogue.js.map +1 -0
  45. package/build/commit/types.d.ts +22 -0
  46. package/build/commit/types.d.ts.map +1 -0
  47. package/build/commit/types.js +2 -0
  48. package/build/commit/types.js.map +1 -0
  49. package/build/commit.d.ts +6 -0
  50. package/build/commit.d.ts.map +1 -0
  51. package/build/commit.js +125 -0
  52. package/build/commit.js.map +1 -0
  53. package/build/config.d.ts +44 -5
  54. package/build/config.d.ts.map +1 -1
  55. package/build/config.js +216 -10
  56. package/build/config.js.map +1 -1
  57. package/build/consts.d.ts +74 -16
  58. package/build/consts.d.ts.map +1 -1
  59. package/build/consts.js +86 -23
  60. package/build/consts.js.map +1 -1
  61. package/build/consts.local.d.ts +94 -0
  62. package/build/consts.local.d.ts.map +1 -0
  63. package/build/consts.local.js +44 -0
  64. package/build/consts.local.js.map +1 -0
  65. package/build/consumer/cancellation/types.d.ts +11 -0
  66. package/build/consumer/cancellation/types.d.ts.map +1 -0
  67. package/build/consumer/cancellation/types.js +2 -0
  68. package/build/consumer/cancellation/types.js.map +1 -0
  69. package/build/consumer/cancellation.d.ts +6 -0
  70. package/build/consumer/cancellation.d.ts.map +1 -0
  71. package/build/consumer/cancellation.js +33 -0
  72. package/build/consumer/cancellation.js.map +1 -0
  73. package/build/consumer/capture/types.d.ts +50 -0
  74. package/build/consumer/capture/types.d.ts.map +1 -0
  75. package/build/consumer/capture/types.js +2 -0
  76. package/build/consumer/capture/types.js.map +1 -0
  77. package/build/consumer/capture.d.ts +6 -0
  78. package/build/consumer/capture.d.ts.map +1 -0
  79. package/build/consumer/capture.js +285 -0
  80. package/build/consumer/capture.js.map +1 -0
  81. package/build/consumer/consts.local.d.ts +10 -0
  82. package/build/consumer/consts.local.d.ts.map +1 -0
  83. package/build/consumer/consts.local.js +11 -0
  84. package/build/consumer/consts.local.js.map +1 -0
  85. package/build/consumer/format/types.d.ts +30 -0
  86. package/build/consumer/format/types.d.ts.map +1 -0
  87. package/build/consumer/format/types.js +2 -0
  88. package/build/consumer/format/types.js.map +1 -0
  89. package/build/consumer/format.d.ts +4 -0
  90. package/build/consumer/format.d.ts.map +1 -0
  91. package/build/consumer/format.js +73 -0
  92. package/build/consumer/format.js.map +1 -0
  93. package/build/consumer/handlers.d.ts +21 -0
  94. package/build/consumer/handlers.d.ts.map +1 -0
  95. package/build/consumer/handlers.js +174 -0
  96. package/build/consumer/handlers.js.map +1 -0
  97. package/build/consumer/index.d.ts +10 -0
  98. package/build/consumer/index.d.ts.map +1 -0
  99. package/build/consumer/index.js +6 -0
  100. package/build/consumer/index.js.map +1 -0
  101. package/build/consumer/mail/types.d.ts +29 -0
  102. package/build/consumer/mail/types.d.ts.map +1 -0
  103. package/build/consumer/mail/types.js +2 -0
  104. package/build/consumer/mail/types.js.map +1 -0
  105. package/build/consumer/mail.d.ts +6 -0
  106. package/build/consumer/mail.d.ts.map +1 -0
  107. package/build/consumer/mail.js +313 -0
  108. package/build/consumer/mail.js.map +1 -0
  109. package/build/consumer/observers/types.d.ts +15 -0
  110. package/build/consumer/observers/types.d.ts.map +1 -0
  111. package/build/consumer/observers/types.js +2 -0
  112. package/build/consumer/observers/types.js.map +1 -0
  113. package/build/consumer/observers.d.ts +6 -0
  114. package/build/consumer/observers.d.ts.map +1 -0
  115. package/build/consumer/observers.js +74 -0
  116. package/build/consumer/observers.js.map +1 -0
  117. package/build/consumer/origin/types.d.ts +17 -0
  118. package/build/consumer/origin/types.d.ts.map +1 -0
  119. package/build/consumer/origin/types.js +2 -0
  120. package/build/consumer/origin/types.js.map +1 -0
  121. package/build/consumer/origin.d.ts +8 -0
  122. package/build/consumer/origin.d.ts.map +1 -0
  123. package/build/consumer/origin.js +43 -0
  124. package/build/consumer/origin.js.map +1 -0
  125. package/build/consumer/reconcile/types.d.ts +13 -0
  126. package/build/consumer/reconcile/types.d.ts.map +1 -0
  127. package/build/consumer/reconcile/types.js +2 -0
  128. package/build/consumer/reconcile/types.js.map +1 -0
  129. package/build/consumer/reconcile.d.ts +5 -0
  130. package/build/consumer/reconcile.d.ts.map +1 -0
  131. package/build/consumer/reconcile.js +321 -0
  132. package/build/consumer/reconcile.js.map +1 -0
  133. package/build/consumer/records/types.d.ts +66 -0
  134. package/build/consumer/records/types.d.ts.map +1 -0
  135. package/build/consumer/records/types.js +2 -0
  136. package/build/consumer/records/types.js.map +1 -0
  137. package/build/consumer/records.d.ts +6 -0
  138. package/build/consumer/records.d.ts.map +1 -0
  139. package/build/consumer/records.js +243 -0
  140. package/build/consumer/records.js.map +1 -0
  141. package/build/consumer/service.d.ts +28 -0
  142. package/build/consumer/service.d.ts.map +1 -0
  143. package/build/consumer/service.js +706 -0
  144. package/build/consumer/service.js.map +1 -0
  145. package/build/consumer/types.d.ts +84 -0
  146. package/build/consumer/types.d.ts.map +1 -0
  147. package/build/consumer/types.js +2 -0
  148. package/build/consumer/types.js.map +1 -0
  149. package/build/consumer/types.local.d.ts +26 -0
  150. package/build/consumer/types.local.d.ts.map +1 -0
  151. package/build/consumer/types.local.js +2 -0
  152. package/build/consumer/types.local.js.map +1 -0
  153. package/build/consumer/withdrawal/types.d.ts +36 -0
  154. package/build/consumer/withdrawal/types.d.ts.map +1 -0
  155. package/build/consumer/withdrawal/types.js +2 -0
  156. package/build/consumer/withdrawal/types.js.map +1 -0
  157. package/build/consumer/withdrawal.d.ts +6 -0
  158. package/build/consumer/withdrawal.d.ts.map +1 -0
  159. package/build/consumer/withdrawal.js +237 -0
  160. package/build/consumer/withdrawal.js.map +1 -0
  161. package/build/entitlement.d.ts +4 -0
  162. package/build/entitlement.d.ts.map +1 -0
  163. package/build/entitlement.js +72 -0
  164. package/build/entitlement.js.map +1 -0
  165. package/build/entrypoints.d.ts +19 -2
  166. package/build/entrypoints.d.ts.map +1 -1
  167. package/build/entrypoints.js +16 -4
  168. package/build/entrypoints.js.map +1 -1
  169. package/build/gate/request.d.ts +4 -0
  170. package/build/gate/request.d.ts.map +1 -0
  171. package/build/gate/request.js +17 -0
  172. package/build/gate/request.js.map +1 -0
  173. package/build/gate/types.d.ts +15 -0
  174. package/build/gate/types.d.ts.map +1 -0
  175. package/build/gate/types.js +2 -0
  176. package/build/gate/types.js.map +1 -0
  177. package/build/gate.d.ts +13 -9
  178. package/build/gate.d.ts.map +1 -1
  179. package/build/gate.js +36 -21
  180. package/build/gate.js.map +1 -1
  181. package/build/index.d.ts +50 -3
  182. package/build/index.d.ts.map +1 -1
  183. package/build/index.js +29 -3
  184. package/build/index.js.map +1 -1
  185. package/build/limit.d.ts +11 -0
  186. package/build/limit.d.ts.map +1 -0
  187. package/build/limit.js +48 -0
  188. package/build/limit.js.map +1 -0
  189. package/build/log.d.ts +3 -0
  190. package/build/log.d.ts.map +1 -0
  191. package/build/log.js +4 -0
  192. package/build/log.js.map +1 -0
  193. package/build/models/declarations/types.d.ts +22 -0
  194. package/build/models/declarations/types.d.ts.map +1 -0
  195. package/build/models/declarations/types.js +2 -0
  196. package/build/models/declarations/types.js.map +1 -0
  197. package/build/models/declarations.d.ts +4 -0
  198. package/build/models/declarations.d.ts.map +1 -0
  199. package/build/models/declarations.js +26 -0
  200. package/build/models/declarations.js.map +1 -0
  201. package/build/models/purchase/types.d.ts +13 -0
  202. package/build/models/purchase/types.d.ts.map +1 -0
  203. package/build/models/purchase/types.js +2 -0
  204. package/build/models/purchase/types.js.map +1 -0
  205. package/build/models/purchase.d.ts +4 -0
  206. package/build/models/purchase.d.ts.map +1 -0
  207. package/build/models/purchase.js +37 -0
  208. package/build/models/purchase.js.map +1 -0
  209. package/build/observer.d.ts +9 -0
  210. package/build/observer.d.ts.map +1 -1
  211. package/build/observer.js +38 -12
  212. package/build/observer.js.map +1 -1
  213. package/build/plan/types.d.ts +21 -0
  214. package/build/plan/types.d.ts.map +1 -0
  215. package/build/plan/types.js +2 -0
  216. package/build/plan/types.js.map +1 -0
  217. package/build/plan.d.ts +7 -0
  218. package/build/plan.d.ts.map +1 -0
  219. package/build/plan.js +29 -0
  220. package/build/plan.js.map +1 -0
  221. package/build/plugins/checkout-plugins/types.d.ts +25 -0
  222. package/build/plugins/checkout-plugins/types.d.ts.map +1 -0
  223. package/build/plugins/checkout-plugins/types.js +2 -0
  224. package/build/plugins/checkout-plugins/types.js.map +1 -0
  225. package/build/plugins/checkout-plugins.d.ts +12 -0
  226. package/build/plugins/checkout-plugins.d.ts.map +1 -0
  227. package/build/plugins/checkout-plugins.js +72 -0
  228. package/build/plugins/checkout-plugins.js.map +1 -0
  229. package/build/plugins/checkout-policy/types.d.ts +18 -0
  230. package/build/plugins/checkout-policy/types.d.ts.map +1 -0
  231. package/build/plugins/checkout-policy/types.js +2 -0
  232. package/build/plugins/checkout-policy/types.js.map +1 -0
  233. package/build/plugins/checkout-policy.d.ts +4 -0
  234. package/build/plugins/checkout-policy.d.ts.map +1 -0
  235. package/build/plugins/checkout-policy.js +26 -0
  236. package/build/plugins/checkout-policy.js.map +1 -0
  237. package/build/plugins/checkout-registry/types.d.ts +7 -0
  238. package/build/plugins/checkout-registry/types.d.ts.map +1 -0
  239. package/build/plugins/checkout-registry/types.js +2 -0
  240. package/build/plugins/checkout-registry/types.js.map +1 -0
  241. package/build/plugins/checkout-registry.d.ts +8 -0
  242. package/build/plugins/checkout-registry.d.ts.map +1 -0
  243. package/build/plugins/checkout-registry.js +21 -0
  244. package/build/plugins/checkout-registry.js.map +1 -0
  245. package/build/plugins/consts.local.d.ts +13 -0
  246. package/build/plugins/consts.local.d.ts.map +1 -0
  247. package/build/plugins/consts.local.js +22 -0
  248. package/build/plugins/consts.local.js.map +1 -0
  249. package/build/plugins/customer-lock/types.d.ts +6 -0
  250. package/build/plugins/customer-lock/types.d.ts.map +1 -0
  251. package/build/plugins/customer-lock/types.js +2 -0
  252. package/build/plugins/customer-lock/types.js.map +1 -0
  253. package/build/plugins/customer-lock.d.ts +5 -0
  254. package/build/plugins/customer-lock.d.ts.map +1 -0
  255. package/build/plugins/customer-lock.js +22 -0
  256. package/build/plugins/customer-lock.js.map +1 -0
  257. package/build/plugins/estimate/cache.d.ts +4 -0
  258. package/build/plugins/estimate/cache.d.ts.map +1 -0
  259. package/build/plugins/estimate/cache.js +7 -0
  260. package/build/plugins/estimate/cache.js.map +1 -0
  261. package/build/plugins/estimate/types.d.ts +27 -0
  262. package/build/plugins/estimate/types.d.ts.map +1 -0
  263. package/build/plugins/estimate/types.js +2 -0
  264. package/build/plugins/estimate/types.js.map +1 -0
  265. package/build/plugins/estimate.d.ts +6 -0
  266. package/build/plugins/estimate.d.ts.map +1 -0
  267. package/build/plugins/estimate.js +271 -0
  268. package/build/plugins/estimate.js.map +1 -0
  269. package/build/plugins/events/types.d.ts +12 -0
  270. package/build/plugins/events/types.d.ts.map +1 -0
  271. package/build/plugins/events/types.js +2 -0
  272. package/build/plugins/events/types.js.map +1 -0
  273. package/build/plugins/events.d.ts +6 -13
  274. package/build/plugins/events.d.ts.map +1 -1
  275. package/build/plugins/events.js +445 -145
  276. package/build/plugins/events.js.map +1 -1
  277. package/build/plugins/fx/types.d.ts +33 -0
  278. package/build/plugins/fx/types.d.ts.map +1 -0
  279. package/build/plugins/fx/types.js +2 -0
  280. package/build/plugins/fx/types.js.map +1 -0
  281. package/build/plugins/fx.d.ts +6 -0
  282. package/build/plugins/fx.d.ts.map +1 -0
  283. package/build/plugins/fx.js +83 -0
  284. package/build/plugins/fx.js.map +1 -0
  285. package/build/plugins/portal/types.d.ts +44 -0
  286. package/build/plugins/portal/types.d.ts.map +1 -0
  287. package/build/plugins/portal/types.js +2 -0
  288. package/build/plugins/portal/types.js.map +1 -0
  289. package/build/plugins/portal.d.ts +6 -0
  290. package/build/plugins/portal.d.ts.map +1 -0
  291. package/build/plugins/portal.js +255 -0
  292. package/build/plugins/portal.js.map +1 -0
  293. package/build/plugins/refunds/types.d.ts +35 -0
  294. package/build/plugins/refunds/types.d.ts.map +1 -0
  295. package/build/plugins/refunds/types.js +2 -0
  296. package/build/plugins/refunds/types.js.map +1 -0
  297. package/build/plugins/refunds.d.ts +6 -0
  298. package/build/plugins/refunds.d.ts.map +1 -0
  299. package/build/plugins/refunds.js +81 -0
  300. package/build/plugins/refunds.js.map +1 -0
  301. package/build/plugins/session/types.d.ts +34 -0
  302. package/build/plugins/session/types.d.ts.map +1 -0
  303. package/build/plugins/session/types.js +2 -0
  304. package/build/plugins/session/types.js.map +1 -0
  305. package/build/plugins/session.d.ts +4 -0
  306. package/build/plugins/session.d.ts.map +1 -0
  307. package/build/plugins/session.js +71 -0
  308. package/build/plugins/session.js.map +1 -0
  309. package/build/plugins/status.d.ts +8 -0
  310. package/build/plugins/status.d.ts.map +1 -0
  311. package/build/plugins/status.js +21 -0
  312. package/build/plugins/status.js.map +1 -0
  313. package/build/plugins/stripe/types.d.ts +20 -0
  314. package/build/plugins/stripe/types.d.ts.map +1 -0
  315. package/build/plugins/stripe/types.js +2 -0
  316. package/build/plugins/stripe/types.js.map +1 -0
  317. package/build/plugins/stripe.d.ts +5 -13
  318. package/build/plugins/stripe.d.ts.map +1 -1
  319. package/build/plugins/stripe.js +481 -129
  320. package/build/plugins/stripe.js.map +1 -1
  321. package/build/plugins/subscriptions/types.d.ts +41 -0
  322. package/build/plugins/subscriptions/types.d.ts.map +1 -0
  323. package/build/plugins/subscriptions/types.js +2 -0
  324. package/build/plugins/subscriptions/types.js.map +1 -0
  325. package/build/plugins/subscriptions.d.ts +6 -0
  326. package/build/plugins/subscriptions.d.ts.map +1 -0
  327. package/build/plugins/subscriptions.js +169 -0
  328. package/build/plugins/subscriptions.js.map +1 -0
  329. package/build/plugins/types.d.ts +7 -0
  330. package/build/plugins/types.d.ts.map +1 -0
  331. package/build/plugins/types.js +2 -0
  332. package/build/plugins/types.js.map +1 -0
  333. package/build/plugins/types.local.d.ts +75 -0
  334. package/build/plugins/types.local.d.ts.map +1 -0
  335. package/build/plugins/types.local.js +2 -0
  336. package/build/plugins/types.local.js.map +1 -0
  337. package/build/plugins/webhook-manager/types.d.ts +62 -0
  338. package/build/plugins/webhook-manager/types.d.ts.map +1 -0
  339. package/build/plugins/webhook-manager/types.js +2 -0
  340. package/build/plugins/webhook-manager/types.js.map +1 -0
  341. package/build/plugins/webhook-manager.d.ts +8 -0
  342. package/build/plugins/webhook-manager.d.ts.map +1 -0
  343. package/build/plugins/webhook-manager.js +245 -0
  344. package/build/plugins/webhook-manager.js.map +1 -0
  345. package/build/protocol.d.ts +13 -0
  346. package/build/protocol.d.ts.map +1 -0
  347. package/build/protocol.js +17 -0
  348. package/build/protocol.js.map +1 -0
  349. package/build/reconcile/types.d.ts +17 -0
  350. package/build/reconcile/types.d.ts.map +1 -0
  351. package/build/reconcile/types.js +2 -0
  352. package/build/reconcile/types.js.map +1 -0
  353. package/build/reconcile.d.ts +12 -0
  354. package/build/reconcile.d.ts.map +1 -0
  355. package/build/reconcile.js +91 -0
  356. package/build/reconcile.js.map +1 -0
  357. package/build/resource.d.ts +12 -1
  358. package/build/resource.d.ts.map +1 -1
  359. package/build/resource.js +97 -6
  360. package/build/resource.js.map +1 -1
  361. package/build/schemas.d.ts +19 -0
  362. package/build/schemas.d.ts.map +1 -0
  363. package/build/schemas.js +244 -0
  364. package/build/schemas.js.map +1 -0
  365. package/build/service.d.ts +28 -3
  366. package/build/service.d.ts.map +1 -1
  367. package/build/service.js +140 -19
  368. package/build/service.js.map +1 -1
  369. package/build/subscription/types.d.ts +21 -0
  370. package/build/subscription/types.d.ts.map +1 -0
  371. package/build/subscription/types.js +2 -0
  372. package/build/subscription/types.js.map +1 -0
  373. package/build/subscription.d.ts +4 -0
  374. package/build/subscription.d.ts.map +1 -0
  375. package/build/subscription.js +84 -0
  376. package/build/subscription.js.map +1 -0
  377. package/build/sync/types.d.ts +25 -0
  378. package/build/sync/types.d.ts.map +1 -0
  379. package/build/sync/types.js +2 -0
  380. package/build/sync/types.js.map +1 -0
  381. package/build/sync.d.ts +4 -3
  382. package/build/sync.d.ts.map +1 -1
  383. package/build/sync.js +231 -79
  384. package/build/sync.js.map +1 -1
  385. package/build/types.d.ts +1262 -36
  386. package/build/types.d.ts.map +1 -1
  387. package/build/types.local.d.ts +22 -0
  388. package/build/types.local.d.ts.map +1 -0
  389. package/build/types.local.js +2 -0
  390. package/build/types.local.js.map +1 -0
  391. package/build/usage/types.d.ts +56 -0
  392. package/build/usage/types.d.ts.map +1 -0
  393. package/build/usage/types.js +2 -0
  394. package/build/usage/types.js.map +1 -0
  395. package/build/usage.d.ts +6 -0
  396. package/build/usage.d.ts.map +1 -0
  397. package/build/usage.js +365 -0
  398. package/build/usage.js.map +1 -0
  399. package/build/utils/types.d.ts +31 -0
  400. package/build/utils/types.d.ts.map +1 -0
  401. package/build/utils/types.js +2 -0
  402. package/build/utils/types.js.map +1 -0
  403. package/build/utils.d.ts +21 -7
  404. package/build/utils.d.ts.map +1 -1
  405. package/build/utils.js +56 -17
  406. package/build/utils.js.map +1 -1
  407. package/package.json +22 -17
  408. package/src/access/types.ts +52 -0
  409. package/src/access.ts +86 -0
  410. package/src/actions/index.ts +1 -0
  411. package/src/actions/resync-subscriptions.ts +10 -0
  412. package/src/actions/resync.ts +14 -5
  413. package/src/actions/webhook.ts +9 -4
  414. package/src/bootstrap/types.ts +16 -0
  415. package/src/bootstrap.ts +31 -0
  416. package/src/catalogue/types.ts +32 -0
  417. package/src/catalogue.ts +135 -0
  418. package/src/commit/types.ts +27 -0
  419. package/src/commit.ts +152 -0
  420. package/src/config.ts +234 -14
  421. package/src/consts.local.ts +62 -0
  422. package/src/consts.ts +100 -36
  423. package/src/consumer/cancellation/types.ts +13 -0
  424. package/src/consumer/cancellation.ts +43 -0
  425. package/src/consumer/capture/types.ts +53 -0
  426. package/src/consumer/capture.ts +322 -0
  427. package/src/consumer/consts.local.ts +18 -0
  428. package/src/consumer/format/types.ts +29 -0
  429. package/src/consumer/format.ts +85 -0
  430. package/src/consumer/handlers.ts +204 -0
  431. package/src/consumer/index.ts +9 -0
  432. package/src/consumer/mail/types.ts +31 -0
  433. package/src/consumer/mail.ts +353 -0
  434. package/src/consumer/observers/types.ts +22 -0
  435. package/src/consumer/observers.ts +97 -0
  436. package/src/consumer/origin/types.ts +17 -0
  437. package/src/consumer/origin.ts +61 -0
  438. package/src/consumer/reconcile/types.ts +13 -0
  439. package/src/consumer/reconcile.ts +331 -0
  440. package/src/consumer/records/types.ts +64 -0
  441. package/src/consumer/records.ts +288 -0
  442. package/src/consumer/service.ts +768 -0
  443. package/src/consumer/types.local.ts +22 -0
  444. package/src/consumer/types.ts +96 -0
  445. package/src/consumer/withdrawal/types.ts +37 -0
  446. package/src/consumer/withdrawal.ts +268 -0
  447. package/src/entitlement.ts +85 -0
  448. package/src/entrypoints.ts +17 -4
  449. package/src/gate/request.ts +24 -0
  450. package/src/gate/types.ts +13 -0
  451. package/src/gate.ts +47 -30
  452. package/src/index.ts +55 -3
  453. package/src/limit.ts +54 -0
  454. package/src/log.ts +4 -0
  455. package/src/models/declarations/types.ts +22 -0
  456. package/src/models/declarations.ts +30 -0
  457. package/src/models/purchase/types.ts +13 -0
  458. package/src/models/purchase.ts +43 -0
  459. package/src/observer.ts +44 -11
  460. package/src/plan/types.ts +21 -0
  461. package/src/plan.ts +46 -0
  462. package/src/plugins/checkout-plugins/types.ts +25 -0
  463. package/src/plugins/checkout-plugins.ts +90 -0
  464. package/src/plugins/checkout-policy/types.ts +18 -0
  465. package/src/plugins/checkout-policy.ts +34 -0
  466. package/src/plugins/checkout-registry/types.ts +7 -0
  467. package/src/plugins/checkout-registry.ts +23 -0
  468. package/src/plugins/consts.local.ts +30 -0
  469. package/src/plugins/customer-lock/types.ts +5 -0
  470. package/src/plugins/customer-lock.ts +25 -0
  471. package/src/plugins/estimate/cache.ts +12 -0
  472. package/src/plugins/estimate/types.ts +28 -0
  473. package/src/plugins/estimate.ts +305 -0
  474. package/src/plugins/events/types.ts +11 -0
  475. package/src/plugins/events.ts +470 -133
  476. package/src/plugins/fx/types.ts +40 -0
  477. package/src/plugins/fx.ts +101 -0
  478. package/src/plugins/portal/types.ts +45 -0
  479. package/src/plugins/portal.ts +284 -0
  480. package/src/plugins/refunds/types.ts +31 -0
  481. package/src/plugins/refunds.ts +95 -0
  482. package/src/plugins/session/types.ts +30 -0
  483. package/src/plugins/session.ts +86 -0
  484. package/src/plugins/status.ts +22 -0
  485. package/src/plugins/stripe/types.ts +20 -0
  486. package/src/plugins/stripe.ts +523 -135
  487. package/src/plugins/subscriptions/types.ts +39 -0
  488. package/src/plugins/subscriptions.ts +195 -0
  489. package/src/plugins/types.local.ts +61 -0
  490. package/src/plugins/types.ts +7 -0
  491. package/src/plugins/webhook-manager/types.ts +63 -0
  492. package/src/plugins/webhook-manager.ts +288 -0
  493. package/src/protocol.ts +29 -0
  494. package/src/reconcile/types.ts +17 -0
  495. package/src/reconcile.ts +110 -0
  496. package/src/resource.ts +158 -11
  497. package/src/schemas.ts +271 -0
  498. package/src/service.ts +161 -19
  499. package/src/subscription/types.ts +23 -0
  500. package/src/subscription.ts +104 -0
  501. package/src/sync/types.ts +25 -0
  502. package/src/sync.ts +255 -72
  503. package/src/types.local.ts +18 -0
  504. package/src/types.ts +1369 -32
  505. package/src/usage/types.ts +51 -0
  506. package/src/usage.ts +432 -0
  507. package/src/utils/types.ts +30 -0
  508. package/src/utils.ts +94 -29
  509. package/tests/checkout-consumer.spec.ts +366 -0
  510. package/tests/checkout-locks.spec.ts +161 -0
  511. package/tests/checkout-plugins.spec.ts +164 -0
  512. package/tests/checkout.spec.ts +271 -93
  513. package/tests/consumer-events.spec.ts +215 -0
  514. package/tests/consumer-fixtures.ts +141 -0
  515. package/tests/consumer-ops.spec.ts +361 -0
  516. package/tests/consumer-rights.integration.spec.ts +147 -0
  517. package/tests/consumer-rights.spec.ts +606 -0
  518. package/tests/context.ts +110 -0
  519. package/tests/entitlement.spec.ts +139 -0
  520. package/tests/estimate.spec.ts +350 -0
  521. package/tests/events.spec.ts +367 -0
  522. package/tests/fake-stripe.ts +987 -0
  523. package/tests/gate-handlers.spec.ts +120 -0
  524. package/tests/gate.spec.ts +63 -72
  525. package/tests/gateway-options.spec.ts +180 -0
  526. package/tests/limit-gate.spec.ts +66 -0
  527. package/tests/portal.spec.ts +202 -0
  528. package/tests/protocol.spec.ts +17 -3
  529. package/tests/sync.spec.ts +114 -0
  530. package/tests/usage.integration.spec.ts +133 -0
  531. package/tests/usage.spec.ts +169 -0
  532. package/tests/webhook-manager.spec.ts +149 -0
  533. package/build/model.d.ts +0 -6
  534. package/build/model.d.ts.map +0 -1
  535. package/build/model.js +0 -33
  536. package/build/model.js.map +0 -1
  537. package/src/model.ts +0 -37
@@ -0,0 +1,987 @@
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_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, makePaygateCustomerResource,
24
+ 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, 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
+ const matchRaw = (filter: Rec) => store.rows.find(row => recordQueryHelper.matchCriteria(row, filter))
735
+ const upsert = (filter: Rec, update: Rec, opts: Rec = {}): { doc: Rec | null, inserted: boolean } => {
736
+ const found = matchRaw(filter)
737
+ if (found != null) {
738
+ applyUpdate(found, update, false)
739
+ return { doc: found, inserted: false }
740
+ }
741
+ if (opts.upsert !== true) return { doc: null, inserted: false }
742
+ const doc: Rec = Object.fromEntries(Object.entries(filter).filter(([, value]) =>
743
+ value === null || typeof value !== 'object' || value instanceof Date))
744
+ applyUpdate(doc, update, true)
745
+ if (violates(doc)) throw duplicate()
746
+ doc.id = `${resource.alias}-${++seq}`
747
+ store.rows.push(doc)
748
+ return { doc, inserted: true }
749
+ }
750
+ target.collection = {
751
+ findOneAndUpdate: async (filter: Rec, update: Rec, opts: Rec = {}) => {
752
+ guard('findOneAndUpdate')
753
+ const before = matchRaw(filter)
754
+ const snapshot = before != null ? structuredClone(before) : null
755
+ const { doc } = upsert(filter, update, opts)
756
+ if (doc == null) return null
757
+ const result = opts.returnDocument === 'after' ? doc : snapshot
758
+ return result == null ? null : { ...structuredClone(result), _id: result.id }
759
+ },
760
+ updateOne: async (filter: Rec, update: Rec, opts: Rec = {}) => {
761
+ guard('updateOne')
762
+ // Like Mongo: an update is checked against the unique indexes before it lands.
763
+ const found = matchRaw(filter)
764
+ if (found != null) {
765
+ const candidate = structuredClone(found)
766
+ applyUpdate(candidate, update, false)
767
+ if (violates(candidate, found)) throw duplicate()
768
+ }
769
+ const { doc, inserted } = upsert(filter, update, opts)
770
+ return { matchedCount: doc != null && !inserted ? 1 : 0, upsertedCount: inserted ? 1 : 0 }
771
+ },
772
+ deleteOne: async (filter: Rec) => {
773
+ const row = matchRaw(filter)
774
+ store.rows = store.rows.filter(item => item !== row)
775
+ return { deletedCount: row != null ? 1 : 0 }
776
+ },
777
+ distinct: async (field: string, filter: Rec = {}) =>
778
+ [...new Set(store.rows.filter(row => recordQueryHelper.matchCriteria(row, filter)).map(row => row[field]))],
779
+ aggregate: (pipeline: Rec[]) => ({
780
+ toArray: async () => {
781
+ guard('aggregate')
782
+ let docs: Rec[] = store.rows.map(row => structuredClone(row))
783
+ for (const stage of pipeline) {
784
+ if (stage.$match != null) {
785
+ docs = docs.filter(doc => recordQueryHelper.matchCriteria(doc, stage.$match))
786
+ } else if (stage.$group != null) {
787
+ const groups = new Map<string, Rec>()
788
+ const { _id: key, ...accumulators } = stage.$group
789
+ for (const doc of docs) {
790
+ const id = Object.fromEntries(Object.entries(key as Rec).map(([name, ref]) => [name, doc[(ref as string).slice(1)]]))
791
+ const hash = JSON.stringify(id)
792
+ const group = groups.get(hash) ?? { _id: id }
793
+ for (const [name, spec] of Object.entries(accumulators as Rec)) {
794
+ group[name] = (group[name] ?? 0) + (doc[(spec.$sum as string).slice(1)] ?? 0)
795
+ }
796
+ groups.set(hash, group)
797
+ }
798
+ docs = [...groups.values()]
799
+ } else {
800
+ throw new Error(`unsupported stage ${JSON.stringify(stage)}`)
801
+ }
802
+ }
803
+ return docs
804
+ },
805
+ }),
806
+ }
807
+
808
+ return store
809
+ }
810
+
811
+ // -----------------------------------------------------------------------------------------------
812
+ // Context
813
+ // -----------------------------------------------------------------------------------------------
814
+
815
+ export interface FakeContextOptions {
816
+ catalogue?: CatalogueOptions
817
+ /** Declare the catalogue yourself instead. */
818
+ declare?: (cfg: Config) => void
819
+ /** This process's `cfg.service` (default `app`). */
820
+ service?: string
821
+ /** The public host of this process's service (default `api.example.com`). */
822
+ host?: string
823
+ /** The base path of this process's service (default none). */
824
+ base?: string
825
+ /** Further backend services by alias, each on its own host (and base). */
826
+ services?: Record<string, { host: string, base?: string }>
827
+ /** The configured webhook override secret. */
828
+ webhookSecret?: string
829
+ portal?: PortalBrandingDef
830
+ pricing?: PricingDef
831
+ stripe?: Partial<FakeStripeState>
832
+ /** Rows each store (by resource alias) holds before the context initializes — a shared database. */
833
+ seed?: Record<string, Rec[]>
834
+ /** Declare a consumer-rights policy (with trader and mail options). */
835
+ consumerRights?: ConsumerRightsDef
836
+ /** The consumer-rights usage meter. */
837
+ meter?: UsageMeter
838
+ /** Register a console mailer under `MAILER_SERVICE` (default true). */
839
+ mailer?: boolean
840
+ /** Register the gateway before the application's consumer-rights call (default: after). */
841
+ gatewayFirst?: boolean
842
+ /** The application's consumer-rights options (default: managed through the fake, with `meter`). */
843
+ rights?: (stripe: Stripe) => ConsumerRightsOptions
844
+ /** The gateway's options (default `{ manage: false }`); its Stripe client is always the fake. */
845
+ gateway?: GatewayServiceOptions
846
+ /** Run on the context after the registrations, before it is configured and initialized. */
847
+ wire?: (ctx: ApiContext) => void
848
+ }
849
+
850
+ export interface Observed {
851
+ topUp: TopUpCompletion[]
852
+ subscription: SubscriptionEvent[]
853
+ refund: RefundEvent[]
854
+ dispute: DisputeEvent[]
855
+ paymentFailed: PaymentFailedEvent[]
856
+ consent: ConsentEvent[]
857
+ withdrawal: WithdrawalEvent[]
858
+ cancellation: CancellationEvent[]
859
+ /** Throw from the next `n` subscription callbacks. */
860
+ failSubscription: number
861
+ failTopUp: number
862
+ failWithdrawal: number
863
+ /** Run inside every top-up / subscription callback, before it records the event. */
864
+ onTopUp?: (event: TopUpCompletion) => Promise<void>
865
+ onSubscription?: (event: SubscriptionEvent) => Promise<void>
866
+ }
867
+
868
+ export interface FakeContext {
869
+ ctx: ApiContext
870
+ stripe: Stripe
871
+ state: FakeStripeState
872
+ stores: Record<string, MemoryStore>
873
+ observed: Observed
874
+ /** Every mail the console mailer took. */
875
+ mails: MailMessage[]
876
+ /** The console mailer — replace its `send` to simulate a transport failure. */
877
+ mailer: ReturnType<typeof makeConsoleMailerService>
878
+ }
879
+
880
+ /**
881
+ * A real server context — real catalogue, payment service, observer, gateway (unmanaged unless
882
+ * `gateway` says otherwise), gates and entitlement service — over in-memory resources, with a fake
883
+ * Stripe for the plugin functions and as the gateway's own client.
884
+ */
885
+ export const makeFakeContext = async (opts: FakeContextOptions = {}): Promise<FakeContext> => {
886
+ const own = opts.service ?? SERVICE
887
+ const services: Record<string, unknown> = {
888
+ [own]: { service: own, type: AppType.Backend, host: opts.host ?? HOST, ...(opts.base != null ? { base: opts.base } : {}) },
889
+ }
890
+ for (const [alias, { host, base }] of Object.entries(opts.services ?? {})) {
891
+ services[alias] = { service: alias, type: AppType.Backend, host, ...(base != null ? { base } : {}) }
892
+ }
893
+ const cfg = serverConfig<ServerConfig>(own, { services } as Partial<ServerConfig>) as unknown as Config
894
+ if (opts.declare != null) {
895
+ opts.declare(cfg)
896
+ } else {
897
+ declareTestCatalogue(cfg, opts.catalogue)
898
+ }
899
+ stripeSecrets(cfg, { api: 'sk_test_offline', ...(opts.webhookSecret != null ? { webhook: opts.webhookSecret } : {}) })
900
+ if (opts.portal != null) {
901
+ portalBranding(cfg, opts.portal)
902
+ }
903
+ if (opts.pricing != null) {
904
+ declarePaymentPricing(cfg, opts.pricing)
905
+ }
906
+ if (opts.consumerRights != null) {
907
+ declareConsumerRights(cfg, opts.consumerRights)
908
+ }
909
+
910
+ const ctx = makeServerContext(cfg as unknown as ServerConfig) as unknown as ApiContext
911
+ const stores: Record<string, MemoryStore> = {}
912
+ const resources = [
913
+ [RES_PAYGATE_CUSTOMER, makePaygateCustomerResource()],
914
+ [RES_PAYMENT_SUBSCRIPTION, makeSubscriptionResource()],
915
+ [RES_PAYMENT_FULFILLMENT, makeFulfillmentResource()],
916
+ [RES_PAYMENT_WEBHOOK, makeWebhookResource()],
917
+ [RES_PAYMENT_USAGE, makeUsageResource()],
918
+ [RES_PAYMENT_USAGE_COUNTER, makeUsageCounterResource()],
919
+ [RES_PAYMENT_FINGERPRINT, makeFingerprintResource()],
920
+ [RES_BILLING_PROFILE, makeBillingProfileResource()],
921
+ [RES_PAYMENT_PURCHASE, makePurchaseResource()],
922
+ [RES_CONSUMER_CONSENT, makeConsumerConsentResource()],
923
+ [RES_CONSUMER_DECLARATION, makeConsumerDeclarationResource()],
924
+ [RES_CONSUMER_EVENT, makeConsumerEventResource()],
925
+ ] as const
926
+ for (const [alias, resource] of resources) {
927
+ stores[alias] = memoryResource(resource as unknown as MongoResource<ResourceRecord>)
928
+ stores[alias].rows.push(...structuredClone(opts.seed?.[alias] ?? []))
929
+ ctx.registerResource(resource as never)
930
+ }
931
+ const { stripe, state } = makeFakeStripe(opts.stripe)
932
+ const mailer = makeConsoleMailerService(MAILER_SERVICE)
933
+ if (opts.mailer !== false) {
934
+ ctx.registerService(mailer)
935
+ }
936
+ // The consumer-rights service manages the paygate through the fake; the gateway stays unmanaged.
937
+ const rights = opts.rights?.(stripe)
938
+ ?? { manage: true, stripe: async () => stripe, ...(opts.meter != null ? { usage: opts.meter } : {}) }
939
+ const gatewayOpts: GatewayServiceOptions = { manage: false, stripe: async () => stripe, ...opts.gateway }
940
+ if (opts.gatewayFirst === true) {
941
+ appendPaymentGatewayService(ctx as never, gatewayOpts)
942
+ appendConsumerRights(ctx as never, rights)
943
+ } else {
944
+ appendConsumerRights(ctx as never, rights)
945
+ appendPaymentGatewayService(ctx as never, gatewayOpts)
946
+ }
947
+ opts.wire?.(ctx)
948
+ ctx.configure()
949
+ await ctx.init()
950
+
951
+ const observed: Observed = {
952
+ topUp: [], subscription: [], refund: [], dispute: [], paymentFailed: [], consent: [], withdrawal: [],
953
+ cancellation: [], failSubscription: 0, failTopUp: 0, failWithdrawal: 0,
954
+ }
955
+ const completions = paymentAccessOf(ctx).observer()
956
+ await completions.ready()
957
+ completions.onTopUp(async event => {
958
+ if (observed.failTopUp > 0) {
959
+ observed.failTopUp--
960
+ throw new Error('ledger unavailable')
961
+ }
962
+ await observed.onTopUp?.(event)
963
+ observed.topUp.push(event)
964
+ })
965
+ completions.onSubscription(async event => {
966
+ if (observed.failSubscription > 0) {
967
+ observed.failSubscription--
968
+ throw new Error('observer unavailable')
969
+ }
970
+ await observed.onSubscription?.(event)
971
+ observed.subscription.push(event)
972
+ })
973
+ completions.onRefund(async event => { observed.refund.push(event) })
974
+ completions.onDispute(async event => { observed.dispute.push(event) })
975
+ completions.onPaymentFailed(async event => { observed.paymentFailed.push(event) })
976
+ completions.onConsent(async event => { observed.consent.push(event) })
977
+ completions.onWithdrawal(async event => {
978
+ if (observed.failWithdrawal > 0) {
979
+ observed.failWithdrawal--
980
+ throw new Error('ledger unavailable')
981
+ }
982
+ observed.withdrawal.push(event)
983
+ })
984
+ completions.onCancellation(async event => { observed.cancellation.push(event) })
985
+
986
+ return { ctx, stripe, state, stores, observed, mails: mailer.captured, mailer }
987
+ }