@donotdev/functions 0.1.0 → 0.1.42

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 (348) hide show
  1. package/LICENSE.md +21 -242
  2. package/README.md +4 -4
  3. package/guidelines/FUNCTIONS.md +9 -0
  4. package/guidelines/VERCEL.md +286 -0
  5. package/lib/firebase/auth/getCustomClaims.d.ts +0 -0
  6. package/lib/firebase/auth/getUserAuthStatus.d.ts +0 -0
  7. package/lib/firebase/auth/index.d.ts +0 -0
  8. package/lib/firebase/auth/removeCustomClaims.d.ts +0 -0
  9. package/lib/firebase/auth/setCustomClaims.d.ts +0 -0
  10. package/lib/firebase/baseFunction.d.ts +0 -0
  11. package/lib/firebase/billing/cancelSubscription.d.ts +0 -0
  12. package/lib/firebase/billing/changePlan.d.ts +0 -0
  13. package/lib/firebase/billing/createCheckoutSession.d.ts +10 -13
  14. package/lib/firebase/billing/createCustomerPortal.d.ts +0 -0
  15. package/lib/firebase/billing/healthCheck.d.ts +0 -0
  16. package/lib/firebase/billing/index.d.ts +0 -0
  17. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -0
  18. package/lib/firebase/billing/webhookHandler.d.ts +0 -0
  19. package/lib/firebase/config/constants.d.ts +0 -0
  20. package/lib/firebase/config/index.d.ts +0 -0
  21. package/lib/firebase/config/secrets.d.ts +0 -0
  22. package/lib/firebase/crud/aggregate.d.ts +0 -0
  23. package/lib/firebase/crud/bulk.d.ts +107 -0
  24. package/lib/firebase/crud/create.d.ts +1 -1
  25. package/lib/firebase/crud/delete.d.ts +0 -0
  26. package/lib/firebase/crud/get.d.ts +0 -0
  27. package/lib/firebase/crud/index.d.ts +1 -0
  28. package/lib/firebase/crud/list.d.ts +0 -0
  29. package/lib/firebase/crud/update.d.ts +0 -0
  30. package/lib/firebase/helpers/githubAccessHelper.d.ts +0 -0
  31. package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +0 -0
  32. package/lib/firebase/helpers/index.d.ts +0 -0
  33. package/lib/firebase/index.d.ts +0 -0
  34. package/lib/firebase/index.js +3 -3
  35. package/lib/firebase/index.js.map +4 -4
  36. package/lib/firebase/oauth/disconnect.d.ts +0 -0
  37. package/lib/firebase/oauth/exchangeToken.d.ts +0 -0
  38. package/lib/firebase/oauth/getConnections.d.ts +0 -0
  39. package/lib/firebase/oauth/githubAccess.d.ts +0 -0
  40. package/lib/firebase/oauth/index.d.ts +0 -0
  41. package/lib/firebase/oauth/refreshToken.d.ts +0 -0
  42. package/lib/firebase/registerCrudFunctions.d.ts +0 -0
  43. package/lib/firebase/scheduled/checkExpiredSubscriptions.d.ts +0 -0
  44. package/lib/firebase/scheduled/index.d.ts +0 -0
  45. package/lib/shared/ai/classifyAIError.d.ts +35 -0
  46. package/lib/shared/ai/costTracker.d.ts +20 -0
  47. package/lib/shared/ai/createAIHandler.d.ts +39 -0
  48. package/lib/shared/ai/createAIRoute.d.ts +20 -0
  49. package/lib/shared/ai/index.d.ts +6 -0
  50. package/lib/shared/ai/providers/anthropic.d.ts +12 -0
  51. package/lib/shared/ai/providers/google.d.ts +10 -0
  52. package/lib/shared/ai/providers/index.d.ts +23 -0
  53. package/lib/shared/ai/providers/openai.d.ts +10 -0
  54. package/lib/shared/ai/resolveModelTier.d.ts +14 -0
  55. package/lib/shared/ai/utils/parseSSE.d.ts +22 -0
  56. package/lib/shared/billing/createCheckout.d.ts +8 -2
  57. package/lib/shared/billing/helpers/index.d.ts +0 -0
  58. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +0 -0
  59. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +0 -0
  60. package/lib/shared/billing/idempotency.d.ts +0 -0
  61. package/lib/shared/billing/index.d.ts +0 -0
  62. package/lib/shared/billing/webhookHandler.d.ts +0 -0
  63. package/lib/shared/crud/bulkCore.d.ts +211 -0
  64. package/lib/shared/crud/index.d.ts +13 -0
  65. package/lib/shared/email/createEmailRoute.d.ts +30 -0
  66. package/lib/shared/email/index.d.ts +3 -0
  67. package/lib/shared/email/provider.d.ts +30 -0
  68. package/lib/shared/email/resendProvider.d.ts +22 -0
  69. package/lib/shared/errorHandling.d.ts +0 -0
  70. package/lib/shared/firebase.d.ts +0 -0
  71. package/lib/shared/github.d.ts +5 -0
  72. package/lib/shared/index.d.ts +3 -0
  73. package/lib/shared/index.js +4 -3
  74. package/lib/shared/index.js.map +4 -4
  75. package/lib/shared/logger.d.ts +2 -0
  76. package/lib/shared/metadata.d.ts +6 -6
  77. package/lib/shared/oauth/exchangeToken.d.ts +1 -0
  78. package/lib/shared/oauth/grantAccess.d.ts +1 -0
  79. package/lib/shared/oauth/index.d.ts +0 -0
  80. package/lib/shared/schema.d.ts +0 -0
  81. package/lib/shared/utils/detectFirestore.d.ts +0 -0
  82. package/lib/shared/utils/external/date.d.ts +0 -0
  83. package/lib/shared/utils/external/index.d.ts +0 -0
  84. package/lib/shared/utils/external/references.d.ts +0 -0
  85. package/lib/shared/utils/external/subscription.d.ts +0 -0
  86. package/lib/shared/utils/firebaseHelpers.d.ts +0 -0
  87. package/lib/shared/utils/functionWrapper.d.ts +0 -0
  88. package/lib/shared/utils/index.d.ts +0 -0
  89. package/lib/shared/utils/internal/auth.d.ts +0 -0
  90. package/lib/shared/utils/internal/firebase.d.ts +0 -0
  91. package/lib/shared/utils/internal/idempotency.d.ts +1 -0
  92. package/lib/shared/utils/internal/index.d.ts +0 -0
  93. package/lib/shared/utils/internal/monitoring.d.ts +0 -0
  94. package/lib/shared/utils/internal/rateLimiter.d.ts +0 -0
  95. package/lib/shared/utils/internal/validation.d.ts +0 -0
  96. package/lib/shared/utils/schemaValidation.d.ts +0 -0
  97. package/lib/shared/utils/validation.d.ts +0 -0
  98. package/lib/shared/utils/vercelHelpers.d.ts +0 -0
  99. package/lib/shared/utils.d.ts +0 -0
  100. package/lib/shared/validation.d.ts +0 -0
  101. package/lib/supabase/ai/createAIFunction.d.ts +30 -0
  102. package/lib/supabase/auth/deleteAccount.d.ts +0 -0
  103. package/lib/supabase/auth/getCustomClaims.d.ts +0 -0
  104. package/lib/supabase/auth/getUserAuthStatus.d.ts +0 -0
  105. package/lib/supabase/auth/removeCustomClaims.d.ts +1 -1
  106. package/lib/supabase/auth/setCustomClaims.d.ts +12 -4
  107. package/lib/supabase/baseFunction.d.ts +0 -0
  108. package/lib/supabase/billing/cancelSubscription.d.ts +0 -0
  109. package/lib/supabase/billing/changePlan.d.ts +1 -1
  110. package/lib/supabase/billing/createCheckoutSession.d.ts +0 -0
  111. package/lib/supabase/billing/createCustomerPortal.d.ts +0 -0
  112. package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +0 -0
  113. package/lib/supabase/crud/aggregate.d.ts +1 -0
  114. package/lib/supabase/crud/bulk.d.ts +63 -0
  115. package/lib/supabase/crud/create.d.ts +2 -1
  116. package/lib/supabase/crud/delete.d.ts +1 -0
  117. package/lib/supabase/crud/get.d.ts +1 -0
  118. package/lib/supabase/crud/index.d.ts +2 -0
  119. package/lib/supabase/crud/list.d.ts +1 -0
  120. package/lib/supabase/crud/update.d.ts +1 -0
  121. package/lib/supabase/edgeFunction.d.ts +56 -0
  122. package/lib/supabase/email/createEmailFunction.d.ts +31 -0
  123. package/lib/supabase/helpers/authProvider.d.ts +0 -0
  124. package/lib/supabase/index.d.ts +8 -0
  125. package/lib/supabase/index.js +3 -2
  126. package/lib/supabase/index.js.map +4 -4
  127. package/lib/supabase/oauth/disconnect.d.ts +0 -0
  128. package/lib/supabase/oauth/exchangeToken.d.ts +0 -0
  129. package/lib/supabase/oauth/getConnections.d.ts +0 -0
  130. package/lib/supabase/oauth/index.d.ts +0 -0
  131. package/lib/supabase/oauth/refreshToken.d.ts +0 -0
  132. package/lib/supabase/registerCrudFunctions.d.ts +0 -0
  133. package/lib/supabase/utils/idempotency.d.ts +0 -0
  134. package/lib/supabase/utils/monitoring.d.ts +0 -0
  135. package/lib/supabase/utils/rateLimiter.d.ts +0 -0
  136. package/lib/vercel/api/ai/chat.d.ts +29 -0
  137. package/lib/vercel/api/ai/index.d.ts +1 -0
  138. package/lib/vercel/api/auth/get-custom-claims.d.ts +0 -0
  139. package/lib/vercel/api/auth/get-user-auth-status.d.ts +0 -0
  140. package/lib/vercel/api/auth/index.d.ts +0 -0
  141. package/lib/vercel/api/auth/remove-custom-claims.d.ts +0 -0
  142. package/lib/vercel/api/auth/set-custom-claims.d.ts +0 -0
  143. package/lib/vercel/api/billing/cancel.d.ts +0 -0
  144. package/lib/vercel/api/billing/change-plan.d.ts +0 -0
  145. package/lib/vercel/api/billing/create-checkout-session.d.ts +0 -0
  146. package/lib/vercel/api/billing/customer-portal.d.ts +0 -0
  147. package/lib/vercel/api/billing/index.d.ts +0 -0
  148. package/lib/vercel/api/billing/refresh-subscription-status.d.ts +0 -0
  149. package/lib/vercel/api/billing/webhook-handler.d.ts +0 -0
  150. package/lib/vercel/api/config/constants.d.ts +0 -0
  151. package/lib/vercel/api/config/firebase-admin.d.ts +0 -0
  152. package/lib/vercel/api/config/index.d.ts +0 -0
  153. package/lib/vercel/api/crud/bulk.d.ts +31 -0
  154. package/lib/vercel/api/crud/create.d.ts +0 -0
  155. package/lib/vercel/api/crud/delete.d.ts +0 -0
  156. package/lib/vercel/api/crud/get.d.ts +0 -0
  157. package/lib/vercel/api/crud/index.d.ts +1 -0
  158. package/lib/vercel/api/crud/list.d.ts +0 -0
  159. package/lib/vercel/api/crud/update.d.ts +0 -0
  160. package/lib/vercel/api/index.d.ts +1 -0
  161. package/lib/vercel/api/index.js +3 -2
  162. package/lib/vercel/api/index.js.map +4 -4
  163. package/lib/vercel/api/oauth/check-github-access.d.ts +0 -0
  164. package/lib/vercel/api/oauth/exchange-token.d.ts +0 -0
  165. package/lib/vercel/api/oauth/grant-github-access.d.ts +0 -0
  166. package/lib/vercel/api/oauth/index.d.ts +0 -0
  167. package/lib/vercel/api/oauth/revoke-github-access.d.ts +0 -0
  168. package/lib/vercel/api/utils/cors.d.ts +0 -0
  169. package/lib/vercel/baseFunction.d.ts +0 -0
  170. package/package.json +40 -7
  171. package/src/firebase/auth/getCustomClaims.ts +0 -0
  172. package/src/firebase/auth/getUserAuthStatus.ts +0 -0
  173. package/src/firebase/auth/index.ts +0 -0
  174. package/src/firebase/auth/removeCustomClaims.ts +0 -0
  175. package/src/firebase/auth/setCustomClaims.ts +0 -0
  176. package/src/firebase/baseFunction.ts +0 -0
  177. package/src/firebase/billing/cancelSubscription.ts +0 -0
  178. package/src/firebase/billing/changePlan.ts +0 -0
  179. package/src/firebase/billing/createCheckoutSession.ts +82 -186
  180. package/src/firebase/billing/createCustomerPortal.ts +0 -0
  181. package/src/firebase/billing/healthCheck.ts +0 -0
  182. package/src/firebase/billing/index.d.ts +0 -0
  183. package/src/firebase/billing/index.ts +0 -0
  184. package/src/firebase/billing/refreshSubscriptionStatus.ts +0 -0
  185. package/src/firebase/billing/webhookHandler.ts +0 -0
  186. package/src/firebase/config/constants.ts +0 -0
  187. package/src/firebase/config/index.ts +0 -0
  188. package/src/firebase/config/secrets.ts +0 -0
  189. package/src/firebase/crud/__tests__/bulk.test.ts +322 -0
  190. package/src/firebase/crud/aggregate.ts +0 -0
  191. package/src/firebase/crud/bulk.ts +272 -0
  192. package/src/firebase/crud/create.ts +20 -33
  193. package/src/firebase/crud/delete.ts +0 -0
  194. package/src/firebase/crud/get.ts +0 -0
  195. package/src/firebase/crud/index.ts +1 -0
  196. package/src/firebase/crud/list.ts +0 -0
  197. package/src/firebase/crud/update.ts +0 -0
  198. package/src/firebase/helpers/githubAccessHelper.ts +0 -0
  199. package/src/firebase/helpers/githubTeamAccessHelper.ts +0 -0
  200. package/src/firebase/helpers/index.ts +0 -0
  201. package/src/firebase/index.d.ts +0 -0
  202. package/src/firebase/index.ts +0 -0
  203. package/src/firebase/oauth/disconnect.ts +0 -0
  204. package/src/firebase/oauth/exchangeToken.ts +4 -4
  205. package/src/firebase/oauth/getConnections.ts +0 -0
  206. package/src/firebase/oauth/githubAccess.ts +0 -0
  207. package/src/firebase/oauth/index.ts +0 -0
  208. package/src/firebase/oauth/refreshToken.ts +4 -4
  209. package/src/firebase/registerCrudFunctions.ts +13 -0
  210. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +0 -0
  211. package/src/firebase/scheduled/index.ts +0 -0
  212. package/src/shared/__tests__/auth.test.ts +0 -0
  213. package/src/shared/__tests__/bulkCore.test.ts +487 -0
  214. package/src/shared/__tests__/errorHandling.test.ts +0 -0
  215. package/src/shared/__tests__/firebase.test.ts +9 -3
  216. package/src/shared/__tests__/idempotency.test.ts +0 -0
  217. package/src/shared/__tests__/internalValidation.test.ts +9 -3
  218. package/src/shared/__tests__/metadata.test.ts +10 -10
  219. package/src/shared/__tests__/rateLimiter.test.ts +0 -0
  220. package/src/shared/__tests__/schema.test.ts +0 -0
  221. package/src/shared/__tests__/schemaValidation.test.ts +0 -0
  222. package/src/shared/__tests__/subscription.test.ts +0 -0
  223. package/src/shared/__tests__/utils.test.ts +10 -4
  224. package/src/shared/__tests__/validation-env.test.ts +9 -3
  225. package/src/shared/__tests__/validation.test.ts +0 -0
  226. package/src/shared/ai/__tests__/costTracker.test.ts +133 -0
  227. package/src/shared/ai/classifyAIError.ts +178 -0
  228. package/src/shared/ai/costTracker.ts +51 -0
  229. package/src/shared/ai/createAIRoute.ts +400 -0
  230. package/src/shared/ai/index.ts +8 -0
  231. package/src/shared/ai/resolveModelTier.ts +61 -0
  232. package/src/shared/billing/__tests__/createCheckout.test.ts +0 -0
  233. package/src/shared/billing/__tests__/webhookHandler.test.ts +0 -0
  234. package/src/shared/billing/createCheckout.ts +168 -8
  235. package/src/shared/billing/helpers/index.ts +0 -0
  236. package/src/shared/billing/helpers/subscriptionManagement.ts +9 -0
  237. package/src/shared/billing/helpers/updateUserSubscription.ts +0 -0
  238. package/src/shared/billing/idempotency.ts +5 -0
  239. package/src/shared/billing/index.ts +0 -0
  240. package/src/shared/billing/webhookHandler.ts +0 -0
  241. package/src/shared/crud/bulkCore.ts +483 -0
  242. package/src/shared/crud/index.ts +23 -0
  243. package/src/shared/email/createEmailRoute.ts +81 -0
  244. package/src/shared/email/index.ts +5 -0
  245. package/src/shared/email/provider.ts +31 -0
  246. package/src/shared/email/resendProvider.ts +56 -0
  247. package/src/shared/errorHandling.ts +10 -4
  248. package/src/shared/firebase.ts +0 -0
  249. package/src/shared/github.ts +38 -0
  250. package/src/shared/index.d.ts +9 -0
  251. package/src/shared/index.ts +3 -0
  252. package/src/shared/logger.ts +2 -0
  253. package/src/shared/metadata.ts +6 -6
  254. package/src/shared/oauth/__tests__/exchangeToken.test.ts +0 -0
  255. package/src/shared/oauth/__tests__/grantAccess.test.ts +0 -0
  256. package/src/shared/oauth/exchangeToken.ts +1 -0
  257. package/src/shared/oauth/grantAccess.ts +1 -0
  258. package/src/shared/oauth/index.ts +0 -0
  259. package/src/shared/schema.ts +0 -0
  260. package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -0
  261. package/src/shared/utils/detectFirestore.ts +0 -0
  262. package/src/shared/utils/external/date.ts +0 -0
  263. package/src/shared/utils/external/index.ts +0 -0
  264. package/src/shared/utils/external/references.ts +0 -0
  265. package/src/shared/utils/external/subscription.ts +0 -0
  266. package/src/shared/utils/firebaseHelpers.ts +0 -0
  267. package/src/shared/utils/functionWrapper.ts +0 -0
  268. package/src/shared/utils/index.ts +0 -0
  269. package/src/shared/utils/internal/auth.ts +0 -0
  270. package/src/shared/utils/internal/firebase.ts +0 -0
  271. package/src/shared/utils/internal/idempotency.ts +1 -0
  272. package/src/shared/utils/internal/index.ts +0 -0
  273. package/src/shared/utils/internal/monitoring.ts +0 -0
  274. package/src/shared/utils/internal/rateLimiter.ts +6 -3
  275. package/src/shared/utils/internal/validation.ts +0 -0
  276. package/src/shared/utils/schemaValidation.ts +0 -0
  277. package/src/shared/utils/validation.ts +0 -0
  278. package/src/shared/utils/vercelHelpers.ts +0 -0
  279. package/src/shared/utils.ts +0 -0
  280. package/src/shared/validation.ts +1 -1
  281. package/src/supabase/__tests__/bulk.test.ts +330 -0
  282. package/src/supabase/ai/createAIFunction.ts +76 -0
  283. package/src/supabase/auth/deleteAccount.ts +0 -0
  284. package/src/supabase/auth/getCustomClaims.ts +0 -0
  285. package/src/supabase/auth/getUserAuthStatus.ts +0 -0
  286. package/src/supabase/auth/removeCustomClaims.ts +38 -2
  287. package/src/supabase/auth/setCustomClaims.ts +64 -5
  288. package/src/supabase/baseFunction.ts +26 -2
  289. package/src/supabase/billing/cancelSubscription.ts +0 -0
  290. package/src/supabase/billing/changePlan.ts +6 -1
  291. package/src/supabase/billing/createCheckoutSession.ts +16 -2
  292. package/src/supabase/billing/createCustomerPortal.ts +0 -0
  293. package/src/supabase/billing/refreshSubscriptionStatus.ts +0 -0
  294. package/src/supabase/crud/aggregate.ts +1 -0
  295. package/src/supabase/crud/bulk.ts +244 -0
  296. package/src/supabase/crud/create.ts +16 -14
  297. package/src/supabase/crud/delete.ts +1 -0
  298. package/src/supabase/crud/get.ts +1 -0
  299. package/src/supabase/crud/index.ts +2 -0
  300. package/src/supabase/crud/list.ts +1 -0
  301. package/src/supabase/crud/update.ts +1 -0
  302. package/src/supabase/edgeFunction.ts +196 -0
  303. package/src/supabase/email/createEmailFunction.ts +72 -0
  304. package/src/supabase/helpers/authProvider.ts +0 -0
  305. package/src/supabase/index.ts +21 -0
  306. package/src/supabase/oauth/disconnect.ts +1 -2
  307. package/src/supabase/oauth/exchangeToken.ts +39 -10
  308. package/src/supabase/oauth/getConnections.ts +1 -4
  309. package/src/supabase/oauth/index.ts +0 -0
  310. package/src/supabase/oauth/refreshToken.ts +6 -12
  311. package/src/supabase/registerCrudFunctions.ts +20 -20
  312. package/src/supabase/utils/idempotency.ts +6 -2
  313. package/src/supabase/utils/monitoring.ts +0 -0
  314. package/src/supabase/utils/rateLimiter.ts +0 -0
  315. package/src/vercel/__tests__/bulk.test.ts +301 -0
  316. package/src/vercel/api/ai/chat.ts +77 -0
  317. package/src/vercel/api/ai/index.ts +3 -0
  318. package/src/vercel/api/auth/get-custom-claims.ts +0 -0
  319. package/src/vercel/api/auth/get-user-auth-status.ts +0 -0
  320. package/src/vercel/api/auth/index.ts +0 -0
  321. package/src/vercel/api/auth/remove-custom-claims.ts +0 -0
  322. package/src/vercel/api/auth/set-custom-claims.ts +0 -0
  323. package/src/vercel/api/billing/cancel.ts +0 -0
  324. package/src/vercel/api/billing/change-plan.ts +0 -0
  325. package/src/vercel/api/billing/create-checkout-session.ts +31 -4
  326. package/src/vercel/api/billing/customer-portal.ts +0 -0
  327. package/src/vercel/api/billing/index.ts +0 -0
  328. package/src/vercel/api/billing/refresh-subscription-status.ts +0 -0
  329. package/src/vercel/api/billing/webhook-handler.ts +8 -1
  330. package/src/vercel/api/config/constants.ts +0 -0
  331. package/src/vercel/api/config/firebase-admin.ts +0 -0
  332. package/src/vercel/api/config/index.ts +0 -0
  333. package/src/vercel/api/crud/bulk.ts +216 -0
  334. package/src/vercel/api/crud/create.ts +10 -9
  335. package/src/vercel/api/crud/delete.ts +0 -0
  336. package/src/vercel/api/crud/get.ts +0 -0
  337. package/src/vercel/api/crud/index.ts +1 -0
  338. package/src/vercel/api/crud/list.ts +0 -0
  339. package/src/vercel/api/crud/update.ts +0 -0
  340. package/src/vercel/api/index.d.ts +0 -0
  341. package/src/vercel/api/index.ts +1 -0
  342. package/src/vercel/api/oauth/check-github-access.ts +0 -0
  343. package/src/vercel/api/oauth/exchange-token.ts +27 -1
  344. package/src/vercel/api/oauth/grant-github-access.ts +0 -0
  345. package/src/vercel/api/oauth/index.ts +0 -0
  346. package/src/vercel/api/oauth/revoke-github-access.ts +0 -0
  347. package/src/vercel/api/utils/cors.ts +8 -0
  348. package/src/vercel/baseFunction.ts +0 -0
@@ -0,0 +1,400 @@
1
+ // packages/functions/src/shared/ai/createAIRoute.ts
2
+
3
+ /**
4
+ * @fileoverview AI Route Handler (Vercel AI SDK)
5
+ * @description Platform-agnostic handler for AI chat requests using Vercel AI SDK.
6
+ * Handles auth (via platform wrapper), rate limiting (Upstash), streaming, and cost tracking.
7
+ *
8
+ * @version 0.1.0
9
+ * @since 0.1.0
10
+ * @author AMBROISE PARK Consulting
11
+ */
12
+
13
+ import { streamText, generateText, tool, jsonSchema } from 'ai';
14
+ import type { LanguageModel, CoreTool } from 'ai';
15
+
16
+ import type {
17
+ AIChatRequest,
18
+ AICostConfig,
19
+ AICostRecord,
20
+ AIRateLimitConfig,
21
+ AIRouteConfig,
22
+ AIToolDefinition,
23
+ AIUsage,
24
+ } from '@donotdev/core/server';
25
+ import { AI_MODELS, validateAIChatRequest } from '@donotdev/core/server';
26
+
27
+ import { calculateCost } from './costTracker.js';
28
+
29
+ // =============================================================================
30
+ // Types
31
+ // =============================================================================
32
+
33
+ /** Per-request options passed to the AI route handler. */
34
+ export interface AIRouteOptions {
35
+ /** Authenticated user ID */
36
+ userId: string;
37
+ /** Request ID for cost tracking */
38
+ requestId?: string;
39
+ /** Callback to persist cost record (platform-specific) */
40
+ onCostRecord?: (record: AICostRecord) => Promise<void>;
41
+ }
42
+
43
+ /** Provider factory map - lazily creates provider instances */
44
+ type ProviderFactory = (apiKey: string) => LanguageModel;
45
+
46
+ // =============================================================================
47
+ // Provider Resolution
48
+ // =============================================================================
49
+
50
+ /** Lazily import and create provider models */
51
+ async function resolveModel(
52
+ provider: string,
53
+ model: string
54
+ ): Promise<LanguageModel> {
55
+ const factories: Record<string, () => Promise<ProviderFactory>> = {
56
+ anthropic: async () => {
57
+ const { createAnthropic } = await import('@ai-sdk/anthropic');
58
+ return (apiKey: string) => createAnthropic({ apiKey })(model);
59
+ },
60
+ openai: async () => {
61
+ const { createOpenAI } = await import('@ai-sdk/openai');
62
+ return (apiKey: string) => createOpenAI({ apiKey })(model);
63
+ },
64
+ google: async () => {
65
+ const { createGoogleGenerativeAI } = await import('@ai-sdk/google');
66
+ return (apiKey: string) => createGoogleGenerativeAI({ apiKey })(model);
67
+ },
68
+ };
69
+
70
+ const factory = factories[provider];
71
+ if (!factory) {
72
+ throw new Error(`Unsupported AI provider: ${provider}`);
73
+ }
74
+
75
+ const apiKey = getAIApiKey(provider);
76
+ const createModel = await factory();
77
+ return createModel(apiKey);
78
+ }
79
+
80
+ // =============================================================================
81
+ // Rate Limiting (reused from old handler)
82
+ // =============================================================================
83
+
84
+ const DEFAULT_RATE_LIMIT: AIRateLimitConfig = {
85
+ maxRequests: 30,
86
+ windowMs: 60_000,
87
+ };
88
+
89
+ let rateLimiter: {
90
+ check: (userId: string, config: AIRateLimitConfig) => Promise<void>;
91
+ } | null = null;
92
+
93
+ async function getRateLimiter() {
94
+ if (rateLimiter) return rateLimiter;
95
+
96
+ const redisUrl = getEnv('UPSTASH_REDIS_REST_URL');
97
+ const redisToken = getEnv('UPSTASH_REDIS_REST_TOKEN');
98
+
99
+ if (!redisUrl || !redisToken) {
100
+ console.warn(
101
+ '[AI] UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN not set. Rate limiting disabled.'
102
+ );
103
+ rateLimiter = { check: async () => {} };
104
+ return rateLimiter;
105
+ }
106
+
107
+ try {
108
+ const { Ratelimit } = await import('@upstash/ratelimit');
109
+ const { Redis } = await import('@upstash/redis');
110
+
111
+ const redis = new Redis({ url: redisUrl, token: redisToken });
112
+ const limiters = new Map<string, InstanceType<typeof Ratelimit>>();
113
+
114
+ rateLimiter = {
115
+ check: async (userId: string, config: AIRateLimitConfig) => {
116
+ const key = `${config.maxRequests}:${config.windowMs}`;
117
+ let rl = limiters.get(key);
118
+ if (!rl) {
119
+ rl = new Ratelimit({
120
+ redis,
121
+ limiter: Ratelimit.slidingWindow(
122
+ config.maxRequests,
123
+ `${config.windowMs}ms`
124
+ ),
125
+ prefix: 'ai_rl',
126
+ });
127
+ limiters.set(key, rl);
128
+ }
129
+
130
+ const result = await rl.limit(userId);
131
+ if (!result.success) {
132
+ throw new Error(
133
+ `Rate limit exceeded. Maximum ${config.maxRequests} requests per ${config.windowMs / 1000}s.`
134
+ );
135
+ }
136
+ },
137
+ };
138
+ return rateLimiter;
139
+ } catch (err) {
140
+ console.warn(
141
+ '[AI] Failed to initialize Upstash rate limiter:',
142
+ err instanceof Error ? err.message : err
143
+ );
144
+ rateLimiter = { check: async () => {} };
145
+ return rateLimiter;
146
+ }
147
+ }
148
+
149
+ // =============================================================================
150
+ // Tool Conversion (JSON Schema → Vercel AI SDK tool)
151
+ // =============================================================================
152
+
153
+ /**
154
+ * Convert framework tool definitions to Vercel AI SDK tools.
155
+ * Uses `jsonSchema()` from the AI SDK to pass JSON Schema directly (no zod dependency).
156
+ * Merges request-level tools with config-level tools (request takes precedence).
157
+ */
158
+ function resolveTools(
159
+ requestTools?: Record<string, AIToolDefinition>,
160
+ configTools?: Record<string, AIToolDefinition>
161
+ ): Record<string, CoreTool> | undefined {
162
+ const merged = { ...configTools, ...requestTools };
163
+ if (Object.keys(merged).length === 0) return undefined;
164
+
165
+ const sdkTools: Record<string, CoreTool> = {};
166
+ for (const [name, def] of Object.entries(merged)) {
167
+ sdkTools[name] = tool({
168
+ description: def.description,
169
+ parameters: jsonSchema(def.parameters),
170
+ });
171
+ }
172
+ return sdkTools;
173
+ }
174
+
175
+ // =============================================================================
176
+ // Core Handler
177
+ // =============================================================================
178
+
179
+ /**
180
+ * Handle an AI chat request using Vercel AI SDK.
181
+ * Supports both streaming (returns SSE Response) and non-streaming (returns JSON).
182
+ *
183
+ * @param request - Validated AI chat request
184
+ * @param config - Route configuration
185
+ * @param options - Per-request options (userId, cost callback)
186
+ * @returns Response (SSE stream or JSON)
187
+ */
188
+ export async function handleAIRequest(
189
+ request: AIChatRequest,
190
+ config: AIRouteConfig,
191
+ options: AIRouteOptions
192
+ ): Promise<Response> {
193
+ // Validate request
194
+ const validation = validateAIChatRequest(request);
195
+ if (!validation.success) {
196
+ return jsonError(
197
+ `Invalid AI request: ${validation.issues?.map((i) => i.message).join(', ')}`,
198
+ 400
199
+ );
200
+ }
201
+
202
+ // Resolve provider + model
203
+ const provider = request.provider || config.provider || 'anthropic';
204
+ const providerModels = AI_MODELS[provider as keyof typeof AI_MODELS];
205
+ const model =
206
+ request.model ||
207
+ config.model ||
208
+ providerModels?.default ||
209
+ 'claude-sonnet-4-20250514';
210
+
211
+ // Validate model against allowed list
212
+ if (providerModels) {
213
+ const allowed = providerModels.models as readonly string[];
214
+ if (!allowed.includes(model)) {
215
+ return jsonError(
216
+ `Model '${model}' is not allowed for provider '${provider}'. Allowed: ${allowed.join(', ')}`,
217
+ 400
218
+ );
219
+ }
220
+ }
221
+
222
+ // Rate limit
223
+ try {
224
+ const rl = await getRateLimiter();
225
+ await rl.check(
226
+ options.userId,
227
+ config.rateLimitConfig || DEFAULT_RATE_LIMIT
228
+ );
229
+ } catch (err) {
230
+ return jsonError(
231
+ err instanceof Error ? err.message : 'Rate limit exceeded',
232
+ 429
233
+ );
234
+ }
235
+
236
+ // Resolve AI SDK model
237
+ let languageModel: LanguageModel;
238
+ try {
239
+ languageModel = await resolveModel(provider, model);
240
+ } catch (err) {
241
+ return jsonError(
242
+ `Failed to initialize provider: ${err instanceof Error ? err.message : String(err)}`,
243
+ 500
244
+ );
245
+ }
246
+
247
+ // Build messages for AI SDK
248
+ const systemMessages = request.messages
249
+ .filter((m) => m.role === 'system')
250
+ .map((m) => m.content);
251
+ const systemPrompt =
252
+ request.systemPrompt ||
253
+ config.systemPrompt ||
254
+ (systemMessages.length > 0 ? systemMessages.join('\n') : undefined);
255
+
256
+ const messages = request.messages
257
+ .filter((m) => m.role !== 'system')
258
+ .map((m) => ({
259
+ role: m.role as 'user' | 'assistant',
260
+ content: m.content,
261
+ }));
262
+
263
+ const maxTokens = request.maxTokens || config.maxTokens || 4096;
264
+ const temperature = request.temperature ?? config.temperature ?? 0.7;
265
+ const requestId = options.requestId || crypto.randomUUID();
266
+
267
+ // Resolve tools (request-level overrides config-level)
268
+ const tools = resolveTools(request.tools, config.tools);
269
+
270
+ // Cost tracking helper
271
+ const recordCost = async (usage: AIUsage) => {
272
+ if (!options.onCostRecord) return;
273
+
274
+ const markup = config.cost?.markup ?? 4.0;
275
+ const cost = calculateCost(usage, model, markup);
276
+
277
+ const record: AICostRecord = {
278
+ userId: options.userId,
279
+ model,
280
+ provider,
281
+ usage,
282
+ providerCost: cost.providerCost,
283
+ billedCost: cost.billedCost,
284
+ markup,
285
+ timestamp: new Date().toISOString(),
286
+ requestId,
287
+ };
288
+
289
+ // Non-blocking - don't let cost recording failure break the response
290
+ options.onCostRecord(record).catch((err) => {
291
+ console.error('[AI] Failed to record cost:', err);
292
+ });
293
+ };
294
+
295
+ // Streaming vs non-streaming
296
+ if (request.stream !== false) {
297
+ // Streaming (default)
298
+ const result = streamText({
299
+ model: languageModel,
300
+ messages,
301
+ system: systemPrompt,
302
+ maxTokens,
303
+ temperature,
304
+ tools,
305
+ onFinish: async ({ usage }: { usage: any }) => {
306
+ await recordCost({
307
+ promptTokens: usage.promptTokens,
308
+ completionTokens: usage.completionTokens,
309
+ totalTokens: usage.promptTokens + usage.completionTokens,
310
+ });
311
+ },
312
+ });
313
+
314
+ return result.toDataStreamResponse();
315
+ }
316
+
317
+ // Non-streaming
318
+ const result = await generateText({
319
+ model: languageModel,
320
+ messages,
321
+ system: systemPrompt,
322
+ maxTokens,
323
+ temperature,
324
+ tools,
325
+ });
326
+
327
+ const usage: AIUsage = {
328
+ promptTokens: result.usage.promptTokens,
329
+ completionTokens: result.usage.completionTokens,
330
+ totalTokens: result.usage.promptTokens + result.usage.completionTokens,
331
+ };
332
+
333
+ await recordCost(usage);
334
+
335
+ // Extract tool calls from result
336
+ const toolCalls =
337
+ result.toolCalls?.map((tc: any) => ({
338
+ id: tc.toolCallId,
339
+ name: tc.toolName,
340
+ args: tc.args,
341
+ })) ?? [];
342
+
343
+ return new Response(
344
+ JSON.stringify({
345
+ message: {
346
+ role: 'assistant',
347
+ content: result.text,
348
+ },
349
+ usage,
350
+ finishReason: result.finishReason,
351
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
352
+ model,
353
+ provider,
354
+ }),
355
+ {
356
+ status: 200,
357
+ headers: { 'Content-Type': 'application/json' },
358
+ }
359
+ );
360
+ }
361
+
362
+ // =============================================================================
363
+ // Helpers
364
+ // =============================================================================
365
+
366
+ function jsonError(message: string, status: number): Response {
367
+ return new Response(JSON.stringify({ error: message }), {
368
+ status,
369
+ headers: { 'Content-Type': 'application/json' },
370
+ });
371
+ }
372
+
373
+ function getEnv(name: string): string | undefined {
374
+ if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
375
+ return (globalThis as any).Deno?.env?.get(name);
376
+ }
377
+ return typeof process !== 'undefined' ? process.env[name] : undefined;
378
+ }
379
+
380
+ function getAIApiKey(provider: string): string {
381
+ const providerKeyMap: Record<string, string> = {
382
+ anthropic: 'ANTHROPIC_API_KEY',
383
+ openai: 'OPENAI_API_KEY',
384
+ google: 'GOOGLE_AI_API_KEY',
385
+ };
386
+
387
+ const providerKey = providerKeyMap[provider];
388
+ if (providerKey) {
389
+ const key = getEnv(providerKey);
390
+ if (key) return key;
391
+ }
392
+
393
+ const key = getEnv('AI_API_KEY');
394
+ if (!key) {
395
+ throw new Error(
396
+ `Missing API key. Set ${providerKey || 'AI_API_KEY'} environment variable.`
397
+ );
398
+ }
399
+ return key;
400
+ }
@@ -0,0 +1,8 @@
1
+ // packages/functions/src/shared/ai/index.ts
2
+
3
+ export { handleAIRequest } from './createAIRoute.js';
4
+ export type { AIRouteOptions } from './createAIRoute.js';
5
+ export { calculateCost } from './costTracker.js';
6
+ export { resolveModelForTier } from './resolveModelTier.js';
7
+ export { classifyAIError, mapClassifiedToHTTP } from './classifyAIError.js';
8
+ export type { AIErrorCode, ClassifiedAIError } from './classifyAIError.js';
@@ -0,0 +1,61 @@
1
+ // packages/functions/src/shared/ai/resolveModelTier.ts
2
+
3
+ /**
4
+ * @fileoverview AI Model Tier Resolver
5
+ * @description Resolves the model ID for a given tier via env var chain.
6
+ * Resolution: per-function env → per-tier env → static SSOT.
7
+ * Cross-runtime: Deno (edge functions) + Node (Vercel/Firebase).
8
+ *
9
+ * @version 0.1.0
10
+ * @since 0.6.0
11
+ * @author AMBROISE PARK Consulting
12
+ */
13
+
14
+ import { AI_TIERS } from '@donotdev/core/server';
15
+ import type { AITierId } from '@donotdev/core/server';
16
+
17
+ // =============================================================================
18
+ // Env helper (Deno + Node cross-runtime)
19
+ // =============================================================================
20
+
21
+ function getEnv(name: string): string | undefined {
22
+ if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
23
+ return (globalThis as any).Deno?.env?.get(name);
24
+ }
25
+ return typeof process !== 'undefined' ? process.env[name] : undefined;
26
+ }
27
+
28
+ // =============================================================================
29
+ // Resolver
30
+ // =============================================================================
31
+
32
+ /**
33
+ * Resolve the AI model ID for a given tier.
34
+ *
35
+ * Resolution chain (first non-empty wins):
36
+ * 1. `AI_MODEL_<FUNCTION_NAME>` env var (per-function override)
37
+ * 2. `AI_TIER_<TIER>` env var (per-tier override)
38
+ * 3. `AI_TIERS.<TIER>.defaultModel` (static SSOT from constants)
39
+ *
40
+ * @param tier - The tier ID ('fast', 'standard', 'premium')
41
+ * @param functionName - Optional function name for per-function env var lookup
42
+ * @returns The resolved model ID string
43
+ */
44
+ export function resolveModelForTier(
45
+ tier: AITierId,
46
+ functionName?: string
47
+ ): string {
48
+ // 1. Per-function env var: AI_MODEL_BRAINSTORM, AI_MODEL_SPEC_CHAT, etc.
49
+ if (functionName) {
50
+ const perFn = getEnv(`AI_MODEL_${functionName.toUpperCase()}`);
51
+ if (perFn) return perFn;
52
+ }
53
+
54
+ // 2. Per-tier env var: AI_TIER_FAST, AI_TIER_STANDARD, AI_TIER_PREMIUM
55
+ const perTier = getEnv(`AI_TIER_${tier.toUpperCase()}`);
56
+ if (perTier) return perTier;
57
+
58
+ // 3. Static SSOT
59
+ const tierConfig = Object.values(AI_TIERS).find((t) => t.id === tier);
60
+ return tierConfig?.defaultModel ?? AI_TIERS.STANDARD.defaultModel;
61
+ }
@@ -24,7 +24,13 @@ import type {
24
24
  */
25
25
  export interface StripeCheckoutProvider {
26
26
  createCheckoutSession(params: {
27
- priceId: string;
27
+ priceId?: string;
28
+ /** Amount in cents (dynamic pricing mode) */
29
+ unitAmount?: number;
30
+ /** Product name for Stripe checkout (dynamic pricing mode) */
31
+ productName?: string;
32
+ /** Currency code, defaults to 'eur' */
33
+ currency?: string;
28
34
  customerEmail?: string;
29
35
  metadata: Record<string, string>;
30
36
  allowPromotionCodes: boolean;
@@ -50,10 +56,64 @@ export interface AuthCheckoutProvider {
50
56
  }>;
51
57
  }
52
58
 
59
+ /**
60
+ * Validate URL has http/https protocol.
61
+ * Platform-agnostic (no firebase logger dependency).
62
+ */
63
+ function validateCheckoutUrl(url: string, name: string): void {
64
+ try {
65
+ const parsed = new URL(url);
66
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
67
+ throw new Error(`Invalid protocol: ${parsed.protocol}`);
68
+ }
69
+ } catch (error) {
70
+ throw new Error(
71
+ `Invalid ${name} URL: ${url}. ${error instanceof Error ? error.message : 'Invalid URL format'}`
72
+ );
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Sanitize metadata: enforce string values, strip script injection, cap lengths.
78
+ * Platform-agnostic (no firebase logger dependency).
79
+ */
80
+ function sanitizeMetadata(
81
+ metadata: Record<string, any>
82
+ ): Record<string, string> {
83
+ const sanitized: Record<string, string> = {};
84
+
85
+ for (const [key, value] of Object.entries(metadata)) {
86
+ if (typeof value !== 'string') {
87
+ throw new Error(
88
+ `Metadata value for key '${key}' must be a string, got ${typeof value}`
89
+ );
90
+ }
91
+
92
+ const sanitizedValue = value
93
+ .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
94
+ .replace(/javascript:/gi, '')
95
+ .replace(/on\w+\s*=/gi, '');
96
+
97
+ if (sanitizedValue.length > 1000) {
98
+ throw new Error(
99
+ `Metadata value for key '${key}' is too long (max 1000 characters)`
100
+ );
101
+ }
102
+
103
+ if (key.length > 100) {
104
+ throw new Error(`Metadata key '${key}' is too long (max 100 characters)`);
105
+ }
106
+
107
+ sanitized[key] = sanitizedValue;
108
+ }
109
+
110
+ return sanitized;
111
+ }
112
+
53
113
  /**
54
114
  * Create checkout session algorithm
55
115
  *
56
- * @version 0.1.0
116
+ * @version 0.2.0
57
117
  * @since 0.0.1
58
118
  * @author AMBROISE PARK Consulting
59
119
  */
@@ -63,8 +123,15 @@ export async function createCheckoutAlgorithm(
63
123
  authProvider: AuthCheckoutProvider,
64
124
  billingConfig: StripeBackConfig
65
125
  ): Promise<CreateCheckoutSessionResponse> {
126
+ if (!process.env.FRONTEND_URL) {
127
+ throw new Error('FRONTEND_URL environment variable is required');
128
+ }
129
+
66
130
  const {
67
131
  priceId,
132
+ unitAmount,
133
+ productName,
134
+ currency,
68
135
  userId,
69
136
  customerEmail,
70
137
  metadata = {},
@@ -86,9 +153,39 @@ export async function createCheckoutAlgorithm(
86
153
  throw new Error(`Invalid billing config key: ${configKey}`);
87
154
  }
88
155
 
89
- // ✅ VALIDATE: priceId matches config
90
- if (billingItem.priceId !== priceId) {
91
- throw new Error('Price ID mismatch with configuration');
156
+ // ✅ VALIDATE: either priceId or (unitAmount + productName)
157
+ const useDynamicPricing = !priceId && unitAmount && productName;
158
+ if (!priceId && !useDynamicPricing) {
159
+ throw new Error('Either priceId or (unitAmount + productName) is required');
160
+ }
161
+
162
+ // ✅ VALIDATE: price_data not supported for subscriptions
163
+ if (useDynamicPricing && mode === 'subscription') {
164
+ throw new Error(
165
+ 'Dynamic pricing (unitAmount) is not supported for subscriptions. Use a Stripe priceId.'
166
+ );
167
+ }
168
+
169
+ if (priceId) {
170
+ // Fixed pricing: validate priceId matches config (if config has one)
171
+ if (billingItem.priceId && billingItem.priceId !== priceId) {
172
+ throw new Error('Price ID mismatch with configuration');
173
+ }
174
+ } else {
175
+ // Dynamic pricing: maxUnitAmount is required as a security cap
176
+ if (!billingItem.maxUnitAmount) {
177
+ throw new Error(
178
+ 'Dynamic pricing requires maxUnitAmount in billing config for security'
179
+ );
180
+ }
181
+ if (unitAmount! > billingItem.maxUnitAmount) {
182
+ throw new Error(
183
+ `Unit amount ${unitAmount} exceeds maximum allowed: ${billingItem.maxUnitAmount}`
184
+ );
185
+ }
186
+ if (unitAmount! < 100) {
187
+ throw new Error('Unit amount must be at least 100 cents (1.00)');
188
+ }
92
189
  }
93
190
 
94
191
  // ✅ VALIDATE: userId exists
@@ -99,18 +196,81 @@ export async function createCheckoutAlgorithm(
99
196
  // Verify user exists
100
197
  await authProvider.getUser(userId);
101
198
 
199
+ // ✅ HOOK: beforeCheckout (ownership check, status validation, server-resolved pricing)
200
+ let finalUnitAmount = unitAmount;
201
+ let finalProductName = productName;
202
+
203
+ if (billingItem.beforeCheckout) {
204
+ const hookResult = await billingItem.beforeCheckout(
205
+ userId,
206
+ {
207
+ priceId,
208
+ unitAmount,
209
+ productName,
210
+ currency,
211
+ mode,
212
+ metadata,
213
+ allowPromotionCodes,
214
+ },
215
+ sanitizeMetadata(metadata)
216
+ );
217
+
218
+ if (!hookResult.allowed) {
219
+ throw new Error(
220
+ hookResult.reason || 'Checkout blocked by beforeCheckout hook'
221
+ );
222
+ }
223
+
224
+ if (hookResult.overrides) {
225
+ if (hookResult.overrides.unitAmount !== undefined) {
226
+ finalUnitAmount = hookResult.overrides.unitAmount;
227
+ }
228
+ if (hookResult.overrides.productName !== undefined) {
229
+ finalProductName = hookResult.overrides.productName;
230
+ }
231
+ }
232
+ }
233
+
234
+ const finalUseDynamicPricing =
235
+ !priceId && finalUnitAmount && finalProductName;
236
+
237
+ // ✅ VALIDATE: overridden amount still respects security cap
238
+ if (
239
+ finalUseDynamicPricing &&
240
+ billingItem.maxUnitAmount &&
241
+ finalUnitAmount! > billingItem.maxUnitAmount
242
+ ) {
243
+ throw new Error(
244
+ `Hook-overridden unit amount ${finalUnitAmount} exceeds maximum allowed: ${billingItem.maxUnitAmount}`
245
+ );
246
+ }
247
+
248
+ // ✅ VALIDATE: URLs are valid http/https
249
+ const resolvedSuccessUrl =
250
+ successUrl || `${process.env.FRONTEND_URL}/billing/success`;
251
+ const resolvedCancelUrl =
252
+ cancelUrl || `${process.env.FRONTEND_URL}/billing/cancel`;
253
+ validateCheckoutUrl(resolvedSuccessUrl, 'success');
254
+ validateCheckoutUrl(resolvedCancelUrl, 'cancel');
255
+
256
+ // ✅ SANITIZE: metadata values (strip scripts, cap lengths)
257
+ const sanitizedMetadata = sanitizeMetadata(metadata);
258
+
102
259
  // Create checkout session
103
260
  const session = await stripeProvider.createCheckoutSession({
104
261
  priceId,
262
+ unitAmount: finalUseDynamicPricing ? finalUnitAmount : undefined,
263
+ productName: finalUseDynamicPricing ? finalProductName : undefined,
264
+ currency: currency || billingItem.currency || 'eur',
105
265
  customerEmail,
106
266
  metadata: {
107
- ...metadata,
267
+ ...sanitizedMetadata,
108
268
  userId,
109
269
  billingConfigKey: configKey as string, // ✅ Server values AFTER spread — cannot be overwritten by client
110
270
  },
111
271
  allowPromotionCodes,
112
- successUrl: successUrl || `${process.env.FRONTEND_URL}/billing/success`,
113
- cancelUrl: cancelUrl || `${process.env.FRONTEND_URL}/billing/cancel`,
272
+ successUrl: resolvedSuccessUrl,
273
+ cancelUrl: resolvedCancelUrl,
114
274
  mode,
115
275
  });
116
276
 
File without changes