reflectdb 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1260 -0
  3. package/dist/cjs/client/index.cjs +1252 -0
  4. package/dist/cjs/client/index.d.cts +629 -0
  5. package/dist/cjs/client/storage/indexeddb.cjs +253 -0
  6. package/dist/cjs/client/storage/indexeddb.d.cts +85 -0
  7. package/dist/cjs/core/index.cjs +202 -0
  8. package/dist/cjs/core/index.d.cts +473 -0
  9. package/dist/cjs/react/index.cjs +1512 -0
  10. package/dist/cjs/react/index.d.cts +748 -0
  11. package/dist/cjs/server/drizzle.cjs +413 -0
  12. package/dist/cjs/server/drizzle.d.cts +233 -0
  13. package/dist/cjs/server/index.cjs +4486 -0
  14. package/dist/cjs/server/index.d.cts +1988 -0
  15. package/dist/cjs/svelte/index.cjs +1414 -0
  16. package/dist/cjs/svelte/index.d.cts +645 -0
  17. package/dist/cjs/transport/bun-ws.cjs +244 -0
  18. package/dist/cjs/transport/bun-ws.d.cts +215 -0
  19. package/dist/cjs/transport/polling.cjs +285 -0
  20. package/dist/cjs/transport/polling.d.cts +210 -0
  21. package/dist/cjs/transport/sse.cjs +312 -0
  22. package/dist/cjs/transport/sse.d.cts +205 -0
  23. package/dist/cjs/transport/ws.cjs +330 -0
  24. package/dist/cjs/transport/ws.d.cts +236 -0
  25. package/dist/cjs/vanilla/index.cjs +1430 -0
  26. package/dist/cjs/vanilla/index.d.cts +657 -0
  27. package/dist/client/index.d.ts +629 -0
  28. package/dist/client/index.js +106 -0
  29. package/dist/client/storage/indexeddb.d.ts +85 -0
  30. package/dist/client/storage/indexeddb.js +213 -0
  31. package/dist/core/index.d.ts +473 -0
  32. package/dist/core/index.js +56 -0
  33. package/dist/react/index.d.ts +748 -0
  34. package/dist/react/index.js +366 -0
  35. package/dist/server/drizzle.d.ts +233 -0
  36. package/dist/server/drizzle.js +9 -0
  37. package/dist/server/index.d.ts +1988 -0
  38. package/dist/server/index.js +3959 -0
  39. package/dist/shared/esm-3tkwvysa.js +54 -0
  40. package/dist/shared/esm-b7xs9cde.js +4 -0
  41. package/dist/shared/esm-rw7jjtrv.js +58 -0
  42. package/dist/shared/esm-wkwx6bd9.js +25 -0
  43. package/dist/shared/esm-ytrd3hbq.js +1007 -0
  44. package/dist/shared/esm-z1xse19c.js +369 -0
  45. package/dist/svelte/index.d.ts +645 -0
  46. package/dist/svelte/index.js +262 -0
  47. package/dist/transport/bun-ws.d.ts +215 -0
  48. package/dist/transport/bun-ws.js +140 -0
  49. package/dist/transport/polling.d.ts +210 -0
  50. package/dist/transport/polling.js +181 -0
  51. package/dist/transport/sse.d.ts +205 -0
  52. package/dist/transport/sse.js +208 -0
  53. package/dist/transport/ws.d.ts +236 -0
  54. package/dist/transport/ws.js +226 -0
  55. package/dist/vanilla/index.d.ts +657 -0
  56. package/dist/vanilla/index.js +278 -0
  57. package/package.json +253 -0
@@ -0,0 +1,330 @@
1
+ var import_node_module = require("node:module");
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ function __accessProp(key) {
7
+ return this[key];
8
+ }
9
+ var __toCommonJS = (from) => {
10
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
11
+ if (entry)
12
+ return entry;
13
+ entry = __defProp({}, "__esModule", { value: true });
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (var key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(entry, key))
17
+ __defProp(entry, key, {
18
+ get: __accessProp.bind(from, key),
19
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
20
+ });
21
+ }
22
+ __moduleCache.set(from, entry);
23
+ return entry;
24
+ };
25
+ var __moduleCache;
26
+ var __returnValue = (v) => v;
27
+ function __exportSetter(name, newValue) {
28
+ this[name] = __returnValue.bind(null, newValue);
29
+ }
30
+ var __export = (target, all) => {
31
+ for (var name in all)
32
+ __defProp(target, name, {
33
+ get: all[name],
34
+ enumerable: true,
35
+ configurable: true,
36
+ set: __exportSetter.bind(all, name)
37
+ });
38
+ };
39
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
40
+
41
+ // src/core/types.ts
42
+ var exports_types = {};
43
+ __export(exports_types, {
44
+ reasonFromError: () => reasonFromError,
45
+ isErrorReason: () => isErrorReason,
46
+ TransportSendError: () => TransportSendError,
47
+ TOMBSTONE_RETENTION_MS: () => TOMBSTONE_RETENTION_MS,
48
+ SUPPORTED_PROTOCOL_VERSIONS: () => SUPPORTED_PROTOCOL_VERSIONS,
49
+ SERVER_TOMBSTONE_RETENTION_MS: () => SERVER_TOMBSTONE_RETENTION_MS,
50
+ PROTOCOL_VERSION: () => PROTOCOL_VERSION,
51
+ MutationError: () => MutationError,
52
+ MAX_CLOCK_DRIFT_MS: () => MAX_CLOCK_DRIFT_MS,
53
+ MAX_BATCH_SIZE: () => MAX_BATCH_SIZE
54
+ });
55
+ function isErrorReason(value) {
56
+ return typeof value === "string" && VALID_ERROR_REASONS.has(value);
57
+ }
58
+ function reasonFromError(err) {
59
+ if (err instanceof MutationError && isErrorReason(err.reason)) {
60
+ return err.reason;
61
+ }
62
+ return "server_error";
63
+ }
64
+ var TransportSendError, PROTOCOL_VERSION = 1, SUPPORTED_PROTOCOL_VERSIONS, MAX_CLOCK_DRIFT_MS, MAX_BATCH_SIZE = 100, TOMBSTONE_RETENTION_MS, SERVER_TOMBSTONE_RETENTION_MS, MutationError, VALID_ERROR_REASONS;
65
+ var init_types = __esm(() => {
66
+ TransportSendError = class TransportSendError extends Error {
67
+ clientId;
68
+ cause;
69
+ constructor(clientId, message, cause) {
70
+ super(message);
71
+ this.clientId = clientId;
72
+ this.cause = cause;
73
+ this.name = "TransportSendError";
74
+ }
75
+ };
76
+ SUPPORTED_PROTOCOL_VERSIONS = [1];
77
+ MAX_CLOCK_DRIFT_MS = 5 * 60 * 1000;
78
+ TOMBSTONE_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
79
+ SERVER_TOMBSTONE_RETENTION_MS = 90 * 24 * 60 * 60 * 1000;
80
+ MutationError = class MutationError extends Error {
81
+ reason;
82
+ constructor(reason, message) {
83
+ super(message ?? reason);
84
+ this.reason = reason;
85
+ }
86
+ };
87
+ VALID_ERROR_REASONS = new Set([
88
+ "outside_shape",
89
+ "readonly_query",
90
+ "rate_limited",
91
+ "buffer_full",
92
+ "server_conflict",
93
+ "custom_conflict",
94
+ "merge_stale",
95
+ "clock_drift",
96
+ "replay",
97
+ "batch_too_large",
98
+ "schema_outdated",
99
+ "auth_revoked",
100
+ "compacted",
101
+ "mutation_rejected",
102
+ "server_error",
103
+ "unknown_query"
104
+ ]);
105
+ });
106
+
107
+ // src/transport/ws.ts
108
+ init_types();
109
+ var exports_ws = {};
110
+ __export(exports_ws, {
111
+ isOriginAllowed: () => isOriginAllowed,
112
+ createWsServerTransport: () => createWsServerTransport,
113
+ createWsClientTransport: () => createWsClientTransport
114
+ });
115
+ module.exports = __toCommonJS(exports_ws);
116
+ function trySend(clientId, ws, data, maxBufferedBytes) {
117
+ const sock = ws;
118
+ const rs = sock.readyState;
119
+ if (rs !== undefined && rs !== 1) {
120
+ throw new TransportSendError(clientId, `ws not open (readyState=${rs})`);
121
+ }
122
+ if (maxBufferedBytes > 0 && (sock.bufferedAmount ?? 0) > maxBufferedBytes) {
123
+ throw new TransportSendError(clientId, `ws outbound buffer over limit (${sock.bufferedAmount} > ${maxBufferedBytes})`);
124
+ }
125
+ try {
126
+ ws.send(data);
127
+ } catch (err) {
128
+ throw new TransportSendError(clientId, `ws send failed: ${err instanceof Error ? err.message : String(err)}`, err);
129
+ }
130
+ }
131
+ function isOriginAllowed(req, allowed) {
132
+ const origin = req.headers.get("origin");
133
+ if (typeof allowed === "function")
134
+ return allowed(origin);
135
+ if (allowed.includes("*"))
136
+ return true;
137
+ if (!origin)
138
+ return false;
139
+ return allowed.includes(origin);
140
+ }
141
+ function createWsServerTransport(cfg = {}) {
142
+ const clients = new Map;
143
+ const rooms = new Map;
144
+ const lastSeen = new Map;
145
+ const maxMessageBytes = cfg.maxMessageBytes ?? 1e6;
146
+ const pingIntervalMs = cfg.pingIntervalMs ?? 30000;
147
+ const pongTimeoutMs = cfg.pongTimeoutMs ?? pingIntervalMs * 2;
148
+ const maxBufferedBytes = cfg.maxBufferedBytes ?? 8000000;
149
+ let heartbeatTimer = null;
150
+ if (pingIntervalMs > 0) {
151
+ heartbeatTimer = setInterval(() => {
152
+ const now = Date.now();
153
+ for (const [clientId, ws] of clients) {
154
+ const last = lastSeen.get(clientId) ?? now;
155
+ if (now - last > pongTimeoutMs) {
156
+ try {
157
+ ws.close();
158
+ } catch {}
159
+ continue;
160
+ }
161
+ try {
162
+ ws.ping?.();
163
+ } catch {}
164
+ }
165
+ }, pingIntervalMs);
166
+ if (typeof heartbeatTimer.unref === "function") {
167
+ heartbeatTimer.unref();
168
+ }
169
+ }
170
+ let messageHandler = null;
171
+ let connectHandler = null;
172
+ let disconnectHandler = null;
173
+ return {
174
+ handleOpen(clientId, ws) {
175
+ clients.set(clientId, ws);
176
+ lastSeen.set(clientId, Date.now());
177
+ connectHandler?.(clientId, new Request("https://ws-connect"));
178
+ },
179
+ handleMessage(clientId, data) {
180
+ lastSeen.set(clientId, Date.now());
181
+ const byteLen = typeof Buffer !== "undefined" ? Buffer.byteLength(data, "utf8") : new Blob([data]).size;
182
+ if (byteLen > maxMessageBytes) {
183
+ console.warn(`[reflectdb] WS server: message from ${clientId} exceeds ${maxMessageBytes} bytes (${byteLen}), closing`);
184
+ const ws = clients.get(clientId);
185
+ try {
186
+ ws?.close();
187
+ } catch {}
188
+ return;
189
+ }
190
+ try {
191
+ const message = JSON.parse(data);
192
+ messageHandler?.(clientId, message);
193
+ } catch (err) {
194
+ console.warn(`[reflectdb] WS server: malformed message from ${clientId}:`, err instanceof Error ? err.message : String(err));
195
+ }
196
+ },
197
+ handleClose(clientId) {
198
+ clients.delete(clientId);
199
+ lastSeen.delete(clientId);
200
+ for (const members of rooms.values()) {
201
+ members.delete(clientId);
202
+ }
203
+ disconnectHandler?.(clientId);
204
+ },
205
+ handlePong(clientId) {
206
+ lastSeen.set(clientId, Date.now());
207
+ },
208
+ async send(clientId, message) {
209
+ const ws = clients.get(clientId);
210
+ if (!ws) {
211
+ throw new TransportSendError(clientId, "no socket registered for client");
212
+ }
213
+ trySend(clientId, ws, JSON.stringify(message), maxBufferedBytes);
214
+ },
215
+ async broadcast(roomId, message, exclude) {
216
+ const members = rooms.get(roomId);
217
+ if (!members)
218
+ return;
219
+ const data = JSON.stringify(message);
220
+ for (const clientId of members) {
221
+ if (clientId === exclude)
222
+ continue;
223
+ const ws = clients.get(clientId);
224
+ if (!ws)
225
+ continue;
226
+ try {
227
+ trySend(clientId, ws, data, maxBufferedBytes);
228
+ } catch (err) {
229
+ console.warn("[reflectdb] ws broadcast skipped a client:", err instanceof Error ? err.message : err);
230
+ }
231
+ }
232
+ },
233
+ disconnect(clientId) {
234
+ const ws = clients.get(clientId);
235
+ if (!ws)
236
+ return;
237
+ try {
238
+ ws.close();
239
+ } catch {}
240
+ clients.delete(clientId);
241
+ },
242
+ onMessage(handler) {
243
+ messageHandler = handler;
244
+ },
245
+ onConnect(handler) {
246
+ connectHandler = handler;
247
+ },
248
+ onDisconnect(handler) {
249
+ disconnectHandler = handler;
250
+ },
251
+ async close() {
252
+ if (heartbeatTimer)
253
+ clearInterval(heartbeatTimer);
254
+ for (const ws of clients.values()) {
255
+ ws.close();
256
+ }
257
+ clients.clear();
258
+ lastSeen.clear();
259
+ rooms.clear();
260
+ }
261
+ };
262
+ }
263
+ function createWsClientTransport(config) {
264
+ let ws = null;
265
+ let handler = null;
266
+ let intentionalClose = false;
267
+ const pending = [];
268
+ const MAX_PENDING = 1000;
269
+ function connect() {
270
+ const socket = new WebSocket(config.url, config.protocols);
271
+ socket.addEventListener("open", () => {
272
+ for (const msg of pending) {
273
+ socket.send(msg);
274
+ }
275
+ pending.length = 0;
276
+ });
277
+ socket.addEventListener("message", (event) => {
278
+ try {
279
+ const message = JSON.parse(event.data);
280
+ handler?.(message);
281
+ } catch (err) {
282
+ console.warn("[reflectdb] WS client: malformed message ignored:", err instanceof Error ? err.message : String(err));
283
+ }
284
+ });
285
+ socket.addEventListener("close", () => {
286
+ if (ws === socket)
287
+ ws = null;
288
+ if (!intentionalClose) {
289
+ handler?.({ type: "disconnect", reason: "ws_closed" });
290
+ }
291
+ });
292
+ socket.addEventListener("error", () => {
293
+ if (!intentionalClose) {
294
+ handler?.({ type: "disconnect", reason: "ws_error" });
295
+ }
296
+ });
297
+ return socket;
298
+ }
299
+ return {
300
+ async send(message) {
301
+ if (!ws) {
302
+ ws = connect();
303
+ }
304
+ const data = JSON.stringify(message);
305
+ if (ws.readyState === WebSocket.OPEN) {
306
+ ws.send(data);
307
+ } else {
308
+ pending.push(data);
309
+ while (pending.length > MAX_PENDING)
310
+ pending.shift();
311
+ }
312
+ },
313
+ subscribe(h) {
314
+ handler = h;
315
+ if (!ws) {
316
+ ws = connect();
317
+ }
318
+ },
319
+ async close() {
320
+ intentionalClose = true;
321
+ if (ws) {
322
+ ws.close();
323
+ ws = null;
324
+ }
325
+ },
326
+ getSocket() {
327
+ return ws;
328
+ }
329
+ };
330
+ }
@@ -0,0 +1,236 @@
1
+ type OpType = "insert" | "update" | "delete";
2
+ type ErrorReason = "outside_shape" | "readonly_query" | "rate_limited" | "buffer_full" | "server_conflict" | "custom_conflict" | "merge_stale" | "clock_drift" | "replay" | "batch_too_large" | "schema_outdated" | "auth_revoked" | "compacted" | "mutation_rejected" | "server_error" | "unknown_query";
3
+ interface HelloMessage {
4
+ type: "hello";
5
+ /** Highest protocol version the client prefers. Retained for back-compat. */
6
+ protocolVersion: number;
7
+ /** All versions the client can speak. Omit for legacy single-version clients. */
8
+ supportedVersions?: readonly number[];
9
+ clientId: string;
10
+ token: string;
11
+ }
12
+ interface BootstrapMessage {
13
+ type: "bootstrap";
14
+ syncParams?: Record<string, Record<string, unknown>>;
15
+ }
16
+ interface ResumeMessage {
17
+ type: "resume";
18
+ since: string;
19
+ }
20
+ interface OpsMessage {
21
+ type: "ops";
22
+ ops: ClientOp[];
23
+ token: string;
24
+ }
25
+ interface ClientOp {
26
+ id: string;
27
+ table: string;
28
+ op: OpType;
29
+ rowId: string;
30
+ payload: Record<string, unknown> | null;
31
+ hlc: string;
32
+ batchId?: string;
33
+ batchSize?: number;
34
+ batchSeq?: number;
35
+ }
36
+ interface SyncDeclareMessage {
37
+ type: "sync_declare";
38
+ table: string;
39
+ params?: Record<string, unknown>;
40
+ window?: number;
41
+ }
42
+ interface LoadMoreMessage {
43
+ type: "load_more";
44
+ table: string;
45
+ count: number;
46
+ }
47
+ interface UnsyncMessage {
48
+ type: "unsync";
49
+ table: string;
50
+ }
51
+ interface AuthMessage {
52
+ type: "auth";
53
+ token: string;
54
+ }
55
+ interface EphemeralMessage {
56
+ type: "ephemeral";
57
+ key: string;
58
+ userId: string;
59
+ data: Record<string, unknown>;
60
+ ttlMs?: number;
61
+ }
62
+ interface HelloAckMessage {
63
+ type: "hello_ack";
64
+ protocolVersion: number;
65
+ serverId: string;
66
+ }
67
+ interface HelloRejectMessage {
68
+ type: "hello_reject";
69
+ reason: string;
70
+ supported: number[];
71
+ }
72
+ interface SnapshotMessage {
73
+ type: "snapshot";
74
+ table: string;
75
+ rows: Record<string, unknown>[];
76
+ colClocks: Record<string, Record<string, string>>;
77
+ append?: boolean;
78
+ totalCount?: number;
79
+ /**
80
+ * Primary key column name for this table. Self-contained per message so the
81
+ * client doesn't depend on `bootstrap_complete.tableMeta` arriving first.
82
+ * When omitted (older servers), the client falls back to tableMeta, then "id".
83
+ */
84
+ pk?: string;
85
+ }
86
+ interface BootstrapCompleteMessage {
87
+ type: "bootstrap_complete";
88
+ serverHlc: string;
89
+ tableMeta: Record<string, TableMeta>;
90
+ }
91
+ interface TableMeta {
92
+ serverSet: string[];
93
+ readonly: string[];
94
+ broadcast: "consistent" | "eager" | "eager-durable";
95
+ /** Primary key column name. Defaults to "id" when omitted (older servers). */
96
+ pk?: string;
97
+ }
98
+ interface DeltaMessage {
99
+ type: "delta";
100
+ table: string;
101
+ op: OpType;
102
+ rowId: string;
103
+ payload: Record<string, unknown> | null;
104
+ hlc: string;
105
+ colClocks?: Record<string, string>;
106
+ }
107
+ interface AckMessage {
108
+ type: "ack";
109
+ opIds: string[];
110
+ }
111
+ interface RejectMessage {
112
+ type: "reject";
113
+ opId?: string;
114
+ batchId?: string;
115
+ reason: ErrorReason;
116
+ serverRow?: Record<string, unknown>;
117
+ }
118
+ interface ResumeCompleteMessage {
119
+ type: "resume_complete";
120
+ serverHlc: string;
121
+ }
122
+ interface ResumeRejectedMessage {
123
+ type: "resume_rejected";
124
+ reason: string;
125
+ serverHlc: string;
126
+ }
127
+ interface ShapeChangedMessage {
128
+ type: "shape_changed";
129
+ table: string;
130
+ reason: "auth_changed" | "params_changed" | "server_policy";
131
+ }
132
+ interface DisconnectMessage {
133
+ type: "disconnect";
134
+ reason: string;
135
+ }
136
+ interface ReauthMessage {
137
+ type: "reauth";
138
+ }
139
+ interface CountChangedMessage {
140
+ type: "count_changed";
141
+ table: string;
142
+ totalCount: number;
143
+ }
144
+ interface EphemeralEvent {
145
+ type: "ephemeral";
146
+ key: string;
147
+ clientId: string;
148
+ userId: string;
149
+ data: Record<string, unknown>;
150
+ ttlMs?: number;
151
+ }
152
+ type ClientMessage = HelloMessage | BootstrapMessage | ResumeMessage | OpsMessage | SyncDeclareMessage | LoadMoreMessage | UnsyncMessage | AuthMessage | EphemeralMessage;
153
+ type ServerMessage = HelloAckMessage | HelloRejectMessage | SnapshotMessage | BootstrapCompleteMessage | DeltaMessage | AckMessage | RejectMessage | ResumeCompleteMessage | ResumeRejectedMessage | ShapeChangedMessage | DisconnectMessage | ReauthMessage | EphemeralEvent | CountChangedMessage;
154
+ interface ServerTransport {
155
+ /**
156
+ * Deliver a message to one client.
157
+ *
158
+ * MUST reject (ideally with `TransportSendError`) when the frame could not
159
+ * be handed to the peer — unknown/closed socket, full outbound queue, or a
160
+ * throw from the underlying socket. Resolving on a dropped frame makes the
161
+ * broadcast engine commit result-cache state the client never received.
162
+ */
163
+ send(clientId: string, message: ServerMessage): Promise<void>;
164
+ broadcast(roomId: string, message: ServerMessage, exclude?: string): Promise<void>;
165
+ onMessage(handler: (clientId: string, message: ClientMessage) => void): void;
166
+ onConnect(handler: (clientId: string, req: Request) => void): void;
167
+ onDisconnect(handler: (clientId: string) => void): void;
168
+ close(): Promise<void>;
169
+ /**
170
+ * Force-disconnect a single client. Optional — if absent, the handler relies
171
+ * on the client honoring a `disconnect` server-message. Required for any
172
+ * transport that carries authentication state, since an adversarial client
173
+ * can otherwise ignore the message and continue using a revoked session.
174
+ */
175
+ disconnect?(clientId: string): Promise<void> | void;
176
+ }
177
+ interface ClientTransport {
178
+ send(message: ClientMessage): Promise<void>;
179
+ subscribe(handler: (message: ServerMessage) => void): void;
180
+ close(): Promise<void>;
181
+ }
182
+ interface WsServerConfig {
183
+ server: {
184
+ upgrade(req: Request, options: {
185
+ data: {
186
+ clientId: string;
187
+ };
188
+ }): boolean;
189
+ };
190
+ path?: string;
191
+ }
192
+ interface WsServerTransportConfig {
193
+ /** Max inbound message bytes before the connection is closed. Default: 1 MB. */
194
+ maxMessageBytes?: number;
195
+ /** Ping interval in ms. 0 disables. Default: 30_000. */
196
+ pingIntervalMs?: number;
197
+ /** Close a connection if no pong is seen in this window. Default: 2× pingInterval. */
198
+ pongTimeoutMs?: number;
199
+ /**
200
+ * Outbound backpressure ceiling. When the socket's `bufferedAmount` exceeds
201
+ * this, `send` rejects instead of queueing more — a slow reader can't make
202
+ * the server buffer without bound. 0 disables. Default: 8 MB.
203
+ */
204
+ maxBufferedBytes?: number;
205
+ }
206
+ /**
207
+ * Origin-check helper for WS/SSE/polling upgrade paths. Callers invoke this
208
+ * before accepting a connection. The default browser WebSocket/EventSource
209
+ * clients always send an Origin header, so a `null` return usually means
210
+ * a non-browser peer — treat accordingly for your threat model.
211
+ *
212
+ * if (!isOriginAllowed(req, ["https://app.example.com"])) return new Response("Forbidden", { status: 403 });
213
+ */
214
+ declare function isOriginAllowed(req: Request, allowed: readonly string[] | ((origin: string | null) => boolean)): boolean;
215
+ declare function createWsServerTransport(cfg?: WsServerTransportConfig): ServerTransport & {
216
+ handleOpen(clientId: string, ws: WebSocketLike): void;
217
+ handleMessage(clientId: string, data: string): void;
218
+ handleClose(clientId: string): void;
219
+ handlePong(clientId: string): void;
220
+ };
221
+ interface WsClientConfig {
222
+ url: string;
223
+ protocols?: string[];
224
+ }
225
+ declare function createWsClientTransport(config: WsClientConfig): ClientTransport & {
226
+ getSocket(): WebSocket | null;
227
+ };
228
+ interface WebSocketLike {
229
+ send(data: string): void;
230
+ close(): void;
231
+ /** WebSocket readyState. When present, only 1 (OPEN) accepts sends. */
232
+ readyState?: number;
233
+ /** Bytes queued but not yet flushed. Used for outbound backpressure. */
234
+ bufferedAmount?: number;
235
+ }
236
+ export { isOriginAllowed, createWsServerTransport, createWsClientTransport, WsServerTransportConfig, WsServerConfig, WsClientConfig, WebSocketLike };