diff --git a/src/_format.ts b/src/_format.ts index cca5c4a..2575142 100644 --- a/src/_format.ts +++ b/src/_format.ts @@ -100,6 +100,10 @@ export function storeFormat(text: string, obj: any, opts?: FormatOptions): void }); } +export function hasFormat(obj: any): boolean { + return !!obj && typeof obj === "object" && ftmSymbol in obj; +} + export function getFormat( obj: any, opts?: FormatOptions, @@ -107,7 +111,7 @@ export function getFormat( indent: string | number | undefined; whitespace: { start: string; end: string }; } { - if (!obj || typeof obj !== "object" || !(ftmSymbol in obj)) { + if (!hasFormat(obj)) { return { indent: opts?.indent ?? 2, whitespace: { start: "", end: "" } }; } const format = obj[ftmSymbol] as FormatInfo; diff --git a/src/toml.ts b/src/toml.ts index 823662c..fd9adf2 100644 --- a/src/toml.ts +++ b/src/toml.ts @@ -1,4 +1,4 @@ -import { getFormat, storeFormat, stripBOM } from "./_format"; +import { getFormat, hasFormat, storeFormat, stripBOM } from "./_format"; import { parse, stringify } from "smol-toml"; // Source: https://github.com/squirrelchat/smol-toml @@ -30,5 +30,5 @@ export function parseTOML(text: string): T { export function stringifyTOML(value: any): string { const format = getFormat(value, { preserveIndentation: false }); const str = stringify(value); - return format.whitespace.start + str + format.whitespace.end; + return hasFormat(value) ? format.whitespace.start + str.trimEnd() + format.whitespace.end : str; } diff --git a/test/toml-roundtrip.test.ts b/test/toml-roundtrip.test.ts new file mode 100644 index 0000000..ec0a39e --- /dev/null +++ b/test/toml-roundtrip.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from "vitest"; +import { parseTOML, stringifyTOML } from "../src"; +import { stringify as stringifyRawTOML } from "smol-toml"; + +describe("TOML whitespace roundtrip", () => { + for (const source of ['name = "sample"\n', 'name = "sample"\n\n', 'name = "sample"']) { + it(`preserves final whitespace ${JSON.stringify(source)}`, () => { + const first = stringifyTOML(parseTOML(source)); + expect(first).toBe(source); + expect(stringifyTOML(parseTOML(first))).toBe(first); + }); + } +}); + +describe("TOML values without stored formatting", () => { + for (const value of [{ name: "sample" }, { note: "first\nsecond" }, {}]) { + it(`preserves the serializer output for ${JSON.stringify(value)}`, () => { + expect(stringifyTOML(value)).toBe(stringifyRawTOML(value)); + }); + } +});