@decimalturn/toml-patch 3.2.0 → 3.2.1-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 (82) hide show
  1. package/dist/dev/comment-alignment.js +372 -0
  2. package/dist/dev/comment-alignment.js.map +1 -0
  3. package/dist/dev/comment-ownership.js +660 -0
  4. package/dist/dev/comment-ownership.js.map +1 -0
  5. package/dist/dev/cst-source.js +118 -0
  6. package/dist/dev/cst-source.js.map +1 -0
  7. package/dist/dev/cst.js +68 -0
  8. package/dist/dev/cst.js.map +1 -0
  9. package/dist/dev/cursor.js +66 -0
  10. package/dist/dev/cursor.js.map +1 -0
  11. package/dist/dev/date-format.js +196 -0
  12. package/dist/dev/date-format.js.map +1 -0
  13. package/dist/dev/decode-utf8.js +27 -0
  14. package/dist/dev/decode-utf8.js.map +1 -0
  15. package/dist/dev/diff-lite.js +123 -0
  16. package/dist/dev/diff-lite.js.map +1 -0
  17. package/dist/dev/diff.js +265 -0
  18. package/dist/dev/diff.js.map +1 -0
  19. package/dist/dev/encode-lite.js +193 -0
  20. package/dist/dev/encode-lite.js.map +1 -0
  21. package/dist/dev/escape-preference.js +166 -0
  22. package/dist/dev/escape-preference.js.map +1 -0
  23. package/dist/dev/find-by-path.js +111 -0
  24. package/dist/dev/find-by-path.js.map +1 -0
  25. package/dist/dev/formatter.js +298 -0
  26. package/dist/dev/formatter.js.map +1 -0
  27. package/dist/dev/generate.js +465 -0
  28. package/dist/dev/generate.js.map +1 -0
  29. package/dist/dev/inline-comma-space.js +13 -0
  30. package/dist/dev/inline-comma-space.js.map +1 -0
  31. package/dist/dev/inline-format.js +106 -0
  32. package/dist/dev/inline-format.js.map +1 -0
  33. package/dist/dev/inline-layout.js +107 -0
  34. package/dist/dev/inline-layout.js.map +1 -0
  35. package/dist/dev/line-ending-backslash.js +320 -0
  36. package/dist/dev/line-ending-backslash.js.map +1 -0
  37. package/dist/dev/literal-string.js +46 -0
  38. package/dist/dev/literal-string.js.map +1 -0
  39. package/dist/dev/location.js +104 -0
  40. package/dist/dev/location.js.map +1 -0
  41. package/dist/dev/parse-error.js +27 -0
  42. package/dist/dev/parse-error.js.map +1 -0
  43. package/dist/dev/parse-js.js +150 -0
  44. package/dist/dev/parse-js.js.map +1 -0
  45. package/dist/dev/parse-string.js +122 -0
  46. package/dist/dev/parse-string.js.map +1 -0
  47. package/dist/dev/parse-toml.js +714 -0
  48. package/dist/dev/parse-toml.js.map +1 -0
  49. package/dist/dev/patch-lite.js +4 -0
  50. package/dist/dev/patch-lite2.js +96 -0
  51. package/dist/dev/patch-lite2.js.map +1 -0
  52. package/dist/dev/patch.js +2652 -0
  53. package/dist/dev/patch.js.map +1 -0
  54. package/dist/dev/smol-toml-date.js +61 -0
  55. package/dist/dev/smol-toml-date.js.map +1 -0
  56. package/dist/dev/to-js.js +303 -0
  57. package/dist/dev/to-js.js.map +1 -0
  58. package/dist/dev/to-toml.js +874 -0
  59. package/dist/dev/to-toml.js.map +1 -0
  60. package/dist/dev/tokenizer.js +225 -0
  61. package/dist/dev/tokenizer.js.map +1 -0
  62. package/dist/dev/toml-document.js +220 -0
  63. package/dist/dev/toml-document.js.map +1 -0
  64. package/dist/dev/toml-format.js +528 -0
  65. package/dist/dev/toml-format.js.map +1 -0
  66. package/dist/dev/toml-patch.js +94 -0
  67. package/dist/dev/toml-patch.js.map +1 -0
  68. package/dist/dev/traverse.js +61 -0
  69. package/dist/dev/traverse.js.map +1 -0
  70. package/dist/dev/truncate.js +64 -0
  71. package/dist/dev/truncate.js.map +1 -0
  72. package/dist/dev/update-order.js +235 -0
  73. package/dist/dev/update-order.js.map +1 -0
  74. package/dist/dev/utils.js +244 -0
  75. package/dist/dev/utils.js.map +1 -0
  76. package/dist/dev/writer.js +758 -0
  77. package/dist/dev/writer.js.map +1 -0
  78. package/package.json +13 -104
  79. package/LICENSE +0 -22
  80. package/README.md +0 -200
  81. package/dist/patch-lite.js +0 -20
  82. package/dist/toml-patch.js +0 -84
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toml-document.js","names":[],"sources":["../../src/toml-document.ts"],"sourcesContent":["import parseTOML, { continueParsingTOML } from './parse-toml';\nimport toJS from './to-js';\nimport { TomlFormat } from './toml-format';\nimport { Block } from './cst';\nimport { patchCst } from './patch';\nimport { attachSources } from './cst-source';\nimport { detectNewline, resolveTomlFormat } from './toml-format';\nimport { truncateCst } from './truncate';\nimport type { ParseOptions, IntegersAsBigInt } from './parse-options';\nimport { decodeUtf8Bytes, hasLeadingBom, stripLeadingBom, UTF8_BOM } from './decode-utf8';\nimport { isObject } from './utils';\n\n/**\n * TomlDocument encapsulates a TOML CST and provides methods to interact with it.\n */\nexport class TomlDocument {\n private _cst: Block[];\n private _currentTomlString: string;\n private _format: TomlFormat;\n private _integersAsBigInt: IntegersAsBigInt;\n private _temporal: boolean;\n\n /**\n * Initializes the TomlDocument with TOML source, parsing it into a CST.\n *\n * When bytes are provided, they are decoded as UTF-8 in fatal mode.\n * This rejects invalid UTF-8 sequences before parsing.\n *\n * @param tomlSource - The TOML source to parse (string or raw UTF-8 bytes)\n * @param options - Optional parse options\n * @param options.integersAsBigInt - Controls bigint vs number for TOML integers\n * @param options.temporal - When true, returns Temporal objects for date/time values\n */\n constructor(tomlSource: string | Uint8Array, options?: ParseOptions) {\n const sourceString = typeof tomlSource === 'string'\n ? tomlSource\n : decodeUtf8Bytes(tomlSource);\n const tomlString = stripLeadingBom(sourceString);\n\n this._currentTomlString = tomlString;\n this._cst = Array.from(parseTOML(tomlString));\n this._integersAsBigInt = options?.integersAsBigInt ?? 'asNeeded';\n this._temporal = options?.temporal ?? false;\n // Auto-detect formatting preferences from the original TOML string\n this._format = TomlFormat.autoDetectFormatWithCst(sourceString, this._cst);\n }\n\n get toTomlString(): string {\n return this._format.leadingBom ? `${UTF8_BOM}${this._currentTomlString}` : this._currentTomlString;\n }\n\n /**\n * Returns the JavaScript object representation of the TOML document.\n */\n get toJsObject(): any {\n const jsObject = toJS(this._cst, this._currentTomlString, {\n integersAsBigInt: this._integersAsBigInt,\n temporal: this._temporal\n });\n // When temporal is enabled, Temporal objects are already returned — no conversion needed.\n // When temporal is disabled, convert custom date classes to regular JavaScript Date objects.\n if (this._temporal) {\n return jsObject;\n }\n return convertCustomDateClasses(jsObject);\n }\n\n /**\n * Returns the internal CST (for testing purposes).\n * @internal\n */\n get cst(): Block[] {\n return this._cst;\n }\n\n /**\n * Applies a patch to the current CST using a modified JS object.\n * Updates the internal CST. Use toTomlString getter to retrieve the updated TOML string.\n *\n * @param updatedObject - The modified JS object to patch with\n * @param format - Optional formatting options\n */\n patch(updatedObject: any, format?: Partial<TomlFormat> | TomlFormat) : void {\n\n const fmt = resolveTomlFormat(format, this._format);\n\n const sourceBefore = this._currentTomlString;\n\n // Only worth deriving the pre-patch values when a stripped date could\n // actually be present; temporal mode hands out Temporal objects untouched.\n if (!this._temporal && hasPlainDate(updatedObject)) {\n const originalObject = toJS(this._cst, sourceBefore, {\n integersAsBigInt: this._integersAsBigInt,\n temporal: false\n });\n updatedObject = restoreDateRepresentations(updatedObject, originalObject);\n }\n\n const indentWidthExplicit = format instanceof TomlFormat ||\n (format != null && Object.prototype.hasOwnProperty.call(format, 'indentWidth'));\n const trailingCommaExplicit = format instanceof TomlFormat ||\n (format != null && Object.prototype.hasOwnProperty.call(format, 'trailingComma'));\n attachSources(this._cst, sourceBefore);\n const result = patchCst(\n this._cst,\n updatedObject,\n fmt,\n indentWidthExplicit,\n trailingCommaExplicit\n );\n this._cst = Array.from(parseTOML(result.tomlString));\n this._format = fmt;\n this._currentTomlString = result.tomlString;\n }\n\n /**\n * Updates the internal document by supplying a modified tomlString.\n * Use toJsObject getter to retrieve the updated JS object representation.\n * @param tomlString - The modified TOML string to update with\n */\n update(tomlString: string): void {\n const tomlContent = stripLeadingBom(tomlString);\n\n if (tomlContent === this._currentTomlString) {\n this._format.leadingBom = hasLeadingBom(tomlString);\n return;\n }\n\n // Now, let's check where the first difference is\n const existingLines = this._currentTomlString.split(this._format.newLine);\n const newLineChar = detectNewline(tomlContent);\n const newTextLines = tomlContent.split(newLineChar);\n let firstDiffLineIndex = 0;\n while (\n firstDiffLineIndex < existingLines.length &&\n firstDiffLineIndex < newTextLines.length &&\n existingLines[firstDiffLineIndex] === newTextLines[firstDiffLineIndex]\n ) {\n firstDiffLineIndex++;\n }\n\n // Calculate the 1-based line number and 0-based column where the first difference occurs\n \n let firstDiffColumn = 0;\n \n // If we're within the bounds of both arrays, find the column where they differ\n if (firstDiffLineIndex < existingLines.length && firstDiffLineIndex < newTextLines.length) {\n const existingLine = existingLines[firstDiffLineIndex];\n const newLine = newTextLines[firstDiffLineIndex];\n \n // Find the first character position where the lines differ\n for (let i = 0; i < Math.max(existingLine.length, newLine.length); i++) {\n if (existingLine[i] !== newLine[i]) {\n firstDiffColumn = i;\n break;\n }\n }\n }\n\n let firstDiffLine = firstDiffLineIndex + 1; // Convert to 1-based\n const { truncatedCst, lastEndPosition } = truncateCst(this._cst, firstDiffLine, firstDiffColumn);\n\n // Determine where to continue parsing from in the new string\n // If lastEndPosition exists, continue from there; otherwise from the start of the document\n const continueFromLine = lastEndPosition ? lastEndPosition.line : 1;\n const continueFromColumn = lastEndPosition ? lastEndPosition.column + 1 : 0;\n\n // Based on the first difference, we can re-parse only the affected part\n // We will need to supply the remaining string after where the CST was truncated\n const remainingLines = newTextLines.slice(continueFromLine - 1);\n \n // If there's a partial line match, we need to extract only the part after the continuation column\n if (remainingLines.length > 0 && continueFromColumn > 0) {\n remainingLines[0] = remainingLines[0].substring(continueFromColumn);\n }\n \n const remainingToml = remainingLines.join(this._format.newLine);\n \n this._cst = Array.from(continueParsingTOML(truncatedCst, remainingToml, {\n line: continueFromLine,\n column: continueFromColumn\n }));\n this._currentTomlString = tomlContent;\n \n // Update the auto-detected format with the new string's characteristics\n this._format = TomlFormat.autoDetectFormatWithCst(tomlString, this._cst);\n }\n\n /**\n * Overwrites the internal syntax tree by fully re-parsing the supplied tomlString.\n * This is simpler but slower than update() which uses incremental parsing.\n * @param tomlString - The TOML string to overwrite with\n */\n overwrite(tomlString: string): void {\n const tomlContent = stripLeadingBom(tomlString);\n\n if (tomlContent === this._currentTomlString) {\n this._format.leadingBom = hasLeadingBom(tomlString);\n return;\n }\n\n // Re-parse the entire document\n this._cst = Array.from(parseTOML(tomlContent));\n this._currentTomlString = tomlContent;\n \n // Update the auto-detected format with the new string's characteristics\n this._format = TomlFormat.autoDetectFormatWithCst(tomlString, this._cst);\n }\n}\n\n/**\n * True when `value` holds a plain `Date` anywhere, i.e. one of the objects\n * toJsObject() produced by stripping a TOML date class. Used to skip the work\n * in restoreDateRepresentations() for the common case of a document with no\n * dates in it. Cycle-safe.\n */\nfunction hasPlainDate(value: any, seen: WeakSet<object> = new WeakSet()): boolean {\n if (value instanceof Date) return value.constructor === Date;\n if (!value || typeof value !== 'object') return false;\n if (seen.has(value)) return false;\n seen.add(value);\n if (Array.isArray(value)) return value.some(item => hasPlainDate(item, seen));\n return Object.keys(value).some(key => hasPlainDate(value[key], seen));\n}\n\n/**\n * Re-attaches the TOML date representation that toJsObject() strips.\n *\n * toJsObject() deliberately hands out plain `Date` objects so that callers get\n * the standard Date contract, notably a standard toISOString(). But the writer\n * derives a value's TOML text from toISOString(), and the TOML date classes\n * override it to return the original spelling. A plain Date handed back in\n * therefore writes as a full offset date-time, so read-modify-write turned\n * `1986-03-02` into `1986-03-02T00:00:00.000Z` whenever the surrounding node was\n * rewritten rather than preserved from the CST.\n *\n * Where the caller left a date alone (still a plain Date, same instant), the\n * original typed instance goes back in so the original spelling is written. A\n * date whose instant actually changed is left as-is: only the caller knows\n * whether a new instant is still meant to be a local date, and they can say so\n * by passing LocalDate / LocalTime / LocalDateTime / OffsetDateTime, which are\n * exported for that purpose. Instances of those classes are never touched.\n *\n * The caller's object is not mutated; a node is copied only when something\n * beneath it changed, so an untouched tree is returned by reference.\n */\nfunction restoreDateRepresentations(updated: any, original: any, seen: WeakSet<object> = new WeakSet()): any {\n if (updated instanceof Date) {\n const erased = updated.constructor === Date\n && original instanceof Date\n && original.constructor !== Date\n && original.getTime() === updated.getTime();\n return erased ? original : updated;\n }\n if (!updated || typeof updated !== 'object' || seen.has(updated)) return updated;\n seen.add(updated);\n\n if (Array.isArray(updated)) {\n if (!Array.isArray(original)) return updated;\n let changed = false;\n const restored = updated.map((item, index) => {\n const next = restoreDateRepresentations(item, original[index], seen);\n if (next !== item) changed = true;\n return next;\n });\n return changed ? restored : updated;\n }\n\n if (!isObject(original)) return updated;\n let changed = false;\n const restored: Record<string, any> = {};\n for (const key of Object.keys(updated)) {\n const value = updated[key];\n const next = restoreDateRepresentations(value, original[key], seen);\n restored[key] = next;\n if (next !== value) changed = true;\n }\n return changed ? restored : updated;\n}\n\n/**\n * Recursively converts custom date classes to regular JavaScript Date objects.\n * This ensures that the toJsObject property returns standard Date objects\n * while preserving the custom classes internally for TOML formatting.\n */\nfunction convertCustomDateClasses(obj: any): any {\n if (obj instanceof Date) {\n // Convert custom date classes to regular Date objects\n return new Date(obj.getTime());\n } else if (Array.isArray(obj)) {\n return obj.map(convertCustomDateClasses);\n } else if (obj && typeof obj === 'object') {\n const result: any = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = convertCustomDateClasses(value);\n }\n return result;\n }\n return obj;\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,IAAa,eAAb,MAA0B;CACxB,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;;;;;;;;;;;;CAaR,YAAY,YAAiC,SAAwB;EACnE,MAAM,eAAe,OAAO,eAAe,WACvC,aACA,gBAAgB,UAAU;EAC9B,MAAM,aAAa,gBAAgB,YAAY;EAE/C,KAAK,qBAAqB;EAC1B,KAAK,OAAO,MAAM,KAAK,UAAU,UAAU,CAAC;EAC5C,KAAK,uEAAoB,QAAS,qBAAoB;EACtD,KAAK,+DAAY,QAAS,aAAY;EAEtC,KAAK,UAAU,WAAW,wBAAwB,cAAc,KAAK,IAAI;C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AO,UAAU;CAChC;CACA,OAAO,UAAU,WAAW;AAC9B;;;;;;AAOA,SAAS,yBAAyB,KAAe;CAC/C,IAAI,eAAe,MAEjB,OAAO,IAAI,KAAK,IAAI,QAAQ,CAAC;MACxB,IAAI,MAAM,QAAQ,GAAG,GAC1B,OAAO,IAAI,IAAI,wBAAwB;MAClC,IAAI,OAAO,OAAO,QAAQ,UAAU;EACzC,MAAM,SAAc,CAAC;EACrB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,GAAG,GAC3C,OAAO,OAAO,yBAAyB,KAAK;EAE9C,OAAO;CACT;CACA,OAAO;AACT"}
@@ -0,0 +1,528 @@
1
+ //! @decimalturn/toml-patch v3.2.1 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
+ import parseTOML from "./parse-toml.js";
3
+ import { hasLeadingBom, stripLeadingBom } from "./decode-utf8.js";
4
+
5
+ //#region src/toml-format.ts
6
+ const DEFAULT_NEWLINE = "\n";
7
+ const DEFAULT_TRAILING_NEWLINE = 1;
8
+ const DEFAULT_TRAILING_COMMA = false;
9
+ const DEFAULT_BRACKET_SPACING = true;
10
+ const DEFAULT_INLINE_TABLE_START = 1;
11
+ const DEFAULT_TRUNCATE_ZERO_TIME_IN_DATES = false;
12
+ const DEFAULT_USE_TABS_FOR_INDENTATION = false;
13
+ const DEFAULT_INDENT_WIDTH = 2;
14
+ const DEFAULT_MINIMUM_DECIMALS = 0;
15
+ const DEFAULT_LEADING_BOM = false;
16
+ const DEFAULT_UPDATE_ORDER = false;
17
+ const DEFAULT_MULTILINE_TABLE = "auto";
18
+ const DEFAULT_MULTILINE_ARRAY = "auto";
19
+ const DEFAULT_ESCAPE_SEQUENCE_UPPER_CASE = true;
20
+ function detectTrailingComma(cst) {
21
+ for (const item of cst) {
22
+ const result = findTrailingCommaInNode(item);
23
+ if (result !== null) return result;
24
+ }
25
+ return false;
26
+ }
27
+ function detectBracketSpacing(tomlString, cst) {
28
+ for (const item of cst) {
29
+ const result = findBracketSpacingInNode(item, tomlString);
30
+ if (result !== null) return result;
31
+ }
32
+ return true;
33
+ }
34
+ function findBracketSpacingInNode(node, tomlString) {
35
+ if (!node || typeof node !== "object") return null;
36
+ if ((node.type === "InlineArray" || node.type === "InlineTable") && node.loc) {
37
+ const bracketSpacing = checkBracketSpacingInLocation(node.loc, tomlString);
38
+ if (bracketSpacing !== null) return bracketSpacing;
39
+ }
40
+ if (node.items && Array.isArray(node.items)) for (const child of node.items) {
41
+ const result = findBracketSpacingInNode(child, tomlString);
42
+ if (result !== null) return result;
43
+ if (child.item) {
44
+ const nestedResult = findBracketSpacingInNode(child.item, tomlString);
45
+ if (nestedResult !== null) return nestedResult;
46
+ }
47
+ }
48
+ for (const prop of [
49
+ "value",
50
+ "key",
51
+ "item"
52
+ ]) if (node[prop]) {
53
+ const result = findBracketSpacingInNode(node[prop], tomlString);
54
+ if (result !== null) return result;
55
+ }
56
+ return null;
57
+ }
58
+ function checkBracketSpacingInLocation(loc, tomlString) {
59
+ if (!loc || !loc.start || !loc.end) return null;
60
+ const lines = tomlString.split(/\r?\n/);
61
+ const startLine = loc.start.line - 1;
62
+ const endLine = loc.end.line - 1;
63
+ const startCol = loc.start.column;
64
+ const endCol = loc.end.column;
65
+ let rawText = "";
66
+ if (startLine === endLine) {
67
+ var _lines$startLine;
68
+ rawText = ((_lines$startLine = lines[startLine]) === null || _lines$startLine === void 0 ? void 0 : _lines$startLine.substring(startCol, endCol + 1)) || "";
69
+ } else {
70
+ if (lines[startLine]) rawText += lines[startLine].substring(startCol);
71
+ for (let i = startLine + 1; i < endLine; i++) rawText += "\n" + (lines[i] || "");
72
+ if (lines[endLine]) rawText += "\n" + lines[endLine].substring(0, endCol + 1);
73
+ }
74
+ const arrayMatch = rawText.match(/^\[(\s*)/);
75
+ const tableMatch = rawText.match(/^\{(\s*)/);
76
+ if (arrayMatch) return arrayMatch[1].length > 0;
77
+ if (tableMatch) return tableMatch[1].length > 0;
78
+ return null;
79
+ }
80
+ function findTrailingCommaInNode(node) {
81
+ if (!node || typeof node !== "object") return null;
82
+ if (node.type === "InlineArray" && node.items && Array.isArray(node.items)) return checkTrailingCommaInItems(node.items);
83
+ if (node.type === "InlineTable" && node.items && Array.isArray(node.items)) return checkTrailingCommaInItems(node.items);
84
+ if (node.type === "KeyValue" && node.value) return findTrailingCommaInNode(node.value);
85
+ if (node.items && Array.isArray(node.items)) for (const item of node.items) {
86
+ const result = findTrailingCommaInNode(item);
87
+ if (result !== null) return result;
88
+ }
89
+ return null;
90
+ }
91
+ function checkTrailingCommaInItems(items) {
92
+ if (items.length === 0) return null;
93
+ const lastItem = items[items.length - 1];
94
+ if (lastItem && typeof lastItem === "object" && "comma" in lastItem) return lastItem.comma === true;
95
+ return false;
96
+ }
97
+ function detectNewline(str) {
98
+ const lfIndex = str.indexOf("\n");
99
+ if (lfIndex > 0 && str[lfIndex - 1] === "\r") return "\r\n";
100
+ return "\n";
101
+ }
102
+ function countTrailingNewlines(str) {
103
+ let count = 0;
104
+ let pos = str.length;
105
+ while (pos > 0 && str[pos - 1] === "\n") {
106
+ count++;
107
+ pos--;
108
+ if (pos > 0 && str[pos - 1] === "\r") pos--;
109
+ }
110
+ return count;
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
+ }
154
+ function detectTabsForIndentation(str) {
155
+ const lines = str.split(/\r?\n/);
156
+ let tabCount = 0;
157
+ let spaceCount = 0;
158
+ for (const line of lines) {
159
+ if (line.length === 0) continue;
160
+ if (line[0] === " ") tabCount++;
161
+ else if (line[0] === " ") spaceCount++;
162
+ if (tabCount + spaceCount >= 5) break;
163
+ }
164
+ if (tabCount > 0) return tabCount >= spaceCount;
165
+ return false;
166
+ }
167
+ function countLeadingSpaces(line) {
168
+ let count = 0;
169
+ while (count < line.length && line[count] === " ") count++;
170
+ return count;
171
+ }
172
+ function detectIndentWidth(tomlString, syntaxTree) {
173
+ const lines = tomlString.split(/\r?\n/);
174
+ const widths = [];
175
+ const containers = /* @__PURE__ */ new Set([
176
+ "Table",
177
+ "TableArray",
178
+ "InlineTable",
179
+ "InlineArray"
180
+ ]);
181
+ const rowNodes = /* @__PURE__ */ new Set([
182
+ "Table",
183
+ "TableArray",
184
+ "InlineTable",
185
+ "InlineArray",
186
+ "KeyValue",
187
+ "InlineItem",
188
+ "Comment"
189
+ ]);
190
+ const visit = (node, containerStartLine) => {
191
+ var _node$loc, _node$loc2, _node$loc3;
192
+ if (!node || typeof node !== "object") return;
193
+ if (containerStartLine !== void 0 && rowNodes.has(node.type) && ((_node$loc = node.loc) === null || _node$loc === void 0 || (_node$loc = _node$loc.start) === null || _node$loc === void 0 ? void 0 : _node$loc.line) > containerStartLine) {
194
+ const leadingSpaces = countLeadingSpaces(lines[node.loc.start.line - 1] ?? "");
195
+ if (leadingSpaces > 0) widths.push(leadingSpaces);
196
+ }
197
+ const nextContainerStartLine = containers.has(node.type) && ((_node$loc2 = node.loc) === null || _node$loc2 === void 0 || (_node$loc2 = _node$loc2.end) === null || _node$loc2 === void 0 ? void 0 : _node$loc2.line) > ((_node$loc3 = node.loc) === null || _node$loc3 === void 0 || (_node$loc3 = _node$loc3.start) === null || _node$loc3 === void 0 ? void 0 : _node$loc3.line) ? node.loc.start.line : containerStartLine;
198
+ if (Array.isArray(node.items)) for (const item of node.items) visit(item, nextContainerStartLine);
199
+ if (node.item) visit(node.item, nextContainerStartLine);
200
+ if (node.value) visit(node.value, nextContainerStartLine);
201
+ };
202
+ const nodes = Array.isArray(syntaxTree) ? syntaxTree : Array.from(syntaxTree ?? []);
203
+ for (const node of nodes) visit(node);
204
+ if (widths.length > 0) return Math.min(...widths);
205
+ const rootIndentWidths = lines.filter((line) => line.trim().length > 0 && !line.trimStart().startsWith("#")).map(countLeadingSpaces).filter((width) => width > 0);
206
+ return rootIndentWidths.length > 0 ? Math.min(...rootIndentWidths) : 2;
207
+ }
208
+ /**
209
+ * Validates a format object and warns about unsupported properties.
210
+ * Throws errors for supported properties with invalid types.
211
+ * @param format - The format object to validate
212
+ * @returns The validated format object with only supported properties and correct types
213
+ */
214
+ /**
215
+ * Spellings accepted for `newLine`, mapped to the line ending they denote.
216
+ * A Map rather than an object literal so that a key like `constructor` cannot
217
+ * resolve through Object.prototype.
218
+ */
219
+ const NEW_LINE_ALIASES = /* @__PURE__ */ new Map([
220
+ ["\n", "\n"],
221
+ ["\r\n", "\r\n"],
222
+ ["\\n", "\n"],
223
+ ["\\r\\n", "\r\n"],
224
+ ["LF", "\n"],
225
+ ["CRLF", "\r\n"],
226
+ ["UNIX", "\n"],
227
+ ["DOS", "\r\n"]
228
+ ]);
229
+ /**
230
+ * Resolves an accepted `newLine` spelling to the literal it denotes.
231
+ *
232
+ * TOML permits only LF and CRLF, so anything else would silently produce a
233
+ * document that does not parse (a bare '\\r', or the literal text 'LF' written
234
+ * between every pair of lines). Rejecting it here means every entry point that
235
+ * resolves a format gets the check, rather than just `patch()`.
236
+ *
237
+ * @throws TypeError when the value denotes neither LF nor CRLF
238
+ */
239
+ function normalizeNewLine(value) {
240
+ const resolved = NEW_LINE_ALIASES.get(value) ?? NEW_LINE_ALIASES.get(value.toUpperCase());
241
+ if (resolved === void 0) throw new TypeError("Invalid newLine value: expected LF or CRLF");
242
+ return resolved;
243
+ }
244
+ function validateFormatObject(format) {
245
+ if (!format || typeof format !== "object") return {};
246
+ const isBool = (v) => typeof v === "boolean" ? null : `expected boolean, got ${typeof v}`;
247
+ const isMultilineContainerMode = (v) => v == null || typeof v === "boolean" || v === "auto" || v === "parent" || typeof v === "number" && Number.isInteger(v) && v >= 0 ? null : `expected boolean, non-negative integer, "auto" or "parent", got ${typeof v}`;
248
+ const schema = {
249
+ newLine: (v) => typeof v === "string" ? null : `expected string, got ${typeof v}`,
250
+ trailingNewline: (v) => typeof v === "boolean" || typeof v === "number" ? null : `expected boolean or number, got ${typeof v}`,
251
+ trailingComma: isBool,
252
+ bracketSpacing: isBool,
253
+ leadingBom: isBool,
254
+ inlineTableStart: (v) => v == null || typeof v === "number" && Number.isInteger(v) && v >= 0 ? null : `expected non-negative integer or undefined, got ${typeof v}`,
255
+ truncateZeroTimeInDates: isBool,
256
+ useTabsForIndentation: isBool,
257
+ indentWidth: (v) => v == null || typeof v === "number" && Number.isInteger(v) && v > 0 ? null : `expected positive integer or undefined, got ${typeof v}`,
258
+ minimumDecimals: (v) => v == null || typeof v === "number" && Number.isInteger(v) && v >= 0 ? null : `expected non-negative integer or undefined, got ${typeof v}`,
259
+ updateOrder: isBool,
260
+ multilineTable: isMultilineContainerMode,
261
+ multilineArray: isMultilineContainerMode,
262
+ escapeSequenceUpperCase: isBool
263
+ };
264
+ const validatedFormat = {};
265
+ const unsupported = [];
266
+ const invalid = [];
267
+ for (const key in format) {
268
+ const validator = Object.prototype.hasOwnProperty.call(schema, key) ? schema[key] : void 0;
269
+ if (validator) {
270
+ const value = format[key];
271
+ const error = validator(value);
272
+ if (error) invalid.push(`${key} (${error})`);
273
+ else validatedFormat[key] = value;
274
+ } else if (Object.prototype.hasOwnProperty.call(format, key)) unsupported.push(key);
275
+ }
276
+ if (unsupported.length > 0) console.warn(`toml-patch: Ignoring unsupported format properties: ${unsupported.join(", ")}. Supported properties are: ${Object.keys(schema).join(", ")}`);
277
+ if (invalid.length > 0) throw new TypeError(`Invalid types for format properties: ${invalid.join(", ")}`);
278
+ if ("newLine" in validatedFormat) validatedFormat.newLine = normalizeNewLine(validatedFormat.newLine);
279
+ return validatedFormat;
280
+ }
281
+ /**
282
+ * Resolves a format parameter to a TomlFormat instance.
283
+ * Handles TomlFormat instances and partial TomlFormat objects as well as undefined.
284
+ *
285
+ * @param format - The format parameter to resolve (TomlFormat instance, partial format object, or undefined)
286
+ * @param fallbackFormat - The fallback TomlFormat to use when no format is provided
287
+ * @returns A resolved TomlFormat instance
288
+ */
289
+ function resolveTomlFormat(format, fallbackFormat) {
290
+ if (format) {
291
+ if (format instanceof TomlFormat) return format;
292
+ else {
293
+ const validatedFormat = validateFormatObject(format);
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);
295
+ }
296
+ } else return fallbackFormat;
297
+ }
298
+ var TomlFormat = class TomlFormat {
299
+ /**
300
+ * The line ending character(s) to use in the output TOML.
301
+ * This option affects only the stringification process, not the internal representation (CST).
302
+ *
303
+ * @example
304
+ * - '\n' for Unix/Linux line endings
305
+ * - '\r\n' for Windows line endings
306
+ */
307
+ newLine;
308
+ /**
309
+ * The number of trailing newlines to add at the end of the TOML document.
310
+ * This option affects only the stringification process, not the internal representation (CST).
311
+ *
312
+ * @example
313
+ * - 0: No trailing newline
314
+ * - 1: One trailing newline (standard)
315
+ * - 2: Two trailing newlines (adds extra spacing)
316
+ */
317
+ trailingNewline;
318
+ /**
319
+ * Whether to add trailing commas after the last element in arrays and inline tables.
320
+ *
321
+ * @example
322
+ * - true: [1, 2, 3,] and { x = 1, y = 2, }
323
+ * - false: [1, 2, 3] and { x = 1, y = 2 }
324
+ */
325
+ trailingComma;
326
+ /**
327
+ * Whether to add spaces after opening brackets/braces and before closing brackets/braces
328
+ * in arrays and inline tables.
329
+ *
330
+ * @example
331
+ * - true: [ 1, 2, 3 ] and { x = 1, y = 2 }
332
+ * - false: [1, 2, 3] and {x = 1, y = 2}
333
+ */
334
+ bracketSpacing;
335
+ /**
336
+ * Whether the output should include a leading UTF-8 BOM marker (U+FEFF).
337
+ *
338
+ * This is auto-detected from the source TOML and preserved during patching.
339
+ */
340
+ leadingBom;
341
+ /**
342
+ * The nesting depth at which new tables should start being formatted as inline tables.
343
+ * When adding new tables during patching or stringifying objects:
344
+ * - Tables at depth >= inlineTableStart will be formatted as inline tables
345
+ * - Tables at depth < inlineTableStart will be formatted as separate table sections
346
+ *
347
+ * @example
348
+ * - 0: All tables are inline tables including top-level tables (root level)
349
+ * - 1: Top-level tables as sections, nested tables as inline (default)
350
+ * - 2: Two levels as sections, deeper nesting as inline
351
+ */
352
+ inlineTableStart;
353
+ /**
354
+ * Whether to truncate time components in UTC date fields when they are zero.
355
+ * This setting affects only the stringification process.
356
+ *
357
+ * @example
358
+ * - true: Date('2024-01-15T00:00:00.000Z') serializes as 2024-01-15
359
+ * - false: Date('2024-01-15T00:00:00.000Z') serializes as 2024-01-15T00:00:00.000Z
360
+ *
361
+ */
362
+ truncateZeroTimeInDates;
363
+ /**
364
+ * Whether to use tabs instead of spaces for indentation/padding.
365
+ * When enabled, lines that need to be indented will use tabs.
366
+ *
367
+ * @example
368
+ * - true: Uses tabs for indentation
369
+ * - false: Uses spaces for indentation (default)
370
+ *
371
+ */
372
+ useTabsForIndentation;
373
+ /**
374
+ * The number of columns used for one indentation level in generated multiline values.
375
+ * This is auto-detected when patching and defaults to two columns.
376
+ */
377
+ indentWidth;
378
+ /**
379
+ * The minimum number of decimal places to use when serializing JS numbers as TOML floats.
380
+ * When greater than 0, plain JS integer values are serialized as TOML floats padded with
381
+ * zeros to reach the specified decimal count. BigInt values are always serialized as integers
382
+ * regardless of this setting.
383
+ *
384
+ * @example
385
+ * - 0: stringify({ x: 1, y: 1.5 }) → x = 1 / y = 1.5 (default)
386
+ * - 1: stringify({ x: 1, y: 1.5 }) → x = 1.0 / y = 1.5
387
+ * - 2: stringify({ x: 1, y: 1.5 }) → x = 1.00 / y = 1.50
388
+ */
389
+ minimumDecimals;
390
+ /**
391
+ * Whether `patch()` should reorder root key-values, `[table]`/`[[array]]` section blocks,
392
+ * and rows inside table bodies to match the key order of the JS object passed to `patch()`,
393
+ * carrying each entry's owned comments along with it (see docs/CommentOwnership.md).
394
+ *
395
+ * Off by default: with the option unset or `false`, `patch()` only ever changes values that
396
+ * actually differ between the existing document and the updated object, preserving the
397
+ * existing document's order even when the JS object's key order differs.
398
+ *
399
+ * Not auto-detectable — the existing document's order says nothing about the caller's
400
+ * intent, so `autoDetectFormatWithCst` always resolves this to `false`.
401
+ *
402
+ * See docs/PLAN-Update-Order.md for the full behavior and current scope limitations.
403
+ */
404
+ updateOrder;
405
+ /**
406
+ * Whether newly generated inline tables should use multiline layout.
407
+ *
408
+ * `true` and `false` select a layout directly. A non-negative integer selects
409
+ * multiline layout at that structural container depth or deeper. `'auto'`
410
+ * keeps new containers compact and `'parent'` follows the immediate parent.
411
+ */
412
+ multilineTable;
413
+ /**
414
+ * Whether newly generated inline arrays should use multiline layout.
415
+ *
416
+ * `true` and `false` select a layout directly. A non-negative integer selects
417
+ * multiline layout at that structural container depth or deeper. `'auto'`
418
+ * keeps new containers compact and `'parent'` follows the immediate parent.
419
+ */
420
+ 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) {
428
+ this.newLine = newLine == null ? "\n" : normalizeNewLine(newLine);
429
+ this.trailingNewline = trailingNewline ?? 1;
430
+ this.trailingComma = trailingComma ?? false;
431
+ this.bracketSpacing = bracketSpacing ?? true;
432
+ this.inlineTableStart = inlineTableStart ?? 1;
433
+ this.truncateZeroTimeInDates = truncateZeroTimeInDates ?? false;
434
+ this.useTabsForIndentation = useTabsForIndentation ?? false;
435
+ this.indentWidth = this.useTabsForIndentation ? 1 : indentWidth ?? 2;
436
+ this.minimumDecimals = minimumDecimals ?? 0;
437
+ this.leadingBom = leadingBom ?? false;
438
+ this.updateOrder = updateOrder ?? false;
439
+ this.multilineTable = multilineTable ?? "auto";
440
+ this.multilineArray = multilineArray ?? "auto";
441
+ this.escapeSequenceUpperCase = escapeSequenceUpperCase ?? true;
442
+ }
443
+ /**
444
+ * Creates a new TomlFormat instance with default formatting preferences.
445
+ *
446
+ * @returns A new TomlFormat instance with default values:
447
+ * - newLine: '\n'
448
+ * - trailingNewline: 1
449
+ * - trailingComma: false
450
+ * - bracketSpacing: true
451
+ * - leadingBom: false
452
+ * - inlineTableStart: 1
453
+ * - truncateZeroTimeInDates: false
454
+ * - useTabsForIndentation: false
455
+ * - minimumDecimals: 0
456
+ * - updateOrder: false
457
+ */
458
+ static default() {
459
+ return new TomlFormat("\n", 1, false, true, 1, false, false, 0, false, false, 2, DEFAULT_MULTILINE_TABLE, DEFAULT_MULTILINE_ARRAY, true);
460
+ }
461
+ /**
462
+ * Auto-detects formatting preferences from an existing TOML string.
463
+ *
464
+ * This method analyzes the provided TOML string to determine formatting
465
+ * preferences such as line endings, trailing newlines, and comma usage.
466
+ *
467
+ * @param tomlString - The TOML string to analyze for formatting patterns
468
+ * @returns A new TomlFormat instance with detected formatting preferences
469
+ *
470
+ * @example
471
+ * ```typescript
472
+ * const toml = 'array = ["a", "b", "c",]\ntable = { x = 1, y = 2, }';
473
+ * const format = TomlFormat.autoDetectFormat(toml);
474
+ * // format.trailingComma will be true
475
+ * // format.newLine will be '\n'
476
+ * // format.trailingNewline will be 0 (no trailing newline)
477
+ * ```
478
+ */
479
+ static autoDetectFormat(tomlString) {
480
+ return TomlFormat.autoDetectFormatWithCst(tomlString);
481
+ }
482
+ /**
483
+ * Internal method: Auto-detects formatting preferences from a TOML string with optional pre-parsed CST.
484
+ *
485
+ * This is used internally to avoid redundant parsing when the CST is already available.
486
+ * External callers should use `autoDetectFormat(tomlString)` instead.
487
+ *
488
+ * @internal
489
+ * @param tomlString - The TOML string to analyze for formatting patterns
490
+ * @param syntaxTree - Optional pre-parsed CST to avoid redundant parsing
491
+ * @returns A new TomlFormat instance with detected formatting preferences
492
+ */
493
+ static autoDetectFormatWithCst(tomlString, syntaxTree) {
494
+ const format = TomlFormat.default();
495
+ format.leadingBom = hasLeadingBom(tomlString);
496
+ const tomlContent = stripLeadingBom(tomlString);
497
+ let cstNodes = [];
498
+ format.newLine = detectNewline(tomlContent);
499
+ format.trailingNewline = countTrailingNewlines(tomlContent);
500
+ try {
501
+ cstNodes = Array.isArray(syntaxTree) ? syntaxTree : Array.from(syntaxTree ?? parseTOML(tomlContent));
502
+ format.trailingComma = detectTrailingComma(cstNodes);
503
+ format.bracketSpacing = detectBracketSpacing(tomlContent, cstNodes);
504
+ } catch (error) {
505
+ format.trailingComma = false;
506
+ format.bracketSpacing = true;
507
+ }
508
+ format.useTabsForIndentation = detectTabsForIndentation(tomlContent);
509
+ if (format.useTabsForIndentation) format.indentWidth = 1;
510
+ else format.indentWidth = detectIndentWidth(tomlContent, cstNodes);
511
+ format.inlineTableStart = 1;
512
+ format.truncateZeroTimeInDates = false;
513
+ format.minimumDecimals = 0;
514
+ format.updateOrder = false;
515
+ format.multilineTable = DEFAULT_MULTILINE_TABLE;
516
+ format.multilineArray = DEFAULT_MULTILINE_ARRAY;
517
+ format.escapeSequenceUpperCase = detectEscapeSequenceUpperCase(cstNodes);
518
+ return format;
519
+ }
520
+ /** @deprecated Use autoDetectFormatWithCst instead. */
521
+ static autoDetectFormatWithAst(tomlString, syntaxTree) {
522
+ return TomlFormat.autoDetectFormatWithCst(tomlString, syntaxTree);
523
+ }
524
+ };
525
+
526
+ //#endregion
527
+ export { DEFAULT_MULTILINE_ARRAY, DEFAULT_MULTILINE_TABLE, TomlFormat, countTrailingNewlines, detectBracketSpacing, detectEscapeSequenceUpperCase, detectIndentWidth, detectNewline, detectTabsForIndentation, detectTrailingComma, normalizeNewLine, resolveTomlFormat, validateFormatObject };
528
+ //# sourceMappingURL=toml-format.js.map