@decimalturn/toml-patch 3.0.2 → 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,11 +1,10 @@
1
+ <img src="assets/toml-patch-logo.png" alt="toml-patch logo" width="120"/>
2
+
1
3
  # toml-patch
2
4
 
3
5
  [![NPM Version](https://img.shields.io/npm/v/%40decimalturn%2Ftoml-patch?logo=npm&logoColor=white&labelColor=red&color=blue)](https://www.npmjs.com/package/@decimalturn/toml-patch)
4
6
  [![JSR Version](https://img.shields.io/jsr/v/%40decimalturn/toml-patch?logo=jsr&color=blue)](https://jsr.io/@decimalturn/toml-patch)
5
7
  [![GitHub branch status](https://img.shields.io/github/check-runs/DecimalTurn/toml-patch/latest)](https://github.com/DecimalTurn/toml-patch/actions/workflows/test-and-build.yml)
6
- <img src="assets/toml-patch-logo.png" alt="toml-patch logo" width="120" align="right" />
7
-
8
-
9
8
 
10
9
  Patch, parse, and stringify [TOML](https://toml.io/en/) (v1.1.0) while preserving comments and formatting.
11
10
 
@@ -13,37 +12,15 @@ This project started as a fork of the [original toml-patch](https://github.com/t
13
12
 
14
13
  We hope that these improvements can be incorporated upstream one day if the original author returns, but until then, this project is the actively maintained version.
15
14
 
16
- ## Table of Contents
15
+ ## Documentation
17
16
 
18
17
  - [Installation](#installation)
19
18
  - [API](#api)
20
- - [Functional API](#functional-api)
21
- - [patch](#patch)
22
- - [Example 1](#example-1)
23
- - [Example 2](#example-2)
24
- - [parse](#parse)
25
- - [Example](#example)
26
- - [stringify](#stringify)
27
- - [Example](#example-1)
28
- - [TomlDocument Class ](#tomldocument-class)
29
- - [Constructor](#constructor)
30
- - [Basic Usage Example](#basic-usage-example)
31
- - [Properties](#properties)
32
- - [Methods](#methods)
33
- - [patch() Example](#patch-example)
34
- - [update() Example](#update-example)
35
- - [Comment Ownership](#comment-ownership)
36
- - [Date/Time Handling & Temporal](#datetime-handling--temporal)
19
+ - [Comment ownership](#comment-ownership)
20
+ - [Date/time handling and Temporal](#datetime-handling--temporal)
37
21
  - [Formatting](#formatting)
38
- - [TomlFormat Class](#tomlformat-class)
39
- - [Basic Usage](#basic-usage)
40
- - [Formatting Options](#formatting-options)
41
- - [Auto-Detection and Patching](#auto-detection-and-patching)
42
- - [Complete Example](#complete-example)
43
- - [Legacy Format Objects](#legacy-format-objects)
44
- - [Changelog](#changelog)
45
- - [Contributing](#contributing)
46
-
22
+ - [Changelog](https://github.com/DecimalTurn/toml-patch/blob/v3.0.4/CHANGELOG.md)
23
+ - [Contributing](https://github.com/DecimalTurn/toml-patch/blob/v3.0.4/CONTRIBUTING.md)
47
24
 
48
25
  ## Installation
49
26
 
@@ -63,322 +40,21 @@ For browser usage, you can use unpkg:
63
40
 
64
41
  ## API
65
42
 
66
- toml-patch provides both a [functional API]((#functional-api)) for one-time operations and a [document-oriented API](#tomldocument-class) for more complex workflows.
67
-
68
- ### Functional API
69
-
70
- For simple one-time operations, you can use the functional API:
71
-
72
- #### <a id="patch"></a>patch(*existing*, *updated*, *format?*)
73
-
74
- ```typescript
75
- function patch(
76
- existing: string,
77
- updated: any,
78
- format?: Format,
79
- ): string
80
- ```
81
-
82
- Applies modifications to a TOML document by comparing an existing TOML string with updated JavaScript data.
83
-
84
- This function preserves formatting and comments from the existing TOML document while applying changes from the updated data structure. It performs a diff between the existing and updated data, then strategically applies only the necessary changes to maintain the original document structure as much as possible.
85
-
86
- **Parameters:**
87
- - `existing: string` - The original TOML document as a string
88
- - `updated: any` - The updated JavaScript object with desired changes
89
- - `format?: Format` - Optional formatting options to apply to new or modified sections
43
+ overwrite(tomlString: string): void
44
+ toml-patch provides a functional API for one-time operations and a document-oriented API for workflows that need multiple operations on the same TOML document.
90
45
 
91
- **Returns:** `string` - A new TOML string with the changes applied
46
+ See the [API reference](https://github.com/DecimalTurn/toml-patch/blob/v3.0.4/docs/API.md) for `patch`, `parse`, `stringify` and the `TomlDocument` class.
92
47
 
93
- Patch an existing TOML string with the given updated JS/JSON value, while attempting to retain the format of the existing document, including comments, indentation, and structure.
48
+ For a quick start, patch an existing TOML string like this:
94
49
 
95
- ##### Example 1
96
50
  ```js
97
- import * as TOML from '@decimalturn/toml-patch';
98
- import { strict as assert } from 'assert';
99
-
100
- const existing = `
101
- # This is a TOML document
51
+ import { patch } from '@decimalturn/toml-patch';
102
52
 
103
- title = "TOML example"
104
- owner.name = "Bob"
105
- `;
106
- const patched = TOML.patch(existing, {
53
+ const existing = 'title = "TOML example"\nowner.name = "Bob"\n';
54
+ const updated = patch(existing, {
107
55
  title: 'TOML example',
108
- owner: {
109
- name: 'Tim'
110
- }
111
- });
112
-
113
- assert.strictEqual(
114
- patched,
115
- `
116
- # This is a TOML document
117
-
118
- title = "TOML example"
119
- owner.name = "Tim"
120
- `
121
- );
122
- ```
123
-
124
- ##### Example 2
125
- ```js
126
- import * as TOML from '@decimalturn/toml-patch';
127
- import { strict as assert } from 'assert';
128
-
129
- const existing = `
130
- # This is a TOML document
131
-
132
- title = "TOML example"
133
- owner.name = "Bob"
134
- `;
135
-
136
- const jsObject = TOML.parse(existing);
137
- jsObject.owner.name = "Tim";
138
-
139
- const patched = TOML.patch(existing, jsObject);
140
-
141
- assert.strictEqual(
142
- patched,
143
- `
144
- # This is a TOML document
145
-
146
- title = "TOML example"
147
- owner.name = "Tim"
148
- `
149
- );
150
- ```
151
-
152
- #### <a id="parse"></a>parse(*value*, *options?*)
153
-
154
- ```typescript
155
- function parse(value: string | Uint8Array, options?: ParseOptions): any
156
- ```
157
-
158
- Parses a TOML string (or raw UTF-8 bytes) into a JavaScript object.
159
-
160
- **Parameters:**
161
- - `value: string | Uint8Array` - The TOML source to parse
162
- - `options?: ParseOptions` - Optional parse options
163
- - `integersAsBigInt?: 'asNeeded' | true | false` — Controls how TOML integers are represented in JS:
164
- - `'asNeeded'` *(default)* — integers within the JS safe-integer range are `number`; larger values are `bigint` to preserve precision
165
- - `true` — all integers are returned as `bigint`
166
- - `false` — all integers are returned as `number` (large values lose precision)
167
- - `temporal?: boolean` — When `true`, TOML date/time values are returned as [Temporal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Temporal) objects instead of custom `Date` subclasses. Default: `false`. Requires Temporal in the runtime (Node 26+ native, Node 20–24 with `--harmony-temporal`, or [@js-temporal/polyfill](https://www.npmjs.com/package/@js-temporal/polyfill) on any version). See [Date/Time Handling](#datetime-handling--temporal).
168
-
169
- **Returns:** `any` - The parsed JavaScript object
170
-
171
- > **Note:** The default `'asNeeded'` mode is a behavioral change from v1.0.7 and earlier. If your code serializes the result to JSON or mixes `number`/`bigint` arithmetic, set `integersAsBigInt: false` to restore the previous behavior.
172
-
173
- ##### Example
174
- ```js
175
- import * as TOML from '@decimalturn/toml-patch';
176
- import { strict as assert } from 'assert';
177
-
178
- const parsed = TOML.parse(`
179
- # This is a TOML document.
180
-
181
- title = "TOML Example"
182
-
183
- [owner]
184
- name = "Tim"`);
185
-
186
- assert.deepStrictEqual(parsed, {
187
- title: 'TOML Example',
188
- owner: {
189
- name: 'Tim'
190
- }
191
- });
192
- ```
193
-
194
- #### <a id="stringify"></a>stringify(*value*, *format?*)
195
-
196
- ```typescript
197
- function stringify(
198
- value: any,
199
- format?: Format,
200
- ): string
201
- ```
202
-
203
- Converts a JavaScript object to a TOML string.
204
-
205
- **Parameters:**
206
- - `value: any` - The JavaScript object to stringify
207
- - `format?: Format` - Optional formatting options for the resulting TOML
208
-
209
- **Returns:** `string` - The stringified TOML representation
210
-
211
- **Format Options:**
212
-
213
- See [Formatting Options](#formatting-options) for more details.
214
-
215
- ##### Example
216
-
217
- ```js
218
- import * as TOML from '@decimalturn/toml-patch';
219
- import { strict as assert } from 'assert';
220
-
221
- const toml = TOML.stringify({
222
- title: 'TOML Example',
223
- owner: {
224
- name: 'Tim'
225
- }
56
+ owner: { name: 'Tim' }
226
57
  });
227
-
228
- assert.strictEqual(
229
- toml,
230
- `title = "TOML Example"
231
-
232
- [owner]
233
- name = "Tim"`
234
- );
235
- ```
236
-
237
- ### TomlDocument Class
238
-
239
- The `TomlDocument` class provides a stateful interface for working with TOML documents. It's ideal when you need to perform multiple operations on the same document.
240
-
241
- #### Constructor
242
-
243
- ```typescript
244
- new TomlDocument(tomlSource: string | Uint8Array, options?: ParseOptions)
245
- ```
246
-
247
- Initializes the TomlDocument with TOML source, parsing it into an internal representation (CST). When bytes are provided they are decoded as UTF-8 in fatal mode, rejecting invalid sequences before parsing.
248
-
249
- > **Tip:** `parseDocument(value, options)` is a convenience alternative to `new TomlDocument(value, options)`.
250
-
251
- **Parameters:**
252
- - `tomlSource: string | Uint8Array` - The TOML source to parse
253
- - `options?: ParseOptions` - Optional parse options
254
- - `integersAsBigInt?: 'asNeeded' | true | false` — Controls how TOML integers are represented in `toJsObject`:
255
- - `'asNeeded'` *(default)* — integers within the JS safe-integer range are `number`; larger values are `bigint` to preserve precision
256
- - `true` — all integers are returned as `bigint`
257
- - `false` — all integers are returned as `number` (large values lose precision)
258
- - `temporal?: boolean` — When `true`, TOML date/time values are returned as [Temporal](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Temporal) objects. Default: `false`. Requires Temporal in the runtime (Node 26+ native, Node 20–24 with `--harmony-temporal`, or [@js-temporal/polyfill](https://www.npmjs.com/package/@js-temporal/polyfill) on any version). See [Date/Time Handling](#datetime-handling--temporal).
259
-
260
- ##### Basic Usage Example
261
-
262
- ```js
263
- import * as TOML from '@decimalturn/toml-patch';
264
-
265
- const doc = new TOML.TomlDocument(`
266
- # Configuration file
267
- title = "My App"
268
- version = "1.0.0"
269
-
270
- [database]
271
- host = "localhost"
272
- port = 5432
273
- `);
274
-
275
- console.log(doc.toJsObject);
276
- // Output: { title: "My App", version: "1.0.0", database: { host: "localhost", port: 5432 } }
277
- ```
278
-
279
- #### Properties
280
-
281
- ```typescript
282
- get toJsObject(): any
283
- get toTomlString(): string
284
- ```
285
-
286
- - `toJsObject: any` - Returns the JavaScript object representation of the TOML document
287
- - `toTomlString: string` - Returns the current TOML string representation
288
-
289
- #### Methods
290
-
291
- ```typescript
292
- patch(updatedObject: any, format?: Format): void
293
- update(tomlString: string): void
294
- overwrite(tomlString: string): void
295
- ```
296
-
297
- **patch(updatedObject, format?)**
298
- - Applies a patch to the current CST using a modified JS object
299
- - Updates the internal CST while preserving formatting and comments
300
- - Use `toTomlString` getter to retrieve the updated TOML string
301
- - **Parameters:**
302
- - `updatedObject: any` - The modified JS object to patch with
303
- - `format?: Format` - Optional formatting options
304
-
305
- **update(tomlString)**
306
- - Updates the internal CST by supplying a modified TOML string
307
- - Uses incremental parsing for efficiency (only re-parses changed portions)
308
- - Use `toJsObject` getter to retrieve the updated JS object representation
309
- - **Parameters:**
310
- - `tomlString: string` - The modified TOML string to update with
311
-
312
- **overwrite(tomlString)**
313
- - Overwrites the internal CST by fully re-parsing the supplied TOML string
314
- - Simpler but slower than `update()` which uses incremental parsing
315
- - **Parameters:**
316
- - `tomlString: string` - The TOML string to overwrite with
317
-
318
- ##### patch() Example
319
-
320
- *Using patch() to modify values while preserving formatting*
321
-
322
- ```js
323
- import * as TOML from '@decimalturn/toml-patch';
324
- // or: import { TomlDocument } from '@decimalturn/toml-patch';
325
-
326
- const doc = new TOML.TomlDocument(`
327
- # Configuration file
328
- title = "My App"
329
- version = "1.0.0"
330
-
331
- [database]
332
- host = "localhost"
333
- port = 5432
334
- `);
335
-
336
- // Modify the JavaScript object
337
- const config = doc.toJsObject;
338
- config.version = "2.0.0";
339
- config.database.port = 3306;
340
- config.database.name = "myapp_db";
341
-
342
- // Apply changes while preserving comments and formatting
343
- doc.patch(config);
344
-
345
- console.log(doc.toTomlString);
346
- // Output:
347
- // # Configuration file
348
- // title = "My App"
349
- // version = "2.0.0"
350
- //
351
- // [database]
352
- // host = "localhost"
353
- // port = 3306
354
- // name = "myapp_db"
355
- ```
356
-
357
- ##### update() Example
358
-
359
- *Using update() for efficient incremental parsing when the TOML string was edited*
360
-
361
- ```js
362
- import * as TOML from '@decimalturn/toml-patch';
363
- // or: import { TomlDocument } from '@decimalturn/toml-patch';
364
-
365
- const originalToml = `
366
- # Server configuration
367
- [server]
368
- host = "localhost"
369
- port = 8080
370
- debug = true
371
- `;
372
-
373
- const doc = new TOML.TomlDocument(originalToml);
374
-
375
- // Make a small change to the TOML string
376
- const updatedToml = originalToml.replace('port = 8080', 'port = 3000');
377
-
378
- // Efficiently update - only re-parses the changed portion
379
- doc.update(updatedToml);
380
-
381
- console.log(doc.toJsObject.server.port); // 3000
382
58
  ```
383
59
 
384
60
  ## Comment Ownership
@@ -405,11 +81,10 @@ y = 2
405
81
  `);
406
82
  ```
407
83
 
408
- See **[docs/CommentOwnership.md](docs/CommentOwnership.md)** for the full behavior, including how a
409
- blank line opts a comment out of ownership, and current scope limitations.
84
+ See the [comment ownership guide](https://github.com/DecimalTurn/toml-patch/blob/v3.0.4/docs/Comment-Ownership.md) for the full behavior, including how a blank line opts a comment out of ownership and current scope limitations.
410
85
 
411
86
  Note that `patch()` does not reorder entries by default.
412
- To have it match the key order of the object you pass in, enable [`updateOrder`](#formatting-options).
87
+ To have it match the key order of the object you pass in, enable `updateOrder` in the [formatting options](https://github.com/DecimalTurn/toml-patch/blob/v3.0.4/docs/Formatting.md#updateorder).
413
88
 
414
89
  ## Date/Time Handling & Temporal
415
90
 
@@ -441,13 +116,11 @@ const obj2 = TOML.parse('d = 2024-01-15\n', { temporal: true });
441
116
 
442
117
  > **Note:** Only offset-based timezones (`+05:30`, `Z`) are supported in TOML. IANA timezone annotations (e.g., `[Asia/Kolkata]`) will throw an error.
443
118
 
444
- See **[docs/Dates.md](docs/Dates.md)** for details and examples.
119
+ See the [date/time guide](https://github.com/DecimalTurn/toml-patch/blob/v3.0.4/docs/Dates.md) for details and examples.
445
120
 
446
121
  ## Formatting
447
122
 
448
- The `TomlFormat` class provides decent control over how TOML documents are formatted during stringification and patching operations. This class encapsulates all formatting preferences, making it easy to maintain consistent styling across your TOML documents.
449
-
450
- ### TomlFormat Class
123
+ The `TomlFormat` class controls how TOML documents are formatted during stringification and patching operations.
451
124
 
452
125
  ```typescript
453
126
  class TomlFormat {
@@ -466,21 +139,17 @@ class TomlFormat {
466
139
  }
467
140
  ```
468
141
 
469
- ### Basic Usage
470
-
471
- The recommended approach is to start with `TomlFormat.default()` and override specific options as needed:
142
+ Start with `TomlFormat.default()` and override the options you need:
472
143
 
473
144
  ```js
474
- import { patch, stringify, TomlFormat } from '@decimalturn/toml-patch';
145
+ import { stringify, TomlFormat } from '@decimalturn/toml-patch';
475
146
 
476
- // Create a custom format configuration
477
147
  const format = TomlFormat.default();
478
- format.newLine = '\r\n'; // Windows line endings
479
- format.trailingNewline = 0; // No trailing newline
480
- format.trailingComma = true; // Add trailing commas
481
- format.bracketSpacing = false; // No spaces in brackets
148
+ format.newLine = '\r\n';
149
+ format.trailingNewline = 0;
150
+ format.trailingComma = true;
151
+ format.bracketSpacing = false;
482
152
 
483
- // Use with stringify
484
153
  const toml = stringify({
485
154
  title: 'My App',
486
155
  tags: ['dev', 'config'],
@@ -489,287 +158,4 @@ const toml = stringify({
489
158
 
490
159
  ```
491
160
 
492
- ### Formatting Options
493
-
494
- **newLine**
495
- - **Type:** `string`
496
- - **Default:** `'\n'`
497
- - **Description:** The line ending character(s) to use in the output TOML. This option affects only the stringification process, not the internal representation (CST).
498
-
499
- ```js
500
- const format = TomlFormat.default();
501
- format.newLine = '\n'; // Unix/Linux line endings
502
- format.newLine = '\r\n'; // Windows line endings
503
- ```
504
-
505
- **trailingNewline**
506
- - **Type:** `number`
507
- - **Default:** `1`
508
- - **Description:** The number of trailing newlines to add at the end of the TOML document. This option affects only the stringification process, not the internal representation (CST).
509
-
510
- ```js
511
- const format = TomlFormat.default();
512
- format.trailingNewline = 0; // No trailing newline
513
- format.trailingNewline = 1; // One trailing newline (standard)
514
- format.trailingNewline = 2; // Two trailing newlines (adds extra spacing)
515
- ```
516
-
517
- **trailingComma**
518
- - **Type:** `boolean`
519
- - **Default:** `false`
520
- - **Description:** Whether to add trailing commas after the last element in arrays and inline tables.
521
-
522
- ```js
523
- const format = TomlFormat.default();
524
- format.trailingComma = false; // [1, 2, 3] and { x = 1, y = 2 }
525
- format.trailingComma = true; // [1, 2, 3,] and { x = 1, y = 2, }
526
- ```
527
-
528
- **bracketSpacing**
529
- - **Type:** `boolean`
530
- - **Default:** `true`
531
- - **Description:** Whether to add spaces after opening brackets/braces and before closing brackets/braces in arrays and inline tables.
532
-
533
- ```js
534
- const format = TomlFormat.default();
535
- format.bracketSpacing = true; // [ 1, 2, 3 ] and { x = 1, y = 2 }
536
- format.bracketSpacing = false; // [1, 2, 3] and {x = 1, y = 2}
537
- ```
538
-
539
- **leadingBom**
540
- - **Type:** `boolean`
541
- - **Default:** `false` (auto-detected from input)
542
- - **Description:** Whether to prepend a UTF-8 BOM (byte order mark, U+FEFF) to the output TOML. This is automatically detected from input strings and maintained through patch and stringify operations.
543
-
544
- **inlineTableStart**
545
- - **Type:** `number` (optional)
546
- - **Default:** `1`
547
- - **Description:** The nesting depth at which new tables should start being formatted as inline tables. When adding new tables during patching or stringifying objects, tables at depth bigger or equal to `inlineTableStart` will be formatted as inline tables, while tables at depth smaller than `inlineTableStart` will be formatted as separate table sections. Note that a table at the top-level of the TOML document is considered to have a depth of 0.
548
-
549
- ```js
550
- const format = TomlFormat.default();
551
- format.inlineTableStart = 0; // All tables are inline tables including top-level
552
- format.inlineTableStart = 1; // Top-level tables as sections, nested tables as inline (default)
553
- format.inlineTableStart = 2; // Two levels as sections, deeper nesting as inline
554
- ```
555
-
556
- Example with `inlineTableStart = 0`:
557
- ```js
558
- // With inlineTableStart = 0, all tables become inline
559
- const format = TomlFormat.default();
560
- format.inlineTableStart = 0;
561
- stringify({ database: { host: 'localhost', port: 5432 } }, format);
562
- // Output: database = { host = "localhost", port = 5432 }
563
- ```
564
-
565
- Example with `inlineTableStart = 1` (default):
566
- ```js
567
- // With inlineTableStart = 1, top-level tables are sections
568
- const format = TomlFormat.default();
569
- format.inlineTableStart = 1;
570
- stringify({ database: { host: 'localhost', port: 5432 } }, format);
571
- // Output:
572
- // [database]
573
- // host = "localhost"
574
- // port = 5432
575
- ```
576
-
577
- **truncateZeroTimeInDates**
578
- - **Type:** `boolean`
579
- - **Default:** `false`
580
- - **Description:** When `true`, JavaScript Date objects with all time components set to zero (midnight UTC) are automatically serialized as date-only values in TOML. This only affects new values during stringify operations; existing TOML dates maintain their original format during patch operations.
581
-
582
- ```js
583
- const format = TomlFormat.default();
584
- format.truncateZeroTimeInDates = false; // new Date('2024-01-15T00:00:00.000Z') → 2024-01-15T00:00:00.000Z
585
- format.truncateZeroTimeInDates = true; // new Date('2024-01-15T00:00:00.000Z') → 2024-01-15
586
- ```
587
-
588
- Example with mixed dates:
589
- ```js
590
- import { stringify, TomlFormat } from '@decimalturn/toml-patch';
591
-
592
- const format = TomlFormat.default();
593
- format.truncateZeroTimeInDates = true;
594
-
595
- const data = {
596
- startDate: new Date('2024-01-15T00:00:00.000Z'), // Will be: 2024-01-15
597
- endDate: new Date('2024-12-31T23:59:59.999Z') // Will be: 2024-12-31T23:59:59.999Z
598
- };
599
-
600
- stringify(data, format);
601
- // Output:
602
- // startDate = 2024-01-15
603
- // endDate = 2024-12-31T23:59:59.999Z
604
- ```
605
-
606
- **minimumDecimals**
607
- - **Type:** `number` (optional)
608
- - **Default:** `0`
609
- - **Description:** The minimum number of decimal places to use when serializing JS numbers as TOML floats. When greater than `0`, plain JS integer values are serialized as TOML floats padded with zeros to reach the specified decimal count. `bigint` values are always serialized as TOML integers regardless of this setting.
610
-
611
- ```js
612
- const format = TomlFormat.default();
613
- format.minimumDecimals = 0; // { x: 1, y: 1.5 } → { x = 1, y = 1.5 } (default)
614
- format.minimumDecimals = 1; // { x: 1, y: 1.5 } → { x = 1.0, y = 1.5 }
615
- format.minimumDecimals = 2; // { x: 1, y: 1.5 } → { x = 1.00, y = 1.50 }
616
- ```
617
-
618
- **updateOrder**
619
- - **Type:** `boolean` (optional)
620
- - **Default:** `false`
621
- - **Description:** Whether `patch()` should reorder entries to match the key order of the JS object you pass in, instead of preserving the existing document's order. Applies to root key-values, `[table]`/`[[array-of-tables]]` section blocks, and rows inside table bodies. Each entry's comments travel with it (see [docs/CommentOwnership.md](docs/CommentOwnership.md)). This option only affects `patch()`, and is never auto-detected — an existing document's order says nothing about what order you want.
622
-
623
- With the option off (the default), `patch()` only changes values that actually differ, leaving order alone. Given:
624
-
625
- ```toml
626
- b = 2
627
- a = 1
628
- ```
629
-
630
- ```js
631
- patch(existing, { a: 1, b: 2 }); // unchanged: b = 2 then a = 1
632
- patch(existing, { a: 1, b: 2 }, { updateOrder: true }); // reordered: a = 1 then b = 2
633
- ```
634
-
635
- Comments travel with their entry. Given:
636
-
637
- ```toml
638
- # the second one
639
- b = 2
640
-
641
- # the first one
642
- a = 1
643
- ```
644
-
645
- `patch(existing, { a: 1, b: 2 }, { updateOrder: true })` produces:
646
-
647
- ```toml
648
- # the first one
649
- a = 1
650
-
651
- # the second one
652
- b = 2
653
- ```
654
-
655
- TOML validity takes precedence over the requested order. A root key-value cannot appear after a section header (it would bind to that section), so root keys and section blocks are reordered independently of each other — a section is never pulled ahead of a root key, regardless of where it sits in the object. Given:
656
-
657
- ```toml
658
- [section]
659
- key = "value"
660
- ```
661
-
662
- `patch(existing, { new_root: 42, section: { key: 'value' } }, { updateOrder: true })` produces:
663
-
664
- ```toml
665
- new_root = 42
666
-
667
- [section]
668
- key = "value"
669
- ```
670
-
671
- Some shapes are not reordered yet: the interiors of inline tables (`{ a = 1, b = 2 }`) and of `[[array-of-tables]]` entries, dotted-key implicit tables, and documents where a table's sub-tables are non-contiguous (`[a]`, `[b]`, `[a.c]` — permuting these would silently relocate unrelated sections). In each case the affected entry is left exactly where it was, and `patch()` emits a `console.warn` naming what it couldn't place so the skip isn't silent.
672
-
673
- ### Auto-Detection and Patching
674
-
675
- The `TomlFormat.autoDetectFormat()` method analyzes existing TOML strings to automatically detect and preserve their current formatting. If you don't supply the `format` argument when patching an existing document, this is what will be used to determine the formatting to use when inserting new elements.
676
-
677
- Note that formatting of existing elements of a TOML string won't be affected by the `format` passed to `patch()` except for `newLine` and `trailingNewline` which are applied at the document level.
678
-
679
-
680
- ### Complete Example
681
-
682
- Here's a comprehensive example showing different formatting configurations:
683
-
684
- ```js
685
- import { stringify, TomlFormat } from '@decimalturn/toml-patch';
686
-
687
- const data = {
688
- title: 'Configuration Example',
689
- settings: {
690
- debug: true,
691
- timeout: 30
692
- },
693
- servers: ['web1', 'web2', 'db1'],
694
- database: {
695
- host: 'localhost',
696
- port: 5432,
697
- ssl: true
698
- }
699
- };
700
-
701
- // Compact formatting (minimal whitespace)
702
- const compact = TomlFormat.default();
703
- compact.bracketSpacing = false;
704
- compact.trailingNewline = 0;
705
-
706
- console.log(stringify(data, compact));
707
- // Output:
708
- // title = "Configuration Example"
709
- // servers = ["web1", "web2", "db1"]
710
- //
711
- // [settings]
712
- // debug = true
713
- // timeout = 30
714
- //
715
- // [database]
716
- // host = "localhost"
717
- // port = 5432
718
- // ssl = true
719
-
720
- // Spacious formatting (with trailing commas and extra spacing)
721
- const spacious = TomlFormat.default();
722
- spacious.trailingComma = true;
723
- spacious.bracketSpacing = true;
724
- spacious.trailingNewline = 2;
725
-
726
- console.log(stringify(data, spacious));
727
- // Output:
728
- // title = "Configuration Example"
729
- // servers = [ "web1", "web2", "db1", ]
730
- //
731
- // [settings]
732
- // debug = true
733
- // timeout = 30
734
- //
735
- // [database]
736
- // host = "localhost"
737
- // port = 5432
738
- // ssl = true
739
- //
740
- //
741
-
742
- // Windows-style formatting
743
- const windows = TomlFormat.default();
744
- windows.newLine = '\r\n';
745
- windows.bracketSpacing = false;
746
- windows.trailingNewline = 1;
747
-
748
- console.log(stringify(data, windows));
749
- // Same structure as compact but with \r\n line endings
750
- ```
751
-
752
- ### Legacy Format Objects
753
-
754
- For backward compatibility, you can still use anonymous objects for formatting options.
755
- ```js
756
- // Legacy approach (still supported)
757
- const result = stringify(data, {
758
- trailingComma: true,
759
- bracketSpacing: false
760
- });
761
-
762
- // Recommended approach
763
- const format = TomlFormat.default();
764
- format.trailingComma = true;
765
- format.bracketSpacing = false;
766
- const result = stringify(data, format);
767
- ```
768
-
769
- ## Changelog
770
-
771
- For a detailed history of changes, see the [CHANGELOG](CHANGELOG.md).
772
-
773
- ## Contributing
774
-
775
- We welcome contributions! Please see the [CONTRIBUTING](CONTRIBUTING.md) guide for details on how to get started, development workflow, and pull request requirements.
161
+ See the [formatting reference](https://github.com/DecimalTurn/toml-patch/blob/v3.0.4/docs/Formatting.md) for the complete list of options, auto-detection behavior, `updateOrder` and more examples.