Y-SweetAPI Reference@y-sweet/client

@y-sweet/client

JavaScript/TypeScript library for connecting a Yjs Doc with a Y-Sweet server in order to sync and persist document updates.

Installation

npm install @y-sweet/client

The @y-sweet/client library is primarily used to connect a given Yjs document to a Y-Sweet server so that changes to the Yjs document are synced across all clients and, optionally, so that the document is persisted to S3 storage.

createYjsProvider(doc, docId, authEndpoint, [options])

Connecting the Yjs document to Y-Sweet is done with the createYjsProvider() function, which takes a Yjs document, a doc ID, an AuthEndpoint, and some optional parameters. It returns a promise which, when awaited, resolves to a YSweetProvider. Note that it is often not necessary to directly interact with the YSweetProvider.

my-app.ts
import { createYjsProvider } from '@y-sweet/client'
 
const doc = new Y.Doc()
const docId = 'my-doc-id'
await createYjsProvider(doc, docId, '/api/auth')

The AuthEndpoint is used by the provider to get a ClientToken that authorizes the client to read and write to the shared document. The AuthEndpoint may either be a string (a full URL or just a path) or an async function that returns a ClientToken. If you are using a meta-framework like NextJS or Remix, you can implement this auth endpoint as an API route, or you can use a server framework like ExpressJS or Hono.

Here’s an example of how the auth endpoint might be implemented using Hono:

my-server.ts
import { DocumentManager } from '@y-sweet/sdk'
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { serve } from '@hono/node-server'
 
const docManager = new DocumentManager(process.env.CONNECTION_STRING)
 
const app = new Hono()
app.use('/api/auth', cors())
app.post('/api/auth', async (c) => {
  const body = await c.req.json()
  const docId = body.docId
  // At this point, in a production app, you'd want to authenticate the user
  // and make sure they have access to the given doc
  const clientToken = await docManager.getOrCreateDocAndToken(docId)
  return c.json(clientToken)
})
serve(app)

Types

createYjsProvider(
  doc: Y.Doc,
  docId: string,
  authEndpoint: string | () => Promise<ClientToken>,
  options: YSweetProviderParams
): Promise<YSweetProviderWithClientToken>
type AuthEndpoint = string | () => Promise<ClientToken>
type ClientToken = {
  url: string
  baseUrl: string
  docId: string
  token?: string
}
type YSweetProviderParams = {
  connect?: boolean
  awareness?: Awareness
  params?: {
      [x: string]: string
  }
  WebSocketPolyfill?: WebSocketPolyfillType
  resyncInterval?: number
  maxBackoffTime?: number
  disableBc?: boolean
  initialClientToken?: ClientToken
}
Built by Jamsocket.