@kition/sync 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,31 @@
1
- # Temporary Holding Version
1
+ # @kition/sync
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 client for the open sync protocol `kition-sync/1`: JSON-RPC 2.0 over WebSocket, reconnect
4
+ with backoff, an offline push queue, and `startRelay`, which relays a `@kition/kdm` replica to and
5
+ from its room. An ES module with type declarations, for Node and for bundlers.
6
+ Most pages do not need it directly: `@kition/embed` co-edits through it.
7
+
8
+ ```sh
9
+ npm i @kition/sync
10
+ ```
11
+
12
+ ```ts
13
+ import { SyncClient, type SyncTransport } from '@kition/sync'
14
+
15
+ const sync = new SyncClient({
16
+ createTransport: (url) => {
17
+ const socket = new WebSocket(url)
18
+ socket.binaryType = 'arraybuffer'
19
+ return socket as unknown as SyncTransport
20
+ },
21
+ })
22
+ // The token comes from your server, which asks Kition Console for it.
23
+ await sync.connect('wss://sync.kition.ai/v1/t/acme', async () => (await (await fetch('/api/sync-token', { method: 'POST' })).json()).token)
24
+ await sync.join(docId)
25
+ sync.onChanges(docId, ({ changes }) => replica.importChanges(changes)) // a @kition/kdm Replica
26
+ await sync.push(docId, replica.exportChanges(sentVersion))
27
+ ```
28
+
29
+ Documentation: https://dev.kition.ai/docs
30
+
31
+ License: Apache-2.0
package/dist/LICENSE ADDED
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Reconnect backoff: 1 s for the first attempt, doubling per further attempt, capped at 30 s,
3
+ * with equal jitter (half fixed, half random) so many clients reconnecting at once do not all
4
+ * retry on the same tick.
5
+ */
6
+ export declare const BACKOFF_BASE_MS = 1000;
7
+ export declare const BACKOFF_CAP_MS = 30000;
8
+ /** `attempt` is 0 for the first reconnect try after a disconnect. `random` returns `[0, 1)`. */
9
+ export declare function backoffDelay(attempt: number, random?: () => number): number;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The blobs a kit's replica exports alongside its changes (Kit UI protocol `replica/export`), and
3
+ * how a receiving side finds the blobs a pushed change needs.
4
+ *
5
+ * A blob section is `(64-hex SHA-256 as ASCII, u64 little-endian length, bytes)*`.
6
+ *
7
+ * The sync server relays KDM change bytes only, never a blob list, so the side that imports a
8
+ * change finds its blobs in the change itself: a replica references a blob by its hash, which a
9
+ * KDM change export (Loro updates) carries as plain text. Every 64-hex run in the bytes is a
10
+ * candidate; the server answers which of them it holds (`blob/has`), and those are fetched. A
11
+ * candidate the server does not hold is not a blob (or a blob no one uploaded), and is skipped.
12
+ */
13
+ export type BlobEntry = {
14
+ hash: string;
15
+ data: Uint8Array;
16
+ };
17
+ export declare function decodeBlobSection(bytes: Uint8Array): BlobEntry[];
18
+ export declare function encodeBlobSection(entries: readonly BlobEntry[]): Uint8Array;
19
+ /**
20
+ * Every lowercase 64-hex string in `bytes` that could be a blob hash: each 64-character window of
21
+ * every run of hex characters, since a hash may sit next to other hex text.
22
+ */
23
+ export declare function blobHashCandidates(bytes: Uint8Array): string[];
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Capability sets in `sync/hello` (Kition platform `docs/platform/index.md` section 3, rule CS2): next to its protocol
3
+ * capabilities (`leases`, `headless`), a server lists the versioned capability sets it serves for
4
+ * the principal, such as `"KitModel 1.0"` and `"KitCollab 1.1"`. A set is `Name major.minor`; a
5
+ * minor version only adds members, so `Name a.b` serves a request for `Name a.c` when `c` is at
6
+ * most `b`. Scripts test for a set, never for a server product or its version.
7
+ */
8
+ /** `Name major.minor` as its parts; `null` for anything else (a protocol capability). */
9
+ export declare function parseCapabilitySet(set: string): {
10
+ name: string;
11
+ major: number;
12
+ minor: number;
13
+ } | null;
14
+ /** The capability sets among `capabilities` (what `sync/hello` lists), in their order. */
15
+ export declare function capabilitySetsOf(capabilities: readonly string[]): string[];
16
+ /**
17
+ * Whether `sets` serve `required` (such as `'KitCollab 1.0'`): a set of the same name and major
18
+ * version with at least its minor version. A malformed name is never served.
19
+ */
20
+ export declare function servesCapabilitySet(required: string, sets: readonly string[]): boolean;
@@ -0,0 +1,253 @@
1
+ import { SyncLeases } from './leases.js';
2
+ import { type AccountSettings, type AgentRunResult, type BlobGetResult, type BlobHasResult, type ChangesPushResult, type ClientInfo, type ExportGetResult, type HelloResult, type HistoryGetResult, type HistoryListResult, type HistoryRestoreResult, type Presence, type PreviewGetResult, type PrivateRoomCreateResult, type Role, type RoomCreateResult, type RoomListing, type RoomsListResult, type RoomJoinResult, type RoomLinkResult, type RoomMembersResult, type RoomOpenResult, type OpenScope, type RoomResolveResult, type SaveBeginResult, type SnapshotGetResult, type SnapshotPreference } from './protocol.js';
3
+ import type { ConnectionState, TransportFactory } from './transport.js';
4
+ import type { SaveFailure, SaveState, SaveTrigger } from './saveMachine.js';
5
+ export type { ConnectionState } from './transport.js';
6
+ /**
7
+ * How a client with no replica of a document starts (protocol 1.8): `shallow: true` asks for a
8
+ * shallow snapshot of the room's latest state (standard 2.0 rule M16a), `prefer: 'shallow'` lets
9
+ * the server choose one for a large document. A server before 1.8 answers a full snapshot.
10
+ */
11
+ export type SnapshotStart = {
12
+ shallow?: boolean;
13
+ prefer?: SnapshotPreference;
14
+ };
15
+ export type SyncClientOptions = {
16
+ createTransport: TransportFactory;
17
+ client?: ClientInfo;
18
+ capabilities?: string[];
19
+ /**
20
+ * The start `snapshot` and a `join` with `since: null` ask for unless they are given their own
21
+ * (protocol 1.8; omitted: full snapshots). History reads go to the server either way
22
+ * (`history`, `historyAt`), so a shallow replica never needs its own.
23
+ */
24
+ start?: SnapshotStart;
25
+ random?: () => number;
26
+ setTimeout?: (run: () => void, ms: number) => unknown;
27
+ clearTimeout?: (handle: unknown) => void;
28
+ };
29
+ type ChangeNotice = {
30
+ changes: Uint8Array;
31
+ seq?: number;
32
+ from?: string;
33
+ };
34
+ /** A token, or what answers one: asked again on every connection attempt, so it can refresh. */
35
+ export type SyncToken = string | (() => string | Promise<string>);
36
+ export declare class SyncClient {
37
+ private readonly options;
38
+ private url;
39
+ private token;
40
+ private transport;
41
+ private decoder;
42
+ private nextId;
43
+ private pending;
44
+ private pushQueue;
45
+ private joined;
46
+ /** The highest server `seq` seen for each joined doc (join, pull, or push ack), for re-joining
47
+ * after a reconnect without a KDM version of its own. */
48
+ private lastSeq;
49
+ private changesListeners;
50
+ private presenceListeners;
51
+ private accessListeners;
52
+ /** This person's role in each joined room, as its last join or `room/access` said. */
53
+ private roles;
54
+ private stateListeners;
55
+ private roomsListeners;
56
+ private accountListeners;
57
+ private resolvedListeners;
58
+ private saveListeners;
59
+ private reconnectAttempt;
60
+ private reconnectTimer;
61
+ private closed;
62
+ private readyForPushes;
63
+ private connectionState;
64
+ private hello;
65
+ constructor(options: SyncClientOptions);
66
+ get state(): ConnectionState;
67
+ /** The handshake result from the most recent successful `sync/hello`. */
68
+ get principal(): import("./protocol.js").Principal | undefined;
69
+ /**
70
+ * The scope of an open-token connection (protocol 1.10, RM1), from the most recent handshake:
71
+ * its one file generation and role; `undefined` for any other connection or before the first.
72
+ */
73
+ get open(): OpenScope | undefined;
74
+ /**
75
+ * The room of this open-token connection's file generation (protocol 1.10, `room/resolve`);
76
+ * `claim: true` asks for the seed claim when it has none (an editor only, RM5).
77
+ */
78
+ resolveRoom(claim?: boolean): Promise<RoomResolveResult>;
79
+ /**
80
+ * Starts a save of `docId`'s room (protocol 1.10, `save/begin`, D3): answers the change to write
81
+ * and its authors, with the room in `force-save` by this session; `conflict` while another runs.
82
+ */
83
+ saveBegin(docId: string, trigger: SaveTrigger): Promise<SaveBeginResult>;
84
+ /** Ends this session's save of `seq` (protocol 1.10, `save/end`): the `version` it wrote, or why it failed. */
85
+ saveEnd(docId: string, seq: number, outcome: {
86
+ version: string;
87
+ } | {
88
+ error: SaveFailure;
89
+ }): Promise<void>;
90
+ /** Hears `docId`'s room save state change (protocol 1.10, `save/changed`). */
91
+ onSave(docId: string, listener: (save: SaveState) => void): () => void;
92
+ /** Hears the connection's file generation get its room (protocol 1.10, `room/resolved`). */
93
+ onRoomResolved(listener: (docId: string) => void): () => void;
94
+ /**
95
+ * Everything the server listed in its most recent `sync/hello`: protocol capabilities (`leases`,
96
+ * `headless`, a server's own names) and capability sets; empty before the first handshake. A
97
+ * reconnect may change it (a principal's plan): read it again when the state turns `online`.
98
+ */
99
+ get capabilities(): readonly string[];
100
+ /**
101
+ * The Kition kit platform's capability sets the server serves this principal (rule CS2), such as
102
+ * `KitModel 1.0` and `KitCollab 1.1`: the `Name major.minor` entries of `capabilities`.
103
+ */
104
+ get capabilitySets(): readonly string[];
105
+ /** Whether the server serves the capability set `set` (such as `'KitCollab 1.1'`); false before the first handshake. */
106
+ supports(set: string): boolean;
107
+ onState(listener: (state: ConnectionState) => void): () => void;
108
+ /**
109
+ * Connects and performs `sync/hello`; resolves once the handshake succeeds. A `token` function
110
+ * is called for every connection attempt (reconnects too), so a short-lived token is fresh.
111
+ */
112
+ connect(url: string, token: SyncToken): Promise<HelloResult>;
113
+ close(): void;
114
+ /**
115
+ * Joins `docId`'s room, or re-joins it after a reconnect. `since` is the server seq the caller
116
+ * already has every change up to (omitted: the highest `seq` this client has itself seen for
117
+ * `docId`, or `null` with none yet, which asks for everything from the room's snapshot).
118
+ *
119
+ * A busy room's catch-up does not fit in one `room/join` reply, so the server pages it (`more`,
120
+ * Kition platform `docs/platform/reference/sync-protocol.md` section 3); this repeats `room/join` with `since` set to each page's
121
+ * `seq` until `more` is `false`, combining every page's `changes` into the one result this
122
+ * resolves with. `presence` and `role` are from the last page.
123
+ *
124
+ * A join with `since: null` (a client with no replica yet) may start from a shallow snapshot
125
+ * (protocol 1.8): `start` (else the client's `start` option) asks for one. The result then says
126
+ * `snapshot` and `shallow`, and `changes[0]` is the shallow snapshot to load as a new replica.
127
+ */
128
+ join(docId: string, since?: number | null, start?: SnapshotStart): Promise<RoomJoinResult>;
129
+ leave(docId: string): void;
130
+ push(docId: string, changes: Uint8Array): Promise<ChangesPushResult>;
131
+ onChanges(docId: string, listener: (notice: ChangeNotice) => void): () => void;
132
+ setPresence(docId: string, state: unknown): void;
133
+ onPresence(docId: string, listener: (peers: Presence[]) => void): () => void;
134
+ /** Blobs, scoped to the document whose room uses them (protocol 1.5). */
135
+ /**
136
+ * Leases for coordinated objects (protocol 1.5, `lease/*`): `acquire`, `release`, `hold` (kept
137
+ * renewed), the rooms' lease lists (`list`, `onChanged`), and `mine`. `available` is false while
138
+ * offline or against a server that does not list the `leases` capability.
139
+ */
140
+ readonly leases: SyncLeases;
141
+ readonly blobs: {
142
+ has: (docId: string, hashes: string[]) => Promise<BlobHasResult>;
143
+ put: (docId: string, data: Uint8Array, mime: string) => Promise<{
144
+ hash: string;
145
+ }>;
146
+ get: (docId: string, hash: string) => Promise<BlobGetResult>;
147
+ };
148
+ /**
149
+ * The room's snapshot, for a client with no replica yet, and the `seq` it reflects; `join` with
150
+ * that `seq` next. `start` (else the client's `start` option) may ask for a shallow one
151
+ * (protocol 1.8), which the result then says (`shallow`).
152
+ */
153
+ snapshot(docId: string, start?: SnapshotStart): Promise<SnapshotGetResult>;
154
+ createRoom(docId: string, snapshot: Uint8Array, name: string, kit: string): Promise<RoomCreateResult>;
155
+ /**
156
+ * Makes a private room (protocol 1.9, `room/create` with `private: true`): it syncs the document
157
+ * to this person's own devices, with no share link until they mint one (`createLink`), which
158
+ * shares it. A server before 1.9 makes an ordinary room and answers its link.
159
+ */
160
+ createPrivateRoom(docId: string, snapshot: Uint8Array, name: string, kit: string): Promise<PrivateRoomCreateResult | RoomCreateResult>;
161
+ /**
162
+ * One page of the rooms this person is a member of, most recently changed first (protocol 1.9,
163
+ * `rooms/list`); pass the answered `cursor` for the next page (`null`: none).
164
+ */
165
+ listRooms(options?: {
166
+ cursor?: string;
167
+ limit?: number;
168
+ }): Promise<RoomsListResult>;
169
+ /** Every room this person is a member of, all pages of `listRooms`, keyed by `docId`. */
170
+ listAllRooms(): Promise<RoomListing[]>;
171
+ /**
172
+ * Hears this person's document list change (protocol 1.9, `rooms/changed`): `room` is the entry
173
+ * now, or `null` when they are no longer a member.
174
+ */
175
+ onRoomsChanged(listener: (docId: string, room: RoomListing | null) => void): () => void;
176
+ /** This person's account settings on the server (protocol 1.9, `account/settings`). */
177
+ accountSettings(): Promise<AccountSettings>;
178
+ /** Changes this person's account settings (protocol 1.9, `account/update`); answers them all. */
179
+ updateAccountSettings(patch: Partial<AccountSettings>): Promise<AccountSettings>;
180
+ /** Hears this person's account settings change on any of their devices (protocol 1.9, `account/changed`). */
181
+ onAccountChanged(listener: (settings: AccountSettings) => void): () => void;
182
+ /** Resolves `shareLink` to the room it points to; `join(result.docId, ...)` actually joins it. */
183
+ openRoom(shareLink: string): Promise<RoomOpenResult>;
184
+ /** Mints another share link to `docId`'s room granting `role` (protocol 1.4, `room/link`; `commenter` since 1.6). */
185
+ createLink(docId: string, role: Exclude<Role, 'owner'>): Promise<RoomLinkResult>;
186
+ /** The room's members and working share links (protocol 1.6, `room/members`; owner or editor). */
187
+ members(docId: string): Promise<RoomMembersResult>;
188
+ /** Changes another member's role (protocol 1.6, `room/setRole`; owner only). */
189
+ setRole(docId: string, principalId: string, role: Exclude<Role, 'owner'>): Promise<void>;
190
+ /** Removes another member from the room (protocol 1.6, `room/removeMember`; owner only). */
191
+ removeMember(docId: string, principalId: string): Promise<void>;
192
+ /** Revokes one of the room's share links (protocol 1.6, `room/revokeLink`; owner only). */
193
+ revokeLink(docId: string, shareLink: string): Promise<void>;
194
+ /**
195
+ * Hears this person's role in `docId`'s room change (protocol 1.6, `room/access`): the owner set
196
+ * a new one, or removed them (`null`; the room is then no longer joined, and not re-joined on a
197
+ * reconnect).
198
+ */
199
+ onAccess(docId: string, listener: (role: Role | null) => void): () => void;
200
+ /** The room's history checkpoints, newest first (protocol 1.5, `history/list`). */
201
+ history(docId: string, options?: {
202
+ before?: number;
203
+ limit?: number;
204
+ }): Promise<HistoryListResult>;
205
+ /** The document as of `seq` (protocol 1.5, `history/get`). */
206
+ historyAt(docId: string, seq: number): Promise<HistoryGetResult>;
207
+ /**
208
+ * Restores the joined room's document as of `seq` as one new change (protocol 1.5,
209
+ * `history/restore`); the change arrives as `changes/pull` like anyone else's.
210
+ */
211
+ restore(docId: string, seq: number): Promise<HistoryRestoreResult>;
212
+ /**
213
+ * A picture of `docId`'s room as of its latest change, rendered by the kit on a server that runs
214
+ * kits headless (protocol 1.7, `preview/get`; the server lists `headless`).
215
+ */
216
+ preview(docId: string, options?: {
217
+ page?: number;
218
+ size?: number;
219
+ }): Promise<PreviewGetResult>;
220
+ /** `docId`'s room as a file in `format`, saved by the kit on the server (protocol 1.7, `export/get`). */
221
+ exportFile(docId: string, format?: string): Promise<ExportGetResult>;
222
+ /**
223
+ * Runs an object-model batch on the joined room's document in the server's headless kit, as an
224
+ * agent acting for this person (protocol 1.7, `agent/run`); the change arrives as `changes/pull`.
225
+ */
226
+ runAgent(docId: string, batch: unknown, prompt?: string): Promise<AgentRunResult>;
227
+ private openConnection;
228
+ private sendHello;
229
+ /** Re-joins every room this client had joined, each with the highest `seq` it last saw for it
230
+ * (never re-fetching history it already has), and delivers whatever catch-up changes come back.
231
+ * A role that changed while the connection was down (a host's new open token, an owner's change
232
+ * whose `room/access` notice could not arrive) is reported to `onAccess` listeners. */
233
+ private rejoinAll;
234
+ /** Sends every queued push, in order, waiting for each one to settle (or be requeued by a
235
+ * disconnect) before sending the next. */
236
+ private flushQueue;
237
+ private handleDisconnect;
238
+ private scheduleReconnect;
239
+ private clearReconnectTimer;
240
+ private setState;
241
+ private failPending;
242
+ /** Sends one push and resolves once it settles (success, failure, or being requeued by a
243
+ * disconnect) -- never the push's own promise, which stays pending across a requeue. */
244
+ private sendPush;
245
+ private request;
246
+ private sendNotification;
247
+ private handleFrame;
248
+ private handleNotification;
249
+ private emitChanges;
250
+ /** Keeps the highest server `seq` seen for `docId`, across joins, pulls, and push acks. */
251
+ private bumpSeq;
252
+ private subscribe;
253
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The wire framing: a JSON text frame carries a message whose `bins` field says how many binary
3
+ * frames follow it, each a payload one of the message's `{"$bin": n}` markers points to. Mirrors
4
+ * `kition-sync-protocol`'s Rust `framing` module; this side builds and reads the markers rather
5
+ * than typed `Bin` fields, since params and results here already carry real `Uint8Array`s.
6
+ */
7
+ export type Frame = string | Uint8Array;
8
+ export type Bin = {
9
+ $bin: number;
10
+ };
11
+ export declare function isBin(value: unknown): value is Bin;
12
+ /** Registers binary payloads as a message is built, handing out the `Bin` marker for each. */
13
+ export declare class Outgoing {
14
+ private readonly bins;
15
+ bin(data: Uint8Array): Bin;
16
+ /** The text frame first, then each registered payload as a binary frame, in order. */
17
+ finish(message: Record<string, unknown>): Frame[];
18
+ }
19
+ /** Reassembles an incoming stream of frames into complete messages; feed one frame at a time. */
20
+ export declare class Decoder {
21
+ private pendingMessage;
22
+ private remaining;
23
+ private collected;
24
+ /** Returns the completed message once every binary frame it declared has arrived. Throws on
25
+ * a frame out of sequence (never corrupts state the caller could keep feeding). */
26
+ feed(frame: Frame): {
27
+ message: Record<string, unknown>;
28
+ bins: Uint8Array[];
29
+ } | undefined;
30
+ private feedText;
31
+ private feedBinary;
32
+ }
33
+ /** Resolves one `Bin` marker against a decoded message's binary frames. */
34
+ export declare function readBin(value: unknown, bins: Uint8Array[]): Uint8Array;
35
+ export declare function readBins(values: unknown, bins: Uint8Array[]): Uint8Array[];
package/dist/hash.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** The hash blobs are addressed by: lowercase hex SHA-256, over Web Crypto (browser and Node 20+). */
2
+ export declare function sha256Hex(data: Uint8Array): Promise<string>;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * `@kition/sync`: the client for the open sync protocol `kition-sync/1` (Kition platform docs/platform/reference/sync-protocol.md).
3
+ * `SyncClient` connects over an injectable `SyncTransport`, reconnects with backoff, re-joins
4
+ * every joined room with the caller's latest local version, and queues pushes made while
5
+ * offline, flushing them in order once reconnected. `startRelay` relays one document's KDM replica
6
+ * to and from its room through it. `LORO_REPLICA_VERSIONS`, the version handling the relay needs,
7
+ * is in `@kition/sync/replicaVersions`, loaded on demand, since it loads the CRDT engine.
8
+ */
9
+ export { capabilitySetsOf, parseCapabilitySet, servesCapabilitySet } from './capabilities.js';
10
+ export { blobHashCandidates, decodeBlobSection, encodeBlobSection, type BlobEntry } from './blobSection.js';
11
+ export { SyncClient, type SnapshotStart, type SyncClientOptions, type SyncToken } from './client.js';
12
+ export type { Bin, Frame } from './framing.js';
13
+ export { HEADLESS_CAPABILITY, OPEN_ROOMS_CAPABILITY, type OpenScope, type RoomResolveResult, type RoomResolvedParams, type SaveAuthor, type SaveBeginResult, type SaveChangedParams, SYNC_PROTOCOL, SyncRpcError, type AgentRunResult, type BlobGetResult, type BlobHasResult, type ChangesPullParams, type Checkpoint, type ChangesPushResult, type ClientInfo, type ErrorCode, type ExportGetResult, type HelloParams, type HelloResult, type HistoryGetResult, type HistoryListResult, type HistoryRestoreResult, type Lease, type Member, ROLE_RANK, type RoomAccessParams, type RoomMembersResult, type ShareLink, type LeaseChangedParams, type Presence, type PresenceUpdateParams, type PreviewGetResult, type Principal, type Role, type AccountSettings, type PrivateRoomCreateResult, type RoomCreateResult, type RoomListing, type RoomsChangedParams, type RoomsListResult, type RoomJoinResult, type RoomLinkResult, type RoomOpenResult, type ServerInfo, type SnapshotGetResult, type SnapshotPreference, } from './protocol.js';
14
+ export { DocumentLeases, SyncLeases, leaseHolder, scopesCollide, type LeaseHold } from './leases.js';
15
+ export { initialSaveState, mustSave, saveTransition, type SaveEvent, type SaveFailure, type SaveOutcome, type SaveState, type SaveStatus, type SaveTrigger } from './saveMachine.js';
16
+ export { classifySaveError, runSave, type SaveRun, type SaveRunOptions } from './saveRun.js';
17
+ export { startRelay, type Relay, type RelayOptions, type RelayReplica, type RelaySync } from './relay.js';
18
+ export type { ReplicaVersions } from './replicaVersions.js';
19
+ export type { ConnectionState, SyncTransport, TransportFactory } from './transport.js';