UNPKG

@tldraw/sync-core

Version:

tldraw infinite canvas SDK (multiplayer sync).

8 lines (7 loc) 2.52 kB
{ "version": 3, "sources": ["../../src/lib/ServerSocketAdapter.ts"], "sourcesContent": ["import { UnknownRecord } from '@tldraw/store'\nimport { TLRoomSocket } from './TLSyncRoom'\nimport { TLSocketServerSentEvent } from './protocol'\n\n/**\n * Minimal server-side WebSocket interface that is compatible with\n *\n * - The standard WebSocket interface (cloudflare, deno, some node setups)\n * - The 'ws' WebSocket interface (some node setups)\n * - The Bun.serve socket implementation\n *\n * @public\n */\nexport interface WebSocketMinimal {\n\t// eslint-disable-next-line @typescript-eslint/method-signature-style\n\taddEventListener?: (type: 'message' | 'close' | 'error', listener: (event: any) => void) => void\n\t// eslint-disable-next-line @typescript-eslint/method-signature-style\n\tremoveEventListener?: (\n\t\ttype: 'message' | 'close' | 'error',\n\t\tlistener: (event: any) => void\n\t) => void\n\t// eslint-disable-next-line @typescript-eslint/method-signature-style\n\tsend: (data: string) => void\n\t// eslint-disable-next-line @typescript-eslint/method-signature-style\n\tclose: (code?: number, reason?: string) => void\n\treadyState: number\n}\n\n/** @internal */\nexport interface ServerSocketAdapterOptions<R extends UnknownRecord> {\n\treadonly ws: WebSocketMinimal\n\t// eslint-disable-next-line @typescript-eslint/method-signature-style\n\treadonly onBeforeSendMessage?: (msg: TLSocketServerSentEvent<R>, stringified: string) => void\n}\n\n/** @internal */\nexport class ServerSocketAdapter<R extends UnknownRecord> implements TLRoomSocket<R> {\n\tconstructor(public readonly opts: ServerSocketAdapterOptions<R>) {}\n\t// eslint-disable-next-line no-restricted-syntax\n\tget isOpen(): boolean {\n\t\treturn this.opts.ws.readyState === 1 // ready state open\n\t}\n\t// see TLRoomSocket for details on why this accepts a union and not just arrays\n\tsendMessage(msg: TLSocketServerSentEvent<R>) {\n\t\tconst message = JSON.stringify(msg)\n\t\tthis.opts.onBeforeSendMessage?.(msg, message)\n\t\tthis.opts.ws.send(message)\n\t}\n\tclose(code?: number, reason?: string) {\n\t\tthis.opts.ws.close(code, reason)\n\t}\n}\n"], "mappings": "AAoCO,MAAM,oBAAwE;AAAA,EACpF,YAA4B,MAAqC;AAArC;AAAA,EAAsC;AAAA;AAAA,EAElE,IAAI,SAAkB;AACrB,WAAO,KAAK,KAAK,GAAG,eAAe;AAAA,EACpC;AAAA;AAAA,EAEA,YAAY,KAAiC;AAC5C,UAAM,UAAU,KAAK,UAAU,GAAG;AAClC,SAAK,KAAK,sBAAsB,KAAK,OAAO;AAC5C,SAAK,KAAK,GAAG,KAAK,OAAO;AAAA,EAC1B;AAAA,EACA,MAAM,MAAe,QAAiB;AACrC,SAAK,KAAK,GAAG,MAAM,MAAM,MAAM;AAAA,EAChC;AACD;", "names": [] }