### Install and Run Development Server Source: https://github.com/napolab/y-durableobjects/blob/main/example/apps/workers/README.md Installs project dependencies using npm and starts the development server. ```bash npm install npm run dev ``` -------------------------------- ### Run UI Development Server Source: https://github.com/napolab/y-durableobjects/blob/main/example/README.md Navigates to the UI application directory and starts the development server using npm. ```bash cd apps/web npm run dev ``` -------------------------------- ### Install y-durableobjects and Hono Source: https://github.com/napolab/y-durableobjects/blob/main/README.md Installs the necessary packages for using y-durableobjects with Hono. This includes the core library and Hono itself, which is a peer dependency. ```bash npm install y-durableobjects hono ``` ```bash yarn add y-durableobjects hono ``` ```bash pnpm add y-durableobjects hono ``` -------------------------------- ### Hono RPC Server Implementation (Without Shorthand) Source: https://github.com/napolab/y-durableobjects/blob/main/README.md This example provides a more explicit server-side setup for Hono RPC, demonstrating how to manually handle WebSocket upgrades. It uses the `upgrade` helper and `hc` for client interaction within the Durable Object context. ```typescript import { Hono } from "hono"; import { YDurableObjects, YDurableObjectsAppType } from "y-durableobjects"; import { upgrade } from "y-durableobjects/helpers/upgrade"; type Bindings = { Y_DURABLE_OBJECTS: DurableObjectNamespace>; }; type Env = { Bindings: Bindings; }; const app = new Hono(); app.get("/editor/:id", upgrade(), async (c) => { const id = c.env.Y_DURABLE_OBJECTS.idFromName(c.req.param("id")); const stub = c.env.Y_DURABLE_OBJECTS.get(id); const url = new URL("/", c.req.url); const client = hc(url, { fetch: stub.fetch.bind(stub), }); const res = await client.rooms[":id"].$get( { param: { id: c.req.param("id") } }, { init: { headers: c.req.raw.headers } }, ); return new Response(null, { webSocket: res.webSocket, status: res.status, statusText: res.statusText, }); }); export default app; export type AppType = typeof app; export { YDurableObjects }; ``` -------------------------------- ### Install Dependencies Source: https://github.com/napolab/y-durableobjects/blob/main/example/README.md Clones the repository and installs project dependencies using npm. ```bash git clone git@github.com:napolab/y-durableobjects.git cd y-durableobjects/example npm install ``` -------------------------------- ### Run Worker Server Source: https://github.com/napolab/y-durableobjects/blob/main/example/README.md Starts the Cloudflare Worker with Durable Objects emulation locally using npm. ```bash cd apps/workers npm run dev ``` -------------------------------- ### Clean Install Dependencies Source: https://github.com/napolab/y-durableobjects/blob/main/README.md Removes existing lock files and node_modules, then reinstalls all project dependencies. This is a common troubleshooting step to resolve dependency conflicts or outdated packages. ```bash # Delete lock files and node_modules rm -rf node_modules pnpm-lock.yaml # Reinstall dependencies pnpm install ``` -------------------------------- ### ESLint Configuration for Type-Aware Linting Source: https://github.com/napolab/y-durableobjects/blob/main/example/apps/web/README.md This snippet shows how to configure ESLint to enable type-aware linting rules for TypeScript projects. It involves setting `parserOptions` to include project configuration and extending specific TypeScript ESLint plugins. ```javascript export default { // other rules... parserOptions: { ecmaVersion: 'latest', sourceType: 'module', project: ['./tsconfig.json', './tsconfig.node.json'], tsconfigRootDir: __dirname, }, } ``` -------------------------------- ### Extend YDurableObjects with Custom Methods Source: https://github.com/napolab/y-durableobjects/blob/main/README.md This example shows how to extend the `YDurableObjects` class to add custom functionality. It demonstrates accessing and manipulating the internal Yjs document (`this.doc`) and performing cleanup operations. ```typescript import { applyUpdate, encodeStateAsUpdate } from "yjs"; import { YDurableObjects } from "y-durableobjects"; export class CustomDurableObject extends YDurableObjects { async customMethod() { // Access and manipulate the YDoc state const update = new Uint8Array([ /* some update data */ ]); this.doc.update(update); await this.cleanup(); } } ``` -------------------------------- ### Fetch YDoc State using JS RPC Source: https://github.com/napolab/y-durableobjects/blob/main/README.md Provides an example of fetching the current state of a YDoc stored within a Durable Object using the JS RPC interface. This is useful for retrieving collaborative document data. ```typescript import { Hono } from "hono"; import { YDurableObjects } from "y-durableobjects"; import { fromUint8Array } from "js-base64"; type Bindings = { Y_DURABLE_OBJECTS: DurableObjectNamespace>; }; type Env = { Bindings: Bindings; }; const app = new Hono(); app.get("/rooms/:id/state", async (c) => { const roomId = c.req.param("id"); const id = c.env.Y_DURABLE_OBJECTS.idFromName(roomId); const stub = c.env.Y_DURABLE_OBJECTS.get(id); const doc = await stub.getYDoc(); const base64 = fromUint8Array(doc); return c.json({ doc: base64 }, 200); }); export default app; export { YDurableObjects }; ``` -------------------------------- ### Update YDoc in Durable Object with Hono Source: https://github.com/napolab/y-durableobjects/blob/main/README.md This snippet demonstrates how to use the `updateYDoc` API to update a Yjs document stored in a Durable Object. It shows the server-side setup using Hono to handle POST requests, receive update data as an ArrayBuffer, and pass it to the Durable Object stub. ```typescript import { Hono } from "hono"; import { YDurableObjects } from "y-durableobjects"; type Bindings = { Y_DURABLE_OBJECTS: DurableObjectNamespace>; }; type Env = { Bindings: Bindings; }; const app = new Hono(); app.post("/rooms/:id/update", async (c) => { const roomId = c.req.param("id"); const id = c.env.Y_DURABLE_OBJECTS.idFromName(roomId); const stub = c.env.Y_DURABLE_OBJECTS.get(id); const buffer = await c.req.arrayBuffer(); const update = new Uint8Array(buffer); await stub.updateYDoc(update); return c.json(null, 200); }); export default app; export { YDurableObjects }; ``` -------------------------------- ### Deploy Project Source: https://github.com/napolab/y-durableobjects/blob/main/example/apps/workers/README.md Deploys the project using npm. ```bash npm run deploy ``` -------------------------------- ### Project Build and Development Commands Source: https://github.com/napolab/y-durableobjects/blob/main/CLAUDE.md Common commands for building, type checking, linting, formatting, and testing the y-durableobjects library. These commands utilize pnpm and are essential for the development workflow. ```bash pnpm build pnpm typecheck pnpm lint pnpm fmt pnpm test ``` -------------------------------- ### Testing Commands Source: https://github.com/napolab/y-durableobjects/blob/main/CLAUDE.md Commands for running tests with Vitest, including running all tests or a specific test file. Configuration is handled in vitest.config.ts. ```bash pnpm test pnpm test path/to/test.test.ts ``` -------------------------------- ### Release Command Source: https://github.com/napolab/y-durableobjects/blob/main/CLAUDE.md Command to publish packages using changesets, typically used for releasing new versions of the library. ```bash pnpm release ``` -------------------------------- ### Integrate y-durableobjects with Hono (Shorthand) Source: https://github.com/napolab/y-durableobjects/blob/main/README.md Demonstrates using the y-durableobjects library with Hono's shorthand routing for simplified integration. It sets up a route for real-time editing using Durable Objects. ```typescript import { Hono } from "hono"; import { YDurableObjects, yRoute } from "y-durableobjects"; type Bindings = { Y_DURABLE_OBJECTS: DurableObjectNamespace>; }; type Env = { Bindings: Bindings; }; const app = new Hono(); const route = app.route( "/editor", yRoute((env) => env.Y_DURABLE_OBJECTS), ); export default route; export type AppType = typeof route; export { YDurableObjects }; ``` -------------------------------- ### Hono RPC Server Implementation (Shorthand) Source: https://github.com/napolab/y-durableobjects/blob/main/README.md This snippet illustrates a concise server-side implementation for Hono RPC using `yRoute`. It sets up a route for real-time collaboration on Yjs documents, making the WebSocket communication straightforward. ```typescript import { Hono } from "hono"; import { YDurableObjects, yRoute } from "y-durableobjects"; type Bindings = { Y_DURABLE_OBJECTS: DurableObjectNamespace>; }; type Env = { Bindings: Bindings; }; const app = new Hono(); const route = app.route( "/editor", yRoute((env) => env.Y_DURABLE_OBJECTS), ); export default route; export type AppType = typeof route; export { YDurableObjects }; ``` -------------------------------- ### Hono RPC Client Implementation Source: https://github.com/napolab/y-durableobjects/blob/main/README.md This client-side snippet shows how to establish a WebSocket connection for Hono RPC using the `hc` utility. It demonstrates creating a typed client to interact with the server-side RPC endpoints. ```typescript import { hc } from "hono/client"; import type { AppType } from "./server"; // Adjust the import path as needed const API_URL = "http://localhost:8787"; export const client = hc(API_URL); const ws = client.editor[":id"].$ws({ param: { id: "example" } }); // ^?const ws: WebSocket ``` -------------------------------- ### Integrate y-durableobjects with Hono (Manual Upgrade) Source: https://github.com/napolab/y-durableobjects/blob/main/README.md Shows how to integrate y-durableobjects with Hono without using the shorthand, specifically handling WebSocket upgrades via fetch. This approach is useful when more control over the request lifecycle is needed. ```typescript import { Hono } from "hono"; import { YDurableObjects, type YDurableObjectsAppType } from "y-durableobjects"; import { upgrade } from "y-durableobjects/helpers/upgrade"; type Bindings = { Y_DURABLE_OBJECTS: DurableObjectNamespace>; }; type Env = { Bindings: Bindings; }; const app = new Hono(); app.get("/editor/:id", upgrade(), async (c) => { const id = c.env.Y_DURABLE_OBJECTS.idFromName(c.req.param("id")); const stub = c.env.Y_DURABLE_OBJECTS.get(id); const url = new URL("/", c.req.url); const client = hc(url.toString(), { fetch: stub.fetch.bind(stub), }); const res = await client.rooms[":id"].$get( { param: { id: c.req.param("id") } }, { init: { headers: c.req.raw.headers } }, ); return new Response(null, { webSocket: res.webSocket, status: res.status, statusText: res.statusText, }); }); export default app; export type AppType = typeof app; export { YDurableObjects }; ``` -------------------------------- ### Hono Integration Helper Source: https://github.com/napolab/y-durableobjects/blob/main/CLAUDE.md A helper function `yRoute()` for integrating y-durableobjects with Hono applications. It handles WebSocket upgrades and connection routing. ```typescript import { Hono } from "hono"; import { serve } from "hono/ws"; import { YDurableObjects } from "./yjs"; const app = new Hono(); app.get('/ws', (c) => { return serve(c, (ws) => { // Handle WebSocket connection for YDurableObjects // ... }); }); export const yRoute = app.fetch; ``` -------------------------------- ### Configure Durable Objects Binding in wrangler.toml Source: https://github.com/napolab/y-durableobjects/blob/main/README.md Sets up the Durable Objects binding in the wrangler.toml file, associating a name with the Durable Object class. This is crucial for Cloudflare Workers to correctly instantiate and manage Durable Objects. ```toml name = "your-worker-name" main = "src/index.ts" compatibility_date = "2024-04-05" account_id = "your-account-id" workers_dev = true # Durable Objects binding [durable_objects] bindings = [ { name = "Y_DURABLE_OBJECTS", class_name = "YDurableObjects" } ] # Durable Objects migrations [[migrations]] tag = "v1" new_classes = ["YDurableObjects"] ``` -------------------------------- ### WSSharedDoc Wrapper Source: https://github.com/napolab/y-durableobjects/blob/main/CLAUDE.md A Yjs document wrapper that supports WebSocket notifications. It manages the awareness protocol for collaborative features and handles document updates and broadcasts. ```typescript import * as Y from "yjs"; import { Awareness } from "y-protocols/awareness"; export class WSSharedDoc extends Y.Doc { private awareness: Awareness; constructor() { super(); this.awareness = new Awareness(this); } // Methods for handling WebSocket messages and awareness updates // ... } ``` -------------------------------- ### Message Type Definitions Source: https://github.com/napolab/y-durableobjects/blob/main/CLAUDE.md Defines the types of binary WebSocket messages used for Yjs synchronization, including sync, awareness, and auth message types. ```typescript export enum MessageType { Sync = 0, Awareness = 1, Auth = 2, // ... other message types } export interface SyncMessage { type: MessageType.Sync; payload: Uint8Array; } export interface AwarenessMessage { type: MessageType.Awareness; payload: Uint8Array; } ``` -------------------------------- ### Check @cloudflare/workers-types Dependency Source: https://github.com/napolab/y-durableobjects/blob/main/README.md Verifies if the @cloudflare/workers-types package is still a dependency in the project. This helps diagnose issues related to Cloudflare environment variables. ```bash pnpm why @cloudflare/workers-types ``` -------------------------------- ### Generate TypeScript Types for Cloudflare Workers Source: https://github.com/napolab/y-durableobjects/blob/main/README.md This command demonstrates how to generate up-to-date TypeScript types for your Cloudflare Workers project using Wrangler. This is crucial for resolving type collisions and ensuring correct environment variable and binding definitions. ```bash wrangler types ``` -------------------------------- ### YDurableObjects Core Class Source: https://github.com/napolab/y-durableobjects/blob/main/CLAUDE.md The main Durable Object class for y-durableobjects. It extends Cloudflare's DurableObject, manages WebSocket connections, Yjs document synchronization, and persistence via YTransactionStorage. It exposes JS RPC methods for document retrieval and updates. ```typescript import { DurableObject } from "cloudflare:workers"; import { YTransactionStorage } from "./storage"; export class YDurableObjects extends DurableObject { private storage: YTransactionStorage; constructor(state) { super(state); this.storage = new YTransactionStorage(state.storage); } async fetch(request) { // Handle WebSocket upgrades and RPC calls // ... } async getYDoc() { // Retrieve Yjs document from storage // ... } async updateYDoc(update) { // Update Yjs document in storage // ... } } ``` -------------------------------- ### YTransactionStorage Persistence Layer Source: https://github.com/napolab/y-durableobjects/blob/main/CLAUDE.md The persistence layer for Yjs updates, utilizing Durable Object storage with transaction support. It implements incremental update storage and periodic compaction. ```typescript import { KVNamespace } from "@cloudflare/workers-types"; export class YTransactionStorage { private storage: KVNamespace; constructor(storage: KVNamespace) { this.storage = storage; } async storeUpdate(key: string, update: Uint8Array) { // Store Yjs update incrementally // ... } async getUpdates(key: string): Promise { // Retrieve stored updates // ... } async compact() { // Perform periodic compaction // ... } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.