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

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 +613 -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 +284 -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 +320 -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 +441 -144
  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 +32 -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 +58 -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 +1258 -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 +321 -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 +330 -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 +466 -132
  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 +28 -0
  483. package/src/plugins/session.ts +73 -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 +1365 -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 +209 -93
  513. package/tests/consumer-events.spec.ts +215 -0
  514. package/tests/consumer-fixtures.ts +134 -0
  515. package/tests/consumer-ops.spec.ts +350 -0
  516. package/tests/consumer-rights.integration.spec.ts +147 -0
  517. package/tests/consumer-rights.spec.ts +572 -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 +357 -0
  522. package/tests/fake-stripe.ts +981 -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,981 @@
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 rate = invoice.subtotal > 0 ? (invoice.tax ?? 0) / invoice.subtotal : 0
330
+ const amount = params.lines.reduce((sum: number, line: Rec) => sum + (line.amount ?? 0), 0)
331
+ const tax = Math.round(amount * rate)
332
+ return { id: 'cnpreview', object: 'credit_note', amount: amount + tax, total: amount + tax, subtotal: amount, currency: invoice.currency }
333
+ },
334
+ create: async (params: Rec, options?: Rec) => {
335
+ call('creditNotes.create', options)
336
+ const invoice = state.invoices[params.invoice]
337
+ if (invoice == null) throw missing('invoice')
338
+ const rate = invoice.subtotal > 0 ? (invoice.tax ?? 0) / invoice.subtotal : 0
339
+ const amount = params.lines.reduce((sum: number, line: Rec) => sum + (line.amount ?? 0), 0)
340
+ const note = {
341
+ id: next('cn'), object: 'credit_note', invoice: params.invoice, refund: params.refund, status: 'issued',
342
+ total: amount + Math.round(amount * rate), currency: invoice.currency, memo: params.memo,
343
+ metadata: { ...params.metadata }, lines: structuredClone(params.lines),
344
+ }
345
+ state.creditNotes.push(note)
346
+ return structuredClone(note)
347
+ },
348
+ list: async (params: Rec = {}) => {
349
+ call('creditNotes.list')
350
+ return page(state.creditNotes.filter(note => params.invoice == null || note.invoice === params.invoice), params)
351
+ },
352
+ },
353
+ invoices: {
354
+ retrieve: async (id: string) => {
355
+ call('invoices.retrieve')
356
+ const invoice = state.invoices[id]
357
+ if (invoice == null) throw missing('invoice')
358
+ return structuredClone(invoice)
359
+ },
360
+ },
361
+ charges: {
362
+ retrieve: async (id: string) => {
363
+ call('charges.retrieve')
364
+ const charge = state.charges[id]
365
+ if (charge == null) throw missing('charge')
366
+ return structuredClone(charge)
367
+ },
368
+ },
369
+ refunds: {
370
+ list: async (params: Rec = {}) => {
371
+ call('refunds.list')
372
+ return page(state.refunds.filter(refund => (params.charge == null || refund.charge === params.charge)
373
+ && (params.payment_intent == null || refund.payment_intent === params.payment_intent)), params)
374
+ },
375
+ create: async (params: Rec, options?: Rec) => {
376
+ call('refunds.create', options)
377
+ const refund = {
378
+ id: next('re'), object: 'refund', amount: params.amount, currency: params.currency ?? 'eur', status: 'succeeded',
379
+ payment_intent: params.payment_intent, charge: null, reason: params.reason, metadata: { ...params.metadata },
380
+ }
381
+ state.refunds.push(refund)
382
+ return structuredClone(refund)
383
+ },
384
+ },
385
+ prices: {
386
+ list: async (params: Rec = {}) => {
387
+ call('prices.list')
388
+ return page(state.prices.filter(price => (params.product == null || price.product === params.product)
389
+ && (params.active == null || price.active === params.active)
390
+ && (params.lookup_keys == null || params.lookup_keys.includes(price.lookup_key))), { limit: 100, ...params })
391
+ },
392
+ create: async (params: Rec) => {
393
+ call('prices.create')
394
+ // Stripe's own default: a price created with no `tax_behavior` is `unspecified`.
395
+ const price = { id: next('price'), active: true, tax_behavior: 'unspecified', ...structuredClone(params) }
396
+ state.prices.push(price)
397
+ return structuredClone(price)
398
+ },
399
+ update: async (id: string, params: Rec) => {
400
+ call('prices.update')
401
+ const price = find(state.prices, id, 'price')
402
+ if (
403
+ params.tax_behavior != null && price.tax_behavior != null && price.tax_behavior !== 'unspecified'
404
+ && price.tax_behavior !== params.tax_behavior
405
+ ) {
406
+ // Real Stripe: once a price's `tax_behavior` is `exclusive` or `inclusive`, it cannot change.
407
+ throw invalidRequest('parameter_invalid_empty')
408
+ }
409
+ Object.assign(price, params)
410
+ return structuredClone(price)
411
+ },
412
+ },
413
+ products: {
414
+ retrieve: async (id: string) => {
415
+ call('products.retrieve')
416
+ if (state.products[id] == null) throw missing('product')
417
+ return structuredClone(state.products[id])
418
+ },
419
+ update: async (id: string, params: Rec) => {
420
+ call('products.update')
421
+ Object.assign(state.products[id], params)
422
+ return structuredClone(state.products[id])
423
+ },
424
+ create: async (params: Rec) => {
425
+ call('products.create')
426
+ state.products[params.id] = structuredClone(params)
427
+ return structuredClone(params)
428
+ },
429
+ },
430
+ customers: {
431
+ retrieve: async (id: string) => {
432
+ call('customers.retrieve')
433
+ if (state.customers[id] == null) throw missing('customer')
434
+ return structuredClone(state.customers[id])
435
+ },
436
+ create: async (params: Rec) => {
437
+ call('customers.create')
438
+ const customer = { id: next('cus'), object: 'customer', address: null, ...structuredClone(params) }
439
+ state.customers[customer.id] = customer
440
+ return structuredClone(customer)
441
+ },
442
+ update: async (id: string, params: Rec) => {
443
+ call('customers.update')
444
+ const customer = state.customers[id]
445
+ if (customer == null) throw missing('customer')
446
+ Object.assign(customer, params)
447
+ return structuredClone(customer)
448
+ },
449
+ },
450
+ checkout: {
451
+ sessions: {
452
+ create: async (params: Rec) => {
453
+ call('checkout.sessions.create')
454
+ state.checkoutSessions.push(structuredClone(params))
455
+ return { id: next('cs'), url: `https://checkout.example.test/${state.seq}` }
456
+ },
457
+ expire: async (id: string) => {
458
+ call('checkout.sessions.expire')
459
+ state.expiredSessions.push(id)
460
+ return { id, status: 'expired' }
461
+ },
462
+ list: async (params: Rec = {}) => {
463
+ call('checkout.sessions.list')
464
+ return page(state.listedSessions.filter(session => (params.status == null || session.status === params.status)
465
+ && (params.created?.gte == null || session.created >= params.created.gte)), params)
466
+ },
467
+ listLineItems: async () => {
468
+ call('checkout.sessions.listLineItems')
469
+ return { data: [{ quantity: state.lineItemQuantity }] }
470
+ },
471
+ },
472
+ },
473
+ tax: {
474
+ calculations: {
475
+ /**
476
+ * A flat-percentage tax model, entirely driven by `state.taxRates` / `taxInvalidCountries`
477
+ * / `taxUnsupportedCountries` — real enough to exercise the status mapping and the
478
+ * scalability rule, never a stand-in for Stripe's actual jurisdiction logic.
479
+ */
480
+ create: async (params: Rec) => {
481
+ call('tax.calculations.create')
482
+ state.taxCalculations.push(structuredClone(params))
483
+ const country = params.customer_details?.address?.country as string | undefined
484
+ if (country != null && state.taxInvalidCountries.includes(country)) {
485
+ throw invalidRequest('customer_tax_location_invalid')
486
+ }
487
+ const lineItem = params.line_items[0]
488
+ const amount: number = lineItem.amount
489
+ const inclusive = lineItem.tax_behavior === 'inclusive'
490
+ const reverseCharge = (params.customer_details?.tax_ids ?? []).length > 0
491
+ const rates = reverseCharge ? [] : (country != null ? state.taxRates[country] ?? [] : [])
492
+ const unsupported = !reverseCharge && rates.length === 0
493
+ && country != null && state.taxUnsupportedCountries.includes(country)
494
+
495
+ const breakdown = reverseCharge
496
+ ? [{
497
+ amount: 0, inclusive, taxable_amount: amount, taxability_reason: 'reverse_charge',
498
+ tax_rate_details: { country, state: null, percentage_decimal: '0', tax_type: 'vat' },
499
+ }]
500
+ : unsupported
501
+ ? [{
502
+ amount: 0, inclusive, taxable_amount: amount, taxability_reason: 'not_supported',
503
+ tax_rate_details: null,
504
+ }]
505
+ : rates.length === 0
506
+ ? [{
507
+ amount: 0, inclusive, taxable_amount: amount, taxability_reason: 'not_collecting',
508
+ tax_rate_details: { country, state: null, percentage_decimal: '0', tax_type: 'vat' },
509
+ }]
510
+ : rates.map(rate => ({
511
+ amount: Math.round(amount * Number(rate.percentage) / 100), inclusive, taxable_amount: amount,
512
+ taxability_reason: 'standard_rated',
513
+ tax_rate_details: { country, state: null, percentage_decimal: rate.percentage, tax_type: rate.type },
514
+ }))
515
+ const taxTotal = breakdown.reduce((sum, row) => sum + row.amount, 0)
516
+
517
+ return {
518
+ id: next('taxcalc'), object: 'tax.calculation', currency: params.currency,
519
+ amount_total: inclusive ? amount : amount + taxTotal,
520
+ tax_amount_exclusive: inclusive ? 0 : taxTotal,
521
+ tax_amount_inclusive: inclusive ? taxTotal : 0,
522
+ tax_breakdown: breakdown,
523
+ }
524
+ },
525
+ },
526
+ settings: {
527
+ retrieve: async () => {
528
+ call('tax.settings.retrieve')
529
+ return structuredClone(state.taxSettings)
530
+ },
531
+ },
532
+ },
533
+ rawRequest: async (method: string, path: string, params: Rec = {}) => {
534
+ call('rawRequest')
535
+ state.rawRequests.push({ method, path, params: structuredClone(params) })
536
+ if (path !== '/v1/fx_quotes') {
537
+ throw new Error(`fake-stripe: unhandled rawRequest path "${path}"`)
538
+ }
539
+ if (state.fxUnavailable) {
540
+ throw new Error('fx_quotes unavailable')
541
+ }
542
+ const local = params['from_currencies[]'] as string
543
+ const rate = state.fxRates[local]
544
+ if (rate == null) {
545
+ return { rates: {} }
546
+ }
547
+ return {
548
+ rates: {
549
+ [local]: {
550
+ exchange_rate: rate.exchangeRate,
551
+ rate_details: {
552
+ base_rate: rate.baseRate ?? rate.exchangeRate,
553
+ reference_rate: rate.referenceRate ?? rate.baseRate ?? rate.exchangeRate,
554
+ fx_fee_rate: rate.fxFeeRate ?? 0.02,
555
+ },
556
+ },
557
+ },
558
+ }
559
+ },
560
+ webhooks: {
561
+ /** Accepts the signature `sig:<secret>` over any body. */
562
+ constructEventAsync: async (raw: string | Buffer, signature: string, secret: string) => {
563
+ if (signature !== `sig:${secret}`) throw new Error('bad signature')
564
+ return JSON.parse(raw.toString())
565
+ },
566
+ },
567
+ }
568
+
569
+ return { stripe: stripe as unknown as Stripe, state }
570
+ }
571
+
572
+ // -----------------------------------------------------------------------------------------------
573
+ // Stripe objects
574
+ // -----------------------------------------------------------------------------------------------
575
+
576
+ let objectSeq = 0
577
+ const epoch = (date: Date): number => Math.floor(date.getTime() / 1000)
578
+
579
+ export interface SubscriptionShape {
580
+ id?: string
581
+ customer?: string
582
+ entityId?: string
583
+ planSku?: string
584
+ status?: Stripe.Subscription.Status
585
+ itemId?: string
586
+ priceId?: string
587
+ periodStart?: Date
588
+ periodEnd?: Date
589
+ cancelAtPeriodEnd?: boolean
590
+ pauseCollection?: Rec | null
591
+ trialEnd?: Date
592
+ latestInvoice?: string
593
+ created?: Date
594
+ endedAt?: Date
595
+ defaultPaymentMethod?: string
596
+ }
597
+
598
+ export const subscriptionOf = (shape: SubscriptionShape = {}): Stripe.Subscription => ({
599
+ id: shape.id ?? 'sub_1',
600
+ object: 'subscription',
601
+ customer: shape.customer ?? 'cus_1',
602
+ status: shape.status ?? 'active',
603
+ metadata: { ...(shape.entityId !== undefined ? { entityId: shape.entityId } : { entityId: 'entity-1' }) },
604
+ items: {
605
+ object: 'list', has_more: false, url: '',
606
+ data: [{ id: shape.itemId ?? 'si_1', price: { id: shape.priceId ?? `price_${shape.planSku ?? PRO}`, lookup_key: shape.planSku ?? PRO } }],
607
+ },
608
+ current_period_start: epoch(shape.periodStart ?? past(1)),
609
+ current_period_end: epoch(shape.periodEnd ?? future(29)),
610
+ cancel_at_period_end: shape.cancelAtPeriodEnd ?? false,
611
+ canceled_at: null,
612
+ ended_at: shape.endedAt != null ? epoch(shape.endedAt) : null,
613
+ pause_collection: shape.pauseCollection ?? null,
614
+ trial_end: shape.trialEnd != null ? epoch(shape.trialEnd) : null,
615
+ latest_invoice: shape.latestInvoice ?? 'in_1',
616
+ created: epoch(shape.created ?? past(1)),
617
+ default_payment_method: shape.defaultPaymentMethod ?? 'pm_1',
618
+ } as unknown as Stripe.Subscription)
619
+
620
+ export const eventOf = (type: string, object: unknown, overrides: Rec = {}): Stripe.Event => ({
621
+ id: `evt_${++objectSeq}`, object: 'event', type, created: epoch(new Date()), data: { object }, ...overrides,
622
+ } as unknown as Stripe.Event)
623
+
624
+ // -----------------------------------------------------------------------------------------------
625
+ // In-memory resources
626
+ // -----------------------------------------------------------------------------------------------
627
+
628
+ const duplicate = (): Error => Object.assign(new Error('E11000 duplicate key error'), { code: 11000 })
629
+
630
+ const plain = (value: unknown): unknown => value instanceof Date ? value.getTime() : value
631
+
632
+ const withoutUndefined = <T extends Rec>(record: T): T =>
633
+ Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined)) as T
634
+
635
+ const applyUpdate = (doc: Rec, update: Rec, inserting: boolean): void => {
636
+ for (const [key, value] of Object.entries(update.$set ?? {})) {
637
+ if (value === undefined) continue
638
+ doc[key] = value
639
+ }
640
+ for (const [key, value] of Object.entries(update.$inc ?? {})) {
641
+ doc[key] = (doc[key] ?? 0) + (value as number)
642
+ }
643
+ for (const key of Object.keys(update.$unset ?? {})) {
644
+ delete doc[key]
645
+ }
646
+ if (inserting) {
647
+ Object.assign(doc, update.$setOnInsert ?? {})
648
+ }
649
+ }
650
+
651
+ export interface MemoryStore {
652
+ rows: Rec[]
653
+ /** Make the next calls of a method throw. */
654
+ failing: Set<string>
655
+ }
656
+
657
+ /**
658
+ * Turn a real resource (its maker's indexes and helpers kept) into an in-memory one over the shared
659
+ * criteria engine, including the raw collection calls the package makes: the conditional counter
660
+ * upsert, `$inc` / `$set` / `$unset`, `$match` + `$group` aggregation and `distinct`.
661
+ */
662
+ export const memoryResource = <T extends ResourceRecord>(resource: MongoResource<T>): MemoryStore => {
663
+ const store: MemoryStore = { rows: [], failing: new Set() }
664
+ const unique = (resource.indexes ?? []).filter(index => index.options?.unique === true)
665
+ .map(index => ({ keys: Object.keys(index.index as Rec), sparse: index.options?.sparse === true }))
666
+ let seq = 0
667
+ const guard = (method: string): void => {
668
+ if (store.failing.has(method)) throw new Error(`${resource.alias}.${method} unavailable`)
669
+ }
670
+ // A sparse unique index ignores a document that carries none of its keys (as Mongo does).
671
+ const violates = (doc: Rec, self?: Rec): boolean => unique.some(({ keys, sparse }) =>
672
+ !(sparse && keys.every(key => doc[key] == null)) && store.rows.some(row =>
673
+ row !== self && keys.every(key => plain(row[key] ?? null) === plain(doc[key] ?? null))))
674
+ const out = (row: Rec): T => structuredClone(row) as T
675
+ const byId = (id: string) => store.rows.find(row => row.id === id)
676
+
677
+ const target = resource as unknown as Rec
678
+ target.init = async () => undefined
679
+ target.get = async (idOrWhere: string | Criteria<T>, opts?: { sort?: never[] }) => {
680
+ guard('get')
681
+ const row = typeof idOrWhere === 'string' ? byId(idOrWhere) : recordQueryHelper.firstMatch(store.rows, idOrWhere as Criteria<any>, opts)
682
+ if (row == null) throw new UnknownRecordError(JSON.stringify(idOrWhere))
683
+ return out(row)
684
+ }
685
+ target.load = async (idOrWhere: string | Criteria<T>, opts?: { sort?: never[] }) => {
686
+ guard('load')
687
+ const row = typeof idOrWhere === 'string' ? byId(idOrWhere) : recordQueryHelper.firstMatch(store.rows, idOrWhere as Criteria<any>, opts)
688
+ return row == null ? null : out(row)
689
+ }
690
+ target.list = async (where?: Criteria<T>, opts?: ListOptions<T>) => {
691
+ guard('list')
692
+ const result = recordQueryHelper.applyQuery(store.rows, where as Criteria<any>, opts as ListOptions<any>)
693
+ return { ...result, items: result.items.map(out) }
694
+ }
695
+ target.count = async (where?: Criteria<T>) => store.rows.filter(row => recordQueryHelper.matchCriteria(row, where)).length
696
+ target.create = async (record: Rec) => {
697
+ guard('create')
698
+ if (record.id != null) throw new RecordExists('id-present')
699
+ const doc = withoutUndefined(structuredClone(record))
700
+ delete doc.id
701
+ if (violates(doc)) throw duplicate()
702
+ doc.id = `${resource.alias}-${++seq}`
703
+ store.rows.push(doc)
704
+ return out(doc)
705
+ }
706
+ target.update = async (record: Rec) => {
707
+ guard('update')
708
+ const existing = byId(record.id)
709
+ if (existing == null) throw new UnknownRecordError(String(record.id))
710
+ const doc = withoutUndefined(structuredClone(record))
711
+ if (violates(doc, existing)) throw duplicate()
712
+ store.rows[store.rows.indexOf(existing)] = doc
713
+ return out(doc)
714
+ }
715
+ target.save = async (record: Rec) => record.id != null ? await target.update(record) : await target.create(record)
716
+ target.delete = async (id: string) => {
717
+ const row = byId(id)
718
+ if (row == null) return null
719
+ store.rows = store.rows.filter(item => item !== row)
720
+ return out(row)
721
+ }
722
+ target.purge = async (where: Criteria<T>) => {
723
+ const before = store.rows.length
724
+ store.rows = store.rows.filter(row => !recordQueryHelper.matchCriteria(row, where))
725
+ return before - store.rows.length
726
+ }
727
+
728
+ const matchRaw = (filter: Rec) => store.rows.find(row => recordQueryHelper.matchCriteria(row, filter))
729
+ const upsert = (filter: Rec, update: Rec, opts: Rec = {}): { doc: Rec | null, inserted: boolean } => {
730
+ const found = matchRaw(filter)
731
+ if (found != null) {
732
+ applyUpdate(found, update, false)
733
+ return { doc: found, inserted: false }
734
+ }
735
+ if (opts.upsert !== true) return { doc: null, inserted: false }
736
+ const doc: Rec = Object.fromEntries(Object.entries(filter).filter(([, value]) =>
737
+ value === null || typeof value !== 'object' || value instanceof Date))
738
+ applyUpdate(doc, update, true)
739
+ if (violates(doc)) throw duplicate()
740
+ doc.id = `${resource.alias}-${++seq}`
741
+ store.rows.push(doc)
742
+ return { doc, inserted: true }
743
+ }
744
+ target.collection = {
745
+ findOneAndUpdate: async (filter: Rec, update: Rec, opts: Rec = {}) => {
746
+ guard('findOneAndUpdate')
747
+ const before = matchRaw(filter)
748
+ const snapshot = before != null ? structuredClone(before) : null
749
+ const { doc } = upsert(filter, update, opts)
750
+ if (doc == null) return null
751
+ const result = opts.returnDocument === 'after' ? doc : snapshot
752
+ return result == null ? null : { ...structuredClone(result), _id: result.id }
753
+ },
754
+ updateOne: async (filter: Rec, update: Rec, opts: Rec = {}) => {
755
+ guard('updateOne')
756
+ // Like Mongo: an update is checked against the unique indexes before it lands.
757
+ const found = matchRaw(filter)
758
+ if (found != null) {
759
+ const candidate = structuredClone(found)
760
+ applyUpdate(candidate, update, false)
761
+ if (violates(candidate, found)) throw duplicate()
762
+ }
763
+ const { doc, inserted } = upsert(filter, update, opts)
764
+ return { matchedCount: doc != null && !inserted ? 1 : 0, upsertedCount: inserted ? 1 : 0 }
765
+ },
766
+ deleteOne: async (filter: Rec) => {
767
+ const row = matchRaw(filter)
768
+ store.rows = store.rows.filter(item => item !== row)
769
+ return { deletedCount: row != null ? 1 : 0 }
770
+ },
771
+ distinct: async (field: string, filter: Rec = {}) =>
772
+ [...new Set(store.rows.filter(row => recordQueryHelper.matchCriteria(row, filter)).map(row => row[field]))],
773
+ aggregate: (pipeline: Rec[]) => ({
774
+ toArray: async () => {
775
+ guard('aggregate')
776
+ let docs: Rec[] = store.rows.map(row => structuredClone(row))
777
+ for (const stage of pipeline) {
778
+ if (stage.$match != null) {
779
+ docs = docs.filter(doc => recordQueryHelper.matchCriteria(doc, stage.$match))
780
+ } else if (stage.$group != null) {
781
+ const groups = new Map<string, Rec>()
782
+ const { _id: key, ...accumulators } = stage.$group
783
+ for (const doc of docs) {
784
+ const id = Object.fromEntries(Object.entries(key as Rec).map(([name, ref]) => [name, doc[(ref as string).slice(1)]]))
785
+ const hash = JSON.stringify(id)
786
+ const group = groups.get(hash) ?? { _id: id }
787
+ for (const [name, spec] of Object.entries(accumulators as Rec)) {
788
+ group[name] = (group[name] ?? 0) + (doc[(spec.$sum as string).slice(1)] ?? 0)
789
+ }
790
+ groups.set(hash, group)
791
+ }
792
+ docs = [...groups.values()]
793
+ } else {
794
+ throw new Error(`unsupported stage ${JSON.stringify(stage)}`)
795
+ }
796
+ }
797
+ return docs
798
+ },
799
+ }),
800
+ }
801
+
802
+ return store
803
+ }
804
+
805
+ // -----------------------------------------------------------------------------------------------
806
+ // Context
807
+ // -----------------------------------------------------------------------------------------------
808
+
809
+ export interface FakeContextOptions {
810
+ catalogue?: CatalogueOptions
811
+ /** Declare the catalogue yourself instead. */
812
+ declare?: (cfg: Config) => void
813
+ /** This process's `cfg.service` (default `app`). */
814
+ service?: string
815
+ /** The public host of this process's service (default `api.example.com`). */
816
+ host?: string
817
+ /** The base path of this process's service (default none). */
818
+ base?: string
819
+ /** Further backend services by alias, each on its own host (and base). */
820
+ services?: Record<string, { host: string, base?: string }>
821
+ /** The configured webhook override secret. */
822
+ webhookSecret?: string
823
+ portal?: PortalBrandingDef
824
+ pricing?: PricingDef
825
+ stripe?: Partial<FakeStripeState>
826
+ /** Rows each store (by resource alias) holds before the context initializes — a shared database. */
827
+ seed?: Record<string, Rec[]>
828
+ /** Declare a consumer-rights policy (with trader and mail options). */
829
+ consumerRights?: ConsumerRightsDef
830
+ /** The consumer-rights usage meter. */
831
+ meter?: UsageMeter
832
+ /** Register a console mailer under `MAILER_SERVICE` (default true). */
833
+ mailer?: boolean
834
+ /** Register the gateway before the application's consumer-rights call (default: after). */
835
+ gatewayFirst?: boolean
836
+ /** The application's consumer-rights options (default: managed through the fake, with `meter`). */
837
+ rights?: (stripe: Stripe) => ConsumerRightsOptions
838
+ /** The gateway's options (default `{ manage: false }`); its Stripe client is always the fake. */
839
+ gateway?: GatewayServiceOptions
840
+ /** Run on the context after the registrations, before it is configured and initialized. */
841
+ wire?: (ctx: ApiContext) => void
842
+ }
843
+
844
+ export interface Observed {
845
+ topUp: TopUpCompletion[]
846
+ subscription: SubscriptionEvent[]
847
+ refund: RefundEvent[]
848
+ dispute: DisputeEvent[]
849
+ paymentFailed: PaymentFailedEvent[]
850
+ consent: ConsentEvent[]
851
+ withdrawal: WithdrawalEvent[]
852
+ cancellation: CancellationEvent[]
853
+ /** Throw from the next `n` subscription callbacks. */
854
+ failSubscription: number
855
+ failTopUp: number
856
+ failWithdrawal: number
857
+ /** Run inside every top-up / subscription callback, before it records the event. */
858
+ onTopUp?: (event: TopUpCompletion) => Promise<void>
859
+ onSubscription?: (event: SubscriptionEvent) => Promise<void>
860
+ }
861
+
862
+ export interface FakeContext {
863
+ ctx: ApiContext
864
+ stripe: Stripe
865
+ state: FakeStripeState
866
+ stores: Record<string, MemoryStore>
867
+ observed: Observed
868
+ /** Every mail the console mailer took. */
869
+ mails: MailMessage[]
870
+ /** The console mailer — replace its `send` to simulate a transport failure. */
871
+ mailer: ReturnType<typeof makeConsoleMailerService>
872
+ }
873
+
874
+ /**
875
+ * A real server context — real catalogue, payment service, observer, gateway (unmanaged unless
876
+ * `gateway` says otherwise), gates and entitlement service — over in-memory resources, with a fake
877
+ * Stripe for the plugin functions and as the gateway's own client.
878
+ */
879
+ export const makeFakeContext = async (opts: FakeContextOptions = {}): Promise<FakeContext> => {
880
+ const own = opts.service ?? SERVICE
881
+ const services: Record<string, unknown> = {
882
+ [own]: { service: own, type: AppType.Backend, host: opts.host ?? HOST, ...(opts.base != null ? { base: opts.base } : {}) },
883
+ }
884
+ for (const [alias, { host, base }] of Object.entries(opts.services ?? {})) {
885
+ services[alias] = { service: alias, type: AppType.Backend, host, ...(base != null ? { base } : {}) }
886
+ }
887
+ const cfg = serverConfig<ServerConfig>(own, { services } as Partial<ServerConfig>) as unknown as Config
888
+ if (opts.declare != null) {
889
+ opts.declare(cfg)
890
+ } else {
891
+ declareTestCatalogue(cfg, opts.catalogue)
892
+ }
893
+ stripeSecrets(cfg, { api: 'sk_test_offline', ...(opts.webhookSecret != null ? { webhook: opts.webhookSecret } : {}) })
894
+ if (opts.portal != null) {
895
+ portalBranding(cfg, opts.portal)
896
+ }
897
+ if (opts.pricing != null) {
898
+ declarePaymentPricing(cfg, opts.pricing)
899
+ }
900
+ if (opts.consumerRights != null) {
901
+ declareConsumerRights(cfg, opts.consumerRights)
902
+ }
903
+
904
+ const ctx = makeServerContext(cfg as unknown as ServerConfig) as unknown as ApiContext
905
+ const stores: Record<string, MemoryStore> = {}
906
+ const resources = [
907
+ [RES_PAYGATE_CUSTOMER, makePaygateCustomerResource()],
908
+ [RES_PAYMENT_SUBSCRIPTION, makeSubscriptionResource()],
909
+ [RES_PAYMENT_FULFILLMENT, makeFulfillmentResource()],
910
+ [RES_PAYMENT_WEBHOOK, makeWebhookResource()],
911
+ [RES_PAYMENT_USAGE, makeUsageResource()],
912
+ [RES_PAYMENT_USAGE_COUNTER, makeUsageCounterResource()],
913
+ [RES_PAYMENT_FINGERPRINT, makeFingerprintResource()],
914
+ [RES_BILLING_PROFILE, makeBillingProfileResource()],
915
+ [RES_PAYMENT_PURCHASE, makePurchaseResource()],
916
+ [RES_CONSUMER_CONSENT, makeConsumerConsentResource()],
917
+ [RES_CONSUMER_DECLARATION, makeConsumerDeclarationResource()],
918
+ [RES_CONSUMER_EVENT, makeConsumerEventResource()],
919
+ ] as const
920
+ for (const [alias, resource] of resources) {
921
+ stores[alias] = memoryResource(resource as unknown as MongoResource<ResourceRecord>)
922
+ stores[alias].rows.push(...structuredClone(opts.seed?.[alias] ?? []))
923
+ ctx.registerResource(resource as never)
924
+ }
925
+ const { stripe, state } = makeFakeStripe(opts.stripe)
926
+ const mailer = makeConsoleMailerService(MAILER_SERVICE)
927
+ if (opts.mailer !== false) {
928
+ ctx.registerService(mailer)
929
+ }
930
+ // The consumer-rights service manages the paygate through the fake; the gateway stays unmanaged.
931
+ const rights = opts.rights?.(stripe)
932
+ ?? { manage: true, stripe: async () => stripe, ...(opts.meter != null ? { usage: opts.meter } : {}) }
933
+ const gatewayOpts: GatewayServiceOptions = { manage: false, stripe: async () => stripe, ...opts.gateway }
934
+ if (opts.gatewayFirst === true) {
935
+ appendPaymentGatewayService(ctx as never, gatewayOpts)
936
+ appendConsumerRights(ctx as never, rights)
937
+ } else {
938
+ appendConsumerRights(ctx as never, rights)
939
+ appendPaymentGatewayService(ctx as never, gatewayOpts)
940
+ }
941
+ opts.wire?.(ctx)
942
+ ctx.configure()
943
+ await ctx.init()
944
+
945
+ const observed: Observed = {
946
+ topUp: [], subscription: [], refund: [], dispute: [], paymentFailed: [], consent: [], withdrawal: [],
947
+ cancellation: [], failSubscription: 0, failTopUp: 0, failWithdrawal: 0,
948
+ }
949
+ const completions = paymentAccessOf(ctx).observer()
950
+ await completions.ready()
951
+ completions.onTopUp(async event => {
952
+ if (observed.failTopUp > 0) {
953
+ observed.failTopUp--
954
+ throw new Error('ledger unavailable')
955
+ }
956
+ await observed.onTopUp?.(event)
957
+ observed.topUp.push(event)
958
+ })
959
+ completions.onSubscription(async event => {
960
+ if (observed.failSubscription > 0) {
961
+ observed.failSubscription--
962
+ throw new Error('observer unavailable')
963
+ }
964
+ await observed.onSubscription?.(event)
965
+ observed.subscription.push(event)
966
+ })
967
+ completions.onRefund(async event => { observed.refund.push(event) })
968
+ completions.onDispute(async event => { observed.dispute.push(event) })
969
+ completions.onPaymentFailed(async event => { observed.paymentFailed.push(event) })
970
+ completions.onConsent(async event => { observed.consent.push(event) })
971
+ completions.onWithdrawal(async event => {
972
+ if (observed.failWithdrawal > 0) {
973
+ observed.failWithdrawal--
974
+ throw new Error('ledger unavailable')
975
+ }
976
+ observed.withdrawal.push(event)
977
+ })
978
+ completions.onCancellation(async event => { observed.cancellation.push(event) })
979
+
980
+ return { ctx, stripe, state, stores, observed, mails: mailer.captured, mailer }
981
+ }