Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/src/engine/graph.ts?version=124&format=json
1,254 linesFirst import 86% · codex-capacity-chair 14%Last change codex-capacity-chair in version 122, 7 versions changed it

You're reading version 124. The newest is 318, and 28 versions since then changed this file. Go to the newestCompare with 318

1// The graph: every atom ever accepted, plus labels. Sets of atoms (states of
2// the codebase) are separate values; the graph only answers questions about
3// atoms and keeps indexes so those questions are cheap.
4
5import {
6 atomId,
7 attrKey,
8 gapKey,
9 isAtomId,
10 isStartNode,
11 lineId,
12 lineKey,
13 parseKey,
14 posKey,
15 seqOf,
16 startNode,
17} from "./keys.ts";
18import {
19 type GraphStateStorage,
20 type StateMap,
21 storedArray,
22 storedLists,
23 storedMap,
24 storedNumbers,
25} from "./state-source.ts";
26import {
27 ATTR_NAMES,
28 type Atom,
29 type AtomId,
30 EngineError,
31 type InsertRun,
32 type Key,
33 type Label,
34 type LineId,
35 type NodeId,
36 REASON_KINDS,
37 type Reason,
38} from "./types.ts";
40/**
41 * Where a line was written and what it says. Its text never changes. A move
42 * can give it another parent in a set, even in another file: `view.parentOf`
43 * and `view.fileOf` say where it is in a set.
44 */
45export interface LineInfo {
46 readonly id: LineId;
47 readonly atom: AtomId;
48 readonly k: number;
49 /** The file it was written in. */
50 readonly file: string;
51 /** The node it was written after. */
52 readonly parent: NodeId;
53 readonly text: string;
56/** One relocation of a line, by the atom that made it; `k` is its place in that atom's moves. */
57export interface RelocationInfo {
58 readonly atom: AtomId;
59 readonly line: LineId;
60 readonly parent: NodeId;
61 readonly k: number;
64/** A `together` reason seen from one end: `other` is the atom at the far end. */
65export interface TogetherLink {
66 readonly other: AtomId;
67 readonly text: string;
68 /** The atom that carries the reason. */
69 readonly from: AtomId;
72export const GRAPH_FORMAT = "ai-first-vcs.graph";
74/** The saved form of a graph. Atoms are in seq order. */
75export interface GraphJSON {
76 readonly format: typeof GRAPH_FORMAT;
77 readonly version: 1;
78 readonly atoms: readonly Atom[];
79 readonly labels: readonly Label[];
82/**
83 * An index entry that holds a lone value as itself, and a list only once there
84 * are two (#46): most keys name one atom, and a list for each costs more than
85 * the value.
86 */
87function pushOne<K, V>(map: StateMap<K, V | V[]>, key: K, value: V): void {
88 const had = map.get(key);
89 if (had === undefined) map.set(key, value);
90 else if (Array.isArray(had)) {
91 had.push(value);
92 map.set(key, had);
93 } else map.set(key, [had, value]);
96function listOf<V>(had: V | V[] | undefined): readonly V[] {
97 return had === undefined ? EMPTY : Array.isArray(had) ? had : [had];
100function pushIndex<K, V>(map: StateMap<K, V[]>, key: K, value: V): void {
101 const list = map.get(key);
102 if (list) {
103 list.push(value);
104 map.set(key, list);
105 } else map.set(key, [value]);
108const EMPTY: readonly never[] = Object.freeze([]);
110/**
111 * A run whose lines are read when asked for (#46, text on disk): a few fields
112 * and a shared reader, where an object with its own accessor cost about 400
113 * bytes a run.
114 */
115class LazyRun implements InsertRun {
116 readonly file: string;
117 readonly parent: NodeId;
118 readonly #text: (start: number, length: number) => readonly string[];
119 readonly #start: number;
120 readonly #length: number;
121 constructor(
122 file: string,
123 parent: NodeId,
124 text: (start: number, length: number) => readonly string[],
125 start: number,
126 length: number,
127 ) {
128 this.file = file;
129 this.parent = parent;
130 this.#text = text;
131 this.#start = start;
132 this.#length = length;
133 }
134 get lines(): readonly string[] {
135 return this.#text(this.#start, this.#length);
136 }
137 toJSON(): InsertRun {
138 return { file: this.file, parent: this.parent, lines: this.lines };
139 }
142/** Characters of atoms' text a graph that keeps text elsewhere holds at most (#46): about 8 MB. */
143const TEXT_CACHE = 4_000_000;
144/** How many list items (deletes and keys) are kept read back (#46): publishes and syncs meet few atoms, but one reformat's atom can hold 100,000. */
145const LIST_CACHE = 50_000;
147/** An atom's deletes and claim keys: kept in the log rather than in memory when the graph has a `lists` reader (#46). */
148export interface AtomLists {
149 readonly deletes: readonly LineId[];
150 readonly writes: readonly Key[];
151 readonly reads: readonly Key[];
152 readonly holds: readonly Key[];
155function listItems(l: AtomLists): number {
156 return l.deletes.length + l.writes.length + l.reads.length + l.holds.length;
159function frozenList<T>(xs: readonly T[]): readonly T[] {
160 return xs.length === 0 ? (EMPTY as readonly T[]) : Object.freeze([...xs]);
163/**
164 * An atom whose deletes, writes, reads and holds are read back through `read` (#46). The getters live on the
165 * prototype, so each atom keeps one reader and a fixed shape, not four closures in a dictionary-mode object.
166 */
167class ListedAtom {
168 readonly #read: () => AtomLists;
169 constructor(fields: object, read: () => AtomLists) {
170 Object.assign(this, fields);
171 this.#read = read;
172 }
173 get deletes(): readonly LineId[] {
174 return this.#read().deletes;
175 }
176 get writes(): readonly Key[] {
177 return this.#read().writes;
178 }
179 get reads(): readonly Key[] {
180 return this.#read().reads;
181 }
182 get holds(): readonly Key[] {
183 return this.#read().holds;
184 }
185 toJSON(): object {
186 return { ...this, ...this.#read() };
187 }
190/** A growable array of 32-bit integers: a line's fields cost 4 bytes each, not an object and its strings (#46). */
191interface NumberIndex {
192 readonly length: number;
193 push(n: number): void;
194 at(i: number): number;
195 set(i: number, n: number): void;
198class Ints implements NumberIndex {
199 #buf: Int32Array | Uint8Array;
200 /** bytes: values 0-255 only, one byte each. */
201 constructor(bytes = false) {
202 this.#buf = bytes ? new Uint8Array(1024) : new Int32Array(1024);
203 }
204 length = 0;
205 push(n: number): void {
206 if (this.length === this.#buf.length) {
207 const bigger =
208 this.#buf instanceof Uint8Array ? new Uint8Array(this.#buf.length * 2) : new Int32Array(this.#buf.length * 2);
209 bigger.set(this.#buf);
210 this.#buf = bigger;
211 }
212 this.#buf[this.length++] = n;
213 }
214 at(i: number): number {
215 return this.#buf[i]!;
216 }
217 set(i: number, n: number): void {
218 this.#buf[i] = n;
219 }
222/**
223 * A line id's place in the graph's line arrays, or -1: "a<seq>.<k>" is line
224 * `base[seq] + k`. Hand-parsed, as seqOf is, with the same rules: no leading
225 * zeros, and k within the lines its atom wrote.
226 */
227function parseLineId(id: string): { seq: number; k: number } | undefined {
228 if (typeof id !== "string") return undefined;
229 const n = id.length;
230 if (n < 4 || id.charCodeAt(0) !== 97 /* a */) return undefined;
231 let i = 1;
232 let seq = 0;
233 const seqStart = i;
234 for (; i < n; i++) {
235 const c = id.charCodeAt(i);
236 if (c === 46 /* . */) break;
237 if (c < 48 || c > 57) return undefined;
238 seq = seq * 10 + (c - 48);
239 }
240 if (i === seqStart || i >= n - 1 || i - seqStart > 15 || (i - seqStart > 1 && id.charCodeAt(seqStart) === 48))
241 return undefined;
242 const kStart = ++i;
243 let k = 0;
244 for (; i < n; i++) {
245 const c = id.charCodeAt(i);
246 if (c < 48 || c > 57) return undefined;
247 k = k * 10 + (c - 48);
248 }
249 if (i - kStart > 15 || (i - kStart > 1 && id.charCodeAt(kStart) === 48)) return undefined;
250 return { seq, k };
253export class Graph {
254 readonly #storage?: GraphStateStorage;
255 #atoms: Atom[] = [];
256 #lamport: number[] = [];
257 // Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its
258 // atom's seq, the file it was written in (an index into #paths) and its parent (a line's n, or -1 - a
259 // path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only
260 // when asked for, so a line costs about 16 bytes here instead of a record, its id and its parent's id.
261 #lineBase: number[] = [];
262 #lineAtom: NumberIndex = new Ints();
263 #lineFile: NumberIndex = new Ints();
264 #lineParent: NumberIndex = new Ints();
265 /** Lines' text, when the graph keeps it; without it, it comes from `texts` (#46, text on disk). */
266 #lineText: string[] | undefined = [];
267 get #lineTotal(): number {
268 return this.#lineAtom.length;
269 }
270 /** Where an atom's lines' text is when the graph doesn't keep it: each run's lines, by the atom's seq. */
271 #texts: ((seq: number) => readonly (readonly string[])[]) | undefined;
272 /** Recently read atoms' text, flattened, most recent last, up to TEXT_CACHE characters. */
273 #textCache = new Map<number, readonly string[]>();
274 #textCached = 0;
276 /**
277 * `texts`, when given, says where each atom's lines' text can be read back
278 * (#46): the graph then keeps no text, only each line's place, and reads an
279 * atom's text when a line of it is asked for, keeping the most recent.
280 */
281 constructor(
282 options: {
283 texts?: (seq: number) => readonly (readonly string[])[];
284 lists?: (seq: number) => AtomLists;
285 storage?: GraphStateStorage;
286 } = {},
287 ) {
288 if (options.texts) {
289 this.#texts = options.texts;
290 this.#lineText = undefined;
291 }
292 if (options.lists) this.#lists = options.lists;
293 this.#storage = options.storage;
294 if (options.storage) {
295 const storage = options.storage;
296 const numbers = (name: string): NumberIndex => storedNumbers(storage, name);
297 this.#atoms = storedArray<Atom>(storage, "atoms", (atom) =>
298 freezeAtom(
299 atom,
300 (id) => id,
301 (author) => author,
302 ),
303 );
304 this.#lamport = storedArray(storage, "lamport");
305 this.#lineBase = storedArray(storage, "line-base");
306 this.#paths = storedArray(storage, "paths");
307 this.#movers = storedArray(storage, "movers");
308 this.#atomFiles = storedArray(storage, "atom-files");
309 this.#atomDeletes = storedArray(storage, "atom-deletes");
310 this.#lineAtom = numbers("line-atom");
311 this.#lineFile = numbers("line-file");
312 this.#lineParent = numbers("line-parent");
313 this.#deleter = numbers("deleter");
314 this.#replacing = numbers("replacing");
315 this.#lineText = storedArray(storage, "line-text");
316 this.#pathIndex = storedMap(storage, "path-index");
317 this.#moreDeleters = storedMap(storage, "more-deleters");
318 this.#writersPages = storedLists<AtomId>(storage, "writers", (key) => key);
319 this.#readersPages = storedLists<AtomId>(storage, "readers", (key) => key);
320 this.#holdersPages = storedLists<AtomId>(storage, "holders", (key) => key);
321 this.#dependentsPages = storedLists<AtomId>(storage, "dependents");
322 this.#resolversPages = storedLists<AtomId>(storage, "resolvers");
323 this.#together = storedMap(storage, "together");
324 this.#fileAtomPages = storedLists<AtomId>(storage, "file-atoms");
325 this.#runStarts = storedMap(storage, "run-starts");
326 this.#relocations = storedMap(storage, "relocations");
327 this.#relocatedTo = storedMap(storage, "relocated-to");
328 this.#relocatedToCode = storedMap(storage, "relocated-to-code");
329 this.#labels = storedMap(storage, "labels");
330 }
331 }
333 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
334 #lists: ((seq: number) => AtomLists) | undefined;
335 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */
336 #listCache = new Map<number, AtomLists>();
337 #listCached = 0;
339 /** An atom's deletes, writes, reads and holds, read back from where they are stored. */
340 #listsOf(seq: number): AtomLists {
341 const hit = this.#listCache.get(seq);
342 if (hit) {
343 this.#listCache.delete(seq);
344 this.#listCache.set(seq, hit);
345 return hit;
346 }
347 const got = this.#lists!(seq);
348 const lists: AtomLists = {
349 deletes: frozenList(got.deletes),
350 writes: frozenList(got.writes),
351 reads: frozenList(got.reads),
352 holds: frozenList(got.holds),
353 };
354 this.#listCache.set(seq, lists);
355 this.#listCached += listItems(lists);
356 for (const [old, kept] of this.#listCache) {
357 if (this.#listCached <= LIST_CACHE || old === seq) break;
358 this.#listCache.delete(old);
359 this.#listCached -= listItems(kept);
360 }
361 return lists;
362 }
364 /** The reader an atom's lists use; made apart from add() so it keeps no atom alive (see #reader). */
365 #listReader(seq: number): () => AtomLists {
366 return () => this.#listsOf(seq);
367 }
369 /**
370 * A claim key as the index keeps it (#46): a line's L:, P: and G: keys by its n (n * 4, + 1, + 2), so the
371 * index holds numbers rather than one string per line; start-node and attribute keys stay strings. A key
372 * naming a line the graph doesn't have stays a string, which nothing has claimed.
373 */
374 #code(key: Key): Key | number {
375 const t = key.charCodeAt(0);
376 if (key.charCodeAt(1) !== 58 || key.charCodeAt(2) === 94) return key; // not "X:", or a start node "^"
377 const k = t === 76 ? 0 : t === 80 ? 1 : t === 71 ? 2 : -1; // L, P, G
378 if (k < 0) return key;
379 const n = this.#lineN(key.slice(2));
380 return n < 0 ? key : n * 4 + k;
381 }
383 /** An atom's lines' text, in k order. */
384 #textOf(seq: number): readonly string[] {
385 const hit = this.#textCache.get(seq);
386 if (hit) {
387 this.#textCache.delete(seq);
388 this.#textCache.set(seq, hit);
389 return hit;
390 }
391 const flat = this.#texts!(seq).flat();
392 let chars = 0;
393 for (const t of flat) chars += t.length + 1;
394 this.#textCache.set(seq, flat);
395 this.#textCached += chars;
396 for (const [old, lines] of this.#textCache) {
397 if (this.#textCached <= TEXT_CACHE || old === seq) break;
398 this.#textCache.delete(old);
399 for (const t of lines) this.#textCached -= t.length + 1;
400 }
401 return flat;
402 }
404 /**
405 * The reader an atom's runs use. Made in a function of its own: a closure made inside add() would
406 * keep add()'s whole scope alive, the atom as given with all its text included.
407 */
408 #reader(seq: number): (start: number, length: number) => readonly string[] {
409 return (start, length) => this.#textOf(seq).slice(start, start + length);
410 }
412 /** Line n's text. */
413 #text(n: number): string {
414 if (this.#lineText) return this.#lineText[n]!;
415 const seq = this.#lineAtom.at(n);
416 return this.#textOf(seq)[n - this.#lineBase[seq]!]!;
417 }
418 #paths: string[] = [];
419 #pathIndex: StateMap<string, number> = new Map();
420 /** The first atom that deletes each line (its seq), or -1; a line deleted by more than one has the rest in #moreDeleters. */
421 #deleter: NumberIndex = new Ints();
422 #moreDeleters: StateMap<number, number[]> = new Map();
423 #writers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
424 #writersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
425 #readers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
426 #readersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
427 #holders: StateMap<Key | number, AtomId | AtomId[]> = new Map();
428 #holdersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
429 #dependents: StateMap<AtomId, AtomId | AtomId[]> = new Map();
430 #dependentsPages: ReturnType<typeof storedLists<AtomId>> | undefined;
431 #resolvers: StateMap<AtomId, AtomId | AtomId[]> = new Map();
432 #resolversPages: ReturnType<typeof storedLists<AtomId>> | undefined;
433 #together: StateMap<AtomId, TogetherLink[]> = new Map();
434 #fileAtoms: StateMap<string, AtomId[]> = new Map();
435 #fileAtomPages: ReturnType<typeof storedLists<AtomId>> | undefined;
436 /** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */
437 #runStarts: StateMap<number, number | number[]> = new Map();
438 /** 1 for the first line of a run whose atom deleted the line it hangs off: the run replaces it. */
439 #replacing: NumberIndex = new Ints(true);
440 #relocations: StateMap<LineId, RelocationInfo[]> = new Map();
441 #relocatedTo: StateMap<NodeId, RelocationInfo[]> = new Map();
442 /** The same relocations by node code (a line's n, or -1 - a path's index), for views laid out by number. */
443 #relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();
444 #movers: AtomId[] = [];
445 #atomFiles: (readonly string[])[] = [];
446 /** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */
447 #atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];
448 #labels: StateMap<string, Label> = new Map();
449 /** Each author's name kept once (#46). */
450 #authors = new Map<string, string>();
452 /** Number of atoms (also the seq the next atom gets). */
453 get size(): number {
454 return this.#atoms.length;
455 }
457 /** The id the next accepted atom must have. */
458 nextId(): AtomId {
459 return atomId(this.#atoms.length);
460 }
462 has(id: AtomId): boolean {
463 const seq = this.#seq(id);
464 return seq >= 0 && seq < this.#atoms.length;
465 }
467 atom(id: AtomId): Atom {
468 const seq = this.#seq(id);
469 const atom = seq >= 0 ? this.#atoms[seq] : undefined;
470 if (!atom) throw new EngineError("unknown-atom", `no atom ${id}`);
471 return atom;
472 }
474 /** All atoms in seq order. */
475 atoms(): readonly Atom[] {
476 return this.#atoms;
477 }
479 /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */
480 lamport(id: AtomId): number {
481 this.atom(id);
482 return this.#lamport[this.#seq(id)]!;
483 }
485 /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */
486 comparePriority(a: AtomId, b: AtomId): number {
487 return this.lamport(a) - this.lamport(b) || this.#seq(a) - this.#seq(b);
488 }
490 line(id: LineId): LineInfo | undefined {
491 const n = this.#lineN(id);
492 if (n < 0) return undefined;
493 const seq = this.#lineAtom.at(n);
494 return {
495 id,
496 atom: this.#atoms[seq]!.id,
497 k: n - this.#lineBase[seq]!,
498 file: this.#paths[this.#lineFile.at(n)]!,
499 parent: this.#nodeName(this.#lineParent.at(n)),
500 text: this.#text(n),
501 };
502 }
504 /** A line's text, or undefined for an unknown line: line(id).text without making the record. */
505 lineText(id: LineId): string | undefined {
506 const n = this.#lineN(id);
507 return n < 0 ? undefined : this.#text(n);
508 }
510 /** The atom that wrote a line, or undefined: line(id).atom without making the record. */
511 lineAtom(id: LineId): AtomId | undefined {
512 const n = this.#lineN(id);
513 return n < 0 ? undefined : this.#atoms[this.#lineAtom.at(n)]!.id;
514 }
516 /** The file a line was written in, or undefined: line(id).file without making the record. */
517 lineFile(id: LineId): string | undefined {
518 const n = this.#lineN(id);
519 return n < 0 ? undefined : this.#paths[this.#lineFile.at(n)];
520 }
522 /** The node a line was written after, or undefined: line(id).parent without making the record. */
523 lineParent(id: LineId): NodeId | undefined {
524 const n = this.#lineN(id);
525 return n < 0 ? undefined : this.#nodeName(this.#lineParent.at(n));
526 }
528 // By number, for views (#46) ------------------------------------------------------
529 // A line's n and a node's code (a line's n, or -1 - a path's index for a file's start) as the graph
530 // keeps them, so a view can lay files out as arrays of numbers. For the engine's own use.
532 /** A line id's n, or -1 for an unknown line. */
533 lineN(id: LineId): number {
534 return this.#lineN(id);
535 }
537 /** A line's id from its n. */
538 lineIdOf(n: number): LineId {
539 return this.#lineName(n);
540 }
542 /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */
543 deletedLines(id: AtomId): readonly LineId[] {
544 const ns = this.#atomDeletes[this.#seq(id)];
545 if (!ns) return EMPTY;
546 const out: LineId[] = new Array(ns.length);
547 for (let i = 0; i < ns.length; i++) out[i] = this.#lineName(ns[i]!);
548 return out;
549 }
551 /** How many lines an atom deletes, without reading its lists. */
552 deleteCount(id: AtomId): number {
553 return this.#atomDeletes[this.#seq(id)]?.length ?? 0;
554 }
556 textOf(n: number): string {
557 return this.#text(n);
558 }
560 /** The seq of the atom that wrote line n. */
561 writerSeqOf(n: number): number {
562 return this.#lineAtom.at(n);
563 }
565 /** Line n's k: its place among its atom's lines. */
566 kOf(n: number): number {
567 return n - this.#lineBase[this.#lineAtom.at(n)]!;
568 }
570 /** The atom id with this seq, as the graph keeps it. */
571 idOfSeq(seq: number): AtomId {
572 return this.#atoms[seq]!.id;
573 }
575 lamportOfSeq(seq: number): number {
576 return this.#lamport[seq]!;
577 }
579 /** The file line n was written in. */
580 writtenIn(n: number): string {
581 return this.#paths[this.#lineFile.at(n)]!;
582 }
584 /** The code of the node line n was written after. */
585 parentCodeOf(n: number): number {
586 return this.#lineParent.at(n);
587 }
589 /** A node's code, or undefined for a node the graph doesn't know (a start node of a file nothing was written in). */
590 codeOf(node: NodeId): number | undefined {
591 return this.#nodeCode(node);
592 }
594 /** The node a code names. */
595 nodeOf(code: number): NodeId {
596 return this.#nodeName(code);
597 }
599 /** The start node's code for a path, or undefined when nothing was ever written in it. */
600 startCodeOf(path: string): number | undefined {
601 const p = this.#pathIndex.get(path);
602 return p === undefined ? undefined : -1 - p;
603 }
605 /** The lines (their n) written right after a node, as childrenOf, into `out`. */
606 childrenN(code: number, out: number[]): void {
607 if (
608 code >= 0 &&
609 code + 1 < this.#lineTotal &&
610 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
611 this.#lineParent.at(code + 1) === code
612 )
613 out.push(code + 1);
614 const starts = this.#runStarts.get(code);
615 if (starts === undefined) return;
616 if (Array.isArray(starts)) out.push(...starts);
617 else out.push(starts);
618 }
620 replacesN(n: number): boolean {
621 return this.#replacing.at(n) === 1;
622 }
624 /** The seqs of every atom that deletes line n (none: an empty list, shared). */
625 deleterSeqsOf(n: number): readonly number[] {
626 const first = this.#deleter.at(n);
627 if (first < 0) return EMPTY;
628 const more = this.#moreDeleters.get(n);
629 return more ? [first, ...more] : [first];
630 }
632 /** Every relocation that puts a line right after the node with this code. */
633 relocatedToCode(code: number): readonly RelocationInfo[] {
634 return this.#relocatedToCode.get(code) ?? EMPTY;
635 }
637 /** How many lines every atom together has written. */
638 get lineCount(): number {
639 return this.#lineTotal;
640 }
642 /** A line id's n, or -1 when no accepted atom wrote it. */
643 #lineN(id: LineId): number {
644 const p = parseLineId(id);
645 if (!p || p.seq >= this.#atoms.length) return -1;
646 const base = this.#lineBase[p.seq]!;
647 const end = p.seq + 1 < this.#lineBase.length ? this.#lineBase[p.seq + 1]! : this.#lineTotal;
648 return p.k < end - base ? base + p.k : -1;
649 }
651 /** A line's id from its n. */
652 #lineName(n: number): LineId {
653 const seq = this.#lineAtom.at(n);
654 return `${this.#atoms[seq]!.id}.${n - this.#lineBase[seq]!}`;
655 }
657 /** A node's code: a line's n, or -1 - a path's index for a start node; undefined when unknown. */
658 #nodeCode(node: NodeId): number | undefined {
659 if (isStartNode(node)) {
660 const p = this.#pathIndex.get(node.slice(1));
661 return p === undefined ? undefined : -1 - p;
662 }
663 const n = this.#lineN(node);
664 return n < 0 ? undefined : n;
665 }
667 #nodeName(code: number): NodeId {
668 return code >= 0 ? this.#lineName(code) : startNode(this.#paths[-1 - code]!);
669 }
671 #pathOf(file: string): number {
672 let p = this.#pathIndex.get(file);
673 if (p === undefined) {
674 p = this.#paths.push(file) - 1;
675 this.#pathIndex.set(file, p);
676 }
677 return p;
678 }
680 /** The line ids an atom inserted, in k order. */
681 linesOf(id: AtomId): LineId[] {
682 const atom = this.atom(id);
683 const out: LineId[] = [];
684 const seq = atom.seq;
685 const count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!;
686 for (let k = 0; k < count; k++) out.push(lineId(id, k));
687 return out;
688 }
690 /** Every atom that deletes this line (across the whole graph). */
691 deletersOf(line: LineId): readonly AtomId[] {
692 const n = this.#lineN(line);
693 if (n < 0) return EMPTY;
694 const first = this.#deleter.at(n);
695 if (first < 0) return EMPTY;
696 const more = this.#moreDeleters.get(n);
697 const out = [this.#atoms[first]!.id];
698 if (more) for (const seq of more) out.push(this.#atoms[seq]!.id);
699 return out;
700 }
702 writersOf(key: Key): readonly AtomId[] {
703 return [...this.eachWriterOf(key)];
704 }
705 *eachWriterOf(key: Key): IterableIterator<AtomId> {
706 const code = this.#code(key);
707 if (this.#writersPages) yield* this.#writersPages.values(JSON.stringify([typeof code, code]));
708 else yield* listOf(this.#writers.get(code));
709 }
711 /** Atoms whose implicit reads include the key. */
712 readersOf(key: Key): readonly AtomId[] {
713 return [...this.eachReaderOf(key)];
714 }
715 *eachReaderOf(key: Key): IterableIterator<AtomId> {
716 const code = this.#code(key);
717 if (this.#readersPages) yield* this.#readersPages.values(JSON.stringify([typeof code, code]));
718 else yield* listOf(this.#readers.get(code));
719 }
721 /** Atoms whose explicit holds include the key. */
722 holdersOf(key: Key): readonly AtomId[] {
723 return [...this.eachHolderOf(key)];
724 }
725 *eachHolderOf(key: Key): IterableIterator<AtomId> {
726 const code = this.#code(key);
727 if (this.#holdersPages) yield* this.#holdersPages.values(JSON.stringify([typeof code, code]));
728 else yield* listOf(this.#holders.get(code));
729 }
731 /** Every atom that inserts or deletes a line of the file, in seq order. */
732 atomsIn(file: string): readonly AtomId[] {
733 if (this.#fileAtomPages) return [...this.#fileAtomPages.values(file)];
734 return this.#fileAtoms.get(file) ?? EMPTY;
735 }
736 *eachAtomIn(file: string): IterableIterator<AtomId> {
737 if (this.#fileAtomPages) yield* this.#fileAtomPages.values(file);
738 else yield* this.#fileAtoms.get(file) ?? EMPTY;
739 }
740 hasAtomsIn(file: string): boolean {
741 return this.#fileAtomPages ? this.#fileAtomPages.length(file) > 0 : this.#fileAtoms.has(file);
742 }
744 /** Unique historical file paths, streamed without collecting their names. */
745 *knownFiles(): IterableIterator<string> {
746 yield* this.#fileAtomPages ? this.#fileAtomPages.keys() : this.#fileAtoms.keys();
747 }
749 /**
750 * The files an atom inserts, deletes or moves lines in, or sets attributes
751 * of, sorted. For lines, the file each was written in (or, for a move to a
752 * start node, that file): a set's moves can have taken them elsewhere.
753 */
754 filesOf(id: AtomId): readonly string[] {
755 this.atom(id);
756 return this.#atomFiles[this.#seq(id)]!;
757 }
759 /** Lines written right after a node (not counting moves), in seq order. */
760 childrenOf(node: NodeId): LineId[] {
761 const out: LineId[] = [];
762 const code = this.#nodeCode(node);
763 if (code === undefined) return out;
764 // The next line of the same run hangs off this one.
765 if (
766 code >= 0 &&
767 code + 1 < this.#lineTotal &&
768 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
769 this.#lineParent.at(code + 1) === code
770 ) {
771 out.push(this.#lineName(code + 1));
772 }
773 for (const n of listOf(this.#runStarts.get(code))) out.push(this.#lineName(n));
774 return out;
775 }
777 /** Whether a line starts a run whose atom deleted the line it hangs off. */
778 replaces(line: LineId): boolean {
779 const n = this.#lineN(line);
780 return n >= 0 && this.#replacing.at(n) === 1;
781 }
783 /** Every relocation of a line, in seq order. */
784 relocationsOf(line: LineId): readonly RelocationInfo[] {
785 return this.#relocations.get(line) ?? EMPTY;
786 }
788 /** Every relocation that puts a line right after this node, in seq order. */
789 relocatedTo(node: NodeId): readonly RelocationInfo[] {
790 return this.#relocatedTo.get(node) ?? EMPTY;
791 }
793 /** Atoms that move lines, in seq order. */
794 movers(): readonly AtomId[] {
795 return this.#movers;
796 }
798 /** Atoms that list this one directly in their deps. */
799 dependentsOf(id: AtomId): readonly AtomId[] {
800 return [...this.eachDependentOf(id)];
801 }
802 *eachDependentOf(id: AtomId): IterableIterator<AtomId> {
803 if (this.#dependentsPages) yield* this.#dependentsPages.values(id);
804 else yield* listOf(this.#dependents.get(id));
805 }
807 /** Atoms whose `resolves` names this one. */
808 resolversOf(id: AtomId): readonly AtomId[] {
809 return [...this.eachResolverOf(id)];
810 }
811 *eachResolverOf(id: AtomId): IterableIterator<AtomId> {
812 if (this.#resolversPages) yield* this.#resolversPages.values(id);
813 else yield* listOf(this.#resolvers.get(id));
814 }
816 /** `together` reasons touching this atom, in either direction. */
817 togetherLinks(id: AtomId): readonly TogetherLink[] {
818 return this.#together.get(id) ?? EMPTY;
819 }
821 /**
822 * The atom plus everything it depends on, transitively. Computed on demand
823 * and not cached: a cached set per atom costs memory quadratic in the length
824 * of a dependency chain. Use `dependsOn` to ask about one pair.
825 */
826 closure(id: AtomId): Set<AtomId> {
827 return this.closureOf([id]);
828 }
830 /** The atoms plus everything they depend on, transitively. */
831 closureOf(ids: Iterable<AtomId>): Set<AtomId> {
832 const out = new Set<AtomId>();
833 const stack: AtomId[] = [];
834 for (const id of ids) {
835 this.atom(id);
836 if (!out.has(id)) {
837 out.add(id);
838 stack.push(id);
839 }
840 }
841 while (stack.length > 0) {
842 for (const d of this.atom(stack.pop()!).deps) {
843 if (!out.has(d)) {
844 out.add(d);
845 stack.push(d);
846 }
847 }
848 }
849 return out;
850 }
852 /** Whether `b` is in the closure of `a` (an atom is in its own closure). */
853 dependsOn(a: AtomId, b: AtomId): boolean {
854 const atom = this.atom(a);
855 this.atom(b);
856 return a === b || this.#reaches(atom.deps, b);
857 }
859 /**
860 * Whether `target` is reachable along deps from any of `from` (themselves
861 * included). A dependency always has a lower lamport than its dependent, so
862 * the search never descends below the target's lamport.
863 */
864 #reaches(from: Iterable<AtomId>, target: AtomId): boolean {
865 const floor = this.#lamport[this.#seq(target)]!;
866 const seen = new Set<AtomId>();
867 const stack = [...from];
868 while (stack.length > 0) {
869 const cur = stack.pop()!;
870 if (cur === target) return true;
871 if (seen.has(cur)) continue;
872 seen.add(cur);
873 if (this.#lamport[this.#seq(cur)]! <= floor) continue;
874 for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
875 }
876 return false;
877 }
879 /**
880 * Accept an atom into the graph. It must carry the next id and seq, and
881 * everything it touches must come from atoms in its dependency closure.
882 * The atom is frozen. Adding to the graph does not add it to any set.
883 */
884 add(atom: Atom): void {
885 if (this.#storage) this.#storage.transaction(() => this.#add(atom));
886 else this.#add(atom);
887 }
889 #add(atom: Atom): void {
890 validateShape(atom);
891 const seq = this.#atoms.length;
892 const bad = (why: string): never => {
893 throw new EngineError("bad-atom", `atom ${atom.id}: ${why}`);
894 };
895 if (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`);
897 const deps = new Set<AtomId>();
898 for (const d of atom.deps) {
899 if (!this.has(d)) bad(`dependency ${d} is not in the graph`);
900 if (deps.has(d)) bad(`dependency ${d} listed twice`);
901 deps.add(d);
902 }
903 for (const d of [...atom.needs, ...atom.resolves]) {
904 if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
905 }
906 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
908 // Everything it touches must come from its closure. Derived deps name the
909 // writers directly, so this is usually one lookup per writer.
910 const below = new Map<AtomId, boolean>();
911 const inClosure = (writer: AtomId): boolean => {
912 let hit = below.get(writer);
913 if (hit === undefined) {
914 hit = deps.has(writer) || this.#reaches(deps, writer);
915 below.set(writer, hit);
916 }
917 return hit;
918 };
919 const checkLine = (line: LineId, what: string): void => {
920 const writer = this.lineAtom(line);
921 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
922 if (!inClosure(writer)) bad(`${what} names line ${line} but ${writer} is not in its closure`);
923 };
925 for (const run of atom.inserts) {
926 if (isStartNode(run.parent)) {
927 if (run.parent !== startNode(run.file)) bad(`run in ${run.file} starts at ${run.parent}`);
928 } else {
929 // The parent may have been moved into run.file, so its own file can differ.
930 checkLine(run.parent, "an insert");
931 }
932 }
933 const moved = new Set<LineId>();
934 for (const m of atom.moves ?? []) {
935 checkLine(m.line, "a move");
936 if (!isStartNode(m.parent)) checkLine(m.parent, "a move");
937 if (m.line === m.parent) bad(`moves ${m.line} after itself`);
938 if (moved.has(m.line)) bad(`moves ${m.line} twice`);
939 moved.add(m.line);
940 if (!atom.writes.includes(posKey(m.line)) || !atom.writes.includes(gapKey(m.parent))) {
941 bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`);
942 }
943 }
944 const deleted = new Set<LineId>();
945 for (const line of atom.deletes) {
946 checkLine(line, "a delete");
947 if (deleted.has(line)) bad(`deletes ${line} twice`);
948 deleted.add(line);
949 }
950 const writes = new Set(atom.writes);
951 for (const line of deleted) if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
952 for (const key of [...atom.writes, ...atom.reads, ...atom.holds]) {
953 const parsed = parseKey(key);
954 if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
955 else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
956 checkLine(parsed.node, `key ${key}`);
957 }
959 // Accept.
960 const frozen = freezeAtom(
961 atom,
962 (id) => this.#atoms[seqOf(id)]!.id,
963 (author) => {
964 if (this.#storage) return author;
965 let a = this.#authors.get(author);
966 if (a === undefined) this.#authors.set(author, (a = author));
967 return a;
968 },
969 this.#texts ? this.#reader(seq) : undefined,
970 this.#lists ? this.#listReader(seq) : undefined,
971 );
972 this.#atoms.push(this.#storage ? atom : frozen);
973 let lam = 0;
974 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);
975 this.#lamport.push(lam);
977 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.
978 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.
979 const deletes = atom.deletes.length > 0 ? new Set(atom.deletes) : undefined;
980 const deletedN = atom.deletes.map((line) => this.#lineN(line));
981 this.#atomDeletes.push(deletedN.length > 0 ? (this.#storage ? deletedN : Int32Array.from(deletedN)) : undefined);
982 this.#lineBase.push(this.#lineTotal);
983 for (const run of atom.inserts) {
984 const file = this.#pathOf(run.file);
985 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent);
986 const first = this.#lineTotal;
987 pushOne(this.#runStarts, parent, first);
988 for (let i = 0; i < run.lines.length; i++) {
989 const n = this.#lineTotal;
990 this.#lineAtom.push(seq);
991 this.#lineFile.push(file);
992 this.#lineParent.push(parent);
993 this.#lineText?.push(run.lines[i]!);
994 this.#deleter.push(-1);
995 this.#replacing.push(i === 0 && deletes?.has(run.parent) ? 1 : 0);
996 parent = n;
997 }
998 }
999 (frozen.moves ?? []).forEach((m, i) => {
1000 const info: RelocationInfo = Object.freeze({ atom: frozen.id, line: m.line, parent: m.parent, k: i });
1001 pushIndex(this.#relocations, m.line, info);
1002 pushIndex(this.#relocatedTo, m.parent, info);
1003 pushIndex(
1004 this.#relocatedToCode,
1005 isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent),
1006 info,
1007 );
1008 });
1009 if (frozen.moves) this.#movers.push(frozen.id);
1010 for (const n of deletedN) {
1011 if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
1012 else pushIndex(this.#moreDeleters, n, seq);
1014 for (const key of new Set(atom.writes)) {
1015 const code = this.#code(key);
1016 if (this.#writersPages) this.#writersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1017 else pushOne(this.#writers, code, frozen.id);
1019 for (const key of new Set(atom.reads)) {
1020 const code = this.#code(key);
1021 if (this.#readersPages) this.#readersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1022 else pushOne(this.#readers, code, frozen.id);
1024 for (const key of new Set(atom.holds)) {
1025 const code = this.#code(key);
1026 if (this.#holdersPages) this.#holdersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1027 else pushOne(this.#holders, code, frozen.id);
1029 for (const d of deps) {
1030 if (this.#dependentsPages) this.#dependentsPages.append(d, frozen.id);
1031 else pushOne(this.#dependents, d, frozen.id);
1033 for (const r of new Set(frozen.resolves)) {
1034 if (this.#resolversPages) this.#resolversPages.append(r, frozen.id);
1035 else pushOne(this.#resolvers, r, frozen.id);
1037 const files = new Set<string>();
1038 for (const run of atom.inserts) files.add(run.file);
1039 for (const n of deletedN) files.add(this.#paths[this.#lineFile.at(n)]!);
1040 for (const a of frozen.attrs ?? []) files.add(a.file);
1041 for (const m of frozen.moves ?? []) {
1042 files.add(this.lineFile(m.line)!);
1043 files.add(isStartNode(m.parent) ? m.parent.slice(1) : this.lineFile(m.parent)!);
1045 this.#atomFiles.push(Object.freeze([...files].sort()));
1046 for (const file of files) {
1047 if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);
1048 else pushIndex(this.#fileAtoms, file, frozen.id);
1050 for (const r of frozen.reasons) {
1051 if (r.kind !== "together" || r.to === frozen.id) continue;
1052 pushIndex(this.#together, frozen.id, { other: r.to, text: r.text, from: frozen.id });
1053 pushIndex(this.#together, r.to, { other: frozen.id, text: r.text, from: frozen.id });
1057 // Labels -----------------------------------------------------------------
1059 /**
1060 * Add or replace a label. Label names may not look like atom ids. A base is
1061 * resolved to its head only when it is used, never followed further, so
1062 * bases may name each other in any shape.
1063 */
1064 setLabel(label: Label): void {
1065 this.#putLabel(label, (name) => this.#labels.has(name));
1068 #putLabel(label: Label, isLabel: (name: string) => boolean): void {
1069 const bad = (why: string): never => {
1070 throw new EngineError("bad-label", `label ${JSON.stringify(label?.name)}: ${why}`);
1071 };
1072 if (typeof label !== "object" || label === null) bad("not an object");
1073 if (typeof label.name !== "string" || label.name === "") bad("needs a name");
1074 if (isAtomId(label.name)) bad("a label name may not look like an atom id");
1075 if (!this.has(label.head)) bad(`head ${label.head} is not in the graph`);
1076 if (
1077 label.base !== undefined &&
1078 !(typeof label.base === "string" && (isLabel(label.base) || this.has(label.base)))
1079 ) {
1080 bad(`base ${label.base} is neither a label nor an atom`);
1082 if (label.base === label.name) bad("a label cannot be its own base");
1083 if (typeof label.title !== "string" || typeof label.message !== "string") bad("needs a title and message");
1084 if (label.follows !== undefined && !Array.isArray(label.follows)) bad("follows must be a list of label names");
1085 const copy: Label = {
1086 name: label.name,
1087 head: label.head,
1088 ...(label.base !== undefined ? { base: label.base } : {}),
1089 title: label.title,
1090 message: label.message,
1091 ...(label.follows !== undefined ? { follows: Object.freeze([...label.follows]) } : {}),
1092 };
1093 this.#labels.set(label.name, Object.freeze(copy));
1096 label(name: string): Label | undefined {
1097 return this.#labels.get(name);
1100 /** Labels sorted by name. */
1101 labels(): Label[] {
1102 return [...this.#labels.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1105 /**
1106 * Remove a label. Labels that used it as their base get its head atom as
1107 * their base instead, so their contents don't change.
1108 */
1109 removeLabel(name: string): boolean {
1110 return this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);
1113 #removeLabel(name: string): boolean {
1114 const gone = this.#labels.get(name);
1115 if (!gone) return false;
1116 this.#labels.delete(name);
1117 for (const label of [...this.#labels.values()]) {
1118 if (label.base === name) this.#labels.set(label.name, Object.freeze({ ...label, base: gone.head }));
1120 return true;
1123 // JSON -------------------------------------------------------------------
1125 toJSON(): GraphJSON {
1126 return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };
1129 /** Load a saved graph. Every atom is re-validated as it is added. */
1130 static fromJSON(data: unknown): Graph {
1131 const bad = (why: string): never => {
1132 throw new EngineError("bad-json", why);
1133 };
1134 if (typeof data !== "object" || data === null) bad("graph JSON must be an object");
1135 const obj = data as Partial<GraphJSON>;
1136 if (obj.format !== GRAPH_FORMAT) bad(`format must be ${GRAPH_FORMAT}`);
1137 if (obj.version !== 1) bad(`unsupported version ${String(obj.version)}`);
1138 if (!Array.isArray(obj.atoms) || !Array.isArray(obj.labels)) bad("atoms and labels must be arrays");
1139 const graph = new Graph();
1140 for (const atom of obj.atoms!) graph.add(atom);
1141 // Labels may name each other as bases, in any order and any shape.
1142 const names = new Set<string>();
1143 for (const label of obj.labels!) {
1144 const name: unknown = (label as Partial<Label> | null)?.name;
1145 if (typeof name !== "string") return bad("every label needs a name");
1146 if (names.has(name)) bad(`label ${name} appears twice`);
1147 names.add(name);
1149 for (const label of obj.labels!) {
1150 try {
1151 graph.#putLabel(label, (name) => names.has(name));
1152 } catch (err) {
1153 if (err instanceof EngineError) bad(err.message);
1154 throw err;
1157 return graph;
1160 #seq(id: AtomId): number {
1161 return typeof id === "string" ? seqOf(id) : -1;
1165function validateShape(atom: Atom): void {
1166 const bad = (why: string): never => {
1167 throw new EngineError("bad-atom", `atom ${String((atom as { id?: unknown }).id)}: ${why}`);
1168 };
1169 if (typeof atom !== "object" || atom === null) bad("not an object");
1170 if (typeof atom.id !== "string" || !Number.isInteger(atom.seq)) bad("needs id and seq");
1171 if (typeof atom.author !== "string" || typeof atom.message !== "string") bad("needs author and message");
1172 if (typeof atom.time !== "number" || !Number.isFinite(atom.time)) bad("time must be a finite number");
1173 const lists = ["inserts", "deletes", "writes", "reads", "holds", "needs", "resolves", "reasons", "deps"] as const;
1174 for (const name of lists) if (!Array.isArray(atom[name])) bad(`${name} must be an array`);
1175 for (const run of atom.inserts as readonly InsertRun[]) {
1176 if (typeof run.file !== "string" || run.file === "" || run.file.includes("\n")) bad("a run needs a file path");
1177 if (typeof run.parent !== "string") bad("a run needs a parent");
1178 if (!Array.isArray(run.lines) || run.lines.length === 0) bad("a run needs at least one line");
1179 for (const text of run.lines) {
1180 if (typeof text !== "string" || text.includes("\n") || text.includes("\r"))
1181 bad("run lines must be strings without line breaks");
1184 if (atom.attrs !== undefined) {
1185 if (!Array.isArray(atom.attrs)) bad("attrs must be an array");
1186 for (const a of atom.attrs) {
1187 if (typeof a?.file !== "string" || a.file === "" || a.file.includes("\n") || !ATTR_NAMES.includes(a.name))
1188 bad("an attr needs a file and a name");
1189 if (a.value !== null && typeof a.value !== "string") bad("an attr value is a string or null");
1190 if (!atom.writes.includes(attrKey(a.file, a.name))) bad(`sets ${a.name} of ${a.file} without writing its key`);
1193 if (atom.moves !== undefined) {
1194 if (!Array.isArray(atom.moves) || atom.moves.length === 0) bad("moves must be a non-empty array");
1195 for (const m of atom.moves) {
1196 if (typeof m?.line !== "string" || typeof m.parent !== "string") bad("a move needs a line and a parent");
1199 for (const name of ["deletes", "writes", "reads", "holds", "needs", "resolves", "deps"] as const) {
1200 for (const x of atom[name]) if (typeof x !== "string") bad(`${name} must hold strings`);
1202 for (const r of atom.reasons as readonly Reason[]) {
1203 if (typeof r.to !== "string" || typeof r.text !== "string" || !REASON_KINDS.includes(r.kind)) {
1204 bad("a reason needs to, kind (together, because-of or supersedes) and text");
1209/**
1210 * A frozen copy of an atom. An empty list is one shared frozen list, and atom
1211 * ids and authors are the graph's own strings (`canon`, `author`), so each is
1212 * kept once however often it's named (#46).
1213 */
1214function freezeAtom(
1215 atom: Atom,
1216 canon: (id: AtomId) => AtomId,
1217 author: (name: string) => string,
1218 text?: (start: number, length: number) => readonly string[],
1219 lists?: () => AtomLists,
1220): Atom {
1221 const list = <T>(xs: readonly T[], f?: (x: T) => T): readonly T[] =>
1222 xs.length === 0 ? EMPTY : Object.freeze(f ? xs.map(f) : [...xs]);
1223 // With text kept elsewhere (#46), a run's lines are read when asked for.
1224 let k = 0;
1225 const run = (r: InsertRun): InsertRun => {
1226 if (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });
1227 const start = k;
1228 const length = r.lines.length;
1229 k += length;
1230 return Object.freeze(new LazyRun(r.file, r.parent, text, start, length));
1231 };
1232 const copy: Atom = {
1233 id: atom.id,
1234 seq: atom.seq,
1235 author: author(atom.author),
1236 message: atom.message,
1237 time: atom.time,
1238 inserts: Object.freeze(atom.inserts.map(run)),
1239 ...(lists
1240 ? {}
1241 : { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),
1242 needs: list(atom.needs, canon),
1243 resolves: list(atom.resolves, canon),
1244 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
1245 deps: list(atom.deps, canon),
1246 ...(atom.attrs && atom.attrs.length > 0
1247 ? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }
1248 : {}),
1249 ...(atom.moves
1250 ? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }
1251 : {}),
1252 } as Atom;
1253 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);