Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat!(ws): final websocket abstraction (#178)
teoa08cc812bef5
diff --git a/js/app/bun.lock b/js/app/bun.lockindex 39495770cc..43f31fcc73 100644--- a/js/app/bun.lock+++ b/js/app/bun.lock@@ -1,5 +1,6 @@{"lockfileVersion": 1,+ "configVersion": 0,"workspaces": {"": {"name": "@coparse/monorepo",@@ -451,10 +452,6 @@},"packages/websocket": {"name": "websocket",- "dependencies": {- "vitest": "^3.2.3",- "zod": "^3.24.1",- },"devDependencies": {"vite-tsconfig-paths": "^5.1.4",},diff --git a/js/app/packages/app/component/settings/Mobile.tsx b/js/app/packages/app/component/settings/Mobile.tsxindex 2bb31abc5e..da764a1260 100644--- a/js/app/packages/app/component/settings/Mobile.tsx+++ b/js/app/packages/app/component/settings/Mobile.tsx@@ -29,7 +29,7 @@ import { notificationServiceClient } from '@service-notification/client';import type { PushNotificationData } from '@service-notification/generated/schemas/pushNotificationData';import { type AsyncStorage, makePersisted } from '@solid-primitives/storage';import { useNavigate } from '@solidjs/router';-import { WebSocketState } from '@websocket/index';+import { WebsocketConnectionState } from '@websocket';import { toast } from 'core/component/Toast/Toast';import {createEffect,@@ -232,7 +232,10 @@ export function useMobileEffect() {App.addListener('resume', () => {const wsState = state();- if (wsState === WebSocketState.Closed || wsState === WebSocketState.Closing)+ if (+ wsState === WebsocketConnectionState.Closed ||+ wsState === WebsocketConnectionState.Closing+ )ws.reconnect();});diff --git a/js/app/packages/core/component/WebsocketDebugger.tsx b/js/app/packages/core/component/WebsocketDebugger.tsxindex b2fea6cb18..fd642385bf 100644--- a/js/app/packages/core/component/WebsocketDebugger.tsx+++ b/js/app/packages/core/component/WebsocketDebugger.tsx@@ -10,14 +10,15 @@ import {state as storageState,ws as storageWs,} from '@service-storage/websocket';-import { WebSocketState } from '@websocket/index';+import { WebsocketConnectionState } from '@websocket';import { createSignal, onCleanup, onMount, Show } from 'solid-js';-const WebSocketStateLabels = {- [WebSocketState.Connecting]: 'Connecting',- [WebSocketState.Open]: 'Open',- [WebSocketState.Closing]: 'Closing',- [WebSocketState.Closed]: 'Closed',+const WebsocketConnectionStateLabels = {+ [WebsocketConnectionState.Connecting]: 'Connecting',+ [WebsocketConnectionState.Open]: 'Open',+ [WebsocketConnectionState.Closing]: 'Closing',+ [WebsocketConnectionState.Closed]: 'Closed',+ [WebsocketConnectionState.Reconnecting]: 'Reconnecting',} as const;export function WebsocketDebugger() {@@ -105,26 +106,26 @@ export function WebsocketDebugger() {<div class="text-sm font-medium text-ink">Cognition Service</div><spanclass={`text-xs font-medium px-3 py-1.5 rounded-lg ${- cognitionState() === WebSocketState.Open+ cognitionState() === WebsocketConnectionState.Open? 'bg-success-bg text-success-ink border border-success/30'- : cognitionState() === WebSocketState.Connecting+ : cognitionState() === WebsocketConnectionState.Connecting? 'bg-alert/10 text-alert-ink border border-alert/30': 'bg-failure-bg text-failure-ink border border-failure/30'}`}>- {WebSocketStateLabels[cognitionState()]}+ {WebsocketConnectionStateLabels[cognitionState()]}</span></div><div class="flex gap-2"><buttononClick={() => cognitionWs.close()}disabled={- cognitionState() === WebSocketState.Closed ||- cognitionState() === WebSocketState.Closing+ cognitionState() === WebsocketConnectionState.Closed ||+ cognitionState() === WebsocketConnectionState.Closing}class={`flex-1 text-xs font-medium px-3 py-2 rounded-lg transition-colors duration-150 border ${- cognitionState() === WebSocketState.Closed ||- cognitionState() === WebSocketState.Closing+ cognitionState() === WebsocketConnectionState.Closed ||+ cognitionState() === WebsocketConnectionState.Closing? 'bg-edge/20 text-ink-disabled border-edge/30 cursor-not-allowed': 'bg-failure-bg hover:bg-failure text-failure-ink border-failure/30'}`}@@ -133,9 +134,9 @@ export function WebsocketDebugger() {</button><buttononClick={() => cognitionWs.reconnect()}- disabled={cognitionState() === WebSocketState.Open}+ disabled={cognitionState() === WebsocketConnectionState.Open}class={`flex-1 text-xs font-medium px-3 py-2 rounded-lg transition-colors duration-150 border ${- cognitionState() === WebSocketState.Open+ cognitionState() === WebsocketConnectionState.Open? 'bg-edge/20 text-ink-disabled border-edge/30 cursor-not-allowed': 'bg-accent/10 hover:bg-accent/20 text-accent-ink border-accent/30'}`}@@ -151,26 +152,26 @@ export function WebsocketDebugger() {<div class="text-sm font-medium text-ink">Connection Service</div><spanclass={`text-xs font-medium px-3 py-1.5 rounded-lg ${- connectionState() === WebSocketState.Open+ connectionState() === WebsocketConnectionState.Open? 'bg-success-bg text-success-ink border border-success/30'- : connectionState() === WebSocketState.Connecting+ : connectionState() === WebsocketConnectionState.Connecting? 'bg-alert/10 text-alert-ink border border-alert/30': 'bg-failure-bg text-failure-ink border border-failure/30'}`}>- {WebSocketStateLabels[connectionState()]}+ {WebsocketConnectionStateLabels[connectionState()]}</span></div><div class="flex gap-2"><buttononClick={() => connectionWs.close()}disabled={- connectionState() === WebSocketState.Closed ||- connectionState() === WebSocketState.Closing+ connectionState() === WebsocketConnectionState.Closed ||+ connectionState() === WebsocketConnectionState.Closing}class={`flex-1 text-xs font-medium px-3 py-2 rounded-lg transition-colors duration-150 border ${- connectionState() === WebSocketState.Closed ||- connectionState() === WebSocketState.Closing+ connectionState() === WebsocketConnectionState.Closed ||+ connectionState() === WebsocketConnectionState.Closing? 'bg-edge/20 text-ink-disabled border-edge/30 cursor-not-allowed': 'bg-failure-bg hover:bg-failure text-failure-ink border-failure/30'}`}@@ -179,9 +180,9 @@ export function WebsocketDebugger() {</button><buttononClick={() => connectionWs.reconnect()}- disabled={connectionState() === WebSocketState.Open}+ disabled={connectionState() === WebsocketConnectionState.Open}class={`flex-1 text-xs font-medium px-3 py-2 rounded-lg transition-colors duration-150 border ${- connectionState() === WebSocketState.Open+ connectionState() === WebsocketConnectionState.Open? 'bg-edge/20 text-ink-disabled border-edge/30 cursor-not-allowed': 'bg-accent/10 hover:bg-accent/20 text-accent-ink border-accent/30'}`}@@ -197,26 +198,26 @@ export function WebsocketDebugger() {<div class="text-sm font-medium text-ink">Storage Service</div><spanclass={`text-xs font-medium px-3 py-1.5 rounded-lg ${- storageState() === WebSocketState.Open+ storageState() === WebsocketConnectionState.Open? 'bg-success-bg text-success-ink border border-success/30'- : storageState() === WebSocketState.Connecting+ : storageState() === WebsocketConnectionState.Connecting? 'bg-alert/10 text-alert-ink border border-alert/30': 'bg-failure-bg text-failure-ink border border-failure/30'}`}>- {WebSocketStateLabels[storageState()]}+ {WebsocketConnectionStateLabels[storageState()]}</span></div><div class="flex gap-2"><buttononClick={() => storageWs.close()}disabled={- storageState() === WebSocketState.Closed ||- storageState() === WebSocketState.Closing+ storageState() === WebsocketConnectionState.Closed ||+ storageState() === WebsocketConnectionState.Closing}class={`flex-1 text-xs font-medium px-3 py-2 rounded-lg transition-colors duration-150 border ${- storageState() === WebSocketState.Closed ||- storageState() === WebSocketState.Closing+ storageState() === WebsocketConnectionState.Closed ||+ storageState() === WebsocketConnectionState.Closing? 'bg-edge/20 text-ink-disabled border-edge/30 cursor-not-allowed': 'bg-failure-bg hover:bg-failure text-failure-ink border-failure/30'}`}@@ -225,9 +226,9 @@ export function WebsocketDebugger() {</button><buttononClick={() => storageWs.reconnect()}- disabled={storageState() === WebSocketState.Open}+ disabled={storageState() === WebsocketConnectionState.Open}class={`flex-1 text-xs font-medium px-3 py-2 rounded-lg transition-colors duration-150 border ${- storageState() === WebSocketState.Open+ storageState() === WebsocketConnectionState.Open? 'bg-edge/20 text-ink-disabled border-edge/30 cursor-not-allowed': 'bg-accent/10 hover:bg-accent/20 text-accent-ink border-accent/30'}`}diff --git a/js/app/packages/service-cognition/websocket.ts b/js/app/packages/service-cognition/websocket.tsindex dd9af63834..520316dbe9 100644--- a/js/app/packages/service-cognition/websocket.ts+++ b/js/app/packages/service-cognition/websocket.ts@@ -1,4 +1,3 @@-import { useIsAuthenticated } from '@core/auth';import { createBlockEffect, inBlock } from '@core/block';import { ENABLE_BEARER_TOKEN_AUTH } from '@core/constant/featureFlags';import { SERVER_HOSTS } from '@core/constant/servers';@@ -6,19 +5,24 @@ import { fetchToken } from '@core/util/fetchWithToken';import { getMacroApiToken } from '@service-auth/fetch';import { createCallback } from '@solid-primitives/rootless';import {- authPlugin,- createDurableSocket,- createSocketEffect,- createWSState,- heartbeatPlugin,- jsonPlugin,-} from '@websocket/index';+ ConstantBackoff,+ JsonSerializer,+ type Websocket,+ WebsocketBuilder,+} from '@websocket';+import { createSocketEffect } from '@websocket/solid/socket-effect';+import { createWebsocketStateSignal } from '@websocket/solid/state-signal';import type { Accessor } from 'solid-js';import { createRoot, createSignal } from 'solid-js';import type { StreamError } from './generated/schemas';import type { FromWebSocketMessage } from './generated/schemas/fromWebSocketMessage';import type { ToWebSocketMessage } from './generated/schemas/toWebSocketMessage';+export type CognitionWebsocket = Websocket<+ ToWebSocketMessage,+ FromWebSocketMessage+>;+export type { StreamError, FromWebSocketMessage, ToWebSocketMessage };/**@@ -37,35 +41,31 @@ export enum WebSocketState {const wsHost: string = SERVER_HOSTS['cognition-websocket-service'];-export const ws = createDurableSocket<ToWebSocketMessage, FromWebSocketMessage>(- wsHost,- {- backoffStrategy: 'linear',- delay: 500,- reconnectUrlResolver: async () => {- if (ENABLE_BEARER_TOKEN_AUTH) {- const apiToken = await getMacroApiToken();- if (!apiToken) throw new Error('No Macro API token');-- return `${wsHost}/?macro-api-token=${apiToken}`;- }- await fetchToken();- return wsHost;- },- },- [- authPlugin({- isAuthenticated: () => {- const isAuth = useIsAuthenticated();- return isAuth() ?? false;- },- }),- heartbeatPlugin({ interval: 25_000 }),- jsonPlugin<ToWebSocketMessage, FromWebSocketMessage>(),- ]-);--export const state = createWSState(ws);+async function resolveWsUrl() {+ if (ENABLE_BEARER_TOKEN_AUTH) {+ const apiToken = await getMacroApiToken();+ if (!apiToken) throw new Error('No Macro API token');+ return `${wsHost}/?macro-api-token=${apiToken}`;+ }+ await fetchToken();+ return wsHost;+}++export const ws: CognitionWebsocket = new WebsocketBuilder(resolveWsUrl)+ .withSerializer(+ new JsonSerializer<ToWebSocketMessage, FromWebSocketMessage>()+ )+ .withBackoff(new ConstantBackoff(500))+ .withHeartbeat({+ interval: 1_000,+ timeout: 1_000,+ pingMessage: 'ping',+ pongMessage: 'pong',+ maxMissedHeartbeats: 3,+ })+ .build();++export const state = createWebsocketStateSignal(ws);export function createCognitionWebsocketBlockEffect<T extends FromWebSocketMessage['type'],diff --git a/js/app/packages/service-connection/websocket.ts b/js/app/packages/service-connection/websocket.tsindex e1be1d9f55..7efa1970a5 100644--- a/js/app/packages/service-connection/websocket.ts+++ b/js/app/packages/service-connection/websocket.ts@@ -1,4 +1,3 @@-import { useIsAuthenticated } from '@core/auth';import { createBlockEffect, inBlock } from '@core/block';import { ENABLE_BEARER_TOKEN_AUTH } from '@core/constant/featureFlags';import { SERVER_HOSTS } from '@core/constant/servers';@@ -6,50 +5,53 @@ import { fetchToken } from '@core/util/fetchWithToken';import { getMacroApiToken } from '@service-auth/fetch';import { createCallback } from '@solid-primitives/rootless';import {- authPlugin,- createDurableSocket,createSocketEffect,- createWSState,- heartbeatPlugin,- jsonPlugin,-} from '@websocket/index';+ JsonSerializer,+ LinearBackoff,+ type Websocket,+ WebsocketBuilder,+} from '@websocket';+import { createWebsocketStateSignal } from '@websocket/solid/state-signal';import type { ToWebsocketMessage } from './generated/schemas/toWebsocketMessage';const wsHost: string = SERVER_HOSTS['connection-gateway'];-const isAuthenticated = useIsAuthenticated();+export type ConnectionGatewayWebsocket = Websocket<+ ToWebsocketMessage,+ FromWebsocketMessage+>;export type FromWebsocketMessage = {type: string;data: any;};-export const ws = createDurableSocket<ToWebsocketMessage, FromWebsocketMessage>(- wsHost,- {- backoffStrategy: 'linear',- delay: 500,- reconnectUrlResolver: async () => {- if (ENABLE_BEARER_TOKEN_AUTH) {- const apiToken = await getMacroApiToken();- if (!apiToken) throw new Error('No Macro API token');+async function resolveWsUrl() {+ if (ENABLE_BEARER_TOKEN_AUTH) {+ const apiToken = await getMacroApiToken();+ if (!apiToken) throw new Error('No Macro API token');- return `${wsHost}/?macro-api-token=${apiToken}`;- }- await fetchToken();- return wsHost;- },- },- [- authPlugin({- isAuthenticated: () => isAuthenticated() ?? false,- }),- heartbeatPlugin({ interval: 25_000 }),- jsonPlugin<ToWebsocketMessage, FromWebsocketMessage>(),- ]-);+ return `${wsHost}/?macro-api-token=${apiToken}`;+ }+ await fetchToken();+ return wsHost;+}++export const ws = new WebsocketBuilder(resolveWsUrl)+ .withSerializer(+ new JsonSerializer<ToWebsocketMessage, FromWebsocketMessage>()+ )+ .withBackoff(new LinearBackoff(500, 500))+ .withHeartbeat({+ interval: 1_000,+ timeout: 1_000,+ pingMessage: 'ping',+ pongMessage: 'pong',+ maxMissedHeartbeats: 3,+ })+ .build();-export const state = createWSState(ws);+export const state = createWebsocketStateSignal(ws);// TODO: add type mapping on the websocket eventexport function createConnectionBlockWebsocketEffect(diff --git a/js/app/packages/service-storage/util/upload.ts b/js/app/packages/service-storage/util/upload.tsindex 97eb00f4b2..693b08b6bb 100644--- a/js/app/packages/service-storage/util/upload.ts+++ b/js/app/packages/service-storage/util/upload.ts@@ -173,7 +173,9 @@ export async function upload(let jobId: string | undefined;let docxProcessingPromise: Promise<boolean | undefined> | undefined;if (fileTypeOrExtension === 'docx') {- const [uploadJobPromise, processingPromise] = uploadDocx(storageWS);+ const [uploadJobPromise, processingPromise] = uploadDocx(+ storageWS.underlyingWebsocket+ );jobId = await uploadJobPromise;if (jobId == null) {diff --git a/js/app/packages/service-storage/websocket.ts b/js/app/packages/service-storage/websocket.tsindex 63d0205fb6..c43a15e571 100644--- a/js/app/packages/service-storage/websocket.ts+++ b/js/app/packages/service-storage/websocket.ts@@ -1,9 +1,11 @@import { SERVER_HOSTS } from '@core/constant/servers';import {- createDurableSocket,- createWSState,- heartbeatPlugin,+ ConstantBackoff,+ type Websocket,+ WebsocketBuilder,+ WebsocketEvent,} from '@websocket';+import { createWebsocketStateSignal } from '@websocket/solid/state-signal';import { createEffect, createSignal, onCleanup } from 'solid-js';import { v7 as uuidv7 } from 'uuid';@@ -18,24 +20,20 @@ const HEARTBEAT_INTERVAL = 300000;*/const HEARTBEAT_TIMEOUT = 5000;-export const ws = createDurableSocket(- SERVER_HOSTS['websocket-service'],- {- retries: 5,- delay: 1500,- },- [- heartbeatPlugin({- message: JSON.stringify({ action: 'wsping' }),- wait: HEARTBEAT_TIMEOUT,- interval: HEARTBEAT_INTERVAL,- }),- ]-);+export const ws = new WebsocketBuilder(SERVER_HOSTS['websocket-service'])+ .withBackoff(new ConstantBackoff(1500))+ .withHeartbeat({+ pingMessage: JSON.stringify({ action: 'wsping' }),+ pongMessage: 'pong',+ timeout: HEARTBEAT_TIMEOUT,+ interval: HEARTBEAT_INTERVAL,+ maxMissedHeartbeats: 3,+ })+ .build();export const storageWS = ws;-export const state = createWSState(ws);+export const state = createWebsocketStateSignal(ws);type WebSocketJobConfig<T, R, D, U> = {// websocket request data@@ -61,7 +59,10 @@ export function createWebSocketJob<T, R, D, U>({const requestId = uuidv7();// TODO: use zod types- const messageHandler = async (event: MessageEvent) => {+ const messageHandler = async (+ _instance: Websocket,+ event: MessageEvent+ ) => {if (event.data === 'pong') return;const eventMessage = JSON.parse(event.data);@@ -98,7 +99,7 @@ export function createWebSocketJob<T, R, D, U>({setJobId(eventMessage.jobId);};- storageWS.addEventListener('message', messageHandler);+ storageWS.addEventListener(WebsocketEvent.Message, messageHandler);storageWS.send(JSON.stringify({requestId,@@ -111,7 +112,7 @@ export function createWebSocketJob<T, R, D, U>({const completedJobId = jobId();const jobFailed = failed();if (completedJobId) {- storageWS.removeEventListener('message', messageHandler);+ storageWS.removeEventListener(WebsocketEvent.Message, messageHandler);const currentResult = result();if (!currentResult) {@@ -125,13 +126,13 @@ export function createWebSocketJob<T, R, D, U>({}if (jobFailed) {- storageWS.removeEventListener('message', messageHandler);+ storageWS.removeEventListener(WebsocketEvent.Message, messageHandler);reject();}});onCleanup(() => {- storageWS.removeEventListener('message', messageHandler);+ storageWS.removeEventListener(WebsocketEvent.Message, messageHandler);});});}diff --git a/js/app/packages/service-sync/source.ts b/js/app/packages/service-sync/source.tsindex bcbf6918d3..2370117a05 100644--- a/js/app/packages/service-sync/source.ts+++ b/js/app/packages/service-sync/source.ts@@ -16,15 +16,18 @@ import { storageServiceClient } from '@service-storage/client';import { createEventBus } from '@solid-primitives/event-bus';import { raceTimeout, until } from '@solid-primitives/promise';import {- bebopPlugin,+ BebopSerializer,+ ConstantBackoff,+ type UrlResolver,+ untilMessage,+ WebsocketBuilder,+ WebsocketConnectionState,+} from '@websocket';+import {createReconnectEffect,createSocketEffect,- createWSState,- heartbeatPlugin,- makeDurableSocket,- untilMessage,- WebSocketState,-} from '@websocket/index';+} from '@websocket/solid/socket-effect';+import { createWebsocketStateSignal } from '@websocket/solid/state-signal';import { encodeFrontiers, type Frontiers } from 'loro-crdt';import { err, ok, type Result, ResultAsync } from 'neverthrow';import { createStore } from 'solid-js/store';@@ -37,14 +40,15 @@ import {const SYNC_SERVICE_WS_URL = `${SYNC_SERVICE_HOSTS['ws']}/document`;-function mapToSyncStatus(status: WebSocketState): SyncSourceStatus {+function mapToSyncStatus(status: WebsocketConnectionState): SyncSourceStatus {switch (status) {- case WebSocketState.Connecting:+ case WebsocketConnectionState.Connecting:return SyncSourceStatus.Connecting;- case WebSocketState.Open:+ case WebsocketConnectionState.Open:return SyncSourceStatus.Connected;- case WebSocketState.Closed:- case WebSocketState.Closing:+ case WebsocketConnectionState.Closed:+ case WebsocketConnectionState.Closing:+ case WebsocketConnectionState.Reconnecting:return SyncSourceStatus.Disconnected;}}@@ -55,7 +59,7 @@ function createSyncServiceSocket(documentId: string, token: string) {/*** Refetches the token if it is expired*/- const getUrl = async () => {+ const getUrl: UrlResolver = async () => {const response =await storageServiceClient.permissionsTokens.createPermissionToken({document_id: documentId,@@ -71,21 +75,18 @@ function createSyncServiceSocket(documentId: string, token: string) {return `${SYNC_SERVICE_WS_URL}/${documentId}/connect?token=${token}`;};- return makeDurableSocket(- URL,- {- backoffStrategy: 'constant',- delay: 500,- reconnectUrlResolver: getUrl,- },- [- heartbeatPlugin({- interval: 1_000,- wait: 1_000,- }),- bebopPlugin(FromPeer, FromRemote),- ]- );+ return new WebsocketBuilder(getUrl)+ .withSerializer(new BebopSerializer(FromPeer, FromRemote))+ .withBackoff(new ConstantBackoff(500))+ .withMaxRetries(20)+ .withHeartbeat({+ interval: 1_000,+ timeout: 1_000,+ pingMessage: 'ping',+ pongMessage: 'pong',+ maxMissedHeartbeats: 1,+ })+ .build();}const TIMEOUTS = {@@ -128,7 +129,7 @@ export const createSyncServiceSource = async (const eventBus = createEventBus<SyncSourceEvent>();- const status = createWSState(ws);+ const status = createWebsocketStateSignal(ws);const [awaitingAckStore, setAwaitingAck] = createStore<Record<string, true>>({}diff --git a/js/app/packages/websocket/MockWebSocket.ts b/js/app/packages/websocket/MockWebSocket.tsdeleted file mode 100644index 8987d85c79..0000000000--- a/js/app/packages/websocket/MockWebSocket.ts+++ /dev/null@@ -1,191 +0,0 @@-import type { MinimalWebSocket } from './MinimalWebSocket';--/**- * Mock WebSocket implementation for testing- */-export class MockWebSocket implements MinimalWebSocket {- binaryType: BinaryType = 'blob';- bufferedAmount: number = 0;- extensions: string = '';- protocol: string = '';- readyState: number = 0; // CONNECTING- url: string;-- onclose: ((this: WebSocket, ev: CloseEvent) => any) | null = null;- onerror: ((this: WebSocket, ev: Event) => any) | null = null;- onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null = null;- onopen: ((this: WebSocket, ev: Event) => any) | null = null;-- readonly CONNECTING = 0;- readonly OPEN = 1;- readonly CLOSING = 2;- readonly CLOSED = 3;-- private listeners = new Map<string, Set<Function>>();- private messageQueue: any[] = [];-- constructor(- url: string | URL,- protocols?: string | string[],- autoOpen = true- ) {- this.url = url.toString();-- if (protocols) {- this.protocol = Array.isArray(protocols) ? protocols[0] : protocols;- }-- if (autoOpen) {- setTimeout(() => this.simulateOpen(), 0);- }- }-- addEventListener<K extends keyof WebSocketEventMap>(- type: K,- listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,- _options?: boolean | AddEventListenerOptions- ): void {- if (!this.listeners.has(type)) {- this.listeners.set(type, new Set());- }- this.listeners.get(type)!.add(listener);- }-- removeEventListener<K extends keyof WebSocketEventMap>(- type: K,- listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,- _options?: boolean | EventListenerOptions- ): void {- this.listeners.get(type)?.delete(listener);- }-- dispatchEvent(event: Event): boolean {- const listeners = this.listeners.get(event.type);- if (listeners) {- listeners.forEach((listener) => {- listener.call(this as any, event);- });- }-- // Also call direct event handlers- const handler = (this as any)[`on${event.type}`];- if (handler) {- handler.call(this as any, event);- }-- return true;- }-- close(code?: number, reason?: string): void {- if (this.readyState === this.CLOSED || this.readyState === this.CLOSING) {- return;- }-- this.readyState = this.CLOSING;-- setTimeout(() => {- this.readyState = this.CLOSED;- const event = new CloseEvent('close', {- code: code ?? 1000,- reason: reason ?? '',- wasClean: true,- });- this.dispatchEvent(event);- }, 0);- }-- send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void {- if (this.readyState !== this.OPEN) {- throw new Error('WebSocket is not open');- }-- this.messageQueue.push(data);- }-- // Test helper methods- simulateOpen(): void {- this.readyState = this.OPEN;- const event = new Event('open');- this.dispatchEvent(event);- }-- simulateMessage(data: any): void {- if (this.readyState !== this.OPEN) {- throw new Error('WebSocket must be open to receive messages');- }-- const event = new MessageEvent('message', { data });- this.dispatchEvent(event);- }-- simulateError(_error?: any): void {- const event = new Event('error');- this.dispatchEvent(event);- }-- simulateClose(code = 1000, reason = ''): void {- this.close(code, reason);- }-- getMessageQueue(): any[] {- return [...this.messageQueue];- }-- clearMessageQueue(): void {- this.messageQueue = [];- }-}--/**- * Factory function for creating mock WebSocket instances- */-export const mockWebSocketFactory = (- url: string | URL,- protocols?: string | string[]-): MinimalWebSocket => {- return new MockWebSocket(url, protocols);-};--/**- * Configurable mock factory for advanced testing scenarios- */-export class ConfigurableMockWebSocketFactory {- private defaultOptions: {- autoOpen?: boolean;- openDelay?: number;- failOnConnect?: boolean;- errorOnSend?: boolean;- } = {};-- constructor(- options?: typeof ConfigurableMockWebSocketFactory.prototype.defaultOptions- ) {- if (options) {- this.defaultOptions = options;- }- }-- create(url: string | URL, protocols?: string | string[]): MinimalWebSocket {- const mock = new MockWebSocket(- url,- protocols,- this.defaultOptions.autoOpen ?? true- );-- if (this.defaultOptions.failOnConnect) {- setTimeout(() => {- mock.simulateError(new Error('Connection failed'));- mock.simulateClose(1006, 'Connection failed');- }, this.defaultOptions.openDelay ?? 0);- }-- if (this.defaultOptions.errorOnSend) {- const _originalSend = mock.send.bind(mock);- mock.send = (_data) => {- throw new Error('Send failed');- };- }-- return mock;- }-}diff --git a/js/app/packages/websocket/README.md b/js/app/packages/websocket/README.mdindex 27b4d4f711..7084c71510 100644--- a/js/app/packages/websocket/README.md+++ b/js/app/packages/websocket/README.md@@ -1,55 +1,73 @@+# @macro/websocket++Type-safe WebSocket abstraction with auto-reconnect, buffering, and heartbeat support.++## Basic Usage```typescript-// Simple WebSocket with auto-cleanup-const ws = createWS('ws://localhost:5000');+import { Websocket } from 'websocket';++const ws = new Websocket<SendType, ReceiveType>('ws://localhost:5000');-// With reconnection-const ws = createReconnectingWS('ws://localhost:5000', [], {- delay: 3000, // 3s between reconnects- retries: 10 // stop after 10 attempts+ws.addEventListener('message', (event) => {+ console.log('Received:', event.detail);});-```-## Composing Features+ws.send({ type: 'hello' });+```-Stack wrappers from inside out:+## Builder Pattern```typescript-const ws = makeAuthenticatedWS( // 4. Auth handling- makeFocusTrackingWS( // 3. Reconnect on focus- makeHeartbeatWS( // 2. Connection health- makeJsonWS( // 1. JSON serialization- createReconnectingWS(url) // 0. Base reconnection- )- )- )-);--// Or use the sensible defaults-const ws = makeJsonWS(- createSensibleWS('ws://localhost:5000')-);+import { WebsocketBuilder, ExponentialBackoff, JsonSerializer } from 'websocket';++const ws = new WebsocketBuilder('ws://localhost:5000')+ .withBackoff(new ExponentialBackoff(1000, 30000))+ .withSerializer(new JsonSerializer())+ .withHeartbeat({ interval: 30000, timeout: 5000 })+ .build();```-## Message Serialization+## Reconnection++Configurable via `retryOptions`:```typescript-// JSON-const ws = makeJsonWS<SendType, ReceiveType>(createWS(url));-ws.send({ type: 'chat', text: 'Hello' }); // auto-serialized+const ws = new Websocket(url, {+ retryOptions: {+ maxRetries: 10,+ backoff: new ExponentialBackoff(1000, 30000)+ }+});+```++## Serialization++Built-in serializers for common formats:-// Zod validation-const ws = makeZodWS(createWS(url), SendSchema, ReceiveSchema);+```typescript+import { JsonSerializer, BebopSerializer } from 'websocket';-// Binary (Bebop)-const ws = makeBebopWS(createWS(url), MessageType, ServerMessageType);+// JSON+new WebsocketBuilder(url)+ .withSerializer(new JsonSerializer())+ .build();++// Bebop (binary)+new WebsocketBuilder(url)+ .withSerializer(new BebopSerializer(encoder, decoder))+ .build();```-## Reactive Effects+## SolidJS Integration++Reactive effects for message handling:```typescript+import { createSocketEffect, createWebsocketEventEffect } from 'websocket';+// Listen to all messages-createWebsocketEffect(ws, (data) => {+createSocketEffect(ws, (data) => {console.log('Received:', data);});@@ -57,49 +75,46 @@ createWebsocketEffect(ws, (data) => {createWebsocketEventEffect(ws, 'chat', (msg: ChatMessage) => {addToChat(msg);});+```-// Custom selectors-createWebsocketSelectEffect(ws,- (data): data is CriticalEvent => data.priority === 'high',- (event) => handleCritical(event)-);+## Connection State-// Block effects for special contexts-createBlockWebsocketEffect(ws, (data) => {- updateBlockState(data);-});+Track connection lifecycle:++```typescript+ws.addEventListener('open', () => console.log('Connected'));+ws.addEventListener('close', () => console.log('Disconnected'));+ws.addEventListener('retry', (e) => console.log('Retrying:', e.detail));+ws.addEventListener('reconnect', (e) => console.log('Reconnected:', e.detail));++// Or use reactive state+import { createWebsocketStateSignal } from 'websocket';+const [state] = createWebsocketStateSignal(ws);```-## Selector Helpers+## API Reference-```typescript-// Single type-messageTypeSelector('chat')+**Core**+- `Websocket<Send, Receive>` - Main WebSocket wrapper+- `WebsocketBuilder` - Fluent builder interface-// Multiple types-multiTypeSelector('chat', 'status', 'typing')+**Backoff Strategies**+- `ExponentialBackoff(initial, max)` - Exponential growth+- `LinearBackoff(initial, increment)` - Linear growth+- `ConstantBackoff(delay)` - Fixed delay-// Property matching-propertySelector('userId', currentUser.id)-```+**Serializers**+- `JsonSerializer<T>()` - JSON serialization+- `BebopSerializer<T>(encoder, decoder)` - Binary serialization++**Queues** (for message buffering)+- `ArrayQueue<T>()` - Unbounded array-based queue+- `RingQueue<T>(capacity)` - Fixed-size circular buffer++**SolidJS Effects**+- `createSocketEffect(ws, handler)` - Listen to all messages+- `createWebsocketEventEffect(ws, type, handler)` - Filter by message type+- `createWebsocketStateSignal(ws)` - Reactive connection state-## Quick Reference--**Base Functions**-- `makeWS` / `createWS` - Basic WebSocket-- `makeReconnectingWS` / `createReconnectingWS` - Auto-reconnect-- `createWSState` - Reactive connection state--**Wrappers** (compose these!)-- `makeHeartbeatWS` - Ping/pong health checks-- `makeFocusTrackingWS` - Reconnect on tab focus-- `makeAuthenticatedWS` - Handle auth changes-- `makeJsonWS` - JSON serialization-- `makeZodWS` - Type validation-- `makeBebopWS` - Binary protocol--**Effects**-- `createWebsocketEffect` - Listen to all messages-- `createWebsocketEventEffect` - Listen by type field-- `createWebsocketSelectEffect` - Custom selector-- `createBlock*` variants - For block contexts+**Utils**+- `untilMessage<T>(ws, predicate)` - Promise that resolves on matching messagediff --git a/js/app/packages/websocket/SolidPrimitives.ts b/js/app/packages/websocket/SolidPrimitives.tsdeleted file mode 100644index dd2d9ffed5..0000000000--- a/js/app/packages/websocket/SolidPrimitives.ts+++ /dev/null@@ -1,313 +0,0 @@-import { type Accessor, createSignal, onCleanup } from 'solid-js';-import { platformWebSocketFactory } from './index';-import type { MinimalWebSocket, WebSocketFactory } from './MinimalWebSocket';--export type WSMessage = string | ArrayBufferLike | ArrayBufferView | Blob;--/**- * Opens a WebSocket connection with a queued send mechanism and configurable factory.- * Messages sent before connection opens are queued and sent when connection establishes.- *- * @param url - WebSocket URL- * @param protocols - Optional protocols- * @param webSocketFactory - Factory function to create WebSocket instances- * @param sendQueue - Optional initial send queue- * @returns WebSocket instance with enhanced send behavior- *- * @example- * ```ts- * const ws = makeWS("ws://localhost:5000", undefined, platformWebSocketFactory);- * createEffect(() => ws.send(serverMessage()));- * onCleanup(() => ws.close());- * ```- */-export const makeWS = (- url: string,- protocols?: string | string[],- webSocketFactory: WebSocketFactory = platformWebSocketFactory,- sendQueue: WSMessage[] = []-): MinimalWebSocket => {- const ws = webSocketFactory(url, protocols);- const _send = ws.send.bind(ws);- ws.send = (msg: WSMessage) =>- ws.readyState === 1 ? _send(msg) : sendQueue.push(msg);- ws.addEventListener('open', () => {- while (sendQueue.length) _send(sendQueue.shift()!);- });- return ws;-};--/**- * Creates a WebSocket that automatically closes on cleanup, with configurable factory.- *- * @param url - WebSocket URL- * @param protocols - Optional protocols- * @param webSocketFactory - Factory function to create WebSocket instances- * @returns WebSocket instance that closes on cleanup- *- * @example- * ```ts- * const ws = createWS("ws://localhost:5000", undefined, tauriWebSocketFactory);- * ```- */-export const createWS = (- url: string,- protocols?: string | string[],- webSocketFactory: WebSocketFactory = platformWebSocketFactory-): MinimalWebSocket => {- const ws = makeWS(url, protocols, webSocketFactory);- onCleanup(() => ws.close());- return ws;-};--/**- * Creates a reactive state signal for the WebSocket's readyState.- *- * @param ws - WebSocket instance- * @returns Reactive accessor for WebSocket state (0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED)- *- * @example- * ```ts- * const ws = createWS('ws://localhost:5000');- * const state = createWSState(ws);- * const states = ["Connecting", "Open", "Closing", "Closed"] as const;- * return <div>{states[state()]}</div>- * ```- */-export const createWSState = (- ws: MinimalWebSocket-): Accessor<0 | 1 | 2 | 3> => {- const [state, setState] = createSignal(ws.readyState as 0 | 1 | 2 | 3);- const _close = ws.close.bind(ws);- ws.addEventListener('open', () => setState(1));- ws.close = (...args) => {- setState(2);- _close(...args);- };- ws.addEventListener('close', () => setState(3));- return state;-};--export type WSReconnectOptions = {- delay?: number;- retries?: number;-};--export type ReconnectingWebSocket = MinimalWebSocket & {- reconnect: () => void;- send: MinimalWebSocket['send'] & { before?: () => void };-};--/**- * Creates a WebSocket with automatic reconnection capabilities.- *- * @param url - WebSocket URL- * @param protocols - Optional protocols- * @param options - Reconnection options- * @param webSocketFactory - Factory function to create WebSocket instances- * @returns Reconnecting WebSocket instance- *- * @example- * ```ts- * const ws = makeReconnectingWS("ws://localhost:5000", undefined, {- * delay: 1000,- * retries: 5- * }, platformWebSocketFactory);- * ```- */-export const makeReconnectingWS = (- url: string,- protocols?: string | string[],- options: WSReconnectOptions = {},- webSocketFactory: WebSocketFactory = platformWebSocketFactory-): ReconnectingWebSocket => {- const { delay = 1000, retries = Infinity } = options;- let ws: MinimalWebSocket;- let retriesLeft = retries;- let timeoutId: ReturnType<typeof setTimeout>;- const sendQueue: WSMessage[] = [];-- const connect = (): void => {- ws = webSocketFactory(url, protocols);- const _send = ws.send.bind(ws);-- ws.send = (msg: WSMessage) => {- if (ws.readyState === 1) {- _send(msg);- } else {- sendQueue.push(msg);- }- };-- ws.addEventListener('open', () => {- retriesLeft = retries;- while (sendQueue.length) {- _send(sendQueue.shift()!);- }- });-- ws.addEventListener('close', (e: CloseEvent) => {- if (retriesLeft > 0 && !e.wasClean) {- retriesLeft--;- timeoutId = setTimeout(connect, delay);- }- });-- ws.addEventListener('error', () => {- if (retriesLeft > 0) {- retriesLeft--;- timeoutId = setTimeout(connect, delay);- }- });- };-- const reconnect = (): void => {- clearTimeout(timeoutId);- retriesLeft = retries;- ws?.close();- connect();- };-- connect();-- // Create proxy to forward all WebSocket properties and methods- const reconnectingWS = new Proxy({} as ReconnectingWebSocket, {- get(target, prop, receiver) {- if (prop === 'reconnect') {- return reconnect;- }- if (prop === 'send') {- const baseSend = (...args: Parameters<MinimalWebSocket['send']>) => {- const typedSend = baseSend as typeof baseSend & {- before?: () => void;- };- if (typedSend.before) typedSend.before();- return ws.send(...args);- };- const typedSend = baseSend as typeof baseSend & { before?: () => void };- typedSend.before = undefined;- return typedSend;- }- if (prop in ws) {- const value = (ws as any)[prop];- return typeof value === 'function' ? value.bind(ws) : value;- }- return Reflect.get(target, prop, receiver);- },- set(target, prop, value) {- if (prop in ws) {- (ws as any)[prop] = value;- return true;- }- return Reflect.set(target, prop, value);- },- });-- return reconnectingWS;-};--/**- * Creates a reconnecting WebSocket that automatically closes on cleanup.- *- * @param url - WebSocket URL- * @param protocols - Optional protocols- * @param options - Reconnection options- * @param webSocketFactory - Factory function to create WebSocket instances- * @returns Reconnecting WebSocket that closes on cleanup- *- * @example- * ```ts- * const ws = createReconnectingWS("ws://localhost:5000", undefined, {- * delay: 1000,- * retries: 5- * });- * ```- */-export const createReconnectingWS = (- url: string,- protocols?: string | string[],- options: WSReconnectOptions = {},- webSocketFactory: WebSocketFactory = platformWebSocketFactory-): ReconnectingWebSocket => {- const ws = makeReconnectingWS(url, protocols, options, webSocketFactory);- onCleanup(() => ws.close());- return ws;-};--export type WSHeartbeatOptions = {- message?: WSMessage;- interval?: number;- wait?: number;-};--/**- * Adds heartbeat functionality to a reconnecting WebSocket.- * Sends periodic ping messages and reconnects if no pong is received.- *- * @param ws - Reconnecting WebSocket instance- * @param options - Heartbeat configuration- * @returns The same WebSocket instance with heartbeat functionality- *- * @example- * ```ts- * const ws = makeReconnectingWS("ws://localhost:5000");- * makeHeartbeatWS(ws, {- * message: "ping",- * interval: 30000,- * wait: 10000- * });- * ```- */-export const makeHeartbeatWS = (- ws: ReconnectingWebSocket,- options: WSHeartbeatOptions = {}-): ReconnectingWebSocket => {- const { message = 'ping', interval = 30000, wait = 10000 } = options;-- let heartbeatInterval: ReturnType<typeof setInterval>;- let pongTimeout: ReturnType<typeof setTimeout>;- let waitingForPong = false;-- const sendHeartbeat = (): void => {- if (ws.readyState === 1 && !waitingForPong) {- ws.send(message);- waitingForPong = true;- pongTimeout = setTimeout(() => {- waitingForPong = false;- ws.reconnect();- }, wait);- }- };-- const resetHeartbeat = (): void => {- clearInterval(heartbeatInterval);- clearTimeout(pongTimeout);- waitingForPong = false;- if (ws.readyState === 1) {- heartbeatInterval = setInterval(sendHeartbeat, interval);- }- };-- ws.send.before = () => {- if (waitingForPong) {- clearTimeout(pongTimeout);- waitingForPong = false;- }- };-- ws.addEventListener('open', resetHeartbeat);- ws.addEventListener('close', () => {- clearInterval(heartbeatInterval);- clearTimeout(pongTimeout);- waitingForPong = false;- });-- ws.addEventListener('message', () => {- if (waitingForPong) {- clearTimeout(pongTimeout);- waitingForPong = false;- }- });-- return ws;-};diff --git a/js/app/packages/websocket/core/backoff/backoff.ts b/js/app/packages/websocket/core/backoff/backoff.tsnew file mode 100644index 0000000000..eeadcf3e8c--- /dev/null+++ b/js/app/packages/websocket/core/backoff/backoff.ts@@ -0,0 +1,26 @@+/**+ * A Backoff produces a series of numbers that are used to determine+ * the delay between connection-retries. Values are expected to be in milliseconds.+ */+export interface Backoff {+ /**+ * The number of retries. Starts at 0, increases by 1 for each call to next(). Resets to 0 when reset() is called.+ */+ readonly retries: number;++ /**+ * Current number in the series.+ */+ readonly current: number;++ /**+ * Advances the series to the next number and returns it.+ * @return the next number in the series+ */+ next(): number;++ /**+ * Resets the series to its initial state.+ */+ reset(): void;+}diff --git a/js/app/packages/websocket/core/backoff/constant-backoff.ts b/js/app/packages/websocket/core/backoff/constant-backoff.tsnew file mode 100644index 0000000000..309c1163d5--- /dev/null+++ b/js/app/packages/websocket/core/backoff/constant-backoff.ts@@ -0,0 +1,38 @@+import type { Backoff } from './backoff';++/**+ * ConstantBackoff always returns the same backoff-time.+ */+export class ConstantBackoff implements Backoff {+ private readonly backoff: number;+ private _retries: number = 0;++ /**+ * Creates a new ConstantBackoff.+ * @param backoff the backoff-time to return+ */+ constructor(backoff: number) {+ if (!Number.isInteger(backoff) || backoff < 0) {+ throw new Error('Backoff must be a positive integer');+ }++ this.backoff = backoff;+ }++ get retries(): number {+ return this._retries;+ }++ get current(): number {+ return this.backoff;+ }++ next(): number {+ this._retries++;+ return this.backoff;+ }++ reset(): void {+ this._retries = 0;+ }+}diff --git a/js/app/packages/websocket/core/backoff/exponential-backoff.ts b/js/app/packages/websocket/core/backoff/exponential-backoff.tsnew file mode 100644index 0000000000..0b3b513cca--- /dev/null+++ b/js/app/packages/websocket/core/backoff/exponential-backoff.ts@@ -0,0 +1,78 @@+import type { Backoff } from './backoff';++/**+ * ExponentialBackoff increases the backoff-time exponentially.+ * An optional maximum can be provided as an upper bound to the+ * exponent and thus to the returned backoff.+ *+ * The series can be described as ('i' is the current step/retry):+ * backoff = base * 2^i | without bound+ * backoff = base * 2^min(i, expMax) | with bound+ *+ * Example:+ *+ * 1) Without bound:+ * base = 1000, expMax = undefined+ * backoff = 1000 * 2^0 = 1000 // first retry+ * backoff = 1000 * 2^1 = 2000 // second retry+ * backoff = 1000 * 2^2 = 4000 // ...doubles with every retry+ * backoff = 1000 * 2^3 = 8000+ * backoff = 1000 * 2^4 = 16000+ * ... // and so on+ *+ * 2) With bound:+ * base = 1000, expMax = 3+ * backoff = 1000 * 2^0 = 1000 // first retry+ * backoff = 1000 * 2^1 = 2000 // second retry+ * backoff = 1000 * 2^2 = 4000 // third retry+ * backoff = 1000 * 2^3 = 8000 // maximum reached, don't increase further+ * backoff = 1000 * 2^3 = 8000+ * backoff = 1000 * 2^3 = 8000+ * ... // and so on+ */+export class ExponentialBackoff implements Backoff {+ private readonly base: number;+ private readonly expMax?: number;+ private i: number;+ private _retries: number = 0;++ /**+ * Creates a new ExponentialBackoff.+ * @param base the base of the exponentiation+ * @param expMax the maximum exponent, no bound if undefined+ */+ constructor(base: number, expMax?: number) {+ if (!Number.isInteger(base) || base < 0) {+ throw new Error('Base must be a positive integer or zero');+ }+ if (expMax !== undefined && (!Number.isInteger(expMax) || expMax < 0)) {+ throw new Error('ExpMax must be a undefined, a positive integer or zero');+ }++ this.base = base;+ this.expMax = expMax;+ this.i = 0;+ }++ get retries() {+ return this._retries;+ }++ get current(): number {+ return this.base * Math.pow(2, this.i);+ }++ next(): number {+ this._retries++;+ this.i =+ this.expMax === undefined+ ? this.i + 1+ : Math.min(this.i + 1, this.expMax);+ return this.current;+ }++ reset(): void {+ this._retries = 0;+ this.i = 0;+ }+}diff --git a/js/app/packages/websocket/core/backoff/linear-backoff.ts b/js/app/packages/websocket/core/backoff/linear-backoff.tsnew file mode 100644index 0000000000..0c3805b1dd--- /dev/null+++ b/js/app/packages/websocket/core/backoff/linear-backoff.ts@@ -0,0 +1,88 @@+import type { Backoff } from './backoff';++/**+ * LinearBackoff returns a backoff-time that is incremented by a fixed amount+ * with every step/retry. An optional maximum can be provided as an upper bound+ * to the returned backoff.+ *+ * The series can be described as ('i' is the current step/retry):+ * backoff = initial + increment * i | without bound+ * backoff = initial + increment * min(i, max) | with bound+ *+ * Example:+ *+ * 1) Without bound:+ * initial = 1000, increment = 1000+ * backoff = 1000 + 1000 * 0 = 1000 // first retry+ * backoff = 1000 + 1000 * 1 = 2000 // second retry+ * backoff = 1000 + 1000 * 2 = 3000 // ...increases by 'increment' with every retry+ * backoff = 1000 + 1000 * 3 = 4000+ * backoff = 1000 + 1000 * 4 = 5000+ * ... // and so on+ *+ * 2) With bound:+ * initial = 1000, increment = 1000, max = 5000+ * backoff = 1000 + 1000 * 0 = 1000 // first retry+ * backoff = 1000 + 1000 * 1 = 2000 // second retry+ * backoff = 1000 + 1000 * 2 = 3000 // third retry+ * backoff = 1000 + 1000 * 3 = 4000 // fourth retry+ * backoff = 1000 + 1000 * 4 = 5000 // maximum reached, don't increase further+ * backoff = 1000 + 1000 * 4 = 5000+ * backoff = 1000 + 1000 * 4 = 5000+ * ... // and so on+ */+export class LinearBackoff implements Backoff {+ private readonly initial: number;+ private readonly increment: number;+ private readonly max?: number;+ private i: number = 0;+ private _retries: number = 0;++ /**+ * Creates a new LinearBackoff.+ * @param initial the initial backoff-time in milliseconds+ * @param increment the amount to increment the backoff-time with every step (in milliseconds)+ * @param max the maximum backoff-time (in milliseconds), no bound if undefined+ */+ constructor(initial: number, increment: number, max?: number) {+ if (initial < 0) {+ throw new Error('Initial must be a positive number or zero');+ }+ if (increment < 0) {+ throw new Error('Increment must be a positive number or zero');+ }+ if (max !== undefined && max < 0) {+ throw new Error('Max must be undefined, a positive number or zero');+ }+ if (max !== undefined && max < initial) {+ throw new Error(+ 'Max must be undefined or greater than or equal to initial'+ );+ }++ this.initial = initial;+ this.increment = increment;+ this.max = max;+ }++ get retries() {+ return this._retries;+ }++ get current(): number {+ return this.max === undefined+ ? this.initial + this.increment * this.i+ : Math.min(this.initial + this.increment * this.i, this.max);+ }++ next(): number {+ this._retries++;+ this.i++;+ return this.current;+ }++ reset(): void {+ this._retries = 0;+ this.i = 0;+ }+}diff --git a/js/app/packages/websocket/core/queue/array-queue.ts b/js/app/packages/websocket/core/queue/array-queue.tsnew file mode 100644index 0000000000..d253323f57--- /dev/null+++ b/js/app/packages/websocket/core/queue/array-queue.ts@@ -0,0 +1,41 @@+import type { Queue } from './queue';++/**+ * An array queue is a queue that has an unbounded capacity. Reading from an array queue+ * will return the oldest element and effectively remove it from the queue.+ */+export class ArrayQueue<E> implements Queue<E> {+ private readonly elements: E[];++ constructor() {+ this.elements = [];+ }++ add(element: E): void {+ this.elements.push(element);+ }++ clear() {+ this.elements.length = 0;+ }++ forEach(fn: (element: E) => unknown) {+ this.elements.forEach(fn);+ }++ length(): number {+ return this.elements.length;+ }++ isEmpty(): boolean {+ return this.elements.length === 0;+ }++ peek(): E | undefined {+ return this.elements[0];+ }++ read(): E | undefined {+ return this.elements.shift();+ }+}diff --git a/js/app/packages/websocket/core/queue/queue.ts b/js/app/packages/websocket/core/queue/queue.tsnew file mode 100644index 0000000000..0edcb65ae2--- /dev/null+++ b/js/app/packages/websocket/core/queue/queue.ts@@ -0,0 +1,46 @@+/**+ * A queue holds elements until they are read. The order in which elements are+ * read is determined by the implementation of the queue.+ */+export interface Queue<E> {+ /**+ * Adds an element to the queue.+ * @param element the element to add+ */+ add(element: E): void;++ /**+ * Clears the queue, removing all elements.+ */+ clear(): void;++ /**+ * Calls the given function for each element in the queue.+ * @param fn the function to call+ */+ forEach(fn: (element: E) => unknown): void;++ /**+ * Number of elements in the queue.+ * @return the number of elements in the queue+ */+ length(): number;++ /**+ * Whether the queue is empty.+ * @return true if the queue is empty, false otherwise+ */+ isEmpty(): boolean;++ /**+ * Returns the next element in the queue without removing it.+ * @return the next element in the queue, or undefined if the queue is empty+ */+ peek(): E | undefined;++ /**+ * Removes and returns the next element in the queue.+ * @return the next element in the queue, or undefined if the queue is empty+ */+ read(): E | undefined;+}diff --git a/js/app/packages/websocket/core/queue/ring-queue.ts b/js/app/packages/websocket/core/queue/ring-queue.tsnew file mode 100644index 0000000000..7f79629ecb--- /dev/null+++ b/js/app/packages/websocket/core/queue/ring-queue.ts@@ -0,0 +1,69 @@+import type { Queue } from './queue';++/**+ * A ring queue is a queue that has a fixed capacity. When the queue is full, the oldest element is+ * removed to make room for the new element. Reading from a ring queue will return the oldest+ * element and effectively remove it from the queue.+ */+export class RingQueue<E> implements Queue<E> {+ private readonly elements: E[];+ private head: number; // index of the next position to write to+ private tail: number; // index of the next position to read from++ constructor(capacity: number) {+ if (!Number.isInteger(capacity) || capacity <= 0) {+ throw new Error('Capacity must be a positive integer');+ }++ this.elements = new Array<E>(capacity + 1); // +1 to distinguish between full and empty+ this.head = 0;+ this.tail = 0;+ }++ add(element: E): void {+ this.elements[this.head] = element;+ this.head = (this.head + 1) % this.elements.length;+ if (this.head === this.tail) {+ this.tail = (this.tail + 1) % this.elements.length;+ }+ }++ clear() {+ this.head = 0;+ this.tail = 0;+ }++ forEach(fn: (element: E) => unknown) {+ for (+ let i = this.tail;+ i !== this.head;+ i = (i + 1) % this.elements.length+ ) {+ fn(this.elements[i]);+ }+ }++ length(): number {+ return this.tail === this.head+ ? 0+ : this.tail < this.head+ ? this.head - this.tail+ : this.elements.length - this.tail + this.head;+ }++ isEmpty(): boolean {+ return this.head === this.tail;+ }++ peek(): E | undefined {+ return this.isEmpty() ? undefined : this.elements[this.tail];+ }++ read(): E | undefined {+ const e = this.peek();+ if (e !== undefined) {+ this.tail = (this.tail + 1) % this.elements.length;+ }+ return e;+ }+}diff --git a/js/app/packages/websocket/core/serializers/bebop-serializer.ts b/js/app/packages/websocket/core/serializers/bebop-serializer.tsnew file mode 100644index 0000000000..caf7c946bd--- /dev/null+++ b/js/app/packages/websocket/core/serializers/bebop-serializer.ts@@ -0,0 +1,30 @@+import type { WebsocketSerializer } from '../websocket-serializer';++type Encoder<I, O> = { encode(data: I): O };+type Decoder<I, O> = { decode(data: I): O };++export class BebopSerializer<Send, Receive>+ implements WebsocketSerializer<Send, Receive>+{+ private readonly encoder: Encoder<Send, Uint8Array>;+ private readonly decoder: Decoder<Uint8Array, Receive>;++ constructor(+ encoder: Encoder<Send, Uint8Array>,+ decoder: Decoder<Uint8Array, Receive>+ ) {+ this.encoder = encoder;+ this.decoder = decoder;+ }++ serialize(data: Send): Uint8Array {+ return this.encoder.encode(data);+ }+ deserialize(data: ArrayBuffer): Receive {+ return this.decoder.decode(new Uint8Array(data));+ }++ get binaryType(): BinaryType {+ return 'arraybuffer';+ }+}diff --git a/js/app/packages/websocket/core/serializers/json-serializer.ts b/js/app/packages/websocket/core/serializers/json-serializer.tsnew file mode 100644index 0000000000..eedd0a56b6--- /dev/null+++ b/js/app/packages/websocket/core/serializers/json-serializer.ts@@ -0,0 +1,12 @@+import type { WebsocketSerializer } from '../websocket-serializer';++export class JsonSerializer<Send, Receive>+ implements WebsocketSerializer<Send, Receive>+{+ serialize(data: Send): string {+ return JSON.stringify(data);+ }+ deserialize(data: string): Receive {+ return JSON.parse(data);+ }+}diff --git a/js/app/packages/websocket/core/websocket-buffer.ts b/js/app/packages/websocket/core/websocket-buffer.tsnew file mode 100644index 0000000000..c9121211a3--- /dev/null+++ b/js/app/packages/websocket/core/websocket-buffer.ts@@ -0,0 +1,18 @@+import type { WebsocketData } from './websocket-serializer';++/**+ * A WebsocketBuffer is used to store messages temporarily until they can be sent.+ */+export interface WebsocketBuffer<E = WebsocketData> {+ /**+ * Adds an element to the buffer.+ * @param element the element to add+ */+ add(element: E): void;++ /**+ * Reads an element from the buffer.+ * @return an element from the buffer or undefined if the buffer is empty+ */+ read(): E | undefined;+}diff --git a/js/app/packages/websocket/core/websocket-builder.ts b/js/app/packages/websocket/core/websocket-builder.tsnew file mode 100644index 0000000000..609f2c830c--- /dev/null+++ b/js/app/packages/websocket/core/websocket-builder.ts@@ -0,0 +1,424 @@+import type { WebSocketFactory } from '../platform/minimal-websocket';+import type { Backoff } from './backoff/backoff';+import { Websocket } from './websocket';+import type { WebsocketBuffer } from './websocket-buffer';+import {+ WebsocketEvent,+ type WebsocketEventListener,+ type WebsocketEventListenerOptions,+} from './websocket-event';+import type { WebsocketHeartbeatOptions } from './websocket-heartbeat-options';+import type { WebsocketOptions } from './websocket-options';+import type {+ WebsocketData,+ WebsocketSerializer,+} from './websocket-serializer';+import type { UrlResolver } from './websocket-url-resolver';++/**+ * Builder for websockets.+ */+export class WebsocketBuilder<Send = WebsocketData, Receive = WebsocketData> {+ private readonly _urlResolver: UrlResolver;++ private _protocols?: string | string[];+ private _options?: WebsocketOptions<Send, Receive>;++ /**+ * Creates a new WebsocketBuilder.+ *+ * @param url the url to connect to+ */+ constructor(resolver: UrlResolver) {+ this._urlResolver = resolver;+ }++ /**+ * Getter for the url.+ *+ * @returns the url+ */+ get url(): UrlResolver {+ return this._urlResolver;+ }++ /**+ * Adds protocols to the websocket. Subsequent calls to this method will override the previously set protocols.+ *+ * @param protocols the protocols to add+ */+ public withProtocols(+ protocols: string | string[] | undefined+ ): WebsocketBuilder<Send, Receive> {+ this._protocols = protocols;+ return this;+ }++ /**+ * Adds a factory to the websocket. Subsequent calls to this method will override the previously set factory.+ *+ * @param factory the factory to add+ * */+ public withFactory(+ factory: WebSocketFactory+ ): WebsocketBuilder<Send, Receive> {+ this._options = {+ ...this._options,+ factory,+ };+ return this;+ }++ /**+ * Getter for the protocols.+ *+ * @returns the protocols, undefined if no protocols have been set+ */+ get protocols(): string | string[] | undefined {+ return this._protocols;+ }++ /**+ * Sets the maximum number of retries before giving up. No limit if undefined.+ *+ * @param maxRetries the maximum number of retries before giving up+ */+ public withMaxRetries(+ maxRetries: number | undefined+ ): WebsocketBuilder<Send, Receive> {+ this._options = {+ ...this._options,+ retry: { ...this._options?.retry, maxRetries },+ };+ return this;+ }++ /**+ * Getter for the maximum number of retries before giving up.+ *+ * @returns the maximum number of retries before giving up, undefined if no maximum has been set+ */+ get maxRetries(): number | undefined {+ return this._options?.retry?.maxRetries;+ }++ /**+ * Sets wether to reconnect immediately after a connection has been lost, ignoring the backoff strategy for the first retry.+ *+ * @param instantReconnect wether to reconnect immediately after a connection has been lost+ */+ public withInstantReconnect(+ instantReconnect: boolean | undefined+ ): WebsocketBuilder<Send, Receive> {+ this._options = {+ ...this._options,+ retry: { ...this._options?.retry, instantReconnect },+ };+ return this;+ }++ /**+ * Getter for wether to reconnect immediately after a connection has been lost, ignoring the backoff strategy for the first retry.+ *+ * @returns wether to reconnect immediately after a connection has been lost, undefined if no value has been set+ */+ get instantReconnect(): boolean | undefined {+ return this._options?.retry?.instantReconnect;+ }++ /**+ * Adds a backoff to the websocket. Subsequent calls to this method will override the previously set backoff.+ *+ * @param backoff the backoff to add+ */+ public withBackoff(+ backoff: Backoff | undefined+ ): WebsocketBuilder<Send, Receive> {+ this._options = {+ ...this._options,+ retry: { ...this._options?.retry, backoff },+ };+ return this;+ }++ /**+ * Getter for the backoff.+ *+ * @returns the backoff, undefined if no backoff has been set+ */+ get backoff(): Backoff | undefined {+ return this._options?.retry?.backoff;+ }++ /**+ * Adds a buffer to the websocket. Subsequent calls to this method will override the previously set buffer.+ *+ * @param buffer the buffer to add+ */+ public withBuffer(+ buffer: WebsocketBuffer<Send> | undefined+ ): WebsocketBuilder<Send, Receive> {+ this._options = { ...this._options, buffer };+ return this;+ }++ /**+ * Adds a heartbeat to the websocket. Subsequent calls to this method will override the previously set heartbeat.+ *+ * @param options the heartbeat to add+ */+ public withHeartbeat(+ options: WebsocketHeartbeatOptions+ ): WebsocketBuilder<Send, Receive> {+ this._options = { ...this._options, heartbeat: options };+ return this;+ }++ /**+ * Adds a serializer to the websocket. Subsequent calls to this method will override the previously set serializer.+ *+ * @param serializer the serializer to add+ */+ public withSerializer<NewSend, NewReceive>(+ serializer: WebsocketSerializer<NewSend, NewReceive>+ ): WebsocketBuilder<NewSend, NewReceive> {+ const newBuilder = new WebsocketBuilder<NewSend, NewReceive>(+ this._urlResolver+ );+ newBuilder._protocols = this._protocols;+ newBuilder._options = {+ retry: this._options?.retry,+ heartbeat: this._options?.heartbeat,+ listeners: this._options?.listeners,+ serializer,+ buffer: this._options?.buffer,+ } as WebsocketOptions<NewSend, NewReceive>;++ if (serializer.binaryType !== undefined) {+ return newBuilder.withBinaryType(serializer.binaryType);+ }++ return newBuilder;+ }++ /**+ * Getter for the buffer.+ *+ * @returns the buffer, undefined if no buffer has been set+ */+ get buffer(): WebsocketBuffer<Send> | undefined {+ return this._options?.buffer;+ }++ /**+ * Sets the binaryType of the websocket.+ *+ * @param binaryType to set.+ * @returns the builder itself.+ */+ public withBinaryType(+ binaryType: BinaryType+ ): WebsocketBuilder<Send, Receive> {+ this._options = {+ ...this._options,+ binaryType,+ };+ return this;+ }++ /**+ * Adds an 'open' event listener to the websocket. Subsequent calls to this method will add additional listeners that will be+ * called in the order they were added.+ *+ * @param listener the listener to add+ * @param options the listener options+ */+ public onOpen(+ listener: WebsocketEventListener<WebsocketEvent.Open, Send, Receive>,+ options?: WebsocketEventListenerOptions+ ): WebsocketBuilder<Send, Receive> {+ this.addListener(WebsocketEvent.Open, listener, options);+ return this;+ }++ /**+ * Adds an 'close' event listener to the websocket. Subsequent calls to this method will add additional listeners that will be+ * called in the order they were added.+ *+ * @param listener the listener to add+ * @param options the listener options+ */+ public onClose(+ listener: WebsocketEventListener<WebsocketEvent.Close, Send, Receive>,+ options?: WebsocketEventListenerOptions+ ): WebsocketBuilder<Send, Receive> {+ this.addListener(WebsocketEvent.Close, listener, options);+ return this;+ }++ /**+ * Adds an 'error' event listener to the websocket. Subsequent calls to this method will add additional listeners that will be+ * called in the order they were added.+ *+ * @param listener the listener to add+ * @param options the listener options+ */+ public onError(+ listener: WebsocketEventListener<WebsocketEvent.Error, Send, Receive>,+ options?: WebsocketEventListenerOptions+ ): WebsocketBuilder<Send, Receive> {+ this.addListener(WebsocketEvent.Error, listener, options);+ return this;+ }++ /**+ * Adds an 'message' event listener to the websocket. Subsequent calls to this method will add additional listeners that will be+ * called in the order they were added.+ *+ * @param listener the listener to add+ * @param options the listener options+ */+ public onMessage(+ listener: WebsocketEventListener<WebsocketEvent.Message, Send, Receive>,+ options?: WebsocketEventListenerOptions+ ): WebsocketBuilder<Send, Receive> {+ this.addListener(WebsocketEvent.Message, listener, options);+ return this;+ }++ /**+ * Adds an 'retry' event listener to the websocket. Subsequent calls to this method will add additional listeners that will be+ * called in the order they were added.+ *+ * @param listener the listener to add+ * @param options the listener options+ */+ public onRetry(+ listener: WebsocketEventListener<WebsocketEvent.retry, Send, Receive>,+ options?: WebsocketEventListenerOptions+ ): WebsocketBuilder<Send, Receive> {+ this.addListener(WebsocketEvent.retry, listener, options);+ return this;+ }++ /**+ * Adds an 'reconnect' event listener to the websocket. Subsequent calls to this method will add additional listeners that will be+ * called in the order they were added.+ *+ * @param listener the listener to add+ * @param options the listener options+ */+ public onReconnect(+ listener: WebsocketEventListener<WebsocketEvent.Reconnect, Send, Receive>,+ options?: WebsocketEventListenerOptions+ ): WebsocketBuilder<Send, Receive> {+ this.addListener(WebsocketEvent.Reconnect, listener, options);+ return this;+ }++ /**+ * Adds an 'heartbeatSent' event listener to the websocket. Subsequent calls to this method will add additional listeners that will be+ * called in the order they were added.+ *+ * @param listener the listener to add+ * @param options the listener options+ */+ public onHeartbeatSent(+ listener: WebsocketEventListener<+ WebsocketEvent.HeartbeatSent,+ Send,+ Receive+ >,+ options?: WebsocketEventListenerOptions+ ): WebsocketBuilder<Send, Receive> {+ this.addListener(WebsocketEvent.HeartbeatSent, listener, options);+ return this;+ }++ /**+ * Adds an 'heartbeatReceived' event listener to the websocket. Subsequent calls to this method will add additional listeners that will be+ * called in the order they were added.+ *+ * @param listener the listener to add+ * @param options the listener options+ */+ public onHeartbeatReceived(+ listener: WebsocketEventListener<+ WebsocketEvent.HeartbeatSent,+ Send,+ Receive+ >,+ options?: WebsocketEventListenerOptions+ ): WebsocketBuilder<Send, Receive> {+ this.addListener(WebsocketEvent.HeartbeatReceived, listener, options);+ return this;+ }++ /**+ * Adds an 'heartbeatMissed' event listener to the websocket. Subsequent calls to this method will add additional listeners that will be+ * called in the order they were added.+ *+ * @param listener the listener to add+ * @param options the listener options+ */+ public onHeartbeatMissed(+ listener: WebsocketEventListener<+ WebsocketEvent.HeartbeatMissed,+ Send,+ Receive+ >,+ options?: WebsocketEventListenerOptions+ ): WebsocketBuilder<Send, Receive> {+ this.addListener(WebsocketEvent.HeartbeatMissed, listener, options);+ return this;+ }++ /**+ * Builds the websocket.+ *+ * @return a new websocket, with the set options+ */+ public build(): Websocket<Send, Receive> {+ const ws = new Websocket<Send, Receive>(+ this._urlResolver,+ this._protocols,+ this._options as WebsocketOptions<Send, Receive>+ ); // instantiate the websocket with the set options++ return ws;+ }++ /**+ * Adds an event listener to the options.+ *+ * @param event the event to add the listener to+ * @param listener the listener to add+ * @param options the listener options+ */+ private addListener<K extends WebsocketEvent>(+ event: WebsocketEvent,+ listener: WebsocketEventListener<K, Send, Receive>,+ options?: WebsocketEventListenerOptions+ ): WebsocketBuilder<Send, Receive> {+ this._options = {+ ...this._options,+ listeners: {+ open: this._options?.listeners?.open ?? [],+ close: this._options?.listeners?.close ?? [],+ error: this._options?.listeners?.error ?? [],+ message: this._options?.listeners?.message ?? [],+ retry: this._options?.listeners?.retry ?? [],+ reconnect: this._options?.listeners?.reconnect ?? [],+ heartbeatSent: this._options?.listeners?.heartbeatSent ?? [],+ heartbeatReceived: this._options?.listeners?.heartbeatReceived ?? [],+ heartbeatMissed: this._options?.listeners?.heartbeatMissed ?? [],+ urlResolved: this._options?.listeners?.urlResolved ?? [],+ [event]: [+ ...(this._options?.listeners?.[event] ?? []),+ { listener, options },+ ],+ },+ };+ return this;+ }+}diff --git a/js/app/packages/websocket/core/websocket-connection-state.ts b/js/app/packages/websocket/core/websocket-connection-state.tsnew file mode 100644index 0000000000..6b3ef520c4--- /dev/null+++ b/js/app/packages/websocket/core/websocket-connection-state.ts@@ -0,0 +1,7 @@+export enum WebsocketConnectionState {+ Connecting = 0,+ Open = 1,+ Closing = 2,+ Closed = 3,+ Reconnecting = 4,+}diff --git a/js/app/packages/websocket/core/websocket-event.ts b/js/app/packages/websocket/core/websocket-event.tsnew file mode 100644index 0000000000..d249d443c4--- /dev/null+++ b/js/app/packages/websocket/core/websocket-event.ts@@ -0,0 +1,169 @@+import type { Websocket } from './websocket';+import type { WebsocketData } from './websocket-serializer';++/**+ * Events that can be fired by the websocket.+ */+export enum WebsocketEvent {+ /** Fired when the url for the websocket has been resolved on creation or reconnection*/+ UrlResolved = 'urlResolved',++ /** Fired when the connection is opened. */+ Open = 'open',++ /** Fired when the connection is closed. */+ Close = 'close',++ /** Fired when the connection has been closed because of an error, such as when some data couldn't be sent. */+ Error = 'error',++ /** Fired when a message is received. */+ Message = 'message',++ /** Fired when the websocket tries to reconnect after a connection loss. */+ retry = 'retry',++ /** Fired when the websocket successfully reconnects after a connection loss. */+ Reconnect = 'reconnect',++ /** Fired when a heartbeat is successfully sent. */+ HeartbeatSent = 'heartbeatSent',++ /** Fired when a heartbeat is received. */+ HeartbeatReceived = 'heartbeatReceived',++ /** Fired when a heartbeat is missed. */+ HeartbeatMissed = 'heartbeatMissed',+}++/***+ * Details/properties of a retry-event.+ */+export type RetryEventDetail = {+ /** Number of retries that have been made since the connection was lost. */+ readonly retries: number;++ /** Time (ms) waited since the last connection-retry. */+ readonly backoff: number;++ /** Timestamp of when the connection was lost or undefined if the connection has never been established. */+ readonly lastConnection: Date | undefined;++ /** The url that was used to connect to. */+ readonly url: string;+};++/**+ * Properties of a reconnect-event.+ */+export type ReconnectEventDetail = Omit<RetryEventDetail, 'backoff'>;++/**+ * Properties of a heartbeat-sent-event or a heartbeat-received-event.+ */+export type HeartbeatEventDetail = {+ /** The message that was sent or received. */+ readonly message: string;+ /** The timestamp of when the message was sent or received. */+ readonly timestamp: number;+};++/**+ * Properties of a heartbeat-missed-event.+ */+export type HeartbeatMissedEventDetail = {+ /** number of missed heartbeats */+ readonly missedHeartbeats: number;++ /** whether the websocket will reconnect due to missed heartbeats */+ readonly willReconnect: boolean;+};++export type UrlResolvedEventDetail = {+ readonly url: string;+};++/**+ * Maps websocket events to their corresponding event.+ */+export type WebsocketEventMap<Receive = WebsocketData> = {+ [WebsocketEvent.UrlResolved]: CustomEvent<UrlResolvedEventDetail>;+ [WebsocketEvent.Open]: Event;+ [WebsocketEvent.Close]: CloseEvent;+ [WebsocketEvent.Error]: Event;+ [WebsocketEvent.Message]: MessageEvent<Receive>;+ [WebsocketEvent.retry]: CustomEvent<RetryEventDetail>;+ [WebsocketEvent.Reconnect]: CustomEvent<ReconnectEventDetail>;+ [WebsocketEvent.HeartbeatSent]: CustomEvent<HeartbeatEventDetail>;+ [WebsocketEvent.HeartbeatReceived]: CustomEvent<HeartbeatEventDetail>;+ [WebsocketEvent.HeartbeatMissed]: CustomEvent<HeartbeatMissedEventDetail>;+};++/**+ * Discriminated union of all websocket events+ */+export type WebsocketEventUnion<Receive = WebsocketData> =+ | { type: WebsocketEvent.Open; event: Event }+ | { type: WebsocketEvent.Close; event: CloseEvent }+ | { type: WebsocketEvent.Error; event: Event }+ | { type: WebsocketEvent.Message; event: MessageEvent<Receive> }+ | { type: WebsocketEvent.retry; event: CustomEvent<RetryEventDetail> }+ | { type: WebsocketEvent.Reconnect; event: CustomEvent<ReconnectEventDetail> }+ | {+ type: WebsocketEvent.HeartbeatSent;+ event: CustomEvent<HeartbeatEventDetail>;+ }+ | {+ type: WebsocketEvent.HeartbeatReceived;+ event: CustomEvent<HeartbeatEventDetail>;+ }+ | {+ type: WebsocketEvent.HeartbeatMissed;+ event: CustomEvent<HeartbeatMissedEventDetail>;+ };++/**+ * Listener for websocket events.+ * */+export type WebsocketEventListener<+ K extends WebsocketEvent,+ Send = WebsocketData,+ Receive = WebsocketData,+> = (+ instance: Websocket<Send, Receive>,+ ev: WebsocketEventMap<Receive>[K]+) => unknown;++export type WebsocketEventListenerParams<+ K extends WebsocketEvent,+ Send = WebsocketData,+ Receive = WebsocketData,+> = Parameters<WebsocketEventListener<K, Send, Receive>>;++/**+ * Options for websocket events.+ */+export type WebsocketEventListenerOptions = EventListenerOptions &+ AddEventListenerOptions;++/**+ * Listener for websocket events with options.+ */+export type WebsocketEventListenerWithOptions<+ K extends WebsocketEvent,+ Send = WebsocketData,+ Receive = WebsocketData,+> = {+ readonly listener: WebsocketEventListener<K, Send, Receive>;+ readonly options?: WebsocketEventListenerOptions;+};++/**+ * Maps websocket events to their corresponding event-listeners.+ */+export type WebsocketEventListeners<+ Send = WebsocketData,+ Receive = WebsocketData,+> = {+ [K in WebsocketEvent]: WebsocketEventListenerWithOptions<K, Send, Receive>[];+};diff --git a/js/app/packages/websocket/core/websocket-heartbeat-options.ts b/js/app/packages/websocket/core/websocket-heartbeat-options.tsnew file mode 100644index 0000000000..2c7c177215--- /dev/null+++ b/js/app/packages/websocket/core/websocket-heartbeat-options.ts@@ -0,0 +1,37 @@+/**+ * Options for the websockets heartbeat-strategy.+ */+export interface WebsocketHeartbeatOptions {+ /** The interval in milliseconds between two pings. */+ readonly interval?: number;++ /** The timeout in milliseconds to wait for a pong after a ping. */+ readonly timeout?: number;++ /** The message to send in the ping. */+ readonly pingMessage?: string;++ /** The message to send in the pong. */+ readonly pongMessage?: string;++ /** The maximum number of missed heartbeats before the connection is considered dead. */+ readonly maxMissedHeartbeats?: number;+}++/**+ * Checks if the given options are valid heartbeat options.+ * @param options the options to check+ * @returns true if the options are valid heartbeat options, false otherwise+ */+export function isRequiredHeartbeatOptions(+ options: WebsocketHeartbeatOptions | undefined+): options is Required<WebsocketHeartbeatOptions> {+ return (+ options !== undefined &&+ options.interval !== undefined &&+ options.timeout !== undefined &&+ options.pingMessage !== undefined &&+ options.pongMessage !== undefined &&+ options.maxMissedHeartbeats !== undefined+ );+}diff --git a/js/app/packages/websocket/core/websocket-options.ts b/js/app/packages/websocket/core/websocket-options.tsnew file mode 100644index 0000000000..a3d7c20d72--- /dev/null+++ b/js/app/packages/websocket/core/websocket-options.ts@@ -0,0 +1,51 @@+import type { WebSocketFactory } from '../platform/minimal-websocket';+import type { WebsocketBuffer } from './websocket-buffer';+import type { WebsocketEventListeners } from './websocket-event';+import type { WebsocketHeartbeatOptions } from './websocket-heartbeat-options';+import type { WebsocketConnectionRetryOptions } from './websocket-retry-options';+import type {+ WebsocketData,+ WebsocketSerializer,+} from './websocket-serializer';++/**+ * Options that can be passed to the Websocket constructor.+ */+export interface WebsocketOptions<+ Send = WebsocketData,+ Receive = WebsocketData,+> {+ readonly binaryType?: BinaryType;++ /**+ * The Buffer to use.+ */+ readonly buffer?: WebsocketBuffer<Send>;++ /**+ * The options for the connection-retry-strategy.+ */+ readonly retry?: WebsocketConnectionRetryOptions;++ /**+ * The initial listeners to add to the websocket.+ */+ readonly listeners?: WebsocketEventListeners<Send, Receive>;++ /**+ * The options for the heartbeat-strategy.+ */+ readonly heartbeat?: WebsocketHeartbeatOptions;++ /**+ * The serializer to use.+ * A serializer serializes data send, and deserializes data on message-event.+ */+ readonly serializer?: WebsocketSerializer<Send, Receive>;++ /**+ * The factory to use to create the websocket.+ * Can be browser-native or a custom implementation.+ */+ readonly factory?: WebSocketFactory;+}diff --git a/js/app/packages/websocket/core/websocket-retry-options.ts b/js/app/packages/websocket/core/websocket-retry-options.tsnew file mode 100644index 0000000000..9d5d5c8adf--- /dev/null+++ b/js/app/packages/websocket/core/websocket-retry-options.ts@@ -0,0 +1,22 @@+import type { Backoff } from './backoff/backoff';++/**+ * Options for the websockets retry-strategy.+ */+export interface WebsocketConnectionRetryOptions {+ /**+ * The maximum number of retries before giving up. No limit if undefined.+ */+ readonly maxRetries?: number;++ /**+ * Wether to reconnect immediately after a connection has been lost,+ * ignoring the backoff strategy for the first retry.+ */+ readonly instantReconnect?: boolean;++ /**+ * The backoff strategy to use. This is used to determine the delay between connection-retries.+ */+ readonly backoff?: Backoff;+}diff --git a/js/app/packages/websocket/core/websocket-serializer.ts b/js/app/packages/websocket/core/websocket-serializer.tsnew file mode 100644index 0000000000..1d4f48d974--- /dev/null+++ b/js/app/packages/websocket/core/websocket-serializer.ts@@ -0,0 +1,77 @@+export type WebsocketData = string | ArrayBufferLike | Blob | ArrayBufferView;++/**+ * Websocket message serializer.+ * Serializes data send, and deserializes data on message-event.+ */+export interface WebsocketSerializer<+ Send = WebsocketData,+ Receive = WebsocketData,+> {+ /**+ * Serializes data send.+ * @param data the data to serialize+ * @return the serialized data+ */+ serialize(data: Send): WebsocketData;+ /**+ * Deserializes data on message-event.+ * @param data the data to deserialize+ * @return the deserialized data+ */+ deserialize(data: WebsocketData): Receive;++ binaryType?: BinaryType;+}++/**+ * Type guard to check if this is default websocket data.+ */+export function isDefaultWebsocketData(data: unknown): data is WebsocketData {+ return (+ typeof data === 'string' ||+ data instanceof ArrayBuffer ||+ data instanceof Blob ||+ ArrayBuffer.isView(data)+ );+}++/**+ * Serializes data send, if a serializer is provided.+ * @param data the data to serialize+ * @param serializer the serializer to use+ * @return the serialized data+ */+export function serializeIfNeeded<+ Send = WebsocketData,+ Receive = WebsocketData,+>(+ data: Send,+ serializer: WebsocketSerializer<Send, Receive> | undefined+): WebsocketData {+ if (serializer === undefined) {+ return data as WebsocketData;+ }++ return serializer.serialize(data as Send);+}++/**+ * Deserializes data on message-event, if a serializer is provided.+ * @param data the data to deserialize+ * @param serializer the serializer to use+ * @return the deserialized data+ */+export function deserializeIfNeeded<+ Send = WebsocketData,+ Receive = WebsocketData,+>(+ data: WebsocketData,+ serializer: WebsocketSerializer<Send, Receive> | undefined+): Receive {+ if (serializer === undefined) {+ return data as Receive;+ }++ return serializer.deserialize(data as WebsocketData);+}diff --git a/js/app/packages/websocket/core/websocket-url-resolver.ts b/js/app/packages/websocket/core/websocket-url-resolver.tsnew file mode 100644index 0000000000..1c64812788--- /dev/null+++ b/js/app/packages/websocket/core/websocket-url-resolver.ts@@ -0,0 +1,18 @@+export type UrlResolver = string | (() => string | Promise<string>);++export function isThunk(+ url: UrlResolver+): url is (() => string) | (() => Promise<string>) {+ return typeof url === 'function';+}++export function isString(url: UrlResolver): url is string {+ return typeof url === 'string';+}++export async function resolveUrl(url: UrlResolver): Promise<string> {+ if (isThunk(url)) {+ return await url();+ }+ return url as string;+}diff --git a/js/app/packages/websocket/core/websocket.ts b/js/app/packages/websocket/core/websocket.tsnew file mode 100644index 0000000000..1ab85cf82b--- /dev/null+++ b/js/app/packages/websocket/core/websocket.ts@@ -0,0 +1,761 @@+import { match, P } from 'ts-pattern';+import { browserWebSocketFactory } from '../platform/minimal-websocket';+import type { Backoff } from './backoff/backoff';+import type { WebsocketBuffer } from './websocket-buffer';+import { WebsocketConnectionState } from './websocket-connection-state';+import {+ type HeartbeatEventDetail,+ type HeartbeatMissedEventDetail,+ type ReconnectEventDetail,+ type RetryEventDetail,+ type UrlResolvedEventDetail,+ WebsocketEvent,+ type WebsocketEventListener,+ type WebsocketEventListenerOptions,+ type WebsocketEventListeners,+ type WebsocketEventListenerWithOptions,+ type WebsocketEventMap,+ type WebsocketEventUnion,+} from './websocket-event';+import { isRequiredHeartbeatOptions } from './websocket-heartbeat-options';+import type { WebsocketOptions } from './websocket-options';+import {+ deserializeIfNeeded,+ serializeIfNeeded,+ type WebsocketData,+} from './websocket-serializer';+import {+ isString,+ resolveUrl,+ type UrlResolver,+} from './websocket-url-resolver';++/**+ * A websocket wrapper that can be configured to reconnect automatically and buffer messages when the websocket is not connected.+ */+export class Websocket<Send = WebsocketData, Receive = WebsocketData> {+ private _url: string; // the url to connect to+ private readonly _urlResolver: UrlResolver; // the url resolver to use+ private readonly _protocols?: string | string[]; // the protocols to use+ private _binaryType?: BinaryType = 'blob'; // the binaryType to use++ private _closedByUser: boolean = false; // whether the websocket was closed by the user+ private _lastConnection?: Date; // timestamp of the last connection+ private _underlyingWebsocket: WebSocket; // the underlying websocket, e.g. native browser websocket+ private retryTimeout?: ReturnType<typeof globalThis.setTimeout>; // timeout for the next retry, if any++ private heartbeatInterval?: ReturnType<typeof setInterval> | undefined; // interval for the heartbeat+ private heartbeatTimeout?: ReturnType<typeof setTimeout> | undefined; // timeout for the heartbeat+ private missedHeartbeats: number = 0; // number of missed heartbeats++ connectionState: WebsocketConnectionState =+ WebsocketConnectionState.Connecting;++ private _options: WebsocketOptions<Send, Receive> &+ Required<Pick<WebsocketOptions<Send, Receive>, 'listeners' | 'retry'>>; // options/config for the websocket++ /**+ * Creates a new websocket.+ *+ * @param url to connect to.+ * @param protocols optional protocols to use.+ * @param options optional options to use.+ */+ constructor(+ resolver: UrlResolver,+ protocols?: string | string[],+ options?: WebsocketOptions<Send, Receive>+ ) {+ this._protocols = protocols;++ // make a copy of the options to prevent the user from changing them+ this._options = {+ buffer: options?.buffer,+ retry: {+ maxRetries: options?.retry?.maxRetries,+ instantReconnect: options?.retry?.instantReconnect,+ backoff: options?.retry?.backoff,+ },+ heartbeat: {+ timeout: options?.heartbeat?.timeout,+ interval: options?.heartbeat?.interval,+ pingMessage: options?.heartbeat?.pingMessage,+ pongMessage: options?.heartbeat?.pongMessage,+ maxMissedHeartbeats: options?.heartbeat?.maxMissedHeartbeats,+ },+ listeners: {+ open: [...(options?.listeners?.open ?? [])],+ close: [...(options?.listeners?.close ?? [])],+ error: [...(options?.listeners?.error ?? [])],+ message: [...(options?.listeners?.message ?? [])],+ retry: [...(options?.listeners?.retry ?? [])],+ reconnect: [...(options?.listeners?.reconnect ?? [])],+ heartbeatSent: [...(options?.listeners?.heartbeatSent ?? [])],+ heartbeatReceived: [...(options?.listeners?.heartbeatReceived ?? [])],+ heartbeatMissed: [...(options?.listeners?.heartbeatMissed ?? [])],+ urlResolved: [...(options?.listeners?.urlResolved ?? [])],+ },+ binaryType: options?.binaryType,+ serializer: options?.serializer,+ factory: options?.factory,+ };++ if (options?.binaryType !== undefined) {+ this.binaryType = options.binaryType;+ }++ this._urlResolver = resolver;++ if (isString(resolver)) {+ this._url = resolver;+ }++ this.tryConnect();+ }++ /**+ * Getter for the url.+ *+ * @return the url.+ */+ get url(): string {+ return this._url;+ }++ /**+ * Getter for the protocols.+ *+ * @return the protocols, or undefined if none were provided.+ */+ get protocols(): string | string[] | undefined {+ return this._protocols;+ }++ /**+ * Getter for the buffer.+ *+ * @return the buffer, or undefined if none was provided.+ */+ get buffer(): WebsocketBuffer<Send> | undefined {+ return this._options.buffer;+ }++ /**+ * Getter for the maxRetries.+ *+ * @return the maxRetries, or undefined if none was provided (no limit).+ */+ get maxRetries(): number | undefined {+ return this._options.retry.maxRetries;+ }++ /**+ * Getter for the instantReconnect.+ *+ * @return the instantReconnect, or undefined if none was provided.+ */+ get instantReconnect(): boolean | undefined {+ return this._options.retry.instantReconnect;+ }++ /**+ * Getter for the backoff.+ *+ * @return the backoff, or undefined if none was provided.+ */+ get backoff(): Backoff | undefined {+ return this._options.retry.backoff;+ }++ /**+ * Whether the websocket was closed by the user. A websocket is closed by the user by calling close().+ *+ * @return true if the websocket was closed by the user, false otherwise.+ */+ get closedByUser(): boolean {+ return this._closedByUser;+ }++ /**+ * Getter for the last 'open' event, e.g. the last time the websocket was connected.+ *+ * @return the last 'open' event, or undefined if the websocket was never connected.+ */+ get lastConnection(): Date | undefined {+ return this._lastConnection;+ }++ /**+ * Getter for the underlying websocket. This can be used to access the browser's native websocket directly.+ *+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket+ * @return the underlying websocket.+ */+ get underlyingWebsocket(): WebSocket {+ return this._underlyingWebsocket;+ }++ /**+ * Getter for the readyState of the underlying websocket.+ *+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState+ * @return the readyState of the underlying websocket.+ */+ get readyState(): number {+ return this._underlyingWebsocket.readyState;+ }++ /**+ * Getter for the bufferedAmount of the underlying websocket.+ *+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/bufferedAmount+ * @return the bufferedAmount of the underlying websocket.+ */+ get bufferedAmount(): number {+ return this._underlyingWebsocket.bufferedAmount;+ }++ /**+ * Getter for the extensions of the underlying websocket.+ *+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/extensions+ * @return the extensions of the underlying websocket.+ */+ get extensions(): string {+ return this._underlyingWebsocket.extensions;+ }++ /**+ * Getter for the binaryType of the underlying websocket.+ *+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/binaryType+ * @return the binaryType of the underlying websocket.+ */+ get binaryType(): BinaryType {+ return this._binaryType ?? this._underlyingWebsocket.binaryType;+ }++ /**+ * Setter for the binaryType of the underlying websocket.+ *+ * @param value to set, 'blob' or 'arraybuffer'.+ */+ set binaryType(value: BinaryType) {+ if (this._underlyingWebsocket) {+ this._underlyingWebsocket.binaryType = value;+ }++ this._binaryType = value;+ }++ /**+ * Sends data over the websocket.+ *+ * If the websocket is not connected and a buffer was provided on creation, the data will be added to the buffer.+ * If no buffer was provided or the websocket was closed by the user, the data will be dropped.+ *+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send+ * @param data to send.+ */+ public send(rawData: Send): void {+ if (this.closedByUser) return; // no-op if closed by user++ let data = serializeIfNeeded(rawData, this._options.serializer);++ if (+ this._underlyingWebsocket &&+ this._underlyingWebsocket.readyState === this._underlyingWebsocket.OPEN+ ) {+ this._underlyingWebsocket.send(data); // websocket is connected, send data+ } else if (this.buffer !== undefined) {+ this.buffer.add(rawData); // websocket is not connected, add data to buffer+ }+ }++ /**+ * Close the websocket. No connection-retry will be attempted after this.+ *+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close+ * @param code optional close code.+ * @param reason optional close reason.+ */+ public close(code?: number, reason?: string): void {+ this.cancelScheduledConnectionRetry(); // cancel any scheduled retries+ this._closedByUser = true; // mark websocket as closed by user+ this._underlyingWebsocket.close(code, reason); // close underlying websocket with provided code and reason+ this.stopHeartbeat();+ }++ /**+ * Adds an event listener for the given event-type.+ *+ * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener+ * @param type of the event to add the listener for.+ * @param listener to add.+ * @param options to use when adding the listener.+ */+ public addEventListener<K extends WebsocketEvent>(+ type: K,+ listener: WebsocketEventListener<K, Send, Receive>,+ options?: WebsocketEventListenerOptions+ ): void {+ this._options.listeners[type].push({ listener, options }); // add listener to list of listeners+ }++ /**+ * Removes one or more event listener for the given event-type that match the given listener and options.+ *+ * @param type of the event to remove the listener for.+ * @param listener to remove.+ * @param options that were used when the listener was added.+ */+ public removeEventListener<K extends WebsocketEvent>(+ type: K,+ listener: WebsocketEventListener<K, Send, Receive>,+ options?: WebsocketEventListenerOptions+ ): void {+ const isListenerNotToBeRemoved = (+ l: WebsocketEventListenerWithOptions<K, Send, Receive>+ ) => l.listener !== listener || l.options !== options;++ (this._options.listeners[type] as WebsocketEventListenerWithOptions<+ K,+ Send,+ Receive+ >[]) = this._options.listeners[type].filter(isListenerNotToBeRemoved); // only keep listeners that are not to be removed+ }++ /**+ * Creates a new browser-native websocket and connects it to the given URL with the given protocols+ * and adds all event listeners to the browser-native websocket.+ *+ * @return the created browser-native websocket which is also stored in the '_underlyingWebsocket' property.+ */+ private async tryConnect(): Promise<WebSocket> {+ const url = await resolveUrl(this._urlResolver);+ this._url = url;+ const event = new CustomEvent<UrlResolvedEventDetail>(+ WebsocketEvent.UrlResolved,+ {+ detail: {+ url: this._url,+ },+ }+ );+ this.dispatchEvent(WebsocketEvent.UrlResolved, event);+ const factory = this._options.factory ?? browserWebSocketFactory;+ const newSocket = factory(this.url, this.protocols); // create new browser-native websocket and add all event listeners+ this._underlyingWebsocket = newSocket;+ this._underlyingWebsocket.addEventListener(+ WebsocketEvent.Open,+ this.handleOpenEvent+ );+ this._underlyingWebsocket.addEventListener(+ WebsocketEvent.Close,+ this.handleCloseEvent+ );+ this._underlyingWebsocket.addEventListener(+ WebsocketEvent.Error,+ this.handleErrorEvent+ );+ this._underlyingWebsocket.addEventListener(+ WebsocketEvent.Message,+ this.handleMessageEvent+ );++ if (this.binaryType !== undefined) {+ this._underlyingWebsocket.binaryType = this.binaryType;+ }++ return this._underlyingWebsocket;+ }++ /**+ * Removes all event listeners from the browser-native websocket and closes it.+ */+ private clearWebsocket() {+ this._underlyingWebsocket.removeEventListener(+ WebsocketEvent.Open,+ this.handleOpenEvent+ );+ this._underlyingWebsocket.removeEventListener(+ WebsocketEvent.Close,+ this.handleCloseEvent+ );+ this._underlyingWebsocket.removeEventListener(+ WebsocketEvent.Error,+ this.handleErrorEvent+ );+ this._underlyingWebsocket.removeEventListener(+ WebsocketEvent.Message,+ this.handleMessageEvent+ );++ // Only close if the connection is OPEN or CLOSING+ // The ws library throws an error when closing a CONNECTING WebSocket+ const readyState = this._underlyingWebsocket.readyState;+ if (+ readyState !== WebSocket.CONNECTING &&+ readyState !== WebSocket.CLOSED+ ) {+ this._underlyingWebsocket.close();+ }+ }++ /**+ * Handles the 'open' event of the browser-native websocket.+ * @param event to handle.+ */+ private handleOpenEvent = (event: Event) =>+ this.handleEvent(WebsocketEvent.Open, event);++ /**+ * Handles the 'error' event of the browser-native websocket.+ * @param event to handle.+ */+ private handleErrorEvent = (event: Event) =>+ this.handleEvent(WebsocketEvent.Error, event);++ /**+ * Handles the 'close' event of the browser-native websocket.+ * @param event to handle.+ */+ private handleCloseEvent = (event: CloseEvent) =>+ this.handleEvent(WebsocketEvent.Close, event);++ private handleHeartbeatReceived = (event: MessageEvent) => {+ if (this.heartbeatTimeout) {+ clearTimeout(this.heartbeatTimeout);+ this.heartbeatTimeout = undefined;+ }++ const receivedHeartbeatEvent = new CustomEvent<HeartbeatEventDetail>(+ WebsocketEvent.HeartbeatReceived,+ {+ detail: {+ message: event.data,+ timestamp: Date.now(),+ },+ }+ );++ this.dispatchEvent(+ WebsocketEvent.HeartbeatReceived,+ receivedHeartbeatEvent+ );+ };++ /**+ * Handles the 'message' event of the browser-native websocket.+ * @param event to handle.+ */+ private handleMessageEvent = (event: MessageEvent) => {+ if (event.data === this._options.heartbeat?.pongMessage) {+ this.handleHeartbeatReceived(event);+ return;+ }+ this.handleEvent(WebsocketEvent.Message, event);+ };++ /**+ * Dispatch an event to all listeners of the given event-type.+ *+ * @param type of the event to dispatch.+ * @param event to dispatch.+ */+ private dispatchEvent<K extends WebsocketEvent>(+ type: K,+ event: WebsocketEventMap<Receive>[K]+ ) {+ const eventListeners: WebsocketEventListeners<Send, Receive>[K] =+ this._options.listeners[type];+ const newEventListeners: WebsocketEventListeners<Send, Receive>[K] = [];++ eventListeners.forEach(({ listener, options }) => {+ listener(this, event); // invoke listener with event++ if (+ options === undefined ||+ options.once === undefined ||+ !options.once+ ) {+ newEventListeners.push({ listener, options }); // only keep listener if it isn't a once-listener+ }+ });++ this._options.listeners[type] = newEventListeners; // replace old listeners with new listeners that don't include once-listeners+ }++ /**+ * Handles the given event by dispatching it to all listeners of the given event-type.+ *+ * @param type of the event to handle.+ * @param event to handle.+ */+ private handleEvent(+ type: WebsocketEvent,+ event: WebsocketEventMap<WebsocketData>[WebsocketEvent]+ ) {+ const eventWithType = {+ event,+ type,+ // Internal event handles have not yet deserialized the data+ // thus here it is WebsocketData and not Receive+ } as WebsocketEventUnion<WebsocketData>;++ match(eventWithType)+ .with({ type: WebsocketEvent.Close }, () => {+ this.stopHeartbeat();+ this.connectionState = WebsocketConnectionState.Closed;+ this.dispatchEvent(type, event);+ this.scheduleConnectionRetryIfNeeded();+ })+ .with({ type: WebsocketEvent.Open }, () => {+ if (this.backoff !== undefined && this._lastConnection !== undefined) {+ const detail: ReconnectEventDetail = {+ retries: this.backoff.retries,+ lastConnection: new Date(this._lastConnection),+ url: this._url,+ };+ const reconnectEvent = new CustomEvent<ReconnectEventDetail>(+ WebsocketEvent.Reconnect,+ { detail }+ );+ this.dispatchEvent(WebsocketEvent.Reconnect, reconnectEvent);+ this.backoff.reset();+ }++ if (this._options.heartbeat) {+ this.startHeartbeat();+ }++ this.connectionState = WebsocketConnectionState.Open;+ this._lastConnection = new Date();+ this.dispatchEvent(type, event);+ this.sendBufferedData();+ })+ .with({ type: WebsocketEvent.retry }, () => {+ this.connectionState = WebsocketConnectionState.Reconnecting;+ this.dispatchEvent(type, event);+ this.clearWebsocket();+ this.tryConnect();+ })+ .with({ type: WebsocketEvent.Error }, () => {+ this.connectionState = WebsocketConnectionState.Closing;+ this.dispatchEvent(type, event);+ })+ .with({ type: WebsocketEvent.Message }, ({ event }) => {+ const data = deserializeIfNeeded(event.data, this._options.serializer);+ const newEvent = new MessageEvent('message', {+ data,+ origin: event.origin,+ lastEventId: event.lastEventId,+ source: event.source,+ });+ this.dispatchEvent(WebsocketEvent.Message, newEvent);+ })+ .with(+ {+ type: P.union(+ WebsocketEvent.Reconnect,+ WebsocketEvent.HeartbeatSent,+ WebsocketEvent.HeartbeatReceived,+ WebsocketEvent.HeartbeatMissed+ ),+ },+ () => {+ this.dispatchEvent(type, event);+ }+ )+ .exhaustive();+ }++ /**+ * Sends buffered data if there is a buffer defined.+ */+ private sendBufferedData() {+ if (this.buffer === undefined) {+ return; // no buffer defined, nothing to send+ }++ for (+ let ele = this.buffer.read();+ ele !== undefined;+ ele = this.buffer.read()+ ) {+ this.send(ele); // send buffered data+ }+ }++ /**+ * Schedules a connection-retry if there is a backoff defined and the websocket was not closed by the user.+ */+ private scheduleConnectionRetryIfNeeded() {+ if (this.closedByUser) {+ return; // user closed the websocket, no retry+ }+ if (this.backoff === undefined) {+ return; // no backoff defined, no retry+ }++ // handler dispatches the retry event to all listeners of the retry event-type+ const handleRetryEvent = (detail: RetryEventDetail) => {+ const event: CustomEvent<RetryEventDetail> = new CustomEvent(+ WebsocketEvent.retry,+ { detail }+ );+ this.handleEvent(WebsocketEvent.retry, event);+ };++ // create retry event detail, depending on the 'instantReconnect' option+ const retryEventDetail: RetryEventDetail = {+ backoff:+ this._options.retry.instantReconnect === true ? 0 : this.backoff.next(),+ retries:+ this._options.retry.instantReconnect === true+ ? 0+ : this.backoff.retries,+ lastConnection: this._lastConnection,+ url: this._url,+ };++ // schedule a new connection-retry if the maximum number of retries is not reached yet+ if (+ this._options.retry.maxRetries === undefined ||+ retryEventDetail.retries <= this._options.retry.maxRetries+ ) {+ this.retryTimeout = globalThis.setTimeout(+ () => handleRetryEvent(retryEventDetail),+ retryEventDetail.backoff+ );+ }+ }++ /**+ * Cancels the scheduled connection-retry, if there is one.+ */+ private cancelScheduledConnectionRetry() {+ globalThis.clearTimeout(this.retryTimeout);+ }++ /**+ * Handles the heartbeat timeout.+ * If we don't receive a pong we will increment the missedHeartbeats counter and check if we should reconnect.+ */+ private handleHeartbeatTimeout() {+ this.missedHeartbeats++;+ if (!isRequiredHeartbeatOptions(this._options?.heartbeat)) {+ return;+ }++ const shouldReconnect =+ this.missedHeartbeats > this._options.heartbeat.maxMissedHeartbeats;++ const event = new CustomEvent<HeartbeatMissedEventDetail>(+ WebsocketEvent.HeartbeatMissed,+ {+ detail: {+ missedHeartbeats: this.missedHeartbeats,+ willReconnect:+ this.missedHeartbeats > this._options.heartbeat.maxMissedHeartbeats,+ },+ }+ );++ this.dispatchEvent(WebsocketEvent.HeartbeatMissed, event);++ if (shouldReconnect) {+ // Close the underlying websocket and trigger a reconnect+ this._underlyingWebsocket.close(1000, 'No heartbeat received');+ }+ }++ private isClosing(): boolean {+ return (+ this._underlyingWebsocket.readyState === this._underlyingWebsocket.CLOSING+ );+ }++ /**+ * Sends a heartbeat message to the websocket.+ * Schedules a timeout for `this._options.heartbeat.timeout` milliseconds.+ * If we don't receive a pong we will increment the missedHeartbeats counter and check if we should reconnect.+ */+ private sendHeartbeat() {+ if (!this._underlyingWebsocket || this.closedByUser) return;+ if (!isRequiredHeartbeatOptions(this._options?.heartbeat)) {+ return;+ }++ if (this.isClosing()) {+ this.handleEvent(+ WebsocketEvent.Close,+ new CloseEvent('closed websocket by heartbeat, already closing')+ );+ return;+ }++ this._underlyingWebsocket.send(this._options.heartbeat.pingMessage);++ const event = new CustomEvent<HeartbeatEventDetail>(+ WebsocketEvent.HeartbeatReceived,+ {+ detail: {+ message: this._options.heartbeat.pingMessage,+ timestamp: Date.now(),+ },+ }+ );++ this.dispatchEvent(WebsocketEvent.HeartbeatSent, event);++ this.heartbeatTimeout = setTimeout(+ () => this.handleHeartbeatTimeout(),+ this._options.heartbeat.timeout+ );+ }++ /** Returns whether the heartbeat is running. */+ isHeartbeatRunning(): boolean {+ return this.heartbeatInterval !== undefined;+ }++ /**+ * Stops the heartbeat interval and timeout.+ */+ private stopHeartbeat() {+ if (this.heartbeatInterval) {+ clearInterval(this.heartbeatInterval);+ this.heartbeatInterval = undefined;+ }++ if (this.heartbeatTimeout) {+ clearTimeout(this.heartbeatTimeout);+ this.heartbeatTimeout = undefined;+ }++ this.missedHeartbeats = 0;+ }++ /**+ * Starts a new heartbeat interval.+ */+ private startHeartbeat() {+ this.stopHeartbeat();+ this.missedHeartbeats = 0;+ if (!isRequiredHeartbeatOptions(this._options?.heartbeat)) {+ return;+ }++ this.heartbeatInterval = setInterval(() => {+ if (this.connectionState === WebsocketConnectionState.Open) {+ this.sendHeartbeat();+ }+ }, this._options.heartbeat.interval);+ }++ reconnect() {+ this.close();+ this.tryConnect();+ }+}diff --git a/js/app/packages/websocket/index.ts b/js/app/packages/websocket/index.tsindex 2ee01e6d9f..c462975f6a 100644--- a/js/app/packages/websocket/index.ts+++ b/js/app/packages/websocket/index.ts@@ -1,954 +1,34 @@-import { AuthState, createAuthChangeEffect } from '@core/auth';-import {- type Accessor,- createRoot,- createSignal,- getOwner,- onCleanup,-} from 'solid-js';-import type { MinimalWebSocket, WebSocketFactory } from './MinimalWebSocket';-import { isTauri, TauriWebSocketWrapper } from './TauriWebSocket';--export type { MinimalWebSocket, WebSocketFactory } from './MinimalWebSocket';-+export type { Backoff } from './core/backoff/backoff';+export { ConstantBackoff } from './core/backoff/constant-backoff';+export { ExponentialBackoff } from './core/backoff/exponential-backoff';+export { LinearBackoff } from './core/backoff/linear-backoff';+export { ArrayQueue } from './core/queue/array-queue';+export type { Queue } from './core/queue/queue';+export { RingQueue } from './core/queue/ring-queue';+export { BebopSerializer } from './core/serializers/bebop-serializer';+export { JsonSerializer } from './core/serializers/json-serializer';+export { Websocket } from './core/websocket';+export type { WebsocketBuffer } from './core/websocket-buffer';+export { WebsocketBuilder } from './core/websocket-builder';+export { WebsocketConnectionState } from './core/websocket-connection-state';export {- createReconnectingWS,- createWS,- makeHeartbeatWS,- makeReconnectingWS,- makeWS,- type ReconnectingWebSocket,- type WSHeartbeatOptions,- type WSMessage,- type WSReconnectOptions,-} from './SolidPrimitives';-export type WebSocketMessage =- | string- | ArrayBufferLike- | ArrayBufferView- | Blob;--export type ObjectLike = Record<string, any>;--export enum WebSocketState {- Connecting = 0,- Open = 1,- Closing = 2,- Closed = 3,-}--type ExponentialBackoffOptions = {- backoffStrategy?: 'exponential';- delay?: number;- maxDelay?: number;- factor?: number;-};--type LinearBackoffOptions = {- backoffStrategy: 'linear';- delay?: number;- maxDelay?: number;- increment?: number;-};--type ConstantBackoffOptions = {- backoffStrategy: 'constant';- delay?: number;-};--type BackoffOptions =- | ExponentialBackoffOptions- | LinearBackoffOptions- | ConstantBackoffOptions;--type ReconnectOptions = {- reconnectUrlResolver?: () => string | Promise<string>;- retries?: number;-} & BackoffOptions;--export type DurableSocketOptions = {- protocols?: string | string[];- webSocketFactory?: WebSocketFactory;-} & ReconnectOptions;--export type IdentityPlugin = <S, R>(- ws: DurableSocket<S, R>-) => DurableSocket<S, R>;--type AnyPlugin<Send, Receive> = SocketPlugin<Send, Receive> | IdentityPlugin;--export type SocketPlugin<Send, Receive> = (- ws: DurableSocket<Send, Receive>-) => DurableSocket<Send, Receive>;--export type DurableSocket<- Send = WebSocketMessage,- Receive = WebSocketMessage,-> = Omit<WebSocket, 'send'> & {- readonly _send?: Send;- readonly _receive?: Receive;- send(data: Send): void;- chainSend<Send, Receive>(- ws: DurableSocket<Send, Receive>,- wrap: (next: (data: any) => void) => (data: Send) => void- ): void;- reconnect: () => void;-};--const DEFAULT_BACKOFF = {- exponential: {- delay: 500,- maxDelay: 30000,- factor: 2,- },- linear: {- delay: 500,- maxDelay: 30000,- increment: 1000,- },- constant: {- delay: 1000,- },- none: {},-};--function isLinearBackoff(opts: BackoffOptions): opts is LinearBackoffOptions {- return opts.backoffStrategy === 'linear';-}--function isExponentialBackoff(- opts: BackoffOptions-): opts is ExponentialBackoffOptions {- return opts.backoffStrategy === 'exponential';-}--function isConstantBackoff(- opts: BackoffOptions-): opts is ConstantBackoffOptions {- return opts.backoffStrategy === 'constant';-}--const DEFAULT_RETRIES = Infinity;--const PREV_SEND = Symbol('previousSend');--/**- * Platform-aware WebSocket factory that uses Tauri WebSocket in Tauri environments- * and falls back to native WebSocket otherwise- */-export const platformWebSocketFactory: WebSocketFactory = (url, protocols) => {- if (isTauri()) {- return new TauriWebSocketWrapper(url.toString(), protocols);- }-- return new WebSocket(url, protocols) as MinimalWebSocket;-};--export function makeDurableSocket<- Send = WebSocketMessage,- Receive = WebSocketMessage,->(- url: string,- options?: DurableSocketOptions,- plugins: AnyPlugin<Send, Receive>[] = []-): DurableSocket<Send, Receive> {- const strategy = options?.backoffStrategy ?? 'exponential';- const defaults = DEFAULT_BACKOFF[strategy];- const opts = {- backoffStrategy: strategy,- retries: options?.retries ?? DEFAULT_RETRIES,- reconnectUrlResolver: options?.reconnectUrlResolver,- protocols: options?.protocols,- webSocketFactory: options?.webSocketFactory,- ...defaults,- ...options,- };-- const resolveUrl = opts.reconnectUrlResolver;- const webSocketFactory = opts.webSocketFactory ?? platformWebSocketFactory;- let currentRetries = opts.retries;- let reconnectAttempt = 0;- const suppressedCloses = new WeakSet<MinimalWebSocket>();- let ws: MinimalWebSocket;- let durableWs: DurableSocket<Send, Receive>;- let isReconnecting = false;-- const messageQueue: WebSocketMessage[] = [];- const eventHandlers = new Map<string, Set<EventListener>>();-- const getReconnectDelay = () => {- let delay: number;-- if (isLinearBackoff(opts)) {- const increment = opts.increment ?? DEFAULT_BACKOFF.linear.increment;- const baseDelay = opts.delay ?? DEFAULT_BACKOFF.linear.delay;- const maxDelay = opts.maxDelay ?? DEFAULT_BACKOFF.linear.maxDelay;- delay = baseDelay + reconnectAttempt * increment;- delay = Math.min(delay, maxDelay);- } else if (isExponentialBackoff(opts)) {- const factor = opts.factor ?? DEFAULT_BACKOFF.exponential.factor;- const baseDelay = opts.delay ?? DEFAULT_BACKOFF.exponential.delay;- const maxDelay = opts.maxDelay ?? DEFAULT_BACKOFF.exponential.maxDelay;- delay = baseDelay * Math.pow(factor, reconnectAttempt);- delay = Math.min(delay, maxDelay);- } else if (isConstantBackoff(opts)) {- delay = (opts as ConstantBackoffOptions).delay ?? 1000;- } else {- throw new Error('Invalid backoff strategy');- }-- reconnectAttempt++;- return Math.round(delay);- };-- const maybeResolveUrl = async () => {- if (resolveUrl) {- try {- url = await resolveUrl();- } catch (e) {- console.error('Reconnect URL resolver failed', e);- }- }- };-- const reconnect = async () => {- if (isReconnecting) return;- isReconnecting = true;-- // mark the current instance as intentionally closing- if (ws && ws.readyState < WebSocketState.Closing) {- suppressedCloses.add(ws);- ws.close();- }-- currentRetries = opts.retries;- reconnectAttempt = 0;- await maybeResolveUrl();- createConnection();- reattachEventHandlers();- };-- const chainSend = <Send, Receive>(- ws: DurableSocket<Send, Receive>,- wrap: (next: (data: any) => void) => (data: Send) => void- ): void => {- const next = ws.send.bind(ws);- (ws as any)[PREV_SEND] = next;- ws.send = wrap(next) as typeof ws.send;- };-- const createConnection = () => {- ws = webSocketFactory(url, opts.protocols);-- // NB: Do not alter this block or touch currentWs!- // There is a spooky stale reference bug where the original send- // refers to the memory address of the first instance of ws instead- // of the current instance. This causes sending to the old closed socket- // after a reconnect, instead of the current socket.- //- // I tried to create a unit test for this but I wansn't able to in a reasonable amount of time.- const currentWs = ws; // Capture the current instance- const originalSend = currentWs.send.bind(currentWs);- currentWs.send = (data: WebSocketMessage) => {- if (currentWs.readyState === WebSocketState.Open) {- originalSend(data);- } else {- messageQueue.push(data);- }- };-- // use currentWs here, not ws- currentWs.addEventListener('open', () => {- reconnectAttempt = 0;- isReconnecting = false;- currentRetries = opts.retries;-- while (messageQueue.length > 0) {- const msg = messageQueue.shift()!;- originalSend(msg);- }- });-- currentWs.addEventListener('close', async () => {- // ignore only if this particular socket was intentionally closed- if (suppressedCloses.has(currentWs)) {- suppressedCloses.delete(currentWs);- return;- }-- if (currentRetries > 0) {- (durableWs as any).dispatchEvent?.(new Event('reconnecting'));-- currentRetries--;- const delay = getReconnectDelay();- setTimeout(async () => {- await maybeResolveUrl();- createConnection();- reattachEventHandlers();- }, delay);- }- });- (ws as DurableSocket<Send, Receive>).reconnect = reconnect;- (ws as DurableSocket<Send, Receive>).chainSend = chainSend;-- enhancedWs = ws as DurableSocket<Send, Receive>;- for (const plugin of plugins) {- enhancedWs = plugin(enhancedWs as DurableSocket<Send, Receive>);- }-- Object.setPrototypeOf(durableWs, enhancedWs);-- for (const prop in enhancedWs) {- if (!(prop in durableWs)) {- const descriptor = Object.getOwnPropertyDescriptor(enhancedWs, prop);- if (descriptor) {- Object.defineProperty(durableWs, prop, descriptor);- }- }- }- };-- const reattachEventHandlers = () => {- eventHandlers.forEach((handlers, type) => {- handlers.forEach((handler) => {- durableWs.addEventListener(type, handler);- });- });- };-- let enhancedWs: DurableSocket<Send, Receive> | null = null;-- durableWs = {- get binaryType() {- return ws?.binaryType;- },- set binaryType(value) {- if (ws) ws.binaryType = value;- },- get bufferedAmount() {- return ws?.bufferedAmount || 0;- },- get extensions() {- return ws?.extensions || '';- },- get onclose() {- return ws?.onclose || null;- },- set onclose(value) {- if (ws) ws.onclose = value;- },- get onerror() {- return ws?.onerror || null;- },- set onerror(value) {- if (ws) ws.onerror = value;- },- get onmessage() {- return ws?.onmessage || null;- },- set onmessage(value) {- if (ws) ws.onmessage = value;- },- get onopen() {- return ws?.onopen || null;- },- set onopen(value) {- if (ws) ws.onopen = value;- },- get protocol() {- return ws?.protocol || '';- },- get readyState() {- return ws?.readyState || WebSocketState.Connecting;- },- get url() {- return ws?.url || url;- },- set url(value) {- url = value;- },-- addEventListener<K extends keyof WebSocketEventMap>(- type: K,- listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,- options?: boolean | AddEventListenerOptions- ) {- if (!eventHandlers.has(type)) {- eventHandlers.set(type, new Set());- }- eventHandlers.get(type)!.add(listener as EventListener);-- // Always attach to the current underlying target (plugins wrap ws.addEventListener anyway)- (enhancedWs ?? ws)?.addEventListener(- type as any,- listener as any,- options as any- );- },-- removeEventListener<K extends keyof WebSocketEventMap>(- type: K,- listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,- options?: boolean | EventListenerOptions- ) {- eventHandlers.get(type)?.delete(listener as EventListener);-- const targets = new Set<any>([ws, enhancedWs]); // dedupe if they are the same- for (const t of targets) {- t?.removeEventListener?.(type as any, listener as any, options as any);- }- },-- dispatchEvent(event: Event): boolean {- return ws?.dispatchEvent(event) || false;- },-- close(code?: number, reason?: string) {- suppressedCloses.add(ws);- currentRetries = 0;- ws?.close(code, reason);- },-- chainSend<Send, Receive>(- ws: DurableSocket<Send, Receive>,- wrap: (next: (data: any) => void) => (data: Send) => void- ): void {- chainSend(ws, wrap);- },-- send(data: Send) {- ws?.send(data as any);- },-- reconnect() {- reconnect();- },-- CONNECTING: WebSocketState.Connecting,- OPEN: WebSocketState.Open,- CLOSING: WebSocketState.Closing,- CLOSED: WebSocketState.Closed,- } as DurableSocket<Send, Receive>;-- createConnection();-- durableWs.send;-- return durableWs;-}--export function createDurableSocket<- Send = WebSocketMessage,- Receive = WebSocketMessage,->(- url: string,- options?: DurableSocketOptions,- plugins: AnyPlugin<Send, Receive>[] = []-): DurableSocket<Send, Receive> {- return createRoot(() => {- return makeDurableSocket<Send, Receive>(url, options, plugins);- });-}--/**- * Returns a reactive state signal for the web socket's readyState:- * ```ts- * const ws = createWS('ws://localhost:5000');- * const state = createWSState(ws);- * const states = ["Connecting", "Open", "Closing", "Closed"] as const;- * return <div>{states[state()]}</div>- * ```- */--export const createWSState = (- ws: DurableSocket<any, any>-): Accessor<WebSocketState> => {- const [state, setState] = createSignal<WebSocketState>(ws.readyState);-- ws.addEventListener('open', () => {- setState(WebSocketState.Open);- reconnecting = false;- });-- const _close = ws.close.bind(ws);- ws.close = (...args) => {- setState(WebSocketState.Closing);- _close(...args);- };-- ws.addEventListener('reconnecting' as any, () => {- reconnecting = true;- setState(WebSocketState.Connecting);- });-- ws.addEventListener('close', () => {- if (!reconnecting) setState(WebSocketState.Closed);- });-- let reconnecting = false;- const _reconnect = ws.reconnect.bind(ws);- ws.reconnect = () => {- reconnecting = true;- setState(WebSocketState.Connecting);- _reconnect();- };-- return state;-};--export type HeartbeatOptions = {- message?: WebSocketMessage;- response?: WebSocketMessage;- interval?: number;- wait?: number;- maxMissedPongs?: number;-};--const DEFAULT_HEARTBEAT_OPTIONS: Required<HeartbeatOptions> = {- message: 'ping',- response: 'pong',- interval: 25_000,- wait: 10_000,- maxMissedPongs: 0,-};--export function heartbeatPlugin(- options: HeartbeatOptions = {}-): IdentityPlugin {- const opts = { ...DEFAULT_HEARTBEAT_OPTIONS, ...options };-- return (ws: DurableSocket<any, any>) => {- let consecutiveMissed = 0;- let idleTimer: ReturnType<typeof setTimeout> | undefined;- let pongTimer: ReturnType<typeof setTimeout> | undefined;-- const clearTimers = () => {- clearTimeout(idleTimer);- clearTimeout(pongTimer);- idleTimer = undefined;- pongTimer = undefined;- };-- const sendPing = () => {- ws.send(opts.message);-- clearTimeout(pongTimer);- pongTimer = setTimeout(() => {- consecutiveMissed++;- if (consecutiveMissed > opts.maxMissedPongs) {- console.warn(- `Heartbeat failure: ${consecutiveMissed} consecutive missed pongs`- );- if (ws.readyState === WebSocketState.Open) {- console.warn('Reconnecting due to missed pongs');- ws.reconnect();- }- } else {- scheduleNextPing();- }- }, opts.wait);- };-- const scheduleNextPing = () => {- clearTimeout(idleTimer);- idleTimer = setTimeout(sendPing, opts.interval);- };-- const onMessage = (event: MessageEvent) => {- if (event.data === opts.response || event.data === 'pong') {- consecutiveMissed = 0;- clearTimeout(pongTimer);- pongTimer = undefined;- }- scheduleNextPing();- };-- ws.chainSend(ws, (next) => (data: WebSocketMessage) => {- return next(data);- });-- ws.addEventListener('open', () => {- consecutiveMissed = 0;- scheduleNextPing();- });- ws.addEventListener('close', clearTimers);- ws.addEventListener('error', clearTimers);- ws.addEventListener('message', onMessage);-- return ws;- };-}--/**- * DurableSocker plugin for using with bebop binary protocol- *- * Will automatically encode and decode websocket messages- *- * @param sendType- * @param receiveType- * @param onFailedParse- * @returns- */-export function bebopPlugin<Send, Receive>(- sendType: { encode: (data: Send) => Uint8Array },- receiveType: { decode: (data: Uint8Array) => Receive },- onFailedParse?: (e: Error) => void-): SocketPlugin<Send, Receive> {- return (ws) => {- const originalAddEventListener = ws.addEventListener.bind(ws);-- ws.chainSend(ws, (next) => (data: Send) => {- if (typeof data === 'string') {- next(data);- return;- }- const encoded = sendType.encode(data);- next(encoded);- });-- ws.addEventListener = (- type: string,- listener: EventListener,- options?: any- ) => {- if (type === 'message') {- const wrappedListener = async (e: MessageEvent) => {- if (- !(- e.data instanceof Blob ||- Object.prototype.toString.call(e.data) === '[object Blob]'- )- ) {- onFailedParse?.(- new Error('Expected Blob, received ' + typeof e.data)- );- return;- }- try {- const buffer = new Uint8Array(await e.data.arrayBuffer());- const decoded = receiveType.decode(buffer);- const { ports: _, ...rest } = e;- const newEvent = new MessageEvent('message', {- ...rest,- data: decoded,- });- listener(newEvent);- } catch (error) {- console.error('Failed to parse bebop message', error);- onFailedParse?.(error as Error);- }- };-- originalAddEventListener(- 'message',- wrappedListener as EventListener,- options- );- } else {- originalAddEventListener(type, listener, options);- }- };-- return ws;- };-}--export function jsonPlugin<Send = any, Receive = any>(- onFailedParse?: (e: Error) => void-): SocketPlugin<Send, Receive> {- return (ws) => {- ws.chainSend(ws, (next) => (data: Send | string) => {- if (typeof data === 'string') {- next(data);- return;- }- try {- next(JSON.stringify(data));- } catch (err) {- onFailedParse?.(err as Error);- }- });-- const add = ws.addEventListener.bind(ws);- const remove = ws.removeEventListener.bind(ws);-- const listenerMap = new WeakMap<EventListener, EventListener>();-- ws.addEventListener = (- type: string,- listener: EventListener,- options?: boolean | AddEventListenerOptions- ) => {- if (type !== 'message') {- add(type, listener, options);- return;- }-- const wrapped: EventListener = (e: MessageEvent) => {- if (typeof e.data === 'string' && /^[{\[]|^"/.test(e.data.trim())) {- try {- const parsed = JSON.parse(e.data) as Receive;- listener(- new MessageEvent('message', {- data: parsed,- origin: e.origin,- lastEventId: e.lastEventId,- source: e.source,- })- );- return;- } catch (err) {- console.error('Failed to parse message', err);- onFailedParse?.(err as Error);- }- }-- listener(e);- };-- listenerMap.set(listener, wrapped);- add('message', wrapped, options);- };-- ws.removeEventListener = (- type: string,- listener: EventListener,- options?: boolean | EventListenerOptions- ) => {- if (type !== 'message') {- remove(type, listener, options);- return;- }-- const wrapped = listenerMap.get(listener);- if (wrapped) {- remove('message', wrapped, options);- listenerMap.delete(listener);- } else {- remove(type, listener, options);- }- };-- return ws;- };-}--export function createSocketEffect<Receive>(- ws: DurableSocket<any, Receive>,- callback: (data: Receive) => void-) {- const messageHandler = (e: MessageEvent) => {- const data = e.data;- callback(data);- };-- ws.addEventListener('message', messageHandler);-- const dispose = () => {- ws.removeEventListener('message', messageHandler);- };-- if (getOwner()) {- onCleanup(() => {- dispose();- });- }-- return dispose;-}--export type AuthPluginOptions = {- /** Check if user is authenticated */- isAuthenticated: () => boolean;- /** Callback when authentication check blocks connection */- onAuthBlocked?: () => void;-};--/**- * DurableSocket plugin for requiring authentication- *- * @param options - Configuration for authentication behavior- * @returns IdentityPlugin- */-export function authPlugin(options: AuthPluginOptions): IdentityPlugin {- const { isAuthenticated, onAuthBlocked } = options;-- return (ws) => {- const originalAddEventListener = ws.addEventListener.bind(ws);- createAuthChangeEffect((stateChange) => {- if (- stateChange.from === AuthState.Unauthenticated &&- stateChange.to === AuthState.Authenticated- ) {- ws.reconnect();- }- });-- ws.addEventListener = (- type: string,- listener: EventListener,- options?: any- ) => {- if (type === 'open') {- const wrappedListener = (e: Event) => {- if (!isAuthenticated()) {- ws.close();- onAuthBlocked?.();- return;- }- listener(e);- };- originalAddEventListener('open', wrappedListener, options);- } else {- originalAddEventListener(type, listener, options);- }- };-- if (ws.readyState === WebSocketState.Connecting && !isAuthenticated()) {- ws.close();- onAuthBlocked?.();- }-- return ws;- };-}--/**- * Creates a reactive effect that responds to websocket messages with a specific event type.- * This is particularly useful for event-based websocket protocols where messages have- * a 'type' field to distinguish different kinds of events.- *- * @param ws - The DurableSocket instance to listen to- * @param eventType - The specific event type to listen for (matches against message.type)- * @param callback - Function to be called when a message of the specified type is received- *- * @example- * ```ts- * const ws = createDurableSocket('wss://api.example.com', undefined, [- * zodPlugin(sendSchema, receiveSchema)- * ]);- *- * createWebsocketEventEffect(ws, 'user_update', (data) => {- * console.log('User updated:', data);- * updateUserState(data);- * });- *- * createWebsocketEventEffect(ws, 'bulk_upload', (data) => {- * console.log('Bulk upload event:', data);- * processBulkUpload(data);- * });- * ```- */-export function createWebsocketEventEffect<- EventType extends string,- Receive extends ObjectLike & { type: EventType },->(- ws: DurableSocket<any, any>,- eventType: EventType,- callback: (data: Receive) => void-) {- const messageHandler = (e: MessageEvent) => {- const data = e.data;-- if (- data &&- typeof data === 'object' &&- 'type' in data &&- data.type === eventType- ) {- callback(data as Receive);- }- };-- ws.addEventListener('message', messageHandler);-- if (getOwner()) {- onCleanup(() => {- ws.removeEventListener('message', messageHandler);- });- }-}--/**- * Creates multiple websocket event effects for different event types on the same socket.- * This is a convenience function for setting up multiple event handlers at once.- *- * @param ws - The DurableSocket instance to listen to- * @param handlers - An object mapping event types to their respective handlers- *- * @example- * ```ts- * const ws = createDurableSocket('wss://api.example.com', undefined, [- * zodPlugin(sendSchema, receiveSchema)- * ]);- *- * createWebsocketEventEffects(ws, {- * user_update: (data) => updateUserState(data),- * bulk_upload: (data) => processBulkUpload(data),- * notification: (data) => showNotification(data),- * });- * ```- */-export function createWebsocketEventEffects<- EventHandlers extends Record<string, (data: any) => void>,->(ws: DurableSocket<any, any>, handlers: EventHandlers) {- Object.entries(handlers).forEach(([eventType, handler]) => {- createWebsocketEventEffect(ws, eventType, handler);- });-}--export function untilMessage<Receive>(- ws: DurableSocket<any, Receive>,- predicate: (data: Receive) => boolean-): Promise<Receive> {- return new Promise((resolve, reject) => {- const cleanup = () => {- ws.removeEventListener('message', handler);- ws.removeEventListener('close', closeHandler);- };-- const handler = (e: MessageEvent) => {- const data = e.data as Receive;- if (predicate(data)) {- cleanup();- resolve(data);- }- };-- const closeHandler = () => {- cleanup();- reject(new Error('WebSocket closed before message received'));- };-- ws.addEventListener('message', handler);- ws.addEventListener('close', closeHandler);- });-}--export function createReconnectEffect(- ws: DurableSocket<any, any>,- callback: () => void-) {- let reconnecting = false;-- const reconnectingHandler = () => {- reconnecting = true;- };-- const openHandler = () => {- if (reconnecting) {- reconnecting = false;- callback();- }- };-- ws.addEventListener('reconnecting', reconnectingHandler);- ws.addEventListener('open', openHandler);-- if (getOwner()) {- onCleanup(() => {- ws.removeEventListener('reconnecting', reconnectingHandler);- ws.removeEventListener('open', openHandler);- });- }-}+ type ReconnectEventDetail,+ type RetryEventDetail,+ WebsocketEvent,+ type WebsocketEventListener,+ type WebsocketEventListenerOptions,+ type WebsocketEventListenerParams,+ type WebsocketEventListeners,+ type WebsocketEventListenerWithOptions,+ type WebsocketEventMap,+} from './core/websocket-event';+export type { WebsocketOptions } from './core/websocket-options';+export type { WebsocketConnectionRetryOptions } from './core/websocket-retry-options';+export type { UrlResolver } from './core/websocket-url-resolver';+export {+ createReconnectEffect,+ createSocketEffect,+ createWebsocketEventEffect,+} from './solid/socket-effect';+export { createWebsocketStateSignal } from './solid/state-signal';+export { untilMessage } from './utils/until-message';diff --git a/js/app/packages/websocket/package.json b/js/app/packages/websocket/package.jsonindex 08c4c816b3..58924ace8e 100644--- a/js/app/packages/websocket/package.json+++ b/js/app/packages/websocket/package.json@@ -1,14 +1,7 @@{"name": "websocket","private": true,- "dependencies": {- "vitest": "^3.2.3",- "zod": "^3.24.1"- },- "scripts": {- "test": "vitest"- },"devDependencies": {"vite-tsconfig-paths": "^5.1.4"}-}\ No newline at end of file+}diff --git a/js/app/packages/websocket/MinimalWebSocket.ts b/js/app/packages/websocket/platform/minimal-websocket.tssimilarity index 100%rename from js/app/packages/websocket/MinimalWebSocket.tsrename to js/app/packages/websocket/platform/minimal-websocket.tsdiff --git a/js/app/packages/websocket/TauriWebSocket.ts b/js/app/packages/websocket/platform/tauri-websocket.tssimilarity index 99%rename from js/app/packages/websocket/TauriWebSocket.tsrename to js/app/packages/websocket/platform/tauri-websocket.tsindex e7aa9d2cc0..d2fcfa7528 100644--- a/js/app/packages/websocket/TauriWebSocket.ts+++ b/js/app/packages/websocket/platform/tauri-websocket.ts@@ -1,5 +1,5 @@import TauriWebsocket from '@tauri-apps/plugin-websocket';-import type { MinimalWebSocket, WebSocketFactory } from './MinimalWebSocket';+import type { MinimalWebSocket, WebSocketFactory } from './minimal-websocket';/*** Check if we're running in a Tauri environmentdiff --git a/js/app/packages/websocket/solid/socket-effect.ts b/js/app/packages/websocket/solid/socket-effect.tsnew file mode 100644index 0000000000..caa4ff2f61--- /dev/null+++ b/js/app/packages/websocket/solid/socket-effect.ts@@ -0,0 +1,100 @@+import type { ObjectLike } from '@core/util/maybeResult';+import { getOwner, onCleanup } from 'solid-js';+import type { Websocket } from '../core/websocket';+import { WebsocketEvent } from '../core/websocket-event';++/**+ * Creates a reactive effect that listens for a specific websocket event and triggers a callback when the event is received.+ *+ * @param ws The websocket to listen for the event on, that has a json serializable data type.+ * @param eventType The type of the event to listen for.+ * @param callback The callback to trigger when the event is received.+ */+export function createWebsocketEventEffect<+ EventType,+ Receive extends ObjectLike & { type: EventType },+>(+ ws: Websocket<any, Receive>,+ eventType: EventType,+ callback: (data: Receive) => void+) {+ const messageHandler = (+ _i: Websocket<any, Receive>,+ e: MessageEvent<Receive>+ ) => {+ const data = e.data;++ if (+ data &&+ typeof data === 'object' &&+ 'type' in data &&+ data.type === eventType+ ) {+ callback(data as Receive);+ }+ };++ ws.addEventListener(WebsocketEvent.Message, messageHandler);++ if (getOwner()) {+ onCleanup(() => {+ ws.removeEventListener(WebsocketEvent.Message, messageHandler);+ });+ }+}++/**+ * Creates a reactive effect that listens for all websocket messages and triggers a callback when a message is received.+ *+ * @param ws The websocket to listen for messages on.+ * @param callback The callback to trigger when a message is received.+ */+export function createSocketEffect<Send, Receive>(+ ws: Websocket<Send, Receive>,+ callback: (data: Receive) => void+) {+ const messageHandler = (+ _: Websocket<Send, Receive>,+ e: MessageEvent<Receive>+ ) => {+ const data = e.data;+ callback(data);+ };++ ws.addEventListener(WebsocketEvent.Message, messageHandler);++ const dispose = () => {+ ws.removeEventListener(WebsocketEvent.Message, messageHandler);+ };++ if (getOwner()) {+ onCleanup(() => {+ dispose();+ });+ }++ return dispose;+}++/**+ * Creates a reactive effect that triggers when a websocket reconnects successfully.+ *+ * @param ws The websocket to listen for reconnects on.+ * @param callback The callback to trigger when the websocket reconnects successfully.+ */+export function createReconnectEffect(+ ws: Websocket<any, any>,+ callback: () => void+) {+ const reconnectingHandler = () => {+ callback();+ };++ ws.addEventListener(WebsocketEvent.Reconnect, reconnectingHandler);++ if (getOwner()) {+ onCleanup(() => {+ ws.removeEventListener(WebsocketEvent.Reconnect, reconnectingHandler);+ });+ }+}diff --git a/js/app/packages/websocket/solid/state-signal.ts b/js/app/packages/websocket/solid/state-signal.tsnew file mode 100644index 0000000000..bd27a57e34--- /dev/null+++ b/js/app/packages/websocket/solid/state-signal.ts@@ -0,0 +1,84 @@+import { type Accessor, createSignal, onCleanup } from 'solid-js';+import type { Websocket } from '../core/websocket';+import { WebsocketConnectionState } from '../core/websocket-connection-state';+import { WebsocketEvent } from '../core/websocket-event';++/**+ * Creates a reactive signal that tracks the connection state of a websocket.+ *+ * @param ws The websocket to track the connection state of.+ * @returns A reactive signal that tracks the connection state of the websocket.+ */+export function createWebsocketStateSignal(+ ws: Websocket<any, any>+): Accessor<WebsocketConnectionState> {+ const [state, setState] = createSignal(ws.connectionState);++ const EVENT_HANDLERS: Record<+ | WebsocketEvent.Open+ | WebsocketEvent.Close+ | WebsocketEvent.Error+ | WebsocketEvent.Reconnect+ | WebsocketEvent.retry,+ () => void+ > = {+ [WebsocketEvent.Open]: () => {+ setState(WebsocketConnectionState.Open);+ },+ [WebsocketEvent.Close]: () => {+ setState(WebsocketConnectionState.Closed);+ },+ [WebsocketEvent.Error]: () => {+ setState(WebsocketConnectionState.Closing);+ },+ [WebsocketEvent.Reconnect]: () => {+ setState(WebsocketConnectionState.Reconnecting);+ },+ [WebsocketEvent.retry]: () => {+ setState(WebsocketConnectionState.Reconnecting);+ },+ };++ ws.addEventListener(WebsocketEvent.Open, EVENT_HANDLERS[WebsocketEvent.Open]);+ ws.addEventListener(+ WebsocketEvent.Close,+ EVENT_HANDLERS[WebsocketEvent.Close]+ );+ ws.addEventListener(+ WebsocketEvent.Error,+ EVENT_HANDLERS[WebsocketEvent.Error]+ );+ ws.addEventListener(+ WebsocketEvent.Reconnect,+ EVENT_HANDLERS[WebsocketEvent.Reconnect]+ );+ ws.addEventListener(+ WebsocketEvent.retry,+ EVENT_HANDLERS[WebsocketEvent.retry]+ );++ onCleanup(() => {+ ws.removeEventListener(+ WebsocketEvent.Open,+ EVENT_HANDLERS[WebsocketEvent.Open]+ );+ ws.removeEventListener(+ WebsocketEvent.Close,+ EVENT_HANDLERS[WebsocketEvent.Close]+ );+ ws.removeEventListener(+ WebsocketEvent.Error,+ EVENT_HANDLERS[WebsocketEvent.Error]+ );+ ws.removeEventListener(+ WebsocketEvent.Reconnect,+ EVENT_HANDLERS[WebsocketEvent.Reconnect]+ );+ ws.removeEventListener(+ WebsocketEvent.retry,+ EVENT_HANDLERS[WebsocketEvent.retry]+ );+ });++ return state;+}diff --git a/js/app/packages/websocket/tests/backoff/constant-backoff.test.ts b/js/app/packages/websocket/tests/backoff/constant-backoff.test.tsnew file mode 100644index 0000000000..336d65b2e4--- /dev/null+++ b/js/app/packages/websocket/tests/backoff/constant-backoff.test.ts@@ -0,0 +1,60 @@+import { describe, expect, test } from 'vitest';+import { ConstantBackoff } from '../../';++describe('Testsuite for ConstantBackoff', () => {+ test('Initialization should throw on negative backoff', () => {+ expect(() => new ConstantBackoff(-1001)).toThrow();+ expect(() => new ConstantBackoff(-42)).toThrow();+ expect(() => new ConstantBackoff(-1)).toThrow();+ });++ test('Initialization should not throw on zero backoff', () => {+ expect(() => new ConstantBackoff(0)).not.toThrow();+ });++ test('Initialization should not throw on positive backoff', () => {+ expect(() => new ConstantBackoff(1)).not.toThrow();+ expect(() => new ConstantBackoff(42)).not.toThrow();+ expect(() => new ConstantBackoff(1001)).not.toThrow();+ });++ test('Backoff should be equal to the given backoff', () => {+ expect(new ConstantBackoff(1).current).toBe(1);+ expect(new ConstantBackoff(42).current).toBe(42);+ expect(new ConstantBackoff(1001).current).toBe(1001);+ });++ test('Backoff should be equal to the given backoff after next', () => {+ const backoff = new ConstantBackoff(42);+ expect(backoff.next()).toBe(42);+ expect(backoff.current).toBe(42);+ });++ test('Backoff should be equal to the given backoff after reset', () => {+ const backoff = new ConstantBackoff(42);+ expect(backoff.next()).toBe(42);+ backoff.reset();+ expect(backoff.current).toBe(42);+ });++ test('Retries should be zero after initialization', () => {+ expect(new ConstantBackoff(42).retries).toBe(0);+ });++ test('Retries should increment with each next', () => {+ const backoff = new ConstantBackoff(42);+ for (let i = 0; i < 100; i++) {+ expect(backoff.retries).toBe(i);+ backoff.next();+ }+ });++ test('Retries should be zero after reset', () => {+ const backoff = new ConstantBackoff(42);+ for (let i = 0; i < 100; i++) {+ backoff.next();+ }+ backoff.reset();+ expect(backoff.retries).toBe(0);+ });+});diff --git a/js/app/packages/websocket/tests/backoff/exponential-backoff.test.ts b/js/app/packages/websocket/tests/backoff/exponential-backoff.test.tsnew file mode 100644index 0000000000..d74c633821--- /dev/null+++ b/js/app/packages/websocket/tests/backoff/exponential-backoff.test.ts@@ -0,0 +1,92 @@+import { describe, expect, test } from 'vitest';+import { ExponentialBackoff } from '../../';++describe('Testsuite for ExponentialBackoff', () => {+ test('Initialization should throw on negative base', () => {+ expect(() => new ExponentialBackoff(-1001)).toThrow();+ expect(() => new ExponentialBackoff(-42)).toThrow();+ expect(() => new ExponentialBackoff(-1)).toThrow();+ });++ test('Initialization should not throw on zero base', () => {+ expect(() => new ExponentialBackoff(0)).not.toThrow();+ });++ test('Initialization should not throw on positive base', () => {+ expect(() => new ExponentialBackoff(1)).not.toThrow();+ expect(() => new ExponentialBackoff(42)).not.toThrow();+ expect(() => new ExponentialBackoff(1001)).not.toThrow();+ });++ test('Initialization should throw on negative max-exponent', () => {+ expect(() => new ExponentialBackoff(42, -1001)).toThrow();+ expect(() => new ExponentialBackoff(42, -42)).toThrow();+ expect(() => new ExponentialBackoff(42, -1)).toThrow();+ });++ test('Initialization should not throw on zero max-exponent', () => {+ expect(() => new ExponentialBackoff(42, 0)).not.toThrow();+ });++ test('Initialization should not throw on positive max-exponent', () => {+ expect(() => new ExponentialBackoff(42, 1)).not.toThrow();+ expect(() => new ExponentialBackoff(42, 42)).not.toThrow();+ expect(() => new ExponentialBackoff(42, 1001)).not.toThrow();+ });++ test('Initialization should not throw on undefined max-exponent', () => {+ expect(() => new ExponentialBackoff(42)).not.toThrow();+ });++ test('Backoff should be equal to the given base', () => {+ expect(new ExponentialBackoff(1).current).toBe(1);+ expect(new ExponentialBackoff(42).current).toBe(42);+ expect(new ExponentialBackoff(1001).current).toBe(1001);+ });++ test('Backoff without max-exponent should double with each next', () => {+ const backoff = new ExponentialBackoff(2);+ for (let i = 0; i < 10; i++) {+ expect(backoff.current).toBe(2 * Math.pow(2, i));+ expect(backoff.next()).toBe(2 * Math.pow(2, i + 1));+ expect(backoff.current).toBe(2 * Math.pow(2, i + 1));+ }+ });++ test('Backoff with max-exponent should not exceed max-exponent', () => {+ const backoff = new ExponentialBackoff(2, 3);+ for (let i = 0; i < 10; i++) {+ expect(backoff.current).toBe(2 * Math.pow(2, Math.min(3, i)));+ expect(backoff.next()).toBe(2 * Math.pow(2, Math.min(3, i + 1)));+ expect(backoff.current).toBe(2 * Math.pow(2, Math.min(3, i + 1)));+ }+ });++ test('Backoff should be equal to the given base after reset', () => {+ const backoff = new ExponentialBackoff(42);+ backoff.next();+ backoff.reset();+ expect(backoff.current).toBe(42);+ });++ test('Retries should be zero after initialization', () => {+ expect(new ExponentialBackoff(42).retries).toBe(0);+ });++ test('Retries should be incremented with each next', () => {+ const backoff = new ExponentialBackoff(42);+ for (let i = 0; i < 10; i++) {+ expect(backoff.retries).toBe(i);+ backoff.next();+ }+ });++ test('Retries should be zero after reset', () => {+ const backoff = new ExponentialBackoff(42);+ for (let i = 0; i < 100; i++) {+ backoff.next();+ }+ backoff.reset();+ expect(backoff.retries).toBe(0);+ });+});diff --git a/js/app/packages/websocket/tests/backoff/linear-backoff.test.ts b/js/app/packages/websocket/tests/backoff/linear-backoff.test.tsnew file mode 100644index 0000000000..25b6b89e82--- /dev/null+++ b/js/app/packages/websocket/tests/backoff/linear-backoff.test.ts@@ -0,0 +1,104 @@+import { describe, expect, test } from 'vitest';+import { LinearBackoff } from '../../';++describe('Testsuite for LinearBackoff', () => {+ test('Initialization should throw on negative initial-backoff', () => {+ expect(() => new LinearBackoff(-1001, 1000)).toThrow();+ expect(() => new LinearBackoff(-42, 1000)).toThrow();+ expect(() => new LinearBackoff(-1, 1000)).toThrow();+ });++ test('Initialization should not throw on zero initial-backoff', () => {+ expect(() => new LinearBackoff(0, 1000)).not.toThrow();+ });++ test('Initialization should not throw on positive initial-backoff', () => {+ expect(() => new LinearBackoff(1, 1000)).not.toThrow();+ expect(() => new LinearBackoff(42, 1000)).not.toThrow();+ expect(() => new LinearBackoff(1001, 1000)).not.toThrow();+ });++ test('Initialization should throw on negative increment', () => {+ expect(() => new LinearBackoff(1000, -1001)).toThrow();+ expect(() => new LinearBackoff(1000, -42)).toThrow();+ expect(() => new LinearBackoff(1000, -1)).toThrow();+ });++ test('Initialization should not throw on zero increment', () => {+ expect(() => new LinearBackoff(1000, 0)).not.toThrow();+ });++ test('Initialization should not throw on positive increment', () => {+ expect(() => new LinearBackoff(1000, 1)).not.toThrow();+ expect(() => new LinearBackoff(1000, 42)).not.toThrow();+ expect(() => new LinearBackoff(1000, 1001)).not.toThrow();+ });++ test('Initialization should throw on negative max-backoff', () => {+ expect(() => new LinearBackoff(1000, 1000, -1001)).toThrow();+ expect(() => new LinearBackoff(1000, 1000, -42)).toThrow();+ expect(() => new LinearBackoff(1000, 1000, -1)).toThrow();+ });++ test('Initialization should not throw on undefined max-backoff', () => {+ expect(() => new LinearBackoff(1000, 1000, undefined)).not.toThrow();+ });++ test('Initialization should throw on max-backoff smaller than initial-backoff', () => {+ expect(() => new LinearBackoff(1000, 1000, 999)).toThrow();+ expect(() => new LinearBackoff(1000, 1000, 42)).toThrow();+ expect(() => new LinearBackoff(1000, 1000, 1)).toThrow();+ });++ test('Backoff should be equal to the given initial-backoff', () => {+ expect(new LinearBackoff(1, 1000).current).toBe(1);+ expect(new LinearBackoff(42, 1000).current).toBe(42);+ expect(new LinearBackoff(1001, 1000).current).toBe(1001);+ });++ test('Backoff should increment by the given increment with each next', () => {+ const backoff = new LinearBackoff(1000, 1000);+ for (let i = 0; i < 10; i++) {+ expect(backoff.current).toBe(1000 + i * 1000);+ expect(backoff.next()).toBe(1000 + (i + 1) * 1000);+ expect(backoff.current).toBe(1000 + (i + 1) * 1000);+ }+ });++ test('Backoff should increment with the given increment but not exceed the given max-backoff', () => {+ const backoff = new LinearBackoff(1000, 1000, 5000);+ for (let i = 0; i < 10; i++) {+ expect(backoff.current).toBe(Math.min(1000 + i * 1000, 5000));+ expect(backoff.next()).toBe(Math.min(1000 + (i + 1) * 1000, 5000));+ expect(backoff.current).toBe(Math.min(1000 + (i + 1) * 1000, 5000));+ }+ });++ test('Backoff should be equal to the given initial-backoff after reset', () => {+ const backoff = new LinearBackoff(42, 1000);+ backoff.next();+ backoff.reset();+ expect(backoff.current).toBe(42);+ });++ test('Retries should be zero after initialization', () => {+ expect(new LinearBackoff(1000, 1000).retries).toBe(0);+ });++ test('Retries should be incremented with each next', () => {+ const backoff = new LinearBackoff(1000, 1000);+ for (let i = 0; i < 10; i++) {+ expect(backoff.retries).toBe(i);+ backoff.next();+ }+ });++ test('Retries should be reset to zero after reset', () => {+ const backoff = new LinearBackoff(1000, 1000);+ for (let i = 0; i < 100; i++) {+ backoff.next();+ }+ backoff.reset();+ expect(backoff.retries).toBe(0);+ });+});diff --git a/js/app/packages/websocket/tests/queue/array-queue.test.ts b/js/app/packages/websocket/tests/queue/array-queue.test.tsnew file mode 100644index 0000000000..27c299d400--- /dev/null+++ b/js/app/packages/websocket/tests/queue/array-queue.test.ts@@ -0,0 +1,171 @@+import { describe, expect, test } from 'vitest';+import { ArrayQueue } from '../../';++describe('Testsuite for ArrayQueue', () => {+ test('Queue should be empty after initialization', () => {+ expect(new ArrayQueue().isEmpty()).toBe(true);+ });++ test('Add should add an element to the queue', () => {+ const queue = new ArrayQueue<number>();+ queue.add(1);+ expect(queue.length()).toBe(1);+ expect(queue.isEmpty()).toBe(false);+ expect(queue.read()).toBe(1);+ });++ test('Add multiple elements should add all elements to the queue', () => {+ const queue = new ArrayQueue<number>();+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ expect(queue.length()).toBe(i + 1);+ }+ });++ test('Clear should remove all elements from the queue', () => {+ const queue = new ArrayQueue<number>();+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ }+ queue.clear();+ expect(queue.length()).toBe(0);+ expect(queue.peek()).toBe(undefined);+ expect(queue.read()).toBe(undefined);+ });++ test('ForEach should iterate over all elements in the queue', () => {+ const queue = new ArrayQueue<number>();+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ }+ let i = 0;+ queue.forEach((element) => {+ expect(element).toBe(i);+ i++;+ });+ });++ test('ForEach should not remove elements from the queue', () => {+ const queue = new ArrayQueue<number>();+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ }+ let i = 0;+ queue.forEach((element) => {+ expect(element).toBe(i);+ i++;+ });+ const es: number[] = [];+ queue.forEach((element) => es.push(element));+ expect(es.length).toBe(100);+ });++ test('Length should be zero on initialization', () => {+ expect(new ArrayQueue().length()).toBe(0);+ });++ test('Length should be zero after clear', () => {+ const queue = new ArrayQueue<number>();+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ }+ queue.clear();+ expect(queue.length()).toBe(0);+ });++ test('Length should be zero after reading all elements', () => {+ const queue = new ArrayQueue<number>();+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ }+ for (let i = 0; i < 100; i++) {+ queue.read();+ }+ expect(queue.length()).toBe(0);+ expect(queue.isEmpty()).toBe(true);+ expect(queue.peek()).toBeUndefined();+ expect(queue.read()).toBeUndefined();+ });++ test('IsEmpty should be true after initialization', () => {+ expect(new ArrayQueue().isEmpty()).toBe(true);+ });++ test('IsEmpty should be true after clear', () => {+ const queue = new ArrayQueue<number>();+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ }+ queue.clear();+ expect(queue.isEmpty()).toBe(true);+ });++ test('IsEmpty should be true after reading all elements', () => {+ const queue = new ArrayQueue<number>();+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ }+ for (let i = 0; i < 100; i++) {+ queue.read();+ }+ expect(queue.isEmpty()).toBe(true);+ });++ test('Peek should return undefined on initialization', () => {+ expect(new ArrayQueue().peek()).toBeUndefined();+ });++ test('Peek should return undefined after clear', () => {+ const queue = new ArrayQueue<number>();+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ }+ queue.clear();+ expect(queue.peek()).toBeUndefined();+ });++ test('Peek should return the oldest element', () => {+ const queue = new ArrayQueue<number>();+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ expect(queue.peek()).toBe(0);+ }+ });++ test('Peek should not remove the oldest element', () => {+ const queue = new ArrayQueue<number>();+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ expect(queue.peek()).toBe(0);+ }+ });++ test('Read should return undefined on initialization', () => {+ expect(new ArrayQueue().read()).toBeUndefined();+ });++ test('Read should return undefined after clear', () => {+ const queue = new ArrayQueue<number>();+ queue.add(1);+ queue.add(2);+ queue.clear();+ expect(queue.read()).toBeUndefined();+ });++ test('Read should return undefined after reading all elements', () => {+ const queue = new ArrayQueue<number>();+ queue.add(1);+ queue.add(2);+ queue.read();+ queue.read();+ expect(queue.read()).toBeUndefined();+ });++ test('Read should return the oldest element', () => {+ const queue = new ArrayQueue<number>();+ queue.add(1);+ queue.add(2);+ expect(queue.read()).toBe(1);+ expect(queue.read()).toBe(2);+ });+});diff --git a/js/app/packages/websocket/tests/queue/ring-queue.test.ts b/js/app/packages/websocket/tests/queue/ring-queue.test.tsnew file mode 100644index 0000000000..833ac3286f--- /dev/null+++ b/js/app/packages/websocket/tests/queue/ring-queue.test.ts@@ -0,0 +1,237 @@+import { describe, expect, test } from 'vitest';+import { RingQueue } from '../../';++describe('Testsuite for RingQueue', () => {+ test('Initialization should throw on negative capacity', () => {+ expect(() => new RingQueue(-1)).toThrow();+ expect(() => new RingQueue(-42)).toThrow();+ expect(() => new RingQueue(-1001)).toThrow();+ });++ test('Initialization should throw on zero capacity', () => {+ expect(() => new RingQueue(0)).toThrow();+ });++ test('Initialization should not throw on positive capacity', () => {+ expect(() => new RingQueue(1)).not.toThrow();+ expect(() => new RingQueue(42)).not.toThrow();+ expect(() => new RingQueue(1001)).not.toThrow();+ });++ test('Add should add an element to the queue', () => {+ const queue = new RingQueue<number>(42);+ queue.add(1);+ expect(queue.length()).toBe(1);+ expect(queue.isEmpty()).toBe(false);+ expect(queue.read()).toBe(1);+ });++ test('Add should overwrite the oldest element if the queue is full', () => {+ const queue = new RingQueue<number>(42);+ for (let i = 0; i < 100; i++) {+ queue.add(i); // 0, 1, 2, ..., 99+ }+ expect(queue.read()).toBe(58); // 58, 59, ..., 99+ });++ test('Clear should remove all elements from the queue', () => {+ const queue = new RingQueue<number>(42);+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ }+ queue.clear();+ expect(queue.length()).toBe(0);+ expect(queue.peek()).toBe(undefined);+ expect(queue.read()).toBe(undefined);+ });++ test('ForEach should iterate over all elements in the queue', () => {+ const queue = new RingQueue<number>(42);+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ }+ let i = 58;+ queue.forEach((element) => {+ expect(element).toBe(i);+ i++;+ });+ });++ test('ForEach should not remove elements from the queue', () => {+ const queue = new RingQueue<number>(42);+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ }+ let i = 58;+ queue.forEach((element) => {+ expect(element).toBe(i);+ i++;+ });+ queue.forEach((element) => {+ expect(queue.read()).toBe(element);+ });+ });++ test('Length should be zero on initialization', () => {+ expect(new RingQueue(1).length()).toBe(0);+ expect(new RingQueue(42).length()).toBe(0);+ expect(new RingQueue(1001).length()).toBe(0);+ });++ test('Length should be zero after clear', () => {+ const queue = new RingQueue<number>(42);+ queue.add(1);+ queue.add(2);+ queue.clear();+ expect(queue.length()).toBe(0);+ });++ test('Length should be zero after reading all elements', () => {+ const queue = new RingQueue<number>(42);+ queue.add(1);+ queue.add(2);+ queue.read();+ queue.read();+ expect(queue.length()).toBe(0);+ });++ test('Length should be equal to the number of available elements', () => {+ const queue = new RingQueue<number>(42);+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ expect(queue.length()).toBe(Math.min(i + 1, 42));+ }+ });++ test('Length should be equal to the capacity after adding more elements than the capacity', () => {+ const queue = new RingQueue<number>(42);+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ }+ expect(queue.length()).toBe(42);+ });++ test('Length should be equal to the number of available elements after reading', () => {+ const queue = new RingQueue<number>(42);+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ expect(queue.length()).toBe(Math.min(i + 1, 42));+ }+ for (let i = 0; i < 100; i++) {+ queue.read();+ expect(queue.length()).toBe(Math.max(42 - i - 1, 0));+ }+ });++ test('Is empty should be true on initialization', () => {+ expect(new RingQueue(1).isEmpty()).toBe(true);+ expect(new RingQueue(42).isEmpty()).toBe(true);+ expect(new RingQueue(1001).isEmpty()).toBe(true);+ });++ test('Is empty should be true after clear', () => {+ const queue = new RingQueue<number>(42);+ queue.add(1);+ queue.add(2);+ queue.clear();+ expect(queue.isEmpty()).toBe(true);+ });++ test('Is empty should be true after reading all elements', () => {+ const queue = new RingQueue<number>(42);+ queue.add(1);+ queue.add(2);+ queue.read();+ queue.read();+ expect(queue.isEmpty()).toBe(true);+ });++ test('Is empty should be false after adding an element', () => {+ const queue = new RingQueue<number>(42);+ queue.add(1);+ expect(queue.isEmpty()).toBe(false);+ });++ test('Is empty should be false after adding more elements than the capacity', () => {+ const queue = new RingQueue<number>(42);+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ }+ expect(queue.isEmpty()).toBe(false);+ });++ test('Peek should return undefined on initialization', () => {+ expect(new RingQueue(1).peek()).toBeUndefined();+ expect(new RingQueue(42).peek()).toBeUndefined();+ expect(new RingQueue(1001).peek()).toBeUndefined();+ });++ test('Peek should return undefined after clear', () => {+ const queue = new RingQueue<number>(42);+ queue.add(1);+ queue.add(2);+ queue.clear();+ expect(queue.peek()).toBeUndefined();+ });++ test('Peek should return the oldest element', () => {+ const queue = new RingQueue<number>(42);+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ expect(queue.peek()).toBe(Math.max(i - 42 + 1, 0));+ }+ });++ test('Peek should not remove elements from the queue', () => {+ const queue = new RingQueue<number>(42);+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ expect(queue.peek()).toBe(Math.max(i - 42 + 1, 0));+ }+ for (let i = 0; i < 100; i++) {+ expect(queue.peek()).toBe(58);+ }+ });++ test('Read should return undefined on initialization', () => {+ expect(new RingQueue(1).read()).toBeUndefined();+ expect(new RingQueue(42).read()).toBeUndefined();+ expect(new RingQueue(1001).read()).toBeUndefined();+ });++ test('Read should return undefined after clear', () => {+ const queue = new RingQueue<number>(42);+ queue.add(1);+ queue.add(2);+ queue.clear();+ expect(queue.read()).toBeUndefined();+ });++ test('Read should return undefined after reading all elements', () => {+ const queue = new RingQueue<number>(42);+ queue.add(1);+ queue.add(2);+ queue.read();+ queue.read();+ expect(queue.read()).toBeUndefined();+ });++ test('Read should return the oldest element', () => {+ const queue = new RingQueue<number>(42);+ queue.add(1);+ queue.add(2);+ expect(queue.read()).toBe(1);+ expect(queue.read()).toBe(2);+ });++ test('Read should return the oldest element after adding more elements than the capacity', () => {+ const queue = new RingQueue<number>(42);+ for (let i = 0; i < 100; i++) {+ queue.add(i);+ }+ for (let i = 0; i < 42; i++) {+ expect(queue.read()).toBe(100 - 42 + i);+ }+ expect(queue.read()).toBeUndefined();+ });+});diff --git a/js/app/packages/websocket/tests/websocket-builder.test.ts b/js/app/packages/websocket/tests/websocket-builder.test.tsnew file mode 100644index 0000000000..a8f9ffd9e0--- /dev/null+++ b/js/app/packages/websocket/tests/websocket-builder.test.ts@@ -0,0 +1,793 @@+import { describe, expect, test, vi } from 'vitest';+import type {+ WebsocketBuffer,+ WebsocketEvent,+ WebsocketEventListenerWithOptions,+} from '../';+import { ArrayQueue, ConstantBackoff, Websocket, WebsocketBuilder } from '../';++describe('Testsuite for WebSocketBuilder', () => {+ const url = 'ws://localhost:8080';++ test('WebsocketBuilder should set url', () => {+ const builder = new WebsocketBuilder(url);+ expect(builder.url).toBe(url);++ const ws = builder.build();+ expect(ws.url).toBe(url);+ });++ test('WebsocketBuilder should set protocols', () => {+ const protocols = ['protocol1', 'protocol2'];++ const builder = new WebsocketBuilder(url).withProtocols(protocols);+ expect(builder.protocols).toBe(protocols);++ const ws = builder.build();+ expect(ws.protocols).toBe(protocols);+ });++ test('WebsocketBuilder should set protocols for subsequent calls', () => {+ const protocols1 = ['protocol1', 'protocol2'];+ const protocols2 = ['protocol3', 'protocol4'];++ const builder = new WebsocketBuilder(url)+ .withProtocols(protocols1)+ .withProtocols(protocols2);+ expect(builder.protocols).toBe(protocols2);++ const ws = builder.build();+ expect(ws.protocols).toBe(protocols2);+ });++ test('WebsocketBuilder should set max-retries', () => {+ const maxRetries = 42;++ const builder = new WebsocketBuilder(url).withMaxRetries(maxRetries);+ expect(builder.maxRetries).toBe(maxRetries);++ const ws = builder.build();+ expect(ws.maxRetries).toBe(maxRetries);+ });++ test('WebsocketBuilder should set max-retries for subsequent calls', () => {+ const maxRetries1 = 42;+ const maxRetries2 = 1337;++ const builder = new WebsocketBuilder(url)+ .withMaxRetries(maxRetries1)+ .withMaxRetries(maxRetries2);+ expect(builder.maxRetries).toBe(maxRetries2);++ const ws = builder.build();+ expect(ws.maxRetries).toBe(maxRetries2);+ });++ test('WebsocketBuilder should return undefined for max-retries if not set', () => {+ const builder = new WebsocketBuilder(url);+ expect(builder.maxRetries).toBeUndefined();++ const ws = builder.build();+ expect(ws.maxRetries).toBeUndefined();+ });++ test('WebsocketBuilder should set instant-reconnect', () => {+ const instantReconnect = true;++ const builder = new WebsocketBuilder(url).withInstantReconnect(+ instantReconnect+ );+ expect(builder.instantReconnect).toBe(instantReconnect);++ const ws = builder.build();+ expect(ws.instantReconnect).toBe(instantReconnect);+ });++ test('WebsocketBuilder should return undefined for instant-reconnect if not set', () => {+ const builder = new WebsocketBuilder(url);+ expect(builder.instantReconnect).toBeUndefined();++ const ws = builder.build();+ expect(ws.instantReconnect).toBeUndefined();+ });++ test('WebsocketBuilder should set backoff', () => {+ const backoff = new ConstantBackoff(42);++ const builder = new WebsocketBuilder(url).withBackoff(backoff);+ expect(builder.backoff).toBe(backoff);++ const ws = builder.build();+ expect(ws.backoff).toBe(backoff);+ });++ test('WebsocketBuilder should set backoff for subsequent calls', () => {+ const backoff1 = new ConstantBackoff(42);+ const backoff2 = new ConstantBackoff(1337);++ const builder = new WebsocketBuilder(url)+ .withBackoff(backoff1)+ .withBackoff(backoff2);+ expect(builder.backoff).toBe(backoff2);++ const ws = builder.build();+ expect(ws.backoff).toBe(backoff2);+ });++ test('WebsocketBuilder should return undefined for backoff if not set', () => {+ const builder = new WebsocketBuilder(url);+ expect(builder.backoff).toBeUndefined();++ const ws = builder.build();+ expect(ws.backoff).toBeUndefined();+ });++ test('WebsocketBuilder should set buffer', () => {+ const buffer: WebsocketBuffer = new ArrayQueue();++ const builder = new WebsocketBuilder(url).withBuffer(buffer);+ expect(builder.buffer).toBe(buffer);++ const ws = builder.build();+ expect(ws.buffer).toBe(buffer);+ });++ test('WebsocketBuilder should set buffer for subsequent calls', () => {+ const buffer1: WebsocketBuffer = new ArrayQueue();+ const buffer2: WebsocketBuffer = new ArrayQueue();++ const builder = new WebsocketBuilder(url)+ .withBuffer(buffer1)+ .withBuffer(buffer2);+ expect(builder.buffer).toBe(buffer2);++ const ws = builder.build();+ expect(ws.buffer).toBe(buffer2);+ });++ test('WebsocketBuilder should return undefined for buffer if not set', () => {+ const builder = new WebsocketBuilder(url);+ expect(builder.buffer).toBeUndefined();++ const ws = builder.build();+ expect(ws.buffer).toBeUndefined();+ });++ test("WebsocketBuilder should set 'open'-listener", () => {+ const listener = vi.fn();++ const builder = new WebsocketBuilder(url).onOpen(listener);+ expect(builder['_options']!['listeners']!.open).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Open>[]+ >([+ {+ listener,+ options: undefined,+ },+ ]);++ const ws = builder.build();+ expect(ws['_options']['listeners'].open).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Open>[]+ >([+ {+ listener,+ options: undefined,+ },+ ]);+ });++ test("WebsocketBuilder should set 'open'-listener for subsequent calls", () => {+ const listener1 = vi.fn();+ const listener2 = vi.fn();++ const builder = new WebsocketBuilder(url)+ .onOpen(listener1)+ .onOpen(listener2);+ expect(builder['_options']!['listeners']!.open).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Open>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options: undefined },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.open).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Open>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options: undefined },+ ]);+ });++ test("WebsocketBuilder should set 'open'-listener with options", () => {+ const listener = vi.fn();+ const options = { once: true };++ const builder = new WebsocketBuilder(url).onOpen(listener, options);+ expect(builder['_options']!['listeners']!.open).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Open>[]+ >([{ listener, options }]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.open).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Open>[]+ >([{ listener, options }]);+ });++ test("WebsocketBuilder should set 'open'-listener with mixed options", () => {+ const listener1 = vi.fn();+ const listener2 = vi.fn();+ const options = { once: true };++ const builder = new WebsocketBuilder(url)+ .onOpen(listener1)+ .onOpen(listener2, options);+ expect(builder['_options']!['listeners']!.open).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Open>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.open).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Open>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options },+ ]);+ });++ test("WebsocketBuilder should set 'close'-listener", () => {+ const listener = vi.fn();++ const builder = new WebsocketBuilder(url).onClose(listener);+ expect(builder['_options']!['listeners']!.close).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Close>[]+ >([+ {+ listener,+ options: undefined,+ },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.close).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Close>[]+ >([+ {+ listener,+ options: undefined,+ },+ ]);+ });++ test("WebsocketBuilder should set 'close'-listener for subsequent calls", () => {+ const listener1 = vi.fn();+ const listener2 = vi.fn();++ const builder = new WebsocketBuilder(url)+ .onClose(listener1)+ .onClose(listener2);+ expect(builder['_options']!['listeners']!.close).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Close>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options: undefined },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.close).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Close>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options: undefined },+ ]);+ });++ test("WebsocketBuilder should set 'close'-listener with options", () => {+ const listener = vi.fn();+ const options = { once: true };++ const builder = new WebsocketBuilder(url).onClose(listener, options);+ expect(builder['_options']!['listeners']!.close).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Close>[]+ >([+ {+ listener,+ options,+ },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.close).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Close>[]+ >([{ listener, options }]);+ });++ test("WebsocketBuilder should set 'close'-listener with mixed options", () => {+ const listener1 = vi.fn();+ const listener2 = vi.fn();+ const options = { once: true };++ const builder = new WebsocketBuilder(url)+ .onClose(listener1)+ .onClose(listener2, options);+ expect(builder['_options']!['listeners']!.close).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Close>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.close).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Close>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options },+ ]);+ });++ test("WebsocketBuilder should set 'error'-listener", () => {+ const listener = vi.fn();++ const builder = new WebsocketBuilder(url).onError(listener);+ expect(builder['_options']!['listeners']!.error).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Error>[]+ >([+ {+ listener,+ options: undefined,+ },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.error).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Error>[]+ >([+ {+ listener,+ options: undefined,+ },+ ]);+ });++ test("WebsocketBuilder should set 'error'-listener for subsequent calls", () => {+ const listener1 = vi.fn();+ const listener2 = vi.fn();++ const builder = new WebsocketBuilder(url)+ .onError(listener1)+ .onError(listener2);+ expect(builder['_options']!['listeners']!.error).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Error>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options: undefined },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.error).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Error>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options: undefined },+ ]);+ });++ test("WebsocketBuilder should set 'error'-listener with options", () => {+ const listener = vi.fn();+ const options = { once: true };++ const builder = new WebsocketBuilder(url).onError(listener, options);+ expect(builder['_options']!['listeners']!.error).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Error>[]+ >([+ {+ listener,+ options,+ },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.error).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Error>[]+ >([{ listener, options }]);+ });++ test("WebsocketBuilder should set 'error'-listener with mixed options", () => {+ const listener1 = vi.fn();+ const listener2 = vi.fn();+ const options = { once: true };++ const builder = new WebsocketBuilder(url)+ .onError(listener1)+ .onError(listener2, options);+ expect(builder['_options']!['listeners']!.error).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Error>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.error).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Error>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options },+ ]);+ });++ test("WebsocketBuilder should set 'message'-listener", () => {+ const listener = vi.fn();++ const builder = new WebsocketBuilder(url).onMessage(listener);+ expect(builder['_options']!['listeners']!.message).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Message>[]+ >([+ {+ listener,+ options: undefined,+ },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.message).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Message>[]+ >([+ {+ listener,+ options: undefined,+ },+ ]);+ });++ test("WebsocketBuilder should set 'message'-listener for subsequent calls", () => {+ const listener1 = vi.fn();+ const listener2 = vi.fn();++ const builder = new WebsocketBuilder(url)+ .onMessage(listener1)+ .onMessage(listener2);+ expect(builder['_options']!['listeners']!.message).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Message>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options: undefined },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.message).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Message>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options: undefined },+ ]);+ });++ test("WebsocketBuilder should set 'message'-listener with options", () => {+ const listener = vi.fn();+ const options = { once: true };++ const builder = new WebsocketBuilder(url).onMessage(listener, options);+ expect(builder['_options']!['listeners']!.message).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Message>[]+ >([+ {+ listener,+ options,+ },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.message).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Message>[]+ >([+ {+ listener,+ options,+ },+ ]);+ });++ test("WebsocketBuilder should set 'message'-listener with mixed options", () => {+ const listener1 = vi.fn();+ const listener2 = vi.fn();+ const options = { once: true };++ const builder = new WebsocketBuilder(url)+ .onMessage(listener1)+ .onMessage(listener2, options);+ expect(builder['_options']!['listeners']!.message).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Message>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.message).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Message>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options },+ ]);+ });++ test("WebsocketBuilder should set 'retry'-listener", () => {+ const listener = vi.fn();++ const builder = new WebsocketBuilder(url).onRetry(listener);+ expect(builder['_options']!['listeners']!.retry).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.retry>[]+ >([+ {+ listener,+ options: undefined,+ },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.retry).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.retry>[]+ >([+ {+ listener,+ options: undefined,+ },+ ]);+ });++ test("WebsocketBuilder should set 'retry'-listener for subsequent calls", () => {+ const listener1 = vi.fn();+ const listener2 = vi.fn();++ const builder = new WebsocketBuilder(url)+ .onRetry(listener1)+ .onRetry(listener2);+ expect(builder['_options']!['listeners']!.retry).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.retry>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options: undefined },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.retry).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.retry>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options: undefined },+ ]);+ });++ test("WebsocketBuilder should set 'retry'-listener with options", () => {+ const listener = vi.fn();+ const options = { once: true };++ const builder = new WebsocketBuilder(url).onRetry(listener, options);+ expect(builder['_options']!['listeners']!.retry).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.retry>[]+ >([+ {+ listener,+ options,+ },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.retry).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.retry>[]+ >([{ listener, options }]);+ });++ test("WebsocketBuilder should set 'retry'-listener with mixed options", () => {+ const listener1 = vi.fn();+ const listener2 = vi.fn();+ const options = { once: true };++ const builder = new WebsocketBuilder(url)+ .onRetry(listener1)+ .onRetry(listener2, options);+ expect(builder['_options']!['listeners']!.retry).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.retry>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.retry).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.retry>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options },+ ]);+ });++ test("WebsocketBuilder should set 'reconnect'-listener", () => {+ const listener = vi.fn();++ const builder = new WebsocketBuilder(url).onReconnect(listener);+ expect(builder['_options']!['listeners']!.reconnect).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Reconnect>[]+ >([+ {+ listener,+ options: undefined,+ },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.reconnect).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Reconnect>[]+ >([+ {+ listener,+ options: undefined,+ },+ ]);+ });++ test("WebsocketBuilder should set 'reconnect'-listener for subsequent calls", () => {+ const listener1 = vi.fn();+ const listener2 = vi.fn();++ const builder = new WebsocketBuilder(url)+ .onReconnect(listener1)+ .onReconnect(listener2);+ expect(builder['_options']!['listeners']!.reconnect).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Reconnect>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options: undefined },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.reconnect).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Reconnect>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options: undefined },+ ]);+ });++ test("WebsocketBuilder should set 'reconnect'-listener with options", () => {+ const listener = vi.fn();+ const options = { once: true };++ const builder = new WebsocketBuilder(url).onReconnect(listener, options);+ expect(builder['_options']!['listeners']!.reconnect).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Reconnect>[]+ >([+ {+ listener,+ options,+ },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.reconnect).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Reconnect>[]+ >([+ {+ listener,+ options,+ },+ ]);+ });++ test("WebsocketBuilder should set 'reconnect'-listener with mixed options", () => {+ const listener1 = vi.fn();+ const listener2 = vi.fn();+ const options = { once: true };++ const builder = new WebsocketBuilder(url)+ .onReconnect(listener1)+ .onReconnect(listener2, options);+ expect(builder['_options']!['listeners']!.reconnect).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Reconnect>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options },+ ]);++ const ws = builder.build();+ expect(ws['_options']!['listeners']!.reconnect).toStrictEqual<+ WebsocketEventListenerWithOptions<WebsocketEvent.Reconnect>[]+ >([+ {+ listener: listener1,+ options: undefined,+ },+ { listener: listener2, options },+ ]);+ });++ test('WebsocketBuilder should return a Websocket instance', () => {+ const builder = new WebsocketBuilder(url);+ const ws = builder.build();++ expect(ws).toBeInstanceOf(Websocket);+ });++ test("WebsocketBuilder should create new Websocket instances with subsequent 'build' calls", () => {+ const builder = new WebsocketBuilder(url);+ const ws1 = builder.build();+ const ws2 = builder.build();++ expect(ws1).not.toBe(ws2);+ });+});diff --git a/js/app/packages/websocket/tests/websocket-heartbeat.test.ts b/js/app/packages/websocket/tests/websocket-heartbeat.test.tsnew file mode 100644index 0000000000..7eff725d1a--- /dev/null+++ b/js/app/packages/websocket/tests/websocket-heartbeat.test.ts@@ -0,0 +1,172 @@+import {+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ expect,+ test,+} from 'vitest';+import {+ ConstantBackoff,+ type Websocket,+ WebsocketBuilder,+ WebsocketEvent,+ type WebsocketEventListenerParams,+} from '../';+import {+ startServerWithHeartbeat,+ stopClient,+ stopServer,+ type WebsocketServerWithHeartbeat,+} from './websocket-test-utils';++describe('Testsuite for Websocket with Heartbeat', () => {+ const serverTimeout: number = process.env.SERVER_TIMEOUT+ ? parseInt(process.env.SERVER_TIMEOUT)+ : 5_000;+ const clientTimeout: number = process.env.CLIENT_TIMEOUT+ ? parseInt(process.env.CLIENT_TIMEOUT)+ : 5_000;+ const testTimeout: number = process.env.TEST_TIMEOUT+ ? parseInt(process.env.TEST_TIMEOUT)+ : 10_000;++ let client: Websocket | undefined; // subject under test+ let server: WebsocketServerWithHeartbeat | undefined; // websocket server used for testing+ let url: string; // dynamically assigned based on server port++ /** Before all tests, log the test configuration. */+ beforeAll(() =>+ console.log(+ `Testing websocket with heartbeat, server timeout: ${serverTimeout}ms, client timeout: ${clientTimeout}ms`+ )+ );++ /** Before each test, start a websocket server on a random port. */+ beforeEach(async () => {+ await stopClient(client, clientTimeout).then(() => {+ client = undefined;+ });+ await stopServer(server, serverTimeout).then(() => {+ server = undefined;+ });+ await startServerWithHeartbeat(0, serverTimeout).then((s) => {+ server = s;+ const address = server.address();+ const port =+ typeof address === 'object' && address !== null ? address.port : 41338;+ url = `ws://localhost:${port}`;+ });+ }, testTimeout);++ /** After each test, stop the websocket server. */+ afterEach(async () => {+ await stopClient(client, clientTimeout).then(() => {+ client = undefined;+ });+ await stopServer(server, serverTimeout).then(() => {+ server = undefined;+ });+ }, testTimeout);++ test('Websocket should send pings on interval', async () => {+ let [heartbeatsSent, heartbeatsReceived] = [0, 0];+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Open>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .withBackoff(new ConstantBackoff(100)) // retry after 1 second+ .withMaxRetries(Infinity)+ .withHeartbeat({+ timeout: 100,+ interval: 100,+ pingMessage: 'ping',+ pongMessage: 'pong',+ maxMissedHeartbeats: 1,+ })+ .onHeartbeatSent((_, _e) => {+ heartbeatsSent++;+ })+ .onHeartbeatReceived((_, _e) => {+ heartbeatsReceived++;+ })+ .onOpen((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Open);+ });++ await new Promise((resolve) => setTimeout(resolve, 200));++ expect(heartbeatsSent).toBeGreaterThan(0);+ expect(heartbeatsReceived).toBeGreaterThan(0);+ });++ test('Websocket should dispatch heartbeatMissed and reconnect when pong not received within timeout', async () => {+ let [heartbeatsSent, heartbeatsReceived, heartbeatMissed] = [0, 0, 0];+ server?.setRespondToPings(false);+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Reconnect>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .withBackoff(new ConstantBackoff(1000))+ .withMaxRetries(Infinity)+ .withHeartbeat({+ timeout: 200,+ interval: 100,+ pingMessage: 'ping',+ pongMessage: 'pong',+ maxMissedHeartbeats: 3,+ })+ .onHeartbeatSent((_, _e) => {+ heartbeatsSent++;+ })+ .onHeartbeatReceived((_i, _ev) => {+ heartbeatsReceived++;+ })+ .onHeartbeatMissed((_i, _ev) => {+ heartbeatMissed++;+ })+ .onReconnect((instance, ev) => {+ resolve([instance, ev]);+ })+ .build();+ }+ ).then(([instance, _ev]) => {+ expect(instance).toBe(client);+ });+ expect(heartbeatsSent).toBeGreaterThan(3);+ expect(heartbeatsReceived).toBe(0);+ expect(heartbeatMissed).toBeGreaterThan(3);+ });++ test('Websocket should reset missed heartbeat counter on successful pong', async () => {+ const missedCounts: number[] = [];++ await new Promise<void>((resolve) => {+ client = new WebsocketBuilder(url)+ .withBackoff(new ConstantBackoff(100))+ .withMaxRetries(Infinity)+ .withHeartbeat({+ timeout: 100,+ interval: 100,+ pingMessage: 'ping',+ pongMessage: 'pong',+ maxMissedHeartbeats: 5,+ })+ .onOpen(() => server!.setRespondToPings(false))+ .onHeartbeatMissed((_, ev) => {+ missedCounts.push(ev.detail.missedHeartbeats);+ })+ .onReconnect(() => {+ server!.setRespondToPings(false);+ setTimeout(resolve, 300);+ })+ .build();+ });++ const restartIndex = missedCounts.lastIndexOf(1);+ expect(restartIndex).toBeGreaterThan(2);+ expect(missedCounts.slice(0, 3)).toEqual([1, 2, 3]);+ });+});diff --git a/js/app/packages/websocket/tests/websocket-test-utils.ts b/js/app/packages/websocket/tests/websocket-test-utils.tsnew file mode 100644index 0000000000..a35452fc2c--- /dev/null+++ b/js/app/packages/websocket/tests/websocket-test-utils.ts@@ -0,0 +1,174 @@+import { WebSocket, WebSocketServer } from 'ws';+import type { Websocket } from '../';+import { WebsocketEvent, type WebsocketEventListenerWithOptions } from '../';++/**+ * Creates a promise that will be rejected after the given amount of milliseconds. The error will be a TimeoutError.+ * @param ms the amount of milliseconds to wait before rejecting+ * @param msg an optional message to include in the error+ */+export const rejectAfter = (ms: number, msg?: string): Promise<void> =>+ new Promise((_, reject) =>+ setTimeout(+ () => reject(msg ? new Error(`Timeout: ${msg}`) : new Error(`Timeout`)),+ ms+ )+ );++/**+ * Stops the given websocket client.+ * @param client the websocket client to stop+ * @param timeout the amount of milliseconds to wait before rejecting+ */+export const stopClient = (+ client: Websocket | undefined,+ timeout: number+): Promise<void> =>+ new Promise<void>((resolve, reject) => {+ if (client === undefined) return resolve();+ if (client.underlyingWebsocket?.readyState === WebSocket.CLOSED)+ return resolve();+ rejectAfter(timeout, 'failed to stop client').catch((err) => reject(err));+ client.addEventListener(WebsocketEvent.Close, () => resolve(), {+ once: true,+ });+ client.close();+ });++/**+ * Starts a websocket server on the given port.+ * @param port the port to start the server on+ * @param timeout the amount of milliseconds to wait before rejecting+ */+export const startServer = (+ port: number,+ timeout: number+): Promise<WebSocketServer> =>+ new Promise((resolve, reject) => {+ rejectAfter(timeout, 'failed to start server').catch((err) => reject(err));+ const wss = new WebSocketServer({ port });+ wss.on('listening', () => resolve(wss));+ wss.on('error', (err) => reject(err));+ });++/**+ * Stops the given websocket server. This will terminate all connections.+ * @param wss the websocket server to stop+ * @param timeout the amount of milliseconds to wait before rejecting+ */+export const stopServer = (+ wss: WebSocketServer | undefined,+ timeout: number+): Promise<void> =>+ new Promise<void>((resolve, reject) => {+ if (wss === undefined) return resolve();+ rejectAfter(timeout, 'failed to stop server').catch((err) => reject(err));+ wss.clients.forEach((c) => c.terminate());+ wss.addListener('close', resolve);+ wss.close();+ });++/**+ * Waits for a client to connect to the given websocket server.+ *+ * @param wss the websocket server to wait for a client to connect to+ * @param timeout the amount of milliseconds to wait before rejecting+ */+export const waitForClientToConnectToServer = (+ wss: WebSocketServer | undefined,+ timeout: number+): Promise<WebSocket> =>+ new Promise<WebSocket>((resolve, reject) => {+ if (wss === undefined) return reject(new Error('wss is undefined'));+ rejectAfter(timeout, 'failed to wait for client to connect').catch((err) =>+ reject(err)+ );+ wss.on('connection', (client) => resolve(client));+ });++/**+ * Returns the listeners for the given event type on the given websocket client.+ *+ * @param client the websocket client to get the listeners from+ * @param type the event type to get the listeners for+ */+export const getListenersWithOptions = <K extends WebsocketEvent>(+ client: Websocket | undefined,+ type: K+): WebsocketEventListenerWithOptions<K>[] =>+ client === undefined ? [] : (client['_options']['listeners'][type] ?? []);++/**+ * Converts a websocket message to a string.+ *+ * @param message the message to convert to a string+ * @param isBinary whether the message is binary+ * @returns the message as a string+ */+export const wsMessageToString = (+ message: ArrayBuffer | Blob | Buffer | Buffer[],+ isBinary: boolean+): string => {+ if (isBinary) {+ throw new Error('Unexpected binary message');+ } else if (!(message instanceof Buffer)) {+ throw new Error('Unexpected message type');+ } else return message.toString('utf-8');+};++/**+ * Converts a websocket message to a string and calls the given handler.+ *+ * @param handler the handler to call with the message+ */+export const onStringMessageReceived =+ (handler: (str: string) => void) =>+ (message: ArrayBuffer | Blob | Buffer | Buffer[], isBinary: boolean) => {+ handler(wsMessageToString(message, isBinary));+ };++/**+ * Closes the given websocket server and terminates all connections.+ *+ * @param wss the websocket server to close+ */+export const closeServer = (wss: WebSocketServer | undefined) => {+ if (wss === undefined) return;+ wss.clients.forEach((client) => client.terminate());+ wss.close();+};++export type WebsocketServerWithHeartbeat = WebSocketServer & {+ setRespondToPings: (value: boolean) => void;+};++/**+ * Starts a websocket server on the given port.+ * @param port the port to start the server on+ * @param timeout the amount of milliseconds to wait before rejecting+ */+export const startServerWithHeartbeat = (+ port: number,+ timeout: number+): Promise<WebsocketServerWithHeartbeat> =>+ new Promise((resolve, reject) => {+ rejectAfter(timeout, 'failed to start server').catch((err) => reject(err));+ const wss = new WebSocketServer({ port });++ let respondToPings = true;++ wss.on('connection', (ws) => {+ ws.on('message', (message) => {+ if (message.toString() === 'ping' && respondToPings) {+ ws.send('pong');+ }+ });+ });++ (wss as any).setRespondToPings = (value: boolean) => {+ respondToPings = value;+ };++ wss.on('listening', () => resolve(wss as any));+ wss.on('error', (err) => reject(err));+ });diff --git a/js/app/packages/websocket/tests/websocket.test.ts b/js/app/packages/websocket/tests/websocket.test.tsnew file mode 100644index 0000000000..5b89a49b18--- /dev/null+++ b/js/app/packages/websocket/tests/websocket.test.ts@@ -0,0 +1,994 @@+import { untilEvent } from '@websocket/utils/until-event';+import {+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ expect,+ test,+} from 'vitest';+import type { WebSocketServer } from 'ws';+import type { WebsocketBuffer } from '../';+import {+ ArrayQueue,+ type Backoff,+ ConstantBackoff,+ Websocket,+ WebsocketBuilder,+ WebsocketEvent,+ type WebsocketEventListenerParams,+} from '../';+import { JsonSerializer } from '../core/serializers/json-serializer';+import {+ closeServer,+ getListenersWithOptions,+ onStringMessageReceived,+ startServer,+ stopClient,+ stopServer,+ waitForClientToConnectToServer,+} from './websocket-test-utils';++describe('Testsuite for Websocket', () => {+ const port: number = process.env.PORT ? parseInt(process.env.PORT) : 41337;+ const url: string = process.env.URL ?? `ws://localhost:${port}`;+ const serverTimeout: number = process.env.SERVER_TIMEOUT+ ? parseInt(process.env.SERVER_TIMEOUT)+ : 5_000;+ const clientTimeout: number = process.env.CLIENT_TIMEOUT+ ? parseInt(process.env.CLIENT_TIMEOUT)+ : 5_000;+ const testTimeout: number = process.env.TEST_TIMEOUT+ ? parseInt(process.env.TEST_TIMEOUT)+ : 10_000;++ let client: Websocket | undefined; // subject under test+ let server: WebSocketServer | undefined; // websocket server used for testing++ /** Before all tests, log the test configuration. */+ beforeAll(() =>+ console.log(+ `Testing websocket on ${url}, server timeout: ${serverTimeout}ms, client timeout: ${clientTimeout}ms`+ )+ );++ /** Before each test, start a websocket server on the given port. */+ beforeEach(async () => {+ await startServer(port, serverTimeout).then((s) => {+ server = s;+ });+ }, testTimeout);++ /** After each test, stop the websocket server. */+ afterEach(async () => {+ await stopClient(client, clientTimeout).then(() => {+ client = undefined;+ });+ await stopServer(server, serverTimeout).then(() => {+ server = undefined;+ });+ }, testTimeout);++ describe('Getter/setter tests', () => {+ describe('Url', () => {+ test('Websocket should return the correct url', () => {+ const client = new Websocket(url);+ expect(client.url).toBe(url);+ });+ });++ describe('Protocols', () => {+ test('Websocket should return the correct protocols when protocols are a string', () => {+ const protocols = 'protocol1';+ const client = new Websocket(url, protocols);+ expect(client.protocols).toEqual(protocols);+ });++ test('Websocket should return the correct protocols when protocols are an array', () => {+ const protocols = ['protocol1', 'protocol2'];+ const client = new Websocket(url, protocols);+ expect(client.protocols).toEqual(protocols);+ });++ test('Websocket should return the correct protocols when protocols are undefined', () => {+ const client = new Websocket(url);+ expect(client.protocols).toBeUndefined();+ });+ });++ describe('Buffer', () => {+ test('Websocket should return the correct buffer when buffer is undefined', () => {+ const client = new Websocket(url);+ expect(client.buffer).toBeUndefined();+ });++ test('Websocket should return the correct buffer when buffer is set', () => {+ const buffer: WebsocketBuffer = new ArrayQueue();+ const client = new Websocket(url, undefined, { buffer });+ expect(client.buffer).toBe(buffer);+ });+ });++ describe('MaxRetries', () => {+ test('Websocket should return the correct maxRetries when maxRetries is undefined', () => {+ const client = new Websocket(url);+ expect(client.maxRetries).toBeUndefined();+ });++ test('Websocket should return the correct maxRetries when maxRetries is set', () => {+ const maxRetries = 5;+ const client = new Websocket(url, undefined, { retry: { maxRetries } });+ expect(client.maxRetries).toBe(maxRetries);+ });+ });++ describe('InstantReconnect', () => {+ test('Websocket should return the correct instantReconnect when instantReconnect is undefined', () => {+ const client = new Websocket(url);+ expect(client.instantReconnect).toBeUndefined();+ });++ test('Websocket should return the correct instantReconnect when instantReconnect is set', () => {+ const instantReconnect = true;+ const client = new Websocket(url, undefined, {+ retry: { instantReconnect },+ });+ expect(client.instantReconnect).toBe(instantReconnect);+ });+ });++ describe('Backoff', () => {+ test('Websocket should return the correct backoff when backoff is undefined', () => {+ const client = new Websocket(url);+ expect(client.backoff).toBeUndefined();+ });++ test('Websocket should return the correct backoff when backoff is set', () => {+ const backoff: Backoff = new ConstantBackoff(1000);+ const client = new Websocket(url, undefined, { retry: { backoff } });+ expect(client.backoff).toBe(backoff);+ });+ });++ describe('ClosedByUser', () => {+ test('Websocket should return false after initialization', () => {+ const client = new Websocket(url);+ expect(client.closedByUser).toBe(false);+ });++ test('Websocket should return true after the client closes the connection', async () => {+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Close>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen((instance) => instance.close())+ .onClose((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Close);+ expect(instance.closedByUser).toBe(true);+ });+ });++ test('Websocket should return false if the server closes the connection', async () => {+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Close>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen(() => closeServer(server))+ .onClose((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Close);+ expect(instance.closedByUser).toBe(false);+ });+ });+ });++ describe('LastConnection', () => {+ test('Websocket should return undefined after initialization', () => {+ const client = new Websocket(url);+ expect(client.lastConnection).toBeUndefined();+ });++ test('Websocket should return the correct date after the client connects to the server', async () => {+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Open>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Open);+ expect(instance.lastConnection).not.toBeUndefined();+ });+ });+ });++ describe('UnderlyingWebsocket', () => {+ test('Websocket should return native websocket after initialization', async () => {+ const client = new Websocket(url);+ await untilEvent(client, WebsocketEvent.UrlResolved);+ expect(client.underlyingWebsocket).not.toBeUndefined();+ expect(client.underlyingWebsocket).toBeInstanceOf(WebSocket);+ });++ test('Websocket should return the underlying websocket after the client connects to the server', async () => {+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Open>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Open);+ expect(instance.underlyingWebsocket).not.toBeUndefined();+ expect(instance.underlyingWebsocket).toBeInstanceOf(WebSocket);+ });+ });++ test('Websocket should return the underlying websocket after the client closes the connection', async () => {+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Close>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen((instance) => instance.close())+ .onClose((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Close);+ expect(instance.underlyingWebsocket).not.toBeUndefined();+ expect(instance.underlyingWebsocket).toBeInstanceOf(WebSocket);+ expect(instance.underlyingWebsocket!.readyState).toBe(+ WebSocket.CLOSED+ );+ });+ });++ test('Websocket should return the underlying websocket after the server closes the connection', async () => {+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Close>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen(() => closeServer(server))+ .onClose((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Close);+ expect(instance.underlyingWebsocket).not.toBeUndefined();+ expect(instance.underlyingWebsocket).toBeInstanceOf(WebSocket);+ expect(instance.underlyingWebsocket!.readyState).toBe(+ WebSocket.CLOSED+ );+ });+ });+ });++ describe('ReadyState', () => {+ test('Websocket should return the correct readyState after initialization', async () => {+ const client = new Websocket(url);+ await untilEvent(client, WebsocketEvent.UrlResolved);+ expect(client.readyState).toBe(WebSocket.CONNECTING);+ });++ test('Websocket should return the correct readyState after the client connects to the server', async () => {+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Open>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Open);+ expect(instance.readyState).toBe(WebSocket.OPEN);+ });+ });++ test('Websocket should return the correct readyState after the client closes the connection', async () => {+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Close>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen((instance) => instance.close())+ .onClose((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Close);+ expect(instance.readyState).toBe(WebSocket.CLOSED);+ });+ });+ });++ describe('BufferedAmount', () => {+ test('Websocket should return the correct bufferedAmount after initialization', async () => {+ const client = new Websocket(url);+ await untilEvent(client, WebsocketEvent.UrlResolved);+ expect(client.bufferedAmount).toBe(0);+ });+ });++ describe('Extensions', () => {+ test('Websocket should return the correct extensions after initialization', async () => {+ const client = new Websocket(url);+ await untilEvent(client, WebsocketEvent.UrlResolved);+ expect(client.extensions).toBe('');+ });+ });++ describe('BinaryType', () => {+ test('Websocket should return the correct binaryType after initialization', () => {+ const client = new Websocket(url);+ expect(client.binaryType).toBe('blob');+ });++ test('Websocket should return the correct binaryType after setting it', () => {+ const client = new Websocket(url);+ client.binaryType = 'arraybuffer';+ expect(client.binaryType).toBe('arraybuffer');+ });+ });+ });++ describe('Event tests', () => {+ describe('Open', () => {+ test(+ "Websocket should fire 'open' when connecting to a server and the underlying websocket should be in readyState 'OPEN'",+ async () => {+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Open>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Open);+ expect(instance.underlyingWebsocket).not.toBeUndefined();+ expect(instance.underlyingWebsocket!.readyState).toBe(+ WebSocket.OPEN+ );+ });+ },+ testTimeout+ );++ test("Websocket should fire 'open' when reconnecting to a server and the underlying websocket should be in readyState 'OPEN'", async () => {+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Open>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .withBackoff(new ConstantBackoff(0))+ .onOpen((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Open);+ expect(instance.underlyingWebsocket).not.toBeUndefined();+ expect(instance.underlyingWebsocket!.readyState).toBe(WebSocket.OPEN);+ });+ });++ test("Websocket shouldn't fire 'open' when it was removed from the event listeners", async () => {+ let timesOpenFired = 0;+ const onOpen = () => timesOpenFired++;++ const clientConnectionPromise = waitForClientToConnectToServer(+ server,+ clientTimeout+ );++ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Open>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .withBackoff(new ConstantBackoff(100)) // try to reconnect after 100ms, 'open' should only fire once+ .onOpen(+ (i, ev) => {+ timesOpenFired++;+ resolve([i, ev]);+ },+ { once: true }+ ) // initial 'open' event, should only fire once+ .build();+ }+ );++ // this resolves after the client has connected to the server, disconnect it right after+ await clientConnectionPromise;+ expect(timesOpenFired).toBe(1);+ expect(+ getListenersWithOptions(client, WebsocketEvent.Open)+ ).toHaveLength(0); // since the initial listener was a 'once'-listener, this should be empty+ client!.addEventListener(WebsocketEvent.Open, onOpen); // add a new listener+ expect(+ getListenersWithOptions(client, WebsocketEvent.Open)+ ).toHaveLength(1); // since the initial listener was a 'once'-listener, this should be empty+ server?.clients.forEach((c) => c.close());++ // wait for the client to reconnect after 100ms+ await waitForClientToConnectToServer(server, clientTimeout);+ await new Promise((resolve) => setTimeout(resolve, 100)); // wait some extra time for client-side event to be fired+ expect(timesOpenFired).toBe(2);+ expect(+ getListenersWithOptions(client, WebsocketEvent.Open)+ ).toHaveLength(1); // since the initial listener was a 'once'-listener, this should be empty++ // remove the event-listener, disconnect again+ client!.removeEventListener(WebsocketEvent.Open, onOpen);+ expect(+ getListenersWithOptions(client, WebsocketEvent.Open)+ ).toHaveLength(0);+ server?.clients.forEach((c) => c.close());++ // wait for the client to reconnect after 100ms, 'open' should not fire again and timesOpenFired will still be 2+ await waitForClientToConnectToServer(server, clientTimeout);+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(timesOpenFired).toBe(2);+ });+ });++ describe('Close', () => {+ test(+ "Websocket should fire 'close' when the server closes the connection and the underlying websocket should be in readyState 'CLOSED'",+ async () => {+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Close>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen(() => closeServer(server))+ .onClose((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Close);+ expect(instance.closedByUser).toBe(false);+ expect(instance.underlyingWebsocket).not.toBeUndefined();+ expect(instance.underlyingWebsocket!.readyState).toBe(+ WebSocket.CLOSED+ );+ });+ },+ testTimeout+ );++ test("Websocket should fire 'close' when the client closes the connection and the underlying websocket should be in readyState 'CLOSED'", async () => {+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Close>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen((instance) => instance.close())+ .onClose((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Close);+ expect(instance.closedByUser).toBe(true);+ expect(instance.underlyingWebsocket).not.toBeUndefined();+ expect(instance.underlyingWebsocket!.readyState).toBe(+ WebSocket.CLOSED+ );+ });+ });++ test("Websocket should fire 'close' when the server closes the connection with a status code other than 1000 and the underlying websocket should be in readyState 'CLOSED'", async () => {+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Close>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen(() =>+ server?.clients.forEach((client) =>+ client.close(1001, 'CLOSE_GOING_AWAY')+ )+ )+ .onClose((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Close);+ expect(ev.code).toBe(1001);+ expect(ev.reason).toBe('CLOSE_GOING_AWAY');+ expect(ev.wasClean).toBe(true);+ expect(instance.closedByUser).toBe(false);+ expect(instance.underlyingWebsocket).not.toBeUndefined();+ expect(instance.underlyingWebsocket!.readyState).toBe(+ WebSocket.CLOSED+ );+ });+ });++ test("Websocket should fire 'close' when the client closes the connection with a status code other than 1000 and the underlying websocket should be in readyState 'CLOSED'", async () => {+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Close>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen((instance) =>+ instance.close(4000, 'APPLICATION_IS_SHUTTING_DOWN')+ )+ .onClose((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Close);+ expect(ev.code).toBe(4000);+ expect(ev.reason).toBe('APPLICATION_IS_SHUTTING_DOWN');+ expect(ev.wasClean).toBe(true);+ expect(instance.closedByUser).toBe(true);+ expect(instance.underlyingWebsocket).not.toBeUndefined();+ expect(instance.underlyingWebsocket!.readyState).toBe(+ WebSocket.CLOSED+ );+ });+ });+ });++ describe('Error', () => {+ test("Websocket should fire 'error' when the server rejects the connection and the underlying websocket should be in readyState 'CLOSED", async () => {+ await stopServer(server, serverTimeout).then(() => {+ server = undefined;+ });+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Error>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onError((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Error);+ expect(instance.underlyingWebsocket).not.toBeUndefined();+ expect(instance.underlyingWebsocket!.readyState).toBe(+ WebSocket.CLOSED+ );+ });+ });+ });++ describe('Message', () => {+ test("Websocket should fire 'message' when the server sends a message", async () => {+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Message>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen(() =>+ server?.clients.forEach((client) => client.send('Hello'))+ )+ .onMessage((instance, ev) => {+ expect(ev.data).toBe('Hello');+ resolve([instance, ev]);+ })+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Message);+ expect(ev.data).toBe('Hello');+ });+ });+ });++ describe('Retry & Reconnect', () => {+ test("Websocket should not emit 'retry' on the first connection attempt, emit it when retrying and emit 'reconnect' when it reconnects", async () => {+ let [openCount, retryCount, reconnectCount] = [0, 0, 0];+ const onOpen = () => openCount++;+ const onRetry = () => retryCount++;+ const onReconnect = () => reconnectCount++;++ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Open>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .withBackoff(new ConstantBackoff(0)) // immediately retry+ .onOpen((instance, ev) => resolve([instance, ev]))+ .onOpen(onOpen)+ .onRetry(onRetry)+ .onReconnect(onReconnect)+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Open);+ });++ // give some time for all handlers to be called+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(openCount).toBe(1);+ expect(retryCount).toBe(0);+ expect(reconnectCount).toBe(0);++ // disconnect all clients and give some time for the retry to happen+ server?.clients.forEach((client) => client.close());+ await new Promise((resolve) => setTimeout(resolve, 100));++ // ws should have retried & reconnect+ expect(openCount).toBe(2);+ expect(retryCount).toBe(1);+ expect(reconnectCount).toBe(1);+ });+ });+ });++ describe('Reconnect behaviour', () => {+ describe('InstantReconnect', () => {+ test('Websocket should try to reconnect immediately when instantReconnect is true', async () => {+ let [openCount, retryCount, reconnectCount] = [0, 0, 0];+ const onOpen = () => openCount++;+ const onRetry = () => retryCount++;+ const onReconnect = () => reconnectCount++;++ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Open>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .withBackoff(new ConstantBackoff(1000)) // retry after 1 second+ .withInstantReconnect(true) // reconnect immediately, don't wait for the backoff for the first retry+ .onOpen((instance, ev) => resolve([instance, ev]))+ .onOpen(onOpen)+ .onRetry(onRetry)+ .onReconnect(onReconnect)+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Open);+ });++ // give some time for all handlers to be called+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(openCount).toBe(1);+ expect(retryCount).toBe(0);+ expect(reconnectCount).toBe(0);++ // disconnect all clients and give some time for the retry to happen+ server?.clients.forEach((client) => client.close());+ await new Promise((resolve) => setTimeout(resolve, 100));++ // ws should have retried & reconnect+ expect(openCount).toBe(2);+ expect(retryCount).toBe(1);+ expect(reconnectCount).toBe(1);+ });++ test('Websocket should not try to reconnect immediately when instantReconnect is false', async () => {+ let [openCount, retryCount, reconnectCount] = [0, 0, 0];+ const onOpen = () => openCount++;+ const onRetry = () => retryCount++;+ const onReconnect = () => reconnectCount++;++ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Open>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .withBackoff(new ConstantBackoff(1000)) // retry after 1 second+ .withInstantReconnect(false) // reconnect immediately, don't wait for the backoff for the first retry+ .onOpen((instance, ev) => resolve([instance, ev]))+ .onOpen(onOpen)+ .onRetry(onRetry)+ .onReconnect(onReconnect)+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Open);+ });++ // give some time for all handlers to be called+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(openCount).toBe(1);+ expect(retryCount).toBe(0);+ expect(reconnectCount).toBe(0);++ // disconnect all clients and give some time for the retry to happen+ server?.clients.forEach((client) => client.close());+ await new Promise((resolve) => setTimeout(resolve, 100));++ // ws shouldn't have retried & reconnect+ expect(openCount).toBe(1);+ expect(retryCount).toBe(0);+ expect(reconnectCount).toBe(0);++ // give some time for the retry to happen+ await new Promise((resolve) => setTimeout(resolve, 1000));+ expect(openCount).toBe(2);+ expect(retryCount).toBe(1);+ expect(reconnectCount).toBe(1);+ });+ });++ describe('MaxRetries', () => {+ test('Websocket should stop trying to reconnect when maxRetries is reached', async () => {+ let [openCount, retryCount, reconnectCount] = [0, 0, 0];+ const onOpen = () => openCount++;+ const onRetry = () => retryCount++;+ const onReconnect = () => reconnectCount++;++ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Open>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .withBackoff(new ConstantBackoff(0)) // retry after 1 second+ .withMaxRetries(5) // retry 5 times+ .onOpen((instance, ev) => resolve([instance, ev]))+ .onOpen(onOpen)+ .onRetry(onRetry)+ .onReconnect(onReconnect)+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Open);+ });++ // give some time for all handlers to be called+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(openCount).toBe(1);+ expect(retryCount).toBe(0);+ expect(reconnectCount).toBe(0);++ // stop server so that the client can't reconnect+ await stopServer(server, serverTimeout);+ await new Promise((resolve) => setTimeout(resolve, 100));++ // ws should have retried but not reconnect+ expect(openCount).toBe(1);+ expect(retryCount).toBe(5);+ expect(reconnectCount).toBe(0);+ });+ });+ });++ describe('Send', () => {+ test('Websocket should send a message to the server and the server should receive it', async () => {+ const serverReceivedMessage = new Promise<string>((resolve) => {+ server?.on('connection', (client) => {+ client?.on(+ 'message',+ onStringMessageReceived((str: string) => {+ resolve(str);+ })+ );+ });+ });++ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Open>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen((instance, ev) => {+ instance.send('Hello');+ resolve([instance, ev]);+ })+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Open);+ expect(instance.underlyingWebsocket).not.toBeUndefined();+ expect(instance.underlyingWebsocket!.readyState).toBe(WebSocket.OPEN);+ });++ await serverReceivedMessage.then((message) =>+ expect(message).toBe('Hello')+ );+ });++ test('Websocket should send a message to the server and the server should receive it as a Uint8Array', async () => {+ const serverReceivedMessage = new Promise<Uint8Array>((resolve) => {+ server?.on('connection', (client) => {+ client?.on('message', (message: Uint8Array) => {+ resolve(message);+ });+ });+ });++ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Open>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen((instance, ev) => {+ instance.send(new Uint8Array([1, 2, 3]));+ resolve([instance, ev]);+ })+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Open);+ expect(instance.underlyingWebsocket).not.toBeUndefined();+ expect(instance.underlyingWebsocket!.readyState).toBe(WebSocket.OPEN);+ });++ await serverReceivedMessage.then((message) => {+ expect(Buffer.from(message).equals(Buffer.from([1, 2, 3]))).toBe(true);+ });+ });++ test('Websocket should buffer messages sent before the connection is open and send them when the connection is open', async () => {+ const messagesReceived: string[] = [];+ const serverReceivedMessages = new Promise<string[]>((resolve) => {+ server?.on('connection', (client) => {+ client?.on(+ 'message',+ onStringMessageReceived((str: string) => {+ messagesReceived.push(str);+ if (messagesReceived.length === 2) {+ resolve(messagesReceived);+ }+ })+ );+ });+ });++ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Open>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .withBuffer(new ArrayQueue())+ .onOpen((instance, ev) => {+ setTimeout(() => {+ instance.send('Hello2');+ resolve([instance, ev]);+ }, 100);+ })+ .build();+ client.send('Hello1'); // This message should be buffered+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Open);+ expect(instance.underlyingWebsocket).not.toBeUndefined();+ expect(instance.underlyingWebsocket!.readyState).toBe(WebSocket.OPEN);+ });++ await serverReceivedMessages.then((messages) => {+ expect(messages).toEqual(['Hello1', 'Hello2']);+ });+ });++ test('Websocket send should short circuit if the websocket was closed by user', async () => {+ await new Promise<WebsocketEventListenerParams<WebsocketEvent.Open>>(+ (resolve) => {+ client = new WebsocketBuilder(url)+ .onOpen((instance, ev) => resolve([instance, ev]))+ .build();+ }+ ).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Open);+ expect(instance.underlyingWebsocket).not.toBeUndefined();+ expect(instance.underlyingWebsocket!.readyState).toBe(WebSocket.OPEN);++ // close the websocket and send a message+ instance.close();+ instance.send('This send should short circuit');+ });+ });+ });++ describe('Send/Receive with serializer', () => {+ test('Websocket should send a message to the server and the server should receive it', async () => {+ let client: Websocket<Record<any, any>, Record<any, any>> | undefined;+ const serverReceivedMessage = new Promise<string>((resolve) => {+ server?.on('connection', (client) => {+ client?.on(+ 'message',+ onStringMessageReceived((str: string) => {+ resolve(str);+ })+ );+ });+ });++ await new Promise<+ WebsocketEventListenerParams<+ WebsocketEvent.Open,+ Record<any, any>,+ Record<any, any>+ >+ >((resolve) => {+ client = new WebsocketBuilder(url)+ .withSerializer(+ new JsonSerializer<Record<any, any>, Record<any, any>>()+ )+ .onOpen((instance, ev) => {+ instance.send({ message: 'Hello' });+ resolve([instance, ev]);+ })+ .build();+ }).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Open);+ });++ await serverReceivedMessage.then((message) =>+ expect(message).toBe(JSON.stringify({ message: 'Hello' }))+ );+ stopClient(client as any, clientTimeout);+ });++ test('Websocket should buffer messages sent before the connection is open and send them when the connection is open', async () => {+ let client: Websocket<Record<any, any>, Record<any, any>> | undefined;+ const messagesReceived: string[] = [];+ const serverReceivedMessages = new Promise<string[]>((resolve) => {+ server?.on('connection', (client) => {+ client?.on(+ 'message',+ onStringMessageReceived((str: string) => {+ messagesReceived.push(str);+ if (messagesReceived.length === 2) {+ resolve(messagesReceived);+ }+ })+ );+ });+ });++ await new Promise<+ WebsocketEventListenerParams<+ WebsocketEvent.Open,+ Record<any, any>,+ Record<any, any>+ >+ >((resolve) => {+ client = new WebsocketBuilder(url)+ .withSerializer(+ new JsonSerializer<Record<any, any>, Record<any, any>>()+ )+ .withBuffer(new ArrayQueue())+ .onOpen((instance, ev) => {+ setTimeout(() => {+ instance.send({ message: 'Hello2' });+ resolve([instance, ev]);+ }, 100);+ })+ .build();+ client.send({ message: 'Hello1' }); // This message should be buffered+ }).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Open);+ expect(instance.underlyingWebsocket).not.toBeUndefined();+ expect(instance.underlyingWebsocket!.readyState).toBe(WebSocket.OPEN);+ });++ await serverReceivedMessages.then((messages) => {+ expect(messages).toEqual([+ JSON.stringify({ message: 'Hello1' }),+ JSON.stringify({ message: 'Hello2' }),+ ]);+ });++ stopClient(client as any, clientTimeout);+ });++ test('Websocket client should receive deserialized messages correctly', async () => {+ let client: Websocket<Record<any, any>, Record<any, any>> | undefined;++ await new Promise<+ WebsocketEventListenerParams<+ WebsocketEvent.Open,+ Record<any, any>,+ Record<any, any>+ >+ >((resolve) => {+ client = new WebsocketBuilder(url)+ .withSerializer(+ new JsonSerializer<Record<any, any>, Record<any, any>>()+ )+ .onOpen(() => {+ server?.clients.forEach((c) => {+ c.send(JSON.stringify({ message: 'Hello' }));+ });+ })+ .onMessage((instance, ev) => {+ console.log('ev', ev.data);+ expect(ev.data).toEqual({ message: 'Hello' });+ resolve([instance, ev]);+ })+ .build();+ }).then(([instance, ev]) => {+ expect(instance).toBe(client);+ expect(ev.type).toBe(WebsocketEvent.Message);+ });++ stopClient(client as any, clientTimeout);+ });+ });+});diff --git a/js/app/packages/websocket/tsconfig.json b/js/app/packages/websocket/tsconfig.jsonindex 4f9992d657..db1fa1ca9b 100644--- a/js/app/packages/websocket/tsconfig.json+++ b/js/app/packages/websocket/tsconfig.json@@ -9,5 +9,5 @@"isolatedModules": true,"skipLibCheck": true,"moduleResolution": "bundler"- },+ }}diff --git a/js/app/packages/websocket/utils/until-event.ts b/js/app/packages/websocket/utils/until-event.tsnew file mode 100644index 0000000000..f9ba4b953b--- /dev/null+++ b/js/app/packages/websocket/utils/until-event.ts@@ -0,0 +1,40 @@+import {+ type Websocket,+ WebsocketEvent,+ type WebsocketEventMap,+} from '@websocket';++/**+ * Waits for a specific websocket event to be emitted.+ *+ * @param ws The websocket to wait for the event on.+ * @param event The event to wait for.+ * @returns A promise that resolves with the event data when the event is emitted.+ */+export async function untilEvent<Send, Receive, K extends WebsocketEvent>(+ ws: Websocket<Send, Receive>,+ event: K+) {+ return new Promise((resolve, reject) => {+ const cleanup = () => {+ ws.removeEventListener(event, handler);+ ws.removeEventListener(WebsocketEvent.Close, closeHandler);+ };++ const handler = (+ _ws: Websocket<Send, Receive>,+ e: WebsocketEventMap<Receive>[typeof event]+ ) => {+ cleanup();+ resolve(e);+ };++ const closeHandler = () => {+ cleanup();+ reject(new Error('WebSocket closed before event'));+ };++ ws.addEventListener(event, handler);+ ws.addEventListener(WebsocketEvent.Close, closeHandler);+ });+}diff --git a/js/app/packages/websocket/utils/until-message.ts b/js/app/packages/websocket/utils/until-message.tsnew file mode 100644index 0000000000..5e7a07e77f--- /dev/null+++ b/js/app/packages/websocket/utils/until-message.ts@@ -0,0 +1,43 @@+import {+ type Websocket,+ WebsocketEvent,+ type WebsocketEventMap,+} from '@websocket';++/**+ * Waits for a message to be received from the websocket.+ *+ * @param ws The websocket to wait for a message on.+ * @param predicate A predicate function that returns true if the message should be considered a match.+ * @returns A promise that resolves with the received message.+ */+export function untilMessage<Send, Receive>(+ ws: Websocket<Send, Receive>,+ predicate: (data: Receive) => boolean+): Promise<Receive> {+ return new Promise((resolve, reject) => {+ const cleanup = () => {+ ws.removeEventListener(WebsocketEvent.Message, handler);+ ws.removeEventListener(WebsocketEvent.Close, closeHandler);+ };++ const handler = (+ _ws: Websocket<Send, Receive>,+ e: WebsocketEventMap<Receive>[WebsocketEvent.Message]+ ) => {+ const data = e.data;+ if (predicate(data)) {+ cleanup();+ resolve(data);+ }+ };++ const closeHandler = () => {+ cleanup();+ reject(new Error('WebSocket closed before message received'));+ };++ ws.addEventListener(WebsocketEvent.Message, handler);+ ws.addEventListener(WebsocketEvent.Close, closeHandler);+ });+}diff --git a/js/app/packages/websocket/vitest.config.ts b/js/app/packages/websocket/vitest.config.tsnew file mode 100644index 0000000000..0402f959a1--- /dev/null+++ b/js/app/packages/websocket/vitest.config.ts@@ -0,0 +1,20 @@+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import tsconfigPaths from 'vite-tsconfig-paths';+import { defineConfig } from 'vitest/config';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);++export default defineConfig({+ plugins: [+ tsconfigPaths({+ root: '../../',+ }),+ ],+ test: {+ environment: 'node',+ globals: true,+ setupFiles: [resolve(__dirname, './vitest.setup.ts')],+ },+});diff --git a/js/app/packages/websocket/vitest.setup.ts b/js/app/packages/websocket/vitest.setup.tsnew file mode 100644index 0000000000..6567f4e072--- /dev/null+++ b/js/app/packages/websocket/vitest.setup.ts@@ -0,0 +1,25 @@+import { WebSocket } from 'ws';++// Polyfill WebSocket for Node.js environment+if (typeof globalThis.WebSocket === 'undefined') {+ globalThis.WebSocket = WebSocket as any;+}++// Polyfill CloseEvent for Node.js environment+if (typeof globalThis.CloseEvent === 'undefined') {+ globalThis.CloseEvent = class CloseEvent extends Event {+ code: number;+ reason: string;+ wasClean: boolean;++ constructor(+ type: string,+ eventInitDict?: { code?: number; reason?: string; wasClean?: boolean }+ ) {+ super(type);+ this.code = eventInitDict?.code ?? 1000;+ this.reason = eventInitDict?.reason ?? '';+ this.wasClean = eventInitDict?.wasClean ?? true;+ }+ } as any;+}diff --git a/js/app/packages/websocket/websocket.test.ts b/js/app/packages/websocket/websocket.test.tsdeleted file mode 100644index b3884d9cc2..0000000000--- a/js/app/packages/websocket/websocket.test.ts+++ /dev/null@@ -1,886 +0,0 @@-import { Server as MockServer } from 'mock-socket';-import { createRoot } from 'solid-js';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import {- bebopPlugin,- createDurableSocket,- createWebsocketEventEffect,- createWebsocketEventEffects,- heartbeatPlugin,- jsonPlugin,-} from '.';--const advance = async (ms: number) => {- await vi.advanceTimersByTimeAsync(ms);-};--const HANDSHAKE_DELAY = 100;-const handshake = () => advance(HANDSHAKE_DELAY);--const now = () => Date.now();--const getRandomPort = () =>- Math.floor(Math.random() * (65535 - 1024 + 1)) + 1024;--const getMockServer = (port?: number): [string, MockServer] => {- const wsPort = port ?? getRandomPort();- const url = `ws://localhost:${wsPort}`;- return [url, new MockServer(url)];-};--beforeEach(() => {- vi.useFakeTimers();-- // Polyfill Blob.arrayBuffer method for mock-socket compatibility- // mock-socket 9.3.1 creates Blob objects without the arrayBuffer() method,- // which causes bebopPlugin to fail. This polyfill ensures the test can run.- const OriginalBlob = globalThis.Blob;- if (OriginalBlob && !OriginalBlob.prototype.arrayBuffer) {- OriginalBlob.prototype.arrayBuffer = async function () {- return new Promise((resolve) => {- const reader = new FileReader();- reader.onload = () => resolve(reader.result as ArrayBuffer);- reader.readAsArrayBuffer(this);- });- };- }-});--afterEach(() => {- vi.useRealTimers();-});--describe('createDurableSocket', () => {- it('should connect immediately', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- const ws = createDurableSocket(url);- expect(ws.readyState).toBe(WebSocket.CONNECTING);- await handshake();- expect(ws.readyState).toBe(WebSocket.OPEN);- expect(server.clients().length).toBe(1);- dispose();- });- });-- it('should reconnect after close', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- let connectionCount = 0;- server.on('connection', () => connectionCount++);-- createDurableSocket(url);- await handshake();-- expect(connectionCount).toBe(1);-- server.clients()[0].close();- await advance(3000);-- expect(connectionCount).toBe(2);- dispose();- });- });-- it('should try to reconnect on server failure', async () => {- await createRoot(async (dispose) => {- const port = getRandomPort();- // Initialize the server- const [url, server] = getMockServer(port);- let ws = createDurableSocket(url);- await handshake();-- expect(ws.readyState).toBe(WebSocket.OPEN);-- // close the server- server.close();-- await advance(100);- // Should have disconnected- expect(ws.readyState).toBe(WebSocket.CLOSED);-- // Let the websocket try and fail to reconnect- // several times, simulating a server being down- await advance(10_000);-- // Bring the server back up- getMockServer(port);-- // give it some time- await advance(10000);-- // Should have reconnected- expect(ws.readyState).toBe(WebSocket.OPEN);- dispose();- });- });-- it('should queue messages sent before open', async () => {- await createRoot(async (dispose) => {- const messages: string[] = [];- const [url, server] = getMockServer();- server.on('connection', (s) =>- s.on('message', (d) => messages.push(d as string))- );-- const ws = createDurableSocket(url);-- ws.send('message1');- ws.send('message2');-- await handshake();- await advance(50);- expect(messages).toEqual(['message1', 'message2']);- dispose();- });- });-- it('should resolve URL with async resolver', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- let connectionCount = 0;- server.on('connection', () => connectionCount++);-- const urlResolver = async () => {- await advance(50);- return `${url}?count=${connectionCount}`;- };-- createDurableSocket(url, { reconnectUrlResolver: urlResolver });-- await advance(300);- expect(connectionCount).toBe(1);-- server.clients()[0].close();- await advance(3000);- expect(connectionCount).toBe(2);- expect(server.clients()[0].url).toBe(`${url}/?count=1`);- dispose();- });- });-- it('should reconnect correctly several times, with variable delay', async () => {- await createRoot(async (dispose) => {- const delays = [10, 50, 100, 500, 1000, 10_000];-- for (const delay of delays) {- const [url, server] = getMockServer();- let connectionCount = 0;- server.on('connection', () => connectionCount++);-- const iterations = 50;-- createDurableSocket(url, {- delay,- retries: Infinity,- });- await handshake();-- expect(connectionCount).toBe(1);-- for (let i = 0; i < iterations; i++) {- server.clients().forEach((c) => c.close());- await advance(delay + 100);- expect(connectionCount).toBe(i + 2);- }- }-- dispose();- });- });-- it('should suppress duplicate reconnect attempts when many errors arrive together', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- let connections = 0;- server.on('connection', (s) => {- connections++;- // flood error/close events- s.dispatchEvent(new Event('error'));- s.dispatchEvent(new Event('error'));- s.close();- s.close();- });-- createDurableSocket(url);- await advance(1_000);-- expect(connections).toBe(2);- dispose();- });- });-});--describe('heartbeatPlugin', () => {- it('sends ping / receives pong', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- const messages: string[] = [];-- server.on('connection', (s) =>- s.on('message', (d) => {- messages.push(d as string);- if (d === 'ping') s.send('pong');- })- );-- createDurableSocket(url, undefined, [- heartbeatPlugin({ interval: 100, wait: 50 }),- ]);- await advance(150);- expect(messages).toContain('ping');- dispose();- });- });-- it('reconnects when pong missing', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- let connectionCount = 0;- server.on('connection', () => connectionCount++);-- createDurableSocket(url, undefined, [- heartbeatPlugin({ interval: 100, wait: 50 }),- ]);- await advance(400);- expect(connectionCount).toBeGreaterThan(1);- dispose();- });- });-- it('resets heartbeat on user activity', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- const pings: number[] = [];- let lastPing = 0;-- server.on('connection', (s) =>- s.on('message', (d) => {- if (d === 'ping') {- pings.push(now() - lastPing);- lastPing = now();- s.send('pong');- }- })- );-- const ws = createDurableSocket(url, undefined, [- heartbeatPlugin({ interval: 100, wait: 50 }),- ]);-- await advance(50);- ws.send('user message'); // resets timer-- await advance(150);- expect(pings.length).toBeGreaterThan(0);- dispose();- });- });-- it('does not reconnect when heartbeat is healthy', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- let connectionCount = 0;-- server.on('connection', (socket) => {- connectionCount++;- socket.on('message', (d) => {- if (d === 'ping') socket.send('pong');- });- });-- createDurableSocket(url, undefined, [- heartbeatPlugin({ interval: 100, wait: 100 }),- ]);-- await handshake();- expect(connectionCount).toBe(1);-- await advance(60_000);-- expect(connectionCount).toBe(1);-- dispose();- });- }, 60_000);-- it('reconnects on missing pong with interval === wait', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- let connectionCount = 0;- const ws = createDurableSocket(url, { delay: 50, retries: 2 }, [- heartbeatPlugin({ interval: 100, wait: 100 }),- jsonPlugin(),- ]);-- setInterval(() => {- ws.send('random');- }, 90);-- server.on('connection', (_) => {- connectionCount++;- });-- await handshake();-- await advance(1000);-- expect(connectionCount).greaterThan(1);- ws.close();- dispose();- });- });-- it('reconnects only once with delayed pong', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- let connectionCount = 0;- let pongEnabled = false;-- server.on('connection', (socket) => {- connectionCount++;- socket.on('message', (d) => {- if (pongEnabled && d === 'ping') socket.send('pong');- });- });-- createDurableSocket(url, undefined, [- heartbeatPlugin({ interval: 500, wait: 500 }),- ]);-- // Need to wait slightly longer than the interval to ensure the heartbeat is sent- // and then the pong is not received.- await advance(1100);- pongEnabled = true;- expect(connectionCount).toBe(2);-- await advance(2000);- expect(connectionCount).toBe(2);- dispose();- });- });-});--describe('createWebsocketEventEffect', () => {- it('should call callback only for messages with matching type', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- const callback = vi.fn();-- const ws = createDurableSocket(url, undefined, [jsonPlugin()]);-- createWebsocketEventEffect(ws, 'user_update', callback);-- await handshake();-- // Send message with matching type- server.clients()[0].send(- JSON.stringify({- type: 'user_update',- data: { id: 1, name: 'Alice' },- })- );-- // Send message with different type- server- .clients()[0]- .send(JSON.stringify({ type: 'other_event', data: { foo: 'bar' } }));-- await advance(50);-- expect(callback).toHaveBeenCalledTimes(1);- expect(callback).toHaveBeenCalledWith({- type: 'user_update',- data: { id: 1, name: 'Alice' },- });-- dispose();- });- });-- it('should handle multiple event effects on the same socket', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- const userCallback = vi.fn();- const uploadCallback = vi.fn();-- const ws = createDurableSocket(url, undefined, [jsonPlugin()]);-- createWebsocketEventEffect(ws, 'user_update', userCallback);- createWebsocketEventEffect(ws, 'bulk_upload', uploadCallback);-- await handshake();-- server- .clients()[0]- .send(JSON.stringify({ type: 'user_update', data: { id: 1 } }));- server- .clients()[0]- .send(JSON.stringify({ type: 'bulk_upload', data: { count: 100 } }));-- await advance(50);-- expect(userCallback).toHaveBeenCalledTimes(1);- expect(userCallback).toHaveBeenCalledWith({- type: 'user_update',- data: { id: 1 },- });-- expect(uploadCallback).toHaveBeenCalledTimes(1);- expect(uploadCallback).toHaveBeenCalledWith({- type: 'bulk_upload',- data: { count: 100 },- });-- dispose();- });- });-- it('should cleanup event listeners on disposal', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- const callback = vi.fn();-- const ws = createDurableSocket(url, undefined, [jsonPlugin()]);-- const innerDispose = createRoot((innerDispose) => {- createWebsocketEventEffect(ws, 'test_event', callback);- return innerDispose;- });-- await handshake();-- // Send message before disposal- server- .clients()[0]- .send(JSON.stringify({ type: 'test_event', data: { before: true } }));-- await advance(50);- expect(callback).toHaveBeenCalledTimes(1);-- // Dispose the effect- innerDispose();-- // Send message after disposal- server- .clients()[0]- .send(JSON.stringify({ type: 'test_event', data: { after: true } }));-- await advance(50);- // Should still be called only once- expect(callback).toHaveBeenCalledTimes(1);-- dispose();- });- });-- it('should work with raw websocket without jsonPlugin', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- const callback = vi.fn();-- const ws = createDurableSocket(url);-- createWebsocketEventEffect(ws, 'test', callback);-- await handshake();-- // Send raw string that's not JSON- server.clients()[0].send('not json');-- await advance(50);-- // Should not be called for non-object messages- expect(callback).not.toHaveBeenCalled();-- dispose();- });- });-- it('should ignore messages without type field', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- const callback = vi.fn();-- const ws = createDurableSocket(url, undefined, [jsonPlugin()]);-- createWebsocketEventEffect(ws, 'test_event', callback);-- await handshake();-- // Send message without type field- server.clients()[0].send(JSON.stringify({ data: 'no type field' }));-- await advance(50);-- expect(callback).not.toHaveBeenCalled();-- dispose();- });- });-});--describe('createWebsocketEventEffects', () => {- it('should register multiple event handlers at once', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- const handlers = {- user_update: vi.fn(),- bulk_upload: vi.fn(),- notification: vi.fn(),- };-- const ws = createDurableSocket(url, undefined, [jsonPlugin()]);-- createWebsocketEventEffects(ws, handlers);-- await handshake();-- // Send different event types- server- .clients()[0]- .send(JSON.stringify({ type: 'user_update', data: { id: 1 } }));- server- .clients()[0]- .send(JSON.stringify({ type: 'bulk_upload', data: { count: 50 } }));- server- .clients()[0]- .send(- JSON.stringify({ type: 'notification', data: { message: 'Hello' } })- );-- await advance(50);-- expect(handlers.user_update).toHaveBeenCalledWith({- type: 'user_update',- data: { id: 1 },- });- expect(handlers.bulk_upload).toHaveBeenCalledWith({- type: 'bulk_upload',- data: { count: 50 },- });- expect(handlers.notification).toHaveBeenCalledWith({- type: 'notification',- data: { message: 'Hello' },- });-- dispose();- });- });-- it('should handle empty handlers object', async () => {- await createRoot(async (dispose) => {- const [url] = getMockServer();- const ws = createDurableSocket(url, undefined, [jsonPlugin()]);-- // Should not throw- expect(() => {- createWebsocketEventEffects(ws, {});- }).not.toThrow();-- dispose();- });- });-});--describe('bebopPlugin', () => {- it('serialises & deserialises messages', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- const mockSend = {- encode: (d: { text: string }) =>- new Uint8Array(new TextEncoder().encode(d.text)),- };- const mockRecv = {- decode: (d: Uint8Array) => ({ text: new TextDecoder().decode(d) }),- };-- let receivedOnClient: any;- let receivedOnServer: any;-- server.on('connection', (s) =>- s.on('message', (d) => {- receivedOnServer = d;- s.send(new Blob([new TextEncoder().encode('server response')]));- })- );-- const ws = createDurableSocket(url, { delay: 50, retries: 2 }, [- bebopPlugin(mockSend, mockRecv),- ]);-- await advance(100);- ws.addEventListener('message', (e) => {- receivedOnClient = e.data;- });-- ws.send({ text: 'client message' });- await advance(500);-- expect(receivedOnServer).toBeInstanceOf(Uint8Array);- expect(receivedOnClient).toEqual({ text: 'server response' });- dispose();- });- });-- it('keeps serialisation after reconnect', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- const mockSend = {- encode: (d: { id: number }) => new Uint8Array([d.id]),- };- const mockRecv = { decode: (d: Uint8Array) => ({ id: d[0] }) };-- const messages: any[] = [];- server.on('connection', (s) => s.on('message', (d) => messages.push(d)));-- const ws = createDurableSocket(url, { delay: 50, retries: 2 }, [- bebopPlugin(mockSend, mockRecv),- ]);-- await advance(100);- ws.send({ id: 1 });-- server.clients()[0].close(); // force reconnect- await advance(100);- ws.send({ id: 2 });-- await advance(100);- expect(messages).toEqual([new Uint8Array([1]), new Uint8Array([2])]);- dispose();- });- });-- it('is consistent through 50 reconnects', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- const mockSend = {- encode: (d: { id: number }) => new Uint8Array([d.id]),- };- const mockRecv = { decode: (d: Uint8Array) => ({ id: d[0] }) };-- const messages: any[] = [];- server.on('connection', (s) => s.on('message', (d) => messages.push(d)));-- const ws = createDurableSocket(url, { delay: 50, retries: 2 }, [- bebopPlugin(mockSend, mockRecv),- ]);-- await advance(100);-- for (let i = 0; i < 50; i++) {- server.clients().forEach((c) => c.close());- await advance(100);-- ws.send({ id: i });- await advance(100);-- expect(messages.filter((m) => m !== 'ping').at(-1)).toEqual(- new Uint8Array([i])- );- }-- ws.close();- dispose();- });- });-- it('remains consistent with heartbeat through 50 reconnects', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- const mockSend = {- encode: (d: { id: number }) => new Uint8Array([d.id]),- };- const mockRecv = { decode: (d: Uint8Array) => ({ id: d[0] }) };-- const messages: any[] = [];- server.on('connection', (s) =>- s.on('message', (d) => {- if (d === 'ping') s.send('pong');- messages.push(d);- })- );-- const ws = createDurableSocket(url, { delay: 100, retries: 2 }, [- heartbeatPlugin({ interval: 3000, wait: 1000 }),- bebopPlugin(mockSend, mockRecv),- ]);-- await advance(100);-- for (let i = 0; i < 50; i++) {- server.clients().forEach((c) => c.close());- await advance(100);-- ws.send({ id: i });- await advance(100);-- expect(messages.filter((m) => m !== 'ping').at(-1)).toEqual(- new Uint8Array([i])- );- }-- ws.close();- dispose();- });- });-});--describe('jsonPlugin', () => {- it('should serialize messages on send', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- const payload = { a: 1, b: 'x' };-- let receivedServerMessage: any;-- server.on('connection', (sock) => {- sock.on('message', (data) => {- if (data !== 'ping') receivedServerMessage = data;- });- });-- const ws = createDurableSocket(url, undefined, [jsonPlugin()]);-- await handshake();-- ws.send(payload);-- await advance(10);-- expect(receivedServerMessage).toBe(JSON.stringify(payload));-- ws.close();- server.close();- dispose();- });- });-- it('should deserialize messages on receive', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();- const inbound = { hello: 'world' };-- const ws = createDurableSocket(url, undefined, [jsonPlugin()]);-- let receivedClientMessage: any;-- ws.addEventListener('message', (e) => {- receivedClientMessage = e.data;- });-- await handshake();-- server.clients().forEach((c) => c.send(JSON.stringify(inbound)));-- await advance(10);-- expect(receivedClientMessage).toEqual(inbound);-- server.close();-- dispose();- });- });-- it('passes non-JSON strings through untouched', async () => {- const [url, server] = getMockServer();-- let receivedMessage;- server.on('connection', (sock) => {- sock.send('pong');- });-- const ws = createDurableSocket(url, undefined, [jsonPlugin()]);- ws.addEventListener('message', (e) => {- receivedMessage = e.data;- });-- await handshake();-- expect(receivedMessage).toBe('pong');-- server.close();- });-- it('passes binary/Blob frames through untouched', async () => {- const [url, server] = getMockServer();- const buf = new Uint8Array([1, 2, 3]).buffer;- server.on('connection', (sock) => {- sock.send(buf);- });- let receivedMessage: any;- const ws = createDurableSocket(url, undefined, [jsonPlugin()]);- ws.addEventListener('message', (e) => {- receivedMessage = e.data;- });-- await handshake();-- expect(receivedMessage).toBeInstanceOf(ArrayBuffer);- expect(new Uint8Array(receivedMessage)).toEqual(new Uint8Array(buf));-- server.close();- });-- it('is consistent through 50 reconnects', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();-- const messages: any[] = [];- server.on('connection', (s) => s.on('message', (d) => messages.push(d)));-- const ws = createDurableSocket(url, { delay: 50, retries: 2 }, [- jsonPlugin(),- ]);-- await advance(100);-- for (let i = 0; i < 50; i++) {- server.clients().forEach((c) => c.close());- await advance(100);-- ws.send({ id: i });- await advance(100);-- expect(messages.filter((m) => m !== 'ping').at(-1)).toEqual(- JSON.stringify({ id: i })- );- }-- ws.close();- dispose();- });- });-- it('is consistent through 50 reconnects with heartbeat', async () => {- await createRoot(async (dispose) => {- const [url, server] = getMockServer();-- const messages: any[] = [];- server.on('connection', (s) => s.on('message', (d) => messages.push(d)));-- const ws = createDurableSocket(url, { delay: 50, retries: 2 }, [- heartbeatPlugin({ interval: 3000, wait: 1000 }),- jsonPlugin(),- ]);-- await advance(100);-- for (let i = 0; i < 50; i++) {- server.clients().forEach((c) => c.close());- await advance(100);-- ws.send({ id: i });- await advance(100);-- expect(messages.filter((m) => m !== 'ping').at(-1)).toEqual(- JSON.stringify({ id: i })- );- }-- ws.close();- dispose();- });- });-});diff --git a/js/app/vitest.config.ts b/js/app/vitest.config.tsindex 1bea214be7..e774db801d 100644--- a/js/app/vitest.config.ts+++ b/js/app/vitest.config.ts@@ -6,5 +6,23 @@ export default defineConfig({plugins: [tsconfigPaths(), solidPlugin()],test: {exclude: [...configDefaults.exclude],+ projects: [+ {+ // WebSocket tests with Node.js environment+ extends: './packages/websocket/vitest.config.ts',+ test: {+ include: ['packages/websocket/**/*.test.{ts,tsx}'],+ name: 'websocket',+ },+ },+ {+ // Default app tests with browser environment+ test: {+ include: ['packages/app/**/*.test.{ts,tsx}'],+ name: 'app',+ environment: 'jsdom',+ },+ },+ ],},});