@dovetail-ts/crdt 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # @dovetail-ts/crdt
2
+
3
+ ## 1.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - 480744b: First release of Dovetail: real-time and offline sync for Ember.
8
+
9
+ - `@dovetail-ts/core`: the connection life cycle, live store subscriptions, the optimistic ledger with rebase and rollback, the offline write queue in IndexedDB with a leader tab and dead letters, `DocSession` and `PresenceRoom`.
10
+ - `@dovetail-ts/warp-drive`: the store feed into WarpDrive.
11
+ - `@dovetail-ts/crdt`, `crdt-yjs`, `crdt-loro` and `crdt-automerge`: one `DocEngine` interface with three engines.
12
+ - `@dovetail-ts/tiptap`: co-editing in Tiptap 3 with carets, per-user undo, versions and comment threads.
13
+ - `@dovetail-ts/ember`, `notifications` and `inspector`: presence and status components, the inbox, toasts and activity feeds, and a dev panel.
14
+ - `@dovetail-ts/server`, the transports (`transport-ws`, `transport-sse`, `transport-cable`) and `conformance`: a Node server and one wire protocol that the Rails gems also pass.
15
+ - Adapters for Hocuspocus, Liveblocks, PartyKit and Supabase, and integrations for Switchyard, Millwork, Benchdog and Lattice. The Neon adapter is not in 1.0: it waits for a stable Neon Realtime client (1.1).
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Joe Gaudet
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,14 @@
1
- # Temporary Holding Version
1
+ # @dovetail-ts/crdt
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The `DocEngine` and `DocStorage` interfaces that every CRDT engine and doc store implements.
4
+
5
+ Part of [Dovetail](https://joegaudet.com/dovetail/). Not released yet.
6
+
7
+ - `DocEngine`: `name`, `capabilities`, `create()` and `load(bytes)`.
8
+ - `DocHandle`: updates, state vectors, `map(name)`, `awareness`, and the optional `versions`,
9
+ `undoScope`, `relativePosition` and `absolutePosition`.
10
+ - `syncStep1` and `applySyncStep`: the two steps of the `doc-sync` message.
11
+ - `CapabilityError` and `requireCapability`: the error for a feature that an engine does not have.
12
+ - `DocStorage` and `MemoryDocStorage`: the doc updates that wait while the client is offline.
13
+
14
+ The Yjs engine (`@dovetail-ts/crdt-yjs`) is the reference implementation.
@@ -0,0 +1,13 @@
1
+ import type { AwarenessChange, DocAwareness, JsonObject, JsonValue } from './engine';
2
+ /** The awareness of the protocol: a JSON state for each client id. */
3
+ export declare class JsonAwareness implements DocAwareness {
4
+ #private;
5
+ readonly clientId: string;
6
+ constructor(clientId: string);
7
+ getLocalState(): JsonObject | null;
8
+ setLocalState(state: JsonObject | null): void;
9
+ setLocalStateField(field: string, value: JsonValue): void;
10
+ getStates(): Map<string, JsonObject>;
11
+ applyRemoteState(clientId: string, state: JsonObject | null): void;
12
+ onChange(listener: (change: AwarenessChange) => void): () => void;
13
+ }
@@ -0,0 +1,165 @@
1
+ /** A JSON value. Awareness states and shared map values are JSON. */
2
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
3
+ [key: string]: JsonValue;
4
+ };
5
+ /** A JSON object. */
6
+ export type JsonObject = {
7
+ [key: string]: JsonValue;
8
+ };
9
+ /**
10
+ * The features of an engine. An engine gives a feature only when its ProseMirror binding has it
11
+ * (the capability matrix of the plan). Code checks a feature here before it uses it.
12
+ */
13
+ export interface EngineCapabilities {
14
+ /** A Tiptap binding: the content of an editor is in the document. */
15
+ tiptap: boolean;
16
+ /** Remote carets and selections, from awareness. */
17
+ cursors: boolean;
18
+ /** Undo and redo of the changes of one origin only (`DocHandle.undoScope`). */
19
+ undo: boolean;
20
+ /** Versions: create, list, open and restore (`DocHandle.versions`). */
21
+ history: boolean;
22
+ /** Positions that follow edits (`DocHandle.relativePosition`), for comment anchors. */
23
+ commentAnchors: boolean;
24
+ }
25
+ /** The name of one feature of `EngineCapabilities`. */
26
+ export type Capability = keyof EngineCapabilities;
27
+ /** The error for a feature that the engine does not have. */
28
+ export declare class CapabilityError extends Error {
29
+ readonly engine: string;
30
+ readonly capability: Capability;
31
+ constructor(engine: string, capability: Capability);
32
+ }
33
+ /** Throws a `CapabilityError` when `engine` does not have `capability`. */
34
+ export declare function requireCapability(engine: DocEngine, capability: Capability): void;
35
+ /** A CRDT engine: it makes documents. */
36
+ export interface DocEngine {
37
+ /** The name of the engine, as `yjs`, `loro` or `automerge`. */
38
+ readonly name: string;
39
+ readonly capabilities: EngineCapabilities;
40
+ /** A new, empty document. */
41
+ create(): DocHandle;
42
+ /** A document from the bytes of `DocHandle.snapshot()` or `DocHandle.encodeUpdate()`. */
43
+ load(snapshot: Uint8Array): DocHandle;
44
+ }
45
+ /** One CRDT document. Updates, state vectors and snapshots are the bytes of the engine. */
46
+ export interface DocHandle {
47
+ /** The engine that made this document. */
48
+ readonly engine: DocEngine;
49
+ /** Merges an update from a peer or from storage. `origin` comes back in `onUpdate`. */
50
+ applyUpdate(update: Uint8Array, origin?: unknown): void;
51
+ /** What this document has, for the first step of the sync (`doc-sync` step 1). */
52
+ encodeStateVector(): Uint8Array;
53
+ /** The changes that a peer with `stateVector` does not have. All changes without it. */
54
+ encodeUpdate(stateVector?: Uint8Array): Uint8Array;
55
+ /** The full state, for `DocEngine.load`. */
56
+ snapshot(): Uint8Array;
57
+ /** Calls `listener` for each change, local or merged. Returns a function that stops it. */
58
+ onUpdate(listener: (update: Uint8Array, origin: unknown) => void): () => void;
59
+ /**
60
+ * A map of JSON values in the document, so it syncs with the content. Names that start
61
+ * with `dovetail:` are for Dovetail (comment threads and versions).
62
+ */
63
+ map(name: string): SharedMap;
64
+ /** The awareness of the document: the state of each client (user, cursor, typing). */
65
+ readonly awareness: DocAwareness;
66
+ /** The versions of the document. Absent without `history`. */
67
+ readonly versions?: DocVersions;
68
+ /** An undo scope for the changes of one origin (per-user undo). Absent without `undo`. */
69
+ undoScope?(origin: unknown): UndoScope;
70
+ /**
71
+ * A position in the root type `field` that stays on the same content while peers edit.
72
+ * Absent without `commentAnchors`.
73
+ */
74
+ relativePosition?(field: string, index: number): Uint8Array;
75
+ /** The index of a relative position now, or null when its parent is gone. */
76
+ absolutePosition?(position: Uint8Array): number | null;
77
+ /** Stops the document and its awareness. */
78
+ destroy(): void;
79
+ }
80
+ /** A map of JSON values in a document. Each key merges on its own (the last write wins). */
81
+ export interface SharedMap {
82
+ get(key: string): JsonValue | undefined;
83
+ set(key: string, value: JsonValue, origin?: unknown): void;
84
+ delete(key: string, origin?: unknown): void;
85
+ entries(): [string, JsonValue][];
86
+ /** Calls `listener` with the changed keys, for local and merged changes. */
87
+ onChange(listener: (keys: string[], origin: unknown) => void): () => void;
88
+ }
89
+ /** The change of an awareness: the client ids that came, changed and went. */
90
+ export interface AwarenessChange {
91
+ added: string[];
92
+ updated: string[];
93
+ removed: string[];
94
+ /** True when the local state changed. Send `getLocalState()` in an `awareness` message. */
95
+ local: boolean;
96
+ }
97
+ /**
98
+ * The state of each client of a document: the user, the status, the cursor and typing. It
99
+ * matches the `awareness` message of the protocol: a JSON state for each `clientId`.
100
+ */
101
+ export interface DocAwareness {
102
+ /** The id of this client in `getStates()`. */
103
+ readonly clientId: string;
104
+ getLocalState(): JsonObject | null;
105
+ /** Sets the local state. null removes this client. */
106
+ setLocalState(state: JsonObject | null): void;
107
+ setLocalStateField(field: string, value: JsonValue): void;
108
+ /** The state of each client, this client included. */
109
+ getStates(): Map<string, JsonObject>;
110
+ /** Applies the state of a remote client from an `awareness` message. null removes it. */
111
+ applyRemoteState(clientId: string, state: JsonObject | null): void;
112
+ /** Calls `listener` for each change. Returns a function that stops it. */
113
+ onChange(listener: (change: AwarenessChange) => void): () => void;
114
+ }
115
+ /** A named version of a document. */
116
+ export interface Version {
117
+ id: string;
118
+ name: string;
119
+ /** An ISO 8601 date-time. */
120
+ createdAt: string;
121
+ /** The id of the user that made the version, or null. */
122
+ by: string | null;
123
+ }
124
+ /** The versions of a document. They are in the document, so they sync. */
125
+ export interface DocVersions {
126
+ /** The versions, the oldest first. */
127
+ list(): Version[];
128
+ /** Keeps the content now as a new version. */
129
+ create(options?: {
130
+ name?: string;
131
+ by?: string | null;
132
+ }): Version;
133
+ /** A new document with the content of a version, for a preview. Destroy it after use. */
134
+ open(id: string): DocHandle;
135
+ /**
136
+ * Makes the content equal to the version, as a new change with `origin`. The comment
137
+ * threads and the versions stay.
138
+ */
139
+ restore(id: string, origin?: unknown): void;
140
+ /** Calls `listener` when a version is added, here or by a peer. */
141
+ onChange(listener: () => void): () => void;
142
+ }
143
+ /** The undo and redo of one origin. */
144
+ export interface UndoScope {
145
+ undo(): boolean;
146
+ redo(): boolean;
147
+ readonly canUndo: boolean;
148
+ readonly canRedo: boolean;
149
+ destroy(): void;
150
+ }
151
+ /** A `doc-sync` step of the protocol, with bytes. The transport encodes them as base64. */
152
+ export type DocSyncStep = {
153
+ step: 1;
154
+ stateVector: Uint8Array;
155
+ } | {
156
+ step: 2;
157
+ update: Uint8Array;
158
+ };
159
+ /** Step 1: what this document has. Send it when the client joins the room. */
160
+ export declare function syncStep1(handle: DocHandle): DocSyncStep;
161
+ /**
162
+ * Applies a `doc-sync` step from a peer. Step 1 gives the step 2 answer to send back. Step 2
163
+ * merges the update with `origin` and gives nothing to send.
164
+ */
165
+ export declare function applySyncStep(handle: DocHandle, message: DocSyncStep, origin?: unknown): DocSyncStep | null;
@@ -0,0 +1,5 @@
1
+ export { applySyncStep, CapabilityError, requireCapability, syncStep1 } from './engine';
2
+ export type { AwarenessChange, Capability, DocAwareness, DocEngine, DocHandle, DocSyncStep, DocVersions, EngineCapabilities, JsonObject, JsonValue, SharedMap, UndoScope, Version, } from './engine';
3
+ export { JsonAwareness } from './awareness';
4
+ export { MemoryDocStorage } from './storage';
5
+ export type { DocKey, DocStorage } from './storage';
package/dist/index.js ADDED
@@ -0,0 +1,93 @@
1
+ // src/engine.ts
2
+ var CapabilityError = class extends Error {
3
+ constructor(engine, capability) {
4
+ super(
5
+ `The "${engine}" engine does not support "${capability}". Check engine.capabilities.${capability} before you use it.`
6
+ );
7
+ this.engine = engine;
8
+ this.capability = capability;
9
+ this.name = "CapabilityError";
10
+ }
11
+ engine;
12
+ capability;
13
+ };
14
+ function requireCapability(engine, capability) {
15
+ if (!engine.capabilities[capability]) throw new CapabilityError(engine.name, capability);
16
+ }
17
+ function syncStep1(handle) {
18
+ return { step: 1, stateVector: handle.encodeStateVector() };
19
+ }
20
+ function applySyncStep(handle, message, origin) {
21
+ if (message.step === 1) return { step: 2, update: handle.encodeUpdate(message.stateVector) };
22
+ handle.applyUpdate(message.update, origin);
23
+ return null;
24
+ }
25
+
26
+ // src/awareness.ts
27
+ var JsonAwareness = class {
28
+ constructor(clientId) {
29
+ this.clientId = clientId;
30
+ this.#states.set(clientId, {});
31
+ }
32
+ clientId;
33
+ #states = /* @__PURE__ */ new Map();
34
+ #listeners = /* @__PURE__ */ new Set();
35
+ getLocalState() {
36
+ return this.#states.get(this.clientId) ?? null;
37
+ }
38
+ setLocalState(state) {
39
+ this.#set(this.clientId, state, true);
40
+ }
41
+ setLocalStateField(field, value) {
42
+ const state = this.getLocalState();
43
+ if (state) this.setLocalState({ ...state, [field]: value });
44
+ }
45
+ getStates() {
46
+ return new Map(this.#states);
47
+ }
48
+ applyRemoteState(clientId, state) {
49
+ this.#set(clientId, state, false);
50
+ }
51
+ onChange(listener) {
52
+ this.#listeners.add(listener);
53
+ return () => this.#listeners.delete(listener);
54
+ }
55
+ #set(clientId, state, local) {
56
+ const old = this.#states.get(clientId);
57
+ const change = { added: [], updated: [], removed: [], local };
58
+ if (state === null) {
59
+ if (!old) return;
60
+ this.#states.delete(clientId);
61
+ change.removed.push(clientId);
62
+ } else {
63
+ if (local && old && JSON.stringify(old) === JSON.stringify(state)) return;
64
+ this.#states.set(clientId, state);
65
+ (old ? change.updated : change.added).push(clientId);
66
+ }
67
+ for (const listener of this.#listeners) listener(change);
68
+ }
69
+ };
70
+
71
+ // src/storage.ts
72
+ var MemoryDocStorage = class {
73
+ #updates = /* @__PURE__ */ new Map();
74
+ async append(room, doc, update) {
75
+ const id = JSON.stringify([room, doc]);
76
+ const entry = this.#updates.get(id) ?? { key: { room, doc }, updates: [] };
77
+ entry.updates.push(update.slice());
78
+ this.#updates.set(id, entry);
79
+ }
80
+ async load(room, doc) {
81
+ return (this.#updates.get(JSON.stringify([room, doc]))?.updates ?? []).map((u) => u.slice());
82
+ }
83
+ async clear(room, doc) {
84
+ this.#updates.delete(JSON.stringify([room, doc]));
85
+ }
86
+ async docs() {
87
+ return [...this.#updates.values()].map((entry) => ({ ...entry.key }));
88
+ }
89
+ };
90
+
91
+ export { CapabilityError, JsonAwareness, MemoryDocStorage, applySyncStep, requireCapability, syncStep1 };
92
+ //# sourceMappingURL=index.js.map
93
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/engine.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C3D,IAAA,OAAA,CAAQ,KAAK,QAAA,CAAS,GAAA,CAAI,KAAK,SAAA,CAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAA,EAAG,WAAW,EAAC,EAAG,IAAI,CAAA,CAAA,KAAK,CAAA,CAAE,OAAO,CAAA;AAAA,EAC3F;AAAA,EAEA,MAAM,KAAA,CAAM,IAAA,EAAc,GAAA,EAA4B;AACpD,IAAA,IAAA,CAAK,QAAA,CAAS,OAAO,IAAA,CAAK,SAAA,CAAU,CAAC,IAAA,EAAM,GAAG,CAAC,CAAC,CAAA;AAAA,EAClD;AAAA,EAEA,MAAM,IAAA,GAA0B;AAC9B,IAAA,OAAO,CAAC,GAAG,IAAA,CAAK,QAAA,CAAS,MAAA,EAAQ,CAAA,CAAE,GAAA,CAAI,CAAA,KAAA,MAAU,EAAE,GAAG,KAAA,CAAM,KAAI,CAAE,CAAA;AAAA,EACpE;AACF","file":"index.js","sourcesContent":["// The DocEngine interface (ADR 0002, ADR 0013). It hides the CRDT engine: Yjs (the reference\n// engine), Loro and Automerge. Each engine package implements it.\n\n/** A JSON value. Awareness states and shared map values are JSON. */\nexport type JsonValue =\n null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }\n\n/** A JSON object. */\nexport type JsonObject = { [key: string]: JsonValue }\n\n/**\n * The features of an engine. An engine gives a feature only when its ProseMirror binding has it\n * (the capability matrix of the plan). Code checks a feature here before it uses it.\n */\nexport interface EngineCapabilities {\n /** A Tiptap binding: the content of an editor is in the document. */\n tiptap: boolean\n /** Remote carets and selections, from awareness. */\n cursors: boolean\n /** Undo and redo of the changes of one origin only (`DocHandle.undoScope`). */\n undo: boolean\n /** Versions: create, list, open and restore (`DocHandle.versions`). */\n history: boolean\n /** Positions that follow edits (`DocHandle.relativePosition`), for comment anchors. */\n commentAnchors: boolean\n}\n\n/** The name of one feature of `EngineCapabilities`. */\nexport type Capability = keyof EngineCapabilities\n\n/** The error for a feature that the engine does not have. */\nexport class CapabilityError extends Error {\n constructor(\n readonly engine: string,\n readonly capability: Capability,\n ) {\n super(\n `The \"${engine}\" engine does not support \"${capability}\". ` +\n `Check engine.capabilities.${capability} before you use it.`,\n )\n this.name = 'CapabilityError'\n }\n}\n\n/** Throws a `CapabilityError` when `engine` does not have `capability`. */\nexport function requireCapability(engine: DocEngine, capability: Capability): void {\n if (!engine.capabilities[capability]) throw new CapabilityError(engine.name, capability)\n}\n\n/** A CRDT engine: it makes documents. */\nexport interface DocEngine {\n /** The name of the engine, as `yjs`, `loro` or `automerge`. */\n readonly name: string\n readonly capabilities: EngineCapabilities\n /** A new, empty document. */\n create(): DocHandle\n /** A document from the bytes of `DocHandle.snapshot()` or `DocHandle.encodeUpdate()`. */\n load(snapshot: Uint8Array): DocHandle\n}\n\n/** One CRDT document. Updates, state vectors and snapshots are the bytes of the engine. */\nexport interface DocHandle {\n /** The engine that made this document. */\n readonly engine: DocEngine\n /** Merges an update from a peer or from storage. `origin` comes back in `onUpdate`. */\n applyUpdate(update: Uint8Array, origin?: unknown): void\n /** What this document has, for the first step of the sync (`doc-sync` step 1). */\n encodeStateVector(): Uint8Array\n /** The changes that a peer with `stateVector` does not have. All changes without it. */\n encodeUpdate(stateVector?: Uint8Array): Uint8Array\n /** The full state, for `DocEngine.load`. */\n snapshot(): Uint8Array\n /** Calls `listener` for each change, local or merged. Returns a function that stops it. */\n onUpdate(listener: (update: Uint8Array, origin: unknown) => void): () => void\n /**\n * A map of JSON values in the document, so it syncs with the content. Names that start\n * with `dovetail:` are for Dovetail (comment threads and versions).\n */\n map(name: string): SharedMap\n /** The awareness of the document: the state of each client (user, cursor, typing). */\n readonly awareness: DocAwareness\n /** The versions of the document. Absent without `history`. */\n readonly versions?: DocVersions\n /** An undo scope for the changes of one origin (per-user undo). Absent without `undo`. */\n undoScope?(origin: unknown): UndoScope\n /**\n * A position in the root type `field` that stays on the same content while peers edit.\n * Absent without `commentAnchors`.\n */\n relativePosition?(field: string, index: number): Uint8Array\n /** The index of a relative position now, or null when its parent is gone. */\n absolutePosition?(position: Uint8Array): number | null\n /** Stops the document and its awareness. */\n destroy(): void\n}\n\n/** A map of JSON values in a document. Each key merges on its own (the last write wins). */\nexport interface SharedMap {\n get(key: string): JsonValue | undefined\n set(key: string, value: JsonValue, origin?: unknown): void\n delete(key: string, origin?: unknown): void\n entries(): [string, JsonValue][]\n /** Calls `listener` with the changed keys, for local and merged changes. */\n onChange(listener: (keys: string[], origin: unknown) => void): () => void\n}\n\n/** The change of an awareness: the client ids that came, changed and went. */\nexport interface AwarenessChange {\n added: string[]\n updated: string[]\n removed: string[]\n /** True when the local state changed. Send `getLocalState()` in an `awareness` message. */\n local: boolean\n}\n\n/**\n * The state of each client of a document: the user, the status, the cursor and typing. It\n * matches the `awareness` message of the protocol: a JSON state for each `clientId`.\n */\nexport interface DocAwareness {\n /** The id of this client in `getStates()`. */\n readonly clientId: string\n getLocalState(): JsonObject | null\n /** Sets the local state. null removes this client. */\n setLocalState(state: JsonObject | null): void\n setLocalStateField(field: string, value: JsonValue): void\n /** The state of each client, this client included. */\n getStates(): Map<string, JsonObject>\n /** Applies the state of a remote client from an `awareness` message. null removes it. */\n applyRemoteState(clientId: string, state: JsonObject | null): void\n /** Calls `listener` for each change. Returns a function that stops it. */\n onChange(listener: (change: AwarenessChange) => void): () => void\n}\n\n/** A named version of a document. */\nexport interface Version {\n id: string\n name: string\n /** An ISO 8601 date-time. */\n createdAt: string\n /** The id of the user that made the version, or null. */\n by: string | null\n}\n\n/** The versions of a document. They are in the document, so they sync. */\nexport interface DocVersions {\n /** The versions, the oldest first. */\n list(): Version[]\n /** Keeps the content now as a new version. */\n create(options?: { name?: string; by?: string | null }): Version\n /** A new document with the content of a version, for a preview. Destroy it after use. */\n open(id: string): DocHandle\n /**\n * Makes the content equal to the version, as a new change with `origin`. The comment\n * threads and the versions stay.\n */\n restore(id: string, origin?: unknown): void\n /** Calls `listener` when a version is added, here or by a peer. */\n onChange(listener: () => void): () => void\n}\n\n/** The undo and redo of one origin. */\nexport interface UndoScope {\n undo(): boolean\n redo(): boolean\n readonly canUndo: boolean\n readonly canRedo: boolean\n destroy(): void\n}\n\n/** A `doc-sync` step of the protocol, with bytes. The transport encodes them as base64. */\nexport type DocSyncStep = { step: 1; stateVector: Uint8Array } | { step: 2; update: Uint8Array }\n\n/** Step 1: what this document has. Send it when the client joins the room. */\nexport function syncStep1(handle: DocHandle): DocSyncStep {\n return { step: 1, stateVector: handle.encodeStateVector() }\n}\n\n/**\n * Applies a `doc-sync` step from a peer. Step 1 gives the step 2 answer to send back. Step 2\n * merges the update with `origin` and gives nothing to send.\n */\nexport function applySyncStep(\n handle: DocHandle,\n message: DocSyncStep,\n origin?: unknown,\n): DocSyncStep | null {\n if (message.step === 1) return { step: 2, update: handle.encodeUpdate(message.stateVector) }\n handle.applyUpdate(message.update, origin)\n return null\n}\n","// The awareness of the protocol on plain JSON. The Loro and Automerge engines and the\n// presence rooms of core use it.\nimport type { AwarenessChange, DocAwareness, JsonObject, JsonValue } from './engine'\n\n/** The awareness of the protocol: a JSON state for each client id. */\nexport class JsonAwareness implements DocAwareness {\n #states = new Map<string, JsonObject>()\n #listeners = new Set<(change: AwarenessChange) => void>()\n\n constructor(readonly clientId: string) {\n this.#states.set(clientId, {})\n }\n\n getLocalState(): JsonObject | null {\n return this.#states.get(this.clientId) ?? null\n }\n\n setLocalState(state: JsonObject | null): void {\n this.#set(this.clientId, state, true)\n }\n\n setLocalStateField(field: string, value: JsonValue): void {\n const state = this.getLocalState()\n if (state) this.setLocalState({ ...state, [field]: value })\n }\n\n getStates(): Map<string, JsonObject> {\n return new Map(this.#states)\n }\n\n applyRemoteState(clientId: string, state: JsonObject | null): void {\n this.#set(clientId, state, false)\n }\n\n onChange(listener: (change: AwarenessChange) => void): () => void {\n this.#listeners.add(listener)\n return () => this.#listeners.delete(listener)\n }\n\n #set(clientId: string, state: JsonObject | null, local: boolean): void {\n const old = this.#states.get(clientId)\n const change: AwarenessChange = { added: [], updated: [], removed: [], local }\n if (state === null) {\n if (!old) return\n this.#states.delete(clientId)\n change.removed.push(clientId)\n } else {\n if (local && old && JSON.stringify(old) === JSON.stringify(state)) return\n this.#states.set(clientId, state)\n ;(old ? change.updated : change.added).push(clientId)\n }\n for (const listener of this.#listeners) listener(change)\n }\n}\n","// DocStorage: where the doc updates made offline wait until the client is online again\n// (plan M3). The offline queue (M2) implements it on the same IndexedDB database as the\n// write queue. The doc sync (M3) uses only this interface.\n\n/** A document in a room. */\nexport interface DocKey {\n room: string\n doc: string\n}\n\n/** The updates of each document that the server does not have yet. */\nexport interface DocStorage {\n /** Adds an update at the end of the updates of the document. */\n append(room: string, doc: string, update: Uint8Array): Promise<void>\n /** The updates of the document, in the order of `append`. */\n load(room: string, doc: string): Promise<Uint8Array[]>\n /**\n * Removes the updates of the document, when the server has them. A storage that tabs share\n * removes only the updates that it loaded or appended, so an update of another tab stays.\n */\n clear(room: string, doc: string): Promise<void>\n /** The documents that have updates. */\n docs(): Promise<DocKey[]>\n}\n\n/** A DocStorage in memory, for tests and for hosts with no IndexedDB. */\nexport class MemoryDocStorage implements DocStorage {\n #updates = new Map<string, { key: DocKey; updates: Uint8Array[] }>()\n\n async append(room: string, doc: string, update: Uint8Array): Promise<void> {\n const id = JSON.stringify([room, doc])\n const entry = this.#updates.get(id) ?? { key: { room, doc }, updates: [] }\n entry.updates.push(update.slice())\n this.#updates.set(id, entry)\n }\n\n async load(room: string, doc: string): Promise<Uint8Array[]> {\n return (this.#updates.get(JSON.stringify([room, doc]))?.updates ?? []).map(u => u.slice())\n }\n\n async clear(room: string, doc: string): Promise<void> {\n this.#updates.delete(JSON.stringify([room, doc]))\n }\n\n async docs(): Promise<DocKey[]> {\n return [...this.#updates.values()].map(entry => ({ ...entry.key }))\n }\n}\n"]}
@@ -0,0 +1,27 @@
1
+ /** A document in a room. */
2
+ export interface DocKey {
3
+ room: string;
4
+ doc: string;
5
+ }
6
+ /** The updates of each document that the server does not have yet. */
7
+ export interface DocStorage {
8
+ /** Adds an update at the end of the updates of the document. */
9
+ append(room: string, doc: string, update: Uint8Array): Promise<void>;
10
+ /** The updates of the document, in the order of `append`. */
11
+ load(room: string, doc: string): Promise<Uint8Array[]>;
12
+ /**
13
+ * Removes the updates of the document, when the server has them. A storage that tabs share
14
+ * removes only the updates that it loaded or appended, so an update of another tab stays.
15
+ */
16
+ clear(room: string, doc: string): Promise<void>;
17
+ /** The documents that have updates. */
18
+ docs(): Promise<DocKey[]>;
19
+ }
20
+ /** A DocStorage in memory, for tests and for hosts with no IndexedDB. */
21
+ export declare class MemoryDocStorage implements DocStorage {
22
+ #private;
23
+ append(room: string, doc: string, update: Uint8Array): Promise<void>;
24
+ load(room: string, doc: string): Promise<Uint8Array[]>;
25
+ clear(room: string, doc: string): Promise<void>;
26
+ docs(): Promise<DocKey[]>;
27
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@dovetail-ts/crdt",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "The DocEngine and DocStorage interfaces that every CRDT engine and doc store implements.",
5
+ "license": "MIT",
6
+ "author": "Joe Gaudet <joe@joegaudet.com>",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/joegaudet/dovetail.git",
10
+ "directory": "packages/crdt"
11
+ },
12
+ "homepage": "https://joegaudet.com/dovetail/",
13
+ "bugs": "https://github.com/joegaudet/dovetail/issues",
14
+ "keywords": [
15
+ "realtime",
16
+ "offline",
17
+ "sync",
18
+ "crdt"
19
+ ],
20
+ "type": "module",
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ },
27
+ "./package.json": "./package.json"
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "CHANGELOG.md",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "sideEffects": false,
36
+ "devDependencies": {
37
+ "tsup": "^8.5.1"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "engines": {
43
+ "node": ">=22.12.0"
44
+ },
45
+ "scripts": {
46
+ "build": "tsc --build --force && tsup"
47
+ }
6
48
  }