import { z } from 'zod'; import { GeeniusError, ErrorCode } from '@geenius/errors'; /** * @module constants * @package @geenius/adapters * @description Defines the shared adapter domains, provider registries, status * labels, and UI metadata used across every runtime variant. Explicit unions * preserve compile-time parity for providers, domains, and statuses. */ /** * Ordered list of all supported adapter domains. * These represent the major functional areas that can have pluggable implementations. */ declare const ADAPTER_DOMAINS: readonly AdapterDomain[]; /** * Type representing valid database provider names for adapter configuration * and resolver registration. * * The v1 public provider subpaths are limited to `convex`, `neon`, * `cloudflareKV`, and `memory`; future and BYOD ids remain metadata/resolver * keys only. */ type DbProviderName = "localStorage" | "convex" | "supabase" | "drizzle" | "neon" | "prisma" | "kysely" | "mongodb" | "cloudflareKV" | "memory"; /** Type representing valid authentication provider names */ type AuthProviderName = "localStorage" | "better-auth" | "convex-auth" | "clerk" | "supabase-auth"; /** Type representing valid AI provider names */ type AiProviderName = "localStorage" | "openai" | "anthropic" | "gemini" | "ollama" | "cloudflare-ai-gateway" | "vercel-ai-sdk"; /** Type representing valid file storage provider names */ type StorageProviderName = "localStorage" | "r2" | "s3" | "uploadthing" | "supabase-storage" | "convex-storage" | "minio"; /** Type representing valid payment provider names */ type PaymentProviderName = "localStorage" | "stripe" | "lemonsqueezy" | "polar" | "noop"; /** Type representing valid admin provider names */ type AdminProviderName = "localStorage"; /** Type representing valid logger provider names */ type LoggerProviderName = "console" | "memory"; /** * Available database providers (ordered from lightweight to production-ready). * Supports local mocks and the four launch provider contracts without importing * downstream SDKs into this package. */ declare const DB_PROVIDERS: readonly DbProviderName[]; /** Canonical database backends that define the expanded boilerplate universe. */ type EcosystemDbProviderName = "convex" | "neon" | "cloudflareKV" | "memory" | "supabase" | "mongodb" | "drizzle" | "prisma" | "kysely"; /** Four database backend categories used by scaffold tooling and setup UIs. */ type EcosystemDbProviderCategory = "platform-native" | "edge-kv" | "in-process" | "byod-orm"; /** Launch readiness for a database backend in the expanded ecosystem. */ type EcosystemDbProviderStage = "launch" | "future" | "byod"; /** Metadata for production database backends in the expanded ecosystem. */ interface EcosystemDbProviderMeta { /** Canonical provider id used in adapter config. */ id: EcosystemDbProviderName; /** Provider family: vendor SDK/native platform versus bring-your-own ORM. */ category: EcosystemDbProviderCategory; /** Whether this backend is part of the current four-provider launch matrix. */ stage: EcosystemDbProviderStage; /** Runtime SDK or ORM package owned by the downstream provider implementation. */ sdk: string; /** Optional default database driver used by the downstream provider implementation. */ defaultDriver?: string; /** Expected auth integration for boilerplate scaffolds using this backend. */ authIntegration: string; /** Schema or data-model artifact expected in generated boilerplates. */ schema: string; /** Factory exported by @geenius/db for this provider family. */ factory: string; } /** * Platform-native database backends tracked for ecosystem metadata. * * Only entries whose metadata stage is `launch` are v1 provider subpaths. */ declare const PLATFORM_NATIVE_DB_PROVIDERS: readonly EcosystemDbProviderName[]; /** BYOD ORM resolver metadata ids tracked for downstream DB adapter factories. */ declare const BYOD_ORM_DB_PROVIDERS: readonly EcosystemDbProviderName[]; /** Database backends included in the current launch matrix. */ declare const LAUNCH_DB_PROVIDERS: readonly EcosystemDbProviderName[]; /** Future DB providers are metadata-only until a coordinated axis expansion. */ declare const FUTURE_DB_PROVIDERS: readonly EcosystemDbProviderName[]; /** Full production database backend universe tracked for launch and later expansion. */ declare const ECOSYSTEM_DB_PROVIDERS: readonly EcosystemDbProviderMeta[]; /** * Available authentication providers. * Ranges from mock implementations (localStorage) to full-featured solutions (Clerk, Supabase). */ declare const AUTH_PROVIDERS: readonly AuthProviderName[]; /** * Available AI/LLM providers. * Includes major API providers (OpenAI, Anthropic) and local options (Ollama). */ declare const AI_PROVIDERS: readonly AiProviderName[]; /** * Available file storage providers. * Supports in-browser storage, cloud providers, and self-hosted options. */ declare const STORAGE_PROVIDERS: readonly StorageProviderName[]; /** * Available payment processing providers. * Includes full-featured (Stripe) and mock implementations for testing. */ declare const PAYMENT_PROVIDERS: readonly PaymentProviderName[]; /** * Available admin panel providers. * Currently limited to localStorage for development/prototyping. */ declare const ADMIN_PROVIDERS: readonly AdminProviderName[]; /** * Available logger providers. * Starts with the local-first console logger while preserving room for * dedicated downstream logging packages to register production sinks later. */ declare const LOGGER_PROVIDERS: readonly LoggerProviderName[]; /** * Valid adapter connection states. * Used to represent the health and availability of configured adapters. */ /** Type representing valid adapter status values */ type AdapterStatus = "connected" | "disconnected" | "error" | "initializing"; declare const ADAPTER_STATUSES: readonly AdapterStatus[]; /** * Human-readable labels for each adapter domain. * Used in UI components like dropdowns, headings, and breadcrumbs. */ declare const DOMAIN_LABELS: Record; /** * Semantic icon identifiers for each adapter domain. * UI variants map these descriptors to native icon components or tokenized * icon slots instead of rendering emoji glyphs from shared metadata. */ declare const DOMAIN_ICONS: Record; /** * Detailed descriptions of each adapter domain. * Displayed in help text, tooltips, and onboarding flows. */ declare const DOMAIN_DESCRIPTIONS: Record; /** * Metadata about a specific provider implementation. * Contains information needed for provider selection UI, documentation links, and tier gating. */ interface ProviderMeta { /** Unique identifier for the provider (matches provider name in config) */ id: string; /** Human-readable provider name for display in UI */ name: string; /** The domain this provider belongs to */ domain: AdapterDomain; /** Brief description of what this provider offers */ description: string; /** Minimum feature tier required to use this provider (tier gating) */ tier: "pronto" | "lancio" | "studio"; /** Whether the provider typically needs an API key or token during setup */ requiresApiKey?: boolean; /** Whether the provider typically needs a configurable base URL during setup */ requiresBaseUrl?: boolean; /** Optional URL to provider documentation or setup guide */ docUrl?: string; } /** * Comprehensive registry of all available providers across all domains. * Used for provider selection UI, documentation, and availability checking. * Organized by domain with localStorage typically first for dev/mock workflows. */ declare const PROVIDER_REGISTRY: readonly Readonly[]; /** * Get all available providers for a specific adapter domain. * * @param domain - The adapter domain to get providers for * @returns Array of provider metadata for the given domain, ordered by tier * * @example * const dbProviders = getProvidersForDomain('db'); * // Returns metadata for localStorage, Convex, Neon, Cloudflare KV, and Memory. */ declare function getProvidersForDomain(domain: AdapterDomain): ProviderMeta[]; /** * Get expanded ecosystem database providers by backend category. * * @param category - Backend category to filter by * @returns Production database provider metadata for the selected category */ declare function getEcosystemDbProvidersByCategory(category: EcosystemDbProviderCategory): EcosystemDbProviderMeta[]; /** * Get expanded ecosystem database providers by launch readiness. * * @param stage - Launch stage to filter by * @returns Production database provider metadata for the selected stage */ declare function getEcosystemDbProvidersByStage(stage: EcosystemDbProviderStage): EcosystemDbProviderMeta[]; /** * Get expanded ecosystem metadata for a database provider. * * @param providerId - Canonical database provider id * @returns Expanded ecosystem metadata if the provider is part of the nine-backend matrix */ declare function getEcosystemDbProviderMeta(providerId: string): EcosystemDbProviderMeta | undefined; /** * Get metadata for a specific provider implementation. * * @param domain - The adapter domain the provider belongs to * @param providerId - The unique identifier of the provider * @returns Provider metadata if found, undefined otherwise * * @example * const stripeMeta = getProviderMeta('payments', 'stripe'); * if (stripeMeta?.tier === 'lancio') { * // Stripe is available on lancio tier * } */ declare function getProviderMeta(domain: AdapterDomain, providerId: string): ProviderMeta | undefined; /** * @module interface * @description Declares the shared admin adapter contract used by the adapters * package. The interfaces define dashboard metrics and user-management * operations consumed by admin-capable runtime variants. */ /** * Business and usage metrics displayed on the admin dashboard. * Provides high-level visibility into platform health and growth. */ interface AdminMetrics { /** Total number of users who have signed up */ totalUsers: number; /** Number of users who have logged in in the last 7/30 days (typically) */ activeUsers: number; /** Number of new user signups since start of today */ newUsersToday: number; /** Total revenue from all time (if payments are tracked) */ totalRevenue?: number; /** Monthly recurring revenue - predictable revenue from active subscriptions */ mrr?: number; } /** * User details with administrative metadata. * Extends AuthUser with status flags and subscription/plan information. * Used in admin dashboards for user management and moderation. */ interface ManagedUser extends AuthUser { /** Whether the user account is active (not suspended/archived) */ isActive: boolean; /** Whether the user is banned from using the platform */ isBanned: boolean; /** Role identifiers assigned directly to the user */ roleIds?: string[]; /** Team identifiers the user belongs to */ teamIds?: string[]; /** The user's subscription plan tier if applicable */ plan?: string; /** ISO 8601 timestamp of the user's last login */ lastLoginAt?: string; } /** * Role metadata used by admin dashboards and policy editors. * Roles group permission strings and can be assigned directly to users. */ interface AdminRole { /** Stable role identifier used by assignments and audit logs */ id: string; /** Human-readable role name shown to operators */ name: string; /** Optional operator-facing role description */ description?: string; /** Permission identifiers granted by this role */ permissions: string[]; /** Whether the role is seeded by the platform and should be protected downstream */ isSystem?: boolean; /** ISO 8601 timestamp for role creation */ createdAt?: string; /** ISO 8601 timestamp for the last role update */ updatedAt?: string; } /** * Draft payload used to create or update an admin role. * Supplying an id updates the existing role or creates a deterministic one. */ interface AdminRoleInput { /** Optional stable identifier; generated by local adapters when omitted */ id?: string; /** Human-readable role name shown to operators */ name: string; /** Optional operator-facing role description */ description?: string; /** Permission identifiers granted by this role */ permissions?: string[]; /** Whether the role is seeded by the platform and should be protected downstream */ isSystem?: boolean; } /** * Team metadata used by admin dashboards and membership editors. * Teams group users and can carry role assignments for downstream policy checks. */ interface AdminTeam { /** Stable team identifier used by memberships and audit logs */ id: string; /** Human-readable team name shown to operators */ name: string; /** Optional operator-facing team description */ description?: string; /** User identifiers that belong to this team */ memberUserIds: string[]; /** Role identifiers granted to this team */ roleIds: string[]; /** ISO 8601 timestamp for team creation */ createdAt?: string; /** ISO 8601 timestamp for the last team update */ updatedAt?: string; } /** * Draft payload used to create or update an admin team. * Supplying an id updates the existing team or creates a deterministic one. */ interface AdminTeamInput { /** Optional stable identifier; generated by local adapters when omitted */ id?: string; /** Human-readable team name shown to operators */ name: string; /** Optional operator-facing team description */ description?: string; /** Initial or replacement member user ids */ memberUserIds?: string[]; /** Initial or replacement team role ids */ roleIds?: string[]; } /** Pagination and search options shared by admin collection methods. */ interface AdminListOptions { /** Max records to return (default depends on adapter) */ limit?: number; /** Number of records to skip (for pagination) */ offset?: number; /** Search query over human-readable names and descriptions */ search?: string; } /** * Contract for admin panel adapter implementations. * * Provides operations for admin dashboards to manage users, roles, teams, and * view metrics. * Implementations handle permissions, audit logging, and data export for * compliance and analysis purposes. * * @example * ```ts * import type { AdminAdapter } from '@geenius/adapters'; * import { resolveAdapter } from '@geenius/adapters'; * * const admin: AdminAdapter = resolveAdapter('admin'); * const logger = resolveAdapter('logger'); * * // Get dashboard metrics * const metrics = await admin.getMetrics(); * await logger.info('Admin metrics loaded', { * activeUsers: metrics.activeUsers, * mrr: metrics.mrr, * }); * * // List users with search * const users = await admin.listUsers({ * limit: 20, * offset: 0, * search: 'alice@example' * }); * * for (const user of users) { * if (user.isBanned) { * await logger.warn('Managed user is banned', { userId: user.id }); * } * } * * // Ban a user * await admin.banUser('user-123'); * * // Delete a user (GDPR/compliance) * await admin.deleteUser('user-456'); * ``` */ interface AdminAdapter { /** * List all users with optional pagination and search. * Returns user metadata including status, subscription, and last login. * * @param options - Configuration for pagination and filtering * @param options.limit - Max users to return (default depends on adapter) * @param options.offset - Number of users to skip (for pagination) * @param options.search - Search query (searches name/email, partial match) * @returns Promise resolving to array of managed user objects * @throws {AdminError} with code 'OPERATION_FAILED' if query fails * * @example * ```ts * // Get first 50 users * const users = await admin.listUsers({ limit: 50, offset: 0 }); * * // Search for users by name * const results = await admin.listUsers({ search: 'alice', limit: 10 }); * ``` */ listUsers(options?: AdminListOptions): Promise; /** * Get a single user by their ID. * Includes full user metadata and administrative status. * * @param id - The unique ID of the user to fetch * @returns Promise resolving to the user object, or null if not found * * @example * ```ts * const user = await admin.getUser('user-123'); * if (user) { * await logger.info('Managed user loaded', { * userId: user.id, * plan: user.plan, * isBanned: user.isBanned, * }); * } * ``` */ getUser(id: string): Promise; /** * Ban a user from using the platform. * Prevents the user from logging in or accessing services. * Ban persists until unbanUser() is called. * * @param id - The ID of the user to ban * @returns Promise resolving to true if user was banned, false if already banned or not found * @throws {AdminError} with code 'OPERATION_FAILED' if ban operation fails * * @example * ```ts * // Ban user for violating terms * const wasBanned = await admin.banUser('user-789'); * if (wasBanned) { * await logger.warn('Managed user banned', { userId: 'user-789' }); * // Notify user of ban and appeal process * await sendBanNotification('user-789'); * } * ``` */ banUser(id: string): Promise; /** * Lift a ban on a user. * Restores the user's access to the platform. * * @param id - The ID of the user to unban * @returns Promise resolving to true if user was unbanned, false if not banned or not found * @throws {AdminError} with code 'OPERATION_FAILED' if unban operation fails * * @example * ```ts * // Appeal approved - restore user access * await admin.unbanUser('user-789'); * await logger.info('Managed user ban lifted', { userId: 'user-789' }); * ``` */ unbanUser(id: string): Promise; /** * Permanently delete a user account. * Removes user data and access. Operation is typically irreversible. * Should trigger data export for compliance purposes. * * @param id - The ID of the user to delete * @returns Promise resolving to true if user was deleted, false if not found * @throws {AdminError} with code 'OPERATION_FAILED' if deletion fails * * @example * ```ts * // Delete user per GDPR right-to-be-forgotten request * const deleted = await admin.deleteUser('user-456'); * if (deleted) { * await logger.warn('Managed user permanently deleted', { userId: 'user-456' }); * // Log for compliance audit * await auditLog('user_deleted', 'user-456', admin.id); * } * ``` */ deleteUser(id: string): Promise; /** * List roles with optional pagination and search. * Returns operator-facing role metadata and permission identifiers. * * @param options - Configuration for pagination and filtering * @returns Promise resolving to matching role records * @throws {AdminError} with code 'OPERATION_FAILED' if query fails */ listRoles(options?: AdminListOptions): Promise; /** * Get a single role by id. * * @param id - The unique id of the role to fetch * @returns Promise resolving to the role object, or null if not found * @throws {AdminError} with code 'OPERATION_FAILED' if lookup fails */ getRole(id: string): Promise; /** * Create or update a role. * Local adapters generate an id when the input omits one; provider adapters may * validate ids against their own policy backend. * * @param input - Role metadata and permissions to persist * @returns Promise resolving to the stored role * @throws {AdminError} with code 'OPERATION_FAILED' if persistence fails */ upsertRole(input: AdminRoleInput): Promise; /** * Delete a role and remove it from direct user and team assignments. * * @param id - The unique id of the role to delete * @returns Promise resolving to true if a role was deleted * @throws {AdminError} with code 'OPERATION_FAILED' if deletion fails */ deleteRole(id: string): Promise; /** * Assign a role directly to a user. * * @param userId - The user receiving the role * @param roleId - The role to assign * @returns Promise resolving to true when the assignment changed * @throws {AdminError} with code 'OPERATION_FAILED' if persistence fails */ assignUserRole(userId: string, roleId: string): Promise; /** * Remove a directly assigned role from a user. * * @param userId - The user losing the role * @param roleId - The role to remove * @returns Promise resolving to true when the assignment changed * @throws {AdminError} with code 'OPERATION_FAILED' if persistence fails */ removeUserRole(userId: string, roleId: string): Promise; /** * List teams with optional pagination and search. * Returns memberships and team-level role assignments. * * @param options - Configuration for pagination and filtering * @returns Promise resolving to matching team records * @throws {AdminError} with code 'OPERATION_FAILED' if query fails */ listTeams(options?: AdminListOptions): Promise; /** * Get a single team by id. * * @param id - The unique id of the team to fetch * @returns Promise resolving to the team object, or null if not found * @throws {AdminError} with code 'OPERATION_FAILED' if lookup fails */ getTeam(id: string): Promise; /** * Create or update a team. * * @param input - Team metadata, members, and team roles to persist * @returns Promise resolving to the stored team * @throws {AdminError} with code 'OPERATION_FAILED' if persistence fails */ upsertTeam(input: AdminTeamInput): Promise; /** * Delete a team and remove the team id from users. * * @param id - The unique id of the team to delete * @returns Promise resolving to true if a team was deleted * @throws {AdminError} with code 'OPERATION_FAILED' if deletion fails */ deleteTeam(id: string): Promise; /** * Add a user to a team. * * @param teamId - The team receiving the user * @param userId - The user to add * @returns Promise resolving to true when the membership changed * @throws {AdminError} with code 'OPERATION_FAILED' if persistence fails */ addTeamMember(teamId: string, userId: string): Promise; /** * Remove a user from a team. * * @param teamId - The team losing the user * @param userId - The user to remove * @returns Promise resolving to true when the membership changed * @throws {AdminError} with code 'OPERATION_FAILED' if persistence fails */ removeTeamMember(teamId: string, userId: string): Promise; /** * Assign a role to a team. * * @param teamId - The team receiving the role * @param roleId - The role to assign * @returns Promise resolving to true when the assignment changed * @throws {AdminError} with code 'OPERATION_FAILED' if persistence fails */ assignTeamRole(teamId: string, roleId: string): Promise; /** * Remove a role from a team. * * @param teamId - The team losing the role * @param roleId - The role to remove * @returns Promise resolving to true when the assignment changed * @throws {AdminError} with code 'OPERATION_FAILED' if persistence fails */ removeTeamRole(teamId: string, roleId: string): Promise; /** * Get high-level business and usage metrics for the dashboard. * Provides KPIs for monitoring platform health and growth. * * @returns Promise resolving to metrics object with counts and revenue data * @throws {AdminError} with code 'OPERATION_FAILED' if metric fetch fails * * @example * ```ts * const metrics = await admin.getMetrics(); * * // Display on dashboard * const dashboard = { * totalUsers: metrics.totalUsers, * activeThisMonth: metrics.activeUsers, * newToday: metrics.newUsersToday, * revenue: { * total: metrics.totalRevenue, * monthly: metrics.mrr * } * }; * * // Growth analysis * if (metrics.newUsersToday > metrics.activeUsers * 0.1) { * await logger.info('Strong signup rate today', { * newUsersToday: metrics.newUsersToday, * }); * } * ``` */ getMetrics(): Promise; } /** * @module interface * @description Declares the shared AI adapter contract used by the adapters * package. The interfaces define chat, completion, embedding, and streaming * operations consumed by AI-capable runtime variants. */ /** * Contract for AI/LLM adapter implementations. * * Defines the core operations for interacting with language models: * - Chat completions (conversation-style interactions) * - Text completions (single-prompt completions) * - Embeddings (semantic text vectors) * - Streaming (token-by-token output) * * Implementations abstract away provider-specific details (API keys, endpoints, model selection) * and normalize responses into a common format. * * @example * ```ts * import type { AiAdapter } from '@geenius/adapters'; * import { resolveAdapter } from '@geenius/adapters'; * * const ai: AiAdapter = resolveAdapter('ai'); * * // Chat completion * const response = await ai.chat([ * { role: 'user', content: 'What is 2+2?' } * ]); * logger.info(response.content); // "The answer is 4." * * // Text completion * const text = await ai.complete('The sky is ', { * maxTokens: 10 * }); * * // Embeddings * const vectors = await ai.embed(['apple', 'orange', 'banana']); * // vectors[0] has embedding for 'apple', etc. * * // Streaming * const stream = await ai.stream([ * { role: 'user', content: 'Write a poem' } * ]); * for await (const token of stream) { * process.stdout.write(token); * } * ``` */ interface AiAdapter { /** * Generate a response to a multi-turn conversation. * Implements standard chat completion semantics (system prompts, role-based messages). * * @param messages - Array of messages in conversation history order * @param options - Configuration for model behavior and constraints * @returns A promise resolving to the model's response * @throws {AiError} with code 'MODEL_ERROR' if the model fails * @throws {AiError} with code 'RATE_LIMIT' if rate limit is exceeded * @throws {AiError} with code 'CONTEXT_LENGTH' if message history exceeds context window * @throws {AiError} with code 'INVALID_INPUT' if messages are malformed * * @example * ```ts * const response = await ai.chat([ * { * role: 'system', * content: 'You are a helpful math tutor.' * }, * { * role: 'user', * content: 'What is the integral of x^2?' * } * ], { * model: 'gpt-4', * temperature: 0.7, * maxTokens: 500 * }); * * logger.info(response.content); * if (response.usage) { * logger.info(`Used ${response.usage.totalTokens} tokens`); * } * ``` */ chat(messages: ChatMessage[], options?: AiOptions): Promise; /** * Generate text completion for a single prompt. * Simpler than chat() for non-conversational use cases. * * @param prompt - The text prompt to complete * @param options - Configuration for model behavior * @returns A promise resolving to the completed text * @throws {AiError} with code 'MODEL_ERROR' if the model fails * @throws {AiError} with code 'RATE_LIMIT' if rate limit is exceeded * @throws {AiError} with code 'CONTEXT_LENGTH' if prompt is too long * * @example * ```ts * const text = await ai.complete( * 'Translate to Spanish: Hello, how are you?\n\n', * { maxTokens: 50, temperature: 0 } * ); * // Returns something like "Hola, ¿cómo estás?" * ``` */ complete(prompt: string, options?: AiOptions): Promise; /** * Generate semantic embeddings (vector representations) for text. * Embeddings enable similarity search, clustering, and recommendation features. * * @param text - Single text string or array of strings to embed * @returns A promise resolving to a 2D array of embedding vectors * (one vector per input string, each vector is an array of numbers) * @throws {AiError} with code 'EMBEDDING_ERROR' if embedding fails * @throws {AiError} with code 'RATE_LIMIT' if rate limit is exceeded * * @example * ```ts * // Single text * const [vector] = await ai.embed('The quick brown fox'); * logger.info(vector.length); // e.g., 1536 (depends on model) * * // Multiple texts * const vectors = await ai.embed([ * 'product description A', * 'product description B', * 'user query' * ]); * * // Compute similarity between user query and products * const similarity = cosineSimilarity(vectors[2], vectors[0]); * ``` */ embed(text: string | string[]): Promise; /** * Stream chat completion tokens one-by-one while the model emits them. * Enables real-time response display without waiting for full completion. * * @param messages - Array of messages in conversation history order * @param options - Configuration for model behavior and constraints * @returns A promise resolving to an async iterable that yields text tokens in string form * @throws {AiError} with code 'MODEL_ERROR' if the model fails * @throws {AiError} with code 'RATE_LIMIT' if rate limit is exceeded * * @example * ```ts * // Browser with Server-Sent Events or WebSocket * const stream = await ai.stream([ * { role: 'user', content: 'Tell me a joke' } * ]); * for await (const token of stream) { * // Append token to DOM in real-time * responseElement.textContent += token; * } * * // Node.js with streaming response * let fullResponse = ''; * const stream = await ai.stream([ * { role: 'user', content: 'Write code to fizzbuzz' } * ], { maxTokens: 1000 }); * for await (const token of stream) { * fullResponse += token; * process.stdout.write(token); // Live output * } * ``` */ stream(messages: ChatMessage[], options?: AiOptions): Promise>; } /** * @module interface * @description Declares the shared authentication adapter contract used by the * adapters package. The interfaces define credential, OAuth, session, and * profile-management operations consumed by auth-capable runtime variants. */ /** * Identifier for third-party OAuth providers. * Includes common providers (Google, GitHub, etc.) and allows for custom providers via string. */ type OAuthProvider = "google" | "github" | "discord" | "twitter" | "apple" | "microsoft" | string; /** * Contract for authentication adapter implementations. * * Defines the core authentication operations that every auth provider must support: * - Password-based sign in/up * - OAuth sign in flows * - Session and user retrieval * - User profile updates * * Implementations handle credential storage, password hashing, session tokens, * OAuth token exchange, and user metadata persistence. * * @example * ```ts * import type { AuthAdapter } from '@geenius/adapters'; * import { resolveAdapter } from '@geenius/adapters'; * * const auth: AuthAdapter = resolveAdapter('auth'); * * // Sign up with password * const session = await auth.signUp('user@example.com', 'password123', 'John Doe'); * * // Sign in * const session = await auth.signIn('user@example.com', 'password123'); * * // OAuth sign in * const oauthUrl = await auth.signInWithOAuth('google', { * redirectUrl: 'https://app.example.com/auth/callback' * }); * // Redirect user to oauthUrl.url * * // Get current user * const user = await auth.getUser(); * if (user) { * logger.info(`Logged in: ${user.name}`); * } * * // Update profile * await auth.updateUser({ name: 'Jane Doe' }); * * // Sign out * await auth.signOut(); * ``` */ interface AuthAdapter { /** * Authenticate a user with email and password. * Validates credentials and creates an authenticated session. * * @param email - The user's email address (case-insensitive) * @param password - The user's plain-text password (will be securely compared) * @returns A promise resolving to an active AuthSession with user details * @throws {AuthError} with code 'INVALID_CREDENTIALS' if email/password don't match or user doesn't exist * @throws {AuthError} with code 'UNAUTHORIZED' if account is disabled * @throws {AuthError} with code 'SERVICE_ERROR' if provider or session persistence fails * * @example * ```ts * try { * const session = await auth.signIn('alice@example.com', 'mypassword'); * logger.info('Welcome back, ' + session.user?.name); * } catch (error) { * if (error.code === 'INVALID_CREDENTIALS') { * logger.error('Invalid email or password'); * } * } * ``` */ signIn(email: string, password: string): Promise; /** * Register a new user with password-based authentication. * Creates a new user account and returns an authenticated session. * * @param email - The email address for the new account (must be unique) * @param password - The plain-text password (will be securely hashed and stored) * @param name - Optional display name for the user * @returns A promise resolving to the created AuthSession * @throws {AuthError} with code 'USER_EXISTS' if email is already registered * @throws {AuthError} with code 'SERVICE_ERROR' if account or session persistence fails * * @example * ```ts * const session = await auth.signUp( * 'newuser@example.com', * 'securePassword123!', * 'New User' * ); * ``` */ signUp(email: string, password: string, name?: string): Promise; /** * Initiate an OAuth (third-party) authentication flow. * Generates an authorization URL that should be opened in the user's browser. * * @param provider - The OAuth provider identifier (e.g., 'google', 'github') * @param options - Optional configuration for the OAuth flow * @param options.redirectUrl - URL to redirect to after OAuth completes (provider-specific) * @returns A promise resolving to an object with a `url` property for redirection * @throws {AuthError} with code 'OAUTH_ERROR' if provider config is invalid * @throws {AuthError} with code 'SERVICE_ERROR' if OAuth service is unavailable * * @example * ```ts * // Get Google OAuth URL * const appOrigin = 'https://app.example.com'; * const { url } = await auth.signInWithOAuth('google', { * redirectUrl: `${appOrigin}/auth/callback` * }); * * // Redirect user's browser to OAuth provider * navigateTo(url); * ``` */ signInWithOAuth(provider: OAuthProvider, options?: { redirectUrl?: string; }): Promise<{ url: string; }>; /** * End the current user session and clear authentication state. * Invalidates the session token and removes persisted authentication data. * * @returns A promise that resolves when sign out is complete * * @example * ```ts * await auth.signOut(); * // User is now unauthenticated * const user = await auth.getUser(); // Returns null * ``` */ signOut(): Promise; /** * Retrieve the currently active authentication session. * Returns the full session object including token and user details. * * @returns A promise resolving to the active AuthSession, or null if not authenticated * @throws {AuthError} with code 'UNAUTHORIZED' if the session user is banned * * @example * ```ts * const session = await auth.getSession(); * if (session && session.sessionToken) { * logger.info('Token expires at:', session.expiresAt); * } * ``` */ getSession(): Promise; /** * Retrieve the currently authenticated user's profile information. * Lighter than getSession() if you only need user details. * * @returns A promise resolving to the AuthUser, or null if not authenticated * * @example * ```ts * const user = await auth.getUser(); * if (user) { * return {user.name}; * } * ``` */ getUser(): Promise; /** * Update the currently authenticated user's profile information. * Only updatable fields (name, image) can be changed via this method. * * @param updates - Partial object with `name` and/or `image` fields to update * @returns A promise resolving to the updated AuthUser, or null if the session user no longer exists * @throws {AuthError} with code 'UNAUTHORIZED' if user is not authenticated * @throws {AuthError} with code 'SERVICE_ERROR' if profile persistence fails * * @example * ```ts * const updated = await auth.updateUser({ * name: 'Jane Doe', * image: 'https://example.com/avatar.jpg' * }); * ``` */ updateUser(updates: Partial>): Promise; } /** * @module interface * @description Declares the shared database adapter contract used by the * adapters package. The interface defines CRUD and query operations consumed * by database-capable runtime variants. */ /** * Contract for database adapter implementations. * * Defines the core CRUD (Create, Read, Update, Delete) and query operations * that every database provider must support. Implementations may extend these * methods with provider-specific overloads or additional features. * * All collections are dynamically named at runtime - there's no schema registration. * Records automatically include an `id` field (string) for the primary key. * * @example * ```ts * import type { DbAdapter } from '@geenius/adapters'; * import { resolveAdapter } from '@geenius/adapters'; * * const db: DbAdapter = resolveAdapter('db'); * * // Create * const user = await db.create('users', { * name: 'Alice', * email: 'alice@example.com', * }); * logger.info(user.id); // auto-generated ID * * // Read * const fetched = await db.get('users', user.id); * * // Update * const updated = await db.update('users', user.id, { name: 'Alice Smith' }); * * // Query * const admins = await db.query('users', [ * { field: 'role', operator: 'eq', value: 'admin' } * ]); * * // Count * const adminCount = await db.count('users', [ * { field: 'role', operator: 'eq', value: 'admin' } * ]); * * // Delete * const deleted = await db.delete('users', user.id); * ``` */ interface DbAdapter { /** * Create a new record in a collection. * Auto-generates a unique ID and stores the record with the provided fields. * * @typeParam T - The type of the full record (including the auto-generated id) * @param collection - The name of the collection or table to insert into * @param data - The record data (all fields except `id`, which is auto-generated) * @returns A promise resolving to the created record with its generated `id` * @throws {DbError} with code 'CONSTRAINT_VIOLATION' if unique constraints fail * @throws {DbError} with code 'COLLECTION_NOT_CONFIGURED' if collection doesn't exist * * @example * ```ts * const newUser = await db.create('users', { * name: 'Bob', * email: 'bob@example.com' * }); * logger.info(newUser.id); // '65a1b2c3d4e5f6g7h8i9j0k1' * ``` */ create>(collection: string, data: Omit): Promise; /** * Retrieve a single record by its ID. * Returns null if the record doesn't exist (not an error). * * @typeParam T - The type of the record to retrieve * @param collection - The name of the collection or table to query * @param id - The record's unique identifier (primary key) * @returns A promise resolving to the record if found, or null if not found * @throws {DbError} with code 'COLLECTION_NOT_CONFIGURED' if collection doesn't exist * * @example * ```ts * const user = await db.get('users', 'user-123'); * if (user) { * logger.info(user.name); * } else { * logger.info('User not found'); * } * ``` */ get(collection: string, id: string): Promise; /** * Partially update an existing record. * Only provided fields are updated; other fields remain unchanged. * Returns null if the record doesn't exist (not an error). * * @typeParam T - The type of the record after update * @param collection - The name of the collection or table to update * @param id - The unique identifier of the record to update * @param data - Partial fields to merge into the existing record * @returns A promise resolving to the updated record if found, or null if not found * @throws {DbError} with code 'CONSTRAINT_VIOLATION' if unique constraints fail * * @example * ```ts * const updated = await db.update('users', 'user-123', { * lastLogin: new Date().toISOString() * }); * ``` */ update>(collection: string, id: string, data: Partial): Promise; /** * Delete a record by its ID. * Idempotent - deleting a non-existent record returns false, not an error. * * @param collection - The name of the collection or table to delete from * @param id - The unique identifier of the record to delete * @returns A promise resolving to true if a record was deleted, false if not found * @throws {DbError} with code 'COLLECTION_NOT_CONFIGURED' if collection doesn't exist * * @example * ```ts * const wasDeleted = await db.delete('users', 'user-123'); * if (wasDeleted) { * logger.info('User deleted'); * } * ``` */ delete(collection: string, id: string): Promise; /** * Retrieve multiple records from a collection with optional pagination and sorting. * Returns all records if options are omitted. * * @typeParam T - The type of records being listed * @param collection - The name of the collection or table to list from * @param options - Optional pagination and sorting configuration * @returns A promise resolving to an array of records (may be empty) * @throws {DbError} with code 'COLLECTION_NOT_CONFIGURED' if collection doesn't exist * * @example * ```ts * // Get all users * const allUsers = await db.list('users'); * * // Get page 2 (10 per page), sorted by name * const page2 = await db.list('users', { * limit: 10, * offset: 10, * orderBy: 'name', * order: 'asc' * }); * ``` */ list(collection: string, options?: ListOptions): Promise; /** * Retrieve records matching specific filter conditions. * All conditions must be satisfied (AND logic). * * @typeParam T - The type of records being queried * @param collection - The name of the collection or table to query * @param filter - Array of conditions that must all match for a record to be returned * @returns A promise resolving to an array of matching records (may be empty) * @throws {DbError} with code 'QUERY_ERROR' if the query is invalid * @throws {DbError} with code 'COLLECTION_NOT_CONFIGURED' if collection doesn't exist * * @example * ```ts * // Find all active users created after a date * const activeUsers = await db.query('users', [ * { field: 'active', operator: 'eq', value: true }, * { field: 'createdAt', operator: 'gte', value: '2024-01-01' } * ]); * * // Find users with name containing 'al' (case-sensitive) * const matches = await db.query('users', [ * { field: 'name', operator: 'contains', value: 'al' } * ]); * ``` */ query(collection: string, filter: QueryFilter): Promise; /** * Count records in a collection, optionally filtered by conditions. * Efficient count operation without fetching full records. * * @param collection - The name of the collection or table * @param filter - Optional conditions to count only matching records * @returns A promise resolving to the count of matching records * @throws {DbError} with code 'QUERY_ERROR' if the filter is invalid * @throws {DbError} with code 'COLLECTION_NOT_CONFIGURED' if collection doesn't exist * * @example * ```ts * // Count all users * const totalUsers = await db.count('users'); * * // Count active users * const activeUsers = await db.count('users', [ * { field: 'active', operator: 'eq', value: true } * ]); * ``` */ count(collection: string, filter?: QueryFilter): Promise; } /** * @module interface * @description Declares the shared file storage adapter contract used by the * adapters package. The interface defines upload, download, listing, and URL * generation workflows consumed by storage-capable runtime variants. */ /** * Upload options for file storage adapters. * Metadata is stored with the file record, while the binary payload remains * provider-private and is retrieved through `download()`. */ interface FileUploadOptions { /** Optional custom filename; when omitted adapters use File.name or generate one */ name?: string; /** Caller-controlled metadata to persist with the file record */ metadata?: FileStorageMetadata; } /** * Options for the localStorage-backed file adapter used by tests, Storybook, * and offline prototypes. */ interface LocalStorageFileAdapterOptions { /** Maximum accepted Blob/File payload size in bytes before base64 conversion */ maxPayloadBytes?: number; } /** * Contract for file storage adapter implementations. * * Handles file lifecycle operations across multiple providers (S3, R2, Uploadthing, etc.). * Provides a unified interface for file management with support for hierarchical storage, * metadata tracking, and public/private access control. * * Files are identified by unique IDs and organized using path prefixes. * All operations are async and handle provider-specific details transparently. * * @example * ```ts * import type { FileStorageAdapter } from '@geenius/adapters'; * import { resolveAdapter } from '@geenius/adapters'; * * const storage: FileStorageAdapter = resolveAdapter('storage'); * * // Upload a file * const file = await pickFileFromRuntime(); * const stored = await storage.upload(file, 'user-123/documents', 'resume.pdf'); * logger.info(stored.id); // unique file ID * * // Get public URL * const url = await storage.getUrl(stored.id); * logger.info(url); // https://storage.example.com/file-uuid * * // List files in a directory * const files = await storage.list('user-123/documents'); * files.forEach(f => { * logger.info(`${f.name} (${f.size} bytes)`); * }); * * // Download a file * const blob = await storage.download(stored.id); * const url = URL.createObjectURL(blob); * await saveBlobForRuntime(blob, stored.name); * * // Delete a file * const deleted = await storage.delete(stored.id); * if (deleted) { * logger.info('File deleted'); * } * ``` */ interface FileStorageAdapter { /** * Upload a file to storage. * Stores the file and returns metadata including a unique ID and public URL. * * @param file - The File or Blob object to upload * @param path - Storage path/prefix to organize files (e.g., 'user-123/documents') * @param nameOrOptions - Optional custom filename or upload options with metadata * @returns A promise resolving to metadata about the uploaded file * @throws {StorageError} with code 'UPLOAD_FAILED' if upload fails * @throws {StorageError} with code 'PAYLOAD_TOO_LARGE' if the payload exceeds adapter limits * @throws {StorageError} with code 'QUOTA_EXCEEDED' if storage quota is full * * @example * ```ts * const blob = await canvasElement.convertToBlob(); * const stored = await storage.upload(blob, 'user-123/images', 'canvas.png'); * logger.info(`Stored at: ${stored.url}`); * ``` */ upload(file: File | Blob, path: string, nameOrOptions?: string | FileUploadOptions): Promise; /** * Download a file's content in Blob form. * Retrieves the raw file data for processing or display. * * @param fileId - The unique identifier of the file to download * @returns A promise resolving to the file's Blob content * @throws {StorageError} with code 'NOT_FOUND' if file doesn't exist * @throws {StorageError} with code 'DOWNLOAD_FAILED' if download fails * * @example * ```ts * const blob = await storage.download('file-uuid-123'); * const image = new Image(); * image.src = URL.createObjectURL(blob); * await renderImageForRuntime(image); * ``` */ download(fileId: string): Promise; /** * Delete a file from storage. * Removes the file and frees up quota. Idempotent - deleting non-existent files returns false. * * @param fileId - The unique identifier of the file to delete * @returns A promise resolving to true if a file was deleted, false if not found * @throws {StorageError} with code 'SERVICE_ERROR' if deletion service is unavailable * * @example * ```ts * const wasDeleted = await storage.delete('file-uuid-123'); * if (wasDeleted) { * logger.info('File removed'); * } * ``` */ delete(fileId: string): Promise; /** * List all files stored at a given path prefix. * Returns metadata for files matching the prefix (similar to directory listing). * * @param prefix - Optional path prefix to filter results (e.g., 'user-123/') * @returns A promise resolving to an array of file metadata (may be empty) * @throws {StorageError} with code 'SERVICE_ERROR' if listing fails * * @example * ```ts * // List all files in a user's directory * const userFiles = await storage.list('user-123/'); * * // List all files in a subdirectory * const documentFiles = await storage.list('user-123/documents/'); * * // List all files in storage * const allFiles = await storage.list(); * ``` */ list(prefix?: string): Promise; /** * Get the public or authenticated URL for a file. * Used to access the file in a browser or via HTTP GET requests. * * @param fileId - The unique identifier of the file * @returns A promise resolving to the file's access URL * @throws {StorageError} with code 'NOT_FOUND' if file doesn't exist * @throws {StorageError} with code 'SERVICE_ERROR' if URL generation fails * * @example * ```ts * const url = await storage.getUrl('file-uuid-123'); * // Use in HTML * await renderImageUrlForRuntime(url); * * // Or create a download link * await renderDownloadLinkForRuntime(url); * ``` */ getUrl(fileId: string): Promise; } /** * @module interface * @description Declares the shared logger adapter contract used across the * adapters package. The interfaces define structured logging behavior and * contextual log metadata for runtime integrations. */ /** * Log level severity, ordered from least to most severe. * Used to control what logs are displayed or stored. */ type LogLevel = "debug" | "info" | "warn" | "error"; /** * Structured metadata object attached to log entries. * Enables rich, queryable log data instead of unstructured strings. * Typical keys: userId, requestId, provider, latency, error, etc. */ interface LogMeta { [key: string]: unknown; } /** * Contract for logger adapter implementations. * * All Geenius packages should use this interface instead of logger.info directly. * This decoupling allows: * - Swapping backends (console → Pino → Datadog → custom) with config * - Structured logging with metadata * - Hierarchical/scoped loggers with context inheritance * - Consistent log formatting across the application * * @example * ```ts * import type { LoggerAdapter } from '@geenius/adapters'; * import { createConsoleLoggerAdapter } from '@geenius/adapters'; * * const logger: LoggerAdapter = createConsoleLoggerAdapter(); * * // Basic logging * await logger.info('User signed in', { userId: 'user-123' }); * await logger.warn('High latency detected', { duration: 1500 }); * await logger.error('Database query failed', { error: err.message, query: 'SELECT *' }); * * // Child logger with scoped metadata * const dbLogger = await logger.child({ adapter: 'db', provider: 'convex' }); * await dbLogger.debug('Executing query', { collection: 'users', operation: 'create' }); * // Output includes: { message, level, adapter, provider, collection, operation } * * // Nested child loggers * const userServiceLogger = await dbLogger.child({ service: 'user-service' }); * await userServiceLogger.info('User created', { userId: 'new-id' }); * // Output includes: { adapter, provider, service, userId } * ``` */ interface LoggerAdapter { /** * Log a debug-level message (least severe, typically disabled in production). * Used for detailed diagnostic information during development and troubleshooting. * * @param message - The log message * @param meta - Optional structured metadata to include in the log entry * * @example * ```ts * await logger.debug('Request payload', { headers, body }); * ``` */ debug(message: string, meta?: LogMeta): Promise; /** * Log an info-level message (general information, normal flow). * Used to track significant events and state changes. * * @param message - The log message * @param meta - Optional structured metadata to include in the log entry * * @example * ```ts * await logger.info('Adapter initialized', { provider: 'convex', version: '1.0.0' }); * ``` */ info(message: string, meta?: LogMeta): Promise; /** * Log a warning-level message (potential problems, unusual conditions). * Used for recoverable issues that might need attention. * * @param message - The log message * @param meta - Optional structured metadata to include in the log entry * * @example * ```ts * await logger.warn('API rate limit approaching', { remaining: 10, resetAt: timestamp }); * ``` */ warn(message: string, meta?: LogMeta): Promise; /** * Log an error-level message (most severe, errors that need attention). * Used for failures and exceptions. * * @param message - The log message * @param meta - Optional structured metadata including error details * * @example * ```ts * try { * await operation(); * } catch (error) { * await logger.error('Operation failed', { * error: error.message, * stack: error.stack, * context: 'user-creation' * }); * } * ``` */ error(message: string, meta?: LogMeta): Promise; /** * Create a child logger with default metadata. * All subsequent logs from this child include the provided metadata, * enabling contextual logging without repeating metadata in each call. * * Child loggers can be further nested - metadata accumulates through the hierarchy. * Useful for adding scope/context like adapter name, service name, request ID, etc. * * @param defaultMeta - Metadata that will be merged into every log from this child * @returns A promise resolving to a new LoggerAdapter with the provided default metadata * * @example * ```ts * // Create a scoped logger for database operations * const dbLogger = await logger.child({ * adapter: 'db', * provider: 'convex' * }); * * // These logs automatically include adapter and provider metadata * await dbLogger.info('Connected to database'); * await dbLogger.debug('Executing query', { collection: 'users' }); * * // Further nesting * const queryLogger = await dbLogger.child({ type: 'write' }); * await queryLogger.info('Insert completed'); * // Log includes: adapter, provider, type, and the explicit 'Insert completed' message * ``` */ child(defaultMeta: LogMeta): Promise; } /** * @module memory * @description Implements an in-memory logger transport for tests, Storybook * fixtures, and offline prototypes that need to assert structured log output. */ /** Structured entry captured by the memory logger transport. */ interface MemoryLogEntry { /** ISO 8601 timestamp captured when the entry was written */ timestamp: string; /** Entry severity level */ level: LogLevel; /** Human-readable log message */ message: string; /** Merged default and per-entry metadata */ meta?: LogMeta; } /** Configuration for the in-memory logger transport. */ interface MemoryLoggerOptions { /** Minimum log level to capture. Defaults to debug. */ minLevel?: LogLevel; /** Existing entry buffer to append to, useful for composing test fixtures. */ entries?: MemoryLogEntry[]; /** Clock hook for deterministic tests. */ now?: () => Date; } /** * Logger adapter with test-friendly access to captured entries. */ interface MemoryLoggerAdapter extends LoggerAdapter { /** Frozen cloned snapshot of captured log entries. */ readonly entries: readonly Readonly[]; /** Snapshot captured entries so assertions cannot mutate the live buffer. */ getEntries(): MemoryLogEntry[]; /** Clear captured entries from the shared buffer. */ clear(): void; /** Create a child memory logger that appends to the same captured buffer. */ child(defaultMeta: LogMeta): Promise; } /** * Creates an in-memory structured logger for test and local review flows. * * @param options - Capture behavior, injected buffer, and clock configuration * @returns A memory logger with captured-entry helpers and child metadata support */ declare function createMemoryLoggerAdapter(options?: MemoryLoggerOptions): MemoryLoggerAdapter; /** * @module interface * @description Declares the shared payments adapter contract used by the * adapters package. The interface defines plan, checkout, and subscription * workflows consumed by payments-capable runtime variants. */ /** * Contract for payment processing adapter implementations. * * Handles subscription management, billing workflows, plan configuration, * and feature access control. Integrates with payment providers (Stripe, etc.) * to manage recurring billing and customer billing state. * * Implementations handle webhooks, plan synchronization, and subscription status * tracking transparently. * * @example * ```ts * import type { PaymentsAdapter } from '@geenius/adapters'; * import { resolveAdapter } from '@geenius/adapters'; * * const payments: PaymentsAdapter = resolveAdapter('payments'); * * // Get available plans * const plans = await payments.getPlans(); * plans.forEach(plan => { * logger.info(`${plan.name}: $${plan.price}/${plan.interval}`); * }); * * // Start checkout for a plan * const checkout = await payments.createCheckout({ * planId: 'pro-plan', * userId: 'user-123', * successUrl: 'https://app.example.com/success', * cancelUrl: 'https://app.example.com/cancel' * }); * // Redirect user to checkout.url * * // Check user's subscription * const subscription = await payments.getSubscription('user-123'); * if (subscription && subscription.status === 'active') { * logger.info('User has active subscription'); * } * * // Feature gating - check if user can access feature * const canExport = await payments.isFeatureEnabled('user-123', 'export'); * if (canExport) { * showExportButton(); * } * * // Cancel subscription * await payments.cancelSubscription('sub-123'); * ``` */ interface PaymentsAdapter { /** * Initiate a checkout session for purchasing or upgrading to a plan. * Generates a checkout URL that should be opened in the user's browser. * * @param params - Configuration for the checkout session * @param params.planId - ID of the plan being purchased * @param params.userId - ID of the user initiating checkout * @param params.successUrl - Optional redirect URL after successful payment * @param params.cancelUrl - Optional redirect URL if user cancels checkout * @returns Promise resolving to the checkout session with redirect URL * @throws {PaymentsError} with code 'INVALID_PLAN' if plan doesn't exist * @throws {PaymentsError} with code 'CHECKOUT_FAILED' if checkout creation fails * @throws {PaymentsError} with code 'SERVICE_ERROR' if payment service is unavailable * * @example * ```ts * const appOrigin = 'https://app.example.com'; * const result = await payments.createCheckout({ * planId: 'team-monthly', * userId: currentUser.id, * successUrl: `${appOrigin}/dashboard`, * cancelUrl: `${appOrigin}/pricing` * }); * * // Redirect to payment provider * navigateTo(result.url); * ``` */ createCheckout(params: CheckoutParams): Promise; /** * Get the current subscription for a user. * Returns the user's active subscription if they have one. * * @param userId - The ID of the user to check * @returns Promise resolving to the user's subscription, or null if none exists * @throws {PaymentsError} with code 'SERVICE_ERROR' if lookup fails * * @example * ```ts * const subscription = await payments.getSubscription(userId); * * if (!subscription) { * // User has no subscription, show upgrade prompt * showUpgradePrompt(); * } else if (subscription.status === 'active') { * // User has active subscription * logger.info(`Plan: ${subscription.planId}, expires: ${subscription.currentPeriodEnd}`); * } else if (subscription.status === 'past_due') { * // Payment failed, show payment retry UI * showRetryPaymentUI(); * } * ``` */ getSubscription(userId: string): Promise; /** * Cancel a subscription immediately. * Removes access to paid features. Can be immediately effective or at period end depending on provider. * * @param subscriptionId - The ID of the subscription to cancel * @returns A promise that resolves when cancellation is complete * @throws {PaymentsError} with code 'SUBSCRIPTION_NOT_FOUND' if subscription doesn't exist * @throws {PaymentsError} with code 'CANCEL_FAILED' if cancellation fails * @throws {PaymentsError} with code 'SERVICE_ERROR' if payment service is unavailable * * @example * ```ts * const subscription = await payments.getSubscription(userId); * if (subscription) { * await payments.cancelSubscription(subscription.id); * logger.info('Subscription cancelled'); * } * ``` */ cancelSubscription(subscriptionId: string): Promise; /** * Get all available pricing plans. * Fetches the current list of plans from the payment provider. * * @returns Promise resolving to an array of available plans * @throws {PaymentsError} with code 'SERVICE_ERROR' if plan fetch fails * * @example * ```ts * const plans = await payments.getPlans(); * // Display plans on pricing page * renderPricingTable(plans.map(plan => ({ * name: plan.name, * price: `$${plan.price / 100}`, * features: plan.features * }))); * ``` */ getPlans(): Promise; /** * Check if a specific feature is enabled for a user. * Determines feature access based on subscription status and plan tier. * Useful for feature gating and progressive disclosure UI. * * @param userId - The ID of the user to check * @param feature - The feature name/identifier to check * @returns Promise resolving to true if feature is enabled, false otherwise * @throws {PaymentsError} with code 'SERVICE_ERROR' if feature check fails * * @example * ```ts * // Feature gating in UI * const canExport = await payments.isFeatureEnabled(userId, 'pdf-export'); * const canShare = await payments.isFeatureEnabled(userId, 'team-sharing'); * * if (canExport) { * showExportButton(); * } else { * showUpgradeButton('Export requires Pro plan'); * } * * // Bulk check multiple features * const features = await Promise.all([ * payments.isFeatureEnabled(userId, 'api-access'), * payments.isFeatureEnabled(userId, 'custom-domain'), * payments.isFeatureEnabled(userId, 'sso') * ]); * ``` */ isFeatureEnabled(userId: string, feature: string): Promise; } /** * @module types * @description Declares the shared domain models used across every adapters * package variant. These types define the cross-framework contract for adapter * inputs, outputs, status reporting, and provider configuration. */ /** * Represents an authenticated user with profile information. * Core user identity and metadata that can be extended by specific auth providers. * * @example * ```ts * const user: AuthUser = { id: "u1", email: "user@example.com" }; * ``` */ interface AuthUser { /** Unique identifier for the user, typically from the auth provider */ id: string; /** User's email address (may not be present for all auth types) */ email?: string; /** User's display name */ name?: string; /** URL to user's profile image or avatar */ image?: string; /** User's role or permission level (e.g., 'admin', 'user') */ role?: string; /** ISO 8601 timestamp when the user was created */ createdAt?: string; } /** * Represents an active authentication session. * Contains session metadata and associated user information. * * @example * ```ts * const session: AuthSession = { userId: "u1", user: { id: "u1" } }; * ``` */ interface AuthSession { /** The ID of the user associated with this session */ userId: string; /** Session token for API authentication (if applicable) */ sessionToken?: string; /** ISO 8601 timestamp when the session expires */ expiresAt?: string; /** Full user object associated with this session, or null when unavailable */ user: AuthUser | null; } /** * Pagination and sorting options for database queries. * Allows clients to retrieve data in manageable chunks with custom ordering. * * @example * ```ts * const options: ListOptions = { limit: 25, orderBy: "createdAt", order: "desc" }; * ``` */ interface ListOptions { /** Maximum number of results to return */ limit?: number; /** Number of results to skip before returning (for pagination) */ offset?: number; /** Field name to order results by */ orderBy?: string; /** Sort direction - ascending or descending */ order?: "asc" | "desc"; } /** * Supported operators for building database query conditions. * Supports standard comparison and membership operations. * * @example * ```ts * const operator: QueryOperator = "eq"; * ``` */ type QueryOperator = "eq" | "neq" | "gt" | "gte" | "lt" | "lte" | "in" | "contains"; /** * A single condition in a database query. * Can be combined with other conditions to build complex filters. * * @example * ```ts * const condition: QueryCondition = { field: "status", operator: "eq", value: "active" }; * ``` */ interface QueryCondition { /** The field name to query against */ field: string; /** The comparison operator to use */ operator: QueryOperator; /** The value to compare against */ value: unknown; } /** * Array of query conditions that can be combined (typically with AND logic). * Provides a declarative way to express database filters. * * @example * ```ts * const filter: QueryFilter = [{ field: "status", operator: "eq", value: "active" }]; * ``` */ type QueryFilter = QueryCondition[]; /** * Pricing plan offered to users. * Defines the features and pricing structure for a subscription tier. * * @example * ```ts * const plan: Plan = { id: "pro", name: "Pro", price: 2000, currency: "USD", interval: "month", features: [] }; * ``` */ interface Plan { /** Unique identifier for the plan */ id: string; /** Human-readable plan name (e.g., 'Pro', 'Enterprise') */ name: string; /** Price in the specified currency (typically in cents) */ price: number; /** ISO 4217 currency code (e.g., 'USD', 'EUR') */ currency: string; /** Billing interval - how often the user is charged */ interval: "month" | "year" | "one-time"; /** List of features included in this plan */ features: string[]; } /** * User subscription to a pricing plan. * Tracks the user's current subscription status and billing cycle. * * @example * ```ts * const subscription: Subscription = { id: "sub", userId: "u1", planId: "pro", status: "active", currentPeriodEnd: new Date().toISOString(), cancelAtPeriodEnd: false }; * ``` */ interface Subscription { /** Unique identifier for the subscription */ id: string; /** ID of the user who owns this subscription */ userId: string; /** ID of the plan this subscription is for */ planId: string; /** Current subscription status */ status: "active" | "cancelled" | "past_due" | "trialing"; /** ISO 8601 timestamp when the current billing period ends */ currentPeriodEnd: string; /** If true, the subscription will be cancelled at the end of the current period */ cancelAtPeriodEnd: boolean; } /** * Parameters needed to initiate a checkout session. * Used when creating a payment checkout with a payment provider. * * @example * ```ts * const params: CheckoutParams = { planId: "pro", userId: "u1" }; * ``` */ interface CheckoutParams { /** ID of the plan the user is subscribing to */ planId: string; /** ID of the user initiating the checkout */ userId: string; /** URL to redirect to after successful payment */ successUrl?: string; /** URL to redirect to if user cancels the checkout */ cancelUrl?: string; } /** * Result of a successful checkout session creation. * Contains the URL to redirect the user to for payment completion. * * @example * ```ts * const result: CheckoutResult = { url: "https://pay.example.com", sessionId: "cs_1" }; * ``` */ interface CheckoutResult { /** Redirect URL where the user completes payment */ url: string; /** Unique session ID for tracking this checkout */ sessionId: string; } /** * Role of a message participant in a conversation. * - 'system': System prompt that sets context for the AI * - 'user': Message from the user * - 'assistant': Message from the AI assistant * * @example * ```ts * const role: ChatRole = "user"; * ``` */ type ChatRole = "system" | "user" | "assistant"; /** * A single message in a conversation with an AI model. * Messages are typically collected in order to form a conversation history. * * @example * ```ts * const message: ChatMessage = { role: "user", content: "Summarize this." }; * ``` */ interface ChatMessage { /** The role of the message sender */ role: ChatRole; /** The text content of the message */ content: string; } /** * Configuration options for AI model inference. * Allows fine-tuning of model behavior and output constraints. * * @example * ```ts * const options: AiOptions = { model: "gpt-5.4", temperature: 0.2 }; * ``` */ interface AiOptions { /** Name or identifier of the model to use */ model?: string; /** Controls randomness - higher values (0.8-1.0) are more creative, lower (0.1-0.3) are more deterministic */ temperature?: number; /** Maximum number of tokens (words) in the response */ maxTokens?: number; } /** * Response from an AI model's chat/completion API. * Includes the generated content and metadata about the generation. * * @example * ```ts * const response: ChatResponse = { content: "Done", finishReason: "stop" }; * ``` */ interface ChatResponse { /** The text content generated by the model */ content: string; /** Reason why the model stopped generating */ finishReason: "stop" | "length" | "error"; /** Token usage statistics (if provided by the model) */ usage?: { /** Number of tokens in the user's prompt */ promptTokens: number; /** Number of tokens in the model's response */ completionTokens: number; /** Total tokens used (prompt + completion) */ totalTokens: number; }; } /** * Metadata for a file stored in a storage adapter. * Contains identification and access information for uploaded files. * * @example * ```ts * const value: FileStorageMetadataValue = "avatar"; * ``` */ type FileStorageMetadataValue = string | number | boolean | null; /** * Caller-controlled metadata stored with a file. * Values stay JSON-compatible so local/dev adapters and provider adapters can * round-trip them without importing provider SDKs. * * @example * ```ts * const metadata: FileStorageMetadata = { public: true, owner: "u1" }; * ``` */ type FileStorageMetadata = Record; /** * File record returned by storage adapters after upload or lookup. Use this in * UI bindings and provider contracts that need a provider-neutral file shape. * * @example * ```ts * const file: StoredFile = { id: "f1", name: "a.txt", path: "/a.txt", size: 2, mimeType: "text/plain", url: "memory://a.txt", createdAt: new Date().toISOString() }; * ``` */ interface StoredFile { /** Unique identifier for the stored file */ id: string; /** Original filename from the user's upload */ name: string; /** Path within the storage system (could include subdirectories) */ path: string; /** File size in bytes */ size: number; /** MIME type of the file (e.g., 'application/pdf', 'image/jpeg') */ mimeType: string; /** Public or authenticated URL to access the file */ url: string; /** Caller-provided metadata persisted separately from the file payload */ metadata?: FileStorageMetadata; /** ISO 8601 timestamp when the file was uploaded */ createdAt: string; } /** * Available service domains that can have adapters configured. * Each domain represents a category of functionality: * - 'db': Database/data persistence * - 'auth': Authentication & authorization * - 'payments': Payment processing & subscriptions * - 'ai': Artificial intelligence & LLMs * - 'storage': File storage & CDN * - 'admin': Administrative tools & dashboards * - 'logger': Structured logging and observability sinks * * @example * ```ts * const domain: AdapterDomain = "db"; * ``` */ type AdapterDomain = "db" | "auth" | "payments" | "ai" | "storage" | "admin" | "logger"; /** * Contract-only infrastructure domains that do not participate in the legacy * UI/local adapter status surface but still need config-driven resolver wiring. * * @example * ```ts * const domain: ContractResolverDomain = "queue"; * ``` */ type ContractResolverDomain = "cache" | "queue" | "events" | "deploy"; /** * All domains accepted by the shared config/resolver registry. * * @example * ```ts * const domain: ResolvableAdapterDomain = "deploy"; * ``` */ type ResolvableAdapterDomain = AdapterDomain | ContractResolverDomain; /** * Union of all provider identifiers accepted by runtime adapter config. * * @example * ```ts * const provider: AdapterProviderName = "memory"; * ``` */ type AdapterProviderName = DbProviderName | AuthProviderName | PaymentProviderName | AiProviderName | StorageProviderName | AdminProviderName | LoggerProviderName; /** * Provider-name union for a specific adapter domain. * * @example * ```ts * const provider: AdapterProviderNameForDomain<"db"> = "neon"; * ``` */ type AdapterProviderNameForDomain = D extends "db" ? DbProviderName : D extends "auth" ? AuthProviderName : D extends "payments" ? PaymentProviderName : D extends "ai" ? AiProviderName : D extends "storage" ? StorageProviderName : D extends "admin" ? AdminProviderName : D extends "logger" ? LoggerProviderName : D extends ContractResolverDomain ? string : never; /** * Configuration for a specific adapter implementation within a domain. * Encapsulates provider details and implementation-specific settings. * * @example * ```ts * const config: DomainAdapterConfig<"neon"> = { provider: "neon", baseUrl: "postgres://example" }; * ``` */ interface DomainAdapterConfig { /** Name of the provider/adapter implementation (e.g., 'stripe', 'convex', 'anthropic') */ provider: ProviderName; /** API key or credentials needed to authenticate with the provider */ apiKey?: string; /** Base URL for API endpoints (if different from provider's default) */ baseUrl?: string; /** Additional provider-specific configuration options */ options?: Record; } /** * Runtime configuration for one domain with its provider id narrowed. * * @example * ```ts * const config: AdapterConfigForDomain<"auth"> = { provider: "better-auth" }; * ``` */ type AdapterConfigForDomain = DomainAdapterConfig>; /** * Complete configuration for all adapter domains. * Defines which providers are used for each service type in the application. * * @example * ```ts * const config: AdapterConfig = { db: { provider: "memory" } }; * ``` */ interface AdapterConfig { /** Database adapter configuration */ db?: AdapterConfigForDomain<"db">; /** Authentication adapter configuration */ auth?: AdapterConfigForDomain<"auth">; /** Payments adapter configuration */ payments?: AdapterConfigForDomain<"payments">; /** AI/LLM adapter configuration */ ai?: AdapterConfigForDomain<"ai">; /** File storage adapter configuration */ storage?: AdapterConfigForDomain<"storage">; /** Admin adapter configuration */ admin?: AdapterConfigForDomain<"admin">; /** Logger adapter configuration */ logger?: AdapterConfigForDomain<"logger">; /** Contract-only cache adapter configuration */ cache?: AdapterConfigForDomain<"cache">; /** Contract-only queue adapter configuration */ queue?: AdapterConfigForDomain<"queue">; /** Contract-only pub/sub and webhooks adapter configuration */ events?: AdapterConfigForDomain<"events">; /** Contract-only deployment adapter configuration */ deploy?: AdapterConfigForDomain<"deploy">; } /** * Indicates the connectivity status of an adapter. * Used to display health status in UI components and manage fallbacks. * * @example * ```ts * const status: AdapterStatusType = "connected"; * ``` */ type AdapterStatusType = "connected" | "disconnected" | "error" | "initializing"; /** * Real-time status information about a connected adapter. * Used for monitoring, debugging, and displaying adapter health in the UI. * * @example * ```ts * const status: AdapterStatusInfo = { domain: "db", provider: "memory", status: "connected" }; * ``` */ interface AdapterStatusInfo { /** The domain this adapter serves */ domain: AdapterDomain; /** The provider implementation being used */ provider: string; /** Current connection/operation status */ status: AdapterStatusType; /** Response latency in milliseconds (if available) */ latency?: number; /** Unix timestamp (ms) of the last health check */ lastCheckedAt?: number; /** Error message if status is 'error' */ error?: string; } /** * Registry entry for a fully configured and initialized adapter. * Tracks both configuration and runtime status of an adapter instance. * * @example * ```ts * const entry: AdapterRegistryEntry = { domain: "db", provider: "memory", status: "connected", config: { provider: "memory" } }; * ``` */ interface AdapterRegistryEntry { /** The domain this adapter serves */ domain: AdapterDomain; /** The provider implementation being used */ provider: string; /** Current connection status */ status: AdapterStatusType; /** Configuration used to initialize this adapter */ config: DomainAdapterConfig; /** Unix timestamp (ms) when the adapter was successfully connected */ connectedAt?: number; } /** * @module errors * @description Defines the typed error hierarchy and helpers shared across the * adapters package. Each error preserves domain-aware error codes so consumers * can discriminate failures without relying on string parsing while still * aligning with the shared `@geenius/errors` base contract. */ /** * Error codes specific to database operations. * Used to categorize and handle different types of database failures. */ type DbErrorCode = "NOT_FOUND" | "CONSTRAINT_VIOLATION" | "QUERY_ERROR" | "CONNECTION_ERROR" | "COLLECTION_NOT_CONFIGURED"; /** * Error codes specific to authentication operations. * Covers credential validation, session management, and OAuth failures. */ type AuthErrorCode = "INVALID_CREDENTIALS" | "USER_EXISTS" | "SESSION_EXPIRED" | "UNAUTHORIZED" | "OAUTH_ERROR" | "SERVICE_ERROR"; /** * Error codes specific to AI/LLM operations. * Includes model-level errors, API limits, and token constraints. */ type AiErrorCode = "MODEL_ERROR" | "RATE_LIMIT" | "CONTEXT_LENGTH" | "SERVICE_ERROR" | "EMBEDDING_ERROR" | "INVALID_INPUT"; /** * Error codes specific to file storage operations. * Covers file lifecycle errors and quota management. */ type StorageErrorCode = "NOT_FOUND" | "UPLOAD_FAILED" | "DOWNLOAD_FAILED" | "PAYLOAD_TOO_LARGE" | "QUOTA_EXCEEDED" | "INVALID_KEY" | "SERVICE_ERROR"; /** * Error codes specific to payment/billing operations. * Covers subscription and checkout workflow errors. */ type PaymentsErrorCode = "INVALID_PLAN" | "CHECKOUT_FAILED" | "SUBSCRIPTION_NOT_FOUND" | "CANCEL_FAILED" | "SERVICE_ERROR" | "NOT_AVAILABLE"; /** * Error codes specific to admin panel operations. * Covers admin-level data and configuration errors. */ type AdminErrorCode = "USER_NOT_FOUND" | "OPERATION_FAILED" | "SERVICE_ERROR"; /** * Error codes for adapter configuration and runtime invariants. * These cover setup-time failures that happen before a domain-specific adapter * can be invoked safely. */ type AdapterInfrastructureErrorCode = "INVALID_CONFIG" | "MISSING_CONFIG" | "MISSING_RESOLVER" | "ADAPTER_NOT_CONFIGURED" | "MISSING_CONTEXT" | "INVARIANT_VIOLATION"; /** * Union of all adapter-specific error codes, including the shared Geenius * error codes that this package reuses from `@geenius/errors`. */ type AdapterErrorCode = ErrorCode | DbErrorCode | AuthErrorCode | AiErrorCode | StorageErrorCode | PaymentsErrorCode | AdminErrorCode | AdapterInfrastructureErrorCode | (string & {}); /** * Base error class for all adapter-related errors. * Provides structured error information for better error handling and logging. * * @example * try { * await adapter.query(/* ... *\/); * } catch (error) { * if (error instanceof AdapterError) { * logger.error(`${error.domain}: ${error.code} - ${error.message}`); * if (isRetryable(error)) { * // Implement retry logic * } * } * } */ declare class AdapterError extends GeeniusError { readonly cause?: unknown | undefined; readonly adapterCode: AdapterErrorCode; readonly domain: string; /** * Creates a new AdapterError instance. * * @param message - Human-readable error message * @param domain - The adapter domain where the error occurred (db, auth, etc.) * @param code - Machine-readable error code for programmatic handling * @param cause - Optional underlying error that caused this error */ constructor(message: string, domain: string, code: AdapterErrorCode, cause?: unknown | undefined); } /** * Error thrown by database adapter operations. * Specializes AdapterError with database-specific error codes. */ declare class DbError extends AdapterError { /** * @param message - Description of what went wrong * @param code - Database-specific error code for routing and handling * @param cause - The underlying error when provided */ constructor(message: string, code: DbErrorCode, cause?: unknown); } /** * Error thrown by authentication adapter operations. * Specializes AdapterError with auth-specific error codes. */ declare class AuthError extends AdapterError { /** * @param message - Description of what went wrong (e.g., credentials invalid) * @param code - Auth-specific error code for routing and handling * @param cause - The underlying error when provided */ constructor(message: string, code: AuthErrorCode, cause?: unknown); } /** * Error thrown by AI/LLM adapter operations. * Specializes AdapterError with AI-specific error codes. */ declare class AiError extends AdapterError { /** * @param message - Description of what went wrong (e.g., rate limited) * @param code - AI-specific error code for routing and handling * @param cause - The underlying error when provided */ constructor(message: string, code: AiErrorCode, cause?: unknown); } /** * Error thrown by file storage adapter operations. * Specializes AdapterError with storage-specific error codes. */ declare class StorageError extends AdapterError { /** * @param message - Description of what went wrong (e.g., upload failed) * @param code - Storage-specific error code for routing and handling * @param cause - The underlying error when provided */ constructor(message: string, code: StorageErrorCode, cause?: unknown); } /** * Error thrown by payment adapter operations. * Specializes AdapterError with payment-specific error codes. */ declare class PaymentsError extends AdapterError { /** * @param message - Description of what went wrong (e.g., checkout failed) * @param code - Payment-specific error code for routing and handling * @param cause - The underlying error when provided */ constructor(message: string, code: PaymentsErrorCode, cause?: unknown); } /** * Error thrown by admin adapter operations. * Specializes AdapterError with admin-specific error codes. */ declare class AdminError extends AdapterError { /** * @param message - Description of what went wrong * @param code - Admin-specific error code for routing and handling * @param cause - The underlying error when provided */ constructor(message: string, code: AdminErrorCode, cause?: unknown); } /** * Error thrown when adapter configuration is invalid or unavailable. * Covers malformed config payloads and missing initialization. */ declare class AdapterConfigurationError extends AdapterError { /** * @param message - Description of the configuration failure * @param code - Configuration-specific error code for routing and handling * @param cause - The underlying error when provided */ constructor(message: string, code: Extract, cause?: unknown); } /** * Error thrown when resolving an adapter through the registry fails. * Covers missing registrations and domains with no configured provider. */ declare class AdapterResolutionError extends AdapterError { /** * @param message - Description of the resolution failure * @param code - Resolution-specific error code for routing and handling * @param cause - The underlying error when provided */ constructor(message: string, code: Extract, cause?: unknown); } /** * Error thrown when a UI adapter context is missing a provider or domain. * Used by React hooks and Solid primitives to fail fast with a typed error. */ declare class AdapterContextError extends AdapterError { /** * @param message - Description of the missing context or adapter * @param code - Context-specific error code for routing and handling * @param cause - The underlying error when provided */ constructor(message: string, code: Extract, cause?: unknown); } /** * Error thrown when the package encounters an unexpected runtime invariant. * Used for bootstrap and environment assumptions that cannot be recovered from. */ declare class AdapterInvariantError extends AdapterError { /** * @param message - Description of the failed invariant * @param cause - The underlying error when provided */ constructor(message: string, cause?: unknown); } /** * Type guard to check if an error is an AdapterError. * Useful for error handling that needs to distinguish adapter errors from other error types. * * @param error - The error to check * @returns True if the error is an instance of AdapterError * * @example * catch (error) { * if (isAdapterError(error)) { * // Handle adapter-specific error * logger.info(`Adapter error: ${error.code}`); * } * } */ declare function isAdapterError(error: unknown): error is AdapterError; /** * Determines if an error is retryable based on its error code. * Some transient errors (rate limits, connection issues, service errors) should be retried, * while others (validation errors, not found) should not. * * @param error - The error to check * @returns True if the error is retryable, false otherwise * * @example * const maxRetries = 3; * for (let i = 0; i < maxRetries; i++) { * try { * return await adapter.operation(); * } catch (error) { * if (isRetryable(error) && i < maxRetries - 1) { * await delay(Math.pow(2, i) * 1000); // exponential backoff * continue; * } * throw error; * } * } */ declare function isRetryable(error: unknown): boolean; /** * @module contracts * @description SDK-free adapter contracts for infrastructure domains. Concrete * provider code lives outside this package except for the memory dev/test * adapters. */ /** * JSON-compatible value accepted by SDK-free adapter contracts. Use this for * payloads that must round-trip through local/dev adapters and provider * contracts without preserving class instances or cyclic references. * * @example * ```ts * const payload: AdapterJsonValue = { feature: "cache", enabled: true }; * ``` */ type AdapterJsonValue = string | number | boolean | null | AdapterJsonValue[] | { [key: string]: AdapterJsonValue; }; /** * Runtime validator for JSON-compatible values passed through adapter * boundaries. Use this before writing cache values, queue payloads, or event * envelopes supplied by application code. * * @example * ```ts * const payload = AdapterJsonValueSchema.parse({ retry: 2 }); * ``` */ declare const AdapterJsonValueSchema: z.ZodType; /** * Launch backend ids supported by the adapter contract matrix. Use this tuple * when building parity tests or provider pickers that must stay aligned with * the handwritten adapter package shape. * * @example * ```ts * const launchBackends = [...ADAPTER_CONTRACT_BACKENDS]; * ``` */ declare const ADAPTER_CONTRACT_BACKENDS: readonly ["convex", "neon", "cloudflareKV", "memory"]; /** * Infrastructure domains owned by the contract-only adapter surface. Use this * tuple when registering SDK-free domain contracts rather than concrete * production providers. * * @example * ```ts * const supportsDeploy = ADAPTER_CONTRACT_DOMAINS.includes("deploy"); * ``` */ declare const ADAPTER_CONTRACT_DOMAINS: readonly ["storage", "cache", "queue", "events", "auth", "payments", "deploy"]; /** * Backend id for a launch adapter contract package. * * @example * ```ts * const backend: AdapterContractBackend = "memory"; * ``` */ type AdapterContractBackend = (typeof ADAPTER_CONTRACT_BACKENDS)[number]; /** * Domain id for the contract-only adapter surface. * * @example * ```ts * const domain: AdapterContractDomain = "queue"; * ``` */ type AdapterContractDomain = (typeof ADAPTER_CONTRACT_DOMAINS)[number]; /** * Runtime validator for launch backend ids accepted by contract manifests. * * @example * ```ts * const backend = AdapterContractBackendSchema.parse("cloudflareKV"); * ``` */ declare const AdapterContractBackendSchema: z.ZodEnum<{ convex: "convex"; neon: "neon"; cloudflareKV: "cloudflareKV"; memory: "memory"; }>; /** * Runtime validator for contract domain ids accepted by contract manifests. * * @example * ```ts * const domain = AdapterContractDomainSchema.parse("events"); * ``` */ declare const AdapterContractDomainSchema: z.ZodEnum<{ auth: "auth"; payments: "payments"; storage: "storage"; cache: "cache"; queue: "queue"; events: "events"; deploy: "deploy"; }>; /** * Runtime validator for string metadata maps used by several domains. Use this * for provider-neutral metadata that must remain small and serializable. * * @example * ```ts * const metadata = AdapterMetadataSchema.parse({ region: "eu" }); * ``` */ declare const AdapterMetadataSchema: z.ZodRecord; /** * Runtime validator for file-storage metadata scalar values. * * @example * ```ts * const value = FileStorageMetadataValueSchema.parse("invoice"); * ``` */ declare const FileStorageMetadataValueSchema: z.ZodUnion; /** * Runtime validator for caller-controlled file metadata maps. Use this before * handing upload metadata to local/dev file storage adapters. * * @example * ```ts * const metadata = FileStorageMetadataSchema.parse({ public: true }); * ``` */ declare const FileStorageMetadataSchema: z.ZodRecord>; /** * Common health status returned by adapter implementations. Use this schema to * normalize provider health checks before surfacing them in review UI or logs. * * @example * ```ts * const health = AdapterHealthSchema.parse({ ok: true, checkedAt: new Date().toISOString() }); * ``` */ declare const AdapterHealthSchema: z.ZodObject<{ ok: z.ZodBoolean; checkedAt: z.ZodString; latencyMs: z.ZodOptional; message: z.ZodOptional; }, z.core.$strip>; /** * Common health status type returned by adapter implementations. * * @example * ```ts * const health: AdapterHealth = { ok: true, checkedAt: new Date().toISOString() }; * ``` */ type AdapterHealth = z.infer; /** * Shared page options for list operations. Use this schema for cursor, prefix, * or bounded limit arguments accepted by contract-only list methods. * * @example * ```ts * const options = AdapterListOptionsSchema.parse({ limit: 25, prefix: "prod/" }); * ``` */ declare const AdapterListOptionsSchema: z.ZodObject<{ limit: z.ZodOptional; cursor: z.ZodOptional; prefix: z.ZodOptional; }, z.core.$strip>; /** * Shared page options type for list operations. * * @example * ```ts * const options: AdapterListOptions = { limit: 50 }; * ``` */ type AdapterListOptions = z.infer; /** * Declarative metadata for a domain/backend contract cell. Use this schema for * manifest files and conformance fixtures that describe adapter capabilities. * * @example * ```ts * const manifest = AdapterContractManifestSchema.parse({ * domain: "cache", * backend: "memory", * provider: "local", * }); * ``` */ declare const AdapterContractManifestSchema: z.ZodObject<{ domain: z.ZodEnum<{ auth: "auth"; payments: "payments"; storage: "storage"; cache: "cache"; queue: "queue"; events: "events"; deploy: "deploy"; }>; backend: z.ZodEnum<{ convex: "convex"; neon: "neon"; cloudflareKV: "cloudflareKV"; memory: "memory"; }>; provider: z.ZodString; capabilities: z.ZodDefault>; }, z.core.$strip>; /** * Declarative metadata for a domain/backend contract cell. * * @example * ```ts * const manifest: AdapterContractManifest = { * domain: "deploy", * backend: "memory", * provider: "local", * capabilities: [], * }; * ``` */ type AdapterContractManifest = z.infer; /** * Error raised by SDK-free contract validation helpers. Use this when a * contract-layer guard rejects input before any concrete provider SDK runs. * * @example * ```ts * throw new AdapterContractError("contract", "Invalid adapter payload"); * ``` */ declare class AdapterContractError extends AdapterError { /** * Creates a contract-layer error without coupling to a concrete provider SDK. * * @param domain - Contract domain that rejected the payload. * @param message - Human-readable validation failure. * @param cause - Optional underlying parser or provider error. * @returns A typed adapter contract error. * @example * ```ts * const error = new AdapterContractError("storage", "Invalid key"); * ``` */ constructor(domain: AdapterContractDomain | "contract", message: string, cause?: unknown); } /** * Error raised by storage contract implementations when object/blob input or * output violates the SDK-free storage contract. * * @example * ```ts * throw new StorageContractError("Storage object key is required"); * ``` */ declare class StorageContractError extends AdapterContractError { /** * Creates a storage-specific contract error. * * @param message - Human-readable storage contract failure. * @param cause - Optional parser or provider error that triggered the failure. * @returns A typed storage contract error. * @example * ```ts * const error = new StorageContractError("Invalid metadata"); * ``` */ constructor(message: string, cause?: unknown); } /** * Error raised by cache contract implementations when cache keys or values do * not satisfy the JSON-compatible cache boundary. * * @example * ```ts * throw new CacheContractError("Cache value is not JSON-compatible"); * ``` */ declare class CacheContractError extends AdapterContractError { /** * Creates a cache-specific contract error. * * @param message - Human-readable cache contract failure. * @param cause - Optional parser or provider error that triggered the failure. * @returns A typed cache contract error. * @example * ```ts * const error = new CacheContractError("Invalid TTL"); * ``` */ constructor(message: string, cause?: unknown); } /** * Error raised by queue contract implementations when job payloads or state * transitions violate the queue contract. * * @example * ```ts * throw new QueueContractError("Job id is required"); * ``` */ declare class QueueContractError extends AdapterContractError { /** * Creates a queue-specific contract error. * * @param message - Human-readable queue contract failure. * @param cause - Optional parser or provider error that triggered the failure. * @returns A typed queue contract error. * @example * ```ts * const error = new QueueContractError("Invalid scheduled run time"); * ``` */ constructor(message: string, cause?: unknown); } /** * Error raised by events contract implementations when pub/sub or webhook * payloads violate the event boundary. * * @example * ```ts * throw new EventsContractError("Webhook URL is invalid"); * ``` */ declare class EventsContractError extends AdapterContractError { /** * Creates an events-specific contract error. * * @param message - Human-readable events contract failure. * @param cause - Optional parser or provider error that triggered the failure. * @returns A typed events contract error. * @example * ```ts * const error = new EventsContractError("Invalid topic"); * ``` */ constructor(message: string, cause?: unknown); } /** * Error raised by auth contract implementations when identity or session * records violate the contract-only auth boundary. * * @example * ```ts * throw new AuthContractError("Session token is required"); * ``` */ declare class AuthContractError extends AdapterContractError { /** * Creates an auth-specific contract error. * * @param message - Human-readable auth contract failure. * @param cause - Optional parser or provider error that triggered the failure. * @returns A typed auth contract error. * @example * ```ts * const error = new AuthContractError("Invalid identity"); * ``` */ constructor(message: string, cause?: unknown); } /** * Error raised by payments contract implementations when plan, checkout, or * subscription records violate the provider-neutral payments contract. * * @example * ```ts * throw new PaymentsContractError("Plan currency must be ISO 4217"); * ``` */ declare class PaymentsContractError extends AdapterContractError { /** * Creates a payments-specific contract error. * * @param message - Human-readable payments contract failure. * @param cause - Optional parser or provider error that triggered the failure. * @returns A typed payments contract error. * @example * ```ts * const error = new PaymentsContractError("Invalid checkout session"); * ``` */ constructor(message: string, cause?: unknown); } /** * Error raised by deployment contract implementations when deployment targets * or results violate the SDK-free deploy boundary. * * @example * ```ts * throw new DeployContractError("Deployment target provider is invalid"); * ``` */ declare class DeployContractError extends AdapterContractError { /** * Creates a deploy-specific contract error. * * @param message - Human-readable deploy contract failure. * @param cause - Optional parser or provider error that triggered the failure. * @returns A typed deploy contract error. * @example * ```ts * const error = new DeployContractError("Invalid deployment result"); * ``` */ constructor(message: string, cause?: unknown); } /** * Serializable object stored by storage adapters. Use this schema to validate * local/dev object storage reads before returning them to consumers. * * @example * ```ts * const object = StorageObjectSchema.parse({ key: "a.txt", body: "ok", size: 2, updatedAt: new Date().toISOString() }); * ``` */ declare const StorageObjectSchema: z.ZodObject<{ key: z.ZodString; body: z.ZodString; contentType: z.ZodOptional; size: z.ZodNumber; etag: z.ZodOptional; metadata: z.ZodDefault>; updatedAt: z.ZodString; }, z.core.$strip>; /** * Serializable object stored by storage adapters. * * @example * ```ts * const object: StorageObject = { key: "a.txt", body: "ok", size: 2, metadata: {}, updatedAt: new Date().toISOString() }; * ``` */ type StorageObject = z.infer; /** * Write payload accepted by storage adapters. Use this schema before persisting * object bodies through memory or provider-bound storage implementations. * * @example * ```ts * const input = StorageWriteInputSchema.parse({ key: "a.txt", body: "ok" }); * ``` */ declare const StorageWriteInputSchema: z.ZodObject<{ key: z.ZodString; body: z.ZodString; contentType: z.ZodOptional; metadata: z.ZodOptional>; ttlSeconds: z.ZodOptional; }, z.core.$strip>; /** * Write payload accepted by storage adapters. * * @example * ```ts * const input: StorageWriteInput = { key: "a.txt", body: "ok" }; * ``` */ type StorageWriteInput = z.infer; /** * Upload options accepted by file storage adapters. Use this for metadata-only * upload settings that remain independent of provider SDK upload types. * * @example * ```ts * const options = FileUploadOptionsSchema.parse({ name: "avatar.png" }); * ``` */ declare const FileUploadOptionsSchema: z.ZodObject<{ name: z.ZodOptional; metadata: z.ZodOptional>>; }, z.core.$strip>; /** * Runtime validator for file records returned by file storage adapters. * * @example * ```ts * const file = StoredFileSchema.parse({ id: "1", name: "a.txt", path: "/a.txt", size: 2, mimeType: "text/plain", url: "memory://a.txt", createdAt: new Date().toISOString() }); * ``` */ declare const StoredFileSchema: z.ZodObject<{ id: z.ZodString; name: z.ZodString; path: z.ZodString; size: z.ZodNumber; mimeType: z.ZodString; url: z.ZodString; metadata: z.ZodOptional>>; createdAt: z.ZodString; }, z.core.$strip>; /** * Contract for object/blob storage providers. Implement this in local/dev * storage adapters or downstream provider modules that own concrete SDKs. * * @example * ```ts * const object = await storage.getObject("a.txt"); * ``` */ interface StorageAdapter { getObject(key: string): Promise; putObject(input: StorageWriteInput): Promise; deleteObject(key: string): Promise; listObjects(options?: AdapterListOptions): Promise; getHealth(): Promise; } /** * Serializable cache entry. Use this schema for cache reads that need to * preserve expiry metadata alongside JSON-compatible values. * * @example * ```ts * const entry = CacheEntrySchema.parse({ key: "flag", value: true, updatedAt: new Date().toISOString() }); * ``` */ declare const CacheEntrySchema: z.ZodObject<{ key: z.ZodString; value: z.ZodType>; expiresAt: z.ZodOptional; updatedAt: z.ZodString; }, z.core.$strip>; /** * Serializable cache entry. * * @example * ```ts * const entry: CacheEntry = { key: "flag", value: true, updatedAt: new Date().toISOString() }; * ``` */ type CacheEntry = z.infer; /** * Cache write options. Use this schema when accepting caller-provided TTLs for * memory, Redis, or edge KV cache implementations. * * @example * ```ts * const options = CacheSetOptionsSchema.parse({ ttlSeconds: 60 }); * ``` */ declare const CacheSetOptionsSchema: z.ZodObject<{ ttlSeconds: z.ZodOptional; }, z.core.$strip>; /** * Cache write options. * * @example * ```ts * const options: CacheSetOptions = { ttlSeconds: 60 }; * ``` */ type CacheSetOptions = z.infer; /** * Contract for key/value cache providers. Implement this for local memory, * Redis, or KV-backed caches while keeping values JSON-compatible. * * @example * ```ts * await cache.set("feature", true, { ttlSeconds: 60 }); * ``` */ interface CacheAdapter { get(key: string): Promise; set(key: string, value: T, options?: CacheSetOptions): Promise; delete(key: string): Promise; has(key: string): Promise; clear(prefix?: string): Promise; getHealth(): Promise; } /** * Queue job status values accepted by the scheduled-work contract. * * @example * ```ts * const status = QueueJobStatusSchema.parse("queued"); * ``` */ declare const QueueJobStatusSchema: z.ZodEnum<{ queued: "queued"; running: "running"; completed: "completed"; failed: "failed"; scheduled: "scheduled"; }>; /** * Queue job status values accepted by the scheduled-work contract. * * @example * ```ts * const status: QueueJobStatus = "scheduled"; * ``` */ type QueueJobStatus = z.infer; /** * Serializable queue job. Use this schema for queue state returned by local or * provider-backed queue adapters. * * @example * ```ts * const job = QueueJobSchema.parse({ id: "1", name: "sync", payload: {}, status: "queued", attempts: 0, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }); * ``` */ declare const QueueJobSchema: z.ZodObject<{ id: z.ZodString; name: z.ZodString; payload: z.ZodType>; status: z.ZodEnum<{ queued: "queued"; running: "running"; completed: "completed"; failed: "failed"; scheduled: "scheduled"; }>; runAt: z.ZodOptional; attempts: z.ZodNumber; createdAt: z.ZodString; updatedAt: z.ZodString; }, z.core.$strip>; /** * Serializable queue job. * * @example * ```ts * const job: QueueJob = { id: "1", name: "sync", payload: {}, status: "queued", attempts: 0, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }; * ``` */ type QueueJob = z.infer; /** * Queue enqueue payload. Use this schema before accepting work from callers or * conformance fixtures. * * @example * ```ts * const input = QueueJobInputSchema.parse({ name: "sync", payload: { id: 1 } }); * ``` */ declare const QueueJobInputSchema: z.ZodObject<{ name: z.ZodString; payload: z.ZodOptional>>; runAt: z.ZodOptional; }, z.core.$strip>; /** * Queue enqueue payload. * * @example * ```ts * const input: QueueJobInput = { name: "sync", payload: { id: 1 } }; * ``` */ type QueueJobInput = z.infer; /** * Contract for queue and scheduled-work providers. Implement this for local * test queues or downstream queue providers that own runtime SDKs. * * @example * ```ts * const job = await queue.enqueue({ name: "sync" }); * ``` */ interface QueueAdapter { enqueue(input: QueueJobInput): Promise; schedule(input: QueueJobInput & { runAt: string; }): Promise; complete(jobId: string): Promise; fail(jobId: string, reason?: string): Promise; listJobs(options?: AdapterListOptions): Promise; getHealth(): Promise; } /** * Serializable event envelope. Use this schema to validate pub/sub messages * before they cross webhook or provider adapter boundaries. * * @example * ```ts * const event = EventEnvelopeSchema.parse({ id: "1", topic: "user.created", payload: {}, createdAt: new Date().toISOString() }); * ``` */ declare const EventEnvelopeSchema: z.ZodObject<{ id: z.ZodString; topic: z.ZodString; payload: z.ZodType>; metadata: z.ZodDefault>; createdAt: z.ZodString; }, z.core.$strip>; /** * Serializable event envelope. * * @example * ```ts * const event: EventEnvelope = { id: "1", topic: "user.created", payload: {}, metadata: {}, createdAt: new Date().toISOString() }; * ``` */ type EventEnvelope = z.infer; /** * Event publish payload. Use this schema before handing caller-supplied events * to local or provider-backed pub/sub adapters. * * @example * ```ts * const input = EventPublishInputSchema.parse({ topic: "user.created", payload: { id: "u1" } }); * ``` */ declare const EventPublishInputSchema: z.ZodObject<{ topic: z.ZodString; payload: z.ZodOptional>>; metadata: z.ZodOptional>; }, z.core.$strip>; /** * Event publish payload. * * @example * ```ts * const input: EventPublishInput = { topic: "user.created", payload: { id: "u1" } }; * ``` */ type EventPublishInput = z.infer; /** * Event subscription payload. Use this schema when a consumer subscribes to a * topic without publishing a payload. * * @example * ```ts * const input = EventSubscribeInputSchema.parse({ topic: "user.created" }); * ``` */ declare const EventSubscribeInputSchema: z.ZodObject<{ topic: z.ZodString; }, z.core.$strip>; /** * Event subscription payload. * * @example * ```ts * const input: EventSubscribeInput = { topic: "user.created" }; * ``` */ type EventSubscribeInput = z.infer; /** * Webhook delivery record. Use this schema for durable delivery status returned * by webhook-capable events adapters. * * @example * ```ts * const delivery = WebhookDeliverySchema.parse({ id: "1", url: "https://example.com", eventId: "evt", status: "queued", createdAt: new Date().toISOString() }); * ``` */ declare const WebhookDeliverySchema: z.ZodObject<{ id: z.ZodString; url: z.ZodString; eventId: z.ZodString; status: z.ZodEnum<{ queued: "queued"; failed: "failed"; delivered: "delivered"; }>; createdAt: z.ZodString; }, z.core.$strip>; /** * Webhook delivery record. * * @example * ```ts * const delivery: WebhookDelivery = { id: "1", url: "https://example.com", eventId: "evt", status: "queued", createdAt: new Date().toISOString() }; * ``` */ type WebhookDelivery = z.infer; /** * Webhook emit payload. Use this schema before dispatching an event envelope to * a caller-provided webhook URL. * * @example * ```ts * const input = WebhookEmitInputSchema.parse({ url: "https://example.com", event }); * ``` */ declare const WebhookEmitInputSchema: z.ZodObject<{ url: z.ZodString; event: z.ZodObject<{ id: z.ZodString; topic: z.ZodString; payload: z.ZodType>; metadata: z.ZodDefault>; createdAt: z.ZodString; }, z.core.$strip>; }, z.core.$strip>; /** * Webhook emit payload. * * @example * ```ts * const input: WebhookEmitInput = { url: "https://example.com", event }; * ``` */ type WebhookEmitInput = z.infer; /** * Unsubscribe handle returned by event subscriptions. Use this to model * provider-neutral cleanup for long-lived local or remote subscriptions. * * @example * ```ts * await subscription.unsubscribe(); * ``` */ interface EventSubscription { unsubscribe(): Promise; } /** * Contract for pub/sub and webhook providers. Implement this for local event * emitters or downstream providers that own broker/webhook SDKs. * * @example * ```ts * const event = await events.publish({ topic: "user.created" }); * ``` */ interface EventsAdapter { publish(input: EventPublishInput): Promise; subscribe(input: EventSubscribeInput, handler: (event: EventEnvelope) => void | Promise): Promise; emitWebhook(input: WebhookEmitInput): Promise; listEvents(options?: AdapterListOptions): Promise; getHealth(): Promise; } /** * Identity record used by auth provider adapters. Use this schema for user * identity payloads before they cross a provider-bound auth slice. * * @example * ```ts * const identity = AuthIdentitySchema.parse({ id: "u1", roles: ["admin"] }); * ``` */ declare const AuthIdentitySchema: z.ZodObject<{ id: z.ZodString; email: z.ZodOptional; name: z.ZodOptional; roles: z.ZodDefault>; metadata: z.ZodDefault>; }, z.core.$strip>; /** * Identity record used by auth provider adapters. * * @example * ```ts * const identity: AuthIdentity = { id: "u1", roles: [], metadata: {} }; * ``` */ type AuthIdentity = z.infer; /** * Session record used by auth provider adapters. Use this schema for session * creation and verification results from local/dev auth implementations. * * @example * ```ts * const session = AuthSessionContractSchema.parse({ id: "s1", identityId: "u1", token: "token", createdAt: new Date().toISOString() }); * ``` */ declare const AuthSessionContractSchema: z.ZodObject<{ id: z.ZodString; identityId: z.ZodString; token: z.ZodString; expiresAt: z.ZodOptional; createdAt: z.ZodString; }, z.core.$strip>; /** * Session record used by auth provider adapters. * * @example * ```ts * const session: AuthSessionContract = { id: "s1", identityId: "u1", token: "token", createdAt: new Date().toISOString() }; * ``` */ type AuthSessionContract = z.infer; /** * Contract for session and identity providers. Implement this in local auth * adapters or downstream provider modules that own auth SDKs. * * @example * ```ts * const session = await auth.verifySession(token); * ``` */ interface AuthProviderAdapter { getIdentity(identityId: string): Promise; createIdentity(identity: AuthIdentity): Promise; createSession(identityId: string): Promise; verifySession(token: string): Promise; revokeSession(sessionId: string): Promise; getHealth(): Promise; } /** * Payment plan record. Use this schema to validate provider-neutral plan data * before displaying pricing or starting checkout. * * @example * ```ts * const plan = PaymentPlanContractSchema.parse({ id: "pro", name: "Pro", currency: "USD", amount: 2000, interval: "month" }); * ``` */ declare const PaymentPlanContractSchema: z.ZodObject<{ id: z.ZodString; name: z.ZodString; currency: z.ZodString; amount: z.ZodNumber; interval: z.ZodEnum<{ month: "month"; year: "year"; "one-time": "one-time"; }>; features: z.ZodDefault>; }, z.core.$strip>; /** * Payment plan record. * * @example * ```ts * const plan: PaymentPlanContract = { id: "pro", name: "Pro", currency: "USD", amount: 2000, interval: "month", features: [] }; * ``` */ type PaymentPlanContract = z.infer; /** * Checkout session creation input. Use this schema before passing checkout * requests to a provider-owned payments adapter. * * @example * ```ts * const input = PaymentCheckoutInputSchema.parse({ planId: "pro", identityId: "u1" }); * ``` */ declare const PaymentCheckoutInputSchema: z.ZodObject<{ planId: z.ZodString; identityId: z.ZodString; successUrl: z.ZodOptional; cancelUrl: z.ZodOptional; }, z.core.$strip>; /** * Checkout session creation input. * * @example * ```ts * const input: PaymentCheckoutInput = { planId: "pro", identityId: "u1" }; * ``` */ type PaymentCheckoutInput = z.infer; /** * Checkout session record. Use this schema for checkout responses returned by * provider-bound payments adapters. * * @example * ```ts * const session = PaymentCheckoutSessionSchema.parse({ id: "cs_1", planId: "pro", identityId: "u1", url: "https://pay.example.com", status: "created", createdAt: new Date().toISOString() }); * ``` */ declare const PaymentCheckoutSessionSchema: z.ZodObject<{ id: z.ZodString; planId: z.ZodString; identityId: z.ZodString; url: z.ZodString; status: z.ZodEnum<{ completed: "completed"; created: "created"; expired: "expired"; }>; createdAt: z.ZodString; }, z.core.$strip>; /** * Checkout session record. * * @example * ```ts * const session: PaymentCheckoutSession = { id: "cs_1", planId: "pro", identityId: "u1", url: "https://pay.example.com", status: "created", createdAt: new Date().toISOString() }; * ``` */ type PaymentCheckoutSession = z.infer; /** * Subscription lifecycle record. Use this schema to normalize subscription * state from payment providers before checking feature access. * * @example * ```ts * const subscription = PaymentSubscriptionContractSchema.parse({ id: "sub_1", planId: "pro", identityId: "u1", status: "active", currentPeriodStart: new Date().toISOString(), currentPeriodEnd: new Date().toISOString(), createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }); * ``` */ declare const PaymentSubscriptionContractSchema: z.ZodObject<{ id: z.ZodString; planId: z.ZodString; identityId: z.ZodString; status: z.ZodEnum<{ active: "active"; cancelled: "cancelled"; past_due: "past_due"; trialing: "trialing"; incomplete: "incomplete"; unpaid: "unpaid"; }>; currentPeriodStart: z.ZodString; currentPeriodEnd: z.ZodString; cancelAtPeriodEnd: z.ZodDefault; cancelledAt: z.ZodOptional; createdAt: z.ZodString; updatedAt: z.ZodString; metadata: z.ZodDefault>; }, z.core.$strip>; /** * Subscription lifecycle record. * * @example * ```ts * const subscription: PaymentSubscriptionContract = { id: "sub_1", planId: "pro", identityId: "u1", status: "active", currentPeriodStart: new Date().toISOString(), currentPeriodEnd: new Date().toISOString(), cancelAtPeriodEnd: false, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), metadata: {} }; * ``` */ type PaymentSubscriptionContract = z.infer; /** * Contract for payment-provider adapters. Implement this in local payment * fakes or downstream provider modules that own payment SDKs. * * @example * ```ts * const plans = await payments.listPlans(); * ``` */ interface PaymentsProviderAdapter { listPlans(): Promise; createCheckout(input: PaymentCheckoutInput): Promise; getSubscription(identityId: string): Promise; cancelSubscription(identityId: string): Promise; isFeatureEnabled(identityId: string, feature: string): Promise; getHealth(): Promise; } /** * Deployment target configuration. Use this schema before a deploy provider * slice accepts app-supplied project and environment metadata. * * @example * ```ts * const target = DeploymentTargetSchema.parse({ id: "prod", provider: "cloudflare", projectId: "app", environment: "production" }); * ``` */ declare const DeploymentTargetSchema: z.ZodObject<{ id: z.ZodString; provider: z.ZodEnum<{ cloudflare: "cloudflare"; vercel: "vercel"; netlify: "netlify"; heroku: "heroku"; }>; projectId: z.ZodString; environment: z.ZodString; metadata: z.ZodDefault>; }, z.core.$strip>; /** * Deployment target configuration. * * @example * ```ts * const target: DeploymentTarget = { id: "prod", provider: "cloudflare", projectId: "app", environment: "production", metadata: {} }; * ``` */ type DeploymentTarget = z.infer; /** * Deployment result record. Use this schema to validate deploy, rollback, * lookup, and list results returned by provider slices. * * @example * ```ts * const result = DeploymentResultSchema.parse({ id: "dep_1", targetId: "prod", status: "ready", createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }); * ``` */ declare const DeploymentResultSchema: z.ZodObject<{ id: z.ZodString; targetId: z.ZodString; status: z.ZodEnum<{ queued: "queued"; failed: "failed"; building: "building"; ready: "ready"; rolled_back: "rolled_back"; }>; url: z.ZodOptional; createdAt: z.ZodString; updatedAt: z.ZodString; }, z.core.$strip>; /** * Deployment result record. * * @example * ```ts * const result: DeploymentResult = { id: "dep_1", targetId: "prod", status: "ready", createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }; * ``` */ type DeploymentResult = z.infer; /** * Contract for deployment-platform adapters. Implement this in provider slices * that own concrete deployment SDKs or app-local deploy wiring. * * @example * ```ts * const result = await deploy.deploy(target); * ``` */ interface DeployAdapter { deploy(target: DeploymentTarget): Promise; rollback(deploymentId: string): Promise; getDeployment(deploymentId: string): Promise; listDeployments(targetId?: string): Promise; getHealth(): Promise; } /** * @module retry * @description Provides retry helpers for transient adapter failures. The * module applies exponential backoff and delegates retry eligibility to the * shared typed error helpers so callers can centralize retry policy. */ /** * Configuration options for automatic retry behavior. * All options are optional and have sensible defaults. */ interface RetryOptions { /** Maximum number of attempts to make (default: 3, meaning 1 initial + 2 retries) */ maxAttempts?: number; /** Initial delay before first retry in milliseconds (default: 500ms) */ delayMs?: number; /** Multiplier applied to delay after each failed attempt (default: 2, creating exponential backoff) */ backoffMultiplier?: number; /** Maximum delay between attempts in milliseconds. Defaults to no cap. */ maxDelayMs?: number; /** Custom function to determine if an error should be retried (default: isRetryable from errors module) */ shouldRetry?: (error: unknown) => boolean; } /** * Executes an async function with automatic retry logic. * Implements exponential backoff to handle transient failures gracefully. * * @typeParam T - The return type of the function being retried * @param fn - The async function to execute and potentially retry * @param options - Configuration options for retry behavior * @returns A promise that resolves to the function's return value * @throws {Error} The last error encountered after all retry attempts are exhausted * * @example * ```ts * // Retry with defaults (3 attempts, 500ms initial delay, 2x backoff) * const user = await withRetry(() => adapter.db.getUser('123')); * * // Customize retry behavior * const result = await withRetry( * () => adapter.ai.chat(messages), * { * maxAttempts: 5, * delayMs: 1000, * backoffMultiplier: 1.5, * maxDelayMs: 5000, * } * ); * * // Custom retry predicate - only retry specific errors * const data = await withRetry( * () => expensiveOperation(), * { * shouldRetry: (error) => { * // Only retry if it's a network error or rate limit * return error.code === 'RATE_LIMIT' || error.code === 'CONNECTION_ERROR'; * } * } * ); * ``` * * @remarks * The delay progression with default settings (maxAttempts=3, delayMs=500, backoffMultiplier=2): * - Attempt 1: Immediate * - Attempt 2: After 500ms * - Attempt 3: After 1000ms * * For custom shouldRetry: If false is returned, the error is thrown immediately without further retries. */ declare function withRetry(fn: () => Promise, options?: RetryOptions): Promise; /** * @module config * @description Manages the shared adapter configuration singleton and runtime * validation helpers. The module ensures adapter domains are configured once * and exposed through a typed contract before adapters are resolved. */ /** * Configure the adapter system with provider implementations. * Must be called exactly once at application startup, before adapters are used. * * @param config - Configuration object specifying provider for each adapter domain * @throws {Error} If config is not a valid object or contains invalid domain configurations * * @example * ```ts * import { configureAdapters } from '@geenius/adapters'; * * // Configure all domains at startup * configureAdapters({ * db: { provider: 'convex' }, * auth: { provider: 'better-auth' }, * ai: { provider: 'openai', apiKey: process.env.OPENAI_API_KEY }, * storage: { provider: 'r2', apiKey: process.env.R2_API_KEY }, * payments: { provider: 'stripe' }, * }); * ``` */ declare function configureAdapters(config: AdapterConfig): void; /** * Retrieve the global adapter configuration. * Safe to call multiple times from all modules. * * @returns The currently configured adapter configuration * @throws {Error} If configureAdapters() has not been called yet * * @example * ```ts * const config = getAdapterConfig(); * logger.info(config.db?.provider); // 'convex' * ``` */ declare function getAdapterConfig(): AdapterConfig; /** * Check if the adapter system has been configured. * Useful for lazy initialization or error handling. * * @returns True if configureAdapters() has been called, false otherwise * * @example * ```ts * if (!isAdaptersConfigured()) { * throw new AdapterConfigurationError('App not initialized - configure adapters first', 'MISSING_CONFIG'); * } * ``` */ declare function isAdaptersConfigured(): boolean; /** * Reset the adapter configuration to an uninitialized state. * Primarily useful for testing, to avoid state leakage between test cases. * * @example * ```ts * beforeEach(() => { * resetAdapterConfig(); // Clear state from previous test * configureAdapters(testConfig); * }); * ``` */ declare function resetAdapterConfig(): void; /** * Get the configuration for a specific adapter domain. * Returns null if the domain is not configured. * * @param domain - The adapter domain to get configuration for * @returns Configuration for the domain, or null if not configured * * @example * ```ts * const dbConfig = getDomainConfig('db'); * if (dbConfig) { * logger.info(`Using ${dbConfig.provider} for database`); * } * ``` */ declare function getDomainConfig(domain: D): AdapterConfigForDomain | null; /** * @module resolve * @description Implements the configuration-driven adapter resolver registry. * The module bridges configured domain providers to concrete adapter factories * so runtime variants can resolve adapters without coupling to implementations. */ /** * Maps adapter domains to their specific interface types. * Used for type-safe adapter resolution without runtime type information. * * @example * // With D = 'db', this type resolves to DbAdapter * type MyAdapter = AdapterForDomain<'db'>; */ type AdapterForDomain = D extends "auth" ? AuthAdapter : D extends "db" ? DbAdapter : D extends "ai" ? AiAdapter : D extends "storage" ? FileStorageAdapter : D extends "payments" ? PaymentsAdapter : D extends "admin" ? AdminAdapter : D extends "logger" ? LoggerAdapter : D extends "cache" ? CacheAdapter : D extends "queue" ? QueueAdapter : D extends "events" ? EventsAdapter : D extends "deploy" ? DeployAdapter : never; /** * Register a factory function for a specific domain and provider combination. * Called by downstream adapter implementation packages or application * bootstrap code to make concrete providers available for resolution. * * @typeParam D - The adapter domain being registered * @param domain - The adapter domain (db, auth, ai, storage, payments, admin) * @param provider - The specific provider name (convex, stripe, anthropic, etc.) * @param resolver - Factory function that creates an adapter instance from config * * @example * ```ts * // In a downstream @geenius/db Convex provider module * import { registerResolver } from '@geenius/adapters'; * * registerResolver('db', 'convex', () => appDbAdapter); * * // In a downstream payments provider module * import { registerResolver } from '@geenius/adapters'; * * registerResolver('payments', 'stripe', (config) => * createStripePaymentsAdapter({ apiKey: config.apiKey }) * ); * ``` * * @remarks * Registration should happen at module load time (top-level), not in functions. * Typically done in the main export file of the concrete provider package or * in the application adapter bootstrap module. */ declare function registerResolver(domain: D, provider: string, resolver: (config: DomainAdapterConfig) => AdapterForDomain): void; /** * Get an adapter instance for a given domain using the current configuration. * The domain must be configured via configureAdapters() and a resolver * must be registered for the configured provider. * * @typeParam D - The adapter domain being requested * @param domain - The adapter domain to resolve * @returns An initialized adapter instance of the appropriate type * @throws {Error} If domain is not configured or no resolver is registered * * @example * ```ts * // Setup (at app startup) * import '@geenius/db/convex-provider'; // Registers the db:convex resolver * import './adapters/anthropic'; // Registers the ai:anthropic resolver * * configureAdapters({ * db: { provider: 'convex' }, * ai: { provider: 'anthropic', apiKey: process.env.ANTHROPIC_API_KEY }, * }); * * // Usage (anywhere in app) * const dbAdapter = resolveAdapter('db'); * const users = await dbAdapter.query('users', {}); * * const aiAdapter = resolveAdapter('ai'); * const response = await aiAdapter.chat([{ role: 'user', content: 'Hello' }]); * ``` * * @remarks * Resolving the same domain multiple times returns a fresh instance * (unless the adapter factory implements caching/singleton behavior). * For performance, consider caching the resolved adapter in your app. */ declare function resolveAdapter(domain: D): AdapterForDomain; /** * Check if a resolver is registered for a specific domain and provider. * Useful for conditional logic around adapter availability. * * @param domain - The adapter domain * @param provider - The provider name * @returns True if a resolver is registered for this domain:provider, false otherwise * * @example * ```ts * if (hasResolver('ai', 'anthropic')) { * // Anthropic is available, can safely use it * const aiAdapter = resolveAdapter('ai'); * } * ``` */ declare function hasResolver(domain: ResolvableAdapterDomain, provider: string): boolean; /** * Clear all registered resolvers from the registry. * Primarily useful in testing to avoid state leakage between tests. * * @example * ```ts * beforeEach(() => { * clearResolvers(); // Clean up from previous test * // Re-register with test doubles * registerResolver('db', 'mock', createMockDbAdapter); * }); * ``` */ declare function clearResolvers(): void; /** * @module browser-storage-adapter * @description Implements the local-first admin adapter used for demos, * prototyping, and Storybook scenarios. The adapter stores admin-facing state * in guarded browser storage and mirrors the shared admin contract. */ /** * Creates the mock browser-storage-backed admin adapter used in demos and Storybook. * * @returns An admin adapter implementation that reuses the local auth dataset for management flows. * @throws {AdminError} When admin-facing browser storage reads or writes fail. */ declare function createLocalStorageAdminAdapter(): AdminAdapter; /** * @module localStorage * @description Implements the local-first AI adapter used for demos, * prototyping, and Storybook scenarios. The adapter stores chat history in * browser `localStorage` and returns deterministic canned responses. */ /** * Context passed to local AI mock response resolvers. */ interface LocalStorageAiResponseContext { /** Messages supplied to the current chat or stream request. */ messages: readonly ChatMessage[]; /** Inference options supplied by the caller, when present. */ options?: AiOptions; /** One-based successful request count for this adapter instance. */ requestCount: number; } /** * Controls deterministic rate-limit simulation for the local AI mock. */ interface LocalStorageAiRateLimitOptions { /** Number of successful AI operations allowed before RATE_LIMIT is thrown. */ afterRequests?: number; /** Error message used when the configured limit is reached. */ message?: string; } /** * Options for configuring the localStorage-backed AI mock. */ interface LocalStorageAiAdapterOptions { /** Deterministic response pool used when no custom resolver is supplied. */ responses?: readonly string[]; /** Optional resolver for per-request mock content. */ resolveResponse?: (context: LocalStorageAiResponseContext) => string; /** Enables deterministic RATE_LIMIT failures for tests and demos. */ rateLimit?: boolean | LocalStorageAiRateLimitOptions; } /** * Creates the mock localStorage-backed AI adapter used in demos and Storybook. * * @param options - Optional deterministic response and rate-limit simulation controls. * @returns An AI adapter implementation that emits deterministic canned responses and stores history locally. * Falls back to isolated in-memory history when browser storage is unavailable * during SSR or edge rendering. * * @throws {AiError} When browser storage quota exhaustion prevents history persistence. * @throws {AiError} With `RATE_LIMIT` when configured rate-limit simulation is reached. */ declare function createLocalStorageAiAdapter(options?: LocalStorageAiAdapterOptions): AiAdapter; /** * @module browser-storage-adapter * @description Implements the local-first authentication adapter used for * demos, prototyping, and Storybook scenarios. The adapter persists users and * sessions to guarded browser storage while conforming to the shared auth contract. */ /** * Creates the mock browser-storage-backed authentication adapter used in demos and Storybook. * * @returns An auth adapter implementation that persists users and sessions to browser storage. * @throws {AuthError} When browser storage reads or writes fail in a recoverable auth flow. */ declare function createLocalStorageAuthAdapter(): AuthAdapter; /** * @module localStorage * @description Implements the local-first database adapter used for demos, * prototyping, and Storybook scenarios. The adapter stores collections in * browser `localStorage` while conforming to the shared database contract. */ /** * Creates the mock localStorage-backed database adapter used in demos and Storybook. * * @returns A database adapter implementation that persists collections to browser storage. * @throws {DbError} When collection reads or writes fail during localStorage access. */ declare function createLocalStorageDbAdapter(): DbAdapter; /** * @module browser-storage-adapter * @description Implements the local-first payments adapter used for demos, * prototyping, and Storybook scenarios. The adapter stores plans and * subscriptions in guarded browser storage while mirroring the payments contract. */ /** * Creates the mock browser-storage-backed payments adapter used in demos and Storybook. * * @returns A payments adapter implementation that stores plans and subscriptions in browser storage. * @throws {PaymentsError} When plans or subscriptions cannot be persisted during method calls. */ declare function createLocalStoragePaymentsAdapter(): PaymentsAdapter; /** * Creates a payments adapter that accepts billing operations without contacting * a provider. * * @returns A no-op payments adapter used by CI, tests, and tiers that intentionally disable billing flows. */ declare function createNoopPaymentsAdapter(): PaymentsAdapter; /** * @module browser-storage-adapter * @description Implements the local-first file storage adapter used for demos, * prototyping, and Storybook scenarios. The adapter persists file metadata and * base64 payloads to guarded browser storage while following the shared contract. */ /** * Creates the mock browser-storage-backed file adapter used in demos and Storybook. * * @param options - Optional local adapter limits for test and prototype payloads. * @returns A file-storage adapter implementation that persists metadata and payloads to browser storage. * @throws {StorageError} When file metadata or blob payloads cannot be persisted or resolved. */ declare function createLocalStorageFileAdapter(options?: LocalStorageFileAdapterOptions): FileStorageAdapter; /** * @module console * @description Implements the shared console-backed logger used by the * adapters package. The logger applies log-level filtering, prefixes, and * contextual child loggers without requiring an external logging backend. */ /** * Configuration options for console logger behavior. */ interface ConsoleLoggerOptions { /** Minimum log level to display. Defaults to 'debug' in development, 'info' in production */ minLevel?: LogLevel; /** Prefix prepended to every log message (e.g., '[MyApp]', '[adapter]') */ prefix?: string; } /** * Creates a logger that outputs to browser/Node console. * * This is the default logger implementation for geenius adapters. * It filters logs by level and supports context via child loggers. * * Log levels are ordered by severity: * - debug: Detailed diagnostic information (disabled in production by default) * - info: General informational messages * - warn: Warning messages about unusual conditions * - error: Error messages about failures * * @param options - Configuration for logger behavior * @returns A LoggerAdapter instance that logs to console * * @example * ```ts * // Default setup - debug in dev, info in prod * const logger = createConsoleLoggerAdapter(); * * // Custom minimum level * const quietLogger = createConsoleLoggerAdapter({ minLevel: 'warn' }); * // Only warns and errors are printed * * // Custom prefix * const prefixedLogger = createConsoleLoggerAdapter({ * prefix: '[MyApp]', * minLevel: 'info' * }); * // Output: "[MyApp] Database connected" * * // Use in code * const dbLogger = await logger.child({ adapter: 'db', provider: 'convex' }); * dbLogger.info('Connection established'); // "[geenius] Connection established { adapter, provider }" * ``` */ declare function createConsoleLoggerAdapter(options?: ConsoleLoggerOptions): LoggerAdapter; /** * @module tier-gate * @description Declares the shared pricing-tier gating rules used by the * adapters package. The module maps features and packages to project tiers for * setup-time and runtime availability checks. */ /** * Supported project pricing tiers in ascending order of capability. * Determines which features and packages are available to a project. */ type ProjectTier = "pronto" | "lancio" | "studio"; /** * Configuration object defining feature and package access per tier. * Features and packages are cumulative - higher tiers inherit from lower tiers. * This means: * - lancio includes all pronto features + lancio-specific features * - studio includes all pronto + lancio features + studio-specific features */ interface TierGateConfig { /** Set of features available for each tier (key examples: 'auth', 'payments', 'ai-chat') */ features: Record; /** NPM packages available for each tier (key examples: '@geenius/admin', '@geenius/payments') */ packages: Record; } /** Readonly tier gating configuration used for frozen default tier records. */ type ReadonlyTierGateConfig = Readonly<{ features: Readonly>; packages: Readonly>; }>; /** * Result returned by requireTier() for feature availability checks. * The shape is intentionally explicit so UI code can render upgrade prompts * without throwing for normal "not available on this tier" outcomes. */ interface TierGateResult { /** True when the requested feature is available at the current tier. */ ok: boolean; /** Current project tier that was checked. */ tier: ProjectTier; /** Feature key that was requested. */ feature: string; /** The first tier where the feature becomes available, when known. */ requiredTier?: ProjectTier; /** Human-readable explanation for failed checks. */ reason?: string; } /** * Default tier gating configuration for geenius applications. * Defines all available features and packages organized by tier. * * Tier progression: * - pronto: Core features for rapid prototyping * - lancio: Production-ready with payments, admin, AI * - studio: Full-featured with advanced AI, analytics, teams, etc. */ declare const DEFAULT_TIER_GATE: ReadonlyTierGateConfig; /** * Require a feature for the current tier without throwing. * * @param tier - Current project tier * @param feature - Feature key to check * @param config - Optional tier-gate configuration, defaults to DEFAULT_TIER_GATE * @returns Result object describing whether the feature is available or which tier unlocks it */ declare function requireTier(tier: ProjectTier, feature: string, config?: TierGateConfig): TierGateResult; /** * Check if a specific feature is available for a given tier. * * @param feature - The feature name to check (e.g., 'payments', 'ai-chat') * @param tier - The tier to check against * @returns True if the feature is available in this tier, false otherwise * * @example * ```ts * if (isFeatureAvailable('payments', 'lancio')) { * // Show payment UI * } * ``` */ declare function isFeatureAvailable(feature: string, tier: ProjectTier): boolean; /** * Check if a specific package is available for a given tier. * * @param pkg - The package name to check (e.g., '@geenius/payments') * @param tier - The tier to check against * @returns True if the package is available in this tier, false otherwise * * @example * ```ts * if (isPackageAvailable('@geenius/admin', 'lancio')) { * // Package can be installed * } * ``` */ declare function isPackageAvailable(pkg: string, tier: ProjectTier): boolean; /** * Get all features available for a specific tier. * Includes features inherited from lower tiers. * * @param tier - The tier to get features for * @returns Array of available feature names * * @example * ```ts * const lancioFeatures = getAvailableFeatures('lancio'); * logger.info(lancioFeatures); // ['auth', 'i18n', 'ai-chat', 'admin', ...] * ``` */ declare function getAvailableFeatures(tier: ProjectTier): string[]; /** * Get all packages available for a specific tier. * Includes packages inherited from lower tiers. * * @param tier - The tier to get packages for * @returns Array of available package names * * @example * ```ts * const studioPackages = getAvailablePackages('studio'); * logger.info(studioPackages.length); // 35+ * ``` */ declare function getAvailablePackages(tier: ProjectTier): string[]; /** * Get the new features that would be unlocked by upgrading from one tier to another. * Useful for upgrade prompts and marketing copy. * * @param currentTier - The current tier the project is on * @param targetTier - The tier being upgraded to * @returns Array of feature names new in the target tier (not in current tier) * * @example * ```ts * const newFeatures = getUpgradeFeatures('pronto', 'lancio'); * logger.info(newFeatures); // ['admin', 'payments', 'blog', ...] * * // Use in UI * showUpgradeDialog({ * title: 'Upgrade to Lancio', * newFeatures: newFeatures, * benefitsList: newFeatures.map(f => `Unlock ${f}`) * }); * ``` */ declare function getUpgradeFeatures(currentTier: ProjectTier, targetTier: ProjectTier): string[]; export { ADAPTER_CONTRACT_BACKENDS, ADAPTER_CONTRACT_DOMAINS, ADAPTER_DOMAINS, ADAPTER_STATUSES, ADMIN_PROVIDERS, AI_PROVIDERS, AUTH_PROVIDERS, type AdapterConfig, type AdapterConfigForDomain, AdapterConfigurationError, AdapterContextError, type AdapterContractBackend, AdapterContractBackendSchema, type AdapterContractDomain, AdapterContractDomainSchema, AdapterContractError, type AdapterContractManifest, AdapterContractManifestSchema, type AdapterDomain, AdapterError, type AdapterHealth, AdapterHealthSchema, type AdapterInfrastructureErrorCode, AdapterInvariantError, type AdapterJsonValue, AdapterJsonValueSchema, type AdapterListOptions, AdapterListOptionsSchema, AdapterMetadataSchema, type AdapterProviderName, type AdapterProviderNameForDomain, type AdapterRegistryEntry, AdapterResolutionError, type AdapterStatus, type AdapterStatusInfo, type AdapterStatusType, type AdminAdapter, AdminError, type AdminErrorCode, type AdminListOptions, type AdminMetrics, type AdminProviderName, type AdminRole, type AdminRoleInput, type AdminTeam, type AdminTeamInput, type AiAdapter, AiError, type AiErrorCode, type AiOptions, type AiProviderName, type AuthAdapter, AuthContractError, AuthError, type AuthErrorCode, type AuthIdentity, AuthIdentitySchema, type AuthProviderAdapter, type AuthProviderName, type AuthSession, type AuthSessionContract, AuthSessionContractSchema, type AuthUser, BYOD_ORM_DB_PROVIDERS, type CacheAdapter, CacheContractError, type CacheEntry, CacheEntrySchema, type CacheSetOptions, CacheSetOptionsSchema, type ChatMessage, type ChatResponse, type ChatRole, type CheckoutParams, type CheckoutResult, type ConsoleLoggerOptions, type ContractResolverDomain, DB_PROVIDERS, DEFAULT_TIER_GATE, DOMAIN_DESCRIPTIONS, DOMAIN_ICONS, DOMAIN_LABELS, type DbAdapter, DbError, type DbErrorCode, type DbProviderName, type DeployAdapter, DeployContractError, type DeploymentResult, DeploymentResultSchema, type DeploymentTarget, DeploymentTargetSchema, type DomainAdapterConfig, ECOSYSTEM_DB_PROVIDERS, type EcosystemDbProviderCategory, type EcosystemDbProviderMeta, type EcosystemDbProviderName, type EcosystemDbProviderStage, type EventEnvelope, EventEnvelopeSchema, type EventPublishInput, EventPublishInputSchema, type EventSubscribeInput, EventSubscribeInputSchema, type EventSubscription, type EventsAdapter, EventsContractError, FUTURE_DB_PROVIDERS, type FileStorageAdapter, type FileStorageMetadata, FileStorageMetadataSchema, type FileStorageMetadataValue, FileStorageMetadataValueSchema, type FileUploadOptions, FileUploadOptionsSchema, LAUNCH_DB_PROVIDERS, LOGGER_PROVIDERS, type ListOptions, type LocalStorageAiAdapterOptions, type LocalStorageAiRateLimitOptions, type LocalStorageAiResponseContext, type LocalStorageFileAdapterOptions, type LogLevel, type LogMeta, type LoggerAdapter, type LoggerProviderName, type ManagedUser, type MemoryLogEntry, type MemoryLoggerAdapter, type MemoryLoggerOptions, type OAuthProvider, PAYMENT_PROVIDERS, PLATFORM_NATIVE_DB_PROVIDERS, PROVIDER_REGISTRY, type PaymentCheckoutInput, PaymentCheckoutInputSchema, type PaymentCheckoutSession, PaymentCheckoutSessionSchema, type PaymentPlanContract, PaymentPlanContractSchema, type PaymentProviderName, type PaymentSubscriptionContract, PaymentSubscriptionContractSchema, type PaymentsAdapter, PaymentsContractError, PaymentsError, type PaymentsErrorCode, type PaymentsProviderAdapter, type Plan, type ProjectTier, type ProviderMeta, type QueryCondition, type QueryFilter, type QueryOperator, type QueueAdapter, QueueContractError, type QueueJob, type QueueJobInput, QueueJobInputSchema, QueueJobSchema, type QueueJobStatus, QueueJobStatusSchema, type ReadonlyTierGateConfig, type ResolvableAdapterDomain, type RetryOptions, STORAGE_PROVIDERS, type StorageAdapter, StorageContractError, StorageError, type StorageErrorCode, type StorageObject, StorageObjectSchema, type StorageProviderName, type StorageWriteInput, StorageWriteInputSchema, type StoredFile, StoredFileSchema, type Subscription, type TierGateConfig, type TierGateResult, type WebhookDelivery, WebhookDeliverySchema, type WebhookEmitInput, WebhookEmitInputSchema, clearResolvers, configureAdapters, createConsoleLoggerAdapter, createLocalStorageAdminAdapter, createLocalStorageAiAdapter, createLocalStorageAuthAdapter, createLocalStorageDbAdapter, createLocalStorageFileAdapter, createLocalStoragePaymentsAdapter, createMemoryLoggerAdapter, createNoopPaymentsAdapter, getAdapterConfig, getAvailableFeatures, getAvailablePackages, getDomainConfig, getEcosystemDbProviderMeta, getEcosystemDbProvidersByCategory, getEcosystemDbProvidersByStage, getProviderMeta, getProvidersForDomain, getUpgradeFeatures, hasResolver, isAdapterError, isAdaptersConfigured, isFeatureAvailable, isPackageAvailable, isRetryable, registerResolver, requireTier, resetAdapterConfig, resolveAdapter, withRetry };