| // Position-faithful edit sessions: byte-offset splices against ONE file's | |
| // original text, applied right-to-left so earlier offsets stay valid, with | |
| // forced verification before anything is written to disk. | |
| // | |
| // This module (together with node.mjs, which is the only thing that should | |
| // be calling `splice`) is what makes "never regenerate text from a tree" | |
| // actually enforceable: an EditSession never has access to a serialized tree | |
| // form, only to the original text plus a list of {index, length, | |
| // replacement} edits. There is no code path here that could reformat | |
| // anything the caller didn't explicitly touch. | |
| import { tokenize } from './lexer.mjs'; | |
| import { writeGameText } from './codec.mjs'; | |
| /** | |
| * Strip comments using the lexer's own state machine (not a second, | |
| * independently-written regex) and count brace characters in what's left. | |
| * This is deliberate: a naive `{`/`}` scan over raw text is fooled by a | |
| * comment that itself contains a brace (real case in this data: | |
| * `# The Eden Agreement }`), and a second regex for "strip comments" risks | |
| * silently diverging from the lexer's actual handling of `#` inside strings | |
| * and `"` inside comments. | |
| * | |
| * @param {string} text | |
| * @returns {{ open: number, close: number }} | |
| */ | |
| export function countBraces(text) { | |
| const tokens = tokenize(text); | |
| let open = 0; | |
| let close = 0; | |
| for (const t of tokens) { | |
| if (t.kind === 'comment') continue; | |
| if (t.kind === 'lbrace') open += 1; | |
| else if (t.kind === 'rbrace') close += 1; | |
| } | |
| return { open, close }; | |
| } | |
| export class EditSession { | |
| /** | |
| * @param {string} path | |
| * @param {string} text - original decoded text (from codec.mjs's readGameText) | |
| * @param {import('./lexer.mjs').Token[]} tokens - tokenize(text), handed in so | |
| * callers who already tokenized don't pay for it twice | |
| * @param {{ bom?: boolean, encoding?: string }} [meta] | |
| */ | |
| constructor(path, text, tokens, meta = {}) { | |
| this.path = path; | |
| this.originalText = text; | |
| this.tokens = tokens; | |
| this.meta = meta; | |
| /** @type {{index:number, length:number, replacement:string}[]} */ | |
| this.splices = []; | |
| this._originalBraces = countBraces(text); | |
| } | |
| get dirty() { | |
| return this.splices.length > 0; | |
| } | |
| /** | |
| * Record one splice. Does not apply or validate anything yet — multiple | |
| * splices from unrelated edits accumulate here and are only reconciled | |
| * (for overlap) at apply() time, so callers can register edits in any | |
| * order. | |
| * | |
| * @param {number} index | |
| * @param {number} length | |
| * @param {string} replacement | |
| */ | |
| splice(index, length, replacement) { | |
| if (index < 0 || length < 0) { | |
| throw new RangeError(`EditSession.splice: invalid range index=${index} length=${length}`); | |
| } | |
| this.splices.push({ index, length, replacement }); | |
| } | |
| /** | |
| * Apply all recorded splices right-to-left against the original text. | |
| * Pure function of the recorded splices; does not write or verify | |
| * anything. Throws if any two splices target overlapping ranges — that is | |
| * always a caller bug (each Node method targets a distinct token/entry | |
| * span), never a legitimate case. | |
| * | |
| * @returns {string} | |
| */ | |
| apply() { | |
| if (this.splices.length === 0) return this.originalText; | |
| const sorted = [...this.splices].sort((a, b) => b.index - a.index); | |
| for (let i = 0; i < sorted.length - 1; i += 1) { | |
| const later = sorted[i]; | |
| const earlier = sorted[i + 1]; | |
| if (earlier.index + earlier.length > later.index) { | |
| throw new Error( | |
| `EditSession.apply: overlapping splices in ${this.path} ` | |
| + `(one at [${earlier.index}, ${earlier.index + earlier.length}), ` | |
| + `another at [${later.index}, ${later.index + later.length}))`, | |
| ); | |
| } | |
| } | |
| let result = this.originalText; | |
| for (const { index, length, replacement } of sorted) { | |
| result = result.slice(0, index) + replacement + result.slice(index + length); | |
| } | |
| return result; | |
| } | |
| /** | |
| * Apply + verify + write. A session with no splices is a true no-op: it | |
| * must never touch the file's bytes or mtime, which is why this checks | |
| * `dirty` itself rather than relying on every caller to check first. | |
| * | |
| * Verification order matches the spec exactly: | |
| * 1. apply splices | |
| * 2. tokenize(out) round-trips to out | |
| * 3. comment-aware brace balance unchanged from before the edit | |
| * 4. writeGameText (which itself re-reads and verifies) | |
| */ | |
| async save() { | |
| if (!this.dirty) return; | |
| const out = this.apply(); | |
| const tokens = tokenize(out); | |
| const rebuilt = tokens.map((t) => t.raw).join(''); | |
| if (rebuilt !== out) { | |
| throw new Error( | |
| `EditSession.save: ${this.path} failed post-edit tokenize round-trip — ` | |
| + 'the applied splices produced text the lexer cannot reproduce exactly', | |
| ); | |
| } | |
| const after = countBraces(out); | |
| const before = this._originalBraces; | |
| if (after.open !== before.open || after.close !== before.close) { | |
| // Opt-out for callers that delete WHOLE AST items (pair + its block | |
| // value): that removes matched brace pairs by construction, so the | |
| // counts legitimately change while the text stays balanced. The | |
| // caller must set this flag explicitly; balance is still verified. | |
| if (!(this.allowBalancedBraceChange && after.open === after.close)) { | |
| throw new Error( | |
| `EditSession.save: ${this.path} brace balance changed — ` | |
| + `before={open:${before.open},close:${before.close}} ` | |
| + `after={open:${after.open},close:${after.close}}`, | |
| ); | |
| } | |
| } | |
| await writeGameText(this.path, out, this.meta); | |
| } | |
| } | |