// The unified API over a position-preserving tree (ast.mjs). One class for // ALL Clausewitz data — provinces, countries, cultures, events, whatever — // because it's all the same shape: a positioned key-value tree where // duplicate keys and duplicate date blocks are normal and must never be // collapsed. // // Mutating methods (`set`/`add`/`remove`) never touch `this.items` and never // synthesize a new tree: they compute a byte-offset splice and hand it to // this file's EditSession (edit.mjs). Reading a Node again after mutating it // through it will NOT reflect the edit — the source of truth after a // mutation is the pending splice list, not the in-memory tree. This is // deliberate: the whole point of this package is that text output is // derived only from {original text + splices}, never from re-walking a // tree, so the tree is not kept in sync with pending edits. const DATE_KEY_RE = /^(\d{1,4})\.(\d{1,2})\.(\d{1,2})$/; /** * Whether a string is a Clausewitz date key (e.g. "1444.11.11"). Exported so * callers/tests can reuse the exact same rule `at()` uses internally. * * @param {string} value * @returns {boolean} */ export function isDateKey(value) { return DATE_KEY_RE.test(value); } function parseDate(value) { const m = DATE_KEY_RE.exec(value); if (!m) return null; return { year: Number(m[1]), month: Number(m[2]), day: Number(m[3]) }; } function compareDates(a, b) { return (a.year - b.year) || (a.month - b.month) || (a.day - b.day); } export class Node { /** * @param {Object} opts * @param {Array} [opts.items] - this scope's items (pair|bare), from ast.mjs. Absent in resolved (at()) mode. * @param {import('./lexer.mjs').Token[]} opts.tokens - full token array for the file * @param {string} opts.text - full original text for the file * @param {string} opts.path - absolute path of the file this node belongs to * @param {'vanilla'|'mod'} [opts.layer] * @param {import('./edit.mjs').EditSession|null} opts.session - null for read-only (at()) nodes * @param {boolean} [opts.readonly] * @param {import('./lexer.mjs').Token|null} [opts.lbraceToken] - null for the root node * @param {import('./lexer.mjs').Token|null} [opts.rbraceToken] - null for root, or an unclosed block * @param {Map|null} [opts.resolved] - resolved-view backing map, set only by at() * @param {{start:number,end:number}|null} [opts.baseSpan] - span to report as .raw when resolved */ constructor(opts) { this.items = opts.items ?? null; this.tokens = opts.tokens; this.text = opts.text; this.path = opts.path; this.layer = opts.layer; this.session = opts.session ?? null; this.readonly = Boolean(opts.readonly); this.lbraceToken = opts.lbraceToken ?? null; this.rbraceToken = opts.rbraceToken ?? null; this._resolved = opts.resolved ?? null; if (this._resolved) { this._span = opts.baseSpan ?? { start: 0, end: this.text.length }; } else if (this.lbraceToken) { const endTok = this.rbraceToken ?? this.tokens[this.tokens.length - 1]; this._span = { start: this.lbraceToken.index, end: this.rbraceToken ? this.rbraceToken.index + this.rbraceToken.length : endTok.index + endTok.length, }; } else { this._span = { start: 0, end: this.text.length }; } } // ---- internal helpers ------------------------------------------------- _matching(key) { return this.items.filter((it) => it.kind === 'pair' && it.keyToken.value === key); } _unwrap(valueNode) { if (valueNode.type === 'scalar') { return valueNode.token ? valueNode.token.value : undefined; } return this._wrapBlock(valueNode); } _wrapBlock(blockValue) { const lbraceToken = this.tokens[blockValue.startTokenIndex]; const rbraceToken = blockValue.closed ? this.tokens[blockValue.endTokenIndex] : null; return new Node({ items: blockValue.items, tokens: this.tokens, text: this.text, path: this.path, layer: this.layer, session: this.session, readonly: this.readonly, lbraceToken, rbraceToken, }); } _toResolvedEntry(valueNode) { if (valueNode.type === 'scalar') { return { kind: 'scalar', value: valueNode.token ? valueNode.token.value : undefined }; } return { kind: 'block', value: this._wrapBlock(valueNode) }; } // For add_X/remove_X verbs, the operand is expected to be a plain scalar // (a tag, a culture id, etc.) in every real case measured. If some future // data ever puts a block there, fall back to its raw source slice rather // than throw — at() must never crash on unexpected-but-real shapes. _scalarOf(valueNode) { if (valueNode.type === 'scalar') { return valueNode.token ? valueNode.token.value : ''; } const start = this.tokens[valueNode.startTokenIndex]; const end = this.tokens[valueNode.endTokenIndex]; return this.text.slice(start.index, end.index + end.length); } _assertWritable() { if (this.readonly) { throw new Error( 'cannot mutate a node produced by at() — it is a read-only resolved view; ' + 'edit the underlying block via node.blocks() instead', ); } } _quoteIfNeeded(value, wasQuoted) { const needsQuote = wasQuoted || /\s/.test(value); if (!needsQuote) return value; if (value.includes('"')) { throw new Error(`cannot quote value containing a double-quote character: ${JSON.stringify(value)}`); } return `"${value}"`; } _locate(index) { let line = 1; let col = 1; for (let i = 0; i < index && i < this.text.length; i += 1) { if (this.text[i] === '\n') { line += 1; col = 1; } else { col += 1; } } return { line, col }; } // ---- the 12-method API (+ bareValues, see below) ----------------------- get(key) { if (this._resolved) { const entry = this._resolved.get(key); if (!entry) return undefined; if (entry.kind === 'accum') { throw new Error(`get(): "${key}" is a date-accumulated set with ${entry.set.size} value(s); use all()`); } return entry.value; } const matches = this._matching(key); if (matches.length > 1) { throw new Error(`get(): key "${key}" occurs ${matches.length} times; use all()`); } if (matches.length === 0) return undefined; return this._unwrap(matches[0].value); } all(key) { if (this._resolved) { const entry = this._resolved.get(key); if (!entry) return []; if (entry.kind === 'accum') return [...entry.set]; return [entry.value]; } return this._matching(key).map((m) => this._unwrap(m.value)); } has(key) { if (this._resolved) { const entry = this._resolved.get(key); if (!entry) return false; if (entry.kind === 'accum') return entry.set.size > 0; return true; } return this._matching(key).length > 0; } keys() { if (this._resolved) { return [...this._resolved.keys()].filter((k) => this.has(k)); } return this.items.filter((it) => it.kind === 'pair').map((it) => it.keyToken.value); } // Not one of the spec's headline 12 methods, but necessary: a block whose // contents are a bare-value list (`historical_idea_groups = { economic_ideas // offensive_ideas }`) or an RGB triple (`color = { 20 50 210 }`) has no // keys at all — `keys()` on it is correctly `[]`. This is the reader for // that shape. Not meaningful on an at() view (date blocks never hold bare // lists in real data), so it returns [] there rather than throwing. bareValues() { if (this._resolved) return []; return this.items.filter((it) => it.kind === 'bare').map((it) => it.token.value); } block(key) { if (this._resolved) { const entry = this._resolved.get(key); if (!entry) return undefined; if (entry.kind === 'accum') { throw new Error(`block(): "${key}" is a date-accumulated set, not a block`); } if (entry.kind !== 'block') { throw new TypeError(`block(): value for key "${key}" is not a block`); } return entry.value; } const matches = this._matching(key); if (matches.length > 1) { throw new Error(`block(): key "${key}" occurs ${matches.length} times; use blocks()`); } if (matches.length === 0) return undefined; const value = matches[0].value; if (value.type !== 'block') { throw new TypeError(`block(): value for key "${key}" is not a block`); } return this._wrapBlock(value); } blocks(key) { if (this._resolved) { if (key === undefined) { const out = []; for (const entry of this._resolved.values()) { if (entry.kind === 'block') out.push(entry.value); } return out; } const entry = this._resolved.get(key); if (!entry) return []; if (entry.kind !== 'block') { throw new TypeError(`blocks(): value for key "${key}" is not a block`); } return [entry.value]; } if (key === undefined) { return this.items .filter((it) => it.kind === 'pair' && it.value.type === 'block') .map((it) => this._wrapBlock(it.value)); } return this._matching(key).map((m) => { if (m.value.type !== 'block') { throw new TypeError(`blocks(): value for key "${key}" is not a block (found a scalar)`); } return this._wrapBlock(m.value); }); } set(key, value) { this._assertWritable(); if (typeof value !== 'string') throw new TypeError('set(): value must be a string'); const matches = this._matching(key); if (matches.length !== 1) { throw new Error( `set(): requires exactly one existing entry for key "${key}"; found ${matches.length} ` + '(use add() to create one)', ); } const valueNode = matches[0].value; if (valueNode.type !== 'scalar') { throw new Error(`set(): value for key "${key}" is a block; edit its contents via block() instead`); } const token = valueNode.token; if (!token) throw new Error(`set(): key "${key}" has no value token to replace (malformed entry)`); const raw = this._quoteIfNeeded(value, token.kind === 'string'); this.session.splice(token.index, token.length, raw); } add(key, value) { this._assertWritable(); if (typeof value !== 'string') throw new TypeError('add(): value must be a string'); const raw = this._quoteIfNeeded(value, false); const entryText = `${key} = ${raw}`; if (this.items.length > 0) { const lastItem = this.items[this.items.length - 1]; const lastToken = this.tokens[lastItem.endTokenIndex]; const insertAt = lastToken.index + lastToken.length; const beforeTok = this.tokens[lastItem.startTokenIndex - 1]; const leading = (beforeTok && beforeTok.kind === 'whitespace') ? beforeTok.raw : '\n'; this.session.splice(insertAt, 0, leading + entryText); return; } // Empty scope: no existing entry to copy indentation style from. This // path has no real-data precedent to match, so it's a documented // heuristic rather than a derived rule. if (this.lbraceToken) { const insertAt = this.lbraceToken.index + this.lbraceToken.length; this.session.splice(insertAt, 0, ` ${entryText} `); } else { this.session.splice(this.text.length, 0, `${entryText}\n`); } } remove(key, value) { this._assertWritable(); const matches = this.items.filter((it) => it.kind === 'pair' && it.keyToken.value === key && (value === undefined || this._unwrap(it.value) === value)); for (const m of matches) { const startTok = this.tokens[m.startTokenIndex]; const endTok = this.tokens[m.endTokenIndex]; let spanStart = startTok.index; let spanEnd = endTok.index + endTok.length; // Consume one adjacent whitespace run so deletion doesn't leave a // blank line: prefer the run right after (up to and including its // first newline, so an intentional blank line further down survives), // falling back to the run right before when this is the last entry // in the scope (nothing whitespace-shaped follows it). const afterTok = this.tokens[m.endTokenIndex + 1]; if (afterTok && afterTok.kind === 'whitespace') { const nl = afterTok.raw.indexOf('\n'); spanEnd += nl !== -1 ? nl + 1 : afterTok.length; } else { const beforeTok = this.tokens[m.startTokenIndex - 1]; if (beforeTok && beforeTok.kind === 'whitespace') { spanStart -= beforeTok.length; } } this.session.splice(spanStart, spanEnd - spanStart, ''); } return matches.length; } at(dateStr) { if (this._resolved) { throw new Error('at(): cannot call at() on a node that is already an at() view'); } const target = parseDate(dateStr); if (!target) { throw new Error(`at(): "${dateStr}" is not a valid date key (expected e.g. "1444.11.11")`); } const resolved = new Map(); // Applies one pair item's verb semantics (plain overwrite, or add_X / // remove_X accumulation into bucket X) into `resolved`. Used for BOTH // this node's own bare (pre-date) top-level fields and every date // block's inner items — `add_core = FRI` sitting bare at the top of a // province file is exactly as much an accumulation into bucket `core` // as a later `add_core` inside a date block is; there is nothing // date-block-specific about the verb, only about which entries qualify // by date. This is what makes duplicate top-level `add_core`/`add_core` // entries (confirmed normal in real data, e.g. Toledo's TLD+CAS cores) // resolve correctly through at() instead of colliding as if plain // overwrites of the same key. // // None of this affects `node.get('add_core')`/`node.get('owner')` on // THIS node (no at()) — those never call this method at all, so the // literal bare fields stay reachable through the normal read path // completely unaffected by at()'s bucket renaming or overwrite // resolution. const applyItem = (inner) => { if (inner.kind !== 'pair') return; const k = inner.keyToken.value; if (k.startsWith('add_')) { const bucket = k.slice(4); let entry = resolved.get(bucket); if (!entry || entry.kind !== 'accum') entry = { kind: 'accum', set: new Set() }; entry.set.add(this._scalarOf(inner.value)); resolved.set(bucket, entry); } else if (k.startsWith('remove_')) { const bucket = k.slice(7); const entry = resolved.get(bucket); if (entry && entry.kind === 'accum') entry.set.delete(this._scalarOf(inner.value)); // Removing something never added: no-op, per spec. } else { resolved.set(k, this._toResolvedEntry(inner.value)); } }; for (const it of this.items) { if (it.kind !== 'pair' || isDateKey(it.keyToken.value)) continue; applyItem(it); } const dateBlocks = this.items .map((it, idx) => ({ it, idx })) .filter(({ it }) => it.kind === 'pair' && isDateKey(it.keyToken.value) && it.value.type === 'block'); // Chronological order; original file order breaks ties (duplicate date // blocks are normal in real data — see history/countries/FRA - France.txt). dateBlocks.sort((a, b) => { const cmp = compareDates(parseDate(a.it.keyToken.value), parseDate(b.it.keyToken.value)); return cmp !== 0 ? cmp : a.idx - b.idx; }); for (const { it } of dateBlocks) { const blockDate = parseDate(it.keyToken.value); if (compareDates(blockDate, target) > 0) continue; for (const inner of it.value.items) applyItem(inner); } return new Node({ tokens: this.tokens, text: this.text, path: this.path, layer: this.layer, session: null, readonly: true, resolved, baseSpan: this._span, }); } get raw() { const { line, col } = this._locate(this._span.start); return { text: this.text.slice(this._span.start, this._span.end), index: this._span.start, line, col, length: this._span.end - this._span.start, }; } get file() { return { path: this.path, layer: this.layer }; } }