@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
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{a as l}from"./chunk-NP2AN2TV.js";import{a as o}from"./chunk-AYY7UXNI.js";async function u(){let{getFirebaseAdminFirestore:i}=await import("./server-7HDAP5DL.js");return i()}o(u,"getFirestore");var s=new Map;async function p(i,e){let a=Date.now(),n=s.get(i);if(n?.blockUntil&&a<n.blockUntil)return{allowed:!1,remaining:0,resetAt:new Date(n.blockUntil),blockRemainingSeconds:Math.ceil((n.blockUntil-a)/1e3)};n&&a>=n.windowStart+e.windowMs&&s.delete(i);let t=s.get(i)||{attempts:0,windowStart:a,blockUntil:null};return t.attempts>=e.maxAttempts?(t.blockUntil=a+e.blockDurationMs,s.set(i,t),l.warn("Rate limit exceeded",{key:i,attempts:t.attempts,blockUntil:new Date(t.blockUntil)}),{allowed:!1,remaining:0,resetAt:new Date(t.blockUntil),blockRemainingSeconds:Math.ceil(e.blockDurationMs/1e3)}):(t.attempts+=1,s.set(i,t),{allowed:!0,remaining:e.maxAttempts-t.attempts,resetAt:new Date(t.windowStart+e.windowMs),blockRemainingSeconds:null})}o(p,"checkRateLimit");async function R(i,e){let a=await u(),n=a.collection("rateLimits").doc(i);try{let t=Date.now(),m={allowed:!0,remaining:e.maxAttempts-1,resetAt:new Date(t+e.windowMs),blockRemainingSeconds:null};return await a.runTransaction(async c=>{let d=await c.get(n);if(!d.exists){c.set(n,{attempts:1,windowStart:t,blockUntil:null,lastUpdated:t}),m={allowed:!0,remaining:e.maxAttempts-1,resetAt:new Date(t+e.windowMs),blockRemainingSeconds:null};return}let r=d.data();if(r.blockUntil&&t<r.blockUntil){m={allowed:!1,remaining:0,resetAt:new Date(r.blockUntil),blockRemainingSeconds:Math.ceil((r.blockUntil-t)/1e3)};return}if(t>=r.windowStart+e.windowMs){c.set(n,{attempts:1,windowStart:t,blockUntil:null,lastUpdated:t}),m={allowed:!0,remaining:e.maxAttempts-1,resetAt:new Date(t+e.windowMs),blockRemainingSeconds:null};return}if(r.attempts>=e.maxAttempts){let w=t+e.blockDurationMs;c.update(n,{blockUntil:w,lastUpdated:t}),l.warn("Rate limit exceeded (Firestore)",{key:i,attempts:r.attempts,blockUntil:new Date(w)}),m={allowed:!1,remaining:0,resetAt:new Date(w),blockRemainingSeconds:Math.ceil(e.blockDurationMs/1e3)};return}c.update(n,{attempts:r.attempts+1,lastUpdated:t}),m={allowed:!0,remaining:e.maxAttempts-(r.attempts+1),resetAt:new Date(r.windowStart+e.windowMs),blockRemainingSeconds:null}}),m}catch(t){return l.error("Rate limit check failed",{key:i,error:t instanceof Error?t.message:String(t)}),{allowed:!1,remaining:0,resetAt:null,blockRemainingSeconds:null}}}o(R,"checkRateLimitWithFirestore");function k(i){s.delete(i),l.info("Rate limit reset",{key:i})}o(k,"resetRateLimit");async function g(i){let a=(await u()).collection("rateLimits").doc(i);try{await a.delete(),l.info("Rate limit reset (Firestore)",{key:i})}catch(n){l.error("Failed to reset rate limit",{key:i,error:n instanceof Error?n.message:String(n)})}}o(g,"resetRateLimitInFirestore");function A(i,e){let a=Date.now(),n=s.get(i);return n?n.blockUntil&&a<n.blockUntil?{allowed:!1,remaining:0,resetAt:new Date(n.blockUntil),blockRemainingSeconds:Math.ceil((n.blockUntil-a)/1e3)}:a>=n.windowStart+e.windowMs?{allowed:!0,remaining:e.maxAttempts,resetAt:null,blockRemainingSeconds:null}:{allowed:n.attempts<e.maxAttempts,remaining:Math.max(0,e.maxAttempts-n.attempts),resetAt:new Date(n.windowStart+e.windowMs),blockRemainingSeconds:null}:{allowed:!0,remaining:e.maxAttempts,resetAt:null,blockRemainingSeconds:null}}o(A,"getRateLimitStatus");var S={checkout:{maxAttempts:5,windowMs:60*1e3,blockDurationMs:300*1e3},webhook:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3},auth:{maxAttempts:10,windowMs:60*1e3,blockDurationMs:300*1e3},api:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3}};export{p as a,R as b,k as c,g as d,A as e,S as f};
22
- //# sourceMappingURL=chunk-IFOYVSPU.js.map
21
+ import{a as l}from"./chunk-PWAGW4R6.js";import{a as o}from"./chunk-AYY7UXNI.js";async function u(){let{getFirebaseAdminFirestore:i}=await import("./server-IQ5JNJOM.js");return i()}o(u,"getFirestore");var s=new Map;async function p(i,e){let a=Date.now(),n=s.get(i);if(n?.blockUntil&&a<n.blockUntil)return{allowed:!1,remaining:0,resetAt:new Date(n.blockUntil),blockRemainingSeconds:Math.ceil((n.blockUntil-a)/1e3)};n&&a>=n.windowStart+e.windowMs&&s.delete(i);let t=s.get(i)||{attempts:0,windowStart:a,blockUntil:null};return t.attempts>=e.maxAttempts?(t.blockUntil=a+e.blockDurationMs,s.set(i,t),l.warn("Rate limit exceeded",{key:i,attempts:t.attempts,blockUntil:new Date(t.blockUntil)}),{allowed:!1,remaining:0,resetAt:new Date(t.blockUntil),blockRemainingSeconds:Math.ceil(e.blockDurationMs/1e3)}):(t.attempts+=1,s.set(i,t),{allowed:!0,remaining:e.maxAttempts-t.attempts,resetAt:new Date(t.windowStart+e.windowMs),blockRemainingSeconds:null})}o(p,"checkRateLimit");async function R(i,e){let a=await u(),n=a.collection("rateLimits").doc(i);try{let t=Date.now(),m={allowed:!0,remaining:e.maxAttempts-1,resetAt:new Date(t+e.windowMs),blockRemainingSeconds:null};return await a.runTransaction(async c=>{let d=await c.get(n);if(!d.exists){c.set(n,{attempts:1,windowStart:t,blockUntil:null,lastUpdated:t}),m={allowed:!0,remaining:e.maxAttempts-1,resetAt:new Date(t+e.windowMs),blockRemainingSeconds:null};return}let r=d.data();if(r.blockUntil&&t<r.blockUntil){m={allowed:!1,remaining:0,resetAt:new Date(r.blockUntil),blockRemainingSeconds:Math.ceil((r.blockUntil-t)/1e3)};return}if(t>=r.windowStart+e.windowMs){c.set(n,{attempts:1,windowStart:t,blockUntil:null,lastUpdated:t}),m={allowed:!0,remaining:e.maxAttempts-1,resetAt:new Date(t+e.windowMs),blockRemainingSeconds:null};return}if(r.attempts>=e.maxAttempts){let w=t+e.blockDurationMs;c.update(n,{blockUntil:w,lastUpdated:t}),l.warn("Rate limit exceeded (Firestore)",{key:i,attempts:r.attempts,blockUntil:new Date(w)}),m={allowed:!1,remaining:0,resetAt:new Date(w),blockRemainingSeconds:Math.ceil(e.blockDurationMs/1e3)};return}c.update(n,{attempts:r.attempts+1,lastUpdated:t}),m={allowed:!0,remaining:e.maxAttempts-(r.attempts+1),resetAt:new Date(r.windowStart+e.windowMs),blockRemainingSeconds:null}}),m}catch(t){return l.error("Rate limit check failed",{key:i,error:t instanceof Error?t.message:String(t)}),{allowed:!1,remaining:0,resetAt:null,blockRemainingSeconds:null}}}o(R,"checkRateLimitWithFirestore");function k(i){s.delete(i),l.info("Rate limit reset",{key:i})}o(k,"resetRateLimit");async function g(i){let a=(await u()).collection("rateLimits").doc(i);try{await a.delete(),l.info("Rate limit reset (Firestore)",{key:i})}catch(n){l.error("Failed to reset rate limit",{key:i,error:n instanceof Error?n.message:String(n)})}}o(g,"resetRateLimitInFirestore");function A(i,e){let a=Date.now(),n=s.get(i);return n?n.blockUntil&&a<n.blockUntil?{allowed:!1,remaining:0,resetAt:new Date(n.blockUntil),blockRemainingSeconds:Math.ceil((n.blockUntil-a)/1e3)}:a>=n.windowStart+e.windowMs?{allowed:!0,remaining:e.maxAttempts,resetAt:null,blockRemainingSeconds:null}:{allowed:n.attempts<e.maxAttempts,remaining:Math.max(0,e.maxAttempts-n.attempts),resetAt:new Date(n.windowStart+e.windowMs),blockRemainingSeconds:null}:{allowed:!0,remaining:e.maxAttempts,resetAt:null,blockRemainingSeconds:null}}o(A,"getRateLimitStatus");var S={checkout:{maxAttempts:5,windowMs:60*1e3,blockDurationMs:300*1e3},webhook:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3},auth:{maxAttempts:10,windowMs:60*1e3,blockDurationMs:300*1e3},api:{maxAttempts:100,windowMs:60*1e3,blockDurationMs:60*1e3}};export{p as a,R as b,k as c,g as d,A as e,S as f};
22
+ //# sourceMappingURL=chunk-3F4BWKQD.js.map
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{a as i}from"./chunk-NP2AN2TV.js";import{a as u}from"./chunk-AYY7UXNI.js";async function d(){let{getFirebaseAdminFirestore:r}=await import("./server-32A5RH4C.js");return r()}u(d,"getFirestore");async function w(r){try{await(await d()).collection("payment_metrics").doc().set({...r,recordedAt:new Date().toISOString()}),i.info("Payment metrics recorded",{operation:r.operation,status:r.status,userId:r.userId})}catch(t){i.error("Failed to record payment metrics",{error:t instanceof Error?t.message:String(t),metrics:r})}}u(w,"recordPaymentMetrics");async function b(r=24){try{let t=await d(),e=new Date;e.setHours(e.getHours()-r);let c=await t.collection("payment_metrics").where("timestamp",">=",e.toISOString()).get();if(c.empty)return{failureRate:0,shouldAlert:!1};let m=c.size,a=c.docs.filter(l=>l.data().status==="failed").length,s=a/m*100,n=s>10;return n&&await g(s,m,a),{failureRate:s,shouldAlert:n}}catch(t){return i.error("Failed to check payment failure rate",{error:t instanceof Error?t.message:String(t)}),{failureRate:0,shouldAlert:!1}}}u(b,"checkPaymentFailureRate");async function S(r=1e4){try{let t=await d(),e=new Date;e.setHours(0,0,0,0);let o=new Date(e);o.setDate(o.getDate()+1);let m=await t.collection("payment_metrics").where("timestamp",">=",e.toISOString()).where("timestamp","<",o.toISOString()).where("status","==","success").get(),a=0;m.docs.forEach(n=>{let l=n.data();l.amount&&l.currency==="usd"&&(a+=l.amount/100)});let s=a>r;return s&&await p(a,r),{totalVolume:a,shouldAlert:s}}catch(t){return i.error("Failed to check payment volume",{error:t instanceof Error?t.message:String(t)}),{totalVolume:0,shouldAlert:!1}}}u(S,"checkPaymentVolume");async function g(r,t,e){try{await(await d()).collection("payment_alerts").doc().set({type:"payment_failure_rate",severity:"high",message:`Payment failure rate is ${r.toFixed(2)}% (${e}/${t} payments failed)`,data:{failureRate:r,totalPayments:t,failedPayments:e},triggeredAt:new Date().toISOString(),status:"active"}),i.error("PAYMENT FAILURE ALERT TRIGGERED",{failureRate:r,totalPayments:t,failedPayments:e})}catch(o){i.error("Failed to trigger payment failure alert",{error:o instanceof Error?o.message:String(o)})}}u(g,"triggerPaymentFailureAlert");async function p(r,t){try{await(await d()).collection("payment_alerts").doc().set({type:"high_payment_volume",severity:"medium",message:`Daily payment volume exceeded threshold: $${r.toFixed(2)} (threshold: $${t})`,data:{totalVolume:r,threshold:t},triggeredAt:new Date().toISOString(),status:"active"}),i.warn("HIGH PAYMENT VOLUME ALERT TRIGGERED",{totalVolume:r,threshold:t})}catch(e){i.error("Failed to trigger high volume alert",{error:e instanceof Error?e.message:String(e)})}}u(p,"triggerHighVolumeAlert");async function P(r,t){try{let c=await(await d()).collection("payment_metrics").where("timestamp",">=",r.toISOString()).where("timestamp","<=",t.toISOString()).get(),m=0,a=0,s=0,n=0;c.docs.forEach(y=>{let f=y.data();m++,f.status==="success"?(a++,f.amount&&f.currency==="usd"&&(n+=f.amount/100)):f.status==="failed"&&s++});let l=a>0?n/a:0;return{totalPayments:m,successfulPayments:a,failedPayments:s,totalVolume:n,averageAmount:l}}catch(e){return i.error("Failed to get payment metrics summary",{error:e instanceof Error?e.message:String(e)}),{totalPayments:0,successfulPayments:0,failedPayments:0,totalVolume:0,averageAmount:0}}}u(P,"getPaymentMetricsSummary");async function A(r=90,t=30){try{let e=await d(),o=new Date,c=new Date(o);c.setDate(c.getDate()-r);let m=await e.collection("payment_metrics").where("recordedAt","<",c.toISOString()).limit(500).get();if(!m.empty){let n=e.batch();m.docs.forEach(l=>n.delete(l.ref)),await n.commit()}let a=new Date(o);a.setDate(a.getDate()-t);let s=await e.collection("payment_alerts").where("triggeredAt","<",a.toISOString()).limit(500).get();if(!s.empty){let n=e.batch();s.docs.forEach(l=>n.delete(l.ref)),await n.commit()}i.info("Payment metrics cleanup completed",{deletedMetrics:m.size,deletedAlerts:s.size})}catch(e){i.error("Payment metrics cleanup failed",{error:e instanceof Error?e.message:String(e)})}}u(A,"cleanupOldMetrics");export{w as a,b,S as c,P as d,A as e};
22
- //# sourceMappingURL=chunk-JTAGPPPL.js.map
21
+ import{a as i}from"./chunk-PWAGW4R6.js";import{a as u}from"./chunk-AYY7UXNI.js";async function d(){let{getFirebaseAdminFirestore:r}=await import("./server-IQ5JNJOM.js");return r()}u(d,"getFirestore");async function w(r){try{await(await d()).collection("payment_metrics").doc().set({...r,recordedAt:new Date().toISOString()}),i.info("Payment metrics recorded",{operation:r.operation,status:r.status,userId:r.userId})}catch(t){i.error("Failed to record payment metrics",{error:t instanceof Error?t.message:String(t),metrics:r})}}u(w,"recordPaymentMetrics");async function b(r=24){try{let t=await d(),e=new Date;e.setHours(e.getHours()-r);let c=await t.collection("payment_metrics").where("timestamp",">=",e.toISOString()).get();if(c.empty)return{failureRate:0,shouldAlert:!1};let m=c.size,a=c.docs.filter(l=>l.data().status==="failed").length,s=a/m*100,n=s>10;return n&&await g(s,m,a),{failureRate:s,shouldAlert:n}}catch(t){return i.error("Failed to check payment failure rate",{error:t instanceof Error?t.message:String(t)}),{failureRate:0,shouldAlert:!1}}}u(b,"checkPaymentFailureRate");async function S(r=1e4){try{let t=await d(),e=new Date;e.setHours(0,0,0,0);let o=new Date(e);o.setDate(o.getDate()+1);let m=await t.collection("payment_metrics").where("timestamp",">=",e.toISOString()).where("timestamp","<",o.toISOString()).where("status","==","success").get(),a=0;m.docs.forEach(n=>{let l=n.data();l.amount&&l.currency==="usd"&&(a+=l.amount/100)});let s=a>r;return s&&await p(a,r),{totalVolume:a,shouldAlert:s}}catch(t){return i.error("Failed to check payment volume",{error:t instanceof Error?t.message:String(t)}),{totalVolume:0,shouldAlert:!1}}}u(S,"checkPaymentVolume");async function g(r,t,e){try{await(await d()).collection("payment_alerts").doc().set({type:"payment_failure_rate",severity:"high",message:`Payment failure rate is ${r.toFixed(2)}% (${e}/${t} payments failed)`,data:{failureRate:r,totalPayments:t,failedPayments:e},triggeredAt:new Date().toISOString(),status:"active"}),i.error("PAYMENT FAILURE ALERT TRIGGERED",{failureRate:r,totalPayments:t,failedPayments:e})}catch(o){i.error("Failed to trigger payment failure alert",{error:o instanceof Error?o.message:String(o)})}}u(g,"triggerPaymentFailureAlert");async function p(r,t){try{await(await d()).collection("payment_alerts").doc().set({type:"high_payment_volume",severity:"medium",message:`Daily payment volume exceeded threshold: $${r.toFixed(2)} (threshold: $${t})`,data:{totalVolume:r,threshold:t},triggeredAt:new Date().toISOString(),status:"active"}),i.warn("HIGH PAYMENT VOLUME ALERT TRIGGERED",{totalVolume:r,threshold:t})}catch(e){i.error("Failed to trigger high volume alert",{error:e instanceof Error?e.message:String(e)})}}u(p,"triggerHighVolumeAlert");async function P(r,t){try{let c=await(await d()).collection("payment_metrics").where("timestamp",">=",r.toISOString()).where("timestamp","<=",t.toISOString()).get(),m=0,a=0,s=0,n=0;c.docs.forEach(y=>{let f=y.data();m++,f.status==="success"?(a++,f.amount&&f.currency==="usd"&&(n+=f.amount/100)):f.status==="failed"&&s++});let l=a>0?n/a:0;return{totalPayments:m,successfulPayments:a,failedPayments:s,totalVolume:n,averageAmount:l}}catch(e){return i.error("Failed to get payment metrics summary",{error:e instanceof Error?e.message:String(e)}),{totalPayments:0,successfulPayments:0,failedPayments:0,totalVolume:0,averageAmount:0}}}u(P,"getPaymentMetricsSummary");async function A(r=90,t=30){try{let e=await d(),o=new Date,c=new Date(o);c.setDate(c.getDate()-r);let m=await e.collection("payment_metrics").where("recordedAt","<",c.toISOString()).limit(500).get();if(!m.empty){let n=e.batch();m.docs.forEach(l=>n.delete(l.ref)),await n.commit()}let a=new Date(o);a.setDate(a.getDate()-t);let s=await e.collection("payment_alerts").where("triggeredAt","<",a.toISOString()).limit(500).get();if(!s.empty){let n=e.batch();s.docs.forEach(l=>n.delete(l.ref)),await n.commit()}i.info("Payment metrics cleanup completed",{deletedMetrics:m.size,deletedAlerts:s.size})}catch(e){i.error("Payment metrics cleanup failed",{error:e instanceof Error?e.message:String(e)})}}u(A,"cleanupOldMetrics");export{w as a,b,S as c,P as d,A as e};
22
+ //# sourceMappingURL=chunk-5IPULSUX.js.map
@@ -0,0 +1,22 @@
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { dirname } from 'node:path';
4
+ import { Buffer } from 'node:buffer';
5
+ import process from 'node:process';
6
+
7
+ const require = __createRequire(import.meta.url);
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = dirname(__filename);
10
+
11
+ if (typeof globalThis !== 'undefined') {
12
+ globalThis.require = require;
13
+ globalThis.__filename = __filename;
14
+ globalThis.__dirname = __dirname;
15
+ globalThis.Buffer = Buffer;
16
+ globalThis.process = process;
17
+ if (typeof global === 'undefined') {
18
+ globalThis.global = globalThis;
19
+ }
20
+ }
21
+ import{d as l}from"./chunk-LCDLG4VG.js";import{L as d,z as u}from"./chunk-GYTCWMXV.js";import{a as i}from"./chunk-AYY7UXNI.js";function h(e){let r=e?.uid;if(!r)throw new Error("User must be authenticated");return l(r)}i(h,"assertAuthenticated");function b(e){if(!e?.uid)return"guest";let r=e.token?.role;return r==="super"?"super":r==="admin"?"admin":e.token?.isSuper?"super":e.token?.isAdmin?"admin":"user"}i(b,"getUserRole");function w(e,r){if(!e||typeof e!="object")throw new Error("Invalid document data");if(Array.isArray(e))throw new Error("Document data cannot be an array");if(r)try{u(r,e)}catch(n){if(n?.issues){let t=n.issues.map(s=>`${s.path?.map(a=>a.key).join(".")||"root"}: ${s.message}`).join("; ");throw new d(`Validation failed: ${t}`,"invalid-argument",{details:{validationErrors:n.issues}})}throw n}}i(w,"validateDocument");async function y(e,r,n){let t=[];if(!n?.incoming?.length)return t;let{getFirebaseAdminFirestore:s}=await import("./server-IQ5JNJOM.js"),a=s();for(let o of n.incoming){let c=await a.collection(o.sourceCollection).where(o.sourceField,"==",r).limit(1).get();c.empty||t.push({collection:o.sourceCollection,field:o.sourceField,count:c.size})}return t}i(y,"findReferences");export{h as a,b,w as c,y as d};
22
+ //# sourceMappingURL=chunk-6USHTJED.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/shared/utils.ts"],
4
+ "sourcesContent": ["// packages/functions/src/shared/utils.ts\n\n/**\n * @fileoverview Shared utilities for Firebase and Vercel functions\n * @description Common utilities that can be used by both Firebase and Vercel function implementations\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport * as v from 'valibot';\n\nimport { DoNotDevError } from '@donotdev/core/server';\nimport type { OAuthPartnerId, UserRole } from '@donotdev/core/server';\n\nimport {\n assertAuthenticated as internalAssertAuthenticated,\n assertAdmin as internalAssertAdmin,\n} from './utils/internal/auth.js';\n\n// Re-export DoNotDevError for external use\nexport { DoNotDevError };\n\n/**\n * Assert that a user is authenticated from a Firebase callable auth context.\n *\n * @deprecated Import `assertAuthenticated` from `@donotdev/functions/shared/utils/internal/auth` instead.\n * This wrapper extracts uid from a Firebase callable auth context and delegates\n * to the canonical version.\n *\n * @param auth - Firebase callable request auth context (object with `.uid`)\n * @returns The authenticated user's uid\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function assertAuthenticated(auth: any): string {\n const uid = auth?.uid;\n if (!uid) {\n throw new Error('User must be authenticated');\n }\n return internalAssertAuthenticated(uid);\n}\n\n/**\n * Get user role from Firebase auth context\n *\n * Determines the user's role for visibility filtering based on:\n * - auth.uid: If missing \u2192 'guest'\n * - auth.token.isSuper: If true \u2192 'super'\n * - auth.token.isAdmin: If true \u2192 'admin'\n * - Otherwise \u2192 'user' (authenticated)\n *\n * @param auth - Firebase auth context from callable function\n * @returns UserRole for visibility filtering\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function getUserRole(auth: any): UserRole {\n if (!auth?.uid) return 'guest';\n\n // Check role claim (standard pattern: auth.token.role = 'admin' | 'super' | etc.)\n const role = auth.token?.role;\n if (role === 'super') return 'super';\n if (role === 'admin') return 'admin';\n\n // Fallback: check legacy boolean flags for backward compatibility\n if (auth.token?.isSuper) return 'super';\n if (auth.token?.isAdmin) return 'admin';\n\n return 'user';\n}\n\n/**\n * Creates a standardized success response\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function createSuccessResponse<T>(data: T): { success: true; data: T } {\n return {\n success: true,\n data,\n };\n}\n\n/**\n * Creates a standardized error response\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function createErrorResponse(error: unknown): {\n success: false;\n error: {\n code: string;\n message: string;\n details?: any;\n };\n} {\n if (error instanceof DoNotDevError) {\n return {\n success: false,\n error: {\n code: error.code,\n message: error.message,\n details: error.details,\n },\n };\n }\n\n if (error instanceof Error) {\n return {\n success: false,\n error: {\n code: 'internal',\n message: error.message,\n },\n };\n }\n\n return {\n success: false,\n error: {\n code: 'internal',\n message: 'An unexpected error occurred',\n },\n };\n}\n\n/**\n * Updates user subscription in Firebase.\n *\n * **Architecture decision \u2014 throwing stubs for billing functions:**\n * These subscription functions (`updateUserSubscription`, `getUserSubscription`,\n * `cancelUserSubscription`, `handleSubscriptionCancellation`) are intentional\n * placeholder implementations. They exist so the framework compiles and\n * type-checks out of the box, but throw at runtime to surface missing\n * integration early. Consumer apps replace them with their billing provider\n * integration (Stripe, Paddle, LemonSqueezy, etc.) via the documented\n * `shared/billing/helpers/` modules.\n *\n * C10: This was a silent no-op stub. It now throws to surface the missing\n * implementation at startup rather than silently dropping webhook events.\n * Use `updateUserSubscription` from `shared/billing/helpers/updateUserSubscription.ts`\n * (which requires an authProvider) instead.\n *\n * @deprecated Import `updateUserSubscription` from `@donotdev/functions/shared/billing/helpers/updateUserSubscription`.\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function updateUserSubscription(\n _firebaseUid: string,\n _subscription: any\n): Promise<void> {\n throw new DoNotDevError(\n 'updateUserSubscription stub called \u2014 import from shared/billing/helpers/updateUserSubscription.ts and supply an authProvider',\n 'unimplemented'\n );\n}\n\n/**\n * Gets user subscription from Firebase.\n *\n * C10: This was a silent no-op stub. Now throws to surface the missing implementation.\n *\n * @deprecated Import from `@donotdev/functions/shared/billing/helpers` or implement directly using Firebase Admin SDK / Stripe API.\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function getUserSubscription(_firebaseUid: string): Promise<any> {\n throw new DoNotDevError(\n 'getUserSubscription stub called \u2014 implement using Firebase Admin SDK or Stripe API',\n 'unimplemented'\n );\n}\n\n/**\n * Cancels user subscription.\n *\n * C10: This was a silent no-op stub. Now throws to surface the missing implementation.\n *\n * @deprecated Import `cancelUserSubscription` from `@donotdev/functions/shared/billing/helpers/subscriptionManagement`.\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function cancelUserSubscription(\n _firebaseUid: string,\n _subscription: any\n): Promise<void> {\n throw new DoNotDevError(\n 'cancelUserSubscription stub called \u2014 import from shared/billing/helpers/subscriptionManagement.ts',\n 'unimplemented'\n );\n}\n\n/**\n * Handles subscription cancellation.\n *\n * C10: This was a silent no-op stub. Now throws to surface the missing implementation.\n *\n * @deprecated Handle via Stripe webhook events. Use `processWebhook` from `@donotdev/functions/shared/billing/webhookHandler`.\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function handleSubscriptionCancellation(\n _firebaseUid: string,\n _subscription: any\n): Promise<void> {\n throw new DoNotDevError(\n 'handleSubscriptionCancellation stub called \u2014 handle via Stripe webhook events',\n 'unimplemented'\n );\n}\n\n/**\n * Asserts that a user has admin privileges\n * Uses role hierarchy: super > admin > user > guest\n *\n * @deprecated Import `assertAdmin` from `@donotdev/functions/shared/utils/internal/auth` instead.\n * This is a thin wrapper that delegates to the canonical provider-agnostic version.\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function assertAdmin(uid: string): Promise<string> {\n return internalAssertAdmin(uid);\n}\n\n/**\n * Validates document data\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateDocument(data: any, schema?: any): void {\n if (!data || typeof data !== 'object') {\n throw new Error('Invalid document data');\n }\n\n if (Array.isArray(data)) {\n throw new Error('Document data cannot be an array');\n }\n\n // Run Valibot schema validation when a schema is provided\n if (schema) {\n try {\n v.parse(schema, data);\n } catch (error: any) {\n if (error?.issues) {\n const messages = error.issues\n .map(\n (issue: v.BaseIssue<unknown>) =>\n `${issue.path?.map((p: any) => p.key).join('.') || 'root'}: ${issue.message}`\n )\n .join('; ');\n throw new DoNotDevError(\n `Validation failed: ${messages}`,\n 'invalid-argument',\n { details: { validationErrors: error.issues } }\n );\n }\n throw error;\n }\n }\n}\n\n/**\n * Validates a Firestore collection name from client-supplied schema.\n *\n * W22: Vercel CRUD handlers accept `schema` (including collection name) from\n * the client. This is a known design limitation. As a defense-in-depth measure,\n * reject collection names that could be used for path traversal or access to\n * internal collections.\n *\n * @param name - Collection name to validate\n * @throws Error if the name is unsafe\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateCollectionName(name: string): void {\n if (!name || typeof name !== 'string') {\n throw new Error('Collection name is required');\n }\n if (name.includes('/') || name.includes('..') || name.startsWith('_')) {\n throw new Error(\n 'Invalid collection name: must not contain \"/\", \"..\", or start with \"_\"'\n );\n }\n}\n\n/**\n * Verifies Firebase auth token\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function verifyFirebaseAuthToken(token: string): Promise<string> {\n if (!token) {\n throw new DoNotDevError('Missing authentication token', 'unauthenticated');\n }\n\n // Lazy: the Vercel/Supabase entries must load without firebase-admin\n const { getFirebaseAdminAuth } = await import('@donotdev/firebase/server');\n try {\n const decodedToken = await getFirebaseAdminAuth().verifyIdToken(token);\n return decodedToken.uid;\n } catch (error) {\n throw new DoNotDevError('Invalid or expired token', 'unauthenticated');\n }\n}\n\n/**\n * Finds references to a document\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function findReferences(\n collection: string,\n docId: string,\n referenceMetadata?: {\n incoming?: Array<{\n sourceCollection: string;\n sourceField: string;\n }>;\n }\n): Promise<Array<{ collection: string; field: string; count: number }>> {\n const references: Array<{\n collection: string;\n field: string;\n count: number;\n }> = [];\n\n if (!referenceMetadata?.incoming?.length) {\n return references;\n }\n\n // Lazy: the Vercel/Supabase entries must load without firebase-admin\n const { getFirebaseAdminFirestore } =\n await import('@donotdev/firebase/server');\n const db = getFirebaseAdminFirestore();\n\n for (const ref of referenceMetadata.incoming) {\n const snapshot = await db\n .collection(ref.sourceCollection)\n .where(ref.sourceField, '==', docId)\n .limit(1)\n .get();\n\n if (!snapshot.empty) {\n references.push({\n collection: ref.sourceCollection,\n field: ref.sourceField,\n count: snapshot.size,\n });\n }\n }\n\n return references;\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;+HAsCO,SAASA,EAAoBC,EAAmB,CACrD,IAAMC,EAAMD,GAAM,IAClB,GAAI,CAACC,EACH,MAAM,IAAI,MAAM,4BAA4B,EAE9C,OAAOF,EAA4BE,CAAG,CACxC,CANgBC,EAAAH,EAAA,uBAwBT,SAASI,EAAYH,EAAqB,CAC/C,GAAI,CAACA,GAAM,IAAK,MAAO,QAGvB,IAAMI,EAAOJ,EAAK,OAAO,KACzB,OAAII,IAAS,QAAgB,QACzBA,IAAS,QAAgB,QAGzBJ,EAAK,OAAO,QAAgB,QAC5BA,EAAK,OAAO,QAAgB,QAEzB,MACT,CAbgBE,EAAAC,EAAA,eAyLT,SAASE,EAAiBC,EAAWC,EAAoB,CAC9D,GAAI,CAACD,GAAQ,OAAOA,GAAS,SAC3B,MAAM,IAAI,MAAM,uBAAuB,EAGzC,GAAI,MAAM,QAAQA,CAAI,EACpB,MAAM,IAAI,MAAM,kCAAkC,EAIpD,GAAIC,EACF,GAAI,CACAC,EAAMD,EAAQD,CAAI,CACtB,OAASG,EAAY,CACnB,GAAIA,GAAO,OAAQ,CACjB,IAAMC,EAAWD,EAAM,OACpB,IACEE,GACC,GAAGA,EAAM,MAAM,IAAKC,GAAWA,EAAE,GAAG,EAAE,KAAK,GAAG,GAAK,MAAM,KAAKD,EAAM,OAAO,EAC/E,EACC,KAAK,IAAI,EACZ,MAAM,IAAIE,EACR,sBAAsBH,CAAQ,GAC9B,mBACA,CAAE,QAAS,CAAE,iBAAkBD,EAAM,MAAO,CAAE,CAChD,CACF,CACA,MAAMA,CACR,CAEJ,CA9BgBK,EAAAT,EAAA,oBAuFhB,eAAsBU,EACpBC,EACAC,EACAC,EAMsE,CACtE,IAAMC,EAID,CAAC,EAEN,GAAI,CAACD,GAAmB,UAAU,OAChC,OAAOC,EAIT,GAAM,CAAE,0BAAAC,CAA0B,EAChC,KAAM,QAAO,sBAA2B,EACpCC,EAAKD,EAA0B,EAErC,QAAWE,KAAOJ,EAAkB,SAAU,CAC5C,IAAMK,EAAW,MAAMF,EACpB,WAAWC,EAAI,gBAAgB,EAC/B,MAAMA,EAAI,YAAa,KAAML,CAAK,EAClC,MAAM,CAAC,EACP,IAAI,EAEFM,EAAS,OACZJ,EAAW,KAAK,CACd,WAAYG,EAAI,iBAChB,MAAOA,EAAI,YACX,MAAOC,EAAS,IAClB,CAAC,CAEL,CAEA,OAAOJ,CACT,CA1CsBK,EAAAT,EAAA",
6
+ "names": ["assertAuthenticated", "auth", "uid", "__name", "getUserRole", "role", "validateDocument", "data", "schema", "parse", "error", "messages", "issue", "p", "DoNotDevError", "__name", "findReferences", "collection", "docId", "referenceMetadata", "references", "getFirebaseAdminFirestore", "db", "ref", "snapshot", "__name"]
7
+ }
@@ -18,6 +18,6 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{R as s,S as C,U as j,e as B,z as P}from"./chunk-6CQXHNVL.js";import{a as o}from"./chunk-AYY7UXNI.js";import{initializeApp as N,getApps as Q,cert as Z}from"firebase-admin/app";import{getAuth as X}from"firebase-admin/auth";import{getFirestore as ee}from"firebase-admin/firestore";import{getFunctions as te}from"firebase-admin/functions";function re(){let e=Q(),t=null;if(e.length===0?process.env.FIREBASE_ADMIN_PRIVATE_KEY&&process.env.FIREBASE_PROJECT_ID&&process.env.FIREBASE_CLIENT_EMAIL?t=N({credential:Z({projectId:process.env.FIREBASE_PROJECT_ID,clientEmail:process.env.FIREBASE_CLIENT_EMAIL,privateKey:process.env.FIREBASE_ADMIN_PRIVATE_KEY.replace(/\\n/g,`
21
+ import{R as s,S as C,U as j,e as B,z as P}from"./chunk-GYTCWMXV.js";import{a as o}from"./chunk-AYY7UXNI.js";import{initializeApp as N,getApps as Q,cert as Z}from"firebase-admin/app";import{getAuth as X}from"firebase-admin/auth";import{getFirestore as ee}from"firebase-admin/firestore";import{getFunctions as te}from"firebase-admin/functions";function re(){let e=Q(),t=null;if(e.length===0?process.env.FIREBASE_ADMIN_PRIVATE_KEY&&process.env.FIREBASE_PROJECT_ID&&process.env.FIREBASE_CLIENT_EMAIL?t=N({credential:Z({projectId:process.env.FIREBASE_PROJECT_ID,clientEmail:process.env.FIREBASE_CLIENT_EMAIL,privateKey:process.env.FIREBASE_ADMIN_PRIVATE_KEY.replace(/\\n/g,`
22
22
  `)}),projectId:process.env.FIREBASE_PROJECT_ID}):t=N():t=e[0]||null,!t)throw new Error("Failed to initialize Firebase Admin app");return{app:t,auth:X(t),firestore:ee(t),functions:te(t)}}o(re,"initializeFirebaseAdminServices");var D=j(re);async function we(){try{return D()}catch(e){throw s(e,{userMessage:"Failed to initialize Firebase Admin",context:{provider:"FirebaseAdmin",operation:"initFirebaseAdmin"},severity:"error"})}}o(we,"initFirebaseAdmin");async function $(){let e=D();if(!e.app)throw new Error("Firebase Admin not initialized");return e.app}o($,"getFirebaseAdminApp");function I(){let e=D();if(!e.auth)throw new Error("Firebase Admin auth not initialized");return e.auth}o(I,"getFirebaseAdminAuth");function z(){let e=D();if(!e.firestore)throw new Error("Firebase Admin firestore not initialized");return e.firestore}o(z,"getFirebaseAdminFirestore");function ve(){let e=D();if(!e.functions)throw new Error("Firebase Admin functions not initialized");return e.functions}o(ve,"getFirebaseAdminFunctions");var W=class{static{o(this,"FirebaseServerAuthAdapter")}async verifyToken(t){try{let r=await I().verifyIdToken(t);return{uid:r.uid,email:r.email,claims:r}}catch(r){throw C(r,"FirebaseServerAuthAdapter","verifyToken")}}async getUser(t){try{let r=await I().getUser(t);return{uid:r.uid,email:r.email,displayName:r.displayName,customClaims:r.customClaims??{}}}catch(r){if(r.code==="auth/user-not-found")return null;throw C(r,"FirebaseServerAuthAdapter","getUser",{uid:t})}}async setCustomClaims(t,r){try{let i=(await I().getUser(t)).customClaims??{};await I().setCustomUserClaims(t,{...i,...r})}catch(n){throw C(n,"FirebaseServerAuthAdapter","setCustomClaims",{uid:t})}}};var O={async getServerAdmin(){try{return $()}catch(e){throw s(e,"Error getting Firebase Admin")}},async getServerFirestore(){try{return z()}catch(e){throw s(e,"Error getting Admin Firestore")}},async generateServerId(){return(await O.getServerFirestore()).collection("_").doc().id}},Re=O.getServerAdmin,g=O.getServerFirestore,ke=O.generateServerId;function L(e){return{seconds:Math.floor(e.getTime()/1e3),nanoseconds:e.getTime()%1e3*1e6,toDate:o(()=>new Date(e),"toDate"),toMillis:o(()=>e.getTime(),"toMillis"),isEqual:o(t=>t.seconds===Math.floor(e.getTime()/1e3)&&t.nanoseconds===e.getTime()%1e3*1e6,"isEqual"),valueOf:o(()=>`Timestamp(seconds=${Math.floor(e.getTime()/1e3)}, nanoseconds=${e.getTime()%1e3*1e6})`,"valueOf")}}o(L,"createTimestamp");function Oe(e){try{if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw s(new Error("Invalid date string format"),{context:{value:e}});return L(t)}if(e instanceof Date){if(isNaN(e.getTime()))throw s(new Error("Invalid Date object"),{context:{value:e}});return L(e)}throw s(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw s(t,"Failed to convert to Timestamp")}}o(Oe,"toTimestamp");function ne(e){try{if(e instanceof Date){if(isNaN(e.getTime()))throw s(new Error("Invalid Date object"),{context:{value:e}});return e.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function")return e.toDate().toISOString();if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw s(new Error("Invalid date string format"),{context:{value:e}});return t.toISOString()}throw s(new Error("Invalid date value type"),{context:{valueType:typeof e}})}catch(t){throw s(t,"Failed to convert to ISO string")}}o(ne,"firestoreToISOString");function ie(e){return typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function"&&"seconds"in e&&"nanoseconds"in e}o(ie,"isTimestamp");function oe(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(e))return!1;let r=new Date(e);return!isNaN(r.getTime())}o(oe,"isISODateString");function J(e){if(!e)return e;if(Array.isArray(e))return e.map(t=>J(t));if(typeof e=="string"&&oe(e))return new Date(e);if(typeof e=="object"&&e!==null){let t={};for(let[r,n]of Object.entries(e))t[r]=J(n);return t}return e}o(J,"convertISOStringsToDates");function v(e,t=!1){if(!e)return e;if(t&&typeof e=="object"&&e!==null&&"id"in e&&"ref"in e&&"data"in e&&typeof e.data=="function"){let r=e,n=r.data();return{id:r.id,...v(n)}}if(Array.isArray(e))return e.map(r=>v(r));if(ie(e))return ne(e);if(typeof e=="object"&&e!==null){let r={};for(let[n,i]of Object.entries(e))r[n]=v(i);return r}return e}o(v,"transformFirestoreData");function A(e,t=[]){if(!e)return e;if(Array.isArray(e))return e.map(r=>A(r,t));if(e instanceof Date)return e.toISOString();if(typeof e=="object"&&e!==null){let r={};for(let[n,i]of Object.entries(e))t.includes(n)||i!==void 0&&(r[n]=A(i,t));return r}return e}o(A,"prepareForFirestore");function qe(e,t){let r={};for(let[n,i]of Object.entries(t)){if(!(n in e)){r[n]=i;continue}JSON.stringify(e[n])!==JSON.stringify(i)&&(r[n]=i)}return{...r,updatedAt:new Date().toISOString()}}o(qe,"createFirestorePartialUpdate");var x=typeof window<"u",y={async batchWrite(e,t,r,n,i={}){if(!t||!t.length)return{successes:0,failures:0};let{idField:a="id",generateIds:d=!0,maxBatchSize:u=450,removeFields:c=[],validate:S=!!n}=i,l={successes:0,failures:0,failedItems:[]};try{let b=[],w=await g(),f=w.batch(),h=0;for(let T=0;T<t.length;T++){let m=t[T];if(!m){l.failures++,l.failedItems?.push({index:T,error:new Error("Item is null or undefined")});continue}try{if(r==="delete"){if(!m[a])throw s(new Error(`Missing ID for delete operation (${a})`),{userMessage:"Unable to delete item: missing ID",severity:"error",context:{collection:e,idField:a,operation:r}});let p=w.collection(e).doc(m[a]);f.delete(p)}else{if(S&&n)try{P(n,m)}catch(Y){throw s(Y,{userMessage:"Validation failed for item",severity:"warning",context:{collection:e,operation:r,idField:a,itemId:m[a]}})}let p=m[a];if(!p&&r==="create"&&d)p=w.collection(e).doc().id,m={...m,[a]:p};else if(!p)throw s(new Error(`Missing ID for ${r} operation (${a})`),{userMessage:`Unable to ${r} item: missing ID`,severity:"error",context:{collection:e,idField:a,operation:r}});let q=[a,...c],F=A(m,q),U=w.collection(e).doc(p);r==="create"?f.create(U,F):r==="update"&&f.update(U,F)}h++,h>=u&&(b.push({batch:f,size:h}),f=w.batch(),h=0)}catch(p){l.failures++,l.failedItems?.push({index:T,error:p instanceof Error?p:new Error(String(p))})}}h>0&&b.push({batch:f,size:h});let k=0;for(let{batch:T,size:m}of b){try{await T.commit(),l.successes+=m}catch(p){let q=p instanceof Error?p:new Error(String(p));for(let F=k;F<k+m;F++)l.failures++,l.failedItems?.push({index:F,error:q})}k+=m}return l}catch(b){throw s(b,{userMessage:`Batch ${r} operation failed for collection ${e}`,context:{collection:e,operation:r,itemCount:t.length,processedCount:l.successes+l.failures,successCount:l.successes,failureCount:l.failures}})}},async batchCreate(e,t,r,n={}){return y.batchWrite(e,t,"create",r,n)},async batchUpdate(e,t,r,n={}){return y.batchWrite(e,t,"update",r,n)},async batchDelete(e,t,r={}){if(t.length>0&&typeof t[0]=="string"){let n=r.idField||"id",i=t.map(a=>({[n]:a}));return y.batchWrite(e,i,"delete",void 0,r)}return y.batchWrite(e,t,"delete",void 0,r)},async runTransaction(e){try{return await(await g()).runTransaction(e)}catch(t){throw s(t,{userMessage:"Transaction failed"})}},async bulkGet(e,t,r={}){if(!t.length)return[];let{maxBatchSize:n=30,transform:i=!0}=r;try{let a=[];for(let c=0;c<t.length;c+=n)a.push(t.slice(c,c+n));let d=a.map(async c=>{let b=await(await g()).collection(e).where("__name__","in",c).get(),w=new Map;return b.forEach(f=>{w.set(f.id,f.data())}),c.map(f=>{let h=w.get(f);return h?i?v({id:f,...h}):{id:f,...h}:null})});return(await Promise.all(d)).flat()}catch(a){throw s(a,{userMessage:`Bulk get operation failed for collection ${e}`,context:{collection:e,idCount:t.length}})}}},E=o(e=>()=>{throw new Error(`Firebase Admin function '${e}' is not available in browser environments`)},"notAvailableInBrowser"),je=x?E("batchWrite"):y.batchWrite,Ne=x?E("batchCreate"):y.batchCreate,$e=x?E("batchUpdate"):y.batchUpdate,ze=x?E("batchDelete"):y.batchDelete,We=x?E("runTransaction"):y.runTransaction,Le=x?E("bulkGet"):y.bulkGet;function R(e,t){return s(e,{userMessage:t?`Error during ${t}`:void 0,context:{operation:t}})}o(R,"handleFirebaseError");async function ae(e,t={}){let{collection:r="subscriptions",userIdField:n="customerId"}=t;try{let d=await(await g()).collection(r).where(n,"==",e).where("status","==","active").limit(1).get();if(d.empty)return null;let u=d.docs[0];if(!u)return null;let c=u.data();return v({id:u.id,...c})}catch(i){throw R(i,"getActiveSubscription")}}o(ae,"getActiveSubscription");async function tt(e,t={}){let{collection:r="subscriptions",userIdField:n="customerId"}=t;try{return(await(await g()).collection(r).where(n,"==",e).orderBy("createdAt","desc").get()).docs.map(u=>v({id:u.id,...u.data()}))}catch(i){throw R(i,"getUserSubscriptions")}}o(tt,"getUserSubscriptions");async function ce(e,t={}){let{collection:r="subscriptions"}=t;try{let n=await g(),i=new Date().toISOString(),a={...e,createdAt:e.createdAt||i,updatedAt:i},d=A(a),{id:u,...c}=d,S=u?n.collection(r).doc(u):n.collection(r).doc();return await S.set(c,{merge:!0}),{...a,id:S.id}}catch(n){throw R(n,"saveSubscription")}}o(ce,"saveSubscription");async function ue(e,t,r={}){let{collection:n="subscriptions"}=r;try{await(await g()).collection(n).doc(e).update({status:t,updatedAt:new Date().toISOString()})}catch(i){throw R(i,"updateSubscriptionStatus")}}o(ue,"updateSubscriptionStatus");async function rt(e,t,r={}){try{let n=await ae(e,r);return n?n.features&&Array.isArray(n.features)?n.features.includes(t):n.metadata&&n.metadata[t]?n.metadata[t]==="true":!1:!1}catch(n){throw s(n,{userMessage:"Failed to check feature access",severity:"error",context:{function:"hasFeatureAccess",userId:e,featureKey:t}})}}o(rt,"hasFeatureAccess");async function nt(e){let{rawBody:t,signature:r,webhookSecret:n,...i}=e,a;try{let u=await import("stripe"),c=u.default??u;a=new c("placeholder",{apiVersion:"2023-10-16"})}catch{throw s(new Error("stripe package is not installed"),{userMessage:"Stripe package missing \u2014 cannot verify webhook signature",severity:"error"})}let d;try{d=a.webhooks.constructEvent(t,r,n)}catch(u){throw s(u,{userMessage:"Stripe webhook signature verification failed",severity:"error",context:{function:"verifyAndHandleStripeWebhook"}})}await de(d,i)}o(nt,"verifyAndHandleStripeWebhook");async function de(e,t={}){let r=e.type,n=e.data.object;try{switch(r){case"customer.subscription.created":case"customer.subscription.updated":await le(n,t);break;case"customer.subscription.deleted":await ue(n.id,"canceled",t);break;default:}}catch(i){throw s(i,{userMessage:`Failed to handle Stripe webhook event: ${r}`,severity:"error",context:{eventType:r,eventId:e.id}})}}o(de,"handleStripeWebhookEvent");async function le(e,t={}){if(!e.items.data.length)throw s(new Error("[subscription] Stripe subscription has no items"),{userMessage:"Stripe subscription has no items \u2014 cannot determine plan",severity:"error",context:{subscriptionId:e.id}});let r={id:e.id,customerId:e.customer,status:e.status,planId:e.items.data[0]?.plan.id||"",currentPeriodStart:new Date(e.current_period_start*1e3).toISOString(),currentPeriodEnd:new Date(e.current_period_end*1e3).toISOString(),cancelAtPeriodEnd:e.cancel_at_period_end,metadata:e.metadata||{},createdAt:new Date(e.created*1e3).toISOString(),updatedAt:new Date().toISOString()};e.canceled_at&&(r.canceledAt=new Date(e.canceled_at*1e3).toISOString()),await ce(r,t)}o(le,"saveSubscriptionFromStripeEvent");var V={};function _(e){V.uniqueConstraintValidator=e}o(_,"registerUniqueConstraintValidator");function G(){return V.uniqueConstraintValidator}o(G,"getUniqueConstraintValidator");function pe(){return!!V.uniqueConstraintValidator}o(pe,"hasUniqueConstraintValidator");async function H(){let e=await g(),t={checkDuplicate:o(async(r,n,i,a)=>{if(i==null)return!1;try{return(await e.collection(r).where(n,"==",i).get()).docs.some(c=>c.id!==a&&c.data()[n]===i)}catch(d){throw s(d,{userMessage:`Failed to check uniqueness for field "${n}"`,severity:"error",context:{collection:r,field:n,value:i}})}},"checkDuplicate")};return _(t),t}o(H,"createFirestoreValidator");async function K(){let e=await g(),t={checkDuplicate:o(async(r,n,i,a)=>{if(i==null)return!1;try{return(await e.collection(r).where(n,"==",i).get()).docs.some(c=>c.id!==a&&c.data()[n]===i)}catch(d){throw s(d,{userMessage:`Failed to check uniqueness for field "${n}"`,severity:"error",context:{collection:r,field:n,value:i}})}},"checkDuplicate")};return _(t),t}o(K,"createAdminFirestoreValidator");var fe=K;async function M(e,t,r,n){if(!t.length)return;let i=G();i||(i=await H());let a=[],u=(await Promise.allSettled(t.map(async({field:c,errorMessage:S})=>{let l=r[c];if(l==null)return;await i.checkDuplicate(e,c,l,n)&&a.push({field:c,message:S||`The ${c} must be unique`})}))).find(c=>c.status==="rejected");if(u&&u.status==="rejected")throw u.reason;if(a.length>0)throw s(new Error("Uniqueness validation failed"),{userMessage:"Uniqueness validation failed",severity:"error",context:{validationErrors:a,collection:e}})}o(M,"validateUniqueness");async function pt(e,t,r,n){try{P(e,t),e.metadata?.uniqueFields?.length&&await M(e.metadata.collection,e.metadata.uniqueFields,t,n),e.metadata?.customValidate&&await e.metadata.customValidate(t,r)}catch(i){throw B(i)?s(i,{userMessage:"Document validation failed",context:{validationErrors:i.issues,data:t},severity:"warning"}):s(i,{userMessage:"Document validation failed",context:{collection:e.metadata?.collection||"unknown"},severity:"error"})}}o(pt,"validateFirestoreDocument");function ft(e,t){let r=e;return r.metadata=t,r}o(ft,"enhanceSchema");import{FieldValue as Dt,Query as It,Timestamp as Rt}from"firebase-admin/firestore";export{we as a,$ as b,I as c,z as d,ve as e,W as f,Re as g,g as h,ke as i,L as j,Oe as k,ne as l,ie as m,J as n,v as o,A as p,qe as q,je as r,Ne as s,$e as t,ze as u,We as v,Le as w,ae as x,tt as y,ce as z,ue as A,rt as B,nt as C,_ as D,G as E,pe as F,H as G,K as H,fe as I,M as J,pt as K,ft as L,Dt as M,It as N,Rt as O};
23
- //# sourceMappingURL=chunk-RM7DV6IQ.js.map
23
+ //# sourceMappingURL=chunk-CXBSROEW.js.map
@@ -19,4 +19,4 @@ if (typeof globalThis !== 'undefined') {
19
19
  }
20
20
  }
21
21
  import{a as i}from"./chunk-AYY7UXNI.js";var ue={ALREADY_EXISTS:"already-exists",CANCELLED:"cancelled",DEADLINE_EXCEEDED:"deadline-exceeded",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",INTERNAL:"internal",INVALID_ARGUMENT:"invalid-argument",NOT_FOUND:"not-found",PERMISSION_DENIED:"permission-denied",RATE_LIMIT_EXCEEDED:"rate-limit-exceeded",TIMEOUT:"timeout",UNAUTHENTICATED:"unauthenticated",UNAVAILABLE:"unavailable",UNIMPLEMENTED:"unimplemented",UNKNOWN:"unknown",VALIDATION_FAILED:"validation-failed"};var ge={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},Re={[ue.PERMISSION_DENIED]:{type:ge.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[ue.NOT_FOUND]:{type:ge.NOT_FOUND,message:"The requested resource was not found"},[ue.ALREADY_EXISTS]:{type:ge.ALREADY_EXISTS,message:"The resource already exists"},[ue.INVALID_ARGUMENT]:{type:ge.VALIDATION_ERROR,message:"Invalid argument provided"}};var P=class e extends Error{static{i(this,"DoNotDevError")}code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,n=ue.INTERNAL,o){super(t),Object.setPrototypeOf(this,e.prototype),this.code=n,this.details=o?.details,this.source=o?.source,this.originalError=o?.originalError,this.context=o?.context,this.displayable=o?.displayable??!0,this.userMessageProvided=o?.userMessageProvided,this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toString(){return`${this.name} [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,source:this.source,originalError:this.originalError,context:this.context,displayable:this.displayable,userMessageProvided:this.userMessageProvided}}};var j={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},ve={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},$n={[j.ANTHROPIC]:{default:"claude-sonnet-4-6",models:["claude-sonnet-4-6","claude-sonnet-4-20250514","claude-haiku-4-5-20251001","claude-opus-4-6","claude-opus-4-20250514"]},[j.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[j.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}};var Gn={FAST:{id:"fast",defaultModel:"claude-haiku-4-5-20251001"},STANDARD:{id:"standard",defaultModel:"claude-sonnet-4-6"},PREMIUM:{id:"premium",defaultModel:"claude-opus-4-6"}},Hn=4,Wn={"claude-sonnet-4-6":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-haiku-4-5-20251001":{promptPer1M:.8,completionPer1M:4,currency:"usd"},"claude-opus-4-6":{promptPer1M:15,completionPer1M:75,currency:"usd"},"claude-sonnet-4-20250514":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-opus-4-20250514":{promptPer1M:15,completionPer1M:75,currency:"usd"},"gpt-4o":{promptPer1M:2.5,completionPer1M:10,currency:"usd"},"gpt-4o-mini":{promptPer1M:.15,completionPer1M:.6,currency:"usd"},"gpt-4.1":{promptPer1M:2,completionPer1M:8,currency:"usd"},"gpt-4.1-mini":{promptPer1M:.4,completionPer1M:1.6,currency:"usd"},"o3-mini":{promptPer1M:1.1,completionPer1M:4.4,currency:"usd"},"gemini-2.0-flash":{promptPer1M:.1,completionPer1M:.4,currency:"usd"},"gemini-2.5-pro":{promptPer1M:1.25,completionPer1M:10,currency:"usd"},"gemini-2.5-flash":{promptPer1M:.15,completionPer1M:.6,currency:"usd"}};var he,Tt={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function Ce(e){return!e&&!he?Tt:{lang:e?.lang??he?.lang,message:e?.message,abortEarly:e?.abortEarly??he?.abortEarly,abortPipeEarly:e?.abortPipeEarly??he?.abortPipeEarly}}i(Ce,"getGlobalConfig");var It;function Rt(e){return It?.get(e)}i(Rt,"getGlobalMessage");var Ct;function wt(e){return Ct?.get(e)}i(wt,"getSchemaMessage");var Ot;function Pt(e,t){return Ot?.get(e)?.get(t)}i(Pt,"getSpecificMessage");function X(e){let t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}i(X,"_stringify");function S(e,t,n,o,c){let u=c&&"input"in c?c.input:n.value,l=c?.expected??e.expects??null,g=c?.received??X(u),m={kind:e.kind,type:e.type,input:u,expected:l,received:g,message:`Invalid ${t}: ${l?`Expected ${l} but r`:"R"}eceived ${g}`,requirement:e.requirement,path:c?.path,issues:c?.issues,lang:o.lang,abortEarly:o.abortEarly,abortPipeEarly:o.abortPipeEarly},h=e.kind==="schema",d=c?.message??e.message??Pt(e.reference,m.lang)??(h?wt(m.lang):null)??o.message??Rt(m.lang);d!==void 0&&(m.message=typeof d=="function"?d(m):d),h&&(n.typed=!1),n.issues?n.issues.push(m):n.issues=[m]}i(S,"_addIssue");function Dt(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}i(Dt,"_isSameValueZero");function Ye(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}i(Ye,"_isValidObjectKey");function we(e,t){let n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??"never"}i(we,"_joinExpects");function R(e){return e["~standard"]={version:1,vendor:"valibot",validate:i(t=>e["~run"]({value:t},Ce()),"validate")},e}i(R,"_standardSchema");var be=class extends Error{static{i(this,"ValiError")}constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function zn(e){return e instanceof be}i(zn,"isValiError");var _t=/^[\w+-]+(?:\.[\w+-]+)*@[\da-zA-Z]+(?:[.-][\da-zA-Z]+)*\.[a-zA-Z]{2,}$/u,Yn=new RegExp("^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}))*)+$","u");var Nt=/^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])[T ](?:0\d|1\d|2[0-3])(?::[0-5]\d){2}(?:\.\d{1,9})?(?:Z| ?[+-](?:0\d|1\d|2[0-3])(?::?[0-5]\d)?)$/u;function le(e,t){return{kind:"validation",type:"check",reference:le,async:!1,expects:null,requirement:e,message:t,"~run"(n,o){return n.typed&&!this.requirement(n.value)&&S(this,"input",n,o),n}}}i(le,"check");function L(e){return{kind:"validation",type:"email",reference:L,expects:null,async:!1,requirement:_t,message:e,"~run"(t,n){return t.typed&&!this.requirement.test(t.value)&&S(this,"email",t,n),t}}}i(L,"email");function B(e){return{kind:"validation",type:"integer",reference:B,async:!1,expects:null,requirement:Number.isInteger,message:e,"~run"(t,n){return t.typed&&!this.requirement(t.value)&&S(this,"integer",t,n),t}}}i(B,"integer");function V(e){return{kind:"validation",type:"iso_timestamp",reference:V,async:!1,expects:null,requirement:Nt,message:e,"~run"(t,n){return t.typed&&!this.requirement.test(t.value)&&S(this,"timestamp",t,n),t}}}i(V,"isoTimestamp");function ne(e,t){return{kind:"validation",type:"length",reference:ne,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length!==this.requirement&&S(this,"length",n,o,{received:`${n.value.length}`}),n}}}i(ne,"length");function $(e,t){return{kind:"validation",type:"max_length",reference:$,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length>this.requirement&&S(this,"length",n,o,{received:`${n.value.length}`}),n}}}i($,"maxLength");function q(e,t){return{kind:"validation",type:"max_value",reference:q,async:!1,expects:`<=${e instanceof Date?e.toJSON():X(e)}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!(n.value<=this.requirement)&&S(this,"value",n,o,{received:n.value instanceof Date?n.value.toJSON():X(n.value)}),n}}}i(q,"maxValue");function f(e,t){return{kind:"validation",type:"min_length",reference:f,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length<this.requirement&&S(this,"length",n,o,{received:`${n.value.length}`}),n}}}i(f,"minLength");function C(e,t){return{kind:"validation",type:"min_value",reference:C,async:!1,expects:`>=${e instanceof Date?e.toJSON():X(e)}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!(n.value>=this.requirement)&&S(this,"value",n,o,{received:n.value instanceof Date?n.value.toJSON():X(n.value)}),n}}}i(C,"minValue");function Oe(e){return{kind:"transformation",type:"raw_transform",reference:Oe,async:!1,"~run"(t,n){let o=e({dataset:t,config:n,addIssue:i(c=>S(this,c?.label??"input",t,n,c),"addIssue"),NEVER:null});return t.issues?t.typed=!1:t.value=o,t}}}i(Oe,"rawTransform");function re(e,t){return{kind:"validation",type:"regex",reference:re,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!this.requirement.test(n.value)&&S(this,"format",n,o),n}}}i(re,"regex");function Ft(e){return{kind:"transformation",type:"transform",reference:Ft,async:!1,operation:e,"~run"(t){return t.value=this.operation(t.value),t}}}i(Ft,"transform");function N(e){return{kind:"validation",type:"url",reference:N,async:!1,expects:null,requirement(t){try{return URL.canParse?URL.canParse(t):(new URL(t),!0)}catch{return!1}},message:e,"~run"(t,n){return t.typed&&!this.requirement(t.value)&&S(this,"URL",t,n),t}}}i(N,"url");var Ut={abortEarly:!0};function Xe(e,t,n){return typeof e.fallback=="function"?e.fallback(t,n):e.fallback}i(Xe,"getFallback");function ce(e,t,n){return typeof e.default=="function"?e.default(t,n):e.default}i(ce,"getDefault");function Z(){return R({kind:"schema",type:"any",reference:Z,expects:"any",async:!1,"~run"(e){return e.typed=!0,e}})}i(Z,"any");function v(e,t){return R({kind:"schema",type:"array",reference:v,expects:"Array",async:!1,item:e,message:t,"~run"(n,o){let c=n.value;if(Array.isArray(c)){n.typed=!0,n.value=[];for(let u=0;u<c.length;u++){let l=c[u],g=this.item["~run"]({value:l},o);if(g.issues){let m={type:"array",origin:"value",input:c,key:u,value:l};for(let h of g.issues)h.path?h.path.unshift(m):h.path=[m],n.issues?.push(h);if(n.issues||(n.issues=g.issues),o.abortEarly){n.typed=!1;break}}g.typed||(n.typed=!1),n.value.push(g.value)}}else S(this,"type",n,o);return n}})}i(v,"array");function k(e){return R({kind:"schema",type:"boolean",reference:k,expects:"boolean",async:!1,message:e,"~run"(t,n){return typeof t.value=="boolean"?t.typed=!0:S(this,"type",t,n),t}})}i(k,"boolean");function Pe(e,t){return R({kind:"schema",type:"custom",reference:Pe,expects:"unknown",async:!1,check:e,message:t,"~run"(n,o){return this.check(n.value)?n.typed=!0:S(this,"type",n,o),n}})}i(Pe,"custom");function De(e){return R({kind:"schema",type:"lazy",reference:De,expects:"unknown",async:!1,getter:e,"~run"(t,n){return this.getter(t.value)["~run"](t,n)}})}i(De,"lazy");function F(e,t){return R({kind:"schema",type:"literal",reference:F,expects:X(e),async:!1,literal:e,message:t,"~run"(n,o){return Dt(n.value,this.literal)?n.typed=!0:S(this,"type",n,o),n}})}i(F,"literal");function _e(e,t){return R({kind:"schema",type:"loose_object",reference:_e,expects:"Object",async:!1,entries:e,message:t,"~run"(n,o){let c=n.value;if(c&&typeof c=="object"){n.typed=!0,n.value={};for(let u in this.entries){let l=this.entries[u];if(u in c||(l.type==="exact_optional"||l.type==="optional"||l.type==="nullish")&&l.default!==void 0){let g=u in c?c[u]:ce(l),m=l["~run"]({value:g},o);if(m.issues){let h={type:"object",origin:"value",input:c,key:u,value:g};for(let d of m.issues)d.path?d.path.unshift(h):d.path=[h],n.issues?.push(d);if(n.issues||(n.issues=m.issues),o.abortEarly){n.typed=!1;break}}m.typed||(n.typed=!1),n.value[u]=m.value}else if(l.fallback!==void 0)n.value[u]=Xe(l);else if(l.type!=="exact_optional"&&l.type!=="optional"&&l.type!=="nullish"&&(S(this,"key",n,o,{input:void 0,expected:`"${u}"`,path:[{type:"object",origin:"key",input:c,key:u,value:c[u]}]}),o.abortEarly))break}if(!n.issues||!o.abortEarly)for(let u in c)Ye(c,u)&&!Object.prototype.hasOwnProperty.call(this.entries,u)&&(n.value[u]=c[u])}else S(this,"type",n,o);return n}})}i(_e,"looseObject");function Ne(e){return R({kind:"schema",type:"never",reference:Ne,expects:"never",async:!1,message:e,"~run"(t,n){return S(this,"type",t,n),t}})}i(Ne,"never");function D(e,t){return R({kind:"schema",type:"nullable",reference:D,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,"~run"(n,o){return n.value===null&&(this.default!==void 0&&(n.value=ce(this,n,o)),n.value===null)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}i(D,"nullable");function U(e,t){return R({kind:"schema",type:"nullish",reference:U,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:t,"~run"(n,o){return(n.value===null||n.value===void 0)&&(this.default!==void 0&&(n.value=ce(this,n,o)),n.value===null||n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}i(U,"nullish");function E(e){return R({kind:"schema",type:"number",reference:E,expects:"number",async:!1,message:e,"~run"(t,n){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:S(this,"type",t,n),t}})}i(E,"number");function p(e,t){return R({kind:"schema",type:"object",reference:p,expects:"Object",async:!1,entries:e,message:t,"~run"(n,o){let c=n.value;if(c&&typeof c=="object"){n.typed=!0,n.value={};for(let u in this.entries){let l=this.entries[u];if(u in c||(l.type==="exact_optional"||l.type==="optional"||l.type==="nullish")&&l.default!==void 0){let g=u in c?c[u]:ce(l),m=l["~run"]({value:g},o);if(m.issues){let h={type:"object",origin:"value",input:c,key:u,value:g};for(let d of m.issues)d.path?d.path.unshift(h):d.path=[h],n.issues?.push(d);if(n.issues||(n.issues=m.issues),o.abortEarly){n.typed=!1;break}}m.typed||(n.typed=!1),n.value[u]=m.value}else if(l.fallback!==void 0)n.value[u]=Xe(l);else if(l.type!=="exact_optional"&&l.type!=="optional"&&l.type!=="nullish"&&(S(this,"key",n,o,{input:void 0,expected:`"${u}"`,path:[{type:"object",origin:"key",input:c,key:u,value:c[u]}]}),o.abortEarly))break}}else S(this,"type",n,o);return n}})}i(p,"object");function s(e,t){return R({kind:"schema",type:"optional",reference:s,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,"~run"(n,o){return n.value===void 0&&(this.default!==void 0&&(n.value=ce(this,n,o)),n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}i(s,"optional");function b(e,t){return R({kind:"schema",type:"picklist",reference:b,expects:we(e.map(X),"|"),async:!1,options:e,message:t,"~run"(n,o){return this.options.includes(n.value)?n.typed=!0:S(this,"type",n,o),n}})}i(b,"picklist");function x(e,t,n){return R({kind:"schema",type:"record",reference:x,expects:"Object",async:!1,key:e,value:t,message:n,"~run"(o,c){let u=o.value;if(u&&typeof u=="object"){o.typed=!0,o.value={};for(let l in u)if(Ye(u,l)){let g=u[l],m=this.key["~run"]({value:l},c);if(m.issues){let d={type:"object",origin:"key",input:u,key:l,value:g};for(let w of m.issues)w.path=[d],o.issues?.push(w);if(o.issues||(o.issues=m.issues),c.abortEarly){o.typed=!1;break}}let h=this.value["~run"]({value:g},c);if(h.issues){let d={type:"object",origin:"value",input:u,key:l,value:g};for(let w of h.issues)w.path?w.path.unshift(d):w.path=[d],o.issues?.push(w);if(o.issues||(o.issues=h.issues),c.abortEarly){o.typed=!1;break}}(!m.typed||!h.typed)&&(o.typed=!1),m.typed&&(o.value[m.value]=h.value)}}else S(this,"type",o,c);return o}})}i(x,"record");function r(e){return R({kind:"schema",type:"string",reference:r,expects:"string",async:!1,message:e,"~run"(t,n){return typeof t.value=="string"?t.typed=!0:S(this,"type",t,n),t}})}i(r,"string");function Mt(e,t){return R({kind:"schema",type:"tuple",reference:Mt,expects:"Array",async:!1,items:e,message:t,"~run"(n,o){let c=n.value;if(Array.isArray(c)){n.typed=!0,n.value=[];for(let u=0;u<this.items.length;u++){let l=c[u],g=this.items[u]["~run"]({value:l},o);if(g.issues){let m={type:"array",origin:"value",input:c,key:u,value:l};for(let h of g.issues)h.path?h.path.unshift(m):h.path=[m],n.issues?.push(h);if(n.issues||(n.issues=g.issues),o.abortEarly){n.typed=!1;break}}g.typed||(n.typed=!1),n.value.push(g.value)}}else S(this,"type",n,o);return n}})}i(Mt,"tuple");function ze(e){let t;if(e)for(let n of e)if(t)for(let o of n.issues)t.push(o);else t=n.issues;return t}i(ze,"_subIssues");function J(e,t){return R({kind:"schema",type:"union",reference:J,expects:we(e.map(n=>n.expects),"|"),async:!1,options:e,message:t,"~run"(n,o){let c,u,l;for(let g of this.options){let m=g["~run"]({value:n.value},o);if(m.typed)if(m.issues)u?u.push(m):u=[m];else{c=m;break}else l?l.push(m):l=[m]}if(c)return c;if(u){if(u.length===1)return u[0];S(this,"type",n,o,{issues:ze(u)}),n.typed=!0}else{if(l?.length===1)return l[0];S(this,"type",n,o,{issues:ze(l)})}return n}})}i(J,"union");function _(){return R({kind:"schema",type:"unknown",reference:_,expects:"unknown",async:!1,"~run"(e){return e.typed=!0,e}})}i(_,"unknown");function pe(e,t,n){return R({kind:"schema",type:"variant",reference:pe,expects:"Object",async:!1,key:e,options:t,message:n,"~run"(o,c){let u=o.value;if(u&&typeof u=="object"){let l,g=0,m=this.key,h=[],d=i((w,O)=>{for(let G of w.options){if(G.type==="variant")d(G,new Set(O).add(G.key));else{let ye=!0,te=0;for(let A of O){let I=G.entries[A];if(A in u?I["~run"]({typed:!1,value:u[A]},Ut).issues:I.type!=="exact_optional"&&I.type!=="optional"&&I.type!=="nullish"){ye=!1,m!==A&&(g<te||g===te&&A in u&&!(m in u))&&(g=te,m=A,h=[]),m===A&&h.push(G.entries[A].expects);break}te++}if(ye){let A=G["~run"]({value:u},c);(!l||!l.typed&&A.typed)&&(l=A)}}if(l&&!l.issues)break}},"parseOptions");if(d(this,new Set([this.key])),l)return l;S(this,"type",o,c,{input:u[m],expected:we(h,"|"),path:[{type:"object",origin:"value",input:u,key:m,value:u[m]}]})}else S(this,"type",o,c);return o}})}i(pe,"variant");function Ze(e,t,n){let o=e["~run"]({value:t},Ce(n));if(o.issues)throw new be(o.issues);return o.value}i(Ze,"parse");function a(...e){return R({...e[0],pipe:e,"~run"(t,n){for(let o of e)if(o.kind!=="metadata"){if(t.issues&&(o.kind==="schema"||o.kind==="transformation")){t.typed=!1;break}(!t.issues||!n.abortEarly&&!n.abortPipeEarly)&&(t=o["~run"](t,n))}return t}})}i(a,"pipe");function W(e,t,n){let o=e["~run"]({value:t},Ce(n));return{typed:o.typed,success:!o.issues,output:o.value,issues:o.issues}}i(W,"safeParse");var Je=p({role:b([ve.USER,ve.ASSISTANT,ve.SYSTEM]),content:a(r(),f(1)),id:s(r()),createdAt:s(r())}),Fe=De(()=>p({type:b(["string","number","boolean","array","object"]),description:s(r()),enum:s(v(r())),items:s(Fe),properties:s(x(r(),Fe)),required:s(v(r()))})),Lt=p({description:a(r(),f(1)),parameters:p({type:F("object"),properties:x(r(),Fe),required:s(v(r()))})}),Bt=p({id:r(),name:r(),args:x(r(),_())}),qt=p({messages:a(v(Je),f(1)),provider:s(b([j.ANTHROPIC,j.OPENAI,j.GOOGLE])),model:s(r()),maxTokens:s(a(E(),B(),C(1))),temperature:s(a(E(),C(0),q(2))),systemPrompt:s(r()),stream:s(k()),tools:s(x(r(),Lt))}),jt=p({promptTokens:E(),completionTokens:E(),totalTokens:E()}),Qn=p({message:Je,usage:s(jt),finishReason:s(r()),toolCalls:s(v(Bt))}),er=p({provider:b([j.ANTHROPIC,j.OPENAI,j.GOOGLE]),model:s(r()),maxTokens:s(a(E(),B(),C(1))),temperature:s(a(E(),C(0),q(2))),systemPrompt:s(r())});function tr(e){return W(qt,e)}i(tr,"validateAIChatRequest");var K={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};var Qe={FREE:"free",PRO:"pro",PREMIUM:"premium"};var et={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};var tt={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"};var de={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};var Ue={PAYMENT:"payment",SUBSCRIPTION:"subscription"};var cr={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};var nt=100,Vt=p({productId:a(r(),f(1),$(200)),quantity:a(E(),B(),C(1),q(1e4))}),mr=a(p({billingConfigKey:s(a(r(),f(1))),lineItems:s(a(v(Vt),f(1,"At least one line item is required"),$(nt,`At most ${nt} line items`))),successUrl:a(r(),N()),cancelUrl:a(r(),N()),customerEmail:s(a(r(),L())),metadata:s(x(r(),r())),allowPromotionCodes:s(k()),userId:s(r()),productId:s(r()),priceId:s(r()),unitAmount:s(a(E(),B(),C(1))),productName:s(a(r(),f(1))),currency:s(a(r(),ne(3,"Currency must be 3-letter ISO code"))),userEmail:s(a(r(),L())),mode:s(b([Ue.PAYMENT,Ue.SUBSCRIPTION]))}),Oe(({dataset:e,addIssue:t,NEVER:n})=>{let o=e.value,c=o.billingConfigKey||o.metadata?.billingConfigKey;return c?{...o,billingConfigKey:c,lineItems:o.lineItems??[{productId:c,quantity:1}]}:(t({message:"billingConfigKey is required"}),n)})),yr=p({sessionId:r(),sessionUrl:D(a(r(),N()))}),gr=p({userId:r(),tier:r(),status:b(Object.values(de)),subscriptionId:D(r()),customerId:r(),subscriptionEnd:D(a(r(),V())),cancelAtPeriodEnd:k(),updatedAt:a(r(),V())}),vr=p({tier:r(),subscriptionId:D(r()),customerId:r(),status:b(Object.values(de)),subscriptionEnd:D(a(r(),V())),cancelAtPeriodEnd:k(),updatedAt:a(r(),V()),isDefault:s(k())}),hr=p({id:r(),type:r(),data:p({object:Z()}),created:a(r(),V())}),br=_e({userId:s(r()),firebaseUid:s(r()),productType:s(r())});var $t=p({type:F("StripePayment"),name:a(r(),f(1,"Product name is required")),description:s(r()),price:r(),currency:s(a(r(),ne(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:s(a(r(),f(1,"Stripe price ID is required"))),unitAmount:s(a(E(),B(),C(1))),productName:s(a(r(),f(1))),maxUnitAmount:s(a(E(),B(),C(1))),tier:a(r(),f(1,"Tier is required")),duration:a(r(),f(1,"Duration is required")),allowPromotionCodes:s(k()),metadata:s(x(r(),r()))}),Gt=p({type:F("StripeSubscription"),name:a(r(),f(1,"Product name is required")),description:s(r()),price:r(),currency:s(a(r(),ne(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:a(r(),f(1,"Stripe price ID is required")),tier:a(r(),f(1,"Tier is required")),duration:b(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:s(k()),metadata:s(x(r(),r()))}),Ht=pe("type",[$t,Gt]),Er=x(r(),Ht),xr=x(r(),p({name:r(),price:r(),currency:r(),description:s(r()),features:s(v(r())),priceId:s(r()),unitAmount:s(E()),productName:s(r()),allowPromotionCodes:s(k())})),rt={name:r(),price:E(),currency:r(),priceId:s(r()),unitAmount:s(a(E(),B(),C(1))),productName:s(a(r(),f(1))),maxUnitAmount:s(a(E(),B(),C(1))),tier:r(),duration:r(),description:s(r()),metadata:s(x(r(),r())),allowPromotionCodes:s(k())},Wt=pe("mode",[p({mode:F("manual"),taxRateIds:a(v(a(r(),f(1))),f(1))}),p({mode:F("automatic")})]),it=5,Kt=p({allowedCountries:a(v(a(r(),re(/^[A-Z]{2}$/,"allowedCountries: uppercase ISO 3166-1 alpha-2 code expected (e.g. FR)"))),f(1)),shippingRateIds:s(a(v(a(r(),f(1))),$(it,`shippingRateIds: at most ${it} (Stripe limit)`)))}),zt=p({type:F("StripeOrder"),name:r(),currency:a(r(),ne(3)),description:s(r()),metadata:s(x(r(),r())),allowPromotionCodes:s(k()),tax:Wt,taxIdCollection:b(["disabled","optional","required"]),billingAddressCollection:b(["auto","required"]),shipping:s(Kt),customerCreation:b(["always","if_required"]),invoiceCreation:k(),paymentMethodConfiguration:s(a(r(),f(1)))}),Yt=x(r(),pe("type",[p({type:F("StripePayment"),...rt}),p({type:F("StripeSubscription"),...rt}),zt]));function Sr(e){return Ze(Yt,e)}i(Sr,"validateStripeBackConfig");var Pr=p({id:r(),email:s(D(a(r(),L()))),displayName:s(D(r())),photoURL:s(D(a(r(),N()))),emailVerified:s(k()),lastLoginAt:s(r()),providerData:s(v(p({providerId:r(),uid:r(),email:s(D(a(r(),L()))),displayName:s(D(r())),photoURL:s(D(a(r(),N()))),phoneNumber:s(D(r()))}))),role:s(b(Object.values(K))),customClaims:s(x(r(),Z()))}),Xt=p({userId:r(),tier:b(Object.values(Qe)),status:b(Object.values(de)),isActive:s(k()),features:s(v(r())),subscriptionId:D(r()),customerId:r(),subscriptionEnd:D(a(r(),V())),cancelAtPeriodEnd:k(),updatedAt:a(r(),V())}),Dr=p({role:s(b(Object.values(K))),subscription:s(Xt),features:s(v(b(Object.values(et)))),permissions:s(v(b(Object.values(tt)))),githubAccess:s(p({username:s(r()),teamAccess:s(v(r())),repoAccess:s(v(r()))}))});var Me={TRUE:!0,FALSE:!1,USER:"user",ADMIN:"admin",SUPER:"super",CREATE_ONLY:"create-only",GENERATED:"generated",COMPUTED:"computed"};var Q={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"};var Hr={EQ:Q.EQ,NEQ:Q.NEQ,LT:Q.LT,LTE:Q.LTE,GT:Q.GT,GTE:Q.GTE};var ot=class extends Error{static{i(this,"BulkCollisionError")}collidingIds;where;constructor(t,n){super(`BulkCollisionError: ${t.length} id(s) appear in both "${n.replace("-",'" and "')}" \u2014 ${t.join(", ")}`),this.name="BulkCollisionError",this.collidingIds=t,this.where=n}};var Qr=p({collection:a(r(),f(1,"Collection name is required")),data:x(r(),_()),idempotencyKey:s(r())}),ei=p({collection:a(r(),f(1,"Collection name is required")),id:a(r(),f(1,"Entity ID is required"))}),ti=p({collection:a(r(),f(1,"Collection name is required")),id:a(r(),f(1,"Entity ID is required")),data:x(r(),_()),merge:s(k(),!1)}),ni=p({collection:a(r(),f(1,"Collection name is required")),id:a(r(),f(1,"Entity ID is required"))}),ri=p({collection:a(r(),f(1,"Collection name is required")),limit:s(a(E(),C(1),q(1e3)),1e3),offset:s(a(E(),C(0)),0),orderBy:s(r()),orderDirection:s(b(["asc","desc"]),"desc"),where:s(v(p({field:r(),operator:b(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:_()})))});var Jt=p({templateId:a(r(),f(1)),to:a(r(),L()),data:x(r(),_()),locale:s(a(r(),f(2),$(5)),"fr"),from:s(r()),replyTo:s(r())}),yi=p({success:k(),messageId:s(r()),error:s(r())});function gi(e){return W(Jt,e)}i(gi,"validateSendEmailRequest");var st=["pull","push","admin","maintain","triage"];var Le=p({owner:a(r(),f(1,"Repository owner is required")),repo:a(r(),f(1,"Repository name is required"))}),Qt=b([...st]),to=p({userId:a(r(),f(1,"User ID is required")),githubUsername:a(r(),f(1,"GitHub username is required")),repoConfig:Le,permission:s(Qt,"push"),customClaims:s(x(r(),Z()))}),no=p({userId:a(r(),f(1,"User ID is required")),githubUsername:a(r(),f(1,"GitHub username is required")),repoConfig:Le}),ro=p({userId:a(r(),f(1,"User ID is required")),githubUsername:a(r(),f(1,"GitHub username is required")),repoConfig:Le}),io=p({provider:r(),purpose:b(["authentication","api-access"]),code:a(r(),f(1,"Authorization code is required")),redirectUri:a(r(),N("Valid redirect URI is required")),codeVerifier:s(r()),state:s(r()),instance:s(a(r(),N()))}),oo=p({provider:r(),refreshToken:a(r(),f(1,"Refresh token is required")),redirectUri:a(r(),N("Valid redirect URI is required"))}),so=p({provider:r()}),ao=p({userId:a(r(),f(1,"User ID is required"))});var at=p({name:r(),color:r(),icon:r(),customParameters:s(x(r(),r())),button:p({backgroundColor:r(),textColor:r(),borderColor:r(),hoverBackgroundColor:r(),focusOutlineColor:r(),fontWeight:s(r(),"500"),textKey:s(r())})}),en=p({...at.entries,type:b(["auth","both"]),scopes:s(v(r())),firebaseProviderId:s(r())}),Ee=J([F(""),a(r(),N())]),tn=p({authUrl:Ee,tokenUrl:Ee,profileUrl:Ee,revokeUrl:s(Ee)}),nn=p({authentication:s(v(r())),"api-access":v(r())}),rn=s(p({pkce:s(k(),!1),codeChallengeMethod:s(b(["S256","plain"]),"S256")})),on=p({...at.entries,type:b(["oauth","both"]),scopes:nn,endpoints:tn,capabilities:rn});var yo={google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:{authentication:["openid","profile","email"],"api-access":["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/gmail.readonly"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/oauth2/v3/userinfo",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:{authentication:["read:user","user:email"],"api-access":["repo","user","read:org","gist","notifications"]},endpoints:{authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",profileUrl:"https://api.github.com/user",revokeUrl:"https://api.github.com/applications/CLIENT_ID/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:{authentication:["identify","email"],"api-access":["guilds","guilds.members.read","bot","messages.read"]},endpoints:{authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",profileUrl:"https://discord.com/api/users/@me",revokeUrl:"https://discord.com/api/oauth2/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:{authentication:["user-read-email","user-read-private"],"api-access":["user-read-playback-state","user-modify-playback-state","user-read-currently-playing","playlist-read-private","playlist-modify-public","user-library-read"]},endpoints:{authUrl:"https://accounts.spotify.com/authorize",tokenUrl:"https://accounts.spotify.com/api/token",profileUrl:"https://api.spotify.com/v1/me",revokeUrl:"https://accounts.spotify.com/api/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:{authentication:["user:read:email"],"api-access":["channel:read:subscriptions","bits:read","channel:manage:broadcast","channel:read:stream_key","user:read:follows"]},endpoints:{authUrl:"https://id.twitch.tv/oauth2/authorize",tokenUrl:"https://id.twitch.tv/oauth2/token",profileUrl:"https://api.twitch.tv/helix/users",revokeUrl:"https://id.twitch.tv/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:{authentication:["identity"],"api-access":["read","submit","vote","mysubreddits","subscribe"]},endpoints:{authUrl:"https://www.reddit.com/api/v1/authorize",tokenUrl:"https://www.reddit.com/api/v1/access_token",profileUrl:"https://oauth.reddit.com/api/v1/me",revokeUrl:"https://www.reddit.com/api/v1/revoke_token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"oauth",scopes:{"api-access":["r_liteprofile","r_emailaddress","w_member_social","r_organization_social"]},endpoints:{authUrl:"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:"https://www.linkedin.com/oauth/v2/accessToken",profileUrl:"https://api.linkedin.com/v2/me",revokeUrl:"https://www.linkedin.com/oauth/v2/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},slack:{name:"Slack",color:"#E01E5A",icon:"slack",type:"oauth",scopes:{"api-access":["channels:read","chat:write","users:read","files:read","im:read"]},endpoints:{authUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",profileUrl:"https://slack.com/api/users.identity",revokeUrl:"https://slack.com/api/auth.revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},notion:{name:"Notion",color:"#000000",icon:"notion",type:"oauth",scopes:{"api-access":["read","write"]},endpoints:{authUrl:"https://api.notion.com/v1/oauth/authorize",tokenUrl:"https://api.notion.com/v1/oauth/token",profileUrl:"https://api.notion.com/v1/users/me",revokeUrl:"https://api.notion.com/v1/oauth/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},medium:{name:"Medium",color:"#000000",icon:"medium",type:"oauth",scopes:{"api-access":["basicProfile","publishPost","listPublications"]},endpoints:{authUrl:"https://medium.com/m/oauth/authorize",tokenUrl:"https://medium.com/v1/tokens",profileUrl:"https://medium.com/v1/me",revokeUrl:"https://medium.com/v1/tokens/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"oauth",scopes:{"api-access":["tweet.read","users.read","follows.read","tweet.write","like.write"]},endpoints:{authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",profileUrl:"https://api.twitter.com/2/users/me",revokeUrl:"https://api.twitter.com/2/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},mastodon:{name:"Mastodon",color:"#6364FF",icon:"mastodon",type:"oauth",scopes:{"api-access":["read","write","follow","push"]},endpoints:{authUrl:"",tokenUrl:"",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},youtube:{name:"YouTube",color:"#FF0000",icon:"youtube",type:"oauth",scopes:{"api-access":["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.force-ssl"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/youtube/v3/channels",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},supabase:{name:"Supabase",color:"#3ECF8E",icon:"supabase",type:"oauth",scopes:{"api-access":["auth:read","auth:write","database:read","database:write","domains:read","domains:write","edge_functions:read","edge_functions:write","environment:read","environment:write","organizations:read","projects:read","projects:write","rest:read","rest:write","secrets:read","secrets:write","storage:read"]},endpoints:{authUrl:"https://api.supabase.com/v1/oauth/authorize",tokenUrl:"https://api.supabase.com/v1/oauth/token",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#F1F3F5",textColor:"#11181C",borderColor:"#E6E8EB",hoverBackgroundColor:"#E6E8EB",focusOutlineColor:"#3ECF8E",fontWeight:"500"}},vercel:{name:"Vercel",color:"#000000",icon:"vercel",type:"oauth",scopes:{authentication:["openid","email","profile","offline_access"],"api-access":["project","project-env-vars","deployment","team","user"]},endpoints:{authUrl:"https://vercel.com/oauth/authorize",tokenUrl:"https://api.vercel.com/login/oauth/token",profileUrl:"https://api.vercel.com/login/oauth/userinfo",revokeUrl:"https://api.vercel.com/login/oauth/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}}},go=x(r(),en),vo=x(r(),on);var ut={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"};var Co={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:ut.ANALYTICS},marketing:{requiresConsent:ut.MARKETING}};function lt(e){return e instanceof Error&&"source"in e&&typeof e.source=="string"?e.source:typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("auth/")?"auth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("oauth/")?"oauth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&["permission-denied","unavailable","not-found","already-exists","unauthenticated","invalid-argument","failed-precondition","resource-exhausted"].includes(e.code)?"firebase":typeof e=="object"&&e!==null&&"issues"in e&&Array.isArray(e.issues)&&"name"in e&&e.name==="ValiError"?"validation":e instanceof Error&&e.name==="EntityHookError"?"entity":typeof e=="object"&&e!==null&&("response"in e||"status"in e||"statusText"in e)?"api":typeof e=="object"&&e!==null&&"componentStack"in e?"ui":"unknown"}i(lt,"detectErrorSource");function H(e){return(t,n)=>{if(t instanceof P)return t;if(typeof t!="object"||t===null){let g=typeof t=="string"?t:e.defaultErrorMessage;return new P(n||g,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let o;e.extractErrorCode?o=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(o=t.code);let c=e.defaultErrorCode;o&&e.errorCodeMapping&&o in e.errorCodeMapping&&(c=e.errorCodeMapping[o]);let u;e.extractErrorMessage?u=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(u=t.message),o&&e.friendlyMessageMapping&&o in e.friendlyMessageMapping&&(u=e.friendlyMessageMapping[o]),u||(u=e.defaultErrorMessage);let l;return e.processMetadata?l=e.processMetadata(t):(l={originalError:t},o&&(l.originalCode=o)),"originalError"in l||(l.originalError=t),new P(n||u,c,{details:l,source:e.errorSource})}}i(H,"createErrorHandler");var xe={"permission-denied":"permission-denied",unavailable:"unavailable","not-found":"not-found","already-exists":"already-exists",unauthenticated:"unauthenticated","invalid-argument":"invalid-argument","failed-precondition":"invalid-argument","resource-exhausted":"rate-limit-exceeded","deadline-exceeded":"timeout",cancelled:"cancelled","not-implemented":"unimplemented"};var ie={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",DELETE_ACCOUNT_REQUIRES_SERVER:"Account deletion requires a server endpoint. Configure a callable provider or deploy a delete-account Edge Function.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},sn={400:"invalid-argument",401:"unauthenticated",403:"permission-denied",404:"not-found",409:"already-exists",422:"validation-failed",429:"rate-limit-exceeded",500:"internal",501:"unimplemented",502:"unavailable",503:"unavailable",504:"timeout"},Be={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},z={auth:{errorSource:"auth",defaultErrorCode:"unknown",defaultErrorMessage:"An authentication error occurred",errorCodeMapping:{"auth/user-not-found":"not-found","auth/wrong-password":"invalid-argument","auth/email-already-in-use":"already-exists","auth/weak-password":"validation-failed","auth/invalid-email":"validation-failed","auth/account-exists-with-different-credential":"already-exists","auth/credential-already-in-use":"already-exists","auth/requires-recent-login":"unauthenticated","auth/user-disabled":"permission-denied","auth/too-many-requests":"rate-limit-exceeded","auth/network-request-failed":"unavailable","auth/popup-blocked":"unavailable","auth/popup-closed-by-user":"invalid-argument","auth/cancelled-popup-request":"invalid-argument","auth/operation-not-allowed":"unimplemented","auth/invalid-credential":"invalid-argument","auth/invalid-verification-code":"invalid-argument","auth/captcha-check-failed":"validation-failed","auth/invalid-phone-number":"validation-failed","auth/missing-phone-number":"invalid-argument","auth/quota-exceeded":"rate-limit-exceeded","auth/timeout":"unavailable","auth/web-storage-unsupported":"unavailable","auth/unauthorized-domain":"permission-denied","auth/internal-error":"internal","auth/invalid-action-code":"invalid-argument","auth/invalid-continue-uri":"invalid-argument","auth/missing-continue-uri":"invalid-argument","auth/missing-ios-bundle-id":"invalid-argument","auth/missing-android-pkg-name":"invalid-argument","auth/unauthorized-continue-uri":"permission-denied","auth/invalid-dynamic-link-domain":"invalid-argument","auth/invalid-tenant-id":"invalid-argument","auth/tenant-id-mismatch":"invalid-argument","auth/provider-already-linked":"already-exists","auth/invalid-persistence-type":"invalid-argument","auth/unsupported-persistence-type":"unimplemented","auth/invalid-provider":"invalid-argument","auth/invalid-client-id":"invalid-argument","oauth/unauthorized-app":"permission-denied","auth/provider-not-enabled":"unimplemented","auth/unknown-provider":"invalid-argument","auth/missing-provider":"invalid-argument","auth/no-user-signed-in":"unauthenticated",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",...xe},friendlyMessageMapping:{"auth/user-not-found":"No account found with this email address.","auth/wrong-password":"Incorrect password. Please try again.","auth/email-already-in-use":"An account with this email already exists.","auth/weak-password":"Password is too weak. It should be at least 6 characters.","auth/invalid-email":"Please enter a valid email address.","auth/account-exists-with-different-credential":"An account already exists with the same email but different sign-in method.","auth/credential-already-in-use":"This credential is already associated with a different user account.","auth/requires-recent-login":"This operation requires you to sign in again for security reasons.","auth/user-disabled":"This account has been disabled.","auth/too-many-requests":"Too many sign-in attempts. Please try again later.","auth/network-request-failed":"Network connection error. Please check your internet connection.","auth/popup-blocked":"Sign-in popup was blocked. Please allow popups for this site.","auth/popup-closed-by-user":"Sign-in popup was closed before completion.","auth/operation-not-allowed":"This sign-in method is not enabled for this project.","auth/internal-error":"An internal authentication error occurred. Please try again.","auth/invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","auth/invalid-continue-uri":"The continue URL provided is invalid.","auth/missing-continue-uri":"A continue URL must be provided in the request.","auth/missing-ios-bundle-id":"An iOS Bundle ID must be provided in the request.","auth/missing-android-pkg-name":"An Android package name must be provided in the request.","auth/unauthorized-continue-uri":"The domain of the continue URL is not allowlisted.","auth/invalid-dynamic-link-domain":"The provided dynamic link domain is not authorized.","auth/invalid-tenant-id":"The provided tenant ID is invalid.","auth/tenant-id-mismatch":"The tenant ID of the provider does not match the tenant ID of the current user.","auth/provider-already-linked":"This authentication provider is already linked to the account.","auth/invalid-persistence-type":"The specified persistence type is invalid.","auth/unsupported-persistence-type":"The current environment does not support the specified persistence type.","auth/invalid-provider":"The specified authentication provider is invalid.","auth/invalid-client-id":"The authentication client ID provided is invalid.","oauth/unauthorized-app":"This application is not authorized to use OAuth with the provided client ID.","auth/provider-not-enabled":"This authentication provider is not enabled.","auth/unknown-provider":"Unknown authentication provider.","auth/missing-provider":"No authentication provider specified in the request.","auth/no-user-signed-in":"No user is currently signed in."}},oauth:{errorSource:"oauth",defaultErrorCode:"unknown",defaultErrorMessage:"An OAuth error occurred",errorCodeMapping:{"oauth/invalid-request":"invalid-argument","oauth/invalid-client":"invalid-argument","oauth/invalid-grant":"invalid-argument","oauth/unauthorized-client":"permission-denied","oauth/unsupported-grant-type":"unimplemented","oauth/invalid-scope":"invalid-argument","oauth/insufficient-scope":"permission-denied","oauth/invalid-token":"unauthenticated","oauth/expired-token":"unauthenticated","oauth/redirect-uri-mismatch":"invalid-argument","oauth/access-denied":"permission-denied","oauth/server-error":"unavailable","oauth/temporarily-unavailable":"unavailable","oauth/state-mismatch":"invalid-argument","oauth/invalid-callback":"invalid-argument","oauth/client-secret-mismatch":"permission-denied","oauth/unauthorized-scope":"permission-denied","oauth/rate-limit-exceeded":"rate-limit-exceeded","oauth/token-expired":"unauthenticated","oauth/missing-token":"invalid-argument","oauth/invalid-code":"invalid-argument","oauth/invalid-redirect":"invalid-argument","oauth/provider-error":"unavailable","oauth/invalid-response":"unavailable","oauth/unauthorized-access":"permission-denied",...xe},friendlyMessageMapping:{"oauth/invalid-request":"The OAuth request was invalid or missing parameters.","oauth/invalid-client":"Client authentication failed.","oauth/invalid-grant":"The provided authorization grant is invalid.","oauth/unauthorized-client":"The client is not authorized to use this grant type.","oauth/unsupported-grant-type":"The requested grant type is not supported.","oauth/invalid-scope":"The requested scope is invalid or unknown.","oauth/insufficient-scope":"The token does not have the required scope for this resource.","oauth/invalid-token":"The access token is invalid.","oauth/expired-token":"The access token has expired.","oauth/redirect-uri-mismatch":"The redirect URI does not match the registered URI.","oauth/access-denied":"The resource owner denied the request.","oauth/server-error":"The authorization server encountered an unexpected error.","oauth/temporarily-unavailable":"The authorization server is temporarily unavailable.","oauth/state-mismatch":"Invalid state parameter. This could be a security issue.","oauth/invalid-callback":"The callback URL is invalid or not registered.","oauth/client-secret-mismatch":"The client secret does not match the registered secret.","oauth/unauthorized-scope":"The requested scope is not authorized for this client.","oauth/rate-limit-exceeded":"Too many requests. Please try again later.","oauth/token-expired":"The OAuth token has expired and needs to be refreshed.","oauth/missing-token":"No OAuth token was provided in the request.","oauth/invalid-code":"The authorization code is invalid or expired.","oauth/invalid-redirect":"The redirect URL is invalid or does not match the registered redirect URL.","oauth/provider-error":"The OAuth provider returned an error.","oauth/invalid-response":"The response from the OAuth provider was invalid.","oauth/unauthorized-access":"Unauthorized access to OAuth resources."}},api:{errorSource:"api",defaultErrorCode:"unknown",defaultErrorMessage:"API request failed",errorCodeMapping:Object.fromEntries(Object.entries(sn).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode:i(e=>{if(typeof e!="object"||e===null)return;let t;return"response"in e&&e.response&&"status"in e.response?t=e.response.status:"status"in e&&typeof e.status=="number"&&(t=e.status),t?.toString()},"extractErrorCode"),processMetadata:i(e=>{let t={originalError:e};return typeof e!="object"||e===null||("response"in e&&e.response?("status"in e.response&&(t.statusCode=e.response.status),"data"in e.response&&(t.responseData=e.response.data)):"status"in e&&(t.statusCode=e.status)),t},"processMetadata")},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:xe,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:ie.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:i(e=>{let t={originalError:e};return typeof e=="object"&&e!==null&&"componentStack"in e&&(t.componentStack=e.componentStack),t},"processMetadata")},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:ie["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:ie.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:i(e=>{if(e instanceof Error)return e.name},"extractErrorCode")}},an=i(e=>e instanceof be?new P(ie["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):H(z.validation)(e),"handleValidationError"),un=i(e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&e.type in Be){let t=e,n=Be[t.type]||"unknown";return new P(t.message||ie[n],n,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&Re[e.code]){let t=e,n=Re[t.code];if(n){let o=Be[n.type]||"unknown";return new P(n.message||ie[o],o,{details:{originalCode:t.code,originalError:e},source:"entity"})}}return H(z.entity)(e)},"handleEntityError"),ct={auth:H(z.auth),oauth:H(z.oauth),api:H(z.api),firebase:H(z.firebase),ui:H(z.ui),validation:an,entity:un,unknown:H(z.unknown)};function Se(e,t,n){return e instanceof P?e:(ct[t]||ct.unknown)(e,n)}i(Se,"mapToDoNotDevError");function pt(e,t,n={}){let o=globalThis.Sentry;o&&o.withScope(c=>{c.setTag("errorSource",t),c.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([u,l])=>{if(typeof l!="function"&&u!=="originalError")try{c.setExtra(u,l)}catch{c.setExtra(u,`[${typeof l}]`)}}),Object.entries(n).forEach(([u,l])=>{if(typeof l!="function")try{c.setExtra(`context.${u}`,l)}catch{c.setExtra(`context.${u}`,`[${typeof l}]`)}}),(e.details?.userId||n.userId)&&c.setUser({id:e.details?.userId||n.userId,email:e.details?.userEmail||n.userEmail}),o.captureException(e)})}i(pt,"captureErrorToSentry");function ln(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof process<"u"&&process.env?"production".toLowerCase()!=="production":!1}i(ln,"isDev");function ke(e,t){let n=typeof t=="string"?{userMessage:t}:t||{},{userMessage:o,context:c={},log:u=!0,reportToSentry:l=!0,showNotification:g=!1,severity:m="error"}=n,h=lt(e),d=e instanceof P?e:Se(e,h,o);if(o&&!d.userMessageProvided&&(d.message.includes("Error")||d.message.includes("Failed")||d.message.length<10?d=new P(o,d.code,{details:{...d.details,originalMessage:d.message},source:h,userMessageProvided:!0}):d=new P(d.message,d.code,{details:{...d.details,userMessage:o},source:h,userMessageProvided:!0})),u){let w=ln()||typeof window<"u"&&window.__DNDEV_DEBUG,O={code:d.code,message:d.message,source:h};switch(m){case"warning":console.warn(`[DoNotDev] ${d.code}: ${d.message}`,w?{...O,details:d.details}:O);break;case"info":console.info(`[DoNotDev] ${d.code}: ${d.message}`,w?{...O,details:d.details}:O);break;case"success":console.log(`[DoNotDev] ${d.code}: ${d.message}`,w?{...O,details:d.details}:O);break;default:console.error(`[DoNotDev] ${d.code}: ${d.message}`,w?{...O,details:d.details,stack:d.stack}:O)}}return l&&pt(d,h,c),g&&typeof window<"u"&&console.warn("[handleError] showNotification requires client-side toast setup"),d}i(ke,"handleError");function Ds(e,t,n,o){let c=o?` ${JSON.stringify(o)}`:"",u=`${t}.${n}(${c})`,l=Se(e,"auth",`${u}: ${cn(e)}`);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&l.code==="unknown"&&e.code!=="unknown"?new P(l.message,l.code,{details:{...l.details,originalCode:e.code},source:l.source}):l}i(Ds,"wrapAuthError");function cn(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}i(cn,"getErrorMessage");var dt={[K.GUEST]:0,[K.USER]:1,[K.ADMIN]:2,[K.SUPER]:3};function qe(e,t){if(!e)return!1;let n=dt[e]??-1,o=dt[t]??1/0;return n>=o}i(qe,"hasRoleAccess");var je="__DNDEV_SINGLETONS__";function pn(){if(typeof globalThis<"u"){let e=globalThis;return e[je]||(e[je]=new Map),e[je]}return new Map}i(pn,"getSingletonRegistry");function ft(e,t){let n=pn();return n.has(e)||n.set(e,t()),n.get(e)}i(ft,"getGlobalSingleton");function Ls(e,...t){let n=null,o=!1;return i(function(){if(n!==null)return n;if(o)throw new Error("Circular dependency detected in singleton initialization");o=!0;try{return typeof e=="function"&&e.prototype?n=new e(...t):n=e(),n}finally{o=!1}},"getInstance")}i(Ls,"createSingleton");function mt(){return ft("providers",()=>({providers:null}))}i(mt,"getProviderState");function Vs(e){let{providers:t}=mt();if(!t)throw new Error(`[dndev] Provider "${e}" not available. Call configureProviders() at app startup.`);let n=t[e];if(!n)throw new Error(`[dndev] Provider "${e}" not configured. Pass it to configureProviders().`);return n}i(Vs,"getProvider");function $s(e){return!!mt().providers?.[e]}i($s,"hasProvider");function dn(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}i(dn,"hasVisibility");function fn(e){if(dn(e))return e.visibility}i(fn,"getFieldVisibility");function mn(e,t){let n=e??"guest";return n==="hidden"?!1:n==="technical"?qe(t,"admin"):n==="owner"?!1:qe(t,n)}i(mn,"isFieldVisible");function yn(e,t,n){for(let o of n.ownerFields)if(e[o]===t)return!0;return!1}i(yn,"isOwnerVisible");function yt(e,t,n){let o=e;if(!o||typeof o!="object"||!o.entries)return console.warn("getVisibleFields expects a Valibot object schema (v.object)."),[];let c=o.entries,u=[],{documentData:l,uid:g,ownership:m}=n??{},h=m&&g!=null&&l&&yn(l,g,m);for(let[d,w]of Object.entries(c)){let O=fn(w);if(O==="owner"){h&&u.push(d);continue}mn(O,t)&&u.push(d)}return u}i(yt,"getVisibleFields");function Xs(e,t,n,o){if(!e)return{};let c=o?.uid!=null&&o?.ownership!=null?{documentData:o.documentData??e,uid:o.uid,ownership:o.ownership}:void 0,u=yt(t,n,c),l={};for(let g of u)Object.prototype.hasOwnProperty.call(e,g)&&(l[g]=e[g]);return l}i(Xs,"filterVisibleFields");function Ve(e){let t=e.listCardFields;if(t){if(Array.isArray(t))return t;let n=t,o=[...n.title??[],...n.subtitle??[],...n.content??[],...n.footer??[]];return[...new Set(o)]}return e.listFields&&e.listFields.length>0?e.listFields:e.fields?Object.keys(e.fields):[]}i(Ve,"getListCardFieldNames");var gn=new Set(["http:","https:","mailto:","tel:","blob:"]);function ta(e){if(!e||typeof e!="string")return"";let t=e.trim();if(/^[/.?#]/.test(t))return t;try{let n=new URL(t);if(gn.has(n.protocol))return t}catch{return t}return""}i(ta,"sanitizeHref");var gt=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],ia="available",oa=["draft","deleted"],$e=["id","createdAt","updatedAt","createdById","updatedById"],sa=[...$e,"status"];var Ae={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...gt]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0}},createdAt:{name:"createdAt",type:"timestamp",visibility:"technical",label:"crud:fields.createdAt",validation:{}},updatedAt:{name:"updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields.updatedAt",validation:{}},createdById:{name:"createdById",type:"reference",visibility:"technical",label:"crud:fields.createdById",validation:{}},updatedById:{name:"updatedById",type:"reference",visibility:"technical",label:"crud:fields.updatedById",validation:{}}};function Te(e,t){let n=new Date(e),o=n.getDate();return n.setMonth(n.getMonth()+t),n.getDate()!==o&&n.setDate(0),n}i(Te,"addMonths");function vt(e,t){let n=new Date(e),o=n.getDate();return n.setFullYear(n.getFullYear()+t),n.getDate()!==o&&n.setDate(0),n}i(vt,"addYears");function wu(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let n;return e==="1month"?n=Te(t,1):e==="3months"?n=Te(t,3):e==="6months"?n=Te(t,6):e==="1year"?n=vt(t,1):e==="2years"?n=vt(t,2):n=Te(t,1),n.toISOString()}i(wu,"calculateSubscriptionEndDate");var St=new Map;function y(e,t){St.set(e,t)}i(y,"registerSchemaGenerator");function T(e,t){return t?e:U(e)}i(T,"applyRequired");var Ie=i(e=>{let t=[];e.validation?.minLength!==void 0&&t.push(f(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push($(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(re(new RegExp(e.validation.pattern),"Invalid format"));let n=t.length>0?a(r(),...t):r();return T(n,e.validation?.required)},"textSchema"),hn=i(e=>{let t=a(r(),L("Invalid email address"));return T(t,e.validation?.required)},"emailSchema"),bn=i(e=>{let t=e.validation?.minLength!==void 0?a(r(),f(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):r();return T(t,e.validation?.required)},"passwordSchema"),En=i(e=>{let t=a(r(),N("Invalid URL"));return T(t,e.validation?.required)},"urlSchema"),oe=i(e=>{let t=[];e.validation?.min!==void 0&&t.push(C(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(q(e.validation.max,`Must be at most ${e.validation.max}`));let n=t.length>0?a(E(),...t):E();return T(n,e.validation?.required)},"numberSchema"),ht=i(e=>{let t=k();return T(t,e.validation?.required)},"booleanSchema"),se=i(e=>{let t=a(r(),le(n=>!isNaN(new Date(n).getTime()),"Invalid date format"));return T(t,e.validation?.required)},"dateSchema"),kt=p({url:r(),filename:r(),size:E(),mimeType:U(r()),uploadedAt:U(r())}),bt=i(e=>{let t=D(kt);return T(t,e.validation?.required)},"fileSchema"),Et=i(e=>{let t=v(kt);return T(t,e.validation?.required)},"filesSchema"),At=p({fullUrl:r(),thumbUrl:r()}),xn=i(e=>{let t=J([r(),At]);return T(t,e.validation?.required)},"pictureSchema"),Sn=i(e=>{let t=v(J([r(),At]));return T(t,e.validation?.required)},"picturesSchema"),kn=i(e=>{let t=p({lat:E(),lng:E()});return T(t,e.validation?.required)},"geopointSchema"),An=i(e=>{let t=p({formatted_address:r(),latitude:E(),longitude:E(),street_number:U(r()),route:U(r()),locality:U(r()),administrative_area_level_1:U(r()),administrative_area_level_2:U(r()),country:U(r()),postal_code:U(r())});return T(t,e.validation?.required)},"addressSchema"),Tn=i(e=>{let t=x(r(),_());return T(t,e.validation?.required)},"mapSchema"),In=i(e=>{let t=v(_());return T(t,e.validation?.required)},"arraySchema"),Ge=i(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let o=t.map(u=>u.value),c=b(o);return T(c,e.validation?.required)}let n=J([r(),E()]);return T(n,e.validation?.required)},"selectSchema"),Rn=i(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let o=t.map(u=>u.value),c=v(b(o));return T(c,e.validation?.required)}let n=v(r());return T(n,e.validation?.required)},"multiselectSchema"),Cn=i(e=>{let t=a(r(),f(1,"Invalid ID format"));return T(t,e.validation?.required)},"referenceSchema"),He=i(e=>{let t=r();return T(t,e.validation?.required)},"stringSchema"),wn=i(e=>{let t=r();return T(t,e.validation?.required)},"telSchema"),On=i(e=>{let t=e.validation?.minLength??15,n=e.validation?.maxLength??34,o=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",c=[];if(t!==void 0&&c.push(f(t,`IBAN must be at least ${t} characters`)),n!==void 0&&c.push($(n,`IBAN must not exceed ${n} characters`)),o){let l=typeof o=="string"?new RegExp(o):o;c.push(re(l,"Invalid IBAN format"))}let u=c.length>0?a(r(),...c):r();return T(u,e.validation?.required)},"ibanSchema"),xt=i(()=>Ne(),"neverSchema"),Pn=i(e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let o=[t.checkedValue,t.uncheckedValue],c=b(o);return T(c,e.validation?.required)}let n=k();return T(n,e.validation?.required)},"switchSchema"),Dn=i(e=>Pe(n=>e.validation?.required?typeof n=="object"&&n!==null?n.gdprConsent===!0:!1:n===!1||n===null||n===void 0?!0:typeof n=="object"&&n!==null?n.gdprConsent===!0:!1,"GDPR consent must be given"),"gdprConsentSchema"),_n=i(e=>{let t=p({amount:E(),currency:s(r()),vatIncluded:s(k()),discountPercent:s(a(E(),C(0),q(100)))});return T(t,e.validation?.required)},"priceSchema");function Nn(){y("text",Ie),y("textarea",Ie),y("richtext",Ie),y("color",Ie),y("email",hn),y("password",bn),y("url",En),y("tel",wn),y("iban",On),y("number",oe),y("currency",oe),y("price",_n),y("range",oe),y("year",oe),y("rating",oe),y("duration",oe),y("boolean",ht),y("checkbox",ht),y("gdprConsent",Dn),y("date",se),y("datetime-local",se),y("time",se),y("week",se),y("month",se),y("timestamp",se),y("file",bt),y("files",Et),y("document",bt),y("documents",Et),y("image",xn),y("images",Sn),y("geopoint",kn),y("address",An),y("map",Tn),y("array",In),y("select",Ge),y("multiselect",Rn),y("radio",Ge),y("combobox",Ge),y("switch",Pn),y("reference",Cn),y("hidden",He),y("avatar",He),y("badge",He),y("submit",xt),y("reset",xt)}i(Nn,"registerBuiltinSchemas");Nn();function fe(e){if(e.validation?.schema){let o=e.validation.schema;return T(o,e.validation?.required)}let t=St.get(e.type);if(t){let o=t(e);if(o!==null)return o}let n=_();return T(n,e.validation?.required)}i(fe,"getSchemaType");function We(e,t){return!!(t.visibility==="hidden"||t.editable===Me.GENERATED||$e.includes(e))}i(We,"isWriteExcluded");function me(e,t){return Object.assign(e,{visibility:t})}i(me,"withVisibility");function ee(e,t){let n=e;return n.metadata={collection:t.collection,entity:t.name,...t.uniqueKeys&&{uniqueKeys:t.uniqueKeys}},n}i(ee,"withMetadata");function Fn(e){let t=fe(e);return me(t,e.visibility)}i(Fn,"createFieldSchema");function Ke(e){let t=fe({...e,validation:{...e.validation,required:!1}});return me(t,e.visibility)}i(Ke,"createOptionalFieldSchema");function Wu(e){let t=e.fields,n={};for(let[A,I]of Object.entries(t))I.visibility!=="hidden"&&(n[A]=Ke(I));let o=ee(p(n),e),c={};for(let[A,I]of Object.entries(t))We(A,I)||(c[A]=Fn(I));let u=ee(p(c),e),l={};for(let[A,I]of Object.entries(t))if(!We(A,I))if(A==="status"){let Y=F("draft");l[A]=me(Y,I.visibility)}else l[A]=Ke(I);let g=ee(p(l),e),m={};for(let[A,I]of Object.entries(t))We(A,I)||(m[A]=Ke(I));m.id=me(fe(Ae.id),"technical");let h=ee(p(m),e),d;if(e.listFields&&e.listFields.length>0){let A=["id","status"],I=[...new Set([...A,...e.listFields])];d={};for(let Y of I){let ae=n[Y];ae&&(d[Y]=ae)}}else d=n;let w=ee(p(d),e),O,G=Ve(e);if(G.length>0){let A=["id","status"],I=[...new Set([...A,...G])];O={};for(let Y of I){let ae=n[Y];ae&&(O[Y]=ae)}}else O=n;let ye=ee(p(O),e),te=ee(p({id:me(fe(Ae.id),"technical")}),e);return{create:u,draft:g,update:h,get:o,list:w,listCard:ye,delete:te}}i(Wu,"createSchemas");var Un=x(r(),_()),Mn=p({id:r(),patch:x(r(),_())}),Ln=r(),Yu=p({inserts:s(v(Un)),updates:s(v(Mn)),deletes:s(v(Ln))}),Xu=p({insertedIds:v(r()),updatedIds:v(r()),deletedIds:v(r())});function Zu(e){let t=new Set((e.updates??[]).map(l=>l.id)),n=e.deletes??[],o=[];for(let l of n)t.has(l)&&o.push(l);if(o.length>0)return{collisions:o,where:"updates-deletes"};let c=e.inserts??[],u=[];for(let l of c)typeof l.id=="string"&&t.has(l.id)&&u.push(l.id);return u.length>0?{collisions:u,where:"inserts-updates"}:{collisions:[],where:null}}i(Zu,"detectBulkCollisions");var Nl=a(r(),le(e=>e.startsWith("/proxy/")||e.startsWith("data:image/"),"Image URL must be box-proxied (/proxy/...) or an inline data:image URI.")),Bn=b(["ephemeral","session","persistent"]),qn=p({title:s(r()),pinnable:s(k()),preferredHeight:s(a(E(),C(0)))}),Fl=p({id:a(r(),f(1)),kind:a(r(),f(1)),lifetime:s(Bn,"ephemeral"),metadata:s(qn),payload:_()}),Ul=p({widgetId:a(r(),f(1)),action:a(r(),f(1)),payload:_()});export{$n as a,Gn as b,Hn as c,Wn as d,zn as e,ne as f,q as g,f as h,C as i,re as j,Ft as k,N as l,Z as m,v as n,k as o,Pe as p,E as q,p as r,s,b as t,x as u,r as v,Mt as w,J as x,_ as y,Ze as z,a as A,W as B,qt as C,tr as D,Qe as E,de as F,mr as G,Sr as H,ot as I,Jt as J,gi as K,P as L,to as M,no as N,ro as O,io as P,yo as Q,ke as R,Ds as S,qe as T,Ls as U,Vs as V,$s as W,Xs as X,Ve as Y,ta as Z,wu as _,ia as $,oa as aa,Wu as ba,Yu as ca,Xu as da,Zu as ea};
22
- //# sourceMappingURL=chunk-5DTPEM64.js.map
22
+ //# sourceMappingURL=chunk-GYTCWMXV.js.map