@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,322 @@
1
+ // packages/functions/src/firebase/crud/__tests__/bulk.test.ts
2
+
3
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
4
+
5
+ // Mock firebase-functions logger before the module under test imports it.
6
+ vi.mock('firebase-functions/v2', () => ({
7
+ logger: {
8
+ info: vi.fn(),
9
+ warn: vi.fn(),
10
+ error: vi.fn(),
11
+ log: vi.fn(),
12
+ },
13
+ }));
14
+
15
+ // Firestore Admin mock — minted ids, a transaction stub that records every
16
+ // tx.set / tx.update / tx.delete call in input order, and a handle to force
17
+ // the transaction body to throw (simulates ROLLBACK).
18
+ interface MockRef {
19
+ id: string;
20
+ }
21
+
22
+ const txCalls: Array<
23
+ | { op: 'set'; ref: MockRef; data: any }
24
+ | { op: 'update'; ref: MockRef; data: any }
25
+ | { op: 'delete'; ref: MockRef }
26
+ > = [];
27
+
28
+ let mintedIdCounter = 0;
29
+ let runTransactionInvocations = 0;
30
+ let simulateRollback: Error | null = null;
31
+
32
+ const mockDocRef = (id?: string): MockRef => {
33
+ if (id) return { id };
34
+ mintedIdCounter += 1;
35
+ return { id: `minted-${mintedIdCounter}` };
36
+ };
37
+
38
+ const mockCollection = () => ({
39
+ doc: (id?: string) => mockDocRef(id),
40
+ });
41
+
42
+ const tx = {
43
+ set: vi.fn((ref: MockRef, data: any) => {
44
+ txCalls.push({ op: 'set', ref, data });
45
+ }),
46
+ update: vi.fn((ref: MockRef, data: any) => {
47
+ txCalls.push({ op: 'update', ref, data });
48
+ }),
49
+ delete: vi.fn((ref: MockRef) => {
50
+ txCalls.push({ op: 'delete', ref });
51
+ }),
52
+ };
53
+
54
+ const mockDb = {
55
+ collection: vi.fn(() => mockCollection()),
56
+ runTransaction: vi.fn(async (fn: (t: typeof tx) => Promise<any>) => {
57
+ runTransactionInvocations += 1;
58
+ if (simulateRollback) {
59
+ // Fire the callback so any validation throw inside still surfaces, then
60
+ // propagate the rollback error.
61
+ try {
62
+ await fn(tx);
63
+ } catch {
64
+ /* swallow — we propagate the rollback error below */
65
+ }
66
+ throw simulateRollback;
67
+ }
68
+ return fn(tx);
69
+ }),
70
+ };
71
+
72
+ vi.mock('@donotdev/firebase/server', () => ({
73
+ getFirebaseAdminFirestore: () => mockDb,
74
+ }));
75
+
76
+ // Import AFTER mocks are in place.
77
+ import { bulkEntityLogicFactory } from '../bulk';
78
+ import { BulkCollisionError } from '@donotdev/core/server';
79
+ import * as v from 'valibot';
80
+
81
+ // ---------------------------------------------------------------------------
82
+ // Fixtures
83
+ // ---------------------------------------------------------------------------
84
+
85
+ const createSchema = v.object({
86
+ name: v.string(),
87
+ });
88
+ const updateSchema = v.object({
89
+ name: v.optional(v.string()),
90
+ });
91
+
92
+ const access = {
93
+ create: 'user' as const,
94
+ update: 'user' as const,
95
+ delete: 'user' as const,
96
+ };
97
+
98
+ const ctx = {
99
+ uid: 'tester-uid',
100
+ userRole: 'user' as const,
101
+ request: {} as any,
102
+ };
103
+
104
+ const COLLECTION = 'cars';
105
+
106
+ function resetState() {
107
+ txCalls.length = 0;
108
+ mintedIdCounter = 0;
109
+ runTransactionInvocations = 0;
110
+ simulateRollback = null;
111
+ tx.set.mockClear();
112
+ tx.update.mockClear();
113
+ tx.delete.mockClear();
114
+ mockDb.collection.mockClear();
115
+ mockDb.runTransaction.mockClear();
116
+ }
117
+
118
+ // ---------------------------------------------------------------------------
119
+ // Tests
120
+ // ---------------------------------------------------------------------------
121
+
122
+ describe('bulkEntityLogicFactory', () => {
123
+ beforeEach(resetState);
124
+
125
+ it('happy path: 2 inserts + 1 update + 1 delete preserves input order', async () => {
126
+ const logic = bulkEntityLogicFactory(
127
+ COLLECTION,
128
+ createSchema,
129
+ updateSchema,
130
+ access
131
+ );
132
+
133
+ const result = await logic(
134
+ {
135
+ inserts: [{ name: 'Alpha' }, { name: 'Beta' }],
136
+ updates: [{ id: 'u1', patch: { name: 'Updated' } }],
137
+ deletes: ['d1'],
138
+ },
139
+ ctx
140
+ );
141
+
142
+ // Single transaction — the core atomicity contract.
143
+ expect(runTransactionInvocations).toBe(1);
144
+
145
+ // Response shape and input-order id preservation.
146
+ expect(result.insertedIds).toEqual(['minted-1', 'minted-2']);
147
+ expect(result.updatedIds).toEqual(['u1']);
148
+ expect(result.deletedIds).toEqual(['d1']);
149
+
150
+ // All ops issued within the transaction, in input order:
151
+ // [insert, insert, update, delete].
152
+ expect(txCalls.map((c) => c.op)).toEqual([
153
+ 'set',
154
+ 'set',
155
+ 'update',
156
+ 'delete',
157
+ ]);
158
+
159
+ // Inserts carry metadata + status.
160
+ const insertCalls = txCalls.filter((c) => c.op === 'set');
161
+ for (const call of insertCalls) {
162
+ expect(call.data.createdById).toBe('tester-uid');
163
+ expect(call.data.updatedById).toBe('tester-uid');
164
+ expect(call.data.status).toBeDefined();
165
+ }
166
+
167
+ // Update patch carries updatedBy metadata.
168
+ const updateCall = txCalls.find((c) => c.op === 'update') as {
169
+ data: any;
170
+ };
171
+ expect(updateCall.data.updatedById).toBe('tester-uid');
172
+ });
173
+
174
+ it('empty bulk returns zeroed response without opening a transaction', async () => {
175
+ const logic = bulkEntityLogicFactory(
176
+ COLLECTION,
177
+ createSchema,
178
+ updateSchema,
179
+ access
180
+ );
181
+
182
+ const result = await logic({}, ctx);
183
+
184
+ expect(result).toEqual({
185
+ insertedIds: [],
186
+ updatedIds: [],
187
+ deletedIds: [],
188
+ });
189
+ expect(runTransactionInvocations).toBe(0);
190
+ expect(mockDb.collection).not.toHaveBeenCalled();
191
+ });
192
+
193
+ it('empty bulk is idempotent across repeated calls', async () => {
194
+ const logic = bulkEntityLogicFactory(
195
+ COLLECTION,
196
+ createSchema,
197
+ updateSchema,
198
+ access
199
+ );
200
+
201
+ const first = await logic({}, ctx);
202
+ const second = await logic({ inserts: [], updates: [], deletes: [] }, ctx);
203
+
204
+ expect(first).toEqual(second);
205
+ expect(runTransactionInvocations).toBe(0);
206
+ });
207
+
208
+ it('rejects with BulkCollisionError when id is in updates AND deletes', async () => {
209
+ const logic = bulkEntityLogicFactory(
210
+ COLLECTION,
211
+ createSchema,
212
+ updateSchema,
213
+ access
214
+ );
215
+
216
+ await expect(
217
+ logic(
218
+ {
219
+ updates: [{ id: 'shared', patch: { name: 'X' } }],
220
+ deletes: ['shared'],
221
+ },
222
+ ctx
223
+ )
224
+ ).rejects.toBeInstanceOf(BulkCollisionError);
225
+
226
+ // No transaction opened.
227
+ expect(runTransactionInvocations).toBe(0);
228
+ expect(txCalls.length).toBe(0);
229
+ });
230
+
231
+ it('rejects insert that fails createSchema without opening a transaction', async () => {
232
+ const logic = bulkEntityLogicFactory(
233
+ COLLECTION,
234
+ createSchema,
235
+ updateSchema,
236
+ access
237
+ );
238
+
239
+ await expect(
240
+ logic(
241
+ {
242
+ // `name` missing — fails createSchema.
243
+ inserts: [{ bogus: 'field' } as any],
244
+ },
245
+ ctx
246
+ )
247
+ ).rejects.toThrow(/Validation failed/);
248
+
249
+ expect(runTransactionInvocations).toBe(0);
250
+ expect(txCalls.length).toBe(0);
251
+ });
252
+
253
+ it('fails on ACL — caller lacks delete access and request contains deletes', async () => {
254
+ const strictAccess = {
255
+ create: 'user' as const,
256
+ update: 'user' as const,
257
+ delete: 'admin' as const,
258
+ };
259
+ const logic = bulkEntityLogicFactory(
260
+ COLLECTION,
261
+ createSchema,
262
+ updateSchema,
263
+ strictAccess
264
+ );
265
+
266
+ await expect(
267
+ logic(
268
+ {
269
+ inserts: [{ name: 'OK' }],
270
+ deletes: ['d1'],
271
+ },
272
+ ctx // userRole: 'user' — cannot delete.
273
+ )
274
+ ).rejects.toThrow(/Access denied for bulk delete/);
275
+
276
+ expect(runTransactionInvocations).toBe(0);
277
+ expect(txCalls.length).toBe(0);
278
+ });
279
+
280
+ it('allows inserts-only when caller has create but not delete access', async () => {
281
+ const strictAccess = {
282
+ create: 'user' as const,
283
+ update: 'user' as const,
284
+ delete: 'admin' as const,
285
+ };
286
+ const logic = bulkEntityLogicFactory(
287
+ COLLECTION,
288
+ createSchema,
289
+ updateSchema,
290
+ strictAccess
291
+ );
292
+
293
+ const result = await logic({ inserts: [{ name: 'Alpha' }] }, ctx);
294
+
295
+ expect(result.insertedIds).toHaveLength(1);
296
+ expect(result.deletedIds).toEqual([]);
297
+ expect(runTransactionInvocations).toBe(1);
298
+ });
299
+
300
+ it('propagates transaction rollback errors (no partial writes surfaced)', async () => {
301
+ const logic = bulkEntityLogicFactory(
302
+ COLLECTION,
303
+ createSchema,
304
+ updateSchema,
305
+ access
306
+ );
307
+
308
+ simulateRollback = new Error('Firestore transaction aborted');
309
+
310
+ await expect(
311
+ logic(
312
+ {
313
+ inserts: [{ name: 'Alpha' }],
314
+ },
315
+ ctx
316
+ )
317
+ ).rejects.toThrow('Firestore transaction aborted');
318
+
319
+ // Transaction was opened, but caller sees the rollback.
320
+ expect(runTransactionInvocations).toBe(1);
321
+ });
322
+ });
File without changes
@@ -0,0 +1,272 @@
1
+ // packages/functions/src/firebase/crud/bulk.ts
2
+
3
+ /**
4
+ * @fileoverview Firebase bulk CRUD handler.
5
+ * @description Thin Firestore adapter on top of the shared `executeBulk`
6
+ * orchestrator. Assembles a firebase-admin `runTransaction` as the
7
+ * target-specific `transact` callback and keeps the wire contract
8
+ * frozen: one HTTP round-trip, one transaction, one audit line, one
9
+ * rate-limit hit. Validation + collision + per-bucket ACL + metadata
10
+ * stamping all live in {@link executeBulk}.
11
+ *
12
+ * @version 0.2.0
13
+ * @since 0.2.0
14
+ * @author AMBROISE PARK Consulting
15
+ */
16
+
17
+ import { logger } from 'firebase-functions/v2';
18
+ import * as v from 'valibot';
19
+
20
+ import { BulkRequestSchema, DEFAULT_STATUS_VALUE } from '@donotdev/core/server';
21
+ import type {
22
+ BulkRequest,
23
+ BulkResponse,
24
+ UserRole,
25
+ } from '@donotdev/core/server';
26
+ import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
27
+
28
+ import {
29
+ createMetadata,
30
+ executeBulk,
31
+ prepareForFirestore,
32
+ updateMetadata,
33
+ } from '../../shared/index.js';
34
+ import { createBaseFunction } from '../baseFunction.js';
35
+ import { CRUD_CONFIG } from '../config/constants.js';
36
+
37
+ import type {
38
+ CallableFunction,
39
+ CallableRequest,
40
+ } from 'firebase-functions/v2/https';
41
+
42
+ /**
43
+ * Request type for the bulk endpoint. Identical to the wire schema; kept as a
44
+ * named alias for parity with `CreateEntityRequest`, `UpdateEntityRequest`, etc.
45
+ */
46
+ export type BulkEntityRequest = BulkRequest;
47
+
48
+ /**
49
+ * Per-operation access split. The three write access roles are passed
50
+ * individually so the factory can enforce them independently when a request
51
+ * mixes op kinds (e.g. only the delete bucket fails ACL).
52
+ */
53
+ interface BulkAccess {
54
+ /** Minimum role to insert into the collection. */
55
+ create: UserRole;
56
+ /** Minimum role to update existing rows. */
57
+ update: UserRole;
58
+ /** Minimum role to delete rows. */
59
+ delete: UserRole;
60
+ }
61
+
62
+ /**
63
+ * Build the business-logic function consumed by {@link createBaseFunction}.
64
+ *
65
+ * Exported for unit testing only — the public entry is {@link bulkEntity}
66
+ * which wraps this factory with auth, role, rate-limit, and schema
67
+ * validation at the transport boundary.
68
+ *
69
+ * The logic itself is a pure delegation to {@link executeBulk}; the only
70
+ * Firestore-specific code lives inside the `transact` closure which issues
71
+ * `tx.set / tx.update / tx.delete` on pre-minted `doc()` references.
72
+ *
73
+ * @internal
74
+ *
75
+ * @example
76
+ * ```typescript
77
+ * const logic = bulkEntityLogicFactory('cars', createSchema, updateSchema, {
78
+ * create: 'user', update: 'user', delete: 'admin',
79
+ * });
80
+ * await logic({ inserts: [{ name: 'a' }] }, { uid: 'u', userRole: 'user', request: req });
81
+ * ```
82
+ *
83
+ * @version 0.2.0
84
+ * @since 0.2.0
85
+ */
86
+ export function bulkEntityLogicFactory(
87
+ collection: string,
88
+ createSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
89
+ draftCreateSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
90
+ updateSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
91
+ access: BulkAccess
92
+ ) {
93
+ return async function bulkEntityLogic(
94
+ data: BulkEntityRequest,
95
+ context: { uid: string; userRole: UserRole; request: CallableRequest<any> }
96
+ ): Promise<BulkResponse> {
97
+ const { uid, userRole } = context;
98
+
99
+ // `getFirebaseAdminFirestore()` / `.collection()` are lazy — resolved only
100
+ // when a populated bucket forces `executeBulk` past its empty
101
+ // short-circuit. Keeps the no-op bulk contract free of DB touches.
102
+ let cachedCollectionRef: ReturnType<
103
+ ReturnType<typeof getFirebaseAdminFirestore>['collection']
104
+ > | null = null;
105
+ const col = () => {
106
+ if (!cachedCollectionRef) {
107
+ cachedCollectionRef =
108
+ getFirebaseAdminFirestore().collection(collection);
109
+ }
110
+ return cachedCollectionRef;
111
+ };
112
+
113
+ return executeBulk({
114
+ collection,
115
+ ops: data,
116
+ createSchema,
117
+ draftCreateSchema,
118
+ updateSchema,
119
+ access,
120
+ uid,
121
+ userRole,
122
+ // Mint ids via Firestore's `doc()` — gives us stable ids across retry
123
+ // of the transaction callback (Firestore may run it more than once).
124
+ mintInsertId: () => col().doc().id,
125
+ stampInsertMetadata: (row, creatorUid) => {
126
+ const status =
127
+ (row.status as string | undefined) ?? DEFAULT_STATUS_VALUE;
128
+ return {
129
+ ...prepareForFirestore(row),
130
+ status,
131
+ ...createMetadata(creatorUid),
132
+ };
133
+ },
134
+ stampUpdateMetadata: (patch, editorUid) => ({
135
+ ...prepareForFirestore(patch),
136
+ ...updateMetadata(editorUid),
137
+ }),
138
+ transact: async ({ inserts, updates, deletes }) => {
139
+ const collectionRef = col();
140
+ return getFirebaseAdminFirestore().runTransaction(async (tx) => {
141
+ const insertedIds: string[] = [];
142
+ const updatedIds: string[] = [];
143
+ const deletedIds: string[] = [];
144
+
145
+ // Writes are issued synchronously on the transaction object — no
146
+ // Promise.all — so Firestore sees a deterministic op sequence.
147
+ for (const { id, row } of inserts) {
148
+ tx.set(collectionRef.doc(id), row);
149
+ insertedIds.push(id);
150
+ }
151
+ for (const { id, patch } of updates) {
152
+ tx.update(collectionRef.doc(id), patch);
153
+ updatedIds.push(id);
154
+ }
155
+ for (const id of deletes) {
156
+ tx.delete(collectionRef.doc(id));
157
+ deletedIds.push(id);
158
+ }
159
+
160
+ return { insertedIds, updatedIds, deletedIds };
161
+ });
162
+ },
163
+ audit: (event, { counts }) => {
164
+ logger.info(event, {
165
+ uid,
166
+ collection,
167
+ inserts: counts.inserts,
168
+ updates: counts.updates,
169
+ deletes: counts.deletes,
170
+ });
171
+ },
172
+ });
173
+ };
174
+ }
175
+
176
+ /**
177
+ * Generic function to perform transactional bulk CRUD in any Firestore
178
+ * collection. Auto-registered as `bulk_${collection}` by
179
+ * {@link createCrudFunctions}.
180
+ *
181
+ * **Atomicity contract** — all inserts / updates / deletes succeed or none
182
+ * do. On any failure the entire Firestore transaction is rolled back and the
183
+ * error is surfaced to the caller via `DoNotDevError`.
184
+ *
185
+ * **One of everything** — one HTTP round-trip, one transaction, one audit
186
+ * entry (`crud.bulk.${collection}` with counts), one rate-limit hit (at
187
+ * `createBaseFunction` entry). Collisions and schema validation fail *before*
188
+ * the transaction is opened.
189
+ *
190
+ * @param collection - The Firestore collection name.
191
+ * @param createSchema - Valibot schema to validate each insert payload.
192
+ * @param updateSchema - Valibot schema to validate each update patch.
193
+ * @param access - Required roles split per op kind.
194
+ * @returns Firebase callable function returning a `BulkResponse`.
195
+ *
196
+ * @throws {BulkCollisionError} When the same id appears in `updates`+`deletes`
197
+ * or `inserts`+`updates`. No writes are attempted.
198
+ * @throws {DoNotDevError} `permission-denied` when the caller lacks the
199
+ * per-op role (e.g. includes deletes but has no delete access).
200
+ * @throws {DoNotDevError} `invalid-argument` when any insert fails
201
+ * `createSchema` or any update patch fails `updateSchema`. Transaction is
202
+ * not opened.
203
+ *
204
+ * @example
205
+ * ```typescript
206
+ * // Usually wired automatically by createCrudFunctions:
207
+ * import { createCrudFunctions } from '@donotdev/functions/firebase';
208
+ * import * as entities from 'entities';
209
+ *
210
+ * export const crud = createCrudFunctions(entities);
211
+ * // → crud.bulk_cars, crud.bulk_orders, etc.
212
+ *
213
+ * // Manual wiring:
214
+ * import { bulkEntity } from '@donotdev/functions/firebase';
215
+ * import { createSchemas } from '@donotdev/core/server';
216
+ * import { carEntity } from './entities/car';
217
+ *
218
+ * const schemas = createSchemas(carEntity);
219
+ * export const bulk_cars = bulkEntity(
220
+ * carEntity.collection,
221
+ * schemas.create,
222
+ * schemas.update,
223
+ * carEntity.access,
224
+ * );
225
+ * ```
226
+ *
227
+ * @version 0.2.0
228
+ * @since 0.2.0
229
+ * @author AMBROISE PARK Consulting
230
+ */
231
+ export const bulkEntity = (
232
+ collection: string,
233
+ createSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
234
+ draftCreateSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
235
+ updateSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
236
+ access: BulkAccess
237
+ ): CallableFunction<BulkEntityRequest, Promise<BulkResponse>> => {
238
+ // The weakest role across the three ops is the function-level gate — a
239
+ // caller who can insert but not delete should still reach the handler so we
240
+ // can return a precise per-op permission-denied if they attempt a delete.
241
+ const requiredRole = weakestRole(access);
242
+
243
+ return createBaseFunction(
244
+ CRUD_CONFIG,
245
+ BulkRequestSchema,
246
+ `bulk_${collection}`,
247
+ bulkEntityLogicFactory(
248
+ collection,
249
+ createSchema,
250
+ draftCreateSchema,
251
+ updateSchema,
252
+ access
253
+ ),
254
+ requiredRole
255
+ );
256
+ };
257
+
258
+ /**
259
+ * Returns the weakest (most-permissive) role across the three bulk op kinds.
260
+ * Role hierarchy: `guest < user < admin < super`.
261
+ *
262
+ * @param access - Per-op roles.
263
+ * @returns The role that satisfies at least one of the three ops.
264
+ */
265
+ function weakestRole(access: BulkAccess): UserRole {
266
+ const order: UserRole[] = ['guest', 'user', 'admin', 'super'];
267
+ const rank = (r: UserRole) => order.indexOf(r);
268
+ const min = [access.create, access.update, access.delete].reduce((a, b) =>
269
+ rank(a) <= rank(b) ? a : b
270
+ );
271
+ return min;
272
+ }
@@ -12,7 +12,6 @@
12
12
  import { logger } from 'firebase-functions/v2';
13
13
  import * as v from 'valibot';
14
14
 
15
- import { DEFAULT_STATUS_VALUE } from '@donotdev/core/server';
16
15
  import type { UserRole, UniqueKeyDefinition } from '@donotdev/core/server';
17
16
  import { getFirebaseAdminFirestore } from '@donotdev/firebase/server';
18
17
 
@@ -150,7 +149,8 @@ async function checkUniqueKeys(
150
149
  */
151
150
  function createEntityLogicFactory(
152
151
  collection: string,
153
- documentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>
152
+ createDocumentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
153
+ draftDocumentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>
154
154
  ) {
155
155
  return async function createEntityLogic(
156
156
  data: CreateEntityRequest,
@@ -209,13 +209,13 @@ function createEntityLogicFactory(
209
209
  }
210
210
  }
211
211
 
212
- // Determine status (default to draft if not provided)
213
- const status = payload.status ?? DEFAULT_STATUS_VALUE;
212
+ // New records start as drafts unless the caller explicitly sets a status.
213
+ const status = payload.status ?? 'draft';
214
214
  const isDraft = status === 'draft';
215
215
 
216
216
  // Check unique keys if schema has metadata with uniqueKeys
217
217
  // This handles findOrCreate behavior and duplicate prevention
218
- const schemaWithMeta = documentSchema as {
218
+ const schemaWithMeta = createDocumentSchema as {
219
219
  metadata?: { uniqueKeys?: UniqueKeyDefinition[] };
220
220
  };
221
221
  const uniqueKeys = schemaWithMeta.metadata?.uniqueKeys;
@@ -248,32 +248,14 @@ function createEntityLogicFactory(
248
248
  ? normalizePayloadForUniqueKeys(payload, uniqueKeys)
249
249
  : payload;
250
250
 
251
- // Validate the document against the schema
252
- // Drafts get structural validation (type checking) but skip required-field enforcement
253
- if (!isDraft) {
254
- validateDocument(normalizedPayload, documentSchema);
255
- } else if (documentSchema) {
256
- // For drafts: validate field types that ARE present, but allow missing required fields
257
- try {
258
- validateDocument(normalizedPayload, documentSchema);
259
- } catch (error: any) {
260
- // Only swallow required-field errors; re-throw type mismatches
261
- const issues = error?.issues ?? error?.cause?.issues;
262
- if (issues && Array.isArray(issues)) {
263
- const nonRequiredIssues = issues.filter(
264
- (issue: any) =>
265
- issue.type !== 'non_optional' &&
266
- issue.type !== 'non_nullish' &&
267
- issue.type !== 'non_nullable'
268
- );
269
- if (nonRequiredIssues.length > 0) {
270
- throw error;
271
- }
272
- } else {
273
- // Not a Valibot error — re-throw
274
- throw error;
275
- }
276
- }
251
+ // Validate the document against the appropriate schema.
252
+ // Drafts must validate against `schemas.draft` so required fields become
253
+ // nullish/optional (so `null` empties don't fail strict `schemas.create`).
254
+ const payloadForValidation = { ...normalizedPayload, status };
255
+ if (isDraft) {
256
+ validateDocument(payloadForValidation, draftDocumentSchema);
257
+ } else {
258
+ validateDocument(payloadForValidation, createDocumentSchema);
277
259
  }
278
260
 
279
261
  // Prepare the document for Firestore and add metadata
@@ -323,7 +305,8 @@ function createEntityLogicFactory(
323
305
  */
324
306
  export const createEntity = (
325
307
  collection: string,
326
- documentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
308
+ createDocumentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
309
+ draftDocumentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
327
310
  requiredRole: UserRole,
328
311
  customSchema?: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>
329
312
  ): CallableFunction<CreateEntityRequest, Promise<any>> => {
@@ -338,7 +321,11 @@ export const createEntity = (
338
321
  CRUD_CONFIG,
339
322
  requestSchema,
340
323
  'create_entity',
341
- createEntityLogicFactory(collection, documentSchema),
324
+ createEntityLogicFactory(
325
+ collection,
326
+ createDocumentSchema,
327
+ draftDocumentSchema
328
+ ),
342
329
  requiredRole
343
330
  );
344
331
  };
File without changes
File without changes
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  export * from './aggregate.js';
13
+ export * from './bulk.js';
13
14
  export * from './create.js';
14
15
  export * from './delete.js';
15
16
  export * from './get.js';