File size: 23,899 Bytes
68d7816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
import { parse as parseToml, stringify as stringifyToml } from 'smol-toml';

import { deepEqual, isPlainObject } from './configPure';

export interface DomainUpdate {
  readonly snakeKey: string;
  readonly previousValue: unknown;
  readonly nextValue: unknown;
}

type LineEdit =
  | {
      readonly type: 'replace';
      readonly startLine: number;
      readonly endLine: number;
      readonly text: string;
    }
  | { readonly type: 'insert'; readonly afterLine: number; readonly text: string };

interface RootRegion {
  readonly rootKey: string;
  start: number;
  end: number;
  dotted: boolean;
}

type RootSegment =
  | { readonly kind: 'trivia'; readonly start: number; readonly end: number }
  | { readonly kind: 'region'; readonly region: RootRegion };

interface DomainStatement {
  readonly key: string;
  readonly startLine: number;
  readonly endLine: number;
  readonly indent: string;
  readonly separator: string;
  readonly valueStart: number;
  readonly valueEnd: number;
}

interface DomainBlock {
  readonly path: readonly string[];
  readonly hasHeader: boolean;
  readonly isArray: boolean;
  readonly startLine: number;
  endLine: number;
  readonly statements: DomainStatement[];
}

interface DomainScan {
  readonly blocks: readonly DomainBlock[];
  readonly ambiguous: boolean;
}

interface KeyValueMatch {
  readonly indent: string;
  readonly keySegments: readonly string[];
  readonly dotted: boolean;
  readonly separator: string;
  readonly valueStart: number;
}

interface HeaderMatch {
  readonly rootKey: string;
  readonly path: readonly string[];
  readonly isArray: boolean;
}

const KEY_VALUE_LINE_PATTERN = /^(\s*)([A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*)(\s*=\s*)([\s\S]*)$/;
const BARE_KEY_CHAR_PATTERN = /[A-Za-z0-9_-]/;

function splitLinesKeepEnds(text: string): string[] {
  const lines: string[] = [];
  let start = 0;
  for (let i = 0; i < text.length; i++) {
    if (text[i] === '\n') {
      lines.push(text.slice(start, i + 1));
      start = i + 1;
    }
  }
  if (start < text.length) lines.push(text.slice(start));
  return lines;
}

function stripLineEnding(line: string): string {
  if (!line.endsWith('\n')) return line;
  return line.endsWith('\r\n') ? line.slice(0, -2) : line.slice(0, -1);
}

function detectEol(text: string): string {
  const index = text.indexOf('\n');
  return index > 0 && text.charAt(index - 1) === '\r' ? '\r\n' : '\n';
}

function isTriviaBody(body: string): boolean {
  const trimmed = body.trim();
  return trimmed.length === 0 || trimmed.startsWith('#');
}

function lineIndexAt(offsets: readonly number[], position: number): number {
  let low = 0;
  let high = offsets.length - 1;
  let result = 0;
  while (low <= high) {
    const mid = (low + high) >> 1;
    if (offsets[mid]! <= position) {
      result = mid;
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }
  return result;
}

function lineStartOffsets(lines: readonly string[]): number[] {
  const offsets: number[] = [];
  let offset = 0;
  for (const line of lines) {
    offsets.push(offset);
    offset += line.length;
  }
  return offsets;
}

function scanStringEnd(text: string, offset: number): number | undefined {
  const quote = text.charAt(offset);
  if (text.startsWith(quote + quote + quote, offset)) {
    let i = offset + 3;
    while (i < text.length) {
      if (quote === '"' && text.charAt(i) === '\\') {
        i += 2;
        continue;
      }
      if (text.charAt(i) === quote) {
        let run = 0;
        while (i + run < text.length && text.charAt(i + run) === quote) run++;
        if (run >= 3) return i + run;
        i += run;
        continue;
      }
      i++;
    }
    return undefined;
  }
  let i = offset + 1;
  while (i < text.length) {
    if (text.charAt(i) === '\n') return undefined;
    if (quote === '"' && text.charAt(i) === '\\') {
      i += 2;
      continue;
    }
    if (text.charAt(i) === quote) return i + 1;
    i++;
  }
  return undefined;
}

function scanBalanced(text: string, offset: number, open: string, close: string): number | undefined {
  let depth = 0;
  let i = offset;
  while (i < text.length) {
    const ch = text.charAt(i);
    if (ch === '"' || ch === "'") {
      const end = scanStringEnd(text, i);
      if (end === undefined) return undefined;
      i = end;
      continue;
    }
    if (ch === open) {
      depth++;
    } else if (ch === close) {
      depth--;
      if (depth === 0) return i + 1;
    } else if (ch === '\n' && open === '{') {
      return undefined;
    }
    i++;
  }
  return undefined;
}

function scanValueEnd(text: string, offset: number): number | undefined {
  const first = text.charAt(offset);
  if (first === '"' || first === "'") return scanStringEnd(text, offset);
  if (first === '[') return scanBalanced(text, offset, '[', ']');
  if (first === '{') return scanBalanced(text, offset, '{', '}');
  let i = offset;
  while (i < text.length) {
    const ch = text.charAt(i);
    if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n' || ch === '#') break;
    i++;
  }
  return i === offset ? undefined : i;
}

function decodeBasicEscape(body: string, offset: number): { char: string; end: number } | undefined {
  const code = body.charAt(offset + 1);
  switch (code) {
    case 'b':
      return { char: '\b', end: offset + 2 };
    case 't':
      return { char: '\t', end: offset + 2 };
    case 'n':
      return { char: '\n', end: offset + 2 };
    case 'f':
      return { char: '\f', end: offset + 2 };
    case 'r':
      return { char: '\r', end: offset + 2 };
    case '"':
      return { char: '"', end: offset + 2 };
    case '\\':
      return { char: '\\', end: offset + 2 };
    case 'u':
      return decodeUnicodeEscape(body, offset, 4);
    case 'U':
      return decodeUnicodeEscape(body, offset, 8);
    default:
      return undefined;
  }
}

function decodeUnicodeEscape(
  body: string,
  offset: number,
  digits: number,
): { char: string; end: number } | undefined {
  const hex = body.slice(offset + 2, offset + 2 + digits);
  if (hex.length !== digits || !/^[0-9a-fA-F]+$/.test(hex)) return undefined;
  const codePoint = Number.parseInt(hex, 16);
  if (codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff)) return undefined;
  return { char: String.fromCodePoint(codePoint), end: offset + 2 + digits };
}

function skipInlineWhitespace(body: string, offset: number): number {
  let i = offset;
  while (i < body.length) {
    const ch = body.charAt(i);
    if (ch !== ' ' && ch !== '\t') break;
    i++;
  }
  return i;
}

interface HeaderSegment {
  readonly value: string;
  readonly end: number;
}

function scanBasicHeaderSegment(body: string, offset: number): HeaderSegment | undefined {
  let i = offset + 1;
  let value = '';
  while (i < body.length) {
    const ch = body.charAt(i);
    if (ch === '"') {
      if (value.length === 0) return undefined;
      return { value, end: i + 1 };
    }
    if (ch === '\\') {
      const escape = decodeBasicEscape(body, i);
      if (escape === undefined) return undefined;
      value += escape.char;
      i = escape.end;
      continue;
    }
    value += ch;
    i++;
  }
  return undefined;
}

function scanLiteralHeaderSegment(body: string, offset: number): HeaderSegment | undefined {
  const close = body.indexOf("'", offset + 1);
  if (close === -1) return undefined;
  const value = body.slice(offset + 1, close);
  if (value.length === 0) return undefined;
  return { value, end: close + 1 };
}

function scanHeaderSegment(body: string, offset: number): HeaderSegment | undefined {
  const start = skipInlineWhitespace(body, offset);
  const ch = body.charAt(start);
  if (ch === '"') return scanBasicHeaderSegment(body, start);
  if (ch === "'") return scanLiteralHeaderSegment(body, start);
  let i = start;
  while (i < body.length && BARE_KEY_CHAR_PATTERN.test(body.charAt(i))) i++;
  if (i === start) return undefined;
  return { value: body.slice(start, i), end: i };
}

function matchHeader(body: string): HeaderMatch | undefined {
  const start = skipInlineWhitespace(body, 0);
  let isArray = false;
  let i: number;
  if (body.startsWith('[[', start)) {
    isArray = true;
    i = start + 2;
  } else if (body.charAt(start) === '[') {
    i = start + 1;
  } else {
    return undefined;
  }
  const path: string[] = [];
  for (;;) {
    const segment = scanHeaderSegment(body, i);
    if (segment === undefined) return undefined;
    path.push(segment.value);
    i = skipInlineWhitespace(body, segment.end);
    const ch = body.charAt(i);
    if (ch === ']') {
      i++;
      break;
    }
    if (ch !== '.') return undefined;
    i = skipInlineWhitespace(body, i + 1);
  }
  if (isArray) {
    if (body.charAt(i) !== ']') return undefined;
    i++;
  }
  const rest = skipInlineWhitespace(body, i);
  if (rest < body.length && body.charAt(rest) !== '#') return undefined;
  return { rootKey: path[0]!, path, isArray };
}

function matchKeyValue(body: string): KeyValueMatch | undefined {
  const match = KEY_VALUE_LINE_PATTERN.exec(body);
  if (match === null) return undefined;
  const keySegments = match[2]!.split('.');
  return {
    indent: match[1]!,
    keySegments,
    dotted: keySegments.length > 1,
    separator: match[3]!,
    valueStart: body.length - match[4]!.length,
  };
}

interface ScannedDocument {
  lines: string[];
  offsets: number[];
  eol: string;
  segments: RootSegment[];
}

function scanRootRegions(text: string): ScannedDocument | undefined {
  const lines = splitLinesKeepEnds(text);
  const offsets = lineStartOffsets(lines);
  const eol = detectEol(text);
  const segments: RootSegment[] = [];
  let region: RootRegion | undefined;
  let triviaStart = -1;
  let i = 0;
  while (i < lines.length) {
    const body = stripLineEnding(lines[i]!);
    if (isTriviaBody(body)) {
      if (triviaStart < 0) triviaStart = i;
      i++;
      continue;
    }
    if (triviaStart >= 0) {
      segments.push({ kind: 'trivia', start: triviaStart, end: i - 1 });
      triviaStart = -1;
    }
    const header = matchHeader(body);
    if (header !== undefined) {
      if (region === undefined || region.rootKey !== header.rootKey) {
        if (region !== undefined) segments.push({ kind: 'region', region });
        region = { rootKey: header.rootKey, start: i, end: i, dotted: false };
      } else {
        region.end = i;
      }
      i++;
      continue;
    }
    const kv = matchKeyValue(body);
    if (kv === undefined) return undefined;
    const valueStart = offsets[i]! + kv.valueStart;
    const valueEnd = scanValueEnd(text, valueStart);
    if (valueEnd === undefined) return undefined;
    const endLine = lineIndexAt(offsets, valueEnd - 1);
    const rootKey = region === undefined ? kv.keySegments[0]! : region.rootKey;
    if (region === undefined || region.rootKey !== rootKey) {
      if (region !== undefined) segments.push({ kind: 'region', region });
      region = { rootKey, start: i, end: endLine, dotted: kv.dotted };
    } else {
      region.end = endLine;
      region.dotted = region.dotted || kv.dotted;
    }
    i = endLine + 1;
  }
  if (triviaStart >= 0) segments.push({ kind: 'trivia', start: triviaStart, end: lines.length - 1 });
  if (region !== undefined) segments.push({ kind: 'region', region });
  return { lines, offsets, eol, segments };
}

function scanDomainRegion(
  text: string,
  lines: readonly string[],
  offsets: readonly number[],
  region: RootRegion,
  snakeKey: string,
): DomainScan | undefined {
  const blocks: DomainBlock[] = [];
  let ambiguous = false;
  let current: DomainBlock | undefined;
  for (let i = region.start; i <= region.end; i++) {
    const body = stripLineEnding(lines[i]!);
    if (isTriviaBody(body)) continue;
    const header = matchHeader(body);
    if (header !== undefined) {
      if (header.rootKey !== snakeKey) return undefined;
      current = {
        path: header.path.slice(1),
        hasHeader: true,
        isArray: header.isArray,
        startLine: i,
        endLine: i,
        statements: [],
      };
      if (header.isArray) ambiguous = true;
      blocks.push(current);
      continue;
    }
    const kv = matchKeyValue(body);
    if (kv === undefined) return undefined;
    if (kv.dotted) ambiguous = true;
    const valueStart = offsets[i]! + kv.valueStart;
    const valueEnd = scanValueEnd(text, valueStart);
    if (valueEnd === undefined) return undefined;
    const endLine = lineIndexAt(offsets, valueEnd - 1);
    const statement: DomainStatement = {
      key: kv.keySegments.at(-1)!,
      startLine: i,
      endLine,
      indent: kv.indent,
      separator: kv.separator,
      valueStart,
      valueEnd,
    };
    if (current === undefined) {
      current = {
        path: [],
        hasHeader: false,
        isArray: false,
        startLine: i,
        endLine,
        statements: [statement],
      };
      blocks.push(current);
    } else {
      current.statements.push(statement);
      current.endLine = endLine;
    }
    i = endLine;
  }
  return { blocks, ambiguous };
}

function pathsEqual(a: readonly string[], b: readonly string[]): boolean {
  if (a.length !== b.length) return false;
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) return false;
  }
  return true;
}

function blocksNestedUnder(blocks: readonly DomainBlock[], path: readonly string[]): readonly DomainBlock[] {
  return blocks.filter(
    (block) => block.path.length >= path.length && pathsEqual(block.path.slice(0, path.length), path),
  );
}

function removeLines(startLine: number, endLine: number): LineEdit {
  return { type: 'replace', startLine, endLine, text: '' };
}

function insertMerged(edits: LineEdit[], afterLine: number, text: string): void {
  const existing = edits.find((edit) => edit.type === 'insert' && edit.afterLine === afterLine);
  if (existing !== undefined && existing.type === 'insert') {
    edits.splice(edits.indexOf(existing), 1, { ...existing, text: existing.text + text });
    return;
  }
  edits.push({ type: 'insert', afterLine, text });
}

function statementSuffix(text: string, statement: DomainStatement): string {
  const lineEnd = text.indexOf('\n', statement.valueEnd);
  const end = lineEnd === -1 ? text.length : lineEnd;
  return text.slice(statement.valueEnd, end).replace(/\r$/, '');
}

function renderStatement(text: string, statement: DomainStatement, valueText: string, eol: string): string {
  const suffix = statementSuffix(text, statement);
  const rendered = `${statement.indent}${statement.key}${statement.separator}${valueText}${suffix}`;
  return rendered.endsWith('\n') ? rendered : `${rendered}${eol}`;
}

function serializeValueText(key: string, value: unknown): string | undefined {
  const prefix = `${key} = `;
  const serialized = stringifyToml({ [key]: value });
  if (!serialized.startsWith(prefix)) return undefined;
  const text = serialized.slice(prefix.length);
  return text.endsWith('\n') ? text.slice(0, -1) : text;
}

function serializeTableBlock(path: readonly string[], value: unknown, eol: string): string {
  let nested: unknown = value;
  for (let i = path.length - 1; i >= 0; i--) {
    nested = { [path[i]!]: nested };
  }
  return stringifyToml(nested as Record<string, unknown>).replaceAll('\n', eol);
}

function blockAnchorLine(block: DomainBlock): number {
  const last = block.statements.at(-1);
  return last === undefined ? block.startLine : last.endLine;
}

function planScalarDomainEdit(
  text: string,
  scan: DomainScan,
  update: DomainUpdate,
  eol: string,
): LineEdit[] | undefined {
  const block = scan.blocks[0];
  if (
    block === undefined ||
    scan.blocks.length !== 1 ||
    block.hasHeader ||
    block.path.length > 0 ||
    block.statements.length !== 1
  ) {
    return undefined;
  }
  const statement = block.statements[0]!;
  if (statement.key !== update.snakeKey) return undefined;
  const valueText = serializeValueText(statement.key, update.nextValue);
  if (valueText === undefined) return undefined;
  return [
    {
      type: 'replace',
      startLine: statement.startLine,
      endLine: statement.endLine,
      text: renderStatement(text, statement, valueText, eol),
    },
  ];
}

function planObjectLevel(
  text: string,
  rootKey: string,
  blocks: readonly DomainBlock[],
  prefix: readonly string[],
  previousValue: Record<string, unknown>,
  nextValue: Record<string, unknown>,
  edits: LineEdit[],
  appends: string[],
  eol: string,
): boolean {
  const block = blocks.find((candidate) => pathsEqual(candidate.path, prefix));
  const keys = [...new Set([...Object.keys(previousValue), ...Object.keys(nextValue)])];
  for (const key of keys) {
    const previous = previousValue[key];
    const next = nextValue[key];
    if (deepEqual(previous, next)) continue;
    const childPath = [...prefix, key];
    const statement = block?.statements.find((candidate) => candidate.key === key);
    const childBlock = blocks.find((candidate) => pathsEqual(candidate.path, childPath));
    if (statement !== undefined && childBlock !== undefined) return false;
    if (next === undefined) {
      if (childBlock !== undefined) {
        if (childBlock.isArray) return false;
        for (const nested of blocksNestedUnder(blocks, childPath)) {
          edits.push(removeLines(nested.startLine, nested.endLine));
        }
        continue;
      }
      if (statement === undefined) return false;
      edits.push(removeLines(statement.startLine, statement.endLine));
      continue;
    }
    if (previous === undefined) {
      if (isPlainObject(next)) {
        appends.push(serializeTableBlock([rootKey, ...childPath], next, eol));
      } else {
        const valueText = serializeValueText(key, next);
        if (valueText === undefined) return false;
        if (block !== undefined) {
          insertMerged(edits, blockAnchorLine(block), `${key} = ${valueText}${eol}`);
        } else {
          appends.push(serializeTableBlock([rootKey, ...prefix], { [key]: next }, eol));
        }
      }
      continue;
    }
    if (isPlainObject(previous) && isPlainObject(next)) {
      if (statement !== undefined || childBlock === undefined || childBlock.isArray) return false;
      if (!planObjectLevel(text, rootKey, blocks, childPath, previous, next, edits, appends, eol)) {
        return false;
      }
      continue;
    }
    if (isPlainObject(next)) {
      if (statement === undefined) return false;
      edits.push(removeLines(statement.startLine, statement.endLine));
      appends.push(serializeTableBlock([rootKey, ...childPath], next, eol));
      continue;
    }
    if (isPlainObject(previous)) {
      if (childBlock === undefined || childBlock.isArray) return false;
      for (const nested of blocksNestedUnder(blocks, childPath)) {
        edits.push(removeLines(nested.startLine, nested.endLine));
      }
      const valueText = serializeValueText(key, next);
      if (valueText === undefined) return false;
      if (block !== undefined) {
        insertMerged(edits, blockAnchorLine(block), `${key} = ${valueText}${eol}`);
      } else {
        appends.push(serializeTableBlock([rootKey, ...prefix], { [key]: next }, eol));
      }
      continue;
    }
    if (statement === undefined) return false;
    const valueText = serializeValueText(key, next);
    if (valueText === undefined) return false;
    edits.push({
      type: 'replace',
      startLine: statement.startLine,
      endLine: statement.endLine,
      text: renderStatement(text, statement, valueText, eol),
    });
  }
  return true;
}

function planDomainKeyEdit(
  text: string,
  scan: DomainScan,
  region: RootRegion,
  update: DomainUpdate,
  eol: string,
): LineEdit[] | undefined {
  if (scan.ambiguous) return undefined;
  const previousValue = update.previousValue;
  const nextValue = update.nextValue;
  if (!isPlainObject(previousValue) || !isPlainObject(nextValue)) {
    if (isPlainObject(previousValue) || isPlainObject(nextValue)) return undefined;
    return planScalarDomainEdit(text, scan, update, eol);
  }
  const edits: LineEdit[] = [];
  const appends: string[] = [];
  if (!planObjectLevel(text, update.snakeKey, scan.blocks, [], previousValue, nextValue, edits, appends, eol)) {
    return undefined;
  }
  if (appends.length > 0) {
    edits.push({ type: 'insert', afterLine: region.end, text: appends.join('') });
  }
  return edits;
}

function editPosition(edit: LineEdit): number {
  return edit.type === 'replace' ? edit.startLine : edit.afterLine + 0.5;
}

function applyLineEdits(lines: readonly string[], edits: readonly LineEdit[], eol: string): string {
  const ordered = edits.toSorted((a, b) => editPosition(b) - editPosition(a));
  const out = [...lines];
  for (const edit of ordered) {
    if (edit.type === 'replace') {
      out.splice(edit.startLine, edit.endLine - edit.startLine + 1, ...splitLinesKeepEnds(edit.text));
    } else {
      const prefix = edit.afterLine < out.length && !out[edit.afterLine]!.endsWith('\n') ? eol : '';
      out.splice(edit.afterLine + 1, 0, ...splitLinesKeepEnds(prefix + edit.text));
    }
  }
  return out.join('');
}

function verifyPlannedText(text: string, expected: Record<string, unknown>): boolean {
  if (text.trim().length === 0) return Object.keys(expected).length === 0;
  try {
    return deepEqual(parseToml(text), expected);
  } catch {
    return false;
  }
}

export function planConfigWriteback(
  originalText: string,
  updates: readonly DomainUpdate[],
  expected: Record<string, unknown>,
): string | undefined {
  const scanned = scanRootRegions(originalText);
  if (scanned === undefined) return undefined;
  const regionsByKey = new Map<string, RootRegion[]>();
  for (const segment of scanned.segments) {
    if (segment.kind !== 'region') continue;
    const list = regionsByKey.get(segment.region.rootKey);
    if (list === undefined) {
      regionsByKey.set(segment.region.rootKey, [segment.region]);
    } else {
      list.push(segment.region);
    }
  }
  const edits: LineEdit[] = [];
  const appends: string[] = [];
  for (const update of updates) {
    if (deepEqual(update.previousValue, update.nextValue)) continue;
    const regions = regionsByKey.get(update.snakeKey) ?? [];
    if (update.previousValue === undefined && regions.length > 0) return undefined;
    if (update.nextValue === undefined) {
      if (update.previousValue === undefined) continue;
      if (regions.length === 0) return undefined;
      for (const region of regions) edits.push(removeLines(region.start, region.end));
      continue;
    }
    if (regions.length === 0) {
      if (update.previousValue !== undefined) return undefined;
      appends.push(serializeTableBlock([update.snakeKey], update.nextValue, scanned.eol));
      continue;
    }
    const replacement = serializeTableBlock([update.snakeKey], update.nextValue, scanned.eol);
    if (regions.length > 1 || regions[0]!.dotted) {
      edits.push({
        type: 'replace',
        startLine: regions[0]!.start,
        endLine: regions[0]!.end,
        text: replacement,
      });
      for (const extra of regions.slice(1)) edits.push(removeLines(extra.start, extra.end));
      continue;
    }
    const region = regions[0]!;
    const scan = scanDomainRegion(originalText, scanned.lines, scanned.offsets, region, update.snakeKey);
    const planned =
      scan === undefined
        ? undefined
        : planDomainKeyEdit(originalText, scan, region, update, scanned.eol);
    if (planned === undefined) {
      edits.push({ type: 'replace', startLine: region.start, endLine: region.end, text: replacement });
      continue;
    }
    edits.push(...planned);
  }
  let text = applyLineEdits(scanned.lines, edits, scanned.eol);
  for (const block of appends) {
    if (text.length > 0 && !text.endsWith('\n')) text += scanned.eol;
    text += block;
  }
  if (!verifyPlannedText(text, expected)) return undefined;
  return text;
}