@decimalturn/toml-patch 3.0.4 → 3.1.0-dev

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) 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 +108 -0
  6. package/dist/dev/cst-source.js.map +1 -0
  7. package/dist/dev/cst.js +59 -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.js +269 -0
  16. package/dist/dev/diff.js.map +1 -0
  17. package/dist/dev/escape-preference.js +144 -0
  18. package/dist/dev/escape-preference.js.map +1 -0
  19. package/dist/dev/find-by-path.js +111 -0
  20. package/dist/dev/find-by-path.js.map +1 -0
  21. package/dist/dev/formatter.js +295 -0
  22. package/dist/dev/formatter.js.map +1 -0
  23. package/dist/dev/generate.js +451 -0
  24. package/dist/dev/generate.js.map +1 -0
  25. package/dist/dev/inline-comma-space.js +13 -0
  26. package/dist/dev/inline-comma-space.js.map +1 -0
  27. package/dist/dev/inline-format.js +106 -0
  28. package/dist/dev/inline-format.js.map +1 -0
  29. package/dist/dev/inline-layout.js +107 -0
  30. package/dist/dev/inline-layout.js.map +1 -0
  31. package/dist/dev/line-ending-backslash.js +320 -0
  32. package/dist/dev/line-ending-backslash.js.map +1 -0
  33. package/dist/dev/location.js +77 -0
  34. package/dist/dev/location.js.map +1 -0
  35. package/dist/dev/parse-error.js +27 -0
  36. package/dist/dev/parse-error.js.map +1 -0
  37. package/dist/dev/parse-js.js +103 -0
  38. package/dist/dev/parse-js.js.map +1 -0
  39. package/dist/dev/parse-string.js +122 -0
  40. package/dist/dev/parse-string.js.map +1 -0
  41. package/dist/dev/parse-toml.js +669 -0
  42. package/dist/dev/parse-toml.js.map +1 -0
  43. package/dist/dev/patch.js +2537 -0
  44. package/dist/dev/patch.js.map +1 -0
  45. package/dist/dev/to-js.js +303 -0
  46. package/dist/dev/to-js.js.map +1 -0
  47. package/dist/dev/to-toml.js +569 -0
  48. package/dist/dev/to-toml.js.map +1 -0
  49. package/dist/dev/tokenizer.js +225 -0
  50. package/dist/dev/tokenizer.js.map +1 -0
  51. package/dist/dev/toml-document.js +215 -0
  52. package/dist/dev/toml-document.js.map +1 -0
  53. package/dist/dev/toml-format.js +476 -0
  54. package/dist/dev/toml-format.js.map +1 -0
  55. package/dist/dev/toml-patch.js +84 -0
  56. package/dist/dev/toml-patch.js.map +1 -0
  57. package/dist/dev/traverse.js +61 -0
  58. package/dist/dev/traverse.js.map +1 -0
  59. package/dist/dev/truncate.js +64 -0
  60. package/dist/dev/truncate.js.map +1 -0
  61. package/dist/dev/update-order.js +235 -0
  62. package/dist/dev/update-order.js.map +1 -0
  63. package/dist/dev/utils.js +223 -0
  64. package/dist/dev/utils.js.map +1 -0
  65. package/dist/dev/writer.js +758 -0
  66. package/dist/dev/writer.js.map +1 -0
  67. package/dist/toml-patch.d.ts +28 -13
  68. package/package.json +12 -88
  69. package/LICENSE +0 -22
  70. package/README.md +0 -161
  71. package/dist/toml-patch.js +0 -54
@@ -0,0 +1,196 @@
1
+ //! @decimalturn/toml-patch v3.1.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
+ //#region src/date-format.ts
3
+ /**
4
+ * Central module for TOML date/time format handling and custom date classes.
5
+ * This module provides all the patterns, classes, and utilities needed to work
6
+ * with the different date/time formats supported by the TOML specification.
7
+ */
8
+ /** Extract UTC date/time parts as zero-padded strings. */
9
+ function fmtParts(d) {
10
+ return {
11
+ year: String(d.getUTCFullYear()).padStart(4, "0"),
12
+ month: String(d.getUTCMonth() + 1).padStart(2, "0"),
13
+ day: String(d.getUTCDate()).padStart(2, "0"),
14
+ hours: String(d.getUTCHours()).padStart(2, "0"),
15
+ minutes: String(d.getUTCMinutes()).padStart(2, "0"),
16
+ seconds: String(d.getUTCSeconds()).padStart(2, "0"),
17
+ ms: d.getUTCMilliseconds()
18
+ };
19
+ }
20
+ /** Format millisecond suffix (".123") preserving original precision, or "" if none needed. */
21
+ function fmtMs(ms, origFmt, msRe = /\.(\d+)\s*$/) {
22
+ if (origFmt && origFmt.includes(".")) {
23
+ const m = origFmt.match(msRe);
24
+ const digits = m ? m[1].length : 3;
25
+ return "." + String(ms).padStart(3, "0").slice(0, digits);
26
+ }
27
+ if (ms > 0) return "." + String(ms).padStart(3, "0").replace(/0+$/, "");
28
+ return "";
29
+ }
30
+ /** Parse a timezone offset string like "+09:00" or "Z" into minutes. */
31
+ function parseOffsetMinutes(offset) {
32
+ if (offset === "Z") return 0;
33
+ const sign = offset[0] === "+" ? 1 : -1;
34
+ const [h, m] = offset.slice(1).split(":");
35
+ return sign * (parseInt(h) * 60 + parseInt(m));
36
+ }
37
+ /**
38
+ * Helper class containing all date format patterns and utilities for TOML date/time handling
39
+ */
40
+ var DateFormatHelper = class DateFormatHelper {
41
+ static IS_DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
42
+ static IS_TIME_ONLY = /^\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?$/;
43
+ static IS_LOCAL_DATETIME_T = /^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?$/;
44
+ static IS_LOCAL_DATETIME_SPACE = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?(?:\.\d+)?$/;
45
+ static IS_OFFSET_DATETIME_T = /^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})$/;
46
+ static IS_OFFSET_DATETIME_SPACE = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})$/;
47
+ static IS_FULL_DATE = /(\d{4})-(\d+)-(\d+)/;
48
+ static IS_FULL_TIME = /(\d+):(\d+)(?::(\d+))?/;
49
+ /**
50
+ * Creates a custom date/time object that preserves the original TOML date/time format.
51
+ *
52
+ * This method detects the TOML date/time format from the raw string and returns an appropriate
53
+ * custom date/time instance (e.g., LocalDate, LocalTime, LocalDateTime, OffsetDateTime) or a Date,
54
+ * using the provided new JavaScript Date value.
55
+ *
56
+ * @param {Date} newJSDate - The new JavaScript Date object representing the updated
57
+ * date/time value. This is used as the source for constructing the custom date/time object.
58
+ * In some cases, this may be a custom date/time object (e.g., LocalTime) instead of a native Date.
59
+ * @param {string} originalRaw - The original TOML date/time string as it appeared in the input.
60
+ * Used to detect the specific TOML date/time format and to extract formatting details (e.g., separator, offset).
61
+ *
62
+ * @returns {Date | LocalDate | LocalTime | LocalDateTime | OffsetDateTime}
63
+ * Returns a custom date/time object that matches the original TOML format:
64
+ * - LocalDate for date-only values (e.g., "2024-01-15")
65
+ * - LocalTime for time-only values (e.g., "10:30:00")
66
+ * - LocalDateTime for local datetimes (e.g., "2024-01-15T10:30:00" or "2024-01-15 10:30:00")
67
+ * - OffsetDateTime for datetimes with offsets (e.g., "2024-01-15T10:30:00+02:00")
68
+ * - Date (native JS Date) as a fallback if the format is unrecognized
69
+ *
70
+ * Format-specific behavior:
71
+ * - Date-only: Returns a LocalDate constructed from the date part of newJSDate.
72
+ * - Time-only: Returns a LocalTime, either from newJSDate (if already LocalTime) or constructed from its time part.
73
+ * - Local datetime: Returns a LocalDateTime, preserving the separator (T or space).
74
+ * - Offset datetime: Returns an OffsetDateTime, reconstructing the date/time with the original offset and separator.
75
+ * - Fallback: Returns newJSDate as-is.
76
+ */
77
+ static createDateWithOriginalFormat(newJSDate, originalRaw) {
78
+ if (DateFormatHelper.IS_DATE_ONLY.test(originalRaw)) {
79
+ if (newJSDate.getUTCHours() !== 0 || newJSDate.getUTCMinutes() !== 0 || newJSDate.getUTCSeconds() !== 0 || newJSDate.getUTCMilliseconds() !== 0) {
80
+ if (newJSDate instanceof OffsetDateTime) return newJSDate;
81
+ let isoString = newJSDate.toISOString().replace("Z", "");
82
+ isoString = isoString.replace(/\.000$/, "");
83
+ return new LocalDateTime(isoString, false);
84
+ }
85
+ const dateStr = newJSDate.toISOString().split("T")[0];
86
+ return new LocalDate(dateStr);
87
+ } else if (DateFormatHelper.IS_TIME_ONLY.test(originalRaw)) {
88
+ if (newJSDate instanceof LocalTime) return newJSDate;
89
+ else {
90
+ const p = fmtParts(newJSDate);
91
+ const msSuffix = fmtMs(p.ms, originalRaw);
92
+ return new LocalTime(`${p.hours}:${p.minutes}:${p.seconds}${msSuffix}`, originalRaw);
93
+ }
94
+ } else if (DateFormatHelper.IS_LOCAL_DATETIME_T.test(originalRaw)) {
95
+ const p = fmtParts(newJSDate);
96
+ const msSuffix = fmtMs(p.ms, originalRaw);
97
+ return new LocalDateTime(`${p.year}-${p.month}-${p.day}T${p.hours}:${p.minutes}:${p.seconds}${msSuffix}`, false, originalRaw);
98
+ } else if (DateFormatHelper.IS_LOCAL_DATETIME_SPACE.test(originalRaw)) {
99
+ const p = fmtParts(newJSDate);
100
+ const msSuffix = fmtMs(p.ms, originalRaw);
101
+ return new LocalDateTime(`${p.year}-${p.month}-${p.day} ${p.hours}:${p.minutes}:${p.seconds}${msSuffix}`, true, originalRaw);
102
+ } else if (DateFormatHelper.IS_OFFSET_DATETIME_T.test(originalRaw) || DateFormatHelper.IS_OFFSET_DATETIME_SPACE.test(originalRaw)) {
103
+ const offsetMatch = originalRaw.match(/([+-]\d{2}:\d{2}|[Zz])$/);
104
+ const originalOffset = offsetMatch ? offsetMatch[1] === "z" ? "Z" : offsetMatch[1] : "Z";
105
+ const useSpaceSeparator = DateFormatHelper.IS_OFFSET_DATETIME_SPACE.test(originalRaw);
106
+ const p = fmtParts(new Date(newJSDate.getTime() + parseOffsetMinutes(originalOffset) * 6e4));
107
+ const sep = useSpaceSeparator ? " " : "T";
108
+ const msSuffix = fmtMs(p.ms, originalRaw, /\.(\d+)(?:[Zz]|[+-]\d{2}:\d{2})\s*$/);
109
+ const newDateTimeString = `${p.year}-${p.month}-${p.day}${sep}${p.hours}:${p.minutes}:${p.seconds}${msSuffix}${originalOffset}`;
110
+ return new OffsetDateTime(newDateTimeString, useSpaceSeparator);
111
+ } else return newJSDate;
112
+ }
113
+ };
114
+ /**
115
+ * Custom Date class for local dates (date-only).
116
+ * Format: 1979-05-27
117
+ */
118
+ var LocalDate = class extends Date {
119
+ constructor(value) {
120
+ super(value);
121
+ }
122
+ toISOString() {
123
+ const p = fmtParts(this);
124
+ return `${p.year}-${p.month}-${p.day}`;
125
+ }
126
+ };
127
+ /**
128
+ * Custom Date class for local times (time-only)
129
+ * Format: 07:32:00 or 07:32:00.999
130
+ */
131
+ var LocalTime = class extends Date {
132
+ originalFormat;
133
+ constructor(value, originalFormat) {
134
+ let normalizedValue = value;
135
+ if (!/:\d{2}:\d{2}/.test(value)) normalizedValue = value + ":00";
136
+ super(`0000-01-01T${normalizedValue}Z`);
137
+ this.originalFormat = originalFormat;
138
+ }
139
+ toISOString() {
140
+ const p = fmtParts(this);
141
+ return `${p.hours}:${p.minutes}:${p.seconds}${fmtMs(p.ms, this.originalFormat)}`;
142
+ }
143
+ };
144
+ /**
145
+ * Custom Date class for local datetime (no timezone)
146
+ * Format: 1979-05-27T07:32:00 or 1979-05-27 07:32:00
147
+ */
148
+ var LocalDateTime = class extends Date {
149
+ useSpaceSeparator = false;
150
+ originalFormat;
151
+ constructor(value, useSpaceSeparator = false, originalFormat) {
152
+ let normalizedValue = value;
153
+ if (!/\d{2}:\d{2}:\d{2}/.test(value)) normalizedValue = value.replace(/(\d{2}:\d{2})([\s\-+TZ]|$)/, "$1:00$2");
154
+ super(normalizedValue.replace(" ", "T") + "Z");
155
+ this.useSpaceSeparator = useSpaceSeparator;
156
+ this.originalFormat = originalFormat || value;
157
+ }
158
+ toISOString() {
159
+ const p = fmtParts(this);
160
+ const sep = this.useSpaceSeparator ? " " : "T";
161
+ return `${p.year}-${p.month}-${p.day}${sep}${p.hours}:${p.minutes}:${p.seconds}${fmtMs(p.ms, this.originalFormat)}`;
162
+ }
163
+ };
164
+ /**
165
+ * Custom Date class for offset datetime that preserves space separator
166
+ * Format: 1979-05-27T07:32:00Z or 1979-05-27 07:32:00-07:00
167
+ */
168
+ var OffsetDateTime = class extends Date {
169
+ useSpaceSeparator = false;
170
+ originalOffset;
171
+ originalFormat;
172
+ constructor(value, useSpaceSeparator = false) {
173
+ let normalizedValue = value;
174
+ if (!/\d{2}:\d{2}:\d{2}/.test(value)) normalizedValue = value.replace(/(\d{2}:\d{2})([\s\-+TZ]|$)/, "$1:00$2");
175
+ super(normalizedValue.replace(" ", "T"));
176
+ this.useSpaceSeparator = useSpaceSeparator;
177
+ this.originalFormat = value;
178
+ const offsetMatch = value.match(/([+-]\d{2}:\d{2}|[Zz])$/);
179
+ if (offsetMatch) this.originalOffset = offsetMatch[1] === "z" ? "Z" : offsetMatch[1];
180
+ }
181
+ toISOString() {
182
+ if (this.originalOffset) {
183
+ const p = fmtParts(new Date(this.getTime() + parseOffsetMinutes(this.originalOffset) * 6e4));
184
+ const sep = this.useSpaceSeparator ? " " : "T";
185
+ const msSuffix = fmtMs(p.ms, this.originalFormat, /\.(\d+)(?:[Zz]|[+-]\d{2}:\d{2})\s*$/);
186
+ return `${p.year}-${p.month}-${p.day}${sep}${p.hours}:${p.minutes}:${p.seconds}${msSuffix}${this.originalOffset}`;
187
+ }
188
+ const isoString = super.toISOString();
189
+ if (this.useSpaceSeparator) return isoString.replace("T", " ");
190
+ return isoString;
191
+ }
192
+ };
193
+
194
+ //#endregion
195
+ export { DateFormatHelper, LocalDate, LocalDateTime, LocalTime, OffsetDateTime };
196
+ //# sourceMappingURL=date-format.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"date-format.js","names":[],"sources":["../../src/date-format.ts"],"sourcesContent":["/**\n * Central module for TOML date/time format handling and custom date classes.\n * This module provides all the patterns, classes, and utilities needed to work\n * with the different date/time formats supported by the TOML specification.\n */\n\n// ---------------------------------------------------------------------------\n// Shared formatting helpers (extracted to reduce duplication)\n// ---------------------------------------------------------------------------\n\n/** Extract UTC date/time parts as zero-padded strings. */\nfunction fmtParts(d: Date) {\n return {\n year: String(d.getUTCFullYear()).padStart(4, '0'),\n month: String(d.getUTCMonth() + 1).padStart(2, '0'),\n day: String(d.getUTCDate()).padStart(2, '0'),\n hours: String(d.getUTCHours()).padStart(2, '0'),\n minutes: String(d.getUTCMinutes()).padStart(2, '0'),\n seconds: String(d.getUTCSeconds()).padStart(2, '0'),\n ms: d.getUTCMilliseconds(),\n };\n}\n\n/** Format millisecond suffix (\".123\") preserving original precision, or \"\" if none needed. */\nfunction fmtMs(ms: number, origFmt: string, msRe: RegExp = /\\.(\\d+)\\s*$/): string {\n const hadMs = origFmt && origFmt.includes('.');\n if (hadMs) {\n const m = origFmt.match(msRe);\n const digits = m ? m[1].length : 3;\n return '.' + String(ms).padStart(3, '0').slice(0, digits);\n }\n if (ms > 0) {\n return '.' + String(ms).padStart(3, '0').replace(/0+$/, '');\n }\n return '';\n}\n\n/** Parse a timezone offset string like \"+09:00\" or \"Z\" into minutes. */\nfunction parseOffsetMinutes(offset: string): number {\n if (offset === 'Z') return 0;\n const sign = offset[0] === '+' ? 1 : -1;\n const [h, m] = offset.slice(1).split(':');\n return sign * (parseInt(h) * 60 + parseInt(m));\n}\n\n// ---------------------------------------------------------------------------\n\n/**\n * Helper class containing all date format patterns and utilities for TOML date/time handling\n */\nexport class DateFormatHelper {\n // Patterns for different date/time formats\n static readonly IS_DATE_ONLY = /^\\d{4}-\\d{2}-\\d{2}$/;\n static readonly IS_TIME_ONLY = /^\\d{2}:\\d{2}(?::\\d{2})?(?:\\.\\d+)?$/;\n static readonly IS_LOCAL_DATETIME_T = /^\\d{4}-\\d{2}-\\d{2}[Tt]\\d{2}:\\d{2}(?::\\d{2})?(?:\\.\\d+)?$/;\n static readonly IS_LOCAL_DATETIME_SPACE = /^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}(?::\\d{2})?(?:\\.\\d+)?$/;\n static readonly IS_OFFSET_DATETIME_T = /^\\d{4}-\\d{2}-\\d{2}[Tt]\\d{2}:\\d{2}(?::\\d{2})?(?:\\.\\d+)?(?:[Zz]|[+-]\\d{2}:\\d{2})$/;\n static readonly IS_OFFSET_DATETIME_SPACE = /^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}(?::\\d{2})?(?:\\.\\d+)?(?:[Zz]|[+-]\\d{2}:\\d{2})$/;\n \n // Legacy patterns from parse-toml.ts (for compatibility)\n // Made more permissive to catch malformed dates (e.g., 1987-7-05) for validation\n static readonly IS_FULL_DATE = /(\\d{4})-(\\d+)-(\\d+)/;\n static readonly IS_FULL_TIME = /(\\d+):(\\d+)(?::(\\d+))?/;\n\n /**\n * Creates a custom date/time object that preserves the original TOML date/time format.\n * \n * This method detects the TOML date/time format from the raw string and returns an appropriate\n * custom date/time instance (e.g., LocalDate, LocalTime, LocalDateTime, OffsetDateTime) or a Date,\n * using the provided new JavaScript Date value.\n * \n * @param {Date} newJSDate - The new JavaScript Date object representing the updated \n * date/time value. This is used as the source for constructing the custom date/time object.\n * In some cases, this may be a custom date/time object (e.g., LocalTime) instead of a native Date.\n * @param {string} originalRaw - The original TOML date/time string as it appeared in the input.\n * Used to detect the specific TOML date/time format and to extract formatting details (e.g., separator, offset).\n * \n * @returns {Date | LocalDate | LocalTime | LocalDateTime | OffsetDateTime}\n * Returns a custom date/time object that matches the original TOML format:\n * - LocalDate for date-only values (e.g., \"2024-01-15\")\n * - LocalTime for time-only values (e.g., \"10:30:00\")\n * - LocalDateTime for local datetimes (e.g., \"2024-01-15T10:30:00\" or \"2024-01-15 10:30:00\")\n * - OffsetDateTime for datetimes with offsets (e.g., \"2024-01-15T10:30:00+02:00\")\n * - Date (native JS Date) as a fallback if the format is unrecognized\n * \n * Format-specific behavior:\n * - Date-only: Returns a LocalDate constructed from the date part of newJSDate.\n * - Time-only: Returns a LocalTime, either from newJSDate (if already LocalTime) or constructed from its time part.\n * - Local datetime: Returns a LocalDateTime, preserving the separator (T or space).\n * - Offset datetime: Returns an OffsetDateTime, reconstructing the date/time with the original offset and separator.\n * - Fallback: Returns newJSDate as-is.\n */\n static createDateWithOriginalFormat(newJSDate: Date, originalRaw: string): Date {\n if (DateFormatHelper.IS_DATE_ONLY.test(originalRaw)) {\n // Local date (date-only) - format: 2024-01-15\n // Check if newJSDate has time components - if so, upgrade appropriately\n if (\n newJSDate.getUTCHours() !== 0 ||\n newJSDate.getUTCMinutes() !== 0 ||\n newJSDate.getUTCSeconds() !== 0 ||\n newJSDate.getUTCMilliseconds() !== 0\n ) {\n // Check if the new value is an OffsetDateTime (has offset information)\n if (newJSDate instanceof OffsetDateTime) {\n // Upgrade to OffsetDateTime - it already has the right format\n return newJSDate;\n }\n \n // Upgrade from date-only to local datetime with time components\n // Use T separator as it's the more common format\n let isoString = newJSDate.toISOString().replace('Z', '');\n // Strip .000 milliseconds if present (don't show unnecessary precision)\n isoString = isoString.replace(/\\.000$/, '');\n return new LocalDateTime(isoString, false);\n }\n const dateStr = newJSDate.toISOString().split('T')[0];\n return new LocalDate(dateStr);\n } else if (DateFormatHelper.IS_TIME_ONLY.test(originalRaw)) {\n // Local time (time-only) - format: 10:30:00\n // For time-only values, we need to handle this more carefully\n // The newJSDate might be a LocalTime object itself\n if (newJSDate instanceof LocalTime) {\n // If the new date is already a LocalTime, use its toISOString\n return newJSDate;\n } else {\n const p = fmtParts(newJSDate);\n const msSuffix = fmtMs(p.ms, originalRaw);\n return new LocalTime(`${p.hours}:${p.minutes}:${p.seconds}${msSuffix}`, originalRaw);\n }\n } else if (DateFormatHelper.IS_LOCAL_DATETIME_T.test(originalRaw)) {\n // Local datetime with T separator - format: 2024-01-15T10:30:00\n const p = fmtParts(newJSDate);\n const msSuffix = fmtMs(p.ms, originalRaw);\n return new LocalDateTime(`${p.year}-${p.month}-${p.day}T${p.hours}:${p.minutes}:${p.seconds}${msSuffix}`, false, originalRaw);\n } else if (DateFormatHelper.IS_LOCAL_DATETIME_SPACE.test(originalRaw)) {\n // Local datetime with space separator - format: 2024-01-15 10:30:00\n const p = fmtParts(newJSDate);\n const msSuffix = fmtMs(p.ms, originalRaw);\n return new LocalDateTime(`${p.year}-${p.month}-${p.day} ${p.hours}:${p.minutes}:${p.seconds}${msSuffix}`, true, originalRaw);\n } else if (DateFormatHelper.IS_OFFSET_DATETIME_T.test(originalRaw) || DateFormatHelper.IS_OFFSET_DATETIME_SPACE.test(originalRaw)) {\n // Offset datetime - preserve the original timezone offset and separator\n const offsetMatch = originalRaw.match(/([+-]\\d{2}:\\d{2}|[Zz])$/);\n const originalOffset = offsetMatch ? (offsetMatch[1] === 'z' ? 'Z' : offsetMatch[1]) : 'Z';\n const useSpaceSeparator = DateFormatHelper.IS_OFFSET_DATETIME_SPACE.test(originalRaw);\n \n // Convert UTC time to local time in the original timezone\n const localTime = new Date(newJSDate.getTime() + parseOffsetMinutes(originalOffset) * 60000);\n const p = fmtParts(localTime);\n const sep = useSpaceSeparator ? ' ' : 'T';\n const msSuffix = fmtMs(p.ms, originalRaw, /\\.(\\d+)(?:[Zz]|[+-]\\d{2}:\\d{2})\\s*$/);\n \n const newDateTimeString = `${p.year}-${p.month}-${p.day}${sep}${p.hours}:${p.minutes}:${p.seconds}${msSuffix}${originalOffset}`;\n return new OffsetDateTime(newDateTimeString, useSpaceSeparator);\n } else {\n // Fallback to regular Date\n return newJSDate;\n }\n }\n}\n\n/**\n * Custom Date class for local dates (date-only).\n * Format: 1979-05-27\n */\nexport class LocalDate extends Date {\n\n constructor(value: string) {\n super(value);\n }\n \n toISOString(): string {\n const p = fmtParts(this);\n return `${p.year}-${p.month}-${p.day}`;\n }\n}\n\n/**\n * Custom Date class for local times (time-only)\n * Format: 07:32:00 or 07:32:00.999\n */\nexport class LocalTime extends Date {\n originalFormat: string;\n \n constructor(value: string, originalFormat: string) {\n // Normalize time to include seconds if missing (TOML 1.1.0 allows optional seconds)\n let normalizedValue = value;\n if (!/:\\d{2}:\\d{2}/.test(value)) {\n // No seconds present, add :00\n normalizedValue = value + ':00';\n }\n // For local time, use year 0000 as the base (TOML spec compliance)\n // Add 'Z' to ensure it's parsed as UTC regardless of system timezone\n super(`0000-01-01T${normalizedValue}Z`);\n this.originalFormat = originalFormat;\n }\n \n toISOString(): string {\n const p = fmtParts(this);\n return `${p.hours}:${p.minutes}:${p.seconds}${fmtMs(p.ms, this.originalFormat)}`;\n }\n}\n\n/**\n * Custom Date class for local datetime (no timezone)\n * Format: 1979-05-27T07:32:00 or 1979-05-27 07:32:00\n */\nexport class LocalDateTime extends Date {\n useSpaceSeparator: boolean = false;\n originalFormat: string;\n \n constructor(value: string, useSpaceSeparator: boolean = false, originalFormat?: string) {\n // Normalize time part to include seconds if missing (TOML 1.1.0 allows optional seconds)\n let normalizedValue = value;\n if (!/\\d{2}:\\d{2}:\\d{2}/.test(value)) {\n normalizedValue = value.replace(/(\\d{2}:\\d{2})([\\s\\-+TZ]|$)/, '$1:00$2');\n }\n // Convert space to T for Date parsing, but remember the original format\n super(normalizedValue.replace(' ', 'T') + 'Z');\n this.useSpaceSeparator = useSpaceSeparator;\n this.originalFormat = originalFormat || value;\n }\n \n toISOString(): string {\n const p = fmtParts(this);\n const sep = this.useSpaceSeparator ? ' ' : 'T';\n return `${p.year}-${p.month}-${p.day}${sep}${p.hours}:${p.minutes}:${p.seconds}${fmtMs(p.ms, this.originalFormat)}`;\n }\n}\n\n/**\n * Custom Date class for offset datetime that preserves space separator\n * Format: 1979-05-27T07:32:00Z or 1979-05-27 07:32:00-07:00\n */\nexport class OffsetDateTime extends Date {\n useSpaceSeparator: boolean = false;\n originalOffset?: string;\n originalFormat: string;\n \n constructor(value: string, useSpaceSeparator: boolean = false) {\n // Normalize time part to include seconds if missing (TOML 1.1.0 allows optional seconds)\n let normalizedValue = value;\n if (!/\\d{2}:\\d{2}:\\d{2}/.test(value)) {\n normalizedValue = value.replace(/(\\d{2}:\\d{2})([\\s\\-+TZ]|$)/, '$1:00$2');\n }\n super(normalizedValue.replace(' ', 'T'));\n this.useSpaceSeparator = useSpaceSeparator;\n this.originalFormat = value;\n \n // Extract and preserve the original offset\n const offsetMatch = value.match(/([+-]\\d{2}:\\d{2}|[Zz])$/);\n if (offsetMatch) {\n this.originalOffset = offsetMatch[1] === 'z' ? 'Z' : offsetMatch[1];\n }\n }\n \n toISOString(): string {\n if (this.originalOffset) {\n const localTime = new Date(this.getTime() + parseOffsetMinutes(this.originalOffset) * 60000);\n const p = fmtParts(localTime);\n const sep = this.useSpaceSeparator ? ' ' : 'T';\n const msSuffix = fmtMs(p.ms, this.originalFormat, /\\.(\\d+)(?:[Zz]|[+-]\\d{2}:\\d{2})\\s*$/);\n return `${p.year}-${p.month}-${p.day}${sep}${p.hours}:${p.minutes}:${p.seconds}${msSuffix}${this.originalOffset}`;\n }\n \n const isoString = super.toISOString();\n if (this.useSpaceSeparator) {\n return isoString.replace('T', ' ');\n }\n return isoString;\n }\n}"],"mappings":";;;;;;;;AAWA,SAAS,SAAS,GAAS;CACzB,OAAO;EACL,MAAM,OAAO,EAAE,eAAe,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG;EAChD,OAAO,OAAO,EAAE,YAAY,IAAI,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG;EAClD,KAAK,OAAO,EAAE,WAAW,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG;EAC3C,OAAO,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG;EAC9C,SAAS,OAAO,EAAE,cAAc,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG;EAClD,SAAS,OAAO,EAAE,cAAc,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG;EAClD,IAAI,EAAE,mBAAmB;CAC3B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, preserving any leading BOM.
5
+ */
6
+ function decodeUtf8Bytes(value) {
7
+ return new TextDecoder("utf-8", {
8
+ fatal: true,
9
+ ignoreBOM: true
10
+ }).decode(value);
11
+ }
12
+ /**
13
+ * Returns true when the input starts with a Unicode BOM character (U+FEFF).
14
+ */
15
+ function hasLeadingBom(value) {
16
+ return value.charCodeAt(0) === 65279;
17
+ }
18
+ /**
19
+ * Strips a leading Unicode BOM character (U+FEFF) from string input.
20
+ */
21
+ function stripLeadingBom(value) {
22
+ return hasLeadingBom(value) ? value.slice(1) : value;
23
+ }
24
+
25
+ //#endregion
26
+ export { decodeUtf8Bytes, hasLeadingBom, stripLeadingBom };
27
+ //# sourceMappingURL=decode-utf8.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decode-utf8.js","names":[],"sources":["../../src/decode-utf8.ts"],"sourcesContent":["/**\n * UTF-8 BOM marker (U+FEFF).\n */\nexport const UTF8_BOM = '\\uFEFF';\n\n/**\n * Decodes UTF-8 bytes in fatal mode, preserving any leading BOM.\n */\nexport function decodeUtf8Bytes(value: Uint8Array): string {\n return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(value);\n}\n\n/**\n * Returns true when the input starts with a Unicode BOM character (U+FEFF).\n */\nexport function hasLeadingBom(value: string): boolean {\n return value.charCodeAt(0) === 0xfeff;\n}\n\n/**\n * Returns true when raw bytes start with a UTF-8 BOM prefix.\n */\nexport function hasLeadingUtf8BomBytes(value: Uint8Array): boolean {\n return value.length >= 3 && value[0] === 0xef && value[1] === 0xbb && value[2] === 0xbf;\n}\n\n/**\n * Strips a leading Unicode BOM character (U+FEFF) from string input.\n */\nexport function stripLeadingBom(value: string): string {\n return hasLeadingBom(value) ? value.slice(1) : value;\n}\n"],"mappings":";;;;;AAQA,SAAgB,gBAAgB,OAA2B;CACzD,OAAO,IAAI,YAAY,SAAS;EAAE,OAAO;EAAM,WAAW;CAAK,CAAC,CAAC,CAAC,OAAO,KAAK;AAChF;;;;AAKA,SAAgB,cAAc,OAAwB;CACpD,OAAO,MAAM,WAAW,CAAC,MAAM;AACjC;;;;AAYA,SAAgB,gBAAgB,OAAuB;CACrD,OAAO,cAAc,KAAK,IAAI,MAAM,MAAM,CAAC,IAAI;AACjD"}
@@ -0,0 +1,269 @@
1
+ //! @decimalturn/toml-patch v3.1.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
+ import { datesEqual, isObject, merge, stableStringify } from "./utils.js";
3
+
4
+ //#region src/diff.ts
5
+ function isAdd(change) {
6
+ return change.type === "Add";
7
+ }
8
+ function isEdit(change) {
9
+ return change.type === "Edit";
10
+ }
11
+ function isRemove(change) {
12
+ return change.type === "Remove";
13
+ }
14
+ function isMove(change) {
15
+ return change.type === "Move";
16
+ }
17
+ function isRename(change) {
18
+ return change.type === "Rename";
19
+ }
20
+ function diff(before, after, path = [], options = {}) {
21
+ if (before === after || datesEqual(before, after)) return [];
22
+ if (typeof before === "number" && typeof after === "number" && Number.isNaN(before) && Number.isNaN(after)) {
23
+ const bufBefore = new Float64Array([before]);
24
+ const bufAfter = new Float64Array([after]);
25
+ const viewBefore = new DataView(bufBefore.buffer);
26
+ const viewAfter = new DataView(bufAfter.buffer);
27
+ if ((viewBefore.getUint32(4, true) & 2147483648) === (viewAfter.getUint32(4, true) & 2147483648)) return [];
28
+ }
29
+ if (Array.isArray(before) && Array.isArray(after)) return compareArrays(before, after, path, options);
30
+ else if (isObject(before) && isObject(after)) return compareObjects(before, after, path, options);
31
+ else return [{
32
+ type: "Edit",
33
+ path
34
+ }];
35
+ }
36
+ function compareObjects(before, after, path = [], options = {}) {
37
+ let changes = [];
38
+ const before_keys = Object.keys(before);
39
+ const before_stable = before_keys.map((key) => stableStringify(before[key]));
40
+ const after_keys = Object.keys(after);
41
+ const after_stable = after_keys.map((key) => stableStringify(after[key]));
42
+ const after_stable_by_key = new Map(after_keys.map((key, index) => [key, after_stable[index]]));
43
+ const before_key_set = new Set(before_keys);
44
+ const after_key_set = new Set(after_keys);
45
+ const groupByValue = (keys, stables, exclude) => {
46
+ const groups = /* @__PURE__ */ new Map();
47
+ keys.forEach((key, index) => {
48
+ if (exclude.has(key)) return;
49
+ const group = groups.get(stables[index]);
50
+ if (group) group.push(key);
51
+ else groups.set(stables[index], [key]);
52
+ });
53
+ return groups;
54
+ };
55
+ const disappeared = groupByValue(before_keys, before_stable, after_key_set);
56
+ const appeared = groupByValue(after_keys, after_stable, before_key_set);
57
+ const renamed = /* @__PURE__ */ new Map();
58
+ const renameTargets = /* @__PURE__ */ new Set();
59
+ const renameSourcesByTarget = /* @__PURE__ */ new Map();
60
+ for (const [value, sources] of disappeared) {
61
+ const targets = appeared.get(value);
62
+ if (!targets) continue;
63
+ const pairs = Math.min(sources.length, targets.length);
64
+ for (let i = 0; i < pairs; i++) {
65
+ renamed.set(sources[i], targets[i]);
66
+ renameTargets.add(targets[i]);
67
+ renameSourcesByTarget.set(targets[i], sources[i]);
68
+ }
69
+ }
70
+ before_keys.forEach((key, index) => {
71
+ const sub_path = path.concat(key);
72
+ if (after_key_set.has(key)) {
73
+ const beforeValue = before[key];
74
+ const afterValue = after[key];
75
+ const hasNonFiniteNumber = typeof beforeValue === "number" && !Number.isFinite(beforeValue) || typeof afterValue === "number" && !Number.isFinite(afterValue);
76
+ if (options.updateOrder || hasNonFiniteNumber || before_stable[index] !== after_stable_by_key.get(key)) merge(changes, diff(before[key], after[key], sub_path, options));
77
+ } else if (renamed.has(key)) changes.push({
78
+ type: "Rename",
79
+ path,
80
+ from: key,
81
+ to: renamed.get(key)
82
+ });
83
+ else changes.push({
84
+ type: "Remove",
85
+ path: sub_path
86
+ });
87
+ });
88
+ after_keys.forEach((key) => {
89
+ if (!before_key_set.has(key) && !renameTargets.has(key)) {
90
+ const add = {
91
+ type: "Add",
92
+ path: path.concat(key)
93
+ };
94
+ if (options.orderSource !== void 0) {
95
+ let orderObject = options.orderSource;
96
+ for (const segment of path) orderObject = orderObject === null || orderObject === void 0 ? void 0 : orderObject[segment];
97
+ if (isObject(orderObject)) {
98
+ const requestedKeys = Object.keys(orderObject);
99
+ const addedIndex = requestedKeys.indexOf(key);
100
+ for (let i = addedIndex + 1; i < requestedKeys.length; i++) {
101
+ const target = requestedKeys[i];
102
+ const source = renameSourcesByTarget.get(target) ?? (before_key_set.has(target) ? target : void 0);
103
+ if (source !== void 0) {
104
+ add.before = source;
105
+ break;
106
+ }
107
+ }
108
+ }
109
+ }
110
+ changes.push(add);
111
+ }
112
+ });
113
+ let requestedKeys = after_keys;
114
+ if (options.orderSource !== void 0) {
115
+ let orderObject = options.orderSource;
116
+ for (const segment of path) orderObject = orderObject === null || orderObject === void 0 ? void 0 : orderObject[segment];
117
+ if (isObject(orderObject)) {
118
+ const afterKeySet = new Set(after_keys);
119
+ requestedKeys = Object.keys(orderObject).filter((key) => afterKeySet.has(key));
120
+ }
121
+ }
122
+ const directChanges = changes.filter((change) => isAdd(change) && change.path.length === path.length + 1 || isRename(change) && change.path.length === path.length);
123
+ if (options.orderSource !== void 0 && directChanges.length > 1) {
124
+ const orderedDirectChanges = [...directChanges].sort((a, b) => {
125
+ const aKey = isAdd(a) ? a.path[a.path.length - 1] : isRename(a) ? a.to : "";
126
+ const bKey = isAdd(b) ? b.path[b.path.length - 1] : isRename(b) ? b.to : "";
127
+ return requestedKeys.indexOf(aKey) - requestedKeys.indexOf(bKey);
128
+ });
129
+ let directIndex = 0;
130
+ changes = changes.map((change) => directChanges.includes(change) ? orderedDirectChanges[directIndex++] : change);
131
+ }
132
+ if (options.updateOrder) {
133
+ const sim = [];
134
+ for (const key of before_keys) if (after_key_set.has(key)) {
135
+ if (!sim.includes(key)) sim.push(key);
136
+ } else if (renamed.has(key)) {
137
+ const to = renamed.get(key);
138
+ if (!sim.includes(to)) sim.push(to);
139
+ }
140
+ for (const key of after_keys) if (!sim.includes(key)) sim.push(key);
141
+ after_keys.forEach((key, targetIndex) => {
142
+ if (sim[targetIndex] === key) return;
143
+ const from = sim.indexOf(key);
144
+ changes.push({
145
+ type: "Move",
146
+ path,
147
+ from,
148
+ to: targetIndex,
149
+ key
150
+ });
151
+ sim.splice(from, 1);
152
+ sim.splice(targetIndex, 0, key);
153
+ });
154
+ }
155
+ return changes;
156
+ }
157
+ function hasMultilineValue(v) {
158
+ if (typeof v === "string") return v.includes("\n");
159
+ if (Array.isArray(v)) return v.length > 0;
160
+ if (v !== null && typeof v === "object" && !(v instanceof Date)) {
161
+ const vals = Object.values(v);
162
+ return vals.some((x) => x !== null && typeof x === "object") || vals.some(hasMultilineValue);
163
+ }
164
+ return false;
165
+ }
166
+ function hasInlineObject(value) {
167
+ return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date);
168
+ }
169
+ function hasMixedStringAndObject(values) {
170
+ return values.length > 4 && values.some((value) => typeof value === "string") && values.some(hasInlineObject);
171
+ }
172
+ function compareArrays(before, after, path = [], options = {}) {
173
+ let changes = [];
174
+ const before_stable = before.map(stableStringify);
175
+ const after_stable = after.map(stableStringify);
176
+ const layoutSensitiveArray = before.some(hasMultilineValue) || after.some(hasMultilineValue) || hasMixedStringAndObject(before) || hasMixedStringAndObject(after);
177
+ const before_sim = before.slice();
178
+ let removedBefore = 0;
179
+ let sameArrayAddEmitted = false;
180
+ const removeChange = (index) => {
181
+ const change = {
182
+ type: "Remove",
183
+ path: path.concat(index)
184
+ };
185
+ if (!sameArrayAddEmitted || removedBefore > 0) Object.defineProperty(change, "coordinate", { value: "source" });
186
+ return change;
187
+ };
188
+ for (let index = 0; index < after_stable.length; index++) {
189
+ const value = after_stable[index];
190
+ const overflow = index >= before_stable.length;
191
+ if (!overflow && before_stable[index] === value) continue;
192
+ const from = overflow ? -1 : before_stable.indexOf(value, index + 1);
193
+ if (from > -1) {
194
+ const valueAt = before_stable[index];
195
+ let beforeCount = 0;
196
+ for (let i = index; i < before_stable.length; i++) if (before_stable[i] === valueAt) beforeCount++;
197
+ let afterCount = 0;
198
+ for (let i = index; i < after_stable.length; i++) if (after_stable[i] === valueAt) afterCount++;
199
+ const surplusDuplicate = beforeCount > afterCount;
200
+ if (layoutSensitiveArray && (after_stable.indexOf(before_stable[index]) === -1 || surplusDuplicate)) {
201
+ changes.push(removeChange(index + removedBefore));
202
+ before_stable.splice(index, 1);
203
+ before_sim.splice(index, 1);
204
+ removedBefore++;
205
+ index--;
206
+ continue;
207
+ }
208
+ if (removedBefore > 0 && surplusDuplicate) {
209
+ changes.push(removeChange(index + removedBefore));
210
+ before_stable.splice(index, 1);
211
+ before_sim.splice(index, 1);
212
+ removedBefore++;
213
+ index--;
214
+ continue;
215
+ }
216
+ if (layoutSensitiveArray && removedBefore > 0) {
217
+ changes.push({
218
+ type: "Add",
219
+ path: path.concat(index)
220
+ });
221
+ sameArrayAddEmitted = true;
222
+ before_stable.splice(index, 0, value);
223
+ before_sim.splice(index, 0, after[index]);
224
+ removedBefore--;
225
+ continue;
226
+ }
227
+ changes.push({
228
+ type: "Move",
229
+ path,
230
+ from,
231
+ to: index
232
+ });
233
+ const move = before_stable.splice(from, 1);
234
+ before_stable.splice(index, 0, ...move);
235
+ const moveValues = before_sim.splice(from, 1);
236
+ before_sim.splice(index, 0, ...moveValues);
237
+ continue;
238
+ }
239
+ let surplus = false;
240
+ if (!overflow) {
241
+ const value = before_stable[index];
242
+ let beforeCount = 0;
243
+ for (let i = index; i < before_stable.length; i++) if (before_stable[i] === value) beforeCount++;
244
+ let afterCount = 0;
245
+ for (let i = index; i < after_stable.length; i++) if (after_stable[i] === value) afterCount++;
246
+ surplus = beforeCount > afterCount;
247
+ }
248
+ if (!overflow && surplus) {
249
+ merge(changes, diff(before_sim[index], after[index], path.concat(index), options));
250
+ before_stable[index] = value;
251
+ before_sim[index] = after[index];
252
+ continue;
253
+ }
254
+ changes.push({
255
+ type: "Add",
256
+ path: path.concat(index)
257
+ });
258
+ sameArrayAddEmitted = true;
259
+ before_stable.splice(index, 0, value);
260
+ before_sim.splice(index, 0, after[index]);
261
+ if (removedBefore > 0) removedBefore--;
262
+ }
263
+ for (let i = after_stable.length; i < before_stable.length; i++) changes.push(removeChange(i + removedBefore));
264
+ return changes;
265
+ }
266
+
267
+ //#endregion
268
+ export { diff as default, isAdd, isEdit, isMove, isRemove, isRename };
269
+ //# sourceMappingURL=diff.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diff.js","names":[],"sources":["../../src/diff.ts"],"sourcesContent":["import { isObject, datesEqual, stableStringify, merge } from './utils';\nimport { Path } from './find-by-path';\n\nexport enum ChangeType {\n Add = 'Add',\n Edit = 'Edit',\n Remove = 'Remove',\n Move = 'Move',\n Rename = 'Rename'\n}\n\nexport interface Add {\n type: ChangeType.Add;\n path: Path;\n /** Existing sibling key that the new member must be inserted before. */\n before?: string;\n}\nexport function isAdd(change: Change): change is Add {\n return change.type === ChangeType.Add;\n}\n\nexport interface Edit {\n type: ChangeType.Edit;\n path: Path;\n}\nexport function isEdit(change: Change): change is Edit {\n return change.type === ChangeType.Edit;\n}\n\nexport interface Remove {\n type: ChangeType.Remove;\n path: Path;\n /** Internal marker for array removes whose index refers to the original array. */\n coordinate?: 'source';\n}\nexport function isRemove(change: Change): change is Remove {\n return change.type === ChangeType.Remove;\n}\n\nexport interface Move {\n type: ChangeType.Move;\n path: Path;\n from: number;\n to: number;\n /** Present only for object-key moves (updateOrder); identifies the child to place. */\n key?: string;\n}\nexport function isMove(change: Change): change is Move {\n return change.type === ChangeType.Move;\n}\n\nexport interface Rename {\n type: ChangeType.Rename;\n path: Path;\n from: string;\n to: string;\n}\nexport function isRename(change: Change): change is Rename {\n return change.type === ChangeType.Rename;\n}\n\nexport type Change = Add | Edit | Remove | Move | Rename;\n\nexport interface DiffOptions {\n /**\n * When true, `compareObjects` additionally emits Moves so that object keys end up in the\n * same order as `after`'s. Off by default: a no-options `diff()` call emits zero Moves for\n * a pure key-order permutation, which is the compatibility guarantee callers rely on. See\n * docs/PLAN-Update-Order.md.\n */\n updateOrder?: boolean;\n /** Object graph whose key order represents the caller's requested order. */\n orderSource?: any;\n}\n\nexport default function diff(before: any, after: any, path: Path = [], options: DiffOptions = {}): Change[] {\n if (before === after || datesEqual(before, after)) {\n return [];\n }\n\n // Both NaN — treat as equal only if they have the same sign bit.\n // -NaN and NaN are distinguishable via IEEE 754, so a sign change\n // from negative NaN to canonical NaN should trigger an edit.\n if (typeof before === 'number' && typeof after === 'number'\n && Number.isNaN(before) && Number.isNaN(after)) {\n const bufBefore = new Float64Array([before]);\n const bufAfter = new Float64Array([after]);\n const viewBefore = new DataView(bufBefore.buffer);\n const viewAfter = new DataView(bufAfter.buffer);\n const signBefore = viewBefore.getUint32(4, true) & 0x80000000;\n const signAfter = viewAfter.getUint32(4, true) & 0x80000000;\n if (signBefore === signAfter) return [];\n // Sign differs — fall through to produce an Edit\n }\n\n if (Array.isArray(before) && Array.isArray(after)) {\n return compareArrays(before, after, path, options);\n } else if (isObject(before) && isObject(after)) {\n return compareObjects(before, after, path, options);\n } else {\n return [\n {\n type: ChangeType.Edit,\n path\n }\n ];\n }\n}\n\nfunction compareObjects(before: any, after: any, path: Path = [], options: DiffOptions = {}): Change[] {\n let changes: Change[] = [];\n\n // 1. Get keys and stable values\n const before_keys = Object.keys(before);\n const before_stable = before_keys.map(key => stableStringify(before[key]));\n const after_keys = Object.keys(after);\n const after_stable = after_keys.map(key => stableStringify(after[key]));\n const after_stable_by_key = new Map(\n after_keys.map((key, index) => [key, after_stable[index]])\n );\n\n // Membership is tested once per key in each pass below, so these are Sets rather than the\n // key arrays: `includes` inside those loops makes the whole function quadratic in the\n // number of keys, which is felt on wide tables — a 2000-key object spent ~28ms there.\n const before_key_set = new Set(before_keys);\n const after_key_set = new Set(after_keys);\n\n // A key that disappeared is inferred to have been renamed when a key appears holding the\n // same value, since a rename is never declared — value equality is the only signal.\n //\n // Several keys can share a value, so the candidates are grouped by value and paired off in\n // order, as many as both sides can supply. Preserving comments is the point of this\n // library, so a plausible pairing is worth more than declining to guess: a renamed node is\n // edited in place and keeps its comments and formatting, whereas a remove-plus-add loses\n // them. Where the pairing is genuinely ambiguous the choice is arbitrary but harmless in\n // kind — a comment lands on one interchangeable key rather than another. Patching in\n // smaller steps removes the ambiguity for callers who care which.\n //\n // Pairing by position is what keeps it one-to-one. Matching with `indexOf` always resolved\n // to the first candidate, so every equal-valued source claimed the same target:\n // `{a:1,b:1} -> {z:1}` emitted two renames onto `z`, and the second blanked its node's\n // key, giving ` = 1` — output that does not parse. Leftovers on either side fall through\n // to Remove or Add.\n //\n // Keys present on both sides are excluded from both groups: they were not renamed and are\n // not available as targets. That is what keeps a removal whose value happens to match an\n // untouched sibling from being read as a rename onto it (issue #262).\n //\n // Tracked as from -> to because step 4 (order emission) has to follow a rename through\n // rather than treating the old name as simply gone.\n const groupByValue = (keys: string[], stables: string[], exclude: Set<string>) => {\n const groups = new Map<string, string[]>();\n keys.forEach((key, index) => {\n if (exclude.has(key)) return;\n const group = groups.get(stables[index]);\n if (group) group.push(key);\n else groups.set(stables[index], [key]);\n });\n return groups;\n };\n\n const disappeared = groupByValue(before_keys, before_stable, after_key_set);\n const appeared = groupByValue(after_keys, after_stable, before_key_set);\n\n const renamed = new Map<string, string>();\n const renameTargets = new Set<string>();\n const renameSourcesByTarget = new Map<string, string>();\n\n for (const [value, sources] of disappeared) {\n const targets = appeared.get(value);\n if (!targets) continue;\n\n const pairs = Math.min(sources.length, targets.length);\n for (let i = 0; i < pairs; i++) {\n renamed.set(sources[i], targets[i]);\n renameTargets.add(targets[i]);\n renameSourcesByTarget.set(targets[i], sources[i]);\n }\n }\n\n // 2. Check for changes, rename, and removed\n before_keys.forEach((key, index) => {\n const sub_path = path.concat(key);\n if (after_key_set.has(key)) {\n const beforeValue = before[key];\n const afterValue = after[key];\n const hasNonFiniteNumber =\n (typeof beforeValue === 'number' && !Number.isFinite(beforeValue)) ||\n (typeof afterValue === 'number' && !Number.isFinite(afterValue));\n if (options.updateOrder || hasNonFiniteNumber ||\n before_stable[index] !== after_stable_by_key.get(key)) {\n merge(changes, diff(before[key], after[key], sub_path, options));\n }\n } else if (renamed.has(key)) {\n changes.push({\n type: ChangeType.Rename,\n path,\n from: key,\n to: renamed.get(key)!\n });\n } else {\n changes.push({\n type: ChangeType.Remove,\n path: sub_path\n });\n }\n });\n\n // 3. Check for additions\n after_keys.forEach(key => {\n if (!before_key_set.has(key) && !renameTargets.has(key)) {\n const add: Add = {\n type: ChangeType.Add,\n path: path.concat(key)\n };\n\n // Adds normally append. If the caller supplied the original object whose order\n // should be honoured, anchor this add before the next member that already has a\n // slot. A rename uses its old key as the anchor because the rename runs in place.\n if (options.orderSource !== undefined) {\n let orderObject = options.orderSource;\n for (const segment of path) orderObject = orderObject?.[segment as any];\n if (isObject(orderObject)) {\n const requestedKeys = Object.keys(orderObject);\n const addedIndex = requestedKeys.indexOf(key);\n for (let i = addedIndex + 1; i < requestedKeys.length; i++) {\n const target = requestedKeys[i];\n const source = renameSourcesByTarget.get(target)\n ?? (before_key_set.has(target) ? target : undefined);\n if (source !== undefined) {\n add.before = source;\n break;\n }\n }\n }\n }\n\n changes.push(add);\n }\n });\n\n let requestedKeys = after_keys;\n if (options.orderSource !== undefined) {\n let orderObject = options.orderSource;\n for (const segment of path) orderObject = orderObject?.[segment as any];\n if (isObject(orderObject)) {\n const afterKeySet = new Set(after_keys);\n requestedKeys = Object.keys(orderObject).filter(key => afterKeySet.has(key));\n }\n }\n\n // A renamed member keeps its existing CST slot, while an added member is appended\n // by the patcher. Emit direct Adds and Renames in the updated object order so an\n // added dotted member can land before a renamed sibling without patch.ts inspecting\n // the CST or the complete change list.\n const directChanges = changes.filter(change =>\n (isAdd(change) && change.path.length === path.length + 1) ||\n (isRename(change) && change.path.length === path.length)\n );\n if (options.orderSource !== undefined && directChanges.length > 1) {\n const orderedDirectChanges = [...directChanges].sort((a, b) => {\n const aKey = isAdd(a) ? a.path[a.path.length - 1] : isRename(a) ? a.to : '';\n const bKey = isAdd(b) ? b.path[b.path.length - 1] : isRename(b) ? b.to : '';\n return requestedKeys.indexOf(aKey as string) - requestedKeys.indexOf(bKey as string);\n });\n let directIndex = 0;\n changes = changes.map(change =>\n directChanges.includes(change) ? orderedDirectChanges[directIndex++] : change\n );\n }\n\n // 4. Order emission (updateOrder only). Predict the key order the document will have\n // once Add/Remove/Rename above are applied, then walk the target order emitting a Move\n // wherever the prediction and the target disagree, splicing the prediction to match as we\n // go — the same simulate-and-splice approach compareArrays already uses for Move.\n if (options.updateOrder) {\n const sim: string[] = [];\n for (const key of before_keys) {\n if (after_key_set.has(key)) {\n if (!sim.includes(key)) sim.push(key);\n } else if (renamed.has(key)) {\n // Guard against the pre-existing spurious-rename case ({a:1,b:1} -> {b:1,x:1} emits\n // Rename a->b even though b is unchanged) pushing a duplicate into sim.\n const to = renamed.get(key)!;\n if (!sim.includes(to)) sim.push(to);\n }\n // removed -> drop\n }\n for (const key of after_keys) {\n if (!sim.includes(key)) sim.push(key); // adds append\n }\n\n after_keys.forEach((key, targetIndex) => {\n if (sim[targetIndex] === key) return;\n\n const from = sim.indexOf(key);\n changes.push({\n type: ChangeType.Move,\n path,\n from,\n to: targetIndex,\n key\n });\n\n sim.splice(from, 1);\n sim.splice(targetIndex, 0, key);\n });\n }\n\n return changes;\n}\n\n// Multiline-formatting proxies, hoisted so compareArrays doesn't rebuild them\n// per call. See the layoutSensitiveArray comment in compareArrays.\nfunction hasMultilineValue(v: any): boolean {\n if (typeof v === 'string') return v.includes('\\n');\n if (Array.isArray(v)) return v.length > 0;\n if (v !== null && typeof v === 'object' && !(v instanceof Date)) {\n const vals = Object.values(v);\n return vals.some(x => x !== null && typeof x === 'object') || vals.some(hasMultilineValue);\n }\n return false;\n}\n\nfunction hasInlineObject(value: any): boolean {\n return value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date);\n}\n\nfunction hasMixedStringAndObject(values: any[]): boolean {\n return values.length > 4 && values.some(value => typeof value === 'string') && values.some(hasInlineObject);\n}\n\nfunction compareArrays(before: any[], after: any[], path: Path = [], options: DiffOptions = {}): Change[] {\n let changes: Change[] = [];\n\n // 1. Convert arrays to stable objects\n const before_stable = before.map(stableStringify);\n const after_stable = after.map(stableStringify);\n\n // The writer corrupts multiline inline content when elements are relocated\n // (moves of elements holding multiline strings drop content lines — fuzz\n // seed 4765). Only for such arrays, prefer resolving a true deletion in\n // place over drifting the element right through a chain of Moves.\n // Multiline DELIMITED strings whose content is single-line aren't visible\n // here (the diff sees only values), but nested arrays/objects are a strong\n // proxy: those are what carry such formatting, and moving them corrupts\n // their interior the same way (fuzz seed 8512). A nested array or object\n // is itself evidence of multiline formatting even when its ELEMENTS are all\n // plain scalars — the formatter freely wraps such a container across lines,\n // and the diff cannot tell from values alone (fuzz seed 40181: removing a\n // scalar above a multiline `[218561, \"…\"]` chain-moved the array and dropped\n // columns out of its tail).\n const multilineArray = before.some(hasMultilineValue) || after.some(hasMultilineValue);\n const layoutSensitiveArray = multilineArray || hasMixedStringAndObject(before) || hasMixedStringAndObject(after);\n\n // Simulation of the actual VALUES, mutated in lockstep with before_stable.\n // The \"removed -> edited in place\" branch below must diff the element the\n // move simulation left at this index, not the untouched original: after a\n // Move, `before[index]` can hold a DIFFERENT element than the one whose\n // stable form sits at `before_stable[index]`, and diffing the wrong one\n // silently drops the edit (fuzz seed 340: `['4', …, true, …]` →\n // `[true, …]` moved `true` from 4 to 0, then diffed the original\n // `before[4]` — which was `true` — against `true`, emitting nothing for\n // the leftover string).\n const before_sim = before.slice();\n\n // Elements spliced out of `before` while walking the loop (the deletion\n // branch below). Remove paths are source coordinates — indices in the\n // ORIGINAL array — because the patcher applies same-array removals in\n // descending index order (see reorder() in patch.ts), so each emitted\n // index must stay valid against the un-shifted array.\n let removedBefore = 0;\n let sameArrayAddEmitted = false;\n\n const removeChange = (index: number): Remove => {\n const change: Remove = { type: ChangeType.Remove, path: path.concat(index) };\n if (!sameArrayAddEmitted || removedBefore > 0) {\n // Non-enumerable so `coordinate` stays out of the diff output that\n // callers and tests compare: it's an internal marker for reorder().\n Object.defineProperty(change, 'coordinate', { value: 'source' });\n }\n return change;\n };\n\n // 2. Step through after array making changes to before array as-needed\n for (let index = 0; index < after_stable.length; index++) {\n const value = after_stable[index];\n const overflow = index >= before_stable.length;\n\n // Check if items are the same\n if (!overflow && before_stable[index] === value) {\n continue;\n }\n\n // Check if item has been moved -> shift into place\n const from = overflow ? -1 : before_stable.indexOf(value, index + 1);\n if (from > -1) {\n // Is `before_stable[index]` (the mismatched element at this slot) a\n // surplus duplicate — more copies surviving in `before`'s unmatched\n // suffix than `after` demands? When so, the extra copy is genuinely\n // gone from this position and a removal in place is the honest edit.\n const valueAt = before_stable[index];\n let beforeCount = 0;\n for (let i = index; i < before_stable.length; i++) {\n if (before_stable[i] === valueAt) beforeCount++;\n }\n let afterCount = 0;\n for (let i = index; i < after_stable.length; i++) {\n if (after_stable[i] === valueAt) afterCount++;\n }\n const surplusDuplicate = beforeCount > afterCount;\n\n // A true deletion in move shape: the element at this position is\n // absent from `after` entirely (or is a surplus duplicate of a value\n // that later slots still hold), while the after-value sits later in\n // `before`. Without this the element only gets resolved at the end,\n // after a chain of Moves that relocates multiline elements — and the\n // writer corrupts their content (fuzz seed 4765: removing one scalar\n // from a multiline inline array dropped a line of a multiline string;\n // fuzz seed 35943: removing one of several duplicate scalars above a\n // nested multiline array chain-moved the array and corrupted its tail).\n if (layoutSensitiveArray && (after_stable.indexOf(before_stable[index]) === -1 || surplusDuplicate)) {\n changes.push(removeChange(index + removedBefore));\n before_stable.splice(index, 1);\n before_sim.splice(index, 1);\n removedBefore++;\n index--;\n continue;\n }\n\n // A Move emitted after an in-place deletion splice: its from/to are\n // simulation coordinates, but the patcher applies ALL removes first\n // (in descending index order) — when a trailing remove follows, the\n // move's source can be pushed out of bounds (fuzz seed 8138). When\n // the displaced element is a surplus duplicate, resolve it as a\n // removal in place instead of a Move: the remaining occurrences stay\n // where they are, so nothing needs to move.\n //\n // (Redundant with the surplus-duplicate removal above when\n // `layoutSensitiveArray` is set, but kept for the non-multiline case\n // where a prior splice already shifted indices and the surplus is\n // unambiguous.)\n if (removedBefore > 0 && surplusDuplicate) {\n changes.push(removeChange(index + removedBefore));\n before_stable.splice(index, 1);\n before_sim.splice(index, 1);\n removedBefore++;\n index--;\n continue;\n }\n\n // After an in-place removal this array is one element short at this\n // slot, so the after-value found later in `before` is NOT being\n // relocated — a fresh copy is needed here. Relocating it via a Move\n // drags multiline elements through a chain that later ADDs a new copy\n // anyway, and the writer corrupts their content (fuzz seed 62263: a\n // nested array above a multiline inline table replaced by a duplicate\n // scalar emitted Remove + Move + Add and mangled the table).\n if (layoutSensitiveArray && removedBefore > 0) {\n changes.push({\n type: ChangeType.Add,\n path: path.concat(index)\n });\n sameArrayAddEmitted = true;\n before_stable.splice(index, 0, value);\n before_sim.splice(index, 0, after[index]);\n // The fresh copy is spliced in BEFORE the original (at `from`), so it\n // shifts every later sim element — including the original we just\n // declined to move — one slot right. `removedBefore` models the\n // LEFT-shift of a prior remove, so a later Remove's source index\n // (`index + removedBefore`) is off by one and removes the wrong\n // element (fuzz seed 179377: `[false, '''…''', …]` edited and trimmed\n // removed its neighbour instead of the surplus scalar). Cancelling\n // one unit of the remove shift keeps the sim↔source mapping aligned.\n removedBefore--;\n continue;\n }\n\n changes.push({\n type: ChangeType.Move,\n path,\n from,\n to: index\n });\n\n const move = before_stable.splice(from, 1);\n before_stable.splice(index, 0, ...move);\n const moveValues = before_sim.splice(from, 1);\n before_sim.splice(index, 0, ...moveValues);\n\n continue;\n }\n\n // Check if item is removed -> assume it's been edited and replace.\n //\n // `after.includes(value)` alone is not enough: when the value also\n // occurs later in the array, the element is read as \"kept\", so the\n // mismatch becomes an Add plus a chain of Moves that re-finds the\n // duplicate — a pathological diff for a plain in-place edit (fuzz seed\n // 1406: `true` → `'4'` with another `true` later emitted Add(1) + six\n // Moves + Remove(10), and the writer corrupted a multiline string).\n // A duplicate further along in `before` can serve the later `after`\n // slot, so this occurrence is surplus whenever `before`'s unmatched\n // suffix holds more copies of the value than `after`'s does — then the\n // element is genuinely gone from its position and edited in place.\n let surplus = false;\n if (!overflow) {\n const value = before_stable[index];\n let beforeCount = 0;\n for (let i = index; i < before_stable.length; i++) {\n if (before_stable[i] === value) beforeCount++;\n }\n let afterCount = 0;\n for (let i = index; i < after_stable.length; i++) {\n if (after_stable[i] === value) afterCount++;\n }\n surplus = beforeCount > afterCount;\n }\n const removed = !overflow && surplus;\n if (removed) {\n merge(changes, diff(before_sim[index], after[index], path.concat(index), options));\n before_stable[index] = value;\n before_sim[index] = after[index];\n\n continue;\n }\n\n // Add as new item and shift existing\n changes.push({\n type: ChangeType.Add,\n path: path.concat(index)\n });\n sameArrayAddEmitted = true;\n before_stable.splice(index, 0, value);\n before_sim.splice(index, 0, after[index]);\n // Same source-index bookkeeping as the refused-move Add above: splicing a\n // new element in front of the surviving suffix shifts later sim indices\n // right by one, so a later Remove's source index (`index + removedBefore`)\n // is one too far right and targets the wrong element when a prior remove\n // is still pending. Cancel one unit of the remove shift (fuzz seed\n // 208822: editing a duplicate scalar and trimming a multiline array\n // removed the multiline string instead of the plain scalar).\n if (removedBefore > 0) removedBefore--;\n }\n\n // 3. Remove any remaining overflow items\n for (let i = after_stable.length; i < before_stable.length; i++) {\n changes.push(removeChange(i + removedBefore));\n }\n\n return changes;\n}\n"],"mappings":";;;;AAiBA,SAAgB,MAAM,QAA+B;CACnD,OAAO,OAAO;AAChB;AAMA,SAAgB,OAAO,QAAgC;CACrD,OAAO,OAAO;AAChB;AAQA,SAAgB,SAAS,QAAkC;CACzD,OAAO,OAAO;AAChB;AAUA,SAAgB,OAAO,QAAgC;CACrD,OAAO,OAAO;AAChB;AAQA,SAAgB,SAAS,QAAkC;CACzD,OAAO,OAAO;AAChB;AAgBA,SAAwB,KAAK,QAAa,OAAY,OAAa,CAAC,GAAG,UAAuB,CAAC,GAAa;CAC1G,IAAI,WAAW,SAAS,WAAW,QAAQ,KAAK,GAC9C,OAAO,CAAC;CAMV,IAAI,OAAO,WAAW,YAAY,OAAO,UAAU,YAC5C,OAAO,MAAM,MAAM,KAAK,OAAO,MAAM,KAA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