@lunora/payment 1.0.0-alpha.79 → 1.0.0-alpha.80
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.d.mts +18 -4
- package/dist/index.d.ts +18 -4
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/MemoryPaymentStore-C2iTSo5g.mjs +1 -0
- package/dist/packem_shared/{adapter.d-xBfAhqVC.d.mts → adapter.d-ov0kaEhj.d.mts} +2 -2
- package/dist/packem_shared/{adapter.d-xBfAhqVC.d.ts → adapter.d-ov0kaEhj.d.ts} +2 -2
- package/dist/packem_shared/addMoney-B4ufWAnD.mjs +1 -0
- package/dist/packem_shared/applyWebhookAction-daHKTG_Q.mjs +1 -0
- package/dist/packem_shared/createDatabasePaymentStore-BlMXuCW_.mjs +1 -0
- package/dist/packem_shared/createPayment-Dmh6IWLZ.mjs +1 -0
- package/dist/packem_shared/{lunoraDatabaseToPaymentDatabase-D5bzccof.mjs → lunoraDatabaseToPaymentDatabase-DBveGQxx.mjs} +1 -1
- package/dist/packem_shared/{reconcile-BpcX9ZyP.mjs → reconcile-Dq48_gHU.mjs} +1 -1
- package/dist/providers/autumn.d.mts +1 -1
- package/dist/providers/autumn.d.ts +1 -1
- package/dist/providers/autumn.mjs +1 -1
- package/dist/providers/creem.d.mts +1 -1
- package/dist/providers/creem.d.ts +1 -1
- package/dist/providers/creem.mjs +1 -1
- package/dist/providers/dodopayments.d.mts +1 -1
- package/dist/providers/dodopayments.d.ts +1 -1
- package/dist/providers/dodopayments.mjs +1 -1
- package/dist/providers/polar.d.mts +1 -1
- package/dist/providers/polar.d.ts +1 -1
- package/dist/providers/polar.mjs +1 -1
- package/dist/providers/stripe.d.mts +1 -1
- package/dist/providers/stripe.d.ts +1 -1
- package/dist/providers/stripe.mjs +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/MemoryPaymentStore-CkXqJEe2.mjs +0 -1
- package/dist/packem_shared/addMoney-COE-qM5x.mjs +0 -1
- package/dist/packem_shared/applyWebhookAction-B_90qZ1b.mjs +0 -1
- package/dist/packem_shared/createDatabasePaymentStore-CodmVJtK.mjs +0 -1
- package/dist/packem_shared/createPayment-CUoaQFnR.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as ProviderId, C as Customer, b as PaymentSession, S as Subscription, U as UsageEvent, W as WebhookActionType, A as ApplyResult, P as PaymentAdapter, c as AttachInput, d as CheckoutResult, e as CancelSubscriptionOptions, f as
|
|
2
|
-
export { type
|
|
1
|
+
import { a as ProviderId, C as Customer, b as PaymentSession, S as Subscription, U as UsageEvent, W as WebhookActionType, A as ApplyResult, P as PaymentAdapter, c as AttachInput, d as CheckoutResult, e as CancelSubscriptionOptions, f as CaptureInput, g as CheckInput, h as CheckResult, i as CheckoutInput, F as FeatureBalance, R as RefundInput, T as TrackInput, j as TrackResult, k as CurrencyCode, M as Money, l as PaymentState, m as SubscriptionState, n as WebhookAction } from "./packem_shared/adapter.d-ov0kaEhj.mjs";
|
|
2
|
+
export { type o as AdapterRegistry, type p as CustomerRef, type q as PortalInput, type r as ProviderCapabilities, type s as RefundAmountKind, type t as ReportUsageInput, type u as SubscriptionPatch, type v as WebhookHeaders, type w as WebhookInput, x as createAdapterRegistry } from "./packem_shared/adapter.d-ov0kaEhj.mjs";
|
|
3
3
|
import { LunoraError } from '@lunora/errors';
|
|
4
4
|
import { TableDefinition } from '@lunora/server';
|
|
5
5
|
/**
|
|
@@ -49,6 +49,8 @@ interface PaymentStore {
|
|
|
49
49
|
* last-writer-wins, and a replayed `set` is idempotent by construction.
|
|
50
50
|
*/
|
|
51
51
|
sumUsage: (referenceId: string, featureId: string, since: number) => Promise<number>;
|
|
52
|
+
/** Period usage totals for many features in one read — the batch form of {@link PaymentStore.sumUsage}. */
|
|
53
|
+
sumUsageByFeature: (referenceId: string, featureIds: ReadonlyArray<string>, since: number) => Promise<ReadonlyMap<string, number>>;
|
|
52
54
|
upsertCustomer: (customer: Customer) => Promise<void>;
|
|
53
55
|
upsertPaymentSession: (session: PaymentSession) => Promise<void>;
|
|
54
56
|
upsertSubscription: (subscription: Subscription) => Promise<void>;
|
|
@@ -72,6 +74,7 @@ declare class MemoryPaymentStore implements PaymentStore {
|
|
|
72
74
|
markUsageReported(provider: ProviderId, idempotencyKey: string): Promise<void>;
|
|
73
75
|
recordUsage(event: UsageEvent): Promise<boolean>;
|
|
74
76
|
sumUsage(referenceId: string, featureId: string, since: number): Promise<number>;
|
|
77
|
+
sumUsageByFeature(referenceId: string, featureIds: ReadonlyArray<string>, since: number): Promise<ReadonlyMap<string, number>>;
|
|
75
78
|
upsertCustomer(customer: Customer): Promise<void>;
|
|
76
79
|
upsertPaymentSession(session: PaymentSession): Promise<void>;
|
|
77
80
|
upsertSubscription(subscription: Subscription): Promise<void>;
|
|
@@ -222,7 +225,13 @@ interface LunoraPayment {
|
|
|
222
225
|
* with `mode` defaulting to `"subscription"`. Returns a hosted-checkout URL to redirect to.
|
|
223
226
|
*/
|
|
224
227
|
attach: (input: AttachInput) => Promise<CheckoutResult>;
|
|
228
|
+
/** Cancel the caller's own uncaptured payment (authorized, derived idempotency key, store synced). */
|
|
229
|
+
cancelPayment: (sessionId: string, options?: {
|
|
230
|
+
idempotencyKey?: string;
|
|
231
|
+
}) => Promise<PaymentSession>;
|
|
225
232
|
cancelSubscription: (subscriptionId: string, options?: CancelSubscriptionOptions) => Promise<Subscription>;
|
|
233
|
+
/** Capture the caller's own authorized payment (authorized, derived idempotency key, store synced). */
|
|
234
|
+
capturePayment: (input: CaptureInput) => Promise<PaymentSession>;
|
|
226
235
|
/**
|
|
227
236
|
* Is a reference allowed something right now? Pass `featureId` to check a grant/allowance (boolean
|
|
228
237
|
* features check plan grants; metered features subtract usage tracked this period) or `priceId` to
|
|
@@ -234,11 +243,16 @@ interface LunoraPayment {
|
|
|
234
243
|
createPortalSession: (referenceId: string, returnUrl: string) => Promise<{
|
|
235
244
|
url: string;
|
|
236
245
|
}>;
|
|
237
|
-
/**
|
|
246
|
+
/**
|
|
247
|
+
* Verify + normalize + apply a provider webhook. 200 once verified, even on a no-op — except an
|
|
248
|
+
* event whose target row doesn't exist yet, which returns 500 so the provider redelivers it once.
|
|
249
|
+
*/
|
|
238
250
|
handleWebhook: (request: Request) => Promise<Response>;
|
|
239
251
|
/** Resolve every configured feature's allowance for a reference in one call. Requires `entitlements`. */
|
|
240
252
|
listBalances: (referenceId: string) => Promise<FeatureBalance[]>;
|
|
241
253
|
listSubscriptions: (referenceId: string) => Promise<Subscription[]>;
|
|
254
|
+
/** Refund the caller's own captured payment (authorized, derived idempotency key, store synced). */
|
|
255
|
+
refundPayment: (input: RefundInput) => Promise<PaymentSession>;
|
|
242
256
|
readonly store: PaymentStore;
|
|
243
257
|
/**
|
|
244
258
|
* Record metered usage for a reference's feature — durably (exactly-once by idempotency key) and,
|
|
@@ -542,4 +556,4 @@ interface VerifyCreemSignatureInput {
|
|
|
542
556
|
* @experimental
|
|
543
557
|
*/
|
|
544
558
|
declare const verifyCreemSignature: (input: VerifyCreemSignatureInput) => Promise<void>;
|
|
545
|
-
export { type ApplyResult, type AttachInput, type AuthorizeReference, type CancelSubscriptionOptions, type CheckInput, type CheckResult, type CheckoutInput, type CheckoutResult, type CreatePaymentOptions, type CurrencyCode, type Customer, type Entitlements, type EntitlementsConfig, type FeatureBalance, type LunoraDatabaseLike, type LunoraPayment, LunoraPaymentError, MemoryPaymentStore, type Money, type MoneyJSON, PAYMENT_TERMINAL_STATES, type PaymentAction, type PaymentAdapter, type PaymentContextLike, type PaymentDatabase, type PaymentErrorCode, type PaymentEvent, type PaymentObserver, type PaymentRow, type PaymentSession, type PaymentState, type PaymentStore, type PaymentsFromContextOptions, type PlanDefinition, type ProviderId, type ReconcileInput, type ReconcileResult, SUBSCRIPTION_TERMINAL_STATES, type Subscription, type SubscriptionAction, type SubscriptionState, type TrackInput, type TrackResult, type UsageEvent, type WebhookAction, type WebhookActionType, addMoney, allocateMoney, applyWebhookAction, canTransitionPayment, canTransitionSubscription, compareMoney, constantTimeEqual, createDatabasePaymentStore, createPayment, entitlementsForReference, featureNames, formatMoney, fromMoneyJSON, hasActivePrice, hmacSha256Hex, idempotencyKey, isZeroDecimalCurrency, isZeroMoney, lunoraDatabaseToPaymentDatabase, money, nextPaymentState, nextSubscriptionState, paymentTables, paymentsFromContext, reconcile, resolveEntitlements, subtractMoney, toMoneyJSON, usagePeriodStart, verifyCreemSignature, verifyStandardWebhook, zeroMoney };
|
|
559
|
+
export { type ApplyResult, type AttachInput, type AuthorizeReference, type CancelSubscriptionOptions, type CaptureInput, type CheckInput, type CheckResult, type CheckoutInput, type CheckoutResult, type CreatePaymentOptions, type CurrencyCode, type Customer, type Entitlements, type EntitlementsConfig, type FeatureBalance, type LunoraDatabaseLike, type LunoraPayment, LunoraPaymentError, MemoryPaymentStore, type Money, type MoneyJSON, PAYMENT_TERMINAL_STATES, type PaymentAction, type PaymentAdapter, type PaymentContextLike, type PaymentDatabase, type PaymentErrorCode, type PaymentEvent, type PaymentObserver, type PaymentRow, type PaymentSession, type PaymentState, type PaymentStore, type PaymentsFromContextOptions, type PlanDefinition, type ProviderId, type ReconcileInput, type ReconcileResult, type RefundInput, SUBSCRIPTION_TERMINAL_STATES, type Subscription, type SubscriptionAction, type SubscriptionState, type TrackInput, type TrackResult, type UsageEvent, type WebhookAction, type WebhookActionType, addMoney, allocateMoney, applyWebhookAction, canTransitionPayment, canTransitionSubscription, compareMoney, constantTimeEqual, createDatabasePaymentStore, createPayment, entitlementsForReference, featureNames, formatMoney, fromMoneyJSON, hasActivePrice, hmacSha256Hex, idempotencyKey, isZeroDecimalCurrency, isZeroMoney, lunoraDatabaseToPaymentDatabase, money, nextPaymentState, nextSubscriptionState, paymentTables, paymentsFromContext, reconcile, resolveEntitlements, subtractMoney, toMoneyJSON, usagePeriodStart, verifyCreemSignature, verifyStandardWebhook, zeroMoney };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as ProviderId, C as Customer, b as PaymentSession, S as Subscription, U as UsageEvent, W as WebhookActionType, A as ApplyResult, P as PaymentAdapter, c as AttachInput, d as CheckoutResult, e as CancelSubscriptionOptions, f as
|
|
2
|
-
export { type
|
|
1
|
+
import { a as ProviderId, C as Customer, b as PaymentSession, S as Subscription, U as UsageEvent, W as WebhookActionType, A as ApplyResult, P as PaymentAdapter, c as AttachInput, d as CheckoutResult, e as CancelSubscriptionOptions, f as CaptureInput, g as CheckInput, h as CheckResult, i as CheckoutInput, F as FeatureBalance, R as RefundInput, T as TrackInput, j as TrackResult, k as CurrencyCode, M as Money, l as PaymentState, m as SubscriptionState, n as WebhookAction } from "./packem_shared/adapter.d-ov0kaEhj.js";
|
|
2
|
+
export { type o as AdapterRegistry, type p as CustomerRef, type q as PortalInput, type r as ProviderCapabilities, type s as RefundAmountKind, type t as ReportUsageInput, type u as SubscriptionPatch, type v as WebhookHeaders, type w as WebhookInput, x as createAdapterRegistry } from "./packem_shared/adapter.d-ov0kaEhj.js";
|
|
3
3
|
import { LunoraError } from '@lunora/errors';
|
|
4
4
|
import { TableDefinition } from '@lunora/server';
|
|
5
5
|
/**
|
|
@@ -49,6 +49,8 @@ interface PaymentStore {
|
|
|
49
49
|
* last-writer-wins, and a replayed `set` is idempotent by construction.
|
|
50
50
|
*/
|
|
51
51
|
sumUsage: (referenceId: string, featureId: string, since: number) => Promise<number>;
|
|
52
|
+
/** Period usage totals for many features in one read — the batch form of {@link PaymentStore.sumUsage}. */
|
|
53
|
+
sumUsageByFeature: (referenceId: string, featureIds: ReadonlyArray<string>, since: number) => Promise<ReadonlyMap<string, number>>;
|
|
52
54
|
upsertCustomer: (customer: Customer) => Promise<void>;
|
|
53
55
|
upsertPaymentSession: (session: PaymentSession) => Promise<void>;
|
|
54
56
|
upsertSubscription: (subscription: Subscription) => Promise<void>;
|
|
@@ -72,6 +74,7 @@ declare class MemoryPaymentStore implements PaymentStore {
|
|
|
72
74
|
markUsageReported(provider: ProviderId, idempotencyKey: string): Promise<void>;
|
|
73
75
|
recordUsage(event: UsageEvent): Promise<boolean>;
|
|
74
76
|
sumUsage(referenceId: string, featureId: string, since: number): Promise<number>;
|
|
77
|
+
sumUsageByFeature(referenceId: string, featureIds: ReadonlyArray<string>, since: number): Promise<ReadonlyMap<string, number>>;
|
|
75
78
|
upsertCustomer(customer: Customer): Promise<void>;
|
|
76
79
|
upsertPaymentSession(session: PaymentSession): Promise<void>;
|
|
77
80
|
upsertSubscription(subscription: Subscription): Promise<void>;
|
|
@@ -222,7 +225,13 @@ interface LunoraPayment {
|
|
|
222
225
|
* with `mode` defaulting to `"subscription"`. Returns a hosted-checkout URL to redirect to.
|
|
223
226
|
*/
|
|
224
227
|
attach: (input: AttachInput) => Promise<CheckoutResult>;
|
|
228
|
+
/** Cancel the caller's own uncaptured payment (authorized, derived idempotency key, store synced). */
|
|
229
|
+
cancelPayment: (sessionId: string, options?: {
|
|
230
|
+
idempotencyKey?: string;
|
|
231
|
+
}) => Promise<PaymentSession>;
|
|
225
232
|
cancelSubscription: (subscriptionId: string, options?: CancelSubscriptionOptions) => Promise<Subscription>;
|
|
233
|
+
/** Capture the caller's own authorized payment (authorized, derived idempotency key, store synced). */
|
|
234
|
+
capturePayment: (input: CaptureInput) => Promise<PaymentSession>;
|
|
226
235
|
/**
|
|
227
236
|
* Is a reference allowed something right now? Pass `featureId` to check a grant/allowance (boolean
|
|
228
237
|
* features check plan grants; metered features subtract usage tracked this period) or `priceId` to
|
|
@@ -234,11 +243,16 @@ interface LunoraPayment {
|
|
|
234
243
|
createPortalSession: (referenceId: string, returnUrl: string) => Promise<{
|
|
235
244
|
url: string;
|
|
236
245
|
}>;
|
|
237
|
-
/**
|
|
246
|
+
/**
|
|
247
|
+
* Verify + normalize + apply a provider webhook. 200 once verified, even on a no-op — except an
|
|
248
|
+
* event whose target row doesn't exist yet, which returns 500 so the provider redelivers it once.
|
|
249
|
+
*/
|
|
238
250
|
handleWebhook: (request: Request) => Promise<Response>;
|
|
239
251
|
/** Resolve every configured feature's allowance for a reference in one call. Requires `entitlements`. */
|
|
240
252
|
listBalances: (referenceId: string) => Promise<FeatureBalance[]>;
|
|
241
253
|
listSubscriptions: (referenceId: string) => Promise<Subscription[]>;
|
|
254
|
+
/** Refund the caller's own captured payment (authorized, derived idempotency key, store synced). */
|
|
255
|
+
refundPayment: (input: RefundInput) => Promise<PaymentSession>;
|
|
242
256
|
readonly store: PaymentStore;
|
|
243
257
|
/**
|
|
244
258
|
* Record metered usage for a reference's feature — durably (exactly-once by idempotency key) and,
|
|
@@ -542,4 +556,4 @@ interface VerifyCreemSignatureInput {
|
|
|
542
556
|
* @experimental
|
|
543
557
|
*/
|
|
544
558
|
declare const verifyCreemSignature: (input: VerifyCreemSignatureInput) => Promise<void>;
|
|
545
|
-
export { type ApplyResult, type AttachInput, type AuthorizeReference, type CancelSubscriptionOptions, type CheckInput, type CheckResult, type CheckoutInput, type CheckoutResult, type CreatePaymentOptions, type CurrencyCode, type Customer, type Entitlements, type EntitlementsConfig, type FeatureBalance, type LunoraDatabaseLike, type LunoraPayment, LunoraPaymentError, MemoryPaymentStore, type Money, type MoneyJSON, PAYMENT_TERMINAL_STATES, type PaymentAction, type PaymentAdapter, type PaymentContextLike, type PaymentDatabase, type PaymentErrorCode, type PaymentEvent, type PaymentObserver, type PaymentRow, type PaymentSession, type PaymentState, type PaymentStore, type PaymentsFromContextOptions, type PlanDefinition, type ProviderId, type ReconcileInput, type ReconcileResult, SUBSCRIPTION_TERMINAL_STATES, type Subscription, type SubscriptionAction, type SubscriptionState, type TrackInput, type TrackResult, type UsageEvent, type WebhookAction, type WebhookActionType, addMoney, allocateMoney, applyWebhookAction, canTransitionPayment, canTransitionSubscription, compareMoney, constantTimeEqual, createDatabasePaymentStore, createPayment, entitlementsForReference, featureNames, formatMoney, fromMoneyJSON, hasActivePrice, hmacSha256Hex, idempotencyKey, isZeroDecimalCurrency, isZeroMoney, lunoraDatabaseToPaymentDatabase, money, nextPaymentState, nextSubscriptionState, paymentTables, paymentsFromContext, reconcile, resolveEntitlements, subtractMoney, toMoneyJSON, usagePeriodStart, verifyCreemSignature, verifyStandardWebhook, zeroMoney };
|
|
559
|
+
export { type ApplyResult, type AttachInput, type AuthorizeReference, type CancelSubscriptionOptions, type CaptureInput, type CheckInput, type CheckResult, type CheckoutInput, type CheckoutResult, type CreatePaymentOptions, type CurrencyCode, type Customer, type Entitlements, type EntitlementsConfig, type FeatureBalance, type LunoraDatabaseLike, type LunoraPayment, LunoraPaymentError, MemoryPaymentStore, type Money, type MoneyJSON, PAYMENT_TERMINAL_STATES, type PaymentAction, type PaymentAdapter, type PaymentContextLike, type PaymentDatabase, type PaymentErrorCode, type PaymentEvent, type PaymentObserver, type PaymentRow, type PaymentSession, type PaymentState, type PaymentStore, type PaymentsFromContextOptions, type PlanDefinition, type ProviderId, type ReconcileInput, type ReconcileResult, type RefundInput, SUBSCRIPTION_TERMINAL_STATES, type Subscription, type SubscriptionAction, type SubscriptionState, type TrackInput, type TrackResult, type UsageEvent, type WebhookAction, type WebhookActionType, addMoney, allocateMoney, applyWebhookAction, canTransitionPayment, canTransitionSubscription, compareMoney, constantTimeEqual, createDatabasePaymentStore, createPayment, entitlementsForReference, featureNames, formatMoney, fromMoneyJSON, hasActivePrice, hmacSha256Hex, idempotencyKey, isZeroDecimalCurrency, isZeroMoney, lunoraDatabaseToPaymentDatabase, money, nextPaymentState, nextSubscriptionState, paymentTables, paymentsFromContext, reconcile, resolveEntitlements, subtractMoney, toMoneyJSON, usagePeriodStart, verifyCreemSignature, verifyStandardWebhook, zeroMoney };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createAdapterRegistry as r}from"./packem_shared/createAdapterRegistry-DyCsry1Q.mjs";import{lunoraDatabaseToPaymentDatabase as a,paymentsFromContext as n}from"./packem_shared/lunoraDatabaseToPaymentDatabase-
|
|
1
|
+
import{createAdapterRegistry as r}from"./packem_shared/createAdapterRegistry-DyCsry1Q.mjs";import{lunoraDatabaseToPaymentDatabase as a,paymentsFromContext as n}from"./packem_shared/lunoraDatabaseToPaymentDatabase-DBveGQxx.mjs";import{createPayment as y}from"./packem_shared/createPayment-Dmh6IWLZ.mjs";import{createDatabasePaymentStore as p}from"./packem_shared/createDatabasePaymentStore-BlMXuCW_.mjs";import{entitlementsForReference as s,featureNames as c,hasActivePrice as x,resolveEntitlements as S,usagePeriodStart as l}from"./packem_shared/entitlementsForReference-Bq-9UUL8.mjs";import{LunoraPaymentError as T}from"./packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{idempotencyKey as P}from"./packem_shared/idempotencyKey-BjxjMMna.mjs";import{addMoney as d,allocateMoney as A,compareMoney as E,formatMoney as N,fromMoneyJSON as h,isZeroDecimalCurrency as R,isZeroMoney as v,money as C,subtractMoney as D,toMoneyJSON as I,zeroMoney as _}from"./packem_shared/addMoney-B4ufWAnD.mjs";import{reconcile as L}from"./packem_shared/reconcile-Dq48_gHU.mjs";import{default as k}from"./packem_shared/paymentTables-Be-_11ux.mjs";import{PAYMENT_TERMINAL_STATES as J,SUBSCRIPTION_TERMINAL_STATES as W,canTransitionPayment as Z,canTransitionSubscription as q,nextPaymentState as z,nextSubscriptionState as B}from"./packem_shared/PAYMENT_TERMINAL_STATES-DVerjPR6.mjs";import{MemoryPaymentStore as K}from"./packem_shared/MemoryPaymentStore-C2iTSo5g.mjs";import{default as Y}from"./packem_shared/applyWebhookAction-daHKTG_Q.mjs";import{constantTimeEqual as w,hmacSha256Hex as G,verifyCreemSignature as Q,verifyStandardWebhook as V}from"./packem_shared/constantTimeEqual-Bj5tU-zT.mjs";export{T as LunoraPaymentError,K as MemoryPaymentStore,J as PAYMENT_TERMINAL_STATES,W as SUBSCRIPTION_TERMINAL_STATES,d as addMoney,A as allocateMoney,Y as applyWebhookAction,Z as canTransitionPayment,q as canTransitionSubscription,E as compareMoney,w as constantTimeEqual,r as createAdapterRegistry,p as createDatabasePaymentStore,y as createPayment,s as entitlementsForReference,c as featureNames,N as formatMoney,h as fromMoneyJSON,x as hasActivePrice,G as hmacSha256Hex,P as idempotencyKey,R as isZeroDecimalCurrency,v as isZeroMoney,a as lunoraDatabaseToPaymentDatabase,C as money,z as nextPaymentState,B as nextSubscriptionState,k as paymentTables,n as paymentsFromContext,L as reconcile,S as resolveEntitlements,D as subtractMoney,I as toMoneyJSON,l as usagePeriodStart,Q as verifyCreemSignature,V as verifyStandardWebhook,_ as zeroMoney};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const u=(i,e)=>`${i}:${e}`,n=(i,e)=>`${i}:${e}`,a=i=>{const e=i.toSorted((r,o)=>r.createdAt-o.createdAt||r.idempotencyKey.localeCompare(o.idempotencyKey));let s=0;for(const r of e)s=r.mode==="set"?r.quantity:s+r.quantity;return s};class d{customers=new Map;processedEvents=new Set;sessions=new Map;subscriptions=new Map;usageEvents=new Map;getCustomerByReference(e,s){return Promise.resolve(this.customers.get(u(e,s)))}getPaymentSession(e,s){return Promise.resolve(this.sessions.get(n(e,s)))}getSubscription(e,s){return Promise.resolve(this.subscriptions.get(n(e,s)))}listSubscriptionsByReference(e){return Promise.resolve([...this.subscriptions.values()].filter(s=>s.referenceId===e))}markEventProcessed(e,s){const r=n(e,s);return this.processedEvents.has(r)?Promise.resolve(!1):(this.processedEvents.add(r),Promise.resolve(!0))}releaseEvent(e,s){return this.processedEvents.delete(n(e,s)),Promise.resolve()}markUsageReported(e,s){const r=n(e,s),o=this.usageEvents.get(r);return o&&this.usageEvents.set(r,{...o,reportedToProvider:!0}),Promise.resolve()}recordUsage(e){const s=n(e.provider,e.idempotencyKey);return this.usageEvents.has(s)?Promise.resolve(!1):(this.usageEvents.set(s,e),Promise.resolve(!0))}sumUsage(e,s,r){const o=[];for(const t of this.usageEvents.values())t.referenceId===e&&t.featureId===s&&t.createdAt>=r&&o.push(t);return Promise.resolve(a(o))}sumUsageByFeature(e,s,r){const o=new Map(s.map(t=>[t,[]]));for(const t of this.usageEvents.values())t.referenceId===e&&t.createdAt>=r&&o.get(t.featureId)?.push(t);return Promise.resolve(new Map([...o].map(([t,c])=>[t,a(c)])))}upsertCustomer(e){return this.customers.set(u(e.provider,e.referenceId),e),Promise.resolve()}upsertPaymentSession(e){return this.sessions.set(n(e.provider,e.id),e),Promise.resolve()}upsertSubscription(e){return this.subscriptions.set(n(e.provider,e.id),e),Promise.resolve()}}export{d as MemoryPaymentStore,a as foldUsage};
|
|
@@ -357,7 +357,7 @@ interface WebhookAction {
|
|
|
357
357
|
*/
|
|
358
358
|
interface ApplyResult {
|
|
359
359
|
readonly applied: boolean;
|
|
360
|
-
readonly reason?: "duplicate" | "illegal_transition" | "invalid_refund_amount" | "ok" | "unhandled";
|
|
360
|
+
readonly reason?: "duplicate" | "illegal_transition" | "invalid_refund_amount" | "ok" | "orphaned" | "unhandled";
|
|
361
361
|
}
|
|
362
362
|
/**
|
|
363
363
|
* A read-only header bag; the platform `Headers` object satisfies it.
|
|
@@ -442,4 +442,4 @@ interface AdapterRegistry {
|
|
|
442
442
|
* @experimental
|
|
443
443
|
*/
|
|
444
444
|
declare const createAdapterRegistry: (adapters: ReadonlyArray<PaymentAdapter>) => AdapterRegistry;
|
|
445
|
-
export { ApplyResult as A, Customer as C, FeatureBalance as F, Money as M, PaymentAdapter as P,
|
|
445
|
+
export { ApplyResult as A, Customer as C, FeatureBalance as F, Money as M, PaymentAdapter as P, RefundInput as R, Subscription as S, TrackInput as T, UsageEvent as U, WebhookActionType as W, ProviderId as a, PaymentSession as b, AttachInput as c, CheckoutResult as d, CancelSubscriptionOptions as e, CaptureInput as f, CheckInput as g, CheckResult as h, CheckoutInput as i, TrackResult as j, CurrencyCode as k, PaymentState as l, SubscriptionState as m, WebhookAction as n, AdapterRegistry as o, CustomerRef as p, PortalInput as q, ProviderCapabilities as r, RefundAmountKind as s, ReportUsageInput as t, SubscriptionPatch as u, WebhookHeaders as v, WebhookInput as w, createAdapterRegistry as x };
|
|
@@ -357,7 +357,7 @@ interface WebhookAction {
|
|
|
357
357
|
*/
|
|
358
358
|
interface ApplyResult {
|
|
359
359
|
readonly applied: boolean;
|
|
360
|
-
readonly reason?: "duplicate" | "illegal_transition" | "invalid_refund_amount" | "ok" | "unhandled";
|
|
360
|
+
readonly reason?: "duplicate" | "illegal_transition" | "invalid_refund_amount" | "ok" | "orphaned" | "unhandled";
|
|
361
361
|
}
|
|
362
362
|
/**
|
|
363
363
|
* A read-only header bag; the platform `Headers` object satisfies it.
|
|
@@ -442,4 +442,4 @@ interface AdapterRegistry {
|
|
|
442
442
|
* @experimental
|
|
443
443
|
*/
|
|
444
444
|
declare const createAdapterRegistry: (adapters: ReadonlyArray<PaymentAdapter>) => AdapterRegistry;
|
|
445
|
-
export { ApplyResult as A, Customer as C, FeatureBalance as F, Money as M, PaymentAdapter as P,
|
|
445
|
+
export { ApplyResult as A, Customer as C, FeatureBalance as F, Money as M, PaymentAdapter as P, RefundInput as R, Subscription as S, TrackInput as T, UsageEvent as U, WebhookActionType as W, ProviderId as a, PaymentSession as b, AttachInput as c, CheckoutResult as d, CancelSubscriptionOptions as e, CaptureInput as f, CheckInput as g, CheckResult as h, CheckoutInput as i, TrackResult as j, CurrencyCode as k, PaymentState as l, SubscriptionState as m, WebhookAction as n, AdapterRegistry as o, CustomerRef as p, PortalInput as q, ProviderCapabilities as r, RefundAmountKind as s, ReportUsageInput as t, SubscriptionPatch as u, WebhookHeaders as v, WebhookInput as w, createAdapterRegistry as x };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toSnapshot as m}from"dinero.js";import{add as a,allocate as p,compare as M,subtract as f,dinero as D}from"dinero.js/bigint";import{LunoraPaymentError as y}from"./LunoraPaymentError-BSxyhWgu.mjs";const C=new Set(["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"]),U=new Set(["BHD","IQD","JOD","KWD","LYD","OMR","TND"]),o=n=>C.has(n)?0n:U.has(n)?3n:2n,F=n=>({base:10n,code:n.toUpperCase(),exponent:o(n.toUpperCase())}),e=n=>D({amount:n.minorUnits,currency:F(n.currency)}),c=n=>{const r=m(n);return{currency:r.currency.code,minorUnits:r.amount}},s=(n,r)=>{if(n.currency!==r.currency)throw new y("CURRENCY_MISMATCH",`cannot combine ${n.currency} with ${r.currency}`)},R=n=>o(n.toUpperCase())===0n,i=(n,r)=>{if(typeof n=="number"&&!Number.isSafeInteger(n))throw new y("VALIDATION_ERROR",`money(): \`minorUnits\` must be a bigint or a safe integer (got ${String(n)})`);const t=typeof n=="bigint"?n:BigInt(n);return{currency:r.toUpperCase(),minorUnits:t}},g=n=>i(0n,n),b=(n,r="en-US")=>{const t=Number(o(n.currency.toUpperCase())),u=Number(n.minorUnits)/10**t;try{return new Intl.NumberFormat(r,{currency:n.currency,style:"currency"}).format(u)}catch{return`${u.toFixed(t)} ${n.currency}`}},h=(n,r)=>(s(n,r),c(a(e(n),e(r)))),w=(n,r)=>(s(n,r),c(f(e(n),e(r)))),E=(n,r)=>(s(n,r),M(e(n),e(r))),O=(n,r)=>p(e(n),[...r]).map(t=>c(t)),A=n=>n.minorUnits===0n,d=n=>({currency:n.currency,minorUnits:n.minorUnits.toString()}),L=n=>i(BigInt(n.minorUnits),n.currency);export{h as addMoney,O as allocateMoney,E as compareMoney,b as formatMoney,L as fromMoneyJSON,R as isZeroDecimalCurrency,A as isZeroMoney,i as money,w as subtractMoney,d as toMoneyJSON,g as zeroMoney};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraPaymentError as I}from"./LunoraPaymentError-BSxyhWgu.mjs";import{compareMoney as l,zeroMoney as c,addMoney as P}from"./addMoney-B4ufWAnD.mjs";import{n as o}from"./observability-BteZ2dJS.mjs";import{nextPaymentState as A,nextSubscriptionState as E}from"./PAYMENT_TERMINAL_STATES-DVerjPR6.mjs";const S={"payment.authorized":"authorize","payment.captured":"capture","payment.failed":"fail","payment.refunded":"refund"},_={"subscription.active":"active","subscription.canceled":"canceled","subscription.past_due":"past_due","subscription.paused":"paused"},b="orphan-retry:",w={"subscription.active":"activate","subscription.canceled":"cancel","subscription.past_due":"mark_past_due","subscription.paused":"pause"},h=(t,e)=>l(t,e)>0?t:e,v=(t,e)=>{if(!e.amount||t.refundedAmount.currency!==e.amount.currency||t.capturedAmount.currency!==e.amount.currency)return;const r=e.amountKind==="absolute"?h(e.amount,t.refundedAmount):P(t.refundedAmount,e.amount);if(!(l(r,t.capturedAmount)>0))return r},T=async(t,e,r)=>{if(!e.sessionId)return{applied:!1,reason:"unhandled"};const n=await t.getPaymentSession(e.provider,e.sessionId),u=n?.state??"initiated",d=Date.now(),p=e.amount?.currency??n?.amount.currency??"USD";let i=r;if(r==="refund"&&n){const a=v(n,e);a&&l(a,n.capturedAmount)<0&&(i="partial_refund")}const f=A(u,i);if(!f)return{applied:!1,reason:"illegal_transition"};const s=n??{amount:e.amount??c(p),capturedAmount:c(p),createdAt:d,id:e.sessionId,provider:e.provider,referenceId:e.referenceId??"",refundedAmount:c(p),state:u,updatedAt:d};let{capturedAmount:y,refundedAmount:m}=s;if(i==="capture"&&e.amount&&(y=e.amount),(i==="partial_refund"||i==="refund")&&e.amount){const a=v(s,e);if(!a)return{applied:!1,reason:"invalid_refund_amount"};m=a}return await t.upsertPaymentSession({...s,capturedAmount:y,referenceId:e.referenceId??s.referenceId,refundedAmount:m,state:f,updatedAt:d}),{applied:!0,reason:"ok"}},k=async(t,e)=>{if(!e.subscriptionId)return{applied:!1,reason:"unhandled"};const r=await t.getSubscription(e.provider,e.subscriptionId),n=Date.now();if(e.type==="subscription.updated")return r?(await t.upsertSubscription({...r,cancelAtPeriodEnd:e.cancelAtPeriodEnd??r.cancelAtPeriodEnd,currentPeriodEnd:e.currentPeriodEnd??r.currentPeriodEnd,currentPeriodStart:e.currentPeriodStart??r.currentPeriodStart,priceId:e.priceId??r.priceId,quantity:e.quantity??r.quantity,updatedAt:n}),{applied:!0,reason:"ok"}):{applied:!1,reason:"orphaned"};const u=_[e.type];if(!u)return{applied:!1,reason:"unhandled"};if(!r)return await t.upsertSubscription({cancelAtPeriodEnd:e.cancelAtPeriodEnd??!1,createdAt:n,currentPeriodEnd:e.currentPeriodEnd,currentPeriodStart:e.currentPeriodStart??n,id:e.subscriptionId,priceId:e.priceId??"",provider:e.provider,quantity:e.quantity??1,referenceId:e.referenceId??"",state:u,updatedAt:n}),{applied:!0,reason:"ok"};const d=r.state==="active"&&u==="active"?"renew":w[e.type],p=d?E(r.state,d):void 0;return p?(await t.upsertSubscription({...r,cancelAtPeriodEnd:e.cancelAtPeriodEnd??r.cancelAtPeriodEnd,currentPeriodEnd:e.currentPeriodEnd??r.currentPeriodEnd,currentPeriodStart:e.currentPeriodStart??r.currentPeriodStart,priceId:e.priceId??r.priceId,quantity:e.quantity??r.quantity,state:p,updatedAt:n}),{applied:!0,reason:"ok"}):{applied:!1,reason:"illegal_transition"}},Y=async(t,e,r)=>{if(e.type==="unhandled")return{applied:!1,reason:"unhandled"};if(!e.eventId?.trim())throw new I("WEBHOOK_EVENT_ID_MISSING",`webhook event id is missing or blank for provider "${e.provider}"`);if(!await t.markEventProcessed(e.provider,e.eventId))return o(r,{eventId:e.eventId,provider:e.provider,type:"webhook.duplicate"}),{applied:!1,reason:"duplicate"};const u=S[e.type];let d;try{d=u?await T(t,e,u):await k(t,e)}catch(p){throw await t.releaseEvent(e.provider,e.eventId),p}return d.reason==="orphaned"&&(await t.markEventProcessed(e.provider,`${b}${e.eventId}`)?await t.releaseEvent(e.provider,e.eventId):d={applied:!1,reason:"unhandled"}),o(r,{action:e.type,eventId:e.eventId,provider:e.provider,reason:d.reason,type:"webhook.applied"}),e.type==="payment.failed"?o(r,{provider:e.provider,referenceId:e.referenceId,sessionId:e.sessionId,type:"payment.failed"}):e.type==="subscription.past_due"&&o(r,{provider:e.provider,referenceId:e.referenceId,subscriptionId:e.subscriptionId,type:"subscription.past_due"}),d};export{Y as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{money as u}from"./addMoney-B4ufWAnD.mjs";import{foldUsage as y}from"./MemoryPaymentStore-C2iTSo5g.mjs";const o=(e,n)=>typeof e[n]=="string"?e[n]:"",A=(e,n)=>typeof e[n]=="string"?e[n]:void 0,c=(e,n)=>typeof e[n]=="number"?e[n]:0,f=(e,n)=>typeof e[n]=="number"?e[n]:void 0,I=(e,n)=>e[n]===!0,p=(e,n)=>{const t=e[n];return typeof t=="bigint"?t:typeof t=="number"||typeof t=="string"?BigInt(t):0n},g=e=>({createdAt:e.createdAt,email:e.email,provider:e.provider,providerCustomerId:e.id,referenceId:e.referenceId}),S=e=>({createdAt:c(e,"createdAt"),email:A(e,"email"),id:o(e,"providerCustomerId"),provider:o(e,"provider"),referenceId:o(e,"referenceId")}),E=e=>({amountMinor:e.amount.minorUnits,capturedMinor:e.capturedAmount.minorUnits,createdAt:e.createdAt,currency:e.amount.currency,provider:e.provider,providerSessionId:e.id,referenceId:e.referenceId,refundedMinor:e.refundedAmount.minorUnits,state:e.state,updatedAt:e.updatedAt}),P=e=>{const n=o(e,"currency");return{amount:u(p(e,"amountMinor"),n),capturedAmount:u(p(e,"capturedMinor"),n),createdAt:c(e,"createdAt"),id:o(e,"providerSessionId"),provider:o(e,"provider"),referenceId:o(e,"referenceId"),refundedAmount:u(p(e,"refundedMinor"),n),state:o(e,"state"),updatedAt:c(e,"updatedAt")}},l=e=>({cancelAtPeriodEnd:e.cancelAtPeriodEnd,createdAt:e.createdAt,currentPeriodEnd:e.currentPeriodEnd,currentPeriodStart:e.currentPeriodStart,priceId:e.priceId,provider:e.provider,providerSubscriptionId:e.id,quantity:e.quantity,referenceId:e.referenceId,state:e.state,updatedAt:e.updatedAt}),m=e=>({cancelAtPeriodEnd:I(e,"cancelAtPeriodEnd"),createdAt:c(e,"createdAt"),currentPeriodEnd:f(e,"currentPeriodEnd"),currentPeriodStart:f(e,"currentPeriodStart"),id:o(e,"providerSubscriptionId"),priceId:o(e,"priceId"),provider:o(e,"provider"),quantity:c(e,"quantity"),referenceId:o(e,"referenceId"),state:o(e,"state"),updatedAt:c(e,"updatedAt")}),M=e=>({createdAt:e.createdAt,featureId:e.featureId,idempotencyKey:e.idempotencyKey,...e.mode==="set"?{mode:"set"}:{},provider:e.provider,quantity:e.quantity,referenceId:e.referenceId,reportedToProvider:e.reportedToProvider}),T=e=>{const n=async(t,d,r)=>{const a=await e.findFirst(t,d);if(a){await e.patch(a._id,r);return}await e.insert(t,r)};return{getCustomerByReference:async(t,d)=>{const r=await e.findFirst("customers",{provider:t,referenceId:d});return r?S(r):void 0},getPaymentSession:async(t,d)=>{const r=await e.findFirst("paymentSessions",{provider:t,providerSessionId:d});return r?P(r):void 0},getSubscription:async(t,d)=>{const r=await e.findFirst("subscriptions",{provider:t,providerSubscriptionId:d});return r?m(r):void 0},listSubscriptionsByReference:async t=>(await e.findMany("subscriptions",{referenceId:t})).map(r=>m(r)),markEventProcessed:async(t,d)=>await e.findFirst("events",{provider:t,providerEventId:d})?!1:(await e.insert("events",{processedAt:Date.now(),provider:t,providerEventId:d,type:""}),!0),releaseEvent:async(t,d)=>{const r=await e.findFirst("events",{provider:t,providerEventId:d});r&&await e.delete(r._id)},markUsageReported:async(t,d)=>{const r=await e.findFirst("usageEvents",{idempotencyKey:d,provider:t});r&&await e.patch(r._id,{reportedToProvider:!0})},recordUsage:async t=>await e.findFirst("usageEvents",{idempotencyKey:t.idempotencyKey,provider:t.provider})?!1:(await e.insert("usageEvents",M(t)),!0),sumUsage:async(t,d,r)=>{const s=(await e.findMany("usageEvents",{featureId:d,referenceId:t})).filter(i=>c(i,"createdAt")>=r).map(i=>({createdAt:c(i,"createdAt"),idempotencyKey:typeof i.idempotencyKey=="string"?i.idempotencyKey:"",mode:i.mode==="set"?"set":"add",quantity:c(i,"quantity")}));return y(s)},sumUsageByFeature:async(t,d,r)=>{const a=await e.findMany("usageEvents",{referenceId:t}),s=new Map(d.map(i=>[i,[]]));for(const i of a)c(i,"createdAt")<r||s.get(typeof i.featureId=="string"?i.featureId:"")?.push({createdAt:c(i,"createdAt"),idempotencyKey:typeof i.idempotencyKey=="string"?i.idempotencyKey:"",mode:i.mode==="set"?"set":"add",quantity:c(i,"quantity")});return new Map([...s].map(([i,v])=>[i,y(v)]))},upsertCustomer:async t=>n("customers",{provider:t.provider,referenceId:t.referenceId},g(t)),upsertPaymentSession:async t=>n("paymentSessions",{provider:t.provider,providerSessionId:t.id},E(t)),upsertSubscription:async t=>n("subscriptions",{provider:t.provider,providerSubscriptionId:t.id},l(t))}};export{T as createDatabasePaymentStore};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as R}from"@lunora/errors";import{usagePeriodStart as I,resolveEntitlements as v,featureNames as A,hasActivePrice as U}from"./entitlementsForReference-Bq-9UUL8.mjs";import{LunoraPaymentError as d}from"./LunoraPaymentError-BSxyhWgu.mjs";import{derivedIdempotencyKey as g,idempotencyKey as S}from"./idempotencyKey-BjxjMMna.mjs";import{addMoney as D,compareMoney as k}from"./addMoney-B4ufWAnD.mjs";import{n as _}from"./observability-BteZ2dJS.mjs";import B from"./applyWebhookAction-daHKTG_Q.mjs";const y=(o,a=200,s)=>Response.json(o,{headers:{"content-type":"application/json",...s},status:a});let u=0;const K=()=>{const o=Date.now();return u=o>u?o:u+1,u},N=o=>o?`${o.currency}:${String(o.minorUnits)}`:"full",C=o=>o&&"referenceId"in o?Object.fromEntries(Object.entries(o).filter(([a])=>a!=="referenceId")):o,V=o=>{const{adapter:a,store:s}=o,f=async e=>{if(!o.authorize)return;let t;try{t=await o.authorize(e)}catch{throw new d("FORBIDDEN",`caller not authorized for reference "${e}"`)}if(!t)throw new d("FORBIDDEN",`caller not authorized for reference "${e}"`)},p=async e=>{await f(e.referenceId);const t=C(e.metadata);let r;const n=await s.getCustomerByReference(a.identifier,e.referenceId);if(n)r=n.id;else{const m=await a.getOrCreateCustomer({email:e.email,referenceId:e.referenceId});r=m.id,await s.upsertCustomer(m)}const i=e.idempotencyKey??await g("checkout",a.identifier,e.referenceId,e.priceId,e.mode,String(e.quantity??1),e.successUrl,e.cancelUrl,t?JSON.stringify(t):"");return a.createCheckout({...e,customerId:r,idempotencyKey:i,metadata:t})},b=(e,t,r)=>{const n=e-t;return{allowed:n>=r,balance:n,limit:e,unlimited:!1,used:t}},P=async(e,t,r,n,i)=>{const m=e.limit(n);if(m!==void 0){const c=await s.sumUsage(r,n,I(t));return b(m,c,i)}return{allowed:e.has(n),unlimited:e.has(n)}},l=async e=>{const t=()=>new d("NOT_FOUND",`payment session "${e}" not found`);let r=await s.getPaymentSession(a.identifier,e);if(!r)try{r=await a.getPaymentStatus(e)}catch{throw t()}if(!r.referenceId)throw t();try{await f(r.referenceId)}catch{throw t()}return r},w=async(e,t)=>{const r={...e,...t,updatedAt:Date.now()};return await s.upsertPaymentSession(r),r};return{adapter:a,attach:async e=>p({...e,mode:e.mode??"subscription"}),cancelPayment:async(e,t)=>{const r=await l(e),n=t?.idempotencyKey??S("cancel_payment",a.identifier,e),i=await a.cancelPayment(e,{...t,idempotencyKey:n});return w(r,{state:i.state})},cancelSubscription:async(e,t)=>{const r=await s.getSubscription(a.identifier,e);if(!r)throw new d("NOT_FOUND",`subscription "${e}" not found`);try{await f(r.referenceId)}catch{throw new d("NOT_FOUND",`subscription "${e}" not found`)}const n=t?.idempotencyKey??S("cancel_subscription",a.identifier,e),i=await a.cancelSubscription(e,{...t,idempotencyKey:n});return await s.upsertSubscription(i),i},capturePayment:async e=>{const t=await l(e.sessionId),r=e.idempotencyKey??await g("capture_payment",a.identifier,e.sessionId,N(e.amount)),n=await a.capturePayment({...e,idempotencyKey:r});return w(t,{capturedAmount:n.capturedAmount,state:n.state})},check:async e=>{if(await f(e.referenceId),e.featureId===void 0&&e.priceId===void 0)throw new d("CONFIG_INVALID","check() requires a featureId or priceId");if(a.checkEntitlement)return a.checkEntitlement(e);const t=await s.listSubscriptionsByReference(e.referenceId);if(e.priceId!==void 0)return{allowed:U(t,e.priceId),unlimited:!1};if(e.featureId===void 0)throw new d("CONFIG_INVALID","check() requires a featureId or priceId");if(!o.entitlements)throw new d("CONFIG_INVALID","check() requires `entitlements` to be configured");const r=v(o.entitlements,t);return P(r,t,e.referenceId,e.featureId,e.quantity??1)},createCheckout:async e=>p(e),createPortalSession:async(e,t)=>{await f(e);const r=await s.getCustomerByReference(a.identifier,e);if(!r)throw new d("NOT_FOUND",`no customer for reference "${e}"`);return a.createPortalSession({customerId:r.id,returnUrl:t})},handleWebhook:async e=>{let t;try{const n=await e.text();t=await a.parseWebhook({headers:e.headers,payload:n})}catch(n){if(n instanceof d){const{body:i,status:m}=R(n);return y({error:i.message},m)}return y({error:"webhook error"},400)}const r=await B(s,t,o.observability);return r.reason==="orphaned"?y({applied:r.applied,reason:r.reason},500):y({applied:r.applied,reason:r.reason},200)},listBalances:async e=>{if(await f(e),a.getBalances)return a.getBalances(e);if(!o.entitlements)throw new d("CONFIG_INVALID","listBalances() requires `entitlements` to be configured");const t=await s.listSubscriptionsByReference(e),r=v(o.entitlements,t),n=A(o.entitlements),i=n.filter(c=>r.limit(c)!==void 0),m=i.length===0?new Map:await s.sumUsageByFeature(e,i,I(t));return n.map(c=>{const h=r.limit(c);return h!==void 0?{featureId:c,...b(h,m.get(c)??0,1)}:{featureId:c,allowed:r.has(c),unlimited:r.has(c)}})},listSubscriptions:async e=>(await f(e),s.listSubscriptionsByReference(e)),refundPayment:async e=>{const t=await l(e.sessionId),r=e.amount?D(t.refundedAmount,e.amount):t.capturedAmount;if(k(r,t.capturedAmount)>0)throw new d("VALIDATION_ERROR",`refundPayment(): refunding ${String(e.amount?.minorUnits)} would exceed the captured amount on session "${e.sessionId}"`);const n=e.idempotencyKey??await g("refund_payment",a.identifier,e.sessionId,N(e.amount),e.reason??"");return await a.refundPayment({...e,idempotencyKey:n}),w(t,{state:k(r,t.capturedAmount)<0?"partially_refunded":"refunded"})},store:s,track:async e=>{await f(e.referenceId);const t=e.quantity===void 0?1:e.quantity;if(!Number.isSafeInteger(t)||t<0)throw new d("VALIDATION_ERROR",`track(): \`quantity\` must be a non-negative safe integer (got ${String(e.quantity)})`);const r=e.idempotencyKey??crypto.randomUUID(),n=e.mode==="set",i=n?await s.listSubscriptionsByReference(e.referenceId):void 0,m=i===void 0?0:await s.sumUsage(e.referenceId,e.featureId,I(i));if(n?t===m:t===0)return{recorded:!1,reportedToProvider:!1};const c=n?t-m:t;if(!await s.recordUsage({createdAt:K(),featureId:e.featureId,idempotencyKey:r,...n?{mode:"set"}:{},provider:a.identifier,quantity:t,referenceId:e.referenceId,reportedToProvider:!1}))return{recorded:!1,reportedToProvider:!1};if(c<=0||!a.capabilities.usageMetering||!a.reportUsage)return{recorded:!0,reportedToProvider:!1};try{const O=await s.getCustomerByReference(a.identifier,e.referenceId);return await a.reportUsage({customerId:O?.id,featureId:e.featureId,idempotencyKey:r,quantity:c,referenceId:e.referenceId}),await s.markUsageReported(a.identifier,r),{recorded:!0,reportedToProvider:!0}}catch{return _(o.observability,{featureId:e.featureId,provider:a.identifier,referenceId:e.referenceId,type:"usage.report_failed"}),{recorded:!0,reportedToProvider:!1}}}}};export{V as createPayment};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createPayment as n}from"./createPayment-
|
|
1
|
+
import{createPayment as n}from"./createPayment-Dmh6IWLZ.mjs";import{createDatabasePaymentStore as i}from"./createDatabasePaymentStore-BlMXuCW_.mjs";const s=r=>({delete:async t=>r.delete(t),findFirst:async(t,e)=>await r.findFirst(t,{where:e}),findMany:async(t,e)=>(await r.findMany(t,{where:e})).page,insert:async(t,e)=>r.insert(t,e),patch:async(t,e)=>r.patch(t,e)}),m=(r,t)=>{const e=r.auth?.userId??void 0;return n({adapter:t.adapter,authorize:t.authorize??(a=>a.trim()!==""&&e!==void 0&&a===e),entitlements:t.entitlements,observability:t.observability,store:i(s(r.db))})};export{s as lunoraDatabaseToPaymentDatabase,m as paymentsFromContext};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{compareMoney as m}from"./addMoney-
|
|
1
|
+
import{compareMoney as m}from"./addMoney-B4ufWAnD.mjs";import{n as c}from"./observability-BteZ2dJS.mjs";const f=(t,e)=>t.currency===e.currency&&m(t,e)===0,l=(t,e)=>t?.state!==e.state||t.cancelAtPeriodEnd!==e.cancelAtPeriodEnd||t.currentPeriodEnd!==e.currentPeriodEnd||t.priceId!==e.priceId||t.quantity!==e.quantity,y=(t,e)=>t?.state!==e.state||!f(t.capturedAmount,e.capturedAmount)||!f(t.refundedAmount,e.refundedAmount),A=new Set(["partially_refunded","refunded"]),S=(t,e)=>{if(!t)return e;const a=t.refundedAmount.currency===e.refundedAmount.currency&&m(t.refundedAmount,e.refundedAmount)>0?t.refundedAmount:e.refundedAmount,d=e.state==="captured"&&A.has(t.state)?t.state:e.state,r=e.referenceId===""?t.referenceId:e.referenceId;return{...e,referenceId:r,refundedAmount:a,state:d}},b=async(t,e,n,a)=>{const d=await t.getSubscriptionStatus(n),r=await e.getSubscription(t.identifier,n);return l(r,d)?(await e.upsertSubscription({...d,createdAt:r?.createdAt??d.createdAt}),c(a,{id:n,kind:"subscription",provider:t.identifier,type:"reconcile.drift"}),!0):!1},P=async(t,e,n,a)=>{const d=await t.getPaymentStatus(n),r=await e.getPaymentSession(t.identifier,n),s=S(r,d);return y(r,s)?(await e.upsertPaymentSession({...s,createdAt:r?.createdAt??s.createdAt}),c(a,{id:n,kind:"payment",provider:t.identifier,type:"reconcile.drift"}),!0):!1},p=async(t,e,n,a,d)=>{const r=await Promise.allSettled(t.map(i=>n(i)));let s=0,o=0;for(const[i,u]of r.entries())u.status==="fulfilled"?u.value&&(s+=1):(o+=1,c(d,{error:u.reason,id:t[i]??"",kind:e,provider:a.identifier,type:"reconcile.error"}));return{failed:o,updated:s}},v=async t=>{const{adapter:e,observability:n,store:a}=t,d=t.subscriptionIds??[],r=t.paymentSessionIds??[],s=await p(d,"subscription",i=>b(e,a,i,n),e,n),o=await p(r,"payment",i=>P(e,a,i,n),e,n);return c(n,{failedPayments:o.failed,failedSubscriptions:s.failed,provider:e.identifier,type:"reconcile.completed",updatedPayments:o.updated,updatedSubscriptions:s.updated}),{checkedPayments:r.length,checkedSubscriptions:d.length,failedPayments:o.failed,failedSubscriptions:s.failed,updatedPayments:o.updated,updatedSubscriptions:s.updated}};export{v as reconcile};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PaymentAdapter } from "../packem_shared/adapter.d-
|
|
1
|
+
import { P as PaymentAdapter } from "../packem_shared/adapter.d-ov0kaEhj.mjs";
|
|
2
2
|
/**
|
|
3
3
|
* The `autumn-js` SDK surface the adapter uses, as a structural type — a real `Autumn` instance
|
|
4
4
|
* satisfies it without a cast. Resources/methods are `unknown` (the adapter re-types the client as
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PaymentAdapter } from "../packem_shared/adapter.d-
|
|
1
|
+
import { P as PaymentAdapter } from "../packem_shared/adapter.d-ov0kaEhj.js";
|
|
2
2
|
/**
|
|
3
3
|
* The `autumn-js` SDK surface the adapter uses, as a structural type — a real `Autumn` instance
|
|
4
4
|
* satisfies it without a cast. Resources/methods are `unknown` (the adapter re-types the client as
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraPaymentError as O}from"../packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{a as i,r as x,c as o,d as p,e as u}from"../packem_shared/json-BJJPJVYj.mjs";import{money as h}from"../packem_shared/addMoney-
|
|
1
|
+
import{LunoraPaymentError as O}from"../packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{a as i,r as x,c as o,d as p,e as u}from"../packem_shared/json-BJJPJVYj.mjs";import{money as h}from"../packem_shared/addMoney-B4ufWAnD.mjs";import{verifyStandardWebhook as C}from"../packem_shared/constantTimeEqual-Bj5tU-zT.mjs";import{m as D}from"../packem_shared/not-supported-Cl0brzhn.mjs";import{s as E}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const P={active:"active",canceled:"canceled",expired:"canceled",past_due:"past_due",scheduled:"paused",trialing:"trialing"},N={activated:"active",canceled:"canceled",cancelled:"canceled",expired:"canceled",scheduled:"paused"},w="::",y=D("autumn"),f=(a,c)=>`${a}${w}${c}`,g=a=>{const c=a.lastIndexOf(w);if(c===-1)throw new O("PROVIDER_ERROR",`malformed autumn subscription id "${a}" (expected "<customerId>::<productId>")`);return{customerId:a.slice(0,c),productId:a.slice(c+w.length)}},A=a=>u(a,"canceled_at","canceledAt")!==void 0||o(a,"status")==="scheduled",k=(a,c)=>{const r=Date.now(),e=o(c,"id","product_id","productId","plan_id","planId")??"",n=o(c,"status")??"active",t=p(c,"past_due")??p(c,"pastDue")??!1;return{cancelAtPeriodEnd:A(c),createdAt:r,currentPeriodEnd:u(c,"current_period_end","currentPeriodEnd")??void 0,currentPeriodStart:u(c,"current_period_start","currentPeriodStart")??void 0,id:f(a,e),priceId:e,provider:"autumn",quantity:u(c,"quantity")??1,referenceId:a,state:t?"past_due":P[n]??"past_due",updatedAt:r}},S=a=>Array.isArray(a)?a.map(c=>i(c)):[],T=(a,c)=>[...S(a.products),...S(a.subscriptions)].find(e=>(o(e,"id","product_id","productId","plan_id","planId")??"")===c),b=a=>({balance:u(a,"remaining","balance"),limit:u(a,"granted","included_usage","limit"),unlimited:p(a,"unlimited")??!1,used:u(a,"usage","used")}),R=(a,c,r,e)=>{const n=Date.now();return{cancelAtPeriodEnd:e,createdAt:n,id:f(a,c),priceId:c,provider:"autumn",quantity:1,referenceId:a,state:r,updatedAt:n}},v=async(a,c,r)=>{const e=i(await a.customers.get({customerId:c})),n=T(e,r);return n?k(c,n):R(c,r,"canceled",!1)},I=a=>o(a,"customer_id","customerId"),q=(a,c)=>{const r={eventId:a,provider:"autumn",raw:{object:c,type:"billing.updated"}},e=I(c),n=S(c.plan_changes)[0]??c,t=n.subscription?i(n.subscription):n,d=o(t,"plan_id","planId","product_id","productId","id"),s=o(t,"status"),m=o(n,"action"),l=p(t,"past_due")??p(t,"pastDue")??!1,_=s===void 0?void 0:P[s],U=m===void 0?void 0:N[m],B=l?"past_due":_??U;return{...r,cancelAtPeriodEnd:p(t,"cancel_at_period_end")??A(t),currentPeriodEnd:u(t,"current_period_end","currentPeriodEnd"),currentPeriodStart:u(t,"current_period_start","currentPeriodStart"),customerId:e,priceId:d,referenceId:e,subscriptionId:e===void 0||d===void 0?void 0:f(e,d),type:E(B)}},M=(a,c,r)=>{const e={eventId:a,provider:"autumn",raw:{object:r,type:c}},n=o(r,"currency")??"usd";switch(c){case"billing.auto_topup_succeeded":{const t=i(r.invoice),d=u(t,"total","amount")??u(r,"total","amount"),s=o(t,"currency")??n;return{...e,amount:d===void 0?void 0:h(BigInt(Math.round(d)),s),customerId:I(r),referenceId:I(r),sessionId:o(t,"id","stripe_id","invoice_id")??o(r,"id"),type:"payment.captured"}}case"billing.updated":return q(a,r);case"customer.product.added":case"customer.product.canceled":case"customer.product.expired":case"customer.product.updated":case"product.attached":{const t=r.product?i(r.product):r,d=c==="customer.product.canceled"||c==="customer.product.expired"?"canceled":o(t,"status"),s=I(r)??I(t);return{...e,cancelAtPeriodEnd:p(t,"cancel_at_period_end")??A(t),currentPeriodEnd:u(t,"current_period_end","currentPeriodEnd"),currentPeriodStart:u(t,"current_period_start","currentPeriodStart"),customerId:s,priceId:o(t,"id","product_id","productId"),referenceId:s,subscriptionId:s===void 0?void 0:f(s,o(t,"id","product_id","productId")??""),type:E(P[d??""]??"past_due")}}case"invoice.paid":case"payment.succeeded":{const t=u(r,"total","amount","amount_paid");return{...e,amount:t===void 0?void 0:h(BigInt(Math.round(t)),n),customerId:I(r),referenceId:I(r),sessionId:o(r,"id","invoice_id","stripe_id"),type:"payment.captured"}}default:return{...e,type:"unhandled"}}},$=a=>o(a,"checkout_url","checkoutUrl","payment_url","paymentUrl","url")??"",z=a=>{const{webhookSecret:c}=a,r=a.client;return{cancelPayment:()=>y("manual payment cancellation"),cancelSubscription:async(e,n)=>{const{customerId:t,productId:d}=g(e);return await r.billing.update({cancelAction:n?.atPeriodEnd?"cancel_end_of_cycle":"cancel_immediately",customerId:t,planId:d}),n?.atPeriodEnd?{...await v(r,t,d),cancelAtPeriodEnd:!0}:R(t,d,"canceled",!1)},capabilities:{merchantOfRecord:!1,portal:!0,usageMetering:!0},capturePayment:e=>y("manual capture"),checkEntitlement:async e=>{if(e.featureId===void 0){const m=i(await r.customers.get({customerId:e.referenceId})),l=T(m,e.priceId??""),_=l?k(e.referenceId,l).state:void 0;return{allowed:_==="active"||_==="trialing",unlimited:!1}}const n=i(await r.check({customerId:e.referenceId,featureId:e.featureId,requiredBalance:e.quantity??1})),t=p(n,"allowed")??!1,d=n.balance,s=typeof d=="object"&&d!==null?i(d):n;return{allowed:t,...b(s)}},createCheckout:async e=>{const n=i(await r.billing.attach({customerId:e.referenceId,planId:e.priceId}));return{id:f(e.referenceId,e.priceId),provider:"autumn",url:$(n)}},createPortalSession:async e=>{const n=i(await r.billing.openCustomerPortal({customerId:e.customerId}));return{url:o(n,"url")??""}},getBalances:async e=>{const n=i(await r.customers.get({customerId:e})),t=i(n.balances??n.features);return Object.entries(t).map(([d,s])=>{const m=i(s),l=b(m);return{allowed:l.unlimited||(l.balance??0)>0,featureId:o(m,"featureId","feature_id")??d,...l}})},getOrCreateCustomer:async e=>{const n=i(await r.customers.getOrCreate({customerId:e.referenceId,email:e.email,name:e.metadata?.name}));return{createdAt:Date.now(),email:o(n,"email")??e.email,id:o(n,"id")??e.referenceId,provider:"autumn",referenceId:e.referenceId}},getPaymentStatus:()=>y("payment-session reconciliation"),getSubscriptionStatus:async e=>{const{customerId:n,productId:t}=g(e);return v(r,n,t)},identifier:"autumn",parseWebhook:async({headers:e,payload:n})=>{const t=e.get("svix-id")??e.get("webhook-id")??"";await C({payload:n,secret:c,toleranceSeconds:a.webhookToleranceSeconds,webhookId:t,webhookSignature:e.get("svix-signature")??e.get("webhook-signature")??"",webhookTimestamp:e.get("svix-timestamp")??e.get("webhook-timestamp")??""});const d=i(JSON.parse(n));return M(t,x(d,"type")??"",i(d.data))},refundPayment:()=>y("refunds"),reportUsage:async e=>{await r.track({customerId:e.referenceId,featureId:e.featureId,value:e.quantity})},resumeSubscription:async e=>{const{customerId:n,productId:t}=g(e);return await r.billing.update({cancelAction:"uncancel",customerId:n,planId:t}),{...await v(r,n,t),cancelAtPeriodEnd:!1}},updateSubscription:async(e,n)=>{const{customerId:t,productId:d}=g(e),s=n.priceId??d;return await r.billing.attach({customerId:t,planId:s}),v(r,t,s)}}};export{z as createAutumnAdapter};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PaymentAdapter } from "../packem_shared/adapter.d-
|
|
1
|
+
import { P as PaymentAdapter } from "../packem_shared/adapter.d-ov0kaEhj.mjs";
|
|
2
2
|
/**
|
|
3
3
|
* The `creem` SDK surface the adapter uses, as a structural type — a real `Creem` instance satisfies
|
|
4
4
|
* it without a cast. Resources are `unknown` (the adapter re-types the client as the real `Creem`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PaymentAdapter } from "../packem_shared/adapter.d-
|
|
1
|
+
import { P as PaymentAdapter } from "../packem_shared/adapter.d-ov0kaEhj.js";
|
|
2
2
|
/**
|
|
3
3
|
* The `creem` SDK surface the adapter uses, as a structural type — a real `Creem` instance satisfies
|
|
4
4
|
* it without a cast. Resources are `unknown` (the adapter re-types the client as the real `Creem`
|
package/dist/providers/creem.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o,c as u,f as m,r as c,b as p,p as f,d as v,e as w}from"../packem_shared/json-BJJPJVYj.mjs";import{money as I,zeroMoney as g}from"../packem_shared/addMoney-
|
|
1
|
+
import{a as o,c as u,f as m,r as c,b as p,p as f,d as v,e as w}from"../packem_shared/json-BJJPJVYj.mjs";import{money as I,zeroMoney as g}from"../packem_shared/addMoney-B4ufWAnD.mjs";import{verifyCreemSignature as A}from"../packem_shared/constantTimeEqual-Bj5tU-zT.mjs";import{m as E}from"../packem_shared/not-supported-Cl0brzhn.mjs";import{s as P}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const k=/already exists/iu,C={canceled:"canceled",completed:"captured",expired:"canceled",paid:"captured",partially_refunded:"partially_refunded",pending:"initiated",refunded:"refunded"},h={active:"active",canceled:"canceled",cancelled:"canceled",expired:"canceled",incomplete:"past_due",paid:"active",past_due:"past_due",paused:"paused",scheduled_cancel:"active",trialing:"trialing",unpaid:"past_due"},_=E("creem (merchant-of-record)"),i=a=>typeof a=="string"?a:c(o(a),"id"),T=a=>u(a,"checkout_url","checkoutUrl")??"",S=a=>u(a,"canceled_at","canceledAt")!==void 0||c(a,"status")==="scheduled_cancel",b=a=>{if(!(a instanceof Error))return!1;const{statusCode:r}=a;return typeof r=="number"&&r!==400&&r!==409?!1:k.test(a.message)},l=a=>{const r=o(a),t=Date.now(),e=c(r,"status")??"";return{cancelAtPeriodEnd:S(r),createdAt:t,currentPeriodEnd:f(u(r,"current_period_end_date","currentPeriodEndDate")),currentPeriodStart:f(u(r,"current_period_start_date","currentPeriodStartDate")),id:c(r,"id")??"",priceId:i(r.product)??"",provider:"creem",quantity:p(r,"units")??1,referenceId:m(r)??i(r.customer)??"",state:h[e]??"past_due",updatedAt:t}},B=a=>{const r=o(a),t=Date.now(),e=o(r.order),n=c(e,"currency")??c(r,"currency")??"usd",s=I(BigInt(Math.round(p(e,"amount")??p(r,"amount")??0)),n),d=C[c(e,"status")??c(r,"status")??""]??"initiated";return{amount:s,capturedAmount:d==="captured"||d==="partially_refunded"||d==="refunded"?s:g(n),createdAt:t,id:c(r,"id")??"",provider:"creem",referenceId:m(r)??"",refundedAmount:d==="refunded"?s:g(n),state:d,updatedAt:t}},D=(a,r,t)=>{const e={eventId:a,provider:"creem",raw:{object:t,type:r}},n=o(t.order),s=c(n,"currency")??c(t,"currency")??"usd";switch(r){case"checkout.completed":{const d=p(n,"amount")??p(t,"amount");return{...e,amount:d===void 0?void 0:I(BigInt(Math.round(d)),s),customerId:i(t.customer),referenceId:m(t),sessionId:c(t,"id"),subscriptionId:i(t.subscription),type:"payment.captured"}}case"refund.created":{const d=w(t,"refund_amount","refundAmount","amount")??p(n,"amount"),y=u(t,"refund_currency","refundCurrency")??s;return{...e,amount:d===void 0?void 0:I(BigInt(Math.round(d)),y),referenceId:m(t),sessionId:i(t.transaction)??i(t.subscription)??i(t.order)??i(t.checkout)??c(t,"id"),type:"payment.refunded"}}case"subscription.active":case"subscription.canceled":case"subscription.expired":case"subscription.paid":case"subscription.past_due":case"subscription.paused":case"subscription.scheduled_cancel":case"subscription.trialing":case"subscription.unpaid":case"subscription.update":{const d=r==="subscription.scheduled_cancel"?"scheduled_cancel":c(t,"status");return{...e,cancelAtPeriodEnd:v(t,"cancel_at_period_end")??S(t),currentPeriodEnd:f(u(t,"current_period_end_date","currentPeriodEndDate")),currentPeriodStart:f(u(t,"current_period_start_date","currentPeriodStartDate")),customerId:i(t.customer),priceId:i(t.product),referenceId:m(t)??i(t.customer),subscriptionId:c(t,"id"),type:P(h[d??""]??"past_due")}}default:return{...e,type:"unhandled"}}},O=a=>{const{webhookSecret:r}=a,t=a.client;return{cancelPayment:()=>_("manual payment cancellation"),cancelSubscription:async(e,n)=>l(await t.subscriptions.cancel(e,{mode:n?.atPeriodEnd===!0?"scheduled":"immediate"})),capabilities:{merchantOfRecord:!0,portal:!0,usageMetering:!1},capturePayment:e=>_("manual capture"),createCheckout:async e=>{const n=await t.checkouts.create({customer:e.customerId?{id:e.customerId}:void 0,metadata:{...e.metadata,referenceId:e.referenceId},productId:e.priceId,requestId:e.idempotencyKey,successUrl:e.successUrl,units:e.quantity});return{id:c(n,"id")??"",provider:"creem",url:T(n)}},createPortalSession:async e=>{const n=await t.customers.generateBillingLinks({customerId:e.customerId});return{url:u(n,"customer_portal_link","customerPortalLink")??""}},getOrCreateCustomer:async e=>{const n=s=>({createdAt:Date.now(),email:c(s,"email")??e.email,id:c(s,"id")??"",provider:"creem",referenceId:e.referenceId});try{return n(o(await t.customers.create({email:e.email??"",metadata:{...e.metadata,referenceId:e.referenceId},name:e.metadata?.name??e.referenceId})))}catch(s){if(e.email!==void 0&&b(s)){const d=o(await t.customers.retrieve(void 0,e.email));if(m(d)!==e.referenceId)throw new Error(`Creem customer for email "${e.email}" already belongs to a different reference; refusing to bind it to "${e.referenceId}".`,{cause:s});return n(d)}throw s}},getPaymentStatus:async e=>B(await t.checkouts.retrieve(e)),getSubscriptionStatus:async e=>l(await t.subscriptions.get(e)),identifier:"creem",parseWebhook:async({headers:e,payload:n})=>{await A({payload:n,secret:r,signature:e.get("creem-signature")??""});const s=o(JSON.parse(n));return D(u(s,"id","event_id","eventId")??"",u(s,"eventType","type")??"",o(s.object))},refundPayment:()=>_("programmatic refunds"),resumeSubscription:async e=>l(await t.subscriptions.resume(e)),updateSubscription:async(e,n)=>n.priceId?l(await t.subscriptions.upgrade(e,{productId:n.priceId,updateBehavior:"proration-charge-immediately"})):l(await t.subscriptions.get(e))}};export{O as createCreemAdapter};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PaymentAdapter } from "../packem_shared/adapter.d-
|
|
1
|
+
import { P as PaymentAdapter } from "../packem_shared/adapter.d-ov0kaEhj.mjs";
|
|
2
2
|
/**
|
|
3
3
|
* The `dodopayments` SDK surface the adapter uses, as a structural type — a real `DodoPayments`
|
|
4
4
|
* instance satisfies it without a cast. Resources are `unknown` (the adapter re-types the client as
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PaymentAdapter } from "../packem_shared/adapter.d-
|
|
1
|
+
import { P as PaymentAdapter } from "../packem_shared/adapter.d-ov0kaEhj.js";
|
|
2
2
|
/**
|
|
3
3
|
* The `dodopayments` SDK surface the adapter uses, as a structural type — a real `DodoPayments`
|
|
4
4
|
* instance satisfies it without a cast. Resources are `unknown` (the adapter re-types the client as
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraPaymentError as v}from"../packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{idempotencyKey as S}from"../packem_shared/idempotencyKey-BjxjMMna.mjs";import{a as i,b as o,r as a,f as u,p as l,d as w}from"../packem_shared/json-BJJPJVYj.mjs";import{money as _,zeroMoney as f}from"../packem_shared/addMoney-
|
|
1
|
+
import{LunoraPaymentError as v}from"../packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{idempotencyKey as S}from"../packem_shared/idempotencyKey-BjxjMMna.mjs";import{a as i,b as o,r as a,f as u,p as l,d as w}from"../packem_shared/json-BJJPJVYj.mjs";import{money as _,zeroMoney as f}from"../packem_shared/addMoney-B4ufWAnD.mjs";import{verifyStandardWebhook as b}from"../packem_shared/constantTimeEqual-Bj5tU-zT.mjs";import{m as h}from"../packem_shared/not-supported-Cl0brzhn.mjs";import{s as A}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const P={cancelled:"canceled",failed:"failed",partially_captured:"captured",partially_captured_and_capturable:"captured",processing:"initiated",requires_capture:"authorized",requires_confirmation:"initiated",requires_customer_action:"authorized",requires_merchant_action:"authorized",requires_payment_method:"initiated",succeeded:"captured"},g={active:"active",cancelled:"canceled",expired:"canceled",failed:"past_due",on_hold:"past_due",paused:"paused",pending:"past_due"},I=h("dodopayments (merchant-of-record)"),p=d=>a(i(d.customer),"customer_id")??a(d,"customer_id"),m=d=>{const n=i(d),t=Date.now(),e=a(n,"status")??"";return{cancelAtPeriodEnd:w(n,"cancel_at_next_billing_date")??!1,createdAt:t,currentPeriodEnd:l(a(n,"next_billing_date")),currentPeriodStart:l(a(n,"previous_billing_date")),id:a(n,"subscription_id")??"",priceId:a(n,"product_id")??"",provider:"dodopayments",quantity:o(n,"quantity")??1,referenceId:u(n)??p(n)??"",state:g[e]??"past_due",updatedAt:t}},q=d=>{const n=i(d),t=Date.now(),e=a(n,"currency")??"usd",r=_(BigInt(Math.round(o(n,"total_amount")??0)),e),s=P[a(n,"status")??""]??"initiated";return{amount:r,capturedAmount:s==="captured"?r:f(e),createdAt:t,id:a(n,"payment_id")??"",provider:"dodopayments",referenceId:u(n)??"",refundedAmount:f(e),state:s,updatedAt:t}},k=(d,n,t)=>{const e={eventId:d,provider:"dodopayments",raw:{object:t,type:n}},r=a(t,"currency")??"usd";switch(n){case"dispute.lost":case"refund.succeeded":return{...e,amount:_(BigInt(Math.round(o(t,"amount")??0)),r),referenceId:u(t),sessionId:a(t,"payment_id"),type:"payment.refunded"};case"payment.cancelled":case"payment.failed":return{...e,referenceId:u(t),sessionId:a(t,"payment_id"),type:"payment.failed"};case"payment.succeeded":return{...e,amount:_(BigInt(Math.round(o(t,"total_amount")??0)),r),customerId:p(t),referenceId:u(t),sessionId:a(t,"payment_id"),subscriptionId:a(t,"subscription_id"),type:"payment.captured"};case"subscription.active":case"subscription.cancelled":case"subscription.expired":case"subscription.failed":case"subscription.on_hold":case"subscription.paused":case"subscription.plan_changed":case"subscription.renewed":case"subscription.updated":{const s=a(t,"status");return{...e,cancelAtPeriodEnd:w(t,"cancel_at_next_billing_date"),currentPeriodEnd:l(a(t,"next_billing_date")),currentPeriodStart:l(a(t,"previous_billing_date")),customerId:p(t),priceId:a(t,"product_id"),quantity:o(t,"quantity"),referenceId:u(t)??p(t),subscriptionId:a(t,"subscription_id"),type:A(g[s??""]??"past_due")}}default:return{...e,type:"unhandled"}}},R=d=>{const{webhookSecret:n}=d,t=d.client;return{cancelPayment:()=>I("manual payment cancellation"),cancelSubscription:async(e,r)=>{const s=r?.atPeriodEnd?{cancel_at_next_billing_date:!0}:{status:"cancelled"};return m(await t.subscriptions.update(e,s))},capabilities:{merchantOfRecord:!0,portal:!0,usageMetering:!0},capturePayment:e=>I("manual capture"),createCheckout:async e=>{const r=i(await t.checkoutSessions.create({customer:e.customerId?{customer_id:e.customerId}:void 0,metadata:{...e.metadata,referenceId:e.referenceId},product_cart:[{product_id:e.priceId,quantity:e.quantity??1}],return_url:e.successUrl}));return{id:a(r,"session_id")??"",provider:"dodopayments",url:a(r,"checkout_url")??""}},createPortalSession:async e=>{const r=i(await t.customers.customerPortal.create(e.customerId,{return_url:e.returnUrl}));return{url:a(r,"link")??a(r,"url")??""}},getOrCreateCustomer:async e=>{const r=i(await t.customers.create({email:e.email??"",name:e.metadata?.name??e.referenceId},{idempotencyKey:S("customer","dodopayments",e.referenceId)}));return{createdAt:Date.now(),email:a(r,"email")??e.email,id:a(r,"customer_id")??"",provider:"dodopayments",referenceId:e.referenceId}},getPaymentStatus:async e=>q(await t.payments.retrieve(e)),getSubscriptionStatus:async e=>m(await t.subscriptions.retrieve(e)),identifier:"dodopayments",parseWebhook:async({headers:e,payload:r})=>{const s=e.get("webhook-id")??"";await b({payload:r,secret:n,toleranceSeconds:d.webhookToleranceSeconds,webhookId:s,webhookSignature:e.get("webhook-signature")??"",webhookTimestamp:e.get("webhook-timestamp")??""});const c=i(JSON.parse(r));return k(s,a(c,"type")??"",i(c.data))},refundPayment:async e=>{if(e.amount!==void 0)throw new v("PROVIDER_ERROR","dodopayments refunds a payment in full; partial refunds require line items and aren't supported here");const r=i(await t.refunds.create({payment_id:e.sessionId,reason:e.reason})),s=a(r,"currency")??"usd",c=_(BigInt(Math.round(o(r,"amount")??0)),s);let y="captured";return a(r,"status")==="succeeded"&&(y="refunded"),{amount:c,capturedAmount:c,createdAt:Date.now(),id:e.sessionId,provider:"dodopayments",referenceId:"",refundedAmount:c,state:y,updatedAt:Date.now()}},reportUsage:async e=>{await t.usageEvents.ingest({events:[{customer_id:e.customerId??e.referenceId,event_id:e.idempotencyKey,event_name:e.featureId,metadata:{value:e.quantity},timestamp:e.timestamp===void 0?void 0:new Date(e.timestamp).toISOString()}]})},resumeSubscription:async e=>{const r=await t.subscriptions.update(e,{cancel_at_next_billing_date:!1});return m(r)},updateSubscription:async(e,r)=>{if(r.priceId!==void 0||r.quantity!==void 0){const s=i(r.priceId!==void 0&&r.quantity!==void 0?void 0:await t.subscriptions.retrieve(e));await t.subscriptions.changePlan(e,{product_id:r.priceId??a(s,"product_id")??"",proration_billing_mode:"prorated_immediately",quantity:r.quantity??o(s,"quantity")??1})}return m(await t.subscriptions.retrieve(e))}}};export{R as createDodoPaymentsAdapter};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PaymentAdapter } from "../packem_shared/adapter.d-
|
|
1
|
+
import { P as PaymentAdapter } from "../packem_shared/adapter.d-ov0kaEhj.mjs";
|
|
2
2
|
/**
|
|
3
3
|
* The `@polar-sh/sdk` surface the adapter uses, as a structural type — a real `Polar` instance
|
|
4
4
|
* satisfies it without a cast. Resources are `unknown` (the adapter re-types the client as the real
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PaymentAdapter } from "../packem_shared/adapter.d-
|
|
1
|
+
import { P as PaymentAdapter } from "../packem_shared/adapter.d-ov0kaEhj.js";
|
|
2
2
|
/**
|
|
3
3
|
* The `@polar-sh/sdk` surface the adapter uses, as a structural type — a real `Polar` instance
|
|
4
4
|
* satisfies it without a cast. Resources are `unknown` (the adapter re-types the client as the real
|
package/dist/providers/polar.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as p,r as n,f as c,d as w,p as
|
|
1
|
+
import{a as p,r as n,f as c,d as w,p as f,b as i}from"../packem_shared/json-BJJPJVYj.mjs";import{money as m,zeroMoney as I}from"../packem_shared/addMoney-B4ufWAnD.mjs";import{verifyStandardWebhook as P}from"../packem_shared/constantTimeEqual-Bj5tU-zT.mjs";import{m as g}from"../packem_shared/not-supported-Cl0brzhn.mjs";import{s as b}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const y=s=>s instanceof Date?s.getTime():f(typeof s=="string"?s:void 0),S={draft:"initiated",paid:"captured",partially_refunded:"partially_refunded",pending:"initiated",refunded:"refunded",void:"canceled"},A={active:"active",canceled:"canceled",incomplete:"past_due",incomplete_expired:"canceled",past_due:"past_due",trialing:"trialing",unpaid:"past_due"},_=g("polar (merchant-of-record)"),u=s=>{const a=p(s),r=Date.now();return{cancelAtPeriodEnd:w(a,"cancelAtPeriodEnd")??!1,createdAt:r,currentPeriodEnd:y(a.currentPeriodEnd),currentPeriodStart:y(a.currentPeriodStart),id:n(a,"id")??"",priceId:n(a,"productId")??"",provider:"polar",quantity:1,referenceId:c(a)??"",state:A[n(a,"status")??""]??"past_due",updatedAt:r}},v=s=>{const a=p(s),r=Date.now(),e=n(a,"currency")??"usd",t=m(BigInt(Math.round(i(a,"totalAmount")??i(a,"amount")??0)),e),d=S[n(a,"status")??""]??"initiated";return{amount:t,capturedAmount:d==="captured"||d==="partially_refunded"||d==="refunded"?t:I(e),createdAt:r,id:n(a,"id")??"",provider:"polar",referenceId:c(a)??"",refundedAmount:d==="refunded"?t:I(e),state:d,updatedAt:r}},h=(s,a,r)=>{const e={eventId:s,provider:"polar",raw:{object:r,type:a}},t=n(r,"currency")??"usd";switch(a){case"order.created":case"order.paid":return a==="order.created"&&S[n(r,"status")??""]!=="captured"?{...e,type:"unhandled"}:{...e,amount:m(i(r,"total_amount")??i(r,"amount")??0,t),customerId:n(r,"customer_id"),referenceId:c(r),sessionId:n(r,"id"),subscriptionId:n(r,"subscription_id"),type:"payment.captured"};case"refund.created":return{...e,amount:m(i(r,"amount")??0,t),referenceId:c(r),sessionId:n(r,"order_id")??n(r,"id"),type:"payment.refunded"};case"subscription.active":case"subscription.canceled":case"subscription.created":case"subscription.revoked":case"subscription.uncanceled":case"subscription.updated":{const d=a==="subscription.revoked"?"subscription.canceled":b(A[n(r,"status")??""]??"past_due");return{...e,cancelAtPeriodEnd:w(r,"cancel_at_period_end"),currentPeriodEnd:f(n(r,"current_period_end")),currentPeriodStart:f(n(r,"current_period_start")),customerId:n(r,"customer_id"),priceId:n(r,"product_id"),referenceId:c(r),subscriptionId:n(r,"id"),type:d}}default:return{...e,type:"unhandled"}}},M=s=>{const{webhookSecret:a}=s,r=s.client;return{cancelPayment:()=>_("manual payment cancellation"),cancelSubscription:async(e,t)=>{const d=t?.atPeriodEnd?await r.subscriptions.update({id:e,subscriptionUpdate:{cancelAtPeriodEnd:!0}}):await r.subscriptions.revoke({id:e});return u(d)},capabilities:{merchantOfRecord:!0,portal:!0,usageMetering:!0},capturePayment:e=>_("manual capture"),createCheckout:async e=>{const t=await r.checkouts.create({customerEmail:e.customerId?void 0:e.email,customerId:e.customerId,externalCustomerId:e.referenceId,metadata:{...e.metadata,referenceId:e.referenceId},products:[e.priceId],returnUrl:e.cancelUrl,successUrl:e.successUrl});return{id:t.id,provider:"polar",url:t.url}},createPortalSession:async e=>({url:(await r.customerSessions.create({customerId:e.customerId})).customerPortalUrl}),getOrCreateCustomer:async e=>{const t=await r.customers.create({email:e.email??"",externalId:e.referenceId,metadata:{...e.metadata,referenceId:e.referenceId},type:"individual"});return{createdAt:Date.now(),email:t.email??void 0,id:t.id,provider:"polar",referenceId:e.referenceId}},getPaymentStatus:async e=>v(await r.orders.get({id:e})),getSubscriptionStatus:async e=>u(await r.subscriptions.get({id:e})),identifier:"polar",parseWebhook:async({headers:e,payload:t})=>{const d=e.get("webhook-id")??"";await P({payload:t,secret:a,toleranceSeconds:s.webhookToleranceSeconds,webhookId:d,webhookSignature:e.get("webhook-signature")??"",webhookTimestamp:e.get("webhook-timestamp")??""});const o=p(JSON.parse(t));return h(d,n(o,"type")??"",p(o.data))},refundPayment:async e=>{const t=e.amount?void 0:await r.orders.get({id:e.sessionId}),d=e.amount?.currency??t?.currency??"usd",o=e.amount?Number(e.amount.minorUnits):t?.totalAmount??0;await r.refunds.create({amount:o,orderId:e.sessionId,reason:e.reason??"customer_request"});const l=e.amount??m(BigInt(Math.round(o)),d);return{amount:l,capturedAmount:l,createdAt:Date.now(),id:e.sessionId,provider:"polar",referenceId:"",refundedAmount:l,state:"refunded",updatedAt:Date.now()}},reportUsage:async e=>{await r.events.ingest({events:[{externalCustomerId:e.referenceId,metadata:{value:e.quantity},name:e.featureId,timestamp:e.timestamp===void 0?void 0:new Date(e.timestamp)}]})},resumeSubscription:async e=>{const t=await r.subscriptions.update({id:e,subscriptionUpdate:{cancelAtPeriodEnd:!1}});return u(t)},updateSubscription:async(e,t)=>{const d=await r.subscriptions.update({id:e,subscriptionUpdate:t.priceId?{productId:t.priceId}:{}});return u(d)}}};export{M as createPolarAdapter};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PaymentAdapter } from "../packem_shared/adapter.d-
|
|
1
|
+
import { P as PaymentAdapter } from "../packem_shared/adapter.d-ov0kaEhj.mjs";
|
|
2
2
|
/**
|
|
3
3
|
* The Stripe SDK surface the adapter uses, as a structural type — a real `Stripe` instance satisfies
|
|
4
4
|
* it without a cast. Resources are `unknown` here (the adapter re-types the client as the real
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PaymentAdapter } from "../packem_shared/adapter.d-
|
|
1
|
+
import { P as PaymentAdapter } from "../packem_shared/adapter.d-ov0kaEhj.js";
|
|
2
2
|
/**
|
|
3
3
|
* The Stripe SDK surface the adapter uses, as a structural type — a real `Stripe` instance satisfies
|
|
4
4
|
* it without a cast. Resources are `unknown` here (the adapter re-types the client as the real
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraPaymentError as E}from"../packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{idempotencyKey as K}from"../packem_shared/idempotencyKey-BjxjMMna.mjs";import{a as
|
|
1
|
+
import{LunoraPaymentError as E}from"../packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{idempotencyKey as K}from"../packem_shared/idempotencyKey-BjxjMMna.mjs";import{a as m,r as a,d as v,b as o}from"../packem_shared/json-BJJPJVYj.mjs";import{compareMoney as P,money as p,zeroMoney as f}from"../packem_shared/addMoney-B4ufWAnD.mjs";import{s as T}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const q={canceled:"canceled",processing:"authorized",requires_action:"authorized",requires_capture:"authorized",requires_confirmation:"initiated",requires_payment_method:"initiated",succeeded:"captured"},w={active:"active",canceled:"canceled",incomplete:"past_due",incomplete_expired:"canceled",past_due:"past_due",paused:"paused",trialing:"trialing",unpaid:"past_due"},c=s=>a(m(s.metadata),"referenceId")??a(s,"client_reference_id"),I=s=>{const n=m(s.items),t=Array.isArray(n.data)?n.data:[];return m(t[0])},S=s=>a(m(I(s).price),"id"),g=s=>o(I(s),"quantity"),h=s=>{const n=o(I(s),"current_period_end")??o(s,"current_period_end");return n===void 0?void 0:n*1e3},A=s=>{const n=o(I(s),"current_period_start")??o(s,"current_period_start");return n===void 0?void 0:n*1e3},_=s=>{const n=m(s),t=a(n,"currency")??"usd",e=o(n,"amount")??0,r=p(BigInt(Math.round(e)),t),i=q[a(n,"status")??""]??"initiated",d=Date.now();return{amount:r,capturedAmount:i==="captured"?p(BigInt(Math.round(o(n,"amount_received")??e)),t):f(t),createdAt:d,id:a(n,"id")??"",provider:"stripe",referenceId:c(n)??"",refundedAmount:f(t),state:i,updatedAt:d}},l=s=>{const n=m(s),t=Date.now();return{cancelAtPeriodEnd:v(n,"cancel_at_period_end")??!1,createdAt:t,currentPeriodEnd:h(n),currentPeriodStart:A(n),id:a(n,"id")??"",priceId:S(n)??"",provider:"stripe",quantity:g(n)??1,referenceId:c(n)??"",state:w[a(n,"status")??""]??"past_due",updatedAt:t}},M=(s,n,t)=>{const e={eventId:s,provider:"stripe",raw:{object:t,type:n}},r=a(t,"currency")??"usd";switch(n){case"charge.refunded":return{...e,amount:p(BigInt(Math.round(o(t,"amount_refunded")??0)),r),amountKind:"absolute",referenceId:c(t),sessionId:a(t,"payment_intent")??a(t,"id"),type:"payment.refunded"};case"checkout.session.completed":{if(a(t,"mode")==="subscription"){const u=a(t,"payment_status"),y=u==="paid"||u==="no_payment_required";return{...e,customerId:a(t,"customer"),referenceId:c(t),subscriptionId:a(t,"subscription"),type:y?"subscription.active":"subscription.updated"}}const i=a(t,"payment_intent");if(i===void 0&&a(t,"payment_status")!=="no_payment_required")return{...e,type:"unhandled"};const d=o(t,"amount_total");return{...e,amount:d===void 0?void 0:p(BigInt(Math.round(d)),r),customerId:a(t,"customer"),referenceId:c(t),sessionId:i??a(t,"id"),type:"payment.captured"}}case"customer.subscription.created":case"customer.subscription.updated":return{...e,cancelAtPeriodEnd:v(t,"cancel_at_period_end"),currentPeriodEnd:h(t),currentPeriodStart:A(t),customerId:a(t,"customer"),priceId:S(t),quantity:g(t),referenceId:c(t),subscriptionId:a(t,"id"),type:T(w[a(t,"status")??""]??"past_due")};case"customer.subscription.deleted":return{...e,referenceId:c(t),subscriptionId:a(t,"id"),type:"subscription.canceled"};case"payment_intent.amount_capturable_updated":return{...e,amount:p(BigInt(Math.round(o(t,"amount")??0)),r),referenceId:c(t),sessionId:a(t,"id"),type:"payment.authorized"};case"payment_intent.payment_failed":return{...e,referenceId:c(t),sessionId:a(t,"id"),type:"payment.failed"};case"payment_intent.succeeded":return{...e,amount:p(BigInt(Math.round(o(t,"amount_received")??o(t,"amount")??0)),r),customerId:a(t,"customer"),referenceId:c(t),sessionId:a(t,"id"),type:"payment.captured"};default:return{...e,type:"unhandled"}}},z=s=>{const{webhookSecret:n}=s,t=s.client;return{cancelPayment:async(e,r)=>{const i=await t.paymentIntents.cancel(e,void 0,{idempotencyKey:r?.idempotencyKey});return _(i)},cancelSubscription:async(e,r)=>{const i=r?.atPeriodEnd?await t.subscriptions.update(e,{cancel_at_period_end:!0},{idempotencyKey:r.idempotencyKey}):await t.subscriptions.cancel(e,void 0,{idempotencyKey:r?.idempotencyKey});return l(i)},capabilities:{merchantOfRecord:!1,portal:!0,usageMetering:!0},capturePayment:async e=>{const r=await t.paymentIntents.capture(e.sessionId,e.amount?{amount_to_capture:Number(e.amount.minorUnits)}:void 0,{idempotencyKey:e.idempotencyKey});return _(r)},createCheckout:async e=>{const r=await t.checkout.sessions.create({cancel_url:e.cancelUrl,client_reference_id:e.referenceId,customer:e.customerId,line_items:[{price:e.priceId,quantity:e.quantity??1}],metadata:{...e.metadata,referenceId:e.referenceId},mode:e.mode,subscription_data:e.mode==="subscription"?{metadata:{referenceId:e.referenceId}}:void 0,success_url:e.successUrl},{idempotencyKey:e.idempotencyKey});return{id:r.id,provider:"stripe",url:r.url??""}},createPortalSession:async e=>({url:(await t.billingPortal.sessions.create({customer:e.customerId,return_url:e.returnUrl})).url}),getOrCreateCustomer:async e=>{const r=await t.customers.create({email:e.email,metadata:{...e.metadata,referenceId:e.referenceId}},{idempotencyKey:K("customer","stripe",e.referenceId)});return{createdAt:Date.now(),email:r.email??void 0,id:r.id,provider:"stripe",referenceId:e.referenceId}},getPaymentStatus:async e=>_(await t.paymentIntents.retrieve(e)),getSubscriptionStatus:async e=>l(await t.subscriptions.retrieve(e)),identifier:"stripe",parseWebhook:async({headers:e,payload:r})=>{const i=e.get("stripe-signature")??"";let d;try{d=await t.webhooks.constructEventAsync(r,i,n,s.webhookToleranceSeconds)}catch(y){throw new E("WEBHOOK_SIGNATURE_INVALID",y instanceof Error?y.message:"invalid webhook signature")}const u=m(m(d.data).object);return M(d.id,d.type,u)},refundPayment:async e=>{await t.refunds.create({amount:e.amount?Number(e.amount.minorUnits):void 0,payment_intent:e.sessionId,reason:e.reason},{idempotencyKey:e.idempotencyKey});const r=await t.paymentIntents.retrieve(e.sessionId),i=_(r),d=e.amount??i.capturedAmount,u=e.amount!==void 0&&P(e.amount,i.capturedAmount)<0;return{...i,refundedAmount:d,state:u?"partially_refunded":"refunded"}},reportUsage:async e=>{await t.billing.meterEvents.create({event_name:e.featureId,identifier:e.idempotencyKey,payload:{stripe_customer_id:e.customerId??"",value:String(e.quantity)},timestamp:e.timestamp===void 0?void 0:Math.floor(e.timestamp/1e3)},{idempotencyKey:e.idempotencyKey})},resumeSubscription:async e=>{const r=await t.subscriptions.update(e,{cancel_at_period_end:!1});return l(r)},updateSubscription:async(e,r)=>{const i={};if(r.priceId!==void 0||r.quantity!==void 0){const u=await t.subscriptions.retrieve(e);i.items=[{id:u.items.data[0]?.id,price:r.priceId,quantity:r.quantity}]}const d=await t.subscriptions.update(e,i);return l(d)}}};export{z as createStripeAdapter};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const u=(n,e)=>`${n}:${e}`,o=(n,e)=>`${n}:${e}`,c=n=>{const e=n.toSorted((r,t)=>r.createdAt-t.createdAt||r.idempotencyKey.localeCompare(t.idempotencyKey));let s=0;for(const r of e)s=r.mode==="set"?r.quantity:s+r.quantity;return s};class a{customers=new Map;processedEvents=new Set;sessions=new Map;subscriptions=new Map;usageEvents=new Map;getCustomerByReference(e,s){return Promise.resolve(this.customers.get(u(e,s)))}getPaymentSession(e,s){return Promise.resolve(this.sessions.get(o(e,s)))}getSubscription(e,s){return Promise.resolve(this.subscriptions.get(o(e,s)))}listSubscriptionsByReference(e){return Promise.resolve([...this.subscriptions.values()].filter(s=>s.referenceId===e))}markEventProcessed(e,s){const r=o(e,s);return this.processedEvents.has(r)?Promise.resolve(!1):(this.processedEvents.add(r),Promise.resolve(!0))}releaseEvent(e,s){return this.processedEvents.delete(o(e,s)),Promise.resolve()}markUsageReported(e,s){const r=o(e,s),t=this.usageEvents.get(r);return t&&this.usageEvents.set(r,{...t,reportedToProvider:!0}),Promise.resolve()}recordUsage(e){const s=o(e.provider,e.idempotencyKey);return this.usageEvents.has(s)?Promise.resolve(!1):(this.usageEvents.set(s,e),Promise.resolve(!0))}sumUsage(e,s,r){const t=[];for(const i of this.usageEvents.values())i.referenceId===e&&i.featureId===s&&i.createdAt>=r&&t.push(i);return Promise.resolve(c(t))}upsertCustomer(e){return this.customers.set(u(e.provider,e.referenceId),e),Promise.resolve()}upsertPaymentSession(e){return this.sessions.set(o(e.provider,e.id),e),Promise.resolve()}upsertSubscription(e){return this.subscriptions.set(o(e.provider,e.id),e),Promise.resolve()}}export{a as MemoryPaymentStore,c as foldUsage};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toSnapshot as i}from"dinero.js";import{add as m,allocate as a,compare as p,subtract as M,dinero as U}from"dinero.js/bigint";import{LunoraPaymentError as C}from"./LunoraPaymentError-BSxyhWgu.mjs";const D=new Set(["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"]),F=new Set(["BHD","IQD","JOD","KWD","LYD","OMR","TND"]),e=n=>D.has(n)?0n:F.has(n)?3n:2n,f=n=>({base:10n,code:n.toUpperCase(),exponent:e(n.toUpperCase())}),t=n=>U({amount:n.minorUnits,currency:f(n.currency)}),c=n=>{const r=i(n);return{currency:r.currency.code,minorUnits:r.amount}},s=(n,r)=>{if(n.currency!==r.currency)throw new C("CURRENCY_MISMATCH",`cannot combine ${n.currency} with ${r.currency}`)},I=n=>e(n.toUpperCase())===0n,y=(n,r)=>{const o=typeof n=="bigint"?n:BigInt(Math.trunc(n));return{currency:r.toUpperCase(),minorUnits:o}},E=n=>y(0n,n),R=(n,r="en-US")=>{const o=Number(e(n.currency.toUpperCase())),u=Number(n.minorUnits)/10**o;try{return new Intl.NumberFormat(r,{currency:n.currency,style:"currency"}).format(u)}catch{return`${u.toFixed(o)} ${n.currency}`}},d=(n,r)=>(s(n,r),c(m(t(n),t(r)))),w=(n,r)=>(s(n,r),c(M(t(n),t(r)))),O=(n,r)=>(s(n,r),p(t(n),t(r))),x=(n,r)=>a(t(n),[...r]).map(o=>c(o)),A=n=>n.minorUnits===0n,J=n=>({currency:n.currency,minorUnits:n.minorUnits.toString()}),L=n=>y(BigInt(n.minorUnits),n.currency);export{d as addMoney,x as allocateMoney,O as compareMoney,R as formatMoney,L as fromMoneyJSON,I as isZeroDecimalCurrency,A as isZeroMoney,y as money,w as subtractMoney,J as toMoneyJSON,E as zeroMoney};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraPaymentError as v}from"./LunoraPaymentError-BSxyhWgu.mjs";import{compareMoney as l,zeroMoney as c,addMoney as P}from"./addMoney-COE-qM5x.mjs";import{n as o}from"./observability-BteZ2dJS.mjs";import{nextPaymentState as A,nextSubscriptionState as S}from"./PAYMENT_TERMINAL_STATES-DVerjPR6.mjs";const E={"payment.authorized":"authorize","payment.captured":"capture","payment.failed":"fail","payment.refunded":"refund"},_={"subscription.active":"active","subscription.canceled":"canceled","subscription.past_due":"past_due","subscription.paused":"paused"},b={"subscription.active":"activate","subscription.canceled":"cancel","subscription.past_due":"mark_past_due","subscription.paused":"pause"},w=(t,e)=>l(t,e)>0?t:e,I=(t,e)=>{if(!e.amount||t.refundedAmount.currency!==e.amount.currency||t.capturedAmount.currency!==e.amount.currency)return;const r=e.amountKind==="absolute"?w(e.amount,t.refundedAmount):P(t.refundedAmount,e.amount);if(!(l(r,t.capturedAmount)>0))return r},h=async(t,e,r)=>{if(!e.sessionId)return{applied:!1,reason:"unhandled"};const n=await t.getPaymentSession(e.provider,e.sessionId),u=n?.state??"initiated",d=Date.now(),i=e.amount?.currency??n?.amount.currency??"USD";let p=r;if(r==="refund"&&n){const s=I(n,e);s&&l(s,n.capturedAmount)<0&&(p="partial_refund")}const f=A(u,p);if(!f)return{applied:!1,reason:"illegal_transition"};const a=n??{amount:e.amount??c(i),capturedAmount:c(i),createdAt:d,id:e.sessionId,provider:e.provider,referenceId:e.referenceId??"",refundedAmount:c(i),state:u,updatedAt:d};let{capturedAmount:m,refundedAmount:y}=a;if(p==="capture"&&e.amount&&(m=e.amount),(p==="partial_refund"||p==="refund")&&e.amount){const s=I(a,e);if(!s)return{applied:!1,reason:"invalid_refund_amount"};y=s}return await t.upsertPaymentSession({...a,capturedAmount:m,referenceId:e.referenceId??a.referenceId,refundedAmount:y,state:f,updatedAt:d}),{applied:!0,reason:"ok"}},T=async(t,e)=>{if(!e.subscriptionId)return{applied:!1,reason:"unhandled"};const r=await t.getSubscription(e.provider,e.subscriptionId),n=Date.now();if(e.type==="subscription.updated")return r?(await t.upsertSubscription({...r,cancelAtPeriodEnd:e.cancelAtPeriodEnd??r.cancelAtPeriodEnd,currentPeriodEnd:e.currentPeriodEnd??r.currentPeriodEnd,currentPeriodStart:e.currentPeriodStart??r.currentPeriodStart,priceId:e.priceId??r.priceId,quantity:e.quantity??r.quantity,updatedAt:n}),{applied:!0,reason:"ok"}):{applied:!1,reason:"unhandled"};const u=_[e.type];if(!u)return{applied:!1,reason:"unhandled"};if(!r)return await t.upsertSubscription({cancelAtPeriodEnd:e.cancelAtPeriodEnd??!1,createdAt:n,currentPeriodEnd:e.currentPeriodEnd,currentPeriodStart:e.currentPeriodStart??n,id:e.subscriptionId,priceId:e.priceId??"",provider:e.provider,quantity:e.quantity??1,referenceId:e.referenceId??"",state:u,updatedAt:n}),{applied:!0,reason:"ok"};const d=r.state==="active"&&u==="active"?"renew":b[e.type],i=d?S(r.state,d):void 0;return i?(await t.upsertSubscription({...r,cancelAtPeriodEnd:e.cancelAtPeriodEnd??r.cancelAtPeriodEnd,currentPeriodEnd:e.currentPeriodEnd??r.currentPeriodEnd,currentPeriodStart:e.currentPeriodStart??r.currentPeriodStart,priceId:e.priceId??r.priceId,quantity:e.quantity??r.quantity,state:i,updatedAt:n}),{applied:!0,reason:"ok"}):{applied:!1,reason:"illegal_transition"}},N=async(t,e,r)=>{if(e.type==="unhandled")return{applied:!1,reason:"unhandled"};if(!e.eventId?.trim())throw new v("WEBHOOK_EVENT_ID_MISSING",`webhook event id is missing or blank for provider "${e.provider}"`);if(!await t.markEventProcessed(e.provider,e.eventId))return o(r,{eventId:e.eventId,provider:e.provider,type:"webhook.duplicate"}),{applied:!1,reason:"duplicate"};const u=E[e.type];let d;try{d=u?await h(t,e,u):await T(t,e)}catch(i){throw await t.releaseEvent(e.provider,e.eventId),i}return o(r,{action:e.type,eventId:e.eventId,provider:e.provider,reason:d.reason,type:"webhook.applied"}),e.type==="payment.failed"?o(r,{provider:e.provider,referenceId:e.referenceId,sessionId:e.sessionId,type:"payment.failed"}):e.type==="subscription.past_due"&&o(r,{provider:e.provider,referenceId:e.referenceId,subscriptionId:e.subscriptionId,type:"subscription.past_due"}),d};export{N as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{money as u}from"./addMoney-COE-qM5x.mjs";import{foldUsage as m}from"./MemoryPaymentStore-CkXqJEe2.mjs";const i=(e,t)=>typeof e[t]=="string"?e[t]:"",v=(e,t)=>typeof e[t]=="string"?e[t]:void 0,o=(e,t)=>typeof e[t]=="number"?e[t]:0,p=(e,t)=>typeof e[t]=="number"?e[t]:void 0,A=(e,t)=>e[t]===!0,s=(e,t)=>{const r=e[t];return typeof r=="bigint"?r:typeof r=="number"||typeof r=="string"?BigInt(r):0n},I=e=>({createdAt:e.createdAt,email:e.email,provider:e.provider,providerCustomerId:e.id,referenceId:e.referenceId}),g=e=>({createdAt:o(e,"createdAt"),email:v(e,"email"),id:i(e,"providerCustomerId"),provider:i(e,"provider"),referenceId:i(e,"referenceId")}),S=e=>({amountMinor:e.amount.minorUnits,capturedMinor:e.capturedAmount.minorUnits,createdAt:e.createdAt,currency:e.amount.currency,provider:e.provider,providerSessionId:e.id,referenceId:e.referenceId,refundedMinor:e.refundedAmount.minorUnits,state:e.state,updatedAt:e.updatedAt}),P=e=>{const t=i(e,"currency");return{amount:u(s(e,"amountMinor"),t),capturedAmount:u(s(e,"capturedMinor"),t),createdAt:o(e,"createdAt"),id:i(e,"providerSessionId"),provider:i(e,"provider"),referenceId:i(e,"referenceId"),refundedAmount:u(s(e,"refundedMinor"),t),state:i(e,"state"),updatedAt:o(e,"updatedAt")}},l=e=>({cancelAtPeriodEnd:e.cancelAtPeriodEnd,createdAt:e.createdAt,currentPeriodEnd:e.currentPeriodEnd,currentPeriodStart:e.currentPeriodStart,priceId:e.priceId,provider:e.provider,providerSubscriptionId:e.id,quantity:e.quantity,referenceId:e.referenceId,state:e.state,updatedAt:e.updatedAt}),y=e=>({cancelAtPeriodEnd:A(e,"cancelAtPeriodEnd"),createdAt:o(e,"createdAt"),currentPeriodEnd:p(e,"currentPeriodEnd"),currentPeriodStart:p(e,"currentPeriodStart"),id:i(e,"providerSubscriptionId"),priceId:i(e,"priceId"),provider:i(e,"provider"),quantity:o(e,"quantity"),referenceId:i(e,"referenceId"),state:i(e,"state"),updatedAt:o(e,"updatedAt")}),E=e=>({createdAt:e.createdAt,featureId:e.featureId,idempotencyKey:e.idempotencyKey,...e.mode==="set"?{mode:"set"}:{},provider:e.provider,quantity:e.quantity,referenceId:e.referenceId,reportedToProvider:e.reportedToProvider}),x=e=>{const t=async(r,d,n)=>{const a=await e.findFirst(r,d);if(a){await e.patch(a._id,n);return}await e.insert(r,n)};return{getCustomerByReference:async(r,d)=>{const n=await e.findFirst("customers",{provider:r,referenceId:d});return n?g(n):void 0},getPaymentSession:async(r,d)=>{const n=await e.findFirst("paymentSessions",{provider:r,providerSessionId:d});return n?P(n):void 0},getSubscription:async(r,d)=>{const n=await e.findFirst("subscriptions",{provider:r,providerSubscriptionId:d});return n?y(n):void 0},listSubscriptionsByReference:async r=>(await e.findMany("subscriptions",{referenceId:r})).map(n=>y(n)),markEventProcessed:async(r,d)=>await e.findFirst("events",{provider:r,providerEventId:d})?!1:(await e.insert("events",{processedAt:Date.now(),provider:r,providerEventId:d,type:""}),!0),releaseEvent:async(r,d)=>{const n=await e.findFirst("events",{provider:r,providerEventId:d});n&&await e.delete(n._id)},markUsageReported:async(r,d)=>{const n=await e.findFirst("usageEvents",{idempotencyKey:d,provider:r});n&&await e.patch(n._id,{reportedToProvider:!0})},recordUsage:async r=>await e.findFirst("usageEvents",{idempotencyKey:r.idempotencyKey,provider:r.provider})?!1:(await e.insert("usageEvents",E(r)),!0),sumUsage:async(r,d,n)=>{const f=(await e.findMany("usageEvents",{featureId:d,referenceId:r})).filter(c=>o(c,"createdAt")>=n).map(c=>({createdAt:o(c,"createdAt"),idempotencyKey:typeof c.idempotencyKey=="string"?c.idempotencyKey:"",mode:c.mode==="set"?"set":"add",quantity:o(c,"quantity")}));return m(f)},upsertCustomer:async r=>t("customers",{provider:r.provider,providerCustomerId:r.id},I(r)),upsertPaymentSession:async r=>t("paymentSessions",{provider:r.provider,providerSessionId:r.id},S(r)),upsertSubscription:async r=>t("subscriptions",{provider:r.provider,providerSubscriptionId:r.id},l(r))}};export{x as createDatabasePaymentStore};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as v}from"@lunora/errors";import{usagePeriodStart as h,resolveEntitlements as g,featureNames as p,hasActivePrice as k}from"./entitlementsForReference-Bq-9UUL8.mjs";import{LunoraPaymentError as d}from"./LunoraPaymentError-BSxyhWgu.mjs";import{idempotencyKey as N,derivedIdempotencyKey as S}from"./idempotencyKey-BjxjMMna.mjs";import{n as O}from"./observability-BteZ2dJS.mjs";import R from"./applyWebhookAction-B_90qZ1b.mjs";const y=(i,t=200,c)=>Response.json(i,{headers:{"content-type":"application/json",...c},status:t});let m=0;const U=()=>{const i=Date.now();return m=i>m?i:m+1,m},B=i=>i&&"referenceId"in i?Object.fromEntries(Object.entries(i).filter(([t])=>t!=="referenceId")):i,T=i=>{const{adapter:t,store:c}=i,f=async e=>{if(!i.authorize)return;let r;try{r=await i.authorize(e)}catch{throw new d("FORBIDDEN",`caller not authorized for reference "${e}"`)}if(!r)throw new d("FORBIDDEN",`caller not authorized for reference "${e}"`)},w=async e=>{await f(e.referenceId);const r=B(e.metadata);let a;const o=await c.getCustomerByReference(t.identifier,e.referenceId);if(o)a=o.id;else{const s=await t.getOrCreateCustomer({email:e.email,referenceId:e.referenceId});a=s.id,await c.upsertCustomer(s)}const n=e.idempotencyKey??await S("checkout",t.identifier,e.referenceId,e.priceId,e.mode,String(e.quantity??1),e.successUrl,e.cancelUrl,r?JSON.stringify(r):"");return t.createCheckout({...e,customerId:a,idempotencyKey:n,metadata:r})},I=async(e,r,a,o,n)=>{const s=e.limit(o);if(s!==void 0){const l=await c.sumUsage(a,o,h(r)),u=s-l;return{allowed:u>=n,balance:u,limit:s,unlimited:!1,used:l}}return{allowed:e.has(o),unlimited:e.has(o)}};return{adapter:t,attach:async e=>w({...e,mode:e.mode??"subscription"}),cancelSubscription:async(e,r)=>{const a=await c.getSubscription(t.identifier,e);if(!a)throw new d("NOT_FOUND",`subscription "${e}" not found`);try{await f(a.referenceId)}catch{throw new d("NOT_FOUND",`subscription "${e}" not found`)}const o=r?.idempotencyKey??N("cancel_subscription",t.identifier,e),n=await t.cancelSubscription(e,{...r,idempotencyKey:o});return await c.upsertSubscription(n),n},check:async e=>{if(await f(e.referenceId),e.featureId===void 0&&e.priceId===void 0)throw new d("CONFIG_INVALID","check() requires a featureId or priceId");if(t.checkEntitlement)return t.checkEntitlement(e);const r=await c.listSubscriptionsByReference(e.referenceId);if(e.priceId!==void 0)return{allowed:k(r,e.priceId),unlimited:!1};if(e.featureId===void 0)throw new d("CONFIG_INVALID","check() requires a featureId or priceId");if(!i.entitlements)throw new d("CONFIG_INVALID","check() requires `entitlements` to be configured");const a=g(i.entitlements,r);return I(a,r,e.referenceId,e.featureId,e.quantity??1)},createCheckout:async e=>w(e),createPortalSession:async(e,r)=>{await f(e);const a=await c.getCustomerByReference(t.identifier,e);if(!a)throw new d("NOT_FOUND",`no customer for reference "${e}"`);return t.createPortalSession({customerId:a.id,returnUrl:r})},handleWebhook:async e=>{let r;try{const o=await e.text();r=await t.parseWebhook({headers:e.headers,payload:o})}catch(o){if(o instanceof d){const{body:n,status:s}=v(o);return y({error:n.message},s)}return y({error:"webhook error"},400)}const a=await R(c,r,i.observability);return y({applied:a.applied,reason:a.reason},200)},listBalances:async e=>{if(await f(e),t.getBalances)return t.getBalances(e);if(!i.entitlements)throw new d("CONFIG_INVALID","listBalances() requires `entitlements` to be configured");const r=await c.listSubscriptionsByReference(e),a=g(i.entitlements,r);return Promise.all(p(i.entitlements).map(async o=>({featureId:o,...await I(a,r,e,o,1)})))},listSubscriptions:async e=>(await f(e),c.listSubscriptionsByReference(e)),store:c,track:async e=>{await f(e.referenceId);const r=e.quantity===void 0?1:e.quantity;if(!Number.isSafeInteger(r)||r<0)throw new d("VALIDATION_ERROR",`track(): \`quantity\` must be a non-negative safe integer (got ${String(e.quantity)})`);const a=e.idempotencyKey??crypto.randomUUID(),o=e.mode==="set",n=o?await c.listSubscriptionsByReference(e.referenceId):void 0,s=n===void 0?0:await c.sumUsage(e.referenceId,e.featureId,h(n));if(o?r===s:r===0)return{recorded:!1,reportedToProvider:!1};const l=o?r-s:r;if(!await c.recordUsage({createdAt:U(),featureId:e.featureId,idempotencyKey:a,...o?{mode:"set"}:{},provider:t.identifier,quantity:r,referenceId:e.referenceId,reportedToProvider:!1}))return{recorded:!1,reportedToProvider:!1};if(l<=0||!t.capabilities.usageMetering||!t.reportUsage)return{recorded:!0,reportedToProvider:!1};try{const b=await c.getCustomerByReference(t.identifier,e.referenceId);return await t.reportUsage({customerId:b?.id,featureId:e.featureId,idempotencyKey:a,quantity:l,referenceId:e.referenceId}),await c.markUsageReported(t.identifier,a),{recorded:!0,reportedToProvider:!0}}catch{return O(i.observability,{featureId:e.featureId,provider:t.identifier,referenceId:e.referenceId,type:"usage.report_failed"}),{recorded:!0,reportedToProvider:!1}}}}};export{T as createPayment};
|