@lunora/payment 1.0.0-alpha.7 → 1.0.0-alpha.71

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 (62) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +5 -2
  3. package/dist/index.d.mts +293 -526
  4. package/dist/index.d.ts +293 -526
  5. package/dist/index.mjs +1 -16
  6. package/dist/packem_shared/LunoraPaymentError-C8uAUIzQ.mjs +1 -0
  7. package/dist/packem_shared/MemoryPaymentStore-CkXqJEe2.mjs +1 -0
  8. package/dist/packem_shared/PAYMENT_TERMINAL_STATES-DVNbZxBy.mjs +1 -0
  9. package/dist/packem_shared/adapter.d-xBfAhqVC.d.mts +445 -0
  10. package/dist/packem_shared/adapter.d-xBfAhqVC.d.ts +445 -0
  11. package/dist/packem_shared/addMoney-BKfsSf0H.mjs +1 -0
  12. package/dist/packem_shared/applyWebhookAction-Bwvycl00.mjs +1 -0
  13. package/dist/packem_shared/constantTimeEqual-B4DP75aY.mjs +1 -0
  14. package/dist/packem_shared/createAdapterRegistry-SoXdsiQd.mjs +1 -0
  15. package/dist/packem_shared/createDatabasePaymentStore-DxChfP5X.mjs +1 -0
  16. package/dist/packem_shared/createPayment-Cj0tRPRZ.mjs +1 -0
  17. package/dist/packem_shared/entitlementsForReference-BbEOKu5d.mjs +1 -0
  18. package/dist/packem_shared/idempotencyKey-CfJKqcE3.mjs +1 -0
  19. package/dist/packem_shared/json-D85Nbd92.mjs +1 -0
  20. package/dist/packem_shared/lunoraDatabaseToPaymentDatabase-CW1VjW4D.mjs +1 -0
  21. package/dist/packem_shared/not-supported-BBbwyP_u.mjs +1 -0
  22. package/dist/packem_shared/observability-C9tz8mj_.mjs +1 -0
  23. package/dist/packem_shared/paymentTables-Be-_11ux.mjs +1 -0
  24. package/dist/packem_shared/reconcile-BjWV0mB0.mjs +1 -0
  25. package/dist/packem_shared/subscription-event-BosLshSM.mjs +1 -0
  26. package/dist/providers/autumn-features.d.mts +129 -0
  27. package/dist/providers/autumn-features.d.ts +129 -0
  28. package/dist/providers/autumn-features.mjs +1 -0
  29. package/dist/providers/autumn.d.mts +28 -0
  30. package/dist/providers/autumn.d.ts +28 -0
  31. package/dist/providers/autumn.mjs +1 -0
  32. package/dist/providers/creem.d.mts +26 -0
  33. package/dist/providers/creem.d.ts +26 -0
  34. package/dist/providers/creem.mjs +1 -0
  35. package/dist/providers/dodopayments.d.mts +30 -0
  36. package/dist/providers/dodopayments.d.ts +30 -0
  37. package/dist/providers/dodopayments.mjs +1 -0
  38. package/dist/providers/polar.d.mts +31 -0
  39. package/dist/providers/polar.d.ts +31 -0
  40. package/dist/providers/polar.mjs +1 -0
  41. package/dist/providers/stripe.d.mts +32 -0
  42. package/dist/providers/stripe.d.ts +32 -0
  43. package/dist/providers/stripe.mjs +1 -0
  44. package/package.json +45 -4
  45. package/dist/packem_shared/LunoraPaymentError-B3hEzXSs.mjs +0 -22
  46. package/dist/packem_shared/MemoryPaymentStore-DvgdWa3C.mjs +0 -72
  47. package/dist/packem_shared/PAYMENT_TERMINAL_STATES-DrxV0clv.mjs +0 -26
  48. package/dist/packem_shared/addMoney-bCcs1nyw.mjs +0 -60
  49. package/dist/packem_shared/applyWebhookAction-DpAqf3Lw.mjs +0 -177
  50. package/dist/packem_shared/constantTimeEqual-CfY0jYcL.mjs +0 -95
  51. package/dist/packem_shared/createAdapterRegistry-BuDHFCBc.mjs +0 -24
  52. package/dist/packem_shared/createDatabasePaymentStore-bYB_HUE6.mjs +0 -172
  53. package/dist/packem_shared/createPayment-BccfPGyw.mjs +0 -190
  54. package/dist/packem_shared/createPolarAdapter-BJtVGSlF.mjs +0 -217
  55. package/dist/packem_shared/createStripeAdapter-D40MVBXg.mjs +0 -270
  56. package/dist/packem_shared/entitlementsForReference-CzZGXPoZ.mjs +0 -51
  57. package/dist/packem_shared/idempotencyKey-BFzDCA7g.mjs +0 -3
  58. package/dist/packem_shared/json-Db337f36.mjs +0 -6
  59. package/dist/packem_shared/lunoraDatabaseToPaymentDatabase-RlKX3Kcd.mjs +0 -29
  60. package/dist/packem_shared/observability-CvhJ205g.mjs +0 -11
  61. package/dist/packem_shared/paymentTables-DccHwWr_.mjs +0 -127
  62. package/dist/packem_shared/reconcile-CI1ukJF9.mjs +0 -73
package/dist/index.mjs CHANGED
@@ -1,16 +1 @@
1
- export { createAdapterRegistry } from './packem_shared/createAdapterRegistry-BuDHFCBc.mjs';
2
- export { lunoraDatabaseToPaymentDatabase, paymentsFromContext } from './packem_shared/lunoraDatabaseToPaymentDatabase-RlKX3Kcd.mjs';
3
- export { createPayment } from './packem_shared/createPayment-BccfPGyw.mjs';
4
- export { createDatabasePaymentStore } from './packem_shared/createDatabasePaymentStore-bYB_HUE6.mjs';
5
- export { entitlementsForReference, featureNames, hasActivePrice, resolveEntitlements, usagePeriodStart } from './packem_shared/entitlementsForReference-CzZGXPoZ.mjs';
6
- export { LunoraPaymentError } from './packem_shared/LunoraPaymentError-B3hEzXSs.mjs';
7
- export { default as idempotencyKey } from './packem_shared/idempotencyKey-BFzDCA7g.mjs';
8
- export { addMoney, allocateMoney, compareMoney, formatMoney, fromMoneyJSON, isZeroDecimalCurrency, isZeroMoney, money, subtractMoney, toMoneyJSON, zeroMoney } from './packem_shared/addMoney-bCcs1nyw.mjs';
9
- export { createPolarAdapter } from './packem_shared/createPolarAdapter-BJtVGSlF.mjs';
10
- export { createStripeAdapter } from './packem_shared/createStripeAdapter-D40MVBXg.mjs';
11
- export { reconcile } from './packem_shared/reconcile-CI1ukJF9.mjs';
12
- export { default as paymentTables } from './packem_shared/paymentTables-DccHwWr_.mjs';
13
- export { PAYMENT_TERMINAL_STATES, SUBSCRIPTION_TERMINAL_STATES, canTransitionPayment, canTransitionSubscription, nextPaymentState, nextSubscriptionState } from './packem_shared/PAYMENT_TERMINAL_STATES-DrxV0clv.mjs';
14
- export { MemoryPaymentStore } from './packem_shared/MemoryPaymentStore-DvgdWa3C.mjs';
15
- export { default as applyWebhookAction } from './packem_shared/applyWebhookAction-DpAqf3Lw.mjs';
16
- export { constantTimeEqual, hmacSha256Hex, parseStripeSignatureHeader, verifyStandardWebhook, verifyStripeSignature } from './packem_shared/constantTimeEqual-CfY0jYcL.mjs';
1
+ import{createAdapterRegistry as r}from"./packem_shared/createAdapterRegistry-SoXdsiQd.mjs";import{lunoraDatabaseToPaymentDatabase as a,paymentsFromContext as n}from"./packem_shared/lunoraDatabaseToPaymentDatabase-CW1VjW4D.mjs";import{createPayment as y}from"./packem_shared/createPayment-Cj0tRPRZ.mjs";import{createDatabasePaymentStore as p}from"./packem_shared/createDatabasePaymentStore-DxChfP5X.mjs";import{entitlementsForReference as s,featureNames as c,hasActivePrice as x,resolveEntitlements as S,usagePeriodStart as l}from"./packem_shared/entitlementsForReference-BbEOKu5d.mjs";import{LunoraPaymentError as T}from"./packem_shared/LunoraPaymentError-C8uAUIzQ.mjs";import{idempotencyKey as P}from"./packem_shared/idempotencyKey-CfJKqcE3.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-BKfsSf0H.mjs";import{reconcile as L}from"./packem_shared/reconcile-BjWV0mB0.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-DVNbZxBy.mjs";import{MemoryPaymentStore as K}from"./packem_shared/MemoryPaymentStore-CkXqJEe2.mjs";import{default as Y}from"./packem_shared/applyWebhookAction-Bwvycl00.mjs";import{constantTimeEqual as w,hmacSha256Hex as G,verifyCreemSignature as Q,verifyStandardWebhook as V}from"./packem_shared/constantTimeEqual-B4DP75aY.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
+ import{LunoraError as N}from"@lunora/errors";const O={CONFIG_INVALID:500,CURRENCY_MISMATCH:400,FORBIDDEN:403,INVALID_TRANSITION:409,NOT_FOUND:404,PROVIDER_ERROR:502,VALIDATION_ERROR:400,WEBHOOK_EVENT_ID_MISSING:400,WEBHOOK_SIGNATURE_INVALID:400,WEBHOOK_TIMESTAMP_INVALID:400};class _ extends N{constructor(I,r){super(I,r,{name:"LunoraPaymentError",status:O[I]})}}export{_ as LunoraPaymentError};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
1
+ const c={authorized:{cancel:"canceled",capture:"captured",fail:"failed"},canceled:{},captured:{partial_refund:"partially_refunded",refund:"refunded"},failed:{},initiated:{authorize:"authorized",cancel:"canceled",capture:"captured",fail:"failed"},partially_refunded:{partial_refund:"partially_refunded",refund:"refunded"},refunded:{}},d={active:{cancel:"canceled",mark_past_due:"past_due",pause:"paused",renew:"active"},canceled:{},past_due:{activate:"active",cancel:"canceled",pause:"paused",renew:"active"},paused:{cancel:"canceled",resume:"active"},trialing:{activate:"active",cancel:"canceled",mark_past_due:"past_due"}},i=new Set(["canceled","failed","refunded"]),r=new Set(["canceled"]),n=(e,a)=>c[e][a],u=(e,a)=>n(e,a)!==void 0,t=(e,a)=>d[e][a],l=(e,a)=>t(e,a)!==void 0;export{i as PAYMENT_TERMINAL_STATES,r as SUBSCRIPTION_TERMINAL_STATES,u as canTransitionPayment,l as canTransitionSubscription,n as nextPaymentState,t as nextSubscriptionState};
@@ -0,0 +1,445 @@
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
+ /**
8
+ * ISO-4217 currency code (uppercase, 3 letters). Not enumerated — provider coverage varies.
9
+ * @experimental
10
+ */
11
+ type CurrencyCode = string;
12
+ /**
13
+ * Money as integer minor units + currency. Always carry the two together.
14
+ *
15
+ * `minorUnits` is a `bigint`, which is **not** JSON-serializable — cross the RPC/wire boundary
16
+ * with the `toMoneyJSON` / `fromMoneyJSON` helpers (see `./money`).
17
+ * @experimental
18
+ */
19
+ interface Money {
20
+ readonly currency: CurrencyCode;
21
+ readonly minorUnits: bigint;
22
+ }
23
+ /**
24
+ * Stable provider identifier (Medusa-style). Ships Stripe/Polar/Autumn/Dodo plus Creem, an EU-friendly MoR.
25
+ * @experimental
26
+ */
27
+ type ProviderId = "autumn" | "creem" | "dodopayments" | "polar" | "stripe";
28
+ /**
29
+ * What a provider can do — encoded in types so tax/UX assumptions aren't tribal knowledge.
30
+ * @experimental
31
+ */
32
+ interface ProviderCapabilities {
33
+ /** True for Polar / Lemon Squeezy / Paddle; false for Stripe (PSP) and Autumn (runs on your own Stripe). Drives tax/invoice ownership. */
34
+ readonly merchantOfRecord: boolean;
35
+ /** Native hosted customer/billing portal. */
36
+ readonly portal: boolean;
37
+ /** Usage-based / metered billing. */
38
+ readonly usageMetering: boolean;
39
+ }
40
+ /**
41
+ * Lifecycle state of a one-time payment session.
42
+ * @experimental
43
+ */
44
+ type PaymentState = "authorized" | "canceled" | "captured" | "failed" | "initiated" | "partially_refunded" | "refunded";
45
+ /**
46
+ * Lifecycle state of a subscription.
47
+ * @experimental
48
+ */
49
+ type SubscriptionState = "active" | "canceled" | "past_due" | "paused" | "trialing";
50
+ /**
51
+ * `Customer` is part of the experimental `@lunora/payment` API and may change without a major version bump.
52
+ * @experimental
53
+ */
54
+ interface Customer {
55
+ readonly createdAt: number;
56
+ readonly email?: string;
57
+ /** Provider-side customer id. */
58
+ readonly id: string;
59
+ readonly provider: ProviderId;
60
+ /** App-side owner the customer belongs to (user / org / workspace). Opaque to this package. */
61
+ readonly referenceId: string;
62
+ }
63
+ /**
64
+ * `PaymentSession` is part of the experimental `@lunora/payment` API and may change without a major version bump.
65
+ * @experimental
66
+ */
67
+ interface PaymentSession {
68
+ readonly amount: Money;
69
+ readonly capturedAmount: Money;
70
+ readonly createdAt: number;
71
+ /** Provider-side payment / intent / session id. */
72
+ readonly id: string;
73
+ readonly provider: ProviderId;
74
+ readonly referenceId: string;
75
+ readonly refundedAmount: Money;
76
+ readonly state: PaymentState;
77
+ readonly updatedAt: number;
78
+ }
79
+ /**
80
+ * `Subscription` is part of the experimental `@lunora/payment` API and may change without a major version bump.
81
+ * @experimental
82
+ */
83
+ interface Subscription {
84
+ readonly cancelAtPeriodEnd: boolean;
85
+ readonly createdAt: number;
86
+ readonly currentPeriodEnd?: number;
87
+ /** Start of the current billing period — the window `check` sums metered usage over. */
88
+ readonly currentPeriodStart?: number;
89
+ readonly id: string;
90
+ readonly priceId: string;
91
+ readonly provider: ProviderId;
92
+ readonly quantity: number;
93
+ readonly referenceId: string;
94
+ readonly state: SubscriptionState;
95
+ readonly updatedAt: number;
96
+ }
97
+ /**
98
+ * `CustomerRef` is part of the experimental `@lunora/payment` API and may change without a major version bump.
99
+ * @experimental
100
+ */
101
+ interface CustomerRef {
102
+ readonly email?: string;
103
+ readonly metadata?: Record<string, string>;
104
+ readonly referenceId: string;
105
+ }
106
+ /**
107
+ * `CheckoutInput` is part of the experimental `@lunora/payment` API and may change without a major version bump.
108
+ * @experimental
109
+ */
110
+ interface CheckoutInput {
111
+ readonly cancelUrl: string;
112
+ /**
113
+ * Ignored at runtime (kept for backward-compat). The provider customer is always derived from the store for the
114
+ * authorized `referenceId` (never caller-supplied) to prevent cross-tenant checkout attachment (IDOR).
115
+ * Retained on the type only for backward compatibility; setting it has no effect.
116
+ */
117
+ readonly customerId?: string;
118
+ /**
119
+ * Customer email, used when the reference has no provider customer yet. Some Merchant-of-Record
120
+ * providers (e.g. Dodo Payments) require an email to mint a customer, so pass it on first checkout.
121
+ */
122
+ readonly email?: string;
123
+ /** Outbound idempotency key for the provider call; auto-derived when omitted. */
124
+ readonly idempotencyKey?: string;
125
+ readonly metadata?: Record<string, string>;
126
+ readonly mode: "payment" | "subscription";
127
+ readonly priceId: string;
128
+ readonly quantity?: number;
129
+ readonly referenceId: string;
130
+ readonly successUrl: string;
131
+ }
132
+ /**
133
+ * `CheckoutResult` is part of the experimental `@lunora/payment` API and may change without a major version bump.
134
+ * @experimental
135
+ */
136
+ interface CheckoutResult {
137
+ readonly id: string;
138
+ readonly provider: ProviderId;
139
+ readonly url: string;
140
+ }
141
+ /**
142
+ * `attach` input — subscribe a reference to a plan. A thin, plan-oriented skin over
143
+ * {@link CheckoutInput}: `mode` defaults to `"subscription"` (the common case), so callers pass
144
+ * just `{ referenceId, priceId, successUrl, cancelUrl }`.
145
+ * @experimental
146
+ */
147
+ interface AttachInput extends Omit<CheckoutInput, "mode"> {
148
+ readonly mode?: CheckoutInput["mode"];
149
+ }
150
+ /**
151
+ * `PortalInput` is part of the experimental `@lunora/payment` API and may change without a major version bump.
152
+ * @experimental
153
+ */
154
+ interface PortalInput {
155
+ readonly customerId: string;
156
+ readonly returnUrl: string;
157
+ }
158
+ /**
159
+ * A single durable usage record — one metered event for a `(referenceId, featureId)` pair.
160
+ * @experimental
161
+ */
162
+ interface UsageEvent {
163
+ readonly createdAt: number;
164
+ readonly featureId: string;
165
+ /** Caller-stable dedupe key — recording the same key twice is a no-op (exactly-once `track`). */
166
+ readonly idempotencyKey: string;
167
+ /**
168
+ * How the period total absorbs this event: `"add"` (the default, and the value
169
+ * assumed for rows written before this field existed) increments it, `"set"`
170
+ * RESETS it to `quantity` and discards everything recorded earlier in the
171
+ * period.
172
+ *
173
+ * The ledger stays append-only either way — a `"set"` is a marker, not a
174
+ * computed delta — which is what makes `track({ mode: "set" })` safe to call
175
+ * concurrently. `PaymentStore.sumUsage` (via `foldUsage`) applies the fold.
176
+ */
177
+ readonly mode?: "add" | "set";
178
+ readonly provider: ProviderId;
179
+ /** For `"add"`, the increment. For `"set"`, the absolute period total this event declares. */
180
+ readonly quantity: number;
181
+ readonly referenceId: string;
182
+ /** Whether the event was successfully forwarded to the provider's metering API. */
183
+ readonly reportedToProvider: boolean;
184
+ }
185
+ /**
186
+ * `track` input — record metered usage for a reference's feature.
187
+ * @experimental
188
+ */
189
+ interface TrackInput {
190
+ readonly featureId: string;
191
+ /** Caller-supplied dedupe key; a fresh one is generated when omitted (so each call records). */
192
+ readonly idempotencyKey?: string;
193
+ /**
194
+ * `"add"` (default) increments usage by `quantity`; `"set"` reconciles the period total to `quantity`.
195
+ *
196
+ * Both are a single append: a `"set"` records the absolute target as a marker that the period fold
197
+ * resets to, rather than reading the current total and appending a delta. Concurrent `"set"` calls
198
+ * for the same reference therefore resolve last-writer-wins instead of over- or under-counting, and
199
+ * a replayed `"set"` is idempotent — neither mode needs a serialized context or a per-reference lock.
200
+ */
201
+ readonly mode?: "add" | "set";
202
+ /**
203
+ * Usage amount to add, or the absolute period total when `mode` is `"set"` (defaults to `1`).
204
+ * Must be a non-negative safe integer — a negative value would drive the summed period usage
205
+ * below zero and hand the reference an unbounded metered balance, so it is rejected.
206
+ */
207
+ readonly quantity?: number;
208
+ readonly referenceId: string;
209
+ }
210
+ /**
211
+ * Result of a `track` call.
212
+ * @experimental
213
+ */
214
+ interface TrackResult {
215
+ /** True when this call inserted a new usage event; false when deduplicated by idempotency key. */
216
+ readonly recorded: boolean;
217
+ /** True when the event was forwarded to the provider's metering API. */
218
+ readonly reportedToProvider: boolean;
219
+ }
220
+ /**
221
+ * `check` input — is a reference allowed something right now? Pass `featureId` to check a feature
222
+ * grant/allowance, or `priceId` to check active access to a product (one of the two is required).
223
+ * @experimental
224
+ */
225
+ interface CheckInput {
226
+ /** Feature to check a grant/allowance for. Provide this **or** `priceId`. */
227
+ readonly featureId?: string;
228
+ /** Provider price/product id to check active access for. Provide this **or** `featureId`. */
229
+ readonly priceId?: string;
230
+ /** Units the caller intends to consume; the check passes only when this many remain (default `1`). */
231
+ readonly quantity?: number;
232
+ readonly referenceId: string;
233
+ }
234
+ /**
235
+ * Result of a `check` call.
236
+ * @experimental
237
+ */
238
+ interface CheckResult {
239
+ /** Whether the reference may consume `quantity` units of the feature right now. */
240
+ readonly allowed: boolean;
241
+ /** Remaining units this period (`limit - used`), for metered features only. */
242
+ readonly balance?: number;
243
+ /** The plan-granted cap, for metered features only. */
244
+ readonly limit?: number;
245
+ /** True for a boolean feature granted without a numeric cap. */
246
+ readonly unlimited: boolean;
247
+ /** Usage consumed this period, for metered features only. */
248
+ readonly used?: number;
249
+ }
250
+ /**
251
+ * One feature's resolved allowance for a reference — a {@link CheckResult} tagged with its feature.
252
+ * @experimental
253
+ */
254
+ interface FeatureBalance extends CheckResult {
255
+ readonly featureId: string;
256
+ }
257
+ /**
258
+ * Input the adapter forwards to the provider's metering API (Stripe Meter Events / Polar ingestion).
259
+ * @experimental
260
+ */
261
+ interface ReportUsageInput {
262
+ /** Provider customer id, when known (Stripe meter events key on it). */
263
+ readonly customerId?: string;
264
+ readonly featureId: string;
265
+ readonly idempotencyKey: string;
266
+ readonly quantity: number;
267
+ readonly referenceId: string;
268
+ /** Event time in epoch ms; defaults to now at the provider. */
269
+ readonly timestamp?: number;
270
+ }
271
+ /**
272
+ * `CaptureInput` is part of the experimental `@lunora/payment` API and may change without a major version bump.
273
+ * @experimental
274
+ */
275
+ interface CaptureInput {
276
+ /** Partial capture amount; full capture when omitted. */
277
+ readonly amount?: Money;
278
+ readonly idempotencyKey?: string;
279
+ readonly sessionId: string;
280
+ }
281
+ /**
282
+ * `RefundInput` is part of the experimental `@lunora/payment` API and may change without a major version bump.
283
+ * @experimental
284
+ */
285
+ interface RefundInput {
286
+ /** Partial refund amount; full refund when omitted. */
287
+ readonly amount?: Money;
288
+ readonly idempotencyKey?: string;
289
+ readonly reason?: string;
290
+ readonly sessionId: string;
291
+ }
292
+ /**
293
+ * `CancelSubscriptionOptions` is part of the experimental `@lunora/payment` API and may change without a major version bump.
294
+ * @experimental
295
+ */
296
+ interface CancelSubscriptionOptions {
297
+ /** Cancel at period end instead of immediately. */
298
+ readonly atPeriodEnd?: boolean;
299
+ readonly idempotencyKey?: string;
300
+ }
301
+ /**
302
+ * `SubscriptionPatch` is part of the experimental `@lunora/payment` API and may change without a major version bump.
303
+ * @experimental
304
+ */
305
+ interface SubscriptionPatch {
306
+ readonly priceId?: string;
307
+ readonly quantity?: number;
308
+ }
309
+ /**
310
+ * Normalized webhook outcome — the *core state transition* a provider event implies.
311
+ * @experimental
312
+ */
313
+ type WebhookActionType = "payment.authorized" | "payment.captured" | "payment.failed" | "payment.refunded" | "subscription.active" | "subscription.canceled" | "subscription.past_due" | "subscription.paused" | "subscription.updated" | "unhandled";
314
+ /**
315
+ * How a refund action's {@link WebhookAction.amount} should be interpreted by the sync layer.
316
+ *
317
+ * `"delta"` is an incremental amount added to the running refunded total (Polar `refund.created`,
318
+ * and the historical default), so multiple events accumulate. `"absolute"` is the provider's
319
+ * cumulative refunded-to-date total (Stripe `charge.refunded` carries `amount_refunded`, which
320
+ * already sums all prior partial refunds); the sync layer sets the refunded total to this value
321
+ * rather than adding, so repeated partial-refund events do not over-count.
322
+ *
323
+ * Omitted means `"delta"`, preserving the original behavior for callers that predate this field.
324
+ * @experimental
325
+ */
326
+ type RefundAmountKind = "absolute" | "delta";
327
+ /**
328
+ * `WebhookAction` is part of the experimental `@lunora/payment` API and may change without a major version bump.
329
+ * @experimental
330
+ */
331
+ interface WebhookAction {
332
+ readonly amount?: Money;
333
+ /**
334
+ * Interpretation of {@link WebhookAction.amount} for refund actions (`payment.refunded`).
335
+ * Defaults to `"delta"` when omitted. Ignored for non-refund actions.
336
+ */
337
+ readonly amountKind?: RefundAmountKind;
338
+ readonly cancelAtPeriodEnd?: boolean;
339
+ readonly currentPeriodEnd?: number;
340
+ readonly currentPeriodStart?: number;
341
+ readonly customerId?: string;
342
+ /** Provider event id — the inbound idempotency key. */
343
+ readonly eventId: string;
344
+ readonly priceId?: string;
345
+ readonly provider: ProviderId;
346
+ readonly quantity?: number;
347
+ /** Raw provider event, retained for the events log / debugging. */
348
+ readonly raw?: unknown;
349
+ readonly referenceId?: string;
350
+ readonly sessionId?: string;
351
+ readonly subscriptionId?: string;
352
+ readonly type: WebhookActionType;
353
+ }
354
+ /**
355
+ * Result of applying a webhook action to the store.
356
+ * @experimental
357
+ */
358
+ interface ApplyResult {
359
+ readonly applied: boolean;
360
+ readonly reason?: "duplicate" | "illegal_transition" | "invalid_refund_amount" | "ok" | "unhandled";
361
+ }
362
+ /**
363
+ * A read-only header bag; the platform `Headers` object satisfies it.
364
+ * @experimental
365
+ */
366
+ interface WebhookHeaders {
367
+ get: (name: string) => null | string;
368
+ }
369
+ /**
370
+ * `WebhookInput` is part of the experimental `@lunora/payment` API and may change without a major version bump.
371
+ * @experimental
372
+ */
373
+ interface WebhookInput {
374
+ /** Request headers (signature schemes read provider-specific headers from here). */
375
+ readonly headers: WebhookHeaders;
376
+ /** Raw request body, exactly as received (required for signature verification). */
377
+ readonly payload: string;
378
+ }
379
+ /**
380
+ * A stateless translator between the provider API and Lunora's normalized vocabulary.
381
+ *
382
+ * Adapters never own state — they make provider calls and normalize provider events into a
383
+ * `WebhookAction`. All durable state lives in the payment store.
384
+ * @experimental
385
+ */
386
+ interface PaymentAdapter {
387
+ cancelPayment: (sessionId: string, options?: {
388
+ idempotencyKey?: string;
389
+ }) => Promise<PaymentSession>;
390
+ cancelSubscription: (subscriptionId: string, options?: CancelSubscriptionOptions) => Promise<Subscription>;
391
+ readonly capabilities: ProviderCapabilities;
392
+ capturePayment: (input: CaptureInput) => Promise<PaymentSession>;
393
+ /**
394
+ * Ask the provider whether a reference may consume `quantity` units of a feature (or holds active
395
+ * access to a product) right now — for providers that own entitlement truth themselves (e.g.
396
+ * Autumn computes balances, credits, and limits from its plan config). Optional: when absent, the
397
+ * facade's `check` evaluates locally from the synced store + the app's `entitlements` config. When
398
+ * present, the facade delegates `check` to it, so `entitlements` need not be configured.
399
+ */
400
+ checkEntitlement?: (input: CheckInput) => Promise<CheckResult>;
401
+ createCheckout: (input: CheckoutInput) => Promise<CheckoutResult>;
402
+ createPortalSession: (input: PortalInput) => Promise<{
403
+ url: string;
404
+ }>;
405
+ /**
406
+ * Resolve every feature allowance for a reference straight from the provider — the optional
407
+ * companion to `checkEntitlement` that powers `listBalances`. Present only on providers that
408
+ * own entitlement truth; when absent, the facade evaluates balances locally from the store + the
409
+ * app's `entitlements` config.
410
+ */
411
+ getBalances?: (referenceId: string) => Promise<FeatureBalance[]>;
412
+ getOrCreateCustomer: (ref: CustomerRef) => Promise<Customer>;
413
+ /** Fetch the provider's current truth for a payment session — the basis for reconciliation. */
414
+ getPaymentStatus: (sessionId: string) => Promise<PaymentSession>;
415
+ /** Fetch the provider's current truth for a subscription — the basis for reconciliation. */
416
+ getSubscriptionStatus: (subscriptionId: string) => Promise<Subscription>;
417
+ /** Stable provider identifier (Medusa-style). */
418
+ readonly identifier: ProviderId;
419
+ /** Verify the signature over the raw body, then normalize the event. Throws on invalid signature. */
420
+ parseWebhook: (input: WebhookInput) => Promise<WebhookAction>;
421
+ refundPayment: (input: RefundInput) => Promise<PaymentSession>;
422
+ /**
423
+ * Forward metered usage to the provider's billing API. Optional — present only on providers
424
+ * whose `capabilities.usageMetering` is `true` and that expose an ingestion endpoint. When
425
+ * absent, `track` still records usage durably and `check` enforces limits locally.
426
+ */
427
+ reportUsage?: (input: ReportUsageInput) => Promise<void>;
428
+ resumeSubscription: (subscriptionId: string) => Promise<Subscription>;
429
+ updateSubscription: (subscriptionId: string, patch: SubscriptionPatch) => Promise<Subscription>;
430
+ }
431
+ /**
432
+ * Registry of adapters keyed by provider id — supports dual-register during provider migration.
433
+ * @experimental
434
+ */
435
+ interface AdapterRegistry {
436
+ all: () => PaymentAdapter[];
437
+ get: (provider: ProviderId) => PaymentAdapter;
438
+ has: (provider: ProviderId) => boolean;
439
+ }
440
+ /**
441
+ * `createAdapterRegistry` is part of the experimental `@lunora/payment` API and may change without a major version bump.
442
+ * @experimental
443
+ */
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, 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 };