rwsdk
Version:
Build fast, server-driven webapps on Cloudflare with SSR, RSC, and realtime
59 lines (58 loc) • 2.6 kB
TypeScript
export type SyncedStateStatus = "connected" | "disconnected" | "reconnecting";
export type StatusChangeCallback = (status: SyncedStateStatus) => void;
export type SyncedStateClient = {
getState(key: string): Promise<unknown>;
setState(value: unknown, key: string): Promise<void>;
subscribe(key: string, handler: (value: unknown) => void): Promise<void>;
unsubscribe(key: string, handler: (value: unknown) => void): Promise<void>;
};
type Subscription = {
key: string;
handler: (value: unknown) => void;
client: SyncedStateClient;
};
/**
* Registers a callback that fires when the connection status changes for an endpoint.
* Returns an unsubscribe function.
*/
export declare const onStatusChange: (endpoint: string, callback: StatusChangeCallback) => (() => void);
declare function getBackoffMs(attempt: number): number;
declare function reconnect(endpoint: string, deadClient: SyncedStateClient): void;
/**
* Returns a cached client for the provided endpoint, creating it when necessary.
* The returned client is a proxy that loads `capnweb` lazily on first method
* call — consumers that never hit `use-synced-state` pay no import cost and
* don't need `capnweb` installed.
* @param endpoint Endpoint to connect to.
* @returns RPC client instance.
*/
export declare const getSyncedStateClient: (endpoint?: string) => SyncedStateClient;
/**
* Initializes and caches an RPC client instance for the sync state endpoint.
* The client is wrapped to track subscriptions for cleanup on page reload.
* @param options Optional endpoint override.
* @returns Cached client instance or `null` when running without `window`.
*/
export declare const initSyncedStateClient: (options?: {
endpoint?: string;
}) => SyncedStateClient | null;
/**
* Injects a client instance for tests and updates the cached endpoint.
* Also clears the subscription registry for test isolation.
* @param client Stub client instance or `null` to clear the cache.
* @param endpoint Endpoint associated with the injected client.
*/
export declare const setSyncedStateClientForTesting: (client: SyncedStateClient | null, endpoint?: string) => void;
export declare const __testing: {
activeSubscriptions: Set<Subscription>;
clientCache: Map<string, SyncedStateClient>;
backoffState: Map<string, {
attempt: number;
timer: ReturnType<typeof setTimeout> | null;
}>;
statusListeners: Map<string, StatusChangeCallback[]>;
reconnect: typeof reconnect;
getBackoffMs: typeof getBackoffMs;
warmUp(endpoint?: string): Promise<void>;
};
export {};