@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/dist/index.js ADDED
@@ -0,0 +1,995 @@
1
+ function P(n) {
2
+ const e = /^([A-Z][A-Za-z0-9]*) (\d+)\.(\d+)$/.exec(n.trim());
3
+ return e ? { name: e[1], major: Number(e[2]), minor: Number(e[3]) } : null;
4
+ }
5
+ function U(n) {
6
+ return n.filter((e) => typeof e == "string" && P(e) !== null);
7
+ }
8
+ function Q(n, e) {
9
+ const t = P(n);
10
+ return t ? e.some((s) => {
11
+ const i = typeof s == "string" ? P(s) : null;
12
+ return i !== null && i.name === t.name && i.major === t.major && i.minor >= t.minor;
13
+ }) : !1;
14
+ }
15
+ const S = 64, T = S + 8;
16
+ function K(n) {
17
+ const e = [], t = new DataView(n.buffer, n.byteOffset, n.byteLength), s = new TextDecoder();
18
+ let i = 0;
19
+ for (; i < n.length; ) {
20
+ if (i + T > n.length) throw new Error("a blob section ends inside a blob header");
21
+ const r = s.decode(n.subarray(i, i + S)), o = Number(t.getBigUint64(i + S, !0)), l = i + T;
22
+ if (l + o > n.length) throw new Error("a blob section ends inside a blob");
23
+ e.push({ hash: r, data: n.slice(l, l + o) }), i = l + o;
24
+ }
25
+ return e;
26
+ }
27
+ function V(n) {
28
+ const e = new Uint8Array(n.reduce((r, o) => r + T + o.data.length, 0)), t = new DataView(e.buffer), s = new TextEncoder();
29
+ let i = 0;
30
+ for (const r of n)
31
+ e.set(s.encode(r.hash), i), t.setBigUint64(i + S, BigInt(r.data.length), !0), e.set(r.data, i + T), i += T + r.data.length;
32
+ return e;
33
+ }
34
+ const G = 1024;
35
+ function J(n) {
36
+ return n >= 48 && n <= 57 || n >= 97 && n <= 102;
37
+ }
38
+ function Y(n) {
39
+ const e = /* @__PURE__ */ new Set(), t = new TextDecoder();
40
+ let s = -1;
41
+ for (let i = 0; i <= n.length; i += 1) {
42
+ if (i < n.length && J(n[i])) {
43
+ s < 0 && (s = i);
44
+ continue;
45
+ }
46
+ if (s >= 0) {
47
+ const r = i - s;
48
+ if (r >= S && r <= G)
49
+ for (let o = s; o + S <= i; o += 1) e.add(t.decode(n.subarray(o, o + S)));
50
+ s = -1;
51
+ }
52
+ }
53
+ return [...e];
54
+ }
55
+ const W = 1e3, Z = 3e4;
56
+ function z(n, e = Math.random) {
57
+ const s = Math.min(W * 2 ** Math.max(n, 0), Z) / 2;
58
+ return s + e() * s;
59
+ }
60
+ function X(n) {
61
+ return typeof n == "object" && n !== null && typeof n.$bin == "number";
62
+ }
63
+ class R {
64
+ bins = [];
65
+ bin(e) {
66
+ const t = this.bins.length;
67
+ return this.bins.push(e), { $bin: t };
68
+ }
69
+ /** The text frame first, then each registered payload as a binary frame, in order. */
70
+ finish(e) {
71
+ const t = this.bins.length > 0 ? { ...e, bins: this.bins.length } : e;
72
+ return [JSON.stringify(t), ...this.bins];
73
+ }
74
+ }
75
+ class I {
76
+ pendingMessage;
77
+ remaining = 0;
78
+ collected = [];
79
+ /** Returns the completed message once every binary frame it declared has arrived. Throws on
80
+ * a frame out of sequence (never corrupts state the caller could keep feeding). */
81
+ feed(e) {
82
+ return typeof e == "string" ? this.feedText(e) : this.feedBinary(e);
83
+ }
84
+ feedText(e) {
85
+ if (this.remaining > 0) throw new Error("a text frame arrived before the previous message received all its binary frames");
86
+ const t = JSON.parse(e), s = typeof t.bins == "number" && t.bins >= 0 ? t.bins : 0;
87
+ if (s === 0) return { message: t, bins: [] };
88
+ this.pendingMessage = t, this.remaining = s, this.collected = [];
89
+ }
90
+ feedBinary(e) {
91
+ if (this.remaining === 0) throw new Error("a binary frame arrived with no message awaiting one");
92
+ if (this.collected.push(e), this.remaining -= 1, this.remaining > 0) return;
93
+ const t = this.pendingMessage, s = this.collected;
94
+ return this.pendingMessage = void 0, this.collected = [], { message: t, bins: s };
95
+ }
96
+ }
97
+ function v(n, e) {
98
+ if (!X(n)) throw new Error('expected a {"$bin": n} marker');
99
+ const t = e[n.$bin];
100
+ if (!t) throw new Error(`binary frame ${n.$bin} is missing`);
101
+ return t;
102
+ }
103
+ function ee(n, e) {
104
+ if (!Array.isArray(n)) throw new Error('expected an array of {"$bin": n} markers');
105
+ return n.map((t) => v(t, e));
106
+ }
107
+ async function N(n) {
108
+ const e = await crypto.subtle.digest("SHA-256", n);
109
+ return Array.from(new Uint8Array(e)).map((t) => t.toString(16).padStart(2, "0")).join("");
110
+ }
111
+ const te = "kition-sync/1", le = { viewer: 0, commenter: 1, editor: 2, owner: 3 }, he = "open-rooms", ue = "headless";
112
+ class q extends Error {
113
+ constructor(e, t, s) {
114
+ super(t), this.code = e, this.data = s;
115
+ }
116
+ /**
117
+ * The room a `room/create` refused `conflict` names (protocol 1.10, RM6): an open-token
118
+ * connection's file generation already has that room, which the caller joins instead.
119
+ */
120
+ get boundDocId() {
121
+ const e = this.data;
122
+ return this.reason === "conflict" && typeof e?.docId == "string" ? e.docId : void 0;
123
+ }
124
+ /** The limit of people co-editing at once a `collab-limit` error names (`error.data.limit`). */
125
+ get collabLimit() {
126
+ const e = this.data;
127
+ return this.reason === "collab-limit" && typeof e?.limit == "number" ? e.limit : void 0;
128
+ }
129
+ /** This error's [[ErrorCode]], when it carries one. */
130
+ get reason() {
131
+ const e = this.data;
132
+ return typeof e?.code == "string" ? e.code : void 0;
133
+ }
134
+ }
135
+ const se = 3e4;
136
+ function de(n) {
137
+ if (!(n instanceof q) || n.reason !== "conflict") return;
138
+ const e = n.data?.lease;
139
+ return e && typeof e == "object" && typeof e.scope == "string" ? e : void 0;
140
+ }
141
+ function fe(n, e) {
142
+ return n === e || n === "*" || e === "*";
143
+ }
144
+ const _ = (n, e) => `${n}\0${e}`;
145
+ class ne {
146
+ constructor(e) {
147
+ this.link = e;
148
+ }
149
+ lists = /* @__PURE__ */ new Map();
150
+ listeners = /* @__PURE__ */ new Map();
151
+ holds = /* @__PURE__ */ new Map();
152
+ /** This connection's session, learned from the first lease it was granted; reset with the connection. */
153
+ session = null;
154
+ /** Whether the server keeps leases and the connection is up: without, there is nobody to coordinate with. */
155
+ get available() {
156
+ return this.link.available();
157
+ }
158
+ /** Takes (or renews) the lease on `scope` for `ttl` ms. Rejects `conflict` (see `leaseHolder`) when another session holds it. */
159
+ async acquire(e, t, s) {
160
+ const i = await this.link.request("lease/acquire", s === void 0 ? { docId: e, scope: t } : { docId: e, scope: t, ttl: s }), r = this.session !== i.lease.session;
161
+ if (this.session = i.lease.session, r) for (const [o, l] of [...this.lists]) for (const c of [...this.listeners.get(o) ?? []]) c(l);
162
+ return i.lease;
163
+ }
164
+ /** Ends this session's lease on `scope` (harmless when it holds none). */
165
+ async release(e, t) {
166
+ this.holds.get(_(e, t))?.stop(), await this.link.request("lease/release", { docId: e, scope: t });
167
+ }
168
+ /**
169
+ * Takes the lease on `scope` and renews it at half its `ttl` until `release` (or the connection
170
+ * drops, which loses it: the server ends a session's leases with the session). Holding a scope
171
+ * already held renews it and answers a new hold that replaces the old one.
172
+ */
173
+ async hold(e, t, s = se) {
174
+ const i = await this.acquire(e, t, s), r = _(e, t);
175
+ this.holds.get(r)?.stop();
176
+ const o = /* @__PURE__ */ new Set(), l = this.link.setTimeout ?? ((m, A) => setTimeout(m, A)), c = this.link.clearTimeout ?? ((m) => clearTimeout(m));
177
+ let u, d = !0;
178
+ const h = () => {
179
+ d && (d = !1, c(u), this.holds.get(r) === k && this.holds.delete(r));
180
+ }, w = () => {
181
+ if (d) {
182
+ h();
183
+ for (const m of [...o]) m();
184
+ }
185
+ }, y = () => {
186
+ u = l(() => {
187
+ d && this.acquire(e, t, s).then(
188
+ () => d && y(),
189
+ () => w()
190
+ );
191
+ }, Math.max(500, Math.floor(s / 2)));
192
+ }, k = { stop: h, lose: w };
193
+ return this.holds.set(r, k), y(), {
194
+ lease: i,
195
+ release: async () => {
196
+ h(), await this.link.request("lease/release", { docId: e, scope: t }).catch(() => {
197
+ });
198
+ },
199
+ onLost: (m) => (o.add(m), () => o.delete(m))
200
+ };
201
+ }
202
+ /** The room's leases as last heard (`lease/changed`); empty before any and while offline. */
203
+ list(e) {
204
+ return this.lists.get(e) ?? [];
205
+ }
206
+ /** Hears `docId`'s lease list each time it changes; answers an unsubscribe. */
207
+ onChanged(e, t) {
208
+ let s = this.listeners.get(e);
209
+ return s || this.listeners.set(e, s = /* @__PURE__ */ new Set()), s.add(t), () => s?.delete(t);
210
+ }
211
+ /** Whether `lease` is this connection's own. */
212
+ mine(e) {
213
+ return this.session !== null && e.session === this.session;
214
+ }
215
+ /** `lease/changed` from the server (the client routes it here). */
216
+ receive(e) {
217
+ const t = e.docId;
218
+ typeof t != "string" || !Array.isArray(e.leases) || this.set(t, e.leases);
219
+ }
220
+ /** The connection dropped: the server ended this session's leases, and the lists are stale. */
221
+ disconnected() {
222
+ this.session = null;
223
+ for (const e of [...this.holds.values()]) e.lose();
224
+ for (const e of [...this.lists.keys()]) this.set(e, []);
225
+ }
226
+ /** Left `docId`'s room: its list no longer applies, and nothing there is held any more. */
227
+ left(e) {
228
+ for (const [t, s] of [...this.holds]) t.startsWith(`${e}\0`) && s.lose();
229
+ this.set(e, []);
230
+ }
231
+ set(e, t) {
232
+ const s = this.lists.get(e) ?? [];
233
+ if (!(!t.length && !s.length)) {
234
+ t.length ? this.lists.set(e, t) : this.lists.delete(e);
235
+ for (const i of [...this.listeners.get(e) ?? []]) i(t);
236
+ }
237
+ }
238
+ }
239
+ class ge {
240
+ constructor(e, t) {
241
+ this.leases = e, this.docId = t;
242
+ }
243
+ holds = /* @__PURE__ */ new Map();
244
+ async acquire(e, t) {
245
+ if (!this.leases.available) return null;
246
+ let s;
247
+ try {
248
+ s = await this.leases.hold(this.docId, e, t);
249
+ } catch (i) {
250
+ if (i instanceof q && (i.reason === "conflict" || i.reason === "forbidden" || i.reason === "invalid")) throw i;
251
+ return null;
252
+ }
253
+ return this.holds.set(e, s), s.onLost(() => {
254
+ this.holds.get(e) === s && this.holds.delete(e);
255
+ }), s.lease;
256
+ }
257
+ async release(e) {
258
+ const t = this.holds.get(e);
259
+ this.holds.delete(e), await t?.release();
260
+ }
261
+ list() {
262
+ return this.leases.list(this.docId);
263
+ }
264
+ onChanged(e) {
265
+ return this.leases.onChanged(this.docId, e);
266
+ }
267
+ mine(e) {
268
+ return this.leases.mine(e);
269
+ }
270
+ /** Releases every lease still held for this editor. */
271
+ dispose() {
272
+ for (const e of this.holds.values()) e.release();
273
+ this.holds.clear();
274
+ }
275
+ }
276
+ const E = () => new q(-32e3, "disconnected", { code: "unavailable" });
277
+ class pe {
278
+ options;
279
+ url = "";
280
+ token = "";
281
+ transport;
282
+ decoder = new I();
283
+ nextId = 1;
284
+ pending = /* @__PURE__ */ new Map();
285
+ pushQueue = [];
286
+ joined = /* @__PURE__ */ new Set();
287
+ /** The highest server `seq` seen for each joined doc (join, pull, or push ack), for re-joining
288
+ * after a reconnect without a KDM version of its own. */
289
+ lastSeq = /* @__PURE__ */ new Map();
290
+ changesListeners = /* @__PURE__ */ new Map();
291
+ presenceListeners = /* @__PURE__ */ new Map();
292
+ accessListeners = /* @__PURE__ */ new Map();
293
+ /** This person's role in each joined room, as its last join or `room/access` said. */
294
+ roles = /* @__PURE__ */ new Map();
295
+ stateListeners = /* @__PURE__ */ new Set();
296
+ roomsListeners = /* @__PURE__ */ new Set();
297
+ accountListeners = /* @__PURE__ */ new Set();
298
+ resolvedListeners = /* @__PURE__ */ new Set();
299
+ saveListeners = /* @__PURE__ */ new Map();
300
+ reconnectAttempt = 0;
301
+ reconnectTimer;
302
+ closed = !1;
303
+ readyForPushes = !1;
304
+ connectionState = "offline";
305
+ hello;
306
+ constructor(e) {
307
+ this.options = e;
308
+ }
309
+ get state() {
310
+ return this.connectionState;
311
+ }
312
+ /** The handshake result from the most recent successful `sync/hello`. */
313
+ get principal() {
314
+ return this.hello?.principal;
315
+ }
316
+ /**
317
+ * The scope of an open-token connection (protocol 1.10, RM1), from the most recent handshake:
318
+ * its one file generation and role; `undefined` for any other connection or before the first.
319
+ */
320
+ get open() {
321
+ const e = this.hello?.open;
322
+ return e && typeof e.file == "string" && typeof e.docKey == "string" ? e : void 0;
323
+ }
324
+ /**
325
+ * The room of this open-token connection's file generation (protocol 1.10, `room/resolve`);
326
+ * `claim: true` asks for the seed claim when it has none (an editor only, RM5).
327
+ */
328
+ resolveRoom(e = !1) {
329
+ return this.request("room/resolve", () => e ? { claim: !0 } : {}, (t) => ({ docId: typeof t.docId == "string" ? t.docId : null, claimed: t.claimed === !0, save: t.save ?? null }));
330
+ }
331
+ /**
332
+ * Starts a save of `docId`'s room (protocol 1.10, `save/begin`, D3): answers the change to write
333
+ * and its authors, with the room in `force-save` by this session; `conflict` while another runs.
334
+ */
335
+ saveBegin(e, t) {
336
+ return this.request("save/begin", () => ({ docId: e, trigger: t }), (s) => ({ save: s.save, seq: s.seq, authors: s.authors ?? [], receipt: typeof s.receipt == "string" ? s.receipt : "" }));
337
+ }
338
+ /** Ends this session's save of `seq` (protocol 1.10, `save/end`): the `version` it wrote, or why it failed. */
339
+ async saveEnd(e, t, s) {
340
+ await this.request("save/end", () => ({ docId: e, seq: t, ..."version" in s ? { version: s.version } : { version: null, error: s.error } }), () => {
341
+ });
342
+ }
343
+ /** Hears `docId`'s room save state change (protocol 1.10, `save/changed`). */
344
+ onSave(e, t) {
345
+ let s = this.saveListeners.get(e);
346
+ return s || this.saveListeners.set(e, s = /* @__PURE__ */ new Set()), s.add(t), () => s.delete(t);
347
+ }
348
+ /** Hears the connection's file generation get its room (protocol 1.10, `room/resolved`). */
349
+ onRoomResolved(e) {
350
+ return this.resolvedListeners.add(e), () => this.resolvedListeners.delete(e);
351
+ }
352
+ /**
353
+ * Everything the server listed in its most recent `sync/hello`: protocol capabilities (`leases`,
354
+ * `headless`, a server's own names) and capability sets; empty before the first handshake. A
355
+ * reconnect may change it (a principal's plan): read it again when the state turns `online`.
356
+ */
357
+ get capabilities() {
358
+ const e = this.hello?.capabilities;
359
+ return Array.isArray(e) ? e.filter((t) => typeof t == "string") : [];
360
+ }
361
+ /**
362
+ * The Kition kit platform's capability sets the server serves this principal (rule CS2), such as
363
+ * `KitModel 1.0` and `KitCollab 1.1`: the `Name major.minor` entries of `capabilities`.
364
+ */
365
+ get capabilitySets() {
366
+ return U(this.capabilities);
367
+ }
368
+ /** Whether the server serves the capability set `set` (such as `'KitCollab 1.1'`); false before the first handshake. */
369
+ supports(e) {
370
+ return Q(e, this.capabilitySets);
371
+ }
372
+ onState(e) {
373
+ return this.stateListeners.add(e), () => this.stateListeners.delete(e);
374
+ }
375
+ /**
376
+ * Connects and performs `sync/hello`; resolves once the handshake succeeds. A `token` function
377
+ * is called for every connection attempt (reconnects too), so a short-lived token is fresh.
378
+ */
379
+ async connect(e, t) {
380
+ return this.closed = !1, this.url = e, this.token = t, this.reconnectAttempt = 0, this.openConnection();
381
+ }
382
+ close() {
383
+ this.closed = !0, this.clearReconnectTimer(), this.transport?.close(), this.transport = void 0, this.setState("offline"), this.failPending(new q(-32e3, "closed", { code: "unavailable" }));
384
+ for (const e of this.pushQueue.splice(0)) e.reject(new q(-32e3, "closed", { code: "unavailable" }));
385
+ }
386
+ /**
387
+ * Joins `docId`'s room, or re-joins it after a reconnect. `since` is the server seq the caller
388
+ * already has every change up to (omitted: the highest `seq` this client has itself seen for
389
+ * `docId`, or `null` with none yet, which asks for everything from the room's snapshot).
390
+ *
391
+ * A busy room's catch-up does not fit in one `room/join` reply, so the server pages it (`more`,
392
+ * Kition platform `docs/platform/reference/sync-protocol.md` section 3); this repeats `room/join` with `since` set to each page's
393
+ * `seq` until `more` is `false`, combining every page's `changes` into the one result this
394
+ * resolves with. `presence` and `role` are from the last page.
395
+ *
396
+ * A join with `since: null` (a client with no replica yet) may start from a shallow snapshot
397
+ * (protocol 1.8): `start` (else the client's `start` option) asks for one. The result then says
398
+ * `snapshot` and `shallow`, and `changes[0]` is the shallow snapshot to load as a new replica.
399
+ */
400
+ async join(e, t, s = this.options.start ?? {}) {
401
+ let i = t === void 0 ? this.lastSeq.get(e) ?? null : t;
402
+ const r = [];
403
+ let o = !1, l = !1, c;
404
+ do {
405
+ const d = i === null ? { docId: e, since: i, ...F(s) } : { docId: e, since: i };
406
+ c = await this.request("room/join", () => d, (h, w) => ({
407
+ changes: ee(h.changes, w),
408
+ seq: h.seq,
409
+ more: h.more,
410
+ presence: h.presence,
411
+ role: h.role,
412
+ ...h.snapshot === !0 ? { snapshot: !0 } : {},
413
+ ...h.shallow === !0 ? { shallow: !0 } : {}
414
+ })), c.snapshot && (o = !0), c.shallow && (l = !0), r.push(...c.changes), i = c.seq;
415
+ } while (c.more);
416
+ const u = { ...c, changes: r, ...o ? { snapshot: o } : {}, ...l ? { shallow: l } : {} };
417
+ return this.joined.add(e), this.roles.set(e, u.role), this.bumpSeq(e, u.seq), u;
418
+ }
419
+ leave(e) {
420
+ this.joined.delete(e), this.roles.delete(e), this.leases.left(e), this.sendNotification("room/leave", () => ({ docId: e }));
421
+ }
422
+ push(e, t) {
423
+ return new Promise((s, i) => {
424
+ const r = { docId: e, changes: t, resolve: s, reject: i };
425
+ this.readyForPushes ? this.sendPush(r) : this.pushQueue.push(r);
426
+ });
427
+ }
428
+ onChanges(e, t) {
429
+ return this.subscribe(this.changesListeners, e, t);
430
+ }
431
+ setPresence(e, t) {
432
+ this.sendNotification("presence/set", () => ({ docId: e, state: t }));
433
+ }
434
+ onPresence(e, t) {
435
+ return this.subscribe(this.presenceListeners, e, t);
436
+ }
437
+ /** Blobs, scoped to the document whose room uses them (protocol 1.5). */
438
+ /**
439
+ * Leases for coordinated objects (protocol 1.5, `lease/*`): `acquire`, `release`, `hold` (kept
440
+ * renewed), the rooms' lease lists (`list`, `onChanged`), and `mine`. `available` is false while
441
+ * offline or against a server that does not list the `leases` capability.
442
+ */
443
+ leases = new ne({
444
+ request: (e, t) => this.request(e, () => t, (s) => s),
445
+ available: () => this.connectionState === "online" && this.capabilities.includes("leases"),
446
+ // Field initializers run before the constructor sets `options`: read them when used.
447
+ setTimeout: (e, t) => (this.options.setTimeout ?? ((s, i) => setTimeout(s, i)))(e, t),
448
+ clearTimeout: (e) => (this.options.clearTimeout ?? ((t) => clearTimeout(t)))(e)
449
+ });
450
+ blobs = {
451
+ has: (e, t) => this.request("blob/has", () => ({ docId: e, hashes: t }), (s) => s),
452
+ put: async (e, t, s) => {
453
+ const i = await N(t);
454
+ return await this.request("blob/put", (r) => ({ docId: e, hash: i, mime: s, data: r.bin(t) }), () => ({})), { hash: i };
455
+ },
456
+ get: async (e, t) => {
457
+ const s = await this.request("blob/get", () => ({ docId: e, hash: t }), (r, o) => ({
458
+ data: v(r.data, o),
459
+ mime: r.mime
460
+ })), i = await N(s.data);
461
+ if (i !== t) throw new Error(`blob/get returned data hashing to ${i}, not the requested ${t}`);
462
+ return s;
463
+ }
464
+ };
465
+ /**
466
+ * The room's snapshot, for a client with no replica yet, and the `seq` it reflects; `join` with
467
+ * that `seq` next. `start` (else the client's `start` option) may ask for a shallow one
468
+ * (protocol 1.8), which the result then says (`shallow`).
469
+ */
470
+ snapshot(e, t = this.options.start ?? {}) {
471
+ return this.request(
472
+ "snapshot/get",
473
+ () => ({ docId: e, ...F(t) }),
474
+ (s, i) => ({ snapshot: v(s.snapshot, i), seq: s.seq, ...s.shallow === !0 ? { shallow: !0 } : {} })
475
+ );
476
+ }
477
+ createRoom(e, t, s, i) {
478
+ return this.request("room/create", (r) => ({ docId: e, snapshot: r.bin(t), name: s, kit: i }), (r) => r);
479
+ }
480
+ /**
481
+ * Makes a private room (protocol 1.9, `room/create` with `private: true`): it syncs the document
482
+ * to this person's own devices, with no share link until they mint one (`createLink`), which
483
+ * shares it. A server before 1.9 makes an ordinary room and answers its link.
484
+ */
485
+ createPrivateRoom(e, t, s, i) {
486
+ return this.request("room/create", (r) => ({ docId: e, snapshot: r.bin(t), name: s, kit: i, private: !0 }), (r) => ({ shareLink: r.shareLink ?? null }));
487
+ }
488
+ /**
489
+ * One page of the rooms this person is a member of, most recently changed first (protocol 1.9,
490
+ * `rooms/list`); pass the answered `cursor` for the next page (`null`: none).
491
+ */
492
+ listRooms(e = {}) {
493
+ return this.request("rooms/list", () => ({ ...e }), (t) => ({ rooms: t.rooms ?? [], cursor: t.cursor ?? null }));
494
+ }
495
+ /** Every room this person is a member of, all pages of `listRooms`, keyed by `docId`. */
496
+ async listAllRooms() {
497
+ const e = /* @__PURE__ */ new Map();
498
+ let t;
499
+ for (let s = 0; s < 1e3; s += 1) {
500
+ const i = await this.listRooms(t === void 0 ? {} : { cursor: t });
501
+ for (const r of i.rooms) e.has(r.docId) || e.set(r.docId, r);
502
+ if (!i.cursor) break;
503
+ t = i.cursor;
504
+ }
505
+ return [...e.values()];
506
+ }
507
+ /**
508
+ * Hears this person's document list change (protocol 1.9, `rooms/changed`): `room` is the entry
509
+ * now, or `null` when they are no longer a member.
510
+ */
511
+ onRoomsChanged(e) {
512
+ return this.roomsListeners.add(e), () => this.roomsListeners.delete(e);
513
+ }
514
+ /** This person's account settings on the server (protocol 1.9, `account/settings`). */
515
+ accountSettings() {
516
+ return this.request("account/settings", () => ({}), (e) => ({ syncAll: e.syncAll === !0 }));
517
+ }
518
+ /** Changes this person's account settings (protocol 1.9, `account/update`); answers them all. */
519
+ updateAccountSettings(e) {
520
+ return this.request("account/update", () => ({ ...e }), (t) => ({ syncAll: t.syncAll === !0 }));
521
+ }
522
+ /** Hears this person's account settings change on any of their devices (protocol 1.9, `account/changed`). */
523
+ onAccountChanged(e) {
524
+ return this.accountListeners.add(e), () => this.accountListeners.delete(e);
525
+ }
526
+ /** Resolves `shareLink` to the room it points to; `join(result.docId, ...)` actually joins it. */
527
+ openRoom(e) {
528
+ return this.request("room/open", () => ({ shareLink: e }), (t) => t);
529
+ }
530
+ /** Mints another share link to `docId`'s room granting `role` (protocol 1.4, `room/link`; `commenter` since 1.6). */
531
+ createLink(e, t) {
532
+ return this.request("room/link", () => ({ docId: e, role: t }), (s) => s);
533
+ }
534
+ /** The room's members and working share links (protocol 1.6, `room/members`; owner or editor). */
535
+ members(e) {
536
+ return this.request("room/members", () => ({ docId: e }), (t) => t);
537
+ }
538
+ /** Changes another member's role (protocol 1.6, `room/setRole`; owner only). */
539
+ async setRole(e, t, s) {
540
+ await this.request("room/setRole", () => ({ docId: e, principalId: t, role: s }), () => {
541
+ });
542
+ }
543
+ /** Removes another member from the room (protocol 1.6, `room/removeMember`; owner only). */
544
+ async removeMember(e, t) {
545
+ await this.request("room/removeMember", () => ({ docId: e, principalId: t }), () => {
546
+ });
547
+ }
548
+ /** Revokes one of the room's share links (protocol 1.6, `room/revokeLink`; owner only). */
549
+ async revokeLink(e, t) {
550
+ await this.request("room/revokeLink", () => ({ docId: e, shareLink: t }), () => {
551
+ });
552
+ }
553
+ /**
554
+ * Hears this person's role in `docId`'s room change (protocol 1.6, `room/access`): the owner set
555
+ * a new one, or removed them (`null`; the room is then no longer joined, and not re-joined on a
556
+ * reconnect).
557
+ */
558
+ onAccess(e, t) {
559
+ return this.subscribe(this.accessListeners, e, t);
560
+ }
561
+ /** The room's history checkpoints, newest first (protocol 1.5, `history/list`). */
562
+ history(e, t = {}) {
563
+ return this.request("history/list", () => ({ docId: e, ...t }), (s) => s);
564
+ }
565
+ /** The document as of `seq` (protocol 1.5, `history/get`). */
566
+ historyAt(e, t) {
567
+ return this.request("history/get", () => ({ docId: e, seq: t }), (s, i) => ({ snapshot: v(s.snapshot, i), seq: s.seq }));
568
+ }
569
+ /**
570
+ * Restores the joined room's document as of `seq` as one new change (protocol 1.5,
571
+ * `history/restore`); the change arrives as `changes/pull` like anyone else's.
572
+ */
573
+ restore(e, t) {
574
+ return this.request("history/restore", () => ({ docId: e, seq: t }), (s) => s);
575
+ }
576
+ /**
577
+ * A picture of `docId`'s room as of its latest change, rendered by the kit on a server that runs
578
+ * kits headless (protocol 1.7, `preview/get`; the server lists `headless`).
579
+ */
580
+ preview(e, t = {}) {
581
+ return this.request(
582
+ "preview/get",
583
+ () => ({ docId: e, ...t }),
584
+ (s, i) => ({
585
+ image: v(s.image, i),
586
+ mimeType: s.mimeType,
587
+ width: s.width,
588
+ height: s.height,
589
+ seq: s.seq
590
+ })
591
+ );
592
+ }
593
+ /** `docId`'s room as a file in `format`, saved by the kit on the server (protocol 1.7, `export/get`). */
594
+ exportFile(e, t) {
595
+ return this.request(
596
+ "export/get",
597
+ () => t === void 0 ? { docId: e } : { docId: e, format: t },
598
+ (s, i) => ({ data: v(s.data, i), name: s.name, format: s.format, seq: s.seq })
599
+ );
600
+ }
601
+ /**
602
+ * Runs an object-model batch on the joined room's document in the server's headless kit, as an
603
+ * agent acting for this person (protocol 1.7, `agent/run`); the change arrives as `changes/pull`.
604
+ */
605
+ runAgent(e, t, s) {
606
+ return this.request("agent/run", () => s === void 0 ? { docId: e, batch: t } : { docId: e, batch: t, prompt: s }, (i) => i);
607
+ }
608
+ // -- connection lifecycle --------------------------------------------------------------------
609
+ async openConnection() {
610
+ this.setState("connecting"), this.decoder = new I();
611
+ const e = this.options.createTransport(this.url);
612
+ return this.transport = e, new Promise((t, s) => {
613
+ e.onopen = () => {
614
+ this.sendHello().then(t, s);
615
+ }, e.onerror = () => {
616
+ }, e.onclose = () => {
617
+ this.handleDisconnect(), s(E());
618
+ }, e.onmessage = (i) => this.handleFrame(i.data);
619
+ });
620
+ }
621
+ async sendHello() {
622
+ const e = this.transport;
623
+ let t;
624
+ try {
625
+ t = typeof this.token == "function" ? await this.token() : this.token;
626
+ } catch (i) {
627
+ throw this.transport === e && e?.close(), i;
628
+ }
629
+ if (this.transport !== e) throw E();
630
+ const s = await this.request(
631
+ "sync/hello",
632
+ () => ({ protocol: te, token: t, client: this.options.client ?? { name: "@kition/sync", version: "0.1.0" }, capabilities: this.options.capabilities ?? [] }),
633
+ (i) => i
634
+ );
635
+ return this.hello = s, this.reconnectAttempt = 0, this.setState("online"), await this.rejoinAll(), this.readyForPushes = !0, await this.flushQueue(), s;
636
+ }
637
+ /** Re-joins every room this client had joined, each with the highest `seq` it last saw for it
638
+ * (never re-fetching history it already has), and delivers whatever catch-up changes come back.
639
+ * A role that changed while the connection was down (a host's new open token, an owner's change
640
+ * whose `room/access` notice could not arrive) is reported to `onAccess` listeners. */
641
+ async rejoinAll() {
642
+ const e = [...this.joined];
643
+ await Promise.allSettled(
644
+ e.map(async (t) => {
645
+ const s = this.roles.get(t), i = await this.join(t, void 0, {});
646
+ if (s !== void 0 && i.role !== s)
647
+ for (const r of this.accessListeners.get(t) ?? []) r(i.role);
648
+ for (const r of i.changes) this.emitChanges(t, { changes: r });
649
+ })
650
+ );
651
+ }
652
+ /** Sends every queued push, in order, waiting for each one to settle (or be requeued by a
653
+ * disconnect) before sending the next. */
654
+ async flushQueue() {
655
+ for (; this.readyForPushes; ) {
656
+ const e = this.pushQueue.shift();
657
+ if (!e) return;
658
+ await this.sendPush(e);
659
+ }
660
+ }
661
+ handleDisconnect() {
662
+ if (this.closed) return;
663
+ this.readyForPushes = !1, this.setState("offline"), this.leases.disconnected();
664
+ const e = [];
665
+ for (const [t, s] of [...this.pending])
666
+ s.push ? (e.push(s.push), s.onRequeue?.()) : s.reject(E()), this.pending.delete(t);
667
+ this.pushQueue = [...e, ...this.pushQueue], this.scheduleReconnect();
668
+ }
669
+ scheduleReconnect() {
670
+ if (this.closed) return;
671
+ const e = z(this.reconnectAttempt, this.options.random);
672
+ this.reconnectAttempt += 1;
673
+ const t = this.options.setTimeout ?? ((s, i) => setTimeout(s, i));
674
+ this.reconnectTimer = t(() => {
675
+ this.openConnection().catch(() => {
676
+ });
677
+ }, e);
678
+ }
679
+ clearReconnectTimer() {
680
+ if (this.reconnectTimer === void 0) return;
681
+ (this.options.clearTimeout ?? ((t) => clearTimeout(t)))(this.reconnectTimer), this.reconnectTimer = void 0;
682
+ }
683
+ setState(e) {
684
+ if (this.connectionState !== e) {
685
+ this.connectionState = e;
686
+ for (const t of this.stateListeners) t(e);
687
+ }
688
+ }
689
+ failPending(e) {
690
+ for (const t of this.pending.values()) t.reject(e);
691
+ this.pending.clear();
692
+ }
693
+ // -- sending and receiving --------------------------------------------------------------------
694
+ /** Sends one push and resolves once it settles (success, failure, or being requeued by a
695
+ * disconnect) -- never the push's own promise, which stays pending across a requeue. */
696
+ sendPush(e) {
697
+ if (!this.transport)
698
+ return this.pushQueue.unshift(e), Promise.resolve();
699
+ const t = this.transport, s = new R(), i = s.bin(e.changes), r = String(this.nextId++), o = { jsonrpc: "2.0", id: r, method: "changes/push", params: { docId: e.docId, changes: i } };
700
+ return new Promise((l) => {
701
+ this.pending.set(r, {
702
+ push: e,
703
+ resolve: (c) => {
704
+ const u = c;
705
+ this.bumpSeq(e.docId, u.seq), e.resolve(u), l();
706
+ },
707
+ reject: (c) => {
708
+ e.reject(c), l();
709
+ },
710
+ onRequeue: l
711
+ });
712
+ for (const c of s.finish(o)) t.send(c);
713
+ });
714
+ }
715
+ request(e, t, s) {
716
+ if (!this.transport || this.connectionState !== "online" && e !== "sync/hello") return Promise.reject(E());
717
+ const i = new R(), r = t(i), o = String(this.nextId++), l = { jsonrpc: "2.0", id: o, method: e, params: r }, c = this.transport;
718
+ return new Promise((u, d) => {
719
+ this.pending.set(o, {
720
+ resolve: (h, w) => u(s(h, w)),
721
+ reject: d
722
+ });
723
+ for (const h of i.finish(l)) c.send(h);
724
+ });
725
+ }
726
+ sendNotification(e, t) {
727
+ if (!this.transport || this.connectionState !== "online") return;
728
+ const s = new R(), i = t(s), r = { jsonrpc: "2.0", method: e, params: i };
729
+ for (const o of s.finish(r)) this.transport.send(o);
730
+ }
731
+ handleFrame(e) {
732
+ let t;
733
+ try {
734
+ t = this.decoder.feed(typeof e == "string" ? e : new Uint8Array(e));
735
+ } catch {
736
+ return;
737
+ }
738
+ if (!t) return;
739
+ const { message: s, bins: i } = t;
740
+ if (typeof s.method == "string" && s.id === void 0) {
741
+ this.handleNotification(s.method, s.params, i);
742
+ return;
743
+ }
744
+ if (s.id !== void 0) {
745
+ const r = this.pending.get(String(s.id));
746
+ if (!r) return;
747
+ this.pending.delete(String(s.id)), s.error ? r.reject(ie(s.error)) : r.resolve(s.result, i);
748
+ }
749
+ }
750
+ handleNotification(e, t, s) {
751
+ if (e === "changes/pull") {
752
+ const i = t.docId, r = t.seq;
753
+ this.bumpSeq(i, r), this.emitChanges(i, { changes: v(t.changes, s), seq: r, from: t.from });
754
+ return;
755
+ }
756
+ if (e === "lease/changed") {
757
+ this.leases.receive(t);
758
+ return;
759
+ }
760
+ if (e === "room/access") {
761
+ const i = t.docId, r = t.role ?? null;
762
+ r === null ? (this.joined.delete(i), this.roles.delete(i), this.leases.left(i)) : this.roles.set(i, r);
763
+ for (const o of this.accessListeners.get(i) ?? []) o(r);
764
+ return;
765
+ }
766
+ if (e === "rooms/changed") {
767
+ const i = t.docId, r = t.room ?? null;
768
+ for (const o of this.roomsListeners) o(i, r);
769
+ return;
770
+ }
771
+ if (e === "save/changed") {
772
+ if (typeof t.docId == "string") for (const i of this.saveListeners.get(t.docId) ?? []) i(t.save);
773
+ return;
774
+ }
775
+ if (e === "room/resolved") {
776
+ if (typeof t.docId == "string") for (const i of this.resolvedListeners) i(t.docId);
777
+ return;
778
+ }
779
+ if (e === "account/changed") {
780
+ const i = { syncAll: t.syncAll === !0 };
781
+ for (const r of this.accountListeners) r(i);
782
+ return;
783
+ }
784
+ if (e === "presence/update") {
785
+ const i = t.docId;
786
+ for (const r of this.presenceListeners.get(i) ?? []) r(t.peers);
787
+ }
788
+ }
789
+ emitChanges(e, t) {
790
+ for (const s of this.changesListeners.get(e) ?? []) s(t);
791
+ }
792
+ /** Keeps the highest server `seq` seen for `docId`, across joins, pulls, and push acks. */
793
+ bumpSeq(e, t) {
794
+ const s = this.lastSeq.get(e);
795
+ (s === void 0 || t > s) && this.lastSeq.set(e, t);
796
+ }
797
+ subscribe(e, t, s) {
798
+ let i = e.get(t);
799
+ return i || e.set(t, i = /* @__PURE__ */ new Set()), i.add(s), () => i?.delete(s);
800
+ }
801
+ }
802
+ function F(n) {
803
+ return { ...n.shallow ? { shallow: !0 } : {}, ...n.prefer ? { prefer: n.prefer } : {} };
804
+ }
805
+ function ie(n) {
806
+ return new q(n.code, n.message, n.data);
807
+ }
808
+ const re = 256;
809
+ function me(n = null) {
810
+ return { status: "editing", dirty: !1, headSeq: 0, savedSeq: 0, version: n, trigger: null, by: null, reason: null, savingSeq: null };
811
+ }
812
+ const oe = (n, e) => Object.keys(n).every((t) => n[t] === e[t]);
813
+ function p(n, e, t) {
814
+ return t ? { state: n, refused: t, changed: !1 } : { state: e, changed: !oe(n, e) };
815
+ }
816
+ function we(n, e) {
817
+ switch (e.type) {
818
+ case "change": {
819
+ const t = Math.max(n.headSeq, e.seq), s = n.status === "closed" ? "editing" : n.status;
820
+ return p(n, { ...n, headSeq: t, dirty: t > n.savedSeq, status: s });
821
+ }
822
+ case "joined":
823
+ return p(n, n.status === "closed" ? { ...n, status: "editing" } : n);
824
+ case "begin":
825
+ return n.status === "force-save" ? p(n, n, n.by === e.by ? void 0 : "conflict") : !n.dirty && e.trigger !== "user" ? p(n, n) : p(n, { ...n, status: "force-save", trigger: e.trigger, by: e.by, savingSeq: n.headSeq });
826
+ case "end": {
827
+ if (n.status !== "force-save" || n.by !== e.by) return p(n, n, "forbidden");
828
+ if (e.seq !== n.savingSeq || e.error === void 0 && (e.version == null || typeof e.version != "string") || e.version != null && (typeof e.version != "string" || !e.version || e.version.length > re)) return p(n, n, "invalid");
829
+ if (e.error === "corrupted") return p(n, { ...n, status: "corrupted", reason: "corrupted", savingSeq: null });
830
+ if (e.error) return p(n, { ...n, status: "editing", reason: e.error, savingSeq: null });
831
+ const t = e.seq;
832
+ return p(n, { ...n, status: "editing", savedSeq: t, version: e.version, dirty: n.headSeq > t, reason: null, savingSeq: null });
833
+ }
834
+ case "left": {
835
+ let t = n;
836
+ return n.status === "force-save" && n.by === e.by && (t = { ...t, status: "editing", savingSeq: null }), e.last && t.status !== "corrupted" && (t = { ...t, status: t.dirty ? "must-save" : "closed" }), p(n, t);
837
+ }
838
+ }
839
+ }
840
+ function ye(n) {
841
+ return n.status === "must-save";
842
+ }
843
+ function ae(n) {
844
+ const e = n ?? {};
845
+ for (const t of [e.code, e.reason, e.data?.reason]) if (t === "conflict" || t === "corrupted") return t;
846
+ return "failed";
847
+ }
848
+ async function be(n) {
849
+ const { client: e, docId: t, trigger: s } = n;
850
+ let i;
851
+ try {
852
+ i = await e.saveBegin(t, s);
853
+ } catch (d) {
854
+ if (d instanceof q && d.reason === "conflict") return { status: "busy" };
855
+ throw d;
856
+ }
857
+ if (i.save.status !== "force-save") return { status: "clean" };
858
+ const { seq: r, authors: o, receipt: l } = i;
859
+ let c;
860
+ try {
861
+ c = await n.write({ seq: r, authors: o, trigger: s, receipt: l });
862
+ } catch (d) {
863
+ const h = (n.classify ?? ae)(d);
864
+ return await e.saveEnd(t, r, { error: h }).catch(() => {
865
+ }), { status: "failed", error: h, cause: d };
866
+ }
867
+ await e.saveEnd(t, r, { version: c });
868
+ let u = !1;
869
+ if (n.checkpoint)
870
+ try {
871
+ await n.checkpoint({ seq: r, version: c }), u = !0;
872
+ } catch {
873
+ u = !1;
874
+ }
875
+ return { status: "saved", version: c, seq: r, authors: o, checkpointed: u };
876
+ }
877
+ const ce = "application/octet-stream";
878
+ function j(n) {
879
+ return n instanceof Uint8Array ? n : new Uint8Array(n);
880
+ }
881
+ function C(n) {
882
+ return n.slice().buffer;
883
+ }
884
+ function ve(n) {
885
+ const { docId: e, replica: t, sync: s, versions: i } = n;
886
+ let r = n.lastSent ?? new Uint8Array();
887
+ const o = /* @__PURE__ */ new Set(), l = [];
888
+ let c = !1, u = !1, d = !1, h = !1, w = Promise.resolve();
889
+ const y = (a) => (w = w.then(() => h ? void 0 : a()).catch((g) => n.onError?.(g)), w);
890
+ async function k(a) {
891
+ const g = a.filter((f) => !o.has(f.hash));
892
+ if (!g.length) return;
893
+ const { missing: b } = await s.blobs.has(e, g.map((f) => f.hash)), L = new Set(b);
894
+ for (const f of g) L.has(f.hash) && await s.blobs.put(e, f.data, ce);
895
+ for (const f of g) o.add(f.hash);
896
+ }
897
+ async function m() {
898
+ if (!c || u) return;
899
+ const a = j(await t.version()), g = await t.exportChanges(C(r)), b = j(g.changes);
900
+ if (i.isEmpty(b)) return;
901
+ try {
902
+ await k(K(j(g.blobs)));
903
+ } catch {
904
+ return;
905
+ }
906
+ r = i.merge(r, a);
907
+ const L = r;
908
+ s.push(e, b).then(() => n.onSent?.(L), (f) => n.onError?.(f));
909
+ }
910
+ async function A(a) {
911
+ const g = Y(a).filter((f) => !o.has(f));
912
+ let b = new Uint8Array();
913
+ if (g.length) {
914
+ let f;
915
+ try {
916
+ const { missing: x } = await s.blobs.has(e, g), $ = new Set(x);
917
+ f = [];
918
+ for (const M of g) $.has(M) || f.push({ hash: M, data: (await s.blobs.get(e, M)).data });
919
+ } catch {
920
+ return l.push(a), !1;
921
+ }
922
+ for (const x of f) o.add(x.hash);
923
+ b = V(f);
924
+ }
925
+ await t.importChanges(C(a), C(b));
926
+ const L = i.endOf(a);
927
+ return L && (r = i.merge(r, L)), !0;
928
+ }
929
+ async function D() {
930
+ for (; l.length; ) {
931
+ const a = l.shift();
932
+ if (!await A(a)) return;
933
+ }
934
+ }
935
+ async function O(a) {
936
+ a === void 0 || l.length || !n.onSeen || n.onSeen({ seq: a, version: j(await t.version()) });
937
+ }
938
+ async function B() {
939
+ const a = await s.join(e, n.since ?? null, {});
940
+ c = !0, u = a.role === "viewer", n.onJoined?.({ presence: a.presence, role: a.role });
941
+ for (const g of a.changes) await A(g);
942
+ await O(a.seq);
943
+ }
944
+ const H = [
945
+ s.onChanges(e, (a) => void y(async () => {
946
+ await A(a.changes) && await O(a.seq);
947
+ })),
948
+ t.onChanged(() => void y(m)),
949
+ s.onAccess?.(e, (a) => {
950
+ u = a === null || a === "viewer", a === null && (c = !1, d = !0), n.onAccess?.(a);
951
+ }) ?? (() => {
952
+ }),
953
+ s.onState((a) => {
954
+ a === "online" && y(async () => {
955
+ d || (c || await B(), await D(), await m());
956
+ });
957
+ })
958
+ ];
959
+ return s.state === "online" && y(async () => {
960
+ await B(), await m();
961
+ }), {
962
+ stop: () => {
963
+ if (!h) {
964
+ h = !0;
965
+ for (const a of H) a();
966
+ c && s.leave(e);
967
+ }
968
+ },
969
+ idle: () => w
970
+ };
971
+ }
972
+ export {
973
+ ge as DocumentLeases,
974
+ ue as HEADLESS_CAPABILITY,
975
+ he as OPEN_ROOMS_CAPABILITY,
976
+ le as ROLE_RANK,
977
+ te as SYNC_PROTOCOL,
978
+ pe as SyncClient,
979
+ ne as SyncLeases,
980
+ q as SyncRpcError,
981
+ Y as blobHashCandidates,
982
+ U as capabilitySetsOf,
983
+ ae as classifySaveError,
984
+ K as decodeBlobSection,
985
+ V as encodeBlobSection,
986
+ me as initialSaveState,
987
+ de as leaseHolder,
988
+ ye as mustSave,
989
+ P as parseCapabilitySet,
990
+ be as runSave,
991
+ we as saveTransition,
992
+ fe as scopesCollide,
993
+ Q as servesCapabilitySet,
994
+ ve as startRelay
995
+ };