@donotdev/functions 0.2.2 → 0.3.0

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 (203) hide show
  1. package/README.md +1 -1
  2. package/lib/chunks/chunk-522YXGDA.js +23 -0
  3. package/lib/chunks/chunk-522YXGDA.js.map +7 -0
  4. package/lib/chunks/chunk-7ODXXXES.js +151 -0
  5. package/lib/chunks/chunk-7ODXXXES.js.map +7 -0
  6. package/lib/chunks/chunk-CP3NNKO5.js +22 -0
  7. package/lib/chunks/chunk-CP3NNKO5.js.map +7 -0
  8. package/lib/chunks/{chunk-2A4FPYNB.js → chunk-CVYSXC27.js} +2 -2
  9. package/lib/chunks/chunk-CVYSXC27.js.map +7 -0
  10. package/lib/chunks/{chunk-PJCJ5H2O.js → chunk-HZM5X5A7.js} +2 -2
  11. package/lib/chunks/chunk-ICNQCRLV.js +22 -0
  12. package/lib/chunks/chunk-ICNQCRLV.js.map +7 -0
  13. package/lib/chunks/chunk-OAZ2JYSD.js +22 -0
  14. package/lib/chunks/chunk-OAZ2JYSD.js.map +7 -0
  15. package/lib/chunks/chunk-OKRR7ST5.js +22 -0
  16. package/lib/chunks/chunk-OKRR7ST5.js.map +7 -0
  17. package/lib/chunks/chunk-PDBNKSBQ.js +22 -0
  18. package/lib/chunks/chunk-PDBNKSBQ.js.map +7 -0
  19. package/lib/chunks/chunk-TJPJXJEK.js +22 -0
  20. package/lib/chunks/{chunk-OZX5ZG44.js.map → chunk-TJPJXJEK.js.map} +1 -1
  21. package/lib/chunks/chunk-W6W4L44F.js +22 -0
  22. package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
  23. package/lib/chunks/{monitoring-UIDJS2KA.js → monitoring-UCBNPPW2.js} +2 -2
  24. package/lib/chunks/{rateLimiter-WNWHI3B4.js → rateLimiter-XKECWM33.js} +2 -2
  25. package/lib/chunks/{server-RYGEBS2B.js → server-24XGDDO3.js} +2 -2
  26. package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
  27. package/lib/firebase/crud/aggregate.d.ts +1 -1
  28. package/lib/firebase/crud/create.d.ts +22 -1
  29. package/lib/firebase/crud/update.d.ts +27 -3
  30. package/lib/firebase/index.js +1 -1
  31. package/lib/firebase/index.js.map +3 -3
  32. package/lib/shared/billing/checkoutValidation.d.ts +1 -1
  33. package/lib/shared/billing/createCheckout.d.ts +1 -1
  34. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
  35. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -8
  36. package/lib/shared/billing/index.d.ts +2 -0
  37. package/lib/shared/billing/orderWebhook.d.ts +29 -2
  38. package/lib/shared/billing/stripePinned.d.ts +43 -0
  39. package/lib/shared/billing/verifyOrderCheckout.d.ts +53 -0
  40. package/lib/shared/crud/bulkCore.d.ts +38 -10
  41. package/lib/shared/crud/index.d.ts +1 -0
  42. package/lib/shared/crud/written.d.ts +21 -0
  43. package/lib/shared/denoEnv.d.ts +25 -0
  44. package/lib/shared/github.d.ts +0 -8
  45. package/lib/shared/index.d.ts +0 -1
  46. package/lib/shared/index.js +1 -1
  47. package/lib/shared/logger.d.ts +14 -14
  48. package/lib/shared/utils/external/subscription.d.ts +0 -8
  49. package/lib/shared/utils.d.ts +13 -10
  50. package/lib/supabase/auth/deleteAccount.d.ts +34 -2
  51. package/lib/supabase/crud/bulk.d.ts +7 -0
  52. package/lib/supabase/crud/create.d.ts +5 -9
  53. package/lib/supabase/crud/entityStore.d.ts +67 -14
  54. package/lib/supabase/crud/update.d.ts +7 -10
  55. package/lib/supabase/index.d.ts +5 -0
  56. package/lib/supabase/index.js +1 -1
  57. package/lib/supabase/index.js.map +4 -4
  58. package/lib/vercel/api/crud/create.d.ts +6 -1
  59. package/lib/vercel/api/crud/update.d.ts +8 -1
  60. package/lib/vercel/api/index.js +1 -1
  61. package/lib/vercel/api/index.js.map +3 -3
  62. package/package.json +9 -9
  63. package/src/firebase/auth/getCustomClaims.ts +2 -0
  64. package/src/firebase/auth/getUserAuthStatus.ts +2 -0
  65. package/src/firebase/auth/removeCustomClaims.ts +33 -1
  66. package/src/firebase/auth/setCustomClaims.ts +6 -0
  67. package/src/firebase/baseFunction.ts +5 -2
  68. package/src/firebase/billing/changePlan.ts +6 -5
  69. package/src/firebase/billing/createCustomerPortal.ts +6 -4
  70. package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
  71. package/src/firebase/billing/webhookHandler.ts +4 -4
  72. package/src/firebase/crud/__tests__/bulk.test.ts +50 -1
  73. package/src/firebase/crud/__tests__/create.test.ts +64 -0
  74. package/src/firebase/crud/__tests__/update.test.ts +97 -0
  75. package/src/firebase/crud/aggregate.ts +37 -19
  76. package/src/firebase/crud/bulk.ts +30 -10
  77. package/src/firebase/crud/create.ts +40 -26
  78. package/src/firebase/crud/delete.ts +6 -1
  79. package/src/firebase/crud/get.ts +12 -14
  80. package/src/firebase/crud/list.ts +23 -12
  81. package/src/firebase/crud/update.ts +49 -25
  82. package/src/firebase/helpers/githubAccessHelper.ts +3 -0
  83. package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
  84. package/src/firebase/oauth/exchangeToken.ts +4 -0
  85. package/src/firebase/oauth/getConnections.ts +1 -1
  86. package/src/firebase/oauth/githubAccess.ts +3 -0
  87. package/src/firebase/oauth/refreshToken.ts +1 -0
  88. package/src/firebase/registerCrudFunctions.ts +1 -0
  89. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
  90. package/src/shared/__tests__/bulkCore.test.ts +191 -0
  91. package/src/shared/__tests__/removeCustomClaims.test.ts +117 -0
  92. package/src/shared/__tests__/setCustomClaims.test.ts +103 -0
  93. package/src/shared/__tests__/utils.test.ts +0 -30
  94. package/src/shared/ai/classifyAIError.ts +18 -10
  95. package/src/shared/ai/createAIRoute.ts +2 -1
  96. package/src/shared/ai/resolveModelTier.ts +2 -1
  97. package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
  98. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
  99. package/src/shared/billing/__tests__/updateUserSubscription.test.ts +139 -0
  100. package/src/shared/billing/__tests__/verifyOrderCheckout.exports.test.ts +47 -0
  101. package/src/shared/billing/__tests__/verifyOrderCheckout.supabase.integration.test.ts +107 -0
  102. package/src/shared/billing/__tests__/verifyOrderCheckout.test.ts +233 -0
  103. package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
  104. package/src/shared/billing/checkoutValidation.ts +19 -2
  105. package/src/shared/billing/createCheckout.ts +56 -11
  106. package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
  107. package/src/shared/billing/helpers/updateUserSubscription.ts +10 -14
  108. package/src/shared/billing/index.ts +2 -0
  109. package/src/shared/billing/orderWebhook.ts +69 -1
  110. package/src/shared/billing/stripeClient.ts +2 -1
  111. package/src/shared/billing/stripePinned.ts +71 -0
  112. package/src/shared/billing/tierWebhookEvents.ts +3 -2
  113. package/src/shared/billing/verifyOrderCheckout.ts +142 -0
  114. package/src/shared/billing/webhookHandler.ts +5 -1
  115. package/src/shared/crud/bulkCore.ts +112 -82
  116. package/src/shared/crud/index.ts +1 -0
  117. package/src/shared/crud/written.ts +56 -0
  118. package/src/shared/denoEnv.ts +29 -0
  119. package/src/shared/email/createEmailRoute.ts +2 -2
  120. package/src/shared/errorHandling.ts +8 -8
  121. package/src/shared/firebase.ts +26 -9
  122. package/src/shared/github.ts +15 -5
  123. package/src/shared/index.d.ts +0 -9
  124. package/src/shared/index.ts +0 -1
  125. package/src/shared/logger.ts +37 -38
  126. package/src/shared/utils/external/date.ts +4 -4
  127. package/src/shared/utils/external/subscription.ts +2 -89
  128. package/src/shared/utils/firebaseHelpers.ts +2 -0
  129. package/src/shared/utils/internal/idempotency.ts +3 -0
  130. package/src/shared/utils/internal/monitoring.ts +6 -5
  131. package/src/shared/utils/internal/validation.ts +2 -0
  132. package/src/shared/utils/schemaValidation.ts +1 -0
  133. package/src/shared/utils/validation.ts +10 -20
  134. package/src/shared/utils.ts +4 -42
  135. package/src/supabase/__tests__/aggregate.test.ts +132 -0
  136. package/src/supabase/__tests__/bulk.test.ts +60 -2
  137. package/src/supabase/__tests__/create.test.ts +86 -0
  138. package/src/supabase/__tests__/entityStore.test.ts +91 -25
  139. package/src/supabase/__tests__/update.test.ts +107 -0
  140. package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
  141. package/src/supabase/auth/deleteAccount.ts +72 -5
  142. package/src/supabase/auth/removeCustomClaims.ts +7 -2
  143. package/src/supabase/auth/setCustomClaims.ts +4 -2
  144. package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
  145. package/src/supabase/crud/aggregate.ts +85 -72
  146. package/src/supabase/crud/bulk.ts +50 -0
  147. package/src/supabase/crud/create.ts +27 -33
  148. package/src/supabase/crud/delete.ts +2 -1
  149. package/src/supabase/crud/entityStore.ts +107 -18
  150. package/src/supabase/crud/get.ts +5 -13
  151. package/src/supabase/crud/list.ts +28 -21
  152. package/src/supabase/crud/update.ts +29 -24
  153. package/src/supabase/edgeFunction.ts +2 -1
  154. package/src/supabase/email/createEmailFunction.ts +2 -1
  155. package/src/supabase/index.ts +8 -0
  156. package/src/supabase/oauth/exchangeToken.ts +1 -0
  157. package/src/supabase/oauth/getConnections.ts +1 -1
  158. package/src/supabase/oauth/refreshToken.ts +1 -0
  159. package/src/supabase/registerCrudFunctions.ts +1 -0
  160. package/src/supabase/utils/idempotency.ts +1 -1
  161. package/src/supabase/utils/monitoring.ts +1 -0
  162. package/src/vercel/__tests__/bulk.test.ts +16 -8
  163. package/src/vercel/api/billing/change-plan.ts +6 -5
  164. package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
  165. package/src/vercel/api/crud/bulk.ts +34 -6
  166. package/src/vercel/api/crud/create.ts +22 -21
  167. package/src/vercel/api/crud/delete.ts +5 -2
  168. package/src/vercel/api/crud/get.ts +10 -8
  169. package/src/vercel/api/crud/list.ts +10 -8
  170. package/src/vercel/api/crud/update.ts +25 -20
  171. package/src/vercel/api/oauth/check-github-access.ts +1 -0
  172. package/src/vercel/api/oauth/exchange-token.ts +5 -2
  173. package/src/vercel/api/oauth/grant-github-access.ts +1 -0
  174. package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
  175. package/src/vercel/baseFunction.ts +5 -1
  176. package/lib/chunks/chunk-2A4FPYNB.js.map +0 -7
  177. package/lib/chunks/chunk-2IFFIUFV.js +0 -23
  178. package/lib/chunks/chunk-2IFFIUFV.js.map +0 -7
  179. package/lib/chunks/chunk-FQSQGOBN.js +0 -22
  180. package/lib/chunks/chunk-FQSQGOBN.js.map +0 -7
  181. package/lib/chunks/chunk-G4FO76EA.js +0 -22
  182. package/lib/chunks/chunk-G4FO76EA.js.map +0 -7
  183. package/lib/chunks/chunk-LSM5Y2E5.js +0 -22
  184. package/lib/chunks/chunk-LSM5Y2E5.js.map +0 -7
  185. package/lib/chunks/chunk-M4JV2JCF.js +0 -22
  186. package/lib/chunks/chunk-M4JV2JCF.js.map +0 -7
  187. package/lib/chunks/chunk-OZX5ZG44.js +0 -22
  188. package/lib/chunks/chunk-PWAGW4R6.js +0 -22
  189. package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
  190. package/lib/chunks/chunk-UYI56E6Q.js +0 -151
  191. package/lib/chunks/chunk-UYI56E6Q.js.map +0 -7
  192. package/lib/chunks/chunk-ZVHC2CAV.js +0 -22
  193. package/lib/chunks/chunk-ZVHC2CAV.js.map +0 -7
  194. package/lib/shared/schema.d.ts +0 -56
  195. package/lib/shared/utils/functionWrapper.d.ts +0 -36
  196. package/src/shared/__tests__/schema.test.ts +0 -219
  197. package/src/shared/schema.ts +0 -192
  198. package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
  199. package/src/shared/utils/functionWrapper.ts +0 -73
  200. /package/lib/chunks/{chunk-PJCJ5H2O.js.map → chunk-HZM5X5A7.js.map} +0 -0
  201. /package/lib/chunks/{monitoring-UIDJS2KA.js.map → monitoring-UCBNPPW2.js.map} +0 -0
  202. /package/lib/chunks/{rateLimiter-WNWHI3B4.js.map → rateLimiter-XKECWM33.js.map} +0 -0
  203. /package/lib/chunks/{server-RYGEBS2B.js.map → server-24XGDDO3.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": "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",
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,56 +0,0 @@
1
- /** Visibility levels matching @donotdev/core */
2
- type Visibility = 'guest' | 'user' | 'admin' | 'technical' | 'hidden' | 'owner';
3
- /**
4
- * Determines if a field should be visible based on its visibility setting
5
- * and the user's authentication/admin status.
6
- *
7
- * Visibility levels:
8
- * - 'guest': Always visible (even to unauthenticated users)
9
- * - 'user': Visible to authenticated users (users see both guest and user fields)
10
- * - 'admin': Visible only to admins
11
- * - 'technical': Visible to admins only (shown as read-only in edit forms)
12
- * - 'hidden': Never visible (passwords, tokens, API keys - only in DB)
13
- * - 'owner': Visible only when uid matches one of entity.ownership.ownerFields (requires document context; here treated as not visible for aggregate)
14
- * - undefined: Defaults to 'user' behavior (visible to authenticated users)
15
- *
16
- * @param key - The name (key) of the field.
17
- * @param visibility - The visibility setting.
18
- * @param isAdmin - Whether the current user is an admin.
19
- * @param isAuthenticated - Whether the current user is authenticated (defaults to true for backward compat).
20
- * @returns True if the field should be visible, false otherwise.
21
- *
22
- * @version 0.1.0
23
- * @since 0.0.1
24
- * @author AMBROISE PARK Consulting
25
- */
26
- export declare function isFieldVisible(key: string, visibility: Visibility | undefined, isAdmin: boolean, isAuthenticated?: boolean): boolean;
27
- /**
28
- * Extracts the names of all fields from a Valibot object schema that should be visible
29
- * based on the user's administrative status and the visibility rules defined in the schema.
30
- *
31
- * @param schema - The Valibot schema, expected to be an object schema (v.object).
32
- * @param isAdmin - Whether the current user is an admin.
33
- * @returns An array of strings, where each string is the name of a visible field.
34
- * Returns an empty array if the schema is not an object schema or has no entries.
35
- *
36
- * @version 0.1.0
37
- * @since 0.0.1
38
- * @author AMBROISE PARK Consulting
39
- */
40
- export declare function getVisibleFields(schema: any, // Accept any Valibot type, but process only objects
41
- isAdmin: boolean): string[];
42
- /**
43
- * Filters the fields of a data object based on visibility rules defined
44
- * in a Valibot schema and the user's admin status.
45
- *
46
- * @template T - The expected type of the data object.
47
- * @param {T | null | undefined} data - The document data object to filter.
48
- * @param {any} schema - The Valibot schema defining the structure and field visibility.
49
- * Expected to be a v.object schema with entries property.
50
- * @param {boolean} isAdmin - Whether the current user has administrative privileges.
51
- * @returns {Partial<T>} A new object containing only the fields visible to the user,
52
- * or an empty object if input data is null/undefined.
53
- */
54
- export declare function filterVisibleFields<T extends Record<string, any>>(data: T | null | undefined, schema: any, // Use any for broader compatibility
55
- isAdmin: boolean): Partial<T>;
56
- export {};
@@ -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,219 +0,0 @@
1
- import { describe, it, expect, vi } from 'vitest';
2
-
3
- import {
4
- isFieldVisible,
5
- getVisibleFields,
6
- filterVisibleFields,
7
- } from '../schema';
8
-
9
- // ---------------------------------------------------------------------------
10
- // isFieldVisible
11
- // ---------------------------------------------------------------------------
12
-
13
- describe('isFieldVisible', () => {
14
- describe('hidden visibility', () => {
15
- it('never visible regardless of auth/admin', () => {
16
- expect(isFieldVisible('secret', 'hidden', true, true)).toBe(false);
17
- expect(isFieldVisible('secret', 'hidden', false, true)).toBe(false);
18
- expect(isFieldVisible('secret', 'hidden', true, false)).toBe(false);
19
- expect(isFieldVisible('secret', 'hidden', false, false)).toBe(false);
20
- });
21
- });
22
-
23
- describe('guest visibility', () => {
24
- it('always visible regardless of auth/admin', () => {
25
- expect(isFieldVisible('title', 'guest', true, true)).toBe(true);
26
- expect(isFieldVisible('title', 'guest', false, true)).toBe(true);
27
- expect(isFieldVisible('title', 'guest', true, false)).toBe(true);
28
- expect(isFieldVisible('title', 'guest', false, false)).toBe(true);
29
- });
30
- });
31
-
32
- describe('admin visibility', () => {
33
- it('visible only to admins', () => {
34
- expect(isFieldVisible('config', 'admin', true, true)).toBe(true);
35
- expect(isFieldVisible('config', 'admin', false, true)).toBe(false);
36
- expect(isFieldVisible('config', 'admin', true, false)).toBe(true);
37
- expect(isFieldVisible('config', 'admin', false, false)).toBe(false);
38
- });
39
- });
40
-
41
- describe('technical visibility', () => {
42
- it('visible only to admins', () => {
43
- expect(isFieldVisible('debug', 'technical', true)).toBe(true);
44
- expect(isFieldVisible('debug', 'technical', false)).toBe(false);
45
- });
46
- });
47
-
48
- describe('owner visibility', () => {
49
- it('returns false in aggregate context', () => {
50
- expect(isFieldVisible('email', 'owner', true, true)).toBe(false);
51
- expect(isFieldVisible('email', 'owner', false, true)).toBe(false);
52
- });
53
- });
54
-
55
- describe('user visibility', () => {
56
- it('visible to authenticated users', () => {
57
- expect(isFieldVisible('profile', 'user', false, true)).toBe(true);
58
- expect(isFieldVisible('profile', 'user', false, false)).toBe(false);
59
- });
60
-
61
- it('visible to admins', () => {
62
- expect(isFieldVisible('profile', 'user', true, true)).toBe(true);
63
- });
64
- });
65
-
66
- describe('undefined visibility (defaults to user)', () => {
67
- it('visible to authenticated users', () => {
68
- expect(isFieldVisible('field', undefined, false, true)).toBe(true);
69
- expect(isFieldVisible('field', undefined, false, false)).toBe(false);
70
- });
71
-
72
- it('defaults isAuthenticated to true', () => {
73
- expect(isFieldVisible('field', undefined, false)).toBe(true);
74
- });
75
- });
76
- });
77
-
78
- // ---------------------------------------------------------------------------
79
- // getVisibleFields
80
- // ---------------------------------------------------------------------------
81
-
82
- describe('getVisibleFields', () => {
83
- it('returns empty array for non-object schema', () => {
84
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
85
-
86
- expect(getVisibleFields(null, false)).toEqual([]);
87
- expect(getVisibleFields('string', false)).toEqual([]);
88
- expect(getVisibleFields({}, false)).toEqual([]);
89
-
90
- warnSpy.mockRestore();
91
- });
92
-
93
- it('returns all fields without visibility for authenticated user', () => {
94
- const schema = {
95
- entries: {
96
- name: {},
97
- email: {},
98
- },
99
- };
100
-
101
- const result = getVisibleFields(schema, false);
102
-
103
- expect(result).toContain('name');
104
- expect(result).toContain('email');
105
- });
106
-
107
- it('excludes hidden fields', () => {
108
- const schema = {
109
- entries: {
110
- name: {},
111
- password: { visibility: 'hidden' },
112
- },
113
- };
114
-
115
- const result = getVisibleFields(schema, true);
116
-
117
- expect(result).toContain('name');
118
- expect(result).not.toContain('password');
119
- });
120
-
121
- it('includes admin fields only for admins', () => {
122
- const schema = {
123
- entries: {
124
- name: {},
125
- config: { visibility: 'admin' },
126
- },
127
- };
128
-
129
- expect(getVisibleFields(schema, true)).toContain('config');
130
- expect(getVisibleFields(schema, false)).not.toContain('config');
131
- });
132
-
133
- it('includes guest fields for everyone', () => {
134
- const schema = {
135
- entries: {
136
- title: { visibility: 'guest' },
137
- },
138
- };
139
-
140
- expect(getVisibleFields(schema, false)).toContain('title');
141
- expect(getVisibleFields(schema, true)).toContain('title');
142
- });
143
- });
144
-
145
- // ---------------------------------------------------------------------------
146
- // filterVisibleFields
147
- // ---------------------------------------------------------------------------
148
-
149
- describe('filterVisibleFields', () => {
150
- it('returns empty object for null data', () => {
151
- const schema = { entries: { name: {} } };
152
-
153
- expect(filterVisibleFields(null, schema, false)).toEqual({});
154
- });
155
-
156
- it('returns empty object for undefined data', () => {
157
- const schema = { entries: { name: {} } };
158
-
159
- expect(filterVisibleFields(undefined, schema, false)).toEqual({});
160
- });
161
-
162
- it('filters data to only visible fields', () => {
163
- const schema = {
164
- entries: {
165
- name: { visibility: 'guest' },
166
- secret: { visibility: 'hidden' },
167
- config: { visibility: 'admin' },
168
- },
169
- };
170
-
171
- const data = { name: 'Alice', secret: 'pw123', config: 'x', extra: 'y' };
172
-
173
- const result = filterVisibleFields(data, schema, false);
174
-
175
- expect(result).toEqual({ name: 'Alice' });
176
- });
177
-
178
- it('includes admin fields when isAdmin is true', () => {
179
- const schema = {
180
- entries: {
181
- name: { visibility: 'guest' },
182
- config: { visibility: 'admin' },
183
- },
184
- };
185
-
186
- const data = { name: 'Alice', config: 'x' };
187
- const result = filterVisibleFields(data, schema, true);
188
-
189
- expect(result).toEqual({ name: 'Alice', config: 'x' });
190
- });
191
-
192
- it('ignores data keys not in schema', () => {
193
- const schema = {
194
- entries: {
195
- name: {},
196
- },
197
- };
198
-
199
- const data = { name: 'Alice', extraField: 'ignored' };
200
- const result = filterVisibleFields(data, schema, false);
201
-
202
- expect(result).toEqual({ name: 'Alice' });
203
- });
204
-
205
- it('handles missing data keys gracefully', () => {
206
- const schema = {
207
- entries: {
208
- name: {},
209
- missing: {},
210
- },
211
- };
212
-
213
- const data = { name: 'Alice' };
214
- const result = filterVisibleFields(data, schema, false);
215
-
216
- expect(result).toEqual({ name: 'Alice' });
217
- expect(result).not.toHaveProperty('missing');
218
- });
219
- });
@@ -1,192 +0,0 @@
1
- // packages/functions/src/shared/schema.ts
2
-
3
- /**
4
- * @fileoverview Schema utilities for functions
5
- * @description Server-safe schema field visibility utilities
6
- *
7
- * @version 0.1.0
8
- * @since 0.0.1
9
- * @author AMBROISE PARK Consulting
10
- */
11
-
12
- import type * as v from 'valibot';
13
-
14
- /** Visibility levels matching @donotdev/core */
15
- type Visibility = 'guest' | 'user' | 'admin' | 'technical' | 'hidden' | 'owner';
16
-
17
- // Define a type for the custom visibility property we might add to Valibot schemas
18
- interface ValibotSchemaWithVisibility extends v.BaseSchema<
19
- unknown,
20
- any,
21
- v.BaseIssue<unknown>
22
- > {
23
- visibility?: Visibility;
24
- }
25
-
26
- /**
27
- * Safely extracts the visibility setting from a Valibot field schema.
28
- * Looks for a custom 'visibility' property on the schema object.
29
- *
30
- * @param field - A Valibot schema field (e.g., v.string()).
31
- * @returns The visibility setting if found, otherwise undefined.
32
- *
33
- * @version 0.1.0
34
- * @since 0.0.1
35
- * @author AMBROISE PARK Consulting
36
- */
37
- function getFieldVisibility(field: any): Visibility | undefined {
38
- // Check if the field has visibility property
39
- if (field && typeof field === 'object' && 'visibility' in field) {
40
- return (field as ValibotSchemaWithVisibility).visibility;
41
- }
42
- return undefined;
43
- }
44
-
45
- /**
46
- * Determines if a field should be visible based on its visibility setting
47
- * and the user's authentication/admin status.
48
- *
49
- * Visibility levels:
50
- * - 'guest': Always visible (even to unauthenticated users)
51
- * - 'user': Visible to authenticated users (users see both guest and user fields)
52
- * - 'admin': Visible only to admins
53
- * - 'technical': Visible to admins only (shown as read-only in edit forms)
54
- * - 'hidden': Never visible (passwords, tokens, API keys - only in DB)
55
- * - 'owner': Visible only when uid matches one of entity.ownership.ownerFields (requires document context; here treated as not visible for aggregate)
56
- * - undefined: Defaults to 'user' behavior (visible to authenticated users)
57
- *
58
- * @param key - The name (key) of the field.
59
- * @param visibility - The visibility setting.
60
- * @param isAdmin - Whether the current user is an admin.
61
- * @param isAuthenticated - Whether the current user is authenticated (defaults to true for backward compat).
62
- * @returns True if the field should be visible, false otherwise.
63
- *
64
- * @version 0.1.0
65
- * @since 0.0.1
66
- * @author AMBROISE PARK Consulting
67
- */
68
- export function isFieldVisible(
69
- key: string,
70
- visibility: Visibility | undefined,
71
- isAdmin: boolean,
72
- isAuthenticated: boolean = true
73
- ): boolean {
74
- // Hidden fields are never exposed
75
- if (visibility === 'hidden') {
76
- return false;
77
- }
78
-
79
- // Guest fields are always visible
80
- if (visibility === 'guest') {
81
- return true;
82
- }
83
-
84
- // Admin fields are visible only to admins
85
- if (visibility === 'admin') {
86
- return isAdmin;
87
- }
88
-
89
- // Technical fields are visible only to admins
90
- if (visibility === 'technical') {
91
- return isAdmin;
92
- }
93
-
94
- // Owner: requires per-document check (documentData, uid, ownership); not available in aggregate context
95
- if (visibility === 'owner') {
96
- return false;
97
- }
98
-
99
- // User fields (or undefined/default) are visible to authenticated users
100
- if (visibility === 'user' || visibility === undefined) {
101
- return isAuthenticated;
102
- }
103
-
104
- // Fallback: hide unknown visibility levels
105
- return false;
106
- }
107
-
108
- /**
109
- * Extracts the names of all fields from a Valibot object schema that should be visible
110
- * based on the user's administrative status and the visibility rules defined in the schema.
111
- *
112
- * @param schema - The Valibot schema, expected to be an object schema (v.object).
113
- * @param isAdmin - Whether the current user is an admin.
114
- * @returns An array of strings, where each string is the name of a visible field.
115
- * Returns an empty array if the schema is not an object schema or has no entries.
116
- *
117
- * @version 0.1.0
118
- * @since 0.0.1
119
- * @author AMBROISE PARK Consulting
120
- */
121
- export function getVisibleFields(
122
- schema: any, // Accept any Valibot type, but process only objects
123
- isAdmin: boolean
124
- ): string[] {
125
- // Valibot object schemas use .entries property
126
- // Ensure the schema is an object schema and has entries
127
- if (!schema || typeof schema !== 'object' || !schema.entries) {
128
- console.warn(
129
- 'getVisibleFields expects a Valibot object schema (v.object).'
130
- );
131
- return []; // Return empty array if not an object schema
132
- }
133
-
134
- // Extract the entries (field definitions) from the schema
135
- const entries = schema.entries as Record<
136
- string,
137
- v.BaseSchema<unknown, any, v.BaseIssue<unknown>>
138
- >;
139
- const visibleFieldNames: string[] = [];
140
-
141
- // Iterate over each field defined in the schema's entries
142
- for (const [key, field] of Object.entries(entries)) {
143
- // Get the visibility setting for the current field
144
- const visibility = getFieldVisibility(field);
145
-
146
- // Check if the field is visible based on its key, visibility setting, and admin status
147
- if (isFieldVisible(key, visibility, isAdmin)) {
148
- visibleFieldNames.push(key); // Add the field name to the list if visible
149
- }
150
- }
151
-
152
- return visibleFieldNames;
153
- }
154
-
155
- /**
156
- * Filters the fields of a data object based on visibility rules defined
157
- * in a Valibot schema and the user's admin status.
158
- *
159
- * @template T - The expected type of the data object.
160
- * @param {T | null | undefined} data - The document data object to filter.
161
- * @param {any} schema - The Valibot schema defining the structure and field visibility.
162
- * Expected to be a v.object schema with entries property.
163
- * @param {boolean} isAdmin - Whether the current user has administrative privileges.
164
- * @returns {Partial<T>} A new object containing only the fields visible to the user,
165
- * or an empty object if input data is null/undefined.
166
- */
167
- export function filterVisibleFields<T extends Record<string, any>>(
168
- data: T | null | undefined,
169
- schema: any, // Use any for broader compatibility
170
- isAdmin: boolean
171
- ): Partial<T> {
172
- if (!data) {
173
- return {}; // Return empty object if data is null or undefined
174
- }
175
-
176
- // Get the list of field names visible based on the schema and admin status
177
- const visibleFieldNames = getVisibleFields(schema, isAdmin);
178
-
179
- // Create a new result object
180
- const result: Partial<T> = {};
181
-
182
- // Iterate over the visible field names and copy corresponding values from the original data
183
- for (const key of visibleFieldNames) {
184
- // Check if the key exists in the original data object
185
- if (Object.prototype.hasOwnProperty.call(data, key)) {
186
- // Type assertion needed as key is string, but we expect it to be keyof T
187
- result[key as keyof T] = data[key as keyof T];
188
- }
189
- }
190
-
191
- return result;
192
- }
@@ -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
- });