@lunora/payment 1.0.0-alpha.13 → 1.0.0-alpha.130

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 +8 -4
  3. package/dist/index.d.mts +407 -530
  4. package/dist/index.d.ts +407 -530
  5. package/dist/index.mjs +1 -16
  6. package/dist/packem_shared/LunoraPaymentError-BSxyhWgu.mjs +1 -0
  7. package/dist/packem_shared/MemoryPaymentStore-CZbrrEb1.mjs +1 -0
  8. package/dist/packem_shared/PAYMENT_TERMINAL_STATES-C-ICZkun.mjs +1 -0
  9. package/dist/packem_shared/adapter.d-DytKm_IF.d.mts +513 -0
  10. package/dist/packem_shared/adapter.d-DytKm_IF.d.ts +513 -0
  11. package/dist/packem_shared/addMoney-B4ufWAnD.mjs +1 -0
  12. package/dist/packem_shared/applyWebhookAction-CvLpZjKP.mjs +1 -0
  13. package/dist/packem_shared/constantTimeEqual-ggrwGvRa.mjs +1 -0
  14. package/dist/packem_shared/createAdapterRegistry-DyCsry1Q.mjs +1 -0
  15. package/dist/packem_shared/createDatabasePaymentStore-BGcHX1uq.mjs +1 -0
  16. package/dist/packem_shared/createPayment-Dimez2zY.mjs +1 -0
  17. package/dist/packem_shared/entitlementsForReference-PMmhAOWa.mjs +1 -0
  18. package/dist/packem_shared/idempotencyKey-qQJLcEQX.mjs +1 -0
  19. package/dist/packem_shared/json-BJJPJVYj.mjs +1 -0
  20. package/dist/packem_shared/lunoraDatabaseToPaymentDatabase-CFPYSEu0.mjs +1 -0
  21. package/dist/packem_shared/not-supported-Cl0brzhn.mjs +1 -0
  22. package/dist/packem_shared/observability-BteZ2dJS.mjs +1 -0
  23. package/dist/packem_shared/paymentTables-Ve_lJxAt.mjs +1 -0
  24. package/dist/packem_shared/reconcile-fbxX8j9k.mjs +1 -0
  25. package/dist/packem_shared/subscription-event-C8GiQSFM.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 +34 -0
  42. package/dist/providers/stripe.d.ts +34 -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-CgErk9zo.mjs +0 -220
  55. package/dist/packem_shared/createStripeAdapter-oDvMhpeX.mjs +0 -279
  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-CgErk9zo.mjs';
10
- export { createStripeAdapter } from './packem_shared/createStripeAdapter-oDvMhpeX.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-DyCsry1Q.mjs";import{lunoraDatabaseToPaymentDatabase as a,paymentsFromContext as n}from"./packem_shared/lunoraDatabaseToPaymentDatabase-CFPYSEu0.mjs";import{createPayment as y,webhookResponse as i}from"./packem_shared/createPayment-Dimez2zY.mjs";import{createDatabasePaymentStore as s}from"./packem_shared/createDatabasePaymentStore-BGcHX1uq.mjs";import{entitlementsForReference as c,featureNames as x,hasActivePrice as S,resolveEntitlements as l,usagePeriodStart as M}from"./packem_shared/entitlementsForReference-PMmhAOWa.mjs";import{LunoraPaymentError as u}from"./packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{idempotencyKey as b}from"./packem_shared/idempotencyKey-qQJLcEQX.mjs";import{addMoney as A,allocateMoney as E,compareMoney as N,formatMoney as h,fromMoneyJSON as R,isZeroDecimalCurrency as v,isZeroMoney as C,money as D,subtractMoney as I,toMoneyJSON as _,zeroMoney as g}from"./packem_shared/addMoney-B4ufWAnD.mjs";import{reconcile as L}from"./packem_shared/reconcile-fbxX8j9k.mjs";import{default as F}from"./packem_shared/paymentTables-Ve_lJxAt.mjs";import{PAYMENT_TERMINAL_STATES as W,SUBSCRIPTION_TERMINAL_STATES as Z,canTransitionPayment as q,canTransitionSubscription as w,nextPaymentState as z,nextSubscriptionState as B}from"./packem_shared/PAYMENT_TERMINAL_STATES-C-ICZkun.mjs";import{MemoryPaymentStore as K}from"./packem_shared/MemoryPaymentStore-CZbrrEb1.mjs";import{default as Y}from"./packem_shared/applyWebhookAction-CvLpZjKP.mjs";import{constantTimeEqual as G,hmacSha256Hex as Q,verifyCreemSignature as V,verifyStandardWebhook as X}from"./packem_shared/constantTimeEqual-ggrwGvRa.mjs";export{u as LunoraPaymentError,K as MemoryPaymentStore,W as PAYMENT_TERMINAL_STATES,Z as SUBSCRIPTION_TERMINAL_STATES,A as addMoney,E as allocateMoney,Y as applyWebhookAction,q as canTransitionPayment,w as canTransitionSubscription,N as compareMoney,G as constantTimeEqual,r as createAdapterRegistry,s as createDatabasePaymentStore,y as createPayment,c as entitlementsForReference,x as featureNames,h as formatMoney,R as fromMoneyJSON,S as hasActivePrice,Q as hmacSha256Hex,b as idempotencyKey,v as isZeroDecimalCurrency,C as isZeroMoney,a as lunoraDatabaseToPaymentDatabase,D as money,z as nextPaymentState,B as nextSubscriptionState,F as paymentTables,n as paymentsFromContext,L as reconcile,l as resolveEntitlements,I as subtractMoney,_ as toMoneyJSON,M as usagePeriodStart,V as verifyCreemSignature,X as verifyStandardWebhook,i as webhookResponse,g as zeroMoney};
@@ -0,0 +1 @@
1
+ import{LunoraError as E}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 R extends E{constructor(I,r){super(I,r,{name:"LunoraPaymentError",status:O[I]})}}export{R as LunoraPaymentError};
@@ -0,0 +1 @@
1
+ const a=(i,e)=>`${i}:${e}`,n=(i,e)=>`${i}:${e}`,u=i=>{const e=i.toSorted((t,r)=>t.createdAt-r.createdAt||t.idempotencyKey.localeCompare(r.idempotencyKey));let s=0;for(const t of e)s=t.mode==="set"?t.quantity:s+t.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(a(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))}listUnreportedUsage(e,s){const t=[...this.usageEvents.values()].filter(r=>r.provider===e&&!r.reportedToProvider&&r.mode!=="set"&&r.quantity>0).toSorted((r,o)=>r.createdAt-o.createdAt||r.idempotencyKey.localeCompare(o.idempotencyKey));return Promise.resolve(t.slice(0,Math.max(0,s)))}markEventProcessed(e,s,t){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 t=n(e,s),r=this.usageEvents.get(t);return r&&this.usageEvents.set(t,{...r,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,t){const r=[];for(const o of this.usageEvents.values())o.referenceId===e&&o.featureId===s&&o.createdAt>=t&&r.push(o);return Promise.resolve(u(r))}sumUsageByFeature(e,s,t){const r=new Map(s.map(o=>[o,[]]));for(const o of this.usageEvents.values())o.referenceId===e&&o.createdAt>=t&&r.get(o.featureId)?.push(o);return Promise.resolve(new Map([...r].map(([o,c])=>[o,u(c)])))}upsertCustomer(e){return this.customers.set(a(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,u as foldUsage};
@@ -0,0 +1 @@
1
+ const c={authorized:{cancel:"canceled",capture:"captured",fail:"failed"},canceled:{},captured:{partial_refund:"partially_refunded",refund:"refunded"},failed:{authorize:"authorized",capture:"captured",fail:"failed"},initiated:{authorize:"authorized",cancel:"canceled",capture:"captured",fail:"failed"},partially_refunded:{partial_refund:"partially_refunded",refund:"refunded"},refunded:{refund:"refunded"}},t={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",pause:"paused",renew:"active"}},r=new Set(["canceled","refunded"]),i=new Set(["canceled"]),n=(e,a)=>c[e][a],u=(e,a)=>n(e,a)!==void 0,d=(e,a)=>t[e][a],l=(e,a)=>d(e,a)!==void 0;export{r as PAYMENT_TERMINAL_STATES,i as SUBSCRIPTION_TERMINAL_STATES,u as canTransitionPayment,l as canTransitionSubscription,n as nextPaymentState,d as nextSubscriptionState};
@@ -0,0 +1,513 @@
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
+ */
10
+ type CurrencyCode = string;
11
+ /**
12
+ * Money as integer minor units + currency. Always carry the two together.
13
+ *
14
+ * `minorUnits` is a `bigint`, which is **not** JSON-serializable — cross the RPC/wire boundary
15
+ * with the `toMoneyJSON` / `fromMoneyJSON` helpers (see `./money`).
16
+ */
17
+ interface Money {
18
+ readonly currency: CurrencyCode;
19
+ readonly minorUnits: bigint;
20
+ }
21
+ /**
22
+ * Stable provider identifier (Medusa-style). Ships Stripe/Polar/Autumn/Dodo plus Creem, an EU-friendly MoR.
23
+ * @experimental
24
+ */
25
+ type ProviderId = "autumn" | "creem" | "dodopayments" | "polar" | "stripe";
26
+ /**
27
+ * What a provider can do — encoded in types so tax/UX assumptions aren't tribal knowledge.
28
+ * @experimental
29
+ */
30
+ interface ProviderCapabilities {
31
+ /** True for Polar / Lemon Squeezy / Paddle; false for Stripe (PSP) and Autumn (runs on your own Stripe). Drives tax/invoice ownership. */
32
+ readonly merchantOfRecord: boolean;
33
+ /** Native hosted customer/billing portal. */
34
+ readonly portal: boolean;
35
+ /** Usage-based / metered billing. */
36
+ readonly usageMetering: boolean;
37
+ }
38
+ /**
39
+ * Lifecycle state of a one-time payment session.
40
+ * @experimental
41
+ */
42
+ type PaymentState = "authorized" | "canceled" | "captured" | "failed" | "initiated" | "partially_refunded" | "refunded";
43
+ /**
44
+ * Lifecycle state of a subscription.
45
+ * @experimental
46
+ */
47
+ type SubscriptionState = "active" | "canceled" | "past_due" | "paused" | "trialing";
48
+ /**
49
+ * `Customer` is part of the experimental `@lunora/payment` API and may change without a major version bump.
50
+ * @experimental
51
+ */
52
+ interface Customer {
53
+ readonly createdAt: number;
54
+ readonly email?: string;
55
+ /** Provider-side customer id. */
56
+ readonly id: string;
57
+ readonly provider: ProviderId;
58
+ /** App-side owner the customer belongs to (user / org / workspace). Opaque to this package. */
59
+ readonly referenceId: string;
60
+ }
61
+ /**
62
+ * `PaymentSession` is part of the experimental `@lunora/payment` API and may change without a major version bump.
63
+ * @experimental
64
+ */
65
+ interface PaymentSession {
66
+ readonly amount: Money;
67
+ readonly capturedAmount: Money;
68
+ readonly createdAt: number;
69
+ /** Provider-side payment / intent / session id. */
70
+ readonly id: string;
71
+ readonly provider: ProviderId;
72
+ readonly referenceId: string;
73
+ readonly refundedAmount: Money;
74
+ readonly state: PaymentState;
75
+ readonly updatedAt: number;
76
+ }
77
+ /**
78
+ * `Subscription` is part of the experimental `@lunora/payment` API and may change without a major version bump.
79
+ * @experimental
80
+ */
81
+ interface Subscription {
82
+ readonly cancelAtPeriodEnd: boolean;
83
+ readonly createdAt: number;
84
+ readonly currentPeriodEnd?: number;
85
+ /** Start of the current billing period — the window `check` sums metered usage over. */
86
+ readonly currentPeriodStart?: number;
87
+ readonly id: string;
88
+ /** The primary (first) price/product id — `priceIds[0]`. Display and single-item plan changes. */
89
+ readonly priceId: string;
90
+ /**
91
+ * EVERY price/product id the subscription bills, not just the primary one. A Stripe subscription
92
+ * can carry an add-on or a metered price alongside the base plan, and a customer paying for one is
93
+ * entitled to it — so entitlements test membership here (see `hasActivePrice`).
94
+ *
95
+ * Optional because the webhook path and any pre-existing stored row carry only `priceId`; absent
96
+ * reads as `[priceId]`, which is exactly right for the single-item case every other provider has.
97
+ */
98
+ readonly priceIds?: ReadonlyArray<string>;
99
+ readonly provider: ProviderId;
100
+ readonly quantity: number;
101
+ readonly referenceId: string;
102
+ readonly state: SubscriptionState;
103
+ readonly updatedAt: number;
104
+ }
105
+ /**
106
+ * `CustomerRef` is part of the experimental `@lunora/payment` API and may change without a major version bump.
107
+ * @experimental
108
+ */
109
+ interface CustomerRef {
110
+ readonly email?: string;
111
+ readonly metadata?: Record<string, string>;
112
+ readonly referenceId: string;
113
+ }
114
+ /**
115
+ * `CheckoutInput` is part of the experimental `@lunora/payment` API and may change without a major version bump.
116
+ * @experimental
117
+ */
118
+ interface CheckoutInput {
119
+ readonly cancelUrl: string;
120
+ /**
121
+ * Ignored at runtime (kept for backward-compat). The provider customer is always derived from the store for the
122
+ * authorized `referenceId` (never caller-supplied) to prevent cross-tenant checkout attachment (IDOR).
123
+ * Retained on the type only for backward compatibility; setting it has no effect.
124
+ */
125
+ readonly customerId?: string;
126
+ /**
127
+ * Customer email, used when the reference has no provider customer yet. Some Merchant-of-Record
128
+ * providers (e.g. Dodo Payments) require an email to mint a customer, so pass it on first checkout.
129
+ */
130
+ readonly email?: string;
131
+ /** Outbound idempotency key for the provider call; auto-derived when omitted. */
132
+ readonly idempotencyKey?: string;
133
+ readonly metadata?: Record<string, string>;
134
+ readonly mode: "payment" | "subscription";
135
+ readonly priceId: string;
136
+ readonly quantity?: number;
137
+ readonly referenceId: string;
138
+ readonly successUrl: string;
139
+ }
140
+ /**
141
+ * `CheckoutResult` is part of the experimental `@lunora/payment` API and may change without a major version bump.
142
+ * @experimental
143
+ */
144
+ interface CheckoutResult {
145
+ readonly id: string;
146
+ readonly provider: ProviderId;
147
+ readonly url: string;
148
+ }
149
+ /**
150
+ * `attach` input — subscribe a reference to a plan. A thin, plan-oriented skin over
151
+ * {@link CheckoutInput}: `mode` defaults to `"subscription"` (the common case), so callers pass
152
+ * just `{ referenceId, priceId, successUrl, cancelUrl }`.
153
+ * @experimental
154
+ */
155
+ interface AttachInput extends Omit<CheckoutInput, "mode"> {
156
+ readonly mode?: CheckoutInput["mode"];
157
+ }
158
+ /**
159
+ * `PortalInput` is part of the experimental `@lunora/payment` API and may change without a major version bump.
160
+ * @experimental
161
+ */
162
+ interface PortalInput {
163
+ readonly customerId: string;
164
+ readonly returnUrl: string;
165
+ }
166
+ /**
167
+ * A single durable usage record — one metered event for a `(referenceId, featureId)` pair.
168
+ * @experimental
169
+ */
170
+ interface UsageEvent {
171
+ readonly createdAt: number;
172
+ readonly featureId: string;
173
+ /** Caller-stable dedupe key — recording the same key twice is a no-op (exactly-once `track`). */
174
+ readonly idempotencyKey: string;
175
+ /**
176
+ * How the period total absorbs this event: `"add"` (the default, and the value
177
+ * assumed for rows written before this field existed) increments it, `"set"`
178
+ * RESETS it to `quantity` and discards everything recorded earlier in the
179
+ * period.
180
+ *
181
+ * The ledger stays append-only either way — a `"set"` is a marker, not a
182
+ * computed delta — which is what makes `track({ mode: "set" })` safe to call
183
+ * concurrently. `PaymentStore.sumUsage` (via `foldUsage`) applies the fold.
184
+ */
185
+ readonly mode?: "add" | "set";
186
+ readonly provider: ProviderId;
187
+ /** For `"add"`, the increment. For `"set"`, the absolute period total this event declares. */
188
+ readonly quantity: number;
189
+ readonly referenceId: string;
190
+ /** Whether the event was successfully forwarded to the provider's metering API. */
191
+ readonly reportedToProvider: boolean;
192
+ }
193
+ /**
194
+ * `track` input — record metered usage for a reference's feature.
195
+ * @experimental
196
+ */
197
+ interface TrackInput {
198
+ readonly featureId: string;
199
+ /** Caller-supplied dedupe key; a fresh one is generated when omitted (so each call records). */
200
+ readonly idempotencyKey?: string;
201
+ /**
202
+ * `"add"` (default) increments usage by `quantity`; `"set"` reconciles the period total to `quantity`.
203
+ *
204
+ * Both are a single append: a `"set"` records the absolute target as a marker that the period fold
205
+ * resets to, rather than reading the current total and appending a delta. Concurrent `"set"` calls
206
+ * for the same reference therefore resolve last-writer-wins instead of over- or under-counting, and
207
+ * a replayed `"set"` is idempotent — neither mode needs a serialized context or a per-reference lock.
208
+ *
209
+ * `"set"` reconciles the LOCAL period total only, so `track` rejects it with `VALIDATION_ERROR` on a
210
+ * provider that meters usage upstream: those meters are additive and cannot take a period total, and
211
+ * a set that LOWERS usage has no negative delta to forward — the provider would keep billing the
212
+ * higher figure while the local ledger holds the lower one. Use `"add"` with a metered provider.
213
+ */
214
+ readonly mode?: "add" | "set";
215
+ /**
216
+ * Usage amount to add, or the absolute period total when `mode` is `"set"` (defaults to `1`).
217
+ * Must be a non-negative safe integer — a negative value would drive the summed period usage
218
+ * below zero and hand the reference an unbounded metered balance, so it is rejected.
219
+ */
220
+ readonly quantity?: number;
221
+ readonly referenceId: string;
222
+ }
223
+ /**
224
+ * Result of a `track` call.
225
+ * @experimental
226
+ */
227
+ interface TrackResult {
228
+ /** True when this call inserted a new usage event; false when deduplicated by idempotency key. */
229
+ readonly recorded: boolean;
230
+ /** True when the event was forwarded to the provider's metering API. */
231
+ readonly reportedToProvider: boolean;
232
+ }
233
+ /**
234
+ * `check` input — is a reference allowed something right now? Pass `featureId` to check a feature
235
+ * grant/allowance, or `priceId` to check active access to a product (one of the two is required).
236
+ * @experimental
237
+ */
238
+ interface CheckInput {
239
+ /** Feature to check a grant/allowance for. Provide this **or** `priceId`. */
240
+ readonly featureId?: string;
241
+ /** Provider price/product id to check active access for. Provide this **or** `featureId`. */
242
+ readonly priceId?: string;
243
+ /** Units the caller intends to consume; the check passes only when this many remain (default `1`). */
244
+ readonly quantity?: number;
245
+ readonly referenceId: string;
246
+ }
247
+ /**
248
+ * Result of a `check` call.
249
+ * @experimental
250
+ */
251
+ interface CheckResult {
252
+ /** Whether the reference may consume `quantity` units of the feature right now. */
253
+ readonly allowed: boolean;
254
+ /** Remaining units this period (`limit - used`), for metered features only. */
255
+ readonly balance?: number;
256
+ /** The plan-granted cap, for metered features only. */
257
+ readonly limit?: number;
258
+ /** True for a boolean feature granted without a numeric cap. */
259
+ readonly unlimited: boolean;
260
+ /** Usage consumed this period, for metered features only. */
261
+ readonly used?: number;
262
+ }
263
+ /**
264
+ * One feature's resolved allowance for a reference — a {@link CheckResult} tagged with its feature.
265
+ * @experimental
266
+ */
267
+ interface FeatureBalance extends CheckResult {
268
+ readonly featureId: string;
269
+ }
270
+ /**
271
+ * Input the adapter forwards to the provider's metering API (Stripe Meter Events / Polar ingestion).
272
+ * @experimental
273
+ */
274
+ interface ReportUsageInput {
275
+ /** Provider customer id, when known (Stripe meter events key on it). */
276
+ readonly customerId?: string;
277
+ readonly featureId: string;
278
+ readonly idempotencyKey: string;
279
+ readonly quantity: number;
280
+ readonly referenceId: string;
281
+ /** Event time in epoch ms; defaults to now at the provider. */
282
+ readonly timestamp?: number;
283
+ }
284
+ /**
285
+ * `CaptureInput` is part of the experimental `@lunora/payment` API and may change without a major version bump.
286
+ * @experimental
287
+ */
288
+ interface CaptureInput {
289
+ /** Partial capture amount; full capture when omitted. */
290
+ readonly amount?: Money;
291
+ readonly idempotencyKey?: string;
292
+ readonly sessionId: string;
293
+ }
294
+ /**
295
+ * `RefundInput` is part of the experimental `@lunora/payment` API and may change without a major version bump.
296
+ * @experimental
297
+ */
298
+ interface RefundInput {
299
+ /** Partial refund amount; full refund when omitted. */
300
+ readonly amount?: Money;
301
+ readonly idempotencyKey?: string;
302
+ readonly reason?: string;
303
+ readonly sessionId: string;
304
+ }
305
+ /**
306
+ * What an adapter's `refundPayment` returns: the provider-shaped session, plus the provider's own id
307
+ * for the refund it just issued.
308
+ *
309
+ * `RefundResult` is part of the experimental `@lunora/payment` API and may change without a major version bump.
310
+ * @experimental
311
+ */
312
+ interface RefundResult extends PaymentSession {
313
+ /**
314
+ * The provider accepted the refund but has NOT moved the money yet — Dodo answers
315
+ * `refunds.create` with `pending`/`review` and settles later via `refund.succeeded`, or never,
316
+ * via `refund.failed`. The facade leaves its ledger untouched for one of these and lets the
317
+ * confirming webhook carry the money, because a `refund.failed` reverses nothing. Absent (the
318
+ * default) means the refund is already settled — Stripe and Polar refund synchronously.
319
+ */
320
+ readonly pending?: boolean;
321
+ /**
322
+ * The provider's id for THIS refund — Stripe and Polar `Refund.id`, Dodo `refund_id`. It is the
323
+ * identity the facade keys its local refund marker on, so two in-flight refunds of the same
324
+ * amount on one session stay distinct. `undefined` only where a provider reports no id, which
325
+ * falls the marker back to the (colliding) amount.
326
+ */
327
+ readonly refundId?: string;
328
+ }
329
+ /**
330
+ * `CancelSubscriptionOptions` is part of the experimental `@lunora/payment` API and may change without a major version bump.
331
+ * @experimental
332
+ */
333
+ interface CancelSubscriptionOptions {
334
+ /** Cancel at period end instead of immediately. */
335
+ readonly atPeriodEnd?: boolean;
336
+ readonly idempotencyKey?: string;
337
+ }
338
+ /**
339
+ * `SubscriptionPatch` is part of the experimental `@lunora/payment` API and may change without a major version bump.
340
+ * @experimental
341
+ */
342
+ interface SubscriptionPatch {
343
+ /**
344
+ * Override the outbound idempotency key. Honoured by the Stripe adapter only — no other provider's
345
+ * plan-change endpoint accepts a key at all (see the `idempotency` module docblock). Stripe
346
+ * otherwise derives one from the subscription and the target plan/quantity, which is stable across
347
+ * retries of the same intent; pass your own only to re-issue a target that was already applied and
348
+ * then changed away from, which a stable key would replay rather than prorate again.
349
+ */
350
+ readonly idempotencyKey?: string;
351
+ readonly priceId?: string;
352
+ readonly quantity?: number;
353
+ }
354
+ /**
355
+ * Normalized webhook outcome — the *core state transition* a provider event implies.
356
+ * @experimental
357
+ */
358
+ type WebhookActionType = "payment.authorized" | "payment.captured" | "payment.failed" | "payment.refunded" | "subscription.active" | "subscription.canceled" | "subscription.past_due" | "subscription.paused" | "subscription.updated" | "unhandled";
359
+ /**
360
+ * How a refund action's {@link WebhookAction.amount} should be interpreted by the sync layer.
361
+ *
362
+ * `"delta"` is an incremental amount added to the running refunded total (Polar `refund.created`,
363
+ * and the historical default), so multiple events accumulate. `"absolute"` is the provider's
364
+ * cumulative refunded-to-date total (Stripe `charge.refunded` carries `amount_refunded`, which
365
+ * already sums all prior partial refunds); the sync layer sets the refunded total to this value
366
+ * rather than adding, so repeated partial-refund events do not over-count.
367
+ *
368
+ * Omitted means `"delta"`, preserving the original behavior for callers that predate this field.
369
+ * @experimental
370
+ */
371
+ type RefundAmountKind = "absolute" | "delta";
372
+ /**
373
+ * `WebhookAction` is part of the experimental `@lunora/payment` API and may change without a major version bump.
374
+ * @experimental
375
+ */
376
+ interface WebhookAction {
377
+ readonly amount?: Money;
378
+ /**
379
+ * Interpretation of {@link WebhookAction.amount} for refund actions (`payment.refunded`).
380
+ * Defaults to `"delta"` when omitted. Ignored for non-refund actions.
381
+ */
382
+ readonly amountKind?: RefundAmountKind;
383
+ readonly cancelAtPeriodEnd?: boolean;
384
+ readonly currentPeriodEnd?: number;
385
+ readonly currentPeriodStart?: number;
386
+ readonly customerId?: string;
387
+ /** Provider event id — the inbound idempotency key. */
388
+ readonly eventId: string;
389
+ readonly priceId?: string;
390
+ /**
391
+ * EVERY price/product id the subscription bills, when the adapter could establish the whole set.
392
+ * `sync.ts` applies it as a WHOLESALE replacement, so it must be complete or absent — never a
393
+ * subset, which would silently drop prices the stored row already had.
394
+ *
395
+ * `undefined` leaves the stored set standing (see {@link Subscription.priceIds}). That is the
396
+ * single-price providers' case, and the fail-closed answer for a provider whose embedded item
397
+ * list is paginated and whose event carries only the first page.
398
+ */
399
+ readonly priceIds?: ReadonlyArray<string>;
400
+ readonly provider: ProviderId;
401
+ readonly quantity?: number;
402
+ /** Raw provider event, retained for the events log / debugging. */
403
+ readonly raw?: unknown;
404
+ readonly referenceId?: string;
405
+ /**
406
+ * Provider id of the refund this event reports (refund actions only). Carries the per-refund
407
+ * identity the sync layer matches against the marker `refundPayment` left behind, so a second
408
+ * facade refund of the same amount is not mistaken for the first one's confirmation.
409
+ */
410
+ readonly refundId?: string;
411
+ readonly sessionId?: string;
412
+ readonly subscriptionId?: string;
413
+ readonly type: WebhookActionType;
414
+ }
415
+ /**
416
+ * Result of applying a webhook action to the store.
417
+ * @experimental
418
+ */
419
+ interface ApplyResult {
420
+ readonly applied: boolean;
421
+ readonly reason?: "duplicate" | "illegal_transition" | "invalid_refund_amount" | "ok" | "orphaned" | "unhandled";
422
+ }
423
+ /**
424
+ * A read-only header bag; the platform `Headers` object satisfies it.
425
+ * @experimental
426
+ */
427
+ interface WebhookHeaders {
428
+ get: (name: string) => null | string;
429
+ }
430
+ /**
431
+ * `WebhookInput` is part of the experimental `@lunora/payment` API and may change without a major version bump.
432
+ * @experimental
433
+ */
434
+ interface WebhookInput {
435
+ /** Request headers (signature schemes read provider-specific headers from here). */
436
+ readonly headers: WebhookHeaders;
437
+ /** Raw request body, exactly as received (required for signature verification). */
438
+ readonly payload: string;
439
+ }
440
+ /**
441
+ * A stateless translator between the provider API and Lunora's normalized vocabulary.
442
+ *
443
+ * Adapters never own state — they make provider calls and normalize provider events into a
444
+ * `WebhookAction`. All durable state lives in the payment store.
445
+ * @experimental
446
+ */
447
+ interface PaymentAdapter {
448
+ cancelPayment: (sessionId: string, options?: {
449
+ idempotencyKey?: string;
450
+ }) => Promise<PaymentSession>;
451
+ cancelSubscription: (subscriptionId: string, options?: CancelSubscriptionOptions) => Promise<Subscription>;
452
+ readonly capabilities: ProviderCapabilities;
453
+ capturePayment: (input: CaptureInput) => Promise<PaymentSession>;
454
+ /**
455
+ * Ask the provider whether a reference may consume `quantity` units of a feature (or holds active
456
+ * access to a product) right now — for providers that own entitlement truth themselves (e.g.
457
+ * Autumn computes balances, credits, and limits from its plan config). Optional: when absent, the
458
+ * facade's `check` evaluates locally from the synced store + the app's `entitlements` config. When
459
+ * present, the facade delegates `check` to it, so `entitlements` need not be configured.
460
+ */
461
+ checkEntitlement?: (input: CheckInput) => Promise<CheckResult>;
462
+ createCheckout: (input: CheckoutInput) => Promise<CheckoutResult>;
463
+ createPortalSession: (input: PortalInput) => Promise<{
464
+ url: string;
465
+ }>;
466
+ /**
467
+ * Resolve every feature allowance for a reference straight from the provider — the optional
468
+ * companion to `checkEntitlement` that powers `listBalances`. Present only on providers that
469
+ * own entitlement truth; when absent, the facade evaluates balances locally from the store + the
470
+ * app's `entitlements` config.
471
+ */
472
+ getBalances?: (referenceId: string) => Promise<FeatureBalance[]>;
473
+ getOrCreateCustomer: (ref: CustomerRef) => Promise<Customer>;
474
+ /** Fetch the provider's current truth for a payment session — the basis for reconciliation. */
475
+ getPaymentStatus: (sessionId: string) => Promise<PaymentSession>;
476
+ /** Fetch the provider's current truth for a subscription — the basis for reconciliation. */
477
+ getSubscriptionStatus: (subscriptionId: string) => Promise<Subscription>;
478
+ /** Stable provider identifier (Medusa-style). */
479
+ readonly identifier: ProviderId;
480
+ /** Verify the signature over the raw body, then normalize the event. Throws on invalid signature. */
481
+ parseWebhook: (input: WebhookInput) => Promise<WebhookAction>;
482
+ /** Issue the refund and report the provider's id for it (see {@link RefundResult.refundId}). */
483
+ refundPayment: (input: RefundInput) => Promise<RefundResult>;
484
+ /**
485
+ * Forward metered usage to the provider's billing API. Optional — present only on providers
486
+ * whose `capabilities.usageMetering` is `true` and that expose an ingestion endpoint. When
487
+ * absent, `track` still records usage durably and `check` enforces limits locally.
488
+ */
489
+ reportUsage?: (input: ReportUsageInput) => Promise<void>;
490
+ /**
491
+ * Clear a pending cancellation. `options.idempotencyKey` overrides the adapter's own stable key
492
+ * and is honoured by the Stripe adapter only — no other provider's endpoint accepts one.
493
+ */
494
+ resumeSubscription: (subscriptionId: string, options?: {
495
+ idempotencyKey?: string;
496
+ }) => Promise<Subscription>;
497
+ updateSubscription: (subscriptionId: string, patch: SubscriptionPatch) => Promise<Subscription>;
498
+ }
499
+ /**
500
+ * Registry of adapters keyed by provider id — supports dual-register during provider migration.
501
+ * @experimental
502
+ */
503
+ interface AdapterRegistry {
504
+ all: () => PaymentAdapter[];
505
+ get: (provider: ProviderId) => PaymentAdapter;
506
+ has: (provider: ProviderId) => boolean;
507
+ }
508
+ /**
509
+ * `createAdapterRegistry` is part of the experimental `@lunora/payment` API and may change without a major version bump.
510
+ * @experimental
511
+ */
512
+ declare const createAdapterRegistry: (adapters: ReadonlyArray<PaymentAdapter>) => AdapterRegistry;
513
+ 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, RefundResult as t, ReportUsageInput as u, SubscriptionPatch as v, WebhookHeaders as w, WebhookInput as x, createAdapterRegistry as y };