y-websocket

repository·master·Indexed 20 days ago

https://github.com/yjs/y-websocket

A WebSocket provider for Yjs that implements a client-server model to distribute awareness information and document updates. It allows Y.Doc synchronization via the WebsocketProvider class, supporting cross-tab communication and various backend implementations, including a standalone @y/websocket-server. It provides detailed connection monitoring through events and a SyncStatus object to track synchronization health.

Tokens
2.1K
Snippets
6
Records
12
Agent score
22%

What's inside y-websocket

  1. Understand SyncStatus and the sync-status event

    master

    When using compatible backends (like yhub), you can monitor detailed synchronization state via the sync-status event or the wsProvider.syncStatus property.

    SyncStatus Object Properties:

    • connected: boolean - Whether the provider is 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 ms of the oldest unconfirmed local update (0 if all synced).
    • lastMessageAge: number - Time in ms since the last message was received from the server.
    • status: 'green' | 'yellow' | 'red' - A distilled status:
      • 'green': Connected, synced, and no unconfirmed local updates.
      • 'yellow': Connected but has unconfirmed local updates younger than 8 seconds.
      • 'red': Disconnected, not synced, or unconfirmed local updates older than 8 seconds.
  2. Start a y-websocket server

    master

    The fastest way to get started is to use the @y/websocket-server backend. This package is a standalone backend compatible with the y-websocket provider.

    Install and start the server using the following commands:

    npm install @y/websocket-server
    HOST=localhost PORT=1234 npx y-websocket
    npm install @y/websocket-server
    HOST=localhost PORT=1234 npx y-websocket
  3. Install y-websocket

    master

    You can install the stable release (recommended for Yjs v13) or the unstable development branch (for Yjs v14 support).

    Stable release (recommended):

    npm i y-websocket

    Main branch / unstable release:

    npm i @y/websocket
    # stable release (recommended)
    npm i y-websocket
    
    # main branch / unstable release
    npm i @y/websocket
  4. Configure WebsocketProvider options

    master

    When instantiating WebsocketProvider, you can pass an optional wsOpts object to customize connection behavior.

    wsOpts = {
      // Set this to `false` if you want to connect manually using wsProvider.connect()
      connect: true,
      // Specify 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: {},
      // You may polyfill the Websocket object (e.g. in Node.js)
      WebsocketPolyfill: Websocket,
      // Specify an existing Awareness instance
      awareness: new awarenessProtocol.Awareness(ydoc),
      // Specify the maximum amount to wait between reconnects (exponential backoff)
      maxBackoffTime: 2500
    }
    wsOpts = {
      connect: true,
      params: {},
      WebsocketPolyfill: Websocket,
      awareness: new awarenessProtocol.Awareness(ydoc),
      maxBackoffTime: 2500
    }
  5. Use WebsocketProvider in a client

    master

    To connect a Yjs document to a remote server, use the WebsocketProvider. It synchronizes the Y.Doc with the server and handles awareness (e.g., cursor positions) and document updates.

    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"
    })
    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"
    })
  6. Use WebsocketProvider in Node.js

    master

    Since Node.js does not have a native WebSocket implementation, you must provide a polyfill (such as the ws package) via the WebsocketPolyfill option in the configuration object.

    const wsProvider = new WebsocketProvider('ws://localhost:1234', 'my-roomname', doc, { WebSocketPolyfill: require('ws') })
  7. WebsocketProvider methods

    master

    Use these methods to control the lifecycle of the provider:

    • wsProvider.disconnect(): Disconnect from the server and prevent reconnection.
    • wsProvider.connect(): Establish a connection. Use this if you previously called disconnect() or if wsOpts.connect was set to false.
    • wsProvider.destroy(): Disconnect from the server and remove all event handlers.
  8. WebsocketProvider properties

    master

    The WebsocketProvider instance exposes several properties to monitor connection and synchronization state:

    • wsconnected: boolean - True if currently connected to the server.
    • wsconnecting: boolean - True if currently connecting to the server.
    • shouldConnect: boolean - If false, the client will not try to reconnect.
    • bcconnected: boolean - True if communicating with other browser windows via BroadcastChannel.
    • synced: boolean - True if connected and synced with the server.
    • syncStatus: SyncStatus - Detailed sync status (works with certain backends like yhub).
    • params: Object<string,string> - The specified URL parameters. Can be updated to refresh connection with new values (e.g. auth tokens).
    • wsProvider.params: boolean - (Note: The documentation lists this as boolean, but context implies it refers to the params object/status).
  9. WebsocketProvider events

    master

    The WebsocketProvider emits several events for monitoring lifecycle and synchronization:

    • wsProvider.on('sync', (isSynced: boolean) => ...): Fired when the client receives content from the server.
    • wsProvider.on('status', ({ status: 'disconnected' | 'connecting' | 'connected' }) => ...): Updates on the current connection status.
    • wsProvider.on('connection-close', (WSClosedEvent) => ...): Fired when the underlying WebSocket connection is closed.
    • wsProvider.on('connection-error', (WSErrorEvent) => ...): Fired when the connection closes with an error.
    • wsProvider.on('sync-status', (syncStatus: SyncStatus) => ...): Detailed sync status updates (works with certain backends like yhub).
  10. Use WebsocketProvider to sync a Y.Doc

    master

    The WebsocketProvider class is used to create a WebSocket connection to a server to synchronize a Yjs document (Y.Doc) and its awareness state. The document name is appended to the provided serverUrl as a path component.

    To use it, instantiate WebsocketProvider with the server URL, a room name, and your Y.Doc instance. By default, it connects immediately upon instantiation.

    ```ts
    import * as Y from '@y/y'
    import { WebsocketProvider } from 'y-websocket'
    
    const doc = new Y.Doc()
    const provider = new WebsocketProvider('http://localhost:1234', 'my-document-name', doc)
    ```埋
  11. Check the synchronization status with syncStatus

    master

    The syncStatus getter returns a SyncStatus object describing the current health of the connection and data synchronization. This is useful for displaying connection indicators (e.g., green/yellow/red lights) to users.

    SyncStatus Object

    PropertyTypeDescription
    connectedbooleanWhether the WebSocket is connected.
    receivedInitialSyncbooleanWhether the initial sync step has been completed.
    localUpdatesSyncedbooleanWhether all local updates have been acknowledged by the server.
    localUpdatesAgenumberAge (ms) of the oldest unsynced local update.
    lastMessageAgenumberAge (ms) since the last message was received.
    status'green' | 'yellow' | 'red'Distilled status:
    - green: Synced, connected, and no unsynced local updates.
    - yellow: Connected, but last local message is younger than 8 seconds.
    - red: Unsynced, disconnected, or last local message is older than 8 seconds.
  12. Listen to WebsocketProvider events

    master

    WebsocketProvider extends ObservableV2 and emits several events to track the connection and synchronization status.

    Supported Events

    EventArgumentsDescription
    connection-close(event: CloseEvent | null, provider: WebsocketProvider) => voidEmitted when the WebSocket connection is closed.
    status(event: { status: 'connected' | 'disconnected' | 'connecting' }) => voidEmitted when the connection state changes.
    connection-error(event: Event, provider: WebsocketProvider) => voidEmitted when a WebSocket error occurs.
    sync(state: boolean) => voidEmitted when the provider's synced state changes.
    sync-status(syncStatus: SyncStatus) => voidEmitted when the distilled sync status changes.