rwsdk
Version:
Build fast, server-driven webapps on Cloudflare with SSR, RSC, and realtime
39 lines (38 loc) • 1.51 kB
JavaScript
import { DEFAULT_SYNCED_STATE_PATH } from "../constants.mjs";
import { manager } from "./state/clientManager.js";
import { createSyncedStateClient } from "./state/clientFactory.js";
import { getBackoffMs } from "./reconnect/backoff.js";
import { PENDING_REQUEST_TIMEOUT_MS } from "./connection/timer.js";
export const onStatusChange = manager.onStatusChange;
/**
* Returns a cached client for the provided endpoint, creating it when necessary.
* The returned client is a thin wrapper around a raw WebSocket that speaks the
* JSON state-sync protocol.
*/
export const getSyncedStateClient = (endpoint = DEFAULT_SYNCED_STATE_PATH, webSocketFactory = (url) => new WebSocket(url)) => {
const normalized = manager.normalizeEndpoint(endpoint);
const existingClient = manager.getClient(normalized);
if (existingClient)
return existingClient;
const client = createSyncedStateClient(normalized, webSocketFactory);
manager.setClient(normalized, client);
return client;
};
/**
* Resets all state for an endpoint. Used by tests to isolate test cases and
* by cleanup paths.
*/
export const setSyncedStateClientForTesting = (client, endpoint = DEFAULT_SYNCED_STATE_PATH) => {
const normalized = manager.normalizeEndpoint(endpoint);
if (client) {
manager.setClient(normalized, client);
}
else {
manager.clearForTesting(normalized);
}
};
// Exported for testing only
export const __testing = {
getBackoffMs,
PENDING_REQUEST_TIMEOUT_MS,
};