@donotdev/functions 0.2.3 → 0.3.0
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/lib/chunks/{chunk-6NXIK35R.js → chunk-522YXGDA.js} +2 -2
- package/lib/chunks/chunk-7ODXXXES.js +151 -0
- package/lib/chunks/{chunk-F3WBFWPO.js.map → chunk-7ODXXXES.js.map} +3 -3
- package/lib/chunks/chunk-CP3NNKO5.js +22 -0
- package/lib/chunks/chunk-CP3NNKO5.js.map +7 -0
- package/lib/chunks/{chunk-GDIUOJMD.js → chunk-CVYSXC27.js} +2 -2
- package/lib/chunks/{chunk-UH445BGK.js → chunk-HZM5X5A7.js} +2 -2
- package/lib/chunks/chunk-ICNQCRLV.js +22 -0
- package/lib/chunks/chunk-ICNQCRLV.js.map +7 -0
- package/lib/chunks/chunk-OAZ2JYSD.js +22 -0
- package/lib/chunks/chunk-OAZ2JYSD.js.map +7 -0
- package/lib/chunks/{chunk-QXIOO2RL.js → chunk-OKRR7ST5.js} +2 -2
- package/lib/chunks/chunk-PDBNKSBQ.js +22 -0
- package/lib/chunks/chunk-PDBNKSBQ.js.map +7 -0
- package/lib/chunks/chunk-TJPJXJEK.js +22 -0
- package/lib/chunks/{chunk-EZKRLLSQ.js.map → chunk-TJPJXJEK.js.map} +1 -1
- package/lib/chunks/{monitoring-LXNVBD3G.js → monitoring-UCBNPPW2.js} +2 -2
- package/lib/chunks/{rateLimiter-GG5LPWXJ.js → rateLimiter-XKECWM33.js} +2 -2
- package/lib/chunks/{server-NODQAE3F.js → server-24XGDDO3.js} +2 -2
- package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/firebase/crud/create.d.ts +22 -1
- package/lib/firebase/crud/update.d.ts +27 -3
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +3 -3
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -8
- package/lib/shared/billing/index.d.ts +2 -0
- package/lib/shared/billing/verifyOrderCheckout.d.ts +53 -0
- package/lib/shared/crud/bulkCore.d.ts +38 -10
- package/lib/shared/crud/index.d.ts +1 -0
- package/lib/shared/crud/written.d.ts +21 -0
- package/lib/shared/index.d.ts +0 -1
- package/lib/shared/index.js +1 -1
- package/lib/shared/utils.d.ts +0 -9
- package/lib/supabase/crud/bulk.d.ts +7 -0
- package/lib/supabase/crud/create.d.ts +5 -1
- package/lib/supabase/crud/entityStore.d.ts +54 -14
- package/lib/supabase/crud/update.d.ts +7 -2
- package/lib/supabase/index.d.ts +4 -0
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +3 -3
- package/lib/vercel/api/crud/create.d.ts +6 -1
- package/lib/vercel/api/crud/update.d.ts +8 -1
- package/lib/vercel/api/index.js +1 -1
- package/package.json +3 -3
- package/src/firebase/auth/removeCustomClaims.ts +31 -1
- package/src/firebase/auth/setCustomClaims.ts +3 -0
- package/src/firebase/crud/__tests__/bulk.test.ts +50 -1
- package/src/firebase/crud/__tests__/create.test.ts +64 -0
- package/src/firebase/crud/__tests__/update.test.ts +97 -0
- package/src/firebase/crud/aggregate.ts +10 -21
- package/src/firebase/crud/bulk.ts +23 -10
- package/src/firebase/crud/create.ts +19 -18
- package/src/firebase/crud/get.ts +3 -12
- package/src/firebase/crud/list.ts +5 -4
- package/src/firebase/crud/update.ts +35 -19
- package/src/firebase/registerCrudFunctions.ts +1 -0
- package/src/shared/__tests__/bulkCore.test.ts +191 -0
- package/src/shared/__tests__/removeCustomClaims.test.ts +117 -0
- package/src/shared/__tests__/setCustomClaims.test.ts +103 -0
- package/src/shared/__tests__/utils.test.ts +0 -30
- package/src/shared/billing/__tests__/updateUserSubscription.test.ts +139 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.exports.test.ts +47 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.supabase.integration.test.ts +107 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.test.ts +233 -0
- package/src/shared/billing/helpers/updateUserSubscription.ts +10 -14
- package/src/shared/billing/index.ts +2 -0
- package/src/shared/billing/verifyOrderCheckout.ts +142 -0
- package/src/shared/crud/bulkCore.ts +110 -81
- package/src/shared/crud/index.ts +1 -0
- package/src/shared/crud/written.ts +56 -0
- package/src/shared/index.d.ts +0 -9
- package/src/shared/index.ts +0 -1
- package/src/shared/utils.ts +0 -43
- package/src/supabase/__tests__/bulk.test.ts +60 -2
- package/src/supabase/__tests__/create.test.ts +86 -0
- package/src/supabase/__tests__/entityStore.test.ts +91 -25
- package/src/supabase/__tests__/update.test.ts +107 -0
- package/src/supabase/auth/removeCustomClaims.ts +7 -2
- package/src/supabase/auth/setCustomClaims.ts +4 -2
- package/src/supabase/crud/bulk.ts +47 -0
- package/src/supabase/crud/create.ts +14 -24
- package/src/supabase/crud/entityStore.ts +106 -17
- package/src/supabase/crud/get.ts +3 -12
- package/src/supabase/crud/list.ts +5 -4
- package/src/supabase/crud/update.ts +20 -18
- package/src/supabase/index.ts +7 -0
- package/src/supabase/registerCrudFunctions.ts +1 -0
- package/src/vercel/__tests__/bulk.test.ts +16 -8
- package/src/vercel/api/crud/bulk.ts +27 -4
- package/src/vercel/api/crud/create.ts +17 -19
- package/src/vercel/api/crud/get.ts +5 -6
- package/src/vercel/api/crud/list.ts +4 -5
- package/src/vercel/api/crud/update.ts +20 -18
- package/lib/chunks/chunk-EZKRLLSQ.js +0 -22
- package/lib/chunks/chunk-F3PHE627.js +0 -22
- package/lib/chunks/chunk-F3PHE627.js.map +0 -7
- package/lib/chunks/chunk-F3WBFWPO.js +0 -151
- package/lib/chunks/chunk-G5DRV3DH.js +0 -22
- package/lib/chunks/chunk-G5DRV3DH.js.map +0 -7
- package/lib/chunks/chunk-Q2WLRFOE.js +0 -22
- package/lib/chunks/chunk-Q2WLRFOE.js.map +0 -7
- package/lib/chunks/chunk-W74UL7AY.js +0 -22
- package/lib/chunks/chunk-W74UL7AY.js.map +0 -7
- package/lib/shared/schema.d.ts +0 -56
- package/src/shared/__tests__/schema.test.ts +0 -219
- package/src/shared/schema.ts +0 -188
- /package/lib/chunks/{chunk-6NXIK35R.js.map → chunk-522YXGDA.js.map} +0 -0
- /package/lib/chunks/{chunk-GDIUOJMD.js.map → chunk-CVYSXC27.js.map} +0 -0
- /package/lib/chunks/{chunk-UH445BGK.js.map → chunk-HZM5X5A7.js.map} +0 -0
- /package/lib/chunks/{chunk-QXIOO2RL.js.map → chunk-OKRR7ST5.js.map} +0 -0
- /package/lib/chunks/{monitoring-LXNVBD3G.js.map → monitoring-UCBNPPW2.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-GG5LPWXJ.js.map → rateLimiter-XKECWM33.js.map} +0 -0
- /package/lib/chunks/{server-NODQAE3F.js.map → server-24XGDDO3.js.map} +0 -0
|
@@ -18,6 +18,6 @@ if (typeof globalThis !== 'undefined') {
|
|
|
18
18
|
globalThis.global = globalThis;
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
-
import{B as k,
|
|
21
|
+
import{$ as z,B as k,Y as s,Z as P,e as $}from"./chunk-ICNQCRLV.js";import{a as i}from"./chunk-AYY7UXNI.js";import{initializeApp as W,getApps as Z,cert as X}from"firebase-admin/app";import{getAuth as ee}from"firebase-admin/auth";import{getFirestore as te}from"firebase-admin/firestore";import{getFunctions as re}from"firebase-admin/functions";function ne(){let e=Z(),t=null;if(e.length===0?process.env.FIREBASE_ADMIN_PRIVATE_KEY&&process.env.FIREBASE_PROJECT_ID&&process.env.FIREBASE_CLIENT_EMAIL?t=W({credential:X({projectId:process.env.FIREBASE_PROJECT_ID,clientEmail:process.env.FIREBASE_CLIENT_EMAIL,privateKey:process.env.FIREBASE_ADMIN_PRIVATE_KEY.replace(/\\n/g,`
|
|
22
22
|
`)}),projectId:process.env.FIREBASE_PROJECT_ID}):t=W():t=e[0]||null,!t)throw new Error("Failed to initialize Firebase Admin app");return{app:t,auth:ee(t),firestore:te(t),functions:re(t)}}i(ne,"initializeFirebaseAdminServices");var x=z(ne);async function Se(){try{return x()}catch(e){throw s(e,{userMessage:"Failed to initialize Firebase Admin",context:{provider:"FirebaseAdmin",operation:"initFirebaseAdmin"},severity:"error"})}}i(Se,"initFirebaseAdmin");async function L(){let e=x();if(!e.app)throw new Error("Firebase Admin not initialized");return e.app}i(L,"getFirebaseAdminApp");function E(){let e=x();if(!e.auth)throw new Error("Firebase Admin auth not initialized");return e.auth}i(E,"getFirebaseAdminAuth");function J(){let e=x();if(!e.firestore)throw new Error("Firebase Admin firestore not initialized");return e.firestore}i(J,"getFirebaseAdminFirestore");function Te(){let e=x();if(!e.functions)throw new Error("Firebase Admin functions not initialized");return e.functions}i(Te,"getFirebaseAdminFunctions");var G=class{static{i(this,"FirebaseServerAuthAdapter")}async verifyToken(t){try{let r=await E().verifyIdToken(t);return{uid:r.uid,email:r.email,claims:r}}catch(r){throw P(r,"FirebaseServerAuthAdapter","verifyToken")}}async getUser(t){try{let r=await E().getUser(t);return{uid:r.uid,email:r.email,displayName:r.displayName,customClaims:r.customClaims??{}}}catch(r){if((typeof r=="object"&&r!==null&&"code"in r?r.code:void 0)==="auth/user-not-found")return null;throw P(r,"FirebaseServerAuthAdapter","getUser",{uid:t})}}async setCustomClaims(t,r){try{let o=(await E().getUser(t)).customClaims??{};await E().setCustomUserClaims(t,{...o,...r})}catch(n){throw P(n,"FirebaseServerAuthAdapter","setCustomClaims",{uid:t})}}};var O={async getServerAdmin(){try{return L()}catch(e){throw s(e,"Error getting Firebase Admin")}},async getServerFirestore(){try{return J()}catch(e){throw s(e,"Error getting Admin Firestore")}},async generateServerId(){return(await O.getServerFirestore()).collection("_").doc().id}},Pe=O.getServerAdmin,g=O.getServerFirestore,Oe=O.generateServerId;function H(e){return{seconds:Math.floor(e.getTime()/1e3),nanoseconds:e.getTime()%1e3*1e6,toDate:i(()=>new Date(e),"toDate"),toMillis:i(()=>e.getTime(),"toMillis"),isEqual:i(t=>t.seconds===Math.floor(e.getTime()/1e3)&&t.nanoseconds===e.getTime()%1e3*1e6,"isEqual"),valueOf:i(()=>`Timestamp(seconds=${Math.floor(e.getTime()/1e3)}, nanoseconds=${e.getTime()%1e3*1e6})`,"valueOf")}}i(H,"createTimestamp");function Ve(e){try{if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw s(new Error("Invalid date string format"),{context:{value:e}});return H(t)}if(e instanceof Date){if(isNaN(e.getTime()))throw s(new Error("Invalid Date object"),{context:{value:e}});return H(e)}throw s(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw s(t,"Failed to convert to Timestamp")}}i(Ve,"toTimestamp");function oe(e){try{if(e instanceof Date){if(isNaN(e.getTime()))throw s(new Error("Invalid Date object"),{context:{value:e}});return e.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function")return e.toDate().toISOString();if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw s(new Error("Invalid date string format"),{context:{value:e}});return t.toISOString()}throw s(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw s(t,"Failed to convert to ISO string")}}i(oe,"firestoreToISOString");function ie(e){return typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function"&&"seconds"in e&&"nanoseconds"in e}i(ie,"isTimestamp");function se(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(e))return!1;let r=new Date(e);return!isNaN(r.getTime())}i(se,"isISODateString");function _e(e){return _(e)}i(_e,"convertISOStringsToDates");function _(e){if(!e)return e;if(Array.isArray(e))return e.map(_);if(typeof e=="string"&&se(e))return new Date(e);if(typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=_(n);return t}return e}i(_,"convertISOStrings");function D(e,t=!1){return C(e,t)}i(D,"transformFirestoreData");function C(e,t=!1){if(!e)return e;if(t&&typeof e=="object"&&"id"in e&&"ref"in e&&"data"in e&&typeof e.data=="function"){let r=e.data(),n=C(r);return{id:e.id,...typeof n=="object"?n:{}}}if(Array.isArray(e))return e.map(r=>C(r));if(ie(e))return oe(e);if(typeof e=="object"){let r={};for(let[n,o]of Object.entries(e))r[n]=C(o);return r}return e}i(C,"transformFirestoreValue");function q(e,t=[]){return M(e,t)}i(q,"prepareForFirestore");function M(e,t){if(!e)return e;if(Array.isArray(e))return e.map(r=>M(r,t));if(e instanceof Date)return e.toISOString();if(typeof e=="object"){let r={};for(let[n,o]of Object.entries(e))t.includes(n)||o!==void 0&&(r[n]=M(o,t));return r}return e}i(M,"prepareValueForFirestore");function Me(e,t){let r={};for(let[n,o]of Object.entries(t)){if(!(n in e)){r[n]=o;continue}JSON.stringify(e[n])!==JSON.stringify(o)&&(r[n]=o)}return{...r,updatedAt:new Date().toISOString()}}i(Me,"createFirestorePartialUpdate");var F=typeof window<"u";function ce(e){return e.length>0&&typeof e[0]=="string"}i(ce,"isIdList");var b={async batchWrite(e,t,r,n,o={}){if(!t||!t.length)return{successes:0,failures:0};let{idField:a="id",generateIds:d=!0,maxBatchSize:u=450,removeFields:c=[],validate:v=!!n}=o,l={successes:0,failures:0,failedItems:[]};try{let y=[],w=await g(),p=w.batch(),h=0;for(let S=0;S<t.length;S++){let m=t[S];if(!m){l.failures++,l.failedItems?.push({index:S,error:new Error("Item is null or undefined")});continue}try{if(r==="delete"){if(!m[a])throw s(new Error(`Missing ID for delete operation (${a})`),{userMessage:"Unable to delete item: missing ID",severity:"error",context:{collection:e,idField:a,operation:r}});let f=w.collection(e).doc(m[a]);p.delete(f)}else{if(v&&n)try{k(n,m)}catch(Q){throw s(Q,{userMessage:"Validation failed for item",severity:"warning",context:{collection:e,operation:r,idField:a,itemId:m[a]}})}let f=m[a];if(!f&&r==="create"&&d)f=w.collection(e).doc().id,m={...m,[a]:f};else if(!f)throw s(new Error(`Missing ID for ${r} operation (${a})`),{userMessage:`Unable to ${r} item: missing ID`,severity:"error",context:{collection:e,idField:a,operation:r}});let V=[a,...c],T=q(m,V),N=w.collection(e).doc(f);r==="create"?p.create(N,T):r==="update"&&p.update(N,T)}h++,h>=u&&(y.push({batch:p,size:h}),p=w.batch(),h=0)}catch(f){l.failures++,l.failedItems?.push({index:S,error:f instanceof Error?f:new Error(String(f))})}}h>0&&y.push({batch:p,size:h});let R=0;for(let{batch:S,size:m}of y){try{await S.commit(),l.successes+=m}catch(f){let V=f instanceof Error?f:new Error(String(f));for(let T=R;T<R+m;T++)l.failures++,l.failedItems?.push({index:T,error:V})}R+=m}return l}catch(y){throw s(y,{userMessage:`Batch ${r} operation failed for collection ${e}`,context:{collection:e,operation:r,itemCount:t.length,processedCount:l.successes+l.failures,successCount:l.successes,failureCount:l.failures}})}},async batchCreate(e,t,r,n={}){return b.batchWrite(e,t,"create",r,n)},async batchUpdate(e,t,r,n={}){return b.batchWrite(e,t,"update",r,n)},async batchDelete(e,t,r={}){if(ce(t)){let n=r.idField||"id",o=t.map(a=>({[n]:a}));return b.batchWrite(e,o,"delete",void 0,r)}return b.batchWrite(e,t,"delete",void 0,r)},async runTransaction(e){try{return await(await g()).runTransaction(e)}catch(t){throw s(t,{userMessage:"Transaction failed"})}},async bulkGet(e,t,r={}){if(!t.length)return[];let{maxBatchSize:n=30,transform:o=!0}=r;try{let a=[];for(let c=0;c<t.length;c+=n)a.push(t.slice(c,c+n));let d=a.map(async c=>{let y=await(await g()).collection(e).where("__name__","in",c).get(),w=new Map;return y.forEach(p=>{w.set(p.id,p.data())}),c.map(p=>{let h=w.get(p);return h?o?D({id:p,...h}):{id:p,...h}:null})});return(await Promise.all(d)).flat()}catch(a){throw s(a,{userMessage:`Bulk get operation failed for collection ${e}`,context:{collection:e,idCount:t.length}})}}},A=i(e=>()=>{throw new Error(`Firebase Admin function '${e}' is not available in browser environments`)},"notAvailableInBrowser"),ze=F?A("batchWrite"):b.batchWrite,We=F?A("batchCreate"):b.batchCreate,Le=F?A("batchUpdate"):b.batchUpdate,Je=F?A("batchDelete"):b.batchDelete,Ge=F?A("runTransaction"):b.runTransaction,He=F?A("bulkGet"):b.bulkGet;function I(e,t){return s(e,{userMessage:t?`Error during ${t}`:void 0,context:{operation:t}})}i(I,"handleFirebaseError");async function ue(e,t={}){let{collection:r="subscriptions",userIdField:n="customerId"}=t;try{let d=await(await g()).collection(r).where(n,"==",e).where("status","==","active").limit(1).get();if(d.empty)return null;let u=d.docs[0];if(!u)return null;let c=u.data();return D({id:u.id,...c})}catch(o){throw I(o,"getActiveSubscription")}}i(ue,"getActiveSubscription");async function ot(e,t={}){let{collection:r="subscriptions",userIdField:n="customerId"}=t;try{return(await(await g()).collection(r).where(n,"==",e).orderBy("createdAt","desc").get()).docs.map(u=>D({id:u.id,...u.data()}))}catch(o){throw I(o,"getUserSubscriptions")}}i(ot,"getUserSubscriptions");async function de(e,t={}){let{collection:r="subscriptions"}=t;try{let n=await g(),o=new Date().toISOString(),a={...e,createdAt:e.createdAt||o,updatedAt:o},d=q(a),{id:u,...c}=d,v=u?n.collection(r).doc(u):n.collection(r).doc();return await v.set(c,{merge:!0}),{...a,id:v.id}}catch(n){throw I(n,"saveSubscription")}}i(de,"saveSubscription");async function le(e,t,r={}){let{collection:n="subscriptions"}=r;try{await(await g()).collection(n).doc(e).update({status:t,updatedAt:new Date().toISOString()})}catch(o){throw I(o,"updateSubscriptionStatus")}}i(le,"updateSubscriptionStatus");async function it(e,t,r={}){try{let n=await ue(e,r);return n?n.features&&Array.isArray(n.features)?n.features.includes(t):n.metadata&&n.metadata[t]?n.metadata[t]==="true":!1:!1}catch(n){throw s(n,{userMessage:"Failed to check feature access",severity:"error",context:{function:"hasFeatureAccess",userId:e,featureKey:t}})}}i(it,"hasFeatureAccess");async function st(e){let{rawBody:t,signature:r,webhookSecret:n,...o}=e,a;try{let u=await import("stripe"),c=u.default??u;a=new c("placeholder",{apiVersion:"2023-10-16"})}catch{throw s(new Error("stripe package is not installed"),{userMessage:"Stripe package missing \u2014 cannot verify webhook signature",severity:"error"})}let d;try{d=a.webhooks.constructEvent(t,r,n)}catch(u){throw s(u,{userMessage:"Stripe webhook signature verification failed",severity:"error",context:{function:"verifyAndHandleStripeWebhook"}})}await fe(d,o)}i(st,"verifyAndHandleStripeWebhook");async function fe(e,t={}){let r=e.type,n=e.data.object;try{switch(r){case"customer.subscription.created":case"customer.subscription.updated":await pe(n,t);break;case"customer.subscription.deleted":await le(n.id,"canceled",t);break;default:}}catch(o){throw s(o,{userMessage:`Failed to handle Stripe webhook event: ${r}`,severity:"error",context:{eventType:r,eventId:e.id}})}}i(fe,"handleStripeWebhookEvent");async function pe(e,t={}){if(!e.items.data.length)throw s(new Error("[subscription] Stripe subscription has no items"),{userMessage:"Stripe subscription has no items \u2014 cannot determine plan",severity:"error",context:{subscriptionId:e.id}});let r={id:e.id,customerId:e.customer,status:e.status,planId:e.items.data[0]?.plan.id||"",currentPeriodStart:new Date(e.current_period_start*1e3).toISOString(),currentPeriodEnd:new Date(e.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:e.cancel_at_period_end,metadata:e.metadata||{},createdAt:new Date(e.created*1e3).toISOString(),updatedAt:new Date().toISOString()};e.canceled_at&&(r.canceledAt=new Date(e.canceled_at*1e3).toISOString()),await de(r,t)}i(pe,"saveSubscriptionFromStripeEvent");var U={};function B(e){U.uniqueConstraintValidator=e}i(B,"registerUniqueConstraintValidator");function K(){return U.uniqueConstraintValidator}i(K,"getUniqueConstraintValidator");function me(){return!!U.uniqueConstraintValidator}i(me,"hasUniqueConstraintValidator");async function Y(){let e=await g(),t={checkDuplicate:i(async(r,n,o,a)=>{if(o==null)return!1;try{return(await e.collection(r).where(n,"==",o).get()).docs.some(c=>c.id!==a&&c.data()[n]===o)}catch(d){throw s(d,{userMessage:`Failed to check uniqueness for field "${n}"`,severity:"error",context:{collection:r,field:n,value:o}})}},"checkDuplicate")};return B(t),t}i(Y,"createFirestoreValidator");async function ge(){let e=await g(),t={checkDuplicate:i(async(r,n,o,a)=>{if(o==null)return!1;try{return(await e.collection(r).where(n,"==",o).get()).docs.some(c=>c.id!==a&&c.data()[n]===o)}catch(d){throw s(d,{userMessage:`Failed to check uniqueness for field "${n}"`,severity:"error",context:{collection:r,field:n,value:o}})}},"checkDuplicate")};return B(t),t}i(ge,"createAdminFirestoreValidator");async function j(e,t,r,n){if(!t.length)return;let o=K();o||(o=await Y());let a=[],u=(await Promise.allSettled(t.map(async({field:c,errorMessage:v})=>{let l=r[c];if(l==null)return;await o.checkDuplicate(e,c,l,n)&&a.push({field:c,message:v||`The ${c} must be unique`})}))).find(c=>c.status==="rejected");if(u&&u.status==="rejected")throw u.reason;if(a.length>0)throw s(new Error("Uniqueness validation failed"),{userMessage:"Uniqueness validation failed",severity:"error",context:{validationErrors:a,collection:e}})}i(j,"validateUniqueness");async function gt(e,t,r,n){try{k(e,t),e.metadata?.uniqueFields?.length&&await j(e.metadata.collection,e.metadata.uniqueFields,t,n),e.metadata?.customValidate&&await e.metadata.customValidate(t,r)}catch(o){throw $(o)?s(o,{userMessage:"Document validation failed",context:{validationErrors:o.issues,data:t},severity:"warning"}):s(o,{userMessage:"Document validation failed",context:{collection:e.metadata?.collection||"unknown"},severity:"error"})}}i(gt,"validateFirestoreDocument");function ht(e,t){return Object.assign(e,{metadata:t})}i(ht,"enhanceSchema");import{FieldValue as kt,Query as Pt,Timestamp as Ot}from"firebase-admin/firestore";export{Se as a,L as b,E as c,J as d,Te as e,G as f,Pe as g,g as h,Oe as i,H as j,Ve as k,oe as l,ie as m,_e as n,D as o,q as p,Me as q,ze as r,We as s,Le as t,Je as u,Ge as v,He as w,ue as x,ot as y,de as z,le as A,it as B,st as C,B as D,K as E,me as F,Y as G,ge as H,j as I,gt as J,ht as K,kt as L,Pt as M,Ot as N};
|
|
23
|
-
//# sourceMappingURL=chunk-
|
|
23
|
+
//# sourceMappingURL=chunk-522YXGDA.js.map
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
4
|
+
import { Buffer } from 'node:buffer';
|
|
5
|
+
import process from 'node:process';
|
|
6
|
+
|
|
7
|
+
const require = __createRequire(import.meta.url);
|
|
8
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
9
|
+
const __dirname = dirname(__filename);
|
|
10
|
+
|
|
11
|
+
if (typeof globalThis !== 'undefined') {
|
|
12
|
+
globalThis.require = require;
|
|
13
|
+
globalThis.__filename = __filename;
|
|
14
|
+
globalThis.__dirname = __dirname;
|
|
15
|
+
globalThis.Buffer = Buffer;
|
|
16
|
+
globalThis.process = process;
|
|
17
|
+
if (typeof global === 'undefined') {
|
|
18
|
+
globalThis.global = globalThis;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
import{B as te,D as re,F as oe,G as A,H as ne,I as ie,M as se,S as x,a as z,b as M,c as J,d as Z,ga as O,o as Q,v as ee}from"./chunk-ICNQCRLV.js";import{a as p}from"./chunk-W6W4L44F.js";import{a as s}from"./chunk-AYY7UXNI.js";function h(e){let t,r,o;if(e instanceof x)t=e.code,r=e.message,o=e.details;else if(e&&typeof e=="object"&&"issues"in e&&(e instanceof Error&&e.name==="ValiError"||"name"in e&&e.name==="ValiError"))t="invalid-argument",r="Validation failed",o={validationErrors:e.issues};else if(e&&typeof e=="object"&&"type"in e&&(e instanceof Error&&e.name==="EntityHookError"||"name"in e&&e.name==="EntityHookError")){let n=e;switch(n.type){case"PERMISSION_DENIED":t="permission-denied";break;case"NOT_FOUND":t="not-found";break;case"ALREADY_EXISTS":t="already-exists";break;case"VALIDATION_ERROR":t="invalid-argument";break;case"NETWORK_ERROR":t="unavailable";break;default:t="internal"}r=n.message,o=void 0}else t="internal",r="An unexpected error occurred",o=void 0;throw t==="internal"&&(r="An unexpected error occurred"),new x(r,t,o?{details:o}:void 0)}s(h,"handleError");function F(e,t,r=J){let o=Z[t];if(!o)throw new Error(`Unknown model for cost calculation: ${t}`);let n=e.promptTokens/1e6*o.promptPer1M,i=e.completionTokens/1e6*o.completionPer1M,a=n+i;return{providerCost:a,billedCost:a*r,markup:r,breakdown:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,promptCost:n,completionCost:i}}}s(F,"calculateCost");function N(){return globalThis.Deno?.env}s(N,"getDenoEnv");async function Pe(e,t){let o={anthropic:s(async()=>{let{createAnthropic:a}=await import("@ai-sdk/anthropic");return c=>a({apiKey:c})(t)},"anthropic"),openai:s(async()=>{let{createOpenAI:a}=await import("@ai-sdk/openai");return c=>a({apiKey:c})(t)},"openai"),google:s(async()=>{let{createGoogle:a}=await import("@ai-sdk/google");return c=>a({apiKey:c})(t)},"google")}[e];if(!o)throw new Error(`Unsupported AI provider: ${e}`);let n=Le(e);return(await o())(n)}s(Pe,"resolveModel");var Oe={maxRequests:30,windowMs:6e4},I=null;async function Ne(){if(I)return I;let e=$("UPSTASH_REDIS_REST_URL"),t=$("UPSTASH_REDIS_REST_TOKEN");if(!e||!t)return console.warn("[AI] UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN not set. Rate limiting disabled."),I={check:s(async()=>{},"check")},I;try{let{Ratelimit:r}=await import("@upstash/ratelimit"),{Redis:o}=await import("@upstash/redis"),n=new o({url:e,token:t}),i=new Map;return I={check:s(async(a,c)=>{let u=`${c.maxRequests}:${c.windowMs}`,d=i.get(u);if(d||(d=new r({redis:n,limiter:r.slidingWindow(c.maxRequests,`${c.windowMs}ms`),prefix:"ai_rl"}),i.set(u,d)),!(await d.limit(a)).success)throw new Error(`Rate limit exceeded. Maximum ${c.maxRequests} requests per ${c.windowMs/1e3}s.`)},"check")},I}catch(r){return console.warn("[AI] Failed to initialize Upstash rate limiter:",r instanceof Error?r.message:r),I={check:s(async()=>{},"check")},I}}s(Ne,"getRateLimiter");function Ue(e,t,r){let o={...r,...t};if(Object.keys(o).length===0)return;let n={};for(let[i,a]of Object.entries(o))n[i]=e.tool({description:a.description,inputSchema:e.jsonSchema(a.parameters)});return n}s(Ue,"resolveTools");function B(e){let t=e.inputTokens??0,r=e.outputTokens??0;return{promptTokens:t,completionTokens:r,totalTokens:e.totalTokens??t+r}}s(B,"toAIUsage");async function $e(e,t,r){let o=oe(e);if(!o.success)return U(`Invalid AI request: ${o.issues?.map(l=>l.message).join(", ")}`,400);let n=e.provider||t.provider||"anthropic",i=z[n],a=e.model||t.model||i?.default||"claude-sonnet-4-20250514";if(i){let l=i.models;if(!l.includes(a))return U(`Model '${a}' is not allowed for provider '${n}'. Allowed: ${l.join(", ")}`,400)}try{await(await Ne()).check(r.userId,t.rateLimitConfig||Oe)}catch(l){return U(l instanceof Error?l.message:"Rate limit exceeded",429)}let c;try{c=await Pe(n,a)}catch(l){return U(`Failed to initialize provider: ${l instanceof Error?l.message:String(l)}`,500)}let u=e.messages.filter(l=>l.role==="system").map(l=>l.content),d=e.systemPrompt||t.systemPrompt||(u.length>0?u.join(`
|
|
22
|
+
`):void 0),m=e.messages.filter(l=>l.role!=="system").map(l=>({role:l.role,content:l.content})),f=e.maxTokens||t.maxTokens||4096,_=e.temperature??t.temperature??.7,S=r.requestId||crypto.randomUUID(),b=await import("ai"),{streamText:C,generateText:R,toUIMessageStream:w,createUIMessageStreamResponse:g}=b,E=Ue(b,e.tools,t.tools),T=s(async l=>{if(!r.onCostRecord)return;let v=t.cost?.markup??4,Y=F(l,a,v),Ae={userId:r.userId,model:a,provider:n,usage:l,providerCost:Y.providerCost,billedCost:Y.billedCost,markup:v,timestamp:new Date().toISOString(),requestId:S};r.onCostRecord(Ae).catch(xe=>{console.error("[AI] Failed to record cost:",xe)})},"recordCost");if(e.stream!==!1){let l=C({model:c,messages:m,instructions:d,maxOutputTokens:f,temperature:_,tools:E,onEnd:s(async({usage:v})=>{await T(B(v))},"onEnd")});return g({stream:w({stream:l.stream,messageMetadata:s(({part:v})=>v.type==="finish"?{usage:B(v.totalUsage)}:void 0,"messageMetadata")})})}let y=await R({model:c,messages:m,instructions:d,maxOutputTokens:f,temperature:_,tools:E}),G=B(y.usage);await T(G);let X=y.toolCalls.map(l=>({id:l.toolCallId,name:l.toolName,args:l.input}));return new Response(JSON.stringify({message:{role:"assistant",content:y.text},usage:G,finishReason:y.finishReason,toolCalls:X.length>0?X:void 0,model:a,provider:n}),{status:200,headers:{"Content-Type":"application/json"}})}s($e,"handleAIRequest");function U(e,t){return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json"}})}s(U,"jsonError");function $(e){return typeof globalThis<"u"&&"Deno"in globalThis?N()?.get(e):typeof process<"u"?process.env[e]:void 0}s($,"getEnv");function Le(e){let r={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",google:"GOOGLE_AI_API_KEY"}[e];if(r){let n=$(r);if(n)return n}let o=$("AI_API_KEY");if(!o)throw new Error(`Missing API key. Set ${r||"AI_API_KEY"} environment variable.`);return o}s(Le,"getAIApiKey");function ae(e){return typeof globalThis<"u"&&"Deno"in globalThis?N()?.get(e):typeof process<"u"?process.env[e]:void 0}s(ae,"getEnv");function De(e,t){if(t){let n=ae(`AI_MODEL_${t.toUpperCase()}`);if(n)return n}let r=ae(`AI_TIER_${e.toUpperCase()}`);return r||(Object.values(M).find(n=>n.id===e)?.defaultModel??M.STANDARD.defaultModel)}s(De,"resolveModelForTier");function Me(e){let t=Be(e),r=We(e);return t===429?{code:"rate_limited",retryable:!0,retryAfterMs:ce(e)??5e3,severity:"transient"}:t===529||t===503?{code:"overloaded",retryable:!0,retryAfterMs:ce(e)??1e4,severity:"transient"}:t===401?{code:"auth_error",retryable:!1,severity:"critical"}:t===402||r.includes("insufficient")||r.includes("credit")?{code:"credits_exhausted",retryable:!1,severity:"critical"}:!t&&(r.includes("fetch")||r.includes("network")||r.includes("ECONNREFUSED")||r.includes("ETIMEDOUT")||r.includes("timeout")||r.includes("aborted")||e instanceof TypeError)?{code:"network",retryable:!0,retryAfterMs:3e3,severity:"transient"}:{code:"internal",retryable:!1,severity:"critical"}}s(Me,"classifyAIError");function Fe(e){switch(e){case"rate_limited":return 429;case"overloaded":return 503;case"auth_error":return 502;case"credits_exhausted":return 502;case"network":return 502;case"internal":return 500}}s(Fe,"mapClassifiedToHTTP");function Be(e){if(e&&typeof e=="object"){if("status"in e&&typeof e.status=="number")return e.status;if("error"in e&&typeof e.error=="object"&&e.error!==null&&"status"in e.error&&typeof e.error.status=="number")return e.error.status}}s(Be,"extractStatus");function We(e){return e instanceof Error?e.message.toLowerCase():typeof e=="string"?e.toLowerCase():e&&typeof e=="object"&&"message"in e?String(e.message).toLowerCase():""}s(We,"extractMessage");function ce(e){if(e&&typeof e=="object"){let t="headers"in e?e.headers:void 0;if(t&&typeof t=="object"){let r="get"in t&&typeof t.get=="function"?t.get("retry-after"):"retry-after"in t?t["retry-after"]:void 0;if(r){let o=Number(r);if(!Number.isNaN(o))return o*1e3}}}}s(ce,"extractRetryAfter");var de="2025-02-24.acacia";var W=de,P="orderId",D="productId";function L(e){return e===null?null:typeof e=="string"?e:e.id}s(L,"idOf");function ue(e){return{line1:e.line1,line2:e.line2,postalCode:e.postal_code,city:e.city,state:e.state,country:e.country}}s(ue,"toAddress");function qe(e){let t=e.customer_details,r=e.collected_information?.shipping_details??null;return{id:e.id,paymentStatus:e.payment_status,currency:e.currency,amountSubtotal:e.amount_subtotal,amountTax:e.total_details?.amount_tax??null,amountShipping:e.total_details?.amount_shipping??null,amountDiscount:e.total_details?.amount_discount??null,amountTotal:e.amount_total,customerId:L(e.customer),customer:t?{email:t.email,name:t.name,phone:t.phone,businessName:t.business_name,address:t.address?ue(t.address):null,taxIds:(t.tax_ids??[]).map(o=>({type:o.type,value:o.value})),taxExempt:t.tax_exempt}:null,shipping:r?{name:r.name,address:ue(r.address)}:null,invoiceId:L(e.invoice),paymentIntentId:L(e.payment_intent),metadata:e.metadata??{}}}s(qe,"toCheckoutSessionSnapshot");async function Ke(e,t){let r=[];for await(let o of e.checkout.sessions.listLineItems(t,{limit:100,expand:["data.price.product"]})){let n=o.price?.product,i=n&&typeof n!="string"&&!n.deleted?n.metadata[D]:void 0;if(!i)throw new Error(`Line item ${o.id} of session ${t} has no ${D} product metadata`);r.push({productId:i,name:o.description??"",quantity:o.quantity??0,amountSubtotal:o.amount_subtotal,amountDiscount:o.amount_discount,amountTax:o.amount_tax,amountTotal:o.amount_total})}return r}s(Ke,"listPaidLineItems");async function pe(e,t,r,o,n,i,a){if(!r||r.slice(0,10)<W.slice(0,10))throw new Error(`Stripe event ${t} (order ${o.metadata?.[P]??"unknown"}) was rendered with API version ${r}; StripeOrder requires ${W} or later. Webhook payloads follow the webhook endpoint's API version, not STRIPE_API_VERSION, and an existing endpoint's version cannot be edited: create a new endpoint (POST /v1/webhook_endpoints with api_version=${W}), set STRIPE_WEBHOOK_SECRET to its signing secret, disable the old endpoint, then resend the failed events. Stripe retries this event for up to 3 days.`);let c=o.metadata??{},u=c.userId,d=c[P];if(!u||!d)throw new Error(`Order session ${o.id} is missing metadata: userId=${u}, orderId=${d}`);let m={userId:u,orderId:d,billingConfigKey:n,eventId:t},f=qe(o);if(e==="checkout.session.async_payment_succeeded"||e==="checkout.session.completed"&&o.payment_status!=="unpaid"){let S=await Ke(a,o.id);await i.onOrderPaid(f,S,m),p.info("[Webhook] Order paid",{orderId:d,billingConfigKey:n,operation:"order_paid"});return}switch(e){case"checkout.session.completed":p.info("[Webhook] Order awaiting async payment",{orderId:d,billingConfigKey:n,operation:"order_payment_pending"});return;case"checkout.session.async_payment_failed":i.onOrderPaymentFailed&&await i.onOrderPaymentFailed(f,m),p.warn("[Webhook] Order payment failed",{orderId:d,billingConfigKey:n,operation:"order_payment_failed"});return;case"checkout.session.expired":i.onOrderExpired&&await i.onOrderExpired(f,m),p.info("[Webhook] Order checkout expired",{orderId:d,billingConfigKey:n,operation:"order_expired"});return;default:return}}s(pe,"handleOrderSessionEvent");function He(e){return{id:e.id,customerId:L(e.customer),type:e.type,value:e.value,country:e.country,verification:e.verification&&{status:e.verification.status,verifiedName:e.verification.verified_name,verifiedAddress:e.verification.verified_address}}}s(He,"toTaxIdSnapshot");async function le(e,t,r){let o=He(t),n=new Set;for(let[i,a]of Object.entries(r))a.type!=="StripeOrder"||!a.onTaxIdUpdated||n.has(a.onTaxIdUpdated)||(n.add(a.onTaxIdUpdated),await a.onTaxIdUpdated(o,{billingConfigKey:i,eventId:e}),p.info("[Webhook] Tax ID updated",{taxIdId:o.id,status:o.verification?.status??null,billingConfigKey:i,operation:"tax_id_updated"}));n.size===0&&p.debug("[Webhook] customer.tax_id.updated without onTaxIdUpdated hook",{eventId:e})}s(le,"handleTaxIdUpdated");function me(e,t){let{billingConfigKey:r,priceId:o}=t,[n]=t.lineItems;if(t.lineItems.length!==1||!n||n.productId!==r||n.quantity!==1)throw new Error(`'${r}' is a single-price item: lineItems must be [{ productId: '${r}', quantity: 1 }]`);let i=t.mode??(e.type==="StripeSubscription"?"subscription":"payment");if(o){if(e.priceId&&e.priceId!==o)throw new Error("Price ID mismatch with configuration");return{priceId:o,mode:i}}if(!e.priceId)throw new Error(`'${r}' has no priceId in the back config: set one, send a priceId, or use StripeOrder for server-priced lines`);return{priceId:e.priceId,mode:i}}s(me,"resolvePricePlan");function fe(e){let t=e.mode||"payment";return{mode:t,line_items:[{price:e.priceId,quantity:1}],allow_promotion_codes:e.allowPromotionCodes,success_url:e.successUrl,cancel_url:e.cancelUrl,customer_email:e.customerEmail,metadata:e.metadata,...t==="subscription"&&{subscription_data:{metadata:e.metadata}}}}s(fe,"toStripeSessionParams");var je={maxKeys:50,maxKeyLength:40,maxValueLength:500};function K(e,t){try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`)}catch(r){throw new Error(`Invalid ${t} URL: ${e}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}s(K,"validateCheckoutUrl");function _e(e){let t={};for(let[r,o]of Object.entries(e)){if(typeof o!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof o}`);t[r]=o.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"")}return t}s(_e,"sanitizeMetadata");function H(e,t){let{maxKeys:r,maxKeyLength:o,maxValueLength:n}=je,i=Object.entries(e);if(i.length>r)throw new Error(`${t}: ${i.length} metadata keys, Stripe allows at most ${r} (server keys included)`);for(let[a,c]of i){if(a.length>o)throw new Error(`${t}: metadata key '${a}' is too long (max ${o} characters)`);if(/[[\]]/.test(a))throw new Error(`${t}: metadata key '${a}' must not contain square brackets`);if(c!==null&&String(c).length>n)throw new Error(`${t}: metadata value for key '${a}' is too long (max ${n} characters)`)}}s(H,"assertStripeMetadata");function j(e){let t=[["metadata",e.metadata],["subscription_data.metadata",e.subscription_data?.metadata],["payment_intent_data.metadata",e.payment_intent_data?.metadata],["invoice_creation.invoice_data.metadata",e.invoice_creation?.invoice_data?.metadata],...(e.line_items??[]).map((r,o)=>[`line_items[${o}].price_data.product_data.metadata`,r.price_data?.product_data?.metadata])];for(let[r,o]of t)o&&H(o,r)}s(j,"assertCheckoutSessionMetadata");function Ee(e,t){if(!e.orderId)throw new Error(`resolveLineItems for '${t}' returned no orderId`);if(e.orderId.length>200)throw new Error(`resolveLineItems for '${t}': orderId is sent as client_reference_id (max 200 characters), got ${e.orderId.length}`);if(e.lineItems.length===0)throw new Error(`resolveLineItems for '${t}' returned no lines`);e.session&&ze(e.session,t);for(let r of e.lineItems){if(!r.productId||!r.name)throw new Error(`resolveLineItems for '${t}' returned a line without productId or name`);if(!Number.isInteger(r.unitAmount)||r.unitAmount<0)throw new Error(`Line '${r.productId}': unitAmount must be a non-negative integer (smallest currency unit), got ${r.unitAmount}`);if(!Number.isInteger(r.quantity)||r.quantity<1)throw new Error(`Line '${r.productId}': quantity must be a positive integer, got ${r.quantity}`);if(r.taxCode!==void 0&&!Ye.test(r.taxCode))throw new Error(`Line '${r.productId}': taxCode must be a Stripe tax code (txcd_ + 8 digits), got '${r.taxCode}'`)}}s(Ee,"assertResolvedOrder");var Ve={minSeconds:1800,maxSeconds:1440*60},he=5e3,Ge=["card","sepa_debit"],Xe=/^cus_[A-Za-z0-9]+$/,Ye=/^txcd_\d{8}$/;function ze(e,t,r=Math.floor(Date.now()/1e3)){let{taxRateIds:o,paymentMethodTypes:n,expiresAt:i,invoiceFooter:a,customerId:c}=e;if(c!==void 0&&!Xe.test(c))throw new Error(`resolveLineItems for '${t}': session.customerId must be a Stripe Customer ID (cus_...), got '${c}'`);if(o&&o.some(u=>typeof u!="string"||u.length===0))throw new Error(`resolveLineItems for '${t}': session.taxRateIds must be non-empty strings`);if(n){if(n.length===0)throw new Error(`resolveLineItems for '${t}': session.paymentMethodTypes must not be empty`);for(let u of n)if(!Ge.includes(u))throw new Error(`resolveLineItems for '${t}': unsupported payment method type '${u}'`)}if(i!==void 0){let{minSeconds:u,maxSeconds:d}=Ve;if(!Number.isInteger(i)||i<r+u||i>r+d)throw new Error(`resolveLineItems for '${t}': session.expiresAt must be a Unix time 30 minutes to 24 hours from now (Stripe), got ${i}`)}if(a!==void 0&&(a.length===0||a.length>he))throw new Error(`resolveLineItems for '${t}': session.invoiceFooter must be 1 to ${he} characters`)}s(ze,"assertResolvedOrderSession");var q=new Map;async function V(e,t,r){for(let o of t){let n=q.get(o);if(n||(n=e(o).then(i=>i.inclusive),q.set(o,n),n.catch(()=>q.delete(o))),await n)throw new Error(`'${r}': Tax Rate '${o}' is inclusive. StripeOrder unit amounts are excl. VAT: use an exclusive Tax Rate (inclusive: false).`)}}s(V,"assertExclusiveTaxRates");function ge(e){return"createStripeSession"in e}s(ge,"isSessionProvider");function ye(e,t){if(e)return e;let r=process.env.FRONTEND_URL;if(!r)throw new Error(`Missing ${t} redirect URL and FRONTEND_URL is not set`);return`${r}/billing/${t}`}s(ye,"resolveRedirectUrl");function Je(e,t){let r={...e.tax.mode==="automatic"&&{address:"auto"},...e.shipping&&{shipping:"auto"},...t&&{name:"auto"}};return Object.keys(r).length>0?r:void 0}s(Je,"customerUpdate");function Ze(e,t,r){let o=t.session??{},n=e.tax.mode==="manual"?o.taxRateIds??e.tax.taxRateIds:void 0,i={...r.metadata,[P]:t.orderId},a=e.taxIdCollection!=="disabled",c=Je(e,a),u=o.customerId?{customer:o.customerId,...c&&{customer_update:c}}:{customer_creation:e.customerCreation,customer_email:r.customerEmail};return{mode:"payment",client_reference_id:t.orderId,line_items:t.lineItems.map(d=>({price_data:{currency:e.currency,unit_amount:d.unitAmount,tax_behavior:"exclusive",product_data:{name:d.name,...d.description&&{description:d.description},...d.taxCode&&{tax_code:d.taxCode},metadata:{[D]:d.productId}}},quantity:d.quantity,...n&&n.length>0&&{tax_rates:n}})),automatic_tax:{enabled:e.tax.mode==="automatic"},tax_id_collection:a?{enabled:!0,required:e.taxIdCollection==="required"?"if_supported":"never"}:{enabled:!1},billing_address_collection:e.billingAddressCollection,...e.shipping&&{shipping_address_collection:{allowed_countries:e.shipping.allowedCountries},...e.shipping.shippingRateIds&&{shipping_options:e.shipping.shippingRateIds.map(d=>({shipping_rate:d}))}},...u,invoice_creation:{enabled:e.invoiceCreation,...e.invoiceCreation&&{invoice_data:{metadata:i,...o.invoiceFooter&&{footer:o.invoiceFooter}}}},...o.paymentMethodTypes?{payment_method_types:o.paymentMethodTypes}:e.paymentMethodConfiguration&&{payment_method_configuration:e.paymentMethodConfiguration},...o.expiresAt!==void 0&&{expires_at:o.expiresAt},allow_promotion_codes:e.allowPromotionCodes===!0,success_url:r.successUrl,cancel_url:r.cancelUrl,metadata:i,payment_intent_data:{metadata:i}}}s(Ze,"buildOrderSessionParams");async function Kt(e,...t){let r=t.length===3,[o,n,i,a]=t.length===3?[e.userId,...t]:t;if(!o)throw new Error(r?"Missing userId in request":"Missing authenticated userId");let c=e.billingConfigKey||e.metadata?.billingConfigKey;if(!c)throw new Error("Missing billingConfigKey (request or metadata)");let u={...e,billingConfigKey:c,lineItems:e.lineItems??[{productId:c,quantity:1}]},d=a[c];if(!d)throw new Error(`Invalid billing config key: ${c}`);let m=d.type==="StripeOrder",f=m?void 0:me(d,u);await i.getUser(o);let _=_e(u.metadata??{}),S={..._,userId:o,billingConfigKey:c};H(m?{...S,[P]:""}:S,"metadata");let b=u.allowPromotionCodes??!0;if(d.beforeCheckout){let g={...u,userId:o,mode:f?.mode??"payment",priceId:f?.priceId,metadata:u.metadata??{},allowPromotionCodes:b},E=await d.beforeCheckout(o,g,_);if(!E.allowed)throw new Error(E.reason||"Checkout blocked by beforeCheckout hook")}let C=ye(u.successUrl,"success"),R=ye(u.cancelUrl,"cancel");K(C,"success"),K(R,"cancel");let w;if(d.type==="StripeOrder"){if(!ge(n))throw new Error(`'${c}' is a StripeOrder: the checkout provider must implement createStripeSession (StripeSessionProvider)`);d.tax.mode==="manual"&&await V(y=>n.retrieveTaxRate(y),d.tax.taxRateIds,c);let g=await d.resolveLineItems(u.lineItems,{userId:o,billingConfigKey:c,metadata:_});Ee(g,c);let E=g.session;if(E?.taxRateIds){if(d.tax.mode!=="manual")throw new Error(`resolveLineItems for '${c}': session.taxRateIds needs tax.mode 'manual'`);await V(y=>n.retrieveTaxRate(y),E.taxRateIds,c)}if(d.tax.mode!=="automatic"&&g.lineItems.some(y=>y.taxCode!==void 0))throw new Error(`resolveLineItems for '${c}': line taxCode needs tax.mode 'automatic'`);if(E?.invoiceFooter&&!d.invoiceCreation)throw new Error(`resolveLineItems for '${c}': session.invoiceFooter needs invoiceCreation`);let T=Ze(d,g,{successUrl:C,cancelUrl:R,customerEmail:u.customerEmail,metadata:S});j(T),w=await n.createStripeSession(T)}else{let g={priceId:f?.priceId,currency:u.currency||d.currency||"eur",customerEmail:u.customerEmail,metadata:S,allowPromotionCodes:b,successUrl:C,cancelUrl:R,mode:f?.mode};if(ge(n)){let E=fe(g);j(E),w=await n.createStripeSession(E)}else w=await n.createCheckoutSession(g)}return{sessionId:w.id,sessionUrl:w.url}}s(Kt,"createCheckoutAlgorithm");async function Gt(e,t,r){let n=(await r.getUser(e)).customClaims||{};if(!t.tier||!t.status)throw new Error("Invalid subscription data: missing tier or status");let i=te(ie,{tier:t.tier,subscriptionId:t.subscriptionId??null,customerId:t.customerId??null,status:t.status,subscriptionEnd:t.subscriptionEnd,cancelAtPeriodEnd:t.cancelAtPeriodEnd??!1,updatedAt:new Date().toISOString(),isDefault:!1}),a={...n,subscription:i};await r.setCustomUserClaims(e,a)}s(Gt,"updateUserSubscription");var k=class extends Error{static{s(this,"ReservationLostError")}eventId;constructor(t){super(`Reservation of webhook event ${t} is no longer held by this worker (lease retaken or row removed)`),this.name="ReservationLostError",this.eventId=t}},Se=4200*1e3,zt=720*60*60*1e3;function Ie(){return crypto.randomUUID()}s(Ie,"newOwnerToken");function we(e){return e.subscription}s(we,"pinnedInvoiceSubscriptionId");function Qt(e,t){return e.includes(t)}s(Qt,"isOneOf");async function ke(e,t,r,o,n){let i={sessionId:t.id,billingConfigKey:t.metadata?.billingConfigKey,userId:t.metadata?.userId,paymentStatus:t.payment_status};switch(e){case"checkout.session.completed":if(t.payment_status==="unpaid"){p.info("[Webhook] Purchase awaiting async payment",{...i,operation:"purchase_payment_pending"});return}if(t.payment_status!=="paid"&&t.payment_status!=="no_payment_required")throw h(new Error(`Checkout session ${t.id} has unknown payment_status ${String(t.payment_status)}`));await ve(t,r,o,n);return;case"checkout.session.async_payment_succeeded":await ve(t,r,o,n);return;case"checkout.session.async_payment_failed":p.warn("[Webhook] Async purchase payment failed, nothing granted",{...i,operation:"purchase_payment_failed"});return;case"checkout.session.expired":p.debug("[Webhook] Checkout session expired",i);return}}s(ke,"handleTierCheckoutEvent");async function ve(e,t,r,o){let{userId:n,billingConfigKey:i}=e.metadata||{};if(!n||!i)throw h(new Error(`Missing required metadata: userId=${n}, billingConfigKey=${i}`));let a=t[i];if(!a)throw h(new Error(`Unknown billing config key: ${i}`));if(p.info("[Webhook] Processing purchase",{userId:n,configKey:i,type:a.type,operation:"purchase_processing"}),a.type==="StripePayment"){if(!o)throw h(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:a.tier,status:A.ACTIVE,subscriptionEnd:O(a.duration),customerId:e.customer},o),a.onPurchaseSuccess)try{await a.onPurchaseSuccess(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onPurchaseSuccess",userId:n,operation:"hook_execution"})}}if(a.type==="StripeSubscription"){if(!o)throw h(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:a.tier,status:A.ACTIVE,subscriptionEnd:O(a.duration),subscriptionId:e.subscription,customerId:e.customer},o),a.onSubscriptionCreated)try{await a.onSubscriptionCreated(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onSubscriptionCreated",userId:n,operation:"hook_execution"})}}p.info("[Webhook] Purchase processed",{userId:n,configKey:i,operation:"purchase_processed"})}s(ve,"grantCheckoutPurchase");async function be(e,t,r,o,n){let i=we(e);if(!i)return;let a=await o.subscriptions.retrieve(i),{userId:c,billingConfigKey:u}=a.metadata||{};if(!c||!u){p.error("[Webhook] Subscription metadata missing userId or billingConfigKey",{subscriptionId:i,hasUserId:!!c,hasBillingConfigKey:!!u,operation:"invoice_payment_succeeded_metadata_missing"});return}let d=t[u];if(!(!d||d.type!=="StripeSubscription")){if(!n)throw h(new Error("Auth provider required for subscription updates"));if(await r(c,{tier:d.tier,status:A.ACTIVE,subscriptionEnd:O(d.duration),subscriptionId:i,customerId:e.customer},n),d.onSubscriptionRenewed)try{await d.onSubscriptionRenewed(c,a.metadata||{})}catch(m){p.error("[Webhook] Hook failed (non-critical)",{error:m instanceof Error?m:new Error(String(m)),hookName:"onSubscriptionRenewed",userId:c,operation:"hook_execution"})}p.info("[Webhook] Subscription renewed",{userId:c,billingConfigKey:u,operation:"subscription_renewed"})}}s(be,"handleInvoicePaymentSucceeded");async function Ce(e,t,r,o){let{userId:n,billingConfigKey:i}=e.metadata||{};if(!n||!i)return;let a=t[i];if(!(!a||a.type!=="StripeSubscription")){if(!o)throw h(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:ne.FREE,status:A.CANCELED,subscriptionEnd:new Date(e.current_period_end*1e3).toISOString(),subscriptionId:e.id,customerId:e.customer},o),a.onSubscriptionCancelled)try{await a.onSubscriptionCancelled(n,e.metadata||{})}catch(c){p.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onSubscriptionCancelled",userId:n,operation:"hook_execution"})}p.info("[Webhook] Subscription cancelled",{userId:n,billingConfigKey:i,operation:"subscription_cancelled"})}}s(Ce,"handleSubscriptionDeleted");async function Re(e,t){let{userId:r,billingConfigKey:o}=e.metadata||{};if(!r||!o){p.warn("[Webhook] Payment failed - missing metadata",{invoiceId:e.id,hasUserId:!!r,hasBillingConfigKey:!!o,operation:"payment_failed_metadata_missing"});return}let n=t[o];if(!n){p.error("[Webhook] Payment failed - unknown billing config",{error:new Error(`Unknown billing config key: ${o}`),userId:r,billingConfigKey:o,operation:"payment_failed_unknown_config"});return}if(n.type==="StripePayment"&&n.onPurchaseFailure)try{await n.onPurchaseFailure(r,e.metadata||{})}catch(i){p.error("[Webhook] Hook failed (non-critical)",{error:i instanceof Error?i:new Error(String(i)),hookName:"onPurchaseFailure",userId:r,operation:"hook_execution"})}if(n.type==="StripeSubscription"&&n.onPaymentFailed)try{await n.onPaymentFailed(r,e.metadata||{})}catch(i){p.error("[Webhook] Hook failed (non-critical)",{error:i instanceof Error?i:new Error(String(i)),hookName:"onPaymentFailed",userId:r,operation:"hook_execution"})}p.warn("[Webhook] Payment failed",{userId:r,billingConfigKey:o,operation:"payment_failed"})}s(Re,"handlePaymentFailed");var et=3,tt=200;async function hr(e,t,r,o,n,i,a,c){try{se(n);let u=n,d=await o.webhooks.constructEventAsync(e,t,r);p.info("[Webhook] Processing event",{eventType:d.type,eventId:d.id,operation:"webhook_processing"});let m=await c.reserve(d.id);if(m.state==="processed")return p.info("[Webhook] Already processed",{eventId:d.id}),{success:!0,message:"Event already processed"};if(m.state==="in_progress")throw p.warn("[Webhook] Event in progress in another delivery",{eventId:d.id,eventType:d.type,operation:"webhook_in_progress"}),new x(`Stripe event ${d.id} is being processed by another delivery; answering non-2xx so Stripe retries it`,"unavailable",{details:{eventId:d.id,reason:"webhook_event_in_progress"}});let{ownerToken:f}=m;a||p.warn("[Webhook] authProvider is null \u2014 subscription-related events will fail",{eventType:d.type,eventId:d.id});try{await nt(d,u,i,o,a)}catch(_){throw p.error("[Webhook] Event processing failed, releasing reservation",{error:_ instanceof Error?_:new Error(String(_)),eventId:d.id,eventType:d.type,operation:"webhook_routing"}),await rt(c,d.id,f),_}return await ot(c,d.id,f),{success:!0,message:"Webhook processed"}}catch(u){throw h(u)}}s(hr,"processWebhook");async function rt(e,t,r){try{await e.release(t,r)||p.warn("[Webhook] Reservation not released: no longer owned",{eventId:t,operation:"idempotency_release_stale"})}catch(o){p.error("[Webhook] Failed to release idempotency reservation",{error:o instanceof Error?o:new Error(String(o)),eventId:t,operation:"idempotency_release"})}}s(rt,"releaseReservation");async function ot(e,t,r){for(let o=1;;o++)try{await e.markProcessed(t,r);return}catch(n){let i=n instanceof Error?n:new Error(String(n));if(n instanceof k)throw p.error("[Webhook] Event processed but its reservation was retaken by another delivery; hooks may run twice",{error:i,eventId:t,operation:"idempotency_mark_processed_lost"}),n;if(o>=et)throw p.error("[Webhook] Event processed but not recorded; answering non-2xx, Stripe will redeliver after the lease and hooks re-run",{error:i,eventId:t,attempts:o,operation:"idempotency_mark_processed_failed"}),n;p.warn("[Webhook] markProcessed failed, retrying",{eventId:t,attempt:o,error:i.message}),await new Promise(a=>setTimeout(a,tt*o))}}s(ot,"markProcessedWithRetry");async function nt(e,t,r,o,n){switch(e.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":case"checkout.session.async_payment_failed":case"checkout.session.expired":await it(e.type,e.id,e.api_version,e.data.object,t,r,o,n);break;case"invoice.payment_succeeded":await be(e.data.object,t,r,o,n);break;case"customer.subscription.deleted":await Ce(e.data.object,t,r,n);break;case"invoice.payment_failed":await Re(e.data.object,t);break;case"customer.tax_id.updated":await le(e.id,e.data.object,t);break;default:p.debug("[Webhook] Unhandled event type",{type:e.type})}}s(nt,"routeEvent");async function it(e,t,r,o,n,i,a,c){let u=o.metadata?.billingConfigKey,d=u?n[u]:void 0;if(u&&d?.type==="StripeOrder"){await pe(e,t,r,o,u,d,a);return}await ke(e,o,n,i,c)}s(it,"handleCheckoutSessionEvent");var Sr=`
|
|
23
|
+
CREATE TABLE IF NOT EXISTS public.webhook_events (
|
|
24
|
+
event_id TEXT PRIMARY KEY,
|
|
25
|
+
status TEXT NOT NULL CHECK (status IN ('processing', 'processed')),
|
|
26
|
+
owner_token UUID NOT NULL,
|
|
27
|
+
reserved_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
28
|
+
processed_at TIMESTAMPTZ
|
|
29
|
+
);
|
|
30
|
+
|
|
31
|
+
-- Only service_role accesses this table
|
|
32
|
+
ALTER TABLE public.webhook_events ENABLE ROW LEVEL SECURITY;
|
|
33
|
+
|
|
34
|
+
CREATE INDEX IF NOT EXISTS idx_webhook_events_processed_at
|
|
35
|
+
ON public.webhook_events (processed_at);
|
|
36
|
+
|
|
37
|
+
-- The functions below run as the caller (SECURITY INVOKER) and refuse every
|
|
38
|
+
-- role but service_role. EXECUTE is deliberately not revoked: on Supabase
|
|
39
|
+
-- Postgres 17.6.1.x a permission-denied function call by anon/authenticated
|
|
40
|
+
-- crashes the backend (signal 11), which restarts every connection.
|
|
41
|
+
CREATE OR REPLACE FUNCTION public.webhook_events_assert_service_role()
|
|
42
|
+
RETURNS VOID
|
|
43
|
+
LANGUAGE plpgsql
|
|
44
|
+
SET search_path = public
|
|
45
|
+
AS $$
|
|
46
|
+
BEGIN
|
|
47
|
+
IF current_user IS DISTINCT FROM 'service_role' THEN
|
|
48
|
+
RAISE EXCEPTION 'webhook_events is reserved to service_role (current role: %)', current_user
|
|
49
|
+
USING ERRCODE = 'insufficient_privilege';
|
|
50
|
+
END IF;
|
|
51
|
+
END;
|
|
52
|
+
$$;
|
|
53
|
+
|
|
54
|
+
-- Atomic reservation. Returns:
|
|
55
|
+
-- 'reserved' the caller now owns the event under p_owner_token
|
|
56
|
+
-- 'processed' the event was already processed (skip, answer 2xx)
|
|
57
|
+
-- 'in_progress' another worker holds a live lease (answer non-2xx, Stripe retries)
|
|
58
|
+
-- A 'processing' row older than the lease is retaken (abandoned worker).
|
|
59
|
+
CREATE OR REPLACE FUNCTION public.webhook_event_reserve(
|
|
60
|
+
p_event_id TEXT,
|
|
61
|
+
p_owner_token UUID,
|
|
62
|
+
p_lease_seconds INT
|
|
63
|
+
)
|
|
64
|
+
RETURNS TEXT
|
|
65
|
+
LANGUAGE plpgsql
|
|
66
|
+
SET search_path = public
|
|
67
|
+
AS $$
|
|
68
|
+
DECLARE
|
|
69
|
+
v_status TEXT;
|
|
70
|
+
BEGIN
|
|
71
|
+
PERFORM public.webhook_events_assert_service_role();
|
|
72
|
+
|
|
73
|
+
INSERT INTO public.webhook_events (event_id, status, owner_token, reserved_at)
|
|
74
|
+
VALUES (p_event_id, 'processing', p_owner_token, clock_timestamp())
|
|
75
|
+
ON CONFLICT (event_id) DO UPDATE
|
|
76
|
+
SET owner_token = EXCLUDED.owner_token,
|
|
77
|
+
reserved_at = clock_timestamp()
|
|
78
|
+
WHERE webhook_events.status = 'processing'
|
|
79
|
+
AND webhook_events.reserved_at
|
|
80
|
+
< clock_timestamp() - make_interval(secs => p_lease_seconds);
|
|
81
|
+
IF FOUND THEN
|
|
82
|
+
RETURN 'reserved';
|
|
83
|
+
END IF;
|
|
84
|
+
|
|
85
|
+
SELECT status INTO v_status
|
|
86
|
+
FROM public.webhook_events
|
|
87
|
+
WHERE event_id = p_event_id;
|
|
88
|
+
IF v_status = 'processed' THEN
|
|
89
|
+
RETURN 'processed';
|
|
90
|
+
END IF;
|
|
91
|
+
-- Live lease, or the row was released in between: Stripe retries either way
|
|
92
|
+
RETURN 'in_progress';
|
|
93
|
+
END;
|
|
94
|
+
$$;
|
|
95
|
+
|
|
96
|
+
-- Mark a reservation processed. Returns false when p_owner_token no longer owns
|
|
97
|
+
-- the row (lease retaken, released, or deleted). Repeating it for the same
|
|
98
|
+
-- owner is a no-op that returns true.
|
|
99
|
+
CREATE OR REPLACE FUNCTION public.webhook_event_mark_processed(
|
|
100
|
+
p_event_id TEXT,
|
|
101
|
+
p_owner_token UUID
|
|
102
|
+
)
|
|
103
|
+
RETURNS BOOLEAN
|
|
104
|
+
LANGUAGE plpgsql
|
|
105
|
+
SET search_path = public
|
|
106
|
+
AS $$
|
|
107
|
+
BEGIN
|
|
108
|
+
PERFORM public.webhook_events_assert_service_role();
|
|
109
|
+
|
|
110
|
+
UPDATE public.webhook_events
|
|
111
|
+
SET status = 'processed',
|
|
112
|
+
processed_at = COALESCE(processed_at, clock_timestamp())
|
|
113
|
+
WHERE event_id = p_event_id
|
|
114
|
+
AND owner_token = p_owner_token;
|
|
115
|
+
RETURN FOUND;
|
|
116
|
+
END;
|
|
117
|
+
$$;
|
|
118
|
+
|
|
119
|
+
-- Drop a reservation after a processing failure. Returns false when
|
|
120
|
+
-- p_owner_token does not own a 'processing' row (nothing is deleted).
|
|
121
|
+
CREATE OR REPLACE FUNCTION public.webhook_event_release(
|
|
122
|
+
p_event_id TEXT,
|
|
123
|
+
p_owner_token UUID
|
|
124
|
+
)
|
|
125
|
+
RETURNS BOOLEAN
|
|
126
|
+
LANGUAGE plpgsql
|
|
127
|
+
SET search_path = public
|
|
128
|
+
AS $$
|
|
129
|
+
BEGIN
|
|
130
|
+
PERFORM public.webhook_events_assert_service_role();
|
|
131
|
+
|
|
132
|
+
DELETE FROM public.webhook_events
|
|
133
|
+
WHERE event_id = p_event_id
|
|
134
|
+
AND owner_token = p_owner_token
|
|
135
|
+
AND status = 'processing';
|
|
136
|
+
RETURN FOUND;
|
|
137
|
+
END;
|
|
138
|
+
$$;
|
|
139
|
+
|
|
140
|
+
-- Enable pg_cron extension (if not already enabled)
|
|
141
|
+
CREATE EXTENSION IF NOT EXISTS pg_cron;
|
|
142
|
+
|
|
143
|
+
-- Cleanup webhook events older than 30 days (daily at 5 AM UTC).
|
|
144
|
+
-- Stripe retries an event for up to 3 days, so older rows are never read again.
|
|
145
|
+
SELECT cron.schedule(
|
|
146
|
+
'cleanup-webhook-events',
|
|
147
|
+
'0 5 * * *',
|
|
148
|
+
$$DELETE FROM public.webhook_events WHERE COALESCE(processed_at, reserved_at) < now() - interval '30 days'$$
|
|
149
|
+
);
|
|
150
|
+
`,st=ee(["reserved","processed","in_progress"]),Te=Q();function Ir(e){let t=s(async(r,o,n)=>{let{data:i,error:a}=await e.rpc(r,o);if(a)throw h(a);let c=re(n,i);if(!c.success)throw h(new Error(`${r} returned an unexpected result: ${JSON.stringify(i)}`));return c.output},"call");return{async reserve(r){let o=Ie(),n=await t("webhook_event_reserve",{p_event_id:r,p_owner_token:o,p_lease_seconds:Se/1e3},st);return n==="reserved"?{state:n,ownerToken:o}:{state:n}},async markProcessed(r,o){if(!await t("webhook_event_mark_processed",{p_event_id:r,p_owner_token:o},Te))throw new k(r)},async release(r,o){return t("webhook_event_release",{p_event_id:r,p_owner_token:o},Te)}}}s(Ir,"createSupabaseIdempotencyStore");export{h as a,F as b,N as c,$e as d,De as e,Me as f,Fe as g,j as h,de as i,W as j,P as k,D as l,qe as m,Ke as n,pe as o,He as p,le as q,Kt as r,Gt as s,k as t,Se as u,zt as v,Ie as w,Qt as x,hr as y,Sr as z,Ir as A};
|
|
151
|
+
//# sourceMappingURL=chunk-7ODXXXES.js.map
|