Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/fix-cloudflare-env-type-collision.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
"y-durableobjects": patch
---

Fix Cloudflare Env type collision and improve TypeScript support

This patch resolves type collision issues and improves TypeScript support:

- **Fixed CI failures**: Removed unavailable @cloudflare/workers-types references from tsconfig.json that were causing TypeScript compilation errors
- **Adopted wrangler types**: Added worker-configuration.d.ts generated by `wrangler types` (introduced in Wrangler v3) for accurate type definitions
- **Resolved type collisions**: Eliminated conflicts where empty Cloudflare.Env from node_modules overwrote project-specific environment types
- **Enhanced documentation**: Added comprehensive troubleshooting guide for type collision issues

Users benefit automatically from improved type support without needing to modify their code. The `wrangler types` command is now the recommended approach for generating Cloudflare Workers TypeScript types.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
node_modules
.turbo
dist
build
build
.mcp.json
.claude/
3 changes: 2 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ example
node_modules
.turbo
pnpm-lock.yaml
dist
dist
worker-configuration.d.ts
67 changes: 67 additions & 0 deletions .serena/project.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# language of the project (csharp, python, rust, java, typescript, go, cpp, or ruby)
# * For C, use cpp
# * For JavaScript, use typescript
# Special requirements:
# * csharp: Requires the presence of a .sln file in the project folder.
language: typescript

# whether to use the project's gitignore file to ignore files
# Added on 2025-04-07
ignore_all_files_in_gitignore: true
# list of additional paths to ignore
# same syntax as gitignore, so you can use * and **
# Was previously called `ignored_dirs`, please update your config if you are using that.
# Added (renamed)on 2025-04-07
ignored_paths: []

# whether the project is in read-only mode
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
# Added on 2025-04-18
read_only: false

# list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
# Below is the complete list of tools for convenience.
# To make sure you have the latest list of tools, and to view their descriptions,
# execute `uv run scripts/print_tool_overview.py`.
#
# * `activate_project`: Activates a project by name.
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
# * `create_text_file`: Creates/overwrites a file in the project directory.
# * `delete_lines`: Deletes a range of lines within a file.
# * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
# * `execute_shell_command`: Executes a shell command.
# * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
# * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
# * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file or directory.
# * `initial_instructions`: Gets the initial instructions for the current project.
# Should only be used in settings where the system prompt cannot be set,
# e.g. in clients you have no control over, like Claude Desktop.
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
# * `insert_at_line`: Inserts content at a given line in a file.
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
# * `list_memories`: Lists memories in Serena's project-specific memory store.
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
# * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
# * `read_file`: Reads a file within the project directory.
# * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
# * `remove_project`: Removes a project from the Serena configuration.
# * `replace_lines`: Replaces a range of lines within a file with new content.
# * `replace_symbol_body`: Replaces the full definition of a symbol.
# * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
# * `search_for_pattern`: Performs a search for a pattern in the project.
# * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
# * `switch_modes`: Activates modes by providing a list of their names
# * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
# * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
# * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
# * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
excluded_tools: []

# initial prompt for the project. It will always be given to the LLM upon activating the project
# (contrary to the memories, which are loaded on demand).
initial_prompt: ""

project_name: "y-durableobjects"
89 changes: 89 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

`y-durableobjects` is a library for real-time collaboration in Cloudflare Workers using Yjs and Durable Objects. It provides WebSocket-based synchronization for Yjs documents with persistent storage.

## Common Development Commands

### Build and Development

- `pnpm build` - Build the library using tsup
- `pnpm typecheck` - Run TypeScript type checking
- `pnpm lint` - Run all linters (ESLint and Prettier)
- `pnpm fmt` - Format code with Prettier and ESLint
- `pnpm test` - Run tests with Vitest

### Testing

- Tests use Vitest with Cloudflare Workers pool
- Run a single test: `pnpm test path/to/test.test.ts`
- Tests are configured with `vitest.config.ts` using Cloudflare Workers environment

### Release Process

- `pnpm release` - Publish packages using changesets

## Architecture

### Core Components

1. **YDurableObjects** (`src/yjs/index.ts`)

- Main Durable Object class extending Cloudflare's DurableObject
- Manages WebSocket connections and Yjs document synchronization
- Handles persistence through YTransactionStorage
- Provides JS RPC methods: `getYDoc()` and `updateYDoc()`

2. **WSSharedDoc** (`src/yjs/remote/ws-shared-doc.ts`)

- Yjs document wrapper with WebSocket notification support
- Manages awareness protocol for collaborative features
- Handles document updates and broadcasts

3. **YTransactionStorage** (`src/yjs/storage/index.ts`)

- Persistence layer for Yjs updates
- Uses Durable Object storage with transaction support
- Implements incremental update storage with periodic compaction

4. **Hono Integration** (`src/index.ts`)
- Provides `yRoute()` helper for easy Hono app integration
- Handles WebSocket upgrade and connection routing

### Message Protocol

- Uses binary WebSocket messages for Yjs synchronization
- Message types defined in `src/yjs/message-type/index.ts`
- Supports sync, awareness, and auth message types

### Development Constraints

1. **Cloudflare Workers Environment**

- Code must be compatible with Workers runtime
- Uses Cloudflare-specific APIs (DurableObject, WebSocketPair)
- External imports marked in tsup config: `hono`, `/cloudflare:/`

2. **TypeScript Strict Mode**

- Strict boolean expressions enforced
- No explicit any allowed
- Consistent type imports/exports required

3. **Code Style**
- Kebab-case for filenames
- No console.log in production code
- Import ordering enforced by ESLint
- Prettier formatting required

### Testing Approach

Tests follow these patterns:

- Unit tests for individual components
- Integration tests using Cloudflare Workers test environment
- WebSocket connection tests with mock implementations
- Storage tests with in-memory implementations
50 changes: 50 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -313,3 +313,53 @@ export const client = hc<AppType>(API_URL);
const ws = client.editor[":id"].$ws({ param: { id: "example" } });
// ^?const ws: WebSocket
```

## Troubleshooting

### Cloudflare Env Type Collision

If you encounter TypeScript errors related to `Cloudflare.Env` type being empty or undefined, this is likely due to a type collision issue.

#### Problem

The issue occurs because `y-durableobjects` requires `@cloudflare/workers-types` as a peer dependency, which can create an empty `Cloudflare.Env` interface in `node_modules`. This empty interface overwrites your project's custom environment types and causes the `worker-configuration.d.ts` file generated from `wrangler types` to be ignored.

#### Recommended Approach

Starting with Wrangler v3, the `wrangler types` command is the recommended approach for generating TypeScript types for Cloudflare Workers. This command generates types based on your project's configuration, compatibility date, and bindings, ensuring accurate and up-to-date type definitions.

To generate types for your project:

```bash
wrangler types
```

This will create a `worker-configuration.d.ts` file (or similar) with the proper type definitions for your Cloudflare Workers environment.

#### Solution

If `Cloudflare.Env` remains empty even after upgrading to the latest `y-durableobjects` version, follow these steps:

1. **Check for remaining dependencies:**

```bash
pnpm why @cloudflare/workers-types
```

2. **Clean install dependencies:**

```bash
# Delete lock files and node_modules
rm -rf node_modules pnpm-lock.yaml
# Reinstall dependencies
pnpm install
```

3. **Verify the fix:**
Run `pnpm why @cloudflare/workers-types` again. If it returns nothing, the issue is resolved.

This issue was addressed in [PR #62](https://github.com/napolab/y-durableobjects/pull/62), but residual `@cloudflare/workers-types` dependencies from `wrangler` may still remain in your lock file until you perform a clean install.

```

```
7 changes: 3 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@
"fmt:eslint": "eslint . --ext .ts,.tsx --fix",
"publint": "publint",
"release": "changeset publish",
"test": "vitest --passWithNoTests"
"test": "vitest run --passWithNoTests",
"test:watch": "vitest --passWithNoTests"
},
"author": "naporin0624",
"files": [
Expand All @@ -76,7 +77,6 @@
"devDependencies": {
"@changesets/cli": "^2.29.2",
"@cloudflare/vitest-pool-workers": "^0.8.18",
"@cloudflare/workers-types": "^4.20250417.0",
"@eslint/compat": "^1.2.8",
"@eslint/eslintrc": "^3.3.1",
"@eslint/js": "^9.24.0",
Expand All @@ -103,15 +103,14 @@
"typescript": "^5.8.3",
"typescript-eslint": "^8.30.1",
"vitest": "3.0.9",
"wrangler": "^4.12.0"
"wrangler": "^4.27.0"
},
"dependencies": {
"lib0": "^0.2.104",
"y-protocols": "^1.0.6",
"yjs": "^13.6.24"
},
"peerDependencies": {
"@cloudflare/workers-types": ">=4.20240405.0",
"hono": ">=4.3"
},
"packageManager": "pnpm@10.8.1"
Expand Down
Loading
Loading