@lunora/payment 1.0.0-alpha.73 → 1.0.0-alpha.74
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{LunoraPaymentError-C8uAUIzQ.mjs → LunoraPaymentError-BSxyhWgu.mjs} +1 -1
- package/dist/packem_shared/{PAYMENT_TERMINAL_STATES-DVNbZxBy.mjs → PAYMENT_TERMINAL_STATES-DVerjPR6.mjs} +1 -1
- package/dist/packem_shared/addMoney-COE-qM5x.mjs +1 -0
- package/dist/packem_shared/applyWebhookAction-B_90qZ1b.mjs +1 -0
- package/dist/packem_shared/constantTimeEqual-Bj5tU-zT.mjs +1 -0
- package/dist/packem_shared/createAdapterRegistry-DyCsry1Q.mjs +1 -0
- package/dist/packem_shared/createDatabasePaymentStore-CodmVJtK.mjs +1 -0
- package/dist/packem_shared/createPayment-CUoaQFnR.mjs +1 -0
- package/dist/packem_shared/entitlementsForReference-Bq-9UUL8.mjs +1 -0
- package/dist/packem_shared/idempotencyKey-BjxjMMna.mjs +1 -0
- package/dist/packem_shared/json-BJJPJVYj.mjs +1 -0
- package/dist/packem_shared/lunoraDatabaseToPaymentDatabase-D5bzccof.mjs +1 -0
- package/dist/packem_shared/not-supported-Cl0brzhn.mjs +1 -0
- package/dist/packem_shared/observability-BteZ2dJS.mjs +1 -0
- package/dist/packem_shared/reconcile-BpcX9ZyP.mjs +1 -0
- package/dist/packem_shared/subscription-event-C8GiQSFM.mjs +1 -0
- package/dist/providers/autumn-features.mjs +1 -1
- package/dist/providers/autumn.mjs +1 -1
- package/dist/providers/creem.mjs +1 -1
- package/dist/providers/dodopayments.mjs +1 -1
- package/dist/providers/polar.mjs +1 -1
- package/dist/providers/stripe.mjs +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/addMoney-BKfsSf0H.mjs +0 -1
- package/dist/packem_shared/applyWebhookAction-Bwvycl00.mjs +0 -1
- package/dist/packem_shared/constantTimeEqual-B4DP75aY.mjs +0 -1
- package/dist/packem_shared/createAdapterRegistry-SoXdsiQd.mjs +0 -1
- package/dist/packem_shared/createDatabasePaymentStore-DxChfP5X.mjs +0 -1
- package/dist/packem_shared/createPayment-Cj0tRPRZ.mjs +0 -1
- package/dist/packem_shared/entitlementsForReference-BbEOKu5d.mjs +0 -1
- package/dist/packem_shared/idempotencyKey-CfJKqcE3.mjs +0 -1
- package/dist/packem_shared/json-D85Nbd92.mjs +0 -1
- package/dist/packem_shared/lunoraDatabaseToPaymentDatabase-CW1VjW4D.mjs +0 -1
- package/dist/packem_shared/not-supported-BBbwyP_u.mjs +0 -1
- package/dist/packem_shared/observability-C9tz8mj_.mjs +0 -1
- package/dist/packem_shared/reconcile-BjWV0mB0.mjs +0 -1
- package/dist/packem_shared/subscription-event-BosLshSM.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createAdapterRegistry as r}from"./packem_shared/createAdapterRegistry-
|
|
1
|
+
import{createAdapterRegistry as r}from"./packem_shared/createAdapterRegistry-DyCsry1Q.mjs";import{lunoraDatabaseToPaymentDatabase as a,paymentsFromContext as n}from"./packem_shared/lunoraDatabaseToPaymentDatabase-D5bzccof.mjs";import{createPayment as y}from"./packem_shared/createPayment-CUoaQFnR.mjs";import{createDatabasePaymentStore as p}from"./packem_shared/createDatabasePaymentStore-CodmVJtK.mjs";import{entitlementsForReference as s,featureNames as c,hasActivePrice as x,resolveEntitlements as S,usagePeriodStart as l}from"./packem_shared/entitlementsForReference-Bq-9UUL8.mjs";import{LunoraPaymentError as T}from"./packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{idempotencyKey as P}from"./packem_shared/idempotencyKey-BjxjMMna.mjs";import{addMoney as d,allocateMoney as A,compareMoney as E,formatMoney as N,fromMoneyJSON as h,isZeroDecimalCurrency as R,isZeroMoney as v,money as C,subtractMoney as D,toMoneyJSON as I,zeroMoney as _}from"./packem_shared/addMoney-COE-qM5x.mjs";import{reconcile as L}from"./packem_shared/reconcile-BpcX9ZyP.mjs";import{default as k}from"./packem_shared/paymentTables-Be-_11ux.mjs";import{PAYMENT_TERMINAL_STATES as J,SUBSCRIPTION_TERMINAL_STATES as W,canTransitionPayment as Z,canTransitionSubscription as q,nextPaymentState as z,nextSubscriptionState as B}from"./packem_shared/PAYMENT_TERMINAL_STATES-DVerjPR6.mjs";import{MemoryPaymentStore as K}from"./packem_shared/MemoryPaymentStore-CkXqJEe2.mjs";import{default as Y}from"./packem_shared/applyWebhookAction-B_90qZ1b.mjs";import{constantTimeEqual as w,hmacSha256Hex as G,verifyCreemSignature as Q,verifyStandardWebhook as V}from"./packem_shared/constantTimeEqual-Bj5tU-zT.mjs";export{T as LunoraPaymentError,K as MemoryPaymentStore,J as PAYMENT_TERMINAL_STATES,W as SUBSCRIPTION_TERMINAL_STATES,d as addMoney,A as allocateMoney,Y as applyWebhookAction,Z as canTransitionPayment,q as canTransitionSubscription,E as compareMoney,w as constantTimeEqual,r as createAdapterRegistry,p as createDatabasePaymentStore,y as createPayment,s as entitlementsForReference,c as featureNames,N as formatMoney,h as fromMoneyJSON,x as hasActivePrice,G as hmacSha256Hex,P as idempotencyKey,R as isZeroDecimalCurrency,v as isZeroMoney,a as lunoraDatabaseToPaymentDatabase,C as money,z as nextPaymentState,B as nextSubscriptionState,k as paymentTables,n as paymentsFromContext,L as reconcile,S as resolveEntitlements,D as subtractMoney,I as toMoneyJSON,l as usagePeriodStart,Q as verifyCreemSignature,V as verifyStandardWebhook,_ as zeroMoney};
|
package/dist/packem_shared/{LunoraPaymentError-C8uAUIzQ.mjs → LunoraPaymentError-BSxyhWgu.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as
|
|
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};
|
|
@@ -1 +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:{}},
|
|
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:{}},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"}},i=new Set(["canceled","failed","refunded"]),r=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{i as PAYMENT_TERMINAL_STATES,r as SUBSCRIPTION_TERMINAL_STATES,u as canTransitionPayment,l as canTransitionSubscription,n as nextPaymentState,d as nextSubscriptionState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toSnapshot as i}from"dinero.js";import{add as m,allocate as a,compare as p,subtract as M,dinero as U}from"dinero.js/bigint";import{LunoraPaymentError as C}from"./LunoraPaymentError-BSxyhWgu.mjs";const D=new Set(["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"]),F=new Set(["BHD","IQD","JOD","KWD","LYD","OMR","TND"]),e=n=>D.has(n)?0n:F.has(n)?3n:2n,f=n=>({base:10n,code:n.toUpperCase(),exponent:e(n.toUpperCase())}),t=n=>U({amount:n.minorUnits,currency:f(n.currency)}),c=n=>{const r=i(n);return{currency:r.currency.code,minorUnits:r.amount}},s=(n,r)=>{if(n.currency!==r.currency)throw new C("CURRENCY_MISMATCH",`cannot combine ${n.currency} with ${r.currency}`)},I=n=>e(n.toUpperCase())===0n,y=(n,r)=>{const o=typeof n=="bigint"?n:BigInt(Math.trunc(n));return{currency:r.toUpperCase(),minorUnits:o}},E=n=>y(0n,n),R=(n,r="en-US")=>{const o=Number(e(n.currency.toUpperCase())),u=Number(n.minorUnits)/10**o;try{return new Intl.NumberFormat(r,{currency:n.currency,style:"currency"}).format(u)}catch{return`${u.toFixed(o)} ${n.currency}`}},d=(n,r)=>(s(n,r),c(m(t(n),t(r)))),w=(n,r)=>(s(n,r),c(M(t(n),t(r)))),O=(n,r)=>(s(n,r),p(t(n),t(r))),x=(n,r)=>a(t(n),[...r]).map(o=>c(o)),A=n=>n.minorUnits===0n,J=n=>({currency:n.currency,minorUnits:n.minorUnits.toString()}),L=n=>y(BigInt(n.minorUnits),n.currency);export{d as addMoney,x as allocateMoney,O as compareMoney,R as formatMoney,L as fromMoneyJSON,I as isZeroDecimalCurrency,A as isZeroMoney,y as money,w as subtractMoney,J as toMoneyJSON,E as zeroMoney};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraPaymentError as v}from"./LunoraPaymentError-BSxyhWgu.mjs";import{compareMoney as l,zeroMoney as c,addMoney as P}from"./addMoney-COE-qM5x.mjs";import{n as o}from"./observability-BteZ2dJS.mjs";import{nextPaymentState as A,nextSubscriptionState as S}from"./PAYMENT_TERMINAL_STATES-DVerjPR6.mjs";const E={"payment.authorized":"authorize","payment.captured":"capture","payment.failed":"fail","payment.refunded":"refund"},_={"subscription.active":"active","subscription.canceled":"canceled","subscription.past_due":"past_due","subscription.paused":"paused"},b={"subscription.active":"activate","subscription.canceled":"cancel","subscription.past_due":"mark_past_due","subscription.paused":"pause"},w=(t,e)=>l(t,e)>0?t:e,I=(t,e)=>{if(!e.amount||t.refundedAmount.currency!==e.amount.currency||t.capturedAmount.currency!==e.amount.currency)return;const r=e.amountKind==="absolute"?w(e.amount,t.refundedAmount):P(t.refundedAmount,e.amount);if(!(l(r,t.capturedAmount)>0))return r},h=async(t,e,r)=>{if(!e.sessionId)return{applied:!1,reason:"unhandled"};const n=await t.getPaymentSession(e.provider,e.sessionId),u=n?.state??"initiated",d=Date.now(),i=e.amount?.currency??n?.amount.currency??"USD";let p=r;if(r==="refund"&&n){const s=I(n,e);s&&l(s,n.capturedAmount)<0&&(p="partial_refund")}const f=A(u,p);if(!f)return{applied:!1,reason:"illegal_transition"};const a=n??{amount:e.amount??c(i),capturedAmount:c(i),createdAt:d,id:e.sessionId,provider:e.provider,referenceId:e.referenceId??"",refundedAmount:c(i),state:u,updatedAt:d};let{capturedAmount:m,refundedAmount:y}=a;if(p==="capture"&&e.amount&&(m=e.amount),(p==="partial_refund"||p==="refund")&&e.amount){const s=I(a,e);if(!s)return{applied:!1,reason:"invalid_refund_amount"};y=s}return await t.upsertPaymentSession({...a,capturedAmount:m,referenceId:e.referenceId??a.referenceId,refundedAmount:y,state:f,updatedAt:d}),{applied:!0,reason:"ok"}},T=async(t,e)=>{if(!e.subscriptionId)return{applied:!1,reason:"unhandled"};const r=await t.getSubscription(e.provider,e.subscriptionId),n=Date.now();if(e.type==="subscription.updated")return r?(await t.upsertSubscription({...r,cancelAtPeriodEnd:e.cancelAtPeriodEnd??r.cancelAtPeriodEnd,currentPeriodEnd:e.currentPeriodEnd??r.currentPeriodEnd,currentPeriodStart:e.currentPeriodStart??r.currentPeriodStart,priceId:e.priceId??r.priceId,quantity:e.quantity??r.quantity,updatedAt:n}),{applied:!0,reason:"ok"}):{applied:!1,reason:"unhandled"};const u=_[e.type];if(!u)return{applied:!1,reason:"unhandled"};if(!r)return await t.upsertSubscription({cancelAtPeriodEnd:e.cancelAtPeriodEnd??!1,createdAt:n,currentPeriodEnd:e.currentPeriodEnd,currentPeriodStart:e.currentPeriodStart??n,id:e.subscriptionId,priceId:e.priceId??"",provider:e.provider,quantity:e.quantity??1,referenceId:e.referenceId??"",state:u,updatedAt:n}),{applied:!0,reason:"ok"};const d=r.state==="active"&&u==="active"?"renew":b[e.type],i=d?S(r.state,d):void 0;return i?(await t.upsertSubscription({...r,cancelAtPeriodEnd:e.cancelAtPeriodEnd??r.cancelAtPeriodEnd,currentPeriodEnd:e.currentPeriodEnd??r.currentPeriodEnd,currentPeriodStart:e.currentPeriodStart??r.currentPeriodStart,priceId:e.priceId??r.priceId,quantity:e.quantity??r.quantity,state:i,updatedAt:n}),{applied:!0,reason:"ok"}):{applied:!1,reason:"illegal_transition"}},N=async(t,e,r)=>{if(e.type==="unhandled")return{applied:!1,reason:"unhandled"};if(!e.eventId?.trim())throw new v("WEBHOOK_EVENT_ID_MISSING",`webhook event id is missing or blank for provider "${e.provider}"`);if(!await t.markEventProcessed(e.provider,e.eventId))return o(r,{eventId:e.eventId,provider:e.provider,type:"webhook.duplicate"}),{applied:!1,reason:"duplicate"};const u=E[e.type];let d;try{d=u?await h(t,e,u):await T(t,e)}catch(i){throw await t.releaseEvent(e.provider,e.eventId),i}return o(r,{action:e.type,eventId:e.eventId,provider:e.provider,reason:d.reason,type:"webhook.applied"}),e.type==="payment.failed"?o(r,{provider:e.provider,referenceId:e.referenceId,sessionId:e.sessionId,type:"payment.failed"}):e.type==="subscription.past_due"&&o(r,{provider:e.provider,referenceId:e.referenceId,subscriptionId:e.subscriptionId,type:"subscription.past_due"}),d};export{N as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraPaymentError as r}from"./LunoraPaymentError-BSxyhWgu.mjs";const g=(e,t)=>{const s=Math.max(e.length,t.length);let o=e.length^t.length;for(let n=0;n<s;n+=1){const a=n<e.length?e.charCodeAt(n):0,i=n<t.length?t.charCodeAt(n):0;o|=a^i}return o===0},h=new TextEncoder,I=e=>[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join(""),d="whsec_",l=e=>new Uint8Array(Array.from(atob(e),t=>t.codePointAt(0)??0)),A=e=>btoa(String.fromCodePoint(...new Uint8Array(e))),f=async(e,t)=>{const s=await crypto.subtle.importKey("raw",e,{hash:"SHA-256",name:"HMAC"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",s,h.encode(t));return A(o)},m=g,y=async(e,t)=>{const s=await crypto.subtle.importKey("raw",h.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",s,h.encode(t));return I(o)},N=async e=>{if(!e.secret)throw new r("CONFIG_INVALID","webhook secret not configured");const t=e.toleranceSeconds??300,s=e.now??Date.now(),o=Number(e.webhookTimestamp);if(!e.webhookId||!e.webhookSignature||!Number.isFinite(o))throw new r("WEBHOOK_SIGNATURE_INVALID","missing standard-webhooks headers");if(Math.abs(Math.floor(s/1e3)-o)>t)throw new r("WEBHOOK_TIMESTAMP_INVALID","signature timestamp outside tolerance");const n=e.secret.startsWith(d)?e.secret.slice(d.length):e.secret;if(!n)throw new r("CONFIG_INVALID","webhook secret not configured");const a=l(n);if(a.length===0)throw new r("CONFIG_INVALID","webhook secret not configured");const i=await f(a,`${e.webhookId}.${e.webhookTimestamp}.${e.payload}`);if(!e.webhookSignature.split(" ").map(c=>{const w=c.indexOf(",");return w===-1?"":c.slice(w+1)}).filter(Boolean).some(c=>m(c,i)))throw new r("WEBHOOK_SIGNATURE_INVALID","no matching signature")},E=async e=>{if(!e.secret)throw new r("CONFIG_INVALID","webhook secret not configured");if(!e.signature)throw new r("WEBHOOK_SIGNATURE_INVALID","missing creem-signature header");const t=await y(e.secret,e.payload);if(!m(e.signature,t))throw new r("WEBHOOK_SIGNATURE_INVALID","no matching signature")};export{m as constantTimeEqual,y as hmacSha256Hex,E as verifyCreemSignature,N as verifyStandardWebhook};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraPaymentError as a}from"./LunoraPaymentError-BSxyhWgu.mjs";const n=o=>{const r=new Map;for(const e of o){if(r.has(e.identifier))throw new a("CONFIG_INVALID",`duplicate adapter for provider "${e.identifier}"`);r.set(e.identifier,e)}return{all:()=>[...r.values()],get:e=>{const t=r.get(e);if(!t)throw new a("CONFIG_INVALID",`no adapter registered for provider "${e}"`);return t},has:e=>r.has(e)}};export{n as createAdapterRegistry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{money as u}from"./addMoney-COE-qM5x.mjs";import{foldUsage as m}from"./MemoryPaymentStore-CkXqJEe2.mjs";const i=(e,t)=>typeof e[t]=="string"?e[t]:"",v=(e,t)=>typeof e[t]=="string"?e[t]:void 0,o=(e,t)=>typeof e[t]=="number"?e[t]:0,p=(e,t)=>typeof e[t]=="number"?e[t]:void 0,A=(e,t)=>e[t]===!0,s=(e,t)=>{const r=e[t];return typeof r=="bigint"?r:typeof r=="number"||typeof r=="string"?BigInt(r):0n},I=e=>({createdAt:e.createdAt,email:e.email,provider:e.provider,providerCustomerId:e.id,referenceId:e.referenceId}),g=e=>({createdAt:o(e,"createdAt"),email:v(e,"email"),id:i(e,"providerCustomerId"),provider:i(e,"provider"),referenceId:i(e,"referenceId")}),S=e=>({amountMinor:e.amount.minorUnits,capturedMinor:e.capturedAmount.minorUnits,createdAt:e.createdAt,currency:e.amount.currency,provider:e.provider,providerSessionId:e.id,referenceId:e.referenceId,refundedMinor:e.refundedAmount.minorUnits,state:e.state,updatedAt:e.updatedAt}),P=e=>{const t=i(e,"currency");return{amount:u(s(e,"amountMinor"),t),capturedAmount:u(s(e,"capturedMinor"),t),createdAt:o(e,"createdAt"),id:i(e,"providerSessionId"),provider:i(e,"provider"),referenceId:i(e,"referenceId"),refundedAmount:u(s(e,"refundedMinor"),t),state:i(e,"state"),updatedAt:o(e,"updatedAt")}},l=e=>({cancelAtPeriodEnd:e.cancelAtPeriodEnd,createdAt:e.createdAt,currentPeriodEnd:e.currentPeriodEnd,currentPeriodStart:e.currentPeriodStart,priceId:e.priceId,provider:e.provider,providerSubscriptionId:e.id,quantity:e.quantity,referenceId:e.referenceId,state:e.state,updatedAt:e.updatedAt}),y=e=>({cancelAtPeriodEnd:A(e,"cancelAtPeriodEnd"),createdAt:o(e,"createdAt"),currentPeriodEnd:p(e,"currentPeriodEnd"),currentPeriodStart:p(e,"currentPeriodStart"),id:i(e,"providerSubscriptionId"),priceId:i(e,"priceId"),provider:i(e,"provider"),quantity:o(e,"quantity"),referenceId:i(e,"referenceId"),state:i(e,"state"),updatedAt:o(e,"updatedAt")}),E=e=>({createdAt:e.createdAt,featureId:e.featureId,idempotencyKey:e.idempotencyKey,...e.mode==="set"?{mode:"set"}:{},provider:e.provider,quantity:e.quantity,referenceId:e.referenceId,reportedToProvider:e.reportedToProvider}),x=e=>{const t=async(r,d,n)=>{const a=await e.findFirst(r,d);if(a){await e.patch(a._id,n);return}await e.insert(r,n)};return{getCustomerByReference:async(r,d)=>{const n=await e.findFirst("customers",{provider:r,referenceId:d});return n?g(n):void 0},getPaymentSession:async(r,d)=>{const n=await e.findFirst("paymentSessions",{provider:r,providerSessionId:d});return n?P(n):void 0},getSubscription:async(r,d)=>{const n=await e.findFirst("subscriptions",{provider:r,providerSubscriptionId:d});return n?y(n):void 0},listSubscriptionsByReference:async r=>(await e.findMany("subscriptions",{referenceId:r})).map(n=>y(n)),markEventProcessed:async(r,d)=>await e.findFirst("events",{provider:r,providerEventId:d})?!1:(await e.insert("events",{processedAt:Date.now(),provider:r,providerEventId:d,type:""}),!0),releaseEvent:async(r,d)=>{const n=await e.findFirst("events",{provider:r,providerEventId:d});n&&await e.delete(n._id)},markUsageReported:async(r,d)=>{const n=await e.findFirst("usageEvents",{idempotencyKey:d,provider:r});n&&await e.patch(n._id,{reportedToProvider:!0})},recordUsage:async r=>await e.findFirst("usageEvents",{idempotencyKey:r.idempotencyKey,provider:r.provider})?!1:(await e.insert("usageEvents",E(r)),!0),sumUsage:async(r,d,n)=>{const f=(await e.findMany("usageEvents",{featureId:d,referenceId:r})).filter(c=>o(c,"createdAt")>=n).map(c=>({createdAt:o(c,"createdAt"),idempotencyKey:typeof c.idempotencyKey=="string"?c.idempotencyKey:"",mode:c.mode==="set"?"set":"add",quantity:o(c,"quantity")}));return m(f)},upsertCustomer:async r=>t("customers",{provider:r.provider,providerCustomerId:r.id},I(r)),upsertPaymentSession:async r=>t("paymentSessions",{provider:r.provider,providerSessionId:r.id},S(r)),upsertSubscription:async r=>t("subscriptions",{provider:r.provider,providerSubscriptionId:r.id},l(r))}};export{x as createDatabasePaymentStore};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as v}from"@lunora/errors";import{usagePeriodStart as h,resolveEntitlements as g,featureNames as p,hasActivePrice as k}from"./entitlementsForReference-Bq-9UUL8.mjs";import{LunoraPaymentError as d}from"./LunoraPaymentError-BSxyhWgu.mjs";import{idempotencyKey as N,derivedIdempotencyKey as S}from"./idempotencyKey-BjxjMMna.mjs";import{n as O}from"./observability-BteZ2dJS.mjs";import R from"./applyWebhookAction-B_90qZ1b.mjs";const y=(i,t=200,c)=>Response.json(i,{headers:{"content-type":"application/json",...c},status:t});let m=0;const U=()=>{const i=Date.now();return m=i>m?i:m+1,m},B=i=>i&&"referenceId"in i?Object.fromEntries(Object.entries(i).filter(([t])=>t!=="referenceId")):i,T=i=>{const{adapter:t,store:c}=i,f=async e=>{if(!i.authorize)return;let r;try{r=await i.authorize(e)}catch{throw new d("FORBIDDEN",`caller not authorized for reference "${e}"`)}if(!r)throw new d("FORBIDDEN",`caller not authorized for reference "${e}"`)},w=async e=>{await f(e.referenceId);const r=B(e.metadata);let a;const o=await c.getCustomerByReference(t.identifier,e.referenceId);if(o)a=o.id;else{const s=await t.getOrCreateCustomer({email:e.email,referenceId:e.referenceId});a=s.id,await c.upsertCustomer(s)}const n=e.idempotencyKey??await S("checkout",t.identifier,e.referenceId,e.priceId,e.mode,String(e.quantity??1),e.successUrl,e.cancelUrl,r?JSON.stringify(r):"");return t.createCheckout({...e,customerId:a,idempotencyKey:n,metadata:r})},I=async(e,r,a,o,n)=>{const s=e.limit(o);if(s!==void 0){const l=await c.sumUsage(a,o,h(r)),u=s-l;return{allowed:u>=n,balance:u,limit:s,unlimited:!1,used:l}}return{allowed:e.has(o),unlimited:e.has(o)}};return{adapter:t,attach:async e=>w({...e,mode:e.mode??"subscription"}),cancelSubscription:async(e,r)=>{const a=await c.getSubscription(t.identifier,e);if(!a)throw new d("NOT_FOUND",`subscription "${e}" not found`);try{await f(a.referenceId)}catch{throw new d("NOT_FOUND",`subscription "${e}" not found`)}const o=r?.idempotencyKey??N("cancel_subscription",t.identifier,e),n=await t.cancelSubscription(e,{...r,idempotencyKey:o});return await c.upsertSubscription(n),n},check:async e=>{if(await f(e.referenceId),e.featureId===void 0&&e.priceId===void 0)throw new d("CONFIG_INVALID","check() requires a featureId or priceId");if(t.checkEntitlement)return t.checkEntitlement(e);const r=await c.listSubscriptionsByReference(e.referenceId);if(e.priceId!==void 0)return{allowed:k(r,e.priceId),unlimited:!1};if(e.featureId===void 0)throw new d("CONFIG_INVALID","check() requires a featureId or priceId");if(!i.entitlements)throw new d("CONFIG_INVALID","check() requires `entitlements` to be configured");const a=g(i.entitlements,r);return I(a,r,e.referenceId,e.featureId,e.quantity??1)},createCheckout:async e=>w(e),createPortalSession:async(e,r)=>{await f(e);const a=await c.getCustomerByReference(t.identifier,e);if(!a)throw new d("NOT_FOUND",`no customer for reference "${e}"`);return t.createPortalSession({customerId:a.id,returnUrl:r})},handleWebhook:async e=>{let r;try{const o=await e.text();r=await t.parseWebhook({headers:e.headers,payload:o})}catch(o){if(o instanceof d){const{body:n,status:s}=v(o);return y({error:n.message},s)}return y({error:"webhook error"},400)}const a=await R(c,r,i.observability);return y({applied:a.applied,reason:a.reason},200)},listBalances:async e=>{if(await f(e),t.getBalances)return t.getBalances(e);if(!i.entitlements)throw new d("CONFIG_INVALID","listBalances() requires `entitlements` to be configured");const r=await c.listSubscriptionsByReference(e),a=g(i.entitlements,r);return Promise.all(p(i.entitlements).map(async o=>({featureId:o,...await I(a,r,e,o,1)})))},listSubscriptions:async e=>(await f(e),c.listSubscriptionsByReference(e)),store:c,track:async e=>{await f(e.referenceId);const r=e.quantity===void 0?1:e.quantity;if(!Number.isSafeInteger(r)||r<0)throw new d("VALIDATION_ERROR",`track(): \`quantity\` must be a non-negative safe integer (got ${String(e.quantity)})`);const a=e.idempotencyKey??crypto.randomUUID(),o=e.mode==="set",n=o?await c.listSubscriptionsByReference(e.referenceId):void 0,s=n===void 0?0:await c.sumUsage(e.referenceId,e.featureId,h(n));if(o?r===s:r===0)return{recorded:!1,reportedToProvider:!1};const l=o?r-s:r;if(!await c.recordUsage({createdAt:U(),featureId:e.featureId,idempotencyKey:a,...o?{mode:"set"}:{},provider:t.identifier,quantity:r,referenceId:e.referenceId,reportedToProvider:!1}))return{recorded:!1,reportedToProvider:!1};if(l<=0||!t.capabilities.usageMetering||!t.reportUsage)return{recorded:!0,reportedToProvider:!1};try{const b=await c.getCustomerByReference(t.identifier,e.referenceId);return await t.reportUsage({customerId:b?.id,featureId:e.featureId,idempotencyKey:a,quantity:l,referenceId:e.referenceId}),await c.markUsageReported(t.identifier,a),{recorded:!0,reportedToProvider:!0}}catch{return O(i.observability,{featureId:e.featureId,provider:t.identifier,referenceId:e.referenceId,type:"usage.report_failed"}),{recorded:!0,reportedToProvider:!1}}}}};export{T as createPayment};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const f=new Set(["active","trialing"]),m=s=>{let t=0;for(const e of s)f.has(e.state)&&e.currentPeriodStart!==void 0&&(t=Math.max(t,e.currentPeriodStart));return t},p=s=>{const t=new Set;for(const e of Object.values(s.plans)){for(const o of e.features??[])t.add(o);for(const o of Object.keys(e.limits??{}))t.add(o)}return[...t].toSorted((e,o)=>e.localeCompare(o))},S=(s,t)=>s.some(e=>e.priceId===t&&f.has(e.state)),d=(s,t)=>{const e=new Set(t.filter(n=>f.has(n.state)).map(n=>n.priceId)),o=[],a=new Set,c=new Map;for(const[n,i]of Object.entries(s.plans))if(i.priceIds.some(r=>e.has(r))){o.push(n);for(const r of i.features??[])a.add(r);for(const[r,l]of Object.entries(i.limits??{})){const u=c.get(r);c.set(r,u===void 0?l:Math.max(u,l))}}return{features:a,has:n=>a.has(n),limit:n=>c.get(n),plans:o}},h=async(s,t,e)=>d(t,await s.listSubscriptionsByReference(e));export{h as entitlementsForReference,p as featureNames,S as hasActivePrice,d as resolveEntitlements,m as usagePeriodStart};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=new TextEncoder,c=async n=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",a.encode(n)))].map(t=>t.toString(16).padStart(2,"0")).join(""),i=(n,...t)=>[n,...t.map(String)].join(":"),r=async(n,t,...e)=>{const o=await c(JSON.stringify([t,...e.map(String)]));return`${n}:${t}:${o}`};export{r as derivedIdempotencyKey,i as idempotencyKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const n=e=>typeof e=="object"&&e!==null?e:{},a=(e,r)=>typeof e[r]=="string"?e[r]:void 0,s=(e,r)=>typeof e[r]=="number"?e[r]:void 0,d=(e,r)=>typeof e[r]=="boolean"?e[r]:void 0,c=(e,...r)=>{for(const t of r){const o=a(e,t);if(o!==void 0)return o}},i=(e,...r)=>{for(const t of r){const o=s(e,t);if(o!==void 0)return o}},f=e=>a(n(e.metadata),"referenceId"),p=e=>{const r=typeof e=="string"?Date.parse(e):Number.NaN;return Number.isNaN(r)?void 0:r};export{n as a,s as b,c,d,i as e,f,p,a as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createPayment as n}from"./createPayment-CUoaQFnR.mjs";import{createDatabasePaymentStore as i}from"./createDatabasePaymentStore-CodmVJtK.mjs";const s=r=>({delete:async t=>r.delete(t),findFirst:async(t,e)=>await r.findFirst(t,{where:e}),findMany:async(t,e)=>(await r.findMany(t,{where:e})).page,insert:async(t,e)=>r.insert(t,e),patch:async(t,e)=>r.patch(t,e)}),m=(r,t)=>{const e=r.auth?.userId??void 0;return n({adapter:t.adapter,authorize:t.authorize??(a=>a.trim()!==""&&e!==void 0&&a===e),entitlements:t.entitlements,observability:t.observability,store:i(s(r.db))})};export{s as lunoraDatabaseToPaymentDatabase,m as paymentsFromContext};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraPaymentError as t}from"./LunoraPaymentError-BSxyhWgu.mjs";const p=o=>r=>{throw new t("PROVIDER_ERROR",`${o} does not support ${r}`)};export{p as m};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=(t,n)=>{if(t)try{t(n)}catch{}};export{r as n};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{compareMoney as m}from"./addMoney-COE-qM5x.mjs";import{n as c}from"./observability-BteZ2dJS.mjs";const f=(t,e)=>t.currency===e.currency&&m(t,e)===0,l=(t,e)=>t?.state!==e.state||t.cancelAtPeriodEnd!==e.cancelAtPeriodEnd||t.currentPeriodEnd!==e.currentPeriodEnd||t.priceId!==e.priceId||t.quantity!==e.quantity,y=(t,e)=>t?.state!==e.state||!f(t.capturedAmount,e.capturedAmount)||!f(t.refundedAmount,e.refundedAmount),A=new Set(["partially_refunded","refunded"]),S=(t,e)=>{if(!t)return e;const a=t.refundedAmount.currency===e.refundedAmount.currency&&m(t.refundedAmount,e.refundedAmount)>0?t.refundedAmount:e.refundedAmount,d=e.state==="captured"&&A.has(t.state)?t.state:e.state,r=e.referenceId===""?t.referenceId:e.referenceId;return{...e,referenceId:r,refundedAmount:a,state:d}},b=async(t,e,n,a)=>{const d=await t.getSubscriptionStatus(n),r=await e.getSubscription(t.identifier,n);return l(r,d)?(await e.upsertSubscription({...d,createdAt:r?.createdAt??d.createdAt}),c(a,{id:n,kind:"subscription",provider:t.identifier,type:"reconcile.drift"}),!0):!1},P=async(t,e,n,a)=>{const d=await t.getPaymentStatus(n),r=await e.getPaymentSession(t.identifier,n),s=S(r,d);return y(r,s)?(await e.upsertPaymentSession({...s,createdAt:r?.createdAt??s.createdAt}),c(a,{id:n,kind:"payment",provider:t.identifier,type:"reconcile.drift"}),!0):!1},p=async(t,e,n,a,d)=>{const r=await Promise.allSettled(t.map(i=>n(i)));let s=0,o=0;for(const[i,u]of r.entries())u.status==="fulfilled"?u.value&&(s+=1):(o+=1,c(d,{error:u.reason,id:t[i]??"",kind:e,provider:a.identifier,type:"reconcile.error"}));return{failed:o,updated:s}},v=async t=>{const{adapter:e,observability:n,store:a}=t,d=t.subscriptionIds??[],r=t.paymentSessionIds??[],s=await p(d,"subscription",i=>b(e,a,i,n),e,n),o=await p(r,"payment",i=>P(e,a,i,n),e,n);return c(n,{failedPayments:o.failed,failedSubscriptions:s.failed,provider:e.identifier,type:"reconcile.completed",updatedPayments:o.updated,updatedSubscriptions:s.updated}),{checkedPayments:r.length,checkedSubscriptions:d.length,failedPayments:o.failed,failedSubscriptions:s.failed,updatedPayments:o.updated,updatedSubscriptions:s.updated}};export{v as reconcile};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const i={active:"subscription.active",canceled:"subscription.canceled",past_due:"subscription.past_due",paused:"subscription.paused",trialing:"subscription.active"},t=s=>s===void 0?"subscription.updated":i[s]??"subscription.updated";export{t as s};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as n,r as c,b as d}from"../packem_shared/json-BJJPJVYj.mjs";const i=a=>typeof a=="string"?a:[...a],u=a=>({featureId:c(a,"featureId")??c(a,"feature_id"),id:c(a,"id")??"",name:c(a,"name"),raw:a}),l=a=>{const s=a.list??a.data??a.events;return(Array.isArray(s)?s:[]).map(e=>{const t=n(e);return{count:d(t,"count")??d(t,"value")??0,period:c(t,"period"),raw:t}})},y=a=>{const s=a.client;return{checkout:async(r,e)=>{const t=n(await s.billing.attach({customerId:r,...e.freeTrial===!1?{customize:{freeTrial:null}}:{},discounts:e.reward?[{rewardId:e.reward}]:void 0,entityId:e.entityId,featureQuantities:e.options?.map(o=>({featureId:o.featureId,quantity:o.quantity})),planId:e.planId,successUrl:e.successUrl})),m=c(t,"paymentUrl")??c(t,"checkoutUrl")??c(t,"url")??"";return{raw:t,url:m}},entities:{create:async(r,e)=>{const t=await s.entities.create({customerId:r,entityId:e.id,featureId:e.featureId,name:e.name});return u(n(t))},delete:async(r,e)=>{await s.entities.delete({customerId:r,entityId:e})},get:async(r,e)=>{const t=await s.entities.get({customerId:r,entityId:e});return u(n(t))}},events:{aggregate:async(r,e)=>{const t=await s.events.aggregate({customerId:r,featureId:i(e.featureId),range:e.range});return l(n(t))},list:async(r,e)=>{const t=await s.events.list({customerId:r,featureId:i(e.featureId)});return l(n(t))}},plans:{list:async()=>{const r=n(await s.plans.list()),e=r.list??r.data??r.plans;return Array.isArray(e)?e.map(t=>n(t)):[]}},referrals:{createCode:async(r,e)=>{const t=n(await s.referrals.createCode({customerId:r,programId:e}));return{code:c(t,"code")??"",raw:t}},redeemCode:async(r,e)=>n(await s.referrals.redeemCode({code:e,customerId:r}))}}};export{y as createAutumnFeatures};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraPaymentError as
|
|
1
|
+
import{LunoraPaymentError as O}from"../packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{a as i,r as x,c as o,d as p,e as u}from"../packem_shared/json-BJJPJVYj.mjs";import{money as h}from"../packem_shared/addMoney-COE-qM5x.mjs";import{verifyStandardWebhook as C}from"../packem_shared/constantTimeEqual-Bj5tU-zT.mjs";import{m as D}from"../packem_shared/not-supported-Cl0brzhn.mjs";import{s as E}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const P={active:"active",canceled:"canceled",expired:"canceled",past_due:"past_due",scheduled:"paused",trialing:"trialing"},N={activated:"active",canceled:"canceled",cancelled:"canceled",expired:"canceled",scheduled:"paused"},w="::",y=D("autumn"),f=(a,c)=>`${a}${w}${c}`,g=a=>{const c=a.lastIndexOf(w);if(c===-1)throw new O("PROVIDER_ERROR",`malformed autumn subscription id "${a}" (expected "<customerId>::<productId>")`);return{customerId:a.slice(0,c),productId:a.slice(c+w.length)}},A=a=>u(a,"canceled_at","canceledAt")!==void 0||o(a,"status")==="scheduled",k=(a,c)=>{const r=Date.now(),e=o(c,"id","product_id","productId","plan_id","planId")??"",n=o(c,"status")??"active",t=p(c,"past_due")??p(c,"pastDue")??!1;return{cancelAtPeriodEnd:A(c),createdAt:r,currentPeriodEnd:u(c,"current_period_end","currentPeriodEnd")??void 0,currentPeriodStart:u(c,"current_period_start","currentPeriodStart")??void 0,id:f(a,e),priceId:e,provider:"autumn",quantity:u(c,"quantity")??1,referenceId:a,state:t?"past_due":P[n]??"past_due",updatedAt:r}},S=a=>Array.isArray(a)?a.map(c=>i(c)):[],T=(a,c)=>[...S(a.products),...S(a.subscriptions)].find(e=>(o(e,"id","product_id","productId","plan_id","planId")??"")===c),b=a=>({balance:u(a,"remaining","balance"),limit:u(a,"granted","included_usage","limit"),unlimited:p(a,"unlimited")??!1,used:u(a,"usage","used")}),R=(a,c,r,e)=>{const n=Date.now();return{cancelAtPeriodEnd:e,createdAt:n,id:f(a,c),priceId:c,provider:"autumn",quantity:1,referenceId:a,state:r,updatedAt:n}},v=async(a,c,r)=>{const e=i(await a.customers.get({customerId:c})),n=T(e,r);return n?k(c,n):R(c,r,"canceled",!1)},I=a=>o(a,"customer_id","customerId"),q=(a,c)=>{const r={eventId:a,provider:"autumn",raw:{object:c,type:"billing.updated"}},e=I(c),n=S(c.plan_changes)[0]??c,t=n.subscription?i(n.subscription):n,d=o(t,"plan_id","planId","product_id","productId","id"),s=o(t,"status"),m=o(n,"action"),l=p(t,"past_due")??p(t,"pastDue")??!1,_=s===void 0?void 0:P[s],U=m===void 0?void 0:N[m],B=l?"past_due":_??U;return{...r,cancelAtPeriodEnd:p(t,"cancel_at_period_end")??A(t),currentPeriodEnd:u(t,"current_period_end","currentPeriodEnd"),currentPeriodStart:u(t,"current_period_start","currentPeriodStart"),customerId:e,priceId:d,referenceId:e,subscriptionId:e===void 0||d===void 0?void 0:f(e,d),type:E(B)}},M=(a,c,r)=>{const e={eventId:a,provider:"autumn",raw:{object:r,type:c}},n=o(r,"currency")??"usd";switch(c){case"billing.auto_topup_succeeded":{const t=i(r.invoice),d=u(t,"total","amount")??u(r,"total","amount"),s=o(t,"currency")??n;return{...e,amount:d===void 0?void 0:h(BigInt(Math.round(d)),s),customerId:I(r),referenceId:I(r),sessionId:o(t,"id","stripe_id","invoice_id")??o(r,"id"),type:"payment.captured"}}case"billing.updated":return q(a,r);case"customer.product.added":case"customer.product.canceled":case"customer.product.expired":case"customer.product.updated":case"product.attached":{const t=r.product?i(r.product):r,d=c==="customer.product.canceled"||c==="customer.product.expired"?"canceled":o(t,"status"),s=I(r)??I(t);return{...e,cancelAtPeriodEnd:p(t,"cancel_at_period_end")??A(t),currentPeriodEnd:u(t,"current_period_end","currentPeriodEnd"),currentPeriodStart:u(t,"current_period_start","currentPeriodStart"),customerId:s,priceId:o(t,"id","product_id","productId"),referenceId:s,subscriptionId:s===void 0?void 0:f(s,o(t,"id","product_id","productId")??""),type:E(P[d??""])}}case"invoice.paid":case"payment.succeeded":{const t=u(r,"total","amount","amount_paid");return{...e,amount:t===void 0?void 0:h(BigInt(Math.round(t)),n),customerId:I(r),referenceId:I(r),sessionId:o(r,"id","invoice_id","stripe_id"),type:"payment.captured"}}default:return{...e,type:"unhandled"}}},$=a=>o(a,"checkout_url","checkoutUrl","payment_url","paymentUrl","url")??"",z=a=>{const{webhookSecret:c}=a,r=a.client;return{cancelPayment:()=>y("manual payment cancellation"),cancelSubscription:async(e,n)=>{const{customerId:t,productId:d}=g(e);return await r.billing.update({cancelAction:n?.atPeriodEnd?"cancel_end_of_cycle":"cancel_immediately",customerId:t,planId:d}),n?.atPeriodEnd?{...await v(r,t,d),cancelAtPeriodEnd:!0}:R(t,d,"canceled",!1)},capabilities:{merchantOfRecord:!1,portal:!0,usageMetering:!0},capturePayment:e=>y("manual capture"),checkEntitlement:async e=>{if(e.featureId===void 0){const m=i(await r.customers.get({customerId:e.referenceId})),l=T(m,e.priceId??""),_=l?k(e.referenceId,l).state:void 0;return{allowed:_==="active"||_==="trialing",unlimited:!1}}const n=i(await r.check({customerId:e.referenceId,featureId:e.featureId,requiredBalance:e.quantity??1})),t=p(n,"allowed")??!1,d=n.balance,s=typeof d=="object"&&d!==null?i(d):n;return{allowed:t,...b(s)}},createCheckout:async e=>{const n=i(await r.billing.attach({customerId:e.referenceId,planId:e.priceId}));return{id:f(e.referenceId,e.priceId),provider:"autumn",url:$(n)}},createPortalSession:async e=>{const n=i(await r.billing.openCustomerPortal({customerId:e.customerId}));return{url:o(n,"url")??""}},getBalances:async e=>{const n=i(await r.customers.get({customerId:e})),t=i(n.balances??n.features);return Object.entries(t).map(([d,s])=>{const m=i(s),l=b(m);return{allowed:l.unlimited||(l.balance??0)>0,featureId:o(m,"featureId","feature_id")??d,...l}})},getOrCreateCustomer:async e=>{const n=i(await r.customers.getOrCreate({customerId:e.referenceId,email:e.email,name:e.metadata?.name}));return{createdAt:Date.now(),email:o(n,"email")??e.email,id:o(n,"id")??e.referenceId,provider:"autumn",referenceId:e.referenceId}},getPaymentStatus:()=>y("payment-session reconciliation"),getSubscriptionStatus:async e=>{const{customerId:n,productId:t}=g(e);return v(r,n,t)},identifier:"autumn",parseWebhook:async({headers:e,payload:n})=>{const t=e.get("svix-id")??e.get("webhook-id")??"";await C({payload:n,secret:c,toleranceSeconds:a.webhookToleranceSeconds,webhookId:t,webhookSignature:e.get("svix-signature")??e.get("webhook-signature")??"",webhookTimestamp:e.get("svix-timestamp")??e.get("webhook-timestamp")??""});const d=i(JSON.parse(n));return M(t,x(d,"type")??"",i(d.data))},refundPayment:()=>y("refunds"),reportUsage:async e=>{await r.track({customerId:e.referenceId,featureId:e.featureId,value:e.quantity})},resumeSubscription:async e=>{const{customerId:n,productId:t}=g(e);return await r.billing.update({cancelAction:"uncancel",customerId:n,planId:t}),{...await v(r,n,t),cancelAtPeriodEnd:!1}},updateSubscription:async(e,n)=>{const{customerId:t,productId:d}=g(e),s=n.priceId??d;return await r.billing.attach({customerId:t,planId:s}),v(r,t,s)}}};export{z as createAutumnAdapter};
|
package/dist/providers/creem.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o,c as u,f as
|
|
1
|
+
import{a as o,c as u,f as m,r as c,b as p,p as f,d as v,e as w}from"../packem_shared/json-BJJPJVYj.mjs";import{money as I,zeroMoney as g}from"../packem_shared/addMoney-COE-qM5x.mjs";import{verifyCreemSignature as A}from"../packem_shared/constantTimeEqual-Bj5tU-zT.mjs";import{m as E}from"../packem_shared/not-supported-Cl0brzhn.mjs";import{s as P}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const k=/already exists/iu,C={canceled:"canceled",completed:"captured",expired:"canceled",paid:"captured",partially_refunded:"partially_refunded",pending:"initiated",refunded:"refunded"},h={active:"active",canceled:"canceled",cancelled:"canceled",expired:"canceled",incomplete:"past_due",paid:"active",past_due:"past_due",paused:"paused",scheduled_cancel:"active",trialing:"trialing",unpaid:"past_due"},_=E("creem (merchant-of-record)"),i=a=>typeof a=="string"?a:c(o(a),"id"),T=a=>u(a,"checkout_url","checkoutUrl")??"",S=a=>u(a,"canceled_at","canceledAt")!==void 0||c(a,"status")==="scheduled_cancel",b=a=>{if(!(a instanceof Error))return!1;const{statusCode:r}=a;return typeof r=="number"&&r!==400&&r!==409?!1:k.test(a.message)},l=a=>{const r=o(a),t=Date.now(),e=c(r,"status")??"";return{cancelAtPeriodEnd:S(r),createdAt:t,currentPeriodEnd:f(u(r,"current_period_end_date","currentPeriodEndDate")),currentPeriodStart:f(u(r,"current_period_start_date","currentPeriodStartDate")),id:c(r,"id")??"",priceId:i(r.product)??"",provider:"creem",quantity:p(r,"units")??1,referenceId:m(r)??i(r.customer)??"",state:h[e]??"past_due",updatedAt:t}},B=a=>{const r=o(a),t=Date.now(),e=o(r.order),n=c(e,"currency")??c(r,"currency")??"usd",s=I(BigInt(Math.round(p(e,"amount")??p(r,"amount")??0)),n),d=C[c(e,"status")??c(r,"status")??""]??"initiated";return{amount:s,capturedAmount:d==="captured"||d==="partially_refunded"||d==="refunded"?s:g(n),createdAt:t,id:c(r,"id")??"",provider:"creem",referenceId:m(r)??"",refundedAmount:d==="refunded"?s:g(n),state:d,updatedAt:t}},D=(a,r,t)=>{const e={eventId:a,provider:"creem",raw:{object:t,type:r}},n=o(t.order),s=c(n,"currency")??c(t,"currency")??"usd";switch(r){case"checkout.completed":{const d=p(n,"amount")??p(t,"amount");return{...e,amount:d===void 0?void 0:I(BigInt(Math.round(d)),s),customerId:i(t.customer),referenceId:m(t),sessionId:c(t,"id"),subscriptionId:i(t.subscription),type:"payment.captured"}}case"refund.created":{const d=w(t,"refund_amount","refundAmount","amount")??p(n,"amount"),y=u(t,"refund_currency","refundCurrency")??s;return{...e,amount:d===void 0?void 0:I(BigInt(Math.round(d)),y),referenceId:m(t),sessionId:i(t.transaction)??i(t.subscription)??i(t.order)??i(t.checkout)??c(t,"id"),type:"payment.refunded"}}case"subscription.active":case"subscription.canceled":case"subscription.expired":case"subscription.paid":case"subscription.past_due":case"subscription.paused":case"subscription.scheduled_cancel":case"subscription.trialing":case"subscription.unpaid":case"subscription.update":{const d=r==="subscription.scheduled_cancel"?"scheduled_cancel":c(t,"status");return{...e,cancelAtPeriodEnd:v(t,"cancel_at_period_end")??S(t),currentPeriodEnd:f(u(t,"current_period_end_date","currentPeriodEndDate")),currentPeriodStart:f(u(t,"current_period_start_date","currentPeriodStartDate")),customerId:i(t.customer),priceId:i(t.product),referenceId:m(t)??i(t.customer),subscriptionId:c(t,"id"),type:P(h[d??""])}}default:return{...e,type:"unhandled"}}},O=a=>{const{webhookSecret:r}=a,t=a.client;return{cancelPayment:()=>_("manual payment cancellation"),cancelSubscription:async(e,n)=>l(await t.subscriptions.cancel(e,{mode:n?.atPeriodEnd===!0?"scheduled":"immediate"})),capabilities:{merchantOfRecord:!0,portal:!0,usageMetering:!1},capturePayment:e=>_("manual capture"),createCheckout:async e=>{const n=await t.checkouts.create({customer:e.customerId?{id:e.customerId}:void 0,metadata:{...e.metadata,referenceId:e.referenceId},productId:e.priceId,requestId:e.idempotencyKey,successUrl:e.successUrl,units:e.quantity});return{id:c(n,"id")??"",provider:"creem",url:T(n)}},createPortalSession:async e=>{const n=await t.customers.generateBillingLinks({customerId:e.customerId});return{url:u(n,"customer_portal_link","customerPortalLink")??""}},getOrCreateCustomer:async e=>{const n=s=>({createdAt:Date.now(),email:c(s,"email")??e.email,id:c(s,"id")??"",provider:"creem",referenceId:e.referenceId});try{return n(o(await t.customers.create({email:e.email??"",metadata:{...e.metadata,referenceId:e.referenceId},name:e.metadata?.name??e.referenceId})))}catch(s){if(e.email!==void 0&&b(s)){const d=o(await t.customers.retrieve(void 0,e.email));if(m(d)!==e.referenceId)throw new Error(`Creem customer for email "${e.email}" already belongs to a different reference; refusing to bind it to "${e.referenceId}".`,{cause:s});return n(d)}throw s}},getPaymentStatus:async e=>B(await t.checkouts.retrieve(e)),getSubscriptionStatus:async e=>l(await t.subscriptions.get(e)),identifier:"creem",parseWebhook:async({headers:e,payload:n})=>{await A({payload:n,secret:r,signature:e.get("creem-signature")??""});const s=o(JSON.parse(n));return D(u(s,"id","event_id","eventId")??"",u(s,"eventType","type")??"",o(s.object))},refundPayment:()=>_("programmatic refunds"),resumeSubscription:async e=>l(await t.subscriptions.resume(e)),updateSubscription:async(e,n)=>n.priceId?l(await t.subscriptions.upgrade(e,{productId:n.priceId,updateBehavior:"proration-charge-immediately"})):l(await t.subscriptions.get(e))}};export{O as createCreemAdapter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraPaymentError as
|
|
1
|
+
import{LunoraPaymentError as v}from"../packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{idempotencyKey as S}from"../packem_shared/idempotencyKey-BjxjMMna.mjs";import{a as i,b as o,r as a,f as u,p as l,d as w}from"../packem_shared/json-BJJPJVYj.mjs";import{money as _,zeroMoney as f}from"../packem_shared/addMoney-COE-qM5x.mjs";import{verifyStandardWebhook as b}from"../packem_shared/constantTimeEqual-Bj5tU-zT.mjs";import{m as h}from"../packem_shared/not-supported-Cl0brzhn.mjs";import{s as A}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const P={cancelled:"canceled",failed:"failed",partially_captured:"captured",partially_captured_and_capturable:"captured",processing:"initiated",requires_capture:"authorized",requires_confirmation:"initiated",requires_customer_action:"authorized",requires_merchant_action:"authorized",requires_payment_method:"initiated",succeeded:"captured"},g={active:"active",cancelled:"canceled",expired:"canceled",failed:"past_due",on_hold:"past_due",paused:"paused",pending:"past_due"},I=h("dodopayments (merchant-of-record)"),p=d=>a(i(d.customer),"customer_id")??a(d,"customer_id"),m=d=>{const n=i(d),t=Date.now(),e=a(n,"status")??"";return{cancelAtPeriodEnd:w(n,"cancel_at_next_billing_date")??!1,createdAt:t,currentPeriodEnd:l(a(n,"next_billing_date")),currentPeriodStart:l(a(n,"previous_billing_date")),id:a(n,"subscription_id")??"",priceId:a(n,"product_id")??"",provider:"dodopayments",quantity:o(n,"quantity")??1,referenceId:u(n)??p(n)??"",state:g[e]??"past_due",updatedAt:t}},q=d=>{const n=i(d),t=Date.now(),e=a(n,"currency")??"usd",r=_(BigInt(Math.round(o(n,"total_amount")??0)),e),s=P[a(n,"status")??""]??"initiated";return{amount:r,capturedAmount:s==="captured"?r:f(e),createdAt:t,id:a(n,"payment_id")??"",provider:"dodopayments",referenceId:u(n)??"",refundedAmount:f(e),state:s,updatedAt:t}},k=(d,n,t)=>{const e={eventId:d,provider:"dodopayments",raw:{object:t,type:n}},r=a(t,"currency")??"usd";switch(n){case"dispute.lost":case"refund.succeeded":return{...e,amount:_(BigInt(Math.round(o(t,"amount")??0)),r),referenceId:u(t),sessionId:a(t,"payment_id"),type:"payment.refunded"};case"payment.cancelled":case"payment.failed":return{...e,referenceId:u(t),sessionId:a(t,"payment_id"),type:"payment.failed"};case"payment.succeeded":return{...e,amount:_(BigInt(Math.round(o(t,"total_amount")??0)),r),customerId:p(t),referenceId:u(t),sessionId:a(t,"payment_id"),subscriptionId:a(t,"subscription_id"),type:"payment.captured"};case"subscription.active":case"subscription.cancelled":case"subscription.expired":case"subscription.failed":case"subscription.on_hold":case"subscription.paused":case"subscription.plan_changed":case"subscription.renewed":case"subscription.updated":{const s=a(t,"status");return{...e,cancelAtPeriodEnd:w(t,"cancel_at_next_billing_date"),currentPeriodEnd:l(a(t,"next_billing_date")),currentPeriodStart:l(a(t,"previous_billing_date")),customerId:p(t),priceId:a(t,"product_id"),quantity:o(t,"quantity"),referenceId:u(t)??p(t),subscriptionId:a(t,"subscription_id"),type:A(g[s??""])}}default:return{...e,type:"unhandled"}}},R=d=>{const{webhookSecret:n}=d,t=d.client;return{cancelPayment:()=>I("manual payment cancellation"),cancelSubscription:async(e,r)=>{const s=r?.atPeriodEnd?{cancel_at_next_billing_date:!0}:{status:"cancelled"};return m(await t.subscriptions.update(e,s))},capabilities:{merchantOfRecord:!0,portal:!0,usageMetering:!0},capturePayment:e=>I("manual capture"),createCheckout:async e=>{const r=i(await t.checkoutSessions.create({customer:e.customerId?{customer_id:e.customerId}:void 0,metadata:{...e.metadata,referenceId:e.referenceId},product_cart:[{product_id:e.priceId,quantity:e.quantity??1}],return_url:e.successUrl}));return{id:a(r,"session_id")??"",provider:"dodopayments",url:a(r,"checkout_url")??""}},createPortalSession:async e=>{const r=i(await t.customers.customerPortal.create(e.customerId,{return_url:e.returnUrl}));return{url:a(r,"link")??a(r,"url")??""}},getOrCreateCustomer:async e=>{const r=i(await t.customers.create({email:e.email??"",name:e.metadata?.name??e.referenceId},{idempotencyKey:S("customer","dodopayments",e.referenceId)}));return{createdAt:Date.now(),email:a(r,"email")??e.email,id:a(r,"customer_id")??"",provider:"dodopayments",referenceId:e.referenceId}},getPaymentStatus:async e=>q(await t.payments.retrieve(e)),getSubscriptionStatus:async e=>m(await t.subscriptions.retrieve(e)),identifier:"dodopayments",parseWebhook:async({headers:e,payload:r})=>{const s=e.get("webhook-id")??"";await b({payload:r,secret:n,toleranceSeconds:d.webhookToleranceSeconds,webhookId:s,webhookSignature:e.get("webhook-signature")??"",webhookTimestamp:e.get("webhook-timestamp")??""});const c=i(JSON.parse(r));return k(s,a(c,"type")??"",i(c.data))},refundPayment:async e=>{if(e.amount!==void 0)throw new v("PROVIDER_ERROR","dodopayments refunds a payment in full; partial refunds require line items and aren't supported here");const r=i(await t.refunds.create({payment_id:e.sessionId,reason:e.reason})),s=a(r,"currency")??"usd",c=_(BigInt(Math.round(o(r,"amount")??0)),s);let y="captured";return a(r,"status")==="succeeded"&&(y="refunded"),{amount:c,capturedAmount:c,createdAt:Date.now(),id:e.sessionId,provider:"dodopayments",referenceId:"",refundedAmount:c,state:y,updatedAt:Date.now()}},reportUsage:async e=>{await t.usageEvents.ingest({events:[{customer_id:e.customerId??e.referenceId,event_id:e.idempotencyKey,event_name:e.featureId,metadata:{value:e.quantity},timestamp:e.timestamp===void 0?void 0:new Date(e.timestamp).toISOString()}]})},resumeSubscription:async e=>{const r=await t.subscriptions.update(e,{cancel_at_next_billing_date:!1});return m(r)},updateSubscription:async(e,r)=>{if(r.priceId!==void 0||r.quantity!==void 0){const s=i(r.priceId!==void 0&&r.quantity!==void 0?void 0:await t.subscriptions.retrieve(e));await t.subscriptions.changePlan(e,{product_id:r.priceId??a(s,"product_id")??"",proration_billing_mode:"prorated_immediately",quantity:r.quantity??o(s,"quantity")??1})}return m(await t.subscriptions.retrieve(e))}}};export{R as createDodoPaymentsAdapter};
|
package/dist/providers/polar.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as p,r as n,f as
|
|
1
|
+
import{a as p,r as n,f as c,d as w,p as I,b as i}from"../packem_shared/json-BJJPJVYj.mjs";import{money as m,zeroMoney as f}from"../packem_shared/addMoney-COE-qM5x.mjs";import{verifyStandardWebhook as g}from"../packem_shared/constantTimeEqual-Bj5tU-zT.mjs";import{m as P}from"../packem_shared/not-supported-Cl0brzhn.mjs";import{s as b}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const y=s=>s instanceof Date?s.getTime():I(typeof s=="string"?s:void 0),S={draft:"initiated",paid:"captured",partially_refunded:"partially_refunded",pending:"initiated",refunded:"refunded",void:"canceled"},A={active:"active",canceled:"canceled",incomplete:"past_due",incomplete_expired:"canceled",past_due:"past_due",trialing:"trialing",unpaid:"past_due"},_=P("polar (merchant-of-record)"),u=s=>{const a=p(s),r=Date.now();return{cancelAtPeriodEnd:w(a,"cancelAtPeriodEnd")??!1,createdAt:r,currentPeriodEnd:y(a.currentPeriodEnd),currentPeriodStart:y(a.currentPeriodStart),id:n(a,"id")??"",priceId:n(a,"productId")??"",provider:"polar",quantity:1,referenceId:c(a)??"",state:A[n(a,"status")??""]??"active",updatedAt:r}},v=s=>{const a=p(s),r=Date.now(),e=n(a,"currency")??"usd",t=m(BigInt(Math.round(i(a,"totalAmount")??i(a,"amount")??0)),e),d=S[n(a,"status")??""]??"initiated";return{amount:t,capturedAmount:d==="captured"||d==="partially_refunded"||d==="refunded"?t:f(e),createdAt:r,id:n(a,"id")??"",provider:"polar",referenceId:c(a)??"",refundedAmount:d==="refunded"?t:f(e),state:d,updatedAt:r}},h=(s,a,r)=>{const e={eventId:s,provider:"polar",raw:{object:r,type:a}},t=n(r,"currency")??"usd";switch(a){case"order.created":case"order.paid":return a==="order.created"&&S[n(r,"status")??""]!=="captured"?{...e,type:"unhandled"}:{...e,amount:m(BigInt(i(r,"total_amount")??i(r,"amount")??0),t),customerId:n(r,"customer_id"),referenceId:c(r),sessionId:n(r,"id"),subscriptionId:n(r,"subscription_id"),type:"payment.captured"};case"refund.created":return{...e,amount:m(BigInt(i(r,"amount")??0),t),referenceId:c(r),sessionId:n(r,"order_id")??n(r,"id"),type:"payment.refunded"};case"subscription.active":case"subscription.canceled":case"subscription.created":case"subscription.revoked":case"subscription.uncanceled":case"subscription.updated":{const d=a==="subscription.revoked"?"subscription.canceled":b(A[n(r,"status")??""]);return{...e,cancelAtPeriodEnd:w(r,"cancel_at_period_end"),currentPeriodEnd:I(n(r,"current_period_end")),currentPeriodStart:I(n(r,"current_period_start")),customerId:n(r,"customer_id"),priceId:n(r,"product_id"),referenceId:c(r),subscriptionId:n(r,"id"),type:d}}default:return{...e,type:"unhandled"}}},D=s=>{const{webhookSecret:a}=s,r=s.client;return{cancelPayment:()=>_("manual payment cancellation"),cancelSubscription:async(e,t)=>{const d=t?.atPeriodEnd?await r.subscriptions.update({id:e,subscriptionUpdate:{cancelAtPeriodEnd:!0}}):await r.subscriptions.revoke({id:e});return u(d)},capabilities:{merchantOfRecord:!0,portal:!0,usageMetering:!0},capturePayment:e=>_("manual capture"),createCheckout:async e=>{const t=await r.checkouts.create({customerEmail:e.customerId?void 0:e.email,customerId:e.customerId,externalCustomerId:e.referenceId,metadata:{...e.metadata,referenceId:e.referenceId},products:[e.priceId],returnUrl:e.cancelUrl,successUrl:e.successUrl});return{id:t.id,provider:"polar",url:t.url}},createPortalSession:async e=>({url:(await r.customerSessions.create({customerId:e.customerId})).customerPortalUrl}),getOrCreateCustomer:async e=>{const t=await r.customers.create({email:e.email??"",externalId:e.referenceId,metadata:{...e.metadata,referenceId:e.referenceId},type:"individual"});return{createdAt:Date.now(),email:t.email??void 0,id:t.id,provider:"polar",referenceId:e.referenceId}},getPaymentStatus:async e=>v(await r.orders.get({id:e})),getSubscriptionStatus:async e=>u(await r.subscriptions.get({id:e})),identifier:"polar",parseWebhook:async({headers:e,payload:t})=>{const d=e.get("webhook-id")??"";await g({payload:t,secret:a,toleranceSeconds:s.webhookToleranceSeconds,webhookId:d,webhookSignature:e.get("webhook-signature")??"",webhookTimestamp:e.get("webhook-timestamp")??""});const o=p(JSON.parse(t));return h(d,n(o,"type")??"",p(o.data))},refundPayment:async e=>{const t=e.amount?void 0:await r.orders.get({id:e.sessionId}),d=e.amount?.currency??t?.currency??"usd",o=e.amount?Number(e.amount.minorUnits):t?.totalAmount??0;await r.refunds.create({amount:o,orderId:e.sessionId,reason:e.reason??"customer_request"});const l=e.amount??m(BigInt(Math.round(o)),d);return{amount:l,capturedAmount:l,createdAt:Date.now(),id:e.sessionId,provider:"polar",referenceId:"",refundedAmount:l,state:"refunded",updatedAt:Date.now()}},reportUsage:async e=>{await r.events.ingest({events:[{externalCustomerId:e.referenceId,metadata:{value:e.quantity},name:e.featureId,timestamp:e.timestamp===void 0?void 0:new Date(e.timestamp)}]})},resumeSubscription:async e=>{const t=await r.subscriptions.update({id:e,subscriptionUpdate:{cancelAtPeriodEnd:!1}});return u(t)},updateSubscription:async(e,t)=>{const d=await r.subscriptions.update({id:e,subscriptionUpdate:t.priceId?{productId:t.priceId}:{}});return u(d)}}};export{D as createPolarAdapter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraPaymentError as
|
|
1
|
+
import{LunoraPaymentError as E}from"../packem_shared/LunoraPaymentError-BSxyhWgu.mjs";import{idempotencyKey as K}from"../packem_shared/idempotencyKey-BjxjMMna.mjs";import{a as u,r as a,d as v,b as c}from"../packem_shared/json-BJJPJVYj.mjs";import{compareMoney as P,money as p,zeroMoney as f}from"../packem_shared/addMoney-COE-qM5x.mjs";import{s as T}from"../packem_shared/subscription-event-C8GiQSFM.mjs";const q={canceled:"canceled",processing:"authorized",requires_action:"authorized",requires_capture:"authorized",requires_confirmation:"initiated",requires_payment_method:"initiated",succeeded:"captured"},w={active:"active",canceled:"canceled",incomplete:"past_due",incomplete_expired:"canceled",past_due:"past_due",paused:"paused",trialing:"trialing",unpaid:"past_due"},o=s=>a(u(s.metadata),"referenceId")??a(s,"client_reference_id"),_=s=>{const n=u(s.items),t=Array.isArray(n.data)?n.data:[];return u(t[0])},S=s=>a(u(_(s).price),"id"),g=s=>c(_(s),"quantity"),h=s=>{const n=c(_(s),"current_period_end")??c(s,"current_period_end");return n===void 0?void 0:n*1e3},A=s=>{const n=c(_(s),"current_period_start")??c(s,"current_period_start");return n===void 0?void 0:n*1e3},y=s=>{const n=u(s),t=a(n,"currency")??"usd",e=c(n,"amount")??0,r=p(BigInt(Math.round(e)),t),i=q[a(n,"status")??""]??"initiated",d=Date.now();return{amount:r,capturedAmount:i==="captured"?p(BigInt(Math.round(c(n,"amount_received")??e)),t):f(t),createdAt:d,id:a(n,"id")??"",provider:"stripe",referenceId:o(n)??"",refundedAmount:f(t),state:i,updatedAt:d}},l=s=>{const n=u(s),t=Date.now();return{cancelAtPeriodEnd:v(n,"cancel_at_period_end")??!1,createdAt:t,currentPeriodEnd:h(n),currentPeriodStart:A(n),id:a(n,"id")??"",priceId:S(n)??"",provider:"stripe",quantity:g(n)??1,referenceId:o(n)??"",state:w[a(n,"status")??""]??"active",updatedAt:t}},M=(s,n,t)=>{const e={eventId:s,provider:"stripe",raw:{object:t,type:n}},r=a(t,"currency")??"usd";switch(n){case"charge.refunded":return{...e,amount:p(BigInt(Math.round(c(t,"amount_refunded")??0)),r),amountKind:"absolute",referenceId:o(t),sessionId:a(t,"payment_intent")??a(t,"id"),type:"payment.refunded"};case"checkout.session.completed":{if(a(t,"mode")==="subscription"){const d=a(t,"payment_status"),m=d==="paid"||d==="no_payment_required";return{...e,customerId:a(t,"customer"),referenceId:o(t),subscriptionId:a(t,"subscription"),type:m?"subscription.active":"subscription.updated"}}const i=c(t,"amount_total");return{...e,amount:i===void 0?void 0:p(BigInt(Math.round(i)),r),customerId:a(t,"customer"),referenceId:o(t),sessionId:a(t,"payment_intent")??a(t,"id"),type:"payment.captured"}}case"customer.subscription.created":case"customer.subscription.updated":return{...e,cancelAtPeriodEnd:v(t,"cancel_at_period_end"),currentPeriodEnd:h(t),currentPeriodStart:A(t),customerId:a(t,"customer"),priceId:S(t),quantity:g(t),referenceId:o(t),subscriptionId:a(t,"id"),type:T(w[a(t,"status")??""])};case"customer.subscription.deleted":return{...e,referenceId:o(t),subscriptionId:a(t,"id"),type:"subscription.canceled"};case"payment_intent.amount_capturable_updated":return{...e,amount:p(BigInt(Math.round(c(t,"amount")??0)),r),referenceId:o(t),sessionId:a(t,"id"),type:"payment.authorized"};case"payment_intent.payment_failed":return{...e,referenceId:o(t),sessionId:a(t,"id"),type:"payment.failed"};case"payment_intent.succeeded":return{...e,amount:p(BigInt(Math.round(c(t,"amount_received")??c(t,"amount")??0)),r),customerId:a(t,"customer"),referenceId:o(t),sessionId:a(t,"id"),type:"payment.captured"};default:return{...e,type:"unhandled"}}},z=s=>{const{webhookSecret:n}=s,t=s.client;return{cancelPayment:async(e,r)=>{const i=await t.paymentIntents.cancel(e,void 0,{idempotencyKey:r?.idempotencyKey});return y(i)},cancelSubscription:async(e,r)=>{const i=r?.atPeriodEnd?await t.subscriptions.update(e,{cancel_at_period_end:!0},{idempotencyKey:r.idempotencyKey}):await t.subscriptions.cancel(e,void 0,{idempotencyKey:r?.idempotencyKey});return l(i)},capabilities:{merchantOfRecord:!1,portal:!0,usageMetering:!0},capturePayment:async e=>{const r=await t.paymentIntents.capture(e.sessionId,e.amount?{amount_to_capture:Number(e.amount.minorUnits)}:void 0,{idempotencyKey:e.idempotencyKey});return y(r)},createCheckout:async e=>{const r=await t.checkout.sessions.create({cancel_url:e.cancelUrl,client_reference_id:e.referenceId,customer:e.customerId,line_items:[{price:e.priceId,quantity:e.quantity??1}],metadata:{...e.metadata,referenceId:e.referenceId},mode:e.mode,subscription_data:e.mode==="subscription"?{metadata:{referenceId:e.referenceId}}:void 0,success_url:e.successUrl},{idempotencyKey:e.idempotencyKey});return{id:r.id,provider:"stripe",url:r.url??""}},createPortalSession:async e=>({url:(await t.billingPortal.sessions.create({customer:e.customerId,return_url:e.returnUrl})).url}),getOrCreateCustomer:async e=>{const r=await t.customers.create({email:e.email,metadata:{...e.metadata,referenceId:e.referenceId}},{idempotencyKey:K("customer","stripe",e.referenceId)});return{createdAt:Date.now(),email:r.email??void 0,id:r.id,provider:"stripe",referenceId:e.referenceId}},getPaymentStatus:async e=>y(await t.paymentIntents.retrieve(e)),getSubscriptionStatus:async e=>l(await t.subscriptions.retrieve(e)),identifier:"stripe",parseWebhook:async({headers:e,payload:r})=>{const i=e.get("stripe-signature")??"";let d;try{d=await t.webhooks.constructEventAsync(r,i,n,s.webhookToleranceSeconds)}catch(I){throw new E("WEBHOOK_SIGNATURE_INVALID",I instanceof Error?I.message:"invalid webhook signature")}const m=u(u(d.data).object);return M(d.id,d.type,m)},refundPayment:async e=>{await t.refunds.create({amount:e.amount?Number(e.amount.minorUnits):void 0,payment_intent:e.sessionId,reason:e.reason},{idempotencyKey:e.idempotencyKey});const r=await t.paymentIntents.retrieve(e.sessionId),i=y(r),d=e.amount??i.capturedAmount,m=e.amount!==void 0&&P(e.amount,i.capturedAmount)<0;return{...i,refundedAmount:d,state:m?"partially_refunded":"refunded"}},reportUsage:async e=>{await t.billing.meterEvents.create({event_name:e.featureId,identifier:e.idempotencyKey,payload:{stripe_customer_id:e.customerId??"",value:String(e.quantity)},timestamp:e.timestamp===void 0?void 0:Math.floor(e.timestamp/1e3)},{idempotencyKey:e.idempotencyKey})},resumeSubscription:async e=>{const r=await t.subscriptions.update(e,{cancel_at_period_end:!1});return l(r)},updateSubscription:async(e,r)=>{const i={};if(r.priceId!==void 0||r.quantity!==void 0){const m=await t.subscriptions.retrieve(e);i.items=[{id:m.items.data[0]?.id,price:r.priceId,quantity:r.quantity}]}const d=await t.subscriptions.update(e,i);return l(d)}}};export{z as createStripeAdapter};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/payment",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.74",
|
|
4
4
|
"description": "Provider-agnostic payments for Lunora: Stripe-first adapter, webhook sync, and subscription/payment state machine",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"billing",
|
|
@@ -72,7 +72,7 @@
|
|
|
72
72
|
},
|
|
73
73
|
"dependencies": {
|
|
74
74
|
"@lunora/errors": "1.0.0-alpha.21",
|
|
75
|
-
"@lunora/server": "1.0.0-alpha.
|
|
75
|
+
"@lunora/server": "1.0.0-alpha.73",
|
|
76
76
|
"@lunora/values": "1.0.0-alpha.26",
|
|
77
77
|
"dinero.js": "2.0.2"
|
|
78
78
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toSnapshot as u}from"dinero.js";import{add as m,allocate as s,compare as p,subtract as U,dinero as M}from"dinero.js/bigint";import{LunoraPaymentError as C}from"./LunoraPaymentError-C8uAUIzQ.mjs";const F=new Set(["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"]),N=new Set(["BHD","IQD","JOD","KWD","LYD","OMR","TND"]),t=r=>F.has(r)?0n:N.has(r)?3n:2n,d=r=>({base:10n,code:r.toUpperCase(),exponent:t(r.toUpperCase())}),n=r=>M({amount:r.minorUnits,currency:d(r.currency)}),c=r=>{const e=u(r);return{currency:e.currency.code,minorUnits:e.amount}},y=(r,e)=>{if(r.currency!==e.currency)throw new C("CURRENCY_MISMATCH",`cannot combine ${r.currency} with ${e.currency}`)},S=r=>t(r.toUpperCase())===0n,i=(r,e)=>{const o=typeof r=="bigint"?r:BigInt(Math.trunc(r));return{currency:e.toUpperCase(),minorUnits:o}},h=r=>i(0n,r),l=(r,e="en-US")=>{const o=Number(t(r.currency.toUpperCase())),a=Number(r.minorUnits)/10**o;try{return new Intl.NumberFormat(e,{currency:r.currency,style:"currency"}).format(a)}catch{return`${a.toFixed(o)} ${r.currency}`}},w=(r,e)=>(y(r,e),c(m(n(r),n(e)))),I=(r,e)=>(y(r,e),c(U(n(r),n(e)))),J=(r,e)=>(y(r,e),p(n(r),n(e))),O=(r,e)=>s(n(r),[...e]).map(o=>c(o)),P=r=>r.minorUnits===0n,R=r=>({currency:r.currency,minorUnits:r.minorUnits.toString()}),g=r=>i(BigInt(r.minorUnits),r.currency);export{w as addMoney,O as allocateMoney,J as compareMoney,l as formatMoney,g as fromMoneyJSON,S as isZeroDecimalCurrency,P as isZeroMoney,i as money,I as subtractMoney,R as toMoneyJSON,h as zeroMoney};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraPaymentError as v}from"./LunoraPaymentError-C8uAUIzQ.mjs";import{compareMoney as l,zeroMoney as c,addMoney as P}from"./addMoney-BKfsSf0H.mjs";import{n as s}from"./observability-C9tz8mj_.mjs";import{nextPaymentState as b,nextSubscriptionState as A}from"./PAYMENT_TERMINAL_STATES-DVNbZxBy.mjs";const E={"payment.authorized":"authorize","payment.captured":"capture","payment.failed":"fail","payment.refunded":"refund"},w={"subscription.active":"active","subscription.canceled":"canceled","subscription.past_due":"past_due","subscription.paused":"paused"},S={"subscription.active":"activate","subscription.canceled":"cancel","subscription.past_due":"mark_past_due","subscription.paused":"pause"},_=(t,e)=>l(t,e)>0?t:e,I=(t,e)=>{if(!e.amount||t.refundedAmount.currency!==e.amount.currency||t.capturedAmount.currency!==e.amount.currency)return;const r=e.amountKind==="absolute"?_(e.amount,t.refundedAmount):P(t.refundedAmount,e.amount);if(!(l(r,t.capturedAmount)>0))return r},h=async(t,e,r)=>{if(!e.sessionId)return{applied:!1,reason:"unhandled"};const n=await t.getPaymentSession(e.provider,e.sessionId),a=n?.state??"initiated",d=Date.now(),i=e.amount?.currency??n?.amount.currency??"USD";let o=r;if(r==="refund"&&n){const u=I(n,e);u&&l(u,n.capturedAmount)<0&&(o="partial_refund")}const f=b(a,o);if(!f)return{applied:!1,reason:"illegal_transition"};const p=n??{amount:e.amount??c(i),capturedAmount:c(i),createdAt:d,id:e.sessionId,provider:e.provider,referenceId:e.referenceId??"",refundedAmount:c(i),state:a,updatedAt:d};let{capturedAmount:m,refundedAmount:y}=p;if(o==="capture"&&e.amount&&(m=e.amount),(o==="partial_refund"||o==="refund")&&e.amount){const u=I(p,e);if(!u)return{applied:!1,reason:"invalid_refund_amount"};y=u}return await t.upsertPaymentSession({...p,capturedAmount:m,referenceId:e.referenceId??p.referenceId,refundedAmount:y,state:f,updatedAt:d}),{applied:!0,reason:"ok"}},k=async(t,e)=>{if(!e.subscriptionId)return{applied:!1,reason:"unhandled"};const r=await t.getSubscription(e.provider,e.subscriptionId),n=Date.now();if(e.type==="subscription.updated")return r?(await t.upsertSubscription({...r,cancelAtPeriodEnd:e.cancelAtPeriodEnd??r.cancelAtPeriodEnd,currentPeriodEnd:e.currentPeriodEnd??r.currentPeriodEnd,currentPeriodStart:e.currentPeriodStart??r.currentPeriodStart,priceId:e.priceId??r.priceId,quantity:e.quantity??r.quantity,updatedAt:n}),{applied:!0,reason:"ok"}):{applied:!1,reason:"unhandled"};const a=w[e.type];if(!a)return{applied:!1,reason:"unhandled"};if(!r)return await t.upsertSubscription({cancelAtPeriodEnd:e.cancelAtPeriodEnd??!1,createdAt:n,currentPeriodEnd:e.currentPeriodEnd,currentPeriodStart:e.currentPeriodStart??n,id:e.subscriptionId,priceId:e.priceId??"",provider:e.provider,quantity:e.quantity??1,referenceId:e.referenceId??"",state:a,updatedAt:n}),{applied:!0,reason:"ok"};const d=r.state==="active"&&a==="active"?"renew":S[e.type],i=d?A(r.state,d):void 0;return i?(await t.upsertSubscription({...r,cancelAtPeriodEnd:e.cancelAtPeriodEnd??r.cancelAtPeriodEnd,currentPeriodEnd:e.currentPeriodEnd??r.currentPeriodEnd,currentPeriodStart:e.currentPeriodStart??r.currentPeriodStart,priceId:e.priceId??r.priceId,quantity:e.quantity??r.quantity,state:i,updatedAt:n}),{applied:!0,reason:"ok"}):{applied:!1,reason:"illegal_transition"}},x=async(t,e,r)=>{if(e.type==="unhandled")return{applied:!1,reason:"unhandled"};if(!e.eventId?.trim())throw new v("WEBHOOK_EVENT_ID_MISSING",`webhook event id is missing or blank for provider "${e.provider}"`);if(!await t.markEventProcessed(e.provider,e.eventId))return s(r,{eventId:e.eventId,provider:e.provider,type:"webhook.duplicate"}),{applied:!1,reason:"duplicate"};const n=E[e.type];let a;try{a=n?await h(t,e,n):await k(t,e)}catch(d){throw await t.releaseEvent(e.provider,e.eventId),d}return s(r,{action:e.type,eventId:e.eventId,provider:e.provider,reason:a.reason,type:"webhook.applied"}),e.type==="payment.failed"?s(r,{provider:e.provider,referenceId:e.referenceId,sessionId:e.sessionId,type:"payment.failed"}):e.type==="subscription.past_due"&&s(r,{provider:e.provider,referenceId:e.referenceId,subscriptionId:e.subscriptionId,type:"subscription.past_due"}),a};export{x as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraPaymentError as r}from"./LunoraPaymentError-C8uAUIzQ.mjs";const m=(t,e)=>{const a=Math.max(t.length,e.length);let o=t.length^e.length;for(let n=0;n<a;n+=1){const s=n<t.length?t.charCodeAt(n):0,c=n<e.length?e.charCodeAt(n):0;o|=s^c}return o===0},h=new TextEncoder,I=t=>[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join(""),g="whsec_",d=t=>new Uint8Array(Array.from(atob(t),e=>e.codePointAt(0)??0)),u=t=>btoa(String.fromCodePoint(...new Uint8Array(t))),A=async(t,e)=>{const a=await crypto.subtle.importKey("raw",t,{hash:"SHA-256",name:"HMAC"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",a,h.encode(e));return u(o)},l=m,f=async(t,e)=>{const a=await crypto.subtle.importKey("raw",h.encode(t),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",a,h.encode(e));return I(o)},y=async t=>{if(!t.secret)throw new r("CONFIG_INVALID","webhook secret not configured");const e=t.toleranceSeconds??300,a=t.now??Date.now(),o=Number(t.webhookTimestamp);if(!t.webhookId||!t.webhookSignature||!Number.isFinite(o))throw new r("WEBHOOK_SIGNATURE_INVALID","missing standard-webhooks headers");if(Math.abs(Math.floor(a/1e3)-o)>e)throw new r("WEBHOOK_TIMESTAMP_INVALID","signature timestamp outside tolerance");const n=t.secret.startsWith(g)?t.secret.slice(g.length):t.secret;if(!n)throw new r("CONFIG_INVALID","webhook secret not configured");const s=d(n);if(s.length===0)throw new r("CONFIG_INVALID","webhook secret not configured");const c=await A(s,`${t.webhookId}.${t.webhookTimestamp}.${t.payload}`);if(!t.webhookSignature.split(" ").map(i=>{const w=i.indexOf(",");return w===-1?"":i.slice(w+1)}).filter(Boolean).some(i=>l(i,c)))throw new r("WEBHOOK_SIGNATURE_INVALID","no matching signature")},N=async t=>{if(!t.secret)throw new r("CONFIG_INVALID","webhook secret not configured");if(!t.signature)throw new r("WEBHOOK_SIGNATURE_INVALID","missing creem-signature header");const e=await f(t.secret,t.payload);if(!l(t.signature,e))throw new r("WEBHOOK_SIGNATURE_INVALID","no matching signature")};export{l as constantTimeEqual,f as hmacSha256Hex,N as verifyCreemSignature,y as verifyStandardWebhook};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraPaymentError as o}from"./LunoraPaymentError-C8uAUIzQ.mjs";const n=i=>{const e=new Map;for(const r of i){if(e.has(r.identifier))throw new o("CONFIG_INVALID",`duplicate adapter for provider "${r.identifier}"`);e.set(r.identifier,r)}return{all:()=>[...e.values()],get:r=>{const t=e.get(r);if(!t)throw new o("CONFIG_INVALID",`no adapter registered for provider "${r}"`);return t},has:r=>e.has(r)}};export{n as createAdapterRegistry};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{money as c}from"./addMoney-BKfsSf0H.mjs";import{foldUsage as y}from"./MemoryPaymentStore-CkXqJEe2.mjs";const n=(e,t)=>typeof e[t]=="string"?e[t]:"",m=(e,t)=>typeof e[t]=="string"?e[t]:void 0,o=(e,t)=>typeof e[t]=="number"?e[t]:0,u=(e,t)=>typeof e[t]=="number"?e[t]:void 0,f=(e,t)=>e[t]===!0,p=(e,t)=>{const r=e[t];return typeof r=="bigint"?r:typeof r=="number"||typeof r=="string"?BigInt(r):0n},I=e=>({createdAt:e.createdAt,email:e.email,provider:e.provider,providerCustomerId:e.id,referenceId:e.referenceId}),A=e=>({createdAt:o(e,"createdAt"),email:m(e,"email"),id:n(e,"providerCustomerId"),provider:n(e,"provider"),referenceId:n(e,"referenceId")}),S=e=>({amountMinor:e.amount.minorUnits,capturedMinor:e.capturedAmount.minorUnits,createdAt:e.createdAt,currency:e.amount.currency,provider:e.provider,providerSessionId:e.id,referenceId:e.referenceId,refundedMinor:e.refundedAmount.minorUnits,state:e.state,updatedAt:e.updatedAt}),P=e=>{const t=n(e,"currency");return{amount:c(p(e,"amountMinor"),t),capturedAmount:c(p(e,"capturedMinor"),t),createdAt:o(e,"createdAt"),id:n(e,"providerSessionId"),provider:n(e,"provider"),referenceId:n(e,"referenceId"),refundedAmount:c(p(e,"refundedMinor"),t),state:n(e,"state"),updatedAt:o(e,"updatedAt")}},g=e=>({cancelAtPeriodEnd:e.cancelAtPeriodEnd,createdAt:e.createdAt,currentPeriodEnd:e.currentPeriodEnd,currentPeriodStart:e.currentPeriodStart,priceId:e.priceId,provider:e.provider,providerSubscriptionId:e.id,quantity:e.quantity,referenceId:e.referenceId,state:e.state,updatedAt:e.updatedAt}),v=e=>({cancelAtPeriodEnd:f(e,"cancelAtPeriodEnd"),createdAt:o(e,"createdAt"),currentPeriodEnd:u(e,"currentPeriodEnd"),currentPeriodStart:u(e,"currentPeriodStart"),id:n(e,"providerSubscriptionId"),priceId:n(e,"priceId"),provider:n(e,"provider"),quantity:o(e,"quantity"),referenceId:n(e,"referenceId"),state:n(e,"state"),updatedAt:o(e,"updatedAt")}),w=e=>({createdAt:e.createdAt,featureId:e.featureId,idempotencyKey:e.idempotencyKey,...e.mode==="set"?{mode:"set"}:{},provider:e.provider,quantity:e.quantity,referenceId:e.referenceId,reportedToProvider:e.reportedToProvider}),l=e=>{const t=async(r,i,d)=>{const s=await e.findFirst(r,i);if(s){await e.patch(s._id,d);return}await e.insert(r,d)};return{getCustomerByReference:async(r,i)=>{const d=await e.findFirst("customers",{provider:r,referenceId:i});return d?A(d):void 0},getPaymentSession:async(r,i)=>{const d=await e.findFirst("paymentSessions",{provider:r,providerSessionId:i});return d?P(d):void 0},getSubscription:async(r,i)=>{const d=await e.findFirst("subscriptions",{provider:r,providerSubscriptionId:i});return d?v(d):void 0},listSubscriptionsByReference:async r=>(await e.findMany("subscriptions",{referenceId:r})).map(i=>v(i)),markEventProcessed:async(r,i)=>await e.findFirst("events",{provider:r,providerEventId:i})?!1:(await e.insert("events",{processedAt:Date.now(),provider:r,providerEventId:i,type:""}),!0),releaseEvent:async(r,i)=>{const d=await e.findFirst("events",{provider:r,providerEventId:i});d&&await e.delete(d._id)},markUsageReported:async(r,i)=>{const d=await e.findFirst("usageEvents",{idempotencyKey:i,provider:r});d&&await e.patch(d._id,{reportedToProvider:!0})},recordUsage:async r=>await e.findFirst("usageEvents",{idempotencyKey:r.idempotencyKey,provider:r.provider})?!1:(await e.insert("usageEvents",w(r)),!0),sumUsage:async(r,i,d)=>{const s=(await e.findMany("usageEvents",{featureId:i,referenceId:r})).filter(a=>o(a,"createdAt")>=d).map(a=>({createdAt:o(a,"createdAt"),idempotencyKey:typeof a.idempotencyKey=="string"?a.idempotencyKey:"",mode:a.mode==="set"?"set":"add",quantity:o(a,"quantity")}));return y(s)},upsertCustomer:async r=>t("customers",{provider:r.provider,providerCustomerId:r.id},I(r)),upsertPaymentSession:async r=>t("paymentSessions",{provider:r.provider,providerSessionId:r.id},S(r)),upsertSubscription:async r=>t("subscriptions",{provider:r.provider,providerSubscriptionId:r.id},g(r))}};export{l as createDatabasePaymentStore};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as b}from"@lunora/errors";import{usagePeriodStart as w,resolveEntitlements as h,featureNames as g,hasActivePrice as v}from"./entitlementsForReference-BbEOKu5d.mjs";import{LunoraPaymentError as d}from"./LunoraPaymentError-C8uAUIzQ.mjs";import{idempotencyKey as N,derivedIdempotencyKey as O}from"./idempotencyKey-CfJKqcE3.mjs";import{n as S}from"./observability-C9tz8mj_.mjs";import k from"./applyWebhookAction-Bwvycl00.mjs";const p=(a,t=200,o)=>Response.json(a,{headers:{"content-type":"application/json",...o},status:t});let m=0;const R=()=>{const a=Date.now();return m=a>m?a:m+1,m},B=a=>a&&"referenceId"in a?Object.fromEntries(Object.entries(a).filter(([t])=>t!=="referenceId")):a,_=a=>{const{adapter:t,store:o}=a,f=async e=>{if(!a.authorize)return;let r;try{r=await a.authorize(e)}catch{throw new d("FORBIDDEN",`caller not authorized for reference "${e}"`)}if(!r)throw new d("FORBIDDEN",`caller not authorized for reference "${e}"`)},y=async e=>{await f(e.referenceId);const r=B(e.metadata);let i;const n=await o.getCustomerByReference(t.identifier,e.referenceId);if(n)i=n.id;else{const s=await t.getOrCreateCustomer({email:e.email,referenceId:e.referenceId});i=s.id,await o.upsertCustomer(s)}const c=e.idempotencyKey??await O("checkout",t.identifier,e.referenceId,e.priceId,e.mode,String(e.quantity??1),e.successUrl,e.cancelUrl,r?JSON.stringify(r):"");return t.createCheckout({...e,customerId:i,idempotencyKey:c,metadata:r})},I=async(e,r,i,n,c)=>{const s=e.limit(n);if(s!==void 0){const u=await o.sumUsage(i,n,w(r)),l=s-u;return{allowed:l>=c,balance:l,limit:s,unlimited:!1,used:u}}return{allowed:e.has(n),unlimited:e.has(n)}};return{adapter:t,attach:async e=>y({...e,mode:e.mode??"subscription"}),cancelSubscription:async(e,r)=>{const i=await o.getSubscription(t.identifier,e);if(!i)throw new d("NOT_FOUND",`subscription "${e}" not found`);try{await f(i.referenceId)}catch{throw new d("NOT_FOUND",`subscription "${e}" not found`)}const n=r?.idempotencyKey??N("cancel_subscription",t.identifier,e),c=await t.cancelSubscription(e,{...r,idempotencyKey:n});return await o.upsertSubscription(c),c},check:async e=>{if(await f(e.referenceId),e.featureId===void 0&&e.priceId===void 0)throw new d("CONFIG_INVALID","check() requires a featureId or priceId");if(t.checkEntitlement)return t.checkEntitlement(e);const r=await o.listSubscriptionsByReference(e.referenceId);if(e.priceId!==void 0)return{allowed:v(r,e.priceId),unlimited:!1};if(e.featureId===void 0)throw new d("CONFIG_INVALID","check() requires a featureId or priceId");if(!a.entitlements)throw new d("CONFIG_INVALID","check() requires `entitlements` to be configured");const i=h(a.entitlements,r);return I(i,r,e.referenceId,e.featureId,e.quantity??1)},createCheckout:async e=>y(e),createPortalSession:async(e,r)=>{await f(e);const i=await o.getCustomerByReference(t.identifier,e);if(!i)throw new d("NOT_FOUND",`no customer for reference "${e}"`);return t.createPortalSession({customerId:i.id,returnUrl:r})},handleWebhook:async e=>{let r;try{const n=await e.text();r=await t.parseWebhook({headers:e.headers,payload:n})}catch(n){if(n instanceof d){const{body:c,status:s}=b(n);return p({error:c.message},s)}return p({error:"webhook error"},400)}const i=await k(o,r,a.observability);return p({applied:i.applied,reason:i.reason},200)},listBalances:async e=>{if(await f(e),t.getBalances)return t.getBalances(e);if(!a.entitlements)throw new d("CONFIG_INVALID","listBalances() requires `entitlements` to be configured");const r=await o.listSubscriptionsByReference(e),i=h(a.entitlements,r);return Promise.all(g(a.entitlements).map(async n=>({featureId:n,...await I(i,r,e,n,1)})))},listSubscriptions:async e=>(await f(e),o.listSubscriptionsByReference(e)),store:o,track:async e=>{await f(e.referenceId);const r=e.quantity===void 0?1:e.quantity;if(!Number.isSafeInteger(r)||r<0)throw new d("VALIDATION_ERROR",`track(): \`quantity\` must be a non-negative safe integer (got ${String(e.quantity)})`);const i=e.idempotencyKey??crypto.randomUUID(),n=e.mode==="set",c=n?await o.listSubscriptionsByReference(e.referenceId):void 0,s=c===void 0?0:await o.sumUsage(e.referenceId,e.featureId,w(c));if(n?r===s:r===0)return{recorded:!1,reportedToProvider:!1};const u=n?r-s:r;if(!await o.recordUsage({createdAt:R(),featureId:e.featureId,idempotencyKey:i,...n?{mode:"set"}:{},provider:t.identifier,quantity:r,referenceId:e.referenceId,reportedToProvider:!1}))return{recorded:!1,reportedToProvider:!1};if(u<=0||!t.capabilities.usageMetering||!t.reportUsage)return{recorded:!0,reportedToProvider:!1};try{const l=await o.getCustomerByReference(t.identifier,e.referenceId);return await t.reportUsage({customerId:l?.id,featureId:e.featureId,idempotencyKey:i,quantity:u,referenceId:e.referenceId}),await o.markUsageReported(t.identifier,i),{recorded:!0,reportedToProvider:!0}}catch{return S(a.observability,{featureId:e.featureId,provider:t.identifier,referenceId:e.referenceId,type:"usage.report_failed"}),{recorded:!0,reportedToProvider:!1}}}}};export{_ as createPayment};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const f=new Set(["active","trialing"]),m=s=>{let t=0;for(const e of s)f.has(e.state)&&e.currentPeriodStart!==void 0&&(t=Math.max(t,e.currentPeriodStart));return t},p=s=>{const t=new Set;for(const e of Object.values(s.plans)){for(const o of e.features??[])t.add(o);for(const o of Object.keys(e.limits??{}))t.add(o)}return[...t].toSorted((e,o)=>e.localeCompare(o))},h=(s,t)=>s.some(e=>e.priceId===t&&f.has(e.state)),u=(s,t)=>{const e=new Set(t.filter(r=>f.has(r.state)).map(r=>r.priceId)),o=[],n=new Set,c=new Map;for(const[r,i]of Object.entries(s.plans))if(i.priceIds.some(a=>e.has(a))){o.push(r);for(const a of i.features??[])n.add(a);for(const[a,l]of Object.entries(i.limits??{})){const d=c.get(a);c.set(a,d===void 0?l:Math.max(d,l))}}return{features:n,has:r=>n.has(r),limit:r=>c.get(r),plans:o}},S=async(s,t,e)=>u(t,await s.listSubscriptionsByReference(e));export{S as entitlementsForReference,p as featureNames,h as hasActivePrice,u as resolveEntitlements,m as usagePeriodStart};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const r=new TextEncoder,a=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",r.encode(e)))].map(t=>t.toString(16).padStart(2,"0")).join(""),o=(e,...t)=>[e,...t.map(String)].join(":"),c=async(e,t,...n)=>{const i=await a(JSON.stringify([t,...n.map(String)]));return`${e}:${t}:${i}`};export{c as derivedIdempotencyKey,o as idempotencyKey};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const s=e=>typeof e=="object"&&e!==null?e:{},t=(e,r)=>typeof e[r]=="string"?e[r]:void 0,d=(e,r)=>typeof e[r]=="number"?e[r]:void 0,f=(e,r)=>typeof e[r]=="boolean"?e[r]:void 0,n=(e,...r)=>{for(const a of r){const o=t(e,a);if(o!==void 0)return o}},i=(e,...r)=>{for(const a of r){const o=d(e,a);if(o!==void 0)return o}},c=e=>t(s(e.metadata),"referenceId"),p=e=>{const r=typeof e=="string"?Date.parse(e):Number.NaN;return Number.isNaN(r)?void 0:r};export{s as a,d as b,n as c,i as d,f as e,c as f,p,t as r};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createPayment as i}from"./createPayment-Cj0tRPRZ.mjs";import{createDatabasePaymentStore as n}from"./createDatabasePaymentStore-DxChfP5X.mjs";const s=e=>({delete:async t=>e.delete(t),findFirst:async(t,a)=>await e.findFirst(t,{where:a}),findMany:async(t,a)=>(await e.findMany(t,{where:a})).page,insert:async(t,a)=>e.insert(t,a),patch:async(t,a)=>e.patch(t,a)}),d=(e,t)=>{const a=e.auth?.userId??void 0;return i({adapter:t.adapter,authorize:t.authorize??(r=>r.trim()!==""&&a!==void 0&&r===a),entitlements:t.entitlements,observability:t.observability,store:n(s(e.db))})};export{s as lunoraDatabaseToPaymentDatabase,d as paymentsFromContext};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraPaymentError as t}from"./LunoraPaymentError-C8uAUIzQ.mjs";const n=o=>r=>{throw new t("PROVIDER_ERROR",`${o} does not support ${r}`)};export{n as e};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const c=(t,r)=>{if(t)try{t(r)}catch{}};export{c as n};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{compareMoney as l}from"./addMoney-BKfsSf0H.mjs";import{n as c}from"./observability-C9tz8mj_.mjs";const p=(t,e)=>t.currency===e.currency&&l(t,e)===0,m=(t,e)=>t?.state!==e.state||t.cancelAtPeriodEnd!==e.cancelAtPeriodEnd||t.currentPeriodEnd!==e.currentPeriodEnd||t.priceId!==e.priceId||t.quantity!==e.quantity,y=(t,e)=>t?.state!==e.state||!p(t.capturedAmount,e.capturedAmount)||!p(t.refundedAmount,e.refundedAmount),A=new Set(["partially_refunded","refunded"]),S=(t,e)=>{if(!t)return e;const r=t.refundedAmount.currency===e.refundedAmount.currency&&l(t.refundedAmount,e.refundedAmount)>0?t.refundedAmount:e.refundedAmount,a=e.state==="captured"&&A.has(t.state)?t.state:e.state,n=e.referenceId===""?t.referenceId:e.referenceId;return{...e,referenceId:n,refundedAmount:r,state:a}},b=async(t,e,r,a)=>{const n=await t.getSubscriptionStatus(r),d=await e.getSubscription(t.identifier,r);return m(d,n)?(await e.upsertSubscription({...n,createdAt:d?.createdAt??n.createdAt}),c(a,{id:r,kind:"subscription",provider:t.identifier,type:"reconcile.drift"}),!0):!1},P=async(t,e,r,a)=>{const n=await t.getPaymentStatus(r),d=await e.getPaymentSession(t.identifier,r),i=S(d,n);return y(d,i)?(await e.upsertPaymentSession({...i,createdAt:d?.createdAt??i.createdAt}),c(a,{id:r,kind:"payment",provider:t.identifier,type:"reconcile.drift"}),!0):!1},f=async(t,e,r,a,n)=>{const d=await Promise.allSettled(t.map(u=>r(u)));let i=0,s=0;for(const[u,o]of d.entries())o.status==="fulfilled"?o.value&&(i+=1):(s+=1,c(n,{error:o.reason,id:t[u]??"",kind:e,provider:a.identifier,type:"reconcile.error"}));return{failed:s,updated:i}},v=async t=>{const{adapter:e,observability:r,store:a}=t,n=t.subscriptionIds??[],d=t.paymentSessionIds??[],i=await f(n,"subscription",u=>b(e,a,u,r),e,r),s=await f(d,"payment",u=>P(e,a,u,r),e,r);return c(r,{failedPayments:s.failed,failedSubscriptions:i.failed,provider:e.identifier,type:"reconcile.completed",updatedPayments:s.updated,updatedSubscriptions:i.updated}),{checkedPayments:d.length,checkedSubscriptions:n.length,failedPayments:s.failed,failedSubscriptions:i.failed,updatedPayments:s.updated,updatedSubscriptions:i.updated}};export{v as reconcile};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const s={active:"subscription.active",canceled:"subscription.canceled",past_due:"subscription.past_due",paused:"subscription.paused",trialing:"subscription.active"},t=i=>i===void 0?"subscription.updated":s[i]??"subscription.updated";export{t as i};
|