@decimalturn/toml-patch 3.1.2-dev → 3.2.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 +1 -1
- package/dist/dev/comment-ownership.js +1 -1
- package/dist/dev/cst-source.js +1 -1
- package/dist/dev/cst.js +11 -2
- package/dist/dev/cst.js.map +1 -1
- package/dist/dev/cursor.js +1 -1
- package/dist/dev/date-format.js +1 -1
- package/dist/dev/decode-utf8.js +1 -1
- package/dist/dev/diff-lite.js +123 -0
- package/dist/dev/diff-lite.js.map +1 -0
- package/dist/dev/diff.js +4 -8
- package/dist/dev/diff.js.map +1 -1
- package/dist/dev/encode-lite.js +193 -0
- package/dist/dev/encode-lite.js.map +1 -0
- package/dist/dev/escape-preference.js +33 -11
- package/dist/dev/escape-preference.js.map +1 -1
- package/dist/dev/find-by-path.js +1 -1
- package/dist/dev/formatter.js +9 -9
- package/dist/dev/formatter.js.map +1 -1
- package/dist/dev/generate.js +53 -39
- package/dist/dev/generate.js.map +1 -1
- package/dist/dev/inline-comma-space.js +1 -1
- package/dist/dev/inline-format.js +1 -1
- package/dist/dev/inline-layout.js +1 -1
- package/dist/dev/line-ending-backslash.js +1 -1
- package/dist/dev/literal-string.js +46 -0
- package/dist/dev/literal-string.js.map +1 -0
- package/dist/dev/location.js +1 -1
- package/dist/dev/parse-error.js +1 -1
- package/dist/dev/parse-js.js +49 -6
- package/dist/dev/parse-js.js.map +1 -1
- package/dist/dev/parse-string.js +1 -1
- package/dist/dev/parse-toml.js +1 -1
- package/dist/dev/patch-lite.js +4 -0
- package/dist/dev/patch-lite2.js +96 -0
- package/dist/dev/patch-lite2.js.map +1 -0
- package/dist/dev/patch.js +150 -38
- package/dist/dev/patch.js.map +1 -1
- package/dist/dev/smol-toml-date.js +61 -0
- package/dist/dev/smol-toml-date.js.map +1 -0
- package/dist/dev/to-js.js +1 -1
- package/dist/dev/to-toml.js +1 -1
- package/dist/dev/tokenizer.js +1 -1
- package/dist/dev/toml-document.js +1 -1
- package/dist/dev/toml-format.js +58 -6
- package/dist/dev/toml-format.js.map +1 -1
- package/dist/dev/toml-patch.js +1 -1
- package/dist/dev/traverse.js +1 -1
- package/dist/dev/truncate.js +1 -1
- package/dist/dev/update-order.js +1 -1
- package/dist/dev/utils.js +26 -5
- package/dist/dev/utils.js.map +1 -1
- package/dist/dev/writer.js +1 -1
- package/dist/patch-lite.d.ts +18 -0
- package/dist/toml-patch.d.ts +7 -1
- package/package.json +6 -1
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
//! @decimalturn/toml-patch v3.2.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
|
|
2
|
+
import { isFloat } from "./cst.js";
|
|
3
|
+
import { DateFormatHelper, LocalDate, LocalDateTime, LocalTime, OffsetDateTime } from "./date-format.js";
|
|
4
|
+
import { isNegativeNan } from "./utils.js";
|
|
5
|
+
import { canUseLiteralString, canUseMultilineLiteral } from "./literal-string.js";
|
|
6
|
+
import { PatchLiteError, formatPath } from "./diff-lite.js";
|
|
7
|
+
|
|
8
|
+
//#region src/encode-lite.ts
|
|
9
|
+
/**
|
|
10
|
+
* Encodes a JavaScript leaf value as valid TOML, independent of the full
|
|
11
|
+
* formatting pipeline. Only the value span is produced; the surrounding key,
|
|
12
|
+
* equals sign, whitespace and comments are never regenerated.
|
|
13
|
+
*/
|
|
14
|
+
function encodeValue(value, existingValue, path) {
|
|
15
|
+
const type = typeof value;
|
|
16
|
+
if (type === "string") return encodeString(value, existingValue === null || existingValue === void 0 ? void 0 : existingValue.raw);
|
|
17
|
+
if (type === "boolean") return value ? "true" : "false";
|
|
18
|
+
if (type === "bigint") return value.toString();
|
|
19
|
+
if (type === "number") {
|
|
20
|
+
if (!Number.isFinite(value)) return encodeNonFinite(value);
|
|
21
|
+
if (Number.isSafeInteger(value) && !Object.is(value, -0) && !isFloat(existingValue)) return encodeInteger(value, existingValue === null || existingValue === void 0 ? void 0 : existingValue.raw);
|
|
22
|
+
return encodeFloat(value, isFloat(existingValue) ? existingValue.raw : void 0);
|
|
23
|
+
}
|
|
24
|
+
if (value instanceof Date) return encodeDate(value, existingValue);
|
|
25
|
+
throw new PatchLiteError("UnsupportedValue", path, `Unsupported value type ${Object.prototype.toString.call(value)} at ${formatPath(path)}`);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Encodes a Date as TOML while keeping the source value's formatting: date vs
|
|
29
|
+
* time vs datetime kind, fractional-digit count, space separator and offset
|
|
30
|
+
* style are all taken from the existing value's raw text, exactly as the full
|
|
31
|
+
* patch() does.
|
|
32
|
+
*/
|
|
33
|
+
function encodeDate(value, existingValue) {
|
|
34
|
+
const raw = existingValue === null || existingValue === void 0 ? void 0 : existingValue.raw;
|
|
35
|
+
const native = toTomlPatchDate(value);
|
|
36
|
+
if (typeof raw !== "string") return native.toISOString();
|
|
37
|
+
return DateFormatHelper.createDateWithOriginalFormat(native, raw).toISOString();
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Converts a smol-toml `TomlDate` to the matching toml-patch class. Duck-typed
|
|
41
|
+
* (the two packages have distinct class objects) and kept local so the lite
|
|
42
|
+
* bundle does not import the vendored smol-toml date module. The `.000` suffix
|
|
43
|
+
* smol-toml always writes for a zero fraction is dropped, so it does not leak
|
|
44
|
+
* into the output and the result matches the full patch() byte for byte.
|
|
45
|
+
*/
|
|
46
|
+
function toTomlPatchDate(value) {
|
|
47
|
+
const v = value;
|
|
48
|
+
if (!(typeof v.isDate === "function" && typeof v.isTime === "function")) return value;
|
|
49
|
+
const canonical = value.toISOString().replace(/\.000(?=([Zz]|[+-]\d{2}:\d{2})$|$)/, "");
|
|
50
|
+
if (v.isDate()) return new LocalDate(canonical);
|
|
51
|
+
if (v.isTime()) return new LocalTime(canonical, canonical);
|
|
52
|
+
if (v.isLocal()) return new LocalDateTime(canonical, false);
|
|
53
|
+
return new OffsetDateTime(canonical, false);
|
|
54
|
+
}
|
|
55
|
+
/** Detects the radix and prefix of a prefixed integer literal (`0x`/`0o`/`0b`). */
|
|
56
|
+
function integerRadixOf(raw) {
|
|
57
|
+
if (raw.startsWith("0x")) return {
|
|
58
|
+
radix: 16,
|
|
59
|
+
prefix: "0x"
|
|
60
|
+
};
|
|
61
|
+
if (raw.startsWith("0o")) return {
|
|
62
|
+
radix: 8,
|
|
63
|
+
prefix: "0o"
|
|
64
|
+
};
|
|
65
|
+
if (raw.startsWith("0b")) return {
|
|
66
|
+
radix: 2,
|
|
67
|
+
prefix: "0b"
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function encodeInteger(value, existingRaw) {
|
|
71
|
+
if (existingRaw) {
|
|
72
|
+
const radixInfo = integerRadixOf(existingRaw);
|
|
73
|
+
if (radixInfo && value >= 0) {
|
|
74
|
+
const uppercaseHex = radixInfo.radix === 16 && /[A-F]/.test(existingRaw);
|
|
75
|
+
let digits = value.toString(radixInfo.radix);
|
|
76
|
+
if (uppercaseHex) digits = digits.toUpperCase();
|
|
77
|
+
return radixInfo.prefix + digits;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return String(value);
|
|
81
|
+
}
|
|
82
|
+
function encodeFloat(value, existingRaw) {
|
|
83
|
+
if (Object.is(value, -0)) return "-0.0";
|
|
84
|
+
if (existingRaw && /[eE]/.test(existingRaw)) return encodeExponentFloat(value, existingRaw);
|
|
85
|
+
const raw = String(value);
|
|
86
|
+
return /[.eE]/.test(raw) ? raw : `${raw}.0`;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Renders a value in exponent notation, matching an existing float's style:
|
|
90
|
+
* a TOML exponent (no leading `+`) and the mantissa's decimal-place count, but
|
|
91
|
+
* dropping a non-zero fraction once the new value becomes a whole number.
|
|
92
|
+
*/
|
|
93
|
+
function encodeExponentFloat(value, existingRaw) {
|
|
94
|
+
const mantissaRaw = existingRaw.slice(0, existingRaw.search(/[eE]/));
|
|
95
|
+
const dotIndex = mantissaRaw.indexOf(".");
|
|
96
|
+
const fraction = dotIndex === -1 ? "" : mantissaRaw.slice(dotIndex + 1);
|
|
97
|
+
const isRound = !/[1-9]/.test(fraction);
|
|
98
|
+
const minDecimals = Number.isInteger(value) && !Object.is(value, -0) ? isRound ? fraction.length : 0 : 0;
|
|
99
|
+
const [mantissa, exponent] = value.toExponential().split(/[eE]/);
|
|
100
|
+
const mantissaDecimals = mantissa.includes(".") ? mantissa.length - mantissa.indexOf(".") - 1 : 0;
|
|
101
|
+
const decimals = Math.max(minDecimals, mantissaDecimals);
|
|
102
|
+
return `${decimals > 0 ? Number(mantissa).toFixed(decimals) : String(Number(mantissa))}${existingRaw.includes("E") ? "E" : "e"}${exponent.replace(/^\+/, "")}`;
|
|
103
|
+
}
|
|
104
|
+
function encodeNonFinite(value) {
|
|
105
|
+
if (Number.isNaN(value)) return isNegativeNan(value) ? "-nan" : "nan";
|
|
106
|
+
return value > 0 ? "inf" : "-inf";
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Encodes a string while preserving the source's literal style. A multiline
|
|
110
|
+
* literal (`'''`) keeps its delimiters and leading newline, and a single-line
|
|
111
|
+
* literal (`'`) stays single-quoted. Backslashes are left untouched because
|
|
112
|
+
* literal strings do not escape, matching the full patch(). A value that can no
|
|
113
|
+
* longer be written literally grows to a multiline literal where possible and
|
|
114
|
+
* falls back to a basic string otherwise.
|
|
115
|
+
*/
|
|
116
|
+
/**
|
|
117
|
+
* The newline to write directly after a multiline delimiter.
|
|
118
|
+
*
|
|
119
|
+
* TOML drops a newline that immediately follows the opening delimiter, so a
|
|
120
|
+
* value that starts with one needs an extra, disposable newline in front of it
|
|
121
|
+
* to survive the round trip.
|
|
122
|
+
*/
|
|
123
|
+
function multilineLeadingNewLine(existingRaw, delimiter, content) {
|
|
124
|
+
if (existingRaw.startsWith(delimiter + "\r\n")) return "\r\n";
|
|
125
|
+
if (existingRaw.startsWith(delimiter + "\n")) return "\n";
|
|
126
|
+
if (content.startsWith("\r\n")) return "\r\n";
|
|
127
|
+
return content.startsWith("\n") ? "\n" : "";
|
|
128
|
+
}
|
|
129
|
+
function encodeString(value, existingRaw) {
|
|
130
|
+
if (existingRaw) {
|
|
131
|
+
if (existingRaw.startsWith("'''")) {
|
|
132
|
+
if (!canUseMultilineLiteral(value)) return encodeBasicString(value);
|
|
133
|
+
return "'''" + multilineLeadingNewLine(existingRaw, "'''", value) + value + "'''";
|
|
134
|
+
}
|
|
135
|
+
if (existingRaw.startsWith("\"\"\"")) return encodeMultilineBasicString(value, existingRaw);
|
|
136
|
+
if (existingRaw.startsWith("'")) {
|
|
137
|
+
if (canUseLiteralString(value)) return "'" + value + "'";
|
|
138
|
+
if (canUseMultilineLiteral(value)) return "'''" + multilineLeadingNewLine(existingRaw, "'''", value) + value + "'''";
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return encodeBasicString(value);
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Encodes a value as a multiline basic string (`"""`), preserving the leading
|
|
145
|
+
* newline style of the source and escaping backslashes, control characters and
|
|
146
|
+
* embedded triple quotes, matching the full patch().
|
|
147
|
+
*/
|
|
148
|
+
function encodeMultilineBasicString(value, existingRaw) {
|
|
149
|
+
const content = escapeMultilineBasicContent(value);
|
|
150
|
+
return "\"\"\"" + multilineLeadingNewLine(existingRaw, "\"\"\"", content) + content + "\"\"\"";
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Escapes the content of a multiline basic string: backslashes are doubled,
|
|
154
|
+
* control characters are escaped, newlines stay literal (CR only as part of
|
|
155
|
+
* CRLF), and embedded `"""` is protected as `""\"`.
|
|
156
|
+
*/
|
|
157
|
+
function escapeMultilineBasicContent(value) {
|
|
158
|
+
let out = "";
|
|
159
|
+
for (let i = 0; i < value.length; i++) {
|
|
160
|
+
const ch = value[i];
|
|
161
|
+
const code = value.charCodeAt(i);
|
|
162
|
+
if (ch === "\\") out += "\\\\";
|
|
163
|
+
else if (ch === "\b") out += "\\b";
|
|
164
|
+
else if (ch === " ") out += "\\t";
|
|
165
|
+
else if (ch === "\n") out += "\n";
|
|
166
|
+
else if (ch === "\f") out += "\\f";
|
|
167
|
+
else if (ch === "\r") out += value.charCodeAt(i + 1) === 10 ? "\r" : "\\r";
|
|
168
|
+
else if (code >= 0 && code <= 7 || code === 11 || code >= 14 && code <= 31 || code === 127) out += "\\u" + code.toString(16).padStart(4, "0").toUpperCase();
|
|
169
|
+
else out += ch;
|
|
170
|
+
}
|
|
171
|
+
return out.replace(/"""/g, "\"\"\\\"");
|
|
172
|
+
}
|
|
173
|
+
function encodeBasicString(value) {
|
|
174
|
+
let out = "\"";
|
|
175
|
+
for (const ch of value) {
|
|
176
|
+
const code = ch.codePointAt(0);
|
|
177
|
+
if (ch === "\"") out += "\\\"";
|
|
178
|
+
else if (ch === "\\") out += "\\\\";
|
|
179
|
+
else if (ch === "\b") out += "\\b";
|
|
180
|
+
else if (ch === " ") out += "\\t";
|
|
181
|
+
else if (ch === "\n") out += "\\n";
|
|
182
|
+
else if (ch === "\f") out += "\\f";
|
|
183
|
+
else if (ch === "\r") out += "\\r";
|
|
184
|
+
else if (code < 32 || code === 127) out += "\\u" + code.toString(16).padStart(4, "0").toUpperCase();
|
|
185
|
+
else out += ch;
|
|
186
|
+
}
|
|
187
|
+
out += "\"";
|
|
188
|
+
return out;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
//#endregion
|
|
192
|
+
export { encodeValue };
|
|
193
|
+
//# sourceMappingURL=encode-lite.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"encode-lite.js","names":["isFloatNode"],"sources":["../../src/encode-lite.ts"],"sourcesContent":["import { isFloat as isFloatNode } from './cst';\nimport { DateFormatHelper, LocalDate, LocalTime, LocalDateTime, OffsetDateTime } from './date-format';\nimport { PatchLiteError, formatPath, Path } from './diff-lite';\nimport { canUseLiteralString, canUseMultilineLiteral } from './literal-string';\nimport { isNegativeNan } from './utils';\n\n/**\n * Encodes a JavaScript leaf value as valid TOML, independent of the full\n * formatting pipeline. Only the value span is produced; the surrounding key,\n * equals sign, whitespace and comments are never regenerated.\n */\nexport function encodeValue(value: any, existingValue: any, path: Path): string {\n const type = typeof value;\n\n if (type === 'string') return encodeString(value, existingValue?.raw);\n if (type === 'boolean') return value ? 'true' : 'false';\n if (type === 'bigint') return value.toString();\n\n if (type === 'number') {\n if (!Number.isFinite(value)) return encodeNonFinite(value);\n if (Number.isSafeInteger(value) && !Object.is(value, -0) && !isFloatNode(existingValue)) {\n return encodeInteger(value, existingValue?.raw);\n }\n return encodeFloat(value, isFloatNode(existingValue) ? existingValue.raw : undefined);\n }\n\n if (value instanceof Date) {\n return encodeDate(value, existingValue);\n }\n\n throw new PatchLiteError(\n 'UnsupportedValue',\n path,\n `Unsupported value type ${Object.prototype.toString.call(value)} at ${formatPath(path)}`\n );\n}\n\n/**\n * Encodes a Date as TOML while keeping the source value's formatting: date vs\n * time vs datetime kind, fractional-digit count, space separator and offset\n * style are all taken from the existing value's raw text, exactly as the full\n * patch() does.\n */\nfunction encodeDate(value: Date, existingValue: any): string {\n const raw = existingValue?.raw;\n const native = toTomlPatchDate(value);\n if (typeof raw !== 'string') return native.toISOString();\n return DateFormatHelper.createDateWithOriginalFormat(native, raw).toISOString();\n}\n\n/**\n * Converts a smol-toml `TomlDate` to the matching toml-patch class. Duck-typed\n * (the two packages have distinct class objects) and kept local so the lite\n * bundle does not import the vendored smol-toml date module. The `.000` suffix\n * smol-toml always writes for a zero fraction is dropped, so it does not leak\n * into the output and the result matches the full patch() byte for byte.\n */\nfunction toTomlPatchDate(value: Date): Date {\n const v = value as any;\n const isSmolTomlDate = typeof v.isDate === 'function' && typeof v.isTime === 'function';\n if (!isSmolTomlDate) return value;\n\n const canonical = value.toISOString().replace(/\\.000(?=([Zz]|[+-]\\d{2}:\\d{2})$|$)/, '');\n if (v.isDate()) return new LocalDate(canonical);\n if (v.isTime()) return new LocalTime(canonical, canonical);\n if (v.isLocal()) return new LocalDateTime(canonical, false);\n return new OffsetDateTime(canonical, false);\n}\n\n/** Detects the radix and prefix of a prefixed integer literal (`0x`/`0o`/`0b`). */\nfunction integerRadixOf(raw: string): { radix: number; prefix: string } | undefined {\n if (raw.startsWith('0x')) return { radix: 16, prefix: '0x' };\n if (raw.startsWith('0o')) return { radix: 8, prefix: '0o' };\n if (raw.startsWith('0b')) return { radix: 2, prefix: '0b' };\n return undefined;\n}\n\nfunction encodeInteger(value: number, existingRaw?: string): string {\n if (existingRaw) {\n const radixInfo = integerRadixOf(existingRaw);\n // TOML prefixed integers cannot carry a sign, so negative values fall\n // back to plain decimal.\n if (radixInfo && value >= 0) {\n const uppercaseHex = radixInfo.radix === 16 && /[A-F]/.test(existingRaw);\n let digits = value.toString(radixInfo.radix);\n if (uppercaseHex) digits = digits.toUpperCase();\n return radixInfo.prefix + digits;\n }\n }\n return String(value);\n}\n\nfunction encodeFloat(value: number, existingRaw?: string): string {\n if (Object.is(value, -0)) return '-0.0';\n\n // Preserve exponent notation when the source used it (e.g. `1.0e10` ->\n // `1.0e11`) rather than expanding into a long plain float.\n if (existingRaw && /[eE]/.test(existingRaw)) {\n return encodeExponentFloat(value, existingRaw);\n }\n\n const raw = String(value);\n return /[.eE]/.test(raw) ? raw : `${raw}.0`;\n}\n\n/**\n * Renders a value in exponent notation, matching an existing float's style:\n * a TOML exponent (no leading `+`) and the mantissa's decimal-place count, but\n * dropping a non-zero fraction once the new value becomes a whole number.\n */\nfunction encodeExponentFloat(value: number, existingRaw: string): string {\n const mantissaRaw = existingRaw.slice(0, existingRaw.search(/[eE]/));\n const dotIndex = mantissaRaw.indexOf('.');\n const fraction = dotIndex === -1 ? '' : mantissaRaw.slice(dotIndex + 1);\n const isRound = !/[1-9]/.test(fraction);\n const valueIsIntegral = Number.isInteger(value) && !Object.is(value, -0);\n\n // Keep the original's decimal count only for an explicit \"round\" float; a\n // non-zero fraction is insignificant once the new value becomes a whole number.\n const minDecimals = valueIsIntegral ? (isRound ? fraction.length : 0) : 0;\n\n const [mantissa, exponent] = value.toExponential().split(/[eE]/);\n const mantissaDecimals = mantissa.includes('.') ? mantissa.length - mantissa.indexOf('.') - 1 : 0;\n const decimals = Math.max(minDecimals, mantissaDecimals);\n const renderedMantissa = decimals > 0\n ? Number(mantissa).toFixed(decimals)\n : String(Number(mantissa));\n const uppercaseExponent = existingRaw.includes('E');\n return `${renderedMantissa}${uppercaseExponent ? 'E' : 'e'}${exponent.replace(/^\\+/, '')}`;\n}\n\nfunction encodeNonFinite(value: number): string {\n // `-nan` is a distinct TOML spelling that round-trips, so the sign has to be\n // written out; emitting a plain `nan` would make the value look changed again\n // on the next call.\n if (Number.isNaN(value)) return isNegativeNan(value) ? '-nan' : 'nan';\n return value > 0 ? 'inf' : '-inf';\n}\n\n/**\n * Encodes a string while preserving the source's literal style. A multiline\n * literal (`'''`) keeps its delimiters and leading newline, and a single-line\n * literal (`'`) stays single-quoted. Backslashes are left untouched because\n * literal strings do not escape, matching the full patch(). A value that can no\n * longer be written literally grows to a multiline literal where possible and\n * falls back to a basic string otherwise.\n */\n/**\n * The newline to write directly after a multiline delimiter.\n *\n * TOML drops a newline that immediately follows the opening delimiter, so a\n * value that starts with one needs an extra, disposable newline in front of it\n * to survive the round trip.\n */\nfunction multilineLeadingNewLine(existingRaw: string, delimiter: string, content: string): string {\n if (existingRaw.startsWith(delimiter + '\\r\\n')) return '\\r\\n';\n if (existingRaw.startsWith(delimiter + '\\n')) return '\\n';\n if (content.startsWith('\\r\\n')) return '\\r\\n';\n return content.startsWith('\\n') ? '\\n' : '';\n}\n\nfunction encodeString(value: string, existingRaw?: string): string {\n if (existingRaw) {\n if (existingRaw.startsWith(\"'''\")) {\n if (!canUseMultilineLiteral(value)) return encodeBasicString(value);\n return \"'''\" + multilineLeadingNewLine(existingRaw, \"'''\", value) + value + \"'''\";\n }\n if (existingRaw.startsWith('\"\"\"')) {\n return encodeMultilineBasicString(value, existingRaw);\n }\n if (existingRaw.startsWith(\"'\")) {\n if (canUseLiteralString(value)) return \"'\" + value + \"'\";\n // Single quotes are non-negotiable but one of them is: a value holding an\n // apostrophe or a newline moves up to a multiline literal.\n if (canUseMultilineLiteral(value)) {\n return \"'''\" + multilineLeadingNewLine(existingRaw, \"'''\", value) + value + \"'''\";\n }\n }\n }\n return encodeBasicString(value);\n}\n\n/**\n * Encodes a value as a multiline basic string (`\"\"\"`), preserving the leading\n * newline style of the source and escaping backslashes, control characters and\n * embedded triple quotes, matching the full patch().\n */\nfunction encodeMultilineBasicString(value: string, existingRaw: string): string {\n const content = escapeMultilineBasicContent(value);\n return '\"\"\"' + multilineLeadingNewLine(existingRaw, '\"\"\"', content) + content + '\"\"\"';\n}\n\n/**\n * Escapes the content of a multiline basic string: backslashes are doubled,\n * control characters are escaped, newlines stay literal (CR only as part of\n * CRLF), and embedded `\"\"\"` is protected as `\"\"\\\"`.\n */\nfunction escapeMultilineBasicContent(value: string): string {\n let out = '';\n for (let i = 0; i < value.length; i++) {\n const ch = value[i];\n const code = value.charCodeAt(i);\n if (ch === '\\\\') out += '\\\\\\\\';\n else if (ch === '\\b') out += '\\\\b';\n else if (ch === '\\t') out += '\\\\t';\n else if (ch === '\\n') out += '\\n';\n else if (ch === '\\f') out += '\\\\f';\n else if (ch === '\\r') {\n // A carriage return is only valid when part of CRLF; escape it otherwise.\n out += value.charCodeAt(i + 1) === 0x0a ? '\\r' : '\\\\r';\n } else if (\n (code >= 0x00 && code <= 0x07) ||\n code === 0x0b ||\n (code >= 0x0e && code <= 0x1f) ||\n code === 0x7f\n ) {\n out += '\\\\u' + code.toString(16).padStart(4, '0').toUpperCase();\n } else {\n out += ch;\n }\n }\n return out.replace(/\"\"\"/g, '\"\"\\\\\"');\n}\n\nfunction encodeBasicString(value: string): string {\n let out = '\"';\n\n for (const ch of value) {\n const code = ch.codePointAt(0)!;\n\n if (ch === '\"') out += '\\\\\"';\n else if (ch === '\\\\') out += '\\\\\\\\';\n else if (ch === '\\b') out += '\\\\b';\n else if (ch === '\\t') out += '\\\\t';\n else if (ch === '\\n') out += '\\\\n';\n else if (ch === '\\f') out += '\\\\f';\n else if (ch === '\\r') out += '\\\\r';\n else if (code < 0x20 || code === 0x7f) out += '\\\\u' + code.toString(16).padStart(4, '0').toUpperCase();\n else out += ch;\n }\n\n out += '\"';\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;AAWA,SAAgB,YAAY,OAAY,eAAoB,MAAoB;CAC9E,MAAM,OAAO,OAAO;CAEpB,IAAI,SAAS,UAAU,OAAO,aAAa,qEAAO,cAAe,GAAG;CACpE,IAAI,SAAS,WAAW,OAAO,QAAQ,SAAS;CAChD,IAAI,SAAS,UAAU,OAAO,MAAM,SAAS;CAE7C,IAAI,SAAS,UAAU;EACrB,IAAI,CAAC,OAAO,SAAS,KAAK,GAAG,OAAO,gBAAgB,KAAK;EACzD,IAAI,OAAO,cAAc,KAAK,KAAK,CAAC,OAAO,GAAG,OAAO,EAAE,KAAK,CAACA,QAAY,aAAa,GACpF,OAAO,cAAc,qEAAO,cAAe,GAAG;EAEhD,OAAO,YAAY,OAAOA,QAAY,aAAa,IAAI,cAAc,MAAM,MAAS;CACtF;CAEA,IAAI,iBAAiB,MACnB,OAAO,WAAW,OAAO,aAAa;CAGxC,MAAM,IAAI,eACR,oBACA,MACA,0BAA0B,OAAO,UAAU,SAAS,KAAK,KAAK,EAAE,MAAM,WAAW,IAAI,GACvF;AACF;;;;;;;AAQA,SAAS,WAAW,OAAa,eAA4B;CAC3D,MAAM,oEAAM,cAAe;CAC3B,MAAM,SAAS,gBAAgB,KAAK;CACpC,IAAI,OAAO,QAAQ,UAAU,OAAO,OAAO,YAAY;CACvD,OAAO,iBAAiB,6BAA6B,QAAQ,GAAG,CAAC,CAAC,YAAY;AAChF;;;;;;;;AASA,SAAS,gBAAgB,OAAmB;CAC1C,MAAM,IAAI;CAEV,IAAI,EADmB,OAAO,EAAE,WAAW,cAAc,OAAO,EAAE,WAAW,aACxD,OAAO;CAE5B,MAAM,YAAY,MA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AAO;OACxB,IAAI,OAAO,MAAM,OAAO;OACxB,IAAI,OAAO,MAAM,OAAO;OACxB,IAAI,OAAO,MAAQ,SAAS,KAAM,OAAO,QAAQ,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,YAAY;OAChG,OAAO;CACd;CAEA,OAAO;CACP,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//! @decimalturn/toml-patch v3.
|
|
1
|
+
//! @decimalturn/toml-patch v3.2.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
|
|
2
2
|
//#region src/escape-preference.ts
|
|
3
3
|
/**
|
|
4
4
|
* @file Escape-style helpers used to preserve escape sequences as preferred encoding (e.g. \u263A)
|
|
@@ -44,7 +44,7 @@ function isDisallowedControl(code, mode) {
|
|
|
44
44
|
if (mode === "singleline-basic") return code <= 31 || code === 127;
|
|
45
45
|
return code >= 0 && code <= 7 || code === 11 || code >= 14 && code <= 31 || code === 127;
|
|
46
46
|
}
|
|
47
|
-
function mandatoryEscaping(ch, mode) {
|
|
47
|
+
function mandatoryEscaping(ch, mode, escapeSequenceUpperCase) {
|
|
48
48
|
switch (ch) {
|
|
49
49
|
case "\\": return "\\\\";
|
|
50
50
|
case "\b": return "\\b";
|
|
@@ -55,12 +55,30 @@ function mandatoryEscaping(ch, mode) {
|
|
|
55
55
|
case "\r": return mode === "singleline-basic" ? "\\r" : "\r";
|
|
56
56
|
default: {
|
|
57
57
|
const code = ch.charCodeAt(0);
|
|
58
|
-
if (isDisallowedControl(code, mode))
|
|
58
|
+
if (isDisallowedControl(code, mode)) {
|
|
59
|
+
const hex = code.toString(16).padStart(4, "0");
|
|
60
|
+
return `\\u${escapeSequenceUpperCase ? hex.toUpperCase() : hex}`;
|
|
61
|
+
}
|
|
59
62
|
return ch;
|
|
60
63
|
}
|
|
61
64
|
}
|
|
62
65
|
}
|
|
63
66
|
/**
|
|
67
|
+
* Uppercases the hex digits of the `\uXXXX` escapes in string content that has
|
|
68
|
+
* already been escaped, for example `\u007f` to `\u007F`.
|
|
69
|
+
*
|
|
70
|
+
* Only escapes are rewritten. A `\uXXXX` that is content rather than an escape
|
|
71
|
+
* is preceded by an escaped backslash, so its run of backslashes has an even
|
|
72
|
+
* length and the sequence is left as written. Uppercasing those would change
|
|
73
|
+
* the value: a string holding the text `\u000c` must not come back as `\u000C`.
|
|
74
|
+
*
|
|
75
|
+
* @param escaped - Content that has already been escaped for a basic string.
|
|
76
|
+
* @returns The content with the hex digits of its escapes uppercased.
|
|
77
|
+
*/
|
|
78
|
+
function upperCaseHexEscapes(escaped) {
|
|
79
|
+
return escaped.replace(/(\\+)u([0-9a-f]{4})/g, (match, backslashes, hex) => backslashes.length % 2 === 1 ? `${backslashes}u${hex.toUpperCase()}` : match);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
64
82
|
* Scans a raw TOML string token and records preferred escape sequence representations for characters.
|
|
65
83
|
*
|
|
66
84
|
* Example: if `existingRaw` contains `\u263A`, this map stores `☺ -> "\\u263A"`.
|
|
@@ -108,7 +126,7 @@ function collectPreferredEscapes(existingRaw) {
|
|
|
108
126
|
}
|
|
109
127
|
return preferred;
|
|
110
128
|
}
|
|
111
|
-
function applyPreferredAndMandatoryEscapes(value, preferred, mode) {
|
|
129
|
+
function applyPreferredAndMandatoryEscapes(value, preferred, mode, escapeSequenceUpperCase) {
|
|
112
130
|
let escaped = "";
|
|
113
131
|
for (const ch of value) {
|
|
114
132
|
const preferredEscape = preferred.get(ch);
|
|
@@ -116,7 +134,7 @@ function applyPreferredAndMandatoryEscapes(value, preferred, mode) {
|
|
|
116
134
|
escaped += preferredEscape;
|
|
117
135
|
continue;
|
|
118
136
|
}
|
|
119
|
-
escaped += mandatoryEscaping(ch, mode);
|
|
137
|
+
escaped += mandatoryEscaping(ch, mode, escapeSequenceUpperCase);
|
|
120
138
|
}
|
|
121
139
|
return escaped;
|
|
122
140
|
}
|
|
@@ -125,20 +143,24 @@ function applyPreferredAndMandatoryEscapes(value, preferred, mode) {
|
|
|
125
143
|
*
|
|
126
144
|
* In `singleline-basic` mode, output is suitable for `"..."` strings.
|
|
127
145
|
* In `multiline-basic` mode, output is suitable for `"""..."""` strings and additionally
|
|
128
|
-
* protects embedded triple quotes.
|
|
146
|
+
* escapes standalone carriage returns and protects embedded triple quotes.
|
|
129
147
|
*
|
|
130
148
|
* @param value - Unescaped JS string value.
|
|
131
149
|
* @param existingRaw - Existing TOML raw string used to infer preferred escapes.
|
|
132
150
|
* @param mode - String rendering mode (`singleline-basic` or `multiline-basic`).
|
|
133
151
|
* @returns Escaped TOML string content without surrounding delimiters.
|
|
134
152
|
*/
|
|
135
|
-
function escapeStringContent(value, existingRaw, mode) {
|
|
153
|
+
function escapeStringContent(value, existingRaw, mode, escapeSequenceUpperCase = true) {
|
|
136
154
|
const preferred = collectPreferredEscapes(existingRaw);
|
|
137
|
-
if (preferred.size === 0 && mode === "singleline-basic")
|
|
138
|
-
|
|
139
|
-
|
|
155
|
+
if (preferred.size === 0 && mode === "singleline-basic") {
|
|
156
|
+
const withDel = JSON.stringify(value).slice(1, -1).replace(/\x7f/g, "\\u007f");
|
|
157
|
+
return escapeSequenceUpperCase ? upperCaseHexEscapes(withDel) : withDel;
|
|
158
|
+
}
|
|
159
|
+
const escaped = applyPreferredAndMandatoryEscapes(value, preferred, mode, escapeSequenceUpperCase);
|
|
160
|
+
if (mode !== "multiline-basic") return escaped;
|
|
161
|
+
return escaped.replace(/\r(?!\n)/g, "\\r").replace(/"""/g, "\"\"\\\"");
|
|
140
162
|
}
|
|
141
163
|
|
|
142
164
|
//#endregion
|
|
143
|
-
export { collectPreferredEscapes, escapeStringContent };
|
|
165
|
+
export { collectPreferredEscapes, escapeStringContent, upperCaseHexEscapes };
|
|
144
166
|
//# sourceMappingURL=escape-preference.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"escape-preference.js","names":[],"sources":["../../src/escape-preference.ts"],"sourcesContent":["/**\n * @file Escape-style helpers used to preserve escape sequences as preferred encoding (e.g. \\u263A)\n * when rewriting TOML basic strings and quoted key parts.\n * \n * @module escape-preference\n * \n * Summary:\n * The problem with naive parsing + re-serializing of TOML strings is that it normalizes \n * all escape sequences to their decoded character values.\n * \n * For example, if a TOML string contains `\\u263A`, the JS string value will contain the raw ☺ character.\n * If we then naively return that string for TOML output, we would get `☺` instead of the original `\\u263A`.\n * This module provides functions to scan existing raw TOML strings to infer the preferred representation of certain characters\n * and then reuse those preferred escapes when generating new TOML output, thus preserving the original style where possible.\n * \n * Note that we are taking the presence of a single instance of an escape sequence in the original raw string as \n * an indication of the user's preferred rendering for that character. A more faithful preservation of style \n * would be to track all instances of each character and their various rendered forms, but this would add \n * complexity and overhead. The current approach tries to balance things out by capturing the first seen \n * escape for each character, which should cover the vast majority of use cases for TOML.\n * \n */\n\n/**\n * Decodes a TOML single-character escape code to its JS character.\n *\n * @param ch - Escape code character (without the leading backslash).\n * @returns The decoded character, or null if the code is not a supported simple escape.\n */\nfunction decodeSimpleEscape(ch: string): string | null {\n switch (ch) {\n case 'b': return '\\b';\n case 't': return '\\t';\n case 'n': return '\\n';\n case 'f': return '\\f';\n case 'r': return '\\r';\n case '\"': return '\"'; // Note that double quotes don't need escaping in JS.\n // Note that single quotes are not escaped in TOML basic strings, so no case for '\\'' is needed.\n case '\\\\': return '\\\\';\n default: return null;\n }\n}\n\nexport type EscapeMode = 'singleline-basic' | 'multiline-basic';\n\nfunction isDisallowedControl(code: number, mode: EscapeMode): boolean {\n if (mode === 'singleline-basic') {\n return code <= 0x1f || code === 0x7f;\n }\n\n return (\n (code >= 0x00 && code <= 0x07) ||\n code === 0x0b ||\n (code >= 0x0e && code <= 0x1f) ||\n code === 0x7f\n );\n}\n\nfunction mandatoryEscaping(ch: string, mode: EscapeMode): string {\n switch (ch) {\n case '\\\\':\n return '\\\\\\\\';\n case '\\b':\n return '\\\\b';\n case '\\t':\n return '\\\\t';\n case '\\f':\n return '\\\\f';\n case '\"':\n return mode === 'singleline-basic' ? '\\\\\"' : '\"';\n case '\\n':\n return mode === 'singleline-basic' ? '\\\\n' : '\\n';\n case '\\r':\n return mode === 'singleline-basic' ? '\\\\r' : '\\r';\n default: {\n const code = ch.charCodeAt(0);\n if (isDisallowedControl(code, mode)) {\n return `\\\\u${code.toString(16).padStart(4, '0').toUpperCase()}`;\n }\n return ch;\n }\n }\n}\n\n/**\n * Scans a raw TOML string token and records preferred escape sequence representations for characters.\n *\n * Example: if `existingRaw` contains `\\u263A`, this map stores `☺ -> \"\\\\u263A\"`.\n * The first seen escape for a character wins to preserve original style.\n *\n * @param existingRaw - Raw TOML string content including escape sequences.\n * @returns A map from decoded character to preferred TOML escape sequence representation.\n */\nexport function collectPreferredEscapes(existingRaw: string): Map<string, string> {\n const preferred = new Map<string, string>();\n\n for (let i = 0; i < existingRaw.length; i++) {\n if (existingRaw[i] !== '\\\\') continue;\n\n const n1 = existingRaw[i + 1];\n if (!n1) continue;\n\n const simple = decodeSimpleEscape(n1);\n if (simple !== null) {\n // Newlines (\\n, \\r) are handled separately and excluded from preference tracking.\n if (simple !== '\\n' && simple !== '\\r' && !preferred.has(simple)) {\n preferred.set(simple, '\\\\' + n1);\n }\n i += 1;\n continue;\n }\n\n if (n1 === 'x' && /^[0-9A-Fa-f]{2}$/.test(existingRaw.slice(i + 2, i + 4))) {\n const rawEscape = existingRaw.slice(i, i + 4);\n const code = Number.parseInt(existingRaw.slice(i + 2, i + 4), 16);\n const decoded = String.fromCharCode(code);\n if (!preferred.has(decoded)) preferred.set(decoded, rawEscape);\n i += 3;\n continue;\n }\n\n if (n1 === 'u' && /^[0-9A-Fa-f]{4}$/.test(existingRaw.slice(i + 2, i + 6))) {\n const rawEscape = existingRaw.slice(i, i + 6);\n const code = Number.parseInt(existingRaw.slice(i + 2, i + 6), 16);\n const decoded = String.fromCodePoint(code);\n if (!preferred.has(decoded)) preferred.set(decoded, rawEscape);\n i += 5;\n continue;\n }\n\n if (n1 === 'U' && /^[0-9A-Fa-f]{8}$/.test(existingRaw.slice(i + 2, i + 10))) {\n const rawEscape = existingRaw.slice(i, i + 10);\n const code = Number.parseInt(existingRaw.slice(i + 2, i + 10), 16);\n const decoded = String.fromCodePoint(code);\n if (!preferred.has(decoded)) preferred.set(decoded, rawEscape);\n i += 9;\n continue;\n }\n }\n\n return preferred;\n}\n\nfunction applyPreferredAndMandatoryEscapes(\n value: string,\n preferred: Map<string, string>,\n mode: EscapeMode\n): string {\n let escaped = '';\n\n for (const ch of value) {\n const preferredEscape = preferred.get(ch);\n if (preferredEscape) {\n escaped += preferredEscape;\n continue;\n }\n\n escaped += mandatoryEscaping(ch, mode);\n }\n\n return escaped;\n}\n\n/**\n * Escapes TOML basic-string content while preserving preferred escape sequences representation from existing raw text.\n *\n * In `singleline-basic` mode, output is suitable for `\"...\"` strings.\n * In `multiline-basic` mode, output is suitable for `\"\"\"...\"\"\"` strings and additionally\n * protects embedded triple quotes.\n *\n * @param value - Unescaped JS string value.\n * @param existingRaw - Existing TOML raw string used to infer preferred escapes.\n * @param mode - String rendering mode (`singleline-basic` or `multiline-basic`).\n * @returns Escaped TOML string content without surrounding delimiters.\n */\nexport function escapeStringContent(value: string, existingRaw: string, mode: EscapeMode): string {\n const preferred = collectPreferredEscapes(existingRaw);\n\n if (preferred.size === 0 && mode === 'singleline-basic') {\n const escaped = JSON.stringify(value).slice(1, -1);\n // JSON.stringify only escapes U+0000–U+001F, but TOML also forbids U+007F (DEL).\n return escaped.replace(/\\x7f/g, '\\\\u007F');\n }\n\n const escaped = applyPreferredAndMandatoryEscapes(value, preferred, mode);\n\n return mode === 'multiline-basic' ? escaped.replace(/\"\"\"/g, '\"\"\\\\\"') : escaped;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAS,mBAAmB,IAA2B;CACrD,QAAQ,IAAR;EACE,KAAK,KAAK,OAAO;EACjB,KAAK,KAAK,OAAO;EACjB,KAAK,KAAK,OAAO;EACjB,KAAK,KA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A0B;CAChG,MAAM,YAAY,wBAAwB,WAAW;CAErD,IAAI,UAAU,SAAS,KAAK,SAAS,oBAGnC,OAFgB,KAAK,UAAU,KAAK,CAAC,CAAC,MAAM,GAAG,EAElC,CAAC,CAAC,QAAQ,SAAS,SAAS;CAG3C,MAAM,UAAU,kCAAkC,OAAO,WAAW,IAAI;CAExE,OAAO,SAAS,oBAAoB,QAAQ,QAAQ,QAAQ,UAAO,IAAI;AACzE"}
|
|
1
|
+
{"version":3,"file":"escape-preference.js","names":[],"sources":["../../src/escape-preference.ts"],"sourcesContent":["/**\n * @file Escape-style helpers used to preserve escape sequences as preferred encoding (e.g. \\u263A)\n * when rewriting TOML basic strings and quoted key parts.\n * \n * @module escape-preference\n * \n * Summary:\n * The problem with naive parsing + re-serializing of TOML strings is that it normalizes \n * all escape sequences to their decoded character values.\n * \n * For example, if a TOML string contains `\\u263A`, the JS string value will contain the raw ☺ character.\n * If we then naively return that string for TOML output, we would get `☺` instead of the original `\\u263A`.\n * This module provides functions to scan existing raw TOML strings to infer the preferred representation of certain characters\n * and then reuse those preferred escapes when generating new TOML output, thus preserving the original style where possible.\n * \n * Note that we are taking the presence of a single instance of an escape sequence in the original raw string as \n * an indication of the user's preferred rendering for that character. A more faithful preservation of style \n * would be to track all instances of each character and their various rendered forms, but this would add \n * complexity and overhead. The current approach tries to balance things out by capturing the first seen \n * escape for each character, which should cover the vast majority of use cases for TOML.\n * \n */\n\n/**\n * Decodes a TOML single-character escape code to its JS character.\n *\n * @param ch - Escape code character (without the leading backslash).\n * @returns The decoded character, or null if the code is not a supported simple escape.\n */\nfunction decodeSimpleEscape(ch: string): string | null {\n switch (ch) {\n case 'b': return '\\b';\n case 't': return '\\t';\n case 'n': return '\\n';\n case 'f': return '\\f';\n case 'r': return '\\r';\n case '\"': return '\"'; // Note that double quotes don't need escaping in JS.\n // Note that single quotes are not escaped in TOML basic strings, so no case for '\\'' is needed.\n case '\\\\': return '\\\\';\n default: return null;\n }\n}\n\nexport type EscapeMode = 'singleline-basic' | 'multiline-basic';\n\nfunction isDisallowedControl(code: number, mode: EscapeMode): boolean {\n if (mode === 'singleline-basic') {\n return code <= 0x1f || code === 0x7f;\n }\n\n return (\n (code >= 0x00 && code <= 0x07) ||\n code === 0x0b ||\n (code >= 0x0e && code <= 0x1f) ||\n code === 0x7f\n );\n}\n\nfunction mandatoryEscaping(ch: string, mode: EscapeMode, escapeSequenceUpperCase: boolean): string {\n switch (ch) {\n case '\\\\':\n return '\\\\\\\\';\n case '\\b':\n return '\\\\b';\n case '\\t':\n return '\\\\t';\n case '\\f':\n return '\\\\f';\n case '\"':\n return mode === 'singleline-basic' ? '\\\\\"' : '\"';\n case '\\n':\n return mode === 'singleline-basic' ? '\\\\n' : '\\n';\n case '\\r':\n return mode === 'singleline-basic' ? '\\\\r' : '\\r';\n default: {\n const code = ch.charCodeAt(0);\n if (isDisallowedControl(code, mode)) {\n const hex = code.toString(16).padStart(4, '0');\n return `\\\\u${escapeSequenceUpperCase ? hex.toUpperCase() : hex}`;\n }\n return ch;\n }\n }\n}\n\n/**\n * Uppercases the hex digits of the `\\uXXXX` escapes in string content that has\n * already been escaped, for example `\\u007f` to `\\u007F`.\n *\n * Only escapes are rewritten. A `\\uXXXX` that is content rather than an escape\n * is preceded by an escaped backslash, so its run of backslashes has an even\n * length and the sequence is left as written. Uppercasing those would change\n * the value: a string holding the text `\\u000c` must not come back as `\\u000C`.\n *\n * @param escaped - Content that has already been escaped for a basic string.\n * @returns The content with the hex digits of its escapes uppercased.\n */\nexport function upperCaseHexEscapes(escaped: string): string {\n return escaped.replace(/(\\\\+)u([0-9a-f]{4})/g, (match, backslashes: string, hex: string) =>\n backslashes.length % 2 === 1 ? `${backslashes}u${hex.toUpperCase()}` : match\n );\n}\n\n/**\n * Scans a raw TOML string token and records preferred escape sequence representations for characters.\n *\n * Example: if `existingRaw` contains `\\u263A`, this map stores `☺ -> \"\\\\u263A\"`.\n * The first seen escape for a character wins to preserve original style.\n *\n * @param existingRaw - Raw TOML string content including escape sequences.\n * @returns A map from decoded character to preferred TOML escape sequence representation.\n */\nexport function collectPreferredEscapes(existingRaw: string): Map<string, string> {\n const preferred = new Map<string, string>();\n\n for (let i = 0; i < existingRaw.length; i++) {\n if (existingRaw[i] !== '\\\\') continue;\n\n const n1 = existingRaw[i + 1];\n if (!n1) continue;\n\n const simple = decodeSimpleEscape(n1);\n if (simple !== null) {\n // Newlines (\\n, \\r) are handled separately and excluded from preference tracking.\n if (simple !== '\\n' && simple !== '\\r' && !preferred.has(simple)) {\n preferred.set(simple, '\\\\' + n1);\n }\n i += 1;\n continue;\n }\n\n if (n1 === 'x' && /^[0-9A-Fa-f]{2}$/.test(existingRaw.slice(i + 2, i + 4))) {\n const rawEscape = existingRaw.slice(i, i + 4);\n const code = Number.parseInt(existingRaw.slice(i + 2, i + 4), 16);\n const decoded = String.fromCharCode(code);\n if (!preferred.has(decoded)) preferred.set(decoded, rawEscape);\n i += 3;\n continue;\n }\n\n if (n1 === 'u' && /^[0-9A-Fa-f]{4}$/.test(existingRaw.slice(i + 2, i + 6))) {\n const rawEscape = existingRaw.slice(i, i + 6);\n const code = Number.parseInt(existingRaw.slice(i + 2, i + 6), 16);\n const decoded = String.fromCodePoint(code);\n if (!preferred.has(decoded)) preferred.set(decoded, rawEscape);\n i += 5;\n continue;\n }\n\n if (n1 === 'U' && /^[0-9A-Fa-f]{8}$/.test(existingRaw.slice(i + 2, i + 10))) {\n const rawEscape = existingRaw.slice(i, i + 10);\n const code = Number.parseInt(existingRaw.slice(i + 2, i + 10), 16);\n const decoded = String.fromCodePoint(code);\n if (!preferred.has(decoded)) preferred.set(decoded, rawEscape);\n i += 9;\n continue;\n }\n }\n\n return preferred;\n}\n\nfunction applyPreferredAndMandatoryEscapes(\n value: string,\n preferred: Map<string, string>,\n mode: EscapeMode,\n escapeSequenceUpperCase: boolean\n): string {\n let escaped = '';\n\n for (const ch of value) {\n const preferredEscape = preferred.get(ch);\n if (preferredEscape) {\n escaped += preferredEscape;\n continue;\n }\n\n escaped += mandatoryEscaping(ch, mode, escapeSequenceUpperCase);\n }\n\n return escaped;\n}\n\n/**\n * Escapes TOML basic-string content while preserving preferred escape sequences representation from existing raw text.\n *\n * In `singleline-basic` mode, output is suitable for `\"...\"` strings.\n * In `multiline-basic` mode, output is suitable for `\"\"\"...\"\"\"` strings and additionally\n * escapes standalone carriage returns and protects embedded triple quotes.\n *\n * @param value - Unescaped JS string value.\n * @param existingRaw - Existing TOML raw string used to infer preferred escapes.\n * @param mode - String rendering mode (`singleline-basic` or `multiline-basic`).\n * @returns Escaped TOML string content without surrounding delimiters.\n */\nexport function escapeStringContent(\n value: string,\n existingRaw: string,\n mode: EscapeMode,\n escapeSequenceUpperCase = true\n): string {\n const preferred = collectPreferredEscapes(existingRaw);\n\n if (preferred.size === 0 && mode === 'singleline-basic') {\n const escaped = JSON.stringify(value).slice(1, -1);\n // JSON.stringify only escapes U+0000–U+001F, but TOML also forbids U+007F (DEL).\n const withDel = escaped.replace(/\\x7f/g, '\\\\u007f');\n return escapeSequenceUpperCase ? upperCaseHexEscapes(withDel) : withDel;\n }\n\n const escaped = applyPreferredAndMandatoryEscapes(value, preferred, mode, escapeSequenceUpperCase);\n\n if (mode !== 'multiline-basic') {\n return escaped;\n }\n\n // A carriage return is only allowed in a multiline string as part of CRLF, so a\n // standalone one is escaped rather than written out raw, which would produce a\n // document that cannot be parsed back.\n return escaped.replace(/\\r(?!\\n)/g, '\\\\r').replace(/\"\"\"/g, '\"\"\\\\\"');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAS,mBAAmB,IAA2B;CACrD,QAAQ,IAAR;EACE,KAAK,KAAK,OAAO;EACjB,KAAK,KAAK,OAAO;EACjB,KAAK,KAAK,OAAO;EACjB,KAAK,KAAK,OAAO;EACjB,KAAK,KAAK,OAAO;EACjB,KAAK,MAAK,OAAO;EAEjB,KAAK,MAAM,OAAO;EAClB,SAAS,OAAO;CAClB;AACF;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ACF;EAEA,WAAW,kBAAkB,IAAI,MAAM,uBAAuB;CAChE;CAEA,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAgB,oBACd,OACA,aACA,MACA,0BAA0B,MAClB;CACR,MAAM,YAAY,wBAAwB,WAAW;CAErD,IAAI,UAAU,SAAS,KAAK,SAAS,oBAAoB;EAGvD,MAAM,UAFU,KAAK,UAAU,KAAK,CAAC,CAAC,MAAM,GAAG,EAEzB,CAAC,CAAC,QAAQ,SAAS,SAAS;EAClD,OAAO,0BAA0B,oBAAoB,OAAO,IAAI;CAClE;CAEA,MAAM,UAAU,kCAAkC,OAAO,WAAW,MAAM,uBAAuB;CAEjG,IAAI,SAAS,mBACX,OAAO;CAMT,OAAO,QAAQ,QAAQ,aAAa,KAAK,CAAC,CAAC,QAAQ,QAAQ,UAAO;AACpE"}
|
package/dist/dev/find-by-path.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//! @decimalturn/toml-patch v3.
|
|
1
|
+
//! @decimalturn/toml-patch v3.2.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
|
|
2
2
|
import { hasItems, isDocument, isInlineItem, isKeyValue, isTable, isTableArray } from "./cst.js";
|
|
3
3
|
import { arraysEqual, stableStringify } from "./utils.js";
|
|
4
4
|
|
package/dist/dev/formatter.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//! @decimalturn/toml-patch v3.
|
|
1
|
+
//! @decimalturn/toml-patch v3.2.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
|
|
2
2
|
import { isInlineArray, isInlineItem, isInlineTable, isKeyValue, isTable, isTableArray } from "./cst.js";
|
|
3
3
|
import { getCommaSpace } from "./inline-comma-space.js";
|
|
4
4
|
import { getInlineContainerLayout, hasStructuralMultilineRows } from "./inline-format.js";
|
|
@@ -31,27 +31,27 @@ function formatTopLevel(document, format) {
|
|
|
31
31
|
remove(document, document, node);
|
|
32
32
|
if (isInlineTable(node.value)) {
|
|
33
33
|
if (node.value.items.length === 0) insert(document, document, generateTable(node.key.value));
|
|
34
|
-
else insert(document, document, formatTable(node, format.bracketSpacing));
|
|
35
|
-
} else formatTableArray(node, format.bracketSpacing).forEach((table_array) => {
|
|
34
|
+
else insert(document, document, formatTable(node, format.bracketSpacing, format.escapeSequenceUpperCase));
|
|
35
|
+
} else formatTableArray(node, format.bracketSpacing, format.escapeSequenceUpperCase).forEach((table_array) => {
|
|
36
36
|
insert(document, document, table_array);
|
|
37
37
|
});
|
|
38
38
|
});
|
|
39
39
|
applyWrites(document);
|
|
40
40
|
return document;
|
|
41
41
|
}
|
|
42
|
-
function formatTable(key_value, bracketSpacing) {
|
|
43
|
-
const table = generateTable(key_value.key.value);
|
|
42
|
+
function formatTable(key_value, bracketSpacing, escapeSequenceUpperCase) {
|
|
43
|
+
const table = generateTable(key_value.key.value, escapeSequenceUpperCase);
|
|
44
44
|
markStringifyRoot(table);
|
|
45
45
|
for (const item of key_value.value.items) insert(table, table, item.item, void 0, void 0, void 0, void 0, true);
|
|
46
46
|
applyWrites(table);
|
|
47
47
|
normalizeGeneratedInlineRows(table, 1, bracketSpacing);
|
|
48
48
|
return table;
|
|
49
49
|
}
|
|
50
|
-
function formatTableArray(key_value, bracketSpacing) {
|
|
50
|
+
function formatTableArray(key_value, bracketSpacing, escapeSequenceUpperCase) {
|
|
51
51
|
const root = generateDocument();
|
|
52
52
|
markStringifyRoot(root);
|
|
53
53
|
for (const inline_array_item of key_value.value.items) {
|
|
54
|
-
const table_array = generateTableArray(key_value.key.value);
|
|
54
|
+
const table_array = generateTableArray(key_value.key.value, escapeSequenceUpperCase);
|
|
55
55
|
insert(root, root, table_array);
|
|
56
56
|
for (const inline_table_item of inline_array_item.item.items) insert(root, table_array, inline_table_item.item, void 0, void 0, void 0, void 0, true);
|
|
57
57
|
}
|
|
@@ -229,7 +229,7 @@ function formatNestedTablesMultiline(document, format) {
|
|
|
229
229
|
const additionalTables = [];
|
|
230
230
|
for (const item of document.items) if (isKeyValue(item) && isInlineTable(item.value)) {
|
|
231
231
|
if (calculateTableDepth(item.key.value) < format.inlineTableStart) {
|
|
232
|
-
const table = formatTable(item, format.bracketSpacing);
|
|
232
|
+
const table = formatTable(item, format.bracketSpacing, format.escapeSequenceUpperCase);
|
|
233
233
|
remove(document, document, item);
|
|
234
234
|
insert(document, document, table);
|
|
235
235
|
processTableForNestedInlines(table, additionalTables, format);
|
|
@@ -263,7 +263,7 @@ function processTableForNestedInlines(table, additionalTables, format) {
|
|
|
263
263
|
}
|
|
264
264
|
}
|
|
265
265
|
for (const { item, nestedTableKey } of toExtract) {
|
|
266
|
-
const separateTable = generateTable(nestedTableKey);
|
|
266
|
+
const separateTable = generateTable(nestedTableKey, format.escapeSequenceUpperCase);
|
|
267
267
|
markStringifyRoot(separateTable);
|
|
268
268
|
const inlineTable = item.value;
|
|
269
269
|
for (const inlineItem of inlineTable.items) insert(separateTable, separateTable, inlineItem.item);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formatter.js","names":[],"sources":["../../src/formatter.ts"],"sourcesContent":["import {\n KeyValue,\n Table,\n InlineTable,\n TableArray,\n InlineArray,\n isInlineTable,\n isInlineArray,\n isKeyValue,\n isInlineItem,\n isTable,\n isTableArray,\n Document,\n Block,\n TreeNode\n} from './cst';\nimport { generateTable, generateDocument, generateTableArray } from './generate';\nimport { insert, remove, applyWrites, shiftNode, markStringifyRoot } from './writer';\nimport { TomlFormat } from './toml-format';\nimport { getInlineContainerLayout, hasStructuralMultilineRows } from './inline-format';\nimport { getCommaSpace } from './inline-comma-space';\n\n// Helper function to detect if an InlineArray originally had trailing commas\nexport function arrayHadTrailingCommas(node: TreeNode): boolean {\n if (!isInlineArray(node)) return false;\n if (node.items.length === 0) return false;\n // Check if the last item has a trailing comma\n const lastItem = node.items[node.items.length - 1];\n return lastItem.comma === true;\n}\n\n// Helper function to detect if an InlineTable originally had trailing commas\nexport function tableHadTrailingCommas(node: TreeNode): boolean {\n if (!isInlineTable(node)) return false;\n if (node.items.length === 0) return false;\n // Check if the last item has a trailing comma\n const lastItem = node.items[node.items.length - 1];\n return lastItem.comma === true;\n}\n\nexport function formatTopLevel(document: Document, format: TomlFormat): Document {\n\n // If inlineTableStart is 0, convert all top-level tables to inline tables\n if (format.inlineTableStart === 0) {\n return document;\n }\n\n const move_to_top_level = document.items.filter(item => {\n if (!isKeyValue(item)) return false;\n\n const is_inline_table = isInlineTable(item.value);\n const is_inline_array =\n isInlineArray(item.value) &&\n item.value.items.length > 0 &&\n item.value.items.every(i => isInlineTable(i.item));\n\n // Only move to top level if the depth is less than inlineTableStart\n if (is_inline_table || is_inline_array) {\n const depth = calculateTableDepth(item.key.value);\n return format.inlineTableStart === undefined || depth < format.inlineTableStart;\n }\n\n return false;\n }) as KeyValue[];\n\n move_to_top_level.forEach(node => {\n remove(document, document, node);\n\n if (isInlineTable(node.value)) {\n // Fast path: empty inline tables don't need the full formatTable\n // machinery (inline table copy, insert loop, applyWrites).\n if ((node.value as InlineTable).items.length === 0) {\n insert(document, document, generateTable(node.key.value));\n } else {\n insert(document, document, formatTable(node, format.bracketSpacing));\n }\n } else {\n formatTableArray(node, format.bracketSpacing).forEach(table_array => {\n insert(document, document, table_array);\n });\n }\n });\n\n applyWrites(document);\n return document;\n}\n\nfunction formatTable(key_value: KeyValue, bracketSpacing: boolean): Table {\n const table = generateTable(key_value.key.value);\n markStringifyRoot(table);\n\n for (const item of (key_value.value as InlineTable).items) {\n insert(table, table, item.item, undefined, undefined, undefined, undefined, true);\n }\n\n applyWrites(table);\n normalizeGeneratedInlineRows(table, 1, bracketSpacing);\n return table;\n}\n\nfunction formatTableArray(key_value: KeyValue, bracketSpacing: boolean): TableArray[] {\n const root = generateDocument();\n markStringifyRoot(root);\n\n for (const inline_array_item of (key_value.value as InlineArray).items) {\n const table_array = generateTableArray(key_value.key.value);\n insert(root, root, table_array);\n\n for (const inline_table_item of (inline_array_item.item as InlineTable).items) {\n insert(root, table_array, inline_table_item.item, undefined, undefined, undefined, undefined, true);\n }\n }\n\n applyWrites(root);\n for (const item of root.items) {\n if (isTable(item) || isTableArray(item)) normalizeGeneratedInlineRows(item, 1, bracketSpacing);\n }\n return root.items as TableArray[];\n}\n\n/**\n * Whether an inline container lays its items out one per row. A container\n * regenerated through a TOML round-trip carries no layout flag, so fall back to\n * the physical rows: a row on a later line than the previous item's end means\n * multiline. A compact container whose items merely SPAN several lines (because\n * one of them is a multiline value) stays compact — its closing bracket still\n * follows its last item.\n */\nfunction isMultilineInlineContainer(container: InlineArray | InlineTable): boolean {\n const layout = getInlineContainerLayout(container);\n return layout !== undefined ? layout : hasStructuralMultilineRows(container);\n}\n\n/**\n * Row indent for a container that is an array ELEMENT (no key of its own).\n * Keyless rows keep the historical minimum of two columns, matching\n * positionGeneratedNestedInlineTables so element rows and their closing\n * bracket stay aligned the same way no matter which path laid them out.\n */\nfunction elementIndentWidth(indentWidth: number): number {\n return Math.max(indentWidth, 2);\n}\n\n/**\n * Lays out a generated inline container so that its rows and closing bracket\n * line up with the key (or, for an array element, the element) that owns it:\n *\n * - a multiline container puts one row per line at `anchorColumn + indentWidth`\n * and its closing bracket at `anchorColumn`;\n * - a nested multiline container inside a row does the same, using that row's\n * key column as its own anchor.\n *\n * `anchorColumn` is the column of the owning key's start. It only has to be\n * correct for containers the generator built: containers parsed from an\n * existing document keep their own formatting, so callers must restrict this\n * to freshly generated/replaced subtrees.\n *\n * Returns whether a nested container's end position moved.\n */\nexport function normalizeInlineContainerRows(\n container: InlineArray | InlineTable,\n anchorColumn: number,\n indentWidth: number,\n bracketSpacing = true\n): boolean {\n const multiline = isMultilineInlineContainer(container);\n let nestedEndChanged = false;\n if (multiline) {\n const rowIndent = anchorColumn + indentWidth;\n for (const item of container.items) {\n shiftNode(item, { lines: 0, columns: rowIndent - item.loc.start.column });\n if (isInlineItem(item)) {\n if (isInlineArray(item.item) || isInlineTable(item.item)) {\n if (normalizeInlineContainerRows(item.item, item.item.loc.start.column, elementIndentWidth(indentWidth), bracketSpacing)) {\n item.loc.end = { ...item.item.loc.end };\n nestedEndChanged = true;\n }\n } else if (isKeyValue(item.item) &&\n (isInlineArray(item.item.value) || isInlineTable(item.item.value))) {\n // The nested container's rows hang off the ROW's key, so it has to\n // be laid out from the key's own column — not from the enclosing\n // container's indent (fuzz3 seed 18515).\n if (normalizeInlineContainerRows(item.item.value, item.item.loc.start.column, indentWidth, bracketSpacing)) {\n item.item.loc.end = { ...item.item.value.loc.end };\n item.loc.end = { ...item.item.loc.end };\n nestedEndChanged = true;\n }\n }\n }\n }\n container.loc.end.column = anchorColumn + 1;\n // The container's own closing bracket moved, so the enclosing item has to\n // re-sync its end from it (its comma is written at that end).\n nestedEndChanged = true;\n }\n\n for (const item of container.items) {\n if (!isInlineItem(item)) continue;\n if (isInlineArray(item.item) || isInlineTable(item.item)) {\n if (normalizeInlineContainerRows(item.item, item.item.loc.start.column, elementIndentWidth(indentWidth), bracketSpacing)) {\n item.loc.end = { ...item.item.loc.end };\n nestedEndChanged = true;\n }\n } else if (isKeyValue(item.item) &&\n (isInlineArray(item.item.value) || isInlineTable(item.item.value))) {\n const value = item.item.value;\n const anchorColumn = item.item.loc.start.column;\n const valueMultiline = isMultilineInlineContainer(value);\n if (normalizeInlineContainerRows(value, anchorColumn, indentWidth, bracketSpacing)) {\n // A MULTILINE nested value closes on its own row, level with the row's\n // key. A compact one closes right after its last item — that end was\n // already computed by its own pass, so snapping it to the key column\n // would place the closing bracket before the item it follows\n // (fuzz3 seed 14739).\n if (valueMultiline) value.loc.end.column = anchorColumn + 1;\n item.item.loc.end = { ...value.loc.end };\n item.loc.end = { ...item.item.loc.end };\n nestedEndChanged = true;\n }\n }\n }\n // A nested container that grew pushes its following siblings along: the\n // siblings were positioned against its OLD end, so the ones still sharing its\n // end row must be re-anchored to its new end before the container's own\n // closing bracket is placed from the last item.\n const commaSpace = getCommaSpace(container) ?? 2;\n for (let index = 1; index < container.items.length; index++) {\n const previous = container.items[index - 1];\n const next = container.items[index];\n if (previous.loc.end.line !== next.loc.start.line) continue;\n const targetColumn = previous.loc.end.column + (previous.comma ? commaSpace : 1);\n shiftNode(next, { lines: 0, columns: targetColumn - next.loc.start.column });\n }\n if (nestedEndChanged && !multiline && container.items.length > 0) {\n const lastItem = container.items[container.items.length - 1];\n container.loc.end = {\n line: lastItem.loc.end.line,\n column: lastItem.loc.end.column + (lastItem.comma ? 1 : 0) + (bracketSpacing ? 2 : 1)\n };\n }\n return nestedEndChanged;\n}\n\nexport function normalizeGeneratedInlineRows(\n block: Table | TableArray | KeyValue,\n indentWidth: number,\n bracketSpacing = true\n): void {\n // A root-level key-value is normalized like the rows of a table: its own key\n // column is the anchor the nested container hangs off.\n const rows: Block[] = isKeyValue(block) ? [block] : block.items;\n for (const item of rows) {\n if (!isKeyValue(item)) continue;\n if (isInlineArray(item.value) || isInlineTable(item.value)) {\n normalizeInlineContainerRows(item.value, item.loc.start.column, indentWidth, bracketSpacing);\n }\n }\n}\n\nexport function normalizeGeneratedInlineContainerRows(\n container: InlineArray | InlineTable,\n indentWidth: number\n): void {\n const normalize = (\n current: InlineArray | InlineTable,\n normalizeCurrent: boolean\n ): void => {\n if (normalizeCurrent) {\n delete (current as { range?: [number, number] }).range;\n const multiline = getInlineContainerLayout(current) === true ||\n hasStructuralMultilineRows(current);\n if (multiline) {\n const rowIndent = current.loc.start.column + indentWidth;\n for (const item of current.items) {\n shiftNode(item, { lines: 0, columns: rowIndent - item.loc.start.column });\n }\n current.loc.end.column = current.loc.start.column + 1;\n }\n }\n\n for (const item of current.items) {\n if (!isInlineItem(item)) continue;\n if (isInlineArray(item.item) || isInlineTable(item.item)) {\n normalize(item.item, isInlineArray(current) && isInlineTable(item.item));\n } else if (isKeyValue(item.item) &&\n (isInlineArray(item.item.value) || isInlineTable(item.item.value))) {\n normalize(item.item.value, false);\n }\n }\n };\n\n normalize(container, false);\n}\n\n/**\n * Updates a table's location end position after removing inline table items.\n * When inline table content is removed from a parent table, the parent table's \n * end position needs to be adjusted to reflect where the content actually ends.\n * \n * @param table - The table whose end position should be updated\n */\nexport function postInlineItemRemovalAdjustment(table: Table | TableArray): void {\n if (table.items.length > 0) {\n const lastItem = table.items[table.items.length - 1];\n table.loc.end.line = lastItem.loc.end.line;\n table.loc.end.column = lastItem.loc.end.column;\n } else {\n // If no items left, table ends at the header line\n table.loc.end.line = table.key.loc.end.line;\n table.loc.end.column = table.key.loc.end.column;\n }\n}\n\n/**\n * Calculates the nesting depth of a table based on its key path.\n * Root level tables (e.g., [table]) have depth 0.\n * First level nested tables (e.g., [table.nested]) have depth 1.\n * \n * @param keyPath - Array representing the table key path (e.g., ['table', 'nested'])\n * @returns The nesting depth (0 for root level, 1+ for nested levels)\n */\nexport function calculateTableDepth(keyPath: string[]): number {\n return Math.max(0, keyPath.length - 1);\n}\n\n/**\n * Converts nested inline tables to separate table sections based on the inlineTableStart depth setting.\n * This function recursively processes all tables in the document and extracts inline tables that are\n * at a depth less than the inlineTableStart threshold.\n */\nexport function formatNestedTablesMultiline(document: Document, format: TomlFormat): Document {\n // If inlineTableStart is undefined, use the default behavior (no conversion)\n // If inlineTableStart is 0, all should be inline (no conversion)\n if (format.inlineTableStart === undefined || format.inlineTableStart === 0) {\n return document;\n }\n\n const additionalTables: { table: Table; parent: Table | TableArray }[] = [];\n \n // Process all existing tables for nested inline tables\n for (const item of document.items) {\n if (isKeyValue(item) && isInlineTable(item.value)) {\n // This is a top-level inline table (depth 0)\n const depth = calculateTableDepth(item.key.value);\n if (depth < format.inlineTableStart) {\n // Convert to a separate table\n const table = formatTable(item, format.bracketSpacing);\n remove(document, document, item);\n insert(document, document, table);\n \n processTableForNestedInlines(table, additionalTables, format);\n }\n } else if (item.type === 'Table') {\n processTableForNestedInlines(item as Table, additionalTables, format);\n } else if (isTableArray(item)) {\n processTableForNestedInlines(item, additionalTables, format);\n }\n }\n \n // Insert each extracted table immediately after its parent block, preserving\n // the parent-child positional relationship. A flat append at the document\n // end (the previous behaviour) misplaced a sub-table of an earlier entry —\n // e.g. `[tp6.k41]` (a sub-table of `[[tp6]]` entry 0) landed after `[[tp6]]`\n // entry 1, reassigning `k41` to the wrong entry. `additionalTables` is in\n // depth-first pre-order (a child is pushed before its own children), so\n // inserting in order with a per-parent counter keeps every sub-table after\n // its parent and before the parent's next sibling.\n const insertedAfter = new Map<Table | TableArray, number>();\n for (const { table, parent } of additionalTables) {\n const index = document.items.indexOf(parent);\n const offset = (insertedAfter.get(parent) ?? 0) + 1;\n insertedAfter.set(parent, offset);\n insert(document, document, table, index + offset);\n }\n\n applyWrites(document);\n return document;\n}\n\n/**\n * Recursively processes a table for nested inline tables and extracts them as separate tables\n * when they are at a depth less than the inlineTableStart threshold.\n */\nfunction processTableForNestedInlines(table: Table | TableArray, additionalTables: { table: Table; parent: Table | TableArray }[], format: TomlFormat): void {\n // Collect all inline tables that need extraction, then process in forward order\n // to preserve the original key order in the output.\n const toExtract: { item: KeyValue; nestedTableKey: string[] }[] = [];\n for (let i = 0; i < table.items.length; i++) {\n const item = table.items[i];\n if (isKeyValue(item) && isInlineTable(item.value)) {\n const nestedTableKey = [...table.key.item.value, ...item.key.value];\n const depth = calculateTableDepth(nestedTableKey);\n if (depth < (format.inlineTableStart ?? 1)) {\n toExtract.push({ item, nestedTableKey });\n }\n }\n }\n\n // Process in forward order. Each item reference captured above is stable\n // even after previous iterations call remove() — the KeyValue node itself\n // stays valid regardless of index shifts.\n for (const { item, nestedTableKey } of toExtract) {\n const separateTable = generateTable(nestedTableKey);\n markStringifyRoot(separateTable);\n const inlineTable = item.value as InlineTable;\n\n for (const inlineItem of inlineTable.items) {\n insert(separateTable, separateTable, inlineItem.item);\n }\n // Finalize the separateTable's internal offsets and recalculate its span\n // so it can be safely inserted into the document later.\n applyWrites(separateTable);\n\n remove(table, table, item);\n postInlineItemRemovalAdjustment(table);\n\n additionalTables.push({ table: separateTable, parent: table });\n\n processTableForNestedInlines(separateTable, additionalTables, format);\n }\n // Apply removal offsets accumulated on this table so remaining items\n // (if any) are shifted to the correct positions.\n if (toExtract.length > 0) {\n applyWrites(table);\n }\n}\n\nexport function formatEmptyLines(document: Document): Document {\n let shift = 0;\n let previous = 0;\n for (const item of document.items) {\n if (previous === 0 && item.loc.start.line > 1) {\n // Remove leading newlines\n shift = 1 - item.loc.start.line;\n } else if (item.loc.start.line + shift > previous + 2) {\n shift += previous + 2 - (item.loc.start.line + shift);\n }\n\n shiftNode(item, {\n lines: shift,\n columns: 0\n });\n previous = item.loc.end.line;\n }\n\n return document;\n}\n"],"mappings":";;;;;;;;AAuBA,SAAgB,uBAAuB,MAAyB;CAC9D,IAAI,CAAC,cAAc,IAAI,GAAG,OAAO;CACjC,IAAI,KAAK,MAAM,WAAW,GAAG,OAAO;CAGpC,OADiB,KAAK,MAAM,KAAK,MAAM,SAAS,EACjC,CAAC,UAAU;AAC5B;AAGA,SAAgB,uBAAuB,MAAyB;CAC9D,IAAI,CAAC,cAAc,IAAI,GAAG,OAAO;CACjC,IAAI,KAAK,MAAM,WAAW,GAAG,OAAO;CAGpC,OADiB,KAAK,MAAM,KAAK,MAAM,SAAS,EACjC,CAAC,UAAU;AAC5B;AAEA,SAAgB,eAAe,UAAoB,QAA8B;CAG/E,IAAI,OAAO,qBAAqB,GAC9B,OAAO;CAqBT,AAlB0B,SAAS,MAAM,QAAO,SAAQ;EACtD,IAAI,CAAC,WAAW,IAAI,GAAG,OAAO;EAE9B,MAAM,kBAAkB,cAAc,KAAK,KAAK;EAChD,MAAM,kBACJ,cAAc,KAAK,KAAK,KACxB,KAAK,MAAM,MAAM,SAAS,KAC1B,KAAK,MAAM,MAAM,OAAM,MAAK,cAAc,EAAE,IAAI,CAAC;EAGnD,IAAI,mBAAmB,iBAAiB;GACtC,MAAM,QAAQ,oBAAoB,KAAK,IAAI,KAAK;GAChD,OAAO,OAAO,qBAAqB,UAAa,QAAQ,OAAO;EACjE;EAEA,OAAO;CACT,CAEgB,CAAC,CAAC,SAAQ,SAAQ;EAChC,OAAO,UAAU,UAAU,IAAI;EAE/B,IAA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AG;GACjD,MAAM,iBAAiB,CAAC,GAAG,MAAM,IAAI,KAAK,OAAO,GAAG,KAAK,IAAI,KAAK;GAElE,IADc,oBAAoB,cAC1B,KAAK,OAAO,oBAAoB,IACtC,UAAU,KAAK;IAAE;IAAM;GAAe,CAAC;EAE3C;CACF;CAKA,KAAK,MAAM,EAAE,MAAM,oBAAoB,WAAW;EAChD,MAAM,gBAAgB,cAAc,cAAc;EAClD,kBAAkB,aAAa;EAC/B,MAAM,cAAc,KAAK;EAEzB,KAAK,MAAM,cAAc,YAAY,OACnC,OAAO,eAAe,eAAe,WAAW,IAAI;EAItD,YAAY,aAAa;EAEzB,OAAO,OAAO,OAAO,IAAI;EACzB,gCAAgC,KAAK;EAErC,iBAAiB,KAAK;GAAE,OAAO;GAAe,QAAQ;EAAM,CAAC;EAE7D,6BAA6B,eAAe,kBAAkB,MAAM;CACtE;CAGA,IAAI,UAAU,SAAS,GACrB,YAAY,KAAK;AAErB;AAEA,SAAgB,iBAAiB,UAA8B;CAC7D,IAAI,QAAQ;CACZ,IAAI,WAAW;CACf,KAAK,MAAM,QAAQ,SAAS,OAAO;EACjC,IAAI,aAAa,KAAK,KAAK,IAAI,MAAM,OAAO,GAE1C,QAAQ,IAAI,KAAK,IAAI,MAAM;OACtB,IAAI,KAAK,IAAI,MAAM,OAAO,QAAQ,WAAW,GAClD,SAAS,WAAW,KAAK,KAAK,IAAI,MAAM,OAAO;EAGjD,UAAU,MAAM;GACd,OAAO;GACP,SAAS;EACX,CAAC;EACD,WAAW,KAAK,IAAI,IAAI;CAC1B;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"formatter.js","names":[],"sources":["../../src/formatter.ts"],"sourcesContent":["import {\n KeyValue,\n Table,\n InlineTable,\n TableArray,\n InlineArray,\n isInlineTable,\n isInlineArray,\n isKeyValue,\n isInlineItem,\n isTable,\n isTableArray,\n Document,\n Block,\n TreeNode\n} from './cst';\nimport { generateTable, generateDocument, generateTableArray } from './generate';\nimport { insert, remove, applyWrites, shiftNode, markStringifyRoot } from './writer';\nimport { TomlFormat } from './toml-format';\nimport { getInlineContainerLayout, hasStructuralMultilineRows } from './inline-format';\nimport { getCommaSpace } from './inline-comma-space';\n\n// Helper function to detect if an InlineArray originally had trailing commas\nexport function arrayHadTrailingCommas(node: TreeNode): boolean {\n if (!isInlineArray(node)) return false;\n if (node.items.length === 0) return false;\n // Check if the last item has a trailing comma\n const lastItem = node.items[node.items.length - 1];\n return lastItem.comma === true;\n}\n\n// Helper function to detect if an InlineTable originally had trailing commas\nexport function tableHadTrailingCommas(node: TreeNode): boolean {\n if (!isInlineTable(node)) return false;\n if (node.items.length === 0) return false;\n // Check if the last item has a trailing comma\n const lastItem = node.items[node.items.length - 1];\n return lastItem.comma === true;\n}\n\nexport function formatTopLevel(document: Document, format: TomlFormat): Document {\n\n // If inlineTableStart is 0, convert all top-level tables to inline tables\n if (format.inlineTableStart === 0) {\n return document;\n }\n\n const move_to_top_level = document.items.filter(item => {\n if (!isKeyValue(item)) return false;\n\n const is_inline_table = isInlineTable(item.value);\n const is_inline_array =\n isInlineArray(item.value) &&\n item.value.items.length > 0 &&\n item.value.items.every(i => isInlineTable(i.item));\n\n // Only move to top level if the depth is less than inlineTableStart\n if (is_inline_table || is_inline_array) {\n const depth = calculateTableDepth(item.key.value);\n return format.inlineTableStart === undefined || depth < format.inlineTableStart;\n }\n\n return false;\n }) as KeyValue[];\n\n move_to_top_level.forEach(node => {\n remove(document, document, node);\n\n if (isInlineTable(node.value)) {\n // Fast path: empty inline tables don't need the full formatTable\n // machinery (inline table copy, insert loop, applyWrites).\n if ((node.value as InlineTable).items.length === 0) {\n insert(document, document, generateTable(node.key.value));\n } else {\n insert(document, document, formatTable(node, format.bracketSpacing, format.escapeSequenceUpperCase));\n }\n } else {\n formatTableArray(node, format.bracketSpacing, format.escapeSequenceUpperCase).forEach(table_array => {\n insert(document, document, table_array);\n });\n }\n });\n\n applyWrites(document);\n return document;\n}\n\nfunction formatTable(key_value: KeyValue, bracketSpacing: boolean, escapeSequenceUpperCase: boolean): Table {\n const table = generateTable(key_value.key.value, escapeSequenceUpperCase);\n markStringifyRoot(table);\n\n for (const item of (key_value.value as InlineTable).items) {\n insert(table, table, item.item, undefined, undefined, undefined, undefined, true);\n }\n\n applyWrites(table);\n normalizeGeneratedInlineRows(table, 1, bracketSpacing);\n return table;\n}\n\nfunction formatTableArray(key_value: KeyValue, bracketSpacing: boolean, escapeSequenceUpperCase: boolean): TableArray[] {\n const root = generateDocument();\n markStringifyRoot(root);\n\n for (const inline_array_item of (key_value.value as InlineArray).items) {\n const table_array = generateTableArray(key_value.key.value, escapeSequenceUpperCase);\n insert(root, root, table_array);\n\n for (const inline_table_item of (inline_array_item.item as InlineTable).items) {\n insert(root, table_array, inline_table_item.item, undefined, undefined, undefined, undefined, true);\n }\n }\n\n applyWrites(root);\n for (const item of root.items) {\n if (isTable(item) || isTableArray(item)) normalizeGeneratedInlineRows(item, 1, bracketSpacing);\n }\n return root.items as TableArray[];\n}\n\n/**\n * Whether an inline container lays its items out one per row. A container\n * regenerated through a TOML round-trip carries no layout flag, so fall back to\n * the physical rows: a row on a later line than the previous item's end means\n * multiline. A compact container whose items merely SPAN several lines (because\n * one of them is a multiline value) stays compact — its closing bracket still\n * follows its last item.\n */\nfunction isMultilineInlineContainer(container: InlineArray | InlineTable): boolean {\n const layout = getInlineContainerLayout(container);\n return layout !== undefined ? layout : hasStructuralMultilineRows(container);\n}\n\n/**\n * Row indent for a container that is an array ELEMENT (no key of its own).\n * Keyless rows keep the historical minimum of two columns, matching\n * positionGeneratedNestedInlineTables so element rows and their closing\n * bracket stay aligned the same way no matter which path laid them out.\n */\nfunction elementIndentWidth(indentWidth: number): number {\n return Math.max(indentWidth, 2);\n}\n\n/**\n * Lays out a generated inline container so that its rows and closing bracket\n * line up with the key (or, for an array element, the element) that owns it:\n *\n * - a multiline container puts one row per line at `anchorColumn + indentWidth`\n * and its closing bracket at `anchorColumn`;\n * - a nested multiline container inside a row does the same, using that row's\n * key column as its own anchor.\n *\n * `anchorColumn` is the column of the owning key's start. It only has to be\n * correct for containers the generator built: containers parsed from an\n * existing document keep their own formatting, so callers must restrict this\n * to freshly generated/replaced subtrees.\n *\n * Returns whether a nested container's end position moved.\n */\nexport function normalizeInlineContainerRows(\n container: InlineArray | InlineTable,\n anchorColumn: number,\n indentWidth: number,\n bracketSpacing = true\n): boolean {\n const multiline = isMultilineInlineContainer(container);\n let nestedEndChanged = false;\n if (multiline) {\n const rowIndent = anchorColumn + indentWidth;\n for (const item of container.items) {\n shiftNode(item, { lines: 0, columns: rowIndent - item.loc.start.column });\n if (isInlineItem(item)) {\n if (isInlineArray(item.item) || isInlineTable(item.item)) {\n if (normalizeInlineContainerRows(item.item, item.item.loc.start.column, elementIndentWidth(indentWidth), bracketSpacing)) {\n item.loc.end = { ...item.item.loc.end };\n nestedEndChanged = true;\n }\n } else if (isKeyValue(item.item) &&\n (isInlineArray(item.item.value) || isInlineTable(item.item.value))) {\n // The nested container's rows hang off the ROW's key, so it has to\n // be laid out from the key's own column — not from the enclosing\n // container's indent (fuzz3 seed 18515).\n if (normalizeInlineContainerRows(item.item.value, item.item.loc.start.column, indentWidth, bracketSpacing)) {\n item.item.loc.end = { ...item.item.value.loc.end };\n item.loc.end = { ...item.item.loc.end };\n nestedEndChanged = true;\n }\n }\n }\n }\n container.loc.end.column = anchorColumn + 1;\n // The container's own closing bracket moved, so the enclosing item has to\n // re-sync its end from it (its comma is written at that end).\n nestedEndChanged = true;\n }\n\n for (const item of container.items) {\n if (!isInlineItem(item)) continue;\n if (isInlineArray(item.item) || isInlineTable(item.item)) {\n if (normalizeInlineContainerRows(item.item, item.item.loc.start.column, elementIndentWidth(indentWidth), bracketSpacing)) {\n item.loc.end = { ...item.item.loc.end };\n nestedEndChanged = true;\n }\n } else if (isKeyValue(item.item) &&\n (isInlineArray(item.item.value) || isInlineTable(item.item.value))) {\n const value = item.item.value;\n const anchorColumn = item.item.loc.start.column;\n const valueMultiline = isMultilineInlineContainer(value);\n if (normalizeInlineContainerRows(value, anchorColumn, indentWidth, bracketSpacing)) {\n // A MULTILINE nested value closes on its own row, level with the row's\n // key. A compact one closes right after its last item — that end was\n // already computed by its own pass, so snapping it to the key column\n // would place the closing bracket before the item it follows\n // (fuzz3 seed 14739).\n if (valueMultiline) value.loc.end.column = anchorColumn + 1;\n item.item.loc.end = { ...value.loc.end };\n item.loc.end = { ...item.item.loc.end };\n nestedEndChanged = true;\n }\n }\n }\n // A nested container that grew pushes its following siblings along: the\n // siblings were positioned against its OLD end, so the ones still sharing its\n // end row must be re-anchored to its new end before the container's own\n // closing bracket is placed from the last item.\n const commaSpace = getCommaSpace(container) ?? 2;\n for (let index = 1; index < container.items.length; index++) {\n const previous = container.items[index - 1];\n const next = container.items[index];\n if (previous.loc.end.line !== next.loc.start.line) continue;\n const targetColumn = previous.loc.end.column + (previous.comma ? commaSpace : 1);\n shiftNode(next, { lines: 0, columns: targetColumn - next.loc.start.column });\n }\n if (nestedEndChanged && !multiline && container.items.length > 0) {\n const lastItem = container.items[container.items.length - 1];\n container.loc.end = {\n line: lastItem.loc.end.line,\n column: lastItem.loc.end.column + (lastItem.comma ? 1 : 0) + (bracketSpacing ? 2 : 1)\n };\n }\n return nestedEndChanged;\n}\n\nexport function normalizeGeneratedInlineRows(\n block: Table | TableArray | KeyValue,\n indentWidth: number,\n bracketSpacing = true\n): void {\n // A root-level key-value is normalized like the rows of a table: its own key\n // column is the anchor the nested container hangs off.\n const rows: Block[] = isKeyValue(block) ? [block] : block.items;\n for (const item of rows) {\n if (!isKeyValue(item)) continue;\n if (isInlineArray(item.value) || isInlineTable(item.value)) {\n normalizeInlineContainerRows(item.value, item.loc.start.column, indentWidth, bracketSpacing);\n }\n }\n}\n\nexport function normalizeGeneratedInlineContainerRows(\n container: InlineArray | InlineTable,\n indentWidth: number\n): void {\n const normalize = (\n current: InlineArray | InlineTable,\n normalizeCurrent: boolean\n ): void => {\n if (normalizeCurrent) {\n delete (current as { range?: [number, number] }).range;\n const multiline = getInlineContainerLayout(current) === true ||\n hasStructuralMultilineRows(current);\n if (multiline) {\n const rowIndent = current.loc.start.column + indentWidth;\n for (const item of current.items) {\n shiftNode(item, { lines: 0, columns: rowIndent - item.loc.start.column });\n }\n current.loc.end.column = current.loc.start.column + 1;\n }\n }\n\n for (const item of current.items) {\n if (!isInlineItem(item)) continue;\n if (isInlineArray(item.item) || isInlineTable(item.item)) {\n normalize(item.item, isInlineArray(current) && isInlineTable(item.item));\n } else if (isKeyValue(item.item) &&\n (isInlineArray(item.item.value) || isInlineTable(item.item.value))) {\n normalize(item.item.value, false);\n }\n }\n };\n\n normalize(container, false);\n}\n\n/**\n * Updates a table's location end position after removing inline table items.\n * When inline table content is removed from a parent table, the parent table's \n * end position needs to be adjusted to reflect where the content actually ends.\n * \n * @param table - The table whose end position should be updated\n */\nexport function postInlineItemRemovalAdjustment(table: Table | TableArray): void {\n if (table.items.length > 0) {\n const lastItem = table.items[table.items.length - 1];\n table.loc.end.line = lastItem.loc.end.line;\n table.loc.end.column = lastItem.loc.end.column;\n } else {\n // If no items left, table ends at the header line\n table.loc.end.line = table.key.loc.end.line;\n table.loc.end.column = table.key.loc.end.column;\n }\n}\n\n/**\n * Calculates the nesting depth of a table based on its key path.\n * Root level tables (e.g., [table]) have depth 0.\n * First level nested tables (e.g., [table.nested]) have depth 1.\n * \n * @param keyPath - Array representing the table key path (e.g., ['table', 'nested'])\n * @returns The nesting depth (0 for root level, 1+ for nested levels)\n */\nexport function calculateTableDepth(keyPath: string[]): number {\n return Math.max(0, keyPath.length - 1);\n}\n\n/**\n * Converts nested inline tables to separate table sections based on the inlineTableStart depth setting.\n * This function recursively processes all tables in the document and extracts inline tables that are\n * at a depth less than the inlineTableStart threshold.\n */\nexport function formatNestedTablesMultiline(document: Document, format: TomlFormat): Document {\n // If inlineTableStart is undefined, use the default behavior (no conversion)\n // If inlineTableStart is 0, all should be inline (no conversion)\n if (format.inlineTableStart === undefined || format.inlineTableStart === 0) {\n return document;\n }\n\n const additionalTables: { table: Table; parent: Table | TableArray }[] = [];\n \n // Process all existing tables for nested inline tables\n for (const item of document.items) {\n if (isKeyValue(item) && isInlineTable(item.value)) {\n // This is a top-level inline table (depth 0)\n const depth = calculateTableDepth(item.key.value);\n if (depth < format.inlineTableStart) {\n // Convert to a separate table\n const table = formatTable(item, format.bracketSpacing, format.escapeSequenceUpperCase);\n remove(document, document, item);\n insert(document, document, table);\n \n processTableForNestedInlines(table, additionalTables, format);\n }\n } else if (item.type === 'Table') {\n processTableForNestedInlines(item as Table, additionalTables, format);\n } else if (isTableArray(item)) {\n processTableForNestedInlines(item, additionalTables, format);\n }\n }\n \n // Insert each extracted table immediately after its parent block, preserving\n // the parent-child positional relationship. A flat append at the document\n // end (the previous behaviour) misplaced a sub-table of an earlier entry —\n // e.g. `[tp6.k41]` (a sub-table of `[[tp6]]` entry 0) landed after `[[tp6]]`\n // entry 1, reassigning `k41` to the wrong entry. `additionalTables` is in\n // depth-first pre-order (a child is pushed before its own children), so\n // inserting in order with a per-parent counter keeps every sub-table after\n // its parent and before the parent's next sibling.\n const insertedAfter = new Map<Table | TableArray, number>();\n for (const { table, parent } of additionalTables) {\n const index = document.items.indexOf(parent);\n const offset = (insertedAfter.get(parent) ?? 0) + 1;\n insertedAfter.set(parent, offset);\n insert(document, document, table, index + offset);\n }\n\n applyWrites(document);\n return document;\n}\n\n/**\n * Recursively processes a table for nested inline tables and extracts them as separate tables\n * when they are at a depth less than the inlineTableStart threshold.\n */\nfunction processTableForNestedInlines(table: Table | TableArray, additionalTables: { table: Table; parent: Table | TableArray }[], format: TomlFormat): void {\n // Collect all inline tables that need extraction, then process in forward order\n // to preserve the original key order in the output.\n const toExtract: { item: KeyValue; nestedTableKey: string[] }[] = [];\n for (let i = 0; i < table.items.length; i++) {\n const item = table.items[i];\n if (isKeyValue(item) && isInlineTable(item.value)) {\n const nestedTableKey = [...table.key.item.value, ...item.key.value];\n const depth = calculateTableDepth(nestedTableKey);\n if (depth < (format.inlineTableStart ?? 1)) {\n toExtract.push({ item, nestedTableKey });\n }\n }\n }\n\n // Process in forward order. Each item reference captured above is stable\n // even after previous iterations call remove() — the KeyValue node itself\n // stays valid regardless of index shifts.\n for (const { item, nestedTableKey } of toExtract) {\n const separateTable = generateTable(nestedTableKey, format.escapeSequenceUpperCase);\n markStringifyRoot(separateTable);\n const inlineTable = item.value as InlineTable;\n\n for (const inlineItem of inlineTable.items) {\n insert(separateTable, separateTable, inlineItem.item);\n }\n // Finalize the separateTable's internal offsets and recalculate its span\n // so it can be safely inserted into the document later.\n applyWrites(separateTable);\n\n remove(table, table, item);\n postInlineItemRemovalAdjustment(table);\n\n additionalTables.push({ table: separateTable, parent: table });\n\n processTableForNestedInlines(separateTable, additionalTables, format);\n }\n // Apply removal offsets accumulated on this table so remaining items\n // (if any) are shifted to the correct positions.\n if (toExtract.length > 0) {\n applyWrites(table);\n }\n}\n\nexport function formatEmptyLines(document: Document): Document {\n let shift = 0;\n let previous = 0;\n for (const item of document.items) {\n if (previous === 0 && item.loc.start.line > 1) {\n // Remove leading newlines\n shift = 1 - item.loc.start.line;\n } else if (item.loc.start.line + shift > previous + 2) {\n shift += previous + 2 - (item.loc.start.line + shift);\n }\n\n shiftNode(item, {\n lines: shift,\n columns: 0\n });\n previous = item.loc.end.line;\n }\n\n return document;\n}\n"],"mappings":";;;;;;;;AAuBA,SAAgB,uBAAuB,MAAyB;CAC9D,IAAI,CAAC,cAAc,IAAI,GAAG,OAAO;CACjC,IAAI,KAAK,MAAM,WAAW,GAAG,OAAO;CAGpC,OADiB,KAAK,MAAM,KAAK,MAAM,SAAS,EACjC,CAAC,UAAU;AAC5B;AAGA,SAAgB,uBAAuB,MAAyB;CAC9D,IAAI,CAAC,cAAc,IAAI,GAAG,OAAO;CACjC,IAAI,KAAK,MAAM,WAAW,GAAG,OAAO;CAGpC,OADiB,KAAK,MAAM,KAAK,MAAM,SAAS,EACjC,CAAC,UAAU;AAC5B;AAEA,S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