@donotdev/functions 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (290) hide show
  1. package/lib/chunks/{chunk-IFOYVSPU.js → chunk-3F4BWKQD.js} +2 -2
  2. package/lib/chunks/{chunk-JTAGPPPL.js → chunk-5IPULSUX.js} +2 -2
  3. package/lib/chunks/chunk-6USHTJED.js +22 -0
  4. package/lib/chunks/chunk-6USHTJED.js.map +7 -0
  5. package/lib/chunks/{chunk-RM7DV6IQ.js → chunk-CXBSROEW.js} +2 -2
  6. package/lib/chunks/{chunk-5DTPEM64.js → chunk-GYTCWMXV.js} +1 -1
  7. package/lib/chunks/{chunk-5DTPEM64.js.map → chunk-GYTCWMXV.js.map} +1 -1
  8. package/lib/chunks/chunk-LCDLG4VG.js +151 -0
  9. package/lib/chunks/{chunk-UH4L3EF3.js.map → chunk-LCDLG4VG.js.map} +4 -4
  10. package/lib/chunks/{chunk-4U7QQWYG.js → chunk-MQANUSY3.js} +2 -2
  11. package/lib/chunks/chunk-OFQVO3FD.js +22 -0
  12. package/lib/chunks/chunk-OFQVO3FD.js.map +7 -0
  13. package/lib/chunks/chunk-PWAGW4R6.js +22 -0
  14. package/lib/chunks/chunk-PWAGW4R6.js.map +7 -0
  15. package/lib/chunks/{chunk-QJAU2MWV.js → chunk-US2VOP4S.js} +2 -2
  16. package/lib/chunks/{chunk-QJAU2MWV.js.map → chunk-US2VOP4S.js.map} +3 -3
  17. package/lib/chunks/chunk-YTKDNZNW.js +22 -0
  18. package/lib/chunks/chunk-YTKDNZNW.js.map +7 -0
  19. package/lib/chunks/{monitoring-AGCSU3FI.js → monitoring-E7JBYBHQ.js} +2 -2
  20. package/lib/chunks/{rateLimiter-6KO7AIZP.js → rateLimiter-SQISLOP5.js} +2 -2
  21. package/lib/chunks/{server-32A5RH4C.js → server-IQ5JNJOM.js} +2 -2
  22. package/lib/firebase/auth/getCustomClaims.d.ts +0 -0
  23. package/lib/firebase/auth/getUserAuthStatus.d.ts +0 -0
  24. package/lib/firebase/auth/index.d.ts +0 -0
  25. package/lib/firebase/auth/removeCustomClaims.d.ts +0 -0
  26. package/lib/firebase/auth/setCustomClaims.d.ts +0 -0
  27. package/lib/firebase/baseFunction.d.ts +0 -0
  28. package/lib/firebase/billing/cancelSubscription.d.ts +0 -0
  29. package/lib/firebase/billing/changePlan.d.ts +0 -0
  30. package/lib/firebase/billing/createCheckoutSession.d.ts +0 -0
  31. package/lib/firebase/billing/createCustomerPortal.d.ts +0 -0
  32. package/lib/firebase/billing/healthCheck.d.ts +0 -0
  33. package/lib/firebase/billing/index.d.ts +0 -0
  34. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -0
  35. package/lib/firebase/billing/webhookHandler.d.ts +0 -0
  36. package/lib/firebase/config/constants.d.ts +0 -0
  37. package/lib/firebase/config/index.d.ts +0 -0
  38. package/lib/firebase/config/secrets.d.ts +0 -0
  39. package/lib/firebase/crud/aggregate.d.ts +0 -0
  40. package/lib/firebase/crud/create.d.ts +0 -0
  41. package/lib/firebase/crud/delete.d.ts +0 -0
  42. package/lib/firebase/crud/get.d.ts +0 -0
  43. package/lib/firebase/crud/index.d.ts +0 -0
  44. package/lib/firebase/crud/list.d.ts +0 -0
  45. package/lib/firebase/crud/update.d.ts +0 -0
  46. package/lib/firebase/helpers/githubAccessHelper.d.ts +0 -0
  47. package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +0 -0
  48. package/lib/firebase/helpers/index.d.ts +0 -0
  49. package/lib/firebase/index.d.ts +0 -0
  50. package/lib/firebase/index.js +1 -1
  51. package/lib/firebase/index.js.map +2 -2
  52. package/lib/firebase/oauth/disconnect.d.ts +0 -0
  53. package/lib/firebase/oauth/exchangeToken.d.ts +0 -0
  54. package/lib/firebase/oauth/getConnections.d.ts +0 -0
  55. package/lib/firebase/oauth/githubAccess.d.ts +0 -0
  56. package/lib/firebase/oauth/index.d.ts +0 -0
  57. package/lib/firebase/oauth/refreshToken.d.ts +0 -0
  58. package/lib/firebase/registerCrudFunctions.d.ts +0 -0
  59. package/lib/firebase/scheduled/checkExpiredSubscriptions.d.ts +0 -0
  60. package/lib/firebase/scheduled/index.d.ts +0 -0
  61. package/lib/shared/ai/classifyAIError.d.ts +0 -0
  62. package/lib/shared/ai/costTracker.d.ts +0 -0
  63. package/lib/shared/ai/createAIRoute.d.ts +0 -0
  64. package/lib/shared/ai/index.d.ts +0 -0
  65. package/lib/shared/ai/resolveModelTier.d.ts +0 -0
  66. package/lib/shared/billing/createCheckout.d.ts +0 -0
  67. package/lib/shared/billing/firestoreIdempotency.d.ts +13 -0
  68. package/lib/shared/billing/helpers/index.d.ts +0 -0
  69. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +0 -0
  70. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +0 -0
  71. package/lib/shared/billing/idempotency.d.ts +1 -12
  72. package/lib/shared/billing/index.d.ts +0 -0
  73. package/lib/shared/billing/stripeClient.d.ts +45 -0
  74. package/lib/shared/billing/webhookHandler.d.ts +5 -4
  75. package/lib/shared/email/createEmailRoute.d.ts +0 -0
  76. package/lib/shared/email/index.d.ts +0 -0
  77. package/lib/shared/email/provider.d.ts +0 -0
  78. package/lib/shared/email/resendProvider.d.ts +0 -0
  79. package/lib/shared/errorHandling.d.ts +0 -0
  80. package/lib/shared/firebase.d.ts +0 -0
  81. package/lib/shared/github.d.ts +0 -0
  82. package/lib/shared/index.d.ts +0 -0
  83. package/lib/shared/index.js +1 -1
  84. package/lib/shared/index.js.map +0 -0
  85. package/lib/shared/logger.d.ts +0 -0
  86. package/lib/shared/metadata.d.ts +0 -0
  87. package/lib/shared/oauth/exchangeToken.d.ts +0 -0
  88. package/lib/shared/oauth/grantAccess.d.ts +0 -0
  89. package/lib/shared/oauth/index.d.ts +0 -0
  90. package/lib/shared/schema.d.ts +0 -0
  91. package/lib/shared/utils/detectFirestore.d.ts +0 -0
  92. package/lib/shared/utils/external/date.d.ts +0 -0
  93. package/lib/shared/utils/external/index.d.ts +0 -0
  94. package/lib/shared/utils/external/references.d.ts +0 -0
  95. package/lib/shared/utils/external/subscription.d.ts +0 -0
  96. package/lib/shared/utils/firebaseHelpers.d.ts +0 -0
  97. package/lib/shared/utils/functionWrapper.d.ts +0 -0
  98. package/lib/shared/utils/index.d.ts +0 -0
  99. package/lib/shared/utils/internal/auth.d.ts +0 -0
  100. package/lib/shared/utils/internal/firebase.d.ts +0 -0
  101. package/lib/shared/utils/internal/idempotency.d.ts +0 -0
  102. package/lib/shared/utils/internal/index.d.ts +0 -0
  103. package/lib/shared/utils/internal/monitoring.d.ts +0 -0
  104. package/lib/shared/utils/internal/rateLimiter.d.ts +0 -0
  105. package/lib/shared/utils/internal/validation.d.ts +0 -8
  106. package/lib/shared/utils/schemaValidation.d.ts +0 -0
  107. package/lib/shared/utils/validation.d.ts +0 -0
  108. package/lib/shared/utils/vercelHelpers.d.ts +0 -0
  109. package/lib/shared/utils.d.ts +0 -43
  110. package/lib/shared/validation.d.ts +0 -0
  111. package/lib/supabase/ai/createAIFunction.d.ts +0 -0
  112. package/lib/supabase/auth/deleteAccount.d.ts +0 -0
  113. package/lib/supabase/auth/getCustomClaims.d.ts +0 -0
  114. package/lib/supabase/auth/getUserAuthStatus.d.ts +0 -0
  115. package/lib/supabase/auth/removeCustomClaims.d.ts +0 -0
  116. package/lib/supabase/auth/setCustomClaims.d.ts +0 -0
  117. package/lib/supabase/baseFunction.d.ts +0 -0
  118. package/lib/supabase/billing/cancelSubscription.d.ts +0 -0
  119. package/lib/supabase/billing/changePlan.d.ts +0 -0
  120. package/lib/supabase/billing/createCheckoutSession.d.ts +0 -0
  121. package/lib/supabase/billing/createCustomerPortal.d.ts +0 -0
  122. package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +0 -0
  123. package/lib/supabase/crud/aggregate.d.ts +0 -0
  124. package/lib/supabase/crud/create.d.ts +0 -0
  125. package/lib/supabase/crud/delete.d.ts +0 -0
  126. package/lib/supabase/crud/get.d.ts +0 -0
  127. package/lib/supabase/crud/index.d.ts +0 -0
  128. package/lib/supabase/crud/list.d.ts +0 -8
  129. package/lib/supabase/crud/update.d.ts +0 -0
  130. package/lib/supabase/edgeFunction.d.ts +0 -0
  131. package/lib/supabase/email/createEmailFunction.d.ts +0 -0
  132. package/lib/supabase/helpers/authProvider.d.ts +0 -0
  133. package/lib/supabase/index.d.ts +3 -2
  134. package/lib/supabase/index.js +1 -1
  135. package/lib/supabase/index.js.map +3 -3
  136. package/lib/supabase/oauth/disconnect.d.ts +0 -0
  137. package/lib/supabase/oauth/exchangeToken.d.ts +0 -0
  138. package/lib/supabase/oauth/getConnections.d.ts +0 -0
  139. package/lib/supabase/oauth/index.d.ts +0 -0
  140. package/lib/supabase/oauth/refreshToken.d.ts +0 -0
  141. package/lib/supabase/registerCrudFunctions.d.ts +0 -0
  142. package/lib/supabase/utils/idempotency.d.ts +0 -0
  143. package/lib/supabase/utils/monitoring.d.ts +0 -0
  144. package/lib/supabase/utils/rateLimiter.d.ts +0 -0
  145. package/lib/vercel/api/ai/chat.d.ts +0 -0
  146. package/lib/vercel/api/ai/index.d.ts +0 -0
  147. package/lib/vercel/api/auth/get-custom-claims.d.ts +0 -0
  148. package/lib/vercel/api/auth/get-user-auth-status.d.ts +0 -0
  149. package/lib/vercel/api/auth/index.d.ts +0 -0
  150. package/lib/vercel/api/auth/remove-custom-claims.d.ts +0 -0
  151. package/lib/vercel/api/auth/set-custom-claims.d.ts +0 -0
  152. package/lib/vercel/api/billing/cancel.d.ts +0 -0
  153. package/lib/vercel/api/billing/change-plan.d.ts +0 -0
  154. package/lib/vercel/api/billing/create-checkout-session.d.ts +0 -0
  155. package/lib/vercel/api/billing/customer-portal.d.ts +0 -0
  156. package/lib/vercel/api/billing/index.d.ts +0 -0
  157. package/lib/vercel/api/billing/refresh-subscription-status.d.ts +0 -0
  158. package/lib/vercel/api/billing/webhook-handler.d.ts +0 -0
  159. package/lib/vercel/api/config/constants.d.ts +0 -0
  160. package/lib/vercel/api/config/firebase-admin.d.ts +0 -0
  161. package/lib/vercel/api/config/index.d.ts +0 -0
  162. package/lib/vercel/api/crud/create.d.ts +0 -0
  163. package/lib/vercel/api/crud/delete.d.ts +0 -0
  164. package/lib/vercel/api/crud/get.d.ts +0 -0
  165. package/lib/vercel/api/crud/index.d.ts +0 -0
  166. package/lib/vercel/api/crud/list.d.ts +0 -0
  167. package/lib/vercel/api/crud/update.d.ts +0 -0
  168. package/lib/vercel/api/index.d.ts +0 -0
  169. package/lib/vercel/api/index.js +1 -1
  170. package/lib/vercel/api/index.js.map +2 -2
  171. package/lib/vercel/api/oauth/check-github-access.d.ts +0 -0
  172. package/lib/vercel/api/oauth/exchange-token.d.ts +0 -0
  173. package/lib/vercel/api/oauth/grant-github-access.d.ts +0 -0
  174. package/lib/vercel/api/oauth/index.d.ts +0 -0
  175. package/lib/vercel/api/oauth/revoke-github-access.d.ts +0 -0
  176. package/lib/vercel/api/utils/cors.d.ts +0 -0
  177. package/lib/vercel/baseFunction.d.ts +0 -0
  178. package/package.json +2 -2
  179. package/src/firebase/billing/cancelSubscription.ts +1 -1
  180. package/src/firebase/billing/changePlan.ts +1 -5
  181. package/src/firebase/billing/createCheckoutSession.ts +1 -5
  182. package/src/firebase/billing/createCustomerPortal.ts +1 -1
  183. package/src/firebase/billing/healthCheck.ts +1 -1
  184. package/src/firebase/billing/refreshSubscriptionStatus.ts +1 -1
  185. package/src/firebase/billing/webhookHandler.ts +2 -2
  186. package/src/shared/__tests__/internalValidation.test.ts +1 -40
  187. package/src/shared/__tests__/logger.test.ts +31 -0
  188. package/src/shared/__tests__/utils.test.ts +1 -1
  189. package/src/shared/billing/__tests__/webhookHandler.test.ts +1 -38
  190. package/src/shared/billing/firestoreIdempotency.ts +189 -0
  191. package/src/shared/billing/helpers/subscriptionManagement.ts +1 -1
  192. package/src/shared/billing/idempotency.ts +5 -172
  193. package/src/shared/billing/stripeClient.ts +91 -0
  194. package/src/shared/billing/webhookHandler.ts +5 -5
  195. package/src/shared/logger.ts +4 -6
  196. package/src/shared/utils/internal/validation.ts +0 -18
  197. package/src/shared/utils.ts +0 -77
  198. package/src/supabase/billing/cancelSubscription.ts +1 -1
  199. package/src/supabase/billing/changePlan.ts +1 -1
  200. package/src/supabase/billing/createCheckoutSession.ts +1 -5
  201. package/src/supabase/billing/createCustomerPortal.ts +1 -1
  202. package/src/supabase/billing/refreshSubscriptionStatus.ts +1 -5
  203. package/src/supabase/billing/stripeWebhook.ts +2 -2
  204. package/src/supabase/crud/list.ts +2 -0
  205. package/src/supabase/index.ts +3 -3
  206. package/src/vercel/api/billing/change-plan.ts +1 -1
  207. package/src/vercel/api/billing/create-checkout-session.ts +1 -5
  208. package/src/vercel/api/billing/customer-portal.ts +1 -1
  209. package/src/vercel/api/billing/refresh-subscription-status.ts +1 -1
  210. package/src/vercel/api/billing/webhook-handler.ts +1 -1
  211. package/lib/chunks/chunk-2JL3GDTO.js +0 -151
  212. package/lib/chunks/chunk-2JL3GDTO.js.map +0 -7
  213. package/lib/chunks/chunk-4TVLH2W2.js +0 -22
  214. package/lib/chunks/chunk-6CQXHNVL.js +0 -22
  215. package/lib/chunks/chunk-6CQXHNVL.js.map +0 -7
  216. package/lib/chunks/chunk-6DSCPZC6.js +0 -22
  217. package/lib/chunks/chunk-6DSCPZC6.js.map +0 -7
  218. package/lib/chunks/chunk-7E6TGWHU.js +0 -22
  219. package/lib/chunks/chunk-7E6TGWHU.js.map +0 -7
  220. package/lib/chunks/chunk-7LT32OWE.js +0 -22
  221. package/lib/chunks/chunk-7VH2GJXT.js +0 -151
  222. package/lib/chunks/chunk-7VH2GJXT.js.map +0 -7
  223. package/lib/chunks/chunk-API5A4BV.js +0 -22
  224. package/lib/chunks/chunk-API5A4BV.js.map +0 -7
  225. package/lib/chunks/chunk-BUP7SXPV.js +0 -23
  226. package/lib/chunks/chunk-BXKRI3JJ.js +0 -22
  227. package/lib/chunks/chunk-BXKRI3JJ.js.map +0 -7
  228. package/lib/chunks/chunk-FSLGZD7A.js +0 -21
  229. package/lib/chunks/chunk-GVLSPWDD.js +0 -151
  230. package/lib/chunks/chunk-GVLSPWDD.js.map +0 -7
  231. package/lib/chunks/chunk-GXQVWEFT.js +0 -22
  232. package/lib/chunks/chunk-GXQVWEFT.js.map +0 -7
  233. package/lib/chunks/chunk-HB7EGXVI.js +0 -22
  234. package/lib/chunks/chunk-HB7EGXVI.js.map +0 -7
  235. package/lib/chunks/chunk-HM7XCMWW.js +0 -22
  236. package/lib/chunks/chunk-HM7XCMWW.js.map +0 -7
  237. package/lib/chunks/chunk-I7IOIL6U.js +0 -151
  238. package/lib/chunks/chunk-I7IOIL6U.js.map +0 -7
  239. package/lib/chunks/chunk-IFOYVSPU.js.map +0 -7
  240. package/lib/chunks/chunk-JTAGPPPL.js.map +0 -7
  241. package/lib/chunks/chunk-MZ232FUE.js +0 -22
  242. package/lib/chunks/chunk-MZ232FUE.js.map +0 -7
  243. package/lib/chunks/chunk-NE5ZTUUZ.js +0 -22
  244. package/lib/chunks/chunk-NE5ZTUUZ.js.map +0 -7
  245. package/lib/chunks/chunk-NP2AN2TV.js +0 -22
  246. package/lib/chunks/chunk-NP2AN2TV.js.map +0 -7
  247. package/lib/chunks/chunk-RM7DV6IQ.js.map +0 -7
  248. package/lib/chunks/chunk-RQZGIZHD.js +0 -151
  249. package/lib/chunks/chunk-RQZGIZHD.js.map +0 -7
  250. package/lib/chunks/chunk-TBEDQLOB.js +0 -23
  251. package/lib/chunks/chunk-TBEDQLOB.js.map +0 -7
  252. package/lib/chunks/chunk-TMHBP3HB.js +0 -22
  253. package/lib/chunks/chunk-TMHBP3HB.js.map +0 -7
  254. package/lib/chunks/chunk-UH4L3EF3.js +0 -151
  255. package/lib/chunks/chunk-UJBIU6TL.js +0 -22
  256. package/lib/chunks/chunk-UJBIU6TL.js.map +0 -7
  257. package/lib/chunks/chunk-VKEYW3NT.js +0 -22
  258. package/lib/chunks/chunk-VKEYW3NT.js.map +0 -7
  259. package/lib/chunks/chunk-XGXBMXJ6.js +0 -22
  260. package/lib/chunks/chunk-XGXBMXJ6.js.map +0 -7
  261. package/lib/chunks/chunk-Y44NEQQG.js +0 -22
  262. package/lib/chunks/chunk-Y44NEQQG.js.map +0 -7
  263. package/lib/chunks/chunk-ZVU3KPXI.js +0 -22
  264. package/lib/chunks/chunk-ZVU3KPXI.js.map +0 -7
  265. package/lib/chunks/monitoring-PVQMFL34.js +0 -22
  266. package/lib/chunks/monitoring-V7FZXTTW.js +0 -22
  267. package/lib/chunks/monitoring-V7FZXTTW.js.map +0 -7
  268. package/lib/chunks/rateLimiter-6KO7AIZP.js.map +0 -7
  269. package/lib/chunks/rateLimiter-OXVBFW5C.js +0 -22
  270. package/lib/chunks/rateLimiter-OXVBFW5C.js.map +0 -7
  271. package/lib/chunks/rateLimiter-U45OMTWR.js +0 -22
  272. package/lib/chunks/rateLimiter-U45OMTWR.js.map +0 -7
  273. package/lib/chunks/server-32A5RH4C.js.map +0 -7
  274. package/lib/chunks/server-7HDAP5DL.js +0 -22
  275. package/lib/chunks/server-7HDAP5DL.js.map +0 -7
  276. package/lib/chunks/server-S2IMFOY7.js +0 -22
  277. package/lib/chunks/server-S2IMFOY7.js.map +0 -7
  278. package/lib/shared/ai/createAIHandler.d.ts +0 -39
  279. package/lib/shared/ai/providers/anthropic.d.ts +0 -12
  280. package/lib/shared/ai/providers/google.d.ts +0 -10
  281. package/lib/shared/ai/providers/index.d.ts +0 -23
  282. package/lib/shared/ai/providers/openai.d.ts +0 -10
  283. package/lib/shared/ai/utils/parseSSE.d.ts +0 -22
  284. /package/lib/chunks/{chunk-7LT32OWE.js.map → chunk-3F4BWKQD.js.map} +0 -0
  285. /package/lib/chunks/{chunk-4TVLH2W2.js.map → chunk-5IPULSUX.js.map} +0 -0
  286. /package/lib/chunks/{chunk-BUP7SXPV.js.map → chunk-CXBSROEW.js.map} +0 -0
  287. /package/lib/chunks/{chunk-4U7QQWYG.js.map → chunk-MQANUSY3.js.map} +0 -0
  288. /package/lib/chunks/{chunk-FSLGZD7A.js.map → monitoring-E7JBYBHQ.js.map} +0 -0
  289. /package/lib/chunks/{monitoring-AGCSU3FI.js.map → rateLimiter-SQISLOP5.js.map} +0 -0
  290. /package/lib/chunks/{monitoring-PVQMFL34.js.map → server-IQ5JNJOM.js.map} +0 -0
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/shared/utils.ts", "../../src/shared/billing/helpers/subscriptionManagement.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 Stripe from 'stripe';\nimport * as v from 'valibot';\n\nimport { DoNotDevError } from '@donotdev/core/server';\nimport type { OAuthPartnerId, UserRole } from '@donotdev/core/server';\n\nimport { STRIPE_API_VERSION_PIN } from './billing/apiVersion.js';\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// Lazy initialization of Stripe\nlet _stripe: Stripe | null = null;\n\n/**\n * Initialize Stripe explicitly (e.g. with a secret from defineSecret).\n * API version: `STRIPE_API_VERSION`, else {@link STRIPE_API_VERSION_PIN}.\n * @param apiKey - Stripe secret key\n *\n * @version 0.2.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function initStripe(apiKey: string) {\n if (!apiKey) throw new Error('Stripe API key is required');\n\n // Unset: the framework pin (pre-basil fields are still read by subscription handlers)\n const apiVersion = process.env.STRIPE_API_VERSION || STRIPE_API_VERSION_PIN;\n\n _stripe = new Stripe(apiKey, {\n apiVersion: apiVersion as any,\n });\n return _stripe;\n}\n\n/**\n * Get Stripe instance with lazy initialization\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function getStripe(): Stripe {\n if (!_stripe) {\n // Legacy/Vercel fallback: Try process.env\n const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;\n if (STRIPE_SECRET_KEY) {\n initStripe(STRIPE_SECRET_KEY);\n } else {\n throw new Error(\n 'Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.'\n );\n }\n }\n // We know _stripe is set here or we threw\n return _stripe!;\n}\n\n/**\n * Lazy-initialized Stripe instance proxy\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport const stripe = new Proxy({} as Stripe, {\n get(target, prop) {\n return getStripe()[prop as keyof Stripe];\n },\n});\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 * Validates that required Stripe environment variables are set\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateStripeEnvironment(): void {\n // Functions v2 automatically injects secrets as process.env when declared in config\n const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;\n if (!STRIPE_SECRET_KEY) {\n throw new Error('Missing STRIPE_SECRET_KEY environment variable');\n }\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", "// packages/functions/src/shared/billing/helpers/subscriptionManagement.ts\n\n/**\n * @fileoverview Shared Subscription Management Logic\n * @description Platform-agnostic subscription management functions\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport type Stripe from 'stripe';\n\nimport { SUBSCRIPTION_STATUS } from '@donotdev/core/server';\nimport type { BillingAuthProvider } from '@donotdev/core/server';\n\nimport { updateUserSubscription } from './updateUserSubscription.js';\nimport { handleError } from '../../errorHandling.js';\nimport { stripe, validateStripeEnvironment } from '../../utils.js';\n\n/**\n * Cancel user subscription at period end\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function cancelUserSubscription(\n userId: string,\n authProvider: BillingAuthProvider\n): Promise<{ success: boolean; endsAt: string }> {\n validateStripeEnvironment();\n\n // Get user's current subscription\n const user = await authProvider.getUser(userId);\n const currentClaims = user.customClaims || {};\n const subscription = currentClaims.subscription as\n | { subscriptionId?: string; tier?: string }\n | undefined;\n const subscriptionId = subscription?.subscriptionId;\n\n if (!subscriptionId) {\n throw handleError(new Error('No active subscription found'));\n }\n\n // Cancel at period end (don't delete immediately)\n const updatedSubscription = (await stripe.subscriptions.update(\n subscriptionId,\n {\n cancel_at_period_end: true,\n }\n )) as Stripe.Subscription;\n\n // Filter status to valid SubscriptionStatus values\n const validStatuses = [\n 'active',\n 'canceled',\n 'past_due',\n 'trialing',\n 'incomplete',\n ] as const;\n const status = validStatuses.includes(updatedSubscription.status as any)\n ? (updatedSubscription.status as (typeof validStatuses)[number])\n : 'incomplete';\n\n // Update Firebase Auth claims\n await updateUserSubscription(\n userId,\n {\n tier: subscription?.tier || 'free',\n status,\n subscriptionEnd: new Date(\n (updatedSubscription as any).current_period_end * 1000\n ).toISOString(),\n cancelAtPeriodEnd: true,\n subscriptionId: updatedSubscription.id,\n customerId: updatedSubscription.customer as string,\n },\n authProvider\n );\n\n return {\n success: true,\n endsAt: new Date(\n (updatedSubscription as any).current_period_end * 1000\n ).toISOString(),\n };\n}\n\n/**\n * Change user subscription plan\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function changeUserPlan(\n userId: string,\n newPriceId: string,\n billingConfigKey: string,\n billingConfig: Record<string, any>,\n authProvider: BillingAuthProvider\n): Promise<{ success: boolean; newTier: string; newPrice: number }> {\n validateStripeEnvironment();\n\n // Validate new plan exists in config\n const billingItem = billingConfig[billingConfigKey];\n if (!billingItem || billingItem.type !== 'StripeSubscription') {\n throw handleError(new Error('Invalid plan'));\n }\n\n // Validate price ID matches config\n if (billingItem.priceId !== newPriceId) {\n throw handleError(new Error('Price ID mismatch with configuration'));\n }\n\n // Get current subscription\n const user = await authProvider.getUser(userId);\n const currentClaims = user.customClaims || {};\n const subscription = currentClaims.subscription as\n | { subscriptionId?: string }\n | undefined;\n const subscriptionId = subscription?.subscriptionId;\n\n if (!subscriptionId) {\n throw handleError(new Error('No active subscription found'));\n }\n\n // Get current subscription from Stripe\n const currentSubscription = (await stripe.subscriptions.retrieve(\n subscriptionId\n )) as Stripe.Subscription;\n\n // Update subscription in Stripe\n const updatedSubscription = (await stripe.subscriptions.update(\n subscriptionId,\n {\n items: [\n {\n id: currentSubscription.items.data[0]?.id,\n price: newPriceId,\n },\n ],\n proration_behavior: 'create_prorations', // Pro-rate the change\n }\n )) as Stripe.Subscription;\n\n // Filter status to valid SubscriptionStatus values\n const validStatuses = [\n 'active',\n 'canceled',\n 'past_due',\n 'trialing',\n 'incomplete',\n ] as const;\n const status = validStatuses.includes(updatedSubscription.status as any)\n ? (updatedSubscription.status as (typeof validStatuses)[number])\n : 'incomplete';\n\n // Update Firebase Auth claims\n await updateUserSubscription(\n userId,\n {\n tier: billingItem.tier,\n status,\n subscriptionEnd: new Date(\n (updatedSubscription as any).current_period_end * 1000\n ).toISOString(),\n cancelAtPeriodEnd: (updatedSubscription as any).cancel_at_period_end,\n subscriptionId: updatedSubscription.id,\n customerId: updatedSubscription.customer as string,\n },\n authProvider\n );\n\n return {\n success: true,\n newTier: billingItem.tier,\n newPrice: billingItem.price,\n };\n}\n\n/**\n * Create Stripe Customer Portal session\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function createCustomerPortalSession(\n userId: string,\n authProvider: BillingAuthProvider,\n returnUrl?: string\n): Promise<{ url: string }> {\n validateStripeEnvironment();\n\n // Get customer ID from user claims\n const user = await authProvider.getUser(userId);\n const currentClaims = user.customClaims || {};\n const subscription = currentClaims.subscription as\n | { customerId?: string }\n | undefined;\n const customerId = subscription?.customerId;\n\n if (!customerId) {\n throw handleError(new Error('No customer found'));\n }\n\n // Validate returnUrl domain\n if (returnUrl) {\n const parsed = new URL(returnUrl);\n const frontendUrl = new URL(process.env.FRONTEND_URL || '');\n if (parsed.origin !== frontendUrl.origin) {\n throw new Error('Invalid return URL: must match frontend domain');\n }\n }\n\n // Create portal session\n const session = await stripe.billingPortal.sessions.create({\n customer: customerId,\n return_url: returnUrl || `${process.env.FRONTEND_URL}/billing`,\n });\n\n return {\n url: session.url,\n };\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;oJAWA,OAAOA,MAAY,SAgBnB,IAAIC,EAAyB,KAWtB,SAASC,EAAWC,EAAgB,CACzC,GAAI,CAACA,EAAQ,MAAM,IAAI,MAAM,4BAA4B,EAGzD,IAAMC,EAAa,QAAQ,IAAI,oBAAsBC,EAErD,OAAAJ,EAAU,IAAIK,EAAOH,EAAQ,CAC3B,WAAYC,CACd,CAAC,EACMH,CACT,CAVgBM,EAAAL,EAAA,cAmBT,SAASM,GAAoB,CAClC,GAAI,CAACP,EAAS,CAEZ,IAAMQ,EAAoB,QAAQ,IAAI,kBACtC,GAAIA,EACFP,EAAWO,CAAiB,MAE5B,OAAM,IAAI,MACR,6EACF,CAEJ,CAEA,OAAOR,CACT,CAdgBM,EAAAC,EAAA,aAuBT,IAAME,EAAS,IAAI,MAAM,CAAC,EAAa,CAC5C,IAAIC,EAAQC,EAAM,CAChB,OAAOJ,EAAU,EAAEI,CAAoB,CACzC,CACF,CAAC,EAgBM,SAASC,EAAoBC,EAAmB,CACrD,IAAMC,EAAMD,GAAM,IAClB,GAAI,CAACC,EACH,MAAM,IAAI,MAAM,4BAA4B,EAE9C,OAAOF,EAA4BE,CAAG,CACxC,CANgBR,EAAAM,EAAA,uBAwBT,SAASG,EAAYF,EAAqB,CAC/C,GAAI,CAACA,GAAM,IAAK,MAAO,QAGvB,IAAMG,EAAOH,EAAK,OAAO,KACzB,OAAIG,IAAS,QAAgB,QACzBA,IAAS,QAAgB,QAGzBH,EAAK,OAAO,QAAgB,QAC5BA,EAAK,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EAAoB,MAAM,KAAK,CAAC,GAAG,GACvC,MAAOJ,CACT,CACF,EACA,mBAAoB,mBACtB,CACF,EAUMJ,EAPgB,CACpB,SACA,WACA,WACA,WACA,YACF,EAC6B,SAASF,EAAoB,MAAa,EAClEA,EAAoB,OACrB,aAGJ,aAAMG,EACJT,EACA,CACE,KAAMe,EAAY,KAClB,OAAAP,EACA,gBAAiB,IAAI,KAClBF,EAA4B,mBAAqB,GACpD,EAAE,YAAY,EACd,kBAAoBA,EAA4B,qBAChD,eAAgBA,EAAoB,GACpC,WAAYA,EAAoB,QAClC,EACAL,CACF,EAEO,CACL,QAAS,GACT,QAASc,EAAY,KACrB,SAAUA,EAAY,KACxB,CACF,CApFsBL,EAAAC,EAAA,kBA6FtB,eAAsBM,EACpBjB,EACAC,EACAiB,EAC0B,CAC1BhB,EAA0B,EAQ1B,IAAMiB,IALO,MAAMlB,EAAa,QAAQD,CAAM,GACnB,cAAgB,CAAC,GACT,cAGF,WAEjC,GAAI,CAACmB,EACH,MAAMd,EAAY,IAAI,MAAM,mBAAmB,CAAC,EAIlD,GAAIa,EAAW,CACb,IAAME,EAAS,IAAI,IAAIF,CAAS,EAC1BG,EAAc,IAAI,IAAI,QAAQ,IAAI,cAAgB,EAAE,EAC1D,GAAID,EAAO,SAAWC,EAAY,OAChC,MAAM,IAAI,MAAM,gDAAgD,CAEpE,CAQA,MAAO,CACL,KANc,MAAMd,EAAO,cAAc,SAAS,OAAO,CACzD,SAAUY,EACV,WAAYD,GAAa,GAAG,QAAQ,IAAI,YAAY,UACtD,CAAC,GAGc,GACf,CACF,CArCsBR,EAAAO,EAAA",
6
- "names": ["Stripe", "_stripe", "initStripe", "apiKey", "apiVersion", "STRIPE_API_VERSION_PIN", "Stripe", "__name", "getStripe", "STRIPE_SECRET_KEY", "stripe", "target", "prop", "assertAuthenticated", "auth", "uid", "getUserRole", "role", "validateStripeEnvironment", "validateDocument", "data", "schema", "parse", "error", "messages", "issue", "p", "DoNotDevError", "__name", "findReferences", "collection", "docId", "referenceMetadata", "references", "getFirebaseAdminFirestore", "db", "ref", "snapshot", "__name", "cancelUserSubscription", "userId", "authProvider", "validateStripeEnvironment", "subscription", "subscriptionId", "handleError", "updatedSubscription", "stripe", "status", "updateUserSubscription", "__name", "changeUserPlan", "newPriceId", "billingConfigKey", "billingConfig", "billingItem", "currentSubscription", "createCustomerPortalSession", "returnUrl", "customerId", "parsed", "frontendUrl"]
7
- }
@@ -1,22 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module';
2
- import { fileURLToPath } from 'node:url';
3
- import { dirname } from 'node:path';
4
- import { Buffer } from 'node:buffer';
5
- import process from 'node:process';
6
-
7
- const require = __createRequire(import.meta.url);
8
- const __filename = fileURLToPath(import.meta.url);
9
- const __dirname = dirname(__filename);
10
-
11
- if (typeof globalThis !== 'undefined') {
12
- globalThis.require = require;
13
- globalThis.__filename = __filename;
14
- globalThis.__dirname = __dirname;
15
- globalThis.Buffer = Buffer;
16
- globalThis.process = process;
17
- if (typeof global === 'undefined') {
18
- globalThis.global = globalThis;
19
- }
20
- }
21
- import{a as l}from"./chunk-NP2AN2TV.js";import{a as o}from"./chunk-AYY7UXNI.js";async function u(){let{getFirebaseAdminFirestore:i}=await import("./server-S2IMFOY7.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-ZVU3KPXI.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/shared/utils/internal/rateLimiter.ts"],
4
- "sourcesContent": ["// packages/functions/src/shared/utils/internal/rateLimiter.ts\n\n/**\n * @fileoverview Server-side rate limiting utilities\n * @description Rate limiting implementation for Firebase Functions and Vercel\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport type {\n ServerRateLimitConfig as RateLimitConfig,\n ServerRateLimitResult as RateLimitResult,\n} from '@donotdev/core';\n\nimport { logger } from '../../logger.js';\n\nexport type { RateLimitConfig, RateLimitResult };\n\ninterface RateLimitEntry {\n attempts: number;\n windowStart: number;\n blockUntil: number | null;\n}\n\n/**\n * Firestore, loaded on first use. `firebase-admin` is an optional peer:\n * Supabase deployments never load it.\n */\nasync function getFirestore() {\n const { getFirebaseAdminFirestore } =\n await import('@donotdev/firebase/server');\n return getFirebaseAdminFirestore();\n}\n\n// In-memory storage for rate limiting (in production, use Redis or Firestore)\nconst rateLimitStore = new Map<string, RateLimitEntry>();\n\n/**\n * Check rate limit for a given key using in-memory storage\n * For production, this should be replaced with Redis or Firestore\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function checkRateLimit(\n key: string,\n config: RateLimitConfig\n): Promise<RateLimitResult> {\n const now = Date.now();\n const entry = rateLimitStore.get(key);\n\n // Check if currently blocked\n if (entry?.blockUntil && now < entry.blockUntil) {\n return {\n allowed: false,\n remaining: 0,\n resetAt: new Date(entry.blockUntil),\n blockRemainingSeconds: Math.ceil((entry.blockUntil - now) / 1000),\n };\n }\n\n // Clean up expired entries\n if (entry && now >= entry.windowStart + config.windowMs) {\n rateLimitStore.delete(key);\n }\n\n const currentEntry = rateLimitStore.get(key) || {\n attempts: 0,\n windowStart: now,\n blockUntil: null,\n };\n\n // Check if limit exceeded\n if (currentEntry.attempts >= config.maxAttempts) {\n // Apply block\n currentEntry.blockUntil = now + config.blockDurationMs;\n rateLimitStore.set(key, currentEntry);\n\n logger.warn('Rate limit exceeded', {\n key,\n attempts: currentEntry.attempts,\n blockUntil: new Date(currentEntry.blockUntil),\n });\n\n return {\n allowed: false,\n remaining: 0,\n resetAt: new Date(currentEntry.blockUntil),\n blockRemainingSeconds: Math.ceil(config.blockDurationMs / 1000),\n };\n }\n\n // Record attempt\n currentEntry.attempts += 1;\n rateLimitStore.set(key, currentEntry);\n\n return {\n allowed: true,\n remaining: config.maxAttempts - currentEntry.attempts,\n resetAt: new Date(currentEntry.windowStart + config.windowMs),\n blockRemainingSeconds: null,\n };\n}\n\n/**\n * Check rate limit using Firestore for persistent storage.\n * This is the recommended approach for production.\n *\n * **Architecture decision \u2014 Firestore transaction for rate limiting:**\n * The read-modify-write cycle is wrapped in a Firestore transaction to\n * eliminate TOCTOU races. While transactions add some latency, rate limiting\n * is a best-effort abuse-prevention mechanism, not a hard security boundary.\n * The window-based approach (maxAttempts per windowMs) tolerates minor\n * timing variations. If transaction contention becomes an issue under extreme\n * load, the catch block fails open (allows the request) to avoid blocking\n * legitimate traffic \u2014 this is an intentional trade-off favoring availability\n * over strict enforcement.\n *\n * For stricter rate limiting (e.g. payment endpoints), consumers can use\n * Redis-backed rate limiters or API gateway-level throttling.\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function checkRateLimitWithFirestore(\n key: string,\n config: RateLimitConfig\n): Promise<RateLimitResult> {\n const db = await getFirestore();\n const rateLimitRef = db.collection('rateLimits').doc(key);\n\n try {\n const now = Date.now();\n\n // W2: Wrap the entire read-modify-write in a Firestore transaction to\n // eliminate the TOCTOU race where two concurrent requests both read the\n // same counter and both increment it independently.\n let result: RateLimitResult = {\n allowed: true,\n remaining: config.maxAttempts - 1,\n resetAt: new Date(now + config.windowMs),\n blockRemainingSeconds: null,\n };\n\n await db.runTransaction(async (tx) => {\n const doc = await tx.get(rateLimitRef);\n\n if (!doc.exists) {\n tx.set(rateLimitRef, {\n attempts: 1,\n windowStart: now,\n blockUntil: null,\n lastUpdated: now,\n });\n result = {\n allowed: true,\n remaining: config.maxAttempts - 1,\n resetAt: new Date(now + config.windowMs),\n blockRemainingSeconds: null,\n };\n return;\n }\n\n const data = doc.data() as RateLimitEntry & { lastUpdated: number };\n\n // Check if currently blocked\n if (data.blockUntil && now < data.blockUntil) {\n result = {\n allowed: false,\n remaining: 0,\n resetAt: new Date(data.blockUntil),\n blockRemainingSeconds: Math.ceil((data.blockUntil - now) / 1000),\n };\n return;\n }\n\n // Check if window expired \u2014 reset\n if (now >= data.windowStart + config.windowMs) {\n tx.set(rateLimitRef, {\n attempts: 1,\n windowStart: now,\n blockUntil: null,\n lastUpdated: now,\n });\n result = {\n allowed: true,\n remaining: config.maxAttempts - 1,\n resetAt: new Date(now + config.windowMs),\n blockRemainingSeconds: null,\n };\n return;\n }\n\n // Check if limit exceeded\n if (data.attempts >= config.maxAttempts) {\n const blockUntil = now + config.blockDurationMs;\n tx.update(rateLimitRef, { blockUntil, lastUpdated: now });\n\n logger.warn('Rate limit exceeded (Firestore)', {\n key,\n attempts: data.attempts,\n blockUntil: new Date(blockUntil),\n });\n\n result = {\n allowed: false,\n remaining: 0,\n resetAt: new Date(blockUntil),\n blockRemainingSeconds: Math.ceil(config.blockDurationMs / 1000),\n };\n return;\n }\n\n // Increment attempts\n tx.update(rateLimitRef, {\n attempts: data.attempts + 1,\n lastUpdated: now,\n });\n result = {\n allowed: true,\n remaining: config.maxAttempts - (data.attempts + 1),\n resetAt: new Date(data.windowStart + config.windowMs),\n blockRemainingSeconds: null,\n };\n });\n\n return result;\n } catch (error) {\n logger.error('Rate limit check failed', {\n key,\n error: error instanceof Error ? error.message : String(error),\n });\n // Fail closed \u2014 deny the request if rate limiting infrastructure fails.\n // Aligns with the Supabase implementation's fail-closed policy.\n // Availability trade-off: legitimate requests may be blocked during\n // Firestore outages, but this prevents abuse when enforcement is down.\n return {\n allowed: false,\n remaining: 0,\n resetAt: null,\n blockRemainingSeconds: null,\n };\n }\n}\n\n/**\n * Reset rate limit for a given key\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function resetRateLimit(key: string): void {\n rateLimitStore.delete(key);\n logger.info('Rate limit reset', { key });\n}\n\n/**\n * Reset rate limit in Firestore\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function resetRateLimitInFirestore(key: string): Promise<void> {\n const db = await getFirestore();\n const rateLimitRef = db.collection('rateLimits').doc(key);\n\n try {\n await rateLimitRef.delete();\n logger.info('Rate limit reset (Firestore)', { key });\n } catch (error) {\n logger.error('Failed to reset rate limit', {\n key,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\n/**\n * Get rate limit status without consuming an attempt\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function getRateLimitStatus(\n key: string,\n config: RateLimitConfig\n): RateLimitResult {\n const now = Date.now();\n const entry = rateLimitStore.get(key);\n\n if (!entry) {\n return {\n allowed: true,\n remaining: config.maxAttempts,\n resetAt: null,\n blockRemainingSeconds: null,\n };\n }\n\n // Check if currently blocked\n if (entry.blockUntil && now < entry.blockUntil) {\n return {\n allowed: false,\n remaining: 0,\n resetAt: new Date(entry.blockUntil),\n blockRemainingSeconds: Math.ceil((entry.blockUntil - now) / 1000),\n };\n }\n\n // Check if window expired\n if (now >= entry.windowStart + config.windowMs) {\n return {\n allowed: true,\n remaining: config.maxAttempts,\n resetAt: null,\n blockRemainingSeconds: null,\n };\n }\n\n return {\n allowed: entry.attempts < config.maxAttempts,\n remaining: Math.max(0, config.maxAttempts - entry.attempts),\n resetAt: new Date(entry.windowStart + config.windowMs),\n blockRemainingSeconds: null,\n };\n}\n\n/**\n * Default rate limit configurations for common operations\n */\nexport const DEFAULT_RATE_LIMITS = {\n checkout: {\n maxAttempts: 5,\n windowMs: 60 * 1000, // 1 minute\n blockDurationMs: 5 * 60 * 1000, // 5 minutes\n },\n webhook: {\n maxAttempts: 100,\n windowMs: 60 * 1000, // 1 minute\n blockDurationMs: 60 * 1000, // 1 minute\n },\n auth: {\n maxAttempts: 10,\n windowMs: 60 * 1000, // 1 minute\n blockDurationMs: 5 * 60 * 1000, // 5 minutes\n },\n api: {\n maxAttempts: 100,\n windowMs: 60 * 1000, // 1 minute\n blockDurationMs: 60 * 1000, // 1 minute\n },\n} as const;\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;gFA8BA,eAAeA,GAAe,CAC5B,GAAM,CAAE,0BAAAC,CAA0B,EAChC,KAAM,QAAO,sBAA2B,EAC1C,OAAOA,EAA0B,CACnC,CAJeC,EAAAF,EAAA,gBAOf,IAAMG,EAAiB,IAAI,IAU3B,eAAsBC,EACpBC,EACAC,EAC0B,CAC1B,IAAMC,EAAM,KAAK,IAAI,EACfC,EAAQL,EAAe,IAAIE,CAAG,EAGpC,GAAIG,GAAO,YAAcD,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AAS,IAAI,KAAKA,EAAM,YAAcF,EAAO,QAAQ,EACrD,sBAAuB,IACzB,EAjCS,CACL,QAAS,GACT,UAAWA,EAAO,YAClB,QAAS,KACT,sBAAuB,IACzB,CA6BJ,CA1CgBJ,EAAAoB,EAAA,sBA+CT,IAAMC,EAAsB,CACjC,SAAU,CACR,YAAa,EACb,SAAU,GAAK,IACf,gBAAiB,IAAS,GAC5B,EACA,QAAS,CACP,YAAa,IACb,SAAU,GAAK,IACf,gBAAiB,GAAK,GACxB,EACA,KAAM,CACJ,YAAa,GACb,SAAU,GAAK,IACf,gBAAiB,IAAS,GAC5B,EACA,IAAK,CACH,YAAa,IACb,SAAU,GAAK,IACf,gBAAiB,GAAK,GACxB,CACF",
6
- "names": ["getFirestore", "getFirebaseAdminFirestore", "__name", "rateLimitStore", "checkRateLimit", "key", "config", "now", "entry", "currentEntry", "logger", "checkRateLimitWithFirestore", "db", "rateLimitRef", "result", "tx", "doc", "data", "blockUntil", "error", "resetRateLimit", "resetRateLimitInFirestore", "getRateLimitStatus", "DEFAULT_RATE_LIMITS"]
7
- }
@@ -1,22 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module';
2
- import { fileURLToPath } from 'node:url';
3
- import { dirname } from 'node:path';
4
- import { Buffer } from 'node:buffer';
5
- import process from 'node:process';
6
-
7
- const require = __createRequire(import.meta.url);
8
- const __filename = fileURLToPath(import.meta.url);
9
- const __dirname = dirname(__filename);
10
-
11
- if (typeof globalThis !== 'undefined') {
12
- globalThis.require = require;
13
- globalThis.__filename = __filename;
14
- globalThis.__dirname = __dirname;
15
- globalThis.Buffer = Buffer;
16
- globalThis.process = process;
17
- if (typeof global === 'undefined') {
18
- globalThis.global = globalThis;
19
- }
20
- }
21
- import{a,b,c,d,e}from"./chunk-4TVLH2W2.js";import"./chunk-NP2AN2TV.js";import"./chunk-AYY7UXNI.js";export{b as checkPaymentFailureRate,c as checkPaymentVolume,e as cleanupOldMetrics,d as getPaymentMetricsSummary,a as recordPaymentMetrics};
22
- //# sourceMappingURL=monitoring-PVQMFL34.js.map
@@ -1,22 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module';
2
- import { fileURLToPath } from 'node:url';
3
- import { dirname } from 'node:path';
4
- import { Buffer } from 'node:buffer';
5
- import process from 'node:process';
6
-
7
- const require = __createRequire(import.meta.url);
8
- const __filename = fileURLToPath(import.meta.url);
9
- const __dirname = dirname(__filename);
10
-
11
- if (typeof globalThis !== 'undefined') {
12
- globalThis.require = require;
13
- globalThis.__filename = __filename;
14
- globalThis.__dirname = __dirname;
15
- globalThis.Buffer = Buffer;
16
- globalThis.process = process;
17
- if (typeof global === 'undefined') {
18
- globalThis.global = globalThis;
19
- }
20
- }
21
- import{a,b,c,d,e}from"./chunk-7E6TGWHU.js";import"./chunk-NP2AN2TV.js";import"./chunk-AYY7UXNI.js";export{b as checkPaymentFailureRate,c as checkPaymentVolume,e as cleanupOldMetrics,d as getPaymentMetricsSummary,a as recordPaymentMetrics};
22
- //# sourceMappingURL=monitoring-V7FZXTTW.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": [],
4
- "sourcesContent": [],
5
- "mappings": "",
6
- "names": []
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": [],
4
- "sourcesContent": [],
5
- "mappings": "",
6
- "names": []
7
- }
@@ -1,22 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module';
2
- import { fileURLToPath } from 'node:url';
3
- import { dirname } from 'node:path';
4
- import { Buffer } from 'node:buffer';
5
- import process from 'node:process';
6
-
7
- const require = __createRequire(import.meta.url);
8
- const __filename = fileURLToPath(import.meta.url);
9
- const __dirname = dirname(__filename);
10
-
11
- if (typeof globalThis !== 'undefined') {
12
- globalThis.require = require;
13
- globalThis.__filename = __filename;
14
- globalThis.__dirname = __dirname;
15
- globalThis.Buffer = Buffer;
16
- globalThis.process = process;
17
- if (typeof global === 'undefined') {
18
- globalThis.global = globalThis;
19
- }
20
- }
21
- import{a,b,c,d,e,f}from"./chunk-IFOYVSPU.js";import"./chunk-NP2AN2TV.js";import"./chunk-AYY7UXNI.js";export{f as DEFAULT_RATE_LIMITS,a as checkRateLimit,b as checkRateLimitWithFirestore,e as getRateLimitStatus,c as resetRateLimit,d as resetRateLimitInFirestore};
22
- //# sourceMappingURL=rateLimiter-OXVBFW5C.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": [],
4
- "sourcesContent": [],
5
- "mappings": "",
6
- "names": []
7
- }
@@ -1,22 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module';
2
- import { fileURLToPath } from 'node:url';
3
- import { dirname } from 'node:path';
4
- import { Buffer } from 'node:buffer';
5
- import process from 'node:process';
6
-
7
- const require = __createRequire(import.meta.url);
8
- const __filename = fileURLToPath(import.meta.url);
9
- const __dirname = dirname(__filename);
10
-
11
- if (typeof globalThis !== 'undefined') {
12
- globalThis.require = require;
13
- globalThis.__filename = __filename;
14
- globalThis.__dirname = __dirname;
15
- globalThis.Buffer = Buffer;
16
- globalThis.process = process;
17
- if (typeof global === 'undefined') {
18
- globalThis.global = globalThis;
19
- }
20
- }
21
- import{a,b,c,d,e,f}from"./chunk-ZVU3KPXI.js";import"./chunk-NP2AN2TV.js";import"./chunk-AYY7UXNI.js";export{f as DEFAULT_RATE_LIMITS,a as checkRateLimit,b as checkRateLimitWithFirestore,e as getRateLimitStatus,c as resetRateLimit,d as resetRateLimitInFirestore};
22
- //# sourceMappingURL=rateLimiter-U45OMTWR.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": [],
4
- "sourcesContent": [],
5
- "mappings": "",
6
- "names": []
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": [],
4
- "sourcesContent": [],
5
- "mappings": "",
6
- "names": []
7
- }
@@ -1,22 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module';
2
- import { fileURLToPath } from 'node:url';
3
- import { dirname } from 'node:path';
4
- import { Buffer } from 'node:buffer';
5
- import process from 'node:process';
6
-
7
- const require = __createRequire(import.meta.url);
8
- const __filename = fileURLToPath(import.meta.url);
9
- const __dirname = dirname(__filename);
10
-
11
- if (typeof globalThis !== 'undefined') {
12
- globalThis.require = require;
13
- globalThis.__filename = __filename;
14
- globalThis.__dirname = __dirname;
15
- globalThis.Buffer = Buffer;
16
- globalThis.process = process;
17
- if (typeof global === 'undefined') {
18
- globalThis.global = globalThis;
19
- }
20
- }
21
- import{A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-TBEDQLOB.js";import"./chunk-TMHBP3HB.js";import"./chunk-AYY7UXNI.js";export{M as FieldValue,f as FirebaseServerAuthAdapter,N as Query,O as Timestamp,s as batchCreate,u as batchDelete,t as batchUpdate,r as batchWrite,w as bulkGet,n as convertISOStringsToDates,H as createAdminFirestoreValidator,I as createFirestoreClientValidator,q as createFirestorePartialUpdate,G as createFirestoreValidator,j as createTimestamp,L as enhanceSchema,l as firestoreToISOString,i as generateServerId,x as getActiveSubscription,b as getFirebaseAdminApp,c as getFirebaseAdminAuth,d as getFirebaseAdminFirestore,e as getFirebaseAdminFunctions,g as getServerAdmin,h as getServerFirestore,E as getUniqueConstraintValidator,y as getUserSubscriptions,B as hasFeatureAccess,F as hasUniqueConstraintValidator,a as initFirebaseAdmin,m as isTimestamp,p as prepareForFirestore,D as registerUniqueConstraintValidator,v as runTransaction,z as saveSubscription,k as toTimestamp,o as transformFirestoreData,A as updateSubscriptionStatus,K as validateFirestoreDocument,J as validateUniqueness,C as verifyAndHandleStripeWebhook};
22
- //# sourceMappingURL=server-7HDAP5DL.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": [],
4
- "sourcesContent": [],
5
- "mappings": "",
6
- "names": []
7
- }
@@ -1,22 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module';
2
- import { fileURLToPath } from 'node:url';
3
- import { dirname } from 'node:path';
4
- import { Buffer } from 'node:buffer';
5
- import process from 'node:process';
6
-
7
- const require = __createRequire(import.meta.url);
8
- const __filename = fileURLToPath(import.meta.url);
9
- const __dirname = dirname(__filename);
10
-
11
- if (typeof globalThis !== 'undefined') {
12
- globalThis.require = require;
13
- globalThis.__filename = __filename;
14
- globalThis.__dirname = __dirname;
15
- globalThis.Buffer = Buffer;
16
- globalThis.process = process;
17
- if (typeof global === 'undefined') {
18
- globalThis.global = globalThis;
19
- }
20
- }
21
- import{A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-RM7DV6IQ.js";import"./chunk-6CQXHNVL.js";import"./chunk-AYY7UXNI.js";export{M as FieldValue,f as FirebaseServerAuthAdapter,N as Query,O as Timestamp,s as batchCreate,u as batchDelete,t as batchUpdate,r as batchWrite,w as bulkGet,n as convertISOStringsToDates,H as createAdminFirestoreValidator,I as createFirestoreClientValidator,q as createFirestorePartialUpdate,G as createFirestoreValidator,j as createTimestamp,L as enhanceSchema,l as firestoreToISOString,i as generateServerId,x as getActiveSubscription,b as getFirebaseAdminApp,c as getFirebaseAdminAuth,d as getFirebaseAdminFirestore,e as getFirebaseAdminFunctions,g as getServerAdmin,h as getServerFirestore,E as getUniqueConstraintValidator,y as getUserSubscriptions,B as hasFeatureAccess,F as hasUniqueConstraintValidator,a as initFirebaseAdmin,m as isTimestamp,p as prepareForFirestore,D as registerUniqueConstraintValidator,v as runTransaction,z as saveSubscription,k as toTimestamp,o as transformFirestoreData,A as updateSubscriptionStatus,K as validateFirestoreDocument,J as validateUniqueness,C as verifyAndHandleStripeWebhook};
22
- //# sourceMappingURL=server-S2IMFOY7.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": [],
4
- "sourcesContent": [],
5
- "mappings": "",
6
- "names": []
7
- }
@@ -1,39 +0,0 @@
1
- /**
2
- * @fileoverview AI Handler Algorithm
3
- * @description Platform-agnostic handler for AI chat requests.
4
- * Validates, rate limits (Upstash), dispatches to provider adapter.
5
- *
6
- * @version 0.2.0
7
- * @since 0.1.0
8
- * @author AMBROISE PARK Consulting
9
- */
10
- import type {
11
- AIChatRequest,
12
- AIChatResponse,
13
- AIProviderAdapter,
14
- AIRateLimitConfig,
15
- } from '@donotdev/core/server';
16
- /**
17
- * Handle an AI chat request (non-streaming).
18
- * Returns the full response as JSON.
19
- */
20
- export declare function handleAIChatRequest(
21
- request: AIChatRequest,
22
- adapter: AIProviderAdapter,
23
- options: {
24
- userId: string;
25
- rateLimitConfig?: AIRateLimitConfig;
26
- }
27
- ): Promise<AIChatResponse>;
28
- /**
29
- * Handle an AI chat request (streaming).
30
- * Returns an SSE Response for direct use in edge functions.
31
- */
32
- export declare function handleAIStreamRequest(
33
- request: AIChatRequest,
34
- adapter: AIProviderAdapter,
35
- options: {
36
- userId: string;
37
- rateLimitConfig?: AIRateLimitConfig;
38
- }
39
- ): Response;
@@ -1,12 +0,0 @@
1
- /**
2
- * @fileoverview Anthropic (Claude) Provider Adapter
3
- * @description fetch-based, no SDK. Normalizes to framework types.
4
- *
5
- * @version 0.1.0
6
- * @since 0.1.0
7
- * @author AMBROISE PARK Consulting
8
- */
9
- import type { AIProviderAdapter } from '@donotdev/core/server';
10
- export declare function createAnthropicAdapter(
11
- apiKey: string
12
- ): AIProviderAdapter;
@@ -1,10 +0,0 @@
1
- /**
2
- * @fileoverview Google (Gemini) Provider Adapter
3
- * @description fetch-based, no SDK. Normalizes to framework types.
4
- *
5
- * @version 0.1.0
6
- * @since 0.1.0
7
- * @author AMBROISE PARK Consulting
8
- */
9
- import type { AIProviderAdapter } from '@donotdev/core/server';
10
- export declare function createGoogleAdapter(apiKey: string): AIProviderAdapter;
@@ -1,23 +0,0 @@
1
- /**
2
- * @fileoverview AI Provider Factory
3
- * @description Creates the right adapter based on provider name.
4
- *
5
- * @version 0.1.0
6
- * @since 0.1.0
7
- * @author AMBROISE PARK Consulting
8
- */
9
- import type { AIProvider, AIProviderAdapter } from '@donotdev/core/server';
10
- /**
11
- * Get the provider adapter for the given provider name.
12
- *
13
- * @param provider - The AI provider ('anthropic', 'openai', 'google')
14
- * @param apiKey - The API key for the provider
15
- * @returns The provider adapter
16
- */
17
- export declare function getProviderAdapter(
18
- provider: AIProvider,
19
- apiKey: string
20
- ): AIProviderAdapter;
21
- export { createAnthropicAdapter } from './anthropic.js';
22
- export { createOpenAIAdapter } from './openai.js';
23
- export { createGoogleAdapter } from './google.js';
@@ -1,10 +0,0 @@
1
- /**
2
- * @fileoverview OpenAI (GPT) Provider Adapter
3
- * @description fetch-based, no SDK. Normalizes to framework types.
4
- *
5
- * @version 0.1.0
6
- * @since 0.1.0
7
- * @author AMBROISE PARK Consulting
8
- */
9
- import type { AIProviderAdapter } from '@donotdev/core/server';
10
- export declare function createOpenAIAdapter(apiKey: string): AIProviderAdapter;
@@ -1,22 +0,0 @@
1
- /**
2
- * @fileoverview Shared SSE Stream Parser
3
- * @description Extracts data lines from an SSE response body.
4
- * All provider adapters share the same reader loop - only event mapping differs.
5
- *
6
- * @version 0.1.0
7
- * @since 0.1.0
8
- * @author AMBROISE PARK Consulting
9
- */
10
- /**
11
- * Parse SSE data lines from a ReadableStream response body.
12
- * Yields each parsed JSON object from `data:` lines.
13
- * Skips `[DONE]` sentinel and malformed JSON.
14
- */
15
- export declare function parseSSEStream(
16
- body: ReadableStream<Uint8Array>
17
- ): AsyncGenerator<unknown>;
18
- /**
19
- * Strip sensitive query parameters from a URL string.
20
- * Used to prevent API key leakage in error messages.
21
- */
22
- export declare function sanitizeApiUrl(url: string): string;