@donotdev/functions 0.1.42 → 0.2.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.
- package/README.md +25 -14
- package/lib/chunks/chunk-2JL3GDTO.js +151 -0
- package/lib/chunks/chunk-2JL3GDTO.js.map +7 -0
- package/lib/chunks/chunk-4TVLH2W2.js +22 -0
- package/lib/chunks/chunk-4TVLH2W2.js.map +7 -0
- package/lib/chunks/chunk-4U7QQWYG.js +22 -0
- package/lib/chunks/chunk-4U7QQWYG.js.map +7 -0
- package/lib/chunks/chunk-5DTPEM64.js +22 -0
- package/lib/chunks/chunk-5DTPEM64.js.map +7 -0
- package/lib/chunks/chunk-6CQXHNVL.js +22 -0
- package/lib/chunks/chunk-6CQXHNVL.js.map +7 -0
- package/lib/chunks/chunk-6DSCPZC6.js +22 -0
- package/lib/chunks/chunk-6DSCPZC6.js.map +7 -0
- package/lib/chunks/chunk-7E6TGWHU.js +22 -0
- package/lib/chunks/chunk-7E6TGWHU.js.map +7 -0
- package/lib/chunks/chunk-7LT32OWE.js +22 -0
- package/lib/chunks/chunk-7LT32OWE.js.map +7 -0
- package/lib/chunks/chunk-7VH2GJXT.js +151 -0
- package/lib/chunks/chunk-7VH2GJXT.js.map +7 -0
- package/lib/chunks/chunk-API5A4BV.js +22 -0
- package/lib/chunks/chunk-API5A4BV.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-BUP7SXPV.js +23 -0
- package/lib/chunks/chunk-BUP7SXPV.js.map +7 -0
- package/lib/chunks/chunk-BXKRI3JJ.js +22 -0
- package/lib/chunks/chunk-BXKRI3JJ.js.map +7 -0
- package/lib/chunks/chunk-FSLGZD7A.js +21 -0
- package/lib/chunks/chunk-FSLGZD7A.js.map +7 -0
- package/lib/chunks/chunk-GVLSPWDD.js +151 -0
- package/lib/chunks/chunk-GVLSPWDD.js.map +7 -0
- package/lib/chunks/chunk-GXQVWEFT.js +22 -0
- package/lib/chunks/chunk-GXQVWEFT.js.map +7 -0
- package/lib/chunks/chunk-HB7EGXVI.js +22 -0
- package/lib/chunks/chunk-HB7EGXVI.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-HM7XCMWW.js +22 -0
- package/lib/chunks/chunk-HM7XCMWW.js.map +7 -0
- package/lib/chunks/chunk-I7IOIL6U.js +151 -0
- package/lib/chunks/chunk-I7IOIL6U.js.map +7 -0
- package/lib/chunks/chunk-IFOYVSPU.js +22 -0
- package/lib/chunks/chunk-IFOYVSPU.js.map +7 -0
- package/lib/chunks/chunk-JTAGPPPL.js +22 -0
- package/lib/chunks/chunk-JTAGPPPL.js.map +7 -0
- package/lib/chunks/chunk-MZ232FUE.js +22 -0
- package/lib/chunks/chunk-MZ232FUE.js.map +7 -0
- package/lib/chunks/chunk-NE5ZTUUZ.js +22 -0
- package/lib/chunks/chunk-NE5ZTUUZ.js.map +7 -0
- package/lib/chunks/chunk-NP2AN2TV.js +22 -0
- package/lib/chunks/chunk-NP2AN2TV.js.map +7 -0
- package/lib/chunks/chunk-QJAU2MWV.js +22 -0
- package/lib/chunks/chunk-QJAU2MWV.js.map +7 -0
- package/lib/chunks/chunk-RM7DV6IQ.js +23 -0
- package/lib/chunks/chunk-RM7DV6IQ.js.map +7 -0
- package/lib/chunks/chunk-RQZGIZHD.js +151 -0
- package/lib/chunks/chunk-RQZGIZHD.js.map +7 -0
- package/lib/chunks/chunk-TBEDQLOB.js +23 -0
- package/lib/chunks/chunk-TBEDQLOB.js.map +7 -0
- package/lib/chunks/chunk-TMHBP3HB.js +22 -0
- package/lib/chunks/chunk-TMHBP3HB.js.map +7 -0
- package/lib/chunks/chunk-UH4L3EF3.js +151 -0
- package/lib/chunks/chunk-UH4L3EF3.js.map +7 -0
- package/lib/chunks/chunk-UJBIU6TL.js +22 -0
- package/lib/chunks/chunk-UJBIU6TL.js.map +7 -0
- package/lib/chunks/chunk-VKEYW3NT.js +22 -0
- package/lib/chunks/chunk-VKEYW3NT.js.map +7 -0
- package/lib/chunks/chunk-XGXBMXJ6.js +22 -0
- package/lib/chunks/chunk-XGXBMXJ6.js.map +7 -0
- package/lib/chunks/chunk-Y44NEQQG.js +22 -0
- package/lib/chunks/chunk-Y44NEQQG.js.map +7 -0
- package/lib/chunks/chunk-ZVU3KPXI.js +22 -0
- package/lib/chunks/chunk-ZVU3KPXI.js.map +7 -0
- package/lib/chunks/monitoring-AGCSU3FI.js +22 -0
- package/lib/chunks/monitoring-AGCSU3FI.js.map +7 -0
- package/lib/chunks/monitoring-PVQMFL34.js +22 -0
- package/lib/chunks/monitoring-PVQMFL34.js.map +7 -0
- package/lib/chunks/monitoring-V7FZXTTW.js +22 -0
- package/lib/chunks/monitoring-V7FZXTTW.js.map +7 -0
- package/lib/chunks/rateLimiter-6KO7AIZP.js +22 -0
- package/lib/chunks/rateLimiter-6KO7AIZP.js.map +7 -0
- package/lib/chunks/rateLimiter-OXVBFW5C.js +22 -0
- package/lib/chunks/rateLimiter-OXVBFW5C.js.map +7 -0
- package/lib/chunks/rateLimiter-U45OMTWR.js +22 -0
- package/lib/chunks/rateLimiter-U45OMTWR.js.map +7 -0
- package/lib/chunks/server-32A5RH4C.js +22 -0
- package/lib/chunks/server-32A5RH4C.js.map +7 -0
- package/lib/chunks/server-7HDAP5DL.js +22 -0
- package/lib/chunks/server-7HDAP5DL.js.map +7 -0
- package/lib/chunks/server-S2IMFOY7.js +22 -0
- package/lib/chunks/server-S2IMFOY7.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/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/createCheckoutSession.d.ts +2 -2
- package/lib/firebase/billing/createCustomerPortal.d.ts +1 -1
- 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/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/list.d.ts +1 -1
- package/lib/firebase/crud/update.d.ts +1 -9
- package/lib/firebase/index.js +1 -5
- package/lib/firebase/index.js.map +4 -4
- package/lib/firebase/oauth/githubAccess.d.ts +2 -2
- package/lib/firebase/registerCrudFunctions.d.ts +9 -1
- 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/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 +32 -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/supabaseIdempotency.d.ts +32 -0
- package/lib/shared/billing/tierWebhookEvents.d.ts +54 -0
- package/lib/shared/billing/webhookHandler.d.ts +28 -20
- package/lib/shared/index.js +1 -6
- package/lib/shared/index.js.map +4 -4
- package/lib/shared/utils/functionWrapper.d.ts +1 -1
- package/lib/shared/utils/internal/auth.d.ts +38 -1
- package/lib/shared/utils/internal/rateLimiter.d.ts +8 -0
- package/lib/shared/utils/schemaValidation.d.ts +1 -1
- package/lib/shared/utils/vercelHelpers.d.ts +8 -0
- package/lib/shared/utils.d.ts +4 -17
- package/lib/supabase/baseFunction.d.ts +1 -1
- package/lib/supabase/billing/stripeWebhook.d.ts +34 -0
- package/lib/supabase/crud/bulk.d.ts +1 -1
- package/lib/supabase/crud/entityStore.d.ts +71 -0
- package/lib/supabase/crud/index.d.ts +2 -0
- package/lib/supabase/helpers/authProvider.d.ts +5 -5
- package/lib/supabase/index.d.ts +10 -2
- package/lib/supabase/index.js +1 -3
- package/lib/supabase/index.js.map +4 -4
- package/lib/supabase/utils/rateLimiter.d.ts +1 -1
- package/lib/vercel/api/ai/chat.d.ts +0 -9
- 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/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/firebase-admin.d.ts +8 -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/list.d.ts +8 -0
- package/lib/vercel/api/crud/update.d.ts +8 -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/revoke-github-access.d.ts +1 -1
- 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 +1 -2
- package/src/firebase/billing/changePlan.ts +2 -3
- package/src/firebase/billing/createCheckoutSession.ts +30 -56
- package/src/firebase/billing/createCustomerPortal.ts +4 -5
- package/src/firebase/billing/healthCheck.ts +0 -0
- package/src/firebase/billing/index.ts +8 -1
- package/src/firebase/billing/refreshSubscriptionStatus.ts +2 -3
- package/src/firebase/billing/webhookHandler.ts +20 -4
- 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 -3
- 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 +2 -1
- 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 +407 -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/helpers/index.ts +0 -1
- package/src/shared/billing/helpers/subscriptionManagement.ts +7 -9
- package/src/shared/billing/helpers/updateUserSubscription.ts +3 -36
- package/src/shared/billing/idempotency.ts +253 -150
- 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/supabaseIdempotency.ts +228 -0
- package/src/shared/billing/tierWebhookEvents.ts +432 -0
- package/src/shared/billing/webhookHandler.ts +188 -385
- 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/schemaValidation.ts +1 -2
- package/src/shared/utils/vercelHelpers.ts +3 -3
- package/src/shared/utils.ts +14 -31
- 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/createCheckoutSession.ts +10 -36
- package/src/supabase/billing/refreshSubscriptionStatus.ts +1 -2
- 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/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 +3 -4
- package/src/vercel/api/billing/create-checkout-session.ts +42 -68
- package/src/vercel/api/billing/customer-portal.ts +2 -4
- package/src/vercel/api/billing/index.ts +4 -2
- package/src/vercel/api/billing/refresh-subscription-status.ts +21 -6
- package/src/vercel/api/billing/webhook-handler.ts +31 -25
- 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
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/shared/metadata.ts", "../../src/shared/crud/bulkCore.ts", "../../src/shared/email/createEmailRoute.ts", "../../src/shared/email/resendProvider.ts"],
|
|
4
|
+
"sourcesContent": ["// packages/functions/src/shared/metadata.ts\n\n/**\n * @fileoverview Document metadata utilities for functions\n * @description Server-safe metadata creation and update utilities\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\n/**\n * Creates metadata for a new document.\n * @param userId - The ID of the user creating the document\n * @returns An object with creation and update timestamps and user IDs\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function createMetadata(userId: string) {\n const now = new Date().toISOString();\n return {\n createdAt: now,\n updatedAt: now,\n createdById: userId,\n updatedById: userId,\n };\n}\n\n/**\n * Creates update metadata for an existing document.\n * @param userId - The ID of the user updating the document\n * @returns An object with update timestamp and user ID\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function updateMetadata(userId: string) {\n return {\n updatedAt: new Date().toISOString(),\n updatedById: userId,\n };\n}\n", "// packages/functions/src/shared/crud/bulkCore.ts\n\n/**\n * @fileoverview Shared bulk CRUD orchestration core.\n * @description Target-agnostic orchestrator that owns the bulk policy\n * (wire validation, collision detection, per-bucket ACL, per-row schema\n * validation, id minting, metadata stamping, audit, response validation).\n * Target storage is delegated to a caller-supplied `transact` callback \u2014\n * this lets Firestore admin, Supabase RPC, Vercel firebase-admin, future\n * GraphQL and future REST-CRUD server aids share one source of truth for\n * correctness without pulling any platform-specific dependencies here.\n *\n * This module is server-only (`shared/` but never imported from `client/`\n * or `common/`) and designed to stay portable across Node and Deno \u2014 it\n * does not import `fs`, `net`, `firebase-admin`, `supabase-js`, etc.\n *\n * @version 0.1.0\n * @since 0.7.0\n * @author AMBROISE PARK Consulting\n */\n\nimport * as v from 'valibot';\n\nimport {\n BulkCollisionError,\n BulkRequestSchema,\n BulkResponseSchema,\n detectBulkCollisions,\n DoNotDevError,\n hasRoleAccess,\n DEFAULT_STATUS_VALUE,\n} from '@donotdev/core/server';\nimport type {\n BulkRequest,\n BulkResponse,\n EntityAccessConfig,\n UserRole,\n} from '@donotdev/core/server';\n\n// =============================================================================\n// Public types\n// =============================================================================\n\n/**\n * Valibot schema alias accepted by {@link executeBulk}. Kept loose (`any` on\n * the parsed output) so callers can pass entity-specific schemas generated by\n * `createSchemas()` without fighting variance.\n */\nexport type BulkRowSchema = v.BaseSchema<unknown, any, v.BaseIssue<unknown>>;\n\n/**\n * A prepared insert row passed to the caller-supplied `transact` callback.\n * When {@link ExecuteBulkParams.mintInsertId} is provided, `id` is the minted\n * value; otherwise it carries whatever id (if any) the client supplied and\n * the storage layer is expected to mint its own.\n */\nexport interface PreparedInsert {\n /** Minted insert id, or the empty string when the target mints its own. */\n id: string;\n /** Fully stamped row ready for storage. */\n row: Record<string, unknown>;\n}\n\n/**\n * A prepared update passed to `transact`.\n */\nexport interface PreparedUpdate {\n /** Target row id. */\n id: string;\n /** Fully stamped patch ready for storage. */\n patch: Record<string, unknown>;\n}\n\n/**\n * Payload handed to the caller-supplied `transact` callback. All three\n * arrays preserve input order and only include non-empty buckets' work.\n */\nexport interface PreparedBulk {\n inserts: PreparedInsert[];\n updates: PreparedUpdate[];\n deletes: string[];\n}\n\n/**\n * Parameters for {@link executeBulk}.\n *\n * @template TRow - Row type recorded for documentation; runtime is opaque.\n */\nexport interface ExecuteBulkParams<TRow = unknown> {\n /** Collection / table name. Passed through to audit + transact as metadata. */\n collection: string;\n /** Raw wire payload to orchestrate. Parsed with {@link BulkRequestSchema}. */\n ops: BulkRequest;\n /** Valibot schema validating each insert row. */\n createSchema: BulkRowSchema;\n /** Valibot schema validating each insert row when status === 'draft'. */\n draftCreateSchema?: BulkRowSchema;\n /** Valibot schema validating each update patch. */\n updateSchema: BulkRowSchema;\n /** Per-bucket required roles. Missing entries are treated as \"no bucket allowed\". */\n access: EntityAccessConfig;\n /** Authenticated caller id (for metadata + audit). */\n uid: string;\n /** Caller's role (for per-bucket ACL). */\n userRole: UserRole;\n /**\n * Target-specific storage. Invoked exactly once when the bulk carries at\n * least one op. Must run all three buckets inside one atomic transaction\n * (writeBatch, runTransaction, Postgres RPC wrapping BEGIN/COMMIT, etc.)\n * and return ids per bucket in input order.\n *\n * The returned shape is validated against `BulkResponseSchema` before\n * being returned to the caller.\n */\n transact: (prepared: PreparedBulk) => Promise<BulkResponse>;\n /**\n * Optional id minting. When provided, every insert is stamped with a\n * freshly-minted id before `transact` runs. When omitted, `id` on each\n * {@link PreparedInsert} is the empty string and the storage layer is\n * expected to mint its own ids (Supabase RPC, GraphQL server, etc.).\n */\n mintInsertId?: () => string;\n /**\n * Optional hook to stamp platform-specific metadata on every insert row\n * (timestamps, createdById, defaults, field-name mapping). Called once per\n * insert row, in input order.\n */\n stampInsertMetadata?: (\n row: Record<string, unknown>,\n uid: string\n ) => Record<string, unknown>;\n /**\n * Optional hook to stamp platform-specific metadata on every update patch.\n */\n stampUpdateMetadata?: (\n patch: Record<string, unknown>,\n uid: string\n ) => Record<string, unknown>;\n /**\n * Optional audit hook. Fires exactly once when `transact` succeeds, with the\n * three op counts. Never fires for empty bulks or rejected validations \u2014\n * matches the \"one audit entry\" contract from `BULK_CRUD_TODO.md` \u00A74.\n */\n audit?: (\n event: string,\n payload: {\n counts: { inserts: number; updates: number; deletes: number };\n }\n ) => void;\n /**\n * Optional rate-limit bookkeeping key. `executeBulk` does NOT perform\n * rate-limit enforcement itself \u2014 the surrounding base-function wrapper\n * already charges one hit at entry. This field is forwarded to `audit()`\n * callers that want to correlate telemetry.\n */\n rateLimitKey?: string;\n}\n\n// =============================================================================\n// Core orchestrator\n// =============================================================================\n\n/**\n * Empty response returned for a no-op bulk. Frozen so accidental mutation\n * from a caller blows up at dev time instead of poisoning the next call.\n */\nconst EMPTY_BULK_RESPONSE: BulkResponse = Object.freeze({\n insertedIds: [],\n updatedIds: [],\n deletedIds: [],\n}) as BulkResponse;\n\n/**\n * Run a bulk CRUD operation against a caller-supplied storage target.\n *\n * **Order of operations** (every step fails loud \u2014 no fallbacks, no partial\n * writes):\n *\n * 1. Parse `ops` with {@link BulkRequestSchema}. Invalid shape \u2192 throws.\n * 2. Collision detection via {@link detectBulkCollisions}. Collision \u2192\n * throws {@link BulkCollisionError}.\n * 3. Empty short-circuit \u2014 if no op carries work, returns a zeroed\n * {@link BulkResponse} without invoking `transact` or `audit`.\n * 4. Per-bucket ACL \u2014 for each populated bucket, asserts the caller's role\n * clears the corresponding `access.{create|update|delete}`. A missing\n * role on a populated bucket is a configuration error and is rejected.\n * 5. Per-row validation \u2014 inserts against `createSchema`, updates against\n * `updateSchema`. The first failure throws a `DoNotDevError` prefixed\n * with `inserts[i]` or `updates[i]` so callers can pinpoint the row.\n * 6. Id minting \u2014 if `mintInsertId` is supplied, every insert gets a fresh\n * id stamped onto its {@link PreparedInsert}. Otherwise `id` is `\"\"` and\n * the storage layer mints its own.\n * 7. Metadata stamping \u2014 `stampInsertMetadata` / `stampUpdateMetadata` run\n * per row / per patch if provided.\n * 8. `transact(prepared)` runs exactly once. Must be atomic. Throws\n * propagate unchanged so the caller's error handler can classify them.\n * 9. Response-shape validation via {@link BulkResponseSchema}. A non-conforming\n * target response throws `DoNotDevError(internal)`.\n * 10. `audit()` fires once with the three op counts.\n *\n * **Not this function's job:** rate-limiting, authentication, HTTP status\n * mapping, target-specific connection pooling, retry policy. All of those\n * belong to the surrounding handler wrapper.\n *\n * @template TRow - Row type (documentation only).\n * @param params - See {@link ExecuteBulkParams}.\n * @returns The validated {@link BulkResponse} from the target.\n *\n * @throws {BulkCollisionError} When the payload contains the same id in\n * two mutually-exclusive buckets.\n * @throws {DoNotDevError} `invalid-argument` on wire-schema failure, per-row\n * validation failure, or collision (wrapped for callers that only rethrow\n * `DoNotDevError`).\n * @throws {DoNotDevError} `permission-denied` when the caller's role cannot\n * satisfy a populated bucket's access requirement.\n * @throws {DoNotDevError} `internal` when the `transact` return value fails\n * {@link BulkResponseSchema}.\n *\n * @example\n * ```typescript\n * import { executeBulk } from '@donotdev/functions/shared';\n * import { BulkResponseSchema } from '@donotdev/core/server';\n *\n * const response = await executeBulk({\n * collection: 'events',\n * ops: req.body,\n * createSchema,\n * updateSchema,\n * access,\n * uid,\n * userRole,\n * mintInsertId: () => crypto.randomUUID(),\n * stampInsertMetadata: (row, uid) => ({\n * ...row,\n * createdById: uid,\n * createdAt: new Date().toISOString(),\n * }),\n * transact: async ({ inserts, updates, deletes }) => {\n * return db.runTransaction(async (tx) => {\n * for (const { id, row } of inserts) tx.set(col.doc(id), row);\n * for (const { id, patch } of updates) tx.update(col.doc(id), patch);\n * for (const id of deletes) tx.delete(col.doc(id));\n * return {\n * insertedIds: inserts.map((i) => i.id),\n * updatedIds: updates.map((u) => u.id),\n * deletedIds: deletes,\n * };\n * });\n * },\n * audit: (event, { counts }) => logger.info(event, counts),\n * });\n * ```\n *\n * @version 0.1.0\n * @since 0.7.0\n * @author AMBROISE PARK Consulting\n */\nexport async function executeBulk<TRow = unknown>(\n params: ExecuteBulkParams<TRow>\n): Promise<BulkResponse> {\n const {\n collection,\n ops,\n createSchema,\n draftCreateSchema,\n updateSchema,\n access,\n uid,\n userRole,\n transact,\n mintInsertId,\n stampInsertMetadata,\n stampUpdateMetadata,\n audit,\n } = params;\n\n // 1. Wire-schema validation. Guarantees the three buckets are arrays of\n // the right shape; per-field entity validation happens in step 5.\n const parsed = v.safeParse(BulkRequestSchema, ops);\n if (!parsed.success) {\n const messages = parsed.issues\n .map(\n (issue) =>\n `${issue.path?.map((p: any) => p.key).join('.') || 'root'}: ${issue.message}`\n )\n .join('; ');\n throw new DoNotDevError(\n `Bulk payload validation failed: ${messages}`,\n 'invalid-argument',\n { details: { validationErrors: parsed.issues } }\n );\n }\n const request: BulkRequest = parsed.output;\n\n const inserts = request.inserts ?? [];\n const updates = request.updates ?? [];\n const deletes = request.deletes ?? [];\n\n // 2. Collision detection. Rejects ambiguous intents BEFORE any further\n // work so a rate-limit hit + HTTP round-trip never buys a partial\n // validation pass only to fail later.\n const collision = detectBulkCollisions(request);\n if (collision.where !== null) {\n throw new BulkCollisionError(collision.collisions, collision.where);\n }\n\n // 3. Empty bulk short-circuit. Per `BULK_CRUD_TODO.md` \u00A78 this never\n // touches the storage layer, never fires audit, and returns a frozen\n // empty response shared across calls (safe \u2014 consumers never mutate).\n if (inserts.length === 0 && updates.length === 0 && deletes.length === 0) {\n return EMPTY_BULK_RESPONSE;\n }\n\n // 4. Per-bucket ACL. The surrounding base-function wrapper already cleared\n // the weakest role; we re-check each populated bucket so mixed-ACL\n // entities reject precisely. A populated bucket with no configured\n // role is a config error \u2014 fail loud rather than silently allow.\n if (inserts.length > 0) {\n if (!access.create) {\n throw new DoNotDevError(\n `Bulk insert requested on ${collection} but no create role is configured`,\n 'permission-denied'\n );\n }\n if (!hasRoleAccess(userRole, access.create)) {\n throw new DoNotDevError(\n `Access denied for bulk insert on ${collection}. Required: ${access.create}, your role: ${userRole}`,\n 'permission-denied'\n );\n }\n }\n if (updates.length > 0) {\n if (!access.update) {\n throw new DoNotDevError(\n `Bulk update requested on ${collection} but no update role is configured`,\n 'permission-denied'\n );\n }\n if (!hasRoleAccess(userRole, access.update)) {\n throw new DoNotDevError(\n `Access denied for bulk update on ${collection}. Required: ${access.update}, your role: ${userRole}`,\n 'permission-denied'\n );\n }\n }\n if (deletes.length > 0) {\n if (!access.delete) {\n throw new DoNotDevError(\n `Bulk delete requested on ${collection} but no delete role is configured`,\n 'permission-denied'\n );\n }\n if (!hasRoleAccess(userRole, access.delete)) {\n throw new DoNotDevError(\n `Access denied for bulk delete on ${collection}. Required: ${access.delete}, your role: ${userRole}`,\n 'permission-denied'\n );\n }\n }\n\n // 5. Per-row validation. First failure wins \u2014 prefixed with its bucket\n // index so callers can point at the offending row.\n for (let i = 0; i < inserts.length; i++) {\n const row = inserts[i]!;\n const rowObj = row as unknown as Record<string, unknown>;\n const status =\n (rowObj.status as string | undefined) ?? DEFAULT_STATUS_VALUE;\n const isDraft = status === 'draft';\n const schemaToUse =\n isDraft && draftCreateSchema ? draftCreateSchema : createSchema;\n // Only inject default `status` when validating against the draft schema.\n // This avoids breaking createSchema-only tests/entities that don't define\n // `status` in their schema shape (valibot's `v.object` is strict by\n // default).\n const payloadForValidation =\n isDraft && draftCreateSchema ? { ...rowObj, status } : rowObj;\n validateRow(payloadForValidation, schemaToUse, `inserts[${i}]`);\n }\n for (let i = 0; i < updates.length; i++) {\n validateRow(updates[i]!.patch, updateSchema, `updates[${i}]`);\n }\n\n // 6. Id minting (if provided). Minting at this layer means `transact`\n // receives stable ids \u2014 crucial for Firestore's retry-able transaction\n // callbacks where the callback body may run more than once.\n const preparedInserts: PreparedInsert[] = inserts.map((row) => {\n const rowRecord = row as unknown as Record<string, unknown>;\n // Always ensure status is present for storage + downstream schema\n // stamping. Validation may have used `draftCreateSchema` to relax\n // required-field enforcement, but storage should still persist a\n // concrete status value.\n const status =\n (rowRecord.status as string | undefined) ?? DEFAULT_STATUS_VALUE;\n const id = mintInsertId ? mintInsertId() : '';\n const stamped = stampInsertMetadata\n ? stampInsertMetadata({ ...rowRecord, status }, uid)\n : ({ ...rowRecord, status } as Record<string, unknown>);\n return { id, row: stamped };\n });\n\n // 7. Update metadata stamping.\n const preparedUpdates: PreparedUpdate[] = updates.map((u) => ({\n id: u.id,\n patch: stampUpdateMetadata\n ? stampUpdateMetadata(u.patch as Record<string, unknown>, uid)\n : (u.patch as Record<string, unknown>),\n }));\n\n // 8. Atomic dispatch. Propagates any `transact` error verbatim \u2014 the\n // surrounding handler wrapper classifies into HTTP / callable codes.\n const raw = await transact({\n inserts: preparedInserts,\n updates: preparedUpdates,\n deletes: [...deletes],\n });\n\n // 9. Response-shape validation at the wire boundary. Drift between a\n // target's return shape and `BulkResponseSchema` would silently corrupt\n // clients that zip ids back onto optimistic entries \u2014 fail loud.\n const responseParse = v.safeParse(BulkResponseSchema, raw);\n if (!responseParse.success) {\n throw new DoNotDevError(\n `Bulk transact() returned an unexpected shape for ${collection}`,\n 'internal'\n );\n }\n\n // 10. One audit entry, counts only (never row ids \u2014 anomaly detection\n // fires on the bulk count per contract \u00A74).\n if (audit) {\n audit(`crud.bulk.${collection}`, {\n counts: {\n inserts: preparedInserts.length,\n updates: preparedUpdates.length,\n deletes: deletes.length,\n },\n });\n }\n\n return responseParse.output;\n}\n\n// =============================================================================\n// Internal helpers\n// =============================================================================\n\n/**\n * Validate a row against a Valibot schema and rethrow a `DoNotDevError`\n * prefixed with the bucket position so callers can point at the offending\n * row. Keeps the hot path free of try/catch overhead when no schema is\n * supplied.\n *\n * @param value - Row or patch to validate.\n * @param schema - Valibot schema.\n * @param locator - Human-readable pointer such as `inserts[2]`.\n *\n * @example\n * ```typescript\n * validateRow(inserts[i], createSchema, `inserts[${i}]`);\n * ```\n *\n * @internal\n */\nfunction validateRow(\n value: unknown,\n schema: BulkRowSchema,\n locator: string\n): void {\n const parsed = v.safeParse(schema, value);\n if (parsed.success) return;\n\n const messages = parsed.issues\n .map(\n (issue) =>\n `${issue.path?.map((p: any) => p.key).join('.') || 'root'}: ${issue.message}`\n )\n .join('; ');\n throw new DoNotDevError(\n `Validation failed on ${locator}: ${messages}`,\n 'invalid-argument',\n { details: { validationErrors: parsed.issues } }\n );\n}\n", "// packages/functions/src/shared/email/createEmailRoute.ts\n\n/**\n * @fileoverview Email Route Handler\n * @description Platform-agnostic handler for email send requests.\n * Validates request, resolves template, renders with locale, sends via provider.\n *\n * @version 0.1.0\n * @since 0.1.0\n * @author AMBROISE PARK Consulting\n */\n\nimport type {\n EmailRouteConfig,\n SendEmailRequest,\n SendEmailResponse,\n} from '@donotdev/core/server';\nimport { validateSendEmailRequest } from '@donotdev/core/server';\n\nimport type { EmailProviderAdapter } from './provider.js';\n\n/**\n * Handle an email send request.\n * Validates input, resolves the template from the registry, renders with locale, and sends.\n *\n * @param request - Email send request (templateId, to, data, locale)\n * @param config - Email route configuration (provider, templates, defaultFrom)\n * @param provider - Email provider adapter (Resend, etc.)\n * @returns Send result with success status and messageId\n *\n * @example\n * ```typescript\n * const result = await handleEmailRequest(\n * { templateId: 'order-confirmation', to: 'user@example.com', data: { orderId: '123' }, locale: 'fr' },\n * emailConfig,\n * resendProvider\n * );\n * ```\n */\nexport async function handleEmailRequest(\n request: SendEmailRequest,\n config: EmailRouteConfig,\n provider: EmailProviderAdapter\n): Promise<SendEmailResponse> {\n // Validate request\n const validation = validateSendEmailRequest(request);\n if (!validation.success) {\n return {\n success: false,\n error: `Invalid email request: ${validation.issues?.map((i) => i.message).join(', ')}`,\n };\n }\n\n // Resolve template\n const template = config.templates[request.templateId];\n if (!template) {\n return {\n success: false,\n error: `Template not found: ${request.templateId}`,\n };\n }\n\n // Render template with locale\n const locale = request.locale || 'fr';\n const subject = template.subject(request.data as any, locale);\n const html = template.html(request.data as any, locale);\n\n // Send via provider\n const result = await provider.send({\n from: request.from || config.defaultFrom,\n to: request.to,\n subject,\n html,\n replyTo: request.replyTo || config.replyTo,\n });\n\n return {\n success: true,\n messageId: result.messageId,\n };\n}\n", "// packages/functions/src/shared/email/resendProvider.ts\n\n/**\n * @fileoverview Resend Email Provider\n * @description Zero-dependency Resend implementation using raw fetch.\n *\n * @version 0.1.0\n * @since 0.1.0\n * @author AMBROISE PARK Consulting\n */\n\nimport type { EmailProviderAdapter } from './provider.js';\n\nconst RESEND_API_URL = 'https://api.resend.com/emails';\n\n/**\n * Create a Resend email provider adapter.\n *\n * @param apiKey - Resend API key\n * @returns EmailProviderAdapter implementation\n *\n * @example\n * ```typescript\n * const provider = createResendProvider(Deno.env.get('RESEND_API_KEY')!);\n * await provider.send({ from: 'noreply@app.com', to: 'user@example.com', subject: 'Hello', html: '<p>Hi</p>' });\n * ```\n */\nexport function createResendProvider(apiKey: string): EmailProviderAdapter {\n if (!apiKey) {\n throw new Error('Resend API key is required');\n }\n\n return {\n async send({ from, to, subject, html, replyTo }) {\n const body: Record<string, string> = { from, to, subject, html };\n if (replyTo) body.reply_to = replyTo;\n\n const response = await fetch(RESEND_API_URL, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => 'Unknown error');\n throw new Error(`Resend API error (${response.status}): ${errorText}`);\n }\n\n const result = await response.json();\n return { messageId: result.id };\n },\n };\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;2IAoBO,SAASA,EAAeC,EAAgB,CAC7C,IAAMC,EAAM,IAAI,KAAK,EAAE,YAAY,EACnC,MAAO,CACL,UAAWA,EACX,UAAWA,EACX,YAAaD,EACb,YAAaA,CACf,CACF,CARgBE,EAAAH,EAAA,kBAmBT,SAASI,EAAeH,EAAgB,CAC7C,MAAO,CACL,UAAW,IAAI,KAAK,EAAE,YAAY,EAClC,YAAaA,CACf,CACF,CALgBE,EAAAC,EAAA,kBC+HhB,IAAMC,EAAoC,OAAO,OAAO,CACtD,YAAa,CAAC,EACd,WAAY,CAAC,EACb,WAAY,CAAC,CACf,CAAC,EAuFD,eAAsBC,EACpBC,EACuB,CACvB,GAAM,CACJ,WAAAC,EACA,IAAAC,EACA,aAAAC,EACA,kBAAAC,EACA,aAAAC,EACA,OAAAC,EACA,IAAAC,EACA,SAAAC,EACA,SAAAC,EACA,aAAAC,EACA,oBAAAC,EACA,oBAAAC,EACA,MAAAC,CACF,EAAIb,EAIEc,EAAWC,EAAUC,EAAmBd,CAAG,EACjD,GAAI,CAACY,EAAO,QAAS,CACnB,IAAMG,EAAWH,EAAO,OACrB,IACEI,GACC,GAAGA,EAAM,MAAM,IAAKC,GAAWA,EAAE,GAAG,EAAE,KAAK,GAAG,GAAK,MAAM,KAAKD,EAAM,OAAO,EAC/E,EACC,KAAK,IAAI,EACZ,MAAM,IAAIE,EACR,mCAAmCH,CAAQ,GAC3C,mBACA,CAAE,QAAS,CAAE,iBAAkBH,EAAO,MAAO,CAAE,CACjD,CACF,CACA,IAAMO,EAAuBP,EAAO,OAE9BQ,EAAUD,EAAQ,SAAW,CAAC,EAC9BE,EAAUF,EAAQ,SAAW,CAAC,EAC9BG,EAAUH,EAAQ,SAAW,CAAC,EAK9BI,EAAYC,EAAqBL,CAAO,EAC9C,GAAII,EAAU,QAAU,KACtB,MAAM,IAAIE,EAAmBF,EAAU,WAAYA,EAAU,KAAK,EAMpE,GAAIH,EAAQ,SAAW,GAAKC,EAAQ,SAAW,GAAKC,EAAQ,SAAW,EACrE,OAAO1B,EAOT,GAAIwB,EAAQ,OAAS,EAAG,CACtB,GAAI,CAAChB,EAAO,OACV,MAAM,IAAIc,EACR,4BAA4BnB,CAAU,oCACtC,mBACF,EAEF,GAAI,CAAC2B,EAAcpB,EAAUF,EAAO,MAAM,EACxC,MAAM,IAAIc,EACR,oCAAoCnB,CAAU,eAAeK,EAAO,MAAM,gBAAgBE,CAAQ,GAClG,mBACF,CAEJ,CACA,GAAIe,EAAQ,OAAS,EAAG,CACtB,GAAI,CAACjB,EAAO,OACV,MAAM,IAAIc,EACR,4BAA4BnB,CAAU,oCACtC,mBACF,EAEF,GAAI,CAAC2B,EAAcpB,EAAUF,EAAO,MAAM,EACxC,MAAM,IAAIc,EACR,oCAAoCnB,CAAU,eAAeK,EAAO,MAAM,gBAAgBE,CAAQ,GAClG,mBACF,CAEJ,CACA,GAAIgB,EAAQ,OAAS,EAAG,CACtB,GAAI,CAAClB,EAAO,OACV,MAAM,IAAIc,EACR,4BAA4BnB,CAAU,oCACtC,mBACF,EAEF,GAAI,CAAC2B,EAAcpB,EAAUF,EAAO,MAAM,EACxC,MAAM,IAAIc,EACR,oCAAoCnB,CAAU,eAAeK,EAAO,MAAM,gBAAgBE,CAAQ,GAClG,mBACF,CAEJ,CAIA,QAASqB,EAAI,EAAGA,EAAIP,EAAQ,OAAQO,IAAK,CAEvC,IAAMC,EADMR,EAAQO,CAAC,EAEfE,EACHD,EAAO,QAAiCE,EACrCC,EAAUF,IAAW,QACrBG,EACJD,GAAW7B,EAAoBA,EAAoBD,EAK/CgC,EACJF,GAAW7B,EAAoB,CAAE,GAAG0B,EAAQ,OAAAC,CAAO,EAAID,EACzDM,EAAYD,EAAsBD,EAAa,WAAWL,CAAC,GAAG,CAChE,CACA,QAASA,EAAI,EAAGA,EAAIN,EAAQ,OAAQM,IAClCO,EAAYb,EAAQM,CAAC,EAAG,MAAOxB,EAAc,WAAWwB,CAAC,GAAG,EAM9D,IAAMQ,EAAoCf,EAAQ,IAAKgB,GAAQ,CAC7D,IAAMC,EAAYD,EAKZP,EACHQ,EAAU,QAAiCP,EACxCQ,EAAK9B,EAAeA,EAAa,EAAI,GACrC+B,EAAU9B,EACZA,EAAoB,CAAE,GAAG4B,EAAW,OAAAR,CAAO,EAAGxB,CAAG,EAChD,CAAE,GAAGgC,EAAW,OAAAR,CAAO,EAC5B,MAAO,CAAE,GAAAS,EAAI,IAAKC,CAAQ,CAC5B,CAAC,EAGKC,EAAoCnB,EAAQ,IAAKoB,IAAO,CAC5D,GAAIA,EAAE,GACN,MAAO/B,EACHA,EAAoB+B,EAAE,MAAkCpC,CAAG,EAC1DoC,EAAE,KACT,EAAE,EAIIC,EAAM,MAAMnC,EAAS,CACzB,QAAS4B,EACT,QAASK,EACT,QAAS,CAAC,GAAGlB,CAAO,CACtB,CAAC,EAKKqB,EAAkB9B,EAAU+B,EAAoBF,CAAG,EACzD,GAAI,CAACC,EAAc,QACjB,MAAM,IAAIzB,EACR,oDAAoDnB,CAAU,GAC9D,UACF,EAKF,OAAIY,GACFA,EAAM,aAAaZ,CAAU,GAAI,CAC/B,OAAQ,CACN,QAASoC,EAAgB,OACzB,QAASK,EAAgB,OACzB,QAASlB,EAAQ,MACnB,CACF,CAAC,EAGIqB,EAAc,MACvB,CAvLsBE,EAAAhD,EAAA,eA8MtB,SAASqC,EACPY,EACAC,EACAC,EACM,CACN,IAAMpC,EAAWC,EAAUkC,EAAQD,CAAK,EACxC,GAAIlC,EAAO,QAAS,OAEpB,IAAMG,EAAWH,EAAO,OACrB,IACEI,GACC,GAAGA,EAAM,MAAM,IAAKC,GAAWA,EAAE,GAAG,EAAE,KAAK,GAAG,GAAK,MAAM,KAAKD,EAAM,OAAO,EAC/E,EACC,KAAK,IAAI,EACZ,MAAM,IAAIE,EACR,wBAAwB8B,CAAO,KAAKjC,CAAQ,GAC5C,mBACA,CAAE,QAAS,CAAE,iBAAkBH,EAAO,MAAO,CAAE,CACjD,CACF,CAnBSiC,EAAAX,EAAA,eCxaT,eAAsBe,EACpBC,EACAC,EACAC,EAC4B,CAE5B,IAAMC,EAAaC,EAAyBJ,CAAO,EACnD,GAAI,CAACG,EAAW,QACd,MAAO,CACL,QAAS,GACT,MAAO,0BAA0BA,EAAW,QAAQ,IAAKE,GAAMA,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC,EACtF,EAIF,IAAMC,EAAWL,EAAO,UAAUD,EAAQ,UAAU,EACpD,GAAI,CAACM,EACH,MAAO,CACL,QAAS,GACT,MAAO,uBAAuBN,EAAQ,UAAU,EAClD,EAIF,IAAMO,EAASP,EAAQ,QAAU,KAC3BQ,EAAUF,EAAS,QAAQN,EAAQ,KAAaO,CAAM,EACtDE,EAAOH,EAAS,KAAKN,EAAQ,KAAaO,CAAM,EAWtD,MAAO,CACL,QAAS,GACT,WAVa,MAAML,EAAS,KAAK,CACjC,KAAMF,EAAQ,MAAQC,EAAO,YAC7B,GAAID,EAAQ,GACZ,QAAAQ,EACA,KAAAC,EACA,QAAST,EAAQ,SAAWC,EAAO,OACrC,CAAC,GAImB,SACpB,CACF,CAzCsBS,EAAAX,EAAA,sBC1BtB,IAAMY,EAAiB,gCAchB,SAASC,EAAqBC,EAAsC,CACzE,GAAI,CAACA,EACH,MAAM,IAAI,MAAM,4BAA4B,EAG9C,MAAO,CACL,MAAM,KAAK,CAAE,KAAAC,EAAM,GAAAC,EAAI,QAAAC,EAAS,KAAAC,EAAM,QAAAC,CAAQ,EAAG,CAC/C,IAAMC,EAA+B,CAAE,KAAAL,EAAM,GAAAC,EAAI,QAAAC,EAAS,KAAAC,CAAK,EAC3DC,IAASC,EAAK,SAAWD,GAE7B,IAAME,EAAW,MAAM,MAAMT,EAAgB,CAC3C,OAAQ,OACR,QAAS,CACP,cAAe,UAAUE,CAAM,GAC/B,eAAgB,kBAClB,EACA,KAAM,KAAK,UAAUM,CAAI,CAC3B,CAAC,EAED,GAAI,CAACC,EAAS,GAAI,CAChB,IAAMC,EAAY,MAAMD,EAAS,KAAK,EAAE,MAAM,IAAM,eAAe,EACnE,MAAM,IAAI,MAAM,qBAAqBA,EAAS,MAAM,MAAMC,CAAS,EAAE,CACvE,CAGA,MAAO,CAAE,WADM,MAAMD,EAAS,KAAK,GACR,EAAG,CAChC,CACF,CACF,CA5BgBE,EAAAV,EAAA",
|
|
6
|
+
"names": ["createMetadata", "userId", "now", "__name", "updateMetadata", "EMPTY_BULK_RESPONSE", "executeBulk", "params", "collection", "ops", "createSchema", "draftCreateSchema", "updateSchema", "access", "uid", "userRole", "transact", "mintInsertId", "stampInsertMetadata", "stampUpdateMetadata", "audit", "parsed", "safeParse", "BulkRequestSchema", "messages", "issue", "p", "DoNotDevError", "request", "inserts", "updates", "deletes", "collision", "detectBulkCollisions", "BulkCollisionError", "hasRoleAccess", "i", "rowObj", "status", "DEFAULT_STATUS_VALUE", "isDraft", "schemaToUse", "payloadForValidation", "validateRow", "preparedInserts", "row", "rowRecord", "id", "stamped", "preparedUpdates", "u", "raw", "responseParse", "BulkResponseSchema", "__name", "value", "schema", "locator", "handleEmailRequest", "request", "config", "provider", "validation", "validateSendEmailRequest", "i", "template", "locale", "subject", "html", "__name", "RESEND_API_URL", "createResendProvider", "apiKey", "from", "to", "subject", "html", "replyTo", "body", "response", "errorText", "__name"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
4
|
+
import { Buffer } from 'node:buffer';
|
|
5
|
+
import process from 'node:process';
|
|
6
|
+
|
|
7
|
+
const require = __createRequire(import.meta.url);
|
|
8
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
9
|
+
const __dirname = dirname(__filename);
|
|
10
|
+
|
|
11
|
+
if (typeof globalThis !== 'undefined') {
|
|
12
|
+
globalThis.require = require;
|
|
13
|
+
globalThis.__filename = __filename;
|
|
14
|
+
globalThis.__dirname = __dirname;
|
|
15
|
+
globalThis.Buffer = Buffer;
|
|
16
|
+
globalThis.process = process;
|
|
17
|
+
if (typeof global === 'undefined') {
|
|
18
|
+
globalThis.global = globalThis;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
import{a as i}from"./chunk-AYY7UXNI.js";var ue={ALREADY_EXISTS:"already-exists",CANCELLED:"cancelled",DEADLINE_EXCEEDED:"deadline-exceeded",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",INTERNAL:"internal",INVALID_ARGUMENT:"invalid-argument",NOT_FOUND:"not-found",PERMISSION_DENIED:"permission-denied",RATE_LIMIT_EXCEEDED:"rate-limit-exceeded",TIMEOUT:"timeout",UNAUTHENTICATED:"unauthenticated",UNAVAILABLE:"unavailable",UNIMPLEMENTED:"unimplemented",UNKNOWN:"unknown",VALIDATION_FAILED:"validation-failed"};var ge={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},Re={[ue.PERMISSION_DENIED]:{type:ge.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[ue.NOT_FOUND]:{type:ge.NOT_FOUND,message:"The requested resource was not found"},[ue.ALREADY_EXISTS]:{type:ge.ALREADY_EXISTS,message:"The resource already exists"},[ue.INVALID_ARGUMENT]:{type:ge.VALIDATION_ERROR,message:"Invalid argument provided"}};var P=class e extends Error{static{i(this,"DoNotDevError")}code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,n=ue.INTERNAL,o){super(t),Object.setPrototypeOf(this,e.prototype),this.code=n,this.details=o?.details,this.source=o?.source,this.originalError=o?.originalError,this.context=o?.context,this.displayable=o?.displayable??!0,this.userMessageProvided=o?.userMessageProvided,this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toString(){return`${this.name} [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,source:this.source,originalError:this.originalError,context:this.context,displayable:this.displayable,userMessageProvided:this.userMessageProvided}}};var j={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},ve={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},$n={[j.ANTHROPIC]:{default:"claude-sonnet-4-6",models:["claude-sonnet-4-6","claude-sonnet-4-20250514","claude-haiku-4-5-20251001","claude-opus-4-6","claude-opus-4-20250514"]},[j.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[j.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}};var Gn={FAST:{id:"fast",defaultModel:"claude-haiku-4-5-20251001"},STANDARD:{id:"standard",defaultModel:"claude-sonnet-4-6"},PREMIUM:{id:"premium",defaultModel:"claude-opus-4-6"}},Hn=4,Wn={"claude-sonnet-4-6":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-haiku-4-5-20251001":{promptPer1M:.8,completionPer1M:4,currency:"usd"},"claude-opus-4-6":{promptPer1M:15,completionPer1M:75,currency:"usd"},"claude-sonnet-4-20250514":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-opus-4-20250514":{promptPer1M:15,completionPer1M:75,currency:"usd"},"gpt-4o":{promptPer1M:2.5,completionPer1M:10,currency:"usd"},"gpt-4o-mini":{promptPer1M:.15,completionPer1M:.6,currency:"usd"},"gpt-4.1":{promptPer1M:2,completionPer1M:8,currency:"usd"},"gpt-4.1-mini":{promptPer1M:.4,completionPer1M:1.6,currency:"usd"},"o3-mini":{promptPer1M:1.1,completionPer1M:4.4,currency:"usd"},"gemini-2.0-flash":{promptPer1M:.1,completionPer1M:.4,currency:"usd"},"gemini-2.5-pro":{promptPer1M:1.25,completionPer1M:10,currency:"usd"},"gemini-2.5-flash":{promptPer1M:.15,completionPer1M:.6,currency:"usd"}};var he,Tt={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function Ce(e){return!e&&!he?Tt:{lang:e?.lang??he?.lang,message:e?.message,abortEarly:e?.abortEarly??he?.abortEarly,abortPipeEarly:e?.abortPipeEarly??he?.abortPipeEarly}}i(Ce,"getGlobalConfig");var It;function Rt(e){return It?.get(e)}i(Rt,"getGlobalMessage");var Ct;function wt(e){return Ct?.get(e)}i(wt,"getSchemaMessage");var Ot;function Pt(e,t){return Ot?.get(e)?.get(t)}i(Pt,"getSpecificMessage");function X(e){let t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}i(X,"_stringify");function S(e,t,n,o,c){let u=c&&"input"in c?c.input:n.value,l=c?.expected??e.expects??null,g=c?.received??X(u),m={kind:e.kind,type:e.type,input:u,expected:l,received:g,message:`Invalid ${t}: ${l?`Expected ${l} but r`:"R"}eceived ${g}`,requirement:e.requirement,path:c?.path,issues:c?.issues,lang:o.lang,abortEarly:o.abortEarly,abortPipeEarly:o.abortPipeEarly},h=e.kind==="schema",d=c?.message??e.message??Pt(e.reference,m.lang)??(h?wt(m.lang):null)??o.message??Rt(m.lang);d!==void 0&&(m.message=typeof d=="function"?d(m):d),h&&(n.typed=!1),n.issues?n.issues.push(m):n.issues=[m]}i(S,"_addIssue");function Dt(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}i(Dt,"_isSameValueZero");function Ye(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}i(Ye,"_isValidObjectKey");function we(e,t){let n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??"never"}i(we,"_joinExpects");function R(e){return e["~standard"]={version:1,vendor:"valibot",validate:i(t=>e["~run"]({value:t},Ce()),"validate")},e}i(R,"_standardSchema");var be=class extends Error{static{i(this,"ValiError")}constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function zn(e){return e instanceof be}i(zn,"isValiError");var _t=/^[\w+-]+(?:\.[\w+-]+)*@[\da-zA-Z]+(?:[.-][\da-zA-Z]+)*\.[a-zA-Z]{2,}$/u,Yn=new RegExp("^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|(?![\\p{Emoji_Modifier_Base}\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}))*)+$","u");var Nt=/^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])[T ](?:0\d|1\d|2[0-3])(?::[0-5]\d){2}(?:\.\d{1,9})?(?:Z| ?[+-](?:0\d|1\d|2[0-3])(?::?[0-5]\d)?)$/u;function le(e,t){return{kind:"validation",type:"check",reference:le,async:!1,expects:null,requirement:e,message:t,"~run"(n,o){return n.typed&&!this.requirement(n.value)&&S(this,"input",n,o),n}}}i(le,"check");function L(e){return{kind:"validation",type:"email",reference:L,expects:null,async:!1,requirement:_t,message:e,"~run"(t,n){return t.typed&&!this.requirement.test(t.value)&&S(this,"email",t,n),t}}}i(L,"email");function B(e){return{kind:"validation",type:"integer",reference:B,async:!1,expects:null,requirement:Number.isInteger,message:e,"~run"(t,n){return t.typed&&!this.requirement(t.value)&&S(this,"integer",t,n),t}}}i(B,"integer");function V(e){return{kind:"validation",type:"iso_timestamp",reference:V,async:!1,expects:null,requirement:Nt,message:e,"~run"(t,n){return t.typed&&!this.requirement.test(t.value)&&S(this,"timestamp",t,n),t}}}i(V,"isoTimestamp");function ne(e,t){return{kind:"validation",type:"length",reference:ne,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length!==this.requirement&&S(this,"length",n,o,{received:`${n.value.length}`}),n}}}i(ne,"length");function $(e,t){return{kind:"validation",type:"max_length",reference:$,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length>this.requirement&&S(this,"length",n,o,{received:`${n.value.length}`}),n}}}i($,"maxLength");function q(e,t){return{kind:"validation",type:"max_value",reference:q,async:!1,expects:`<=${e instanceof Date?e.toJSON():X(e)}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!(n.value<=this.requirement)&&S(this,"value",n,o,{received:n.value instanceof Date?n.value.toJSON():X(n.value)}),n}}}i(q,"maxValue");function f(e,t){return{kind:"validation",type:"min_length",reference:f,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&n.value.length<this.requirement&&S(this,"length",n,o,{received:`${n.value.length}`}),n}}}i(f,"minLength");function C(e,t){return{kind:"validation",type:"min_value",reference:C,async:!1,expects:`>=${e instanceof Date?e.toJSON():X(e)}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!(n.value>=this.requirement)&&S(this,"value",n,o,{received:n.value instanceof Date?n.value.toJSON():X(n.value)}),n}}}i(C,"minValue");function Oe(e){return{kind:"transformation",type:"raw_transform",reference:Oe,async:!1,"~run"(t,n){let o=e({dataset:t,config:n,addIssue:i(c=>S(this,c?.label??"input",t,n,c),"addIssue"),NEVER:null});return t.issues?t.typed=!1:t.value=o,t}}}i(Oe,"rawTransform");function re(e,t){return{kind:"validation",type:"regex",reference:re,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(n,o){return n.typed&&!this.requirement.test(n.value)&&S(this,"format",n,o),n}}}i(re,"regex");function Ft(e){return{kind:"transformation",type:"transform",reference:Ft,async:!1,operation:e,"~run"(t){return t.value=this.operation(t.value),t}}}i(Ft,"transform");function N(e){return{kind:"validation",type:"url",reference:N,async:!1,expects:null,requirement(t){try{return URL.canParse?URL.canParse(t):(new URL(t),!0)}catch{return!1}},message:e,"~run"(t,n){return t.typed&&!this.requirement(t.value)&&S(this,"URL",t,n),t}}}i(N,"url");var Ut={abortEarly:!0};function Xe(e,t,n){return typeof e.fallback=="function"?e.fallback(t,n):e.fallback}i(Xe,"getFallback");function ce(e,t,n){return typeof e.default=="function"?e.default(t,n):e.default}i(ce,"getDefault");function Z(){return R({kind:"schema",type:"any",reference:Z,expects:"any",async:!1,"~run"(e){return e.typed=!0,e}})}i(Z,"any");function v(e,t){return R({kind:"schema",type:"array",reference:v,expects:"Array",async:!1,item:e,message:t,"~run"(n,o){let c=n.value;if(Array.isArray(c)){n.typed=!0,n.value=[];for(let u=0;u<c.length;u++){let l=c[u],g=this.item["~run"]({value:l},o);if(g.issues){let m={type:"array",origin:"value",input:c,key:u,value:l};for(let h of g.issues)h.path?h.path.unshift(m):h.path=[m],n.issues?.push(h);if(n.issues||(n.issues=g.issues),o.abortEarly){n.typed=!1;break}}g.typed||(n.typed=!1),n.value.push(g.value)}}else S(this,"type",n,o);return n}})}i(v,"array");function k(e){return R({kind:"schema",type:"boolean",reference:k,expects:"boolean",async:!1,message:e,"~run"(t,n){return typeof t.value=="boolean"?t.typed=!0:S(this,"type",t,n),t}})}i(k,"boolean");function Pe(e,t){return R({kind:"schema",type:"custom",reference:Pe,expects:"unknown",async:!1,check:e,message:t,"~run"(n,o){return this.check(n.value)?n.typed=!0:S(this,"type",n,o),n}})}i(Pe,"custom");function De(e){return R({kind:"schema",type:"lazy",reference:De,expects:"unknown",async:!1,getter:e,"~run"(t,n){return this.getter(t.value)["~run"](t,n)}})}i(De,"lazy");function F(e,t){return R({kind:"schema",type:"literal",reference:F,expects:X(e),async:!1,literal:e,message:t,"~run"(n,o){return Dt(n.value,this.literal)?n.typed=!0:S(this,"type",n,o),n}})}i(F,"literal");function _e(e,t){return R({kind:"schema",type:"loose_object",reference:_e,expects:"Object",async:!1,entries:e,message:t,"~run"(n,o){let c=n.value;if(c&&typeof c=="object"){n.typed=!0,n.value={};for(let u in this.entries){let l=this.entries[u];if(u in c||(l.type==="exact_optional"||l.type==="optional"||l.type==="nullish")&&l.default!==void 0){let g=u in c?c[u]:ce(l),m=l["~run"]({value:g},o);if(m.issues){let h={type:"object",origin:"value",input:c,key:u,value:g};for(let d of m.issues)d.path?d.path.unshift(h):d.path=[h],n.issues?.push(d);if(n.issues||(n.issues=m.issues),o.abortEarly){n.typed=!1;break}}m.typed||(n.typed=!1),n.value[u]=m.value}else if(l.fallback!==void 0)n.value[u]=Xe(l);else if(l.type!=="exact_optional"&&l.type!=="optional"&&l.type!=="nullish"&&(S(this,"key",n,o,{input:void 0,expected:`"${u}"`,path:[{type:"object",origin:"key",input:c,key:u,value:c[u]}]}),o.abortEarly))break}if(!n.issues||!o.abortEarly)for(let u in c)Ye(c,u)&&!Object.prototype.hasOwnProperty.call(this.entries,u)&&(n.value[u]=c[u])}else S(this,"type",n,o);return n}})}i(_e,"looseObject");function Ne(e){return R({kind:"schema",type:"never",reference:Ne,expects:"never",async:!1,message:e,"~run"(t,n){return S(this,"type",t,n),t}})}i(Ne,"never");function D(e,t){return R({kind:"schema",type:"nullable",reference:D,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,"~run"(n,o){return n.value===null&&(this.default!==void 0&&(n.value=ce(this,n,o)),n.value===null)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}i(D,"nullable");function U(e,t){return R({kind:"schema",type:"nullish",reference:U,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,default:t,"~run"(n,o){return(n.value===null||n.value===void 0)&&(this.default!==void 0&&(n.value=ce(this,n,o)),n.value===null||n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}i(U,"nullish");function E(e){return R({kind:"schema",type:"number",reference:E,expects:"number",async:!1,message:e,"~run"(t,n){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:S(this,"type",t,n),t}})}i(E,"number");function p(e,t){return R({kind:"schema",type:"object",reference:p,expects:"Object",async:!1,entries:e,message:t,"~run"(n,o){let c=n.value;if(c&&typeof c=="object"){n.typed=!0,n.value={};for(let u in this.entries){let l=this.entries[u];if(u in c||(l.type==="exact_optional"||l.type==="optional"||l.type==="nullish")&&l.default!==void 0){let g=u in c?c[u]:ce(l),m=l["~run"]({value:g},o);if(m.issues){let h={type:"object",origin:"value",input:c,key:u,value:g};for(let d of m.issues)d.path?d.path.unshift(h):d.path=[h],n.issues?.push(d);if(n.issues||(n.issues=m.issues),o.abortEarly){n.typed=!1;break}}m.typed||(n.typed=!1),n.value[u]=m.value}else if(l.fallback!==void 0)n.value[u]=Xe(l);else if(l.type!=="exact_optional"&&l.type!=="optional"&&l.type!=="nullish"&&(S(this,"key",n,o,{input:void 0,expected:`"${u}"`,path:[{type:"object",origin:"key",input:c,key:u,value:c[u]}]}),o.abortEarly))break}}else S(this,"type",n,o);return n}})}i(p,"object");function s(e,t){return R({kind:"schema",type:"optional",reference:s,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,"~run"(n,o){return n.value===void 0&&(this.default!==void 0&&(n.value=ce(this,n,o)),n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,o)}})}i(s,"optional");function b(e,t){return R({kind:"schema",type:"picklist",reference:b,expects:we(e.map(X),"|"),async:!1,options:e,message:t,"~run"(n,o){return this.options.includes(n.value)?n.typed=!0:S(this,"type",n,o),n}})}i(b,"picklist");function x(e,t,n){return R({kind:"schema",type:"record",reference:x,expects:"Object",async:!1,key:e,value:t,message:n,"~run"(o,c){let u=o.value;if(u&&typeof u=="object"){o.typed=!0,o.value={};for(let l in u)if(Ye(u,l)){let g=u[l],m=this.key["~run"]({value:l},c);if(m.issues){let d={type:"object",origin:"key",input:u,key:l,value:g};for(let w of m.issues)w.path=[d],o.issues?.push(w);if(o.issues||(o.issues=m.issues),c.abortEarly){o.typed=!1;break}}let h=this.value["~run"]({value:g},c);if(h.issues){let d={type:"object",origin:"value",input:u,key:l,value:g};for(let w of h.issues)w.path?w.path.unshift(d):w.path=[d],o.issues?.push(w);if(o.issues||(o.issues=h.issues),c.abortEarly){o.typed=!1;break}}(!m.typed||!h.typed)&&(o.typed=!1),m.typed&&(o.value[m.value]=h.value)}}else S(this,"type",o,c);return o}})}i(x,"record");function r(e){return R({kind:"schema",type:"string",reference:r,expects:"string",async:!1,message:e,"~run"(t,n){return typeof t.value=="string"?t.typed=!0:S(this,"type",t,n),t}})}i(r,"string");function Mt(e,t){return R({kind:"schema",type:"tuple",reference:Mt,expects:"Array",async:!1,items:e,message:t,"~run"(n,o){let c=n.value;if(Array.isArray(c)){n.typed=!0,n.value=[];for(let u=0;u<this.items.length;u++){let l=c[u],g=this.items[u]["~run"]({value:l},o);if(g.issues){let m={type:"array",origin:"value",input:c,key:u,value:l};for(let h of g.issues)h.path?h.path.unshift(m):h.path=[m],n.issues?.push(h);if(n.issues||(n.issues=g.issues),o.abortEarly){n.typed=!1;break}}g.typed||(n.typed=!1),n.value.push(g.value)}}else S(this,"type",n,o);return n}})}i(Mt,"tuple");function ze(e){let t;if(e)for(let n of e)if(t)for(let o of n.issues)t.push(o);else t=n.issues;return t}i(ze,"_subIssues");function J(e,t){return R({kind:"schema",type:"union",reference:J,expects:we(e.map(n=>n.expects),"|"),async:!1,options:e,message:t,"~run"(n,o){let c,u,l;for(let g of this.options){let m=g["~run"]({value:n.value},o);if(m.typed)if(m.issues)u?u.push(m):u=[m];else{c=m;break}else l?l.push(m):l=[m]}if(c)return c;if(u){if(u.length===1)return u[0];S(this,"type",n,o,{issues:ze(u)}),n.typed=!0}else{if(l?.length===1)return l[0];S(this,"type",n,o,{issues:ze(l)})}return n}})}i(J,"union");function _(){return R({kind:"schema",type:"unknown",reference:_,expects:"unknown",async:!1,"~run"(e){return e.typed=!0,e}})}i(_,"unknown");function pe(e,t,n){return R({kind:"schema",type:"variant",reference:pe,expects:"Object",async:!1,key:e,options:t,message:n,"~run"(o,c){let u=o.value;if(u&&typeof u=="object"){let l,g=0,m=this.key,h=[],d=i((w,O)=>{for(let G of w.options){if(G.type==="variant")d(G,new Set(O).add(G.key));else{let ye=!0,te=0;for(let A of O){let I=G.entries[A];if(A in u?I["~run"]({typed:!1,value:u[A]},Ut).issues:I.type!=="exact_optional"&&I.type!=="optional"&&I.type!=="nullish"){ye=!1,m!==A&&(g<te||g===te&&A in u&&!(m in u))&&(g=te,m=A,h=[]),m===A&&h.push(G.entries[A].expects);break}te++}if(ye){let A=G["~run"]({value:u},c);(!l||!l.typed&&A.typed)&&(l=A)}}if(l&&!l.issues)break}},"parseOptions");if(d(this,new Set([this.key])),l)return l;S(this,"type",o,c,{input:u[m],expected:we(h,"|"),path:[{type:"object",origin:"value",input:u,key:m,value:u[m]}]})}else S(this,"type",o,c);return o}})}i(pe,"variant");function Ze(e,t,n){let o=e["~run"]({value:t},Ce(n));if(o.issues)throw new be(o.issues);return o.value}i(Ze,"parse");function a(...e){return R({...e[0],pipe:e,"~run"(t,n){for(let o of e)if(o.kind!=="metadata"){if(t.issues&&(o.kind==="schema"||o.kind==="transformation")){t.typed=!1;break}(!t.issues||!n.abortEarly&&!n.abortPipeEarly)&&(t=o["~run"](t,n))}return t}})}i(a,"pipe");function W(e,t,n){let o=e["~run"]({value:t},Ce(n));return{typed:o.typed,success:!o.issues,output:o.value,issues:o.issues}}i(W,"safeParse");var Je=p({role:b([ve.USER,ve.ASSISTANT,ve.SYSTEM]),content:a(r(),f(1)),id:s(r()),createdAt:s(r())}),Fe=De(()=>p({type:b(["string","number","boolean","array","object"]),description:s(r()),enum:s(v(r())),items:s(Fe),properties:s(x(r(),Fe)),required:s(v(r()))})),Lt=p({description:a(r(),f(1)),parameters:p({type:F("object"),properties:x(r(),Fe),required:s(v(r()))})}),Bt=p({id:r(),name:r(),args:x(r(),_())}),qt=p({messages:a(v(Je),f(1)),provider:s(b([j.ANTHROPIC,j.OPENAI,j.GOOGLE])),model:s(r()),maxTokens:s(a(E(),B(),C(1))),temperature:s(a(E(),C(0),q(2))),systemPrompt:s(r()),stream:s(k()),tools:s(x(r(),Lt))}),jt=p({promptTokens:E(),completionTokens:E(),totalTokens:E()}),Qn=p({message:Je,usage:s(jt),finishReason:s(r()),toolCalls:s(v(Bt))}),er=p({provider:b([j.ANTHROPIC,j.OPENAI,j.GOOGLE]),model:s(r()),maxTokens:s(a(E(),B(),C(1))),temperature:s(a(E(),C(0),q(2))),systemPrompt:s(r())});function tr(e){return W(qt,e)}i(tr,"validateAIChatRequest");var K={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};var Qe={FREE:"free",PRO:"pro",PREMIUM:"premium"};var et={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};var tt={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"};var de={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};var Ue={PAYMENT:"payment",SUBSCRIPTION:"subscription"};var cr={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};var nt=100,Vt=p({productId:a(r(),f(1),$(200)),quantity:a(E(),B(),C(1),q(1e4))}),mr=a(p({billingConfigKey:s(a(r(),f(1))),lineItems:s(a(v(Vt),f(1,"At least one line item is required"),$(nt,`At most ${nt} line items`))),successUrl:a(r(),N()),cancelUrl:a(r(),N()),customerEmail:s(a(r(),L())),metadata:s(x(r(),r())),allowPromotionCodes:s(k()),userId:s(r()),productId:s(r()),priceId:s(r()),unitAmount:s(a(E(),B(),C(1))),productName:s(a(r(),f(1))),currency:s(a(r(),ne(3,"Currency must be 3-letter ISO code"))),userEmail:s(a(r(),L())),mode:s(b([Ue.PAYMENT,Ue.SUBSCRIPTION]))}),Oe(({dataset:e,addIssue:t,NEVER:n})=>{let o=e.value,c=o.billingConfigKey||o.metadata?.billingConfigKey;return c?{...o,billingConfigKey:c,lineItems:o.lineItems??[{productId:c,quantity:1}]}:(t({message:"billingConfigKey is required"}),n)})),yr=p({sessionId:r(),sessionUrl:D(a(r(),N()))}),gr=p({userId:r(),tier:r(),status:b(Object.values(de)),subscriptionId:D(r()),customerId:r(),subscriptionEnd:D(a(r(),V())),cancelAtPeriodEnd:k(),updatedAt:a(r(),V())}),vr=p({tier:r(),subscriptionId:D(r()),customerId:r(),status:b(Object.values(de)),subscriptionEnd:D(a(r(),V())),cancelAtPeriodEnd:k(),updatedAt:a(r(),V()),isDefault:s(k())}),hr=p({id:r(),type:r(),data:p({object:Z()}),created:a(r(),V())}),br=_e({userId:s(r()),firebaseUid:s(r()),productType:s(r())});var $t=p({type:F("StripePayment"),name:a(r(),f(1,"Product name is required")),description:s(r()),price:r(),currency:s(a(r(),ne(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:s(a(r(),f(1,"Stripe price ID is required"))),unitAmount:s(a(E(),B(),C(1))),productName:s(a(r(),f(1))),maxUnitAmount:s(a(E(),B(),C(1))),tier:a(r(),f(1,"Tier is required")),duration:a(r(),f(1,"Duration is required")),allowPromotionCodes:s(k()),metadata:s(x(r(),r()))}),Gt=p({type:F("StripeSubscription"),name:a(r(),f(1,"Product name is required")),description:s(r()),price:r(),currency:s(a(r(),ne(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:a(r(),f(1,"Stripe price ID is required")),tier:a(r(),f(1,"Tier is required")),duration:b(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:s(k()),metadata:s(x(r(),r()))}),Ht=pe("type",[$t,Gt]),Er=x(r(),Ht),xr=x(r(),p({name:r(),price:r(),currency:r(),description:s(r()),features:s(v(r())),priceId:s(r()),unitAmount:s(E()),productName:s(r()),allowPromotionCodes:s(k())})),rt={name:r(),price:E(),currency:r(),priceId:s(r()),unitAmount:s(a(E(),B(),C(1))),productName:s(a(r(),f(1))),maxUnitAmount:s(a(E(),B(),C(1))),tier:r(),duration:r(),description:s(r()),metadata:s(x(r(),r())),allowPromotionCodes:s(k())},Wt=pe("mode",[p({mode:F("manual"),taxRateIds:a(v(a(r(),f(1))),f(1))}),p({mode:F("automatic")})]),it=5,Kt=p({allowedCountries:a(v(a(r(),re(/^[A-Z]{2}$/,"allowedCountries: uppercase ISO 3166-1 alpha-2 code expected (e.g. FR)"))),f(1)),shippingRateIds:s(a(v(a(r(),f(1))),$(it,`shippingRateIds: at most ${it} (Stripe limit)`)))}),zt=p({type:F("StripeOrder"),name:r(),currency:a(r(),ne(3)),description:s(r()),metadata:s(x(r(),r())),allowPromotionCodes:s(k()),tax:Wt,taxIdCollection:b(["disabled","optional","required"]),billingAddressCollection:b(["auto","required"]),shipping:s(Kt),customerCreation:b(["always","if_required"]),invoiceCreation:k(),paymentMethodConfiguration:s(a(r(),f(1)))}),Yt=x(r(),pe("type",[p({type:F("StripePayment"),...rt}),p({type:F("StripeSubscription"),...rt}),zt]));function Sr(e){return Ze(Yt,e)}i(Sr,"validateStripeBackConfig");var Pr=p({id:r(),email:s(D(a(r(),L()))),displayName:s(D(r())),photoURL:s(D(a(r(),N()))),emailVerified:s(k()),lastLoginAt:s(r()),providerData:s(v(p({providerId:r(),uid:r(),email:s(D(a(r(),L()))),displayName:s(D(r())),photoURL:s(D(a(r(),N()))),phoneNumber:s(D(r()))}))),role:s(b(Object.values(K))),customClaims:s(x(r(),Z()))}),Xt=p({userId:r(),tier:b(Object.values(Qe)),status:b(Object.values(de)),isActive:s(k()),features:s(v(r())),subscriptionId:D(r()),customerId:r(),subscriptionEnd:D(a(r(),V())),cancelAtPeriodEnd:k(),updatedAt:a(r(),V())}),Dr=p({role:s(b(Object.values(K))),subscription:s(Xt),features:s(v(b(Object.values(et)))),permissions:s(v(b(Object.values(tt)))),githubAccess:s(p({username:s(r()),teamAccess:s(v(r())),repoAccess:s(v(r()))}))});var Me={TRUE:!0,FALSE:!1,USER:"user",ADMIN:"admin",SUPER:"super",CREATE_ONLY:"create-only",GENERATED:"generated",COMPUTED:"computed"};var Q={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"};var Hr={EQ:Q.EQ,NEQ:Q.NEQ,LT:Q.LT,LTE:Q.LTE,GT:Q.GT,GTE:Q.GTE};var ot=class extends Error{static{i(this,"BulkCollisionError")}collidingIds;where;constructor(t,n){super(`BulkCollisionError: ${t.length} id(s) appear in both "${n.replace("-",'" and "')}" \u2014 ${t.join(", ")}`),this.name="BulkCollisionError",this.collidingIds=t,this.where=n}};var Qr=p({collection:a(r(),f(1,"Collection name is required")),data:x(r(),_()),idempotencyKey:s(r())}),ei=p({collection:a(r(),f(1,"Collection name is required")),id:a(r(),f(1,"Entity ID is required"))}),ti=p({collection:a(r(),f(1,"Collection name is required")),id:a(r(),f(1,"Entity ID is required")),data:x(r(),_()),merge:s(k(),!1)}),ni=p({collection:a(r(),f(1,"Collection name is required")),id:a(r(),f(1,"Entity ID is required"))}),ri=p({collection:a(r(),f(1,"Collection name is required")),limit:s(a(E(),C(1),q(1e3)),1e3),offset:s(a(E(),C(0)),0),orderBy:s(r()),orderDirection:s(b(["asc","desc"]),"desc"),where:s(v(p({field:r(),operator:b(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:_()})))});var Jt=p({templateId:a(r(),f(1)),to:a(r(),L()),data:x(r(),_()),locale:s(a(r(),f(2),$(5)),"fr"),from:s(r()),replyTo:s(r())}),yi=p({success:k(),messageId:s(r()),error:s(r())});function gi(e){return W(Jt,e)}i(gi,"validateSendEmailRequest");var st=["pull","push","admin","maintain","triage"];var Le=p({owner:a(r(),f(1,"Repository owner is required")),repo:a(r(),f(1,"Repository name is required"))}),Qt=b([...st]),to=p({userId:a(r(),f(1,"User ID is required")),githubUsername:a(r(),f(1,"GitHub username is required")),repoConfig:Le,permission:s(Qt,"push"),customClaims:s(x(r(),Z()))}),no=p({userId:a(r(),f(1,"User ID is required")),githubUsername:a(r(),f(1,"GitHub username is required")),repoConfig:Le}),ro=p({userId:a(r(),f(1,"User ID is required")),githubUsername:a(r(),f(1,"GitHub username is required")),repoConfig:Le}),io=p({provider:r(),purpose:b(["authentication","api-access"]),code:a(r(),f(1,"Authorization code is required")),redirectUri:a(r(),N("Valid redirect URI is required")),codeVerifier:s(r()),state:s(r()),instance:s(a(r(),N()))}),oo=p({provider:r(),refreshToken:a(r(),f(1,"Refresh token is required")),redirectUri:a(r(),N("Valid redirect URI is required"))}),so=p({provider:r()}),ao=p({userId:a(r(),f(1,"User ID is required"))});var at=p({name:r(),color:r(),icon:r(),customParameters:s(x(r(),r())),button:p({backgroundColor:r(),textColor:r(),borderColor:r(),hoverBackgroundColor:r(),focusOutlineColor:r(),fontWeight:s(r(),"500"),textKey:s(r())})}),en=p({...at.entries,type:b(["auth","both"]),scopes:s(v(r())),firebaseProviderId:s(r())}),Ee=J([F(""),a(r(),N())]),tn=p({authUrl:Ee,tokenUrl:Ee,profileUrl:Ee,revokeUrl:s(Ee)}),nn=p({authentication:s(v(r())),"api-access":v(r())}),rn=s(p({pkce:s(k(),!1),codeChallengeMethod:s(b(["S256","plain"]),"S256")})),on=p({...at.entries,type:b(["oauth","both"]),scopes:nn,endpoints:tn,capabilities:rn});var yo={google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:{authentication:["openid","profile","email"],"api-access":["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/gmail.readonly"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/oauth2/v3/userinfo",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:{authentication:["read:user","user:email"],"api-access":["repo","user","read:org","gist","notifications"]},endpoints:{authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",profileUrl:"https://api.github.com/user",revokeUrl:"https://api.github.com/applications/CLIENT_ID/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:{authentication:["identify","email"],"api-access":["guilds","guilds.members.read","bot","messages.read"]},endpoints:{authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",profileUrl:"https://discord.com/api/users/@me",revokeUrl:"https://discord.com/api/oauth2/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:{authentication:["user-read-email","user-read-private"],"api-access":["user-read-playback-state","user-modify-playback-state","user-read-currently-playing","playlist-read-private","playlist-modify-public","user-library-read"]},endpoints:{authUrl:"https://accounts.spotify.com/authorize",tokenUrl:"https://accounts.spotify.com/api/token",profileUrl:"https://api.spotify.com/v1/me",revokeUrl:"https://accounts.spotify.com/api/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:{authentication:["user:read:email"],"api-access":["channel:read:subscriptions","bits:read","channel:manage:broadcast","channel:read:stream_key","user:read:follows"]},endpoints:{authUrl:"https://id.twitch.tv/oauth2/authorize",tokenUrl:"https://id.twitch.tv/oauth2/token",profileUrl:"https://api.twitch.tv/helix/users",revokeUrl:"https://id.twitch.tv/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:{authentication:["identity"],"api-access":["read","submit","vote","mysubreddits","subscribe"]},endpoints:{authUrl:"https://www.reddit.com/api/v1/authorize",tokenUrl:"https://www.reddit.com/api/v1/access_token",profileUrl:"https://oauth.reddit.com/api/v1/me",revokeUrl:"https://www.reddit.com/api/v1/revoke_token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"oauth",scopes:{"api-access":["r_liteprofile","r_emailaddress","w_member_social","r_organization_social"]},endpoints:{authUrl:"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:"https://www.linkedin.com/oauth/v2/accessToken",profileUrl:"https://api.linkedin.com/v2/me",revokeUrl:"https://www.linkedin.com/oauth/v2/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},slack:{name:"Slack",color:"#E01E5A",icon:"slack",type:"oauth",scopes:{"api-access":["channels:read","chat:write","users:read","files:read","im:read"]},endpoints:{authUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",profileUrl:"https://slack.com/api/users.identity",revokeUrl:"https://slack.com/api/auth.revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},notion:{name:"Notion",color:"#000000",icon:"notion",type:"oauth",scopes:{"api-access":["read","write"]},endpoints:{authUrl:"https://api.notion.com/v1/oauth/authorize",tokenUrl:"https://api.notion.com/v1/oauth/token",profileUrl:"https://api.notion.com/v1/users/me",revokeUrl:"https://api.notion.com/v1/oauth/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},medium:{name:"Medium",color:"#000000",icon:"medium",type:"oauth",scopes:{"api-access":["basicProfile","publishPost","listPublications"]},endpoints:{authUrl:"https://medium.com/m/oauth/authorize",tokenUrl:"https://medium.com/v1/tokens",profileUrl:"https://medium.com/v1/me",revokeUrl:"https://medium.com/v1/tokens/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"oauth",scopes:{"api-access":["tweet.read","users.read","follows.read","tweet.write","like.write"]},endpoints:{authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",profileUrl:"https://api.twitter.com/2/users/me",revokeUrl:"https://api.twitter.com/2/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},mastodon:{name:"Mastodon",color:"#6364FF",icon:"mastodon",type:"oauth",scopes:{"api-access":["read","write","follow","push"]},endpoints:{authUrl:"",tokenUrl:"",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},youtube:{name:"YouTube",color:"#FF0000",icon:"youtube",type:"oauth",scopes:{"api-access":["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.force-ssl"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/youtube/v3/channels",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},supabase:{name:"Supabase",color:"#3ECF8E",icon:"supabase",type:"oauth",scopes:{"api-access":["auth:read","auth:write","database:read","database:write","domains:read","domains:write","edge_functions:read","edge_functions:write","environment:read","environment:write","organizations:read","projects:read","projects:write","rest:read","rest:write","secrets:read","secrets:write","storage:read"]},endpoints:{authUrl:"https://api.supabase.com/v1/oauth/authorize",tokenUrl:"https://api.supabase.com/v1/oauth/token",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#F1F3F5",textColor:"#11181C",borderColor:"#E6E8EB",hoverBackgroundColor:"#E6E8EB",focusOutlineColor:"#3ECF8E",fontWeight:"500"}},vercel:{name:"Vercel",color:"#000000",icon:"vercel",type:"oauth",scopes:{authentication:["openid","email","profile","offline_access"],"api-access":["project","project-env-vars","deployment","team","user"]},endpoints:{authUrl:"https://vercel.com/oauth/authorize",tokenUrl:"https://api.vercel.com/login/oauth/token",profileUrl:"https://api.vercel.com/login/oauth/userinfo",revokeUrl:"https://api.vercel.com/login/oauth/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}}},go=x(r(),en),vo=x(r(),on);var ut={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"};var Co={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:ut.ANALYTICS},marketing:{requiresConsent:ut.MARKETING}};function lt(e){return e instanceof Error&&"source"in e&&typeof e.source=="string"?e.source:typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("auth/")?"auth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("oauth/")?"oauth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&["permission-denied","unavailable","not-found","already-exists","unauthenticated","invalid-argument","failed-precondition","resource-exhausted"].includes(e.code)?"firebase":typeof e=="object"&&e!==null&&"issues"in e&&Array.isArray(e.issues)&&"name"in e&&e.name==="ValiError"?"validation":e instanceof Error&&e.name==="EntityHookError"?"entity":typeof e=="object"&&e!==null&&("response"in e||"status"in e||"statusText"in e)?"api":typeof e=="object"&&e!==null&&"componentStack"in e?"ui":"unknown"}i(lt,"detectErrorSource");function H(e){return(t,n)=>{if(t instanceof P)return t;if(typeof t!="object"||t===null){let g=typeof t=="string"?t:e.defaultErrorMessage;return new P(n||g,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let o;e.extractErrorCode?o=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(o=t.code);let c=e.defaultErrorCode;o&&e.errorCodeMapping&&o in e.errorCodeMapping&&(c=e.errorCodeMapping[o]);let u;e.extractErrorMessage?u=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(u=t.message),o&&e.friendlyMessageMapping&&o in e.friendlyMessageMapping&&(u=e.friendlyMessageMapping[o]),u||(u=e.defaultErrorMessage);let l;return e.processMetadata?l=e.processMetadata(t):(l={originalError:t},o&&(l.originalCode=o)),"originalError"in l||(l.originalError=t),new P(n||u,c,{details:l,source:e.errorSource})}}i(H,"createErrorHandler");var xe={"permission-denied":"permission-denied",unavailable:"unavailable","not-found":"not-found","already-exists":"already-exists",unauthenticated:"unauthenticated","invalid-argument":"invalid-argument","failed-precondition":"invalid-argument","resource-exhausted":"rate-limit-exceeded","deadline-exceeded":"timeout",cancelled:"cancelled","not-implemented":"unimplemented"};var ie={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",DELETE_ACCOUNT_REQUIRES_SERVER:"Account deletion requires a server endpoint. Configure a callable provider or deploy a delete-account Edge Function.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},sn={400:"invalid-argument",401:"unauthenticated",403:"permission-denied",404:"not-found",409:"already-exists",422:"validation-failed",429:"rate-limit-exceeded",500:"internal",501:"unimplemented",502:"unavailable",503:"unavailable",504:"timeout"},Be={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},z={auth:{errorSource:"auth",defaultErrorCode:"unknown",defaultErrorMessage:"An authentication error occurred",errorCodeMapping:{"auth/user-not-found":"not-found","auth/wrong-password":"invalid-argument","auth/email-already-in-use":"already-exists","auth/weak-password":"validation-failed","auth/invalid-email":"validation-failed","auth/account-exists-with-different-credential":"already-exists","auth/credential-already-in-use":"already-exists","auth/requires-recent-login":"unauthenticated","auth/user-disabled":"permission-denied","auth/too-many-requests":"rate-limit-exceeded","auth/network-request-failed":"unavailable","auth/popup-blocked":"unavailable","auth/popup-closed-by-user":"invalid-argument","auth/cancelled-popup-request":"invalid-argument","auth/operation-not-allowed":"unimplemented","auth/invalid-credential":"invalid-argument","auth/invalid-verification-code":"invalid-argument","auth/captcha-check-failed":"validation-failed","auth/invalid-phone-number":"validation-failed","auth/missing-phone-number":"invalid-argument","auth/quota-exceeded":"rate-limit-exceeded","auth/timeout":"unavailable","auth/web-storage-unsupported":"unavailable","auth/unauthorized-domain":"permission-denied","auth/internal-error":"internal","auth/invalid-action-code":"invalid-argument","auth/invalid-continue-uri":"invalid-argument","auth/missing-continue-uri":"invalid-argument","auth/missing-ios-bundle-id":"invalid-argument","auth/missing-android-pkg-name":"invalid-argument","auth/unauthorized-continue-uri":"permission-denied","auth/invalid-dynamic-link-domain":"invalid-argument","auth/invalid-tenant-id":"invalid-argument","auth/tenant-id-mismatch":"invalid-argument","auth/provider-already-linked":"already-exists","auth/invalid-persistence-type":"invalid-argument","auth/unsupported-persistence-type":"unimplemented","auth/invalid-provider":"invalid-argument","auth/invalid-client-id":"invalid-argument","oauth/unauthorized-app":"permission-denied","auth/provider-not-enabled":"unimplemented","auth/unknown-provider":"invalid-argument","auth/missing-provider":"invalid-argument","auth/no-user-signed-in":"unauthenticated",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",...xe},friendlyMessageMapping:{"auth/user-not-found":"No account found with this email address.","auth/wrong-password":"Incorrect password. Please try again.","auth/email-already-in-use":"An account with this email already exists.","auth/weak-password":"Password is too weak. It should be at least 6 characters.","auth/invalid-email":"Please enter a valid email address.","auth/account-exists-with-different-credential":"An account already exists with the same email but different sign-in method.","auth/credential-already-in-use":"This credential is already associated with a different user account.","auth/requires-recent-login":"This operation requires you to sign in again for security reasons.","auth/user-disabled":"This account has been disabled.","auth/too-many-requests":"Too many sign-in attempts. Please try again later.","auth/network-request-failed":"Network connection error. Please check your internet connection.","auth/popup-blocked":"Sign-in popup was blocked. Please allow popups for this site.","auth/popup-closed-by-user":"Sign-in popup was closed before completion.","auth/operation-not-allowed":"This sign-in method is not enabled for this project.","auth/internal-error":"An internal authentication error occurred. Please try again.","auth/invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","auth/invalid-continue-uri":"The continue URL provided is invalid.","auth/missing-continue-uri":"A continue URL must be provided in the request.","auth/missing-ios-bundle-id":"An iOS Bundle ID must be provided in the request.","auth/missing-android-pkg-name":"An Android package name must be provided in the request.","auth/unauthorized-continue-uri":"The domain of the continue URL is not allowlisted.","auth/invalid-dynamic-link-domain":"The provided dynamic link domain is not authorized.","auth/invalid-tenant-id":"The provided tenant ID is invalid.","auth/tenant-id-mismatch":"The tenant ID of the provider does not match the tenant ID of the current user.","auth/provider-already-linked":"This authentication provider is already linked to the account.","auth/invalid-persistence-type":"The specified persistence type is invalid.","auth/unsupported-persistence-type":"The current environment does not support the specified persistence type.","auth/invalid-provider":"The specified authentication provider is invalid.","auth/invalid-client-id":"The authentication client ID provided is invalid.","oauth/unauthorized-app":"This application is not authorized to use OAuth with the provided client ID.","auth/provider-not-enabled":"This authentication provider is not enabled.","auth/unknown-provider":"Unknown authentication provider.","auth/missing-provider":"No authentication provider specified in the request.","auth/no-user-signed-in":"No user is currently signed in."}},oauth:{errorSource:"oauth",defaultErrorCode:"unknown",defaultErrorMessage:"An OAuth error occurred",errorCodeMapping:{"oauth/invalid-request":"invalid-argument","oauth/invalid-client":"invalid-argument","oauth/invalid-grant":"invalid-argument","oauth/unauthorized-client":"permission-denied","oauth/unsupported-grant-type":"unimplemented","oauth/invalid-scope":"invalid-argument","oauth/insufficient-scope":"permission-denied","oauth/invalid-token":"unauthenticated","oauth/expired-token":"unauthenticated","oauth/redirect-uri-mismatch":"invalid-argument","oauth/access-denied":"permission-denied","oauth/server-error":"unavailable","oauth/temporarily-unavailable":"unavailable","oauth/state-mismatch":"invalid-argument","oauth/invalid-callback":"invalid-argument","oauth/client-secret-mismatch":"permission-denied","oauth/unauthorized-scope":"permission-denied","oauth/rate-limit-exceeded":"rate-limit-exceeded","oauth/token-expired":"unauthenticated","oauth/missing-token":"invalid-argument","oauth/invalid-code":"invalid-argument","oauth/invalid-redirect":"invalid-argument","oauth/provider-error":"unavailable","oauth/invalid-response":"unavailable","oauth/unauthorized-access":"permission-denied",...xe},friendlyMessageMapping:{"oauth/invalid-request":"The OAuth request was invalid or missing parameters.","oauth/invalid-client":"Client authentication failed.","oauth/invalid-grant":"The provided authorization grant is invalid.","oauth/unauthorized-client":"The client is not authorized to use this grant type.","oauth/unsupported-grant-type":"The requested grant type is not supported.","oauth/invalid-scope":"The requested scope is invalid or unknown.","oauth/insufficient-scope":"The token does not have the required scope for this resource.","oauth/invalid-token":"The access token is invalid.","oauth/expired-token":"The access token has expired.","oauth/redirect-uri-mismatch":"The redirect URI does not match the registered URI.","oauth/access-denied":"The resource owner denied the request.","oauth/server-error":"The authorization server encountered an unexpected error.","oauth/temporarily-unavailable":"The authorization server is temporarily unavailable.","oauth/state-mismatch":"Invalid state parameter. This could be a security issue.","oauth/invalid-callback":"The callback URL is invalid or not registered.","oauth/client-secret-mismatch":"The client secret does not match the registered secret.","oauth/unauthorized-scope":"The requested scope is not authorized for this client.","oauth/rate-limit-exceeded":"Too many requests. Please try again later.","oauth/token-expired":"The OAuth token has expired and needs to be refreshed.","oauth/missing-token":"No OAuth token was provided in the request.","oauth/invalid-code":"The authorization code is invalid or expired.","oauth/invalid-redirect":"The redirect URL is invalid or does not match the registered redirect URL.","oauth/provider-error":"The OAuth provider returned an error.","oauth/invalid-response":"The response from the OAuth provider was invalid.","oauth/unauthorized-access":"Unauthorized access to OAuth resources."}},api:{errorSource:"api",defaultErrorCode:"unknown",defaultErrorMessage:"API request failed",errorCodeMapping:Object.fromEntries(Object.entries(sn).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode:i(e=>{if(typeof e!="object"||e===null)return;let t;return"response"in e&&e.response&&"status"in e.response?t=e.response.status:"status"in e&&typeof e.status=="number"&&(t=e.status),t?.toString()},"extractErrorCode"),processMetadata:i(e=>{let t={originalError:e};return typeof e!="object"||e===null||("response"in e&&e.response?("status"in e.response&&(t.statusCode=e.response.status),"data"in e.response&&(t.responseData=e.response.data)):"status"in e&&(t.statusCode=e.status)),t},"processMetadata")},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:xe,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:ie.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:i(e=>{let t={originalError:e};return typeof e=="object"&&e!==null&&"componentStack"in e&&(t.componentStack=e.componentStack),t},"processMetadata")},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:ie["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:ie.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:i(e=>{if(e instanceof Error)return e.name},"extractErrorCode")}},an=i(e=>e instanceof be?new P(ie["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):H(z.validation)(e),"handleValidationError"),un=i(e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&e.type in Be){let t=e,n=Be[t.type]||"unknown";return new P(t.message||ie[n],n,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&Re[e.code]){let t=e,n=Re[t.code];if(n){let o=Be[n.type]||"unknown";return new P(n.message||ie[o],o,{details:{originalCode:t.code,originalError:e},source:"entity"})}}return H(z.entity)(e)},"handleEntityError"),ct={auth:H(z.auth),oauth:H(z.oauth),api:H(z.api),firebase:H(z.firebase),ui:H(z.ui),validation:an,entity:un,unknown:H(z.unknown)};function Se(e,t,n){return e instanceof P?e:(ct[t]||ct.unknown)(e,n)}i(Se,"mapToDoNotDevError");function pt(e,t,n={}){let o=globalThis.Sentry;o&&o.withScope(c=>{c.setTag("errorSource",t),c.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([u,l])=>{if(typeof l!="function"&&u!=="originalError")try{c.setExtra(u,l)}catch{c.setExtra(u,`[${typeof l}]`)}}),Object.entries(n).forEach(([u,l])=>{if(typeof l!="function")try{c.setExtra(`context.${u}`,l)}catch{c.setExtra(`context.${u}`,`[${typeof l}]`)}}),(e.details?.userId||n.userId)&&c.setUser({id:e.details?.userId||n.userId,email:e.details?.userEmail||n.userEmail}),o.captureException(e)})}i(pt,"captureErrorToSentry");function ln(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof process<"u"&&process.env?"production".toLowerCase()!=="production":!1}i(ln,"isDev");function ke(e,t){let n=typeof t=="string"?{userMessage:t}:t||{},{userMessage:o,context:c={},log:u=!0,reportToSentry:l=!0,showNotification:g=!1,severity:m="error"}=n,h=lt(e),d=e instanceof P?e:Se(e,h,o);if(o&&!d.userMessageProvided&&(d.message.includes("Error")||d.message.includes("Failed")||d.message.length<10?d=new P(o,d.code,{details:{...d.details,originalMessage:d.message},source:h,userMessageProvided:!0}):d=new P(d.message,d.code,{details:{...d.details,userMessage:o},source:h,userMessageProvided:!0})),u){let w=ln()||typeof window<"u"&&window.__DNDEV_DEBUG,O={code:d.code,message:d.message,source:h};switch(m){case"warning":console.warn(`[DoNotDev] ${d.code}: ${d.message}`,w?{...O,details:d.details}:O);break;case"info":console.info(`[DoNotDev] ${d.code}: ${d.message}`,w?{...O,details:d.details}:O);break;case"success":console.log(`[DoNotDev] ${d.code}: ${d.message}`,w?{...O,details:d.details}:O);break;default:console.error(`[DoNotDev] ${d.code}: ${d.message}`,w?{...O,details:d.details,stack:d.stack}:O)}}return l&&pt(d,h,c),g&&typeof window<"u"&&console.warn("[handleError] showNotification requires client-side toast setup"),d}i(ke,"handleError");function Ds(e,t,n,o){let c=o?` ${JSON.stringify(o)}`:"",u=`${t}.${n}(${c})`,l=Se(e,"auth",`${u}: ${cn(e)}`);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&l.code==="unknown"&&e.code!=="unknown"?new P(l.message,l.code,{details:{...l.details,originalCode:e.code},source:l.source}):l}i(Ds,"wrapAuthError");function cn(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}i(cn,"getErrorMessage");var dt={[K.GUEST]:0,[K.USER]:1,[K.ADMIN]:2,[K.SUPER]:3};function qe(e,t){if(!e)return!1;let n=dt[e]??-1,o=dt[t]??1/0;return n>=o}i(qe,"hasRoleAccess");var je="__DNDEV_SINGLETONS__";function pn(){if(typeof globalThis<"u"){let e=globalThis;return e[je]||(e[je]=new Map),e[je]}return new Map}i(pn,"getSingletonRegistry");function ft(e,t){let n=pn();return n.has(e)||n.set(e,t()),n.get(e)}i(ft,"getGlobalSingleton");function Ls(e,...t){let n=null,o=!1;return i(function(){if(n!==null)return n;if(o)throw new Error("Circular dependency detected in singleton initialization");o=!0;try{return typeof e=="function"&&e.prototype?n=new e(...t):n=e(),n}finally{o=!1}},"getInstance")}i(Ls,"createSingleton");function mt(){return ft("providers",()=>({providers:null}))}i(mt,"getProviderState");function Vs(e){let{providers:t}=mt();if(!t)throw new Error(`[dndev] Provider "${e}" not available. Call configureProviders() at app startup.`);let n=t[e];if(!n)throw new Error(`[dndev] Provider "${e}" not configured. Pass it to configureProviders().`);return n}i(Vs,"getProvider");function $s(e){return!!mt().providers?.[e]}i($s,"hasProvider");function dn(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}i(dn,"hasVisibility");function fn(e){if(dn(e))return e.visibility}i(fn,"getFieldVisibility");function mn(e,t){let n=e??"guest";return n==="hidden"?!1:n==="technical"?qe(t,"admin"):n==="owner"?!1:qe(t,n)}i(mn,"isFieldVisible");function yn(e,t,n){for(let o of n.ownerFields)if(e[o]===t)return!0;return!1}i(yn,"isOwnerVisible");function yt(e,t,n){let o=e;if(!o||typeof o!="object"||!o.entries)return console.warn("getVisibleFields expects a Valibot object schema (v.object)."),[];let c=o.entries,u=[],{documentData:l,uid:g,ownership:m}=n??{},h=m&&g!=null&&l&&yn(l,g,m);for(let[d,w]of Object.entries(c)){let O=fn(w);if(O==="owner"){h&&u.push(d);continue}mn(O,t)&&u.push(d)}return u}i(yt,"getVisibleFields");function Xs(e,t,n,o){if(!e)return{};let c=o?.uid!=null&&o?.ownership!=null?{documentData:o.documentData??e,uid:o.uid,ownership:o.ownership}:void 0,u=yt(t,n,c),l={};for(let g of u)Object.prototype.hasOwnProperty.call(e,g)&&(l[g]=e[g]);return l}i(Xs,"filterVisibleFields");function Ve(e){let t=e.listCardFields;if(t){if(Array.isArray(t))return t;let n=t,o=[...n.title??[],...n.subtitle??[],...n.content??[],...n.footer??[]];return[...new Set(o)]}return e.listFields&&e.listFields.length>0?e.listFields:e.fields?Object.keys(e.fields):[]}i(Ve,"getListCardFieldNames");var gn=new Set(["http:","https:","mailto:","tel:","blob:"]);function ta(e){if(!e||typeof e!="string")return"";let t=e.trim();if(/^[/.?#]/.test(t))return t;try{let n=new URL(t);if(gn.has(n.protocol))return t}catch{return t}return""}i(ta,"sanitizeHref");var gt=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],ia="available",oa=["draft","deleted"],$e=["id","createdAt","updatedAt","createdById","updatedById"],sa=[...$e,"status"];var Ae={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...gt]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0}},createdAt:{name:"createdAt",type:"timestamp",visibility:"technical",label:"crud:fields.createdAt",validation:{}},updatedAt:{name:"updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields.updatedAt",validation:{}},createdById:{name:"createdById",type:"reference",visibility:"technical",label:"crud:fields.createdById",validation:{}},updatedById:{name:"updatedById",type:"reference",visibility:"technical",label:"crud:fields.updatedById",validation:{}}};function Te(e,t){let n=new Date(e),o=n.getDate();return n.setMonth(n.getMonth()+t),n.getDate()!==o&&n.setDate(0),n}i(Te,"addMonths");function vt(e,t){let n=new Date(e),o=n.getDate();return n.setFullYear(n.getFullYear()+t),n.getDate()!==o&&n.setDate(0),n}i(vt,"addYears");function wu(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let n;return e==="1month"?n=Te(t,1):e==="3months"?n=Te(t,3):e==="6months"?n=Te(t,6):e==="1year"?n=vt(t,1):e==="2years"?n=vt(t,2):n=Te(t,1),n.toISOString()}i(wu,"calculateSubscriptionEndDate");var St=new Map;function y(e,t){St.set(e,t)}i(y,"registerSchemaGenerator");function T(e,t){return t?e:U(e)}i(T,"applyRequired");var Ie=i(e=>{let t=[];e.validation?.minLength!==void 0&&t.push(f(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push($(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(re(new RegExp(e.validation.pattern),"Invalid format"));let n=t.length>0?a(r(),...t):r();return T(n,e.validation?.required)},"textSchema"),hn=i(e=>{let t=a(r(),L("Invalid email address"));return T(t,e.validation?.required)},"emailSchema"),bn=i(e=>{let t=e.validation?.minLength!==void 0?a(r(),f(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):r();return T(t,e.validation?.required)},"passwordSchema"),En=i(e=>{let t=a(r(),N("Invalid URL"));return T(t,e.validation?.required)},"urlSchema"),oe=i(e=>{let t=[];e.validation?.min!==void 0&&t.push(C(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(q(e.validation.max,`Must be at most ${e.validation.max}`));let n=t.length>0?a(E(),...t):E();return T(n,e.validation?.required)},"numberSchema"),ht=i(e=>{let t=k();return T(t,e.validation?.required)},"booleanSchema"),se=i(e=>{let t=a(r(),le(n=>!isNaN(new Date(n).getTime()),"Invalid date format"));return T(t,e.validation?.required)},"dateSchema"),kt=p({url:r(),filename:r(),size:E(),mimeType:U(r()),uploadedAt:U(r())}),bt=i(e=>{let t=D(kt);return T(t,e.validation?.required)},"fileSchema"),Et=i(e=>{let t=v(kt);return T(t,e.validation?.required)},"filesSchema"),At=p({fullUrl:r(),thumbUrl:r()}),xn=i(e=>{let t=J([r(),At]);return T(t,e.validation?.required)},"pictureSchema"),Sn=i(e=>{let t=v(J([r(),At]));return T(t,e.validation?.required)},"picturesSchema"),kn=i(e=>{let t=p({lat:E(),lng:E()});return T(t,e.validation?.required)},"geopointSchema"),An=i(e=>{let t=p({formatted_address:r(),latitude:E(),longitude:E(),street_number:U(r()),route:U(r()),locality:U(r()),administrative_area_level_1:U(r()),administrative_area_level_2:U(r()),country:U(r()),postal_code:U(r())});return T(t,e.validation?.required)},"addressSchema"),Tn=i(e=>{let t=x(r(),_());return T(t,e.validation?.required)},"mapSchema"),In=i(e=>{let t=v(_());return T(t,e.validation?.required)},"arraySchema"),Ge=i(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let o=t.map(u=>u.value),c=b(o);return T(c,e.validation?.required)}let n=J([r(),E()]);return T(n,e.validation?.required)},"selectSchema"),Rn=i(e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let o=t.map(u=>u.value),c=v(b(o));return T(c,e.validation?.required)}let n=v(r());return T(n,e.validation?.required)},"multiselectSchema"),Cn=i(e=>{let t=a(r(),f(1,"Invalid ID format"));return T(t,e.validation?.required)},"referenceSchema"),He=i(e=>{let t=r();return T(t,e.validation?.required)},"stringSchema"),wn=i(e=>{let t=r();return T(t,e.validation?.required)},"telSchema"),On=i(e=>{let t=e.validation?.minLength??15,n=e.validation?.maxLength??34,o=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",c=[];if(t!==void 0&&c.push(f(t,`IBAN must be at least ${t} characters`)),n!==void 0&&c.push($(n,`IBAN must not exceed ${n} characters`)),o){let l=typeof o=="string"?new RegExp(o):o;c.push(re(l,"Invalid IBAN format"))}let u=c.length>0?a(r(),...c):r();return T(u,e.validation?.required)},"ibanSchema"),xt=i(()=>Ne(),"neverSchema"),Pn=i(e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let o=[t.checkedValue,t.uncheckedValue],c=b(o);return T(c,e.validation?.required)}let n=k();return T(n,e.validation?.required)},"switchSchema"),Dn=i(e=>Pe(n=>e.validation?.required?typeof n=="object"&&n!==null?n.gdprConsent===!0:!1:n===!1||n===null||n===void 0?!0:typeof n=="object"&&n!==null?n.gdprConsent===!0:!1,"GDPR consent must be given"),"gdprConsentSchema"),_n=i(e=>{let t=p({amount:E(),currency:s(r()),vatIncluded:s(k()),discountPercent:s(a(E(),C(0),q(100)))});return T(t,e.validation?.required)},"priceSchema");function Nn(){y("text",Ie),y("textarea",Ie),y("richtext",Ie),y("color",Ie),y("email",hn),y("password",bn),y("url",En),y("tel",wn),y("iban",On),y("number",oe),y("currency",oe),y("price",_n),y("range",oe),y("year",oe),y("rating",oe),y("duration",oe),y("boolean",ht),y("checkbox",ht),y("gdprConsent",Dn),y("date",se),y("datetime-local",se),y("time",se),y("week",se),y("month",se),y("timestamp",se),y("file",bt),y("files",Et),y("document",bt),y("documents",Et),y("image",xn),y("images",Sn),y("geopoint",kn),y("address",An),y("map",Tn),y("array",In),y("select",Ge),y("multiselect",Rn),y("radio",Ge),y("combobox",Ge),y("switch",Pn),y("reference",Cn),y("hidden",He),y("avatar",He),y("badge",He),y("submit",xt),y("reset",xt)}i(Nn,"registerBuiltinSchemas");Nn();function fe(e){if(e.validation?.schema){let o=e.validation.schema;return T(o,e.validation?.required)}let t=St.get(e.type);if(t){let o=t(e);if(o!==null)return o}let n=_();return T(n,e.validation?.required)}i(fe,"getSchemaType");function We(e,t){return!!(t.visibility==="hidden"||t.editable===Me.GENERATED||$e.includes(e))}i(We,"isWriteExcluded");function me(e,t){return Object.assign(e,{visibility:t})}i(me,"withVisibility");function ee(e,t){let n=e;return n.metadata={collection:t.collection,entity:t.name,...t.uniqueKeys&&{uniqueKeys:t.uniqueKeys}},n}i(ee,"withMetadata");function Fn(e){let t=fe(e);return me(t,e.visibility)}i(Fn,"createFieldSchema");function Ke(e){let t=fe({...e,validation:{...e.validation,required:!1}});return me(t,e.visibility)}i(Ke,"createOptionalFieldSchema");function Wu(e){let t=e.fields,n={};for(let[A,I]of Object.entries(t))I.visibility!=="hidden"&&(n[A]=Ke(I));let o=ee(p(n),e),c={};for(let[A,I]of Object.entries(t))We(A,I)||(c[A]=Fn(I));let u=ee(p(c),e),l={};for(let[A,I]of Object.entries(t))if(!We(A,I))if(A==="status"){let Y=F("draft");l[A]=me(Y,I.visibility)}else l[A]=Ke(I);let g=ee(p(l),e),m={};for(let[A,I]of Object.entries(t))We(A,I)||(m[A]=Ke(I));m.id=me(fe(Ae.id),"technical");let h=ee(p(m),e),d;if(e.listFields&&e.listFields.length>0){let A=["id","status"],I=[...new Set([...A,...e.listFields])];d={};for(let Y of I){let ae=n[Y];ae&&(d[Y]=ae)}}else d=n;let w=ee(p(d),e),O,G=Ve(e);if(G.length>0){let A=["id","status"],I=[...new Set([...A,...G])];O={};for(let Y of I){let ae=n[Y];ae&&(O[Y]=ae)}}else O=n;let ye=ee(p(O),e),te=ee(p({id:me(fe(Ae.id),"technical")}),e);return{create:u,draft:g,update:h,get:o,list:w,listCard:ye,delete:te}}i(Wu,"createSchemas");var Un=x(r(),_()),Mn=p({id:r(),patch:x(r(),_())}),Ln=r(),Yu=p({inserts:s(v(Un)),updates:s(v(Mn)),deletes:s(v(Ln))}),Xu=p({insertedIds:v(r()),updatedIds:v(r()),deletedIds:v(r())});function Zu(e){let t=new Set((e.updates??[]).map(l=>l.id)),n=e.deletes??[],o=[];for(let l of n)t.has(l)&&o.push(l);if(o.length>0)return{collisions:o,where:"updates-deletes"};let c=e.inserts??[],u=[];for(let l of c)typeof l.id=="string"&&t.has(l.id)&&u.push(l.id);return u.length>0?{collisions:u,where:"inserts-updates"}:{collisions:[],where:null}}i(Zu,"detectBulkCollisions");var Nl=a(r(),le(e=>e.startsWith("/proxy/")||e.startsWith("data:image/"),"Image URL must be box-proxied (/proxy/...) or an inline data:image URI.")),Bn=b(["ephemeral","session","persistent"]),qn=p({title:s(r()),pinnable:s(k()),preferredHeight:s(a(E(),C(0)))}),Fl=p({id:a(r(),f(1)),kind:a(r(),f(1)),lifetime:s(Bn,"ephemeral"),metadata:s(qn),payload:_()}),Ul=p({widgetId:a(r(),f(1)),action:a(r(),f(1)),payload:_()});export{$n as a,Gn as b,Hn as c,Wn as d,zn as e,ne as f,q as g,f as h,C as i,re as j,Ft as k,N as l,Z as m,v as n,k as o,Pe as p,E as q,p as r,s,b as t,x as u,r as v,Mt as w,J as x,_ as y,Ze as z,a as A,W as B,qt as C,tr as D,Qe as E,de as F,mr as G,Sr as H,ot as I,Jt as J,gi as K,P as L,to as M,no as N,ro as O,io as P,yo as Q,ke as R,Ds as S,qe as T,Ls as U,Vs as V,$s as W,Xs as X,Ve as Y,ta as Z,wu as _,ia as $,oa as aa,Wu as ba,Yu as ca,Xu as da,Zu as ea};
|
|
22
|
+
//# sourceMappingURL=chunk-5DTPEM64.js.map
|