@donotdev/functions 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (290) hide show
  1. package/lib/chunks/{chunk-IFOYVSPU.js → chunk-3F4BWKQD.js} +2 -2
  2. package/lib/chunks/{chunk-JTAGPPPL.js → chunk-5IPULSUX.js} +2 -2
  3. package/lib/chunks/chunk-6USHTJED.js +22 -0
  4. package/lib/chunks/chunk-6USHTJED.js.map +7 -0
  5. package/lib/chunks/{chunk-RM7DV6IQ.js → chunk-CXBSROEW.js} +2 -2
  6. package/lib/chunks/{chunk-5DTPEM64.js → chunk-GYTCWMXV.js} +1 -1
  7. package/lib/chunks/{chunk-5DTPEM64.js.map → chunk-GYTCWMXV.js.map} +1 -1
  8. package/lib/chunks/chunk-LCDLG4VG.js +151 -0
  9. package/lib/chunks/{chunk-UH4L3EF3.js.map → chunk-LCDLG4VG.js.map} +4 -4
  10. package/lib/chunks/{chunk-4U7QQWYG.js → chunk-MQANUSY3.js} +2 -2
  11. package/lib/chunks/chunk-OFQVO3FD.js +22 -0
  12. package/lib/chunks/chunk-OFQVO3FD.js.map +7 -0
  13. package/lib/chunks/chunk-PWAGW4R6.js +22 -0
  14. package/lib/chunks/chunk-PWAGW4R6.js.map +7 -0
  15. package/lib/chunks/{chunk-QJAU2MWV.js → chunk-US2VOP4S.js} +2 -2
  16. package/lib/chunks/{chunk-QJAU2MWV.js.map → chunk-US2VOP4S.js.map} +3 -3
  17. package/lib/chunks/chunk-YTKDNZNW.js +22 -0
  18. package/lib/chunks/chunk-YTKDNZNW.js.map +7 -0
  19. package/lib/chunks/{monitoring-AGCSU3FI.js → monitoring-E7JBYBHQ.js} +2 -2
  20. package/lib/chunks/{rateLimiter-6KO7AIZP.js → rateLimiter-SQISLOP5.js} +2 -2
  21. package/lib/chunks/{server-32A5RH4C.js → server-IQ5JNJOM.js} +2 -2
  22. package/lib/firebase/auth/getCustomClaims.d.ts +0 -0
  23. package/lib/firebase/auth/getUserAuthStatus.d.ts +0 -0
  24. package/lib/firebase/auth/index.d.ts +0 -0
  25. package/lib/firebase/auth/removeCustomClaims.d.ts +0 -0
  26. package/lib/firebase/auth/setCustomClaims.d.ts +0 -0
  27. package/lib/firebase/baseFunction.d.ts +0 -0
  28. package/lib/firebase/billing/cancelSubscription.d.ts +0 -0
  29. package/lib/firebase/billing/changePlan.d.ts +0 -0
  30. package/lib/firebase/billing/createCheckoutSession.d.ts +0 -0
  31. package/lib/firebase/billing/createCustomerPortal.d.ts +0 -0
  32. package/lib/firebase/billing/healthCheck.d.ts +0 -0
  33. package/lib/firebase/billing/index.d.ts +0 -0
  34. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -0
  35. package/lib/firebase/billing/webhookHandler.d.ts +0 -0
  36. package/lib/firebase/config/constants.d.ts +0 -0
  37. package/lib/firebase/config/index.d.ts +0 -0
  38. package/lib/firebase/config/secrets.d.ts +0 -0
  39. package/lib/firebase/crud/aggregate.d.ts +0 -0
  40. package/lib/firebase/crud/create.d.ts +0 -0
  41. package/lib/firebase/crud/delete.d.ts +0 -0
  42. package/lib/firebase/crud/get.d.ts +0 -0
  43. package/lib/firebase/crud/index.d.ts +0 -0
  44. package/lib/firebase/crud/list.d.ts +0 -0
  45. package/lib/firebase/crud/update.d.ts +0 -0
  46. package/lib/firebase/helpers/githubAccessHelper.d.ts +0 -0
  47. package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +0 -0
  48. package/lib/firebase/helpers/index.d.ts +0 -0
  49. package/lib/firebase/index.d.ts +0 -0
  50. package/lib/firebase/index.js +1 -1
  51. package/lib/firebase/index.js.map +2 -2
  52. package/lib/firebase/oauth/disconnect.d.ts +0 -0
  53. package/lib/firebase/oauth/exchangeToken.d.ts +0 -0
  54. package/lib/firebase/oauth/getConnections.d.ts +0 -0
  55. package/lib/firebase/oauth/githubAccess.d.ts +0 -0
  56. package/lib/firebase/oauth/index.d.ts +0 -0
  57. package/lib/firebase/oauth/refreshToken.d.ts +0 -0
  58. package/lib/firebase/registerCrudFunctions.d.ts +0 -0
  59. package/lib/firebase/scheduled/checkExpiredSubscriptions.d.ts +0 -0
  60. package/lib/firebase/scheduled/index.d.ts +0 -0
  61. package/lib/shared/ai/classifyAIError.d.ts +0 -0
  62. package/lib/shared/ai/costTracker.d.ts +0 -0
  63. package/lib/shared/ai/createAIRoute.d.ts +0 -0
  64. package/lib/shared/ai/index.d.ts +0 -0
  65. package/lib/shared/ai/resolveModelTier.d.ts +0 -0
  66. package/lib/shared/billing/createCheckout.d.ts +0 -0
  67. package/lib/shared/billing/firestoreIdempotency.d.ts +13 -0
  68. package/lib/shared/billing/helpers/index.d.ts +0 -0
  69. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +0 -0
  70. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +0 -0
  71. package/lib/shared/billing/idempotency.d.ts +1 -12
  72. package/lib/shared/billing/index.d.ts +0 -0
  73. package/lib/shared/billing/stripeClient.d.ts +45 -0
  74. package/lib/shared/billing/webhookHandler.d.ts +5 -4
  75. package/lib/shared/email/createEmailRoute.d.ts +0 -0
  76. package/lib/shared/email/index.d.ts +0 -0
  77. package/lib/shared/email/provider.d.ts +0 -0
  78. package/lib/shared/email/resendProvider.d.ts +0 -0
  79. package/lib/shared/errorHandling.d.ts +0 -0
  80. package/lib/shared/firebase.d.ts +0 -0
  81. package/lib/shared/github.d.ts +0 -0
  82. package/lib/shared/index.d.ts +0 -0
  83. package/lib/shared/index.js +1 -1
  84. package/lib/shared/index.js.map +0 -0
  85. package/lib/shared/logger.d.ts +0 -0
  86. package/lib/shared/metadata.d.ts +0 -0
  87. package/lib/shared/oauth/exchangeToken.d.ts +0 -0
  88. package/lib/shared/oauth/grantAccess.d.ts +0 -0
  89. package/lib/shared/oauth/index.d.ts +0 -0
  90. package/lib/shared/schema.d.ts +0 -0
  91. package/lib/shared/utils/detectFirestore.d.ts +0 -0
  92. package/lib/shared/utils/external/date.d.ts +0 -0
  93. package/lib/shared/utils/external/index.d.ts +0 -0
  94. package/lib/shared/utils/external/references.d.ts +0 -0
  95. package/lib/shared/utils/external/subscription.d.ts +0 -0
  96. package/lib/shared/utils/firebaseHelpers.d.ts +0 -0
  97. package/lib/shared/utils/functionWrapper.d.ts +0 -0
  98. package/lib/shared/utils/index.d.ts +0 -0
  99. package/lib/shared/utils/internal/auth.d.ts +0 -0
  100. package/lib/shared/utils/internal/firebase.d.ts +0 -0
  101. package/lib/shared/utils/internal/idempotency.d.ts +0 -0
  102. package/lib/shared/utils/internal/index.d.ts +0 -0
  103. package/lib/shared/utils/internal/monitoring.d.ts +0 -0
  104. package/lib/shared/utils/internal/rateLimiter.d.ts +0 -0
  105. package/lib/shared/utils/internal/validation.d.ts +0 -8
  106. package/lib/shared/utils/schemaValidation.d.ts +0 -0
  107. package/lib/shared/utils/validation.d.ts +0 -0
  108. package/lib/shared/utils/vercelHelpers.d.ts +0 -0
  109. package/lib/shared/utils.d.ts +0 -43
  110. package/lib/shared/validation.d.ts +0 -0
  111. package/lib/supabase/ai/createAIFunction.d.ts +0 -0
  112. package/lib/supabase/auth/deleteAccount.d.ts +0 -0
  113. package/lib/supabase/auth/getCustomClaims.d.ts +0 -0
  114. package/lib/supabase/auth/getUserAuthStatus.d.ts +0 -0
  115. package/lib/supabase/auth/removeCustomClaims.d.ts +0 -0
  116. package/lib/supabase/auth/setCustomClaims.d.ts +0 -0
  117. package/lib/supabase/baseFunction.d.ts +0 -0
  118. package/lib/supabase/billing/cancelSubscription.d.ts +0 -0
  119. package/lib/supabase/billing/changePlan.d.ts +0 -0
  120. package/lib/supabase/billing/createCheckoutSession.d.ts +0 -0
  121. package/lib/supabase/billing/createCustomerPortal.d.ts +0 -0
  122. package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +0 -0
  123. package/lib/supabase/crud/aggregate.d.ts +0 -0
  124. package/lib/supabase/crud/create.d.ts +0 -0
  125. package/lib/supabase/crud/delete.d.ts +0 -0
  126. package/lib/supabase/crud/get.d.ts +0 -0
  127. package/lib/supabase/crud/index.d.ts +0 -0
  128. package/lib/supabase/crud/list.d.ts +0 -8
  129. package/lib/supabase/crud/update.d.ts +0 -0
  130. package/lib/supabase/edgeFunction.d.ts +0 -0
  131. package/lib/supabase/email/createEmailFunction.d.ts +0 -0
  132. package/lib/supabase/helpers/authProvider.d.ts +0 -0
  133. package/lib/supabase/index.d.ts +3 -2
  134. package/lib/supabase/index.js +1 -1
  135. package/lib/supabase/index.js.map +3 -3
  136. package/lib/supabase/oauth/disconnect.d.ts +0 -0
  137. package/lib/supabase/oauth/exchangeToken.d.ts +0 -0
  138. package/lib/supabase/oauth/getConnections.d.ts +0 -0
  139. package/lib/supabase/oauth/index.d.ts +0 -0
  140. package/lib/supabase/oauth/refreshToken.d.ts +0 -0
  141. package/lib/supabase/registerCrudFunctions.d.ts +0 -0
  142. package/lib/supabase/utils/idempotency.d.ts +0 -0
  143. package/lib/supabase/utils/monitoring.d.ts +0 -0
  144. package/lib/supabase/utils/rateLimiter.d.ts +0 -0
  145. package/lib/vercel/api/ai/chat.d.ts +0 -0
  146. package/lib/vercel/api/ai/index.d.ts +0 -0
  147. package/lib/vercel/api/auth/get-custom-claims.d.ts +0 -0
  148. package/lib/vercel/api/auth/get-user-auth-status.d.ts +0 -0
  149. package/lib/vercel/api/auth/index.d.ts +0 -0
  150. package/lib/vercel/api/auth/remove-custom-claims.d.ts +0 -0
  151. package/lib/vercel/api/auth/set-custom-claims.d.ts +0 -0
  152. package/lib/vercel/api/billing/cancel.d.ts +0 -0
  153. package/lib/vercel/api/billing/change-plan.d.ts +0 -0
  154. package/lib/vercel/api/billing/create-checkout-session.d.ts +0 -0
  155. package/lib/vercel/api/billing/customer-portal.d.ts +0 -0
  156. package/lib/vercel/api/billing/index.d.ts +0 -0
  157. package/lib/vercel/api/billing/refresh-subscription-status.d.ts +0 -0
  158. package/lib/vercel/api/billing/webhook-handler.d.ts +0 -0
  159. package/lib/vercel/api/config/constants.d.ts +0 -0
  160. package/lib/vercel/api/config/firebase-admin.d.ts +0 -0
  161. package/lib/vercel/api/config/index.d.ts +0 -0
  162. package/lib/vercel/api/crud/create.d.ts +0 -0
  163. package/lib/vercel/api/crud/delete.d.ts +0 -0
  164. package/lib/vercel/api/crud/get.d.ts +0 -0
  165. package/lib/vercel/api/crud/index.d.ts +0 -0
  166. package/lib/vercel/api/crud/list.d.ts +0 -0
  167. package/lib/vercel/api/crud/update.d.ts +0 -0
  168. package/lib/vercel/api/index.d.ts +0 -0
  169. package/lib/vercel/api/index.js +1 -1
  170. package/lib/vercel/api/index.js.map +2 -2
  171. package/lib/vercel/api/oauth/check-github-access.d.ts +0 -0
  172. package/lib/vercel/api/oauth/exchange-token.d.ts +0 -0
  173. package/lib/vercel/api/oauth/grant-github-access.d.ts +0 -0
  174. package/lib/vercel/api/oauth/index.d.ts +0 -0
  175. package/lib/vercel/api/oauth/revoke-github-access.d.ts +0 -0
  176. package/lib/vercel/api/utils/cors.d.ts +0 -0
  177. package/lib/vercel/baseFunction.d.ts +0 -0
  178. package/package.json +2 -2
  179. package/src/firebase/billing/cancelSubscription.ts +1 -1
  180. package/src/firebase/billing/changePlan.ts +1 -5
  181. package/src/firebase/billing/createCheckoutSession.ts +1 -5
  182. package/src/firebase/billing/createCustomerPortal.ts +1 -1
  183. package/src/firebase/billing/healthCheck.ts +1 -1
  184. package/src/firebase/billing/refreshSubscriptionStatus.ts +1 -1
  185. package/src/firebase/billing/webhookHandler.ts +2 -2
  186. package/src/shared/__tests__/internalValidation.test.ts +1 -40
  187. package/src/shared/__tests__/logger.test.ts +31 -0
  188. package/src/shared/__tests__/utils.test.ts +1 -1
  189. package/src/shared/billing/__tests__/webhookHandler.test.ts +1 -38
  190. package/src/shared/billing/firestoreIdempotency.ts +189 -0
  191. package/src/shared/billing/helpers/subscriptionManagement.ts +1 -1
  192. package/src/shared/billing/idempotency.ts +5 -172
  193. package/src/shared/billing/stripeClient.ts +91 -0
  194. package/src/shared/billing/webhookHandler.ts +5 -5
  195. package/src/shared/logger.ts +4 -6
  196. package/src/shared/utils/internal/validation.ts +0 -18
  197. package/src/shared/utils.ts +0 -77
  198. package/src/supabase/billing/cancelSubscription.ts +1 -1
  199. package/src/supabase/billing/changePlan.ts +1 -1
  200. package/src/supabase/billing/createCheckoutSession.ts +1 -5
  201. package/src/supabase/billing/createCustomerPortal.ts +1 -1
  202. package/src/supabase/billing/refreshSubscriptionStatus.ts +1 -5
  203. package/src/supabase/billing/stripeWebhook.ts +2 -2
  204. package/src/supabase/crud/list.ts +2 -0
  205. package/src/supabase/index.ts +3 -3
  206. package/src/vercel/api/billing/change-plan.ts +1 -1
  207. package/src/vercel/api/billing/create-checkout-session.ts +1 -5
  208. package/src/vercel/api/billing/customer-portal.ts +1 -1
  209. package/src/vercel/api/billing/refresh-subscription-status.ts +1 -1
  210. package/src/vercel/api/billing/webhook-handler.ts +1 -1
  211. package/lib/chunks/chunk-2JL3GDTO.js +0 -151
  212. package/lib/chunks/chunk-2JL3GDTO.js.map +0 -7
  213. package/lib/chunks/chunk-4TVLH2W2.js +0 -22
  214. package/lib/chunks/chunk-6CQXHNVL.js +0 -22
  215. package/lib/chunks/chunk-6CQXHNVL.js.map +0 -7
  216. package/lib/chunks/chunk-6DSCPZC6.js +0 -22
  217. package/lib/chunks/chunk-6DSCPZC6.js.map +0 -7
  218. package/lib/chunks/chunk-7E6TGWHU.js +0 -22
  219. package/lib/chunks/chunk-7E6TGWHU.js.map +0 -7
  220. package/lib/chunks/chunk-7LT32OWE.js +0 -22
  221. package/lib/chunks/chunk-7VH2GJXT.js +0 -151
  222. package/lib/chunks/chunk-7VH2GJXT.js.map +0 -7
  223. package/lib/chunks/chunk-API5A4BV.js +0 -22
  224. package/lib/chunks/chunk-API5A4BV.js.map +0 -7
  225. package/lib/chunks/chunk-BUP7SXPV.js +0 -23
  226. package/lib/chunks/chunk-BXKRI3JJ.js +0 -22
  227. package/lib/chunks/chunk-BXKRI3JJ.js.map +0 -7
  228. package/lib/chunks/chunk-FSLGZD7A.js +0 -21
  229. package/lib/chunks/chunk-GVLSPWDD.js +0 -151
  230. package/lib/chunks/chunk-GVLSPWDD.js.map +0 -7
  231. package/lib/chunks/chunk-GXQVWEFT.js +0 -22
  232. package/lib/chunks/chunk-GXQVWEFT.js.map +0 -7
  233. package/lib/chunks/chunk-HB7EGXVI.js +0 -22
  234. package/lib/chunks/chunk-HB7EGXVI.js.map +0 -7
  235. package/lib/chunks/chunk-HM7XCMWW.js +0 -22
  236. package/lib/chunks/chunk-HM7XCMWW.js.map +0 -7
  237. package/lib/chunks/chunk-I7IOIL6U.js +0 -151
  238. package/lib/chunks/chunk-I7IOIL6U.js.map +0 -7
  239. package/lib/chunks/chunk-IFOYVSPU.js.map +0 -7
  240. package/lib/chunks/chunk-JTAGPPPL.js.map +0 -7
  241. package/lib/chunks/chunk-MZ232FUE.js +0 -22
  242. package/lib/chunks/chunk-MZ232FUE.js.map +0 -7
  243. package/lib/chunks/chunk-NE5ZTUUZ.js +0 -22
  244. package/lib/chunks/chunk-NE5ZTUUZ.js.map +0 -7
  245. package/lib/chunks/chunk-NP2AN2TV.js +0 -22
  246. package/lib/chunks/chunk-NP2AN2TV.js.map +0 -7
  247. package/lib/chunks/chunk-RM7DV6IQ.js.map +0 -7
  248. package/lib/chunks/chunk-RQZGIZHD.js +0 -151
  249. package/lib/chunks/chunk-RQZGIZHD.js.map +0 -7
  250. package/lib/chunks/chunk-TBEDQLOB.js +0 -23
  251. package/lib/chunks/chunk-TBEDQLOB.js.map +0 -7
  252. package/lib/chunks/chunk-TMHBP3HB.js +0 -22
  253. package/lib/chunks/chunk-TMHBP3HB.js.map +0 -7
  254. package/lib/chunks/chunk-UH4L3EF3.js +0 -151
  255. package/lib/chunks/chunk-UJBIU6TL.js +0 -22
  256. package/lib/chunks/chunk-UJBIU6TL.js.map +0 -7
  257. package/lib/chunks/chunk-VKEYW3NT.js +0 -22
  258. package/lib/chunks/chunk-VKEYW3NT.js.map +0 -7
  259. package/lib/chunks/chunk-XGXBMXJ6.js +0 -22
  260. package/lib/chunks/chunk-XGXBMXJ6.js.map +0 -7
  261. package/lib/chunks/chunk-Y44NEQQG.js +0 -22
  262. package/lib/chunks/chunk-Y44NEQQG.js.map +0 -7
  263. package/lib/chunks/chunk-ZVU3KPXI.js +0 -22
  264. package/lib/chunks/chunk-ZVU3KPXI.js.map +0 -7
  265. package/lib/chunks/monitoring-PVQMFL34.js +0 -22
  266. package/lib/chunks/monitoring-V7FZXTTW.js +0 -22
  267. package/lib/chunks/monitoring-V7FZXTTW.js.map +0 -7
  268. package/lib/chunks/rateLimiter-6KO7AIZP.js.map +0 -7
  269. package/lib/chunks/rateLimiter-OXVBFW5C.js +0 -22
  270. package/lib/chunks/rateLimiter-OXVBFW5C.js.map +0 -7
  271. package/lib/chunks/rateLimiter-U45OMTWR.js +0 -22
  272. package/lib/chunks/rateLimiter-U45OMTWR.js.map +0 -7
  273. package/lib/chunks/server-32A5RH4C.js.map +0 -7
  274. package/lib/chunks/server-7HDAP5DL.js +0 -22
  275. package/lib/chunks/server-7HDAP5DL.js.map +0 -7
  276. package/lib/chunks/server-S2IMFOY7.js +0 -22
  277. package/lib/chunks/server-S2IMFOY7.js.map +0 -7
  278. package/lib/shared/ai/createAIHandler.d.ts +0 -39
  279. package/lib/shared/ai/providers/anthropic.d.ts +0 -12
  280. package/lib/shared/ai/providers/google.d.ts +0 -10
  281. package/lib/shared/ai/providers/index.d.ts +0 -23
  282. package/lib/shared/ai/providers/openai.d.ts +0 -10
  283. package/lib/shared/ai/utils/parseSSE.d.ts +0 -22
  284. /package/lib/chunks/{chunk-7LT32OWE.js.map → chunk-3F4BWKQD.js.map} +0 -0
  285. /package/lib/chunks/{chunk-4TVLH2W2.js.map → chunk-5IPULSUX.js.map} +0 -0
  286. /package/lib/chunks/{chunk-BUP7SXPV.js.map → chunk-CXBSROEW.js.map} +0 -0
  287. /package/lib/chunks/{chunk-4U7QQWYG.js.map → chunk-MQANUSY3.js.map} +0 -0
  288. /package/lib/chunks/{chunk-FSLGZD7A.js.map → monitoring-E7JBYBHQ.js.map} +0 -0
  289. /package/lib/chunks/{monitoring-AGCSU3FI.js.map → rateLimiter-SQISLOP5.js.map} +0 -0
  290. /package/lib/chunks/{monitoring-PVQMFL34.js.map → server-IQ5JNJOM.js.map} +0 -0
@@ -1,151 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module';
2
- import { fileURLToPath } from 'node:url';
3
- import { dirname } from 'node:path';
4
- import { Buffer } from 'node:buffer';
5
- import process from 'node:process';
6
-
7
- const require = __createRequire(import.meta.url);
8
- const __filename = fileURLToPath(import.meta.url);
9
- const __dirname = dirname(__filename);
10
-
11
- if (typeof globalThis !== 'undefined') {
12
- globalThis.require = require;
13
- globalThis.__filename = __filename;
14
- globalThis.__dirname = __dirname;
15
- globalThis.Buffer = Buffer;
16
- globalThis.process = process;
17
- if (typeof global === 'undefined') {
18
- globalThis.global = globalThis;
19
- }
20
- }
21
- import{A as fe,B as P,D as he,E as Ee,F as M,H as ye,L as b,V,W as G,_ as D,a as se,b as H,c as ie,d as ae,k as ce,o as de,p as ue,q as j,r as pe,s as L,t as C,v as le,x as me}from"./chunk-6CQXHNVL.js";import{a as l}from"./chunk-NP2AN2TV.js";import{a as i}from"./chunk-AYY7UXNI.js";function E(e){let t,r,o;if(e instanceof b)t=e.code,r=e.message,o=e.details;else if(e&&typeof e=="object"&&"issues"in e&&(e instanceof Error&&e.name==="ValiError"||e.name==="ValiError"))t="invalid-argument",r="Validation failed",o={validationErrors:e.issues};else if(e&&typeof e=="object"&&"type"in e&&(e instanceof Error&&e.name==="EntityHookError"||e.name==="EntityHookError")){let n=e;switch(n.type){case"PERMISSION_DENIED":t="permission-denied";break;case"NOT_FOUND":t="not-found";break;case"ALREADY_EXISTS":t="already-exists";break;case"VALIDATION_ERROR":t="invalid-argument";break;case"NETWORK_ERROR":t="unavailable";break;default:t="internal"}r=n.message,o=void 0}else t="internal",r="An unexpected error occurred",o=void 0;throw t==="internal"&&(r="An unexpected error occurred"),new b(r,t,o?{details:o}:void 0)}i(E,"handleError");var ge=C(["firebase","supabase"]);function Tt(e){let t=P(ge,e);if(!t.success){let r=ge.options.map(o=>`'${o}'`).join(", ");throw new b(`Invalid backend ${JSON.stringify(e)}: expected one of ${r}`,"invalid-argument")}return t.output}i(Tt,"parseAuthBackend");async function Y(){let{getFirebaseAdminAuth:e}=await import("./server-S2IMFOY7.js");return e()}i(Y,"getFirebaseAuth");function Ke(e){if(!e||typeof e!="string")throw new Error("Authentication required");return e}i(Ke,"assertAuthenticated");async function Ct(e){Ke(e);try{let t={};G("serverAuth")?t=(await V("serverAuth").getUser(e))?.customClaims??{}:t=(await(await Y()).getUser(e)).customClaims??{};let r=t.role;if(!(r==="admin"||r==="super"||t.isAdmin===!0||t.isSuper===!0))throw new Error("Admin privileges required");return e}catch(t){throw t instanceof Error&&t.message==="Admin privileges required"?t:new Error("Failed to verify admin status")}}i(Ct,"assertAdmin");function qe(e){if(!e||!e.startsWith("Bearer "))throw new Error("Missing or invalid authorization header");let t=e.split("Bearer ")[1];if(!t)throw new Error("Missing token in authorization header");return t}i(qe,"extractBearerToken");async function He(e,t){try{return t==="supabase"?await je(e):t==="firebase"?{uid:(await(await Y()).verifyIdToken(e)).uid}:G("serverAuth")?{uid:(await V("serverAuth").verifyToken(e)).uid}:{uid:(await(await Y()).verifyIdToken(e)).uid}}catch{throw new Error("Invalid or expired token")}}i(He,"verifyToken");async function je(e){let{createClient:t}=await import("@supabase/supabase-js"),r=process.env.SUPABASE_URL,o=process.env.SUPABASE_SECRET_KEY||process.env.SUPABASE_SERVICE_ROLE_KEY;if(!r||!o)throw new Error("Missing SUPABASE_URL or SUPABASE_SECRET_KEY/SUPABASE_SERVICE_ROLE_KEY environment variables");let n=t(r,o,{auth:{autoRefreshToken:!1,persistSession:!1}}),{data:{user:s},error:a}=await n.auth.getUser(e);if(a||!s)throw new Error("Invalid or expired token");return{uid:s.id}}i(je,"verifySupabaseToken");async function Ve(e,t){let r=qe(e.headers.authorization),{uid:o}=await He(r,t);return o}i(Ve,"verifyAuthToken");var Pt=Ve;function X(e,t,r=ie){let o=ae[t];if(!o)throw new Error(`Unknown model for cost calculation: ${t}`);let n=e.promptTokens/1e6*o.promptPer1M,s=e.completionTokens/1e6*o.completionPer1M,a=n+s;return{providerCost:a,billedCost:a*r,markup:r,breakdown:{promptTokens:e.promptTokens,completionTokens:e.completionTokens,promptCost:n,completionCost:s}}}i(X,"calculateCost");async function Ge(e,t){let o={anthropic:i(async()=>{let{createAnthropic:a}=await import("@ai-sdk/anthropic");return c=>a({apiKey:c})(t)},"anthropic"),openai:i(async()=>{let{createOpenAI:a}=await import("@ai-sdk/openai");return c=>a({apiKey:c})(t)},"openai"),google:i(async()=>{let{createGoogleGenerativeAI:a}=await import("@ai-sdk/google");return c=>a({apiKey:c})(t)},"google")}[e];if(!o)throw new Error(`Unsupported AI provider: ${e}`);let n=Qe(e);return(await o())(n)}i(Ge,"resolveModel");var Ye={maxRequests:30,windowMs:6e4},I=null;async function Xe(){if(I)return I;let e=B("UPSTASH_REDIS_REST_URL"),t=B("UPSTASH_REDIS_REST_TOKEN");if(!e||!t)return console.warn("[AI] UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN not set. Rate limiting disabled."),I={check:i(async()=>{},"check")},I;try{let{Ratelimit:r}=await import("@upstash/ratelimit"),{Redis:o}=await import("@upstash/redis"),n=new o({url:e,token:t}),s=new Map;return I={check:i(async(a,c)=>{let u=`${c.maxRequests}:${c.windowMs}`,d=s.get(u);if(d||(d=new r({redis:n,limiter:r.slidingWindow(c.maxRequests,`${c.windowMs}ms`),prefix:"ai_rl"}),s.set(u,d)),!(await d.limit(a)).success)throw new Error(`Rate limit exceeded. Maximum ${c.maxRequests} requests per ${c.windowMs/1e3}s.`)},"check")},I}catch(r){return console.warn("[AI] Failed to initialize Upstash rate limiter:",r instanceof Error?r.message:r),I={check:i(async()=>{},"check")},I}}i(Xe,"getRateLimiter");function ze(e,t,r){let o={...r,...t};if(Object.keys(o).length===0)return;let n={};for(let[s,a]of Object.entries(o))n[s]=e.tool({description:a.description,parameters:e.jsonSchema(a.parameters)});return n}i(ze,"resolveTools");async function Je(e,t,r){let o=he(e);if(!o.success)return F(`Invalid AI request: ${o.issues?.map(p=>p.message).join(", ")}`,400);let n=e.provider||t.provider||"anthropic",s=se[n],a=e.model||t.model||s?.default||"claude-sonnet-4-20250514";if(s){let p=s.models;if(!p.includes(a))return F(`Model '${a}' is not allowed for provider '${n}'. Allowed: ${p.join(", ")}`,400)}try{await(await Xe()).check(r.userId,t.rateLimitConfig||Ye)}catch(p){return F(p instanceof Error?p.message:"Rate limit exceeded",429)}let c;try{c=await Ge(n,a)}catch(p){return F(`Failed to initialize provider: ${p instanceof Error?p.message:String(p)}`,500)}let u=e.messages.filter(p=>p.role==="system").map(p=>p.content),d=e.systemPrompt||t.systemPrompt||(u.length>0?u.join(`
22
- `):void 0),m=e.messages.filter(p=>p.role!=="system").map(p=>({role:p.role,content:p.content})),f=e.maxTokens||t.maxTokens||4096,h=e.temperature??t.temperature??.7,S=r.requestId||crypto.randomUUID(),U=await import("ai"),{streamText:k,generateText:A}=U,R=ze(U,e.tools,t.tools),T=i(async p=>{if(!r.onCostRecord)return;let w=t.cost?.markup??4,ne=X(p,a,w),Be={userId:r.userId,model:a,provider:n,usage:p,providerCost:ne.providerCost,billedCost:ne.billedCost,markup:w,timestamp:new Date().toISOString(),requestId:S};r.onCostRecord(Be).catch(We=>{console.error("[AI] Failed to record cost:",We)})},"recordCost");if(e.stream!==!1)return k({model:c,messages:m,system:d,maxTokens:f,temperature:h,tools:R,onFinish:i(async({usage:w})=>{await T({promptTokens:w.promptTokens,completionTokens:w.completionTokens,totalTokens:w.promptTokens+w.completionTokens})},"onFinish")}).toDataStreamResponse();let g=await A({model:c,messages:m,system:d,maxTokens:f,temperature:h,tools:R}),_={promptTokens:g.usage.promptTokens,completionTokens:g.usage.completionTokens,totalTokens:g.usage.promptTokens+g.usage.completionTokens};await T(_);let y=g.toolCalls?.map(p=>({id:p.toolCallId,name:p.toolName,args:p.args}))??[];return new Response(JSON.stringify({message:{role:"assistant",content:g.text},usage:_,finishReason:g.finishReason,toolCalls:y.length>0?y:void 0,model:a,provider:n}),{status:200,headers:{"Content-Type":"application/json"}})}i(Je,"handleAIRequest");function F(e,t){return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json"}})}i(F,"jsonError");function B(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}i(B,"getEnv");function Qe(e){let r={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",google:"GOOGLE_AI_API_KEY"}[e];if(r){let n=B(r);if(n)return n}let o=B("AI_API_KEY");if(!o)throw new Error(`Missing API key. Set ${r||"AI_API_KEY"} environment variable.`);return o}i(Qe,"getAIApiKey");function we(e){return typeof globalThis<"u"&&"Deno"in globalThis?globalThis.Deno?.env?.get(e):typeof process<"u"?process.env[e]:void 0}i(we,"getEnv");function Ze(e,t){if(t){let n=we(`AI_MODEL_${t.toUpperCase()}`);if(n)return n}let r=we(`AI_TIER_${e.toUpperCase()}`);return r||(Object.values(H).find(n=>n.id===e)?.defaultModel??H.STANDARD.defaultModel)}i(Ze,"resolveModelForTier");function et(e){let t=rt(e),r=ot(e);return t===429?{code:"rate_limited",retryable:!0,retryAfterMs:ve(e)??5e3,severity:"transient"}:t===529||t===503?{code:"overloaded",retryable:!0,retryAfterMs:ve(e)??1e4,severity:"transient"}:t===401?{code:"auth_error",retryable:!1,severity:"critical"}:t===402||r.includes("insufficient")||r.includes("credit")?{code:"credits_exhausted",retryable:!1,severity:"critical"}:!t&&(r.includes("fetch")||r.includes("network")||r.includes("ECONNREFUSED")||r.includes("ETIMEDOUT")||r.includes("timeout")||r.includes("aborted")||e instanceof TypeError)?{code:"network",retryable:!0,retryAfterMs:3e3,severity:"transient"}:{code:"internal",retryable:!1,severity:"critical"}}i(et,"classifyAIError");function tt(e){switch(e){case"rate_limited":return 429;case"overloaded":return 503;case"auth_error":return 502;case"credits_exhausted":return 502;case"network":return 502;case"internal":return 500}}i(tt,"mapClassifiedToHTTP");function rt(e){if(e&&typeof e=="object"){if("status"in e&&typeof e.status=="number")return e.status;if("error"in e&&typeof e.error?.status=="number")return e.error.status}}i(rt,"extractStatus");function ot(e){return e instanceof Error?e.message.toLowerCase():typeof e=="string"?e.toLowerCase():e&&typeof e=="object"&&"message"in e?String(e.message).toLowerCase():""}i(ot,"extractMessage");function ve(e){if(e&&typeof e=="object"){let t=e.headers;if(t){let r=typeof t.get=="function"?t.get("retry-after"):t["retry-after"];if(r){let o=Number(r);if(!Number.isNaN(o))return o*1e3}}}}i(ve,"extractRetryAfter");var Se="2025-02-24.acacia";var z=Se,$="orderId",W="productId";function J(e){return e===null?null:typeof e=="string"?e:e.id}i(J,"idOf");function ke(e){return{line1:e.line1,line2:e.line2,postalCode:e.postal_code,city:e.city,state:e.state,country:e.country}}i(ke,"toAddress");function nt(e){let t=e.customer_details,r=e.collected_information?.shipping_details??null;return{id:e.id,paymentStatus:e.payment_status,currency:e.currency,amountSubtotal:e.amount_subtotal,amountTax:e.total_details?.amount_tax??null,amountShipping:e.total_details?.amount_shipping??null,amountDiscount:e.total_details?.amount_discount??null,amountTotal:e.amount_total,customerId:J(e.customer),customer:t?{email:t.email,name:t.name,phone:t.phone,businessName:t.business_name,address:t.address?ke(t.address):null,taxIds:(t.tax_ids??[]).map(o=>({type:o.type,value:o.value})),taxExempt:t.tax_exempt}:null,shipping:r?{name:r.name,address:ke(r.address)}:null,invoiceId:J(e.invoice),paymentIntentId:J(e.payment_intent),metadata:e.metadata??{}}}i(nt,"toCheckoutSessionSnapshot");async function st(e,t){let r=[];for await(let o of e.checkout.sessions.listLineItems(t,{limit:100,expand:["data.price.product"]})){let n=o.price?.product,s=n&&typeof n!="string"&&!n.deleted?n.metadata[W]:void 0;if(!s)throw new Error(`Line item ${o.id} of session ${t} has no ${W} product metadata`);r.push({productId:s,name:o.description??"",quantity:o.quantity??0,amountSubtotal:o.amount_subtotal,amountDiscount:o.amount_discount,amountTax:o.amount_tax,amountTotal:o.amount_total})}return r}i(st,"listPaidLineItems");async function Ie(e,t,r,o,n,s,a){if(!r||r.slice(0,10)<z.slice(0,10))throw new Error(`Stripe event ${t} (order ${o.metadata?.[$]??"unknown"}) was rendered with API version ${r}; StripeOrder requires ${z} or later. Webhook payloads follow the webhook endpoint's API version, not STRIPE_API_VERSION, and an existing endpoint's version cannot be edited: create a new endpoint (POST /v1/webhook_endpoints with api_version=${z}), set STRIPE_WEBHOOK_SECRET to its signing secret, disable the old endpoint, then resend the failed events. Stripe retries this event for up to 3 days.`);let c=o.metadata??{},u=c.userId,d=c[$];if(!u||!d)throw new Error(`Order session ${o.id} is missing metadata: userId=${u}, orderId=${d}`);let m={userId:u,orderId:d,billingConfigKey:n,eventId:t},f=nt(o);if(e==="checkout.session.async_payment_succeeded"||e==="checkout.session.completed"&&o.payment_status!=="unpaid"){let S=await st(a,o.id);await s.onOrderPaid(f,S,m),l.info("[Webhook] Order paid",{orderId:d,billingConfigKey:n,operation:"order_paid"});return}switch(e){case"checkout.session.completed":l.info("[Webhook] Order awaiting async payment",{orderId:d,billingConfigKey:n,operation:"order_payment_pending"});return;case"checkout.session.async_payment_failed":s.onOrderPaymentFailed&&await s.onOrderPaymentFailed(f,m),l.warn("[Webhook] Order payment failed",{orderId:d,billingConfigKey:n,operation:"order_payment_failed"});return;case"checkout.session.expired":s.onOrderExpired&&await s.onOrderExpired(f,m),l.info("[Webhook] Order checkout expired",{orderId:d,billingConfigKey:n,operation:"order_expired"});return;default:return}}i(Ie,"handleOrderSessionEvent");function be(e,t){let{billingConfigKey:r,priceId:o,unitAmount:n,productName:s}=t,[a]=t.lineItems;if(t.lineItems.length!==1||!a||a.productId!==r||a.quantity!==1)throw new Error(`'${r}' is a single-price item: lineItems must be [{ productId: '${r}', quantity: 1 }]`);let c=!o&&!!n&&!!s,u=t.mode??(e.type==="StripeSubscription"?"subscription":"payment");if(o){if(e.priceId&&e.priceId!==o)throw new Error("Price ID mismatch with configuration");return{priceId:o,dynamic:c,mode:u}}if(c){if(u==="subscription")throw new Error("Dynamic pricing (unitAmount) is not supported for subscriptions. Use a Stripe priceId.");if(!e.maxUnitAmount)throw new Error("Dynamic pricing requires maxUnitAmount in billing config for security");if(n>e.maxUnitAmount)throw new Error(`Unit amount ${n} exceeds maximum allowed: ${e.maxUnitAmount}`);if(n<100)throw new Error("Unit amount must be at least 100 cents (1.00)");return{dynamic:c,mode:u}}if(!e.priceId)throw new Error(`'${r}' has no priceId in the back config: set one, send a priceId, or use StripeOrder for server-priced lines`);return{priceId:e.priceId,dynamic:c,mode:u}}i(be,"resolvePricePlan");function Ae(e){let t=e.mode||"payment";return{mode:t,line_items:[e.priceId?{price:e.priceId,quantity:1}:{price_data:{currency:e.currency||"eur",unit_amount:e.unitAmount,product_data:{name:e.productName}},quantity:1}],allow_promotion_codes:e.allowPromotionCodes,success_url:e.successUrl,cancel_url:e.cancelUrl,customer_email:e.customerEmail,metadata:e.metadata,...t==="subscription"&&{subscription_data:{metadata:e.metadata}}}}i(Ae,"toStripeSessionParams");var it={maxKeys:50,maxKeyLength:40,maxValueLength:500};function Z(e,t){try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`)}catch(r){throw new Error(`Invalid ${t} URL: ${e}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}i(Z,"validateCheckoutUrl");function Te(e){let t={};for(let[r,o]of Object.entries(e)){if(typeof o!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof o}`);t[r]=o.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"")}return t}i(Te,"sanitizeMetadata");function ee(e,t){let{maxKeys:r,maxKeyLength:o,maxValueLength:n}=it,s=Object.entries(e);if(s.length>r)throw new Error(`${t}: ${s.length} metadata keys, Stripe allows at most ${r} (server keys included)`);for(let[a,c]of s){if(a.length>o)throw new Error(`${t}: metadata key '${a}' is too long (max ${o} characters)`);if(/[[\]]/.test(a))throw new Error(`${t}: metadata key '${a}' must not contain square brackets`);if(c!==null&&String(c).length>n)throw new Error(`${t}: metadata value for key '${a}' is too long (max ${n} characters)`)}}i(ee,"assertStripeMetadata");function te(e){let t=[["metadata",e.metadata],["subscription_data.metadata",e.subscription_data?.metadata],["payment_intent_data.metadata",e.payment_intent_data?.metadata],["invoice_creation.invoice_data.metadata",e.invoice_creation?.invoice_data?.metadata],...(e.line_items??[]).map((r,o)=>[`line_items[${o}].price_data.product_data.metadata`,r.price_data?.product_data?.metadata])];for(let[r,o]of t)o&&ee(o,r)}i(te,"assertCheckoutSessionMetadata");function Ce(e,t){if(!e.orderId)throw new Error(`resolveLineItems for '${t}' returned no orderId`);if(e.orderId.length>200)throw new Error(`resolveLineItems for '${t}': orderId is sent as client_reference_id (max 200 characters), got ${e.orderId.length}`);if(e.lineItems.length===0)throw new Error(`resolveLineItems for '${t}' returned no lines`);e.session&&dt(e.session,t);for(let r of e.lineItems){if(!r.productId||!r.name)throw new Error(`resolveLineItems for '${t}' returned a line without productId or name`);if(!Number.isInteger(r.unitAmount)||r.unitAmount<0)throw new Error(`Line '${r.productId}': unitAmount must be a non-negative integer (smallest currency unit), got ${r.unitAmount}`);if(!Number.isInteger(r.quantity)||r.quantity<1)throw new Error(`Line '${r.productId}': quantity must be a positive integer, got ${r.quantity}`)}}i(Ce,"assertResolvedOrder");var at={minSeconds:1800,maxSeconds:1440*60},Re=5e3,ct=["card","sepa_debit"];function dt(e,t,r=Math.floor(Date.now()/1e3)){let{taxRateIds:o,paymentMethodTypes:n,expiresAt:s,invoiceFooter:a}=e;if(o&&o.some(c=>typeof c!="string"||c.length===0))throw new Error(`resolveLineItems for '${t}': session.taxRateIds must be non-empty strings`);if(n){if(n.length===0)throw new Error(`resolveLineItems for '${t}': session.paymentMethodTypes must not be empty`);for(let c of n)if(!ct.includes(c))throw new Error(`resolveLineItems for '${t}': unsupported payment method type '${c}'`)}if(s!==void 0){let{minSeconds:c,maxSeconds:u}=at;if(!Number.isInteger(s)||s<r+c||s>r+u)throw new Error(`resolveLineItems for '${t}': session.expiresAt must be a Unix time 30 minutes to 24 hours from now (Stripe), got ${s}`)}if(a!==void 0&&(a.length===0||a.length>Re))throw new Error(`resolveLineItems for '${t}': session.invoiceFooter must be 1 to ${Re} characters`)}i(dt,"assertResolvedOrderSession");var Q=new Map;async function re(e,t,r){for(let o of t){let n=Q.get(o);if(n||(n=e(o).then(s=>s.inclusive),Q.set(o,n),n.catch(()=>Q.delete(o))),await n)throw new Error(`'${r}': Tax Rate '${o}' is inclusive. StripeOrder unit amounts are excl. VAT: use an exclusive Tax Rate (inclusive: false).`)}}i(re,"assertExclusiveTaxRates");function Pe(e){return"createStripeSession"in e}i(Pe,"isSessionProvider");function xe(e,t){if(e)return e;let r=process.env.FRONTEND_URL;if(!r)throw new Error(`Missing ${t} redirect URL and FRONTEND_URL is not set`);return`${r}/billing/${t}`}i(xe,"resolveRedirectUrl");function ut(e,t,r){let o=t.session??{},n=e.tax.mode==="manual"?o.taxRateIds??e.tax.taxRateIds:void 0,s={...r.metadata,[$]:t.orderId};return{mode:"payment",client_reference_id:t.orderId,line_items:t.lineItems.map(a=>({price_data:{currency:e.currency,unit_amount:a.unitAmount,tax_behavior:"exclusive",product_data:{name:a.name,...a.description&&{description:a.description},metadata:{[W]:a.productId}}},quantity:a.quantity,...n&&n.length>0&&{tax_rates:n}})),automatic_tax:{enabled:e.tax.mode==="automatic"},tax_id_collection:e.taxIdCollection==="disabled"?{enabled:!1}:{enabled:!0,required:e.taxIdCollection==="required"?"if_supported":"never"},billing_address_collection:e.billingAddressCollection,...e.shipping&&{shipping_address_collection:{allowed_countries:e.shipping.allowedCountries},...e.shipping.shippingRateIds&&{shipping_options:e.shipping.shippingRateIds.map(a=>({shipping_rate:a}))}},customer_creation:e.customerCreation,invoice_creation:{enabled:e.invoiceCreation,...e.invoiceCreation&&{invoice_data:{metadata:s,...o.invoiceFooter&&{footer:o.invoiceFooter}}}},...o.paymentMethodTypes?{payment_method_types:o.paymentMethodTypes}:e.paymentMethodConfiguration&&{payment_method_configuration:e.paymentMethodConfiguration},...o.expiresAt!==void 0&&{expires_at:o.expiresAt},allow_promotion_codes:e.allowPromotionCodes===!0,success_url:r.successUrl,cancel_url:r.cancelUrl,customer_email:r.customerEmail,metadata:s,payment_intent_data:{metadata:s}}}i(ut,"buildOrderSessionParams");async function cr(e,...t){let r=t.length===3,[o,n,s,a]=t.length===3?[e.userId,...t]:t;if(!o)throw new Error(r?"Missing userId in request":"Missing authenticated userId");let c=e.billingConfigKey||e.metadata?.billingConfigKey;if(!c)throw new Error("Missing billingConfigKey (request or metadata)");let u={...e,billingConfigKey:c,lineItems:e.lineItems??[{productId:c,quantity:1}]},d=a[c];if(!d)throw new Error(`Invalid billing config key: ${c}`);let m=d.type==="StripeOrder",f=m?void 0:be(d,u);await s.getUser(o);let h=Te(u.metadata??{}),S={...h,userId:o,billingConfigKey:c};ee(m?{...S,[$]:""}:S,"metadata");let U=u.allowPromotionCodes??!0,k=u.unitAmount,A=u.productName;if(d.beforeCheckout){let _={...u,userId:o,mode:f?.mode??"payment",priceId:f?.priceId,metadata:u.metadata??{},allowPromotionCodes:U},y=await d.beforeCheckout(o,_,h);if(!y.allowed)throw new Error(y.reason||"Checkout blocked by beforeCheckout hook");f?.dynamic&&y.overrides&&(k=y.overrides.unitAmount??k,A=y.overrides.productName??A)}let R=xe(u.successUrl,"success"),T=xe(u.cancelUrl,"cancel");Z(R,"success"),Z(T,"cancel");let g;if(d.type==="StripeOrder"){if(!Pe(n))throw new Error(`'${c}' is a StripeOrder: the checkout provider must implement createStripeSession (StripeSessionProvider)`);d.tax.mode==="manual"&&await re(w=>n.retrieveTaxRate(w),d.tax.taxRateIds,c);let _=await d.resolveLineItems(u.lineItems,{userId:o,billingConfigKey:c,metadata:h});Ce(_,c);let y=_.session;if(y?.taxRateIds){if(d.tax.mode!=="manual")throw new Error(`resolveLineItems for '${c}': session.taxRateIds needs tax.mode 'manual'`);await re(w=>n.retrieveTaxRate(w),y.taxRateIds,c)}if(y?.invoiceFooter&&!d.invoiceCreation)throw new Error(`resolveLineItems for '${c}': session.invoiceFooter needs invoiceCreation`);let p=ut(d,_,{successUrl:R,cancelUrl:T,customerEmail:u.customerEmail,metadata:S});te(p),g=await n.createStripeSession(p)}else{let _=!!f?.dynamic&&!!k&&!!A;if(_&&d.maxUnitAmount&&k>d.maxUnitAmount)throw new Error(`Hook-overridden unit amount ${k} exceeds maximum allowed: ${d.maxUnitAmount}`);let y={priceId:f?.priceId,unitAmount:_?k:void 0,productName:_?A:void 0,currency:u.currency||d.currency||"eur",customerEmail:u.customerEmail,metadata:S,allowPromotionCodes:U,successUrl:R,cancelUrl:T,mode:f?.mode};if(Pe(n)){let p=Ae(y);te(p),g=await n.createStripeSession(p)}else g=await n.createCheckoutSession(y)}return{sessionId:g.id,sessionUrl:g.url}}i(cr,"createCheckoutAlgorithm");async function pr(e,t,r){let n=(await r.getUser(e)).customClaims||{};if(!t.tier||!t.status)throw new Error("Invalid subscription data: missing tier or status");t.customerId||console.warn(`[updateUserSubscription] customerId is undefined for user ${e}. Falling back to userId. This may cause issues with Stripe API calls.`);let s={tier:t.tier,subscriptionId:t.subscriptionId||null,customerId:t.customerId||e,status:t.status,subscriptionEnd:t.subscriptionEnd,cancelAtPeriodEnd:t.cancelAtPeriodEnd||!1,updatedAt:new Date().toISOString(),isDefault:!1},a={...n,subscription:s};await r.setCustomUserClaims(e,a)}i(pr,"updateUserSubscription");function oe(){if(process.env.FUNCTION_NAME||process.env.FIREBASE_CONFIG)return!0;let e=!!process.env.FIREBASE_PROJECT_ID,t=!!process.env.FIREBASE_CLIENT_EMAIL,r=!!process.env.FIREBASE_PRIVATE_KEY;return e&&t&&r}i(oe,"isFirestoreConfigured");async function fr(){if(!oe())return!1;try{let{getFirebaseAdminFirestore:e}=await import("./server-S2IMFOY7.js");return await e().collection("_health_check").limit(1).get(),!0}catch(e){return console.warn("[Firestore] Not available:",e instanceof Error?e.message:String(e)),!1}}i(fr,"isFirestoreAvailable");var v=class extends Error{static{i(this,"ReservationLostError")}eventId;constructor(t){super(`Reservation of webhook event ${t} is no longer held by this worker (lease retaken or row removed)`),this.name="ReservationLostError",this.eventId=t}},x=4200*1e3,K=720*60*60*1e3;function O(){return crypto.randomUUID()}i(O,"newOwnerToken");var pt=`
23
- CREATE TABLE IF NOT EXISTS public.webhook_events (
24
- event_id TEXT PRIMARY KEY,
25
- status TEXT NOT NULL CHECK (status IN ('processing', 'processed')),
26
- owner_token UUID NOT NULL,
27
- reserved_at TIMESTAMPTZ NOT NULL DEFAULT now(),
28
- processed_at TIMESTAMPTZ
29
- );
30
-
31
- -- Only service_role accesses this table
32
- ALTER TABLE public.webhook_events ENABLE ROW LEVEL SECURITY;
33
-
34
- CREATE INDEX IF NOT EXISTS idx_webhook_events_processed_at
35
- ON public.webhook_events (processed_at);
36
-
37
- -- The functions below run as the caller (SECURITY INVOKER) and refuse every
38
- -- role but service_role. EXECUTE is deliberately not revoked: on Supabase
39
- -- Postgres 17.6.1.x a permission-denied function call by anon/authenticated
40
- -- crashes the backend (signal 11), which restarts every connection.
41
- CREATE OR REPLACE FUNCTION public.webhook_events_assert_service_role()
42
- RETURNS VOID
43
- LANGUAGE plpgsql
44
- SET search_path = public
45
- AS $$
46
- BEGIN
47
- IF current_user IS DISTINCT FROM 'service_role' THEN
48
- RAISE EXCEPTION 'webhook_events is reserved to service_role (current role: %)', current_user
49
- USING ERRCODE = 'insufficient_privilege';
50
- END IF;
51
- END;
52
- $$;
53
-
54
- -- Atomic reservation. Returns:
55
- -- 'reserved' the caller now owns the event under p_owner_token
56
- -- 'processed' the event was already processed (skip, answer 2xx)
57
- -- 'in_progress' another worker holds a live lease (answer non-2xx, Stripe retries)
58
- -- A 'processing' row older than the lease is retaken (abandoned worker).
59
- CREATE OR REPLACE FUNCTION public.webhook_event_reserve(
60
- p_event_id TEXT,
61
- p_owner_token UUID,
62
- p_lease_seconds INT
63
- )
64
- RETURNS TEXT
65
- LANGUAGE plpgsql
66
- SET search_path = public
67
- AS $$
68
- DECLARE
69
- v_status TEXT;
70
- BEGIN
71
- PERFORM public.webhook_events_assert_service_role();
72
-
73
- INSERT INTO public.webhook_events (event_id, status, owner_token, reserved_at)
74
- VALUES (p_event_id, 'processing', p_owner_token, clock_timestamp())
75
- ON CONFLICT (event_id) DO UPDATE
76
- SET owner_token = EXCLUDED.owner_token,
77
- reserved_at = clock_timestamp()
78
- WHERE webhook_events.status = 'processing'
79
- AND webhook_events.reserved_at
80
- < clock_timestamp() - make_interval(secs => p_lease_seconds);
81
- IF FOUND THEN
82
- RETURN 'reserved';
83
- END IF;
84
-
85
- SELECT status INTO v_status
86
- FROM public.webhook_events
87
- WHERE event_id = p_event_id;
88
- IF v_status = 'processed' THEN
89
- RETURN 'processed';
90
- END IF;
91
- -- Live lease, or the row was released in between: Stripe retries either way
92
- RETURN 'in_progress';
93
- END;
94
- $$;
95
-
96
- -- Mark a reservation processed. Returns false when p_owner_token no longer owns
97
- -- the row (lease retaken, released, or deleted). Repeating it for the same
98
- -- owner is a no-op that returns true.
99
- CREATE OR REPLACE FUNCTION public.webhook_event_mark_processed(
100
- p_event_id TEXT,
101
- p_owner_token UUID
102
- )
103
- RETURNS BOOLEAN
104
- LANGUAGE plpgsql
105
- SET search_path = public
106
- AS $$
107
- BEGIN
108
- PERFORM public.webhook_events_assert_service_role();
109
-
110
- UPDATE public.webhook_events
111
- SET status = 'processed',
112
- processed_at = COALESCE(processed_at, clock_timestamp())
113
- WHERE event_id = p_event_id
114
- AND owner_token = p_owner_token;
115
- RETURN FOUND;
116
- END;
117
- $$;
118
-
119
- -- Drop a reservation after a processing failure. Returns false when
120
- -- p_owner_token does not own a 'processing' row (nothing is deleted).
121
- CREATE OR REPLACE FUNCTION public.webhook_event_release(
122
- p_event_id TEXT,
123
- p_owner_token UUID
124
- )
125
- RETURNS BOOLEAN
126
- LANGUAGE plpgsql
127
- SET search_path = public
128
- AS $$
129
- BEGIN
130
- PERFORM public.webhook_events_assert_service_role();
131
-
132
- DELETE FROM public.webhook_events
133
- WHERE event_id = p_event_id
134
- AND owner_token = p_owner_token
135
- AND status = 'processing';
136
- RETURN FOUND;
137
- END;
138
- $$;
139
-
140
- -- Enable pg_cron extension (if not already enabled)
141
- CREATE EXTENSION IF NOT EXISTS pg_cron;
142
-
143
- -- Cleanup webhook events older than 30 days (daily at 5 AM UTC).
144
- -- Stripe retries an event for up to 3 days, so older rows are never read again.
145
- SELECT cron.schedule(
146
- 'cleanup-webhook-events',
147
- '0 5 * * *',
148
- $$DELETE FROM public.webhook_events WHERE COALESCE(processed_at, reserved_at) < now() - interval '30 days'$$
149
- );
150
- `,lt=C(["reserved","processed","in_progress"]),Oe=de();function mt(e){let t=i(async(r,o,n)=>{let{data:s,error:a}=await e.rpc(r,o);if(a)throw E(a);let c=P(n,s);if(!c.success)throw E(new Error(`${r} returned an unexpected result: ${JSON.stringify(s)}`));return c.output},"call");return{async reserve(r){let o=O(),n=await t("webhook_event_reserve",{p_event_id:r,p_owner_token:o,p_lease_seconds:x/1e3},lt);return n==="reserved"?{state:n,ownerToken:o}:{state:n}},async markProcessed(r,o){if(!await t("webhook_event_mark_processed",{p_event_id:r,p_owner_token:o},Oe))throw new v(r)},async release(r,o){return t("webhook_event_release",{p_event_id:r,p_owner_token:o},Oe)}}}i(mt,"createSupabaseIdempotencyStore");var Ne="webhook_idempotency";function ft(){let e=new Map,t=i(async r=>{let o=e.get(r),n=Date.now();if(o?.status==="processed")return{state:"processed"};if(o&&n-o.at<x)return{state:"in_progress"};let s=O();return e.set(r,{status:"processing",ownerToken:s,at:n}),{state:"reserved",ownerToken:s}},"reserve");return{reserve:t,async checkAndReserve(r){return(await t(r)).state!=="reserved"},async markProcessed(r,o){let n=e.get(r);if(o!==void 0&&n?.ownerToken!==o)throw new v(r);e.set(r,{status:"processed",ownerToken:o??n?.ownerToken??O(),at:Date.now()})},async release(r,o){let n=e.get(r);return n?.status!=="processing"||n.ownerToken!==o?!1:(e.delete(r),!0)},async isProcessed(r){return e.get(r)?.status==="processed"}}}i(ft,"createInMemoryIdempotencyStore");var ht=me([j(),fe(ue(e=>typeof e=="object"&&e!==null&&typeof e.toMillis=="function","expiresAt must be a Firestore Timestamp or a number"),ce(e=>e.toMillis()))]),Et=pe({status:L(C(["processing","processed"])),ownerToken:L(le()),reservedAt:L(j()),expiresAt:L(ht)});function q(e,t){let r=P(Et,t);if(!r.success)throw new Error(`Malformed ${Ne}/${e}: ${r.issues.map(o=>o.message).join("; ")}`);return r.output}i(q,"parseEventDoc");function yt(){let e=null,t=i(async()=>{e||(e=await import("./server-S2IMFOY7.js"));let o=e.getFirebaseAdminFirestore();return{firestore:o,Timestamp:e.Timestamp,refOf:i(n=>o.collection(Ne).doc(n),"refOf")}},"load"),r=i(async o=>{let{firestore:n,Timestamp:s,refOf:a}=await t(),c=a(o);try{return await n.runTransaction(async u=>{let d=await u.get(c),m=Date.now();if(d.exists){let h=q(o,d.data());if(h.status==="processing"){if(m-(h.reservedAt??0)<x)return{state:"in_progress"}}else if((h.expiresAt??0)>=m)return{state:"processed"}}let f=O();return u.set(c,{eventId:o,status:"processing",ownerToken:f,reservedAt:m,expiresAt:s.fromMillis(m+K)}),{state:"reserved",ownerToken:f}})}catch(u){throw E(u)}},"reserve");return{reserve:r,async checkAndReserve(o){return(await r(o)).state!=="reserved"},async markProcessed(o,n){let{firestore:s,Timestamp:a,refOf:c}=await t(),u=c(o),d=Date.now(),m={eventId:o,status:"processed",processedAt:d,expiresAt:a.fromMillis(d+K)};try{if(n===void 0){await u.set(m);return}await s.runTransaction(async f=>{let h=await f.get(u);if((h.exists?q(o,h.data()):null)?.ownerToken!==n)throw new v(o);f.set(u,{...m,ownerToken:n})})}catch(f){throw f instanceof v?f:E(f)}},async release(o,n){let{firestore:s,refOf:a}=await t(),c=a(o);try{return await s.runTransaction(async u=>{let d=await u.get(c);if(!d.exists)return!1;let m=q(o,d.data());return m.status!=="processing"||m.ownerToken!==n?!1:(u.delete(c),!0)})}catch(u){throw E(u)}},async isProcessed(o){let{refOf:n}=await t();try{let s=await n(o).get();if(!s.exists)return!1;let a=q(o,s.data());return a.status!=="processing"&&(a.expiresAt??0)>=Date.now()}catch(s){throw E(s)}}}}i(yt,"createFirestoreIdempotencyStore");var N=null;function Ue(){return N||(oe()?N=yt():(console.warn("[Idempotency] Firestore not configured, using in-memory (not durable). Pass an explicit store."),N=ft()),N)}i(Ue,"createIdempotencyStore");function Ar(){N=null}i(Ar,"resetIdempotencyStore");async function Me(e,t,r,o,n){let s={sessionId:t.id,billingConfigKey:t.metadata?.billingConfigKey,userId:t.metadata?.userId,paymentStatus:t.payment_status};switch(e){case"checkout.session.completed":if(t.payment_status==="unpaid"){l.info("[Webhook] Purchase awaiting async payment",{...s,operation:"purchase_payment_pending"});return}if(t.payment_status!=="paid"&&t.payment_status!=="no_payment_required")throw E(new Error(`Checkout session ${t.id} has unknown payment_status ${String(t.payment_status)}`));await Le(t,r,o,n);return;case"checkout.session.async_payment_succeeded":await Le(t,r,o,n);return;case"checkout.session.async_payment_failed":l.warn("[Webhook] Async purchase payment failed, nothing granted",{...s,operation:"purchase_payment_failed"});return;case"checkout.session.expired":l.debug("[Webhook] Checkout session expired",s);return}}i(Me,"handleTierCheckoutEvent");async function Le(e,t,r,o){let{userId:n,billingConfigKey:s}=e.metadata||{};if(!n||!s)throw E(new Error(`Missing required metadata: userId=${n}, billingConfigKey=${s}`));let a=t[s];if(!a)throw E(new Error(`Unknown billing config key: ${s}`));if(l.info("[Webhook] Processing purchase",{userId:n,configKey:s,type:a.type,operation:"purchase_processing"}),a.type==="StripePayment"){if(!o)throw E(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:a.tier,status:M.ACTIVE,subscriptionEnd:D(a.duration),customerId:e.customer},o),a.onPurchaseSuccess)try{await a.onPurchaseSuccess(n,e.metadata||{})}catch(c){l.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onPurchaseSuccess",userId:n,operation:"hook_execution"})}}if(a.type==="StripeSubscription"){if(!o)throw E(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:a.tier,status:M.ACTIVE,subscriptionEnd:D(a.duration),subscriptionId:e.subscription,customerId:e.customer},o),a.onSubscriptionCreated)try{await a.onSubscriptionCreated(n,e.metadata||{})}catch(c){l.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onSubscriptionCreated",userId:n,operation:"hook_execution"})}}l.info("[Webhook] Purchase processed",{userId:n,configKey:s,operation:"purchase_processed"})}i(Le,"grantCheckoutPurchase");async function $e(e,t,r,o,n){let s=e.subscription;if(!s)return;let a=await o.subscriptions.retrieve(s),{userId:c,billingConfigKey:u}=a.metadata||{};if(!c||!u){l.error("[Webhook] Subscription metadata missing userId or billingConfigKey",{subscriptionId:s,hasUserId:!!c,hasBillingConfigKey:!!u,operation:"invoice_payment_succeeded_metadata_missing"});return}let d=t[u];if(!(!d||d.type!=="StripeSubscription")){if(!n)throw E(new Error("Auth provider required for subscription updates"));if(await r(c,{tier:d.tier,status:M.ACTIVE,subscriptionEnd:D(d.duration),subscriptionId:s,customerId:e.customer},n),d.onSubscriptionRenewed)try{await d.onSubscriptionRenewed(c,a.metadata||{})}catch(m){l.error("[Webhook] Hook failed (non-critical)",{error:m instanceof Error?m:new Error(String(m)),hookName:"onSubscriptionRenewed",userId:c,operation:"hook_execution"})}l.info("[Webhook] Subscription renewed",{userId:c,billingConfigKey:u,operation:"subscription_renewed"})}}i($e,"handleInvoicePaymentSucceeded");async function De(e,t,r,o){let{userId:n,billingConfigKey:s}=e.metadata||{};if(!n||!s)return;let a=t[s];if(!(!a||a.type!=="StripeSubscription")){if(!o)throw E(new Error("Auth provider required for subscription updates"));if(await r(n,{tier:Ee.FREE,status:M.CANCELED,subscriptionEnd:new Date(e.current_period_end*1e3).toISOString(),subscriptionId:e.id,customerId:e.customer},o),a.onSubscriptionCancelled)try{await a.onSubscriptionCancelled(n,e.metadata||{})}catch(c){l.error("[Webhook] Hook failed (non-critical)",{error:c instanceof Error?c:new Error(String(c)),hookName:"onSubscriptionCancelled",userId:n,operation:"hook_execution"})}l.info("[Webhook] Subscription cancelled",{userId:n,billingConfigKey:s,operation:"subscription_cancelled"})}}i(De,"handleSubscriptionDeleted");async function Fe(e,t){let{userId:r,billingConfigKey:o}=e.metadata||{};if(!r||!o){l.warn("[Webhook] Payment failed - missing metadata",{invoiceId:e.id,hasUserId:!!r,hasBillingConfigKey:!!o,operation:"payment_failed_metadata_missing"});return}let n=t[o];if(!n){l.error("[Webhook] Payment failed - unknown billing config",{error:new Error(`Unknown billing config key: ${o}`),userId:r,billingConfigKey:o,operation:"payment_failed_unknown_config"});return}if(n.type==="StripePayment"&&n.onPurchaseFailure)try{await n.onPurchaseFailure(r,e.metadata||{})}catch(s){l.error("[Webhook] Hook failed (non-critical)",{error:s instanceof Error?s:new Error(String(s)),hookName:"onPurchaseFailure",userId:r,operation:"hook_execution"})}if(n.type==="StripeSubscription"&&n.onPaymentFailed)try{await n.onPaymentFailed(r,e.metadata||{})}catch(s){l.error("[Webhook] Hook failed (non-critical)",{error:s instanceof Error?s:new Error(String(s)),hookName:"onPaymentFailed",userId:r,operation:"hook_execution"})}l.warn("[Webhook] Payment failed",{userId:r,billingConfigKey:o,operation:"payment_failed"})}i(Fe,"handlePaymentFailed");var gt=3,_t=200;async function qr(e,t,r,o,n,s,a,c=Ue()){try{ye(n);let u=n,d=await o.webhooks.constructEventAsync(e,t,r);l.info("[Webhook] Processing event",{eventType:d.type,eventId:d.id,operation:"webhook_processing"});let m=await c.reserve(d.id);if(m.state==="processed")return l.info("[Webhook] Already processed",{eventId:d.id}),{success:!0,message:"Event already processed"};if(m.state==="in_progress")throw l.warn("[Webhook] Event in progress in another delivery",{eventId:d.id,eventType:d.type,operation:"webhook_in_progress"}),new b(`Stripe event ${d.id} is being processed by another delivery; answering non-2xx so Stripe retries it`,"unavailable",{details:{eventId:d.id,reason:"webhook_event_in_progress"}});let{ownerToken:f}=m;a||l.warn("[Webhook] authProvider is null \u2014 subscription-related events will fail",{eventType:d.type,eventId:d.id});try{await St(d,u,s,o,a)}catch(h){throw l.error("[Webhook] Event processing failed, releasing reservation",{error:h instanceof Error?h:new Error(String(h)),eventId:d.id,eventType:d.type,operation:"webhook_routing"}),await wt(c,d.id,f),h}return await vt(c,d.id,f),{success:!0,message:"Webhook processed"}}catch(u){throw E(u)}}i(qr,"processWebhook");async function wt(e,t,r){try{await e.release(t,r)||l.warn("[Webhook] Reservation not released: no longer owned",{eventId:t,operation:"idempotency_release_stale"})}catch(o){l.error("[Webhook] Failed to release idempotency reservation",{error:o instanceof Error?o:new Error(String(o)),eventId:t,operation:"idempotency_release"})}}i(wt,"releaseReservation");async function vt(e,t,r){for(let o=1;;o++)try{await e.markProcessed(t,r);return}catch(n){let s=n instanceof Error?n:new Error(String(n));if(n instanceof v)throw l.error("[Webhook] Event processed but its reservation was retaken by another delivery; hooks may run twice",{error:s,eventId:t,operation:"idempotency_mark_processed_lost"}),n;if(o>=gt)throw l.error("[Webhook] Event processed but not recorded; answering non-2xx, Stripe will redeliver after the lease and hooks re-run",{error:s,eventId:t,attempts:o,operation:"idempotency_mark_processed_failed"}),n;l.warn("[Webhook] markProcessed failed, retrying",{eventId:t,attempt:o,error:s.message}),await new Promise(a=>setTimeout(a,_t*o))}}i(vt,"markProcessedWithRetry");async function St(e,t,r,o,n){switch(e.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":case"checkout.session.async_payment_failed":case"checkout.session.expired":await kt(e.type,e.id,e.api_version,e.data.object,t,r,o,n);break;case"invoice.payment_succeeded":await $e(e.data.object,t,r,o,n);break;case"customer.subscription.deleted":await De(e.data.object,t,r,n);break;case"invoice.payment_failed":await Fe(e.data.object,t);break;default:l.debug("[Webhook] Unhandled event type",{type:e.type})}}i(St,"routeEvent");async function kt(e,t,r,o,n,s,a,c){let u=o.metadata?.billingConfigKey,d=u?n[u]:void 0;if(u&&d?.type==="StripeOrder"){await Ie(e,t,r,o,u,d,a);return}await Me(e,o,n,s,c)}i(kt,"handleCheckoutSessionEvent");export{E as a,ge as b,Tt as c,Ke as d,Ct as e,He as f,Ve as g,Pt as h,X as i,Je as j,Ze as k,et as l,tt as m,te as n,Se as o,z as p,$ as q,W as r,nt as s,st as t,Ie as u,cr as v,pr as w,oe as x,fr as y,v as z,x as A,K as B,pt as C,mt as D,ft as E,yt as F,Ue as G,Ar as H,qr as I};
151
- //# sourceMappingURL=chunk-I7IOIL6U.js.map