### Start y-websocket server Source: https://github.com/yjs/y-websocket/blob/master/README.md Install and start the @y/websocket-server backend for y-websocket. Ensure HOST and PORT environment variables are set. ```sh npm install @y/websocket-server HOST=localhost PORT=1234 npx y-websocket ``` -------------------------------- ### Install y-websocket Source: https://github.com/yjs/y-websocket/blob/master/README.md Install the stable or unstable release of y-websocket using npm. ```sh # stable release (recommended) npm i y-websocket # main branch / unstable release npm i @y/websocket ``` -------------------------------- ### Initialize WebsocketProvider Source: https://github.com/yjs/y-websocket/blob/master/README.md Create a new instance of WebsocketProvider to connect to a Yjs document synchronization server. Ensure the serverUrl, room name, and Yjs document are provided. Optional WebSocket options can be configured. ```javascript wsProvider = new WebsocketProvider(serverUrl, room, ydoc, wsOpts) ``` -------------------------------- ### Configure WebsocketProvider Options Source: https://github.com/yjs/y-websocket/blob/master/README.md Customize the behavior of the WebsocketProvider with various options. This includes controlling automatic connection, attaching URL parameters, providing a WebSocket polyfill, specifying an awareness instance, and setting the maximum backoff time for reconnections. ```javascript wsOpts = { // Set this to `false` if you want to connect manually using wsProvider.connect() connect: true, // Specify a query-string / url parameters that will be url-encoded and attached to the `serverUrl` // I.e. params = { auth: "bearer" } will be transformed to "?auth=bearer" params: {}, // Object // You may polyill the Websocket object (https://developer.mozilla.org/en-US/docs/Web/API/WebSocket). // E.g. In nodejs, you could specify WebsocketPolyfill = require('ws') WebsocketPolyfill: Websocket, // Specify an existing Awareness instance - see https://github.com/yjs/y-protocols awareness: new awarenessProtocol.Awareness(ydoc), // Specify the maximum amount to wait between reconnects (we use exponential backoff). maxBackoffTime: 2500 } ``` -------------------------------- ### Import WebsocketProvider Source: https://github.com/yjs/y-websocket/blob/master/README.md Import the necessary WebsocketProvider class from the y-websocket library. ```javascript import { WebsocketProvider } from 'y-websocket' ``` -------------------------------- ### WebsocketProvider Constructor Source: https://github.com/yjs/y-websocket/blob/master/README.md Creates a new websocket-provider instance to synchronize Yjs documents. Changes are synced to other clients via the connected server as long as the provider or the ydoc is not destroyed. Optional configuration can be provided. ```APIDOC ## WebsocketProvider Constructor ### Description Creates a new websocket-provider instance. As long as this provider, or the connected ydoc, is not destroyed, the changes will be synced to other clients via the connected server. Optionally, you may specify a configuration object. ### Signature `new WebsocketProvider(serverUrl: string, room: string, ydoc: Y.Doc [, wsOpts: WsOpts])` ### Parameters * `serverUrl` (string) - The URL of the WebSocket server. * `room` (string) - The name of the room to join. * `ydoc` (Y.Doc) - The Yjs document to synchronize. * `wsOpts` (WsOpts, optional) - Configuration options for the WebSocket provider. ### WsOpts Configuration ```json { "connect": true, // Set to `false` to connect manually using wsProvider.connect() "params": {}, // Object - Query-string parameters to attach to the serverUrl "WebsocketPolyfill": Websocket, // Polyfill for the WebSocket object (e.g., require('ws') in Node.js) "awareness": awarenessProtocol.Awareness, // An existing Awareness instance "maxBackoffTime": 2500 // Maximum time to wait between reconnects (exponential backoff) } ``` ``` -------------------------------- ### Node.js WebSocket Polyfill Source: https://github.com/yjs/y-websocket/blob/master/README.md Configure the WebSocket provider in Node.js to use the 'ws' package as a WebSocket polyfill for server connections. ```js const wsProvider = new WebsocketProvider('ws://localhost:1234', 'my-roomname', doc, { WebSocketPolyfill: require('ws') }) ``` -------------------------------- ### Yjs Client Connection Source: https://github.com/yjs/y-websocket/blob/master/README.md Connect a Yjs document to a y-websocket server. Imports Yjs and WebsocketProvider. Logs connection status. ```js import * as Y from '@y/y' import { WebsocketProvider } from 'y-websocket' const doc = new Y.Doc() const wsProvider = new WebsocketProvider('ws://localhost:1234', 'my-roomname', doc) wsProvider.on('status', event => { console.log(event.status) // logs "connected" or "disconnected" }) ``` -------------------------------- ### WebsocketProvider Methods Source: https://github.com/yjs/y-websocket/blob/master/README.md Provides methods to control the WebSocket connection, such as disconnecting, connecting, and destroying the provider instance. ```APIDOC ## WebsocketProvider Methods ### Description Methods for managing the WebSocket connection and lifecycle of the `WebsocketProvider`. ### Methods * **`disconnect()`**: Disconnects from the server and prevents automatic reconnection. * **`connect()`**: Establishes a WebSocket connection to the server. Use this if you have previously disconnected or set `wsOpts.connect = false`. * **`destroy()`**: Destroys the `wsProvider` instance, disconnecting from the server and removing all event handlers. ``` -------------------------------- ### Handle Detailed Sync Status Updates Source: https://github.com/yjs/y-websocket/blob/master/README.md Listen to the 'sync-status' event for detailed synchronization information, including connection status, initial sync completion, local update confirmation, and message age. This feature is backend-dependent (e.g., yhub). ```javascript wsProvider.on('sync-status', function(syncStatus) { // Handle detailed sync status updates }) ``` -------------------------------- ### WebsocketProvider Events Source: https://github.com/yjs/y-websocket/blob/master/README.md Defines events that can be listened to for updates on synchronization status, connection state, and connection errors. ```APIDOC ## WebsocketProvider Events ### Description Event listeners for monitoring the state of the `WebsocketProvider`. ### Events * **`sync`**: Fired when the client has received content from the server. - **Handler Signature**: `function(isSynced: boolean)` * **`status`**: Receives updates about the current connection status. - **Handler Signature**: `function({ status: 'disconnected' | 'connecting' | 'connected' })` * **`connection-close`**: Fires when the underlying WebSocket connection is closed, forwarding the WebSocket event. - **Handler Signature**: `function(WSClosedEvent)` * **`connection-error`**: Fires when the underlying WebSocket connection closes with an error, forwarding the WebSocket event. - **Handler Signature**: `function(WSErrorEvent)` * **`sync-status`**: Receives detailed sync status updates, particularly useful with certain backends (e.g., yhub). - **Handler Signature**: `function(syncStatus: SyncStatus)` - **`syncStatus` Object Properties**: - `connected` (boolean): Whether the provider is currently connected to the server. - `receivedInitialSync` (boolean): Whether the initial sync with the server has completed. - `localUpdatesSynced` (boolean): Whether all local updates have been confirmed by the server. - `localUpdatesAge` (number): Age in milliseconds of the oldest unconfirmed local update. - `lastMessageAge` (number): Time in milliseconds since the last message was received from the server. - `status` ('green' | 'yellow' | 'red'): Distilled sync status. ``` -------------------------------- ### WebsocketProvider Properties Source: https://github.com/yjs/y-websocket/blob/master/README.md Exposes properties to monitor the connection status and synchronization state of the WebSocket provider. ```APIDOC ## WebsocketProvider Properties ### Description Properties to inspect the connection and synchronization status of the `WebsocketProvider` instance. ### Properties * **`wsconnected`** (boolean): True if the instance is currently connected to the server. * **`wsconnecting`** (boolean): True if the instance is currently attempting to connect to the server. * **`shouldConnect`** (boolean): If false, the client will not attempt to reconnect. * **`bcconnected`** (boolean): True if the instance is currently communicating with other browser windows via BroadcastChannel. * **`synced`** (boolean): True if the instance is currently connected and synchronized with the server. * **`syncStatus`** (SyncStatus): An object containing detailed synchronization status, including `connected`, `receivedInitialSync`, `localUpdatesSynced`, `localUpdatesAge`, `lastMessageAge`, and `status` ('green', 'yellow', or 'red'). This property is primarily useful with backends like yhub. * **`params`** (boolean): The specified URL parameters. This can be updated, and the new values will be used when a new connection is established. It's recommended to update this regularly if it contains an authentication token. ``` -------------------------------- ### Handle WebSocket Sync Event Source: https://github.com/yjs/y-websocket/blob/master/README.md Listen for the 'sync' event to be notified when the client has successfully received content from the server. The event handler receives a boolean indicating the synchronization status. ```javascript wsProvider.on('sync', function(isSynced) { // Handle sync status change }) ``` -------------------------------- ### Disconnect and Reconnect WebSocket Provider Source: https://github.com/yjs/y-websocket/blob/master/README.md Manually disconnect the WebSocket provider from the server using `disconnect()` and prevent reconnections. Use `connect()` to re-establish the connection, which is useful if automatic connection was disabled or after a manual disconnection. ```javascript wsProvider.disconnect() wsProvider.connect() ``` -------------------------------- ### Handle WebSocket Connection Close Source: https://github.com/yjs/y-websocket/blob/master/README.md Register an event listener for 'connection-close' to be informed when the underlying WebSocket connection is terminated. This event forwards the original WebSocket close event. ```javascript wsProvider.on('connection-close', function(WSClosedEvent) { // Handle connection close event }) ``` -------------------------------- ### Handle WebSocket Status Updates Source: https://github.com/yjs/y-websocket/blob/master/README.md Subscribe to the 'status' event to receive updates on the WebSocket connection status. The event provides the current status, which can be 'disconnected', 'connecting', or 'connected'. ```javascript wsProvider.on('status', function({ status }) { // Handle status update }) ``` -------------------------------- ### Handle WebSocket Connection Error Source: https://github.com/yjs/y-websocket/blob/master/README.md Use the 'connection-error' event to catch and handle errors that occur during the WebSocket connection. This event forwards the original WebSocket error event. ```javascript wsProvider.on('connection-error', function(WSErrorEvent) { // Handle connection error event }) ``` -------------------------------- ### Destroy WebSocket Provider Source: https://github.com/yjs/y-websocket/blob/master/README.md Clean up the WebSocket provider instance by calling `destroy()`. This will disconnect from the server and remove all associated event handlers, releasing resources. ```javascript wsProvider.destroy() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.