herdr-gentle-shell 1.8.0 → 1.9.0

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,1133 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // The in-process owner of Herdr's `[theme]` table (theme-sync-fix T2 over S3/S4,
5
+ // third correction pass).
6
+ //
7
+ // WHY THIS SHAPE. Three verifiers in a row broke a planner that tried to VALIDATE
8
+ // the whole document with a hand-written TOML grammar: every pass fixed one
9
+ // corner and the next one found another. The scope was wrong. This planner is a
10
+ // LINE SPLICER, not a validator:
11
+ //
12
+ // OPAQUE OUTSIDE THE THEME TABLES. It finds table boundaries (headers are only
13
+ // headers at a real line start — never inside a multi-line string, a multi-line
14
+ // array, an inline table or a comment) and then treats every other line as
15
+ // opaque bytes. An input that is already invalid TOML outside `[theme]` and
16
+ // `[theme.custom]` is the user's pre-existing breakage: Herdr refuses to load
17
+ // it, and this module's only promise is that it does not touch those lines.
18
+ //
19
+ // STRICT INSIDE THE THEME TABLES. Where it writes, it accepts only comments,
20
+ // blank lines and `key = value [comment]` with a single-line string, boolean,
21
+ // integer or float, and it refuses anything else for a key it must touch. A key
22
+ // it does not touch is left byte for byte whenever the scanner can tell where
23
+ // that line ends (so an untargeted `yellow = """reset"""` keeps working).
24
+ //
25
+ // SPLICING INVARIANT, ENFORCED. Before `ok: true` the planner re-derives the
26
+ // non-theme lines of its own output and compares them with the input's; a
27
+ // mismatch is an internal error, never a silent edit. The only lines it may
28
+ // remove from the opaque region are the 1.8.0 markers this package wrote.
29
+ //
30
+ // WHAT IS GUARANTEED: table boundaries are correct for documents whose
31
+ // multi-line strings, arrays and inline tables are terminated; the theme tables
32
+ // only ever contain the strict line forms above; every byte outside the theme
33
+ // tables is preserved (modulo one added line terminator when a table or block is
34
+ // placed after an unterminated last line, and that addition is recorded on the
35
+ // managed block's end line so a later clear takes it back); a `was` marker
36
+ // records the whole original line and a restore gives back its key/value plus the
37
+ // user's CURRENT trailing comment when they edited it; CRLF/mixed EOL, a BOM and
38
+ // a missing final newline survive; planning is idempotent and reversible.
39
+ //
40
+ // WHAT IS NOT GUARANTEED, deliberately: this is NOT a TOML validator. It does not
41
+ // check values, dates, numbers or keys outside the theme tables, does not detect
42
+ // duplicate keys or tables anywhere else, does not validate a projected palette
43
+ // beyond its shape (#rrggbb, known token), and does not lock the config. Deleting
44
+ // those checks is the point of this pass: they caused false refusals of valid
45
+ // files, and they were never able to make an invalid file valid. Outside the
46
+ // theme tables an escape only consumes the character after it, so an illegal
47
+ // escape there is not a refusal (whether it is legal TOML is a parser's job).
48
+ //
49
+ // TWO KNOWN LIMITS. A comment that would parse as a `was` marker for the key
50
+ // below a managed block is AMBIGUOUS once that block is removed or moved (the
51
+ // next plan would promote the user's ordinary comment to ownership), so such a
52
+ // plan refuses instead of guessing. And a `[theme]` name line this planner
53
+ // inserted is never removed again: a projection always carries a theme name, so
54
+ // there is no "empty projection" that could ask for it.
55
+ //
56
+ // Pure on purpose: it takes text and a projection and returns text. The writer
57
+ // (lib/herdr-theme-apply.js) owns every file descriptor, backup and reload.
58
+
59
+ const { HERDR_BASE_THEMES, HERDR_TOKEN_ORDER, isConcreteHex } = require('./theme-projection.js');
60
+
61
+ const WAS_PREFIX = '# herdr-gentle-shell: was ';
62
+ const BLOCK_BEGIN = '# herdr-gentle-shell: begin';
63
+ const BLOCK_BEGIN_CREATED = '# herdr-gentle-shell: begin created';
64
+ // The block's end, when placing the block also added the file's missing final
65
+ // line ending to the line above it. A later clear must take that ending back,
66
+ // and the text alone cannot tell who added it, so the fact is recorded here.
67
+ const BLOCK_END_ADDED = '# herdr-gentle-shell: end after a missing line ending';
68
+ const BLOCK_END = '# herdr-gentle-shell: end';
69
+
70
+ // The 1.8.0 managed block. Its body is ordinary `[theme]` config now, so only a
71
+ // nearest-paired marker pair that encloses a theme table is dropped; every other
72
+ // marker line is the user's text and is preserved.
73
+ const LEGACY_BEGIN = '# BEGIN herdr-gentle-theme (managed; do not edit)';
74
+ const LEGACY_END = '# END herdr-gentle-theme';
75
+
76
+ // Raw control characters make the line scan unsafe and are invalid TOML
77
+ // anywhere, including inside a comment. Tab and newline are the exceptions, and
78
+ // U+2028/U+2029/U+0085 are ordinary characters in a comment.
79
+ const CONTROL_CHARACTERS = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/;
80
+ const BARE_CARRIAGE_RETURN = /\r(?!\n)/;
81
+ const BOM = '\uFEFF';
82
+
83
+ // A line we record as an original cannot carry a character that breaks "one
84
+ // line" for a reader. Only C0 controls (tab excepted) and DEL do that: U+0085,
85
+ // U+2028 and U+2029 are legal characters in a TOML comment and are ordinary
86
+ // text, not line separators, so they must survive a record/restore untouched.
87
+ const UNRECORDABLE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/;
88
+
89
+ // The ONLY value forms accepted inside `[theme]`/`[theme.custom]` (design point
90
+ // 3). Outside those tables nothing is validated.
91
+ const STRICT_NUMBER = new RegExp(
92
+ '^(?:'
93
+ + '[+-]?(?:0|[1-9](?:_?[0-9])*)(?:\\.[0-9](?:_?[0-9])*)?(?:[eE][+-]?[0-9](?:_?[0-9])*)?'
94
+ + '|[+-]?(?:inf|nan)'
95
+ + '|0x[0-9A-Fa-f](?:_?[0-9A-Fa-f])*'
96
+ + '|0o[0-7](?:_?[0-7])*'
97
+ + '|0b[01](?:_?[01])*'
98
+ + ')$',
99
+ );
100
+
101
+ const BASIC_ESCAPES = new Set(['b', 't', 'n', 'f', 'r', '"', '\\']);
102
+
103
+ const THEME_KEYS_REFUSED = new Set(['dark_name', 'light_name']);
104
+ const THEME_OWNED_KEYS = new Set(['name', 'custom', 'auto_switch', 'dark_name', 'light_name']);
105
+
106
+ function fail(line, reason) {
107
+ return `line ${line}: ${reason}; no changes proposed.`;
108
+ }
109
+
110
+ /* ------------------------------------------------------------- projection */
111
+
112
+ function invalidProjection(projection) {
113
+ if (typeof projection !== 'object' || projection === null || Array.isArray(projection)) {
114
+ return 'Invalid Herdr theme projection: expected an object; no changes proposed.';
115
+ }
116
+ for (const key of Object.keys(projection)) {
117
+ if (key !== 'name' && key !== 'custom') {
118
+ return `Invalid Herdr theme projection: unknown key \`${key}\`; no changes proposed.`;
119
+ }
120
+ }
121
+ if (typeof projection.name !== 'string' || !HERDR_BASE_THEMES.includes(projection.name)) {
122
+ return `Invalid Herdr theme projection: theme name ${JSON.stringify(projection.name)} is not a Herdr native theme; no changes proposed.`;
123
+ }
124
+ if (projection.custom !== undefined) {
125
+ const custom = projection.custom;
126
+ if (typeof custom !== 'object' || custom === null || Array.isArray(custom)) {
127
+ return 'Invalid Herdr theme projection: `custom` must be a record of tokens; no changes proposed.';
128
+ }
129
+ for (const [token, value] of Object.entries(custom)) {
130
+ if (!HERDR_TOKEN_ORDER.includes(token)) {
131
+ return `Invalid Herdr theme projection: \`${token}\` is not a Herdr theme token; no changes proposed.`;
132
+ }
133
+ if (!isConcreteHex(value)) {
134
+ return `Invalid Herdr theme projection: \`${token}\` value ${JSON.stringify(value)} is not #rrggbb; no changes proposed.`;
135
+ }
136
+ }
137
+ }
138
+ return null;
139
+ }
140
+
141
+ /* ------------------------------------------------------------------ lines */
142
+
143
+ function splitLines(text) {
144
+ const lines = [];
145
+ let start = 0;
146
+ while (start < text.length) {
147
+ const newline = text.indexOf('\n', start);
148
+ if (newline < 0) {
149
+ lines.push({ start, end: text.length, content: text.slice(start), eol: '' });
150
+ break;
151
+ }
152
+ const crlf = newline > start && text[newline - 1] === '\r';
153
+ const contentEnd = crlf ? newline - 1 : newline;
154
+ lines.push({ start, end: newline + 1, content: text.slice(start, contentEnd), eol: crlf ? '\r\n' : '\n' });
155
+ start = newline + 1;
156
+ }
157
+ return lines;
158
+ }
159
+
160
+ function lineIndexAt(lines, offset) {
161
+ let low = 0;
162
+ let high = lines.length - 1;
163
+ while (low < high) {
164
+ const mid = (low + high + 1) >> 1;
165
+ if (lines[mid].start <= offset) low = mid;
166
+ else high = mid - 1;
167
+ }
168
+ return low;
169
+ }
170
+
171
+ function isSpace(character) {
172
+ return character === ' ' || character === '\t';
173
+ }
174
+
175
+ function indentOf(content) {
176
+ const match = /^[ \t]*/.exec(content);
177
+ return match ? match[0] : '';
178
+ }
179
+
180
+ /* --------------------------------------------------- string / value echoes */
181
+
182
+ // Validate one escape sequence starting at the backslash. Surrogates are refused
183
+ // because they are not scalar values: a config Herdr cannot parse is not a config.
184
+ function escapeAt(text, index, multiline) {
185
+ const escape = text[index + 1];
186
+ if (escape === undefined) return { error: 'unterminated string' };
187
+ if (BASIC_ESCAPES.has(escape)) return { end: index + 2 };
188
+ if (escape === 'u' || escape === 'U') {
189
+ const size = escape === 'u' ? 4 : 8;
190
+ const hex = text.slice(index + 2, index + 2 + size);
191
+ if (hex.length !== size || !/^[0-9a-fA-F]+$/.test(hex)) return { error: 'invalid unicode escape in a string' };
192
+ const code = Number.parseInt(hex, 16);
193
+ if (code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return { error: 'unicode escapes must be scalar values' };
194
+ return { end: index + 2 + size };
195
+ }
196
+ if (multiline) {
197
+ // A line-ending backslash: the backslash is the last non-blank character of
198
+ // the line and it trims all following whitespace and newlines.
199
+ let cursor = index + 1;
200
+ while (cursor < text.length && (text[cursor] === ' ' || text[cursor] === '\t')) cursor += 1;
201
+ const newline = text[cursor] === '\n' ? cursor + 1 : text[cursor] === '\r' && text[cursor + 1] === '\n' ? cursor + 2 : -1;
202
+ if (newline >= 0) {
203
+ let end = newline;
204
+ while (end < text.length && /[ \t\r\n]/.test(text[end])) end += 1;
205
+ return { end };
206
+ }
207
+ }
208
+ return { error: `unsupported escape \\${escape} in a string` };
209
+ }
210
+
211
+ function decodeEscapes(inner, multiline) {
212
+ let out = '';
213
+ for (let index = 0; index < inner.length; index += 1) {
214
+ const character = inner[index];
215
+ if (character !== '\\') {
216
+ out += character;
217
+ continue;
218
+ }
219
+ const escape = inner[index + 1];
220
+ if (escape === 'u' || escape === 'U') {
221
+ const size = escape === 'u' ? 4 : 8;
222
+ const code = Number.parseInt(inner.slice(index + 2, index + 2 + size), 16);
223
+ if (!Number.isFinite(code)) return null;
224
+ out += String.fromCodePoint(code);
225
+ index += 1 + size;
226
+ continue;
227
+ }
228
+ if (multiline && (escape === '\n' || escape === '\r')) {
229
+ index += escape === '\r' ? 2 : 1;
230
+ while (index + 1 < inner.length && /[ \t\r\n]/.test(inner[index + 1])) index += 1;
231
+ continue;
232
+ }
233
+ const values = { b: '\b', t: '\t', n: '\n', f: '\f', r: '\r', '"': '"', '\\': '\\' };
234
+ if (escape === undefined || !Object.hasOwn(values, escape)) return null;
235
+ out += values[escape];
236
+ index += 1;
237
+ }
238
+ return out;
239
+ }
240
+
241
+ // Where a single-line string starting here ends, checking its escapes.
242
+ function singleLineStringEnd(text, index) {
243
+ const quote = text[index];
244
+ let cursor = index + 1;
245
+ while (cursor < text.length) {
246
+ const character = text[cursor];
247
+ if (quote === '"' && character === '\\') {
248
+ const escape = escapeAt(text, cursor, false);
249
+ if (escape.error) return null;
250
+ cursor = escape.end;
251
+ continue;
252
+ }
253
+ if (character === quote) return cursor + 1;
254
+ cursor += 1;
255
+ }
256
+ return null;
257
+ }
258
+
259
+ /* ------------------------------------------- tolerant boundary scanning --- */
260
+
261
+ // Where does the value starting at `from` end? This is NOT a grammar: it only
262
+ // tracks the three contexts that can hide a line break — multi-line strings,
263
+ // arrays and inline tables — plus comments, so table headers can be recognised
264
+ // at real line starts. It refuses only when a context cannot be closed.
265
+ function scanValueBoundary(text, from) {
266
+ const length = text.length;
267
+ let index = from;
268
+ const brackets = [];
269
+ let string = null;
270
+ while (index < length) {
271
+ const character = text[index];
272
+ if (string !== null) {
273
+ if (string === '"""' || string === "'''") {
274
+ if (string === '"""' && character === '\\') {
275
+ // Boundary scan only: consume the escaped character and never validate
276
+ // it (this covers line continuations, a bad escape, and an escaped
277
+ // quote alike). Whether the escape is legal TOML is a parser's job.
278
+ if (index + 1 >= length) return { error: 'unterminated string' };
279
+ index += 2;
280
+ continue;
281
+ }
282
+ if (character === string[0]) {
283
+ let run = 0;
284
+ while (text[index + run] === string[0]) run += 1;
285
+ if (run < 3) {
286
+ index += run;
287
+ continue;
288
+ }
289
+ // Any run of three or more closes the string. Whether the remaining
290
+ // quotes are legal TOML is a parser's judgement, not a boundary's.
291
+ string = null;
292
+ index += run;
293
+ continue;
294
+ }
295
+ index += 1;
296
+ continue;
297
+ }
298
+ if (string === '"') {
299
+ if (character === '\\') {
300
+ // Boundary scan only: an escape consumes the next character and is not
301
+ // validated here. A string outside the theme tables is the user's
302
+ // bytes; whether its escapes are legal is not this scanner's business.
303
+ if (index + 1 >= length) return { error: 'unterminated string' };
304
+ index += 2;
305
+ continue;
306
+ }
307
+ if (character === '"') {
308
+ string = null;
309
+ index += 1;
310
+ continue;
311
+ }
312
+ } else if (character === "'") {
313
+ string = null;
314
+ index += 1;
315
+ continue;
316
+ }
317
+ if (character === '\n') return { error: 'unterminated string' };
318
+ index += 1;
319
+ continue;
320
+ }
321
+ if (character === '#') {
322
+ while (index < length && text[index] !== '\n') index += 1;
323
+ continue;
324
+ }
325
+ if (character === '"' || character === "'") {
326
+ const triple = character.repeat(3);
327
+ if (text.startsWith(triple, index)) {
328
+ string = triple;
329
+ index += 3;
330
+ continue;
331
+ }
332
+ string = character;
333
+ index += 1;
334
+ continue;
335
+ }
336
+ if (character === '[' || character === '{') {
337
+ brackets.push(character === '[' ? ']' : '}');
338
+ index += 1;
339
+ continue;
340
+ }
341
+ if (character === ']' || character === '}') {
342
+ const expected = brackets.pop();
343
+ if (expected !== undefined && expected !== character) return { error: 'mismatched bracket or brace' };
344
+ index += 1;
345
+ continue;
346
+ }
347
+ if (character === '\n' && brackets.length === 0) return { end: index };
348
+ index += 1;
349
+ }
350
+ if (string !== null) return { error: 'unterminated string' };
351
+ if (brackets.length > 0) return { error: 'unterminated array or inline table' };
352
+ return { end: length };
353
+ }
354
+
355
+ // One quoted key segment: a quoted segment is ONE literal segment, so
356
+ // `["theme"]` is `[theme]` while `["theme.custom"]` is a different root key.
357
+ function quotedSegmentAt(text, start, limit) {
358
+ if (text.startsWith(text[start].repeat(3), start)) return { error: 'a quoted key must be on one line' };
359
+ const end = singleLineStringEnd(text, start);
360
+ if (end === null || end > limit) return { error: 'unterminated quoted key' };
361
+ const raw = text.slice(start + 1, end - 1);
362
+ const value = text[start] === '"' ? decodeEscapes(raw, false) : raw;
363
+ if (value === null) return { error: 'unsupported escape in a quoted key' };
364
+ return { value, end };
365
+ }
366
+
367
+ function parseKeySegmentsAt(text, start, limit) {
368
+ const segments = [];
369
+ let index = start;
370
+ for (;;) {
371
+ if (index >= limit) return { error: 'unterminated key' };
372
+ const character = text[index];
373
+ if (character === '"' || character === "'") {
374
+ const quoted = quotedSegmentAt(text, index, limit);
375
+ if (quoted.error) return quoted;
376
+ segments.push(quoted.value);
377
+ index = quoted.end;
378
+ } else {
379
+ const bare = /^[A-Za-z0-9_-]+/.exec(text.slice(index, limit));
380
+ if (!bare) return { error: 'not a key/value line' };
381
+ segments.push(bare[0]);
382
+ index += bare[0].length;
383
+ }
384
+ while (index < limit && isSpace(text[index])) index += 1;
385
+ if (text[index] !== '.') return { segments, end: index };
386
+ index += 1;
387
+ while (index < limit && isSpace(text[index])) index += 1;
388
+ }
389
+ }
390
+
391
+ function parseTableHeaderAt(text, start, limit) {
392
+ const array = text[start + 1] === '[';
393
+ let index = start + (array ? 2 : 1);
394
+ const segments = [];
395
+ let expectSegment = true;
396
+ for (;;) {
397
+ while (index < limit && isSpace(text[index])) index += 1;
398
+ if (index >= limit) return { error: 'unterminated table header' };
399
+ const character = text[index];
400
+ if (character === ']') {
401
+ if (segments.length === 0 || expectSegment) return { error: 'unsupported table header' };
402
+ index += 1;
403
+ if (array) {
404
+ if (text[index] !== ']') return { error: 'unterminated array-of-tables header' };
405
+ index += 1;
406
+ }
407
+ const rest = text.slice(index, limit).trim();
408
+ if (rest !== '' && !rest.startsWith('#')) return { error: 'trailing content after the table header' };
409
+ return { array, segments };
410
+ }
411
+ if (character === '.') {
412
+ if (expectSegment) return { error: 'unsupported table header' };
413
+ index += 1;
414
+ expectSegment = true;
415
+ continue;
416
+ }
417
+ if (!expectSegment) return { error: 'unsupported table header' };
418
+ if (character === '"' || character === "'") {
419
+ const quoted = quotedSegmentAt(text, index, limit);
420
+ if (quoted.error) return quoted;
421
+ segments.push(quoted.value);
422
+ index = quoted.end;
423
+ } else {
424
+ const bare = /^[A-Za-z0-9_-]+/.exec(text.slice(index, limit));
425
+ if (!bare) return { error: 'unsupported table header' };
426
+ segments.push(bare[0]);
427
+ index += bare[0].length;
428
+ }
429
+ expectSegment = false;
430
+ }
431
+ }
432
+
433
+ // Statements: blank, comment, header or content. A content statement may span
434
+ // lines; its `keys` are a best-effort key prefix (null when unparseable), which
435
+ // is all the theme decisions need.
436
+ function scanStatements(text, lines) {
437
+ const statements = [];
438
+ let pos = 0;
439
+ let lineIndex = 0;
440
+ while (pos < text.length) {
441
+ const line = lines[lineIndex];
442
+ const contentEnd = line.start + line.content.length;
443
+ let cursor = pos;
444
+ while (cursor < contentEnd && isSpace(text[cursor])) cursor += 1;
445
+ if (cursor >= contentEnd) {
446
+ statements.push({ kind: 'blank', line: lineIndex + 1, lastLine: lineIndex + 1 });
447
+ pos = line.end;
448
+ lineIndex += 1;
449
+ continue;
450
+ }
451
+ if (text[cursor] === '#') {
452
+ statements.push({ kind: 'comment', line: lineIndex + 1, lastLine: lineIndex + 1, text: line.content });
453
+ pos = line.end;
454
+ lineIndex += 1;
455
+ continue;
456
+ }
457
+ if (text[cursor] === '[') {
458
+ const header = parseTableHeaderAt(text, cursor, contentEnd);
459
+ if (header.error) return { error: fail(lineIndex + 1, header.error) };
460
+ statements.push({ kind: 'header', array: header.array, path: header.segments, line: lineIndex + 1, lastLine: lineIndex + 1 });
461
+ pos = line.end;
462
+ lineIndex += 1;
463
+ continue;
464
+ }
465
+ const key = parseKeySegmentsAt(text, cursor, contentEnd);
466
+ let valueStart = null;
467
+ let boundary;
468
+ if (key.error) {
469
+ // No key: the line is opaque content that cannot continue past its `=`.
470
+ const equals = text.indexOf('=', cursor);
471
+ boundary = equals >= 0 && equals < contentEnd ? scanValueBoundary(text, equals + 1) : { end: contentEnd };
472
+ } else {
473
+ let after = key.end;
474
+ while (after < contentEnd && isSpace(text[after])) after += 1;
475
+ if (text[after] !== '=') {
476
+ boundary = { end: contentEnd };
477
+ } else {
478
+ after += 1;
479
+ while (after < text.length && isSpace(text[after])) after += 1;
480
+ valueStart = after;
481
+ boundary = scanValueBoundary(text, after);
482
+ }
483
+ }
484
+ if (boundary.error) return { error: fail(lineIndex + 1, boundary.error) };
485
+ const lastLine = lineIndexAt(lines, Math.max(cursor, boundary.end - 1)) + 1;
486
+ statements.push({
487
+ kind: 'content',
488
+ line: lineIndex + 1,
489
+ lastLine,
490
+ keys: key.error ? null : key.segments,
491
+ valueStart,
492
+ });
493
+ if (lines[lastLine - 1].end >= text.length) break;
494
+ pos = lines[lastLine - 1].end;
495
+ lineIndex = lineIndexAt(lines, pos);
496
+ }
497
+ return { statements };
498
+ }
499
+
500
+ /* -------------------------------------------- strict theme-table grammar --- */
501
+
502
+ // `key = value [comment]` where the key is ONE bare or quoted segment and the
503
+ // value is a single-line string, boolean, integer or float. Anything else is
504
+ // `other` — not an error by itself, because an untouched line is the user's.
505
+ function parseThemeLine(content) {
506
+ const indent = indentOf(content);
507
+ let index = indent.length;
508
+ if (index >= content.length || content[index] === '#') return { kind: 'blank-line' };
509
+ let key;
510
+ if (content[index] === '"' || content[index] === "'") {
511
+ const quoted = quotedSegmentAt(content, index, content.length);
512
+ if (quoted.error) return { kind: 'other' };
513
+ key = quoted.value;
514
+ index = quoted.end;
515
+ } else {
516
+ const bare = /^[A-Za-z0-9_-]+/.exec(content.slice(index));
517
+ if (!bare) return { kind: 'other' };
518
+ key = bare[0];
519
+ index += bare[0].length;
520
+ }
521
+ while (index < content.length && isSpace(content[index])) index += 1;
522
+ if (content[index] !== '=') return { kind: 'other' };
523
+ index += 1;
524
+ while (index < content.length && isSpace(content[index])) index += 1;
525
+ const valueStart = index;
526
+ let valueKind = null;
527
+ if (content[index] === '"' || content[index] === "'") {
528
+ const end = singleLineStringEnd(content, index);
529
+ if (end === null) return { kind: 'other' };
530
+ valueKind = 'string';
531
+ index = end;
532
+ } else {
533
+ const run = /^[^ \t#]*/.exec(content.slice(index))[0];
534
+ if (run === '') return { kind: 'other' };
535
+ if (/^(?:true|false)$/.test(run)) valueKind = 'boolean';
536
+ else if (STRICT_NUMBER.test(run)) valueKind = 'number';
537
+ else return { kind: 'other' };
538
+ index += run.length;
539
+ }
540
+ while (index < content.length && isSpace(content[index])) index += 1;
541
+ if (index < content.length && content[index] !== '#') return { kind: 'other' };
542
+ return {
543
+ kind: 'key',
544
+ key,
545
+ indent,
546
+ valueStart,
547
+ valueEnd: valueStart + (valueKind === 'string' ? (singleLineStringEnd(content, valueStart) - valueStart) : (/^[^ \t#]*/.exec(content.slice(valueStart))[0].length)),
548
+ valueKind,
549
+ raw: content.slice(valueStart, valueStart + (valueKind === 'string'
550
+ ? singleLineStringEnd(content, valueStart) - valueStart
551
+ : /^[^ \t#]*/.exec(content.slice(valueStart))[0].length)),
552
+ };
553
+ }
554
+
555
+ // The text of a `was` marker for `key`, or null when the comment is not one of
556
+ // ours. The payload is the WHOLE original line minus its indentation — trailing
557
+ // spaces, tabs and an inline comment included — because a restore must give back
558
+ // the user's bytes exactly. It must parse with the same strict grammar, name the
559
+ // same key and carry a string (the only thing this writer records); a payload
560
+ // that cannot be read back safely is an ordinary comment.
561
+ function markerLine(commentText, key) {
562
+ const indent = indentOf(commentText);
563
+ const rest = commentText.slice(indent.length);
564
+ if (!rest.startsWith(WAS_PREFIX)) return null;
565
+ const payload = rest.slice(WAS_PREFIX.length);
566
+ if (UNRECORDABLE.test(payload)) return null;
567
+ const parsed = parseThemeLine(payload);
568
+ if (parsed.kind !== 'key' || parsed.key !== key || parsed.valueKind !== 'string') return null;
569
+ return { payload, value: decodedStringValue(parsed) };
570
+ }
571
+
572
+ // A comment line directly above `begin` that would parse as a marker for the
573
+ // first key after the block. Such a line is the user's ordinary comment today,
574
+ // but once the block lines are removed it is adjacent to that key and the next
575
+ // plan would treat it as ownership. Returns its line number, or -1.
576
+ function ambiguousMarkerAbove(lines, statements, isComment, blockBegin, blockEnd) {
577
+ let key = null;
578
+ for (const statement of statements) {
579
+ if (statement.kind !== 'content' || statement.line <= blockEnd) continue;
580
+ if (!statement.keys || statement.keys.length !== 1) break;
581
+ key = statement.keys[0];
582
+ break;
583
+ }
584
+ if (key === null || !HERDR_TOKEN_ORDER.includes(key)) return -1;
585
+ for (let line = blockBegin - 1; line >= 1 && isComment(line); line -= 1) {
586
+ if (markerLine(lines[line - 1].content, key) !== null) return line;
587
+ }
588
+ return -1;
589
+ }
590
+
591
+ // Every marker for `key` in the contiguous comment block above the key line.
592
+ function markersAbove(lines, isComment, keyLine, key) {
593
+ const found = [];
594
+ for (let line = keyLine - 1; line >= 1; line -= 1) {
595
+ if (!isComment(line)) break;
596
+ const marker = markerLine(lines[line - 1].content, key);
597
+ if (marker === null) continue;
598
+ found.push({ line, payload: marker.payload, value: marker.value });
599
+ }
600
+ return found;
601
+ }
602
+
603
+ // A string value's decoded text. Escapes belong to basic strings only: a literal
604
+ // string is exactly the characters between its quotes, so `'\u0023123456'` is
605
+ // that text and NOT the colour `#123456`.
606
+ function decodedStringValue(strict) {
607
+ return strict.raw[0] === '"' ? decodeEscapes(strict.raw.slice(1, -1), false) : strict.raw.slice(1, -1);
608
+ }
609
+
610
+ /* ------------------------------------------------------------------ splice */
611
+
612
+ function themePath(path) {
613
+ if (path.length === 1) return path[0] === 'theme';
614
+ return path.length === 2 && path[0] === 'theme' && path[1] === 'custom';
615
+ }
616
+
617
+ // The lines the planner guarantees it will not touch: every physical line that
618
+ // is not inside a `[theme]`/`[theme.custom]` table. Exported so the splice
619
+ // invariant can be tested directly.
620
+ function opaqueLines(text, skipLines = []) {
621
+ const bom = text.startsWith(BOM) ? BOM : '';
622
+ const body = text.slice(bom.length);
623
+ const lines = splitLines(body);
624
+ const scanned = scanStatements(body, lines);
625
+ if (scanned.error) return null;
626
+ const skip = new Set(skipLines);
627
+ const headers = scanned.statements.filter((statement) => statement.kind === 'header');
628
+ const inside = new Set();
629
+ for (let index = 0; index < headers.length; index += 1) {
630
+ if (!themePath(headers[index].path)) continue;
631
+ const from = headers[index].line;
632
+ const to = index + 1 < headers.length ? headers[index + 1].line - 1 : lines.length;
633
+ for (let line = from; line <= to; line += 1) inside.add(line);
634
+ }
635
+ const opaque = [];
636
+ for (let line = 1; line <= lines.length; line += 1) {
637
+ if (inside.has(line) || skip.has(line)) continue;
638
+ opaque.push({ content: lines[line - 1].content, eol: lines[line - 1].eol });
639
+ }
640
+ return opaque;
641
+ }
642
+
643
+ // The invariant itself: the opaque lines of the output equal the input's, except
644
+ // that the last one may GAIN the single line terminator needed to append a table.
645
+ function spliceInvariant(beforeText, afterText, skipBeforeLines = []) {
646
+ const before = opaqueLines(beforeText, skipBeforeLines);
647
+ const after = opaqueLines(afterText);
648
+ if (before === null || after === null) return false;
649
+ if (before.length !== after.length) return false;
650
+ for (let index = 0; index < before.length; index += 1) {
651
+ if (before[index].content !== after[index].content) return false;
652
+ if (index === before.length - 1) {
653
+ // The file's tail: appending a table may add the one terminator that ends
654
+ // an unterminated last line, and clearing may take it back again. Any
655
+ // other change to a terminator is a splice.
656
+ if (before[index].eol !== after[index].eol && beforeText.endsWith('\n')) return false;
657
+ continue;
658
+ }
659
+ if (before[index].eol !== after[index].eol) return false;
660
+ }
661
+ return true;
662
+ }
663
+
664
+ /* ------------------------------------------------------------------- plan */
665
+
666
+ function planThemeConfig(rawText, projection) {
667
+ const invalid = invalidProjection(projection);
668
+ if (invalid) return { ok: false, error: invalid };
669
+ if (typeof rawText !== 'string') {
670
+ return { ok: false, error: 'Unsupported Herdr config: expected text; no changes proposed.' };
671
+ }
672
+
673
+ // A UTF-8 BOM is part of the file the user owns: skip it while scanning and
674
+ // put it back byte for byte.
675
+ const bom = rawText.startsWith(BOM) ? BOM : '';
676
+ const body = rawText.slice(bom.length);
677
+ const lines = splitLines(body);
678
+ const documentEol = (lines.find((line) => line.eol !== '') ?? { eol: '\n' }).eol;
679
+
680
+ // Structural, not semantic: these characters break the line model itself.
681
+ const control = CONTROL_CHARACTERS.exec(body);
682
+ if (control) return { ok: false, error: fail(lineIndexAt(lines, control.index) + 1, 'unsupported control character') };
683
+ const carriageReturn = BARE_CARRIAGE_RETURN.exec(body);
684
+ if (carriageReturn) {
685
+ return { ok: false, error: fail(lineIndexAt(lines, carriageReturn.index) + 1, 'a bare carriage return is not a line ending') };
686
+ }
687
+
688
+ const scanned = scanStatements(body, lines);
689
+ if (scanned.error) return { ok: false, error: scanned.error };
690
+ const { statements } = scanned;
691
+ const kindByLine = new Map(statements.map((statement) => [statement.line, statement.kind]));
692
+ const isCommentLine = (line) => kindByLine.get(line) === 'comment';
693
+
694
+ // ---- pass 1: sections, theme tables, our block.
695
+ let section = 'root';
696
+ let themeHeader = -1;
697
+ let customHeader = -1;
698
+ let customLastKeyLine = -1;
699
+ let customHasOtherContent = false;
700
+ let blockBegin = -1;
701
+ let blockEnd = -1;
702
+ let blockCreated = false;
703
+ let blockAddedEof = false;
704
+ let nameField = null;
705
+ const userTokens = new Map();
706
+ const blockTokens = new Map();
707
+ const themeKeys = new Set();
708
+ const customKeys = new Set();
709
+ const legacyBegin = [];
710
+ const legacyEnd = [];
711
+
712
+ const fieldOf = (statement) => ({
713
+ keyLine: statement.line,
714
+ lastLine: statement.lastLine,
715
+ indent: indentOf(lines[statement.line - 1].content),
716
+ lineText: lines[statement.line - 1].content.slice(indentOf(lines[statement.line - 1].content).length),
717
+ // A multi-line STRING form can sit on one physical line; it still cannot be
718
+ // recorded as one original line.
719
+ multiline: statement.lastLine !== statement.line
720
+ || (statement.valueStart !== null && /^["']{3}/.test(body.slice(statement.valueStart, statement.valueStart + 3))),
721
+ });
722
+
723
+ for (const statement of statements) {
724
+ if (statement.kind === 'comment') {
725
+ const trimmed = statement.text.trim();
726
+ if (section === 'theme.custom') {
727
+ if (trimmed === BLOCK_BEGIN || trimmed === BLOCK_BEGIN_CREATED) {
728
+ if (blockBegin >= 0) return { ok: false, error: fail(statement.line, 'the `# herdr-gentle-shell: begin` line appears more than once') };
729
+ blockBegin = statement.line;
730
+ blockCreated = trimmed === BLOCK_BEGIN_CREATED;
731
+ } else if (trimmed === BLOCK_END || trimmed === BLOCK_END_ADDED) {
732
+ blockAddedEof = trimmed === BLOCK_END_ADDED;
733
+ if (blockBegin < 0 || blockEnd >= 0) {
734
+ return { ok: false, error: fail(statement.line, 'the `# herdr-gentle-shell: end` line has no matching begin') };
735
+ }
736
+ blockEnd = statement.line;
737
+ }
738
+ }
739
+ if (section === 'theme.custom' && blockBegin >= 0 && blockEnd < 0
740
+ && statement.line !== blockBegin && statement.line !== blockEnd) {
741
+ // Between begin and end only our own `<token> = "#rrggbb"` lines are ours.
742
+ // A comment there would be deleted by the rewrite, so it is a refusal.
743
+ return { ok: false, error: fail(statement.line, 'unexpected content inside the herdr-gentle-shell block') };
744
+ }
745
+ if (section === 'theme.custom' && trimmed !== BLOCK_BEGIN && trimmed !== BLOCK_BEGIN_CREATED
746
+ && trimmed !== BLOCK_END && trimmed !== BLOCK_END_ADDED) {
747
+ customHasOtherContent = true;
748
+ }
749
+ if (trimmed === LEGACY_BEGIN) legacyBegin.push(statement.line);
750
+ else if (trimmed === LEGACY_END) legacyEnd.push(statement.line);
751
+ continue;
752
+ }
753
+
754
+ if (statement.kind === 'header') {
755
+ if (blockBegin >= 0 && blockEnd < 0) {
756
+ return { ok: false, error: fail(statement.line, 'the `# herdr-gentle-shell` block is not terminated') };
757
+ }
758
+ const path = statement.path;
759
+ if (path[0] !== 'theme') {
760
+ section = 'other';
761
+ continue;
762
+ }
763
+ if (statement.array) {
764
+ return { ok: false, error: fail(statement.line, `\`[[${path.join('.')}]]\` array-of-tables is not supported`) };
765
+ }
766
+ if (path.length === 1) {
767
+ if (themeHeader >= 0) return { ok: false, error: fail(statement.line, '`[theme]` appears more than once') };
768
+ themeHeader = statement.line;
769
+ section = 'theme';
770
+ continue;
771
+ }
772
+ if (path.length === 2 && path[1] === 'custom') {
773
+ if (customHeader >= 0) return { ok: false, error: fail(statement.line, '`[theme.custom]` appears more than once') };
774
+ customHeader = statement.line;
775
+ section = 'theme.custom';
776
+ continue;
777
+ }
778
+ return { ok: false, error: fail(statement.line, `\`[${path.join('.')}]\` is not a table this writer owns`) };
779
+ }
780
+
781
+ if (statement.kind === 'blank' && section === 'theme.custom') {
782
+ if (blockBegin >= 0 && blockEnd < 0) {
783
+ // A whitespace-only line inside our block is not ours either.
784
+ return { ok: false, error: fail(statement.line, 'unexpected content inside the herdr-gentle-shell block') };
785
+ }
786
+ customHasOtherContent = true;
787
+ continue;
788
+ }
789
+ if (statement.kind !== 'content') continue;
790
+ if (section === 'root' && statement.keys && statement.keys[0] === 'theme') {
791
+ return {
792
+ ok: false,
793
+ error: fail(statement.line, statement.keys.length === 1 ? 'a top-level `theme` key is user configuration' : 'a dotted `theme` key cannot be adopted safely'),
794
+ };
795
+ }
796
+ if (section !== 'theme' && section !== 'theme.custom') continue;
797
+
798
+ const lineContent = lines[statement.line - 1].content;
799
+ const single = statement.lastLine === statement.line;
800
+ const strict = single ? parseThemeLine(lineContent) : { kind: 'other' };
801
+ const keys = statement.keys;
802
+ const keyName = keys && keys.length >= 1 ? keys[0] : null;
803
+
804
+ if (section === 'theme.custom' && blockBegin >= 0 && blockEnd < 0) {
805
+ // Inside our block ONLY our own `<token> = "#rrggbb"` lines are ours. A
806
+ // human line is never deleted, so anything else is a refusal.
807
+ const match = /^([a-z0-9_]+) = "(#[0-9a-fA-F]{6})"$/.exec(lineContent.trim());
808
+ if (!single || !match || !HERDR_TOKEN_ORDER.includes(match[1])) {
809
+ return { ok: false, error: fail(statement.line, 'unexpected content inside the herdr-gentle-shell block') };
810
+ }
811
+ if (blockTokens.has(match[1])) {
812
+ return { ok: false, error: fail(statement.line, `\`${match[1]}\` appears more than once in \`[theme.custom]\``) };
813
+ }
814
+ blockTokens.set(match[1], { line: statement.line });
815
+ continue;
816
+ }
817
+
818
+ if (section === 'theme') {
819
+ if (keyName === null) continue;
820
+ const dotted = keys.length > 1;
821
+ if (dotted && THEME_OWNED_KEYS.has(keyName)) {
822
+ return { ok: false, error: fail(statement.line, 'a dotted key extending `[theme]` cannot be adopted safely') };
823
+ }
824
+ if (dotted) continue;
825
+ if (THEME_KEYS_REFUSED.has(keyName)) {
826
+ return { ok: false, error: fail(statement.line, `\`${keyName}\` in \`[theme]\` is not supported`) };
827
+ }
828
+ if (keyName === 'custom') {
829
+ return { ok: false, error: fail(statement.line, '`custom` in `[theme]` must be a `[theme.custom]` table') };
830
+ }
831
+ if (keyName === 'auto_switch' || keyName === 'name') {
832
+ if (themeKeys.has(keyName)) {
833
+ return { ok: false, error: fail(statement.line, `\`${keyName}\` appears more than once in \`[theme]\``) };
834
+ }
835
+ themeKeys.add(keyName);
836
+ }
837
+ if (keyName === 'auto_switch') {
838
+ // The reference refuses this line outright, which is why the user's real
839
+ // config (auto_switch = false) was never written. Accept it untouched.
840
+ if (strict.kind !== 'key' || strict.raw !== 'false') {
841
+ return { ok: false, error: fail(statement.line, '`auto_switch` is only supported as `auto_switch = false`') };
842
+ }
843
+ continue;
844
+ }
845
+ if (keyName === 'name') {
846
+ if (strict.kind !== 'key' || strict.valueKind !== 'string') {
847
+ return { ok: false, error: fail(statement.line, '`name` value is not a plain single-line string') };
848
+ }
849
+ nameField = { ...fieldOf(statement), strict, value: decodedStringValue(strict) };
850
+ }
851
+ continue;
852
+ }
853
+
854
+ // [theme.custom]
855
+ if (keyName === null) {
856
+ customHasOtherContent = true;
857
+ continue;
858
+ }
859
+ if (keys.length > 1 && HERDR_TOKEN_ORDER.includes(keyName)) {
860
+ return { ok: false, error: fail(statement.line, 'a dotted key extending `[theme.custom]` cannot be adopted safely') };
861
+ }
862
+ if (keys.length > 1) {
863
+ customHasOtherContent = true;
864
+ continue;
865
+ }
866
+ customLastKeyLine = statement.lastLine;
867
+ if (!HERDR_TOKEN_ORDER.includes(keyName)) {
868
+ customHasOtherContent = true;
869
+ continue;
870
+ }
871
+ if (customKeys.has(keyName)) {
872
+ return { ok: false, error: fail(statement.line, `\`${keyName}\` appears more than once in \`[theme.custom]\``) };
873
+ }
874
+ customKeys.add(keyName);
875
+ userTokens.set(keyName, { ...fieldOf(statement), strict, value: strict.kind === 'key' && strict.valueKind === 'string' ? decodedStringValue(strict) : null });
876
+ }
877
+
878
+ if (blockBegin >= 0 && blockEnd < 0) {
879
+ return { ok: false, error: fail(blockBegin, 'the `# herdr-gentle-shell` block is not terminated') };
880
+ }
881
+ for (const [token, field] of blockTokens) {
882
+ const user = userTokens.get(token);
883
+ if (user) return { ok: false, error: fail(user.keyLine, `\`${token}\` appears more than once in \`[theme.custom]\``) };
884
+ void field;
885
+ }
886
+
887
+ // ---- legacy 1.8.0 marker pairing: nearest preceding BEGIN, theme table inside.
888
+ const dropped = new Set();
889
+ const legacyDroppedLines = [];
890
+ {
891
+ const open = [];
892
+ for (const statement of statements) {
893
+ if (statement.kind !== 'comment') continue;
894
+ const trimmed = statement.text.trim();
895
+ if (trimmed === LEGACY_BEGIN) {
896
+ open.push(statement.line);
897
+ continue;
898
+ }
899
+ if (trimmed !== LEGACY_END) continue;
900
+ const begin = open.pop();
901
+ if (begin === undefined) continue;
902
+ const enclosesTheme = statements.some(
903
+ (candidate) => candidate.kind === 'header' && candidate.line > begin && candidate.line < statement.line && themePath(candidate.path),
904
+ );
905
+ if (!enclosesTheme) continue;
906
+ dropped.add(begin - 1);
907
+ dropped.add(statement.line - 1);
908
+ legacyDroppedLines.push(begin, statement.line);
909
+ }
910
+ }
911
+
912
+ const desired = new Map(Object.entries(projection.custom ?? {}));
913
+ const replaced = new Map();
914
+ const insertBefore = new Map();
915
+ const insertAfter = new Map();
916
+
917
+ const replaceValue = (field, raw) => {
918
+ const content = lines[field.keyLine - 1].content;
919
+ replaced.set(field.keyLine - 1, content.slice(0, field.strict.valueStart) + raw + content.slice(field.strict.valueEnd));
920
+ };
921
+ const restoreLine = (field, marker) => {
922
+ // A restore gives the user's original line back, but their LATEST edit wins:
923
+ // the key/value part comes from the recorded line, the trailing whitespace
924
+ // and inline comment from the line as it is now when they differ (E: a user
925
+ // who edits the comment after we wrote the value must keep their comment).
926
+ const payload = marker.payload;
927
+ const stored = parseThemeLine(payload);
928
+ const current = field.strict;
929
+ let restored = payload;
930
+ if (stored.kind === 'key' && current.kind === 'key') {
931
+ const currentTrailing = lines[field.keyLine - 1].content.slice(current.valueEnd);
932
+ // Only an explicit comment/whitespace on the line now counts as an edit;
933
+ // an empty tail says nothing, so the recorded bytes (D: exact restore) win.
934
+ if (currentTrailing.trim() !== '' && currentTrailing !== payload.slice(stored.valueEnd)) {
935
+ restored = payload.slice(0, stored.valueEnd) + currentTrailing;
936
+ }
937
+ }
938
+ replaced.set(field.keyLine - 1, field.indent + restored);
939
+ for (let line = field.keyLine; line < field.lastLine; line += 1) dropped.add(line);
940
+ };
941
+
942
+ const addMarker = (field, marker) => {
943
+ if (!insertBefore.has(field.keyLine - 1)) insertBefore.set(field.keyLine - 1, []);
944
+ insertBefore.get(field.keyLine - 1).push(`${field.indent}${WAS_PREFIX}${marker}`);
945
+ };
946
+ const cannotRecord = (field, key) => fail(field.keyLine, `cannot record the original value of \`${key}\` safely`);
947
+
948
+ // Rule 1: the theme name, in place, or inserted right after its header.
949
+ if (nameField) {
950
+ const markers = markersAbove(lines, isCommentLine, nameField.keyLine, 'name');
951
+ if (markers.length > 1) {
952
+ return { ok: false, error: fail(markers[0].line, 'duplicate herdr-gentle-shell marker for `name`') };
953
+ }
954
+ const marker = markers.length === 1 ? markers[0] : null;
955
+ if (marker && marker.value === projection.name) {
956
+ // The projection is back to the value the user originally had: give the
957
+ // ORIGINAL line back (its quoting, spacing and comment) and drop the marker.
958
+ restoreLine(nameField, marker);
959
+ dropped.add(marker.line - 1);
960
+ } else if (nameField.value !== projection.name) {
961
+ if (nameField.strict.kind !== 'key' || nameField.strict.valueKind !== 'string') {
962
+ return { ok: false, error: fail(nameField.keyLine, '`name` value is not a plain single-line string') };
963
+ }
964
+ // A line we cannot record on one comment line is refused, not half-recorded.
965
+ if (!marker && UNRECORDABLE.test(nameField.lineText)) {
966
+ return { ok: false, error: cannotRecord(nameField, 'name') };
967
+ }
968
+ replaceValue(nameField, `"${projection.name}"`);
969
+ if (!marker) addMarker(nameField, nameField.lineText);
970
+ }
971
+ } else if (themeHeader >= 0) {
972
+ insertAfter.set(themeHeader - 1, [`name = "${projection.name}"`]);
973
+ } else if (blockBegin >= 0 || customHeader >= 0) {
974
+ // A theme name that no table carries is appended at the end (see below).
975
+ }
976
+
977
+ // Rule 2 + reconciliation.
978
+ const blockLines = [];
979
+ for (const token of HERDR_TOKEN_ORDER) {
980
+ const wanted = desired.get(token);
981
+ const user = userTokens.get(token);
982
+ if (!user) {
983
+ if (wanted !== undefined) blockLines.push(`${token} = "${wanted}"`);
984
+ continue;
985
+ }
986
+ const markers = markersAbove(lines, isCommentLine, user.keyLine, token);
987
+ if (markers.length > 1) {
988
+ return { ok: false, error: fail(markers[0].line, `duplicate herdr-gentle-shell marker for \`${token}\``) };
989
+ }
990
+ const marker = markers.length === 1 ? markers[0] : null;
991
+ if (marker === null && wanted === undefined) continue;
992
+ if (user.strict.kind !== 'key' || user.strict.valueKind !== 'string') {
993
+ // This line would be replaced or dropped, and the user edited it since (a
994
+ // multi-line value, for instance). Refuse: never delete the user's bytes.
995
+ return {
996
+ ok: false,
997
+ error: user.multiline
998
+ ? cannotRecord(user, token)
999
+ : fail(user.keyLine, `\`${token}\` value is not a plain single-line string`),
1000
+ };
1001
+ }
1002
+ if (marker !== null && marker.value === wanted) {
1003
+ // Back to the user's original value: restore the line verbatim (quoting,
1004
+ // spacing, inline comment) and forget the marker.
1005
+ restoreLine(user, marker);
1006
+ dropped.add(marker.line - 1);
1007
+ continue;
1008
+ }
1009
+ if (wanted === undefined) {
1010
+ restoreLine(user, marker);
1011
+ dropped.add(marker.line - 1);
1012
+ continue;
1013
+ }
1014
+ if (user.value === wanted) continue;
1015
+ if (!marker && UNRECORDABLE.test(user.lineText)) {
1016
+ return { ok: false, error: cannotRecord(user, token) };
1017
+ }
1018
+ replaceValue(user, `"${wanted}"`);
1019
+ if (!marker) addMarker(user, user.lineText);
1020
+ }
1021
+
1022
+ const willAppendEof = (!nameField && themeHeader < 0) || (customHeader < 0 && blockLines.length > 0);
1023
+ const createdFlag = blockCreated || customHeader < 0;
1024
+ // Does this plan append a table after an unterminated last line, i.e. add the
1025
+ // file's missing final line ending? Only then may a later clear take it back.
1026
+ const lastIndex = lines.length - 1;
1027
+ // Lines this plan puts AFTER the document's last line force that line's
1028
+ // terminator: an append at EOF, a name inserted below an unterminated header,
1029
+ // or a block inserted below the last user key.
1030
+ const blockAnchor = customLastKeyLine > 0 ? customLastKeyLine - 1 : customHeader - 1;
1031
+ const insertAfterLast = insertAfter.has(lastIndex)
1032
+ || (blockLines.length > 0 && customHeader >= 0 && blockAnchor === lastIndex);
1033
+ const addsEofTerminator = lines.length > 0 && !dropped.has(lastIndex)
1034
+ && lines[lastIndex].eol === '' && (willAppendEof || insertAfterLast);
1035
+ // Where the block is (or was) placed, did that add the file's missing final
1036
+ // line ending? Once the block exists its end line is the only record; while it
1037
+ // is being placed this plan knows it directly. (An unchanged block is never
1038
+ // rewritten just to restate its spelling.)
1039
+ const eofMarked = blockBegin >= 0 ? blockAddedEof : addsEofTerminator;
1040
+ const beginLine = createdFlag ? BLOCK_BEGIN_CREATED : BLOCK_BEGIN;
1041
+ const endLine = eofMarked ? BLOCK_END_ADDED : BLOCK_END;
1042
+ const blockWanted = [];
1043
+ if (blockLines.length > 0) blockWanted.push(beginLine, ...blockLines, endLine);
1044
+
1045
+ if (blockBegin >= 0) {
1046
+ const actual = [];
1047
+ for (let line = blockBegin; line <= blockEnd; line += 1) actual.push(lines[line - 1].content);
1048
+ const sameBlock = actual.length === blockWanted.length && actual.every((text, index) => text === blockWanted[index]);
1049
+ if (!sameBlock) {
1050
+ // Removing or moving the block makes a comment that sat above `begin`
1051
+ // adjacent to the key below it. If that comment would parse as a marker
1052
+ // for that key, the next plan would promote the user's ordinary comment to
1053
+ // ownership (silently restoring an old colour and eating the comment), so
1054
+ // the shape is ambiguous and this plan refuses instead of guessing.
1055
+ const ambiguous = ambiguousMarkerAbove(lines, statements, isCommentLine, blockBegin, blockEnd);
1056
+ if (ambiguous >= 0) {
1057
+ return { ok: false, error: fail(ambiguous, 'ambiguous herdr-gentle-shell marker above the managed block') };
1058
+ }
1059
+ for (let line = blockBegin; line <= blockEnd; line += 1) dropped.add(line - 1);
1060
+ if (blockWanted.length > 0) {
1061
+ const anchor = customLastKeyLine > 0 ? customLastKeyLine - 1 : customHeader - 1;
1062
+ if (!insertAfter.has(anchor)) insertAfter.set(anchor, []);
1063
+ insertAfter.get(anchor).push(...blockWanted);
1064
+ }
1065
+ }
1066
+ } else if (blockWanted.length > 0) {
1067
+ const anchor = customLastKeyLine > 0 ? customLastKeyLine - 1 : customHeader - 1;
1068
+ if (!insertAfter.has(anchor)) insertAfter.set(anchor, []);
1069
+ insertAfter.get(anchor).push(...blockWanted);
1070
+ }
1071
+
1072
+ // A `[theme.custom]` header this planner created goes away again when its
1073
+ // block empties and the table holds nothing else, so a full cycle is byte
1074
+ // identical. A header the user wrote is never removed.
1075
+ if (blockBegin >= 0 && blockWanted.length === 0 && blockCreated && !customHasOtherContent
1076
+ && userTokens.size === 0 && customLastKeyLine === -1) {
1077
+ dropped.add(customHeader - 1);
1078
+ }
1079
+
1080
+ // Tables that do not exist yet are created at the end, theme before custom.
1081
+ const eofBlocks = [];
1082
+ if (!nameField && themeHeader < 0) eofBlocks.push(['[theme]', `name = "${projection.name}"`]);
1083
+ if (customHeader < 0 && blockWanted.length > 0) eofBlocks.push(['[theme.custom]', ...blockWanted]);
1084
+
1085
+ // Rebuild line by line. Every inserted line uses the ending of the line it is
1086
+ // attached to, so CRLF and mixed documents keep their shape.
1087
+ let text = '';
1088
+ for (let index = 0; index < lines.length; index += 1) {
1089
+ const line = lines[index];
1090
+ const eol = line.eol || documentEol;
1091
+ const before = insertBefore.get(index);
1092
+ if (before) for (const entry of before) text += entry + eol;
1093
+ if (!dropped.has(index)) text += (replaced.get(index) ?? line.content) + line.eol;
1094
+ const after = insertAfter.get(index);
1095
+ if (after) {
1096
+ if (line.eol === '') text += eol;
1097
+ for (const entry of after) text += entry + eol;
1098
+ }
1099
+ }
1100
+
1101
+ const eofEol = lines.length > 0 ? lines[lines.length - 1].eol || documentEol : documentEol;
1102
+ for (const block of eofBlocks) {
1103
+ // Appending a table adds exactly ONE terminator to end an unterminated last
1104
+ // line, and a blank separator only when the file already ended with one.
1105
+ if (text.length > 0 && !text.endsWith('\n')) text += eofEol;
1106
+ for (const line of block) text += line + eofEol;
1107
+ }
1108
+
1109
+ // A document without a final newline keeps having none, and the removed line
1110
+ // ending must be the whole ending: stripping a bare "\n" from "\r\n" would
1111
+ // leave a lone CR and an invalid file.
1112
+ const unterminated = rawText.length > 0 && !rawText.endsWith('\n');
1113
+ // ...only when THIS planner is the one that added the ending (it is appending
1114
+ // a table after an unterminated last line now, or the created block records
1115
+ // that it did). A user's own unterminated line that merely sat above a block
1116
+ // we removed keeps its bytes, and a legacy marker at EOF owned its own ending.
1117
+ const addedEofTerminator = addsEofTerminator || blockAddedEof;
1118
+ if (unterminated && addedEofTerminator && !legacyDroppedLines.includes(lines.length) && /\r?\n$/.test(text)) {
1119
+ text = text.replace(/\r?\n$/, '');
1120
+ }
1121
+
1122
+ const result = bom + text;
1123
+ if (result !== rawText && !spliceInvariant(rawText, result, legacyDroppedLines)) {
1124
+ return { ok: false, error: 'internal splice invariant violated; no changes proposed.' };
1125
+ }
1126
+ return { ok: true, text: result, changed: result !== rawText };
1127
+ }
1128
+
1129
+ module.exports = {
1130
+ planThemeConfig,
1131
+ opaqueLines,
1132
+ spliceInvariant,
1133
+ };