@donotdev/functions 0.1.1 → 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 +0 -0
  4. package/guidelines/VERCEL.md +27 -1
  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 +0 -0
  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 +0 -0
  46. package/lib/shared/ai/costTracker.d.ts +0 -0
  47. package/lib/shared/ai/createAIHandler.d.ts +39 -0
  48. package/lib/shared/ai/createAIRoute.d.ts +0 -0
  49. package/lib/shared/ai/index.d.ts +0 -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 +0 -0
  55. package/lib/shared/ai/utils/parseSSE.d.ts +22 -0
  56. package/lib/shared/billing/createCheckout.d.ts +0 -0
  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 +0 -0
  66. package/lib/shared/email/index.d.ts +0 -0
  67. package/lib/shared/email/provider.d.ts +0 -0
  68. package/lib/shared/email/resendProvider.d.ts +0 -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 +0 -0
  72. package/lib/shared/index.d.ts +1 -0
  73. package/lib/shared/index.js +4 -4
  74. package/lib/shared/index.js.map +4 -4
  75. package/lib/shared/logger.d.ts +0 -0
  76. package/lib/shared/metadata.d.ts +6 -6
  77. package/lib/shared/oauth/exchangeToken.d.ts +0 -0
  78. package/lib/shared/oauth/grantAccess.d.ts +0 -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 +0 -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 +0 -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 +0 -0
  106. package/lib/supabase/auth/setCustomClaims.d.ts +0 -0
  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 +0 -0
  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 +0 -0
  114. package/lib/supabase/crud/bulk.d.ts +63 -0
  115. package/lib/supabase/crud/create.d.ts +1 -1
  116. package/lib/supabase/crud/delete.d.ts +0 -0
  117. package/lib/supabase/crud/get.d.ts +0 -0
  118. package/lib/supabase/crud/index.d.ts +2 -0
  119. package/lib/supabase/crud/list.d.ts +0 -0
  120. package/lib/supabase/crud/update.d.ts +0 -0
  121. package/lib/supabase/edgeFunction.d.ts +0 -0
  122. package/lib/supabase/email/createEmailFunction.d.ts +0 -0
  123. package/lib/supabase/helpers/authProvider.d.ts +0 -0
  124. package/lib/supabase/index.d.ts +3 -3
  125. package/lib/supabase/index.js +3 -3
  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 +0 -0
  137. package/lib/vercel/api/ai/index.d.ts +0 -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 +0 -0
  161. package/lib/vercel/api/index.js +3 -3
  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 +6 -6
  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 +5 -1
  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 +0 -0
  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 +0 -0
  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 +25 -13
  227. package/src/shared/ai/classifyAIError.ts +26 -11
  228. package/src/shared/ai/costTracker.ts +0 -0
  229. package/src/shared/ai/createAIRoute.ts +11 -8
  230. package/src/shared/ai/index.ts +0 -0
  231. package/src/shared/ai/resolveModelTier.ts +5 -2
  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 +24 -9
  235. package/src/shared/billing/helpers/index.ts +0 -0
  236. package/src/shared/billing/helpers/subscriptionManagement.ts +0 -0
  237. package/src/shared/billing/helpers/updateUserSubscription.ts +0 -0
  238. package/src/shared/billing/idempotency.ts +0 -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 +0 -0
  244. package/src/shared/email/index.ts +0 -0
  245. package/src/shared/email/provider.ts +0 -0
  246. package/src/shared/email/resendProvider.ts +1 -1
  247. package/src/shared/errorHandling.ts +0 -0
  248. package/src/shared/firebase.ts +0 -0
  249. package/src/shared/github.ts +0 -0
  250. package/src/shared/index.d.ts +9 -0
  251. package/src/shared/index.ts +1 -0
  252. package/src/shared/logger.ts +0 -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 +0 -0
  257. package/src/shared/oauth/grantAccess.ts +0 -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 +0 -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 +0 -0
  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 +0 -0
  281. package/src/supabase/__tests__/bulk.test.ts +330 -0
  282. package/src/supabase/ai/createAIFunction.ts +17 -16
  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 +0 -0
  287. package/src/supabase/auth/setCustomClaims.ts +1 -3
  288. package/src/supabase/baseFunction.ts +0 -0
  289. package/src/supabase/billing/cancelSubscription.ts +0 -0
  290. package/src/supabase/billing/changePlan.ts +1 -1
  291. package/src/supabase/billing/createCheckoutSession.ts +0 -0
  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 +0 -0
  295. package/src/supabase/crud/bulk.ts +244 -0
  296. package/src/supabase/crud/create.ts +15 -14
  297. package/src/supabase/crud/delete.ts +0 -0
  298. package/src/supabase/crud/get.ts +0 -0
  299. package/src/supabase/crud/index.ts +2 -0
  300. package/src/supabase/crud/list.ts +0 -0
  301. package/src/supabase/crud/update.ts +0 -0
  302. package/src/supabase/edgeFunction.ts +4 -3
  303. package/src/supabase/email/createEmailFunction.ts +9 -12
  304. package/src/supabase/helpers/authProvider.ts +0 -0
  305. package/src/supabase/index.ts +12 -3
  306. package/src/supabase/oauth/disconnect.ts +1 -2
  307. package/src/supabase/oauth/exchangeToken.ts +1 -3
  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 +2 -7
  311. package/src/supabase/registerCrudFunctions.ts +38 -26
  312. package/src/supabase/utils/idempotency.ts +0 -0
  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 +0 -0
  317. package/src/vercel/api/ai/index.ts +2 -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 +5 -1
  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 +0 -0
  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 +0 -0
  342. package/src/vercel/api/oauth/check-github-access.ts +0 -0
  343. package/src/vercel/api/oauth/exchange-token.ts +4 -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 +3 -1
  348. package/src/vercel/baseFunction.ts +0 -0
@@ -0,0 +1,483 @@
1
+ // packages/functions/src/shared/crud/bulkCore.ts
2
+
3
+ /**
4
+ * @fileoverview Shared bulk CRUD orchestration core.
5
+ * @description Target-agnostic orchestrator that owns the bulk policy
6
+ * (wire validation, collision detection, per-bucket ACL, per-row schema
7
+ * validation, id minting, metadata stamping, audit, response validation).
8
+ * Target storage is delegated to a caller-supplied `transact` callback —
9
+ * this lets Firestore admin, Supabase RPC, Vercel firebase-admin, future
10
+ * GraphQL and future REST-CRUD server aids share one source of truth for
11
+ * correctness without pulling any platform-specific dependencies here.
12
+ *
13
+ * This module is server-only (`shared/` but never imported from `client/`
14
+ * or `common/`) and designed to stay portable across Node and Deno — it
15
+ * does not import `fs`, `net`, `firebase-admin`, `supabase-js`, etc.
16
+ *
17
+ * @version 0.1.0
18
+ * @since 0.7.0
19
+ * @author AMBROISE PARK Consulting
20
+ */
21
+
22
+ import * as v from 'valibot';
23
+
24
+ import {
25
+ BulkCollisionError,
26
+ BulkRequestSchema,
27
+ BulkResponseSchema,
28
+ detectBulkCollisions,
29
+ DoNotDevError,
30
+ hasRoleAccess,
31
+ DEFAULT_STATUS_VALUE,
32
+ } from '@donotdev/core/server';
33
+ import type {
34
+ BulkRequest,
35
+ BulkResponse,
36
+ EntityAccessConfig,
37
+ UserRole,
38
+ } from '@donotdev/core/server';
39
+
40
+ // =============================================================================
41
+ // Public types
42
+ // =============================================================================
43
+
44
+ /**
45
+ * Valibot schema alias accepted by {@link executeBulk}. Kept loose (`any` on
46
+ * the parsed output) so callers can pass entity-specific schemas generated by
47
+ * `createSchemas()` without fighting variance.
48
+ */
49
+ export type BulkRowSchema = v.BaseSchema<unknown, any, v.BaseIssue<unknown>>;
50
+
51
+ /**
52
+ * A prepared insert row passed to the caller-supplied `transact` callback.
53
+ * When {@link ExecuteBulkParams.mintInsertId} is provided, `id` is the minted
54
+ * value; otherwise it carries whatever id (if any) the client supplied and
55
+ * the storage layer is expected to mint its own.
56
+ */
57
+ export interface PreparedInsert {
58
+ /** Minted insert id, or the empty string when the target mints its own. */
59
+ id: string;
60
+ /** Fully stamped row ready for storage. */
61
+ row: Record<string, unknown>;
62
+ }
63
+
64
+ /**
65
+ * A prepared update passed to `transact`.
66
+ */
67
+ export interface PreparedUpdate {
68
+ /** Target row id. */
69
+ id: string;
70
+ /** Fully stamped patch ready for storage. */
71
+ patch: Record<string, unknown>;
72
+ }
73
+
74
+ /**
75
+ * Payload handed to the caller-supplied `transact` callback. All three
76
+ * arrays preserve input order and only include non-empty buckets' work.
77
+ */
78
+ export interface PreparedBulk {
79
+ inserts: PreparedInsert[];
80
+ updates: PreparedUpdate[];
81
+ deletes: string[];
82
+ }
83
+
84
+ /**
85
+ * Parameters for {@link executeBulk}.
86
+ *
87
+ * @template TRow - Row type recorded for documentation; runtime is opaque.
88
+ */
89
+ export interface ExecuteBulkParams<TRow = unknown> {
90
+ /** Collection / table name. Passed through to audit + transact as metadata. */
91
+ collection: string;
92
+ /** Raw wire payload to orchestrate. Parsed with {@link BulkRequestSchema}. */
93
+ ops: BulkRequest;
94
+ /** Valibot schema validating each insert row. */
95
+ createSchema: BulkRowSchema;
96
+ /** Valibot schema validating each insert row when status === 'draft'. */
97
+ draftCreateSchema?: BulkRowSchema;
98
+ /** Valibot schema validating each update patch. */
99
+ updateSchema: BulkRowSchema;
100
+ /** Per-bucket required roles. Missing entries are treated as "no bucket allowed". */
101
+ access: EntityAccessConfig;
102
+ /** Authenticated caller id (for metadata + audit). */
103
+ uid: string;
104
+ /** Caller's role (for per-bucket ACL). */
105
+ userRole: UserRole;
106
+ /**
107
+ * Target-specific storage. Invoked exactly once when the bulk carries at
108
+ * least one op. Must run all three buckets inside one atomic transaction
109
+ * (writeBatch, runTransaction, Postgres RPC wrapping BEGIN/COMMIT, etc.)
110
+ * and return ids per bucket in input order.
111
+ *
112
+ * The returned shape is validated against `BulkResponseSchema` before
113
+ * being returned to the caller.
114
+ */
115
+ transact: (prepared: PreparedBulk) => Promise<BulkResponse>;
116
+ /**
117
+ * Optional id minting. When provided, every insert is stamped with a
118
+ * freshly-minted id before `transact` runs. When omitted, `id` on each
119
+ * {@link PreparedInsert} is the empty string and the storage layer is
120
+ * expected to mint its own ids (Supabase RPC, GraphQL server, etc.).
121
+ */
122
+ mintInsertId?: () => string;
123
+ /**
124
+ * Optional hook to stamp platform-specific metadata on every insert row
125
+ * (timestamps, createdById, defaults, field-name mapping). Called once per
126
+ * insert row, in input order.
127
+ */
128
+ stampInsertMetadata?: (
129
+ row: Record<string, unknown>,
130
+ uid: string
131
+ ) => Record<string, unknown>;
132
+ /**
133
+ * Optional hook to stamp platform-specific metadata on every update patch.
134
+ */
135
+ stampUpdateMetadata?: (
136
+ patch: Record<string, unknown>,
137
+ uid: string
138
+ ) => Record<string, unknown>;
139
+ /**
140
+ * Optional audit hook. Fires exactly once when `transact` succeeds, with the
141
+ * three op counts. Never fires for empty bulks or rejected validations —
142
+ * matches the "one audit entry" contract from `BULK_CRUD_TODO.md` §4.
143
+ */
144
+ audit?: (
145
+ event: string,
146
+ payload: {
147
+ counts: { inserts: number; updates: number; deletes: number };
148
+ }
149
+ ) => void;
150
+ /**
151
+ * Optional rate-limit bookkeeping key. `executeBulk` does NOT perform
152
+ * rate-limit enforcement itself — the surrounding base-function wrapper
153
+ * already charges one hit at entry. This field is forwarded to `audit()`
154
+ * callers that want to correlate telemetry.
155
+ */
156
+ rateLimitKey?: string;
157
+ }
158
+
159
+ // =============================================================================
160
+ // Core orchestrator
161
+ // =============================================================================
162
+
163
+ /**
164
+ * Empty response returned for a no-op bulk. Frozen so accidental mutation
165
+ * from a caller blows up at dev time instead of poisoning the next call.
166
+ */
167
+ const EMPTY_BULK_RESPONSE: BulkResponse = Object.freeze({
168
+ insertedIds: [],
169
+ updatedIds: [],
170
+ deletedIds: [],
171
+ }) as BulkResponse;
172
+
173
+ /**
174
+ * Run a bulk CRUD operation against a caller-supplied storage target.
175
+ *
176
+ * **Order of operations** (every step fails loud — no fallbacks, no partial
177
+ * writes):
178
+ *
179
+ * 1. Parse `ops` with {@link BulkRequestSchema}. Invalid shape → throws.
180
+ * 2. Collision detection via {@link detectBulkCollisions}. Collision →
181
+ * throws {@link BulkCollisionError}.
182
+ * 3. Empty short-circuit — if no op carries work, returns a zeroed
183
+ * {@link BulkResponse} without invoking `transact` or `audit`.
184
+ * 4. Per-bucket ACL — for each populated bucket, asserts the caller's role
185
+ * clears the corresponding `access.{create|update|delete}`. A missing
186
+ * role on a populated bucket is a configuration error and is rejected.
187
+ * 5. Per-row validation — inserts against `createSchema`, updates against
188
+ * `updateSchema`. The first failure throws a `DoNotDevError` prefixed
189
+ * with `inserts[i]` or `updates[i]` so callers can pinpoint the row.
190
+ * 6. Id minting — if `mintInsertId` is supplied, every insert gets a fresh
191
+ * id stamped onto its {@link PreparedInsert}. Otherwise `id` is `""` and
192
+ * the storage layer mints its own.
193
+ * 7. Metadata stamping — `stampInsertMetadata` / `stampUpdateMetadata` run
194
+ * per row / per patch if provided.
195
+ * 8. `transact(prepared)` runs exactly once. Must be atomic. Throws
196
+ * propagate unchanged so the caller's error handler can classify them.
197
+ * 9. Response-shape validation via {@link BulkResponseSchema}. A non-conforming
198
+ * target response throws `DoNotDevError(internal)`.
199
+ * 10. `audit()` fires once with the three op counts.
200
+ *
201
+ * **Not this function's job:** rate-limiting, authentication, HTTP status
202
+ * mapping, target-specific connection pooling, retry policy. All of those
203
+ * belong to the surrounding handler wrapper.
204
+ *
205
+ * @template TRow - Row type (documentation only).
206
+ * @param params - See {@link ExecuteBulkParams}.
207
+ * @returns The validated {@link BulkResponse} from the target.
208
+ *
209
+ * @throws {BulkCollisionError} When the payload contains the same id in
210
+ * two mutually-exclusive buckets.
211
+ * @throws {DoNotDevError} `invalid-argument` on wire-schema failure, per-row
212
+ * validation failure, or collision (wrapped for callers that only rethrow
213
+ * `DoNotDevError`).
214
+ * @throws {DoNotDevError} `permission-denied` when the caller's role cannot
215
+ * satisfy a populated bucket's access requirement.
216
+ * @throws {DoNotDevError} `internal` when the `transact` return value fails
217
+ * {@link BulkResponseSchema}.
218
+ *
219
+ * @example
220
+ * ```typescript
221
+ * import { executeBulk } from '@donotdev/functions/shared';
222
+ * import { BulkResponseSchema } from '@donotdev/core/server';
223
+ *
224
+ * const response = await executeBulk({
225
+ * collection: 'events',
226
+ * ops: req.body,
227
+ * createSchema,
228
+ * updateSchema,
229
+ * access,
230
+ * uid,
231
+ * userRole,
232
+ * mintInsertId: () => crypto.randomUUID(),
233
+ * stampInsertMetadata: (row, uid) => ({
234
+ * ...row,
235
+ * createdById: uid,
236
+ * createdAt: new Date().toISOString(),
237
+ * }),
238
+ * transact: async ({ inserts, updates, deletes }) => {
239
+ * return db.runTransaction(async (tx) => {
240
+ * for (const { id, row } of inserts) tx.set(col.doc(id), row);
241
+ * for (const { id, patch } of updates) tx.update(col.doc(id), patch);
242
+ * for (const id of deletes) tx.delete(col.doc(id));
243
+ * return {
244
+ * insertedIds: inserts.map((i) => i.id),
245
+ * updatedIds: updates.map((u) => u.id),
246
+ * deletedIds: deletes,
247
+ * };
248
+ * });
249
+ * },
250
+ * audit: (event, { counts }) => logger.info(event, counts),
251
+ * });
252
+ * ```
253
+ *
254
+ * @version 0.1.0
255
+ * @since 0.7.0
256
+ * @author AMBROISE PARK Consulting
257
+ */
258
+ export async function executeBulk<TRow = unknown>(
259
+ params: ExecuteBulkParams<TRow>
260
+ ): Promise<BulkResponse> {
261
+ const {
262
+ collection,
263
+ ops,
264
+ createSchema,
265
+ draftCreateSchema,
266
+ updateSchema,
267
+ access,
268
+ uid,
269
+ userRole,
270
+ transact,
271
+ mintInsertId,
272
+ stampInsertMetadata,
273
+ stampUpdateMetadata,
274
+ audit,
275
+ } = params;
276
+
277
+ // 1. Wire-schema validation. Guarantees the three buckets are arrays of
278
+ // the right shape; per-field entity validation happens in step 5.
279
+ const parsed = v.safeParse(BulkRequestSchema, ops);
280
+ if (!parsed.success) {
281
+ const messages = parsed.issues
282
+ .map(
283
+ (issue) =>
284
+ `${issue.path?.map((p: any) => p.key).join('.') || 'root'}: ${issue.message}`
285
+ )
286
+ .join('; ');
287
+ throw new DoNotDevError(
288
+ `Bulk payload validation failed: ${messages}`,
289
+ 'invalid-argument',
290
+ { details: { validationErrors: parsed.issues } }
291
+ );
292
+ }
293
+ const request: BulkRequest = parsed.output;
294
+
295
+ const inserts = request.inserts ?? [];
296
+ const updates = request.updates ?? [];
297
+ const deletes = request.deletes ?? [];
298
+
299
+ // 2. Collision detection. Rejects ambiguous intents BEFORE any further
300
+ // work so a rate-limit hit + HTTP round-trip never buys a partial
301
+ // validation pass only to fail later.
302
+ const collision = detectBulkCollisions(request);
303
+ if (collision.where !== null) {
304
+ throw new BulkCollisionError(collision.collisions, collision.where);
305
+ }
306
+
307
+ // 3. Empty bulk short-circuit. Per `BULK_CRUD_TODO.md` §8 this never
308
+ // touches the storage layer, never fires audit, and returns a frozen
309
+ // empty response shared across calls (safe — consumers never mutate).
310
+ if (inserts.length === 0 && updates.length === 0 && deletes.length === 0) {
311
+ return EMPTY_BULK_RESPONSE;
312
+ }
313
+
314
+ // 4. Per-bucket ACL. The surrounding base-function wrapper already cleared
315
+ // the weakest role; we re-check each populated bucket so mixed-ACL
316
+ // entities reject precisely. A populated bucket with no configured
317
+ // role is a config error — fail loud rather than silently allow.
318
+ if (inserts.length > 0) {
319
+ if (!access.create) {
320
+ throw new DoNotDevError(
321
+ `Bulk insert requested on ${collection} but no create role is configured`,
322
+ 'permission-denied'
323
+ );
324
+ }
325
+ if (!hasRoleAccess(userRole, access.create)) {
326
+ throw new DoNotDevError(
327
+ `Access denied for bulk insert on ${collection}. Required: ${access.create}, your role: ${userRole}`,
328
+ 'permission-denied'
329
+ );
330
+ }
331
+ }
332
+ if (updates.length > 0) {
333
+ if (!access.update) {
334
+ throw new DoNotDevError(
335
+ `Bulk update requested on ${collection} but no update role is configured`,
336
+ 'permission-denied'
337
+ );
338
+ }
339
+ if (!hasRoleAccess(userRole, access.update)) {
340
+ throw new DoNotDevError(
341
+ `Access denied for bulk update on ${collection}. Required: ${access.update}, your role: ${userRole}`,
342
+ 'permission-denied'
343
+ );
344
+ }
345
+ }
346
+ if (deletes.length > 0) {
347
+ if (!access.delete) {
348
+ throw new DoNotDevError(
349
+ `Bulk delete requested on ${collection} but no delete role is configured`,
350
+ 'permission-denied'
351
+ );
352
+ }
353
+ if (!hasRoleAccess(userRole, access.delete)) {
354
+ throw new DoNotDevError(
355
+ `Access denied for bulk delete on ${collection}. Required: ${access.delete}, your role: ${userRole}`,
356
+ 'permission-denied'
357
+ );
358
+ }
359
+ }
360
+
361
+ // 5. Per-row validation. First failure wins — prefixed with its bucket
362
+ // index so callers can point at the offending row.
363
+ for (let i = 0; i < inserts.length; i++) {
364
+ const row = inserts[i]!;
365
+ const rowObj = row as unknown as Record<string, unknown>;
366
+ const status =
367
+ (rowObj.status as string | undefined) ?? DEFAULT_STATUS_VALUE;
368
+ const isDraft = status === 'draft';
369
+ const schemaToUse =
370
+ isDraft && draftCreateSchema ? draftCreateSchema : createSchema;
371
+ // Only inject default `status` when validating against the draft schema.
372
+ // This avoids breaking createSchema-only tests/entities that don't define
373
+ // `status` in their schema shape (valibot's `v.object` is strict by
374
+ // default).
375
+ const payloadForValidation =
376
+ isDraft && draftCreateSchema ? { ...rowObj, status } : rowObj;
377
+ validateRow(payloadForValidation, schemaToUse, `inserts[${i}]`);
378
+ }
379
+ for (let i = 0; i < updates.length; i++) {
380
+ validateRow(updates[i]!.patch, updateSchema, `updates[${i}]`);
381
+ }
382
+
383
+ // 6. Id minting (if provided). Minting at this layer means `transact`
384
+ // receives stable ids — crucial for Firestore's retry-able transaction
385
+ // callbacks where the callback body may run more than once.
386
+ const preparedInserts: PreparedInsert[] = inserts.map((row) => {
387
+ const rowRecord = row as unknown as Record<string, unknown>;
388
+ // Always ensure status is present for storage + downstream schema
389
+ // stamping. Validation may have used `draftCreateSchema` to relax
390
+ // required-field enforcement, but storage should still persist a
391
+ // concrete status value.
392
+ const status =
393
+ (rowRecord.status as string | undefined) ?? DEFAULT_STATUS_VALUE;
394
+ const id = mintInsertId ? mintInsertId() : '';
395
+ const stamped = stampInsertMetadata
396
+ ? stampInsertMetadata({ ...rowRecord, status }, uid)
397
+ : ({ ...rowRecord, status } as Record<string, unknown>);
398
+ return { id, row: stamped };
399
+ });
400
+
401
+ // 7. Update metadata stamping.
402
+ const preparedUpdates: PreparedUpdate[] = updates.map((u) => ({
403
+ id: u.id,
404
+ patch: stampUpdateMetadata
405
+ ? stampUpdateMetadata(u.patch as Record<string, unknown>, uid)
406
+ : (u.patch as Record<string, unknown>),
407
+ }));
408
+
409
+ // 8. Atomic dispatch. Propagates any `transact` error verbatim — the
410
+ // surrounding handler wrapper classifies into HTTP / callable codes.
411
+ const raw = await transact({
412
+ inserts: preparedInserts,
413
+ updates: preparedUpdates,
414
+ deletes: [...deletes],
415
+ });
416
+
417
+ // 9. Response-shape validation at the wire boundary. Drift between a
418
+ // target's return shape and `BulkResponseSchema` would silently corrupt
419
+ // clients that zip ids back onto optimistic entries — fail loud.
420
+ const responseParse = v.safeParse(BulkResponseSchema, raw);
421
+ if (!responseParse.success) {
422
+ throw new DoNotDevError(
423
+ `Bulk transact() returned an unexpected shape for ${collection}`,
424
+ 'internal'
425
+ );
426
+ }
427
+
428
+ // 10. One audit entry, counts only (never row ids — anomaly detection
429
+ // fires on the bulk count per contract §4).
430
+ if (audit) {
431
+ audit(`crud.bulk.${collection}`, {
432
+ counts: {
433
+ inserts: preparedInserts.length,
434
+ updates: preparedUpdates.length,
435
+ deletes: deletes.length,
436
+ },
437
+ });
438
+ }
439
+
440
+ return responseParse.output;
441
+ }
442
+
443
+ // =============================================================================
444
+ // Internal helpers
445
+ // =============================================================================
446
+
447
+ /**
448
+ * Validate a row against a Valibot schema and rethrow a `DoNotDevError`
449
+ * prefixed with the bucket position so callers can point at the offending
450
+ * row. Keeps the hot path free of try/catch overhead when no schema is
451
+ * supplied.
452
+ *
453
+ * @param value - Row or patch to validate.
454
+ * @param schema - Valibot schema.
455
+ * @param locator - Human-readable pointer such as `inserts[2]`.
456
+ *
457
+ * @example
458
+ * ```typescript
459
+ * validateRow(inserts[i], createSchema, `inserts[${i}]`);
460
+ * ```
461
+ *
462
+ * @internal
463
+ */
464
+ function validateRow(
465
+ value: unknown,
466
+ schema: BulkRowSchema,
467
+ locator: string
468
+ ): void {
469
+ const parsed = v.safeParse(schema, value);
470
+ if (parsed.success) return;
471
+
472
+ const messages = parsed.issues
473
+ .map(
474
+ (issue) =>
475
+ `${issue.path?.map((p: any) => p.key).join('.') || 'root'}: ${issue.message}`
476
+ )
477
+ .join('; ');
478
+ throw new DoNotDevError(
479
+ `Validation failed on ${locator}: ${messages}`,
480
+ 'invalid-argument',
481
+ { details: { validationErrors: parsed.issues } }
482
+ );
483
+ }
@@ -0,0 +1,23 @@
1
+ // packages/functions/src/shared/crud/index.ts
2
+
3
+ /**
4
+ * @fileoverview Shared CRUD orchestration primitives.
5
+ * @description Barrel for the target-agnostic CRUD cores that Firestore,
6
+ * Supabase, Vercel, GraphQL and REST-CRUD server aids all consume.
7
+ * Exported from `@donotdev/functions/shared` (and the root entry) so
8
+ * out-of-package consumers can build their own adapters without pulling
9
+ * a target-specific SDK.
10
+ *
11
+ * @version 0.1.0
12
+ * @since 0.7.0
13
+ * @author AMBROISE PARK Consulting
14
+ */
15
+
16
+ export {
17
+ executeBulk,
18
+ type ExecuteBulkParams,
19
+ type PreparedBulk,
20
+ type PreparedInsert,
21
+ type PreparedUpdate,
22
+ type BulkRowSchema,
23
+ } from './bulkCore.js';
File without changes
File without changes
File without changes
@@ -38,7 +38,7 @@ export function createResendProvider(apiKey: string): EmailProviderAdapter {
38
38
  const response = await fetch(RESEND_API_URL, {
39
39
  method: 'POST',
40
40
  headers: {
41
- 'Authorization': `Bearer ${apiKey}`,
41
+ Authorization: `Bearer ${apiKey}`,
42
42
  'Content-Type': 'application/json',
43
43
  },
44
44
  body: JSON.stringify(body),
File without changes
File without changes
File without changes
@@ -54,6 +54,15 @@ export * from './schema.js';
54
54
  */
55
55
  export * from './utils/index.js';
56
56
 
57
+ /**
58
+ * Shared CRUD orchestration core (executeBulk, ExecuteBulkParams, ...).
59
+ *
60
+ * @version 0.1.0
61
+ * @since 0.7.0
62
+ * @author AMBROISE PARK Consulting
63
+ */
64
+ export * from './crud/index.js';
65
+
57
66
  /**
58
67
  * Billing utilities
59
68
  *
@@ -14,6 +14,7 @@ export * from './github.js';
14
14
  export * from './metadata.js';
15
15
  export * from './schema.js';
16
16
  export * from './utils/index.js';
17
+ export * from './crud/index.js';
17
18
  export * from './ai/index.js';
18
19
  export * from './billing/index.js';
19
20
  export * from './email/index.js';
File without changes
@@ -21,10 +21,10 @@
21
21
  export function createMetadata(userId: string) {
22
22
  const now = new Date().toISOString();
23
23
  return {
24
- _createdAt: now,
25
- _updatedAt: now,
26
- _createdBy: userId,
27
- _updatedBy: userId,
24
+ createdAt: now,
25
+ updatedAt: now,
26
+ createdById: userId,
27
+ updatedById: userId,
28
28
  };
29
29
  }
30
30
 
@@ -39,7 +39,7 @@ export function createMetadata(userId: string) {
39
39
  */
40
40
  export function updateMetadata(userId: string) {
41
41
  return {
42
- _updatedAt: new Date().toISOString(),
43
- _updatedBy: userId,
42
+ updatedAt: new Date().toISOString(),
43
+ updatedById: userId,
44
44
  };
45
45
  }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes