| 57 | * for the pattern this is ported from). |
| 58 | */ |
| 59 | export class WsClient { |
| 60 | private ws: WsWebSocket | null = null; |
| 61 | private readonly _queue: AnyFrame[] = []; |
| 62 | private readonly _waiters: PendingWaiter[] = []; |
| 63 | private readonly _subscribers = new Set<(f: AnyFrame) => void>(); |
| 64 | private _closed = false; |
| 65 | private _closeReason: { code: number; reason: string } | null = null; |
| 66 | private _closeWaiters: Array<(v: { code: number; reason: string }) => void> = []; |
| 67 | |
| 68 | constructor(private readonly opts: WsClientOptions) {} |
| 69 | |
| 70 | /** Open the socket; resolves once `open` fires. */ |
| 71 | async open(): Promise<void> { |
| 72 | if (this.ws) return; |
| 73 | await new Promise<void>((resolve, reject) => { |
| 74 | const ws = new this.opts.wsImpl(this.opts.url); |
| 75 | this.ws = ws; |
| 76 | ws.once('open', () => { |
| 77 | recordReportEvent( |
| 78 | { kind: 'ws', direction: 'lifecycle', url: this.opts.url, message: 'open' }, |
| 79 | { reportDir: this.opts.reportDir }, |
| 80 | ); |
| 81 | resolve(); |
| 82 | }); |
| 83 | ws.once('error', (err) => { |
| 84 | if (this._closed) return; |
| 85 | recordReportEvent( |
| 86 | { |
| 87 | kind: 'ws', |
| 88 | direction: 'lifecycle', |
| 89 | url: this.opts.url, |
| 90 | message: 'error', |
| 91 | error: errorForReport(err), |
| 92 | }, |
| 93 | { reportDir: this.opts.reportDir }, |
| 94 | ); |
| 95 | reject(err as Error); |
| 96 | }); |
| 97 | ws.on('message', (data) => this._onMessage(data)); |
| 98 | ws.on('close', (code, reason) => this._onClose(code, String(reason ?? ''))); |
| 99 | }); |
| 100 | } |
| 101 | |
| 102 | /** JSON-stringifies and sends a frame. */ |
| 103 | send(frame: object): void { |
| 104 | if (!this.ws) throw new Error('ws not open'); |
| 105 | this.ws.send(JSON.stringify(frame)); |
| 106 | recordReportEvent( |
| 107 | { kind: 'ws', direction: 'out', url: this.opts.url, frame }, |
| 108 | { reportDir: this.opts.reportDir }, |
| 109 | ); |
| 110 | } |
| 111 | |
| 112 | /** Register a frame subscriber. Returns an unsubscribe handle. */ |
| 113 | onFrame(handler: (f: AnyFrame) => void): () => void { |
| 114 | this._subscribers.add(handler); |
| 115 | return () => { |
| 116 | this._subscribers.delete(handler); |
nothing calls this directly
no outgoing calls
no test coverage detected