better-auth-flutterwave 0.0.0 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +307 -0
  3. package/dist/client.d.mts +96 -0
  4. package/dist/client.d.mts.map +1 -0
  5. package/dist/client.mjs +75 -0
  6. package/dist/client.mjs.map +1 -0
  7. package/dist/index-BxLoiCsI.d.mts +927 -0
  8. package/dist/index-BxLoiCsI.d.mts.map +1 -0
  9. package/dist/index.d.mts +2 -0
  10. package/dist/index.mjs +1753 -0
  11. package/dist/index.mjs.map +1 -0
  12. package/dist/version-csqIJRyo.mjs +73 -0
  13. package/dist/version-csqIJRyo.mjs.map +1 -0
  14. package/package.json +119 -8
  15. package/skills/better-auth-flutterwave-setup/SKILL.md +23 -0
  16. package/skills/better-auth-flutterwave-setup/agents/openai.yaml +6 -0
  17. package/skills/flutterwave-billing-flows/SKILL.md +21 -0
  18. package/skills/flutterwave-billing-flows/agents/openai.yaml +6 -0
  19. package/skills/flutterwave-catalog-limits/SKILL.md +17 -0
  20. package/skills/flutterwave-catalog-limits/agents/openai.yaml +6 -0
  21. package/skills/flutterwave-client-api/SKILL.md +20 -0
  22. package/skills/flutterwave-client-api/agents/openai.yaml +6 -0
  23. package/skills/flutterwave-local-subscriptions/SKILL.md +18 -0
  24. package/skills/flutterwave-local-subscriptions/agents/openai.yaml +6 -0
  25. package/skills/flutterwave-organization-billing/SKILL.md +18 -0
  26. package/skills/flutterwave-organization-billing/agents/openai.yaml +6 -0
  27. package/skills/flutterwave-schema-migrations/SKILL.md +19 -0
  28. package/skills/flutterwave-schema-migrations/agents/openai.yaml +6 -0
  29. package/skills/flutterwave-tanstack-start/SKILL.md +20 -0
  30. package/skills/flutterwave-tanstack-start/agents/openai.yaml +6 -0
  31. package/skills/flutterwave-testing-fixtures/SKILL.md +20 -0
  32. package/skills/flutterwave-testing-fixtures/agents/openai.yaml +6 -0
  33. package/skills/flutterwave-webhooks-events/SKILL.md +17 -0
  34. package/skills/flutterwave-webhooks-events/agents/openai.yaml +6 -0
  35. package/index.js +0 -1
package/dist/index.mjs ADDED
@@ -0,0 +1,1753 @@
1
+ import { a as getMetadataBoolean, c as hasFlutterwaveMetadata, i as createRenewalMetadata, l as parseFlutterwaveMetadata, n as createCheckoutMetadata, o as getMetadataNumber, r as createProrationMetadata, s as getMetadataString, t as PACKAGE_VERSION, u as stringifyFlutterwaveMetadata } from "./version-csqIJRyo.mjs";
2
+ import { createRequire } from "node:module";
3
+ import { HIDE_METADATA, defineErrorCodes } from "better-auth";
4
+ import { createHash, timingSafeEqual } from "node:crypto";
5
+ import { APIError, createAuthEndpoint, getSessionFromCtx, originCheck, sessionMiddleware } from "better-auth/api";
6
+ import * as z from "zod";
7
+ import { Buffer } from "node:buffer";
8
+ import { mergeSchema } from "better-auth/db";
9
+ //#region src/billing-store.ts
10
+ function sortSubscriptionsForCurrent(subscriptions) {
11
+ const statusRank = /* @__PURE__ */ new Map([
12
+ ["active", 0],
13
+ ["trialing", 1],
14
+ ["incomplete", 2],
15
+ ["past_due", 3],
16
+ ["canceled", 4]
17
+ ]);
18
+ return [...subscriptions].sort((a, b) => {
19
+ const statusDifference = (statusRank.get(a.status) ?? 99) - (statusRank.get(b.status) ?? 99);
20
+ return statusDifference !== 0 ? statusDifference : new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime();
21
+ });
22
+ }
23
+ function createBillingStore(ctx) {
24
+ return createBillingStoreFromAdapter(ctx.context.adapter);
25
+ }
26
+ function createBillingStoreFromAdapter(adapter) {
27
+ const findOne = async (model, where) => await adapter.findOne({
28
+ model,
29
+ where
30
+ }) ?? null;
31
+ const findMany = async (model, where) => await adapter.findMany({
32
+ model,
33
+ ...where ? { where } : {}
34
+ }) ?? [];
35
+ return {
36
+ findSubscriptionById: (id) => findOne("flutterwaveSubscription", [{
37
+ field: "id",
38
+ value: id
39
+ }]),
40
+ findSubscriptionByProviderId: (subscriptionId) => findOne("flutterwaveSubscription", [{
41
+ field: "subscriptionId",
42
+ value: subscriptionId
43
+ }]),
44
+ findSubscriptionsByReference: (referenceId) => findMany("flutterwaveSubscription", [{
45
+ field: "referenceId",
46
+ value: referenceId
47
+ }]),
48
+ async findCurrentSubscription(referenceId, groupId) {
49
+ const candidates = await this.findSubscriptionsByReference(referenceId);
50
+ return sortSubscriptionsForCurrent(groupId === void 0 ? candidates : candidates.filter(({ groupId: candidateGroup }) => groupId === null ? candidateGroup === void 0 || candidateGroup === null || candidateGroup === "" : candidateGroup === groupId))[0] ?? null;
51
+ },
52
+ async retireCompetingSubscriptions(referenceId, groupId, exceptId) {
53
+ const candidates = await this.findSubscriptionsByReference(referenceId);
54
+ const now = /* @__PURE__ */ new Date();
55
+ for (const candidate of candidates) {
56
+ const sameGroup = groupId === null ? candidate.groupId === void 0 || candidate.groupId === null || candidate.groupId === "" : candidate.groupId === groupId;
57
+ if (candidate.id !== exceptId && sameGroup && (candidate.status === "active" || candidate.status === "trialing")) await this.updateSubscription(candidate.id, {
58
+ status: "canceled",
59
+ cancelAtPeriodEnd: false,
60
+ canceledAt: now,
61
+ endedAt: now,
62
+ updatedAt: now
63
+ });
64
+ }
65
+ },
66
+ findSubscriptionsByTxRef: (txRef) => findMany("flutterwaveSubscription", [{
67
+ field: "txRef",
68
+ value: txRef
69
+ }]),
70
+ createSubscription: (data) => adapter.create({
71
+ model: "flutterwaveSubscription",
72
+ data
73
+ }),
74
+ updateSubscription: (id, update) => adapter.update({
75
+ model: "flutterwaveSubscription",
76
+ update,
77
+ where: [{
78
+ field: "id",
79
+ value: id
80
+ }]
81
+ }),
82
+ updateSubscriptionByProviderId: (subscriptionId, update) => adapter.update({
83
+ model: "flutterwaveSubscription",
84
+ update,
85
+ where: [{
86
+ field: "subscriptionId",
87
+ value: subscriptionId
88
+ }]
89
+ }),
90
+ createTransaction: (data) => adapter.create({
91
+ model: "flutterwaveTransaction",
92
+ data
93
+ }),
94
+ findTransactionByTxRef: (txRef) => findOne("flutterwaveTransaction", [{
95
+ field: "txRef",
96
+ value: txRef
97
+ }]),
98
+ findTransactionById: (transactionId) => findOne("flutterwaveTransaction", [{
99
+ field: "transactionId",
100
+ value: transactionId
101
+ }]),
102
+ updateTransactionByTxRef: (txRef, update) => adapter.update({
103
+ model: "flutterwaveTransaction",
104
+ update,
105
+ where: [{
106
+ field: "txRef",
107
+ value: txRef
108
+ }]
109
+ }),
110
+ async listTransactions(referenceId) {
111
+ return (await findMany("flutterwaveTransaction", [{
112
+ field: "referenceId",
113
+ value: referenceId
114
+ }])).sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
115
+ },
116
+ async listProducts() {
117
+ return (await findMany("flutterwaveProduct")).sort((a, b) => a.name.localeCompare(b.name));
118
+ },
119
+ findProductByName: (name) => findOne("flutterwaveProduct", [{
120
+ field: "name",
121
+ value: name
122
+ }]),
123
+ findProductBySlug: (slug) => findOne("flutterwaveProduct", [{
124
+ field: "slug",
125
+ value: slug
126
+ }]),
127
+ async updateProduct(id, update) {
128
+ await adapter.update({
129
+ model: "flutterwaveProduct",
130
+ update,
131
+ where: [{
132
+ field: "id",
133
+ value: id
134
+ }]
135
+ });
136
+ },
137
+ async upsertProductBySlug(slug, data) {
138
+ const existing = await this.findProductBySlug(slug);
139
+ if (existing?.id !== void 0) {
140
+ const { createdAt: _createdAt, ...update } = data;
141
+ await this.updateProduct(existing.id, update);
142
+ } else await adapter.create({
143
+ model: "flutterwaveProduct",
144
+ data: {
145
+ ...data,
146
+ slug
147
+ }
148
+ });
149
+ },
150
+ listPlans: () => findMany("flutterwavePlan"),
151
+ findPlanByName: (name) => findOne("flutterwavePlan", [{
152
+ field: "name",
153
+ value: name
154
+ }]),
155
+ findPlanByPaymentPlanId: (paymentPlanId) => findOne("flutterwavePlan", [{
156
+ field: "paymentPlanId",
157
+ value: paymentPlanId
158
+ }]),
159
+ async upsertPlanByPaymentPlanId(paymentPlanId, data) {
160
+ const existing = await this.findPlanByPaymentPlanId(paymentPlanId);
161
+ if (existing?.id !== void 0) {
162
+ const { createdAt: _createdAt, ...update } = data;
163
+ await adapter.update({
164
+ model: "flutterwavePlan",
165
+ update,
166
+ where: [{
167
+ field: "id",
168
+ value: existing.id
169
+ }]
170
+ });
171
+ } else await adapter.create({
172
+ model: "flutterwavePlan",
173
+ data: {
174
+ ...data,
175
+ paymentPlanId
176
+ }
177
+ });
178
+ },
179
+ createWebhookEvent: (data) => adapter.create({
180
+ model: "flutterwaveWebhookEvent",
181
+ data
182
+ }),
183
+ findWebhookEvent: (eventId) => findOne("flutterwaveWebhookEvent", [{
184
+ field: "eventId",
185
+ value: eventId
186
+ }]),
187
+ updateWebhookEvent: (eventId, update) => adapter.update({
188
+ model: "flutterwaveWebhookEvent",
189
+ update,
190
+ where: [{
191
+ field: "eventId",
192
+ value: eventId
193
+ }]
194
+ }),
195
+ createRefund: (data) => adapter.create({
196
+ model: "flutterwaveRefund",
197
+ data
198
+ }),
199
+ findRefundByProviderId: (refundId) => findOne("flutterwaveRefund", [{
200
+ field: "refundId",
201
+ value: refundId
202
+ }]),
203
+ listPendingRefunds: () => findMany("flutterwaveRefund", [{
204
+ field: "status",
205
+ value: "pending"
206
+ }]),
207
+ updateRefund: (id, update) => adapter.update({
208
+ model: "flutterwaveRefund",
209
+ update,
210
+ where: [{
211
+ field: "id",
212
+ value: id
213
+ }]
214
+ }),
215
+ findUser: (id) => findOne("user", [{
216
+ field: "id",
217
+ value: id
218
+ }]),
219
+ findOrganization: (id) => findOne("organization", [{
220
+ field: "id",
221
+ value: id
222
+ }]),
223
+ findOrganizationOwner: (organizationId) => findOne("member", [{
224
+ field: "organizationId",
225
+ value: organizationId
226
+ }, {
227
+ field: "role",
228
+ value: "owner"
229
+ }]),
230
+ listMembers: (organizationId) => findMany("member", [{
231
+ field: "organizationId",
232
+ value: organizationId
233
+ }]),
234
+ listTeams: (organizationId) => findMany("team", [{
235
+ field: "organizationId",
236
+ value: organizationId
237
+ }])
238
+ };
239
+ }
240
+ //#endregion
241
+ //#region src/flutterwave-contracts.ts
242
+ const currencySchema = z.string().regex(/^[A-Z]{3}$/, "Currency must be a three-letter ISO code");
243
+ const positiveAmountSchema = z.coerce.number().positive();
244
+ const optionalDateSchema = z.string().nullable().optional();
245
+ const flutterwaveEnvelopeSchema = (data) => z.object({
246
+ status: z.string(),
247
+ message: z.string().optional(),
248
+ data
249
+ }).passthrough();
250
+ const standardCheckoutInputSchema = z.object({
251
+ tx_ref: z.string().min(1).max(100),
252
+ amount: positiveAmountSchema,
253
+ currency: currencySchema,
254
+ redirect_url: z.url(),
255
+ customer: z.object({
256
+ email: z.email(),
257
+ name: z.string().min(1).optional(),
258
+ phonenumber: z.string().min(1).optional()
259
+ }).passthrough(),
260
+ payment_options: z.string().min(1).optional(),
261
+ payment_plan: z.number().int().positive().optional(),
262
+ subaccounts: z.array(z.object({
263
+ id: z.string().min(1),
264
+ transaction_charge_type: z.enum(["flat", "percentage"]).optional(),
265
+ transaction_charge: z.number().nonnegative().optional()
266
+ }).passthrough()).min(1).optional(),
267
+ customizations: z.object({
268
+ title: z.string().optional(),
269
+ description: z.string().optional(),
270
+ logo: z.url().optional()
271
+ }).optional(),
272
+ meta: z.record(z.string(), z.unknown()).optional()
273
+ }).passthrough();
274
+ const checkoutDataSchema = z.object({ link: z.url() }).passthrough();
275
+ const transactionSchema = z.object({
276
+ id: z.coerce.number().int().positive(),
277
+ tx_ref: z.string().min(1),
278
+ flw_ref: z.string().nullable().optional(),
279
+ amount: positiveAmountSchema,
280
+ charged_amount: z.coerce.number().nonnegative().optional(),
281
+ currency: currencySchema,
282
+ status: z.string().min(1),
283
+ payment_type: z.string().nullable().optional(),
284
+ created_at: optionalDateSchema,
285
+ customer: z.object({
286
+ id: z.coerce.number().int().optional(),
287
+ email: z.email(),
288
+ name: z.string().nullable().optional()
289
+ }).passthrough().optional(),
290
+ card: z.object({ token: z.string().min(1).optional() }).passthrough().nullable().optional()
291
+ }).passthrough();
292
+ const paymentPlanSchema = z.object({
293
+ id: z.coerce.number().int().positive(),
294
+ name: z.string().min(1),
295
+ amount: positiveAmountSchema.nullable().optional().transform((value) => value ?? void 0),
296
+ interval: z.string().min(1),
297
+ currency: currencySchema,
298
+ status: z.string().optional(),
299
+ duration: z.coerce.number().int().nonnegative().optional(),
300
+ created_at: optionalDateSchema
301
+ }).passthrough();
302
+ const subscriptionSchema = z.object({
303
+ id: z.coerce.number().int().positive(),
304
+ amount: positiveAmountSchema,
305
+ customer: z.object({
306
+ email: z.email().optional(),
307
+ customer_email: z.email().optional()
308
+ }).passthrough().optional(),
309
+ plan: z.coerce.number().int().positive().optional(),
310
+ status: z.string().min(1),
311
+ currency: currencySchema.optional(),
312
+ created_at: optionalDateSchema
313
+ }).passthrough();
314
+ const tokenChargeInputSchema = z.object({
315
+ token: z.string().min(1),
316
+ currency: currencySchema,
317
+ country: z.string().length(2).toUpperCase().optional(),
318
+ amount: positiveAmountSchema,
319
+ email: z.email(),
320
+ tx_ref: z.string().min(1).max(100),
321
+ narration: z.string().optional()
322
+ }).passthrough();
323
+ const refundSchema = z.object({
324
+ id: z.coerce.number().int().positive().optional(),
325
+ transaction_id: z.coerce.number().int().positive().optional(),
326
+ amount_refunded: z.coerce.number().nonnegative().optional(),
327
+ amount: z.coerce.number().nonnegative().optional(),
328
+ status: z.string().min(1),
329
+ created_at: optionalDateSchema
330
+ }).passthrough();
331
+ //#endregion
332
+ //#region src/flutterwave-sdk.ts
333
+ var FlutterwaveAdapterError = class extends Error {
334
+ operation;
335
+ status;
336
+ cause;
337
+ constructor(operation, message, options) {
338
+ super(message);
339
+ this.name = "FlutterwaveAdapterError";
340
+ this.operation = operation;
341
+ this.status = options?.status;
342
+ this.cause = options?.cause;
343
+ }
344
+ };
345
+ const require = createRequire(import.meta.url);
346
+ function createSdkClient(publicKey, secretKey) {
347
+ return new (require("flutterwave-node-v3"))(publicKey, secretKey);
348
+ }
349
+ function messageFromUnknown(value) {
350
+ if (typeof value === "string") return value;
351
+ if (typeof value !== "object" || value === null) return void 0;
352
+ const message = Reflect.get(value, "message");
353
+ return typeof message === "string" ? message : void 0;
354
+ }
355
+ function parseEnvelope(operation, raw, dataSchema) {
356
+ const envelope = flutterwaveEnvelopeSchema(dataSchema).safeParse(raw);
357
+ if (!envelope.success) throw new FlutterwaveAdapterError(operation, "Flutterwave returned an invalid response", { cause: envelope.error });
358
+ if (envelope.data.status.toLowerCase() !== "success") throw new FlutterwaveAdapterError(operation, envelope.data.message ?? "Flutterwave rejected the request");
359
+ return envelope.data.data;
360
+ }
361
+ async function sdkCall(operation, action, schema) {
362
+ try {
363
+ return parseEnvelope(operation, await action(), schema);
364
+ } catch (error) {
365
+ if (error instanceof FlutterwaveAdapterError) throw error;
366
+ throw new FlutterwaveAdapterError(operation, messageFromUnknown(error) ?? `Flutterwave ${operation} failed`, { cause: error });
367
+ }
368
+ }
369
+ const positiveIdSchema = z.number().int().positive();
370
+ const optionalPositiveAmountSchema = z.number().positive().optional();
371
+ /**
372
+ * Creates the provider boundary used by the plugin.
373
+ *
374
+ * `flutterwave-node-v3` performs always-on telemetry and writes telemetry state in
375
+ * the operating-system temporary directory. Inject `flutterwaveClient` in tests,
376
+ * serverless environments that prohibit those writes, or when custom transport is
377
+ * required. This adapter intentionally uses only the SDK's Promise API.
378
+ */
379
+ function createFlutterwaveAdapter(options) {
380
+ if (!options.publicKey) throw new FlutterwaveAdapterError("configuration", "publicKey is required");
381
+ if (!options.secretKey) throw new FlutterwaveAdapterError("configuration", "secretKey is required");
382
+ const client = options.flutterwaveClient ?? createSdkClient(options.publicKey, options.secretKey);
383
+ const fetchImpl = options.fetch ?? globalThis.fetch;
384
+ const apiBaseUrl = (options.apiBaseUrl ?? "https://api.flutterwave.com").replace(/\/+$/, "");
385
+ return {
386
+ async initializePayment(input) {
387
+ const body = standardCheckoutInputSchema.parse(input);
388
+ if (typeof fetchImpl !== "function") throw new FlutterwaveAdapterError("initialize payment", "Fetch is not available");
389
+ let response;
390
+ try {
391
+ response = await fetchImpl(`${apiBaseUrl}/v3/payments`, {
392
+ method: "POST",
393
+ headers: {
394
+ authorization: `Bearer ${options.secretKey}`,
395
+ "content-type": "application/json"
396
+ },
397
+ body: JSON.stringify(body)
398
+ });
399
+ } catch (error) {
400
+ throw new FlutterwaveAdapterError("initialize payment", messageFromUnknown(error) ?? "Flutterwave checkout request failed", { cause: error });
401
+ }
402
+ let raw;
403
+ try {
404
+ raw = await response.json();
405
+ } catch (error) {
406
+ throw new FlutterwaveAdapterError("initialize payment", "Flutterwave returned a non-JSON response", {
407
+ status: response.status,
408
+ cause: error
409
+ });
410
+ }
411
+ if (!response.ok) throw new FlutterwaveAdapterError("initialize payment", messageFromUnknown(raw) ?? `Flutterwave checkout failed with HTTP ${response.status}`, { status: response.status });
412
+ return parseEnvelope("initialize payment", raw, checkoutDataSchema);
413
+ },
414
+ async verifyTransaction(input) {
415
+ if (input.transactionId === void 0 === (input.txRef === void 0)) throw new FlutterwaveAdapterError("verify transaction", "Provide exactly one of transactionId or txRef");
416
+ return input.transactionId !== void 0 ? sdkCall("verify transaction", () => client.Transaction.verify({ id: positiveIdSchema.parse(input.transactionId) }), transactionSchema) : sdkCall("verify transaction", () => client.Transaction.verify_by_tx({ tx_ref: z.string().min(1).parse(input.txRef) }), transactionSchema);
417
+ },
418
+ listPaymentPlans: () => sdkCall("list payment plans", () => client.PaymentPlan.get_all({}), z.array(paymentPlanSchema)),
419
+ listSubscriptions: (input = {}) => {
420
+ const query = {
421
+ email: input.email,
422
+ status: input.status,
423
+ ...input.plan === void 0 ? {} : { plan: String(input.plan) },
424
+ ...input.transactionId === void 0 ? {} : { transaction_id: String(input.transactionId) },
425
+ ...input.page === void 0 ? {} : { page: String(input.page) }
426
+ };
427
+ return sdkCall("list subscriptions", () => client.Subscription.fetch_all(query), z.array(subscriptionSchema));
428
+ },
429
+ cancelSubscription: (subscriptionId) => sdkCall("cancel subscription", () => client.Subscription.cancel({ id: positiveIdSchema.parse(subscriptionId) }), subscriptionSchema),
430
+ activateSubscription: (subscriptionId) => sdkCall("activate subscription", () => client.Subscription.activate({ id: positiveIdSchema.parse(subscriptionId) }), subscriptionSchema),
431
+ chargeToken: (input) => {
432
+ const body = tokenChargeInputSchema.parse(input);
433
+ return sdkCall("charge token", () => client.Tokenized.charge(body), transactionSchema);
434
+ },
435
+ refundTransaction: (transactionId, amount) => sdkCall("refund transaction", () => client.Transaction.refund({
436
+ id: positiveIdSchema.parse(transactionId),
437
+ amount: optionalPositiveAmountSchema.parse(amount)
438
+ }), refundSchema)
439
+ };
440
+ }
441
+ //#endregion
442
+ //#region src/reference-access.ts
443
+ const DEFAULT_BILLING_ORG_ROLES = ["owner", "admin"];
444
+ function normalizeBillingRoles(roles) {
445
+ return new Set(roles.map((value) => value.trim()).filter((value) => value !== ""));
446
+ }
447
+ function getBillingRoles(options) {
448
+ return options.organization?.billingRoles ?? DEFAULT_BILLING_ORG_ROLES;
449
+ }
450
+ function hasBillingRole(role, billingRoles = DEFAULT_BILLING_ORG_ROLES) {
451
+ const allowedRoles = normalizeBillingRoles(billingRoles);
452
+ if (Array.isArray(role)) return role.some((value) => hasBillingRole(value, billingRoles));
453
+ if (typeof role !== "string") return false;
454
+ return role.split(",").map((value) => value.trim()).some((value) => allowedRoles.has(value));
455
+ }
456
+ function resolveBillingReferenceId(input) {
457
+ const body = input.body ?? {};
458
+ const query = input.query ?? {};
459
+ const requestQueryReferenceId = typeof input.requestUrl === "string" ? new URL(input.requestUrl).searchParams.get("referenceId") ?? void 0 : void 0;
460
+ return body.referenceId ?? query.referenceId ?? requestQueryReferenceId ?? input.fallbackUserId;
461
+ }
462
+ async function authorizeBillingReference(ctx, options, data) {
463
+ if (data.referenceId === data.user.id) return;
464
+ if (options.subscription?.enabled === true && typeof options.subscription.authorizeReference === "function") {
465
+ if (await options.subscription.authorizeReference({
466
+ user: data.user,
467
+ session: data.session,
468
+ referenceId: data.referenceId,
469
+ action: data.action
470
+ }, ctx) === true) return;
471
+ throw new APIError("UNAUTHORIZED");
472
+ }
473
+ if (options.organization?.enabled === true) {
474
+ const member = await ctx.context.adapter.findOne({
475
+ model: "member",
476
+ where: [{
477
+ field: "userId",
478
+ value: data.user.id
479
+ }, {
480
+ field: "organizationId",
481
+ value: data.referenceId
482
+ }]
483
+ });
484
+ if (member !== null && member !== void 0 && hasBillingRole(member.role, getBillingRoles(options))) return;
485
+ }
486
+ throw new APIError("UNAUTHORIZED");
487
+ }
488
+ //#endregion
489
+ //#region src/route-modules/webhook.ts
490
+ function getWebhookRequest(ctx) {
491
+ return ctx.requestClone ?? ctx.request;
492
+ }
493
+ function getWebhookHeaders(ctx) {
494
+ return ctx.headers ?? ctx.request?.headers;
495
+ }
496
+ //#endregion
497
+ //#region src/route-modules/shared.ts
498
+ const FLUTTERWAVE_ERROR_CODES = defineErrorCodes({
499
+ SUBSCRIPTION_NOT_FOUND: "Subscription not found",
500
+ SUBSCRIPTION_PLAN_NOT_FOUND: "Subscription plan not found",
501
+ FAILED_TO_INITIALIZE_TRANSACTION: "Failed to initialize transaction",
502
+ FAILED_TO_VERIFY_TRANSACTION: "Failed to verify transaction",
503
+ FAILED_TO_DISABLE_SUBSCRIPTION: "Failed to disable subscription",
504
+ FAILED_TO_ENABLE_SUBSCRIPTION: "Failed to enable subscription",
505
+ EMAIL_VERIFICATION_REQUIRED: "Email verification is required before you can subscribe to a plan",
506
+ SUBSCRIPTION_PAYMENT_CHANNEL_NOT_ALLOWED: "This subscription only supports specific payment channels"
507
+ });
508
+ async function hmacSha256Base64(secret, message) {
509
+ const encoder = new TextEncoder();
510
+ const keyData = encoder.encode(secret);
511
+ const msgData = encoder.encode(message);
512
+ const crypto = globalThis.crypto;
513
+ if (crypto !== void 0 && crypto !== null && "subtle" in crypto) {
514
+ const subtle = crypto.subtle;
515
+ const key = await subtle.importKey("raw", keyData, {
516
+ name: "HMAC",
517
+ hash: "SHA-256"
518
+ }, false, ["sign"]);
519
+ const signature = await subtle.sign("HMAC", key, msgData);
520
+ return Buffer.from(signature).toString("base64");
521
+ }
522
+ const { createHmac } = await import("node:crypto");
523
+ return createHmac("sha256", secret).update(message).digest("base64");
524
+ }
525
+ function timingSafeEqualString(left, right) {
526
+ const leftBytes = Buffer.from(left);
527
+ const rightBytes = Buffer.from(right);
528
+ if (leftBytes.length !== rightBytes.length) return false;
529
+ return timingSafeEqual(leftBytes, rightBytes);
530
+ }
531
+ //#endregion
532
+ //#region src/token-crypto.ts
533
+ const encoder = new TextEncoder();
534
+ const decoder = new TextDecoder();
535
+ function toBase64(value) {
536
+ return Buffer.from(value).toString("base64url");
537
+ }
538
+ function fromBase64(value) {
539
+ return new Uint8Array(Buffer.from(value, "base64url"));
540
+ }
541
+ async function deriveKey(secret) {
542
+ const digest = await crypto.subtle.digest("SHA-256", encoder.encode(secret));
543
+ return crypto.subtle.importKey("raw", digest, "AES-GCM", false, ["encrypt", "decrypt"]);
544
+ }
545
+ async function encryptPaymentToken(token, secret) {
546
+ const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
547
+ const encrypted = await crypto.subtle.encrypt({
548
+ name: "AES-GCM",
549
+ iv
550
+ }, await deriveKey(secret), encoder.encode(token));
551
+ return `v1.${toBase64(iv)}.${toBase64(new Uint8Array(encrypted))}`;
552
+ }
553
+ async function decryptPaymentToken(value, secret) {
554
+ const [version, encodedIv, encodedCiphertext] = value.split(".");
555
+ if (version !== "v1" || !encodedIv || !encodedCiphertext) throw new Error("Unsupported encrypted payment token");
556
+ const iv = Uint8Array.from(fromBase64(encodedIv));
557
+ const ciphertext = Uint8Array.from(fromBase64(encodedCiphertext));
558
+ const decrypted = await crypto.subtle.decrypt({
559
+ name: "AES-GCM",
560
+ iv
561
+ }, await deriveKey(secret), ciphertext);
562
+ return decoder.decode(decrypted);
563
+ }
564
+ //#endregion
565
+ //#region src/utils.ts
566
+ function normalizeSubscriptionGroup(group) {
567
+ const normalized = group?.trim().toLowerCase();
568
+ return normalized === void 0 || normalized === "" ? null : normalized;
569
+ }
570
+ async function getPlans(subscriptionOptions) {
571
+ if (subscriptionOptions?.enabled === true) return typeof subscriptionOptions.plans === "function" ? subscriptionOptions.plans() : subscriptionOptions.plans;
572
+ throw new Error("Subscriptions are not enabled in the Flutterwave options.");
573
+ }
574
+ async function getPlanByName(options, name) {
575
+ if (typeof name !== "string" || name.trim() === "") return null;
576
+ if (options.subscription?.enabled === true) {
577
+ const plans = await getPlans(options.subscription);
578
+ const normalizedName = name.toLowerCase();
579
+ return plans.find((plan) => typeof plan.name === "string" && plan.name.toLowerCase() === normalizedName) ?? null;
580
+ }
581
+ return null;
582
+ }
583
+ //#endregion
584
+ //#region src/routes.ts
585
+ const subaccountSchema = z.object({
586
+ id: z.string().min(1),
587
+ transactionSplitRatio: z.number().positive().optional(),
588
+ transactionChargeType: z.enum([
589
+ "flat",
590
+ "percentage",
591
+ "flat_subaccount"
592
+ ]).optional(),
593
+ transactionCharge: z.number().nonnegative().optional()
594
+ });
595
+ const initializeBodySchema = z.object({
596
+ amount: z.number().positive().optional(),
597
+ currency: z.string().length(3).transform((value) => value.toUpperCase()).optional(),
598
+ redirectUrl: z.string().url(),
599
+ txRef: z.string().min(1).max(100).optional(),
600
+ referenceId: z.string().optional(),
601
+ plan: z.string().optional(),
602
+ product: z.string().optional(),
603
+ quantity: z.number().int().positive().default(1),
604
+ metadata: z.record(z.string(), z.unknown()).optional(),
605
+ paymentOptions: z.string().optional(),
606
+ subaccounts: z.array(subaccountSchema).optional()
607
+ });
608
+ const verifyBodySchema = z.object({
609
+ transactionId: z.union([z.string(), z.number()]).optional(),
610
+ txRef: z.string().optional(),
611
+ referenceId: z.string().optional()
612
+ }).refine((body) => body.transactionId === void 0 !== (body.txRef === void 0), { message: "Provide exactly one of transactionId or txRef" });
613
+ const webhookPayloadSchema = z.object({
614
+ event: z.string().min(1),
615
+ data: z.object({
616
+ id: z.union([z.string(), z.number()]).optional(),
617
+ tx_ref: z.string().optional(),
618
+ flw_ref: z.string().optional(),
619
+ status: z.string().optional(),
620
+ amount: z.coerce.number().optional(),
621
+ charged_amount: z.coerce.number().optional(),
622
+ currency: z.string().optional(),
623
+ payment_type: z.string().optional(),
624
+ customer: z.object({ email: z.string().optional() }).passthrough().optional()
625
+ }).passthrough()
626
+ });
627
+ function adapter$1(options) {
628
+ return createFlutterwaveAdapter({
629
+ publicKey: options.publicKey,
630
+ secretKey: options.secretKey,
631
+ flutterwaveClient: options.flutterwaveClient,
632
+ fetch: options.fetch,
633
+ apiBaseUrl: options.apiBaseUrl
634
+ });
635
+ }
636
+ function mapTransaction(data) {
637
+ return {
638
+ id: data.id,
639
+ txRef: data.tx_ref,
640
+ flwRef: data.flw_ref ?? void 0,
641
+ status: data.status,
642
+ amount: data.amount,
643
+ chargedAmount: data.charged_amount,
644
+ currency: data.currency,
645
+ paymentType: data.payment_type ?? void 0,
646
+ customer: data.customer ? {
647
+ email: data.customer.email,
648
+ name: data.customer.name ?? void 0
649
+ } : void 0
650
+ };
651
+ }
652
+ async function authenticatedReference(ctx, options, action, requested) {
653
+ const current = await getSessionFromCtx(ctx);
654
+ if (!current) throw new APIError("UNAUTHORIZED");
655
+ const referenceId = requested ?? current.user.id;
656
+ await authorizeBillingReference(ctx, options, {
657
+ user: current.user,
658
+ session: current.session,
659
+ referenceId,
660
+ action
661
+ });
662
+ return {
663
+ user: current.user,
664
+ session: current.session,
665
+ referenceId
666
+ };
667
+ }
668
+ async function resolveBillingEmail(ctx, options, referenceId, user) {
669
+ if (referenceId === user.id) return user.email;
670
+ if (options.organization?.enabled !== true) throw new APIError("UNAUTHORIZED");
671
+ const store = createBillingStore(ctx);
672
+ const explicit = (await store.findOrganization(referenceId))?.email;
673
+ if (explicit) return explicit;
674
+ const owner = await store.findOrganizationOwner(referenceId);
675
+ const ownerUser = owner ? await store.findUser(owner.userId) : null;
676
+ if (!ownerUser?.email) throw new APIError("BAD_REQUEST", { message: "Billing email not found" });
677
+ return ownerUser.email;
678
+ }
679
+ async function configuredProducts(options) {
680
+ const source = options.products?.products;
681
+ if (!source) return [];
682
+ return typeof source === "function" ? source() : source;
683
+ }
684
+ const initializeTransaction = (options, path) => createAuthEndpoint(path, {
685
+ method: "POST",
686
+ body: initializeBodySchema,
687
+ use: [sessionMiddleware, originCheck]
688
+ }, async (ctx) => {
689
+ const { user, referenceId } = await authenticatedReference(ctx, options, "initialize-transaction", ctx.body.referenceId);
690
+ if (options.subscription?.requireEmailVerification === true && ctx.body.plan && user.emailVerified !== true) throw new APIError("BAD_REQUEST", FLUTTERWAVE_ERROR_CODES.EMAIL_VERIFICATION_REQUIRED);
691
+ const billingEmail = await resolveBillingEmail(ctx, options, referenceId, user);
692
+ const plans = await getPlans(options.subscription);
693
+ const plan = ctx.body.plan ? plans.find((candidate) => candidate.name.toLowerCase() === ctx.body.plan?.toLowerCase()) : void 0;
694
+ if (ctx.body.plan && !plan) throw new APIError("NOT_FOUND", { message: "Plan not found" });
695
+ const products = await configuredProducts(options);
696
+ const product = ctx.body.product ? products.find((candidate) => candidate.name.toLowerCase() === ctx.body.product?.toLowerCase() || candidate.slug === ctx.body.product) : void 0;
697
+ if (ctx.body.product && !product) throw new APIError("NOT_FOUND", { message: "Product not found" });
698
+ const amount = ctx.body.amount ?? (plan?.amount !== void 0 ? plan.amount + (plan.seatAmount ?? 0) * Math.max(0, ctx.body.quantity - 1) : product ? product.price * ctx.body.quantity : void 0);
699
+ const currency = ctx.body.currency ?? plan?.currency ?? product?.currency;
700
+ if (!amount || !currency) throw new APIError("BAD_REQUEST", { message: "amount and currency are required" });
701
+ const requestedSplits = ctx.body.subaccounts ?? options.marketplace?.defaultSplit;
702
+ const allowed = new Set(options.marketplace?.allowedSubaccountIds ?? []);
703
+ if (requestedSplits?.some(({ id }) => !allowed.has(id))) throw new APIError("FORBIDDEN", { message: "Subaccount is not allowlisted" });
704
+ const txRef = ctx.body.txRef ?? `flw_${crypto.randomUUID()}`;
705
+ const groupId = normalizeSubscriptionGroup(plan?.group);
706
+ const metadata = createCheckoutMetadata({
707
+ referenceId,
708
+ userId: user.id,
709
+ plan: plan?.name,
710
+ groupId,
711
+ product: product?.name,
712
+ extra: ctx.body.metadata,
713
+ trial: {
714
+ isTrial: false,
715
+ requested: false,
716
+ granted: false
717
+ }
718
+ });
719
+ const result = await adapter$1(options).initializePayment({
720
+ tx_ref: txRef,
721
+ amount,
722
+ currency,
723
+ redirect_url: ctx.body.redirectUrl,
724
+ customer: {
725
+ email: billingEmail,
726
+ name: user.name
727
+ },
728
+ payment_options: plan?.paymentPlanId ? "card" : ctx.body.paymentOptions,
729
+ payment_plan: plan?.paymentPlanId,
730
+ subaccounts: requestedSplits?.map((split) => ({
731
+ id: split.id,
732
+ transaction_charge_type: split.transactionChargeType === "flat_subaccount" ? "flat" : split.transactionChargeType,
733
+ transaction_charge: split.transactionCharge,
734
+ transaction_split_ratio: split.transactionSplitRatio
735
+ })),
736
+ meta: metadata
737
+ });
738
+ const store = createBillingStore(ctx);
739
+ const now = /* @__PURE__ */ new Date();
740
+ await store.createTransaction({
741
+ txRef,
742
+ referenceId,
743
+ userId: user.id,
744
+ amount,
745
+ currency,
746
+ status: "pending",
747
+ plan: plan?.name,
748
+ product: product?.name,
749
+ subaccountId: requestedSplits?.[0]?.id,
750
+ metadata: stringifyFlutterwaveMetadata(metadata),
751
+ createdAt: now,
752
+ updatedAt: now
753
+ });
754
+ if (plan) await store.createSubscription({
755
+ userId: user.id,
756
+ referenceId,
757
+ plan: plan.name,
758
+ paymentPlanId: plan.paymentPlanId,
759
+ txRef,
760
+ billingEmail,
761
+ status: "incomplete",
762
+ seats: ctx.body.quantity,
763
+ groupId,
764
+ cancelAtPeriodEnd: false,
765
+ billingInterval: plan.interval,
766
+ createdAt: now,
767
+ updatedAt: now
768
+ });
769
+ return {
770
+ kind: "checkout",
771
+ url: result.link,
772
+ txRef,
773
+ redirect: true
774
+ };
775
+ });
776
+ const verifyTransaction = (options, path) => createAuthEndpoint(path, {
777
+ method: "POST",
778
+ body: verifyBodySchema,
779
+ use: [sessionMiddleware, originCheck]
780
+ }, async (ctx) => {
781
+ const store = createBillingStore(ctx);
782
+ const expected = ctx.body.txRef ? await store.findTransactionByTxRef(ctx.body.txRef) : await store.findTransactionById(Number(ctx.body.transactionId));
783
+ if (!expected) throw new APIError("NOT_FOUND", { message: "Transaction not found" });
784
+ if (ctx.body.referenceId !== void 0 && ctx.body.referenceId !== expected.referenceId) throw new APIError("UNAUTHORIZED");
785
+ await authenticatedReference(ctx, options, "verify-transaction", expected.referenceId);
786
+ const verified = await adapter$1(options).verifyTransaction({
787
+ transactionId: ctx.body.transactionId === void 0 ? void 0 : Number(ctx.body.transactionId),
788
+ txRef: ctx.body.txRef
789
+ });
790
+ if (verified.tx_ref !== expected.txRef || verified.amount !== expected.amount || verified.currency !== expected.currency || verified.status !== "successful") throw new APIError("BAD_REQUEST", { message: "Verified transaction does not match the expected payment" });
791
+ const now = /* @__PURE__ */ new Date();
792
+ await store.updateTransactionByTxRef(expected.txRef, {
793
+ transactionId: verified.id,
794
+ flwRef: verified.flw_ref,
795
+ chargedAmount: verified.charged_amount,
796
+ paymentType: verified.payment_type,
797
+ status: verified.status,
798
+ verifiedAt: now,
799
+ reconciledAt: now,
800
+ updatedAt: now
801
+ });
802
+ const linked = await store.findSubscriptionsByTxRef(expected.txRef);
803
+ for (const subscription of linked) {
804
+ let subscriptionId = subscription.subscriptionId;
805
+ if (subscription.paymentPlanId && subscription.billingEmail) {
806
+ const matches = (await adapter$1(options).listSubscriptions({
807
+ email: subscription.billingEmail,
808
+ plan: subscription.paymentPlanId,
809
+ transactionId: verified.id
810
+ })).filter((candidate) => candidate.status !== "cancelled");
811
+ subscriptionId = matches.length === 1 ? matches[0]?.id : void 0;
812
+ }
813
+ await store.updateSubscription(subscription.id, {
814
+ subscriptionId,
815
+ status: subscription.paymentPlanId !== void 0 && subscription.paymentPlanId !== null && subscriptionId === void 0 ? "incomplete" : "active",
816
+ encryptedPaymentToken: verified.card?.token ? await encryptPaymentToken(verified.card.token, ctx.context.secret) : subscription.encryptedPaymentToken,
817
+ periodStart: now,
818
+ reconciledAt: now,
819
+ updatedAt: now
820
+ });
821
+ await store.retireCompetingSubscriptions(subscription.referenceId, subscription.groupId ?? null, subscription.id);
822
+ }
823
+ return {
824
+ status: verified.status,
825
+ txRef: verified.tx_ref,
826
+ data: mapTransaction(verified)
827
+ };
828
+ });
829
+ const referenceQuerySchema = z.object({ referenceId: z.string().optional() });
830
+ const listTransactions = (options, path) => createAuthEndpoint(path, {
831
+ method: "GET",
832
+ query: referenceQuerySchema,
833
+ use: [sessionMiddleware]
834
+ }, async (ctx) => {
835
+ const current = await getSessionFromCtx(ctx);
836
+ if (!current) throw new APIError("UNAUTHORIZED");
837
+ const referenceId = resolveBillingReferenceId({
838
+ query: ctx.query,
839
+ requestUrl: ctx.request?.url,
840
+ fallbackUserId: current.user.id
841
+ });
842
+ await authenticatedReference(ctx, options, "list-transactions", referenceId);
843
+ return { transactions: await createBillingStore(ctx).listTransactions(referenceId) };
844
+ });
845
+ const listSubscriptions = (options, path) => createAuthEndpoint(path, {
846
+ method: "GET",
847
+ query: referenceQuerySchema,
848
+ use: [sessionMiddleware]
849
+ }, async (ctx) => {
850
+ const current = await getSessionFromCtx(ctx);
851
+ if (!current) throw new APIError("UNAUTHORIZED");
852
+ const referenceId = resolveBillingReferenceId({
853
+ query: ctx.query,
854
+ requestUrl: ctx.request?.url,
855
+ fallbackUserId: current.user.id
856
+ });
857
+ await authenticatedReference(ctx, options, "list-subscriptions", referenceId);
858
+ return { subscriptions: await createBillingStore(ctx).findSubscriptionsByReference(referenceId) };
859
+ });
860
+ const subscriptionBodySchema = z.object({
861
+ subscriptionId: z.coerce.number().int().positive(),
862
+ atPeriodEnd: z.boolean().optional()
863
+ });
864
+ const cancelSubscription = (options, path) => createAuthEndpoint(path, {
865
+ method: "POST",
866
+ body: subscriptionBodySchema,
867
+ use: [sessionMiddleware, originCheck]
868
+ }, async (ctx) => {
869
+ const store = createBillingStore(ctx);
870
+ const local = await store.findSubscriptionByProviderId(ctx.body.subscriptionId);
871
+ if (!local) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
872
+ await authenticatedReference(ctx, options, "disable-subscription", local.referenceId);
873
+ const now = /* @__PURE__ */ new Date();
874
+ if (ctx.body.atPeriodEnd === true || options.subscription?.cancelBehavior === "at_period_end") {
875
+ await store.updateSubscription(local.id, {
876
+ cancelAtPeriodEnd: true,
877
+ cancelAt: local.periodEnd ?? now,
878
+ updatedAt: now
879
+ });
880
+ return { status: "scheduled" };
881
+ }
882
+ await adapter$1(options).cancelSubscription(ctx.body.subscriptionId);
883
+ await store.updateSubscription(local.id, {
884
+ status: "canceled",
885
+ cancelAtPeriodEnd: false,
886
+ canceledAt: now,
887
+ endedAt: now,
888
+ updatedAt: now
889
+ });
890
+ return { status: "canceled" };
891
+ });
892
+ const restoreSubscription = (options, path) => createAuthEndpoint(path, {
893
+ method: "POST",
894
+ body: subscriptionBodySchema.omit({ atPeriodEnd: true }),
895
+ use: [sessionMiddleware, originCheck]
896
+ }, async (ctx) => {
897
+ const store = createBillingStore(ctx);
898
+ const local = await store.findSubscriptionByProviderId(ctx.body.subscriptionId);
899
+ if (!local) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
900
+ await authenticatedReference(ctx, options, "enable-subscription", local.referenceId);
901
+ await adapter$1(options).activateSubscription(ctx.body.subscriptionId);
902
+ await store.updateSubscription(local.id, {
903
+ status: "active",
904
+ cancelAtPeriodEnd: false,
905
+ cancelAt: null,
906
+ canceledAt: null,
907
+ endedAt: null,
908
+ updatedAt: /* @__PURE__ */ new Date()
909
+ });
910
+ return { status: "active" };
911
+ });
912
+ const createSubscription = initializeTransaction;
913
+ const upgradeSubscription = initializeTransaction;
914
+ const listProducts = (options, path) => createAuthEndpoint(path, { method: "GET" }, async (ctx) => {
915
+ const configured = await configuredProducts(options);
916
+ const stored = await createBillingStore(ctx).listProducts();
917
+ return { products: stored.length > 0 ? stored : configured };
918
+ });
919
+ const listPlans = (options, path) => createAuthEndpoint(path, { method: "GET" }, async (ctx) => {
920
+ const configured = await getPlans(options.subscription);
921
+ const stored = await createBillingStore(ctx).listPlans();
922
+ return { plans: stored.length > 0 ? stored : configured };
923
+ });
924
+ const getConfig = (options, path) => createAuthEndpoint(path, { method: "GET" }, async (ctx) => ({
925
+ plans: (await createBillingStore(ctx).listPlans()).concat(await getPlans(options.subscription)),
926
+ products: await configuredProducts(options),
927
+ subscriptions: options.subscription?.enabled === true,
928
+ marketplace: options.marketplace !== void 0
929
+ }));
930
+ const flutterwaveWebhook = (options, path) => createAuthEndpoint(path, {
931
+ method: "POST",
932
+ metadata: {
933
+ ...HIDE_METADATA,
934
+ openapi: { operationId: "flutterwaveWebhook" }
935
+ },
936
+ cloneRequest: true,
937
+ disableBody: true
938
+ }, async (ctx) => {
939
+ const request = getWebhookRequest(ctx);
940
+ if (!request) throw new APIError("BAD_REQUEST", { message: "Request is missing" });
941
+ const rawBody = await request.text();
942
+ const signature = getWebhookHeaders(ctx)?.get("flutterwave-signature");
943
+ if (!signature) throw new APIError("UNAUTHORIZED", { message: "Missing signature" });
944
+ if (!timingSafeEqualString(signature, await hmacSha256Base64(options.webhook?.secretHash ?? options.secretHash, rawBody))) throw new APIError("UNAUTHORIZED", { message: "Invalid signature" });
945
+ let webhookJson;
946
+ try {
947
+ webhookJson = JSON.parse(rawBody);
948
+ } catch {
949
+ ctx.context.logger.warn("Ignoring non-JSON signed Flutterwave webhook");
950
+ return ctx.json({ received: true });
951
+ }
952
+ const parsedEvent = webhookPayloadSchema.safeParse(webhookJson);
953
+ if (!parsedEvent.success) {
954
+ ctx.context.logger.warn("Ignoring malformed signed Flutterwave webhook");
955
+ return ctx.json({ received: true });
956
+ }
957
+ const event = parsedEvent.data;
958
+ const data = event.data;
959
+ const eventId = createHash("sha256").update(`${event.event}:${String(data.id ?? "")}:${String(data.status ?? "")}`).digest("hex");
960
+ const store = createBillingStore(ctx);
961
+ const existingEvent = await store.findWebhookEvent(eventId);
962
+ if (existingEvent?.status === "processed") return ctx.json({ received: true });
963
+ const now = /* @__PURE__ */ new Date();
964
+ if (existingEvent === null) try {
965
+ await store.createWebhookEvent({
966
+ eventId,
967
+ eventType: event.event,
968
+ transactionId: data.id === void 0 ? void 0 : Number(data.id),
969
+ txRef: data.tx_ref,
970
+ payload: rawBody,
971
+ status: "processing",
972
+ createdAt: now,
973
+ updatedAt: now
974
+ });
975
+ } catch (error) {
976
+ const concurrent = await store.findWebhookEvent(eventId);
977
+ if (concurrent === null) throw error;
978
+ if (concurrent.status === "processed" || concurrent.status === "processing") return ctx.json({ received: true });
979
+ }
980
+ else await store.updateWebhookEvent(eventId, {
981
+ status: "processing",
982
+ updatedAt: now
983
+ });
984
+ if (data.tx_ref && data.id !== void 0) try {
985
+ const local = await store.findTransactionByTxRef(data.tx_ref);
986
+ const verified = await adapter$1(options).verifyTransaction({ transactionId: Number(data.id) });
987
+ if (local && verified.tx_ref === local.txRef && verified.amount === local.amount && verified.currency === local.currency) {
988
+ await store.updateTransactionByTxRef(local.txRef, {
989
+ transactionId: verified.id,
990
+ flwRef: verified.flw_ref,
991
+ chargedAmount: verified.charged_amount,
992
+ paymentType: verified.payment_type,
993
+ status: verified.status,
994
+ verifiedAt: now,
995
+ reconciledAt: now,
996
+ updatedAt: now
997
+ });
998
+ if (verified.status === "successful") for (const subscription of await store.findSubscriptionsByTxRef(local.txRef)) {
999
+ let subscriptionId = subscription.subscriptionId;
1000
+ if (subscription.paymentPlanId !== void 0 && subscription.paymentPlanId !== null && subscription.billingEmail !== void 0 && subscription.billingEmail !== null && subscription.billingEmail !== "") {
1001
+ const matches = (await adapter$1(options).listSubscriptions({
1002
+ email: subscription.billingEmail,
1003
+ plan: subscription.paymentPlanId,
1004
+ transactionId: verified.id
1005
+ })).filter((candidate) => candidate.status !== "cancelled");
1006
+ subscriptionId = matches.length === 1 ? matches[0]?.id : void 0;
1007
+ }
1008
+ await store.updateSubscription(subscription.id, {
1009
+ subscriptionId,
1010
+ status: subscription.paymentPlanId !== void 0 && subscription.paymentPlanId !== null && subscriptionId === void 0 ? "incomplete" : "active",
1011
+ encryptedPaymentToken: verified.card?.token !== void 0 ? await encryptPaymentToken(verified.card.token, ctx.context.secret) : subscription.encryptedPaymentToken,
1012
+ reconciledAt: now,
1013
+ updatedAt: now
1014
+ });
1015
+ await store.retireCompetingSubscriptions(subscription.referenceId, subscription.groupId ?? null, subscription.id);
1016
+ }
1017
+ }
1018
+ } catch (error) {
1019
+ ctx.context.logger.error("Flutterwave webhook reconciliation failed", error);
1020
+ await store.updateWebhookEvent(eventId, {
1021
+ status: "failed",
1022
+ updatedAt: /* @__PURE__ */ new Date()
1023
+ });
1024
+ return ctx.json({ received: true });
1025
+ }
1026
+ await store.updateWebhookEvent(eventId, {
1027
+ status: "processed",
1028
+ processedAt: /* @__PURE__ */ new Date(),
1029
+ updatedAt: /* @__PURE__ */ new Date()
1030
+ });
1031
+ await options.onEvent?.(event);
1032
+ return ctx.json({ received: true });
1033
+ });
1034
+ //#endregion
1035
+ //#region src/schema.ts
1036
+ const transactions = { flutterwaveTransaction: { fields: {
1037
+ txRef: {
1038
+ type: "string",
1039
+ required: true,
1040
+ unique: true
1041
+ },
1042
+ transactionId: {
1043
+ type: "number",
1044
+ required: false,
1045
+ unique: true
1046
+ },
1047
+ flwRef: {
1048
+ type: "string",
1049
+ required: false,
1050
+ index: true
1051
+ },
1052
+ referenceId: {
1053
+ type: "string",
1054
+ required: true,
1055
+ index: true
1056
+ },
1057
+ userId: {
1058
+ type: "string",
1059
+ required: true,
1060
+ index: true
1061
+ },
1062
+ amount: {
1063
+ type: "number",
1064
+ required: false
1065
+ },
1066
+ chargedAmount: {
1067
+ type: "number",
1068
+ required: false
1069
+ },
1070
+ currency: {
1071
+ type: "string",
1072
+ required: true
1073
+ },
1074
+ status: {
1075
+ type: "string",
1076
+ required: true,
1077
+ index: true
1078
+ },
1079
+ paymentPlanId: {
1080
+ type: "number",
1081
+ required: false,
1082
+ index: true
1083
+ },
1084
+ plan: {
1085
+ type: "string",
1086
+ required: false,
1087
+ index: true
1088
+ },
1089
+ product: {
1090
+ type: "string",
1091
+ required: false
1092
+ },
1093
+ paymentType: {
1094
+ type: "string",
1095
+ required: false
1096
+ },
1097
+ subaccountId: {
1098
+ type: "string",
1099
+ required: false,
1100
+ index: true
1101
+ },
1102
+ metadata: {
1103
+ type: "string",
1104
+ required: false
1105
+ },
1106
+ verifiedAt: {
1107
+ type: "date",
1108
+ required: false
1109
+ },
1110
+ reconciledAt: {
1111
+ type: "date",
1112
+ required: false
1113
+ },
1114
+ createdAt: {
1115
+ type: "date",
1116
+ required: true
1117
+ },
1118
+ updatedAt: {
1119
+ type: "date",
1120
+ required: true
1121
+ }
1122
+ } } };
1123
+ const subscriptions = { flutterwaveSubscription: { fields: {
1124
+ plan: {
1125
+ type: "string",
1126
+ required: true,
1127
+ index: true
1128
+ },
1129
+ referenceId: {
1130
+ type: "string",
1131
+ required: true,
1132
+ index: true
1133
+ },
1134
+ userId: {
1135
+ type: "string",
1136
+ required: true,
1137
+ index: true
1138
+ },
1139
+ billingEmail: {
1140
+ type: "string",
1141
+ required: true,
1142
+ index: true
1143
+ },
1144
+ subscriptionId: {
1145
+ type: "number",
1146
+ required: false,
1147
+ unique: true
1148
+ },
1149
+ paymentPlanId: {
1150
+ type: "number",
1151
+ required: false,
1152
+ index: true
1153
+ },
1154
+ txRef: {
1155
+ type: "string",
1156
+ required: false,
1157
+ index: true
1158
+ },
1159
+ encryptedPaymentToken: {
1160
+ type: "string",
1161
+ required: false
1162
+ },
1163
+ status: {
1164
+ type: "string",
1165
+ required: true,
1166
+ defaultValue: "incomplete",
1167
+ index: true
1168
+ },
1169
+ periodStart: {
1170
+ type: "date",
1171
+ required: false
1172
+ },
1173
+ periodEnd: {
1174
+ type: "date",
1175
+ required: false
1176
+ },
1177
+ trialStart: {
1178
+ type: "date",
1179
+ required: false
1180
+ },
1181
+ trialEnd: {
1182
+ type: "date",
1183
+ required: false
1184
+ },
1185
+ cancelAtPeriodEnd: {
1186
+ type: "boolean",
1187
+ required: false,
1188
+ defaultValue: false
1189
+ },
1190
+ cancelAt: {
1191
+ type: "date",
1192
+ required: false
1193
+ },
1194
+ canceledAt: {
1195
+ type: "date",
1196
+ required: false
1197
+ },
1198
+ endedAt: {
1199
+ type: "date",
1200
+ required: false
1201
+ },
1202
+ billingInterval: {
1203
+ type: "string",
1204
+ required: false
1205
+ },
1206
+ groupId: {
1207
+ type: "string",
1208
+ required: false,
1209
+ index: true
1210
+ },
1211
+ seats: {
1212
+ type: "number",
1213
+ required: false
1214
+ },
1215
+ pendingPlan: {
1216
+ type: "string",
1217
+ required: false
1218
+ },
1219
+ reconciledAt: {
1220
+ type: "date",
1221
+ required: false
1222
+ },
1223
+ createdAt: {
1224
+ type: "date",
1225
+ required: true
1226
+ },
1227
+ updatedAt: {
1228
+ type: "date",
1229
+ required: true
1230
+ }
1231
+ } } };
1232
+ const products = { flutterwaveProduct: { fields: {
1233
+ name: {
1234
+ type: "string",
1235
+ required: true
1236
+ },
1237
+ description: {
1238
+ type: "string",
1239
+ required: false
1240
+ },
1241
+ price: {
1242
+ type: "number",
1243
+ required: true
1244
+ },
1245
+ currency: {
1246
+ type: "string",
1247
+ required: true
1248
+ },
1249
+ quantity: {
1250
+ type: "number",
1251
+ required: false,
1252
+ defaultValue: 0
1253
+ },
1254
+ unlimited: {
1255
+ type: "boolean",
1256
+ required: false,
1257
+ defaultValue: true
1258
+ },
1259
+ slug: {
1260
+ type: "string",
1261
+ required: true,
1262
+ unique: true
1263
+ },
1264
+ metadata: {
1265
+ type: "string",
1266
+ required: false
1267
+ },
1268
+ createdAt: {
1269
+ type: "date",
1270
+ required: true
1271
+ },
1272
+ updatedAt: {
1273
+ type: "date",
1274
+ required: true
1275
+ }
1276
+ } } };
1277
+ const plans = { flutterwavePlan: { fields: {
1278
+ name: {
1279
+ type: "string",
1280
+ required: true
1281
+ },
1282
+ description: {
1283
+ type: "string",
1284
+ required: false
1285
+ },
1286
+ amount: {
1287
+ type: "number",
1288
+ required: true
1289
+ },
1290
+ currency: {
1291
+ type: "string",
1292
+ required: true
1293
+ },
1294
+ interval: {
1295
+ type: "string",
1296
+ required: true
1297
+ },
1298
+ group: {
1299
+ type: "string",
1300
+ required: false
1301
+ },
1302
+ paymentPlanId: {
1303
+ type: "number",
1304
+ required: false,
1305
+ unique: true
1306
+ },
1307
+ metadata: {
1308
+ type: "string",
1309
+ required: false
1310
+ },
1311
+ reconciledAt: {
1312
+ type: "date",
1313
+ required: false
1314
+ },
1315
+ createdAt: {
1316
+ type: "date",
1317
+ required: true
1318
+ },
1319
+ updatedAt: {
1320
+ type: "date",
1321
+ required: true
1322
+ }
1323
+ } } };
1324
+ const webhookEvents = { flutterwaveWebhookEvent: { fields: {
1325
+ eventId: {
1326
+ type: "string",
1327
+ required: true,
1328
+ unique: true
1329
+ },
1330
+ eventType: {
1331
+ type: "string",
1332
+ required: true,
1333
+ index: true
1334
+ },
1335
+ transactionId: {
1336
+ type: "number",
1337
+ required: false,
1338
+ index: true
1339
+ },
1340
+ txRef: {
1341
+ type: "string",
1342
+ required: false,
1343
+ index: true
1344
+ },
1345
+ payload: {
1346
+ type: "string",
1347
+ required: true
1348
+ },
1349
+ status: {
1350
+ type: "string",
1351
+ required: true,
1352
+ defaultValue: "pending",
1353
+ index: true
1354
+ },
1355
+ processedAt: {
1356
+ type: "date",
1357
+ required: false
1358
+ },
1359
+ createdAt: {
1360
+ type: "date",
1361
+ required: true
1362
+ },
1363
+ updatedAt: {
1364
+ type: "date",
1365
+ required: true
1366
+ }
1367
+ } } };
1368
+ const refunds = { flutterwaveRefund: { fields: {
1369
+ refundId: {
1370
+ type: "number",
1371
+ required: false,
1372
+ unique: true
1373
+ },
1374
+ transactionId: {
1375
+ type: "number",
1376
+ required: true,
1377
+ index: true
1378
+ },
1379
+ txRef: {
1380
+ type: "string",
1381
+ required: true,
1382
+ index: true
1383
+ },
1384
+ referenceId: {
1385
+ type: "string",
1386
+ required: true,
1387
+ index: true
1388
+ },
1389
+ amount: {
1390
+ type: "number",
1391
+ required: true
1392
+ },
1393
+ currency: {
1394
+ type: "string",
1395
+ required: true
1396
+ },
1397
+ status: {
1398
+ type: "string",
1399
+ required: true,
1400
+ index: true
1401
+ },
1402
+ reason: {
1403
+ type: "string",
1404
+ required: false
1405
+ },
1406
+ metadata: {
1407
+ type: "string",
1408
+ required: false
1409
+ },
1410
+ reconciledAt: {
1411
+ type: "date",
1412
+ required: false
1413
+ },
1414
+ createdAt: {
1415
+ type: "date",
1416
+ required: true
1417
+ },
1418
+ updatedAt: {
1419
+ type: "date",
1420
+ required: true
1421
+ }
1422
+ } } };
1423
+ const flutterwavePluginSchema = {
1424
+ ...transactions,
1425
+ ...subscriptions,
1426
+ ...products,
1427
+ ...plans,
1428
+ ...webhookEvents,
1429
+ ...refunds
1430
+ };
1431
+ const getSchema = (options) => {
1432
+ const { flutterwaveSubscription: _subscription, ...withoutSubscriptions } = flutterwavePluginSchema;
1433
+ const baseSchema = options.subscription?.enabled === true ? flutterwavePluginSchema : withoutSubscriptions;
1434
+ const optionSchema = options.schema;
1435
+ if (options.schema !== void 0 && options.subscription?.enabled !== true && "flutterwaveSubscription" in options.schema) {
1436
+ const { flutterwaveSubscription: _customSubscription, ...restSchema } = optionSchema ?? {};
1437
+ return mergeSchema(baseSchema, restSchema);
1438
+ }
1439
+ return mergeSchema(baseSchema, optionSchema);
1440
+ };
1441
+ //#endregion
1442
+ //#region src/limits.ts
1443
+ const checkSeatLimit = async (ctx, organizationId, seatsToAdd = 1) => {
1444
+ const store = createBillingStore(ctx);
1445
+ const seatLimit = (await store.findSubscriptionsByReference(organizationId)).filter((subscription) => subscription.status === "active" || subscription.status === "trialing").reduce((maximum, subscription) => typeof subscription.seats === "number" ? Math.max(maximum ?? subscription.seats, subscription.seats) : maximum, void 0);
1446
+ const members = await store.listMembers(organizationId);
1447
+ if (seatLimit === void 0) return true;
1448
+ if (members.length + seatsToAdd > seatLimit) throw new APIError("FORBIDDEN", { message: `Organization member limit reached. Used: ${members.length}, Max: ${seatLimit}` });
1449
+ return true;
1450
+ };
1451
+ async function getOrganizationEntitlements(ctx, organizationId, options) {
1452
+ const subscriptions = (await createBillingStore(ctx).findSubscriptionsByReference(organizationId)).filter((subscription) => subscription.status === "active" || subscription.status === "trialing");
1453
+ const limits = {};
1454
+ const features = /* @__PURE__ */ new Set();
1455
+ for (const subscription of subscriptions) {
1456
+ const plan = await getPlanByName(options, subscription.plan);
1457
+ for (const [name, value] of Object.entries(plan?.limits ?? {})) if (typeof value === "number" && Number.isFinite(value)) limits[name] = Math.max(limits[name] ?? value, value);
1458
+ for (const feature of plan?.features ?? []) features.add(feature);
1459
+ }
1460
+ return {
1461
+ limits,
1462
+ features: [...features]
1463
+ };
1464
+ }
1465
+ const checkTeamLimit = async (ctx, organizationId, maxTeams) => {
1466
+ if ((await createBillingStore(ctx).listTeams(organizationId)).length >= maxTeams) throw new APIError("FORBIDDEN", { message: `Organization team limit reached. Max teams: ${maxTeams}` });
1467
+ return true;
1468
+ };
1469
+ //#endregion
1470
+ //#region src/operations.ts
1471
+ function adapter(options) {
1472
+ return createFlutterwaveAdapter({
1473
+ publicKey: options.publicKey,
1474
+ secretKey: options.secretKey,
1475
+ flutterwaveClient: options.flutterwaveClient,
1476
+ fetch: options.fetch,
1477
+ apiBaseUrl: options.apiBaseUrl
1478
+ });
1479
+ }
1480
+ async function syncFlutterwavePlans(ctx, options) {
1481
+ const remote = await adapter(options).listPaymentPlans();
1482
+ const store = createBillingStore(ctx);
1483
+ const now = /* @__PURE__ */ new Date();
1484
+ for (const plan of remote) await store.upsertPlanByPaymentPlanId(plan.id, {
1485
+ name: plan.name,
1486
+ amount: plan.amount,
1487
+ currency: plan.currency,
1488
+ interval: plan.interval,
1489
+ paymentPlanId: plan.id,
1490
+ reconciledAt: now,
1491
+ createdAt: now,
1492
+ updatedAt: now
1493
+ });
1494
+ return {
1495
+ status: "success",
1496
+ count: remote.length
1497
+ };
1498
+ }
1499
+ async function chargeSubscriptionRenewal(ctx, options, input) {
1500
+ const store = createBillingStore(ctx);
1501
+ const subscription = await store.findSubscriptionById(input.subscriptionId);
1502
+ if (!subscription) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
1503
+ const plan = await store.findPlanByName(subscription.plan) ?? await (async () => {
1504
+ const configured = options.subscription?.plans;
1505
+ return (typeof configured === "function" ? await configured() : configured ?? []).find((candidate) => candidate.name === subscription.plan) ?? null;
1506
+ })();
1507
+ const amount = input.amount ?? plan?.amount;
1508
+ if (!amount || !plan?.currency || !subscription.billingEmail) throw new APIError("BAD_REQUEST", { message: "Subscription billing details are incomplete" });
1509
+ const txRef = `flw_renewal_${crypto.randomUUID()}`;
1510
+ const metadata = stringifyFlutterwaveMetadata(createRenewalMetadata({
1511
+ subscriptionId: subscription.id,
1512
+ referenceId: subscription.referenceId
1513
+ }));
1514
+ if (!subscription.encryptedPaymentToken) {
1515
+ if (!input.redirectUrl) throw new APIError("BAD_REQUEST", { message: "redirectUrl is required when the subscription has no reusable payment token" });
1516
+ const checkout = await adapter(options).initializePayment({
1517
+ tx_ref: txRef,
1518
+ amount,
1519
+ currency: plan.currency,
1520
+ redirect_url: input.redirectUrl,
1521
+ customer: { email: subscription.billingEmail },
1522
+ meta: parseMetadata(metadata)
1523
+ });
1524
+ const now = /* @__PURE__ */ new Date();
1525
+ await store.createTransaction({
1526
+ txRef,
1527
+ referenceId: subscription.referenceId,
1528
+ userId: subscription.userId,
1529
+ amount,
1530
+ currency: plan.currency,
1531
+ status: "pending",
1532
+ plan: subscription.plan,
1533
+ metadata,
1534
+ createdAt: now,
1535
+ updatedAt: now
1536
+ });
1537
+ await store.updateSubscription(subscription.id, {
1538
+ txRef,
1539
+ status: "past_due",
1540
+ updatedAt: now
1541
+ });
1542
+ return {
1543
+ status: "pending",
1544
+ data: {
1545
+ kind: "checkout",
1546
+ url: checkout.link,
1547
+ txRef,
1548
+ redirect: true
1549
+ }
1550
+ };
1551
+ }
1552
+ const token = await decryptPaymentToken(subscription.encryptedPaymentToken, ctx.context.secret);
1553
+ const charged = await adapter(options).chargeToken({
1554
+ token,
1555
+ amount,
1556
+ currency: plan.currency,
1557
+ email: subscription.billingEmail,
1558
+ tx_ref: txRef
1559
+ });
1560
+ const verified = await adapter(options).verifyTransaction({ transactionId: charged.id });
1561
+ if (verified.tx_ref !== txRef || verified.amount !== amount || verified.currency !== plan.currency) throw new APIError("BAD_REQUEST", { message: "Tokenized renewal did not match the expected payment" });
1562
+ const now = /* @__PURE__ */ new Date();
1563
+ await store.createTransaction({
1564
+ txRef,
1565
+ transactionId: verified.id,
1566
+ flwRef: verified.flw_ref,
1567
+ referenceId: subscription.referenceId,
1568
+ userId: subscription.userId,
1569
+ amount,
1570
+ chargedAmount: verified.charged_amount,
1571
+ currency: plan.currency,
1572
+ status: verified.status,
1573
+ plan: subscription.plan,
1574
+ paymentType: verified.payment_type,
1575
+ metadata,
1576
+ verifiedAt: now,
1577
+ reconciledAt: now,
1578
+ createdAt: now,
1579
+ updatedAt: now
1580
+ });
1581
+ await store.updateSubscription(subscription.id, {
1582
+ txRef,
1583
+ status: verified.status === "successful" ? "active" : "past_due",
1584
+ reconciledAt: now,
1585
+ updatedAt: now
1586
+ });
1587
+ return {
1588
+ status: verified.status === "successful" ? "success" : "failed",
1589
+ data: {
1590
+ id: verified.id,
1591
+ txRef: verified.tx_ref,
1592
+ flwRef: verified.flw_ref ?? void 0,
1593
+ amount: verified.amount,
1594
+ chargedAmount: verified.charged_amount,
1595
+ currency: verified.currency,
1596
+ status: verified.status,
1597
+ paymentType: verified.payment_type ?? void 0
1598
+ }
1599
+ };
1600
+ }
1601
+ function parseMetadata(value) {
1602
+ if (!value) return void 0;
1603
+ return JSON.parse(value);
1604
+ }
1605
+ async function refundFlutterwaveTransaction(ctx, options, input) {
1606
+ const store = createBillingStore(ctx);
1607
+ const transaction = await store.findTransactionById(input.transactionId);
1608
+ if (!transaction) throw new APIError("NOT_FOUND", { message: "Transaction not found" });
1609
+ const result = await adapter(options).refundTransaction(input.transactionId, input.amount);
1610
+ const now = /* @__PURE__ */ new Date();
1611
+ return store.createRefund({
1612
+ refundId: result.id,
1613
+ transactionId: input.transactionId,
1614
+ txRef: transaction.txRef,
1615
+ referenceId: transaction.referenceId,
1616
+ amount: result.amount_refunded ?? result.amount ?? input.amount ?? transaction.amount,
1617
+ currency: transaction.currency,
1618
+ status: result.status,
1619
+ reason: input.reason,
1620
+ createdAt: now,
1621
+ updatedAt: now
1622
+ });
1623
+ }
1624
+ //#endregion
1625
+ //#region src/reconciliation.ts
1626
+ async function reconcileFlutterwaveTransaction(ctx, options, input) {
1627
+ const store = createBillingStore(ctx);
1628
+ const local = input.txRef ? await store.findTransactionByTxRef(input.txRef) : input.transactionId ? await store.findTransactionById(input.transactionId) : null;
1629
+ if (!local) throw new APIError("NOT_FOUND", { message: "Transaction not found" });
1630
+ const verified = await createFlutterwaveAdapter({
1631
+ publicKey: options.publicKey,
1632
+ secretKey: options.secretKey,
1633
+ flutterwaveClient: options.flutterwaveClient,
1634
+ fetch: options.fetch,
1635
+ apiBaseUrl: options.apiBaseUrl
1636
+ }).verifyTransaction({
1637
+ txRef: input.txRef,
1638
+ transactionId: input.transactionId
1639
+ });
1640
+ if (!(verified.tx_ref === local.txRef && verified.amount === local.amount && verified.currency === local.currency)) {
1641
+ if (input.throwOnError === false) return {
1642
+ ok: false,
1643
+ source: input.source ?? "server",
1644
+ txRef: local.txRef,
1645
+ error: {
1646
+ code: "TRANSACTION_MISMATCH",
1647
+ message: "Transaction details do not match"
1648
+ }
1649
+ };
1650
+ throw new APIError("BAD_REQUEST", { message: "Transaction details do not match" });
1651
+ }
1652
+ const now = /* @__PURE__ */ new Date();
1653
+ await store.updateTransactionByTxRef(local.txRef, {
1654
+ transactionId: verified.id,
1655
+ flwRef: verified.flw_ref,
1656
+ chargedAmount: verified.charged_amount,
1657
+ paymentType: verified.payment_type,
1658
+ status: verified.status,
1659
+ verifiedAt: now,
1660
+ reconciledAt: now,
1661
+ updatedAt: now
1662
+ });
1663
+ for (const subscription of await store.findSubscriptionsByTxRef(local.txRef)) await store.updateSubscription(subscription.id, {
1664
+ status: verified.status === "successful" ? "active" : subscription.status,
1665
+ reconciledAt: now,
1666
+ updatedAt: now
1667
+ });
1668
+ const data = {
1669
+ id: verified.id,
1670
+ txRef: verified.tx_ref,
1671
+ flwRef: verified.flw_ref ?? void 0,
1672
+ amount: verified.amount,
1673
+ chargedAmount: verified.charged_amount,
1674
+ currency: verified.currency,
1675
+ status: verified.status,
1676
+ paymentType: verified.payment_type ?? void 0
1677
+ };
1678
+ return {
1679
+ ok: true,
1680
+ source: input.source ?? "server",
1681
+ txRef: local.txRef,
1682
+ status: verified.status,
1683
+ data
1684
+ };
1685
+ }
1686
+ const refundEnvelopeSchema = z.object({
1687
+ status: z.string(),
1688
+ data: z.object({
1689
+ id: z.coerce.number().optional(),
1690
+ status: z.string(),
1691
+ amount_refunded: z.coerce.number().optional()
1692
+ })
1693
+ });
1694
+ async function reconcileFlutterwaveRefunds(ctx, options) {
1695
+ const store = createBillingStore(ctx);
1696
+ const pending = await store.listPendingRefunds();
1697
+ const fetchImpl = options.fetch ?? globalThis.fetch;
1698
+ const baseUrl = (options.apiBaseUrl ?? "https://api.flutterwave.com").replace(/\/+$/, "");
1699
+ let updated = 0;
1700
+ for (const refund of pending) {
1701
+ if (!refund.refundId) continue;
1702
+ const response = await fetchImpl(`${baseUrl}/v3/refunds/${refund.refundId}`, { headers: { authorization: `Bearer ${options.secretKey}` } });
1703
+ if (!response.ok) continue;
1704
+ const parsed = refundEnvelopeSchema.safeParse(await response.json());
1705
+ if (!parsed.success) continue;
1706
+ await store.updateRefund(refund.id, {
1707
+ status: parsed.data.data.status,
1708
+ amount: parsed.data.data.amount_refunded ?? refund.amount,
1709
+ reconciledAt: /* @__PURE__ */ new Date(),
1710
+ updatedAt: /* @__PURE__ */ new Date()
1711
+ });
1712
+ updated++;
1713
+ }
1714
+ return {
1715
+ status: "success",
1716
+ count: updated
1717
+ };
1718
+ }
1719
+ //#endregion
1720
+ //#region src/index.ts
1721
+ const INTERNAL_ERROR_CODES = defineErrorCodes(Object.fromEntries(Object.entries(FLUTTERWAVE_ERROR_CODES).map(([key, value]) => [key, typeof value === "string" ? value : value.message])));
1722
+ const flutterwave = (options) => {
1723
+ const routeOptions = options;
1724
+ return {
1725
+ id: "flutterwave",
1726
+ version: PACKAGE_VERSION,
1727
+ endpoints: {
1728
+ initializeFlutterwaveTransaction: initializeTransaction(routeOptions, "/flutterwave/transaction/initialize"),
1729
+ verifyFlutterwaveTransaction: verifyTransaction(routeOptions, "/flutterwave/transaction/verify"),
1730
+ listFlutterwaveTransactions: listTransactions(routeOptions, "/flutterwave/transaction/list"),
1731
+ listFlutterwaveSubscriptions: listSubscriptions(routeOptions, "/flutterwave/subscription/list"),
1732
+ createFlutterwaveSubscription: createSubscription(routeOptions, "/flutterwave/subscription/create"),
1733
+ upgradeFlutterwaveSubscription: upgradeSubscription(routeOptions, "/flutterwave/subscription/upgrade"),
1734
+ cancelFlutterwaveSubscription: cancelSubscription(routeOptions, "/flutterwave/subscription/cancel"),
1735
+ restoreFlutterwaveSubscription: restoreSubscription(routeOptions, "/flutterwave/subscription/restore"),
1736
+ listFlutterwaveProducts: listProducts(routeOptions, "/flutterwave/product/list"),
1737
+ listFlutterwavePlans: listPlans(routeOptions, "/flutterwave/plan/list"),
1738
+ getFlutterwaveConfig: getConfig(routeOptions, "/flutterwave/config"),
1739
+ flutterwaveWebhook: flutterwaveWebhook(routeOptions, "/flutterwave/webhook")
1740
+ },
1741
+ schema: getSchema(routeOptions),
1742
+ init: (ctx) => {
1743
+ if (options.organization?.enabled === true && !ctx.hasPlugin("organization")) ctx.logger.error("Flutterwave organization billing requires the Better Auth organization plugin.");
1744
+ return { options: {} };
1745
+ },
1746
+ $ERROR_CODES: INTERNAL_ERROR_CODES,
1747
+ options
1748
+ };
1749
+ };
1750
+ //#endregion
1751
+ export { FlutterwaveAdapterError, chargeSubscriptionRenewal, checkSeatLimit, checkTeamLimit, createCheckoutMetadata, createFlutterwaveAdapter, createProrationMetadata, createRenewalMetadata, decryptPaymentToken, encryptPaymentToken, flutterwave, getMetadataBoolean, getMetadataNumber, getMetadataString, getOrganizationEntitlements, hasFlutterwaveMetadata, parseFlutterwaveMetadata, reconcileFlutterwaveRefunds, reconcileFlutterwaveTransaction, refundFlutterwaveTransaction, stringifyFlutterwaveMetadata, syncFlutterwavePlans };
1752
+
1753
+ //# sourceMappingURL=index.mjs.map