@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.
Files changed (56) hide show
  1. package/dist/dev/comment-alignment.js +1 -1
  2. package/dist/dev/comment-ownership.js +1 -1
  3. package/dist/dev/cst-source.js +1 -1
  4. package/dist/dev/cst.js +11 -2
  5. package/dist/dev/cst.js.map +1 -1
  6. package/dist/dev/cursor.js +1 -1
  7. package/dist/dev/date-format.js +1 -1
  8. package/dist/dev/decode-utf8.js +1 -1
  9. package/dist/dev/diff-lite.js +123 -0
  10. package/dist/dev/diff-lite.js.map +1 -0
  11. package/dist/dev/diff.js +4 -8
  12. package/dist/dev/diff.js.map +1 -1
  13. package/dist/dev/encode-lite.js +193 -0
  14. package/dist/dev/encode-lite.js.map +1 -0
  15. package/dist/dev/escape-preference.js +33 -11
  16. package/dist/dev/escape-preference.js.map +1 -1
  17. package/dist/dev/find-by-path.js +1 -1
  18. package/dist/dev/formatter.js +9 -9
  19. package/dist/dev/formatter.js.map +1 -1
  20. package/dist/dev/generate.js +53 -39
  21. package/dist/dev/generate.js.map +1 -1
  22. package/dist/dev/inline-comma-space.js +1 -1
  23. package/dist/dev/inline-format.js +1 -1
  24. package/dist/dev/inline-layout.js +1 -1
  25. package/dist/dev/line-ending-backslash.js +1 -1
  26. package/dist/dev/literal-string.js +46 -0
  27. package/dist/dev/literal-string.js.map +1 -0
  28. package/dist/dev/location.js +1 -1
  29. package/dist/dev/parse-error.js +1 -1
  30. package/dist/dev/parse-js.js +49 -6
  31. package/dist/dev/parse-js.js.map +1 -1
  32. package/dist/dev/parse-string.js +1 -1
  33. package/dist/dev/parse-toml.js +1 -1
  34. package/dist/dev/patch-lite.js +4 -0
  35. package/dist/dev/patch-lite2.js +96 -0
  36. package/dist/dev/patch-lite2.js.map +1 -0
  37. package/dist/dev/patch.js +150 -38
  38. package/dist/dev/patch.js.map +1 -1
  39. package/dist/dev/smol-toml-date.js +61 -0
  40. package/dist/dev/smol-toml-date.js.map +1 -0
  41. package/dist/dev/to-js.js +1 -1
  42. package/dist/dev/to-toml.js +1 -1
  43. package/dist/dev/tokenizer.js +1 -1
  44. package/dist/dev/toml-document.js +1 -1
  45. package/dist/dev/toml-format.js +58 -6
  46. package/dist/dev/toml-format.js.map +1 -1
  47. package/dist/dev/toml-patch.js +1 -1
  48. package/dist/dev/traverse.js +1 -1
  49. package/dist/dev/truncate.js +1 -1
  50. package/dist/dev/update-order.js +1 -1
  51. package/dist/dev/utils.js +26 -5
  52. package/dist/dev/utils.js.map +1 -1
  53. package/dist/dev/writer.js +1 -1
  54. package/dist/patch-lite.d.ts +18 -0
  55. package/dist/toml-patch.d.ts +7 -1
  56. package/package.json +6 -1
@@ -0,0 +1,61 @@
1
+ //! @decimalturn/toml-patch v3.2.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
+ import { LocalDate, LocalDateTime, LocalTime, OffsetDateTime } from "./date-format.js";
3
+
4
+ //#region src/smol-toml-date.ts
5
+ /*!
6
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
7
+ * SPDX-License-Identifier: BSD-3-Clause
8
+ *
9
+ * Redistribution and use in source and binary forms, with or without
10
+ * modification, are permitted provided that the following conditions are met:
11
+ *
12
+ * 1. Redistributions of source code must retain the above copyright notice, this
13
+ * list of conditions and the following disclaimer.
14
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
15
+ * this list of conditions and the following disclaimer in the
16
+ * documentation and/or other materials provided with the distribution.
17
+ * 3. Neither the name of the copyright holder nor the names of its contributors
18
+ * may be used to endorse or promote products derived from this software without
19
+ * specific prior written permission.
20
+ *
21
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
22
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
25
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
+ */
32
+ /**
33
+ * True when `value` is a smol-toml `TomlDate` instance.
34
+ *
35
+ * Duck-typed rather than `instanceof TomlDate`: the caller's object was parsed
36
+ * by the smol-toml package, whose `TomlDate` is a different class object than
37
+ * this vendored copy, so `instanceof` would never match. The `isDate` /
38
+ * `isTime` / `isDateTime` methods only exist on smol-toml's date class, which
39
+ * is what distinguishes it from toml-patch's own date classes.
40
+ */
41
+ function isSmolTomlDate(value) {
42
+ return value instanceof Date && typeof value.isDate === "function" && typeof value.isTime === "function" && typeof value.isDateTime === "function";
43
+ }
44
+ /**
45
+ * Converts a smol-toml `TomlDate` into the equivalent toml-patch date class.
46
+ *
47
+ * smol-toml always renders a zero-fraction time or datetime with a trailing
48
+ * `.000`, while toml-patch omits it. Stripping it gives the canonical form
49
+ * that compares equal to a value parsed from TOML source without a fraction.
50
+ */
51
+ function smolTomlDateToNative(value) {
52
+ const canonical = value.toISOString().replace(/\.000(?=([Zz]|[+-]\d{2}:\d{2})$|$)/, "");
53
+ if (value.isDate()) return new LocalDate(canonical);
54
+ if (value.isTime()) return new LocalTime(canonical, canonical);
55
+ if (value.isLocal()) return new LocalDateTime(canonical, false);
56
+ return new OffsetDateTime(canonical, false);
57
+ }
58
+
59
+ //#endregion
60
+ export { isSmolTomlDate, smolTomlDateToNative };
61
+ //# sourceMappingURL=smol-toml-date.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"smol-toml-date.js","names":[],"sources":["../../src/smol-toml-date.ts"],"sourcesContent":["/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n// Vendored from smol-toml (https://github.com/squirrelchat/smol-toml),\n// src/date.ts. Kept in the regular package so values produced by smol-toml's\n// parser can be recognised by type. The lite distribution duck-types these\n// values instead of importing this module, to stay small.\n\nimport { LocalDate, LocalTime, LocalDateTime, OffsetDateTime } from './date-format';\n\ntype Offset = string | null\n\nconst DATE_TIME_RE = /^(\\d{4}-\\d{2}-\\d{2})?[T ]?(?:(\\d{2}):\\d{2}(?::\\d{2}(?:\\.\\d+)?)?)?(Z|[-+]\\d{2}:\\d{2})?$/i\n\nexport class TomlDate extends Date {\n\t#hasDate = false\n\t#hasTime = false\n\t#offset: Offset = null\n\n\tconstructor(date: string | Date) {\n\t\tlet hasDate = true\n\t\tlet hasTime = true\n\t\tlet offset: Offset = 'Z'\n\n\t\tif (typeof date === 'string') {\n\t\t\tconst match = date.match(DATE_TIME_RE)\n\t\t\tif (match) {\n\t\t\t\tif (!match[1]) {\n\t\t\t\t\thasDate = false\n\t\t\t\t\tdate = `0000-01-01T${date}`\n\t\t\t\t}\n\n\t\t\t\thasTime = !!match[2]\n\t\t\t\t// Make sure to use T instead of a space. Breaks in case of extreme values otherwise.\n\t\t\t\tif (hasTime && date[10] === ' ') {\n\t\t\t\t\tdate = date.replace(' ', 'T')\n\t\t\t\t}\n\t\t\t\t// Do not allow rollover hours.\n\t\t\t\tif (match[2] && +match[2] > 23) {\n\t\t\t\t\tdate = ''\n\t\t\t\t} else {\n\t\t\t\t\toffset = match[3] || null\n\t\t\t\t\tdate = date.toUpperCase()\n\t\t\t\t\tif (!offset && hasTime) date += 'Z'\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdate = ''\n\t\t\t}\n\t\t}\n\n\t\tsuper(date)\n\t\tif (!isNaN(this.getTime())) {\n\t\t\tthis.#hasDate = hasDate\n\t\t\tthis.#hasTime = hasTime\n\t\t\tthis.#offset = offset\n\t\t}\n\t}\n\n\tisDateTime() {\n\t\treturn this.#hasDate && this.#hasTime\n\t}\n\n\tisLocal() {\n\t\treturn !this.#hasDate || !this.#hasTime || !this.#offset\n\t}\n\n\tisDate() {\n\t\treturn this.#hasDate && !this.#hasTime\n\t}\n\n\tisTime() {\n\t\treturn this.#hasTime && !this.#hasDate\n\t}\n\n\tisValid() {\n\t\treturn this.#hasDate || this.#hasTime\n\t}\n\n\toverride toISOString() {\n\t\tconst iso = super.toISOString()\n\n\t\t// Local Date\n\t\tif (this.isDate())\n\t\t\treturn iso.slice(0, 10)\n\n\t\t// Local Time\n\t\tif (this.isTime())\n\t\t\treturn iso.slice(11, 23)\n\n\t\t// Local DateTime\n\t\tif (this.#offset === null)\n\t\t\treturn iso.slice(0, -1)\n\n\t\t// Offset DateTime\n\t\tif (this.#offset === 'Z')\n\t\t\treturn iso\n\n\t\t// This part is quite annoying: JS strips the original timezone from the ISO string representation\n\t\t// Instead of using a \"modified\" date and \"Z\", we restore the representation \"as authored\"\n\n\t\tlet offset = (+(this.#offset.slice(1, 3)) * 60) + +(this.#offset.slice(4, 6))\n\t\toffset = this.#offset[0] === '-' ? offset : -offset\n\n\t\tconst offsetDate = new Date(this.getTime() - (offset * 60e3))\n\t\treturn offsetDate.toISOString().slice(0, -1) + this.#offset\n\t}\n\n\tstatic wrapAsOffsetDateTime(jsDate: Date, offset = 'Z') {\n\t\tconst date = new TomlDate(jsDate)\n\t\tdate.#offset = offset\n\t\treturn date\n\t}\n\n\tstatic wrapAsLocalDateTime(jsDate: Date) {\n\t\tconst date = new TomlDate(jsDate)\n\t\tdate.#offset = null\n\t\treturn date\n\t}\n\n\tstatic wrapAsLocalDate(jsDate: Date) {\n\t\tconst date = new TomlDate(jsDate)\n\t\tdate.#hasTime = false\n\t\tdate.#offset = null\n\t\treturn date\n\t}\n\n\tstatic wrapAsLocalTime(jsDate: Date) {\n\t\tconst date = new TomlDate(jsDate)\n\t\tdate.#hasDate = false\n\t\tdate.#offset = null\n\t\treturn date\n\t}\n}\n\n/**\n * True when `value` is a smol-toml `TomlDate` instance.\n *\n * Duck-typed rather than `instanceof TomlDate`: the caller's object was parsed\n * by the smol-toml package, whose `TomlDate` is a different class object than\n * this vendored copy, so `instanceof` would never match. The `isDate` /\n * `isTime` / `isDateTime` methods only exist on smol-toml's date class, which\n * is what distinguishes it from toml-patch's own date classes.\n */\nexport function isSmolTomlDate(value: unknown): value is TomlDate {\n return (\n value instanceof Date &&\n typeof (value as any).isDate === 'function' &&\n typeof (value as any).isTime === 'function' &&\n typeof (value as any).isDateTime === 'function'\n );\n}\n\n/**\n * Converts a smol-toml `TomlDate` into the equivalent toml-patch date class.\n *\n * smol-toml always renders a zero-fraction time or datetime with a trailing\n * `.000`, while toml-patch omits it. Stripping it gives the canonical form\n * that compares equal to a value parsed from TOML source without a fraction.\n */\nexport function smolTomlDateToNative(\n value: TomlDate\n): LocalDate | LocalTime | LocalDateTime | OffsetDateTime {\n const canonical = value.toISOString().replace(/\\.000(?=([Zz]|[+-]\\d{2}:\\d{2})$|$)/, '');\n\n if (value.isDate()) {\n return new LocalDate(canonical);\n }\n if (value.isTime()) {\n return new LocalTime(canonical, canonical);\n }\n if (value.isLocal()) {\n return new LocalDateTime(canonical, false);\n }\n return new OffsetDateTime(canonical, false);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwKA,SAAgB,eAAe,OAAmC;CAChE,OACE,iBAAiB,QACjB,OAAQ,MAAc,WAAW,cACjC,OAAQ,MAAc,WAAW,cACjC,OAAQ,MAAc,eAAe;AAEzC;;;;;;;;AASA,SAAgB,qBACd,OACwD;CACxD,MAAM,YAAY,MAAM,YAAY,CAAC,CAAC,QAAQ,sCAAsC,EAAE;CAEtF,IAAI,MAAM,OAAO,GACf,OAAO,IAAI,UAAU,SAAS;CAEhC,IAAI,MAAM,OAAO,GACf,OAAO,IAAI,UAAU,WAAW,SAAS;CAE3C,IAAI,MAAM,QAAQ,GAChB,OAAO,IAAI,cAAc,WAAW,KAAK;CAE3C,OAAO,IAAI,eAAe,WAAW,KAAK;AAC5C"}
package/dist/dev/to-js.js CHANGED
@@ -1,4 +1,4 @@
1
- //! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
1
+ //! @decimalturn/toml-patch v3.2.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
2
  import ParseError from "./parse-error.js";
3
3
  import { LocalDate, LocalDateTime, LocalTime, OffsetDateTime } from "./date-format.js";
4
4
  import { blank, has, isDate, last } from "./utils.js";
@@ -1,4 +1,4 @@
1
- //! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
1
+ //! @decimalturn/toml-patch v3.2.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
2
  import { hasItem, hasItems, isInlineArray, isInlineItem, isInlineTable, isKeyValue, isTable, isTableArray } from "./cst.js";
3
3
  import { getCommaSpace } from "./inline-comma-space.js";
4
4
  import { isIterable } from "./utils.js";
@@ -1,4 +1,4 @@
1
- //! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
1
+ //! @decimalturn/toml-patch v3.2.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
2
  import { findPosition } from "./location.js";
3
3
  import ParseError from "./parse-error.js";
4
4
 
@@ -1,4 +1,4 @@
1
- //! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
1
+ //! @decimalturn/toml-patch v3.2.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
2
  import parseTOML, { continueParsingTOML } from "./parse-toml.js";
3
3
  import { isObject } from "./utils.js";
4
4
  import { decodeUtf8Bytes, hasLeadingBom, stripLeadingBom } from "./decode-utf8.js";
@@ -1,4 +1,4 @@
1
- //! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
1
+ //! @decimalturn/toml-patch v3.2.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
2
  import parseTOML from "./parse-toml.js";
3
3
  import { hasLeadingBom, stripLeadingBom } from "./decode-utf8.js";
4
4
 
@@ -16,6 +16,7 @@ const DEFAULT_LEADING_BOM = false;
16
16
  const DEFAULT_UPDATE_ORDER = false;
17
17
  const DEFAULT_MULTILINE_TABLE = "auto";
18
18
  const DEFAULT_MULTILINE_ARRAY = "auto";
19
+ const DEFAULT_ESCAPE_SEQUENCE_UPPER_CASE = true;
19
20
  function detectTrailingComma(cst) {
20
21
  for (const item of cst) {
21
22
  const result = findTrailingCommaInNode(item);
@@ -108,6 +109,48 @@ function countTrailingNewlines(str) {
108
109
  }
109
110
  return count;
110
111
  }
112
+ function escapeCaseOfRaw(raw) {
113
+ for (let i = 0; i < raw.length; i++) {
114
+ if (raw[i] !== "\\") continue;
115
+ const n1 = raw[i + 1];
116
+ if (!n1) return null;
117
+ if (n1 === "\\") {
118
+ i++;
119
+ continue;
120
+ }
121
+ if (n1 === "x" && /^[0-9A-Fa-f]{2}$/.test(raw.slice(i + 2, i + 4))) return /[A-F]/.test(raw.slice(i + 2, i + 4));
122
+ if (n1 === "u" && /^[0-9A-Fa-f]{4}$/.test(raw.slice(i + 2, i + 6))) return /[A-F]/.test(raw.slice(i + 2, i + 6));
123
+ if (n1 === "U" && /^[0-9A-Fa-f]{8}$/.test(raw.slice(i + 2, i + 10))) return /[A-F]/.test(raw.slice(i + 2, i + 10));
124
+ }
125
+ return null;
126
+ }
127
+ function findEscapeCaseInNode(node) {
128
+ if (!node || typeof node !== "object") return null;
129
+ if (node.type === "String" && typeof node.raw === "string") {
130
+ const result = escapeCaseOfRaw(node.raw);
131
+ if (result !== null) return result;
132
+ }
133
+ for (const prop of [
134
+ "key",
135
+ "item",
136
+ "value"
137
+ ]) if (node[prop] && typeof node[prop] === "object") {
138
+ const result = findEscapeCaseInNode(node[prop]);
139
+ if (result !== null) return result;
140
+ }
141
+ if (Array.isArray(node.items)) for (const child of node.items) {
142
+ const result = findEscapeCaseInNode(child);
143
+ if (result !== null) return result;
144
+ }
145
+ return null;
146
+ }
147
+ function detectEscapeSequenceUpperCase(cstNodes) {
148
+ for (const node of cstNodes) {
149
+ const result = findEscapeCaseInNode(node);
150
+ if (result !== null) return result;
151
+ }
152
+ return true;
153
+ }
111
154
  function detectTabsForIndentation(str) {
112
155
  const lines = str.split(/\r?\n/);
113
156
  let tabCount = 0;
@@ -215,7 +258,8 @@ function validateFormatObject(format) {
215
258
  minimumDecimals: (v) => v == null || typeof v === "number" && Number.isInteger(v) && v >= 0 ? null : `expected non-negative integer or undefined, got ${typeof v}`,
216
259
  updateOrder: isBool,
217
260
  multilineTable: isMultilineContainerMode,
218
- multilineArray: isMultilineContainerMode
261
+ multilineArray: isMultilineContainerMode,
262
+ escapeSequenceUpperCase: isBool
219
263
  };
220
264
  const validatedFormat = {};
221
265
  const unsupported = [];
@@ -247,7 +291,7 @@ function resolveTomlFormat(format, fallbackFormat) {
247
291
  if (format instanceof TomlFormat) return format;
248
292
  else {
249
293
  const validatedFormat = validateFormatObject(format);
250
- return new TomlFormat(validatedFormat.newLine ?? fallbackFormat.newLine, validatedFormat.trailingNewline ?? fallbackFormat.trailingNewline, validatedFormat.trailingComma ?? fallbackFormat.trailingComma, validatedFormat.bracketSpacing ?? fallbackFormat.bracketSpacing, "inlineTableStart" in validatedFormat ? validatedFormat.inlineTableStart : fallbackFormat.inlineTableStart, validatedFormat.truncateZeroTimeInDates ?? fallbackFormat.truncateZeroTimeInDates, validatedFormat.useTabsForIndentation ?? fallbackFormat.useTabsForIndentation, validatedFormat.minimumDecimals ?? fallbackFormat.minimumDecimals, validatedFormat.leadingBom ?? fallbackFormat.leadingBom, validatedFormat.updateOrder ?? fallbackFormat.updateOrder, validatedFormat.indentWidth ?? fallbackFormat.indentWidth, validatedFormat.multilineTable ?? fallbackFormat.multilineTable, validatedFormat.multilineArray ?? fallbackFormat.multilineArray);
294
+ return new TomlFormat(validatedFormat.newLine ?? fallbackFormat.newLine, validatedFormat.trailingNewline ?? fallbackFormat.trailingNewline, validatedFormat.trailingComma ?? fallbackFormat.trailingComma, validatedFormat.bracketSpacing ?? fallbackFormat.bracketSpacing, "inlineTableStart" in validatedFormat ? validatedFormat.inlineTableStart : fallbackFormat.inlineTableStart, validatedFormat.truncateZeroTimeInDates ?? fallbackFormat.truncateZeroTimeInDates, validatedFormat.useTabsForIndentation ?? fallbackFormat.useTabsForIndentation, validatedFormat.minimumDecimals ?? fallbackFormat.minimumDecimals, validatedFormat.leadingBom ?? fallbackFormat.leadingBom, validatedFormat.updateOrder ?? fallbackFormat.updateOrder, validatedFormat.indentWidth ?? fallbackFormat.indentWidth, validatedFormat.multilineTable ?? fallbackFormat.multilineTable, validatedFormat.multilineArray ?? fallbackFormat.multilineArray, validatedFormat.escapeSequenceUpperCase ?? fallbackFormat.escapeSequenceUpperCase);
251
295
  }
252
296
  } else return fallbackFormat;
253
297
  }
@@ -374,7 +418,13 @@ var TomlFormat = class TomlFormat {
374
418
  * keeps new containers compact and `'parent'` follows the immediate parent.
375
419
  */
376
420
  multilineArray;
377
- constructor(newLine, trailingNewline, trailingComma, bracketSpacing, inlineTableStart, truncateZeroTimeInDates, useTabsForIndentation, minimumDecimals, leadingBom, updateOrder, indentWidth, multilineTable, multilineArray) {
421
+ /**
422
+ * Whether to write `\uXXXX` / `\UXXXXXXXX` / `\xHH` escape sequences with
423
+ * uppercase hex digits. Auto-detected from the first hex escape sequence in
424
+ * the document during patching; defaults to `true` (uppercase hex).
425
+ */
426
+ escapeSequenceUpperCase;
427
+ constructor(newLine, trailingNewline, trailingComma, bracketSpacing, inlineTableStart, truncateZeroTimeInDates, useTabsForIndentation, minimumDecimals, leadingBom, updateOrder, indentWidth, multilineTable, multilineArray, escapeSequenceUpperCase) {
378
428
  this.newLine = newLine == null ? "\n" : normalizeNewLine(newLine);
379
429
  this.trailingNewline = trailingNewline ?? 1;
380
430
  this.trailingComma = trailingComma ?? false;
@@ -388,6 +438,7 @@ var TomlFormat = class TomlFormat {
388
438
  this.updateOrder = updateOrder ?? false;
389
439
  this.multilineTable = multilineTable ?? "auto";
390
440
  this.multilineArray = multilineArray ?? "auto";
441
+ this.escapeSequenceUpperCase = escapeSequenceUpperCase ?? true;
391
442
  }
392
443
  /**
393
444
  * Creates a new TomlFormat instance with default formatting preferences.
@@ -405,7 +456,7 @@ var TomlFormat = class TomlFormat {
405
456
  * - updateOrder: false
406
457
  */
407
458
  static default() {
408
- return new TomlFormat("\n", 1, false, true, 1, false, false, 0, false, false, 2, DEFAULT_MULTILINE_TABLE, DEFAULT_MULTILINE_ARRAY);
459
+ return new TomlFormat("\n", 1, false, true, 1, false, false, 0, false, false, 2, DEFAULT_MULTILINE_TABLE, DEFAULT_MULTILINE_ARRAY, true);
409
460
  }
410
461
  /**
411
462
  * Auto-detects formatting preferences from an existing TOML string.
@@ -463,6 +514,7 @@ var TomlFormat = class TomlFormat {
463
514
  format.updateOrder = false;
464
515
  format.multilineTable = DEFAULT_MULTILINE_TABLE;
465
516
  format.multilineArray = DEFAULT_MULTILINE_ARRAY;
517
+ format.escapeSequenceUpperCase = detectEscapeSequenceUpperCase(cstNodes);
466
518
  return format;
467
519
  }
468
520
  /** @deprecated Use autoDetectFormatWithCst instead. */
@@ -472,5 +524,5 @@ var TomlFormat = class TomlFormat {
472
524
  };
473
525
 
474
526
  //#endregion
475
- export { DEFAULT_MULTILINE_ARRAY, DEFAULT_MULTILINE_TABLE, TomlFormat, countTrailingNewlines, detectBracketSpacing, detectIndentWidth, detectNewline, detectTabsForIndentation, detectTrailingComma, normalizeNewLine, resolveTomlFormat, validateFormatObject };
527
+ export { DEFAULT_MULTILINE_ARRAY, DEFAULT_MULTILINE_TABLE, TomlFormat, countTrailingNewlines, detectBracketSpacing, detectEscapeSequenceUpperCase, detectIndentWidth, detectNewline, detectTabsForIndentation, detectTrailingComma, normalizeNewLine, resolveTomlFormat, validateFormatObject };
476
528
  //# sourceMappingURL=toml-format.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"toml-format.js","names":[],"sources":["../../src/toml-format.ts"],"sourcesContent":["import { hasLeadingBom, stripLeadingBom } from './decode-utf8';\nimport parseTOML from './parse-toml';\n\n// Default formatting values\nexport const DEFAULT_NEWLINE = '\\n';\nexport const DEFAULT_TRAILING_NEWLINE = 1;\nexport const DEFAULT_TRAILING_COMMA = false;\nexport const DEFAULT_BRACKET_SPACING = true;\nexport const DEFAULT_INLINE_TABLE_START = 1;\nexport const DEFAULT_TRUNCATE_ZERO_TIME_IN_DATES = false;\nexport const DEFAULT_USE_TABS_FOR_INDENTATION = false;\nexport const DEFAULT_INDENT_WIDTH = 2;\nexport const DEFAULT_MINIMUM_DECIMALS = 0;\nexport const DEFAULT_LEADING_BOM = false;\nexport const DEFAULT_UPDATE_ORDER = false;\nexport const DEFAULT_MULTILINE_TABLE = 'auto';\nexport const DEFAULT_MULTILINE_ARRAY = 'auto';\n\nexport type MultilineContainerMode = boolean | number | 'auto' | 'parent';\n\n// Detects if trailing commas are used in the existing TOML by examining the CST\n// Returns true if trailing commas are used, false if not or comma-separated structures found (ie. default to false)\nexport function detectTrailingComma(cst: Iterable<any>): boolean {\n // Look for the first inline array or inline table to determine trailing comma preference\n for (const item of cst) {\n const result = findTrailingCommaInNode(item);\n if (result !== null) {\n return result;\n }\n }\n // Return default if no comma-separated structures are found\n return DEFAULT_TRAILING_COMMA;\n}\n\n// Detects if bracket spacing is used in inline arrays and tables by examining the raw string\n// Returns true if bracket spacing is found, false if not or no bracket structures found (default to true)\nexport function detectBracketSpacing(tomlString: string, cst: Iterable<any>): boolean {\n // Look for inline arrays and tables\n for (const item of cst) {\n const result = findBracketSpacingInNode(item, tomlString);\n if (result !== null) {\n return result;\n }\n }\n // Return default if no bracket structures are found\n return DEFAULT_BRACKET_SPACING;\n}\n\n// Helper function to recursively search for bracket spacing in a node\nfunction findBracketSpacingInNode(node: any, tomlString: string): boolean | null {\n if (!node || typeof node !== 'object') {\n return null;\n }\n\n // Check if this is an InlineArray or InlineTable\n if ((node.type === 'InlineArray' || node.type === 'InlineTable') && node.loc) {\n const bracketSpacing = checkBracketSpacingInLocation(node.loc, tomlString);\n if (bracketSpacing !== null) {\n return bracketSpacing;\n }\n }\n\n // Recursively check nested structures\n if (node.items && Array.isArray(node.items)) {\n for (const child of node.items) {\n const result = findBracketSpacingInNode(child, tomlString);\n if (result !== null) {\n return result;\n }\n // Also check nested item if it exists\n if (child.item) {\n const nestedResult = findBracketSpacingInNode(child.item, tomlString);\n if (nestedResult !== null) {\n return nestedResult;\n }\n }\n }\n }\n\n // Check other properties that might contain nodes\n for (const prop of ['value', 'key', 'item']) {\n if (node[prop]) {\n const result = findBracketSpacingInNode(node[prop], tomlString);\n if (result !== null) {\n return result;\n }\n }\n }\n\n return null;\n}\n\n// Helper function to check bracket spacing in a specific location\nfunction checkBracketSpacingInLocation(loc: any, tomlString: string): boolean | null {\n if (!loc || !loc.start || !loc.end) {\n return null;\n }\n\n // Extract the raw text for this location\n const lines = tomlString.split(/\\r?\\n/);\n const startLine = loc.start.line - 1; // Convert to 0-based\n const endLine = loc.end.line - 1;\n const startCol = loc.start.column;\n const endCol = loc.end.column;\n\n let rawText = '';\n if (startLine === endLine) {\n rawText = lines[startLine]?.substring(startCol, endCol + 1) || '';\n } else {\n // Multi-line case\n if (lines[startLine]) {\n rawText += lines[startLine].substring(startCol);\n }\n for (let i = startLine + 1; i < endLine; i++) {\n rawText += '\\n' + (lines[i] || '');\n }\n if (lines[endLine]) {\n rawText += '\\n' + lines[endLine].substring(0, endCol + 1);\n }\n }\n\n // Check for bracket spacing patterns\n // For arrays: [ elements ] vs [elements]\n // For tables: { elements } vs {elements}\n const arrayMatch = rawText.match(/^\\[(\\s*)/);\n const tableMatch = rawText.match(/^\\{(\\s*)/);\n \n if (arrayMatch) {\n // Check if there's a space after the opening bracket\n return arrayMatch[1].length > 0;\n }\n \n if (tableMatch) {\n // Check if there's a space after the opening brace\n return tableMatch[1].length > 0;\n }\n\n return null;\n}\n\n// Helper function to recursively search for comma usage in a node\nfunction findTrailingCommaInNode(node: any): boolean | null {\n if (!node || typeof node !== 'object') {\n return null;\n }\n\n // Check if this is an InlineArray\n if (node.type === 'InlineArray' && node.items && Array.isArray(node.items)) {\n return checkTrailingCommaInItems(node.items);\n }\n\n // Check if this is an InlineTable\n if (node.type === 'InlineTable' && node.items && Array.isArray(node.items)) {\n return checkTrailingCommaInItems(node.items);\n }\n\n // Check if this is a KeyValue with a value that might contain arrays/tables\n if (node.type === 'KeyValue' && node.value) {\n return findTrailingCommaInNode(node.value);\n }\n\n // For other node types, recursively check any items array\n if (node.items && Array.isArray(node.items)) {\n for (const item of node.items) {\n const result = findTrailingCommaInNode(item);\n if (result !== null) {\n return result;\n }\n }\n }\n\n return null;\n}\n\n// Check trailing comma usage in an array of inline items\nfunction checkTrailingCommaInItems(items: any[]): boolean | null {\n if (items.length === 0) {\n return null;\n }\n\n // Check the last item to see if it has a trailing comma\n const lastItem = items[items.length - 1];\n if (lastItem && typeof lastItem === 'object' && 'comma' in lastItem) {\n return lastItem.comma === true;\n }\n\n return false;\n}\n\n// Returns the detected newline (\\n or \\r\\n) from a string, defaulting to \\n.\n// First occurrence wins: if \\r\\n appears anywhere before a bare \\n, the document\n// is considered CRLF even if later lines (or string values) use bare LF.\nexport function detectNewline(str: string): string {\n const lfIndex = str.indexOf('\\n');\n if (lfIndex > 0 && str[lfIndex - 1] === '\\r') {\n return '\\r\\n';\n }\n return '\\n';\n}\n\n// Counts consecutive trailing newlines at the end of a string.\n// Counts each \\n (whether bare or as part of \\r\\n) as one newline unit,\n// so mixed trailing line endings (e.g. a CRLF document with a bare \\n at EOF)\n// are still counted correctly.\nexport function countTrailingNewlines(str: string): number {\n let count = 0;\n let pos = str.length;\n while (pos > 0 && str[pos - 1] === '\\n') {\n count++;\n pos--;\n if (pos > 0 && str[pos - 1] === '\\r') {\n pos--; // consume the \\r as part of CRLF\n }\n }\n return count;\n}\n\n// Detects if tabs are used for indentation by checking the first few indented lines\nexport function detectTabsForIndentation(str: string): boolean {\n const lines = str.split(/\\r?\\n/);\n let tabCount = 0;\n let spaceCount = 0;\n \n for (const line of lines) {\n // Skip empty lines\n if (line.length === 0) continue;\n \n // Check the first character of non-empty lines\n if (line[0] === '\\t') {\n tabCount++;\n } else if (line[0] === ' ') {\n spaceCount++;\n }\n \n // If we've seen enough evidence, make a decision\n if (tabCount + spaceCount >= 5) {\n break;\n }\n }\n \n // Prefer tabs when they are at least as common as spaces, provided there is tab evidence.\n if (tabCount > 0) {\n return tabCount >= spaceCount;\n }\n return false; // default to spaces if no evidence\n}\n/*\n Detect the indentation width (number of spaces) used in the existing TOML by examining the CST.\n\n This function already assumes that the TOML document does not use tabs for indentation. \n Do not use this function if tabs are used for indentation!\n\n It looks for the first indented line in the CST that is part of a nested \n structure (like a table or array) and measures the number of leading spaces \n to determine the indentation width.\n*/\nfunction countLeadingSpaces(line: string): number {\n let count = 0;\n while (count < line.length && line[count] === ' ') count++;\n return count;\n}\n\nexport function detectIndentWidth(tomlString: string, syntaxTree?: Iterable<any>): number {\n const lines = tomlString.split(/\\r?\\n/);\n const widths: number[] = [];\n const containers = new Set(['Table', 'TableArray', 'InlineTable', 'InlineArray']);\n const rowNodes = new Set(['Table', 'TableArray', 'InlineTable', 'InlineArray', 'KeyValue', 'InlineItem', 'Comment']);\n\n const visit = (node: any, containerStartLine?: number): void => {\n if (!node || typeof node !== 'object') return;\n\n if (\n containerStartLine !== undefined &&\n rowNodes.has(node.type) &&\n node.loc?.start?.line > containerStartLine\n ) {\n const line = lines[node.loc.start.line - 1] ?? '';\n const leadingSpaces = countLeadingSpaces(line);\n if (leadingSpaces > 0) widths.push(leadingSpaces);\n }\n\n const nextContainerStartLine = containers.has(node.type) && node.loc?.end?.line > node.loc?.start?.line\n ? node.loc.start.line\n : containerStartLine;\n\n if (Array.isArray(node.items)) {\n for (const item of node.items) visit(item, nextContainerStartLine);\n }\n if (node.item) visit(node.item, nextContainerStartLine);\n if (node.value) visit(node.value, nextContainerStartLine);\n };\n\n const nodes = Array.isArray(syntaxTree)\n ? syntaxTree\n : Array.from(syntaxTree ?? []);\n for (const node of nodes) visit(node);\n\n if (widths.length > 0) return Math.min(...widths);\n\n // A document with only an indented root key has no nested CST row from which to\n // infer the width. Use its content indentation as a fallback, ignoring blank lines\n // and comments so a banner cannot become the detected indent.\n const rootIndentWidths = lines\n .filter(line => line.trim().length > 0 && !line.trimStart().startsWith('#'))\n .map(countLeadingSpaces)\n .filter(width => width > 0);\n return rootIndentWidths.length > 0 ? Math.min(...rootIndentWidths) : DEFAULT_INDENT_WIDTH;\n}\n\n/**\n * Validates a format object and warns about unsupported properties.\n * Throws errors for supported properties with invalid types.\n * @param format - The format object to validate\n * @returns The validated format object with only supported properties and correct types\n */\n/**\n * Spellings accepted for `newLine`, mapped to the line ending they denote.\n * A Map rather than an object literal so that a key like `constructor` cannot\n * resolve through Object.prototype.\n */\nconst NEW_LINE_ALIASES = new Map<string, string>([\n ['\\n', '\\n'],\n ['\\r\\n', '\\r\\n'],\n ['\\\\n', '\\n'],\n ['\\\\r\\\\n', '\\r\\n'],\n ['LF', '\\n'],\n ['CRLF', '\\r\\n'],\n ['UNIX', '\\n'],\n ['DOS', '\\r\\n']\n]);\n\n/**\n * Resolves an accepted `newLine` spelling to the literal it denotes.\n *\n * TOML permits only LF and CRLF, so anything else would silently produce a\n * document that does not parse (a bare '\\\\r', or the literal text 'LF' written\n * between every pair of lines). Rejecting it here means every entry point that\n * resolves a format gets the check, rather than just `patch()`.\n *\n * @throws TypeError when the value denotes neither LF nor CRLF\n */\nexport function normalizeNewLine(value: string): string {\n const resolved = NEW_LINE_ALIASES.get(value) ?? NEW_LINE_ALIASES.get(value.toUpperCase());\n if (resolved === undefined) {\n throw new TypeError('Invalid newLine value: expected LF or CRLF');\n }\n return resolved;\n}\n\nexport function validateFormatObject(format: any): any {\n if (!format || typeof format !== 'object') {\n return {};\n }\n\n // Schema-driven validation: each key maps to a validator returning an error string or null\n const isBool = (v: any): string | null =>\n typeof v === 'boolean' ? null : `expected boolean, got ${typeof v}`;\n const isMultilineContainerMode = (v: any): string | null =>\n v == null ||\n typeof v === 'boolean' ||\n v === 'auto' ||\n v === 'parent' ||\n (typeof v === 'number' && Number.isInteger(v) && v >= 0)\n ? null\n : `expected boolean, non-negative integer, \"auto\" or \"parent\", got ${typeof v}`;\n const schema: Record<string, (v: any) => string | null> = {\n newLine: v => typeof v === 'string' ? null : `expected string, got ${typeof v}`,\n trailingNewline: v => typeof v === 'boolean' || typeof v === 'number' ? null : `expected boolean or number, got ${typeof v}`,\n trailingComma: isBool,\n bracketSpacing: isBool,\n leadingBom: isBool,\n inlineTableStart: v => v == null || (typeof v === 'number' && Number.isInteger(v) && v >= 0)\n ? null : `expected non-negative integer or undefined, got ${typeof v}`,\n truncateZeroTimeInDates: isBool,\n useTabsForIndentation: isBool,\n indentWidth: v => v == null || (typeof v === 'number' && Number.isInteger(v) && v > 0)\n ? null : `expected positive integer or undefined, got ${typeof v}`,\n minimumDecimals: v => v == null || (typeof v === 'number' && Number.isInteger(v) && v >= 0)\n ? null : `expected non-negative integer or undefined, got ${typeof v}`,\n updateOrder: isBool,\n multilineTable: isMultilineContainerMode,\n multilineArray: isMultilineContainerMode,\n };\n\n const validatedFormat: any = {};\n const unsupported: string[] = [];\n const invalid: string[] = [];\n\n for (const key in format) {\n const validator = Object.prototype.hasOwnProperty.call(schema, key) ? schema[key] : undefined;\n if (validator) {\n const value = format[key];\n const error = validator(value);\n if (error) {\n invalid.push(`${key} (${error})`);\n } else {\n validatedFormat[key] = value;\n }\n } else if (Object.prototype.hasOwnProperty.call(format, key)) {\n unsupported.push(key);\n }\n }\n\n if (unsupported.length > 0) {\n console.warn(`toml-patch: Ignoring unsupported format properties: ${unsupported.join(', ')}. Supported properties are: ${Object.keys(schema).join(', ')}`);\n }\n if (invalid.length > 0) {\n throw new TypeError(`Invalid types for format properties: ${invalid.join(', ')}`);\n }\n\n // Runs after the type checks so a non-string newLine is still reported as a\n // type error rather than an unsupported value.\n if ('newLine' in validatedFormat) {\n validatedFormat.newLine = normalizeNewLine(validatedFormat.newLine);\n }\n\n return validatedFormat;\n}\n\n/**\n * Resolves a format parameter to a TomlFormat instance.\n * Handles TomlFormat instances and partial TomlFormat objects as well as undefined.\n * \n * @param format - The format parameter to resolve (TomlFormat instance, partial format object, or undefined)\n * @param fallbackFormat - The fallback TomlFormat to use when no format is provided\n * @returns A resolved TomlFormat instance\n */\nexport function resolveTomlFormat(format: Partial<TomlFormat> | TomlFormat | undefined, fallbackFormat: TomlFormat): TomlFormat {\n if (format) {\n // If format is provided, validate and merge it with fallback\n if (format instanceof TomlFormat) {\n return format;\n } else {\n // Validate the format object and warn about unsupported properties\n const validatedFormat = validateFormatObject(format);\n \n // Create a new TomlFormat instance with validated properties\n return new TomlFormat(\n validatedFormat.newLine ?? fallbackFormat.newLine,\n validatedFormat.trailingNewline ?? fallbackFormat.trailingNewline,\n validatedFormat.trailingComma ?? fallbackFormat.trailingComma,\n validatedFormat.bracketSpacing ?? fallbackFormat.bracketSpacing,\n 'inlineTableStart' in validatedFormat ? validatedFormat.inlineTableStart : fallbackFormat.inlineTableStart,\n validatedFormat.truncateZeroTimeInDates ?? fallbackFormat.truncateZeroTimeInDates,\n validatedFormat.useTabsForIndentation ?? fallbackFormat.useTabsForIndentation,\n validatedFormat.minimumDecimals ?? fallbackFormat.minimumDecimals,\n validatedFormat.leadingBom ?? fallbackFormat.leadingBom,\n validatedFormat.updateOrder ?? fallbackFormat.updateOrder,\n validatedFormat.indentWidth ?? fallbackFormat.indentWidth,\n validatedFormat.multilineTable ?? fallbackFormat.multilineTable,\n validatedFormat.multilineArray ?? fallbackFormat.multilineArray,\n );\n }\n } else {\n // Use fallback format when no format is provided\n return fallbackFormat;\n }\n}\n\nexport class TomlFormat {\n \n /**\n * The line ending character(s) to use in the output TOML.\n * This option affects only the stringification process, not the internal representation (CST).\n * \n * @example\n * - '\\n' for Unix/Linux line endings\n * - '\\r\\n' for Windows line endings\n */\n newLine: string;\n \n /**\n * The number of trailing newlines to add at the end of the TOML document.\n * This option affects only the stringification process, not the internal representation (CST).\n * \n * @example\n * - 0: No trailing newline\n * - 1: One trailing newline (standard)\n * - 2: Two trailing newlines (adds extra spacing)\n */\n trailingNewline: number;\n \n /**\n * Whether to add trailing commas after the last element in arrays and inline tables.\n * \n * @example\n * - true: [1, 2, 3,] and { x = 1, y = 2, }\n * - false: [1, 2, 3] and { x = 1, y = 2 }\n */\n trailingComma: boolean;\n \n /**\n * Whether to add spaces after opening brackets/braces and before closing brackets/braces\n * in arrays and inline tables.\n * \n * @example\n * - true: [ 1, 2, 3 ] and { x = 1, y = 2 }\n * - false: [1, 2, 3] and {x = 1, y = 2}\n */\n bracketSpacing: boolean;\n\n /**\n * Whether the output should include a leading UTF-8 BOM marker (U+FEFF).\n *\n * This is auto-detected from the source TOML and preserved during patching.\n */\n leadingBom: boolean;\n\n /**\n * The nesting depth at which new tables should start being formatted as inline tables.\n * When adding new tables during patching or stringifying objects:\n * - Tables at depth >= inlineTableStart will be formatted as inline tables\n * - Tables at depth < inlineTableStart will be formatted as separate table sections\n * \n * @example\n * - 0: All tables are inline tables including top-level tables (root level)\n * - 1: Top-level tables as sections, nested tables as inline (default)\n * - 2: Two levels as sections, deeper nesting as inline\n */\n inlineTableStart?: number;\n\n /**\n * Whether to truncate time components in UTC date fields when they are zero.\n * This setting affects only the stringification process.\n * \n * @example \n * - true: Date('2024-01-15T00:00:00.000Z') serializes as 2024-01-15\n * - false: Date('2024-01-15T00:00:00.000Z') serializes as 2024-01-15T00:00:00.000Z\n * \n */\n truncateZeroTimeInDates?: boolean;\n\n /**\n * Whether to use tabs instead of spaces for indentation/padding.\n * When enabled, lines that need to be indented will use tabs.\n * \n * @example \n * - true: Uses tabs for indentation\n * - false: Uses spaces for indentation (default)\n * \n */\n useTabsForIndentation?: boolean;\n\n /**\n * The number of columns used for one indentation level in generated multiline values.\n * This is auto-detected when patching and defaults to two columns.\n */\n indentWidth: number;\n\n /**\n * The minimum number of decimal places to use when serializing JS numbers as TOML floats.\n * When greater than 0, plain JS integer values are serialized as TOML floats padded with\n * zeros to reach the specified decimal count. BigInt values are always serialized as integers\n * regardless of this setting.\n *\n * @example\n * - 0: stringify({ x: 1, y: 1.5 }) → x = 1 / y = 1.5 (default)\n * - 1: stringify({ x: 1, y: 1.5 }) → x = 1.0 / y = 1.5\n * - 2: stringify({ x: 1, y: 1.5 }) → x = 1.00 / y = 1.50\n */\n minimumDecimals?: number;\n\n /**\n * Whether `patch()` should reorder root key-values, `[table]`/`[[array]]` section blocks,\n * and rows inside table bodies to match the key order of the JS object passed to `patch()`,\n * carrying each entry's owned comments along with it (see docs/CommentOwnership.md).\n *\n * Off by default: with the option unset or `false`, `patch()` only ever changes values that\n * actually differ between the existing document and the updated object, preserving the\n * existing document's order even when the JS object's key order differs.\n *\n * Not auto-detectable — the existing document's order says nothing about the caller's\n * intent, so `autoDetectFormatWithCst` always resolves this to `false`.\n *\n * See docs/PLAN-Update-Order.md for the full behavior and current scope limitations.\n */\n updateOrder?: boolean;\n\n /**\n * Whether newly generated inline tables should use multiline layout.\n *\n * `true` and `false` select a layout directly. A non-negative integer selects\n * multiline layout at that structural container depth or deeper. `'auto'`\n * keeps new containers compact and `'parent'` follows the immediate parent.\n */\n multilineTable: MultilineContainerMode;\n\n /**\n * Whether newly generated inline arrays should use multiline layout.\n *\n * `true` and `false` select a layout directly. A non-negative integer selects\n * multiline layout at that structural container depth or deeper. `'auto'`\n * keeps new containers compact and `'parent'` follows the immediate parent.\n */\n multilineArray: MultilineContainerMode;\n\n // These options were part of the original TimHall's version and are not yet implemented\n //printWidth?: number;\n //tabWidth?: number;\n\n constructor(\n newLine?: string,\n trailingNewline?: number,\n trailingComma?: boolean,\n bracketSpacing?: boolean,\n inlineTableStart?: number,\n truncateZeroTimeInDates?: boolean,\n useTabsForIndentation?: boolean,\n minimumDecimals?: number,\n leadingBom?: boolean,\n updateOrder?: boolean,\n indentWidth?: number,\n multilineTable?: MultilineContainerMode | null,\n multilineArray?: MultilineContainerMode | null\n ) {\n // Use provided values or fall back to defaults\n this.newLine = newLine == null ? DEFAULT_NEWLINE : normalizeNewLine(newLine);\n this.trailingNewline = trailingNewline ?? DEFAULT_TRAILING_NEWLINE;\n this.trailingComma = trailingComma ?? DEFAULT_TRAILING_COMMA;\n this.bracketSpacing = bracketSpacing ?? DEFAULT_BRACKET_SPACING;\n this.inlineTableStart = inlineTableStart ?? DEFAULT_INLINE_TABLE_START;\n this.truncateZeroTimeInDates = truncateZeroTimeInDates ?? DEFAULT_TRUNCATE_ZERO_TIME_IN_DATES;\n this.useTabsForIndentation = useTabsForIndentation ?? DEFAULT_USE_TABS_FOR_INDENTATION;\n this.indentWidth = this.useTabsForIndentation ? 1 : indentWidth ?? DEFAULT_INDENT_WIDTH;\n this.minimumDecimals = minimumDecimals ?? DEFAULT_MINIMUM_DECIMALS;\n this.leadingBom = leadingBom ?? DEFAULT_LEADING_BOM;\n this.updateOrder = updateOrder ?? DEFAULT_UPDATE_ORDER;\n this.multilineTable = multilineTable ?? DEFAULT_MULTILINE_TABLE;\n this.multilineArray = multilineArray ?? DEFAULT_MULTILINE_ARRAY;\n }\n\n /**\n * Creates a new TomlFormat instance with default formatting preferences.\n * \n * @returns A new TomlFormat instance with default values:\n * - newLine: '\\n'\n * - trailingNewline: 1\n * - trailingComma: false\n * - bracketSpacing: true\n * - leadingBom: false\n * - inlineTableStart: 1\n * - truncateZeroTimeInDates: false\n * - useTabsForIndentation: false\n * - minimumDecimals: 0\n * - updateOrder: false\n */\n static default(): TomlFormat {\n return new TomlFormat(\n DEFAULT_NEWLINE,\n DEFAULT_TRAILING_NEWLINE,\n DEFAULT_TRAILING_COMMA,\n DEFAULT_BRACKET_SPACING,\n DEFAULT_INLINE_TABLE_START,\n DEFAULT_TRUNCATE_ZERO_TIME_IN_DATES,\n DEFAULT_USE_TABS_FOR_INDENTATION,\n DEFAULT_MINIMUM_DECIMALS,\n DEFAULT_LEADING_BOM,\n DEFAULT_UPDATE_ORDER,\n DEFAULT_INDENT_WIDTH,\n DEFAULT_MULTILINE_TABLE,\n DEFAULT_MULTILINE_ARRAY\n );\n }\n\n /**\n * Auto-detects formatting preferences from an existing TOML string.\n * \n * This method analyzes the provided TOML string to determine formatting\n * preferences such as line endings, trailing newlines, and comma usage.\n * \n * @param tomlString - The TOML string to analyze for formatting patterns\n * @returns A new TomlFormat instance with detected formatting preferences\n * \n * @example\n * ```typescript\n * const toml = 'array = [\"a\", \"b\", \"c\",]\\ntable = { x = 1, y = 2, }';\n * const format = TomlFormat.autoDetectFormat(toml);\n * // format.trailingComma will be true\n * // format.newLine will be '\\n'\n * // format.trailingNewline will be 0 (no trailing newline)\n * ```\n */\n static autoDetectFormat(tomlString: string): TomlFormat {\n return TomlFormat.autoDetectFormatWithCst(tomlString);\n }\n\n /**\n * Internal method: Auto-detects formatting preferences from a TOML string with optional pre-parsed CST.\n * \n * This is used internally to avoid redundant parsing when the CST is already available.\n * External callers should use `autoDetectFormat(tomlString)` instead.\n * \n * @internal\n * @param tomlString - The TOML string to analyze for formatting patterns\n * @param syntaxTree - Optional pre-parsed CST to avoid redundant parsing\n * @returns A new TomlFormat instance with detected formatting preferences\n */\n static autoDetectFormatWithCst(tomlString: string, syntaxTree?: Iterable<any>): TomlFormat {\n const format = TomlFormat.default();\n format.leadingBom = hasLeadingBom(tomlString);\n // Strip the BOM before other formatting detection to avoid interference.\n const tomlContent = stripLeadingBom(tomlString);\n let cstNodes: any[] = [];\n \n // Detect line ending style\n format.newLine = detectNewline(tomlContent);\n \n // Detect trailing newline count\n format.trailingNewline = countTrailingNewlines(tomlContent);\n \n // Get TOML syntax tree to detect comma and bracket spacing usage patterns\n try {\n // Materialize only when needed so we can traverse the same CST twice.\n cstNodes = Array.isArray(syntaxTree)\n ? syntaxTree\n : Array.from(syntaxTree ?? parseTOML(tomlContent));\n format.trailingComma = detectTrailingComma(cstNodes);\n format.bracketSpacing = detectBracketSpacing(tomlContent, cstNodes);\n } catch (error) {\n // If parsing fails, fall back to defaults\n // This ensures the method is robust against malformed TOML\n format.trailingComma = DEFAULT_TRAILING_COMMA;\n format.bracketSpacing = DEFAULT_BRACKET_SPACING;\n }\n \n // Detect if tabs are used for indentation\n format.useTabsForIndentation = detectTabsForIndentation(tomlContent);\n if (format.useTabsForIndentation) {\n // If tabs are used, indentWidth is effectively 1 (one tab character)\n format.indentWidth = 1;\n } else {\n // Otherwise, detect the number of spaces used for indentation\n format.indentWidth = detectIndentWidth(tomlContent, cstNodes);\n }\n \n \n // inlineTableStart uses default value since auto-detection would require\n // complex analysis of nested table formatting preferences\n format.inlineTableStart = DEFAULT_INLINE_TABLE_START;\n\n // truncateZeroTimeInDates uses default value as well\n // We could always implement detection logic if needed\n // That would imply checking if all dates have no time component in the TOML.\n // However, it's not because all dates have no time component that a new key-value can't be introduced where the time component corresponds to midnight.\n format.truncateZeroTimeInDates = DEFAULT_TRUNCATE_ZERO_TIME_IN_DATES;\n\n // minimumDecimals uses default value (0) — caller must set explicitly\n format.minimumDecimals = DEFAULT_MINIMUM_DECIMALS;\n\n // updateOrder uses default value (false) as well — the existing document's order says\n // nothing about the caller's intent, so this is never auto-detected.\n format.updateOrder = DEFAULT_UPDATE_ORDER;\n\n // Multiline container layout is caller intent, so it is never auto-detected.\n format.multilineTable = DEFAULT_MULTILINE_TABLE;\n format.multilineArray = DEFAULT_MULTILINE_ARRAY;\n\n return format;\n }\n\n /** @deprecated Use autoDetectFormatWithCst instead. */\n static autoDetectFormatWithAst(tomlString: string, syntaxTree?: Iterable<any>): TomlFormat {\n return TomlFormat.autoDetectFormatWithCst(tomlString, syntaxTree);\n }\n}\n"],"mappings":";;;;;AAIA,MAAa,kBAAkB;AAC/B,MAAa,2BAA2B;AACxC,MAAa,yBAAyB;AACtC,MAAa,0BAA0B;AACvC,MAAa,6BAA6B;AAC1C,MAAa,sCAAsC;AACnD,MAAa,mCAAmC;AAChD,MAAa,uBAAuB;AACpC,MAAa,2BAA2B;AACxC,MAAa,sBAAsB;AACnC,MAAa,uBAAuB;AACpC,MAAa,0BAA0B;AACvC,MAAa,0BAA0B;AAMvC,SAAgB,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;EACxB,OAAO,iBAAiB;EAExB,OAAO;CACT;;CAGA,OAAO,wBAAwB,YAAoB,YAAwC;EACzF,OAAO,WAAW,wBAAwB,YAAY,UAAU;CAClE;AACF"}
1
+ {"version":3,"file":"toml-format.js","names":[],"sources":["../../src/toml-format.ts"],"sourcesContent":["import { hasLeadingBom, stripLeadingBom } from './decode-utf8';\nimport parseTOML from './parse-toml';\n\n// Default formatting values\nexport const DEFAULT_NEWLINE = '\\n';\nexport const DEFAULT_TRAILING_NEWLINE = 1;\nexport const DEFAULT_TRAILING_COMMA = false;\nexport const DEFAULT_BRACKET_SPACING = true;\nexport const DEFAULT_INLINE_TABLE_START = 1;\nexport const DEFAULT_TRUNCATE_ZERO_TIME_IN_DATES = false;\nexport const DEFAULT_USE_TABS_FOR_INDENTATION = false;\nexport const DEFAULT_INDENT_WIDTH = 2;\nexport const DEFAULT_MINIMUM_DECIMALS = 0;\nexport const DEFAULT_LEADING_BOM = false;\nexport const DEFAULT_UPDATE_ORDER = false;\nexport const DEFAULT_MULTILINE_TABLE = 'auto';\nexport const DEFAULT_MULTILINE_ARRAY = 'auto';\nexport const DEFAULT_ESCAPE_SEQUENCE_UPPER_CASE = true;\n\nexport type MultilineContainerMode = boolean | number | 'auto' | 'parent';\n\n// Detects if trailing commas are used in the existing TOML by examining the CST\n// Returns true if trailing commas are used, false if not or comma-separated structures found (ie. default to false)\nexport function detectTrailingComma(cst: Iterable<any>): boolean {\n // Look for the first inline array or inline table to determine trailing comma preference\n for (const item of cst) {\n const result = findTrailingCommaInNode(item);\n if (result !== null) {\n return result;\n }\n }\n // Return default if no comma-separated structures are found\n return DEFAULT_TRAILING_COMMA;\n}\n\n// Detects if bracket spacing is used in inline arrays and tables by examining the raw string\n// Returns true if bracket spacing is found, false if not or no bracket structures found (default to true)\nexport function detectBracketSpacing(tomlString: string, cst: Iterable<any>): boolean {\n // Look for inline arrays and tables\n for (const item of cst) {\n const result = findBracketSpacingInNode(item, tomlString);\n if (result !== null) {\n return result;\n }\n }\n // Return default if no bracket structures are found\n return DEFAULT_BRACKET_SPACING;\n}\n\n// Helper function to recursively search for bracket spacing in a node\nfunction findBracketSpacingInNode(node: any, tomlString: string): boolean | null {\n if (!node || typeof node !== 'object') {\n return null;\n }\n\n // Check if this is an InlineArray or InlineTable\n if ((node.type === 'InlineArray' || node.type === 'InlineTable') && node.loc) {\n const bracketSpacing = checkBracketSpacingInLocation(node.loc, tomlString);\n if (bracketSpacing !== null) {\n return bracketSpacing;\n }\n }\n\n // Recursively check nested structures\n if (node.items && Array.isArray(node.items)) {\n for (const child of node.items) {\n const result = findBracketSpacingInNode(child, tomlString);\n if (result !== null) {\n return result;\n }\n // Also check nested item if it exists\n if (child.item) {\n const nestedResult = findBracketSpacingInNode(child.item, tomlString);\n if (nestedResult !== null) {\n return nestedResult;\n }\n }\n }\n }\n\n // Check other properties that might contain nodes\n for (const prop of ['value', 'key', 'item']) {\n if (node[prop]) {\n const result = findBracketSpacingInNode(node[prop], tomlString);\n if (result !== null) {\n return result;\n }\n }\n }\n\n return null;\n}\n\n// Helper function to check bracket spacing in a specific location\nfunction checkBracketSpacingInLocation(loc: any, tomlString: string): boolean | null {\n if (!loc || !loc.start || !loc.end) {\n return null;\n }\n\n // Extract the raw text for this location\n const lines = tomlString.split(/\\r?\\n/);\n const startLine = loc.start.line - 1; // Convert to 0-based\n const endLine = loc.end.line - 1;\n const startCol = loc.start.column;\n const endCol = loc.end.column;\n\n let rawText = '';\n if (startLine === endLine) {\n rawText = lines[startLine]?.substring(startCol, endCol + 1) || '';\n } else {\n // Multi-line case\n if (lines[startLine]) {\n rawText += lines[startLine].substring(startCol);\n }\n for (let i = startLine + 1; i < endLine; i++) {\n rawText += '\\n' + (lines[i] || '');\n }\n if (lines[endLine]) {\n rawText += '\\n' + lines[endLine].substring(0, endCol + 1);\n }\n }\n\n // Check for bracket spacing patterns\n // For arrays: [ elements ] vs [elements]\n // For tables: { elements } vs {elements}\n const arrayMatch = rawText.match(/^\\[(\\s*)/);\n const tableMatch = rawText.match(/^\\{(\\s*)/);\n \n if (arrayMatch) {\n // Check if there's a space after the opening bracket\n return arrayMatch[1].length > 0;\n }\n \n if (tableMatch) {\n // Check if there's a space after the opening brace\n return tableMatch[1].length > 0;\n }\n\n return null;\n}\n\n// Helper function to recursively search for comma usage in a node\nfunction findTrailingCommaInNode(node: any): boolean | null {\n if (!node || typeof node !== 'object') {\n return null;\n }\n\n // Check if this is an InlineArray\n if (node.type === 'InlineArray' && node.items && Array.isArray(node.items)) {\n return checkTrailingCommaInItems(node.items);\n }\n\n // Check if this is an InlineTable\n if (node.type === 'InlineTable' && node.items && Array.isArray(node.items)) {\n return checkTrailingCommaInItems(node.items);\n }\n\n // Check if this is a KeyValue with a value that might contain arrays/tables\n if (node.type === 'KeyValue' && node.value) {\n return findTrailingCommaInNode(node.value);\n }\n\n // For other node types, recursively check any items array\n if (node.items && Array.isArray(node.items)) {\n for (const item of node.items) {\n const result = findTrailingCommaInNode(item);\n if (result !== null) {\n return result;\n }\n }\n }\n\n return null;\n}\n\n// Check trailing comma usage in an array of inline items\nfunction checkTrailingCommaInItems(items: any[]): boolean | null {\n if (items.length === 0) {\n return null;\n }\n\n // Check the last item to see if it has a trailing comma\n const lastItem = items[items.length - 1];\n if (lastItem && typeof lastItem === 'object' && 'comma' in lastItem) {\n return lastItem.comma === true;\n }\n\n return false;\n}\n\n// Returns the detected newline (\\n or \\r\\n) from a string, defaulting to \\n.\n// First occurrence wins: if \\r\\n appears anywhere before a bare \\n, the document\n// is considered CRLF even if later lines (or string values) use bare LF.\nexport function detectNewline(str: string): string {\n const lfIndex = str.indexOf('\\n');\n if (lfIndex > 0 && str[lfIndex - 1] === '\\r') {\n return '\\r\\n';\n }\n return '\\n';\n}\n\n// Counts consecutive trailing newlines at the end of a string.\n// Counts each \\n (whether bare or as part of \\r\\n) as one newline unit,\n// so mixed trailing line endings (e.g. a CRLF document with a bare \\n at EOF)\n// are still counted correctly.\nexport function countTrailingNewlines(str: string): number {\n let count = 0;\n let pos = str.length;\n while (pos > 0 && str[pos - 1] === '\\n') {\n count++;\n pos--;\n if (pos > 0 && str[pos - 1] === '\\r') {\n pos--; // consume the \\r as part of CRLF\n }\n }\n return count;\n}\n\n// Returns the case (uppercase vs lowercase) of the first hex escape sequence found in a\n// string's raw text, or null when the string contains no hex escape sequences.\nfunction escapeCaseOfRaw(raw: string): boolean | null {\n for (let i = 0; i < raw.length; i++) {\n if (raw[i] !== '\\\\') continue;\n const n1 = raw[i + 1];\n if (!n1) return null;\n\n if (n1 === '\\\\') {\n // An escaped backslash: the character after it is content, so the second\n // backslash does not start a hex escape. `\\\\uabcd` is the text `\\uabcd`\n // and must not decide the case of the escapes the library generates.\n i++;\n continue;\n }\n\n if (n1 === 'x' && /^[0-9A-Fa-f]{2}$/.test(raw.slice(i + 2, i + 4))) {\n return /[A-F]/.test(raw.slice(i + 2, i + 4));\n }\n if (n1 === 'u' && /^[0-9A-Fa-f]{4}$/.test(raw.slice(i + 2, i + 6))) {\n return /[A-F]/.test(raw.slice(i + 2, i + 6));\n }\n if (n1 === 'U' && /^[0-9A-Fa-f]{8}$/.test(raw.slice(i + 2, i + 10))) {\n return /[A-F]/.test(raw.slice(i + 2, i + 10));\n }\n // Simple escapes (\\b, \\t, \\n, \\f, \\r, \\\", \\\\) carry no hex digits, so they\n // cannot inform the case preference and are skipped.\n }\n return null;\n}\n\nfunction findEscapeCaseInNode(node: any): boolean | null {\n if (!node || typeof node !== 'object') return null;\n\n if (node.type === 'String' && typeof node.raw === 'string') {\n const result = escapeCaseOfRaw(node.raw);\n if (result !== null) return result;\n }\n\n for (const prop of ['key', 'item', 'value']) {\n if (node[prop] && typeof node[prop] === 'object') {\n const result = findEscapeCaseInNode(node[prop]);\n if (result !== null) return result;\n }\n }\n if (Array.isArray(node.items)) {\n for (const child of node.items) {\n const result = findEscapeCaseInNode(child);\n if (result !== null) return result;\n }\n }\n\n return null;\n}\n\n// Detects whether escape sequences in existing string values use uppercase hex digits.\n// The first hex escape sequence encountered in document order wins: uppercase hex (A-F)\n// selects uppercase output, lowercase selects lowercase output.\nexport function detectEscapeSequenceUpperCase(cstNodes: Iterable<any>): boolean {\n for (const node of cstNodes) {\n const result = findEscapeCaseInNode(node);\n if (result !== null) return result;\n }\n return DEFAULT_ESCAPE_SEQUENCE_UPPER_CASE;\n}\n\n// Detects if tabs are used for indentation by checking the first few indented lines\nexport function detectTabsForIndentation(str: string): boolean {\n const lines = str.split(/\\r?\\n/);\n let tabCount = 0;\n let spaceCount = 0;\n \n for (const line of lines) {\n // Skip empty lines\n if (line.length === 0) continue;\n \n // Check the first character of non-empty lines\n if (line[0] === '\\t') {\n tabCount++;\n } else if (line[0] === ' ') {\n spaceCount++;\n }\n \n // If we've seen enough evidence, make a decision\n if (tabCount + spaceCount >= 5) {\n break;\n }\n }\n \n // Prefer tabs when they are at least as common as spaces, provided there is tab evidence.\n if (tabCount > 0) {\n return tabCount >= spaceCount;\n }\n return false; // default to spaces if no evidence\n}\n/*\n Detect the indentation width (number of spaces) used in the existing TOML by examining the CST.\n\n This function already assumes that the TOML document does not use tabs for indentation. \n Do not use this function if tabs are used for indentation!\n\n It looks for the first indented line in the CST that is part of a nested \n structure (like a table or array) and measures the number of leading spaces \n to determine the indentation width.\n*/\nfunction countLeadingSpaces(line: string): number {\n let count = 0;\n while (count < line.length && line[count] === ' ') count++;\n return count;\n}\n\nexport function detectIndentWidth(tomlString: string, syntaxTree?: Iterable<any>): number {\n const lines = tomlString.split(/\\r?\\n/);\n const widths: number[] = [];\n const containers = new Set(['Table', 'TableArray', 'InlineTable', 'InlineArray']);\n const rowNodes = new Set(['Table', 'TableArray', 'InlineTable', 'InlineArray', 'KeyValue', 'InlineItem', 'Comment']);\n\n const visit = (node: any, containerStartLine?: number): void => {\n if (!node || typeof node !== 'object') return;\n\n if (\n containerStartLine !== undefined &&\n rowNodes.has(node.type) &&\n node.loc?.start?.line > containerStartLine\n ) {\n const line = lines[node.loc.start.line - 1] ?? '';\n const leadingSpaces = countLeadingSpaces(line);\n if (leadingSpaces > 0) widths.push(leadingSpaces);\n }\n\n const nextContainerStartLine = containers.has(node.type) && node.loc?.end?.line > node.loc?.start?.line\n ? node.loc.start.line\n : containerStartLine;\n\n if (Array.isArray(node.items)) {\n for (const item of node.items) visit(item, nextContainerStartLine);\n }\n if (node.item) visit(node.item, nextContainerStartLine);\n if (node.value) visit(node.value, nextContainerStartLine);\n };\n\n const nodes = Array.isArray(syntaxTree)\n ? syntaxTree\n : Array.from(syntaxTree ?? []);\n for (const node of nodes) visit(node);\n\n if (widths.length > 0) return Math.min(...widths);\n\n // A document with only an indented root key has no nested CST row from which to\n // infer the width. Use its content indentation as a fallback, ignoring blank lines\n // and comments so a banner cannot become the detected indent.\n const rootIndentWidths = lines\n .filter(line => line.trim().length > 0 && !line.trimStart().startsWith('#'))\n .map(countLeadingSpaces)\n .filter(width => width > 0);\n return rootIndentWidths.length > 0 ? Math.min(...rootIndentWidths) : DEFAULT_INDENT_WIDTH;\n}\n\n/**\n * Validates a format object and warns about unsupported properties.\n * Throws errors for supported properties with invalid types.\n * @param format - The format object to validate\n * @returns The validated format object with only supported properties and correct types\n */\n/**\n * Spellings accepted for `newLine`, mapped to the line ending they denote.\n * A Map rather than an object literal so that a key like `constructor` cannot\n * resolve through Object.prototype.\n */\nconst NEW_LINE_ALIASES = new Map<string, string>([\n ['\\n', '\\n'],\n ['\\r\\n', '\\r\\n'],\n ['\\\\n', '\\n'],\n ['\\\\r\\\\n', '\\r\\n'],\n ['LF', '\\n'],\n ['CRLF', '\\r\\n'],\n ['UNIX', '\\n'],\n ['DOS', '\\r\\n']\n]);\n\n/**\n * Resolves an accepted `newLine` spelling to the literal it denotes.\n *\n * TOML permits only LF and CRLF, so anything else would silently produce a\n * document that does not parse (a bare '\\\\r', or the literal text 'LF' written\n * between every pair of lines). Rejecting it here means every entry point that\n * resolves a format gets the check, rather than just `patch()`.\n *\n * @throws TypeError when the value denotes neither LF nor CRLF\n */\nexport function normalizeNewLine(value: string): string {\n const resolved = NEW_LINE_ALIASES.get(value) ?? NEW_LINE_ALIASES.get(value.toUpperCase());\n if (resolved === undefined) {\n throw new TypeError('Invalid newLine value: expected LF or CRLF');\n }\n return resolved;\n}\n\nexport function validateFormatObject(format: any): any {\n if (!format || typeof format !== 'object') {\n return {};\n }\n\n // Schema-driven validation: each key maps to a validator returning an error string or null\n const isBool = (v: any): string | null =>\n typeof v === 'boolean' ? null : `expected boolean, got ${typeof v}`;\n const isMultilineContainerMode = (v: any): string | null =>\n v == null ||\n typeof v === 'boolean' ||\n v === 'auto' ||\n v === 'parent' ||\n (typeof v === 'number' && Number.isInteger(v) && v >= 0)\n ? null\n : `expected boolean, non-negative integer, \"auto\" or \"parent\", got ${typeof v}`;\n const schema: Record<string, (v: any) => string | null> = {\n newLine: v => typeof v === 'string' ? null : `expected string, got ${typeof v}`,\n trailingNewline: v => typeof v === 'boolean' || typeof v === 'number' ? null : `expected boolean or number, got ${typeof v}`,\n trailingComma: isBool,\n bracketSpacing: isBool,\n leadingBom: isBool,\n inlineTableStart: v => v == null || (typeof v === 'number' && Number.isInteger(v) && v >= 0)\n ? null : `expected non-negative integer or undefined, got ${typeof v}`,\n truncateZeroTimeInDates: isBool,\n useTabsForIndentation: isBool,\n indentWidth: v => v == null || (typeof v === 'number' && Number.isInteger(v) && v > 0)\n ? null : `expected positive integer or undefined, got ${typeof v}`,\n minimumDecimals: v => v == null || (typeof v === 'number' && Number.isInteger(v) && v >= 0)\n ? null : `expected non-negative integer or undefined, got ${typeof v}`,\n updateOrder: isBool,\n multilineTable: isMultilineContainerMode,\n multilineArray: isMultilineContainerMode,\n escapeSequenceUpperCase: isBool,\n };\n\n const validatedFormat: any = {};\n const unsupported: string[] = [];\n const invalid: string[] = [];\n\n for (const key in format) {\n const validator = Object.prototype.hasOwnProperty.call(schema, key) ? schema[key] : undefined;\n if (validator) {\n const value = format[key];\n const error = validator(value);\n if (error) {\n invalid.push(`${key} (${error})`);\n } else {\n validatedFormat[key] = value;\n }\n } else if (Object.prototype.hasOwnProperty.call(format, key)) {\n unsupported.push(key);\n }\n }\n\n if (unsupported.length > 0) {\n console.warn(`toml-patch: Ignoring unsupported format properties: ${unsupported.join(', ')}. Supported properties are: ${Object.keys(schema).join(', ')}`);\n }\n if (invalid.length > 0) {\n throw new TypeError(`Invalid types for format properties: ${invalid.join(', ')}`);\n }\n\n // Runs after the type checks so a non-string newLine is still reported as a\n // type error rather than an unsupported value.\n if ('newLine' in validatedFormat) {\n validatedFormat.newLine = normalizeNewLine(validatedFormat.newLine);\n }\n\n return validatedFormat;\n}\n\n/**\n * Resolves a format parameter to a TomlFormat instance.\n * Handles TomlFormat instances and partial TomlFormat objects as well as undefined.\n * \n * @param format - The format parameter to resolve (TomlFormat instance, partial format object, or undefined)\n * @param fallbackFormat - The fallback TomlFormat to use when no format is provided\n * @returns A resolved TomlFormat instance\n */\nexport function resolveTomlFormat(format: Partial<TomlFormat> | TomlFormat | undefined, fallbackFormat: TomlFormat): TomlFormat {\n if (format) {\n // If format is provided, validate and merge it with fallback\n if (format instanceof TomlFormat) {\n return format;\n } else {\n // Validate the format object and warn about unsupported properties\n const validatedFormat = validateFormatObject(format);\n \n // Create a new TomlFormat instance with validated properties\n return new TomlFormat(\n validatedFormat.newLine ?? fallbackFormat.newLine,\n validatedFormat.trailingNewline ?? fallbackFormat.trailingNewline,\n validatedFormat.trailingComma ?? fallbackFormat.trailingComma,\n validatedFormat.bracketSpacing ?? fallbackFormat.bracketSpacing,\n 'inlineTableStart' in validatedFormat ? validatedFormat.inlineTableStart : fallbackFormat.inlineTableStart,\n validatedFormat.truncateZeroTimeInDates ?? fallbackFormat.truncateZeroTimeInDates,\n validatedFormat.useTabsForIndentation ?? fallbackFormat.useTabsForIndentation,\n validatedFormat.minimumDecimals ?? fallbackFormat.minimumDecimals,\n validatedFormat.leadingBom ?? fallbackFormat.leadingBom,\n validatedFormat.updateOrder ?? fallbackFormat.updateOrder,\n validatedFormat.indentWidth ?? fallbackFormat.indentWidth,\n validatedFormat.multilineTable ?? fallbackFormat.multilineTable,\n validatedFormat.multilineArray ?? fallbackFormat.multilineArray,\n validatedFormat.escapeSequenceUpperCase ?? fallbackFormat.escapeSequenceUpperCase,\n );\n }\n } else {\n // Use fallback format when no format is provided\n return fallbackFormat;\n }\n}\n\nexport class TomlFormat {\n \n /**\n * The line ending character(s) to use in the output TOML.\n * This option affects only the stringification process, not the internal representation (CST).\n * \n * @example\n * - '\\n' for Unix/Linux line endings\n * - '\\r\\n' for Windows line endings\n */\n newLine: string;\n \n /**\n * The number of trailing newlines to add at the end of the TOML document.\n * This option affects only the stringification process, not the internal representation (CST).\n * \n * @example\n * - 0: No trailing newline\n * - 1: One trailing newline (standard)\n * - 2: Two trailing newlines (adds extra spacing)\n */\n trailingNewline: number;\n \n /**\n * Whether to add trailing commas after the last element in arrays and inline tables.\n * \n * @example\n * - true: [1, 2, 3,] and { x = 1, y = 2, }\n * - false: [1, 2, 3] and { x = 1, y = 2 }\n */\n trailingComma: boolean;\n \n /**\n * Whether to add spaces after opening brackets/braces and before closing brackets/braces\n * in arrays and inline tables.\n * \n * @example\n * - true: [ 1, 2, 3 ] and { x = 1, y = 2 }\n * - false: [1, 2, 3] and {x = 1, y = 2}\n */\n bracketSpacing: boolean;\n\n /**\n * Whether the output should include a leading UTF-8 BOM marker (U+FEFF).\n *\n * This is auto-detected from the source TOML and preserved during patching.\n */\n leadingBom: boolean;\n\n /**\n * The nesting depth at which new tables should start being formatted as inline tables.\n * When adding new tables during patching or stringifying objects:\n * - Tables at depth >= inlineTableStart will be formatted as inline tables\n * - Tables at depth < inlineTableStart will be formatted as separate table sections\n * \n * @example\n * - 0: All tables are inline tables including top-level tables (root level)\n * - 1: Top-level tables as sections, nested tables as inline (default)\n * - 2: Two levels as sections, deeper nesting as inline\n */\n inlineTableStart?: number;\n\n /**\n * Whether to truncate time components in UTC date fields when they are zero.\n * This setting affects only the stringification process.\n * \n * @example \n * - true: Date('2024-01-15T00:00:00.000Z') serializes as 2024-01-15\n * - false: Date('2024-01-15T00:00:00.000Z') serializes as 2024-01-15T00:00:00.000Z\n * \n */\n truncateZeroTimeInDates?: boolean;\n\n /**\n * Whether to use tabs instead of spaces for indentation/padding.\n * When enabled, lines that need to be indented will use tabs.\n * \n * @example \n * - true: Uses tabs for indentation\n * - false: Uses spaces for indentation (default)\n * \n */\n useTabsForIndentation?: boolean;\n\n /**\n * The number of columns used for one indentation level in generated multiline values.\n * This is auto-detected when patching and defaults to two columns.\n */\n indentWidth: number;\n\n /**\n * The minimum number of decimal places to use when serializing JS numbers as TOML floats.\n * When greater than 0, plain JS integer values are serialized as TOML floats padded with\n * zeros to reach the specified decimal count. BigInt values are always serialized as integers\n * regardless of this setting.\n *\n * @example\n * - 0: stringify({ x: 1, y: 1.5 }) → x = 1 / y = 1.5 (default)\n * - 1: stringify({ x: 1, y: 1.5 }) → x = 1.0 / y = 1.5\n * - 2: stringify({ x: 1, y: 1.5 }) → x = 1.00 / y = 1.50\n */\n minimumDecimals?: number;\n\n /**\n * Whether `patch()` should reorder root key-values, `[table]`/`[[array]]` section blocks,\n * and rows inside table bodies to match the key order of the JS object passed to `patch()`,\n * carrying each entry's owned comments along with it (see docs/CommentOwnership.md).\n *\n * Off by default: with the option unset or `false`, `patch()` only ever changes values that\n * actually differ between the existing document and the updated object, preserving the\n * existing document's order even when the JS object's key order differs.\n *\n * Not auto-detectable — the existing document's order says nothing about the caller's\n * intent, so `autoDetectFormatWithCst` always resolves this to `false`.\n *\n * See docs/PLAN-Update-Order.md for the full behavior and current scope limitations.\n */\n updateOrder?: boolean;\n\n /**\n * Whether newly generated inline tables should use multiline layout.\n *\n * `true` and `false` select a layout directly. A non-negative integer selects\n * multiline layout at that structural container depth or deeper. `'auto'`\n * keeps new containers compact and `'parent'` follows the immediate parent.\n */\n multilineTable: MultilineContainerMode;\n\n /**\n * Whether newly generated inline arrays should use multiline layout.\n *\n * `true` and `false` select a layout directly. A non-negative integer selects\n * multiline layout at that structural container depth or deeper. `'auto'`\n * keeps new containers compact and `'parent'` follows the immediate parent.\n */\n multilineArray: MultilineContainerMode;\n\n /**\n * Whether to write `\\uXXXX` / `\\UXXXXXXXX` / `\\xHH` escape sequences with\n * uppercase hex digits. Auto-detected from the first hex escape sequence in\n * the document during patching; defaults to `true` (uppercase hex).\n */\n escapeSequenceUpperCase: boolean;\n\n // These options were part of the original TimHall's version and are not yet implemented\n //printWidth?: number;\n //tabWidth?: number;\n\n constructor(\n newLine?: string,\n trailingNewline?: number,\n trailingComma?: boolean,\n bracketSpacing?: boolean,\n inlineTableStart?: number,\n truncateZeroTimeInDates?: boolean,\n useTabsForIndentation?: boolean,\n minimumDecimals?: number,\n leadingBom?: boolean,\n updateOrder?: boolean,\n indentWidth?: number,\n multilineTable?: MultilineContainerMode | null,\n multilineArray?: MultilineContainerMode | null,\n escapeSequenceUpperCase?: boolean\n ) {\n // Use provided values or fall back to defaults\n this.newLine = newLine == null ? DEFAULT_NEWLINE : normalizeNewLine(newLine);\n this.trailingNewline = trailingNewline ?? DEFAULT_TRAILING_NEWLINE;\n this.trailingComma = trailingComma ?? DEFAULT_TRAILING_COMMA;\n this.bracketSpacing = bracketSpacing ?? DEFAULT_BRACKET_SPACING;\n this.inlineTableStart = inlineTableStart ?? DEFAULT_INLINE_TABLE_START;\n this.truncateZeroTimeInDates = truncateZeroTimeInDates ?? DEFAULT_TRUNCATE_ZERO_TIME_IN_DATES;\n this.useTabsForIndentation = useTabsForIndentation ?? DEFAULT_USE_TABS_FOR_INDENTATION;\n this.indentWidth = this.useTabsForIndentation ? 1 : indentWidth ?? DEFAULT_INDENT_WIDTH;\n this.minimumDecimals = minimumDecimals ?? DEFAULT_MINIMUM_DECIMALS;\n this.leadingBom = leadingBom ?? DEFAULT_LEADING_BOM;\n this.updateOrder = updateOrder ?? DEFAULT_UPDATE_ORDER;\n this.multilineTable = multilineTable ?? DEFAULT_MULTILINE_TABLE;\n this.multilineArray = multilineArray ?? DEFAULT_MULTILINE_ARRAY;\n this.escapeSequenceUpperCase = escapeSequenceUpperCase ?? DEFAULT_ESCAPE_SEQUENCE_UPPER_CASE;\n }\n\n /**\n * Creates a new TomlFormat instance with default formatting preferences.\n * \n * @returns A new TomlFormat instance with default values:\n * - newLine: '\\n'\n * - trailingNewline: 1\n * - trailingComma: false\n * - bracketSpacing: true\n * - leadingBom: false\n * - inlineTableStart: 1\n * - truncateZeroTimeInDates: false\n * - useTabsForIndentation: false\n * - minimumDecimals: 0\n * - updateOrder: false\n */\n static default(): TomlFormat {\n return new TomlFormat(\n DEFAULT_NEWLINE,\n DEFAULT_TRAILING_NEWLINE,\n DEFAULT_TRAILING_COMMA,\n DEFAULT_BRACKET_SPACING,\n DEFAULT_INLINE_TABLE_START,\n DEFAULT_TRUNCATE_ZERO_TIME_IN_DATES,\n DEFAULT_USE_TABS_FOR_INDENTATION,\n DEFAULT_MINIMUM_DECIMALS,\n DEFAULT_LEADING_BOM,\n DEFAULT_UPDATE_ORDER,\n DEFAULT_INDENT_WIDTH,\n DEFAULT_MULTILINE_TABLE,\n DEFAULT_MULTILINE_ARRAY,\n DEFAULT_ESCAPE_SEQUENCE_UPPER_CASE\n );\n }\n\n /**\n * Auto-detects formatting preferences from an existing TOML string.\n * \n * This method analyzes the provided TOML string to determine formatting\n * preferences such as line endings, trailing newlines, and comma usage.\n * \n * @param tomlString - The TOML string to analyze for formatting patterns\n * @returns A new TomlFormat instance with detected formatting preferences\n * \n * @example\n * ```typescript\n * const toml = 'array = [\"a\", \"b\", \"c\",]\\ntable = { x = 1, y = 2, }';\n * const format = TomlFormat.autoDetectFormat(toml);\n * // format.trailingComma will be true\n * // format.newLine will be '\\n'\n * // format.trailingNewline will be 0 (no trailing newline)\n * ```\n */\n static autoDetectFormat(tomlString: string): TomlFormat {\n return TomlFormat.autoDetectFormatWithCst(tomlString);\n }\n\n /**\n * Internal method: Auto-detects formatting preferences from a TOML string with optional pre-parsed CST.\n * \n * This is used internally to avoid redundant parsing when the CST is already available.\n * External callers should use `autoDetectFormat(tomlString)` instead.\n * \n * @internal\n * @param tomlString - The TOML string to analyze for formatting patterns\n * @param syntaxTree - Optional pre-parsed CST to avoid redundant parsing\n * @returns A new TomlFormat instance with detected formatting preferences\n */\n static autoDetectFormatWithCst(tomlString: string, syntaxTree?: Iterable<any>): TomlFormat {\n const format = TomlFormat.default();\n format.leadingBom = hasLeadingBom(tomlString);\n // Strip the BOM before other formatting detection to avoid interference.\n const tomlContent = stripLeadingBom(tomlString);\n let cstNodes: any[] = [];\n \n // Detect line ending style\n format.newLine = detectNewline(tomlContent);\n \n // Detect trailing newline count\n format.trailingNewline = countTrailingNewlines(tomlContent);\n \n // Get TOML syntax tree to detect comma and bracket spacing usage patterns\n try {\n // Materialize only when needed so we can traverse the same CST twice.\n cstNodes = Array.isArray(syntaxTree)\n ? syntaxTree\n : Array.from(syntaxTree ?? parseTOML(tomlContent));\n format.trailingComma = detectTrailingComma(cstNodes);\n format.bracketSpacing = detectBracketSpacing(tomlContent, cstNodes);\n } catch (error) {\n // If parsing fails, fall back to defaults\n // This ensures the method is robust against malformed TOML\n format.trailingComma = DEFAULT_TRAILING_COMMA;\n format.bracketSpacing = DEFAULT_BRACKET_SPACING;\n }\n \n // Detect if tabs are used for indentation\n format.useTabsForIndentation = detectTabsForIndentation(tomlContent);\n if (format.useTabsForIndentation) {\n // If tabs are used, indentWidth is effectively 1 (one tab character)\n format.indentWidth = 1;\n } else {\n // Otherwise, detect the number of spaces used for indentation\n format.indentWidth = detectIndentWidth(tomlContent, cstNodes);\n }\n \n \n // inlineTableStart uses default value since auto-detection would require\n // complex analysis of nested table formatting preferences\n format.inlineTableStart = DEFAULT_INLINE_TABLE_START;\n\n // truncateZeroTimeInDates uses default value as well\n // We could always implement detection logic if needed\n // That would imply checking if all dates have no time component in the TOML.\n // However, it's not because all dates have no time component that a new key-value can't be introduced where the time component corresponds to midnight.\n format.truncateZeroTimeInDates = DEFAULT_TRUNCATE_ZERO_TIME_IN_DATES;\n\n // minimumDecimals uses default value (0) — caller must set explicitly\n format.minimumDecimals = DEFAULT_MINIMUM_DECIMALS;\n\n // updateOrder uses default value (false) as well — the existing document's order says\n // nothing about the caller's intent, so this is never auto-detected.\n format.updateOrder = DEFAULT_UPDATE_ORDER;\n\n // Multiline container layout is caller intent, so it is never auto-detected.\n format.multilineTable = DEFAULT_MULTILINE_TABLE;\n format.multilineArray = DEFAULT_MULTILINE_ARRAY;\n\n // Escape sequence case follows the first hex escape found in the document.\n format.escapeSequenceUpperCase = detectEscapeSequenceUpperCase(cstNodes);\n\n return format;\n }\n\n /** @deprecated Use autoDetectFormatWithCst instead. */\n static autoDetectFormatWithAst(tomlString: string, syntaxTree?: Iterable<any>): TomlFormat {\n return TomlFormat.autoDetectFormatWithCst(tomlString, syntaxTree);\n }\n}\n"],"mappings":";;;;;AAIA,MAAa,kBAAkB;AAC/B,MAAa,2BAA2B;AACxC,MAAa,yBAAyB;AACtC,MAAa,0BAA0B;AACvC,MAAa,6BAA6B;AAC1C,MAAa,sCAAsC;AACnD,MAAa,mCAAmC;AAChD,MAAa,uBAAuB;AACpC,MAAa,2BAA2B;AACxC,MAAa,sBAAsB;AACnC,MAAa,uBAAuB;AACpC,MAAa,0BAA0B;AACvC,MAAa,0BAA0B;AACvC,MAAa,qCAAqC;AAMlD,SAAgB,oBAAoB,KAA6B;CAE/D,KAAK,MAAM,QAAQ,KAAK;EACtB,MAAM,SAAS,wBAAwB,IAAI;EAC3C,IAAI,WAAW,MACb,OAAO;CAEX;CAEA;AACF;AAIA,SAAgB,qBAAqB,YAAoB,KAA6B;CAEpF,KAAK,MAAM,QAAQ,KAAK;EACtB,MAAM,SAAS,yBAAyB,MAAM,UAAU;EACxD,IAAI,WAAW,MACb,OAAO;CAEX;CAEA;AACF;AAGA,SAAS,yBAAyB,MAAW,YAAoC;CAC/E,IAAI,CAAC,QAAQ,OAAO,SAAS,UAC3B,OAAO;CAIT,KAAK,KAAK,SAAS,iBAAiB,KAAK,SAAS,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4 @@
1
- //! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
1
+ //! @decimalturn/toml-patch v3.2.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
2
  import { LocalDate, LocalDateTime, LocalTime, OffsetDateTime } from "./date-format.js";
3
3
  import parseTOML from "./parse-toml.js";
4
4
  import { decodeUtf8Bytes, stripLeadingBom } from "./decode-utf8.js";
@@ -1,4 +1,4 @@
1
- //! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
1
+ //! @decimalturn/toml-patch v3.2.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
2
  import { isIterable } from "./utils.js";
3
3
 
4
4
  //#region src/traverse.ts
@@ -1,4 +1,4 @@
1
- //! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
1
+ //! @decimalturn/toml-patch v3.2.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
2
  //#region src/truncate.ts
3
3
  /**
4
4
  * Compares two positions to determine their ordering.
@@ -1,4 +1,4 @@
1
- //! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
1
+ //! @decimalturn/toml-patch v3.2.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
2
  import { hasItem, isDocument, isInlineItem, isKeyValue, isTable, isTableArray } from "./cst.js";
3
3
  import { recalcContainerEnd, shiftNode } from "./writer.js";
4
4
  import { tryFindByPath } from "./find-by-path.js";
package/dist/dev/utils.js CHANGED
@@ -1,4 +1,4 @@
1
- //! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
1
+ //! @decimalturn/toml-patch v3.2.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
2
  //#region src/utils.ts
3
3
  /**
4
4
  * @file Utility functions for the TOML patch library.
@@ -13,6 +13,27 @@ function last(values) {
13
13
  function blank() {
14
14
  return Object.create(null);
15
15
  }
16
+ /**
17
+ * Equality that keeps the sign of zero.
18
+ *
19
+ * `0 === -0` is true, but TOML spells the sign (`0` against `-0.0`), so an edit
20
+ * that only flips the sign would otherwise look like no change at all.
21
+ */
22
+ function sameValue(a, b) {
23
+ return a === b && (typeof a !== "number" || Object.is(a, b));
24
+ }
25
+ const signScratch = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));
26
+ /**
27
+ * Detects a negative NaN through its IEEE 754 sign bit.
28
+ *
29
+ * Arithmetic cannot tell the two apart, but `-nan` is a distinct TOML spelling
30
+ * that round-trips, so the bit pattern is the only way to recognise it.
31
+ */
32
+ function isNegativeNan(value) {
33
+ if (!Number.isNaN(value)) return false;
34
+ signScratch.setFloat64(0, value, true);
35
+ return (signScratch.getUint32(4, true) & 2147483648) !== 0;
36
+ }
16
37
  function isString(value) {
17
38
  return typeof value === "string";
18
39
  }
@@ -160,10 +181,10 @@ function stableStringify(object) {
160
181
  else if (isDate(value)) output.push(JSON.stringify(value.toISOString()));
161
182
  else if (typeof value === "bigint") output.push(value.toString() + "n");
162
183
  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 ? "-" : "+";
184
+ const sign = Number.isNaN(value) ? isNegativeNan(value) ? "-" : "+" : value < 0 ? "-" : "+";
165
185
  output.push(`${sign}${String(value)}`);
166
- } else output.push(JSON.stringify(value));
186
+ } else if (typeof value === "number" && Object.is(value, -0)) output.push("-0");
187
+ else output.push(JSON.stringify(value));
167
188
  }
168
189
  return output.join("");
169
190
  }
@@ -219,5 +240,5 @@ function assertNoLoneSurrogate(value, describe) {
219
240
  }
220
241
 
221
242
  //#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 };
243
+ export { arraysEqual, assertNoLoneSurrogate, blank, datesEqual, has, isBasicString, isBigInt, isBoolean, isDate, isFloat, isInteger, isIterable, isLiteralString, isMultilineBasicString, isMultilineLiteralString, isNegativeNan, isObject, isString, isTemporal, last, merge, sameValue, stableStringify, temporalToTomlString };
223
244
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":[],"sources":["../../src/utils.ts"],"sourcesContent":["/**\n * @file Utility functions for the TOML patch library.\n * @module utils\n */\n\n/**\n * General utility functions\n */\n\nexport function last<TValue>(values: TValue[]): TValue | undefined {\n return values[values.length - 1];\n}\n\nexport type BlankObject = { [key: string]: any };\n\nexport function blank(): BlankObject {\n return Object.create(null);\n}\n\nexport function isString(value: any): value is string {\n return typeof value === 'string';\n}\n\nexport function isInteger(value: any): value is number {\n return typeof value === 'number'\n && value % 1 === 0\n && isFinite(value)\n && !Object.is(value, -0)\n && value >= Number.MIN_SAFE_INTEGER\n && value <= Number.MAX_SAFE_INTEGER;\n}\n\nexport function isBigInt(value: any): value is bigint {\n return typeof value === 'bigint';\n}\n\nexport function isFloat(value: any): value is number {\n return typeof value === 'number' && (!isInteger(value) || !isFinite(value) || Object.is(value, -0));\n}\n\nexport function isBoolean(value: any): value is boolean {\n return typeof value === 'boolean';\n}\n\nexport function isDate(value: any): value is Date {\n return Object.prototype.toString.call(value) === '[object Date]';\n}\n\n/**\n * Duck-type check for Temporal API objects.\n *\n * Works with both the native Temporal (constructor names like\n * \"Temporal.PlainDate\") and the @js-temporal/polyfill (constructor\n * names like \"PlainDate\"). Avoids instanceof issues across realms.\n *\n * Only the four TOML-relevant types are checked:\n * PlainDate, PlainTime, PlainDateTime, ZonedDateTime.\n */\nconst TEMPORAL_TYPE_NAMES = new Set([\n 'Temporal.PlainDate', 'Temporal.PlainTime', 'Temporal.PlainDateTime', 'Temporal.ZonedDateTime',\n 'PlainDate', 'PlainTime', 'PlainDateTime', 'ZonedDateTime'\n]);\n\nexport function isTemporal(value: any): boolean {\n return value != null\n && typeof value === 'object'\n && TEMPORAL_TYPE_NAMES.has(value.constructor?.name)\n && typeof (value as any).equals === 'function';\n}\n\n/**\n * Converts a Temporal object to its TOML-compatible string representation.\n *\n * For ZonedDateTime, this strips the IANA timezone annotation (e.g. [Asia/Kolkata])\n * and normalizes +00:00 to Z, since TOML only supports offset-based timezones.\n * For other Temporal types, this is equivalent to toString().\n */\nexport function temporalToTomlString(value: any): string {\n const name: string = value.constructor?.name ?? '';\n\n if (name === 'Temporal.ZonedDateTime' || name === 'ZonedDateTime') {\n // Reject IANA timezone annotations — TOML only supports offsets.\n const full = value.toString();\n const bracketMatch = full.match(/\\[(.+)\\]$/);\n if (bracketMatch && !/^[+-]\\d{2}:\\d{2}$/.test(bracketMatch[1])) {\n throw new Error(\n `ZonedDateTime with IANA timezone \"${full}\" cannot be represented in TOML. ` +\n 'TOML only supports offset-based timezones (+05:30, Z).'\n );\n }\n // Strip bracket annotation, then normalize +00:00 offset suffix to Z\n return full.replace(/\\[.*\\]$/, '').replace(/(\\+00:00)$/, 'Z');\n }\n\n const raw = value.toString();\n // Reject bracket annotations on non-ZonedDateTime types too\n // (non-ISO calendars like [u-ca=...] are not valid TOML).\n if (/\\[.*\\]/.test(raw)) {\n throw new Error(\n `Temporal value contains unsupported annotation: \"${raw}\". ` +\n 'TOML only supports ISO 8601 calendar.'\n );\n }\n return raw;\n}\n\nexport function isObject(value: any): boolean {\n return value && typeof value === 'object' && !isDate(value) && !isTemporal(value) && !Array.isArray(value);\n}\n\nexport function isIterable<T>(value: any): value is Iterable<T> {\n return value != null && typeof value[Symbol.iterator] === 'function';\n}\n\n/**\n * String type detection functions\n *\n * These functions identify the type of TOML string representation from the raw string.\n * The library preserves the preference for escape sequences by maintaining the original\n * string type (basic vs literal, single-line vs multiline) when possible during patching.\n */\n\nexport function isBasicString(raw: string): boolean {\n return raw.startsWith('\"') && !raw.startsWith('\"\"\"');\n}\n\nexport function isMultilineBasicString(raw: string): boolean {\n return raw.startsWith('\"\"\"');\n}\n\nexport function isLiteralString(raw: string): boolean {\n return raw.startsWith(\"'\") && !raw.startsWith(\"'''\");\n}\n\nexport function isMultilineLiteralString(raw: string): boolean {\n return raw.startsWith(\"'''\");\n}\n\n/**\n * Object and array utilities\n */\n\nexport function has(object: any, key: string): boolean {\n // All objects come from blank() (Object.create(null)) so there is no\n // prototype chain — `key in object` is safe and avoids the slow\n // Object.prototype.hasOwnProperty.call indirection.\n return key in object;\n}\n\nexport function arraysEqual<TItem>(a: TItem[], b: TItem[]): boolean {\n if (a.length !== b.length) return false;\n\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n\n return true;\n}\n\nexport function datesEqual(a: any, b: any): boolean {\n // Temporal objects: compare via toString(). Two ZonedDateTime values\n // with different IANA zones are NOT the same even if their offsets match.\n if (isTemporal(a) && isTemporal(b)) {\n return a.toString() === b.toString();\n }\n // Custom Date subclasses: compare via toISOString()\n if (isDate(a) && isDate(b)) {\n return a.toISOString() === b.toISOString();\n }\n return false;\n}\n\nexport function stableStringify(object: any): string {\n const output: string[] = [];\n const active = new WeakSet<object>();\n const pending: Array<{ value: any } | { text: string } | { leave: object; text: string }> = [{ value: object }];\n\n while (pending.length > 0) {\n const token = pending.pop()!;\n if ('text' in token) {\n output.push(token.text);\n if ('leave' in token) active.delete(token.leave);\n continue;\n }\n\n const value = token.value;\n if (isObject(value)) {\n if (active.has(value)) {\n throw new TypeError('Cannot stableStringify a circular structure');\n }\n active.add(value);\n const keys = Object.keys(value).sort();\n output.push('{');\n pending.push({ leave: value, text: '}' });\n for (let index = keys.length - 1; index >= 0; index--) {\n const key = keys[index];\n if (index < keys.length - 1) pending.push({ text: ',' });\n pending.push({ value: value[key] });\n pending.push({ text: ':' });\n pending.push({ text: JSON.stringify(key) });\n }\n } else if (Array.isArray(value)) {\n if (active.has(value)) {\n throw new TypeError('Cannot stableStringify a circular structure');\n }\n active.add(value);\n output.push('[');\n pending.push({ leave: value, text: ']' });\n for (let index = value.length - 1; index >= 0; index--) {\n if (index < value.length - 1) pending.push({ text: ',' });\n pending.push({ value: value[index] });\n }\n } else if (isTemporal(value)) {\n // Temporal objects use toString() for a stable ISO representation\n output.push(JSON.stringify(value.toString()));\n } else if (isDate(value)) {\n // Custom Date subclasses use toISOString()\n output.push(JSON.stringify(value.toISOString()));\n } else if (typeof value === 'bigint') {\n output.push(value.toString() + 'n');\n } else if (typeof value === 'number' && !Number.isFinite(value)) {\n // NaN, Infinity and -Infinity all round-trip through JSON.stringify as\n // \"null\", so they collapse into one another (and into a literal `null`\n // value) in the diff's stable form — an array like `[1, inf, 2, nan]`\n // then diffs `inf` and `nan` as the same element and removes the wrong\n // one (fuzz seed 22629). Tag them by their IEEE 754 sign bit so every\n // distinct non-finite number (including -NaN vs +NaN) stays unique.\n const buf = new Float64Array([value]);\n const view = new DataView(buf.buffer);\n const sign = view.getUint32(4, true) & 0x80000000 ? '-' : '+';\n output.push(`${sign}${String(value)}`);\n } else {\n output.push(JSON.stringify(value));\n }\n }\n\n return output.join('');\n}\n\nexport function merge<TValue>(target: TValue[], values: TValue[]) {\n // __mutating__: merge values into target\n // Reference: https://dev.to/uilicious/javascript-array-push-is-945x-faster-than-array-concat-1oki\n const original_length = target.length;\n const added_length = values.length;\n target.length = original_length + added_length;\n\n for (let i = 0; i < added_length; i++) {\n target[original_length + i] = values[i];\n }\n}\n\n/**\n * `String.prototype.isWellFormed`, when the runtime has it (Node 20+; this package supports\n * Node 16, so it has to be optional). Returns false exactly when a string contains an unpaired\n * surrogate — the same predicate as `findLoneSurrogate`, but far cheaper.\n * \n * It only yields a boolean, so locating the offending unit for the error message still needs\n * `findLoneSurrogate` — but that only runs on the failing path.\n */\nconst nativeIsWellFormed: ((this: string) => boolean) | undefined =\n typeof String.prototype.isWellFormed === 'function' ? String.prototype.isWellFormed : undefined;\n\n/**\n * Finds the first unpaired surrogate code unit in `value`, if any.\n *\n * JS strings are UTF-16, so an astral character is legitimately stored as a high/low surrogate\n * *pair* — those are fine. An unpaired one is not a Unicode scalar value, so it has no valid\n * UTF-8 encoding and cannot be represented in TOML.\n */\nfunction findLoneSurrogate(value: string): { index: number; code: number } | undefined {\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < 0xd800 || code > 0xdfff) continue;\n\n // A high surrogate is valid only when immediately followed by a low one.\n if (code <= 0xdbff) {\n const next = value.charCodeAt(i + 1); // NaN past the end — fails the range test below\n if (next >= 0xdc00 && next <= 0xdfff) {\n i++; // consume the pair\n continue;\n }\n }\n\n // Either an unpaired high surrogate, or a low surrogate with no high before it (a paired\n // low is always consumed by the branch above).\n return { index: i, code };\n }\n\n return undefined;\n}\n\n/**\n * Throws if `value` contains an unpaired surrogate. `describe` names what is being encoded\n * (e.g. `'String value'`, `'Key \"a\"'`) so the message points at the offending input.\n */\nexport function assertNoLoneSurrogate(value: string, describe: string): void {\n // Fast path for the overwhelmingly common case of a clean string. When the native check is\n // missing we fall through and scan, which is the same work as before.\n if (nativeIsWellFormed !== undefined && nativeIsWellFormed.call(value)) return;\n\n const found = findLoneSurrogate(value);\n if (!found) return;\n\n const hex = found.code.toString(16).toUpperCase().padStart(4, '0');\n throw new Error(\n `${describe} contains a lone surrogate (U+${hex}) at index ${found.index}. ` +\n `Unpaired surrogates are not Unicode scalar values and cannot be encoded as TOML.`\n );\n}\n\n\n"],"mappings":";;;;;;;;;AASA,SAAgB,KAAa,QAAsC;CACjE,OAAO,OAAO,OAAO,SAAS;AAChC;AAIA,SAAgB,QAAqB;CACnC,OAAO,OAAO,OAAO,IAAI;AAC3B;AAEA,SAAgB,SAAS,OAA6B;CACpD,OAAO,OAAO,UAAU;AAC1B;AAEA,SAAgB,UAAU,OAA6B;CACrD,OAAO,OAAO,UAAU,YACnB,QAAQ,MAAM,KACd,SAAS,KAAK,KACd,CAAC,OAAO,GAAG,OAAO,EAAE,KACpB,SAAS,OAAO,oBAChB,SAAS,OAAO;AACvB;AAEA,SAAgB,SAAS,OAA6B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names":[],"sources":["../../src/utils.ts"],"sourcesContent":["/**\n * @file Utility functions for the TOML patch library.\n * @module utils\n */\n\n/**\n * General utility functions\n */\n\nexport function last<TValue>(values: TValue[]): TValue | undefined {\n return values[values.length - 1];\n}\n\nexport type BlankObject = { [key: string]: any };\n\nexport function blank(): BlankObject {\n return Object.create(null);\n}\n\n/**\n * Equality that keeps the sign of zero.\n *\n * `0 === -0` is true, but TOML spells the sign (`0` against `-0.0`), so an edit\n * that only flips the sign would otherwise look like no change at all.\n */\nexport function sameValue(a: any, b: any): boolean {\n return a === b && (typeof a !== 'number' || Object.is(a, b));\n}\n\n// Scratch buffer for reading the sign bit of a number. The value has to be\n// written through DataView: `new Float64Array([value])` is not reliable for\n// this, because the engine occasionally canonicalises the NaN payload on the\n// way in, and a `-nan` then reads as positive (about one call in twenty\n// thousand, which is enough to make NaN handling intermittent).\nconst signScratch = new DataView(new ArrayBuffer(8));\n\n/**\n * Detects a negative NaN through its IEEE 754 sign bit.\n *\n * Arithmetic cannot tell the two apart, but `-nan` is a distinct TOML spelling\n * that round-trips, so the bit pattern is the only way to recognise it.\n */\nexport function isNegativeNan(value: number): boolean {\n if (!Number.isNaN(value)) return false;\n signScratch.setFloat64(0, value, true);\n return (signScratch.getUint32(4, true) & 0x80000000) !== 0;\n}\n\nexport function isString(value: any): value is string {\n return typeof value === 'string';\n}\n\nexport function isInteger(value: any): value is number {\n return typeof value === 'number'\n && value % 1 === 0\n && isFinite(value)\n && !Object.is(value, -0)\n && value >= Number.MIN_SAFE_INTEGER\n && value <= Number.MAX_SAFE_INTEGER;\n}\n\nexport function isBigInt(value: any): value is bigint {\n return typeof value === 'bigint';\n}\n\nexport function isFloat(value: any): value is number {\n return typeof value === 'number' && (!isInteger(value) || !isFinite(value) || Object.is(value, -0));\n}\n\nexport function isBoolean(value: any): value is boolean {\n return typeof value === 'boolean';\n}\n\nexport function isDate(value: any): value is Date {\n return Object.prototype.toString.call(value) === '[object Date]';\n}\n\n/**\n * Duck-type check for Temporal API objects.\n *\n * Works with both the native Temporal (constructor names like\n * \"Temporal.PlainDate\") and the @js-temporal/polyfill (constructor\n * names like \"PlainDate\"). Avoids instanceof issues across realms.\n *\n * Only the four TOML-relevant types are checked:\n * PlainDate, PlainTime, PlainDateTime, ZonedDateTime.\n */\nconst TEMPORAL_TYPE_NAMES = new Set([\n 'Temporal.PlainDate', 'Temporal.PlainTime', 'Temporal.PlainDateTime', 'Temporal.ZonedDateTime',\n 'PlainDate', 'PlainTime', 'PlainDateTime', 'ZonedDateTime'\n]);\n\nexport function isTemporal(value: any): boolean {\n return value != null\n && typeof value === 'object'\n && TEMPORAL_TYPE_NAMES.has(value.constructor?.name)\n && typeof (value as any).equals === 'function';\n}\n\n/**\n * Converts a Temporal object to its TOML-compatible string representation.\n *\n * For ZonedDateTime, this strips the IANA timezone annotation (e.g. [Asia/Kolkata])\n * and normalizes +00:00 to Z, since TOML only supports offset-based timezones.\n * For other Temporal types, this is equivalent to toString().\n */\nexport function temporalToTomlString(value: any): string {\n const name: string = value.constructor?.name ?? '';\n\n if (name === 'Temporal.ZonedDateTime' || name === 'ZonedDateTime') {\n // Reject IANA timezone annotations — TOML only supports offsets.\n const full = value.toString();\n const bracketMatch = full.match(/\\[(.+)\\]$/);\n if (bracketMatch && !/^[+-]\\d{2}:\\d{2}$/.test(bracketMatch[1])) {\n throw new Error(\n `ZonedDateTime with IANA timezone \"${full}\" cannot be represented in TOML. ` +\n 'TOML only supports offset-based timezones (+05:30, Z).'\n );\n }\n // Strip bracket annotation, then normalize +00:00 offset suffix to Z\n return full.replace(/\\[.*\\]$/, '').replace(/(\\+00:00)$/, 'Z');\n }\n\n const raw = value.toString();\n // Reject bracket annotations on non-ZonedDateTime types too\n // (non-ISO calendars like [u-ca=...] are not valid TOML).\n if (/\\[.*\\]/.test(raw)) {\n throw new Error(\n `Temporal value contains unsupported annotation: \"${raw}\". ` +\n 'TOML only supports ISO 8601 calendar.'\n );\n }\n return raw;\n}\n\nexport function isObject(value: any): boolean {\n return value && typeof value === 'object' && !isDate(value) && !isTemporal(value) && !Array.isArray(value);\n}\n\nexport function isIterable<T>(value: any): value is Iterable<T> {\n return value != null && typeof value[Symbol.iterator] === 'function';\n}\n\n/**\n * String type detection functions\n *\n * These functions identify the type of TOML string representation from the raw string.\n * The library preserves the preference for escape sequences by maintaining the original\n * string type (basic vs literal, single-line vs multiline) when possible during patching.\n */\n\nexport function isBasicString(raw: string): boolean {\n return raw.startsWith('\"') && !raw.startsWith('\"\"\"');\n}\n\nexport function isMultilineBasicString(raw: string): boolean {\n return raw.startsWith('\"\"\"');\n}\n\nexport function isLiteralString(raw: string): boolean {\n return raw.startsWith(\"'\") && !raw.startsWith(\"'''\");\n}\n\nexport function isMultilineLiteralString(raw: string): boolean {\n return raw.startsWith(\"'''\");\n}\n\n/**\n * Object and array utilities\n */\n\nexport function has(object: any, key: string): boolean {\n // All objects come from blank() (Object.create(null)) so there is no\n // prototype chain — `key in object` is safe and avoids the slow\n // Object.prototype.hasOwnProperty.call indirection.\n return key in object;\n}\n\nexport function arraysEqual<TItem>(a: TItem[], b: TItem[]): boolean {\n if (a.length !== b.length) return false;\n\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n\n return true;\n}\n\nexport function datesEqual(a: any, b: any): boolean {\n // Temporal objects: compare via toString(). Two ZonedDateTime values\n // with different IANA zones are NOT the same even if their offsets match.\n if (isTemporal(a) && isTemporal(b)) {\n return a.toString() === b.toString();\n }\n // Custom Date subclasses: compare via toISOString()\n if (isDate(a) && isDate(b)) {\n return a.toISOString() === b.toISOString();\n }\n return false;\n}\n\nexport function stableStringify(object: any): string {\n const output: string[] = [];\n const active = new WeakSet<object>();\n const pending: Array<{ value: any } | { text: string } | { leave: object; text: string }> = [{ value: object }];\n\n while (pending.length > 0) {\n const token = pending.pop()!;\n if ('text' in token) {\n output.push(token.text);\n if ('leave' in token) active.delete(token.leave);\n continue;\n }\n\n const value = token.value;\n if (isObject(value)) {\n if (active.has(value)) {\n throw new TypeError('Cannot stableStringify a circular structure');\n }\n active.add(value);\n const keys = Object.keys(value).sort();\n output.push('{');\n pending.push({ leave: value, text: '}' });\n for (let index = keys.length - 1; index >= 0; index--) {\n const key = keys[index];\n if (index < keys.length - 1) pending.push({ text: ',' });\n pending.push({ value: value[key] });\n pending.push({ text: ':' });\n pending.push({ text: JSON.stringify(key) });\n }\n } else if (Array.isArray(value)) {\n if (active.has(value)) {\n throw new TypeError('Cannot stableStringify a circular structure');\n }\n active.add(value);\n output.push('[');\n pending.push({ leave: value, text: ']' });\n for (let index = value.length - 1; index >= 0; index--) {\n if (index < value.length - 1) pending.push({ text: ',' });\n pending.push({ value: value[index] });\n }\n } else if (isTemporal(value)) {\n // Temporal objects use toString() for a stable ISO representation\n output.push(JSON.stringify(value.toString()));\n } else if (isDate(value)) {\n // Custom Date subclasses use toISOString()\n output.push(JSON.stringify(value.toISOString()));\n } else if (typeof value === 'bigint') {\n output.push(value.toString() + 'n');\n } else if (typeof value === 'number' && !Number.isFinite(value)) {\n // NaN, Infinity and -Infinity all round-trip through JSON.stringify as\n // \"null\", so they collapse into one another (and into a literal `null`\n // value) in the diff's stable form — an array like `[1, inf, 2, nan]`\n // then diffs `inf` and `nan` as the same element and removes the wrong\n // one (fuzz seed 22629). Tag them by their IEEE 754 sign bit so every\n // distinct non-finite number (including -NaN vs +NaN) stays unique.\n const sign = Number.isNaN(value)\n ? (isNegativeNan(value) ? '-' : '+')\n : (value < 0 ? '-' : '+');\n output.push(`${sign}${String(value)}`);\n } else if (typeof value === 'number' && Object.is(value, -0)) {\n // JSON.stringify(-0) is \"0\", so negative zero would compare equal to a\n // plain zero and an edit that only flips the sign would be skipped.\n // TOML spells the sign (`0` against `-0.0`), so keep them apart here too.\n output.push('-0');\n } else {\n output.push(JSON.stringify(value));\n }\n }\n\n return output.join('');\n}\n\nexport function merge<TValue>(target: TValue[], values: TValue[]) {\n // __mutating__: merge values into target\n // Reference: https://dev.to/uilicious/javascript-array-push-is-945x-faster-than-array-concat-1oki\n const original_length = target.length;\n const added_length = values.length;\n target.length = original_length + added_length;\n\n for (let i = 0; i < added_length; i++) {\n target[original_length + i] = values[i];\n }\n}\n\n/**\n * `String.prototype.isWellFormed`, when the runtime has it (Node 20+; this package supports\n * Node 16, so it has to be optional). Returns false exactly when a string contains an unpaired\n * surrogate — the same predicate as `findLoneSurrogate`, but far cheaper.\n * \n * It only yields a boolean, so locating the offending unit for the error message still needs\n * `findLoneSurrogate` — but that only runs on the failing path.\n */\nconst nativeIsWellFormed: ((this: string) => boolean) | undefined =\n typeof String.prototype.isWellFormed === 'function' ? String.prototype.isWellFormed : undefined;\n\n/**\n * Finds the first unpaired surrogate code unit in `value`, if any.\n *\n * JS strings are UTF-16, so an astral character is legitimately stored as a high/low surrogate\n * *pair* — those are fine. An unpaired one is not a Unicode scalar value, so it has no valid\n * UTF-8 encoding and cannot be represented in TOML.\n */\nfunction findLoneSurrogate(value: string): { index: number; code: number } | undefined {\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code < 0xd800 || code > 0xdfff) continue;\n\n // A high surrogate is valid only when immediately followed by a low one.\n if (code <= 0xdbff) {\n const next = value.charCodeAt(i + 1); // NaN past the end — fails the range test below\n if (next >= 0xdc00 && next <= 0xdfff) {\n i++; // consume the pair\n continue;\n }\n }\n\n // Either an unpaired high surrogate, or a low surrogate with no high before it (a paired\n // low is always consumed by the branch above).\n return { index: i, code };\n }\n\n return undefined;\n}\n\n/**\n * Throws if `value` contains an unpaired surrogate. `describe` names what is being encoded\n * (e.g. `'String value'`, `'Key \"a\"'`) so the message points at the offending input.\n */\nexport function assertNoLoneSurrogate(value: string, describe: string): void {\n // Fast path for the overwhelmingly common case of a clean string. When the native check is\n // missing we fall through and scan, which is the same work as before.\n if (nativeIsWellFormed !== undefined && nativeIsWellFormed.call(value)) return;\n\n const found = findLoneSurrogate(value);\n if (!found) return;\n\n const hex = found.code.toString(16).toUpperCase().padStart(4, '0');\n throw new Error(\n `${describe} contains a lone surrogate (U+${hex}) at index ${found.index}. ` +\n `Unpaired surrogates are not Unicode scalar values and cannot be encoded as TOML.`\n );\n}\n\n\n"],"mappings":";;;;;;;;;AASA,SAAgB,KAAa,QAAsC;CACjE,OAAO,OAAO,OAAO,SAAS;AAChC;AAIA,SAAgB,QAAqB;CACnC,OAAO,OAAO,OAAO,IAAI;AAC3B;;;;;;;AAQA,SAAgB,UAAU,GAAQ,GAAiB;CACjD,OAAO,MAAM,MAAM,OAAO,MAAM,YAAY,OAAO,GAAG,GAAG,CAAC;AAC5D;AAOA,MAAM,8BAAc,IAAI,yBAAS,IAAI,YAAY,CAAC,CAAC;;;;;;;AAQnD,SAAgB,cAAc,OAAwB;CACpD,IAAI,CAAC,OAAO,MAAM,KAAK,GAAG,OAAO;CACjC,YAAY,WAAW,GAAG,OAAO,IAAI;CACrC,QAAQ,YAAY,UAAU,GAAG,IAAI,IAAI,gBAAgB;AAC3D;AAEA,SAAgB,SAAS,OAA6B;CACpD,OAAO,OAAO,UAAU;AAC1B;AAEA,SAAgB,UAAU,OAA6B;CACrD,OAAO,OAAO,UAAU,YACnB,QAAQ,MAAM,KACd,SAAS,KAAK,KACd,CAAC,OAAO,GAAG,OAAO,EAAE,KACpB,SAAS,OAAO,oBAChB,SAAS,OAAO;AACvB;AAEA,SAAgB,SAAS,OAA6B;CACpD,OAAO,OAAO,UAAU;AAC1B;AAEA,SAAgB,QAAQ,OAA6B;CACnD,OAAO,OAAO,UAAU,aAAa,CAAC,UAAU,KAAK,KAAK,CAAC,SAAS,KAAK,KAAK,OAAO,GAAG,OAAO,EAAE;AACnG;AAEA,SAAgB,UAAU,OAA8B;CACtD,OAAO,OAAO,UAAU;AAC1B;AAEA,SAAgB,OAAO,OAA2B;CAChD,OAAO,OAAO,UAAU,SAAS,KAAK,KAAK,MAAM;AACnD;;;;;;;;;;;AAYA,MAAM,sCAAsB,IAAI,IAAI;CAClC;CAAsB;CAAsB;CAA0B;CACtE;CAAa;C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B,OAAO,SAAS,kBAAkB;CAElC,KAAK,IAAI,IAAI,GAAG,IAAI,cAAc,KAChC,OAAO,kBAAkB,KAAK,OAAO;AAEzC;;;;;;;;;AAUA,MAAM,qBACJ,OAAO,OAAO,UAAU,iBAAiB,aAAa,OAAO,UAAU,eAAe;;;;;;;;AASxF,SAAS,kBAAkB,OAA4D;CACrF,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,OAAO,MAAM,WAAW,CAAC;EAC/B,IAAI,OAAO,SAAU,OAAO,OAAQ;EAGpC,IAAI,QAAQ,OAAQ;GAClB,MAAM,OAAO,MAAM,WAAW,IAAI,CAAC;GACnC,IAAI,QAAQ,SAAU,QAAQ,OAAQ;IACpC;IACA;GACF;EACF;EAIA,OAAO;GAAE,OAAO;GAAG;EAAK;CAC1B;AAGF;;;;;AAMA,SAAgB,sBAAsB,OAAe,UAAwB;CAG3E,IAAI,uBAAuB,UAAa,mBAAmB,KAAK,KAAK,GAAG;CAExE,MAAM,QAAQ,kBAAkB,KAAK;CACrC,IAAI,CAAC,OAAO;CAEZ,MAAM,MAAM,MAAM,KAAK,SAAS,EAAE,CAAC,CAAC,YAAY,CAAC,CAAC,SAAS,GAAG,GAAG;CACjE,MAAM,IAAI,MACR,GAAG,SAAS,gCAAgC,IAAI,aAAa,MAAM,MAAM,mFAE3E;AACF"}
@@ -1,4 +1,4 @@
1
- //! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
1
+ //! @decimalturn/toml-patch v3.2.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
2
  import { hasItem, hasItems, isBlock, isComment, isDocument, isInlineArray, isInlineItem, isInlineTable, isKeyValue, isTable, isTableArray } from "./cst.js";
3
3
  import { clonePosition, getSpan } from "./location.js";
4
4
  import { getCommaSpace } from "./inline-comma-space.js";