@donotdev/functions 0.1.44 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -14
- package/lib/chunks/chunk-3F4BWKQD.js +22 -0
- package/lib/chunks/chunk-3F4BWKQD.js.map +7 -0
- package/lib/chunks/chunk-5IPULSUX.js +22 -0
- package/lib/chunks/chunk-5IPULSUX.js.map +7 -0
- package/lib/chunks/chunk-6USHTJED.js +22 -0
- package/lib/chunks/chunk-6USHTJED.js.map +7 -0
- package/lib/chunks/chunk-AYY7UXNI.js +22 -0
- package/lib/chunks/chunk-AYY7UXNI.js.map +7 -0
- package/lib/chunks/chunk-CXBSROEW.js +23 -0
- package/lib/chunks/chunk-CXBSROEW.js.map +7 -0
- package/lib/chunks/chunk-GYTCWMXV.js +22 -0
- package/lib/chunks/chunk-GYTCWMXV.js.map +7 -0
- package/lib/chunks/chunk-HLNYUAZH.js +22 -0
- package/lib/chunks/chunk-HLNYUAZH.js.map +7 -0
- package/lib/chunks/chunk-LCDLG4VG.js +151 -0
- package/lib/chunks/chunk-LCDLG4VG.js.map +7 -0
- package/lib/chunks/chunk-MQANUSY3.js +22 -0
- package/lib/chunks/chunk-MQANUSY3.js.map +7 -0
- package/lib/chunks/chunk-OFQVO3FD.js +22 -0
- package/lib/chunks/chunk-OFQVO3FD.js.map +7 -0
- package/lib/chunks/chunk-PWAGW4R6.js +22 -0
- package/lib/chunks/chunk-PWAGW4R6.js.map +7 -0
- package/lib/chunks/chunk-US2VOP4S.js +22 -0
- package/lib/chunks/chunk-US2VOP4S.js.map +7 -0
- package/lib/chunks/chunk-YTKDNZNW.js +22 -0
- package/lib/chunks/chunk-YTKDNZNW.js.map +7 -0
- package/lib/chunks/monitoring-E7JBYBHQ.js +22 -0
- package/lib/chunks/monitoring-E7JBYBHQ.js.map +7 -0
- package/lib/chunks/rateLimiter-SQISLOP5.js +22 -0
- package/lib/chunks/rateLimiter-SQISLOP5.js.map +7 -0
- package/lib/chunks/server-IQ5JNJOM.js +22 -0
- package/lib/chunks/server-IQ5JNJOM.js.map +7 -0
- package/lib/firebase/auth/getCustomClaims.d.ts +1 -1
- package/lib/firebase/auth/getUserAuthStatus.d.ts +1 -1
- package/lib/firebase/auth/index.d.ts +0 -0
- package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/firebase/auth/setCustomClaims.d.ts +1 -1
- package/lib/firebase/baseFunction.d.ts +1 -1
- package/lib/firebase/billing/cancelSubscription.d.ts +0 -0
- package/lib/firebase/billing/changePlan.d.ts +0 -0
- package/lib/firebase/billing/createCheckoutSession.d.ts +2 -2
- package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
- package/lib/firebase/billing/healthCheck.d.ts +0 -0
- package/lib/firebase/billing/index.d.ts +2 -1
- package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -8
- package/lib/firebase/billing/webhookHandler.d.ts +17 -2
- package/lib/firebase/config/constants.d.ts +0 -0
- package/lib/firebase/config/index.d.ts +0 -0
- package/lib/firebase/config/secrets.d.ts +0 -0
- package/lib/firebase/crud/aggregate.d.ts +0 -9
- package/lib/firebase/crud/bulk.d.ts +2 -2
- package/lib/firebase/crud/create.d.ts +1 -1
- package/lib/firebase/crud/delete.d.ts +1 -1
- package/lib/firebase/crud/get.d.ts +1 -1
- package/lib/firebase/crud/index.d.ts +0 -0
- package/lib/firebase/crud/list.d.ts +1 -1
- package/lib/firebase/crud/update.d.ts +1 -9
- package/lib/firebase/helpers/githubAccessHelper.d.ts +0 -0
- package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +0 -0
- package/lib/firebase/helpers/index.d.ts +0 -0
- package/lib/firebase/index.d.ts +0 -0
- package/lib/firebase/index.js +1 -5
- package/lib/firebase/index.js.map +4 -4
- package/lib/firebase/oauth/disconnect.d.ts +0 -0
- package/lib/firebase/oauth/exchangeToken.d.ts +0 -0
- package/lib/firebase/oauth/getConnections.d.ts +0 -0
- package/lib/firebase/oauth/githubAccess.d.ts +2 -2
- package/lib/firebase/oauth/index.d.ts +0 -0
- package/lib/firebase/oauth/refreshToken.d.ts +0 -0
- package/lib/firebase/registerCrudFunctions.d.ts +9 -1
- package/lib/firebase/scheduled/checkExpiredSubscriptions.d.ts +0 -0
- package/lib/firebase/scheduled/index.d.ts +0 -0
- package/lib/shared/ai/classifyAIError.d.ts +0 -0
- package/lib/shared/ai/costTracker.d.ts +0 -0
- package/lib/shared/ai/createAIRoute.d.ts +0 -0
- package/lib/shared/ai/index.d.ts +0 -0
- package/lib/shared/ai/resolveModelTier.d.ts +0 -0
- package/lib/shared/billing/apiVersion.d.ts +22 -0
- package/lib/shared/billing/checkoutPrice.d.ts +27 -0
- package/lib/shared/billing/checkoutValidation.d.ts +89 -0
- package/lib/shared/billing/createCheckout.d.ts +73 -24
- package/lib/shared/billing/firestoreIdempotency.d.ts +13 -0
- package/lib/shared/billing/helpers/index.d.ts +0 -1
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +4 -4
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -29
- package/lib/shared/billing/idempotency.d.ts +21 -10
- package/lib/shared/billing/idempotencyContract.d.ts +121 -0
- package/lib/shared/billing/index.d.ts +2 -0
- package/lib/shared/billing/orderWebhook.d.ts +75 -0
- package/lib/shared/billing/stripeClient.d.ts +45 -0
- package/lib/shared/billing/supabaseIdempotency.d.ts +32 -0
- package/lib/shared/billing/tierWebhookEvents.d.ts +54 -0
- package/lib/shared/billing/webhookHandler.d.ts +29 -20
- package/lib/shared/email/createEmailRoute.d.ts +0 -0
- package/lib/shared/email/index.d.ts +0 -0
- package/lib/shared/email/provider.d.ts +0 -0
- package/lib/shared/email/resendProvider.d.ts +0 -0
- package/lib/shared/errorHandling.d.ts +0 -0
- package/lib/shared/firebase.d.ts +0 -0
- package/lib/shared/github.d.ts +0 -0
- package/lib/shared/index.d.ts +0 -0
- package/lib/shared/index.js +1 -6
- package/lib/shared/index.js.map +4 -4
- package/lib/shared/logger.d.ts +0 -0
- package/lib/shared/metadata.d.ts +0 -0
- package/lib/shared/oauth/exchangeToken.d.ts +0 -0
- package/lib/shared/oauth/grantAccess.d.ts +0 -0
- package/lib/shared/oauth/index.d.ts +0 -0
- package/lib/shared/schema.d.ts +0 -0
- package/lib/shared/utils/detectFirestore.d.ts +0 -0
- package/lib/shared/utils/external/date.d.ts +0 -0
- package/lib/shared/utils/external/index.d.ts +0 -0
- package/lib/shared/utils/external/references.d.ts +0 -0
- package/lib/shared/utils/external/subscription.d.ts +0 -0
- package/lib/shared/utils/firebaseHelpers.d.ts +0 -0
- package/lib/shared/utils/functionWrapper.d.ts +1 -1
- package/lib/shared/utils/index.d.ts +0 -0
- package/lib/shared/utils/internal/auth.d.ts +38 -1
- package/lib/shared/utils/internal/firebase.d.ts +0 -0
- package/lib/shared/utils/internal/idempotency.d.ts +0 -0
- package/lib/shared/utils/internal/index.d.ts +0 -0
- package/lib/shared/utils/internal/monitoring.d.ts +0 -0
- package/lib/shared/utils/internal/rateLimiter.d.ts +8 -0
- package/lib/shared/utils/internal/validation.d.ts +0 -8
- package/lib/shared/utils/schemaValidation.d.ts +1 -1
- package/lib/shared/utils/validation.d.ts +0 -0
- package/lib/shared/utils/vercelHelpers.d.ts +8 -0
- package/lib/shared/utils.d.ts +0 -56
- package/lib/shared/validation.d.ts +0 -0
- package/lib/supabase/ai/createAIFunction.d.ts +0 -0
- package/lib/supabase/auth/deleteAccount.d.ts +0 -0
- package/lib/supabase/auth/getCustomClaims.d.ts +0 -0
- package/lib/supabase/auth/getUserAuthStatus.d.ts +0 -0
- package/lib/supabase/auth/removeCustomClaims.d.ts +0 -0
- package/lib/supabase/auth/setCustomClaims.d.ts +0 -0
- package/lib/supabase/baseFunction.d.ts +1 -1
- package/lib/supabase/billing/cancelSubscription.d.ts +0 -0
- package/lib/supabase/billing/changePlan.d.ts +0 -0
- package/lib/supabase/billing/createCheckoutSession.d.ts +0 -0
- package/lib/supabase/billing/createCustomerPortal.d.ts +0 -0
- package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +0 -0
- package/lib/supabase/billing/stripeWebhook.d.ts +34 -0
- package/lib/supabase/crud/aggregate.d.ts +0 -0
- package/lib/supabase/crud/bulk.d.ts +1 -1
- package/lib/supabase/crud/create.d.ts +0 -0
- package/lib/supabase/crud/delete.d.ts +0 -0
- package/lib/supabase/crud/entityStore.d.ts +71 -0
- package/lib/supabase/crud/get.d.ts +0 -0
- package/lib/supabase/crud/index.d.ts +2 -0
- package/lib/supabase/crud/list.d.ts +0 -8
- package/lib/supabase/crud/update.d.ts +0 -0
- package/lib/supabase/edgeFunction.d.ts +0 -0
- package/lib/supabase/email/createEmailFunction.d.ts +0 -0
- package/lib/supabase/helpers/authProvider.d.ts +5 -5
- package/lib/supabase/index.d.ts +11 -2
- package/lib/supabase/index.js +1 -3
- package/lib/supabase/index.js.map +4 -4
- package/lib/supabase/oauth/disconnect.d.ts +0 -0
- package/lib/supabase/oauth/exchangeToken.d.ts +0 -0
- package/lib/supabase/oauth/getConnections.d.ts +0 -0
- package/lib/supabase/oauth/index.d.ts +0 -0
- package/lib/supabase/oauth/refreshToken.d.ts +0 -0
- package/lib/supabase/registerCrudFunctions.d.ts +0 -0
- package/lib/supabase/utils/idempotency.d.ts +0 -0
- package/lib/supabase/utils/monitoring.d.ts +0 -0
- package/lib/supabase/utils/rateLimiter.d.ts +1 -1
- package/lib/vercel/api/ai/chat.d.ts +0 -9
- package/lib/vercel/api/ai/index.d.ts +0 -0
- package/lib/vercel/api/auth/get-custom-claims.d.ts +8 -0
- package/lib/vercel/api/auth/get-user-auth-status.d.ts +8 -0
- package/lib/vercel/api/auth/index.d.ts +0 -0
- package/lib/vercel/api/auth/remove-custom-claims.d.ts +8 -0
- package/lib/vercel/api/auth/set-custom-claims.d.ts +8 -0
- package/lib/vercel/api/billing/backend.d.ts +39 -0
- package/lib/vercel/api/billing/cancel.d.ts +8 -0
- package/lib/vercel/api/billing/change-plan.d.ts +9 -1
- package/lib/vercel/api/billing/create-checkout-session.d.ts +25 -6
- package/lib/vercel/api/billing/customer-portal.d.ts +8 -0
- package/lib/vercel/api/billing/index.d.ts +4 -2
- package/lib/vercel/api/billing/refresh-subscription-status.d.ts +19 -3
- package/lib/vercel/api/billing/webhook-handler.d.ts +25 -4
- package/lib/vercel/api/config/constants.d.ts +0 -0
- package/lib/vercel/api/config/firebase-admin.d.ts +8 -0
- package/lib/vercel/api/config/index.d.ts +0 -0
- package/lib/vercel/api/crud/bulk.d.ts +17 -0
- package/lib/vercel/api/crud/create.d.ts +8 -0
- package/lib/vercel/api/crud/delete.d.ts +8 -0
- package/lib/vercel/api/crud/get.d.ts +8 -0
- package/lib/vercel/api/crud/index.d.ts +0 -0
- package/lib/vercel/api/crud/list.d.ts +8 -0
- package/lib/vercel/api/crud/update.d.ts +8 -0
- package/lib/vercel/api/index.d.ts +0 -0
- package/lib/vercel/api/index.js +1 -3
- package/lib/vercel/api/index.js.map +4 -4
- package/lib/vercel/api/oauth/check-github-access.d.ts +8 -0
- package/lib/vercel/api/oauth/exchange-token.d.ts +8 -0
- package/lib/vercel/api/oauth/grant-github-access.d.ts +8 -0
- package/lib/vercel/api/oauth/index.d.ts +0 -0
- package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
- package/lib/vercel/api/utils/cors.d.ts +0 -0
- package/lib/vercel/baseFunction.d.ts +4 -1
- package/lib/vercel/supabaseAdmin.d.ts +22 -0
- package/package.json +25 -26
- package/src/firebase/auth/getCustomClaims.ts +4 -5
- package/src/firebase/auth/getUserAuthStatus.ts +4 -5
- package/src/firebase/auth/removeCustomClaims.ts +4 -5
- package/src/firebase/auth/setCustomClaims.ts +4 -5
- package/src/firebase/baseFunction.ts +4 -5
- package/src/firebase/billing/cancelSubscription.ts +2 -3
- package/src/firebase/billing/changePlan.ts +3 -8
- package/src/firebase/billing/createCheckoutSession.ts +31 -61
- package/src/firebase/billing/createCustomerPortal.ts +5 -6
- package/src/firebase/billing/healthCheck.ts +1 -1
- package/src/firebase/billing/index.ts +8 -1
- package/src/firebase/billing/refreshSubscriptionStatus.ts +3 -4
- package/src/firebase/billing/webhookHandler.ts +21 -5
- package/src/firebase/crud/__tests__/bulk.test.ts +11 -1
- package/src/firebase/crud/aggregate.ts +1 -2
- package/src/firebase/crud/bulk.ts +5 -6
- package/src/firebase/crud/create.ts +5 -6
- package/src/firebase/crud/delete.ts +4 -5
- package/src/firebase/crud/get.ts +4 -5
- package/src/firebase/crud/list.ts +4 -5
- package/src/firebase/crud/update.ts +5 -6
- package/src/firebase/oauth/githubAccess.ts +2 -3
- package/src/firebase/registerCrudFunctions.ts +2 -2
- package/src/shared/__tests__/auth.test.ts +0 -3
- package/src/shared/__tests__/bulkCore.test.ts +3 -2
- package/src/shared/__tests__/errorHandling.test.ts +2 -2
- package/src/shared/__tests__/idempotency.test.ts +282 -55
- package/src/shared/__tests__/internalValidation.test.ts +3 -42
- package/src/shared/__tests__/logger.test.ts +31 -0
- package/src/shared/__tests__/rateLimiter.test.ts +2 -8
- package/src/shared/__tests__/schemaValidation.test.ts +1 -1
- package/src/shared/__tests__/utils.test.ts +3 -2
- package/src/shared/__tests__/validation-env.test.ts +0 -0
- package/src/shared/ai/createAIRoute.ts +53 -30
- package/src/shared/billing/__tests__/checkoutValidation.test.ts +219 -0
- package/src/shared/billing/__tests__/createCheckout.compat.test.ts +349 -0
- package/src/shared/billing/__tests__/createCheckout.test.ts +454 -411
- package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +92 -0
- package/src/shared/billing/__tests__/webhookCorrectness.test.ts +387 -0
- package/src/shared/billing/__tests__/webhookHandler.test.ts +370 -23
- package/src/shared/billing/apiVersion.ts +25 -0
- package/src/shared/billing/checkoutPrice.ts +125 -0
- package/src/shared/billing/checkoutValidation.ts +284 -0
- package/src/shared/billing/createCheckout.ts +332 -196
- package/src/shared/billing/firestoreIdempotency.ts +189 -0
- package/src/shared/billing/helpers/index.ts +0 -1
- package/src/shared/billing/helpers/subscriptionManagement.ts +8 -10
- package/src/shared/billing/helpers/updateUserSubscription.ts +3 -36
- package/src/shared/billing/idempotency.ts +104 -168
- package/src/shared/billing/idempotencyContract.ts +135 -0
- package/src/shared/billing/index.ts +2 -0
- package/src/shared/billing/orderWebhook.ts +269 -0
- package/src/shared/billing/stripeClient.ts +91 -0
- package/src/shared/billing/supabaseIdempotency.ts +228 -0
- package/src/shared/billing/tierWebhookEvents.ts +432 -0
- package/src/shared/billing/webhookHandler.ts +189 -386
- package/src/shared/logger.ts +4 -6
- package/src/shared/utils/external/subscription.ts +0 -0
- package/src/shared/utils/firebaseHelpers.ts +2 -3
- package/src/shared/utils/functionWrapper.ts +1 -2
- package/src/shared/utils/internal/auth.ts +55 -7
- package/src/shared/utils/internal/monitoring.ts +17 -9
- package/src/shared/utils/internal/rateLimiter.ts +14 -5
- package/src/shared/utils/internal/validation.ts +0 -18
- package/src/shared/utils/schemaValidation.ts +1 -2
- package/src/shared/utils/vercelHelpers.ts +3 -3
- package/src/shared/utils.ts +5 -99
- package/src/shared/validation.ts +1 -1
- package/src/supabase/__tests__/bulk.test.ts +3 -1
- package/src/supabase/__tests__/entityStore.test.ts +90 -0
- package/src/supabase/baseFunction.ts +1 -2
- package/src/supabase/billing/cancelSubscription.ts +1 -1
- package/src/supabase/billing/changePlan.ts +1 -1
- package/src/supabase/billing/createCheckoutSession.ts +11 -41
- package/src/supabase/billing/createCustomerPortal.ts +1 -1
- package/src/supabase/billing/refreshSubscriptionStatus.ts +2 -7
- package/src/supabase/billing/stripeWebhook.ts +79 -0
- package/src/supabase/crud/aggregate.ts +1 -1
- package/src/supabase/crud/bulk.ts +3 -7
- package/src/supabase/crud/create.ts +1 -1
- package/src/supabase/crud/entityStore.ts +240 -0
- package/src/supabase/crud/index.ts +8 -0
- package/src/supabase/crud/list.ts +2 -0
- package/src/supabase/crud/update.ts +1 -1
- package/src/supabase/helpers/authProvider.ts +6 -5
- package/src/supabase/index.ts +26 -0
- package/src/supabase/utils/rateLimiter.ts +2 -2
- package/src/vercel/__tests__/bulk.test.ts +24 -21
- package/src/vercel/__tests__/firebaseOptional.test.ts +64 -0
- package/src/vercel/api/ai/chat.ts +2 -1
- package/src/vercel/api/auth/get-custom-claims.ts +2 -3
- package/src/vercel/api/auth/get-user-auth-status.ts +2 -3
- package/src/vercel/api/auth/remove-custom-claims.ts +2 -3
- package/src/vercel/api/auth/set-custom-claims.ts +3 -3
- package/src/vercel/api/billing/backend.ts +72 -0
- package/src/vercel/api/billing/cancel.ts +2 -4
- package/src/vercel/api/billing/change-plan.ts +4 -5
- package/src/vercel/api/billing/create-checkout-session.ts +43 -73
- package/src/vercel/api/billing/customer-portal.ts +3 -5
- package/src/vercel/api/billing/index.ts +4 -2
- package/src/vercel/api/billing/refresh-subscription-status.ts +22 -7
- package/src/vercel/api/billing/webhook-handler.ts +32 -26
- package/src/vercel/api/config/firebase-admin.ts +2 -2
- package/src/vercel/api/crud/bulk.ts +6 -9
- package/src/vercel/api/crud/create.ts +6 -5
- package/src/vercel/api/crud/delete.ts +4 -3
- package/src/vercel/api/crud/get.ts +6 -5
- package/src/vercel/api/crud/list.ts +6 -5
- package/src/vercel/api/crud/update.ts +6 -5
- package/src/vercel/api/oauth/check-github-access.ts +5 -5
- package/src/vercel/api/oauth/exchange-token.ts +3 -3
- package/src/vercel/api/oauth/grant-github-access.ts +5 -5
- package/src/vercel/api/oauth/revoke-github-access.ts +3 -4
- package/src/vercel/baseFunction.ts +23 -8
- package/src/vercel/supabaseAdmin.ts +45 -0
- package/lib/shared/ai/createAIHandler.d.ts +0 -39
- package/lib/shared/ai/providers/anthropic.d.ts +0 -12
- package/lib/shared/ai/providers/google.d.ts +0 -10
- package/lib/shared/ai/providers/index.d.ts +0 -23
- package/lib/shared/ai/providers/openai.d.ts +0 -10
- package/lib/shared/ai/utils/parseSSE.d.ts +0 -22
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Stripe client for billing functions
|
|
3
|
+
* @description Lazily initialized Stripe SDK instance shared by the Firebase,
|
|
4
|
+
* Vercel and Supabase billing handlers. Kept apart from `shared/utils.ts` so
|
|
5
|
+
* code that does not bill (CRUD, auth) never loads the Stripe SDK.
|
|
6
|
+
*
|
|
7
|
+
* @version 0.2.1
|
|
8
|
+
* @since 0.0.1
|
|
9
|
+
* @author AMBROISE PARK Consulting
|
|
10
|
+
*/
|
|
11
|
+
import Stripe from 'stripe';
|
|
12
|
+
/**
|
|
13
|
+
* Initialize Stripe explicitly (e.g. with a secret from defineSecret).
|
|
14
|
+
* API version: `STRIPE_API_VERSION`, else {@link STRIPE_API_VERSION_PIN}.
|
|
15
|
+
* @param apiKey - Stripe secret key
|
|
16
|
+
*
|
|
17
|
+
* @version 0.2.0
|
|
18
|
+
* @since 0.0.1
|
|
19
|
+
* @author AMBROISE PARK Consulting
|
|
20
|
+
*/
|
|
21
|
+
export declare function initStripe(apiKey: string): Stripe;
|
|
22
|
+
/**
|
|
23
|
+
* Get Stripe instance with lazy initialization
|
|
24
|
+
*
|
|
25
|
+
* @version 0.1.0
|
|
26
|
+
* @since 0.0.1
|
|
27
|
+
* @author AMBROISE PARK Consulting
|
|
28
|
+
*/
|
|
29
|
+
export declare function getStripe(): Stripe;
|
|
30
|
+
/**
|
|
31
|
+
* Lazy-initialized Stripe instance proxy
|
|
32
|
+
*
|
|
33
|
+
* @version 0.1.0
|
|
34
|
+
* @since 0.0.1
|
|
35
|
+
* @author AMBROISE PARK Consulting
|
|
36
|
+
*/
|
|
37
|
+
export declare const stripe: Stripe;
|
|
38
|
+
/**
|
|
39
|
+
* Validates that required Stripe environment variables are set
|
|
40
|
+
*
|
|
41
|
+
* @version 0.1.0
|
|
42
|
+
* @since 0.0.1
|
|
43
|
+
* @author AMBROISE PARK Consulting
|
|
44
|
+
*/
|
|
45
|
+
export declare function validateStripeEnvironment(): void;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Postgres (Supabase) webhook idempotency store
|
|
3
|
+
* @description `webhook_events` table and its RPCs. Re-exported from
|
|
4
|
+
* `idempotency.ts`.
|
|
5
|
+
*
|
|
6
|
+
* @version 0.2.0
|
|
7
|
+
* @since 0.2.0
|
|
8
|
+
* @author AMBROISE PARK Consulting
|
|
9
|
+
*/
|
|
10
|
+
import type { SupabaseClient } from '@supabase/supabase-js';
|
|
11
|
+
import type { IdempotencyStore } from './idempotencyContract.js';
|
|
12
|
+
/**
|
|
13
|
+
* SQL required by {@link createSupabaseIdempotencyStore}: table, the
|
|
14
|
+
* service_role-only RPCs `webhook_event_reserve` / `webhook_event_mark_processed`
|
|
15
|
+
* / `webhook_event_release`, and a daily pg_cron cleanup (30 days). Shipped
|
|
16
|
+
* verbatim as the CLI Supabase template migration `*_webhook_events.sql`.
|
|
17
|
+
*
|
|
18
|
+
* @version 0.2.0
|
|
19
|
+
* @since 0.2.0
|
|
20
|
+
* @author AMBROISE PARK Consulting
|
|
21
|
+
*/
|
|
22
|
+
export declare const WEBHOOK_EVENTS_SQL = "\nCREATE TABLE IF NOT EXISTS public.webhook_events (\n event_id TEXT PRIMARY KEY,\n status TEXT NOT NULL CHECK (status IN ('processing', 'processed')),\n owner_token UUID NOT NULL,\n reserved_at TIMESTAMPTZ NOT NULL DEFAULT now(),\n processed_at TIMESTAMPTZ\n);\n\n-- Only service_role accesses this table\nALTER TABLE public.webhook_events ENABLE ROW LEVEL SECURITY;\n\nCREATE INDEX IF NOT EXISTS idx_webhook_events_processed_at\n ON public.webhook_events (processed_at);\n\n-- The functions below run as the caller (SECURITY INVOKER) and refuse every\n-- role but service_role. EXECUTE is deliberately not revoked: on Supabase\n-- Postgres 17.6.1.x a permission-denied function call by anon/authenticated\n-- crashes the backend (signal 11), which restarts every connection.\nCREATE OR REPLACE FUNCTION public.webhook_events_assert_service_role()\nRETURNS VOID\nLANGUAGE plpgsql\nSET search_path = public\nAS $$\nBEGIN\n IF current_user IS DISTINCT FROM 'service_role' THEN\n RAISE EXCEPTION 'webhook_events is reserved to service_role (current role: %)', current_user\n USING ERRCODE = 'insufficient_privilege';\n END IF;\nEND;\n$$;\n\n-- Atomic reservation. Returns:\n-- 'reserved' the caller now owns the event under p_owner_token\n-- 'processed' the event was already processed (skip, answer 2xx)\n-- 'in_progress' another worker holds a live lease (answer non-2xx, Stripe retries)\n-- A 'processing' row older than the lease is retaken (abandoned worker).\nCREATE OR REPLACE FUNCTION public.webhook_event_reserve(\n p_event_id TEXT,\n p_owner_token UUID,\n p_lease_seconds INT\n)\nRETURNS TEXT\nLANGUAGE plpgsql\nSET search_path = public\nAS $$\nDECLARE\n v_status TEXT;\nBEGIN\n PERFORM public.webhook_events_assert_service_role();\n\n INSERT INTO public.webhook_events (event_id, status, owner_token, reserved_at)\n VALUES (p_event_id, 'processing', p_owner_token, clock_timestamp())\n ON CONFLICT (event_id) DO UPDATE\n SET owner_token = EXCLUDED.owner_token,\n reserved_at = clock_timestamp()\n WHERE webhook_events.status = 'processing'\n AND webhook_events.reserved_at\n < clock_timestamp() - make_interval(secs => p_lease_seconds);\n IF FOUND THEN\n RETURN 'reserved';\n END IF;\n\n SELECT status INTO v_status\n FROM public.webhook_events\n WHERE event_id = p_event_id;\n IF v_status = 'processed' THEN\n RETURN 'processed';\n END IF;\n -- Live lease, or the row was released in between: Stripe retries either way\n RETURN 'in_progress';\nEND;\n$$;\n\n-- Mark a reservation processed. Returns false when p_owner_token no longer owns\n-- the row (lease retaken, released, or deleted). Repeating it for the same\n-- owner is a no-op that returns true.\nCREATE OR REPLACE FUNCTION public.webhook_event_mark_processed(\n p_event_id TEXT,\n p_owner_token UUID\n)\nRETURNS BOOLEAN\nLANGUAGE plpgsql\nSET search_path = public\nAS $$\nBEGIN\n PERFORM public.webhook_events_assert_service_role();\n\n UPDATE public.webhook_events\n SET status = 'processed',\n processed_at = COALESCE(processed_at, clock_timestamp())\n WHERE event_id = p_event_id\n AND owner_token = p_owner_token;\n RETURN FOUND;\nEND;\n$$;\n\n-- Drop a reservation after a processing failure. Returns false when\n-- p_owner_token does not own a 'processing' row (nothing is deleted).\nCREATE OR REPLACE FUNCTION public.webhook_event_release(\n p_event_id TEXT,\n p_owner_token UUID\n)\nRETURNS BOOLEAN\nLANGUAGE plpgsql\nSET search_path = public\nAS $$\nBEGIN\n PERFORM public.webhook_events_assert_service_role();\n\n DELETE FROM public.webhook_events\n WHERE event_id = p_event_id\n AND owner_token = p_owner_token\n AND status = 'processing';\n RETURN FOUND;\nEND;\n$$;\n\n-- Enable pg_cron extension (if not already enabled)\nCREATE EXTENSION IF NOT EXISTS pg_cron;\n\n-- Cleanup webhook events older than 30 days (daily at 5 AM UTC).\n-- Stripe retries an event for up to 3 days, so older rows are never read again.\nSELECT cron.schedule(\n 'cleanup-webhook-events',\n '0 5 * * *',\n $$DELETE FROM public.webhook_events WHERE COALESCE(processed_at, reserved_at) < now() - interval '30 days'$$\n);\n";
|
|
23
|
+
/**
|
|
24
|
+
* Postgres-backed store (Supabase). Requires {@link WEBHOOK_EVENTS_SQL}.
|
|
25
|
+
*
|
|
26
|
+
* @param supabaseAdmin - Supabase client created with the service role key
|
|
27
|
+
*
|
|
28
|
+
* @version 0.2.0
|
|
29
|
+
* @since 0.2.0
|
|
30
|
+
* @author AMBROISE PARK Consulting
|
|
31
|
+
*/
|
|
32
|
+
export declare function createSupabaseIdempotencyStore(supabaseAdmin: SupabaseClient): IdempotencyStore;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Stripe webhook handlers for tier items
|
|
3
|
+
* @description StripePayment / StripeSubscription event handlers routed by
|
|
4
|
+
* `processWebhook`: checkout grant (payment_status aware), renewal,
|
|
5
|
+
* cancellation and payment failure.
|
|
6
|
+
*
|
|
7
|
+
* @version 0.2.0
|
|
8
|
+
* @since 0.0.1
|
|
9
|
+
* @author AMBROISE PARK Consulting
|
|
10
|
+
*/
|
|
11
|
+
import type Stripe from 'stripe';
|
|
12
|
+
import type { BillingAuthProvider, StripeBackConfig, UpdateSubscriptionFn } from '@donotdev/core/server';
|
|
13
|
+
import type { OrderSessionEventType } from './orderWebhook.js';
|
|
14
|
+
/**
|
|
15
|
+
* Checkout Session event of a StripePayment / StripeSubscription item.
|
|
16
|
+
* Grants only once the payment is settled (Stripe fulfillment guide,
|
|
17
|
+
* https://docs.stripe.com/checkout/fulfillment):
|
|
18
|
+
* - `completed` + `paid` / `no_payment_required` → grant
|
|
19
|
+
* - `completed` + `unpaid` (delayed method, e.g. SEPA debit) → log, wait
|
|
20
|
+
* - `async_payment_succeeded` → grant
|
|
21
|
+
* - `async_payment_failed` → log (nothing was granted)
|
|
22
|
+
* - `expired` → ignored
|
|
23
|
+
*
|
|
24
|
+
* @throws When `payment_status` is not a known value, or when the grant fails
|
|
25
|
+
*
|
|
26
|
+
* @version 0.2.0
|
|
27
|
+
* @since 0.2.0
|
|
28
|
+
* @author AMBROISE PARK Consulting
|
|
29
|
+
*/
|
|
30
|
+
export declare function handleTierCheckoutEvent(eventType: OrderSessionEventType, session: Stripe.Checkout.Session, config: StripeBackConfig, updateSubscription: UpdateSubscriptionFn, authProvider: BillingAuthProvider | null): Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* Handle subscription renewal
|
|
33
|
+
*
|
|
34
|
+
* @version 0.1.0
|
|
35
|
+
* @since 0.0.1
|
|
36
|
+
* @author AMBROISE PARK Consulting
|
|
37
|
+
*/
|
|
38
|
+
export declare function handleInvoicePaymentSucceeded(invoice: Stripe.Invoice, config: StripeBackConfig, updateSubscription: UpdateSubscriptionFn, stripe: Stripe, authProvider: BillingAuthProvider | null): Promise<void>;
|
|
39
|
+
/**
|
|
40
|
+
* Handle subscription cancellation
|
|
41
|
+
*
|
|
42
|
+
* @version 0.1.0
|
|
43
|
+
* @since 0.0.1
|
|
44
|
+
* @author AMBROISE PARK Consulting
|
|
45
|
+
*/
|
|
46
|
+
export declare function handleSubscriptionDeleted(subscription: Stripe.Subscription, config: StripeBackConfig, updateSubscription: UpdateSubscriptionFn, authProvider: BillingAuthProvider | null): Promise<void>;
|
|
47
|
+
/**
|
|
48
|
+
* Handle payment failure
|
|
49
|
+
*
|
|
50
|
+
* @version 0.1.0
|
|
51
|
+
* @since 0.0.1
|
|
52
|
+
* @author AMBROISE PARK Consulting
|
|
53
|
+
*/
|
|
54
|
+
export declare function handlePaymentFailed(invoice: Stripe.Invoice, config: StripeBackConfig): Promise<void>;
|
|
@@ -1,20 +1,28 @@
|
|
|
1
|
-
import type { SubscriptionData, AuthProvider } from './helpers/updateUserSubscription.js';
|
|
2
|
-
import type Stripe from 'stripe';
|
|
3
|
-
/**
|
|
4
|
-
* Platform-agnostic auth provider interface for webhook handlers
|
|
5
|
-
*/
|
|
6
|
-
export interface WebhookAuthProvider {
|
|
7
|
-
getUser(userId: string): Promise<{
|
|
8
|
-
customClaims?: Record<string, unknown>;
|
|
9
|
-
}>;
|
|
10
|
-
setCustomUserClaims(userId: string, claims: Record<string, unknown>): Promise<void>;
|
|
11
|
-
}
|
|
12
1
|
/**
|
|
13
|
-
*
|
|
2
|
+
* @fileoverview Stripe webhook handler
|
|
3
|
+
* @description Verifies, deduplicates and routes Stripe webhook events for
|
|
4
|
+
* one-time payments, subscriptions (`tierWebhookEvents.ts`) and multi-line
|
|
5
|
+
* orders (`orderWebhook.ts`).
|
|
6
|
+
*
|
|
7
|
+
* @version 0.2.0
|
|
8
|
+
* @since 0.0.1
|
|
9
|
+
* @author AMBROISE PARK Consulting
|
|
14
10
|
*/
|
|
15
|
-
|
|
11
|
+
import type Stripe from 'stripe';
|
|
12
|
+
import type { BillingAuthProvider, StripeBackConfig, UpdateSubscriptionFn } from '@donotdev/core/server';
|
|
13
|
+
import type { IdempotencyStore } from './idempotencyContract.js';
|
|
16
14
|
/**
|
|
17
|
-
*
|
|
15
|
+
* Verify, deduplicate and route one Stripe webhook event.
|
|
16
|
+
*
|
|
17
|
+
* Idempotency (at-least-once): the event is reserved before routing.
|
|
18
|
+
* - Already processed → resolves "Event already processed" (answer 2xx).
|
|
19
|
+
* - Another delivery holds a live lease → throws `unavailable` (answer non-2xx,
|
|
20
|
+
* Stripe retries later; an abandoned lease is retaken after it expires).
|
|
21
|
+
* - Routing throws → the reservation is released and the error rethrown, so
|
|
22
|
+
* Stripe's retry is processed.
|
|
23
|
+
* - Routing succeeds → the event is marked processed, retried a bounded number
|
|
24
|
+
* of times; if it still fails the error is rethrown WITHOUT releasing, so the
|
|
25
|
+
* event is re-run after the lease. Hooks must therefore be idempotent.
|
|
18
26
|
*
|
|
19
27
|
* @param rawBody - Raw request body
|
|
20
28
|
* @param signature - Stripe signature
|
|
@@ -22,16 +30,17 @@ export type UpdateSubscriptionFn = (userId: string, data: SubscriptionData, auth
|
|
|
22
30
|
* @param stripe - Stripe instance
|
|
23
31
|
* @param billingConfig - Billing configuration
|
|
24
32
|
* @param updateSubscription - Function to update user subscription
|
|
33
|
+
* @param authProvider - Auth provider for subscription claims (null: subscription events fail)
|
|
34
|
+
* @param idempotencyStore - Durable store matching the backend
|
|
35
|
+
* (`createFirestoreIdempotencyStore` / `createSupabaseIdempotencyStore`). Required:
|
|
36
|
+
* shared logic never picks a backend.
|
|
37
|
+
* @throws Any failure: the caller must answer non-2xx so Stripe retries
|
|
25
38
|
*
|
|
26
|
-
* @version 0.1
|
|
39
|
+
* @version 0.2.1
|
|
27
40
|
* @since 0.0.1
|
|
28
41
|
* @author AMBROISE PARK Consulting
|
|
29
42
|
*/
|
|
30
|
-
export declare function processWebhook(rawBody: string | Buffer, signature: string, webhookSecret: string, stripe: Stripe, billingConfig:
|
|
43
|
+
export declare function processWebhook(rawBody: string | Buffer, signature: string, webhookSecret: string, stripe: Stripe, billingConfig: StripeBackConfig, updateSubscription: UpdateSubscriptionFn, authProvider: BillingAuthProvider | null, idempotencyStore: IdempotencyStore): Promise<{
|
|
31
44
|
success: boolean;
|
|
32
45
|
message: string;
|
|
33
46
|
}>;
|
|
34
|
-
/**
|
|
35
|
-
* Calculate subscription end date with proper edge case handling
|
|
36
|
-
* Fixes issues like Jan 31 + 1 month = March 3 (should be Feb 28/29)
|
|
37
|
-
*/
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
package/lib/shared/firebase.d.ts
CHANGED
|
File without changes
|
package/lib/shared/github.d.ts
CHANGED
|
File without changes
|
package/lib/shared/index.d.ts
CHANGED
|
File without changes
|
package/lib/shared/index.js
CHANGED
|
@@ -18,10 +18,5 @@ if (typeof globalThis !== 'undefined') {
|
|
|
18
18
|
globalThis.global = globalThis;
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
-
var kr=Object.defineProperty;var i=(e,t)=>kr(e,"name",{value:t,configurable:!0});var c=(e,t)=>()=>(e&&(t=e(e=0)),t);var Lo=(e,t)=>{for(var r in t)kr(e,r,{get:t[r],enumerable:!0})};var se,Qe,wr,At,Rr,Ar,Tt=c(()=>{"use strict";se={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},Qe={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},wr={[se.ANTHROPIC]:{default:"claude-sonnet-4-6",models:["claude-sonnet-4-6","claude-sonnet-4-20250514","claude-haiku-4-5-20251001","claude-opus-4-6","claude-opus-4-20250514"]},[se.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[se.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}},At={FAST:{id:"fast",defaultModel:"claude-haiku-4-5-20251001"},STANDARD:{id:"standard",defaultModel:"claude-sonnet-4-6"},PREMIUM:{id:"premium",defaultModel:"claude-opus-4-6"}},Rr=4,Ar={"claude-sonnet-4-6":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-haiku-4-5-20251001":{promptPer1M:.8,completionPer1M:4,currency:"usd"},"claude-opus-4-6":{promptPer1M:15,completionPer1M:75,currency:"usd"},"claude-sonnet-4-20250514":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-opus-4-20250514":{promptPer1M:15,completionPer1M:75,currency:"usd"},"gpt-4o":{promptPer1M:2.5,completionPer1M:10,currency:"usd"},"gpt-4o-mini":{promptPer1M:.15,completionPer1M:.6,currency:"usd"},"gpt-4.1":{promptPer1M:2,completionPer1M:8,currency:"usd"},"gpt-4.1-mini":{promptPer1M:.4,completionPer1M:1.6,currency:"usd"},"o3-mini":{promptPer1M:1.1,completionPer1M:4.4,currency:"usd"},"gemini-2.0-flash":{promptPer1M:.1,completionPer1M:.4,currency:"usd"},"gemini-2.5-pro":{promptPer1M:1.25,completionPer1M:10,currency:"usd"},"gemini-2.5-flash":{promptPer1M:.15,completionPer1M:.6,currency:"usd"}}});function Ct(e){return{lang:e?.lang??It?.lang,message:e?.message,abortEarly:e?.abortEarly??It?.abortEarly,abortPipeEarly:e?.abortPipeEarly??It?.abortPipeEarly}}function qo(e){return Bo?.get(e)}function Vo(e){return $o?.get(e)}function Go(e,t){return jo?.get(e)?.get(t)}function we(e){let t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function D(e,t,r,n,o){let s=o&&"input"in o?o.input:r.value,u=o?.expected??e.expects??null,d=o?.received??we(s),p={kind:e.kind,type:e.type,input:s,expected:u,received:d,message:`Invalid ${t}: ${u?`Expected ${u} but r`:"R"}eceived ${d}`,requirement:e.requirement,path:o?.path,issues:o?.issues,lang:n.lang,abortEarly:n.abortEarly,abortPipeEarly:n.abortPipeEarly},g=e.kind==="schema",m=o?.message??e.message??Go(e.reference,p.lang)??(g?Vo(p.lang):null)??n.message??qo(p.lang);m!==void 0&&(p.message=typeof m=="function"?m(p):m),g&&(r.typed=!1),r.issues?r.issues.push(p):r.issues=[p]}function q(e){return{version:1,vendor:"valibot",validate(t){return e["~run"]({value:t},Ct())}}}function Ir(e,t){return Object.hasOwn(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}function Pt(e,t){let r=[...new Set(e)];return r.length>1?`(${r.join(` ${t} `)})`:r[0]??"never"}function Cr(e){return e instanceof et}function Re(e,t){return{kind:"validation",type:"check",reference:Re,async:!1,expects:null,requirement:e,message:t,"~run"(r,n){return r.typed&&!this.requirement(r.value)&&D(this,"input",r,n),r}}}function ne(e){return{kind:"validation",type:"email",reference:ne,expects:null,async:!1,requirement:Ho,message:e,"~run"(t,r){return t.typed&&!this.requirement.test(t.value)&&D(this,"email",t,r),t}}}function ae(e){return{kind:"validation",type:"integer",reference:ae,async:!1,expects:null,requirement:Number.isInteger,message:e,"~run"(t,r){return t.typed&&!this.requirement(t.value)&&D(this,"integer",t,r),t}}}function ue(e){return{kind:"validation",type:"iso_timestamp",reference:ue,async:!1,expects:null,requirement:Wo,message:e,"~run"(t,r){return t.typed&&!this.requirement.test(t.value)&&D(this,"timestamp",t,r),t}}}function Ae(e,t){return{kind:"validation",type:"length",reference:Ae,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&r.value.length!==this.requirement&&D(this,"length",r,n,{received:`${r.value.length}`}),r}}}function _e(e,t){return{kind:"validation",type:"max_length",reference:_e,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&r.value.length>this.requirement&&D(this,"length",r,n,{received:`${r.value.length}`}),r}}}function pe(e,t){return{kind:"validation",type:"max_value",reference:pe,async:!1,expects:`<=${e instanceof Date?e.toJSON():we(e)}`,requirement:e,message:t,"~run"(r,n){return r.typed&&!(r.value<=this.requirement)&&D(this,"value",r,n,{received:r.value instanceof Date?r.value.toJSON():we(r.value)}),r}}}function h(e,t){return{kind:"validation",type:"min_length",reference:h,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&r.value.length<this.requirement&&D(this,"length",r,n,{received:`${r.value.length}`}),r}}}function U(e,t){return{kind:"validation",type:"min_value",reference:U,async:!1,expects:`>=${e instanceof Date?e.toJSON():we(e)}`,requirement:e,message:t,"~run"(r,n){return r.typed&&!(r.value>=this.requirement)&&D(this,"value",r,n,{received:r.value instanceof Date?r.value.toJSON():we(r.value)}),r}}}function Fe(e,t){return{kind:"validation",type:"regex",reference:Fe,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(r,n){return r.typed&&!this.requirement.test(r.value)&&D(this,"format",r,n),r}}}function Y(e){return{kind:"validation",type:"url",reference:Y,async:!1,expects:null,requirement(t){try{return new URL(t),!0}catch{return!1}},message:e,"~run"(t,r){return t.typed&&!this.requirement(t.value)&&D(this,"URL",t,r),t}}}function Pr(e,t,r){return typeof e.fallback=="function"?e.fallback(t,r):e.fallback}function $e(e,t,r){return typeof e.default=="function"?e.default(t,r):e.default}function de(){return{kind:"schema",type:"any",reference:de,expects:"any",async:!1,get"~standard"(){return q(this)},"~run"(e){return e.typed=!0,e}}}function R(e,t){return{kind:"schema",type:"array",reference:R,expects:"Array",async:!1,item:e,message:t,get"~standard"(){return q(this)},"~run"(r,n){let o=r.value;if(Array.isArray(o)){r.typed=!0,r.value=[];for(let s=0;s<o.length;s++){let u=o[s],d=this.item["~run"]({value:u},n);if(d.issues){let p={type:"array",origin:"value",input:o,key:s,value:u};for(let g of d.issues)g.path?g.path.unshift(p):g.path=[p],r.issues?.push(g);if(r.issues||(r.issues=d.issues),n.abortEarly){r.typed=!1;break}}d.typed||(r.typed=!1),r.value.push(d.value)}}else D(this,"type",r,n);return r}}}function O(e){return{kind:"schema",type:"boolean",reference:O,expects:"boolean",async:!1,message:e,get"~standard"(){return q(this)},"~run"(t,r){return typeof t.value=="boolean"?t.typed=!0:D(this,"type",t,r),t}}}function Dt(e,t){return{kind:"schema",type:"custom",reference:Dt,expects:"unknown",async:!1,check:e,message:t,get"~standard"(){return q(this)},"~run"(r,n){return this.check(r.value)?r.typed=!0:D(this,"type",r,n),r}}}function Ot(e){return{kind:"schema",type:"lazy",reference:Ot,expects:"unknown",async:!1,getter:e,get"~standard"(){return q(this)},"~run"(t,r){return this.getter(t.value)["~run"](t,r)}}}function be(e,t){return{kind:"schema",type:"literal",reference:be,expects:we(e),async:!1,literal:e,message:t,get"~standard"(){return q(this)},"~run"(r,n){return r.value===this.literal?r.typed=!0:D(this,"type",r,n),r}}}function _t(e,t){return{kind:"schema",type:"loose_object",reference:_t,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return q(this)},"~run"(r,n){let o=r.value;if(o&&typeof o=="object"){r.typed=!0,r.value={};for(let s in this.entries){let u=this.entries[s];if(s in o||(u.type==="exact_optional"||u.type==="optional"||u.type==="nullish")&&u.default!==void 0){let d=s in o?o[s]:$e(u),p=u["~run"]({value:d},n);if(p.issues){let g={type:"object",origin:"value",input:o,key:s,value:d};for(let m of p.issues)m.path?m.path.unshift(g):m.path=[g],r.issues?.push(m);if(r.issues||(r.issues=p.issues),n.abortEarly){r.typed=!1;break}}p.typed||(r.typed=!1),r.value[s]=p.value}else if(u.fallback!==void 0)r.value[s]=Pr(u);else if(u.type!=="exact_optional"&&u.type!=="optional"&&u.type!=="nullish"&&(D(this,"key",r,n,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:o,key:s,value:o[s]}]}),n.abortEarly))break}if(!r.issues||!n.abortEarly)for(let s in o)Ir(o,s)&&!(s in this.entries)&&(r.value[s]=o[s])}else D(this,"type",r,n);return r}}}function Ft(e){return{kind:"schema",type:"never",reference:Ft,expects:"never",async:!1,message:e,get"~standard"(){return q(this)},"~run"(t,r){return D(this,"type",t,r),t}}}function V(e,t){return{kind:"schema",type:"nullable",reference:V,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,get"~standard"(){return q(this)},"~run"(r,n){return r.value===null&&(this.default!==void 0&&(r.value=$e(this,r,n)),r.value===null)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function ee(e,t){return{kind:"schema",type:"nullish",reference:ee,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return q(this)},"~run"(r,n){return(r.value===null||r.value===void 0)&&(this.default!==void 0&&(r.value=$e(this,r,n)),r.value===null||r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function k(e){return{kind:"schema",type:"number",reference:k,expects:"number",async:!1,message:e,get"~standard"(){return q(this)},"~run"(t,r){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:D(this,"type",t,r),t}}}function y(e,t){return{kind:"schema",type:"object",reference:y,expects:"Object",async:!1,entries:e,message:t,get"~standard"(){return q(this)},"~run"(r,n){let o=r.value;if(o&&typeof o=="object"){r.typed=!0,r.value={};for(let s in this.entries){let u=this.entries[s];if(s in o||(u.type==="exact_optional"||u.type==="optional"||u.type==="nullish")&&u.default!==void 0){let d=s in o?o[s]:$e(u),p=u["~run"]({value:d},n);if(p.issues){let g={type:"object",origin:"value",input:o,key:s,value:d};for(let m of p.issues)m.path?m.path.unshift(g):m.path=[g],r.issues?.push(m);if(r.issues||(r.issues=p.issues),n.abortEarly){r.typed=!1;break}}p.typed||(r.typed=!1),r.value[s]=p.value}else if(u.fallback!==void 0)r.value[s]=Pr(u);else if(u.type!=="exact_optional"&&u.type!=="optional"&&u.type!=="nullish"&&(D(this,"key",r,n,{input:void 0,expected:`"${s}"`,path:[{type:"object",origin:"key",input:o,key:s,value:o[s]}]}),n.abortEarly))break}}else D(this,"type",r,n);return r}}}function l(e,t){return{kind:"schema",type:"optional",reference:l,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,get"~standard"(){return q(this)},"~run"(r,n){return r.value===void 0&&(this.default!==void 0&&(r.value=$e(this,r,n)),r.value===void 0)?(r.typed=!0,r):this.wrapped["~run"](r,n)}}}function A(e,t){return{kind:"schema",type:"picklist",reference:A,expects:Pt(e.map(we),"|"),async:!1,options:e,message:t,get"~standard"(){return q(this)},"~run"(r,n){return this.options.includes(r.value)?r.typed=!0:D(this,"type",r,n),r}}}function T(e,t,r){return{kind:"schema",type:"record",reference:T,expects:"Object",async:!1,key:e,value:t,message:r,get"~standard"(){return q(this)},"~run"(n,o){let s=n.value;if(s&&typeof s=="object"){n.typed=!0,n.value={};for(let u in s)if(Ir(s,u)){let d=s[u],p=this.key["~run"]({value:u},o);if(p.issues){let m={type:"object",origin:"key",input:s,key:u,value:d};for(let x of p.issues)x.path=[m],n.issues?.push(x);if(n.issues||(n.issues=p.issues),o.abortEarly){n.typed=!1;break}}let g=this.value["~run"]({value:d},o);if(g.issues){let m={type:"object",origin:"value",input:s,key:u,value:d};for(let x of g.issues)x.path?x.path.unshift(m):x.path=[m],n.issues?.push(x);if(n.issues||(n.issues=g.issues),o.abortEarly){n.typed=!1;break}}(!p.typed||!g.typed)&&(n.typed=!1),p.typed&&(n.value[p.value]=g.value)}}else D(this,"type",n,o);return n}}}function a(e){return{kind:"schema",type:"string",reference:a,expects:"string",async:!1,message:e,get"~standard"(){return q(this)},"~run"(t,r){return typeof t.value=="string"?t.typed=!0:D(this,"type",t,r),t}}}function Tr(e){let t;if(e)for(let r of e)t?t.push(...r.issues):t=r.issues;return t}function Te(e,t){return{kind:"schema",type:"union",reference:Te,expects:Pt(e.map(r=>r.expects),"|"),async:!1,options:e,message:t,get"~standard"(){return q(this)},"~run"(r,n){let o,s,u;for(let d of this.options){let p=d["~run"]({value:r.value},n);if(p.typed)if(p.issues)s?s.push(p):s=[p];else{o=p;break}else u?u.push(p):u=[p]}if(o)return o;if(s){if(s.length===1)return s[0];D(this,"type",r,n,{issues:Tr(s)}),r.typed=!0}else{if(u?.length===1)return u[0];D(this,"type",r,n,{issues:Tr(u)})}return r}}}function W(){return{kind:"schema",type:"unknown",reference:W,expects:"unknown",async:!1,get"~standard"(){return q(this)},"~run"(e){return e.typed=!0,e}}}function Nt(e,t,r){return{kind:"schema",type:"variant",reference:Nt,expects:"Object",async:!1,key:e,options:t,message:r,get"~standard"(){return q(this)},"~run"(n,o){let s=n.value;if(s&&typeof s=="object"){let u,d=0,p=this.key,g=[],m=i((x,P)=>{for(let _ of x.options){if(_.type==="variant")m(_,new Set(P).add(_.key));else{let N=!0,M=0;for(let v of P){let I=_.entries[v];if(v in s?I["~run"]({typed:!1,value:s[v]},{abortEarly:!0}).issues:I.type!=="exact_optional"&&I.type!=="optional"&&I.type!=="nullish"){N=!1,p!==v&&(d<M||d===M&&v in s&&!(p in s))&&(d=M,p=v,g=[]),p===v&&g.push(_.entries[v].expects);break}M++}if(N){let v=_["~run"]({value:s},o);(!u||!u.typed&&v.typed)&&(u=v)}}if(u&&!u.issues)break}},"parseOptions");if(m(this,new Set([this.key])),u)return u;D(this,"type",n,o,{input:s[p],expected:Pt(g,"|"),path:[{type:"object",origin:"value",input:s,key:p,value:s[p]}]})}else D(this,"type",n,o);return n}}}function fe(e,t,r){let n=e["~run"]({value:t},Ct(r));if(n.issues)throw new et(n.issues);return n.value}function f(...e){return{...e[0],pipe:e,get"~standard"(){return q(this)},"~run"(t,r){for(let n of e)if(n.kind!=="metadata"){if(t.issues&&(n.kind==="schema"||n.kind==="transformation")){t.typed=!1;break}(!t.issues||!r.abortEarly&&!r.abortPipeEarly)&&(t=n["~run"](t,r))}return t}}}function X(e,t,r){let n=e["~run"]({value:t},Ct(r));return{typed:n.typed,success:!n.issues,output:n.value,issues:n.issues}}var It,Bo,$o,jo,et,Ho,pu,Wo,z=c(()=>{i(Ct,"getGlobalConfig");i(qo,"getGlobalMessage");i(Vo,"getSchemaMessage");i(Go,"getSpecificMessage");i(we,"_stringify");i(D,"_addIssue");i(q,"_getStandardProps");i(Ir,"_isValidObjectKey");i(Pt,"_joinExpects");i(Cr,"isValiError");et=class extends Error{static{i(this,"ValiError")}constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}},Ho=/^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu,pu=new RegExp("^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}))*)+$","u"),Wo=/^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])[T ](?:0\d|1\d|2[0-3])(?::[0-5]\d){2}(?:\.\d{1,9})?(?:Z| ?[+-](?:0\d|1\d|2[0-3])(?::?[0-5]\d)?)$/u;i(Re,"check");i(ne,"email");i(ae,"integer");i(ue,"isoTimestamp");i(Ae,"length");i(_e,"maxLength");i(pe,"maxValue");i(h,"minLength");i(U,"minValue");i(Fe,"regex");i(Y,"url");i(Pr,"getFallback");i($e,"getDefault");i(de,"any");i(R,"array");i(O,"boolean");i(Dt,"custom");i(Ot,"lazy");i(be,"literal");i(_t,"looseObject");i(Ft,"never");i(V,"nullable");i(ee,"nullish");i(k,"number");i(y,"object");i(l,"optional");i(A,"picklist");i(T,"record");i(a,"string");i(Tr,"_subIssues");i(Te,"union");i(W,"unknown");i(Nt,"variant");i(fe,"parse");i(f,"pipe");i(X,"safeParse")});function Or(e){return X(Yo,e)}var Dr,Ut,zo,Ko,Yo,Xo,gu,yu,_r=c(()=>{"use strict";z();Tt();Dr=y({role:A([Qe.USER,Qe.ASSISTANT,Qe.SYSTEM]),content:f(a(),h(1)),id:l(a()),createdAt:l(a())}),Ut=Ot(()=>y({type:A(["string","number","boolean","array","object"]),description:l(a()),enum:l(R(a())),items:l(Ut),properties:l(T(a(),Ut)),required:l(R(a()))})),zo=y({description:f(a(),h(1)),parameters:y({type:be("object"),properties:T(a(),Ut),required:l(R(a()))})}),Ko=y({id:a(),name:a(),args:T(a(),W())}),Yo=y({messages:f(R(Dr),h(1)),provider:l(A([se.ANTHROPIC,se.OPENAI,se.GOOGLE])),model:l(a()),maxTokens:l(f(k(),ae(),U(1))),temperature:l(f(k(),U(0),pe(2))),systemPrompt:l(a()),stream:l(O()),tools:l(T(a(),zo))}),Xo=y({promptTokens:k(),completionTokens:k(),totalTokens:k()}),gu=y({message:Dr,usage:l(Xo),finishReason:l(a()),toolCalls:l(R(Ko))}),yu=y({provider:A([se.ANTHROPIC,se.OPENAI,se.GOOGLE]),model:l(a()),maxTokens:l(f(k(),ae(),U(1))),temperature:l(f(k(),U(0),pe(2))),systemPrompt:l(a())});i(Or,"validateAIChatRequest")});var Fr=c(()=>{"use strict"});var Nr=c(()=>{"use strict";Tt();_r();Fr()});var Ee,tt,Ur,Mr,Mt=c(()=>{"use strict";Ee={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"},tt={FREE:"free",PRO:"pro",PREMIUM:"premium"},Ur={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"},Mr={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"}});var ie,Lt,Ru,Bt=c(()=>{"use strict";ie={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"},Lt={PAYMENT:"payment",SUBSCRIPTION:"subscription"},Ru={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}});function Lr(e){return fe(es,e)}var Cu,Pu,Du,Ou,_u,Fu,Zo,Jo,Qo,Nu,Uu,es,Br=c(()=>{"use strict";z();Bt();Cu=f(y({userId:l(a()),productId:l(a()),priceId:l(a()),unitAmount:l(f(k(),ae(),U(1))),productName:l(f(a(),h(1))),currency:l(f(a(),Ae(3,"Currency must be 3-letter ISO code"))),successUrl:f(a(),Y()),cancelUrl:f(a(),Y()),customerEmail:l(f(a(),ne())),userEmail:l(f(a(),ne())),metadata:l(T(a(),a())),allowPromotionCodes:l(O()),mode:l(A([Lt.PAYMENT,Lt.SUBSCRIPTION]))}),Re(e=>!!(e.priceId||e.unitAmount&&e.productName),"Either priceId or (unitAmount + productName) is required")),Pu=y({sessionId:a(),sessionUrl:V(f(a(),Y()))}),Du=y({userId:a(),tier:a(),status:A(Object.values(ie)),subscriptionId:V(a()),customerId:a(),subscriptionEnd:V(f(a(),ue())),cancelAtPeriodEnd:O(),updatedAt:f(a(),ue())}),Ou=y({tier:a(),subscriptionId:V(a()),customerId:a(),status:A(Object.values(ie)),subscriptionEnd:V(f(a(),ue())),cancelAtPeriodEnd:O(),updatedAt:f(a(),ue()),isDefault:l(O())}),_u=y({id:a(),type:a(),data:y({object:de()}),created:f(a(),ue())}),Fu=_t({userId:l(a()),firebaseUid:l(a()),productType:l(a())}),Zo=y({type:be("StripePayment"),name:f(a(),h(1,"Product name is required")),description:l(a()),price:a(),currency:l(f(a(),Ae(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:l(f(a(),h(1,"Stripe price ID is required"))),unitAmount:l(f(k(),ae(),U(1))),productName:l(f(a(),h(1))),maxUnitAmount:l(f(k(),ae(),U(1))),tier:f(a(),h(1,"Tier is required")),duration:f(a(),h(1,"Duration is required")),allowPromotionCodes:l(O()),metadata:l(T(a(),a()))}),Jo=y({type:be("StripeSubscription"),name:f(a(),h(1,"Product name is required")),description:l(a()),price:a(),currency:l(f(a(),Ae(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:f(a(),h(1,"Stripe price ID is required")),tier:f(a(),h(1,"Tier is required")),duration:A(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:l(O()),metadata:l(T(a(),a()))}),Qo=Nt("type",[Zo,Jo]),Nu=T(a(),Qo),Uu=T(a(),y({name:a(),price:a(),currency:a(),description:l(a()),features:l(R(a())),priceId:l(a()),unitAmount:l(k()),productName:l(a()),allowPromotionCodes:l(O())})),es=T(a(),y({type:A(["StripePayment","StripeSubscription"]),name:a(),price:k(),currency:a(),priceId:l(a()),unitAmount:l(f(k(),ae(),U(1))),productName:l(f(a(),h(1))),maxUnitAmount:l(f(k(),ae(),U(1))),tier:a(),duration:a(),description:l(a()),metadata:l(T(a(),a())),allowPromotionCodes:l(O())}));i(Lr,"validateStripeBackConfig")});var qr=c(()=>{"use strict"});var qt=c(()=>{"use strict";Bt();Br();qr()});var Hu,ts,Wu,$r=c(()=>{"use strict";z();Mt();qt();Hu=y({id:a(),email:l(V(f(a(),ne()))),displayName:l(V(a())),photoURL:l(V(f(a(),Y()))),emailVerified:l(O()),lastLoginAt:l(a()),providerData:l(R(y({providerId:a(),uid:a(),email:l(V(f(a(),ne()))),displayName:l(V(a())),photoURL:l(V(f(a(),Y()))),phoneNumber:l(V(a()))}))),role:l(A(Object.values(Ee))),customClaims:l(T(a(),de()))}),ts=y({userId:a(),tier:A(Object.values(tt)),status:A(Object.values(ie)),isActive:l(O()),features:l(R(a())),subscriptionId:V(a()),customerId:a(),subscriptionEnd:V(f(a(),ue())),cancelAtPeriodEnd:O(),updatedAt:f(a(),ue())}),Wu=y({role:l(A(Object.values(Ee))),subscription:l(ts),features:l(R(A(Object.values(Ur)))),permissions:l(R(A(Object.values(Mr)))),githubAccess:l(y({username:l(a()),teamAccess:l(R(a())),repoAccess:l(R(a()))}))})});var Vr=c(()=>{"use strict"});var jr=c(()=>{"use strict"});var Gr=c(()=>{"use strict";Mt();$r();Vr();jr()});var Hr=c(()=>{"use strict"});var Wr=c(()=>{"use strict"});var Ie,rt=c(()=>{"use strict";Ie={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"}});var oc,zr=c(()=>{"use strict";rt();oc={EQ:Ie.EQ,NEQ:Ie.NEQ,LT:Ie.LT,LTE:Ie.LTE,GT:Ie.GT,GTE:Ie.GTE}});var Kr=c(()=>{"use strict"});var Yr=c(()=>{"use strict"});var nt,Xr=c(()=>{"use strict";nt=class extends Error{static{i(this,"BulkCollisionError")}collidingIds;where;constructor(t,r){super(`BulkCollisionError: ${t.length} id(s) appear in both "${r.replace("-",'" and "')}" \u2014 ${t.join(", ")}`),this.name="BulkCollisionError",this.collidingIds=t,this.where=r}}});var fc,mc,gc,yc,hc,Zr=c(()=>{"use strict";z();rt();fc=y({collection:f(a(),h(1,"Collection name is required")),data:T(a(),W()),idempotencyKey:l(a())}),mc=y({collection:f(a(),h(1,"Collection name is required")),id:f(a(),h(1,"Entity ID is required"))}),gc=y({collection:f(a(),h(1,"Collection name is required")),id:f(a(),h(1,"Entity ID is required")),data:T(a(),W()),merge:l(O(),!1)}),yc=y({collection:f(a(),h(1,"Collection name is required")),id:f(a(),h(1,"Entity ID is required"))}),hc=y({collection:f(a(),h(1,"Collection name is required")),limit:l(f(k(),U(1),pe(1e3)),1e3),offset:l(f(k(),U(0)),0),orderBy:l(a()),orderDirection:l(A(["asc","desc"]),"desc"),where:l(R(y({field:a(),operator:A(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:W()})))})});var Jr=c(()=>{"use strict"});var Qr=c(()=>{"use strict";Wr();zr();Kr();rt();Yr();Xr();Zr();Jr()});var en=c(()=>{"use strict"});function tn(e){return X(ns,e)}var ns,Cc,rn=c(()=>{"use strict";z();ns=y({templateId:f(a(),h(1)),to:f(a(),ne()),data:T(a(),W()),locale:l(f(a(),h(2),_e(5)),"fr"),from:l(a()),replyTo:l(a())}),Cc=y({success:O(),messageId:l(a()),error:l(a())});i(tn,"validateSendEmailRequest")});var nn=c(()=>{"use strict"});var on=c(()=>{"use strict";en();rn();nn()});var Ve,it,$t,w,sn=c(()=>{"use strict";Ve={ALREADY_EXISTS:"already-exists",CANCELLED:"cancelled",DEADLINE_EXCEEDED:"deadline-exceeded",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",INTERNAL:"internal",INVALID_ARGUMENT:"invalid-argument",NOT_FOUND:"not-found",PERMISSION_DENIED:"permission-denied",RATE_LIMIT_EXCEEDED:"rate-limit-exceeded",TIMEOUT:"timeout",UNAUTHENTICATED:"unauthenticated",UNAVAILABLE:"unavailable",UNIMPLEMENTED:"unimplemented",UNKNOWN:"unknown",VALIDATION_FAILED:"validation-failed"},it={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},$t={[Ve.PERMISSION_DENIED]:{type:it.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[Ve.NOT_FOUND]:{type:it.NOT_FOUND,message:"The requested resource was not found"},[Ve.ALREADY_EXISTS]:{type:it.ALREADY_EXISTS,message:"The resource already exists"},[Ve.INVALID_ARGUMENT]:{type:it.VALIDATION_ERROR,message:"Invalid argument provided"}},w=class e extends Error{static{i(this,"DoNotDevError")}code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,r=Ve.INTERNAL,n){super(t),Object.setPrototypeOf(this,e.prototype),this.code=r,this.details=n?.details,this.source=n?.source,this.originalError=n?.originalError,this.context=n?.context,this.displayable=n?.displayable??!0,this.userMessageProvided=n?.userMessageProvided,this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toString(){return`${this.name} [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,source:this.source,originalError:this.originalError,context:this.context,displayable:this.displayable,userMessageProvided:this.userMessageProvided}}}});var an=c(()=>{"use strict";sn()});var un=c(()=>{"use strict"});var cn=c(()=>{"use strict"});var ln=c(()=>{"use strict"});var pn=c(()=>{"use strict"});var dn=c(()=>{"use strict"});var fn=c(()=>{"use strict"});var mn=c(()=>{"use strict";cn();ln();pn();dn();fn()});var gn=c(()=>{"use strict"});var yn=c(()=>{"use strict";gn()});var hn=c(()=>{"use strict"});var vn=c(()=>{"use strict";hn()});var bn=c(()=>{"use strict"});var En=c(()=>{"use strict";bn()});var Sn=c(()=>{"use strict"});var xn=c(()=>{"use strict";Sn()});var kn=c(()=>{"use strict"});var wn=c(()=>{"use strict"});var Rn=c(()=>{"use strict";wn()});var An=c(()=>{"use strict"});var Tn=c(()=>{"use strict";kn();Rn();An()});var In=c(()=>{"use strict"});var Cn=c(()=>{"use strict";In()});var Pn,Vt=c(()=>{"use strict";Pn=["pull","push","admin","maintain","triage"]});var Dn=c(()=>{"use strict"});var jt,is,yl,hl,vl,bl,El,Sl,xl,On=c(()=>{"use strict";z();Vt();jt=y({owner:f(a(),h(1,"Repository owner is required")),repo:f(a(),h(1,"Repository name is required"))}),is=A([...Pn]),yl=y({userId:f(a(),h(1,"User ID is required")),githubUsername:f(a(),h(1,"GitHub username is required")),repoConfig:jt,permission:l(is,"push"),customClaims:l(T(a(),de()))}),hl=y({userId:f(a(),h(1,"User ID is required")),githubUsername:f(a(),h(1,"GitHub username is required")),repoConfig:jt}),vl=y({userId:f(a(),h(1,"User ID is required")),githubUsername:f(a(),h(1,"GitHub username is required")),repoConfig:jt}),bl=y({provider:a(),purpose:A(["authentication","api-access"]),code:f(a(),h(1,"Authorization code is required")),redirectUri:f(a(),Y("Valid redirect URI is required")),codeVerifier:l(a()),state:l(a()),instance:l(f(a(),Y()))}),El=y({provider:a(),refreshToken:f(a(),h(1,"Refresh token is required")),redirectUri:f(a(),Y("Valid redirect URI is required"))}),Sl=y({provider:a()}),xl=y({userId:f(a(),h(1,"User ID is required"))})});var _n=c(()=>{"use strict";Vt();Dn();On()});var Fn=c(()=>{"use strict"});var Nn,os,ot,ss,as,us,cs,Cl,Pl,Un=c(()=>{"use strict";z();Nn=y({name:a(),color:a(),icon:a(),customParameters:l(T(a(),a())),button:y({backgroundColor:a(),textColor:a(),borderColor:a(),hoverBackgroundColor:a(),focusOutlineColor:a(),fontWeight:l(a(),"500"),textKey:l(a())})}),os=y({...Nn.entries,type:A(["auth","both"]),scopes:l(R(a())),firebaseProviderId:l(a())}),ot=Te([be(""),f(a(),Y())]),ss=y({authUrl:ot,tokenUrl:ot,profileUrl:ot,revokeUrl:l(ot)}),as=y({authentication:l(R(a())),"api-access":R(a())}),us=l(y({pkce:l(O(),!1),codeChallengeMethod:l(A(["S256","plain"]),"S256")})),cs=y({...Nn.entries,type:A(["oauth","both"]),scopes:as,endpoints:ss,capabilities:us}),Cl=T(a(),os),Pl=T(a(),cs)});var Mn=c(()=>{"use strict"});var Ln=c(()=>{"use strict";Fn();Un();Mn()});var Bn=c(()=>{"use strict"});var qn=c(()=>{"use strict"});var $n=c(()=>{"use strict";Bn();qn()});var Vn=c(()=>{"use strict"});var jn=c(()=>{"use strict";Vn()});var Gn=c(()=>{"use strict"});var Hn=c(()=>{"use strict";Gn()});var Wn,$l,zn=c(()=>{"use strict";Wn={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},$l={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:Wn.ANALYTICS},marketing:{requiresConsent:Wn.MARKETING}}});var Kn=c(()=>{"use strict"});var Yn=c(()=>{"use strict";zn();Kn()});var Xn=c(()=>{"use strict"});var Zn=c(()=>{"use strict"});var Jn=c(()=>{"use strict";Xn();Zn()});var me=c(()=>{"use strict";Nr();Gr();qt();Hr();Qr();on();an();un();mn();yn();vn();En();xn();Tn();Cn();_n();Ln();$n();jn();Hn();Yn();Jn()});var je=c(()=>{"use strict";me()});function Qn(e){return e instanceof Error&&"source"in e&&typeof e.source=="string"?e.source:typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("auth/")?"auth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("oauth/")?"oauth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&["permission-denied","unavailable","not-found","already-exists","unauthenticated","invalid-argument","failed-precondition","resource-exhausted"].includes(e.code)?"firebase":typeof e=="object"&&e!==null&&"issues"in e&&Array.isArray(e.issues)&&"name"in e&&e.name==="ValiError"?"validation":e instanceof Error&&e.name==="EntityHookError"?"entity":typeof e=="object"&&e!==null&&("response"in e||"status"in e||"statusText"in e)?"api":typeof e=="object"&&e!==null&&"componentStack"in e?"ui":"unknown"}var Gt=c(()=>{"use strict";i(Qn,"detectErrorSource")});function ge(e){return(t,r)=>{if(t instanceof w)return t;if(typeof t!="object"||t===null){let d=typeof t=="string"?t:e.defaultErrorMessage;return new w(r||d,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let n;e.extractErrorCode?n=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(n=t.code);let o=e.defaultErrorCode;n&&e.errorCodeMapping&&n in e.errorCodeMapping&&(o=e.errorCodeMapping[n]);let s;e.extractErrorMessage?s=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(s=t.message),n&&e.friendlyMessageMapping&&n in e.friendlyMessageMapping&&(s=e.friendlyMessageMapping[n]),s||(s=e.defaultErrorMessage);let u;return e.processMetadata?u=e.processMetadata(t):(u={originalError:t},n&&(u.originalCode=n)),"originalError"in u||(u.originalError=t),new w(r||s,o,{details:u,source:e.errorSource})}}var st,Ht=c(()=>{"use strict";je();i(ge,"createErrorHandler");st={"permission-denied":"permission-denied",unavailable:"unavailable","not-found":"not-found","already-exists":"already-exists",unauthenticated:"unauthenticated","invalid-argument":"invalid-argument","failed-precondition":"invalid-argument","resource-exhausted":"rate-limit-exceeded","deadline-exceeded":"timeout",cancelled:"cancelled","not-implemented":"unimplemented"}});function at(e,t,r){return e instanceof w?e:(ei[t]||ei.unknown)(e,r)}var Ne,ls,Wt,Se,ps,ds,ei,zt=c(()=>{"use strict";z();me();je();Ht();Ne={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",DELETE_ACCOUNT_REQUIRES_SERVER:"Account deletion requires a server endpoint. Configure a callable provider or deploy a delete-account Edge Function.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},ls={400:"invalid-argument",401:"unauthenticated",403:"permission-denied",404:"not-found",409:"already-exists",422:"validation-failed",429:"rate-limit-exceeded",500:"internal",501:"unimplemented",502:"unavailable",503:"unavailable",504:"timeout"},Wt={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},Se={auth:{errorSource:"auth",defaultErrorCode:"unknown",defaultErrorMessage:"An authentication error occurred",errorCodeMapping:{"auth/user-not-found":"not-found","auth/wrong-password":"invalid-argument","auth/email-already-in-use":"already-exists","auth/weak-password":"validation-failed","auth/invalid-email":"validation-failed","auth/account-exists-with-different-credential":"already-exists","auth/credential-already-in-use":"already-exists","auth/requires-recent-login":"unauthenticated","auth/user-disabled":"permission-denied","auth/too-many-requests":"rate-limit-exceeded","auth/network-request-failed":"unavailable","auth/popup-blocked":"unavailable","auth/popup-closed-by-user":"invalid-argument","auth/cancelled-popup-request":"invalid-argument","auth/operation-not-allowed":"unimplemented","auth/invalid-credential":"invalid-argument","auth/invalid-verification-code":"invalid-argument","auth/captcha-check-failed":"validation-failed","auth/invalid-phone-number":"validation-failed","auth/missing-phone-number":"invalid-argument","auth/quota-exceeded":"rate-limit-exceeded","auth/timeout":"unavailable","auth/web-storage-unsupported":"unavailable","auth/unauthorized-domain":"permission-denied","auth/internal-error":"internal","auth/invalid-action-code":"invalid-argument","auth/invalid-continue-uri":"invalid-argument","auth/missing-continue-uri":"invalid-argument","auth/missing-ios-bundle-id":"invalid-argument","auth/missing-android-pkg-name":"invalid-argument","auth/unauthorized-continue-uri":"permission-denied","auth/invalid-dynamic-link-domain":"invalid-argument","auth/invalid-tenant-id":"invalid-argument","auth/tenant-id-mismatch":"invalid-argument","auth/provider-already-linked":"already-exists","auth/invalid-persistence-type":"invalid-argument","auth/unsupported-persistence-type":"unimplemented","auth/invalid-provider":"invalid-argument","auth/invalid-client-id":"invalid-argument","oauth/unauthorized-app":"permission-denied","auth/provider-not-enabled":"unimplemented","auth/unknown-provider":"invalid-argument","auth/missing-provider":"invalid-argument","auth/no-user-signed-in":"unauthenticated",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",...st},friendlyMessageMapping:{"auth/user-not-found":"No account found with this email address.","auth/wrong-password":"Incorrect password. Please try again.","auth/email-already-in-use":"An account with this email already exists.","auth/weak-password":"Password is too weak. It should be at least 6 characters.","auth/invalid-email":"Please enter a valid email address.","auth/account-exists-with-different-credential":"An account already exists with the same email but different sign-in method.","auth/credential-already-in-use":"This credential is already associated with a different user account.","auth/requires-recent-login":"This operation requires you to sign in again for security reasons.","auth/user-disabled":"This account has been disabled.","auth/too-many-requests":"Too many sign-in attempts. Please try again later.","auth/network-request-failed":"Network connection error. Please check your internet connection.","auth/popup-blocked":"Sign-in popup was blocked. Please allow popups for this site.","auth/popup-closed-by-user":"Sign-in popup was closed before completion.","auth/operation-not-allowed":"This sign-in method is not enabled for this project.","auth/internal-error":"An internal authentication error occurred. Please try again.","auth/invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","auth/invalid-continue-uri":"The continue URL provided is invalid.","auth/missing-continue-uri":"A continue URL must be provided in the request.","auth/missing-ios-bundle-id":"An iOS Bundle ID must be provided in the request.","auth/missing-android-pkg-name":"An Android package name must be provided in the request.","auth/unauthorized-continue-uri":"The domain of the continue URL is not allowlisted.","auth/invalid-dynamic-link-domain":"The provided dynamic link domain is not authorized.","auth/invalid-tenant-id":"The provided tenant ID is invalid.","auth/tenant-id-mismatch":"The tenant ID of the provider does not match the tenant ID of the current user.","auth/provider-already-linked":"This authentication provider is already linked to the account.","auth/invalid-persistence-type":"The specified persistence type is invalid.","auth/unsupported-persistence-type":"The current environment does not support the specified persistence type.","auth/invalid-provider":"The specified authentication provider is invalid.","auth/invalid-client-id":"The authentication client ID provided is invalid.","oauth/unauthorized-app":"This application is not authorized to use OAuth with the provided client ID.","auth/provider-not-enabled":"This authentication provider is not enabled.","auth/unknown-provider":"Unknown authentication provider.","auth/missing-provider":"No authentication provider specified in the request.","auth/no-user-signed-in":"No user is currently signed in."}},oauth:{errorSource:"oauth",defaultErrorCode:"unknown",defaultErrorMessage:"An OAuth error occurred",errorCodeMapping:{"oauth/invalid-request":"invalid-argument","oauth/invalid-client":"invalid-argument","oauth/invalid-grant":"invalid-argument","oauth/unauthorized-client":"permission-denied","oauth/unsupported-grant-type":"unimplemented","oauth/invalid-scope":"invalid-argument","oauth/insufficient-scope":"permission-denied","oauth/invalid-token":"unauthenticated","oauth/expired-token":"unauthenticated","oauth/redirect-uri-mismatch":"invalid-argument","oauth/access-denied":"permission-denied","oauth/server-error":"unavailable","oauth/temporarily-unavailable":"unavailable","oauth/state-mismatch":"invalid-argument","oauth/invalid-callback":"invalid-argument","oauth/client-secret-mismatch":"permission-denied","oauth/unauthorized-scope":"permission-denied","oauth/rate-limit-exceeded":"rate-limit-exceeded","oauth/token-expired":"unauthenticated","oauth/missing-token":"invalid-argument","oauth/invalid-code":"invalid-argument","oauth/invalid-redirect":"invalid-argument","oauth/provider-error":"unavailable","oauth/invalid-response":"unavailable","oauth/unauthorized-access":"permission-denied",...st},friendlyMessageMapping:{"oauth/invalid-request":"The OAuth request was invalid or missing parameters.","oauth/invalid-client":"Client authentication failed.","oauth/invalid-grant":"The provided authorization grant is invalid.","oauth/unauthorized-client":"The client is not authorized to use this grant type.","oauth/unsupported-grant-type":"The requested grant type is not supported.","oauth/invalid-scope":"The requested scope is invalid or unknown.","oauth/insufficient-scope":"The token does not have the required scope for this resource.","oauth/invalid-token":"The access token is invalid.","oauth/expired-token":"The access token has expired.","oauth/redirect-uri-mismatch":"The redirect URI does not match the registered URI.","oauth/access-denied":"The resource owner denied the request.","oauth/server-error":"The authorization server encountered an unexpected error.","oauth/temporarily-unavailable":"The authorization server is temporarily unavailable.","oauth/state-mismatch":"Invalid state parameter. This could be a security issue.","oauth/invalid-callback":"The callback URL is invalid or not registered.","oauth/client-secret-mismatch":"The client secret does not match the registered secret.","oauth/unauthorized-scope":"The requested scope is not authorized for this client.","oauth/rate-limit-exceeded":"Too many requests. Please try again later.","oauth/token-expired":"The OAuth token has expired and needs to be refreshed.","oauth/missing-token":"No OAuth token was provided in the request.","oauth/invalid-code":"The authorization code is invalid or expired.","oauth/invalid-redirect":"The redirect URL is invalid or does not match the registered redirect URL.","oauth/provider-error":"The OAuth provider returned an error.","oauth/invalid-response":"The response from the OAuth provider was invalid.","oauth/unauthorized-access":"Unauthorized access to OAuth resources."}},api:{errorSource:"api",defaultErrorCode:"unknown",defaultErrorMessage:"API request failed",errorCodeMapping:Object.fromEntries(Object.entries(ls).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode:i(e=>{if(typeof e!="object"||e===null)return;let t;return"response"in e&&e.response&&"status"in e.response?t=e.response.status:"status"in e&&typeof e.status=="number"&&(t=e.status),t?.toString()},"extractErrorCode"),processMetadata:i(e=>{let t={originalError:e};return typeof e!="object"||e===null||("response"in e&&e.response?("status"in e.response&&(t.statusCode=e.response.status),"data"in e.response&&(t.responseData=e.response.data)):"status"in e&&(t.statusCode=e.status)),t},"processMetadata")},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:st,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:Ne.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:i(e=>{let t={originalError:e};return typeof e=="object"&&e!==null&&"componentStack"in e&&(t.componentStack=e.componentStack),t},"processMetadata")},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:Ne["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:Ne.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:i(e=>{if(e instanceof Error)return e.name},"extractErrorCode")}},ps=i(e=>e instanceof et?new w(Ne["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):ge(Se.validation)(e),"handleValidationError"),ds=i(e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&e.type in Wt){let t=e,r=Wt[t.type]||"unknown";return new w(t.message||Ne[r],r,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&$t[e.code]){let t=e,r=$t[t.code];if(r){let n=Wt[r.type]||"unknown";return new w(r.message||Ne[n],n,{details:{originalCode:t.code,originalError:e},source:"entity"})}}return ge(Se.entity)(e)},"handleEntityError"),ei={auth:ge(Se.auth),oauth:ge(Se.oauth),api:ge(Se.api),firebase:ge(Se.firebase),ui:ge(Se.ui),validation:ps,entity:ds,unknown:ge(Se.unknown)};i(at,"mapToDoNotDevError")});function ti(e,t,r={}){let n=globalThis.Sentry;n&&n.withScope(o=>{o.setTag("errorSource",t),o.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([s,u])=>{if(typeof u!="function"&&s!=="originalError")try{o.setExtra(s,u)}catch{o.setExtra(s,`[${typeof u}]`)}}),Object.entries(r).forEach(([s,u])=>{if(typeof u!="function")try{o.setExtra(`context.${s}`,u)}catch{o.setExtra(`context.${s}`,`[${typeof u}]`)}}),(e.details?.userId||r.userId)&&o.setUser({id:e.details?.userId||r.userId,email:e.details?.userEmail||r.userEmail}),n.captureException(e)})}var Kt=c(()=>{"use strict";i(ti,"captureErrorToSentry")});function fs(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof process<"u"&&process.env?"production".toLowerCase()!=="production":!1}function S(e,t){let r=typeof t=="string"?{userMessage:t}:t||{},{userMessage:n,context:o={},log:s=!0,reportToSentry:u=!0,showNotification:d=!1,severity:p="error"}=r,g=Qn(e),m=e instanceof w?e:at(e,g,n);if(n&&!m.userMessageProvided&&(m.message.includes("Error")||m.message.includes("Failed")||m.message.length<10?m=new w(n,m.code,{details:{...m.details,originalMessage:m.message},source:g,userMessageProvided:!0}):m=new w(m.message,m.code,{details:{...m.details,userMessage:n},source:g,userMessageProvided:!0})),s){let x=fs()||typeof window<"u"&&window.__DNDEV_DEBUG,P={code:m.code,message:m.message,source:g};switch(p){case"warning":console.warn(`[DoNotDev] ${m.code}: ${m.message}`,x?{...P,details:m.details}:P);break;case"info":console.info(`[DoNotDev] ${m.code}: ${m.message}`,x?{...P,details:m.details}:P);break;case"success":console.log(`[DoNotDev] ${m.code}: ${m.message}`,x?{...P,details:m.details}:P);break;default:console.error(`[DoNotDev] ${m.code}: ${m.message}`,x?{...P,details:m.details,stack:m.stack}:P)}}return u&&ti(m,g,o),d&&typeof window<"u"&&console.warn("[handleError] showNotification requires client-side toast setup"),m}var ri=c(()=>{"use strict";je();Gt();zt();Kt();i(fs,"isDev");i(S,"handleError")});var ut=c(()=>{"use strict";je();ri();Gt();zt();Kt();Ht()});function ct(e,t,r,n){let o=n?` ${JSON.stringify(n)}`:"",s=`${t}.${r}(${o})`,u=at(e,"auth",`${s}: ${ms(e)}`);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&u.code==="unknown"&&e.code!=="unknown"?new w(u.message,u.code,{details:{...u.details,originalCode:e.code},source:u.source}):u}function ms(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}var ni=c(()=>{"use strict";ut();i(ct,"wrapAuthError");i(ms,"getErrorMessage")});var ii=c(()=>{"use strict";ut()});var oi=c(()=>{"use strict";ni();ii()});var si=c(()=>{"use strict"});var ai=c(()=>{"use strict"});var ui=c(()=>{"use strict"});var ci=c(()=>{"use strict"});var li=c(()=>{"use strict"});var pi=c(()=>{"use strict"});var di=c(()=>{"use strict"});var fi=c(()=>{"use strict"});var mi=c(()=>{"use strict"});function Ge(e,t){if(!e)return!1;let r=gi[e]??-1,n=gi[t]??1/0;return r>=n}var gi,Yt=c(()=>{"use strict";me();gi={[Ee.GUEST]:0,[Ee.USER]:1,[Ee.ADMIN]:2,[Ee.SUPER]:3};i(Ge,"hasRoleAccess")});var yi=c(()=>{"use strict";me()});function gs(){if(typeof globalThis<"u"){let e=globalThis;return e[Xt]||(e[Xt]=new Map),e[Xt]}return new Map}function hi(e,t){let r=gs();return r.has(e)||r.set(e,t()),r.get(e)}function vi(e,...t){let r=null,n=!1;return i(function(){if(r!==null)return r;if(n)throw new Error("Circular dependency detected in singleton initialization");n=!0;try{return typeof e=="function"&&e.prototype?r=new e(...t):r=e(),r}finally{n=!1}},"getInstance")}var Xt,Zt=c(()=>{"use strict";Xt="__DNDEV_SINGLETONS__";i(gs,"getSingletonRegistry");i(hi,"getGlobalSingleton");i(vi,"createSingleton")});function bi(){return hi("providers",()=>({providers:null}))}function Jt(e){let{providers:t}=bi();if(!t)throw new Error(`[dndev] Provider "${e}" not available. Call configureProviders() at app startup.`);let r=t[e];if(!r)throw new Error(`[dndev] Provider "${e}" not configured. Pass it to configureProviders().`);return r}function Qt(e){return!!bi().providers?.[e]}var Ei=c(()=>{"use strict";Zt();i(bi,"getProviderState");i(Jt,"getProvider");i(Qt,"hasProvider")});var Si=c(()=>{"use strict"});var er=c(()=>{"use strict";Yt()});var xi=c(()=>{"use strict";er()});var ki=c(()=>{"use strict"});var wi=c(()=>{"use strict"});var Ri=c(()=>{"use strict";xi();ki();er();wi()});var Ai=c(()=>{"use strict"});var Ti=c(()=>{"use strict";Ai()});var Ii=c(()=>{"use strict"});var Ci=c(()=>{"use strict"});var Pi=c(()=>{"use strict"});var Di=c(()=>{"use strict"});var Oi=c(()=>{"use strict";oi();si();ai();ui();ci();ut();li();pi();di();fi();mi();Yt();yi();Ei();Zt();Si();Ri();Ti();Ii();Ci();Pi();Di()});var _i=c(()=>{"use strict"});var Fi=c(()=>{"use strict"});var Ni=c(()=>{"use strict"});var xe=c(()=>{Oi();_i();Fi();Ni()});var Ui=c(()=>{"use strict"});var Mi=c(()=>{"use strict"});function b(e,t){hs.set(e,t)}function F(e,t){return t?e:ee(e)}function Fs(){b("text",lt),b("textarea",lt),b("richtext",lt),b("color",lt),b("email",vs),b("password",bs),b("url",Es),b("tel",Cs),b("iban",Ps),b("number",Ue),b("currency",Ue),b("price",_s),b("range",Ue),b("year",Ue),b("rating",Ue),b("duration",Ue),b("boolean",Li),b("checkbox",Li),b("gdprConsent",Os),b("date",Me),b("datetime-local",Me),b("time",Me),b("week",Me),b("month",Me),b("timestamp",Me),b("file",Bi),b("files",qi),b("document",Bi),b("documents",qi),b("image",Ss),b("images",xs),b("geopoint",ks),b("address",ws),b("map",Rs),b("array",As),b("select",tr),b("multiselect",Ts),b("radio",tr),b("combobox",tr),b("switch",Ds),b("reference",Is),b("hidden",rr),b("avatar",rr),b("badge",rr),b("submit",$i),b("reset",$i)}var hs,lt,vs,bs,Es,Ue,Li,Me,Vi,Bi,qi,ji,Ss,xs,ks,ws,Rs,As,tr,Ts,Is,rr,Cs,Ps,$i,Ds,Os,_s,nr=c(()=>{"use strict";z();hs=new Map;i(b,"registerSchemaGenerator");i(F,"applyRequired");lt=i(e=>{let t=[];e.validation?.minLength!==void 0&&t.push(h(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(_e(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(Fe(new RegExp(e.validation.pattern),"Invalid format"));let r=t.length>0?f(a(),...t):a();return F(r,e.validation?.required)},"textSchema"),vs=i(e=>{let t=f(a(),ne("Invalid email address"));return F(t,e.validation?.required)},"emailSchema"),bs=i(e=>{let t=e.validation?.minLength!==void 0?f(a(),h(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):a();return F(t,e.validation?.required)},"passwordSchema"),Es=i(e=>{let t=f(a(),Y("Invalid URL"));return F(t,e.validation?.required)},"urlSchema"),Ue=i(e=>{let t=[];e.validation?.min!==void 0&&t.push(U(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(pe(e.validation.max,`Must be at most ${e.validation.max}`));let r=t.length>0?f(k(),...t):k();return F(r,e.validation?.required)},"numberSchema"),Li=i(e=>{let t=O();return F(t,e.validation?.required)},"booleanSchema"),Me=i(e=>{let t=f(a(),Re(r=>!isNaN(new Date(r).getTime()),"Invalid date format"));return F(t,e.validation?.required)},"dateSchema"),Vi=y({url:a(),filename:a(),size:k(),mimeType:ee(a()),uploadedAt:ee(a())}),Bi=i(e=>{let t=V(Vi);return F(t,e.validation?.required)},"fileSchema"),qi=i(e=>{let t=R(Vi);return F(t,e.validation?.required)},"filesSchema"),ji=y({fullUrl:a(),thumbUrl:a()}),Ss=i(e=>{let t=Te([a(),ji]);return F(t,e.validation?.required)},"pictureSchema"),xs=i(e=>{let t=R(Te([a(),ji]));return F(t,e.validation?.required)},"picturesSchema"),ks=i(e=>{let t=y({lat:k(),lng:k()});return F(t,e.validation?.required)},"geopointSchema"),ws=i(e=>{let t=y({formatted_address:a(),latitude:k(),longitude:k(),street_number:ee(a()),route:ee(a()),locality:ee(a()),administrative_area_level_1:ee(a()),administrative_area_level_2:ee(a()),country:ee(a()),postal_code:ee(a())});return F(t,e.validation?.required)},"addressSchema"),Rs=i(e=>{let t=T(a(),W());return F(t,e.validation?.required)},"mapSchema"),As=i(e=>{let t=R(W());return F(t,e.validation?.required)},"arraySchema"),tr=i(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let n=t.map(s=>s.value),o=A(n);return F(o,e.validation?.required)}let r=Te([a(),k()]);return F(r,e.validation?.required)},"selectSchema"),Ts=i(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let n=t.map(s=>s.value),o=R(A(n));return F(o,e.validation?.required)}let r=R(a());return F(r,e.validation?.required)},"multiselectSchema"),Is=i(e=>{let t=f(a(),h(1,"Invalid ID format"));return F(t,e.validation?.required)},"referenceSchema"),rr=i(e=>{let t=a();return F(t,e.validation?.required)},"stringSchema"),Cs=i(e=>{let t=a();return F(t,e.validation?.required)},"telSchema"),Ps=i(e=>{let t=e.validation?.minLength??15,r=e.validation?.maxLength??34,n=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",o=[];if(t!==void 0&&o.push(h(t,`IBAN must be at least ${t} characters`)),r!==void 0&&o.push(_e(r,`IBAN must not exceed ${r} characters`)),n){let u=typeof n=="string"?new RegExp(n):n;o.push(Fe(u,"Invalid IBAN format"))}let s=o.length>0?f(a(),...o):a();return F(s,e.validation?.required)},"ibanSchema"),$i=i(()=>Ft(),"neverSchema"),Ds=i(e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let n=[t.checkedValue,t.uncheckedValue],o=A(n);return F(o,e.validation?.required)}let r=O();return F(r,e.validation?.required)},"switchSchema"),Os=i(e=>Dt(r=>e.validation?.required?typeof r=="object"&&r!==null?r.gdprConsent===!0:!1:r===!1||r===null||r===void 0?!0:typeof r=="object"&&r!==null?r.gdprConsent===!0:!1,"GDPR consent must be given"),"gdprConsentSchema"),_s=i(e=>{let t=y({amount:k(),currency:l(a()),vatIncluded:l(O()),discountPercent:l(f(k(),U(0),pe(100)))});return F(t,e.validation?.required)},"priceSchema");i(Fs,"registerBuiltinSchemas");Fs()});var ir=c(()=>{"use strict";xe()});var or=c(()=>{"use strict";xe()});var Gi=c(()=>{"use strict";ir();or()});var Hi=c(()=>{"use strict";Mi();nr();ir();Gi();or()});var Wi=c(()=>{"use strict";xe()});var zi,sr,Ki,dm,Yi,pt=c(()=>{"use strict";me();zi=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],sr="available",Ki=["id","createdAt","updatedAt","createdById","updatedById"],dm=[...Ki,"status"],Yi={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...zi]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0}},createdAt:{name:"createdAt",type:"timestamp",visibility:"technical",label:"crud:fields.createdAt",validation:{}},updatedAt:{name:"updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields.updatedAt",validation:{}},createdById:{name:"createdById",type:"reference",visibility:"technical",label:"crud:fields.createdById",validation:{}},updatedById:{name:"updatedById",type:"reference",visibility:"technical",label:"crud:fields.updatedById",validation:{}}}});var Xi=c(()=>{"use strict";me();xe();pt()});var Zi=c(()=>{"use strict";me();xe();nr();pt()});var Ji=c(()=>{"use strict"});var Qi=c(()=>{"use strict"});function ro(e){let t=new Set((e.updates??[]).map(u=>u.id)),r=e.deletes??[],n=[];for(let u of r)t.has(u)&&n.push(u);if(n.length>0)return{collisions:n,where:"updates-deletes"};let o=e.inserts??[],s=[];for(let u of o)typeof u.id=="string"&&t.has(u.id)&&s.push(u.id);return s.length>0?{collisions:s,where:"inserts-updates"}:{collisions:[],where:null}}var Ms,Ls,Bs,eo,to,no=c(()=>{"use strict";z();Ms=T(a(),W()),Ls=y({id:a(),patch:T(a(),W())}),Bs=a(),eo=y({inserts:l(R(Ms)),updates:l(R(Ls)),deletes:l(R(Bs))}),to=y({insertedIds:R(a()),updatedIds:R(a()),deletedIds:R(a())});i(ro,"detectBulkCollisions")});var io=c(()=>{"use strict";no()});var Nm,qs,$s,Um,Mm,oo=c(()=>{"use strict";z();Nm=f(a(),Re(e=>e.startsWith("/proxy/")||e.startsWith("data:image/"),"Image URL must be box-proxied (/proxy/...) or an inline data:image URI.")),qs=A(["ephemeral","session","persistent"]),$s=y({title:l(a()),pinnable:l(O()),preferredHeight:l(f(k(),U(0)))}),Um=y({id:f(a(),h(1)),kind:f(a(),h(1)),lifetime:l(qs,"ephemeral"),metadata:l($s),payload:W()}),Mm=y({widgetId:f(a(),h(1)),action:f(a(),h(1)),payload:W()})});var so=c(()=>{"use strict";Hi();Wi();pt();Xi();Zi();Ji();Qi();io();oo()});var ao=c(()=>{"use strict";Ui();so()});var $=c(()=>{xe();me();ao();xe()});import{initializeApp as lo,getApps as Ks,cert as Ys}from"firebase-admin/app";import{getAuth as Xs}from"firebase-admin/auth";import{getFirestore as Zs}from"firebase-admin/firestore";import{getFunctions as Js}from"firebase-admin/functions";function Qs(){let e=Ks(),t=null;if(e.length===0?process.env.FIREBASE_ADMIN_PRIVATE_KEY&&process.env.FIREBASE_PROJECT_ID&&process.env.FIREBASE_CLIENT_EMAIL?t=lo({credential:Ys({projectId:process.env.FIREBASE_PROJECT_ID,clientEmail:process.env.FIREBASE_CLIENT_EMAIL,privateKey:process.env.FIREBASE_ADMIN_PRIVATE_KEY.replace(/\\n/g,`
|
|
22
|
-
`)}),projectId:process.env.FIREBASE_PROJECT_ID}):t=lo():t=e[0]||null,!t)throw new Error("Failed to initialize Firebase Admin app");return{app:t,auth:Xs(t),firestore:Zs(t),functions:Js(t)}}async function ea(){try{return He()}catch(e){throw S(e,{userMessage:"Failed to initialize Firebase Admin",context:{provider:"FirebaseAdmin",operation:"initFirebaseAdmin"},severity:"error"})}}async function We(){let e=He();if(!e.app)throw new Error("Firebase Admin not initialized");return e.app}function J(){let e=He();if(!e.auth)throw new Error("Firebase Admin auth not initialized");return e.auth}function G(){let e=He();if(!e.firestore)throw new Error("Firebase Admin firestore not initialized");return e.firestore}function ta(){let e=He();if(!e.functions)throw new Error("Firebase Admin functions not initialized");return e.functions}var He,ft=c(()=>{"use strict";$();i(Qs,"initializeFirebaseAdminServices");He=vi(Qs);i(ea,"initFirebaseAdmin");i(We,"getFirebaseAdminApp");i(J,"getFirebaseAdminAuth");i(G,"getFirebaseAdminFirestore");i(ta,"getFirebaseAdminFunctions")});var lr,po=c(()=>{"use strict";$();ft();lr=class{static{i(this,"FirebaseServerAuthAdapter")}async verifyToken(t){try{let r=await J().verifyIdToken(t);return{uid:r.uid,email:r.email,claims:r}}catch(r){throw ct(r,"FirebaseServerAuthAdapter","verifyToken")}}async getUser(t){try{let r=await J().getUser(t);return{uid:r.uid,email:r.email,displayName:r.displayName,customClaims:r.customClaims??{}}}catch(r){if(r.code==="auth/user-not-found")return null;throw ct(r,"FirebaseServerAuthAdapter","getUser",{uid:t})}}async setCustomClaims(t,r){try{let o=(await J().getUser(t)).customClaims??{};await J().setCustomUserClaims(t,{...o,...r})}catch(n){throw ct(n,"FirebaseServerAuthAdapter","setCustomClaims",{uid:t})}}}});var mt,ra,Q,na,ze=c(()=>{"use strict";$();ft();mt={async getServerAdmin(){try{return We()}catch(e){throw S(e,"Error getting Firebase Admin")}},async getServerFirestore(){try{return G()}catch(e){throw S(e,"Error getting Admin Firestore")}},async generateServerId(){return(await mt.getServerFirestore()).collection("_").doc().id}},ra=mt.getServerAdmin,Q=mt.getServerFirestore,na=mt.generateServerId});function pr(e){return{seconds:Math.floor(e.getTime()/1e3),nanoseconds:e.getTime()%1e3*1e6,toDate:i(()=>new Date(e),"toDate"),toMillis:i(()=>e.getTime(),"toMillis"),isEqual:i(t=>t.seconds===Math.floor(e.getTime()/1e3)&&t.nanoseconds===e.getTime()%1e3*1e6,"isEqual"),valueOf:i(()=>`Timestamp(seconds=${Math.floor(e.getTime()/1e3)}, nanoseconds=${e.getTime()%1e3*1e6})`,"valueOf")}}function ia(e){try{if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw S(new Error("Invalid date string format"),{context:{value:e}});return pr(t)}if(e instanceof Date){if(isNaN(e.getTime()))throw S(new Error("Invalid Date object"),{context:{value:e}});return pr(e)}throw S(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw S(t,"Failed to convert to Timestamp")}}function fo(e){try{if(e instanceof Date){if(isNaN(e.getTime()))throw S(new Error("Invalid Date object"),{context:{value:e}});return e.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function")return e.toDate().toISOString();if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw S(new Error("Invalid date string format"),{context:{value:e}});return t.toISOString()}throw S(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw S(t,"Failed to convert to ISO string")}}function mo(e){return typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function"&&"seconds"in e&&"nanoseconds"in e}function oa(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(e))return!1;let r=new Date(e);return!isNaN(r.getTime())}function dr(e){if(!e)return e;if(Array.isArray(e))return e.map(t=>dr(t));if(typeof e=="string"&&oa(e))return new Date(e);if(typeof e=="object"&&e!==null){let t={};for(let[r,n]of Object.entries(e))t[r]=dr(n);return t}return e}function ye(e,t=!1){if(!e)return e;if(t&&typeof e=="object"&&e!==null&&"id"in e&&"ref"in e&&"data"in e&&typeof e.data=="function"){let r=e,n=r.data();return{id:r.id,...ye(n)}}if(Array.isArray(e))return e.map(r=>ye(r));if(mo(e))return fo(e);if(typeof e=="object"&&e!==null){let r={};for(let[n,o]of Object.entries(e))r[n]=ye(o);return r}return e}function Ce(e,t=[]){if(!e)return e;if(Array.isArray(e))return e.map(r=>Ce(r,t));if(e instanceof Date)return e.toISOString();if(typeof e=="object"&&e!==null){let r={};for(let[n,o]of Object.entries(e))t.includes(n)||o!==void 0&&(r[n]=Ce(o,t));return r}return e}function sa(e,t){let r={};for(let[n,o]of Object.entries(t)){if(!(n in e)){r[n]=o;continue}JSON.stringify(e[n])!==JSON.stringify(o)&&(r[n]=o)}return{...r,updatedAt:new Date().toISOString()}}var gt=c(()=>{"use strict";$();i(pr,"createTimestamp");i(ia,"toTimestamp");i(fo,"firestoreToISOString");i(mo,"isTimestamp");i(oa,"isISODateString");i(dr,"convertISOStringsToDates");i(ye,"transformFirestoreData");i(Ce,"prepareForFirestore");i(sa,"createFirestorePartialUpdate")});var Le,ce,Be,aa,ua,ca,la,pa,da,go=c(()=>{"use strict";z();$();ze();gt();Le=typeof window<"u",ce={async batchWrite(e,t,r,n,o={}){if(!t||!t.length)return{successes:0,failures:0};let{idField:s="id",generateIds:u=!0,maxBatchSize:d=450,removeFields:p=[],validate:g=!!n}=o,m={successes:0,failures:0,failedItems:[]};try{let x=[],P=await Q(),_=P.batch(),N=0;for(let v=0;v<t.length;v++){let I=t[v];if(!I){m.failures++,m.failedItems?.push({index:v,error:new Error("Item is null or undefined")});continue}try{if(r==="delete"){if(!I[s])throw S(new Error(`Missing ID for delete operation (${s})`),{userMessage:"Unable to delete item: missing ID",severity:"error",context:{collection:e,idField:s,operation:r}});let C=P.collection(e).doc(I[s]);_.delete(C)}else{if(g&&n)try{fe(n,I)}catch(he){throw S(he,{userMessage:"Validation failed for item",severity:"warning",context:{collection:e,operation:r,idField:s,itemId:I[s]}})}let C=I[s];if(!C&&r==="create"&&u)C=P.collection(e).doc().id,I={...I,[s]:C};else if(!C)throw S(new Error(`Missing ID for ${r} operation (${s})`),{userMessage:`Unable to ${r} item: missing ID`,severity:"error",context:{collection:e,idField:s,operation:r}});let E=[s,...p],L=Ce(I,E),re=P.collection(e).doc(C);r==="create"?_.create(re,L):r==="update"&&_.update(re,L)}N++,N>=d&&(x.push({batch:_,size:N}),_=P.batch(),N=0)}catch(C){m.failures++,m.failedItems?.push({index:v,error:C instanceof Error?C:new Error(String(C))})}}N>0&&x.push({batch:_,size:N});let M=0;for(let{batch:v,size:I}of x){try{await v.commit(),m.successes+=I}catch(C){let E=C instanceof Error?C:new Error(String(C));for(let L=M;L<M+I;L++)m.failures++,m.failedItems?.push({index:L,error:E})}M+=I}return m}catch(x){throw S(x,{userMessage:`Batch ${r} operation failed for collection ${e}`,context:{collection:e,operation:r,itemCount:t.length,processedCount:m.successes+m.failures,successCount:m.successes,failureCount:m.failures}})}},async batchCreate(e,t,r,n={}){return ce.batchWrite(e,t,"create",r,n)},async batchUpdate(e,t,r,n={}){return ce.batchWrite(e,t,"update",r,n)},async batchDelete(e,t,r={}){if(t.length>0&&typeof t[0]=="string"){let n=r.idField||"id",o=t.map(s=>({[n]:s}));return ce.batchWrite(e,o,"delete",void 0,r)}return ce.batchWrite(e,t,"delete",void 0,r)},async runTransaction(e){try{return await(await Q()).runTransaction(e)}catch(t){throw S(t,{userMessage:"Transaction failed"})}},async bulkGet(e,t,r={}){if(!t.length)return[];let{maxBatchSize:n=30,transform:o=!0}=r;try{let s=[];for(let p=0;p<t.length;p+=n)s.push(t.slice(p,p+n));let u=s.map(async p=>{let x=await(await Q()).collection(e).where("__name__","in",p).get(),P=new Map;return x.forEach(_=>{P.set(_.id,_.data())}),p.map(_=>{let N=P.get(_);return N?o?ye({id:_,...N}):{id:_,...N}:null})});return(await Promise.all(u)).flat()}catch(s){throw S(s,{userMessage:`Bulk get operation failed for collection ${e}`,context:{collection:e,idCount:t.length}})}}},Be=i(e=>()=>{throw new Error(`Firebase Admin function '${e}' is not available in browser environments`)},"notAvailableInBrowser"),aa=Le?Be("batchWrite"):ce.batchWrite,ua=Le?Be("batchCreate"):ce.batchCreate,ca=Le?Be("batchUpdate"):ce.batchUpdate,la=Le?Be("batchDelete"):ce.batchDelete,pa=Le?Be("runTransaction"):ce.runTransaction,da=Le?Be("bulkGet"):ce.bulkGet});function Ke(e,t){return S(e,{userMessage:t?`Error during ${t}`:void 0,context:{operation:t}})}var yo=c(()=>{"use strict";$();i(Ke,"handleFirebaseError")});async function ho(e,t={}){let{collection:r="subscriptions",userIdField:n="customerId"}=t;try{let u=await(await Q()).collection(r).where(n,"==",e).where("status","==","active").limit(1).get();if(u.empty)return null;let d=u.docs[0];if(!d)return null;let p=d.data();return ye({id:d.id,...p})}catch(o){throw Ke(o,"getActiveSubscription")}}async function fa(e,t={}){let{collection:r="subscriptions",userIdField:n="customerId"}=t;try{return(await(await Q()).collection(r).where(n,"==",e).orderBy("createdAt","desc").get()).docs.map(d=>ye({id:d.id,...d.data()}))}catch(o){throw Ke(o,"getUserSubscriptions")}}async function vo(e,t={}){let{collection:r="subscriptions"}=t;try{let n=await Q(),o=new Date().toISOString(),s={...e,createdAt:e.createdAt||o,updatedAt:o},u=Ce(s),{id:d,...p}=u,g=d?n.collection(r).doc(d):n.collection(r).doc();return await g.set(p,{merge:!0}),{...s,id:g.id}}catch(n){throw Ke(n,"saveSubscription")}}async function bo(e,t,r={}){let{collection:n="subscriptions"}=r;try{await(await Q()).collection(n).doc(e).update({status:t,updatedAt:new Date().toISOString()})}catch(o){throw Ke(o,"updateSubscriptionStatus")}}async function ma(e,t,r={}){try{let n=await ho(e,r);return n?n.features&&Array.isArray(n.features)?n.features.includes(t):n.metadata&&n.metadata[t]?n.metadata[t]==="true":!1:!1}catch(n){throw S(n,{userMessage:"Failed to check feature access",severity:"error",context:{function:"hasFeatureAccess",userId:e,featureKey:t}})}}async function ga(e){let{rawBody:t,signature:r,webhookSecret:n,...o}=e,s;try{let d=await import("stripe"),p=d.default??d;s=new p("placeholder",{apiVersion:"2023-10-16"})}catch{throw S(new Error("stripe package is not installed"),{userMessage:"Stripe package missing \u2014 cannot verify webhook signature",severity:"error"})}let u;try{u=s.webhooks.constructEvent(t,r,n)}catch(d){throw S(d,{userMessage:"Stripe webhook signature verification failed",severity:"error",context:{function:"verifyAndHandleStripeWebhook"}})}await ya(u,o)}async function ya(e,t={}){let r=e.type,n=e.data.object;try{switch(r){case"customer.subscription.created":case"customer.subscription.updated":await ha(n,t);break;case"customer.subscription.deleted":await bo(n.id,"canceled",t);break;default:}}catch(o){throw S(o,{userMessage:`Failed to handle Stripe webhook event: ${r}`,severity:"error",context:{eventType:r,eventId:e.id}})}}async function ha(e,t={}){if(!e.items.data.length)throw S(new Error("[subscription] Stripe subscription has no items"),{userMessage:"Stripe subscription has no items \u2014 cannot determine plan",severity:"error",context:{subscriptionId:e.id}});let r={id:e.id,customerId:e.customer,status:e.status,planId:e.items.data[0]?.plan.id||"",currentPeriodStart:new Date(e.current_period_start*1e3).toISOString(),currentPeriodEnd:new Date(e.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:e.cancel_at_period_end,metadata:e.metadata||{},createdAt:new Date(e.created*1e3).toISOString(),updatedAt:new Date().toISOString()};e.canceled_at&&(r.canceledAt=new Date(e.canceled_at*1e3).toISOString()),await vo(r,t)}var Eo=c(()=>{"use strict";$();ze();gt();yo();i(ho,"getActiveSubscription");i(fa,"getUserSubscriptions");i(vo,"saveSubscription");i(bo,"updateSubscriptionStatus");i(ma,"hasFeatureAccess");i(ga,"verifyAndHandleStripeWebhook");i(ya,"handleStripeWebhookEvent");i(ha,"saveSubscriptionFromStripeEvent")});function yt(e){fr.uniqueConstraintValidator=e}function mr(){return fr.uniqueConstraintValidator}function So(){return!!fr.uniqueConstraintValidator}async function gr(){let e=await Q(),t={checkDuplicate:i(async(r,n,o,s)=>{if(o==null)return!1;try{return(await e.collection(r).where(n,"==",o).get()).docs.some(p=>p.id!==s&&p.data()[n]===o)}catch(u){throw S(u,{userMessage:`Failed to check uniqueness for field "${n}"`,severity:"error",context:{collection:r,field:n,value:o}})}},"checkDuplicate")};return yt(t),t}async function yr(){let e=await Q(),t={checkDuplicate:i(async(r,n,o,s)=>{if(o==null)return!1;try{return(await e.collection(r).where(n,"==",o).get()).docs.some(p=>p.id!==s&&p.data()[n]===o)}catch(u){throw S(u,{userMessage:`Failed to check uniqueness for field "${n}"`,severity:"error",context:{collection:r,field:n,value:o}})}},"checkDuplicate")};return yt(t),t}async function ht(e,t,r,n){if(!t.length)return;let o=mr();o||(o=await gr());let s=[],d=(await Promise.allSettled(t.map(async({field:p,errorMessage:g})=>{let m=r[p];if(m==null)return;await o.checkDuplicate(e,p,m,n)&&s.push({field:p,message:g||`The ${p} must be unique`})}))).find(p=>p.status==="rejected");if(d&&d.status==="rejected")throw d.reason;if(s.length>0)throw S(new Error("Uniqueness validation failed"),{userMessage:"Uniqueness validation failed",severity:"error",context:{validationErrors:s,collection:e}})}var fr,xo,vt=c(()=>{"use strict";$();ze();fr={};i(yt,"registerUniqueConstraintValidator");i(mr,"getUniqueConstraintValidator");i(So,"hasUniqueConstraintValidator");i(gr,"createFirestoreValidator");i(yr,"createAdminFirestoreValidator");xo=yr;i(ht,"validateUniqueness")});async function va(e,t,r,n){try{fe(e,t),e.metadata?.uniqueFields?.length&&await ht(e.metadata.collection,e.metadata.uniqueFields,t,n),e.metadata?.customValidate&&await e.metadata.customValidate(t,r)}catch(o){throw Cr(o)?S(o,{userMessage:"Document validation failed",context:{validationErrors:o.issues,data:t},severity:"warning"}):S(o,{userMessage:"Document validation failed",context:{collection:e.metadata?.collection||"unknown"},severity:"error"})}}function ba(e,t){let r=e;return r.metadata=t,r}var ko=c(()=>{"use strict";z();$();vt();vt();i(va,"validateFirestoreDocument");i(ba,"enhanceSchema")});var wo={};Lo(wo,{FieldValue:()=>Ea,FirebaseServerAuthAdapter:()=>lr,Query:()=>Sa,Timestamp:()=>xa,batchCreate:()=>ua,batchDelete:()=>la,batchUpdate:()=>ca,batchWrite:()=>aa,bulkGet:()=>da,convertISOStringsToDates:()=>dr,createAdminFirestoreValidator:()=>yr,createFirestoreClientValidator:()=>xo,createFirestorePartialUpdate:()=>sa,createFirestoreValidator:()=>gr,createTimestamp:()=>pr,enhanceSchema:()=>ba,firestoreToISOString:()=>fo,generateServerId:()=>na,getActiveSubscription:()=>ho,getFirebaseAdminApp:()=>We,getFirebaseAdminAuth:()=>J,getFirebaseAdminFirestore:()=>G,getFirebaseAdminFunctions:()=>ta,getServerAdmin:()=>ra,getServerFirestore:()=>Q,getUniqueConstraintValidator:()=>mr,getUserSubscriptions:()=>fa,hasFeatureAccess:()=>ma,hasUniqueConstraintValidator:()=>So,initFirebaseAdmin:()=>ea,isTimestamp:()=>mo,prepareForFirestore:()=>Ce,registerUniqueConstraintValidator:()=>yt,runTransaction:()=>pa,saveSubscription:()=>vo,toTimestamp:()=>ia,transformFirestoreData:()=>ye,updateSubscriptionStatus:()=>bo,validateFirestoreDocument:()=>va,validateUniqueness:()=>ht,verifyAndHandleStripeWebhook:()=>ga});import{FieldValue as Ea,Query as Sa,Timestamp as xa}from"firebase-admin/firestore";var le=c(()=>{"use strict";po();ft();ze();go();Eo();ko();vt();gt()});$();function te(e){let t,r,n;if(e instanceof w)t=e.code,r=e.message,n=e.details;else if(e&&typeof e=="object"&&"issues"in e&&(e instanceof Error&&e.name==="ValiError"||e.name==="ValiError"))t="invalid-argument",r="Validation failed",n={validationErrors:e.issues};else if(e&&typeof e=="object"&&"type"in e&&(e instanceof Error&&e.name==="EntityHookError"||e.name==="EntityHookError")){let o=e;switch(o.type){case"PERMISSION_DENIED":t="permission-denied";break;case"NOT_FOUND":t="not-found";break;case"ALREADY_EXISTS":t="already-exists";break;case"VALIDATION_ERROR":t="invalid-argument";break;case"NETWORK_ERROR":t="unavailable";break;default:t="internal"}r=o.message,n=void 0}else t="internal",r="An unexpected error occurred",n=void 0;throw t==="internal"&&(r="An unexpected error occurred"),new w(r,t,n?{details:n}:void 0)}i(te,"handleError");var Vs=/^[a-zA-Z0-9_.-]+$/;function j(e,t){if(!Vs.test(e))throw new Error(`Invalid ${t}: must contain only alphanumeric, hyphens, underscores, and dots`)}i(j,"validateGitHubName");var ar=class{static{i(this,"GitHubApiService")}config;constructor(t){this.config={baseUrl:"https://api.github.com",...t}}async getCurrentUser(){return await this.request("/user")}async getUserRepositories(t){t&&j(t,"username");let r=t?`/users/${t}/repos`:"/user/repos";return await this.request(r)}async addCollaborator(t){j(t.owner,"owner"),j(t.repo,"repo"),j(t.username,"username");try{return await this.request(`/repos/${t.owner}/${t.repo}/collaborators/${t.username}`,{method:"PUT",body:JSON.stringify({permission:t.permission||"push"})}),!0}catch(r){return console.error("Failed to add collaborator:",r),!1}}async isCollaborator(t,r,n){j(t,"owner"),j(r,"repo"),j(n,"username");try{return await this.request(`/repos/${t}/${r}/collaborators/${n}`,{method:"GET"}),!0}catch(o){return o.message?.includes("404")||console.error("Failed to check collaborator status:",o),!1}}async removeCollaborator(t,r,n){j(t,"owner"),j(r,"repo"),j(n,"username");try{return await this.request(`/repos/${t}/${r}/collaborators/${n}`,{method:"DELETE"}),!0}catch(o){return console.error("Failed to remove collaborator:",o),!1}}async addTeamMember(t,r,n,o="member"){j(t,"org"),j(r,"teamSlug"),j(n,"username");try{return await this.request(`/orgs/${t}/teams/${r}/memberships/${n}`,{method:"PUT",body:JSON.stringify({role:o})}),!0}catch(s){return console.error("Failed to add team member:",s),!1}}async removeTeamMember(t,r,n){j(t,"org"),j(r,"teamSlug"),j(n,"username");try{return await this.request(`/orgs/${t}/teams/${r}/memberships/${n}`,{method:"DELETE"}),!0}catch(o){return console.error("Failed to remove team member:",o),!1}}async isTeamMember(t,r,n){j(t,"org"),j(r,"teamSlug"),j(n,"username");try{return await this.request(`/orgs/${t}/teams/${r}/memberships/${n}`,{method:"GET"}),!0}catch(o){return o.message?.includes("404")||console.error("Failed to check team membership:",o),!1}}async request(t,r={}){let n=`${this.config.baseUrl}${t}`,o=await fetch(n,{...r,headers:{Authorization:`Bearer ${this.config.accessToken}`,Accept:"application/vnd.github.v3+json","User-Agent":"DoNotDev-Functions","Content-Type":"application/json",...r.headers}});if(!o.ok){let s=await o.json().catch(()=>({})),u={message:s.message||`HTTP ${o.status}: ${o.statusText}`,documentation_url:s.documentation_url,status:o.status};throw new Error(`GitHub API Error: ${u.message}`)}return o.json()}};function sg(e){return new ar({accessToken:e})}i(sg,"createGitHubApiService");function cg(e){let t=new Date().toISOString();return{createdAt:t,updatedAt:t,createdById:e,updatedById:e}}i(cg,"createMetadata");function lg(e){return{updatedAt:new Date().toISOString(),updatedById:e}}i(lg,"updateMetadata");function js(e){if(e&&typeof e=="object"&&"visibility"in e)return e.visibility}i(js,"getFieldVisibility");function Gs(e,t,r,n=!0){return t==="hidden"?!1:t==="guest"?!0:t==="admin"||t==="technical"?r:t==="owner"?!1:t==="user"||t===void 0?n:!1}i(Gs,"isFieldVisible");function Hs(e,t){if(!e||typeof e!="object"||!e.entries)return console.warn("getVisibleFields expects a Valibot object schema (v.object)."),[];let r=e.entries,n=[];for(let[o,s]of Object.entries(r)){let u=js(s);Gs(o,u,t)&&n.push(o)}return n}i(Hs,"getVisibleFields");function fg(e,t,r){if(!e)return{};let n=Hs(t,r),o={};for(let s of n)Object.prototype.hasOwnProperty.call(e,s)&&(o[s]=e[s]);return o}i(fg,"filterVisibleFields");z();import{logger as uo}from"firebase-functions/v2";var co={webhookEvent:y({id:f(a(),h(1,"Event ID is required")),type:f(a(),h(1,"Event type is required")),data:y({object:de()}),created:f(k(),U(0,"Valid timestamp required"))}),purchaseRequest:y({userId:f(a(),h(1,"User ID is required")),productType:f(a(),h(1,"Product type is required")),githubUsername:l(f(a(),Fe(/^[a-zA-Z0-9]([a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/,"Invalid GitHub username"))),sessionId:f(a(),h(1,"Session ID is required")),amount:l(f(k(),U(0,"Amount must be positive"))),currency:l(f(a(),Ae(3,"Currency must be 3 characters")))})};function hg(e){try{return{isValid:!0,data:fe(co.webhookEvent,e),errors:[]}}catch(t){if(t&&typeof t=="object"&&"issues"in t&&(t instanceof Error&&t.name==="ValiError"||t.name==="ValiError")){let n=t.issues.map(o=>`${o.path?.map(s=>s.key).join(".")||""}: ${o.message}`);return uo.warn("Webhook event validation failed",{errors:n,data:e}),{isValid:!1,errors:n}}return{isValid:!1,errors:["Unknown validation error"]}}}i(hg,"validateWebhookEvent");function vg(e){try{return{isValid:!0,data:fe(co.purchaseRequest,e),errors:[]}}catch(t){if(t&&typeof t=="object"&&"issues"in t&&(t instanceof Error&&t.name==="ValiError"||t.name==="ValiError")){let n=t.issues.map(o=>`${o.path?.map(s=>s.key).join(".")||""}: ${o.message}`);return uo.warn("Purchase request validation failed",{errors:n,data:e}),{isValid:!1,errors:n}}return{isValid:!1,errors:["Unknown validation error"]}}}i(vg,"validatePurchaseRequest");function bg(e){return/^[a-zA-Z0-9]([a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/.test(e)}i(bg,"validateGitHubUsername");function Eg(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}i(Eg,"validateEmail");function Sg(e){return e.startsWith("price_")&&e.length>6}i(Sg,"validateStripePriceId");function xg(e){return e.startsWith("cs_")&&e.length>3}i(xg,"validateStripeSessionId");function kg(e,t="URL"){try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`);return e}catch(r){throw new Error(`Invalid ${t}: ${e}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}i(kg,"validateUrl");function wg(e){let t={};for(let[r,n]of Object.entries(e)){if(typeof n!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof n}`);let o=n.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");if(o.length>1e3)throw new Error(`Metadata value for key '${r}' is too long (max 1000 characters)`);if(r.length>100)throw new Error(`Metadata key '${r}' is too long (max 100 characters)`);t[r]=o}return t}i(wg,"validateMetadata");z();function dt(e,t,r){let o=X(r||t,e);return o.success?{success:!0,data:o.output}:{success:!1,error:`Validation failed: ${o.issues.map(s=>s.message).join(", ")}`}}i(dt,"validateRequestData");function ur(e,t){return async(r,n)=>{let o=dt(r.data,e,n);if(!o.success)throw new Error(o.error);return await t(r,o.data)}}i(ur,"withSchemaValidation");function cr(e,t){return async(r,n,o)=>{let s=dt(r.body,e,o);return s.success?await t(r,n,s.data):n.status(400).json({error:s.error})}}i(cr,"withVercelSchemaValidation");function Tg(e,t){let r=ur(e,t);return{standard:i(n=>r(n),"standard"),withSchema:i((n,o)=>r(n,o),"withSchema")}}i(Tg,"createFirebaseFunction");function Ig(e,t){return cr(e,t)}i(Ig,"createVercelFunction");import{onCall as Ws}from"firebase-functions/v2/https";function zs(e,t,r){let n=ur(t,r);return{onCall:Ws(e,async o=>await n(o)),withSchema:i(async(o,s)=>await n(o,s),"withSchema")}}i(zs,"createFirebaseCallable");function _g(e,t,r){let{onCall:n,withSchema:o}=zs(e,t,r);return{[r.name||"mainFunction"]:n,[`${r.name||"mainFunction"}WithSchema`]:o}}i(_g,"createFirebaseFunctionExports");function Mg(e,t){return cr(e,t)}i(Mg,"createVercelHandler");function Lg(e,t,r){return async(n,o,s)=>{if(n.method!==e)return o.status(405).json({error:"Method not allowed"});let u=dt(n.body,t,s);return u.success?await r(n,o,u.data):o.status(400).json({error:u.error})}}i(Lg,"createVercelApiHandler");le();function Ly(e){if(e instanceof Date)return e.toISOString();if(typeof e=="object"&&e!==null&&"toDate"in e){let r=e;if(typeof r.toDate=="function")return r.toDate().toISOString()}if(typeof e=="string"){let r=new Date(e);if(isNaN(r.getTime()))throw new Error("Invalid date format");return r.toISOString()}let t=new Date(e);if(isNaN(t.getTime()))throw new Error("Invalid date format");return t.toISOString()}i(Ly,"toISOString");function bt(e,t){let r=new Date(e),n=r.getDate();return r.setMonth(r.getMonth()+t),r.getDate()!==n&&r.setDate(0),r}i(bt,"addMonths");function Ro(e,t){let r=new Date(e),n=r.getDate();return r.setFullYear(r.getFullYear()+t),r.getDate()!==n&&r.setDate(0),r}i(Ro,"addYears");function Et(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let r;return e==="1month"?r=bt(t,1):e==="3months"?r=bt(t,3):e==="6months"?r=bt(t,6):e==="1year"?r=Ro(t,1):e==="2years"?r=Ro(t,2):r=bt(t,1),r.toISOString()}i(Et,"calculateSubscriptionEndDate");le();async function jy(e,t){return[]}i(jy,"findReferences");$();le();function ka(e){return{price_pro_monthly:"pro",price_ai_monthly:"ai",price_pro_yearly:"pro",price_ai_yearly:"ai"}[e]||"free"}i(ka,"getTierFromPriceId");async function wa(e,t){if(!e)throw new Error("Firebase UID is required to cancel subscription");let r={tier:"free",subscriptionId:null,customerId:t.customer,status:"canceled",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString()};try{let n=J(),o=G(),u=(await n.getUser(e)).customClaims||{};await n.setCustomUserClaims(e,{...u,subscription:r}),await o.collection("subscriptions").doc(e).update({...r,updatedAt:new Date().toISOString()}),console.log(`Subscription canceled for user ${e}:`,{subscriptionId:t.id})}catch(n){throw console.error("Failed to cancel user subscription:",n),new Error("Failed to cancel user subscription")}}i(wa,"cancelUserSubscription");async function Ra(e){try{return(await J().getUser(e)).customClaims?.subscription||null}catch(t){return console.error("Failed to get user subscription:",t),null}}i(Ra,"getUserSubscription");$();le();function Aa(e){if(!e||typeof e!="string")throw new Error("Authentication required");return e}i(Aa,"assertAuthenticated");async function rh(e){Aa(e);try{let t={};Qt("serverAuth")?t=(await Jt("serverAuth").getUser(e))?.customClaims??{}:t=(await J().getUser(e)).customClaims??{};let r=t.role;if(!(r==="admin"||r==="super"||t.isAdmin===!0||t.isSuper===!0))throw new Error("Admin privileges required");return e}catch(t){throw t instanceof Error&&t.message==="Admin privileges required"?t:new Error("Failed to verify admin status")}}i(rh,"assertAdmin");function Ta(e){if(!e||!e.startsWith("Bearer "))throw new Error("Missing or invalid authorization header");let t=e.split("Bearer ")[1];if(!t)throw new Error("Missing token in authorization header");return t}i(Ta,"extractBearerToken");async function Ia(e,t){try{return t==="supabase"?await Ca(e):t==="firebase"?{uid:(await J().verifyIdToken(e)).uid}:Qt("serverAuth")?{uid:(await Jt("serverAuth").verifyToken(e)).uid}:{uid:(await J().verifyIdToken(e)).uid}}catch{throw new Error("Invalid or expired token")}}i(Ia,"verifyToken");async function Ca(e){let{createClient:t}=await import("@supabase/supabase-js"),r=process.env.SUPABASE_URL,n=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!r||!n)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let o=t(r,n,{auth:{autoRefreshToken:!1,persistSession:!1}}),{data:{user:s},error:u}=await o.auth.getUser(e);if(u||!s)throw new Error("Invalid or expired token");return{uid:s.id}}i(Ca,"verifySupabaseToken");async function Pa(e,t){let r=Ta(e.headers.authorization),{uid:n}=await Ia(r,t);return n}i(Pa,"verifyAuthToken");var nh=Pa;le();async function ah(){return await We()}i(ah,"initializeFirebaseAdmin");le();import{logger as St}from"firebase-functions/v2";async function dh(e,t){let r=G();try{let o=await r.collection("idempotency").doc(`${t}_${e}`).get();if(o.exists){let s=o.data();return St.info("Operation already processed (idempotency)",{key:e,operation:t,processedAt:s.processedAt,processedBy:s.processedBy}),s.result}return null}catch(n){throw St.error("Idempotency check failed",{key:e,operation:t,error:n instanceof Error?n.message:String(n)}),new Error(`Idempotency check failed for ${t}/${e}: ${n instanceof Error?n.message:String(n)}`)}}i(dh,"checkIdempotency");async function fh(e,t,r,n){try{await G().collection("idempotency").doc(`${t}_${e}`).set({result:r,processedAt:new Date().toISOString(),processedBy:n}),St.info("Idempotency result stored",{key:e,operation:t,processedBy:n})}catch(o){St.error("Failed to store idempotency result",{key:e,operation:t,processedBy:n,error:o instanceof Error?o.message:String(o)})}}i(fh,"storeIdempotencyResult");le();import{logger as oe}from"firebase-functions/v2";async function vh(e){try{await G().collection("payment_metrics").doc().set({...e,recordedAt:new Date().toISOString()}),oe.info("Payment metrics recorded",{operation:e.operation,status:e.status,userId:e.userId})}catch(t){oe.error("Failed to record payment metrics",{error:t instanceof Error?t.message:String(t),metrics:e})}}i(vh,"recordPaymentMetrics");async function bh(e=24){try{let t=G(),r=new Date;r.setHours(r.getHours()-e);let o=await t.collection("payment_metrics").where("timestamp",">=",r.toISOString()).get();if(o.empty)return{failureRate:0,shouldAlert:!1};let s=o.size,u=o.docs.filter(g=>g.data().status==="failed").length,d=u/s*100,p=d>10;return p&&await Da(d,s,u),{failureRate:d,shouldAlert:p}}catch(t){return oe.error("Failed to check payment failure rate",{error:t instanceof Error?t.message:String(t)}),{failureRate:0,shouldAlert:!1}}}i(bh,"checkPaymentFailureRate");async function Eh(e=1e4){try{let t=G(),r=new Date;r.setHours(0,0,0,0);let n=new Date(r);n.setDate(n.getDate()+1);let s=await t.collection("payment_metrics").where("timestamp",">=",r.toISOString()).where("timestamp","<",n.toISOString()).where("status","==","success").get(),u=0;s.docs.forEach(p=>{let g=p.data();g.amount&&g.currency==="usd"&&(u+=g.amount/100)});let d=u>e;return d&&await Oa(u,e),{totalVolume:u,shouldAlert:d}}catch(t){return oe.error("Failed to check payment volume",{error:t instanceof Error?t.message:String(t)}),{totalVolume:0,shouldAlert:!1}}}i(Eh,"checkPaymentVolume");async function Da(e,t,r){try{await G().collection("payment_alerts").doc().set({type:"payment_failure_rate",severity:"high",message:`Payment failure rate is ${e.toFixed(2)}% (${r}/${t} payments failed)`,data:{failureRate:e,totalPayments:t,failedPayments:r},triggeredAt:new Date().toISOString(),status:"active"}),oe.error("PAYMENT FAILURE ALERT TRIGGERED",{failureRate:e,totalPayments:t,failedPayments:r})}catch(n){oe.error("Failed to trigger payment failure alert",{error:n instanceof Error?n.message:String(n)})}}i(Da,"triggerPaymentFailureAlert");async function Oa(e,t){try{await G().collection("payment_alerts").doc().set({type:"high_payment_volume",severity:"medium",message:`Daily payment volume exceeded threshold: $${e.toFixed(2)} (threshold: $${t})`,data:{totalVolume:e,threshold:t},triggeredAt:new Date().toISOString(),status:"active"}),oe.warn("HIGH PAYMENT VOLUME ALERT TRIGGERED",{totalVolume:e,threshold:t})}catch(r){oe.error("Failed to trigger high volume alert",{error:r instanceof Error?r.message:String(r)})}}i(Oa,"triggerHighVolumeAlert");async function Sh(e,t){try{let o=await G().collection("payment_metrics").where("timestamp",">=",e.toISOString()).where("timestamp","<=",t.toISOString()).get(),s=0,u=0,d=0,p=0;o.docs.forEach(m=>{let x=m.data();s++,x.status==="success"?(u++,x.amount&&x.currency==="usd"&&(p+=x.amount/100)):x.status==="failed"&&d++});let g=u>0?p/u:0;return{totalPayments:s,successfulPayments:u,failedPayments:d,totalVolume:p,averageAmount:g}}catch(r){return oe.error("Failed to get payment metrics summary",{error:r instanceof Error?r.message:String(r)}),{totalPayments:0,successfulPayments:0,failedPayments:0,totalVolume:0,averageAmount:0}}}i(Sh,"getPaymentMetricsSummary");async function xh(e=90,t=30){try{let r=G(),n=new Date,o=new Date(n);o.setDate(o.getDate()-e);let s=await r.collection("payment_metrics").where("recordedAt","<",o.toISOString()).limit(500).get();if(!s.empty){let p=r.batch();s.docs.forEach(g=>p.delete(g.ref)),await p.commit()}let u=new Date(n);u.setDate(u.getDate()-t);let d=await r.collection("payment_alerts").where("triggeredAt","<",u.toISOString()).limit(500).get();if(!d.empty){let p=r.batch();d.docs.forEach(g=>p.delete(g.ref)),await p.commit()}oe.info("Payment metrics cleanup completed",{deletedMetrics:s.size,deletedAlerts:d.size})}catch(r){oe.error("Payment metrics cleanup failed",{error:r instanceof Error?r.message:String(r)})}}i(xh,"cleanupOldMetrics");le();import{logger as qe}from"firebase-functions/v2";var Pe=new Map;async function Th(e,t){let r=Date.now(),n=Pe.get(e);if(n?.blockUntil&&r<n.blockUntil)return{allowed:!1,remaining:0,resetAt:new Date(n.blockUntil),blockRemainingSeconds:Math.ceil((n.blockUntil-r)/1e3)};n&&r>=n.windowStart+t.windowMs&&Pe.delete(e);let o=Pe.get(e)||{attempts:0,windowStart:r,blockUntil:null};return o.attempts>=t.maxAttempts?(o.blockUntil=r+t.blockDurationMs,Pe.set(e,o),qe.warn("Rate limit exceeded",{key:e,attempts:o.attempts,blockUntil:new Date(o.blockUntil)}),{allowed:!1,remaining:0,resetAt:new Date(o.blockUntil),blockRemainingSeconds:Math.ceil(t.blockDurationMs/1e3)}):(o.attempts+=1,Pe.set(e,o),{allowed:!0,remaining:t.maxAttempts-o.attempts,resetAt:new Date(o.windowStart+t.windowMs),blockRemainingSeconds:null})}i(Th,"checkRateLimit");async function Ih(e,t){let r=G(),n=r.collection("rateLimits").doc(e);try{let o=Date.now(),s={allowed:!0,remaining:t.maxAttempts-1,resetAt:new Date(o+t.windowMs),blockRemainingSeconds:null};return await r.runTransaction(async u=>{let d=await u.get(n);if(!d.exists){u.set(n,{attempts:1,windowStart:o,blockUntil:null,lastUpdated:o}),s={allowed:!0,remaining:t.maxAttempts-1,resetAt:new Date(o+t.windowMs),blockRemainingSeconds:null};return}let p=d.data();if(p.blockUntil&&o<p.blockUntil){s={allowed:!1,remaining:0,resetAt:new Date(p.blockUntil),blockRemainingSeconds:Math.ceil((p.blockUntil-o)/1e3)};return}if(o>=p.windowStart+t.windowMs){u.set(n,{attempts:1,windowStart:o,blockUntil:null,lastUpdated:o}),s={allowed:!0,remaining:t.maxAttempts-1,resetAt:new Date(o+t.windowMs),blockRemainingSeconds:null};return}if(p.attempts>=t.maxAttempts){let g=o+t.blockDurationMs;u.update(n,{blockUntil:g,lastUpdated:o}),qe.warn("Rate limit exceeded (Firestore)",{key:e,attempts:p.attempts,blockUntil:new Date(g)}),s={allowed:!1,remaining:0,resetAt:new Date(g),blockRemainingSeconds:Math.ceil(t.blockDurationMs/1e3)};return}u.update(n,{attempts:p.attempts+1,lastUpdated:o}),s={allowed:!0,remaining:t.maxAttempts-(p.attempts+1),resetAt:new Date(p.windowStart+t.windowMs),blockRemainingSeconds:null}}),s}catch(o){return qe.error("Rate limit check failed",{key:e,error:o instanceof Error?o.message:String(o)}),{allowed:!1,remaining:0,resetAt:null,blockRemainingSeconds:null}}}i(Ih,"checkRateLimitWithFirestore");function Ch(e){Pe.delete(e),qe.info("Rate limit reset",{key:e})}i(Ch,"resetRateLimit");async function Ph(e){let r=G().collection("rateLimits").doc(e);try{await r.delete(),qe.info("Rate limit reset (Firestore)",{key:e})}catch(n){qe.error("Failed to reset rate limit",{key:e,error:n instanceof Error?n.message:String(n)})}}i(Ph,"resetRateLimitInFirestore");function Dh(e,t){let r=Date.now(),n=Pe.get(e);return n?n.blockUntil&&r<n.blockUntil?{allowed:!1,remaining:0,resetAt:new Date(n.blockUntil),blockRemainingSeconds:Math.ceil((n.blockUntil-r)/1e3)}:r>=n.windowStart+t.windowMs?{allowed:!0,remaining:t.maxAttempts,resetAt:null,blockRemainingSeconds:null}:{allowed:n.attempts<t.maxAttempts,remaining:Math.max(0,t.maxAttempts-n.attempts),resetAt:new Date(n.windowStart+t.windowMs),blockRemainingSeconds:null}:{allowed:!0,remaining:t.maxAttempts,resetAt:null,blockRemainingSeconds:null}}i(Dh,"getRateLimitStatus");var Oh={checkout:{maxAttempts:5,windowMs:60*1e3,blockDurationMs:300*1e3},webhook:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3},auth:{maxAttempts:10,windowMs:60*1e3,blockDurationMs:300*1e3},api:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3}};z();$();function Uh(){let t=["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"].filter(r=>!process.env[r]);if(t.length>0)throw new Error(`Missing required environment variables: ${t.join(", ")}`)}i(Uh,"validateStripeEnvironment");function Mh(e){try{return JSON.parse(e)}catch{return null}}i(Mh,"safeJsonParse");function Lh(e){if(!e||typeof e!="string")throw new Error("Collection name is required");if(e.includes("/")||e.includes("..")||e.startsWith("_"))throw new Error('Invalid collection name: must not contain "/", "..", or start with "_"')}i(Lh,"validateCollectionName");function Bh(e,t){if(!e||typeof e!="object")throw new w("Invalid document data","invalid-argument");if(Array.isArray(e))throw new w("Document data cannot be an array","invalid-argument");if(t){let r=X(t,e);if(!r.success){let n=r.issues.map(o=>`${o.path?.map(s=>s.key).join(".")||"root"}: ${o.message}`).join("; ");throw new w(`Validation failed: ${n}`,"invalid-argument",{details:{validationErrors:r.issues}})}}}i(Bh,"validateDocument");z();$();var _a=Object.freeze({insertedIds:[],updatedIds:[],deletedIds:[]});async function Fa(e){let{collection:t,ops:r,createSchema:n,draftCreateSchema:o,updateSchema:s,access:u,uid:d,userRole:p,transact:g,mintInsertId:m,stampInsertMetadata:x,stampUpdateMetadata:P,audit:_}=e,N=X(eo,r);if(!N.success){let B=N.issues.map(Z=>`${Z.path?.map(ve=>ve.key).join(".")||"root"}: ${Z.message}`).join("; ");throw new w(`Bulk payload validation failed: ${B}`,"invalid-argument",{details:{validationErrors:N.issues}})}let M=N.output,v=M.inserts??[],I=M.updates??[],C=M.deletes??[],E=ro(M);if(E.where!==null)throw new nt(E.collisions,E.where);if(v.length===0&&I.length===0&&C.length===0)return _a;if(v.length>0){if(!u.create)throw new w(`Bulk insert requested on ${t} but no create role is configured`,"permission-denied");if(!Ge(p,u.create))throw new w(`Access denied for bulk insert on ${t}. Required: ${u.create}, your role: ${p}`,"permission-denied")}if(I.length>0){if(!u.update)throw new w(`Bulk update requested on ${t} but no update role is configured`,"permission-denied");if(!Ge(p,u.update))throw new w(`Access denied for bulk update on ${t}. Required: ${u.update}, your role: ${p}`,"permission-denied")}if(C.length>0){if(!u.delete)throw new w(`Bulk delete requested on ${t} but no delete role is configured`,"permission-denied");if(!Ge(p,u.delete))throw new w(`Access denied for bulk delete on ${t}. Required: ${u.delete}, your role: ${p}`,"permission-denied")}for(let B=0;B<v.length;B++){let ve=v[B],Ze=ve.status??sr,Je=Ze==="draft",Uo=Je&&o?o:n,Mo=Je&&o?{...ve,status:Ze}:ve;Ao(Mo,Uo,`inserts[${B}]`)}for(let B=0;B<I.length;B++)Ao(I[B].patch,s,`updates[${B}]`);let L=v.map(B=>{let Z=B,ve=Z.status??sr,Ze=m?m():"",Je=x?x({...Z,status:ve},d):{...Z,status:ve};return{id:Ze,row:Je}}),re=I.map(B=>({id:B.id,patch:P?P(B.patch,d):B.patch})),he=await g({inserts:L,updates:re,deletes:[...C]}),Oe=X(to,he);if(!Oe.success)throw new w(`Bulk transact() returned an unexpected shape for ${t}`,"internal");return _&&_(`crud.bulk.${t}`,{counts:{inserts:L.length,updates:re.length,deletes:C.length}}),Oe.output}i(Fa,"executeBulk");function Ao(e,t,r){let n=X(t,e);if(n.success)return;let o=n.issues.map(s=>`${s.path?.map(u=>u.key).join(".")||"root"}: ${s.message}`).join("; ");throw new w(`Validation failed on ${r}: ${o}`,"invalid-argument",{details:{validationErrors:n.issues}})}i(Ao,"validateRow");$();import{streamText as Na,generateText as Ua,tool as Ma,jsonSchema as La}from"ai";$();function hr(e,t,r=Rr){let n=Ar[t];if(!n)throw new Error(`Unknown model for cost calculation: ${t}`);let o=e.promptTokens/1e6*n.promptPer1M,s=e.completionTokens/1e6*n.completionPer1M,u=o+s;return{providerCost:u,billedCost:u*r,markup:r,breakdown:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,promptCost:o,completionCost:s}}}i(hr,"calculateCost");async function Ba(e,t){let n={anthropic:i(async()=>{let{createAnthropic:u}=await import("@ai-sdk/anthropic");return d=>u({apiKey:d})(t)},"anthropic"),openai:i(async()=>{let{createOpenAI:u}=await import("@ai-sdk/openai");return d=>u({apiKey:d})(t)},"openai"),google:i(async()=>{let{createGoogleGenerativeAI:u}=await import("@ai-sdk/google");return d=>u({apiKey:d})(t)},"google")}[e];if(!n)throw new Error(`Unsupported AI provider: ${e}`);let o=Ga(e);return(await n())(o)}i(Ba,"resolveModel");var qa={maxRequests:30,windowMs:6e4},ke=null;async function $a(){if(ke)return ke;let e=kt("UPSTASH_REDIS_REST_URL"),t=kt("UPSTASH_REDIS_REST_TOKEN");if(!e||!t)return console.warn("[AI] UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN not set. Rate limiting disabled."),ke={check:i(async()=>{},"check")},ke;try{let{Ratelimit:r}=await import("@upstash/ratelimit"),{Redis:n}=await import("@upstash/redis"),o=new n({url:e,token:t}),s=new Map;return ke={check:i(async(u,d)=>{let p=`${d.maxRequests}:${d.windowMs}`,g=s.get(p);if(g||(g=new r({redis:o,limiter:r.slidingWindow(d.maxRequests,`${d.windowMs}ms`),prefix:"ai_rl"}),s.set(p,g)),!(await g.limit(u)).success)throw new Error(`Rate limit exceeded. Maximum ${d.maxRequests} requests per ${d.windowMs/1e3}s.`)},"check")},ke}catch(r){return console.warn("[AI] Failed to initialize Upstash rate limiter:",r instanceof Error?r.message:r),ke={check:i(async()=>{},"check")},ke}}i($a,"getRateLimiter");function Va(e,t){let r={...t,...e};if(Object.keys(r).length===0)return;let n={};for(let[o,s]of Object.entries(r))n[o]=Ma({description:s.description,parameters:La(s.parameters)});return n}i(Va,"resolveTools");async function ja(e,t,r){let n=Or(e);if(!n.success)return xt(`Invalid AI request: ${n.issues?.map(E=>E.message).join(", ")}`,400);let o=e.provider||t.provider||"anthropic",s=wr[o],u=e.model||t.model||s?.default||"claude-sonnet-4-20250514";if(s){let E=s.models;if(!E.includes(u))return xt(`Model '${u}' is not allowed for provider '${o}'. Allowed: ${E.join(", ")}`,400)}try{await(await $a()).check(r.userId,t.rateLimitConfig||qa)}catch(E){return xt(E instanceof Error?E.message:"Rate limit exceeded",429)}let d;try{d=await Ba(o,u)}catch(E){return xt(`Failed to initialize provider: ${E instanceof Error?E.message:String(E)}`,500)}let p=e.messages.filter(E=>E.role==="system").map(E=>E.content),g=e.systemPrompt||t.systemPrompt||(p.length>0?p.join(`
|
|
23
|
-
`):void 0),m=e.messages.filter(E=>E.role!=="system").map(E=>({role:E.role,content:E.content})),x=e.maxTokens||t.maxTokens||4096,P=e.temperature??t.temperature??.7,_=r.requestId||crypto.randomUUID(),N=Va(e.tools,t.tools),M=i(async E=>{if(!r.onCostRecord)return;let L=t.cost?.markup??4,re=hr(E,u,L),he={userId:r.userId,model:u,provider:o,usage:E,providerCost:re.providerCost,billedCost:re.billedCost,markup:L,timestamp:new Date().toISOString(),requestId:_};r.onCostRecord(he).catch(Oe=>{console.error("[AI] Failed to record cost:",Oe)})},"recordCost");if(e.stream!==!1)return Na({model:d,messages:m,system:g,maxTokens:x,temperature:P,tools:N,onFinish:i(async({usage:L})=>{await M({promptTokens:L.promptTokens,completionTokens:L.completionTokens,totalTokens:L.promptTokens+L.completionTokens})},"onFinish")}).toDataStreamResponse();let v=await Ua({model:d,messages:m,system:g,maxTokens:x,temperature:P,tools:N}),I={promptTokens:v.usage.promptTokens,completionTokens:v.usage.completionTokens,totalTokens:v.usage.promptTokens+v.usage.completionTokens};await M(I);let C=v.toolCalls?.map(E=>({id:E.toolCallId,name:E.toolName,args:E.args}))??[];return new Response(JSON.stringify({message:{role:"assistant",content:v.text},usage:I,finishReason:v.finishReason,toolCalls:C.length>0?C:void 0,model:u,provider:o}),{status:200,headers:{"Content-Type":"application/json"}})}i(ja,"handleAIRequest");function xt(e,t){return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json"}})}i(xt,"jsonError");function kt(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}i(kt,"getEnv");function Ga(e){let r={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",google:"GOOGLE_AI_API_KEY"}[e];if(r){let o=kt(r);if(o)return o}let n=kt("AI_API_KEY");if(!n)throw new Error(`Missing API key. Set ${r||"AI_API_KEY"} environment variable.`);return n}i(Ga,"getAIApiKey");$();function To(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}i(To,"getEnv");function Ha(e,t){if(t){let o=To(`AI_MODEL_${t.toUpperCase()}`);if(o)return o}let r=To(`AI_TIER_${e.toUpperCase()}`);return r||(Object.values(At).find(o=>o.id===e)?.defaultModel??At.STANDARD.defaultModel)}i(Ha,"resolveModelForTier");function Wa(e){let t=Ka(e),r=Ya(e);return t===429?{code:"rate_limited",retryable:!0,retryAfterMs:Io(e)??5e3,severity:"transient"}:t===529||t===503?{code:"overloaded",retryable:!0,retryAfterMs:Io(e)??1e4,severity:"transient"}:t===401?{code:"auth_error",retryable:!1,severity:"critical"}:t===402||r.includes("insufficient")||r.includes("credit")?{code:"credits_exhausted",retryable:!1,severity:"critical"}:!t&&(r.includes("fetch")||r.includes("network")||r.includes("ECONNREFUSED")||r.includes("ETIMEDOUT")||r.includes("timeout")||r.includes("aborted")||e instanceof TypeError)?{code:"network",retryable:!0,retryAfterMs:3e3,severity:"transient"}:{code:"internal",retryable:!1,severity:"critical"}}i(Wa,"classifyAIError");function za(e){switch(e){case"rate_limited":return 429;case"overloaded":return 503;case"auth_error":return 502;case"credits_exhausted":return 502;case"network":return 502;case"internal":return 500}}i(za,"mapClassifiedToHTTP");function Ka(e){if(e&&typeof e=="object"){if("status"in e&&typeof e.status=="number")return e.status;if("error"in e&&typeof e.error?.status=="number")return e.error.status}}i(Ka,"extractStatus");function Ya(e){return e instanceof Error?e.message.toLowerCase():typeof e=="string"?e.toLowerCase():e&&typeof e=="object"&&"message"in e?String(e.message).toLowerCase():""}i(Ya,"extractMessage");function Io(e){if(e&&typeof e=="object"){let t=e.headers;if(t){let r=typeof t.get=="function"?t.get("retry-after"):t["retry-after"];if(r){let n=Number(r);if(!Number.isNaN(n))return n*1e3}}}}i(Io,"extractRetryAfter");function Co(e,t){try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`)}catch(r){throw new Error(`Invalid ${t} URL: ${e}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}i(Co,"validateCheckoutUrl");function Po(e){let t={};for(let[r,n]of Object.entries(e)){if(typeof n!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof n}`);let o=n.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");if(o.length>1e3)throw new Error(`Metadata value for key '${r}' is too long (max 1000 characters)`);if(r.length>100)throw new Error(`Metadata key '${r}' is too long (max 100 characters)`);t[r]=o}return t}i(Po,"sanitizeMetadata");async function pv(e,t,r,n){if(!process.env.FRONTEND_URL)throw new Error("FRONTEND_URL environment variable is required");let{priceId:o,unitAmount:s,productName:u,currency:d,userId:p,customerEmail:g,metadata:m={},allowPromotionCodes:x=!0,successUrl:P,cancelUrl:_,mode:N="payment"}=e,M=m.billingConfigKey;if(!M)throw new Error("Missing billingConfigKey in metadata");let v=n[M];if(!v)throw new Error(`Invalid billing config key: ${M}`);let I=!o&&s&&u;if(!o&&!I)throw new Error("Either priceId or (unitAmount + productName) is required");if(I&&N==="subscription")throw new Error("Dynamic pricing (unitAmount) is not supported for subscriptions. Use a Stripe priceId.");if(o){if(v.priceId&&v.priceId!==o)throw new Error("Price ID mismatch with configuration")}else{if(!v.maxUnitAmount)throw new Error("Dynamic pricing requires maxUnitAmount in billing config for security");if(s>v.maxUnitAmount)throw new Error(`Unit amount ${s} exceeds maximum allowed: ${v.maxUnitAmount}`);if(s<100)throw new Error("Unit amount must be at least 100 cents (1.00)")}if(!p)throw new Error("Missing userId in request");await r.getUser(p);let C=s,E=u;if(v.beforeCheckout){let Z=await v.beforeCheckout(p,{priceId:o,unitAmount:s,productName:u,currency:d,mode:N,metadata:m,allowPromotionCodes:x},Po(m));if(!Z.allowed)throw new Error(Z.reason||"Checkout blocked by beforeCheckout hook");Z.overrides&&(Z.overrides.unitAmount!==void 0&&(C=Z.overrides.unitAmount),Z.overrides.productName!==void 0&&(E=Z.overrides.productName))}let L=!o&&C&&E;if(L&&v.maxUnitAmount&&C>v.maxUnitAmount)throw new Error(`Hook-overridden unit amount ${C} exceeds maximum allowed: ${v.maxUnitAmount}`);let re=P||`${process.env.FRONTEND_URL}/billing/success`,he=_||`${process.env.FRONTEND_URL}/billing/cancel`;Co(re,"success"),Co(he,"cancel");let Oe=Po(m),B=await t.createCheckoutSession({priceId:o,unitAmount:L?C:void 0,productName:L?E:void 0,currency:d||v.currency||"eur",customerEmail:g,metadata:{...Oe,userId:p,billingConfigKey:M},allowPromotionCodes:x,successUrl:re,cancelUrl:he,mode:N});return{sessionId:B.id,sessionUrl:B.url}}i(pv,"createCheckoutAlgorithm");async function Xa(e,t,r){let o=(await r.getUser(e)).customClaims||{};if(!t.tier||!t.status)throw new Error("Invalid subscription data: missing tier or status");t.customerId||console.warn(`[updateUserSubscription] customerId is undefined for user ${e}. Falling back to userId. This may cause issues with Stripe API calls.`);let s={tier:t.tier,subscriptionId:t.subscriptionId||null,customerId:t.customerId||e,status:t.status,subscriptionEnd:t.subscriptionEnd,cancelAtPeriodEnd:t.cancelAtPeriodEnd||!1,updatedAt:new Date().toISOString(),isDefault:!1},u={...o,subscription:s};await r.setCustomUserClaims(e,u)}i(Xa,"updateUserSubscription");$();if(typeof globalThis<"u"&&"window"in globalThis)throw new Error("Server logger cannot be imported on client side");var Za=typeof process<"u"&&!!process.versions?.node,Ye=!1,De=null,wt=!1;async function Do(){if(!wt)try{let e=process.env.SENTRY_DSN;if(e){let{init:t,captureException:r,captureMessage:n}=await import("@sentry/node");t({dsn:e,environment:"production"}),De={captureException:r,captureMessage:n},Ye=!0}}catch{Ye=!1}finally{wt=!0}}i(Do,"initializeSentry");var Oo=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s[s.FATAL=4]="FATAL",s))(Oo||{}),H={debug(e,t){this.log(0,e,t)},info(e,t){this.log(1,e,t)},warn(e,t){this.log(2,e,t)},async error(e,t){if(this.log(3,e,t),wt||await Do(),Ye&&De)try{t?.error instanceof Error?De.captureException(t.error):De.captureMessage(e,"error")}catch(r){console.error("Sentry error:",r)}},async fatal(e,t){if(this.log(4,e,t),wt||await Do(),Ye&&De)try{t?.error instanceof Error?De.captureException(t.error):De.captureMessage(e,"fatal")}catch(r){console.error("Sentry error:",r)}},log(e,t,r){let n=new Date().toISOString(),o={level:e,message:t,timestamp:n,context:r,error:r?.error,metadata:{...Za?{pid:process.pid,nodeVersion:process.version,platform:process.platform}:{},...r?.metadata}},s=Oo[e],u=r?` ${JSON.stringify(r)}`:"";switch(e){case 0:console.debug(`[${n}] [DEBUG] ${t}${u}`);break;case 1:console.info(`[${n}] [INFO] ${t}${u}`);break;case 2:console.warn(`[${n}] [WARN] ${t}${u}`);break;case 3:console.error(`[${n}] [ERROR] ${t}${u}`);break;case 4:console.error(`[${n}] [FATAL] ${t}${u}`);break}},isSentryEnabled(){return Ye},getLevel(){return 0}};function _o(){if(process.env.FUNCTION_NAME||process.env.FIREBASE_CONFIG)return!0;let e=!!process.env.FIREBASE_PROJECT_ID,t=!!process.env.FIREBASE_CLIENT_EMAIL,r=!!process.env.FIREBASE_PRIVATE_KEY;return e&&t&&r}i(_o,"isFirestoreConfigured");var vr=class{static{i(this,"InMemoryIdempotency")}store=new Set;warned=!1;async isProcessed(t){return this.warned||(console.warn(`\u26A0\uFE0F [Idempotency] Using in-memory storage (not production-ready for scale)
|
|
24
|
-
Enable Firestore for production: https://console.firebase.google.com
|
|
25
|
-
Good for: Single instance, < 1K webhooks/month
|
|
26
|
-
Upgrade when: Multiple instances, > 1K webhooks/month`),this.warned=!0),this.store.has(t)}async markProcessed(t){if(this.store.add(t),this.store.size>1e3){let r=this.store.values().next().value;r&&this.store.delete(r)}}async checkAndReserve(t){return this.store.has(t)?!0:(this.store.add(t),!1)}},br=class{static{i(this,"FirestoreIdempotency")}db;collection="webhook_idempotency";initialized=!1;async init(){if(this.initialized)return;let{getFirebaseAdminFirestore:t}=await Promise.resolve().then(()=>(le(),wo));this.db=t(),this.initialized=!0}async isProcessed(t){await this.init();try{let r=await this.db.collection(this.collection).doc(t).get();if(!r.exists)return!1;let n=r.data();return n?(n.expiresAt||0)<Date.now()?(await r.ref.delete(),!1):!0:!1}catch(r){throw te(r)}}async markProcessed(t){await this.init();try{await this.db.runTransaction(async r=>{let n=this.db.collection(this.collection).doc(t);(await r.get(n)).exists||r.set(n,{eventId:t,processedAt:Date.now(),expiresAt:Date.now()+720*60*60*1e3})})}catch(r){throw te(r)}}async checkAndReserve(t){await this.init();try{let r=!1;return await this.db.runTransaction(async n=>{let o=this.db.collection(this.collection).doc(t),s=await n.get(o);if(s.exists&&(s.data()?.expiresAt||0)>=Date.now()){r=!0;return}n.set(o,{eventId:t,processedAt:Date.now(),expiresAt:Date.now()+720*60*60*1e3})}),r}catch(r){throw te(r)}}},Xe=null;function Fo(){return Xe||(_o()?(console.log("\u2705 [Idempotency] Using Firestore (production-ready)"),Xe=new br):(console.warn("\u26A0\uFE0F [Idempotency] Firestore not configured, using in-memory"),Xe=new vr),Xe)}i(Fo,"createIdempotencyStore");var Er=null;function Ja(){return Er||(Er=Fo()),Er}i(Ja,"getIdempotencyStore");async function Dv(e,t,r,n,o,s,u){try{let d=Lr(o),p=n.webhooks.constructEvent(e,t,r);return H.info("[Webhook] Processing event",{eventType:p.type,eventId:p.id,operation:"webhook_processing"}),await Ja().checkAndReserve(p.id)?(H.info("[Webhook] Already processed",{eventId:p.id}),{success:!0,message:"Event already processed"}):(u||H.warn("[Webhook] authProvider is null \u2014 subscription-related events will fail",{eventType:p.type,eventId:p.id}),await Qa(p,d,s,n,u),{success:!0,message:"Webhook processed"})}catch(d){throw te(d)}}i(Dv,"processWebhook");async function Qa(e,t,r,n,o){switch(e.type){case"checkout.session.completed":await eu(e.data.object,t,r,o);break;case"invoice.payment_succeeded":await tu(e.data.object,t,r,n,o);break;case"customer.subscription.deleted":await ru(e.data.object,t,r,o);break;case"invoice.payment_failed":await nu(e.data.object,t);break;default:H.debug("[Webhook] Unhandled event type",{type:e.type})}}i(Qa,"routeEvent");async function eu(e,t,r,n){let{userId:o,billingConfigKey:s}=e.metadata||{};if(!o||!s)throw te(new Error(`Missing required metadata: userId=${o}, billingConfigKey=${s}`));let u=t[s];if(!u)throw te(new Error(`Unknown billing config key: ${s}`));if(H.info("[Webhook] Processing purchase",{userId:o,configKey:s,type:u.type,operation:"purchase_processing"}),u.type==="StripePayment"){if(!n)throw te(new Error("Auth provider required for subscription updates"));if(await r(o,{tier:u.tier,status:ie.ACTIVE,subscriptionEnd:Et(u.duration),customerId:e.customer},n),u.onPurchaseSuccess)try{await u.onPurchaseSuccess(o,e.metadata||{})}catch(d){H.error("[Webhook] Hook failed (non-critical)",{error:d instanceof Error?d:new Error(String(d)),hookName:"onPurchaseSuccess",userId:o,operation:"hook_execution"})}}if(u.type==="StripeSubscription"){if(!n)throw te(new Error("Auth provider required for subscription updates"));if(await r(o,{tier:u.tier,status:ie.ACTIVE,subscriptionEnd:Et(u.duration),subscriptionId:e.subscription,customerId:e.customer},n),u.onSubscriptionCreated)try{await u.onSubscriptionCreated(o,e.metadata||{})}catch(d){H.error("[Webhook] Hook failed (non-critical)",{error:d instanceof Error?d:new Error(String(d)),hookName:"onSubscriptionCreated",userId:o,operation:"hook_execution"})}}H.info("[Webhook] Purchase processed",{userId:o,configKey:s,operation:"purchase_processed"})}i(eu,"handleCheckoutCompleted");async function tu(e,t,r,n,o){let s=e.subscription;if(!s)return;let u=await n.subscriptions.retrieve(s),{userId:d,billingConfigKey:p}=u.metadata||{};if(!d||!p){H.error("[Webhook] Subscription metadata missing userId or billingConfigKey",{subscriptionId:s,hasUserId:!!d,hasBillingConfigKey:!!p,operation:"invoice_payment_succeeded_metadata_missing"});return}let g=t[p];if(!(!g||g.type!=="StripeSubscription")){if(!o)throw te(new Error("Auth provider required for subscription updates"));if(await r(d,{tier:g.tier,status:ie.ACTIVE,subscriptionEnd:Et(g.duration),subscriptionId:s,customerId:e.customer},o),g.onSubscriptionRenewed)try{await g.onSubscriptionRenewed(d,u.metadata||{})}catch(m){H.error("[Webhook] Hook failed (non-critical)",{error:m instanceof Error?m:new Error(String(m)),hookName:"onSubscriptionRenewed",userId:d,operation:"hook_execution"})}H.info("[Webhook] Subscription renewed",{userId:d,billingConfigKey:p,operation:"subscription_renewed"})}}i(tu,"handleInvoicePaymentSucceeded");async function ru(e,t,r,n){let{userId:o,billingConfigKey:s}=e.metadata||{};if(!o||!s)return;let u=t[s];if(!(!u||u.type!=="StripeSubscription")){if(!n)throw te(new Error("Auth provider required for subscription updates"));if(await r(o,{tier:tt.FREE,status:ie.CANCELED,subscriptionEnd:new Date(e.current_period_end*1e3).toISOString(),subscriptionId:e.id,customerId:e.customer},n),u.onSubscriptionCancelled)try{await u.onSubscriptionCancelled(o,e.metadata||{})}catch(d){H.error("[Webhook] Hook failed (non-critical)",{error:d instanceof Error?d:new Error(String(d)),hookName:"onSubscriptionCancelled",userId:o,operation:"hook_execution"})}H.info("[Webhook] Subscription cancelled",{userId:o,billingConfigKey:s,operation:"subscription_cancelled"})}}i(ru,"handleSubscriptionDeleted");async function nu(e,t){let{userId:r,billingConfigKey:n}=e.metadata||{};if(!r||!n){H.warn("[Webhook] Payment failed - missing metadata",{invoiceId:e.id,hasUserId:!!r,hasBillingConfigKey:!!n,operation:"payment_failed_metadata_missing"});return}let o=t[n];if(!o){H.error("[Webhook] Payment failed - unknown billing config",{error:new Error(`Unknown billing config key: ${n}`),userId:r,billingConfigKey:n,operation:"payment_failed_unknown_config"});return}if(o.type==="StripePayment"&&o.onPurchaseFailure)try{await o.onPurchaseFailure(r,e.metadata||{})}catch(s){H.error("[Webhook] Hook failed (non-critical)",{error:s instanceof Error?s:new Error(String(s)),hookName:"onPurchaseFailure",userId:r,operation:"hook_execution"})}if(o.type==="StripeSubscription"&&o.onPaymentFailed)try{await o.onPaymentFailed(r,e.metadata||{})}catch(s){H.error("[Webhook] Hook failed (non-critical)",{error:s instanceof Error?s:new Error(String(s)),hookName:"onPaymentFailed",userId:r,operation:"hook_execution"})}H.warn("[Webhook] Payment failed",{userId:r,billingConfigKey:n,operation:"payment_failed"})}i(nu,"handlePaymentFailed");$();async function iu(e,t,r){let n=tn(e);if(!n.success)return{success:!1,error:`Invalid email request: ${n.issues?.map(g=>g.message).join(", ")}`};let o=t.templates[e.templateId];if(!o)return{success:!1,error:`Template not found: ${e.templateId}`};let s=e.locale||"fr",u=o.subject(e.data,s),d=o.html(e.data,s);return{success:!0,messageId:(await r.send({from:e.from||t.defaultFrom,to:e.to,subject:u,html:d,replyTo:e.replyTo||t.replyTo})).messageId}}i(iu,"handleEmailRequest");var ou="https://api.resend.com/emails";function su(e){if(!e)throw new Error("Resend API key is required");return{async send({from:t,to:r,subject:n,html:o,replyTo:s}){let u={from:t,to:r,subject:n,html:o};s&&(u.reply_to=s);let d=await fetch(ou,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(u)});if(!d.ok){let g=await d.text().catch(()=>"Unknown error");throw new Error(`Resend API error (${d.status}): ${g}`)}return{messageId:(await d.json()).id}}}}i(su,"createResendProvider");async function Vv(e,t){let{code:r,redirectUri:n,codeVerifier:o}=e;return await t.exchangeCodeForToken({code:r,redirectUri:n,codeVerifier:o})}i(Vv,"exchangeTokenAlgorithm");async function Hv(e,t,r,n,o){return await o.grantAccess({userId:e,provider:t,accessToken:r,refreshToken:n})}i(Hv,"grantAccessAlgorithm");function Sr(e){return{seconds:Math.floor(e.getTime()/1e3),nanoseconds:e.getTime()%1e3*1e6,toDate:i(()=>new Date(e),"toDate"),toMillis:i(()=>e.getTime(),"toMillis"),isEqual:i(t=>t.seconds===Math.floor(e.getTime()/1e3)&&t.nanoseconds===e.getTime()%1e3*1e6,"isEqual"),valueOf:i(()=>`Timestamp(seconds=${Math.floor(e.getTime()/1e3)}, nanoseconds=${e.getTime()%1e3*1e6})`,"valueOf")}}i(Sr,"createTimestamp");function au(e){try{if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid date string format: ${e}`);return Sr(t)}if(e instanceof Date){if(isNaN(e.getTime()))throw new Error("Invalid Date object");return Sr(e)}throw new Error("Date must be a string or Date object")}catch(t){throw new Error(`Failed to convert to timestamp: ${t instanceof Error?t.message:"Unknown error"}`)}}i(au,"toTimestamp");function uu(e){return e.toDate().toISOString()}i(uu,"toISOString");function No(e){return e&&typeof e=="object"&&typeof e.seconds=="number"&&typeof e.nanoseconds=="number"&&typeof e.toDate=="function"&&typeof e.toMillis=="function"}i(No,"isTimestamp");function Rt(e,t=!1){if(!e)return e;if(t&&typeof e=="object"&&e!==null&&"id"in e&&"ref"in e&&"data"in e&&typeof e.data=="function"){let r=e,n=r.data();return{id:r.id,...Rt(n)}}if(Array.isArray(e))return e.map(r=>Rt(r));if(No(e))return uu(e);if(typeof e=="object"&&e!==null){let r={};for(let[n,o]of Object.entries(e))r[n]=Rt(o);return r}return e}i(Rt,"transformFirestoreData");function xr(e,t=[]){if(!e)return e;if(Array.isArray(e))return e.map(r=>xr(r,t));if(typeof e=="object"&&e!==null){let r={};for(let[n,o]of Object.entries(e))t.includes(n)||(o instanceof Date?r[n]=o.toISOString():r[n]=xr(o,t));return r}return e instanceof Date?e.toISOString():e}i(xr,"prepareForFirestore");export{Oh as DEFAULT_RATE_LIMITS,w as DoNotDevError,ar as GitHubApiService,co as StripeValidationSchemas,rh as assertAdmin,Aa as assertAuthenticated,hr as calculateCost,Et as calculateSubscriptionEndDate,wa as cancelUserSubscription,dh as checkIdempotency,bh as checkPaymentFailureRate,Eh as checkPaymentVolume,Th as checkRateLimit,Ih as checkRateLimitWithFirestore,Wa as classifyAIError,xh as cleanupOldMetrics,pv as createCheckoutAlgorithm,zs as createFirebaseCallable,Tg as createFirebaseFunction,_g as createFirebaseFunctionExports,sg as createGitHubApiService,cg as createMetadata,su as createResendProvider,Sr as createTimestamp,Lg as createVercelApiHandler,Ig as createVercelFunction,Mg as createVercelHandler,Vv as exchangeTokenAlgorithm,Fa as executeBulk,fg as filterVisibleFields,jy as findReferences,Sh as getPaymentMetricsSummary,Dh as getRateLimitStatus,ka as getTierFromPriceId,Ra as getUserSubscription,Hs as getVisibleFields,Hv as grantAccessAlgorithm,ja as handleAIRequest,iu as handleEmailRequest,te as handleError,ah as initializeFirebaseAdmin,Gs as isFieldVisible,No as isTimestamp,za as mapClassifiedToHTTP,xr as prepareForFirestore,Dv as processWebhook,vh as recordPaymentMetrics,Ch as resetRateLimit,Ph as resetRateLimitInFirestore,Ha as resolveModelForTier,Mh as safeJsonParse,fh as storeIdempotencyResult,Ly as toISOString,au as toTimestamp,Rt as transformFirestoreData,lg as updateMetadata,Xa as updateUserSubscription,Lh as validateCollectionName,Bh as validateDocument,Eg as validateEmail,bg as validateGitHubUsername,wg as validateMetadata,vg as validatePurchaseRequest,dt as validateRequestData,Uh as validateStripeEnvironment,Sg as validateStripePriceId,xg as validateStripeSessionId,kg as validateUrl,hg as validateWebhookEvent,Pa as verifyAuthToken,nh as verifyFirebaseAuthToken,Ia as verifyToken,ur as withSchemaValidation,cr as withVercelSchemaValidation};
|
|
21
|
+
import{A as E,B as F,C as G,D as O,E as P,F as Q,G as aa,H as ba,I as ca,J as Da,K as Ea,L as Fa,M as Ga,N as Ha,O as Ia,P as Ja,a as c,b as d,c as g,d as h,e as i,f as j,g as k,h as l,i as m,j as n,k as o,l as p,m as q,n as r,o as s,p as t,q as u,r as v,s as w,t as x,u as y,v as z,w as A,x as B,y as C,z as D}from"../chunks/chunk-US2VOP4S.js";import{c as va,d as ya,e as za,f as Aa}from"../chunks/chunk-YTKDNZNW.js";import{a as e,b as f,c as da,d as Ba,e as Ca}from"../chunks/chunk-MQANUSY3.js";import{B as ua,C as wa,D as xa,a as b,b as H,c as I,d as J,e as K,f as L,g as M,h as N,i as ea,j as fa,k as ga,l as ha,m as ia,p as ja,q as ka,r as la,s as ma,t as na,u as oa,v as pa,w as qa,x as ra,y as sa,z as ta}from"../chunks/chunk-LCDLG4VG.js";import"../chunks/chunk-CXBSROEW.js";import{L as a}from"../chunks/chunk-GYTCWMXV.js";import{a as R,b as S,c as T,d as U,e as V}from"../chunks/chunk-5IPULSUX.js";import{a as W,b as X,c as Y,d as Z,e as _,f as $}from"../chunks/chunk-3F4BWKQD.js";import"../chunks/chunk-PWAGW4R6.js";import"../chunks/chunk-AYY7UXNI.js";export{H as AuthBackendSchema,$ as DEFAULT_RATE_LIMITS,a as DoNotDevError,c as GitHubApiService,ja as MIN_ORDER_API_VERSION,ka as ORDER_ID_METADATA_KEY,la as PRODUCT_ID_METADATA_KEY,sa as RESERVATION_LEASE_MS,ra as ReservationLostError,j as StripeValidationSchemas,wa as WEBHOOK_EVENTS_SQL,ta as WEBHOOK_EVENT_RETENTION_MS,K as assertAdmin,J as assertAuthenticated,ea as calculateCost,C as calculateSubscriptionEndDate,F as cancelUserSubscription,P as checkIdempotency,S as checkPaymentFailureRate,T as checkPaymentVolume,W as checkRateLimit,X as checkRateLimitWithFirestore,ha as classifyAIError,V as cleanupOldMetrics,pa as createCheckoutAlgorithm,x as createFirebaseCallable,v as createFirebaseFunction,y as createFirebaseFunctionExports,va as createFirestoreIdempotencyStore,d as createGitHubApiService,za as createIdempotencyStore,ya as createInMemoryIdempotencyStore,e as createMetadata,Ca as createResendProvider,xa as createSupabaseIdempotencyStore,Fa as createTimestamp,A as createVercelApiHandler,w as createVercelFunction,z as createVercelHandler,Da as exchangeTokenAlgorithm,da as executeBulk,i as filterVisibleFields,D as findReferences,U as getPaymentMetricsSummary,_ as getRateLimitStatus,E as getTierFromPriceId,G as getUserSubscription,h as getVisibleFields,Ea as grantAccessAlgorithm,fa as handleAIRequest,Ba as handleEmailRequest,b as handleError,oa as handleOrderSessionEvent,O as initializeFirebaseAdmin,g as isFieldVisible,Ha as isTimestamp,na as listPaidLineItems,ia as mapClassifiedToHTTP,I as parseAuthBackend,Ja as prepareForFirestore,ua as processWebhook,R as recordPaymentMetrics,Aa as resetIdempotencyStore,Y as resetRateLimit,Z as resetRateLimitInFirestore,ga as resolveModelForTier,aa as safeJsonParse,Q as storeIdempotencyResult,ma as toCheckoutSessionSnapshot,B as toISOString,Ga as toTimestamp,Ia as transformFirestoreData,f as updateMetadata,qa as updateUserSubscription,ba as validateCollectionName,ca as validateDocument,n as validateEmail,m as validateGitHubUsername,r as validateMetadata,l as validatePurchaseRequest,s as validateRequestData,o as validateStripePriceId,p as validateStripeSessionId,q as validateUrl,k as validateWebhookEvent,M as verifyAuthToken,N as verifyFirebaseAuthToken,L as verifyToken,t as withSchemaValidation,u as withVercelSchemaValidation};
|
|
27
22
|
//# sourceMappingURL=index.js.map
|