@donotdev/functions 0.1.44 → 0.2.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.
- package/README.md +25 -14
- package/lib/chunks/chunk-3F4BWKQD.js +22 -0
- package/lib/chunks/chunk-3F4BWKQD.js.map +7 -0
- package/lib/chunks/chunk-5IPULSUX.js +22 -0
- package/lib/chunks/chunk-5IPULSUX.js.map +7 -0
- package/lib/chunks/chunk-6USHTJED.js +22 -0
- package/lib/chunks/chunk-6USHTJED.js.map +7 -0
- package/lib/chunks/chunk-AYY7UXNI.js +22 -0
- package/lib/chunks/chunk-AYY7UXNI.js.map +7 -0
- package/lib/chunks/chunk-CXBSROEW.js +23 -0
- package/lib/chunks/chunk-CXBSROEW.js.map +7 -0
- package/lib/chunks/chunk-GYTCWMXV.js +22 -0
- package/lib/chunks/chunk-GYTCWMXV.js.map +7 -0
- package/lib/chunks/chunk-HLNYUAZH.js +22 -0
- package/lib/chunks/chunk-HLNYUAZH.js.map +7 -0
- package/lib/chunks/chunk-LCDLG4VG.js +151 -0
- package/lib/chunks/chunk-LCDLG4VG.js.map +7 -0
- package/lib/chunks/chunk-MQANUSY3.js +22 -0
- package/lib/chunks/chunk-MQANUSY3.js.map +7 -0
- package/lib/chunks/chunk-OFQVO3FD.js +22 -0
- package/lib/chunks/chunk-OFQVO3FD.js.map +7 -0
- package/lib/chunks/chunk-PWAGW4R6.js +22 -0
- package/lib/chunks/chunk-PWAGW4R6.js.map +7 -0
- package/lib/chunks/chunk-US2VOP4S.js +22 -0
- package/lib/chunks/chunk-US2VOP4S.js.map +7 -0
- package/lib/chunks/chunk-YTKDNZNW.js +22 -0
- package/lib/chunks/chunk-YTKDNZNW.js.map +7 -0
- package/lib/chunks/monitoring-E7JBYBHQ.js +22 -0
- package/lib/chunks/monitoring-E7JBYBHQ.js.map +7 -0
- package/lib/chunks/rateLimiter-SQISLOP5.js +22 -0
- package/lib/chunks/rateLimiter-SQISLOP5.js.map +7 -0
- package/lib/chunks/server-IQ5JNJOM.js +22 -0
- package/lib/chunks/server-IQ5JNJOM.js.map +7 -0
- package/lib/firebase/auth/getCustomClaims.d.ts +1 -1
- package/lib/firebase/auth/getUserAuthStatus.d.ts +1 -1
- package/lib/firebase/auth/index.d.ts +0 -0
- package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/firebase/auth/setCustomClaims.d.ts +1 -1
- package/lib/firebase/baseFunction.d.ts +1 -1
- package/lib/firebase/billing/cancelSubscription.d.ts +0 -0
- package/lib/firebase/billing/changePlan.d.ts +0 -0
- package/lib/firebase/billing/createCheckoutSession.d.ts +2 -2
- package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
- package/lib/firebase/billing/healthCheck.d.ts +0 -0
- package/lib/firebase/billing/index.d.ts +2 -1
- package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -8
- package/lib/firebase/billing/webhookHandler.d.ts +17 -2
- package/lib/firebase/config/constants.d.ts +0 -0
- package/lib/firebase/config/index.d.ts +0 -0
- package/lib/firebase/config/secrets.d.ts +0 -0
- package/lib/firebase/crud/aggregate.d.ts +0 -9
- package/lib/firebase/crud/bulk.d.ts +2 -2
- package/lib/firebase/crud/create.d.ts +1 -1
- package/lib/firebase/crud/delete.d.ts +1 -1
- package/lib/firebase/crud/get.d.ts +1 -1
- package/lib/firebase/crud/index.d.ts +0 -0
- package/lib/firebase/crud/list.d.ts +1 -1
- package/lib/firebase/crud/update.d.ts +1 -9
- package/lib/firebase/helpers/githubAccessHelper.d.ts +0 -0
- package/lib/firebase/helpers/githubTeamAccessHelper.d.ts +0 -0
- package/lib/firebase/helpers/index.d.ts +0 -0
- package/lib/firebase/index.d.ts +0 -0
- package/lib/firebase/index.js +1 -5
- package/lib/firebase/index.js.map +4 -4
- package/lib/firebase/oauth/disconnect.d.ts +0 -0
- package/lib/firebase/oauth/exchangeToken.d.ts +0 -0
- package/lib/firebase/oauth/getConnections.d.ts +0 -0
- package/lib/firebase/oauth/githubAccess.d.ts +2 -2
- package/lib/firebase/oauth/index.d.ts +0 -0
- package/lib/firebase/oauth/refreshToken.d.ts +0 -0
- package/lib/firebase/registerCrudFunctions.d.ts +9 -1
- package/lib/firebase/scheduled/checkExpiredSubscriptions.d.ts +0 -0
- package/lib/firebase/scheduled/index.d.ts +0 -0
- package/lib/shared/ai/classifyAIError.d.ts +0 -0
- package/lib/shared/ai/costTracker.d.ts +0 -0
- package/lib/shared/ai/createAIRoute.d.ts +0 -0
- package/lib/shared/ai/index.d.ts +0 -0
- package/lib/shared/ai/resolveModelTier.d.ts +0 -0
- package/lib/shared/billing/apiVersion.d.ts +22 -0
- package/lib/shared/billing/checkoutPrice.d.ts +27 -0
- package/lib/shared/billing/checkoutValidation.d.ts +89 -0
- package/lib/shared/billing/createCheckout.d.ts +73 -24
- package/lib/shared/billing/firestoreIdempotency.d.ts +13 -0
- package/lib/shared/billing/helpers/index.d.ts +0 -1
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +4 -4
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -29
- package/lib/shared/billing/idempotency.d.ts +21 -10
- package/lib/shared/billing/idempotencyContract.d.ts +121 -0
- package/lib/shared/billing/index.d.ts +2 -0
- package/lib/shared/billing/orderWebhook.d.ts +75 -0
- package/lib/shared/billing/stripeClient.d.ts +45 -0
- package/lib/shared/billing/supabaseIdempotency.d.ts +32 -0
- package/lib/shared/billing/tierWebhookEvents.d.ts +54 -0
- package/lib/shared/billing/webhookHandler.d.ts +29 -20
- package/lib/shared/email/createEmailRoute.d.ts +0 -0
- package/lib/shared/email/index.d.ts +0 -0
- package/lib/shared/email/provider.d.ts +0 -0
- package/lib/shared/email/resendProvider.d.ts +0 -0
- package/lib/shared/errorHandling.d.ts +0 -0
- package/lib/shared/firebase.d.ts +0 -0
- package/lib/shared/github.d.ts +0 -0
- package/lib/shared/index.d.ts +0 -0
- package/lib/shared/index.js +1 -6
- package/lib/shared/index.js.map +4 -4
- package/lib/shared/logger.d.ts +0 -0
- package/lib/shared/metadata.d.ts +0 -0
- package/lib/shared/oauth/exchangeToken.d.ts +0 -0
- package/lib/shared/oauth/grantAccess.d.ts +0 -0
- package/lib/shared/oauth/index.d.ts +0 -0
- package/lib/shared/schema.d.ts +0 -0
- package/lib/shared/utils/detectFirestore.d.ts +0 -0
- package/lib/shared/utils/external/date.d.ts +0 -0
- package/lib/shared/utils/external/index.d.ts +0 -0
- package/lib/shared/utils/external/references.d.ts +0 -0
- package/lib/shared/utils/external/subscription.d.ts +0 -0
- package/lib/shared/utils/firebaseHelpers.d.ts +0 -0
- package/lib/shared/utils/functionWrapper.d.ts +1 -1
- package/lib/shared/utils/index.d.ts +0 -0
- package/lib/shared/utils/internal/auth.d.ts +38 -1
- package/lib/shared/utils/internal/firebase.d.ts +0 -0
- package/lib/shared/utils/internal/idempotency.d.ts +0 -0
- package/lib/shared/utils/internal/index.d.ts +0 -0
- package/lib/shared/utils/internal/monitoring.d.ts +0 -0
- package/lib/shared/utils/internal/rateLimiter.d.ts +8 -0
- package/lib/shared/utils/internal/validation.d.ts +0 -8
- package/lib/shared/utils/schemaValidation.d.ts +1 -1
- package/lib/shared/utils/validation.d.ts +0 -0
- package/lib/shared/utils/vercelHelpers.d.ts +8 -0
- package/lib/shared/utils.d.ts +0 -56
- package/lib/shared/validation.d.ts +0 -0
- package/lib/supabase/ai/createAIFunction.d.ts +0 -0
- package/lib/supabase/auth/deleteAccount.d.ts +0 -0
- package/lib/supabase/auth/getCustomClaims.d.ts +0 -0
- package/lib/supabase/auth/getUserAuthStatus.d.ts +0 -0
- package/lib/supabase/auth/removeCustomClaims.d.ts +0 -0
- package/lib/supabase/auth/setCustomClaims.d.ts +0 -0
- package/lib/supabase/baseFunction.d.ts +1 -1
- package/lib/supabase/billing/cancelSubscription.d.ts +0 -0
- package/lib/supabase/billing/changePlan.d.ts +0 -0
- package/lib/supabase/billing/createCheckoutSession.d.ts +0 -0
- package/lib/supabase/billing/createCustomerPortal.d.ts +0 -0
- package/lib/supabase/billing/refreshSubscriptionStatus.d.ts +0 -0
- package/lib/supabase/billing/stripeWebhook.d.ts +34 -0
- package/lib/supabase/crud/aggregate.d.ts +0 -0
- package/lib/supabase/crud/bulk.d.ts +1 -1
- package/lib/supabase/crud/create.d.ts +0 -0
- package/lib/supabase/crud/delete.d.ts +0 -0
- package/lib/supabase/crud/entityStore.d.ts +71 -0
- package/lib/supabase/crud/get.d.ts +0 -0
- package/lib/supabase/crud/index.d.ts +2 -0
- package/lib/supabase/crud/list.d.ts +0 -8
- package/lib/supabase/crud/update.d.ts +0 -0
- package/lib/supabase/edgeFunction.d.ts +0 -0
- package/lib/supabase/email/createEmailFunction.d.ts +0 -0
- package/lib/supabase/helpers/authProvider.d.ts +5 -5
- package/lib/supabase/index.d.ts +11 -2
- package/lib/supabase/index.js +1 -3
- package/lib/supabase/index.js.map +4 -4
- package/lib/supabase/oauth/disconnect.d.ts +0 -0
- package/lib/supabase/oauth/exchangeToken.d.ts +0 -0
- package/lib/supabase/oauth/getConnections.d.ts +0 -0
- package/lib/supabase/oauth/index.d.ts +0 -0
- package/lib/supabase/oauth/refreshToken.d.ts +0 -0
- package/lib/supabase/registerCrudFunctions.d.ts +0 -0
- package/lib/supabase/utils/idempotency.d.ts +0 -0
- package/lib/supabase/utils/monitoring.d.ts +0 -0
- package/lib/supabase/utils/rateLimiter.d.ts +1 -1
- package/lib/vercel/api/ai/chat.d.ts +0 -9
- package/lib/vercel/api/ai/index.d.ts +0 -0
- package/lib/vercel/api/auth/get-custom-claims.d.ts +8 -0
- package/lib/vercel/api/auth/get-user-auth-status.d.ts +8 -0
- package/lib/vercel/api/auth/index.d.ts +0 -0
- package/lib/vercel/api/auth/remove-custom-claims.d.ts +8 -0
- package/lib/vercel/api/auth/set-custom-claims.d.ts +8 -0
- package/lib/vercel/api/billing/backend.d.ts +39 -0
- package/lib/vercel/api/billing/cancel.d.ts +8 -0
- package/lib/vercel/api/billing/change-plan.d.ts +9 -1
- package/lib/vercel/api/billing/create-checkout-session.d.ts +25 -6
- package/lib/vercel/api/billing/customer-portal.d.ts +8 -0
- package/lib/vercel/api/billing/index.d.ts +4 -2
- package/lib/vercel/api/billing/refresh-subscription-status.d.ts +19 -3
- package/lib/vercel/api/billing/webhook-handler.d.ts +25 -4
- package/lib/vercel/api/config/constants.d.ts +0 -0
- package/lib/vercel/api/config/firebase-admin.d.ts +8 -0
- package/lib/vercel/api/config/index.d.ts +0 -0
- package/lib/vercel/api/crud/bulk.d.ts +17 -0
- package/lib/vercel/api/crud/create.d.ts +8 -0
- package/lib/vercel/api/crud/delete.d.ts +8 -0
- package/lib/vercel/api/crud/get.d.ts +8 -0
- package/lib/vercel/api/crud/index.d.ts +0 -0
- package/lib/vercel/api/crud/list.d.ts +8 -0
- package/lib/vercel/api/crud/update.d.ts +8 -0
- package/lib/vercel/api/index.d.ts +0 -0
- package/lib/vercel/api/index.js +1 -3
- package/lib/vercel/api/index.js.map +4 -4
- package/lib/vercel/api/oauth/check-github-access.d.ts +8 -0
- package/lib/vercel/api/oauth/exchange-token.d.ts +8 -0
- package/lib/vercel/api/oauth/grant-github-access.d.ts +8 -0
- package/lib/vercel/api/oauth/index.d.ts +0 -0
- package/lib/vercel/api/oauth/revoke-github-access.d.ts +1 -1
- package/lib/vercel/api/utils/cors.d.ts +0 -0
- package/lib/vercel/baseFunction.d.ts +4 -1
- package/lib/vercel/supabaseAdmin.d.ts +22 -0
- package/package.json +25 -26
- package/src/firebase/auth/getCustomClaims.ts +4 -5
- package/src/firebase/auth/getUserAuthStatus.ts +4 -5
- package/src/firebase/auth/removeCustomClaims.ts +4 -5
- package/src/firebase/auth/setCustomClaims.ts +4 -5
- package/src/firebase/baseFunction.ts +4 -5
- package/src/firebase/billing/cancelSubscription.ts +2 -3
- package/src/firebase/billing/changePlan.ts +3 -8
- package/src/firebase/billing/createCheckoutSession.ts +31 -61
- package/src/firebase/billing/createCustomerPortal.ts +5 -6
- package/src/firebase/billing/healthCheck.ts +1 -1
- package/src/firebase/billing/index.ts +8 -1
- package/src/firebase/billing/refreshSubscriptionStatus.ts +3 -4
- package/src/firebase/billing/webhookHandler.ts +21 -5
- package/src/firebase/crud/__tests__/bulk.test.ts +11 -1
- package/src/firebase/crud/aggregate.ts +1 -2
- package/src/firebase/crud/bulk.ts +5 -6
- package/src/firebase/crud/create.ts +5 -6
- package/src/firebase/crud/delete.ts +4 -5
- package/src/firebase/crud/get.ts +4 -5
- package/src/firebase/crud/list.ts +4 -5
- package/src/firebase/crud/update.ts +5 -6
- package/src/firebase/oauth/githubAccess.ts +2 -3
- package/src/firebase/registerCrudFunctions.ts +2 -2
- package/src/shared/__tests__/auth.test.ts +0 -3
- package/src/shared/__tests__/bulkCore.test.ts +3 -2
- package/src/shared/__tests__/errorHandling.test.ts +2 -2
- package/src/shared/__tests__/idempotency.test.ts +282 -55
- package/src/shared/__tests__/internalValidation.test.ts +3 -42
- package/src/shared/__tests__/logger.test.ts +31 -0
- package/src/shared/__tests__/rateLimiter.test.ts +2 -8
- package/src/shared/__tests__/schemaValidation.test.ts +1 -1
- package/src/shared/__tests__/utils.test.ts +3 -2
- package/src/shared/__tests__/validation-env.test.ts +0 -0
- package/src/shared/ai/createAIRoute.ts +53 -30
- package/src/shared/billing/__tests__/checkoutValidation.test.ts +219 -0
- package/src/shared/billing/__tests__/createCheckout.compat.test.ts +349 -0
- package/src/shared/billing/__tests__/createCheckout.test.ts +454 -411
- package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +92 -0
- package/src/shared/billing/__tests__/webhookCorrectness.test.ts +387 -0
- package/src/shared/billing/__tests__/webhookHandler.test.ts +370 -23
- package/src/shared/billing/apiVersion.ts +25 -0
- package/src/shared/billing/checkoutPrice.ts +125 -0
- package/src/shared/billing/checkoutValidation.ts +284 -0
- package/src/shared/billing/createCheckout.ts +332 -196
- package/src/shared/billing/firestoreIdempotency.ts +189 -0
- package/src/shared/billing/helpers/index.ts +0 -1
- package/src/shared/billing/helpers/subscriptionManagement.ts +8 -10
- package/src/shared/billing/helpers/updateUserSubscription.ts +3 -36
- package/src/shared/billing/idempotency.ts +104 -168
- package/src/shared/billing/idempotencyContract.ts +135 -0
- package/src/shared/billing/index.ts +2 -0
- package/src/shared/billing/orderWebhook.ts +269 -0
- package/src/shared/billing/stripeClient.ts +91 -0
- package/src/shared/billing/supabaseIdempotency.ts +228 -0
- package/src/shared/billing/tierWebhookEvents.ts +432 -0
- package/src/shared/billing/webhookHandler.ts +189 -386
- package/src/shared/logger.ts +4 -6
- package/src/shared/utils/external/subscription.ts +0 -0
- package/src/shared/utils/firebaseHelpers.ts +2 -3
- package/src/shared/utils/functionWrapper.ts +1 -2
- package/src/shared/utils/internal/auth.ts +55 -7
- package/src/shared/utils/internal/monitoring.ts +17 -9
- package/src/shared/utils/internal/rateLimiter.ts +14 -5
- package/src/shared/utils/internal/validation.ts +0 -18
- package/src/shared/utils/schemaValidation.ts +1 -2
- package/src/shared/utils/vercelHelpers.ts +3 -3
- package/src/shared/utils.ts +5 -99
- package/src/shared/validation.ts +1 -1
- package/src/supabase/__tests__/bulk.test.ts +3 -1
- package/src/supabase/__tests__/entityStore.test.ts +90 -0
- package/src/supabase/baseFunction.ts +1 -2
- package/src/supabase/billing/cancelSubscription.ts +1 -1
- package/src/supabase/billing/changePlan.ts +1 -1
- package/src/supabase/billing/createCheckoutSession.ts +11 -41
- package/src/supabase/billing/createCustomerPortal.ts +1 -1
- package/src/supabase/billing/refreshSubscriptionStatus.ts +2 -7
- package/src/supabase/billing/stripeWebhook.ts +79 -0
- package/src/supabase/crud/aggregate.ts +1 -1
- package/src/supabase/crud/bulk.ts +3 -7
- package/src/supabase/crud/create.ts +1 -1
- package/src/supabase/crud/entityStore.ts +240 -0
- package/src/supabase/crud/index.ts +8 -0
- package/src/supabase/crud/list.ts +2 -0
- package/src/supabase/crud/update.ts +1 -1
- package/src/supabase/helpers/authProvider.ts +6 -5
- package/src/supabase/index.ts +26 -0
- package/src/supabase/utils/rateLimiter.ts +2 -2
- package/src/vercel/__tests__/bulk.test.ts +24 -21
- package/src/vercel/__tests__/firebaseOptional.test.ts +64 -0
- package/src/vercel/api/ai/chat.ts +2 -1
- package/src/vercel/api/auth/get-custom-claims.ts +2 -3
- package/src/vercel/api/auth/get-user-auth-status.ts +2 -3
- package/src/vercel/api/auth/remove-custom-claims.ts +2 -3
- package/src/vercel/api/auth/set-custom-claims.ts +3 -3
- package/src/vercel/api/billing/backend.ts +72 -0
- package/src/vercel/api/billing/cancel.ts +2 -4
- package/src/vercel/api/billing/change-plan.ts +4 -5
- package/src/vercel/api/billing/create-checkout-session.ts +43 -73
- package/src/vercel/api/billing/customer-portal.ts +3 -5
- package/src/vercel/api/billing/index.ts +4 -2
- package/src/vercel/api/billing/refresh-subscription-status.ts +22 -7
- package/src/vercel/api/billing/webhook-handler.ts +32 -26
- package/src/vercel/api/config/firebase-admin.ts +2 -2
- package/src/vercel/api/crud/bulk.ts +6 -9
- package/src/vercel/api/crud/create.ts +6 -5
- package/src/vercel/api/crud/delete.ts +4 -3
- package/src/vercel/api/crud/get.ts +6 -5
- package/src/vercel/api/crud/list.ts +6 -5
- package/src/vercel/api/crud/update.ts +6 -5
- package/src/vercel/api/oauth/check-github-access.ts +5 -5
- package/src/vercel/api/oauth/exchange-token.ts +3 -3
- package/src/vercel/api/oauth/grant-github-access.ts +5 -5
- package/src/vercel/api/oauth/revoke-github-access.ts +3 -4
- package/src/vercel/baseFunction.ts +23 -8
- package/src/vercel/supabaseAdmin.ts +45 -0
- package/lib/shared/ai/createAIHandler.d.ts +0 -39
- package/lib/shared/ai/providers/anthropic.d.ts +0 -12
- package/lib/shared/ai/providers/google.d.ts +0 -10
- package/lib/shared/ai/providers/index.d.ts +0 -23
- package/lib/shared/ai/providers/openai.d.ts +0 -10
- package/lib/shared/ai/utils/parseSSE.d.ts +0 -22
|
@@ -1,17 +1,20 @@
|
|
|
1
1
|
// packages/functions/src/shared/ai/createAIRoute.ts
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* @fileoverview AI Route Handler (Vercel AI SDK)
|
|
4
|
+
* @fileoverview AI Route Handler (Vercel AI SDK 7)
|
|
5
5
|
* @description Platform-agnostic handler for AI chat requests using Vercel AI SDK.
|
|
6
6
|
* Handles auth (via platform wrapper), rate limiting (Upstash), streaming, and cost tracking.
|
|
7
|
+
* Streaming responses use the UI message stream protocol read by `@ai-sdk/react`
|
|
8
|
+
* `useChat`; token usage travels as message metadata (`metadata.usage`, AIUsage).
|
|
7
9
|
*
|
|
8
|
-
* @version 0.
|
|
10
|
+
* @version 0.2.0
|
|
9
11
|
* @since 0.1.0
|
|
10
12
|
* @author AMBROISE PARK Consulting
|
|
11
13
|
*/
|
|
12
14
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
+
// `ai` is loaded on first request (handleAIRequest): importing this module must not
|
|
16
|
+
// require the AI SDK, so server entries that re-export it run without it installed.
|
|
17
|
+
import type { JSONSchema7, LanguageModel, LanguageModelUsage, Tool } from 'ai';
|
|
15
18
|
|
|
16
19
|
import type {
|
|
17
20
|
AIChatRequest,
|
|
@@ -62,8 +65,8 @@ async function resolveModel(
|
|
|
62
65
|
return (apiKey: string) => createOpenAI({ apiKey })(model);
|
|
63
66
|
},
|
|
64
67
|
google: async () => {
|
|
65
|
-
const {
|
|
66
|
-
return (apiKey: string) =>
|
|
68
|
+
const { createGoogle } = await import('@ai-sdk/google');
|
|
69
|
+
return (apiKey: string) => createGoogle({ apiKey })(model);
|
|
67
70
|
},
|
|
68
71
|
};
|
|
69
72
|
|
|
@@ -156,22 +159,34 @@ async function getRateLimiter() {
|
|
|
156
159
|
* Merges request-level tools with config-level tools (request takes precedence).
|
|
157
160
|
*/
|
|
158
161
|
function resolveTools(
|
|
162
|
+
sdk: Pick<typeof import('ai'), 'tool' | 'jsonSchema'>,
|
|
159
163
|
requestTools?: Record<string, AIToolDefinition>,
|
|
160
164
|
configTools?: Record<string, AIToolDefinition>
|
|
161
|
-
): Record<string,
|
|
165
|
+
): Record<string, Tool> | undefined {
|
|
162
166
|
const merged = { ...configTools, ...requestTools };
|
|
163
167
|
if (Object.keys(merged).length === 0) return undefined;
|
|
164
168
|
|
|
165
|
-
const sdkTools: Record<string,
|
|
169
|
+
const sdkTools: Record<string, Tool> = {};
|
|
166
170
|
for (const [name, def] of Object.entries(merged)) {
|
|
167
|
-
sdkTools[name] = tool({
|
|
171
|
+
sdkTools[name] = sdk.tool({
|
|
168
172
|
description: def.description,
|
|
169
|
-
|
|
173
|
+
inputSchema: sdk.jsonSchema(def.parameters as JSONSchema7),
|
|
170
174
|
});
|
|
171
175
|
}
|
|
172
176
|
return sdkTools;
|
|
173
177
|
}
|
|
174
178
|
|
|
179
|
+
/** AI SDK usage (input/output tokens) → framework usage (prompt/completion tokens). */
|
|
180
|
+
function toAIUsage(usage: LanguageModelUsage): AIUsage {
|
|
181
|
+
const promptTokens = usage.inputTokens ?? 0;
|
|
182
|
+
const completionTokens = usage.outputTokens ?? 0;
|
|
183
|
+
return {
|
|
184
|
+
promptTokens,
|
|
185
|
+
completionTokens,
|
|
186
|
+
totalTokens: usage.totalTokens ?? promptTokens + completionTokens,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
175
190
|
// =============================================================================
|
|
176
191
|
// Core Handler
|
|
177
192
|
// =============================================================================
|
|
@@ -265,7 +280,14 @@ export async function handleAIRequest(
|
|
|
265
280
|
const requestId = options.requestId || crypto.randomUUID();
|
|
266
281
|
|
|
267
282
|
// Resolve tools (request-level overrides config-level)
|
|
268
|
-
const
|
|
283
|
+
const sdk = await import('ai');
|
|
284
|
+
const {
|
|
285
|
+
streamText,
|
|
286
|
+
generateText,
|
|
287
|
+
toUIMessageStream,
|
|
288
|
+
createUIMessageStreamResponse,
|
|
289
|
+
} = sdk;
|
|
290
|
+
const tools = resolveTools(sdk, request.tools, config.tools);
|
|
269
291
|
|
|
270
292
|
// Cost tracking helper
|
|
271
293
|
const recordCost = async (usage: AIUsage) => {
|
|
@@ -298,47 +320,48 @@ export async function handleAIRequest(
|
|
|
298
320
|
const result = streamText({
|
|
299
321
|
model: languageModel,
|
|
300
322
|
messages,
|
|
301
|
-
|
|
302
|
-
maxTokens,
|
|
323
|
+
instructions: systemPrompt,
|
|
324
|
+
maxOutputTokens: maxTokens,
|
|
303
325
|
temperature,
|
|
304
326
|
tools,
|
|
305
|
-
|
|
306
|
-
await recordCost(
|
|
307
|
-
promptTokens: usage.promptTokens,
|
|
308
|
-
completionTokens: usage.completionTokens,
|
|
309
|
-
totalTokens: usage.promptTokens + usage.completionTokens,
|
|
310
|
-
});
|
|
327
|
+
onEnd: async ({ usage }) => {
|
|
328
|
+
await recordCost(toAIUsage(usage));
|
|
311
329
|
},
|
|
312
330
|
});
|
|
313
331
|
|
|
314
|
-
return
|
|
332
|
+
return createUIMessageStreamResponse({
|
|
333
|
+
stream: toUIMessageStream({
|
|
334
|
+
stream: result.stream,
|
|
335
|
+
// Usage for the client's cost display (useAIChat reads metadata.usage).
|
|
336
|
+
messageMetadata: ({ part }) =>
|
|
337
|
+
part.type === 'finish'
|
|
338
|
+
? { usage: toAIUsage(part.totalUsage) }
|
|
339
|
+
: undefined,
|
|
340
|
+
}),
|
|
341
|
+
});
|
|
315
342
|
}
|
|
316
343
|
|
|
317
344
|
// Non-streaming
|
|
318
345
|
const result = await generateText({
|
|
319
346
|
model: languageModel,
|
|
320
347
|
messages,
|
|
321
|
-
|
|
322
|
-
maxTokens,
|
|
348
|
+
instructions: systemPrompt,
|
|
349
|
+
maxOutputTokens: maxTokens,
|
|
323
350
|
temperature,
|
|
324
351
|
tools,
|
|
325
352
|
});
|
|
326
353
|
|
|
327
|
-
const usage
|
|
328
|
-
promptTokens: result.usage.promptTokens,
|
|
329
|
-
completionTokens: result.usage.completionTokens,
|
|
330
|
-
totalTokens: result.usage.promptTokens + result.usage.completionTokens,
|
|
331
|
-
};
|
|
354
|
+
const usage = toAIUsage(result.usage);
|
|
332
355
|
|
|
333
356
|
await recordCost(usage);
|
|
334
357
|
|
|
335
358
|
// Extract tool calls from result
|
|
336
359
|
const toolCalls =
|
|
337
|
-
result.toolCalls
|
|
360
|
+
result.toolCalls.map((tc) => ({
|
|
338
361
|
id: tc.toolCallId,
|
|
339
362
|
name: tc.toolName,
|
|
340
|
-
args: tc.
|
|
341
|
-
}))
|
|
363
|
+
args: tc.input as Record<string, unknown>,
|
|
364
|
+
}));
|
|
342
365
|
|
|
343
366
|
return new Response(
|
|
344
367
|
JSON.stringify({
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
// packages/functions/src/shared/billing/__tests__/checkoutValidation.test.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Tests for checkout validation (Stripe limits, inclusive tax rates)
|
|
5
|
+
*
|
|
6
|
+
* @version 0.2.0
|
|
7
|
+
* @since 0.2.0
|
|
8
|
+
* @author AMBROISE PARK Consulting
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import * as v from 'valibot';
|
|
12
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
13
|
+
|
|
14
|
+
import { StripeOrderShippingSchema } from '@donotdev/core/server';
|
|
15
|
+
import type {
|
|
16
|
+
CreateCheckoutSessionRequest,
|
|
17
|
+
StripeBackConfig,
|
|
18
|
+
StripeOrderBackItem,
|
|
19
|
+
} from '@donotdev/core/server';
|
|
20
|
+
|
|
21
|
+
import { assertCheckoutSessionMetadata } from '../checkoutValidation.js';
|
|
22
|
+
import { createCheckoutAlgorithm } from '../createCheckout.js';
|
|
23
|
+
import type { StripeCheckoutProvider } from '@donotdev/core/server';
|
|
24
|
+
|
|
25
|
+
import type { AuthCheckoutProvider, StripeSessionProvider } from '../createCheckout.js';
|
|
26
|
+
|
|
27
|
+
const USER_ID = 'user_001';
|
|
28
|
+
const URLS = {
|
|
29
|
+
successUrl: 'https://app.example.com/billing/success',
|
|
30
|
+
cancelUrl: 'https://app.example.com/billing/cancel',
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const auth: AuthCheckoutProvider = {
|
|
34
|
+
getUser: vi.fn(async () => ({ customClaims: {} })),
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
function makeSessionProvider(inclusiveIds: string[] = []) {
|
|
38
|
+
const createStripeSession = vi.fn<StripeSessionProvider['createStripeSession']>(
|
|
39
|
+
async () => ({ id: 'cs_1', url: 'https://checkout.stripe.com/c/cs_1' })
|
|
40
|
+
);
|
|
41
|
+
const retrieveTaxRate = vi.fn<StripeSessionProvider['retrieveTaxRate']>(
|
|
42
|
+
async (id) => ({ id, inclusive: inclusiveIds.includes(id) })
|
|
43
|
+
);
|
|
44
|
+
return { createStripeSession, retrieveTaxRate };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function makeConfig(order: Partial<StripeOrderBackItem> = {}): StripeBackConfig {
|
|
48
|
+
return {
|
|
49
|
+
pro: {
|
|
50
|
+
type: 'StripeSubscription',
|
|
51
|
+
name: 'Pro',
|
|
52
|
+
price: 1999,
|
|
53
|
+
currency: 'eur',
|
|
54
|
+
priceId: 'price_pro',
|
|
55
|
+
tier: 'pro',
|
|
56
|
+
duration: '1month',
|
|
57
|
+
},
|
|
58
|
+
shop: {
|
|
59
|
+
type: 'StripeOrder',
|
|
60
|
+
name: 'Shop',
|
|
61
|
+
currency: 'eur',
|
|
62
|
+
tax: { mode: 'manual', taxRateIds: ['txr_val_20'] },
|
|
63
|
+
taxIdCollection: 'optional',
|
|
64
|
+
billingAddressCollection: 'required',
|
|
65
|
+
customerCreation: 'always',
|
|
66
|
+
invoiceCreation: true,
|
|
67
|
+
resolveLineItems: vi.fn(async () => ({
|
|
68
|
+
orderId: 'ord_1',
|
|
69
|
+
lineItems: [{ productId: 'p', name: 'P', unitAmount: 1000, quantity: 1 }],
|
|
70
|
+
})),
|
|
71
|
+
onOrderPaid: vi.fn(async () => {}),
|
|
72
|
+
...order,
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const PRO: CreateCheckoutSessionRequest = {
|
|
78
|
+
billingConfigKey: 'pro',
|
|
79
|
+
lineItems: [{ productId: 'pro', quantity: 1 }],
|
|
80
|
+
...URLS,
|
|
81
|
+
};
|
|
82
|
+
const SHOP: CreateCheckoutSessionRequest = {
|
|
83
|
+
billingConfigKey: 'shop',
|
|
84
|
+
lineItems: [{ productId: 'p', quantity: 1 }],
|
|
85
|
+
...URLS,
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
describe('Stripe metadata limits', () => {
|
|
89
|
+
it.each([
|
|
90
|
+
['51 keys incl. server keys', Object.fromEntries(Array.from({ length: 49 }, (_, i) => [`k${i}`, 'v'])), /at most 50/],
|
|
91
|
+
['41-char key', { ['k'.repeat(41)]: 'v' }, /too long \(max 40/],
|
|
92
|
+
['square brackets in key', { 'a[b]': 'v' }, /square brackets/],
|
|
93
|
+
['501-char value', { note: 'x'.repeat(501) }, /too long \(max 500/],
|
|
94
|
+
])('rejects %s before calling Stripe (single-price and 0.1.x provider)', async (_l, metadata, error) => {
|
|
95
|
+
const stripe = makeSessionProvider();
|
|
96
|
+
await expect(
|
|
97
|
+
createCheckoutAlgorithm({ ...PRO, metadata }, USER_ID, stripe, auth, makeConfig())
|
|
98
|
+
).rejects.toThrow(error);
|
|
99
|
+
expect(stripe.createStripeSession).not.toHaveBeenCalled();
|
|
100
|
+
|
|
101
|
+
const legacy = { createCheckoutSession: vi.fn<StripeCheckoutProvider['createCheckoutSession']>() };
|
|
102
|
+
await expect(
|
|
103
|
+
createCheckoutAlgorithm({ ...PRO, metadata }, USER_ID, legacy, auth, makeConfig())
|
|
104
|
+
).rejects.toThrow(error);
|
|
105
|
+
expect(legacy.createCheckoutSession).not.toHaveBeenCalled();
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('accepts metadata at the limits (48 client keys + userId + billingConfigKey, 40/500 chars)', async () => {
|
|
109
|
+
const metadata = Object.fromEntries(
|
|
110
|
+
Array.from({ length: 48 }, (_, i) => [`${i}`.padEnd(40, 'k'), 'v'.repeat(500)])
|
|
111
|
+
);
|
|
112
|
+
const stripe = makeSessionProvider();
|
|
113
|
+
await createCheckoutAlgorithm({ ...PRO, metadata }, USER_ID, stripe, auth, makeConfig());
|
|
114
|
+
expect(stripe.createStripeSession).toHaveBeenCalledTimes(1);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('StripeOrder: counts orderId and fails before resolveLineItems creates an order', async () => {
|
|
118
|
+
const config = makeConfig();
|
|
119
|
+
const metadata = Object.fromEntries(Array.from({ length: 48 }, (_, i) => [`k${i}`, 'v']));
|
|
120
|
+
await expect(
|
|
121
|
+
createCheckoutAlgorithm({ ...SHOP, metadata }, USER_ID, makeSessionProvider(), auth, config)
|
|
122
|
+
).rejects.toThrow(/at most 50/);
|
|
123
|
+
expect((config.shop as StripeOrderBackItem).resolveLineItems).not.toHaveBeenCalled();
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it('checks every metadata map of the session params', () => {
|
|
127
|
+
expect(() =>
|
|
128
|
+
assertCheckoutSessionMetadata({
|
|
129
|
+
mode: 'payment',
|
|
130
|
+
metadata: { ok: 'v' },
|
|
131
|
+
payment_intent_data: { metadata: { ['x'.repeat(41)]: 'v' } },
|
|
132
|
+
})
|
|
133
|
+
).toThrow(/payment_intent_data\.metadata/);
|
|
134
|
+
expect(() =>
|
|
135
|
+
assertCheckoutSessionMetadata({
|
|
136
|
+
mode: 'payment',
|
|
137
|
+
line_items: [
|
|
138
|
+
{
|
|
139
|
+
price_data: {
|
|
140
|
+
currency: 'eur',
|
|
141
|
+
unit_amount: 1,
|
|
142
|
+
product_data: { name: 'n', metadata: { productId: 'y'.repeat(501) } },
|
|
143
|
+
},
|
|
144
|
+
quantity: 1,
|
|
145
|
+
},
|
|
146
|
+
],
|
|
147
|
+
})
|
|
148
|
+
).toThrow(/line_items\[0\]\.price_data\.product_data\.metadata/);
|
|
149
|
+
});
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
describe('StripeOrder manual tax: inclusive Tax Rates', () => {
|
|
153
|
+
it('rejects an inclusive Tax Rate before resolving lines', async () => {
|
|
154
|
+
const config = makeConfig({ tax: { mode: 'manual', taxRateIds: ['txr_val_incl'] } });
|
|
155
|
+
const stripe = makeSessionProvider(['txr_val_incl']);
|
|
156
|
+
await expect(
|
|
157
|
+
createCheckoutAlgorithm(SHOP, USER_ID, stripe, auth, config)
|
|
158
|
+
).rejects.toThrow(/Tax Rate 'txr_val_incl' is inclusive/);
|
|
159
|
+
expect((config.shop as StripeOrderBackItem).resolveLineItems).not.toHaveBeenCalled();
|
|
160
|
+
expect(stripe.createStripeSession).not.toHaveBeenCalled();
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it('retrieves each Tax Rate once per instance', async () => {
|
|
164
|
+
const config = makeConfig({ tax: { mode: 'manual', taxRateIds: ['txr_val_once'] } });
|
|
165
|
+
const stripe = makeSessionProvider();
|
|
166
|
+
await createCheckoutAlgorithm(SHOP, USER_ID, stripe, auth, config);
|
|
167
|
+
await createCheckoutAlgorithm(SHOP, USER_ID, stripe, auth, config);
|
|
168
|
+
expect(stripe.retrieveTaxRate).toHaveBeenCalledTimes(1);
|
|
169
|
+
expect(stripe.createStripeSession).toHaveBeenCalledTimes(2);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it('does not cache a failed lookup', async () => {
|
|
173
|
+
const config = makeConfig({ tax: { mode: 'manual', taxRateIds: ['txr_val_flaky'] } });
|
|
174
|
+
const stripe = makeSessionProvider();
|
|
175
|
+
stripe.retrieveTaxRate.mockRejectedValueOnce(new Error('stripe down'));
|
|
176
|
+
await expect(createCheckoutAlgorithm(SHOP, USER_ID, stripe, auth, config)).rejects.toThrow(
|
|
177
|
+
'stripe down'
|
|
178
|
+
);
|
|
179
|
+
await createCheckoutAlgorithm(SHOP, USER_ID, stripe, auth, config);
|
|
180
|
+
expect(stripe.retrieveTaxRate).toHaveBeenCalledTimes(2);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it('automatic tax does not retrieve Tax Rates', async () => {
|
|
184
|
+
const stripe = makeSessionProvider();
|
|
185
|
+
await createCheckoutAlgorithm(SHOP, USER_ID, stripe, auth, makeConfig({ tax: { mode: 'automatic' } }));
|
|
186
|
+
expect(stripe.retrieveTaxRate).not.toHaveBeenCalled();
|
|
187
|
+
});
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
describe('StripeOrder Stripe limits', () => {
|
|
191
|
+
it('orderId (client_reference_id) is capped at 200 characters', async () => {
|
|
192
|
+
const config = makeConfig({
|
|
193
|
+
resolveLineItems: vi.fn(async () => ({
|
|
194
|
+
orderId: 'o'.repeat(201),
|
|
195
|
+
lineItems: [{ productId: 'p', name: 'P', unitAmount: 1000, quantity: 1 }],
|
|
196
|
+
})),
|
|
197
|
+
});
|
|
198
|
+
await expect(
|
|
199
|
+
createCheckoutAlgorithm(SHOP, USER_ID, makeSessionProvider(), auth, config)
|
|
200
|
+
).rejects.toThrow(/client_reference_id \(max 200/);
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
it('allowedCountries: uppercase ISO 3166-1 alpha-2 only', () => {
|
|
204
|
+
expect(v.safeParse(StripeOrderShippingSchema, { allowedCountries: ['FR', 'BE'] }).success).toBe(true);
|
|
205
|
+
for (const code of ['fr', 'F1', 'FRA', 'Fr']) {
|
|
206
|
+
expect(v.safeParse(StripeOrderShippingSchema, { allowedCountries: [code] }).success).toBe(false);
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
it('shippingRateIds: at most 5', () => {
|
|
211
|
+
const ids = (n: number) => Array.from({ length: n }, (_, i) => `shr_${i}`);
|
|
212
|
+
expect(
|
|
213
|
+
v.safeParse(StripeOrderShippingSchema, { allowedCountries: ['FR'], shippingRateIds: ids(5) }).success
|
|
214
|
+
).toBe(true);
|
|
215
|
+
expect(
|
|
216
|
+
v.safeParse(StripeOrderShippingSchema, { allowedCountries: ['FR'], shippingRateIds: ids(6) }).success
|
|
217
|
+
).toBe(false);
|
|
218
|
+
});
|
|
219
|
+
});
|