@donotdev/functions 0.0.20 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (303) hide show
  1. package/LICENSE.md +3 -3
  2. package/guidelines/FUNCTIONS.md +9 -0
  3. package/guidelines/VERCEL.md +260 -0
  4. package/lib/firebase/auth/getCustomClaims.d.ts +2 -2
  5. package/lib/firebase/auth/getUserAuthStatus.d.ts +2 -2
  6. package/lib/firebase/auth/index.d.ts +1 -1
  7. package/lib/firebase/auth/removeCustomClaims.d.ts +2 -2
  8. package/lib/firebase/auth/setCustomClaims.d.ts +2 -2
  9. package/lib/firebase/baseFunction.d.ts +1 -1
  10. package/lib/firebase/billing/cancelSubscription.d.ts +1 -1
  11. package/lib/firebase/billing/changePlan.d.ts +1 -1
  12. package/lib/firebase/billing/createCheckoutSession.d.ts +10 -13
  13. package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
  14. package/lib/firebase/billing/index.d.ts +1 -1
  15. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +2 -2
  16. package/lib/firebase/config/constants.d.ts +4 -4
  17. package/lib/firebase/config/index.d.ts +1 -1
  18. package/lib/firebase/crud/aggregate.d.ts +2 -2
  19. package/lib/firebase/crud/delete.d.ts +1 -1
  20. package/lib/firebase/crud/get.d.ts +1 -1
  21. package/lib/firebase/crud/index.d.ts +1 -1
  22. package/lib/firebase/crud/update.d.ts +1 -1
  23. package/lib/firebase/helpers/githubAccessHelper.d.ts +3 -3
  24. package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +2 -2
  25. package/lib/firebase/helpers/index.d.ts +1 -1
  26. package/lib/firebase/index.d.ts +1 -1
  27. package/lib/firebase/index.js +3 -3
  28. package/lib/firebase/index.js.map +4 -4
  29. package/lib/firebase/oauth/disconnect.d.ts +1 -1
  30. package/lib/firebase/oauth/exchangeToken.d.ts +1 -1
  31. package/lib/firebase/oauth/getConnections.d.ts +1 -1
  32. package/lib/firebase/oauth/githubAccess.d.ts +6 -6
  33. package/lib/firebase/oauth/index.d.ts +1 -1
  34. package/lib/firebase/oauth/refreshToken.d.ts +1 -1
  35. package/lib/firebase/scheduled/index.d.ts +1 -1
  36. package/lib/shared/ai/classifyAIError.d.ts +35 -0
  37. package/lib/shared/ai/costTracker.d.ts +20 -0
  38. package/lib/shared/ai/createAIRoute.d.ts +20 -0
  39. package/lib/shared/ai/index.d.ts +6 -0
  40. package/lib/shared/ai/resolveModelTier.d.ts +14 -0
  41. package/lib/shared/billing/createCheckout.d.ts +11 -5
  42. package/lib/shared/billing/helpers/index.d.ts +1 -1
  43. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +3 -3
  44. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +4 -4
  45. package/lib/shared/billing/idempotency.d.ts +2 -2
  46. package/lib/shared/billing/index.d.ts +1 -1
  47. package/lib/shared/billing/webhookHandler.d.ts +1 -1
  48. package/lib/shared/email/createEmailRoute.d.ts +30 -0
  49. package/lib/shared/email/index.d.ts +3 -0
  50. package/lib/shared/email/provider.d.ts +30 -0
  51. package/lib/shared/email/resendProvider.d.ts +22 -0
  52. package/lib/shared/errorHandling.d.ts +1 -1
  53. package/lib/shared/firebase.d.ts +7 -7
  54. package/lib/shared/github.d.ts +16 -11
  55. package/lib/shared/index.d.ts +3 -1
  56. package/lib/shared/index.js +4 -3
  57. package/lib/shared/index.js.map +4 -4
  58. package/lib/shared/logger.d.ts +8 -6
  59. package/lib/shared/metadata.d.ts +3 -3
  60. package/lib/shared/oauth/exchangeToken.d.ts +3 -2
  61. package/lib/shared/oauth/grantAccess.d.ts +3 -2
  62. package/lib/shared/oauth/index.d.ts +1 -1
  63. package/lib/shared/schema.d.ts +2 -2
  64. package/lib/shared/utils/detectFirestore.d.ts +3 -3
  65. package/lib/shared/utils/external/date.d.ts +2 -2
  66. package/lib/shared/utils/external/index.d.ts +1 -1
  67. package/lib/shared/utils/external/references.d.ts +1 -1
  68. package/lib/shared/utils/external/subscription.d.ts +5 -5
  69. package/lib/shared/utils/firebaseHelpers.d.ts +2 -2
  70. package/lib/shared/utils/functionWrapper.d.ts +4 -4
  71. package/lib/shared/utils/index.d.ts +1 -1
  72. package/lib/shared/utils/internal/auth.d.ts +4 -4
  73. package/lib/shared/utils/internal/idempotency.d.ts +3 -2
  74. package/lib/shared/utils/internal/index.d.ts +1 -1
  75. package/lib/shared/utils/internal/monitoring.d.ts +7 -7
  76. package/lib/shared/utils/internal/rateLimiter.d.ts +5 -5
  77. package/lib/shared/utils/internal/validation.d.ts +4 -4
  78. package/lib/shared/utils/schemaValidation.d.ts +6 -6
  79. package/lib/shared/utils/validation.d.ts +9 -9
  80. package/lib/shared/utils/vercelHelpers.d.ts +2 -2
  81. package/lib/shared/utils.d.ts +19 -19
  82. package/lib/shared/validation.d.ts +2 -2
  83. package/lib/supabase/ai/createAIFunction.d.ts +30 -0
  84. package/lib/supabase/auth/deleteAccount.d.ts +1 -1
  85. package/lib/supabase/auth/getCustomClaims.d.ts +1 -1
  86. package/lib/supabase/auth/getUserAuthStatus.d.ts +1 -1
  87. package/lib/supabase/auth/removeCustomClaims.d.ts +1 -1
  88. package/lib/supabase/auth/setCustomClaims.d.ts +12 -4
  89. package/lib/supabase/baseFunction.d.ts +2 -2
  90. package/lib/supabase/billing/cancelSubscription.d.ts +1 -1
  91. package/lib/supabase/billing/changePlan.d.ts +2 -2
  92. package/lib/supabase/billing/createCheckoutSession.d.ts +1 -1
  93. package/lib/supabase/billing/createCustomerPortal.d.ts +1 -1
  94. package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +1 -1
  95. package/lib/supabase/crud/aggregate.d.ts +2 -1
  96. package/lib/supabase/crud/create.d.ts +2 -1
  97. package/lib/supabase/crud/delete.d.ts +1 -0
  98. package/lib/supabase/crud/get.d.ts +2 -1
  99. package/lib/supabase/crud/index.d.ts +1 -1
  100. package/lib/supabase/crud/list.d.ts +2 -1
  101. package/lib/supabase/crud/update.d.ts +2 -1
  102. package/lib/supabase/edgeFunction.d.ts +56 -0
  103. package/lib/supabase/email/createEmailFunction.d.ts +31 -0
  104. package/lib/supabase/helpers/authProvider.d.ts +2 -2
  105. package/lib/supabase/index.d.ts +11 -2
  106. package/lib/supabase/index.js +3 -2
  107. package/lib/supabase/index.js.map +4 -4
  108. package/lib/supabase/oauth/disconnect.d.ts +13 -0
  109. package/lib/supabase/oauth/exchangeToken.d.ts +13 -0
  110. package/lib/supabase/oauth/getConnections.d.ts +13 -0
  111. package/lib/supabase/oauth/index.d.ts +12 -0
  112. package/lib/supabase/oauth/refreshToken.d.ts +13 -0
  113. package/lib/supabase/utils/idempotency.d.ts +1 -1
  114. package/lib/supabase/utils/monitoring.d.ts +1 -1
  115. package/lib/supabase/utils/rateLimiter.d.ts +1 -1
  116. package/lib/vercel/api/ai/chat.d.ts +29 -0
  117. package/lib/vercel/api/ai/index.d.ts +1 -0
  118. package/lib/vercel/api/auth/index.d.ts +1 -1
  119. package/lib/vercel/api/billing/cancel.d.ts +1 -1
  120. package/lib/vercel/api/billing/change-plan.d.ts +1 -1
  121. package/lib/vercel/api/billing/create-checkout-session.d.ts +1 -1
  122. package/lib/vercel/api/billing/index.d.ts +1 -1
  123. package/lib/vercel/api/billing/refresh-subscription-status.d.ts +1 -1
  124. package/lib/vercel/api/billing/webhook-handler.d.ts +2 -2
  125. package/lib/vercel/api/config/constants.d.ts +9 -9
  126. package/lib/vercel/api/config/firebase-admin.d.ts +2 -2
  127. package/lib/vercel/api/config/index.d.ts +1 -1
  128. package/lib/vercel/api/crud/index.d.ts +1 -1
  129. package/lib/vercel/api/index.d.ts +2 -1
  130. package/lib/vercel/api/index.js +3 -2
  131. package/lib/vercel/api/index.js.map +4 -4
  132. package/lib/vercel/api/oauth/check-github-access.d.ts +1 -1
  133. package/lib/vercel/api/oauth/grant-github-access.d.ts +1 -1
  134. package/lib/vercel/api/oauth/index.d.ts +1 -1
  135. package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
  136. package/lib/vercel/api/utils/cors.d.ts +4 -4
  137. package/lib/vercel/baseFunction.d.ts +2 -2
  138. package/package.json +38 -5
  139. package/src/firebase/auth/getCustomClaims.ts +3 -3
  140. package/src/firebase/auth/getUserAuthStatus.ts +3 -3
  141. package/src/firebase/auth/index.ts +1 -1
  142. package/src/firebase/auth/removeCustomClaims.ts +3 -3
  143. package/src/firebase/auth/setCustomClaims.ts +70 -69
  144. package/src/firebase/baseFunction.ts +2 -2
  145. package/src/firebase/billing/cancelSubscription.ts +3 -3
  146. package/src/firebase/billing/changePlan.ts +3 -3
  147. package/src/firebase/billing/createCheckoutSession.ts +79 -187
  148. package/src/firebase/billing/createCustomerPortal.ts +1 -1
  149. package/src/firebase/billing/healthCheck.ts +1 -1
  150. package/src/firebase/billing/index.d.ts +11 -11
  151. package/src/firebase/billing/index.ts +1 -1
  152. package/src/firebase/billing/refreshSubscriptionStatus.ts +3 -3
  153. package/src/firebase/billing/webhookHandler.ts +1 -1
  154. package/src/firebase/config/constants.ts +4 -4
  155. package/src/firebase/config/index.ts +1 -1
  156. package/src/firebase/config/secrets.ts +1 -1
  157. package/src/firebase/crud/aggregate.ts +2 -2
  158. package/src/firebase/crud/create.ts +2 -2
  159. package/src/firebase/crud/delete.ts +3 -3
  160. package/src/firebase/crud/get.ts +1 -1
  161. package/src/firebase/crud/index.ts +1 -1
  162. package/src/firebase/crud/list.ts +1 -1
  163. package/src/firebase/crud/update.ts +2 -2
  164. package/src/firebase/helpers/githubAccessHelper.ts +4 -4
  165. package/src/firebase/helpers/githubTeamAccessHelper.ts +3 -3
  166. package/src/firebase/helpers/index.ts +1 -1
  167. package/src/firebase/index.d.ts +9 -9
  168. package/src/firebase/index.ts +1 -1
  169. package/src/firebase/oauth/disconnect.ts +2 -2
  170. package/src/firebase/oauth/exchangeToken.ts +6 -6
  171. package/src/firebase/oauth/getConnections.ts +2 -2
  172. package/src/firebase/oauth/githubAccess.ts +10 -10
  173. package/src/firebase/oauth/index.ts +1 -1
  174. package/src/firebase/oauth/refreshToken.ts +6 -6
  175. package/src/firebase/registerCrudFunctions.ts +1 -1
  176. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +1 -1
  177. package/src/firebase/scheduled/index.ts +1 -1
  178. package/src/shared/__tests__/auth.test.ts +46 -0
  179. package/src/shared/__tests__/errorHandling.test.ts +66 -1
  180. package/src/shared/__tests__/firebase.test.ts +293 -0
  181. package/src/shared/__tests__/internalValidation.test.ts +190 -0
  182. package/src/shared/__tests__/metadata.test.ts +66 -0
  183. package/src/shared/__tests__/schema.test.ts +219 -0
  184. package/src/shared/__tests__/schemaValidation.test.ts +72 -0
  185. package/src/shared/__tests__/subscription.test.ts +45 -0
  186. package/src/shared/__tests__/utils.test.ts +281 -0
  187. package/src/shared/__tests__/validation-env.test.ts +73 -0
  188. package/src/shared/ai/__tests__/costTracker.test.ts +121 -0
  189. package/src/shared/ai/classifyAIError.ts +163 -0
  190. package/src/shared/ai/costTracker.ts +51 -0
  191. package/src/shared/ai/createAIRoute.ts +397 -0
  192. package/src/shared/ai/index.ts +8 -0
  193. package/src/shared/ai/resolveModelTier.ts +58 -0
  194. package/src/shared/billing/__tests__/createCheckout.test.ts +1 -1
  195. package/src/shared/billing/__tests__/webhookHandler.test.ts +1 -1
  196. package/src/shared/billing/createCheckout.ts +156 -11
  197. package/src/shared/billing/helpers/index.ts +1 -1
  198. package/src/shared/billing/helpers/subscriptionManagement.ts +13 -4
  199. package/src/shared/billing/helpers/updateUserSubscription.ts +4 -4
  200. package/src/shared/billing/idempotency.ts +9 -4
  201. package/src/shared/billing/index.ts +1 -1
  202. package/src/shared/billing/webhookHandler.ts +7 -7
  203. package/src/shared/email/createEmailRoute.ts +81 -0
  204. package/src/shared/email/index.ts +5 -0
  205. package/src/shared/email/provider.ts +31 -0
  206. package/src/shared/email/resendProvider.ts +56 -0
  207. package/src/shared/errorHandling.ts +12 -6
  208. package/src/shared/firebase.ts +7 -7
  209. package/src/shared/github.ts +49 -11
  210. package/src/shared/index.d.ts +9 -9
  211. package/src/shared/index.ts +3 -1
  212. package/src/shared/logger.ts +10 -8
  213. package/src/shared/metadata.ts +3 -3
  214. package/src/shared/oauth/__tests__/exchangeToken.test.ts +1 -1
  215. package/src/shared/oauth/exchangeToken.ts +3 -2
  216. package/src/shared/oauth/grantAccess.ts +3 -2
  217. package/src/shared/oauth/index.ts +1 -1
  218. package/src/shared/schema.ts +4 -4
  219. package/src/shared/utils/__tests__/functionWrapper.test.ts +1 -1
  220. package/src/shared/utils/detectFirestore.ts +3 -3
  221. package/src/shared/utils/external/date.ts +5 -5
  222. package/src/shared/utils/external/index.ts +1 -1
  223. package/src/shared/utils/external/references.ts +2 -2
  224. package/src/shared/utils/external/subscription.ts +5 -5
  225. package/src/shared/utils/firebaseHelpers.ts +3 -3
  226. package/src/shared/utils/functionWrapper.ts +4 -4
  227. package/src/shared/utils/index.ts +1 -1
  228. package/src/shared/utils/internal/auth.ts +7 -7
  229. package/src/shared/utils/internal/firebase.ts +1 -1
  230. package/src/shared/utils/internal/idempotency.ts +4 -3
  231. package/src/shared/utils/internal/index.ts +1 -1
  232. package/src/shared/utils/internal/monitoring.ts +8 -8
  233. package/src/shared/utils/internal/rateLimiter.ts +12 -9
  234. package/src/shared/utils/internal/validation.ts +5 -5
  235. package/src/shared/utils/schemaValidation.ts +6 -6
  236. package/src/shared/utils/validation.ts +10 -10
  237. package/src/shared/utils/vercelHelpers.ts +3 -3
  238. package/src/shared/utils.ts +19 -19
  239. package/src/shared/validation.ts +3 -3
  240. package/src/supabase/ai/createAIFunction.ts +75 -0
  241. package/src/supabase/auth/deleteAccount.ts +2 -2
  242. package/src/supabase/auth/getCustomClaims.ts +2 -2
  243. package/src/supabase/auth/getUserAuthStatus.ts +2 -2
  244. package/src/supabase/auth/removeCustomClaims.ts +38 -2
  245. package/src/supabase/auth/setCustomClaims.ts +66 -5
  246. package/src/supabase/baseFunction.ts +29 -5
  247. package/src/supabase/billing/cancelSubscription.ts +2 -2
  248. package/src/supabase/billing/changePlan.ts +8 -3
  249. package/src/supabase/billing/createCheckoutSession.ts +18 -4
  250. package/src/supabase/billing/createCustomerPortal.ts +2 -2
  251. package/src/supabase/billing/refreshSubscriptionStatus.ts +2 -2
  252. package/src/supabase/crud/aggregate.ts +2 -1
  253. package/src/supabase/crud/create.ts +2 -1
  254. package/src/supabase/crud/delete.ts +2 -1
  255. package/src/supabase/crud/get.ts +2 -1
  256. package/src/supabase/crud/index.ts +1 -1
  257. package/src/supabase/crud/list.ts +2 -1
  258. package/src/supabase/crud/update.ts +2 -1
  259. package/src/supabase/edgeFunction.ts +195 -0
  260. package/src/supabase/email/createEmailFunction.ts +75 -0
  261. package/src/supabase/helpers/authProvider.ts +2 -2
  262. package/src/supabase/index.ts +22 -2
  263. package/src/supabase/oauth/disconnect.ts +104 -0
  264. package/src/supabase/oauth/exchangeToken.ts +183 -0
  265. package/src/supabase/oauth/getConnections.ts +85 -0
  266. package/src/supabase/oauth/index.ts +15 -0
  267. package/src/supabase/oauth/refreshToken.ts +130 -0
  268. package/src/supabase/registerCrudFunctions.ts +30 -42
  269. package/src/supabase/utils/idempotency.ts +7 -3
  270. package/src/supabase/utils/monitoring.ts +1 -1
  271. package/src/supabase/utils/rateLimiter.ts +1 -1
  272. package/src/vercel/api/ai/chat.ts +77 -0
  273. package/src/vercel/api/ai/index.ts +1 -0
  274. package/src/vercel/api/auth/get-custom-claims.ts +1 -1
  275. package/src/vercel/api/auth/get-user-auth-status.ts +1 -1
  276. package/src/vercel/api/auth/index.ts +1 -1
  277. package/src/vercel/api/auth/remove-custom-claims.ts +1 -1
  278. package/src/vercel/api/auth/set-custom-claims.ts +2 -4
  279. package/src/vercel/api/billing/cancel.ts +3 -3
  280. package/src/vercel/api/billing/change-plan.ts +3 -3
  281. package/src/vercel/api/billing/create-checkout-session.ts +30 -7
  282. package/src/vercel/api/billing/customer-portal.ts +1 -1
  283. package/src/vercel/api/billing/index.ts +1 -1
  284. package/src/vercel/api/billing/refresh-subscription-status.ts +1 -1
  285. package/src/vercel/api/billing/webhook-handler.ts +11 -4
  286. package/src/vercel/api/config/constants.ts +9 -9
  287. package/src/vercel/api/config/firebase-admin.ts +3 -3
  288. package/src/vercel/api/config/index.ts +1 -1
  289. package/src/vercel/api/crud/create.ts +1 -1
  290. package/src/vercel/api/crud/delete.ts +1 -1
  291. package/src/vercel/api/crud/get.ts +1 -1
  292. package/src/vercel/api/crud/index.ts +1 -1
  293. package/src/vercel/api/crud/list.ts +1 -1
  294. package/src/vercel/api/crud/update.ts +1 -1
  295. package/src/vercel/api/index.d.ts +1 -1
  296. package/src/vercel/api/index.ts +2 -1
  297. package/src/vercel/api/oauth/check-github-access.ts +3 -3
  298. package/src/vercel/api/oauth/exchange-token.ts +25 -2
  299. package/src/vercel/api/oauth/grant-github-access.ts +3 -3
  300. package/src/vercel/api/oauth/index.ts +1 -1
  301. package/src/vercel/api/oauth/revoke-github-access.ts +1 -1
  302. package/src/vercel/api/utils/cors.ts +10 -4
  303. package/src/vercel/baseFunction.ts +2 -2
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Refresh Subscription Status — Supabase Edge Function
5
5
  * @description Direct Stripe lookup + claim update via Supabase Admin.
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.5.0
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -38,7 +38,7 @@ const refreshSubscriptionSchema = v.object({
38
38
  *
39
39
  * @returns `(req: Request) => Promise<Response>` handler
40
40
  *
41
- * @version 0.0.1
41
+ * @version 0.1.0
42
42
  * @since 0.5.0
43
43
  */
44
44
  export function createRefreshSubscriptionStatus() {
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Generic handler to aggregate entities in Supabase.
5
5
  * @description Provides aggregate operations (COUNT, SUM, AVG, MIN, MAX, GROUP BY) for PostgreSQL.
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.5.0
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -19,6 +19,7 @@ import { createSupabaseHandler } from '../baseFunction.js';
19
19
 
20
20
  const mapper = defaultFieldMapper;
21
21
 
22
+ /** Request payload for aggregate operations (COUNT, SUM, AVG, MIN, MAX) on entities. */
22
23
  export type AggregateEntityRequest = {
23
24
  where?: Array<[string, any, any]>;
24
25
  aggregate: {
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Generic handler to create an entity in Supabase.
5
5
  * @description Provides a reusable implementation for creating documents in PostgreSQL with validation.
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.5.0
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -25,6 +25,7 @@ import { checkIdempotency, storeIdempotency } from '../utils/idempotency.js';
25
25
 
26
26
  const mapper = defaultFieldMapper;
27
27
 
28
+ /** Request payload for creating an entity with optional idempotency. */
28
29
  export type CreateEntityRequest = {
29
30
  payload: Record<string, any>;
30
31
  idempotencyKey?: string;
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Generic handler to delete an entity from Supabase.
5
5
  * @description Provides a reusable implementation for deleting documents from PostgreSQL.
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.5.0
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -16,6 +16,7 @@ import type { UserRole } from '@donotdev/core/server';
16
16
  import { DoNotDevError } from '../../shared/utils.js';
17
17
  import { createSupabaseHandler } from '../baseFunction.js';
18
18
 
19
+ /** Request payload for deleting a single entity by ID. */
19
20
  export type DeleteEntityRequest = { id: string };
20
21
 
21
22
  /**
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Generic handler to retrieve a single entity from Supabase.
5
5
  * @description Provides a reusable implementation for retrieving documents from PostgreSQL with visibility filtering.
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.5.0
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -26,6 +26,7 @@ import {
26
26
  import { DoNotDevError } from '../../shared/utils.js';
27
27
  import { createSupabaseHandler } from '../baseFunction.js';
28
28
 
29
+ /** Request payload for retrieving a single entity by ID. */
29
30
  export type GetEntityRequest = { id: string };
30
31
 
31
32
  /**
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Supabase CRUD handlers barrel export
5
5
  * @description Exports all Supabase CRUD handler factories
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.5.0
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Generic handler to list entities from Supabase with pagination, filtering, and sorting.
5
5
  * @description Provides a reusable implementation for listing documents from PostgreSQL with advanced query capabilities.
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.5.0
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -40,6 +40,7 @@ function toBackendColumn(field: unknown): string {
40
40
  );
41
41
  }
42
42
 
43
+ /** Request payload for listing entities with filtering, sorting, and pagination. */
43
44
  export interface ListEntityRequest {
44
45
  where?: Array<[string, any, any]>;
45
46
  orderBy?: Array<[string, 'asc' | 'desc']>;
@@ -4,7 +4,7 @@
4
4
  * @fileoverview Generic handler to update an entity in Supabase.
5
5
  * @description Provides a reusable implementation for updating documents in PostgreSQL with validation.
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.5.0
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -21,6 +21,7 @@ import { checkIdempotency, storeIdempotency } from '../utils/idempotency.js';
21
21
 
22
22
  const mapper = defaultFieldMapper;
23
23
 
24
+ /** Request payload for updating an entity by ID with optional idempotency. */
24
25
  export type UpdateEntityRequest = {
25
26
  id: string;
26
27
  payload: Record<string, any>;
@@ -0,0 +1,195 @@
1
+ // packages/functions/src/supabase/edgeFunction.ts
2
+
3
+ /**
4
+ * @fileoverview Lightweight edge function wrapper
5
+ * @description Handles CORS, auth, and response formatting for custom Supabase
6
+ * Edge Functions that don't fit the typed createSupabaseHandler pattern.
7
+ *
8
+ * Use createSupabaseHandler for typed CRUD-style handlers with schema validation.
9
+ * Use createEdgeFunction for multi-action functions, AI chat, webhooks, etc.
10
+ *
11
+ * @version 0.1.0
12
+ * @since 0.6.0
13
+ * @author AMBROISE PARK Consulting
14
+ */
15
+
16
+ import { createClient } from '@supabase/supabase-js';
17
+ import type { SupabaseClient } from '@supabase/supabase-js';
18
+
19
+ // =============================================================================
20
+ // Types
21
+ // =============================================================================
22
+
23
+ /**
24
+ * Context passed to edge function handlers.
25
+ *
26
+ * @version 0.1.0
27
+ * @since 0.6.0
28
+ */
29
+ export interface EdgeFunctionContext {
30
+ /** Authenticated user (null if no valid JWT or requireAuth=false) */
31
+ user: { id: string; email?: string } | null;
32
+ /** Admin client (service role, bypasses RLS) - always available */
33
+ supabaseAdmin: SupabaseClient;
34
+ /** User-scoped client (RLS) - null if no valid JWT */
35
+ userClient: SupabaseClient | null;
36
+ /** JSON response with CORS headers */
37
+ json: (data: unknown, status?: number) => Response;
38
+ /** JSON error response: { error: message } with CORS headers */
39
+ error: (message: string, status?: number) => Response;
40
+ /** Raw response with CORS headers (for structured payloads) */
41
+ respond: (data: unknown, status: number) => Response;
42
+ }
43
+
44
+ /** Configuration options for edge function creation. */
45
+ export interface EdgeFunctionOptions {
46
+ /** Require JWT auth - returns 401 if missing/invalid (default: true) */
47
+ requireAuth?: boolean;
48
+ /** Extra CORS allowed headers (e.g., 'stripe-signature', 'x-build-secret') */
49
+ extraHeaders?: string[];
50
+ }
51
+
52
+ // =============================================================================
53
+ // Factory
54
+ // =============================================================================
55
+
56
+ /**
57
+ * Create a Supabase Edge Function handler with CORS, optional auth, and response helpers.
58
+ *
59
+ * @example
60
+ * ```typescript
61
+ * // Auth required (default)
62
+ * Deno.serve(createEdgeFunction(async (req, ctx) => {
63
+ * const body = await req.json();
64
+ * return ctx.json({ result: 'ok' });
65
+ * }));
66
+ *
67
+ * // No auth (public endpoint)
68
+ * Deno.serve(createEdgeFunction(async (req, ctx) => {
69
+ * return ctx.json({ public: true });
70
+ * }, { requireAuth: false }));
71
+ *
72
+ * // Custom auth (webhook)
73
+ * Deno.serve(createEdgeFunction(async (req, ctx) => {
74
+ * const sig = req.headers.get('stripe-signature');
75
+ * if (!sig) return ctx.error('Missing signature', 401);
76
+ * return ctx.json({ received: true });
77
+ * }, { requireAuth: false, extraHeaders: ['stripe-signature'] }));
78
+ * ```
79
+ */
80
+ export function createEdgeFunction(
81
+ handler: (req: Request, ctx: EdgeFunctionContext) => Promise<Response>,
82
+ options?: EdgeFunctionOptions,
83
+ ): (req: Request) => Promise<Response> {
84
+ const requireAuth = options?.requireAuth ?? true;
85
+ const baseHeaders = 'authorization, content-type, x-client-info, apikey';
86
+ const allowedHeaders = options?.extraHeaders?.length
87
+ ? `${baseHeaders}, ${options.extraHeaders.join(', ')}`
88
+ : baseHeaders;
89
+
90
+ return async (req: Request): Promise<Response> => {
91
+ const allowedOrigin = getEnv('ALLOWED_ORIGIN') || '*';
92
+
93
+ // Response helpers (closed over allowedOrigin)
94
+ const respond = (data: unknown, status: number) =>
95
+ jsonResponse(data, status, allowedOrigin);
96
+ const json = (data: unknown, status = 200) => respond(data, status);
97
+ const error = (message: string, status = 400) =>
98
+ respond({ error: message }, status);
99
+
100
+ // CORS preflight
101
+ if (req.method === 'OPTIONS') {
102
+ return new Response(null, {
103
+ status: 204,
104
+ headers: {
105
+ 'Access-Control-Allow-Origin': allowedOrigin,
106
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
107
+ 'Access-Control-Allow-Headers': allowedHeaders,
108
+ },
109
+ });
110
+ }
111
+
112
+ // Method check
113
+ if (req.method !== 'POST') {
114
+ return error('Method not allowed', 405);
115
+ }
116
+
117
+ // Supabase clients
118
+ const supabaseUrl = getEnv('SUPABASE_URL');
119
+ const serviceKey =
120
+ getEnv('SUPABASE_SECRET_KEY') || getEnv('SUPABASE_SERVICE_ROLE_KEY');
121
+
122
+ if (!supabaseUrl || !serviceKey) {
123
+ console.error('Missing SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY');
124
+ return error('Server misconfigured', 500);
125
+ }
126
+
127
+ const supabaseAdmin = createClient(supabaseUrl, serviceKey, {
128
+ auth: { autoRefreshToken: false, persistSession: false },
129
+ });
130
+
131
+ // Auth
132
+ let user: { id: string; email?: string } | null = null;
133
+ let userClient: SupabaseClient | null = null;
134
+
135
+ const authHeader = req.headers.get('authorization');
136
+ if (authHeader?.startsWith('Bearer ')) {
137
+ const jwt = authHeader.slice(7);
138
+ const anonKey = getEnv('SUPABASE_ANON_KEY');
139
+ if (anonKey) {
140
+ userClient = createClient(supabaseUrl, anonKey, {
141
+ global: { headers: { Authorization: `Bearer ${jwt}` } },
142
+ });
143
+ const { data, error: authError } = await supabaseAdmin.auth.getUser(jwt);
144
+ if (!authError && data.user) {
145
+ user = { id: data.user.id, email: data.user.email ?? undefined };
146
+ }
147
+ }
148
+ }
149
+
150
+ if (requireAuth && !user) {
151
+ return error('Unauthorized', 401);
152
+ }
153
+
154
+ const ctx: EdgeFunctionContext = {
155
+ user,
156
+ supabaseAdmin,
157
+ userClient,
158
+ json,
159
+ error,
160
+ respond,
161
+ };
162
+
163
+ try {
164
+ return await handler(req, ctx);
165
+ } catch (e) {
166
+ console.error('Edge function error:', e);
167
+ return error('Internal error', 500);
168
+ }
169
+ };
170
+ }
171
+
172
+ // =============================================================================
173
+ // Helpers
174
+ // =============================================================================
175
+
176
+ function jsonResponse(
177
+ data: unknown,
178
+ status: number,
179
+ allowedOrigin: string,
180
+ ): Response {
181
+ return new Response(JSON.stringify(data), {
182
+ status,
183
+ headers: {
184
+ 'Content-Type': 'application/json',
185
+ 'Access-Control-Allow-Origin': allowedOrigin,
186
+ },
187
+ });
188
+ }
189
+
190
+ function getEnv(key: string): string {
191
+ if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
192
+ return (globalThis as any).Deno?.env?.get(key) ?? '';
193
+ }
194
+ return typeof process !== 'undefined' ? (process.env[key] ?? '') : '';
195
+ }
@@ -0,0 +1,75 @@
1
+ // packages/functions/src/supabase/email/createEmailFunction.ts
2
+
3
+ /**
4
+ * @fileoverview Email Send - Supabase Edge Function Factory
5
+ * @description Wraps the shared email handler for Supabase Edge Functions.
6
+ * Resolves Resend provider from env, adds auth context.
7
+ *
8
+ * @version 0.1.0
9
+ * @since 0.1.0
10
+ * @author AMBROISE PARK Consulting
11
+ */
12
+
13
+ import type {
14
+ EmailRouteConfig,
15
+ SendEmailRequest,
16
+ } from '@donotdev/core/server';
17
+ import { SendEmailRequestSchema } from '@donotdev/core/server';
18
+
19
+ import { handleEmailRequest } from '../../shared/email/index.js';
20
+ import { createResendProvider } from '../../shared/email/resendProvider.js';
21
+ import { createSupabaseHandler } from '../baseFunction.js';
22
+
23
+ /**
24
+ * Create a Supabase Edge Function handler for sending emails.
25
+ * Requires RESEND_API_KEY environment variable.
26
+ *
27
+ * @param config - Email route configuration (templates, defaultFrom)
28
+ * @returns `(req: Request) => Promise<Response>` handler
29
+ *
30
+ * @example
31
+ * ```typescript
32
+ * // supabase/functions/send-email/index.ts
33
+ * import { createEmailFunction } from '@donotdev/functions/supabase';
34
+ *
35
+ * const handler = createEmailFunction({
36
+ * provider: 'resend',
37
+ * defaultFrom: 'Frabled <noreply@frabled.com>',
38
+ * templates: { 'order-confirmation': orderConfirmationTemplate },
39
+ * });
40
+ * Deno.serve(handler);
41
+ * ```
42
+ */
43
+ export function createEmailFunction(config: EmailRouteConfig) {
44
+ return createSupabaseHandler(
45
+ 'send-email',
46
+ SendEmailRequestSchema,
47
+ async (data: SendEmailRequest, _ctx) => {
48
+ const apiKey = getEnv('RESEND_API_KEY');
49
+ if (!apiKey) {
50
+ return new Response(
51
+ JSON.stringify({ success: false, error: 'Email provider not configured' }),
52
+ { status: 500, headers: { 'Content-Type': 'application/json' } }
53
+ );
54
+ }
55
+
56
+ const provider = createResendProvider(apiKey);
57
+ const result = await handleEmailRequest(data, config, provider);
58
+
59
+ return new Response(
60
+ JSON.stringify(result),
61
+ {
62
+ status: result.success ? 200 : 400,
63
+ headers: { 'Content-Type': 'application/json' },
64
+ }
65
+ );
66
+ }
67
+ );
68
+ }
69
+
70
+ function getEnv(name: string): string | undefined {
71
+ if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
72
+ return (globalThis as any).Deno?.env?.get(name);
73
+ }
74
+ return typeof process !== 'undefined' ? process.env[name] : undefined;
75
+ }
@@ -5,7 +5,7 @@
5
5
  * @description Maps Supabase Admin auth to the shared `AuthProvider` interface,
6
6
  * bridging `app_metadata` ↔ `customClaims`.
7
7
  *
8
- * @version 0.0.1
8
+ * @version 0.1.0
9
9
  * @since 0.5.0
10
10
  * @author AMBROISE PARK Consulting
11
11
  */
@@ -24,7 +24,7 @@ import type { SupabaseClient } from '@supabase/supabase-js';
24
24
  * @param supabaseAdmin - Supabase client created with the service role key
25
25
  * @returns AuthProvider compatible with shared billing helpers
26
26
  *
27
- * @version 0.0.1
27
+ * @version 0.1.0
28
28
  * @since 0.5.0
29
29
  */
30
30
  export function createSupabaseAuthProvider(
@@ -2,9 +2,9 @@
2
2
 
3
3
  /**
4
4
  * @fileoverview Supabase Edge Functions barrel exports
5
- * @description All Supabase Edge Function handlers for auth and billing.
5
+ * @description All Supabase Edge Function handlers for auth, billing, and OAuth.
6
6
  *
7
- * @version 0.0.1
7
+ * @version 0.1.0
8
8
  * @since 0.5.0
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
@@ -12,6 +12,8 @@
12
12
  // Base
13
13
  export { createSupabaseHandler } from './baseFunction.js';
14
14
  export type { SupabaseHandlerContext } from './baseFunction.js';
15
+ export { createEdgeFunction } from './edgeFunction.js';
16
+ export type { EdgeFunctionContext, EdgeFunctionOptions } from './edgeFunction.js';
15
17
 
16
18
  // Helpers
17
19
  export { createSupabaseAuthProvider } from './helpers/authProvider.js';
@@ -19,6 +21,7 @@ export { createSupabaseAuthProvider } from './helpers/authProvider.js';
19
21
  // Auth
20
22
  export { createDeleteAccount } from './auth/deleteAccount.js';
21
23
  export { createSetCustomClaims } from './auth/setCustomClaims.js';
24
+ export type { SetCustomClaimsOptions } from './auth/setCustomClaims.js';
22
25
  export { createGetCustomClaims } from './auth/getCustomClaims.js';
23
26
  export { createRemoveCustomClaims } from './auth/removeCustomClaims.js';
24
27
  export { createGetUserAuthStatus } from './auth/getUserAuthStatus.js';
@@ -30,6 +33,23 @@ export { createChangePlan } from './billing/changePlan.js';
30
33
  export { createCustomerPortal } from './billing/createCustomerPortal.js';
31
34
  export { createRefreshSubscriptionStatus } from './billing/refreshSubscriptionStatus.js';
32
35
 
36
+ // OAuth
37
+ export {
38
+ createExchangeToken,
39
+ createDisconnect,
40
+ createRefreshToken,
41
+ createGetConnections,
42
+ } from './oauth/index.js';
43
+
44
+ // AI
45
+ export { createAIFunction } from './ai/createAIFunction.js';
46
+ export { resolveModelForTier } from '../shared/ai/resolveModelTier.js';
47
+ export { classifyAIError, mapClassifiedToHTTP } from '../shared/ai/classifyAIError.js';
48
+ export type { AIErrorCode, ClassifiedAIError } from '../shared/ai/classifyAIError.js';
49
+
50
+ // Email
51
+ export { createEmailFunction } from './email/createEmailFunction.js';
52
+
33
53
  // CRUD
34
54
  export {
35
55
  createSupabaseGetEntity,
@@ -0,0 +1,104 @@
1
+ // packages/functions/src/supabase/oauth/disconnect.ts
2
+
3
+ /**
4
+ * @fileoverview OAuth disconnect Supabase Edge Function
5
+ * @description Supabase Edge Function for disconnecting OAuth providers
6
+ *
7
+ * @version 0.1.0
8
+ * @since 0.1.0
9
+ * @author AMBROISE PARK Consulting
10
+ */
11
+
12
+ import * as v from 'valibot';
13
+
14
+ import {
15
+ OAUTH_PARTNERS,
16
+ type OAuthPartnerId,
17
+ type OAuthPurpose,
18
+ } from '@donotdev/core/server';
19
+
20
+ import { createSupabaseHandler } from '../baseFunction.js';
21
+ import type { SupabaseHandlerContext } from '../baseFunction.js';
22
+
23
+ const disconnectSchema = v.object({
24
+ provider: v.string() as v.BaseSchema<
25
+ unknown,
26
+ OAuthPartnerId,
27
+ v.BaseIssue<unknown>
28
+ >,
29
+ purpose: v.picklist(['authentication', 'api-access']) as v.BaseSchema<
30
+ unknown,
31
+ OAuthPurpose,
32
+ v.BaseIssue<unknown>
33
+ >,
34
+ });
35
+
36
+ /**
37
+ * Create an OAuth disconnect Edge Function handler
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * import { createDisconnect } from '@donotdev/functions/supabase';
42
+ * Deno.serve(createDisconnect());
43
+ * ```
44
+ *
45
+ * @version 0.1.0
46
+ * @since 0.1.0
47
+ */
48
+ export function createDisconnect() {
49
+ return createSupabaseHandler(
50
+ 'disconnect',
51
+ disconnectSchema,
52
+ async (
53
+ data: { provider: OAuthPartnerId; purpose: OAuthPurpose },
54
+ ctx: SupabaseHandlerContext
55
+ ) => {
56
+ const { provider, purpose } = data;
57
+
58
+ // Get existing connection to revoke token
59
+ const { data: connection } = await ctx.supabaseAdmin
60
+ .from('oauth_connections')
61
+ .select('credentials')
62
+ .eq('user_id', ctx.uid)
63
+ .eq('provider', provider)
64
+ .eq('purpose', purpose)
65
+ .single();
66
+
67
+ // Revoke token if possible
68
+ if (connection?.credentials?.accessToken) {
69
+ const endpoints = OAUTH_PARTNERS[provider];
70
+ const revokeUrl =
71
+ 'revokeUrl' in endpoints ? endpoints.revokeUrl : null;
72
+ if (revokeUrl) {
73
+ try {
74
+ await fetch(revokeUrl.toString(), {
75
+ method: 'POST',
76
+ headers: {
77
+ 'Content-Type': 'application/x-www-form-urlencoded',
78
+ },
79
+ body: new URLSearchParams({
80
+ token: connection.credentials.accessToken,
81
+ }).toString(),
82
+ });
83
+ } catch (e) {
84
+ console.warn(`Failed to revoke token for ${provider}:`, e);
85
+ }
86
+ }
87
+ }
88
+
89
+ // Delete connection
90
+ const { error } = await ctx.supabaseAdmin
91
+ .from('oauth_connections')
92
+ .delete()
93
+ .eq('user_id', ctx.uid)
94
+ .eq('provider', provider)
95
+ .eq('purpose', purpose);
96
+
97
+ if (error) {
98
+ throw new Error(`Failed to disconnect: ${error.message}`);
99
+ }
100
+
101
+ return { success: true };
102
+ }
103
+ );
104
+ }