- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/src/engine/view.ts?version=136&format=json
666 linesFirst import 65% · codex-capacity-chair 29% · codex-capacity-policy 7%Last change codex-capacity-chair in version 132, 15 versions changed it
You're reading version 136. The newest is 318, and 30 versions since then changed this file.
1// Projection: the files a closed set of atoms produces. A pure function of the
2// set. Each file is a tree of lines hanging off its start node; linearizing it
3// depth-first, children in descending priority, gives the file's sequence. A
4// line hangs off the node it was written after, unless a move in the set gave
5// it another parent (#28): then the newest such move decides.
6//
7// A laid-out file is kept as arrays of line numbers (the graph's n), not as a
8// record per line (#46): a record, its id and two index entries cost about
9// 370 bytes a line, and the view cache holds up to 200,000 lines. Records are
10// made when a caller asks for them, and the latest asked for is kept.
12import type { Graph, RelocationInfo } from "./graph.ts";
13import { isStartNode } from "./keys.ts";
14import { resolveScratchMoves, scratchLayoutNodes } from "./relocation-scratch.ts";
15import { StableSet } from "./state-source.ts";
16import { joinLines } from "./text.ts";
17import { type AtomId, type AtomSet, EngineError, type LineId, type NodeId } from "./types.ts";
19/** A line in a file's full sequence, tombstones included. */
20export interface SeqLine {
21 readonly id: LineId;
22 readonly text: string;
23 /** The atom that wrote it. */
24 readonly atom: AtomId;
25 /** Atoms in the set that delete it, by seq. Empty when it is visible. */
26 readonly deletedBy: readonly AtomId[];
27 readonly visible: boolean;
28}
30/** A visible line of a projected file. */
31export interface VisibleLine {
32 readonly id: LineId;
33 readonly text: string;
34 readonly atom: AtomId;
35}
37/** A file's attributes in a view. */
38export interface FileAttrs {
39 /** Kept with no lines (an empty file). */
40 readonly exists: boolean;
41 readonly exec: boolean;
42 /** The target, when the file is a symbolic link. */
43 readonly link: string | null;
44 /** The SHA-256 of its bytes, when the file is binary. */
45 readonly blob: string | null;
46}
48const NO_ATTRS: FileAttrs = { exists: false, exec: false, link: null, blob: null };
49const NONE: readonly never[] = Object.freeze([]);
51interface FileState {
52 readonly attrs: FileAttrs;
53 /** Full history is retained only when a sequence caller explicitly requests it. */
54 readonly complete: boolean;
55 /** The file's sequence, tombstones included: each line's n. */
56 readonly seq: Int32Array;
57 /** Its visible lines' n, in order. */
58 readonly vis: Int32Array;
59 /** For each deleted position in seq: the seqs of the atoms in the set that delete it, by priority. */
60 readonly deletedBy: ReadonlyMap<number, readonly number[]>;
61 /** Positions by n, built the first time they're asked for. */
62 seqIndex?: Map<number, number>;
63 visIndex?: Map<number, number>;
64}
66interface Child {
67 readonly n: number;
68 /** 1 when the child's atom deleted the parent (the child replaces it), else 0. A moved line is 0. */
69 readonly replaces: number;
70 readonly lamport: number;
71 readonly seq: number;
72 readonly k: number;
73}
75const EMPTY_INTS = new Int32Array(0);
76const NO_FILE: FileState = { attrs: NO_ATTRS, complete: true, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
78// Approximate retained-container costs for View.weight(): reference slots,
79// object headers, and map/set entries. These are cache-budget units, not V8
80// heap measurements. Referenced Graph strings and records are not charged.
81const ARRAY_HEADER_BYTES = 24;
82const OBJECT_BYTES = 32;
83const MAP_HEADER_BYTES = 32;
84const MAP_ENTRY_BYTES = 40;
85const SET_ENTRY_BYTES = 32;
86const REFERENCE_BYTES = 8;
87const FILE_LOCATION_MEMO_ENTRIES = 256;
89/**
90 * The projection of a closed set. Construct once, then ask for files, lines
91 * and sequences. Throws `not-closed` if some atom's dependency is missing.
92 * Each file is laid out the first time it is asked for, so a view of a large
93 * set costs little until files are read.
94 */
95export class View {
96 readonly graph: Graph;
97 /** The set, made from #in the first time it's asked for: a view keeps a byte per atom, not a copy of the set (#46). */
98 #set: AtomSet | undefined;
99 readonly #stable: StableSet<AtomId> | undefined;
100 /** Fixed-size memo for immutable indexed membership, independent of history size. */
101 #membershipSeq = new Float64Array(256).fill(-1);
102 #membershipValue = new Uint8Array(256);
103 #files = new Map<string, FileState>();
104 /** Every file the set wrote in, sorted; worked out the first time it's asked for. */
105 #knownList: string[] | undefined;
106 /** 1 for each atom (by seq) in the set. */
107 #in: Uint8Array;
108 /** Atoms in the set that move lines. */
109 #movers: AtomId[] | undefined;
110 #hasMoves = false;
111 /** Each moved line's relocation that counts in this set; built on first use. */
112 #relocs: Map<LineId, RelocationInfo> | undefined;
113 /** The same, by n, with the new parent's code. */
114 #relocsN: Map<number, { readonly r: RelocationInfo; readonly parent: number }> | undefined;
115 /** Bounded memo: ancestry can span the entire history even for one visible line. */
116 #fileOf = new Map<number, string>();
117 /** The latest records asked for: one file's lines, one file's sequence, one file's text. */
118 #linesCache: { path: string; lines: readonly VisibleLine[] } | undefined;
119 #seqCache: { path: string; seq: readonly SeqLine[] } | undefined;
120 #textCache: { path: string; text: string } | undefined;
122 constructor(graph: Graph, set: Iterable<AtomId>) {
123 this.graph = graph;
124 if (set instanceof StableSet) {
125 this.#stable = set;
126 this.#set = set;
127 this.#in = new Uint8Array(0);
128 for (const id of set) {
129 const atom = graph.atom(id);
130 for (const dependency of atom.deps) {
131 graph.atom(dependency);
132 if (!set.has(dependency))
133 throw new EngineError("not-closed", `set is not closed: ${id} depends on ${dependency}`);
134 }
135 }
136 for (const id of graph.movers()) {
137 if (set.has(id)) {
138 this.#hasMoves = true;
139 break;
140 }
141 }
142 this.#relocs = this.#hasMoves ? undefined : new Map();
143 this.#relocsN = this.#hasMoves ? undefined : new Map();
144 return;
145 }
146 const inSet = new Uint8Array(graph.size);
147 for (const id of set) {
148 const atom = graph.atom(id);
149 inSet[atom.seq] = 1;
150 }
151 // Validate one atom at a time. Keeping all decoded atoms here defeats
152 // storage-backed Graph reads even though the view only needs membership.
153 for (let seq = 0; seq < inSet.length; seq++) {
154 if (inSet[seq] !== 1) continue;
155 const atom = graph.atom(graph.idOfSeq(seq));
156 for (const d of atom.deps) {
157 if (inSet[graph.atom(d).seq] !== 1)
158 throw new EngineError("not-closed", `set is not closed: ${atom.id} depends on ${d}`);
159 }
160 }
161 this.graph = graph;
162 this.#in = inSet;
163 this.#movers = graph.movers().filter((id) => inSet[graph.atom(id).seq] === 1);
164 this.#hasMoves = this.#movers.length > 0;
165 this.#relocs = this.#movers.length === 0 ? new Map() : undefined;
166 this.#relocsN = this.#movers.length === 0 ? new Map() : undefined;
167 }
169 /** The set of atoms this view projects. */
170 get set(): AtomSet {
171 if (!this.#set) {
172 const out = new Set<AtomId>();
173 for (let seq = 0; seq < this.#in.length; seq++) if (this.#in[seq] === 1) out.add(this.graph.idOfSeq(seq));
174 this.#set = out;
175 }
176 return this.#set;
177 }
179 /** Whether the atom with this seq is in the set. */
180 #has(seq: number): boolean {
181 if (this.#stable) {
182 const slot = seq % this.#membershipSeq.length;
183 if (this.#membershipSeq[slot] === seq) return this.#membershipValue[slot] === 1;
184 const present = this.#stable.has(this.graph.idOfSeq(seq));
185 this.#membershipSeq[slot] = seq;
186 this.#membershipValue[slot] = present ? 1 : 0;
187 return present;
188 }
189 return seq < this.#in.length && this.#in[seq] === 1;
190 }
192 /**
193 * The relocation that counts for each moved line: the newest (by priority)
194 * in the set. Two moves made apart can loop lines into each other, so no
195 * start node reaches them; then the oldest relocation on the loop is
196 * ignored, and the next newest of that line counts, until none loop.
197 */
198 #relocations(): Map<LineId, RelocationInfo> {
199 if (this.#relocs) return this.#relocs;
200 const graph = this.graph;
201 const stronger = (a: RelocationInfo, b: RelocationInfo): boolean => graph.comparePriority(a.atom, b.atom) > 0;
202 // Persistent reads decode new objects. Cycle suppression must identify the
203 // logical move, not one particular decoded JavaScript object.
204 const identity = (r: RelocationInfo): string => JSON.stringify([r.atom, r.k]);
205 const ignored = new Set<string>();
206 const pick = (line: LineId): RelocationInfo | undefined => {
207 let best: RelocationInfo | undefined;
208 for (const r of graph.eachRelocationOf(line)) {
209 if (this.#has(graph.atom(r.atom).seq) && !ignored.has(identity(r)) && (!best || stronger(r, best))) best = r;
210 }
211 return best;
212 };
213 const relocs = new Map<LineId, RelocationInfo>();
214 for (const id of this.#eachMover()) {
215 for (const m of graph.atom(id).moves!) {
216 if (!relocs.has(m.line)) relocs.set(m.line, pick(m.line)!);
217 }
218 }
219 const parentOf = (line: LineId): NodeId => relocs.get(line)?.parent ?? graph.lineParent(line)!;
220 const reaches = new Set<LineId>();
221 for (const line of [...relocs.keys()]) {
222 for (;;) {
223 const path: LineId[] = [];
224 const onPath = new Map<LineId, number>();
225 let cur: NodeId = line;
226 let loopAt = -1;
227 while (!isStartNode(cur) && !reaches.has(cur)) {
228 const at = onPath.get(cur);
229 if (at !== undefined) {
230 loopAt = at;
231 break;
232 }
233 onPath.set(cur, path.length);
234 path.push(cur);
235 cur = parentOf(cur);
236 }
237 if (loopAt < 0) {
238 for (const l of path) reaches.add(l);
239 break;
240 }
241 let weakest: RelocationInfo | undefined;
242 for (const l of path.slice(loopAt)) {
243 const r = relocs.get(l);
244 if (r && (!weakest || stronger(weakest, r))) weakest = r;
245 }
246 ignored.add(identity(weakest!));
247 const next = pick(weakest!.line);
248 if (next) relocs.set(weakest!.line, next);
249 else relocs.delete(weakest!.line);
250 }
251 }
252 this.#relocs = relocs;
253 return relocs;
254 }
256 /** The relocations by n, with each new parent's code. */
257 #relocationsN(): Map<number, { readonly r: RelocationInfo; readonly parent: number }> {
258 if (this.#relocsN) return this.#relocsN;
259 const out = new Map<number, { readonly r: RelocationInfo; readonly parent: number }>();
260 for (const [line, r] of this.#relocations())
261 out.set(this.graph.lineN(line), { r, parent: this.graph.codeOf(r.parent)! });
262 this.#relocsN = out;
263 return out;
264 }
266 /** The node a line hangs off in this set: where it was written, or where a move put it. */
267 parentOf(line: LineId): NodeId {
268 if (this.graph.lineParent(line) === undefined) throw new EngineError("unknown-line", `no line ${line}`);
269 if (this.#hasMoves && this.graph.hasOrderedChildren)
270 return this.graph.withProjectionScratch((scratch) =>
271 resolveScratchMoves(this.graph, (id) => this.#has(this.graph.atom(id).seq), scratch).parent(line),
272 );
273 const r = this.#hasMoves ? this.#relocations().get(line) : undefined;
274 if (r) return r.parent;
275 const parent = this.graph.lineParent(line);
276 if (parent === undefined) throw new EngineError("unknown-line", `no line ${line}`);
277 return parent;
278 }
280 /** Whether any atom in the set moves lines. */
281 hasMoves(): boolean {
282 return this.#hasMoves;
283 }
284 *#eachMover(): IterableIterator<AtomId> {
285 if (this.#movers) yield* this.#movers;
286 else for (const id of this.graph.movers()) if (this.#stable!.has(id)) yield id;
287 }
289 /** The file a line is in, in this set: the one its chain of parents reaches. */
290 fileOf(line: LineId): string {
291 const n = this.graph.lineN(line);
292 if (n < 0) throw new EngineError("unknown-line", `no line ${line}`);
293 return this.#fileOfN(n);
294 }
296 #fileOfN(n: number): string {
297 const graph = this.graph;
298 if (!this.#hasMoves) return graph.writtenIn(n);
299 if (graph.hasOrderedChildren)
300 return graph.withProjectionScratch((scratch) => {
301 const moves = resolveScratchMoves(graph, (id) => this.#has(graph.atom(id).seq), scratch);
302 let current = graph.nodeOf(n);
303 while (!isStartNode(current)) current = moves.parent(current);
304 return current.slice(1);
305 });
306 const relocs = this.#relocationsN();
307 // Keep only a fixed tail of the walk for path compression. The selected
308 // relocation graph is acyclic, so traversal needs no history-sized stack.
309 const path: number[] = [];
310 let visited = 0;
311 let cur = n;
312 let file: string | undefined;
313 while (file === undefined) {
314 if (cur < 0) file = graph.nodeOf(cur).slice(1);
315 else {
316 file = this.#fileOf.get(cur);
317 if (file === undefined) {
318 path[visited++ % FILE_LOCATION_MEMO_ENTRIES] = cur;
319 cur = relocs.get(cur)?.parent ?? graph.parentCodeOf(cur);
320 }
321 }
322 }
323 for (const l of path) {
324 if (!this.#fileOf.has(l) && this.#fileOf.size >= FILE_LOCATION_MEMO_ENTRIES)
325 this.#fileOf.delete(this.#fileOf.keys().next().value!);
326 this.#fileOf.set(l, file);
327 }
328 return file;
329 }
331 /** The lines hanging off a node in this set, in layout order. */
332 #children(code: number): Child[] {
333 const graph = this.graph;
334 const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
335 const out: Child[] = [];
336 for (const n of graph.eachChildN(code)) {
337 const seq = graph.writerSeqOf(n);
338 if (!this.#has(seq) || relocs?.has(n)) continue;
339 out.push({ n, replaces: graph.replacesN(n) ? 1 : 0, lamport: graph.lamportOfSeq(seq), seq, k: graph.kOf(n) });
340 }
341 if (relocs) {
342 for (const r of graph.eachRelocatedToCode(code)) {
343 const n = graph.lineN(r.line);
344 const selected = relocs.get(n)?.r;
345 if (!selected || selected.atom !== r.atom || selected.k !== r.k) continue;
346 const seq = graph.atom(r.atom).seq;
347 out.push({ n, replaces: 0, lamport: graph.lamportOfSeq(seq), seq, k: r.k });
348 }
349 }
350 // A line's replacements (runs of atoms that deleted it) first, then the
351 // rest; each group in descending priority (lamport, then seq); lines of
352 // one atom keep k order. A replacement already outranks every insertion
353 // after the line that reads it (it depends on them, or conflicts with
354 // them); the grouping also puts it above a `before` insertion, which
355 // doesn't read the line above, so the new text lands in the replaced
356 // line's place. A moved line ranks like an insertion by the moving atom.
357 if (out.length > 1)
358 out.sort((a, b) => b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k);
359 return out;
360 }
362 /** Parent/successor traversal keeps no history-sized ancestry or sibling frontier. */
363 *#layoutNodes(start: number): IterableIterator<number> {
364 const graph = this.graph;
365 if (graph.hasOrderedChildren && !this.#hasMoves) {
366 const first = (parent: number, after?: number): number | undefined => {
367 for (const n of graph.orderedChildrenN(parent, after)) if (this.#has(graph.writerSeqOf(n))) return n;
368 return undefined;
369 };
370 let n = first(start);
371 while (n !== undefined) {
372 yield n;
373 const child = first(n);
374 if (child !== undefined) {
375 n = child;
376 continue;
377 }
378 let previous = n;
379 for (;;) {
380 const parent = graph.parentCodeOf(previous);
381 const sibling = first(parent, previous);
382 if (sibling !== undefined) {
383 n = sibling;
384 break;
385 }
386 if (parent === start) {
387 n = undefined;
388 break;
389 }
390 if (parent < 0 || parent >= previous) throw new Error("invalid persistent layout ancestry");
391 previous = parent;
392 }
393 }
394 return;
395 }
396 const stack: number[] = [];
397 const push = (parent: number): void => {
398 const children = this.#children(parent);
399 for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!.n);
400 };
401 push(start);
402 while (stack.length) {
403 const n = stack.pop()!;
404 yield n;
405 push(n);
406 }
407 }
409 /** Lay out one file: its line tree from the set's atoms, linearized. */
410 #layout(path: string, complete: boolean): FileState {
411 const graph = this.graph;
412 if (this.#hasMoves && graph.hasOrderedChildren)
413 return graph.withProjectionScratch((scratch) =>
414 this.#layoutResolved(
415 path,
416 complete,
417 scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, `^${path}`),
418 ),
419 );
420 return this.#layoutResolved(path, complete);
421 }
423 #layoutResolved(path: string, complete: boolean, nodes?: Iterable<number>): FileState {
424 const graph = this.graph;
425 // For each attribute, the highest-priority setter in the set wins.
426 const setters = new Map<string, { id: AtomId; value: string | null }>();
427 for (const id of graph.eachAtomIn(path)) {
428 if (!this.#has(graph.atom(id).seq)) continue;
429 for (const a of graph.atom(id).attrs ?? []) {
430 if (a.file !== path) continue;
431 const best = setters.get(a.name);
432 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(a.name, { id, value: a.value });
433 }
434 }
436 const seq: number[] = [];
437 const vis: number[] = [];
438 const deletedBy = new Map<number, readonly number[]>();
440 const start = graph.startCodeOf(path);
441 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b;
442 for (const n of nodes ?? (start === undefined ? [] : this.#layoutNodes(start))) {
443 let deleted = false;
444 const by: number[] = [];
445 for (const deleter of graph.eachDeleterSeqOf(n)) {
446 if (!this.#has(deleter)) continue;
447 deleted = true;
448 if (!complete) break;
449 by.push(deleter);
450 }
451 if (deleted) {
452 if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by);
453 } else vis.push(n);
454 if (complete) seq.push(n);
455 }
456 const attrs: FileAttrs = {
457 exists: setters.get("exists")?.value === "1",
458 exec: setters.get("exec")?.value === "1",
459 link: setters.get("link")?.value ?? null,
460 blob: setters.get("blob")?.value ?? null,
461 };
462 return { attrs, complete, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy };
463 }
465 get #known(): string[] {
466 if (!this.#knownList) {
467 const known = new Set<string>();
468 if (this.#stable) {
469 for (const id of this.#stable) for (const file of this.graph.filesOf(id)) known.add(file);
470 } else {
471 for (let seq = 0; seq < this.#in.length; seq++)
472 if (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file);
473 }
474 this.#knownList = [...known].sort();
475 }
476 return this.#knownList;
477 }
479 /** Files with at least one visible line, sorted. */
480 paths(): string[] {
481 if (this.#stable) {
482 const paths: string[] = [];
483 for (const path of this.graph.knownFiles()) {
484 if (this.hasFile(path)) paths.push(path);
485 else this.#files.delete(path);
486 }
487 return paths.sort();
488 }
489 return this.#known.filter((p) => this.hasFile(p));
490 }
492 /** Every file the set has ever written a line in, including fully deleted ones. */
493 knownPaths(): string[] {
494 return [...this.#known];
495 }
497 /** Whether the file exists in this projection (has a visible line). */
498 hasFile(path: string): boolean {
499 const f = this.#file(path);
500 return f.vis.length > 0 || f.attrs.exists || f.attrs.link !== null || f.attrs.blob !== null;
501 }
503 /** A file's attributes: kept while empty, executable, a link's target. */
504 attrs(path: string): FileAttrs {
505 return this.#file(path).attrs;
506 }
508 /** The projected text of a file ("" if it has no visible lines). */
509 text(path: string): string {
510 if (this.#textCache?.path === path) return this.#textCache.text;
511 const vis = this.#file(path).vis;
512 const lines: string[] = new Array(vis.length);
513 for (let i = 0; i < vis.length; i++) lines[i] = this.graph.textOf(vis[i]!);
514 const text = joinLines(lines);
515 this.#textCache = { path, text };
516 return text;
517 }
519 /** Whether a file reads the same here and in `other` (of the same graph), compared line by line without joining either (#46). */
520 sameText(path: string, other: View): boolean {
521 const a = this.#file(path).vis;
522 const b = other.#file(path).vis;
523 if (a.length !== b.length) return false;
524 for (let i = 0; i < a.length; i++)
525 if (a[i] !== b[i] && this.graph.textOf(a[i]!) !== this.graph.textOf(b[i]!)) return false;
526 return true;
527 }
529 /** Visible lines with their ids. */
530 lines(path: string): readonly VisibleLine[] {
531 if (this.#linesCache?.path === path) return this.#linesCache.lines;
532 const graph = this.graph;
533 const vis = this.#file(path).vis;
534 const lines: VisibleLine[] = new Array(vis.length);
535 for (let i = 0; i < vis.length; i++) {
536 const n = vis[i]!;
537 lines[i] = { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };
538 }
539 this.#linesCache = { path, lines };
540 return lines;
541 }
543 /** The full linearized sequence of a file, tombstones included. */
544 sequence(path: string): readonly SeqLine[] {
545 if (this.#seqCache?.path === path) return this.#seqCache.seq;
546 const graph = this.graph;
547 const f = this.#file(path, true);
548 const out: SeqLine[] = new Array(f.seq.length);
549 for (let i = 0; i < f.seq.length; i++) {
550 const n = f.seq[i]!;
551 const by = f.deletedBy.get(i);
552 out[i] = {
553 id: graph.lineIdOf(n),
554 text: graph.textOf(n),
555 atom: graph.idOfSeq(graph.writerSeqOf(n)),
556 deletedBy: by ? by.map((s) => graph.idOfSeq(s)) : NONE,
557 visible: by === undefined,
558 };
559 }
560 this.#seqCache = { path, seq: out };
561 return out;
562 }
564 /** Index of a line in `sequence(path)`, or -1. */
565 sequenceIndex(path: string, line: LineId): number {
566 const f = this.#file(path, true);
567 if (!f.seqIndex) {
568 f.seqIndex = new Map();
569 for (let i = 0; i < f.seq.length; i++) f.seqIndex.set(f.seq[i]!, i);
570 }
571 return f.seqIndex.get(this.graph.lineN(line)) ?? -1;
572 }
574 /** Index of a line in `lines(path)` (0-based visible line number), or -1 if not visible. */
575 lineNumber(path: string, line: LineId): number {
576 const f = this.#file(path);
577 if (!f.visIndex) {
578 f.visIndex = new Map();
579 for (let i = 0; i < f.vis.length; i++) f.visIndex.set(f.vis[i]!, i);
580 }
581 return f.visIndex.get(this.graph.lineN(line)) ?? -1;
582 }
584 /** All projected text files, path -> text, in path order. Binary files are in `blobs()`. */
585 files(): Record<string, string> {
586 const out: Record<string, string> = {};
587 for (const path of this.paths()) if (this.#file(path).attrs.blob === null) out[path] = this.text(path);
588 return out;
589 }
591 /** Binary files, path -> the SHA-256 of their bytes, in path order. */
592 blobs(): Record<string, string> {
593 const out: Record<string, string> = {};
594 for (const path of this.paths()) {
595 const blob = this.#file(path).attrs.blob;
596 if (blob !== null) out[path] = blob;
597 }
598 return out;
599 }
601 /**
602 * About how many bytes of retained state this view costs (#46). This uses
603 * approximate ownership costs for containers and wrappers, not V8 heap
604 * measurements. Graph-owned strings and records count only as references.
605 * This method only inspects already-created state: it does not lay out files,
606 * populate lazy caches, enumerate the graph, or count temporary traversal
607 * containers and shared empty singleton payloads as retained view state.
608 */
609 weight(): number {
610 let n = this.#in.byteLength;
611 n += 2 * ARRAY_HEADER_BYTES + this.#membershipSeq.byteLength + this.#membershipValue.byteLength;
612 if (this.#movers) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#movers.length;
613 n += MAP_HEADER_BYTES; // #files exists from construction.
614 n += MAP_HEADER_BYTES; // #fileOf exists from construction.
615 if (this.#stable) n += this.#stable.retainedBytes;
616 else if (this.#set) n += OBJECT_BYTES + SET_ENTRY_BYTES * this.#set.size;
617 if (this.#knownList) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#knownList.length;
618 if (this.#relocs) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * this.#relocs.size;
619 if (this.#relocsN) n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + OBJECT_BYTES) * this.#relocsN.size;
620 n += MAP_ENTRY_BYTES * this.#fileOf.size;
621 for (const f of this.#files.values()) {
622 n += MAP_ENTRY_BYTES;
623 if (f !== NO_FILE) {
624 // FileState and FileAttrs are per laid-out file; typed-array
625 // headers are separate from their payload byte lengths below.
626 n += OBJECT_BYTES + OBJECT_BYTES + 2 * ARRAY_HEADER_BYTES;
627 n += f.seq.byteLength + f.vis.byteLength;
628 n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + ARRAY_HEADER_BYTES) * f.deletedBy.size;
629 for (const deleters of f.deletedBy.values()) n += REFERENCE_BYTES * deleters.length;
630 if (f.seqIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.seqIndex.size;
631 if (f.visIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.visIndex.size;
632 }
633 }
634 if (this.#linesCache)
635 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 100 * this.#linesCache.lines.length;
636 if (this.#seqCache) {
637 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 120 * this.#seqCache.seq.length;
638 for (const line of this.#seqCache.seq)
639 if (line.deletedBy !== NONE) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * line.deletedBy.length;
640 }
641 if (this.#textCache) n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 2 * this.#textCache.text.length;
642 return n;
643 }
645 #file(path: string, complete = false): FileState {
646 let state = this.#files.get(path);
647 if (!state || (complete && !state.complete)) {
648 state = this.graph.hasAtomsIn(path) ? this.#layout(path, complete) : NO_FILE;
649 this.#files.set(path, state);
650 }
651 return state;
652 }
653}
655/** The files of a closed set, path -> text. */
656export function project(graph: Graph, set: Iterable<AtomId>): Record<string, string> {
657 return new View(graph, set).files();
658}
660/** Where a node sits in a file's sequence: the index just after it (0 for a start node). */
661export function indexAfter(view: View, path: string, node: NodeId): number {
662 if (isStartNode(node)) return 0;
663 const i = view.sequenceIndex(path, node);
664 if (i < 0) throw new EngineError("not-in-view", `line ${node} is not in ${path} in this view`);
665 return i + 1;
666}