import { b as ClientInfo, c as ConfigKey, d as ConfigParams, A as AnyMethodShape, V as ValueType, e as ConfigType, O as OAuthProvider, W as WebsocketClientProvider, f as ClientChannel } from './types-B_R3eHmq.js';
import { ObjectId } from 'mongodb';
import React, { ReactNode } from 'react';
import * as react_jsx_runtime from 'react/jsx-runtime';
import { QueryClient, DehydratedState } from '@tanstack/react-query';
import 'http';
import 'express';

interface ClientConfig {
    baseUrl: string;
    getAuthToken: () => string | undefined;
    setAuthToken: (token: string | null) => void;
    getClientInfo: () => ClientInfo;
    /**
     * Opens a URL for OAuth redirects. React Native must use
     * `(url) => Linking.openURL(url)` — WebView is not supported.
     * Defaults to `window.location.href` when not provided.
     */
    openUrl?: (url: string) => void;
}
/**
 * Configure the Modelence client for non-browser environments like React Native.
 *
 * When configured, the client uses the provided functions for auth-token
 * storage, client-info collection, and URL resolution instead of the
 * default browser APIs (localStorage, window.screen, relative URLs).
 *
 * @example
 * ```ts
 * import { configureClient } from 'modelence/client';
 * import { Linking } from 'react-native';
 *
 * let authToken: string | undefined;
 *
 * configureClient({
 *   baseUrl: 'https://myapp.com',
 *   getAuthToken: () => authToken,
 *   setAuthToken: (token) => { authToken = token ?? undefined; },
 *   getClientInfo: () => ({
 *     screenWidth: Dimensions.get('screen').width,
 *     screenHeight: Dimensions.get('screen').height,
 *     windowWidth: Dimensions.get('window').width,
 *     windowHeight: Dimensions.get('window').height,
 *     pixelRatio: PixelRatio.get(),
 *     orientation: null,
 *   }),
 *   openUrl: (url) => Linking.openURL(url),
 * });
 * ```
 */
declare function configureClient(userConfig: ClientConfig): void;

/**
 * @sidebarTitle getConfig (client)
 *
 * @param key
 * @returns
 */
declare function getConfig(key: ConfigKey): string | number | boolean | undefined;

declare class MethodError extends Error {
    status: number;
    /**
     * Machine-readable error code set by the server (when available), so callers
     * can branch on the error kind without matching the human-readable message.
     * For example, a login attempt with an unverified email yields
     * `code === 'EMAIL_NOT_VERIFIED'`.
     */
    code?: string;
    constructor(message: string, status: number, code?: string);
}
type MethodArgs = Record<string, unknown>;
type CallMethodOptions = {
    errorHandler?: (error: Error, methodName: string) => void;
};
/**
 * Calls a server-side method (query or mutation) defined on a Modelence module.
 *
 * Both `args` and `options` are optional. Use the type parameter `T` to type the return value.
 *
 * @example
 * ```typescript
 * import { callMethod } from 'modelence/client';
 *
 * // No arguments
 * const todos = await callMethod<Todo[]>('todo.getAll');
 *
 * // With arguments
 * const todo = await callMethod<Todo>('todo.getOne', { id: '123' });
 *
 * // With a custom error handler
 * const created = await callMethod<Todo>(
 *   'todo.create',
 *   { title: 'Buy groceries' },
 *   { errorHandler: (error, methodName) => console.error(methodName, error) }
 * );
 * ```
 *
 * @param methodName - Fully qualified method name, e.g. `'todo.getAll'`.
 * @param args - Arguments passed to the server-side method. Defaults to `{}`.
 * @param options - Call-site options such as a custom {@link CallMethodOptions.errorHandler}. Defaults to `{}`.
 * @returns A promise that resolves to the method's return value.
 */
declare function callMethod<T = unknown>(methodName: string, args?: MethodArgs, options?: CallMethodOptions): Promise<T>;

/**
 * Recursively maps ObjectId → string to match the sanitized runtime values
 * sent over the wire. Dates are preserved (revived via typeMap on the client).
 */
type Sanitized<T> = T extends ObjectId ? string : T extends Date ? Date : T extends (infer U)[] ? Sanitized<U>[] : T extends object ? {
    [K in keyof T]: Sanitized<T[K]>;
} : T;
type ExtractArgs<M> = M extends (args: infer A, ...rest: any[]) => any ? A : M extends {
    handler: (args: infer A, ...rest: any[]) => any;
} ? A : MethodArgs;
type ExtractResult<M> = M extends (...args: any[]) => Promise<infer R> ? Sanitized<R> : M extends {
    handler: (...args: any[]) => Promise<infer R>;
} ? Sanitized<R> : unknown;
type PublicKeyOf<TSchema extends Record<string, ConfigParams>> = {
    [K in keyof TSchema as TSchema[K] extends ConfigParams<ConfigType, true> ? string & K : never]: ValueType<TSchema[K]['type']>;
};
type AnyModule = {
    name: string;
    configSchema: Record<string, ConfigParams>;
    queries: Record<string, AnyMethodShape>;
    mutations: Record<string, AnyMethodShape>;
};
/**
 * Creates a typed client accessor for a module's public configs, queries, and mutations.
 *
 * Use `import type` to reference the module so no server code is bundled on the client.
 * Arg and return types for queries and mutations are inferred automatically from the
 * server-side handler signatures.
 *
 * @param moduleName - The module's name as passed to `new Module(name, ...)`.
 *
 * @example
 * ```ts
 * // src/client/payments.ts
 * import type paymentsModule from '../server/payments';
 * import { createClientModule } from 'modelence/client';
 *
 * export const payments = createClientModule<typeof paymentsModule>('payments');
 * ```
 *
 * ```ts
 * // src/components/Checkout.tsx
 * import { useQuery, useMutation } from '@tanstack/react-query';
 * import { payments } from '../client/payments';
 *
 * // Typed config — public keys only, private and secret keys excluded:
 * const currency = payments.getConfig('currency'); // string | undefined
 *
 * // Typed query — pass directly to useQuery:
 * const { data: products } = useQuery(payments.query('getProducts', { page: 1 }));
 *
 * // Typed mutation — pass directly to useMutation:
 * const { mutate: charge } = useMutation(payments.mutation('charge'));
 * charge({ amount: 100 }); // args typed from handler signature
 * ```
 */
declare function createClientModule<TModule extends AnyModule>(moduleName: string): {
    getConfig<K extends keyof PublicKeyOf<TModule["configSchema"]> & string>(key: K): PublicKeyOf<TModule["configSchema"]>[K] | undefined;
    query<K extends keyof TModule["queries"] & string>(name: K, ...rest: {} extends ExtractArgs<TModule["queries"][K]> ? [args?: ExtractArgs<TModule["queries"][K]>] : [args: ExtractArgs<TModule["queries"][K]>]): {
        queryKey: readonly [string, K, ExtractArgs<TModule["queries"][K]>];
        queryFn: () => Promise<ExtractResult<TModule["queries"][K]>>;
    };
    mutation<K extends keyof TModule["mutations"] & string>(name: K): {
        mutationFn: (args: ExtractArgs<TModule["mutations"][K]>) => Promise<ExtractResult<TModule["mutations"][K]>>;
    };
    /**
     * Returns options for `useInfiniteQuery`. The `getArgs` callback receives the
     * current `pageParam` and returns the args to pass to the query handler.
     * Spread the result into `useInfiniteQuery` alongside `getNextPageParam`.
     *
     * Annotate the `pageParam` type in the callback so TypeScript can infer the
     * page param type — no manual generic needed on `useInfiniteQuery`.
     */
    infiniteQuery<K extends keyof TModule["queries"] & string, TPageParam = unknown>(name: K, getArgs: (pageParam: TPageParam | undefined) => ExtractArgs<TModule["queries"][K]>): {
        queryKey: readonly [string, K, "infinite", ExtractArgs<TModule["queries"][K]>];
        initialPageParam: TPageParam | undefined;
        queryFn: ({ pageParam, }: {
            pageParam: TPageParam | undefined;
        }) => Promise<ExtractResult<TModule["queries"][K]>>;
    };
};

declare const systemConfig: {
    getConfig<K extends "env.type" | "site.url">(key: K): {
        'env.type': string;
        'site.url': string;
    }[K] | undefined;
    query<K extends string>(name: K, args?: any): {
        queryKey: readonly [string, K, any];
        queryFn: () => Promise<unknown>;
    };
    mutation<K extends string>(name: K): {
        mutationFn: (args: any) => Promise<unknown>;
    };
    infiniteQuery<K extends string, TPageParam = unknown>(name: K, getArgs: (pageParam: TPageParam | undefined) => any): {
        queryKey: readonly [string, K, "infinite", any];
        initialPageParam: TPageParam | undefined;
        queryFn: ({ pageParam, }: {
            pageParam: TPageParam | undefined;
        }) => Promise<unknown>;
    };
};

type ErrorHandler = (error: Error, methodName: string) => void;

type SsrRouter = (props: {
    children: React.ReactNode;
    location?: string;
}) => React.ReactElement;
interface RenderAppOptions {
    loadingElement: React.ReactNode;
    routesElement: React.ReactNode;
    favicon?: string;
    errorHandler?: ErrorHandler;
    router?: SsrRouter;
}
declare function renderApp(options: RenderAppOptions): void;

interface ModelenceQueryProviderProps {
    children: ReactNode;
    client?: QueryClient;
    dehydratedState?: DehydratedState;
}
declare function ModelenceQueryProvider({ children, client, dehydratedState, }: ModelenceQueryProviderProps): react_jsx_runtime.JSX.Element;

type Args = Record<string, unknown>;
/**
 * Connects a `QueryClient` to Modelence's live-query layer. Auto-called by
 * `<ModelenceQueryProvider>`; only call manually if you mount your own
 * `<QueryClientProvider>`.
 *
 * Note: WebSocket setup is deferred until the first `modelenceLiveQuery`
 * call, so apps that only use `modelenceQuery`/`modelenceMutation` never
 * open a socket.
 */
declare function connectModelenceQueryClient(queryClient: QueryClient): void;
declare function disconnectModelenceQueryClient(): void;
/** @deprecated Use `connectModelenceQueryClient(queryClient)` instead. */
declare class ModelenceQueryClient {
    connect(queryClient: QueryClient): void;
}
/**
 * @example
 * ```tsx
 * const { data } = useQuery(modelenceQuery('todo.getAll'));
 * ```
 */
declare function modelenceQuery<T = unknown>(methodName: string, args?: Args): {
    queryKey: (string | Args)[];
    queryFn: () => Promise<T>;
};
/**
 * Live query — data updates in real time as the underlying collection changes.
 * Requires a `QueryClient` connected via `<ModelenceQueryProvider>` or
 * `connectModelenceQueryClient(...)`.
 */
declare function modelenceLiveQuery<T = unknown>(methodName: string, args?: Args): {
    queryKey: readonly ["live", string, Args];
    queryFn: () => Promise<T>;
    staleTime: number;
    refetchOnWindowFocus: boolean;
    refetchOnMount: boolean;
    refetchOnReconnect: boolean;
    gcTime: number;
};
declare function modelenceMutation<T = unknown>(methodName: string, defaultArgs?: Args): {
    mutationFn: (variables?: Args) => Promise<T>;
};
type ModelenceQueryKey<T extends string, U extends Args = Args> = readonly [T, U];
/** Builds a query key matching `modelenceQuery(...)` for cache operations. */
declare function createQueryKey<T extends string, U extends Args = Args>(methodName: T, args?: U): ModelenceQueryKey<T, U>;

type User = {
    id: string;
    handle: string;
    roles: string[];
    hasRole: (role: string) => boolean;
    requireRole: (role: string) => void;
    firstName?: string;
    lastName?: string;
    avatarUrl?: string;
};
/**
 * `useSession` is a hook that returns the current user, and in the future will also return other details about the current session.
 *
 * @example
 * ```ts
 * import { useSession } from 'modelence/client';
 *
 * function MyComponent() {
 *   const { user } = useSession();
 *   return <div>{user?.handle}</div>;
 * }
 * ```
 */
declare function useSession(): {
    user: User | null;
};

type UserInfo = {
    id: string;
    handle: string;
    roles: string[];
    hasRole: (role: string) => boolean;
    requireRole: (role: string) => void;
    firstName?: string;
    lastName?: string;
    avatarUrl?: string;
};
/**
 * Sign up a new user with an email and password.
 *
 * @example
 * ```ts
 * await signupWithPassword({ email: 'test@example.com', password: '12345678' });
 * await signupWithPassword({ email: 'test@example.com', password: '12345678', handle: 'myhandle', firstName: 'John' });
 * ```
 * @param options.email - The email of the user.
 * @param options.password - The password of the user.
 * @param options.handle - Optional custom handle. If omitted, one is derived from the email.
 * @param options.firstName - Optional first name.
 * @param options.lastName - Optional last name.
 * @param options.avatarUrl - Optional avatar URL.
 */
declare function signupWithPassword(options: {
    email: string;
    password: string;
    handle?: string;
    firstName?: string;
    lastName?: string;
    avatarUrl?: string;
}): Promise<void>;
/**
 * Login a user with an email and password.
 *
 * @example
 * ```ts
 * await loginWithPassword({ email: 'test@example.com', password: '12345678' });
 * ```
 * @param options.email - The email of the user.
 * @param options.password - The password of the user.
 */
declare function loginWithPassword(options: {
    email: string;
    password: string;
}): Promise<{
    id: string;
    handle: string;
    roles: string[];
    hasRole: (role: string) => boolean;
    requireRole: (role: string) => void;
    firstName?: string;
    lastName?: string;
    avatarUrl?: string;
} | null>;
/**
 * Update the current user's profile.
 *
 * @example
 * ```ts
 * await updateProfile({ firstName: 'Atul', lastName: 'Yadav', avatarUrl: 'https://example.com/avatar.jpg', handle: 'atulyadav' });
 * ```
 * @param options.firstName - The first name of the user.
 * @param options.lastName - The last name of the user.
 * @param options.avatarUrl - The avatar URL of the user.
 * @param options.handle - The handle of the user.
 */
declare function updateProfile(options: {
    firstName?: string;
    lastName?: string;
    avatarUrl?: string;
    handle?: string;
}): Promise<{
    id: string;
    handle: string;
    roles: string[];
    hasRole: (role: string) => boolean;
    requireRole: (role: string) => void;
    firstName?: string;
    lastName?: string;
    avatarUrl?: string;
} | null>;
/**
 * Verify user's email with a verification token.
 *
 * @example
 * ```ts
 * await verifyEmail({ token: 'verification-token' });
 * ```
 * @param options.token - The email verification token.
 */
declare function verifyEmail(options: {
    token: string;
}): Promise<void>;
/**
 * Resend the verification email for a given email address.
 * The email is only sent if the address is registered and not yet verified.
 * A generic response is always returned to avoid leaking account information.
 *
 * @example
 * ```ts
 * await resendEmailVerification({ email: 'user@example.com' });
 * ```
 * @param options.email - The email address to resend verification to.
 */
declare function resendEmailVerification(options: {
    email: string;
}): Promise<void>;
/**
 * Logout the current user.
 *
 */
declare function logout(): Promise<void>;
/**
 * Send reset password token.
 * @param options.email - The email of the user.
 */
declare function sendResetPasswordToken(options: {
    email: string;
}): Promise<void>;
/**
 * Reset password.
 * @param options.token - The password reset token.
 * @param options.password - The new password.
 */
declare function resetPassword(options: {
    token: string;
    password: string;
}): Promise<void>;
/**
 * Link an OAuth provider to the currently signed-in user's account.
 * Redirects the browser to the OAuth provider's authorization page.
 * The provider will redirect back and the account will be linked.
 *
 * @example
 * ```ts
 * linkOAuthProvider({ provider: 'google' });
 * ```
 * @param options.provider - The OAuth provider to link ('google' or 'github').
 */
declare function linkOAuthProvider(options: {
    provider: OAuthProvider;
}): Promise<void>;
/**
 * Unlink an OAuth provider from the currently signed-in user's account.
 *
 * @example
 * ```ts
 * await unlinkOAuthProvider({ provider: 'github' });
 * ```
 * @param options.provider - The OAuth provider to unlink ('google' or 'github').
 */
declare function unlinkOAuthProvider(options: {
    provider: OAuthProvider;
}): Promise<void>;

declare function subscribeLiveQuery<T = unknown>(method: string, args: Record<string, unknown>, onData: (data: T) => void, onError?: (error: string) => void): () => void;

declare function setWebsocketClientProvider(provider: WebsocketClientProvider | null): void;
declare function getWebsocketClientProvider(): WebsocketClientProvider | null;
declare function startWebsockets(props?: {
    provider?: WebsocketClientProvider;
    channels?: ClientChannel[];
}): void;

declare function getLocalStorageSession(): any;

declare const AppProvider: any;

export { AppProvider, type CallMethodOptions, ClientChannel, type ClientConfig, type MethodArgs, MethodError, ModelenceQueryClient, type ModelenceQueryKey, ModelenceQueryProvider, type UserInfo, ValueType, callMethod, configureClient, connectModelenceQueryClient, createClientModule, createQueryKey, disconnectModelenceQueryClient, getConfig, getLocalStorageSession, getWebsocketClientProvider, linkOAuthProvider, loginWithPassword, logout, modelenceLiveQuery, modelenceMutation, modelenceQuery, renderApp, resendEmailVerification, resetPassword, sendResetPasswordToken, setWebsocketClientProvider, signupWithPassword, startWebsockets, subscribeLiveQuery, systemConfig, unlinkOAuthProvider, updateProfile, useSession, verifyEmail };
