@umohpyro/better-auth-nuvion 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 better-auth-nuvion contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,141 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # better-auth-nuvion
2
+
3
+ Accept payments with [Nuvion](https://nuvion.co) from your [Better Auth](https://better-auth.com) app, and split every payment across your platform, resellers and merchants automatically.
4
+
5
+ - **Multi-level merchants.** Organizations form a hierarchy (platform, reseller, merchant; depth up to 3). Each payment cascades child to parent.
6
+ - **Flexible fees.** Per-merchant flat fee, basis points, or both, with a minimum and a cap. The payer or the merchant can bear the fee.
7
+ - **Exact money math.** Integer minor units only. Splits always sum to the amount charged, and rounding remainders go to the platform.
8
+ - **Safe by construction.** Signed webhooks (HMAC-SHA256, constant-time, replay window), event de-duplication, and an idempotent leg executor that retries without double-paying.
9
+ - **Built on Better Auth.** Uses the `organization` plugin for tenancy and `@better-auth/api-key` for developer keys. Tables are created by Better Auth's schema migration.
10
+ - **Provider-agnostic engine.** The split engine knows nothing about Nuvion; the Nuvion integration is one provider behind a two-method interface.
11
+
12
+ > **Status: 0.1, pre-release, not on npm yet** (until the first release, build it with `npm run build` and install the tarball from `npm pack`). It is verified against a simulated Nuvion API and, on the Nuvion sandbox, for hosted checkout, signed webhooks and counterparty creation; real book transfers end to end are not verified yet. See [Status and limits](#status-and-limits).
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ npm install @umohpyro/better-auth-nuvion better-auth zod
18
+ ```
19
+
20
+ One package, three entry points:
21
+
22
+ | Import | What |
23
+ |---|---|
24
+ | `@umohpyro/better-auth-nuvion` | The Better Auth plugin: schema, endpoints, webhook receiver |
25
+ | `@umohpyro/better-auth-nuvion/client` | The typed client plugin |
26
+ | `@umohpyro/better-auth-nuvion/engine` | The provider-agnostic split engine (fee math, hierarchy rules, ledger, leg executor) for use on its own |
27
+
28
+ ESM and CommonJS are both supported. The package is published under the author's scope while it is unofficial and pre-release.
29
+
30
+ ## Setup
31
+
32
+ ```ts
33
+ import { betterAuth } from "better-auth";
34
+ import { organization } from "better-auth/plugins";
35
+ import { apiKey } from "@better-auth/api-key";
36
+ import { nuvion } from "@umohpyro/better-auth-nuvion";
37
+
38
+ export const auth = betterAuth({
39
+ plugins: [
40
+ organization(),
41
+ apiKey(),
42
+ nuvion({
43
+ apiKey: process.env.NUVION_API_KEY!, // nv_test_... for sandbox
44
+ webhookSecret: process.env.NUVION_WEBHOOK_SECRET!, // nv_wsk_...
45
+ baseUrl: "https://api.nuvion.dev", // default
46
+ webhookToleranceMs: 5 * 60_000, // optional replay window
47
+ }),
48
+ ],
49
+ });
50
+ ```
51
+
52
+ Create the tables with Better Auth's CLI (`npx @better-auth/cli migrate`, or `generate` for Prisma and Drizzle). The plugin adds `parentOrganizationId` to `organization` and six `nuvion*` tables; amounts and timestamps are `bigint` so they do not overflow on Postgres. Then register this webhook URL in Nuvion and subscribe to `inflows.completed`, `outflows.completed`, `outflows.failed` and `outflows.cancelled`:
53
+
54
+ ```
55
+ https://your-app.example.com/api/auth/nuvion/webhook
56
+ ```
57
+
58
+ Keep keys in the environment. Never commit them.
59
+
60
+ ### Typed client
61
+
62
+ ```ts
63
+ import { createAuthClient } from "better-auth/client";
64
+ import { organizationClient } from "better-auth/client/plugins";
65
+ import { nuvionClient } from "@umohpyro/better-auth-nuvion/client";
66
+
67
+ const authClient = createAuthClient({ plugins: [organizationClient(), nuvionClient()] });
68
+
69
+ const { data } = await authClient.nuvion.payments({
70
+ organizationId: "org_merchant",
71
+ amountMinor: 10_000,
72
+ currency: "GBP",
73
+ redirectUrl: "https://shop.example.com/done",
74
+ });
75
+ // data.checkoutUrl, data.chargedMinor, data.legs
76
+ ```
77
+
78
+ Request bodies are typed from the server schema; a wrong type fails `tsc`. Other calls: `authClient.nuvion.organization.parent`, `.organization.bind`, `.feeRule`, `.payments.retry`.
79
+
80
+ ## How it works
81
+
82
+ 1. **Hierarchy.** `POST /nuvion/organization/parent` sets an organization's parent. Cycles and depth above 3 are rejected.
83
+ 2. **Bind to Nuvion.** `POST /nuvion/organization/bind` maps an organization to a Nuvion `entityId` and `accountId`.
84
+ 3. **Fee rules.** `POST /nuvion/fee-rule` is called by an admin of the **parent** organization. The rule is what the parent takes from the child's payments:
85
+
86
+ ```json
87
+ { "organizationId": "org_merchant", "flatMinor": 0, "bps": 300, "minMinor": 50, "capMinor": 5000, "bearer": "merchant" }
88
+ ```
89
+
90
+ 4. **Charge.** `POST /nuvion/payments` quotes the split and creates a hosted checkout:
91
+
92
+ ```json
93
+ { "organizationId": "org_merchant", "amountMinor": 10000, "currency": "GBP", "redirectUrl": "https://shop.example.com/done" }
94
+ ```
95
+
96
+ The response contains `checkoutUrl`, `chargedMinor` and the computed legs. With `bearer: "payer"`, `chargedMinor` is the base plus the fee and the merchant nets the base.
97
+ 5. **Settle.** When Nuvion sends `inflows.completed`, the plugin verifies the signature, checks the amount against the quote, and issues one `book-transfer` per beneficiary from the merchant's account. Nuvion's `outflows.*` events move each leg to `completed` or `failed`.
98
+ 6. **Recover.** `POST /nuvion/payments/retry` re-runs failed or stuck legs.
99
+ 7. **Counterparties are created for you.** A book transfer needs a counterparty and a `book-transfer` payment detail on the sending entity. The plugin creates the pair the first time a transfer needs it (and for refund reversals), using the receiving organization's name and its account's `nuvion_ban`, and saves the ids in `nuvionDestination`. `POST /nuvion/organization/destinations { organizationId }` does it ahead of time for that organization and all its ancestors and reports a problem (for example two organizations bound to the same Nuvion account, which cannot transfer to each other) before a customer pays. Set the contact details Nuvion requires on these counterparties with the `counterparty` option (`email`, `relationship`, `address`); the defaults are placeholders.
100
+ 8. **Refund.** `POST /nuvion/payments/refund` cancels unsent legs and adds a reversal leg for every moved leg (beneficiary back to the paying org), so the merchant account is made whole. It does not pay the customer back; Nuvion documents no refund API for funding-session inflows. Each beneficiary-to-origin pair needs a counterparty, like the forward legs.
101
+
102
+ ### Fee cascade
103
+
104
+ A rule on organization X is what X's parent takes from money flowing through X. For a merchant under a reseller under the platform, with 3% on the merchant and 50% on the reseller, a 10,000 payment gives the merchant 9,700, the reseller 150 and the platform 150. Fees round down, so remainders accumulate at the platform. This is property-tested to sum exactly.
105
+
106
+ ### Failure semantics
107
+
108
+ Nuvion has no atomic multi-recipient settlement, so each leg is its own transfer. The executor is built for that:
109
+
110
+ | Situation | Behavior |
111
+ |---|---|
112
+ | Duplicate or replayed webhook | Ignored by event id and by payment state |
113
+ | Amount differs from the quote | Not split |
114
+ | One leg rejected (for example insufficient funds) | Payment becomes `partial`; retry re-issues only that leg under a new reference |
115
+ | Timeout or 5xx | Same reference reused; a `409` from Nuvion means the transfer already exists |
116
+ | Late event for an older attempt | Ignored |
117
+ | Refund after split | Unsent legs cancelled, reversal legs created for moved legs |
118
+
119
+ ## Development
120
+
121
+ ```bash
122
+ npm install
123
+ npm test # builds, then runs 31 tests; no network or keys needed
124
+ npm run typecheck
125
+ ```
126
+
127
+ `npm run build` compiles each package with `tsc` to `dist/` (ESM plus `.d.ts`), in dependency order. The integration tests run the same scenarios against Better Auth's in-memory adapter, SQLite (`node:sqlite`) and Postgres (PGlite), using migrations generated from the plugin schema, with a simulated Nuvion API.
128
+
129
+ ## Status and limits
130
+
131
+ Verified: migration and queries on SQLite and Postgres (PGlite). Verified on the Nuvion sandbox: a hosted-checkout funding session paid with the sandbox bank, real signed `inflows.completed` webhooks (signature, ISO timestamp, the reference in `unique_reference` and `narration`), and creation of the counterparty and `book-transfer` payment detail between two accounts. Not yet verified: real book transfers and `outflows.*` confirmations end to end, MySQL, Prisma and Drizzle adapters, a networked Postgres server, concurrent webhook delivery against a SQL database (it is tested against the in-memory store), and Nuvion production.
132
+
133
+
134
+
135
+ Not yet implemented: authentication of payment endpoints by API key, a reconciliation job for legs stuck in `sent`, mapping refund events to payments, subscriptions, multi-currency splits, and attribution of Nuvion's own fees to legs. Amounts use JavaScript numbers (safe for fiat). Details, platform constraints and open questions for Nuvion are in [docs/platform-notes.md](docs/platform-notes.md).
136
+
137
+ The package is published under the author's npm scope (`@umohpyro`) while it is unofficial; the name will change if it is adopted.
138
+
139
+ ## License
140
+
141
+ MIT
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/client.ts
21
+ var client_exports = {};
22
+ __export(client_exports, {
23
+ nuvionClient: () => nuvionClient
24
+ });
25
+ module.exports = __toCommonJS(client_exports);
26
+ var nuvionClient = () => ({
27
+ id: "nuvion",
28
+ $InferServerPlugin: {}
29
+ });
30
+ // Annotate the CommonJS export names for ESM import in node:
31
+ 0 && (module.exports = {
32
+ nuvionClient
33
+ });
@@ -0,0 +1,12 @@
1
+ import { nuvion } from './index.cjs';
2
+ import './types-BWF8YNYE.cjs';
3
+ import 'better-auth';
4
+ import 'zod';
5
+
6
+ /** `createAuthClient({ plugins: [nuvionClient()] })` gives typed `client.nuvion.*` calls. */
7
+ declare const nuvionClient: () => {
8
+ id: "nuvion";
9
+ $InferServerPlugin: ReturnType<typeof nuvion>;
10
+ };
11
+
12
+ export { nuvionClient };
@@ -0,0 +1,12 @@
1
+ import { nuvion } from './index.js';
2
+ import './types-BWF8YNYE.js';
3
+ import 'better-auth';
4
+ import 'zod';
5
+
6
+ /** `createAuthClient({ plugins: [nuvionClient()] })` gives typed `client.nuvion.*` calls. */
7
+ declare const nuvionClient: () => {
8
+ id: "nuvion";
9
+ $InferServerPlugin: ReturnType<typeof nuvion>;
10
+ };
11
+
12
+ export { nuvionClient };
package/dist/client.js ADDED
@@ -0,0 +1,8 @@
1
+ // src/client.ts
2
+ var nuvionClient = () => ({
3
+ id: "nuvion",
4
+ $InferServerPlugin: {}
5
+ });
6
+ export {
7
+ nuvionClient
8
+ };
@@ -0,0 +1,343 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/engine/index.ts
21
+ var engine_exports = {};
22
+ __export(engine_exports, {
23
+ MAX_DEPTH: () => MAX_DEPTH,
24
+ MemoryStore: () => MemoryStore,
25
+ ProviderError: () => ProviderError,
26
+ SplitService: () => SplitService,
27
+ assertValidParent: () => assertValidParent,
28
+ chainOf: () => chainOf,
29
+ computeFee: () => computeFee,
30
+ quote: () => quote,
31
+ validateRule: () => validateRule
32
+ });
33
+ module.exports = __toCommonJS(engine_exports);
34
+
35
+ // src/engine/fees.ts
36
+ var isInt = (n) => Number.isSafeInteger(n) && n >= 0;
37
+ function validateRule(r) {
38
+ if (!isInt(r.flatMinor)) throw new RangeError("flatMinor must be a non-negative integer");
39
+ if (!Number.isInteger(r.bps) || r.bps < 0 || r.bps > 1e4) throw new RangeError("bps must be an integer 0..10000");
40
+ for (const k of ["minMinor", "capMinor"]) {
41
+ if (r[k] !== void 0 && !isInt(r[k])) throw new RangeError(`${k} must be a non-negative integer`);
42
+ }
43
+ if (r.minMinor !== void 0 && r.capMinor !== void 0 && r.minMinor > r.capMinor) {
44
+ throw new RangeError("minMinor must be <= capMinor");
45
+ }
46
+ }
47
+ function computeFee(amountMinor, r) {
48
+ if (!isInt(amountMinor)) throw new RangeError("amount must be a non-negative integer");
49
+ if (!r) return 0;
50
+ validateRule(r);
51
+ let fee = r.flatMinor + Number(BigInt(amountMinor) * BigInt(r.bps) / 10000n);
52
+ if (r.minMinor !== void 0) fee = Math.max(fee, r.minMinor);
53
+ if (r.capMinor !== void 0) fee = Math.min(fee, r.capMinor);
54
+ return Math.min(fee, amountMinor);
55
+ }
56
+ function quote(baseMinor, chain) {
57
+ if (!isInt(baseMinor) || baseMinor === 0) throw new RangeError("base must be a positive integer");
58
+ if (chain.length < 1) throw new RangeError("empty chain");
59
+ const leafRule = chain.length > 1 ? chain[0].rule : void 0;
60
+ let charged = baseMinor;
61
+ if (leafRule?.bearer === "payer") charged = baseMinor + computeFee(baseMinor, leafRule);
62
+ const legs = [];
63
+ let inflow = charged;
64
+ for (let i = 0; i < chain.length - 1; i++) {
65
+ const node = chain[i];
66
+ let fee;
67
+ if (i === 0 && leafRule?.bearer === "payer") fee = charged - baseMinor;
68
+ else fee = computeFee(inflow, node.rule);
69
+ legs.push({ organizationId: node.organizationId, amountMinor: inflow - fee });
70
+ inflow = fee;
71
+ }
72
+ legs.push({ organizationId: chain[chain.length - 1].organizationId, amountMinor: inflow });
73
+ const sum = legs.reduce((s, l) => s + l.amountMinor, 0);
74
+ if (sum !== charged) throw new Error(`split invariant broken: ${sum} !== ${charged}`);
75
+ return { baseMinor, chargedMinor: charged, legs };
76
+ }
77
+
78
+ // src/engine/hierarchy.ts
79
+ var MAX_DEPTH = 3;
80
+ async function chainOf(organizationId, parentOf) {
81
+ const chain = [];
82
+ const seen = /* @__PURE__ */ new Set();
83
+ let cur = organizationId;
84
+ while (cur) {
85
+ if (seen.has(cur)) throw new Error(`cycle detected at ${cur}`);
86
+ seen.add(cur);
87
+ chain.push(cur);
88
+ if (chain.length > MAX_DEPTH) throw new Error(`hierarchy deeper than ${MAX_DEPTH}`);
89
+ cur = await parentOf(cur);
90
+ }
91
+ return chain;
92
+ }
93
+ async function assertValidParent(orgId, parentId, parentOf, childrenOf) {
94
+ if (parentId === null) return;
95
+ if (parentId === orgId) throw new Error("an organization cannot be its own parent");
96
+ const up = await chainOf(parentId, parentOf);
97
+ if (up.includes(orgId)) throw new Error("cycle: parent is a descendant of the organization");
98
+ const below = await subtreeHeight(orgId, childrenOf);
99
+ if (up.length + below > MAX_DEPTH) throw new Error(`hierarchy would exceed depth ${MAX_DEPTH}`);
100
+ }
101
+ async function subtreeHeight(id, childrenOf, guard = 0) {
102
+ if (guard > MAX_DEPTH + 1) return MAX_DEPTH + 1;
103
+ const kids = await childrenOf(id);
104
+ let h = 0;
105
+ for (const k of kids) h = Math.max(h, await subtreeHeight(k, childrenOf, guard + 1));
106
+ return 1 + h;
107
+ }
108
+
109
+ // src/engine/types.ts
110
+ var ProviderError = class extends Error {
111
+ kind;
112
+ constructor(kind, message) {
113
+ super(message);
114
+ this.kind = kind;
115
+ }
116
+ };
117
+
118
+ // src/engine/memory-store.ts
119
+ var MemoryStore = class {
120
+ rules = /* @__PURE__ */ new Map();
121
+ parents = /* @__PURE__ */ new Map();
122
+ payments = /* @__PURE__ */ new Map();
123
+ legs = /* @__PURE__ */ new Map();
124
+ events = /* @__PURE__ */ new Set();
125
+ async getRule(id) {
126
+ return this.rules.get(id);
127
+ }
128
+ async parentOf(id) {
129
+ return this.parents.get(id) ?? null;
130
+ }
131
+ async insertPayment(p) {
132
+ if ([...this.payments.values()].some((x) => x.reference === p.reference)) throw new Error("duplicate reference");
133
+ this.payments.set(p.id, { ...p });
134
+ }
135
+ async getPayment(id) {
136
+ const p = this.payments.get(id);
137
+ return p && { ...p };
138
+ }
139
+ async findPaymentByReference(ref) {
140
+ const p = [...this.payments.values()].find((x) => x.reference === ref);
141
+ return p && { ...p };
142
+ }
143
+ async transitionPayment(id, from, to) {
144
+ const p = this.payments.get(id);
145
+ if (!p || !from.includes(p.status)) return false;
146
+ p.status = to;
147
+ return true;
148
+ }
149
+ async claimEvent(id) {
150
+ if (this.events.has(id)) return false;
151
+ this.events.add(id);
152
+ return true;
153
+ }
154
+ async insertLegs(legs) {
155
+ for (const l of legs) this.legs.set(l.id, { ...l });
156
+ }
157
+ async getLeg(id) {
158
+ const l = this.legs.get(id);
159
+ return l && { ...l };
160
+ }
161
+ async legsOf(paymentId) {
162
+ return [...this.legs.values()].filter((l) => l.paymentId === paymentId).map((l) => ({ ...l }));
163
+ }
164
+ async updateLeg(id, patch) {
165
+ const l = this.legs.get(id);
166
+ if (l) Object.assign(l, patch);
167
+ }
168
+ };
169
+
170
+ // src/engine/service.ts
171
+ var uid = () => crypto.randomUUID();
172
+ var SplitService = class {
173
+ store;
174
+ provider;
175
+ constructor(store, provider) {
176
+ this.store = store;
177
+ this.provider = provider;
178
+ }
179
+ /** Quote + persist a payment and open a hosted checkout for the (possibly grossed-up) charged amount. */
180
+ async createPayment(a) {
181
+ const q = await this.quoteFor(a.organizationId, a.baseMinor);
182
+ const id = uid();
183
+ const reference = `pay_${id}`;
184
+ const payment = {
185
+ id,
186
+ organizationId: a.organizationId,
187
+ reference,
188
+ baseMinor: a.baseMinor,
189
+ chargedMinor: q.chargedMinor,
190
+ currency: a.currency,
191
+ status: "pending",
192
+ createdAt: Date.now()
193
+ };
194
+ await this.store.insertPayment(payment);
195
+ const s = await this.provider.createCheckout({
196
+ organizationId: a.organizationId,
197
+ amountMinor: q.chargedMinor,
198
+ currency: a.currency,
199
+ reference,
200
+ narration: reference,
201
+ redirectUrl: a.redirectUrl
202
+ });
203
+ payment.providerSessionId = s.sessionId;
204
+ return { payment, checkoutUrl: s.checkoutUrl, quote: q };
205
+ }
206
+ async quoteFor(organizationId, baseMinor) {
207
+ const ids = await chainOf(organizationId, (o) => this.store.parentOf(o));
208
+ const chain = await Promise.all(ids.map(async (id) => ({ organizationId: id, rule: await this.store.getRule(id) })));
209
+ return quote(baseMinor, chain);
210
+ }
211
+ /**
212
+ * inflows.completed. Idempotent on eventId AND on payment status (a redelivery with a new event id is still a no-op).
213
+ * Funds landed in the leaf's account; legs move each beneficiary's share out of it.
214
+ */
215
+ async onInflowCompleted(e) {
216
+ if (!await this.store.claimEvent(e.eventId)) return { status: "duplicate-event" };
217
+ const p = await this.store.findPaymentByReference(e.reference);
218
+ if (!p) return { status: "unknown-payment" };
219
+ if (e.amountMinor !== p.chargedMinor || e.currency !== p.currency) {
220
+ return { status: "amount-mismatch", paymentId: p.id };
221
+ }
222
+ if (!await this.store.transitionPayment(p.id, ["pending"], "received")) {
223
+ return { status: "already-processed", paymentId: p.id };
224
+ }
225
+ const q = await this.quoteFor(p.organizationId, p.baseMinor);
226
+ if (q.chargedMinor !== p.chargedMinor) throw new Error("fee rules changed between checkout and settlement; manual review");
227
+ const legs = q.legs.filter((l, i) => i > 0 && l.amountMinor > 0).map((l) => ({
228
+ id: uid(),
229
+ paymentId: p.id,
230
+ kind: "split",
231
+ fromOrganizationId: p.organizationId,
232
+ toOrganizationId: l.organizationId,
233
+ amountMinor: l.amountMinor,
234
+ state: "pending",
235
+ attempt: 0
236
+ }));
237
+ await this.store.insertLegs(legs);
238
+ const r = await this.executeLegs(p.id);
239
+ return { status: "processed", paymentId: p.id, ...r };
240
+ }
241
+ /** Run every runnable leg once. Retry = call again. Sent/completed legs are never re-issued. */
242
+ async executeLegs(paymentId) {
243
+ const p = await this.store.getPayment(paymentId);
244
+ if (!p) throw new Error("payment not found");
245
+ await this.store.transitionPayment(paymentId, ["received", "partial"], "splitting");
246
+ for (const leg of await this.store.legsOf(paymentId)) {
247
+ if (leg.state !== "pending" && leg.state !== "failed") continue;
248
+ const attempt = leg.state === "failed" ? leg.attempt + 1 : leg.attempt;
249
+ try {
250
+ const r = await this.provider.transfer({
251
+ fromOrganizationId: leg.fromOrganizationId,
252
+ toOrganizationId: leg.toOrganizationId,
253
+ amountMinor: leg.amountMinor,
254
+ currency: p.currency,
255
+ reference: `${leg.id}-a${attempt}`,
256
+ narration: `${leg.kind} ${p.reference}`
257
+ });
258
+ await this.store.updateLeg(leg.id, { state: "sent", attempt, providerRef: r.providerRef, error: null });
259
+ } catch (err) {
260
+ if (!(err instanceof ProviderError)) throw err;
261
+ if (err.kind === "rejected") await this.store.updateLeg(leg.id, { state: "failed", attempt, error: err.message });
262
+ else if (err.kind === "duplicate") await this.store.updateLeg(leg.id, { state: "sent", attempt, error: "duplicate-reference" });
263
+ else await this.store.updateLeg(leg.id, { state: "pending", attempt, error: err.message });
264
+ }
265
+ }
266
+ return this.refreshStatus(paymentId);
267
+ }
268
+ /** outflows.completed / outflows.failed for a leg, matched by our reference `${legId}-a${attempt}`. */
269
+ async onTransferEvent(e) {
270
+ if (!await this.store.claimEvent(e.eventId)) return { status: "duplicate-event" };
271
+ const m = /^(.+)-a(\d+)$/.exec(e.reference);
272
+ const leg = m && await this.store.getLeg(m[1]);
273
+ if (!m || !leg) return { status: "unknown-leg" };
274
+ if (Number(m[2]) !== leg.attempt) return { status: "stale-attempt" };
275
+ if (leg.state === "completed" || leg.state === "cancelled") return { status: "already-processed" };
276
+ await this.store.updateLeg(leg.id, e.ok ? { state: "completed", error: null } : { state: "failed", error: "provider reported failure" });
277
+ await this.refreshStatus(leg.paymentId);
278
+ return { status: "processed" };
279
+ }
280
+ /**
281
+ * Refund after split (outflows.refunded). Money already left the leaf account, so the payer refund is only
282
+ * fundable if beneficiaries give their shares back: cancel unsent legs, add one reversal leg per moved leg.
283
+ */
284
+ async onRefund(paymentId) {
285
+ const p = await this.store.getPayment(paymentId);
286
+ if (!p) throw new Error("payment not found");
287
+ if (!await this.store.transitionPayment(paymentId, ["pending", "received", "splitting", "partial", "settled"], "refund_partial")) {
288
+ return { status: "already-refunded" };
289
+ }
290
+ const reversals = [];
291
+ for (const leg of await this.store.legsOf(paymentId)) {
292
+ if (leg.kind !== "split") continue;
293
+ if (leg.state === "pending" || leg.state === "failed") await this.store.updateLeg(leg.id, { state: "cancelled" });
294
+ else
295
+ reversals.push({
296
+ id: uid(),
297
+ paymentId,
298
+ kind: "reversal",
299
+ fromOrganizationId: leg.toOrganizationId,
300
+ toOrganizationId: leg.fromOrganizationId,
301
+ amountMinor: leg.amountMinor,
302
+ state: "pending",
303
+ attempt: 0
304
+ });
305
+ }
306
+ await this.store.insertLegs(reversals);
307
+ return { status: "refund-started", reversals: reversals.length, ...await this.executeLegs(paymentId) };
308
+ }
309
+ async refreshStatus(paymentId) {
310
+ const p = await this.store.getPayment(paymentId);
311
+ const live = (await this.store.legsOf(paymentId)).filter((l) => l.state !== "cancelled");
312
+ const done = live.every((l) => l.state === "completed");
313
+ let next = p.status;
314
+ if (p.status === "refund_partial") {
315
+ if (done) {
316
+ await this.store.transitionPayment(paymentId, ["refund_partial"], "refunded");
317
+ next = "refunded";
318
+ }
319
+ } else if (live.length > 0 && done) {
320
+ await this.store.transitionPayment(paymentId, ["splitting", "partial", "received"], "settled");
321
+ next = "settled";
322
+ } else if (live.length === 0) {
323
+ await this.store.transitionPayment(paymentId, ["splitting"], "settled");
324
+ next = "settled";
325
+ } else if (live.some((l) => l.state === "failed")) {
326
+ await this.store.transitionPayment(paymentId, ["splitting"], "partial");
327
+ next = "partial";
328
+ }
329
+ return { paymentStatus: next, legs: await this.store.legsOf(paymentId) };
330
+ }
331
+ };
332
+ // Annotate the CommonJS export names for ESM import in node:
333
+ 0 && (module.exports = {
334
+ MAX_DEPTH,
335
+ MemoryStore,
336
+ ProviderError,
337
+ SplitService,
338
+ assertValidParent,
339
+ chainOf,
340
+ computeFee,
341
+ quote,
342
+ validateRule
343
+ });