@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.
@@ -0,0 +1,151 @@
1
+ import { S as Store, F as FeeRule, P as Payment, a as PaymentLeg, b as PaymentStatus, L as LegKind, c as LegState, d as PaymentProvider, Q as Quote } from './types-BWF8YNYE.cjs';
2
+ export { C as ChainNode, e as FeeBearer, f as Leg, g as ProviderError, h as ProviderErrorKind, T as TransferRequest, i as computeFee, q as quote, v as validateRule } from './types-BWF8YNYE.cjs';
3
+
4
+ declare const MAX_DEPTH = 3;
5
+ type ParentLookup = (organizationId: string) => Promise<string | null | undefined>;
6
+ /** Chain from org up to the root, leaf first. Throws on cycles or depth > MAX_DEPTH. */
7
+ declare function chainOf(organizationId: string, parentOf: ParentLookup): Promise<string[]>;
8
+ /** Validate setting `parentId` as the parent of `orgId`. Also checks the subtree below orgId fits the depth cap. */
9
+ declare function assertValidParent(orgId: string, parentId: string | null, parentOf: ParentLookup, childrenOf: (id: string) => Promise<string[]>): Promise<void>;
10
+
11
+ declare class MemoryStore implements Store {
12
+ rules: Map<string, FeeRule>;
13
+ parents: Map<string, string | null>;
14
+ payments: Map<string, Payment>;
15
+ legs: Map<string, PaymentLeg>;
16
+ events: Set<string>;
17
+ getRule(id: string): Promise<FeeRule | undefined>;
18
+ parentOf(id: string): Promise<string | null>;
19
+ insertPayment(p: Payment): Promise<void>;
20
+ getPayment(id: string): Promise<{
21
+ id: string;
22
+ organizationId: string;
23
+ reference: string;
24
+ providerSessionId?: string;
25
+ baseMinor: number;
26
+ chargedMinor: number;
27
+ currency: string;
28
+ status: PaymentStatus;
29
+ createdAt: number;
30
+ } | undefined>;
31
+ findPaymentByReference(ref: string): Promise<{
32
+ id: string;
33
+ organizationId: string;
34
+ reference: string;
35
+ providerSessionId?: string;
36
+ baseMinor: number;
37
+ chargedMinor: number;
38
+ currency: string;
39
+ status: PaymentStatus;
40
+ createdAt: number;
41
+ } | undefined>;
42
+ transitionPayment(id: string, from: PaymentStatus[], to: PaymentStatus): Promise<boolean>;
43
+ claimEvent(id: string): Promise<boolean>;
44
+ insertLegs(legs: PaymentLeg[]): Promise<void>;
45
+ getLeg(id: string): Promise<{
46
+ id: string;
47
+ paymentId: string;
48
+ kind: LegKind;
49
+ fromOrganizationId: string;
50
+ toOrganizationId: string;
51
+ amountMinor: number;
52
+ state: LegState;
53
+ attempt: number;
54
+ providerRef?: string;
55
+ error?: string | null;
56
+ } | undefined>;
57
+ legsOf(paymentId: string): Promise<{
58
+ id: string;
59
+ paymentId: string;
60
+ kind: LegKind;
61
+ fromOrganizationId: string;
62
+ toOrganizationId: string;
63
+ amountMinor: number;
64
+ state: LegState;
65
+ attempt: number;
66
+ providerRef?: string;
67
+ error?: string | null;
68
+ }[]>;
69
+ updateLeg(id: string, patch: Partial<PaymentLeg>): Promise<void>;
70
+ }
71
+
72
+ declare class SplitService {
73
+ private store;
74
+ private provider;
75
+ constructor(store: Store, provider: PaymentProvider);
76
+ /** Quote + persist a payment and open a hosted checkout for the (possibly grossed-up) charged amount. */
77
+ createPayment(a: {
78
+ organizationId: string;
79
+ baseMinor: number;
80
+ currency: string;
81
+ redirectUrl: string;
82
+ }): Promise<{
83
+ payment: Payment;
84
+ checkoutUrl: string;
85
+ quote: Quote;
86
+ }>;
87
+ quoteFor(organizationId: string, baseMinor: number): Promise<Quote>;
88
+ /**
89
+ * inflows.completed. Idempotent on eventId AND on payment status (a redelivery with a new event id is still a no-op).
90
+ * Funds landed in the leaf's account; legs move each beneficiary's share out of it.
91
+ */
92
+ onInflowCompleted(e: {
93
+ eventId: string;
94
+ reference: string;
95
+ amountMinor: number;
96
+ currency: string;
97
+ }): Promise<{
98
+ status: "duplicate-event";
99
+ paymentId?: undefined;
100
+ } | {
101
+ status: "unknown-payment";
102
+ paymentId?: undefined;
103
+ } | {
104
+ status: "amount-mismatch";
105
+ paymentId: string;
106
+ } | {
107
+ status: "already-processed";
108
+ paymentId: string;
109
+ } | {
110
+ paymentStatus: PaymentStatus;
111
+ legs: PaymentLeg[];
112
+ status: "processed";
113
+ paymentId: string;
114
+ }>;
115
+ /** Run every runnable leg once. Retry = call again. Sent/completed legs are never re-issued. */
116
+ executeLegs(paymentId: string): Promise<{
117
+ paymentStatus: PaymentStatus;
118
+ legs: PaymentLeg[];
119
+ }>;
120
+ /** outflows.completed / outflows.failed for a leg, matched by our reference `${legId}-a${attempt}`. */
121
+ onTransferEvent(e: {
122
+ eventId: string;
123
+ reference: string;
124
+ ok: boolean;
125
+ }): Promise<{
126
+ status: "duplicate-event";
127
+ } | {
128
+ status: "unknown-leg";
129
+ } | {
130
+ status: "stale-attempt";
131
+ } | {
132
+ status: "already-processed";
133
+ } | {
134
+ status: "processed";
135
+ }>;
136
+ /**
137
+ * Refund after split (outflows.refunded). Money already left the leaf account, so the payer refund is only
138
+ * fundable if beneficiaries give their shares back: cancel unsent legs, add one reversal leg per moved leg.
139
+ */
140
+ onRefund(paymentId: string): Promise<{
141
+ status: "already-refunded";
142
+ } | {
143
+ paymentStatus: PaymentStatus;
144
+ legs: PaymentLeg[];
145
+ status: "refund-started";
146
+ reversals: number;
147
+ }>;
148
+ private refreshStatus;
149
+ }
150
+
151
+ export { FeeRule, LegKind, LegState, MAX_DEPTH, MemoryStore, type ParentLookup, Payment, PaymentLeg, PaymentProvider, PaymentStatus, Quote, SplitService, Store, assertValidParent, chainOf };
@@ -0,0 +1,151 @@
1
+ import { S as Store, F as FeeRule, P as Payment, a as PaymentLeg, b as PaymentStatus, L as LegKind, c as LegState, d as PaymentProvider, Q as Quote } from './types-BWF8YNYE.js';
2
+ export { C as ChainNode, e as FeeBearer, f as Leg, g as ProviderError, h as ProviderErrorKind, T as TransferRequest, i as computeFee, q as quote, v as validateRule } from './types-BWF8YNYE.js';
3
+
4
+ declare const MAX_DEPTH = 3;
5
+ type ParentLookup = (organizationId: string) => Promise<string | null | undefined>;
6
+ /** Chain from org up to the root, leaf first. Throws on cycles or depth > MAX_DEPTH. */
7
+ declare function chainOf(organizationId: string, parentOf: ParentLookup): Promise<string[]>;
8
+ /** Validate setting `parentId` as the parent of `orgId`. Also checks the subtree below orgId fits the depth cap. */
9
+ declare function assertValidParent(orgId: string, parentId: string | null, parentOf: ParentLookup, childrenOf: (id: string) => Promise<string[]>): Promise<void>;
10
+
11
+ declare class MemoryStore implements Store {
12
+ rules: Map<string, FeeRule>;
13
+ parents: Map<string, string | null>;
14
+ payments: Map<string, Payment>;
15
+ legs: Map<string, PaymentLeg>;
16
+ events: Set<string>;
17
+ getRule(id: string): Promise<FeeRule | undefined>;
18
+ parentOf(id: string): Promise<string | null>;
19
+ insertPayment(p: Payment): Promise<void>;
20
+ getPayment(id: string): Promise<{
21
+ id: string;
22
+ organizationId: string;
23
+ reference: string;
24
+ providerSessionId?: string;
25
+ baseMinor: number;
26
+ chargedMinor: number;
27
+ currency: string;
28
+ status: PaymentStatus;
29
+ createdAt: number;
30
+ } | undefined>;
31
+ findPaymentByReference(ref: string): Promise<{
32
+ id: string;
33
+ organizationId: string;
34
+ reference: string;
35
+ providerSessionId?: string;
36
+ baseMinor: number;
37
+ chargedMinor: number;
38
+ currency: string;
39
+ status: PaymentStatus;
40
+ createdAt: number;
41
+ } | undefined>;
42
+ transitionPayment(id: string, from: PaymentStatus[], to: PaymentStatus): Promise<boolean>;
43
+ claimEvent(id: string): Promise<boolean>;
44
+ insertLegs(legs: PaymentLeg[]): Promise<void>;
45
+ getLeg(id: string): Promise<{
46
+ id: string;
47
+ paymentId: string;
48
+ kind: LegKind;
49
+ fromOrganizationId: string;
50
+ toOrganizationId: string;
51
+ amountMinor: number;
52
+ state: LegState;
53
+ attempt: number;
54
+ providerRef?: string;
55
+ error?: string | null;
56
+ } | undefined>;
57
+ legsOf(paymentId: string): Promise<{
58
+ id: string;
59
+ paymentId: string;
60
+ kind: LegKind;
61
+ fromOrganizationId: string;
62
+ toOrganizationId: string;
63
+ amountMinor: number;
64
+ state: LegState;
65
+ attempt: number;
66
+ providerRef?: string;
67
+ error?: string | null;
68
+ }[]>;
69
+ updateLeg(id: string, patch: Partial<PaymentLeg>): Promise<void>;
70
+ }
71
+
72
+ declare class SplitService {
73
+ private store;
74
+ private provider;
75
+ constructor(store: Store, provider: PaymentProvider);
76
+ /** Quote + persist a payment and open a hosted checkout for the (possibly grossed-up) charged amount. */
77
+ createPayment(a: {
78
+ organizationId: string;
79
+ baseMinor: number;
80
+ currency: string;
81
+ redirectUrl: string;
82
+ }): Promise<{
83
+ payment: Payment;
84
+ checkoutUrl: string;
85
+ quote: Quote;
86
+ }>;
87
+ quoteFor(organizationId: string, baseMinor: number): Promise<Quote>;
88
+ /**
89
+ * inflows.completed. Idempotent on eventId AND on payment status (a redelivery with a new event id is still a no-op).
90
+ * Funds landed in the leaf's account; legs move each beneficiary's share out of it.
91
+ */
92
+ onInflowCompleted(e: {
93
+ eventId: string;
94
+ reference: string;
95
+ amountMinor: number;
96
+ currency: string;
97
+ }): Promise<{
98
+ status: "duplicate-event";
99
+ paymentId?: undefined;
100
+ } | {
101
+ status: "unknown-payment";
102
+ paymentId?: undefined;
103
+ } | {
104
+ status: "amount-mismatch";
105
+ paymentId: string;
106
+ } | {
107
+ status: "already-processed";
108
+ paymentId: string;
109
+ } | {
110
+ paymentStatus: PaymentStatus;
111
+ legs: PaymentLeg[];
112
+ status: "processed";
113
+ paymentId: string;
114
+ }>;
115
+ /** Run every runnable leg once. Retry = call again. Sent/completed legs are never re-issued. */
116
+ executeLegs(paymentId: string): Promise<{
117
+ paymentStatus: PaymentStatus;
118
+ legs: PaymentLeg[];
119
+ }>;
120
+ /** outflows.completed / outflows.failed for a leg, matched by our reference `${legId}-a${attempt}`. */
121
+ onTransferEvent(e: {
122
+ eventId: string;
123
+ reference: string;
124
+ ok: boolean;
125
+ }): Promise<{
126
+ status: "duplicate-event";
127
+ } | {
128
+ status: "unknown-leg";
129
+ } | {
130
+ status: "stale-attempt";
131
+ } | {
132
+ status: "already-processed";
133
+ } | {
134
+ status: "processed";
135
+ }>;
136
+ /**
137
+ * Refund after split (outflows.refunded). Money already left the leaf account, so the payer refund is only
138
+ * fundable if beneficiaries give their shares back: cancel unsent legs, add one reversal leg per moved leg.
139
+ */
140
+ onRefund(paymentId: string): Promise<{
141
+ status: "already-refunded";
142
+ } | {
143
+ paymentStatus: PaymentStatus;
144
+ legs: PaymentLeg[];
145
+ status: "refund-started";
146
+ reversals: number;
147
+ }>;
148
+ private refreshStatus;
149
+ }
150
+
151
+ export { FeeRule, LegKind, LegState, MAX_DEPTH, MemoryStore, type ParentLookup, Payment, PaymentLeg, PaymentProvider, PaymentStatus, Quote, SplitService, Store, assertValidParent, chainOf };
package/dist/engine.js ADDED
@@ -0,0 +1,308 @@
1
+ // src/engine/fees.ts
2
+ var isInt = (n) => Number.isSafeInteger(n) && n >= 0;
3
+ function validateRule(r) {
4
+ if (!isInt(r.flatMinor)) throw new RangeError("flatMinor must be a non-negative integer");
5
+ if (!Number.isInteger(r.bps) || r.bps < 0 || r.bps > 1e4) throw new RangeError("bps must be an integer 0..10000");
6
+ for (const k of ["minMinor", "capMinor"]) {
7
+ if (r[k] !== void 0 && !isInt(r[k])) throw new RangeError(`${k} must be a non-negative integer`);
8
+ }
9
+ if (r.minMinor !== void 0 && r.capMinor !== void 0 && r.minMinor > r.capMinor) {
10
+ throw new RangeError("minMinor must be <= capMinor");
11
+ }
12
+ }
13
+ function computeFee(amountMinor, r) {
14
+ if (!isInt(amountMinor)) throw new RangeError("amount must be a non-negative integer");
15
+ if (!r) return 0;
16
+ validateRule(r);
17
+ let fee = r.flatMinor + Number(BigInt(amountMinor) * BigInt(r.bps) / 10000n);
18
+ if (r.minMinor !== void 0) fee = Math.max(fee, r.minMinor);
19
+ if (r.capMinor !== void 0) fee = Math.min(fee, r.capMinor);
20
+ return Math.min(fee, amountMinor);
21
+ }
22
+ function quote(baseMinor, chain) {
23
+ if (!isInt(baseMinor) || baseMinor === 0) throw new RangeError("base must be a positive integer");
24
+ if (chain.length < 1) throw new RangeError("empty chain");
25
+ const leafRule = chain.length > 1 ? chain[0].rule : void 0;
26
+ let charged = baseMinor;
27
+ if (leafRule?.bearer === "payer") charged = baseMinor + computeFee(baseMinor, leafRule);
28
+ const legs = [];
29
+ let inflow = charged;
30
+ for (let i = 0; i < chain.length - 1; i++) {
31
+ const node = chain[i];
32
+ let fee;
33
+ if (i === 0 && leafRule?.bearer === "payer") fee = charged - baseMinor;
34
+ else fee = computeFee(inflow, node.rule);
35
+ legs.push({ organizationId: node.organizationId, amountMinor: inflow - fee });
36
+ inflow = fee;
37
+ }
38
+ legs.push({ organizationId: chain[chain.length - 1].organizationId, amountMinor: inflow });
39
+ const sum = legs.reduce((s, l) => s + l.amountMinor, 0);
40
+ if (sum !== charged) throw new Error(`split invariant broken: ${sum} !== ${charged}`);
41
+ return { baseMinor, chargedMinor: charged, legs };
42
+ }
43
+
44
+ // src/engine/hierarchy.ts
45
+ var MAX_DEPTH = 3;
46
+ async function chainOf(organizationId, parentOf) {
47
+ const chain = [];
48
+ const seen = /* @__PURE__ */ new Set();
49
+ let cur = organizationId;
50
+ while (cur) {
51
+ if (seen.has(cur)) throw new Error(`cycle detected at ${cur}`);
52
+ seen.add(cur);
53
+ chain.push(cur);
54
+ if (chain.length > MAX_DEPTH) throw new Error(`hierarchy deeper than ${MAX_DEPTH}`);
55
+ cur = await parentOf(cur);
56
+ }
57
+ return chain;
58
+ }
59
+ async function assertValidParent(orgId, parentId, parentOf, childrenOf) {
60
+ if (parentId === null) return;
61
+ if (parentId === orgId) throw new Error("an organization cannot be its own parent");
62
+ const up = await chainOf(parentId, parentOf);
63
+ if (up.includes(orgId)) throw new Error("cycle: parent is a descendant of the organization");
64
+ const below = await subtreeHeight(orgId, childrenOf);
65
+ if (up.length + below > MAX_DEPTH) throw new Error(`hierarchy would exceed depth ${MAX_DEPTH}`);
66
+ }
67
+ async function subtreeHeight(id, childrenOf, guard = 0) {
68
+ if (guard > MAX_DEPTH + 1) return MAX_DEPTH + 1;
69
+ const kids = await childrenOf(id);
70
+ let h = 0;
71
+ for (const k of kids) h = Math.max(h, await subtreeHeight(k, childrenOf, guard + 1));
72
+ return 1 + h;
73
+ }
74
+
75
+ // src/engine/types.ts
76
+ var ProviderError = class extends Error {
77
+ kind;
78
+ constructor(kind, message) {
79
+ super(message);
80
+ this.kind = kind;
81
+ }
82
+ };
83
+
84
+ // src/engine/memory-store.ts
85
+ var MemoryStore = class {
86
+ rules = /* @__PURE__ */ new Map();
87
+ parents = /* @__PURE__ */ new Map();
88
+ payments = /* @__PURE__ */ new Map();
89
+ legs = /* @__PURE__ */ new Map();
90
+ events = /* @__PURE__ */ new Set();
91
+ async getRule(id) {
92
+ return this.rules.get(id);
93
+ }
94
+ async parentOf(id) {
95
+ return this.parents.get(id) ?? null;
96
+ }
97
+ async insertPayment(p) {
98
+ if ([...this.payments.values()].some((x) => x.reference === p.reference)) throw new Error("duplicate reference");
99
+ this.payments.set(p.id, { ...p });
100
+ }
101
+ async getPayment(id) {
102
+ const p = this.payments.get(id);
103
+ return p && { ...p };
104
+ }
105
+ async findPaymentByReference(ref) {
106
+ const p = [...this.payments.values()].find((x) => x.reference === ref);
107
+ return p && { ...p };
108
+ }
109
+ async transitionPayment(id, from, to) {
110
+ const p = this.payments.get(id);
111
+ if (!p || !from.includes(p.status)) return false;
112
+ p.status = to;
113
+ return true;
114
+ }
115
+ async claimEvent(id) {
116
+ if (this.events.has(id)) return false;
117
+ this.events.add(id);
118
+ return true;
119
+ }
120
+ async insertLegs(legs) {
121
+ for (const l of legs) this.legs.set(l.id, { ...l });
122
+ }
123
+ async getLeg(id) {
124
+ const l = this.legs.get(id);
125
+ return l && { ...l };
126
+ }
127
+ async legsOf(paymentId) {
128
+ return [...this.legs.values()].filter((l) => l.paymentId === paymentId).map((l) => ({ ...l }));
129
+ }
130
+ async updateLeg(id, patch) {
131
+ const l = this.legs.get(id);
132
+ if (l) Object.assign(l, patch);
133
+ }
134
+ };
135
+
136
+ // src/engine/service.ts
137
+ var uid = () => crypto.randomUUID();
138
+ var SplitService = class {
139
+ store;
140
+ provider;
141
+ constructor(store, provider) {
142
+ this.store = store;
143
+ this.provider = provider;
144
+ }
145
+ /** Quote + persist a payment and open a hosted checkout for the (possibly grossed-up) charged amount. */
146
+ async createPayment(a) {
147
+ const q = await this.quoteFor(a.organizationId, a.baseMinor);
148
+ const id = uid();
149
+ const reference = `pay_${id}`;
150
+ const payment = {
151
+ id,
152
+ organizationId: a.organizationId,
153
+ reference,
154
+ baseMinor: a.baseMinor,
155
+ chargedMinor: q.chargedMinor,
156
+ currency: a.currency,
157
+ status: "pending",
158
+ createdAt: Date.now()
159
+ };
160
+ await this.store.insertPayment(payment);
161
+ const s = await this.provider.createCheckout({
162
+ organizationId: a.organizationId,
163
+ amountMinor: q.chargedMinor,
164
+ currency: a.currency,
165
+ reference,
166
+ narration: reference,
167
+ redirectUrl: a.redirectUrl
168
+ });
169
+ payment.providerSessionId = s.sessionId;
170
+ return { payment, checkoutUrl: s.checkoutUrl, quote: q };
171
+ }
172
+ async quoteFor(organizationId, baseMinor) {
173
+ const ids = await chainOf(organizationId, (o) => this.store.parentOf(o));
174
+ const chain = await Promise.all(ids.map(async (id) => ({ organizationId: id, rule: await this.store.getRule(id) })));
175
+ return quote(baseMinor, chain);
176
+ }
177
+ /**
178
+ * inflows.completed. Idempotent on eventId AND on payment status (a redelivery with a new event id is still a no-op).
179
+ * Funds landed in the leaf's account; legs move each beneficiary's share out of it.
180
+ */
181
+ async onInflowCompleted(e) {
182
+ if (!await this.store.claimEvent(e.eventId)) return { status: "duplicate-event" };
183
+ const p = await this.store.findPaymentByReference(e.reference);
184
+ if (!p) return { status: "unknown-payment" };
185
+ if (e.amountMinor !== p.chargedMinor || e.currency !== p.currency) {
186
+ return { status: "amount-mismatch", paymentId: p.id };
187
+ }
188
+ if (!await this.store.transitionPayment(p.id, ["pending"], "received")) {
189
+ return { status: "already-processed", paymentId: p.id };
190
+ }
191
+ const q = await this.quoteFor(p.organizationId, p.baseMinor);
192
+ if (q.chargedMinor !== p.chargedMinor) throw new Error("fee rules changed between checkout and settlement; manual review");
193
+ const legs = q.legs.filter((l, i) => i > 0 && l.amountMinor > 0).map((l) => ({
194
+ id: uid(),
195
+ paymentId: p.id,
196
+ kind: "split",
197
+ fromOrganizationId: p.organizationId,
198
+ toOrganizationId: l.organizationId,
199
+ amountMinor: l.amountMinor,
200
+ state: "pending",
201
+ attempt: 0
202
+ }));
203
+ await this.store.insertLegs(legs);
204
+ const r = await this.executeLegs(p.id);
205
+ return { status: "processed", paymentId: p.id, ...r };
206
+ }
207
+ /** Run every runnable leg once. Retry = call again. Sent/completed legs are never re-issued. */
208
+ async executeLegs(paymentId) {
209
+ const p = await this.store.getPayment(paymentId);
210
+ if (!p) throw new Error("payment not found");
211
+ await this.store.transitionPayment(paymentId, ["received", "partial"], "splitting");
212
+ for (const leg of await this.store.legsOf(paymentId)) {
213
+ if (leg.state !== "pending" && leg.state !== "failed") continue;
214
+ const attempt = leg.state === "failed" ? leg.attempt + 1 : leg.attempt;
215
+ try {
216
+ const r = await this.provider.transfer({
217
+ fromOrganizationId: leg.fromOrganizationId,
218
+ toOrganizationId: leg.toOrganizationId,
219
+ amountMinor: leg.amountMinor,
220
+ currency: p.currency,
221
+ reference: `${leg.id}-a${attempt}`,
222
+ narration: `${leg.kind} ${p.reference}`
223
+ });
224
+ await this.store.updateLeg(leg.id, { state: "sent", attempt, providerRef: r.providerRef, error: null });
225
+ } catch (err) {
226
+ if (!(err instanceof ProviderError)) throw err;
227
+ if (err.kind === "rejected") await this.store.updateLeg(leg.id, { state: "failed", attempt, error: err.message });
228
+ else if (err.kind === "duplicate") await this.store.updateLeg(leg.id, { state: "sent", attempt, error: "duplicate-reference" });
229
+ else await this.store.updateLeg(leg.id, { state: "pending", attempt, error: err.message });
230
+ }
231
+ }
232
+ return this.refreshStatus(paymentId);
233
+ }
234
+ /** outflows.completed / outflows.failed for a leg, matched by our reference `${legId}-a${attempt}`. */
235
+ async onTransferEvent(e) {
236
+ if (!await this.store.claimEvent(e.eventId)) return { status: "duplicate-event" };
237
+ const m = /^(.+)-a(\d+)$/.exec(e.reference);
238
+ const leg = m && await this.store.getLeg(m[1]);
239
+ if (!m || !leg) return { status: "unknown-leg" };
240
+ if (Number(m[2]) !== leg.attempt) return { status: "stale-attempt" };
241
+ if (leg.state === "completed" || leg.state === "cancelled") return { status: "already-processed" };
242
+ await this.store.updateLeg(leg.id, e.ok ? { state: "completed", error: null } : { state: "failed", error: "provider reported failure" });
243
+ await this.refreshStatus(leg.paymentId);
244
+ return { status: "processed" };
245
+ }
246
+ /**
247
+ * Refund after split (outflows.refunded). Money already left the leaf account, so the payer refund is only
248
+ * fundable if beneficiaries give their shares back: cancel unsent legs, add one reversal leg per moved leg.
249
+ */
250
+ async onRefund(paymentId) {
251
+ const p = await this.store.getPayment(paymentId);
252
+ if (!p) throw new Error("payment not found");
253
+ if (!await this.store.transitionPayment(paymentId, ["pending", "received", "splitting", "partial", "settled"], "refund_partial")) {
254
+ return { status: "already-refunded" };
255
+ }
256
+ const reversals = [];
257
+ for (const leg of await this.store.legsOf(paymentId)) {
258
+ if (leg.kind !== "split") continue;
259
+ if (leg.state === "pending" || leg.state === "failed") await this.store.updateLeg(leg.id, { state: "cancelled" });
260
+ else
261
+ reversals.push({
262
+ id: uid(),
263
+ paymentId,
264
+ kind: "reversal",
265
+ fromOrganizationId: leg.toOrganizationId,
266
+ toOrganizationId: leg.fromOrganizationId,
267
+ amountMinor: leg.amountMinor,
268
+ state: "pending",
269
+ attempt: 0
270
+ });
271
+ }
272
+ await this.store.insertLegs(reversals);
273
+ return { status: "refund-started", reversals: reversals.length, ...await this.executeLegs(paymentId) };
274
+ }
275
+ async refreshStatus(paymentId) {
276
+ const p = await this.store.getPayment(paymentId);
277
+ const live = (await this.store.legsOf(paymentId)).filter((l) => l.state !== "cancelled");
278
+ const done = live.every((l) => l.state === "completed");
279
+ let next = p.status;
280
+ if (p.status === "refund_partial") {
281
+ if (done) {
282
+ await this.store.transitionPayment(paymentId, ["refund_partial"], "refunded");
283
+ next = "refunded";
284
+ }
285
+ } else if (live.length > 0 && done) {
286
+ await this.store.transitionPayment(paymentId, ["splitting", "partial", "received"], "settled");
287
+ next = "settled";
288
+ } else if (live.length === 0) {
289
+ await this.store.transitionPayment(paymentId, ["splitting"], "settled");
290
+ next = "settled";
291
+ } else if (live.some((l) => l.state === "failed")) {
292
+ await this.store.transitionPayment(paymentId, ["splitting"], "partial");
293
+ next = "partial";
294
+ }
295
+ return { paymentStatus: next, legs: await this.store.legsOf(paymentId) };
296
+ }
297
+ };
298
+ export {
299
+ MAX_DEPTH,
300
+ MemoryStore,
301
+ ProviderError,
302
+ SplitService,
303
+ assertValidParent,
304
+ chainOf,
305
+ computeFee,
306
+ quote,
307
+ validateRule
308
+ };