yamlover 0.3.3 → 0.3.4

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.
@@ -0,0 +1,187 @@
1
+ /**
2
+ * embed.ts — surgical, indentation-aware edits that EMBED fragments and annotations into a
3
+ * yamlover host body (a standalone `*.yamlover` document, or a directory's
4
+ * `.yamlover/body.yamlover` overlay). Pure string→string transforms, like the chapter-list
5
+ * insertion in engine-api.ts — the parser tracks no spans, so we edit the source text directly,
6
+ * preserving the rest of the file (comments, formatting). See ANNOTATIONS.md.
7
+ *
8
+ * A host body is YAML-shaped: a mapping's keys at one indent; a sequence's `- ` items at the
9
+ * SAME indent as their key; an item/value body 2 deeper. We descend a `within` path of mapping
10
+ * KEYS (creating any that are absent, as empty blocks) to reach a target node, then:
11
+ * • append an element to its `yamlover-annotations:` sequence (creating the key), or
12
+ * • upsert a `<slug>:` entry into its `yamlover-fragments:` mapping (creating the key).
13
+ *
14
+ * Index (sequence-position) descent — e.g. tagging a chapter CHUNK, which would turn its
15
+ * block-scalar into an omni node — is intentionally NOT handled here; the server resolves such a
16
+ * target to a key-addressable host. Keep this module free of fs / Store coupling so it unit-tests
17
+ * in isolation (see test/embed.test.ts).
18
+ */
19
+
20
+ const ANNOTATIONS_KEY = "yamlover-annotations";
21
+ const FRAGMENTS_KEY = "yamlover-fragments";
22
+
23
+ const indentOf = (line: string): number => { let i = 0; while (line[i] === " ") i++; return i; };
24
+ const isContentLine = (line: string): boolean => { const t = line.trim(); return t.length > 0 && !t.startsWith("#"); };
25
+
26
+ /** The indent of the first content line — the top mapping's key column (0 for most bodies). */
27
+ function firstContentIndent(lines: string[]): number {
28
+ for (const l of lines) if (isContentLine(l)) return indentOf(l);
29
+ return 0;
30
+ }
31
+
32
+ /** A yamlover plain/quoted key token: bare when it is a safe plain scalar, else double-quoted
33
+ * (JSON escapes — the subset the parser reads back). Mirrors how filenames with dots/spaces are
34
+ * authored as overlay keys (e.g. `"S0002-9904.pdf":`). */
35
+ export function keyToken(key: string): string {
36
+ return /^[A-Za-z0-9_][A-Za-z0-9_-]*$/.test(key) ? key : JSON.stringify(key);
37
+ }
38
+
39
+ /** Line index of `key:` at exactly `indent` within [lo,hi); -1 once the mapping ends (a dedent
40
+ * to a shallower content line). Skips deeper lines (a nested value / block scalar). */
41
+ function findKeyLine(lines: string[], lo: number, hi: number, indent: number, key: string): number {
42
+ const tok = keyToken(key);
43
+ for (let i = lo; i < hi; i++) {
44
+ if (!isContentLine(lines[i])) continue;
45
+ const ind = indentOf(lines[i]);
46
+ if (ind < indent) return -1; // left the mapping
47
+ if (ind !== indent) continue; // deeper — a nested value
48
+ const t = lines[i].trim();
49
+ if (t === `${key}:` || t.startsWith(`${key}: `) || t === `${tok}:` || t.startsWith(`${tok}: `)) return i;
50
+ }
51
+ return -1;
52
+ }
53
+
54
+ /** Walk `end` back over trailing blank lines, so an insert lands right after the last content. */
55
+ function trimBack(lines: string[], floor: number, end: number): number {
56
+ let e = end;
57
+ while (e > floor + 1 && !isContentLine(lines[e - 1])) e--;
58
+ return e;
59
+ }
60
+
61
+ /** The end (exclusive) of the block owned by the content starting at `from`, whose own lines sit
62
+ * at >= `indent`: the first later content line shallower than `indent`, sans trailing blanks. */
63
+ function blockEnd(lines: string[], from: number, hi: number, indent: number): number {
64
+ let last = from;
65
+ for (let i = from; i < hi; i++) {
66
+ if (!isContentLine(lines[i])) continue;
67
+ if (indentOf(lines[i]) < indent) return trimBack(lines, last, i);
68
+ last = i;
69
+ }
70
+ return trimBack(lines, last, hi);
71
+ }
72
+
73
+ interface Region { lo: number; hi: number; indent: number } // a mapping body: child keys at `indent`, within [lo,hi)
74
+
75
+ /** Descend the mapping-KEY path `within` to the target node's body region, CREATING any missing
76
+ * key as an empty block (so a fresh overlay grows the `"file":` → `yamlover-fragments:` →
77
+ * `<slug>:` spine on demand). Mutates `lines` in place; returns the region under the last key. */
78
+ function reachBody(lines: string[], within: string[]): Region {
79
+ let lo = 0;
80
+ let hi = lines.length;
81
+ let indent = firstContentIndent(lines);
82
+ if (lines.length === 1 && lines[0] === "") { lines.length = 0; hi = 0; indent = 0; } // empty file
83
+
84
+ for (const key of within) {
85
+ const L = findKeyLine(lines, lo, hi, indent, key);
86
+ if (L < 0) {
87
+ const at = trimBack(lines, lo - 1, hi); // append the new key at the end of the current body
88
+ lines.splice(at, 0, `${" ".repeat(indent)}${keyToken(key)}:`);
89
+ lo = at + 1; hi = at + 1; indent += 2; // its (empty) body
90
+ continue;
91
+ }
92
+ const inline = lines[L].slice(indentOf(lines[L])).slice(`${lines[L].trim().split(":")[0]}:`.length);
93
+ const bodyLo = L + 1;
94
+ const bodyHi = blockEnd(lines, bodyLo, hi, indent + 1); // anything deeper than the key
95
+ // the child key column: a deeper content line's indent if the node already has a block body,
96
+ // else key-indent + 2 (a leaf/inline value gains its first field there — an omni node).
97
+ let childIndent = indent + 2;
98
+ for (let i = bodyLo; i < bodyHi; i++) {
99
+ if (isContentLine(lines[i]) && indentOf(lines[i]) > indent) { childIndent = indentOf(lines[i]); break; }
100
+ }
101
+ void inline;
102
+ lo = bodyLo; hi = bodyHi; indent = childIndent;
103
+ }
104
+ return { lo, hi, indent };
105
+ }
106
+
107
+ /** Start lines of the `- ` items of a sequence whose key sits at `indent` (items at the same
108
+ * indent), scanning the region body for the `key:` then its items. */
109
+ function seqItemLines(lines: string[], region: Region, key: string): { keyLine: number; items: number[]; end: number } | null {
110
+ const keyLine = findKeyLine(lines, region.lo, region.hi, region.indent, key);
111
+ if (keyLine < 0) return null;
112
+ const items: number[] = [];
113
+ let end = keyLine + 1;
114
+ for (let i = keyLine + 1; i < region.hi; i++) {
115
+ if (!isContentLine(lines[i])) continue;
116
+ const ind = indentOf(lines[i]);
117
+ if (ind < region.indent) break;
118
+ if (ind === region.indent) {
119
+ const t = lines[i].trim();
120
+ if (t === "-" || t.startsWith("- ")) { items.push(i); end = i; continue; }
121
+ break; // a sibling key at the list indent → the sequence ended
122
+ }
123
+ end = i; // deeper — the current item's body
124
+ }
125
+ return { keyLine, items, end: trimBack(lines, end, region.hi) };
126
+ }
127
+
128
+ /** Append one annotation element (rendered at the list indent) to the `yamlover-annotations:`
129
+ * sequence of the node addressed by `within`, creating the key (and any missing path) if absent.
130
+ * `render(indent)` returns the element's source lines (a `- *…tag` item, or a `- {…}` object). */
131
+ export function appendAnnotation(text: string, within: string[], render: (indent: number) => string[]): string {
132
+ const lines = text.replace(/\n$/, "").split("\n");
133
+ const region = reachBody(lines, within);
134
+ const seq = seqItemLines(lines, region, ANNOTATIONS_KEY);
135
+ if (!seq) {
136
+ const at = trimBack(lines, region.lo - 1, region.hi);
137
+ lines.splice(at, 0, `${" ".repeat(region.indent)}${ANNOTATIONS_KEY}:`, ...render(region.indent));
138
+ } else {
139
+ lines.splice(seq.end, 0, ...render(region.indent));
140
+ }
141
+ return lines.join("\n") + "\n";
142
+ }
143
+
144
+ /** Upsert a `<slug>:` entry into the `yamlover-fragments:` mapping of the node addressed by
145
+ * `within`, creating the key (and any missing path) if absent. `render(indent)` returns the
146
+ * fragment's source lines INCLUDING the `<slug>:` line, at the mapping's child indent. A slug
147
+ * that already exists is REPLACED (its whole block). */
148
+ export function upsertFragment(text: string, within: string[], slug: string, render: (indent: number) => string[]): string {
149
+ const lines = text.replace(/\n$/, "").split("\n");
150
+ const region = reachBody(lines, within);
151
+ let fragKey = findKeyLine(lines, region.lo, region.hi, region.indent, FRAGMENTS_KEY);
152
+ if (fragKey < 0) {
153
+ const at = trimBack(lines, region.lo - 1, region.hi);
154
+ lines.splice(at, 0, `${" ".repeat(region.indent)}${FRAGMENTS_KEY}:`);
155
+ fragKey = at;
156
+ }
157
+ const mapIndent = region.indent + 2;
158
+ const mapBody: Region = { lo: fragKey + 1, hi: blockEnd(lines, fragKey + 1, lines.length, region.indent + 1), indent: mapIndent };
159
+ const existing = findKeyLine(lines, mapBody.lo, mapBody.hi, mapIndent, slug);
160
+ if (existing >= 0) {
161
+ const end = blockEnd(lines, existing + 1, mapBody.hi, mapIndent + 1);
162
+ lines.splice(existing, end - existing, ...render(mapIndent));
163
+ } else {
164
+ const at = trimBack(lines, fragKey, mapBody.hi);
165
+ lines.splice(at, 0, ...render(mapIndent));
166
+ }
167
+ return lines.join("\n") + "\n";
168
+ }
169
+
170
+ /** Remove an annotation element from the `yamlover-annotations:` of the node at `within` — the
171
+ * first `- ` item whose trimmed text matches `predicate`. Returns the text unchanged if none
172
+ * matches. The block of a multi-line object item is removed whole. */
173
+ export function removeAnnotation(text: string, within: string[], predicate: (itemText: string) => boolean): string {
174
+ const lines = text.replace(/\n$/, "").split("\n");
175
+ const region = reachBody(lines, within);
176
+ const seq = seqItemLines(lines, region, ANNOTATIONS_KEY);
177
+ if (!seq) return text;
178
+ for (let k = 0; k < seq.items.length; k++) {
179
+ const i = seq.items[k];
180
+ const itemText = lines[i].trim().replace(/^-\s*/, "");
181
+ if (!predicate(itemText)) continue;
182
+ const next = k + 1 < seq.items.length ? seq.items[k + 1] : seq.end;
183
+ lines.splice(i, next - i);
184
+ return lines.join("\n") + "\n";
185
+ }
186
+ return text;
187
+ }