@donotdev/functions 0.2.2 → 0.2.3

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 (161) hide show
  1. package/README.md +1 -1
  2. package/lib/chunks/chunk-6NXIK35R.js +23 -0
  3. package/lib/chunks/chunk-6NXIK35R.js.map +7 -0
  4. package/lib/chunks/chunk-EZKRLLSQ.js +22 -0
  5. package/lib/chunks/{chunk-OZX5ZG44.js.map → chunk-EZKRLLSQ.js.map} +1 -1
  6. package/lib/chunks/chunk-F3PHE627.js +22 -0
  7. package/lib/chunks/chunk-F3PHE627.js.map +7 -0
  8. package/lib/chunks/chunk-F3WBFWPO.js +151 -0
  9. package/lib/chunks/chunk-F3WBFWPO.js.map +7 -0
  10. package/lib/chunks/chunk-G5DRV3DH.js +22 -0
  11. package/lib/chunks/chunk-G5DRV3DH.js.map +7 -0
  12. package/lib/chunks/{chunk-2A4FPYNB.js → chunk-GDIUOJMD.js} +2 -2
  13. package/lib/chunks/chunk-GDIUOJMD.js.map +7 -0
  14. package/lib/chunks/chunk-Q2WLRFOE.js +22 -0
  15. package/lib/chunks/chunk-Q2WLRFOE.js.map +7 -0
  16. package/lib/chunks/chunk-QXIOO2RL.js +22 -0
  17. package/lib/chunks/chunk-QXIOO2RL.js.map +7 -0
  18. package/lib/chunks/{chunk-PJCJ5H2O.js → chunk-UH445BGK.js} +2 -2
  19. package/lib/chunks/chunk-W6W4L44F.js +22 -0
  20. package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
  21. package/lib/chunks/chunk-W74UL7AY.js +22 -0
  22. package/lib/chunks/chunk-W74UL7AY.js.map +7 -0
  23. package/lib/chunks/{monitoring-UIDJS2KA.js → monitoring-LXNVBD3G.js} +2 -2
  24. package/lib/chunks/{rateLimiter-WNWHI3B4.js → rateLimiter-GG5LPWXJ.js} +2 -2
  25. package/lib/chunks/{server-RYGEBS2B.js → server-NODQAE3F.js} +2 -2
  26. package/lib/firebase/crud/aggregate.d.ts +1 -1
  27. package/lib/firebase/index.js +1 -1
  28. package/lib/firebase/index.js.map +3 -3
  29. package/lib/shared/billing/checkoutValidation.d.ts +1 -1
  30. package/lib/shared/billing/createCheckout.d.ts +1 -1
  31. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
  32. package/lib/shared/billing/orderWebhook.d.ts +29 -2
  33. package/lib/shared/billing/stripePinned.d.ts +43 -0
  34. package/lib/shared/denoEnv.d.ts +25 -0
  35. package/lib/shared/github.d.ts +0 -8
  36. package/lib/shared/index.js +1 -1
  37. package/lib/shared/logger.d.ts +14 -14
  38. package/lib/shared/utils/external/subscription.d.ts +0 -8
  39. package/lib/shared/utils.d.ts +15 -3
  40. package/lib/supabase/auth/deleteAccount.d.ts +34 -2
  41. package/lib/supabase/crud/create.d.ts +0 -8
  42. package/lib/supabase/crud/entityStore.d.ts +13 -0
  43. package/lib/supabase/crud/update.d.ts +0 -8
  44. package/lib/supabase/index.d.ts +1 -0
  45. package/lib/supabase/index.js +1 -1
  46. package/lib/supabase/index.js.map +4 -4
  47. package/lib/vercel/api/index.js +1 -1
  48. package/lib/vercel/api/index.js.map +3 -3
  49. package/package.json +9 -9
  50. package/src/firebase/auth/getCustomClaims.ts +2 -0
  51. package/src/firebase/auth/getUserAuthStatus.ts +2 -0
  52. package/src/firebase/auth/removeCustomClaims.ts +2 -0
  53. package/src/firebase/auth/setCustomClaims.ts +3 -0
  54. package/src/firebase/baseFunction.ts +5 -2
  55. package/src/firebase/billing/changePlan.ts +6 -5
  56. package/src/firebase/billing/createCustomerPortal.ts +6 -4
  57. package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
  58. package/src/firebase/billing/webhookHandler.ts +4 -4
  59. package/src/firebase/crud/aggregate.ts +41 -12
  60. package/src/firebase/crud/bulk.ts +7 -0
  61. package/src/firebase/crud/create.ts +21 -8
  62. package/src/firebase/crud/delete.ts +6 -1
  63. package/src/firebase/crud/get.ts +9 -2
  64. package/src/firebase/crud/list.ts +18 -8
  65. package/src/firebase/crud/update.ts +15 -7
  66. package/src/firebase/helpers/githubAccessHelper.ts +3 -0
  67. package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
  68. package/src/firebase/oauth/exchangeToken.ts +4 -0
  69. package/src/firebase/oauth/getConnections.ts +1 -1
  70. package/src/firebase/oauth/githubAccess.ts +3 -0
  71. package/src/firebase/oauth/refreshToken.ts +1 -0
  72. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
  73. package/src/shared/ai/classifyAIError.ts +18 -10
  74. package/src/shared/ai/createAIRoute.ts +2 -1
  75. package/src/shared/ai/resolveModelTier.ts +2 -1
  76. package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
  77. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
  78. package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
  79. package/src/shared/billing/checkoutValidation.ts +19 -2
  80. package/src/shared/billing/createCheckout.ts +56 -11
  81. package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
  82. package/src/shared/billing/orderWebhook.ts +69 -1
  83. package/src/shared/billing/stripeClient.ts +2 -1
  84. package/src/shared/billing/stripePinned.ts +71 -0
  85. package/src/shared/billing/tierWebhookEvents.ts +3 -2
  86. package/src/shared/billing/webhookHandler.ts +5 -1
  87. package/src/shared/crud/bulkCore.ts +3 -2
  88. package/src/shared/denoEnv.ts +29 -0
  89. package/src/shared/email/createEmailRoute.ts +2 -2
  90. package/src/shared/errorHandling.ts +8 -8
  91. package/src/shared/firebase.ts +26 -9
  92. package/src/shared/github.ts +15 -5
  93. package/src/shared/logger.ts +37 -38
  94. package/src/shared/schema.ts +6 -10
  95. package/src/shared/utils/external/date.ts +4 -4
  96. package/src/shared/utils/external/subscription.ts +2 -89
  97. package/src/shared/utils/firebaseHelpers.ts +2 -0
  98. package/src/shared/utils/internal/idempotency.ts +3 -0
  99. package/src/shared/utils/internal/monitoring.ts +6 -5
  100. package/src/shared/utils/internal/validation.ts +2 -0
  101. package/src/shared/utils/schemaValidation.ts +1 -0
  102. package/src/shared/utils/validation.ts +10 -20
  103. package/src/shared/utils.ts +12 -7
  104. package/src/supabase/__tests__/aggregate.test.ts +132 -0
  105. package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
  106. package/src/supabase/auth/deleteAccount.ts +72 -5
  107. package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
  108. package/src/supabase/crud/aggregate.ts +85 -72
  109. package/src/supabase/crud/bulk.ts +3 -0
  110. package/src/supabase/crud/create.ts +13 -9
  111. package/src/supabase/crud/delete.ts +2 -1
  112. package/src/supabase/crud/entityStore.ts +1 -1
  113. package/src/supabase/crud/get.ts +2 -1
  114. package/src/supabase/crud/list.ts +23 -17
  115. package/src/supabase/crud/update.ts +9 -6
  116. package/src/supabase/edgeFunction.ts +2 -1
  117. package/src/supabase/email/createEmailFunction.ts +2 -1
  118. package/src/supabase/index.ts +1 -0
  119. package/src/supabase/oauth/exchangeToken.ts +1 -0
  120. package/src/supabase/oauth/getConnections.ts +1 -1
  121. package/src/supabase/oauth/refreshToken.ts +1 -0
  122. package/src/supabase/utils/idempotency.ts +1 -1
  123. package/src/supabase/utils/monitoring.ts +1 -0
  124. package/src/vercel/api/billing/change-plan.ts +6 -5
  125. package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
  126. package/src/vercel/api/crud/bulk.ts +7 -2
  127. package/src/vercel/api/crud/create.ts +6 -3
  128. package/src/vercel/api/crud/delete.ts +5 -2
  129. package/src/vercel/api/crud/get.ts +5 -2
  130. package/src/vercel/api/crud/list.ts +6 -3
  131. package/src/vercel/api/crud/update.ts +6 -3
  132. package/src/vercel/api/oauth/check-github-access.ts +1 -0
  133. package/src/vercel/api/oauth/exchange-token.ts +5 -2
  134. package/src/vercel/api/oauth/grant-github-access.ts +1 -0
  135. package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
  136. package/src/vercel/baseFunction.ts +5 -1
  137. package/lib/chunks/chunk-2A4FPYNB.js.map +0 -7
  138. package/lib/chunks/chunk-2IFFIUFV.js +0 -23
  139. package/lib/chunks/chunk-2IFFIUFV.js.map +0 -7
  140. package/lib/chunks/chunk-FQSQGOBN.js +0 -22
  141. package/lib/chunks/chunk-FQSQGOBN.js.map +0 -7
  142. package/lib/chunks/chunk-G4FO76EA.js +0 -22
  143. package/lib/chunks/chunk-G4FO76EA.js.map +0 -7
  144. package/lib/chunks/chunk-LSM5Y2E5.js +0 -22
  145. package/lib/chunks/chunk-LSM5Y2E5.js.map +0 -7
  146. package/lib/chunks/chunk-M4JV2JCF.js +0 -22
  147. package/lib/chunks/chunk-M4JV2JCF.js.map +0 -7
  148. package/lib/chunks/chunk-OZX5ZG44.js +0 -22
  149. package/lib/chunks/chunk-PWAGW4R6.js +0 -22
  150. package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
  151. package/lib/chunks/chunk-UYI56E6Q.js +0 -151
  152. package/lib/chunks/chunk-UYI56E6Q.js.map +0 -7
  153. package/lib/chunks/chunk-ZVHC2CAV.js +0 -22
  154. package/lib/chunks/chunk-ZVHC2CAV.js.map +0 -7
  155. package/lib/shared/utils/functionWrapper.d.ts +0 -36
  156. package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
  157. package/src/shared/utils/functionWrapper.ts +0 -73
  158. /package/lib/chunks/{chunk-PJCJ5H2O.js.map → chunk-UH445BGK.js.map} +0 -0
  159. /package/lib/chunks/{monitoring-UIDJS2KA.js.map → monitoring-LXNVBD3G.js.map} +0 -0
  160. /package/lib/chunks/{rateLimiter-WNWHI3B4.js.map → rateLimiter-GG5LPWXJ.js.map} +0 -0
  161. /package/lib/chunks/{server-RYGEBS2B.js.map → server-NODQAE3F.js.map} +0 -0
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/shared/billing/stripeClient.ts", "../../src/shared/billing/helpers/subscriptionManagement.ts"],
4
- "sourcesContent": ["// packages/functions/src/shared/billing/stripeClient.ts\n\n/**\n * @fileoverview Stripe client for billing functions\n * @description Lazily initialized Stripe SDK instance shared by the Firebase,\n * Vercel and Supabase billing handlers. Kept apart from `shared/utils.ts` so\n * code that does not bill (CRUD, auth) never loads the Stripe SDK.\n *\n * @version 0.2.1\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport Stripe from 'stripe';\n\nimport { STRIPE_API_VERSION_PIN } from './apiVersion.js';\n\n// Lazy initialization of Stripe\nlet _stripe: Stripe | null = null;\n\n/**\n * Initialize Stripe explicitly (e.g. with a secret from defineSecret).\n * API version: `STRIPE_API_VERSION`, else {@link STRIPE_API_VERSION_PIN}.\n * @param apiKey - Stripe secret key\n *\n * @version 0.2.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function initStripe(apiKey: string) {\n if (!apiKey) throw new Error('Stripe API key is required');\n\n // Unset: the framework pin (pre-basil fields are still read by subscription handlers)\n const apiVersion = process.env.STRIPE_API_VERSION || STRIPE_API_VERSION_PIN;\n\n _stripe = new Stripe(apiKey, {\n apiVersion: apiVersion as any,\n });\n return _stripe;\n}\n\n/**\n * Get Stripe instance with lazy initialization\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function getStripe(): Stripe {\n if (!_stripe) {\n // Legacy/Vercel fallback: Try process.env\n const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;\n if (STRIPE_SECRET_KEY) {\n initStripe(STRIPE_SECRET_KEY);\n } else {\n throw new Error(\n 'Stripe not initialized. Call initStripe() or set STRIPE_SECRET_KEY env var.'\n );\n }\n }\n // We know _stripe is set here or we threw\n return _stripe!;\n}\n\n/**\n * Lazy-initialized Stripe instance proxy\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport const stripe = new Proxy({} as Stripe, {\n get(target, prop) {\n return getStripe()[prop as keyof Stripe];\n },\n});\n\n/**\n * Validates that required Stripe environment variables are set\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function validateStripeEnvironment(): void {\n // Functions v2 automatically injects secrets as process.env when declared in config\n const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;\n if (!STRIPE_SECRET_KEY) {\n throw new Error('Missing STRIPE_SECRET_KEY environment variable');\n }\n}\n", "// packages/functions/src/shared/billing/helpers/subscriptionManagement.ts\n\n/**\n * @fileoverview Shared Subscription Management Logic\n * @description Platform-agnostic subscription management functions\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport type Stripe from 'stripe';\n\nimport { SUBSCRIPTION_STATUS } from '@donotdev/core/server';\nimport type { BillingAuthProvider } from '@donotdev/core/server';\n\nimport { updateUserSubscription } from './updateUserSubscription.js';\nimport { handleError } from '../../errorHandling.js';\nimport { stripe, validateStripeEnvironment } from '../stripeClient.js';\n\n/**\n * Cancel user subscription at period end\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function cancelUserSubscription(\n userId: string,\n authProvider: BillingAuthProvider\n): Promise<{ success: boolean; endsAt: string }> {\n validateStripeEnvironment();\n\n // Get user's current subscription\n const user = await authProvider.getUser(userId);\n const currentClaims = user.customClaims || {};\n const subscription = currentClaims.subscription as\n | { subscriptionId?: string; tier?: string }\n | undefined;\n const subscriptionId = subscription?.subscriptionId;\n\n if (!subscriptionId) {\n throw handleError(new Error('No active subscription found'));\n }\n\n // Cancel at period end (don't delete immediately)\n const updatedSubscription = (await stripe.subscriptions.update(\n subscriptionId,\n {\n cancel_at_period_end: true,\n }\n )) as Stripe.Subscription;\n\n // Filter status to valid SubscriptionStatus values\n const validStatuses = [\n 'active',\n 'canceled',\n 'past_due',\n 'trialing',\n 'incomplete',\n ] as const;\n const status = validStatuses.includes(updatedSubscription.status as any)\n ? (updatedSubscription.status as (typeof validStatuses)[number])\n : 'incomplete';\n\n // Update Firebase Auth claims\n await updateUserSubscription(\n userId,\n {\n tier: subscription?.tier || 'free',\n status,\n subscriptionEnd: new Date(\n (updatedSubscription as any).current_period_end * 1000\n ).toISOString(),\n cancelAtPeriodEnd: true,\n subscriptionId: updatedSubscription.id,\n customerId: updatedSubscription.customer as string,\n },\n authProvider\n );\n\n return {\n success: true,\n endsAt: new Date(\n (updatedSubscription as any).current_period_end * 1000\n ).toISOString(),\n };\n}\n\n/**\n * Change user subscription plan\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function changeUserPlan(\n userId: string,\n newPriceId: string,\n billingConfigKey: string,\n billingConfig: Record<string, any>,\n authProvider: BillingAuthProvider\n): Promise<{ success: boolean; newTier: string; newPrice: number }> {\n validateStripeEnvironment();\n\n // Validate new plan exists in config\n const billingItem = billingConfig[billingConfigKey];\n if (!billingItem || billingItem.type !== 'StripeSubscription') {\n throw handleError(new Error('Invalid plan'));\n }\n\n // Validate price ID matches config\n if (billingItem.priceId !== newPriceId) {\n throw handleError(new Error('Price ID mismatch with configuration'));\n }\n\n // Get current subscription\n const user = await authProvider.getUser(userId);\n const currentClaims = user.customClaims || {};\n const subscription = currentClaims.subscription as\n | { subscriptionId?: string }\n | undefined;\n const subscriptionId = subscription?.subscriptionId;\n\n if (!subscriptionId) {\n throw handleError(new Error('No active subscription found'));\n }\n\n // Get current subscription from Stripe\n const currentSubscription = (await stripe.subscriptions.retrieve(\n subscriptionId\n )) as Stripe.Subscription;\n\n // Update subscription in Stripe\n const updatedSubscription = (await stripe.subscriptions.update(\n subscriptionId,\n {\n items: [\n {\n id: currentSubscription.items.data[0]?.id,\n price: newPriceId,\n },\n ],\n proration_behavior: 'create_prorations', // Pro-rate the change\n }\n )) as Stripe.Subscription;\n\n // Filter status to valid SubscriptionStatus values\n const validStatuses = [\n 'active',\n 'canceled',\n 'past_due',\n 'trialing',\n 'incomplete',\n ] as const;\n const status = validStatuses.includes(updatedSubscription.status as any)\n ? (updatedSubscription.status as (typeof validStatuses)[number])\n : 'incomplete';\n\n // Update Firebase Auth claims\n await updateUserSubscription(\n userId,\n {\n tier: billingItem.tier,\n status,\n subscriptionEnd: new Date(\n (updatedSubscription as any).current_period_end * 1000\n ).toISOString(),\n cancelAtPeriodEnd: (updatedSubscription as any).cancel_at_period_end,\n subscriptionId: updatedSubscription.id,\n customerId: updatedSubscription.customer as string,\n },\n authProvider\n );\n\n return {\n success: true,\n newTier: billingItem.tier,\n newPrice: billingItem.price,\n };\n}\n\n/**\n * Create Stripe Customer Portal session\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function createCustomerPortalSession(\n userId: string,\n authProvider: BillingAuthProvider,\n returnUrl?: string\n): Promise<{ url: string }> {\n validateStripeEnvironment();\n\n // Get customer ID from user claims\n const user = await authProvider.getUser(userId);\n const currentClaims = user.customClaims || {};\n const subscription = currentClaims.subscription as\n | { customerId?: string }\n | undefined;\n const customerId = subscription?.customerId;\n\n if (!customerId) {\n throw handleError(new Error('No customer found'));\n }\n\n // Validate returnUrl domain\n if (returnUrl) {\n const parsed = new URL(returnUrl);\n const frontendUrl = new URL(process.env.FRONTEND_URL || '');\n if (parsed.origin !== frontendUrl.origin) {\n throw new Error('Invalid return URL: must match frontend domain');\n }\n }\n\n // Create portal session\n const session = await stripe.billingPortal.sessions.create({\n customer: customerId,\n return_url: returnUrl || `${process.env.FRONTEND_URL}/billing`,\n });\n\n return {\n url: session.url,\n };\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;yFAaA,OAAOA,MAAY,SAKnB,IAAIC,EAAyB,KAWtB,SAASC,EAAWC,EAAgB,CACzC,GAAI,CAACA,EAAQ,MAAM,IAAI,MAAM,4BAA4B,EAGzD,IAAMC,EAAa,QAAQ,IAAI,oBAAsBC,EAErD,OAAAJ,EAAU,IAAIK,EAAOH,EAAQ,CAC3B,WAAYC,CACd,CAAC,EACMH,CACT,CAVgBM,EAAAL,EAAA,cAmBT,SAASM,GAAoB,CAClC,GAAI,CAACP,EAAS,CAEZ,IAAMQ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c,SAAS,OAAO,CACzD,SAAUY,EACV,WAAYD,GAAa,GAAG,QAAQ,IAAI,YAAY,UACtD,CAAC,GAGc,GACf,CACF,CArCsBR,EAAAO,EAAA",
6
- "names": ["Stripe", "_stripe", "initStripe", "apiKey", "apiVersion", "STRIPE_API_VERSION_PIN", "Stripe", "__name", "getStripe", "STRIPE_SECRET_KEY", "stripe", "target", "prop", "validateStripeEnvironment", "cancelUserSubscription", "userId", "authProvider", "validateStripeEnvironment", "subscription", "subscriptionId", "handleError", "updatedSubscription", "stripe", "status", "updateUserSubscription", "__name", "changeUserPlan", "newPriceId", "billingConfigKey", "billingConfig", "billingItem", "currentSubscription", "createCustomerPortalSession", "returnUrl", "customerId", "parsed", "frontendUrl"]
7
- }
@@ -1,36 +0,0 @@
1
- /**
2
- * @fileoverview Simple DRY wrapper for functions with schema validation
3
- * @description Eliminates duplication by providing a clean pattern for all functions
4
- *
5
- * @version 0.1.0
6
- * @since 0.0.1
7
- * @author AMBROISE PARK Consulting
8
- */
9
- import type { CallableRequest } from 'firebase-functions/v2/https';
10
- import type { NextApiRequest, NextApiResponse } from 'next';
11
- import * as v from 'valibot';
12
- /**
13
- * Simple wrapper that validates data against schema and calls the handler
14
- * This is the ONLY pattern needed for all functions
15
- *
16
- * @version 0.1.0
17
- * @since 0.0.1
18
- * @author AMBROISE PARK Consulting
19
- */
20
- export declare function withValidation<TData, TResponse>(schema: v.BaseSchema<unknown, TData, v.BaseIssue<unknown>>, handler: (data: TData) => Promise<TResponse>): (data: any) => Promise<TResponse>;
21
- /**
22
- * Firebase function wrapper
23
- *
24
- * @version 0.1.0
25
- * @since 0.0.1
26
- * @author AMBROISE PARK Consulting
27
- */
28
- export declare function firebaseFunction<TData, TResponse>(schema: v.BaseSchema<unknown, TData, v.BaseIssue<unknown>>, handler: (data: TData) => Promise<TResponse>): (request: CallableRequest<TData>) => Promise<TResponse>;
29
- /**
30
- * Vercel function wrapper
31
- *
32
- * @version 0.1.0
33
- * @since 0.0.1
34
- * @author AMBROISE PARK Consulting
35
- */
36
- export declare function vercelFunction<TData, TResponse>(schema: v.BaseSchema<unknown, TData, v.BaseIssue<unknown>>, handler: (req: NextApiRequest, res: NextApiResponse, data: TData) => Promise<TResponse>): (req: NextApiRequest, res: NextApiResponse) => Promise<TResponse>;
@@ -1,122 +0,0 @@
1
- // packages/functions/src/shared/utils/__tests__/functionWrapper.test.ts
2
-
3
- /**
4
- * @fileoverview Tests for withValidation, firebaseFunction, vercelFunction
5
- * @description Unit tests for schema validation wrappers.
6
- *
7
- * @version 0.1.0
8
- * @since 0.0.1
9
- * @author AMBROISE PARK Consulting
10
- */
11
-
12
- import * as v from 'valibot';
13
- import { describe, it, expect, vi, beforeEach } from 'vitest';
14
-
15
- import {
16
- withValidation,
17
- firebaseFunction,
18
- vercelFunction,
19
- } from '../functionWrapper';
20
-
21
- // ---------------------------------------------------------------------------
22
- // Schemas and fixtures
23
- // ---------------------------------------------------------------------------
24
-
25
- const TestSchema = v.object({
26
- name: v.pipe(v.string(), v.minLength(1)),
27
- count: v.optional(v.pipe(v.number(), v.minValue(0))),
28
- });
29
-
30
- type TestData = v.InferOutput<typeof TestSchema>;
31
-
32
- // ---------------------------------------------------------------------------
33
- // withValidation
34
- // ---------------------------------------------------------------------------
35
-
36
- describe('withValidation', () => {
37
- it('returns handler result when data is valid', async () => {
38
- const handler = vi.fn().mockResolvedValue({ id: '123' });
39
- const wrapped = withValidation(TestSchema, handler);
40
- const data = { name: 'foo', count: 2 };
41
-
42
- const result = await wrapped(data);
43
-
44
- expect(result).toEqual({ id: '123' });
45
- expect(handler).toHaveBeenCalledWith({ name: 'foo', count: 2 });
46
- });
47
-
48
- it('throws when data fails validation', async () => {
49
- const handler = vi.fn();
50
- const wrapped = withValidation(TestSchema, handler);
51
-
52
- await expect(wrapped({ name: '' })).rejects.toThrow();
53
- expect(handler).not.toHaveBeenCalled();
54
- });
55
-
56
- it('passes validated (parsed) data to handler', async () => {
57
- const handler = vi.fn().mockResolvedValue(undefined);
58
- const wrapped = withValidation(TestSchema, handler);
59
- await wrapped({ name: 'a', count: 0 });
60
-
61
- expect(handler).toHaveBeenCalledWith(
62
- expect.objectContaining({ name: 'a', count: 0 })
63
- );
64
- });
65
- });
66
-
67
- // ---------------------------------------------------------------------------
68
- // firebaseFunction
69
- // ---------------------------------------------------------------------------
70
-
71
- describe('firebaseFunction', () => {
72
- it('calls handler with parsed request.data', async () => {
73
- const handler = vi.fn().mockResolvedValue({ success: true });
74
- const fn = firebaseFunction(TestSchema, handler);
75
- const request = {
76
- data: { name: 'test', count: 1 },
77
- rawRequest: {} as any,
78
- };
79
-
80
- const result = await fn(request);
81
-
82
- expect(result).toEqual({ success: true });
83
- expect(handler).toHaveBeenCalledWith({ name: 'test', count: 1 });
84
- });
85
-
86
- it('throws when request.data is invalid', async () => {
87
- const handler = vi.fn();
88
- const fn = firebaseFunction(TestSchema, handler);
89
- const request = { data: { name: '' }, rawRequest: {} as any };
90
-
91
- await expect(fn(request)).rejects.toThrow();
92
- expect(handler).not.toHaveBeenCalled();
93
- });
94
- });
95
-
96
- // ---------------------------------------------------------------------------
97
- // vercelFunction
98
- // ---------------------------------------------------------------------------
99
-
100
- describe('vercelFunction', () => {
101
- it('parses req.body and calls handler with (req, res, data)', async () => {
102
- const handler = vi.fn().mockResolvedValue({ ok: true });
103
- const fn = vercelFunction(TestSchema, handler);
104
- const req = { body: { name: 'v', count: 0 } } as any;
105
- const res = {} as any;
106
-
107
- const result = await fn(req, res);
108
-
109
- expect(result).toEqual({ ok: true });
110
- expect(handler).toHaveBeenCalledWith(req, res, { name: 'v', count: 0 });
111
- });
112
-
113
- it('throws when req.body is invalid', async () => {
114
- const handler = vi.fn();
115
- const fn = vercelFunction(TestSchema, handler);
116
- const req = { body: {} } as any;
117
- const res = {} as any;
118
-
119
- await expect(fn(req, res)).rejects.toThrow();
120
- expect(handler).not.toHaveBeenCalled();
121
- });
122
- });
@@ -1,73 +0,0 @@
1
- // packages/functions/src/shared/utils/functionWrapper.ts
2
-
3
- /**
4
- * @fileoverview Simple DRY wrapper for functions with schema validation
5
- * @description Eliminates duplication by providing a clean pattern for all functions
6
- *
7
- * @version 0.1.0
8
- * @since 0.0.1
9
- * @author AMBROISE PARK Consulting
10
- */
11
-
12
- import type { CallableRequest } from 'firebase-functions/v2/https';
13
- import type { NextApiRequest, NextApiResponse } from 'next';
14
- import * as v from 'valibot';
15
-
16
- /**
17
- * Simple wrapper that validates data against schema and calls the handler
18
- * This is the ONLY pattern needed for all functions
19
- *
20
- * @version 0.1.0
21
- * @since 0.0.1
22
- * @author AMBROISE PARK Consulting
23
- */
24
- export function withValidation<TData, TResponse>(
25
- schema: v.BaseSchema<unknown, TData, v.BaseIssue<unknown>>,
26
- handler: (data: TData) => Promise<TResponse>
27
- ) {
28
- return async (data: any): Promise<TResponse> => {
29
- // Schema handles ALL validation - no manual checks needed
30
- const validatedData = v.parse(schema, data);
31
- return await handler(validatedData);
32
- };
33
- }
34
-
35
- /**
36
- * Firebase function wrapper
37
- *
38
- * @version 0.1.0
39
- * @since 0.0.1
40
- * @author AMBROISE PARK Consulting
41
- */
42
- export function firebaseFunction<TData, TResponse>(
43
- schema: v.BaseSchema<unknown, TData, v.BaseIssue<unknown>>,
44
- handler: (data: TData) => Promise<TResponse>
45
- ) {
46
- return async (request: CallableRequest<TData>): Promise<TResponse> => {
47
- return await withValidation(schema, handler)(request.data as any);
48
- };
49
- }
50
-
51
- /**
52
- * Vercel function wrapper
53
- *
54
- * @version 0.1.0
55
- * @since 0.0.1
56
- * @author AMBROISE PARK Consulting
57
- */
58
- export function vercelFunction<TData, TResponse>(
59
- schema: v.BaseSchema<unknown, TData, v.BaseIssue<unknown>>,
60
- handler: (
61
- req: NextApiRequest,
62
- res: NextApiResponse,
63
- data: TData
64
- ) => Promise<TResponse>
65
- ) {
66
- return async (
67
- req: NextApiRequest,
68
- res: NextApiResponse
69
- ): Promise<TResponse> => {
70
- const validatedData = v.parse(schema, req.body);
71
- return await handler(req, res, validatedData);
72
- };
73
- }