ygo

package module
v1.13.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 13, 2026 License: MIT Imports: 8 Imported by: 0

README

Ygo

CI Go Reference Go Report Card Go Version Yjs Protocol Live Demo Codeberg Mirror

Pure-Go port of Yjs, the CRDT framework for collaborative applications.

Ygo speaks the Yjs V1 and V2 wire formats byte-for-byte. JavaScript clients running yjs@13.x synchronize directly with Go servers and vice versa, with both directions verified through 158 cross-language fixture scenarios generated from yjs@13.6.31. The bundled WebSocket server is Hocuspocus-compatible. No CGO; gomobile bind produces an iOS xcframework and Android AAR (manually verified, not run in CI).

Highlights

  • Byte-for-byte wire compatibility, verified in both directions. 158 cross-language fixture scenarios (generated from yjs@13.6.31) cover the V1 and V2 update formats, snapshots, subdocuments, undo, relative positions, GC, awareness, and the sync protocol, JS to Go and Go to JS, plus 56 lib0 primitive vectors. The suite runs in CI on every push, so a regression in either direction fails the build.
  • Pure Go, no CGO — mobile included. Builds for any Go target, compiles to WASM, and cross-compiles freely. gomobile bind produces an iOS xcframework and Android AAR (manually verified on 2026-06-12, not run in CI) carrying a full mobile SDK: editable Text / Map, undo, cursors, and a built-in background sync client (WebSocket + reconnect), so a Swift / Kotlin app only renders UI. No V8, no embedded JavaScript engine, no Rust FFI bridge.
  • Embeddable sync client, offline-first. The client package is a Go-native y-websocket/Hocuspocus provider: handshake, incremental updates, awareness, reconnect with backoff. With a LocalStore it persists the document to disk (pure-Go SQLite), loads it before any network so the app works offline, and syncs edits made offline up on reconnect. The building block for bots, CLI tools, server-side agents, and the mobile SDK (EnableOfflineStore).
  • Complete CRDT type set. Map, Array, Text (rich-text formatting, Quill deltas, embeds), XML types, Awareness, UndoManager, Snapshots / time-travel, and Subdocuments.
  • Change observers. Map.Observe / Array.Observe / Text.Observe deliver Quill-style deltas of exactly what changed; ObserveDeep bubbles events from nested types with their path. Semantic parity with yjs's YMapEvent / YArrayEvent / YTextEvent. On mobile, ObserveChanges hands a native editor the delta as JSON.
  • Compact encoding. Commit-time block squash collapses per-character edits into single items (about 1 byte per character in V1), and garbage collection frees deleted content at commit. On a real-world editing trace V1 document size drops from ~1.97 MB to ~223 KB, competitive with V2.
  • Forward-looking wire handling. ygo already handles both confirmed wire-level changes in the yjs@14 release candidate: 53-bit client IDs throughout (byte-verified above 2^32) and Skip structs in the update stream (decoded as no-op gaps). Full attribution / IdMap support waits for the v14 format to stabilize.
  • Ready-to-run server: yserve. A self-hosted Yjs server in a single static binary — a Hocuspocus alternative with no Node, no Redis, no CGO. Same wire protocol, so existing @hocuspocus/provider / y-websocket clients connect unchanged; SQLite persistence and periodic document versioning built in. Also embeds as a plain http.Handler inside an existing Go backend.
  • EU-sovereign mirror on codeberg.org/Deln0r/ygo, auto-synced from GitHub on every push for adopters who prefer or require EU-hosted code infrastructure.

Live demo: open ygo.deln0r.com in two browser tabs and start typing. Same protocol any standard Yjs ecosystem client speaks, with a pure-Go server behind it.

Quick start

package main

import (
    "fmt"

    "github.com/Deln0r/ygo"
)

func main() {
    src := ygo.NewDoc()
    m := ygo.NewMap(src, "settings")

    txn := src.WriteTxn()
    m.Set(txn, "theme", "dark")
    m.Set(txn, "lang", "go")
    txn.Commit()

    // Encode the source doc's full state as wire bytes.
    update := ygo.EncodeStateAsUpdate(src)

    // Apply to a fresh peer doc — same bytes JS Yjs's Y.applyUpdate consumes.
    dst := ygo.NewDoc()
    if err := ygo.ApplyUpdate(dst, update); err != nil {
        panic(err)
    }

    dstMap := ygo.NewMap(dst, "settings")
    fmt.Println(dstMap.Get("theme")) // dark
}

For a collaborative server backend, see yserve — a stand-alone, Hocuspocus-compatible WebSocket server with SQLite persistence and document versioning, in one static binary:

go run ./cmd/yserve -addr :1234 -store data.db -version-interval 10m
Undo / Redo

Wrap any shared types in an UndoManager to get scoped, grouped Undo / Redo:

d := ygo.NewDoc()
m := ygo.NewMap(d, "settings")

um := ygo.NewUndoManager(d, m) // watch m; defaults to local edits, 500ms grouping
defer um.Close()

txn := d.WriteTxn()
m.Set(txn, "theme", "dark")
txn.Commit()

um.Undo() // m no longer has "theme"
um.Redo() // "theme" == "dark" again

Only local edits under the watched types are captured; remote updates applied via ApplyUpdate are not. Rapid edits inside the capture-timeout window collapse into one undo step; call um.StopCapturing() to force a boundary. The semantics match yjs@13.6.31's UndoManager, checked by cross-language conformance fixtures.

Snapshots / time-travel

Capture a point in a document's history and reconstruct it later. The source doc must have GC disabled so deleted content is retained:

d := ygo.NewDocWithOptions(ygo.Options{DisableGC: true})
txt := ygo.NewText(d, "t")

txn := d.WriteTxn()
txt.Insert(txn, 0, "world!")
txn.Commit()

snap := ygo.CreateSnapshot(d)         // mark this moment
saved := ygo.EncodeSnapshot(snap)     // persist it (byte-compatible with Y.encodeSnapshot)

txn = d.WriteTxn()
txt.Insert(txn, 0, "hello ")          // doc moves on
txn.Commit()

restored, _ := ygo.RestoreSnapshot(d, snap) // reconstruct the marked state
ygo.NewText(restored, "t").String()         // "world!"

The snapshot wire format (EncodeSnapshot / DecodeSnapshot) is byte-compatible with yjs@13.6.31's Y.encodeSnapshot, verified by cross-language fixtures including multi-client delete-set ordering. RestoreSnapshot mirrors Y.createDocFromSnapshot.

Subdocuments

Nest a Y.Doc inside a Map. The parent stores a reference (the subdoc's GUID); the subdocument's own content syncs as a separate update stream:

d := ygo.NewDoc()
m := ygo.NewMap(d, "m")

txn := d.WriteTxn()
sub := m.SetDoc(txn, "child") // nest a new subdocument
txn.Commit()

// after syncing the parent to another replica:
got, ok := m.GetDoc(d, "child") // got.GUID() == sub.GUID()

The ContentDoc wire format (GUID + options) is byte-compatible with yjs@13.6.31, verified by cross-language fixtures. Lifecycle events are observable via d.OnSubdocs (added / removed / loaded GUIDs per transaction); SetDocWithOptions(..., autoLoad) and subdoc.Load() drive the loaded set, so a sync provider knows which nested documents to fetch.

Observing changes

Subscribe to a shared type to learn exactly what changed in each transaction, local or remote:

m := ygo.NewMap(d, "settings")
unsub := m.Observe(func(e *ygo.MapEvent) {
    for key, change := range e.Keys {
        // change.Action is "add" / "update" / "delete"; change.OldValue
        // holds the prior value for update / delete.
        fmt.Printf("%s %s\n", change.Action, key)
    }
})
defer unsub()

Array.Observe and Text.Observe deliver a Quill-style delta ({Insert, Delete, Retain} ops; Text ops carry formatting attributes). Map.ObserveDeep / Array.ObserveDeep fire for changes to nested types too, with each event's Path from the observed type to the change. The event semantics match yjs's YMapEvent / YArrayEvent / YTextEvent, cross-checked against captured reference output.

Status

Feature-complete and stable. The CRDT engine, the V1 and V2 wire formats, and the full type set above are validated bidirectionally against yjs@13.6.31 and exercised in CI on every push. The public API is considered stable for the v1.x line; changes follow semantic versioning, with new functionality as minor releases and breaking changes deferred to a future major.

Layer Status
internal/lib0 varint + RLE encoding done; verified byte-equivalent vs JS lib0@0.2.117 (40 + 16 fixtures)
internal/block (Item, Content, Branch, Splice, Integrate-YATA, TrySquash, Repair, search markers) done; full YATA conflict resolution + per-branch LRU position cache
internal/store (BlockStore, ItemSlice, Materialize) done
internal/doc (Doc, Transaction, TransactionMut) done; lock semantics + root-branch registry
internal/encoding (StateVector, IdSet, Update encode/decode/apply, Pending buffer, V1 + V2 codecs) done; JS Yjs → Go proven by 29 V1 + 32 V2 fixture scenarios; Go → JS proven by 48 reverse fixtures (Map / Array / Text / XmlFragment)
internal/utf16 (UTF-16 length / byte-offset / surrogate-aware split) done
internal/types/Map (Set / Get / Delete / Has / Len / Range / Clear + SetMap / SetArray / SetText) done; nested-type construction supported
internal/types/Array (Insert / InsertRange / Push / Delete / Get / Len / Range / ToSlice + InsertMap / InsertArray / InsertText) done; nested-type construction supported
internal/types/Text (Insert / Delete / String / Length + InsertWithAttributes / Format / InsertEmbed / Range / ToDelta / ApplyDelta) done; full rich-text + Quill delta batch API
Nested-type construction (Map-in-Map, Array-in-Map, etc., to arbitrary depth) done; ContentType wire format + Repair ParentID resolution + pending-queue retry
internal/types/Xml* (XmlFragment, XmlElement, XmlText) done; ProseMirror/Tiptap/BlockNote unblocked. XmlHook (legacy) deferred.
Persistence (Store interface + modernc.org/sqlite reference impl) done; append-only update log, Flush compaction, LoadDoc / GetStateVector / GetDiff helpers; pure-Go (no CGO)
y-sync protocol (internal/sync) done; full Hocuspocus message subset (Sync + Awareness + QueryAwareness + Auth + Stateless + BroadcastStateless + Close + SyncStatus); per-document Auth permission scoping deferred (tech-debt)
Awareness (internal/awareness) done; LWW presence map, JSON wire payload per y-protocols, self-eviction defense, SweepOutdated, decode caps + per-room client cap + tombstone GC (DoS hardening)
server/ (WebSocket sync server) done; http.Handler mount-anywhere shape, per-doc broadcaster, persists every applied update to optional persist.Store, awareness disconnect tombstones + periodic presence sweep (AwarenessTimeout / MaxAwarenessClients)
yserve (Hocuspocus-compat server binary) done; single static binary with SQLite persistence (-store) and periodic document versioning (-version-interval / -keep-versions); cmd/ygo-server remains as a deprecated alias
gomobile/ (app-level mobile SDK for iOS/Android) done; pure-Go (no CGO) bindable SDK with two levels: the full shared type set — Text (UTF-16 mutators), rich text (ApplyDelta / Format / InsertEmbed — Quill deltas in, symmetric with ObserveChanges), Map and Array (typed JSON values, nested types), and XmlFragment / XmlElement / XmlText (ProseMirror / Tiptap) — plus UndoManager, cursor anchors (relative positions), live collaborator presence (ObservePresence / PresenceStates delivering remote cursors and identity as JSON), and an embedded sync Client (NewClient / Connect / Listener) so a Swift / Kotlin app edits the Doc and renders UI while sync runs in the background; plus the bytes-in/bytes-out wire layer for custom transports. gomobile bind was manually verified once (2026-06-12, Xcode 16 + NDK 27 + Go 1.26) to produce a valid Ygo.xcframework (arm64 + simulator universal) and Android .aar (arm64-v8a / armeabi-v7a / x86 / x86_64); the bind step is not run in CI (the pure-Go package compiles in CI, guarding against CGO leak). See gomobile/README.md for commands.
V2 update encoding done; lib0 RLE primitives + column encoder/decoder + Update.{EncodeV2,DecodeV2} + public ygo.{EncodeStateAsUpdateV2,EncodeDiffV2,ApplyUpdateV2}; bidirectional cross-language fixtures vs yjs@13.6.31
Untrusted-input hardening done; every wire-supplied element count in the V1/V2 update, snapshot, id-set, and Any-content decoders is bounded against the input length, closing a length-prefix amplification DoS (a few bytes forcing a multi-terabyte allocation). Continuous fuzzing of the decode + apply paths runs nightly in CI (fuzz.yml) with the discovered crashers committed as regression corpus
dmonad/crdt-benchmarks B1-B4 port done; B1.1-B1.11 / B2.1-B2.4 / B3.1+3+4 / B4 (260k-edit real-world LaTeX trace). Baseline in BENCHMARKS.md.
UndoManager (internal/undo) done; scoped Undo / Redo over Map / Array / Text with capture-timeout grouping, tracked-origin filtering, and a Redone chain for deletion restore. Cross-language conformance vs yjs@13.6.31 (7 scenarios)
Snapshots (CreateSnapshot / EncodeSnapshot / RestoreSnapshot) done; V1 wire format byte-compatible with yjs@13.6.31 (cross-language fixtures incl. multi-client), RestoreSnapshot mirrors Y.createDocFromSnapshot
Subdocuments (Map.SetDoc / Map.GetDoc) done; ContentDoc wire format (GUID + options) byte-compatible with yjs@13.6.31, cross-language fixtures. Lifecycle events via OnSubdocs / autoLoad / Load
Wire client-ID width 53-bit client IDs throughout (uint64 + varint), byte-verified against yjs@13.6.31 for IDs above 2^32. Forward-compatible with the wider client-ID space yjs@14 introduces
Commit-time block squash done; merges same-client adjacent-clock items at commit (~1 byte/char V1), paired with Apply-side partial-overlap slicing for correct remote integration of merged blocks
GC merging done; deleted content is freed at commit (ContentDeleted, byte-aligned with yjs) and adjacent deleted runs are merged. Deleting a nested shared type recursively collapses its whole subtree into garbage-collected runs (cross-language fixtures), matching yjs. Skipped when GC is disabled or for items an UndoManager keeps
Relative positions (cursors) done; CreateRelativePositionFromTypeIndex / CreateAbsolutePositionFromRelativePosition, binary form byte-compatible with Y.encodeRelativePosition, follows undone deletions; cross-language fixtures incl. surrogate pairs and 53-bit client IDs
Versioned persistence done; named point-in-time versions independent of the live log (persist.VersionStore: save / list / load / restore / prune), atomic restore, sqlite reference implementation
Change observers done; Map.Observe (YMapEvent: add / update / delete + oldValue), Array.Observe and Text.Observe (Quill-style insert / delete / retain delta, Text formatting-aware), Map/Array.ObserveDeep (event-path bubbling from nested types). Deltas cross-checked against captured yjs@13.6.31 output; fire on local and remote transactions. gomobile Text/Map.ObserveChanges deliver the delta as Quill JSON

Goals

  1. Binary protocol compatibility with Yjs v13.x in both V1 and V2 wire formats. Byte-for-byte. JS clients sync with Go servers and vice versa, bidirectionally verified.
  2. Idiomatic Go API. Channels for events, explicit transactions, error returns.
  3. Pure Go. No CGO. gomobile bind works for iOS/Android.
  4. Pluggable persistence with modernc.org/sqlite reference implementation.
  5. Performance within 2× of yrs on dmonad/crdt-benchmarks B1-B4. See BENCHMARKS.md.

Non-goals

  • C-FFI surface. Yrs already provides this; Ygo's unique value is pure-Go native binaries.
  • Drop-in replacement for the Node.js Yjs runtime. Ygo is the Go port; use yjs itself if you want a JavaScript runtime.
  • Loro, Automerge, RGA, or other CRDT designs. Ygo implements the Yjs wire format, period.

Wire compatibility

The single most-important guarantee of this project is byte-level wire compatibility with yjs@13.x. This is enforced by 158 cross-language fixture scenarios (plus 56 lib0 primitive vectors):

  • 29 V1 forward fixtures (testdata/yjs-updates.json) — JS Yjs encodes via Y.encodeStateAsUpdate, Go decodes and applies, state matches.
  • 32 V2 forward fixtures (testdata/yjs-update-v2-fixtures.json) — same with Y.encodeStateAsUpdateV2.
  • 48 reverse fixtures (testdata/go-updates.json + go-update-v2-fixtures.json) — Go encodes via EncodeStateAsUpdate / EncodeStateAsUpdateV2, JS Yjs decodes via Y.applyUpdate / Y.applyUpdateV2, state matches.
  • 49 feature fixtures — XML (5), awareness (6), sync protocol (6), undo (7), snapshots (4), subdocuments (3), wire edge cases incl. 53-bit client IDs (3), nested-type GC (4), relative positions (11), all captured from the pinned JS reference and byte-compared in both directions where the feature has a Go encoder.

The fixtures regenerate from pinned yjs@13.6.31 + lib0@0.2.117 + y-protocols@1.0.7 on every CI run; git diff --exit-code testdata/ catches byte-level regressions.

How is this different from Hocuspocus / y-websocket / y-leveldb?

Project Runtime What it provides Relationship to Ygo
yjs (npm) Node / browser The reference CRDT implementation Ygo's wire-format target
y-websocket Node Reference WebSocket server yserve is a Go-native equivalent
Hocuspocus Node Production WebSocket server with auth, persistence, extensions yserve speaks the same 8-message envelope (Sync / Awareness / QueryAwareness / Auth / Stateless / BroadcastStateless / Close / SyncStatus) in one static binary
yrs Rust Reference Rust port Ygo's executable spec for porting decisions
y-leveldb, y-indexeddb Node / browser Persistence backends Ygo's persist/sqlite is a Go-native equivalent
Ygo Go CRDT engine + WS server + persistence in one monorepo, pure-Go for native mobile This project

If you have an existing Yjs deployment and want to move the server side to Go (no Node runtime, single static binary, native iOS / Android via gomobile) — Ygo is the path. If you're starting fresh and your team is comfortable with Node, Hocuspocus is the mature choice.

Benchmarks

See BENCHMARKS.md for the full table. Highlights from B4 (259,778-edit real-world LaTeX paper trace) on Apple M3, Go 1.26:

Metric Ygo V1 Ygo V2 yjs (Node, Intel i5-8400) ywasm (Intel i5-8400)
Apply all edits 20.3 s 20.3 s 5.7 s 28.7 s
Encoded doc size 223 KB 160 KB 160 KB 160 KB
Encode time 0.6 ms 10.5 ms 11 ms 3 ms
Parse time 4.4 ms 4.5 ms 39 ms 16 ms

How to read this:

  • Doc sizes are now at or near yjs parity. V1 lands within 1.4× of yjs (223 KB vs 160 KB; it was 1.97 MB, ~12× bloat, before commit-time block squash + GC shipped). V2 matches yjs byte-for-byte-scale at 160 KB. A 2,000-character sequential insert encodes to ~1.0 byte/char in V1. Squash ships with the paired Apply-side partial-overlap handling that keeps remote integration correct when a peer sends a merged block overlapping the receiver's state.
  • Apply throughput is the trade. ~3.5× yjs wall-clock on different hardware (Apple M3 vs the slower i5-8400, so the normalized gap is wider): the per-commit squash + GC scans that buy the 8.8× smaller documents roughly doubled apply time versus the pre-squash build. Against yrs's published sub-10-s B4 numbers this sits at about 2×, at the DESIGN.md target boundary, with known commit-pipeline optimization headroom. (ywasm is yrs compiled to WebAssembly and is not representative of native yrs — wasm overhead inflates it ~5×.)
  • Encode and parse are fast once the doc is compact: V1 encode 0.6 ms and parse 4.4 ms on the 223 KB document, both ahead of yjs's published numbers on its hardware.

A direct head-to-head harness against native yrs under identical hardware is on the roadmap but not yet run; the numbers above are honest absolute figures with hardware caveats.

Roadmap

Towards v1.0: benchmarks refresh · documentation site · external security audit. (Undo manager, Snapshots, Subdocuments, commit-time block squash, GC merging: done.)

Per-layer port notes live in docs/yrs-port-notes/. Items intentionally deferred or partial are tracked in docs/tech-debt.md. Detailed design decisions in DESIGN.md.

Examples

Runnable examples in examples/:

  • collab-server — embed the WebSocket sync server and wire its hooks (OnConnect, ReadOnly, OnChange, OnLoadDocument), resource caps, a SQLite store, and a /stats endpoint.
  • collab-client — a Go-native sync client: connect, observe remote changes, edit, converge.
  • offline-first — client-side offline persistence with a LocalStore: usable with no network, edits survive restarts and sync up on reconnect.

The core CRDT API also has output-verified runnable examples on pkg.go.dev (Map, Array, Text, two-document sync, UndoManager).

Documentation

License

MIT. See LICENSE.

Acknowledgements

Documentation

Overview

Package ygo is a pure-Go port of the Yjs CRDT framework.

ygo is binary-protocol compatible with the npm yjs package (V1 update encoding), allowing JavaScript clients to synchronize seamlessly with Go servers and vice versa.

Pure-Go means no CGO, so gomobile bind works for iOS/Android targets.

Status: pre-alpha. Public API is unstable.

See https://github.com/Deln0r/ygo for documentation and examples.

Example

Example is the basic shape: create a document, edit a shared type inside a write transaction, and read the value back.

package main

import (
	"fmt"

	"github.com/Deln0r/ygo"
)

func main() {
	doc := ygo.NewDoc()
	settings := ygo.NewMap(doc, "settings")

	txn := doc.WriteTxn()
	settings.Set(txn, "theme", "dark")
	settings.Set(txn, "fontSize", int64(14))
	txn.Commit()

	fmt.Println(settings.Get("theme"))
	fmt.Println(settings.Get("fontSize"))
}
Output:
dark
14
Example (Array)

Example_array shows the shared Array: an ordered sequence you append to and read positionally.

package main

import (
	"fmt"

	"github.com/Deln0r/ygo"
)

func main() {
	doc := ygo.NewDoc()
	todo := ygo.NewArray(doc, "todo")

	txn := doc.WriteTxn()
	todo.Push(txn, "buy milk", "write code")
	txn.Commit()

	fmt.Println(todo.Len())
	fmt.Println(todo.Get(0))
	fmt.Println(todo.Get(1))
}
Output:
2
buy milk
write code
Example (Sync)

Example_sync shows the core CRDT property: two documents that never talked to each other each apply the other's update and converge on the same merged state, independent of order.

package main

import (
	"fmt"

	"github.com/Deln0r/ygo"
)

func main() {
	// Peer A sets a title on its copy.
	a := ygo.NewDoc()
	am := ygo.NewMap(a, "doc")
	wa := a.WriteTxn()
	am.Set(wa, "title", "Hello")
	wa.Commit()

	// Peer B sets a different key on its own copy.
	b := ygo.NewDoc()
	bm := ygo.NewMap(b, "doc")
	wb := b.WriteTxn()
	bm.Set(wb, "author", "Ada")
	wb.Commit()

	// Exchange full-state updates and apply each to the other.
	if err := ygo.ApplyUpdate(a, ygo.EncodeStateAsUpdate(b)); err != nil {
		panic(err)
	}
	if err := ygo.ApplyUpdate(b, ygo.EncodeStateAsUpdate(a)); err != nil {
		panic(err)
	}

	// Both converge to the same merged state.
	fmt.Println(am.Get("title"), am.Get("author"))
	fmt.Println(bm.Get("title"), bm.Get("author"))
}
Output:
Hello Ada
Hello Ada
Example (Text)

Example_text shows the shared Text: a collaborative string edited by index. Inserts commute so concurrent edits converge.

package main

import (
	"fmt"

	"github.com/Deln0r/ygo"
)

func main() {
	doc := ygo.NewDoc()
	note := ygo.NewText(doc, "note")

	txn := doc.WriteTxn()
	_ = note.Insert(txn, 0, "world")
	_ = note.Insert(txn, 0, "hello ")
	txn.Commit()

	fmt.Println(note.String())
}
Output:
hello world
Example (Undo)

Example_undo shows the built-in UndoManager: track a shared type, edit it, then step backward and forward through the edit history.

package main

import (
	"fmt"

	"github.com/Deln0r/ygo"
)

func main() {
	doc := ygo.NewDoc()
	m := ygo.NewMap(doc, "doc")
	undo := ygo.NewUndoManager(doc, m)

	txn := doc.WriteTxn()
	m.Set(txn, "title", "draft")
	txn.Commit()
	fmt.Println(m.Get("title"))

	undo.Undo()
	fmt.Println(m.Has("title"))

	undo.Redo()
	fmt.Println(m.Get("title"))
}
Output:
draft
false
draft

Index

Examples

Constants

View Source
const (
	ChunkString = types.ChunkString
	ChunkEmbed  = types.ChunkEmbed
)

Text.Range emits chunks of either of these kinds.

View Source
const DefaultAwarenessTimeout = awareness.DefaultTimeout

DefaultAwarenessTimeout is the y-protocols convention for stale awareness-entry eviction (30 seconds). Pass to Awareness.SweepOutdated.

View Source
const MaxClientID = doc.MaxClientID

MaxClientID is the upper bound on Doc.ClientID values (2^53 - 1, matching JS Yjs's safe-integer range).

View Source
const Version = "0.0.0-dev"

Version is the current ygo version.

Variables

View Source
var ErrSnapshotGC = errors.New("ygo: RestoreSnapshot requires the source Doc to have GC disabled (NewDocWithOptions with DisableGC: true)")

ErrSnapshotGC is returned by RestoreSnapshot when the source Doc has garbage collection enabled, which can discard content a snapshot needs to reconstruct.

Functions

func ApplyUpdate

func ApplyUpdate(d *Doc, raw []byte) error

ApplyUpdate decodes raw and integrates it into d. Items whose dependencies the local store has not yet seen queue in the per-doc pending buffer and drain automatically on subsequent ApplyUpdate calls that satisfy them.

Use HasPending / MissingSV to inspect the queue.

func ApplyUpdateV2

func ApplyUpdateV2(d *Doc, raw []byte) error

ApplyUpdateV2 decodes V2 wire bytes and integrates them into d. Pending-buffer semantics identical to ApplyUpdate (V1) — items missing causal dependencies queue silently and drain on subsequent ApplyUpdate / ApplyUpdateV2 calls.

V1 and V2 are NOT wire-interchangeable. Calling ApplyUpdateV2 on V1 bytes (or ApplyUpdate on V2 bytes) is undefined behaviour — either errors loudly or yields a semantically-wrong Update that fails integrate. Per the docs there is no autodetect; the caller must know which version they have via the surrounding transport metadata.

func DiffUpdate added in v1.13.0

func DiffUpdate(update, remoteSV []byte) ([]byte, error)

DiffUpdate returns the part of a V1 update that a peer identified by remoteSV (a wire-encoded state vector, e.g. from EncodeStateVector or EncodeStateVectorFromUpdate) is missing. Mirrors yjs diffUpdate: trim a stored update before sending it to a peer that already has part of it.

It reconstructs the update's state and diffs against remoteSV, emitting whole blocks like EncodeDiff. A full update that ygo produces (EncodeStateAsUpdate / MergeUpdates) is self-contained and fully covered; a diff (from EncodeDiff) or a hand-crafted update whose block dependencies are absent drops those unresolved blocks.

func EncodeDiff

func EncodeDiff(d *Doc, remoteSVBytes []byte) ([]byte, error)

EncodeDiff returns the wire-encoded V1 update covering the blocks d has that the remote (per remoteSVBytes) does not. A nil remoteSVBytes is treated as the empty SV — emit everything.

remoteSVBytes is the V1 wire-encoded form of the remote's state vector (the same shape EncodeStateVector produces).

func EncodeDiffV2

func EncodeDiffV2(d *Doc, remoteSVBytes []byte) ([]byte, error)

EncodeDiffV2 is the V2 analogue of EncodeDiff. State-vector argument shape is identical (still V1 wire-encoded SV); only the outgoing update bytes use the V2 column layout.

func EncodeRelativePosition added in v1.1.0

func EncodeRelativePosition(rpos RelativePosition) ([]byte, error)

EncodeRelativePosition serialises rpos to the yjs binary form (byte-compatible with Y.encodeRelativePosition). Errors only on a zero-value rpos with no anchor set.

func EncodeSnapshot added in v0.10.0

func EncodeSnapshot(s Snapshot) []byte

EncodeSnapshot returns the V1 wire encoding of s, byte-compatible with yjs `Y.encodeSnapshot`.

func EncodeStateAsUpdate

func EncodeStateAsUpdate(d *Doc) []byte

EncodeStateAsUpdate returns the wire-encoded V1 update carrying the doc's full state. Apply to a fresh peer doc to bring it up to speed in one shot; same bytes interoperate with JS Yjs's Y.encodeStateAsUpdate.

func EncodeStateAsUpdateV2

func EncodeStateAsUpdateV2(d *Doc) []byte

EncodeStateAsUpdateV2 returns the wire-encoded V2 update carrying the doc's full state. V2 is the column-oriented alternative wire format used by Y.encodeStateAsUpdateV2 / Hocuspocus-V2 paths and some adopters' on-disk persistence layers (y-leveldb, y-indexeddb, SQLite/Postgres Hocuspocus adapters).

V1 and V2 are NOT wire-interchangeable — see ApplyUpdateV2.

func EncodeStateVector

func EncodeStateVector(d *Doc) []byte

EncodeStateVector returns the wire-encoded V1 state vector of d. Sync-protocol callers send this to peers as "here's what I have; send me everything else."

func EncodeStateVectorFromUpdate added in v1.13.0

func EncodeStateVectorFromUpdate(update []byte) ([]byte, error)

EncodeStateVectorFromUpdate computes the state vector a V1 update advances to, directly from the update bytes without reconstructing a document. Mirrors yjs encodeStateVectorFromUpdate: index or diff stored updates server-side without loading the full document into memory.

func EqualSnapshots added in v0.10.0

func EqualSnapshots(a, b Snapshot) bool

EqualSnapshots reports whether two snapshots are identical.

func HasPending

func HasPending(d *Doc) bool

HasPending reports whether d has any queued items awaiting causal dependencies.

func MergeUpdates

func MergeUpdates(updates [][]byte) ([]byte, error)

MergeUpdates decodes every blob in updates in order, applies them to a fresh Doc, and returns a single V1 update blob equivalent to the merged state. Returns nil for an empty input.

Used by persistence layers for compaction (Flush) and by transports that want to batch-coalesce updates before sending.

func MergeUpdatesV2 added in v1.13.0

func MergeUpdatesV2(updates [][]byte) ([]byte, error)

MergeUpdatesV2 is the V2 counterpart of MergeUpdates: it coalesces V2 update blobs into a single equivalent V2 update. Returns nil for an empty input. Like MergeUpdates it reconstructs then re-encodes, so blocks whose causal dependencies are absent across the merged set are dropped rather than preserved behind Skip blocks (as yjs mergeUpdatesV2 would); ygo-produced full updates are self-contained and unaffected.

func MissingSV

func MissingSV(d *Doc) []byte

MissingSV returns the wire-encoded V1 state vector identifying the clocks d needs to receive in order to drain its pending buffer. An empty result means the queue is empty.

Sync-protocol callers send this to peers as a re-fetch request: "I am stuck on items that need updates past this clock."

Types

type AbsolutePosition added in v1.1.0

type AbsolutePosition = types.AbsolutePosition

AbsolutePosition is a resolved RelativePosition: the shared type's branch and the current numeric index within it.

func CreateAbsolutePositionFromRelativePosition added in v1.1.0

func CreateAbsolutePositionFromRelativePosition(d *Doc, rpos RelativePosition) (AbsolutePosition, bool)

CreateAbsolutePositionFromRelativePosition resolves rpos against the current state of d. ok is false when the anchor refers to state this replica has not yet seen or to a garbage-collected range.

Acquires the doc's locks internally; calling it while holding an open Transaction / TransactionMut on the same doc from the same goroutine deadlocks (Go RWMutex is not re-entrant).

type Array

type Array = types.Array

Shared-type wrappers — re-exported from internal/types.

func NewArray

func NewArray(d *Doc, name string) *Array

type ArrayDeltaOp added in v1.2.0

type ArrayDeltaOp = types.ArrayDeltaOp

ArrayDeltaOp is one op of an array change delta: exactly one of Insert (values), Delete (count), or Retain (count) is set.

type ArrayEvent added in v1.2.0

type ArrayEvent = types.ArrayEvent

ArrayEvent is delivered to Array observers (Array.Observe) after a transaction that changed the array. Delta is the Quill-style change description. Semantic parity with yjs YArrayEvent.

type Attrs

type Attrs = types.Attrs

Attrs is the format-attribute map used by Text's rich-text API and DeltaOp. Keys are arbitrary strings; values are JSON-serializable scalars. A nil value clears the attribute on the affected range.

type Awareness

type Awareness = awareness.Awareness

Awareness tracks per-client ephemeral state (cursors, names, selections). Independent of any Doc; the local clientID is passed at construction. Embedders typically pair an Awareness with a Doc and use d.ClientID() as the awareness clientID.

func NewAwareness

func NewAwareness(clientID uint64) *Awareness

NewAwareness returns a fresh Awareness for the given local clientID. Use d.ClientID() to keep the awareness layer in sync with the doc.

type Branch

type Branch = block.Branch

Branch is the low-level shared-data container the types layer wraps. Most callers should use the typed constructors (NewMap, NewArray, NewText, NewXmlFragment) rather than building Branches directly. Re-exported here for advanced cases (custom shared-type implementations, observability code).

type ChunkKind

type ChunkKind = types.ChunkKind

ChunkKind discriminates the variants emitted by Text.Range.

type DeltaOp

type DeltaOp = types.DeltaOp

DeltaOp is one Quill-style delta operation produced by Text.ToDelta and (future) consumed by Text.ApplyDelta.

type Doc

type Doc = doc.Doc

Doc is a single CRDT replica — the local view of a collaborative document. Construct with NewDoc; mutate via WriteTxn; read via ReadTxn. See the doc-comment on the underlying type for the full concurrency contract.

func NewDoc

func NewDoc() *Doc

NewDoc returns a fresh Doc with default options and a random client identifier.

func NewDocWithOptions

func NewDocWithOptions(opts Options) *Doc

NewDocWithOptions returns a fresh Doc with the given options.

func RestoreSnapshot added in v0.10.0

func RestoreSnapshot(d *Doc, snap Snapshot) (*Doc, error)

RestoreSnapshot reconstructs the document state that d had at the moment snap was taken, returning it as a new Doc. Byte-equivalent to yjs `Y.createDocFromSnapshot`.

d must have been created with GC disabled (ygo.NewDocWithOptions with DisableGC: true); otherwise deleted content the snapshot references may have been collected and RestoreSnapshot returns ErrSnapshotGC. The returned Doc also has GC disabled so it can itself be snapshotted.

The source Doc is not logically changed (the reconstruction may split blocks internally, which is transparent to readers).

type KeyChange added in v1.2.0

type KeyChange = types.KeyChange

KeyChange describes one map key's change in a MapEvent: Action is "add", "update", or "delete"; OldValue is the prior value (nil for "add").

type Map

type Map = types.Map

Shared-type wrappers — re-exported from internal/types.

func NewMap

func NewMap(d *Doc, name string) *Map

NewMap, NewArray, NewText, NewXmlFragment return wrappers bound to the root branch with the given name in d. The branch is lazily created on first call; subsequent calls with the same name return wrappers pointing at the same underlying state.

Per-branch type discipline: a branch should be used as ONE type (Map OR Array OR Text OR XML). Mixing types on the same root branch produces undefined behaviour.

type MapEvent added in v1.2.0

type MapEvent = types.MapEvent

MapEvent is delivered to Map observers (Map.Observe) after a transaction that changed the map, describing which keys changed and how. Byte-for-byte semantic parity with yjs YMapEvent.

type Options

type Options = doc.Options

Options bundles per-Doc settings (deterministic ClientID, GC disable). The zero value is the recommended configuration.

type RelativePosition added in v1.1.0

type RelativePosition = types.RelativePosition

RelativePosition is a cursor/selection anchor attached to the document model rather than a numeric index, so it stays on the same logical character as concurrent edits land. Create one with CreateRelativePositionFromTypeIndex, ship it between peers with EncodeRelativePosition (byte-compatible with Y.encodeRelativePosition), and resolve it back to an index with CreateAbsolutePositionFromRelativePosition.

func CreateRelativePositionFromTypeIndex added in v1.1.0

func CreateRelativePositionFromTypeIndex(t SharedType, index uint64, assoc int64) (RelativePosition, error)

CreateRelativePositionFromTypeIndex anchors index within the shared type t (any wrapper: Map, Array, Text, Xml*). index counts UTF-16 code units for Text, elements for Array. assoc >= 0 sticks to the character after the position (default for cursors), assoc < 0 to the character before it.

func DecodeRelativePosition added in v1.1.0

func DecodeRelativePosition(buf []byte) (RelativePosition, error)

DecodeRelativePosition parses the yjs binary form.

type SharedType added in v1.1.0

type SharedType = UndoScope

SharedType is any shared-type wrapper (Map, Array, Text, XmlFragment, XmlElement, XmlText). Alias of UndoScope; both name the same one-method interface.

type Snapshot added in v0.10.0

type Snapshot = encoding.Snapshot

Snapshot is a point-in-time marker of a document's history (the deleted ID ranges plus per-client clock heads as of the snapshot). Encode it with EncodeSnapshot for storage; reconstruct the document state it captured with RestoreSnapshot (see the Snapshot doc).

For time-travel to work, create the doc with GC disabled (ygo.NewDocWithOptions with DisableGC) so deleted content the snapshot references is retained.

func CreateSnapshot added in v0.10.0

func CreateSnapshot(d *Doc) Snapshot

CreateSnapshot captures the current state of d as a Snapshot. Byte-compatible with yjs `Y.snapshot(doc)`.

func DecodeSnapshot added in v0.10.0

func DecodeSnapshot(buf []byte) (Snapshot, error)

DecodeSnapshot parses a V1 snapshot produced by EncodeSnapshot or yjs `Y.encodeSnapshot`.

type SubdocsEvent added in v1.0.0

type SubdocsEvent = doc.SubdocsEvent

SubdocsEvent carries the subdocument lifecycle changes of one transaction: GUIDs added, removed, and loaded. Observe with Doc.OnSubdocs.

type Text

type Text = types.Text

Shared-type wrappers — re-exported from internal/types.

func NewText

func NewText(d *Doc, name string) *Text

type TextEvent added in v1.2.0

type TextEvent = types.TextEvent

TextEvent is delivered to Text observers (Text.Observe) after a transaction that changed the text. Delta is the formatting-aware Quill-style change description. Semantic parity with yjs YTextEvent.

type Transaction

type Transaction = doc.Transaction

Transaction is a read-only transaction holding the doc's read lock for its lifetime. Created by Doc.ReadTxn; released by Close.

type TransactionMut

type TransactionMut = doc.TransactionMut

TransactionMut is a write transaction holding the doc's write lock. Created by Doc.WriteTxn; released by Commit.

type UndoManager added in v0.10.0

type UndoManager = undo.UndoManager

UndoManager records local mutations under a scope of shared types and reverses them with Undo / Redo. It subscribes to the doc's transaction lifecycle; close it with Close when no longer needed.

Scope is given as the typed wrappers themselves (a Map, Array, Text, or XML type). Only mutations under one of the scoped types, made by a tracked origin (local edits by default), are captured. Bursty edits within the capture-timeout window collapse into a single undo step.

m := ygo.NewMap(d, "settings")
um := ygo.NewUndoManager(d, m)
defer um.Close()
// ... edits to m ...
um.Undo() // reverts the last captured step

func NewUndoManager added in v0.10.0

func NewUndoManager(d *Doc, scope ...UndoScope) *UndoManager

NewUndoManager creates an UndoManager on d watching the given scope of shared types. At least one scope type is required.

um := ygo.NewUndoManager(d, myMap, myArray)

func NewUndoManagerWithOptions added in v0.10.0

func NewUndoManagerWithOptions(d *Doc, opts UndoManagerOptions, scope ...UndoScope) *UndoManager

NewUndoManagerWithOptions is NewUndoManager with explicit options.

type UndoManagerOptions added in v0.10.0

type UndoManagerOptions = undo.Options

UndoManagerOptions configures an UndoManager. A zero value selects the defaults: 500 ms capture timeout, track local (nil) origin only.

type UndoScope added in v0.10.0

type UndoScope interface {
	Branch() *Branch
}

UndoScope is anything an UndoManager can watch. Every shared-type wrapper (Map, Array, Text, XmlFragment, XmlElement, XmlText) satisfies it via its Branch method.

type XmlElement

type XmlElement = types.XmlElement

Shared-type wrappers — re-exported from internal/types.

func NewXmlElement

func NewXmlElement(d *Doc, name string) *XmlElement

NewXmlElement wraps a branch as an XmlElement. Typically used for root-level XML where the branch was constructed via d.Branch(name); nested elements should be constructed via XmlFragment.InsertXmlElement / XmlElement.InsertXmlElement which set TypeRef and Name automatically.

type XmlFragment

type XmlFragment = types.XmlFragment

Shared-type wrappers — re-exported from internal/types.

func NewXmlFragment

func NewXmlFragment(d *Doc, name string) *XmlFragment

type XmlText

type XmlText = types.XmlText

Shared-type wrappers — re-exported from internal/types.

func NewXmlText

func NewXmlText(d *Doc, name string) *XmlText

Directories

Path Synopsis
Package benchmarks ports the dmonad/crdt-benchmarks B1-B4 workload suite to ygo.
Package benchmarks ports the dmonad/crdt-benchmarks B1-B4 workload suite to ygo.
Package client is a Yjs sync provider over WebSocket: the Go equivalent of y-websocket's WebsocketProvider, compatible with yserve, Hocuspocus, and the reference y-websocket server.
Package client is a Yjs sync provider over WebSocket: the Go equivalent of y-websocket's WebsocketProvider, compatible with yserve, Hocuspocus, and the reference y-websocket server.
cmd
gen-go-fixtures command
gen-go-fixtures generates reverse-direction wire-format fixtures: Go encodes Doc state via EncodeStateAsUpdate (V1) and EncodeStateAsUpdateV2, captures the bytes + expected state, and writes them as JSON.
gen-go-fixtures generates reverse-direction wire-format fixtures: Go encodes Doc state via EncodeStateAsUpdate (V1) and EncodeStateAsUpdateV2, captures the bytes + expected state, and writes them as JSON.
ygo-server command
Command ygo-server is the legacy name of the stand-alone WebSocket sync server for ygo documents.
Command ygo-server is the legacy name of the stand-alone WebSocket sync server for ygo documents.
yserve command
Command yserve is a self-hosted Yjs sync server in a single static binary: a drop-in replacement for a Hocuspocus deployment with no Node runtime, no Redis, and no CGO.
Command yserve is a self-hosted Yjs sync server in a single static binary: a drop-in replacement for a Hocuspocus deployment with no Node runtime, no Redis, and no CGO.
examples
collab-client command
Command collab-client is a runnable example of the ygo Go-native sync client.
Command collab-client is a runnable example of the ygo Go-native sync client.
collab-server command
Command collab-server is a runnable example of embedding the ygo WebSocket sync server in your own Go backend and wiring its library-only extension points: connection lifecycle hooks, read-only viewers, an on-change side effect, first-load seeding, resource caps, and a live stats endpoint.
Command collab-server is a runnable example of embedding the ygo WebSocket sync server in your own Go backend and wiring its library-only extension points: connection lifecycle hooks, read-only viewers, an on-change side effect, first-load seeding, resource caps, and a live stats endpoint.
offline-first command
Command offline-first demonstrates the ygo client's offline-first persistence.
Command offline-first demonstrates the ygo client's offline-first persistence.
Package gomobile is the bytes-in/bytes-out subset of the ygo API designed to survive `gomobile bind`.
Package gomobile is the bytes-in/bytes-out subset of the ygo API designed to survive `gomobile bind`.
internal
awareness
Package awareness implements the y-protocols Awareness layer — the ephemeral, presence-style sibling of the document CRDT used to track per-client transient state like cursor positions, user names, and selection ranges.
Package awareness implements the y-protocols Awareness layer — the ephemeral, presence-style sibling of the document CRDT used to track per-client transient state like cursor positions, user names, and selection ranges.
block
Package block defines the building blocks of a Yjs document.
Package block defines the building blocks of a Yjs document.
doc
Package doc owns the Doc and Transaction types — the document container plus its mutation-lifecycle wrapper.
Package doc owns the Doc and Transaction types — the document container plus its mutation-lifecycle wrapper.
encoding
Package encoding implements the V1 wire format yrs and JS Yjs use for state vectors, delete sets, and document updates.
Package encoding implements the V1 wire format yrs and JS Yjs use for state vectors, delete sets, and document updates.
lib0
Package lib0 implements the binary encoding format used by Yjs.
Package lib0 implements the binary encoding format used by Yjs.
store
Package store implements the per-client block storage that owns the memory for every Item in a Yjs document.
Package store implements the per-client block storage that owns the memory for every Item in a Yjs document.
sync
Package sync implements the y-protocols/sync wire format and the Hocuspocus outer message envelope.
Package sync implements the y-protocols/sync wire format and the Hocuspocus outer message envelope.
types
Package types holds the user-facing shared CRDT collection types: Map, Array, Text, XmlElement / XmlFragment / XmlText.
Package types holds the user-facing shared CRDT collection types: Map, Array, Text, XmlElement / XmlFragment / XmlText.
undo
Package undo implements the Yjs UndoManager semantics in pure Go.
Package undo implements the Yjs UndoManager semantics in pure Go.
utf16
Package utf16 provides UTF-16 code-unit length and offset helpers over Go's UTF-8 strings.
Package utf16 provides UTF-16 code-unit length and offset helpers over Go's UTF-8 strings.
Package persist defines the storage contract for ygo documents and provides helpers that turn stored update logs back into live Docs.
Package persist defines the storage contract for ygo documents and provides helpers that turn stored update logs back into live Docs.
sqlite
Package sqlite is the reference persist.Store implementation backed by modernc.org/sqlite.
Package sqlite is the reference persist.Store implementation backed by modernc.org/sqlite.
Package server implements the y-websocket / Hocuspocus-compatible WebSocket sync server for ygo documents.
Package server implements the y-websocket / Hocuspocus-compatible WebSocket sync server for ygo documents.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL