import { SdkBillingPlan, SdkConsentType } from '@sylphx/contract';

/**
 * REST Client for Sylphx Platform
 *
 * Type-safe REST API client built on plain `fetch` (no runtime `openapi-fetch`
 * dependency — ADR-084 routes types through `@sylphx/contract` so the codegen
 * layer no longer needs a transport library of its own). Public surface is
 * preserved: consumers still call `client.GET('/path')`, `client.POST(...)`,
 * etc. The middleware chain (deduplication → circuit breaker → ETag →
 * retry) runs in the same order as the previous implementation.
 *
 * @example
 * ```typescript
 * import { createRestClient } from '@sylphx/sdk'
 *
 * const client = createRestClient({
 *   secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey!,
 * })
 *
 * const { data: user, error } = await client.GET('/auth/me')
 * const { data: result } = await client.POST('/auth/login', {
 *   body: { email, password },
 * })
 * ```
 */
/**
 * Retry configuration for automatic request retries
 */
interface RetryConfig {
    /** Maximum number of retries (default: 3) */
    maxRetries?: number;
    /** Base delay in milliseconds (default: 1000) */
    baseDelay?: number;
    /** Maximum delay in milliseconds (default: 30000) */
    maxDelay?: number;
    /** Custom function to determine if error is retryable */
    shouldRetry?: (status: number, attempt: number) => boolean;
    /** Request timeout in milliseconds (default: 30000) */
    timeout?: number;
}
/**
 * Request deduplication configuration
 */
interface DeduplicationConfig {
    /** Enable request deduplication (default: true) */
    enabled?: boolean;
    /** HTTP methods to deduplicate (default: ['GET']) */
    methods?: ('GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH')[];
}
/**
 * Circuit breaker configuration (AWS/Resilience4j pattern)
 *
 * Prevents cascade failures by fast-failing when service is unhealthy.
 * States: CLOSED (normal) → OPEN (failing) → HALF_OPEN (testing)
 */
interface CircuitBreakerConfig {
    /** Enable circuit breaker (default: true) */
    enabled?: boolean;
    /** Number of failures before opening circuit (default: 5) */
    failureThreshold?: number;
    /** Time window for counting failures in ms (default: 10000) */
    windowMs?: number;
    /** How long circuit stays open in ms (default: 30000) */
    openDurationMs?: number;
    /** Custom function to determine if response is a failure */
    isFailure?: (status: number) => boolean;
}
/**
 * ETag/Conditional request configuration (HTTP caching pattern)
 *
 * Enables HTTP conditional requests with If-None-Match header
 * to avoid re-downloading unchanged data (saves bandwidth).
 */
interface ETagConfig {
    /** Enable ETag caching (default: true for GET requests) */
    enabled?: boolean;
    /** Maximum cache entries (default: 100) */
    maxEntries?: number;
    /** Cache TTL in milliseconds (default: 5 minutes) */
    ttlMs?: number;
}
/**
 * Configuration for the REST client
 *
 * The app key identifies the app — no separate app ID needed.
 */
interface RestClientConfig {
    /**
     * Your app key — identifies the app and environment.
     *
     * Accepts either:
     * - Secret key (sk_dev_, sk_stg_, sk_prod_) — full access, server-side only
     * - Publishable key (app_dev_, app_stg_, app_prod_) — limited access, safe for client
     */
    secretKey: string;
    /** Platform URL (default: https://sylphx.com) */
    platformUrl?: string;
    /** Retry configuration (default: 3 retries with exponential backoff) */
    retry?: RetryConfig | false;
    /**
     * Request deduplication configuration (default: enabled for GET)
     *
     * Prevents duplicate concurrent requests for the same resource.
     * When multiple components request the same data simultaneously,
     * only one API call is made and the result is shared.
     */
    deduplication?: DeduplicationConfig | false;
    /**
     * Circuit breaker configuration (default: enabled)
     *
     * Prevents cascade failures by fast-failing when service is unhealthy.
     * Opens after 5 failures in 10s, stays open for 30s, then allows test request.
     */
    circuitBreaker?: CircuitBreakerConfig | false;
    /**
     * ETag caching configuration (default: enabled for GET)
     *
     * Uses HTTP conditional requests to avoid re-downloading unchanged data.
     * Saves bandwidth by returning 304 Not Modified when content hasn't changed.
     */
    etag?: ETagConfig | false;
}
/**
 * Middleware contract — kept structurally identical to the previous
 * `openapi-fetch` shape so existing implementations (dedup / circuit breaker
 * / ETag / retry) compose without change.
 */
interface Middleware {
    onRequest?: (ctx: {
        request: Request;
    }) => Promise<Request | undefined> | Request | undefined;
    onFetch?: (ctx: {
        request: Request;
        next: (request: Request) => Promise<Response>;
    }) => Promise<Response | undefined> | Response | undefined;
    onResponse?: (ctx: {
        request: Request;
        response: Response;
    }) => Promise<Response | undefined> | Response | undefined;
}
/**
 * Options for an HTTP request — structural subset of `openapi-fetch`'s
 * `FetchOptions` so existing callsites (`client.GET('/path', { params: {...} })`)
 * continue to compile.
 */
interface RequestOptions {
    body?: unknown;
    params?: {
        path?: Record<string, string>;
        query?: Record<string, unknown>;
    };
    headers?: Record<string, string>;
}
/**
 * Response envelope — `{ data, error, response }` mirroring `openapi-fetch`.
 * `data` is present on 2xx, `error` on non-2xx; both carry the parsed JSON
 * body when the server returns one. `response` is always the raw `Response`
 * so consumers can read headers (Content-Type, Retry-After, etc.).
 */
interface FetchResponse<TOk, TError> {
    data?: TOk;
    error?: TError;
    response: Response;
}
/**
 * The typed method surface. Callers pass a path + options; return envelope
 * follows openapi-fetch's shape so migration is drop-in for the small number
 * of internal callers that relied on `.GET` / `.POST` etc.
 */
interface RestClient {
    GET<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
    POST<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
    PUT<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
    PATCH<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
    DELETE<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
    HEAD<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
    OPTIONS<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
    use(...middleware: readonly Middleware[]): void;
}

declare class InvalidConnectionUrlError extends Error {
    readonly code: "INVALID_CONNECTION_URL";
    constructor(message: string);
}

/**
 * SDK Configuration — ADR-055 Connection URL API
 *
 * v0.5.0: The primary entry point is `createClient(url)` which accepts
 * a `sylphx://` connection URL. The old `createConfig({ ref, publicKey })`
 * API is removed.
 *
 * @example
 * ```typescript
 * import { createClient } from '@sylphx/sdk'
 *
 * const sylphx = createClient(process.env.SYLPHX_URL!)
 * // Parses: sylphx://pk_prod_{ref?}_{hex}@bold-river-a1b2c3.api.sylphx.com
 * ```
 */

/**
 * SDK Configuration object — immutable, frozen.
 *
 * Created by `createClient()` or `createServerClient()`.
 * Passed to all pure SDK functions (`track()`, `signIn()`, etc.).
 */
interface SylphxConfig {
    /** The credential string (pk_* or sk_*) */
    readonly credential: string;
    /** Credential type: 'pk' (publishable) or 'sk' (secret) */
    readonly credentialType: 'pk' | 'sk';
    /** Target environment: dev, stg, prod, or prev */
    readonly env: 'dev' | 'stg' | 'prod' | 'prev';
    /** Resource slug (first DNS label), e.g. 'bold-river-a1b2c3' */
    readonly slug: string;
    /** Pre-computed API base URL, e.g. 'https://bold-river-a1b2c3.api.sylphx.com/v1' */
    readonly baseUrl: string;
    /** Optional access token for authenticated requests */
    readonly accessToken?: string;
    /**
     * Secret key — populated when credentialType is 'sk'.
     * Backward-compatible alias for `credential` when credential is sk_*.
     */
    readonly secretKey?: string;
    /**
     * Publishable key — populated when credentialType is 'pk'.
     * Backward-compatible alias for `credential` when credential is pk_*.
     */
    readonly publicKey?: string;
    /**
     * @deprecated Use `slug`. Backward-compatible alias.
     */
    readonly ref: string;
}
/**
 * Explicit components input — alternative to connection URL string.
 *
 * For multi-tenant apps or cases where components are stored separately.
 */
interface SylphxClientInput {
    /** Resource slug, e.g. 'bold-river-a1b2c3' */
    slug?: string;
    /** Publishable key (pk_*) — client-safe */
    publicKey?: string;
    /** Secret key (sk_*) — server-side only */
    secretKey?: string;
    /** Optional access token */
    accessToken?: string;
    /** API domain override (default: api.sylphx.com) */
    domain?: string;
    /**
     * @deprecated Use `slug`. Accepted for backward compatibility during migration.
     */
    ref?: string;
    /**
     * @deprecated Use `domain`. Accepted for backward compatibility during migration.
     */
    platformUrl?: string;
}
/**
 * Create a Sylphx client from a connection URL or explicit components.
 *
 * This is the primary SDK entry point for client-side (browser) usage.
 * Accepts a `sylphx://` connection URL or an explicit components object.
 *
 * @example Connection URL (recommended)
 * ```typescript
 * const sylphx = createClient(process.env.NEXT_PUBLIC_SYLPHX_URL!)
 * // Parses: sylphx://pk_prod_{ref?}_{hex}@bold-river-a1b2c3.api.sylphx.com
 * ```
 *
 * @example Explicit components
 * ```typescript
 * const sylphx = createClient({
 *   slug: 'bold-river-a1b2c3',
 *   publicKey: 'pk_prod_f19e...',
 * })
 * ```
 */
declare function createClient(input: string | SylphxClientInput): SylphxConfig;
/**
 * Create a Sylphx server client from a connection URL or explicit components.
 *
 * Equivalent to `createClient()` but validates that a secret key (sk_*) is provided.
 * Use this for server-side operations that require elevated permissions.
 *
 * @example Connection URL (recommended)
 * ```typescript
 * const sylphx = createServerClient(process.env.SYLPHX_SECRET_URL!)
 * // Parses: sylphx://sk_prod_{ref?}_{hex}@bold-river-a1b2c3.api.sylphx.com
 * ```
 *
 * @example Explicit components
 * ```typescript
 * const sylphx = createServerClient({
 *   slug: 'bold-river-a1b2c3',
 *   secretKey: 'sk_prod_5120...',
 * })
 * ```
 */
declare function createServerClient(input: string | SylphxClientInput): SylphxConfig;

/**
 * Billing Functions
 *
 * Pure functions for billing and subscriptions.
 * Uses REST API at /api/sdk/billing/* for all operations.
 *
 * Wire-shape types are re-exported from `@sylphx/contract` (ADR-084). The
 * contract is the single source of truth for `GET /billing/plans`,
 * `/billing/subscription`, `POST /billing/checkout`, `/billing/portal`,
 * `GET /billing/balance`, `/billing/usage`.
 */

type Plan = SdkBillingPlan;

/**
 * Consent Functions
 *
 * Pure functions for GDPR/CCPA consent management.
 *
 * ## Architecture (ADR-004)
 *
 * Consent uses **Inline Defaults + Auto-Discovery + Console Override**:
 * - Code provides optional inline defaults when checking consent
 * - Platform auto-discovers/creates consent types when first referenced
 * - Console can override names, descriptions, requirements without deployment
 *
 * Wire-shape types are re-exported from `@sylphx/contract` (ADR-084). The
 * contract is the single source of truth for `GET /consent/types`,
 * `GET /consent`, `POST /consent`, and friends. SDK-specific input types
 * (history pagination, anonymous linking) remain local — they describe
 * ergonomic helpers on top of the wire shapes rather than the wire
 * shapes themselves.
 *
 * @example
 * ```typescript
 * import { hasConsent, getUserConsents, setConsents } from '@sylphx/sdk'
 *
 * // Check consent with inline defaults (auto-discovered if doesn't exist)
 * if (await hasConsent(config, 'analytics', { userId: 'user-123' }, {
 *   name: 'Analytics Cookies',
 *   description: 'Help us understand how visitors use our site',
 *   category: 'analytics',
 *   required: false,
 * })) {
 *   track('pageview')
 * }
 *
 * // Get user's current consents
 * const consents = await getUserConsents(config, { userId: 'user-123' })
 *
 * // Set specific consents
 * await setConsents(config, {
 *   userId: 'user-123',
 *   consents: { analytics: true, marketing: false }
 * })
 * ```
 */

type ConsentType = SdkConsentType;

/**
 * AI Functions
 *
 * Pure functions for AI completions - Vercel AI SDK style.
 * Direct API calls with natural tree-shaking.
 *
 * Wire-shape types are re-exported from `@sylphx/contract` (ADR-084). The
 * contract is the single source of truth for `GET /ai/models`,
 * `/ai/usage`, `/ai/rate-limit`. Chat-completion / embedding envelopes
 * remain local to this module — they pass through the Vercel AI SDK
 * bridge and evolve independently of the platform contract.
 */

interface ChatMessage {
    role: 'system' | 'user' | 'assistant' | 'tool';
    content: string | ContentPart[];
    name?: string;
    tool_call_id?: string;
    tool_calls?: ToolCall[];
    /** Timestamp for UI display */
    timestamp?: Date;
}
interface ContentPart {
    type: 'text' | 'image_url';
    text?: string;
    image_url?: {
        url: string;
        detail?: 'auto' | 'low' | 'high';
    };
}
interface ToolCall {
    id: string;
    type: 'function';
    function: {
        name: string;
        arguments: string;
    };
}

/**
 * SDK-specific types — cross-layer helpers and server-first configuration.
 *
 * Wire-shape types (API request/response envelopes) live in
 * `@sylphx/contract` and are re-exported per namespace from their SDK
 * module (e.g. `Plan` / `Subscription` from `./billing`, `ConsentType`
 * from `./consent`, `TokenResponse` from `./auth`). React-hook wrapper
 * shapes live in `./react/types` (tRPC-like convenience shapes that
 * are not part of the platform wire).
 *
 * History: pre-ADR-084 this file mirrored every wire shape the SDK
 * exposed; those aliases now come directly from `@sylphx/contract`.
 */

declare const OAUTH_PROVIDERS: readonly ["google", "github", "apple", "microsoft", "facebook", "twitter", "discord", "linkedin", "slack", "gitlab", "bitbucket", "twitch", "spotify"];
type OAuthProviderId = (typeof OAUTH_PROVIDERS)[number];
interface OAuthProviderInfo$1 {
    id: OAuthProviderId;
    name: string;
}
interface FeatureFlagDefinition$1 {
    key: string;
    name: string;
    description: string | null;
    enabled: boolean;
    rolloutPercentage: number;
    targetPremiumOnly: boolean;
    targetAdminOnly: boolean;
}
interface AppMetadata$1 {
    id: string;
    name: string;
    slug: string;
}
/** Fetched server-side via `getAppConfig()`, passed to `SylphxProvider`. */
interface AppConfig {
    plans: Plan[];
    consentTypes: ConsentType[];
    oauthProviders: OAuthProviderInfo$1[];
    featureFlags: FeatureFlagDefinition$1[];
    app: AppMetadata$1;
    fetchedAt: string;
}
interface AccessTokenPayload {
    /** Raw UUID (OAuth/OIDC spec). */
    sub: string;
    /** Prefixed platform ID (e.g. `user_xxx`). */
    pid?: string;
    email: string;
    name?: string;
    picture?: string;
    email_verified: boolean;
    app_id: string;
    role?: string;
    /** Project session id when the token was minted from a BaaS auth session. */
    sid?: string;
    iat: number;
    exp: number;
}

/**
 * API Key Validation — Single Source of Truth
 *
 * OAuth 2.0 standard key validation for Sylphx Platform.
 * ALL key validation, sanitization, and environment detection logic lives here.
 *
 * Principles:
 * 1. Fail fast - Invalid input rejected immediately with clear errors
 * 2. Helpful errors - Tell users exactly what's wrong and how to fix it
 * 3. Development warnings - Warn about issues that would fail in production
 * 4. No silent fixes - Transparency over convenience (but warn + continue)
 * 5. Single Source of Truth - All key logic in one place
 *
 * Key Formats (ADR-021):
 * - Publishable key: pk_(dev|stg|prod|prev)_{ref}_{32hex} — client-safe (new)
 * - Secret Key:      sk_(dev|stg|prod|prev)_{ref}_{64hex} — server-side only
 *
 * Legacy Key Formats (backward-compat):
 * - App ID (old):    app_(dev|stg|prod|prev)_[identifier] — Public identifier
 *
 * Special Internal Formats (NOT rotated):
 * - Console bootstrap: app_prod_platform_{slug} / sk_prod_platform_{slug}
 */
/** Environment type derived from key prefix */
type EnvironmentType = 'development' | 'staging' | 'production' | 'preview';
/** Key type - publicKey (pk_*), appId (legacy app_*), or secret (sk_*) */
type KeyType = 'publicKey' | 'appId' | 'secret';
/** Validation result with clear error information */
interface KeyValidationResult {
    /** Whether the key is valid (possibly after sanitization) */
    valid: boolean;
    /** The sanitized key to use (only if valid) */
    sanitizedKey: string;
    /** Detected key type */
    keyType?: KeyType;
    /** Detected environment */
    environment?: EnvironmentType;
    /** Error message if invalid */
    error?: string;
    /** Warning message if key was auto-fixed */
    warning?: string;
    /** Detected issues for debugging */
    issues?: string[];
}
/**
 * Validate a legacy App ID (app_*) and return detailed results.
 *
 * @deprecated Use validatePublicKey() for new pk_* keys (ADR-021).
 *
 * @example
 * ```typescript
 * const result = validateAppId(process.env.NEXT_PUBLIC_SYLPHX_APP_ID)
 * if (!result.valid) {
 *   throw new Error(result.error)
 * }
 * if (result.warning) {
 *   console.warn(result.warning)
 * }
 * ```
 */
declare function validateAppId(key: string | undefined | null): KeyValidationResult;
/**
 * Validate and sanitize App ID, logging warnings.
 *
 * @deprecated Use validateAndSanitizePublicKey() for new pk_* keys (ADR-021).
 * @throws Error if the key is invalid and cannot be sanitized
 * @returns The sanitized App ID
 */
declare function validateAndSanitizeAppId(key: string | undefined | null): string;
/**
 * Validate a secret key and return detailed results
 *
 * @example
 * ```typescript
 * const result = validateSecretKey('sk_prod_...')
 * if (!result.valid) {
 *   throw new Error(result.error)
 * }
 * ```
 */
declare function validateSecretKey(key: string | undefined | null): KeyValidationResult;
/**
 * Validate and sanitize secret key, logging warnings
 *
 * @throws Error if the key is invalid and cannot be sanitized
 * @returns The sanitized secret key
 */
declare function validateAndSanitizeSecretKey(key: string | undefined | null): string;
/**
 * Detect environment type from any key (App ID or Secret Key)
 *
 * @example
 * ```typescript
 * detectEnvironment('sk_dev_abc123')   // 'development'
 * detectEnvironment('app_prod_xyz789') // 'production'
 * detectEnvironment('sk_stg_qwe456')   // 'staging'
 * ```
 *
 * @throws Error if key format is invalid
 */
declare function detectEnvironment(key: string): EnvironmentType;
/**
 * Check if running in development environment based on key
 */
declare function isDevelopmentKey(key: string): boolean;
/**
 * Check if running in production environment based on key
 */
declare function isProductionKey(key: string): boolean;
/**
 * Get the cookie namespace for a given secret key
 *
 * Used by auth middleware to namespace cookies per environment.
 * This prevents dev/staging/prod cookies from conflicting.
 *
 * @example
 * ```typescript
 * getCookieNamespace('sk_dev_abc123')  // 'sylphx_dev'
 * getCookieNamespace('sk_prod_xyz789') // 'sylphx_prod'
 * ```
 */
declare function getCookieNamespace(secretKey: string): string;
/**
 * Detect the type of key.
 *
 * @returns 'publicKey' (pk_*), 'appId' (legacy app_*), 'secret' (sk_*), or null if unknown
 */
declare function detectKeyType(key: string): KeyType | null;
/**
 * Check if a key is an App ID (legacy app_* format)
 *
 * @deprecated Use isPublishableKey() to also accept new pk_* keys
 */
declare function isAppId(key: string): boolean;
/**
 * Check if a key is a secret key (sk_*)
 */
declare function isSecretKey(key: string): boolean;
/**
 * Validate any key (auto-detects type)
 *
 * Use this when you accept either App ID or Secret Key.
 * The function auto-detects the key type and validates accordingly.
 *
 * @example
 * ```typescript
 * const result = validateKey('sk_prod_...')
 * if (!result.valid) {
 *   throw new Error(result.error)
 * }
 * const sanitizedKey = result.sanitizedKey
 * ```
 */
declare function validateKey(key: string | undefined | null): KeyValidationResult;
/**
 * Validate any key and return sanitized version (throws on error)
 *
 * Use this when you need the key value and want to throw on invalid input.
 */
declare function validateAndSanitizeKey(key: string | undefined | null): string;
/**
 * Check if we're in development mode (based on NODE_ENV or hostname)
 */
declare function isDevelopmentRuntime(): boolean;

/**
 * OAuth SDK — customer-app-facing social login (ADR-089 Phase 4a)
 *
 * Backed by `apps/runtime/src/server/runtime/routes/oauth.ts`:
 *
 *   POST /oauth/authorize   — initiate OAuth flow, returns provider URL
 *
 * The per-provider callback handler is a browser-side redirect endpoint
 * on the runtime (`GET /oauth/callback/{provider}`); SDK consumers
 * redirect the user to `authorizationUrl`, then receive a `code` on
 * their own `redirect_uri` which they exchange via `signIn()` or
 * `auth/login` with grant_type=authorization_code.
 *
 * PKCE is required per OAuth 2.1. Callers MUST generate `code_verifier`
 * + `code_challenge` and persist the verifier in session / cookie for
 * the subsequent token exchange — this SDK does not retain state.
 *
 * ## Distinction from `auth.oauth`
 *
 * `auth.oauth.*` (from `./auth`) targets platform-plane admin mint
 * (`/auth/platform-jwt/mint`) used by Console / CLI. The functions
 * here target the customer-app social-login flow.
 */

type OAuthProvider = OAuthProviderId | (string & {});

/**
 * Functions Client — Serverless V8 Isolate Functions (ADR-043)
 *
 * Deploy and manage serverless functions powered by Supabase Edge Runtime.
 * Functions run in isolated V8 contexts with < 5ms cold starts.
 *
 * ## Key Concepts
 *
 * - Functions are TypeScript/JavaScript handlers deployed to the Sylphx edge runtime
 * - Invoked via HTTP: GET/POST https://{project}.sylphx.app/functions/{name}
 * - Can access all Sylphx BaaS services via the SDK inside the handler
 * - Isolated per project — no shared state between projects
 *
 * ## Quick Start
 *
 * ```typescript
 * // functions/hello-world/index.ts — your function code
 * import { createServerClient } from '@sylphx/sdk/server'
 *
 * export default async function handler(req: Request): Promise<Response> {
 *   const { name } = await req.json()
 *   return Response.json({ message: `Hello, ${name}!` })
 * }
 * ```
 *
 * ```typescript
 * // Deploy programmatically from trusted server-side tooling
 * import { createConfig, FunctionsClient } from '@sylphx/sdk'
 *
 * const config = createConfig({ secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey! })
 *
 * await FunctionsClient.deploy(config, {
 *   name: 'hello-world',
 *   code: `export default async (req) => Response.json({ ok: true })`,
 * })
 *
 * // Invoke the function
 * const result = await FunctionsClient.invoke(config, 'hello-world', { name: 'world' })
 * ```
 *
 * ## Available in handler
 *
 * All Web Standard APIs are available inside function handlers:
 * - `fetch()` — HTTP requests
 * - `Request`, `Response`, `Headers`, `URL`
 * - `crypto` — Web Crypto API
 * - `TextEncoder`, `TextDecoder`
 * - `Deno.env.get('KEY')` — access injected env vars
 *
 * ## Constraints
 *
 * - Memory: 150 MB default (max 512 MB)
 * - Timeout: 30s default (max 120s)
 * - No filesystem access (`fs` module unavailable)
 * - No raw socket access (`net` module unavailable)
 * - npm packages via CDN URL: `import { z } from 'https://esm.sh/zod'`
 */

type FunctionStatus = 'active' | 'deploying' | 'failed' | 'disabled';
type FunctionRuntime = 'deno';
interface FunctionDeployOptions {
    /**
     * Function slug — URL-safe name (lowercase kebab-case).
     * Used in the invocation URL: /functions/{name}
     */
    name: string;
    /**
     * TypeScript/JavaScript source code.
     * Must export a default handler function:
     *   export default async function(req: Request): Promise<Response> { ... }
     *
     * For larger bundles, use a production-backed deployment workflow that
     * uploads source as an artifact instead of embedding it in JSON.
     */
    code: string;
    /** Human-readable display name */
    displayName?: string;
    /** Short description shown in console */
    description?: string;
    /** Memory limit in MB (default: 150, max: 512) */
    memoryMb?: number;
    /** Execution timeout in seconds (default: 30, max: 120) */
    timeoutSeconds?: number;
    /** Per-function env var overrides (merged with project env vars) */
    envVars?: Record<string, string>;
    /** Whether invocations require Sylphx platform auth (default: false) */
    requireAuth?: boolean;
    /** Target environment slug (default: 'production') */
    environment?: string;
}
interface FunctionRecord {
    id: string;
    name: string;
    displayName: string | null;
    description: string | null;
    status: FunctionStatus;
    version: number;
    runtime: FunctionRuntime;
    memoryMb: number;
    timeoutSeconds: number;
    requireAuth: boolean;
    invocationCount: number;
    errorCount: number;
    lastInvokedAt: string | null;
    /** Invocation URL */
    url: string;
    createdAt: string;
    updatedAt: string;
}
interface FunctionDeployResult {
    id: string;
    name: string;
    version: number;
    status: FunctionStatus;
    /** The live invocation URL */
    url: string;
}
interface FunctionInvokeOptions {
    /** HTTP method (default: POST) */
    method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
    /** Request headers */
    headers?: Record<string, string>;
    /** Request body (JSON-serialized automatically) */
    body?: unknown;
    /** Query parameters appended to the URL */
    query?: Record<string, string>;
}
interface FunctionListOptions {
    /** Filter by status */
    status?: FunctionStatus;
    /** Environment slug (default: 'production') */
    environment?: string;
    /** Max results (default: 50) */
    limit?: number;
}
interface FunctionLogsOptions {
    /** Maximum log entries to return (default: 100) */
    limit?: number;
    /** Only return errors */
    errorsOnly?: boolean;
    /** ISO timestamp — only logs after this time */
    since?: string;
}
interface FunctionLogEntry {
    id: string;
    status: 'success' | 'error' | 'timeout';
    statusCode: number | null;
    durationMs: number | null;
    method: string;
    path: string | null;
    errorMessage: string | null;
    createdAt: string;
}
declare const FunctionsClient: {
    /**
     * Deploy (create or update) a function.
     *
     * If a function with the same name already exists, it is updated
     * (version number incremented, code replaced atomically).
     *
     * @example
     * ```typescript
     * const fn = await FunctionsClient.deploy(config, {
     *   name: 'send-webhook',
     *   code: `
     *     export default async (req: Request) => {
     *       const body = await req.json()
     *       await fetch(body.url, { method: 'POST', body: JSON.stringify(body.payload) })
     *       return Response.json({ ok: true })
     *     }
     *   `,
     *   timeoutSeconds: 10,
     * })
     * console.log('Deployed:', fn.url)
     * ```
     */
    readonly deploy: (config: SylphxConfig, options: FunctionDeployOptions) => Promise<FunctionDeployResult>;
    /**
     * Get a function by name.
     */
    readonly get: (config: SylphxConfig, name: string) => Promise<FunctionRecord>;
    /**
     * List all functions for this project.
     */
    readonly list: (config: SylphxConfig, options?: FunctionListOptions) => Promise<FunctionRecord[]>;
    /**
     * Delete a function permanently.
     */
    readonly delete: (config: SylphxConfig, name: string) => Promise<void>;
    /**
     * Invoke a function from server-side code.
     *
     * For client-side invocations, call the function URL directly via fetch().
     *
     * @example
     * ```typescript
     * const result = await FunctionsClient.invoke(config, 'process-order', {
     *   body: { orderId: '123', userId: 'user_abc' },
     * })
     * ```
     */
    readonly invoke: <T = unknown>(config: SylphxConfig, name: string, body?: unknown, options?: FunctionInvokeOptions) => Promise<T>;
    /**
     * Retrieve recent invocation logs for a function.
     *
     * @example
     * ```typescript
     * const logs = await FunctionsClient.logs(config, 'send-webhook', { errorsOnly: true })
     * for (const entry of logs) {
     *   console.log(`${entry.status} ${entry.durationMs}ms`, entry.errorMessage)
     * }
     * ```
     */
    readonly logs: (config: SylphxConfig, name: string, options?: FunctionLogsOptions) => Promise<FunctionLogEntry[]>;
};

/**
 * Platform ID utilities for the Sylphx SDK
 *
 * Converts between raw UUIDs (used internally / in JWT sub claims) and
 * prefixed TypeID strings (used in all API responses and JWT pid claims).
 *
 * Uses TypeID spec v0.3.0 (Crockford base32, case-insensitive).
 * Also accepts legacy base58 format for backward compatibility.
 *
 * No external dependencies — pure TypeScript implementation of Crockford base32.
 *
 * @example
 * ```ts
 * import { encodeUserId, decodeUserId } from '@sylphx/sdk/nextjs'
 *
 * const prefixed = encodeUserId('018f4a3b-1c2d-7000-9abc-def012345678')
 * // => 'user_01h2xcejqtf2nbrexx3vqjhp41'
 *
 * const uuid = decodeUserId('user_01h2xcejqtf2nbrexx3vqjhp41')
 * // => '018f4a3b-1c2d-7000-9abc-def012345678'
 * ```
 */
/**
 * Encode a raw UUID as a prefixed TypeID user ID.
 *
 * @param uuid - Raw UUID string (with or without dashes)
 * @returns Prefixed TypeID: `user_<crockford_base32>`
 */
declare function encodeUserId(uuid: string): string;
/**
 * Decode a prefixed user ID back to a raw UUID.
 * Accepts both TypeID (current) and base58 (legacy) formats.
 *
 * @param prefixedId - Prefixed user ID: `user_<encoded>`
 * @returns Raw UUID string, or null if invalid
 */
declare function decodeUserId(prefixedId: string): string | null;

/**
 * Server-side AI Client
 *
 * Creates an OpenAI-compatible client configured for Sylphx Platform.
 * Use this in Server Components, API routes, and server actions.
 *
 * @example
 * ```ts
 * import { createAI } from '@sylphx/platform-sdk/server'
 *
 * const ai = createAI()
 *
 * // Chat completion
 * const response = await ai.chat({
 *   model: 'anthropic/claude-3.5-sonnet',
 *   messages: [{ role: 'user', content: 'Hello!' }],
 * })
 *
 * // Embeddings
 * const embeddings = await ai.embed({
 *   model: 'openai/text-embedding-3-small',
 *   input: 'Hello world',
 * })
 *
 * // Streaming
 * const stream = await ai.chat({
 *   model: 'anthropic/claude-3.5-sonnet',
 *   messages: [{ role: 'user', content: 'Tell me a story' }],
 *   stream: true,
 * })
 *
 * for await (const chunk of stream) {
 *   process.stdout.write(chunk.choices[0]?.delta?.content || '')
 * }
 * ```
 */
interface AIClientOptions {
    /** Server connection URL. Defaults to SYLPHX_SECRET_URL. */
    secretUrl?: string;
    /** @deprecated Use secretUrl. */
    secretKey?: string;
    /** Platform URL (default: https://api.sylphx.com) */
    platformUrl?: string;
}

interface ChatCompletionOptions {
    model: string;
    messages: ChatMessage[];
    temperature?: number;
    max_tokens?: number;
    top_p?: number;
    frequency_penalty?: number;
    presence_penalty?: number;
    stop?: string | string[];
    stream?: false;
    user?: string;
}
interface ChatCompletionStreamOptions extends Omit<ChatCompletionOptions, 'stream'> {
    stream: true;
}
interface ChatCompletionResponse {
    id: string;
    object: 'chat.completion';
    created: number;
    model: string;
    choices: Array<{
        index: number;
        message: {
            role: 'assistant';
            content: string;
        };
        finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | null;
    }>;
    usage: {
        prompt_tokens: number;
        completion_tokens: number;
        total_tokens: number;
    };
}
interface ChatCompletionChunk {
    id: string;
    object: 'chat.completion.chunk';
    created: number;
    model: string;
    choices: Array<{
        index: number;
        delta: {
            role?: 'assistant';
            content?: string;
        };
        finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | null;
    }>;
}
interface EmbeddingOptions {
    model: string;
    input: string | string[];
    dimensions?: number;
    user?: string;
}
interface EmbeddingResponse {
    object: 'list';
    data: Array<{
        object: 'embedding';
        index: number;
        embedding: number[];
    }>;
    model: string;
    usage: {
        prompt_tokens: number;
        total_tokens: number;
    };
}
interface ModelInfo {
    id: string;
    name: string;
    context_length: number;
    pricing: {
        prompt: string;
        completion: string;
    };
    capabilities: string[];
}
interface ModelsResponse {
    object: 'list';
    data: ModelInfo[];
}
interface AIClient {
    /** Create a chat completion */
    chat(options: ChatCompletionOptions): Promise<ChatCompletionResponse>;
    /** Create a streaming chat completion */
    chat(options: ChatCompletionStreamOptions): Promise<AsyncIterable<ChatCompletionChunk>>;
    /** Create embeddings */
    embed(options: EmbeddingOptions): Promise<EmbeddingResponse>;
    /** List available models */
    listModels(options?: {
        capability?: string;
        search?: string;
    }): Promise<ModelsResponse>;
}
/**
 * Create a server-side AI client
 *
 * Uses environment variables by default:
 *
 * - SYLPHX_SECRET_URL: Your app's server connection URL
 */
declare function createAI(options?: AIClientOptions): AIClient;
/**
 * Get the default AI client (singleton)
 * Creates one using environment variables on first call
 */
declare function getAI(): AIClient;

/**
 * KV (Key-Value Store) Types
 *
 * Shared type definitions for KV operations.
 * Used by both server-side client (server/kv.ts) and React hooks (react/hooks/use-kv.ts).
 *
 * Single Source of Truth — never duplicate these types.
 */
/** TTL options for SET operations */
interface KvSetOptions {
    /** Expire time in seconds */
    ex?: number;
    /** Expire time in milliseconds */
    px?: number;
    /** Unix timestamp (seconds) at which the key will expire */
    exat?: number;
    /** Unix timestamp (milliseconds) at which the key will expire */
    pxat?: number;
    /** Only set the key if it does not already exist */
    nx?: boolean;
    /** Only set the key if it already exists */
    xx?: boolean;
}
/** Rate limit result */
interface KvRateLimitResult {
    /** Whether the request is allowed (under rate limit) */
    success: boolean;
    /** The rate limit maximum */
    limit: number;
    /** Remaining requests in current window */
    remaining: number;
    /** Unix timestamp (ms) when the rate limit resets */
    reset: number;
}
/** Sorted set member */
interface KvZMember {
    /** Member identifier */
    member: string;
    /** Score for ranking */
    score?: number;
}

/**
 * Server-side KV (Key-Value Store) Client
 *
 * Creates a client for key-value operations via Upstash Redis.
 * Use this in Server Components, API routes, and server actions.
 *
 * @example
 * ```ts
 * import { createKv } from '@sylphx/sdk/server'
 *
 * const kv = createKv()
 *
 * // Basic operations
 * await kv.set('user:123:profile', { name: 'John' }, { ex: 3600 })
 * const profile = await kv.get('user:123:profile')
 *
 * // Atomic counter
 * const views = await kv.incr('page:home:views')
 *
 * // Rate limiting
 * const { success, remaining } = await kv.ratelimit('api:user123', {
 *   limit: 100,
 *   window: '1h',
 * })
 * ```
 */

interface KvClientOptions {
    /** Server connection URL. Defaults to SYLPHX_SECRET_URL. */
    secretUrl?: string;
    /** @deprecated Use secretUrl. */
    secretKey?: string;
    /** Platform URL (default: https://api.sylphx.com) */
    platformUrl?: string;
}
interface KvClient {
    /**
     * Get a value by key
     *
     * @param key - Key name
     * @returns The value, or null if not found
     */
    get<T = unknown>(key: string): Promise<{
        value: T | null;
        ttl: number | null;
    }>;
    /**
     * Set a value
     *
     * @param key - Key name
     * @param value - Any JSON-serializable value
     * @param options - TTL and conditional options (ex, px, nx, xx)
     * @returns Whether the SET was successful
     */
    set<T = unknown>(key: string, value: T, options?: KvSetOptions): Promise<boolean>;
    /**
     * Delete a key
     *
     * @param key - Key name
     * @returns Number of keys deleted (0 or 1)
     */
    del(key: string): Promise<number>;
    /**
     * Check if a key exists
     *
     * @param key - Key name
     * @returns Whether the key exists
     */
    exists(key: string): Promise<boolean>;
    /**
     * Get multiple values
     *
     * @param keys - Array of keys to get (max 100)
     * @returns Map of key -> value (null if not found)
     */
    mget<T = unknown>(keys: string[]): Promise<Record<string, T | null>>;
    /**
     * Set multiple values
     *
     * @param entries - Array of { key, value } pairs (max 100)
     * @param options - TTL options (ex or px only)
     */
    mset<T = unknown>(entries: Array<{
        key: string;
        value: T;
    }>, options?: Pick<KvSetOptions, 'ex' | 'px'>): Promise<void>;
    /**
     * Increment a numeric value atomically
     *
     * Creates key with value 0 if it does not exist.
     *
     * @param key - Key name
     * @param by - Amount to increment by (default: 1, use negative for decrement)
     * @returns The value after increment
     */
    incr(key: string, by?: number): Promise<number>;
    /**
     * Set key expiration
     *
     * @param key - Key name
     * @param seconds - TTL in seconds
     * @returns Whether the TTL was set (false if key does not exist)
     */
    expire(key: string, seconds: number): Promise<boolean>;
    /**
     * Check rate limit using sliding window algorithm
     *
     * @param key - Rate limit identifier (e.g., "api:user123")
     * @param options - Limit and window configuration
     * @returns Rate limit status
     *
     * @example
     * ```ts
     * const { success, remaining, reset } = await kv.ratelimit('api:user123', {
     *   limit: 100,
     *   window: '1h',
     * })
     *
     * if (!success) {
     *   throw new Error('Rate limit exceeded')
     * }
     * ```
     */
    ratelimit(key: string, options: {
        limit: number;
        window: string;
    }): Promise<KvRateLimitResult>;
    /**
     * Set hash fields
     *
     * @param key - Hash key
     * @param fields - Field-value pairs to set
     * @returns Number of fields that were created (not updated)
     */
    hset<T = unknown>(key: string, fields: Record<string, T>): Promise<number>;
    /**
     * Get a hash field
     *
     * @param key - Hash key
     * @param field - Field name
     * @returns Field value, or null if not found
     */
    hget<T = unknown>(key: string, field: string): Promise<T | null>;
    /**
     * Get all hash fields
     *
     * @param key - Hash key
     * @returns All field-value pairs, or null if key does not exist
     */
    hgetall<T = unknown>(key: string): Promise<Record<string, T> | null>;
    /**
     * Push values to the left of a list
     *
     * @param key - List key
     * @param values - Values to push
     * @returns Length of the list after push
     */
    lpush<T = unknown>(key: string, ...values: T[]): Promise<number>;
    /**
     * Get a range of elements from a list
     *
     * @param key - List key
     * @param start - Start index (0-based, negative for from end)
     * @param stop - Stop index (inclusive, -1 for end)
     * @returns Values in the specified range
     */
    lrange<T = unknown>(key: string, start?: number, stop?: number): Promise<T[]>;
    /**
     * Add members with scores to a sorted set
     *
     * @param key - Sorted set key
     * @param members - Score-member pairs
     * @returns Number of members added (not updated)
     */
    zadd(key: string, ...members: Array<{
        score: number;
        member: string;
    }>): Promise<number>;
    /**
     * Get members from a sorted set by rank range
     *
     * @param key - Sorted set key
     * @param start - Start rank (0-based)
     * @param stop - Stop rank (inclusive)
     * @param options - Include scores and/or reverse order
     * @returns Members in the specified range
     */
    zrange(key: string, start?: number, stop?: number, options?: {
        withScores?: boolean;
        rev?: boolean;
    }): Promise<KvZMember[]>;
}
/**
 * Create a server-side KV client
 *
 * Uses environment variables by default:
 * - SYLPHX_SECRET_URL: Your app's server connection URL
 */
declare function createKv(options?: KvClientOptions): KvClient;
/**
 * Get the default KV client (singleton)
 * Creates one using environment variables on first call
 */
declare function getKv(): KvClient;

/**
 * Shared Realtime Types
 *
 * Single source of truth for types used by both:
 * - Server: streams.ts (createStreams)
 * - React: use-realtime.ts (useRealtime hook)
 */
/** A message from a stream */
interface StreamMessage<T = unknown> {
    /** Stream entry ID (e.g., "1234567890-0") */
    id: string;
    /** Event type */
    event: string;
    /** Channel the message was sent to */
    channel: string;
    /** Event data */
    data: T;
    /** Unix timestamp in milliseconds */
    timestamp?: number;
}

/**
 * Server-side Streams Client
 *
 * Creates a client for real-time pub/sub via Redis Streams.
 * Use this in Server Components, API routes, and server actions.
 *
 * @example
 * ```ts
 * import { createStreams } from '@sylphx/sdk/server'
 *
 * const streams = createStreams()
 *
 * // Emit an event
 * const id = await streams.emit('chat:room-1', 'message', {
 *   text: 'Hello!',
 *   userId: '123',
 * })
 *
 * // Get message history
 * const messages = await streams.history('chat:room-1', { limit: 50 })
 *
 * // Using channel helper
 * const room = streams.channel('chat:room-1')
 * await room.emit('message', { text: 'Hello!' })
 * const history = await room.history({ limit: 50 })
 * ```
 */

interface StreamsClientOptions {
    /** Server connection URL. Defaults to SYLPHX_SECRET_URL. */
    secretUrl?: string;
    /** @deprecated Use secretUrl. */
    secretKey?: string;
    /** Platform URL (default: https://api.sylphx.com) */
    platformUrl?: string;
}
/** Options for fetching stream history */
interface StreamHistoryOptions {
    /** Start ID ("-" for oldest) */
    start?: string;
    /** End ID ("+" for newest) */
    end?: string;
    /** Maximum number of messages (max 1000) */
    limit?: number;
}
/** Helper for a specific channel */
interface ChannelHelper {
    /** Emit an event to this channel */
    emit<T>(event: string, data: T): Promise<string>;
    /** Get message history for this channel */
    history<T>(options?: StreamHistoryOptions): Promise<StreamMessage<T>[]>;
}
interface StreamsClient {
    /**
     * Emit an event to a channel
     *
     * @param channel - Channel name (e.g., "chat:room-1")
     * @param event - Event type (e.g., "message")
     * @param data - Event data (any JSON-serializable value)
     * @returns Stream entry ID
     */
    emit<T>(channel: string, event: string, data: T): Promise<string>;
    /**
     * Get message history for a channel
     *
     * @param channel - Channel name
     * @param options - History options (start, end, limit)
     * @returns Array of messages in chronological order
     */
    history<T>(channel: string, options?: StreamHistoryOptions): Promise<StreamMessage<T>[]>;
    /**
     * Get a channel helper for convenient operations
     *
     * @param channel - Channel name
     * @returns Channel helper with emit() and history()
     */
    channel(name: string): ChannelHelper;
}
/**
 * Create a server-side Streams client
 *
 * Uses environment variables by default:
 *
 * - SYLPHX_SECRET_URL: Your app's server connection URL
 */
declare function createStreams(options?: StreamsClientOptions): StreamsClient;
/**
 * Get the default Streams client (singleton)
 * Creates one using environment variables on first call
 */
declare function getStreams(): StreamsClient;

/**
 * Sylphx Server SDK
 *
 * Server-side operations using REST API for type safety.
 * Uses connection URL (sylphx://sk_*@tenant-slug.api.sylphx.com) for authentication.
 *
 * @example
 * ```typescript
 * import { createServerClient, verifyWebhook } from '@sylphx/sdk/server'
 *
 * const sylphx = createServerClient(process.env.SYLPHX_SECRET_URL!)
 * const client = createServerRestClient({
 *   secretKey: sylphx.secretKey!,
 *   platformUrl: sylphx.baseUrl.replace(/\/v1$/, ''),
 * })
 *
 * // REST API calls
 * const { data: plans } = await client.GET('/billing/plans')
 * const { data: user } = await client.GET('/user/profile')
 * ```
 */

interface ServerConfig {
    /**
     * Your Secret Key (keep secure, server-only)
     *
     * The secret key IS the app identity — no separate app ID needed.
     * Use environment-specific keys for proper isolation:
     * - Development: sk_dev_xxx (relaxed rate limits, test mode)
     * - Staging: sk_stg_xxx (test mode, production-like settings)
     * - Production: sk_prod_xxx (strict settings, live data)
     */
    secretKey: string;
    /** Platform URL (defaults to https://sylphx.com) */
    platformUrl?: string;
    /** Optional cache TTL in seconds. Default: 60 */
    revalidate?: number;
}
/**
 * Create a Server REST Client for type-safe API calls.
 *
 * For the new connection URL API, use `createServerClient()` from '@sylphx/sdk'.
 * This function creates an openapi-fetch REST client from a raw secret key.
 *
 * @example
 * ```typescript
 * const client = createServerRestClient({
 *   secretKey: 'sk_prod_...',
 * })
 *
 * const { data: plans } = await client.GET('/billing/plans')
 * ```
 */
declare function createServerRestClient(config: ServerConfig): RestClient;
/**
 * Create a Server REST Client with user context (access token)
 */
declare function createAuthenticatedServerClient(config: ServerConfig, accessToken: string): RestClient;
/**
 * Reset the JWKS cache.
 *
 * Use in tests to prevent state bleed between test cases.
 * In production, the cache auto-expires after JWK_CACHE_TTL_MS (1 hour).
 *
 * @example
 * ```typescript
 * afterEach(() => resetJwksCache())
 * ```
 */
declare function resetJwksCache(): void;
/**
 * Fetch JWKS from the platform
 */
declare function getJwks(platformUrl?: string): Promise<JsonWebKey[]>;
/**
 * Verify an access token from the platform
 */
declare function verifyAccessToken(token: string, options: {
    secretKey?: string;
    platformUrl?: string;
}): Promise<AccessTokenPayload>;
interface WebhookPayload {
    event: string;
    data: unknown;
    timestamp: number;
    id: string;
}
interface WebhookVerifyResult {
    valid: boolean;
    payload?: WebhookPayload;
    error?: string;
}
interface WebhookVerifyOptions {
    /** Maximum age of webhook in milliseconds (default: 5 minutes) */
    maxAge?: number;
    /** Allow clock skew in milliseconds (default: 30 seconds) */
    clockSkew?: number;
}
/**
 * Verify webhook signature from Sylphx Platform
 *
 * The platform sends `X-Webhook-Signature` in `t={unix_seconds},v1={hmac_hex}`
 * format. This function accepts either:
 * - The raw header value (auto-parsed)
 * - Pre-extracted `signature` + `timestamp` strings
 *
 * @example
 * ```typescript
 * import { verifyWebhook } from '@sylphx/sdk/server'
 *
 * export async function POST(request: Request) {
 *   const body = await request.text()
 *   const result = await verifyWebhook({
 *     payload: body,
 *     signatureHeader: request.headers.get('x-webhook-signature'),
 *     secret: process.env.SYLPHX_WEBHOOK_SECRET!,
 *   })
 *
 *   if (!result.valid) {
 *     return new Response('Invalid signature', { status: 401 })
 *   }
 *
 *   console.log('Received webhook:', result.payload)
 * }
 * ```
 */
declare function verifyWebhook(options: {
    payload: string;
    /** Raw X-Webhook-Signature header value: "t={seconds},v1={hex}" */
    signatureHeader?: string | null;
    /** Pre-extracted HMAC hex (if parsing header yourself) */
    signature?: string | null;
    /** Pre-extracted timestamp in unix seconds (if parsing header yourself) */
    timestamp?: string | null;
    secret: string;
    verifyOptions?: WebhookVerifyOptions;
}): Promise<WebhookVerifyResult>;
/**
 * Create a webhook handler with automatic verification
 *
 * @example
 * ```typescript
 * import { createWebhookHandler } from '@sylphx/sdk/server'
 *
 * const handler = createWebhookHandler({
 *   secret: process.env.SYLPHX_WEBHOOK_SECRET!,
 *   handlers: {
 *     'user.created': async (data) => {
 *       console.log('New user:', data)
 *     },
 *     'subscription.updated': async (data) => {
 *       console.log('Subscription changed:', data)
 *     },
 *   },
 * })
 *
 * export { handler as POST }
 * ```
 */
declare function createWebhookHandler(config: {
    secret: string;
    handlers: Record<string, (data: unknown) => Promise<void> | void>;
    verifyOptions?: WebhookVerifyOptions;
}): (request: Request) => Promise<Response>;

/** Common options for authenticated SDK fetch — secret key identifies the app */
interface AuthenticatedFetchOptions {
    /** Secret key for authentication (sk_dev_xxx, sk_stg_xxx, sk_prod_xxx) */
    secretKey: string;
    /** Platform URL (defaults to https://sylphx.com) */
    platformUrl?: string;
    /** Optional cache TTL in seconds. Default: 60 */
    revalidate?: number;
}
/**
 * Options for public endpoints that only need an App ID (public key).
 * The App ID IS the app identity — no separate key needed.
 */
interface PublicFetchOptions {
    /** App ID (app_dev_xxx, app_stg_xxx, app_prod_xxx) — identifies the app */
    appId: string;
    /** Platform URL (defaults to https://sylphx.com) */
    platformUrl?: string;
    /** Optional cache TTL in seconds. Default: 60 */
    revalidate?: number;
}

/** OAuth provider with display name */
interface OAuthProviderInfo {
    id: OAuthProvider;
    name: string;
}
/**
 * Get enabled OAuth providers for an app (server-side)
 *
 * The App ID identifies the app via `X-App-Id` header.
 *
 * @example
 * ```tsx
 * const providers = await getOAuthProviders({
 *   appId: process.env.NEXT_PUBLIC_SYLPHX_APP_ID!,
 * })
 * ```
 */
declare function getOAuthProviders(options: PublicFetchOptions): Promise<OAuthProvider[]>;
/**
 * Get enabled OAuth providers with full info (server-side)
 */
declare function getOAuthProvidersWithInfo(options: PublicFetchOptions): Promise<OAuthProviderInfo[]>;

/**
 * Get subscription plans for an app (server-side)
 *
 * Note: Prefer using `getAppConfig()` which fetches all config in parallel.
 * This function is used internally by `getAppConfig()`.
 */
declare function getPlans(options: AuthenticatedFetchOptions): Promise<Plan[]>;

/**
 * Get consent types for an app (server-side)
 *
 * Note: Prefer using `getAppConfig()` which fetches all config in parallel.
 * This function is used internally by `getAppConfig()`.
 */
declare function getConsentTypes(options: AuthenticatedFetchOptions): Promise<ConsentType[]>;
/** Feature flag definition for SSR */
interface FeatureFlagDefinition {
    key: string;
    name: string;
    description: string | null;
    enabled: boolean;
    rolloutPercentage: number;
    targetPremiumOnly: boolean;
    targetAdminOnly: boolean;
}
/**
 * Get feature flag definitions for an app (server-side)
 *
 * Returns flag definitions. Evaluation (rollout, targeting) happens
 * client-side using the LocalEvaluator with user context.
 *
 * @example
 * ```tsx
 * import { getFeatureFlags } from '@sylphx/sdk/server'
 *
 * export default async function RootLayout({ children }) {
 *   const sylphx = createServerClient(process.env.SYLPHX_SECRET_URL!)
 *   const flags = await getFeatureFlags({
 *     secretKey: sylphx.secretKey!,
 *     platformUrl: sylphx.baseUrl.replace(/\/v[0-9]+$/, ''),
 *   })
 *   return <FeatureFlagsProvider initialFlags={flags}>{children}</FeatureFlagsProvider>
 * }
 * ```
 */
declare function getFeatureFlags(options: AuthenticatedFetchOptions): Promise<FeatureFlagDefinition[]>;
/** App metadata returned by /api/sdk/app */
interface AppMetadata {
    id: string;
    name: string;
    slug: string;
}
/**
 * Get app metadata (server-side)
 *
 * @internal Used by getAppConfig() - rarely called directly
 */
declare function getAppMetadata(options: AuthenticatedFetchOptions): Promise<AppMetadata>;

/**
 * Options for getAppConfig()
 */
interface GetAppConfigOptions {
    /** Secret key for authenticated endpoints (plans, flags, consent types) */
    secretKey: string;
    /** App ID for public endpoints (OAuth providers) - identifies your app */
    appId: string;
    /** Platform URL (defaults to https://sylphx.com) */
    platformUrl?: string;
    /** Optional cache TTL in seconds. Default: 60 */
    revalidate?: number;
}
/**
 * Get complete app configuration for the SDK (server-side)
 *
 * This is the **recommended** way to initialize the Sylphx SDK. It fetches all
 * configuration data in a single call from a Server Component, eliminating the
 * need for client-side config fetching and the associated loading states.
 *
 * Returns:
 * - plans: Subscription plans for billing
 * - consentTypes: GDPR/CCPA consent configuration
 * - oauthProviders: Enabled OAuth providers for auth
 * - featureFlags: Feature flag definitions for client-side evaluation
 * - app: App metadata (id, name, slug)
 * - fetchedAt: ISO timestamp for cache debugging
 *
 * @example
 * ```tsx
 * // app/layout.tsx (Server Component)
 * import { getAppConfig } from '@sylphx/sdk/server'
 *
 * export default async function RootLayout({ children }) {
 *   const sylphx = createServerClient(process.env.SYLPHX_SECRET_URL!)
 *   const config = await getAppConfig({
 *     secretKey: sylphx.secretKey!,
 *     appId: process.env.NEXT_PUBLIC_SYLPHX_APP_ID!,
 *     platformUrl: sylphx.baseUrl.replace(/\/v[0-9]+$/, ''),
 *   })
 *
 *   return (
 *     <html>
 *       <body>
 *         <SylphxProvider
 *           config={config}
 *           appId={process.env.NEXT_PUBLIC_SYLPHX_APP_ID!}
 *         >
 *           {children}
 *         </SylphxProvider>
 *       </body>
 *     </html>
 *   )
 * }
 * ```
 */
declare function getAppConfig(options: GetAppConfigOptions): Promise<AppConfig>;
/** Referral leaderboard entry */
interface ReferralLeaderboardEntry {
    rank: number;
    userId: string;
    /** Masked username for privacy */
    name: string;
    /** Number of successful referrals */
    referrals: number;
    isCurrentUser: boolean;
}
/** Referral leaderboard result */
interface ReferralLeaderboardResult {
    entries: ReferralLeaderboardEntry[];
    total: number;
    period: 'all' | 'month' | 'week';
}
/**
 * Get referral leaderboard for an app (server-side)
 *
 * @example
 * ```tsx
 * import { getReferralLeaderboard } from '@sylphx/sdk/server'
 *
 * export default async function ReferralsPage() {
 *   const leaderboard = await getReferralLeaderboard({
 *     secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey!,
 *     limit: 10,
 *     period: 'month',
 *   })
 *   return <ReferralLeaderboard initialData={leaderboard} />
 * }
 * ```
 */
declare function getReferralLeaderboard(options: AuthenticatedFetchOptions & {
    limit?: number;
    period?: 'all' | 'month' | 'week';
}): Promise<ReferralLeaderboardResult>;
/** Engagement leaderboard entry */
interface EngagementLeaderboardEntry {
    rank: number;
    userId: string;
    name: string;
    score: number;
    isCurrentUser: boolean;
}
/** Engagement leaderboard result */
interface EngagementLeaderboardResult {
    leaderboardId: string;
    entries: EngagementLeaderboardEntry[];
    period: string;
    resetTime: string | null;
    userEntry: EngagementLeaderboardEntry | null;
}
/**
 * Get engagement leaderboard for an app (server-side)
 *
 * @example
 * ```tsx
 * import { getEngagementLeaderboard } from '@sylphx/sdk/server'
 *
 * export default async function LeaderboardPage() {
 *   const leaderboard = await getEngagementLeaderboard({
 *     secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey!,
 *     leaderboardId: 'high-scores',
 *   })
 *   return <Leaderboard initialData={leaderboard} />
 * }
 * ```
 */
declare function getEngagementLeaderboard(options: AuthenticatedFetchOptions & {
    leaderboardId: string;
    limit?: number;
}): Promise<EngagementLeaderboardResult>;
/** Database connection info returned by Platform */
interface DatabaseConnectionInfo {
    connectionString: string;
    databaseName: string;
    roleName: string;
    status: 'provisioning' | 'ready' | 'suspended' | 'failed' | 'deleted';
}
/** Database status info */
interface DatabaseStatusInfo {
    status: 'provisioning' | 'ready' | 'suspended' | 'failed' | 'deleted' | 'not_provisioned';
    region: string | null;
    pgVersion: number | null;
    databaseName: string | null;
}
/**
 * Get database connection string from Platform (server-side)
 *
 * Use this when your app's database is provisioned by the Sylphx Platform.
 * The connection string is securely stored on Platform and retrieved at startup.
 *
 * **Note:** This requires NEON_API_KEY and PLATFORM_ENCRYPTION_KEY to be
 * configured on the Platform, and your app's database to be provisioned.
 *
 * @example
 * ```typescript
 * import { getDatabaseConnection } from '@sylphx/sdk/server'
 *
 * // In your database initialization
 * const dbInfo = await getDatabaseConnection({
 *   secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey!,
 * })
 *
 * if (dbInfo) {
 *   const pool = new Pool({ connectionString: dbInfo.connectionString })
 * }
 * ```
 */
declare function getDatabaseConnection(options: AuthenticatedFetchOptions): Promise<DatabaseConnectionInfo | null>;
/**
 * Get database status from Platform (server-side)
 *
 * Use this to check if your app's database is provisioned and ready.
 *
 * @example
 * ```typescript
 * import { getDatabaseStatus } from '@sylphx/sdk/server'
 *
 * const status = await getDatabaseStatus({
 *   secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey!,
 * })
 *
 * if (status?.status === 'ready') {
 *   // Database is ready to use
 * }
 * ```
 */
declare function getDatabaseStatus(options: AuthenticatedFetchOptions): Promise<DatabaseStatusInfo>;

export { type AIClient, type AIClientOptions, type AppConfig, type AppMetadata, type ChannelHelper, type ChatCompletionChunk, type ChatCompletionOptions, type ChatCompletionResponse, type ChatCompletionStreamOptions, type ChatMessage, type ConsentType, type DatabaseConnectionInfo, type DatabaseStatusInfo, type EmbeddingOptions, type EmbeddingResponse, type EngagementLeaderboardEntry, type EngagementLeaderboardResult, type EnvironmentType, type FeatureFlagDefinition, type FunctionDeployOptions, type FunctionDeployResult, type FunctionInvokeOptions, type FunctionListOptions, type FunctionLogEntry, type FunctionLogsOptions, type FunctionRecord, type FunctionRuntime, type FunctionStatus, FunctionsClient, type GetAppConfigOptions, InvalidConnectionUrlError, type KeyType, type KeyValidationResult, type KvClient, type KvClientOptions, type KvRateLimitResult, type KvSetOptions, type KvZMember, type ModelInfo, type ModelsResponse, type OAuthProvider, type OAuthProviderInfo, type Plan, type ReferralLeaderboardEntry, type ReferralLeaderboardResult, type RestClient, type RestClientConfig as ServerClientConfig, type ServerConfig, type StreamHistoryOptions, type StreamMessage, type StreamsClient, type StreamsClientOptions, type SylphxClientInput, type SylphxConfig, type WebhookPayload, type WebhookVerifyOptions, type WebhookVerifyResult, createAI, createAuthenticatedServerClient, createClient, createKv, createServerClient, createServerRestClient, createStreams, createWebhookHandler, decodeUserId, detectEnvironment, detectKeyType, encodeUserId, getAI, getAppConfig, getAppMetadata, getConsentTypes, getCookieNamespace, getDatabaseConnection, getDatabaseStatus, getEngagementLeaderboard, getFeatureFlags, getJwks, getKv, getOAuthProviders, getOAuthProvidersWithInfo, getPlans, getReferralLeaderboard, getStreams, isAppId, isDevelopmentKey, isDevelopmentRuntime, isProductionKey, isSecretKey, resetJwksCache, validateAndSanitizeAppId, validateAndSanitizeKey, validateAndSanitizeSecretKey, validateAppId, validateKey, validateSecretKey, verifyAccessToken, verifyWebhook };
