@donotdev/functions 0.1.1 → 0.1.44
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/LICENSE.md +21 -242
- package/README.md +4 -4
- package/guidelines/FUNCTIONS.md +0 -0
- package/guidelines/VERCEL.md +27 -1
- package/lib/firebase/auth/getCustomClaims.d.ts +0 -0
- package/lib/firebase/auth/getUserAuthStatus.d.ts +0 -0
- package/lib/firebase/auth/index.d.ts +0 -0
- package/lib/firebase/auth/removeCustomClaims.d.ts +0 -0
- package/lib/firebase/auth/setCustomClaims.d.ts +0 -0
- package/lib/firebase/baseFunction.d.ts +0 -0
- 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 +0 -0
- package/lib/firebase/billing/createCustomerPortal.d.ts +0 -0
- package/lib/firebase/billing/healthCheck.d.ts +0 -0
- package/lib/firebase/billing/index.d.ts +0 -0
- package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +0 -0
- package/lib/firebase/billing/webhookHandler.d.ts +0 -0
- 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 -0
- package/lib/firebase/crud/bulk.d.ts +107 -0
- package/lib/firebase/crud/create.d.ts +1 -1
- package/lib/firebase/crud/delete.d.ts +0 -0
- package/lib/firebase/crud/get.d.ts +0 -0
- package/lib/firebase/crud/index.d.ts +1 -0
- package/lib/firebase/crud/list.d.ts +0 -0
- package/lib/firebase/crud/update.d.ts +0 -0
- 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 +3 -3
- 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 +0 -0
- package/lib/firebase/oauth/index.d.ts +0 -0
- package/lib/firebase/oauth/refreshToken.d.ts +0 -0
- package/lib/firebase/registerCrudFunctions.d.ts +0 -0
- 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/createAIHandler.d.ts +39 -0
- package/lib/shared/ai/createAIRoute.d.ts +0 -0
- package/lib/shared/ai/index.d.ts +0 -0
- package/lib/shared/ai/providers/anthropic.d.ts +12 -0
- package/lib/shared/ai/providers/google.d.ts +10 -0
- package/lib/shared/ai/providers/index.d.ts +23 -0
- package/lib/shared/ai/providers/openai.d.ts +10 -0
- package/lib/shared/ai/resolveModelTier.d.ts +0 -0
- package/lib/shared/ai/utils/parseSSE.d.ts +22 -0
- package/lib/shared/billing/createCheckout.d.ts +0 -0
- package/lib/shared/billing/helpers/index.d.ts +0 -0
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +0 -0
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +0 -0
- package/lib/shared/billing/idempotency.d.ts +0 -0
- package/lib/shared/billing/index.d.ts +0 -0
- package/lib/shared/billing/webhookHandler.d.ts +0 -0
- package/lib/shared/crud/bulkCore.d.ts +211 -0
- package/lib/shared/crud/index.d.ts +13 -0
- 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 +1 -0
- package/lib/shared/index.js +4 -4
- package/lib/shared/index.js.map +4 -4
- package/lib/shared/logger.d.ts +0 -0
- package/lib/shared/metadata.d.ts +6 -6
- 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 +0 -0
- package/lib/shared/utils/index.d.ts +0 -0
- package/lib/shared/utils/internal/auth.d.ts +0 -0
- 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 +0 -0
- package/lib/shared/utils/internal/validation.d.ts +0 -0
- package/lib/shared/utils/schemaValidation.d.ts +0 -0
- package/lib/shared/utils/validation.d.ts +0 -0
- package/lib/shared/utils/vercelHelpers.d.ts +0 -0
- package/lib/shared/utils.d.ts +0 -0
- 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 +0 -0
- 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/crud/aggregate.d.ts +0 -0
- package/lib/supabase/crud/bulk.d.ts +63 -0
- package/lib/supabase/crud/create.d.ts +1 -1
- package/lib/supabase/crud/delete.d.ts +0 -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 -0
- 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 +0 -0
- package/lib/supabase/index.d.ts +3 -3
- package/lib/supabase/index.js +3 -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 +0 -0
- package/lib/vercel/api/ai/chat.d.ts +0 -0
- package/lib/vercel/api/ai/index.d.ts +0 -0
- package/lib/vercel/api/auth/get-custom-claims.d.ts +0 -0
- package/lib/vercel/api/auth/get-user-auth-status.d.ts +0 -0
- package/lib/vercel/api/auth/index.d.ts +0 -0
- package/lib/vercel/api/auth/remove-custom-claims.d.ts +0 -0
- package/lib/vercel/api/auth/set-custom-claims.d.ts +0 -0
- package/lib/vercel/api/billing/cancel.d.ts +0 -0
- package/lib/vercel/api/billing/change-plan.d.ts +0 -0
- package/lib/vercel/api/billing/create-checkout-session.d.ts +0 -0
- package/lib/vercel/api/billing/customer-portal.d.ts +0 -0
- package/lib/vercel/api/billing/index.d.ts +0 -0
- package/lib/vercel/api/billing/refresh-subscription-status.d.ts +0 -0
- package/lib/vercel/api/billing/webhook-handler.d.ts +0 -0
- package/lib/vercel/api/config/constants.d.ts +0 -0
- package/lib/vercel/api/config/firebase-admin.d.ts +0 -0
- package/lib/vercel/api/config/index.d.ts +0 -0
- package/lib/vercel/api/crud/bulk.d.ts +31 -0
- package/lib/vercel/api/crud/create.d.ts +0 -0
- package/lib/vercel/api/crud/delete.d.ts +0 -0
- package/lib/vercel/api/crud/get.d.ts +0 -0
- package/lib/vercel/api/crud/index.d.ts +1 -0
- package/lib/vercel/api/crud/list.d.ts +0 -0
- package/lib/vercel/api/crud/update.d.ts +0 -0
- package/lib/vercel/api/index.d.ts +0 -0
- package/lib/vercel/api/index.js +3 -3
- package/lib/vercel/api/index.js.map +4 -4
- package/lib/vercel/api/oauth/check-github-access.d.ts +0 -0
- package/lib/vercel/api/oauth/exchange-token.d.ts +0 -0
- package/lib/vercel/api/oauth/grant-github-access.d.ts +0 -0
- package/lib/vercel/api/oauth/index.d.ts +0 -0
- package/lib/vercel/api/oauth/revoke-github-access.d.ts +0 -0
- package/lib/vercel/api/utils/cors.d.ts +0 -0
- package/lib/vercel/baseFunction.d.ts +0 -0
- package/package.json +6 -6
- package/src/firebase/auth/getCustomClaims.ts +0 -0
- package/src/firebase/auth/getUserAuthStatus.ts +0 -0
- package/src/firebase/auth/index.ts +0 -0
- package/src/firebase/auth/removeCustomClaims.ts +0 -0
- package/src/firebase/auth/setCustomClaims.ts +0 -0
- package/src/firebase/baseFunction.ts +0 -0
- package/src/firebase/billing/cancelSubscription.ts +0 -0
- package/src/firebase/billing/changePlan.ts +0 -0
- package/src/firebase/billing/createCheckoutSession.ts +5 -1
- package/src/firebase/billing/createCustomerPortal.ts +0 -0
- package/src/firebase/billing/healthCheck.ts +0 -0
- package/src/firebase/billing/index.d.ts +0 -0
- package/src/firebase/billing/index.ts +0 -0
- package/src/firebase/billing/refreshSubscriptionStatus.ts +0 -0
- package/src/firebase/billing/webhookHandler.ts +0 -0
- package/src/firebase/config/constants.ts +0 -0
- package/src/firebase/config/index.ts +0 -0
- package/src/firebase/config/secrets.ts +0 -0
- package/src/firebase/crud/__tests__/bulk.test.ts +322 -0
- package/src/firebase/crud/aggregate.ts +0 -0
- package/src/firebase/crud/bulk.ts +272 -0
- package/src/firebase/crud/create.ts +20 -33
- package/src/firebase/crud/delete.ts +0 -0
- package/src/firebase/crud/get.ts +0 -0
- package/src/firebase/crud/index.ts +1 -0
- package/src/firebase/crud/list.ts +0 -0
- package/src/firebase/crud/update.ts +0 -0
- package/src/firebase/helpers/githubAccessHelper.ts +0 -0
- package/src/firebase/helpers/githubTeamAccessHelper.ts +0 -0
- package/src/firebase/helpers/index.ts +0 -0
- package/src/firebase/index.d.ts +0 -0
- package/src/firebase/index.ts +0 -0
- package/src/firebase/oauth/disconnect.ts +0 -0
- package/src/firebase/oauth/exchangeToken.ts +0 -0
- package/src/firebase/oauth/getConnections.ts +0 -0
- package/src/firebase/oauth/githubAccess.ts +0 -0
- package/src/firebase/oauth/index.ts +0 -0
- package/src/firebase/oauth/refreshToken.ts +0 -0
- package/src/firebase/registerCrudFunctions.ts +13 -0
- package/src/firebase/scheduled/checkExpiredSubscriptions.ts +0 -0
- package/src/firebase/scheduled/index.ts +0 -0
- package/src/shared/__tests__/auth.test.ts +0 -0
- package/src/shared/__tests__/bulkCore.test.ts +487 -0
- package/src/shared/__tests__/errorHandling.test.ts +0 -0
- package/src/shared/__tests__/firebase.test.ts +9 -3
- package/src/shared/__tests__/idempotency.test.ts +0 -0
- package/src/shared/__tests__/internalValidation.test.ts +9 -3
- package/src/shared/__tests__/metadata.test.ts +10 -10
- package/src/shared/__tests__/rateLimiter.test.ts +0 -0
- package/src/shared/__tests__/schema.test.ts +0 -0
- package/src/shared/__tests__/schemaValidation.test.ts +0 -0
- package/src/shared/__tests__/subscription.test.ts +0 -0
- package/src/shared/__tests__/utils.test.ts +10 -4
- package/src/shared/__tests__/validation-env.test.ts +9 -3
- package/src/shared/__tests__/validation.test.ts +0 -0
- package/src/shared/ai/__tests__/costTracker.test.ts +25 -13
- package/src/shared/ai/classifyAIError.ts +26 -11
- package/src/shared/ai/costTracker.ts +0 -0
- package/src/shared/ai/createAIRoute.ts +11 -8
- package/src/shared/ai/index.ts +0 -0
- package/src/shared/ai/resolveModelTier.ts +5 -2
- package/src/shared/billing/__tests__/createCheckout.test.ts +0 -0
- package/src/shared/billing/__tests__/webhookHandler.test.ts +0 -0
- package/src/shared/billing/createCheckout.ts +24 -9
- package/src/shared/billing/helpers/index.ts +0 -0
- package/src/shared/billing/helpers/subscriptionManagement.ts +0 -0
- package/src/shared/billing/helpers/updateUserSubscription.ts +0 -0
- package/src/shared/billing/idempotency.ts +0 -0
- package/src/shared/billing/index.ts +0 -0
- package/src/shared/billing/webhookHandler.ts +0 -0
- package/src/shared/crud/bulkCore.ts +483 -0
- package/src/shared/crud/index.ts +23 -0
- package/src/shared/email/createEmailRoute.ts +0 -0
- package/src/shared/email/index.ts +0 -0
- package/src/shared/email/provider.ts +0 -0
- package/src/shared/email/resendProvider.ts +1 -1
- package/src/shared/errorHandling.ts +0 -0
- package/src/shared/firebase.ts +0 -0
- package/src/shared/github.ts +0 -0
- package/src/shared/index.d.ts +9 -0
- package/src/shared/index.ts +1 -0
- package/src/shared/logger.ts +0 -0
- package/src/shared/metadata.ts +6 -6
- package/src/shared/oauth/__tests__/exchangeToken.test.ts +0 -0
- package/src/shared/oauth/__tests__/grantAccess.test.ts +0 -0
- package/src/shared/oauth/exchangeToken.ts +0 -0
- package/src/shared/oauth/grantAccess.ts +0 -0
- package/src/shared/oauth/index.ts +0 -0
- package/src/shared/schema.ts +0 -0
- package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -0
- package/src/shared/utils/detectFirestore.ts +0 -0
- package/src/shared/utils/external/date.ts +0 -0
- package/src/shared/utils/external/index.ts +0 -0
- package/src/shared/utils/external/references.ts +0 -0
- package/src/shared/utils/external/subscription.ts +0 -0
- package/src/shared/utils/firebaseHelpers.ts +0 -0
- package/src/shared/utils/functionWrapper.ts +0 -0
- package/src/shared/utils/index.ts +0 -0
- package/src/shared/utils/internal/auth.ts +0 -0
- package/src/shared/utils/internal/firebase.ts +0 -0
- package/src/shared/utils/internal/idempotency.ts +0 -0
- package/src/shared/utils/internal/index.ts +0 -0
- package/src/shared/utils/internal/monitoring.ts +0 -0
- package/src/shared/utils/internal/rateLimiter.ts +0 -0
- package/src/shared/utils/internal/validation.ts +0 -0
- package/src/shared/utils/schemaValidation.ts +0 -0
- package/src/shared/utils/validation.ts +0 -0
- package/src/shared/utils/vercelHelpers.ts +0 -0
- package/src/shared/utils.ts +0 -0
- package/src/shared/validation.ts +0 -0
- package/src/supabase/__tests__/bulk.test.ts +330 -0
- package/src/supabase/ai/createAIFunction.ts +17 -16
- package/src/supabase/auth/deleteAccount.ts +0 -0
- package/src/supabase/auth/getCustomClaims.ts +0 -0
- package/src/supabase/auth/getUserAuthStatus.ts +0 -0
- package/src/supabase/auth/removeCustomClaims.ts +0 -0
- package/src/supabase/auth/setCustomClaims.ts +1 -3
- package/src/supabase/baseFunction.ts +0 -0
- package/src/supabase/billing/cancelSubscription.ts +0 -0
- package/src/supabase/billing/changePlan.ts +1 -1
- package/src/supabase/billing/createCheckoutSession.ts +0 -0
- package/src/supabase/billing/createCustomerPortal.ts +0 -0
- package/src/supabase/billing/refreshSubscriptionStatus.ts +0 -0
- package/src/supabase/crud/aggregate.ts +0 -0
- package/src/supabase/crud/bulk.ts +244 -0
- package/src/supabase/crud/create.ts +15 -14
- package/src/supabase/crud/delete.ts +0 -0
- package/src/supabase/crud/get.ts +0 -0
- package/src/supabase/crud/index.ts +2 -0
- package/src/supabase/crud/list.ts +0 -0
- package/src/supabase/crud/update.ts +0 -0
- package/src/supabase/edgeFunction.ts +4 -3
- package/src/supabase/email/createEmailFunction.ts +9 -12
- package/src/supabase/helpers/authProvider.ts +0 -0
- package/src/supabase/index.ts +12 -3
- package/src/supabase/oauth/disconnect.ts +1 -2
- package/src/supabase/oauth/exchangeToken.ts +1 -3
- package/src/supabase/oauth/getConnections.ts +1 -4
- package/src/supabase/oauth/index.ts +0 -0
- package/src/supabase/oauth/refreshToken.ts +2 -7
- package/src/supabase/registerCrudFunctions.ts +38 -26
- package/src/supabase/utils/idempotency.ts +0 -0
- package/src/supabase/utils/monitoring.ts +0 -0
- package/src/supabase/utils/rateLimiter.ts +0 -0
- package/src/vercel/__tests__/bulk.test.ts +301 -0
- package/src/vercel/api/ai/chat.ts +0 -0
- package/src/vercel/api/ai/index.ts +2 -0
- package/src/vercel/api/auth/get-custom-claims.ts +0 -0
- package/src/vercel/api/auth/get-user-auth-status.ts +0 -0
- package/src/vercel/api/auth/index.ts +0 -0
- package/src/vercel/api/auth/remove-custom-claims.ts +0 -0
- package/src/vercel/api/auth/set-custom-claims.ts +0 -0
- package/src/vercel/api/billing/cancel.ts +0 -0
- package/src/vercel/api/billing/change-plan.ts +0 -0
- package/src/vercel/api/billing/create-checkout-session.ts +5 -1
- package/src/vercel/api/billing/customer-portal.ts +0 -0
- package/src/vercel/api/billing/index.ts +0 -0
- package/src/vercel/api/billing/refresh-subscription-status.ts +0 -0
- package/src/vercel/api/billing/webhook-handler.ts +0 -0
- package/src/vercel/api/config/constants.ts +0 -0
- package/src/vercel/api/config/firebase-admin.ts +0 -0
- package/src/vercel/api/config/index.ts +0 -0
- package/src/vercel/api/crud/bulk.ts +216 -0
- package/src/vercel/api/crud/create.ts +10 -9
- package/src/vercel/api/crud/delete.ts +0 -0
- package/src/vercel/api/crud/get.ts +0 -0
- package/src/vercel/api/crud/index.ts +1 -0
- package/src/vercel/api/crud/list.ts +0 -0
- package/src/vercel/api/crud/update.ts +0 -0
- package/src/vercel/api/index.d.ts +0 -0
- package/src/vercel/api/index.ts +0 -0
- package/src/vercel/api/oauth/check-github-access.ts +0 -0
- package/src/vercel/api/oauth/exchange-token.ts +4 -1
- package/src/vercel/api/oauth/grant-github-access.ts +0 -0
- package/src/vercel/api/oauth/index.ts +0 -0
- package/src/vercel/api/oauth/revoke-github-access.ts +0 -0
- package/src/vercel/api/utils/cors.ts +3 -1
- package/src/vercel/baseFunction.ts +0 -0
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Unit tests for `createSupabaseBulkEntity`.
|
|
3
|
+
* @description Exercises happy-path, empty-bulk short-circuit, collision rejection,
|
|
4
|
+
* validation failure, ACL failure, and field-mapping preservation. The base
|
|
5
|
+
* handler wrapper (`createSupabaseHandler`) is stubbed so tests invoke the
|
|
6
|
+
* inner business logic directly without needing a mock Deno `Request`.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
10
|
+
import * as v from 'valibot';
|
|
11
|
+
|
|
12
|
+
// ---------------------------------------------------------------------------
|
|
13
|
+
// Mocks
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
|
|
16
|
+
// Stub the wrapper so the factory returns `(data, ctx) => handler(...)` instead
|
|
17
|
+
// of a Request-based handler. This lets us call the business logic directly
|
|
18
|
+
// and assert on its behaviour without mocking a full Deno runtime.
|
|
19
|
+
vi.mock('../baseFunction.js', () => ({
|
|
20
|
+
createSupabaseHandler: vi.fn(
|
|
21
|
+
(_operationName: string, _schema: unknown, handler: any) => handler
|
|
22
|
+
),
|
|
23
|
+
}));
|
|
24
|
+
|
|
25
|
+
// Field mapper stub — identity roundtrip is enough to prove mapping is invoked
|
|
26
|
+
// (we spy on the calls and verify snake_case output in the happy path).
|
|
27
|
+
vi.mock('@donotdev/supabase/server', () => ({
|
|
28
|
+
defaultFieldMapper: {
|
|
29
|
+
toBackendField: (f: string) => f,
|
|
30
|
+
toBackendKeys: (o: Record<string, unknown>) => {
|
|
31
|
+
// Convert camelCase → snake_case for the keys we stamp as metadata.
|
|
32
|
+
const out: Record<string, unknown> = {};
|
|
33
|
+
for (const [k, v] of Object.entries(o)) {
|
|
34
|
+
const snake = k.replace(/[A-Z]/g, (m) => `_${m.toLowerCase()}`);
|
|
35
|
+
out[snake] = v;
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
},
|
|
39
|
+
fromBackendRow: (r: Record<string, unknown>) => r,
|
|
40
|
+
},
|
|
41
|
+
}));
|
|
42
|
+
|
|
43
|
+
// Import after mocks so the bulk module picks them up.
|
|
44
|
+
import { createSupabaseBulkEntity } from '../crud/bulk.js';
|
|
45
|
+
|
|
46
|
+
// ---------------------------------------------------------------------------
|
|
47
|
+
// Fixtures
|
|
48
|
+
// ---------------------------------------------------------------------------
|
|
49
|
+
|
|
50
|
+
const CreateSchema = v.object({
|
|
51
|
+
name: v.pipe(v.string(), v.minLength(1)),
|
|
52
|
+
});
|
|
53
|
+
const UpdateSchema = v.object({
|
|
54
|
+
name: v.optional(v.string()),
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const access = {
|
|
58
|
+
create: 'user' as const,
|
|
59
|
+
read: 'user' as const,
|
|
60
|
+
update: 'user' as const,
|
|
61
|
+
delete: 'user' as const,
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/** Build a bulk handler + a stubbed Supabase admin client. */
|
|
65
|
+
function setup(opts?: {
|
|
66
|
+
rpcResult?: unknown;
|
|
67
|
+
rpcError?: { message: string } | null;
|
|
68
|
+
}) {
|
|
69
|
+
const rpcSpy = vi.fn().mockResolvedValue({
|
|
70
|
+
data: opts?.rpcResult ?? {
|
|
71
|
+
insertedIds: [],
|
|
72
|
+
updatedIds: [],
|
|
73
|
+
deletedIds: [],
|
|
74
|
+
},
|
|
75
|
+
error: opts?.rpcError ?? null,
|
|
76
|
+
});
|
|
77
|
+
const supabaseAdmin = { rpc: rpcSpy } as unknown as any;
|
|
78
|
+
|
|
79
|
+
const inner = createSupabaseBulkEntity(
|
|
80
|
+
'events',
|
|
81
|
+
CreateSchema,
|
|
82
|
+
UpdateSchema,
|
|
83
|
+
access
|
|
84
|
+
) as unknown as (data: any, ctx: any) => Promise<any>;
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
handler: inner,
|
|
88
|
+
rpcSpy,
|
|
89
|
+
ctx: {
|
|
90
|
+
uid: 'user-1',
|
|
91
|
+
userRole: 'user' as const,
|
|
92
|
+
supabaseAdmin,
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// ---------------------------------------------------------------------------
|
|
98
|
+
// Tests
|
|
99
|
+
// ---------------------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
describe('createSupabaseBulkEntity', () => {
|
|
102
|
+
beforeEach(() => {
|
|
103
|
+
vi.clearAllMocks();
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('happy path: 2 inserts + 1 update + 1 delete → calls RPC once, returns echoed ids in input order', async () => {
|
|
107
|
+
const rpcResult = {
|
|
108
|
+
insertedIds: ['new-1', 'new-2'],
|
|
109
|
+
updatedIds: ['u-1'],
|
|
110
|
+
deletedIds: ['d-1'],
|
|
111
|
+
};
|
|
112
|
+
const { handler, rpcSpy, ctx } = setup({ rpcResult });
|
|
113
|
+
|
|
114
|
+
const result = await handler(
|
|
115
|
+
{
|
|
116
|
+
inserts: [{ name: 'Alice' }, { name: 'Bob' }],
|
|
117
|
+
updates: [{ id: 'u-1', patch: { name: 'Updated' } }],
|
|
118
|
+
deletes: ['d-1'],
|
|
119
|
+
},
|
|
120
|
+
ctx
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
expect(rpcSpy).toHaveBeenCalledTimes(1);
|
|
124
|
+
expect(rpcSpy).toHaveBeenCalledWith(
|
|
125
|
+
'crud_bulk',
|
|
126
|
+
expect.objectContaining({
|
|
127
|
+
p_collection: 'events',
|
|
128
|
+
p_inserts: expect.any(Array),
|
|
129
|
+
p_updates: expect.any(Array),
|
|
130
|
+
p_deletes: ['d-1'],
|
|
131
|
+
})
|
|
132
|
+
);
|
|
133
|
+
expect(result).toEqual(rpcResult);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it('empty bulk short-circuits: no RPC call, zeroed response', async () => {
|
|
137
|
+
const { handler, rpcSpy, ctx } = setup();
|
|
138
|
+
|
|
139
|
+
const result = await handler({}, ctx);
|
|
140
|
+
|
|
141
|
+
expect(rpcSpy).not.toHaveBeenCalled();
|
|
142
|
+
expect(result).toEqual({
|
|
143
|
+
insertedIds: [],
|
|
144
|
+
updatedIds: [],
|
|
145
|
+
deletedIds: [],
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it('empty arrays also short-circuit (no RPC call)', async () => {
|
|
150
|
+
const { handler, rpcSpy, ctx } = setup();
|
|
151
|
+
|
|
152
|
+
const result = await handler(
|
|
153
|
+
{ inserts: [], updates: [], deletes: [] },
|
|
154
|
+
ctx
|
|
155
|
+
);
|
|
156
|
+
|
|
157
|
+
expect(rpcSpy).not.toHaveBeenCalled();
|
|
158
|
+
expect(result).toEqual({
|
|
159
|
+
insertedIds: [],
|
|
160
|
+
updatedIds: [],
|
|
161
|
+
deletedIds: [],
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it('collision rejection (updates + deletes): throws, no RPC', async () => {
|
|
166
|
+
const { handler, rpcSpy, ctx } = setup();
|
|
167
|
+
|
|
168
|
+
await expect(
|
|
169
|
+
handler(
|
|
170
|
+
{
|
|
171
|
+
updates: [{ id: 'a', patch: { name: 'X' } }],
|
|
172
|
+
deletes: ['a'],
|
|
173
|
+
},
|
|
174
|
+
ctx
|
|
175
|
+
)
|
|
176
|
+
).rejects.toMatchObject({
|
|
177
|
+
code: 'invalid-argument',
|
|
178
|
+
message: expect.stringContaining('BulkCollisionError'),
|
|
179
|
+
details: expect.objectContaining({
|
|
180
|
+
collidingIds: ['a'],
|
|
181
|
+
where: 'updates-deletes',
|
|
182
|
+
}),
|
|
183
|
+
});
|
|
184
|
+
expect(rpcSpy).not.toHaveBeenCalled();
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
it('validation failure on insert: rejects before any RPC write', async () => {
|
|
188
|
+
const { handler, rpcSpy, ctx } = setup();
|
|
189
|
+
|
|
190
|
+
await expect(
|
|
191
|
+
handler(
|
|
192
|
+
{
|
|
193
|
+
inserts: [{ name: 'Alice' }, { name: '' }], // second one invalid
|
|
194
|
+
updates: [{ id: 'u-1', patch: { name: 'Ok' } }],
|
|
195
|
+
},
|
|
196
|
+
ctx
|
|
197
|
+
)
|
|
198
|
+
).rejects.toMatchObject({
|
|
199
|
+
code: 'invalid-argument',
|
|
200
|
+
message: expect.stringContaining('inserts[1]'),
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
expect(rpcSpy).not.toHaveBeenCalled();
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
it('validation failure on update patch: rejects before any RPC write', async () => {
|
|
207
|
+
const { handler, rpcSpy, ctx } = setup();
|
|
208
|
+
|
|
209
|
+
await expect(
|
|
210
|
+
handler(
|
|
211
|
+
{
|
|
212
|
+
updates: [{ id: 'u-1', patch: { name: 123 as any } }], // number not string
|
|
213
|
+
},
|
|
214
|
+
ctx
|
|
215
|
+
)
|
|
216
|
+
).rejects.toMatchObject({
|
|
217
|
+
code: 'invalid-argument',
|
|
218
|
+
message: expect.stringContaining('updates[0]'),
|
|
219
|
+
});
|
|
220
|
+
expect(rpcSpy).not.toHaveBeenCalled();
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
it('ACL failure: user lacks delete role → rejects, no RPC', async () => {
|
|
224
|
+
const rpcSpy = vi.fn();
|
|
225
|
+
const supabaseAdmin = { rpc: rpcSpy } as unknown as any;
|
|
226
|
+
|
|
227
|
+
const inner = createSupabaseBulkEntity(
|
|
228
|
+
'events',
|
|
229
|
+
CreateSchema,
|
|
230
|
+
UpdateSchema,
|
|
231
|
+
{ ...access, delete: 'admin' }
|
|
232
|
+
) as unknown as (data: any, ctx: any) => Promise<any>;
|
|
233
|
+
|
|
234
|
+
await expect(
|
|
235
|
+
inner(
|
|
236
|
+
{ deletes: ['a', 'b'] },
|
|
237
|
+
{ uid: 'u', userRole: 'user', supabaseAdmin }
|
|
238
|
+
)
|
|
239
|
+
).rejects.toMatchObject({
|
|
240
|
+
code: 'permission-denied',
|
|
241
|
+
message: expect.stringContaining('admin'),
|
|
242
|
+
});
|
|
243
|
+
expect(rpcSpy).not.toHaveBeenCalled();
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
it('field-mapping: inserts carry snake_case metadata (created_at, created_by_id) via toBackendKeys', async () => {
|
|
247
|
+
const rpcResult = {
|
|
248
|
+
insertedIds: ['n-1'],
|
|
249
|
+
updatedIds: [],
|
|
250
|
+
deletedIds: [],
|
|
251
|
+
};
|
|
252
|
+
const { handler, rpcSpy, ctx } = setup({ rpcResult });
|
|
253
|
+
|
|
254
|
+
await handler({ inserts: [{ name: 'Alice' }] }, ctx);
|
|
255
|
+
|
|
256
|
+
expect(rpcSpy).toHaveBeenCalledTimes(1);
|
|
257
|
+
const call = rpcSpy.mock.calls[0];
|
|
258
|
+
const args = call[1];
|
|
259
|
+
const firstInsert = args.p_inserts[0];
|
|
260
|
+
|
|
261
|
+
// Metadata keys came from createMetadata() and were snake-cased by our
|
|
262
|
+
// stubbed toBackendKeys.
|
|
263
|
+
expect(firstInsert).toMatchObject({
|
|
264
|
+
name: 'Alice',
|
|
265
|
+
created_by_id: 'user-1',
|
|
266
|
+
updated_by_id: 'user-1',
|
|
267
|
+
});
|
|
268
|
+
expect(firstInsert.created_at).toBeDefined();
|
|
269
|
+
expect(firstInsert.updated_at).toBeDefined();
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
it('field-mapping: updates carry snake_case metadata (updated_at, updated_by_id), no created_* leakage', async () => {
|
|
273
|
+
const rpcResult = {
|
|
274
|
+
insertedIds: [],
|
|
275
|
+
updatedIds: ['u-1'],
|
|
276
|
+
deletedIds: [],
|
|
277
|
+
};
|
|
278
|
+
const { handler, rpcSpy, ctx } = setup({ rpcResult });
|
|
279
|
+
|
|
280
|
+
await handler(
|
|
281
|
+
{ updates: [{ id: 'u-1', patch: { name: 'Renamed' } }] },
|
|
282
|
+
ctx
|
|
283
|
+
);
|
|
284
|
+
|
|
285
|
+
const args = rpcSpy.mock.calls[0][1];
|
|
286
|
+
const firstPatch = args.p_updates[0].patch;
|
|
287
|
+
|
|
288
|
+
expect(firstPatch).toMatchObject({
|
|
289
|
+
name: 'Renamed',
|
|
290
|
+
updated_by_id: 'user-1',
|
|
291
|
+
});
|
|
292
|
+
expect(firstPatch.updated_at).toBeDefined();
|
|
293
|
+
expect(firstPatch.created_by_id).toBeUndefined();
|
|
294
|
+
expect(firstPatch.created_at).toBeUndefined();
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
it('RPC error surfaces as DoNotDevError (transaction-level failure)', async () => {
|
|
298
|
+
const { handler, ctx } = setup({
|
|
299
|
+
rpcError: { message: 'deadlock detected' },
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
await expect(handler({ deletes: ['a'] }, ctx)).rejects.toMatchObject({
|
|
303
|
+
code: 'internal',
|
|
304
|
+
message: expect.stringContaining('bulk'),
|
|
305
|
+
});
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
it('input order is preserved in RPC payload', async () => {
|
|
309
|
+
const rpcResult = {
|
|
310
|
+
insertedIds: ['n-1', 'n-2', 'n-3'],
|
|
311
|
+
updatedIds: ['u-1', 'u-2'],
|
|
312
|
+
deletedIds: ['d-1', 'd-2'],
|
|
313
|
+
};
|
|
314
|
+
const { handler, rpcSpy, ctx } = setup({ rpcResult });
|
|
315
|
+
|
|
316
|
+
const inserts = [{ name: 'A' }, { name: 'B' }, { name: 'C' }];
|
|
317
|
+
const updates = [
|
|
318
|
+
{ id: 'u-1', patch: { name: 'X' } },
|
|
319
|
+
{ id: 'u-2', patch: { name: 'Y' } },
|
|
320
|
+
];
|
|
321
|
+
const deletes = ['d-1', 'd-2'];
|
|
322
|
+
|
|
323
|
+
await handler({ inserts, updates, deletes }, ctx);
|
|
324
|
+
|
|
325
|
+
const args = rpcSpy.mock.calls[0][1];
|
|
326
|
+
expect(args.p_inserts.map((r: any) => r.name)).toEqual(['A', 'B', 'C']);
|
|
327
|
+
expect(args.p_updates.map((u: any) => u.id)).toEqual(['u-1', 'u-2']);
|
|
328
|
+
expect(args.p_deletes).toEqual(['d-1', 'd-2']);
|
|
329
|
+
});
|
|
330
|
+
});
|
|
@@ -49,24 +49,25 @@ export function createAIFunction(config: AIRouteConfig) {
|
|
|
49
49
|
requestId: crypto.randomUUID(),
|
|
50
50
|
onCostRecord: async (record: AICostRecord) => {
|
|
51
51
|
// Write cost record to Supabase
|
|
52
|
-
const { error } = await ctx.supabaseAdmin
|
|
53
|
-
.
|
|
54
|
-
.
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
created_at: record.timestamp,
|
|
66
|
-
});
|
|
52
|
+
const { error } = await ctx.supabaseAdmin.from('ai_usage').insert({
|
|
53
|
+
user_id: record.userId,
|
|
54
|
+
model: record.model,
|
|
55
|
+
provider: record.provider,
|
|
56
|
+
prompt_tokens: record.usage.promptTokens,
|
|
57
|
+
completion_tokens: record.usage.completionTokens,
|
|
58
|
+
total_tokens: record.usage.totalTokens,
|
|
59
|
+
provider_cost: record.providerCost,
|
|
60
|
+
billed_cost: record.billedCost,
|
|
61
|
+
markup: record.markup,
|
|
62
|
+
request_id: record.requestId,
|
|
63
|
+
created_at: record.timestamp,
|
|
64
|
+
});
|
|
67
65
|
|
|
68
66
|
if (error) {
|
|
69
|
-
console.error(
|
|
67
|
+
console.error(
|
|
68
|
+
'[AI] Failed to record cost to Supabase:',
|
|
69
|
+
error.message
|
|
70
|
+
);
|
|
70
71
|
}
|
|
71
72
|
},
|
|
72
73
|
});
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
@@ -104,9 +104,7 @@ export function createSetCustomClaims(options: SetCustomClaimsOptions) {
|
|
|
104
104
|
(k) => !allowedKeys.has(k)
|
|
105
105
|
);
|
|
106
106
|
if (disallowedKeys.length > 0) {
|
|
107
|
-
throw new Error(
|
|
108
|
-
`Claim keys not allowed: ${disallowedKeys.join(', ')}`
|
|
109
|
-
);
|
|
107
|
+
throw new Error(`Claim keys not allowed: ${disallowedKeys.join(', ')}`);
|
|
110
108
|
}
|
|
111
109
|
|
|
112
110
|
// Get current app_metadata
|
|
File without changes
|
|
File without changes
|
|
@@ -51,7 +51,7 @@ export function createChangePlan(billingConfig: StripeBackConfig) {
|
|
|
51
51
|
async (data, ctx) => {
|
|
52
52
|
// Non-admin users can only change their own plan
|
|
53
53
|
if (!hasRoleAccess(ctx.userRole, 'admin') && data.userId !== ctx.uid) {
|
|
54
|
-
throw new Error(
|
|
54
|
+
throw new Error("Forbidden: cannot change another user's plan");
|
|
55
55
|
}
|
|
56
56
|
|
|
57
57
|
initStripe(getStripeKey());
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
// packages/functions/src/supabase/crud/bulk.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Supabase bulk CRUD handler.
|
|
5
|
+
* @description Thin Supabase RPC adapter on top of the shared `executeBulk`
|
|
6
|
+
* orchestrator. Assembles a `supabaseAdmin.rpc('crud_bulk', ...)` call as
|
|
7
|
+
* the target-specific `transact` callback; all other policy (validation,
|
|
8
|
+
* collision, per-bucket ACL, metadata stamping, audit) lives in
|
|
9
|
+
* {@link executeBulk} so Firestore, Vercel, GraphQL and future REST-CRUD
|
|
10
|
+
* server aids share one correctness surface.
|
|
11
|
+
*
|
|
12
|
+
* The Postgres RPC `crud_bulk` wraps `BEGIN ... COMMIT`, so one RPC call
|
|
13
|
+
* is one transaction from the client's perspective.
|
|
14
|
+
*
|
|
15
|
+
* @version 0.2.0
|
|
16
|
+
* @since 0.6.0
|
|
17
|
+
* @author AMBROISE PARK Consulting
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import * as v from 'valibot';
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
BulkCollisionError,
|
|
24
|
+
BulkRequestSchema,
|
|
25
|
+
DoNotDevError,
|
|
26
|
+
} from '@donotdev/core/server';
|
|
27
|
+
import type {
|
|
28
|
+
BulkRequest,
|
|
29
|
+
BulkResponse,
|
|
30
|
+
EntityAccessConfig,
|
|
31
|
+
UserRole,
|
|
32
|
+
} from '@donotdev/core/server';
|
|
33
|
+
import { defaultFieldMapper } from '@donotdev/supabase/server';
|
|
34
|
+
|
|
35
|
+
import {
|
|
36
|
+
createMetadata,
|
|
37
|
+
executeBulk,
|
|
38
|
+
updateMetadata,
|
|
39
|
+
} from '../../shared/index.js';
|
|
40
|
+
import { createSupabaseHandler } from '../baseFunction.js';
|
|
41
|
+
|
|
42
|
+
// =============================================================================
|
|
43
|
+
// Types & helpers
|
|
44
|
+
// =============================================================================
|
|
45
|
+
|
|
46
|
+
const mapper = defaultFieldMapper;
|
|
47
|
+
|
|
48
|
+
/** Request payload accepted by the bulk handler — mirrors {@link BulkRequestSchema}. */
|
|
49
|
+
export type BulkEntityRequest = BulkRequest;
|
|
50
|
+
|
|
51
|
+
/** Ordered list of role levels, low → high. Used to pick the strictest needed role. */
|
|
52
|
+
const ROLE_RANK: Record<UserRole, number> = {
|
|
53
|
+
guest: 0,
|
|
54
|
+
user: 1,
|
|
55
|
+
admin: 2,
|
|
56
|
+
super: 3,
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Strip client-supplied timestamps (DB triggers own them) and convert keys to
|
|
61
|
+
* the snake_case shape the DB expects.
|
|
62
|
+
*/
|
|
63
|
+
function prepareInsertRow(
|
|
64
|
+
row: Record<string, unknown>,
|
|
65
|
+
uid: string
|
|
66
|
+
): Record<string, unknown> {
|
|
67
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
68
|
+
const { createdAt, updatedAt, created_at, updated_at, ...rest } =
|
|
69
|
+
row as Record<string, unknown>;
|
|
70
|
+
const snake = mapper.toBackendKeys(rest);
|
|
71
|
+
const meta = mapper.toBackendKeys(
|
|
72
|
+
createMetadata(uid) as Record<string, unknown>
|
|
73
|
+
);
|
|
74
|
+
return { ...snake, ...meta };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function preparePatch(
|
|
78
|
+
patch: Record<string, unknown>,
|
|
79
|
+
uid: string
|
|
80
|
+
): Record<string, unknown> {
|
|
81
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
82
|
+
const {
|
|
83
|
+
createdAt,
|
|
84
|
+
updatedAt,
|
|
85
|
+
created_at,
|
|
86
|
+
updated_at,
|
|
87
|
+
id: _id,
|
|
88
|
+
...rest
|
|
89
|
+
} = patch as Record<string, unknown>;
|
|
90
|
+
const snake = mapper.toBackendKeys(rest);
|
|
91
|
+
const meta = mapper.toBackendKeys(
|
|
92
|
+
updateMetadata(uid) as Record<string, unknown>
|
|
93
|
+
);
|
|
94
|
+
return { ...snake, ...meta };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// =============================================================================
|
|
98
|
+
// Factory
|
|
99
|
+
// =============================================================================
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Create a Supabase Edge Function handler for atomic bulk CRUD on one collection.
|
|
103
|
+
*
|
|
104
|
+
* @description
|
|
105
|
+
* One HTTP round-trip, one rate-limit hit, one audit line, one DB transaction.
|
|
106
|
+
* Inserts, updates and deletes run in input order inside the `crud_bulk` RPC
|
|
107
|
+
* which wraps `BEGIN ... COMMIT` — any failure triggers `ROLLBACK` and the
|
|
108
|
+
* client observes a rejected promise with no partial state.
|
|
109
|
+
*
|
|
110
|
+
* The factory returns a handler that is auto-registered as `bulk_${collection}`
|
|
111
|
+
* by {@link createSupabaseCrudFunctions}.
|
|
112
|
+
*
|
|
113
|
+
* @param collection - Postgres table name for the entity.
|
|
114
|
+
* @param createSchema - Valibot schema validating each `inserts[]` row.
|
|
115
|
+
* @param updateSchema - Valibot schema validating each `updates[].patch` object.
|
|
116
|
+
* @param access - Entity access config; per-bucket role check runs before writes.
|
|
117
|
+
* @returns A `(req: Request) => Promise<Response>` handler for `Deno.serve`.
|
|
118
|
+
* @throws BulkCollisionError — via the thrown DoNotDevError when an id appears in two buckets.
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* ```typescript
|
|
122
|
+
* // Auto-registration (preferred):
|
|
123
|
+
* import * as entities from '../_shared/entities.ts';
|
|
124
|
+
* import { createSupabaseCrudFunctions } from '@donotdev/functions/supabase';
|
|
125
|
+
* const { serve } = createSupabaseCrudFunctions(entities);
|
|
126
|
+
* Deno.serve(serve);
|
|
127
|
+
* // POST { _functionName: 'bulk_events', inserts: [...], updates: [...], deletes: [...] }
|
|
128
|
+
*
|
|
129
|
+
* // Manual registration:
|
|
130
|
+
* import { createSupabaseBulkEntity } from '@donotdev/functions/supabase';
|
|
131
|
+
* import { eventEntity, eventCreateSchema, eventUpdateSchema } from '../_shared/entities.ts';
|
|
132
|
+
* Deno.serve(createSupabaseBulkEntity(
|
|
133
|
+
* eventEntity.collection,
|
|
134
|
+
* eventCreateSchema,
|
|
135
|
+
* eventUpdateSchema,
|
|
136
|
+
* eventEntity.access,
|
|
137
|
+
* ));
|
|
138
|
+
* ```
|
|
139
|
+
*
|
|
140
|
+
* @version 0.2.0
|
|
141
|
+
* @since 0.6.0
|
|
142
|
+
*/
|
|
143
|
+
export function createSupabaseBulkEntity(
|
|
144
|
+
collection: string,
|
|
145
|
+
createSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
146
|
+
draftCreateSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
147
|
+
updateSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
|
|
148
|
+
access: EntityAccessConfig
|
|
149
|
+
): (req: Request) => Promise<Response> {
|
|
150
|
+
// The wrapper role is the strictest across the three buckets. Entities that
|
|
151
|
+
// only configure a subset (e.g. read-only) collapse to 'user' so mixed-ACL
|
|
152
|
+
// misalignments still reach the handler where `executeBulk` catches them
|
|
153
|
+
// with a precise per-bucket error.
|
|
154
|
+
const wrapperRole: UserRole = (() => {
|
|
155
|
+
const roles: UserRole[] = [];
|
|
156
|
+
if (access.create) roles.push(access.create);
|
|
157
|
+
if (access.update) roles.push(access.update);
|
|
158
|
+
if (access.delete) roles.push(access.delete);
|
|
159
|
+
if (roles.length === 0) return 'user';
|
|
160
|
+
return roles.reduce((a, b) => (ROLE_RANK[a] >= ROLE_RANK[b] ? a : b));
|
|
161
|
+
})();
|
|
162
|
+
|
|
163
|
+
return createSupabaseHandler(
|
|
164
|
+
`bulk_${collection}`,
|
|
165
|
+
BulkRequestSchema,
|
|
166
|
+
async (data: BulkEntityRequest, ctx): Promise<BulkResponse> => {
|
|
167
|
+
const { uid, userRole, supabaseAdmin } = ctx;
|
|
168
|
+
|
|
169
|
+
try {
|
|
170
|
+
return await executeBulk({
|
|
171
|
+
collection,
|
|
172
|
+
ops: data,
|
|
173
|
+
createSchema,
|
|
174
|
+
draftCreateSchema,
|
|
175
|
+
updateSchema,
|
|
176
|
+
access,
|
|
177
|
+
uid,
|
|
178
|
+
userRole,
|
|
179
|
+
// Supabase's `crud_bulk` RPC mints ids server-side — skip the
|
|
180
|
+
// client-side mint hook so the RPC owns the id space.
|
|
181
|
+
stampInsertMetadata: prepareInsertRow,
|
|
182
|
+
stampUpdateMetadata: preparePatch,
|
|
183
|
+
transact: async ({ inserts, updates, deletes }) => {
|
|
184
|
+
const { data: rpcResult, error: rpcError } =
|
|
185
|
+
await supabaseAdmin.rpc('crud_bulk', {
|
|
186
|
+
p_collection: collection,
|
|
187
|
+
p_inserts: inserts.map((i) => i.row),
|
|
188
|
+
p_updates: updates.map((u) => ({ id: u.id, patch: u.patch })),
|
|
189
|
+
p_deletes: deletes,
|
|
190
|
+
});
|
|
191
|
+
if (rpcError) {
|
|
192
|
+
throw new DoNotDevError(
|
|
193
|
+
`Failed to execute bulk: ${rpcError.message}`,
|
|
194
|
+
'internal'
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
// RPC may return either camelCase or snake_case id arrays — normalise
|
|
198
|
+
// before `executeBulk` runs its `BulkResponseSchema` validation.
|
|
199
|
+
const raw = (rpcResult ?? {}) as Record<string, unknown>;
|
|
200
|
+
return {
|
|
201
|
+
insertedIds: Array.isArray(raw.insertedIds)
|
|
202
|
+
? (raw.insertedIds as string[])
|
|
203
|
+
: Array.isArray(raw.inserted_ids)
|
|
204
|
+
? (raw.inserted_ids as string[])
|
|
205
|
+
: [],
|
|
206
|
+
updatedIds: Array.isArray(raw.updatedIds)
|
|
207
|
+
? (raw.updatedIds as string[])
|
|
208
|
+
: Array.isArray(raw.updated_ids)
|
|
209
|
+
? (raw.updated_ids as string[])
|
|
210
|
+
: [],
|
|
211
|
+
deletedIds: Array.isArray(raw.deletedIds)
|
|
212
|
+
? (raw.deletedIds as string[])
|
|
213
|
+
: Array.isArray(raw.deleted_ids)
|
|
214
|
+
? (raw.deleted_ids as string[])
|
|
215
|
+
: [],
|
|
216
|
+
};
|
|
217
|
+
},
|
|
218
|
+
audit: (event, { counts }) => {
|
|
219
|
+
// One audit line per bulk (matches the "one audit entry"
|
|
220
|
+
// contract). Sibling handlers use console.log for parity with
|
|
221
|
+
// the edge-function logging expectations.
|
|
222
|
+
console.log(
|
|
223
|
+
`[${event}] uid=${uid} inserts=${counts.inserts} updates=${counts.updates} deletes=${counts.deletes}`
|
|
224
|
+
);
|
|
225
|
+
},
|
|
226
|
+
});
|
|
227
|
+
} catch (err) {
|
|
228
|
+
// Translate the shared orchestrator's collision error into the
|
|
229
|
+
// DoNotDevError shape expected by the Supabase wire contract
|
|
230
|
+
// (invalid-argument + collision details in `details`).
|
|
231
|
+
if (err instanceof BulkCollisionError) {
|
|
232
|
+
throw new DoNotDevError(err.message, 'invalid-argument', {
|
|
233
|
+
details: {
|
|
234
|
+
collidingIds: err.collidingIds,
|
|
235
|
+
where: err.where,
|
|
236
|
+
},
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
throw err;
|
|
240
|
+
}
|
|
241
|
+
},
|
|
242
|
+
wrapperRole
|
|
243
|
+
);
|
|
244
|
+
}
|