@decimalturn/toml-patch 3.0.3 → 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
@@ -6,46 +6,21 @@
6
6
  [![JSR Version](https://img.shields.io/jsr/v/%40decimalturn/toml-patch?logo=jsr&color=blue)](https://jsr.io/@decimalturn/toml-patch)
7
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)
8
8
 
9
-
10
-
11
-
12
9
  Patch, parse, and stringify [TOML](https://toml.io/en/) (v1.1.0) while preserving comments and formatting.
13
10
 
14
11
  This project started as a fork of the [original toml-patch](https://github.com/timhall/toml-patch) but has since evolved into a standalone project with significant improvements in reliability and features. We've added TOML v1.1 support, introduced new APIs like `TomlDocument` and `TomlFormat` classes, fixed numerous bugs through increase in testing namely with [toml-test](https://github.com/toml-lang/toml-test).
15
12
 
16
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.
17
14
 
18
- ## Table of Contents
15
+ ## Documentation
19
16
 
20
17
  - [Installation](#installation)
21
18
  - [API](#api)
22
- - [Functional API](#functional-api)
23
- - [patch](#patch)
24
- - [Example 1](#example-1)
25
- - [Example 2](#example-2)
26
- - [parse](#parse)
27
- - [Example](#example)
28
- - [stringify](#stringify)
29
- - [Example](#example-1)
30
- - [TomlDocument Class ](#tomldocument-class)
31
- - [Constructor](#constructor)
32
- - [Basic Usage Example](#basic-usage-example)
33
- - [Properties](#properties)
34
- - [Methods](#methods)
35
- - [patch() Example](#patch-example)
36
- - [update() Example](#update-example)
37
- - [Comment Ownership](#comment-ownership)
38
- - [Date/Time Handling & Temporal](#datetime-handling--temporal)
19
+ - [Comment ownership](#comment-ownership)
20
+ - [Date/time handling and Temporal](#datetime-handling--temporal)
39
21
  - [Formatting](#formatting)
40
- - [TomlFormat Class](#tomlformat-class)
41
- - [Basic Usage](#basic-usage)
42
- - [Formatting Options](#formatting-options)
43
- - [Auto-Detection and Patching](#auto-detection-and-patching)
44
- - [Complete Example](#complete-example)
45
- - [Legacy Format Objects](#legacy-format-objects)
46
- - [Changelog](#changelog)
47
- - [Contributing](#contributing)
48
-
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)
49
24
 
50
25
  ## Installation
51
26
 
@@ -65,322 +40,21 @@ For browser usage, you can use unpkg:
65
40
 
66
41
  ## API
67
42
 
68
- toml-patch provides both a [functional API]((#functional-api)) for one-time operations and a [document-oriented API](#tomldocument-class) for more complex workflows.
69
-
70
- ### Functional API
71
-
72
- For simple one-time operations, you can use the functional API:
73
-
74
- #### <a id="patch"></a>patch(*existing*, *updated*, *format?*)
75
-
76
- ```typescript
77
- function patch(
78
- existing: string,
79
- updated: any,
80
- format?: Format,
81
- ): string
82
- ```
83
-
84
- Applies modifications to a TOML document by comparing an existing TOML string with updated JavaScript data.
85
-
86
- 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.
87
-
88
- **Parameters:**
89
- - `existing: string` - The original TOML document as a string
90
- - `updated: any` - The updated JavaScript object with desired changes
91
- - `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.
92
45
 
93
- **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.
94
47
 
95
- 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:
96
49
 
97
- ##### Example 1
98
50
  ```js
99
- import * as TOML from '@decimalturn/toml-patch';
100
- import { strict as assert } from 'assert';
101
-
102
- const existing = `
103
- # This is a TOML document
51
+ import { patch } from '@decimalturn/toml-patch';
104
52
 
105
- title = "TOML example"
106
- owner.name = "Bob"
107
- `;
108
- const patched = TOML.patch(existing, {
53
+ const existing = 'title = "TOML example"\nowner.name = "Bob"\n';
54
+ const updated = patch(existing, {
109
55
  title: 'TOML example',
110
- owner: {
111
- name: 'Tim'
112
- }
113
- });
114
-
115
- assert.strictEqual(
116
- patched,
117
- `
118
- # This is a TOML document
119
-
120
- title = "TOML example"
121
- owner.name = "Tim"
122
- `
123
- );
124
- ```
125
-
126
- ##### Example 2
127
- ```js
128
- import * as TOML from '@decimalturn/toml-patch';
129
- import { strict as assert } from 'assert';
130
-
131
- const existing = `
132
- # This is a TOML document
133
-
134
- title = "TOML example"
135
- owner.name = "Bob"
136
- `;
137
-
138
- const jsObject = TOML.parse(existing);
139
- jsObject.owner.name = "Tim";
140
-
141
- const patched = TOML.patch(existing, jsObject);
142
-
143
- assert.strictEqual(
144
- patched,
145
- `
146
- # This is a TOML document
147
-
148
- title = "TOML example"
149
- owner.name = "Tim"
150
- `
151
- );
152
- ```
153
-
154
- #### <a id="parse"></a>parse(*value*, *options?*)
155
-
156
- ```typescript
157
- function parse(value: string | Uint8Array, options?: ParseOptions): any
158
- ```
159
-
160
- Parses a TOML string (or raw UTF-8 bytes) into a JavaScript object.
161
-
162
- **Parameters:**
163
- - `value: string | Uint8Array` - The TOML source to parse
164
- - `options?: ParseOptions` - Optional parse options
165
- - `integersAsBigInt?: 'asNeeded' | true | false` — Controls how TOML integers are represented in JS:
166
- - `'asNeeded'` *(default)* — integers within the JS safe-integer range are `number`; larger values are `bigint` to preserve precision
167
- - `true` — all integers are returned as `bigint`
168
- - `false` — all integers are returned as `number` (large values lose precision)
169
- - `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).
170
-
171
- **Returns:** `any` - The parsed JavaScript object
172
-
173
- > **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.
174
-
175
- ##### Example
176
- ```js
177
- import * as TOML from '@decimalturn/toml-patch';
178
- import { strict as assert } from 'assert';
179
-
180
- const parsed = TOML.parse(`
181
- # This is a TOML document.
182
-
183
- title = "TOML Example"
184
-
185
- [owner]
186
- name = "Tim"`);
187
-
188
- assert.deepStrictEqual(parsed, {
189
- title: 'TOML Example',
190
- owner: {
191
- name: 'Tim'
192
- }
193
- });
194
- ```
195
-
196
- #### <a id="stringify"></a>stringify(*value*, *format?*)
197
-
198
- ```typescript
199
- function stringify(
200
- value: any,
201
- format?: Format,
202
- ): string
203
- ```
204
-
205
- Converts a JavaScript object to a TOML string.
206
-
207
- **Parameters:**
208
- - `value: any` - The JavaScript object to stringify
209
- - `format?: Format` - Optional formatting options for the resulting TOML
210
-
211
- **Returns:** `string` - The stringified TOML representation
212
-
213
- **Format Options:**
214
-
215
- See [Formatting Options](#formatting-options) for more details.
216
-
217
- ##### Example
218
-
219
- ```js
220
- import * as TOML from '@decimalturn/toml-patch';
221
- import { strict as assert } from 'assert';
222
-
223
- const toml = TOML.stringify({
224
- title: 'TOML Example',
225
- owner: {
226
- name: 'Tim'
227
- }
56
+ owner: { name: 'Tim' }
228
57
  });
229
-
230
- assert.strictEqual(
231
- toml,
232
- `title = "TOML Example"
233
-
234
- [owner]
235
- name = "Tim"`
236
- );
237
- ```
238
-
239
- ### TomlDocument Class
240
-
241
- 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.
242
-
243
- #### Constructor
244
-
245
- ```typescript
246
- new TomlDocument(tomlSource: string | Uint8Array, options?: ParseOptions)
247
- ```
248
-
249
- 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.
250
-
251
- > **Tip:** `parseDocument(value, options)` is a convenience alternative to `new TomlDocument(value, options)`.
252
-
253
- **Parameters:**
254
- - `tomlSource: string | Uint8Array` - The TOML source to parse
255
- - `options?: ParseOptions` - Optional parse options
256
- - `integersAsBigInt?: 'asNeeded' | true | false` — Controls how TOML integers are represented in `toJsObject`:
257
- - `'asNeeded'` *(default)* — integers within the JS safe-integer range are `number`; larger values are `bigint` to preserve precision
258
- - `true` — all integers are returned as `bigint`
259
- - `false` — all integers are returned as `number` (large values lose precision)
260
- - `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).
261
-
262
- ##### Basic Usage Example
263
-
264
- ```js
265
- import * as TOML from '@decimalturn/toml-patch';
266
-
267
- const doc = new TOML.TomlDocument(`
268
- # Configuration file
269
- title = "My App"
270
- version = "1.0.0"
271
-
272
- [database]
273
- host = "localhost"
274
- port = 5432
275
- `);
276
-
277
- console.log(doc.toJsObject);
278
- // Output: { title: "My App", version: "1.0.0", database: { host: "localhost", port: 5432 } }
279
- ```
280
-
281
- #### Properties
282
-
283
- ```typescript
284
- get toJsObject(): any
285
- get toTomlString(): string
286
- ```
287
-
288
- - `toJsObject: any` - Returns the JavaScript object representation of the TOML document
289
- - `toTomlString: string` - Returns the current TOML string representation
290
-
291
- #### Methods
292
-
293
- ```typescript
294
- patch(updatedObject: any, format?: Format): void
295
- update(tomlString: string): void
296
- overwrite(tomlString: string): void
297
- ```
298
-
299
- **patch(updatedObject, format?)**
300
- - Applies a patch to the current CST using a modified JS object
301
- - Updates the internal CST while preserving formatting and comments
302
- - Use `toTomlString` getter to retrieve the updated TOML string
303
- - **Parameters:**
304
- - `updatedObject: any` - The modified JS object to patch with
305
- - `format?: Format` - Optional formatting options
306
-
307
- **update(tomlString)**
308
- - Updates the internal CST by supplying a modified TOML string
309
- - Uses incremental parsing for efficiency (only re-parses changed portions)
310
- - Use `toJsObject` getter to retrieve the updated JS object representation
311
- - **Parameters:**
312
- - `tomlString: string` - The modified TOML string to update with
313
-
314
- **overwrite(tomlString)**
315
- - Overwrites the internal CST by fully re-parsing the supplied TOML string
316
- - Simpler but slower than `update()` which uses incremental parsing
317
- - **Parameters:**
318
- - `tomlString: string` - The TOML string to overwrite with
319
-
320
- ##### patch() Example
321
-
322
- *Using patch() to modify values while preserving formatting*
323
-
324
- ```js
325
- import * as TOML from '@decimalturn/toml-patch';
326
- // or: import { TomlDocument } from '@decimalturn/toml-patch';
327
-
328
- const doc = new TOML.TomlDocument(`
329
- # Configuration file
330
- title = "My App"
331
- version = "1.0.0"
332
-
333
- [database]
334
- host = "localhost"
335
- port = 5432
336
- `);
337
-
338
- // Modify the JavaScript object
339
- const config = doc.toJsObject;
340
- config.version = "2.0.0";
341
- config.database.port = 3306;
342
- config.database.name = "myapp_db";
343
-
344
- // Apply changes while preserving comments and formatting
345
- doc.patch(config);
346
-
347
- console.log(doc.toTomlString);
348
- // Output:
349
- // # Configuration file
350
- // title = "My App"
351
- // version = "2.0.0"
352
- //
353
- // [database]
354
- // host = "localhost"
355
- // port = 3306
356
- // name = "myapp_db"
357
- ```
358
-
359
- ##### update() Example
360
-
361
- *Using update() for efficient incremental parsing when the TOML string was edited*
362
-
363
- ```js
364
- import * as TOML from '@decimalturn/toml-patch';
365
- // or: import { TomlDocument } from '@decimalturn/toml-patch';
366
-
367
- const originalToml = `
368
- # Server configuration
369
- [server]
370
- host = "localhost"
371
- port = 8080
372
- debug = true
373
- `;
374
-
375
- const doc = new TOML.TomlDocument(originalToml);
376
-
377
- // Make a small change to the TOML string
378
- const updatedToml = originalToml.replace('port = 8080', 'port = 3000');
379
-
380
- // Efficiently update - only re-parses the changed portion
381
- doc.update(updatedToml);
382
-
383
- console.log(doc.toJsObject.server.port); // 3000
384
58
  ```
385
59
 
386
60
  ## Comment Ownership
@@ -407,11 +81,10 @@ y = 2
407
81
  `);
408
82
  ```
409
83
 
410
- See **[docs/CommentOwnership.md](docs/CommentOwnership.md)** for the full behavior, including how a
411
- 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.
412
85
 
413
86
  Note that `patch()` does not reorder entries by default.
414
- 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).
415
88
 
416
89
  ## Date/Time Handling & Temporal
417
90
 
@@ -443,13 +116,11 @@ const obj2 = TOML.parse('d = 2024-01-15\n', { temporal: true });
443
116
 
444
117
  > **Note:** Only offset-based timezones (`+05:30`, `Z`) are supported in TOML. IANA timezone annotations (e.g., `[Asia/Kolkata]`) will throw an error.
445
118
 
446
- 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.
447
120
 
448
121
  ## Formatting
449
122
 
450
- 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.
451
-
452
- ### TomlFormat Class
123
+ The `TomlFormat` class controls how TOML documents are formatted during stringification and patching operations.
453
124
 
454
125
  ```typescript
455
126
  class TomlFormat {
@@ -468,21 +139,17 @@ class TomlFormat {
468
139
  }
469
140
  ```
470
141
 
471
- ### Basic Usage
472
-
473
- 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:
474
143
 
475
144
  ```js
476
- import { patch, stringify, TomlFormat } from '@decimalturn/toml-patch';
145
+ import { stringify, TomlFormat } from '@decimalturn/toml-patch';
477
146
 
478
- // Create a custom format configuration
479
147
  const format = TomlFormat.default();
480
- format.newLine = '\r\n'; // Windows line endings
481
- format.trailingNewline = 0; // No trailing newline
482
- format.trailingComma = true; // Add trailing commas
483
- format.bracketSpacing = false; // No spaces in brackets
148
+ format.newLine = '\r\n';
149
+ format.trailingNewline = 0;
150
+ format.trailingComma = true;
151
+ format.bracketSpacing = false;
484
152
 
485
- // Use with stringify
486
153
  const toml = stringify({
487
154
  title: 'My App',
488
155
  tags: ['dev', 'config'],
@@ -491,287 +158,4 @@ const toml = stringify({
491
158
 
492
159
  ```
493
160
 
494
- ### Formatting Options
495
-
496
- **newLine**
497
- - **Type:** `string`
498
- - **Default:** `'\n'`
499
- - **Description:** The line ending character(s) to use in the output TOML. This option affects only the stringification process, not the internal representation (CST).
500
-
501
- ```js
502
- const format = TomlFormat.default();
503
- format.newLine = '\n'; // Unix/Linux line endings
504
- format.newLine = '\r\n'; // Windows line endings
505
- ```
506
-
507
- **trailingNewline**
508
- - **Type:** `number`
509
- - **Default:** `1`
510
- - **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).
511
-
512
- ```js
513
- const format = TomlFormat.default();
514
- format.trailingNewline = 0; // No trailing newline
515
- format.trailingNewline = 1; // One trailing newline (standard)
516
- format.trailingNewline = 2; // Two trailing newlines (adds extra spacing)
517
- ```
518
-
519
- **trailingComma**
520
- - **Type:** `boolean`
521
- - **Default:** `false`
522
- - **Description:** Whether to add trailing commas after the last element in arrays and inline tables.
523
-
524
- ```js
525
- const format = TomlFormat.default();
526
- format.trailingComma = false; // [1, 2, 3] and { x = 1, y = 2 }
527
- format.trailingComma = true; // [1, 2, 3,] and { x = 1, y = 2, }
528
- ```
529
-
530
- **bracketSpacing**
531
- - **Type:** `boolean`
532
- - **Default:** `true`
533
- - **Description:** Whether to add spaces after opening brackets/braces and before closing brackets/braces in arrays and inline tables.
534
-
535
- ```js
536
- const format = TomlFormat.default();
537
- format.bracketSpacing = true; // [ 1, 2, 3 ] and { x = 1, y = 2 }
538
- format.bracketSpacing = false; // [1, 2, 3] and {x = 1, y = 2}
539
- ```
540
-
541
- **leadingBom**
542
- - **Type:** `boolean`
543
- - **Default:** `false` (auto-detected from input)
544
- - **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.
545
-
546
- **inlineTableStart**
547
- - **Type:** `number` (optional)
548
- - **Default:** `1`
549
- - **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.
550
-
551
- ```js
552
- const format = TomlFormat.default();
553
- format.inlineTableStart = 0; // All tables are inline tables including top-level
554
- format.inlineTableStart = 1; // Top-level tables as sections, nested tables as inline (default)
555
- format.inlineTableStart = 2; // Two levels as sections, deeper nesting as inline
556
- ```
557
-
558
- Example with `inlineTableStart = 0`:
559
- ```js
560
- // With inlineTableStart = 0, all tables become inline
561
- const format = TomlFormat.default();
562
- format.inlineTableStart = 0;
563
- stringify({ database: { host: 'localhost', port: 5432 } }, format);
564
- // Output: database = { host = "localhost", port = 5432 }
565
- ```
566
-
567
- Example with `inlineTableStart = 1` (default):
568
- ```js
569
- // With inlineTableStart = 1, top-level tables are sections
570
- const format = TomlFormat.default();
571
- format.inlineTableStart = 1;
572
- stringify({ database: { host: 'localhost', port: 5432 } }, format);
573
- // Output:
574
- // [database]
575
- // host = "localhost"
576
- // port = 5432
577
- ```
578
-
579
- **truncateZeroTimeInDates**
580
- - **Type:** `boolean`
581
- - **Default:** `false`
582
- - **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.
583
-
584
- ```js
585
- const format = TomlFormat.default();
586
- format.truncateZeroTimeInDates = false; // new Date('2024-01-15T00:00:00.000Z') → 2024-01-15T00:00:00.000Z
587
- format.truncateZeroTimeInDates = true; // new Date('2024-01-15T00:00:00.000Z') → 2024-01-15
588
- ```
589
-
590
- Example with mixed dates:
591
- ```js
592
- import { stringify, TomlFormat } from '@decimalturn/toml-patch';
593
-
594
- const format = TomlFormat.default();
595
- format.truncateZeroTimeInDates = true;
596
-
597
- const data = {
598
- startDate: new Date('2024-01-15T00:00:00.000Z'), // Will be: 2024-01-15
599
- endDate: new Date('2024-12-31T23:59:59.999Z') // Will be: 2024-12-31T23:59:59.999Z
600
- };
601
-
602
- stringify(data, format);
603
- // Output:
604
- // startDate = 2024-01-15
605
- // endDate = 2024-12-31T23:59:59.999Z
606
- ```
607
-
608
- **minimumDecimals**
609
- - **Type:** `number` (optional)
610
- - **Default:** `0`
611
- - **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.
612
-
613
- ```js
614
- const format = TomlFormat.default();
615
- format.minimumDecimals = 0; // { x: 1, y: 1.5 } → { x = 1, y = 1.5 } (default)
616
- format.minimumDecimals = 1; // { x: 1, y: 1.5 } → { x = 1.0, y = 1.5 }
617
- format.minimumDecimals = 2; // { x: 1, y: 1.5 } → { x = 1.00, y = 1.50 }
618
- ```
619
-
620
- **updateOrder**
621
- - **Type:** `boolean` (optional)
622
- - **Default:** `false`
623
- - **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.
624
-
625
- With the option off (the default), `patch()` only changes values that actually differ, leaving order alone. Given:
626
-
627
- ```toml
628
- b = 2
629
- a = 1
630
- ```
631
-
632
- ```js
633
- patch(existing, { a: 1, b: 2 }); // unchanged: b = 2 then a = 1
634
- patch(existing, { a: 1, b: 2 }, { updateOrder: true }); // reordered: a = 1 then b = 2
635
- ```
636
-
637
- Comments travel with their entry. Given:
638
-
639
- ```toml
640
- # the second one
641
- b = 2
642
-
643
- # the first one
644
- a = 1
645
- ```
646
-
647
- `patch(existing, { a: 1, b: 2 }, { updateOrder: true })` produces:
648
-
649
- ```toml
650
- # the first one
651
- a = 1
652
-
653
- # the second one
654
- b = 2
655
- ```
656
-
657
- 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:
658
-
659
- ```toml
660
- [section]
661
- key = "value"
662
- ```
663
-
664
- `patch(existing, { new_root: 42, section: { key: 'value' } }, { updateOrder: true })` produces:
665
-
666
- ```toml
667
- new_root = 42
668
-
669
- [section]
670
- key = "value"
671
- ```
672
-
673
- 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.
674
-
675
- ### Auto-Detection and Patching
676
-
677
- 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.
678
-
679
- 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.
680
-
681
-
682
- ### Complete Example
683
-
684
- Here's a comprehensive example showing different formatting configurations:
685
-
686
- ```js
687
- import { stringify, TomlFormat } from '@decimalturn/toml-patch';
688
-
689
- const data = {
690
- title: 'Configuration Example',
691
- settings: {
692
- debug: true,
693
- timeout: 30
694
- },
695
- servers: ['web1', 'web2', 'db1'],
696
- database: {
697
- host: 'localhost',
698
- port: 5432,
699
- ssl: true
700
- }
701
- };
702
-
703
- // Compact formatting (minimal whitespace)
704
- const compact = TomlFormat.default();
705
- compact.bracketSpacing = false;
706
- compact.trailingNewline = 0;
707
-
708
- console.log(stringify(data, compact));
709
- // Output:
710
- // title = "Configuration Example"
711
- // servers = ["web1", "web2", "db1"]
712
- //
713
- // [settings]
714
- // debug = true
715
- // timeout = 30
716
- //
717
- // [database]
718
- // host = "localhost"
719
- // port = 5432
720
- // ssl = true
721
-
722
- // Spacious formatting (with trailing commas and extra spacing)
723
- const spacious = TomlFormat.default();
724
- spacious.trailingComma = true;
725
- spacious.bracketSpacing = true;
726
- spacious.trailingNewline = 2;
727
-
728
- console.log(stringify(data, spacious));
729
- // Output:
730
- // title = "Configuration Example"
731
- // servers = [ "web1", "web2", "db1", ]
732
- //
733
- // [settings]
734
- // debug = true
735
- // timeout = 30
736
- //
737
- // [database]
738
- // host = "localhost"
739
- // port = 5432
740
- // ssl = true
741
- //
742
- //
743
-
744
- // Windows-style formatting
745
- const windows = TomlFormat.default();
746
- windows.newLine = '\r\n';
747
- windows.bracketSpacing = false;
748
- windows.trailingNewline = 1;
749
-
750
- console.log(stringify(data, windows));
751
- // Same structure as compact but with \r\n line endings
752
- ```
753
-
754
- ### Legacy Format Objects
755
-
756
- For backward compatibility, you can still use anonymous objects for formatting options.
757
- ```js
758
- // Legacy approach (still supported)
759
- const result = stringify(data, {
760
- trailingComma: true,
761
- bracketSpacing: false
762
- });
763
-
764
- // Recommended approach
765
- const format = TomlFormat.default();
766
- format.trailingComma = true;
767
- format.bracketSpacing = false;
768
- const result = stringify(data, format);
769
- ```
770
-
771
- ## Changelog
772
-
773
- For a detailed history of changes, see the [CHANGELOG](CHANGELOG.md).
774
-
775
- ## Contributing
776
-
777
- 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.