@decimalturn/toml-patch 3.3.1-dev → 3.3.1

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.
Files changed (82) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +203 -0
  3. package/dist/toml-patch.js +84 -0
  4. package/package.json +103 -16
  5. package/dist/dev/comment-alignment.js +0 -372
  6. package/dist/dev/comment-alignment.js.map +0 -1
  7. package/dist/dev/comment-ownership.js +0 -660
  8. package/dist/dev/comment-ownership.js.map +0 -1
  9. package/dist/dev/cst-source.js +0 -118
  10. package/dist/dev/cst-source.js.map +0 -1
  11. package/dist/dev/cst.js +0 -68
  12. package/dist/dev/cst.js.map +0 -1
  13. package/dist/dev/cursor.js +0 -66
  14. package/dist/dev/cursor.js.map +0 -1
  15. package/dist/dev/date-format.js +0 -287
  16. package/dist/dev/date-format.js.map +0 -1
  17. package/dist/dev/decode-utf8.js +0 -27
  18. package/dist/dev/decode-utf8.js.map +0 -1
  19. package/dist/dev/diff-lite.js +0 -108
  20. package/dist/dev/diff-lite.js.map +0 -1
  21. package/dist/dev/diff.js +0 -265
  22. package/dist/dev/diff.js.map +0 -1
  23. package/dist/dev/encode-lite.js +0 -210
  24. package/dist/dev/encode-lite.js.map +0 -1
  25. package/dist/dev/escape-preference.js +0 -166
  26. package/dist/dev/escape-preference.js.map +0 -1
  27. package/dist/dev/find-by-path.js +0 -111
  28. package/dist/dev/find-by-path.js.map +0 -1
  29. package/dist/dev/formatter.js +0 -298
  30. package/dist/dev/formatter.js.map +0 -1
  31. package/dist/dev/generate.js +0 -466
  32. package/dist/dev/generate.js.map +0 -1
  33. package/dist/dev/inline-comma-space.js +0 -13
  34. package/dist/dev/inline-comma-space.js.map +0 -1
  35. package/dist/dev/inline-format.js +0 -106
  36. package/dist/dev/inline-format.js.map +0 -1
  37. package/dist/dev/inline-layout.js +0 -107
  38. package/dist/dev/inline-layout.js.map +0 -1
  39. package/dist/dev/line-ending-backslash.js +0 -320
  40. package/dist/dev/line-ending-backslash.js.map +0 -1
  41. package/dist/dev/literal-string.js +0 -46
  42. package/dist/dev/literal-string.js.map +0 -1
  43. package/dist/dev/location.js +0 -104
  44. package/dist/dev/location.js.map +0 -1
  45. package/dist/dev/parse-error.js +0 -27
  46. package/dist/dev/parse-error.js.map +0 -1
  47. package/dist/dev/parse-js.js +0 -150
  48. package/dist/dev/parse-js.js.map +0 -1
  49. package/dist/dev/parse-string.js +0 -120
  50. package/dist/dev/parse-string.js.map +0 -1
  51. package/dist/dev/parse-toml.js +0 -714
  52. package/dist/dev/parse-toml.js.map +0 -1
  53. package/dist/dev/patch-lite.js +0 -4
  54. package/dist/dev/patch-lite2.js +0 -97
  55. package/dist/dev/patch-lite2.js.map +0 -1
  56. package/dist/dev/patch.js +0 -2659
  57. package/dist/dev/patch.js.map +0 -1
  58. package/dist/dev/smol-toml-date.js +0 -61
  59. package/dist/dev/smol-toml-date.js.map +0 -1
  60. package/dist/dev/to-js.js +0 -303
  61. package/dist/dev/to-js.js.map +0 -1
  62. package/dist/dev/to-toml.js +0 -874
  63. package/dist/dev/to-toml.js.map +0 -1
  64. package/dist/dev/tokenizer.js +0 -225
  65. package/dist/dev/tokenizer.js.map +0 -1
  66. package/dist/dev/toml-document.js +0 -220
  67. package/dist/dev/toml-document.js.map +0 -1
  68. package/dist/dev/toml-format.js +0 -549
  69. package/dist/dev/toml-format.js.map +0 -1
  70. package/dist/dev/toml-patch.js +0 -94
  71. package/dist/dev/toml-patch.js.map +0 -1
  72. package/dist/dev/traverse.js +0 -61
  73. package/dist/dev/traverse.js.map +0 -1
  74. package/dist/dev/truncate.js +0 -64
  75. package/dist/dev/truncate.js.map +0 -1
  76. package/dist/dev/update-order.js +0 -235
  77. package/dist/dev/update-order.js.map +0 -1
  78. package/dist/dev/utils.js +0 -302
  79. package/dist/dev/utils.js.map +0 -1
  80. package/dist/dev/writer.js +0 -758
  81. package/dist/dev/writer.js.map +0 -1
  82. package/dist/patch-lite.d.ts +0 -18
package/dist/dev/patch.js DELETED
@@ -1,2659 +0,0 @@
1
- //! @decimalturn/toml-patch v3.3.1 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
- import { hasItem, hasItems, isComment, isDateTime, isDocument, isFloat, isInlineArray, isInlineItem, isInlineTable, isInteger, isKeyValue, isString, isTable, isTableArray } from "./cst.js";
3
- import { getSpan } from "./location.js";
4
- import { IS_BARE_KEY, createNewlineScanState } from "./tokenizer.js";
5
- import { DateFormatHelper, padFractionalSeconds } from "./date-format.js";
6
- import parseTOML from "./parse-toml.js";
7
- import { arraysEqual, datesEqual, hasTemporal, isDate, isInteger as isInteger$1, isObject, isTemporal, last, stableStringify, temporalToTomlString } from "./utils.js";
8
- import traverse from "./traverse.js";
9
- import { stripLeadingBom } from "./decode-utf8.js";
10
- import { TomlFormat, resolveTomlFormat } from "./toml-format.js";
11
- import { attachSources } from "./cst-source.js";
12
- import { findInlineContainerDepth, findInlineContainerParent, hasStructuralMultilineRows, resolveInlineContainerLayout } from "./inline-format.js";
13
- import { addExitOffset, applyBracketSpacing, applyWrites, deleteInlineContainerNeedingTighten, getExitOffsets, getPendingEnterOffsets, hasInlineContainerNeedingTighten, insert, markDirty, perLine, recalcContainerEnd, remove, replace, setInlineIndentColumn, setRootIndentWidth, shiftNode } from "./writer.js";
14
- import { escapeStringContent } from "./escape-preference.js";
15
- import { generateInlineItem, generateKey, generateKeyValue, generateString, generateTable, generateTableArray } from "./generate.js";
16
- import { arrayHadTrailingCommas, calculateTableDepth, normalizeGeneratedInlineContainerRows, normalizeInlineContainerRows, postInlineItemRemovalAdjustment, tableHadTrailingCommas } from "./formatter.js";
17
- import { positionGeneratedNestedInlineTables, prepareInsertedNestedInlineContainer } from "./inline-layout.js";
18
- import parseJS from "./parse-js.js";
19
- import toTOML, { toTOMLCursor } from "./to-toml.js";
20
- import toJS from "./to-js.js";
21
- import diff, { isAdd, isEdit, isMove, isRemove, isRename } from "./diff.js";
22
- import findByPath, { findParent, tryFindByPath } from "./find-by-path.js";
23
- import { findHostContainer, moveInlineElement, removeMember, resolveGroups } from "./comment-ownership.js";
24
- import { applyKeyOrderMoves } from "./update-order.js";
25
- import { getInlineInsertColumnDelta, normalizeInlineCommentAlignmentInString, preserveAlignedInlineCommentColumn, preserveAlignedInlineCommentForDelta, recordInlineTableCommentDelta } from "./comment-alignment.js";
26
-
27
- //#region src/patch.ts
28
- /**
29
- * Applies modifications to a TOML document by comparing an existing TOML string with updated JavaScript data.
30
- *
31
- * This function preserves formatting and comments from the existing TOML document while
32
- * applying changes from the updated data structure. It performs a diff between the existing
33
- * and updated data, then strategically applies only the necessary changes to maintain the
34
- * original document structure as much as possible.
35
- *
36
- * @param existing - The original TOML document as a string
37
- * @param updated - The updated JavaScript object with desired changes
38
- * @param format - Optional formatting options to apply to new or modified sections
39
- * @returns A new TOML string with the changes applied
40
- */
41
- function patch(existing, updated, format) {
42
- const newlineState = createNewlineScanState();
43
- const existingToml = stripLeadingBom(existing);
44
- const existing_cst = Array.from(parseTOML(existingToml, newlineState));
45
- attachSources(existing_cst, existingToml);
46
- const autoDetectedFormat = TomlFormat.autoDetectFormatWithCst(existing, existing_cst);
47
- const fmt = resolveTomlFormat(format, autoDetectedFormat);
48
- if (newlineState.mixed) {
49
- const normalized = fmt.newLine === "\r\n" ? "CRLF" : "LF";
50
- console.warn(`toml-patch: Mixed line endings detected. Line endings in the output will be normalized to ${normalized}`);
51
- }
52
- const patchedToml = patchCst(existing_cst, updated, fmt, format instanceof TomlFormat || format != null && Object.prototype.hasOwnProperty.call(format, "indentWidth"), format instanceof TomlFormat || format != null && Object.prototype.hasOwnProperty.call(format, "trailingComma")).tomlString;
53
- const withBom = (toml) => fmt.leadingBom ? `${""}${toml}` : toml;
54
- return withBom(patchedToml);
55
- }
56
- /**
57
- * Length of the existing dotted key's prefix that the edit path matches.
58
- * Only the path's RELATIVE tail (past the key's container) is eligible:
59
- * the absolute path carries the container's own key segments (e.g. the
60
- * [mbe.""] header consumes ['mbe',''] before the row key), and matching
61
- * against those keeps extra key segments when the container's key echoes
62
- * the row's — editing `mbe[""][""]` once truncated the row
63
- * `"".""."mfn31vru"` to `"".""` instead of `""` (fuzz seed 13057).
64
- */
65
- function truncationMatchLen(changePath, existingKey, containerAbsLen) {
66
- const relPath = changePath.slice(containerAbsLen);
67
- let matchLen = 0;
68
- const max = Math.min(relPath.length, existingKey.length);
69
- for (let i = 1; i <= max; i++) if (arraysEqual(relPath.slice(relPath.length - i), existingKey.slice(0, i))) matchLen = i;
70
- return matchLen;
71
- }
72
- function inlineTableAddIndex(parent, child, beforeKey) {
73
- if (beforeKey === void 0) return void 0;
74
- const childKey = child.key.value;
75
- if (childKey.length < 2) return void 0;
76
- const prefix = childKey.slice(0, -1);
77
- for (let index = 0; index < parent.items.length; index++) {
78
- const item = parent.items[index];
79
- if (!isInlineItem(item) || !isKeyValue(item.item)) continue;
80
- const existingKey = item.item.key.value;
81
- if (existingKey.length === childKey.length && arraysEqual(existingKey.slice(0, -1), prefix) && existingKey[existingKey.length - 1] === beforeKey) return index;
82
- }
83
- }
84
- /** Every node currently in `document`, seeding updateOrder's isEligibleForLeading guard. */
85
- function collectPrePatchNodes(document) {
86
- const nodes = /* @__PURE__ */ new WeakSet();
87
- const visit = (node) => {
88
- nodes.add(node);
89
- };
90
- traverse(document, {
91
- Document: visit,
92
- Table: visit,
93
- TableKey: visit,
94
- TableArray: visit,
95
- TableArrayKey: visit,
96
- KeyValue: visit,
97
- Key: visit,
98
- String: visit,
99
- Integer: visit,
100
- Float: visit,
101
- Boolean: visit,
102
- DateTime: visit,
103
- InlineArray: visit,
104
- InlineItem: visit,
105
- InlineTable: visit,
106
- Comment: visit
107
- });
108
- return nodes;
109
- }
110
- /**
111
- * updateOrder needs `updated_js`'s TOP-level key order to reflect exactly what the caller
112
- * requested — but parseJS -> formatTopLevel unconditionally hoists any inline-table/AOT-shaped
113
- * root key into its own [section]/[[array]] block via remove-then-APPEND (src/formatter.ts).
114
- * That's a genuine TOML requirement (root scalars must precede section headers) when the
115
- * value becomes an actual section, but formatTopLevel applies it to ANY nested object at the
116
- * default inlineTableStart, even when the existing document represents it as a plain inline
117
- * value with no such constraint — silently reordering it after every scalar key, regardless
118
- * of the caller's request or updateOrder.
119
- *
120
- * Fixes this by re-deriving the root key order from a throwaway, un-hoisted parse
121
- * (inlineTableStart: 0 disables the section conversion entirely) and re-keying `updated_js`'s
122
- * top level to match. Only the top-level key ORDER is affected — values, nested levels, and
123
- * the actual output format of newly-added content (still driven by `format`/`diffing_fmt`,
124
- * unrelated to this) are untouched. Only called when `format.updateOrder` is set, so it costs
125
- * nothing when the option is off.
126
- */
127
- function applyRequestedRootKeyOrder(updated, updated_js, diffing_fmt, useTemporal) {
128
- if (!isObject(updated_js)) return updated_js;
129
- const unhoisted_fmt = resolveTomlFormat({
130
- ...diffing_fmt,
131
- inlineTableStart: 0
132
- }, diffing_fmt);
133
- const unhoisted_document = parseJS(updated, unhoisted_fmt);
134
- const unhoisted_js = toJS(unhoisted_document.items, "", { temporal: useTemporal });
135
- if (!isObject(unhoisted_js)) return updated_js;
136
- const reordered = {};
137
- for (const key of Object.keys(unhoisted_js)) if (Object.prototype.hasOwnProperty.call(updated_js, key)) reordered[key] = updated_js[key];
138
- for (const key of Object.keys(updated_js)) if (!Object.prototype.hasOwnProperty.call(reordered, key)) reordered[key] = updated_js[key];
139
- return reordered;
140
- }
141
- /**
142
- * The parser's table-body loop consumes comments between consecutive [[x]] entries
143
- * as trailing children of the first entry (it sees `# comment` before the next
144
- * `[[x]]` header). This function promotes those trailing comments to Document-level
145
- * siblings so that resolveGroups can assign them to the correct entry.
146
- */
147
- function normalizeAotEntryComments(doc) {
148
- const items = doc.items;
149
- for (let i = 0; i < items.length; i++) {
150
- const item = items[i];
151
- if (!((isTable(item) || isTableArray(item)) && hasItems(item))) continue;
152
- const containerItems = item.items;
153
- let commentStart = containerItems.length;
154
- while (commentStart > 0 && isComment(containerItems[commentStart - 1])) commentStart--;
155
- if (commentStart < containerItems.length) {
156
- const nextItem = items[i + 1];
157
- if (nextItem && isTableArray(nextItem)) {
158
- const thisKey = item.key.item.value;
159
- const nextKey = nextItem.key.item.value;
160
- if (arraysEqual(thisKey, nextKey.slice(0, thisKey.length))) {
161
- const comments = containerItems.splice(commentStart);
162
- const nextIdx = items.indexOf(nextItem);
163
- for (const comment of [...comments].reverse()) items.splice(nextIdx, 0, comment);
164
- recalcContainerEnd(item);
165
- }
166
- }
167
- }
168
- }
169
- }
170
- function patchCst(existing_cst, updated, format, indentWidthExplicit = false, trailingCommaExplicit = true) {
171
- const items = [...existing_cst];
172
- updated = compactSparseArrays(updated);
173
- const useTemporal = hasTemporal(updated);
174
- let endLine = 1;
175
- let endColumn = 0;
176
- for (const item of items) {
177
- const e = item.loc.end;
178
- if (e.line > endLine || e.line === endLine && e.column > endColumn) {
179
- endLine = e.line;
180
- endColumn = e.column;
181
- }
182
- }
183
- const existing_js = toJS(items, "", { temporal: useTemporal });
184
- const existing_document = {
185
- type: "Document",
186
- loc: {
187
- start: {
188
- line: 1,
189
- column: 0
190
- },
191
- end: {
192
- line: endLine,
193
- column: endColumn
194
- }
195
- },
196
- items
197
- };
198
- setRootIndentWidth(existing_document, format.indentWidth);
199
- const diffing_inlineTableStart = format.inlineTableStart != null && format.inlineTableStart > 1 ? 1 : format.inlineTableStart;
200
- const diffing_fmt = resolveTomlFormat({
201
- ...format,
202
- inlineTableStart: diffing_inlineTableStart
203
- }, format);
204
- const updated_document = parseJS(updated, diffing_fmt);
205
- const updated_js_raw = toJS(updated_document.items, "", { temporal: useTemporal });
206
- const updated_js = format.updateOrder ? applyRequestedRootKeyOrder(updated, updated_js_raw, diffing_fmt, useTemporal) : updated_js_raw;
207
- if (!format.updateOrder && valuesEqualIterative(existing_js, updated_js)) return {
208
- tomlString: toTOML(items, format),
209
- document: existing_document
210
- };
211
- const changes = reorder(coalesceStructuralReplacements(existing_document, updated_js, diff(existing_js, updated_js, [], {
212
- updateOrder: format.updateOrder,
213
- orderSource: updated
214
- })));
215
- if (changes.length === 0) return {
216
- tomlString: toTOML(items, format),
217
- document: existing_document
218
- };
219
- const patched_document = applyChanges(existing_document, updated_document, changes, format, useTemporal, collectPrePatchNodes(existing_document), updated, indentWidthExplicit, trailingCommaExplicit);
220
- return {
221
- tomlString: normalizeInlineCommentAlignmentInString(patched_document, toTOMLCursor(patched_document.items, format), format),
222
- document: patched_document
223
- };
224
- }
225
- function valuesEqualIterative(left, right) {
226
- const pending = [[left, right]];
227
- while (pending.length > 0) {
228
- const [a, b] = pending.pop();
229
- if (typeof a === "number" && typeof b === "number" && (!Number.isFinite(a) || !Number.isFinite(b))) return false;
230
- if (typeof a === "number" && typeof b === "number" && Number.isNaN(a) && Number.isNaN(b)) return false;
231
- if (Object.is(a, b)) continue;
232
- if (isDate(a) && isDate(b)) {
233
- if (!datesEqual(a, b)) return false;
234
- continue;
235
- }
236
- if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
237
- if (Array.isArray(a) !== Array.isArray(b)) return false;
238
- if (!Array.isArray(a)) {
239
- const aPrototype = Object.getPrototypeOf(a);
240
- const bPrototype = Object.getPrototypeOf(b);
241
- if (aPrototype !== Object.prototype && aPrototype !== null || bPrototype !== Object.prototype && bPrototype !== null) return false;
242
- }
243
- const aKeys = Object.keys(a);
244
- const bKeys = Object.keys(b);
245
- if (aKeys.length !== bKeys.length) return false;
246
- for (const key of aKeys) {
247
- if (!Object.prototype.hasOwnProperty.call(b, key)) return false;
248
- pending.push([a[key], b[key]]);
249
- }
250
- }
251
- return true;
252
- }
253
- function compactSparseArrays(value) {
254
- if (Array.isArray(value)) {
255
- let changed = false;
256
- const compacted = [];
257
- for (let index = 0; index < value.length; index++) {
258
- if (!Object.prototype.hasOwnProperty.call(value, index)) {
259
- changed = true;
260
- continue;
261
- }
262
- const child = compactSparseArrays(value[index]);
263
- changed ||= child !== value[index];
264
- compacted.push(child);
265
- }
266
- return changed ? compacted : value;
267
- }
268
- if (!isObject(value)) return value;
269
- let normalized = value;
270
- for (const key of Object.keys(value)) {
271
- const child = compactSparseArrays(value[key]);
272
- if (child !== value[key]) {
273
- if (normalized === value) normalized = { ...value };
274
- normalized[key] = child;
275
- }
276
- }
277
- return normalized;
278
- }
279
- function reorder(changes) {
280
- for (let i = 0; i < changes.length; i++) {
281
- const change = changes[i];
282
- if (isRemove(change)) {
283
- const aIdx = last(change.path);
284
- const aPrefix = change.path.slice(0, -1);
285
- let j = i + 1;
286
- while (j < changes.length) {
287
- const next_change = changes[j];
288
- if (isAdd(next_change)) {
289
- if (typeof last(next_change.path) === "number" && arraysEqual(aPrefix, next_change.path.slice(0, -1))) {
290
- if (change.coordinate === "source") {
291
- let sourceRemove = -1;
292
- for (let k = j + 1; k < changes.length; k++) {
293
- const candidate = changes[k];
294
- if (isRemove(candidate) && candidate.coordinate === "source" && arraysEqual(aPrefix, candidate.path.slice(0, -1))) {
295
- sourceRemove = k;
296
- break;
297
- }
298
- }
299
- if (sourceRemove !== -1) {
300
- const sourceChange = changes.splice(sourceRemove, 1)[0];
301
- changes.splice(i, 0, sourceChange);
302
- i = -1;
303
- break;
304
- }
305
- }
306
- break;
307
- }
308
- j++;
309
- continue;
310
- }
311
- if (isMove(next_change) && next_change.key === void 0) {
312
- if (arraysEqual(aPrefix, next_change.path)) break;
313
- j++;
314
- continue;
315
- }
316
- if (!isRemove(next_change)) {
317
- j++;
318
- continue;
319
- }
320
- const bIdx = last(next_change.path);
321
- const bPrefix = next_change.path.slice(0, -1);
322
- if (typeof aIdx === "number" && typeof bIdx === "number" && arraysEqual(aPrefix, bPrefix) && bIdx > aIdx) {
323
- changes.splice(j, 1);
324
- changes.splice(i, 0, next_change);
325
- i = -1;
326
- break;
327
- }
328
- j++;
329
- }
330
- }
331
- }
332
- return changes;
333
- }
334
- /**
335
- * Merges sibling `Remove(prefix.oldKey)` + `Add(prefix.newKey)` changes that
336
- * share a common parent path into a single `Edit(prefix)` change.
337
- *
338
- * When a table/AOT is replaced by an incompatible type at a shallower path
339
- * (e.g. `[a.b]` → `a = { x = 1 }`), the object-diff sees the whole `a`
340
- * subtree disappear and a differently-shaped `a` appear, and reports it as
341
- * a `Remove` of the old child (`a.b`) plus one `Add` per key of the new
342
- * value (`a.x`) — never a single `Edit` on `a` itself, since `a` never
343
- * existed as its own JS-diff node (it was only implicit via the dotted
344
- * table key). Left alone, the generic Add handling resolves the missing
345
- * `a` container by walking up to the document root (`findParent`), silently
346
- * dropping the `a` nesting. Coalescing back into one `Edit(prefix)` routes
347
- * it through `handleStructuralEdit`, which already rebuilds the correct
348
- * nested structure from the full updated value at that path.
349
- *
350
- * Only applies when `prefix` has no literal node of its own in `original`
351
- * (it was purely implicit) — if `prefix` is an actual existing table, the
352
- * normal per-key Add/Remove handling already does the right thing.
353
- *
354
- * Also merges per-index Edit/Add/Remove changes under an existing
355
- * array-of-tables (AOT) whose updated value is still a JS array but no
356
- * longer made up entirely of plain objects (e.g. `[[i]]` → `i = [1, 2, 3]`
357
- * or `i = [9]`). An AOT entry is a Table living at the document level, not
358
- * an item inside an array node, so it can't be edited/appended/removed in
359
- * place the way the diff assumes — the whole array needs to be rebuilt via
360
- * `handleStructuralEdit`. When every element of the updated array is still
361
- * a plain object, the AOT stays an AOT and the normal per-entry handling is
362
- * left untouched.
363
- */
364
- function coalesceStructuralReplacements(original, updated_js, changes) {
365
- const consumed = /* @__PURE__ */ new Set();
366
- const coalescedEdits = [];
367
- const groups = /* @__PURE__ */ new Map();
368
- for (const change of changes) {
369
- if (!isRemove(change) && !isAdd(change)) continue;
370
- const parentPath = change.path.slice(0, -1);
371
- if (parentPath.length === 0) continue;
372
- const key = JSON.stringify(parentPath);
373
- let group = groups.get(key);
374
- if (!group) {
375
- group = {
376
- path: parentPath,
377
- removes: [],
378
- adds: []
379
- };
380
- groups.set(key, group);
381
- }
382
- (isRemove(change) ? group.removes : group.adds).push(change);
383
- }
384
- for (const group of groups.values()) {
385
- if (group.removes.length === 0 || group.adds.length === 0) continue;
386
- if (tryFindByPath(original, group.path)) continue;
387
- group.removes.forEach((change) => consumed.add(change));
388
- group.adds.forEach((change) => consumed.add(change));
389
- coalescedEdits.push({
390
- type: "Edit",
391
- path: group.path
392
- });
393
- }
394
- for (const change of changes) {
395
- if (consumed.has(change) || !isRemove(change) && !isAdd(change)) continue;
396
- const elementPath = change.path.slice(0, -1);
397
- if (elementPath.length === 0 || typeof last(elementPath) !== "number") continue;
398
- const element = tryFindByPath(original, elementPath);
399
- if (!element || !isInlineItem(element) || !isInlineTable(element.item)) continue;
400
- const siblings = changes.filter((candidate) => !consumed.has(candidate) && (isRemove(candidate) || isAdd(candidate)) && arraysEqual(candidate.path.slice(0, -1), elementPath));
401
- if (siblings.length === 0 || siblings.some((candidate) => candidate.path.length !== elementPath.length + 1)) continue;
402
- const existingKeys = new Set(element.item.items.filter(isInlineItem).map((item) => {
403
- const keyValue = isKeyValue(item.item) ? item.item : void 0;
404
- return (keyValue === null || keyValue === void 0 ? void 0 : keyValue.key.value.length) === 1 ? keyValue.key.value[0] : void 0;
405
- }).filter((key) => key !== void 0));
406
- const removedKeys = new Set(siblings.filter(isRemove).map((candidate) => last(candidate.path)));
407
- if (!siblings.some(isRemove) || !siblings.some(isAdd) || existingKeys.size !== removedKeys.size || [...existingKeys].some((key) => !removedKeys.has(key))) continue;
408
- for (const sibling of siblings) consumed.add(sibling);
409
- coalescedEdits.push({
410
- type: "Edit",
411
- path: elementPath
412
- });
413
- }
414
- const arrayPrefixes = /* @__PURE__ */ new Map();
415
- for (const change of changes) {
416
- if (consumed.has(change)) continue;
417
- if (!isEdit(change) && !isAdd(change) && !isRemove(change)) continue;
418
- if (typeof last(change.path) !== "number") continue;
419
- const prefix = change.path.slice(0, -1);
420
- if (prefix.length === 0) continue;
421
- const firstEntry = tryFindByPath(original, prefix.concat(0));
422
- if (!firstEntry || !isTableArray(firstEntry)) continue;
423
- arrayPrefixes.set(JSON.stringify(prefix), prefix);
424
- }
425
- for (const prefix of arrayPrefixes.values()) {
426
- let value = updated_js;
427
- for (const key of prefix) value = value === null || value === void 0 ? void 0 : value[key];
428
- if (!Array.isArray(value)) continue;
429
- if (value.every((el) => isObject(el))) continue;
430
- const elementChanges = changes.filter((c) => !consumed.has(c) && (isEdit(c) || isAdd(c) || isRemove(c)) && c.path.length > prefix.length && arraysEqual(c.path.slice(0, prefix.length), prefix));
431
- if (elementChanges.length < 2) continue;
432
- for (const change of elementChanges) consumed.add(change);
433
- coalescedEdits.push({
434
- type: "Edit",
435
- path: prefix
436
- });
437
- }
438
- if (consumed.size === 0) return changes;
439
- const result = changes.filter((change) => !consumed.has(change));
440
- result.push(...coalescedEdits);
441
- return result;
442
- }
443
- function preserveEscapedKeyRaw(existingRaw, keyParts, escapeSequenceUpperCase = true) {
444
- return keyParts.map((part) => IS_BARE_KEY.test(part) ? part : `"${escapeStringContent(part, existingRaw, "singleline-basic", escapeSequenceUpperCase)}"`).join(".");
445
- }
446
- function dottedKeySeparators(raw) {
447
- const separators = [];
448
- let quote;
449
- let escaped = false;
450
- for (let index = 0; index < raw.length; index++) {
451
- const character = raw[index];
452
- if (quote) {
453
- if (quote === "\"" && escaped) escaped = false;
454
- else if (quote === "\"" && character === "\\") escaped = true;
455
- else if (character === quote) quote = void 0;
456
- continue;
457
- }
458
- if (character === "\"" || character === "'") {
459
- quote = character;
460
- continue;
461
- }
462
- if (character !== ".") continue;
463
- let start = index;
464
- while (start > 0 && (raw[start - 1] === " " || raw[start - 1] === " ")) start--;
465
- let end = index + 1;
466
- while (end < raw.length && (raw[end] === " " || raw[end] === " ")) end++;
467
- separators.push(raw.slice(start, end));
468
- }
469
- return separators;
470
- }
471
- function dottedKeyParts(raw) {
472
- const parts = [];
473
- let start = 0;
474
- let quote;
475
- let escaped = false;
476
- for (let index = 0; index < raw.length; index++) {
477
- const character = raw[index];
478
- if (quote) {
479
- if (quote === "\"" && escaped) escaped = false;
480
- else if (quote === "\"" && character === "\\") escaped = true;
481
- else if (character === quote) quote = void 0;
482
- continue;
483
- }
484
- if (character === "\"" || character === "'") quote = character;
485
- else if (character === ".") {
486
- parts.push(raw.slice(start, index));
487
- start = index + 1;
488
- }
489
- }
490
- parts.push(raw.slice(start));
491
- return parts;
492
- }
493
- function preserveDottedKeySpacing(key, styleRaw) {
494
- const separators = dottedKeySeparators(styleRaw);
495
- if (separators.length === 0) return;
496
- key.raw = dottedKeyParts(key.raw).reduce((raw, part, index) => {
497
- if (index === 0) return part;
498
- return `${raw}${separators[Math.min(index - 1, separators.length - 1)]}${part}`;
499
- }, "");
500
- key.loc.end.column = key.loc.start.column + key.raw.length;
501
- }
502
- function findDottedKeyStyle(root, prefix) {
503
- let style;
504
- traverse(root, { KeyValue: (node) => {
505
- if (!style && node.key.value.length > prefix.length && arraysEqual(node.key.value.slice(0, prefix.length), prefix) && dottedKeySeparators(node.key.raw).length > 0) style = node;
506
- } });
507
- return style;
508
- }
509
- /**
510
- * Analyzes an existing float's raw text: whether it uses exponent notation and
511
- * whether its fractional part is all zeros (a "round" float such as `1.0`).
512
- */
513
- function analyzeFloatStyle(raw) {
514
- const expIndex = raw.search(/[eE]/);
515
- const mantissa = expIndex === -1 ? raw : raw.slice(0, expIndex);
516
- const dotIndex = mantissa.indexOf(".");
517
- const fraction = dotIndex === -1 ? "" : mantissa.slice(dotIndex + 1);
518
- return {
519
- hasExponent: expIndex !== -1,
520
- fractionLength: fraction.length,
521
- isRound: !/[1-9]/.test(fraction)
522
- };
523
- }
524
- /** Counts the decimal places written in a float's raw text (before any exponent). */
525
- function decimalPlacesOfRaw(raw) {
526
- const expIndex = raw.search(/[eE]/);
527
- const mantissa = expIndex === -1 ? raw : raw.slice(0, expIndex);
528
- const dotIndex = mantissa.indexOf(".");
529
- return dotIndex === -1 ? 0 : mantissa.length - dotIndex - 1;
530
- }
531
- /** Renders a value in TOML exponent notation (e.g. `1.0e11`) with at least `minimumDecimals` decimals. */
532
- function renderExponentNotation(value, minimumDecimals, uppercaseExponent = false) {
533
- const [mantissa, exponent] = value.toExponential().split(/[eE]/);
534
- const decimals = Math.max(minimumDecimals, decimalPlacesOfRaw(mantissa));
535
- return `${decimals > 0 ? Number(mantissa).toFixed(decimals) : String(Number(mantissa))}${uppercaseExponent ? "E" : "e"}${exponent.replace(/^\+/, "")}`;
536
- }
537
- /** Detects the radix and prefix of a prefixed integer literal (`0x`/`0o`/`0b`). */
538
- function integerRadixOf(raw) {
539
- if (raw.startsWith("0x")) return {
540
- radix: 16,
541
- prefix: "0x"
542
- };
543
- if (raw.startsWith("0o")) return {
544
- radix: 8,
545
- prefix: "0o"
546
- };
547
- if (raw.startsWith("0b")) return {
548
- radix: 2,
549
- prefix: "0b"
550
- };
551
- }
552
- /** Extracts the underscore grouping period: the digit count of the rightmost group. */
553
- function underscorePeriodOf(raw) {
554
- let body = raw;
555
- if (body.startsWith("+") || body.startsWith("-")) body = body.slice(1);
556
- if (body.startsWith("0x") || body.startsWith("0o") || body.startsWith("0b")) body = body.slice(2);
557
- const lastUnderscore = body.lastIndexOf("_");
558
- return lastUnderscore === -1 ? void 0 : body.length - lastUnderscore - 1;
559
- }
560
- /** Inserts an underscore every `period` digits, counted from the right. */
561
- function groupDigits(digits, period) {
562
- if (digits.length <= period) return digits;
563
- let result = "";
564
- let count = 0;
565
- for (let i = digits.length - 1; i >= 0; i--) {
566
- result = digits[i] + result;
567
- count++;
568
- if (count === period && i > 0) {
569
- result = "_" + result;
570
- count = 0;
571
- }
572
- }
573
- return result;
574
- }
575
- /** Renders an integer in the style of an existing integer literal (radix, digit case, grouping). */
576
- function renderIntegerLike(value, existingRaw) {
577
- const radixInfo = integerRadixOf(existingRaw);
578
- const period = underscorePeriodOf(existingRaw);
579
- if (radixInfo) {
580
- if (typeof value === "bigint" ? value < 0n : value < 0) return void 0;
581
- const uppercaseHex = radixInfo.radix === 16 && /[A-F]/.test(existingRaw);
582
- let digits = value.toString(radixInfo.radix);
583
- if (uppercaseHex) digits = digits.toUpperCase();
584
- return radixInfo.prefix + (period ? groupDigits(digits, period) : digits);
585
- }
586
- if (period) {
587
- const negative = typeof value === "bigint" ? value < 0n : value < 0;
588
- const abs = negative ? value.toString().slice(1) : value.toString();
589
- return (negative ? "-" : "") + groupDigits(abs, period);
590
- }
591
- }
592
- /**
593
- * Preserves formatting from the existing node when applying it to the replacement node.
594
- * This includes multiline string formats, trailing commas, DateTime formats, etc.
595
- *
596
- * @param existing - The existing node with formatting to preserve
597
- * @param replacement - The replacement node to apply formatting to
598
- */
599
- function preserveFormatting(existing, replacement, escapeSequenceUpperCase = true, minimumTimeDecimals = 0) {
600
- if (isString(existing) && isString(replacement)) {
601
- const newString = generateString(replacement.value, existing.raw, escapeSequenceUpperCase);
602
- replacement.raw = newString.raw;
603
- replacement.loc = newString.loc;
604
- }
605
- if (isDateTime(existing) && isDateTime(replacement)) {
606
- const originalRaw = existing.raw;
607
- const newValue = replacement.value;
608
- if (isTemporal(newValue)) {
609
- let raw = temporalToTomlString(newValue);
610
- if (originalRaw.includes(" ") && raw.includes("T")) raw = raw.replace("T", " ");
611
- if (/(?:\+00:00|-00:00)/.test(originalRaw) && raw.endsWith("Z")) {
612
- const offset = originalRaw.match(/([+-]00:00)/)[1];
613
- raw = raw.replace(/Z$/, offset);
614
- }
615
- raw = padFractionalSeconds(raw, minimumTimeDecimals);
616
- replacement.raw = raw;
617
- replacement.loc.end.column = replacement.loc.start.column + replacement.raw.length;
618
- } else if (DateFormatHelper.IS_TIME_ONLY.test(originalRaw) && newValue instanceof Date && newValue.getUTCFullYear() > 1) {} else {
619
- const formattedDate = DateFormatHelper.createDateWithOriginalFormat(newValue, originalRaw);
620
- replacement.value = formattedDate;
621
- replacement.raw = padFractionalSeconds(formattedDate.toISOString(), minimumTimeDecimals);
622
- replacement.loc.end.column = replacement.loc.start.column + replacement.raw.length;
623
- }
624
- }
625
- if (isFloat(existing) && isFloat(replacement) && Number.isNaN(existing.value) && Number.isNaN(replacement.value)) {
626
- const existingFloat = existing;
627
- const replacementFloat = replacement;
628
- if (existingFloat.nanSign) {
629
- replacementFloat.nanSign = "+";
630
- replacementFloat.raw = "+nan";
631
- }
632
- }
633
- if (isInteger(existing) && replacement.type === "Integer") {
634
- const existingInt = existing;
635
- const newRaw = renderIntegerLike(replacement.value, existingInt.raw);
636
- if (newRaw !== void 0) {
637
- const replacementInt = replacement;
638
- replacementInt.raw = newRaw;
639
- replacementInt.loc.end.column = replacementInt.loc.start.column + newRaw.length;
640
- }
641
- }
642
- if (isFloat(existing) && (replacement.type === "Integer" || replacement.type === "Float")) {
643
- const existingFloat = existing;
644
- const value = replacement.value;
645
- if (typeof value === "number") {
646
- const { hasExponent, fractionLength, isRound } = analyzeFloatStyle(existingFloat.raw);
647
- const valueIsIntegral = Number.isInteger(value) && !Object.is(value, -0);
648
- const replacementDecimals = decimalPlacesOfRaw(replacement.raw);
649
- let newRaw;
650
- if (hasExponent && Number.isFinite(value) && !Object.is(value, -0)) {
651
- const uppercaseExponent = existingFloat.raw.includes("E");
652
- newRaw = renderExponentNotation(value, valueIsIntegral ? Math.max(isRound ? fractionLength : 0, replacementDecimals) : replacementDecimals, uppercaseExponent);
653
- } else if (valueIsIntegral && isRound) newRaw = value.toFixed(Math.max(fractionLength, replacementDecimals));
654
- if (newRaw !== void 0) {
655
- const replacementFloat = replacement;
656
- replacementFloat.type = "Float";
657
- replacementFloat.raw = newRaw;
658
- replacementFloat.loc.end.column = replacementFloat.loc.start.column + newRaw.length;
659
- }
660
- }
661
- }
662
- if (isInlineArray(existing) && isInlineArray(replacement)) {
663
- const originalHadTrailingCommas = arrayHadTrailingCommas(existing);
664
- if (replacement.items.length > 0) {
665
- const lastItem = replacement.items[replacement.items.length - 1];
666
- if (lastItem.comma !== originalHadTrailingCommas) {
667
- lastItem.comma = originalHadTrailingCommas;
668
- if (originalHadTrailingCommas) replacement.loc.end.column += 1;
669
- }
670
- }
671
- }
672
- if (isInlineTable(existing) && isInlineTable(replacement)) {
673
- const originalHadTrailingCommas = tableHadTrailingCommas(existing);
674
- if (replacement.items.length > 0) {
675
- const lastItem = replacement.items[replacement.items.length - 1];
676
- if (lastItem.comma !== originalHadTrailingCommas) {
677
- lastItem.comma = originalHadTrailingCommas;
678
- if (originalHadTrailingCommas) replacement.loc.end.column += 1;
679
- }
680
- }
681
- }
682
- }
683
- /**
684
- * Applies a list of changes to the original TOML document CST while preserving formatting and structure.
685
- *
686
- * This function processes different types of changes (Add, Edit, Remove, Move, Rename) and applies them
687
- * to the original document in a way that maintains the existing formatting preferences, comments, and
688
- * structural elements as much as possible. Special handling is provided for different node types like
689
- * inline tables, arrays, and table arrays to ensure proper formatting consistency.
690
- *
691
- * @param original - The original TOML document CST to be modified
692
- * @param updated - The updated document CST containing new values for changes
693
- * @param changes - Array of change objects describing what modifications to apply
694
- * @param format - Formatting preferences to use for newly added elements
695
- * @returns The modified original document with all changes applied
696
- *
697
- * @example
698
- * ```typescript
699
- * const changes = [
700
- * { type: 'add', path: ['newKey'], value: 'newValue' },
701
- * { type: 'edit', path: ['existingKey'], value: 'updatedValue' }
702
- * ];
703
- * const result = applyChanges(originalDoc, updatedDoc, changes, format);
704
- * ```
705
- */
706
- function applyChanges(original, updated, changes, format, temporal = false, commentEligibleNodes = /* @__PURE__ */ new WeakSet(), rawUpdated = void 0, indentWidthExplicit = false, trailingCommaExplicit = true) {
707
- const emptiedAotKeys = /* @__PURE__ */ new Map();
708
- const materialisedTables = /* @__PURE__ */ new Set();
709
- function trackAdjacentComment(table) {
710
- const items = original.items;
711
- const idx = items.indexOf(table);
712
- if (idx > 0) {
713
- const prev = items[idx - 1];
714
- if (isComment(prev) && prev.loc.end.line + 1 === table.loc.start.line) materialisedTables.add(table);
715
- }
716
- }
717
- const absolutePathCache = /* @__PURE__ */ new WeakMap();
718
- function absolutePathOf(target) {
719
- const cached = absolutePathCache.get(target);
720
- if (cached !== void 0) return cached;
721
- const indexes = {};
722
- function walk(node, path) {
723
- if (node === target) return path;
724
- if (isKeyValue(node)) return walk(node.value, path);
725
- if (isInlineItem(node)) return walk(node.item, path);
726
- if (!hasItems(node)) return void 0;
727
- for (let i = 0; i < node.items.length; i++) {
728
- const item = node.items[i];
729
- let key = [];
730
- if (isKeyValue(item)) key = item.key.value;
731
- else if (isTable(item) || isTableArray(item)) {
732
- key = item.key.item.value;
733
- if (isTableArray(item)) {
734
- const ks = stableStringify(key);
735
- indexes[ks] = (indexes[ks] ?? -1) + 1;
736
- key = key.concat(indexes[ks]);
737
- }
738
- } else if (isInlineItem(item)) {
739
- if (isKeyValue(item.item)) key = item.item.key.value;
740
- else key = [i];
741
- }
742
- const found = walk(item, key.length ? path.concat(key) : path);
743
- if (found) return found;
744
- }
745
- }
746
- const result = walk(original, []);
747
- if (result !== void 0) absolutePathCache.set(target, result);
748
- return result;
749
- }
750
- function isPrefixMatchedNode(candidate, probe) {
751
- const kv = isKeyValue(candidate) ? candidate : isInlineItem(candidate) && isKeyValue(candidate.item) ? candidate.item : void 0;
752
- if (!kv) return false;
753
- const keyLen = kv.key.value.length;
754
- if (keyLen > probe.length) return true;
755
- return !arraysEqual(kv.key.value, probe.slice(probe.length - keyLen));
756
- }
757
- function aotEntryUsesDottedKey(styleEntry, relativeKey) {
758
- const fullKey = styleEntry.key.item.value.concat(relativeKey);
759
- if (styleEntry.items.some((item) => isKeyValue(item) && item.key.value.length > relativeKey.length && arraysEqual(item.key.value.slice(0, relativeKey.length), relativeKey))) return true;
760
- return original.items.some((item) => {
761
- if (!isTable(item) && !isTableArray(item)) return false;
762
- const key = item.key.item.value;
763
- return key.length > fullKey.length && arraysEqual(key.slice(0, fullKey.length), fullKey);
764
- });
765
- }
766
- function preserveAotEntryDottedKeys(entry, styleEntry) {
767
- const rows = [];
768
- let changed = false;
769
- for (const item of entry.items) {
770
- if (!isKeyValue(item) || !isInlineTable(item.value) || !aotEntryUsesDottedKey(styleEntry, item.key.value)) {
771
- rows.push(item);
772
- continue;
773
- }
774
- const replacementRows = [];
775
- for (const nestedItem of item.value.items) {
776
- if (!isInlineItem(nestedItem) || !isKeyValue(nestedItem.item)) continue;
777
- let nestedValue = toJS([nestedItem.item], "", { temporal });
778
- for (const key of nestedItem.item.key.value) nestedValue = nestedValue === null || nestedValue === void 0 ? void 0 : nestedValue[key];
779
- const freshValue = regenerateValue(nestedValue, format);
780
- if (freshValue !== void 0) replacementRows.push(generateKeyValue(item.key.value.concat(nestedItem.item.key.value), freshValue));
781
- }
782
- if (replacementRows.length > 0) {
783
- rows.push(...replacementRows);
784
- changed = true;
785
- } else rows.push(item);
786
- }
787
- if (!changed) return entry;
788
- const rebuilt = generateTableArray(entry.key.item.value, format.escapeSequenceUpperCase);
789
- for (const row of rows) insert(rebuilt, rebuilt, row);
790
- applyWrites(rebuilt);
791
- return rebuilt;
792
- }
793
- function findStructuralParent(root, target) {
794
- function walk(node) {
795
- if (isKeyValue(node)) return walk(node.value);
796
- if (isInlineItem(node)) return walk(node.item);
797
- if (!hasItems(node)) return void 0;
798
- const items = node.items;
799
- for (const item of items) {
800
- if (item === target) return node;
801
- if (isInlineItem(item) && item.item === target) return node;
802
- }
803
- for (const item of items) {
804
- const found = walk(isInlineItem(item) ? item.item : item);
805
- if (found) return found;
806
- }
807
- }
808
- return walk(root);
809
- }
810
- function extendKeyWithParentAndReplace(freshKV, parentKey, existing, tableParent) {
811
- const dottedKey = parentKey.concat(freshKV.key.value);
812
- const oldRaw = freshKV.key.raw;
813
- freshKV.key.value = dottedKey;
814
- freshKV.key.raw = dottedKey.map((part) => IS_BARE_KEY.test(part) ? part : JSON.stringify(part).replace(/\x7f/g, "\\u007f")).join(".");
815
- const delta = freshKV.key.raw.length - oldRaw.length;
816
- freshKV.key.loc.end.column = freshKV.key.loc.start.column + freshKV.key.raw.length;
817
- freshKV.equals += delta;
818
- shiftNode(freshKV.value, {
819
- lines: 0,
820
- columns: delta
821
- }, { first_line_only: true });
822
- if (freshKV.loc.end.line === freshKV.loc.start.line) freshKV.loc.end.column += delta;
823
- replace(original, tableParent, existing, freshKV);
824
- hoistRootKeyValueAboveTables(original, freshKV);
825
- }
826
- function extendSectionKeyInPlace(section, parentKey) {
827
- const keyNode = section.key.item;
828
- const oldRaw = keyNode.raw;
829
- const dottedKey = parentKey.concat(keyNode.value);
830
- const newRaw = dottedKey.map((part) => IS_BARE_KEY.test(part) ? part : JSON.stringify(part).replace(/\x7f/g, "\\u007f")).join(".");
831
- const delta = newRaw.length - oldRaw.length;
832
- keyNode.value = dottedKey;
833
- keyNode.raw = newRaw;
834
- keyNode.loc.end.column = keyNode.loc.start.column + newRaw.length;
835
- if (section.key.loc.end.line === section.key.loc.start.line) section.key.loc.end.column += delta;
836
- }
837
- function extendSectionKeyWithParentAndReplace(section, parentKey, existing, tableParent) {
838
- extendSectionKeyInPlace(section, parentKey);
839
- replace(original, tableParent, existing, section);
840
- }
841
- function restoreMissingKeySegments(parent_path, child, change_path) {
842
- const direct = tryFindByPath(original, parent_path);
843
- if (direct && !isPrefixMatchedNode(direct, parent_path)) return null;
844
- let prefixLen = parent_path.length;
845
- while (prefixLen > 0) {
846
- const node = tryFindByPath(original, parent_path.slice(0, prefixLen));
847
- if (node && !isPrefixMatchedNode(node, parent_path.slice(0, prefixLen))) break;
848
- prefixLen--;
849
- }
850
- const missing = parent_path.slice(prefixLen);
851
- if (missing.length === 0 || !missing.every((seg) => typeof seg === "string")) return null;
852
- if (rawUpdated !== void 0) {
853
- let jsValue = rawUpdated;
854
- for (const k of change_path) jsValue = jsValue === null || jsValue === void 0 ? void 0 : jsValue[k];
855
- if (jsValue !== void 0) {
856
- const freshValue = regenerateValue(jsValue, format);
857
- if (freshValue !== void 0) return generateKeyValue([...missing, ...child.key.value], freshValue, false, format.escapeSequenceUpperCase);
858
- }
859
- }
860
- const oldKey = child.key;
861
- const newRaw = [...missing, ...oldKey.value].map((part) => IS_BARE_KEY.test(part) ? part : JSON.stringify(part).replace(/\x7f/g, "\\u007f")).join(".");
862
- const colDelta = newRaw.length - oldKey.raw.length;
863
- oldKey.raw = newRaw;
864
- oldKey.value = [...missing, ...oldKey.value];
865
- oldKey.loc.end.column = oldKey.loc.start.column + newRaw.length;
866
- child.equals += colDelta;
867
- shiftNode(child.value, {
868
- lines: 0,
869
- columns: colDelta
870
- }, { first_line_only: true });
871
- if (child.loc.end.line === child.loc.start.line) child.loc.end.column += colDelta;
872
- return child;
873
- }
874
- const restoredInsertContainers = /* @__PURE__ */ new Set();
875
- const insertedInlineContainers = /* @__PURE__ */ new Set();
876
- const removedInlineTrailingCommas = /* @__PURE__ */ new WeakMap();
877
- function trailingCommaForAddedItem(container, detected) {
878
- return removedInlineTrailingCommas.get(container) ?? detected;
879
- }
880
- const objectMoves = [];
881
- const replacedInlineArrays = /* @__PURE__ */ new Set();
882
- const replacedInlineContainers = [];
883
- function regenerateInlineChildForParent(parent, changePath, child) {
884
- if (!isInlineArray(parent) && !isInlineTable(parent) || !isInlineItem(child)) return child;
885
- if (isInlineTable(parent) && !isKeyValue(child.item)) return child;
886
- let jsValue = rawUpdated;
887
- for (const key of changePath) jsValue = jsValue === null || jsValue === void 0 ? void 0 : jsValue[key];
888
- if (!Array.isArray(jsValue) && !isObject(jsValue)) return child;
889
- const parentDepth = findInlineContainerDepth(original, parent) ?? 0;
890
- const parentIsMultiline = perLine(parent) || parent.items.length === 0 && parent.loc.end.line > parent.loc.start.line;
891
- const generatedIndentWidth = indentWidthExplicit ? format.indentWidth : isInlineArray(parent) && parent.items.length === 0 ? Math.max(format.indentWidth, 4) : format.indentWidth;
892
- if (isInlineArray(parent) && parent.items.length === 0 && !format.useTabsForIndentation) setInlineIndentColumn(parent, Math.max(generatedIndentWidth, 4));
893
- const kind = Array.isArray(jsValue) ? "array" : "table";
894
- const sibling = parent.items.map((item) => isInlineTable(parent) && isKeyValue(item.item) ? item.item.value : item.item).find((item) => kind === "array" ? isInlineArray(item) : isInlineTable(item));
895
- const siblingTrailingComma = sibling && kind === "array" ? arrayHadTrailingCommas(sibling) : sibling && kind === "table" ? tableHadTrailingCommas(sibling) : false;
896
- const siblingContainer = sibling;
897
- const siblingBracketSpacing = siblingContainer && siblingContainer.items.length > 0 ? siblingContainer.items[0].loc.start.column - siblingContainer.loc.start.column > 1 : void 0;
898
- const multiline = resolveInlineContainerLayout(kind, parentDepth + 1, parentIsMultiline, format);
899
- const modeProperty = kind === "array" ? "multilineArray" : "multilineTable";
900
- const contextualFormat = resolveTomlFormat({
901
- ...format,
902
- inlineTableStart: 0,
903
- [modeProperty]: multiline,
904
- trailingComma: trailingCommaExplicit ? format.trailingComma : siblingTrailingComma,
905
- bracketSpacing: siblingBracketSpacing ?? format.bracketSpacing,
906
- indentWidth: generatedIndentWidth
907
- }, format);
908
- const wrapper = parseJS({ tmp: jsValue }, contextualFormat, parentDepth + 1, parentIsMultiline).items[0];
909
- if (!wrapper || !isKeyValue(wrapper)) return child;
910
- const value = wrapper.value;
911
- if (multiline && (isInlineArray(value) || isInlineTable(value))) {
912
- const startColumn = value.loc.start.column;
913
- value.loc.start.column = 0;
914
- if (value.loc.end.line === value.loc.start.line) value.loc.end.column -= startColumn;
915
- else if (resolveInlineContainerLayout(isInlineArray(value) ? "array" : "table", parentDepth + 1, parentIsMultiline, contextualFormat)) value.loc.end.column = 1;
916
- }
917
- if (isInlineTable(parent)) {
918
- const keyValue = generateKeyValue(child.item.key.value, value, false, format.escapeSequenceUpperCase);
919
- const regenerated = generateInlineItem(keyValue);
920
- regenerated.comma = child.comma;
921
- return regenerated;
922
- }
923
- const regenerated = generateInlineItem(value);
924
- if (parent.items.length === 0 && isInlineArray(parent) && isInlineTable(value)) regenerated.comma = true;
925
- return regenerated;
926
- }
927
- function regenerateInlineReplacement(existing, replacement, changePath) {
928
- const replacementValue = isInlineItem(replacement) ? replacement.item : replacement;
929
- if (!isInlineArray(replacementValue) && !isInlineTable(replacementValue)) return replacement;
930
- let jsValue = rawUpdated;
931
- for (const key of changePath) jsValue = jsValue === null || jsValue === void 0 ? void 0 : jsValue[key];
932
- if (!Array.isArray(jsValue) && !isObject(jsValue)) return replacement;
933
- const parent = findInlineContainerParent(original, existing);
934
- const parentDepth = parent ? findInlineContainerDepth(original, parent) ?? 0 : -1;
935
- const parentIsMultiline = parent ? perLine(parent) || parent.items.length === 0 && parent.loc.end.line > parent.loc.start.line : false;
936
- const kind = Array.isArray(jsValue) ? "array" : "table";
937
- const mode = kind === "array" ? format.multilineArray : format.multilineTable;
938
- const selected = resolveInlineContainerLayout(kind, parentDepth + 1, parentIsMultiline, format);
939
- const existingValue = isInlineItem(existing) ? existing.item : existing;
940
- const existingInlineValue = isInlineArray(existingValue) || isInlineTable(existingValue) ? existingValue : void 0;
941
- const existingKind = isInlineArray(existingValue) ? "array" : isInlineTable(existingValue) ? "table" : void 0;
942
- const preserveSourceLayout = existingInlineValue !== void 0 && existingKind !== kind && hasStructuralMultilineRows(existingInlineValue) && mode === "auto";
943
- if (!(selected || preserveSourceLayout)) return replacement;
944
- const modeProperty = kind === "array" ? "multilineArray" : "multilineTable";
945
- const contextualFormat = resolveTomlFormat({
946
- ...format,
947
- inlineTableStart: 0,
948
- [modeProperty]: true,
949
- trailingComma: trailingCommaExplicit ? format.trailingComma : false
950
- }, format);
951
- const wrapper = parseJS({ tmp: jsValue }, contextualFormat, parentDepth + 1, parentIsMultiline).items[0];
952
- if (!wrapper || !isKeyValue(wrapper)) return replacement;
953
- const value = wrapper.value;
954
- if (isInlineArray(value) || isInlineTable(value)) {
955
- const targetColumn = isInlineItem(existing) ? existing.item.loc.start.column : existing.loc.start.column;
956
- if (value.loc.end.line === value.loc.start.line) value.loc.end.column += targetColumn - value.loc.start.column;
957
- else value.loc.end.column = 1;
958
- value.loc.start.column = targetColumn;
959
- }
960
- if (isInlineItem(replacement)) {
961
- const regenerated = generateInlineItem(value);
962
- regenerated.comma = replacement.comma;
963
- return regenerated;
964
- }
965
- return value;
966
- }
967
- changes.forEach((change) => {
968
- if (isAdd(change)) {
969
- var _findHostContainer;
970
- let child = findByPath(updated, change.path);
971
- const parent_path = change.path.slice(0, -1);
972
- let index = last(change.path);
973
- let is_table_array = isTableArray(child);
974
- if (isInteger$1(index) && !is_table_array && !isInteger$1(last(parent_path))) {
975
- const sibling = tryFindByPath(original, parent_path.concat(0));
976
- if (sibling && isTableArray(sibling)) is_table_array = true;
977
- }
978
- if (is_table_array && isInteger$1(index) && !isInteger$1(last(parent_path))) {
979
- const existingParent = tryFindByPath(original, parent_path);
980
- const existingArray = existingParent && isKeyValue(existingParent) ? existingParent.value : existingParent;
981
- if (existingArray && isInlineArray(existingArray)) {
982
- let jsValue = toJS(updated.items, "", { temporal });
983
- for (const k of change.path) jsValue = jsValue === null || jsValue === void 0 ? void 0 : jsValue[k];
984
- const inlineFmt = resolveTomlFormat({
985
- ...format,
986
- inlineTableStart: 0
987
- }, format);
988
- const valueDoc = jsValue === void 0 ? void 0 : parseJS({ tmp: jsValue }, inlineFmt);
989
- const wrapper = valueDoc === null || valueDoc === void 0 ? void 0 : valueDoc.items[0];
990
- if (wrapper && isKeyValue(wrapper)) {
991
- child = generateInlineItem(wrapper.value);
992
- is_table_array = false;
993
- if (isInlineItem(child) && isInlineTable(child.item) && child.item.items.length > 0) {
994
- const table = child.item;
995
- if (!(table.items[0].loc.start.column - table.loc.start.column > 1)) {
996
- const sibling = existingArray.items.map((item) => item.item).find((item) => isInlineTable(item) && item.items.length > 0);
997
- if (sibling && sibling.items[0].loc.start.column - sibling.loc.start.column > 1) applyBracketSpacing(original, table, true);
998
- }
999
- }
1000
- }
1001
- }
1002
- }
1003
- if (is_table_array && !isTableArray(child)) {
1004
- const tableArrayKey = parent_path.filter((p) => typeof p === "string");
1005
- let jsValue = toJS(updated.items, "", { temporal });
1006
- for (const k of change.path) jsValue = jsValue === null || jsValue === void 0 ? void 0 : jsValue[k];
1007
- if (jsValue !== void 0) {
1008
- const freshTableArray = generateTableArray(tableArrayKey, format.escapeSequenceUpperCase);
1009
- const entryDoc = parseJS(jsValue, format);
1010
- for (const item of entryDoc.items) insert(freshTableArray, freshTableArray, item, void 0);
1011
- const prefixNestedSectionKeys = (node) => {
1012
- if (!hasItems(node)) return;
1013
- for (const item of node.items) {
1014
- if (!isTable(item) && !isTableArray(item)) continue;
1015
- const holder = item.key;
1016
- const keyNode = holder.item;
1017
- const fullKey = tableArrayKey.concat(keyNode.value);
1018
- keyNode.value = fullKey;
1019
- keyNode.raw = generateKey(fullKey, format.escapeSequenceUpperCase).raw;
1020
- keyNode.loc.start.column = holder.loc.start.column + 1;
1021
- keyNode.loc.end.column = keyNode.loc.start.column + keyNode.raw.length;
1022
- holder.loc.end.column = keyNode.loc.start.column + keyNode.raw.length + 1;
1023
- prefixNestedSectionKeys(item);
1024
- }
1025
- };
1026
- prefixNestedSectionKeys(freshTableArray);
1027
- applyWrites(freshTableArray);
1028
- child = freshTableArray;
1029
- }
1030
- }
1031
- let parent;
1032
- if (isTable(child)) parent = original;
1033
- else if (is_table_array) {
1034
- parent = original;
1035
- const document = original;
1036
- const before = tryFindByPath(document, parent_path.concat(index - 1));
1037
- const after = tryFindByPath(document, parent_path.concat(index));
1038
- if (after) index = document.items.indexOf(after);
1039
- else if (before) {
1040
- index = document.items.indexOf(before) + 1;
1041
- if (isTableArray(before)) {
1042
- const aotKey = before.key.item.value;
1043
- let lastSubTable = index - 1;
1044
- for (let i = index; i < document.items.length; i++) {
1045
- const item = document.items[i];
1046
- const key = isTable(item) || isTableArray(item) ? item.key.item.value : void 0;
1047
- if (key && key.length > aotKey.length && arraysEqual(key.slice(0, aotKey.length), aotKey)) lastSubTable = i;
1048
- }
1049
- index = lastSubTable + 1;
1050
- if (isTableArray(child)) child = preserveAotEntryDottedKeys(child, before);
1051
- }
1052
- } else index = document.items.length;
1053
- } else {
1054
- parent = original;
1055
- for (let pLen = change.path.length - 1; pLen >= 0; pLen--) {
1056
- const candidate = tryFindByPath(original, change.path.slice(0, pLen));
1057
- if (!candidate) continue;
1058
- if (isPrefixMatchedNode(candidate, change.path.slice(0, pLen))) continue;
1059
- parent = candidate;
1060
- break;
1061
- }
1062
- if (isKeyValue(parent)) parent = parent.value;
1063
- else if (isInlineItem(parent) && isKeyValue(parent.item)) parent = parent.item.value;
1064
- else if (isInlineItem(parent) && isInlineTable(parent.item)) parent = parent.item;
1065
- else if (isInlineItem(parent) && isInlineArray(parent.item)) parent = parent.item;
1066
- }
1067
- if (isInlineArray(parent) || isInlineTable(parent)) {
1068
- child = regenerateInlineChildForParent(parent, change.path, child);
1069
- prepareInsertedNestedInlineContainer(parent, child, format.indentWidth);
1070
- }
1071
- if (isInlineArray(parent)) {
1072
- const rowNode = tryFindByPath(original, parent_path);
1073
- const rowContainer = tryFindByPath(original, parent_path.slice(0, -1));
1074
- if (rowNode && isKeyValue(rowNode) && rowContainer) {
1075
- const deltaColumns = getInlineInsertColumnDelta(parent, child, index);
1076
- if (deltaColumns !== 0) preserveAlignedInlineCommentForDelta(rowContainer, rowNode, deltaColumns);
1077
- }
1078
- }
1079
- const multilineInlineParent = (isInlineArray(parent) || isInlineTable(parent)) && parent.loc.end.line > parent.loc.start.line;
1080
- if (multilineInlineParent && insertedInlineContainers.has(parent)) applyWrites(original);
1081
- const inlineHostItems = isInlineArray(parent) || isInlineTable(parent) ? (_findHostContainer = findHostContainer(original, parent)) === null || _findHostContainer === void 0 ? void 0 : _findHostContainer.items : void 0;
1082
- if (isTableArray(parent) || isInlineArray(parent) || isDocument(parent)) {
1083
- if (isInlineArray(parent)) {
1084
- const originalHadTrailingCommas = trailingCommaForAddedItem(parent, arrayHadTrailingCommas(parent));
1085
- if (isInlineItem(child)) {
1086
- const generatedMultilineTable = parent.items.length === 0 && isInlineTable(child.item) && perLine(child.item);
1087
- child.comma = generatedMultilineTable || originalHadTrailingCommas;
1088
- const addedItem = child;
1089
- const addedTable = isInlineTable(addedItem.item) ? addedItem.item : void 0;
1090
- const siblingTable = addedTable && addedTable.items.length > 0 ? parent.items.map((item) => item.item).find((item) => item !== addedItem.item && isInlineTable(item)) : void 0;
1091
- if (addedTable && siblingTable) {
1092
- const wanted = tableHadTrailingCommas(siblingTable);
1093
- if (wanted !== tableHadTrailingCommas(addedTable)) {
1094
- let jsValue = toJS(updated.items, "", { temporal });
1095
- for (const k of change.path) jsValue = jsValue === null || jsValue === void 0 ? void 0 : jsValue[k];
1096
- const matchedFmt = resolveTomlFormat({
1097
- ...format,
1098
- inlineTableStart: 0,
1099
- trailingComma: wanted
1100
- }, format);
1101
- const rebuilt = jsValue === void 0 ? void 0 : parseJS({ tmp: jsValue }, matchedFmt).items[0];
1102
- if (rebuilt && isKeyValue(rebuilt)) {
1103
- const replacementItem = generateInlineItem(rebuilt.value);
1104
- replacementItem.comma = addedItem.comma;
1105
- child = replacementItem;
1106
- }
1107
- }
1108
- }
1109
- }
1110
- }
1111
- if (format.inlineTableStart !== void 0 && format.inlineTableStart > 0 && isDocument(parent) && isTable(child)) {
1112
- const additionalTables = convertNestedInlineTablesToMultiline(child, original, format);
1113
- insert(original, parent, child, index);
1114
- for (const table of additionalTables) insert(original, original, table, void 0);
1115
- } else {
1116
- let childToInsert = child;
1117
- if (isInlineItem(child) && (isTableArray(parent) || isDocument(parent))) childToInsert = child.item;
1118
- let resolvedIndex = index;
1119
- if (isDocument(parent) && isKeyValue(childToInsert)) {
1120
- const rootTableEnd = parent.items.findIndex((item) => isTable(item) || isTableArray(item));
1121
- if (rootTableEnd !== -1) resolvedIndex = rootTableEnd;
1122
- }
1123
- let restoredKeySegments = false;
1124
- if ((isTableArray(parent) || isDocument(parent)) && isKeyValue(childToInsert)) {
1125
- const restored = restoreMissingKeySegments(parent_path, childToInsert, change.path);
1126
- if (restored) {
1127
- if (restoredInsertContainers.has(parent)) applyWrites(original);
1128
- childToInsert = restored;
1129
- restoredKeySegments = true;
1130
- }
1131
- }
1132
- if (isInlineArray(parent) && parent.items.length === 0) applyWrites(original);
1133
- if (resolvedIndex === 0 && isInlineArray(parent) && getPendingEnterOffsets(original).has(parent)) applyWrites(original);
1134
- if (resolvedIndex === 0 && (isDocument(parent) || isTable(parent) || isTableArray(parent)) && getPendingEnterOffsets(original).has(parent)) applyWrites(original);
1135
- if (isKeyValue(childToInsert) && childToInsert.key.value.length > 1) {
1136
- const style = findDottedKeyStyle(original, childToInsert.key.value.slice(0, -1));
1137
- if (style) {
1138
- const oldEquals = childToInsert.equals;
1139
- preserveDottedKeySpacing(childToInsert.key, style.key.raw);
1140
- childToInsert.equals = childToInsert.key.loc.end.column + style.equals - style.key.loc.end.column;
1141
- const columnDelta = childToInsert.equals - oldEquals;
1142
- shiftNode(childToInsert.value, {
1143
- lines: 0,
1144
- columns: columnDelta
1145
- }, { first_line_only: true });
1146
- if (childToInsert.loc.end.line === childToInsert.loc.start.line) childToInsert.loc.end.column += columnDelta;
1147
- }
1148
- }
1149
- insert(original, parent, childToInsert, resolvedIndex, void 0, inlineHostItems);
1150
- if (restoredKeySegments) restoredInsertContainers.add(parent);
1151
- }
1152
- } else if (isInlineTable(parent)) {
1153
- if (parent.items.length === 0) {
1154
- applyWrites(original);
1155
- if (hasInlineContainerNeedingTighten(parent) && parent.loc.end.line > parent.loc.start.line) parent.loc.end.line = parent.loc.start.line;
1156
- }
1157
- const originalHadTrailingCommas = trailingCommaForAddedItem(parent, tableHadTrailingCommas(parent));
1158
- if (isKeyValue(child)) {
1159
- const inlineItem = generateInlineItem(child);
1160
- inlineItem.comma = originalHadTrailingCommas;
1161
- const insertIndex = inlineTableAddIndex(parent, child, change.before);
1162
- insert(original, parent, inlineItem, insertIndex, void 0, inlineHostItems);
1163
- } else if (isInlineItem(child) && isKeyValue(child.item)) {
1164
- let kv = child.item;
1165
- const restored = restoreMissingKeySegments(parent_path, kv, change.path);
1166
- if (restored) {
1167
- if (restoredInsertContainers.has(parent)) applyWrites(original);
1168
- kv = restored;
1169
- }
1170
- const inlineItem = generateInlineItem(kv);
1171
- inlineItem.comma = originalHadTrailingCommas;
1172
- const insertIndex = inlineTableAddIndex(parent, kv, change.before);
1173
- insert(original, parent, inlineItem, insertIndex, void 0, inlineHostItems);
1174
- if (restored) restoredInsertContainers.add(parent);
1175
- } else insert(original, parent, child, void 0, void 0, inlineHostItems);
1176
- } else if (format.inlineTableStart !== void 0 && format.inlineTableStart > 0 && isKeyValue(child) && isInlineTable(child.value) && isTable(parent)) {
1177
- const nestedTableKey = [...parent.key.item.value, ...child.key.value];
1178
- if (calculateTableDepth(nestedTableKey) < format.inlineTableStart) convertInlineTableToSeparateSection(child, parent, original, format);
1179
- else insert(original, parent, child);
1180
- } else if (format.inlineTableStart === 0 && isKeyValue(child) && isInlineTable(child.value) && isDocument(parent)) insert(original, parent, child, void 0, true);
1181
- else {
1182
- let childToInsert = child;
1183
- if (isInlineItem(child) && (isTable(parent) || isTableArray(parent) || isDocument(parent))) childToInsert = child.item;
1184
- let restoredKeySegments = false;
1185
- if (isTable(parent) && isKeyValue(childToInsert)) {
1186
- const restored = restoreMissingKeySegments(parent_path, childToInsert, change.path);
1187
- if (restored) {
1188
- if (restoredInsertContainers.has(parent)) applyWrites(original);
1189
- childToInsert = restored;
1190
- restoredKeySegments = true;
1191
- }
1192
- }
1193
- const leadingLines = (isTable(parent) || isTableArray(parent)) && parent.items.length > 0 && parent.items.every(isComment) ? 2 : void 0;
1194
- insert(original, parent, childToInsert, void 0, void 0, void 0, leadingLines);
1195
- if (restoredKeySegments) restoredInsertContainers.add(parent);
1196
- }
1197
- if (multilineInlineParent) insertedInlineContainers.add(parent);
1198
- } else if (isEdit(change)) {
1199
- let existing = tryFindByPath(original, change.path);
1200
- let replacement;
1201
- try {
1202
- replacement = findByPath(updated, change.path);
1203
- } catch {
1204
- replacement = void 0;
1205
- }
1206
- if (!existing || !replacement) {
1207
- handleStructuralEdit(original, updated, change, format, temporal, commentEligibleNodes, materialisedTables);
1208
- return;
1209
- }
1210
- if (isKeyValue(existing) && isTable(replacement)) {
1211
- const tableKey = replacement.key.item.value;
1212
- if (findDocumentItemsByKeyPrefix(original, tableKey).some((n) => n !== existing)) {
1213
- handleStructuralEdit(original, updated, change, format, temporal, commentEligibleNodes, materialisedTables);
1214
- return;
1215
- }
1216
- }
1217
- if (isInlineItem(existing) && (isTable(replacement) || isTableArray(replacement))) {
1218
- const parentArr = tryFindByPath(original, change.path.slice(0, -1));
1219
- const parentArray = parentArr && isKeyValue(parentArr) ? parentArr.value : parentArr;
1220
- if (parentArray && isInlineArray(parentArray)) {
1221
- let jsValue = rawUpdated;
1222
- for (const k of change.path) jsValue = jsValue === null || jsValue === void 0 ? void 0 : jsValue[k];
1223
- if (jsValue !== void 0) {
1224
- const inlineFmt = resolveTomlFormat({
1225
- ...format,
1226
- inlineTableStart: 0
1227
- }, format);
1228
- const valueDoc = parseJS({ tmp: jsValue }, inlineFmt);
1229
- const wrapper = valueDoc === null || valueDoc === void 0 ? void 0 : valueDoc.items[0];
1230
- if (wrapper && isKeyValue(wrapper)) replacement = generateInlineItem(wrapper.value);
1231
- }
1232
- }
1233
- }
1234
- let parent;
1235
- let containerParent = tryFindByPath(original, change.path.slice(0, -1));
1236
- if (containerParent && isKeyValue(containerParent) && isPrefixMatchedNode(containerParent, change.path.slice(0, -1))) containerParent = findStructuralParent(original, containerParent);
1237
- const inlineTableRowContext = findEnclosingInlineTableRowContext(original, change.path);
1238
- if (isKeyValue(existing) && isKeyValue(replacement)) {
1239
- let keyTruncated = false;
1240
- if (existing.key.value.length > 1) {
1241
- const absPath = absolutePathOf(existing);
1242
- const matchLen = truncationMatchLen(change.path, existing.key.value, absPath ? absPath.length - existing.key.value.length : 0);
1243
- if (matchLen > 0 && matchLen < existing.key.value.length) {
1244
- existing.key.value = existing.key.value.slice(0, matchLen);
1245
- existing.key.raw = generateKey(existing.key.value).raw;
1246
- const oldEndCol = existing.key.loc.end.column;
1247
- const newEndCol = existing.key.loc.start.column + existing.key.raw.length;
1248
- const delta = newEndCol - oldEndCol;
1249
- existing.key.loc.end.column = newEndCol;
1250
- existing.equals += delta;
1251
- existing.value.loc.start.column += delta;
1252
- if (existing.value.loc.end.line === existing.value.loc.start.line) existing.value.loc.end.column += delta;
1253
- if (existing.loc.end.line === existing.loc.start.line) existing.loc.end.column += delta;
1254
- keyTruncated = true;
1255
- const truncatedPrefix = existing.key.value;
1256
- if (containerParent && (isTable(containerParent) || isDocument(containerParent) || isTableArray(containerParent))) {
1257
- const parentItems = [...containerParent.items];
1258
- for (let si = parentItems.length - 1; si >= 0; si--) {
1259
- const sibling = parentItems[si];
1260
- if (sibling === existing) continue;
1261
- const siblingKey = isKeyValue(sibling) ? sibling.key.value : isTable(sibling) || isTableArray(sibling) ? sibling.key.item.value : void 0;
1262
- if (siblingKey && siblingKey.length >= truncatedPrefix.length && arraysEqual(siblingKey.slice(0, truncatedPrefix.length), truncatedPrefix)) removeMember(original, containerParent, sibling);
1263
- }
1264
- }
1265
- }
1266
- }
1267
- if (!keyTruncated && isKeyValue(replacement)) {
1268
- if (containerParent && (isTable(containerParent) || isDocument(containerParent) || isTableArray(containerParent))) removeSiblingsExtendingPrefix(original, containerParent, existing.key.value, existing);
1269
- }
1270
- preserveFormatting(existing.value, replacement.value, format.escapeSequenceUpperCase, format.minimumTimeDecimals ?? 0);
1271
- if (containerParent) preserveAlignedInlineCommentColumn(containerParent, existing, existing.value, replacement.value);
1272
- parent = existing;
1273
- existing = existing.value;
1274
- replacement = replacement.value;
1275
- if (keyTruncated && rawUpdated !== void 0) {
1276
- let jsValue = rawUpdated;
1277
- for (const k of change.path) jsValue = jsValue === null || jsValue === void 0 ? void 0 : jsValue[k];
1278
- if (jsValue !== void 0) {
1279
- const freshValue = regenerateValue(jsValue, format);
1280
- if (freshValue !== void 0) {
1281
- replacement = freshValue;
1282
- preserveFormatting(existing, replacement, format.escapeSequenceUpperCase, format.minimumTimeDecimals ?? 0);
1283
- }
1284
- }
1285
- }
1286
- } else if (isKeyValue(existing) && isInlineItem(replacement) && isKeyValue(replacement.item)) {
1287
- let keyTruncated = false;
1288
- if (existing.key.value.length > 1) {
1289
- const absPath = absolutePathOf(existing);
1290
- const matchLen = truncationMatchLen(change.path, existing.key.value, absPath ? absPath.length - existing.key.value.length : 0);
1291
- if (matchLen > 0 && matchLen < existing.key.value.length) {
1292
- existing.key.value = existing.key.value.slice(0, matchLen);
1293
- existing.key.raw = generateKey(existing.key.value).raw;
1294
- const oldEndCol = existing.key.loc.end.column;
1295
- const newEndCol = existing.key.loc.start.column + existing.key.raw.length;
1296
- const delta = newEndCol - oldEndCol;
1297
- existing.key.loc.end.column = newEndCol;
1298
- existing.equals += delta;
1299
- existing.value.loc.start.column += delta;
1300
- if (existing.value.loc.end.line === existing.value.loc.start.line) existing.value.loc.end.column += delta;
1301
- if (existing.loc.end.line === existing.loc.start.line) existing.loc.end.column += delta;
1302
- keyTruncated = true;
1303
- const truncatedPrefix = existing.key.value;
1304
- if (containerParent && (isTable(containerParent) || isDocument(containerParent) || isTableArray(containerParent))) {
1305
- const parentItems = [...containerParent.items];
1306
- for (let si = parentItems.length - 1; si >= 0; si--) {
1307
- const sibling = parentItems[si];
1308
- if (sibling === existing) continue;
1309
- const siblingKey = isKeyValue(sibling) ? sibling.key.value : isTable(sibling) || isTableArray(sibling) ? sibling.key.item.value : void 0;
1310
- if (siblingKey && siblingKey.length >= truncatedPrefix.length && arraysEqual(siblingKey.slice(0, truncatedPrefix.length), truncatedPrefix)) removeMember(original, containerParent, sibling);
1311
- }
1312
- }
1313
- }
1314
- }
1315
- if (!keyTruncated && isKeyValue(replacement.item)) {
1316
- if (containerParent && (isTable(containerParent) || isDocument(containerParent) || isTableArray(containerParent))) removeSiblingsExtendingPrefix(original, containerParent, existing.key.value, existing);
1317
- }
1318
- parent = existing;
1319
- existing = existing.value;
1320
- replacement = replacement.item.value;
1321
- if (keyTruncated && rawUpdated !== void 0) {
1322
- let jsValue = rawUpdated;
1323
- for (const k of change.path) jsValue = jsValue === null || jsValue === void 0 ? void 0 : jsValue[k];
1324
- if (jsValue !== void 0) {
1325
- const freshValue = regenerateValue(jsValue, format);
1326
- if (freshValue !== void 0) replacement = freshValue;
1327
- }
1328
- }
1329
- } else if (isInlineItem(existing) && isKeyValue(existing.item) && isKeyValue(replacement)) {
1330
- const existingKeyValue = existing.item;
1331
- let keyTruncated = false;
1332
- if (existingKeyValue.key.value.length > 1) {
1333
- const absPath = absolutePathOf(existingKeyValue);
1334
- const matchLen = truncationMatchLen(change.path, existingKeyValue.key.value, absPath ? absPath.length - existingKeyValue.key.value.length : 0);
1335
- if (matchLen > 0 && matchLen < existingKeyValue.key.value.length) {
1336
- existingKeyValue.key.value = existingKeyValue.key.value.slice(0, matchLen);
1337
- existingKeyValue.key.raw = generateKey(existingKeyValue.key.value, format.escapeSequenceUpperCase).raw;
1338
- const oldEndCol = existingKeyValue.key.loc.end.column;
1339
- const newEndCol = existingKeyValue.key.loc.start.column + existingKeyValue.key.raw.length;
1340
- const delta = newEndCol - oldEndCol;
1341
- existingKeyValue.key.loc.end.column = newEndCol;
1342
- existingKeyValue.equals += delta;
1343
- existingKeyValue.value.loc.start.column += delta;
1344
- if (existingKeyValue.value.loc.end.line === existingKeyValue.value.loc.start.line) existingKeyValue.value.loc.end.column += delta;
1345
- if (existingKeyValue.loc.end.line === existingKeyValue.loc.start.line) existingKeyValue.loc.end.column += delta;
1346
- if (existingKeyValue.loc.end.line === existingKeyValue.loc.start.line) addExitOffset(original, existingKeyValue, {
1347
- lines: 0,
1348
- columns: delta
1349
- });
1350
- keyTruncated = true;
1351
- const truncatedPrefix = existingKeyValue.key.value;
1352
- let scanParent = containerParent;
1353
- if (scanParent && isInlineItem(scanParent)) scanParent = scanParent.item;
1354
- if (scanParent && isKeyValue(scanParent)) scanParent = scanParent.value;
1355
- if (scanParent && hasItems(scanParent)) {
1356
- const parentItems = [...scanParent.items];
1357
- for (let si = parentItems.length - 1; si >= 0; si--) {
1358
- const sibling = parentItems[si];
1359
- if (sibling === existing) continue;
1360
- const siblingKey = isKeyValue(sibling) ? sibling.key.value : isInlineItem(sibling) && isKeyValue(sibling.item) ? sibling.item.key.value : isTable(sibling) || isTableArray(sibling) ? sibling.key.item.value : void 0;
1361
- if (siblingKey && siblingKey.length >= truncatedPrefix.length && arraysEqual(siblingKey.slice(0, truncatedPrefix.length), truncatedPrefix)) removeMember(original, scanParent, sibling);
1362
- }
1363
- }
1364
- }
1365
- }
1366
- preserveFormatting(existingKeyValue.value, replacement.value, format.escapeSequenceUpperCase, format.minimumTimeDecimals ?? 0);
1367
- parent = existingKeyValue;
1368
- existing = existingKeyValue.value;
1369
- replacement = replacement.value;
1370
- if (keyTruncated && rawUpdated !== void 0) {
1371
- let jsValue = rawUpdated;
1372
- for (const k of change.path) jsValue = jsValue === null || jsValue === void 0 ? void 0 : jsValue[k];
1373
- if (jsValue !== void 0) {
1374
- const freshValue = regenerateValue(jsValue, format);
1375
- if (freshValue !== void 0) {
1376
- replacement = freshValue;
1377
- preserveFormatting(existing, replacement, format.escapeSequenceUpperCase, format.minimumTimeDecimals ?? 0);
1378
- }
1379
- }
1380
- }
1381
- } else if (isInlineItem(existing) && isInlineItem(replacement) && isKeyValue(existing.item) && isKeyValue(replacement.item)) {
1382
- let keyTruncated = false;
1383
- const existingKV = existing.item;
1384
- if (existingKV.key.value.length > 1) {
1385
- const absPath = absolutePathOf(existingKV);
1386
- const matchLen = truncationMatchLen(change.path, existingKV.key.value, absPath ? absPath.length - existingKV.key.value.length : 0);
1387
- if (matchLen > 0 && matchLen < existingKV.key.value.length) {
1388
- existingKV.key.value = existingKV.key.value.slice(0, matchLen);
1389
- existingKV.key.raw = generateKey(existingKV.key.value, format.escapeSequenceUpperCase).raw;
1390
- const oldEndCol = existingKV.key.loc.end.column;
1391
- const newEndCol = existingKV.key.loc.start.column + existingKV.key.raw.length;
1392
- const delta = newEndCol - oldEndCol;
1393
- existingKV.key.loc.end.column = newEndCol;
1394
- existingKV.equals += delta;
1395
- existingKV.value.loc.start.column += delta;
1396
- if (existingKV.value.loc.end.line === existingKV.value.loc.start.line) existingKV.value.loc.end.column += delta;
1397
- if (existingKV.loc.end.line === existingKV.loc.start.line) existingKV.loc.end.column += delta;
1398
- if (existingKV.loc.end.line === existingKV.loc.start.line) addExitOffset(original, existingKV, {
1399
- lines: 0,
1400
- columns: delta
1401
- });
1402
- keyTruncated = true;
1403
- const truncatedPrefix = existingKV.key.value;
1404
- let scanParent = containerParent;
1405
- if (scanParent && isInlineItem(scanParent)) scanParent = scanParent.item;
1406
- if (scanParent && isKeyValue(scanParent)) scanParent = scanParent.value;
1407
- if (scanParent && hasItems(scanParent)) {
1408
- const parentItems = [...scanParent.items];
1409
- for (let si = parentItems.length - 1; si >= 0; si--) {
1410
- const sibling = parentItems[si];
1411
- if (sibling === existing) continue;
1412
- const siblingKey = isKeyValue(sibling) ? sibling.key.value : isInlineItem(sibling) && isKeyValue(sibling.item) ? sibling.item.key.value : isTable(sibling) || isTableArray(sibling) ? sibling.key.item.value : void 0;
1413
- if (siblingKey && siblingKey.length >= truncatedPrefix.length && arraysEqual(siblingKey.slice(0, truncatedPrefix.length), truncatedPrefix)) removeMember(original, scanParent, sibling);
1414
- }
1415
- }
1416
- }
1417
- }
1418
- preserveFormatting(existingKV.value, replacement.item.value, format.escapeSequenceUpperCase, format.minimumTimeDecimals ?? 0);
1419
- parent = existingKV;
1420
- existing = existingKV.value;
1421
- replacement = replacement.item.value;
1422
- if (keyTruncated && rawUpdated !== void 0) {
1423
- let jsValue = rawUpdated;
1424
- for (const k of change.path) jsValue = jsValue === null || jsValue === void 0 ? void 0 : jsValue[k];
1425
- if (jsValue !== void 0) {
1426
- const freshValue = regenerateValue(jsValue, format);
1427
- if (freshValue !== void 0) {
1428
- replacement = freshValue;
1429
- preserveFormatting(existing, replacement, format.escapeSequenceUpperCase, format.minimumTimeDecimals ?? 0);
1430
- }
1431
- }
1432
- }
1433
- } else if (isTable(existing)) {
1434
- let jsValue = toJS(updated.items, "", { temporal });
1435
- for (const key of change.path) jsValue = jsValue === null || jsValue === void 0 ? void 0 : jsValue[key];
1436
- if (jsValue !== void 0) {
1437
- const existingTableKey = existing.key.item.value;
1438
- const lastSegment = existingTableKey.slice(-1);
1439
- const parentKey = existingTableKey.slice(0, -1);
1440
- const tableParent = findStructuralParent(original, existing) ?? findParent(original, change.path);
1441
- if (isDocument(tableParent)) {
1442
- const sectionedSiblings = findDocumentItemsByKeyPrefix(original, existingTableKey).filter((n) => n !== existing && (isTable(n) || isTableArray(n)));
1443
- for (const sibling of sectionedSiblings) removeMember(original, tableParent, sibling);
1444
- }
1445
- const freshDoc = parseJS({ [lastSegment[0]]: jsValue }, format);
1446
- const freshKV = freshDoc.items[0];
1447
- if (parentKey.length > 0) {
1448
- if (isTable(freshKV) || isTableArray(freshKV)) {
1449
- extendSectionKeyWithParentAndReplace(freshKV, parentKey, existing, tableParent);
1450
- commentEligibleNodes.add(freshKV);
1451
- } else if (findDocumentItemsByKeyPrefix(original, parentKey).some(isKeyValue)) {
1452
- extendKeyWithParentAndReplace(freshKV, parentKey, existing, tableParent);
1453
- commentEligibleNodes.add(freshKV);
1454
- } else {
1455
- const survivingParent = original.items.find((n) => n !== existing && (isTable(n) || isTableArray(n)) && arraysEqual(n.key.item.value, parentKey));
1456
- if (survivingParent) {
1457
- insert(original, survivingParent, freshKV, void 0);
1458
- removeMember(original, tableParent, existing);
1459
- commentEligibleNodes.add(freshKV);
1460
- } else {
1461
- const newTable = generateTable(parentKey, format.escapeSequenceUpperCase);
1462
- materialisedTables.add(newTable);
1463
- insert(original, newTable, freshKV, 0);
1464
- replace(original, tableParent, existing, newTable);
1465
- commentEligibleNodes.add(newTable);
1466
- }
1467
- }
1468
- } else {
1469
- replace(original, tableParent, existing, freshKV);
1470
- commentEligibleNodes.add(freshKV);
1471
- hoistRootKeyValueAboveTables(original, freshKV);
1472
- }
1473
- if (freshDoc.items.length > 1) for (let i = 1; i < freshDoc.items.length; i++) {
1474
- const extraEntry = freshDoc.items[i];
1475
- if (parentKey.length > 0) extendSectionKeyInPlace(extraEntry, parentKey);
1476
- const prev = i === 1 ? freshKV : freshDoc.items[i - 1];
1477
- const prevIndex = tableParent.items.indexOf(prev);
1478
- insert(original, tableParent, extraEntry, prevIndex + 1);
1479
- commentEligibleNodes.add(extraEntry);
1480
- }
1481
- return;
1482
- }
1483
- parent = findParent(original, change.path);
1484
- } else if (isTableArray(existing)) {
1485
- const updated_js = toJS(updated.items, "", { temporal });
1486
- const existingAotKey = existing.key.item.value;
1487
- let jsValue = updated_js;
1488
- const navPath = typeof change.path[change.path.length - 1] === "number" ? change.path.slice(0, -1) : change.path;
1489
- for (const key of navPath) jsValue = jsValue === null || jsValue === void 0 ? void 0 : jsValue[key];
1490
- if (jsValue !== void 0) {
1491
- const lastSegment = existingAotKey.slice(-1);
1492
- const parentKey = existingAotKey.slice(0, -1);
1493
- const tableParent = findStructuralParent(original, existing) ?? findParent(original, change.path);
1494
- const freshKV = parseJS({ [lastSegment[0]]: jsValue }, format).items[0];
1495
- if (Array.isArray(jsValue) && !jsValue.every((v) => isObject(v))) {
1496
- const siblingEntries = findDocumentItemsByKeyPrefix(original, existingAotKey).filter((n) => n !== existing && (isTable(n) || isTableArray(n)));
1497
- for (const sibling of siblingEntries) removeMember(original, original, sibling);
1498
- }
1499
- if (parentKey.length > 0) {
1500
- if (isTable(freshKV) || isTableArray(freshKV)) {
1501
- extendSectionKeyWithParentAndReplace(freshKV, parentKey, existing, tableParent);
1502
- commentEligibleNodes.add(freshKV);
1503
- } else {
1504
- const existingParentTable = isDocument(tableParent) ? tableParent.items.find((item) => isTable(item) && arraysEqual(item.key.item.value, parentKey)) : void 0;
1505
- if (existingParentTable) {
1506
- const existingRow = existingParentTable.items.find((row) => isKeyValue(row) && arraysEqual(row.key.value, freshKV.key.value));
1507
- if (existingRow) replace(original, existingParentTable, existingRow, freshKV);
1508
- else insert(original, existingParentTable, freshKV, void 0);
1509
- removeMember(original, tableParent, existing);
1510
- commentEligibleNodes.add(existingParentTable);
1511
- return;
1512
- }
1513
- if (findDocumentItemsByKeyPrefix(original, parentKey).some(isKeyValue)) {
1514
- extendKeyWithParentAndReplace(freshKV, parentKey, existing, tableParent);
1515
- commentEligibleNodes.add(freshKV);
1516
- } else {
1517
- const newTable = generateTable(parentKey, format.escapeSequenceUpperCase);
1518
- materialisedTables.add(newTable);
1519
- insert(original, newTable, freshKV, 0);
1520
- replace(original, tableParent, existing, newTable);
1521
- commentEligibleNodes.add(newTable);
1522
- }
1523
- }
1524
- } else {
1525
- replace(original, tableParent, existing, freshKV);
1526
- commentEligibleNodes.add(freshKV);
1527
- hoistRootKeyValueAboveTables(original, freshKV);
1528
- }
1529
- return;
1530
- }
1531
- parent = findParent(original, change.path);
1532
- } else {
1533
- parent = findParent(original, change.path);
1534
- if (isKeyValue(parent)) {
1535
- const parentPath = change.path.slice(0, -1);
1536
- const arrayNode = findByPath(original, parentPath);
1537
- if (isKeyValue(arrayNode) && isInlineArray(arrayNode.value)) parent = arrayNode.value;
1538
- } else if (isInlineItem(parent) && isKeyValue(parent.item)) parent = parent.item.value;
1539
- else if (isInlineItem(parent) && isInlineTable(parent.item)) parent = parent.item;
1540
- else if (isInlineItem(parent) && isInlineArray(parent.item)) parent = parent.item;
1541
- }
1542
- if (isInlineItem(existing) && isInlineItem(replacement)) {
1543
- if (isString(existing.item) && isString(replacement.item)) {
1544
- preserveFormatting(existing.item, replacement.item, format.escapeSequenceUpperCase, format.minimumTimeDecimals ?? 0);
1545
- replacement.loc = {
1546
- start: { ...replacement.item.loc.start },
1547
- end: { ...replacement.item.loc.end }
1548
- };
1549
- }
1550
- replacement.comma = existing.comma;
1551
- }
1552
- if (inlineTableRowContext) {
1553
- const existingSpan = getSpan(existing.loc);
1554
- const deltaColumns = getSpan(replacement.loc).columns - existingSpan.columns;
1555
- if (deltaColumns !== 0) recordInlineTableCommentDelta(inlineTableRowContext.container, inlineTableRowContext.row, deltaColumns);
1556
- }
1557
- replacement = regenerateInlineReplacement(existing, replacement, change.path);
1558
- replace(original, parent, existing, replacement);
1559
- if (isInlineArray(replacement)) replacedInlineArrays.add(replacement);
1560
- if (isInlineArray(replacement) || isInlineTable(replacement)) {
1561
- applyWrites(original);
1562
- normalizeGeneratedInlineContainerRows(replacement, format.indentWidth);
1563
- replacedInlineContainers.push({
1564
- owner: parent,
1565
- container: replacement
1566
- });
1567
- }
1568
- if (isDocument(parent) && isKeyValue(existing) && (isTable(replacement) || isTableArray(replacement))) sinkTableBelowRootKeyValues(original, replacement);
1569
- } else if (isRemove(change)) {
1570
- const node = tryFindByPath(original, change.path);
1571
- if (!node) {
1572
- const nextAotEntry = () => {
1573
- const direct = tryFindByPath(original, change.path.concat(0));
1574
- if (direct) return direct;
1575
- return findDocumentItemsByKeyPrefix(original, change.path).filter(isTableArray)[0];
1576
- };
1577
- const first = nextAotEntry();
1578
- if (first) {
1579
- const firstIndex = original.items.indexOf(first);
1580
- let materialiseAotInPlace = false;
1581
- if (change.path.length > 1 && rawUpdated !== void 0) {
1582
- const parentPath = change.path.slice(0, -1);
1583
- if (findDocumentItemsByKeyPrefix(original, parentPath).filter((s) => !(isTableArray(s) && arraysEqual(s.key.item.value, change.path))).length === 0) {
1584
- let value = rawUpdated;
1585
- for (const k of parentPath) value = value === null || value === void 0 ? void 0 : value[k];
1586
- if (isObject(value) && Object.keys(value).length === 0) {
1587
- const aotNode = first;
1588
- const aotKeyHolder = aotNode.key;
1589
- while (aotNode.items.length > 0) removeMember(original, aotNode, last(aotNode.items));
1590
- applyWrites(original);
1591
- aotNode.type = "Table";
1592
- aotKeyHolder.type = "TableKey";
1593
- const aotKey = hasItem(aotKeyHolder) ? aotKeyHolder.item : aotKeyHolder;
1594
- aotKey.value = parentPath;
1595
- aotKey.raw = preserveEscapedKeyRaw(aotKey.raw, aotKey.value, format.escapeSequenceUpperCase);
1596
- aotKey.loc.end.column = aotKey.loc.start.column + aotKey.raw.length;
1597
- aotKeyHolder.loc.end.column = aotKeyHolder.loc.start.column + aotKey.raw.length + 2;
1598
- aotNode.loc.end.line = aotKeyHolder.loc.end.line;
1599
- aotNode.loc.end.column = aotKeyHolder.loc.end.column;
1600
- trackAdjacentComment(aotNode);
1601
- materialiseAotInPlace = true;
1602
- }
1603
- }
1604
- }
1605
- let entry;
1606
- while (entry = nextAotEntry()) removeMember(original, original, entry);
1607
- for (const tableNode of findDocumentItemsByKeyPrefix(original, change.path).filter(isTable)) removeMember(original, original, tableNode);
1608
- if (tryFindByPath(updated, change.path)) {
1609
- const aotPath = change.path;
1610
- emptiedAotKeys.set(aotPath.join("."), aotPath);
1611
- }
1612
- if (!materialiseAotInPlace && change.path.length > 1 && rawUpdated !== void 0) {
1613
- const parentPath = change.path.slice(0, -1);
1614
- if (findDocumentItemsByKeyPrefix(original, parentPath).length === 0) {
1615
- let value = rawUpdated;
1616
- for (const k of parentPath) value = value === null || value === void 0 ? void 0 : value[k];
1617
- if (isObject(value) && Object.keys(value).length === 0) {
1618
- const emptyTable = generateTable(parentPath, format.escapeSequenceUpperCase);
1619
- materialisedTables.add(emptyTable);
1620
- const insertIdx = firstIndex >= 0 ? Math.min(firstIndex, original.items.length) : original.items.length;
1621
- applyWrites(original);
1622
- insert(original, original, emptyTable, insertIdx);
1623
- }
1624
- }
1625
- }
1626
- } else {
1627
- const cstPath = stripAotEntryIndices(original, change.path);
1628
- const prefixNodes = findDocumentItemsByKeyPrefix(original, cstPath);
1629
- if (prefixNodes.length > 0) {
1630
- const firstPrefixIndex = original.items.indexOf(prefixNodes[0]);
1631
- for (const prefixNode of prefixNodes) removeMember(original, original, prefixNode);
1632
- if (cstPath.length > 1 && rawUpdated !== void 0) {
1633
- const cstParentPath = cstPath.slice(0, -1);
1634
- if (findDocumentItemsByKeyPrefix(original, cstParentPath).length === 0) {
1635
- let value = rawUpdated;
1636
- for (const k of change.path.slice(0, -1)) value = value === null || value === void 0 ? void 0 : value[k];
1637
- if (isObject(value) && Object.keys(value).length === 0) {
1638
- const emptyTable = generateTable(cstParentPath, format.escapeSequenceUpperCase);
1639
- materialisedTables.add(emptyTable);
1640
- const insertIdx = firstPrefixIndex >= 0 ? Math.min(firstPrefixIndex, original.items.length) : original.items.length;
1641
- applyWrites(original);
1642
- insert(original, original, emptyTable, insertIdx);
1643
- }
1644
- }
1645
- }
1646
- } else findByPath(original, change.path);
1647
- }
1648
- } else {
1649
- let parent = findParent(original, change.path);
1650
- if (parent === node) parent = findParent(original, change.path.slice(0, -1));
1651
- if (parent === node) {
1652
- const host = findHostContainer(original, node);
1653
- if (host) parent = host;
1654
- }
1655
- if (isKeyValue(parent)) parent = parent.value;
1656
- if (isInlineItem(parent) && isKeyValue(parent.item)) parent = parent.item.value;
1657
- if (isInlineItem(parent) && isInlineTable(parent.item)) parent = parent.item;
1658
- if (isInlineItem(parent) && isInlineArray(parent.item)) parent = parent.item;
1659
- if (!hasItems(parent) || !parent.items.includes(node)) parent = findStructuralParent(original, node) ?? (hasItems(parent) ? original : findHostContainer(original, node) ?? original);
1660
- let materialisedInPlace = false;
1661
- if (change.path.length > 1 && isTable(node) && rawUpdated !== void 0) {
1662
- const parentPath = change.path.slice(0, -1);
1663
- const cstParentPath = node.key.item.value.slice(0, -1);
1664
- if (findDocumentItemsByKeyPrefix(original, cstParentPath).filter((s) => s !== node).length === 0) {
1665
- let value = rawUpdated;
1666
- for (const k of parentPath) value = value === null || value === void 0 ? void 0 : value[k];
1667
- if (isObject(value) && Object.keys(value).length === 0) {
1668
- const table = node;
1669
- while (table.items.length > 0) remove(original, table, last(table.items));
1670
- applyWrites(original);
1671
- const keyHolder = table.key;
1672
- const key = hasItem(keyHolder) ? keyHolder.item : keyHolder;
1673
- key.value = cstParentPath;
1674
- key.raw = preserveEscapedKeyRaw(key.raw, key.value, format.escapeSequenceUpperCase);
1675
- key.loc.end.column = key.loc.start.column + key.raw.length;
1676
- keyHolder.loc.end.column = keyHolder.loc.start.column + key.raw.length + 2;
1677
- table.loc.end.line = keyHolder.loc.end.line;
1678
- table.loc.end.column = keyHolder.loc.end.column;
1679
- trackAdjacentComment(table);
1680
- materialisedInPlace = true;
1681
- }
1682
- }
1683
- }
1684
- const nodeIndex = isDocument(parent) && hasItems(parent) ? parent.items.indexOf(node) : -1;
1685
- const containerItemIndex = hasItems(parent) && !isDocument(parent) ? parent.items.indexOf(node) : -1;
1686
- const removedInlineComma = isInlineItem(node) ? node.comma : void 0;
1687
- if (isInlineItem(node) && (isInlineArray(parent) || isInlineTable(parent))) setInlineIndentColumn(parent, node.loc.start.column);
1688
- if (isInlineItem(node) && (isInlineArray(parent) || isInlineTable(parent)) && containerItemIndex === parent.items.length - 1 && removedInlineComma !== void 0) removedInlineTrailingCommas.set(parent, removedInlineComma);
1689
- const bracketGapBefore = isInlineItem(node) && (isInlineArray(parent) || isInlineTable(parent)) && node.loc.end.line === parent.loc.end.line ? parent.loc.end.column - node.loc.end.column : void 0;
1690
- const nodeAbsolutePath = absolutePathOf(isInlineItem(node) && isKeyValue(node.item) ? node.item : node);
1691
- const removePrefixKv = isKeyValue(node) ? node : isInlineItem(node) && isKeyValue(node.item) ? node.item : void 0;
1692
- if (removePrefixKv && nodeAbsolutePath && hasItems(parent)) {
1693
- const containerAbsLen = nodeAbsolutePath.length - removePrefixKv.key.value.length;
1694
- const relativePrefix = change.path.slice(containerAbsLen);
1695
- if (relativePrefix.length > 0 && relativePrefix.length < removePrefixKv.key.value.length) {
1696
- const siblings = parent.items;
1697
- const toRemove = [];
1698
- for (const sibling of siblings) {
1699
- if (sibling === node) continue;
1700
- const siblingKey = isKeyValue(sibling) ? sibling.key.value : isInlineItem(sibling) && isKeyValue(sibling.item) ? sibling.item.key.value : isTable(sibling) || isTableArray(sibling) ? sibling.key.item.value : void 0;
1701
- if (siblingKey && siblingKey.length > relativePrefix.length && arraysEqual(siblingKey.slice(0, relativePrefix.length), relativePrefix)) toRemove.push(sibling);
1702
- }
1703
- for (const sibling of toRemove) removeMember(original, parent, sibling);
1704
- }
1705
- }
1706
- if (removePrefixKv && nodeAbsolutePath && hasItems(parent)) {
1707
- const key = removePrefixKv.key.value;
1708
- const siblings = parent.items;
1709
- const extending = [];
1710
- for (const sibling of siblings) {
1711
- if (sibling === node) continue;
1712
- const siblingKey = isKeyValue(sibling) ? sibling.key.value : isInlineItem(sibling) && isKeyValue(sibling.item) ? sibling.item.key.value : isTable(sibling) || isTableArray(sibling) ? sibling.key.item.value : void 0;
1713
- if (siblingKey && siblingKey.length > key.length && arraysEqual(siblingKey.slice(0, key.length), key)) extending.push(sibling);
1714
- }
1715
- for (const sibling of extending) removeMember(original, parent, sibling);
1716
- }
1717
- if ((isTable(node) || isTableArray(node)) && hasItems(parent)) {
1718
- const key = node.key.item.value;
1719
- const siblings = parent.items;
1720
- const extending = [];
1721
- const aotEntry = isTableArray(node);
1722
- const ownStart = siblings.indexOf(node);
1723
- let ownEnd = siblings.length;
1724
- if (aotEntry) for (let i = ownStart + 1; i < siblings.length; i++) {
1725
- const s = siblings[i];
1726
- if (!isTableArray(s)) continue;
1727
- const sKey = s.key.item.value;
1728
- if (sKey.length <= key.length && arraysEqual(sKey, key.slice(0, sKey.length))) {
1729
- ownEnd = i;
1730
- break;
1731
- }
1732
- }
1733
- for (const [index, sibling] of siblings.entries()) {
1734
- if (sibling === node) continue;
1735
- if (aotEntry && (index < ownStart || index >= ownEnd)) continue;
1736
- const siblingKey = isKeyValue(sibling) ? sibling.key.value : isTable(sibling) || isTableArray(sibling) ? sibling.key.item.value : void 0;
1737
- if (siblingKey && siblingKey.length > key.length && arraysEqual(siblingKey.slice(0, key.length), key)) extending.push(sibling);
1738
- }
1739
- for (const sibling of extending) removeMember(original, parent, sibling);
1740
- }
1741
- if (!materialisedInPlace) removeMember(original, parent, node);
1742
- if (isInlineItem(node) && (isInlineArray(parent) || isInlineTable(parent)) && node.loc.end.line === parent.loc.end.line) {
1743
- const remaining = parent.items;
1744
- const tailOnBracketRow = parent.loc.end.line === parent.loc.start.line ? remaining.every((item) => item.loc.end.line === parent.loc.start.line) : remaining.length > 0 && last(remaining).loc.end.line === parent.loc.end.line;
1745
- if (remaining.length > 0 && containerItemIndex === remaining.length && tailOnBracketRow) {
1746
- const gap = bracketGapBefore ?? parent.loc.end.column - node.loc.end.column;
1747
- applyWrites(original);
1748
- const targetEnd = last(remaining).loc.end.column + gap;
1749
- if (parent.loc.end.column !== targetEnd) parent.loc.end.column = targetEnd;
1750
- let owner;
1751
- const findOwner = (n) => {
1752
- if (isKeyValue(n)) {
1753
- if (n.value === parent) return n;
1754
- return findOwner(n.value);
1755
- }
1756
- if (isInlineItem(n)) return findOwner(n.item);
1757
- if (!hasItems(n)) return void 0;
1758
- for (const item of n.items) {
1759
- const found = findOwner(isInlineItem(item) ? item.item : item);
1760
- if (found) return found;
1761
- }
1762
- };
1763
- owner = findOwner(original);
1764
- if (owner && owner.loc.end.line === parent.loc.end.line) {
1765
- owner.loc.end.column = parent.loc.end.column;
1766
- const findWrapper = (n) => {
1767
- if (isKeyValue(n)) return findWrapper(n.value);
1768
- if (isInlineItem(n)) {
1769
- if (n.item === owner) return n;
1770
- return findWrapper(n.item);
1771
- }
1772
- if (!hasItems(n)) return void 0;
1773
- for (const item of n.items) {
1774
- const found = findWrapper(item);
1775
- if (found) return found;
1776
- }
1777
- };
1778
- const wrapper = findWrapper(original);
1779
- if (wrapper) {
1780
- const delta = parent.loc.end.column - wrapper.loc.end.column;
1781
- wrapper.loc.end.column = parent.loc.end.column;
1782
- if (delta !== 0) {
1783
- addExitOffset(original, wrapper, {
1784
- lines: 0,
1785
- columns: delta
1786
- });
1787
- markDirty(original);
1788
- applyWrites(original);
1789
- }
1790
- }
1791
- }
1792
- }
1793
- }
1794
- if (!materialisedInPlace && change.path.length > 1 && (isTable(node) || isTableArray(node)) && rawUpdated !== void 0) {
1795
- const parentPath = change.path.slice(0, -1);
1796
- const cstParentKey = node.key.item.value.slice(0, -1);
1797
- if (findDocumentItemsByKeyPrefix(original, cstParentKey).length === 0) {
1798
- let value = rawUpdated;
1799
- for (const k of parentPath) value = value === null || value === void 0 ? void 0 : value[k];
1800
- if (isObject(value) && Object.keys(value).length === 0) {
1801
- const emptyTable = generateTable(cstParentKey, format.escapeSequenceUpperCase);
1802
- materialisedTables.add(emptyTable);
1803
- const insertIdx = nodeIndex >= 0 ? Math.min(nodeIndex, original.items.length) : original.items.length;
1804
- applyWrites(original);
1805
- insert(original, original, emptyTable, insertIdx);
1806
- }
1807
- }
1808
- }
1809
- if (!materialisedInPlace && change.path.length > 1 && rawUpdated !== void 0) {
1810
- const kv = isKeyValue(node) ? node : isInlineItem(node) && isKeyValue(node.item) ? node.item : void 0;
1811
- if (kv && kv.key.value.length > 1) {
1812
- const parentPath = change.path.slice(0, -1);
1813
- const container = isDocument(parent) || isTable(parent) || isTableArray(parent) || isInlineTable(parent) ? parent : original;
1814
- if (hasItems(container)) {
1815
- let relativePrefix;
1816
- if (isTable(container) || isTableArray(container)) {
1817
- const containerKey = container.key.item.value;
1818
- let offset = 0;
1819
- let matched = 0;
1820
- for (let k = 0; k < containerKey.length && offset < parentPath.length; k++) {
1821
- while (offset < parentPath.length && typeof parentPath[offset] === "number") offset++;
1822
- if (offset >= parentPath.length || parentPath[offset] !== containerKey[k]) break;
1823
- matched++;
1824
- offset++;
1825
- }
1826
- while (offset < parentPath.length && typeof parentPath[offset] === "number") offset++;
1827
- if (matched === containerKey.length) relativePrefix = parentPath.slice(offset);
1828
- else relativePrefix = parentPath.slice(containerKey.length + (isTableArray(container) ? 1 : 0));
1829
- } else if (isInlineTable(container)) {
1830
- if (nodeAbsolutePath) {
1831
- const containerSegs = nodeAbsolutePath.slice(0, nodeAbsolutePath.length - kv.key.value.length);
1832
- let offset = 0;
1833
- let matched = 0;
1834
- while (matched < containerSegs.length && offset < parentPath.length) {
1835
- while (offset < parentPath.length && typeof parentPath[offset] === "number") offset++;
1836
- if (offset >= parentPath.length || parentPath[offset] !== containerSegs[matched]) break;
1837
- matched++;
1838
- offset++;
1839
- }
1840
- while (offset < parentPath.length && typeof parentPath[offset] === "number") offset++;
1841
- if (matched === containerSegs.length) relativePrefix = parentPath.slice(offset);
1842
- else relativePrefix = parentPath.slice(containerSegs.length);
1843
- } else relativePrefix = parentPath.slice(parentPath.length - (kv.key.value.length - 1));
1844
- } else relativePrefix = parentPath;
1845
- relativePrefix = relativePrefix.filter((seg) => typeof seg === "string");
1846
- const remaining = container.items.filter((item) => {
1847
- const key = isKeyValue(item) ? item.key.value : isInlineItem(item) && isKeyValue(item.item) ? item.item.key.value : void 0;
1848
- if (!key) return false;
1849
- return arraysEqual(key.slice(0, relativePrefix.length), relativePrefix);
1850
- });
1851
- const isAotEntry = isTableArray(container);
1852
- let docSiblings = [];
1853
- if (isAotEntry && remaining.length === 0) docSiblings = findDocumentItemsByKeyPrefix(original, container.key.item.value.concat(relativePrefix));
1854
- const containerAlreadyIsParent = relativePrefix.length === 0 && (isTable(container) || isTableArray(container) || isInlineTable(container));
1855
- if (remaining.length === 0 && docSiblings.length === 0 && !containerAlreadyIsParent) {
1856
- let value = rawUpdated;
1857
- for (const k of parentPath) value = value === null || value === void 0 ? void 0 : value[k];
1858
- if (isObject(value) && Object.keys(value).length === 0) {
1859
- if (isInlineTable(container)) {
1860
- const freshKey = relativePrefix.map((part) => IS_BARE_KEY.test(part) ? part : JSON.stringify(part).replace(/\x7f/g, "\\u007f")).join(".");
1861
- const freshKv = Array.from(parseTOML(`${freshKey} = {}`))[0];
1862
- if (isKeyValue(freshKv)) {
1863
- const inlineItem = generateInlineItem(freshKv);
1864
- inlineItem.comma = removedInlineComma ?? false;
1865
- applyWrites(original);
1866
- if (hasInlineContainerNeedingTighten(container) && container.loc.end.line > container.loc.start.line) container.loc.end.line = container.loc.start.line;
1867
- insert(original, container, inlineItem, containerItemIndex >= 0 ? containerItemIndex : void 0);
1868
- if (format.bracketSpacing) shiftNode(inlineItem, {
1869
- lines: 0,
1870
- columns: 1
1871
- });
1872
- const tailRow = container.items[containerItemIndex + 1];
1873
- const pendingInsertOffset = getExitOffsets(original).get(inlineItem);
1874
- if (tailRow && pendingInsertOffset && tailRow.loc.start.line === inlineItem.loc.end.line) pendingInsertOffset.columns = inlineItem.loc.end.column + 2 - tailRow.loc.start.column;
1875
- }
1876
- return;
1877
- }
1878
- const tableKey = isAotEntry ? container.key.item.value.concat(relativePrefix) : isTable(container) ? container.key.item.value.concat(relativePrefix) : relativePrefix;
1879
- const emptyTable = generateTable(tableKey, format.escapeSequenceUpperCase);
1880
- materialisedTables.add(emptyTable);
1881
- let insertIdx = nodeIndex >= 0 ? nodeIndex : original.items.length;
1882
- if (isAotEntry) {
1883
- const entryIdx = original.items.indexOf(container);
1884
- insertIdx = entryIdx >= 0 ? entryIdx + 1 : original.items.length;
1885
- } else if (isTable(container)) {
1886
- const parentIdx = original.items.indexOf(container);
1887
- insertIdx = parentIdx >= 0 ? parentIdx + 1 : original.items.length;
1888
- } else if (isDocument(container)) {
1889
- const headerIdx = firstSectionHeaderIndex(original);
1890
- insertIdx = headerIdx >= 0 ? headerIdx : original.items.length;
1891
- }
1892
- applyWrites(original);
1893
- insert(original, original, emptyTable, insertIdx);
1894
- }
1895
- }
1896
- }
1897
- }
1898
- }
1899
- if (isTableArray(node)) {
1900
- const aotKey = node.key.item.value;
1901
- const aotPath = change.path.slice(0, -1);
1902
- if (!tryFindByPath(original, aotPath.concat(0)) && tryFindByPath(updated, aotPath)) emptiedAotKeys.set(aotKey.join("."), aotKey);
1903
- }
1904
- }
1905
- } else if (isMove(change)) {
1906
- if (change.key !== void 0) {
1907
- objectMoves.push(change);
1908
- return;
1909
- }
1910
- let parent = tryFindByPath(original, change.path);
1911
- if (parent) {
1912
- if (hasItem(parent)) parent = parent.item;
1913
- if (isKeyValue(parent)) parent = parent.value;
1914
- if (change.from >= parent.items.length) return;
1915
- const node = parent.items[change.from];
1916
- moveInlineElement(original, parent, node, change.to);
1917
- } else {
1918
- normalizeAotEntryComments(original);
1919
- const fromNode = findByPath(original, change.path.concat(change.from));
1920
- const fromGroup = resolveGroups(original).find((s) => s.member === fromNode);
1921
- const groupItems = fromGroup ? [...fromGroup.items] : [fromNode];
1922
- const groupOriginalPos = groupItems.map((item) => ({
1923
- startLine: item.loc.start.line,
1924
- endLine: item.loc.end.line
1925
- }));
1926
- const groupFirstIdx = original.items.indexOf(fromGroup ? fromGroup.items[0] : fromNode);
1927
- const lastGroupEnd = groupOriginalPos[groupOriginalPos.length - 1].endLine;
1928
- let originalAfterGap;
1929
- for (let k = 0; k < original.items.length; k++) {
1930
- const item = original.items[k];
1931
- if (item.loc.start.line > lastGroupEnd) {
1932
- originalAfterGap = item.loc.start.line - lastGroupEnd;
1933
- break;
1934
- }
1935
- }
1936
- if (originalAfterGap === void 0 && groupFirstIdx > 0) {
1937
- const beforeGroup = original.items[groupFirstIdx - 1];
1938
- originalAfterGap = groupOriginalPos[0].startLine - beforeGroup.loc.end.line;
1939
- }
1940
- const memberIdx = fromGroup ? fromGroup.items.indexOf(fromNode) : 0;
1941
- for (let i = 0; i <= memberIdx; i++) {
1942
- if (!original.items.includes(groupItems[i])) continue;
1943
- remove(original, original, groupItems[i]);
1944
- }
1945
- for (let i = memberIdx + 1; i < groupItems.length; i++) {
1946
- const idx = original.items.indexOf(groupItems[i]);
1947
- if (idx >= 0) original.items.splice(idx, 1);
1948
- }
1949
- const toEntry = tryFindByPath(original, change.path.concat(change.to));
1950
- let toIndex;
1951
- let targetHasLeadingComment = false;
1952
- const sourceHadLeadingComment = fromGroup && fromGroup.items[0] !== fromNode && isComment(fromGroup.items[0]);
1953
- if (toEntry) {
1954
- const targetGroup = resolveGroups(original).find((s) => s.member === toEntry);
1955
- targetHasLeadingComment = !!(targetGroup && targetGroup.items[0] !== toEntry && isComment(targetGroup.items[0]));
1956
- if (targetHasLeadingComment && sourceHadLeadingComment) toIndex = original.items.indexOf(targetGroup.items[0]);
1957
- else toIndex = original.items.indexOf(toEntry);
1958
- } else toIndex = original.items.length;
1959
- const targetPrevEnd = toIndex > 0 ? original.items[toIndex - 1].loc.end.line : 0;
1960
- const targetFirstLine = toIndex < original.items.length ? original.items[toIndex].loc.start.line : void 0;
1961
- const isCommentedSwap = targetHasLeadingComment && sourceHadLeadingComment;
1962
- let insertIdx = toIndex;
1963
- for (let i = 0; i < groupItems.length; i++) {
1964
- const item = groupItems[i];
1965
- let itemLeadingLines;
1966
- if ((isCommentedSwap || sourceHadLeadingComment && toIndex > 0 && toIndex < original.items.length) && insertIdx > 0) {
1967
- const prevEnd = i === 0 ? targetPrevEnd : groupOriginalPos[i - 1].endLine;
1968
- const origLeading = i === 0 && targetFirstLine !== void 0 ? targetFirstLine - targetPrevEnd : groupOriginalPos[i].startLine - prevEnd;
1969
- if (origLeading !== (isTable(item) || isTableArray(item) ? 2 : 1)) itemLeadingLines = origLeading;
1970
- }
1971
- insert(original, original, item, insertIdx, void 0, void 0, itemLeadingLines);
1972
- insertIdx++;
1973
- }
1974
- if (originalAfterGap !== void 0) {
1975
- applyWrites(original);
1976
- const lastItem = groupItems[groupItems.length - 1];
1977
- const afterStart = original.items.indexOf(lastItem) + 1;
1978
- if (afterStart < original.items.length) {
1979
- const newGap = original.items[afterStart].loc.start.line - lastItem.loc.end.line;
1980
- const delta = originalAfterGap - newGap;
1981
- if (delta !== 0) for (let j = afterStart; j < original.items.length; j++) shiftNode(original.items[j], {
1982
- lines: delta,
1983
- columns: 0
1984
- });
1985
- }
1986
- }
1987
- }
1988
- } else if (isRename(change)) {
1989
- const sourcePath = change.path.concat(change.from);
1990
- let parent = tryFindByPath(original, sourcePath);
1991
- if (!parent) {
1992
- const prefixNodes = findDocumentItemsByKeyPrefix(original, sourcePath);
1993
- if (prefixNodes.length === 1 && (isTable(prefixNodes[0]) || isTableArray(prefixNodes[0]))) {
1994
- const keyHolder = prefixNodes[0].key;
1995
- const key = hasItem(keyHolder) ? keyHolder.item : keyHolder;
1996
- const segmentIndex = sourcePath.length - 1;
1997
- const originalRaw = key.raw;
1998
- key.value[segmentIndex] = change.to;
1999
- key.raw = preserveEscapedKeyRaw(key.raw, key.value, format.escapeSequenceUpperCase);
2000
- preserveDottedKeySpacing(key, originalRaw);
2001
- key.loc.end.column = key.loc.start.column + key.raw.length;
2002
- return;
2003
- }
2004
- }
2005
- if (!parent) parent = findByPath(original, sourcePath);
2006
- let replacement = findByPath(updated, change.path.concat(change.to));
2007
- if (hasItem(parent)) parent = parent.item;
2008
- if (hasItem(replacement)) replacement = replacement.item;
2009
- const parentHolder = parent.key;
2010
- const replacementHolder = replacement.key;
2011
- const parentKey = hasItem(parentHolder) ? parentHolder.item : parentHolder;
2012
- const replacementKey = hasItem(replacementHolder) ? replacementHolder.item : replacementHolder;
2013
- if (parentKey.value.length !== replacementKey.value.length) {
2014
- const fullSourcePath = change.path.concat(change.from);
2015
- if ((isTable(parent) || isTableArray(parent)) && isKeyValue(replacement) && arraysEqual(parentKey.value.slice(0, fullSourcePath.length), fullSourcePath)) {
2016
- const segmentIndex = fullSourcePath.length - 1;
2017
- const originalRaw = parentKey.raw;
2018
- parentKey.value[segmentIndex] = change.to;
2019
- parentKey.raw = preserveEscapedKeyRaw(parentKey.raw, parentKey.value, format.escapeSequenceUpperCase);
2020
- preserveDottedKeySpacing(parentKey, originalRaw);
2021
- parentKey.loc.end.column = parentKey.loc.start.column + parentKey.raw.length;
2022
- return;
2023
- }
2024
- if (isKeyValue(parent) && isKeyValue(replacement) && parentKey.value.length <= fullSourcePath.length && arraysEqual(parentKey.value, fullSourcePath.slice(fullSourcePath.length - parentKey.value.length))) {
2025
- const oldKeyRaw = parentKey.raw;
2026
- parentKey.value[parentKey.value.length - 1] = change.to;
2027
- parentKey.raw = preserveEscapedKeyRaw(parentKey.raw, parentKey.value, format.escapeSequenceUpperCase);
2028
- parentKey.loc.end.column = parentKey.loc.start.column + parentKey.raw.length;
2029
- const keyWidthDelta = parentKey.raw.length - oldKeyRaw.length;
2030
- if (keyWidthDelta > 0) {
2031
- parent.equals += keyWidthDelta;
2032
- shiftNode(parent.value, {
2033
- lines: 0,
2034
- columns: keyWidthDelta
2035
- }, { first_line_only: true });
2036
- addExitOffset(original, parent.value, {
2037
- lines: 0,
2038
- columns: keyWidthDelta
2039
- });
2040
- }
2041
- return;
2042
- }
2043
- throw new Error(`Cannot rename "${parentKey.raw}" to "${replacementKey.raw}": the replacement key has ${replacementKey.value.length} segment(s) where the existing key has ${parentKey.value.length}, so one cannot be substituted for the other.`);
2044
- }
2045
- replacementKey.raw = preserveEscapedKeyRaw(parentKey.raw, replacementKey.value, format.escapeSequenceUpperCase);
2046
- preserveDottedKeySpacing(replacementKey, parentKey.raw);
2047
- replacementKey.loc.end.column = replacementKey.loc.start.column + replacementKey.raw.length;
2048
- const keyOwner = hasItem(parentHolder) ? parentHolder : parent;
2049
- replace(original, keyOwner, parentKey, replacementKey);
2050
- }
2051
- });
2052
- applyWrites(original);
2053
- for (let i = 1; i < original.items.length; i++) {
2054
- const prev = original.items[i - 1];
2055
- const curr = original.items[i];
2056
- if (isComment(prev) && isTable(curr) && materialisedTables.has(curr)) {
2057
- const gap = curr.loc.start.line - prev.loc.end.line - 1;
2058
- if (gap > 0) shiftNode(curr, {
2059
- lines: -gap,
2060
- columns: 0
2061
- });
2062
- }
2063
- }
2064
- const rootItems = original.items;
2065
- for (let i = 0; i < rootItems.length - 1; i++) {
2066
- const curr = rootItems[i];
2067
- const next = rootItems[i + 1];
2068
- if ((isTable(curr) || isTableArray(curr)) && curr.items.length === 0 && (isTable(next) || isTableArray(next))) {
2069
- const gap = next.loc.start.line - curr.loc.end.line - 1;
2070
- if (gap > 1) {
2071
- const delta = 1 - gap;
2072
- for (let j = i + 1; j < rootItems.length; j++) shiftNode(rootItems[j], {
2073
- lines: delta,
2074
- columns: 0
2075
- });
2076
- }
2077
- }
2078
- }
2079
- let needsTighten = false;
2080
- traverse(original, {
2081
- InlineTable: (node) => {
2082
- if (hasInlineContainerNeedingTighten(node)) needsTighten = true;
2083
- },
2084
- InlineArray: (node) => {
2085
- if (hasInlineContainerNeedingTighten(node)) needsTighten = true;
2086
- }
2087
- });
2088
- if (needsTighten) applyWrites(original);
2089
- let hasTightened = false;
2090
- const tightenedInlineContainers = [];
2091
- traverse(original, {
2092
- InlineTable: (node) => {
2093
- if (hasInlineContainerNeedingTighten(node)) {
2094
- tightenedInlineContainers.push(node);
2095
- tightenInlineContainerEnd(node);
2096
- deleteInlineContainerNeedingTighten(node);
2097
- applyBracketSpacing(original, node, format.bracketSpacing);
2098
- hasTightened = true;
2099
- }
2100
- },
2101
- InlineArray: (node) => {
2102
- if (hasInlineContainerNeedingTighten(node)) {
2103
- tightenInlineContainerEnd(node);
2104
- deleteInlineContainerNeedingTighten(node);
2105
- applyBracketSpacing(original, node, format.bracketSpacing);
2106
- hasTightened = true;
2107
- }
2108
- }
2109
- });
2110
- if (hasTightened) {
2111
- applyWrites(original);
2112
- for (const container of tightenedInlineContainers) compactInlineContainerAncestors(original, container);
2113
- recalcInlineContainerEnds(original);
2114
- }
2115
- cleanupOrphanedComments(original);
2116
- replaceEmptiedTableArrays(original, emptiedAotKeys, format);
2117
- applyKeyOrderMoves(original, objectMoves, commentEligibleNodes);
2118
- if (objectMoves.length > 0) markDirty(original);
2119
- if (replacedInlineArrays.size > 0) {
2120
- applyWrites(original);
2121
- for (const array of replacedInlineArrays) positionGeneratedNestedInlineTables(array, format.indentWidth);
2122
- }
2123
- if (replacedInlineContainers.length > 0) {
2124
- applyWrites(original);
2125
- for (const { owner, container } of replacedInlineContainers) {
2126
- deleteSubtreeRanges(container);
2127
- normalizeInlineContainerRows(container, owner.loc.start.column, format.indentWidth, format.bracketSpacing);
2128
- }
2129
- }
2130
- return original;
2131
- }
2132
- /**
2133
- * Drops the `range` of a node and every descendant, so the renderer rebuilds
2134
- * the text from the node locations instead of copying the original slice.
2135
- *
2136
- * Regenerated values are parsed from a standalone TOML snippet, so their ranges
2137
- * point into that snippet. Relocating the subtree shifts the locations but not
2138
- * the snippet's interior text: a copied slice would keep the snippet's absolute
2139
- * indentation and ignore the new row positions (fuzz3 seed 18515).
2140
- */
2141
- function deleteSubtreeRanges(node) {
2142
- delete node.range;
2143
- if (hasItems(node)) for (const child of node.items) deleteSubtreeRanges(child);
2144
- if (hasItem(node)) deleteSubtreeRanges(node.item);
2145
- if (isKeyValue(node)) {
2146
- deleteSubtreeRanges(node.key);
2147
- deleteSubtreeRanges(node.value);
2148
- }
2149
- }
2150
- /**
2151
- * Position of the first `[table]`/`[[array]]` header in `doc`, or -1 if there is none.
2152
- *
2153
- * A key-value that physically follows a section header belongs to that section, not to the
2154
- * root table. So any path that regenerates a root-level key has to land it above the first
2155
- * header — appending at the end of the document silently reparents it, and the value comes
2156
- * back under the wrong key on the next parse. See
2157
- * docs/bug-notes/comment-eligibility-on-structural-replace.md.
2158
- */
2159
- function firstSectionHeaderIndex(doc) {
2160
- return doc.items.findIndex((item) => isTable(item) || isTableArray(item));
2161
- }
2162
- /** Index to insert a regenerated root key-value at so it stays in the root table. */
2163
- function rootKeyValueInsertIndex(doc) {
2164
- const firstTableIndex = firstSectionHeaderIndex(doc);
2165
- return firstTableIndex === -1 ? void 0 : firstTableIndex;
2166
- }
2167
- /**
2168
- * Moves an already-inserted root-level key-value back above the first section header, for the
2169
- * paths that place it via `replace()` (which pins it to the replaced node's position) rather
2170
- * than choosing an index. Also tends to reunite the key with a leading comment left behind at
2171
- * its original position.
2172
- */
2173
- function hoistRootKeyValueAboveTables(doc, kv) {
2174
- const kvIndex = doc.items.indexOf(kv);
2175
- if (kvIndex < 0) return;
2176
- const firstTableIndex = firstSectionHeaderIndex(doc);
2177
- if (firstTableIndex === -1 || firstTableIndex > kvIndex) return;
2178
- remove(doc, doc, kv);
2179
- applyWrites(doc);
2180
- insert(doc, doc, kv, firstTableIndex);
2181
- }
2182
- /**
2183
- * The converse of hoistRootKeyValueAboveTables: an edit that turned a
2184
- * root-level KeyValue into a Table section inserts a section header where
2185
- * the KV was — and a section header captures every key-value that follows it
2186
- * in the document. If any root KV comes after the new header (and before the
2187
- * next section), move the table below the root-table scope (fuzz seed 590:
2188
- * `g86 = "str"` became `[g86]` while `fofc`/`y3n`/`"<w"` followed it).
2189
- */
2190
- function sinkTableBelowRootKeyValues(doc, table) {
2191
- const tableIndex = doc.items.indexOf(table);
2192
- if (tableIndex < 0) return;
2193
- const nextSectionIndex = doc.items.findIndex((item, i) => i > tableIndex && (isTable(item) || isTableArray(item)));
2194
- if (!doc.items.some((item, i) => i > tableIndex && isKeyValue(item) && (nextSectionIndex === -1 || i < nextSectionIndex))) return;
2195
- const target = nextSectionIndex === -1 ? doc.items.length : nextSectionIndex;
2196
- applyWrites(doc);
2197
- remove(doc, doc, table);
2198
- insert(doc, doc, table, target - 1);
2199
- }
2200
- /**
2201
- * Handles structural edits where findByPath can't resolve the existing CST node
2202
- * because the structure type has changed (e.g. table→scalar, AOT→scalar, array→empty).
2203
- * Swaps the fresh key-value in for the old structural nodes.
2204
- */
2205
- function handleStructuralEdit(original, updated, change, format, temporal, commentEligibleNodes, materialisedTables) {
2206
- let jsValue = toJS(updated.items, "", { temporal });
2207
- for (const key of change.path) jsValue = jsValue === null || jsValue === void 0 ? void 0 : jsValue[key];
2208
- if (jsValue === void 0) return;
2209
- {
2210
- const aotIndexPos = change.path.findIndex((seg) => typeof seg === "number");
2211
- if (aotIndexPos > 0 && change.path.slice(aotIndexPos + 1).every((seg) => typeof seg === "string")) {
2212
- const entry = tryFindByPath(original, change.path.slice(0, aotIndexPos + 1));
2213
- if (entry && isTableArray(entry)) {
2214
- const entryKey = entry.key.item.value;
2215
- const changedKey = change.path.slice(aotIndexPos + 1);
2216
- const toRemove = findDocumentItemsByKeyPrefix(original, entryKey.concat(changedKey));
2217
- for (const prefixNode of toRemove) removeMember(original, original, prefixNode);
2218
- const inlineToRemove = entry.items.filter((item) => {
2219
- const key = isKeyValue(item) ? item.key.value : void 0;
2220
- return key && key.length > changedKey.length && arraysEqual(key.slice(0, changedKey.length), changedKey);
2221
- });
2222
- for (const item of inlineToRemove) removeMember(original, entry, item);
2223
- let tail = jsValue;
2224
- for (let k = change.path.length - 1; k > aotIndexPos; k--) tail = { [change.path[k]]: tail };
2225
- const tailDoc = parseJS(tail, format);
2226
- const tailToml = toTOML(tailDoc.items, format);
2227
- const tailCst = Array.from(parseTOML(tailToml));
2228
- const upsertEntryKeyValue = (kv) => {
2229
- const existingRow = entry.items.find((row) => isKeyValue(row) && arraysEqual(row.key.value, kv.key.value));
2230
- if (existingRow) replace(original, entry, existingRow, kv);
2231
- else insert(original, entry, kv, void 0);
2232
- };
2233
- for (const item of tailCst) {
2234
- if (isKeyValue(item)) {
2235
- upsertEntryKeyValue(item);
2236
- continue;
2237
- }
2238
- if (isTable(item)) {
2239
- const tableKey = item.key.item.value;
2240
- for (const row of item.items) {
2241
- if (!isKeyValue(row)) continue;
2242
- const oldRaw = row.key.raw;
2243
- const dotted = tableKey.concat(row.key.value);
2244
- row.key.value = dotted;
2245
- row.key.raw = generateKey(dotted, format.escapeSequenceUpperCase).raw;
2246
- const delta = row.key.raw.length - oldRaw.length;
2247
- row.key.loc.end.column = row.key.loc.start.column + row.key.raw.length;
2248
- row.equals += delta;
2249
- shiftNode(row.value, {
2250
- lines: 0,
2251
- columns: delta
2252
- }, { first_line_only: true });
2253
- if (row.loc.end.line === row.loc.start.line) row.loc.end.column += delta;
2254
- upsertEntryKeyValue(row);
2255
- }
2256
- }
2257
- }
2258
- return;
2259
- }
2260
- }
2261
- }
2262
- let nested = jsValue;
2263
- for (let i = change.path.length - 1; i >= 0; i--) nested = { [change.path[i]]: nested };
2264
- const prefixNodes = findDocumentItemsByKeyPrefix(original, change.path);
2265
- for (const prefixNode of prefixNodes) remove(original, original, prefixNode);
2266
- const freshDoc = parseJS(nested, format);
2267
- const replacementToml = toTOML(freshDoc.items, format);
2268
- const replacementCst = Array.from(parseTOML(replacementToml));
2269
- const insertIndex = rootKeyValueInsertIndex(original);
2270
- if (insertIndex !== void 0) applyWrites(original);
2271
- let firstInserted;
2272
- for (let i = 0; i < replacementCst.length; i++) {
2273
- const item = replacementCst[i];
2274
- const existingTable = isTable(item) ? original.items.find((t) => isTable(t) && arraysEqual(t.key.item.value, item.key.item.value)) : void 0;
2275
- if (existingTable) {
2276
- for (const row of item.items) insert(original, existingTable, row, void 0);
2277
- if (!firstInserted) firstInserted = existingTable;
2278
- continue;
2279
- }
2280
- if (isKeyValue(item) && isInlineTable(item.value)) {
2281
- const kvKey = item.key.value;
2282
- const survivingTable = original.items.find((t) => isTable(t) && arraysEqual(t.key.item.value, kvKey));
2283
- if (survivingTable) {
2284
- for (const row of item.value.items) {
2285
- const rowNode = isInlineItem(row) ? row.item : row;
2286
- insert(original, survivingTable, rowNode, void 0);
2287
- }
2288
- if (!firstInserted) firstInserted = survivingTable;
2289
- continue;
2290
- }
2291
- if (findDocumentItemsByKeyPrefix(original, kvKey).filter((t) => isKeyValue(t) || isTable(t) || isTableArray(t)).length > 0) {
2292
- for (const row of item.value.items) {
2293
- const rowNode = isInlineItem(row) ? row.item : row;
2294
- if (isKeyValue(rowNode)) {
2295
- const oldRaw = rowNode.key.raw;
2296
- const dotted = kvKey.concat(rowNode.key.value);
2297
- rowNode.key.value = dotted;
2298
- rowNode.key.raw = dotted.map((part) => IS_BARE_KEY.test(part) ? part : JSON.stringify(part).replace(/\x7f/g, "\\u007f")).join(".");
2299
- const delta = rowNode.key.raw.length - oldRaw.length;
2300
- rowNode.key.loc.end.column = rowNode.key.loc.start.column + rowNode.key.raw.length;
2301
- rowNode.equals += delta;
2302
- shiftNode(rowNode.value, {
2303
- lines: 0,
2304
- columns: delta
2305
- }, { first_line_only: true });
2306
- if (rowNode.loc.end.line === rowNode.loc.start.line) rowNode.loc.end.column += delta;
2307
- }
2308
- insert(original, original, rowNode, i === 0 ? insertIndex : void 0);
2309
- if (!firstInserted) firstInserted = rowNode;
2310
- }
2311
- continue;
2312
- }
2313
- }
2314
- if (isTable(item)) {
2315
- const tableKey = item.key.item.value;
2316
- if (findDocumentItemsByKeyPrefix(original, tableKey).filter((t) => isKeyValue(t)).length > 0) {
2317
- for (const row of item.items) {
2318
- if (isKeyValue(row)) {
2319
- const oldRaw = row.key.raw;
2320
- const dotted = tableKey.concat(row.key.value);
2321
- row.key.value = dotted;
2322
- row.key.raw = dotted.map((part) => IS_BARE_KEY.test(part) ? part : JSON.stringify(part).replace(/\x7f/g, "\\u007f")).join(".");
2323
- const delta = row.key.raw.length - oldRaw.length;
2324
- row.key.loc.end.column = row.key.loc.start.column + row.key.raw.length;
2325
- row.equals += delta;
2326
- shiftNode(row.value, {
2327
- lines: 0,
2328
- columns: delta
2329
- }, { first_line_only: true });
2330
- if (row.loc.end.line === row.loc.start.line) row.loc.end.column += delta;
2331
- }
2332
- insert(original, original, row, i === 0 ? insertIndex : void 0);
2333
- if (!firstInserted) firstInserted = row;
2334
- }
2335
- continue;
2336
- }
2337
- }
2338
- if (i > 0 && firstInserted && isTable(firstInserted) && isKeyValue(item)) insert(original, firstInserted, item, void 0);
2339
- else insert(original, original, item, i === 0 ? insertIndex : void 0);
2340
- if (!firstInserted) firstInserted = item;
2341
- }
2342
- const replacementKV = firstInserted;
2343
- if (isTable(replacementKV)) materialisedTables.add(replacementKV);
2344
- commentEligibleNodes.add(replacementKV);
2345
- }
2346
- /**
2347
- * Tighten the end column of a single-line InlineTable or InlineArray whose
2348
- * only item was removed by remove(). When items remain, the end is tightened
2349
- * to just after the last item; when empty, to start + 2 so brackets touch
2350
- * (e.g. `[]` or `{}`). loc.end is exclusive.
2351
- */
2352
- function tightenInlineContainerEnd(node) {
2353
- if (node.items.length > 0) {
2354
- const lastItem = node.items[node.items.length - 1];
2355
- node.loc.end.column = lastItem.loc.end.column + 1;
2356
- } else {
2357
- node.loc.end.line = node.loc.start.line;
2358
- node.loc.end.column = node.loc.start.column + 2;
2359
- }
2360
- }
2361
- function compactInlineContainerAncestors(root, target) {
2362
- const path = [];
2363
- const locate = (node) => {
2364
- path.push(node);
2365
- if (node === target) return true;
2366
- if (isKeyValue(node)) {
2367
- if (locate(node.value)) return true;
2368
- } else if (isInlineItem(node)) {
2369
- if (locate(node.item)) return true;
2370
- } else if (hasItems(node)) {
2371
- for (const item of node.items) if (locate(item)) return true;
2372
- }
2373
- path.pop();
2374
- return false;
2375
- };
2376
- if (!locate(root)) return;
2377
- const enclosingRow = path.findLast(isInlineItem);
2378
- if (!enclosingRow) return;
2379
- const lineDelta = target.loc.end.line - enclosingRow.loc.end.line;
2380
- if (lineDelta === 0) return;
2381
- const inlineContainerIndex = path.findLastIndex((node, index) => index < path.length - 1 && (isInlineTable(node) || isInlineArray(node)));
2382
- if (inlineContainerIndex < 0) return;
2383
- const inlineContainer = path[inlineContainerIndex];
2384
- const child = path[inlineContainerIndex + 1];
2385
- const childIndex = inlineContainer.items.indexOf(child);
2386
- const next = childIndex >= 0 ? inlineContainer.items[childIndex + 1] : void 0;
2387
- if (childIndex < 0 || !next) return;
2388
- const gap = next.loc.start.column - child.loc.end.column;
2389
- const columnDelta = resolveInnerEndCol(child) + gap - next.loc.start.column;
2390
- for (let i = childIndex + 1; i < inlineContainer.items.length; i++) shiftNode(inlineContainer.items[i], {
2391
- lines: lineDelta,
2392
- columns: columnDelta
2393
- });
2394
- inlineContainer.loc.end.column += columnDelta;
2395
- for (const node of path) if (node !== target && node.loc.end.line > target.loc.end.line) node.loc.end.line += lineDelta;
2396
- for (let i = path.length - 1; i >= 0; i--) {
2397
- const node = path[i];
2398
- if (isKeyValue(node)) {
2399
- node.loc.end = { ...node.value.loc.end };
2400
- if (node.value !== target && isInlineTable(node.value)) node.loc.end.column += columnDelta;
2401
- } else if (isInlineItem(node)) node.loc.end = { ...node.item.loc.end };
2402
- }
2403
- }
2404
- /**
2405
- * After tightening a nested single-line InlineTable (whose only item was
2406
- * removed), recalculate the end positions of any parent single-line InlineTable
2407
- * or InlineArray containers. The remove() call zeroed the offset for the
2408
- * removed item (single-line, no siblings), so applyWrites can't propagate the
2409
- * shrink to ancestor containers.
2410
- */
2411
- function recalcInlineContainerEnds(root) {
2412
- traverse(root, {
2413
- InlineTable: { exit: (node) => {
2414
- if (node.items.length === 0) return;
2415
- if (node.loc.end.line !== node.loc.start.line) return;
2416
- const lastItem = node.items[node.items.length - 1];
2417
- const innerEndCol = resolveInnerEndCol(lastItem);
2418
- const originalEndCol = node.loc.end.column;
2419
- const newEndCol = innerEndCol + (originalEndCol - lastItem.loc.end.column);
2420
- if (newEndCol !== originalEndCol) node.loc.end.column = newEndCol;
2421
- } },
2422
- InlineArray: { exit: (node) => {
2423
- if (node.items.length === 0) return;
2424
- if (node.loc.end.line !== node.loc.start.line) return;
2425
- const lastItem = node.items[node.items.length - 1];
2426
- const innerEndCol = resolveInnerEndCol(lastItem);
2427
- const originalEndCol = node.loc.end.column;
2428
- const newEndCol = innerEndCol + (originalEndCol - lastItem.loc.end.column);
2429
- if (newEndCol !== originalEndCol) node.loc.end.column = newEndCol;
2430
- } }
2431
- });
2432
- }
2433
- /**
2434
- * Resolve the effective end column of an InlineItem's inner value,
2435
- * looking through KeyValue wrappers and into tightened InlineTable or
2436
- * InlineArray containers. Returns lastItem.loc.end.column for items
2437
- * that don't need or support look-through.
2438
- */
2439
- function resolveInnerEndCol(lastItem) {
2440
- if (!isInlineItem(lastItem)) return lastItem.loc.end.column;
2441
- if (isKeyValue(lastItem.item)) {
2442
- const v = lastItem.item.value;
2443
- if (isInlineTable(v) || isInlineArray(v)) return v.loc.end.column;
2444
- }
2445
- if (isInlineTable(lastItem.item) || isInlineArray(lastItem.item)) return lastItem.item.loc.end.column;
2446
- return lastItem.loc.end.column;
2447
- }
2448
- /**
2449
- * Removes Comment nodes that were extracted from inside an InlineArray
2450
- * when that array has been emptied.
2451
- *
2452
- * When a multiline inline array has interior comments (e.g. `arr = [\n 1, # one\n 2, # two\n]`),
2453
- * the parser extracts the comments to the parent Document level as siblings of the KeyValue.
2454
- * If the array is later emptied, these comments become orphaned and must be removed
2455
- * to produce valid TOML output.
2456
- *
2457
- * This does NOT apply to InlineTables, where interior comments are meaningful
2458
- * section-level comments that should be preserved even when the table is empty.
2459
- */
2460
- function cleanupOrphanedComments(doc) {
2461
- traverse(doc, { KeyValue: (kv) => {
2462
- const value = kv.value;
2463
- if (!isInlineArray(value)) return;
2464
- if (value.items.length > 0) return;
2465
- const parentContainer = findParent(doc, [kv.key.value[0]]);
2466
- if (!parentContainer || !hasItems(parentContainer)) return;
2467
- const kvStartLine = kv.loc.start.line;
2468
- const kvEndLine = kv.loc.end.line;
2469
- const items = parentContainer.items;
2470
- for (let i = items.length - 1; i >= 0; i--) {
2471
- const item = items[i];
2472
- if (!isComment(item)) continue;
2473
- const commentLine = item.loc.start.line;
2474
- if (commentLine >= kvStartLine && commentLine <= kvEndLine) items.splice(i, 1);
2475
- }
2476
- } });
2477
- }
2478
- /**
2479
- * Replaces emptied TableArrays with inline empty array key-values so that
2480
- * keys aren't silently lost when all AOT entries are removed (e.g. b = []).
2481
- */
2482
- function replaceEmptiedTableArrays(doc, emptiedKeys, format) {
2483
- if (emptiedKeys.size === 0) return;
2484
- for (const path of emptiedKeys.values()) {
2485
- if (path.length > 1) {
2486
- const parentEntry = tryFindByPath(doc, path.slice(0, -1).concat([0]));
2487
- if (parentEntry && isTableArray(parentEntry)) {
2488
- const lastSegment = path[path.length - 1];
2489
- const emptyArrayDoc = parseJS({ [lastSegment]: [] }, format);
2490
- const emptyKV = generateKeyValue([lastSegment], emptyArrayDoc.items[0].value);
2491
- applyWrites(doc);
2492
- insert(doc, parentEntry, emptyKV);
2493
- continue;
2494
- }
2495
- let hostTable;
2496
- for (let len = path.length - 1; len >= 1; len--) {
2497
- const ancestor = tryFindByPath(doc, path.slice(0, len));
2498
- if (ancestor && isTable(ancestor)) {
2499
- hostTable = ancestor;
2500
- break;
2501
- }
2502
- }
2503
- if (hostTable) {
2504
- const relativeKey = path.slice(hostTable.key.item.value.length);
2505
- const emptyArrayDoc = parseJS({ [relativeKey[relativeKey.length - 1]]: [] }, format);
2506
- const emptyKV = generateKeyValue(relativeKey, emptyArrayDoc.items[0].value);
2507
- applyWrites(doc);
2508
- insert(doc, hostTable, emptyKV);
2509
- continue;
2510
- }
2511
- }
2512
- const emptyArrayDoc = parseJS({ [path[path.length - 1]]: [] }, format);
2513
- const emptyKV = generateKeyValue(path, emptyArrayDoc.items[0].value);
2514
- applyWrites(doc);
2515
- insert(doc, doc, emptyKV, rootKeyValueInsertIndex(doc));
2516
- }
2517
- applyWrites(doc);
2518
- }
2519
- /**
2520
- * Converts nested inline tables to separate table sections based on the inlineTableStart depth setting.
2521
- * This function recursively processes a table and extracts any inline tables within it,
2522
- * creating separate table sections with properly nested keys.
2523
- *
2524
- * @param table - The table to process for nested inline tables
2525
- * @param original - The original document for inserting new items
2526
- * @param format - The formatting options
2527
- * @returns Array of additional tables that should be added to the document
2528
- */
2529
- function convertNestedInlineTablesToMultiline(table, original, format) {
2530
- const additionalTables = [];
2531
- const processTableForNestedInlines = (currentTable, tablesToAdd) => {
2532
- for (let i = currentTable.items.length - 1; i >= 0; i--) {
2533
- const item = currentTable.items[i];
2534
- if (isKeyValue(item) && isInlineTable(item.value)) {
2535
- const nestedTableKey = [...currentTable.key.item.value, ...item.key.value];
2536
- if (calculateTableDepth(nestedTableKey) < (format.inlineTableStart ?? 1) && format.inlineTableStart !== 0) {
2537
- const separateTable = generateTable(nestedTableKey, format.escapeSequenceUpperCase);
2538
- for (const inlineItem of item.value.items) if (isInlineItem(inlineItem) && isKeyValue(inlineItem.item)) insert(original, separateTable, inlineItem.item, void 0);
2539
- currentTable.items.splice(i, 1);
2540
- postInlineItemRemovalAdjustment(currentTable);
2541
- tablesToAdd.push(separateTable);
2542
- processTableForNestedInlines(separateTable, tablesToAdd);
2543
- }
2544
- }
2545
- }
2546
- };
2547
- processTableForNestedInlines(table, additionalTables);
2548
- return additionalTables;
2549
- }
2550
- /**
2551
- * Converts an inline table to a separate table section when adding to an existing table.
2552
- * This function creates a new table section with the combined key path and moves all
2553
- * properties from the inline table to the separate table section.
2554
- *
2555
- * @param child - The KeyValue node with an InlineTable as its value
2556
- * @param parent - The parent table where the KeyValue would be added
2557
- * @param original - The original document for inserting new items
2558
- * @param format - The formatting options
2559
- */
2560
- function convertInlineTableToSeparateSection(child, parent, original, format) {
2561
- const nestedTableKey = [...parent.key.item.value, ...child.key.value];
2562
- const separateTable = generateTable(nestedTableKey, format.escapeSequenceUpperCase);
2563
- if (isInlineTable(child.value)) {
2564
- for (const inlineItem of child.value.items) if (isInlineItem(inlineItem) && isKeyValue(inlineItem.item)) insert(original, separateTable, inlineItem.item, void 0);
2565
- }
2566
- insert(original, original, separateTable, void 0);
2567
- postInlineItemRemovalAdjustment(parent);
2568
- const additionalTables = convertNestedInlineTablesToMultiline(separateTable, original, format);
2569
- for (const table of additionalTables) insert(original, original, table, void 0);
2570
- }
2571
- /**
2572
- * Regenerate a replacement Value node with clean loc values through a
2573
- * TOML round-trip. Handles both KeyValue and Table output from parseJS
2574
- * (formatTopLevel may convert a root-level key to a [section] when
2575
- * inlineTableStart is 0). Returns undefined when the value cannot be
2576
- * safely regenerated.
2577
- */
2578
- function regenerateValue(jsValue, format) {
2579
- const inlineFmt = resolveTomlFormat({
2580
- ...format,
2581
- inlineTableStart: 0
2582
- }, format);
2583
- const freshDoc = parseJS({ __tmp__: jsValue }, inlineFmt);
2584
- const replacementToml = toTOML(freshDoc.items, inlineFmt);
2585
- const freshItem = Array.from(parseTOML(replacementToml))[0];
2586
- if (isKeyValue(freshItem)) return freshItem.value;
2587
- if (isTable(freshItem) && freshItem.items.length > 0 && isKeyValue(freshItem.items[0])) return freshItem.items[0].value;
2588
- }
2589
- function findEnclosingInlineTableRowContext(document, path) {
2590
- for (let i = path.length - 1; i > 0; i--) {
2591
- const candidate = tryFindByPath(document, path.slice(0, i));
2592
- if (!candidate || !isKeyValue(candidate) || !isInlineTable(candidate.value)) continue;
2593
- const container = tryFindByPath(document, path.slice(0, i - 1));
2594
- if (container && hasItems(container)) return {
2595
- container,
2596
- row: candidate
2597
- };
2598
- }
2599
- }
2600
- /**
2601
- * Finds all Document-level items whose key path starts with the given prefix.
2602
- * This handles implicit intermediate keys — keys that are a prefix of a dotted
2603
- * table key but have no CST node of their own (e.g. path ["references"] when
2604
- * only ["references", "VBIDE"] exists in the document).
2605
- */
2606
- function findDocumentItemsByKeyPrefix(document, pathPrefix) {
2607
- const matchingNodes = [];
2608
- for (const item of document.items) {
2609
- let key;
2610
- if (isKeyValue(item)) key = item.key.value;
2611
- else if (isTable(item)) key = item.key.item.value;
2612
- else if (isTableArray(item)) key = item.key.item.value;
2613
- if (key && arraysEqual(key.slice(0, pathPrefix.length), pathPrefix)) matchingNodes.push(item);
2614
- }
2615
- return matchingNodes;
2616
- }
2617
- /**
2618
- * Converts a JS-object change path into CST key coordinates by dropping the
2619
- * numeric array-of-tables entry indices. The diff walks the JS object, so a
2620
- * path into an AOT entry interleaves the entry's numeric index (e.g. `["", 0,
2621
- * "fv"]`), but CST keys carry no such index — `[[""]]` entries live at the
2622
- * document level and their sub-tables are keyed `["", "fv"]`. A numeric
2623
- * segment is an AOT entry index when the accumulated path is a document-level
2624
- * TableArray key; inline-array indices (which ARE part of the CST path) never
2625
- * resolve to a document-level TableArray.
2626
- */
2627
- function stripAotEntryIndices(original, jsPath) {
2628
- const cstPath = [];
2629
- for (const seg of jsPath) {
2630
- if (typeof seg === "number") {
2631
- if (findDocumentItemsByKeyPrefix(original, cstPath).some(isTableArray)) continue;
2632
- }
2633
- cstPath.push(seg);
2634
- }
2635
- return cstPath;
2636
- }
2637
- /**
2638
- * Removes sibling key-values and table/table-array sections whose key extends
2639
- * `prefix` (i.e. `prefix` is a strict prefix of the sibling's key) from
2640
- * `container`'s items, leaving `keep` untouched. Used when a key collapses to
2641
- * a scalar: any dotted-key or section that still nests under it would re-define
2642
- * the key on re-parse ("Value already defined").
2643
- *
2644
- * Iterates a snapshot of the items because `removeMember` splices the live
2645
- * array (fuzz seed 31662).
2646
- */
2647
- function removeSiblingsExtendingPrefix(original, container, prefix, keep) {
2648
- const parentItems = [...container.items];
2649
- for (let si = parentItems.length - 1; si >= 0; si--) {
2650
- const sibling = parentItems[si];
2651
- if (sibling === keep) continue;
2652
- const siblingKey = isKeyValue(sibling) ? sibling.key.value : isTable(sibling) || isTableArray(sibling) ? sibling.key.item.value : void 0;
2653
- if (siblingKey && siblingKey.length > prefix.length && arraysEqual(siblingKey.slice(0, prefix.length), prefix)) removeMember(original, container, sibling);
2654
- }
2655
- }
2656
-
2657
- //#endregion
2658
- export { patch as default, patchCst };
2659
- //# sourceMappingURL=patch.js.map