@graview/ship 0.1.50 → 0.1.52

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.
@@ -1,5 +1,5 @@
1
1
  import { lowerFirst } from "@graview/core/words";
2
- import { FieldRevisions, InvalidArguments, UnknownMutationError, hidesFrom, hueFor, isUnset, namesUnseen, participantKey, redact, seatLens, sha256Hex, seenBy, seesId, refusalOf, VISITOR_PRESENCE_TTL_MS, WIRE_PROTOCOL, withInverse, } from "@graview/core";
2
+ import { FieldRevisions, InvalidArguments, UnknownMutationError, hidesFrom, hueFor, isUnset, namesUnseen, participantKey, redact, seatLens, sha256Hex, seenBy, seesId, refusalOf, applySplice, TYPE_TEXT, UNSET, VISITOR_PRESENCE_TTL_MS, WIRE_PROTOCOL, withInverse, } from "@graview/core";
3
3
  // What a seat is served keeps the fields its sight keeps (Roadmap f-field-sight): the protocol judges them.
4
4
  import "@graview/core/field-sight";
5
5
  import "@graview/core/publishing";
@@ -23,24 +23,106 @@ class NotAdmitted extends Error {
23
23
  * inverse off the op, so it is sent the inverse written out — the bytes
24
24
  * format 1 cost, and nothing it would misread.
25
25
  */
26
- export function opsFor(opFormat, ops) {
27
- return opFormat !== undefined && opFormat >= 2 ? ops : ops.map(withInverse);
26
+ export function opsFor(opFormat, ops, store) {
27
+ const read = store && (opFormat ?? 1) < 3 ? wholeSplices(store, ops) : ops;
28
+ return opFormat !== undefined && opFormat >= 2 ? read : read.map(withInverse);
29
+ }
30
+ /**
31
+ * A SPLICE AS A READER BEFORE OP FORMAT 3 READS IT (Roadmap f-collab-text,
32
+ * phase 3): a `patch-node` of the field's whole text before and after it,
33
+ * as every op before typing together wrote one. A reader that did not say
34
+ * it reads format 3 has never met a `splice-text` and would refuse it; it
35
+ * is sent the same change whole and its copy folds to the same text. The
36
+ * text each splice stood on is read by walking back from the field's value
37
+ * now over the log's ops since — at a broadcast that is the op just
38
+ * landed, in a catch-up as far as the oldest op asked about. An op that is
39
+ * not in the store's log at its seq is sent as it is.
40
+ */
41
+ function wholeSplices(store, ops) {
42
+ const spliced = ops.filter((op) => op.primitives.some((one) => one.op === "splice-text"));
43
+ if (spliced.length === 0)
44
+ return ops;
45
+ const key = (id, field) => `${id}\u0000${field}`;
46
+ const texts = new Map();
47
+ for (const op of spliced)
48
+ for (const one of op.primitives)
49
+ if (one.op === "splice-text")
50
+ texts.set(key(one.id, one.field), store.graph.getNode(one.id)?.[one.field]);
51
+ const wanted = new Set(spliced.map((op) => op.seq));
52
+ const first = Math.max(store.log.horizon, Math.min(...wanted));
53
+ const log = store.log.all();
54
+ /** Each wanted op's splices, by field, in order: the text before and after each. */
55
+ const whole = new Map();
56
+ for (let seq = store.log.length - 1; seq >= first; seq--) {
57
+ const op = log[seq - store.log.horizon];
58
+ for (let at = op.primitives.length - 1; at >= 0; at--) {
59
+ const one = op.primitives[at];
60
+ if (one.op === "splice-text") {
61
+ const field = key(one.id, one.field);
62
+ if (!texts.has(field))
63
+ continue;
64
+ const after = texts.get(field);
65
+ let before;
66
+ try {
67
+ before = typeof after === "string" ? applySplice(after, { at: one.at, removed: one.inserted, inserted: one.removed }) : undefined;
68
+ }
69
+ catch {
70
+ before = undefined;
71
+ }
72
+ texts.set(field, before);
73
+ if (!wanted.has(seq))
74
+ continue;
75
+ let byField = whole.get(seq);
76
+ if (!byField)
77
+ whole.set(seq, (byField = new Map()));
78
+ byField.set(field, [{ before, after }, ...(byField.get(field) ?? [])]);
79
+ }
80
+ else if (one.op === "patch-node") {
81
+ for (const field of Object.keys(one.after))
82
+ if (texts.has(key(one.id, field)))
83
+ texts.set(key(one.id, field), one.before[field]);
84
+ }
85
+ else if (one.op === "add-node" || one.op === "remove-node") {
86
+ for (const [field] of texts)
87
+ if (field.startsWith(`${one.node.id}\u0000`))
88
+ texts.set(field, one.op === "add-node" ? undefined : one.node[field.slice(one.node.id.length + 1)]);
89
+ }
90
+ }
91
+ }
92
+ return ops.map((op) => {
93
+ const byField = whole.get(op.seq);
94
+ if (!byField || log[op.seq - store.log.horizon]?.id !== op.id)
95
+ return op;
96
+ const taken = new Map();
97
+ const primitives = op.primitives.map((one) => {
98
+ if (one.op !== "splice-text")
99
+ return one;
100
+ const field = key(one.id, one.field);
101
+ const at = taken.get(field) ?? 0;
102
+ taken.set(field, at + 1);
103
+ const said = byField.get(field)?.[at];
104
+ if (!said || typeof said.after !== "string")
105
+ return one;
106
+ return { op: "patch-node", id: one.id, before: { [one.field]: typeof said.before === "string" ? said.before : UNSET }, after: { [one.field]: said.after } };
107
+ });
108
+ return { ...op, primitives };
109
+ });
28
110
  }
29
111
  /** The op format a request says it reads: `?opFormat=<n>` on its URL; nothing when it says none. */
30
112
  export function opFormatOf(url) {
31
113
  const said = Number((typeof url === "string" ? new URL(url, "http://graview.invalid") : url).searchParams.get("opFormat"));
32
114
  return Number.isInteger(said) && said > 0 ? said : undefined;
33
115
  }
34
- /** A live message as a socket of this op format reads it: its ops, and a welcome's log, bare or with their inverses. */
35
- function readableBy(opFormat, message) {
36
- if (opFormat !== undefined && opFormat >= 2)
116
+ /** A live message as a socket of this op format reads it: its ops, and a welcome's log, bare or with their inverses, and its splices whole before format 3. */
117
+ function readableBy(opFormat, message, store) {
118
+ if (opFormat !== undefined && opFormat >= 3)
37
119
  return message;
38
120
  if (message.t === "welcome") {
39
- const state = message.state ? { state: { ...message.state, log: opsFor(opFormat, message.state.log) } } : {};
40
- return { ...message, ops: opsFor(opFormat, message.ops), ...state };
121
+ const state = message.state ? { state: { ...message.state, log: opsFor(opFormat, message.state.log, store) } } : {};
122
+ return { ...message, ops: opsFor(opFormat, message.ops, store), ...state };
41
123
  }
42
124
  if (message.t === "ops" || message.t === "ack")
43
- return { ...message, ops: opsFor(opFormat, message.ops) };
125
+ return { ...message, ops: opsFor(opFormat, message.ops, store) };
44
126
  return message;
45
127
  }
46
128
  /** A client's claim of what its change came through: a short string, or none. */
@@ -79,13 +161,24 @@ const forWhom = (author) => author.onBehalfOf?.id ? { onBehalfOf: author.onBehal
79
161
  * given, the claimed key is not read at all.
80
162
  */
81
163
  export function presenceFrom(told, seat, now = new Date(), participant) {
82
- const { participant: claimed, kind: _kind, name: claimedName, onBehalfOf: _for, onBehalfOfName: _forName, until: _until, held: _held, at: _at, ...said } = told;
164
+ const { participant: claimed, kind: _kind, name: claimedName, onBehalfOf: _for, onBehalfOfName: _forName, until: _until, held: _held, at: _at, caret: claimedCaret, ...said } = told;
165
+ const caret = caretOf(claimedCaret);
83
166
  // The session is what follows the seat's own `kind:id:` — an id may hold a colon (`shopper:bethan`).
84
167
  const own = `${seat.kind}:${seat.id ?? ""}:`;
85
168
  const session = claimed.startsWith(own) ? claimed.slice(own.length) : (claimed.split(":").at(-1) ?? "");
86
169
  const key = participant ?? (seat.id ? participantKey({ kind: seat.kind, id: seat.id, session }) : claimed);
87
170
  const name = seat.name ?? claimedName;
88
- return { ...said, participant: key, kind: seat.kind, ...(name ? { name } : {}), ...forWhom(seat), at: now.toISOString() };
171
+ return { ...said, participant: key, kind: seat.kind, ...(name ? { name } : {}), ...forWhom(seat), ...(caret ? { caret } : {}), at: now.toISOString() };
172
+ }
173
+ /** A caret as a client said it (Roadmap f-collab-text), kept only when it is one: a record, a field, and three counts. */
174
+ function caretOf(said) {
175
+ if (typeof said !== "object" || said === null)
176
+ return undefined;
177
+ const { node, field, anchor, head, rev } = said;
178
+ const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
179
+ if (typeof node !== "string" || typeof field !== "string" || node.length > 512 || field.length > 512 || !count(anchor) || !count(head) || !count(rev))
180
+ return undefined;
181
+ return { node, field, anchor, head, rev };
89
182
  }
90
183
  /**
91
184
  * A VISITOR WITHOUT A SOCKET, as a host announces it (FR-47): an agent
@@ -147,7 +240,7 @@ const mintSession = () => globalThis.crypto.randomUUID().slice(0, 8);
147
240
  * where they stand or what they hover when that names a record the seat
148
241
  * may not see. A participant whose id is no record is shown as they are.
149
242
  */
150
- export function presenceSeenBy(who, sees) {
243
+ export function presenceSeenBy(who, sees, seesField) {
151
244
  const names = (value) => value.split(/[/?#=&,;]/).every((part) => part === "" || sees(decodeURIComponent(part)));
152
245
  return who
153
246
  .filter((presence) => {
@@ -157,7 +250,7 @@ export function presenceSeenBy(who, sees) {
157
250
  })
158
251
  .map((presence) => {
159
252
  // An agent is shown; for whom it acts is not, to a seat that may not see that person (FR-47).
160
- const { onBehalfOf, onBehalfOfName, ...rest } = presence;
253
+ const { onBehalfOf, onBehalfOfName, caret, ...rest } = presence;
161
254
  const forWhom = onBehalfOf !== undefined && sees(onBehalfOf) ? { onBehalfOf, ...(onBehalfOfName !== undefined ? { onBehalfOfName } : {}) } : {};
162
255
  return {
163
256
  ...rest,
@@ -165,6 +258,8 @@ export function presenceSeenBy(who, sees) {
165
258
  stop: names(presence.stop) ? presence.stop : "",
166
259
  ...(typeof presence.over === "string" && !sees(presence.over) ? { over: null } : {}),
167
260
  ...(presence.robot?.at && !sees(presence.robot.at) ? { robot: { ...presence.robot, at: null } } : {}),
261
+ // A caret in a field the seat may not see is not said at all: where somebody types says what is there (Roadmap f-collab-text).
262
+ ...(caret && sees(caret.node) && (seesField?.(caret.node, caret.field) ?? true) ? { caret } : {}),
168
263
  };
169
264
  });
170
265
  }
@@ -305,6 +400,41 @@ export function wireOf(store, withheldKey) {
305
400
  }
306
401
  return revisions;
307
402
  };
403
+ /*
404
+ * A KEYSTROKE TYPED AGAINST TEXT BEHIND THE HORIZON (Roadmap f-collab-text,
405
+ * phase 3): the log no longer holds what was typed between the text its
406
+ * sender read and now, so it cannot be carried over it. A conflict, not a
407
+ * refusal: the person keeps theirs, or puts the text they had over it
408
+ * whole. A compaction keeps the horizon behind every open socket
409
+ * (`floor`), so only a client that was away meets this.
410
+ */
411
+ const typedBehind = (author, calls) => {
412
+ const floor = store.log.horizon - 1;
413
+ const out = [];
414
+ for (const call of calls) {
415
+ if (call?.name !== TYPE_TEXT || !call.args)
416
+ continue;
417
+ const { node, field, rev } = call.args;
418
+ if (typeof node !== "string" || typeof field !== "string" || typeof rev !== "number" || rev >= floor)
419
+ continue;
420
+ const lens = sighted(author) ? seatLens(store, author) : undefined;
421
+ if (lens && (!lens.shows(node) || keptField(lens, node, field)))
422
+ continue;
423
+ const at = current().of(node, field);
424
+ const wrote = at >= store.log.horizon ? store.log.opsFrom(at)[0] : undefined;
425
+ const seen = wrote && lens ? redact([wrote], lens)[0] : wrote;
426
+ out.push({
427
+ node,
428
+ field,
429
+ theirs: (lens ? seenBy(store, author) : store).graph.getNode(node)?.[field],
430
+ yours: undefined,
431
+ by: seen?.author.name ?? seen?.author.id ?? "Someone",
432
+ rev: at,
433
+ saw: rev,
434
+ });
435
+ }
436
+ return out;
437
+ };
308
438
  // Where a seat is served through: the head in a live app, without judging its sight; what was published, for a reader of one that publishes.
309
439
  const servedTo = (principal) => (store.publishing?.mode === "on-publish" ? seenBy(store, principal).servedSeq : store.log.length);
310
440
  return {
@@ -332,7 +462,10 @@ export function wireOf(store, withheldKey) {
332
462
  // A visitor whose announced time has passed is never told of, though a host may still hold it.
333
463
  const now = Date.now();
334
464
  const standing = who.filter((presence) => presence.until === undefined || now < Date.parse(presence.until));
335
- return sighted(principal) ? presenceSeenBy(standing, seesId(store, principal)) : standing;
465
+ if (!sighted(principal))
466
+ return standing;
467
+ const lens = seatLens(store, principal);
468
+ return presenceSeenBy(standing, seesId(store, principal), (node, field) => !keptField(lens, node, field));
336
469
  },
337
470
  claim(batch, seat) {
338
471
  if (batch === undefined || batch === null || batch === "")
@@ -369,11 +502,22 @@ export function wireOf(store, withheldKey) {
369
502
  horizonOf: () => (store.log.horizon > 0 ? { horizon: store.log.horizon } : {}),
370
503
  enabledModules: () => [...store.modules.enabled].sort(),
371
504
  conflictsOf(author, calls, base, via) {
505
+ const behind = typedBehind(author, calls);
506
+ if (behind.length > 0)
507
+ return behind;
372
508
  if (!Array.isArray(base) || base.length === 0)
373
509
  return [];
374
510
  const lens = sighted(author) ? seatLens(store, author) : undefined;
375
- // A record the seat is not served is not there to have moved: the call itself is refused for naming it.
376
- const claimed = base.filter((entry) => entry && typeof entry.node === "string" && typeof entry.field === "string" && typeof entry.rev === "number" && (!lens || (lens.shows(entry.node) && !keptField(lens, entry.node, entry.field))));
511
+ /*
512
+ * A record the seat is not served is not there to have moved: the call itself is refused for naming it.
513
+ * A field typed together is never stale: a whole write over it is merged with what was typed since (`ApplyOptions.base`).
514
+ */
515
+ const claimed = base.filter((entry) => entry &&
516
+ typeof entry.node === "string" &&
517
+ typeof entry.field === "string" &&
518
+ typeof entry.rev === "number" &&
519
+ !store.collaborative(entry.node, entry.field) &&
520
+ (!lens || (lens.shows(entry.node) && !keptField(lens, entry.node, entry.field))));
377
521
  const revs = current();
378
522
  const stale = revs.stale(claimed);
379
523
  if (stale.length === 0)
@@ -418,7 +562,7 @@ export function wireOf(store, withheldKey) {
418
562
  },
419
563
  };
420
564
  }
421
- const say = (peer, message) => sayText(peer, JSON.stringify(readableBy(peer.opFormat, message)));
565
+ const sayTo = (peer, message, store) => sayText(peer, JSON.stringify(readableBy(peer.opFormat, message, store)));
422
566
  const sayText = (peer, text) => {
423
567
  try {
424
568
  peer.send(text);
@@ -446,7 +590,7 @@ const SEAT_LOST_CODE = 4000;
446
590
  /** The host lost this socket's seat: told to open again, closed when it can be, and served nothing more. */
447
591
  const lost = (peer) => {
448
592
  delete peer.cursor;
449
- say(peer, { t: "error", reopen: true, sentence: SEAT_LOST });
593
+ sayTo(peer, { t: "error", reopen: true, sentence: SEAT_LOST });
450
594
  try {
451
595
  peer.close?.(SEAT_LOST_CODE, "Seat no longer known: open it again.");
452
596
  }
@@ -461,6 +605,9 @@ const lost = (peer) => {
461
605
  export function liveProtocol(options) {
462
606
  const { store } = options;
463
607
  const wire = wireOf(store, options.withheldKey);
608
+ /** The store, as what a reader before op format 3 is sent is read from: each splice whole (`opsFor`). */
609
+ const served = store;
610
+ const say = (peer, message) => sayTo(peer, message, served);
464
611
  /**
465
612
  * The log an open carries for this seat (`openTail`): the latest ops and
466
613
  * the seq they begin at, or the whole log and the store's own horizon.
@@ -557,7 +704,7 @@ export function liveProtocol(options) {
557
704
  }
558
705
  // The ops handed in, when they are the whole of what this peer is missing; the log otherwise.
559
706
  const after = (ops && ops.length > 0 && ops[0].seq <= from && ops.at(-1).seq >= last ? ops.filter((op) => op.seq >= from) : store.log.opsFrom(from)).filter((op) => op.seq <= last);
560
- const text = after.length > 0 ? JSON.stringify({ t: "ops", seq: cursorAt(last), ops: opsFor(peer.opFormat, wire.shown(seat, after)) }) : "";
707
+ const text = after.length > 0 ? JSON.stringify({ t: "ops", seq: cursorAt(last), ops: opsFor(peer.opFormat, wire.shown(seat, after), served) }) : "";
561
708
  if (key !== undefined)
562
709
  sight.texts.set(key, text);
563
710
  if (text.length > 0)
@@ -635,7 +782,19 @@ export function liveProtocol(options) {
635
782
  throw new NotAdmitted(answer);
636
783
  }
637
784
  : undefined;
638
- const applying = { author: seat, via, ...(change.intent ? { intent: change.intent } : {}), batch, ...(admitting ? { admit: admitting } : {}), ...(change.lineage !== undefined ? { lineage: change.lineage } : {}) };
785
+ // What the caller read, so a whole write over a field typed together merges with what was typed since (Roadmap f-collab-text).
786
+ const base = Array.isArray(change.base)
787
+ ? change.base.filter((entry) => entry && typeof entry.node === "string" && typeof entry.field === "string" && typeof entry.rev === "number")
788
+ : [];
789
+ const applying = {
790
+ author: seat,
791
+ via,
792
+ ...(change.intent ? { intent: change.intent } : {}),
793
+ batch,
794
+ ...(admitting ? { admit: admitting } : {}),
795
+ ...(change.lineage !== undefined ? { lineage: change.lineage } : {}),
796
+ ...(base.length > 0 ? { base } : {}),
797
+ };
639
798
  result = change.t === "undo" ? store.undo(change.batches, applying) : store.applyAll(change.calls, applying);
640
799
  }
641
800
  catch (error) {
@@ -821,7 +980,8 @@ export function liveProtocol(options) {
821
980
  delete peer.opFormat;
822
981
  const asked = seqAt(message.seq);
823
982
  // Behind the horizon, or past where the seat is served: the whole state, never a skip (`behind`).
824
- const seq = asked !== undefined && asked >= 0 && wire.behind(seat, asked) ? undefined : asked;
983
+ // A page that read nothing (-1) is behind a horizon past 0 as any other is: what it never read is not in the log to send.
984
+ const seq = asked !== undefined && wire.behind(seat, asked) ? undefined : asked;
825
985
  peer.cursor = wire.servedSeq(seat) - 1;
826
986
  // Its own key, built from the seat, so the client can leave itself out of who is here (FR-47).
827
987
  peer.participant ??= participantKey({ kind: seat.kind, ...(seat.id ? { id: seat.id } : {}), session: mintSession() });
@@ -1017,9 +1177,9 @@ export function liveProtocol(options) {
1017
1177
  const flushed = await durable([]);
1018
1178
  if (!("saved" in flushed))
1019
1179
  return reply(503, { error: UNSAVED, refused: true, reason: "unavailable", ...said });
1020
- return { ...reply(200, { ops: opsFor(reads, wire.shown(asked.seat, claim.answered)), batch: change.batch, ...said }), landed: flushed.saved };
1180
+ return { ...reply(200, { ops: opsFor(reads, wire.shown(asked.seat, claim.answered), served), batch: change.batch, ...said }), landed: flushed.saved };
1021
1181
  }
1022
- return reply(200, { ops: opsFor(reads, wire.shown(asked.seat, claim.answered)), batch: change.batch, ...said });
1182
+ return reply(200, { ops: opsFor(reads, wire.shown(asked.seat, claim.answered), served), batch: change.batch, ...said });
1023
1183
  }
1024
1184
  /*
1025
1185
  * THE HOST'S LIMITS, BEFORE ANYTHING IS JUDGED. Busy is 429 and the
@@ -1050,7 +1210,7 @@ export function liveProtocol(options) {
1050
1210
  if (!landing.saved)
1051
1211
  return reply(503, { error: UNSAVED, refused: true, reason: "unavailable", ...said });
1052
1212
  // An act may make what its own seat may not see: that op goes back withheld, as it would on a poll.
1053
- return { ...reply(200, { ops: opsFor(reads, wire.shown(asked.seat, landing.result.ops)), batch: landing.result.batch, ...said }), landed: landing.saved };
1213
+ return { ...reply(200, { ops: opsFor(reads, wire.shown(asked.seat, landing.result.ops), served), batch: landing.result.batch, ...said }), landed: landing.saved };
1054
1214
  },
1055
1215
  state(asked) {
1056
1216
  const seen = wire.seenFor(asked.seat);
@@ -1059,7 +1219,7 @@ export function liveProtocol(options) {
1059
1219
  ...answering(asked),
1060
1220
  snapshot: seen.snapshot(),
1061
1221
  ...opened,
1062
- log: opsFor(asked.opFormat, opened.log),
1222
+ log: opsFor(asked.opFormat, opened.log, served),
1063
1223
  cursor: cursorAt(opened.log.at(-1)?.seq ?? (opened.horizon ?? 0) - 1),
1064
1224
  ...wire.servedOf(asked.seat),
1065
1225
  migrated: [...(options.migrated ?? [])],
@@ -1072,8 +1232,8 @@ export function liveProtocol(options) {
1072
1232
  // A client the ops cannot catch up — behind the horizon, or past where it is now served — is told to take the state.
1073
1233
  // (The ops after the horizon still come, so a client that predates `reset` sees the gap and takes the state as it did.)
1074
1234
  if (wire.behind(asked.seat, seq))
1075
- return reply(200, { ops: opsFor(asked.opFormat, ops), cursor, reset: true, ...wire.horizonOf(), ...wire.servedOf(asked.seat), ...answering(asked) });
1076
- return reply(200, { ops: opsFor(asked.opFormat, ops), cursor, ...wire.servedOf(asked.seat), ...answering(asked) });
1235
+ return reply(200, { ops: opsFor(asked.opFormat, ops, served), cursor, reset: true, ...wire.horizonOf(), ...wire.servedOf(asked.seat), ...answering(asked) });
1236
+ return reply(200, { ops: opsFor(asked.opFormat, ops, served), cursor, ...wire.servedOf(asked.seat), ...answering(asked) });
1077
1237
  },
1078
1238
  declared(peers) {
1079
1239
  for (const peer of peers) {
@@ -1090,6 +1250,13 @@ export function liveProtocol(options) {
1090
1250
  if (peer.cursor !== undefined)
1091
1251
  sayText(peer, text);
1092
1252
  },
1253
+ floor(peers) {
1254
+ let lowest;
1255
+ for (const peer of peers)
1256
+ if (peer.cursor !== undefined && (lowest === undefined || peer.cursor < lowest))
1257
+ lowest = peer.cursor;
1258
+ return lowest === undefined ? undefined : lowest + 1;
1259
+ },
1093
1260
  };
1094
1261
  }
1095
1262
  /** Whether a field of a record is one the seat's sight keeps from it (Roadmap f-field-sight): when it was last written is not the seat's to learn either. */