@decimalturn/toml-patch 3.0.4 → 3.1.0-dev
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.
- package/dist/dev/comment-alignment.js +372 -0
- package/dist/dev/comment-alignment.js.map +1 -0
- package/dist/dev/comment-ownership.js +660 -0
- package/dist/dev/comment-ownership.js.map +1 -0
- package/dist/dev/cst-source.js +108 -0
- package/dist/dev/cst-source.js.map +1 -0
- package/dist/dev/cst.js +59 -0
- package/dist/dev/cst.js.map +1 -0
- package/dist/dev/cursor.js +66 -0
- package/dist/dev/cursor.js.map +1 -0
- package/dist/dev/date-format.js +196 -0
- package/dist/dev/date-format.js.map +1 -0
- package/dist/dev/decode-utf8.js +27 -0
- package/dist/dev/decode-utf8.js.map +1 -0
- package/dist/dev/diff.js +269 -0
- package/dist/dev/diff.js.map +1 -0
- package/dist/dev/escape-preference.js +144 -0
- package/dist/dev/escape-preference.js.map +1 -0
- package/dist/dev/find-by-path.js +111 -0
- package/dist/dev/find-by-path.js.map +1 -0
- package/dist/dev/formatter.js +295 -0
- package/dist/dev/formatter.js.map +1 -0
- package/dist/dev/generate.js +451 -0
- package/dist/dev/generate.js.map +1 -0
- package/dist/dev/inline-comma-space.js +13 -0
- package/dist/dev/inline-comma-space.js.map +1 -0
- package/dist/dev/inline-format.js +106 -0
- package/dist/dev/inline-format.js.map +1 -0
- package/dist/dev/inline-layout.js +107 -0
- package/dist/dev/inline-layout.js.map +1 -0
- package/dist/dev/line-ending-backslash.js +320 -0
- package/dist/dev/line-ending-backslash.js.map +1 -0
- package/dist/dev/location.js +77 -0
- package/dist/dev/location.js.map +1 -0
- package/dist/dev/parse-error.js +27 -0
- package/dist/dev/parse-error.js.map +1 -0
- package/dist/dev/parse-js.js +103 -0
- package/dist/dev/parse-js.js.map +1 -0
- package/dist/dev/parse-string.js +122 -0
- package/dist/dev/parse-string.js.map +1 -0
- package/dist/dev/parse-toml.js +669 -0
- package/dist/dev/parse-toml.js.map +1 -0
- package/dist/dev/patch.js +2537 -0
- package/dist/dev/patch.js.map +1 -0
- package/dist/dev/to-js.js +303 -0
- package/dist/dev/to-js.js.map +1 -0
- package/dist/dev/to-toml.js +569 -0
- package/dist/dev/to-toml.js.map +1 -0
- package/dist/dev/tokenizer.js +225 -0
- package/dist/dev/tokenizer.js.map +1 -0
- package/dist/dev/toml-document.js +215 -0
- package/dist/dev/toml-document.js.map +1 -0
- package/dist/dev/toml-format.js +476 -0
- package/dist/dev/toml-format.js.map +1 -0
- package/dist/dev/toml-patch.js +84 -0
- package/dist/dev/toml-patch.js.map +1 -0
- package/dist/dev/traverse.js +61 -0
- package/dist/dev/traverse.js.map +1 -0
- package/dist/dev/truncate.js +64 -0
- package/dist/dev/truncate.js.map +1 -0
- package/dist/dev/update-order.js +235 -0
- package/dist/dev/update-order.js.map +1 -0
- package/dist/dev/utils.js +223 -0
- package/dist/dev/utils.js.map +1 -0
- package/dist/dev/writer.js +758 -0
- package/dist/dev/writer.js.map +1 -0
- package/dist/toml-patch.d.ts +28 -13
- package/package.json +12 -88
- package/LICENSE +0 -22
- package/README.md +0 -161
- package/dist/toml-patch.js +0 -54
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
//! @decimalturn/toml-patch v3.1.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
|
|
2
|
+
import { isIterable } from "./utils.js";
|
|
3
|
+
|
|
4
|
+
//#region src/traverse.ts
|
|
5
|
+
function traverse(cst, visitor) {
|
|
6
|
+
if (isIterable(cst)) traverseArray(cst, null);
|
|
7
|
+
else traverseNode(cst, null);
|
|
8
|
+
function traverseArray(array, parent) {
|
|
9
|
+
for (const node of array) traverseNode(node, parent);
|
|
10
|
+
}
|
|
11
|
+
function traverseNode(node, parent) {
|
|
12
|
+
const visit = visitor[node.type];
|
|
13
|
+
if (visit && typeof visit === "function") visit(node, parent);
|
|
14
|
+
if (visit && visit.enter) visit.enter(node, parent);
|
|
15
|
+
switch (node.type) {
|
|
16
|
+
case "Document":
|
|
17
|
+
traverseArray(node.items, node);
|
|
18
|
+
break;
|
|
19
|
+
case "Table":
|
|
20
|
+
traverseNode(node.key, node);
|
|
21
|
+
traverseArray(node.items, node);
|
|
22
|
+
break;
|
|
23
|
+
case "TableKey":
|
|
24
|
+
traverseNode(node.item, node);
|
|
25
|
+
break;
|
|
26
|
+
case "TableArray":
|
|
27
|
+
traverseNode(node.key, node);
|
|
28
|
+
traverseArray(node.items, node);
|
|
29
|
+
break;
|
|
30
|
+
case "TableArrayKey":
|
|
31
|
+
traverseNode(node.item, node);
|
|
32
|
+
break;
|
|
33
|
+
case "KeyValue":
|
|
34
|
+
traverseNode(node.key, node);
|
|
35
|
+
traverseNode(node.value, node);
|
|
36
|
+
break;
|
|
37
|
+
case "InlineArray":
|
|
38
|
+
traverseArray(node.items, node);
|
|
39
|
+
break;
|
|
40
|
+
case "InlineItem":
|
|
41
|
+
traverseNode(node.item, node);
|
|
42
|
+
break;
|
|
43
|
+
case "InlineTable":
|
|
44
|
+
traverseArray(node.items, node);
|
|
45
|
+
break;
|
|
46
|
+
case "Key":
|
|
47
|
+
case "String":
|
|
48
|
+
case "Integer":
|
|
49
|
+
case "Float":
|
|
50
|
+
case "Boolean":
|
|
51
|
+
case "DateTime":
|
|
52
|
+
case "Comment": break;
|
|
53
|
+
default: throw new Error(`Unrecognized node type "${node.type}"`);
|
|
54
|
+
}
|
|
55
|
+
if (visit && visit.exit) visit.exit(node, parent);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
//#endregion
|
|
60
|
+
export { traverse as default };
|
|
61
|
+
//# sourceMappingURL=traverse.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"traverse.js","names":[],"sources":["../../src/traverse.ts"],"sourcesContent":["import {\n NodeType,\n CST,\n TreeNode,\n Document,\n Table,\n TableKey,\n TableArray,\n TableArrayKey,\n KeyValue,\n Key,\n String,\n Integer,\n Float,\n Boolean,\n DateTime,\n Comment,\n InlineArray,\n InlineTable,\n InlineItem\n} from './cst';\nimport { isIterable } from './utils';\n\nexport type Visit<TNode = TreeNode> = (node: TNode, parent: TNode | null) => void;\nexport type EnterExit<TNode = TreeNode> = { enter?: Visit<TNode>; exit?: Visit<TNode> };\n\nexport type Visitor = {\n Document?: Visit<Document> | EnterExit<Document>;\n Table?: Visit<Table> | EnterExit<Table>;\n TableKey?: Visit<TableKey> | EnterExit<TableKey>;\n TableArray?: Visit<TableArray> | EnterExit<TableArray>;\n TableArrayKey?: Visit<TableArrayKey> | EnterExit<TableArrayKey>;\n KeyValue?: Visit<KeyValue> | EnterExit<KeyValue>;\n Key?: Visit<Key> | EnterExit<Key>;\n String?: Visit<String> | EnterExit<String>;\n Integer?: Visit<Integer> | EnterExit<Integer>;\n Float?: Visit<Float> | EnterExit<Float>;\n Boolean?: Visit<Boolean> | EnterExit<Boolean>;\n DateTime?: Visit<DateTime> | EnterExit<DateTime>;\n InlineArray?: Visit<InlineArray> | EnterExit<InlineArray>;\n InlineItem?: Visit<InlineItem> | EnterExit<InlineItem>;\n InlineTable?: Visit<InlineTable> | EnterExit<InlineTable>;\n Comment?: Visit<Comment> | EnterExit<Comment>;\n};\n\n////////////////////////////////////////////////////////////////////////////////\n// The traverse function is used to walk the CST and call the visitor functions\n////////////////////////////////////////////////////////////////////////////////\nexport default function traverse(cst: CST | TreeNode, visitor: Visitor) {\n if (isIterable(cst)) {\n traverseArray(cst, null);\n } else {\n traverseNode(cst, null);\n }\n\n function traverseArray(array: Iterable<TreeNode>, parent: TreeNode | null) {\n for (const node of array) {\n traverseNode(node, parent);\n }\n }\n\n function traverseNode(node: TreeNode, parent: TreeNode | null) {\n const visit = visitor[node.type];\n\n if (visit && typeof visit === 'function') {\n (visit as Visit)(node, parent);\n }\n\n if (visit && (visit as EnterExit).enter) {\n (visit as EnterExit).enter!(node, parent);\n }\n\n switch (node.type) {\n case NodeType.Document:\n traverseArray((node as Document).items, node);\n break;\n\n case NodeType.Table:\n traverseNode((node as Table).key, node);\n traverseArray((node as Table).items, node);\n break;\n case NodeType.TableKey:\n traverseNode((node as TableKey).item, node);\n break;\n\n case NodeType.TableArray:\n traverseNode((node as TableArray).key, node);\n traverseArray((node as TableArray).items, node);\n break;\n case NodeType.TableArrayKey:\n traverseNode((node as TableArrayKey).item, node);\n break;\n\n case NodeType.KeyValue:\n traverseNode((node as KeyValue).key, node);\n traverseNode((node as KeyValue).value, node);\n break;\n\n case NodeType.InlineArray:\n traverseArray((node as InlineArray).items, node);\n break;\n case NodeType.InlineItem:\n traverseNode((node as InlineItem).item, node);\n break;\n\n case NodeType.InlineTable:\n traverseArray((node as InlineTable).items, node);\n break;\n\n case NodeType.Key:\n case NodeType.String:\n case NodeType.Integer:\n case NodeType.Float:\n case NodeType.Boolean:\n case NodeType.DateTime:\n case NodeType.Comment:\n break;\n\n default:\n throw new Error(`Unrecognized node type \"${node.type}\"`);\n }\n\n if (visit && (visit as EnterExit).exit) {\n (visit as EnterExit).exit!(node, parent);\n }\n }\n}\n"],"mappings":";;;;AAgDA,SAAwB,SAAS,KAAqB,SAAkB;CACtE,IAAI,WAAW,GAAG,GAChB,cAAc,KAAK,IAAI;MAEvB,aAAa,KAAK,IAAI;CAGxB,SAAS,cAAc,OAA2B,QAAyB;EACzE,KAAK,MAAM,QAAQ,OACjB,aAAa,MAAM,MAAM;CAE7B;CAEA,SAAS,aAAa,MAAgB,QAAyB;EAC7D,MAAM,QAAQ,QAAQ,KAAK;EAE3B,IAAI,SAAS,OAAO,UAAU,YAC5B,AAAC,MAAgB,MAAM,MAAM;EAG/B,IAAI,SAAU,MAAoB,OAChC,AAAC,MAAoB,MAAO,MAAM,MAAM;EAG1C,QAAQ,KAAK,MAAb;GACE;IACE,cAAe,KAAkB,OAAO,IAAI;IAC5C;GAEF;IACE,aAAc,KAAe,KAAK,IAAI;IACtC,cAAe,KAAe,OAAO,IAAI;IACzC;GACF;IACE,aAAc,KAAkB,MAAM,IAAI;IAC1C;GAEF;IACE,aAAc,KAAoB,KAAK,IAAI;IAC3C,cAAe,KAAoB,OAAO,IAAI;IAC9C;GACF;IACE,aAAc,KAAuB,MAAM,IAAI;IAC/C;GAEF;IACE,aAAc,KAAkB,KAAK,IAAI;IACzC,aAAc,KAAkB,OAAO,IAAI;IAC3C;GAEF;IACE,cAAe,KAAqB,OAAO,IAAI;IAC/C;GACF;IACE,aAAc,KAAoB,MAAM,IAAI;IAC5C;GAEF;IACE,cAAe,KAAqB,OAAO,IAAI;IAC/C;GAEF;GACA;GACA;GACA;GACA;GACA;GACA,gBACE;GAEF,SACE,MAAM,IAAI,MAAM,2BAA2B,KAAK,KAAK,EAAE;EAC3D;EAEA,IAAI,SAAU,MAAoB,MAChC,AAAC,MAAoB,KAAM,MAAM,MAAM;CAE3C;AACF"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
//! @decimalturn/toml-patch v3.1.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
|
|
2
|
+
//#region src/truncate.ts
|
|
3
|
+
/**
|
|
4
|
+
* Compares two positions to determine their ordering.
|
|
5
|
+
* @param pos1 - First position
|
|
6
|
+
* @param pos2 - Second position
|
|
7
|
+
* @returns Negative if pos1 < pos2, 0 if equal, positive if pos1 > pos2
|
|
8
|
+
*/
|
|
9
|
+
function comparePositions(pos1, pos2) {
|
|
10
|
+
if (pos1.line !== pos2.line) return pos1.line - pos2.line;
|
|
11
|
+
return pos1.column - pos2.column;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Truncates a CST based on a position (line, column) in the source string.
|
|
15
|
+
*
|
|
16
|
+
* This function filters the CST to include only the nodes that end before
|
|
17
|
+
* the specified position. This ensures that blocks containing changes are
|
|
18
|
+
* excluded and can be reparsed. This is useful for incremental parsing scenarios
|
|
19
|
+
* where you want to keep only the unchanged portion of the CST.
|
|
20
|
+
*
|
|
21
|
+
* Special handling: If the truncation point falls within a Table or TableArray
|
|
22
|
+
* (e.g., in a comment inside the table), the entire table is excluded to ensure
|
|
23
|
+
* proper reparsing.
|
|
24
|
+
*
|
|
25
|
+
* @param cst - The CST to truncate
|
|
26
|
+
* @param line - The line number (1-indexed) at which to truncate
|
|
27
|
+
* @param column - The column number (0-indexed) at which to truncate
|
|
28
|
+
* @returns An object containing the truncated CST and the end position of the last included node
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```typescript
|
|
32
|
+
* const cst = parseTOML(tomlString);
|
|
33
|
+
* // Get CST up to line 5, column 10 (only nodes that end before this position)
|
|
34
|
+
* const { truncatedCst, lastEndPosition } = truncateCst(cst, 5, 10);
|
|
35
|
+
* for (const node of truncatedCst) {
|
|
36
|
+
* // process node
|
|
37
|
+
* }
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
function truncateCst(cst, line, column) {
|
|
41
|
+
const limit = {
|
|
42
|
+
line,
|
|
43
|
+
column
|
|
44
|
+
};
|
|
45
|
+
const nodes = [];
|
|
46
|
+
let lastEndPosition = null;
|
|
47
|
+
for (const node of cst) {
|
|
48
|
+
const nodeEndsBeforeLimit = comparePositions(node.loc.end, limit) < 0;
|
|
49
|
+
const nodeStartsBeforeLimit = comparePositions(node.loc.start, limit) < 0;
|
|
50
|
+
if (nodeEndsBeforeLimit) {
|
|
51
|
+
nodes.push(node);
|
|
52
|
+
lastEndPosition = node.loc.end;
|
|
53
|
+
} else if (nodeStartsBeforeLimit && !nodeEndsBeforeLimit) break;
|
|
54
|
+
else break;
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
truncatedCst: nodes,
|
|
58
|
+
lastEndPosition
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
//#endregion
|
|
63
|
+
export { truncateCst };
|
|
64
|
+
//# sourceMappingURL=truncate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"truncate.js","names":[],"sources":["../../src/truncate.ts"],"sourcesContent":["import { CST, Block } from './cst';\nimport { Position } from './location';\n\n/**\n * Compares two positions to determine their ordering.\n * @param pos1 - First position\n * @param pos2 - Second position\n * @returns Negative if pos1 < pos2, 0 if equal, positive if pos1 > pos2\n */\nfunction comparePositions(pos1: Position, pos2: Position): number {\n if (pos1.line !== pos2.line) {\n return pos1.line - pos2.line;\n }\n return pos1.column - pos2.column;\n}\n\n/**\n * Checks if a block node should be included based on its location.\n * A block is included if its end position is before the limit position.\n * This ensures that only complete blocks that don't contain the change are kept.\n * @param node - The block node to check\n * @param limit - The position limit\n * @returns true if the block should be included\n */\nfunction shouldIncludeBlock(node: Block, limit: Position): boolean {\n return comparePositions(node.loc.end, limit) < 0;\n}\n\n/**\n * Truncates a CST based on a position (line, column) in the source string.\n * \n * This function filters the CST to include only the nodes that end before\n * the specified position. This ensures that blocks containing changes are\n * excluded and can be reparsed. This is useful for incremental parsing scenarios\n * where you want to keep only the unchanged portion of the CST.\n * \n * Special handling: If the truncation point falls within a Table or TableArray\n * (e.g., in a comment inside the table), the entire table is excluded to ensure\n * proper reparsing.\n * \n * @param cst - The CST to truncate\n * @param line - The line number (1-indexed) at which to truncate\n * @param column - The column number (0-indexed) at which to truncate\n * @returns An object containing the truncated CST and the end position of the last included node\n * \n * @example\n * ```typescript\n * const cst = parseTOML(tomlString);\n * // Get CST up to line 5, column 10 (only nodes that end before this position)\n * const { truncatedCst, lastEndPosition } = truncateCst(cst, 5, 10);\n * for (const node of truncatedCst) {\n * // process node\n * }\n * ```\n */\nexport function truncateCst(cst: CST, line: number, column: number): {\n truncatedCst: CST;\n lastEndPosition: Position | null \n} {\n const limit: Position = { line, column };\n const nodes: Block[] = [];\n let lastEndPosition: Position | null = null;\n \n for (const node of cst) {\n const nodeEndsBeforeLimit = comparePositions(node.loc.end, limit) < 0;\n const nodeStartsBeforeLimit = comparePositions(node.loc.start, limit) < 0;\n \n if (nodeEndsBeforeLimit) {\n // Node completely ends before the limit - include it\n nodes.push(node);\n lastEndPosition = node.loc.end;\n } else if (nodeStartsBeforeLimit && !nodeEndsBeforeLimit) {\n // Node starts before the limit but ends at or after it\n // This means the truncation point is within this node\n // For Table/TableArray nodes, don't include them if the change is inside\n // This ensures the entire table gets reparsed\n break;\n } else {\n // Node starts at or after the limit - stop\n break;\n }\n }\n \n return {\n truncatedCst: nodes,\n lastEndPosition\n };\n}\n\n/**\n * Finds the last block node in a CST that ends before the specified position.\n * \n * @param cst - The CST to search\n * @param line - The line number (1-indexed)\n * @param column - The column number (0-indexed)\n * @returns The last block node that ends before the position, or undefined if no such node exists\n * \n * @example\n * ```typescript\n * const cst = parseTOML(tomlString);\n * const lastNode = findLastNodeBeforePosition(cst, 5, 10);\n * if (lastNode) {\n * console.log('Last node type:', lastNode.type);\n * }\n * ```\n */\nexport function findLastNodeBeforePosition(cst: CST, line: number, column: number): Block | undefined {\n const limit: Position = { line, column };\n let lastNode: Block | undefined = undefined;\n \n for (const node of cst) {\n if (shouldIncludeBlock(node, limit)) {\n lastNode = node;\n } else {\n // Once we encounter a node that starts after the limit, we can stop\n break;\n }\n }\n \n return lastNode;\n}\n"],"mappings":";;;;;;;;AASA,SAAS,iBAAiB,MAAgB,MAAwB;CAChE,IAAI,KAAK,SAAS,KAAK,MACrB,OAAO,KAAK,OAAO,KAAK;CAE1B,OAAO,KAAK,SAAS,KAAK;AAC5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,YAAY,KAAU,MAAc,QAGlD;CACA,MAAM,QAAkB;EAAE;EAAM;CAAO;CACvC,MAAM,QAAiB,CAAC;CACxB,IAAI,kBAAmC;CAEvC,KAAK,MAAM,QAAQ,KAAK;EACtB,MAAM,sBAAsB,iBAAiB,KAAK,IAAI,KAAK,KAAK,IAAI;EACpE,MAAM,wBAAwB,iBAAiB,KAAK,IAAI,OAAO,KAAK,IAAI;EAExE,IAAI,qBAAqB;GAEvB,MAAM,KAAK,IAAI;GACf,kBAAkB,KAAK,IAAI;EAC7B,OAAO,IAAI,yBAAyB,CAAC,qBAKnC;OAGA;CAEJ;CAEA,OAAO;EACL,cAAc;EACd;CACF;AACF"}
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
//! @decimalturn/toml-patch v3.1.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
|
|
2
|
+
import { hasItem, isDocument, isInlineItem, isKeyValue, isTable, isTableArray } from "./cst.js";
|
|
3
|
+
import { recalcContainerEnd, shiftNode } from "./writer.js";
|
|
4
|
+
import { tryFindByPath } from "./find-by-path.js";
|
|
5
|
+
import { normalizeSectionComments, resolveSlots } from "./comment-ownership.js";
|
|
6
|
+
|
|
7
|
+
//#region src/update-order.ts
|
|
8
|
+
function buildUnits(slots) {
|
|
9
|
+
const units = [];
|
|
10
|
+
for (const slot of slots) {
|
|
11
|
+
if (slot.kind === "pinned") {
|
|
12
|
+
units.push({
|
|
13
|
+
kind: "pinned",
|
|
14
|
+
isSection: false,
|
|
15
|
+
movable: false,
|
|
16
|
+
slots: [slot],
|
|
17
|
+
startLine: slot.startLine,
|
|
18
|
+
endLine: slot.endLine,
|
|
19
|
+
items: slot.items
|
|
20
|
+
});
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
const isSection = isTable(slot.member) || isTableArray(slot.member);
|
|
24
|
+
const previous = units[units.length - 1];
|
|
25
|
+
if (previous && previous.kind === "member" && slot.key !== void 0 && previous.key === slot.key) {
|
|
26
|
+
previous.slots.push(slot);
|
|
27
|
+
previous.endLine = slot.endLine;
|
|
28
|
+
previous.items = previous.items.concat(slot.items);
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
units.push({
|
|
32
|
+
kind: "member",
|
|
33
|
+
key: slot.key,
|
|
34
|
+
isSection,
|
|
35
|
+
movable: slot.key !== void 0,
|
|
36
|
+
slots: [slot],
|
|
37
|
+
startLine: slot.startLine,
|
|
38
|
+
endLine: slot.endLine,
|
|
39
|
+
items: [...slot.items]
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
const countByKey = /* @__PURE__ */ new Map();
|
|
43
|
+
for (const unit of units) {
|
|
44
|
+
if (unit.kind !== "member" || unit.key === void 0) continue;
|
|
45
|
+
countByKey.set(unit.key, (countByKey.get(unit.key) ?? 0) + 1);
|
|
46
|
+
}
|
|
47
|
+
for (const unit of units) if (unit.kind === "member" && unit.key !== void 0 && countByKey.get(unit.key) > 1) unit.movable = false;
|
|
48
|
+
return units;
|
|
49
|
+
}
|
|
50
|
+
/** Replays `moves` against `currentOrder` using the same simulate-and-splice approach
|
|
51
|
+
* compareObjects used to generate them, reconstructing the full requested key order. */
|
|
52
|
+
function computeTargetOrder(currentOrder, moves) {
|
|
53
|
+
const sim = [...currentOrder];
|
|
54
|
+
for (const move of moves) {
|
|
55
|
+
if (move.key === void 0) continue;
|
|
56
|
+
const from = sim.indexOf(move.key);
|
|
57
|
+
if (from === -1) continue;
|
|
58
|
+
const to = Math.max(0, Math.min(move.to, sim.length - 1));
|
|
59
|
+
if (from === to) continue;
|
|
60
|
+
sim.splice(from, 1);
|
|
61
|
+
sim.splice(to, 0, move.key);
|
|
62
|
+
}
|
|
63
|
+
return sim;
|
|
64
|
+
}
|
|
65
|
+
/** Full dotted path to the entry a Move targets (its container path plus its own key), for
|
|
66
|
+
* warning messages -- clearer than the bare key alone once anything is nested more than one
|
|
67
|
+
* level deep (e.g. "t.hello.moon" rather than just "moon"). */
|
|
68
|
+
function describeMovePath(move) {
|
|
69
|
+
return [...move.path, move.key].join(".");
|
|
70
|
+
}
|
|
71
|
+
function resolveImplicitDottedContainer(document, path, moveKey, commentEligibleNodes) {
|
|
72
|
+
if (path.some((segment) => typeof segment !== "string")) return void 0;
|
|
73
|
+
const target = [...path, moveKey];
|
|
74
|
+
const candidates = [{
|
|
75
|
+
container: document,
|
|
76
|
+
prefix: []
|
|
77
|
+
}];
|
|
78
|
+
for (const item of document.items) if (isTable(item) || isTableArray(item)) candidates.push({
|
|
79
|
+
container: item,
|
|
80
|
+
prefix: item.key.item.value
|
|
81
|
+
});
|
|
82
|
+
for (const candidate of candidates) for (const item of candidate.container.items) {
|
|
83
|
+
if (!isKeyValue(item) || item.key.value.length < 2) continue;
|
|
84
|
+
if (commentEligibleNodes.has(item)) continue;
|
|
85
|
+
const fullKey = [...candidate.prefix, ...item.key.value];
|
|
86
|
+
if (fullKey.length !== target.length) continue;
|
|
87
|
+
if (!fullKey.every((segment, index) => segment === target[index])) continue;
|
|
88
|
+
return {
|
|
89
|
+
container: candidate.container,
|
|
90
|
+
dottedPrefix: item.key.value.slice(0, -1)
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
function resolveContainer(document, path, moveKey, commentEligibleNodes) {
|
|
95
|
+
if (path.length === 0) return { container: document };
|
|
96
|
+
let node;
|
|
97
|
+
try {
|
|
98
|
+
node = tryFindByPath(document, path);
|
|
99
|
+
} catch {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (!node) return void 0;
|
|
103
|
+
if (isKeyValue(node)) node = node.value;
|
|
104
|
+
if (node && hasItem(node)) node = node.item;
|
|
105
|
+
if (node && (isDocument(node) || isTable(node) || isTableArray(node))) return { container: node };
|
|
106
|
+
if (moveKey === void 0) return void 0;
|
|
107
|
+
const implicit = resolveImplicitDottedContainer(document, path, moveKey, commentEligibleNodes);
|
|
108
|
+
if (implicit) return implicit;
|
|
109
|
+
let numericIndex = -1;
|
|
110
|
+
for (let i = path.length - 1; i >= 0; i--) if (typeof path[i] === "number") {
|
|
111
|
+
numericIndex = i;
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
if (numericIndex < 0) return void 0;
|
|
115
|
+
const dottedPrefix = path.slice(numericIndex + 1);
|
|
116
|
+
if (dottedPrefix.length === 0 || dottedPrefix.some((segment) => typeof segment !== "string")) return;
|
|
117
|
+
const entry = tryFindByPath(document, path.slice(0, numericIndex + 1));
|
|
118
|
+
if (!entry || !isTableArray(entry)) return void 0;
|
|
119
|
+
const targetKey = [...dottedPrefix, moveKey];
|
|
120
|
+
return entry.items.some((item) => isKeyValue(item) && item.key.value.length === targetKey.length && item.key.value.every((segment, index) => segment === targetKey[index])) ? {
|
|
121
|
+
container: entry,
|
|
122
|
+
dottedPrefix
|
|
123
|
+
} : void 0;
|
|
124
|
+
}
|
|
125
|
+
function isNewMoveTarget(document, move, commentEligibleNodes) {
|
|
126
|
+
if (move.key === void 0) return false;
|
|
127
|
+
let target;
|
|
128
|
+
try {
|
|
129
|
+
target = tryFindByPath(document, move.path.concat(move.key));
|
|
130
|
+
} catch {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
return target !== void 0 && isInlineItem(target) && !commentEligibleNodes.has(target);
|
|
134
|
+
}
|
|
135
|
+
function applyContainerMoves(container, moves, commentEligibleNodes, warnings, dottedPrefix) {
|
|
136
|
+
const units = buildUnits(resolveSlots(container, (node) => commentEligibleNodes.has(node), dottedPrefix ? (member) => {
|
|
137
|
+
if (!isKeyValue(member)) return void 0;
|
|
138
|
+
const key = member.key.value;
|
|
139
|
+
if (key.length !== dottedPrefix.length + 1) return void 0;
|
|
140
|
+
for (let i = 0; i < dottedPrefix.length; i++) if (key[i] !== dottedPrefix[i]) return void 0;
|
|
141
|
+
return key[dottedPrefix.length];
|
|
142
|
+
} : void 0));
|
|
143
|
+
const movableUnitsByKey = /* @__PURE__ */ new Map();
|
|
144
|
+
for (const unit of units) if (unit.kind === "member" && unit.movable && unit.key !== void 0) movableUnitsByKey.set(unit.key, unit);
|
|
145
|
+
const memberKeys = new Set(units.filter((u) => u.kind === "member" && u.key !== void 0).map((u) => u.key));
|
|
146
|
+
for (const move of moves) if (move.key !== void 0 && memberKeys.has(move.key) && !movableUnitsByKey.has(move.key)) warnings.push(`"${describeMovePath(move)}" -- its entries are not contiguous in the document (e.g. the TOML spec's own "valid but discouraged" out-of-order table pattern), so reordering was skipped for it`);
|
|
147
|
+
if (movableUnitsByKey.size === 0) return;
|
|
148
|
+
const currentOrder = dottedPrefix ? units.filter((u) => u.kind === "member" && u.movable).map((u) => u.key) : units.filter((u) => u.kind === "member").map((u, index) => u.movable ? u.key : `\u0000anchor:${index}`);
|
|
149
|
+
const relevantMoves = moves.filter((m) => m.key !== void 0 && movableUnitsByKey.has(m.key));
|
|
150
|
+
if (relevantMoves.length === 0) return;
|
|
151
|
+
const targetOrder = computeTargetOrder(currentOrder, relevantMoves).filter((k) => movableUnitsByKey.has(k));
|
|
152
|
+
const rootKvTargetOrder = targetOrder.filter((k) => !movableUnitsByKey.get(k).isSection);
|
|
153
|
+
const sectionTargetOrder = targetOrder.filter((k) => movableUnitsByKey.get(k).isSection);
|
|
154
|
+
let sawSection = false;
|
|
155
|
+
for (const key of targetOrder) if (movableUnitsByKey.get(key).isSection) sawSection = true;
|
|
156
|
+
else if (sawSection) {
|
|
157
|
+
warnings.push("the requested order asked for a root key-value to be positioned after a section header, which TOML cannot represent -- each group (root key-values, section blocks) was reordered to match its own requested relative order instead");
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
let rootKvCursor = 0;
|
|
161
|
+
let sectionCursor = 0;
|
|
162
|
+
const finalUnits = units.map((unit) => {
|
|
163
|
+
if (unit.kind !== "member" || !unit.movable) return unit;
|
|
164
|
+
const key = unit.isSection ? sectionTargetOrder[sectionCursor++] : rootKvTargetOrder[rootKvCursor++];
|
|
165
|
+
return movableUnitsByKey.get(key);
|
|
166
|
+
});
|
|
167
|
+
if (finalUnits.every((u, i) => u === units[i])) return;
|
|
168
|
+
const containerFirstLine = isDocument(container) ? 1 : container.key.loc.end.line;
|
|
169
|
+
const gapBefore = units.map((unit, i) => {
|
|
170
|
+
if (i === 0) return unit.startLine - containerFirstLine;
|
|
171
|
+
return unit.startLine - units[i - 1].endLine - 1;
|
|
172
|
+
});
|
|
173
|
+
let cursorEnd = containerFirstLine;
|
|
174
|
+
for (let i = 0; i < finalUnits.length; i++) {
|
|
175
|
+
const unit = finalUnits[i];
|
|
176
|
+
const gap = gapBefore[i];
|
|
177
|
+
const delta = (i === 0 ? cursorEnd : cursorEnd + 1) + gap - unit.startLine;
|
|
178
|
+
if (delta !== 0) for (const item of unit.items) shiftNode(item, {
|
|
179
|
+
lines: delta,
|
|
180
|
+
columns: 0
|
|
181
|
+
});
|
|
182
|
+
cursorEnd = unit.endLine + delta;
|
|
183
|
+
}
|
|
184
|
+
const newItems = finalUnits.flatMap((u) => u.items);
|
|
185
|
+
const items = container.items;
|
|
186
|
+
items.splice(0, items.length, ...newItems);
|
|
187
|
+
recalcContainerEnd(container);
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Reorders `document`'s root key-values, [table]/[[array]] section blocks, and table-body
|
|
191
|
+
* rows to match `moves` (object-key Moves collected from the isMove branch in patch.ts),
|
|
192
|
+
* carrying each entry's owned comments with it. See docs/PLAN-Update-Order.md.
|
|
193
|
+
*
|
|
194
|
+
* Must run after every other structural change in this patch has already been applied to
|
|
195
|
+
* `document` (Add/Remove/Rename/array-Move/structural-edit) — it does no insertion or
|
|
196
|
+
* deletion of its own, only permutes and relays out what's already there.
|
|
197
|
+
*/
|
|
198
|
+
function applyKeyOrderMoves(document, moves, commentEligibleNodes) {
|
|
199
|
+
if (moves.length === 0) return;
|
|
200
|
+
normalizeSectionComments(document);
|
|
201
|
+
const warnings = [];
|
|
202
|
+
const movesByContainer = /* @__PURE__ */ new Map();
|
|
203
|
+
for (const move of moves) {
|
|
204
|
+
var _resolved$dottedPrefi;
|
|
205
|
+
if (move.key === void 0) continue;
|
|
206
|
+
const resolved = resolveContainer(document, move.path, move.key, commentEligibleNodes);
|
|
207
|
+
if (!resolved) {
|
|
208
|
+
if (isNewMoveTarget(document, move, commentEligibleNodes)) continue;
|
|
209
|
+
warnings.push(`"${describeMovePath(move)}" -- unsupported location for reordering (e.g. a dotted-key implicit table, or an interior of an inline table/array-of-tables entry)`);
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
const scopeKey = ((_resolved$dottedPrefi = resolved.dottedPrefix) === null || _resolved$dottedPrefi === void 0 ? void 0 : _resolved$dottedPrefi.join("\0")) ?? "";
|
|
213
|
+
let scopedMoves = movesByContainer.get(resolved.container);
|
|
214
|
+
if (!scopedMoves) {
|
|
215
|
+
scopedMoves = /* @__PURE__ */ new Map();
|
|
216
|
+
movesByContainer.set(resolved.container, scopedMoves);
|
|
217
|
+
}
|
|
218
|
+
const bucket = scopedMoves.get(scopeKey);
|
|
219
|
+
if (bucket) bucket.moves.push(move);
|
|
220
|
+
else scopedMoves.set(scopeKey, {
|
|
221
|
+
...resolved,
|
|
222
|
+
moves: [move]
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
for (const scopedMoves of movesByContainer.values()) for (const target of scopedMoves.values()) applyContainerMoves(target.container, target.moves, commentEligibleNodes, warnings, target.dottedPrefix);
|
|
226
|
+
if (warnings.length > 0) {
|
|
227
|
+
const unique = [...new Set(warnings)];
|
|
228
|
+
console.warn(`toml-patch: updateOrder could not honor the requested position for ${unique.length === 1 ? "1 entry" : `${unique.length} entries`}, left unchanged:\n` + unique.map((w) => ` - ${w}`).join("\n"));
|
|
229
|
+
}
|
|
230
|
+
recalcContainerEnd(document);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
//#endregion
|
|
234
|
+
export { applyKeyOrderMoves };
|
|
235
|
+
//# sourceMappingURL=update-order.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"update-order.js","names":[],"sources":["../../src/update-order.ts"],"sourcesContent":["import {\n Document,\n Table,\n TableArray,\n TreeNode,\n isDocument,\n isTable,\n isTableArray,\n isKeyValue,\n isInlineItem,\n hasItem\n} from './cst';\nimport { Move } from './diff';\nimport { Path, tryFindByPath } from './find-by-path';\nimport { resolveSlots, normalizeSectionComments, Slot } from './comment-ownership';\nimport { shiftNode, recalcContainerEnd } from './writer';\n\n/**\n * A resolved, orderable unit within a container: either one member slot, or — when the same\n * key resolves to more than one CONSECUTIVE member slot (an [[array-of-tables]]'s entries, or\n * a [table] immediately followed by its own [table.sub]) — all of them coalesced into one\n * group that moves as a rigid block, preserving their own relative order. Pinned slots (no\n * key) are never coalesced and never reordered; see `movable` below.\n */\ninterface Unit {\n kind: 'member' | 'pinned';\n key?: string;\n isSection: boolean;\n /** False for pinned units, and for member units whose key maps to more than one\n * NON-contiguous group (the dotted-key / non-contiguous-document-group hazard) — both\n * are treated as fixed anchors: never reordered, always left exactly where they are. */\n movable: boolean;\n slots: Slot[];\n startLine: number;\n endLine: number;\n items: TreeNode[];\n}\n\nfunction buildUnits(slots: Slot[]): Unit[] {\n const units: Unit[] = [];\n\n for (const slot of slots) {\n if (slot.kind === 'pinned') {\n units.push({\n kind: 'pinned',\n isSection: false,\n movable: false,\n slots: [slot],\n startLine: slot.startLine,\n endLine: slot.endLine,\n items: slot.items\n });\n continue;\n }\n\n const isSection = isTable(slot.member!) || isTableArray(slot.member!);\n const previous = units[units.length - 1];\n if (previous && previous.kind === 'member' && slot.key !== undefined && previous.key === slot.key) {\n // Contiguous run sharing the same first key segment (AOT entries, or [a] then\n // [a.sub]) — coalesce into one unit that will move together.\n previous.slots.push(slot);\n previous.endLine = slot.endLine;\n previous.items = previous.items.concat(slot.items);\n continue;\n }\n\n units.push({\n kind: 'member',\n key: slot.key,\n isSection,\n movable: slot.key !== undefined, // corrected below once every unit for this container is known\n slots: [slot],\n startLine: slot.startLine,\n endLine: slot.endLine,\n items: [...slot.items]\n });\n }\n\n // A key that resolves to more than one, NON-contiguous unit (e.g. `hello.world` / `b` /\n // `hello.moon`) can't be safely reordered: resolveSlots has no way to represent \"hello\" as\n // a single relocatable thing when another key sits between its occurrences. Bail on moving\n // any of them — \"did nothing\" is the safe failure mode (docs/PLAN-Update-Order.md, Scope).\n const countByKey = new Map<string, number>();\n for (const unit of units) {\n if (unit.kind !== 'member' || unit.key === undefined) continue;\n countByKey.set(unit.key, (countByKey.get(unit.key) ?? 0) + 1);\n }\n for (const unit of units) {\n if (unit.kind === 'member' && unit.key !== undefined && countByKey.get(unit.key)! > 1) {\n unit.movable = false;\n }\n }\n\n return units;\n}\n\n/** Replays `moves` against `currentOrder` using the same simulate-and-splice approach\n * compareObjects used to generate them, reconstructing the full requested key order. */\nfunction computeTargetOrder(currentOrder: string[], moves: Move[]): string[] {\n const sim = [...currentOrder];\n for (const move of moves) {\n if (move.key === undefined) continue;\n const from = sim.indexOf(move.key);\n if (from === -1) continue; // not one of this container's movable keys\n const to = Math.max(0, Math.min(move.to, sim.length - 1));\n if (from === to) continue;\n sim.splice(from, 1);\n sim.splice(to, 0, move.key);\n }\n return sim;\n}\n\n/** Full dotted path to the entry a Move targets (its container path plus its own key), for\n * warning messages -- clearer than the bare key alone once anything is nested more than one\n * level deep (e.g. \"t.hello.moon\" rather than just \"moon\"). */\nfunction describeMovePath(move: Move): string {\n return [...move.path, move.key].join('.');\n}\n\n/** Resolves a Move's `path` to the Document/Table/TableArray it targets, unwrapping a\n * KeyValue/InlineItem wrapper if `tryFindByPath` returns one. Dotted-key members inside an\n * AOT entry are returned with a scoped prefix so they can be reordered in that entry. */\ninterface ResolvedContainer {\n container: Document | Table | TableArray;\n dottedPrefix?: string[];\n}\n\nfunction resolveImplicitDottedContainer(\n document: Document,\n path: Path,\n moveKey: string,\n commentEligibleNodes: WeakSet<TreeNode>\n): ResolvedContainer | undefined {\n if (path.some(segment => typeof segment !== 'string')) return undefined;\n\n const target = [...path, moveKey];\n const candidates: { container: Document | Table | TableArray; prefix: string[] }[] = [\n { container: document, prefix: [] }\n ];\n\n for (const item of document.items as TreeNode[]) {\n if (isTable(item) || isTableArray(item)) {\n candidates.push({ container: item, prefix: item.key.item.value });\n }\n }\n\n for (const candidate of candidates) {\n for (const item of candidate.container.items as TreeNode[]) {\n if (!isKeyValue(item) || item.key.value.length < 2) continue;\n if (commentEligibleNodes.has(item)) continue;\n const fullKey = [...candidate.prefix, ...item.key.value];\n if (fullKey.length !== target.length) continue;\n if (!fullKey.every((segment, index) => segment === target[index])) continue;\n return { container: candidate.container, dottedPrefix: item.key.value.slice(0, -1) };\n }\n }\n\n return undefined;\n}\n\nfunction resolveContainer(\n document: Document,\n path: Path,\n moveKey: string | undefined,\n commentEligibleNodes: WeakSet<TreeNode>\n): ResolvedContainer | undefined {\n if (path.length === 0) return { container: document };\n\n let node: TreeNode | undefined;\n try {\n node = tryFindByPath(document, path);\n } catch {\n return undefined;\n }\n if (!node) return undefined;\n\n if (isKeyValue(node)) node = node.value;\n if (node && hasItem(node)) node = node.item;\n\n if (node && (isDocument(node) || isTable(node) || isTableArray(node))) {\n return { container: node };\n }\n\n if (moveKey === undefined) return undefined;\n\n const implicit = resolveImplicitDottedContainer(document, path, moveKey, commentEligibleNodes);\n if (implicit) return implicit;\n\n // A dotted key inside an AOT entry is represented as a KeyValue directly in the\n // entry's items. Its object path contains the AOT index, so resolve the entry first\n // and use the remaining dotted segments as a scoped member prefix.\n let numericIndex = -1;\n for (let i = path.length - 1; i >= 0; i--) {\n if (typeof path[i] === 'number') {\n numericIndex = i;\n break;\n }\n }\n if (numericIndex < 0) return undefined;\n\n const dottedPrefix = path.slice(numericIndex + 1);\n if (dottedPrefix.length === 0 || dottedPrefix.some(segment => typeof segment !== 'string')) {\n return undefined;\n }\n\n const entry = tryFindByPath(document, path.slice(0, numericIndex + 1));\n if (!entry || !isTableArray(entry)) return undefined;\n\n const targetKey = [...dottedPrefix, moveKey];\n const hasTarget = (entry.items as TreeNode[]).some(item =>\n isKeyValue(item) &&\n item.key.value.length === targetKey.length &&\n item.key.value.every((segment, index) => segment === targetKey[index])\n );\n return hasTarget ? { container: entry, dottedPrefix: dottedPrefix as string[] } : undefined;\n}\n\nfunction isNewMoveTarget(\n document: Document,\n move: Move,\n commentEligibleNodes: WeakSet<TreeNode>\n): boolean {\n if (move.key === undefined) return false;\n let target: TreeNode | undefined;\n try {\n target = tryFindByPath(document, move.path.concat(move.key));\n } catch {\n return false;\n }\n return target !== undefined && isInlineItem(target) && !commentEligibleNodes.has(target);\n}\n\nfunction applyContainerMoves(\n container: Document | Table | TableArray,\n moves: Move[],\n commentEligibleNodes: WeakSet<TreeNode>,\n warnings: string[],\n dottedPrefix?: string[]\n): void {\n const memberKey = dottedPrefix\n ? (member: TreeNode): string | undefined => {\n if (!isKeyValue(member)) return undefined;\n const key = member.key.value;\n if (key.length !== dottedPrefix.length + 1) return undefined;\n for (let i = 0; i < dottedPrefix.length; i++) {\n if (key[i] !== dottedPrefix[i]) return undefined;\n }\n return key[dottedPrefix.length];\n }\n : undefined;\n const slots = resolveSlots(container, node => commentEligibleNodes.has(node), memberKey);\n const units = buildUnits(slots);\n\n const movableUnitsByKey = new Map<string, Unit>();\n for (const unit of units) {\n if (unit.kind === 'member' && unit.movable && unit.key !== undefined) {\n movableUnitsByKey.set(unit.key, unit);\n }\n }\n\n // Warn about any requested move whose key genuinely exists here as a member but was marked\n // unmovable by buildUnits (a non-contiguous group) -- the caller asked for a specific\n // position and it was silently left exactly where it was.\n const memberKeys = new Set(\n units.filter(u => u.kind === 'member' && u.key !== undefined).map(u => u.key!)\n );\n for (const move of moves) {\n if (move.key !== undefined && memberKeys.has(move.key) && !movableUnitsByKey.has(move.key)) {\n warnings.push(\n `\"${describeMovePath(move)}\" -- its entries are not contiguous in the document (e.g. the ` +\n `TOML spec's own \"valid but discouraged\" out-of-order table pattern), so reordering was ` +\n `skipped for it`\n );\n }\n }\n\n if (movableUnitsByKey.size === 0) return; // nothing this container can safely reorder\n\n // Move.from/to are indices in the object whose order was diffed. For a scoped AOT move,\n // that object contains only the dotted members under `dottedPrefix`, not every row in the\n // AOT entry. Simulating against unrelated rows would therefore interpret `move.to` in the\n // wrong index space. The final placement below still walks every unit, keeping unrelated\n // rows and pinned slots at their original positions.\n const currentOrder = dottedPrefix\n ? units\n .filter(u => u.kind === 'member' && u.movable)\n .map(u => u.key!)\n : units\n .filter(u => u.kind === 'member')\n .map((u, index) => u.movable ? u.key! : `\\u0000anchor:${index}`);\n\n const relevantMoves = moves.filter(m => m.key !== undefined && movableUnitsByKey.has(m.key));\n if (relevantMoves.length === 0) return;\n\n const targetOrder = computeTargetOrder(currentOrder, relevantMoves)\n .filter(k => movableUnitsByKey.has(k));\n\n // Validity partition (docs/PLAN-Update-Order.md, Scope): a root key-value can never appear\n // after a section header. Root-KV positions and section positions are fixed by the\n // ORIGINAL structure (that's what made them root-KVs vs sections in the first place) —\n // only WHICH key fills each position-of-its-kind is being decided here.\n const rootKvTargetOrder = targetOrder.filter(k => !movableUnitsByKey.get(k)!.isSection);\n const sectionTargetOrder = targetOrder.filter(k => movableUnitsByKey.get(k)!.isSection);\n\n // Warn when the requested order itself asked for a root key-value to land after a section\n // header -- structurally impossible, so each partition falls back to keeping its own\n // requested relative order instead of the literal interleaving that was asked for.\n let sawSection = false;\n for (const key of targetOrder) {\n if (movableUnitsByKey.get(key)!.isSection) {\n sawSection = true;\n } else if (sawSection) {\n warnings.push(\n 'the requested order asked for a root key-value to be positioned after a section header, ' +\n 'which TOML cannot represent -- each group (root key-values, section blocks) was reordered ' +\n 'to match its own requested relative order instead'\n );\n break;\n }\n }\n\n let rootKvCursor = 0;\n let sectionCursor = 0;\n const finalUnits: Unit[] = units.map(unit => {\n if (unit.kind !== 'member' || !unit.movable) return unit;\n const key = unit.isSection ? sectionTargetOrder[sectionCursor++] : rootKvTargetOrder[rootKvCursor++];\n return movableUnitsByKey.get(key)!;\n });\n\n // Nothing to do if the permutation is the identity.\n if (finalUnits.every((u, i) => u === units[i])) return;\n\n // Precompute each POSITION's own gap (number of blank lines before it), before permuting —\n // gaps belong to the position, not to whichever unit ends up there (docs/PLAN-Update-Order.md\n // §3.3 Step 6): this is what makes \"0 within a run, 1 between sections\" fall out for free\n // regardless of which specific key now occupies a given position.\n const containerFirstLine = isDocument(container) ? 1 : container.key.loc.end.line;\n const gapBefore: number[] = units.map((unit, i) => {\n if (i === 0) return unit.startLine - containerFirstLine;\n return unit.startLine - units[i - 1].endLine - 1;\n });\n\n let cursorEnd = containerFirstLine; // end line of whatever was placed immediately before\n for (let i = 0; i < finalUnits.length; i++) {\n const unit = finalUnits[i];\n const gap = gapBefore[i];\n const newStart = (i === 0 ? cursorEnd : cursorEnd + 1) + gap;\n const delta = newStart - unit.startLine;\n\n if (delta !== 0) {\n for (const item of unit.items) {\n shiftNode(item, { lines: delta, columns: 0 });\n }\n }\n\n cursorEnd = unit.endLine + delta;\n }\n\n const newItems = finalUnits.flatMap(u => u.items);\n const items = container.items as TreeNode[];\n items.splice(0, items.length, ...(newItems as any[]));\n\n recalcContainerEnd(container);\n}\n\n/**\n * Reorders `document`'s root key-values, [table]/[[array]] section blocks, and table-body\n * rows to match `moves` (object-key Moves collected from the isMove branch in patch.ts),\n * carrying each entry's owned comments with it. See docs/PLAN-Update-Order.md.\n *\n * Must run after every other structural change in this patch has already been applied to\n * `document` (Add/Remove/Rename/array-Move/structural-edit) — it does no insertion or\n * deletion of its own, only permutes and relays out what's already there.\n */\nexport function applyKeyOrderMoves(document: Document, moves: Move[], commentEligibleNodes: WeakSet<TreeNode>): void {\n if (moves.length === 0) return;\n\n // R5: a comment that visually introduces the next section but is physically parked as a\n // trailing item of the previous one must be re-parented before slots are resolved, or it\n // travels with the wrong block.\n normalizeSectionComments(document);\n\n // Collects every requested reposition this pass couldn't honor, across every container, so\n // a single consolidated console.warn can report them at the end (docs/PLAN-Update-Order.md\n // scope limitations: non-contiguous groups, the root-KV/section validity partition, and\n // shapes reordering doesn't reach yet at all -- inline-table interiors, dotted-key implicit\n // tables outside an AOT entry, and AOT-entry sub-tables. \"Did nothing\" for the affected entry is\n // the safe failure mode in every case; this only makes that silence visible to the caller.\n const warnings: string[] = [];\n\n const movesByContainer = new Map<\n Document | Table | TableArray,\n Map<string, ResolvedContainer & { moves: Move[] }>\n >();\n for (const move of moves) {\n if (move.key === undefined) continue;\n const resolved = resolveContainer(document, move.path, move.key, commentEligibleNodes);\n if (!resolved) {\n if (isNewMoveTarget(document, move, commentEligibleNodes)) continue;\n // Never throw — this is reached for shapes updateOrder doesn't support at all yet:\n // dotted-key implicit tables outside an AOT entry, inline-table interiors, and\n // AOT-entry sub-tables only reachable via document-sibling scanning.\n warnings.push(\n `\"${describeMovePath(move)}\" -- unsupported location for reordering (e.g. a dotted-key ` +\n `implicit table, or an interior of an inline table/array-of-tables entry)`\n );\n continue;\n }\n const scopeKey = resolved.dottedPrefix?.join('\\u0000') ?? '';\n let scopedMoves = movesByContainer.get(resolved.container);\n if (!scopedMoves) {\n scopedMoves = new Map();\n movesByContainer.set(resolved.container, scopedMoves);\n }\n const bucket = scopedMoves.get(scopeKey);\n if (bucket) bucket.moves.push(move);\n else scopedMoves.set(scopeKey, { ...resolved, moves: [move] });\n }\n\n for (const scopedMoves of movesByContainer.values()) {\n for (const target of scopedMoves.values()) {\n applyContainerMoves(target.container, target.moves, commentEligibleNodes, warnings, target.dottedPrefix);\n }\n }\n\n if (warnings.length > 0) {\n const unique = [...new Set(warnings)];\n console.warn(\n `toml-patch: updateOrder could not honor the requested position for ` +\n `${unique.length === 1 ? '1 entry' : `${unique.length} entries`}, left unchanged:\\n` +\n unique.map(w => ` - ${w}`).join('\\n')\n );\n }\n\n recalcContainerEnd(document);\n}\n"],"mappings":";;;;;;;AAsCA,SAAS,WAAW,OAAuB;CACzC,MAAM,QAAgB,CAAC;CAEvB,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,KAAK,SAAS,UAAU;GAC1B,MAAM,KAAK;IACT,MAAM;IACN,WAAW;IACX,SAAS;IACT,OAAO,CAAC,IAAI;IACZ,WAAW,KAAK;IAChB,SAAS,KAAK;IACd,OAAO,KAAK;GACd,CAAC;GACD;EACF;EAEA,MAAM,YAAY,QAAQ,KAAK,MAAO,KAAK,aAAa,KAAK,MAAO;EACpE,MAAM,WAAW,MAAM,MAAM,SAAS;EACtC,IAAI,YAAY,SAAS,SAAS,YAAY,KAAK,QAAQ,UAAa,SAAS,QAAQ,KAAK,KAAK;GAGjG,SAAS,MAAM,KAAK,IAAI;GACxB,SAAS,UAAU,KAAK;GACxB,SAAS,QAAQ,SAAS,MAAM,OAAO,KAAK,KAAK;GACjD;EACF;EAEA,MAAM,KAAK;GACT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GACb,IAAI,gBAAgB,UAAU,MAAM,oBAAoB,GAAG;GAI3D,SAAS,KACP,IAAI,iBAAiB,IAAI,EAAE,qIAE7B;GACA;EACF;EACA,MAAM,qCAAW,SAAS,4FAAc,KAAK,IAAQ,MAAK;EAC1D,IAAI,cAAc,iBAAiB,IAAI,SAAS,SAAS;EACzD,IAAI,CAAC,aAAa;GAChB,8BAAc,IAAI,IAAI;GACtB,iBAAiB,IAAI,SAAS,WAAW,WAAW;EACtD;EACA,MAAM,SAAS,YAAY,IAAI,QAAQ;EACvC,IAAI,QAAQ,OAAO,MAAM,KAAK,IAAI;OAC7B,YAAY,IAAI,UAAU;GAAE,GAAG;GAAU,OAAO,CAAC,IAAI;EAAE,CAAC;CAC/D;CAEA,KAAK,MAAM,eAAe,iBAAiB,OAAO,GAChD,KAAK,MAAM,UAAU,YAAY,OAAO,GACtC,oBAAoB,OAAO,WAAW,OAAO,OAAO,sBAAsB,UAAU,OAAO,YAAY;CAI3G,IAAI,SAAS,SAAS,GAAG;EACvB,MAAM,SAAS,CAAC,GAAG,IAAI,IAAI,QAAQ,CAAC;EACpC,QAAQ,KACN,sEACG,OAAO,WAAW,IAAI,YAAY,GAAG,OAAO,OAAO,UAAU,uBAChE,OAAO,KAAI,MAAK,OAAO,GAAG,CAAC,CAAC,KAAK,IAAI,CACvC;CACF;CAEA,mBAAmB,QAAQ;AAC7B"}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
//! @decimalturn/toml-patch v3.1.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
|
|
2
|
+
//#region src/utils.ts
|
|
3
|
+
/**
|
|
4
|
+
* @file Utility functions for the TOML patch library.
|
|
5
|
+
* @module utils
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* General utility functions
|
|
9
|
+
*/
|
|
10
|
+
function last(values) {
|
|
11
|
+
return values[values.length - 1];
|
|
12
|
+
}
|
|
13
|
+
function blank() {
|
|
14
|
+
return Object.create(null);
|
|
15
|
+
}
|
|
16
|
+
function isString(value) {
|
|
17
|
+
return typeof value === "string";
|
|
18
|
+
}
|
|
19
|
+
function isInteger(value) {
|
|
20
|
+
return typeof value === "number" && value % 1 === 0 && isFinite(value) && !Object.is(value, -0) && value >= Number.MIN_SAFE_INTEGER && value <= Number.MAX_SAFE_INTEGER;
|
|
21
|
+
}
|
|
22
|
+
function isBigInt(value) {
|
|
23
|
+
return typeof value === "bigint";
|
|
24
|
+
}
|
|
25
|
+
function isFloat(value) {
|
|
26
|
+
return typeof value === "number" && (!isInteger(value) || !isFinite(value) || Object.is(value, -0));
|
|
27
|
+
}
|
|
28
|
+
function isBoolean(value) {
|
|
29
|
+
return typeof value === "boolean";
|
|
30
|
+
}
|
|
31
|
+
function isDate(value) {
|
|
32
|
+
return Object.prototype.toString.call(value) === "[object Date]";
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Duck-type check for Temporal API objects.
|
|
36
|
+
*
|
|
37
|
+
* Works with both the native Temporal (constructor names like
|
|
38
|
+
* "Temporal.PlainDate") and the @js-temporal/polyfill (constructor
|
|
39
|
+
* names like "PlainDate"). Avoids instanceof issues across realms.
|
|
40
|
+
*
|
|
41
|
+
* Only the four TOML-relevant types are checked:
|
|
42
|
+
* PlainDate, PlainTime, PlainDateTime, ZonedDateTime.
|
|
43
|
+
*/
|
|
44
|
+
const TEMPORAL_TYPE_NAMES = /* @__PURE__ */ new Set([
|
|
45
|
+
"Temporal.PlainDate",
|
|
46
|
+
"Temporal.PlainTime",
|
|
47
|
+
"Temporal.PlainDateTime",
|
|
48
|
+
"Temporal.ZonedDateTime",
|
|
49
|
+
"PlainDate",
|
|
50
|
+
"PlainTime",
|
|
51
|
+
"PlainDateTime",
|
|
52
|
+
"ZonedDateTime"
|
|
53
|
+
]);
|
|
54
|
+
function isTemporal(value) {
|
|
55
|
+
var _value$constructor;
|
|
56
|
+
return value != null && typeof value === "object" && TEMPORAL_TYPE_NAMES.has((_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name) && typeof value.equals === "function";
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Converts a Temporal object to its TOML-compatible string representation.
|
|
60
|
+
*
|
|
61
|
+
* For ZonedDateTime, this strips the IANA timezone annotation (e.g. [Asia/Kolkata])
|
|
62
|
+
* and normalizes +00:00 to Z, since TOML only supports offset-based timezones.
|
|
63
|
+
* For other Temporal types, this is equivalent to toString().
|
|
64
|
+
*/
|
|
65
|
+
function temporalToTomlString(value) {
|
|
66
|
+
var _value$constructor2;
|
|
67
|
+
const name = ((_value$constructor2 = value.constructor) === null || _value$constructor2 === void 0 ? void 0 : _value$constructor2.name) ?? "";
|
|
68
|
+
if (name === "Temporal.ZonedDateTime" || name === "ZonedDateTime") {
|
|
69
|
+
const full = value.toString();
|
|
70
|
+
const bracketMatch = full.match(/\[(.+)\]$/);
|
|
71
|
+
if (bracketMatch && !/^[+-]\d{2}:\d{2}$/.test(bracketMatch[1])) throw new Error(`ZonedDateTime with IANA timezone "${full}" cannot be represented in TOML. TOML only supports offset-based timezones (+05:30, Z).`);
|
|
72
|
+
return full.replace(/\[.*\]$/, "").replace(/(\+00:00)$/, "Z");
|
|
73
|
+
}
|
|
74
|
+
const raw = value.toString();
|
|
75
|
+
if (/\[.*\]/.test(raw)) throw new Error(`Temporal value contains unsupported annotation: "${raw}". TOML only supports ISO 8601 calendar.`);
|
|
76
|
+
return raw;
|
|
77
|
+
}
|
|
78
|
+
function isObject(value) {
|
|
79
|
+
return value && typeof value === "object" && !isDate(value) && !isTemporal(value) && !Array.isArray(value);
|
|
80
|
+
}
|
|
81
|
+
function isIterable(value) {
|
|
82
|
+
return value != null && typeof value[Symbol.iterator] === "function";
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* String type detection functions
|
|
86
|
+
*
|
|
87
|
+
* These functions identify the type of TOML string representation from the raw string.
|
|
88
|
+
* The library preserves the preference for escape sequences by maintaining the original
|
|
89
|
+
* string type (basic vs literal, single-line vs multiline) when possible during patching.
|
|
90
|
+
*/
|
|
91
|
+
function isBasicString(raw) {
|
|
92
|
+
return raw.startsWith("\"") && !raw.startsWith("\"\"\"");
|
|
93
|
+
}
|
|
94
|
+
function isMultilineBasicString(raw) {
|
|
95
|
+
return raw.startsWith("\"\"\"");
|
|
96
|
+
}
|
|
97
|
+
function isLiteralString(raw) {
|
|
98
|
+
return raw.startsWith("'") && !raw.startsWith("'''");
|
|
99
|
+
}
|
|
100
|
+
function isMultilineLiteralString(raw) {
|
|
101
|
+
return raw.startsWith("'''");
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Object and array utilities
|
|
105
|
+
*/
|
|
106
|
+
function has(object, key) {
|
|
107
|
+
return key in object;
|
|
108
|
+
}
|
|
109
|
+
function arraysEqual(a, b) {
|
|
110
|
+
if (a.length !== b.length) return false;
|
|
111
|
+
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
function datesEqual(a, b) {
|
|
115
|
+
if (isTemporal(a) && isTemporal(b)) return a.toString() === b.toString();
|
|
116
|
+
if (isDate(a) && isDate(b)) return a.toISOString() === b.toISOString();
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
function stableStringify(object) {
|
|
120
|
+
const output = [];
|
|
121
|
+
const active = /* @__PURE__ */ new WeakSet();
|
|
122
|
+
const pending = [{ value: object }];
|
|
123
|
+
while (pending.length > 0) {
|
|
124
|
+
const token = pending.pop();
|
|
125
|
+
if ("text" in token) {
|
|
126
|
+
output.push(token.text);
|
|
127
|
+
if ("leave" in token) active.delete(token.leave);
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
const value = token.value;
|
|
131
|
+
if (isObject(value)) {
|
|
132
|
+
if (active.has(value)) throw new TypeError("Cannot stableStringify a circular structure");
|
|
133
|
+
active.add(value);
|
|
134
|
+
const keys = Object.keys(value).sort();
|
|
135
|
+
output.push("{");
|
|
136
|
+
pending.push({
|
|
137
|
+
leave: value,
|
|
138
|
+
text: "}"
|
|
139
|
+
});
|
|
140
|
+
for (let index = keys.length - 1; index >= 0; index--) {
|
|
141
|
+
const key = keys[index];
|
|
142
|
+
if (index < keys.length - 1) pending.push({ text: "," });
|
|
143
|
+
pending.push({ value: value[key] });
|
|
144
|
+
pending.push({ text: ":" });
|
|
145
|
+
pending.push({ text: JSON.stringify(key) });
|
|
146
|
+
}
|
|
147
|
+
} else if (Array.isArray(value)) {
|
|
148
|
+
if (active.has(value)) throw new TypeError("Cannot stableStringify a circular structure");
|
|
149
|
+
active.add(value);
|
|
150
|
+
output.push("[");
|
|
151
|
+
pending.push({
|
|
152
|
+
leave: value,
|
|
153
|
+
text: "]"
|
|
154
|
+
});
|
|
155
|
+
for (let index = value.length - 1; index >= 0; index--) {
|
|
156
|
+
if (index < value.length - 1) pending.push({ text: "," });
|
|
157
|
+
pending.push({ value: value[index] });
|
|
158
|
+
}
|
|
159
|
+
} else if (isTemporal(value)) output.push(JSON.stringify(value.toString()));
|
|
160
|
+
else if (isDate(value)) output.push(JSON.stringify(value.toISOString()));
|
|
161
|
+
else if (typeof value === "bigint") output.push(value.toString() + "n");
|
|
162
|
+
else if (typeof value === "number" && !Number.isFinite(value)) {
|
|
163
|
+
const buf = new Float64Array([value]);
|
|
164
|
+
const sign = new DataView(buf.buffer).getUint32(4, true) & 2147483648 ? "-" : "+";
|
|
165
|
+
output.push(`${sign}${String(value)}`);
|
|
166
|
+
} else output.push(JSON.stringify(value));
|
|
167
|
+
}
|
|
168
|
+
return output.join("");
|
|
169
|
+
}
|
|
170
|
+
function merge(target, values) {
|
|
171
|
+
const original_length = target.length;
|
|
172
|
+
const added_length = values.length;
|
|
173
|
+
target.length = original_length + added_length;
|
|
174
|
+
for (let i = 0; i < added_length; i++) target[original_length + i] = values[i];
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* `String.prototype.isWellFormed`, when the runtime has it (Node 20+; this package supports
|
|
178
|
+
* Node 16, so it has to be optional). Returns false exactly when a string contains an unpaired
|
|
179
|
+
* surrogate — the same predicate as `findLoneSurrogate`, but far cheaper.
|
|
180
|
+
*
|
|
181
|
+
* It only yields a boolean, so locating the offending unit for the error message still needs
|
|
182
|
+
* `findLoneSurrogate` — but that only runs on the failing path.
|
|
183
|
+
*/
|
|
184
|
+
const nativeIsWellFormed = typeof String.prototype.isWellFormed === "function" ? String.prototype.isWellFormed : void 0;
|
|
185
|
+
/**
|
|
186
|
+
* Finds the first unpaired surrogate code unit in `value`, if any.
|
|
187
|
+
*
|
|
188
|
+
* JS strings are UTF-16, so an astral character is legitimately stored as a high/low surrogate
|
|
189
|
+
* *pair* — those are fine. An unpaired one is not a Unicode scalar value, so it has no valid
|
|
190
|
+
* UTF-8 encoding and cannot be represented in TOML.
|
|
191
|
+
*/
|
|
192
|
+
function findLoneSurrogate(value) {
|
|
193
|
+
for (let i = 0; i < value.length; i++) {
|
|
194
|
+
const code = value.charCodeAt(i);
|
|
195
|
+
if (code < 55296 || code > 57343) continue;
|
|
196
|
+
if (code <= 56319) {
|
|
197
|
+
const next = value.charCodeAt(i + 1);
|
|
198
|
+
if (next >= 56320 && next <= 57343) {
|
|
199
|
+
i++;
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return {
|
|
204
|
+
index: i,
|
|
205
|
+
code
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Throws if `value` contains an unpaired surrogate. `describe` names what is being encoded
|
|
211
|
+
* (e.g. `'String value'`, `'Key "a"'`) so the message points at the offending input.
|
|
212
|
+
*/
|
|
213
|
+
function assertNoLoneSurrogate(value, describe) {
|
|
214
|
+
if (nativeIsWellFormed !== void 0 && nativeIsWellFormed.call(value)) return;
|
|
215
|
+
const found = findLoneSurrogate(value);
|
|
216
|
+
if (!found) return;
|
|
217
|
+
const hex = found.code.toString(16).toUpperCase().padStart(4, "0");
|
|
218
|
+
throw new Error(`${describe} contains a lone surrogate (U+${hex}) at index ${found.index}. Unpaired surrogates are not Unicode scalar values and cannot be encoded as TOML.`);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
//#endregion
|
|
222
|
+
export { arraysEqual, assertNoLoneSurrogate, blank, datesEqual, has, isBasicString, isBigInt, isBoolean, isDate, isFloat, isInteger, isIterable, isLiteralString, isMultilineBasicString, isMultilineLiteralString, isObject, isString, isTemporal, last, merge, stableStringify, temporalToTomlString };
|
|
223
|
+
//# sourceMappingURL=utils.js.map
|