@lunora/payment 1.0.0-alpha.2 → 1.0.0-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +3 -2
  3. package/__assets__/package-og.svg +1 -1
  4. package/dist/index.d.mts +20 -459
  5. package/dist/index.d.ts +20 -459
  6. package/dist/index.mjs +9 -11
  7. package/dist/packem_shared/{LunoraPaymentError-B3hEzXSs.mjs → LunoraPaymentError-BeQlhkZj.mjs} +4 -7
  8. package/dist/packem_shared/adapter.d-iFA55DzU.d.mts +312 -0
  9. package/dist/packem_shared/adapter.d-iFA55DzU.d.ts +312 -0
  10. package/dist/packem_shared/{addMoney-bCcs1nyw.mjs → addMoney-jSh_7TfF.mjs} +1 -1
  11. package/dist/packem_shared/{applyWebhookAction-DpAqf3Lw.mjs → applyWebhookAction-CLAx4svt.mjs} +1 -1
  12. package/dist/packem_shared/{constantTimeEqual-CfY0jYcL.mjs → constantTimeEqual-BQjoW85H.mjs} +14 -38
  13. package/dist/packem_shared/{createAdapterRegistry-BuDHFCBc.mjs → createAdapterRegistry-Ds7bx_TK.mjs} +1 -1
  14. package/dist/packem_shared/{createDatabasePaymentStore-bYB_HUE6.mjs → createDatabasePaymentStore-C0NUCj1H.mjs} +1 -1
  15. package/dist/packem_shared/{createPayment-BccfPGyw.mjs → createPayment-DzX-ji34.mjs} +17 -5
  16. package/dist/packem_shared/json-DhcPm8EO.mjs +11 -0
  17. package/dist/packem_shared/{lunoraDatabaseToPaymentDatabase-RlKX3Kcd.mjs → lunoraDatabaseToPaymentDatabase-CL2vdAXq.mjs} +2 -2
  18. package/dist/packem_shared/not-supported-C0onRyia.mjs +7 -0
  19. package/dist/packem_shared/{reconcile-CI1ukJF9.mjs → reconcile-Dtn_ErbJ.mjs} +1 -1
  20. package/dist/packem_shared/subscription-event-CwEsWRCK.mjs +17 -0
  21. package/dist/providers/autumn-features.d.mts +94 -0
  22. package/dist/providers/autumn-features.d.ts +94 -0
  23. package/dist/providers/autumn-features.mjs +95 -0
  24. package/dist/providers/autumn.d.mts +19 -0
  25. package/dist/providers/autumn.d.ts +19 -0
  26. package/dist/providers/autumn.mjs +294 -0
  27. package/dist/providers/creem.d.mts +17 -0
  28. package/dist/providers/creem.d.ts +17 -0
  29. package/dist/providers/creem.mjs +205 -0
  30. package/dist/providers/dodopayments.d.mts +21 -0
  31. package/dist/providers/dodopayments.d.ts +21 -0
  32. package/dist/providers/dodopayments.mjs +259 -0
  33. package/dist/providers/polar.d.mts +22 -0
  34. package/dist/providers/polar.d.ts +22 -0
  35. package/dist/{packem_shared/createPolarAdapter-BJtVGSlF.mjs → providers/polar.mjs} +51 -47
  36. package/dist/providers/stripe.d.mts +23 -0
  37. package/dist/providers/stripe.d.ts +23 -0
  38. package/dist/{packem_shared/createStripeAdapter-D40MVBXg.mjs → providers/stripe.mjs} +56 -55
  39. package/package.json +46 -5
  40. package/dist/packem_shared/json-Db337f36.mjs +0 -6
@@ -0,0 +1,312 @@
1
+ /**
2
+ * Core domain types for `@lunora/payment`.
3
+ *
4
+ * The provider is a stateless translator; the store owns all state. These types are the
5
+ * provider-agnostic vocabulary every adapter normalizes onto.
6
+ */
7
+ /** ISO-4217 currency code (uppercase, 3 letters). Not enumerated — provider coverage varies. */
8
+ type CurrencyCode = string;
9
+ /**
10
+ * Money as integer minor units + currency. Always carry the two together.
11
+ *
12
+ * `minorUnits` is a `bigint`, which is **not** JSON-serializable — cross the RPC/wire boundary
13
+ * with the `toMoneyJSON` / `fromMoneyJSON` helpers (see `./money`).
14
+ */
15
+ interface Money {
16
+ readonly currency: CurrencyCode;
17
+ readonly minorUnits: bigint;
18
+ }
19
+ /** Stable provider identifier (Medusa-style). Ships Stripe/Polar/Autumn/Dodo plus Creem, an EU-friendly MoR. */
20
+ type ProviderId = "autumn" | "creem" | "dodopayments" | "polar" | "stripe";
21
+ /** What a provider can do — encoded in types so tax/UX assumptions aren't tribal knowledge. */
22
+ interface ProviderCapabilities {
23
+ /** True for Polar / Lemon Squeezy / Paddle; false for Stripe (PSP) and Autumn (runs on your own Stripe). Drives tax/invoice ownership. */
24
+ readonly merchantOfRecord: boolean;
25
+ /** Native hosted customer/billing portal. */
26
+ readonly portal: boolean;
27
+ /** Usage-based / metered billing. */
28
+ readonly usageMetering: boolean;
29
+ }
30
+ /** Lifecycle state of a one-time payment session. */
31
+ type PaymentState = "authorized" | "canceled" | "captured" | "failed" | "initiated" | "partially_refunded" | "refunded";
32
+ /** Lifecycle state of a subscription. */
33
+ type SubscriptionState = "active" | "canceled" | "past_due" | "paused" | "trialing";
34
+ interface Customer {
35
+ readonly createdAt: number;
36
+ readonly email?: string;
37
+ /** Provider-side customer id. */
38
+ readonly id: string;
39
+ readonly provider: ProviderId;
40
+ /** App-side owner the customer belongs to (user / org / workspace). Opaque to this package. */
41
+ readonly referenceId: string;
42
+ }
43
+ interface PaymentSession {
44
+ readonly amount: Money;
45
+ readonly capturedAmount: Money;
46
+ readonly createdAt: number;
47
+ /** Provider-side payment / intent / session id. */
48
+ readonly id: string;
49
+ readonly provider: ProviderId;
50
+ readonly referenceId: string;
51
+ readonly refundedAmount: Money;
52
+ readonly state: PaymentState;
53
+ readonly updatedAt: number;
54
+ }
55
+ interface Subscription {
56
+ readonly cancelAtPeriodEnd: boolean;
57
+ readonly createdAt: number;
58
+ readonly currentPeriodEnd?: number;
59
+ /** Start of the current billing period — the window `check` sums metered usage over. */
60
+ readonly currentPeriodStart?: number;
61
+ readonly id: string;
62
+ readonly priceId: string;
63
+ readonly provider: ProviderId;
64
+ readonly quantity: number;
65
+ readonly referenceId: string;
66
+ readonly state: SubscriptionState;
67
+ readonly updatedAt: number;
68
+ }
69
+ interface CustomerRef {
70
+ readonly email?: string;
71
+ readonly metadata?: Record<string, string>;
72
+ readonly referenceId: string;
73
+ }
74
+ interface CheckoutInput {
75
+ readonly cancelUrl: string;
76
+ /** Existing provider customer id, if known. */
77
+ readonly customerId?: string;
78
+ /**
79
+ * Customer email, used when the reference has no provider customer yet. Some Merchant-of-Record
80
+ * providers (e.g. Dodo Payments) require an email to mint a customer, so pass it on first checkout.
81
+ */
82
+ readonly email?: string;
83
+ /** Outbound idempotency key for the provider call; auto-derived when omitted. */
84
+ readonly idempotencyKey?: string;
85
+ readonly metadata?: Record<string, string>;
86
+ readonly mode: "payment" | "subscription";
87
+ readonly priceId: string;
88
+ readonly quantity?: number;
89
+ readonly referenceId: string;
90
+ readonly successUrl: string;
91
+ }
92
+ interface CheckoutResult {
93
+ readonly id: string;
94
+ readonly provider: ProviderId;
95
+ readonly url: string;
96
+ }
97
+ /**
98
+ * `attach` input — subscribe a reference to a plan. A thin, plan-oriented skin over
99
+ * {@link CheckoutInput}: `mode` defaults to `"subscription"` (the common case), so callers pass
100
+ * just `{ referenceId, priceId, successUrl, cancelUrl }`.
101
+ */
102
+ interface AttachInput extends Omit<CheckoutInput, "mode"> {
103
+ readonly mode?: CheckoutInput["mode"];
104
+ }
105
+ interface PortalInput {
106
+ readonly customerId: string;
107
+ readonly returnUrl: string;
108
+ }
109
+ /** A single durable usage record — one metered event for a `(referenceId, featureId)` pair. */
110
+ interface UsageEvent {
111
+ readonly createdAt: number;
112
+ readonly featureId: string;
113
+ /** Caller-stable dedupe key — recording the same key twice is a no-op (exactly-once `track`). */
114
+ readonly idempotencyKey: string;
115
+ readonly provider: ProviderId;
116
+ readonly quantity: number;
117
+ readonly referenceId: string;
118
+ /** Whether the event was successfully forwarded to the provider's metering API. */
119
+ readonly reportedToProvider: boolean;
120
+ }
121
+ /** `track` input — record metered usage for a reference's feature. */
122
+ interface TrackInput {
123
+ readonly featureId: string;
124
+ /** Caller-supplied dedupe key; a fresh one is generated when omitted (so each call records). */
125
+ readonly idempotencyKey?: string;
126
+ /** `"add"` (default) increments usage by `quantity`; `"set"` reconciles the period total to `quantity`. */
127
+ readonly mode?: "add" | "set";
128
+ /** Usage amount to add, or the absolute period total when `mode` is `"set"` (defaults to `1`). */
129
+ readonly quantity?: number;
130
+ readonly referenceId: string;
131
+ }
132
+ /** Result of a `track` call. */
133
+ interface TrackResult {
134
+ /** True when this call inserted a new usage event; false when deduplicated by idempotency key. */
135
+ readonly recorded: boolean;
136
+ /** True when the event was forwarded to the provider's metering API. */
137
+ readonly reportedToProvider: boolean;
138
+ }
139
+ /**
140
+ * `check` input — is a reference allowed something right now? Pass `featureId` to check a feature
141
+ * grant/allowance, or `priceId` to check active access to a product (one of the two is required).
142
+ */
143
+ interface CheckInput {
144
+ /** Feature to check a grant/allowance for. Provide this **or** `priceId`. */
145
+ readonly featureId?: string;
146
+ /** Provider price/product id to check active access for. Provide this **or** `featureId`. */
147
+ readonly priceId?: string;
148
+ /** Units the caller intends to consume; the check passes only when this many remain (default `1`). */
149
+ readonly quantity?: number;
150
+ readonly referenceId: string;
151
+ }
152
+ /** Result of a `check` call. */
153
+ interface CheckResult {
154
+ /** Whether the reference may consume `quantity` units of the feature right now. */
155
+ readonly allowed: boolean;
156
+ /** Remaining units this period (`limit - used`), for metered features only. */
157
+ readonly balance?: number;
158
+ /** The plan-granted cap, for metered features only. */
159
+ readonly limit?: number;
160
+ /** True for a boolean feature granted without a numeric cap. */
161
+ readonly unlimited: boolean;
162
+ /** Usage consumed this period, for metered features only. */
163
+ readonly used?: number;
164
+ }
165
+ /** One feature's resolved allowance for a reference — a {@link CheckResult} tagged with its feature. */
166
+ interface FeatureBalance extends CheckResult {
167
+ readonly featureId: string;
168
+ }
169
+ /** Input the adapter forwards to the provider's metering API (Stripe Meter Events / Polar ingestion). */
170
+ interface ReportUsageInput {
171
+ /** Provider customer id, when known (Stripe meter events key on it). */
172
+ readonly customerId?: string;
173
+ readonly featureId: string;
174
+ readonly idempotencyKey: string;
175
+ readonly quantity: number;
176
+ readonly referenceId: string;
177
+ /** Event time in epoch ms; defaults to now at the provider. */
178
+ readonly timestamp?: number;
179
+ }
180
+ interface CaptureInput {
181
+ /** Partial capture amount; full capture when omitted. */
182
+ readonly amount?: Money;
183
+ readonly idempotencyKey?: string;
184
+ readonly sessionId: string;
185
+ }
186
+ interface RefundInput {
187
+ /** Partial refund amount; full refund when omitted. */
188
+ readonly amount?: Money;
189
+ readonly idempotencyKey?: string;
190
+ readonly reason?: string;
191
+ readonly sessionId: string;
192
+ }
193
+ interface CancelSubscriptionOptions {
194
+ /** Cancel at period end instead of immediately. */
195
+ readonly atPeriodEnd?: boolean;
196
+ readonly idempotencyKey?: string;
197
+ }
198
+ interface SubscriptionPatch {
199
+ readonly priceId?: string;
200
+ readonly quantity?: number;
201
+ }
202
+ /** Normalized webhook outcome — the *core state transition* a provider event implies. */
203
+ type WebhookActionType = "payment.authorized" | "payment.captured" | "payment.failed" | "payment.refunded" | "subscription.active" | "subscription.canceled" | "subscription.past_due" | "subscription.paused" | "subscription.updated" | "unhandled";
204
+ /**
205
+ * How a refund action's {@link WebhookAction.amount} should be interpreted by the sync layer.
206
+ *
207
+ * `"delta"` is an incremental amount added to the running refunded total (Polar `refund.created`,
208
+ * and the historical default), so multiple events accumulate. `"absolute"` is the provider's
209
+ * cumulative refunded-to-date total (Stripe `charge.refunded` carries `amount_refunded`, which
210
+ * already sums all prior partial refunds); the sync layer sets the refunded total to this value
211
+ * rather than adding, so repeated partial-refund events do not over-count.
212
+ *
213
+ * Omitted means `"delta"`, preserving the original behavior for callers that predate this field.
214
+ */
215
+ type RefundAmountKind = "absolute" | "delta";
216
+ interface WebhookAction {
217
+ readonly amount?: Money;
218
+ /**
219
+ * Interpretation of {@link WebhookAction.amount} for refund actions (`payment.refunded`).
220
+ * Defaults to `"delta"` when omitted. Ignored for non-refund actions.
221
+ */
222
+ readonly amountKind?: RefundAmountKind;
223
+ readonly cancelAtPeriodEnd?: boolean;
224
+ readonly currentPeriodEnd?: number;
225
+ readonly currentPeriodStart?: number;
226
+ readonly customerId?: string;
227
+ /** Provider event id — the inbound idempotency key. */
228
+ readonly eventId: string;
229
+ readonly priceId?: string;
230
+ readonly provider: ProviderId;
231
+ readonly quantity?: number;
232
+ /** Raw provider event, retained for the events log / debugging. */
233
+ readonly raw?: unknown;
234
+ readonly referenceId?: string;
235
+ readonly sessionId?: string;
236
+ readonly subscriptionId?: string;
237
+ readonly type: WebhookActionType;
238
+ }
239
+ /** Result of applying a webhook action to the store. */
240
+ interface ApplyResult {
241
+ readonly applied: boolean;
242
+ readonly reason?: "duplicate" | "illegal_transition" | "invalid_refund_amount" | "ok" | "unhandled";
243
+ }
244
+ /** A read-only header bag; the platform `Headers` object satisfies it. */
245
+ interface WebhookHeaders {
246
+ get: (name: string) => null | string;
247
+ }
248
+ interface WebhookInput {
249
+ /** Request headers (signature schemes read provider-specific headers from here). */
250
+ readonly headers: WebhookHeaders;
251
+ /** Raw request body, exactly as received (required for signature verification). */
252
+ readonly payload: string;
253
+ }
254
+ /**
255
+ * A stateless translator between the provider API and Lunora's normalized vocabulary.
256
+ *
257
+ * Adapters never own state — they make provider calls and normalize provider events into a
258
+ * `WebhookAction`. All durable state lives in the payment store.
259
+ */
260
+ interface PaymentAdapter {
261
+ cancelPayment: (sessionId: string, options?: {
262
+ idempotencyKey?: string;
263
+ }) => Promise<PaymentSession>;
264
+ cancelSubscription: (subscriptionId: string, options?: CancelSubscriptionOptions) => Promise<Subscription>;
265
+ readonly capabilities: ProviderCapabilities;
266
+ capturePayment: (input: CaptureInput) => Promise<PaymentSession>;
267
+ /**
268
+ * Ask the provider whether a reference may consume `quantity` units of a feature (or holds active
269
+ * access to a product) right now — for providers that own entitlement truth themselves (e.g.
270
+ * Autumn computes balances, credits, and limits from its plan config). Optional: when absent, the
271
+ * facade's `check` evaluates locally from the synced store + the app's `entitlements` config. When
272
+ * present, the facade delegates `check` to it, so `entitlements` need not be configured.
273
+ */
274
+ checkEntitlement?: (input: CheckInput) => Promise<CheckResult>;
275
+ createCheckout: (input: CheckoutInput) => Promise<CheckoutResult>;
276
+ createPortalSession: (input: PortalInput) => Promise<{
277
+ url: string;
278
+ }>;
279
+ /**
280
+ * Resolve every feature allowance for a reference straight from the provider — the optional
281
+ * companion to `checkEntitlement` that powers `listBalances`. Present only on providers that
282
+ * own entitlement truth; when absent, the facade evaluates balances locally from the store + the
283
+ * app's `entitlements` config.
284
+ */
285
+ getBalances?: (referenceId: string) => Promise<FeatureBalance[]>;
286
+ getOrCreateCustomer: (ref: CustomerRef) => Promise<Customer>;
287
+ /** Fetch the provider's current truth for a payment session — the basis for reconciliation. */
288
+ getPaymentStatus: (sessionId: string) => Promise<PaymentSession>;
289
+ /** Fetch the provider's current truth for a subscription — the basis for reconciliation. */
290
+ getSubscriptionStatus: (subscriptionId: string) => Promise<Subscription>;
291
+ /** Stable provider identifier (Medusa-style). */
292
+ readonly identifier: ProviderId;
293
+ /** Verify the signature over the raw body, then normalize the event. Throws on invalid signature. */
294
+ parseWebhook: (input: WebhookInput) => Promise<WebhookAction>;
295
+ refundPayment: (input: RefundInput) => Promise<PaymentSession>;
296
+ /**
297
+ * Forward metered usage to the provider's billing API. Optional — present only on providers
298
+ * whose `capabilities.usageMetering` is `true` and that expose an ingestion endpoint. When
299
+ * absent, `track` still records usage durably and `check` enforces limits locally.
300
+ */
301
+ reportUsage?: (input: ReportUsageInput) => Promise<void>;
302
+ resumeSubscription: (subscriptionId: string) => Promise<Subscription>;
303
+ updateSubscription: (subscriptionId: string, patch: SubscriptionPatch) => Promise<Subscription>;
304
+ }
305
+ /** Registry of adapters keyed by provider id — supports dual-register during provider migration. */
306
+ interface AdapterRegistry {
307
+ all: () => PaymentAdapter[];
308
+ get: (provider: ProviderId) => PaymentAdapter;
309
+ has: (provider: ProviderId) => boolean;
310
+ }
311
+ declare const createAdapterRegistry: (adapters: ReadonlyArray<PaymentAdapter>) => AdapterRegistry;
312
+ export { ApplyResult as A, Customer as C, FeatureBalance as F, Money as M, PaymentAdapter as P, RefundAmountKind 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, CheckInput as f, CheckResult as g, CheckoutInput as h, TrackResult as i, CurrencyCode as j, PaymentState as k, SubscriptionState as l, WebhookAction as m, AdapterRegistry as n, CaptureInput as o, CustomerRef as p, PortalInput as q, ProviderCapabilities as r, RefundInput as s, ReportUsageInput as t, SubscriptionPatch as u, WebhookHeaders as v, WebhookInput as w, createAdapterRegistry as x };
@@ -0,0 +1,312 @@
1
+ /**
2
+ * Core domain types for `@lunora/payment`.
3
+ *
4
+ * The provider is a stateless translator; the store owns all state. These types are the
5
+ * provider-agnostic vocabulary every adapter normalizes onto.
6
+ */
7
+ /** ISO-4217 currency code (uppercase, 3 letters). Not enumerated — provider coverage varies. */
8
+ type CurrencyCode = string;
9
+ /**
10
+ * Money as integer minor units + currency. Always carry the two together.
11
+ *
12
+ * `minorUnits` is a `bigint`, which is **not** JSON-serializable — cross the RPC/wire boundary
13
+ * with the `toMoneyJSON` / `fromMoneyJSON` helpers (see `./money`).
14
+ */
15
+ interface Money {
16
+ readonly currency: CurrencyCode;
17
+ readonly minorUnits: bigint;
18
+ }
19
+ /** Stable provider identifier (Medusa-style). Ships Stripe/Polar/Autumn/Dodo plus Creem, an EU-friendly MoR. */
20
+ type ProviderId = "autumn" | "creem" | "dodopayments" | "polar" | "stripe";
21
+ /** What a provider can do — encoded in types so tax/UX assumptions aren't tribal knowledge. */
22
+ interface ProviderCapabilities {
23
+ /** True for Polar / Lemon Squeezy / Paddle; false for Stripe (PSP) and Autumn (runs on your own Stripe). Drives tax/invoice ownership. */
24
+ readonly merchantOfRecord: boolean;
25
+ /** Native hosted customer/billing portal. */
26
+ readonly portal: boolean;
27
+ /** Usage-based / metered billing. */
28
+ readonly usageMetering: boolean;
29
+ }
30
+ /** Lifecycle state of a one-time payment session. */
31
+ type PaymentState = "authorized" | "canceled" | "captured" | "failed" | "initiated" | "partially_refunded" | "refunded";
32
+ /** Lifecycle state of a subscription. */
33
+ type SubscriptionState = "active" | "canceled" | "past_due" | "paused" | "trialing";
34
+ interface Customer {
35
+ readonly createdAt: number;
36
+ readonly email?: string;
37
+ /** Provider-side customer id. */
38
+ readonly id: string;
39
+ readonly provider: ProviderId;
40
+ /** App-side owner the customer belongs to (user / org / workspace). Opaque to this package. */
41
+ readonly referenceId: string;
42
+ }
43
+ interface PaymentSession {
44
+ readonly amount: Money;
45
+ readonly capturedAmount: Money;
46
+ readonly createdAt: number;
47
+ /** Provider-side payment / intent / session id. */
48
+ readonly id: string;
49
+ readonly provider: ProviderId;
50
+ readonly referenceId: string;
51
+ readonly refundedAmount: Money;
52
+ readonly state: PaymentState;
53
+ readonly updatedAt: number;
54
+ }
55
+ interface Subscription {
56
+ readonly cancelAtPeriodEnd: boolean;
57
+ readonly createdAt: number;
58
+ readonly currentPeriodEnd?: number;
59
+ /** Start of the current billing period — the window `check` sums metered usage over. */
60
+ readonly currentPeriodStart?: number;
61
+ readonly id: string;
62
+ readonly priceId: string;
63
+ readonly provider: ProviderId;
64
+ readonly quantity: number;
65
+ readonly referenceId: string;
66
+ readonly state: SubscriptionState;
67
+ readonly updatedAt: number;
68
+ }
69
+ interface CustomerRef {
70
+ readonly email?: string;
71
+ readonly metadata?: Record<string, string>;
72
+ readonly referenceId: string;
73
+ }
74
+ interface CheckoutInput {
75
+ readonly cancelUrl: string;
76
+ /** Existing provider customer id, if known. */
77
+ readonly customerId?: string;
78
+ /**
79
+ * Customer email, used when the reference has no provider customer yet. Some Merchant-of-Record
80
+ * providers (e.g. Dodo Payments) require an email to mint a customer, so pass it on first checkout.
81
+ */
82
+ readonly email?: string;
83
+ /** Outbound idempotency key for the provider call; auto-derived when omitted. */
84
+ readonly idempotencyKey?: string;
85
+ readonly metadata?: Record<string, string>;
86
+ readonly mode: "payment" | "subscription";
87
+ readonly priceId: string;
88
+ readonly quantity?: number;
89
+ readonly referenceId: string;
90
+ readonly successUrl: string;
91
+ }
92
+ interface CheckoutResult {
93
+ readonly id: string;
94
+ readonly provider: ProviderId;
95
+ readonly url: string;
96
+ }
97
+ /**
98
+ * `attach` input — subscribe a reference to a plan. A thin, plan-oriented skin over
99
+ * {@link CheckoutInput}: `mode` defaults to `"subscription"` (the common case), so callers pass
100
+ * just `{ referenceId, priceId, successUrl, cancelUrl }`.
101
+ */
102
+ interface AttachInput extends Omit<CheckoutInput, "mode"> {
103
+ readonly mode?: CheckoutInput["mode"];
104
+ }
105
+ interface PortalInput {
106
+ readonly customerId: string;
107
+ readonly returnUrl: string;
108
+ }
109
+ /** A single durable usage record — one metered event for a `(referenceId, featureId)` pair. */
110
+ interface UsageEvent {
111
+ readonly createdAt: number;
112
+ readonly featureId: string;
113
+ /** Caller-stable dedupe key — recording the same key twice is a no-op (exactly-once `track`). */
114
+ readonly idempotencyKey: string;
115
+ readonly provider: ProviderId;
116
+ readonly quantity: number;
117
+ readonly referenceId: string;
118
+ /** Whether the event was successfully forwarded to the provider's metering API. */
119
+ readonly reportedToProvider: boolean;
120
+ }
121
+ /** `track` input — record metered usage for a reference's feature. */
122
+ interface TrackInput {
123
+ readonly featureId: string;
124
+ /** Caller-supplied dedupe key; a fresh one is generated when omitted (so each call records). */
125
+ readonly idempotencyKey?: string;
126
+ /** `"add"` (default) increments usage by `quantity`; `"set"` reconciles the period total to `quantity`. */
127
+ readonly mode?: "add" | "set";
128
+ /** Usage amount to add, or the absolute period total when `mode` is `"set"` (defaults to `1`). */
129
+ readonly quantity?: number;
130
+ readonly referenceId: string;
131
+ }
132
+ /** Result of a `track` call. */
133
+ interface TrackResult {
134
+ /** True when this call inserted a new usage event; false when deduplicated by idempotency key. */
135
+ readonly recorded: boolean;
136
+ /** True when the event was forwarded to the provider's metering API. */
137
+ readonly reportedToProvider: boolean;
138
+ }
139
+ /**
140
+ * `check` input — is a reference allowed something right now? Pass `featureId` to check a feature
141
+ * grant/allowance, or `priceId` to check active access to a product (one of the two is required).
142
+ */
143
+ interface CheckInput {
144
+ /** Feature to check a grant/allowance for. Provide this **or** `priceId`. */
145
+ readonly featureId?: string;
146
+ /** Provider price/product id to check active access for. Provide this **or** `featureId`. */
147
+ readonly priceId?: string;
148
+ /** Units the caller intends to consume; the check passes only when this many remain (default `1`). */
149
+ readonly quantity?: number;
150
+ readonly referenceId: string;
151
+ }
152
+ /** Result of a `check` call. */
153
+ interface CheckResult {
154
+ /** Whether the reference may consume `quantity` units of the feature right now. */
155
+ readonly allowed: boolean;
156
+ /** Remaining units this period (`limit - used`), for metered features only. */
157
+ readonly balance?: number;
158
+ /** The plan-granted cap, for metered features only. */
159
+ readonly limit?: number;
160
+ /** True for a boolean feature granted without a numeric cap. */
161
+ readonly unlimited: boolean;
162
+ /** Usage consumed this period, for metered features only. */
163
+ readonly used?: number;
164
+ }
165
+ /** One feature's resolved allowance for a reference — a {@link CheckResult} tagged with its feature. */
166
+ interface FeatureBalance extends CheckResult {
167
+ readonly featureId: string;
168
+ }
169
+ /** Input the adapter forwards to the provider's metering API (Stripe Meter Events / Polar ingestion). */
170
+ interface ReportUsageInput {
171
+ /** Provider customer id, when known (Stripe meter events key on it). */
172
+ readonly customerId?: string;
173
+ readonly featureId: string;
174
+ readonly idempotencyKey: string;
175
+ readonly quantity: number;
176
+ readonly referenceId: string;
177
+ /** Event time in epoch ms; defaults to now at the provider. */
178
+ readonly timestamp?: number;
179
+ }
180
+ interface CaptureInput {
181
+ /** Partial capture amount; full capture when omitted. */
182
+ readonly amount?: Money;
183
+ readonly idempotencyKey?: string;
184
+ readonly sessionId: string;
185
+ }
186
+ interface RefundInput {
187
+ /** Partial refund amount; full refund when omitted. */
188
+ readonly amount?: Money;
189
+ readonly idempotencyKey?: string;
190
+ readonly reason?: string;
191
+ readonly sessionId: string;
192
+ }
193
+ interface CancelSubscriptionOptions {
194
+ /** Cancel at period end instead of immediately. */
195
+ readonly atPeriodEnd?: boolean;
196
+ readonly idempotencyKey?: string;
197
+ }
198
+ interface SubscriptionPatch {
199
+ readonly priceId?: string;
200
+ readonly quantity?: number;
201
+ }
202
+ /** Normalized webhook outcome — the *core state transition* a provider event implies. */
203
+ type WebhookActionType = "payment.authorized" | "payment.captured" | "payment.failed" | "payment.refunded" | "subscription.active" | "subscription.canceled" | "subscription.past_due" | "subscription.paused" | "subscription.updated" | "unhandled";
204
+ /**
205
+ * How a refund action's {@link WebhookAction.amount} should be interpreted by the sync layer.
206
+ *
207
+ * `"delta"` is an incremental amount added to the running refunded total (Polar `refund.created`,
208
+ * and the historical default), so multiple events accumulate. `"absolute"` is the provider's
209
+ * cumulative refunded-to-date total (Stripe `charge.refunded` carries `amount_refunded`, which
210
+ * already sums all prior partial refunds); the sync layer sets the refunded total to this value
211
+ * rather than adding, so repeated partial-refund events do not over-count.
212
+ *
213
+ * Omitted means `"delta"`, preserving the original behavior for callers that predate this field.
214
+ */
215
+ type RefundAmountKind = "absolute" | "delta";
216
+ interface WebhookAction {
217
+ readonly amount?: Money;
218
+ /**
219
+ * Interpretation of {@link WebhookAction.amount} for refund actions (`payment.refunded`).
220
+ * Defaults to `"delta"` when omitted. Ignored for non-refund actions.
221
+ */
222
+ readonly amountKind?: RefundAmountKind;
223
+ readonly cancelAtPeriodEnd?: boolean;
224
+ readonly currentPeriodEnd?: number;
225
+ readonly currentPeriodStart?: number;
226
+ readonly customerId?: string;
227
+ /** Provider event id — the inbound idempotency key. */
228
+ readonly eventId: string;
229
+ readonly priceId?: string;
230
+ readonly provider: ProviderId;
231
+ readonly quantity?: number;
232
+ /** Raw provider event, retained for the events log / debugging. */
233
+ readonly raw?: unknown;
234
+ readonly referenceId?: string;
235
+ readonly sessionId?: string;
236
+ readonly subscriptionId?: string;
237
+ readonly type: WebhookActionType;
238
+ }
239
+ /** Result of applying a webhook action to the store. */
240
+ interface ApplyResult {
241
+ readonly applied: boolean;
242
+ readonly reason?: "duplicate" | "illegal_transition" | "invalid_refund_amount" | "ok" | "unhandled";
243
+ }
244
+ /** A read-only header bag; the platform `Headers` object satisfies it. */
245
+ interface WebhookHeaders {
246
+ get: (name: string) => null | string;
247
+ }
248
+ interface WebhookInput {
249
+ /** Request headers (signature schemes read provider-specific headers from here). */
250
+ readonly headers: WebhookHeaders;
251
+ /** Raw request body, exactly as received (required for signature verification). */
252
+ readonly payload: string;
253
+ }
254
+ /**
255
+ * A stateless translator between the provider API and Lunora's normalized vocabulary.
256
+ *
257
+ * Adapters never own state — they make provider calls and normalize provider events into a
258
+ * `WebhookAction`. All durable state lives in the payment store.
259
+ */
260
+ interface PaymentAdapter {
261
+ cancelPayment: (sessionId: string, options?: {
262
+ idempotencyKey?: string;
263
+ }) => Promise<PaymentSession>;
264
+ cancelSubscription: (subscriptionId: string, options?: CancelSubscriptionOptions) => Promise<Subscription>;
265
+ readonly capabilities: ProviderCapabilities;
266
+ capturePayment: (input: CaptureInput) => Promise<PaymentSession>;
267
+ /**
268
+ * Ask the provider whether a reference may consume `quantity` units of a feature (or holds active
269
+ * access to a product) right now — for providers that own entitlement truth themselves (e.g.
270
+ * Autumn computes balances, credits, and limits from its plan config). Optional: when absent, the
271
+ * facade's `check` evaluates locally from the synced store + the app's `entitlements` config. When
272
+ * present, the facade delegates `check` to it, so `entitlements` need not be configured.
273
+ */
274
+ checkEntitlement?: (input: CheckInput) => Promise<CheckResult>;
275
+ createCheckout: (input: CheckoutInput) => Promise<CheckoutResult>;
276
+ createPortalSession: (input: PortalInput) => Promise<{
277
+ url: string;
278
+ }>;
279
+ /**
280
+ * Resolve every feature allowance for a reference straight from the provider — the optional
281
+ * companion to `checkEntitlement` that powers `listBalances`. Present only on providers that
282
+ * own entitlement truth; when absent, the facade evaluates balances locally from the store + the
283
+ * app's `entitlements` config.
284
+ */
285
+ getBalances?: (referenceId: string) => Promise<FeatureBalance[]>;
286
+ getOrCreateCustomer: (ref: CustomerRef) => Promise<Customer>;
287
+ /** Fetch the provider's current truth for a payment session — the basis for reconciliation. */
288
+ getPaymentStatus: (sessionId: string) => Promise<PaymentSession>;
289
+ /** Fetch the provider's current truth for a subscription — the basis for reconciliation. */
290
+ getSubscriptionStatus: (subscriptionId: string) => Promise<Subscription>;
291
+ /** Stable provider identifier (Medusa-style). */
292
+ readonly identifier: ProviderId;
293
+ /** Verify the signature over the raw body, then normalize the event. Throws on invalid signature. */
294
+ parseWebhook: (input: WebhookInput) => Promise<WebhookAction>;
295
+ refundPayment: (input: RefundInput) => Promise<PaymentSession>;
296
+ /**
297
+ * Forward metered usage to the provider's billing API. Optional — present only on providers
298
+ * whose `capabilities.usageMetering` is `true` and that expose an ingestion endpoint. When
299
+ * absent, `track` still records usage durably and `check` enforces limits locally.
300
+ */
301
+ reportUsage?: (input: ReportUsageInput) => Promise<void>;
302
+ resumeSubscription: (subscriptionId: string) => Promise<Subscription>;
303
+ updateSubscription: (subscriptionId: string, patch: SubscriptionPatch) => Promise<Subscription>;
304
+ }
305
+ /** Registry of adapters keyed by provider id — supports dual-register during provider migration. */
306
+ interface AdapterRegistry {
307
+ all: () => PaymentAdapter[];
308
+ get: (provider: ProviderId) => PaymentAdapter;
309
+ has: (provider: ProviderId) => boolean;
310
+ }
311
+ declare const createAdapterRegistry: (adapters: ReadonlyArray<PaymentAdapter>) => AdapterRegistry;
312
+ export { ApplyResult as A, Customer as C, FeatureBalance as F, Money as M, PaymentAdapter as P, RefundAmountKind 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, CheckInput as f, CheckResult as g, CheckoutInput as h, TrackResult as i, CurrencyCode as j, PaymentState as k, SubscriptionState as l, WebhookAction as m, AdapterRegistry as n, CaptureInput as o, CustomerRef as p, PortalInput as q, ProviderCapabilities as r, RefundInput as s, ReportUsageInput as t, SubscriptionPatch as u, WebhookHeaders as v, WebhookInput as w, createAdapterRegistry as x };
@@ -1,6 +1,6 @@
1
1
  import { toSnapshot } from 'dinero.js';
2
2
  import { add, allocate, compare, subtract, dinero } from 'dinero.js/bigint';
3
- import { LunoraPaymentError } from './LunoraPaymentError-B3hEzXSs.mjs';
3
+ import { LunoraPaymentError } from './LunoraPaymentError-BeQlhkZj.mjs';
4
4
 
5
5
  const ZERO_DECIMAL = /* @__PURE__ */ new Set(["BIF", "CLP", "DJF", "GNF", "JPY", "KMF", "KRW", "MGA", "PYG", "RWF", "UGX", "VND", "VUV", "XAF", "XOF", "XPF"]);
6
6
  const THREE_DECIMAL = /* @__PURE__ */ new Set(["BHD", "IQD", "JOD", "KWD", "LYD", "OMR", "TND"]);
@@ -1,4 +1,4 @@
1
- import { compareMoney, zeroMoney, addMoney } from './addMoney-bCcs1nyw.mjs';
1
+ import { compareMoney, zeroMoney, addMoney } from './addMoney-jSh_7TfF.mjs';
2
2
  import { n as notifyObserver } from './observability-CvhJ205g.mjs';
3
3
  import { nextPaymentState, nextSubscriptionState } from './PAYMENT_TERMINAL_STATES-DrxV0clv.mjs';
4
4