@donotdev/functions 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/README.md +2 -2
  2. package/lib/chunks/chunk-6NXIK35R.js +23 -0
  3. package/lib/chunks/chunk-6NXIK35R.js.map +7 -0
  4. package/lib/chunks/chunk-EZKRLLSQ.js +22 -0
  5. package/lib/chunks/chunk-EZKRLLSQ.js.map +7 -0
  6. package/lib/chunks/chunk-F3PHE627.js +22 -0
  7. package/lib/chunks/chunk-F3PHE627.js.map +7 -0
  8. package/lib/chunks/chunk-F3WBFWPO.js +151 -0
  9. package/lib/chunks/chunk-F3WBFWPO.js.map +7 -0
  10. package/lib/chunks/chunk-G5DRV3DH.js +22 -0
  11. package/lib/chunks/chunk-G5DRV3DH.js.map +7 -0
  12. package/lib/chunks/{chunk-5IPULSUX.js → chunk-GDIUOJMD.js} +2 -2
  13. package/lib/chunks/chunk-GDIUOJMD.js.map +7 -0
  14. package/lib/chunks/chunk-Q2WLRFOE.js +22 -0
  15. package/lib/chunks/chunk-Q2WLRFOE.js.map +7 -0
  16. package/lib/chunks/chunk-QXIOO2RL.js +22 -0
  17. package/lib/chunks/chunk-QXIOO2RL.js.map +7 -0
  18. package/lib/chunks/{chunk-3F4BWKQD.js → chunk-UH445BGK.js} +2 -2
  19. package/lib/chunks/chunk-W6W4L44F.js +22 -0
  20. package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
  21. package/lib/chunks/chunk-W74UL7AY.js +22 -0
  22. package/lib/chunks/chunk-W74UL7AY.js.map +7 -0
  23. package/lib/chunks/{monitoring-E7JBYBHQ.js → monitoring-LXNVBD3G.js} +2 -2
  24. package/lib/chunks/{rateLimiter-SQISLOP5.js → rateLimiter-GG5LPWXJ.js} +2 -2
  25. package/lib/chunks/server-NODQAE3F.js +22 -0
  26. package/lib/firebase/billing/index.d.ts +2 -2
  27. package/lib/firebase/crud/aggregate.d.ts +1 -1
  28. package/lib/firebase/index.d.ts +1 -1
  29. package/lib/firebase/index.js +1 -1
  30. package/lib/firebase/index.js.map +4 -4
  31. package/lib/firebase/registerCrudFunctions.d.ts +0 -5
  32. package/lib/shared/billing/checkoutPrice.d.ts +3 -6
  33. package/lib/shared/billing/checkoutValidation.d.ts +1 -1
  34. package/lib/shared/billing/createCheckout.d.ts +4 -4
  35. package/lib/shared/billing/firestoreIdempotency.d.ts +2 -2
  36. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
  37. package/lib/shared/billing/idempotency.d.ts +3 -23
  38. package/lib/shared/billing/idempotencyContract.d.ts +0 -20
  39. package/lib/shared/billing/orderWebhook.d.ts +29 -2
  40. package/lib/shared/billing/stripePinned.d.ts +43 -0
  41. package/lib/shared/denoEnv.d.ts +25 -0
  42. package/lib/shared/github.d.ts +0 -8
  43. package/lib/shared/index.js +1 -1
  44. package/lib/shared/logger.d.ts +14 -14
  45. package/lib/shared/utils/external/subscription.d.ts +0 -8
  46. package/lib/shared/utils/internal/auth.d.ts +1 -5
  47. package/lib/shared/utils.d.ts +12 -83
  48. package/lib/supabase/auth/deleteAccount.d.ts +34 -2
  49. package/lib/supabase/crud/create.d.ts +0 -8
  50. package/lib/supabase/crud/entityStore.d.ts +13 -0
  51. package/lib/supabase/crud/update.d.ts +0 -8
  52. package/lib/supabase/index.d.ts +1 -0
  53. package/lib/supabase/index.js +1 -1
  54. package/lib/supabase/index.js.map +4 -4
  55. package/lib/vercel/api/index.js +1 -1
  56. package/lib/vercel/api/index.js.map +3 -3
  57. package/package.json +9 -9
  58. package/src/firebase/auth/getCustomClaims.ts +2 -0
  59. package/src/firebase/auth/getUserAuthStatus.ts +2 -0
  60. package/src/firebase/auth/removeCustomClaims.ts +2 -0
  61. package/src/firebase/auth/setCustomClaims.ts +3 -0
  62. package/src/firebase/baseFunction.ts +8 -4
  63. package/src/firebase/billing/changePlan.ts +6 -5
  64. package/src/firebase/billing/createCustomerPortal.ts +6 -4
  65. package/src/firebase/billing/index.d.ts +0 -12
  66. package/src/firebase/billing/index.ts +0 -3
  67. package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
  68. package/src/firebase/billing/webhookHandler.ts +4 -4
  69. package/src/firebase/crud/aggregate.ts +41 -12
  70. package/src/firebase/crud/bulk.ts +7 -0
  71. package/src/firebase/crud/create.ts +21 -8
  72. package/src/firebase/crud/delete.ts +6 -1
  73. package/src/firebase/crud/get.ts +9 -2
  74. package/src/firebase/crud/list.ts +18 -8
  75. package/src/firebase/crud/update.ts +15 -7
  76. package/src/firebase/helpers/githubAccessHelper.ts +3 -0
  77. package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
  78. package/src/firebase/index.ts +0 -1
  79. package/src/firebase/oauth/disconnect.ts +2 -2
  80. package/src/firebase/oauth/exchangeToken.ts +6 -2
  81. package/src/firebase/oauth/getConnections.ts +3 -3
  82. package/src/firebase/oauth/githubAccess.ts +7 -4
  83. package/src/firebase/oauth/refreshToken.ts +3 -2
  84. package/src/firebase/registerCrudFunctions.ts +0 -19
  85. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
  86. package/src/shared/__tests__/idempotency.test.ts +0 -32
  87. package/src/shared/__tests__/utils.test.ts +0 -25
  88. package/src/shared/ai/classifyAIError.ts +18 -10
  89. package/src/shared/ai/createAIRoute.ts +2 -1
  90. package/src/shared/ai/resolveModelTier.ts +2 -1
  91. package/src/shared/billing/__tests__/createCheckout.compat.test.ts +4 -110
  92. package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
  93. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
  94. package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
  95. package/src/shared/billing/checkoutPrice.ts +7 -42
  96. package/src/shared/billing/checkoutValidation.ts +19 -2
  97. package/src/shared/billing/createCheckout.ts +59 -30
  98. package/src/shared/billing/firestoreIdempotency.ts +2 -21
  99. package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
  100. package/src/shared/billing/idempotency.ts +4 -54
  101. package/src/shared/billing/idempotencyContract.ts +0 -21
  102. package/src/shared/billing/orderWebhook.ts +69 -1
  103. package/src/shared/billing/stripeClient.ts +2 -1
  104. package/src/shared/billing/stripePinned.ts +71 -0
  105. package/src/shared/billing/tierWebhookEvents.ts +3 -2
  106. package/src/shared/billing/webhookHandler.ts +5 -1
  107. package/src/shared/crud/bulkCore.ts +3 -2
  108. package/src/shared/denoEnv.ts +29 -0
  109. package/src/shared/email/createEmailRoute.ts +2 -2
  110. package/src/shared/errorHandling.ts +8 -8
  111. package/src/shared/firebase.ts +26 -9
  112. package/src/shared/github.ts +15 -5
  113. package/src/shared/logger.ts +37 -38
  114. package/src/shared/schema.ts +6 -10
  115. package/src/shared/utils/external/date.ts +4 -4
  116. package/src/shared/utils/external/subscription.ts +2 -89
  117. package/src/shared/utils/firebaseHelpers.ts +2 -0
  118. package/src/shared/utils/internal/auth.ts +1 -6
  119. package/src/shared/utils/internal/idempotency.ts +3 -0
  120. package/src/shared/utils/internal/monitoring.ts +6 -5
  121. package/src/shared/utils/internal/validation.ts +2 -0
  122. package/src/shared/utils/schemaValidation.ts +1 -0
  123. package/src/shared/utils/validation.ts +10 -20
  124. package/src/shared/utils.ts +12 -138
  125. package/src/supabase/__tests__/aggregate.test.ts +132 -0
  126. package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
  127. package/src/supabase/auth/deleteAccount.ts +72 -5
  128. package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
  129. package/src/supabase/crud/aggregate.ts +85 -72
  130. package/src/supabase/crud/bulk.ts +3 -0
  131. package/src/supabase/crud/create.ts +13 -9
  132. package/src/supabase/crud/delete.ts +2 -1
  133. package/src/supabase/crud/entityStore.ts +1 -1
  134. package/src/supabase/crud/get.ts +2 -1
  135. package/src/supabase/crud/list.ts +23 -17
  136. package/src/supabase/crud/update.ts +9 -6
  137. package/src/supabase/edgeFunction.ts +2 -1
  138. package/src/supabase/email/createEmailFunction.ts +2 -1
  139. package/src/supabase/index.ts +1 -0
  140. package/src/supabase/oauth/exchangeToken.ts +1 -0
  141. package/src/supabase/oauth/getConnections.ts +1 -1
  142. package/src/supabase/oauth/refreshToken.ts +1 -0
  143. package/src/supabase/utils/idempotency.ts +1 -1
  144. package/src/supabase/utils/monitoring.ts +1 -0
  145. package/src/vercel/api/billing/change-plan.ts +6 -5
  146. package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
  147. package/src/vercel/api/crud/bulk.ts +7 -2
  148. package/src/vercel/api/crud/create.ts +6 -3
  149. package/src/vercel/api/crud/delete.ts +5 -2
  150. package/src/vercel/api/crud/get.ts +5 -2
  151. package/src/vercel/api/crud/list.ts +6 -3
  152. package/src/vercel/api/crud/update.ts +6 -3
  153. package/src/vercel/api/oauth/check-github-access.ts +1 -0
  154. package/src/vercel/api/oauth/exchange-token.ts +5 -2
  155. package/src/vercel/api/oauth/grant-github-access.ts +1 -0
  156. package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
  157. package/src/vercel/baseFunction.ts +5 -1
  158. package/lib/chunks/chunk-5IPULSUX.js.map +0 -7
  159. package/lib/chunks/chunk-6USHTJED.js +0 -22
  160. package/lib/chunks/chunk-6USHTJED.js.map +0 -7
  161. package/lib/chunks/chunk-CXBSROEW.js +0 -23
  162. package/lib/chunks/chunk-CXBSROEW.js.map +0 -7
  163. package/lib/chunks/chunk-GYTCWMXV.js +0 -22
  164. package/lib/chunks/chunk-GYTCWMXV.js.map +0 -7
  165. package/lib/chunks/chunk-LCDLG4VG.js +0 -151
  166. package/lib/chunks/chunk-LCDLG4VG.js.map +0 -7
  167. package/lib/chunks/chunk-MQANUSY3.js +0 -22
  168. package/lib/chunks/chunk-MQANUSY3.js.map +0 -7
  169. package/lib/chunks/chunk-OFQVO3FD.js +0 -22
  170. package/lib/chunks/chunk-OFQVO3FD.js.map +0 -7
  171. package/lib/chunks/chunk-PWAGW4R6.js +0 -22
  172. package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
  173. package/lib/chunks/chunk-US2VOP4S.js +0 -22
  174. package/lib/chunks/chunk-US2VOP4S.js.map +0 -7
  175. package/lib/chunks/chunk-YTKDNZNW.js +0 -22
  176. package/lib/chunks/chunk-YTKDNZNW.js.map +0 -7
  177. package/lib/chunks/server-IQ5JNJOM.js +0 -22
  178. package/lib/shared/utils/functionWrapper.d.ts +0 -36
  179. package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
  180. package/src/shared/utils/functionWrapper.ts +0 -73
  181. /package/lib/chunks/{chunk-3F4BWKQD.js.map → chunk-UH445BGK.js.map} +0 -0
  182. /package/lib/chunks/{monitoring-E7JBYBHQ.js.map → monitoring-LXNVBD3G.js.map} +0 -0
  183. /package/lib/chunks/{rateLimiter-SQISLOP5.js.map → rateLimiter-GG5LPWXJ.js.map} +0 -0
  184. /package/lib/chunks/{server-IQ5JNJOM.js.map → server-NODQAE3F.js.map} +0 -0
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{a,b,c,d,e}from"./chunk-5IPULSUX.js";import"./chunk-PWAGW4R6.js";import"./chunk-AYY7UXNI.js";export{b as checkPaymentFailureRate,c as checkPaymentVolume,e as cleanupOldMetrics,d as getPaymentMetricsSummary,a as recordPaymentMetrics};
22
- //# sourceMappingURL=monitoring-E7JBYBHQ.js.map
21
+ import{a,b,c,d,e}from"./chunk-GDIUOJMD.js";import"./chunk-W6W4L44F.js";import"./chunk-AYY7UXNI.js";export{b as checkPaymentFailureRate,c as checkPaymentVolume,e as cleanupOldMetrics,d as getPaymentMetricsSummary,a as recordPaymentMetrics};
22
+ //# sourceMappingURL=monitoring-LXNVBD3G.js.map
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{a,b,c,d,e,f}from"./chunk-3F4BWKQD.js";import"./chunk-PWAGW4R6.js";import"./chunk-AYY7UXNI.js";export{f as DEFAULT_RATE_LIMITS,a as checkRateLimit,b as checkRateLimitWithFirestore,e as getRateLimitStatus,c as resetRateLimit,d as resetRateLimitInFirestore};
22
- //# sourceMappingURL=rateLimiter-SQISLOP5.js.map
21
+ import{a,b,c,d,e,f}from"./chunk-UH445BGK.js";import"./chunk-W6W4L44F.js";import"./chunk-AYY7UXNI.js";export{f as DEFAULT_RATE_LIMITS,a as checkRateLimit,b as checkRateLimitWithFirestore,e as getRateLimitStatus,c as resetRateLimit,d as resetRateLimitInFirestore};
22
+ //# sourceMappingURL=rateLimiter-GG5LPWXJ.js.map
@@ -0,0 +1,22 @@
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{A,B,C,D,E,F,G,H,I,J,K,L,M,N,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-6NXIK35R.js";import"./chunk-W74UL7AY.js";import"./chunk-AYY7UXNI.js";export{L as FieldValue,f as FirebaseServerAuthAdapter,M as Query,N as Timestamp,s as batchCreate,u as batchDelete,t as batchUpdate,r as batchWrite,w as bulkGet,n as convertISOStringsToDates,H as createAdminFirestoreValidator,q as createFirestorePartialUpdate,G as createFirestoreValidator,j as createTimestamp,K as enhanceSchema,l as firestoreToISOString,i as generateServerId,x as getActiveSubscription,b as getFirebaseAdminApp,c as getFirebaseAdminAuth,d as getFirebaseAdminFirestore,e as getFirebaseAdminFunctions,g as getServerAdmin,h as getServerFirestore,E as getUniqueConstraintValidator,y as getUserSubscriptions,B as hasFeatureAccess,F as hasUniqueConstraintValidator,a as initFirebaseAdmin,m as isTimestamp,p as prepareForFirestore,D as registerUniqueConstraintValidator,v as runTransaction,z as saveSubscription,k as toTimestamp,o as transformFirestoreData,A as updateSubscriptionStatus,J as validateFirestoreDocument,I as validateUniqueness,C as verifyAndHandleStripeWebhook};
22
+ //# sourceMappingURL=server-NODQAE3F.js.map
@@ -9,8 +9,8 @@
9
9
  export { createCheckoutSession } from './createCheckoutSession.js';
10
10
  export { createStripeWebhook } from './webhookHandler.js';
11
11
  export * from '../../shared/billing/helpers/index.js';
12
- export { createFirestoreIdempotencyStore, createIdempotencyStore, resetIdempotencyStore, ReservationLostError, } from '../../shared/billing/idempotency.js';
13
- export type { IdempotencyStore, LegacyIdempotencyStore, ReservationResult, } from '../../shared/billing/idempotency.js';
12
+ export { createFirestoreIdempotencyStore, ReservationLostError, } from '../../shared/billing/idempotency.js';
13
+ export type { IdempotencyStore, ReservationResult, } from '../../shared/billing/idempotency.js';
14
14
  export { isFirestoreConfigured, isFirestoreAvailable, } from '../../shared/utils/detectFirestore.js';
15
15
  export { billingHealth } from './healthCheck.js';
16
16
  export * from './refreshSubscriptionStatus.js';
@@ -80,7 +80,7 @@ export interface AggregateConfig {
80
80
  * @author AMBROISE PARK Consulting
81
81
  */
82
82
  export declare const aggregateEntities: (collection: string, documentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>, config: AggregateConfig) => import("firebase-functions/https").CallableFunction<{
83
- where?: [string, any, any][] | undefined;
83
+ where?: [string, unknown, unknown][] | undefined;
84
84
  dateRange?: {
85
85
  field: string;
86
86
  start?: string | undefined;
@@ -14,4 +14,4 @@ export * from './helpers/index.js';
14
14
  export * from './oauth/index.js';
15
15
  export * from './scheduled/index.js';
16
16
  export { createBaseFunction } from './baseFunction.js';
17
- export { registerCrudFunctions, createCrudFunctions, type CrudFunctions, } from './registerCrudFunctions.js';
17
+ export { createCrudFunctions, type CrudFunctions, } from './registerCrudFunctions.js';
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{O as N,P as te,a as L,c as Qe}from"../chunks/chunk-US2VOP4S.js";import{a as Ae,b as vt,c as ke,e as Ct,f as Rt}from"../chunks/chunk-YTKDNZNW.js";import{a as B,b as et,c as le,d as tt}from"../chunks/chunk-6USHTJED.js";import{a as be,b as ve,c as Xe}from"../chunks/chunk-MQANUSY3.js";import{a as K,b as O,c as X,d as rt}from"../chunks/chunk-OFQVO3FD.js";import{B as Je,a as k,n as Ye,v as Ze,w as Ce,x as bt}from"../chunks/chunk-LCDLG4VG.js";import{M as se,c as h,d as v}from"../chunks/chunk-CXBSROEW.js";import{$ as ye,A as x,B as ge,G as Ne,L as F,M as Ke,N as Me,O as je,Q as ee,T as Q,X as he,Y as Ve,aa as we,ba as We,ca as ze,g as Oe,h as $,i as Pe,l as Ge,m as H,n as J,q as He,r as A,s as T,t as $e,u as oe,v as b,w as ue,z as Le}from"../chunks/chunk-GYTCWMXV.js";import"../chunks/chunk-5IPULSUX.js";import"../chunks/chunk-3F4BWKQD.js";import"../chunks/chunk-PWAGW4R6.js";import{a as u}from"../chunks/chunk-AYY7UXNI.js";import{logger as Y}from"firebase-functions/v2";import{onCall as At}from"firebase-functions/v2/https";var ot=process.env.FIREBASE_REGION||"europe-west1",St=process.env.ENFORCE_APP_CHECK==="true",me={region:ot,...St&&{enforceAppCheck:!0}},Ur={...me,invoker:"public",memory:"1GiB",timeoutSeconds:60,cors:!0},P={...me,memory:"512MiB",timeoutSeconds:30,cors:!0},M={...me,memory:"256MiB",timeoutSeconds:20},j={...me,invoker:"public",memory:"256MiB",timeoutSeconds:15,cors:!0},Re={...me,invoker:"public",memory:"256MiB",timeoutSeconds:15,cors:!0},Dr={"europe-west1":"Belgium","europe-west2":"London","europe-west3":"Frankfurt","europe-west6":"Zurich","europe-central2":"Warsaw","us-central1":"Iowa","us-east1":"South Carolina","us-east4":"Northern Virginia","us-west1":"Oregon","asia-east1":"Taiwan","asia-northeast1":"Tokyo","asia-southeast1":"Singapore"},xr=u(()=>{let r=["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"].filter(e=>!process.env[e]);if(r.length>0)throw new Error(`Missing required environment variables: ${r.join(", ")}`);console.log(`\u{1F30D} Firebase Functions configured for region: ${ot}`)},"validateEnvironment");var Ee=null,st=null,Fe=null;async function kt(){if(!Ee){let t=await import("../chunks/rateLimiter-SQISLOP5.js");Ee=t.checkRateLimitWithFirestore,st=t.DEFAULT_RATE_LIMITS}return{checkRateLimitWithFirestore:Ee,DEFAULT_RATE_LIMITS:st}}u(kt,"loadRateLimiter");async function nt(){return Fe||(Fe=(await import("../chunks/monitoring-E7JBYBHQ.js")).recordPaymentMetrics),Fe}u(nt,"loadMonitoring");function Et(t){let r=t.rawRequest.headers["x-forwarded-for"];if(r){let s=(Array.isArray(r)?r.join(","):r).split(",").map(n=>n.trim()).filter(Boolean);if(s.length>0)return s[s.length-1]}return t.rawRequest.ip||t.rawRequest.socket?.remoteAddress||"unknown"}u(Et,"getClientIp");function C(t,r,e,o,s="user",n){if(!r){let i=new Error(`Schema is undefined for ${e}. Ensure the schema is properly imported and exported.`);throw Y.error("[createBaseFunction] Schema validation failed at creation time",{operation:e,schemaType:typeof r,schemaValue:r,schemaConstructor:r?.constructor?.name}),i}if(typeof r!="object"||r===null){let i=new Error(`Invalid schema type for ${e}. Expected Valibot schema object, got ${typeof r}.`);throw Y.error("[createBaseFunction] Invalid schema type",{operation:e,schemaType:typeof r,schemaValue:r}),i}return At(t,async i=>{try{if(Y.info(`[${e}] Request received`,{hasAuth:!!i.auth,userId:i.auth?.uid||"anonymous",hasData:i.data!==void 0&&i.data!==null,dataKeys:i.data?Object.keys(i.data):[],dataPreview:(()=>{if(!i.data)return"null";try{let p=JSON.stringify(i.data);return p.length>200?p.substring(0,200)+"...":p}catch{return"[unserializable]"}})()}),i.app||Y.warn(`[AppCheck] Missing token for ${e}`,{hasAuth:!!i.auth,userId:i.auth?.uid||"anonymous"}),!r)throw Y.error(`[${e}] Schema became undefined at runtime (this should not happen)`,{operation:e,schemaType:typeof r,requestData:i.data}),new Error(`Schema is undefined for ${e} - this indicates a bundling/import issue`);let c=i.data??{},a;try{a=Le(r,c)}catch(p){throw Y.error(`Schema validation failed for ${e}`,{error:p instanceof Error?p.message:String(p),data:i.data}),p}let l=et(i.auth),m;if(s==="guest")m=i.auth?.uid||"guest";else if(m=B(i.auth),!Q(l,s))throw Y.warn(`Insufficient role for ${e}`,{userId:m,userRole:l,requiredRole:s}),new Error(`Access denied. Required role: ${s}, your role: ${l}`);if(process.env.DISABLE_RATE_LIMITING!=="true"){let{checkRateLimitWithFirestore:p,DEFAULT_RATE_LIMITS:d}=await kt(),g=s==="guest"&&m==="guest"?`ip_${Et(i)}`:`uid_${m}`,R=`${e}_${g}`,I=Object.hasOwn(d,e)?d[e]:d.api,f=await p(R,I);if(!f.allowed)throw Y.warn(`Rate limit exceeded for ${e}`,{identifier:g,remaining:f.remaining,resetAt:f.resetAt}),n?.audit({type:"rate_limit.exceeded",userId:m,metadata:{operation:e,remaining:0}}),new Error(`Rate limit exceeded. Try again in ${f.blockRemainingSeconds} seconds.`)}let w=await o(a,{uid:m,userRole:l,request:i});return process.env.ENABLE_METRICS==="true"&&await(await nt())({operation:e,userId:m,status:"success",timestamp:new Date().toISOString(),metadata:{requestId:i.rawRequest.headers["x-request-id"]||"unknown"}}),w}catch(c){process.env.ENABLE_METRICS==="true"&&await(await nt())({operation:e,userId:i.auth?.uid||"anonymous",status:"failed",timestamp:new Date().toISOString(),metadata:{error:c instanceof Error?c.message:"Unknown error",requestId:i.rawRequest.headers["x-request-id"]||"unknown"}});try{k(c)}catch(a){if(a instanceof F){let{HttpsError:l}=await import("firebase-functions/v2/https");throw new l(a.code,a.message,a.details)}throw a}}})}u(C,"createBaseFunction");var Ft=A({});async function It(t,r){return{customClaims:(await h().getUser(r.uid)).customClaims||{}}}u(It,"getCustomClaimsLogic");var Wr=u(t=>C(M,t||Ft,"get_custom_claims",It),"getCustomClaims");var _t=A({});async function Tt(t,r){let e=await h().getUser(r.uid);return{uid:e.uid,email:e.email,emailVerified:e.emailVerified,customClaims:e.customClaims||{},disabled:e.disabled}}u(Tt,"getUserAuthStatusLogic");var Jr=u(t=>C(M,t||_t,"get_user_auth_status",Tt),"getUserAuthStatus");var qt=A({claimsToRemove:x(J(b()),$(1,"At least one claim must be specified"))});async function Ut(t,r){let{claimsToRemove:e}=t,n={...(await h().getUser(r.uid)).customClaims||{}};return e.forEach(i=>{delete n[i]}),await h().setCustomUserClaims(r.uid,n),{success:!0,customClaims:n}}u(Ut,"removeCustomClaimsLogic");var no=u(t=>C(M,t||qt,"remove_custom_claims",Ut),"removeCustomClaims");var Dt=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated"]),xt=A({customClaims:oe(b(),H()),idempotencyKey:T(b())});function Bt(t){return u(async function(e,o){let{customClaims:s,idempotencyKey:n}=e;if(!s||typeof s!="object")throw new Error("customClaims must be an object");let i=Object.keys(s).filter(w=>!t.has(w));if(i.length>0)throw new Error(`Claim keys not allowed: ${i.join(", ")}`);if(n!==void 0){if(typeof n!="string"||n.length===0||n.length>256)throw new Error("idempotencyKey must be a non-empty string of at most 256 characters");if(!/^[\w\-.:@]+$/.test(n))throw new Error("idempotencyKey contains invalid characters (allowed: alphanumeric, -, _, ., :, @)")}if(n){let w=v(),p=w.collection("idempotency").doc(`claims_${n}`),d,g=!1;if(await w.runTransaction(async R=>{let I=await R.get(p);if(I.exists){d=I.data()?.result,g=!0;return}R.set(p,{processing:!0,reservedAt:new Date().toISOString()})}),g)return d}let l={...(await h().getUser(o.uid)).customClaims||{},...s};await h().setCustomUserClaims(o.uid,l);let m={success:!0,customClaims:l};return n&&await v().collection("idempotency").doc(`claims_${n}`).set({result:m,processedAt:new Date().toISOString(),processedBy:o.uid}),m},"setCustomClaimsLogic")}u(Bt,"createSetCustomClaimsLogic");var mo=u(t=>{let r=new Set(t.allowedClaimKeys);for(let o of r)if(Dt.has(o))throw new Error(`Claim key "${o}" is blocked \u2014 it is a privilege-escalation vector and cannot be self-assigned.`);let e=t.customSchema||xt;return C(M,e,"set_custom_claims",Bt(r))},"setCustomClaims");import{defineSecret as Ie}from"firebase-functions/params";var V=Ie("STRIPE_SECRET_KEY"),it=Ie("STRIPE_WEBHOOK_SECRET"),de=Ie("GITHUB_PERSONAL_ACCESS_TOKEN");async function Ot(t,r,e){K(V.value()),X();let o={async createStripeSession(n){let i=r.uid,c={...n,metadata:{...n.metadata,firebaseUid:i},...n.subscription_data&&{subscription_data:{...n.subscription_data,metadata:{...n.subscription_data.metadata,firebaseUid:i}}}};Ye(c);let a=await O.checkout.sessions.create(c);return{id:a.id,url:a.url}},async retrieveTaxRate(n){let i=await O.taxRates.retrieve(n);return{id:i.id,inclusive:i.inclusive}}},s={async getUser(n){return{customClaims:(await h().getUser(n)).customClaims}}};return Ze(t,r.uid,o,s,e)}u(Ot,"createCheckoutSessionLogic");function Pt(t){return C(P,Ne,"create_checkout_session",(r,e)=>Ot(r,e,t))}u(Pt,"createCheckoutSession");import{logger as pe}from"firebase-functions/v2";import{onRequest as Gt}from"firebase-functions/v2/https";async function Ht(t){if(t.rawBody&&Buffer.isBuffer(t.rawBody))return t.rawBody;let r=[];for await(let e of t)r.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(r)}u(Ht,"getRawBody");function $t(t){return Gt(P,async(r,e)=>{K(V.value());try{let o=r.headers["stripe-signature"];if(!o||Array.isArray(o)){let a=new Error("No Stripe signature found");throw pe.error("[Webhook] Missing signature",{error:a,operation:"webhook_signature_validation"}),k(a)}let s=it.value();if(!s){let a=new Error("STRIPE_WEBHOOK_SECRET not configured");throw pe.error("[Webhook] Missing webhook secret",{error:a,operation:"webhook_configuration"}),k(a)}let n=await Ht(r);if(!n||n.length===0){let a=new Error("Missing or empty request body");throw pe.error("[Webhook] Invalid body",{error:a,operation:"webhook_raw_body"}),k(a)}let c=await Je(n,o,s,O,t,Ce,{async getUser(a){return h().getUser(a)},async setCustomUserClaims(a,l){await h().setCustomUserClaims(a,l)}},ke());pe.info("[Firebase Webhook] Success",c),e.status(200).json({received:!0})}catch(o){throw pe.error("[Firebase Webhook] Error",{error:o instanceof Error?o.message:String(o)}),k(o)}})}u($t,"createStripeWebhook");import{onRequest as Lt}from"firebase-functions/v2/https";var Nt=Lt(P,async(t,r)=>{let e="healthy";try{await O.products.list({limit:1})}catch{e="unhealthy"}Ae()||(e=e==="healthy"?"degraded":e),["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_API_VERSION"].some(n=>!process.env[n])&&(e="unhealthy");let s=e==="unhealthy"?503:200;r.status(s).json({status:e,timestamp:Date.now()})});var Kt=A({userId:x(b(),$(1,"User ID is required"))});async function Mt(t,r){X();let e=r.uid,s=(await h().getUser(e)).customClaims||{},n=s.subscription?.subscriptionId;if(!n)throw new Error("No active subscription found");let i=await O.subscriptions.retrieve(n),c={...s,subscription:{...s.subscription,status:i.status,currentPeriodStart:new Date(i.current_period_start*1e3).toISOString(),currentPeriodEnd:new Date(i.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:i.cancel_at_period_end}};return await h().setCustomUserClaims(e,c),{success:!0,userId:e,status:i.status,currentPeriodEnd:new Date(i.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:i.cancel_at_period_end}}u(Mt,"refreshSubscriptionStatusLogic");var Qo=u(t=>C(P,t||Kt,"refresh_subscription_status",Mt),"refreshSubscriptionStatus");var jt=A({userId:b()});async function Vt(t,r){K(V.value());let e=r.uid;return await rt(e,{async getUser(s){return h().getUser(s)},async setCustomUserClaims(s,n){await h().setCustomUserClaims(s,n)}})}u(Vt,"cancelSubscriptionLogic");function Wt(){return C(P,jt,"cancel_subscription",Vt)}u(Wt,"cancelSubscription");var zt=A({userId:b(),newPriceId:b(),billingConfigKey:b()});async function Qt(t,r,e){K(V.value()),X();let o=r.uid,{newPriceId:s,billingConfigKey:n}=t,i=e[n];if(!i||i.type!=="StripeSubscription")throw k(new Error("Invalid plan"));if(i.priceId!==s)throw k(new Error("Price ID mismatch with configuration"));let l=((await h().getUser(o)).customClaims||{}).subscription?.subscriptionId;if(!l)throw k(new Error("No active subscription found"));let m=await O.subscriptions.retrieve(l),w=await O.subscriptions.update(l,{items:[{id:m.items.data[0]?.id,price:s}],proration_behavior:"create_prorations"}),d=["active","canceled","past_due","trialing","incomplete"].includes(w.status)?w.status:"incomplete";return await Ce(o,{tier:i.tier,status:d,subscriptionEnd:new Date(w.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:w.cancel_at_period_end,subscriptionId:w.id,customerId:w.customer},{async getUser(g){return h().getUser(g)},async setCustomUserClaims(g,R){await h().setCustomUserClaims(g,R)}}),{success:!0,newTier:i.tier,newPrice:i.price}}u(Qt,"changePlanLogic");function Xt(t){return C(P,zt,"change_plan",(r,e)=>Qt(r,e,t))}u(Xt,"changePlan");var Yt=A({userId:b(),returnUrl:T(x(b(),Ge()))});async function Zt(t,r){K(V.value());try{X()}catch(l){throw k(l)}let e=r.uid,{returnUrl:o}=t,s=await h().getUser(e),i=(s.customClaims||{}).subscription?.customerId||s.customClaims?.stripeCustomerId;if(!i)throw k(new Error("No Stripe customer ID found for user"));let c=o??(process.env.FRONTEND_URL?`${process.env.FRONTEND_URL}/dashboard`:void 0);if(!c)throw k(new Error("returnUrl is required (or set FRONTEND_URL env var)"));return{url:(await O.billingPortal.sessions.create({customer:i,return_url:c})).url}}u(Zt,"createCustomerPortalLogic");function Jt(){return C(P,Yt,"create_customer_portal",Zt)}u(Jt,"createCustomerPortal");function er(t,r){return t?.entries?.[r]?t.entries[r]?.visibility:void 0}u(er,"getFieldVisibilityFromSchema");function tr(t,r,e){if(t==="*")return!0;let o=er(r,t);return Qe(t,o,e)}u(tr,"canAggregateField");function ct(t){if(t!=null&&typeof t=="object"&&"amount"in t){let e=t,o=Number(e.amount);if(!Number.isFinite(o))return NaN;let s=Number(e.discountPercent),n=Number.isFinite(s)?Math.min(100,Math.max(0,s)):0;return n>0?o*(1-n/100):o}let r=Number(t);return Number.isFinite(r)?r:NaN}u(ct,"getPriceOrNumberValue");function Se(t,r){return ct(t[r])}u(Se,"getNumericValue");function at(t,r){let e=t;switch(r.filter&&(e=t.filter(o=>{let s=o[r.filter.field],n=s!=null&&typeof s=="object"&&"amount"in s?ct(s):typeof s=="number"||s==null?s:Number(s);switch(r.filter.operator){case"==":return s===r.filter.value;case"!=":return s!==r.filter.value;case">":return n>r.filter.value;case"<":return n<r.filter.value;case">=":return n>=r.filter.value;case"<=":return n<=r.filter.value;default:return!0}})),r.operation){case"count":return e.length;case"sum":return e.reduce((o,s)=>{let n=Se(s,r.field);return o+(Number.isFinite(n)?n:0)},0);case"avg":return e.length===0?null:e.reduce((s,n)=>{let i=Se(n,r.field);return s+(Number.isFinite(i)?i:0)},0)/e.length;case"min":return e.length===0?null:e.reduce((o,s)=>{let n=Se(s,r.field);return Number.isFinite(n)?o===null?n:Math.min(o,n):o},null);case"max":return e.length===0?null:e.reduce((o,s)=>{let n=Se(s,r.field);return Number.isFinite(n)?o===null?n:Math.max(o,n):o},null);default:return null}}u(at,"computeMetric");function rr(t,r,e){return u(async function(s,n){let i=v(),{userRole:c}=n,a=Q(c,"admin"),l=new Set;e.metrics?.forEach(f=>l.add(f.field)),e.groupBy?.forEach(f=>{l.add(f.field),f.metrics.forEach(E=>l.add(E.field))});for(let f of l)if(!tr(f,r,a))throw new F(`Access denied: cannot aggregate field '${f}'`,"permission-denied");let m=i.collection(t),w=[...e.where||[],...s.where||[]];for(let[f,E,_]of w)m=m.where(f,E,_);if(s.dateRange){let{field:f,start:E,end:_}=s.dateRange;E&&(m=m.where(f,">=",new Date(E))),_&&(m=m.where(f,"<=",new Date(_)))}let g=(await m.limit(1e4).get()).docs.map(f=>({id:f.id,...f.data()})),R={};if(e.metrics)for(let f of e.metrics)R[f.as]=at(g,f);let I={};if(e.groupBy)for(let f of e.groupBy){let E=new Map;for(let S of g){let q=String(S[f.field]??"null");E.has(q)||E.set(q,[]),E.get(q).push(S)}let _={};for(let[S,q]of E){_[S]={};for(let G of f.metrics)_[S][G.as]=at(q,G)}I[f.field]=_}return{metrics:R,groups:I,meta:{collection:t,totalDocs:g.length,computedAt:new Date().toISOString()}}},"aggregateEntitiesLogic")}u(rr,"aggregateEntitiesLogicFactory");var $s=u((t,r,e)=>{let o=A({where:T(J(ue([b(),H(),H()]))),dateRange:T(A({field:b(),start:T(b()),end:T(b())}))});return C(j,o,"aggregate_entities",rr(t,r,e))},"aggregateEntities");import{logger as or}from"firebase-functions/v2";function sr(t,r,e,o,s){return u(async function(i,c){let{uid:a,userRole:l}=c,m=null,w=u(()=>(m||(m=v().collection(t)),m),"col");return Xe({collection:t,ops:i,createSchema:r,draftCreateSchema:e,updateSchema:o,access:s,uid:a,userRole:l,mintInsertId:u(()=>w().doc().id,"mintInsertId"),stampInsertMetadata:u((p,d)=>{let g=p.status??ye;return{...te(p),status:g,...be(d)}},"stampInsertMetadata"),stampUpdateMetadata:u((p,d)=>({...te(p),...ve(d)}),"stampUpdateMetadata"),transact:u(async({inserts:p,updates:d,deletes:g})=>{let R=w();return v().runTransaction(async I=>{let f=[],E=[],_=[];for(let{id:S,row:q}of p)I.set(R.doc(S),q),f.push(S);for(let{id:S,patch:q}of d)I.update(R.doc(S),q),E.push(S);for(let S of g)I.delete(R.doc(S)),_.push(S);return{insertedIds:f,updatedIds:E,deletedIds:_}})},"transact"),audit:u((p,{counts:d})=>{or.info(p,{uid:a,collection:t,inserts:d.inserts,updates:d.updates,deletes:d.deletes})},"audit")})},"bulkEntityLogic")}u(sr,"bulkEntityLogicFactory");var ut=u((t,r,e,o,s)=>{let n=nr(s);return C(j,ze,`bulk_${t}`,sr(t,r,e,o,s),n)},"bulkEntity");function nr(t){let r=["guest","user","admin","super"],e=u(s=>r.indexOf(s),"rank");return[t.create,t.update,t.delete].reduce((s,n)=>e(s)<=e(n)?s:n)}u(nr,"weakestRole");import{logger as ir}from"firebase-functions/v2";function ar(t){return typeof t=="string"?t.toLowerCase():t}u(ar,"normalizeValue");function cr(t,r){let e={...t};for(let o of r)for(let s of o.fields)typeof e[s]=="string"&&(e[s]=e[s].toLowerCase());return e}u(cr,"normalizePayloadForUniqueKeys");async function ur(t,r,e,o){let s=v();for(let n of e){if(o&&n.skipForDrafts===!0||!n.fields.every(l=>r[l]!=null&&r[l]!==""))continue;let c=s.collection(t);for(let l of n.fields)c=c.where(l,"==",ar(r[l]));let a=await c.limit(1).get();if(!a.empty){let l=a.docs[0],m=N({id:l.id,...l.data()});if(n.findOrCreate)return{found:!0,existingDoc:m,findOrCreate:!0};let w=n.fields.join(" + ");throw new F(n.errorMessage||`Duplicate ${w}`,"already-exists",{details:{fields:n.fields,existingId:l.id}})}}return{found:!1}}u(ur,"checkUniqueKeys");function lr(t,r,e){return u(async function(s,n){let{payload:i,idempotencyKey:c}=s,{uid:a}=n;if(c!==void 0){if(typeof c!="string"||c.length===0||c.length>256)throw new F("idempotencyKey must be a non-empty string of at most 256 characters","invalid-argument");if(!/^[\w\-.:@]+$/.test(c))throw new F("idempotencyKey contains invalid characters","invalid-argument")}if(c){let S=v(),q=S.collection("idempotency").doc(`create_${c}`),G,W=!1;if(await S.runTransaction(async Z=>{let y=await Z.get(q);if(y.exists){G=y.data()?.result,W=!0;return}Z.set(q,{processing:!0,reservedAt:new Date().toISOString()})}),W)return G}let l=i.status??"draft",m=l==="draft",p=r.metadata?.uniqueKeys;if(p&&p.length>0){let S=await ur(t,i,p,m);if(S.found&&S.findOrCreate)return ir.info("[create_entity] findOrCreate: returning existing document",{collection:t,existingId:S.existingDoc.id}),S.existingDoc}let d=p&&p.length>0?cr(i,p):i,g={...d,status:l};m?le(g,e):le(g,r);let R={...te(d),status:l,...be(a)},I=v(),E=await(await I.collection(t).add(R)).get(),_=N({id:E.id,...E.data()});return c&&await I.collection("idempotency").doc(`create_${c}`).set({result:_,processedAt:new Date().toISOString(),processedBy:a}),_},"createEntityLogic")}u(lr,"createEntityLogicFactory");var lt=u((t,r,e,o,s)=>{let n=s||A({payload:oe(b(),H()),idempotencyKey:T(b())});return C(j,n,"create_entity",lr(t,r,e),o)},"createEntity");import"firebase-functions/v2";function mr(t){return u(async function(e,o){let{id:s}=e,n=await tt(t,s);if(n.length>0)throw new F("Cannot delete: item is referenced by other entities","permission-denied",{details:{references:n}});return await v().collection(t).doc(s).delete(),{success:!0}},"deleteEntityLogic")}u(mr,"deleteEntityLogicFactory");var mt=u((t,r,e)=>{let o=e||A({id:x(b(),$(1))});return C(j,o,"delete_entity",mr(t),r)},"deleteEntity");function dr(t,r,e){return u(async function(s,n){let{id:i}=s,{userRole:c,uid:a}=n,w=await v().collection(t).doc(i).get();if(!w.exists)throw new F("Entity not found","not-found");let p=Q(c,"admin"),d=w.data();if(!p&&we.includes(d?.status))throw new F("Entity not found","not-found");let g=d||{},I=he(g,r,c,e&&a?{documentData:g,uid:a,ownership:e}:void 0);return N({id:w.id,...I})},"getEntityLogic")}u(dr,"getEntityLogicFactory");var dt=u((t,r,e,o,s)=>{let n=o||A({id:x(b(),$(1))});return C(Re,n,"get_entity",dr(t,r,s),e)},"getEntity");import{logger as pr}from"firebase-functions/v2";function fr(t,r){let e=t;for(let o of r)e=e.where(o.field,o.op,o.value);return e}u(fr,"applyPublicCondition");function gr(t,r,e,o,s){return u(async function(i,c){let{where:a=[],orderBy:l=[],limit:m,startAfterId:w,search:p}=i,{userRole:d,uid:g}=c,R=Q(d,"admin"),I=v(),f=I.collection(t);if(R||(f=f.where("status","not-in",[...we])),o&&!R){if(s&&o.publicCondition&&o.publicCondition.length>0)f=fr(f,o.publicCondition);else if(!s&&o.ownerFields.length>0){if(o.ownerFields.length>1)throw new F(`Multiple ownerFields (${o.ownerFields.join(", ")}) are not supported for Firestore list queries. Use a single ownerIds array field with array-contains instead.`,"invalid-argument");let y=o.ownerFields[0];f=f.where(y,"==",g)}}if(p){let{field:y,query:U}=p;if(e&&e.length>0){if(!e.includes(y))throw new F(`Search field '${y}' is not allowed`,"invalid-argument")}else if(y.startsWith("_")||y.includes("."))throw new F(`Search field '${y}' is not allowed`,"invalid-argument");f=f.where(y,">=",U).where(y,"<=",U+"\uF8FF")}for(let[y,U,z]of a){if(e&&e.length>0){if(!e.includes(y)&&y!=="status"&&y!=="id")throw new F(`Where field '${y}' is not allowed`,"invalid-argument")}else if(y.startsWith("_")||y.includes("."))throw new F(`Where field '${y}' is not allowed`,"invalid-argument");f=f.where(y,U,z)}for(let[y,U]of l)f=f.orderBy(y,U);if(w){let y=await I.collection(t).doc(w).get();if(!y.exists)throw new F("Start after document not found","not-found");f=f.startAfter(y)}let E=1e3,_=m!==void 0&&m>0?Math.min(m,E):E;m!==void 0&&m>E&&pr.warn(`[list_entities] Requested limit ${m} exceeds MAX_LIST_LIMIT (${E}), capping`,{requestedLimit:m,effectiveLimit:_,collection:t}),f=f.limit(_);let S=await f.get(),q=u(y=>typeof y=="object"&&y!==null&&"thumbUrl"in y&&"fullUrl"in y,"isPictureObject"),G=u(y=>{if(Array.isArray(y)&&y.length>0){let U=y[0];if(q(U))return U.thumbUrl||U.fullUrl||null;if(typeof U=="string")return U}else if(q(y))return y.thumbUrl||y.fullUrl||null;return y},"optimizePictureField"),W=o&&g?{uid:g,ownership:o}:void 0,Z=S.docs.map(y=>{let U=y.data()||{},z=he(U,r,d,W?{...W,documentData:U}:void 0);if(e&&e.length>0){let fe={id:y.id};for(let ce of e)if(ce in z){let wt=z[ce];fe[ce]=G(wt)}return fe}let Be={id:y.id};for(let[fe,ce]of Object.entries(z))Be[fe]=G(ce);return Be});return{items:N(Z),lastVisible:S.docs[S.docs.length-1]?.id||null,count:S.docs.length,hasMore:S.docs.length===_}},"listEntitiesLogic")}u(gr,"listEntitiesLogicFactory");var _e=u((t,r,e,o,s,n,i)=>{let c=o||A({where:T(J(ue([b(),H(),H()]))),orderBy:T(J(ue([b(),$e(["asc","desc"])]))),limit:T(x(He(),Pe(1),Oe(1e3))),startAfterId:T(b()),search:T(A({field:b(),query:b()}))});return C(Re,c,"list_entities",gr(t,r,s,n,i),e)},"listEntities");function hr(t){return typeof t=="string"?t.toLowerCase():t}u(hr,"normalizeValue");function yr(t,r){let e={...t};for(let o of r)for(let s of o.fields)typeof e[s]=="string"&&(e[s]=e[s].toLowerCase());return e}u(yr,"normalizePayloadForUniqueKeys");async function wr(t,r,e,o,s,n){let i=v();for(let c of s){if(n&&c.skipForDrafts===!0||!c.fields.some(d=>d in o)||!c.fields.every(d=>e[d]!=null&&e[d]!==""))continue;let m=i.collection(t);for(let d of c.fields)m=m.where(d,"==",hr(e[d]));let p=(await m.limit(2).get()).docs.find(d=>d.id!==r);if(p){let d=c.fields.join(" + ");throw new F(c.errorMessage||`Duplicate ${d}`,"already-exists",{details:{fields:c.fields,existingId:p.id}})}}}u(wr,"checkUniqueKeysForUpdate");function br(t,r){return u(async function(o,s){let{id:n,payload:i,idempotencyKey:c}=o,{uid:a}=s;if(c!==void 0){if(typeof c!="string"||c.length===0||c.length>256)throw new F("idempotencyKey must be a non-empty string of at most 256 characters","invalid-argument");if(!/^[\w\-.:@]+$/.test(c))throw new F("idempotencyKey contains invalid characters","invalid-argument")}if(c){let G=v(),W=G.collection("idempotency").doc(`update_${c}`),Z,y=!1;if(await G.runTransaction(async U=>{let z=await U.get(W);if(z.exists){Z=z.data()?.result,y=!0;return}U.set(W,{processing:!0,reservedAt:new Date().toISOString()})}),y)return Z}let l=v(),m=l.collection(t).doc(n),w=await m.get();if(!w.exists)throw new F("Entity not found","not-found");let d={...N(w.data()),...i},R=(d.status??ye)==="draft",f=r.metadata?.uniqueKeys;f&&f.length>0&&await wr(t,n,d,i,f,R),R||le(d,r);let E=f&&f.length>0?yr(i,f):i,_={...te(E),...ve(a)};await m.update(_);let S=await m.get(),q=N({id:S.id,...S.data()});return c&&await l.collection("idempotency").doc(`update_${c}`).set({result:q,processedAt:new Date().toISOString(),processedBy:a}),q},"updateEntityLogic")}u(br,"updateEntityLogicFactory");var pt=u((t,r,e,o)=>{let s=o||A({id:x(b(),$(1)),payload:oe(b(),H()),idempotencyKey:T(b())});return C(j,s,"update_entity",br(t,r),e)},"updateEntity");import{logger as Te}from"firebase-functions/v2";async function jn(t,r,e,o="pull",s){let n=process.env.GITHUB_PERSONAL_ACCESS_TOKEN;if(!n)throw k(new Error("GitHub Personal Access Token not configured"));let i=new L({accessToken:n});if(await i.isCollaborator(e.owner,e.repo,r)||await i.addCollaborator({owner:e.owner,repo:e.repo,username:r,permission:o}),s){let l=(await h().getUser(t)).customClaims||{};await h().setCustomUserClaims(t,{...l,...s,githubAccess:!0,githubUsername:r,githubRepoAccess:{owner:e.owner,repo:e.repo,permission:o,grantedAt:new Date().toISOString()}})}process.env.SAVE_GITHUB_ACCESS_TO_FIRESTORE==="true"&&await v().collection("githubAccess").doc(t).set({githubUsername:r,repoConfig:e,permission:o,accessGranted:!0,grantedAt:Date.now()},{merge:!0}),Te.info("GitHub repository access granted",{userId:t,githubUsername:r,repoConfig:e,permission:o})}u(jn,"grantGitHubAccessHelper");async function Vn(t,r){let o=(await h().getUser(t)).customClaims||{};return r?Object.fromEntries(r.filter(n=>n in o).map(n=>[n,o[n]])):o}u(Vn,"getCustomClaimsHelper");async function Wn(t,r,e=!0){let o={};if(e)try{o=(await h().getUser(t)).customClaims||{}}catch(n){Te.warn("Could not fetch current claims for user",{userId:t,error:n})}let s=e?{...o,...r}:r;await h().setCustomUserClaims(t,s),process.env.SAVE_CLAIMS_TO_FIRESTORE==="true"&&await v().collection("userClaims").doc(t).set({claims:s,updatedAt:new Date().toISOString()},{merge:!0}),Te.info("Custom claims updated",{userId:t,claimKeys:Object.keys(r)})}u(Wn,"setCustomClaimsHelper");import{logger as ne}from"firebase-functions/v2";async function ei(t,r,e,o="member"){try{let s=process.env.GITHUB_PERSONAL_ACCESS_TOKEN;if(!s)throw new Error("GitHub Personal Access Token not configured");let n=new L({accessToken:s});if(!await n.isTeamMember(e.org,e.team,r)&&!await n.addTeamMember(e.org,e.team,r,o))throw new Error(`Failed to add ${r} to team ${e.org}/${e.team}`);let a=(await h().getUser(t)).customClaims||{},l={...a,githubTeamAccess:{...a.githubTeamAccess,[e.org]:{...a.githubTeamAccess?.[e.org],[e.team]:{username:r,role:o,grantedAt:new Date().toISOString()}}}};await h().setCustomUserClaims(t,l),ne.info("GitHub team access granted",{userId:t,githubUsername:r,teamConfig:e,role:o})}catch(s){throw ne.error("Failed to grant GitHub team access",{userId:t,githubUsername:r,teamConfig:e,error:s instanceof Error?s.message:String(s)}),k(s)}}u(ei,"grantGitHubTeamAccessHelper");async function ti(t,r,e){try{let o=process.env.GITHUB_PERSONAL_ACCESS_TOKEN;if(!o)throw new Error("GitHub Personal Access Token not configured");let s=new L({accessToken:o});await s.isTeamMember(e.org,e.team,r)&&(await s.removeTeamMember(e.org,e.team,r)||ne.warn(`Failed to remove ${r} from team ${e.org}/${e.team}`));let c=(await h().getUser(t)).customClaims||{};if(c.githubTeamAccess?.[e.org]?.[e.team]){let a={...c};a.githubTeamAccess[e.org]&&(delete a.githubTeamAccess[e.org][e.team],Object.keys(a.githubTeamAccess[e.org]).length===0&&delete a.githubTeamAccess[e.org]),await h().setCustomUserClaims(t,a)}ne.info("GitHub team access revoked",{userId:t,githubUsername:r,teamConfig:e})}catch(o){throw ne.error("Failed to revoke GitHub team access",{userId:t,githubUsername:r,teamConfig:e,error:o instanceof Error?o.message:String(o)}),k(o)}}u(ti,"revokeGitHubTeamAccessHelper");async function ri(t,r,e){try{let o=process.env.GITHUB_PERSONAL_ACCESS_TOKEN;if(!o)throw new Error("GitHub Personal Access Token not configured");let n=await new L({accessToken:o}).isTeamMember(e.org,e.team,r),a=((await h().getUser(t)).customClaims||{}).githubTeamAccess?.[e.org]?.[e.team];return{hasTeamAccess:n,hasCustomClaimsAccess:!!a,accessDetails:a||null}}catch(o){throw ne.error("Failed to check GitHub team access",{userId:t,githubUsername:r,teamConfig:e,error:o instanceof Error?o.message:String(o)}),k(o)}}u(ri,"checkGitHubTeamAccessHelper");import{onCall as vr,HttpsError as qe}from"firebase-functions/v2/https";var ui=vr(async t=>{let r=B(t.auth),{provider:e,purpose:o}=t.data;try{let n=await v().collection("oauth_connections").where("userId","==",r).where("provider","==",e).where("purpose","==",o).get();if(n.empty)throw new qe("not-found","Connection not found");let i=n.docs[0];if(!i)throw new qe("not-found","Connection not found");let c=i.data();if(c?.credentials?.accessToken)try{await Cr(e,c.credentials.accessToken)}catch(a){console.warn(`Failed to revoke token for ${e}:`,a)}return await i.ref.delete(),{success:!0}}catch(s){throw console.error(`Error disconnecting ${e}:`,s),new qe("internal",s instanceof Error?s.message:"Failed to disconnect")}});async function Cr(t,r){try{let e=ee[t],o="revokeUrl"in e?e.revokeUrl:null;if(!o)return;let s=await fetch(o.toString(),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:r}).toString()});s.ok||console.warn(`Failed to revoke token for ${t}:`,s.status)}catch(e){console.error(`Error revoking token for ${t}:`,e)}}u(Cr,"revokeToken");import{onCall as Rr,HttpsError as ie}from"firebase-functions/v2/https";var hi=Rr(async t=>{let r=B(t.auth),{provider:e,purpose:o,code:s,redirectUri:n,codeVerifier:i,idempotencyKey:c}=t.data;if(c!==void 0){if(typeof c!="string"||c.length===0||c.length>256)throw new ie("invalid-argument","idempotencyKey must be a non-empty string of at most 256 characters");if(!/^[\w\-.:@]+$/.test(c))throw new ie("invalid-argument","idempotencyKey contains invalid characters")}if(!e||!o||!s||!n)throw new ie("invalid-argument","Missing required parameters");if(c){let a=v(),l=a.collection("idempotency").doc(`oauth_${c}`),m,w=!1;if(await a.runTransaction(async p=>{let d=await p.get(l);if(d.exists){m=d.data()?.result,w=!0;return}p.set(l,{processing:!0,reservedAt:new Date().toISOString()})}),w)return m}try{let a=ee[e];if(!a)throw new ie("invalid-argument",`Provider ${e} is not supported`);let l=e.toUpperCase(),m=process.env[`${l}_CLIENT_ID`],w=process.env[`${l}_CLIENT_SECRET`];if(!m||!w)throw new ie("failed-precondition",`Provider ${e} is not configured`);let p=await fetch(a.endpoints.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"authorization_code",client_id:m,client_secret:w,code:s,redirect_uri:n,...i?{code_verifier:i}:{}}).toString()});if(!p.ok){let f=await p.text();throw console.error(`Token exchange error for ${e}: ${p.status} ${p.statusText}`),new Error(`Failed to exchange code for token: ${p.status} ${p.statusText}`)}let d=await p.json(),g={accessToken:d.access_token,refreshToken:d.refresh_token||null,expiresAt:d.expires_in?Math.floor(Date.now()/1e3)+d.expires_in:null,idToken:d.id_token||null,scope:d.scope?d.scope.split(" "):[]},R=null;g.accessToken&&(R=await Sr(e,g.accessToken)),await Ar({uid:r,provider:e,purpose:o,credentials:g,profile:R});let I={success:!0,credentials:g,profile:R};return c&&await v().collection("idempotency").doc(`oauth_${c}`).set({result:I,processedAt:new Date().toISOString(),processedBy:r}),I}catch(a){throw console.error(`OAuth token exchange error for ${e}:`,a instanceof Error?a.message:"Unknown error"),new ie("internal",a instanceof Error?a.message:"Failed to exchange code for token")}});async function Sr(t,r){try{let e=ee[t];if(!e?.endpoints?.profileUrl)return null;let o=await fetch(e.endpoints.profileUrl,{headers:{Authorization:`Bearer ${r}`,Accept:"application/json"}});return o.ok?await o.json():(console.warn(`Failed to fetch profile for ${t}:`,o.status),null)}catch(e){return console.error(`Error fetching profile for ${t}:`,e),null}}u(Sr,"fetchUserProfile");async function Ar(t){try{let e=await v().collection("oauth_connections").where("userId","==",t.uid).where("provider","==",t.provider).where("purpose","==",t.purpose).get(),o={userId:t.uid,provider:t.provider,purpose:t.purpose,credentials:t.credentials,profile:t.profile,connected:!0,createdAt:se.serverTimestamp(),updatedAt:se.serverTimestamp(),lastUsed:se.serverTimestamp()};if(e.empty)await v().collection("oauth_connections").add(o);else{let s=e.docs[0];s&&await s.ref.update({...o,createdAt:s.data()?.createdAt})}}catch(r){throw console.error("Error saving OAuth connection:",r),r}}u(Ar,"saveOAuthConnection");import{onCall as kr,HttpsError as Er}from"firebase-functions/v2/https";var Ri=kr(async t=>{let r=B(t.auth),{purpose:e}=t.data||{};try{let o=v().collection("oauth_connections").where("userId","==",r);return{connections:(await(e?o.where("purpose","==",e):o).get()).docs.map(c=>{let a=c.data(),l=a.credentials?.expiresAt?a.credentials.expiresAt<Math.floor(Date.now()/1e3):!1;return{id:c.id,userId:a.userId,provider:a.provider,purpose:a.purpose,connected:!l,createdAt:a.createdAt?.toDate?.()?a.createdAt.toDate().toISOString():a.createdAt,updatedAt:a.updatedAt?.toDate?.()?a.updatedAt.toDate().toISOString():a.updatedAt,lastUsed:a.lastUsed?.toDate?.()?a.lastUsed.toDate().toISOString():a.lastUsed,hasCredentials:!l&&!!a.credentials,profile:a.profile}})}}catch(o){throw console.error("Error getting OAuth connections:",o),new Er("internal",o instanceof Error?o.message:"Failed to get connections")}});import{logger as Ue}from"firebase-functions/v2";import{onCall as De}from"firebase-functions/v2/https";var xe={...M,secrets:[de]};async function ft(t,r){try{let e=B(t.auth),s=ge(r||Ke,t.data);if(!s.success)throw new Error(`Validation failed: ${s.issues.map(g=>g.message).join(", ")}`);let n=s.output,{githubUsername:i,repoConfig:c,permission:a="push",customClaims:l}=n,m=e,w=de.value();if(!w)throw k(new Error("GitHub Personal Access Token not configured"));if(await new L({accessToken:w}).addCollaborator({owner:c.owner,repo:c.repo,username:i,permission:a}),l){let g=await h().getUser(m),R={...g.customClaims,...l,githubAccess:{...g.customClaims?.githubAccess,[c.owner]:{...g.customClaims?.githubAccess?.[c.owner],[c.repo]:{username:i,permission:a,grantedAt:new Date().toISOString()}}}};await h().setCustomUserClaims(m,R)}let d={success:!0,userId:m,githubUsername:i,repoConfig:c,permission:a,message:`Successfully granted ${i} ${a} access to ${c.owner}/${c.repo}`};return Ue.info("GitHub access granted",{userId:d.userId,githubUsername:d.githubUsername,repoConfig:d.repoConfig}),d}catch(e){throw k(e)}}u(ft,"grantGitHubAccessInternal");var Di=De(xe,async t=>await ft(t));async function xi(t,r){return await ft(t,r)}u(xi,"grantGitHubAccessWithSchema");async function gt(t,r){try{let e=B(t.auth),s=ge(r||Me,t.data);if(!s.success)throw new Error(`Validation failed: ${s.issues.map(g=>g.message).join(", ")}`);let{githubUsername:n,repoConfig:i}=s.output,c=e,a=de.value();if(!a)throw k(new Error("GitHub Personal Access Token not configured"));await new L({accessToken:a}).removeCollaborator(i.owner,i.repo,n)||Ue.warn(`Failed to remove ${n} from GitHub repository`);let p=(await h().getUser(c)).customClaims||{};if(p.githubAccess?.[i.owner]?.[i.repo]){let g={...p};g.githubAccess[i.owner]&&(delete g.githubAccess[i.owner][i.repo],Object.keys(g.githubAccess[i.owner]).length===0&&delete g.githubAccess[i.owner]),await h().setCustomUserClaims(c,g)}let d={success:!0,userId:c,githubUsername:n,repoConfig:i,message:`Successfully revoked ${n} access to ${i.owner}/${i.repo}`};return Ue.info("GitHub access revoked",{userId:d.userId,githubUsername:d.githubUsername,repoConfig:d.repoConfig}),d}catch(e){throw k(e)}}u(gt,"revokeGitHubAccessInternal");var Bi=De(xe,async t=>await gt(t));async function Oi(t,r){return await gt(t,r)}u(Oi,"revokeGitHubAccessWithSchema");async function ht(t,r){try{let e=B(t.auth),s=ge(r||je,t.data);if(!s.success)throw new Error(`Validation failed: ${s.issues.map(R=>R.message).join(", ")}`);let{githubUsername:n,repoConfig:i}=s.output,c=e,a=de.value();if(!a)throw k(new Error("GitHub Personal Access Token not configured"));let m=await new L({accessToken:a}).isCollaborator(i.owner,i.repo,n),d=((await h().getUser(c)).customClaims||{}).githubAccess?.[i.owner]?.[i.repo];return{success:!0,userId:c,githubUsername:n,repoConfig:i,hasAccess:m,customClaimsAccess:!!d,accessDetails:d||null,message:m?`${n} has access to ${i.owner}/${i.repo}`:`${n} does not have access to ${i.owner}/${i.repo}`}}catch(e){throw k(e)}}u(ht,"checkGitHubAccessInternal");var Pi=De(xe,async t=>await ht(t));async function Gi(t,r){return await ht(t,r)}u(Gi,"checkGitHubAccessWithSchema");import{onCall as Fr,HttpsError as ae}from"firebase-functions/v2/https";var ji=Fr(async t=>{let r=B(t.auth),{provider:e,refreshToken:o,redirectUri:s}=t.data;try{let n=ee[e];if(!n?.endpoints?.tokenUrl)throw new ae("invalid-argument",`Provider ${e} does not support token refresh`);let i=e.toUpperCase(),c=process.env[`${i}_CLIENT_ID`],a=process.env[`${i}_CLIENT_SECRET`];if(!c||!a)throw new ae("failed-precondition",`Provider ${e} is not configured`);let l=await fetch(n.endpoints.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"refresh_token",client_id:c,client_secret:a,refresh_token:o,redirect_uri:s}).toString()});if(!l.ok){let d=await l.text();throw console.error(`Token refresh error for ${e}:`,d),new Error(`Failed to refresh token: ${l.status} ${l.statusText}`)}let m=await l.json(),p=await v().collection("oauth_connections").where("userId","==",r).where("provider","==",e).get();if(p.empty)throw new ae("not-found","OAuth connection not found");{let d=p.docs[0];if(!d)throw new ae("not-found","OAuth connection document not found");let g=d.data();if(!g)throw new ae("internal","OAuth connection data is invalid");let R={...g.credentials,accessToken:m.access_token,expiresAt:m.expires_in?Math.floor(Date.now()/1e3)+m.expires_in:g.credentials.expiresAt,refreshToken:m.refresh_token||g.credentials.refreshToken};return await d.ref.update({credentials:R,updatedAt:se.serverTimestamp()}),{success:!0,credentials:{accessToken:m.access_token,refreshToken:m.refresh_token,expiresAt:m.expires_in?Math.floor(Date.now()/1e3)+m.expires_in:null,scope:m.scope?m.scope.split(" "):[]}}}}catch(n){throw console.error(`OAuth token refresh error for ${e}:`,n),new ae("internal",n instanceof Error?n.message:"Failed to refresh token")}});import{logger as re}from"firebase-functions/v2";import{onSchedule as Ir}from"firebase-functions/v2/scheduler";var Yi=Ir({schedule:"0 0 * * *",timeZone:"UTC"},async()=>{try{re.info("Starting expired subscription check");let t=h(),r=v(),e=new Date,o=process.env.USERS_COLLECTION_PATH||"users",n=await r.collection(o).where("subscription.status","==","active").get(),i=0,c=0;for(let a of n.docs)try{let m=a.data().subscription;if(!m||!m.subscriptionEnd)continue;new Date(m.subscriptionEnd)<e&&(re.info("Found expired subscription",{userId:a.id,subscriptionEnd:m.subscriptionEnd,tier:m.tier}),await _r(a.id,m),c++),i++}catch(l){re.error("Error processing user subscription",{userId:a.id,error:l instanceof Error?l.message:String(l)})}re.info("Expired subscription check completed",{processedCount:i,expiredCount:c})}catch(t){throw re.error("Failed to check expired subscriptions",{error:t instanceof Error?t.message:String(t)}),k(t)}});async function _r(t,r){try{let e=h(),s=(await e.getUser(t)).customClaims||{},n=new Date().toISOString(),i={...s,subscription:{...r,status:"expired",expiredAt:n,updatedAt:n}};await e.setCustomUserClaims(t,i),re.info("Successfully revoked expired subscription",{userId:t,tier:r.tier})}catch(e){throw re.error("Failed to revoke expired subscription",{userId:t,error:e instanceof Error?e.message:String(e)}),e}}u(_r,"revokeExpiredSubscription");function yt(t,r={}){let{prefix:e=""}=r,o={};for(let[s,n]of Object.entries(t)){if(!qr(n))continue;let i=n,c=i.collection,a=We(i),l=i.access;o[`${e}create_${c}`]=lt(c,a.create,a.draft,l.create),o[`${e}get_${c}`]=dt(c,a.get,l.read,void 0,i.ownership),o[`${e}list_${c}`]=_e(c,a.get,l.read,void 0,i.listFields,i.ownership,!1),o[`${e}listCard_${c}`]=_e(c,a.get,l.read,void 0,Ve(i),i.ownership,!0),o[`${e}update_${c}`]=pt(c,a.update,l.update),o[`${e}delete_${c}`]=mt(c,l.delete),o[`${e}bulk_${c}`]=ut(c,a.create,a.draft,a.update,{create:l.create,update:l.update,delete:l.delete})}return o}u(yt,"createCrudFunctions");function Tr(t,r,e={}){let o=yt(t,e);return r&&Object.assign(r,o),o}u(Tr,"registerCrudFunctions");function qr(t){return typeof t=="object"&&t!==null&&"collection"in t&&"fields"in t}u(qr,"isEntity");export{M as AUTH_CONFIG,Dr as AVAILABLE_REGIONS,j as CRUD_CONFIG,Re as CRUD_READ_CONFIG,ot as FIREBASE_REGION,Ur as FUNCTION_CONFIG,bt as ReservationLostError,P as STRIPE_CONFIG,$s as aggregateEntities,Nt as billingHealth,ut as bulkEntity,sr as bulkEntityLogicFactory,Wt as cancelSubscription,Xt as changePlan,Yi as checkExpiredSubscriptions,Pi as checkGitHubAccess,Gi as checkGitHubAccessWithSchema,ri as checkGitHubTeamAccessHelper,C as createBaseFunction,Pt as createCheckoutSession,yt as createCrudFunctions,Jt as createCustomerPortal,lt as createEntity,ke as createFirestoreIdempotencyStore,Ct as createIdempotencyStore,$t as createStripeWebhook,mt as deleteEntity,ui as disconnect,hi as exchangeToken,Ri as getConnections,Wr as getCustomClaims,Vn as getCustomClaimsHelper,dt as getEntity,Jr as getUserAuthStatus,Di as grantGitHubAccess,jn as grantGitHubAccessHelper,xi as grantGitHubAccessWithSchema,ei as grantGitHubTeamAccessHelper,vt as isFirestoreAvailable,Ae as isFirestoreConfigured,_e as listEntities,Qo as refreshSubscriptionStatus,ji as refreshToken,Tr as registerCrudFunctions,no as removeCustomClaims,Rt as resetIdempotencyStore,Bi as revokeGitHubAccess,Oi as revokeGitHubAccessWithSchema,ti as revokeGitHubTeamAccessHelper,mo as setCustomClaims,Wn as setCustomClaimsHelper,pt as updateEntity,Ce as updateUserSubscription,xr as validateEnvironment};
21
+ import{O as L,P as te,a as N,c as Ye}from"../chunks/chunk-Q2WLRFOE.js";import{c as x,g as ke}from"../chunks/chunk-EZKRLLSQ.js";import{a as rt,b as le,c as ot}from"../chunks/chunk-F3PHE627.js";import{a as be,b as ve,c as Xe}from"../chunks/chunk-G5DRV3DH.js";import{a as K,b as P,c as Y,d as nt}from"../chunks/chunk-QXIOO2RL.js";import{a as k,h as Je,r as Ze,s as Ce,t as vt,x as et,y as tt}from"../chunks/chunk-F3WBFWPO.js";import{L as ne,c as h,d as v}from"../chunks/chunk-6NXIK35R.js";import{A as $,B as Le,C as O,D as ge,I as Ke,N as F,O as Me,P as je,Q as Ve,S as ee,V as Q,Z as he,_ as We,ba as ye,ca as we,da as ze,ea as Qe,g as Pe,h as H,i as Be,l as Ge,m as He,n as Z,s as $e,t as A,u as T,v as Ne,w as oe,x as b,y as ue}from"../chunks/chunk-W74UL7AY.js";import"../chunks/chunk-GDIUOJMD.js";import"../chunks/chunk-UH445BGK.js";import"../chunks/chunk-W6W4L44F.js";import{a as u}from"../chunks/chunk-AYY7UXNI.js";import{logger as X}from"firebase-functions/v2";import{onCall as Rt}from"firebase-functions/v2/https";var st=process.env.FIREBASE_REGION||"europe-west1",Ct=process.env.ENFORCE_APP_CHECK==="true",de={region:st,...Ct&&{enforceAppCheck:!0}},Dr={...de,invoker:"public",memory:"1GiB",timeoutSeconds:60,cors:!0},B={...de,memory:"512MiB",timeoutSeconds:30,cors:!0},M={...de,memory:"256MiB",timeoutSeconds:20},j={...de,invoker:"public",memory:"256MiB",timeoutSeconds:15,cors:!0},Re={...de,invoker:"public",memory:"256MiB",timeoutSeconds:15,cors:!0},Or={"europe-west1":"Belgium","europe-west2":"London","europe-west3":"Frankfurt","europe-west6":"Zurich","europe-central2":"Warsaw","us-central1":"Iowa","us-east1":"South Carolina","us-east4":"Northern Virginia","us-west1":"Oregon","asia-east1":"Taiwan","asia-northeast1":"Tokyo","asia-southeast1":"Singapore"},xr=u(()=>{let r=["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"].filter(e=>!process.env[e]);if(r.length>0)throw new Error(`Missing required environment variables: ${r.join(", ")}`);console.log(`\u{1F30D} Firebase Functions configured for region: ${st}`)},"validateEnvironment");var Ee=null,it=null,Fe=null;async function St(){if(!Ee){let t=await import("../chunks/rateLimiter-GG5LPWXJ.js");Ee=t.checkRateLimitWithFirestore,it=t.DEFAULT_RATE_LIMITS}return{checkRateLimitWithFirestore:Ee,DEFAULT_RATE_LIMITS:it}}u(St,"loadRateLimiter");async function at(){return Fe||(Fe=(await import("../chunks/monitoring-LXNVBD3G.js")).recordPaymentMetrics),Fe}u(at,"loadMonitoring");function At(t){let r=t.rawRequest.headers["x-forwarded-for"];if(r){let n=(Array.isArray(r)?r.join(","):r).split(",").map(s=>s.trim()).filter(Boolean);if(n.length>0)return n[n.length-1]}return t.rawRequest.ip||t.rawRequest.socket?.remoteAddress||"unknown"}u(At,"getClientIp");function C(t,r,e,o,n="user",s){if(!r){let i=new Error(`Schema is undefined for ${e}. Ensure the schema is properly imported and exported.`);throw X.error("[createBaseFunction] Schema validation failed at creation time",{operation:e,schemaType:typeof r,schemaValue:r,schemaConstructor:r?.constructor?.name}),i}if(typeof r!="object"||r===null){let i=new Error(`Invalid schema type for ${e}. Expected Valibot schema object, got ${typeof r}.`);throw X.error("[createBaseFunction] Invalid schema type",{operation:e,schemaType:typeof r,schemaValue:r}),i}return Rt(t,async i=>{try{if(X.info(`[${e}] Request received`,{hasAuth:!!i.auth,userId:i.auth?.uid||"anonymous",hasData:i.data!==void 0&&i.data!==null,dataKeys:i.data?Object.keys(i.data):[],dataPreview:(()=>{if(!i.data)return"null";try{let p=JSON.stringify(i.data);return p.length>200?p.substring(0,200)+"...":p}catch{return"[unserializable]"}})()}),i.app||X.warn(`[AppCheck] Missing token for ${e}`,{hasAuth:!!i.auth,userId:i.auth?.uid||"anonymous"}),!r)throw X.error(`[${e}] Schema became undefined at runtime (this should not happen)`,{operation:e,schemaType:typeof r,requestData:i.data}),new Error(`Schema is undefined for ${e} - this indicates a bundling/import issue`);let c=i.data??{},a;try{a=Le(r,c)}catch(p){throw X.error(`Schema validation failed for ${e}`,{error:p instanceof Error?p.message:String(p),data:i.data}),p}let l=rt(i.auth),d;if(n==="guest")d=i.auth?.uid||"guest";else if(d=x(i.auth?.uid),!Q(l,n))throw X.warn(`Insufficient role for ${e}`,{userId:d,userRole:l,requiredRole:n}),new Error(`Access denied. Required role: ${n}, your role: ${l}`);if(process.env.DISABLE_RATE_LIMITING!=="true"){let{checkRateLimitWithFirestore:p,DEFAULT_RATE_LIMITS:m}=await St(),g=n==="guest"&&d==="guest"?`ip_${At(i)}`:`uid_${d}`,R=`${e}_${g}`,I=Object.hasOwn(m,e)?m[e]:m.api,f=await p(R,I);if(!f.allowed)throw X.warn(`Rate limit exceeded for ${e}`,{identifier:g,remaining:f.remaining,resetAt:f.resetAt}),s?.audit({type:"rate_limit.exceeded",userId:d,metadata:{operation:e,remaining:0}}),new Error(`Rate limit exceeded. Try again in ${f.blockRemainingSeconds} seconds.`)}let w=await o(a,{uid:d,userRole:l,request:i});return process.env.ENABLE_METRICS==="true"&&await(await at())({operation:e,userId:d,status:"success",timestamp:new Date().toISOString(),metadata:{requestId:i.rawRequest.headers["x-request-id"]||"unknown"}}),w}catch(c){process.env.ENABLE_METRICS==="true"&&await(await at())({operation:e,userId:i.auth?.uid||"anonymous",status:"failed",timestamp:new Date().toISOString(),metadata:{error:c instanceof Error?c.message:"Unknown error",requestId:i.rawRequest.headers["x-request-id"]||"unknown"}});try{k(c)}catch(a){if(a instanceof F){let{HttpsError:l}=await import("firebase-functions/v2/https");throw new l(a.code,a.message,a.details)}throw a}}})}u(C,"createBaseFunction");var kt=A({});async function Et(t,r){return{customClaims:(await h().getUser(r.uid)).customClaims||{}}}u(Et,"getCustomClaimsLogic");var Qr=u(t=>C(M,t||kt,"get_custom_claims",Et),"getCustomClaims");var Ft=A({});async function It(t,r){let e=await h().getUser(r.uid);return{uid:e.uid,email:e.email,emailVerified:e.emailVerified,customClaims:e.customClaims||{},disabled:e.disabled}}u(It,"getUserAuthStatusLogic");var to=u(t=>C(M,t||Ft,"get_user_auth_status",It),"getUserAuthStatus");var _t=A({claimsToRemove:O(Z(b()),H(1,"At least one claim must be specified"))});async function Tt(t,r){let{claimsToRemove:e}=t,s={...(await h().getUser(r.uid)).customClaims||{}};return e.forEach(i=>{delete s[i]}),await h().setCustomUserClaims(r.uid,s),{success:!0,customClaims:s}}u(Tt,"removeCustomClaimsLogic");var ao=u(t=>C(M,t||_t,"remove_custom_claims",Tt),"removeCustomClaims");var qt=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated"]),Ut=A({customClaims:oe(b(),He()),idempotencyKey:T(b())});function Dt(t){return u(async function(e,o){let{customClaims:n,idempotencyKey:s}=e;if(!n||typeof n!="object")throw new Error("customClaims must be an object");let i=Object.keys(n).filter(w=>!t.has(w));if(i.length>0)throw new Error(`Claim keys not allowed: ${i.join(", ")}`);if(s!==void 0){if(typeof s!="string"||s.length===0||s.length>256)throw new Error("idempotencyKey must be a non-empty string of at most 256 characters");if(!/^[\w\-.:@]+$/.test(s))throw new Error("idempotencyKey contains invalid characters (allowed: alphanumeric, -, _, ., :, @)")}if(s){let w=v(),p=w.collection("idempotency").doc(`claims_${s}`),m,g=!1;if(await w.runTransaction(async R=>{let I=await R.get(p);if(I.exists){m=I.data()?.result,g=!0;return}R.set(p,{processing:!0,reservedAt:new Date().toISOString()})}),g)return m}let l={...(await h().getUser(o.uid)).customClaims||{},...n};await h().setCustomUserClaims(o.uid,l);let d={success:!0,customClaims:l};return s&&await v().collection("idempotency").doc(`claims_${s}`).set({result:d,processedAt:new Date().toISOString(),processedBy:o.uid}),d},"setCustomClaimsLogic")}u(Dt,"createSetCustomClaimsLogic");var fo=u(t=>{let r=new Set(t.allowedClaimKeys);for(let o of r)if(qt.has(o))throw new Error(`Claim key "${o}" is blocked \u2014 it is a privilege-escalation vector and cannot be self-assigned.`);let e=t.customSchema||Ut;return C(M,e,"set_custom_claims",Dt(r))},"setCustomClaims");import{defineSecret as Ie}from"firebase-functions/params";var V=Ie("STRIPE_SECRET_KEY"),ct=Ie("STRIPE_WEBHOOK_SECRET"),me=Ie("GITHUB_PERSONAL_ACCESS_TOKEN");async function Ot(t,r,e){K(V.value()),Y();let o={async createStripeSession(s){let i=r.uid,c={...s,metadata:{...s.metadata,firebaseUid:i},...s.subscription_data&&{subscription_data:{...s.subscription_data,metadata:{...s.subscription_data.metadata,firebaseUid:i}}}};Je(c);let a=await P.checkout.sessions.create(c);return{id:a.id,url:a.url}},async retrieveTaxRate(s){let i=await P.taxRates.retrieve(s);return{id:i.id,inclusive:i.inclusive}}},n={async getUser(s){return{customClaims:(await h().getUser(s)).customClaims}}};return Ze(t,r.uid,o,n,e)}u(Ot,"createCheckoutSessionLogic");function xt(t){return C(B,Ke,"create_checkout_session",(r,e)=>Ot(r,e,t))}u(xt,"createCheckoutSession");import{logger as pe}from"firebase-functions/v2";import{onRequest as Pt}from"firebase-functions/v2/https";async function Bt(t){if(t.rawBody&&Buffer.isBuffer(t.rawBody))return t.rawBody;let r=[];for await(let e of t)r.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(r)}u(Bt,"getRawBody");function Gt(t){return Pt(B,async(r,e)=>{K(V.value());try{let o=r.headers["stripe-signature"];if(!o||Array.isArray(o)){let a=new Error("No Stripe signature found");throw pe.error("[Webhook] Missing signature",{error:a,operation:"webhook_signature_validation"}),k(a)}let n=ct.value();if(!n){let a=new Error("STRIPE_WEBHOOK_SECRET not configured");throw pe.error("[Webhook] Missing webhook secret",{error:a,operation:"webhook_configuration"}),k(a)}let s=await Bt(r);if(!s||s.length===0){let a=new Error("Missing or empty request body");throw pe.error("[Webhook] Invalid body",{error:a,operation:"webhook_raw_body"}),k(a)}let c=await tt(s,o,n,P,t,Ce,{async getUser(a){return h().getUser(a)},async setCustomUserClaims(a,l){await h().setCustomUserClaims(a,l)}},ke());pe.info("[Firebase Webhook] Success",c),e.status(200).json({received:!0})}catch(o){throw pe.error("[Firebase Webhook] Error",{error:o instanceof Error?o.message:String(o)}),k(o)}})}u(Gt,"createStripeWebhook");function Se(){if(process.env.FUNCTION_NAME||process.env.FIREBASE_CONFIG)return!0;let t=!!process.env.FIREBASE_PROJECT_ID,r=!!process.env.FIREBASE_CLIENT_EMAIL,e=!!process.env.FIREBASE_PRIVATE_KEY;return t&&r&&e}u(Se,"isFirestoreConfigured");async function Ht(){if(!Se())return!1;try{let{getFirebaseAdminFirestore:t}=await import("../chunks/server-NODQAE3F.js");return await t().collection("_health_check").limit(1).get(),!0}catch(t){return console.warn("[Firestore] Not available:",t instanceof Error?t.message:String(t)),!1}}u(Ht,"isFirestoreAvailable");import{onRequest as $t}from"firebase-functions/v2/https";var Nt=$t(B,async(t,r)=>{let e="healthy";try{await P.products.list({limit:1})}catch{e="unhealthy"}Se()||(e=e==="healthy"?"degraded":e),["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_API_VERSION"].some(s=>!process.env[s])&&(e="unhealthy");let n=e==="unhealthy"?503:200;r.status(n).json({status:e,timestamp:Date.now()})});var Lt=A({userId:O(b(),H(1,"User ID is required"))});async function Kt(t,r){Y();let e=r.uid,n=(await h().getUser(e)).customClaims||{},s=n.subscription?.subscriptionId;if(!s)throw new Error("No active subscription found");let i=await P.subscriptions.retrieve(s),c={...n,subscription:{...n.subscription,status:i.status,currentPeriodStart:new Date(i.current_period_start*1e3).toISOString(),currentPeriodEnd:new Date(i.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:i.cancel_at_period_end}};return await h().setCustomUserClaims(e,c),{success:!0,userId:e,status:i.status,currentPeriodEnd:new Date(i.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:i.cancel_at_period_end}}u(Kt,"refreshSubscriptionStatusLogic");var Zo=u(t=>C(B,t||Lt,"refresh_subscription_status",Kt),"refreshSubscriptionStatus");var Mt=A({userId:b()});async function jt(t,r){K(V.value());let e=r.uid;return await nt(e,{async getUser(n){return h().getUser(n)},async setCustomUserClaims(n,s){await h().setCustomUserClaims(n,s)}})}u(jt,"cancelSubscriptionLogic");function Vt(){return C(B,Mt,"cancel_subscription",jt)}u(Vt,"cancelSubscription");var Wt=A({userId:b(),newPriceId:b(),billingConfigKey:b()});async function zt(t,r,e){K(V.value()),Y();let o=r.uid,{newPriceId:n,billingConfigKey:s}=t,i=e[s];if(!i||i.type!=="StripeSubscription")throw k(new Error("Invalid plan"));if(i.priceId!==n)throw k(new Error("Price ID mismatch with configuration"));let l=((await h().getUser(o)).customClaims||{}).subscription?.subscriptionId;if(!l)throw k(new Error("No active subscription found"));let d=await P.subscriptions.retrieve(l),w=await P.subscriptions.update(l,{items:[{id:d.items.data[0]?.id,price:n}],proration_behavior:"create_prorations"}),m=et(["active","canceled","past_due","trialing","incomplete"],w.status)?w.status:"incomplete";return await Ce(o,{tier:i.tier,status:m,subscriptionEnd:new Date(w.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:w.cancel_at_period_end,subscriptionId:w.id,customerId:w.customer},{async getUser(g){return h().getUser(g)},async setCustomUserClaims(g,R){await h().setCustomUserClaims(g,R)}}),{success:!0,newTier:i.tier,newPrice:i.price}}u(zt,"changePlanLogic");function Qt(t){return C(B,Wt,"change_plan",(r,e)=>zt(r,e,t))}u(Qt,"changePlan");var Yt=A({userId:b(),returnUrl:T(O(b(),Ge()))});async function Xt(t,r){K(V.value());try{Y()}catch(d){throw k(d)}let e=r.uid,{returnUrl:o}=t,n=await h().getUser(e),c=(n.customClaims||{}).subscription?.customerId||n.customClaims?.stripeCustomerId;if(!c)throw k(new Error("No Stripe customer ID found for user"));let a=o??(process.env.FRONTEND_URL?`${process.env.FRONTEND_URL}/dashboard`:void 0);if(!a)throw k(new Error("returnUrl is required (or set FRONTEND_URL env var)"));return{url:(await P.billingPortal.sessions.create({customer:c,return_url:a})).url}}u(Xt,"createCustomerPortalLogic");function Jt(){return C(B,Yt,"create_customer_portal",Xt)}u(Jt,"createCustomerPortal");function Zt(t,r){if(typeof t!="object"||t===null||!("entries"in t))return;let{entries:e}=t;if(typeof e!="object"||e===null)return;let o=e[r];if(!(!o||typeof o!="object"&&typeof o!="function"))return"visibility"in o?o.visibility:void 0}u(Zt,"getFieldVisibilityFromSchema");var er=["guest","user","admin","technical","hidden","owner"];function tr(t){return typeof t=="string"&&er.includes(t)}u(tr,"isFieldVisibility");function rr(t,r,e){if(t==="*")return!0;let o=Zt(r,t);return o!==void 0&&!tr(o)?!1:Ye(t,o,e)}u(rr,"canAggregateField");function lt(t){if(t!=null&&typeof t=="object"&&"amount"in t){let e=t,o=Number(e.amount);if(!Number.isFinite(o))return NaN;let n=Number(e.discountPercent),s=Number.isFinite(n)?Math.min(100,Math.max(0,n)):0;return s>0?o*(1-s/100):o}let r=Number(t);return Number.isFinite(r)?r:NaN}u(lt,"getPriceOrNumberValue");function Ae(t,r){return lt(t[r])}u(Ae,"getNumericValue");function ut(t,r){let e=t;switch(r.filter&&(e=t.filter(o=>{let n=o[r.filter.field],s=n!=null&&typeof n=="object"&&"amount"in n?lt(n):typeof n=="number"||n==null?n:Number(n);switch(r.filter.operator){case"==":return n===r.filter.value;case"!=":return n!==r.filter.value;case">":return s>r.filter.value;case"<":return s<r.filter.value;case">=":return s>=r.filter.value;case"<=":return s<=r.filter.value;default:return!0}})),r.operation){case"count":return e.length;case"sum":return e.reduce((o,n)=>{let s=Ae(n,r.field);return o+(Number.isFinite(s)?s:0)},0);case"avg":return e.length===0?null:e.reduce((n,s)=>{let i=Ae(s,r.field);return n+(Number.isFinite(i)?i:0)},0)/e.length;case"min":return e.length===0?null:e.reduce((o,n)=>{let s=Ae(n,r.field);return Number.isFinite(s)?o===null?s:Math.min(o,s):o},null);case"max":return e.length===0?null:e.reduce((o,n)=>{let s=Ae(n,r.field);return Number.isFinite(s)?o===null?s:Math.max(o,s):o},null);default:return null}}u(ut,"computeMetric");function or(t,r,e){return u(async function(n,s){let i=v(),{userRole:c}=s,a=Q(c,"admin"),l=new Set;e.metrics?.forEach(f=>l.add(f.field)),e.groupBy?.forEach(f=>{l.add(f.field),f.metrics.forEach(E=>l.add(E.field))});for(let f of l)if(!rr(f,r,a))throw new F(`Access denied: cannot aggregate field '${f}'`,"permission-denied");let d=i.collection(t),w=[...e.where||[],...n.where||[]];for(let[f,E,_]of w)d=d.where(f,E,_);if(n.dateRange){let{field:f,start:E,end:_}=n.dateRange;E&&(d=d.where(f,">=",new Date(E))),_&&(d=d.where(f,"<=",new Date(_)))}let g=(await d.limit(1e4).get()).docs.map(f=>({id:f.id,...f.data()})),R={};if(e.metrics)for(let f of e.metrics)R[f.as]=ut(g,f);let I={};if(e.groupBy)for(let f of e.groupBy){let E=new Map;for(let S of g){let q=String(S[f.field]??"null");E.has(q)||E.set(q,[]),E.get(q).push(S)}let _={};for(let[S,q]of E){_[S]={};for(let G of f.metrics)_[S][G.as]=ut(q,G)}I[f.field]=_}return{metrics:R,groups:I,meta:{collection:t,totalDocs:g.length,computedAt:new Date().toISOString()}}},"aggregateEntitiesLogic")}u(or,"aggregateEntitiesLogicFactory");var Wn=u((t,r,e)=>{let o=A({where:T(Z(ue([b(),$(),$()]))),dateRange:T(A({field:b(),start:T(b()),end:T(b())}))});return C(j,o,"aggregate_entities",or(t,r,e))},"aggregateEntities");import{logger as nr}from"firebase-functions/v2";function sr(t,r,e,o,n){return u(async function(i,c){let{uid:a,userRole:l}=c,d=null,w=u(()=>(d||(d=v().collection(t)),d),"col");return Xe({collection:t,ops:i,createSchema:r,draftCreateSchema:e,updateSchema:o,access:n,uid:a,userRole:l,mintInsertId:u(()=>w().doc().id,"mintInsertId"),stampInsertMetadata:u((p,m)=>{let g=p.status??ye;return{...te(p),status:g,...be(m)}},"stampInsertMetadata"),stampUpdateMetadata:u((p,m)=>({...te(p),...ve(m)}),"stampUpdateMetadata"),transact:u(async({inserts:p,updates:m,deletes:g})=>{let R=w();return v().runTransaction(async I=>{let f=[],E=[],_=[];for(let{id:S,row:q}of p)I.set(R.doc(S),q),f.push(S);for(let{id:S,patch:q}of m)I.update(R.doc(S),q),E.push(S);for(let S of g)I.delete(R.doc(S)),_.push(S);return{insertedIds:f,updatedIds:E,deletedIds:_}})},"transact"),audit:u((p,{counts:m})=>{nr.info(p,{uid:a,collection:t,inserts:m.inserts,updates:m.updates,deletes:m.deletes})},"audit")})},"bulkEntityLogic")}u(sr,"bulkEntityLogicFactory");var dt=u((t,r,e,o,n)=>{let s=ir(n);return C(j,Qe,`bulk_${t}`,sr(t,r,e,o,n),s)},"bulkEntity");function ir(t){let r=["guest","user","admin","super"],e=u(n=>r.indexOf(n),"rank");return[t.create,t.update,t.delete].reduce((n,s)=>e(n)<=e(s)?n:s)}u(ir,"weakestRole");import{logger as ar}from"firebase-functions/v2";function cr(t){return typeof t=="string"?t.toLowerCase():t}u(cr,"normalizeValue");function ur(t,r){let e={...t};for(let o of r)for(let n of o.fields)typeof e[n]=="string"&&(e[n]=e[n].toLowerCase());return e}u(ur,"normalizePayloadForUniqueKeys");async function lr(t,r,e,o){let n=v();for(let s of e){if(o&&s.skipForDrafts===!0||!s.fields.every(l=>r[l]!=null&&r[l]!==""))continue;let c=n.collection(t);for(let l of s.fields)c=c.where(l,"==",cr(r[l]));let a=await c.limit(1).get();if(!a.empty){let l=a.docs[0],d=L({id:l.id,...l.data()});if(s.findOrCreate)return{found:!0,existingDoc:d,findOrCreate:!0};let w=s.fields.join(" + ");throw new F(s.errorMessage||`Duplicate ${w}`,"already-exists",{details:{fields:s.fields,existingId:l.id}})}}return{found:!1}}u(lr,"checkUniqueKeys");function dr(t,r,e){return u(async function(n,s){let{payload:i,idempotencyKey:c}=n,{uid:a}=s;if(c!==void 0){if(typeof c!="string"||c.length===0||c.length>256)throw new F("idempotencyKey must be a non-empty string of at most 256 characters","invalid-argument");if(!/^[\w\-.:@]+$/.test(c))throw new F("idempotencyKey contains invalid characters","invalid-argument")}if(c){let S=v(),q=S.collection("idempotency").doc(`create_${c}`),G,W=!1;if(await S.runTransaction(async J=>{let y=await J.get(q);if(y.exists){G=y.data()?.result,W=!0;return}J.set(q,{processing:!0,reservedAt:new Date().toISOString()})}),W)return G}let l=i.status??"draft",d=l==="draft",p=r.metadata?.uniqueKeys;if(p&&p.length>0){let S=await lr(t,i,p,d);if(S.found&&S.findOrCreate)return ar.info("[create_entity] findOrCreate: returning existing document",{collection:t,existingId:S.existingDoc.id}),S.existingDoc}let m=p&&p.length>0?ur(i,p):i,g={...m,status:l};d?le(g,e):le(g,r);let R={...te(m),status:l,...be(a)},I=v(),E=await(await I.collection(t).add(R)).get(),_=L({id:E.id,...E.data()});return c&&await I.collection("idempotency").doc(`create_${c}`).set({result:_,processedAt:new Date().toISOString(),processedBy:a}),_},"createEntityLogic")}u(dr,"createEntityLogicFactory");var mt=u((t,r,e,o,n)=>{let s=n||A({payload:oe(b(),$()),idempotencyKey:T(b())});return C(j,s,"create_entity",dr(t,r,e),o)},"createEntity");import"firebase-functions/v2";function mr(t){return u(async function(e,o){let{id:n}=e,s=await ot(t,n);if(s.length>0)throw new F("Cannot delete: item is referenced by other entities","permission-denied",{details:{references:s}});return await v().collection(t).doc(n).delete(),{success:!0}},"deleteEntityLogic")}u(mr,"deleteEntityLogicFactory");var pt=u((t,r,e)=>{let o=e||A({id:O(b(),H(1))});return C(j,o,"delete_entity",mr(t),r)},"deleteEntity");function pr(t,r,e){return u(async function(n,s){let{id:i}=n,{userRole:c,uid:a}=s,w=await v().collection(t).doc(i).get();if(!w.exists)throw new F("Entity not found","not-found");let p=Q(c,"admin"),m=w.data();if(!p&&we.includes(m?.status))throw new F("Entity not found","not-found");let g=m||{},I=he(g,r,c,e&&a?{documentData:g,uid:a,ownership:e}:void 0);return L({id:w.id,...I})},"getEntityLogic")}u(pr,"getEntityLogicFactory");var ft=u((t,r,e,o,n)=>{let s=o||A({id:O(b(),H(1))});return C(Re,s,"get_entity",pr(t,r,n),e)},"getEntity");import{logger as fr}from"firebase-functions/v2";function gr(t,r){let e=t;for(let o of r)e=e.where(o.field,o.op,o.value);return e}u(gr,"applyPublicCondition");function hr(t,r,e,o,n){return u(async function(i,c){let{where:a=[],orderBy:l=[],limit:d,startAfterId:w,search:p}=i,{userRole:m,uid:g}=c,R=Q(m,"admin"),I=v(),f=I.collection(t);if(R||(f=f.where("status","not-in",[...we])),o&&!R){if(n&&o.publicCondition&&o.publicCondition.length>0)f=gr(f,o.publicCondition);else if(!n&&o.ownerFields.length>0){if(o.ownerFields.length>1)throw new F(`Multiple ownerFields (${o.ownerFields.join(", ")}) are not supported for Firestore list queries. Use a single ownerIds array field with array-contains instead.`,"invalid-argument");let y=o.ownerFields[0];f=f.where(y,"==",g)}}if(p){let{field:y,query:U}=p;if(e&&e.length>0){if(!e.includes(y))throw new F(`Search field '${y}' is not allowed`,"invalid-argument")}else if(y.startsWith("_")||y.includes("."))throw new F(`Search field '${y}' is not allowed`,"invalid-argument");f=f.where(y,">=",U).where(y,"<=",U+"\uF8FF")}for(let[y,U,z]of a){if(e&&e.length>0){if(!e.includes(y)&&y!=="status"&&y!=="id")throw new F(`Where field '${y}' is not allowed`,"invalid-argument")}else if(y.startsWith("_")||y.includes("."))throw new F(`Where field '${y}' is not allowed`,"invalid-argument");f=f.where(y,U,z)}for(let[y,U]of l)f=f.orderBy(y,U);if(w){let y=await I.collection(t).doc(w).get();if(!y.exists)throw new F("Start after document not found","not-found");f=f.startAfter(y)}let E=1e3,_=d!==void 0&&d>0?Math.min(d,E):E;d!==void 0&&d>E&&fr.warn(`[list_entities] Requested limit ${d} exceeds MAX_LIST_LIMIT (${E}), capping`,{requestedLimit:d,effectiveLimit:_,collection:t}),f=f.limit(_);let S=await f.get(),q=u(y=>typeof y=="object"&&y!==null&&"thumbUrl"in y&&"fullUrl"in y,"isPictureObject"),G=u(y=>{if(Array.isArray(y)&&y.length>0){let U=y[0];if(q(U))return U.thumbUrl||U.fullUrl||null;if(typeof U=="string")return U}else if(q(y))return y.thumbUrl||y.fullUrl||null;return y},"optimizePictureField"),W=o&&g?{uid:g,ownership:o}:void 0,J=S.docs.map(y=>{let U=y.data()||{},z=he(U,r,m,W?{...W,documentData:U}:void 0);if(e&&e.length>0){let fe={id:y.id};for(let ce of e)if(ce in z){let bt=z[ce];fe[ce]=G(bt)}return fe}let xe={id:y.id};for(let[fe,ce]of Object.entries(z))xe[fe]=G(ce);return xe});return{items:L(J),lastVisible:S.docs[S.docs.length-1]?.id||null,count:S.docs.length,hasMore:S.docs.length===_}},"listEntitiesLogic")}u(hr,"listEntitiesLogicFactory");var _e=u((t,r,e,o,n,s,i)=>{let c=o||A({where:T(Z(ue([b(),$(),$()]))),orderBy:T(Z(ue([b(),Ne(["asc","desc"])]))),limit:T(O($e(),Be(1),Pe(1e3))),startAfterId:T(b()),search:T(A({field:b(),query:b()}))});return C(Re,c,"list_entities",hr(t,r,n,s,i),e)},"listEntities");function yr(t){return typeof t=="string"?t.toLowerCase():t}u(yr,"normalizeValue");function wr(t,r){let e={...t};for(let o of r)for(let n of o.fields)typeof e[n]=="string"&&(e[n]=e[n].toLowerCase());return e}u(wr,"normalizePayloadForUniqueKeys");async function br(t,r,e,o,n,s){let i=v();for(let c of n){if(s&&c.skipForDrafts===!0||!c.fields.some(m=>m in o)||!c.fields.every(m=>e[m]!=null&&e[m]!==""))continue;let d=i.collection(t);for(let m of c.fields)d=d.where(m,"==",yr(e[m]));let p=(await d.limit(2).get()).docs.find(m=>m.id!==r);if(p){let m=c.fields.join(" + ");throw new F(c.errorMessage||`Duplicate ${m}`,"already-exists",{details:{fields:c.fields,existingId:p.id}})}}}u(br,"checkUniqueKeysForUpdate");function vr(t,r){return u(async function(o,n){let{id:s,payload:i,idempotencyKey:c}=o,{uid:a}=n;if(c!==void 0){if(typeof c!="string"||c.length===0||c.length>256)throw new F("idempotencyKey must be a non-empty string of at most 256 characters","invalid-argument");if(!/^[\w\-.:@]+$/.test(c))throw new F("idempotencyKey contains invalid characters","invalid-argument")}if(c){let G=v(),W=G.collection("idempotency").doc(`update_${c}`),J,y=!1;if(await G.runTransaction(async U=>{let z=await U.get(W);if(z.exists){J=z.data()?.result,y=!0;return}U.set(W,{processing:!0,reservedAt:new Date().toISOString()})}),y)return J}let l=v(),d=l.collection(t).doc(s),w=await d.get();if(!w.exists)throw new F("Entity not found","not-found");let m={...L(w.data()),...i},R=(m.status??ye)==="draft",f=r.metadata?.uniqueKeys;f&&f.length>0&&await br(t,s,m,i,f,R),R||le(m,r);let E=f&&f.length>0?wr(i,f):i,_={...te(E),...ve(a)};await d.update(_);let S=await d.get(),q=L({id:S.id,...S.data()});return c&&await l.collection("idempotency").doc(`update_${c}`).set({result:q,processedAt:new Date().toISOString(),processedBy:a}),q},"updateEntityLogic")}u(vr,"updateEntityLogicFactory");var gt=u((t,r,e,o)=>{let n=o||A({id:O(b(),H(1)),payload:oe(b(),$()),idempotencyKey:T(b())});return C(j,n,"update_entity",vr(t,r),e)},"updateEntity");import{logger as Te}from"firebase-functions/v2";async function Xs(t,r,e,o="pull",n){let s=process.env.GITHUB_PERSONAL_ACCESS_TOKEN;if(!s)throw k(new Error("GitHub Personal Access Token not configured"));let i=new N({accessToken:s});if(await i.isCollaborator(e.owner,e.repo,r)||await i.addCollaborator({owner:e.owner,repo:e.repo,username:r,permission:o}),n){let l=(await h().getUser(t)).customClaims||{};await h().setCustomUserClaims(t,{...l,...n,githubAccess:!0,githubUsername:r,githubRepoAccess:{owner:e.owner,repo:e.repo,permission:o,grantedAt:new Date().toISOString()}})}process.env.SAVE_GITHUB_ACCESS_TO_FIRESTORE==="true"&&await v().collection("githubAccess").doc(t).set({githubUsername:r,repoConfig:e,permission:o,accessGranted:!0,grantedAt:Date.now()},{merge:!0}),Te.info("GitHub repository access granted",{userId:t,githubUsername:r,repoConfig:e,permission:o})}u(Xs,"grantGitHubAccessHelper");async function Js(t,r){let o=(await h().getUser(t)).customClaims||{};return r?Object.fromEntries(r.filter(s=>s in o).map(s=>[s,o[s]])):o}u(Js,"getCustomClaimsHelper");async function Zs(t,r,e=!0){let o={};if(e)try{o=(await h().getUser(t)).customClaims||{}}catch(s){Te.warn("Could not fetch current claims for user",{userId:t,error:s})}let n=e?{...o,...r}:r;await h().setCustomUserClaims(t,n),process.env.SAVE_CLAIMS_TO_FIRESTORE==="true"&&await v().collection("userClaims").doc(t).set({claims:n,updatedAt:new Date().toISOString()},{merge:!0}),Te.info("Custom claims updated",{userId:t,claimKeys:Object.keys(r)})}u(Zs,"setCustomClaimsHelper");import{logger as se}from"firebase-functions/v2";async function ii(t,r,e,o="member"){try{let n=process.env.GITHUB_PERSONAL_ACCESS_TOKEN;if(!n)throw new Error("GitHub Personal Access Token not configured");let s=new N({accessToken:n});if(!await s.isTeamMember(e.org,e.team,r)&&!await s.addTeamMember(e.org,e.team,r,o))throw new Error(`Failed to add ${r} to team ${e.org}/${e.team}`);let a=(await h().getUser(t)).customClaims||{},l={...a,githubTeamAccess:{...a.githubTeamAccess,[e.org]:{...a.githubTeamAccess?.[e.org],[e.team]:{username:r,role:o,grantedAt:new Date().toISOString()}}}};await h().setCustomUserClaims(t,l),se.info("GitHub team access granted",{userId:t,githubUsername:r,teamConfig:e,role:o})}catch(n){throw se.error("Failed to grant GitHub team access",{userId:t,githubUsername:r,teamConfig:e,error:n instanceof Error?n.message:String(n)}),k(n)}}u(ii,"grantGitHubTeamAccessHelper");async function ai(t,r,e){try{let o=process.env.GITHUB_PERSONAL_ACCESS_TOKEN;if(!o)throw new Error("GitHub Personal Access Token not configured");let n=new N({accessToken:o});await n.isTeamMember(e.org,e.team,r)&&(await n.removeTeamMember(e.org,e.team,r)||se.warn(`Failed to remove ${r} from team ${e.org}/${e.team}`));let c=(await h().getUser(t)).customClaims||{};if(c.githubTeamAccess?.[e.org]?.[e.team]){let a={...c};a.githubTeamAccess[e.org]&&(delete a.githubTeamAccess[e.org][e.team],Object.keys(a.githubTeamAccess[e.org]).length===0&&delete a.githubTeamAccess[e.org]),await h().setCustomUserClaims(t,a)}se.info("GitHub team access revoked",{userId:t,githubUsername:r,teamConfig:e})}catch(o){throw se.error("Failed to revoke GitHub team access",{userId:t,githubUsername:r,teamConfig:e,error:o instanceof Error?o.message:String(o)}),k(o)}}u(ai,"revokeGitHubTeamAccessHelper");async function ci(t,r,e){try{let o=process.env.GITHUB_PERSONAL_ACCESS_TOKEN;if(!o)throw new Error("GitHub Personal Access Token not configured");let s=await new N({accessToken:o}).isTeamMember(e.org,e.team,r),a=((await h().getUser(t)).customClaims||{}).githubTeamAccess?.[e.org]?.[e.team];return{hasTeamAccess:s,hasCustomClaimsAccess:!!a,accessDetails:a||null}}catch(o){throw se.error("Failed to check GitHub team access",{userId:t,githubUsername:r,teamConfig:e,error:o instanceof Error?o.message:String(o)}),k(o)}}u(ci,"checkGitHubTeamAccessHelper");import{onCall as Cr,HttpsError as qe}from"firebase-functions/v2/https";var gi=Cr(async t=>{let r=x(t.auth?.uid),{provider:e,purpose:o}=t.data;try{let s=await v().collection("oauth_connections").where("userId","==",r).where("provider","==",e).where("purpose","==",o).get();if(s.empty)throw new qe("not-found","Connection not found");let i=s.docs[0];if(!i)throw new qe("not-found","Connection not found");let c=i.data();if(c?.credentials?.accessToken)try{await Rr(e,c.credentials.accessToken)}catch(a){console.warn(`Failed to revoke token for ${e}:`,a)}return await i.ref.delete(),{success:!0}}catch(n){throw console.error(`Error disconnecting ${e}:`,n),new qe("internal",n instanceof Error?n.message:"Failed to disconnect")}});async function Rr(t,r){try{let e=ee[t],o="revokeUrl"in e?e.revokeUrl:null;if(!o)return;let n=await fetch(o.toString(),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:r}).toString()});n.ok||console.warn(`Failed to revoke token for ${t}:`,n.status)}catch(e){console.error(`Error revoking token for ${t}:`,e)}}u(Rr,"revokeToken");import{onCall as Sr,HttpsError as ie}from"firebase-functions/v2/https";var Ri=Sr(async t=>{let r=x(t.auth?.uid),{provider:e,purpose:o,code:n,redirectUri:s,codeVerifier:i,idempotencyKey:c}=t.data;if(c!==void 0){if(typeof c!="string"||c.length===0||c.length>256)throw new ie("invalid-argument","idempotencyKey must be a non-empty string of at most 256 characters");if(!/^[\w\-.:@]+$/.test(c))throw new ie("invalid-argument","idempotencyKey contains invalid characters")}if(!e||!o||!n||!s)throw new ie("invalid-argument","Missing required parameters");if(c){let a=v(),l=a.collection("idempotency").doc(`oauth_${c}`),d,w=!1;if(await a.runTransaction(async p=>{let m=await p.get(l);if(m.exists){d=m.data()?.result,w=!0;return}p.set(l,{processing:!0,reservedAt:new Date().toISOString()})}),w)return d}try{let a=ee[e];if(!a)throw new ie("invalid-argument",`Provider ${e} is not supported`);let l=e.toUpperCase(),d=process.env[`${l}_CLIENT_ID`],w=process.env[`${l}_CLIENT_SECRET`];if(!d||!w)throw new ie("failed-precondition",`Provider ${e} is not configured`);let p=await fetch(a.endpoints.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"authorization_code",client_id:d,client_secret:w,code:n,redirect_uri:s,...i?{code_verifier:i}:{}}).toString()});if(!p.ok){let f=await p.text();throw console.error(`Token exchange error for ${e}: ${p.status} ${p.statusText}`),new Error(`Failed to exchange code for token: ${p.status} ${p.statusText}`)}let m=await p.json(),g={accessToken:m.access_token,refreshToken:m.refresh_token||null,expiresAt:m.expires_in?Math.floor(Date.now()/1e3)+m.expires_in:null,idToken:m.id_token||null,scope:m.scope?m.scope.split(" "):[]},R=null;g.accessToken&&(R=await Ar(e,g.accessToken)),await kr({uid:r,provider:e,purpose:o,credentials:g,profile:R});let I={success:!0,credentials:g,profile:R};return c&&await v().collection("idempotency").doc(`oauth_${c}`).set({result:I,processedAt:new Date().toISOString(),processedBy:r}),I}catch(a){throw console.error(`OAuth token exchange error for ${e}:`,a instanceof Error?a.message:"Unknown error"),new ie("internal",a instanceof Error?a.message:"Failed to exchange code for token")}});async function Ar(t,r){try{let e=ee[t];if(!e?.endpoints?.profileUrl)return null;let o=await fetch(e.endpoints.profileUrl,{headers:{Authorization:`Bearer ${r}`,Accept:"application/json"}});return o.ok?await o.json():(console.warn(`Failed to fetch profile for ${t}:`,o.status),null)}catch(e){return console.error(`Error fetching profile for ${t}:`,e),null}}u(Ar,"fetchUserProfile");async function kr(t){try{let e=await v().collection("oauth_connections").where("userId","==",t.uid).where("provider","==",t.provider).where("purpose","==",t.purpose).get(),o={userId:t.uid,provider:t.provider,purpose:t.purpose,credentials:t.credentials,profile:t.profile,connected:!0,createdAt:ne.serverTimestamp(),updatedAt:ne.serverTimestamp(),lastUsed:ne.serverTimestamp()};if(e.empty)await v().collection("oauth_connections").add(o);else{let n=e.docs[0];n&&await n.ref.update({...o,createdAt:n.data()?.createdAt})}}catch(r){throw console.error("Error saving OAuth connection:",r),r}}u(kr,"saveOAuthConnection");import{onCall as Er,HttpsError as Fr}from"firebase-functions/v2/https";var Ii=Er(async t=>{let r=x(t.auth?.uid),{purpose:e}=t.data||{};try{let o=v().collection("oauth_connections").where("userId","==",r);return{connections:(await(e?o.where("purpose","==",e):o).get()).docs.map(c=>{let a=c.data(),l=a.credentials?.expiresAt?a.credentials.expiresAt<Math.floor(Date.now()/1e3):!1;return{id:c.id,userId:a.userId,provider:a.provider,purpose:a.purpose,connected:!l,createdAt:a.createdAt?.toDate?.()?a.createdAt.toDate().toISOString():a.createdAt,updatedAt:a.updatedAt?.toDate?.()?a.updatedAt.toDate().toISOString():a.updatedAt,lastUsed:a.lastUsed?.toDate?.()?a.lastUsed.toDate().toISOString():a.lastUsed,hasCredentials:!l&&!!a.credentials,profile:a.profile}})}}catch(o){throw console.error("Error getting OAuth connections:",o),new Fr("internal",o instanceof Error?o.message:"Failed to get connections")}});import{logger as Ue}from"firebase-functions/v2";import{onCall as De}from"firebase-functions/v2/https";var Oe={...M,secrets:[me]};async function ht(t,r){try{let e=x(t.auth?.uid),n=ge(r||Me,t.data);if(!n.success)throw new Error(`Validation failed: ${n.issues.map(g=>g.message).join(", ")}`);let s=n.output,{githubUsername:i,repoConfig:c,permission:a="push",customClaims:l}=s,d=e,w=me.value();if(!w)throw k(new Error("GitHub Personal Access Token not configured"));if(await new N({accessToken:w}).addCollaborator({owner:c.owner,repo:c.repo,username:i,permission:a}),l){let g=await h().getUser(d),R={...g.customClaims,...l,githubAccess:{...g.customClaims?.githubAccess,[c.owner]:{...g.customClaims?.githubAccess?.[c.owner],[c.repo]:{username:i,permission:a,grantedAt:new Date().toISOString()}}}};await h().setCustomUserClaims(d,R)}let m={success:!0,userId:d,githubUsername:i,repoConfig:c,permission:a,message:`Successfully granted ${i} ${a} access to ${c.owner}/${c.repo}`};return Ue.info("GitHub access granted",{userId:m.userId,githubUsername:m.githubUsername,repoConfig:m.repoConfig}),m}catch(e){throw k(e)}}u(ht,"grantGitHubAccessInternal");var Hi=De(Oe,async t=>await ht(t));async function $i(t,r){return await ht(t,r)}u($i,"grantGitHubAccessWithSchema");async function yt(t,r){try{let e=x(t.auth?.uid),n=ge(r||je,t.data);if(!n.success)throw new Error(`Validation failed: ${n.issues.map(g=>g.message).join(", ")}`);let{githubUsername:s,repoConfig:i}=n.output,c=e,a=me.value();if(!a)throw k(new Error("GitHub Personal Access Token not configured"));await new N({accessToken:a}).removeCollaborator(i.owner,i.repo,s)||Ue.warn(`Failed to remove ${s} from GitHub repository`);let p=(await h().getUser(c)).customClaims||{};if(p.githubAccess?.[i.owner]?.[i.repo]){let g={...p};g.githubAccess[i.owner]&&(delete g.githubAccess[i.owner][i.repo],Object.keys(g.githubAccess[i.owner]).length===0&&delete g.githubAccess[i.owner]),await h().setCustomUserClaims(c,g)}let m={success:!0,userId:c,githubUsername:s,repoConfig:i,message:`Successfully revoked ${s} access to ${i.owner}/${i.repo}`};return Ue.info("GitHub access revoked",{userId:m.userId,githubUsername:m.githubUsername,repoConfig:m.repoConfig}),m}catch(e){throw k(e)}}u(yt,"revokeGitHubAccessInternal");var Ni=De(Oe,async t=>await yt(t));async function Li(t,r){return await yt(t,r)}u(Li,"revokeGitHubAccessWithSchema");async function wt(t,r){try{let e=x(t.auth?.uid),n=ge(r||Ve,t.data);if(!n.success)throw new Error(`Validation failed: ${n.issues.map(R=>R.message).join(", ")}`);let{githubUsername:s,repoConfig:i}=n.output,c=e,a=me.value();if(!a)throw k(new Error("GitHub Personal Access Token not configured"));let d=await new N({accessToken:a}).isCollaborator(i.owner,i.repo,s),m=((await h().getUser(c)).customClaims||{}).githubAccess?.[i.owner]?.[i.repo];return{success:!0,userId:c,githubUsername:s,repoConfig:i,hasAccess:d,customClaimsAccess:!!m,accessDetails:m||null,message:d?`${s} has access to ${i.owner}/${i.repo}`:`${s} does not have access to ${i.owner}/${i.repo}`}}catch(e){throw k(e)}}u(wt,"checkGitHubAccessInternal");var Ki=De(Oe,async t=>await wt(t));async function Mi(t,r){return await wt(t,r)}u(Mi,"checkGitHubAccessWithSchema");import{onCall as Ir,HttpsError as ae}from"firebase-functions/v2/https";var Xi=Ir(async t=>{let r=x(t.auth?.uid),{provider:e,refreshToken:o,redirectUri:n}=t.data;try{let s=ee[e];if(!s?.endpoints?.tokenUrl)throw new ae("invalid-argument",`Provider ${e} does not support token refresh`);let i=e.toUpperCase(),c=process.env[`${i}_CLIENT_ID`],a=process.env[`${i}_CLIENT_SECRET`];if(!c||!a)throw new ae("failed-precondition",`Provider ${e} is not configured`);let l=await fetch(s.endpoints.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"refresh_token",client_id:c,client_secret:a,refresh_token:o,redirect_uri:n}).toString()});if(!l.ok){let m=await l.text();throw console.error(`Token refresh error for ${e}:`,m),new Error(`Failed to refresh token: ${l.status} ${l.statusText}`)}let d=await l.json(),p=await v().collection("oauth_connections").where("userId","==",r).where("provider","==",e).get();if(p.empty)throw new ae("not-found","OAuth connection not found");{let m=p.docs[0];if(!m)throw new ae("not-found","OAuth connection document not found");let g=m.data();if(!g)throw new ae("internal","OAuth connection data is invalid");let R={...g.credentials,accessToken:d.access_token,expiresAt:d.expires_in?Math.floor(Date.now()/1e3)+d.expires_in:g.credentials.expiresAt,refreshToken:d.refresh_token||g.credentials.refreshToken};return await m.ref.update({credentials:R,updatedAt:ne.serverTimestamp()}),{success:!0,credentials:{accessToken:d.access_token,refreshToken:d.refresh_token,expiresAt:d.expires_in?Math.floor(Date.now()/1e3)+d.expires_in:null,scope:d.scope?d.scope.split(" "):[]}}}}catch(s){throw console.error(`OAuth token refresh error for ${e}:`,s),new ae("internal",s instanceof Error?s.message:"Failed to refresh token")}});import{logger as re}from"firebase-functions/v2";import{onSchedule as _r}from"firebase-functions/v2/scheduler";var oa=_r({schedule:"0 0 * * *",timeZone:"UTC"},async()=>{try{re.info("Starting expired subscription check");let t=h(),r=v(),e=new Date,o=process.env.USERS_COLLECTION_PATH||"users",s=await r.collection(o).where("subscription.status","==","active").get(),i=0,c=0;for(let a of s.docs)try{let d=a.data().subscription;if(!d||!d.subscriptionEnd)continue;new Date(d.subscriptionEnd)<e&&(re.info("Found expired subscription",{userId:a.id,subscriptionEnd:d.subscriptionEnd,tier:d.tier}),await Tr(a.id,d),c++),i++}catch(l){re.error("Error processing user subscription",{userId:a.id,error:l instanceof Error?l.message:String(l)})}re.info("Expired subscription check completed",{processedCount:i,expiredCount:c})}catch(t){throw re.error("Failed to check expired subscriptions",{error:t instanceof Error?t.message:String(t)}),k(t)}});async function Tr(t,r){try{let e=h(),n=(await e.getUser(t)).customClaims||{},s=new Date().toISOString(),i={...n,subscription:{...r,status:"expired",expiredAt:s,updatedAt:s}};await e.setCustomUserClaims(t,i),re.info("Successfully revoked expired subscription",{userId:t,tier:r.tier})}catch(e){throw re.error("Failed to revoke expired subscription",{userId:t,error:e instanceof Error?e.message:String(e)}),e}}u(Tr,"revokeExpiredSubscription");function qr(t,r={}){let{prefix:e=""}=r,o={};for(let[n,s]of Object.entries(t)){if(!Ur(s))continue;let i=s,c=i.collection,a=ze(i),l=i.access;o[`${e}create_${c}`]=mt(c,a.create,a.draft,l.create),o[`${e}get_${c}`]=ft(c,a.get,l.read,void 0,i.ownership),o[`${e}list_${c}`]=_e(c,a.get,l.read,void 0,i.listFields,i.ownership,!1),o[`${e}listCard_${c}`]=_e(c,a.get,l.read,void 0,We(i),i.ownership,!0),o[`${e}update_${c}`]=gt(c,a.update,l.update),o[`${e}delete_${c}`]=pt(c,l.delete),o[`${e}bulk_${c}`]=dt(c,a.create,a.draft,a.update,{create:l.create,update:l.update,delete:l.delete})}return o}u(qr,"createCrudFunctions");function Ur(t){return typeof t=="object"&&t!==null&&"collection"in t&&"fields"in t}u(Ur,"isEntity");export{M as AUTH_CONFIG,Or as AVAILABLE_REGIONS,j as CRUD_CONFIG,Re as CRUD_READ_CONFIG,st as FIREBASE_REGION,Dr as FUNCTION_CONFIG,vt as ReservationLostError,B as STRIPE_CONFIG,Wn as aggregateEntities,Nt as billingHealth,dt as bulkEntity,sr as bulkEntityLogicFactory,Vt as cancelSubscription,Qt as changePlan,oa as checkExpiredSubscriptions,Ki as checkGitHubAccess,Mi as checkGitHubAccessWithSchema,ci as checkGitHubTeamAccessHelper,C as createBaseFunction,xt as createCheckoutSession,qr as createCrudFunctions,Jt as createCustomerPortal,mt as createEntity,ke as createFirestoreIdempotencyStore,Gt as createStripeWebhook,pt as deleteEntity,gi as disconnect,Ri as exchangeToken,Ii as getConnections,Qr as getCustomClaims,Js as getCustomClaimsHelper,ft as getEntity,to as getUserAuthStatus,Hi as grantGitHubAccess,Xs as grantGitHubAccessHelper,$i as grantGitHubAccessWithSchema,ii as grantGitHubTeamAccessHelper,Ht as isFirestoreAvailable,Se as isFirestoreConfigured,_e as listEntities,Zo as refreshSubscriptionStatus,Xi as refreshToken,ao as removeCustomClaims,Ni as revokeGitHubAccess,Li as revokeGitHubAccessWithSchema,ai as revokeGitHubTeamAccessHelper,fo as setCustomClaims,Zs as setCustomClaimsHelper,gt as updateEntity,Ce as updateUserSubscription,xr as validateEnvironment};
22
22
  //# sourceMappingURL=index.js.map