@bachsproof/bachs 0.0.0-stage → 2.0.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/dist/index.js ADDED
@@ -0,0 +1,475 @@
1
+ import { randomUUID, createHmac } from 'crypto';
2
+ import { z } from 'zod';
3
+
4
+ // src/fixtures.ts
5
+
6
+ // src/money.ts
7
+ var DECIMAL_AMOUNT = /^(?:0|[1-9]\d*)(?:\.(\d+))?$/;
8
+ function normalize(coefficient, scale) {
9
+ let normalizedCoefficient = coefficient;
10
+ let normalizedScale = scale;
11
+ while (normalizedScale > 0 && normalizedCoefficient % 10n === 0n) {
12
+ normalizedCoefficient /= 10n;
13
+ normalizedScale -= 1;
14
+ }
15
+ return { coefficient: normalizedCoefficient, scale: normalizedScale };
16
+ }
17
+ function parseBachsMoney(amount, currency) {
18
+ if (!/^[A-Z]{3}$/.test(currency)) throw new Error(`Invalid ISO currency ${currency}`);
19
+ const match = DECIMAL_AMOUNT.exec(amount);
20
+ if (!match) throw new Error(`Invalid Bachs decimal amount ${amount}`);
21
+ const fraction = match[1] ?? "";
22
+ const coefficient = BigInt(`${match[0].split(".")[0]}${fraction}`);
23
+ return { coefficient, scale: fraction.length, currency };
24
+ }
25
+ function compareBachsMoney(left, right) {
26
+ if (left.currency !== right.currency) throw new Error("Cannot compare money in different currencies");
27
+ const normalizedLeft = normalize(left.coefficient, left.scale);
28
+ const normalizedRight = normalize(right.coefficient, right.scale);
29
+ const scale = Math.max(normalizedLeft.scale, normalizedRight.scale);
30
+ const leftValue = normalizedLeft.coefficient * 10n ** BigInt(scale - normalizedLeft.scale);
31
+ const rightValue = normalizedRight.coefficient * 10n ** BigInt(scale - normalizedRight.scale);
32
+ return leftValue < rightValue ? -1 : leftValue > rightValue ? 1 : 0;
33
+ }
34
+ function toBachsMinorUnits(value, scale) {
35
+ if (!Number.isInteger(scale) || scale < 0) throw new Error("Money scale must be a non-negative integer");
36
+ if (value.scale > scale && value.coefficient % 10n ** BigInt(value.scale - scale) !== 0n) {
37
+ throw new Error(`Amount ${value.coefficient} has more precision than storage scale ${scale}`);
38
+ }
39
+ return value.coefficient * 10n ** BigInt(scale - value.scale);
40
+ }
41
+ function safeNumberMoney(value) {
42
+ const number = Number(value);
43
+ if (!Number.isSafeInteger(number)) throw new Error("Financial amount exceeds JavaScript safe integer range");
44
+ return number;
45
+ }
46
+ function formatBachsMoney(value, scale) {
47
+ if (scale < 0 || !Number.isInteger(scale)) throw new Error("Money scale must be a non-negative integer");
48
+ const negative = value < 0n;
49
+ const digits = (negative ? -value : value).toString().padStart(scale + 1, "0");
50
+ if (scale === 0) return `${negative ? "-" : ""}${digits}`;
51
+ const split = digits.length - scale;
52
+ return `${negative ? "-" : ""}${digits.slice(0, split)}.${digits.slice(split)}`;
53
+ }
54
+
55
+ // src/fixtures.ts
56
+ var customerSchema = z.object({
57
+ id: z.string().min(1).nullable().optional(),
58
+ customer_id: z.string().min(1).nullable().optional(),
59
+ email: z.string().email().nullable().optional(),
60
+ name: z.string().nullable().optional()
61
+ }).passthrough();
62
+ var checkoutDataSchema = z.object({
63
+ checkout_id: z.string().min(1),
64
+ status: z.string().min(1),
65
+ mode: z.string().min(1),
66
+ payment_status: z.string().nullable(),
67
+ amount: z.string().min(1),
68
+ currency: z.string().length(3).nullable(),
69
+ reference: z.string().min(1).nullable(),
70
+ customer: customerSchema.nullable(),
71
+ charge: z.object({ id: z.string().min(1) }).passthrough().nullable(),
72
+ metadata: z.record(z.unknown()).default({})
73
+ }).passthrough();
74
+ var collectionDataSchema = z.object({
75
+ charge_id: z.string().min(1).nullable(),
76
+ checkout_id: z.string().min(1).nullable(),
77
+ reference: z.string().min(1).nullable(),
78
+ status: z.string().min(1),
79
+ amount: z.string().min(1),
80
+ currency: z.string().length(3),
81
+ customer: customerSchema,
82
+ metadata: z.record(z.unknown()).default({})
83
+ }).passthrough();
84
+ var underpaidDataSchema = z.object({
85
+ charge_id: z.string().min(1),
86
+ reference: z.string().min(1).nullable(),
87
+ checkout_id: z.string().min(1).nullable(),
88
+ amount_paid: z.string().min(1),
89
+ amount_expected: z.string().min(1),
90
+ amount_remaining: z.string().min(1),
91
+ currency: z.string().length(3),
92
+ status: z.literal("UNDERPAID"),
93
+ metadata: z.record(z.unknown()).default({})
94
+ }).passthrough();
95
+ var failedDataSchema = z.object({
96
+ charge_id: z.string().min(1),
97
+ checkout_id: z.string().min(1).nullable(),
98
+ reference: z.string().min(1).nullable(),
99
+ status: z.enum(["FAILED", "EXPIRED"]),
100
+ amount: z.string().min(1),
101
+ currency: z.string().length(3),
102
+ settlement_amount: z.string().min(1).nullable().optional(),
103
+ settlement_currency: z.string().length(3).nullable().optional(),
104
+ processing_fee: z.string().min(1).nullable().optional(),
105
+ processing_fee_currency: z.string().length(3).nullable().optional(),
106
+ fee_bearer: z.string().nullable().optional(),
107
+ product_cart: z.unknown().nullable().optional(),
108
+ customer: customerSchema,
109
+ reason: z.string().nullable().optional(),
110
+ payment_method_details: z.unknown().nullable().optional(),
111
+ metadata: z.record(z.unknown()).default({})
112
+ }).passthrough();
113
+ var genericDataSchema = z.record(z.unknown());
114
+ var eventEnvelope = z.object({
115
+ id: z.string().min(1),
116
+ type: z.string().min(1),
117
+ created_at: z.string().datetime({ offset: true }),
118
+ organization_id: z.string().min(1),
119
+ data: genericDataSchema
120
+ }).passthrough();
121
+ var BachsWebhookEventSchema = z.union([
122
+ eventEnvelope.extend({ type: z.literal("checkout.completed"), data: checkoutDataSchema }),
123
+ eventEnvelope.extend({ type: z.literal("checkout.expired"), data: checkoutDataSchema }),
124
+ eventEnvelope.extend({ type: z.literal("collection.succeeded"), data: collectionDataSchema }),
125
+ eventEnvelope.extend({ type: z.literal("collection.underpaid"), data: underpaidDataSchema }),
126
+ eventEnvelope.extend({ type: z.literal("collection.failed"), data: failedDataSchema }),
127
+ eventEnvelope
128
+ ]);
129
+ function isoAt(baseMs, offsetMs = 0) {
130
+ return new Date(baseMs + offsetMs).toISOString();
131
+ }
132
+ function expectedNoCredit(event) {
133
+ return {
134
+ reference: event.reference,
135
+ eligible: false,
136
+ amountMinor: event.amountMinor,
137
+ currency: event.currency,
138
+ expectedCreditCount: 0
139
+ };
140
+ }
141
+ function checkoutFixture(base, type, options) {
142
+ const charge = options.charge ? { id: base.providerPaymentId } : null;
143
+ return {
144
+ ...base,
145
+ id: `evt_${randomUUID().replaceAll("-", "")}`,
146
+ type,
147
+ created_at: options.createdAt,
148
+ data: {
149
+ checkout_id: base.checkoutId,
150
+ status: options.status,
151
+ mode: "payment",
152
+ payment_status: options.paymentStatus,
153
+ amount: formatBachsMoney(BigInt(base.amountMinor), 2),
154
+ currency: base.currency,
155
+ reference: base.reference,
156
+ customer: { id: base.customerId, email: "synthetic@example.com", name: "Synthetic Customer" },
157
+ charge,
158
+ success_url: "https://example.test/success",
159
+ cancel_url: "https://example.test/cancel",
160
+ subscription: null,
161
+ completed_at: options.eligible ? options.createdAt : null,
162
+ expires_at: options.createdAt,
163
+ metadata: { order_id: base.reference }
164
+ },
165
+ amountMinor: base.amountMinor,
166
+ status: options.eligible ? "SUCCEEDED" : options.status,
167
+ eligible: options.eligible
168
+ };
169
+ }
170
+ function delivery(event, _input, overrides = {}) {
171
+ return {
172
+ event,
173
+ ...overrides
174
+ };
175
+ }
176
+ function createBachsScenario(scenario, input, customerId2) {
177
+ if (["concurrent-duplicate-credit", "sequential-duplicate-webhook", "concurrent-unique-payments"].includes(scenario)) return void 0;
178
+ const reference = input.reference;
179
+ const amountMinor = input.amountMinor ?? 5e6;
180
+ const currency = input.currency ?? "NGN";
181
+ const base = createBachsMockFixture({ reference, amountMinor, currency, customerId: customerId2 });
182
+ const now = Date.now();
183
+ const successful = () => ({
184
+ deliveries: [delivery(base)],
185
+ verification: [{ event: base, expected: expectedBachsState(base) }]
186
+ });
187
+ if (scenario === "cross-event-duplicate-payment") {
188
+ const completed = checkoutFixture(base, "checkout.completed", {
189
+ createdAt: isoAt(now),
190
+ paymentStatus: "paid",
191
+ charge: true,
192
+ eligible: true,
193
+ status: "completed"
194
+ });
195
+ return {
196
+ concurrent: true,
197
+ deliveries: [delivery(completed, input, { participantId: "checkout-completed" }), delivery(base, input, { participantId: "collection-succeeded" })],
198
+ verification: [{ event: base, expected: expectedBachsState(base) }]
199
+ };
200
+ }
201
+ if (scenario === "out-of-order-events") {
202
+ const expired = checkoutFixture(base, "checkout.expired", {
203
+ createdAt: isoAt(now),
204
+ paymentStatus: null,
205
+ charge: false,
206
+ eligible: false,
207
+ status: "expired"
208
+ });
209
+ const newerSuccess = { ...base, created_at: isoAt(now + 1e3) };
210
+ return {
211
+ deliveries: [delivery(newerSuccess, input, { participantId: "newer-success" }), delivery(expired, input, { participantId: "older-expired" })],
212
+ verification: [{ event: newerSuccess, expected: expectedBachsState(newerSuccess) }]
213
+ };
214
+ }
215
+ if (scenario === "incomplete-checkout") {
216
+ const incomplete = checkoutFixture(base, "checkout.completed", {
217
+ createdAt: isoAt(now),
218
+ paymentStatus: "no_payment_required",
219
+ charge: false,
220
+ eligible: false,
221
+ status: "completed"
222
+ });
223
+ return { deliveries: [delivery(incomplete)], verification: [{ event: incomplete, expected: expectedNoCredit(incomplete) }] };
224
+ }
225
+ if (scenario === "expired-checkout") {
226
+ const expired = checkoutFixture(base, "checkout.expired", {
227
+ createdAt: isoAt(now),
228
+ paymentStatus: null,
229
+ charge: false,
230
+ eligible: false,
231
+ status: "expired"
232
+ });
233
+ return { deliveries: [delivery(expired)], verification: [{ event: expired, expected: expectedNoCredit(expired) }] };
234
+ }
235
+ if (scenario === "incorrect-payment-amount") {
236
+ const incorrect = createBachsMockFixture({ reference, amountMinor: amountMinor + 1, currency, customerId: customerId2 });
237
+ return { deliveries: [delivery(incorrect)], verification: [{ event: incorrect, expected: expectedNoCredit(incorrect) }] };
238
+ }
239
+ if (scenario === "incorrect-payment-currency") {
240
+ const incorrectCurrency = currency === "USD" ? "EUR" : "USD";
241
+ const incorrect = createBachsMockFixture({ reference, amountMinor, currency: incorrectCurrency, customerId: customerId2 });
242
+ return { deliveries: [delivery(incorrect)], verification: [{ event: incorrect, expected: expectedNoCredit(incorrect) }] };
243
+ }
244
+ if (scenario === "underpaid-payment") {
245
+ const paidMinor = Math.max(1, Math.floor(amountMinor / 2));
246
+ const paid = formatBachsMoney(BigInt(paidMinor), 2);
247
+ const expectedAmount = formatBachsMoney(BigInt(amountMinor), 2);
248
+ const remaining = formatBachsMoney(BigInt(amountMinor - paidMinor), 2);
249
+ const underpaid = {
250
+ ...base,
251
+ id: `evt_${randomUUID().replaceAll("-", "")}`,
252
+ type: "collection.underpaid",
253
+ data: {
254
+ charge_id: base.providerPaymentId,
255
+ reference,
256
+ checkout_id: base.checkoutId,
257
+ amount_paid: paid,
258
+ amount_expected: expectedAmount,
259
+ amount_remaining: remaining,
260
+ currency,
261
+ status: "UNDERPAID",
262
+ metadata: { order_id: reference }
263
+ },
264
+ amountMinor: paidMinor,
265
+ status: "UNDERPAID",
266
+ eligible: false
267
+ };
268
+ return { deliveries: [delivery(underpaid)], verification: [{ event: underpaid, expected: expectedNoCredit(underpaid) }] };
269
+ }
270
+ if (scenario === "failed-payment") {
271
+ const failed = {
272
+ ...base,
273
+ id: `evt_${randomUUID().replaceAll("-", "")}`,
274
+ type: "collection.failed",
275
+ data: {
276
+ charge_id: base.providerPaymentId,
277
+ checkout_id: base.checkoutId,
278
+ reference,
279
+ status: "FAILED",
280
+ amount: formatBachsMoney(BigInt(amountMinor), 2),
281
+ currency,
282
+ settlement_amount: null,
283
+ settlement_currency: null,
284
+ processing_fee: null,
285
+ processing_fee_currency: null,
286
+ fee_bearer: "merchant",
287
+ product_cart: null,
288
+ customer: { id: base.customerId, email: "synthetic@example.com", name: "Synthetic Customer" },
289
+ reason: "synthetic_test_failure",
290
+ payment_method_details: null,
291
+ metadata: { order_id: reference }
292
+ },
293
+ status: "FAILED",
294
+ eligible: false
295
+ };
296
+ return { deliveries: [delivery(failed)], verification: [{ event: failed, expected: expectedNoCredit(failed) }] };
297
+ }
298
+ return successful();
299
+ }
300
+ function createBachsMockFixture(options) {
301
+ const eligible = options.eligible !== false;
302
+ const reference = options.reference;
303
+ const currency = options.currency ?? "NGN";
304
+ const amountMinor = options.amountMinor ?? 5e6;
305
+ const amount = formatBachsMoney(BigInt(amountMinor), 2);
306
+ const exactAmount = parseBachsMoney(amount, currency);
307
+ const providerPaymentId = `ch_${randomUUID().replaceAll("-", "")}`;
308
+ const checkoutId = `chk_${randomUUID().replaceAll("-", "")}`;
309
+ return {
310
+ id: `evt_${randomUUID().replaceAll("-", "")}`,
311
+ type: "collection.succeeded",
312
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
313
+ organization_id: "acct_bachsproof_test",
314
+ data: {
315
+ charge_id: providerPaymentId,
316
+ checkout_id: checkoutId,
317
+ reference,
318
+ status: eligible ? "SUCCEEDED" : "ACCEPTED",
319
+ amount,
320
+ currency,
321
+ settlement_amount: amount,
322
+ settlement_currency: currency,
323
+ fee_bearer: "merchant",
324
+ product_cart: null,
325
+ customer: { id: options.customerId ?? "customer-test-001", email: "synthetic@example.com", name: "Synthetic Customer" },
326
+ payment_method_details: null,
327
+ metadata: { order_id: reference }
328
+ },
329
+ reference,
330
+ amountMinor: safeNumberMoney(toBachsMinorUnits(exactAmount, 2)),
331
+ amountScale: 2,
332
+ currency,
333
+ status: eligible ? "SUCCEEDED" : "ACCEPTED",
334
+ customerId: options.customerId ?? "customer-test-001",
335
+ providerPaymentId,
336
+ checkoutId,
337
+ eligible
338
+ };
339
+ }
340
+ function serializeBachsPaymentEvent(event) {
341
+ return JSON.stringify({
342
+ id: event.id,
343
+ type: event.type,
344
+ created_at: event.created_at,
345
+ organization_id: event.organization_id,
346
+ data: event.data
347
+ });
348
+ }
349
+ function parseBachsWebhookEvent(value) {
350
+ return BachsWebhookEventSchema.parse(value);
351
+ }
352
+ function stringField(value) {
353
+ return typeof value === "string" && value.length > 0 ? value : void 0;
354
+ }
355
+ function customerId(value) {
356
+ if (!value || typeof value !== "object") return void 0;
357
+ const candidate = value;
358
+ return stringField(candidate.id) ?? stringField(candidate.customer_id);
359
+ }
360
+ function normalizeBachsWebhookEvent(value) {
361
+ const event = parseBachsWebhookEvent(value);
362
+ if (event.type === "checkout.completed" || event.type === "checkout.expired") {
363
+ const data2 = event.data;
364
+ const amount2 = data2.currency ? parseBachsMoney(data2.amount, data2.currency) : void 0;
365
+ const eligible = event.type === "checkout.completed" && data2.status === "completed" && data2.mode === "payment" && data2.payment_status === "paid" && data2.charge !== null && data2.currency !== null;
366
+ return {
367
+ eventId: event.id,
368
+ eventType: event.type,
369
+ eventCreatedAt: event.created_at,
370
+ reference: data2.reference ?? void 0,
371
+ amountMinor: amount2 ? safeNumberMoney(toBachsMinorUnits(amount2, amount2.scale)) : void 0,
372
+ amountScale: amount2?.scale,
373
+ amount: data2.amount,
374
+ currency: data2.currency ?? void 0,
375
+ customerId: customerId(data2.customer),
376
+ providerPaymentId: data2.charge?.id,
377
+ checkoutId: data2.checkout_id,
378
+ eligible,
379
+ status: eligible ? "SUCCEEDED" : data2.status
380
+ };
381
+ }
382
+ if (event.type === "collection.succeeded") {
383
+ const data2 = event.data;
384
+ const amount2 = parseBachsMoney(data2.amount, data2.currency);
385
+ const eligible = data2.status === "SUCCEEDED";
386
+ return {
387
+ eventId: event.id,
388
+ eventType: event.type,
389
+ eventCreatedAt: event.created_at,
390
+ reference: data2.reference ?? void 0,
391
+ amountMinor: safeNumberMoney(toBachsMinorUnits(amount2, amount2.scale)),
392
+ amountScale: amount2.scale,
393
+ amount: data2.amount,
394
+ currency: data2.currency,
395
+ customerId: customerId(data2.customer),
396
+ providerPaymentId: data2.charge_id ?? void 0,
397
+ checkoutId: data2.checkout_id ?? void 0,
398
+ eligible,
399
+ status: data2.status
400
+ };
401
+ }
402
+ const data = event.data;
403
+ const reference = stringField(data.reference);
404
+ const amount = event.type === "collection.underpaid" ? stringField(data.amount_paid) : stringField(data.amount);
405
+ const currency = stringField(data.currency);
406
+ let amountMinor;
407
+ let amountScale;
408
+ if (amount && currency) {
409
+ const exact = parseBachsMoney(amount, currency);
410
+ amountMinor = safeNumberMoney(toBachsMinorUnits(exact, exact.scale));
411
+ amountScale = exact.scale;
412
+ }
413
+ return {
414
+ eventId: event.id,
415
+ eventType: event.type,
416
+ eventCreatedAt: event.created_at,
417
+ reference,
418
+ amountMinor,
419
+ amountScale,
420
+ amount,
421
+ currency,
422
+ customerId: customerId(data.customer),
423
+ providerPaymentId: stringField(data.charge_id),
424
+ checkoutId: stringField(data.checkout_id),
425
+ eligible: false,
426
+ status: event.type === "collection.underpaid" ? "UNDERPAID" : "FAILED"
427
+ };
428
+ }
429
+ function expectedBachsState(event) {
430
+ return {
431
+ reference: event.reference,
432
+ eligible: event.eligible,
433
+ amountMinor: event.amountMinor,
434
+ currency: event.currency,
435
+ expectedCreditCount: 1
436
+ };
437
+ }
438
+
439
+ // src/adapter.ts
440
+ function bachsAdapter(options) {
441
+ if (options.mode !== "mock") {
442
+ throw new Error('BachsProof currently supports only local mock mode. Use bachsAdapter({ mode: "mock" }); it does not call the Bachs sandbox.');
443
+ }
444
+ return {
445
+ // These values are copied into reports and help distinguish provider modes.
446
+ name: "Bachs",
447
+ mode: "mock",
448
+ createPayment(input) {
449
+ return createBachsMockFixture({ customerId: options.customerId, ...input });
450
+ },
451
+ serialize(event) {
452
+ return serializeBachsPaymentEvent(event);
453
+ },
454
+ expectedState(event) {
455
+ return expectedBachsState(event);
456
+ },
457
+ createScenario(scenario, input) {
458
+ return createBachsScenario(scenario, input, options.customerId);
459
+ },
460
+ headers() {
461
+ return { "x-bachsproof-provider-mode": "mock" };
462
+ }
463
+ };
464
+ }
465
+ function signBachsWebhook(rawBody, secret, timestamp = Math.floor(Date.now() / 1e3)) {
466
+ if (!secret) throw new Error("Bachs webhook signing requires a non-empty secret");
467
+ if (!Number.isInteger(timestamp) || timestamp < 0) throw new Error("Bachs webhook signature timestamp must be a non-negative integer");
468
+ const payload = `${timestamp}.${typeof rawBody === "string" ? rawBody : Buffer.from(rawBody).toString("utf8")}`;
469
+ const signature = createHmac("sha256", secret).update(payload).digest("hex");
470
+ return { "x-bachs-signature-v2": `t=${timestamp},v1=${signature}` };
471
+ }
472
+
473
+ export { BachsWebhookEventSchema, bachsAdapter, compareBachsMoney, createBachsMockFixture, createBachsScenario, expectedBachsState, formatBachsMoney, normalizeBachsWebhookEvent, parseBachsMoney, parseBachsWebhookEvent, safeNumberMoney, serializeBachsPaymentEvent, signBachsWebhook, toBachsMinorUnits };
474
+ //# sourceMappingURL=index.js.map
475
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/money.ts","../src/fixtures.ts","../src/adapter.ts","../src/signing.ts"],"names":["customerId","data","amount"],"mappings":";;;;;;AAcA,IAAM,cAAA,GAAiB,8BAAA;AAEvB,SAAS,SAAA,CAAU,aAAqB,KAAA,EAAuD;AAC7F,EAAA,IAAI,qBAAA,GAAwB,WAAA;AAC5B,EAAA,IAAI,eAAA,GAAkB,KAAA;AACtB,EAAA,OAAO,eAAA,GAAkB,CAAA,IAAK,qBAAA,GAAwB,GAAA,KAAQ,EAAA,EAAI;AAChE,IAAA,qBAAA,IAAyB,GAAA;AACzB,IAAA,eAAA,IAAmB,CAAA;AAAA,EACrB;AACA,EAAA,OAAO,EAAE,WAAA,EAAa,qBAAA,EAAuB,KAAA,EAAO,eAAA,EAAgB;AACtE;AAGO,SAAS,eAAA,CAAgB,QAAgB,QAAA,EAA8B;AAC5E,EAAA,IAAI,CAAC,YAAA,CAAa,IAAA,CAAK,QAAQ,CAAA,QAAS,IAAI,KAAA,CAAM,CAAA,qBAAA,EAAwB,QAAQ,CAAA,CAAE,CAAA;AACpF,EAAA,MAAM,KAAA,GAAQ,cAAA,CAAe,IAAA,CAAK,MAAM,CAAA;AACxC,EAAA,IAAI,CAAC,KAAA,EAAO,MAAM,IAAI,KAAA,CAAM,CAAA,6BAAA,EAAgC,MAAM,CAAA,CAAE,CAAA;AACpE,EAAA,MAAM,Q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EAA8B,MAAA,EAAgB,SAAA,GAAY,IAAA,CAAK,MAAM,IAAA,CAAK,GAAA,EAAI,GAAI,GAAI,CAAA,EAA2B;AAChJ,EAAA,IAAI,CAAC,MAAA,EAAQ,MAAM,IAAI,MAAM,mDAAmD,CAAA;AAChF,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,SAAS,CAAA,IAAK,YAAY,CAAA,EAAG,MAAM,IAAI,KAAA,CAAM,kEAAkE,CAAA;AACrI,EAAA,MAAM,OAAA,GAAU,CAAA,EAAG,SAAS,CAAA,CAAA,EAAI,OAAO,OAAA,KAAY,QAAA,GAAW,OAAA,GAAU,MAAA,CAAO,IAAA,CAAK,OAAO,CAAA,CAAE,QAAA,CAAS,MAAM,CAAC,CAAA,CAAA;AAC7G,EAAA,MAAM,SAAA,GAAY,WAAW,QAAA,EAAU,MAAM,EAAE,MAAA,CAAO,OAAO,CAAA,CAAE,MAAA,CAAO,KAAK,CAAA;AAC3E,EAAA,OAAO,EAAE,sBAAA,EAAwB,CAAA,EAAA,EAAK,SAAS,CAAA,IAAA,EAAO,SAAS,CAAA,CAAA,EAAG;AACpE","file":"index.js","sourcesContent":["/**\n * Exact decimal parsing for Bachs amounts.\n *\n * Bachs sends money as decimal strings at the currency's precision. We keep\n * the decimal coefficient as a bigint and retain its scale rather than ever\n * passing through Number arithmetic. Callers can convert to a bounded integer\n * only at an application boundary that explicitly requires it.\n */\nexport interface ExactMoney {\n currency: string;\n coefficient: bigint;\n scale: number;\n}\n\nconst DECIMAL_AMOUNT = /^(?:0|[1-9]\\d*)(?:\\.(\\d+))?$/;\n\nfunction normalize(coefficient: bigint, scale: number): { coefficient: bigint; scale: number } {\n let normalizedCoefficient = coefficient;\n let normalizedScale = scale;\n while (normalizedScale > 0 && normalizedCoefficient % 10n === 0n) {\n normalizedCoefficient /= 10n;\n normalizedScale -= 1;\n }\n return { coefficient: normalizedCoefficient, scale: normalizedScale };\n}\n\n/** Parse a Bachs decimal amount without floating-point conversion. */\nexport function parseBachsMoney(amount: string, currency: string): ExactMoney {\n if (!/^[A-Z]{3}$/.test(currency)) throw new Error(`Invalid ISO currency ${currency}`);\n const match = DECIMAL_AMOUNT.exec(amount);\n if (!match) throw new Error(`Invalid Bachs decimal amount ${amount}`);\n const fraction = match[1] ?? \"\";\n const coefficient = BigInt(`${match[0].split(\".\")[0]}${fraction}`);\n return { coefficient, scale: fraction.length, currency };\n}\n\n/** Compare two exact monetary values after checking their currencies. */\nexport function compareBachsMoney(left: ExactMoney, right: ExactMoney): -1 | 0 | 1 {\n if (left.currency !== right.currency) throw new Error(\"Cannot compare money in different currencies\");\n const normalizedLeft = normalize(left.coefficient, left.scale);\n const normalizedRight = normalize(right.coefficient, right.scale);\n const scale = Math.max(normalizedLeft.scale, normalizedRight.scale);\n const leftValue = normalizedLeft.coefficient * 10n ** BigInt(scale - normalizedLeft.scale);\n const rightValue = normalizedRight.coefficient * 10n ** BigInt(scale - normalizedRight.scale);\n return leftValue < rightValue ? -1 : leftValue > rightValue ? 1 : 0;\n}\n\n/** Convert an exact amount to an integer at the supplied storage scale. */\nexport function toBachsMinorUnits(value: ExactMoney, scale: number): bigint {\n if (!Number.isInteger(scale) || scale < 0) throw new Error(\"Money scale must be a non-negative integer\");\n if (value.scale > scale && value.coefficient % (10n ** BigInt(value.scale - scale)) !== 0n) {\n throw new Error(`Amount ${value.coefficient} has more precision than storage scale ${scale}`);\n }\n return value.coefficient * 10n ** BigInt(scale - value.scale);\n}\n\n/** Convert a bigint to the provider-neutral number shape only when safe. */\nexport function safeNumberMoney(value: bigint): number {\n const number = Number(value);\n if (!Number.isSafeInteger(number)) throw new Error(\"Financial amount exceeds JavaScript safe integer range\");\n return number;\n}\n\n/** Format an integer amount for a local fixture without floating-point math. */\nexport function formatBachsMoney(value: bigint, scale: number): string {\n if (scale < 0 || !Number.isInteger(scale)) throw new Error(\"Money scale must be a non-negative integer\");\n const negative = value < 0n;\n const digits = (negative ? -value : value).toString().padStart(scale + 1, \"0\");\n if (scale === 0) return `${negative ? \"-\" : \"\"}${digits}`;\n const split = digits.length - scale;\n return `${negative ? \"-\" : \"\"}${digits.slice(0, split)}.${digits.slice(split)}`;\n}\n","import { randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport type { ExpectedPaymentState, PaymentEvent, ProviderScenario, ProviderScenarioInput, ScenarioName } from \"@bachsproof/core\";\nimport { formatBachsMoney, parseBachsMoney, safeNumberMoney, toBachsMinorUnits } from \"./money.js\";\n\nconst customerSchema = z.object({\n id: z.string().min(1).nullable().optional(),\n customer_id: z.string().min(1).nullable().optional(),\n email: z.string().email().nullable().optional(),\n name: z.string().nullable().optional()\n}).passthrough();\n\nconst checkoutDataSchema = z.object({\n checkout_id: z.string().min(1),\n status: z.string().min(1),\n mode: z.string().min(1),\n payment_status: z.string().nullable(),\n amount: z.string().min(1),\n currency: z.string().length(3).nullable(),\n reference: z.string().min(1).nullable(),\n customer: customerSchema.nullable(),\n charge: z.object({ id: z.string().min(1) }).passthrough().nullable(),\n metadata: z.record(z.unknown()).default({})\n}).passthrough();\n\nconst collectionDataSchema = z.object({\n charge_id: z.string().min(1).nullable(),\n checkout_id: z.string().min(1).nullable(),\n reference: z.string().min(1).nullable(),\n status: z.string().min(1),\n amount: z.string().min(1),\n currency: z.string().length(3),\n customer: customerSchema,\n metadata: z.record(z.unknown()).default({})\n}).passthrough();\n\nconst underpaidDataSchema = z.object({\n charge_id: z.string().min(1),\n reference: z.string().min(1).nullable(),\n checkout_id: z.string().min(1).nullable(),\n amount_paid: z.string().min(1),\n amount_expected: z.string().min(1),\n amount_remaining: z.string().min(1),\n currency: z.string().length(3),\n status: z.literal(\"UNDERPAID\"),\n metadata: z.record(z.unknown()).default({})\n}).passthrough();\n\nconst failedDataSchema = z.object({\n charge_id: z.string().min(1),\n checkout_id: z.string().min(1).nullable(),\n reference: z.string().min(1).nullable(),\n status: z.enum([\"FAILED\", \"EXPIRED\"]),\n amount: z.string().min(1),\n currency: z.string().length(3),\n settlement_amount: z.string().min(1).nullable().optional(),\n settlement_currency: z.string().length(3).nullable().optional(),\n processing_fee: z.string().min(1).nullable().optional(),\n processing_fee_currency: z.string().length(3).nullable().optional(),\n fee_bearer: z.string().nullable().optional(),\n product_cart: z.unknown().nullable().optional(),\n customer: customerSchema,\n reason: z.string().nullable().optional(),\n payment_method_details: z.unknown().nullable().optional(),\n metadata: z.record(z.unknown()).default({})\n}).passthrough();\n\nconst genericDataSchema = z.record(z.unknown());\n\nconst eventEnvelope = z.object({\n id: z.string().min(1),\n type: z.string().min(1),\n created_at: z.string().datetime({ offset: true }),\n organization_id: z.string().min(1),\n data: genericDataSchema\n}).passthrough();\n\nexport const BachsWebhookEventSchema = z.union([\n eventEnvelope.extend({ type: z.literal(\"checkout.completed\"), data: checkoutDataSchema }),\n eventEnvelope.extend({ type: z.literal(\"checkout.expired\"), data: checkoutDataSchema }),\n eventEnvelope.extend({ type: z.literal(\"collection.succeeded\"), data: collectionDataSchema }),\n eventEnvelope.extend({ type: z.literal(\"collection.underpaid\"), data: underpaidDataSchema }),\n eventEnvelope.extend({ type: z.literal(\"collection.failed\"), data: failedDataSchema }),\n eventEnvelope\n]);\n\nexport type BachsWebhookEvent = z.infer<typeof BachsWebhookEventSchema>;\ntype CheckoutData = z.infer<typeof checkoutDataSchema>;\ntype CollectionData = z.infer<typeof collectionDataSchema>;\n\nexport interface NormalizedBachsPayment {\n eventId: string;\n eventType: BachsWebhookEvent[\"type\"];\n eventCreatedAt: string;\n reference?: string;\n amountMinor?: number;\n amountScale?: number;\n amount?: string;\n currency?: string;\n customerId?: string;\n providerPaymentId?: string;\n checkoutId?: string;\n eligible: boolean;\n status: string;\n}\n\nexport interface BachsPaymentEvent extends PaymentEvent {\n id: string;\n type: BachsWebhookEvent[\"type\"];\n created_at: string;\n organization_id: string;\n data: BachsWebhookEvent[\"data\"];\n /** Normalized fields used by the provider-neutral core. */\n reference: string;\n amountMinor: number;\n amountScale: number;\n currency: string;\n status: string;\n customerId: string;\n providerPaymentId: string;\n checkoutId: string;\n eligible: boolean;\n}\n\nexport interface BachsFixtureOptions {\n reference: string;\n amountMinor?: number;\n currency?: string;\n eligible?: boolean;\n customerId?: string;\n}\n\nfunction isoAt(baseMs: number, offsetMs = 0): string {\n return new Date(baseMs + offsetMs).toISOString();\n}\n\nfunction expectedNoCredit(event: BachsPaymentEvent): ExpectedPaymentState {\n return {\n reference: event.reference,\n eligible: false,\n amountMinor: event.amountMinor,\n currency: event.currency,\n expectedCreditCount: 0\n };\n}\n\nfunction checkoutFixture(\n base: BachsPaymentEvent,\n type: \"checkout.completed\" | \"checkout.expired\",\n options: { createdAt: string; paymentStatus: string | null; charge: boolean; eligible: boolean; status: string }\n): BachsPaymentEvent {\n const charge = options.charge ? { id: base.providerPaymentId } : null;\n return {\n ...base,\n id: `evt_${randomUUID().replaceAll(\"-\", \"\")}`,\n type,\n created_at: options.createdAt,\n data: {\n checkout_id: base.checkoutId,\n status: options.status,\n mode: \"payment\",\n payment_status: options.paymentStatus,\n amount: formatBachsMoney(BigInt(base.amountMinor), 2),\n currency: base.currency,\n reference: base.reference,\n customer: { id: base.customerId, email: \"synthetic@example.com\", name: \"Synthetic Customer\" },\n charge,\n success_url: \"https://example.test/success\",\n cancel_url: \"https://example.test/cancel\",\n subscription: null,\n completed_at: options.eligible ? options.createdAt : null,\n expires_at: options.createdAt,\n metadata: { order_id: base.reference }\n } as BachsPaymentEvent[\"data\"],\n amountMinor: base.amountMinor,\n status: options.eligible ? \"SUCCEEDED\" : options.status,\n eligible: options.eligible\n };\n}\n\nfunction delivery(event: BachsPaymentEvent, _input: ProviderScenarioInput, overrides: Partial<import(\"@bachsproof/core\").ProviderScenarioDelivery<BachsPaymentEvent>> = {}) {\n return {\n event,\n ...overrides\n };\n}\n\n/**\n * Build documented Bachs lifecycle and rejection scenarios. These are\n * synthetic webhook deliveries for isolated, authorized test environments;\n * they do not call Bachs or create real payment state.\n */\nexport function createBachsScenario(scenario: ScenarioName, input: ProviderScenarioInput, customerId?: string): ProviderScenario<BachsPaymentEvent> | undefined {\n if ([\"concurrent-duplicate-credit\", \"sequential-duplicate-webhook\", \"concurrent-unique-payments\"].includes(scenario)) return undefined;\n const reference = input.reference;\n const amountMinor = input.amountMinor ?? 5_000_000;\n const currency = input.currency ?? \"NGN\";\n const base = createBachsMockFixture({ reference, amountMinor, currency, customerId });\n const now = Date.now();\n const successful = () => ({\n deliveries: [delivery(base, input)],\n verification: [{ event: base, expected: expectedBachsState(base) }]\n });\n\n if (scenario === \"cross-event-duplicate-payment\") {\n const completed = checkoutFixture(base, \"checkout.completed\", {\n createdAt: isoAt(now),\n paymentStatus: \"paid\",\n charge: true,\n eligible: true,\n status: \"completed\"\n });\n return {\n concurrent: true,\n deliveries: [delivery(completed, input, { participantId: \"checkout-completed\" }), delivery(base, input, { participantId: \"collection-succeeded\" })],\n verification: [{ event: base, expected: expectedBachsState(base) }]\n };\n }\n\n if (scenario === \"out-of-order-events\") {\n const expired = checkoutFixture(base, \"checkout.expired\", {\n createdAt: isoAt(now),\n paymentStatus: null,\n charge: false,\n eligible: false,\n status: \"expired\"\n });\n const newerSuccess = { ...base, created_at: isoAt(now + 1_000) };\n return {\n deliveries: [delivery(newerSuccess, input, { participantId: \"newer-success\" }), delivery(expired, input, { participantId: \"older-expired\" })],\n verification: [{ event: newerSuccess, expected: expectedBachsState(newerSuccess) }]\n };\n }\n\n if (scenario === \"incomplete-checkout\") {\n const incomplete = checkoutFixture(base, \"checkout.completed\", {\n createdAt: isoAt(now),\n paymentStatus: \"no_payment_required\",\n charge: false,\n eligible: false,\n status: \"completed\"\n });\n return { deliveries: [delivery(incomplete, input)], verification: [{ event: incomplete, expected: expectedNoCredit(incomplete) }] };\n }\n\n if (scenario === \"expired-checkout\") {\n const expired = checkoutFixture(base, \"checkout.expired\", {\n createdAt: isoAt(now),\n paymentStatus: null,\n charge: false,\n eligible: false,\n status: \"expired\"\n });\n return { deliveries: [delivery(expired, input)], verification: [{ event: expired, expected: expectedNoCredit(expired) }] };\n }\n\n if (scenario === \"incorrect-payment-amount\") {\n const incorrect = createBachsMockFixture({ reference, amountMinor: amountMinor + 1, currency, customerId });\n return { deliveries: [delivery(incorrect, input)], verification: [{ event: incorrect, expected: expectedNoCredit(incorrect) }] };\n }\n\n if (scenario === \"incorrect-payment-currency\") {\n const incorrectCurrency = currency === \"USD\" ? \"EUR\" : \"USD\";\n const incorrect = createBachsMockFixture({ reference, amountMinor, currency: incorrectCurrency, customerId });\n return { deliveries: [delivery(incorrect, input)], verification: [{ event: incorrect, expected: expectedNoCredit(incorrect) }] };\n }\n\n if (scenario === \"underpaid-payment\") {\n const paidMinor = Math.max(1, Math.floor(amountMinor / 2));\n const paid = formatBachsMoney(BigInt(paidMinor), 2);\n const expectedAmount = formatBachsMoney(BigInt(amountMinor), 2);\n const remaining = formatBachsMoney(BigInt(amountMinor - paidMinor), 2);\n const underpaid: BachsPaymentEvent = {\n ...base,\n id: `evt_${randomUUID().replaceAll(\"-\", \"\")}`,\n type: \"collection.underpaid\",\n data: {\n charge_id: base.providerPaymentId,\n reference,\n checkout_id: base.checkoutId,\n amount_paid: paid,\n amount_expected: expectedAmount,\n amount_remaining: remaining,\n currency,\n status: \"UNDERPAID\",\n metadata: { order_id: reference }\n } as BachsPaymentEvent[\"data\"],\n amountMinor: paidMinor,\n status: \"UNDERPAID\",\n eligible: false\n };\n return { deliveries: [delivery(underpaid, input)], verification: [{ event: underpaid, expected: expectedNoCredit(underpaid) }] };\n }\n\n if (scenario === \"failed-payment\") {\n const failed: BachsPaymentEvent = {\n ...base,\n id: `evt_${randomUUID().replaceAll(\"-\", \"\")}`,\n type: \"collection.failed\",\n data: {\n charge_id: base.providerPaymentId,\n checkout_id: base.checkoutId,\n reference,\n status: \"FAILED\",\n amount: formatBachsMoney(BigInt(amountMinor), 2),\n currency,\n settlement_amount: null,\n settlement_currency: null,\n processing_fee: null,\n processing_fee_currency: null,\n fee_bearer: \"merchant\",\n product_cart: null,\n customer: { id: base.customerId, email: \"synthetic@example.com\", name: \"Synthetic Customer\" },\n reason: \"synthetic_test_failure\",\n payment_method_details: null,\n metadata: { order_id: reference }\n } as BachsPaymentEvent[\"data\"],\n status: \"FAILED\",\n eligible: false\n };\n return { deliveries: [delivery(failed, input)], verification: [{ event: failed, expected: expectedNoCredit(failed) }] };\n }\n\n return successful();\n}\n\n/** Generate a deterministic local fixture with the documented collection envelope. */\nexport function createBachsMockFixture(options: BachsFixtureOptions): BachsPaymentEvent {\n const eligible = options.eligible !== false;\n const reference = options.reference;\n const currency = options.currency ?? \"NGN\";\n const amountMinor = options.amountMinor ?? 5_000_000;\n const amount = formatBachsMoney(BigInt(amountMinor), 2);\n const exactAmount = parseBachsMoney(amount, currency);\n const providerPaymentId = `ch_${randomUUID().replaceAll(\"-\", \"\")}`;\n const checkoutId = `chk_${randomUUID().replaceAll(\"-\", \"\")}`;\n return {\n id: `evt_${randomUUID().replaceAll(\"-\", \"\")}`,\n type: \"collection.succeeded\",\n created_at: new Date().toISOString(),\n organization_id: \"acct_bachsproof_test\",\n data: {\n charge_id: providerPaymentId,\n checkout_id: checkoutId,\n reference,\n status: eligible ? \"SUCCEEDED\" : \"ACCEPTED\",\n amount,\n currency,\n settlement_amount: amount,\n settlement_currency: currency,\n fee_bearer: \"merchant\",\n product_cart: null,\n customer: { id: options.customerId ?? \"customer-test-001\", email: \"synthetic@example.com\", name: \"Synthetic Customer\" },\n payment_method_details: null,\n metadata: { order_id: reference }\n },\n reference,\n amountMinor: safeNumberMoney(toBachsMinorUnits(exactAmount, 2)),\n amountScale: 2,\n currency,\n status: eligible ? \"SUCCEEDED\" : \"ACCEPTED\",\n customerId: options.customerId ?? \"customer-test-001\",\n providerPaymentId,\n checkoutId,\n eligible\n };\n}\n\n/** Serialize only the authentic provider envelope, excluding normalized fields. */\nexport function serializeBachsPaymentEvent(event: BachsPaymentEvent): string {\n return JSON.stringify({\n id: event.id,\n type: event.type,\n created_at: event.created_at,\n organization_id: event.organization_id,\n data: event.data\n });\n}\n\n/** Validate an externally supplied documented Bachs webhook envelope. */\nexport function parseBachsWebhookEvent(value: unknown): BachsWebhookEvent {\n return BachsWebhookEventSchema.parse(value);\n}\n\nfunction stringField(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction customerId(value: unknown): string | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n const candidate = value as Record<string, unknown>;\n return stringField(candidate.id) ?? stringField(candidate.customer_id);\n}\n\n/** Normalize only fields verified in the documented event examples. */\nexport function normalizeBachsWebhookEvent(value: unknown): NormalizedBachsPayment {\n const event = parseBachsWebhookEvent(value);\n if (event.type === \"checkout.completed\" || event.type === \"checkout.expired\") {\n const data = event.data as CheckoutData;\n const amount = data.currency ? parseBachsMoney(data.amount, data.currency) : undefined;\n const eligible = event.type === \"checkout.completed\"\n && data.status === \"completed\"\n && data.mode === \"payment\"\n && data.payment_status === \"paid\"\n && data.charge !== null\n && data.currency !== null;\n return {\n eventId: event.id,\n eventType: event.type,\n eventCreatedAt: event.created_at,\n reference: data.reference ?? undefined,\n amountMinor: amount ? safeNumberMoney(toBachsMinorUnits(amount, amount.scale)) : undefined,\n amountScale: amount?.scale,\n amount: data.amount,\n currency: data.currency ?? undefined,\n customerId: customerId(data.customer),\n providerPaymentId: data.charge?.id,\n checkoutId: data.checkout_id,\n eligible,\n status: eligible ? \"SUCCEEDED\" : data.status\n };\n }\n\n if (event.type === \"collection.succeeded\") {\n const data = event.data as CollectionData;\n const amount = parseBachsMoney(data.amount, data.currency);\n const eligible = data.status === \"SUCCEEDED\";\n return {\n eventId: event.id,\n eventType: event.type,\n eventCreatedAt: event.created_at,\n reference: data.reference ?? undefined,\n amountMinor: safeNumberMoney(toBachsMinorUnits(amount, amount.scale)),\n amountScale: amount.scale,\n amount: data.amount,\n currency: data.currency,\n customerId: customerId(data.customer),\n providerPaymentId: data.charge_id ?? undefined,\n checkoutId: data.checkout_id ?? undefined,\n eligible,\n status: data.status\n };\n }\n\n // Underpaid and failed events are explicitly non-fulfilling. Underpaid uses\n // the documented amount_paid field for observability; it still cannot create\n // a wallet credit until a later successful event arrives.\n const data = event.data as Record<string, unknown>;\n const reference = stringField(data.reference);\n const amount = event.type === \"collection.underpaid\"\n ? stringField(data.amount_paid)\n : stringField(data.amount);\n const currency = stringField(data.currency);\n let amountMinor: number | undefined;\n let amountScale: number | undefined;\n if (amount && currency) {\n const exact = parseBachsMoney(amount, currency);\n amountMinor = safeNumberMoney(toBachsMinorUnits(exact, exact.scale));\n amountScale = exact.scale;\n }\n return {\n eventId: event.id,\n eventType: event.type,\n eventCreatedAt: event.created_at,\n reference,\n amountMinor,\n amountScale,\n amount,\n currency,\n customerId: customerId(data.customer),\n providerPaymentId: stringField(data.charge_id),\n checkoutId: stringField(data.checkout_id),\n eligible: false,\n status: event.type === \"collection.underpaid\" ? \"UNDERPAID\" : \"FAILED\"\n };\n}\n\n/** Translate provider metadata into the core's expected-state model. */\nexport function expectedBachsState(event: BachsPaymentEvent): ExpectedPaymentState {\n return {\n reference: event.reference,\n eligible: event.eligible,\n amountMinor: event.amountMinor,\n currency: event.currency,\n expectedCreditCount: 1\n };\n}\n","import type { ProviderAdapter } from \"@bachsproof/core\";\nimport { createBachsMockFixture, createBachsScenario, expectedBachsState, serializeBachsPaymentEvent, type BachsFixtureOptions, type BachsPaymentEvent } from \"./fixtures.js\";\n\nexport interface BachsAdapterOptions {\n mode: \"mock\";\n /** Optional isolated customer ID for database-backed integration tests. */\n customerId?: string;\n}\n\n/**\n * Build the provider-neutral adapter. Mock mode is explicit so a caller never\n * mistakes synthetic fixtures for authenticated provider traffic.\n */\nexport function bachsAdapter(options: BachsAdapterOptions): ProviderAdapter<BachsPaymentEvent> {\n if (options.mode !== \"mock\") {\n throw new Error(\"BachsProof currently supports only local mock mode. Use bachsAdapter({ mode: \\\"mock\\\" }); it does not call the Bachs sandbox.\");\n }\n return {\n // These values are copied into reports and help distinguish provider modes.\n name: \"Bachs\",\n mode: \"mock\",\n createPayment(input) {\n return createBachsMockFixture({ customerId: options.customerId, ...input });\n },\n serialize(event) {\n return serializeBachsPaymentEvent(event);\n },\n expectedState(event) {\n return expectedBachsState(event);\n },\n createScenario(scenario, input) {\n return createBachsScenario(scenario, input, options.customerId);\n },\n headers() {\n return { \"x-bachsproof-provider-mode\": \"mock\" };\n }\n };\n}\n","import { createHmac } from \"node:crypto\";\n\n/**\n * Create the documented Bachs V2 signature header for a raw request body.\n * This is intended for deterministic test delivery; it never performs a\n * provider API call or represents a live Bachs delivery.\n */\nexport function signBachsWebhook(rawBody: string | Uint8Array, secret: string, timestamp = Math.floor(Date.now() / 1000)): Record<string, string> {\n if (!secret) throw new Error(\"Bachs webhook signing requires a non-empty secret\");\n if (!Number.isInteger(timestamp) || timestamp < 0) throw new Error(\"Bachs webhook signature timestamp must be a non-negative integer\");\n const payload = `${timestamp}.${typeof rawBody === \"string\" ? rawBody : Buffer.from(rawBody).toString(\"utf8\")}`;\n const signature = createHmac(\"sha256\", secret).update(payload).digest(\"hex\");\n return { \"x-bachs-signature-v2\": `t=${timestamp},v1=${signature}` };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@bachsproof/bachs",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "2.0.0",
4
+ "description": "Bachs-shaped test fixtures, signing helpers, and exact money utilities for BachsProof",
5
+ "keywords": [
6
+ "payments",
7
+ "bachs",
8
+ "webhooks",
9
+ "payment-testing",
10
+ "typescript"
11
+ ],
12
+ "license": "MIT",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/therealEmma/BachsProof.git",
16
+ "directory": "packages/bachs"
17
+ },
18
+ "homepage": "https://github.com/therealEmma/BachsProof#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/therealEmma/BachsProof/issues"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "type": "module",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "import": "./dist/index.js"
30
+ }
31
+ },
32
+ "main": "./dist/index.js",
33
+ "types": "./dist/index.d.ts",
34
+ "files": [
35
+ "dist",
36
+ "README.md",
37
+ "LICENSE"
38
+ ],
39
+ "engines": {
40
+ "node": ">=22"
41
+ },
42
+ "dependencies": {
43
+ "zod": "^3.24.1",
44
+ "@bachsproof/core": "2.0.0"
45
+ },
46
+ "devDependencies": {
47
+ "tsup": "^8.3.5",
48
+ "typescript": "^5.7.2"
49
+ },
50
+ "scripts": {
51
+ "build": "tsup"
52
+ }
6
53
  }