@donotdev/functions 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +1 -1
  2. package/lib/chunks/{chunk-5IPULSUX.js → chunk-2A4FPYNB.js} +2 -2
  3. package/lib/chunks/chunk-2IFFIUFV.js +23 -0
  4. package/lib/chunks/{chunk-CXBSROEW.js.map → chunk-2IFFIUFV.js.map} +3 -3
  5. package/lib/chunks/chunk-FQSQGOBN.js +22 -0
  6. package/lib/chunks/chunk-FQSQGOBN.js.map +7 -0
  7. package/lib/chunks/chunk-G4FO76EA.js +22 -0
  8. package/lib/chunks/{chunk-GYTCWMXV.js.map → chunk-G4FO76EA.js.map} +3 -3
  9. package/lib/chunks/{chunk-US2VOP4S.js → chunk-LSM5Y2E5.js} +2 -2
  10. package/lib/chunks/{chunk-MQANUSY3.js → chunk-M4JV2JCF.js} +2 -2
  11. package/lib/chunks/chunk-OZX5ZG44.js +22 -0
  12. package/lib/chunks/chunk-OZX5ZG44.js.map +7 -0
  13. package/lib/chunks/{chunk-3F4BWKQD.js → chunk-PJCJ5H2O.js} +2 -2
  14. package/lib/chunks/chunk-UYI56E6Q.js +151 -0
  15. package/lib/chunks/chunk-UYI56E6Q.js.map +7 -0
  16. package/lib/chunks/{chunk-OFQVO3FD.js → chunk-ZVHC2CAV.js} +2 -2
  17. package/lib/chunks/{monitoring-E7JBYBHQ.js → monitoring-UIDJS2KA.js} +2 -2
  18. package/lib/chunks/{rateLimiter-SQISLOP5.js → rateLimiter-WNWHI3B4.js} +2 -2
  19. package/lib/chunks/server-RYGEBS2B.js +22 -0
  20. package/lib/firebase/billing/index.d.ts +2 -2
  21. package/lib/firebase/index.d.ts +1 -1
  22. package/lib/firebase/index.js +1 -1
  23. package/lib/firebase/index.js.map +4 -4
  24. package/lib/firebase/registerCrudFunctions.d.ts +0 -5
  25. package/lib/shared/billing/checkoutPrice.d.ts +3 -6
  26. package/lib/shared/billing/createCheckout.d.ts +3 -3
  27. package/lib/shared/billing/firestoreIdempotency.d.ts +2 -2
  28. package/lib/shared/billing/idempotency.d.ts +3 -23
  29. package/lib/shared/billing/idempotencyContract.d.ts +0 -20
  30. package/lib/shared/index.js +1 -1
  31. package/lib/shared/utils/internal/auth.d.ts +1 -5
  32. package/lib/shared/utils.d.ts +0 -83
  33. package/lib/supabase/index.js +1 -1
  34. package/lib/vercel/api/index.js +1 -1
  35. package/package.json +2 -2
  36. package/src/firebase/baseFunction.ts +3 -2
  37. package/src/firebase/billing/index.d.ts +0 -12
  38. package/src/firebase/billing/index.ts +0 -3
  39. package/src/firebase/index.ts +0 -1
  40. package/src/firebase/oauth/disconnect.ts +2 -2
  41. package/src/firebase/oauth/exchangeToken.ts +2 -2
  42. package/src/firebase/oauth/getConnections.ts +2 -2
  43. package/src/firebase/oauth/githubAccess.ts +4 -4
  44. package/src/firebase/oauth/refreshToken.ts +2 -2
  45. package/src/firebase/registerCrudFunctions.ts +0 -19
  46. package/src/shared/__tests__/idempotency.test.ts +0 -32
  47. package/src/shared/__tests__/utils.test.ts +0 -25
  48. package/src/shared/billing/__tests__/createCheckout.compat.test.ts +4 -110
  49. package/src/shared/billing/checkoutPrice.ts +7 -42
  50. package/src/shared/billing/createCheckout.ts +3 -19
  51. package/src/shared/billing/firestoreIdempotency.ts +2 -21
  52. package/src/shared/billing/idempotency.ts +4 -54
  53. package/src/shared/billing/idempotencyContract.ts +0 -21
  54. package/src/shared/utils/internal/auth.ts +1 -6
  55. package/src/shared/utils.ts +0 -131
  56. package/lib/chunks/chunk-6USHTJED.js +0 -22
  57. package/lib/chunks/chunk-6USHTJED.js.map +0 -7
  58. package/lib/chunks/chunk-CXBSROEW.js +0 -23
  59. package/lib/chunks/chunk-GYTCWMXV.js +0 -22
  60. package/lib/chunks/chunk-LCDLG4VG.js +0 -151
  61. package/lib/chunks/chunk-LCDLG4VG.js.map +0 -7
  62. package/lib/chunks/chunk-YTKDNZNW.js +0 -22
  63. package/lib/chunks/chunk-YTKDNZNW.js.map +0 -7
  64. package/lib/chunks/server-IQ5JNJOM.js +0 -22
  65. /package/lib/chunks/{chunk-5IPULSUX.js.map → chunk-2A4FPYNB.js.map} +0 -0
  66. /package/lib/chunks/{chunk-US2VOP4S.js.map → chunk-LSM5Y2E5.js.map} +0 -0
  67. /package/lib/chunks/{chunk-MQANUSY3.js.map → chunk-M4JV2JCF.js.map} +0 -0
  68. /package/lib/chunks/{chunk-3F4BWKQD.js.map → chunk-PJCJ5H2O.js.map} +0 -0
  69. /package/lib/chunks/{chunk-OFQVO3FD.js.map → chunk-ZVHC2CAV.js.map} +0 -0
  70. /package/lib/chunks/{monitoring-E7JBYBHQ.js.map → monitoring-UIDJS2KA.js.map} +0 -0
  71. /package/lib/chunks/{rateLimiter-SQISLOP5.js.map → rateLimiter-WNWHI3B4.js.map} +0 -0
  72. /package/lib/chunks/{server-IQ5JNJOM.js.map → server-RYGEBS2B.js.map} +0 -0
@@ -32,9 +32,4 @@ export type CrudFunctions = Record<string, HttpsFunction>;
32
32
  * ```
33
33
  */
34
34
  export declare function createCrudFunctions(entities: Record<string, Entity | unknown>, options?: RegisterOptions): CrudFunctions;
35
- /**
36
- * @deprecated Use createCrudFunctions() for ESM. This mutates target which doesn't work in ESM.
37
- * Auto-register CRUD functions for all entities (CJS pattern)
38
- */
39
- export declare function registerCrudFunctions(entities: Record<string, Entity | unknown>, target?: Record<string, any>, options?: RegisterOptions): CrudFunctions;
40
35
  export {};
@@ -11,16 +11,13 @@ import type Stripe from 'stripe';
11
11
  import type { CheckoutMode, CheckoutSessionParams, CreateCheckoutSessionRequest, StripePaymentBackItem, StripeSubscriptionBackItem } from '@donotdev/core/server';
12
12
  /** Price resolved for a single-price item (0.1.x rules). */
13
13
  export interface PricePlan {
14
- /** Fixed price charged; undefined for dynamic pricing */
15
- priceId?: string;
16
- /** 0.1.x dynamic pricing (client unitAmount + productName) */
17
- dynamic: boolean;
14
+ /** Price charged */
15
+ priceId: string;
18
16
  mode: CheckoutMode;
19
17
  }
20
18
  /**
21
19
  * 0.1.x pricing for StripePayment/StripeSubscription: a request priceId (must
22
- * match the config priceId when set), else 0.1.x dynamic pricing capped by
23
- * `maxUnitAmount`, else the back-config priceId.
20
+ * match the config priceId when set), else the back-config priceId.
24
21
  */
25
22
  export declare function resolvePricePlan(item: StripePaymentBackItem | StripeSubscriptionBackItem, request: CreateCheckoutSessionRequest): PricePlan;
26
23
  /** 0.1.x params → Stripe params (what the 0.1.x Firebase/Supabase providers sent). */
@@ -2,7 +2,7 @@
2
2
  * @fileoverview Create Checkout Session Algorithm
3
3
  * @description Platform-agnostic algorithm for creating Stripe checkout sessions.
4
4
  * StripePayment/StripeSubscription items keep the 0.1.x behaviour (request or
5
- * back-config priceId, 0.1.x dynamic pricing). StripeOrder items are priced on
5
+ * back-config priceId). StripeOrder items are priced on
6
6
  * the server (`resolveLineItems`) and need a {@link StripeSessionProvider}.
7
7
  *
8
8
  * @version 0.2.0
@@ -64,8 +64,8 @@ export interface AuthCheckoutProvider {
64
64
  * Create checkout session algorithm
65
65
  *
66
66
  * 1. Resolve the billing config item and verify the user
67
- * 2. Single-price items: 0.1.x pricing (request/back-config priceId, dynamic pricing)
68
- * 3. `beforeCheckout` hook (block/allow; 0.1.x dynamic-pricing overrides)
67
+ * 2. Single-price items: 0.1.x pricing (request/back-config priceId)
68
+ * 3. `beforeCheckout` hook (block/allow)
69
69
  * 4. StripeOrder: reject inclusive manual Tax Rates, `resolveLineItems` prices every line
70
70
  * and may set per-order session options (`ResolvedOrder.session`: tax rates,
71
71
  * payment methods, expiry, invoice footer)
@@ -1,4 +1,4 @@
1
- import type { LegacyIdempotencyStore } from './idempotencyContract.js';
1
+ import type { IdempotencyStore } from './idempotencyContract.js';
2
2
  /**
3
3
  * Firestore-backed store (transactions). Collection: `webhook_idempotency`.
4
4
  *
@@ -10,4 +10,4 @@ import type { LegacyIdempotencyStore } from './idempotencyContract.js';
10
10
  * @since 0.2.0
11
11
  * @author AMBROISE PARK Consulting
12
12
  */
13
- export declare function createFirestoreIdempotencyStore(): LegacyIdempotencyStore;
13
+ export declare function createFirestoreIdempotencyStore(): IdempotencyStore;
@@ -1,6 +1,6 @@
1
- import type { LegacyIdempotencyStore } from './idempotencyContract.js';
1
+ import type { IdempotencyStore } from './idempotencyContract.js';
2
2
  export { RESERVATION_LEASE_MS, ReservationLostError, WEBHOOK_EVENT_RETENTION_MS, } from './idempotencyContract.js';
3
- export type { IdempotencyStore, LegacyIdempotencyStore, ReservationResult, } from './idempotencyContract.js';
3
+ export type { IdempotencyStore, ReservationResult, } from './idempotencyContract.js';
4
4
  export { createFirestoreIdempotencyStore } from './firestoreIdempotency.js';
5
5
  /**
6
6
  * In-memory store. Single process only: for tests, never for a deployed webhook.
@@ -9,25 +9,5 @@ export { createFirestoreIdempotencyStore } from './firestoreIdempotency.js';
9
9
  * @since 0.2.0
10
10
  * @author AMBROISE PARK Consulting
11
11
  */
12
- export declare function createInMemoryIdempotencyStore(): LegacyIdempotencyStore;
13
- /**
14
- * 0.1.x store auto-detection: Firestore when configured, else in-memory.
15
- *
16
- * @deprecated In-memory is not durable across instances. Pass an explicit store:
17
- * {@link createFirestoreIdempotencyStore} or `createSupabaseIdempotencyStore`.
18
- * Framework webhook entry points already do.
19
- * @version 0.2.0
20
- * @since 0.0.1
21
- * @author AMBROISE PARK Consulting
22
- */
23
- export declare function createIdempotencyStore(): LegacyIdempotencyStore;
24
- /**
25
- * Reset the store cached by {@link createIdempotencyStore} (tests).
26
- *
27
- * @deprecated See {@link createIdempotencyStore}.
28
- * @version 0.1.0
29
- * @since 0.0.1
30
- * @author AMBROISE PARK Consulting
31
- */
32
- export declare function resetIdempotencyStore(): void;
12
+ export declare function createInMemoryIdempotencyStore(): IdempotencyStore;
33
13
  export { WEBHOOK_EVENTS_SQL, createSupabaseIdempotencyStore, } from './supabaseIdempotency.js';
@@ -48,26 +48,6 @@ export interface IdempotencyStore {
48
48
  */
49
49
  release(eventId: string, ownerToken: string): Promise<boolean>;
50
50
  }
51
- /**
52
- * Store with the 0.1.x accessors.
53
- *
54
- * @deprecated Use {@link IdempotencyStore}: `reserve` returns three states and
55
- * an owner token; `checkAndReserve` and `isProcessed` do not.
56
- * @version 0.2.0
57
- * @since 0.2.0
58
- * @author AMBROISE PARK Consulting
59
- */
60
- export interface LegacyIdempotencyStore extends IdempotencyStore {
61
- /** 0.1.x: `true` when the event must be skipped (processed or live lease). */
62
- checkAndReserve(eventId: string): Promise<boolean>;
63
- /** Whether the event was processed (non-atomic read). */
64
- isProcessed(eventId: string): Promise<boolean>;
65
- /**
66
- * Mark processed. Without `ownerToken` (0.1.x call) the write is unconditional.
67
- * @throws {ReservationLostError} When `ownerToken` is given and no longer owns the event
68
- */
69
- markProcessed(eventId: string, ownerToken?: string): Promise<void>;
70
- }
71
51
  /**
72
52
  * Thrown by `markProcessed` when the caller no longer owns the reservation:
73
53
  * its lease expired and another delivery retook the event, or the row is gone.
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
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};
21
+ import{A as E,B as F,C as G,D as N,E as O,F as P,G as $,H as aa,I as ba,J as Aa,K as Ba,L as Ca,M as Da,N as Ea,O as Fa,P as Ga,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-LSM5Y2E5.js";import{a as H,b as I,c as J,d as K,e as L,f as M,g as ua,h as xa}from"../chunks/chunk-OZX5ZG44.js";import{a as e,b as f,c as ca,d as ya,e as za}from"../chunks/chunk-M4JV2JCF.js";import{a as b,b as da,c as ea,d as fa,e as ga,f as ha,i as ia,j as ja,k as ka,l as la,m as ma,n as na,o as oa,p as pa,q as qa,r as ra,s as sa,u as ta,v as va,w as wa}from"../chunks/chunk-UYI56E6Q.js";import"../chunks/chunk-2IFFIUFV.js";import{L as a}from"../chunks/chunk-G4FO76EA.js";import{a as Q,b as R,c as S,d as T,e as U}from"../chunks/chunk-2A4FPYNB.js";import{a as V,b as W,c as X,d as Y,e as Z,f as _}from"../chunks/chunk-PJCJ5H2O.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,ia as MIN_ORDER_API_VERSION,ja as ORDER_ID_METADATA_KEY,ka as PRODUCT_ID_METADATA_KEY,ra as RESERVATION_LEASE_MS,qa as ReservationLostError,j as StripeValidationSchemas,va as WEBHOOK_EVENTS_SQL,sa as WEBHOOK_EVENT_RETENTION_MS,K as assertAdmin,J as assertAuthenticated,da as calculateCost,C as calculateSubscriptionEndDate,F as cancelUserSubscription,O as checkIdempotency,R as checkPaymentFailureRate,S as checkPaymentVolume,V as checkRateLimit,W as checkRateLimitWithFirestore,ga as classifyAIError,U as cleanupOldMetrics,oa as createCheckoutAlgorithm,x as createFirebaseCallable,v as createFirebaseFunction,y as createFirebaseFunctionExports,ua as createFirestoreIdempotencyStore,d as createGitHubApiService,xa as createInMemoryIdempotencyStore,e as createMetadata,za as createResendProvider,wa as createSupabaseIdempotencyStore,Ca as createTimestamp,A as createVercelApiHandler,w as createVercelFunction,z as createVercelHandler,Aa as exchangeTokenAlgorithm,ca as executeBulk,i as filterVisibleFields,D as findReferences,T as getPaymentMetricsSummary,Z as getRateLimitStatus,E as getTierFromPriceId,G as getUserSubscription,h as getVisibleFields,Ba as grantAccessAlgorithm,ea as handleAIRequest,ya as handleEmailRequest,b as handleError,na as handleOrderSessionEvent,N as initializeFirebaseAdmin,g as isFieldVisible,Ea as isTimestamp,ma as listPaidLineItems,ha as mapClassifiedToHTTP,I as parseAuthBackend,Ga as prepareForFirestore,ta as processWebhook,Q as recordPaymentMetrics,X as resetRateLimit,Y as resetRateLimitInFirestore,fa as resolveModelForTier,$ as safeJsonParse,P as storeIdempotencyResult,la as toCheckoutSessionSnapshot,B as toISOString,Da as toTimestamp,Fa as transformFirestoreData,f as updateMetadata,pa as updateUserSubscription,aa as validateCollectionName,ba 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,L as verifyToken,t as withSchemaValidation,u as withVercelSchemaValidation};
22
22
  //# sourceMappingURL=index.js.map
@@ -45,7 +45,7 @@ export declare function parseAuthBackend(backend: unknown): AuthProvider;
45
45
  * @since 0.0.1
46
46
  * @author AMBROISE PARK Consulting
47
47
  */
48
- export declare function assertAuthenticated(uid: string): string;
48
+ export declare function assertAuthenticated(uid: string | undefined): string;
49
49
  /**
50
50
  * Validates that user has admin privileges.
51
51
  * Uses IServerAuthAdapter when configured, falls back to Firebase Admin SDK.
@@ -88,7 +88,3 @@ export declare function verifyToken(token: string, provider?: AuthProvider): Pro
88
88
  * @author AMBROISE PARK Consulting
89
89
  */
90
90
  export declare function verifyAuthToken(req: NextApiRequest, provider?: AuthProvider): Promise<string>;
91
- /**
92
- * @deprecated Use verifyAuthToken instead. Kept for backwards compatibility.
93
- */
94
- export declare const verifyFirebaseAuthToken: typeof verifyAuthToken;
@@ -1,21 +1,6 @@
1
1
  import { DoNotDevError } from '@donotdev/core/server';
2
2
  import type { UserRole } from '@donotdev/core/server';
3
3
  export { DoNotDevError };
4
- /**
5
- * Assert that a user is authenticated from a Firebase callable auth context.
6
- *
7
- * @deprecated Import `assertAuthenticated` from `@donotdev/functions/shared/utils/internal/auth` instead.
8
- * This wrapper extracts uid from a Firebase callable auth context and delegates
9
- * to the canonical version.
10
- *
11
- * @param auth - Firebase callable request auth context (object with `.uid`)
12
- * @returns The authenticated user's uid
13
- *
14
- * @version 0.1.0
15
- * @since 0.0.1
16
- * @author AMBROISE PARK Consulting
17
- */
18
- export declare function assertAuthenticated(auth: any): string;
19
4
  /**
20
5
  * Get user role from Firebase auth context
21
6
  *
@@ -59,74 +44,6 @@ export declare function createErrorResponse(error: unknown): {
59
44
  details?: any;
60
45
  };
61
46
  };
62
- /**
63
- * Updates user subscription in Firebase.
64
- *
65
- * **Architecture decision — throwing stubs for billing functions:**
66
- * These subscription functions (`updateUserSubscription`, `getUserSubscription`,
67
- * `cancelUserSubscription`, `handleSubscriptionCancellation`) are intentional
68
- * placeholder implementations. They exist so the framework compiles and
69
- * type-checks out of the box, but throw at runtime to surface missing
70
- * integration early. Consumer apps replace them with their billing provider
71
- * integration (Stripe, Paddle, LemonSqueezy, etc.) via the documented
72
- * `shared/billing/helpers/` modules.
73
- *
74
- * C10: This was a silent no-op stub. It now throws to surface the missing
75
- * implementation at startup rather than silently dropping webhook events.
76
- * Use `updateUserSubscription` from `shared/billing/helpers/updateUserSubscription.ts`
77
- * (which requires an authProvider) instead.
78
- *
79
- * @deprecated Import `updateUserSubscription` from `@donotdev/functions/shared/billing/helpers/updateUserSubscription`.
80
- * @version 0.1.0
81
- * @since 0.0.1
82
- * @author AMBROISE PARK Consulting
83
- */
84
- export declare function updateUserSubscription(_firebaseUid: string, _subscription: any): Promise<void>;
85
- /**
86
- * Gets user subscription from Firebase.
87
- *
88
- * C10: This was a silent no-op stub. Now throws to surface the missing implementation.
89
- *
90
- * @deprecated Import from `@donotdev/functions/shared/billing/helpers` or implement directly using Firebase Admin SDK / Stripe API.
91
- * @version 0.1.0
92
- * @since 0.0.1
93
- * @author AMBROISE PARK Consulting
94
- */
95
- export declare function getUserSubscription(_firebaseUid: string): Promise<any>;
96
- /**
97
- * Cancels user subscription.
98
- *
99
- * C10: This was a silent no-op stub. Now throws to surface the missing implementation.
100
- *
101
- * @deprecated Import `cancelUserSubscription` from `@donotdev/functions/shared/billing/helpers/subscriptionManagement`.
102
- * @version 0.1.0
103
- * @since 0.0.1
104
- * @author AMBROISE PARK Consulting
105
- */
106
- export declare function cancelUserSubscription(_firebaseUid: string, _subscription: any): Promise<void>;
107
- /**
108
- * Handles subscription cancellation.
109
- *
110
- * C10: This was a silent no-op stub. Now throws to surface the missing implementation.
111
- *
112
- * @deprecated Handle via Stripe webhook events. Use `processWebhook` from `@donotdev/functions/shared/billing/webhookHandler`.
113
- * @version 0.1.0
114
- * @since 0.0.1
115
- * @author AMBROISE PARK Consulting
116
- */
117
- export declare function handleSubscriptionCancellation(_firebaseUid: string, _subscription: any): Promise<void>;
118
- /**
119
- * Asserts that a user has admin privileges
120
- * Uses role hierarchy: super > admin > user > guest
121
- *
122
- * @deprecated Import `assertAdmin` from `@donotdev/functions/shared/utils/internal/auth` instead.
123
- * This is a thin wrapper that delegates to the canonical provider-agnostic version.
124
- *
125
- * @version 0.1.0
126
- * @since 0.0.1
127
- * @author AMBROISE PARK Consulting
128
- */
129
- export declare function assertAdmin(uid: string): Promise<string>;
130
47
  /**
131
48
  * Validates document data
132
49
  *
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{c as Re}from"../chunks/chunk-6USHTJED.js";import{a as Ee,b as ve,c as tt,d as Be,e as Ue}from"../chunks/chunk-MQANUSY3.js";import{a as j,b as ke,c as Fe}from"../chunks/chunk-HLNYUAZH.js";import{a as M,b as Z,c as be,d as st,e as it,f as at}from"../chunks/chunk-OFQVO3FD.js";import{B as ot,C as jt,D as Oe,j as rt,k as Ot,l as Bt,m as Ut,o as Ft,v as De,w as nt,x as qt}from"../chunks/chunk-LCDLG4VG.js";import{A as I,B as Ve,C as Ye,G as ze,I as Qe,J as We,L as A,P as Ge,Q as te,T as W,X as re,Y as Je,Z as Ze,aa as ne,ba as Xe,ca as et,h as x,i as Le,l as Se,m as H,n as z,q as He,r as R,s as P,t as Q,u as ee,v as w,w as ae,y as Ne}from"../chunks/chunk-GYTCWMXV.js";import"../chunks/chunk-PWAGW4R6.js";import{a as s}from"../chunks/chunk-AYY7UXNI.js";import{createClient as Lt}from"@supabase/supabase-js";async function qe(e,t){try{let{error:n}=await e.from("operation_metrics").insert({operation:t.operation,user_id:t.userId||null,status:t.status,duration_ms:t.durationMs||null,metadata:t.metadata||null,error_code:t.errorCode||null,error_message:t.errorMessage||null});n&&console.error("[monitoring] Record failed:",n)}catch(n){console.error("[monitoring] Record failed:",n)}}s(qe,"recordOperationMetrics");async function $t(e,t,n=24){try{let r=new Date;r.setHours(r.getHours()-n);let{data:i,error:c}=await e.from("operation_metrics").select("status").eq("operation",t).gte("timestamp",r.toISOString());return c||!i||i.length===0?0:i.filter(a=>a.status==="failed").length/i.length*100}catch(r){return console.error("[monitoring] Get failure rate failed:",r),0}}s($t,"getFailureRate");async function Mt(e,t,n=24){try{let r=new Date;r.setHours(r.getHours()-n);let{data:i,error:c}=await e.from("operation_metrics").select("operation").eq("user_id",t).gte("timestamp",r.toISOString());if(c||!i)return{};let o={};for(let a of i)o[a.operation]=(o[a.operation]||0)+1;return o}catch(r){return console.error("[monitoring] Get operation counts failed:",r),{}}}s(Mt,"getOperationCounts");async function Kt(e,t,n=24){try{let r=new Date;r.setHours(r.getHours()-n);let{data:i,error:c}=await e.from("operation_metrics").select("operation, duration_ms").gte("timestamp",r.toISOString()).not("duration_ms","is",null);if(c||!i)return[];let o={};for(let u of i)u.duration_ms&&(o[u.operation]||(o[u.operation]={sum:0,count:0}),o[u.operation].sum+=u.duration_ms,o[u.operation].count+=1);let a=[];for(let[u,m]of Object.entries(o)){let p=m.sum/m.count;p>=t&&a.push({operation:u,avgDuration:Math.round(p),count:m.count})}return a.sort((u,m)=>m.avgDuration-u.avgDuration)}catch(r){return console.error("[monitoring] Get slow operations failed:",r),[]}}s(Kt,"getSlowOperations");function h(e,t,n,r="user",i){return async c=>{try{let o=oe("ALLOWED_ORIGIN","*"),a=s((T,O)=>ct(T,O,o),"respond");if(c.method==="OPTIONS")return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":o,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"authorization, content-type, x-client-info, apikey"}});if(c.method!=="POST")return a({error:"Method not allowed"},405);let u=c.headers.get("authorization");if(!u?.startsWith("Bearer "))return a({error:"Missing or invalid authorization header"},401);let m=u.slice(7),p=Ht("SUPABASE_URL"),f=oe("SUPABASE_SECRET_KEY")||oe("SUPABASE_SERVICE_ROLE_KEY");if(!f)throw new Error("Missing environment variable: SUPABASE_SECRET_KEY or SUPABASE_SERVICE_ROLE_KEY");let g=Lt(p,f,{auth:{autoRefreshToken:!1,persistSession:!1}}),{data:{user:S},error:C}=await g.auth.getUser(m);if(C||!S)return a({error:"Invalid or expired token"},401);let d=(S.app_metadata??{}).role||"user";if(r!=="guest"){if(!W(d,r))return a({error:`Access denied. Required role: ${r}, your role: ${d}`},403)}if(!(oe("DISABLE_RATE_LIMITING")==="true")){let T=r==="guest"&&S.id==="guest"?`ip_${Vt(c)}`:`uid_${S.id}`,O=`${e}_${T}`,L=ke[e]||ke.api,B=await Fe(g,O,L);if(!B.allowed)return i?.audit({type:"rate_limit.exceeded",userId:S.id,metadata:{operation:e,remaining:0}}),a({error:`Rate limit exceeded. Try again in ${B.blockRemainingSeconds} seconds.`},429)}let b=c.headers.get("content-length"),E=1048576;if(b&&parseInt(b,10)>E)return a({error:`Request body too large. Maximum size: ${E} bytes`},413);let K=await c.json().catch(()=>({})),k=Ve(t,K);if(!k.success){let T=k.issues.map(O=>O.message).join(", ");return a({error:`Validation failed: ${T}`},400)}let V=oe("ENABLE_METRICS")==="true",Y=V?Date.now():0,$,F=null;try{$=await n(k.output,{uid:S.id,userRole:d,supabaseAdmin:g})}catch(T){throw F=T instanceof Error?T:new Error(String(T)),T}finally{if(V){let T=Date.now()-Y;await qe(g,{operation:e,userId:S.id,status:F?"failed":"success",durationMs:T,metadata:{requestId:c.headers.get("x-request-id")||void 0},errorCode:F?dt(F.message):void 0,errorMessage:F?F.message:void 0})}}if($ instanceof Response){let T=new Headers($.headers);return T.set("Access-Control-Allow-Origin",o),new Response($.body,{status:$.status,statusText:$.statusText,headers:T})}return a($,200)}catch(o){console.error(`[${e}] Error:`,o);let a=o instanceof Error?o.message:"Internal server error",u=dt(a),p=new Set(["rate-limit-exceeded","not-found","permission-denied","invalid-argument","already-exists"]).has(u)?a:"Internal server error",f=Yt(a),g=oe("ALLOWED_ORIGIN","*");return ct({error:p},f,g)}}}s(h,"createSupabaseHandler");function ct(e,t,n="*"){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":n}})}s(ct,"jsonResponse");function Ht(e){let t=typeof Deno<"u"?Deno.env.get(e):process.env[e];if(!t)throw new Error(`Missing environment variable: ${e}`);return t}s(Ht,"getEnvOrThrow");function oe(e,t=""){return(typeof Deno<"u"?Deno.env.get(e):process.env[e])||t}s(oe,"getEnv");var Nt=/^(?:\d{1,3}\.){3}\d{1,3}$|^[0-9a-fA-F:]{2,45}$/;function ut(e){return Nt.test(e)}s(ut,"isValidIp");function Vt(e){let t=e.headers.get("x-forwarded-for");if(t){let r=t.split(",").map(c=>c.trim()).filter(Boolean),i=r[r.length-1];if(i&&ut(i))return i}let n=e.headers.get("cf-connecting-ip");return n&&ut(n)?n:"unknown"}s(Vt,"getClientIp");function dt(e){return e.includes("Rate limit")?"rate-limit-exceeded":e.includes("not found")||e.includes("No active")?"not-found":e.includes("permission")||e.includes("denied")||e.includes("Forbidden")?"permission-denied":e.includes("mismatch")||e.includes("Invalid")||e.includes("Missing")?"invalid-argument":e.includes("already-exists")||e.includes("Duplicate")?"already-exists":"internal"}s(dt,"getErrorCode");function Yt(e){return e.includes("Rate limit")?429:e.includes("not found")||e.includes("No active")?404:e.includes("permission")||e.includes("denied")||e.includes("Forbidden")?403:e.includes("mismatch")||e.includes("Invalid")||e.includes("Missing")?400:500}s(Yt,"getErrorStatus");import{createClient as pt}from"@supabase/supabase-js";function ue(e,t){let n=t?.requireAuth??!0,r="authorization, content-type, x-client-info, apikey",i=t?.extraHeaders?.length?`${r}, ${t.extraHeaders.join(", ")}`:r;return async c=>{let o=ce("ALLOWED_ORIGIN")||"*",a=s((l,b)=>zt(l,b,o),"respond"),u=s((l,b=200)=>a(l,b),"json"),m=s((l,b=400)=>a({error:l},b),"error");if(c.method==="OPTIONS")return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":o,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":i}});if(c.method!=="POST")return m("Method not allowed",405);let p=ce("SUPABASE_URL"),f=ce("SUPABASE_SECRET_KEY")||ce("SUPABASE_SERVICE_ROLE_KEY");if(!p||!f)return console.error("Missing SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY"),m("Server misconfigured",500);let g=pt(p,f,{auth:{autoRefreshToken:!1,persistSession:!1}}),S=null,C=null,v=c.headers.get("authorization");if(v?.startsWith("Bearer ")){let l=v.slice(7),b=ce("SUPABASE_ANON_KEY");if(b){C=pt(p,b,{global:{headers:{Authorization:`Bearer ${l}`}}});let{data:E,error:K}=await g.auth.getUser(l);!K&&E.user&&(S={id:E.user.id,email:E.user.email??void 0})}}if(n&&!S)return m("Unauthorized",401);let d={user:S,supabaseAdmin:g,userClient:C,json:u,error:m,respond:a};try{return await e(c,d)}catch(l){return console.error("Edge function error:",l),m("Internal error",500)}}}s(ue,"createEdgeFunction");function zt(e,t,n){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":n}})}s(zt,"jsonResponse");function ce(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e)??"":typeof process<"u"?process.env[e]??"":""}s(ce,"getEnv");var Qt=R({});function Wt(){return h("delete-account",Qt,async(e,t)=>{let{error:n}=await t.supabaseAdmin.auth.admin.deleteUser(t.uid);if(n)throw n;return{success:!0}})}s(Wt,"createDeleteAccount");var Gt=R({customClaims:ee(w(),Ne()),idempotencyKey:P(w())}),Jt=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated","plan","tier","provider","providers","sub","iss","aud"]);function Zt(e){let t=new Set(e.allowedClaimKeys);for(let n of t)if(Jt.has(n))throw new Error(`Claim key "${n}" is blocked - it is a privilege-escalation vector and cannot be self-assigned.`);return h("set-custom-claims",Gt,async(n,r)=>{let i=Object.keys(n.customClaims).filter(p=>!t.has(p));if(i.length>0)throw new Error(`Claim keys not allowed: ${i.join(", ")}`);let{data:{user:c},error:o}=await r.supabaseAdmin.auth.admin.getUserById(r.uid);if(o||!c)throw new Error("User not found");let u={...c.app_metadata??{},...n.customClaims},{error:m}=await r.supabaseAdmin.auth.admin.updateUserById(r.uid,{app_metadata:u});if(m)throw m;return{success:!0,customClaims:u}},"user")}s(Zt,"createSetCustomClaims");var Xt=R({});function er(){return h("get-custom-claims",Xt,async(e,t)=>{let{data:{user:n},error:r}=await t.supabaseAdmin.auth.admin.getUserById(t.uid);if(r||!n)throw new Error("User not found");return{customClaims:n.app_metadata??{}}},"user")}s(er,"createGetCustomClaims");var tr=R({claimsToRemove:I(z(w()),x(1,"At least one claim key is required"))}),rr=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated","plan","tier","provider","providers","sub","iss","aud"]);function nr(){return h("remove-custom-claims",tr,async(e,t)=>{let n=e.claimsToRemove.filter(a=>rr.has(a));if(n.length>0)throw new Error(`Protected claims cannot be removed: ${n.join(", ")}`);let{data:{user:r},error:i}=await t.supabaseAdmin.auth.admin.getUserById(t.uid);if(i||!r)throw new Error("User not found");let c={...r.app_metadata??{}};for(let a of e.claimsToRemove)delete c[a];let{error:o}=await t.supabaseAdmin.auth.admin.updateUserById(t.uid,{app_metadata:c});if(o)throw o;return{success:!0,customClaims:c}},"user")}s(nr,"createRemoveCustomClaims");var or=R({});function sr(){return h("get-user-auth-status",or,async(e,t)=>{let{data:{user:n},error:r}=await t.supabaseAdmin.auth.admin.getUserById(t.uid);if(r||!n)throw new Error("User not found");return{uid:n.id,email:n.email,emailVerified:n.email_confirmed_at!=null,customClaims:n.app_metadata??{},disabled:n.banned_until!=null}},"user")}s(sr,"createGetUserAuthStatus");function ir(e){return h("create-checkout-session",ze,async(t,n)=>{M(ar()),be();let r=j(n.supabaseAdmin),i={async createStripeSession(c){let o=await Z.checkout.sessions.create(c);return{id:o.id,url:o.url}},async retrieveTaxRate(c){let o=await Z.taxRates.retrieve(c);return{id:o.id,inclusive:o.inclusive}}};return De(t,n.uid,i,r,e)})}s(ir,"createCheckoutSession");function ar(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}s(ar,"getStripeKey");function lt(e){let t=typeof Deno<"u"?Deno.env.get(e):process.env[e];if(!t)throw new Error(`Missing ${e} environment variable`);return t}s(lt,"getEnvOrThrow");function cr(e){return ue(async(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return n.error("Missing Stripe signature",400);M(lt("STRIPE_SECRET_KEY"));let i=await ot(await t.text(),r,lt("STRIPE_WEBHOOK_SECRET"),Z,e,nt,j(n.supabaseAdmin),Oe(n.supabaseAdmin));return n.json({received:!0,message:i.message})},{requireAuth:!1,extraHeaders:["stripe-signature"]})}s(cr,"createStripeWebhook");var ur=R({userId:I(w(),x(1,"User ID is required"))});function dr(){return h("cancel-subscription",ur,async(e,t)=>{M(pr());let n=j(t.supabaseAdmin);return st(e.userId,n)})}s(dr,"createCancelSubscription");function pr(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}s(pr,"getStripeKey");var lr=R({userId:I(w(),x(1,"User ID is required")),newPriceId:I(w(),x(1,"Price ID is required")),billingConfigKey:I(w(),x(1,"Billing config key is required"))});function fr(e){return h("change-plan",lr,async(t,n)=>{if(!W(n.userRole,"admin")&&t.userId!==n.uid)throw new Error("Forbidden: cannot change another user's plan");M(mr());let r=j(n.supabaseAdmin);return it(t.userId,t.newPriceId,t.billingConfigKey,e,r)})}s(fr,"createChangePlan");function mr(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}s(mr,"getStripeKey");var gr=R({userId:I(w(),x(1,"User ID is required")),returnUrl:P(I(w(),Se()))});function yr(){return h("create-customer-portal",gr,async(e,t)=>{M(hr());let n=j(t.supabaseAdmin);return at(e.userId,n,e.returnUrl)})}s(yr,"createCustomerPortal");function hr(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}s(hr,"getStripeKey");var wr=R({userId:I(w(),x(1,"User ID is required"))});function Sr(){return h("refresh-subscription-status",wr,async(e,t)=>{M(Er()),be();let n=j(t.supabaseAdmin),i=(await n.getUser(e.userId)).customClaims||{},c=i.subscription?.subscriptionId;if(!c)throw new Error("No active subscription found");let o=await Z.subscriptions.retrieve(c),a={...i,subscription:{...i.subscription,status:o.status,currentPeriodStart:new Date(o.current_period_start*1e3).toISOString(),currentPeriodEnd:new Date(o.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:o.cancel_at_period_end}};return await n.setCustomUserClaims(e.userId,a),{success:!0,userId:e.userId,status:o.status,currentPeriodEnd:new Date(o.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:o.cancel_at_period_end}})}s(Sr,"createRefreshSubscriptionStatus");function Er(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}s(Er,"getStripeKey");function mt(e){let t={};for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r.replace(/<[^>]*>/g,"").slice(0,1e3):typeof r=="object"&&r!==null&&!Array.isArray(r)?t[n]=mt(r):t[n]=r;return t}s(mt,"sanitizeProfileData");function ft(e){return typeof Deno<"u"?Deno.env.get(e):process.env[e]}s(ft,"getEnv");function gt(){return h("exchange-token",Ge,async(e,t)=>{let{provider:n,purpose:r,code:i,redirectUri:c,codeVerifier:o}=e;if(!Ze(c))throw new Error("Invalid redirect URI scheme");let a=te[n];if(!a?.endpoints?.tokenUrl)throw new Error(`Provider ${n} is not supported`);let u=n.toUpperCase(),m=ft(`${u}_CLIENT_ID`),p=ft(`${u}_CLIENT_SECRET`);if(!m||!p)throw new Error(`Provider ${n} is not configured`);let f=await fetch(a.endpoints.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"authorization_code",client_id:m,client_secret:p,code:i,redirect_uri:c,...o?{code_verifier:o}:{}}).toString()});if(!f.ok){let d=await f.text();throw console.error(`Token exchange error for ${n}: ${f.status}`,d),new Error(`Failed to exchange code for token: ${f.status}`)}let g=await f.json(),S={accessToken:g.access_token,refreshToken:g.refresh_token||null,expiresAt:g.expires_in?Math.floor(Date.now()/1e3)+g.expires_in:null,idToken:g.id_token||null,scope:g.scope?g.scope.split(" "):[]},C=null;if(S.accessToken&&a.endpoints.profileUrl)try{let d=await fetch(a.endpoints.profileUrl,{headers:{Authorization:`Bearer ${S.accessToken}`,Accept:"application/json"}});if(d.ok){let l=await d.json();C=mt(l)}}catch(d){console.warn(`Failed to fetch profile for ${n}:`,d)}let{error:v}=await t.supabaseAdmin.from("oauth_connections").upsert({user_id:t.uid,provider:n,purpose:r,credentials:S,profile:C,connected:!0,updated_at:new Date().toISOString()},{onConflict:"user_id,provider,purpose"});return v&&console.error("Error saving OAuth connection:",v),{success:!0,credentials:S,profile:C}})}s(gt,"createExchangeToken");var vr=R({provider:w(),purpose:Q(["authentication","api-access"])});function yt(){return h("disconnect",vr,async(e,t)=>{let{provider:n,purpose:r}=e,{data:i}=await t.supabaseAdmin.from("oauth_connections").select("credentials").eq("user_id",t.uid).eq("provider",n).eq("purpose",r).single();if(i?.credentials?.accessToken){let o=te[n],a="revokeUrl"in o?o.revokeUrl:null;if(a)try{await fetch(a.toString(),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:i.credentials.accessToken}).toString()})}catch(u){console.warn(`Failed to revoke token for ${n}:`,u)}}let{error:c}=await t.supabaseAdmin.from("oauth_connections").delete().eq("user_id",t.uid).eq("provider",n).eq("purpose",r);if(c)throw new Error(`Failed to disconnect: ${c.message}`);return{success:!0}})}s(yt,"createDisconnect");function ht(e){return typeof Deno<"u"?Deno.env.get(e):process.env[e]}s(ht,"getEnv");var Rr=R({provider:w(),refreshToken:I(w(),x(1,"Refresh token is required")),redirectUri:I(w(),Se("Valid redirect URI is required"))});function wt(){return h("refresh-token",Rr,async(e,t)=>{let{provider:n,refreshToken:r,redirectUri:i}=e,c=te[n];if(!c?.endpoints?.tokenUrl)throw new Error(`Provider ${n} does not support token refresh`);let o=n.toUpperCase(),a=ht(`${o}_CLIENT_ID`),u=ht(`${o}_CLIENT_SECRET`);if(!a||!u)throw new Error(`Provider ${n} is not configured`);let m=await fetch(c.endpoints.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"refresh_token",client_id:a,client_secret:u,refresh_token:r,redirect_uri:i}).toString()});if(!m.ok){let S=await m.text();throw console.error(`Token refresh error for ${n}:`,S),new Error(`Failed to refresh token: ${m.status}`)}let p=await m.json(),f={accessToken:p.access_token,refreshToken:p.refresh_token||r,expiresAt:p.expires_in?Math.floor(Date.now()/1e3)+p.expires_in:null,scope:p.scope?p.scope.split(" "):[]},{error:g}=await t.supabaseAdmin.from("oauth_connections").update({credentials:f,updated_at:new Date().toISOString()}).eq("user_id",t.uid).eq("provider",n);return g&&console.error("Error updating OAuth connection:",g),{success:!0,credentials:f}})}s(wt,"createRefreshToken");var br=R({purpose:P(Q(["authentication","api-access"]))});function St(){return h("get-connections",br,async(e,t)=>{let n=t.supabaseAdmin.from("oauth_connections").select("*").eq("user_id",t.uid);e.purpose&&(n=n.eq("purpose",e.purpose));let{data:r,error:i}=await n;if(i)throw new Error(`Failed to get connections: ${i.message}`);return{connections:(r||[]).map(o=>{let a=o.credentials?.expiresAt?o.credentials.expiresAt<Math.floor(Date.now()/1e3):!1;return{id:o.id,userId:o.user_id,provider:o.provider,purpose:o.purpose,connected:!a,createdAt:o.created_at,updatedAt:o.updated_at,hasCredentials:!a&&!!o.credentials,profile:o.profile}})}})}s(St,"createGetConnections");function kr(e){return h("ai-chat",Ye,async(t,n)=>rt(t,e,{userId:n.uid,requestId:crypto.randomUUID(),onCostRecord:s(async r=>{let{error:i}=await n.supabaseAdmin.from("ai_usage").insert({user_id:r.userId,model:r.model,provider:r.provider,prompt_tokens:r.usage.promptTokens,completion_tokens:r.usage.completionTokens,total_tokens:r.usage.totalTokens,provider_cost:r.providerCost,billed_cost:r.billedCost,markup:r.markup,request_id:r.requestId,created_at:r.timestamp});i&&console.error("[AI] Failed to record cost to Supabase:",i.message)},"onCostRecord")}))}s(kr,"createAIFunction");function Ar(e){return h("send-email",We,async(t,n)=>{let r=Cr("RESEND_API_KEY");if(!r)return new Response(JSON.stringify({success:!1,error:"Email provider not configured"}),{status:500,headers:{"Content-Type":"application/json"}});let i=Ue(r),c=await Be(t,e,i);return new Response(JSON.stringify(c),{status:c.success?200:400,headers:{"Content-Type":"application/json"}})})}s(Ar,"createEmailFunction");function Cr(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}s(Cr,"getEnv");import{createClient as qo}from"@supabase/supabase-js";function Ae(e){return typeof e!="string"?String(e):e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").toLowerCase()}s(Ae,"camelToSnake");function Et(e){return typeof e!="string"?String(e):e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}s(Et,"snakeToCamel");var vt=new Set(["createdAt","updatedAt"]);function Rt(e){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e))return e;if(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(e))return new Date(e.replace(" ","T")).toISOString()}return e}s(Rt,"toIsoString");function _r(){return{toBackendField:s(r=>{if(typeof r!="string")throw new TypeError(`Supabase field mapper: field name must be a string (e.g. "createdById"), got ${typeof r}. Check where query options (orderBy/where) are built \u2014 ensure "field" is the field name string, not a schema or other value.`);return Ae(r)},"toBackendField"),toBackendKeys:s(r=>{let i={};for(let[c,o]of Object.entries(r))i[Ae(c)]=o;return i},"toBackendKeys"),fromBackendRow:s(r=>{let i={};for(let[c,o]of Object.entries(r)){let a=Et(c);i[a]=vt.has(a)?Rt(o):o}return i},"fromBackendRow")}}s(_r,"createFieldMapperInternal");var U=_r(),Ir=["id","createdAt","updatedAt","createdById","updatedById","status"];function de(e){if(!e||typeof e!="object")return[];let t=e.entries;return!t||typeof t!="object"?[]:Object.keys(t)}s(de,"getEntityFieldNames");function X(e){let t=new Map;for(let n of e)t.set(Ae(n),n);for(let n of Ir)t.set(Ae(n),n);return{toBackendField:U.toBackendField,toBackendKeys:U.toBackendKeys,fromBackendRow:s(n=>{let r={};for(let[i,c]of Object.entries(n)){let o=t.get(i)??Et(i);r[o]=vt.has(o)?Rt(c):c}return r},"fromBackendRow")}}s(X,"createEntityAwareMapper");function Ce(e,t,n,r){let i=R({id:I(w(),x(1))});return h(`get_${e}`,i,async(c,o)=>{let{id:a}=c,{userRole:u,uid:m,supabaseAdmin:p}=o,{data:f,error:g}=await p.from(e).select("*").eq("id",a).single();if(g||!f)throw new A("Entity not found","not-found");if(!W(u,"admin")&&ne.includes(f.status))throw new A("Entity not found","not-found");let C=de(t),d=(C.length>0?X(C):U).fromBackendRow(f),b=re(d,t,u,r&&m?{documentData:d,uid:m,ownership:r}:void 0);return{id:f.id,...b}},n)}s(Ce,"createSupabaseGetEntity");var bt={create:24,update:12,delete:1,default:24};async function pe(e,t,n){try{let r=`${n}_${t}`,{data:i,error:c}=await e.from("idempotency").select("result").eq("idempotency_key",t).eq("operation",n).gt("expires_at",new Date().toISOString()).single();return c||!i?null:i.result}catch(r){throw console.error("[idempotency] Check failed:",r),new Error("[idempotency] Unable to verify idempotency. Operation rejected to prevent potential duplicate processing.")}}s(pe,"checkIdempotency");async function le(e,t,n,r,i,c){try{let o=`${n}_${t}`,a=c??bt[n]??bt.default,u=new Date;u.setHours(u.getHours()+a);let{error:m}=await e.from("idempotency").upsert({id:o,operation:n,idempotency_key:t,result:r,processed_by:i,expires_at:u.toISOString()},{onConflict:"idempotency_key"});m&&console.error("[idempotency] Store failed:",m)}catch(o){console.error("[idempotency] Store failed:",o)}}s(le,"storeIdempotency");async function xr(e){try{let{data:t,error:n}=await e.from("idempotency").delete().lt("expires_at",new Date().toISOString()).select("id");return n?(console.error("[idempotency] Cleanup failed:",n),0):t?.length??0}catch(t){return console.error("[idempotency] Cleanup failed:",t),0}}s(xr,"cleanupExpiredIdempotency");var fe=U;function Tr(e){return typeof e=="string"?e.toLowerCase():e}s(Tr,"normalizeValue");function Pr(e,t){let n={...e};for(let r of t)for(let i of r.fields)typeof n[i]=="string"&&(n[i]=n[i].toLowerCase());return n}s(Pr,"normalizePayloadForUniqueKeys");async function Dr(e,t,n,r,i){for(let c of n){if(r&&c.skipForDrafts===!0||!c.fields.every(p=>t[p]!=null&&t[p]!==""))continue;let a=i.from(e).select("*");for(let p of c.fields)a=a.eq(fe.toBackendField(p),Tr(t[p]));let{data:u,error:m}=await a.limit(1);if(!m&&u&&u.length>0){let p=fe.fromBackendRow(u[0]);if(c.findOrCreate)return{found:!0,existingDoc:p,findOrCreate:!0};let f=c.fields.join(" + ");throw new A(c.errorMessage||`Duplicate ${f}`,"already-exists",{details:{fields:c.fields,existingId:p.id}})}}return{found:!1}}s(Dr,"checkUniqueKeys");function _e(e,t,n,r){let i=R({payload:ee(w(),H()),idempotencyKey:P(w())});return h(`create_${e}`,i,async(c,o)=>{let{payload:a,idempotencyKey:u}=c,{uid:m,userRole:p,supabaseAdmin:f}=o;if(u){let B=await pe(f,u,"create");if(B)return B}let g=a.status??"draft",S=g==="draft",v=t.metadata?.uniqueKeys;if(v&&v.length>0){let B=await Dr(e,a,v,S,f);if(B.found&&B.findOrCreate)return re(B.existingDoc,t,p)}let d=v&&v.length>0?Pr(a,v):a,l={...d,status:g};Re(l,S?n:t);let b=Ee(m),E=fe.toBackendKeys(b),{createdAt:K,updatedAt:k,created_at:V,updated_at:Y,...$}=d,F=fe.toBackendKeys($),{data:T,error:O}=await f.from(e).insert({...F,status:g,...E}).select().single();if(O)throw new A(`Failed to create entity: ${O.message}`,"internal");let L=fe.fromBackendRow(T);return u&&await le(f,u,"create",L,m),L},r)}s(_e,"createSupabaseCreateEntity");var me=U;function Or(e){return typeof e=="string"?e.toLowerCase():e}s(Or,"normalizeValue");async function Br(e,t,n,r,i,c){for(let o of r){if(i&&o.skipForDrafts===!0||o.fields.filter(g=>g in n).length===0||!o.fields.every(g=>n[g]!=null&&n[g]!==""))continue;let m=c.from(e).select("*");for(let g of o.fields)m=m.eq(me.toBackendField(g),Or(n[g]));m=m.neq("id",t);let{data:p,error:f}=await m.limit(1);if(!f&&p&&p.length>0){let g=o.fields.join(" + ");throw new A(o.errorMessage||`Duplicate ${g}`,"already-exists",{details:{fields:o.fields,existingId:p[0].id}})}}}s(Br,"checkUniqueKeys");function Ie(e,t,n){let r=R({id:I(w(),x(1)),payload:ee(w(),H()),idempotencyKey:P(w())});return h(`update_${e}`,r,async(i,c)=>{let{id:o,payload:a,idempotencyKey:u}=i,{uid:m,supabaseAdmin:p}=c;if(u){let se=await pe(p,u,"update");if(se)return se}let{data:f,error:g}=await p.from(e).select("*").eq("id",o).single();if(g||!f)throw new A("Entity not found","not-found");let S={...me.fromBackendRow(f),...a},v=(S.status??f.status)==="draft",l=t.metadata?.uniqueKeys;l&&l.length>0&&await Br(e,o,S,l,v,p),v||Re(S,t);let b=ve(m),E=me.toBackendKeys(b),{createdAt:K,updatedAt:k,created_at:V,updated_at:Y,id:$,...F}=a,T=me.toBackendKeys(F),{data:O,error:L}=await p.from(e).update({...T,...E}).eq("id",o).select().single();if(L)throw new A(`Failed to update entity: ${L.message}`,"internal");let B=me.fromBackendRow(O);return u&&await le(p,u,"update",B,m),B},n)}s(Ie,"createSupabaseUpdateEntity");async function Ur(e,t,n,r){let i=[];if(!r)return i;if(r.incoming)for(let c of r.incoming){let{count:o,error:a}=await e.from(c.sourceCollection).select("*",{count:"exact",head:!0}).eq(c.sourceField,n);!a&&o&&o>0&&i.push({collection:c.sourceCollection,field:c.sourceField,count:o})}return r.outgoing,i}s(Ur,"findReferences");function xe(e,t,n){let r=R({id:I(w(),x(1))});return h(`delete_${e}`,r,async(i,c)=>{let{id:o}=i,{supabaseAdmin:a}=c;n&&!n.incoming&&console.warn(`[delete_${e}] referenceMetadata provided but incoming is undefined \u2014 reference check skipped`);let m=(await Ur(a,e,o,n)).filter(f=>n?.incoming?.find(S=>S.sourceCollection===f.collection&&S.sourceField===f.field)?.required===!0);if(m.length>0)throw new A("Cannot delete: item is referenced by other entities","permission-denied",{details:{references:m}});let{error:p}=await a.from(e).delete().eq("id",o);if(p)throw new A(`Failed to delete entity: ${p.message}`,"internal");return{success:!0}},t)}s(xe,"createSupabaseDeleteEntity");import{Buffer as Ct}from"node:buffer";var je=U;function G(e){return je.toBackendField(typeof e=="string"?e:String(e))}s(G,"toBackendColumn");function kt(e,t){let n={id:e,orderBy:t};return Ct.from(JSON.stringify(n)).toString("base64")}s(kt,"encodeCursor");function At(e){try{let t=JSON.parse(Ct.from(e,"base64").toString());if(!t||typeof t!="object"||typeof t.id!="string"||!t.id||typeof t.orderBy!="object"||t.orderBy===null||Array.isArray(t.orderBy))throw new A("Invalid cursor content","invalid-argument");return t}catch(t){throw t instanceof A?t:new A("Invalid cursor format","invalid-argument")}}s(At,"decodeCursor");var Fr=/^[a-zA-Z][a-zA-Z0-9_]*$/;function _t(e,t,n,r){if(!Fr.test(t))throw new A(`Invalid field name: '${t}'`,"invalid-argument");switch(n){case"==":return e.eq(t,r);case"!=":return e.neq(t,r);case">":return e.gt(t,r);case">=":return e.gte(t,r);case"<":return e.lt(t,r);case"<=":return e.lte(t,r);case"in":return e.in(t,Array.isArray(r)?r:[r]);case"not-in":return e.not(t,"in",Array.isArray(r)?r:[r]);case"array-contains":return e.contains(t,[r]);case"array-contains-any":return e.contains(t,Array.isArray(r)?r:[r]);default:return e.eq(t,r)}}s(_t,"applyOperator");function qr(e,t){let n=e;for(let r of t)n=_t(n,G(r.field),r.op,r.value);return n}s(qr,"applyPublicCondition");function ge(e,t,n,r,i,c){let o=R({where:P(z(ae([w(),H(),H()]))),orderBy:P(z(ae([I(w(),x(1)),Q(["asc","desc"])]))),limit:P(I(He(),Le(1))),startAfterId:P(w()),startAfterCursor:P(w()),search:P(R({field:w(),query:w()}))});return h(c?`listCard_${e}`:`list_${e}`,o,async(a,u)=>{let{where:m=[],orderBy:p=[],limit:f=1e3,startAfterId:g,startAfterCursor:S,search:C}=a,{userRole:v,uid:d,supabaseAdmin:l}=u,b=W(v,"admin"),E=r?.filter(y=>typeof y=="string"),K=E&&E.length>0?E.map(y=>G(y)).join(", ")+", id, status":"*",k=l.from(e).select(K,{count:"exact"});if(b||(k=k.not("status","in",[...ne])),i&&!b){if(c&&i.publicCondition&&i.publicCondition.length>0)k=qr(k,i.publicCondition);else if(!c&&i.ownerFields.length>0){let y=i.ownerFields[0];k=k.eq(G(y),d)}}if(C){if(E&&E.length>0){if(!E.includes(C.field))throw new A(`Search field '${C.field}' is not allowed`,"invalid-argument")}else if(C.field.startsWith("_")||C.field.includes("."))throw new A(`Search field '${C.field}' is not allowed`,"invalid-argument");let y=C.query.replace(/%/g,"\\%").replace(/_/g,"\\_");k=k.ilike(G(C.field),`%${y}%`)}for(let[y,_,q]of m){if(E&&E.length>0){if(!E.includes(y)&&y!=="status"&&y!=="id")throw new A(`Where field '${y}' is not allowed`,"invalid-argument")}else if(y.startsWith("_")||y.includes("."))throw new A(`Where field '${y}' is not allowed`,"invalid-argument");k=_t(k,G(y),_,q)}let V=p.some(([y])=>G(y)==="id");for(let[y,_]of p)k=k.order(G(y),{ascending:_==="asc"});!V&&p.length>0&&(k=k.order("id",{ascending:!0}));let Y=!1;if(S){Y=!0;try{let y=At(S);if(p.length===0)k=k.gt("id",y.id);else{let _=p[0][0],q=p[0][1],J=G(_),N=y.orderBy[_];q==="asc"?k=k.gte(J,N):k=k.lte(J,N)}}catch{throw new A("Invalid cursor format","invalid-argument")}k=k.limit(f+1)}else if(g){let y=parseInt(g,10);if(isNaN(y))throw new A("Invalid startAfterId","invalid-argument");k=k.range(y,y+f-1)}else k=k.range(0,f-1);let{data:$,error:F,count:T}=await k;if(F)throw new A(`Failed to list entities: ${F.message}`,"internal");let O=$||[];if(Y&&S&&O.length>0)try{let y=At(S);O=O.filter(_=>{if(p.length===0)return _.id!==y.id;let q=p[0][0],J=y.orderBy[q],N=_[je.toBackendField(q)];return!(_.id===y.id&&N===J)})}catch{}let L=s(y=>typeof y=="object"&&y!==null&&"thumbUrl"in y&&"fullUrl"in y,"isPictureObject"),B=s(y=>{if(Array.isArray(y)&&y.length>0){let _=y[0];if(L(_))return _.thumbUrl||_.fullUrl||null;if(typeof _=="string")return _}else if(L(y))return y.thumbUrl||y.fullUrl||null;return y},"optimizePictureField"),se=i&&d?{uid:d,ownership:i}:void 0,Me=de(t),Pt=Me.length>0?X(Me):je,he=O.map(y=>{let _=Pt.fromBackendRow(y),q=re(_,t,v,se?{...se,documentData:_}:void 0);if(E&&E.length>0){let N={id:_.id};for(let ie of E)if(ie in q){let Dt=q[ie];N[ie]=B(Dt)}return N}let J={id:_.id};for(let[N,ie]of Object.entries(q))J[N]=B(ie);return J}),Ke=O.length===f,we=null;if(Ke&&he.length>0){let y=he[he.length-1];if(Y&&p.length>0){let _=p[0][0],q={};q[_]=y[_],we=kt(y.id,q)}else if(Y)we=kt(y.id,{});else{let _=g?parseInt(g,10):0;we=String(_+O.length)}}return{items:he,lastVisible:we,count:T??void 0,hasMore:Ke}},n)}s(ge,"createSupabaseListEntities");var ye=U;function jr(e,t,n,r){switch(n){case"==":return e.eq(t,r);case"!=":return e.neq(t,r);case">":return e.gt(t,r);case">=":return e.gte(t,r);case"<":return e.lt(t,r);case"<=":return e.lte(t,r);case"in":return e.in(t,Array.isArray(r)?r:[r]);case"not-in":return e.not(t,"in",Array.isArray(r)?r:[r]);case"array-contains":return e.contains(t,[r]);default:return e.eq(t,r)}}s(jr,"applyOperator");function Te(e,t,n){let r=R({where:P(z(ae([w(),H(),H()]))),aggregate:R({field:w(),operation:Q(["count","sum","avg","min","max"])}),groupBy:P(z(w()))});return h(`aggregate_${e}`,r,async(i,c)=>{let{where:o=[],aggregate:a,groupBy:u}=i,{supabaseAdmin:m}=c,p=ye.toBackendField(a.field),f=m.from(e);for(let[v,d,l]of o)f=jr(f,ye.toBackendField(v),d,l);if(u&&u.length>0){let d=`${u.map(l=>ye.toBackendField(l)).join(", ")}, ${a.operation}(${p})`;f=f.select(d);for(let l of u)f=f.group(ye.toBackendField(l))}else a.operation==="count"?f=f.select("*",{count:"exact",head:!0}):f=f.select(p);let{data:g,error:S,count:C}=await f;if(S)throw new A(`Failed to aggregate entities: ${S.message}`,"internal");if(u&&u.length>0){let v={};for(let d of g||[]){let l=u.map(b=>d[ye.toBackendField(b)]).join("|");v[l]=d[`${a.operation}`]||0}return{value:v}}else{if(a.operation==="count")return{value:C??0};{let v=(g||[]).map(l=>l[p]).filter(l=>l!=null&&!isNaN(Number(l))).map(l=>Number(l));if(v.length===0)return{value:0};let d;switch(a.operation){case"sum":d=v.reduce((l,b)=>l+b,0);break;case"avg":d=v.reduce((l,b)=>l+b,0)/v.length;break;case"min":d=Math.min(...v);break;case"max":d=Math.max(...v);break;default:d=0}return{value:d}}}},n)}s(Te,"createSupabaseAggregateEntities");var Pe=U,It={guest:0,user:1,admin:2,super:3};function $r(e,t){let{createdAt:n,updatedAt:r,created_at:i,updated_at:c,...o}=e,a=Pe.toBackendKeys(o),u=Pe.toBackendKeys(Ee(t));return{...a,...u}}s($r,"prepareInsertRow");function Mr(e,t){let{createdAt:n,updatedAt:r,created_at:i,updated_at:c,id:o,...a}=e,u=Pe.toBackendKeys(a),m=Pe.toBackendKeys(ve(t));return{...u,...m}}s(Mr,"preparePatch");function $e(e,t,n,r,i){let c=(()=>{let o=[];return i.create&&o.push(i.create),i.update&&o.push(i.update),i.delete&&o.push(i.delete),o.length===0?"user":o.reduce((a,u)=>It[a]>=It[u]?a:u)})();return h(`bulk_${e}`,et,async(o,a)=>{let{uid:u,userRole:m,supabaseAdmin:p}=a;try{return await tt({collection:e,ops:o,createSchema:t,draftCreateSchema:n,updateSchema:r,access:i,uid:u,userRole:m,stampInsertMetadata:$r,stampUpdateMetadata:Mr,transact:s(async({inserts:f,updates:g,deletes:S})=>{let{data:C,error:v}=await p.rpc("crud_bulk",{p_collection:e,p_inserts:f.map(l=>l.row),p_updates:g.map(l=>({id:l.id,patch:l.patch})),p_deletes:S});if(v)throw new A(`Failed to execute bulk: ${v.message}`,"internal");let d=C??{};return{insertedIds:Array.isArray(d.insertedIds)?d.insertedIds:Array.isArray(d.inserted_ids)?d.inserted_ids:[],updatedIds:Array.isArray(d.updatedIds)?d.updatedIds:Array.isArray(d.updated_ids)?d.updated_ids:[],deletedIds:Array.isArray(d.deletedIds)?d.deletedIds:Array.isArray(d.deleted_ids)?d.deleted_ids:[]}},"transact"),audit:s((f,{counts:g})=>{console.log(`[${f}] uid=${u} inserts=${g.inserts} updates=${g.updates} deletes=${g.deletes}`)},"audit")})}catch(f){throw f instanceof Qe?new A(f.message,"invalid-argument",{details:{collidingIds:f.collidingIds,where:f.where}}):f}},c)}s($e,"createSupabaseBulkEntity");var Kr=/^[a-zA-Z][a-zA-Z0-9_]*$/;function xt(e){return`(${e.map(t=>JSON.stringify(String(t))).join(",")})`}s(xt,"postgrestList");function Lr(e,t,n,r){let i=Array.isArray(r)?r:[r];switch(n){case"==":return e.eq(t,r);case"!=":return e.neq(t,r);case">":return e.gt(t,r);case">=":return e.gte(t,r);case"<":return e.lt(t,r);case"<=":return e.lte(t,r);case"in":return e.in(t,i);case"not-in":return e.not(t,"in",xt(i));case"array-contains":return e.contains(t,[r]);case"array-contains-any":return e.overlaps(t,i)}}s(Lr,"applyCondition");function Tt(e,t){let n=Object.keys(t.fields),r=new Set(n),i=X(n),c=t.collection,o=r.has("status"),a=s(()=>e.from(c),"from"),u=s(d=>{if(!r.has(d)||!Kr.test(d))throw new A(`${t.name}: unknown field '${d}'`,"invalid-argument");return i.toBackendField(d)},"column"),m=s(d=>{let l={};for(let[b,E]of Object.entries(d))E!==void 0&&(l[u(b)]=E);return l},"toColumns"),p=s(d=>(d??[]).map(l=>i.fromBackendRow(l)),"fromRows"),f=s((d,l)=>{throw new A(`${d} ${c}: ${l.message}`,"internal")},"fail"),g=s(d=>d&&d.length>0?[...new Set(["id",...d])].map(u).join(", "):"*","selectList"),S=s((d,l,b)=>{let E=d;for(let[K,k,V]of l)E=Lr(E,u(K),k,V);return o&&!b&&(E=E.not("status","in",xt(ne))),E},"filtered"),C=s(async(d={})=>{let l=S(a().select(g(d.select)),d.where??[],d.includeHidden);for(let[K,k]of d.orderBy??[])l=l.order(u(K),{ascending:k==="asc"});d.limit!==void 0&&(l=l.limit(d.limit));let{data:b,error:E}=await l;return E&&f("list",E),p(b)},"list"),v=s(async d=>{let l=await C({...d,limit:2});if(l.length>1)throw new A(`${t.name}: more than one row matches`,"internal");return l[0]??null},"find");return{list:C,find:v,get:s((d,l)=>v({...l,where:[["id","==",d]]}),"get"),async insert(d){if(d.length===0)return[];let{data:l,error:b}=await a().insert(d.map(E=>m(E))).select("*");return b&&f("insert",b),p(l)},async update(d,l){if(d.length===0)throw new A(`${t.name}: update without a condition`,"invalid-argument");let{data:b,error:E}=await S(a().update(m(l)),d,!0).select("*");return E&&f("update",E),p(b)}}}s(Tt,"createEntityStore");function Hr(e){let t={};for(let[r,i]of Object.entries(e)){if(!Nr(i))continue;let c=i,o=c.collection,a=Xe(c),u=c.access;t[`create_${o}`]=_e(o,a.create,a.draft,u.create),t[`get_${o}`]=Ce(o,a.get,u.read,c.ownership),t[`list_${o}`]=ge(o,a.get,u.read,c.listFields,c.ownership,!1),t[`listCard_${o}`]=ge(o,a.get,u.read,Je(c),c.ownership,!0),t[`update_${o}`]=Ie(o,a.update,u.update);let p=a.get.metadata?.references;t[`delete_${o}`]=xe(o,u.delete,p),t[`aggregate_${o}`]=Te(o,a.get,u.read),t[`bulk_${o}`]=$e(o,a.create,a.draft,a.update,u)}let n=ue(async(r,i)=>{let c=await r.json().catch(()=>({})),o=c._functionName;if(!o)return i.error("Missing _functionName in request body",400);let a=t[o];if(!a)return i.error(`Unknown function: ${o}`,404);let{_functionName:u,...m}=c,p=new Request(r.url,{method:r.method,headers:r.headers,body:JSON.stringify(m)});return a(p)},{requireAuth:!1});return{handlers:t,serve:n}}s(Hr,"createSupabaseCrudFunctions");function Nr(e){return typeof e=="object"&&e!==null&&"collection"in e&&"fields"in e}s(Nr,"isEntity");export{ke as DEFAULT_RATE_LIMITS,qt as ReservationLostError,Ft as STRIPE_API_VERSION_PIN,jt as WEBHOOK_EVENTS_SQL,pe as checkIdempotency,Fe as checkRateLimitWithPostgres,Bt as classifyAIError,xr as cleanupExpiredIdempotency,kr as createAIFunction,dr as createCancelSubscription,fr as createChangePlan,De as createCheckoutAlgorithm,ir as createCheckoutSession,yr as createCustomerPortal,Wt as createDeleteAccount,yt as createDisconnect,ue as createEdgeFunction,Ar as createEmailFunction,Tt as createEntityStore,gt as createExchangeToken,St as createGetConnections,er as createGetCustomClaims,sr as createGetUserAuthStatus,Sr as createRefreshSubscriptionStatus,wt as createRefreshToken,nr as createRemoveCustomClaims,Ue as createResendProvider,Zt as createSetCustomClaims,cr as createStripeWebhook,Te as createSupabaseAggregateEntities,j as createSupabaseAuthProvider,_e as createSupabaseCreateEntity,Hr as createSupabaseCrudFunctions,xe as createSupabaseDeleteEntity,Ce as createSupabaseGetEntity,h as createSupabaseHandler,Oe as createSupabaseIdempotencyStore,ge as createSupabaseListEntities,Ie as createSupabaseUpdateEntity,$t as getFailureRate,Mt as getOperationCounts,Kt as getSlowOperations,Be as handleEmailRequest,Ut as mapClassifiedToHTTP,qe as recordOperationMetrics,Ot as resolveModelForTier,le as storeIdempotency};
21
+ import{b as Re}from"../chunks/chunk-FQSQGOBN.js";import{a as Ee,b as ve,c as tt,d as Be,e as Ue}from"../chunks/chunk-M4JV2JCF.js";import{a as j,b as ke,c as Fe}from"../chunks/chunk-HLNYUAZH.js";import{a as M,b as Z,c as be,d as st,e as it,f as at}from"../chunks/chunk-ZVHC2CAV.js";import{c as rt,d as Ot,e as Bt,f as Ut,h as Ft,o as De,p as nt,q as qt,u as ot,v as jt,w as Oe}from"../chunks/chunk-UYI56E6Q.js";import{A as I,B as Ve,C as Ye,G as ze,I as Qe,J as We,L as A,P as Ge,Q as te,T as W,X as re,Y as Je,Z as Ze,aa as ne,ba as Xe,ca as et,h as x,i as Le,l as Se,m as H,n as z,q as He,r as R,s as P,t as Q,u as ee,v as w,w as ae,y as Ne}from"../chunks/chunk-G4FO76EA.js";import"../chunks/chunk-PWAGW4R6.js";import{a as s}from"../chunks/chunk-AYY7UXNI.js";import{createClient as Lt}from"@supabase/supabase-js";async function qe(e,t){try{let{error:n}=await e.from("operation_metrics").insert({operation:t.operation,user_id:t.userId||null,status:t.status,duration_ms:t.durationMs||null,metadata:t.metadata||null,error_code:t.errorCode||null,error_message:t.errorMessage||null});n&&console.error("[monitoring] Record failed:",n)}catch(n){console.error("[monitoring] Record failed:",n)}}s(qe,"recordOperationMetrics");async function $t(e,t,n=24){try{let r=new Date;r.setHours(r.getHours()-n);let{data:i,error:c}=await e.from("operation_metrics").select("status").eq("operation",t).gte("timestamp",r.toISOString());return c||!i||i.length===0?0:i.filter(a=>a.status==="failed").length/i.length*100}catch(r){return console.error("[monitoring] Get failure rate failed:",r),0}}s($t,"getFailureRate");async function Mt(e,t,n=24){try{let r=new Date;r.setHours(r.getHours()-n);let{data:i,error:c}=await e.from("operation_metrics").select("operation").eq("user_id",t).gte("timestamp",r.toISOString());if(c||!i)return{};let o={};for(let a of i)o[a.operation]=(o[a.operation]||0)+1;return o}catch(r){return console.error("[monitoring] Get operation counts failed:",r),{}}}s(Mt,"getOperationCounts");async function Kt(e,t,n=24){try{let r=new Date;r.setHours(r.getHours()-n);let{data:i,error:c}=await e.from("operation_metrics").select("operation, duration_ms").gte("timestamp",r.toISOString()).not("duration_ms","is",null);if(c||!i)return[];let o={};for(let u of i)u.duration_ms&&(o[u.operation]||(o[u.operation]={sum:0,count:0}),o[u.operation].sum+=u.duration_ms,o[u.operation].count+=1);let a=[];for(let[u,m]of Object.entries(o)){let p=m.sum/m.count;p>=t&&a.push({operation:u,avgDuration:Math.round(p),count:m.count})}return a.sort((u,m)=>m.avgDuration-u.avgDuration)}catch(r){return console.error("[monitoring] Get slow operations failed:",r),[]}}s(Kt,"getSlowOperations");function h(e,t,n,r="user",i){return async c=>{try{let o=oe("ALLOWED_ORIGIN","*"),a=s((T,O)=>ct(T,O,o),"respond");if(c.method==="OPTIONS")return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":o,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"authorization, content-type, x-client-info, apikey"}});if(c.method!=="POST")return a({error:"Method not allowed"},405);let u=c.headers.get("authorization");if(!u?.startsWith("Bearer "))return a({error:"Missing or invalid authorization header"},401);let m=u.slice(7),p=Ht("SUPABASE_URL"),f=oe("SUPABASE_SECRET_KEY")||oe("SUPABASE_SERVICE_ROLE_KEY");if(!f)throw new Error("Missing environment variable: SUPABASE_SECRET_KEY or SUPABASE_SERVICE_ROLE_KEY");let g=Lt(p,f,{auth:{autoRefreshToken:!1,persistSession:!1}}),{data:{user:S},error:C}=await g.auth.getUser(m);if(C||!S)return a({error:"Invalid or expired token"},401);let d=(S.app_metadata??{}).role||"user";if(r!=="guest"){if(!W(d,r))return a({error:`Access denied. Required role: ${r}, your role: ${d}`},403)}if(!(oe("DISABLE_RATE_LIMITING")==="true")){let T=r==="guest"&&S.id==="guest"?`ip_${Vt(c)}`:`uid_${S.id}`,O=`${e}_${T}`,L=ke[e]||ke.api,B=await Fe(g,O,L);if(!B.allowed)return i?.audit({type:"rate_limit.exceeded",userId:S.id,metadata:{operation:e,remaining:0}}),a({error:`Rate limit exceeded. Try again in ${B.blockRemainingSeconds} seconds.`},429)}let b=c.headers.get("content-length"),E=1048576;if(b&&parseInt(b,10)>E)return a({error:`Request body too large. Maximum size: ${E} bytes`},413);let K=await c.json().catch(()=>({})),k=Ve(t,K);if(!k.success){let T=k.issues.map(O=>O.message).join(", ");return a({error:`Validation failed: ${T}`},400)}let V=oe("ENABLE_METRICS")==="true",Y=V?Date.now():0,$,F=null;try{$=await n(k.output,{uid:S.id,userRole:d,supabaseAdmin:g})}catch(T){throw F=T instanceof Error?T:new Error(String(T)),T}finally{if(V){let T=Date.now()-Y;await qe(g,{operation:e,userId:S.id,status:F?"failed":"success",durationMs:T,metadata:{requestId:c.headers.get("x-request-id")||void 0},errorCode:F?dt(F.message):void 0,errorMessage:F?F.message:void 0})}}if($ instanceof Response){let T=new Headers($.headers);return T.set("Access-Control-Allow-Origin",o),new Response($.body,{status:$.status,statusText:$.statusText,headers:T})}return a($,200)}catch(o){console.error(`[${e}] Error:`,o);let a=o instanceof Error?o.message:"Internal server error",u=dt(a),p=new Set(["rate-limit-exceeded","not-found","permission-denied","invalid-argument","already-exists"]).has(u)?a:"Internal server error",f=Yt(a),g=oe("ALLOWED_ORIGIN","*");return ct({error:p},f,g)}}}s(h,"createSupabaseHandler");function ct(e,t,n="*"){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":n}})}s(ct,"jsonResponse");function Ht(e){let t=typeof Deno<"u"?Deno.env.get(e):process.env[e];if(!t)throw new Error(`Missing environment variable: ${e}`);return t}s(Ht,"getEnvOrThrow");function oe(e,t=""){return(typeof Deno<"u"?Deno.env.get(e):process.env[e])||t}s(oe,"getEnv");var Nt=/^(?:\d{1,3}\.){3}\d{1,3}$|^[0-9a-fA-F:]{2,45}$/;function ut(e){return Nt.test(e)}s(ut,"isValidIp");function Vt(e){let t=e.headers.get("x-forwarded-for");if(t){let r=t.split(",").map(c=>c.trim()).filter(Boolean),i=r[r.length-1];if(i&&ut(i))return i}let n=e.headers.get("cf-connecting-ip");return n&&ut(n)?n:"unknown"}s(Vt,"getClientIp");function dt(e){return e.includes("Rate limit")?"rate-limit-exceeded":e.includes("not found")||e.includes("No active")?"not-found":e.includes("permission")||e.includes("denied")||e.includes("Forbidden")?"permission-denied":e.includes("mismatch")||e.includes("Invalid")||e.includes("Missing")?"invalid-argument":e.includes("already-exists")||e.includes("Duplicate")?"already-exists":"internal"}s(dt,"getErrorCode");function Yt(e){return e.includes("Rate limit")?429:e.includes("not found")||e.includes("No active")?404:e.includes("permission")||e.includes("denied")||e.includes("Forbidden")?403:e.includes("mismatch")||e.includes("Invalid")||e.includes("Missing")?400:500}s(Yt,"getErrorStatus");import{createClient as pt}from"@supabase/supabase-js";function ue(e,t){let n=t?.requireAuth??!0,r="authorization, content-type, x-client-info, apikey",i=t?.extraHeaders?.length?`${r}, ${t.extraHeaders.join(", ")}`:r;return async c=>{let o=ce("ALLOWED_ORIGIN")||"*",a=s((l,b)=>zt(l,b,o),"respond"),u=s((l,b=200)=>a(l,b),"json"),m=s((l,b=400)=>a({error:l},b),"error");if(c.method==="OPTIONS")return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":o,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":i}});if(c.method!=="POST")return m("Method not allowed",405);let p=ce("SUPABASE_URL"),f=ce("SUPABASE_SECRET_KEY")||ce("SUPABASE_SERVICE_ROLE_KEY");if(!p||!f)return console.error("Missing SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY"),m("Server misconfigured",500);let g=pt(p,f,{auth:{autoRefreshToken:!1,persistSession:!1}}),S=null,C=null,v=c.headers.get("authorization");if(v?.startsWith("Bearer ")){let l=v.slice(7),b=ce("SUPABASE_ANON_KEY");if(b){C=pt(p,b,{global:{headers:{Authorization:`Bearer ${l}`}}});let{data:E,error:K}=await g.auth.getUser(l);!K&&E.user&&(S={id:E.user.id,email:E.user.email??void 0})}}if(n&&!S)return m("Unauthorized",401);let d={user:S,supabaseAdmin:g,userClient:C,json:u,error:m,respond:a};try{return await e(c,d)}catch(l){return console.error("Edge function error:",l),m("Internal error",500)}}}s(ue,"createEdgeFunction");function zt(e,t,n){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":n}})}s(zt,"jsonResponse");function ce(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e)??"":typeof process<"u"?process.env[e]??"":""}s(ce,"getEnv");var Qt=R({});function Wt(){return h("delete-account",Qt,async(e,t)=>{let{error:n}=await t.supabaseAdmin.auth.admin.deleteUser(t.uid);if(n)throw n;return{success:!0}})}s(Wt,"createDeleteAccount");var Gt=R({customClaims:ee(w(),Ne()),idempotencyKey:P(w())}),Jt=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated","plan","tier","provider","providers","sub","iss","aud"]);function Zt(e){let t=new Set(e.allowedClaimKeys);for(let n of t)if(Jt.has(n))throw new Error(`Claim key "${n}" is blocked - it is a privilege-escalation vector and cannot be self-assigned.`);return h("set-custom-claims",Gt,async(n,r)=>{let i=Object.keys(n.customClaims).filter(p=>!t.has(p));if(i.length>0)throw new Error(`Claim keys not allowed: ${i.join(", ")}`);let{data:{user:c},error:o}=await r.supabaseAdmin.auth.admin.getUserById(r.uid);if(o||!c)throw new Error("User not found");let u={...c.app_metadata??{},...n.customClaims},{error:m}=await r.supabaseAdmin.auth.admin.updateUserById(r.uid,{app_metadata:u});if(m)throw m;return{success:!0,customClaims:u}},"user")}s(Zt,"createSetCustomClaims");var Xt=R({});function er(){return h("get-custom-claims",Xt,async(e,t)=>{let{data:{user:n},error:r}=await t.supabaseAdmin.auth.admin.getUserById(t.uid);if(r||!n)throw new Error("User not found");return{customClaims:n.app_metadata??{}}},"user")}s(er,"createGetCustomClaims");var tr=R({claimsToRemove:I(z(w()),x(1,"At least one claim key is required"))}),rr=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated","plan","tier","provider","providers","sub","iss","aud"]);function nr(){return h("remove-custom-claims",tr,async(e,t)=>{let n=e.claimsToRemove.filter(a=>rr.has(a));if(n.length>0)throw new Error(`Protected claims cannot be removed: ${n.join(", ")}`);let{data:{user:r},error:i}=await t.supabaseAdmin.auth.admin.getUserById(t.uid);if(i||!r)throw new Error("User not found");let c={...r.app_metadata??{}};for(let a of e.claimsToRemove)delete c[a];let{error:o}=await t.supabaseAdmin.auth.admin.updateUserById(t.uid,{app_metadata:c});if(o)throw o;return{success:!0,customClaims:c}},"user")}s(nr,"createRemoveCustomClaims");var or=R({});function sr(){return h("get-user-auth-status",or,async(e,t)=>{let{data:{user:n},error:r}=await t.supabaseAdmin.auth.admin.getUserById(t.uid);if(r||!n)throw new Error("User not found");return{uid:n.id,email:n.email,emailVerified:n.email_confirmed_at!=null,customClaims:n.app_metadata??{},disabled:n.banned_until!=null}},"user")}s(sr,"createGetUserAuthStatus");function ir(e){return h("create-checkout-session",ze,async(t,n)=>{M(ar()),be();let r=j(n.supabaseAdmin),i={async createStripeSession(c){let o=await Z.checkout.sessions.create(c);return{id:o.id,url:o.url}},async retrieveTaxRate(c){let o=await Z.taxRates.retrieve(c);return{id:o.id,inclusive:o.inclusive}}};return De(t,n.uid,i,r,e)})}s(ir,"createCheckoutSession");function ar(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}s(ar,"getStripeKey");function lt(e){let t=typeof Deno<"u"?Deno.env.get(e):process.env[e];if(!t)throw new Error(`Missing ${e} environment variable`);return t}s(lt,"getEnvOrThrow");function cr(e){return ue(async(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return n.error("Missing Stripe signature",400);M(lt("STRIPE_SECRET_KEY"));let i=await ot(await t.text(),r,lt("STRIPE_WEBHOOK_SECRET"),Z,e,nt,j(n.supabaseAdmin),Oe(n.supabaseAdmin));return n.json({received:!0,message:i.message})},{requireAuth:!1,extraHeaders:["stripe-signature"]})}s(cr,"createStripeWebhook");var ur=R({userId:I(w(),x(1,"User ID is required"))});function dr(){return h("cancel-subscription",ur,async(e,t)=>{M(pr());let n=j(t.supabaseAdmin);return st(e.userId,n)})}s(dr,"createCancelSubscription");function pr(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}s(pr,"getStripeKey");var lr=R({userId:I(w(),x(1,"User ID is required")),newPriceId:I(w(),x(1,"Price ID is required")),billingConfigKey:I(w(),x(1,"Billing config key is required"))});function fr(e){return h("change-plan",lr,async(t,n)=>{if(!W(n.userRole,"admin")&&t.userId!==n.uid)throw new Error("Forbidden: cannot change another user's plan");M(mr());let r=j(n.supabaseAdmin);return it(t.userId,t.newPriceId,t.billingConfigKey,e,r)})}s(fr,"createChangePlan");function mr(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}s(mr,"getStripeKey");var gr=R({userId:I(w(),x(1,"User ID is required")),returnUrl:P(I(w(),Se()))});function yr(){return h("create-customer-portal",gr,async(e,t)=>{M(hr());let n=j(t.supabaseAdmin);return at(e.userId,n,e.returnUrl)})}s(yr,"createCustomerPortal");function hr(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}s(hr,"getStripeKey");var wr=R({userId:I(w(),x(1,"User ID is required"))});function Sr(){return h("refresh-subscription-status",wr,async(e,t)=>{M(Er()),be();let n=j(t.supabaseAdmin),i=(await n.getUser(e.userId)).customClaims||{},c=i.subscription?.subscriptionId;if(!c)throw new Error("No active subscription found");let o=await Z.subscriptions.retrieve(c),a={...i,subscription:{...i.subscription,status:o.status,currentPeriodStart:new Date(o.current_period_start*1e3).toISOString(),currentPeriodEnd:new Date(o.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:o.cancel_at_period_end}};return await n.setCustomUserClaims(e.userId,a),{success:!0,userId:e.userId,status:o.status,currentPeriodEnd:new Date(o.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:o.cancel_at_period_end}})}s(Sr,"createRefreshSubscriptionStatus");function Er(){let e=typeof Deno<"u"?Deno.env.get("STRIPE_SECRET_KEY"):process.env.STRIPE_SECRET_KEY;if(!e)throw new Error("Missing STRIPE_SECRET_KEY environment variable");return e}s(Er,"getStripeKey");function mt(e){let t={};for(let[n,r]of Object.entries(e))typeof r=="string"?t[n]=r.replace(/<[^>]*>/g,"").slice(0,1e3):typeof r=="object"&&r!==null&&!Array.isArray(r)?t[n]=mt(r):t[n]=r;return t}s(mt,"sanitizeProfileData");function ft(e){return typeof Deno<"u"?Deno.env.get(e):process.env[e]}s(ft,"getEnv");function gt(){return h("exchange-token",Ge,async(e,t)=>{let{provider:n,purpose:r,code:i,redirectUri:c,codeVerifier:o}=e;if(!Ze(c))throw new Error("Invalid redirect URI scheme");let a=te[n];if(!a?.endpoints?.tokenUrl)throw new Error(`Provider ${n} is not supported`);let u=n.toUpperCase(),m=ft(`${u}_CLIENT_ID`),p=ft(`${u}_CLIENT_SECRET`);if(!m||!p)throw new Error(`Provider ${n} is not configured`);let f=await fetch(a.endpoints.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"authorization_code",client_id:m,client_secret:p,code:i,redirect_uri:c,...o?{code_verifier:o}:{}}).toString()});if(!f.ok){let d=await f.text();throw console.error(`Token exchange error for ${n}: ${f.status}`,d),new Error(`Failed to exchange code for token: ${f.status}`)}let g=await f.json(),S={accessToken:g.access_token,refreshToken:g.refresh_token||null,expiresAt:g.expires_in?Math.floor(Date.now()/1e3)+g.expires_in:null,idToken:g.id_token||null,scope:g.scope?g.scope.split(" "):[]},C=null;if(S.accessToken&&a.endpoints.profileUrl)try{let d=await fetch(a.endpoints.profileUrl,{headers:{Authorization:`Bearer ${S.accessToken}`,Accept:"application/json"}});if(d.ok){let l=await d.json();C=mt(l)}}catch(d){console.warn(`Failed to fetch profile for ${n}:`,d)}let{error:v}=await t.supabaseAdmin.from("oauth_connections").upsert({user_id:t.uid,provider:n,purpose:r,credentials:S,profile:C,connected:!0,updated_at:new Date().toISOString()},{onConflict:"user_id,provider,purpose"});return v&&console.error("Error saving OAuth connection:",v),{success:!0,credentials:S,profile:C}})}s(gt,"createExchangeToken");var vr=R({provider:w(),purpose:Q(["authentication","api-access"])});function yt(){return h("disconnect",vr,async(e,t)=>{let{provider:n,purpose:r}=e,{data:i}=await t.supabaseAdmin.from("oauth_connections").select("credentials").eq("user_id",t.uid).eq("provider",n).eq("purpose",r).single();if(i?.credentials?.accessToken){let o=te[n],a="revokeUrl"in o?o.revokeUrl:null;if(a)try{await fetch(a.toString(),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:i.credentials.accessToken}).toString()})}catch(u){console.warn(`Failed to revoke token for ${n}:`,u)}}let{error:c}=await t.supabaseAdmin.from("oauth_connections").delete().eq("user_id",t.uid).eq("provider",n).eq("purpose",r);if(c)throw new Error(`Failed to disconnect: ${c.message}`);return{success:!0}})}s(yt,"createDisconnect");function ht(e){return typeof Deno<"u"?Deno.env.get(e):process.env[e]}s(ht,"getEnv");var Rr=R({provider:w(),refreshToken:I(w(),x(1,"Refresh token is required")),redirectUri:I(w(),Se("Valid redirect URI is required"))});function wt(){return h("refresh-token",Rr,async(e,t)=>{let{provider:n,refreshToken:r,redirectUri:i}=e,c=te[n];if(!c?.endpoints?.tokenUrl)throw new Error(`Provider ${n} does not support token refresh`);let o=n.toUpperCase(),a=ht(`${o}_CLIENT_ID`),u=ht(`${o}_CLIENT_SECRET`);if(!a||!u)throw new Error(`Provider ${n} is not configured`);let m=await fetch(c.endpoints.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"refresh_token",client_id:a,client_secret:u,refresh_token:r,redirect_uri:i}).toString()});if(!m.ok){let S=await m.text();throw console.error(`Token refresh error for ${n}:`,S),new Error(`Failed to refresh token: ${m.status}`)}let p=await m.json(),f={accessToken:p.access_token,refreshToken:p.refresh_token||r,expiresAt:p.expires_in?Math.floor(Date.now()/1e3)+p.expires_in:null,scope:p.scope?p.scope.split(" "):[]},{error:g}=await t.supabaseAdmin.from("oauth_connections").update({credentials:f,updated_at:new Date().toISOString()}).eq("user_id",t.uid).eq("provider",n);return g&&console.error("Error updating OAuth connection:",g),{success:!0,credentials:f}})}s(wt,"createRefreshToken");var br=R({purpose:P(Q(["authentication","api-access"]))});function St(){return h("get-connections",br,async(e,t)=>{let n=t.supabaseAdmin.from("oauth_connections").select("*").eq("user_id",t.uid);e.purpose&&(n=n.eq("purpose",e.purpose));let{data:r,error:i}=await n;if(i)throw new Error(`Failed to get connections: ${i.message}`);return{connections:(r||[]).map(o=>{let a=o.credentials?.expiresAt?o.credentials.expiresAt<Math.floor(Date.now()/1e3):!1;return{id:o.id,userId:o.user_id,provider:o.provider,purpose:o.purpose,connected:!a,createdAt:o.created_at,updatedAt:o.updated_at,hasCredentials:!a&&!!o.credentials,profile:o.profile}})}})}s(St,"createGetConnections");function kr(e){return h("ai-chat",Ye,async(t,n)=>rt(t,e,{userId:n.uid,requestId:crypto.randomUUID(),onCostRecord:s(async r=>{let{error:i}=await n.supabaseAdmin.from("ai_usage").insert({user_id:r.userId,model:r.model,provider:r.provider,prompt_tokens:r.usage.promptTokens,completion_tokens:r.usage.completionTokens,total_tokens:r.usage.totalTokens,provider_cost:r.providerCost,billed_cost:r.billedCost,markup:r.markup,request_id:r.requestId,created_at:r.timestamp});i&&console.error("[AI] Failed to record cost to Supabase:",i.message)},"onCostRecord")}))}s(kr,"createAIFunction");function Ar(e){return h("send-email",We,async(t,n)=>{let r=Cr("RESEND_API_KEY");if(!r)return new Response(JSON.stringify({success:!1,error:"Email provider not configured"}),{status:500,headers:{"Content-Type":"application/json"}});let i=Ue(r),c=await Be(t,e,i);return new Response(JSON.stringify(c),{status:c.success?200:400,headers:{"Content-Type":"application/json"}})})}s(Ar,"createEmailFunction");function Cr(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}s(Cr,"getEnv");import{createClient as qo}from"@supabase/supabase-js";function Ae(e){return typeof e!="string"?String(e):e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").toLowerCase()}s(Ae,"camelToSnake");function Et(e){return typeof e!="string"?String(e):e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}s(Et,"snakeToCamel");var vt=new Set(["createdAt","updatedAt"]);function Rt(e){if(e instanceof Date)return e.toISOString();if(typeof e=="string"){if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e))return e;if(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(e))return new Date(e.replace(" ","T")).toISOString()}return e}s(Rt,"toIsoString");function _r(){return{toBackendField:s(r=>{if(typeof r!="string")throw new TypeError(`Supabase field mapper: field name must be a string (e.g. "createdById"), got ${typeof r}. Check where query options (orderBy/where) are built \u2014 ensure "field" is the field name string, not a schema or other value.`);return Ae(r)},"toBackendField"),toBackendKeys:s(r=>{let i={};for(let[c,o]of Object.entries(r))i[Ae(c)]=o;return i},"toBackendKeys"),fromBackendRow:s(r=>{let i={};for(let[c,o]of Object.entries(r)){let a=Et(c);i[a]=vt.has(a)?Rt(o):o}return i},"fromBackendRow")}}s(_r,"createFieldMapperInternal");var U=_r(),Ir=["id","createdAt","updatedAt","createdById","updatedById","status"];function de(e){if(!e||typeof e!="object")return[];let t=e.entries;return!t||typeof t!="object"?[]:Object.keys(t)}s(de,"getEntityFieldNames");function X(e){let t=new Map;for(let n of e)t.set(Ae(n),n);for(let n of Ir)t.set(Ae(n),n);return{toBackendField:U.toBackendField,toBackendKeys:U.toBackendKeys,fromBackendRow:s(n=>{let r={};for(let[i,c]of Object.entries(n)){let o=t.get(i)??Et(i);r[o]=vt.has(o)?Rt(c):c}return r},"fromBackendRow")}}s(X,"createEntityAwareMapper");function Ce(e,t,n,r){let i=R({id:I(w(),x(1))});return h(`get_${e}`,i,async(c,o)=>{let{id:a}=c,{userRole:u,uid:m,supabaseAdmin:p}=o,{data:f,error:g}=await p.from(e).select("*").eq("id",a).single();if(g||!f)throw new A("Entity not found","not-found");if(!W(u,"admin")&&ne.includes(f.status))throw new A("Entity not found","not-found");let C=de(t),d=(C.length>0?X(C):U).fromBackendRow(f),b=re(d,t,u,r&&m?{documentData:d,uid:m,ownership:r}:void 0);return{id:f.id,...b}},n)}s(Ce,"createSupabaseGetEntity");var bt={create:24,update:12,delete:1,default:24};async function pe(e,t,n){try{let r=`${n}_${t}`,{data:i,error:c}=await e.from("idempotency").select("result").eq("idempotency_key",t).eq("operation",n).gt("expires_at",new Date().toISOString()).single();return c||!i?null:i.result}catch(r){throw console.error("[idempotency] Check failed:",r),new Error("[idempotency] Unable to verify idempotency. Operation rejected to prevent potential duplicate processing.")}}s(pe,"checkIdempotency");async function le(e,t,n,r,i,c){try{let o=`${n}_${t}`,a=c??bt[n]??bt.default,u=new Date;u.setHours(u.getHours()+a);let{error:m}=await e.from("idempotency").upsert({id:o,operation:n,idempotency_key:t,result:r,processed_by:i,expires_at:u.toISOString()},{onConflict:"idempotency_key"});m&&console.error("[idempotency] Store failed:",m)}catch(o){console.error("[idempotency] Store failed:",o)}}s(le,"storeIdempotency");async function xr(e){try{let{data:t,error:n}=await e.from("idempotency").delete().lt("expires_at",new Date().toISOString()).select("id");return n?(console.error("[idempotency] Cleanup failed:",n),0):t?.length??0}catch(t){return console.error("[idempotency] Cleanup failed:",t),0}}s(xr,"cleanupExpiredIdempotency");var fe=U;function Tr(e){return typeof e=="string"?e.toLowerCase():e}s(Tr,"normalizeValue");function Pr(e,t){let n={...e};for(let r of t)for(let i of r.fields)typeof n[i]=="string"&&(n[i]=n[i].toLowerCase());return n}s(Pr,"normalizePayloadForUniqueKeys");async function Dr(e,t,n,r,i){for(let c of n){if(r&&c.skipForDrafts===!0||!c.fields.every(p=>t[p]!=null&&t[p]!==""))continue;let a=i.from(e).select("*");for(let p of c.fields)a=a.eq(fe.toBackendField(p),Tr(t[p]));let{data:u,error:m}=await a.limit(1);if(!m&&u&&u.length>0){let p=fe.fromBackendRow(u[0]);if(c.findOrCreate)return{found:!0,existingDoc:p,findOrCreate:!0};let f=c.fields.join(" + ");throw new A(c.errorMessage||`Duplicate ${f}`,"already-exists",{details:{fields:c.fields,existingId:p.id}})}}return{found:!1}}s(Dr,"checkUniqueKeys");function _e(e,t,n,r){let i=R({payload:ee(w(),H()),idempotencyKey:P(w())});return h(`create_${e}`,i,async(c,o)=>{let{payload:a,idempotencyKey:u}=c,{uid:m,userRole:p,supabaseAdmin:f}=o;if(u){let B=await pe(f,u,"create");if(B)return B}let g=a.status??"draft",S=g==="draft",v=t.metadata?.uniqueKeys;if(v&&v.length>0){let B=await Dr(e,a,v,S,f);if(B.found&&B.findOrCreate)return re(B.existingDoc,t,p)}let d=v&&v.length>0?Pr(a,v):a,l={...d,status:g};Re(l,S?n:t);let b=Ee(m),E=fe.toBackendKeys(b),{createdAt:K,updatedAt:k,created_at:V,updated_at:Y,...$}=d,F=fe.toBackendKeys($),{data:T,error:O}=await f.from(e).insert({...F,status:g,...E}).select().single();if(O)throw new A(`Failed to create entity: ${O.message}`,"internal");let L=fe.fromBackendRow(T);return u&&await le(f,u,"create",L,m),L},r)}s(_e,"createSupabaseCreateEntity");var me=U;function Or(e){return typeof e=="string"?e.toLowerCase():e}s(Or,"normalizeValue");async function Br(e,t,n,r,i,c){for(let o of r){if(i&&o.skipForDrafts===!0||o.fields.filter(g=>g in n).length===0||!o.fields.every(g=>n[g]!=null&&n[g]!==""))continue;let m=c.from(e).select("*");for(let g of o.fields)m=m.eq(me.toBackendField(g),Or(n[g]));m=m.neq("id",t);let{data:p,error:f}=await m.limit(1);if(!f&&p&&p.length>0){let g=o.fields.join(" + ");throw new A(o.errorMessage||`Duplicate ${g}`,"already-exists",{details:{fields:o.fields,existingId:p[0].id}})}}}s(Br,"checkUniqueKeys");function Ie(e,t,n){let r=R({id:I(w(),x(1)),payload:ee(w(),H()),idempotencyKey:P(w())});return h(`update_${e}`,r,async(i,c)=>{let{id:o,payload:a,idempotencyKey:u}=i,{uid:m,supabaseAdmin:p}=c;if(u){let se=await pe(p,u,"update");if(se)return se}let{data:f,error:g}=await p.from(e).select("*").eq("id",o).single();if(g||!f)throw new A("Entity not found","not-found");let S={...me.fromBackendRow(f),...a},v=(S.status??f.status)==="draft",l=t.metadata?.uniqueKeys;l&&l.length>0&&await Br(e,o,S,l,v,p),v||Re(S,t);let b=ve(m),E=me.toBackendKeys(b),{createdAt:K,updatedAt:k,created_at:V,updated_at:Y,id:$,...F}=a,T=me.toBackendKeys(F),{data:O,error:L}=await p.from(e).update({...T,...E}).eq("id",o).select().single();if(L)throw new A(`Failed to update entity: ${L.message}`,"internal");let B=me.fromBackendRow(O);return u&&await le(p,u,"update",B,m),B},n)}s(Ie,"createSupabaseUpdateEntity");async function Ur(e,t,n,r){let i=[];if(!r)return i;if(r.incoming)for(let c of r.incoming){let{count:o,error:a}=await e.from(c.sourceCollection).select("*",{count:"exact",head:!0}).eq(c.sourceField,n);!a&&o&&o>0&&i.push({collection:c.sourceCollection,field:c.sourceField,count:o})}return r.outgoing,i}s(Ur,"findReferences");function xe(e,t,n){let r=R({id:I(w(),x(1))});return h(`delete_${e}`,r,async(i,c)=>{let{id:o}=i,{supabaseAdmin:a}=c;n&&!n.incoming&&console.warn(`[delete_${e}] referenceMetadata provided but incoming is undefined \u2014 reference check skipped`);let m=(await Ur(a,e,o,n)).filter(f=>n?.incoming?.find(S=>S.sourceCollection===f.collection&&S.sourceField===f.field)?.required===!0);if(m.length>0)throw new A("Cannot delete: item is referenced by other entities","permission-denied",{details:{references:m}});let{error:p}=await a.from(e).delete().eq("id",o);if(p)throw new A(`Failed to delete entity: ${p.message}`,"internal");return{success:!0}},t)}s(xe,"createSupabaseDeleteEntity");import{Buffer as Ct}from"node:buffer";var je=U;function G(e){return je.toBackendField(typeof e=="string"?e:String(e))}s(G,"toBackendColumn");function kt(e,t){let n={id:e,orderBy:t};return Ct.from(JSON.stringify(n)).toString("base64")}s(kt,"encodeCursor");function At(e){try{let t=JSON.parse(Ct.from(e,"base64").toString());if(!t||typeof t!="object"||typeof t.id!="string"||!t.id||typeof t.orderBy!="object"||t.orderBy===null||Array.isArray(t.orderBy))throw new A("Invalid cursor content","invalid-argument");return t}catch(t){throw t instanceof A?t:new A("Invalid cursor format","invalid-argument")}}s(At,"decodeCursor");var Fr=/^[a-zA-Z][a-zA-Z0-9_]*$/;function _t(e,t,n,r){if(!Fr.test(t))throw new A(`Invalid field name: '${t}'`,"invalid-argument");switch(n){case"==":return e.eq(t,r);case"!=":return e.neq(t,r);case">":return e.gt(t,r);case">=":return e.gte(t,r);case"<":return e.lt(t,r);case"<=":return e.lte(t,r);case"in":return e.in(t,Array.isArray(r)?r:[r]);case"not-in":return e.not(t,"in",Array.isArray(r)?r:[r]);case"array-contains":return e.contains(t,[r]);case"array-contains-any":return e.contains(t,Array.isArray(r)?r:[r]);default:return e.eq(t,r)}}s(_t,"applyOperator");function qr(e,t){let n=e;for(let r of t)n=_t(n,G(r.field),r.op,r.value);return n}s(qr,"applyPublicCondition");function ge(e,t,n,r,i,c){let o=R({where:P(z(ae([w(),H(),H()]))),orderBy:P(z(ae([I(w(),x(1)),Q(["asc","desc"])]))),limit:P(I(He(),Le(1))),startAfterId:P(w()),startAfterCursor:P(w()),search:P(R({field:w(),query:w()}))});return h(c?`listCard_${e}`:`list_${e}`,o,async(a,u)=>{let{where:m=[],orderBy:p=[],limit:f=1e3,startAfterId:g,startAfterCursor:S,search:C}=a,{userRole:v,uid:d,supabaseAdmin:l}=u,b=W(v,"admin"),E=r?.filter(y=>typeof y=="string"),K=E&&E.length>0?E.map(y=>G(y)).join(", ")+", id, status":"*",k=l.from(e).select(K,{count:"exact"});if(b||(k=k.not("status","in",[...ne])),i&&!b){if(c&&i.publicCondition&&i.publicCondition.length>0)k=qr(k,i.publicCondition);else if(!c&&i.ownerFields.length>0){let y=i.ownerFields[0];k=k.eq(G(y),d)}}if(C){if(E&&E.length>0){if(!E.includes(C.field))throw new A(`Search field '${C.field}' is not allowed`,"invalid-argument")}else if(C.field.startsWith("_")||C.field.includes("."))throw new A(`Search field '${C.field}' is not allowed`,"invalid-argument");let y=C.query.replace(/%/g,"\\%").replace(/_/g,"\\_");k=k.ilike(G(C.field),`%${y}%`)}for(let[y,_,q]of m){if(E&&E.length>0){if(!E.includes(y)&&y!=="status"&&y!=="id")throw new A(`Where field '${y}' is not allowed`,"invalid-argument")}else if(y.startsWith("_")||y.includes("."))throw new A(`Where field '${y}' is not allowed`,"invalid-argument");k=_t(k,G(y),_,q)}let V=p.some(([y])=>G(y)==="id");for(let[y,_]of p)k=k.order(G(y),{ascending:_==="asc"});!V&&p.length>0&&(k=k.order("id",{ascending:!0}));let Y=!1;if(S){Y=!0;try{let y=At(S);if(p.length===0)k=k.gt("id",y.id);else{let _=p[0][0],q=p[0][1],J=G(_),N=y.orderBy[_];q==="asc"?k=k.gte(J,N):k=k.lte(J,N)}}catch{throw new A("Invalid cursor format","invalid-argument")}k=k.limit(f+1)}else if(g){let y=parseInt(g,10);if(isNaN(y))throw new A("Invalid startAfterId","invalid-argument");k=k.range(y,y+f-1)}else k=k.range(0,f-1);let{data:$,error:F,count:T}=await k;if(F)throw new A(`Failed to list entities: ${F.message}`,"internal");let O=$||[];if(Y&&S&&O.length>0)try{let y=At(S);O=O.filter(_=>{if(p.length===0)return _.id!==y.id;let q=p[0][0],J=y.orderBy[q],N=_[je.toBackendField(q)];return!(_.id===y.id&&N===J)})}catch{}let L=s(y=>typeof y=="object"&&y!==null&&"thumbUrl"in y&&"fullUrl"in y,"isPictureObject"),B=s(y=>{if(Array.isArray(y)&&y.length>0){let _=y[0];if(L(_))return _.thumbUrl||_.fullUrl||null;if(typeof _=="string")return _}else if(L(y))return y.thumbUrl||y.fullUrl||null;return y},"optimizePictureField"),se=i&&d?{uid:d,ownership:i}:void 0,Me=de(t),Pt=Me.length>0?X(Me):je,he=O.map(y=>{let _=Pt.fromBackendRow(y),q=re(_,t,v,se?{...se,documentData:_}:void 0);if(E&&E.length>0){let N={id:_.id};for(let ie of E)if(ie in q){let Dt=q[ie];N[ie]=B(Dt)}return N}let J={id:_.id};for(let[N,ie]of Object.entries(q))J[N]=B(ie);return J}),Ke=O.length===f,we=null;if(Ke&&he.length>0){let y=he[he.length-1];if(Y&&p.length>0){let _=p[0][0],q={};q[_]=y[_],we=kt(y.id,q)}else if(Y)we=kt(y.id,{});else{let _=g?parseInt(g,10):0;we=String(_+O.length)}}return{items:he,lastVisible:we,count:T??void 0,hasMore:Ke}},n)}s(ge,"createSupabaseListEntities");var ye=U;function jr(e,t,n,r){switch(n){case"==":return e.eq(t,r);case"!=":return e.neq(t,r);case">":return e.gt(t,r);case">=":return e.gte(t,r);case"<":return e.lt(t,r);case"<=":return e.lte(t,r);case"in":return e.in(t,Array.isArray(r)?r:[r]);case"not-in":return e.not(t,"in",Array.isArray(r)?r:[r]);case"array-contains":return e.contains(t,[r]);default:return e.eq(t,r)}}s(jr,"applyOperator");function Te(e,t,n){let r=R({where:P(z(ae([w(),H(),H()]))),aggregate:R({field:w(),operation:Q(["count","sum","avg","min","max"])}),groupBy:P(z(w()))});return h(`aggregate_${e}`,r,async(i,c)=>{let{where:o=[],aggregate:a,groupBy:u}=i,{supabaseAdmin:m}=c,p=ye.toBackendField(a.field),f=m.from(e);for(let[v,d,l]of o)f=jr(f,ye.toBackendField(v),d,l);if(u&&u.length>0){let d=`${u.map(l=>ye.toBackendField(l)).join(", ")}, ${a.operation}(${p})`;f=f.select(d);for(let l of u)f=f.group(ye.toBackendField(l))}else a.operation==="count"?f=f.select("*",{count:"exact",head:!0}):f=f.select(p);let{data:g,error:S,count:C}=await f;if(S)throw new A(`Failed to aggregate entities: ${S.message}`,"internal");if(u&&u.length>0){let v={};for(let d of g||[]){let l=u.map(b=>d[ye.toBackendField(b)]).join("|");v[l]=d[`${a.operation}`]||0}return{value:v}}else{if(a.operation==="count")return{value:C??0};{let v=(g||[]).map(l=>l[p]).filter(l=>l!=null&&!isNaN(Number(l))).map(l=>Number(l));if(v.length===0)return{value:0};let d;switch(a.operation){case"sum":d=v.reduce((l,b)=>l+b,0);break;case"avg":d=v.reduce((l,b)=>l+b,0)/v.length;break;case"min":d=Math.min(...v);break;case"max":d=Math.max(...v);break;default:d=0}return{value:d}}}},n)}s(Te,"createSupabaseAggregateEntities");var Pe=U,It={guest:0,user:1,admin:2,super:3};function $r(e,t){let{createdAt:n,updatedAt:r,created_at:i,updated_at:c,...o}=e,a=Pe.toBackendKeys(o),u=Pe.toBackendKeys(Ee(t));return{...a,...u}}s($r,"prepareInsertRow");function Mr(e,t){let{createdAt:n,updatedAt:r,created_at:i,updated_at:c,id:o,...a}=e,u=Pe.toBackendKeys(a),m=Pe.toBackendKeys(ve(t));return{...u,...m}}s(Mr,"preparePatch");function $e(e,t,n,r,i){let c=(()=>{let o=[];return i.create&&o.push(i.create),i.update&&o.push(i.update),i.delete&&o.push(i.delete),o.length===0?"user":o.reduce((a,u)=>It[a]>=It[u]?a:u)})();return h(`bulk_${e}`,et,async(o,a)=>{let{uid:u,userRole:m,supabaseAdmin:p}=a;try{return await tt({collection:e,ops:o,createSchema:t,draftCreateSchema:n,updateSchema:r,access:i,uid:u,userRole:m,stampInsertMetadata:$r,stampUpdateMetadata:Mr,transact:s(async({inserts:f,updates:g,deletes:S})=>{let{data:C,error:v}=await p.rpc("crud_bulk",{p_collection:e,p_inserts:f.map(l=>l.row),p_updates:g.map(l=>({id:l.id,patch:l.patch})),p_deletes:S});if(v)throw new A(`Failed to execute bulk: ${v.message}`,"internal");let d=C??{};return{insertedIds:Array.isArray(d.insertedIds)?d.insertedIds:Array.isArray(d.inserted_ids)?d.inserted_ids:[],updatedIds:Array.isArray(d.updatedIds)?d.updatedIds:Array.isArray(d.updated_ids)?d.updated_ids:[],deletedIds:Array.isArray(d.deletedIds)?d.deletedIds:Array.isArray(d.deleted_ids)?d.deleted_ids:[]}},"transact"),audit:s((f,{counts:g})=>{console.log(`[${f}] uid=${u} inserts=${g.inserts} updates=${g.updates} deletes=${g.deletes}`)},"audit")})}catch(f){throw f instanceof Qe?new A(f.message,"invalid-argument",{details:{collidingIds:f.collidingIds,where:f.where}}):f}},c)}s($e,"createSupabaseBulkEntity");var Kr=/^[a-zA-Z][a-zA-Z0-9_]*$/;function xt(e){return`(${e.map(t=>JSON.stringify(String(t))).join(",")})`}s(xt,"postgrestList");function Lr(e,t,n,r){let i=Array.isArray(r)?r:[r];switch(n){case"==":return e.eq(t,r);case"!=":return e.neq(t,r);case">":return e.gt(t,r);case">=":return e.gte(t,r);case"<":return e.lt(t,r);case"<=":return e.lte(t,r);case"in":return e.in(t,i);case"not-in":return e.not(t,"in",xt(i));case"array-contains":return e.contains(t,[r]);case"array-contains-any":return e.overlaps(t,i)}}s(Lr,"applyCondition");function Tt(e,t){let n=Object.keys(t.fields),r=new Set(n),i=X(n),c=t.collection,o=r.has("status"),a=s(()=>e.from(c),"from"),u=s(d=>{if(!r.has(d)||!Kr.test(d))throw new A(`${t.name}: unknown field '${d}'`,"invalid-argument");return i.toBackendField(d)},"column"),m=s(d=>{let l={};for(let[b,E]of Object.entries(d))E!==void 0&&(l[u(b)]=E);return l},"toColumns"),p=s(d=>(d??[]).map(l=>i.fromBackendRow(l)),"fromRows"),f=s((d,l)=>{throw new A(`${d} ${c}: ${l.message}`,"internal")},"fail"),g=s(d=>d&&d.length>0?[...new Set(["id",...d])].map(u).join(", "):"*","selectList"),S=s((d,l,b)=>{let E=d;for(let[K,k,V]of l)E=Lr(E,u(K),k,V);return o&&!b&&(E=E.not("status","in",xt(ne))),E},"filtered"),C=s(async(d={})=>{let l=S(a().select(g(d.select)),d.where??[],d.includeHidden);for(let[K,k]of d.orderBy??[])l=l.order(u(K),{ascending:k==="asc"});d.limit!==void 0&&(l=l.limit(d.limit));let{data:b,error:E}=await l;return E&&f("list",E),p(b)},"list"),v=s(async d=>{let l=await C({...d,limit:2});if(l.length>1)throw new A(`${t.name}: more than one row matches`,"internal");return l[0]??null},"find");return{list:C,find:v,get:s((d,l)=>v({...l,where:[["id","==",d]]}),"get"),async insert(d){if(d.length===0)return[];let{data:l,error:b}=await a().insert(d.map(E=>m(E))).select("*");return b&&f("insert",b),p(l)},async update(d,l){if(d.length===0)throw new A(`${t.name}: update without a condition`,"invalid-argument");let{data:b,error:E}=await S(a().update(m(l)),d,!0).select("*");return E&&f("update",E),p(b)}}}s(Tt,"createEntityStore");function Hr(e){let t={};for(let[r,i]of Object.entries(e)){if(!Nr(i))continue;let c=i,o=c.collection,a=Xe(c),u=c.access;t[`create_${o}`]=_e(o,a.create,a.draft,u.create),t[`get_${o}`]=Ce(o,a.get,u.read,c.ownership),t[`list_${o}`]=ge(o,a.get,u.read,c.listFields,c.ownership,!1),t[`listCard_${o}`]=ge(o,a.get,u.read,Je(c),c.ownership,!0),t[`update_${o}`]=Ie(o,a.update,u.update);let p=a.get.metadata?.references;t[`delete_${o}`]=xe(o,u.delete,p),t[`aggregate_${o}`]=Te(o,a.get,u.read),t[`bulk_${o}`]=$e(o,a.create,a.draft,a.update,u)}let n=ue(async(r,i)=>{let c=await r.json().catch(()=>({})),o=c._functionName;if(!o)return i.error("Missing _functionName in request body",400);let a=t[o];if(!a)return i.error(`Unknown function: ${o}`,404);let{_functionName:u,...m}=c,p=new Request(r.url,{method:r.method,headers:r.headers,body:JSON.stringify(m)});return a(p)},{requireAuth:!1});return{handlers:t,serve:n}}s(Hr,"createSupabaseCrudFunctions");function Nr(e){return typeof e=="object"&&e!==null&&"collection"in e&&"fields"in e}s(Nr,"isEntity");export{ke as DEFAULT_RATE_LIMITS,qt as ReservationLostError,Ft as STRIPE_API_VERSION_PIN,jt as WEBHOOK_EVENTS_SQL,pe as checkIdempotency,Fe as checkRateLimitWithPostgres,Bt as classifyAIError,xr as cleanupExpiredIdempotency,kr as createAIFunction,dr as createCancelSubscription,fr as createChangePlan,De as createCheckoutAlgorithm,ir as createCheckoutSession,yr as createCustomerPortal,Wt as createDeleteAccount,yt as createDisconnect,ue as createEdgeFunction,Ar as createEmailFunction,Tt as createEntityStore,gt as createExchangeToken,St as createGetConnections,er as createGetCustomClaims,sr as createGetUserAuthStatus,Sr as createRefreshSubscriptionStatus,wt as createRefreshToken,nr as createRemoveCustomClaims,Ue as createResendProvider,Zt as createSetCustomClaims,cr as createStripeWebhook,Te as createSupabaseAggregateEntities,j as createSupabaseAuthProvider,_e as createSupabaseCreateEntity,Hr as createSupabaseCrudFunctions,xe as createSupabaseDeleteEntity,Ce as createSupabaseGetEntity,h as createSupabaseHandler,Oe as createSupabaseIdempotencyStore,ge as createSupabaseListEntities,Ie as createSupabaseUpdateEntity,$t as getFailureRate,Mt as getOperationCounts,Kt as getSlowOperations,Be as handleEmailRequest,Ut as mapClassifiedToHTTP,qe as recordOperationMetrics,Ot as resolveModelForTier,le as storeIdempotency};
22
22
  //# sourceMappingURL=index.js.map
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{c as Y}from"../../chunks/chunk-YTKDNZNW.js";import{a as Z,c as Q}from"../../chunks/chunk-HLNYUAZH.js";import{a as J,b as d,c as A,d as X}from"../../chunks/chunk-OFQVO3FD.js";import{B as H,D as z,a as m,c as E,f as M,g as I,j as $,v as G,w as B}from"../../chunks/chunk-LCDLG4VG.js";import{A as C,B as x,C as L,G as V,L as K,h as j,l as q,r as y,s as F,v as l}from"../../chunks/chunk-GYTCWMXV.js";import{a as O}from"../../chunks/chunk-5IPULSUX.js";import{b as W,f as U}from"../../chunks/chunk-3F4BWKQD.js";import{a as D}from"../../chunks/chunk-PWAGW4R6.js";import{a as o}from"../../chunks/chunk-AYY7UXNI.js";function re(s){return async t=>{let e=t.headers.get("authorization");if(!e?.startsWith("Bearer "))return new Response(JSON.stringify({error:"Missing authorization header"}),{status:401,headers:{"Content-Type":"application/json"}});let i=e.slice(7),n;try{n=(await M(i)).uid}catch{return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:401,headers:{"Content-Type":"application/json"}})}let a=await t.json().catch(()=>({})),c=x(L,a);if(!c.success){let u=c.issues.map(r=>r.message).join(", ");return new Response(JSON.stringify({error:`Validation failed: ${u}`}),{status:400,headers:{"Content-Type":"application/json"}})}return $(c.output,s,{userId:n,requestId:crypto.randomUUID()})}}o(re,"createAIChatRoute");var se=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated"]);function Ue(s){let t=new Set(s.allowedClaimKeys);for(let e of t)if(se.has(e))throw new Error(`Claim key "${e}" is blocked \u2014 it is a privilege-escalation vector and cannot be self-assigned.`);return o(async function(i,n){if(i.method!=="POST")return n.status(405).json({error:"Method not allowed"});try{let a=await I(i),{customClaims:c}=i.body;if(!c||typeof c!="object")throw m(new Error("customClaims must be an object"));let u=Object.keys(c).filter(w=>!t.has(w));if(u.length>0)throw m(new Error(`Claim keys not allowed: ${u.join(", ")}`));let{getFirebaseAdminAuth:r}=await import("../../chunks/server-IQ5JNJOM.js"),h={...(await r().getUser(a)).customClaims||{},...c};return await r().setCustomUserClaims(a,h),n.status(200).json({success:!0,customClaims:h})}catch(a){throw m(a)}},"handler")}o(Ue,"createSetCustomClaimsHandler");var k=null;async function P(){if(k)return k;let s=process.env.SUPABASE_URL,t=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!s||!t)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let{createClient:e}=await import("@supabase/supabase-js");return k=e(s,t,{auth:{autoRefreshToken:!1,persistSession:!1}}),k}o(P,"getSupabaseAdmin");async function _(s){if(E(s)==="supabase"){let e=await P();return{authProvider:Z(e),idempotencyStore:z(e)}}let{getFirebaseAdminAuth:t}=await import("../../chunks/server-IQ5JNJOM.js");return{authProvider:{async getUser(e){return{customClaims:(await t().getUser(e)).customClaims}},async setCustomUserClaims(e,i){await t().setCustomUserClaims(e,i)}},idempotencyStore:Y()}}o(_,"resolveBillingBackend");function g(s,t,e,i,n,a){return a!==void 0&&E(a),async(c,u)=>{try{if(c.method!==s)return u.status(405).json({error:"Method not allowed"});let r=x(t,c.body);if(!r.success)return u.status(400).json({error:`Validation failed: ${r.issues.map(T=>T.message).join(", ")}`});let p=r.output,S=await I(c,a),h=`${e}_${S}`,w=U[e]||U.api,f=a==="supabase"?await Q(await P(),h,w):await W(h,w);if(!f.allowed)return n?.audit({type:"rate_limit.exceeded",userId:S,metadata:{operation:e,remaining:0}}),u.status(429).json({error:`Rate limit exceeded. Try again in ${f.blockRemainingSeconds} seconds.`,retryAfter:f.blockRemainingSeconds});let b=await i(c,u,p,{uid:S});return b==null&&console.warn(`[${e}] businessLogic returned ${b} \u2014 ensure the handler returns a value or calls res.json() directly`),process.env.ENABLE_METRICS==="true"&&await O({operation:e,userId:S,status:"success",timestamp:new Date().toISOString(),metadata:{requestId:c.headers["x-request-id"]||"unknown"}}),b}catch(r){process.env.ENABLE_METRICS==="true"&&await O({operation:e,userId:c.headers.authorization?"authenticated":"anonymous",status:"failed",timestamp:new Date().toISOString(),metadata:{error:r instanceof Error?r.message:"Unknown error",requestId:c.headers["x-request-id"]||"unknown"}});try{m(r)}catch(p){let S=oe(p);return u.status(S.status).json({error:S.message})}return u.status(500).json({error:"Internal server error"})}}}o(g,"createVercelBaseFunction");function oe(s){return s instanceof K?{status:{"invalid-argument":400,"validation-failed":400,unauthenticated:401,"permission-denied":403,"not-found":404,"already-exists":409,"rate-limit-exceeded":429,"deadline-exceeded":504,unavailable:503}[s.code]??500,message:s.message}:{status:500,message:"Internal server error"}}o(oe,"classifiedToHttp");async function ie(s,t,e,i,n){J(process.env.STRIPE_SECRET_KEY||""),A();let a={async createStripeSession(r){let p=await d.checkout.sessions.create(r);return{id:p.id,url:p.url}},async retrieveTaxRate(r){let p=await d.taxRates.retrieve(r);return{id:p.id,inclusive:p.inclusive}}},{authProvider:c}=await _(n.backend),u=await G(t,e.uid,a,c,i);return s.status(200).json(u)}o(ie,"createCheckoutSessionLogic");function ne(s,t){return g("POST",V,"create_checkout_session",(e,i,n,a)=>ie(i,n,a,s,t),void 0,t.backend)}o(ne,"createCheckoutSession");function ae(s,t){return async(e,i)=>{if(e.method!=="POST"){i.status(405).json({error:"Method not allowed"});return}try{let n=e.headers["stripe-signature"];if(!n||Array.isArray(n))throw new Error("No Stripe signature found");let a=process.env.STRIPE_WEBHOOK_SECRET;if(!a)throw new Error("STRIPE_WEBHOOK_SECRET not configured");if(parseInt(e.headers["content-length"]||"0",10)>ee){i.status(413).json({error:"Payload too large"});return}let u=await ce(e),{authProvider:r,idempotencyStore:p}=await _(t.backend);await H(u,n,a,d,s,B,r,p),i.status(200).json({received:!0})}catch(n){D.error("[Vercel Webhook] Error",{error:n instanceof Error?n:new Error(String(n)),operation:"webhook_processing"}),i.status(400).json({error:"Webhook processing failed"})}}}o(ae,"createStripeWebhook");var ee=1*1024*1024;async function ce(s){let t=[],e=0;for await(let i of s){let n=typeof i=="string"?Buffer.from(i):i;if(e+=n.length,e>ee)throw new Error("Request body too large");t.push(n)}return Buffer.concat(t)}o(ce,"getRawBody");var ue=y({userId:C(l(),j(1,"User ID is required"))});function pe(s){return{}[s||""]||"free"}o(pe,"getTierFromPriceId");async function me(s,t,e,i){A();let n=i.uid,{getFirebaseAdminAuth:a}=await import("../../chunks/server-IQ5JNJOM.js"),u=(await a().getUser(n)).customClaims||{};if(!u.subscriptionId)return{success:!0,subscription:null,message:"User has no active subscription"};let r=await d.subscriptions.retrieve(u.subscriptionId),p={tier:pe(r.items.data[0]?.price.id),subscriptionId:r.id,customerId:r.customer,status:r.status,currentPeriodEnd:new Date(r.current_period_end*1e3).toISOString()};return await a().setCustomUserClaims(n,{...u,...p}),{success:!0,subscription:p,message:"Subscription status updated successfully"}}o(me,"refreshSubscriptionStatusLogic");var de=o(s=>g("POST",s||ue,"refresh_subscription_status",me),"refreshSubscriptionStatus"),le=de;var fe=y({userId:l()});async function ge(s,t,e,i){let n=i.uid,{getFirebaseAdminAuth:a}=await import("../../chunks/server-IQ5JNJOM.js"),u=await X(n,{async getUser(r){return a().getUser(r)},async setCustomUserClaims(r,p){await a().setCustomUserClaims(r,p)}});return t.status(200).json({success:u.success,cancelAtPeriodEnd:!0,endsAt:u.endsAt})}o(ge,"cancelSubscriptionLogic");var Se=o(()=>g("POST",fe,"cancel_subscription",ge),"cancelSubscription"),he=Se;var ye=y({userId:l(),newPriceId:l(),billingConfigKey:l()});async function Ae(s,t,e,i,n){A();let a=i.uid,{newPriceId:c,billingConfigKey:u}=e,r=n[u];if(!r||r.type!=="StripeSubscription")throw m(new Error("Invalid plan"));if(r.priceId!==c)throw m(new Error("Price ID mismatch"));let{getFirebaseAdminAuth:p}=await import("../../chunks/server-IQ5JNJOM.js"),h=(await p().getUser(a)).customClaims?.subscription?.subscriptionId;if(!h)throw m(new Error("No active subscription"));let w=await d.subscriptions.retrieve(h),f=await d.subscriptions.update(h,{items:[{id:w.items.data[0]?.id,price:c}],proration_behavior:"create_prorations"}),T=["active","canceled","past_due","trialing","incomplete"].includes(f.status)?f.status:"incomplete";return await B(a,{tier:r.tier,status:T,subscriptionEnd:new Date(f.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:f.cancel_at_period_end,subscriptionId:f.id,customerId:f.customer},{async getUser(N){return p().getUser(N)},async setCustomUserClaims(N,te){await p().setCustomUserClaims(N,te)}}),t.status(200).json({success:!0,newTier:r.tier,newPrice:r.price})}o(Ae,"changePlanLogic");var we=o(s=>g("POST",ye,"change_plan",(t,e,i,n)=>Ae(t,e,i,n,s)),"changePlan"),be=we;var ve=y({userId:l(),returnUrl:F(C(l(),q()))});async function Re(s,t,e,i){A();let n=i.uid,{returnUrl:a}=e,{getFirebaseAdminAuth:c}=await import("../../chunks/server-IQ5JNJOM.js"),r=(await c().getUser(n)).customClaims?.subscription?.customerId;if(!r)throw m(new Error("No customer found"));let p=await d.billingPortal.sessions.create({customer:r,return_url:a||`${process.env.FRONTEND_URL}/billing`});return t.status(200).json({url:p.url})}o(Re,"createCustomerPortalLogic");var Ce=o(()=>g("POST",ve,"create_customer_portal",Re),"createCustomerPortal"),xe=Ce;var R=process.env.FIREBASE_REGION||"europe-west1",Kt={region:R,memory:"1GiB",timeoutSeconds:60},Mt={region:R,memory:"512MiB",timeoutSeconds:30},Dt={region:R,memory:"256MiB",timeoutSeconds:20},Wt={region:R,memory:"256MiB",timeoutSeconds:15},$t={"europe-west1":"Belgium","europe-west2":"London","europe-west3":"Frankfurt","europe-west6":"Zurich","europe-central2":"Warsaw","us-central1":"Iowa","us-east1":"South Carolina","us-east4":"Northern Virginia","us-west1":"Oregon","asia-east1":"Taiwan","asia-northeast1":"Tokyo","asia-southeast1":"Singapore"},Gt=o(()=>{let t=["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"].filter(e=>!process.env[e]);if(t.length>0)throw new Error(`Missing required environment variables: ${t.join(", ")}`);console.log(`\u{1F30D} Firebase Functions configured for region: ${R}`)},"validateEnvironment");async function zt(){let{getFirebaseAdminApp:s}=await import("../../chunks/server-IQ5JNJOM.js");return await s()}o(zt,"initializeFirebaseAdmin");async function Jt(){let{getFirebaseAdminApp:s}=await import("../../chunks/server-IQ5JNJOM.js");return await s()}o(Jt,"getFirebaseAdmin");export{Dt as AUTH_CONFIG,$t as AVAILABLE_REGIONS,Wt as CRUD_CONFIG,R as FIREBASE_REGION,Kt as FUNCTION_CONFIG,Mt as STRIPE_CONFIG,he as cancelSubscription,be as changePlan,re as createAIChatRoute,ne as createCheckoutSession,xe as createCustomerPortal,Ue as createSetCustomClaimsHandler,ae as createStripeWebhook,Jt as getFirebaseAdmin,zt as initializeFirebaseAdmin,le as refreshSubscriptionStatus,B as updateUserSubscription,Gt as validateEnvironment};
21
+ import{b as E,e as M,f as I,g as Y}from"../../chunks/chunk-OZX5ZG44.js";import{a as Z,c as Q}from"../../chunks/chunk-HLNYUAZH.js";import{a as J,b as d,c as A,d as X}from"../../chunks/chunk-ZVHC2CAV.js";import{a as m,c as $,o as G,p as B,u as H,w as z}from"../../chunks/chunk-UYI56E6Q.js";import{A as C,B as x,C as L,G as V,L as K,h as j,l as q,r as y,s as F,v as l}from"../../chunks/chunk-G4FO76EA.js";import{a as O}from"../../chunks/chunk-2A4FPYNB.js";import{b as W,f as U}from"../../chunks/chunk-PJCJ5H2O.js";import{a as D}from"../../chunks/chunk-PWAGW4R6.js";import{a as o}from"../../chunks/chunk-AYY7UXNI.js";function re(s){return async t=>{let e=t.headers.get("authorization");if(!e?.startsWith("Bearer "))return new Response(JSON.stringify({error:"Missing authorization header"}),{status:401,headers:{"Content-Type":"application/json"}});let i=e.slice(7),n;try{n=(await M(i)).uid}catch{return new Response(JSON.stringify({error:"Invalid or expired token"}),{status:401,headers:{"Content-Type":"application/json"}})}let a=await t.json().catch(()=>({})),c=x(L,a);if(!c.success){let u=c.issues.map(r=>r.message).join(", ");return new Response(JSON.stringify({error:`Validation failed: ${u}`}),{status:400,headers:{"Content-Type":"application/json"}})}return $(c.output,s,{userId:n,requestId:crypto.randomUUID()})}}o(re,"createAIChatRoute");var se=new Set(["admin","isAdmin","isSuper","isSuperAdmin","role","roles","permissions","superuser","moderator","staff","elevated"]);function Ue(s){let t=new Set(s.allowedClaimKeys);for(let e of t)if(se.has(e))throw new Error(`Claim key "${e}" is blocked \u2014 it is a privilege-escalation vector and cannot be self-assigned.`);return o(async function(i,n){if(i.method!=="POST")return n.status(405).json({error:"Method not allowed"});try{let a=await I(i),{customClaims:c}=i.body;if(!c||typeof c!="object")throw m(new Error("customClaims must be an object"));let u=Object.keys(c).filter(w=>!t.has(w));if(u.length>0)throw m(new Error(`Claim keys not allowed: ${u.join(", ")}`));let{getFirebaseAdminAuth:r}=await import("../../chunks/server-RYGEBS2B.js"),h={...(await r().getUser(a)).customClaims||{},...c};return await r().setCustomUserClaims(a,h),n.status(200).json({success:!0,customClaims:h})}catch(a){throw m(a)}},"handler")}o(Ue,"createSetCustomClaimsHandler");var k=null;async function P(){if(k)return k;let s=process.env.SUPABASE_URL,t=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!s||!t)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let{createClient:e}=await import("@supabase/supabase-js");return k=e(s,t,{auth:{autoRefreshToken:!1,persistSession:!1}}),k}o(P,"getSupabaseAdmin");async function _(s){if(E(s)==="supabase"){let e=await P();return{authProvider:Z(e),idempotencyStore:z(e)}}let{getFirebaseAdminAuth:t}=await import("../../chunks/server-RYGEBS2B.js");return{authProvider:{async getUser(e){return{customClaims:(await t().getUser(e)).customClaims}},async setCustomUserClaims(e,i){await t().setCustomUserClaims(e,i)}},idempotencyStore:Y()}}o(_,"resolveBillingBackend");function g(s,t,e,i,n,a){return a!==void 0&&E(a),async(c,u)=>{try{if(c.method!==s)return u.status(405).json({error:"Method not allowed"});let r=x(t,c.body);if(!r.success)return u.status(400).json({error:`Validation failed: ${r.issues.map(T=>T.message).join(", ")}`});let p=r.output,S=await I(c,a),h=`${e}_${S}`,w=U[e]||U.api,f=a==="supabase"?await Q(await P(),h,w):await W(h,w);if(!f.allowed)return n?.audit({type:"rate_limit.exceeded",userId:S,metadata:{operation:e,remaining:0}}),u.status(429).json({error:`Rate limit exceeded. Try again in ${f.blockRemainingSeconds} seconds.`,retryAfter:f.blockRemainingSeconds});let b=await i(c,u,p,{uid:S});return b==null&&console.warn(`[${e}] businessLogic returned ${b} \u2014 ensure the handler returns a value or calls res.json() directly`),process.env.ENABLE_METRICS==="true"&&await O({operation:e,userId:S,status:"success",timestamp:new Date().toISOString(),metadata:{requestId:c.headers["x-request-id"]||"unknown"}}),b}catch(r){process.env.ENABLE_METRICS==="true"&&await O({operation:e,userId:c.headers.authorization?"authenticated":"anonymous",status:"failed",timestamp:new Date().toISOString(),metadata:{error:r instanceof Error?r.message:"Unknown error",requestId:c.headers["x-request-id"]||"unknown"}});try{m(r)}catch(p){let S=oe(p);return u.status(S.status).json({error:S.message})}return u.status(500).json({error:"Internal server error"})}}}o(g,"createVercelBaseFunction");function oe(s){return s instanceof K?{status:{"invalid-argument":400,"validation-failed":400,unauthenticated:401,"permission-denied":403,"not-found":404,"already-exists":409,"rate-limit-exceeded":429,"deadline-exceeded":504,unavailable:503}[s.code]??500,message:s.message}:{status:500,message:"Internal server error"}}o(oe,"classifiedToHttp");async function ie(s,t,e,i,n){J(process.env.STRIPE_SECRET_KEY||""),A();let a={async createStripeSession(r){let p=await d.checkout.sessions.create(r);return{id:p.id,url:p.url}},async retrieveTaxRate(r){let p=await d.taxRates.retrieve(r);return{id:p.id,inclusive:p.inclusive}}},{authProvider:c}=await _(n.backend),u=await G(t,e.uid,a,c,i);return s.status(200).json(u)}o(ie,"createCheckoutSessionLogic");function ne(s,t){return g("POST",V,"create_checkout_session",(e,i,n,a)=>ie(i,n,a,s,t),void 0,t.backend)}o(ne,"createCheckoutSession");function ae(s,t){return async(e,i)=>{if(e.method!=="POST"){i.status(405).json({error:"Method not allowed"});return}try{let n=e.headers["stripe-signature"];if(!n||Array.isArray(n))throw new Error("No Stripe signature found");let a=process.env.STRIPE_WEBHOOK_SECRET;if(!a)throw new Error("STRIPE_WEBHOOK_SECRET not configured");if(parseInt(e.headers["content-length"]||"0",10)>ee){i.status(413).json({error:"Payload too large"});return}let u=await ce(e),{authProvider:r,idempotencyStore:p}=await _(t.backend);await H(u,n,a,d,s,B,r,p),i.status(200).json({received:!0})}catch(n){D.error("[Vercel Webhook] Error",{error:n instanceof Error?n:new Error(String(n)),operation:"webhook_processing"}),i.status(400).json({error:"Webhook processing failed"})}}}o(ae,"createStripeWebhook");var ee=1*1024*1024;async function ce(s){let t=[],e=0;for await(let i of s){let n=typeof i=="string"?Buffer.from(i):i;if(e+=n.length,e>ee)throw new Error("Request body too large");t.push(n)}return Buffer.concat(t)}o(ce,"getRawBody");var ue=y({userId:C(l(),j(1,"User ID is required"))});function pe(s){return{}[s||""]||"free"}o(pe,"getTierFromPriceId");async function me(s,t,e,i){A();let n=i.uid,{getFirebaseAdminAuth:a}=await import("../../chunks/server-RYGEBS2B.js"),u=(await a().getUser(n)).customClaims||{};if(!u.subscriptionId)return{success:!0,subscription:null,message:"User has no active subscription"};let r=await d.subscriptions.retrieve(u.subscriptionId),p={tier:pe(r.items.data[0]?.price.id),subscriptionId:r.id,customerId:r.customer,status:r.status,currentPeriodEnd:new Date(r.current_period_end*1e3).toISOString()};return await a().setCustomUserClaims(n,{...u,...p}),{success:!0,subscription:p,message:"Subscription status updated successfully"}}o(me,"refreshSubscriptionStatusLogic");var de=o(s=>g("POST",s||ue,"refresh_subscription_status",me),"refreshSubscriptionStatus"),le=de;var fe=y({userId:l()});async function ge(s,t,e,i){let n=i.uid,{getFirebaseAdminAuth:a}=await import("../../chunks/server-RYGEBS2B.js"),u=await X(n,{async getUser(r){return a().getUser(r)},async setCustomUserClaims(r,p){await a().setCustomUserClaims(r,p)}});return t.status(200).json({success:u.success,cancelAtPeriodEnd:!0,endsAt:u.endsAt})}o(ge,"cancelSubscriptionLogic");var Se=o(()=>g("POST",fe,"cancel_subscription",ge),"cancelSubscription"),he=Se;var ye=y({userId:l(),newPriceId:l(),billingConfigKey:l()});async function Ae(s,t,e,i,n){A();let a=i.uid,{newPriceId:c,billingConfigKey:u}=e,r=n[u];if(!r||r.type!=="StripeSubscription")throw m(new Error("Invalid plan"));if(r.priceId!==c)throw m(new Error("Price ID mismatch"));let{getFirebaseAdminAuth:p}=await import("../../chunks/server-RYGEBS2B.js"),h=(await p().getUser(a)).customClaims?.subscription?.subscriptionId;if(!h)throw m(new Error("No active subscription"));let w=await d.subscriptions.retrieve(h),f=await d.subscriptions.update(h,{items:[{id:w.items.data[0]?.id,price:c}],proration_behavior:"create_prorations"}),T=["active","canceled","past_due","trialing","incomplete"].includes(f.status)?f.status:"incomplete";return await B(a,{tier:r.tier,status:T,subscriptionEnd:new Date(f.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:f.cancel_at_period_end,subscriptionId:f.id,customerId:f.customer},{async getUser(N){return p().getUser(N)},async setCustomUserClaims(N,te){await p().setCustomUserClaims(N,te)}}),t.status(200).json({success:!0,newTier:r.tier,newPrice:r.price})}o(Ae,"changePlanLogic");var we=o(s=>g("POST",ye,"change_plan",(t,e,i,n)=>Ae(t,e,i,n,s)),"changePlan"),be=we;var ve=y({userId:l(),returnUrl:F(C(l(),q()))});async function Re(s,t,e,i){A();let n=i.uid,{returnUrl:a}=e,{getFirebaseAdminAuth:c}=await import("../../chunks/server-RYGEBS2B.js"),r=(await c().getUser(n)).customClaims?.subscription?.customerId;if(!r)throw m(new Error("No customer found"));let p=await d.billingPortal.sessions.create({customer:r,return_url:a||`${process.env.FRONTEND_URL}/billing`});return t.status(200).json({url:p.url})}o(Re,"createCustomerPortalLogic");var Ce=o(()=>g("POST",ve,"create_customer_portal",Re),"createCustomerPortal"),xe=Ce;var R=process.env.FIREBASE_REGION||"europe-west1",Kt={region:R,memory:"1GiB",timeoutSeconds:60},Mt={region:R,memory:"512MiB",timeoutSeconds:30},Dt={region:R,memory:"256MiB",timeoutSeconds:20},Wt={region:R,memory:"256MiB",timeoutSeconds:15},$t={"europe-west1":"Belgium","europe-west2":"London","europe-west3":"Frankfurt","europe-west6":"Zurich","europe-central2":"Warsaw","us-central1":"Iowa","us-east1":"South Carolina","us-east4":"Northern Virginia","us-west1":"Oregon","asia-east1":"Taiwan","asia-northeast1":"Tokyo","asia-southeast1":"Singapore"},Gt=o(()=>{let t=["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"].filter(e=>!process.env[e]);if(t.length>0)throw new Error(`Missing required environment variables: ${t.join(", ")}`);console.log(`\u{1F30D} Firebase Functions configured for region: ${R}`)},"validateEnvironment");async function zt(){let{getFirebaseAdminApp:s}=await import("../../chunks/server-RYGEBS2B.js");return await s()}o(zt,"initializeFirebaseAdmin");async function Jt(){let{getFirebaseAdminApp:s}=await import("../../chunks/server-RYGEBS2B.js");return await s()}o(Jt,"getFirebaseAdmin");export{Dt as AUTH_CONFIG,$t as AVAILABLE_REGIONS,Wt as CRUD_CONFIG,R as FIREBASE_REGION,Kt as FUNCTION_CONFIG,Mt as STRIPE_CONFIG,he as cancelSubscription,be as changePlan,re as createAIChatRoute,ne as createCheckoutSession,xe as createCustomerPortal,Ue as createSetCustomClaimsHandler,ae as createStripeWebhook,Jt as getFirebaseAdmin,zt as initializeFirebaseAdmin,le as refreshSubscriptionStatus,B as updateUserSubscription,Gt as validateEnvironment};
22
22
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@donotdev/functions",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "private": false,
5
5
  "description": "Backend functions for DoNotDev Framework - Firebase, Vercel, and platform-agnostic implementations for auth, billing, CRUD, and OAuth",
6
6
  "main": "./lib/firebase/index.js",
@@ -53,7 +53,7 @@
53
53
  "serve": "firebase emulators:start --only functions"
54
54
  },
55
55
  "dependencies": {
56
- "@donotdev/core": "^0.2.1",
56
+ "@donotdev/core": "^0.2.2",
57
57
  "@donotdev/supabase": "^0.2.0"
58
58
  },
59
59
  "peerDependencies": {
@@ -23,7 +23,8 @@ import type { UserRole } from '@donotdev/core/server';
23
23
 
24
24
  import { FUNCTION_CONFIG } from './config/constants.js';
25
25
  import { handleError, DoNotDevError } from '../shared/errorHandling.js';
26
- import { assertAuthenticated, getUserRole } from '../shared/utils.js';
26
+ import { getUserRole } from '../shared/utils.js';
27
+ import { assertAuthenticated } from '../shared/utils/internal/auth.js';
27
28
 
28
29
  // Optional monitoring imports - only used when enabled
29
30
  // Lazy loaded to avoid unnecessary Firestore operations
@@ -236,7 +237,7 @@ export function createBaseFunction<TRequest, TResponse>(
236
237
  uid = request.auth?.uid || 'guest';
237
238
  } else {
238
239
  // Non-guest access: require authentication
239
- uid = assertAuthenticated(request.auth);
240
+ uid = assertAuthenticated(request.auth?.uid);
240
241
 
241
242
  // Verify user has required role level
242
243
  if (!hasRoleAccess(userRole, requiredRole)) {
@@ -36,18 +36,6 @@ export { createStripeWebhook } from './webhookHandler.js';
36
36
  */
37
37
  export * from '../../shared/billing/helpers/index.js';
38
38
 
39
- /**
40
- * Idempotency utilities for advanced users
41
- *
42
- * @version 0.1.0
43
- * @since 0.0.1
44
- * @author AMBROISE PARK Consulting
45
- */
46
- export {
47
- createIdempotencyStore,
48
- resetIdempotencyStore,
49
- } from '../../shared/billing/idempotency.js';
50
-
51
39
  /**
52
40
  * Firestore detection utilities
53
41
  *