@decimalturn/toml-patch

中文文档
3.3.2发布于 2026/11/01MITTypeScriptES Module零依赖构建来源已验证

Patch, parse, and stringify TOML while preserving comments, whitespace and formatting.

原始使用文档
文档目录8 节
  1. Documentation
  2. Installation
  3. API
  4. Patch-lite
  5. Comment Ownership
  6. Date/Time Handling & Temporal
  7. Enabling Temporal
  8. Formatting
toml-patch logo

toml-patch

NPM Version JSR Version GitHub branch status

Patch, parse, and stringify TOML (v1.1.0) while preserving comments, whitespace and formatting.

This project started as a fork of the original 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.

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.

Documentation

Installation

toml-patch is dependency-free and can be installed via your favorite package manager.

Example with NPM

$ npm install --save @decimalturn/toml-patch

For the standalone lite distribution, install the lite npm dist-tag:

$ npm install --save @decimalturn/toml-patch@lite

For browser usage, you can use unpkg:

<script type="module">
  import * as TOML from 'https://unpkg.com/@decimalturn/[email protected]/dist/toml-patch.js';
</script>

API

overwrite(tomlString: string): void 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.

See the API reference for patch, parse, stringify and the TomlDocument class.

For a quick start, patch an existing TOML string like this:

import { patch } from '@decimalturn/toml-patch';

const existing = 'title = "TOML example"\nowner.name = "Bob"\n';
const updated = patch(existing, {
  title: 'TOML example',
  owner: { name: 'Tim' }
});

Patch-lite

patch-lite is a smaller, edit-only distribution for applications that only need to update existing TOML values, such as bumping a package version. It exposes the same patch name with a two-argument (existing, updated) signature.

It is not part of the main package: the main package ships the full API only. Install the lite build from the lite npm dist-tag, then import it with the same specifier:

npm install --save @decimalturn/toml-patch@lite
import { patch } from '@decimalturn/toml-patch';

const existing = 'version = "1.0.0"\n';
const updated = patch(existing, { version: '1.0.1' });
// updated === 'version = "1.0.1"\n'

The dist-tag tarball maps its root export to the lite build, so there is no patch-lite subpath: import { patch } from '@decimalturn/toml-patch/patch-lite' fails with ERR_PACKAGE_PATH_NOT_EXPORTED. Switching between the two is an install change, never a code change.

The lite function edits existing primitive values only and preserves all source text outside the edited value, including comments, whitespace, line endings and a leading BOM. Added or removed keys, array length changes, reordering, renames, primitive/container type changes and unsupported value types throw before any output is produced. Date/time values may be given as the custom Date subclasses or as Temporal objects; both are serialized into the existing row's shape. Use the full patch() for additions, removals, moves, renames and advanced formatting.

Unlike the full patch(), the lite distribution performs no encoding validation on its output: it does not reject strings containing unpaired UTF-16 surrogates, which cannot be represented as valid TOML/UTF-8. Use the full patch() when this validation is required.

The Patch-lite guide lists every supported and rejected operation with its error code, the value-encoding rules that differ from the full patch(), and the measured size and throughput, so you can check whether the lite distribution covers your use case.

Comment Ownership

When patch() removes or reorders an entry, any comment describing it (a same-line trailing comment, or a line-comment directly above with no blank line in between) travels along with it, instead of being left behind to describe whatever ends up in that spot. This applies to root keys, [table]/[[array-of-tables]] blocks, and elements inside multi-line arrays and inline tables.

import * as TOML from '@decimalturn/toml-patch';
import { strict as assert } from 'assert';

const existing = `
x = 1 # a note about x
y = 2
`;

const patched = TOML.patch(existing, { y: 2 });

assert.strictEqual(patched, `
y = 2
`);

See the comment ownership guide for the full behavior, including how a blank line opts a comment out of ownership and current scope limitations.

Note that patch() does not reorder entries by default. To have it match the key order of the object you pass in, enable updateOrder in the formatting options.

Date/Time Handling & Temporal

TOML date/time values are parsed into custom Date subclasses (LocalDate, LocalTime, LocalDateTime, OffsetDateTime) by default. Set temporal: true to receive Temporal objects instead. stringify() and patch() auto-detect Temporal objects and serialize them correctly. Fractional seconds keep the source precision, sub-millisecond digits included.

Enabling Temporal

The temporal: true option requires Temporal to be available in the runtime:

RuntimeHow to enable
Node.js 26+Built-in (no config needed)
Node.js 20–24node --harmony-temporal flag
Node.js 14–26@js-temporal/polyfill
import * as TOML from '@decimalturn/toml-patch';

// Node 26+ (native) or Node 20–24 with --harmony-temporal:
const obj = TOML.parse('d = 2024-01-15\n', { temporal: true });
// obj.d → Temporal.PlainDate

// All Node versions with the polyfill:
import { Temporal } from '@js-temporal/polyfill';
globalThis.Temporal = Temporal;
const obj2 = TOML.parse('d = 2024-01-15\n', { temporal: true });
// obj2.d → PlainDate (polyfill)

Note: Only offset-based timezones (+05:30, Z) are supported in TOML. IANA timezone annotations (e.g., [Asia/Kolkata]) will throw an error.

See the date/time guide for details and examples.

Formatting

The TomlFormat class controls how TOML documents are formatted during stringification and patching operations.

class TomlFormat {
  newLine: string
  trailingNewline: number
  trailingComma: boolean
  bracketSpacing: boolean
  inlineTableStart?: number
  truncateZeroTimeInDates: boolean
  useTabsForIndentation?: boolean
  indentWidth: number
  minimumDecimals?: number
  minimumTimeDecimals?: number
  leadingBom: boolean
  updateOrder?: boolean
  multilineTable: boolean | number | 'auto' | 'parent'
  multilineArray: boolean | number | 'auto' | 'parent'

  static default(): TomlFormat
  static autoDetectFormat(tomlString: string): TomlFormat
}

Start with TomlFormat.default() and override the options you need. e.g.:

import { stringify, TomlFormat } from '@decimalturn/toml-patch';

const format = TomlFormat.default();
format.newLine = '\r\n';
format.trailingNewline = 0;
format.trailingComma = true;
format.bracketSpacing = false;
format.indentWidth = 4;
format.multilineTable = 'parent';

const toml = stringify({
  title: 'My App',
  tags: ['dev', 'config'],
  database: { host: 'localhost', port: 5432 }
}, format);

See the formatting reference for the complete list of options, auto-detection behavior, updateOrder and more examples.

版本与发布记录

@decimalturn/toml-patch 共发布 58 个版本,首次发布于 2025/04/12;过去 12 个月发布了 49 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.3.2latest2026/11/012 天前
3.3.2-litelite2026/11/012 天前
3.3.2-devdev2026/11/012 天前
3.3.1-lite2026/10/1816 天前
3.3.1-dev2026/10/1816 天前
3.3.12026/10/1816 天前

关于 @decimalturn/toml-patch 的常见问题

@decimalturn/toml-patch 是什么?

修补、解析和字符串化TOML,同时保留注释、空白和格式。

如何安装 @decimalturn/toml-patch?

在项目目录运行 npm install @decimalturn/toml-patch,或使用 pnpm add / yarn add / bun add。

@decimalturn/toml-patch 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@decimalturn/toml-patch 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@decimalturn/toml-patch 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=16。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@decimalturn/toml-patch 可以商用吗?

@decimalturn/toml-patch 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@decimalturn/toml-patch 还在维护吗?

最新版本 3.3.2 发布于 2026/11/01(2 天前);至今共发布 58 个版本,其中过去 12 个月发布了 49 个;首次发布于 2025/04/12。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。